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