Initial import from FreeBSD RELENG_4:
[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  */
30
31 #include "opt_ata.h"
32 #include <sys/param.h>
33 #include <sys/systm.h>
34 #include <sys/ata.h>
35 #include <sys/kernel.h>
36 #include <sys/malloc.h>
37 #include <sys/buf.h>
38 #include <sys/bus.h>
39 #include <sys/conf.h>
40 #include <sys/disk.h>
41 #include <sys/devicestat.h>
42 #include <sys/cons.h>
43 #include <sys/sysctl.h>
44 #include <sys/syslog.h>
45 #include <vm/vm.h>
46 #include <vm/pmap.h>
47 #include <machine/md_var.h>
48 #include <machine/bus.h>
49 #include <machine/clock.h>
50 #include <sys/rman.h>
51 #include <dev/ata/ata-all.h>
52 #include <dev/ata/ata-disk.h>
53 #include <dev/ata/ata-raid.h>
54
55 /* device structures */
56 static d_open_t         adopen;
57 static d_close_t        adclose;
58 static d_strategy_t     adstrategy;
59 static d_dump_t         addump;
60 static struct cdevsw ad_cdevsw = {
61         /* open */      adopen,
62         /* close */     adclose,
63         /* read */      physread,
64         /* write */     physwrite,
65         /* ioctl */     noioctl,
66         /* poll */      nopoll,
67         /* mmap */      nommap,
68         /* strategy */  adstrategy,
69         /* name */      "ad",
70         /* maj */       116,
71         /* dump */      addump,
72         /* psize */     nopsize,
73         /* flags */     D_DISK,
74         /* bmaj */      30
75 };
76 static struct cdevsw addisk_cdevsw;
77
78 /* prototypes */
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)
109 {
110     struct ad_softc *adp;
111     dev_t dev;
112
113     if (!(adp = malloc(sizeof(struct ad_softc), M_AD, M_NOWAIT | M_ZERO))) {
114         ata_prtdev(atadev, "failed to allocate driver storage\n");
115         return;
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     bufq_init(&adp->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     ATA_SLEEPLOCK_CH(atadev->channel, ATA_CONTROL);
145     /* use multiple sectors/interrupt if device supports it */
146     adp->transfersize = DEV_BSIZE;
147     if (ad_version(atadev->param->version_major)) {
148         int secsperint = max(1, min(atadev->param->sectors_intr, 16));
149
150         if (!ata_command(atadev, ATA_C_SET_MULTI, 0, secsperint,
151                          0, ATA_WAIT_INTR) && !ata_wait(atadev, 0))
152         adp->transfersize *= secsperint;
153     }
154
155     /* enable read caching if not default on device */
156     if (ata_command(atadev, ATA_C_SETFEATURES,
157                     0, 0, ATA_C_F_ENAB_RCACHE, ATA_WAIT_INTR))
158         ata_prtdev(atadev, "enabling readahead cache failed\n");
159
160     /* enable write caching if allowed and not default on device */
161     if (ata_wc || (ata_tags && ad_tagsupported(adp))) {
162         if (ata_command(atadev, ATA_C_SETFEATURES,
163                         0, 0, ATA_C_F_ENAB_WCACHE, ATA_WAIT_INTR))
164             ata_prtdev(atadev, "enabling write cache failed\n");
165     }
166     else {
167         if (ata_command(atadev, ATA_C_SETFEATURES,
168                         0, 0, ATA_C_F_DIS_WCACHE, ATA_WAIT_INTR))
169             ata_prtdev(atadev, "disabling write cache failed\n");
170     }
171
172     /* use DMA if allowed and if drive/controller supports it */
173     if (ata_dma)
174         ata_dmainit(atadev->channel, atadev->unit, ata_pmode(atadev->param), 
175                     ata_wmode(atadev->param), ata_umode(atadev->param));
176     else
177         ata_dmainit(atadev->channel, atadev->unit,
178                     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_cdevsw, &addisk_cdevsw);
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 buf *bp;
234
235     atadev->flags |= ATA_D_DETACHING;
236     ata_prtdev(atadev, "removed from configuration\n");
237     ad_invalidatequeue(adp, NULL);
238     TAILQ_FOREACH(request, &atadev->channel->ata_queue, chain) {
239         if (request->softc != adp)
240             continue;
241         TAILQ_REMOVE(&atadev->channel->ata_queue, request, chain);
242         request->bp->b_error = ENXIO;
243         request->bp->b_flags |= B_ERROR;
244         biodone(request->bp);
245         ad_free(request);
246     }
247     while ((bp = bufq_first(&adp->queue))) {
248         bufq_remove(&adp->queue, bp); 
249         bp->b_error = ENXIO;
250         bp->b_flags |= B_ERROR;
251         biodone(bp);
252     }
253     disk_invalidate(&adp->disk);
254     disk_destroy(adp->dev);
255     devstat_remove_entry(&adp->stats);
256     if (flush) {
257         if (ata_command(atadev, ATA_C_FLUSHCACHE, 0, 0, 0, ATA_WAIT_READY))
258             ata_prtdev(atadev, "flushing cache on detach failed\n");
259     }
260     if (adp->flags & AD_F_RAID_SUBDISK)
261         ata_raiddisk_detach(adp);
262     ata_free_name(atadev);
263     ata_free_lun(&adp_lun_map, adp->lun);
264     atadev->driver = NULL;
265     atadev->flags = 0;
266     free(adp, M_AD);
267 }
268
269 static int
270 adopen(dev_t dev, int flags, int fmt, struct proc *p)
271 {
272     struct ad_softc *adp = dev->si_drv1;
273
274     if (adp->flags & AD_F_RAID_SUBDISK)
275         return EBUSY;
276     return 0;
277 }
278
279 static int
280 adclose(dev_t dev, int flags, int fmt, struct proc *p)
281 {
282     struct ad_softc *adp = dev->si_drv1;
283
284     ATA_SLEEPLOCK_CH(adp->device->channel, ATA_CONTROL);
285     if (ata_command(adp->device, ATA_C_FLUSHCACHE, 0, 0, 0, ATA_WAIT_READY))
286         ata_prtdev(adp->device, "flushing cache on close failed\n");
287     ATA_UNLOCK_CH(adp->device->channel);
288     return 0;
289 }
290
291 static void 
292 adstrategy(struct buf *bp)
293 {
294     struct ad_softc *adp = bp->b_dev->si_drv1;
295     int s;
296
297     if (adp->device->flags & ATA_D_DETACHING) {
298         bp->b_error = ENXIO;
299         bp->b_flags |= B_ERROR;
300         biodone(bp);
301         return;
302     }
303     s = splbio();
304     bufqdisksort(&adp->queue, bp);
305     splx(s);
306     ata_start(adp->device->channel);
307 }
308
309 int
310 addump(dev_t dev)
311 {
312     struct ad_softc *adp = dev->si_drv1;
313     struct ad_request request;
314     u_int count, blkno, secsize;
315     vm_offset_t addr = 0;
316     long blkcnt;
317     int dumppages = MAXDUMPPGS;
318     int error;
319     int i;
320
321     if ((error = disk_dumpcheck(dev, &count, &blkno, &secsize)))
322         return error;
323         
324     if (!adp)
325         return ENXIO;
326
327     /* force PIO mode for dumps */
328     adp->device->mode = ATA_PIO;
329     ata_reinit(adp->device->channel);
330
331     blkcnt = howmany(PAGE_SIZE, secsize);
332
333     while (count > 0) {
334         caddr_t va = NULL;
335         DELAY(1000);
336
337         if ((count / blkcnt) < dumppages)
338             dumppages = count / blkcnt;
339
340         for (i = 0; i < dumppages; ++i) {
341             vm_offset_t a = addr + (i * PAGE_SIZE);
342             if (is_physical_memory(a))
343                 va = pmap_kenter_temporary(trunc_page(a), i);
344             else
345                 va = pmap_kenter_temporary(trunc_page(0), i);
346         }
347
348         bzero(&request, sizeof(struct ad_request));
349         request.softc = adp;
350         request.blockaddr = blkno;
351         request.bytecount = PAGE_SIZE * dumppages;
352         request.data = va;
353
354         while (request.bytecount > 0) {
355             ad_transfer(&request);
356             if (request.flags & ADR_F_ERROR)
357                 return EIO;
358             request.donecount += request.currentsize;
359             request.bytecount -= request.currentsize;
360             DELAY(20);
361         }
362
363         if (dumpstatus(addr, (off_t)count * DEV_BSIZE) < 0)
364             return EINTR;
365
366         blkno += blkcnt * dumppages;
367         count -= blkcnt * dumppages;
368         addr += PAGE_SIZE * dumppages;
369     }
370
371     if (ata_wait(adp->device, ATA_S_READY | ATA_S_DSC) < 0)
372         ata_prtdev(adp->device, "timeout waiting for final ready\n");
373     return 0;
374 }
375
376 void
377 ad_start(struct ata_device *atadev)
378 {
379     struct ad_softc *adp = atadev->driver;
380     struct buf *bp = bufq_first(&adp->queue);
381     struct ad_request *request;
382     int tag = 0;
383
384     if (!bp)
385         return;
386
387     /* if tagged queueing enabled get next free tag */
388     if (adp->flags & AD_F_TAG_ENABLED) {
389         while (tag <= adp->num_tags && adp->tags[tag])
390             tag++;
391         if (tag > adp->num_tags )
392             return;
393     }
394
395     if (!(request = malloc(sizeof(struct ad_request), M_AD, M_NOWAIT|M_ZERO))) {
396         ata_prtdev(atadev, "out of memory in start\n");
397         return;
398     }
399
400     /* setup request */
401     request->softc = adp;
402     request->bp = bp;
403     request->blockaddr = bp->b_pblkno;
404     request->bytecount = bp->b_bcount;
405     request->data = bp->b_data;
406     request->tag = tag;
407     if (bp->b_flags & B_READ) 
408         request->flags |= ADR_F_READ;
409     if (adp->device->mode >= ATA_DMA) {
410         if (!(request->dmatab = ata_dmaalloc(atadev->channel, atadev->unit)))
411             adp->device->mode = ATA_PIO;
412     }
413
414     /* insert in tag array */
415     adp->tags[tag] = request;
416
417     /* remove from drive queue */
418     bufq_remove(&adp->queue, bp); 
419
420     /* link onto controller queue */
421     TAILQ_INSERT_TAIL(&atadev->channel->ata_queue, request, chain);
422 }
423
424 int
425 ad_transfer(struct ad_request *request)
426 {
427     struct ad_softc *adp;
428     u_int64_t lba;
429     u_int32_t count, max_count;
430     u_int8_t cmd;
431     int flags = ATA_IMMEDIATE;
432
433     /* get request params */
434     adp = request->softc;
435
436     /* calculate transfer details */
437     lba = request->blockaddr + (request->donecount / DEV_BSIZE);
438    
439     if (request->donecount == 0) {
440
441         /* start timeout for this transfer */
442         if (dumping)
443             request->timeout_handle.callout = NULL;
444         else
445             request->timeout_handle = 
446                 timeout((timeout_t*)ad_timeout, request, 10 * hz);
447
448         /* setup transfer parameters */
449         count = howmany(request->bytecount, DEV_BSIZE);
450         max_count = adp->device->param->support.address48 ? 65536 : 256;
451         if (count > max_count) {
452             ata_prtdev(adp->device,
453                        "count %d size transfers not supported\n", count);
454             count = max_count;
455         }
456
457         if (adp->flags & AD_F_CHS_USED) {
458             int sector = (lba % adp->sectors) + 1;
459             int cylinder = lba / (adp->sectors * adp->heads);
460             int head = (lba % (adp->sectors * adp->heads)) / adp->sectors;
461
462             lba = (sector&0xff) | ((cylinder&0xffff)<<8) | ((head&0xf)<<24);
463             adp->device->flags |= ATA_D_USE_CHS;
464         }
465
466         /* setup first transfer length */
467         request->currentsize = min(request->bytecount, adp->transfersize);
468
469         devstat_start_transaction(&adp->stats);
470
471         /* does this drive & transfer work with DMA ? */
472         request->flags &= ~ADR_F_DMA_USED;
473         if (adp->device->mode >= ATA_DMA &&
474             !ata_dmasetup(adp->device->channel, adp->device->unit,
475                           request->dmatab, request->data, request->bytecount)) {
476             request->flags |= ADR_F_DMA_USED;
477             request->currentsize = request->bytecount;
478
479             /* do we have tags enabled ? */
480             if (adp->flags & AD_F_TAG_ENABLED) {
481                 cmd = (request->flags & ADR_F_READ) ?
482                     ATA_C_READ_DMA_QUEUED : ATA_C_WRITE_DMA_QUEUED;
483
484                 if (ata_command(adp->device, cmd, lba,
485                                 request->tag << 3, count, flags)) {
486                     ata_prtdev(adp->device, "error executing command");
487                     goto transfer_failed;
488                 }
489                 if (ata_wait(adp->device, ATA_S_READY)) {
490                     ata_prtdev(adp->device, "timeout waiting for READY\n");
491                     goto transfer_failed;
492                 }
493                 adp->outstanding++;
494
495                 /* if ATA bus RELEASE check for SERVICE */
496                 if (adp->flags & AD_F_TAG_ENABLED &&
497                     ATA_INB(adp->device->channel->r_io, ATA_IREASON) &
498                     ATA_I_RELEASE)
499                     return ad_service(adp, 1);
500             }
501             else {
502                 cmd = (request->flags & ADR_F_READ) ?
503                     ATA_C_READ_DMA : ATA_C_WRITE_DMA;
504
505                 if (ata_command(adp->device, cmd, lba, count, 0, flags)) {
506                     ata_prtdev(adp->device, "error executing command");
507                     goto transfer_failed;
508                 }
509 #if 0
510                 /*
511                  * wait for data transfer phase
512                  *
513                  * well this should be here acording to specs, but older
514                  * promise controllers doesn't like it, they lockup!
515                  */
516                 if (ata_wait(adp->device, ATA_S_READY | ATA_S_DRQ)) {
517                     ata_prtdev(adp->device, "timeout waiting for data phase\n");
518                     goto transfer_failed;
519                 }
520 #endif
521             }
522
523             /* start transfer, return and wait for interrupt */
524             ata_dmastart(adp->device->channel, adp->device->unit,
525                          request->dmatab, request->flags & ADR_F_READ);
526             return ATA_OP_CONTINUES;
527         }
528
529         /* does this drive support multi sector transfers ? */
530         if (request->currentsize > DEV_BSIZE)
531             cmd = request->flags&ADR_F_READ ? ATA_C_READ_MUL : ATA_C_WRITE_MUL;
532
533         /* just plain old single sector transfer */
534         else
535             cmd = request->flags&ADR_F_READ ? ATA_C_READ : ATA_C_WRITE;
536
537         if (ata_command(adp->device, cmd, lba, count, 0, flags)){
538             ata_prtdev(adp->device, "error executing command");
539             goto transfer_failed;
540         }
541     }
542    
543     /* calculate this transfer length */
544     request->currentsize = min(request->bytecount, adp->transfersize);
545
546     /* if this is a PIO read operation, return and wait for interrupt */
547     if (request->flags & ADR_F_READ)
548         return ATA_OP_CONTINUES;
549
550     /* ready to write PIO data ? */
551     if (ata_wait(adp->device, (ATA_S_READY | ATA_S_DSC | ATA_S_DRQ)) < 0) {
552         ata_prtdev(adp->device, "timeout waiting for DRQ");
553         goto transfer_failed;
554     }
555
556     /* output the data */
557     if (adp->device->channel->flags & ATA_USE_16BIT)
558         ATA_OUTSW(adp->device->channel->r_io, ATA_DATA,
559                   (void *)((uintptr_t)request->data + request->donecount),
560                   request->currentsize / sizeof(int16_t));
561     else
562         ATA_OUTSL(adp->device->channel->r_io, ATA_DATA,
563                   (void *)((uintptr_t)request->data + request->donecount),
564                   request->currentsize / sizeof(int32_t));
565     return ATA_OP_CONTINUES;
566
567 transfer_failed:
568     untimeout((timeout_t *)ad_timeout, request, request->timeout_handle);
569     ad_invalidatequeue(adp, request);
570     printf(" - resetting\n");
571
572     /* if retries still permit, reinject this request */
573     if (request->retries++ < AD_MAX_RETRIES)
574         TAILQ_INSERT_HEAD(&adp->device->channel->ata_queue, request, chain);
575     else {
576         /* retries all used up, return error */
577         request->bp->b_error = EIO;
578         request->bp->b_flags |= B_ERROR;
579         request->bp->b_resid = request->bytecount;
580         devstat_end_transaction_buf(&adp->stats, request->bp);
581         biodone(request->bp);
582         ad_free(request);
583     }
584     ata_reinit(adp->device->channel);
585     return ATA_OP_CONTINUES;
586 }
587
588 int
589 ad_interrupt(struct ad_request *request)
590 {
591     struct ad_softc *adp = request->softc;
592     int dma_stat = 0;
593
594     /* finish DMA transfer */
595     if (request->flags & ADR_F_DMA_USED)
596         dma_stat = ata_dmadone(adp->device->channel);
597
598     /* do we have a corrected soft error ? */
599     if (adp->device->channel->status & ATA_S_CORR)
600         diskerr(request->bp, "soft error (ECC corrected)", LOG_PRINTF,
601                 request->blockaddr + (request->donecount / DEV_BSIZE),
602                 &adp->disk.d_label);
603
604     /* did any real errors happen ? */
605     if ((adp->device->channel->status & ATA_S_ERROR) ||
606         (request->flags & ADR_F_DMA_USED && dma_stat & ATA_BMSTAT_ERROR)) {
607         adp->device->channel->error =
608             ATA_INB(adp->device->channel->r_io, ATA_ERROR);
609         diskerr(request->bp, (adp->device->channel->error & ATA_E_ICRC) ?
610                 "UDMA ICRC error" : "hard error", LOG_PRINTF,
611                 request->blockaddr + (request->donecount / DEV_BSIZE),
612                 &adp->disk.d_label);
613
614         /* if this is a UDMA CRC error, reinject request */
615         if (request->flags & ADR_F_DMA_USED &&
616             adp->device->channel->error & ATA_E_ICRC) {
617             untimeout((timeout_t *)ad_timeout, request,request->timeout_handle);
618             ad_invalidatequeue(adp, request);
619
620             if (request->retries++ < AD_MAX_RETRIES)
621                 printf(" retrying\n");
622             else {
623                 ata_dmainit(adp->device->channel, adp->device->unit, 
624                             ata_pmode(adp->device->param), -1, -1);
625                 printf(" falling back to PIO mode\n");
626             }
627             TAILQ_INSERT_HEAD(&adp->device->channel->ata_queue, request, chain);
628             return ATA_OP_FINISHED;
629         }
630
631         /* if using DMA, try once again in PIO mode */
632         if (request->flags & ADR_F_DMA_USED) {
633             untimeout((timeout_t *)ad_timeout, request,request->timeout_handle);
634             ad_invalidatequeue(adp, request);
635             ata_dmainit(adp->device->channel, adp->device->unit,
636                         ata_pmode(adp->device->param), -1, -1);
637             request->flags |= ADR_F_FORCE_PIO;
638             printf(" trying PIO mode\n");
639             TAILQ_INSERT_HEAD(&adp->device->channel->ata_queue, request, chain);
640             return ATA_OP_FINISHED;
641         }
642
643         request->flags |= ADR_F_ERROR;
644         printf(" status=%02x error=%02x\n", 
645                adp->device->channel->status, adp->device->channel->error);
646     }
647
648     /* if we arrived here with forced PIO mode, DMA doesn't work right */
649     if (request->flags & ADR_F_FORCE_PIO && !(request->flags & ADR_F_ERROR))
650         ata_prtdev(adp->device, "DMA problem fallback to PIO mode\n");
651
652     /* if this was a PIO read operation, get the data */
653     if (!(request->flags & ADR_F_DMA_USED) &&
654         (request->flags & (ADR_F_READ | ADR_F_ERROR)) == ADR_F_READ) {
655
656         /* ready to receive data? */
657         if ((adp->device->channel->status & (ATA_S_READY|ATA_S_DSC|ATA_S_DRQ))
658             != (ATA_S_READY|ATA_S_DSC|ATA_S_DRQ))
659             ata_prtdev(adp->device, "read interrupt arrived early");
660
661         if (ata_wait(adp->device, (ATA_S_READY | ATA_S_DSC | ATA_S_DRQ)) != 0) {
662             ata_prtdev(adp->device, "read error detected (too) late");
663             request->flags |= ADR_F_ERROR;
664         }
665         else {
666             /* data ready, read in */
667             if (adp->device->channel->flags & ATA_USE_16BIT)
668                 ATA_INSW(adp->device->channel->r_io, ATA_DATA,
669                          (void*)((uintptr_t)request->data + request->donecount),
670                          request->currentsize / sizeof(int16_t));
671             else
672                 ATA_INSL(adp->device->channel->r_io, ATA_DATA,
673                          (void*)((uintptr_t)request->data + request->donecount),
674                          request->currentsize / sizeof(int32_t));
675         }
676     }
677
678     /* finish up transfer */
679     if (request->flags & ADR_F_ERROR) {
680         request->bp->b_error = EIO;
681         request->bp->b_flags |= B_ERROR;
682     } 
683     else {
684         request->bytecount -= request->currentsize;
685         request->donecount += request->currentsize;
686         if (request->bytecount > 0) {
687             ad_transfer(request);
688             return ATA_OP_CONTINUES;
689         }
690     }
691
692     /* disarm timeout for this transfer */
693     untimeout((timeout_t *)ad_timeout, request, request->timeout_handle);
694
695     request->bp->b_resid = request->bytecount;
696
697     devstat_end_transaction_buf(&adp->stats, request->bp);
698     biodone(request->bp);
699     ad_free(request);
700     adp->outstanding--;
701
702     /* check for SERVICE (tagged operations only) */
703     return ad_service(adp, 1);
704 }
705
706 int
707 ad_service(struct ad_softc *adp, int change)
708 {
709     /* do we have to check the other device on this channel ? */
710     if (adp->device->channel->flags & ATA_QUEUED && change) {
711         int device = adp->device->unit;
712
713         if (adp->device->unit == ATA_MASTER) {
714             if ((adp->device->channel->devices & ATA_ATA_SLAVE) &&
715                 (adp->device->channel->device[SLAVE].driver) &&
716                 ((struct ad_softc *) (adp->device->channel->
717                  device[SLAVE].driver))->flags & AD_F_TAG_ENABLED)
718                 device = ATA_SLAVE;
719         }
720         else {
721             if ((adp->device->channel->devices & ATA_ATA_MASTER) &&
722                 (adp->device->channel->device[MASTER].driver) &&
723                 ((struct ad_softc *) (adp->device->channel->
724                  device[MASTER].driver))->flags & AD_F_TAG_ENABLED)
725                 device = ATA_MASTER;
726         }
727         if (device != adp->device->unit &&
728             ((struct ad_softc *)
729              (adp->device->channel->
730               device[ATA_DEV(device)].driver))->outstanding > 0) {
731             ATA_OUTB(adp->device->channel->r_io, ATA_DRIVE, ATA_D_IBM | device);
732             adp = adp->device->channel->device[ATA_DEV(device)].driver;
733             DELAY(1);
734         }
735     }
736     adp->device->channel->status =
737         ATA_INB(adp->device->channel->r_altio, ATA_ALTSTAT);
738  
739     /* do we have a SERVICE request from the drive ? */
740     if (adp->flags & AD_F_TAG_ENABLED &&
741         adp->outstanding > 0 &&
742         adp->device->channel->status & ATA_S_SERVICE) {
743         struct ad_request *request;
744         int tag;
745
746         /* check for error */
747         if (adp->device->channel->status & ATA_S_ERROR) {
748             ata_prtdev(adp->device, "Oops! controller says s=0x%02x e=0x%02x\n",
749                        adp->device->channel->status,
750                        adp->device->channel->error);
751             ad_invalidatequeue(adp, NULL);
752             return ATA_OP_FINISHED;
753         }
754
755         /* issue SERVICE cmd */
756         if (ata_command(adp->device, ATA_C_SERVICE, 0, 0, 0, ATA_IMMEDIATE)) {
757             ata_prtdev(adp->device, "problem executing SERVICE cmd\n");
758             ad_invalidatequeue(adp, NULL);
759             return ATA_OP_FINISHED;
760         }
761
762         /* setup the transfer environment when ready */
763         if (ata_wait(adp->device, ATA_S_READY)) {
764             ata_prtdev(adp->device, "SERVICE timeout tag=%d s=%02x e=%02x\n",
765                        ATA_INB(adp->device->channel->r_io, ATA_COUNT) >> 3,
766                        adp->device->channel->status,
767                        adp->device->channel->error);
768             ad_invalidatequeue(adp, NULL);
769             return ATA_OP_FINISHED;
770         }
771         tag = ATA_INB(adp->device->channel->r_io, ATA_COUNT) >> 3;
772         if (!(request = adp->tags[tag])) {
773             ata_prtdev(adp->device, "no request for tag=%d\n", tag);    
774             ad_invalidatequeue(adp, NULL);
775             return ATA_OP_FINISHED;
776         }
777         ATA_FORCELOCK_CH(adp->device->channel, ATA_ACTIVE_ATA);
778         adp->device->channel->running = request;
779         request->serv++;
780
781         /* start DMA transfer when ready */
782         if (ata_wait(adp->device, ATA_S_READY | ATA_S_DRQ)) {
783             ata_prtdev(adp->device, "timeout starting DMA s=%02x e=%02x\n",
784                        adp->device->channel->status,
785                        adp->device->channel->error);
786             ad_invalidatequeue(adp, NULL);
787             return ATA_OP_FINISHED;
788         }
789         ata_dmastart(adp->device->channel, adp->device->unit,
790                      request->dmatab, request->flags & ADR_F_READ);
791         return ATA_OP_CONTINUES;
792     }
793     return ATA_OP_FINISHED;
794 }
795
796 static void
797 ad_free(struct ad_request *request)
798 {
799     int s = splbio();
800
801     if (request->dmatab)
802         free(request->dmatab, M_DEVBUF);
803     request->softc->tags[request->tag] = NULL;
804     free(request, M_AD);
805     splx(s);
806 }
807
808 static void
809 ad_invalidatequeue(struct ad_softc *adp, struct ad_request *request)
810 {
811     /* if tags used invalidate all other tagged transfers */
812     if (adp->flags & AD_F_TAG_ENABLED) {
813         struct ad_request *tmpreq;
814         int tag;
815
816         ata_prtdev(adp->device, "invalidating queued requests\n");
817         for (tag = 0; tag <= adp->num_tags; tag++) {
818             tmpreq = adp->tags[tag];
819             adp->tags[tag] = NULL;
820             if (tmpreq == request || tmpreq == NULL)
821                 continue;
822             untimeout((timeout_t *)ad_timeout, tmpreq, tmpreq->timeout_handle);
823             TAILQ_INSERT_HEAD(&adp->device->channel->ata_queue, tmpreq, chain);
824         }
825         if (ata_command(adp->device, ATA_C_NOP,
826                         0, 0, ATA_C_F_FLUSHQUEUE, ATA_WAIT_READY))
827             ata_prtdev(adp->device, "flush queue failed\n");
828         adp->outstanding = 0;
829     }
830 }
831
832 static int
833 ad_tagsupported(struct ad_softc *adp)
834 {
835     const char *good[] = {"IBM-DPTA", "IBM-DTLA", NULL};
836     int i = 0;
837
838     switch (adp->device->channel->chiptype) {
839     case 0x4d33105a: /* Promises before TX2 doesn't work with tagged queuing */
840     case 0x4d38105a:
841     case 0x0d30105a:
842     case 0x4d30105a:  
843         return 0;
844     }
845
846     /* check that drive does DMA, has tags enabled, and is one we know works */
847     if (adp->device->mode >= ATA_DMA && adp->device->param->support.queued && 
848         adp->device->param->enabled.queued) {
849         while (good[i] != NULL) {
850             if (!strncmp(adp->device->param->model, good[i], strlen(good[i])))
851                 return 1;
852             i++;
853         }
854         /* 
855          * check IBM's new obscure way of naming drives 
856          * we want "IC" (IBM CORP) and "AT" or "AV" (ATA interface)
857          * but doesn't care about the other info (size, capacity etc)
858          */
859         if (!strncmp(adp->device->param->model, "IC", 2) &&
860             (!strncmp(adp->device->param->model + 8, "AT", 2) ||
861              !strncmp(adp->device->param->model + 8, "AV", 2)))
862                 return 1;
863     }
864     return 0;
865 }
866
867 static void
868 ad_timeout(struct ad_request *request)
869 {
870     struct ad_softc *adp = request->softc;
871
872     adp->device->channel->running = NULL;
873     ata_prtdev(adp->device, "%s command timeout tag=%d serv=%d - resetting\n",
874                (request->flags & ADR_F_READ) ? "READ" : "WRITE",
875                request->tag, request->serv);
876
877     if (request->flags & ADR_F_DMA_USED) {
878         ata_dmadone(adp->device->channel);
879         ad_invalidatequeue(adp, request);
880         if (request->retries == AD_MAX_RETRIES) {
881             ata_dmainit(adp->device->channel, adp->device->unit,
882                         ata_pmode(adp->device->param), -1, -1);
883             ata_prtdev(adp->device, "trying fallback to PIO mode\n");
884             request->retries = 0;
885         }
886     }
887
888     /* if retries still permit, reinject this request */
889     if (request->retries++ < AD_MAX_RETRIES) {
890         TAILQ_INSERT_HEAD(&adp->device->channel->ata_queue, request, chain);
891     }
892     else {
893         /* retries all used up, return error */
894         request->bp->b_error = EIO;
895         request->bp->b_flags |= B_ERROR;
896         devstat_end_transaction_buf(&adp->stats, request->bp);
897         biodone(request->bp);
898         ad_free(request);
899     }
900     ata_reinit(adp->device->channel);
901 }
902
903 void
904 ad_reinit(struct ata_device *atadev)
905 {
906     struct ad_softc *adp = atadev->driver;
907
908     /* reinit disk parameters */
909     ad_invalidatequeue(atadev->driver, NULL);
910     ata_command(atadev, ATA_C_SET_MULTI, 0,
911                 adp->transfersize / DEV_BSIZE, 0, ATA_WAIT_READY);
912     if (adp->device->mode >= ATA_DMA)
913         ata_dmainit(atadev->channel, atadev->unit,
914                     ata_pmode(adp->device->param),
915                     ata_wmode(adp->device->param),
916                     ata_umode(adp->device->param));
917     else
918         ata_dmainit(atadev->channel, atadev->unit,
919                     ata_pmode(adp->device->param), -1, -1);
920 }
921
922 void
923 ad_print(struct ad_softc *adp) 
924 {
925     if (bootverbose) {
926         ata_prtdev(adp->device, "<%.40s/%.8s> ATA-%d disk at ata%d-%s\n", 
927                    adp->device->param->model, adp->device->param->revision,
928                    ad_version(adp->device->param->version_major), 
929                    device_get_unit(adp->device->channel->dev),
930                    (adp->device->unit == ATA_MASTER) ? "master" : "slave");
931
932         ata_prtdev(adp->device,
933                    "%lluMB (%llu sectors), %llu C, %u H, %u S, %u B\n",
934                    (unsigned long long)(adp->total_secs /
935                    ((1024L*1024L)/DEV_BSIZE)),
936                    (unsigned long long) adp->total_secs,
937                    (unsigned long long) (adp->total_secs /
938                     (adp->heads * adp->sectors)),
939                    adp->heads, adp->sectors, DEV_BSIZE);
940
941         ata_prtdev(adp->device, "%d secs/int, %d depth queue, %s%s\n", 
942                    adp->transfersize / DEV_BSIZE, adp->num_tags + 1,
943                    (adp->flags & AD_F_TAG_ENABLED) ? "tagged " : "",
944                    ata_mode2str(adp->device->mode));
945
946         ata_prtdev(adp->device, "piomode=%d dmamode=%d udmamode=%d cblid=%d\n",
947                    ata_pmode(adp->device->param), ata_wmode(adp->device->param),
948                    ata_umode(adp->device->param), 
949                    adp->device->param->hwres_cblid);
950
951     }
952     else
953         ata_prtdev(adp->device,"%lluMB <%.40s> [%lld/%d/%d] at ata%d-%s %s%s\n",
954                    (unsigned long long)(adp->total_secs /
955                    ((1024L * 1024L) / DEV_BSIZE)),
956                    adp->device->param->model,
957                    (unsigned long long)(adp->total_secs /
958                     (adp->heads*adp->sectors)),
959                    adp->heads, adp->sectors,
960                    device_get_unit(adp->device->channel->dev),
961                    (adp->device->unit == ATA_MASTER) ? "master" : "slave",
962                    (adp->flags & AD_F_TAG_ENABLED) ? "tagged " : "",
963                    ata_mode2str(adp->device->mode));
964 }
965
966 static int
967 ad_version(u_int16_t version)
968 {
969     int bit;
970
971     if (version == 0xffff)
972         return 0;
973     for (bit = 15; bit >= 0; bit--)
974         if (version & (1<<bit))
975             return bit;
976     return 0;
977 }