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