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