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