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