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