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