]> CyberLeo.Net >> Repos - FreeBSD/stable/9.git/blob - sys/cam/ata/ata_da.c
MFC r251061:
[FreeBSD/stable/9.git] / sys / cam / ata / ata_da.c
1 /*-
2  * Copyright (c) 2009 Alexander Motin <mav@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  *
15  * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR
16  * IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
17  * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.
18  * IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT,
19  * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
20  * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
21  * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
22  * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
23  * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
24  * THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
25  */
26
27 #include <sys/cdefs.h>
28 __FBSDID("$FreeBSD$");
29
30 #include "opt_ada.h"
31 #include "opt_ata.h"
32
33 #include <sys/param.h>
34
35 #ifdef _KERNEL
36 #include <sys/systm.h>
37 #include <sys/kernel.h>
38 #include <sys/bio.h>
39 #include <sys/sysctl.h>
40 #include <sys/taskqueue.h>
41 #include <sys/lock.h>
42 #include <sys/mutex.h>
43 #include <sys/conf.h>
44 #include <sys/devicestat.h>
45 #include <sys/eventhandler.h>
46 #include <sys/malloc.h>
47 #include <sys/cons.h>
48 #include <sys/reboot.h>
49 #include <geom/geom_disk.h>
50 #endif /* _KERNEL */
51
52 #ifndef _KERNEL
53 #include <stdio.h>
54 #include <string.h>
55 #endif /* _KERNEL */
56
57 #include <cam/cam.h>
58 #include <cam/cam_ccb.h>
59 #include <cam/cam_periph.h>
60 #include <cam/cam_xpt_periph.h>
61 #include <cam/cam_sim.h>
62
63 #include <cam/ata/ata_all.h>
64
65 #include <machine/md_var.h>     /* geometry translation */
66
67 #ifdef _KERNEL
68
69 #define ATA_MAX_28BIT_LBA               268435455UL
70
71 typedef enum {
72         ADA_STATE_RAHEAD,
73         ADA_STATE_WCACHE,
74         ADA_STATE_NORMAL
75 } ada_state;
76
77 typedef enum {
78         ADA_FLAG_PACK_INVALID   = 0x0001,
79         ADA_FLAG_CAN_48BIT      = 0x0002,
80         ADA_FLAG_CAN_FLUSHCACHE = 0x0004,
81         ADA_FLAG_CAN_NCQ        = 0x0008,
82         ADA_FLAG_CAN_DMA        = 0x0010,
83         ADA_FLAG_NEED_OTAG      = 0x0020,
84         ADA_FLAG_WENT_IDLE      = 0x0040,
85         ADA_FLAG_CAN_TRIM       = 0x0080,
86         ADA_FLAG_OPEN           = 0x0100,
87         ADA_FLAG_SCTX_INIT      = 0x0200,
88         ADA_FLAG_CAN_CFA        = 0x0400,
89         ADA_FLAG_CAN_POWERMGT   = 0x0800,
90         ADA_FLAG_CAN_DMA48      = 0x1000
91 } ada_flags;
92
93 typedef enum {
94         ADA_Q_NONE              = 0x00,
95         ADA_Q_4K                = 0x01,
96 } ada_quirks;
97
98 #define ADA_Q_BIT_STRING        \
99         "\020"                  \
100         "\0014K"
101
102 typedef enum {
103         ADA_CCB_RAHEAD          = 0x01,
104         ADA_CCB_WCACHE          = 0x02,
105         ADA_CCB_BUFFER_IO       = 0x03,
106         ADA_CCB_WAITING         = 0x04,
107         ADA_CCB_DUMP            = 0x05,
108         ADA_CCB_TRIM            = 0x06,
109         ADA_CCB_TYPE_MASK       = 0x0F,
110 } ada_ccb_state;
111
112 /* Offsets into our private area for storing information */
113 #define ccb_state       ppriv_field0
114 #define ccb_bp          ppriv_ptr1
115
116 struct disk_params {
117         u_int8_t  heads;
118         u_int8_t  secs_per_track;
119         u_int32_t cylinders;
120         u_int32_t secsize;      /* Number of bytes/logical sector */
121         u_int64_t sectors;      /* Total number sectors */
122 };
123
124 #define TRIM_MAX_BLOCKS 8
125 #define TRIM_MAX_RANGES (TRIM_MAX_BLOCKS * ATA_DSM_BLK_RANGES)
126 #define TRIM_MAX_BIOS   (TRIM_MAX_RANGES * 4)
127 struct trim_request {
128         uint8_t         data[TRIM_MAX_RANGES * ATA_DSM_RANGE_SIZE];
129         struct bio      *bps[TRIM_MAX_BIOS];
130 };
131
132 struct ada_softc {
133         struct   bio_queue_head bio_queue;
134         struct   bio_queue_head trim_queue;
135         ada_state state;
136         ada_flags flags;        
137         ada_quirks quirks;
138         int      sort_io_queue;
139         int      ordered_tag_count;
140         int      outstanding_cmds;
141         int      trim_max_ranges;
142         int      trim_running;
143         int      read_ahead;
144         int      write_cache;
145 #ifdef ADA_TEST_FAILURE
146         int      force_read_error;
147         int      force_write_error;
148         int      periodic_read_error;
149         int      periodic_read_count;
150 #endif
151         struct   disk_params params;
152         struct   disk *disk;
153         struct task             sysctl_task;
154         struct sysctl_ctx_list  sysctl_ctx;
155         struct sysctl_oid       *sysctl_tree;
156         struct callout          sendordered_c;
157         struct trim_request     trim_req;
158 };
159
160 struct ada_quirk_entry {
161         struct scsi_inquiry_pattern inq_pat;
162         ada_quirks quirks;
163 };
164
165 static struct ada_quirk_entry ada_quirk_table[] =
166 {
167         {
168                 /* Hitachi Advanced Format (4k) drives */
169                 { T_DIRECT, SIP_MEDIA_FIXED, "*", "Hitachi H??????????E3*", "*" },
170                 /*quirks*/ADA_Q_4K
171         },
172         {
173                 /* Samsung Advanced Format (4k) drives */
174                 { T_DIRECT, SIP_MEDIA_FIXED, "*", "SAMSUNG HD155UI*", "*" },
175                 /*quirks*/ADA_Q_4K
176         },
177         {
178                 /* Samsung Advanced Format (4k) drives */
179                 { T_DIRECT, SIP_MEDIA_FIXED, "*", "SAMSUNG HD204UI*", "*" },
180                 /*quirks*/ADA_Q_4K
181         },
182         {
183                 /* Seagate Barracuda Green Advanced Format (4k) drives */
184                 { T_DIRECT, SIP_MEDIA_FIXED, "*", "ST????DL*", "*" },
185                 /*quirks*/ADA_Q_4K
186         },
187         {
188                 /* Seagate Barracuda Advanced Format (4k) drives */
189                 { T_DIRECT, SIP_MEDIA_FIXED, "*", "ST???DM*", "*" },
190                 /*quirks*/ADA_Q_4K
191         },
192         {
193                 /* Seagate Barracuda Advanced Format (4k) drives */
194                 { T_DIRECT, SIP_MEDIA_FIXED, "*", "ST????DM*", "*" },
195                 /*quirks*/ADA_Q_4K
196         },
197         {
198                 /* Seagate Momentus Advanced Format (4k) drives */
199                 { T_DIRECT, SIP_MEDIA_FIXED, "*", "ST9500423AS*", "*" },
200                 /*quirks*/ADA_Q_4K
201         },
202         {
203                 /* Seagate Momentus Advanced Format (4k) drives */
204                 { T_DIRECT, SIP_MEDIA_FIXED, "*", "ST9500424AS*", "*" },
205                 /*quirks*/ADA_Q_4K
206         },
207         {
208                 /* Seagate Momentus Advanced Format (4k) drives */
209                 { T_DIRECT, SIP_MEDIA_FIXED, "*", "ST9640423AS*", "*" },
210                 /*quirks*/ADA_Q_4K
211         },
212         {
213                 /* Seagate Momentus Advanced Format (4k) drives */
214                 { T_DIRECT, SIP_MEDIA_FIXED, "*", "ST9640424AS*", "*" },
215                 /*quirks*/ADA_Q_4K
216         },
217         {
218                 /* Seagate Momentus Advanced Format (4k) drives */
219                 { T_DIRECT, SIP_MEDIA_FIXED, "*", "ST9750420AS*", "*" },
220                 /*quirks*/ADA_Q_4K
221         },
222         {
223                 /* Seagate Momentus Advanced Format (4k) drives */
224                 { T_DIRECT, SIP_MEDIA_FIXED, "*", "ST9750422AS*", "*" },
225                 /*quirks*/ADA_Q_4K
226         },
227         {
228                 /* Seagate Momentus Advanced Format (4k) drives */
229                 { T_DIRECT, SIP_MEDIA_FIXED, "*", "ST9750423AS*", "*" },
230                 /*quirks*/ADA_Q_4K
231         },
232         {
233                 /* Seagate Momentus Thin Advanced Format (4k) drives */
234                 { T_DIRECT, SIP_MEDIA_FIXED, "*", "ST???LT*", "*" },
235                 /*quirks*/ADA_Q_4K
236         },
237         {
238                 /* WDC Caviar Green Advanced Format (4k) drives */
239                 { T_DIRECT, SIP_MEDIA_FIXED, "*", "WDC WD????RS*", "*" },
240                 /*quirks*/ADA_Q_4K
241         },
242         {
243                 /* WDC Caviar Green Advanced Format (4k) drives */
244                 { T_DIRECT, SIP_MEDIA_FIXED, "*", "WDC WD????RX*", "*" },
245                 /*quirks*/ADA_Q_4K
246         },
247         {
248                 /* WDC Caviar Green Advanced Format (4k) drives */
249                 { T_DIRECT, SIP_MEDIA_FIXED, "*", "WDC WD??????RS*", "*" },
250                 /*quirks*/ADA_Q_4K
251         },
252         {
253                 /* WDC Caviar Green Advanced Format (4k) drives */
254                 { T_DIRECT, SIP_MEDIA_FIXED, "*", "WDC WD??????RX*", "*" },
255                 /*quirks*/ADA_Q_4K
256         },
257         {
258                 /* WDC Scorpio Black Advanced Format (4k) drives */
259                 { T_DIRECT, SIP_MEDIA_FIXED, "*", "WDC WD???PKT*", "*" },
260                 /*quirks*/ADA_Q_4K
261         },
262         {
263                 /* WDC Scorpio Black Advanced Format (4k) drives */
264                 { T_DIRECT, SIP_MEDIA_FIXED, "*", "WDC WD?????PKT*", "*" },
265                 /*quirks*/ADA_Q_4K
266         },
267         {
268                 /* WDC Scorpio Blue Advanced Format (4k) drives */
269                 { T_DIRECT, SIP_MEDIA_FIXED, "*", "WDC WD???PVT*", "*" },
270                 /*quirks*/ADA_Q_4K
271         },
272         {
273                 /* WDC Scorpio Blue Advanced Format (4k) drives */
274                 { T_DIRECT, SIP_MEDIA_FIXED, "*", "WDC WD?????PVT*", "*" },
275                 /*quirks*/ADA_Q_4K
276         },
277         /* SSDs */
278         {
279                 /*
280                  * Corsair Force 2 SSDs
281                  * 4k optimised & trim only works in 4k requests + 4k aligned
282                  */
283                 { T_DIRECT, SIP_MEDIA_FIXED, "*", "Corsair CSSD-F*", "*" },
284                 /*quirks*/ADA_Q_4K
285         },
286         {
287                 /*
288                  * Corsair Force 3 SSDs
289                  * 4k optimised & trim only works in 4k requests + 4k aligned
290                  */
291                 { T_DIRECT, SIP_MEDIA_FIXED, "*", "Corsair Force 3*", "*" },
292                 /*quirks*/ADA_Q_4K
293         },
294         {
295                 /*
296                  * Corsair Force GT SSDs
297                  * 4k optimised & trim only works in 4k requests + 4k aligned
298                  */
299                 { T_DIRECT, SIP_MEDIA_FIXED, "*", "Corsair Force GT*", "*" },
300                 /*quirks*/ADA_Q_4K
301         },
302         {
303                 /*
304                  * Crucial M4 SSDs
305                  * 4k optimised & trim only works in 4k requests + 4k aligned
306                  */
307                 { T_DIRECT, SIP_MEDIA_FIXED, "*", "M4-CT???M4SSD2*", "*" },
308                 /*quirks*/ADA_Q_4K
309         },
310         {
311                 /*
312                  * Crucial RealSSD C300 SSDs
313                  * 4k optimised
314                  */
315                 { T_DIRECT, SIP_MEDIA_FIXED, "*", "C300-CTFDDAC???MAG*",
316                 "*" }, /*quirks*/ADA_Q_4K
317         },
318         {
319                 /*
320                  * Intel 320 Series SSDs
321                  * 4k optimised & trim only works in 4k requests + 4k aligned
322                  */
323                 { T_DIRECT, SIP_MEDIA_FIXED, "*", "INTEL SSDSA2CW*", "*" },
324                 /*quirks*/ADA_Q_4K
325         },
326         {
327                 /*
328                  * Intel 330 Series SSDs
329                  * 4k optimised & trim only works in 4k requests + 4k aligned
330                  */
331                 { T_DIRECT, SIP_MEDIA_FIXED, "*", "INTEL SSDSC2CT*", "*" },
332                 /*quirks*/ADA_Q_4K
333         },
334         {
335                 /*
336                  * Intel 510 Series SSDs
337                  * 4k optimised & trim only works in 4k requests + 4k aligned
338                  */
339                 { T_DIRECT, SIP_MEDIA_FIXED, "*", "INTEL SSDSC2MH*", "*" },
340                 /*quirks*/ADA_Q_4K
341         },
342         {
343                 /*
344                  * Intel 520 Series SSDs
345                  * 4k optimised & trim only works in 4k requests + 4k aligned
346                  */
347                 { T_DIRECT, SIP_MEDIA_FIXED, "*", "INTEL SSDSC2BW*", "*" },
348                 /*quirks*/ADA_Q_4K
349         },
350         {
351                 /*
352                  * Kingston E100 Series SSDs
353                  * 4k optimised & trim only works in 4k requests + 4k aligned
354                  */
355                 { T_DIRECT, SIP_MEDIA_FIXED, "*", "KINGSTON SE100S3*", "*" },
356                 /*quirks*/ADA_Q_4K
357         },
358         {
359                 /*
360                  * Kingston HyperX 3k SSDs
361                  * 4k optimised & trim only works in 4k requests + 4k aligned
362                  */
363                 { T_DIRECT, SIP_MEDIA_FIXED, "*", "KINGSTON SH103S3*", "*" },
364                 /*quirks*/ADA_Q_4K
365         },
366         {
367                 /*
368                  * OCZ Agility 3 SSDs
369                  * 4k optimised & trim only works in 4k requests + 4k aligned
370                  */
371                 { T_DIRECT, SIP_MEDIA_FIXED, "*", "OCZ-AGILITY3*", "*" },
372                 /*quirks*/ADA_Q_4K
373         },
374         {
375                 /*
376                  * OCZ Deneva R Series SSDs
377                  * 4k optimised & trim only works in 4k requests + 4k aligned
378                  */
379                 { T_DIRECT, SIP_MEDIA_FIXED, "*", "DENRSTE251M45*", "*" },
380                 /*quirks*/ADA_Q_4K
381         },
382         {
383                 /*
384                  * OCZ Vertex 2 SSDs (inc pro series)
385                  * 4k optimised & trim only works in 4k requests + 4k aligned
386                  */
387                 { T_DIRECT, SIP_MEDIA_FIXED, "*", "OCZ?VERTEX2*", "*" },
388                 /*quirks*/ADA_Q_4K
389         },
390         {
391                 /*
392                  * OCZ Vertex 3 SSDs
393                  * 4k optimised & trim only works in 4k requests + 4k aligned
394                  */
395                 { T_DIRECT, SIP_MEDIA_FIXED, "*", "OCZ-VERTEX3*", "*" },
396                 /*quirks*/ADA_Q_4K
397         },
398         {
399                 /*
400                  * Samsung 830 Series SSDs
401                  * 4k optimised
402                  */
403                 { T_DIRECT, SIP_MEDIA_FIXED, "*", "SAMSUNG SSD 830 Series*", "*" },
404                 /*quirks*/ADA_Q_4K
405         },
406         {
407                 /*
408                  * SuperTalent TeraDrive CT SSDs
409                  * 4k optimised & trim only works in 4k requests + 4k aligned
410                  */
411                 { T_DIRECT, SIP_MEDIA_FIXED, "*", "FTM??CT25H*", "*" },
412                 /*quirks*/ADA_Q_4K
413         },
414         {
415                 /*
416                  * XceedIOPS SATA SSDs
417                  * 4k optimised
418                  */
419                 { T_DIRECT, SIP_MEDIA_FIXED, "*", "SG9XCS2D*", "*" },
420                 /*quirks*/ADA_Q_4K
421         },
422         {
423                 /* Default */
424                 {
425                   T_ANY, SIP_MEDIA_REMOVABLE|SIP_MEDIA_FIXED,
426                   /*vendor*/"*", /*product*/"*", /*revision*/"*"
427                 },
428                 /*quirks*/0
429         },
430 };
431
432 static  disk_strategy_t adastrategy;
433 static  dumper_t        adadump;
434 static  periph_init_t   adainit;
435 static  void            adaasync(void *callback_arg, u_int32_t code,
436                                 struct cam_path *path, void *arg);
437 static  void            adasysctlinit(void *context, int pending);
438 static  periph_ctor_t   adaregister;
439 static  periph_dtor_t   adacleanup;
440 static  periph_start_t  adastart;
441 static  periph_oninv_t  adaoninvalidate;
442 static  void            adadone(struct cam_periph *periph,
443                                union ccb *done_ccb);
444 static  int             adaerror(union ccb *ccb, u_int32_t cam_flags,
445                                 u_int32_t sense_flags);
446 static void             adagetparams(struct cam_periph *periph,
447                                 struct ccb_getdev *cgd);
448 static timeout_t        adasendorderedtag;
449 static void             adashutdown(void *arg, int howto);
450 static void             adasuspend(void *arg);
451 static void             adaresume(void *arg);
452
453 #ifndef ADA_DEFAULT_LEGACY_ALIASES
454 #ifdef ATA_CAM
455 #define ADA_DEFAULT_LEGACY_ALIASES      1
456 #else
457 #define ADA_DEFAULT_LEGACY_ALIASES      0
458 #endif
459 #endif
460
461 #ifndef ADA_DEFAULT_TIMEOUT
462 #define ADA_DEFAULT_TIMEOUT 30  /* Timeout in seconds */
463 #endif
464
465 #ifndef ADA_DEFAULT_RETRY
466 #define ADA_DEFAULT_RETRY       4
467 #endif
468
469 #ifndef ADA_DEFAULT_SEND_ORDERED
470 #define ADA_DEFAULT_SEND_ORDERED        1
471 #endif
472
473 #ifndef ADA_DEFAULT_SPINDOWN_SHUTDOWN
474 #define ADA_DEFAULT_SPINDOWN_SHUTDOWN   1
475 #endif
476
477 #ifndef ADA_DEFAULT_SPINDOWN_SUSPEND
478 #define ADA_DEFAULT_SPINDOWN_SUSPEND    1
479 #endif
480
481 #ifndef ADA_DEFAULT_READ_AHEAD
482 #define ADA_DEFAULT_READ_AHEAD  1
483 #endif
484
485 #ifndef ADA_DEFAULT_WRITE_CACHE
486 #define ADA_DEFAULT_WRITE_CACHE 1
487 #endif
488
489 #define ADA_RA  (softc->read_ahead >= 0 ? \
490                  softc->read_ahead : ada_read_ahead)
491 #define ADA_WC  (softc->write_cache >= 0 ? \
492                  softc->write_cache : ada_write_cache)
493 #define ADA_SIO (softc->sort_io_queue >= 0 ? \
494                  softc->sort_io_queue : cam_sort_io_queues)
495
496 /*
497  * Most platforms map firmware geometry to actual, but some don't.  If
498  * not overridden, default to nothing.
499  */
500 #ifndef ata_disk_firmware_geom_adjust
501 #define ata_disk_firmware_geom_adjust(disk)
502 #endif
503
504 static int ada_legacy_aliases = ADA_DEFAULT_LEGACY_ALIASES;
505 static int ada_retry_count = ADA_DEFAULT_RETRY;
506 static int ada_default_timeout = ADA_DEFAULT_TIMEOUT;
507 static int ada_send_ordered = ADA_DEFAULT_SEND_ORDERED;
508 static int ada_spindown_shutdown = ADA_DEFAULT_SPINDOWN_SHUTDOWN;
509 static int ada_spindown_suspend = ADA_DEFAULT_SPINDOWN_SUSPEND;
510 static int ada_read_ahead = ADA_DEFAULT_READ_AHEAD;
511 static int ada_write_cache = ADA_DEFAULT_WRITE_CACHE;
512
513 static SYSCTL_NODE(_kern_cam, OID_AUTO, ada, CTLFLAG_RD, 0,
514             "CAM Direct Access Disk driver");
515 SYSCTL_INT(_kern_cam_ada, OID_AUTO, legacy_aliases, CTLFLAG_RW,
516            &ada_legacy_aliases, 0, "Create legacy-like device aliases");
517 TUNABLE_INT("kern.cam.ada.legacy_aliases", &ada_legacy_aliases);
518 SYSCTL_INT(_kern_cam_ada, OID_AUTO, retry_count, CTLFLAG_RW,
519            &ada_retry_count, 0, "Normal I/O retry count");
520 TUNABLE_INT("kern.cam.ada.retry_count", &ada_retry_count);
521 SYSCTL_INT(_kern_cam_ada, OID_AUTO, default_timeout, CTLFLAG_RW,
522            &ada_default_timeout, 0, "Normal I/O timeout (in seconds)");
523 TUNABLE_INT("kern.cam.ada.default_timeout", &ada_default_timeout);
524 SYSCTL_INT(_kern_cam_ada, OID_AUTO, send_ordered, CTLFLAG_RW,
525            &ada_send_ordered, 0, "Send Ordered Tags");
526 TUNABLE_INT("kern.cam.ada.send_ordered", &ada_send_ordered);
527 SYSCTL_INT(_kern_cam_ada, OID_AUTO, spindown_shutdown, CTLFLAG_RW,
528            &ada_spindown_shutdown, 0, "Spin down upon shutdown");
529 TUNABLE_INT("kern.cam.ada.spindown_shutdown", &ada_spindown_shutdown);
530 SYSCTL_INT(_kern_cam_ada, OID_AUTO, spindown_suspend, CTLFLAG_RW,
531            &ada_spindown_suspend, 0, "Spin down upon suspend");
532 TUNABLE_INT("kern.cam.ada.spindown_suspend", &ada_spindown_suspend);
533 SYSCTL_INT(_kern_cam_ada, OID_AUTO, read_ahead, CTLFLAG_RW,
534            &ada_read_ahead, 0, "Enable disk read-ahead");
535 TUNABLE_INT("kern.cam.ada.read_ahead", &ada_read_ahead);
536 SYSCTL_INT(_kern_cam_ada, OID_AUTO, write_cache, CTLFLAG_RW,
537            &ada_write_cache, 0, "Enable disk write cache");
538 TUNABLE_INT("kern.cam.ada.write_cache", &ada_write_cache);
539
540 /*
541  * ADA_ORDEREDTAG_INTERVAL determines how often, relative
542  * to the default timeout, we check to see whether an ordered
543  * tagged transaction is appropriate to prevent simple tag
544  * starvation.  Since we'd like to ensure that there is at least
545  * 1/2 of the timeout length left for a starved transaction to
546  * complete after we've sent an ordered tag, we must poll at least
547  * four times in every timeout period.  This takes care of the worst
548  * case where a starved transaction starts during an interval that
549  * meets the requirement "don't send an ordered tag" test so it takes
550  * us two intervals to determine that a tag must be sent.
551  */
552 #ifndef ADA_ORDEREDTAG_INTERVAL
553 #define ADA_ORDEREDTAG_INTERVAL 4
554 #endif
555
556 static struct periph_driver adadriver =
557 {
558         adainit, "ada",
559         TAILQ_HEAD_INITIALIZER(adadriver.units), /* generation */ 0
560 };
561
562 PERIPHDRIVER_DECLARE(ada, adadriver);
563
564 static MALLOC_DEFINE(M_ATADA, "ata_da", "ata_da buffers");
565
566 static int
567 adaopen(struct disk *dp)
568 {
569         struct cam_periph *periph;
570         struct ada_softc *softc;
571         int error;
572
573         periph = (struct cam_periph *)dp->d_drv1;
574         if (cam_periph_acquire(periph) != CAM_REQ_CMP) {
575                 return(ENXIO);
576         }
577
578         cam_periph_lock(periph);
579         if ((error = cam_periph_hold(periph, PRIBIO|PCATCH)) != 0) {
580                 cam_periph_unlock(periph);
581                 cam_periph_release(periph);
582                 return (error);
583         }
584
585         softc = (struct ada_softc *)periph->softc;
586         softc->flags |= ADA_FLAG_OPEN;
587
588         CAM_DEBUG(periph->path, CAM_DEBUG_TRACE | CAM_DEBUG_PERIPH,
589             ("adaopen\n"));
590
591         if ((softc->flags & ADA_FLAG_PACK_INVALID) != 0) {
592                 /* Invalidate our pack information. */
593                 softc->flags &= ~ADA_FLAG_PACK_INVALID;
594         }
595
596         cam_periph_unhold(periph);
597         cam_periph_unlock(periph);
598         return (0);
599 }
600
601 static int
602 adaclose(struct disk *dp)
603 {
604         struct  cam_periph *periph;
605         struct  ada_softc *softc;
606         union ccb *ccb;
607
608         periph = (struct cam_periph *)dp->d_drv1;
609         cam_periph_lock(periph);
610         if (cam_periph_hold(periph, PRIBIO) != 0) {
611                 cam_periph_unlock(periph);
612                 cam_periph_release(periph);
613                 return (0);
614         }
615
616         softc = (struct ada_softc *)periph->softc;
617
618         CAM_DEBUG(periph->path, CAM_DEBUG_TRACE | CAM_DEBUG_PERIPH,
619             ("adaclose\n"));
620
621         /* We only sync the cache if the drive is capable of it. */
622         if ((softc->flags & ADA_FLAG_CAN_FLUSHCACHE) != 0 &&
623             (softc->flags & ADA_FLAG_PACK_INVALID) == 0) {
624
625                 ccb = cam_periph_getccb(periph, CAM_PRIORITY_NORMAL);
626                 cam_fill_ataio(&ccb->ataio,
627                                     1,
628                                     adadone,
629                                     CAM_DIR_NONE,
630                                     0,
631                                     NULL,
632                                     0,
633                                     ada_default_timeout*1000);
634
635                 if (softc->flags & ADA_FLAG_CAN_48BIT)
636                         ata_48bit_cmd(&ccb->ataio, ATA_FLUSHCACHE48, 0, 0, 0);
637                 else
638                         ata_28bit_cmd(&ccb->ataio, ATA_FLUSHCACHE, 0, 0, 0);
639                 cam_periph_runccb(ccb, adaerror, /*cam_flags*/0,
640                     /*sense_flags*/0, softc->disk->d_devstat);
641
642                 if ((ccb->ccb_h.status & CAM_STATUS_MASK) != CAM_REQ_CMP)
643                         xpt_print(periph->path, "Synchronize cache failed\n");
644                 xpt_release_ccb(ccb);
645         }
646
647         softc->flags &= ~ADA_FLAG_OPEN;
648         cam_periph_unhold(periph);
649         cam_periph_unlock(periph);
650         cam_periph_release(periph);
651         return (0);     
652 }
653
654 static void
655 adaschedule(struct cam_periph *periph)
656 {
657         struct ada_softc *softc = (struct ada_softc *)periph->softc;
658         uint32_t prio;
659
660         /* Check if cam_periph_getccb() was called. */
661         prio = periph->immediate_priority;
662
663         /* Check if we have more work to do. */
664         if (bioq_first(&softc->bio_queue) ||
665             (!softc->trim_running && bioq_first(&softc->trim_queue))) {
666                 prio = CAM_PRIORITY_NORMAL;
667         }
668
669         /* Schedule CCB if any of above is true. */
670         if (prio != CAM_PRIORITY_NONE)
671                 xpt_schedule(periph, prio);
672 }
673
674 /*
675  * Actually translate the requested transfer into one the physical driver
676  * can understand.  The transfer is described by a buf and will include
677  * only one physical transfer.
678  */
679 static void
680 adastrategy(struct bio *bp)
681 {
682         struct cam_periph *periph;
683         struct ada_softc *softc;
684         
685         periph = (struct cam_periph *)bp->bio_disk->d_drv1;
686         softc = (struct ada_softc *)periph->softc;
687
688         cam_periph_lock(periph);
689
690         CAM_DEBUG(periph->path, CAM_DEBUG_TRACE, ("adastrategy(%p)\n", bp));
691
692         /*
693          * If the device has been made invalid, error out
694          */
695         if ((softc->flags & ADA_FLAG_PACK_INVALID)) {
696                 cam_periph_unlock(periph);
697                 biofinish(bp, NULL, ENXIO);
698                 return;
699         }
700         
701         /*
702          * Place it in the queue of disk activities for this disk
703          */
704         if (bp->bio_cmd == BIO_DELETE &&
705             (softc->flags & ADA_FLAG_CAN_TRIM)) {
706                 if (ADA_SIO)
707                     bioq_disksort(&softc->trim_queue, bp);
708                 else
709                     bioq_insert_tail(&softc->trim_queue, bp);
710         } else {
711                 if (ADA_SIO)
712                     bioq_disksort(&softc->bio_queue, bp);
713                 else
714                     bioq_insert_tail(&softc->bio_queue, bp);
715         }
716
717         /*
718          * Schedule ourselves for performing the work.
719          */
720         adaschedule(periph);
721         cam_periph_unlock(periph);
722
723         return;
724 }
725
726 static int
727 adadump(void *arg, void *virtual, vm_offset_t physical, off_t offset, size_t length)
728 {
729         struct      cam_periph *periph;
730         struct      ada_softc *softc;
731         u_int       secsize;
732         union       ccb ccb;
733         struct      disk *dp;
734         uint64_t    lba;
735         uint16_t    count;
736         int         error = 0;
737
738         dp = arg;
739         periph = dp->d_drv1;
740         softc = (struct ada_softc *)periph->softc;
741         cam_periph_lock(periph);
742         secsize = softc->params.secsize;
743         lba = offset / secsize;
744         count = length / secsize;
745         
746         if ((softc->flags & ADA_FLAG_PACK_INVALID) != 0) {
747                 cam_periph_unlock(periph);
748                 return (ENXIO);
749         }
750
751         if (length > 0) {
752                 xpt_setup_ccb(&ccb.ccb_h, periph->path, CAM_PRIORITY_NORMAL);
753                 ccb.ccb_h.ccb_state = ADA_CCB_DUMP;
754                 cam_fill_ataio(&ccb.ataio,
755                     0,
756                     adadone,
757                     CAM_DIR_OUT,
758                     0,
759                     (u_int8_t *) virtual,
760                     length,
761                     ada_default_timeout*1000);
762                 if ((softc->flags & ADA_FLAG_CAN_48BIT) &&
763                     (lba + count >= ATA_MAX_28BIT_LBA ||
764                     count >= 256)) {
765                         ata_48bit_cmd(&ccb.ataio, ATA_WRITE_DMA48,
766                             0, lba, count);
767                 } else {
768                         ata_28bit_cmd(&ccb.ataio, ATA_WRITE_DMA,
769                             0, lba, count);
770                 }
771                 xpt_polled_action(&ccb);
772
773                 error = cam_periph_error(&ccb,
774                     0, SF_NO_RECOVERY | SF_NO_RETRY, NULL);
775                 if ((ccb.ccb_h.status & CAM_DEV_QFRZN) != 0)
776                         cam_release_devq(ccb.ccb_h.path, /*relsim_flags*/0,
777                             /*reduction*/0, /*timeout*/0, /*getcount_only*/0);
778                 if (error != 0)
779                         printf("Aborting dump due to I/O error.\n");
780
781                 cam_periph_unlock(periph);
782                 return (error);
783         }
784
785         if (softc->flags & ADA_FLAG_CAN_FLUSHCACHE) {
786                 xpt_setup_ccb(&ccb.ccb_h, periph->path, CAM_PRIORITY_NORMAL);
787
788                 ccb.ccb_h.ccb_state = ADA_CCB_DUMP;
789                 cam_fill_ataio(&ccb.ataio,
790                                     0,
791                                     adadone,
792                                     CAM_DIR_NONE,
793                                     0,
794                                     NULL,
795                                     0,
796                                     ada_default_timeout*1000);
797
798                 if (softc->flags & ADA_FLAG_CAN_48BIT)
799                         ata_48bit_cmd(&ccb.ataio, ATA_FLUSHCACHE48, 0, 0, 0);
800                 else
801                         ata_28bit_cmd(&ccb.ataio, ATA_FLUSHCACHE, 0, 0, 0);
802                 xpt_polled_action(&ccb);
803
804                 error = cam_periph_error(&ccb,
805                     0, SF_NO_RECOVERY | SF_NO_RETRY, NULL);
806                 if ((ccb.ccb_h.status & CAM_DEV_QFRZN) != 0)
807                         cam_release_devq(ccb.ccb_h.path, /*relsim_flags*/0,
808                             /*reduction*/0, /*timeout*/0, /*getcount_only*/0);
809                 if (error != 0)
810                         xpt_print(periph->path, "Synchronize cache failed\n");
811         }
812         cam_periph_unlock(periph);
813         return (error);
814 }
815
816 static void
817 adainit(void)
818 {
819         cam_status status;
820
821         /*
822          * Install a global async callback.  This callback will
823          * receive async callbacks like "new device found".
824          */
825         status = xpt_register_async(AC_FOUND_DEVICE, adaasync, NULL, NULL);
826
827         if (status != CAM_REQ_CMP) {
828                 printf("ada: Failed to attach master async callback "
829                        "due to status 0x%x!\n", status);
830         } else if (ada_send_ordered) {
831
832                 /* Register our event handlers */
833                 if ((EVENTHANDLER_REGISTER(power_suspend, adasuspend,
834                                            NULL, EVENTHANDLER_PRI_LAST)) == NULL)
835                     printf("adainit: power event registration failed!\n");
836                 if ((EVENTHANDLER_REGISTER(power_resume, adaresume,
837                                            NULL, EVENTHANDLER_PRI_LAST)) == NULL)
838                     printf("adainit: power event registration failed!\n");
839                 if ((EVENTHANDLER_REGISTER(shutdown_post_sync, adashutdown,
840                                            NULL, SHUTDOWN_PRI_DEFAULT)) == NULL)
841                     printf("adainit: shutdown event registration failed!\n");
842         }
843 }
844
845 /*
846  * Callback from GEOM, called when it has finished cleaning up its
847  * resources.
848  */
849 static void
850 adadiskgonecb(struct disk *dp)
851 {
852         struct cam_periph *periph;
853
854         periph = (struct cam_periph *)dp->d_drv1;
855
856         cam_periph_release(periph);
857 }
858
859 static void
860 adaoninvalidate(struct cam_periph *periph)
861 {
862         struct ada_softc *softc;
863
864         softc = (struct ada_softc *)periph->softc;
865
866         /*
867          * De-register any async callbacks.
868          */
869         xpt_register_async(0, adaasync, periph, periph->path);
870
871         softc->flags |= ADA_FLAG_PACK_INVALID;
872
873         /*
874          * Return all queued I/O with ENXIO.
875          * XXX Handle any transactions queued to the card
876          *     with XPT_ABORT_CCB.
877          */
878         bioq_flush(&softc->bio_queue, NULL, ENXIO);
879         bioq_flush(&softc->trim_queue, NULL, ENXIO);
880
881         disk_gone(softc->disk);
882         xpt_print(periph->path, "lost device\n");
883 }
884
885 static void
886 adacleanup(struct cam_periph *periph)
887 {
888         struct ada_softc *softc;
889
890         softc = (struct ada_softc *)periph->softc;
891
892         xpt_print(periph->path, "removing device entry\n");
893         cam_periph_unlock(periph);
894
895         /*
896          * If we can't free the sysctl tree, oh well...
897          */
898         if ((softc->flags & ADA_FLAG_SCTX_INIT) != 0
899             && sysctl_ctx_free(&softc->sysctl_ctx) != 0) {
900                 xpt_print(periph->path, "can't remove sysctl context\n");
901         }
902
903         disk_destroy(softc->disk);
904         callout_drain(&softc->sendordered_c);
905         free(softc, M_DEVBUF);
906         cam_periph_lock(periph);
907 }
908
909 static void
910 adaasync(void *callback_arg, u_int32_t code,
911         struct cam_path *path, void *arg)
912 {
913         struct ccb_getdev cgd;
914         struct cam_periph *periph;
915         struct ada_softc *softc;
916
917         periph = (struct cam_periph *)callback_arg;
918         switch (code) {
919         case AC_FOUND_DEVICE:
920         {
921                 struct ccb_getdev *cgd;
922                 cam_status status;
923  
924                 cgd = (struct ccb_getdev *)arg;
925                 if (cgd == NULL)
926                         break;
927
928                 if (cgd->protocol != PROTO_ATA)
929                         break;
930
931                 /*
932                  * Allocate a peripheral instance for
933                  * this device and start the probe
934                  * process.
935                  */
936                 status = cam_periph_alloc(adaregister, adaoninvalidate,
937                                           adacleanup, adastart,
938                                           "ada", CAM_PERIPH_BIO,
939                                           cgd->ccb_h.path, adaasync,
940                                           AC_FOUND_DEVICE, cgd);
941
942                 if (status != CAM_REQ_CMP
943                  && status != CAM_REQ_INPROG)
944                         printf("adaasync: Unable to attach to new device "
945                                 "due to status 0x%x\n", status);
946                 break;
947         }
948         case AC_GETDEV_CHANGED:
949         {
950                 softc = (struct ada_softc *)periph->softc;
951                 xpt_setup_ccb(&cgd.ccb_h, periph->path, CAM_PRIORITY_NORMAL);
952                 cgd.ccb_h.func_code = XPT_GDEV_TYPE;
953                 xpt_action((union ccb *)&cgd);
954
955                 if ((cgd.ident_data.capabilities1 & ATA_SUPPORT_DMA) &&
956                     (cgd.inq_flags & SID_DMA))
957                         softc->flags |= ADA_FLAG_CAN_DMA;
958                 else
959                         softc->flags &= ~ADA_FLAG_CAN_DMA;
960                 if (cgd.ident_data.support.command2 & ATA_SUPPORT_ADDRESS48) {
961                         softc->flags |= ADA_FLAG_CAN_48BIT;
962                         if (cgd.inq_flags & SID_DMA48)
963                                 softc->flags |= ADA_FLAG_CAN_DMA48;
964                         else
965                                 softc->flags &= ~ADA_FLAG_CAN_DMA48;
966                 } else
967                         softc->flags &= ~(ADA_FLAG_CAN_48BIT |
968                             ADA_FLAG_CAN_DMA48);
969                 if ((cgd.ident_data.satacapabilities & ATA_SUPPORT_NCQ) &&
970                     (cgd.inq_flags & SID_DMA) && (cgd.inq_flags & SID_CmdQue))
971                         softc->flags |= ADA_FLAG_CAN_NCQ;
972                 else
973                         softc->flags &= ~ADA_FLAG_CAN_NCQ;
974                 if ((cgd.ident_data.support_dsm & ATA_SUPPORT_DSM_TRIM) &&
975                     (cgd.inq_flags & SID_DMA))
976                         softc->flags |= ADA_FLAG_CAN_TRIM;
977                 else
978                         softc->flags &= ~ADA_FLAG_CAN_TRIM;
979
980                 cam_periph_async(periph, code, path, arg);
981                 break;
982         }
983         case AC_ADVINFO_CHANGED:
984         {
985                 uintptr_t buftype;
986
987                 buftype = (uintptr_t)arg;
988                 if (buftype == CDAI_TYPE_PHYS_PATH) {
989                         struct ada_softc *softc;
990
991                         softc = periph->softc;
992                         disk_attr_changed(softc->disk, "GEOM::physpath",
993                                           M_NOWAIT);
994                 }
995                 break;
996         }
997         case AC_SENT_BDR:
998         case AC_BUS_RESET:
999         {
1000                 softc = (struct ada_softc *)periph->softc;
1001                 cam_periph_async(periph, code, path, arg);
1002                 if (softc->state != ADA_STATE_NORMAL)
1003                         break;
1004                 xpt_setup_ccb(&cgd.ccb_h, periph->path, CAM_PRIORITY_NORMAL);
1005                 cgd.ccb_h.func_code = XPT_GDEV_TYPE;
1006                 xpt_action((union ccb *)&cgd);
1007                 if (ADA_RA >= 0 &&
1008                     cgd.ident_data.support.command1 & ATA_SUPPORT_LOOKAHEAD)
1009                         softc->state = ADA_STATE_RAHEAD;
1010                 else if (ADA_WC >= 0 &&
1011                     cgd.ident_data.support.command1 & ATA_SUPPORT_WRITECACHE)
1012                         softc->state = ADA_STATE_WCACHE;
1013                 else
1014                     break;
1015                 cam_periph_acquire(periph);
1016                 cam_freeze_devq_arg(periph->path,
1017                     RELSIM_RELEASE_RUNLEVEL, CAM_RL_DEV + 1);
1018                 xpt_schedule(periph, CAM_PRIORITY_DEV);
1019         }
1020         default:
1021                 cam_periph_async(periph, code, path, arg);
1022                 break;
1023         }
1024 }
1025
1026 static void
1027 adasysctlinit(void *context, int pending)
1028 {
1029         struct cam_periph *periph;
1030         struct ada_softc *softc;
1031         char tmpstr[80], tmpstr2[80];
1032
1033         periph = (struct cam_periph *)context;
1034
1035         /* periph was held for us when this task was enqueued */
1036         if (periph->flags & CAM_PERIPH_INVALID) {
1037                 cam_periph_release(periph);
1038                 return;
1039         }
1040
1041         softc = (struct ada_softc *)periph->softc;
1042         snprintf(tmpstr, sizeof(tmpstr), "CAM ADA unit %d", periph->unit_number);
1043         snprintf(tmpstr2, sizeof(tmpstr2), "%d", periph->unit_number);
1044
1045         sysctl_ctx_init(&softc->sysctl_ctx);
1046         softc->flags |= ADA_FLAG_SCTX_INIT;
1047         softc->sysctl_tree = SYSCTL_ADD_NODE(&softc->sysctl_ctx,
1048                 SYSCTL_STATIC_CHILDREN(_kern_cam_ada), OID_AUTO, tmpstr2,
1049                 CTLFLAG_RD, 0, tmpstr);
1050         if (softc->sysctl_tree == NULL) {
1051                 printf("adasysctlinit: unable to allocate sysctl tree\n");
1052                 cam_periph_release(periph);
1053                 return;
1054         }
1055
1056         SYSCTL_ADD_INT(&softc->sysctl_ctx, SYSCTL_CHILDREN(softc->sysctl_tree),
1057                 OID_AUTO, "read_ahead", CTLFLAG_RW | CTLFLAG_MPSAFE,
1058                 &softc->read_ahead, 0, "Enable disk read ahead.");
1059         SYSCTL_ADD_INT(&softc->sysctl_ctx, SYSCTL_CHILDREN(softc->sysctl_tree),
1060                 OID_AUTO, "write_cache", CTLFLAG_RW | CTLFLAG_MPSAFE,
1061                 &softc->write_cache, 0, "Enable disk write cache.");
1062         SYSCTL_ADD_INT(&softc->sysctl_ctx, SYSCTL_CHILDREN(softc->sysctl_tree),
1063                 OID_AUTO, "sort_io_queue", CTLFLAG_RW | CTLFLAG_MPSAFE,
1064                 &softc->sort_io_queue, 0,
1065                 "Sort IO queue to try and optimise disk access patterns");
1066 #ifdef ADA_TEST_FAILURE
1067         /*
1068          * Add a 'door bell' sysctl which allows one to set it from userland
1069          * and cause something bad to happen.  For the moment, we only allow
1070          * whacking the next read or write.
1071          */
1072         SYSCTL_ADD_INT(&softc->sysctl_ctx, SYSCTL_CHILDREN(softc->sysctl_tree),
1073                 OID_AUTO, "force_read_error", CTLFLAG_RW | CTLFLAG_MPSAFE,
1074                 &softc->force_read_error, 0,
1075                 "Force a read error for the next N reads.");
1076         SYSCTL_ADD_INT(&softc->sysctl_ctx, SYSCTL_CHILDREN(softc->sysctl_tree),
1077                 OID_AUTO, "force_write_error", CTLFLAG_RW | CTLFLAG_MPSAFE,
1078                 &softc->force_write_error, 0,
1079                 "Force a write error for the next N writes.");
1080         SYSCTL_ADD_INT(&softc->sysctl_ctx, SYSCTL_CHILDREN(softc->sysctl_tree),
1081                 OID_AUTO, "periodic_read_error", CTLFLAG_RW | CTLFLAG_MPSAFE,
1082                 &softc->periodic_read_error, 0,
1083                 "Force a read error every N reads (don't set too low).");
1084 #endif
1085         cam_periph_release(periph);
1086 }
1087
1088 static int
1089 adagetattr(struct bio *bp)
1090 {
1091         int ret;
1092         struct cam_periph *periph;
1093
1094         periph = (struct cam_periph *)bp->bio_disk->d_drv1;
1095         cam_periph_lock(periph);
1096         ret = xpt_getattr(bp->bio_data, bp->bio_length, bp->bio_attribute,
1097             periph->path);
1098         cam_periph_unlock(periph);
1099         if (ret == 0)
1100                 bp->bio_completed = bp->bio_length;
1101         return ret;
1102 }
1103
1104 static cam_status
1105 adaregister(struct cam_periph *periph, void *arg)
1106 {
1107         struct ada_softc *softc;
1108         struct ccb_pathinq cpi;
1109         struct ccb_getdev *cgd;
1110         char   announce_buf[80], buf1[32];
1111         struct disk_params *dp;
1112         caddr_t match;
1113         u_int maxio;
1114         int legacy_id, quirks;
1115
1116         cgd = (struct ccb_getdev *)arg;
1117         if (cgd == NULL) {
1118                 printf("adaregister: no getdev CCB, can't register device\n");
1119                 return(CAM_REQ_CMP_ERR);
1120         }
1121
1122         softc = (struct ada_softc *)malloc(sizeof(*softc), M_DEVBUF,
1123             M_NOWAIT|M_ZERO);
1124
1125         if (softc == NULL) {
1126                 printf("adaregister: Unable to probe new device. "
1127                     "Unable to allocate softc\n");
1128                 return(CAM_REQ_CMP_ERR);
1129         }
1130
1131         bioq_init(&softc->bio_queue);
1132         bioq_init(&softc->trim_queue);
1133
1134         if ((cgd->ident_data.capabilities1 & ATA_SUPPORT_DMA) &&
1135             (cgd->inq_flags & SID_DMA))
1136                 softc->flags |= ADA_FLAG_CAN_DMA;
1137         if (cgd->ident_data.support.command2 & ATA_SUPPORT_ADDRESS48) {
1138                 softc->flags |= ADA_FLAG_CAN_48BIT;
1139                 if (cgd->inq_flags & SID_DMA48)
1140                         softc->flags |= ADA_FLAG_CAN_DMA48;
1141         }
1142         if (cgd->ident_data.support.command2 & ATA_SUPPORT_FLUSHCACHE)
1143                 softc->flags |= ADA_FLAG_CAN_FLUSHCACHE;
1144         if (cgd->ident_data.support.command1 & ATA_SUPPORT_POWERMGT)
1145                 softc->flags |= ADA_FLAG_CAN_POWERMGT;
1146         if ((cgd->ident_data.satacapabilities & ATA_SUPPORT_NCQ) &&
1147             (cgd->inq_flags & SID_DMA) && (cgd->inq_flags & SID_CmdQue))
1148                 softc->flags |= ADA_FLAG_CAN_NCQ;
1149         if ((cgd->ident_data.support_dsm & ATA_SUPPORT_DSM_TRIM) &&
1150             (cgd->inq_flags & SID_DMA)) {
1151                 softc->flags |= ADA_FLAG_CAN_TRIM;
1152                 softc->trim_max_ranges = TRIM_MAX_RANGES;
1153                 if (cgd->ident_data.max_dsm_blocks != 0) {
1154                         softc->trim_max_ranges =
1155                             min(cgd->ident_data.max_dsm_blocks *
1156                                 ATA_DSM_BLK_RANGES, softc->trim_max_ranges);
1157                 }
1158         }
1159         if (cgd->ident_data.support.command2 & ATA_SUPPORT_CFA)
1160                 softc->flags |= ADA_FLAG_CAN_CFA;
1161
1162         periph->softc = softc;
1163
1164         /*
1165          * See if this device has any quirks.
1166          */
1167         match = cam_quirkmatch((caddr_t)&cgd->ident_data,
1168                                (caddr_t)ada_quirk_table,
1169                                sizeof(ada_quirk_table)/sizeof(*ada_quirk_table),
1170                                sizeof(*ada_quirk_table), ata_identify_match);
1171         if (match != NULL)
1172                 softc->quirks = ((struct ada_quirk_entry *)match)->quirks;
1173         else
1174                 softc->quirks = ADA_Q_NONE;
1175
1176         bzero(&cpi, sizeof(cpi));
1177         xpt_setup_ccb(&cpi.ccb_h, periph->path, CAM_PRIORITY_NONE);
1178         cpi.ccb_h.func_code = XPT_PATH_INQ;
1179         xpt_action((union ccb *)&cpi);
1180
1181         TASK_INIT(&softc->sysctl_task, 0, adasysctlinit, periph);
1182
1183         /*
1184          * Register this media as a disk
1185          */
1186         (void)cam_periph_hold(periph, PRIBIO);
1187         cam_periph_unlock(periph);
1188         snprintf(announce_buf, sizeof(announce_buf),
1189             "kern.cam.ada.%d.quirks", periph->unit_number);
1190         quirks = softc->quirks;
1191         TUNABLE_INT_FETCH(announce_buf, &quirks);
1192         softc->quirks = quirks;
1193         softc->read_ahead = -1;
1194         snprintf(announce_buf, sizeof(announce_buf),
1195             "kern.cam.ada.%d.read_ahead", periph->unit_number);
1196         TUNABLE_INT_FETCH(announce_buf, &softc->read_ahead);
1197         softc->write_cache = -1;
1198         snprintf(announce_buf, sizeof(announce_buf),
1199             "kern.cam.ada.%d.write_cache", periph->unit_number);
1200         TUNABLE_INT_FETCH(announce_buf, &softc->write_cache);
1201         /* Disable queue sorting for non-rotational media by default. */
1202         if (cgd->ident_data.media_rotation_rate == 1)
1203                 softc->sort_io_queue = 0;
1204         else
1205                 softc->sort_io_queue = -1;
1206         adagetparams(periph, cgd);
1207         softc->disk = disk_alloc();
1208         softc->disk->d_devstat = devstat_new_entry(periph->periph_name,
1209                           periph->unit_number, softc->params.secsize,
1210                           DEVSTAT_ALL_SUPPORTED,
1211                           DEVSTAT_TYPE_DIRECT |
1212                           XPORT_DEVSTAT_TYPE(cpi.transport),
1213                           DEVSTAT_PRIORITY_DISK);
1214         softc->disk->d_open = adaopen;
1215         softc->disk->d_close = adaclose;
1216         softc->disk->d_strategy = adastrategy;
1217         softc->disk->d_getattr = adagetattr;
1218         softc->disk->d_dump = adadump;
1219         softc->disk->d_gone = adadiskgonecb;
1220         softc->disk->d_name = "ada";
1221         softc->disk->d_drv1 = periph;
1222         maxio = cpi.maxio;              /* Honor max I/O size of SIM */
1223         if (maxio == 0)
1224                 maxio = DFLTPHYS;       /* traditional default */
1225         else if (maxio > MAXPHYS)
1226                 maxio = MAXPHYS;        /* for safety */
1227         if (softc->flags & ADA_FLAG_CAN_48BIT)
1228                 maxio = min(maxio, 65536 * softc->params.secsize);
1229         else                                    /* 28bit ATA command limit */
1230                 maxio = min(maxio, 256 * softc->params.secsize);
1231         softc->disk->d_maxsize = maxio;
1232         softc->disk->d_unit = periph->unit_number;
1233         softc->disk->d_flags = 0;
1234         if (softc->flags & ADA_FLAG_CAN_FLUSHCACHE)
1235                 softc->disk->d_flags |= DISKFLAG_CANFLUSHCACHE;
1236         if (softc->flags & ADA_FLAG_CAN_TRIM) {
1237                 softc->disk->d_flags |= DISKFLAG_CANDELETE;
1238         } else if ((softc->flags & ADA_FLAG_CAN_CFA) &&
1239             !(softc->flags & ADA_FLAG_CAN_48BIT)) {
1240                 softc->disk->d_flags |= DISKFLAG_CANDELETE;
1241         }
1242         strlcpy(softc->disk->d_descr, cgd->ident_data.model,
1243             MIN(sizeof(softc->disk->d_descr), sizeof(cgd->ident_data.model)));
1244         strlcpy(softc->disk->d_ident, cgd->ident_data.serial,
1245             MIN(sizeof(softc->disk->d_ident), sizeof(cgd->ident_data.serial)));
1246         softc->disk->d_hba_vendor = cpi.hba_vendor;
1247         softc->disk->d_hba_device = cpi.hba_device;
1248         softc->disk->d_hba_subvendor = cpi.hba_subvendor;
1249         softc->disk->d_hba_subdevice = cpi.hba_subdevice;
1250
1251         softc->disk->d_sectorsize = softc->params.secsize;
1252         softc->disk->d_mediasize = (off_t)softc->params.sectors *
1253             softc->params.secsize;
1254         if (ata_physical_sector_size(&cgd->ident_data) !=
1255             softc->params.secsize) {
1256                 softc->disk->d_stripesize =
1257                     ata_physical_sector_size(&cgd->ident_data);
1258                 softc->disk->d_stripeoffset = (softc->disk->d_stripesize -
1259                     ata_logical_sector_offset(&cgd->ident_data)) %
1260                     softc->disk->d_stripesize;
1261         } else if (softc->quirks & ADA_Q_4K) {
1262                 softc->disk->d_stripesize = 4096;
1263                 softc->disk->d_stripeoffset = 0;
1264         }
1265         softc->disk->d_fwsectors = softc->params.secs_per_track;
1266         softc->disk->d_fwheads = softc->params.heads;
1267         ata_disk_firmware_geom_adjust(softc->disk);
1268
1269         if (ada_legacy_aliases) {
1270 #ifdef ATA_STATIC_ID
1271                 legacy_id = xpt_path_legacy_ata_id(periph->path);
1272 #else
1273                 legacy_id = softc->disk->d_unit;
1274 #endif
1275                 if (legacy_id >= 0) {
1276                         snprintf(announce_buf, sizeof(announce_buf),
1277                             "kern.devalias.%s%d",
1278                             softc->disk->d_name, softc->disk->d_unit);
1279                         snprintf(buf1, sizeof(buf1),
1280                             "ad%d", legacy_id);
1281                         setenv(announce_buf, buf1);
1282                 }
1283         } else
1284                 legacy_id = -1;
1285         /*
1286          * Acquire a reference to the periph before we register with GEOM.
1287          * We'll release this reference once GEOM calls us back (via
1288          * adadiskgonecb()) telling us that our provider has been freed.
1289          */
1290         if (cam_periph_acquire(periph) != CAM_REQ_CMP) {
1291                 xpt_print(periph->path, "%s: lost periph during "
1292                           "registration!\n", __func__);
1293                 cam_periph_lock(periph);
1294                 return (CAM_REQ_CMP_ERR);
1295         }
1296         disk_create(softc->disk, DISK_VERSION);
1297         cam_periph_lock(periph);
1298         cam_periph_unhold(periph);
1299
1300         dp = &softc->params;
1301         snprintf(announce_buf, sizeof(announce_buf),
1302                 "%juMB (%ju %u byte sectors: %dH %dS/T %dC)",
1303                 (uintmax_t)(((uintmax_t)dp->secsize *
1304                 dp->sectors) / (1024*1024)),
1305                 (uintmax_t)dp->sectors,
1306                 dp->secsize, dp->heads,
1307                 dp->secs_per_track, dp->cylinders);
1308         xpt_announce_periph(periph, announce_buf);
1309         xpt_announce_quirks(periph, softc->quirks, ADA_Q_BIT_STRING);
1310         if (legacy_id >= 0)
1311                 printf("%s%d: Previously was known as ad%d\n",
1312                        periph->periph_name, periph->unit_number, legacy_id);
1313
1314         /*
1315          * Create our sysctl variables, now that we know
1316          * we have successfully attached.
1317          */
1318         cam_periph_acquire(periph);
1319         taskqueue_enqueue(taskqueue_thread, &softc->sysctl_task);
1320
1321         /*
1322          * Add async callbacks for bus reset and
1323          * bus device reset calls.  I don't bother
1324          * checking if this fails as, in most cases,
1325          * the system will function just fine without
1326          * them and the only alternative would be to
1327          * not attach the device on failure.
1328          */
1329         xpt_register_async(AC_SENT_BDR | AC_BUS_RESET | AC_LOST_DEVICE |
1330             AC_GETDEV_CHANGED | AC_ADVINFO_CHANGED,
1331             adaasync, periph, periph->path);
1332
1333         /*
1334          * Schedule a periodic event to occasionally send an
1335          * ordered tag to a device.
1336          */
1337         callout_init_mtx(&softc->sendordered_c, periph->sim->mtx, 0);
1338         callout_reset(&softc->sendordered_c,
1339             (ada_default_timeout * hz) / ADA_ORDEREDTAG_INTERVAL,
1340             adasendorderedtag, softc);
1341
1342         if (ADA_RA >= 0 &&
1343             cgd->ident_data.support.command1 & ATA_SUPPORT_LOOKAHEAD) {
1344                 softc->state = ADA_STATE_RAHEAD;
1345                 cam_periph_acquire(periph);
1346                 cam_freeze_devq_arg(periph->path,
1347                     RELSIM_RELEASE_RUNLEVEL, CAM_RL_DEV + 1);
1348                 xpt_schedule(periph, CAM_PRIORITY_DEV);
1349         } else if (ADA_WC >= 0 &&
1350             cgd->ident_data.support.command1 & ATA_SUPPORT_WRITECACHE) {
1351                 softc->state = ADA_STATE_WCACHE;
1352                 cam_periph_acquire(periph);
1353                 cam_freeze_devq_arg(periph->path,
1354                     RELSIM_RELEASE_RUNLEVEL, CAM_RL_DEV + 1);
1355                 xpt_schedule(periph, CAM_PRIORITY_DEV);
1356         } else
1357                 softc->state = ADA_STATE_NORMAL;
1358
1359         return(CAM_REQ_CMP);
1360 }
1361
1362 static void
1363 adastart(struct cam_periph *periph, union ccb *start_ccb)
1364 {
1365         struct ada_softc *softc = (struct ada_softc *)periph->softc;
1366         struct ccb_ataio *ataio = &start_ccb->ataio;
1367
1368         CAM_DEBUG(periph->path, CAM_DEBUG_TRACE, ("adastart\n"));
1369
1370         switch (softc->state) {
1371         case ADA_STATE_NORMAL:
1372         {
1373                 struct bio *bp;
1374                 u_int8_t tag_code;
1375
1376                 /* Execute immediate CCB if waiting. */
1377                 if (periph->immediate_priority <= periph->pinfo.priority) {
1378                         CAM_DEBUG(periph->path, CAM_DEBUG_SUBTRACE,
1379                                         ("queuing for immediate ccb\n"));
1380                         start_ccb->ccb_h.ccb_state = ADA_CCB_WAITING;
1381                         SLIST_INSERT_HEAD(&periph->ccb_list, &start_ccb->ccb_h,
1382                                           periph_links.sle);
1383                         periph->immediate_priority = CAM_PRIORITY_NONE;
1384                         wakeup(&periph->ccb_list);
1385                         /* Have more work to do, so ensure we stay scheduled */
1386                         adaschedule(periph);
1387                         break;
1388                 }
1389                 /* Run TRIM if not running yet. */
1390                 if (!softc->trim_running &&
1391                     (bp = bioq_first(&softc->trim_queue)) != 0) {
1392                         struct trim_request *req = &softc->trim_req;
1393                         struct bio *bp1;
1394                         uint64_t lastlba = (uint64_t)-1;
1395                         int bps = 0, c, lastcount = 0, off, ranges = 0;
1396
1397                         softc->trim_running = 1;
1398                         bzero(req, sizeof(*req));
1399                         bp1 = bp;
1400                         do {
1401                                 uint64_t lba = bp1->bio_pblkno;
1402                                 int count = bp1->bio_bcount /
1403                                     softc->params.secsize;
1404
1405                                 bioq_remove(&softc->trim_queue, bp1);
1406
1407                                 /* Try to extend the previous range. */
1408                                 if (lba == lastlba) {
1409                                         c = min(count, ATA_DSM_RANGE_MAX - lastcount);
1410                                         lastcount += c;
1411                                         off = (ranges - 1) * ATA_DSM_RANGE_SIZE;
1412                                         req->data[off + 6] = lastcount & 0xff;
1413                                         req->data[off + 7] =
1414                                             (lastcount >> 8) & 0xff;
1415                                         count -= c;
1416                                         lba += c;
1417                                 }
1418
1419                                 while (count > 0) {
1420                                         c = min(count, ATA_DSM_RANGE_MAX);
1421                                         off = ranges * ATA_DSM_RANGE_SIZE;
1422                                         req->data[off + 0] = lba & 0xff;
1423                                         req->data[off + 1] = (lba >> 8) & 0xff;
1424                                         req->data[off + 2] = (lba >> 16) & 0xff;
1425                                         req->data[off + 3] = (lba >> 24) & 0xff;
1426                                         req->data[off + 4] = (lba >> 32) & 0xff;
1427                                         req->data[off + 5] = (lba >> 40) & 0xff;
1428                                         req->data[off + 6] = c & 0xff;
1429                                         req->data[off + 7] = (c >> 8) & 0xff;
1430                                         lba += c;
1431                                         count -= c;
1432                                         lastcount = c;
1433                                         ranges++;
1434                                         /*
1435                                          * Its the caller's responsibility to ensure the
1436                                          * request will fit so we don't need to check for
1437                                          * overrun here
1438                                          */
1439                                 }
1440                                 lastlba = lba;
1441                                 req->bps[bps++] = bp1;
1442                                 bp1 = bioq_first(&softc->trim_queue);
1443                                 if (bps >= TRIM_MAX_BIOS ||
1444                                     bp1 == NULL ||
1445                                     bp1->bio_bcount / softc->params.secsize >
1446                                     (softc->trim_max_ranges - ranges) *
1447                                     ATA_DSM_RANGE_MAX)
1448                                         break;
1449                         } while (1);
1450                         cam_fill_ataio(ataio,
1451                             ada_retry_count,
1452                             adadone,
1453                             CAM_DIR_OUT,
1454                             0,
1455                             req->data,
1456                             ((ranges + ATA_DSM_BLK_RANGES - 1) /
1457                                 ATA_DSM_BLK_RANGES) * ATA_DSM_BLK_SIZE,
1458                             ada_default_timeout * 1000);
1459                         ata_48bit_cmd(ataio, ATA_DATA_SET_MANAGEMENT,
1460                             ATA_DSM_TRIM, 0, (ranges + ATA_DSM_BLK_RANGES -
1461                             1) / ATA_DSM_BLK_RANGES);
1462                         start_ccb->ccb_h.ccb_state = ADA_CCB_TRIM;
1463                         goto out;
1464                 }
1465                 /* Run regular command. */
1466                 bp = bioq_first(&softc->bio_queue);
1467                 if (bp == NULL) {
1468                         xpt_release_ccb(start_ccb);
1469                         break;
1470                 }
1471                 bioq_remove(&softc->bio_queue, bp);
1472
1473                 if ((bp->bio_flags & BIO_ORDERED) != 0
1474                  || (softc->flags & ADA_FLAG_NEED_OTAG) != 0) {
1475                         softc->flags &= ~ADA_FLAG_NEED_OTAG;
1476                         softc->ordered_tag_count++;
1477                         tag_code = 0;
1478                 } else {
1479                         tag_code = 1;
1480                 }
1481                 switch (bp->bio_cmd) {
1482                 case BIO_READ:
1483                 case BIO_WRITE:
1484                 {
1485                         uint64_t lba = bp->bio_pblkno;
1486                         uint16_t count = bp->bio_bcount / softc->params.secsize;
1487 #ifdef ADA_TEST_FAILURE
1488                         int fail = 0;
1489
1490                         /*
1491                          * Support the failure ioctls.  If the command is a
1492                          * read, and there are pending forced read errors, or
1493                          * if a write and pending write errors, then fail this
1494                          * operation with EIO.  This is useful for testing
1495                          * purposes.  Also, support having every Nth read fail.
1496                          *
1497                          * This is a rather blunt tool.
1498                          */
1499                         if (bp->bio_cmd == BIO_READ) {
1500                                 if (softc->force_read_error) {
1501                                         softc->force_read_error--;
1502                                         fail = 1;
1503                                 }
1504                                 if (softc->periodic_read_error > 0) {
1505                                         if (++softc->periodic_read_count >=
1506                                             softc->periodic_read_error) {
1507                                                 softc->periodic_read_count = 0;
1508                                                 fail = 1;
1509                                         }
1510                                 }
1511                         } else {
1512                                 if (softc->force_write_error) {
1513                                         softc->force_write_error--;
1514                                         fail = 1;
1515                                 }
1516                         }
1517                         if (fail) {
1518                                 bp->bio_error = EIO;
1519                                 bp->bio_flags |= BIO_ERROR;
1520                                 biodone(bp);
1521                                 xpt_release_ccb(start_ccb);
1522                                 adaschedule(periph);
1523                                 return;
1524                         }
1525 #endif
1526                         cam_fill_ataio(ataio,
1527                             ada_retry_count,
1528                             adadone,
1529                             bp->bio_cmd == BIO_READ ?
1530                                 CAM_DIR_IN : CAM_DIR_OUT,
1531                             tag_code,
1532                             bp->bio_data,
1533                             bp->bio_bcount,
1534                             ada_default_timeout*1000);
1535
1536                         if ((softc->flags & ADA_FLAG_CAN_NCQ) && tag_code) {
1537                                 if (bp->bio_cmd == BIO_READ) {
1538                                         ata_ncq_cmd(ataio, ATA_READ_FPDMA_QUEUED,
1539                                             lba, count);
1540                                 } else {
1541                                         ata_ncq_cmd(ataio, ATA_WRITE_FPDMA_QUEUED,
1542                                             lba, count);
1543                                 }
1544                         } else if ((softc->flags & ADA_FLAG_CAN_48BIT) &&
1545                             (lba + count >= ATA_MAX_28BIT_LBA ||
1546                             count > 256)) {
1547                                 if (softc->flags & ADA_FLAG_CAN_DMA48) {
1548                                         if (bp->bio_cmd == BIO_READ) {
1549                                                 ata_48bit_cmd(ataio, ATA_READ_DMA48,
1550                                                     0, lba, count);
1551                                         } else {
1552                                                 ata_48bit_cmd(ataio, ATA_WRITE_DMA48,
1553                                                     0, lba, count);
1554                                         }
1555                                 } else {
1556                                         if (bp->bio_cmd == BIO_READ) {
1557                                                 ata_48bit_cmd(ataio, ATA_READ_MUL48,
1558                                                     0, lba, count);
1559                                         } else {
1560                                                 ata_48bit_cmd(ataio, ATA_WRITE_MUL48,
1561                                                     0, lba, count);
1562                                         }
1563                                 }
1564                         } else {
1565                                 if (count == 256)
1566                                         count = 0;
1567                                 if (softc->flags & ADA_FLAG_CAN_DMA) {
1568                                         if (bp->bio_cmd == BIO_READ) {
1569                                                 ata_28bit_cmd(ataio, ATA_READ_DMA,
1570                                                     0, lba, count);
1571                                         } else {
1572                                                 ata_28bit_cmd(ataio, ATA_WRITE_DMA,
1573                                                     0, lba, count);
1574                                         }
1575                                 } else {
1576                                         if (bp->bio_cmd == BIO_READ) {
1577                                                 ata_28bit_cmd(ataio, ATA_READ_MUL,
1578                                                     0, lba, count);
1579                                         } else {
1580                                                 ata_28bit_cmd(ataio, ATA_WRITE_MUL,
1581                                                     0, lba, count);
1582                                         }
1583                                 }
1584                         }
1585                         break;
1586                 }
1587                 case BIO_DELETE:
1588                 {
1589                         uint64_t lba = bp->bio_pblkno;
1590                         uint16_t count = bp->bio_bcount / softc->params.secsize;
1591
1592                         cam_fill_ataio(ataio,
1593                             ada_retry_count,
1594                             adadone,
1595                             CAM_DIR_NONE,
1596                             0,
1597                             NULL,
1598                             0,
1599                             ada_default_timeout*1000);
1600
1601                         if (count >= 256)
1602                                 count = 0;
1603                         ata_28bit_cmd(ataio, ATA_CFA_ERASE, 0, lba, count);
1604                         break;
1605                 }
1606                 case BIO_FLUSH:
1607                         cam_fill_ataio(ataio,
1608                             1,
1609                             adadone,
1610                             CAM_DIR_NONE,
1611                             0,
1612                             NULL,
1613                             0,
1614                             ada_default_timeout*1000);
1615
1616                         if (softc->flags & ADA_FLAG_CAN_48BIT)
1617                                 ata_48bit_cmd(ataio, ATA_FLUSHCACHE48, 0, 0, 0);
1618                         else
1619                                 ata_28bit_cmd(ataio, ATA_FLUSHCACHE, 0, 0, 0);
1620                         break;
1621                 }
1622                 start_ccb->ccb_h.ccb_state = ADA_CCB_BUFFER_IO;
1623 out:
1624                 start_ccb->ccb_h.ccb_bp = bp;
1625                 softc->outstanding_cmds++;
1626                 xpt_action(start_ccb);
1627
1628                 /* May have more work to do, so ensure we stay scheduled */
1629                 adaschedule(periph);
1630                 break;
1631         }
1632         case ADA_STATE_RAHEAD:
1633         case ADA_STATE_WCACHE:
1634         {
1635                 if (softc->flags & ADA_FLAG_PACK_INVALID) {
1636                         softc->state = ADA_STATE_NORMAL;
1637                         xpt_release_ccb(start_ccb);
1638                         cam_release_devq(periph->path,
1639                             RELSIM_RELEASE_RUNLEVEL, 0, CAM_RL_DEV + 1, FALSE);
1640                         adaschedule(periph);
1641                         cam_periph_release_locked(periph);
1642                         return;
1643                 }
1644
1645                 cam_fill_ataio(ataio,
1646                     1,
1647                     adadone,
1648                     CAM_DIR_NONE,
1649                     0,
1650                     NULL,
1651                     0,
1652                     ada_default_timeout*1000);
1653
1654                 if (softc->state == ADA_STATE_RAHEAD) {
1655                         ata_28bit_cmd(ataio, ATA_SETFEATURES, ADA_RA ?
1656                             ATA_SF_ENAB_RCACHE : ATA_SF_DIS_RCACHE, 0, 0);
1657                         start_ccb->ccb_h.ccb_state = ADA_CCB_RAHEAD;
1658                 } else {
1659                         ata_28bit_cmd(ataio, ATA_SETFEATURES, ADA_WC ?
1660                             ATA_SF_ENAB_WCACHE : ATA_SF_DIS_WCACHE, 0, 0);
1661                         start_ccb->ccb_h.ccb_state = ADA_CCB_WCACHE;
1662                 }
1663                 xpt_action(start_ccb);
1664                 break;
1665         }
1666         }
1667 }
1668
1669 static void
1670 adadone(struct cam_periph *periph, union ccb *done_ccb)
1671 {
1672         struct ada_softc *softc;
1673         struct ccb_ataio *ataio;
1674         struct ccb_getdev *cgd;
1675
1676         softc = (struct ada_softc *)periph->softc;
1677         ataio = &done_ccb->ataio;
1678
1679         CAM_DEBUG(periph->path, CAM_DEBUG_TRACE, ("adadone\n"));
1680
1681         switch (ataio->ccb_h.ccb_state & ADA_CCB_TYPE_MASK) {
1682         case ADA_CCB_BUFFER_IO:
1683         case ADA_CCB_TRIM:
1684         {
1685                 struct bio *bp;
1686
1687                 bp = (struct bio *)done_ccb->ccb_h.ccb_bp;
1688                 if ((done_ccb->ccb_h.status & CAM_STATUS_MASK) != CAM_REQ_CMP) {
1689                         int error;
1690                         
1691                         error = adaerror(done_ccb, 0, 0);
1692                         if (error == ERESTART) {
1693                                 /* A retry was scheduled, so just return. */
1694                                 return;
1695                         }
1696                         if (error != 0) {
1697                                 if (error == ENXIO &&
1698                                     (softc->flags & ADA_FLAG_PACK_INVALID) == 0) {
1699                                         /*
1700                                          * Catastrophic error.  Mark our pack as
1701                                          * invalid.
1702                                          */
1703                                         /*
1704                                          * XXX See if this is really a media
1705                                          * XXX change first?
1706                                          */
1707                                         xpt_print(periph->path,
1708                                             "Invalidating pack\n");
1709                                         softc->flags |= ADA_FLAG_PACK_INVALID;
1710                                 }
1711                                 bp->bio_error = error;
1712                                 bp->bio_resid = bp->bio_bcount;
1713                                 bp->bio_flags |= BIO_ERROR;
1714                         } else {
1715                                 bp->bio_resid = ataio->resid;
1716                                 bp->bio_error = 0;
1717                                 if (bp->bio_resid != 0)
1718                                         bp->bio_flags |= BIO_ERROR;
1719                         }
1720                         if ((done_ccb->ccb_h.status & CAM_DEV_QFRZN) != 0)
1721                                 cam_release_devq(done_ccb->ccb_h.path,
1722                                                  /*relsim_flags*/0,
1723                                                  /*reduction*/0,
1724                                                  /*timeout*/0,
1725                                                  /*getcount_only*/0);
1726                 } else {
1727                         if ((done_ccb->ccb_h.status & CAM_DEV_QFRZN) != 0)
1728                                 panic("REQ_CMP with QFRZN");
1729                         bp->bio_resid = ataio->resid;
1730                         if (ataio->resid > 0)
1731                                 bp->bio_flags |= BIO_ERROR;
1732                 }
1733                 softc->outstanding_cmds--;
1734                 if (softc->outstanding_cmds == 0)
1735                         softc->flags |= ADA_FLAG_WENT_IDLE;
1736                 if ((ataio->ccb_h.ccb_state & ADA_CCB_TYPE_MASK) ==
1737                     ADA_CCB_TRIM) {
1738                         struct trim_request *req =
1739                             (struct trim_request *)ataio->data_ptr;
1740                         int i;
1741
1742                         for (i = 1; i < TRIM_MAX_BIOS && req->bps[i]; i++) {
1743                                 struct bio *bp1 = req->bps[i];
1744                                 
1745                                 bp1->bio_resid = bp->bio_resid;
1746                                 bp1->bio_error = bp->bio_error;
1747                                 if (bp->bio_flags & BIO_ERROR)
1748                                         bp1->bio_flags |= BIO_ERROR;
1749                                 biodone(bp1);
1750                         }
1751                         softc->trim_running = 0;
1752                         biodone(bp);
1753                         adaschedule(periph);
1754                 } else
1755                         biodone(bp);
1756                 break;
1757         }
1758         case ADA_CCB_RAHEAD:
1759         {
1760                 if ((done_ccb->ccb_h.status & CAM_STATUS_MASK) != CAM_REQ_CMP) {
1761                         if (adaerror(done_ccb, 0, 0) == ERESTART) {
1762                                 return;
1763                         } else if ((done_ccb->ccb_h.status & CAM_DEV_QFRZN) != 0) {
1764                                 cam_release_devq(done_ccb->ccb_h.path,
1765                                     /*relsim_flags*/0,
1766                                     /*reduction*/0,
1767                                     /*timeout*/0,
1768                                     /*getcount_only*/0);
1769                         }
1770                 }
1771
1772                 /*
1773                  * Since our peripheral may be invalidated by an error
1774                  * above or an external event, we must release our CCB
1775                  * before releasing the reference on the peripheral.
1776                  * The peripheral will only go away once the last reference
1777                  * is removed, and we need it around for the CCB release
1778                  * operation.
1779                  */
1780                 cgd = (struct ccb_getdev *)done_ccb;
1781                 xpt_setup_ccb(&cgd->ccb_h, periph->path, CAM_PRIORITY_NORMAL);
1782                 cgd->ccb_h.func_code = XPT_GDEV_TYPE;
1783                 xpt_action((union ccb *)cgd);
1784                 if (ADA_WC >= 0 &&
1785                     cgd->ident_data.support.command1 & ATA_SUPPORT_WRITECACHE) {
1786                         softc->state = ADA_STATE_WCACHE;
1787                         xpt_release_ccb(done_ccb);
1788                         xpt_schedule(periph, CAM_PRIORITY_DEV);
1789                         return;
1790                 }
1791                 softc->state = ADA_STATE_NORMAL;
1792                 xpt_release_ccb(done_ccb);
1793                 cam_release_devq(periph->path,
1794                     RELSIM_RELEASE_RUNLEVEL, 0, CAM_RL_DEV + 1, FALSE);
1795                 adaschedule(periph);
1796                 cam_periph_release_locked(periph);
1797                 return;
1798         }
1799         case ADA_CCB_WCACHE:
1800         {
1801                 if ((done_ccb->ccb_h.status & CAM_STATUS_MASK) != CAM_REQ_CMP) {
1802                         if (adaerror(done_ccb, 0, 0) == ERESTART) {
1803                                 return;
1804                         } else if ((done_ccb->ccb_h.status & CAM_DEV_QFRZN) != 0) {
1805                                 cam_release_devq(done_ccb->ccb_h.path,
1806                                     /*relsim_flags*/0,
1807                                     /*reduction*/0,
1808                                     /*timeout*/0,
1809                                     /*getcount_only*/0);
1810                         }
1811                 }
1812
1813                 softc->state = ADA_STATE_NORMAL;
1814                 /*
1815                  * Since our peripheral may be invalidated by an error
1816                  * above or an external event, we must release our CCB
1817                  * before releasing the reference on the peripheral.
1818                  * The peripheral will only go away once the last reference
1819                  * is removed, and we need it around for the CCB release
1820                  * operation.
1821                  */
1822                 xpt_release_ccb(done_ccb);
1823                 cam_release_devq(periph->path,
1824                     RELSIM_RELEASE_RUNLEVEL, 0, CAM_RL_DEV + 1, FALSE);
1825                 adaschedule(periph);
1826                 cam_periph_release_locked(periph);
1827                 return;
1828         }
1829         case ADA_CCB_WAITING:
1830         {
1831                 /* Caller will release the CCB */
1832                 wakeup(&done_ccb->ccb_h.cbfcnp);
1833                 return;
1834         }
1835         case ADA_CCB_DUMP:
1836                 /* No-op.  We're polling */
1837                 return;
1838         default:
1839                 break;
1840         }
1841         xpt_release_ccb(done_ccb);
1842 }
1843
1844 static int
1845 adaerror(union ccb *ccb, u_int32_t cam_flags, u_int32_t sense_flags)
1846 {
1847
1848         return(cam_periph_error(ccb, cam_flags, sense_flags, NULL));
1849 }
1850
1851 static void
1852 adagetparams(struct cam_periph *periph, struct ccb_getdev *cgd)
1853 {
1854         struct ada_softc *softc = (struct ada_softc *)periph->softc;
1855         struct disk_params *dp = &softc->params;
1856         u_int64_t lbasize48;
1857         u_int32_t lbasize;
1858
1859         dp->secsize = ata_logical_sector_size(&cgd->ident_data);
1860         if ((cgd->ident_data.atavalid & ATA_FLAG_54_58) &&
1861                 cgd->ident_data.current_heads && cgd->ident_data.current_sectors) {
1862                 dp->heads = cgd->ident_data.current_heads;
1863                 dp->secs_per_track = cgd->ident_data.current_sectors;
1864                 dp->cylinders = cgd->ident_data.cylinders;
1865                 dp->sectors = (u_int32_t)cgd->ident_data.current_size_1 |
1866                           ((u_int32_t)cgd->ident_data.current_size_2 << 16);
1867         } else {
1868                 dp->heads = cgd->ident_data.heads;
1869                 dp->secs_per_track = cgd->ident_data.sectors;
1870                 dp->cylinders = cgd->ident_data.cylinders;
1871                 dp->sectors = cgd->ident_data.cylinders * dp->heads * dp->secs_per_track;  
1872         }
1873         lbasize = (u_int32_t)cgd->ident_data.lba_size_1 |
1874                   ((u_int32_t)cgd->ident_data.lba_size_2 << 16);
1875
1876         /* use the 28bit LBA size if valid or bigger than the CHS mapping */
1877         if (cgd->ident_data.cylinders == 16383 || dp->sectors < lbasize)
1878                 dp->sectors = lbasize;
1879
1880         /* use the 48bit LBA size if valid */
1881         lbasize48 = ((u_int64_t)cgd->ident_data.lba_size48_1) |
1882                     ((u_int64_t)cgd->ident_data.lba_size48_2 << 16) |
1883                     ((u_int64_t)cgd->ident_data.lba_size48_3 << 32) |
1884                     ((u_int64_t)cgd->ident_data.lba_size48_4 << 48);
1885         if ((cgd->ident_data.support.command2 & ATA_SUPPORT_ADDRESS48) &&
1886             lbasize48 > ATA_MAX_28BIT_LBA)
1887                 dp->sectors = lbasize48;
1888 }
1889
1890 static void
1891 adasendorderedtag(void *arg)
1892 {
1893         struct ada_softc *softc = arg;
1894
1895         if (ada_send_ordered) {
1896                 if ((softc->ordered_tag_count == 0) 
1897                  && ((softc->flags & ADA_FLAG_WENT_IDLE) == 0)) {
1898                         softc->flags |= ADA_FLAG_NEED_OTAG;
1899                 }
1900                 if (softc->outstanding_cmds > 0)
1901                         softc->flags &= ~ADA_FLAG_WENT_IDLE;
1902
1903                 softc->ordered_tag_count = 0;
1904         }
1905         /* Queue us up again */
1906         callout_reset(&softc->sendordered_c,
1907             (ada_default_timeout * hz) / ADA_ORDEREDTAG_INTERVAL,
1908             adasendorderedtag, softc);
1909 }
1910
1911 /*
1912  * Step through all ADA peripheral drivers, and if the device is still open,
1913  * sync the disk cache to physical media.
1914  */
1915 static void
1916 adaflush(void)
1917 {
1918         struct cam_periph *periph;
1919         struct ada_softc *softc;
1920         union ccb *ccb;
1921         int error;
1922
1923         CAM_PERIPH_FOREACH(periph, &adadriver) {
1924                 /* If we paniced with lock held - not recurse here. */
1925                 if (cam_periph_owned(periph))
1926                         continue;
1927                 cam_periph_lock(periph);
1928                 softc = (struct ada_softc *)periph->softc;
1929                 /*
1930                  * We only sync the cache if the drive is still open, and
1931                  * if the drive is capable of it..
1932                  */
1933                 if (((softc->flags & ADA_FLAG_OPEN) == 0) ||
1934                     (softc->flags & ADA_FLAG_CAN_FLUSHCACHE) == 0) {
1935                         cam_periph_unlock(periph);
1936                         continue;
1937                 }
1938
1939                 ccb = cam_periph_getccb(periph, CAM_PRIORITY_NORMAL);
1940                 cam_fill_ataio(&ccb->ataio,
1941                                     0,
1942                                     adadone,
1943                                     CAM_DIR_NONE,
1944                                     0,
1945                                     NULL,
1946                                     0,
1947                                     ada_default_timeout*1000);
1948                 if (softc->flags & ADA_FLAG_CAN_48BIT)
1949                         ata_48bit_cmd(&ccb->ataio, ATA_FLUSHCACHE48, 0, 0, 0);
1950                 else
1951                         ata_28bit_cmd(&ccb->ataio, ATA_FLUSHCACHE, 0, 0, 0);
1952
1953                 error = cam_periph_runccb(ccb, adaerror, /*cam_flags*/0,
1954                     /*sense_flags*/ SF_NO_RECOVERY | SF_NO_RETRY,
1955                     softc->disk->d_devstat);
1956                 if (error != 0)
1957                         xpt_print(periph->path, "Synchronize cache failed\n");
1958                 xpt_release_ccb(ccb);
1959                 cam_periph_unlock(periph);
1960         }
1961 }
1962
1963 static void
1964 adaspindown(uint8_t cmd, int flags)
1965 {
1966         struct cam_periph *periph;
1967         struct ada_softc *softc;
1968         union ccb *ccb;
1969         int error;
1970
1971         CAM_PERIPH_FOREACH(periph, &adadriver) {
1972                 /* If we paniced with lock held - not recurse here. */
1973                 if (cam_periph_owned(periph))
1974                         continue;
1975                 cam_periph_lock(periph);
1976                 softc = (struct ada_softc *)periph->softc;
1977                 /*
1978                  * We only spin-down the drive if it is capable of it..
1979                  */
1980                 if ((softc->flags & ADA_FLAG_CAN_POWERMGT) == 0) {
1981                         cam_periph_unlock(periph);
1982                         continue;
1983                 }
1984
1985                 if (bootverbose)
1986                         xpt_print(periph->path, "spin-down\n");
1987
1988                 ccb = cam_periph_getccb(periph, CAM_PRIORITY_NORMAL);
1989                 cam_fill_ataio(&ccb->ataio,
1990                                     0,
1991                                     adadone,
1992                                     CAM_DIR_NONE | flags,
1993                                     0,
1994                                     NULL,
1995                                     0,
1996                                     ada_default_timeout*1000);
1997                 ata_28bit_cmd(&ccb->ataio, cmd, 0, 0, 0);
1998
1999                 error = cam_periph_runccb(ccb, adaerror, /*cam_flags*/0,
2000                     /*sense_flags*/ SF_NO_RECOVERY | SF_NO_RETRY,
2001                     softc->disk->d_devstat);
2002                 if (error != 0)
2003                         xpt_print(periph->path, "Spin-down disk failed\n");
2004                 xpt_release_ccb(ccb);
2005                 cam_periph_unlock(periph);
2006         }
2007 }
2008
2009 static void
2010 adashutdown(void *arg, int howto)
2011 {
2012
2013         adaflush();
2014         if (ada_spindown_shutdown != 0 &&
2015             (howto & (RB_HALT | RB_POWEROFF)) != 0)
2016                 adaspindown(ATA_STANDBY_IMMEDIATE, 0);
2017 }
2018
2019 static void
2020 adasuspend(void *arg)
2021 {
2022
2023         adaflush();
2024         if (ada_spindown_suspend != 0)
2025                 adaspindown(ATA_SLEEP, CAM_DEV_QFREEZE);
2026 }
2027
2028 static void
2029 adaresume(void *arg)
2030 {
2031         struct cam_periph *periph;
2032         struct ada_softc *softc;
2033
2034         if (ada_spindown_suspend == 0)
2035                 return;
2036
2037         CAM_PERIPH_FOREACH(periph, &adadriver) {
2038                 cam_periph_lock(periph);
2039                 softc = (struct ada_softc *)periph->softc;
2040                 /*
2041                  * We only spin-down the drive if it is capable of it..
2042                  */
2043                 if ((softc->flags & ADA_FLAG_CAN_POWERMGT) == 0) {
2044                         cam_periph_unlock(periph);
2045                         continue;
2046                 }
2047
2048                 if (bootverbose)
2049                         xpt_print(periph->path, "resume\n");
2050
2051                 /*
2052                  * Drop freeze taken due to CAM_DEV_QFREEZE flag set on
2053                  * sleep request.
2054                  */
2055                 cam_release_devq(periph->path,
2056                          /*relsim_flags*/0,
2057                          /*openings*/0,
2058                          /*timeout*/0,
2059                          /*getcount_only*/0);
2060                 
2061                 cam_periph_unlock(periph);
2062         }
2063 }
2064
2065 #endif /* _KERNEL */