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