]> git.lizzy.rs Git - plan9front.git/blob - sys/src/9/pc/sdide.c
sdide: add another vid/did for 82801FB
[plan9front.git] / sys / src / 9 / pc / sdide.c
1 #include "u.h"
2 #include "../port/lib.h"
3 #include "mem.h"
4 #include "dat.h"
5 #include "fns.h"
6 #include "io.h"
7 #include "ureg.h"
8 #include "../port/error.h"
9
10 #include "../port/sd.h"
11 #include <fis.h>
12
13 #define HOWMANY(x, y)   (((x)+((y)-1))/(y))
14 #define ROUNDUP(x, y)   (HOWMANY((x), (y))*(y))
15 #define uprint(...)     snprint(up->genbuf, sizeof up->genbuf, __VA_ARGS__);
16 #pragma varargck        argpos  atadebug                3
17
18 extern SDifc sdideifc;
19
20 enum {
21         DbgCONFIG       = 0x0001,       /* detected drive config info */
22         DbgIDENTIFY     = 0x0002,       /* detected drive identify info */
23         DbgSTATE        = 0x0004,       /* dump state on panic */
24         DbgPROBE        = 0x0008,       /* trace device probing */
25         DbgDEBUG        = 0x0080,       /* the current problem... */
26         DbgINL          = 0x0100,       /* That Inil20+ message we hate */
27         Dbg48BIT        = 0x0200,       /* 48-bit LBA */
28         DbgBsy          = 0x0400,       /* interrupt but Bsy (shared IRQ) */
29         DbgAtazz        = 0x0800,       /* debug raw ata io */
30 };
31 #define DEBUG           (DbgDEBUG|DbgSTATE)
32
33 enum {                                  /* I/O ports */
34         Data            = 0,
35         Error           = 1,            /* (read) */
36         Features        = 1,            /* (write) */
37         Count           = 2,            /* sector count<7-0>, sector count<15-8> */
38         Ir              = 2,            /* interrupt reason (PACKET) */
39         Sector          = 3,            /* sector number */
40         Lbalo           = 3,            /* LBA<7-0>, LBA<31-24> */
41         Cyllo           = 4,            /* cylinder low */
42         Bytelo          = 4,            /* byte count low (PACKET) */
43         Lbamid          = 4,            /* LBA<15-8>, LBA<39-32> */
44         Cylhi           = 5,            /* cylinder high */
45         Bytehi          = 5,            /* byte count hi (PACKET) */
46         Lbahi           = 5,            /* LBA<23-16>, LBA<47-40> */
47         Dh              = 6,            /* Device/Head, LBA<27-24> */
48         Status          = 7,            /* (read) */
49         Command         = 7,            /* (write) */
50
51         As              = 2,            /* Alternate Status (read) */
52         Dc              = 2,            /* Device Control (write) */
53 };
54
55 enum {                                  /* Error */
56         Med             = 0x01,         /* Media error */
57         Ili             = 0x01,         /* command set specific (PACKET) */
58         Nm              = 0x02,         /* No Media */
59         Eom             = 0x02,         /* command set specific (PACKET) */
60         Abrt            = 0x04,         /* Aborted command */
61         Mcr             = 0x08,         /* Media Change Request */
62         Idnf            = 0x10,         /* no user-accessible address */
63         Mc              = 0x20,         /* Media Change */
64         Unc             = 0x40,         /* Uncorrectable data error */
65         Wp              = 0x40,         /* Write Protect */
66         Icrc            = 0x80,         /* Interface CRC error */
67 };
68
69 enum {                                  /* Features */
70         Dma             = 0x01,         /* data transfer via DMA (PACKET) */
71         Ovl             = 0x02,         /* command overlapped (PACKET) */
72 };
73
74 enum {                                  /* Interrupt Reason */
75         Cd              = 0x01,         /* Command/Data */
76         Io              = 0x02,         /* I/O direction */
77         Rel             = 0x04,         /* Bus Release */
78 };
79
80 enum {                                  /* Device/Head */
81         Dev0            = 0xA0,         /* Master */
82         Dev1            = 0xB0,         /* Slave */
83         Devs            = Dev0 | Dev1,
84         Lba             = 0x40,         /* LBA mode */
85 };
86
87 enum {                                  /* Status, Alternate Status */
88         Err             = 0x01,         /* Error */
89         Chk             = 0x01,         /* Check error (PACKET) */
90         Drq             = 0x08,         /* Data Request */
91         Dsc             = 0x10,         /* Device Seek Complete */
92         Serv            = 0x10,         /* Service */
93         Df              = 0x20,         /* Device Fault */
94         Dmrd            = 0x20,         /* DMA ready (PACKET) */
95         Drdy            = 0x40,         /* Device Ready */
96         Bsy             = 0x80,         /* Busy */
97 };
98
99 enum {                                  /* Command */
100         Cnop            = 0x00,         /* NOP */
101         Crs             = 0x20,         /* Read Sectors */
102         Crs48           = 0x24,         /* Read Sectors Ext */
103         Crd48           = 0x25,         /* Read w/ DMA Ext */
104         Crsm48          = 0x29,         /* Read Multiple Ext */
105         Cws             = 0x30,         /* Write Sectors */
106         Cws48           = 0x34,         /* Write Sectors Ext */
107         Cwd48           = 0x35,         /* Write w/ DMA Ext */
108         Cwsm48          = 0x39,         /* Write Multiple Ext */
109         Cedd            = 0x90,         /* Execute Device Diagnostics */
110         Cpkt            = 0xA0,         /* Packet */
111         Cidpkt          = 0xA1,         /* Identify Packet Device */
112         Crsm            = 0xC4,         /* Read Multiple */
113         Cwsm            = 0xC5,         /* Write Multiple */
114         Csm             = 0xC6,         /* Set Multiple */
115         Crd             = 0xC8,         /* Read DMA */
116         Cwd             = 0xCA,         /* Write DMA */
117         Cid             = 0xEC,         /* Identify Device */
118 };
119
120 enum {                                  /* Device Control */
121         Nien            = 0x02,         /* (not) Interrupt Enable */
122         Srst            = 0x04,         /* Software Reset */
123         Hob             = 0x80,         /* High Order Bit [sic] */
124 };
125
126 enum {                                  /* PCI Configuration Registers */
127         Bmiba           = 0x20,         /* Bus Master Interface Base Address */
128         Idetim          = 0x40,         /* IE Timing */
129         Sidetim         = 0x44,         /* Slave IE Timing */
130         Udmactl         = 0x48,         /* Ultra DMA/33 Control */
131         Udmatim         = 0x4A,         /* Ultra DMA/33 Timing */
132 };
133
134 enum {                                  /* Bus Master IDE I/O Ports */
135         Bmicx           = 0,            /* Command */
136         Bmisx           = 2,            /* Status */
137         Bmidtpx         = 4,            /* Descriptor Table Pointer */
138 };
139
140 enum {                                  /* Bmicx */
141         Ssbm            = 0x01,         /* Start/Stop Bus Master */
142         Rwcon           = 0x08,         /* Read/Write Control */
143 };
144
145 enum {                                  /* Bmisx */
146         Bmidea          = 0x01,         /* Bus Master IDE Active */
147         Idedmae         = 0x02,         /* IDE DMA Error  (R/WC) */
148         Ideints         = 0x04,         /* IDE Interrupt Status (R/WC) */
149         Dma0cap         = 0x20,         /* Drive 0 DMA Capable */
150         Dma1cap         = 0x40,         /* Drive 0 DMA Capable */
151 };
152 enum {                                  /* Physical Region Descriptor */
153         PrdEOT          = 0x80000000,   /* End of Transfer */
154 };
155
156 enum {                                  /* offsets into the identify info. */
157         Iconfig         = 0,            /* general configuration */
158         Ilcyl           = 1,            /* logical cylinders */
159         Ilhead          = 3,            /* logical heads */
160         Ilsec           = 6,            /* logical sectors per logical track */
161         Iserial         = 10,           /* serial number */
162         Ifirmware       = 23,           /* firmware revision */
163         Imodel          = 27,           /* model number */
164         Imaxrwm         = 47,           /* max. read/write multiple sectors */
165         Icapabilities   = 49,           /* capabilities */
166         Istandby        = 50,           /* device specific standby timer */
167         Ipiomode        = 51,           /* PIO data transfer mode number */
168         Ivalid          = 53,
169         Iccyl           = 54,           /* cylinders if (valid&0x01) */
170         Ichead          = 55,           /* heads if (valid&0x01) */
171         Icsec           = 56,           /* sectors if (valid&0x01) */
172         Iccap           = 57,           /* capacity if (valid&0x01) */
173         Irwm            = 59,           /* read/write multiple */
174         Ilba            = 60,           /* LBA size */
175         Imwdma          = 63,           /* multiword DMA mode */
176         Iapiomode       = 64,           /* advanced PIO modes supported */
177         Iminmwdma       = 65,           /* min. multiword DMA cycle time */
178         Irecmwdma       = 66,           /* rec. multiword DMA cycle time */
179         Iminpio         = 67,           /* min. PIO cycle w/o flow control */
180         Iminiordy       = 68,           /* min. PIO cycle with IORDY */
181         Ipcktbr         = 71,           /* time from PACKET to bus release */
182         Iserbsy         = 72,           /* time from SERVICE to !Bsy */
183         Iqdepth         = 75,           /* max. queue depth */
184         Imajor          = 80,           /* major version number */
185         Iminor          = 81,           /* minor version number */
186         Icsfs           = 82,           /* command set/feature supported */
187         Icsfe           = 85,           /* command set/feature enabled */
188         Iudma           = 88,           /* ultra DMA mode */
189         Ierase          = 89,           /* time for security erase */
190         Ieerase         = 90,           /* time for enhanced security erase */
191         Ipower          = 91,           /* current advanced power management */
192         Ilba48          = 100,          /* 48-bit LBA size (64 bits in 100-103) */
193         Irmsn           = 127,          /* removable status notification */
194         Isecstat        = 128,          /* security status */
195         Icfapwr         = 160,          /* CFA power mode */
196         Imediaserial    = 176,          /* current media serial number */
197         Icksum          = 255,          /* checksum */
198 };
199
200 enum {                                  /* bit masks for config identify info */
201         Mpktsz          = 0x0003,       /* packet command size */
202         Mincomplete     = 0x0004,       /* incomplete information */
203         Mdrq            = 0x0060,       /* DRQ type */
204         Mrmdev          = 0x0080,       /* device is removable */
205         Mtype           = 0x1F00,       /* device type */
206         Mproto          = 0x8000,       /* command protocol */
207 };
208
209 enum {                                  /* bit masks for capabilities identify info */
210         Mdma            = 0x0100,       /* DMA supported */
211         Mlba            = 0x0200,       /* LBA supported */
212         Mnoiordy        = 0x0400,       /* IORDY may be disabled */
213         Miordy          = 0x0800,       /* IORDY supported */
214         Msoftrst        = 0x1000,       /* needs soft reset when Bsy */
215         Mqueueing       = 0x4000,       /* queueing overlap supported */
216         Midma           = 0x8000,       /* interleaved DMA supported */
217 };
218
219 enum {                                  /* bit masks for supported/enabled features */
220         Msmart          = 0x0001,
221         Msecurity       = 0x0002,
222         Mrmmedia        = 0x0004,
223         Mpwrmgmt        = 0x0008,
224         Mpkt            = 0x0010,
225         Mwcache         = 0x0020,
226         Mlookahead      = 0x0040,
227         Mrelirq         = 0x0080,
228         Msvcirq         = 0x0100,
229         Mreset          = 0x0200,
230         Mprotected      = 0x0400,
231         Mwbuf           = 0x1000,
232         Mrbuf           = 0x2000,
233         Mnop            = 0x4000,
234         Mmicrocode      = 0x0001,
235         Mqueued         = 0x0002,
236         Mcfa            = 0x0004,
237         Mapm            = 0x0008,
238         Mnotify         = 0x0010,
239         Mspinup         = 0x0040,
240         Mmaxsec         = 0x0100,
241         Mautoacoustic   = 0x0200,
242         Maddr48         = 0x0400,
243         Mdevconfov      = 0x0800,
244         Mflush          = 0x1000,
245         Mflush48        = 0x2000,
246         Msmarterror     = 0x0001,
247         Msmartselftest  = 0x0002,
248         Mmserial        = 0x0004,
249         Mmpassthru      = 0x0008,
250         Mlogging        = 0x0020,
251 };
252
253 typedef struct Ctlr Ctlr;
254 typedef struct Drive Drive;
255
256 typedef struct Prd {                    /* Physical Region Descriptor */
257         ulong   pa;                     /* Physical Base Address */
258         int     count;
259 } Prd;
260
261 enum {
262         BMspan          = 32*1024,      /* must be power of 2 <= 64*1024 */
263
264         Nprd            = SDmaxio/BMspan+2,
265 };
266
267 typedef struct Ctlr {
268         int     cmdport;
269         int     ctlport;
270         int     irq;
271         int     tbdf;
272         int     bmiba;                  /* bus master interface base address */
273         int     maxio;                  /* sector count transfer maximum */
274         int     span;                   /* don't span this boundary with dma */
275         int     maxdma;                 /* don't attempt dma transfers bigger than this */
276
277         Pcidev* pcidev;
278         void    (*ienable)(Ctlr*);
279         void    (*idisable)(Ctlr*);
280         SDev*   sdev;
281
282         Drive*  drive[2];
283
284         Prd*    prdt;                   /* physical region descriptor table */
285         void    (*irqack)(Ctlr*);
286
287         QLock;                          /* current command */
288         Drive*  curdrive;
289         int     command;                /* last command issued (debugging) */
290         Rendez;
291         int     done;
292         uint    nrq;
293         uint    nildrive;
294         uint    bsy;
295
296         Lock;                           /* register access */
297 } Ctlr;
298
299 typedef struct Drive {
300         Ctlr*   ctlr;
301         SDunit  *unit;
302
303         int     dev;
304         ushort  info[256];
305         Sfis;
306
307         int     dma;                    /* DMA R/W possible */
308         int     dmactl;
309         int     rwm;                    /* read/write multiple possible */
310         int     rwmctl;
311
312         int     pkt;                    /* PACKET device, length of pktcmd */
313         uchar   pktcmd[16];
314         int     pktdma;                 /* this PACKET command using dma */
315
316         uvlong  sectors;
317         uint    secsize;
318         char    serial[20+1];
319         char    firmware[8+1];
320         char    model[40+1];
321
322         QLock;                          /* drive access */
323         int     command;                /* current command */
324         int     write;
325         uchar*  data;
326         int     dlen;
327         uchar*  limit;
328         int     count;                  /* sectors */
329         int     block;                  /* R/W bytes per block */
330         int     status;
331         int     error;
332         int     flags;                  /* internal flags */
333         uint    missirq;
334         uint    spurloop;
335         uint    irq;
336         uint    bsy;
337 } Drive;
338
339 enum {                                  /* internal flags */
340         Lba48always     = 0x2,          /* ... */
341         Online          = 0x4,          /* drive onlined */
342 };
343
344 static void
345 pc87415ienable(Ctlr* ctlr)
346 {
347         Pcidev *p;
348         int x;
349
350         p = ctlr->pcidev;
351         if(p == nil)
352                 return;
353
354         x = pcicfgr32(p, 0x40);
355         if(ctlr->cmdport == p->mem[0].bar)
356                 x &= ~0x00000100;
357         else
358                 x &= ~0x00000200;
359         pcicfgw32(p, 0x40, x);
360 }
361
362 static void
363 atadumpstate(Drive* drive, SDreq *r, uvlong lba, int count)
364 {
365         Prd *prd;
366         Pcidev *p;
367         Ctlr *ctlr;
368         int i, bmiba, ccnt;
369         uvlong clba;
370
371         if(!(DEBUG & DbgSTATE))
372                 return;
373
374         ctlr = drive->ctlr;
375         print("command %2.2uX\n", ctlr->command);
376         print("data %8.8p limit %8.8p dlen %d status %uX error %uX\n",
377                 drive->data, drive->limit, drive->dlen,
378                 drive->status, drive->error);
379         if(r->clen == -16)
380                 clba = fisrw(nil, r->cmd, &ccnt);
381         else 
382                 sdfakescsirw(r, &clba, &ccnt, 0);
383         print("lba %llud -> %llud, count %d -> %d (%d)\n",
384                 clba, lba, ccnt, count, drive->count);
385         if(!(inb(ctlr->ctlport+As) & Bsy)){
386                 for(i = 1; i < 7; i++)
387                         print(" 0x%2.2uX", inb(ctlr->cmdport+i));
388                 print(" 0x%2.2uX\n", inb(ctlr->ctlport+As));
389         }
390         if(drive->command == Cwd || drive->command == Crd
391         || drive->command == (Pdma|Pin) || drive->command == (Pdma|Pout)){
392                 bmiba = ctlr->bmiba;
393                 prd = ctlr->prdt;
394                 print("bmicx %2.2uX bmisx %2.2uX prdt %8.8p\n",
395                         inb(bmiba+Bmicx), inb(bmiba+Bmisx), prd);
396                 while(prd){
397                         print("pa 0x%8.8luX count %8.8uX\n",
398                                 prd->pa, prd->count);
399                         if(prd->count & PrdEOT)
400                                 break;
401                         prd++;
402                 }
403         }
404         if(ctlr->pcidev && ctlr->pcidev->vid == 0x8086){
405                 p = ctlr->pcidev;
406                 print("0x40: %4.4uX 0x42: %4.4uX ",
407                         pcicfgr16(p, 0x40), pcicfgr16(p, 0x42));
408                 print("0x48: %2.2uX\n", pcicfgr8(p, 0x48));
409                 print("0x4A: %4.4uX\n", pcicfgr16(p, 0x4A));
410         }
411 }
412
413 static void
414 atadebug(int cmdport, int ctlport, char* fmt, ...)
415 {
416         char *p, *e, buf[PRINTSIZE];
417         int i;
418         va_list arg;
419
420         if(!(DEBUG & DbgPROBE))
421                 return;
422
423         p = buf;
424         e = buf + sizeof buf;
425         va_start(arg, fmt);
426         p = vseprint(p, e, fmt, arg);
427         va_end(arg);
428
429         if(cmdport){
430                 if(p > buf && p[-1] == '\n')
431                         p--;
432                 p = seprint(p, e, " ataregs 0x%uX:", cmdport);
433                 for(i = Features; i < Command; i++)
434                         p = seprint(p, e, " 0x%2.2uX", inb(cmdport+i));
435                 if(ctlport)
436                         p = seprint(p, e, " 0x%2.2uX", inb(ctlport+As));
437                 p = seprint(p, e, "\n");
438         }
439         putstrn(buf, p - buf);
440 }
441
442 static int
443 ataready(int cmdport, int ctlport, int dev, int reset, int ready, int m)
444 {
445         int as, m0;
446
447         atadebug(cmdport, ctlport, "ataready: dev %ux:%ux reset %ux ready %ux",
448                 cmdport, dev, reset, ready);
449         m0 = m;
450         do{
451                 /*
452                  * Wait for the controller to become not busy and
453                  * possibly for a status bit to become true (usually
454                  * Drdy). Must change to the appropriate device
455                  * register set if necessary before testing for ready.
456                  * Always run through the loop at least once so it
457                  * can be used as a test for !Bsy.
458                  */
459                 as = inb(ctlport+As);
460                 if(as & reset){
461                         /* nothing to do */
462                 }
463                 else if(dev){
464                         outb(cmdport+Dh, dev);
465                         dev = 0;
466                 }
467                 else if(ready == 0 || (as & ready)){
468                         atadebug(0, 0, "ataready: %d:%d %#.2ux\n", m, m0, as);
469                         return as;
470                 }
471                 microdelay(1);
472         }while(m-- > 0);
473         atadebug(0, 0, "ataready: timeout %d %#.2ux\n", m0, as);
474         return -1;
475 }
476
477 static int
478 atadone(void* arg)
479 {
480         return ((Ctlr*)arg)->done;
481 }
482
483 static int
484 atarwmmode(Drive* drive, int cmdport, int ctlport, int dev)
485 {
486         int as, maxrwm, rwm;
487
488         maxrwm = drive->info[Imaxrwm] & 0xFF;
489         if(maxrwm == 0)
490                 return 0;
491
492         /*
493          * Sometimes drives come up with the current count set
494          * to 0; if so, set a suitable value, otherwise believe
495          * the value in Irwm if the 0x100 bit is set.
496          */
497         if(drive->info[Irwm] & 0x100)
498                 rwm = drive->info[Irwm] & 0xFF;
499         else
500                 rwm = 0;
501         if(rwm == 0)
502                 rwm = maxrwm;
503         if(rwm > 16)
504                 rwm = 16;
505         if(ataready(cmdport, ctlport, dev, Bsy|Drq, Drdy, 102*1000) < 0)
506                 return 0;
507         outb(cmdport+Count, rwm);
508         outb(cmdport+Command, Csm);
509         microdelay(1);
510         as = ataready(cmdport, ctlport, 0, Bsy, Drdy|Df|Err, 1000);
511         inb(cmdport+Status);
512         if(as < 0 || (as & (Df|Err)))
513                 return 0;
514
515         drive->rwm = rwm;
516
517         return rwm;
518 }
519
520 static int
521 atadmamode(SDunit *unit, Drive* drive)
522 {
523         char buf[32], *s;
524         int dma;
525
526         /*
527          * Check if any DMA mode enabled.
528          * Assumes the BIOS has picked and enabled the best.
529          * This is completely passive at the moment, no attempt is
530          * made to ensure the hardware is correctly set up.
531          */
532         dma = drive->info[Imwdma] & 0x0707;
533         drive->dma = (dma>>8) & dma;
534         if(drive->dma == 0 && (drive->info[Ivalid] & 0x04)){
535                 dma = drive->info[Iudma] & 0x7F7F;
536                 drive->dma = (dma>>8) & dma;
537                 if(drive->dma)
538                         drive->dma |= 'U'<<16;
539         }
540         if(unit != nil){
541                 snprint(buf, sizeof buf, "*%sdma", unit->name);
542                 s = getconf(buf);
543                 if((s && !strcmp(s, "on")) || (!s && !getconf("*nodma")))
544                         drive->dmactl = drive->dma;
545         }
546         return dma;
547 }
548
549 static int
550 ataidentify(Ctlr*, int cmdport, int ctlport, int dev, int pkt, void* info)
551 {
552         int as, command, drdy;
553
554         if(pkt){
555                 command = Cidpkt;
556                 drdy = 0;
557         }
558         else{
559                 command = Cid;
560                 drdy = Drdy;
561         }
562         dev &= ~Lba;
563         as = ataready(cmdport, ctlport, dev, Bsy|Drq, drdy, 103*1000);
564         if(as < 0)
565                 return as;
566         outb(cmdport+Command, command);
567         microdelay(1);
568
569         as = ataready(cmdport, ctlport, 0, Bsy, Drq|Err, 400*1000);
570         if(as < 0)
571                 return -1;
572         if(as & Err)
573                 return as;
574
575         memset(info, 0, 512);
576         inss(cmdport+Data, info, 256);
577         ataready(cmdport, ctlport, dev, Bsy|Drq, Drdy, 3*1000);
578         inb(cmdport+Status);
579
580         return 0;
581 }
582
583 static Drive*
584 atadrive(SDunit *unit, Drive *drive, int cmdport, int ctlport, int dev)
585 {
586         int as, pkt;
587         uchar buf[512], oserial[21];
588         uvlong osectors;
589         Ctlr *ctlr;
590
591         if(DEBUG & DbgIDENTIFY)
592                 print("identify: port %ux dev %.2ux\n", cmdport, dev & ~Lba);
593         atadebug(0, 0, "identify: port 0x%uX dev 0x%2.2uX\n", cmdport, dev);
594         pkt = 1;
595         if(drive != nil){
596                 osectors = drive->sectors;
597                 memmove(oserial, drive->serial, sizeof drive->serial);
598                 ctlr = drive->ctlr;
599         }else{
600                 osectors = 0;
601                 memset(oserial, 0, sizeof drive->serial);
602                 ctlr = nil;
603         }
604 retry:
605         as = ataidentify(ctlr, cmdport, ctlport, dev, pkt, buf);
606         if(as < 0)
607                 return nil;
608         if(as & Err){
609                 if(pkt == 0)
610                         return nil;
611                 pkt = 0;
612                 goto retry;
613         }
614
615         if(drive == 0){
616                 if((drive = malloc(sizeof(Drive))) == nil)
617                         return nil;
618                 drive->serial[0] = ' ';
619                 drive->dev = dev;
620         }
621
622         memmove(drive->info, buf, sizeof(drive->info));
623
624         setfissig(drive, pkt? 0xeb140000: 0x0101);
625         drive->sectors = idfeat(drive, drive->info);
626         drive->secsize = idss(drive, drive->info);
627
628         idmove(drive->serial, drive->info+10, 20);
629         idmove(drive->firmware, drive->info+23, 8);
630         idmove(drive->model, drive->info+27, 40);
631         if(unit != nil){
632                 memset(unit->inquiry, 0, sizeof unit->inquiry);
633                 unit->inquiry[2] = 2;
634                 unit->inquiry[3] = 2;
635                 unit->inquiry[4] = sizeof unit->inquiry - 4;
636                 memmove(unit->inquiry+8, drive->model, 40);
637         }
638
639         if(pkt){
640                 drive->pkt = 12;
641                 if(drive->feat & Datapi16)
642                         drive->pkt = 16;
643         }else{
644                 drive->pkt = 0;
645                 if(drive->feat & Dlba)
646                         drive->dev |= Lba;
647                 atarwmmode(drive, cmdport, ctlport, dev);
648         }
649         atadmamode(unit, drive);        
650
651         if(osectors != 0 && memcmp(oserial, drive->serial, sizeof oserial) != 0)
652                 if(unit)
653                         unit->sectors = 0;
654         drive->unit = unit;
655         if(DEBUG & DbgCONFIG){
656                 print("dev %2.2uX port %uX config %4.4uX capabilities %4.4uX",
657                         dev, cmdport, drive->info[Iconfig], drive->info[Icapabilities]);
658                 print(" mwdma %4.4uX", drive->info[Imwdma]);
659                 if(drive->info[Ivalid] & 0x04)
660                         print(" udma %4.4uX", drive->info[Iudma]);
661                 print(" dma %8.8uX rwm %ud", drive->dma, drive->rwm);
662                 if(drive->feat&Dllba)
663                         print("\tLLBA sectors %llud", drive->sectors);
664                 print("\n");
665         }
666
667         return drive;
668 }
669
670 static void
671 atasrst(int ctlport)
672 {
673         int dc0;
674
675         /*
676          * Srst is a big stick and may cause problems if further
677          * commands are tried before the drives become ready again.
678          * Also, there will be problems here if overlapped commands
679          * are ever supported.
680          */
681         dc0 = inb(ctlport+Dc);
682         microdelay(5);
683         outb(ctlport+Dc, Srst|dc0);
684         microdelay(5);
685         outb(ctlport+Dc, dc0);
686         microdelay(2*1000);
687 }
688
689 static int
690 seldev(int dev, int map)
691 {
692         if((dev & Devs) == Dev0 && map&1)
693                 return dev;
694         if((dev & Devs) == Dev1 && map&2)
695                 return dev;
696         return -1;
697 }
698
699 static SDev*
700 ataprobe(int cmdport, int ctlport, int irq, int map)
701 {
702         Ctlr* ctlr;
703         SDev *sdev;
704         Drive *drive;
705         int dev, error, rhi, rlo;
706         static int nonlegacy = 'C';
707
708         if(ioalloc(cmdport, 8, 0, "atacmd") < 0) {
709                 print("ataprobe: Cannot allocate %X\n", cmdport);
710                 return nil;
711         }
712         if(ioalloc(ctlport+As, 1, 0, "atactl") < 0){
713                 print("ataprobe: Cannot allocate %X\n", ctlport + As);
714                 iofree(cmdport);
715                 return nil;
716         }
717
718         /*
719          * Try to detect a floating bus.
720          * Bsy should be cleared. If not, see if the cylinder registers
721          * are read/write capable.
722          * If the master fails, try the slave to catch slave-only
723          * configurations.
724          * There's no need to restore the tested registers as they will
725          * be reset on any detected drives by the Cedd command.
726          * All this indicates is that there is at least one drive on the
727          * controller; when the non-existent drive is selected in a
728          * single-drive configuration the registers of the existing drive
729          * are often seen, only command execution fails.
730          */
731         if((dev = seldev(Dev0, map)) == -1)
732         if((dev = seldev(Dev1, map)) == -1)
733                 goto release;
734         if(inb(ctlport+As) & Bsy){
735                 outb(cmdport+Dh, dev);
736                 microdelay(1);
737 trydev1:
738                 atadebug(cmdport, ctlport, "ataprobe bsy");
739                 outb(cmdport+Cyllo, 0xAA);
740                 outb(cmdport+Cylhi, 0x55);
741                 outb(cmdport+Sector, 0xFF);
742                 rlo = inb(cmdport+Cyllo);
743                 rhi = inb(cmdport+Cylhi);
744                 if(rlo != 0xAA && (rlo == 0xFF || rhi != 0x55)){
745                         if(dev == Dev1 || (dev = seldev(Dev1, map)) == -1){
746 release:
747                                 outb(cmdport+Dc, Nien);
748                                 inb(cmdport+Status);
749                                 /* further measures to prevent irqs? */
750                                 iofree(cmdport);
751                                 iofree(ctlport+As);
752                                 return nil;
753                         }
754                         if(ataready(cmdport, ctlport, dev, Bsy, 0, 20*1000) < 0)
755                                 goto trydev1;
756                 }
757         }
758
759         /*
760          * Disable interrupts on any detected controllers.
761          */
762         outb(ctlport+Dc, Nien);
763 tryedd1:
764         if(ataready(cmdport, ctlport, dev, Bsy|Drq, 0, 105*1000) < 0){
765                 /*
766                  * There's something there, but it didn't come up clean,
767                  * so try hitting it with a big stick. The timing here is
768                  * wrong but this is a last-ditch effort and it sometimes
769                  * gets some marginal hardware back online.
770                  */
771                 atasrst(ctlport);
772                 if(ataready(cmdport, ctlport, dev, Bsy|Drq, 0, 106*1000) < 0)
773                         goto release;
774         }
775
776         /*
777          * Can only get here if controller is not busy.
778          * If there are drives Bsy will be set within 400nS,
779          * must wait 2mS before testing Status.
780          * Wait for the command to complete (6 seconds max).
781          */
782         outb(cmdport+Command, Cedd);
783         delay(2);
784         if(ataready(cmdport, ctlport, dev, Bsy|Drq, 0, 6*1000*1000) < 0)
785                 goto release;
786
787         /*
788          * If bit 0 of the error register is set then the selected drive
789          * exists. This is enough to detect single-drive configurations.
790          * However, if the master exists there is no way short of executing
791          * a command to determine if a slave is present.
792          * It appears possible to get here testing Dev0 although it doesn't
793          * exist and the EDD won't take, so try again with Dev1.
794          */
795         error = inb(cmdport+Error);
796         atadebug(cmdport, ctlport, "ataprobe: dev %uX", dev);
797         if((error & ~0x80) != 0x01){
798                 if(dev == Dev1)
799                         goto release;
800                 if((dev = seldev(Dev1, map)) == -1)
801                         goto release;
802                 goto tryedd1;
803         }
804
805         /*
806          * At least one drive is known to exist, try to
807          * identify it. If that fails, don't bother checking
808          * any further.
809          * If the one drive found is Dev0 and the EDD command
810          * didn't indicate Dev1 doesn't exist, check for it.
811          */
812         if((drive = atadrive(0, 0, cmdport, ctlport, dev)) == nil)
813                 goto release;
814         if((ctlr = malloc(sizeof(Ctlr))) == nil){
815                 free(drive);
816                 goto release;
817         }
818         if((sdev = malloc(sizeof(SDev))) == nil){
819                 free(ctlr);
820                 free(drive);
821                 goto release;
822         }
823         drive->ctlr = ctlr;
824         if(dev == Dev0){
825                 ctlr->drive[0] = drive;
826                 if(!(error & 0x80)){
827                         /*
828                          * Always leave Dh pointing to a valid drive,
829                          * otherwise a subsequent call to ataready on
830                          * this controller may try to test a bogus Status.
831                          * Ataprobe is the only place possibly invalid
832                          * drives should be selected.
833                          */
834                         drive = atadrive(0, 0, cmdport, ctlport, Dev1);
835                         if(drive != nil){
836                                 drive->ctlr = ctlr;
837                                 ctlr->drive[1] = drive;
838                         }
839                         else{
840                                 outb(cmdport+Dh, Dev0);
841                                 microdelay(1);
842                         }
843                 }
844         }
845         else
846                 ctlr->drive[1] = drive;
847
848         ctlr->cmdport = cmdport;
849         ctlr->ctlport = ctlport;
850         ctlr->irq = irq;
851         ctlr->tbdf = BUSUNKNOWN;
852         ctlr->command = Cedd;           /* debugging */
853         
854         switch(cmdport){
855         default:
856                 sdev->idno = nonlegacy;
857                 break;
858         case 0x1F0:
859                 sdev->idno = 'C';
860                 nonlegacy = 'E';
861                 break;
862         case 0x170:
863                 sdev->idno = 'D';
864                 nonlegacy = 'E';
865                 break;
866         }
867         sdev->ifc = &sdideifc;
868         sdev->ctlr = ctlr;
869         sdev->nunit = 2;
870         ctlr->sdev = sdev;
871
872         return sdev;
873 }
874
875 static void
876 ataclear(SDev *sdev)
877 {
878         Ctlr* ctlr;
879
880         ctlr = sdev->ctlr;
881         iofree(ctlr->cmdport);
882         iofree(ctlr->ctlport + As);
883
884         if (ctlr->drive[0])
885                 free(ctlr->drive[0]);
886         if (ctlr->drive[1])
887                 free(ctlr->drive[1]);
888         if (sdev->name)
889                 free(sdev->name);
890         if (sdev->unitflg)
891                 free(sdev->unitflg);
892         if (sdev->unit)
893                 free(sdev->unit);
894         free(ctlr);
895         free(sdev);
896 }
897
898 static char *
899 atastat(SDev *sdev, char *p, char *e)
900 {
901         Ctlr *ctlr;
902
903         ctlr = sdev->ctlr;
904 //      return seprint(p, e, "%s ata port %X ctl %X irq %d %T\n", 
905 //                  sdev->name, ctlr->cmdport, ctlr->ctlport, ctlr->irq, ctlr->tbdf);
906         return seprint(p, e, "%s ata port %X ctl %X irq %d\n", 
907                     sdev->name, ctlr->cmdport, ctlr->ctlport, ctlr->irq);
908 }
909
910 static SDev*
911 ataprobew(DevConf *cf)
912 {
913         char *p;
914         ISAConf isa;
915         
916         if (cf->nports != 2)
917                 error(Ebadarg);
918
919         memset(&isa, 0, sizeof isa);
920         isa.port = cf->ports[0].port;
921         isa.irq = cf->intnum;
922         if((p=strchr(cf->type, '/')) == nil || pcmspecial(p+1, &isa) < 0)
923                 error("cannot find controller");
924
925         return ataprobe(cf->ports[0].port, cf->ports[1].port, cf->intnum, 3);
926 }
927
928 static void atainterrupt(Ureg*, void*);
929
930 static int
931 iowait(Drive *drive, int ms, int interrupt)
932 {
933         int msec, step;
934         Ctlr *ctlr;
935
936         step = 1000;
937         if(drive->missirq > 10)
938                 step = 50;
939         ctlr = drive->ctlr;
940         for(msec = 0; msec < ms; msec += step){
941                 while(waserror())
942                         if(interrupt)
943                                 return -1;
944                 tsleep(ctlr, atadone, ctlr, step);
945                 poperror();
946                 if(ctlr->done)
947                         break;
948                 atainterrupt(nil, ctlr);
949                 if(ctlr->done){
950                         if(drive->missirq++ < 3)
951                                 print("ide: caught missed irq\n");
952                         break;
953                 }else
954                         drive->spurloop++;
955         }
956         return ctlr->done;
957 }
958
959 static void
960 atanop(Drive* drive, int subcommand)
961 {
962         Ctlr* ctlr;
963         int as, cmdport, ctlport, timeo;
964
965         /*
966          * Attempt to abort a command by using NOP.
967          * In response, the drive is supposed to set Abrt
968          * in the Error register, set (Drdy|Err) in Status
969          * and clear Bsy when done. However, some drives
970          * (e.g. ATAPI Zip) just go Bsy then clear Status
971          * when done, hence the timeout loop only on Bsy
972          * and the forced setting of drive->error.
973          */
974         ctlr = drive->ctlr;
975         cmdport = ctlr->cmdport;
976         outb(cmdport+Features, subcommand);
977         outb(cmdport+Dh, drive->dev);
978         ctlr->command = Cnop;           /* debugging */
979         outb(cmdport+Command, Cnop);
980
981         microdelay(1);
982         ctlport = ctlr->ctlport;
983         for(timeo = 0; timeo < 1000; timeo++){
984                 as = inb(ctlport+As);
985                 if(!(as & Bsy))
986                         break;
987                 microdelay(1);
988         }
989         drive->error |= Abrt;
990 }
991
992 static void
993 ataabort(Drive* drive, int dolock)
994 {
995         /*
996          * If NOP is available use it otherwise
997          * must try a software reset.
998          */
999         if(dolock)
1000                 ilock(drive->ctlr);
1001         if(drive->feat & Dnop)
1002                 atanop(drive, 0);
1003         else{
1004                 atasrst(drive->ctlr->ctlport);
1005                 drive->error |= Abrt;
1006         }
1007         if(dolock)
1008                 iunlock(drive->ctlr);
1009 }
1010
1011 static int
1012 atadmasetup(Drive* drive, int len)
1013 {
1014         Prd *prd;
1015         ulong pa;
1016         Ctlr *ctlr;
1017         int bmiba, bmisx, count, i, span;
1018
1019         ctlr = drive->ctlr;
1020         pa = PCIWADDR(drive->data);
1021         if(pa & 0x03)
1022                 return -1;
1023         if(ctlr->maxdma && len > ctlr->maxdma)
1024                 return -1;
1025
1026         /*
1027          * Sometimes drives identify themselves as being DMA capable
1028          * although they are not on a busmastering controller.
1029          */
1030         prd = ctlr->prdt;
1031         if(prd == nil){
1032                 drive->dmactl = 0;
1033                 print("disabling dma: not on a busmastering controller\n");
1034                 return -1;
1035         }
1036
1037         for(i = 0; len && i < Nprd; i++){
1038                 prd->pa = pa;
1039                 span = ROUNDUP(pa, ctlr->span);
1040                 if(span == pa)
1041                         span += ctlr->span;
1042                 count = span - pa;
1043                 if(count >= len){
1044                         prd->count = PrdEOT|len;
1045                         break;
1046                 }
1047                 prd->count = count;
1048                 len -= count;
1049                 pa += count;
1050                 prd++;
1051         }
1052         if(i == Nprd)
1053                 return -1;
1054
1055         bmiba = ctlr->bmiba;
1056         outl(bmiba+Bmidtpx, PCIWADDR(ctlr->prdt));
1057         if(drive->write)
1058                 outb(bmiba+Bmicx, 0);
1059         else
1060                 outb(bmiba+Bmicx, Rwcon);
1061         bmisx = inb(bmiba+Bmisx);
1062         outb(bmiba+Bmisx, bmisx|Ideints|Idedmae);
1063
1064         return 0;
1065 }
1066
1067 static void
1068 atadmastart(Ctlr* ctlr, int write)
1069 {
1070         if(write)
1071                 outb(ctlr->bmiba+Bmicx, Ssbm);
1072         else
1073                 outb(ctlr->bmiba+Bmicx, Rwcon|Ssbm);
1074 }
1075
1076 static int
1077 atadmastop(Ctlr* ctlr)
1078 {
1079         int bmiba;
1080
1081         bmiba = ctlr->bmiba;
1082         outb(bmiba+Bmicx, inb(bmiba+Bmicx) & ~Ssbm);
1083
1084         return inb(bmiba+Bmisx);
1085 }
1086
1087 static void
1088 atadmainterrupt(Drive* drive, int count)
1089 {
1090         Ctlr* ctlr;
1091         int bmiba, bmisx;
1092
1093         ctlr = drive->ctlr;
1094         bmiba = ctlr->bmiba;
1095         bmisx = inb(bmiba+Bmisx);
1096         switch(bmisx & (Ideints|Idedmae|Bmidea)){
1097         case Bmidea:
1098                 /*
1099                  * Data transfer still in progress, nothing to do
1100                  * (this should never happen).
1101                  */
1102                 return;
1103
1104         case Ideints:
1105         case Ideints|Bmidea:
1106                 /*
1107                  * Normal termination, tidy up.
1108                  */
1109                 drive->data += count;
1110                 break;
1111
1112         default:
1113                 /*
1114                  * What's left are error conditions (memory transfer
1115                  * problem) and the device is not done but the PRD is
1116                  * exhausted. For both cases must somehow tell the
1117                  * drive to abort.
1118                  */
1119                 ataabort(drive, 0);
1120                 break;
1121         }
1122         atadmastop(ctlr);
1123         ctlr->done = 1;
1124 }
1125
1126 static void
1127 atapktinterrupt(Drive* drive)
1128 {
1129         Ctlr* ctlr;
1130         int cmdport, len;
1131
1132         ctlr = drive->ctlr;
1133         cmdport = ctlr->cmdport;
1134         switch(inb(cmdport+Ir) & (/*Rel|*/Io|Cd)){
1135         case Cd:
1136                 outss(cmdport+Data, drive->pktcmd, drive->pkt/2);
1137                 break;
1138
1139         case 0:
1140                 if(drive->pktdma)
1141                         goto Pktdma;
1142                 len = (inb(cmdport+Bytehi)<<8)|inb(cmdport+Bytelo);
1143                 if(drive->data+len > drive->limit){
1144                         atanop(drive, 0);
1145                         break;
1146                 }
1147                 outss(cmdport+Data, drive->data, len/2);
1148                 drive->data += len;
1149                 break;
1150
1151         case Io:
1152                 if(drive->pktdma)
1153                         goto Pktdma;
1154                 len = (inb(cmdport+Bytehi)<<8)|inb(cmdport+Bytelo);
1155                 if(drive->data+len > drive->limit){
1156                         atanop(drive, 0);
1157                         break;
1158                 }
1159                 inss(cmdport+Data, drive->data, len/2);
1160                 drive->data += len;
1161                 break;
1162
1163         case Io|Cd:
1164                 if(drive->pktdma){
1165         Pktdma:
1166                         atadmainterrupt(drive, drive->dlen);
1167                 } else
1168                         ctlr->done = 1;
1169                 break;
1170         }
1171 }
1172
1173 static int
1174 atapktio0(Drive *drive, SDreq *r)
1175 {
1176         uchar *cmd;
1177         int as, cmdport, ctlport, len, rv;
1178         Ctlr *ctlr;
1179
1180         rv = SDok;
1181         cmd = r->cmd;
1182         drive->command = Cpkt;
1183         memmove(drive->pktcmd, cmd, r->clen);
1184         memset(drive->pktcmd+r->clen, 0, drive->pkt-r->clen);
1185         drive->limit = drive->data+drive->dlen;
1186
1187         ctlr = drive->ctlr;
1188         cmdport = ctlr->cmdport;
1189         ctlport = ctlr->ctlport;
1190
1191         as = ataready(cmdport, ctlport, drive->dev, Bsy|Drq, 0, 107*1000);
1192         /* used to test as&Chk as failure too, but some CD readers use that for media change */
1193         if(as < 0)
1194                 return SDnostatus;
1195
1196         ilock(ctlr);
1197         if(drive->dlen && drive->dmactl && !atadmasetup(drive, drive->dlen)){
1198                 drive->pktdma = Dma;
1199                 len = 0;                /* bytecount should be 0 for dma */
1200         }else{
1201                 drive->pktdma = 0;
1202                 if(drive->secsize)
1203                         len = 16*drive->secsize;
1204                 else
1205                         len = 0x8000;
1206         }
1207         outb(cmdport+Features, drive->pktdma);
1208         outb(cmdport+Count, 0);
1209         outb(cmdport+Sector, 0);
1210         outb(cmdport+Bytelo, len);
1211         outb(cmdport+Bytehi, len>>8);
1212         outb(cmdport+Dh, drive->dev);
1213         ctlr->done = 0;
1214         ctlr->curdrive = drive;
1215         ctlr->command = Cpkt;           /* debugging */
1216         outb(cmdport+Command, Cpkt);
1217
1218         microdelay(1);
1219         as = ataready(cmdport, ctlport, 0, Bsy, Drq|Chk, 4*1000);
1220         if(as < 0 || (as & (Bsy|Chk))){
1221                 drive->status = as<0 ? 0 : as;
1222                 ctlr->curdrive = nil;
1223                 ctlr->done = 1;
1224                 rv = SDtimeout;
1225         }else
1226                 atapktinterrupt(drive);
1227         if(drive->pktdma)
1228                 atadmastart(ctlr, drive->write);
1229         iunlock(ctlr);
1230
1231         if(iowait(drive, 30*1000, 0) <= 0){
1232                 ilock(ctlr);
1233                 ataabort(drive, 0);
1234         } else
1235                 ilock(ctlr);
1236         if(drive->error){
1237                 if(drive->pktdma)
1238                         atadmastop(ctlr);
1239                 drive->status |= Chk;
1240                 ctlr->curdrive = nil;
1241         }
1242         iunlock(ctlr);
1243
1244         if(drive->status & Chk){
1245                 rv = SDcheck;
1246                 if(drive->pktdma){
1247                         print("atapktio: disabling dma\n");
1248                         drive->dmactl = 0;
1249                         rv = SDretry;
1250                 }
1251         }
1252         return rv;
1253 }
1254
1255 static int
1256 atapktio(Drive* drive, SDreq *r)
1257 {
1258         int n;
1259         Ctlr *ctlr;
1260
1261         ctlr = drive->ctlr;
1262         qlock(ctlr);
1263         n = atapktio0(drive, r);
1264         qunlock(ctlr);
1265         return n;
1266 }
1267
1268 static uchar cmd48[256] = {
1269         [Crs]   Crs48,
1270         [Crd]   Crd48,
1271         [Crsm]  Crsm48,
1272         [Cws]   Cws48,
1273         [Cwd]   Cwd48,
1274         [Cwsm]  Cwsm48,
1275 };
1276
1277 enum{
1278         Last28  = (1<<28) - 1 - 1,
1279 };
1280
1281 static int
1282 atageniostart(Drive* drive, uvlong lba)
1283 {
1284         Ctlr *ctlr;
1285         uchar cmd;
1286         int as, c, cmdport, ctlport, h, len, s, use48;
1287
1288         use48 = 0;
1289         if((drive->flags&Lba48always) || lba > Last28 || drive->count > 256){
1290                 if((drive->feat & Dllba) == 0)
1291                         return -1;
1292                 use48 = 1;
1293                 c = h = s = 0;
1294         }else if(drive->dev & Lba){
1295                 c = (lba>>8) & 0xFFFF;
1296                 h = (lba>>24) & 0x0F;
1297                 s = lba & 0xFF;
1298         }else{
1299                 if (drive->s == 0 || drive->h == 0){
1300                         print("sdide: chs address botch");
1301                         return -1;
1302                 }
1303                 c = lba/(drive->s*drive->h);
1304                 h = (lba/drive->s) % drive->h;
1305                 s = (lba % drive->s) + 1;
1306         }
1307
1308         ctlr = drive->ctlr;
1309         cmdport = ctlr->cmdport;
1310         ctlport = ctlr->ctlport;
1311         if(ataready(cmdport, ctlport, drive->dev, Bsy|Drq, Drdy, 101*1000) < 0)
1312                 return -1;
1313
1314         ilock(ctlr);
1315         if(drive->dmactl && !atadmasetup(drive, drive->count*drive->secsize)){
1316                 if(drive->write)
1317                         drive->command = Cwd;
1318                 else
1319                         drive->command = Crd;
1320         }
1321         else if(drive->rwmctl){
1322                 drive->block = drive->rwm*drive->secsize;
1323                 if(drive->write)
1324                         drive->command = Cwsm;
1325                 else
1326                         drive->command = Crsm;
1327         }
1328         else{
1329                 drive->block = drive->secsize;
1330                 if(drive->write)
1331                         drive->command = Cws;
1332                 else
1333                         drive->command = Crs;
1334         }
1335         drive->limit = drive->data + drive->count*drive->secsize;
1336         cmd = drive->command;
1337         if(use48){
1338                 outb(cmdport+Count, drive->count>>8);
1339                 outb(cmdport+Count, drive->count);
1340                 outb(cmdport+Lbalo, lba>>24);
1341                 outb(cmdport+Lbalo, lba);
1342                 outb(cmdport+Lbamid, lba>>32);
1343                 outb(cmdport+Lbamid, lba>>8);
1344                 outb(cmdport+Lbahi, lba>>40);
1345                 outb(cmdport+Lbahi, lba>>16);
1346                 outb(cmdport+Dh, drive->dev|Lba);
1347                 cmd = cmd48[cmd];
1348
1349                 if(DEBUG & Dbg48BIT)
1350                         print("using 48-bit commands\n");
1351         }else{
1352                 outb(cmdport+Count, drive->count);
1353                 outb(cmdport+Sector, s);
1354                 outb(cmdport+Cyllo, c);
1355                 outb(cmdport+Cylhi, c>>8);
1356                 outb(cmdport+Dh, drive->dev|h);
1357         }
1358         ctlr->done = 0;
1359         ctlr->curdrive = drive;
1360         ctlr->command = drive->command; /* debugging */
1361         outb(cmdport+Command, cmd);
1362
1363         switch(drive->command){
1364         case Cws:
1365         case Cwsm:
1366                 microdelay(1);
1367                 /* 10*1000 for flash ide drives - maybe detect them? */
1368                 as = ataready(cmdport, ctlport, 0, Bsy, Drq|Err, 10*1000);
1369                 if(as < 0 || (as & Err)){
1370                         iunlock(ctlr);
1371                         return -1;
1372                 }
1373                 len = drive->block;
1374                 if(drive->data+len > drive->limit)
1375                         len = drive->limit-drive->data;
1376                 outss(cmdport+Data, drive->data, len/2);
1377                 break;
1378
1379         case Crd:
1380         case Cwd:
1381                 atadmastart(ctlr, drive->write);
1382                 break;
1383         }
1384         iunlock(ctlr);
1385
1386         return 0;
1387 }
1388
1389 static int
1390 atagenioretry(Drive* drive, SDreq *r, uvlong lba, int count)
1391 {
1392         char *s;
1393         int rv, count0, rw;
1394         uvlong lba0;
1395
1396         if(drive->dmactl){
1397                 drive->dmactl = 0;
1398                 s = "disabling dma";
1399                 rv = SDretry;
1400         }else if(drive->rwmctl){
1401                 drive->rwmctl = 0;
1402                 s = "disabling rwm";
1403                 rv = SDretry;
1404         }else{
1405                 s = "nondma";
1406                 rv = sdsetsense(r, SDcheck, 4, 8, drive->error);
1407         }
1408         sdfakescsirw(r, &lba0, &count0, &rw);
1409         print("atagenioretry: %s %c:%llud:%d @%llud:%d\n",
1410                 s, "rw"[rw], lba0, count0, lba, count);
1411         return rv;
1412 }
1413
1414 static int
1415 atagenio(Drive* drive, SDreq *r)
1416 {
1417         Ctlr *ctlr;
1418         uvlong lba;
1419         int i, rw, count, maxio;
1420
1421         if((i = sdfakescsi(r)) != SDnostatus)
1422                 return i;
1423         if((i = sdfakescsirw(r, &lba, &count, &rw)) != SDnostatus)
1424                 return i;
1425         ctlr = drive->ctlr;
1426         if(drive->data == nil)
1427                 return SDok;
1428         if(drive->dlen < count*drive->secsize)
1429                 count = drive->dlen/drive->secsize;
1430         qlock(ctlr);
1431         if(ctlr->maxio)
1432                 maxio = ctlr->maxio;
1433         else if(drive->feat & Dllba)
1434                 maxio = 65536;
1435         else
1436                 maxio = 256;
1437         while(count){
1438                 if(count > maxio)
1439                         drive->count = maxio;
1440                 else
1441                         drive->count = count;
1442                 if(atageniostart(drive, lba)){
1443                         ilock(ctlr);
1444                         atanop(drive, 0);
1445                         iunlock(ctlr);
1446                         qunlock(ctlr);
1447                         return atagenioretry(drive, r, lba, count);
1448                 }
1449                 iowait(drive, 30*1000, 0);
1450                 if(!ctlr->done){
1451                         /*
1452                          * What should the above timeout be? In
1453                          * standby and sleep modes it could take as
1454                          * long as 30 seconds for a drive to respond.
1455                          * Very hard to get out of this cleanly.
1456                          */
1457                         atadumpstate(drive, r, lba, count);
1458                         ataabort(drive, 1);
1459                         qunlock(ctlr);
1460                         return atagenioretry(drive, r, lba, count);
1461                 }
1462
1463                 if(drive->status & Err){
1464                         qunlock(ctlr);
1465                         print("atagenio: %llud:%d\n", lba, drive->count);
1466                         return sdsetsense(r, SDcheck, 4, 8, drive->error);
1467                 }
1468                 count -= drive->count;
1469                 lba += drive->count;
1470         }
1471         qunlock(ctlr);
1472
1473         return SDok;
1474 }
1475
1476 static int
1477 atario(SDreq* r)
1478 {
1479         uchar *p;
1480         int status;
1481         Ctlr *ctlr;
1482         Drive *drive;
1483         SDunit *unit;
1484
1485         unit = r->unit;
1486         if((ctlr = unit->dev->ctlr) == nil || ctlr->drive[unit->subno] == nil){
1487                 r->status = SDtimeout;
1488                 return SDtimeout;
1489         }
1490         drive = ctlr->drive[unit->subno];
1491         qlock(drive);
1492         for(;;){
1493                 drive->write = r->write;
1494                 drive->data = r->data;
1495                 drive->dlen = r->dlen;
1496                 drive->status = 0;
1497                 drive->error = 0;
1498                 if(drive->pkt)
1499                         status = atapktio(drive, r);
1500                 else
1501                         status = atagenio(drive, r);
1502                 if(status != SDretry)
1503                         break;
1504                 if(DbgDEBUG)
1505                         print("%s: retry: dma %8.8uX rwm %4.4uX\n",
1506                                 unit->name, drive->dmactl, drive->rwmctl);
1507         }
1508         if(status == SDok && r->rlen == 0 && (r->flags & SDvalidsense) == 0){
1509                 sdsetsense(r, SDok, 0, 0, 0);
1510                 if(drive->data){
1511                         p = r->data;
1512                         r->rlen = drive->data - p;
1513                 }
1514                 else
1515                         r->rlen = 0;
1516         }
1517         qunlock(drive);
1518         return status;
1519 }
1520
1521 /**/
1522 static int
1523 isdmacmd(Drive *d, SDreq *r)
1524 {
1525         switch(r->ataproto & Pprotom){
1526         default:
1527                 return 0;
1528         case Pdmq:
1529                 error("no queued support");
1530         case Pdma:
1531                 if(!(d->dmactl || d->rwmctl))
1532                         error("dma in non dma mode\n");
1533                 return 1;
1534         }
1535 }
1536
1537 static int
1538 atagenatastart(Drive* d, SDreq *r)
1539 {
1540         uchar u;
1541         int as, cmdport, ctlport, len, pr, isdma;
1542         Ctlr *ctlr;
1543
1544         isdma = isdmacmd(d, r);
1545         ctlr = d->ctlr;
1546         cmdport = ctlr->cmdport;
1547         ctlport = ctlr->ctlport;
1548         if(ataready(cmdport, ctlport, d->dev, Bsy|Drq, d->pkt ? 0 : Drdy, 101*1000) < 0)
1549                 return -1;
1550
1551         ilock(ctlr);
1552         if(isdma && atadmasetup(d, d->block)){
1553                 iunlock(ctlr);
1554                 return -1;
1555         
1556         }
1557         if(d->feat & Dllba && (r->ataproto & P28) == 0){
1558                 outb(cmdport+Features, r->cmd[Ffeat8]);
1559                 outb(cmdport+Features, r->cmd[Ffeat]);
1560                 outb(cmdport+Count, r->cmd[Fsc8]);
1561                 outb(cmdport+Count, r->cmd[Fsc]);
1562                 outb(cmdport+Lbalo, r->cmd[Flba24]);
1563                 outb(cmdport+Lbalo, r->cmd[Flba0]);
1564                 outb(cmdport+Lbamid, r->cmd[Flba32]);
1565                 outb(cmdport+Lbamid, r->cmd[Flba8]);
1566                 outb(cmdport+Lbahi, r->cmd[Flba40]);
1567                 outb(cmdport+Lbahi, r->cmd[Flba16]);
1568                 u = r->cmd[Fdev] & ~0xb0;
1569                 outb(cmdport+Dh, d->dev|u);
1570         }else{
1571                 outb(cmdport+Features, r->cmd[Ffeat]);
1572                 outb(cmdport+Count, r->cmd[Fsc]);
1573                 outb(cmdport+Lbalo, r->cmd[Flba0]);
1574                 outb(cmdport+Lbamid, r->cmd[Flba8]);
1575                 outb(cmdport+Lbahi, r->cmd[Flba16]);
1576                 u = r->cmd[Fdev] & ~0xb0;
1577                 outb(cmdport+Dh, d->dev|u);
1578         }
1579         ctlr->done = 0;
1580         ctlr->curdrive = d;
1581         d->command = r->ataproto & (Pprotom|Pdatam);
1582         ctlr->command = r->cmd[Fcmd];
1583         outb(cmdport+Command, r->cmd[Fcmd]);
1584
1585         pr = r->ataproto & Pprotom;
1586         if(pr == Pnd || pr == Preset)
1587                 USED(d);
1588         else if(!isdma){
1589                 microdelay(1);
1590                 /* 10*1000 for flash ide drives - maybe detect them? */
1591                 as = ataready(cmdport, ctlport, 0, Bsy, Drq|Err, 10*1000);
1592                 if(as < 0 || (as & Err)){
1593                         iunlock(ctlr);
1594                         return -1;
1595                 }
1596                 len = d->block;
1597                 if(r->write && len > 0)
1598                         outss(cmdport+Data, d->data, len/2);
1599         }else
1600                 atadmastart(ctlr, d->write);
1601         iunlock(ctlr);
1602         return 0;
1603 }
1604
1605 static void
1606 mkrfis(Drive *d, SDreq *r)
1607 {
1608         uchar *u;
1609         int cmdport;
1610         Ctlr *ctlr;
1611
1612         ctlr = d->ctlr;
1613         cmdport = ctlr->cmdport;
1614         u = r->cmd;
1615
1616         ilock(ctlr);
1617         u[Ftype] = 0x34;
1618         u[Fioport] = 0;
1619         if((d->feat & Dllba) && (r->ataproto & P28) == 0){
1620                 u[Frerror] = inb(cmdport+Error);
1621                 u[Fsc8] = inb(cmdport+Count);
1622                 u[Fsc] = inb(cmdport+Count);
1623                 u[Flba24] = inb(cmdport+Lbalo);
1624                 u[Flba0] = inb(cmdport+Lbalo);
1625                 u[Flba32] = inb(cmdport+Lbamid);
1626                 u[Flba8] = inb(cmdport+Lbamid);
1627                 u[Flba40] = inb(cmdport+Lbahi);
1628                 u[Flba16] = inb(cmdport+Lbahi);
1629                 u[Fdev] = inb(cmdport+Dh);
1630                 u[Fstatus] = inb(cmdport+Status);
1631         }else{
1632                 u[Frerror] = inb(cmdport+Error);
1633                 u[Fsc] = inb(cmdport+Count);
1634                 u[Flba0] = inb(cmdport+Lbalo);
1635                 u[Flba8] = inb(cmdport+Lbamid);
1636                 u[Flba16] = inb(cmdport+Lbahi);
1637                 u[Fdev] = inb(cmdport+Dh);
1638                 u[Fstatus] = inb(cmdport+Status);
1639         }
1640         iunlock(ctlr);
1641 }
1642
1643 static int
1644 atarstdone(Drive *d)
1645 {
1646         int as;
1647         Ctlr *c;
1648
1649         c = d->ctlr;
1650         as = ataready(c->cmdport, c->ctlport, 0, Bsy|Drq, 0, 5*1000);
1651         c->done = as >= 0;
1652         return c->done;
1653 }
1654
1655 static uint
1656 cmdss(Drive *d, SDreq *r)
1657 {
1658         switch(r->cmd[Fcmd]){
1659         case Cid:
1660         case Cidpkt:
1661                 return 512;
1662         default:
1663                 return d->secsize;
1664         }
1665 }
1666
1667 /*
1668  * various checks.  we should be craftier and
1669  * avoid figuring out how big stuff is supposed to be.
1670  */
1671 static uint
1672 patasizeck(Drive *d, SDreq *r)
1673 {
1674         uint count, maxio, secsize;
1675         Ctlr *ctlr;
1676
1677         secsize = cmdss(d, r);          /* BOTCH */
1678         if(secsize == 0)
1679                 error(Eio);
1680         count = r->dlen / secsize;
1681         ctlr = d->ctlr;
1682         if(ctlr->maxio)
1683                 maxio = ctlr->maxio;
1684         else if((d->feat & Dllba) && (r->ataproto & P28) == 0)
1685                 maxio = 65536;
1686         else
1687                 maxio = 256;
1688         if(count > maxio){
1689                 uprint("i/o too large, lim %d", maxio);
1690                 error(up->genbuf);
1691         }
1692         if(r->ataproto&Ppio && count > 1)
1693                 error("invalid # of sectors");
1694         return count;
1695 }
1696
1697 static int
1698 atapataio(Drive *d, SDreq *r)
1699 {
1700         int rv;
1701         Ctlr *ctlr;
1702
1703         d->count = 0;
1704         if(r->ataproto & Pdatam)
1705                 d->count = patasizeck(d, r);
1706         d->block = r->dlen;
1707         d->limit = d->data + r->dlen;
1708
1709         ctlr = d->ctlr;
1710         qlock(ctlr);
1711         if(waserror()){
1712                 qunlock(ctlr);
1713                 nexterror();
1714         }
1715         rv = atagenatastart(d, r);
1716         poperror();
1717         if(rv){
1718                 if(DEBUG & DbgAtazz)
1719                         print("sdide: !atageatastart\n");
1720                 ilock(ctlr);
1721                 atanop(d, 0);
1722                 iunlock(ctlr);
1723                 qunlock(ctlr);
1724                 return sdsetsense(r, SDcheck, 4, 8, d->error);
1725         }
1726
1727         if((r->ataproto & Pprotom) == Preset)
1728                 atarstdone(d);
1729         else
1730                 while(iowait(d, 30*1000, 1) == 0)
1731                         ;
1732         if(!ctlr->done){
1733                 if(DEBUG & DbgAtazz){
1734                         print("sdide: !done\n");
1735                         atadumpstate(d, r, 0, d->count);
1736                 }
1737                 ataabort(d, 1);
1738                 qunlock(ctlr);
1739                 return sdsetsense(r, SDcheck, 11, 0, 6);        /* aborted; i/o process terminated */
1740         }
1741         mkrfis(d, r);
1742         if(d->status & Err){
1743                 if(DEBUG & DbgAtazz)
1744                         print("sdide: status&Err\n");
1745                 qunlock(ctlr);
1746                 return sdsetsense(r, SDcheck, 4, 8, d->error);
1747         }
1748         qunlock(ctlr);
1749         return SDok;
1750 }
1751
1752 static int
1753 ataataio0(Drive *d, SDreq *r)
1754 {
1755         int i;
1756
1757         if((r->ataproto & Pprotom) == Ppkt){
1758                 if(r->clen > d->pkt)
1759                         error(Eio);
1760                 qlock(d->ctlr);
1761                 i = atapktio0(d, r);
1762                 d->block = d->data - (uchar*)r->data;
1763                 mkrfis(d, r);
1764                 qunlock(d->ctlr);
1765                 return i;
1766         }else
1767                 return atapataio(d, r);
1768 }
1769
1770 /*
1771  * hack to allow udma mode to be set or unset
1772  * via direct ata command.  it would be better
1773  * to move the assumptions about dma mode out
1774  * of some of the helper functions.
1775  */
1776 static int
1777 isudm(SDreq *r)
1778 {
1779         uchar *c;
1780
1781         c = r->cmd;
1782         if(c[Fcmd] == 0xef && c[Ffeat] == 0x03){
1783                 if(c[Fsc]&0x40)
1784                         return 1;
1785                 return -1;
1786         }
1787         return 0;
1788 }
1789
1790 static int
1791 fisreqchk(Sfis *f, SDreq *r)
1792 {
1793         if((r->ataproto & Pprotom) == Ppkt)
1794                 return SDnostatus;
1795         /*
1796          * handle oob requests;
1797          *    restrict & sanitize commands
1798          */
1799         if(r->clen != 16)
1800                 error(Eio);
1801         if(r->cmd[0] == 0xf0){
1802                 sigtofis(f, r->cmd);
1803                 r->status = SDok;
1804                 return SDok;
1805         }
1806         r->cmd[0] = 0x27;
1807         r->cmd[1] = 0x80;
1808         r->cmd[7] |= 0xa0;
1809         return SDnostatus;
1810 }
1811
1812 static int
1813 ataataio(SDreq *r)
1814 {
1815         int status, udm;
1816         Ctlr *c;
1817         Drive *d;
1818         SDunit *u;
1819
1820         u = r->unit;
1821         if((c = u->dev->ctlr) == nil || (d = c->drive[u->subno]) == nil){
1822                 r->status = SDtimeout;
1823                 return SDtimeout;
1824         }
1825         if((status = fisreqchk(d, r)) != SDnostatus)
1826                 return status;
1827         udm = isudm(r);
1828
1829         qlock(d);
1830         if(waserror()){
1831                 qunlock(d);
1832                 nexterror();
1833         }
1834 retry:
1835         d->write = r->write;
1836         d->data = r->data;
1837         d->dlen = r->dlen;
1838         d->status = 0;
1839         d->error = 0;
1840
1841         switch(status = ataataio0(d, r)){
1842         case SDretry:
1843                 if(DbgDEBUG)
1844                         print("%s: retry: dma %.8ux rwm %.4ux\n",
1845                                 u->name, d->dmactl, d->rwmctl);
1846                 goto retry;
1847         case SDok:
1848                 if(udm == 1)
1849                         d->dmactl = d->dma;
1850                 else if(udm == -1)
1851                         d->dmactl = 0;
1852                 sdsetsense(r, SDok, 0, 0, 0);
1853                 r->rlen = d->block;
1854                 break;
1855         }
1856         poperror();
1857         qunlock(d);
1858         r->status = status;
1859         return status;
1860 }
1861 /**/
1862
1863 static void
1864 ichirqack(Ctlr *ctlr)
1865 {
1866         int bmiba;
1867
1868         if(bmiba = ctlr->bmiba)
1869                 outb(bmiba+Bmisx, inb(bmiba+Bmisx));
1870 }
1871
1872 static void
1873 atainterrupt(Ureg*, void* arg)
1874 {
1875         Ctlr *ctlr;
1876         Drive *drive;
1877         int cmdport, len, status;
1878
1879         ctlr = arg;
1880
1881         ilock(ctlr);
1882         ctlr->nrq++;
1883         if(ctlr->curdrive)
1884                 ctlr->curdrive->irq++;
1885         if(inb(ctlr->ctlport+As) & Bsy){
1886                 ctlr->bsy++;
1887                 if(ctlr->curdrive)
1888                         ctlr->curdrive->bsy++;
1889                 iunlock(ctlr);
1890                 if(DEBUG & DbgBsy)
1891                         print("IBsy+");
1892                 return;
1893         }
1894         cmdport = ctlr->cmdport;
1895         status = inb(cmdport+Status);
1896         if((drive = ctlr->curdrive) == nil){
1897                 ctlr->nildrive++;
1898                 if(ctlr->irqack != nil)
1899                         ctlr->irqack(ctlr);
1900                 iunlock(ctlr);
1901                 if((DEBUG & DbgINL) && ctlr->command != Cedd)
1902                         print("Inil%2.2uX+", ctlr->command);
1903                 return;
1904         }
1905         if(status & Err)
1906                 drive->error = inb(cmdport+Error);
1907         else switch(drive->command){
1908         default:
1909                 drive->error = Abrt;
1910                 break;
1911
1912         case Crs:
1913         case Crsm:
1914         case Ppio|Pin:
1915                 if(!(status & Drq)){
1916                         drive->error = Abrt;
1917                         break;
1918                 }
1919                 len = drive->block;
1920                 if(drive->data+len > drive->limit)
1921                         len = drive->limit-drive->data;
1922                 inss(cmdport+Data, drive->data, len/2);
1923                 drive->data += len;
1924                 if(drive->data >= drive->limit)
1925                         ctlr->done = 1;
1926                 break;
1927
1928         case Cws:
1929         case Cwsm:
1930         case Ppio|Pout:
1931                 len = drive->block;
1932                 if(drive->data+len > drive->limit)
1933                         len = drive->limit-drive->data;
1934                 drive->data += len;
1935                 if(drive->data >= drive->limit){
1936                         ctlr->done = 1;
1937                         break;
1938                 }
1939                 if(!(status & Drq)){
1940                         drive->error = Abrt;
1941                         break;
1942                 }
1943                 len = drive->block;
1944                 if(drive->data+len > drive->limit)
1945                         len = drive->limit-drive->data;
1946                 outss(cmdport+Data, drive->data, len/2);
1947                 break;
1948
1949         case Cpkt:
1950         case Ppkt|Pin:
1951         case Ppkt|Pout:
1952                 atapktinterrupt(drive);
1953                 break;
1954
1955         case Crd:
1956         case Cwd:
1957         case Pdma|Pin:
1958         case Pdma|Pout:
1959                 atadmainterrupt(drive, drive->count*drive->secsize);
1960                 break;
1961
1962         case Pnd:
1963         case Preset:
1964                 ctlr->done = 1;
1965                 break;
1966         }
1967         if(ctlr->irqack != nil)
1968                 ctlr->irqack(ctlr);
1969         iunlock(ctlr);
1970
1971         if(drive->error){
1972                 status |= Err;
1973                 ctlr->done = 1;
1974         }
1975
1976         if(ctlr->done){
1977                 ctlr->curdrive = nil;
1978                 drive->status = status;
1979                 wakeup(ctlr);
1980         }
1981 }
1982
1983 typedef struct Lchan Lchan;
1984 struct Lchan {
1985         int     cmdport;
1986         int     ctlport;
1987         int     irq;
1988         int     probed;
1989 };
1990 static Lchan lchan[2] = {
1991         0x1f0,  0x3f4,  IrqATA0,        0,
1992         0x170,  0x374,  IrqATA1,        0,
1993 };
1994
1995 static int
1996 badccru(Pcidev *p)
1997 {
1998         switch(p->did<<16 | p->did){
1999         case 0x439c<<16 | 0x1002:
2000         case 0x438c<<16 | 0x1002:
2001                 print("%T: allowing bad ccru %.2ux for suspected ide controller\n",
2002                         p->tbdf, p->ccru);
2003                 return 1;
2004         default:
2005                 return 0;
2006         }
2007 }
2008
2009 static SDev*
2010 atapnp(void)
2011 {
2012         char *s;
2013         int channel, map, ispc87415, maxio, pi, r, span, maxdma, tbdf;
2014         Ctlr *ctlr;
2015         Pcidev *p;
2016         SDev *sdev, *head, *tail;
2017         void (*irqack)(Ctlr*);
2018
2019         head = tail = nil;
2020         for(p = nil; p = pcimatch(p, 0, 0); ){
2021                 /*
2022                  * Look for devices with the correct class and sub-class
2023                  * code and known device and vendor ID; add native-mode
2024                  * channels to the list to be probed, save info for the
2025                  * compatibility mode channels.
2026                  * Note that the legacy devices should not be considered
2027                  * PCI devices by the interrupt controller.
2028                  * For both native and legacy, save info for busmastering
2029                  * if capable.
2030                  * Promise Ultra ATA/66 (PDC20262) appears to
2031                  * 1) give a sub-class of 'other mass storage controller'
2032                  *    instead of 'IDE controller', regardless of whether it's
2033                  *    the only controller or not;
2034                  * 2) put 0 in the programming interface byte (probably
2035                  *    as a consequence of 1) above).
2036                  * Sub-class code 0x04 is 'RAID controller', e.g. VIA VT8237.
2037                  */
2038                 if(p->ccrb != 0x01)
2039                         continue;
2040                 if(!badccru(p))
2041                 if(p->ccru != 0x01 && p->ccru != 0x04 && p->ccru != 0x80)
2042                         continue;
2043                 pi = p->ccrp;
2044                 map = 3;
2045                 ispc87415 = 0;
2046                 maxdma = 0;
2047                 maxio = 0;
2048                 if(s = getconf("*idemaxio"))
2049                         maxio = atoi(s);
2050                 span = BMspan;
2051                 irqack = nil;
2052
2053                 switch((p->did<<16)|p->vid){
2054                 default:
2055                         continue;
2056
2057                 case (0x0002<<16)|0x100B:       /* NS PC87415 */
2058                         /*
2059                          * Disable interrupts on both channels until
2060                          * after they are probed for drives.
2061                          * This must be called before interrupts are
2062                          * enabled because the IRQ may be shared.
2063                          */
2064                         ispc87415 = 1;
2065                         pcicfgw32(p, 0x40, 0x00000300);
2066                         break;
2067                 case (0x1000<<16)|0x1042:       /* PC-Tech RZ1000 */
2068                         /*
2069                          * Turn off prefetch. Overkill, but cheap.
2070                          */
2071                         r = pcicfgr32(p, 0x40);
2072                         r &= ~0x2000;
2073                         pcicfgw32(p, 0x40, r);
2074                         break;
2075                 case (0x4D38<<16)|0x105A:       /* Promise PDC20262 */
2076                 case (0x4D30<<16)|0x105A:       /* Promise PDC202xx */
2077                 case (0x4D68<<16)|0x105A:       /* Promise PDC20268 */
2078                 case (0x4D69<<16)|0x105A:       /* Promise Ultra/133 TX2 */
2079                 case (0x3373<<16)|0x105A:       /* Promise 20378 RAID */
2080                 case (0x3149<<16)|0x1106:       /* VIA VT8237 SATA/RAID */
2081                 case (0x3112<<16)|0x1095:       /* SiL 3112 SATA/RAID */
2082                         maxio = 15;
2083                         span = 8*1024;
2084                         /*FALLTHROUGH*/
2085                 case (0x3114<<16)|0x1095:       /* SiL 3114 SATA/RAID */
2086                 case (0x0680<<16)|0x1095:       /* SiI 0680/680A PATA133 ATAPI/RAID */
2087                         pi = 0x85;
2088                         break;
2089                 case (0x0004<<16)|0x1103:       /* HighPoint HPT366 */
2090                         pi = 0x85;
2091                         /*
2092                          * Turn off fast interrupt prediction.
2093                          */
2094                         if((r = pcicfgr8(p, 0x51)) & 0x80)
2095                                 pcicfgw8(p, 0x51, r & ~0x80);
2096                         if((r = pcicfgr8(p, 0x55)) & 0x80)
2097                                 pcicfgw8(p, 0x55, r & ~0x80);
2098                         break;
2099                 case (0x0640<<16)|0x1095:       /* CMD 640B */
2100                         /*
2101                          * Bugfix code here...
2102                          */
2103                         break;
2104                 case (0x7441<<16)|0x1022:       /* AMD 768 */
2105                 case (0x7800<<16)|0x1022:
2106                         /*
2107                          * Set:
2108                          *      0x41    prefetch, postwrite;
2109                          *      0x43    FIFO configuration 1/2 and 1/2;
2110                          *      0x44    status register read retry;
2111                          *      0x46    DMA read and end of sector flush.
2112                          */
2113                         r = pcicfgr8(p, 0x41);
2114                         pcicfgw8(p, 0x41, r|0xF0);
2115                         r = pcicfgr8(p, 0x43);
2116                         pcicfgw8(p, 0x43, (r & 0x90)|0x2A);
2117                         r = pcicfgr8(p, 0x44);
2118                         pcicfgw8(p, 0x44, r|0x08);
2119                         r = pcicfgr8(p, 0x46);
2120                         pcicfgw8(p, 0x46, (r & 0x0C)|0xF0);
2121                         /*FALLTHROUGH*/
2122                 case (0x01BC<<16)|0x10DE:       /* nVidia nForce1 */
2123                 case (0x0065<<16)|0x10DE:       /* nVidia nForce2 */
2124                 case (0x0085<<16)|0x10DE:       /* nVidia nForce2 MCP */
2125                 case (0x00E3<<16)|0x10DE:       /* nVidia nForce2 250 SATA */
2126                 case (0x00D5<<16)|0x10DE:       /* nVidia nForce3 */
2127                 case (0x00E5<<16)|0x10DE:       /* nVidia nForce3 Pro */
2128                 case (0x00EE<<16)|0x10DE:       /* nVidia nForce3 250 SATA */
2129                 case (0x0035<<16)|0x10DE:       /* nVidia nForce3 MCP */
2130                 case (0x0053<<16)|0x10DE:       /* nVidia nForce4 */
2131                 case (0x0054<<16)|0x10DE:       /* nVidia nForce4 SATA */
2132                 case (0x0055<<16)|0x10DE:       /* nVidia nForce4 SATA */
2133                 case (0x0266<<16)|0x10DE:       /* nVidia nForce4 430 SATA */
2134                 case (0x0265<<16)|0x10DE:       /* nVidia nForce 51 MCP */
2135                 case (0x0267<<16)|0x10DE:       /* nVidia nForce 55 MCP SATA */
2136                 case (0x03ec<<16)|0x10DE:       /* nVidia nForce 61 MCP SATA */
2137                 case (0x03f6<<16)|0x10DE:       /* nVidia nForce 61 MCP PATA */
2138                 case (0x0448<<16)|0x10DE:       /* nVidia nForce 65 MCP SATA */
2139                 case (0x0560<<16)|0x10DE:       /* nVidia nForce 69 MCP SATA */
2140                         /*
2141                          * Ditto, although it may have a different base
2142                          * address for the registers (0x50?).
2143                          */
2144                         /*FALLTHROUGH*/
2145                 case (0x209A<<16)|0x1022:       /* AMD CS5536 */
2146                 case (0x7401<<16)|0x1022:       /* AMD 755 Cobra */
2147                 case (0x7409<<16)|0x1022:       /* AMD 756 Viper */
2148                 case (0x7410<<16)|0x1022:       /* AMD 766 Viper Plus */
2149                 case (0x7469<<16)|0x1022:       /* AMD 3111 */
2150                 case (0x4376<<16)|0x1002:       /* SB4xx pata */
2151                 case (0x4379<<16)|0x1002:       /* SB4xx sata */
2152                 case (0x437a<<16)|0x1002:       /* SB4xx sata ctlr #2 */
2153                 case (0x437c<<16)|0x1002:       /* Rx6xx pata */
2154                 case (0x438c<<16)|0x1002:       /* ATI SB600 PATA */
2155                 case (0x439c<<16)|0x1002:       /* SB7xx pata */
2156                         break;
2157
2158                 case (0x6101<<16)|0x11ab:       /* Marvell PATA */
2159                 case (0x6121<<16)|0x11ab:       /* Marvell PATA */
2160                 case (0x6123<<16)|0x11ab:       /* Marvell PATA */
2161                 case (0x6145<<16)|0x11ab:       /* Marvell PATA */
2162                 case (0x1b4b<<16)|0x91a0:       /* Marvell PATA */
2163                 case (0x1b4b<<16)|0x91a4:       /* Marvell PATA */
2164                         break;
2165
2166                 case (0x0211<<16)|0x1166:       /* ServerWorks IB6566 */
2167                         {
2168                                 Pcidev *sb;
2169
2170                                 sb = pcimatch(nil, 0x1166, 0x0200);
2171                                 if(sb == nil)
2172                                         break;
2173                                 r = pcicfgr32(sb, 0x64);
2174                                 r &= ~0x2000;
2175                                 pcicfgw32(sb, 0x64, r);
2176                         }
2177                         span = 32*1024;
2178                         break;
2179                 case (0x5229<<16)|0x10B9:       /* ALi M1543 */
2180                 case (0x5288<<16)|0x10B9:       /* ALi M5288 SATA */
2181                         /*FALLTHROUGH*/
2182                 case (0x5513<<16)|0x1039:       /* SiS 962 */
2183                 case (0x0646<<16)|0x1095:       /* CMD 646 */
2184                 case (0x0571<<16)|0x1106:       /* VIA 82C686 */
2185                 case (0x9001<<16)|0x1106:       /* VIA chipset in VIA PV530 */
2186                 case (0x0502<<16)|0x100b:       /* National Semiconductor SC1100/SCx200 */
2187                         break;
2188                 case (0x2360<<16)|0x197b:       /* jmicron jmb360 */
2189                 case (0x2361<<16)|0x197b:       /* jmicron jmb361 */
2190                 case (0x2363<<16)|0x197b:       /* jmicron jmb363 */
2191                 case (0x2365<<16)|0x197b:       /* jmicron jmb365 */
2192                 case (0x2366<<16)|0x197b:       /* jmicron jmb366 */
2193                 case (0x2368<<16)|0x197b:       /* jmicron jmb368 */
2194                         break;
2195                 case (0x7010<<16)|0x8086:       /* 82371SB (PIIX3) */
2196                 case (0x1230<<16)|0x8086:       /* 82371FB (PIIX) */
2197                 case (0x7111<<16)|0x8086:       /* 82371[AE]B (PIIX4[E]) */
2198                         maxdma = 0x20000;
2199                         break;
2200                 case (0x2411<<16)|0x8086:       /* 82801AA (ICH) */
2201                 case (0x2421<<16)|0x8086:       /* 82801AB (ICH0) */
2202                 case (0x244A<<16)|0x8086:       /* 82801BA (ICH2, Mobile) */
2203                 case (0x244B<<16)|0x8086:       /* 82801BA (ICH2, High-End) */
2204                 case (0x248A<<16)|0x8086:       /* 82801CA (ICH3, Mobile) */
2205                 case (0x248B<<16)|0x8086:       /* 82801CA (ICH3, High-End) */
2206                 case (0x24CA<<16)|0x8086:       /* 82801DBM (ICH4, Mobile) */
2207                 case (0x24CB<<16)|0x8086:       /* 82801DB (ICH4, High-End) */
2208                 case (0x24D1<<16)|0x8086:       /* 82801er (ich5) */
2209                 case (0x24DB<<16)|0x8086:       /* 82801EB (ICH5) */
2210                 case (0x25A2<<16)|0x8086:       /* 6300ESB pata */
2211                 case (0x25A3<<16)|0x8086:       /* 6300ESB (E7210) */
2212                 case (0x266F<<16)|0x8086:       /* 82801FB (ICH6) */
2213                 case (0x2651<<16)|0x8086:       /* 82801FB (ICH6) */
2214                 case (0x2653<<16)|0x8086:       /* 82801FBM (ICH6, Mobile) */
2215                 case (0x269e<<16)|0x8086:       /* 63xxESB (intel 5000) */
2216                 case (0x27DF<<16)|0x8086:       /* 82801G PATA (ICH7) */
2217                 case (0x27C0<<16)|0x8086:       /* 82801GB SATA (ICH7) */
2218                 case (0x27C4<<16)|0x8086:       /* 82801GBM SATA (ICH7) */
2219                 case (0x27C5<<16)|0x8086:       /* 82801GBM SATA AHCI (ICH7) */
2220                 case (0x2850<<16)|0x8086:       /* 82801HBM/HEM PATA */
2221                 case (0x2820<<16)|0x8086:       /* 82801HB/HR/HH/HO SATA IDE */
2222                 case (0x2828<<16)|0x8086:       /* 82801HBM SATA (ICH8-M) */
2223                 case (0x2829<<16)|0x8086:       /* 82801HBM SATA AHCI (ICH8-M) */
2224                 case (0x2920<<16)|0x8086:       /* 82801(IB)/IR/IH/IO SATA (ICH9) port 0-3 */
2225                 case (0x2921<<16)|0x8086:       /* 82801(IB)/IR/IH/IO SATA (ICH9) port 0-1 */
2226                 case (0x2926<<16)|0x8086:       /* 82801(IB)/IR/IH/IO SATA (ICH9) port 4-5 */
2227                 case (0x2928<<16)|0x8086:       /* 82801(IB)/IR/IH/IO SATA (ICH9m) port 0-1 */
2228                 case (0x2929<<16)|0x8086:       /* 82801(IB)/IR/IH/IO SATA (ICH9m) port 0-1, 4-5 */
2229                 case (0x292d<<16)|0x8086:       /* 82801(IB)/IR/IH/IO SATA (ICH9m) port 4-5*/
2230                 case (0x3a20<<16)|0x8086:       /* 82801ji (ich10) */
2231                 case (0x3a26<<16)|0x8086:       /* 82801ji (ich10) */
2232                 case (0x3b20<<16)|0x8086:       /* 34x0 (pch) port 0-3 */
2233                 case (0x3b21<<16)|0x8086:       /* 34x0 (pch) port 4-5 */
2234                 case (0x3b28<<16)|0x8086:       /* 34x0pm (pch) port 0-1, 4-5 */
2235                 case (0x3b2e<<16)|0x8086:       /* 34x0pm (pch) port 0-3 */
2236                         map = 0;
2237                         if(pcicfgr16(p, 0x40) & 0x8000)
2238                                 map |= 1;
2239                         if(pcicfgr16(p, 0x42) & 0x8000)
2240                                 map |= 2;
2241                         irqack = ichirqack;
2242                         break;
2243                 }
2244                 for(channel = 0; channel < 2; channel++){
2245                         if((map & 1<<channel) == 0)
2246                                 continue;
2247                         if(pi & 1<<2*channel){
2248                                 sdev = ataprobe(p->mem[0+2*channel].bar & ~0x01,
2249                                                 p->mem[1+2*channel].bar & ~0x01,
2250                                                 p->intl, 3);
2251                                 tbdf = p->tbdf;
2252                         }
2253                         else if(lchan[channel].probed == 0){
2254                                 sdev = ataprobe(lchan[channel].cmdport,
2255                                         lchan[channel].ctlport, lchan[channel].irq, 3);
2256                                 lchan[channel].probed = 1;
2257                                 tbdf = BUSUNKNOWN;
2258                         }
2259                         else
2260                                 continue;
2261                         if(sdev == nil)
2262                                 continue;
2263                         ctlr = sdev->ctlr;
2264                         if(ispc87415) {
2265                                 ctlr->ienable = pc87415ienable;
2266                                 print("pc87415disable: not yet implemented\n");
2267                         }
2268                         ctlr->tbdf = tbdf;
2269                         ctlr->pcidev = p;
2270                         ctlr->maxio = maxio;
2271                         ctlr->maxdma = maxdma;
2272                         ctlr->span = span;
2273                         ctlr->irqack = irqack;
2274                         if(pi & 0x80)
2275                                 ctlr->bmiba = (p->mem[4].bar & ~0x01) + channel*8;
2276                         if(head != nil)
2277                                 tail->next = sdev;
2278                         else
2279                                 head = sdev;
2280                         tail = sdev;
2281                 }
2282         }
2283
2284         if(lchan[0].probed + lchan[1].probed == 0)
2285                 for(channel = 0; channel < 2; channel++){
2286                         sdev = nil;
2287                         if(lchan[channel].probed == 0){
2288         //                      print("sdide: blind probe %.3ux\n", lchan[channel].cmdport);
2289                                 sdev = ataprobe(lchan[channel].cmdport,
2290                                         lchan[channel].ctlport, lchan[channel].irq, 3);
2291                                 lchan[channel].probed = 1;
2292                         }
2293                         if(sdev == nil)
2294                                 continue;
2295                         if(head != nil)
2296                                 tail->next = sdev;
2297                         else
2298                                 head = sdev;
2299                         tail = sdev;
2300                 }
2301
2302 if(0){
2303         int port;
2304         ISAConf isa;
2305
2306         /*
2307          * Hack for PCMCIA drives.
2308          * This will be tidied once we figure out how the whole
2309          * removeable device thing is going to work.
2310          */
2311         memset(&isa, 0, sizeof(isa));
2312         isa.port = 0x180;               /* change this for your machine */
2313         isa.irq = 11;                   /* change this for your machine */
2314
2315         port = isa.port+0x0C;
2316         channel = pcmspecial("MK2001MPL", &isa);
2317         if(channel == -1)
2318                 channel = pcmspecial("SunDisk", &isa);
2319         if(channel == -1){
2320                 isa.irq = 10;
2321                 channel = pcmspecial("CF", &isa);
2322         }
2323         if(channel == -1){
2324                 isa.irq = 10;
2325                 channel = pcmspecial("OLYMPUS", &isa);
2326         }
2327         if(channel == -1){
2328                 port = isa.port+0x204;
2329                 channel = pcmspecial("ATA/ATAPI", &isa);
2330         }
2331         if(channel >= 0 && (sdev = ataprobe(isa.port, port, isa.irq, 3)) != nil){
2332                 if(head != nil)
2333                         tail->next = sdev;
2334                 else
2335                         head = sdev;
2336         }
2337 }
2338         return head;
2339 }
2340
2341 static void
2342 atadmaclr(Ctlr *ctlr)
2343 {
2344         int bmiba, bmisx;
2345
2346         if(ctlr->curdrive)
2347                 ataabort(ctlr->curdrive, 1);
2348         bmiba = ctlr->bmiba;
2349         if(bmiba == 0)
2350                 return;
2351         atadmastop(ctlr);
2352         outl(bmiba+Bmidtpx, 0);
2353         bmisx = inb(bmiba+Bmisx) & ~Bmidea;
2354         outb(bmiba+Bmisx, bmisx|Ideints|Idedmae);
2355 //      pciintst(ctlr->pcidev);
2356 }
2357
2358 static int
2359 ataenable(SDev* sdev)
2360 {
2361         Ctlr *ctlr;
2362         char name[32];
2363
2364         ctlr = sdev->ctlr;
2365         if(ctlr->bmiba){
2366                 atadmaclr(ctlr);
2367                 if(ctlr->pcidev != nil)
2368                         pcisetbme(ctlr->pcidev);
2369                 ctlr->prdt = mallocalign(Nprd*sizeof(Prd), 4, 0, 64*1024);
2370         }
2371         snprint(name, sizeof(name), "%s (%s)", sdev->name, sdev->ifc->name);
2372         intrenable(ctlr->irq, atainterrupt, ctlr, ctlr->tbdf, name);
2373         outb(ctlr->ctlport+Dc, 0);
2374         if(ctlr->ienable)
2375                 ctlr->ienable(ctlr);
2376         return 1;
2377 }
2378
2379 static int
2380 atadisable(SDev *sdev)
2381 {
2382         Ctlr *ctlr;
2383         char name[32];
2384
2385         ctlr = sdev->ctlr;
2386         outb(ctlr->ctlport+Dc, Nien);           /* disable interrupts */
2387         if (ctlr->idisable)
2388                 ctlr->idisable(ctlr);
2389         snprint(name, sizeof(name), "%s (%s)", sdev->name, sdev->ifc->name);
2390         intrdisable(ctlr->irq, atainterrupt, ctlr, ctlr->tbdf, name);
2391         if(ctlr->bmiba) {
2392 //              atadmaclr(ctlr);
2393                 if (ctlr->pcidev)
2394                         pciclrbme(ctlr->pcidev);
2395                 free(ctlr->prdt);
2396                 ctlr->prdt = nil;
2397         }
2398         return 0;
2399 }
2400
2401 static int
2402 ataonline(SDunit *unit)
2403 {
2404         Drive *drive;
2405         Ctlr *ctlr;
2406         int ret;
2407
2408         if((ctlr = unit->dev->ctlr) == nil || ctlr->drive[unit->subno] == nil)
2409                 return 0;
2410         ret = 1;
2411         drive = ctlr->drive[unit->subno];
2412         if((drive->flags & Online) == 0){
2413                 drive->flags |= Online;
2414                 atadrive(unit, drive, ctlr->cmdport, ctlr->ctlport, drive->dev);
2415                 ret = 2;
2416         }
2417         if(drive->feat & Datapi){
2418                 ulong dma;
2419
2420                 dma = drive->dmactl;
2421                 drive->dmactl = 0;
2422                 ret = scsionline(unit);
2423                 drive->dmactl = dma;
2424         } else {
2425                 unit->sectors = drive->sectors;
2426                 unit->secsize = drive->secsize;
2427         }
2428         return ret;
2429 }
2430
2431 static int
2432 atarctl(SDunit* unit, char* p, int l)
2433 {
2434         Ctlr *ctlr;
2435         Drive *drive;
2436         char *e, *op;
2437
2438         if((ctlr = unit->dev->ctlr) == nil || ctlr->drive[unit->subno] == nil)
2439                 return 0;
2440         drive = ctlr->drive[unit->subno];
2441
2442         e = p+l;
2443         op = p;
2444         qlock(drive);
2445         p = seprint(p, e, "config %4.4uX capabilities %4.4uX", drive->info[Iconfig], drive->info[Icapabilities]);
2446         if(drive->dma)
2447                 p = seprint(p, e, " dma %8.8uX dmactl %8.8uX", drive->dma, drive->dmactl);
2448         if(drive->rwm)
2449                 p = seprint(p, e, " rwm %ud rwmctl %ud", drive->rwm, drive->rwmctl);
2450         if(drive->feat & Dllba)
2451                 p = seprint(p, e, " lba48always %s", (drive->flags&Lba48always) ? "on" : "off");
2452         p = seprint(p, e, "\n");
2453         p = seprint(p, e, "model        %s\n", drive->model);
2454         p = seprint(p, e, "serial       %s\n", drive->serial);
2455         p = seprint(p, e, "firm %s\n", drive->firmware);
2456         p = seprint(p, e, "feat ");
2457         p = pflag(p, e, drive);
2458         if(drive->sectors){
2459                 p = seprint(p, e, "geometry %llud %d", drive->sectors, drive->secsize);
2460                 if(drive->pkt == 0 && (drive->feat & Dlba) == 0)
2461                         p = seprint(p, e, " %d %d %d", drive->c, drive->h, drive->s);
2462                 p = seprint(p, e, "\n");
2463         }
2464         p = seprint(p, e, "missirq      %ud\n", drive->missirq);
2465         p = seprint(p, e, "sloop        %ud\n", drive->spurloop);
2466         p = seprint(p, e, "irq  %ud %ud\n", ctlr->nrq, drive->irq);
2467         p = seprint(p, e, "bsy  %ud %ud\n", ctlr->bsy, drive->bsy);
2468         p = seprint(p, e, "nildrive     %ud\n", ctlr->nildrive);
2469         qunlock(drive);
2470
2471         return p - op;
2472 }
2473
2474 static int
2475 atawctl(SDunit* unit, Cmdbuf* cb)
2476 {
2477         Ctlr *ctlr;
2478         Drive *drive;
2479
2480         if((ctlr = unit->dev->ctlr) == nil || ctlr->drive[unit->subno] == nil)
2481                 return 0;
2482         drive = ctlr->drive[unit->subno];
2483
2484         qlock(drive);
2485         if(waserror()){
2486                 qunlock(drive);
2487                 nexterror();
2488         }
2489
2490         /*
2491          * Dma and rwm control is passive at the moment,
2492          * i.e. it is assumed that the hardware is set up
2493          * correctly already either by the BIOS or when
2494          * the drive was initially identified.
2495          */
2496         if(strcmp(cb->f[0], "dma") == 0){
2497                 if(cb->nf != 2 || drive->dma == 0)
2498                         error(Ebadctl);
2499                 if(strcmp(cb->f[1], "on") == 0)
2500                         drive->dmactl = drive->dma;
2501                 else if(strcmp(cb->f[1], "off") == 0)
2502                         drive->dmactl = 0;
2503                 else
2504                         error(Ebadctl);
2505         }
2506         else if(strcmp(cb->f[0], "rwm") == 0){
2507                 if(cb->nf != 2 || drive->rwm == 0)
2508                         error(Ebadctl);
2509                 if(strcmp(cb->f[1], "on") == 0)
2510                         drive->rwmctl = drive->rwm;
2511                 else if(strcmp(cb->f[1], "off") == 0)
2512                         drive->rwmctl = 0;
2513                 else
2514                         error(Ebadctl);
2515         }
2516         else if(strcmp(cb->f[0], "lba48always") == 0){
2517                 if(cb->nf != 2 || !(drive->feat & Dllba))
2518                         error(Ebadctl);
2519                 if(strcmp(cb->f[1], "on") == 0)
2520                         drive->flags |= Lba48always;
2521                 else if(strcmp(cb->f[1], "off") == 0)
2522                         drive->flags &= ~Lba48always;
2523                 else
2524                         error(Ebadctl);
2525         }
2526         else if(strcmp(cb->f[0], "identify") == 0){
2527                 atadrive(unit, drive, ctlr->cmdport, ctlr->ctlport, drive->dev);
2528         }
2529         else
2530                 error(Ebadctl);
2531         qunlock(drive);
2532         poperror();
2533
2534         return 0;
2535 }
2536
2537 SDifc sdideifc = {
2538         "ide",                          /* name */
2539
2540         atapnp,                         /* pnp */
2541         nil,                            /* legacy */
2542         ataenable,                      /* enable */
2543         atadisable,                     /* disable */
2544
2545         scsiverify,                     /* verify */
2546         ataonline,                      /* online */
2547         atario,                         /* rio */
2548         atarctl,                        /* rctl */
2549         atawctl,                        /* wctl */
2550
2551         scsibio,                        /* bio */
2552         ataprobew,                      /* probe */
2553         ataclear,                       /* clear */
2554         atastat,                        /* rtopctl */
2555         nil,                            /* wtopctl */
2556         ataataio,
2557 };