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