Merge from vendor branch TEXINFO:
[dragonfly.git] / sys / dev / disk / ata / ata-disk.c
1 /*-
2  * Copyright (c) 1998,1999,2000,2001,2002 Søren Schmidt <sos@FreeBSD.org>
3  * All rights reserved.
4  *
5  * Redistribution and use in source and binary forms, with or without
6  * modification, are permitted provided that the following conditions
7  * are met:
8  * 1. Redistributions of source code must retain the above copyright
9  *    notice, this list of conditions and the following disclaimer,
10  *    without modification, immediately at the beginning of the file.
11  * 2. Redistributions in binary form must reproduce the above copyright
12  *    notice, this list of conditions and the following disclaimer in the
13  *    documentation and/or other materials provided with the distribution.
14  * 3. The name of the author may not be used to endorse or promote products
15  *    derived from this software without specific prior written permission.
16  *
17  * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR
18  * IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
19  * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.
20  * IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT,
21  * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
22  * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
23  * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
24  * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
25  * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
26  * THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
27  *
28  * $FreeBSD: src/sys/dev/ata/ata-disk.c,v 1.60.2.24 2003/01/30 07:19:59 sos Exp $
29  * $DragonFly: src/sys/dev/disk/ata/ata-disk.c,v 1.25 2005/08/26 14:26:45 hmp Exp $
30  */
31
32 #include "opt_ata.h"
33 #include <sys/param.h>
34 #include <sys/systm.h>
35 #include <sys/ata.h>
36 #include <sys/kernel.h>
37 #include <sys/malloc.h>
38 #include <sys/buf.h>
39 #include <sys/bus.h>
40 #include <sys/conf.h>
41 #include <sys/disk.h>
42 #include <sys/devicestat.h>
43 #include <sys/cons.h>
44 #include <sys/sysctl.h>
45 #include <sys/syslog.h>
46 #include <vm/vm.h>
47 #include <vm/pmap.h>
48 #include <machine/md_var.h>
49 #include <machine/bus.h>
50 #include <machine/clock.h>
51 #include <sys/rman.h>
52 #include "ata-all.h"
53 #include "ata-disk.h"
54 #include "ata-raid.h"
55 #include <sys/proc.h>
56 #include <sys/buf2.h>
57 #include <sys/thread2.h>
58
59 /* device structures */
60 static d_open_t         adopen;
61 static d_close_t        adclose;
62 static d_strategy_t     adstrategy;
63 static d_dump_t         addump;
64
65 static struct cdevsw ad_cdevsw = {
66         /* name */      "ad",
67         /* maj */       116,
68         /* flags */     D_DISK,
69         /* port */      NULL,
70         /* clone */     NULL,
71
72         /* open */      adopen,
73         /* close */     adclose,
74         /* read */      physread,
75         /* write */     physwrite,
76         /* ioctl */     noioctl,
77         /* poll */      nopoll,
78         /* mmap */      nommap,
79         /* strategy */  adstrategy,
80         /* dump */      addump,
81         /* psize */     nopsize
82 };
83
84 /* prototypes */
85 static void ad_requeue(struct ata_channel *, struct ad_request *);
86 static void ad_invalidatequeue(struct ad_softc *, struct ad_request *);
87 static int ad_tagsupported(struct ad_softc *);
88 static void ad_timeout(struct ad_request *);
89 static void ad_free(struct ad_request *);
90 static int ad_version(u_int16_t);
91
92 /* misc defines */
93 #define AD_MAX_RETRIES  3
94
95 /* internal vars */
96 static u_int32_t adp_lun_map = 0;
97 static int ata_dma = 1;
98 static int ata_wc = 1;
99 static int ata_tags = 0; 
100 TUNABLE_INT("hw.ata.ata_dma", &ata_dma);
101 TUNABLE_INT("hw.ata.wc", &ata_wc);
102 TUNABLE_INT("hw.ata.tags", &ata_tags);
103 static MALLOC_DEFINE(M_AD, "AD driver", "ATA disk driver");
104
105 /* sysctl vars */
106 SYSCTL_DECL(_hw_ata);
107 SYSCTL_INT(_hw_ata, OID_AUTO, ata_dma, CTLFLAG_RD, &ata_dma, 0,
108            "ATA disk DMA mode control");
109 SYSCTL_INT(_hw_ata, OID_AUTO, wc, CTLFLAG_RD, &ata_wc, 0,
110            "ATA disk write caching");
111 SYSCTL_INT(_hw_ata, OID_AUTO, tags, CTLFLAG_RD, &ata_tags, 0,
112            "ATA disk tagged queuing support");
113
114 void
115 ad_attach(struct ata_device *atadev, int alreadylocked)
116 {
117     struct ad_softc *adp;
118     dev_t dev;
119
120     adp = malloc(sizeof(struct ad_softc), M_AD, M_WAITOK | M_ZERO);
121
122     KKASSERT(atadev->channel->req_mpipe.max_count != 0);
123
124     adp->device = atadev;
125 #ifdef ATA_STATIC_ID
126     adp->lun = (device_get_unit(atadev->channel->dev)<<1)+ATA_DEV(atadev->unit);
127 #else
128     adp->lun = ata_get_lun(&adp_lun_map);
129 #endif
130     ata_set_name(atadev, "ad", adp->lun);
131     adp->heads = atadev->param->heads;
132     adp->sectors = atadev->param->sectors;
133     adp->total_secs = atadev->param->cylinders * adp->heads * adp->sectors;     
134     bufq_init(&adp->queue);
135
136     /* does this device need oldstyle CHS addressing */
137     if (!ad_version(atadev->param->version_major) || 
138         !(atadev->param->atavalid & ATA_FLAG_54_58) || !atadev->param->lba_size)
139         adp->flags |= AD_F_CHS_USED;
140
141     /* use the 28bit LBA size if valid */
142     if (atadev->param->cylinders == 16383 &&
143         adp->total_secs < atadev->param->lba_size)
144         adp->total_secs = atadev->param->lba_size;
145
146     /* use the 48bit LBA size if valid */
147     if (atadev->param->support.address48 &&
148         atadev->param->lba_size48 > 268435455)
149         adp->total_secs = atadev->param->lba_size48;
150     
151     if (!alreadylocked)
152         ATA_SLEEPLOCK_CH(atadev->channel, ATA_CONTROL);
153     /* use multiple sectors/interrupt if device supports it */
154     adp->transfersize = DEV_BSIZE;
155     if (ad_version(atadev->param->version_major)) {
156         int secsperint = max(1, min(atadev->param->sectors_intr, 16));
157
158         if (!ata_command(atadev, ATA_C_SET_MULTI, 0, secsperint,
159                          0, ATA_WAIT_INTR) && !ata_wait(atadev, 0))
160         adp->transfersize *= secsperint;
161     }
162
163     /* enable read caching if not default on device */
164     if (ata_command(atadev, ATA_C_SETFEATURES,
165                     0, 0, ATA_C_F_ENAB_RCACHE, ATA_WAIT_INTR))
166         ata_prtdev(atadev, "enabling readahead cache failed\n");
167
168     /* enable write caching if allowed and not default on device */
169     if (ata_wc || (ata_tags && ad_tagsupported(adp))) {
170         if (ata_command(atadev, ATA_C_SETFEATURES,
171                         0, 0, ATA_C_F_ENAB_WCACHE, ATA_WAIT_INTR))
172             ata_prtdev(atadev, "enabling write cache failed\n");
173     }
174     else {
175         if (ata_command(atadev, ATA_C_SETFEATURES,
176                         0, 0, ATA_C_F_DIS_WCACHE, ATA_WAIT_INTR))
177             ata_prtdev(atadev, "disabling write cache failed\n");
178     }
179
180     /* use DMA if allowed and if drive/controller supports it */
181     if (ata_dma)
182         ata_dmainit(atadev, ata_pmode(atadev->param), 
183                     ata_wmode(atadev->param), ata_umode(atadev->param));
184     else
185         ata_dmainit(atadev, ata_pmode(atadev->param), -1, -1);
186
187     /* use tagged queueing if allowed and supported */
188     if (ata_tags && ad_tagsupported(adp)) {
189         adp->num_tags = atadev->param->queuelen;
190         adp->flags |= AD_F_TAG_ENABLED;
191         adp->device->channel->flags |= ATA_QUEUED;
192         if (ata_command(atadev, ATA_C_SETFEATURES,
193                         0, 0, ATA_C_F_DIS_RELIRQ, ATA_WAIT_INTR))
194             ata_prtdev(atadev, "disabling release interrupt failed\n");
195         if (ata_command(atadev, ATA_C_SETFEATURES,
196                         0, 0, ATA_C_F_DIS_SRVIRQ, ATA_WAIT_INTR))
197             ata_prtdev(atadev, "disabling service interrupt failed\n");
198     }
199
200     ATA_UNLOCK_CH(atadev->channel);
201
202     devstat_add_entry(&adp->stats, "ad", adp->lun, DEV_BSIZE,
203                       DEVSTAT_NO_ORDERED_TAGS,
204                       DEVSTAT_TYPE_DIRECT | DEVSTAT_TYPE_IF_IDE,
205                       DEVSTAT_PRIORITY_DISK);
206
207     dev = disk_create(adp->lun, &adp->disk, 0, &ad_cdevsw);
208     dev->si_drv1 = adp;
209     dev->si_iosize_max = 256 * DEV_BSIZE;
210     adp->dev = dev;
211
212     /* construct the disklabel */
213     bzero(&adp->disk.d_label, sizeof(struct disklabel));
214     adp->disk.d_label.d_secsize = DEV_BSIZE;
215     adp->disk.d_label.d_nsectors = adp->sectors;
216     adp->disk.d_label.d_ntracks = adp->heads;
217     adp->disk.d_label.d_ncylinders = adp->total_secs/(adp->heads*adp->sectors);
218     adp->disk.d_label.d_secpercyl = adp->sectors * adp->heads;
219     adp->disk.d_label.d_secperunit = adp->total_secs;
220
221     atadev->driver = adp;
222     atadev->flags = 0;
223
224     /* if this disk belongs to an ATA RAID dont print the probe */
225     if (ata_raiddisk_attach(adp))
226         adp->flags |= AD_F_RAID_SUBDISK;
227     else {
228         if (atadev->driver) {
229             ad_print(adp);
230             ata_enclosure_print(atadev);
231         }
232     }
233 }
234
235 void
236 ad_detach(struct ata_device *atadev, int flush) /* get rid of flush XXX SOS */
237 {
238     struct ad_softc *adp = atadev->driver;
239     struct ad_request *request;
240     struct buf *bp;
241
242     atadev->flags |= ATA_D_DETACHING;
243     ata_prtdev(atadev, "removed from configuration\n");
244     ad_invalidatequeue(adp, NULL);
245     TAILQ_FOREACH(request, &atadev->channel->ata_queue, chain) {
246         if (request->softc != adp)
247             continue;
248         TAILQ_REMOVE(&atadev->channel->ata_queue, request, chain);
249         request->bp->b_error = ENXIO;
250         request->bp->b_flags |= B_ERROR;
251         biodone(request->bp);
252         ad_free(request);
253     }
254     ata_dmafree(atadev);
255     while ((bp = bufq_first(&adp->queue))) {
256         bufq_remove(&adp->queue, bp); 
257         bp->b_error = ENXIO;
258         bp->b_flags |= B_ERROR;
259         biodone(bp);
260     }
261     disk_invalidate(&adp->disk);
262     devstat_remove_entry(&adp->stats);
263     disk_destroy(&adp->disk);
264     if (flush) {
265         if (ata_command(atadev, ATA_C_FLUSHCACHE, 0, 0, 0, ATA_WAIT_READY))
266             ata_prtdev(atadev, "flushing cache on detach failed\n");
267     }
268     if (adp->flags & AD_F_RAID_SUBDISK)
269         ata_raiddisk_detach(adp);
270     ata_free_name(atadev);
271     ata_free_lun(&adp_lun_map, adp->lun);
272     atadev->driver = NULL;
273     atadev->flags = 0;
274     free(adp, M_AD);
275 }
276
277 static int
278 adopen(dev_t dev, int flags, int fmt, struct thread *td)
279 {
280     struct ad_softc *adp = dev->si_drv1;
281
282     if (adp->flags & AD_F_RAID_SUBDISK)
283         return EBUSY;
284     return 0;
285 }
286
287 static int
288 adclose(dev_t dev, int flags, int fmt, struct thread *td)
289 {
290     struct ad_softc *adp = dev->si_drv1;
291
292     crit_enter();       /* interlock non-atomic channel lock */
293     ATA_SLEEPLOCK_CH(adp->device->channel, ATA_CONTROL);
294     if (ata_command(adp->device, ATA_C_FLUSHCACHE, 0, 0, 0, ATA_WAIT_READY))
295         ata_prtdev(adp->device, "flushing cache on close failed\n");
296     ATA_UNLOCK_CH(adp->device->channel);
297     crit_exit();
298     return 0;
299 }
300
301 /*
302  * note: always use the passed device rather then bp->b_dev, as the bp
303  * may have been translated through several layers.
304  */
305 static void 
306 adstrategy(struct buf *bp)
307 {
308     struct ad_softc *adp = bp->b_dev->si_drv1;
309
310     if (adp->device->flags & ATA_D_DETACHING) {
311         bp->b_error = ENXIO;
312         bp->b_flags |= B_ERROR;
313         biodone(bp);
314         return;
315     }
316     crit_enter();
317     bufqdisksort(&adp->queue, bp);
318     crit_exit();
319     ata_start(adp->device->channel);
320 }
321
322 int
323 addump(dev_t dev, u_int count, u_int blkno, u_int secsize)
324 {
325     struct ad_softc *adp = dev->si_drv1;
326     struct ad_request request;
327     vm_paddr_t addr = 0;
328     long blkcnt;
329     int dumppages = MAXDUMPPGS;
330     int i;
331
332     if (!adp)
333         return ENXIO;
334
335     /* force PIO mode for dumps */
336     adp->device->mode = ATA_PIO;
337     ata_reinit(adp->device->channel);
338
339     blkcnt = howmany(PAGE_SIZE, secsize);
340
341     while (count > 0) {
342         caddr_t va = NULL;
343         DELAY(1000);
344
345         if ((count / blkcnt) < dumppages)
346             dumppages = count / blkcnt;
347
348         for (i = 0; i < dumppages; ++i) {
349             vm_paddr_t a = addr + (i * PAGE_SIZE);
350             if (is_physical_memory(a))
351                 va = pmap_kenter_temporary(trunc_page(a), i);
352             else
353                 va = pmap_kenter_temporary(trunc_page(0), i);
354         }
355
356         bzero(&request, sizeof(struct ad_request));
357         request.softc = adp;
358         request.blockaddr = blkno;
359         request.bytecount = PAGE_SIZE * dumppages;
360         request.data = va;
361         callout_init(&request.callout);
362
363         while (request.bytecount > 0) {
364             ad_transfer(&request);
365             if (request.flags & ADR_F_ERROR)
366                 return EIO;
367             request.donecount += request.currentsize;
368             request.bytecount -= request.currentsize;
369             DELAY(20);
370         }
371
372         if (dumpstatus(addr, (off_t)count * DEV_BSIZE) < 0)
373             return EINTR;
374
375         blkno += blkcnt * dumppages;
376         count -= blkcnt * dumppages;
377         addr += PAGE_SIZE * dumppages;
378     }
379
380     if (ata_wait(adp->device, ATA_S_READY | ATA_S_DSC) < 0)
381         ata_prtdev(adp->device, "timeout waiting for final ready\n");
382     return 0;
383 }
384
385 /*
386  * Critical section is held when this function is called
387  * by ata_start().
388  */
389 void
390 ad_start(struct ata_device *atadev)
391 {
392     struct ad_softc *adp = atadev->driver;
393     struct buf *bp = bufq_first(&adp->queue);
394     struct ad_request *request;
395     int tag = 0;
396
397     if (!bp)
398         return;
399
400     /* if tagged queueing enabled get next free tag */
401     if (adp->flags & AD_F_TAG_ENABLED) {
402         while (tag <= adp->num_tags && adp->tags[tag])
403             tag++;
404         if (tag > adp->num_tags )
405             return;
406     }
407
408     /*
409      * Allocate a request.  The allocation can only fail if the pipeline
410      * is full, in which case the request will be picked up later when
411      * ad_start() is called after another request completes.
412      */
413     request = mpipe_alloc_nowait(&atadev->channel->req_mpipe);
414     if (request == NULL) {
415         ata_prtdev(atadev, "pipeline full allocating request in ad_start\n");
416         return;
417     }
418
419     /* setup request */
420     request->softc = adp;
421     request->bp = bp;
422     request->blockaddr = bp->b_pblkno;
423     request->bytecount = bp->b_bcount;
424     request->data = bp->b_data;
425     request->tag = tag;
426     callout_init(&request->callout);
427     if (bp->b_flags & B_READ) 
428         request->flags |= ADR_F_READ;
429     if (adp->device->mode >= ATA_DMA) {
430         if (ata_dmaalloc(atadev, M_NOWAIT) != 0) {
431             mpipe_free(&atadev->channel->req_mpipe, request);
432             ata_prtdev(atadev, "pipeline full allocated dmabuf in ad_start\n");
433             /* do not revert to PIO, wait for ad_start after I/O completion */
434             return;
435         }
436     }
437
438     /* insert in tag array */
439     adp->tags[tag] = request;
440
441     /* remove from drive queue */
442     bufq_remove(&adp->queue, bp); 
443
444     /* link onto controller queue */
445     TAILQ_INSERT_TAIL(&atadev->channel->ata_queue, request, chain);
446 }
447
448 void
449 ad_requeue(struct ata_channel *chan, struct ad_request *req)
450 {
451         if (req->donecount) {
452                 ata_printf(chan, -1,
453                         "WARNING: resetting donecount %u for retry\n",
454                          req->donecount);
455                 req->bytecount += req->donecount;
456                 req->donecount = 0;
457         }
458         TAILQ_INSERT_HEAD(&chan->ata_queue, req, chain);
459 }
460
461 int
462 ad_transfer(struct ad_request *request)
463 {
464     struct ad_softc *adp;
465     u_int64_t lba;
466     u_int32_t count, max_count;
467     u_int8_t cmd;
468     int flags = ATA_IMMEDIATE;
469
470     /* get request params */
471     adp = request->softc;
472
473     /* calculate transfer details */
474     lba = request->blockaddr + (request->donecount / DEV_BSIZE);
475    
476     if (request->donecount == 0) {
477
478         /* start timeout for this transfer */
479         if (dumping) {
480                 callout_stop(&request->callout);
481         } else {
482                 callout_reset(&request->callout, 10 * hz, 
483                                 (void *)ad_timeout, request);
484         }
485
486         /* setup transfer parameters */
487         count = howmany(request->bytecount, DEV_BSIZE);
488         max_count = adp->device->param->support.address48 ? 65536 : 256;
489         if (count > max_count) {
490             ata_prtdev(adp->device,
491                        "count %d size transfers not supported\n", count);
492             count = max_count;
493         }
494
495         if (adp->flags & AD_F_CHS_USED) {
496             int sector = (lba % adp->sectors) + 1;
497             int cylinder = lba / (adp->sectors * adp->heads);
498             int head = (lba % (adp->sectors * adp->heads)) / adp->sectors;
499
500             lba = (sector&0xff) | ((cylinder&0xffff)<<8) | ((head&0xf)<<24);
501             adp->device->flags |= ATA_D_USE_CHS;
502         }
503
504         /* setup first transfer length */
505         request->currentsize = min(request->bytecount, adp->transfersize);
506
507         devstat_start_transaction(&adp->stats);
508
509         /* does this drive & transfer work with DMA ? */
510         request->flags &= ~ADR_F_DMA_USED;
511         if (adp->device->mode >= ATA_DMA &&
512             !ata_dmasetup(adp->device, request->data, request->bytecount)) {
513             request->flags |= ADR_F_DMA_USED;
514             request->currentsize = request->bytecount;
515
516             /* do we have tags enabled ? */
517             if (adp->flags & AD_F_TAG_ENABLED) {
518                 cmd = (request->flags & ADR_F_READ) ?
519                     ATA_C_READ_DMA_QUEUED : ATA_C_WRITE_DMA_QUEUED;
520
521                 if (ata_command(adp->device, cmd, lba,
522                                 request->tag << 3, count, flags)) {
523                     ata_prtdev(adp->device, "error executing command");
524                     goto transfer_failed;
525                 }
526                 if (ata_wait(adp->device, ATA_S_READY)) {
527                     ata_prtdev(adp->device, "timeout waiting for READY\n");
528                     goto transfer_failed;
529                 }
530                 adp->outstanding++;
531
532                 /* if ATA bus RELEASE check for SERVICE */
533                 if (adp->flags & AD_F_TAG_ENABLED &&
534                     ATA_INB(adp->device->channel->r_io, ATA_IREASON) &
535                     ATA_I_RELEASE)
536                     return ad_service(adp, 1);
537             }
538             else {
539                 cmd = (request->flags & ADR_F_READ) ?
540                     ATA_C_READ_DMA : ATA_C_WRITE_DMA;
541
542                 if (ata_command(adp->device, cmd, lba, count, 0, flags)) {
543                     ata_prtdev(adp->device, "error executing command");
544                     goto transfer_failed;
545                 }
546 #if 0
547                 /*
548                  * wait for data transfer phase
549                  *
550                  * well this should be here acording to specs, but older
551                  * promise controllers doesn't like it, they lockup!
552                  */
553                 if (ata_wait(adp->device, ATA_S_READY | ATA_S_DRQ)) {
554                     ata_prtdev(adp->device, "timeout waiting for data phase\n");
555                     goto transfer_failed;
556                 }
557 #endif
558             }
559
560             /* start transfer, return and wait for interrupt */
561             ata_dmastart(adp->device, request->data, request->bytecount,
562                         request->flags & ADR_F_READ);
563             return ATA_OP_CONTINUES;
564         }
565
566         /* does this drive support multi sector transfers ? */
567         if (request->currentsize > DEV_BSIZE)
568             cmd = request->flags&ADR_F_READ ? ATA_C_READ_MUL : ATA_C_WRITE_MUL;
569
570         /* just plain old single sector transfer */
571         else
572             cmd = request->flags&ADR_F_READ ? ATA_C_READ : ATA_C_WRITE;
573
574         if (ata_command(adp->device, cmd, lba, count, 0, flags)){
575             ata_prtdev(adp->device, "error executing command");
576             goto transfer_failed;
577         }
578     }
579    
580     /* calculate this transfer length */
581     request->currentsize = min(request->bytecount, adp->transfersize);
582
583     /* if this is a PIO read operation, return and wait for interrupt */
584     if (request->flags & ADR_F_READ)
585         return ATA_OP_CONTINUES;
586
587     /* ready to write PIO data ? */
588     if (ata_wait(adp->device, (ATA_S_READY | ATA_S_DSC | ATA_S_DRQ)) < 0) {
589         ata_prtdev(adp->device, "timeout waiting for DRQ");
590         goto transfer_failed;
591     }
592
593     /* output the data */
594     if (adp->device->channel->flags & ATA_USE_16BIT)
595         ATA_OUTSW(adp->device->channel->r_io, ATA_DATA,
596                   (void *)((uintptr_t)request->data + request->donecount),
597                   request->currentsize / sizeof(int16_t));
598     else
599         ATA_OUTSL(adp->device->channel->r_io, ATA_DATA,
600                   (void *)((uintptr_t)request->data + request->donecount),
601                   request->currentsize / sizeof(int32_t));
602     return ATA_OP_CONTINUES;
603
604 transfer_failed:
605     callout_stop(&request->callout);
606     ad_invalidatequeue(adp, request);
607     printf(" - resetting\n");
608
609     /* if retries still permit, reinject this request */
610     if (request->retries++ < AD_MAX_RETRIES)
611         ad_requeue(adp->device->channel, request);
612     else {
613         /* retries all used up, return error */
614         request->bp->b_error = EIO;
615         request->bp->b_flags |= B_ERROR;
616         request->bp->b_resid = request->bytecount;
617         devstat_end_transaction_buf(&adp->stats, request->bp);
618         biodone(request->bp);
619         ad_free(request);
620     }
621     ata_reinit(adp->device->channel);
622     return ATA_OP_CONTINUES;
623 }
624
625 int
626 ad_interrupt(struct ad_request *request)
627 {
628     struct ad_softc *adp = request->softc;
629     int dma_stat = 0;
630
631     /* finish DMA transfer */
632     if (request->flags & ADR_F_DMA_USED)
633         dma_stat = ata_dmadone(adp->device);
634
635     /* do we have a corrected soft error ? */
636     if (adp->device->channel->status & ATA_S_CORR)
637         diskerr(request->bp, request->bp->b_dev,
638                 "soft error (ECC corrected)", LOG_PRINTF,
639                 request->blockaddr + (request->donecount / DEV_BSIZE),
640                 &adp->disk.d_label);
641
642     /* did any real errors happen ? */
643     if ((adp->device->channel->status & ATA_S_ERROR) ||
644         (request->flags & ADR_F_DMA_USED && dma_stat & ATA_BMSTAT_ERROR)) {
645         adp->device->channel->error =
646             ATA_INB(adp->device->channel->r_io, ATA_ERROR);
647         diskerr(request->bp, request->bp->b_dev,
648                 (adp->device->channel->error & ATA_E_ICRC) ?
649                 "UDMA ICRC error" : "hard error", LOG_PRINTF,
650                 request->blockaddr + (request->donecount / DEV_BSIZE),
651                 &adp->disk.d_label);
652
653         /* if this is a UDMA CRC error, reinject request */
654         if (request->flags & ADR_F_DMA_USED &&
655             adp->device->channel->error & ATA_E_ICRC) {
656             callout_stop(&request->callout);
657             ad_invalidatequeue(adp, request);
658
659             if (request->retries++ < AD_MAX_RETRIES)
660                 printf(" retrying\n");
661             else {
662                 ata_dmainit(adp->device, ata_pmode(adp->device->param), -1, -1);
663                 printf(" falling back to PIO mode\n");
664             }
665             ad_requeue(adp->device->channel, request);
666             return ATA_OP_FINISHED;
667         }
668
669         /* if using DMA, try once again in PIO mode */
670         if (request->flags & ADR_F_DMA_USED) {
671             callout_stop(&request->callout);
672             ad_invalidatequeue(adp, request);
673             ata_dmainit(adp->device, ata_pmode(adp->device->param), -1, -1);
674             request->flags |= ADR_F_FORCE_PIO;
675             printf(" trying PIO mode\n");
676             ad_requeue(adp->device->channel, request);
677             return ATA_OP_FINISHED;
678         }
679
680         request->flags |= ADR_F_ERROR;
681         printf(" status=%02x error=%02x\n", 
682                adp->device->channel->status, adp->device->channel->error);
683     }
684
685     /* if we arrived here with forced PIO mode, DMA doesn't work right */
686     if (request->flags & ADR_F_FORCE_PIO && !(request->flags & ADR_F_ERROR))
687         ata_prtdev(adp->device, "DMA problem fallback to PIO mode\n");
688
689     /* if this was a PIO read operation, get the data */
690     if (!(request->flags & ADR_F_DMA_USED) &&
691         (request->flags & (ADR_F_READ | ADR_F_ERROR)) == ADR_F_READ) {
692
693         /* ready to receive data? */
694         if ((adp->device->channel->status & ATA_S_READY) == 0)
695             ata_prtdev(adp->device, "read interrupt arrived early");
696
697         if (ata_wait(adp->device, (ATA_S_READY | ATA_S_DSC | ATA_S_DRQ)) != 0) {
698             ata_prtdev(adp->device, "read error detected (too) late");
699             request->flags |= ADR_F_ERROR;
700         }
701         else {
702             /* data ready, read in */
703             if (adp->device->channel->flags & ATA_USE_16BIT)
704                 ATA_INSW(adp->device->channel->r_io, ATA_DATA,
705                          (void*)((uintptr_t)request->data + request->donecount),
706                          request->currentsize / sizeof(int16_t));
707             else
708                 ATA_INSL(adp->device->channel->r_io, ATA_DATA,
709                          (void*)((uintptr_t)request->data + request->donecount),
710                          request->currentsize / sizeof(int32_t));
711         }
712     }
713
714     /* finish up transfer */
715     if (request->flags & ADR_F_ERROR) {
716         request->bp->b_error = EIO;
717         request->bp->b_flags |= B_ERROR;
718     } 
719     else {
720         request->bytecount -= request->currentsize;
721         request->donecount += request->currentsize;
722         if (request->bytecount > 0) {
723             ad_transfer(request);
724             return ATA_OP_CONTINUES;
725         }
726     }
727
728     /* disarm timeout for this transfer */
729     callout_stop(&request->callout);
730
731     request->bp->b_resid = request->bytecount;
732
733     devstat_end_transaction_buf(&adp->stats, request->bp);
734     biodone(request->bp);
735     ad_free(request);
736     adp->outstanding--;
737
738     /* check for SERVICE (tagged operations only) */
739     return ad_service(adp, 1);
740 }
741
742 int
743 ad_service(struct ad_softc *adp, int change)
744 {
745     /* do we have to check the other device on this channel ? */
746     if (adp->device->channel->flags & ATA_QUEUED && change) {
747         int device = adp->device->unit;
748
749         if (adp->device->unit == ATA_MASTER) {
750             if ((adp->device->channel->devices & ATA_ATA_SLAVE) &&
751                 (adp->device->channel->device[SLAVE].driver) &&
752                 ((struct ad_softc *) (adp->device->channel->
753                  device[SLAVE].driver))->flags & AD_F_TAG_ENABLED)
754                 device = ATA_SLAVE;
755         }
756         else {
757             if ((adp->device->channel->devices & ATA_ATA_MASTER) &&
758                 (adp->device->channel->device[MASTER].driver) &&
759                 ((struct ad_softc *) (adp->device->channel->
760                  device[MASTER].driver))->flags & AD_F_TAG_ENABLED)
761                 device = ATA_MASTER;
762         }
763         if (device != adp->device->unit &&
764             ((struct ad_softc *)
765              (adp->device->channel->
766               device[ATA_DEV(device)].driver))->outstanding > 0) {
767             ATA_OUTB(adp->device->channel->r_io, ATA_DRIVE, ATA_D_IBM | device);
768             adp = adp->device->channel->device[ATA_DEV(device)].driver;
769             DELAY(10);
770         }
771     }
772     adp->device->channel->status =
773         ATA_INB(adp->device->channel->r_altio, ATA_ALTSTAT);
774  
775     /* do we have a SERVICE request from the drive ? */
776     if (adp->flags & AD_F_TAG_ENABLED &&
777         adp->outstanding > 0 &&
778         adp->device->channel->status & ATA_S_SERVICE) {
779         struct ad_request *request;
780         int tag;
781
782         /* check for error */
783         if (adp->device->channel->status & ATA_S_ERROR) {
784             ata_prtdev(adp->device, "Oops! controller says s=0x%02x e=0x%02x\n",
785                        adp->device->channel->status,
786                        adp->device->channel->error);
787             ad_invalidatequeue(adp, NULL);
788             return ATA_OP_FINISHED;
789         }
790
791         /* issue SERVICE cmd */
792         if (ata_command(adp->device, ATA_C_SERVICE, 0, 0, 0, ATA_IMMEDIATE)) {
793             ata_prtdev(adp->device, "problem executing SERVICE cmd\n");
794             ad_invalidatequeue(adp, NULL);
795             return ATA_OP_FINISHED;
796         }
797
798         /* setup the transfer environment when ready */
799         if (ata_wait(adp->device, ATA_S_READY)) {
800             ata_prtdev(adp->device, "SERVICE timeout tag=%d s=%02x e=%02x\n",
801                        ATA_INB(adp->device->channel->r_io, ATA_COUNT) >> 3,
802                        adp->device->channel->status,
803                        adp->device->channel->error);
804             ad_invalidatequeue(adp, NULL);
805             return ATA_OP_FINISHED;
806         }
807         tag = ATA_INB(adp->device->channel->r_io, ATA_COUNT) >> 3;
808         if (!(request = adp->tags[tag])) {
809             ata_prtdev(adp->device, "no request for tag=%d\n", tag);    
810             ad_invalidatequeue(adp, NULL);
811             return ATA_OP_FINISHED;
812         }
813         ATA_FORCELOCK_CH(adp->device->channel, ATA_ACTIVE_ATA);
814         adp->device->channel->running = request;
815         request->serv++;
816
817         /* start DMA transfer when ready */
818         if (ata_wait(adp->device, ATA_S_READY | ATA_S_DRQ)) {
819             ata_prtdev(adp->device, "timeout starting DMA s=%02x e=%02x\n",
820                        adp->device->channel->status,
821                        adp->device->channel->error);
822             ad_invalidatequeue(adp, NULL);
823             return ATA_OP_FINISHED;
824         }
825         ata_dmastart(adp->device, request->data, request->bytecount,
826                     request->flags & ADR_F_READ);
827         return ATA_OP_CONTINUES;
828     }
829     return ATA_OP_FINISHED;
830 }
831
832 static void
833 ad_free(struct ad_request *request)
834 {
835     crit_enter();
836     ata_dmafree(request->softc->device);
837     request->softc->tags[request->tag] = NULL;
838     mpipe_free(&request->softc->device->channel->req_mpipe, request);
839     crit_exit();
840 }
841
842 static void
843 ad_invalidatequeue(struct ad_softc *adp, struct ad_request *request)
844 {
845     /* if tags used invalidate all other tagged transfers */
846     if (adp->flags & AD_F_TAG_ENABLED) {
847         struct ad_request *tmpreq;
848         int tag;
849
850         ata_prtdev(adp->device, "invalidating queued requests\n");
851         for (tag = 0; tag <= adp->num_tags; tag++) {
852             tmpreq = adp->tags[tag];
853             adp->tags[tag] = NULL;
854             if (tmpreq == request || tmpreq == NULL)
855                 continue;
856             callout_stop(&request->callout);
857             ad_requeue(adp->device->channel, tmpreq);
858         }
859         if (ata_command(adp->device, ATA_C_NOP,
860                         0, 0, ATA_C_F_FLUSHQUEUE, ATA_WAIT_READY))
861             ata_prtdev(adp->device, "flush queue failed\n");
862         adp->outstanding = 0;
863     }
864 }
865
866 static int
867 ad_tagsupported(struct ad_softc *adp)
868 {
869     const char *good[] = {"IBM-DPTA", "IBM-DTLA", NULL};
870     int i = 0;
871
872     switch (adp->device->channel->chiptype) {
873     case 0x4d33105a: /* Promises before TX2 doesn't work with tagged queuing */
874     case 0x4d38105a:
875     case 0x0d30105a:
876     case 0x4d30105a:  
877         return 0;
878     }
879
880     /* check that drive does DMA, has tags enabled, and is one we know works */
881     if (adp->device->mode >= ATA_DMA && adp->device->param->support.queued && 
882         adp->device->param->enabled.queued) {
883         while (good[i] != NULL) {
884             if (!strncmp(adp->device->param->model, good[i], strlen(good[i])))
885                 return 1;
886             i++;
887         }
888         /* 
889          * check IBM's new obscure way of naming drives 
890          * we want "IC" (IBM CORP) and "AT" or "AV" (ATA interface)
891          * but doesn't care about the other info (size, capacity etc)
892          */
893         if (!strncmp(adp->device->param->model, "IC", 2) &&
894             (!strncmp(adp->device->param->model + 8, "AT", 2) ||
895              !strncmp(adp->device->param->model + 8, "AV", 2)))
896                 return 1;
897     }
898     return 0;
899 }
900
901 static void
902 ad_timeout(struct ad_request *request)
903 {
904     struct ad_softc *adp = request->softc;
905
906     adp->device->channel->running = NULL;
907     ata_prtdev(adp->device, "%s command timeout tag=%d serv=%d - resetting\n",
908                (request->flags & ADR_F_READ) ? "READ" : "WRITE",
909                request->tag, request->serv);
910
911     if (request->flags & ADR_F_DMA_USED) {
912         ata_dmadone(adp->device);
913         ad_invalidatequeue(adp, request);
914         if (request->retries == AD_MAX_RETRIES) {
915             ata_dmainit(adp->device, ata_pmode(adp->device->param), -1, -1);
916             ata_prtdev(adp->device, "trying fallback to PIO mode\n");
917             request->retries = 0;
918         }
919     }
920
921     /* if retries still permit, reinject this request */
922     if (request->retries++ < AD_MAX_RETRIES) {
923         ad_requeue(adp->device->channel, request);
924     }
925     else {
926         /* retries all used up, return error */
927         request->bp->b_error = EIO;
928         request->bp->b_flags |= B_ERROR;
929         devstat_end_transaction_buf(&adp->stats, request->bp);
930         biodone(request->bp);
931         ad_free(request);
932     }
933     ata_reinit(adp->device->channel);
934 }
935
936 void
937 ad_reinit(struct ata_device *atadev)
938 {
939     struct ad_softc *adp = atadev->driver;
940
941     /* reinit disk parameters */
942     ad_invalidatequeue(atadev->driver, NULL);
943     ata_command(atadev, ATA_C_SET_MULTI, 0,
944                 adp->transfersize / DEV_BSIZE, 0, ATA_WAIT_READY);
945     if (adp->device->mode >= ATA_DMA)
946         ata_dmainit(atadev, ata_pmode(adp->device->param),
947                     ata_wmode(adp->device->param),
948                     ata_umode(adp->device->param));
949     else
950         ata_dmainit(atadev, ata_pmode(adp->device->param), -1, -1);
951 }
952
953 void
954 ad_print(struct ad_softc *adp) 
955 {
956     if (bootverbose) {
957         ata_prtdev(adp->device, "<%.40s/%.8s> ATA-%d disk at ata%d-%s\n", 
958                    adp->device->param->model, adp->device->param->revision,
959                    ad_version(adp->device->param->version_major), 
960                    device_get_unit(adp->device->channel->dev),
961                    (adp->device->unit == ATA_MASTER) ? "master" : "slave");
962
963         ata_prtdev(adp->device,
964                    "%lluMB (%llu sectors), %llu C, %u H, %u S, %u B\n",
965                    (unsigned long long)(adp->total_secs /
966                    ((1024L*1024L)/DEV_BSIZE)),
967                    (unsigned long long) adp->total_secs,
968                    (unsigned long long) (adp->total_secs /
969                     (adp->heads * adp->sectors)),
970                    adp->heads, adp->sectors, DEV_BSIZE);
971
972         ata_prtdev(adp->device, "%d secs/int, %d depth queue, %s%s\n", 
973                    adp->transfersize / DEV_BSIZE, adp->num_tags + 1,
974                    (adp->flags & AD_F_TAG_ENABLED) ? "tagged " : "",
975                    ata_mode2str(adp->device->mode));
976
977         ata_prtdev(adp->device, "piomode=%d dmamode=%d udmamode=%d cblid=%d\n",
978                    ata_pmode(adp->device->param), ata_wmode(adp->device->param),
979                    ata_umode(adp->device->param), 
980                    adp->device->param->hwres_cblid);
981
982     }
983     else
984         ata_prtdev(adp->device,"%lluMB <%.40s> [%lld/%d/%d] at ata%d-%s %s%s\n",
985                    (unsigned long long)(adp->total_secs /
986                    ((1024L * 1024L) / DEV_BSIZE)),
987                    adp->device->param->model,
988                    (unsigned long long)(adp->total_secs /
989                     (adp->heads*adp->sectors)),
990                    adp->heads, adp->sectors,
991                    device_get_unit(adp->device->channel->dev),
992                    (adp->device->unit == ATA_MASTER) ? "master" : "slave",
993                    (adp->flags & AD_F_TAG_ENABLED) ? "tagged " : "",
994                    ata_mode2str(adp->device->mode));
995 }
996
997 static int
998 ad_version(u_int16_t version)
999 {
1000     int bit;
1001
1002     if (version == 0xffff)
1003         return 0;
1004     for (bit = 15; bit >= 0; bit--)
1005         if (version & (1<<bit))
1006             return bit;
1007     return 0;
1008 }