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