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