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