]> CyberLeo.Net >> Repos - FreeBSD/stable/9.git/blob - sys/cam/scsi/scsi_da.c
MFC r250792:
[FreeBSD/stable/9.git] / sys / cam / scsi / scsi_da.c
1 /*-
2  * Implementation of SCSI Direct Access Peripheral driver for CAM.
3  *
4  * Copyright (c) 1997 Justin T. Gibbs.
5  * All rights reserved.
6  *
7  * Redistribution and use in source and binary forms, with or without
8  * modification, are permitted provided that the following conditions
9  * are met:
10  * 1. Redistributions of source code must retain the above copyright
11  *    notice, this list of conditions, and the following disclaimer,
12  *    without modification, immediately at the beginning of the file.
13  * 2. The name of the author may not be used to endorse or promote products
14  *    derived from this software without specific prior written permission.
15  *
16  * THIS SOFTWARE IS PROVIDED BY THE AUTHOR AND CONTRIBUTORS ``AS IS'' AND
17  * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
18  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
19  * ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE FOR
20  * ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
21  * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
22  * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
23  * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
24  * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
25  * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
26  * SUCH DAMAGE.
27  */
28
29 #include <sys/cdefs.h>
30 __FBSDID("$FreeBSD$");
31
32 #include <sys/param.h>
33
34 #ifdef _KERNEL
35 #include <sys/systm.h>
36 #include <sys/kernel.h>
37 #include <sys/bio.h>
38 #include <sys/sysctl.h>
39 #include <sys/taskqueue.h>
40 #include <sys/lock.h>
41 #include <sys/mutex.h>
42 #include <sys/conf.h>
43 #include <sys/devicestat.h>
44 #include <sys/eventhandler.h>
45 #include <sys/malloc.h>
46 #include <sys/cons.h>
47 #include <sys/endian.h>
48 #include <geom/geom.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/scsi/scsi_message.h>
64
65 #ifndef _KERNEL 
66 #include <cam/scsi/scsi_da.h>
67 #endif /* !_KERNEL */
68
69 #ifdef _KERNEL
70 typedef enum {
71         DA_STATE_PROBE_RC,
72         DA_STATE_PROBE_RC16,
73         DA_STATE_PROBE_LBP,
74         DA_STATE_PROBE_BLK_LIMITS,
75         DA_STATE_PROBE_BDC,
76         DA_STATE_PROBE_ATA,
77         DA_STATE_NORMAL
78 } da_state;
79
80 typedef enum {
81         DA_FLAG_PACK_INVALID    = 0x001,
82         DA_FLAG_NEW_PACK        = 0x002,
83         DA_FLAG_PACK_LOCKED     = 0x004,
84         DA_FLAG_PACK_REMOVABLE  = 0x008,
85         DA_FLAG_SAW_MEDIA       = 0x010,
86         DA_FLAG_NEED_OTAG       = 0x020,
87         DA_FLAG_WENT_IDLE       = 0x040,
88         DA_FLAG_RETRY_UA        = 0x080,
89         DA_FLAG_OPEN            = 0x100,
90         DA_FLAG_SCTX_INIT       = 0x200,
91         DA_FLAG_CAN_RC16        = 0x400,
92         DA_FLAG_PROBED          = 0x800         
93 } da_flags;
94
95 typedef enum {
96         DA_Q_NONE               = 0x00,
97         DA_Q_NO_SYNC_CACHE      = 0x01,
98         DA_Q_NO_6_BYTE          = 0x02,
99         DA_Q_NO_PREVENT         = 0x04,
100         DA_Q_4K                 = 0x08
101 } da_quirks;
102
103 #define DA_Q_BIT_STRING         \
104         "\020"                  \
105         "\001NO_SYNC_CACHE"     \
106         "\002NO_6_BYTE"         \
107         "\003NO_PREVENT"        \
108         "\0044K"
109
110 typedef enum {
111         DA_CCB_PROBE_RC         = 0x01,
112         DA_CCB_PROBE_RC16       = 0x02,
113         DA_CCB_PROBE_LBP        = 0x03,
114         DA_CCB_PROBE_BLK_LIMITS = 0x04,
115         DA_CCB_PROBE_BDC        = 0x05,
116         DA_CCB_PROBE_ATA        = 0x06,
117         DA_CCB_BUFFER_IO        = 0x07,
118         DA_CCB_WAITING          = 0x08,
119         DA_CCB_DUMP             = 0x0A,
120         DA_CCB_DELETE           = 0x0B,
121         DA_CCB_TUR              = 0x0C,
122         DA_CCB_TYPE_MASK        = 0x0F,
123         DA_CCB_RETRY_UA         = 0x10
124 } da_ccb_state;
125
126 /*
127  * Order here is important for method choice
128  *
129  * We prefer ATA_TRIM as tests run against a Sandforce 2281 SSD attached to
130  * LSI 2008 (mps) controller (FW: v12, Drv: v14) resulted 20% quicker deletes
131  * using ATA_TRIM than the corresponding UNMAP results for a real world mysql
132  * import taking 5mins.
133  *
134  */
135 typedef enum {
136         DA_DELETE_NONE,
137         DA_DELETE_DISABLE,
138         DA_DELETE_ATA_TRIM,
139         DA_DELETE_UNMAP,
140         DA_DELETE_WS16,
141         DA_DELETE_WS10,
142         DA_DELETE_ZERO,
143         DA_DELETE_MIN = DA_DELETE_ATA_TRIM,
144         DA_DELETE_MAX = DA_DELETE_ZERO
145 } da_delete_methods;
146
147 static const char *da_delete_method_names[] =
148     { "NONE", "DISABLE", "ATA_TRIM", "UNMAP", "WS16", "WS10", "ZERO" };
149 static const char *da_delete_method_desc[] =
150     { "NONE", "DISABLED", "ATA TRIM", "UNMAP", "WRITE SAME(16) with UNMAP",
151       "WRITE SAME(10) with UNMAP", "ZERO" };
152
153 /* Offsets into our private area for storing information */
154 #define ccb_state       ppriv_field0
155 #define ccb_bp          ppriv_ptr1
156
157 struct disk_params {
158         u_int8_t  heads;
159         u_int32_t cylinders;
160         u_int8_t  secs_per_track;
161         u_int32_t secsize;      /* Number of bytes/sector */
162         u_int64_t sectors;      /* total number sectors */
163         u_int     stripesize;
164         u_int     stripeoffset;
165 };
166
167 #define UNMAP_RANGE_MAX         0xffffffff
168 #define UNMAP_HEAD_SIZE         8
169 #define UNMAP_RANGE_SIZE        16
170 #define UNMAP_MAX_RANGES        2048 /* Protocol Max is 4095 */
171 #define UNMAP_BUF_SIZE          ((UNMAP_MAX_RANGES * UNMAP_RANGE_SIZE) + \
172                                 UNMAP_HEAD_SIZE)
173
174 #define WS10_MAX_BLKS           0xffff
175 #define WS16_MAX_BLKS           0xffffffff
176 #define ATA_TRIM_MAX_RANGES     ((UNMAP_BUF_SIZE / \
177         (ATA_DSM_RANGE_SIZE * ATA_DSM_BLK_SIZE)) * ATA_DSM_BLK_SIZE)
178
179 struct da_softc {
180         struct   bio_queue_head bio_queue;
181         struct   bio_queue_head delete_queue;
182         struct   bio_queue_head delete_run_queue;
183         SLIST_ENTRY(da_softc) links;
184         LIST_HEAD(, ccb_hdr) pending_ccbs;
185         da_state state;
186         da_flags flags; 
187         da_quirks quirks;
188         int      sort_io_queue;
189         int      minimum_cmd_size;
190         int      error_inject;
191         int      ordered_tag_count;
192         int      outstanding_cmds;
193         int      trim_max_ranges;
194         int      delete_running;
195         int      tur;
196         int      delete_available;      /* Delete methods possibly available */
197         uint32_t                unmap_max_ranges;
198         uint32_t                unmap_max_lba;
199         uint64_t                ws_max_blks;
200         da_delete_methods       delete_method;
201         struct   disk_params params;
202         struct   disk *disk;
203         union    ccb saved_ccb;
204         struct task             sysctl_task;
205         struct sysctl_ctx_list  sysctl_ctx;
206         struct sysctl_oid       *sysctl_tree;
207         struct callout          sendordered_c;
208         uint64_t wwpn;
209         uint8_t  unmap_buf[UNMAP_BUF_SIZE];
210         struct scsi_read_capacity_data_long rcaplong;
211         struct callout          mediapoll_c;
212 };
213
214 #define dadeleteflag(softc, delete_method, enable)                      \
215         if (enable) {                                                   \
216                 softc->delete_available |= (1 << delete_method);        \
217         } else {                                                        \
218                 softc->delete_available &= ~(1 << delete_method);       \
219         }
220
221 struct da_quirk_entry {
222         struct scsi_inquiry_pattern inq_pat;
223         da_quirks quirks;
224 };
225
226 static const char quantum[] = "QUANTUM";
227 static const char microp[] = "MICROP";
228
229 static struct da_quirk_entry da_quirk_table[] =
230 {
231         /* SPI, FC devices */
232         {
233                 /*
234                  * Fujitsu M2513A MO drives.
235                  * Tested devices: M2513A2 firmware versions 1200 & 1300.
236                  * (dip switch selects whether T_DIRECT or T_OPTICAL device)
237                  * Reported by: W.Scholten <whs@xs4all.nl>
238                  */
239                 {T_DIRECT, SIP_MEDIA_REMOVABLE, "FUJITSU", "M2513A", "*"},
240                 /*quirks*/ DA_Q_NO_SYNC_CACHE
241         },
242         {
243                 /* See above. */
244                 {T_OPTICAL, SIP_MEDIA_REMOVABLE, "FUJITSU", "M2513A", "*"},
245                 /*quirks*/ DA_Q_NO_SYNC_CACHE
246         },
247         {
248                 /*
249                  * This particular Fujitsu drive doesn't like the
250                  * synchronize cache command.
251                  * Reported by: Tom Jackson <toj@gorilla.net>
252                  */
253                 {T_DIRECT, SIP_MEDIA_FIXED, "FUJITSU", "M2954*", "*"},
254                 /*quirks*/ DA_Q_NO_SYNC_CACHE
255         },
256         {
257                 /*
258                  * This drive doesn't like the synchronize cache command
259                  * either.  Reported by: Matthew Jacob <mjacob@feral.com>
260                  * in NetBSD PR kern/6027, August 24, 1998.
261                  */
262                 {T_DIRECT, SIP_MEDIA_FIXED, microp, "2217*", "*"},
263                 /*quirks*/ DA_Q_NO_SYNC_CACHE
264         },
265         {
266                 /*
267                  * This drive doesn't like the synchronize cache command
268                  * either.  Reported by: Hellmuth Michaelis (hm@kts.org)
269                  * (PR 8882).
270                  */
271                 {T_DIRECT, SIP_MEDIA_FIXED, microp, "2112*", "*"},
272                 /*quirks*/ DA_Q_NO_SYNC_CACHE
273         },
274         {
275                 /*
276                  * Doesn't like the synchronize cache command.
277                  * Reported by: Blaz Zupan <blaz@gold.amis.net>
278                  */
279                 {T_DIRECT, SIP_MEDIA_FIXED, "NEC", "D3847*", "*"},
280                 /*quirks*/ DA_Q_NO_SYNC_CACHE
281         },
282         {
283                 /*
284                  * Doesn't like the synchronize cache command.
285                  * Reported by: Blaz Zupan <blaz@gold.amis.net>
286                  */
287                 {T_DIRECT, SIP_MEDIA_FIXED, quantum, "MAVERICK 540S", "*"},
288                 /*quirks*/ DA_Q_NO_SYNC_CACHE
289         },
290         {
291                 /*
292                  * Doesn't like the synchronize cache command.
293                  */
294                 {T_DIRECT, SIP_MEDIA_FIXED, quantum, "LPS525S", "*"},
295                 /*quirks*/ DA_Q_NO_SYNC_CACHE
296         },
297         {
298                 /*
299                  * Doesn't like the synchronize cache command.
300                  * Reported by: walter@pelissero.de
301                  */
302                 {T_DIRECT, SIP_MEDIA_FIXED, quantum, "LPS540S", "*"},
303                 /*quirks*/ DA_Q_NO_SYNC_CACHE
304         },
305         {
306                 /*
307                  * Doesn't work correctly with 6 byte reads/writes.
308                  * Returns illegal request, and points to byte 9 of the
309                  * 6-byte CDB.
310                  * Reported by:  Adam McDougall <bsdx@spawnet.com>
311                  */
312                 {T_DIRECT, SIP_MEDIA_FIXED, quantum, "VIKING 4*", "*"},
313                 /*quirks*/ DA_Q_NO_6_BYTE
314         },
315         {
316                 /* See above. */
317                 {T_DIRECT, SIP_MEDIA_FIXED, quantum, "VIKING 2*", "*"},
318                 /*quirks*/ DA_Q_NO_6_BYTE
319         },
320         {
321                 /*
322                  * Doesn't like the synchronize cache command.
323                  * Reported by: walter@pelissero.de
324                  */
325                 {T_DIRECT, SIP_MEDIA_FIXED, "CONNER", "CP3500*", "*"},
326                 /*quirks*/ DA_Q_NO_SYNC_CACHE
327         },
328         {
329                 /*
330                  * The CISS RAID controllers do not support SYNC_CACHE
331                  */
332                 {T_DIRECT, SIP_MEDIA_FIXED, "COMPAQ", "RAID*", "*"},
333                 /*quirks*/ DA_Q_NO_SYNC_CACHE
334         },
335         /* USB mass storage devices supported by umass(4) */
336         {
337                 /*
338                  * EXATELECOM (Sigmatel) i-Bead 100/105 USB Flash MP3 Player
339                  * PR: kern/51675
340                  */
341                 {T_DIRECT, SIP_MEDIA_REMOVABLE, "EXATEL", "i-BEAD10*", "*"},
342                 /*quirks*/ DA_Q_NO_SYNC_CACHE
343         },
344         {
345                 /*
346                  * Power Quotient Int. (PQI) USB flash key
347                  * PR: kern/53067
348                  */
349                 {T_DIRECT, SIP_MEDIA_REMOVABLE, "Generic*", "USB Flash Disk*",
350                 "*"}, /*quirks*/ DA_Q_NO_SYNC_CACHE
351         },
352         {
353                 /*
354                  * Creative Nomad MUVO mp3 player (USB)
355                  * PR: kern/53094
356                  */
357                 {T_DIRECT, SIP_MEDIA_REMOVABLE, "CREATIVE", "NOMAD_MUVO", "*"},
358                 /*quirks*/ DA_Q_NO_SYNC_CACHE|DA_Q_NO_PREVENT
359         },
360         {
361                 /*
362                  * Jungsoft NEXDISK USB flash key
363                  * PR: kern/54737
364                  */
365                 {T_DIRECT, SIP_MEDIA_REMOVABLE, "JUNGSOFT", "NEXDISK*", "*"},
366                 /*quirks*/ DA_Q_NO_SYNC_CACHE
367         },
368         {
369                 /*
370                  * FreeDik USB Mini Data Drive
371                  * PR: kern/54786
372                  */
373                 {T_DIRECT, SIP_MEDIA_REMOVABLE, "FreeDik*", "Mini Data Drive",
374                 "*"}, /*quirks*/ DA_Q_NO_SYNC_CACHE
375         },
376         {
377                 /*
378                  * Sigmatel USB Flash MP3 Player
379                  * PR: kern/57046
380                  */
381                 {T_DIRECT, SIP_MEDIA_REMOVABLE, "SigmaTel", "MSCN", "*"},
382                 /*quirks*/ DA_Q_NO_SYNC_CACHE|DA_Q_NO_PREVENT
383         },
384         {
385                 /*
386                  * Neuros USB Digital Audio Computer
387                  * PR: kern/63645
388                  */
389                 {T_DIRECT, SIP_MEDIA_REMOVABLE, "NEUROS", "dig. audio comp.",
390                 "*"}, /*quirks*/ DA_Q_NO_SYNC_CACHE
391         },
392         {
393                 /*
394                  * SEAGRAND NP-900 MP3 Player
395                  * PR: kern/64563
396                  */
397                 {T_DIRECT, SIP_MEDIA_REMOVABLE, "SEAGRAND", "NP-900*", "*"},
398                 /*quirks*/ DA_Q_NO_SYNC_CACHE|DA_Q_NO_PREVENT
399         },
400         {
401                 /*
402                  * iRiver iFP MP3 player (with UMS Firmware)
403                  * PR: kern/54881, i386/63941, kern/66124
404                  */
405                 {T_DIRECT, SIP_MEDIA_REMOVABLE, "iRiver", "iFP*", "*"},
406                 /*quirks*/ DA_Q_NO_SYNC_CACHE
407         },
408         {
409                 /*
410                  * Frontier Labs NEX IA+ Digital Audio Player, rev 1.10/0.01
411                  * PR: kern/70158
412                  */
413                 {T_DIRECT, SIP_MEDIA_REMOVABLE, "FL" , "Nex*", "*"},
414                 /*quirks*/ DA_Q_NO_SYNC_CACHE
415         },
416         {
417                 /*
418                  * ZICPlay USB MP3 Player with FM
419                  * PR: kern/75057
420                  */
421                 {T_DIRECT, SIP_MEDIA_REMOVABLE, "ACTIONS*" , "USB DISK*", "*"},
422                 /*quirks*/ DA_Q_NO_SYNC_CACHE
423         },
424         {
425                 /*
426                  * TEAC USB floppy mechanisms
427                  */
428                 {T_DIRECT, SIP_MEDIA_REMOVABLE, "TEAC" , "FD-05*", "*"},
429                 /*quirks*/ DA_Q_NO_SYNC_CACHE
430         },
431         {
432                 /*
433                  * Kingston DataTraveler II+ USB Pen-Drive.
434                  * Reported by: Pawel Jakub Dawidek <pjd@FreeBSD.org>
435                  */
436                 {T_DIRECT, SIP_MEDIA_REMOVABLE, "Kingston" , "DataTraveler II+",
437                 "*"}, /*quirks*/ DA_Q_NO_SYNC_CACHE
438         },
439         {
440                 /*
441                  * USB DISK Pro PMAP
442                  * Reported by: jhs
443                  * PR: usb/96381
444                  */
445                 {T_DIRECT, SIP_MEDIA_REMOVABLE, " ", "USB DISK Pro", "PMAP"},
446                 /*quirks*/ DA_Q_NO_SYNC_CACHE
447         },
448         {
449                 /*
450                  * Motorola E398 Mobile Phone (TransFlash memory card).
451                  * Reported by: Wojciech A. Koszek <dunstan@FreeBSD.czest.pl>
452                  * PR: usb/89889
453                  */
454                 {T_DIRECT, SIP_MEDIA_REMOVABLE, "Motorola" , "Motorola Phone",
455                 "*"}, /*quirks*/ DA_Q_NO_SYNC_CACHE
456         },
457         {
458                 /*
459                  * Qware BeatZkey! Pro
460                  * PR: usb/79164
461                  */
462                 {T_DIRECT, SIP_MEDIA_REMOVABLE, "GENERIC", "USB DISK DEVICE",
463                 "*"}, /*quirks*/ DA_Q_NO_SYNC_CACHE
464         },
465         {
466                 /*
467                  * Time DPA20B 1GB MP3 Player
468                  * PR: usb/81846
469                  */
470                 {T_DIRECT, SIP_MEDIA_REMOVABLE, "USB2.0*", "(FS) FLASH DISK*",
471                 "*"}, /*quirks*/ DA_Q_NO_SYNC_CACHE
472         },
473         {
474                 /*
475                  * Samsung USB key 128Mb
476                  * PR: usb/90081
477                  */
478                 {T_DIRECT, SIP_MEDIA_REMOVABLE, "USB-DISK", "FreeDik-FlashUsb",
479                 "*"}, /*quirks*/ DA_Q_NO_SYNC_CACHE
480         },
481         {
482                 /*
483                  * Kingston DataTraveler 2.0 USB Flash memory.
484                  * PR: usb/89196
485                  */
486                 {T_DIRECT, SIP_MEDIA_REMOVABLE, "Kingston", "DataTraveler 2.0",
487                 "*"}, /*quirks*/ DA_Q_NO_SYNC_CACHE
488         },
489         {
490                 /*
491                  * Creative MUVO Slim mp3 player (USB)
492                  * PR: usb/86131
493                  */
494                 {T_DIRECT, SIP_MEDIA_REMOVABLE, "CREATIVE", "MuVo Slim",
495                 "*"}, /*quirks*/ DA_Q_NO_SYNC_CACHE|DA_Q_NO_PREVENT
496                 },
497         {
498                 /*
499                  * United MP5512 Portable MP3 Player (2-in-1 USB DISK/MP3)
500                  * PR: usb/80487
501                  */
502                 {T_DIRECT, SIP_MEDIA_REMOVABLE, "Generic*", "MUSIC DISK",
503                 "*"}, /*quirks*/ DA_Q_NO_SYNC_CACHE
504         },
505         {
506                 /*
507                  * SanDisk Micro Cruzer 128MB
508                  * PR: usb/75970
509                  */
510                 {T_DIRECT, SIP_MEDIA_REMOVABLE, "SanDisk" , "Micro Cruzer",
511                 "*"}, /*quirks*/ DA_Q_NO_SYNC_CACHE
512         },
513         {
514                 /*
515                  * TOSHIBA TransMemory USB sticks
516                  * PR: kern/94660
517                  */
518                 {T_DIRECT, SIP_MEDIA_REMOVABLE, "TOSHIBA", "TransMemory",
519                 "*"}, /*quirks*/ DA_Q_NO_SYNC_CACHE
520         },
521         {
522                 /*
523                  * PNY USB Flash keys
524                  * PR: usb/75578, usb/72344, usb/65436 
525                  */
526                 {T_DIRECT, SIP_MEDIA_REMOVABLE, "*" , "USB DISK*",
527                 "*"}, /*quirks*/ DA_Q_NO_SYNC_CACHE
528         },
529         {
530                 /*
531                  * Genesys 6-in-1 Card Reader
532                  * PR: usb/94647
533                  */
534                 {T_DIRECT, SIP_MEDIA_REMOVABLE, "Generic*", "STORAGE DEVICE*",
535                 "*"}, /*quirks*/ DA_Q_NO_SYNC_CACHE
536         },
537         {
538                 /*
539                  * Rekam Digital CAMERA
540                  * PR: usb/98713
541                  */
542                 {T_DIRECT, SIP_MEDIA_REMOVABLE, "CAMERA*", "4MP-9J6*",
543                 "*"}, /*quirks*/ DA_Q_NO_SYNC_CACHE
544         },
545         {
546                 /*
547                  * iRiver H10 MP3 player
548                  * PR: usb/102547
549                  */
550                 {T_DIRECT, SIP_MEDIA_REMOVABLE, "iriver", "H10*",
551                 "*"}, /*quirks*/ DA_Q_NO_SYNC_CACHE
552         },
553         {
554                 /*
555                  * iRiver U10 MP3 player
556                  * PR: usb/92306
557                  */
558                 {T_DIRECT, SIP_MEDIA_REMOVABLE, "iriver", "U10*",
559                 "*"}, /*quirks*/ DA_Q_NO_SYNC_CACHE
560         },
561         {
562                 /*
563                  * X-Micro Flash Disk
564                  * PR: usb/96901
565                  */
566                 {T_DIRECT, SIP_MEDIA_REMOVABLE, "X-Micro", "Flash Disk",
567                 "*"}, /*quirks*/ DA_Q_NO_SYNC_CACHE
568         },
569         {
570                 /*
571                  * EasyMP3 EM732X USB 2.0 Flash MP3 Player
572                  * PR: usb/96546
573                  */
574                 {T_DIRECT, SIP_MEDIA_REMOVABLE, "EM732X", "MP3 Player*",
575                 "1.00"}, /*quirks*/ DA_Q_NO_SYNC_CACHE
576         },
577         {
578                 /*
579                  * Denver MP3 player
580                  * PR: usb/107101
581                  */
582                 {T_DIRECT, SIP_MEDIA_REMOVABLE, "DENVER", "MP3 PLAYER",
583                  "*"}, /*quirks*/ DA_Q_NO_SYNC_CACHE
584         },
585         {
586                 /*
587                  * Philips USB Key Audio KEY013
588                  * PR: usb/68412
589                  */
590                 {T_DIRECT, SIP_MEDIA_REMOVABLE, "PHILIPS", "Key*", "*"},
591                 /*quirks*/ DA_Q_NO_SYNC_CACHE | DA_Q_NO_PREVENT
592         },
593         {
594                 /*
595                  * JNC MP3 Player
596                  * PR: usb/94439
597                  */
598                 {T_DIRECT, SIP_MEDIA_REMOVABLE, "JNC*" , "MP3 Player*",
599                  "*"}, /*quirks*/ DA_Q_NO_SYNC_CACHE
600         },
601         {
602                 /*
603                  * SAMSUNG MP0402H
604                  * PR: usb/108427
605                  */
606                 {T_DIRECT, SIP_MEDIA_FIXED, "SAMSUNG", "MP0402H", "*"},
607                 /*quirks*/ DA_Q_NO_SYNC_CACHE
608         },
609         {
610                 /*
611                  * I/O Magic USB flash - Giga Bank
612                  * PR: usb/108810
613                  */
614                 {T_DIRECT, SIP_MEDIA_FIXED, "GS-Magic", "stor*", "*"},
615                 /*quirks*/ DA_Q_NO_SYNC_CACHE
616         },
617         {
618                 /*
619                  * JoyFly 128mb USB Flash Drive
620                  * PR: 96133
621                  */
622                 {T_DIRECT, SIP_MEDIA_REMOVABLE, "USB 2.0", "Flash Disk*",
623                  "*"}, /*quirks*/ DA_Q_NO_SYNC_CACHE
624         },
625         {
626                 /*
627                  * ChipsBnk usb stick
628                  * PR: 103702
629                  */
630                 {T_DIRECT, SIP_MEDIA_REMOVABLE, "ChipsBnk", "USB*",
631                  "*"}, /*quirks*/ DA_Q_NO_SYNC_CACHE
632         },
633         {
634                 /*
635                  * Storcase (Kingston) InfoStation IFS FC2/SATA-R 201A
636                  * PR: 129858
637                  */
638                 {T_DIRECT, SIP_MEDIA_FIXED, "IFS", "FC2/SATA-R*",
639                  "*"}, /*quirks*/ DA_Q_NO_SYNC_CACHE
640         },
641         {
642                 /*
643                  * Samsung YP-U3 mp3-player
644                  * PR: 125398
645                  */
646                 {T_DIRECT, SIP_MEDIA_REMOVABLE, "Samsung", "YP-U3",
647                  "*"}, /*quirks*/ DA_Q_NO_SYNC_CACHE
648         },
649         {
650                 {T_DIRECT, SIP_MEDIA_REMOVABLE, "Netac", "OnlyDisk*",
651                  "2000"}, /*quirks*/ DA_Q_NO_SYNC_CACHE
652         },
653         {
654                 /*
655                  * Sony Cyber-Shot DSC cameras
656                  * PR: usb/137035
657                  */
658                 {T_DIRECT, SIP_MEDIA_REMOVABLE, "Sony", "Sony DSC", "*"},
659                 /*quirks*/ DA_Q_NO_SYNC_CACHE | DA_Q_NO_PREVENT
660         },
661         {
662                 {T_DIRECT, SIP_MEDIA_REMOVABLE, "Kingston", "DataTraveler G3",
663                  "1.00"}, /*quirks*/ DA_Q_NO_PREVENT
664         },
665         /* ATA/SATA devices over SAS/USB/... */
666         {
667                 /* Hitachi Advanced Format (4k) drives */
668                 { T_DIRECT, SIP_MEDIA_FIXED, "Hitachi", "H??????????E3*", "*" },
669                 /*quirks*/DA_Q_4K
670         },
671         {
672                 /* Samsung Advanced Format (4k) drives */
673                 { T_DIRECT, SIP_MEDIA_FIXED, "ATA", "SAMSUNG HD155UI*", "*" },
674                 /*quirks*/DA_Q_4K
675         },
676         {
677                 /* Samsung Advanced Format (4k) drives */
678                 { T_DIRECT, SIP_MEDIA_FIXED, "SAMSUNG", "HD155UI*", "*" },
679                 /*quirks*/DA_Q_4K
680         },
681         {
682                 /* Samsung Advanced Format (4k) drives */
683                 { T_DIRECT, SIP_MEDIA_FIXED, "ATA", "SAMSUNG HD204UI*", "*" },
684                 /*quirks*/DA_Q_4K
685         },
686         {
687                 /* Samsung Advanced Format (4k) drives */
688                 { T_DIRECT, SIP_MEDIA_FIXED, "SAMSUNG", "HD204UI*", "*" },
689                 /*quirks*/DA_Q_4K
690         },
691         {
692                 /* Seagate Barracuda Green Advanced Format (4k) drives */
693                 { T_DIRECT, SIP_MEDIA_FIXED, "ATA", "ST????DL*", "*" },
694                 /*quirks*/DA_Q_4K
695         },
696         {
697                 /* Seagate Barracuda Green Advanced Format (4k) drives */
698                 { T_DIRECT, SIP_MEDIA_FIXED, "ST????DL", "*", "*" },
699                 /*quirks*/DA_Q_4K
700         },
701         {
702                 /* Seagate Barracuda Green Advanced Format (4k) drives */
703                 { T_DIRECT, SIP_MEDIA_FIXED, "ATA", "ST???DM*", "*" },
704                 /*quirks*/DA_Q_4K
705         },
706         {
707                 /* Seagate Barracuda Green Advanced Format (4k) drives */
708                 { T_DIRECT, SIP_MEDIA_FIXED, "ST???DM*", "*", "*" },
709                 /*quirks*/DA_Q_4K
710         },
711         {
712                 /* Seagate Barracuda Green Advanced Format (4k) drives */
713                 { T_DIRECT, SIP_MEDIA_FIXED, "ATA", "ST????DM*", "*" },
714                 /*quirks*/DA_Q_4K
715         },
716         {
717                 /* Seagate Barracuda Green Advanced Format (4k) drives */
718                 { T_DIRECT, SIP_MEDIA_FIXED, "ST????DM", "*", "*" },
719                 /*quirks*/DA_Q_4K
720         },
721         {
722                 /* Seagate Momentus Advanced Format (4k) drives */
723                 { T_DIRECT, SIP_MEDIA_FIXED, "ATA", "ST9500423AS*", "*" },
724                 /*quirks*/DA_Q_4K
725         },
726         {
727                 /* Seagate Momentus Advanced Format (4k) drives */
728                 { T_DIRECT, SIP_MEDIA_FIXED, "ST950042", "3AS*", "*" },
729                 /*quirks*/DA_Q_4K
730         },
731         {
732                 /* Seagate Momentus Advanced Format (4k) drives */
733                 { T_DIRECT, SIP_MEDIA_FIXED, "ATA", "ST9500424AS*", "*" },
734                 /*quirks*/DA_Q_4K
735         },
736         {
737                 /* Seagate Momentus Advanced Format (4k) drives */
738                 { T_DIRECT, SIP_MEDIA_FIXED, "ST950042", "4AS*", "*" },
739                 /*quirks*/DA_Q_4K
740         },
741         {
742                 /* Seagate Momentus Advanced Format (4k) drives */
743                 { T_DIRECT, SIP_MEDIA_FIXED, "ATA", "ST9640423AS*", "*" },
744                 /*quirks*/DA_Q_4K
745         },
746         {
747                 /* Seagate Momentus Advanced Format (4k) drives */
748                 { T_DIRECT, SIP_MEDIA_FIXED, "ST964042", "3AS*", "*" },
749                 /*quirks*/DA_Q_4K
750         },
751         {
752                 /* Seagate Momentus Advanced Format (4k) drives */
753                 { T_DIRECT, SIP_MEDIA_FIXED, "ATA", "ST9640424AS*", "*" },
754                 /*quirks*/DA_Q_4K
755         },
756         {
757                 /* Seagate Momentus Advanced Format (4k) drives */
758                 { T_DIRECT, SIP_MEDIA_FIXED, "ST964042", "4AS*", "*" },
759                 /*quirks*/DA_Q_4K
760         },
761         {
762                 /* Seagate Momentus Advanced Format (4k) drives */
763                 { T_DIRECT, SIP_MEDIA_FIXED, "ATA", "ST9750420AS*", "*" },
764                 /*quirks*/DA_Q_4K
765         },
766         {
767                 /* Seagate Momentus Advanced Format (4k) drives */
768                 { T_DIRECT, SIP_MEDIA_FIXED, "ST975042", "0AS*", "*" },
769                 /*quirks*/DA_Q_4K
770         },
771         {
772                 /* Seagate Momentus Advanced Format (4k) drives */
773                 { T_DIRECT, SIP_MEDIA_FIXED, "ATA", "ST9750422AS*", "*" },
774                 /*quirks*/DA_Q_4K
775         },
776         {
777                 /* Seagate Momentus Advanced Format (4k) drives */
778                 { T_DIRECT, SIP_MEDIA_FIXED, "ST975042", "2AS*", "*" },
779                 /*quirks*/DA_Q_4K
780         },
781         {
782                 /* Seagate Momentus Advanced Format (4k) drives */
783                 { T_DIRECT, SIP_MEDIA_FIXED, "ATA", "ST9750423AS*", "*" },
784                 /*quirks*/DA_Q_4K
785         },
786         {
787                 /* Seagate Momentus Advanced Format (4k) drives */
788                 { T_DIRECT, SIP_MEDIA_FIXED, "ST975042", "3AS*", "*" },
789                 /*quirks*/DA_Q_4K
790         },
791         {
792                 /* Seagate Momentus Thin Advanced Format (4k) drives */
793                 { T_DIRECT, SIP_MEDIA_FIXED, "ATA", "ST???LT*", "*" },
794                 /*quirks*/DA_Q_4K
795         },
796         {
797                 /* Seagate Momentus Thin Advanced Format (4k) drives */
798                 { T_DIRECT, SIP_MEDIA_FIXED, "ST???LT*", "*", "*" },
799                 /*quirks*/DA_Q_4K
800         },
801         {
802                 /* WDC Caviar Green Advanced Format (4k) drives */
803                 { T_DIRECT, SIP_MEDIA_FIXED, "ATA", "WDC WD????RS*", "*" },
804                 /*quirks*/DA_Q_4K
805         },
806         {
807                 /* WDC Caviar Green Advanced Format (4k) drives */
808                 { T_DIRECT, SIP_MEDIA_FIXED, "WDC WD??", "??RS*", "*" },
809                 /*quirks*/DA_Q_4K
810         },
811         {
812                 /* WDC Caviar Green Advanced Format (4k) drives */
813                 { T_DIRECT, SIP_MEDIA_FIXED, "ATA", "WDC WD????RX*", "*" },
814                 /*quirks*/DA_Q_4K
815         },
816         {
817                 /* WDC Caviar Green Advanced Format (4k) drives */
818                 { T_DIRECT, SIP_MEDIA_FIXED, "WDC WD??", "??RX*", "*" },
819                 /*quirks*/DA_Q_4K
820         },
821         {
822                 /* WDC Caviar Green Advanced Format (4k) drives */
823                 { T_DIRECT, SIP_MEDIA_FIXED, "ATA", "WDC WD??????RS*", "*" },
824                 /*quirks*/DA_Q_4K
825         },
826         {
827                 /* WDC Caviar Green Advanced Format (4k) drives */
828                 { T_DIRECT, SIP_MEDIA_FIXED, "WDC WD??", "????RS*", "*" },
829                 /*quirks*/DA_Q_4K
830         },
831         {
832                 /* WDC Caviar Green Advanced Format (4k) drives */
833                 { T_DIRECT, SIP_MEDIA_FIXED, "ATA", "WDC WD??????RX*", "*" },
834                 /*quirks*/DA_Q_4K
835         },
836         {
837                 /* WDC Caviar Green Advanced Format (4k) drives */
838                 { T_DIRECT, SIP_MEDIA_FIXED, "WDC WD??", "????RX*", "*" },
839                 /*quirks*/DA_Q_4K
840         },
841         {
842                 /* WDC Scorpio Black Advanced Format (4k) drives */
843                 { T_DIRECT, SIP_MEDIA_FIXED, "ATA", "WDC WD???PKT*", "*" },
844                 /*quirks*/DA_Q_4K
845         },
846         {
847                 /* WDC Scorpio Black Advanced Format (4k) drives */
848                 { T_DIRECT, SIP_MEDIA_FIXED, "WDC WD??", "?PKT*", "*" },
849                 /*quirks*/DA_Q_4K
850         },
851         {
852                 /* WDC Scorpio Black Advanced Format (4k) drives */
853                 { T_DIRECT, SIP_MEDIA_FIXED, "ATA", "WDC WD?????PKT*", "*" },
854                 /*quirks*/DA_Q_4K
855         },
856         {
857                 /* WDC Scorpio Black Advanced Format (4k) drives */
858                 { T_DIRECT, SIP_MEDIA_FIXED, "WDC WD??", "???PKT*", "*" },
859                 /*quirks*/DA_Q_4K
860         },
861         {
862                 /* WDC Scorpio Blue Advanced Format (4k) drives */
863                 { T_DIRECT, SIP_MEDIA_FIXED, "ATA", "WDC WD???PVT*", "*" },
864                 /*quirks*/DA_Q_4K
865         },
866         {
867                 /* WDC Scorpio Blue Advanced Format (4k) drives */
868                 { T_DIRECT, SIP_MEDIA_FIXED, "WDC WD??", "?PVT*", "*" },
869                 /*quirks*/DA_Q_4K
870         },
871         {
872                 /* WDC Scorpio Blue Advanced Format (4k) drives */
873                 { T_DIRECT, SIP_MEDIA_FIXED, "ATA", "WDC WD?????PVT*", "*" },
874                 /*quirks*/DA_Q_4K
875         },
876         {
877                 /* WDC Scorpio Blue Advanced Format (4k) drives */
878                 { T_DIRECT, SIP_MEDIA_FIXED, "WDC WD??", "???PVT*", "*" },
879                 /*quirks*/DA_Q_4K
880         },
881         {
882                 /*
883                  * Olympus FE-210 camera
884                  */
885                 {T_DIRECT, SIP_MEDIA_REMOVABLE, "OLYMPUS", "FE210*",
886                 "*"}, /*quirks*/ DA_Q_NO_SYNC_CACHE
887         },
888         {
889                 /*
890                  * LG UP3S MP3 player
891                  */
892                 {T_DIRECT, SIP_MEDIA_REMOVABLE, "LG", "UP3S",
893                 "*"}, /*quirks*/ DA_Q_NO_SYNC_CACHE
894         },
895         {
896                 /*
897                  * Laser MP3-2GA13 MP3 player
898                  */
899                 {T_DIRECT, SIP_MEDIA_REMOVABLE, "USB 2.0", "(HS) Flash Disk",
900                 "*"}, /*quirks*/ DA_Q_NO_SYNC_CACHE
901         },
902         {
903                 /*
904                  * LaCie external 250GB Hard drive des by Porsche
905                  * Submitted by: Ben Stuyts <ben@altesco.nl>
906                  * PR: 121474
907                  */
908                 {T_DIRECT, SIP_MEDIA_FIXED, "SAMSUNG", "HM250JI", "*"},
909                 /*quirks*/ DA_Q_NO_SYNC_CACHE
910         },
911 };
912
913 static  disk_strategy_t dastrategy;
914 static  dumper_t        dadump;
915 static  periph_init_t   dainit;
916 static  void            daasync(void *callback_arg, u_int32_t code,
917                                 struct cam_path *path, void *arg);
918 static  void            dasysctlinit(void *context, int pending);
919 static  int             dacmdsizesysctl(SYSCTL_HANDLER_ARGS);
920 static  int             dadeletemethodsysctl(SYSCTL_HANDLER_ARGS);
921 static  void            dadeletemethodset(struct da_softc *softc,
922                                           da_delete_methods delete_method);
923 static  void            dadeletemethodchoose(struct da_softc *softc,
924                                              da_delete_methods default_method);
925 static  void            daprobedone(struct cam_periph *periph, union ccb *ccb);
926
927 static  periph_ctor_t   daregister;
928 static  periph_dtor_t   dacleanup;
929 static  periph_start_t  dastart;
930 static  periph_oninv_t  daoninvalidate;
931 static  void            dadone(struct cam_periph *periph,
932                                union ccb *done_ccb);
933 static  int             daerror(union ccb *ccb, u_int32_t cam_flags,
934                                 u_int32_t sense_flags);
935 static void             daprevent(struct cam_periph *periph, int action);
936 static void             dareprobe(struct cam_periph *periph);
937 static void             dasetgeom(struct cam_periph *periph, uint32_t block_len,
938                                   uint64_t maxsector,
939                                   struct scsi_read_capacity_data_long *rcaplong,
940                                   size_t rcap_size);
941 static timeout_t        dasendorderedtag;
942 static void             dashutdown(void *arg, int howto);
943 static timeout_t        damediapoll;
944
945 #ifndef DA_DEFAULT_POLL_PERIOD
946 #define DA_DEFAULT_POLL_PERIOD  3
947 #endif
948
949 #ifndef DA_DEFAULT_TIMEOUT
950 #define DA_DEFAULT_TIMEOUT 60   /* Timeout in seconds */
951 #endif
952
953 #ifndef DA_DEFAULT_RETRY
954 #define DA_DEFAULT_RETRY        4
955 #endif
956
957 #ifndef DA_DEFAULT_SEND_ORDERED
958 #define DA_DEFAULT_SEND_ORDERED 1
959 #endif
960
961 #define DA_SIO (softc->sort_io_queue >= 0 ? \
962     softc->sort_io_queue : cam_sort_io_queues)
963
964 static int da_poll_period = DA_DEFAULT_POLL_PERIOD;
965 static int da_retry_count = DA_DEFAULT_RETRY;
966 static int da_default_timeout = DA_DEFAULT_TIMEOUT;
967 static int da_send_ordered = DA_DEFAULT_SEND_ORDERED;
968
969 static SYSCTL_NODE(_kern_cam, OID_AUTO, da, CTLFLAG_RD, 0,
970             "CAM Direct Access Disk driver");
971 SYSCTL_INT(_kern_cam_da, OID_AUTO, poll_period, CTLFLAG_RW,
972            &da_poll_period, 0, "Media polling period in seconds");
973 TUNABLE_INT("kern.cam.da.poll_period", &da_poll_period);
974 SYSCTL_INT(_kern_cam_da, OID_AUTO, retry_count, CTLFLAG_RW,
975            &da_retry_count, 0, "Normal I/O retry count");
976 TUNABLE_INT("kern.cam.da.retry_count", &da_retry_count);
977 SYSCTL_INT(_kern_cam_da, OID_AUTO, default_timeout, CTLFLAG_RW,
978            &da_default_timeout, 0, "Normal I/O timeout (in seconds)");
979 TUNABLE_INT("kern.cam.da.default_timeout", &da_default_timeout);
980 SYSCTL_INT(_kern_cam_da, OID_AUTO, send_ordered, CTLFLAG_RW,
981            &da_send_ordered, 0, "Send Ordered Tags");
982 TUNABLE_INT("kern.cam.da.send_ordered", &da_send_ordered);
983
984 /*
985  * DA_ORDEREDTAG_INTERVAL determines how often, relative
986  * to the default timeout, we check to see whether an ordered
987  * tagged transaction is appropriate to prevent simple tag
988  * starvation.  Since we'd like to ensure that there is at least
989  * 1/2 of the timeout length left for a starved transaction to
990  * complete after we've sent an ordered tag, we must poll at least
991  * four times in every timeout period.  This takes care of the worst
992  * case where a starved transaction starts during an interval that
993  * meets the requirement "don't send an ordered tag" test so it takes
994  * us two intervals to determine that a tag must be sent.
995  */
996 #ifndef DA_ORDEREDTAG_INTERVAL
997 #define DA_ORDEREDTAG_INTERVAL 4
998 #endif
999
1000 static struct periph_driver dadriver =
1001 {
1002         dainit, "da",
1003         TAILQ_HEAD_INITIALIZER(dadriver.units), /* generation */ 0
1004 };
1005
1006 PERIPHDRIVER_DECLARE(da, dadriver);
1007
1008 static MALLOC_DEFINE(M_SCSIDA, "scsi_da", "scsi_da buffers");
1009
1010 static int
1011 daopen(struct disk *dp)
1012 {
1013         struct cam_periph *periph;
1014         struct da_softc *softc;
1015         int unit;
1016         int error;
1017
1018         periph = (struct cam_periph *)dp->d_drv1;
1019         if (cam_periph_acquire(periph) != CAM_REQ_CMP) {
1020                 return (ENXIO);
1021         }
1022
1023         cam_periph_lock(periph);
1024         if ((error = cam_periph_hold(periph, PRIBIO|PCATCH)) != 0) {
1025                 cam_periph_unlock(periph);
1026                 cam_periph_release(periph);
1027                 return (error);
1028         }
1029
1030         unit = periph->unit_number;
1031         softc = (struct da_softc *)periph->softc;
1032         softc->flags |= DA_FLAG_OPEN;
1033
1034         CAM_DEBUG(periph->path, CAM_DEBUG_TRACE | CAM_DEBUG_PERIPH,
1035             ("daopen\n"));
1036
1037         if ((softc->flags & DA_FLAG_PACK_INVALID) != 0) {
1038                 /* Invalidate our pack information. */
1039                 softc->flags &= ~DA_FLAG_PACK_INVALID;
1040         }
1041
1042         dareprobe(periph);
1043
1044         /* Wait for the disk size update.  */
1045         error = cam_periph_sleep(periph, &softc->disk->d_mediasize, PRIBIO,
1046             "dareprobe", 0);
1047         if (error != 0)
1048                 xpt_print(periph->path, "unable to retrieve capacity data");
1049
1050         if (periph->flags & CAM_PERIPH_INVALID ||
1051             softc->disk->d_sectorsize == 0 ||
1052             softc->disk->d_mediasize == 0)
1053                 error = ENXIO;
1054
1055         if (error == 0 && (softc->flags & DA_FLAG_PACK_REMOVABLE) != 0 &&
1056             (softc->quirks & DA_Q_NO_PREVENT) == 0)
1057                 daprevent(periph, PR_PREVENT);
1058
1059         if (error == 0)
1060                 softc->flags |= DA_FLAG_SAW_MEDIA;
1061
1062         cam_periph_unhold(periph);
1063         cam_periph_unlock(periph);
1064
1065         if (error != 0) {
1066                 softc->flags &= ~DA_FLAG_OPEN;
1067                 cam_periph_release(periph);
1068         }
1069
1070         return (error);
1071 }
1072
1073 static int
1074 daclose(struct disk *dp)
1075 {
1076         struct  cam_periph *periph;
1077         struct  da_softc *softc;
1078
1079         periph = (struct cam_periph *)dp->d_drv1;
1080         cam_periph_lock(periph);
1081         if (cam_periph_hold(periph, PRIBIO) != 0) {
1082                 cam_periph_unlock(periph);
1083                 cam_periph_release(periph);
1084                 return (0);
1085         }
1086
1087         softc = (struct da_softc *)periph->softc;
1088
1089         CAM_DEBUG(periph->path, CAM_DEBUG_TRACE | CAM_DEBUG_PERIPH,
1090             ("daclose\n"));
1091
1092         if ((softc->quirks & DA_Q_NO_SYNC_CACHE) == 0
1093          && (softc->flags & DA_FLAG_PACK_INVALID) == 0) {
1094                 union   ccb *ccb;
1095
1096                 ccb = cam_periph_getccb(periph, CAM_PRIORITY_NORMAL);
1097
1098                 scsi_synchronize_cache(&ccb->csio,
1099                                        /*retries*/1,
1100                                        /*cbfcnp*/dadone,
1101                                        MSG_SIMPLE_Q_TAG,
1102                                        /*begin_lba*/0,/* Cover the whole disk */
1103                                        /*lb_count*/0,
1104                                        SSD_FULL_SIZE,
1105                                        5 * 60 * 1000);
1106
1107                 cam_periph_runccb(ccb, daerror, /*cam_flags*/0,
1108                                   /*sense_flags*/SF_RETRY_UA | SF_QUIET_IR,
1109                                   softc->disk->d_devstat);
1110                 xpt_release_ccb(ccb);
1111
1112         }
1113
1114         if ((softc->flags & DA_FLAG_PACK_REMOVABLE) != 0) {
1115                 if ((softc->quirks & DA_Q_NO_PREVENT) == 0)
1116                         daprevent(periph, PR_ALLOW);
1117                 /*
1118                  * If we've got removeable media, mark the blocksize as
1119                  * unavailable, since it could change when new media is
1120                  * inserted.
1121                  */
1122                 softc->disk->d_devstat->flags |= DEVSTAT_BS_UNAVAILABLE;
1123         }
1124
1125         softc->flags &= ~DA_FLAG_OPEN;
1126         cam_periph_unhold(periph);
1127         cam_periph_unlock(periph);
1128         cam_periph_release(periph);
1129         return (0);     
1130 }
1131
1132 static void
1133 daschedule(struct cam_periph *periph)
1134 {
1135         struct da_softc *softc = (struct da_softc *)periph->softc;
1136         uint32_t prio;
1137
1138         if (softc->state != DA_STATE_NORMAL)
1139                 return;
1140
1141         /* Check if cam_periph_getccb() was called. */
1142         prio = periph->immediate_priority;
1143
1144         /* Check if we have more work to do. */
1145         if (bioq_first(&softc->bio_queue) ||
1146             (!softc->delete_running && bioq_first(&softc->delete_queue)) ||
1147             softc->tur) {
1148                 prio = CAM_PRIORITY_NORMAL;
1149         }
1150
1151         /* Schedule CCB if any of above is true. */
1152         if (prio != CAM_PRIORITY_NONE)
1153                 xpt_schedule(periph, prio);
1154 }
1155
1156 /*
1157  * Actually translate the requested transfer into one the physical driver
1158  * can understand.  The transfer is described by a buf and will include
1159  * only one physical transfer.
1160  */
1161 static void
1162 dastrategy(struct bio *bp)
1163 {
1164         struct cam_periph *periph;
1165         struct da_softc *softc;
1166         
1167         periph = (struct cam_periph *)bp->bio_disk->d_drv1;
1168         softc = (struct da_softc *)periph->softc;
1169
1170         cam_periph_lock(periph);
1171
1172         /*
1173          * If the device has been made invalid, error out
1174          */
1175         if ((softc->flags & DA_FLAG_PACK_INVALID)) {
1176                 cam_periph_unlock(periph);
1177                 biofinish(bp, NULL, ENXIO);
1178                 return;
1179         }
1180
1181         CAM_DEBUG(periph->path, CAM_DEBUG_TRACE, ("dastrategy(%p)\n", bp));
1182
1183         /*
1184          * Place it in the queue of disk activities for this disk
1185          */
1186         if (bp->bio_cmd == BIO_DELETE) {
1187                 if (bp->bio_bcount == 0)
1188                         biodone(bp);
1189                 else if (DA_SIO)
1190                         bioq_disksort(&softc->delete_queue, bp);
1191                 else
1192                         bioq_insert_tail(&softc->delete_queue, bp);
1193         } else if (DA_SIO) {
1194                 bioq_disksort(&softc->bio_queue, bp);
1195         } else {
1196                 bioq_insert_tail(&softc->bio_queue, bp);
1197         }
1198
1199         /*
1200          * Schedule ourselves for performing the work.
1201          */
1202         daschedule(periph);
1203         cam_periph_unlock(periph);
1204
1205         return;
1206 }
1207
1208 static int
1209 dadump(void *arg, void *virtual, vm_offset_t physical, off_t offset, size_t length)
1210 {
1211         struct      cam_periph *periph;
1212         struct      da_softc *softc;
1213         u_int       secsize;
1214         struct      ccb_scsiio csio;
1215         struct      disk *dp;
1216         int         error = 0;
1217
1218         dp = arg;
1219         periph = dp->d_drv1;
1220         softc = (struct da_softc *)periph->softc;
1221         cam_periph_lock(periph);
1222         secsize = softc->params.secsize;
1223         
1224         if ((softc->flags & DA_FLAG_PACK_INVALID) != 0) {
1225                 cam_periph_unlock(periph);
1226                 return (ENXIO);
1227         }
1228
1229         if (length > 0) {
1230                 xpt_setup_ccb(&csio.ccb_h, periph->path, CAM_PRIORITY_NORMAL);
1231                 csio.ccb_h.ccb_state = DA_CCB_DUMP;
1232                 scsi_read_write(&csio,
1233                                 /*retries*/0,
1234                                 dadone,
1235                                 MSG_ORDERED_Q_TAG,
1236                                 /*read*/FALSE,
1237                                 /*byte2*/0,
1238                                 /*minimum_cmd_size*/ softc->minimum_cmd_size,
1239                                 offset / secsize,
1240                                 length / secsize,
1241                                 /*data_ptr*/(u_int8_t *) virtual,
1242                                 /*dxfer_len*/length,
1243                                 /*sense_len*/SSD_FULL_SIZE,
1244                                 da_default_timeout * 1000);
1245                 xpt_polled_action((union ccb *)&csio);
1246
1247                 error = cam_periph_error((union ccb *)&csio,
1248                     0, SF_NO_RECOVERY | SF_NO_RETRY, NULL);
1249                 if ((csio.ccb_h.status & CAM_DEV_QFRZN) != 0)
1250                         cam_release_devq(csio.ccb_h.path, /*relsim_flags*/0,
1251                             /*reduction*/0, /*timeout*/0, /*getcount_only*/0);
1252                 if (error != 0)
1253                         printf("Aborting dump due to I/O error.\n");
1254                 cam_periph_unlock(periph);
1255                 return (error);
1256         }
1257                 
1258         /*
1259          * Sync the disk cache contents to the physical media.
1260          */
1261         if ((softc->quirks & DA_Q_NO_SYNC_CACHE) == 0) {
1262
1263                 xpt_setup_ccb(&csio.ccb_h, periph->path, CAM_PRIORITY_NORMAL);
1264                 csio.ccb_h.ccb_state = DA_CCB_DUMP;
1265                 scsi_synchronize_cache(&csio,
1266                                        /*retries*/0,
1267                                        /*cbfcnp*/dadone,
1268                                        MSG_SIMPLE_Q_TAG,
1269                                        /*begin_lba*/0,/* Cover the whole disk */
1270                                        /*lb_count*/0,
1271                                        SSD_FULL_SIZE,
1272                                        5 * 60 * 1000);
1273                 xpt_polled_action((union ccb *)&csio);
1274
1275                 error = cam_periph_error((union ccb *)&csio,
1276                     0, SF_NO_RECOVERY | SF_NO_RETRY | SF_QUIET_IR, NULL);
1277                 if ((csio.ccb_h.status & CAM_DEV_QFRZN) != 0)
1278                         cam_release_devq(csio.ccb_h.path, /*relsim_flags*/0,
1279                             /*reduction*/0, /*timeout*/0, /*getcount_only*/0);
1280                 if (error != 0)
1281                         xpt_print(periph->path, "Synchronize cache failed\n");
1282         }
1283         cam_periph_unlock(periph);
1284         return (error);
1285 }
1286
1287 static int
1288 dagetattr(struct bio *bp)
1289 {
1290         int ret;
1291         struct cam_periph *periph;
1292
1293         periph = (struct cam_periph *)bp->bio_disk->d_drv1;
1294         cam_periph_lock(periph);
1295         ret = xpt_getattr(bp->bio_data, bp->bio_length, bp->bio_attribute,
1296             periph->path);
1297         cam_periph_unlock(periph);
1298         if (ret == 0)
1299                 bp->bio_completed = bp->bio_length;
1300         return ret;
1301 }
1302
1303 static void
1304 dainit(void)
1305 {
1306         cam_status status;
1307
1308         /*
1309          * Install a global async callback.  This callback will
1310          * receive async callbacks like "new device found".
1311          */
1312         status = xpt_register_async(AC_FOUND_DEVICE, daasync, NULL, NULL);
1313
1314         if (status != CAM_REQ_CMP) {
1315                 printf("da: Failed to attach master async callback "
1316                        "due to status 0x%x!\n", status);
1317         } else if (da_send_ordered) {
1318
1319                 /* Register our shutdown event handler */
1320                 if ((EVENTHANDLER_REGISTER(shutdown_post_sync, dashutdown, 
1321                                            NULL, SHUTDOWN_PRI_DEFAULT)) == NULL)
1322                     printf("dainit: shutdown event registration failed!\n");
1323         }
1324 }
1325
1326 /*
1327  * Callback from GEOM, called when it has finished cleaning up its
1328  * resources.
1329  */
1330 static void
1331 dadiskgonecb(struct disk *dp)
1332 {
1333         struct cam_periph *periph;
1334
1335         periph = (struct cam_periph *)dp->d_drv1;
1336         cam_periph_release(periph);
1337 }
1338
1339 static void
1340 daoninvalidate(struct cam_periph *periph)
1341 {
1342         struct da_softc *softc;
1343
1344         softc = (struct da_softc *)periph->softc;
1345
1346         /*
1347          * De-register any async callbacks.
1348          */
1349         xpt_register_async(0, daasync, periph, periph->path);
1350
1351         softc->flags |= DA_FLAG_PACK_INVALID;
1352
1353         /*
1354          * Return all queued I/O with ENXIO.
1355          * XXX Handle any transactions queued to the card
1356          *     with XPT_ABORT_CCB.
1357          */
1358         bioq_flush(&softc->bio_queue, NULL, ENXIO);
1359         bioq_flush(&softc->delete_queue, NULL, ENXIO);
1360
1361         /*
1362          * Tell GEOM that we've gone away, we'll get a callback when it is
1363          * done cleaning up its resources.
1364          */
1365         disk_gone(softc->disk);
1366
1367         xpt_print(periph->path, "lost device - %d outstanding, %d refs\n",
1368                   softc->outstanding_cmds, periph->refcount);
1369 }
1370
1371 static void
1372 dacleanup(struct cam_periph *periph)
1373 {
1374         struct da_softc *softc;
1375
1376         softc = (struct da_softc *)periph->softc;
1377
1378         xpt_print(periph->path, "removing device entry\n");
1379         cam_periph_unlock(periph);
1380
1381         /*
1382          * If we can't free the sysctl tree, oh well...
1383          */
1384         if ((softc->flags & DA_FLAG_SCTX_INIT) != 0
1385             && sysctl_ctx_free(&softc->sysctl_ctx) != 0) {
1386                 xpt_print(periph->path, "can't remove sysctl context\n");
1387         }
1388
1389         callout_drain(&softc->mediapoll_c);
1390         disk_destroy(softc->disk);
1391         callout_drain(&softc->sendordered_c);
1392         free(softc, M_DEVBUF);
1393         cam_periph_lock(periph);
1394 }
1395
1396 static void
1397 daasync(void *callback_arg, u_int32_t code,
1398         struct cam_path *path, void *arg)
1399 {
1400         struct cam_periph *periph;
1401         struct da_softc *softc;
1402
1403         periph = (struct cam_periph *)callback_arg;
1404         switch (code) {
1405         case AC_FOUND_DEVICE:
1406         {
1407                 struct ccb_getdev *cgd;
1408                 cam_status status;
1409  
1410                 cgd = (struct ccb_getdev *)arg;
1411                 if (cgd == NULL)
1412                         break;
1413
1414                 if (cgd->protocol != PROTO_SCSI)
1415                         break;
1416
1417                 if (SID_TYPE(&cgd->inq_data) != T_DIRECT
1418                     && SID_TYPE(&cgd->inq_data) != T_RBC
1419                     && SID_TYPE(&cgd->inq_data) != T_OPTICAL)
1420                         break;
1421
1422                 /*
1423                  * Allocate a peripheral instance for
1424                  * this device and start the probe
1425                  * process.
1426                  */
1427                 status = cam_periph_alloc(daregister, daoninvalidate,
1428                                           dacleanup, dastart,
1429                                           "da", CAM_PERIPH_BIO,
1430                                           cgd->ccb_h.path, daasync,
1431                                           AC_FOUND_DEVICE, cgd);
1432
1433                 if (status != CAM_REQ_CMP
1434                  && status != CAM_REQ_INPROG)
1435                         printf("daasync: Unable to attach to new device "
1436                                 "due to status 0x%x\n", status);
1437                 return;
1438         }
1439         case AC_ADVINFO_CHANGED:
1440         {
1441                 uintptr_t buftype;
1442
1443                 buftype = (uintptr_t)arg;
1444                 if (buftype == CDAI_TYPE_PHYS_PATH) {
1445                         struct da_softc *softc;
1446
1447                         softc = periph->softc;
1448                         disk_attr_changed(softc->disk, "GEOM::physpath",
1449                                           M_NOWAIT);
1450                 }
1451                 break;
1452         }
1453         case AC_UNIT_ATTENTION:
1454         {
1455                 union ccb *ccb;
1456                 int error_code, sense_key, asc, ascq;
1457
1458                 softc = (struct da_softc *)periph->softc;
1459                 ccb = (union ccb *)arg;
1460
1461                 /*
1462                  * Handle all UNIT ATTENTIONs except our own,
1463                  * as they will be handled by daerror().
1464                  */
1465                 if (xpt_path_periph(ccb->ccb_h.path) != periph &&
1466                     scsi_extract_sense_ccb(ccb,
1467                      &error_code, &sense_key, &asc, &ascq)) {
1468                         if (asc == 0x2A && ascq == 0x09) {
1469                                 xpt_print(ccb->ccb_h.path,
1470                                     "capacity data has changed\n");
1471                                 dareprobe(periph);
1472                         } else if (asc == 0x28 && ascq == 0x00)
1473                                 disk_media_changed(softc->disk, M_NOWAIT);
1474                 }
1475                 cam_periph_async(periph, code, path, arg);
1476                 break;
1477         }
1478         case AC_SCSI_AEN:
1479                 softc = (struct da_softc *)periph->softc;
1480                 if (!softc->tur) {
1481                         if (cam_periph_acquire(periph) == CAM_REQ_CMP) {
1482                                 softc->tur = 1;
1483                                 daschedule(periph);
1484                         }
1485                 }
1486                 /* FALLTHROUGH */
1487         case AC_SENT_BDR:
1488         case AC_BUS_RESET:
1489         {
1490                 struct ccb_hdr *ccbh;
1491
1492                 softc = (struct da_softc *)periph->softc;
1493                 /*
1494                  * Don't fail on the expected unit attention
1495                  * that will occur.
1496                  */
1497                 softc->flags |= DA_FLAG_RETRY_UA;
1498                 LIST_FOREACH(ccbh, &softc->pending_ccbs, periph_links.le)
1499                         ccbh->ccb_state |= DA_CCB_RETRY_UA;
1500                 break;
1501         }
1502         default:
1503                 break;
1504         }
1505         cam_periph_async(periph, code, path, arg);
1506 }
1507
1508 static void
1509 dasysctlinit(void *context, int pending)
1510 {
1511         struct cam_periph *periph;
1512         struct da_softc *softc;
1513         char tmpstr[80], tmpstr2[80];
1514         struct ccb_trans_settings cts;
1515
1516         periph = (struct cam_periph *)context;
1517         /*
1518          * periph was held for us when this task was enqueued
1519          */
1520         if (periph->flags & CAM_PERIPH_INVALID) {
1521                 cam_periph_release(periph);
1522                 return;
1523         }
1524
1525         softc = (struct da_softc *)periph->softc;
1526         snprintf(tmpstr, sizeof(tmpstr), "CAM DA unit %d", periph->unit_number);
1527         snprintf(tmpstr2, sizeof(tmpstr2), "%d", periph->unit_number);
1528
1529         sysctl_ctx_init(&softc->sysctl_ctx);
1530         softc->flags |= DA_FLAG_SCTX_INIT;
1531         softc->sysctl_tree = SYSCTL_ADD_NODE(&softc->sysctl_ctx,
1532                 SYSCTL_STATIC_CHILDREN(_kern_cam_da), OID_AUTO, tmpstr2,
1533                 CTLFLAG_RD, 0, tmpstr);
1534         if (softc->sysctl_tree == NULL) {
1535                 printf("dasysctlinit: unable to allocate sysctl tree\n");
1536                 cam_periph_release(periph);
1537                 return;
1538         }
1539
1540         /*
1541          * Now register the sysctl handler, so the user can change the value on
1542          * the fly.
1543          */
1544         SYSCTL_ADD_PROC(&softc->sysctl_ctx, SYSCTL_CHILDREN(softc->sysctl_tree),
1545                 OID_AUTO, "delete_method", CTLTYPE_STRING | CTLFLAG_RW,
1546                 softc, 0, dadeletemethodsysctl, "A",
1547                 "BIO_DELETE execution method");
1548         SYSCTL_ADD_PROC(&softc->sysctl_ctx, SYSCTL_CHILDREN(softc->sysctl_tree),
1549                 OID_AUTO, "minimum_cmd_size", CTLTYPE_INT | CTLFLAG_RW,
1550                 &softc->minimum_cmd_size, 0, dacmdsizesysctl, "I",
1551                 "Minimum CDB size");
1552         SYSCTL_ADD_INT(&softc->sysctl_ctx, SYSCTL_CHILDREN(softc->sysctl_tree),
1553                 OID_AUTO, "sort_io_queue", CTLFLAG_RW, &softc->sort_io_queue, 0,
1554                 "Sort IO queue to try and optimise disk access patterns");
1555
1556         SYSCTL_ADD_INT(&softc->sysctl_ctx,
1557                        SYSCTL_CHILDREN(softc->sysctl_tree),
1558                        OID_AUTO,
1559                        "error_inject",
1560                        CTLFLAG_RW,
1561                        &softc->error_inject,
1562                        0,
1563                        "error_inject leaf");
1564
1565
1566         /*
1567          * Add some addressing info.
1568          */
1569         memset(&cts, 0, sizeof (cts));
1570         xpt_setup_ccb(&cts.ccb_h, periph->path, CAM_PRIORITY_NONE);
1571         cts.ccb_h.func_code = XPT_GET_TRAN_SETTINGS;
1572         cts.type = CTS_TYPE_CURRENT_SETTINGS;
1573         cam_periph_lock(periph);
1574         xpt_action((union ccb *)&cts);
1575         cam_periph_unlock(periph);
1576         if (cts.ccb_h.status != CAM_REQ_CMP) {
1577                 cam_periph_release(periph);
1578                 return;
1579         }
1580         if (cts.protocol == PROTO_SCSI && cts.transport == XPORT_FC) {
1581                 struct ccb_trans_settings_fc *fc = &cts.xport_specific.fc;
1582                 if (fc->valid & CTS_FC_VALID_WWPN) {
1583                         softc->wwpn = fc->wwpn;
1584                         SYSCTL_ADD_UQUAD(&softc->sysctl_ctx,
1585                             SYSCTL_CHILDREN(softc->sysctl_tree),
1586                             OID_AUTO, "wwpn", CTLFLAG_RD,
1587                             &softc->wwpn, "World Wide Port Name");
1588                 }
1589         }
1590         cam_periph_release(periph);
1591 }
1592
1593 static int
1594 dacmdsizesysctl(SYSCTL_HANDLER_ARGS)
1595 {
1596         int error, value;
1597
1598         value = *(int *)arg1;
1599
1600         error = sysctl_handle_int(oidp, &value, 0, req);
1601
1602         if ((error != 0)
1603          || (req->newptr == NULL))
1604                 return (error);
1605
1606         /*
1607          * Acceptable values here are 6, 10, 12 or 16.
1608          */
1609         if (value < 6)
1610                 value = 6;
1611         else if ((value > 6)
1612               && (value <= 10))
1613                 value = 10;
1614         else if ((value > 10)
1615               && (value <= 12))
1616                 value = 12;
1617         else if (value > 12)
1618                 value = 16;
1619
1620         *(int *)arg1 = value;
1621
1622         return (0);
1623 }
1624
1625 static void
1626 dadeletemethodset(struct da_softc *softc, da_delete_methods delete_method)
1627 {
1628
1629
1630         softc->delete_method = delete_method;
1631
1632         if (softc->delete_method > DA_DELETE_DISABLE)
1633                 softc->disk->d_flags |= DISKFLAG_CANDELETE;
1634         else
1635                 softc->disk->d_flags &= ~DISKFLAG_CANDELETE;
1636 }
1637
1638 static void
1639 daprobedone(struct cam_periph *periph, union ccb *ccb)
1640 {
1641         struct da_softc *softc;
1642
1643         softc = (struct da_softc *)periph->softc;
1644
1645         dadeletemethodchoose(softc, DA_DELETE_NONE);
1646
1647         if (bootverbose && (softc->flags & DA_FLAG_PROBED) == 0) {
1648                 char buf[80];
1649                 int i, sep;
1650
1651                 snprintf(buf, sizeof(buf), "Delete methods: <");
1652                 sep = 0;
1653                 for (i = DA_DELETE_MIN; i <= DA_DELETE_MAX; i++) {
1654                         if (softc->delete_available & (1 << i)) {
1655                                 if (sep) {
1656                                         strlcat(buf, ",", sizeof(buf));
1657                                 } else {
1658                                     sep = 1;
1659                                 }
1660                                 strlcat(buf, da_delete_method_names[i],
1661                                     sizeof(buf));
1662                                 if (i == softc->delete_method) {
1663                                         strlcat(buf, "(*)", sizeof(buf));
1664                                 }
1665                         }
1666                 }
1667                 if (sep == 0) {
1668                         if (softc->delete_method == DA_DELETE_NONE) 
1669                                 strlcat(buf, "NONE(*)", sizeof(buf));
1670                         else
1671                                 strlcat(buf, "DISABLED(*)", sizeof(buf));
1672                 }
1673                 strlcat(buf, ">", sizeof(buf));
1674                 printf("%s%d: %s\n", periph->periph_name,
1675                     periph->unit_number, buf);
1676         }
1677
1678         /*
1679          * Since our peripheral may be invalidated by an error
1680          * above or an external event, we must release our CCB
1681          * before releasing the probe lock on the peripheral.
1682          * The peripheral will only go away once the last lock
1683          * is removed, and we need it around for the CCB release
1684          * operation.
1685          */
1686         xpt_release_ccb(ccb);
1687         softc->state = DA_STATE_NORMAL;
1688         daschedule(periph);
1689         wakeup(&softc->disk->d_mediasize);
1690         if ((softc->flags & DA_FLAG_PROBED) == 0) {
1691                 softc->flags |= DA_FLAG_PROBED;
1692                 cam_periph_unhold(periph);
1693         } else
1694                 cam_periph_release_locked(periph);
1695 }
1696
1697 static void
1698 dadeletemethodchoose(struct da_softc *softc, da_delete_methods default_method)
1699 {
1700         int i, delete_method;
1701
1702         delete_method = default_method;
1703
1704         /*
1705          * Use the pre-defined order to choose the best
1706          * performing delete.
1707          */
1708         for (i = DA_DELETE_MIN; i <= DA_DELETE_MAX; i++) {
1709                 if (softc->delete_available & (1 << i)) {
1710                         dadeletemethodset(softc, i);
1711                         return;
1712                 }
1713         }
1714         dadeletemethodset(softc, delete_method);
1715 }
1716
1717 static int
1718 dadeletemethodsysctl(SYSCTL_HANDLER_ARGS)
1719 {
1720         char buf[16];
1721         const char *p;
1722         struct da_softc *softc;
1723         int i, error, value;
1724
1725         softc = (struct da_softc *)arg1;
1726
1727         value = softc->delete_method;
1728         if (value < 0 || value > DA_DELETE_MAX)
1729                 p = "UNKNOWN";
1730         else
1731                 p = da_delete_method_names[value];
1732         strncpy(buf, p, sizeof(buf));
1733         error = sysctl_handle_string(oidp, buf, sizeof(buf), req);
1734         if (error != 0 || req->newptr == NULL)
1735                 return (error);
1736         for (i = 0; i <= DA_DELETE_MAX; i++) {
1737                 if (!(softc->delete_available & (1 << i)) ||
1738                     strcmp(buf, da_delete_method_names[i]) != 0)
1739                         continue;
1740                 dadeletemethodset(softc, i);
1741                 return (0);
1742         }
1743         return (EINVAL);
1744 }
1745
1746 static cam_status
1747 daregister(struct cam_periph *periph, void *arg)
1748 {
1749         struct da_softc *softc;
1750         struct ccb_pathinq cpi;
1751         struct ccb_getdev *cgd;
1752         char tmpstr[80];
1753         caddr_t match;
1754
1755         cgd = (struct ccb_getdev *)arg;
1756         if (cgd == NULL) {
1757                 printf("daregister: no getdev CCB, can't register device\n");
1758                 return(CAM_REQ_CMP_ERR);
1759         }
1760
1761         softc = (struct da_softc *)malloc(sizeof(*softc), M_DEVBUF,
1762             M_NOWAIT|M_ZERO);
1763
1764         if (softc == NULL) {
1765                 printf("daregister: Unable to probe new device. "
1766                        "Unable to allocate softc\n");                           
1767                 return(CAM_REQ_CMP_ERR);
1768         }
1769
1770         LIST_INIT(&softc->pending_ccbs);
1771         softc->state = DA_STATE_PROBE_RC;
1772         bioq_init(&softc->bio_queue);
1773         bioq_init(&softc->delete_queue);
1774         bioq_init(&softc->delete_run_queue);
1775         if (SID_IS_REMOVABLE(&cgd->inq_data))
1776                 softc->flags |= DA_FLAG_PACK_REMOVABLE;
1777         softc->unmap_max_ranges = UNMAP_MAX_RANGES;
1778         softc->unmap_max_lba = UNMAP_RANGE_MAX;
1779         softc->ws_max_blks = WS16_MAX_BLKS;
1780         softc->trim_max_ranges = ATA_TRIM_MAX_RANGES;
1781         softc->sort_io_queue = -1;
1782
1783         periph->softc = softc;
1784
1785         /*
1786          * See if this device has any quirks.
1787          */
1788         match = cam_quirkmatch((caddr_t)&cgd->inq_data,
1789                                (caddr_t)da_quirk_table,
1790                                sizeof(da_quirk_table)/sizeof(*da_quirk_table),
1791                                sizeof(*da_quirk_table), scsi_inquiry_match);
1792
1793         if (match != NULL)
1794                 softc->quirks = ((struct da_quirk_entry *)match)->quirks;
1795         else
1796                 softc->quirks = DA_Q_NONE;
1797
1798         /* Check if the SIM does not want 6 byte commands */
1799         bzero(&cpi, sizeof(cpi));
1800         xpt_setup_ccb(&cpi.ccb_h, periph->path, CAM_PRIORITY_NORMAL);
1801         cpi.ccb_h.func_code = XPT_PATH_INQ;
1802         xpt_action((union ccb *)&cpi);
1803         if (cpi.ccb_h.status == CAM_REQ_CMP && (cpi.hba_misc & PIM_NO_6_BYTE))
1804                 softc->quirks |= DA_Q_NO_6_BYTE;
1805
1806         TASK_INIT(&softc->sysctl_task, 0, dasysctlinit, periph);
1807
1808         /*
1809          * Take an exclusive refcount on the periph while dastart is called
1810          * to finish the probe.  The reference will be dropped in dadone at
1811          * the end of probe.
1812          */
1813         (void)cam_periph_hold(periph, PRIBIO);
1814
1815         /*
1816          * Schedule a periodic event to occasionally send an
1817          * ordered tag to a device.
1818          */
1819         callout_init_mtx(&softc->sendordered_c, periph->sim->mtx, 0);
1820         callout_reset(&softc->sendordered_c,
1821             (da_default_timeout * hz) / DA_ORDEREDTAG_INTERVAL,
1822             dasendorderedtag, softc);
1823
1824         cam_periph_unlock(periph);
1825         /*
1826          * RBC devices don't have to support READ(6), only READ(10).
1827          */
1828         if (softc->quirks & DA_Q_NO_6_BYTE || SID_TYPE(&cgd->inq_data) == T_RBC)
1829                 softc->minimum_cmd_size = 10;
1830         else
1831                 softc->minimum_cmd_size = 6;
1832
1833         /*
1834          * Load the user's default, if any.
1835          */
1836         snprintf(tmpstr, sizeof(tmpstr), "kern.cam.da.%d.minimum_cmd_size",
1837                  periph->unit_number);
1838         TUNABLE_INT_FETCH(tmpstr, &softc->minimum_cmd_size);
1839
1840         /*
1841          * 6, 10, 12 and 16 are the currently permissible values.
1842          */
1843         if (softc->minimum_cmd_size < 6)
1844                 softc->minimum_cmd_size = 6;
1845         else if ((softc->minimum_cmd_size > 6)
1846               && (softc->minimum_cmd_size <= 10))
1847                 softc->minimum_cmd_size = 10;
1848         else if ((softc->minimum_cmd_size > 10)
1849               && (softc->minimum_cmd_size <= 12))
1850                 softc->minimum_cmd_size = 12;
1851         else if (softc->minimum_cmd_size > 12)
1852                 softc->minimum_cmd_size = 16;
1853
1854         /* Predict whether device may support READ CAPACITY(16). */
1855         if (SID_ANSI_REV(&cgd->inq_data) >= SCSI_REV_SPC3) {
1856                 softc->flags |= DA_FLAG_CAN_RC16;
1857                 softc->state = DA_STATE_PROBE_RC16;
1858         }
1859
1860         /*
1861          * Register this media as a disk.
1862          */
1863         softc->disk = disk_alloc();
1864         softc->disk->d_devstat = devstat_new_entry(periph->periph_name,
1865                           periph->unit_number, 0,
1866                           DEVSTAT_BS_UNAVAILABLE,
1867                           SID_TYPE(&cgd->inq_data) |
1868                           XPORT_DEVSTAT_TYPE(cpi.transport),
1869                           DEVSTAT_PRIORITY_DISK);
1870         softc->disk->d_open = daopen;
1871         softc->disk->d_close = daclose;
1872         softc->disk->d_strategy = dastrategy;
1873         softc->disk->d_dump = dadump;
1874         softc->disk->d_getattr = dagetattr;
1875         softc->disk->d_gone = dadiskgonecb;
1876         softc->disk->d_name = "da";
1877         softc->disk->d_drv1 = periph;
1878         if (cpi.maxio == 0)
1879                 softc->disk->d_maxsize = DFLTPHYS;      /* traditional default */
1880         else if (cpi.maxio > MAXPHYS)
1881                 softc->disk->d_maxsize = MAXPHYS;       /* for safety */
1882         else
1883                 softc->disk->d_maxsize = cpi.maxio;
1884         softc->disk->d_unit = periph->unit_number;
1885         softc->disk->d_flags = 0;
1886         if ((softc->quirks & DA_Q_NO_SYNC_CACHE) == 0)
1887                 softc->disk->d_flags |= DISKFLAG_CANFLUSHCACHE;
1888         cam_strvis(softc->disk->d_descr, cgd->inq_data.vendor,
1889             sizeof(cgd->inq_data.vendor), sizeof(softc->disk->d_descr));
1890         strlcat(softc->disk->d_descr, " ", sizeof(softc->disk->d_descr));
1891         cam_strvis(&softc->disk->d_descr[strlen(softc->disk->d_descr)],
1892             cgd->inq_data.product, sizeof(cgd->inq_data.product),
1893             sizeof(softc->disk->d_descr) - strlen(softc->disk->d_descr));
1894         softc->disk->d_hba_vendor = cpi.hba_vendor;
1895         softc->disk->d_hba_device = cpi.hba_device;
1896         softc->disk->d_hba_subvendor = cpi.hba_subvendor;
1897         softc->disk->d_hba_subdevice = cpi.hba_subdevice;
1898
1899         /*
1900          * Acquire a reference to the periph before we register with GEOM.
1901          * We'll release this reference once GEOM calls us back (via
1902          * dadiskgonecb()) telling us that our provider has been freed.
1903          */
1904         if (cam_periph_acquire(periph) != CAM_REQ_CMP) {
1905                 xpt_print(periph->path, "%s: lost periph during "
1906                           "registration!\n", __func__);
1907                 cam_periph_lock(periph);
1908                 return (CAM_REQ_CMP_ERR);
1909         }
1910
1911         disk_create(softc->disk, DISK_VERSION);
1912         cam_periph_lock(periph);
1913
1914         /*
1915          * Add async callbacks for events of interest.
1916          * I don't bother checking if this fails as,
1917          * in most cases, the system will function just
1918          * fine without them and the only alternative
1919          * would be to not attach the device on failure.
1920          */
1921         xpt_register_async(AC_SENT_BDR | AC_BUS_RESET | AC_LOST_DEVICE |
1922             AC_ADVINFO_CHANGED | AC_SCSI_AEN | AC_UNIT_ATTENTION,
1923             daasync, periph, periph->path);
1924
1925         /*
1926          * Emit an attribute changed notification just in case 
1927          * physical path information arrived before our async
1928          * event handler was registered, but after anyone attaching
1929          * to our disk device polled it.
1930          */
1931         disk_attr_changed(softc->disk, "GEOM::physpath", M_NOWAIT);
1932
1933         /*
1934          * Schedule a periodic media polling events.
1935          */
1936         callout_init_mtx(&softc->mediapoll_c, periph->sim->mtx, 0);
1937         if ((softc->flags & DA_FLAG_PACK_REMOVABLE) &&
1938             (cgd->inq_flags & SID_AEN) == 0 &&
1939             da_poll_period != 0)
1940                 callout_reset(&softc->mediapoll_c, da_poll_period * hz,
1941                     damediapoll, periph);
1942
1943         xpt_schedule(periph, CAM_PRIORITY_DEV);
1944
1945         return(CAM_REQ_CMP);
1946 }
1947
1948 static void
1949 dastart(struct cam_periph *periph, union ccb *start_ccb)
1950 {
1951         struct da_softc *softc;
1952
1953         softc = (struct da_softc *)periph->softc;
1954
1955         CAM_DEBUG(periph->path, CAM_DEBUG_TRACE, ("dastart\n"));
1956
1957 skipstate:
1958         switch (softc->state) {
1959         case DA_STATE_NORMAL:
1960         {
1961                 struct bio *bp, *bp1;
1962                 uint8_t tag_code;
1963
1964                 /* Execute immediate CCB if waiting. */
1965                 if (periph->immediate_priority <= periph->pinfo.priority) {
1966                         CAM_DEBUG(periph->path, CAM_DEBUG_SUBTRACE,
1967                                         ("queuing for immediate ccb\n"));
1968                         start_ccb->ccb_h.ccb_state = DA_CCB_WAITING;
1969                         SLIST_INSERT_HEAD(&periph->ccb_list, &start_ccb->ccb_h,
1970                                           periph_links.sle);
1971                         periph->immediate_priority = CAM_PRIORITY_NONE;
1972                         wakeup(&periph->ccb_list);
1973                         /* May have more work to do, so ensure we stay scheduled */
1974                         daschedule(periph);
1975                         break;
1976                 }
1977
1978                 /* Run BIO_DELETE if not running yet. */
1979                 if (!softc->delete_running &&
1980                     (bp = bioq_first(&softc->delete_queue)) != NULL) {
1981                     uint64_t lba;
1982                     uint64_t count; /* forward compat with WS32 */
1983
1984                     /*
1985                      * In each of the methods below, while its the caller's
1986                      * responsibility to ensure the request will fit into a
1987                      * single device request, we might have changed the delete
1988                      * method due to the device incorrectly advertising either
1989                      * its supported methods or limits.
1990                      * 
1991                      * To prevent this causing further issues we validate the
1992                      * against the methods limits, and warn which would
1993                      * otherwise be unnecessary.
1994                      */
1995
1996                     if (softc->delete_method == DA_DELETE_UNMAP) {
1997                         uint8_t *buf = softc->unmap_buf;
1998                         uint64_t lastlba = (uint64_t)-1;
1999                         uint32_t lastcount = 0, c;
2000                         uint64_t totalcount = 0;
2001                         uint32_t off, ranges = 0;
2002
2003                         /*
2004                          * Currently this doesn't take the UNMAP
2005                          * Granularity and Granularity Alignment
2006                          * fields into account.
2007                          *
2008                          * This could result in both unoptimal unmap
2009                          * requests as as well as UNMAP calls unmapping
2010                          * fewer LBA's than requested.
2011                          */
2012
2013                         softc->delete_running = 1;
2014                         bzero(softc->unmap_buf, sizeof(softc->unmap_buf));
2015                         bp1 = bp;
2016                         do {
2017                                 bioq_remove(&softc->delete_queue, bp1);
2018                                 if (bp1 != bp)
2019                                         bioq_insert_tail(&softc->delete_run_queue, bp1);
2020                                 lba = bp1->bio_pblkno;
2021                                 count = bp1->bio_bcount / softc->params.secsize;
2022
2023                                 /* Try to extend the previous range. */
2024                                 if (lba == lastlba) {
2025                                         c = min(count, softc->unmap_max_lba -
2026                                                 lastcount);
2027                                         lastcount += c;
2028                                         off = ((ranges - 1) * UNMAP_RANGE_SIZE) +
2029                                               UNMAP_HEAD_SIZE;
2030                                         scsi_ulto4b(lastcount, &buf[off + 8]);
2031                                         count -= c;
2032                                         lba +=c;
2033                                         totalcount += c;
2034                                 }
2035
2036                                 while (count > 0) {
2037                                         c = min(count, softc->unmap_max_lba);
2038                                         if (totalcount + c > softc->unmap_max_lba ||
2039                                             ranges >= softc->unmap_max_ranges) {
2040                                                 xpt_print(periph->path,
2041                                                   "%s issuing short delete %ld > %ld"
2042                                                   "|| %d >= %d",
2043                                                   da_delete_method_desc[softc->delete_method],
2044                                                   totalcount + c, softc->unmap_max_lba,
2045                                                   ranges, softc->unmap_max_ranges);
2046                                                 break;
2047                                         }
2048                                         off = (ranges * UNMAP_RANGE_SIZE) +
2049                                               UNMAP_HEAD_SIZE;
2050                                         scsi_u64to8b(lba, &buf[off + 0]);
2051                                         scsi_ulto4b(c, &buf[off + 8]);
2052                                         lba += c;
2053                                         totalcount += c;
2054                                         ranges++;
2055                                         count -= c;
2056                                         lastcount = c;
2057                                 }
2058                                 lastlba = lba;
2059                                 bp1 = bioq_first(&softc->delete_queue);
2060                                 if (bp1 == NULL ||
2061                                     ranges >= softc->unmap_max_ranges ||
2062                                     totalcount + bp1->bio_bcount /
2063                                      softc->params.secsize > softc->unmap_max_lba)
2064                                         break;
2065                         } while (1);
2066                         scsi_ulto2b(ranges * 16 + 6, &buf[0]);
2067                         scsi_ulto2b(ranges * 16, &buf[2]);
2068
2069                         scsi_unmap(&start_ccb->csio,
2070                                         /*retries*/da_retry_count,
2071                                         /*cbfcnp*/dadone,
2072                                         /*tag_action*/MSG_SIMPLE_Q_TAG,
2073                                         /*byte2*/0,
2074                                         /*data_ptr*/ buf,
2075                                         /*dxfer_len*/ ranges * 16 + 8,
2076                                         /*sense_len*/SSD_FULL_SIZE,
2077                                         da_default_timeout * 1000);
2078                         start_ccb->ccb_h.ccb_state = DA_CCB_DELETE;
2079                         goto out;
2080                     } else if (softc->delete_method == DA_DELETE_ATA_TRIM) {
2081                                 uint8_t *buf = softc->unmap_buf;
2082                                 uint64_t lastlba = (uint64_t)-1;
2083                                 uint32_t lastcount = 0, c, requestcount;
2084                                 int ranges = 0, off, block_count;
2085
2086                                 softc->delete_running = 1;
2087                                 bzero(softc->unmap_buf, sizeof(softc->unmap_buf));
2088                                 bp1 = bp;
2089                                 do {
2090                                         bioq_remove(&softc->delete_queue, bp1);
2091                                         if (bp1 != bp)
2092                                                 bioq_insert_tail(&softc->delete_run_queue, bp1);
2093                                         lba = bp1->bio_pblkno;
2094                                         count = bp1->bio_bcount / softc->params.secsize;
2095                                         requestcount = count;
2096
2097                                         /* Try to extend the previous range. */
2098                                         if (lba == lastlba) {
2099                                                 c = min(count, ATA_DSM_RANGE_MAX - lastcount);
2100                                                 lastcount += c;
2101                                                 off = (ranges - 1) * 8;
2102                                                 buf[off + 6] = lastcount & 0xff;
2103                                                 buf[off + 7] = (lastcount >> 8) & 0xff;
2104                                                 count -= c;
2105                                                 lba += c;
2106                                         }
2107
2108                                         while (count > 0) {
2109                                                 c = min(count, ATA_DSM_RANGE_MAX);
2110                                                 off = ranges * 8;
2111
2112                                                 buf[off + 0] = lba & 0xff;
2113                                                 buf[off + 1] = (lba >> 8) & 0xff;
2114                                                 buf[off + 2] = (lba >> 16) & 0xff;
2115                                                 buf[off + 3] = (lba >> 24) & 0xff;
2116                                                 buf[off + 4] = (lba >> 32) & 0xff;
2117                                                 buf[off + 5] = (lba >> 40) & 0xff;
2118                                                 buf[off + 6] = c & 0xff;
2119                                                 buf[off + 7] = (c >> 8) & 0xff;
2120                                                 lba += c;
2121                                                 ranges++;
2122                                                 count -= c;
2123                                                 lastcount = c;
2124                                                 if (count != 0 && ranges == softc->trim_max_ranges) {
2125                                                         xpt_print(periph->path,
2126                                                           "%s issuing short delete %ld > %ld",
2127                                                           da_delete_method_desc[softc->delete_method],
2128                                                           requestcount,
2129                                                           (softc->trim_max_ranges - ranges) *
2130                                                           ATA_DSM_RANGE_MAX);
2131                                                         break;
2132                                                 }
2133                                         }
2134                                         lastlba = lba;
2135                                         bp1 = bioq_first(&softc->delete_queue);
2136                                         if (bp1 == NULL ||
2137                                             bp1->bio_bcount / softc->params.secsize >
2138                                             (softc->trim_max_ranges - ranges) *
2139                                                     ATA_DSM_RANGE_MAX)
2140                                                 break;
2141                                 } while (1);
2142
2143                                 block_count = (ranges + ATA_DSM_BLK_RANGES - 1) /
2144                                               ATA_DSM_BLK_RANGES;
2145                                 scsi_ata_trim(&start_ccb->csio,
2146                                                 /*retries*/da_retry_count,
2147                                                 /*cbfcnp*/dadone,
2148                                                 /*tag_action*/MSG_SIMPLE_Q_TAG,
2149                                                 block_count,
2150                                                 /*data_ptr*/buf,
2151                                                 /*dxfer_len*/block_count * ATA_DSM_BLK_SIZE,
2152                                                 /*sense_len*/SSD_FULL_SIZE,
2153                                                 da_default_timeout * 1000);
2154                                 start_ccb->ccb_h.ccb_state = DA_CCB_DELETE;
2155                                 goto out;
2156                     } else if (softc->delete_method == DA_DELETE_ZERO ||
2157                                softc->delete_method == DA_DELETE_WS10 ||
2158                                softc->delete_method == DA_DELETE_WS16) {
2159                         uint64_t ws_max_blks;
2160                         ws_max_blks = softc->ws_max_blks / softc->params.secsize;
2161                         softc->delete_running = 1;
2162                         lba = bp->bio_pblkno;
2163                         count = 0;
2164                         bp1 = bp;
2165                         do {
2166                                 bioq_remove(&softc->delete_queue, bp1);
2167                                 if (bp1 != bp)
2168                                         bioq_insert_tail(&softc->delete_run_queue, bp1);
2169                                 count += bp1->bio_bcount / softc->params.secsize;
2170                                 if (count > ws_max_blks) {
2171                                         count = min(count, ws_max_blks);
2172                                         xpt_print(periph->path,
2173                                           "%s issuing short delete %ld > %ld",
2174                                           da_delete_method_desc[softc->delete_method],
2175                                           count, ws_max_blks);
2176                                         break;
2177                                 }
2178                                 bp1 = bioq_first(&softc->delete_queue);
2179                                 if (bp1 == NULL ||
2180                                     lba + count != bp1->bio_pblkno ||
2181                                     count + bp1->bio_bcount /
2182                                      softc->params.secsize > ws_max_blks)
2183                                         break;
2184                         } while (1);
2185
2186                         scsi_write_same(&start_ccb->csio,
2187                                         /*retries*/da_retry_count,
2188                                         /*cbfcnp*/dadone,
2189                                         /*tag_action*/MSG_SIMPLE_Q_TAG,
2190                                         /*byte2*/softc->delete_method ==
2191                                             DA_DELETE_ZERO ? 0 : SWS_UNMAP,
2192                                         softc->delete_method ==
2193                                             DA_DELETE_WS16 ? 16 : 10,
2194                                         /*lba*/lba,
2195                                         /*block_count*/count,
2196                                         /*data_ptr*/ __DECONST(void *,
2197                                             zero_region),
2198                                         /*dxfer_len*/ softc->params.secsize,
2199                                         /*sense_len*/SSD_FULL_SIZE,
2200                                         da_default_timeout * 1000);
2201                         start_ccb->ccb_h.ccb_state = DA_CCB_DELETE;
2202                         goto out;
2203                     } else {
2204                         bioq_flush(&softc->delete_queue, NULL, 0);
2205                         /* FALLTHROUGH */
2206                     }
2207                 }
2208
2209                 /* Run regular command. */
2210                 bp = bioq_takefirst(&softc->bio_queue);
2211                 if (bp == NULL) {
2212                         if (softc->tur) {
2213                                 softc->tur = 0;
2214                                 scsi_test_unit_ready(&start_ccb->csio,
2215                                      /*retries*/ da_retry_count,
2216                                      dadone,
2217                                      MSG_SIMPLE_Q_TAG,
2218                                      SSD_FULL_SIZE,
2219                                      da_default_timeout * 1000);
2220                                 start_ccb->ccb_h.ccb_bp = NULL;
2221                                 start_ccb->ccb_h.ccb_state = DA_CCB_TUR;
2222                                 xpt_action(start_ccb);
2223                         } else
2224                                 xpt_release_ccb(start_ccb);
2225                         break;
2226                 }
2227                 if (softc->tur) {
2228                         softc->tur = 0;
2229                         cam_periph_release_locked(periph);
2230                 }
2231
2232                 if ((bp->bio_flags & BIO_ORDERED) != 0 ||
2233                     (softc->flags & DA_FLAG_NEED_OTAG) != 0) {
2234                         softc->flags &= ~DA_FLAG_NEED_OTAG;
2235                         softc->ordered_tag_count++;
2236                         tag_code = MSG_ORDERED_Q_TAG;
2237                 } else {
2238                         tag_code = MSG_SIMPLE_Q_TAG;
2239                 }
2240
2241                 switch (bp->bio_cmd) {
2242                 case BIO_READ:
2243                 case BIO_WRITE:
2244                         scsi_read_write(&start_ccb->csio,
2245                                         /*retries*/da_retry_count,
2246                                         /*cbfcnp*/dadone,
2247                                         /*tag_action*/tag_code,
2248                                         /*read_op*/bp->bio_cmd
2249                                                 == BIO_READ,
2250                                         /*byte2*/0,
2251                                         softc->minimum_cmd_size,
2252                                         /*lba*/bp->bio_pblkno,
2253                                         /*block_count*/bp->bio_bcount /
2254                                         softc->params.secsize,
2255                                         /*data_ptr*/ bp->bio_data,
2256                                         /*dxfer_len*/ bp->bio_bcount,
2257                                         /*sense_len*/SSD_FULL_SIZE,
2258                                         da_default_timeout * 1000);
2259                         break;
2260                 case BIO_FLUSH:
2261                         /*
2262                          * BIO_FLUSH doesn't currently communicate
2263                          * range data, so we synchronize the cache
2264                          * over the whole disk.  We also force
2265                          * ordered tag semantics the flush applies
2266                          * to all previously queued I/O.
2267                          */
2268                         scsi_synchronize_cache(&start_ccb->csio,
2269                                                /*retries*/1,
2270                                                /*cbfcnp*/dadone,
2271                                                MSG_ORDERED_Q_TAG,
2272                                                /*begin_lba*/0,
2273                                                /*lb_count*/0,
2274                                                SSD_FULL_SIZE,
2275                                                da_default_timeout*1000);
2276                         break;
2277                 }
2278                 start_ccb->ccb_h.ccb_state = DA_CCB_BUFFER_IO;
2279
2280 out:
2281                 /*
2282                  * Block out any asyncronous callbacks
2283                  * while we touch the pending ccb list.
2284                  */
2285                 LIST_INSERT_HEAD(&softc->pending_ccbs,
2286                                  &start_ccb->ccb_h, periph_links.le);
2287                 softc->outstanding_cmds++;
2288
2289                 /* We expect a unit attention from this device */
2290                 if ((softc->flags & DA_FLAG_RETRY_UA) != 0) {
2291                         start_ccb->ccb_h.ccb_state |= DA_CCB_RETRY_UA;
2292                         softc->flags &= ~DA_FLAG_RETRY_UA;
2293                 }
2294
2295                 start_ccb->ccb_h.ccb_bp = bp;
2296                 xpt_action(start_ccb);
2297
2298                 /* May have more work to do, so ensure we stay scheduled */
2299                 daschedule(periph);
2300                 break;
2301         }
2302         case DA_STATE_PROBE_RC:
2303         {
2304                 struct scsi_read_capacity_data *rcap;
2305
2306                 rcap = (struct scsi_read_capacity_data *)
2307                     malloc(sizeof(*rcap), M_SCSIDA, M_NOWAIT|M_ZERO);
2308                 if (rcap == NULL) {
2309                         printf("dastart: Couldn't malloc read_capacity data\n");
2310                         /* da_free_periph??? */
2311                         break;
2312                 }
2313                 scsi_read_capacity(&start_ccb->csio,
2314                                    /*retries*/da_retry_count,
2315                                    dadone,
2316                                    MSG_SIMPLE_Q_TAG,
2317                                    rcap,
2318                                    SSD_FULL_SIZE,
2319                                    /*timeout*/5000);
2320                 start_ccb->ccb_h.ccb_bp = NULL;
2321                 start_ccb->ccb_h.ccb_state = DA_CCB_PROBE_RC;
2322                 xpt_action(start_ccb);
2323                 break;
2324         }
2325         case DA_STATE_PROBE_RC16:
2326         {
2327                 struct scsi_read_capacity_data_long *rcaplong;
2328
2329                 rcaplong = (struct scsi_read_capacity_data_long *)
2330                         malloc(sizeof(*rcaplong), M_SCSIDA, M_NOWAIT|M_ZERO);
2331                 if (rcaplong == NULL) {
2332                         printf("dastart: Couldn't malloc read_capacity data\n");
2333                         /* da_free_periph??? */
2334                         break;
2335                 }
2336                 scsi_read_capacity_16(&start_ccb->csio,
2337                                       /*retries*/ da_retry_count,
2338                                       /*cbfcnp*/ dadone,
2339                                       /*tag_action*/ MSG_SIMPLE_Q_TAG,
2340                                       /*lba*/ 0,
2341                                       /*reladr*/ 0,
2342                                       /*pmi*/ 0,
2343                                       rcaplong,
2344                                       /*sense_len*/ SSD_FULL_SIZE,
2345                                       /*timeout*/ da_default_timeout * 1000);
2346                 start_ccb->ccb_h.ccb_bp = NULL;
2347                 start_ccb->ccb_h.ccb_state = DA_CCB_PROBE_RC16;
2348                 xpt_action(start_ccb);
2349                 break;
2350         }
2351         case DA_STATE_PROBE_LBP:
2352         {
2353                 struct scsi_vpd_logical_block_prov *lbp;
2354
2355                 if (!scsi_vpd_supported_page(periph, SVPD_LBP)) {
2356                         /*
2357                          * If we get here we don't support any SBC-3 delete
2358                          * methods with UNMAP as the Logical Block Provisioning
2359                          * VPD page support is required for devices which
2360                          * support it according to T10/1799-D Revision 31
2361                          * however older revisions of the spec don't mandate
2362                          * this so we currently don't remove these methods
2363                          * from the available set.
2364                          */
2365                         softc->state = DA_STATE_PROBE_BLK_LIMITS;
2366                         goto skipstate;
2367                 }
2368
2369                 lbp = (struct scsi_vpd_logical_block_prov *)
2370                         malloc(sizeof(*lbp), M_SCSIDA, M_NOWAIT|M_ZERO);
2371
2372                 if (lbp == NULL) {
2373                         printf("dastart: Couldn't malloc lbp data\n");
2374                         /* da_free_periph??? */
2375                         break;
2376                 }
2377
2378                 scsi_inquiry(&start_ccb->csio,
2379                              /*retries*/da_retry_count,
2380                              /*cbfcnp*/dadone,
2381                              /*tag_action*/MSG_SIMPLE_Q_TAG,
2382                              /*inq_buf*/(u_int8_t *)lbp,
2383                              /*inq_len*/sizeof(*lbp),
2384                              /*evpd*/TRUE,
2385                              /*page_code*/SVPD_LBP,
2386                              /*sense_len*/SSD_MIN_SIZE,
2387                              /*timeout*/da_default_timeout * 1000);
2388                 start_ccb->ccb_h.ccb_bp = NULL;
2389                 start_ccb->ccb_h.ccb_state = DA_CCB_PROBE_LBP;
2390                 xpt_action(start_ccb);
2391                 break;
2392         }
2393         case DA_STATE_PROBE_BLK_LIMITS:
2394         {
2395                 struct scsi_vpd_block_limits *block_limits;
2396
2397                 if (!scsi_vpd_supported_page(periph, SVPD_BLOCK_LIMITS)) {
2398                         /* Not supported skip to next probe */
2399                         softc->state = DA_STATE_PROBE_BDC;
2400                         goto skipstate;
2401                 }
2402
2403                 block_limits = (struct scsi_vpd_block_limits *)
2404                         malloc(sizeof(*block_limits), M_SCSIDA, M_NOWAIT|M_ZERO);
2405
2406                 if (block_limits == NULL) {
2407                         printf("dastart: Couldn't malloc block_limits data\n");
2408                         /* da_free_periph??? */
2409                         break;
2410                 }
2411
2412                 scsi_inquiry(&start_ccb->csio,
2413                              /*retries*/da_retry_count,
2414                              /*cbfcnp*/dadone,
2415                              /*tag_action*/MSG_SIMPLE_Q_TAG,
2416                              /*inq_buf*/(u_int8_t *)block_limits,
2417                              /*inq_len*/sizeof(*block_limits),
2418                              /*evpd*/TRUE,
2419                              /*page_code*/SVPD_BLOCK_LIMITS,
2420                              /*sense_len*/SSD_MIN_SIZE,
2421                              /*timeout*/da_default_timeout * 1000);
2422                 start_ccb->ccb_h.ccb_bp = NULL;
2423                 start_ccb->ccb_h.ccb_state = DA_CCB_PROBE_BLK_LIMITS;
2424                 xpt_action(start_ccb);
2425                 break;
2426         }
2427         case DA_STATE_PROBE_BDC:
2428         {
2429                 struct scsi_vpd_block_characteristics *bdc;
2430
2431                 if (!scsi_vpd_supported_page(periph, SVPD_BDC)) {
2432                         softc->state = DA_STATE_PROBE_ATA;
2433                         goto skipstate;
2434                 }
2435
2436                 bdc = (struct scsi_vpd_block_characteristics *)
2437                         malloc(sizeof(*bdc), M_SCSIDA, M_NOWAIT|M_ZERO);
2438
2439                 if (bdc == NULL) {
2440                         printf("dastart: Couldn't malloc bdc data\n");
2441                         /* da_free_periph??? */
2442                         break;
2443                 }
2444
2445                 scsi_inquiry(&start_ccb->csio,
2446                              /*retries*/da_retry_count,
2447                              /*cbfcnp*/dadone,
2448                              /*tag_action*/MSG_SIMPLE_Q_TAG,
2449                              /*inq_buf*/(u_int8_t *)bdc,
2450                              /*inq_len*/sizeof(*bdc),
2451                              /*evpd*/TRUE,
2452                              /*page_code*/SVPD_BDC,
2453                              /*sense_len*/SSD_MIN_SIZE,
2454                              /*timeout*/da_default_timeout * 1000);
2455                 start_ccb->ccb_h.ccb_bp = NULL;
2456                 start_ccb->ccb_h.ccb_state = DA_CCB_PROBE_BDC;
2457                 xpt_action(start_ccb);
2458                 break;
2459         }
2460         case DA_STATE_PROBE_ATA:
2461         {
2462                 struct ata_params *ata_params;
2463
2464                 if (!scsi_vpd_supported_page(periph, SVPD_ATA_INFORMATION)) {
2465                         daprobedone(periph, start_ccb);
2466                         break;
2467                 }
2468
2469                 ata_params = (struct ata_params*)
2470                         malloc(sizeof(*ata_params), M_SCSIDA, M_NOWAIT|M_ZERO);
2471
2472                 if (ata_params == NULL) {
2473                         printf("dastart: Couldn't malloc ata_params data\n");
2474                         /* da_free_periph??? */
2475                         break;
2476                 }
2477
2478                 scsi_ata_identify(&start_ccb->csio,
2479                                   /*retries*/da_retry_count,
2480                                   /*cbfcnp*/dadone,
2481                                   /*tag_action*/MSG_SIMPLE_Q_TAG,
2482                                   /*data_ptr*/(u_int8_t *)ata_params,
2483                                   /*dxfer_len*/sizeof(*ata_params),
2484                                   /*sense_len*/SSD_FULL_SIZE,
2485                                   /*timeout*/da_default_timeout * 1000);
2486                 start_ccb->ccb_h.ccb_bp = NULL;
2487                 start_ccb->ccb_h.ccb_state = DA_CCB_PROBE_ATA;
2488                 xpt_action(start_ccb);
2489                 break;
2490         }
2491         }
2492 }
2493
2494 static int
2495 cmd6workaround(union ccb *ccb)
2496 {
2497         struct scsi_rw_6 cmd6;
2498         struct scsi_rw_10 *cmd10;
2499         struct da_softc *softc;
2500         u_int8_t *cdb;
2501         struct bio *bp;
2502         int frozen;
2503
2504         cdb = ccb->csio.cdb_io.cdb_bytes;
2505         softc = (struct da_softc *)xpt_path_periph(ccb->ccb_h.path)->softc;
2506
2507         if (ccb->ccb_h.ccb_state == DA_CCB_DELETE) {
2508                 da_delete_methods old_method = softc->delete_method;
2509
2510                 /*
2511                  * Typically there are two reasons for failure here
2512                  * 1. Delete method was detected as supported but isn't
2513                  * 2. Delete failed due to invalid params e.g. too big
2514                  *
2515                  * While we will attempt to choose an alternative delete method
2516                  * this may result in short deletes if the existing delete
2517                  * requests from geom are big for the new method choosen.
2518                  *
2519                  * This method assumes that the error which triggered this
2520                  * will not retry the io otherwise a panic will occur
2521                  */
2522                 dadeleteflag(softc, old_method, 0);
2523                 dadeletemethodchoose(softc, DA_DELETE_DISABLE);
2524                 if (softc->delete_method == DA_DELETE_DISABLE)
2525                         xpt_print(ccb->ccb_h.path,
2526                                   "%s failed, disabling BIO_DELETE\n",
2527                                   da_delete_method_desc[old_method]);
2528                 else
2529                         xpt_print(ccb->ccb_h.path,
2530                                   "%s failed, switching to %s BIO_DELETE\n",
2531                                   da_delete_method_desc[old_method],
2532                                   da_delete_method_desc[softc->delete_method]);
2533
2534                 if (DA_SIO) {
2535                         while ((bp = bioq_takefirst(&softc->delete_run_queue))
2536                             != NULL)
2537                                 bioq_disksort(&softc->delete_queue, bp);
2538                 } else {
2539                         while ((bp = bioq_takefirst(&softc->delete_run_queue))
2540                             != NULL)
2541                                 bioq_insert_tail(&softc->delete_queue, bp);
2542                 }
2543                 bioq_insert_tail(&softc->delete_queue,
2544                     (struct bio *)ccb->ccb_h.ccb_bp);
2545                 ccb->ccb_h.ccb_bp = NULL;
2546                 return (0);
2547         }
2548
2549         /* Translation only possible if CDB is an array and cmd is R/W6 */
2550         if ((ccb->ccb_h.flags & CAM_CDB_POINTER) != 0 ||
2551             (*cdb != READ_6 && *cdb != WRITE_6))
2552                 return 0;
2553
2554         xpt_print(ccb->ccb_h.path, "READ(6)/WRITE(6) not supported, "
2555             "increasing minimum_cmd_size to 10.\n");
2556         softc->minimum_cmd_size = 10;
2557
2558         bcopy(cdb, &cmd6, sizeof(struct scsi_rw_6));
2559         cmd10 = (struct scsi_rw_10 *)cdb;
2560         cmd10->opcode = (cmd6.opcode == READ_6) ? READ_10 : WRITE_10;
2561         cmd10->byte2 = 0;
2562         scsi_ulto4b(scsi_3btoul(cmd6.addr), cmd10->addr);
2563         cmd10->reserved = 0;
2564         scsi_ulto2b(cmd6.length, cmd10->length);
2565         cmd10->control = cmd6.control;
2566         ccb->csio.cdb_len = sizeof(*cmd10);
2567
2568         /* Requeue request, unfreezing queue if necessary */
2569         frozen = (ccb->ccb_h.status & CAM_DEV_QFRZN) != 0;
2570         ccb->ccb_h.status = CAM_REQUEUE_REQ;
2571         xpt_action(ccb);
2572         if (frozen) {
2573                 cam_release_devq(ccb->ccb_h.path,
2574                                  /*relsim_flags*/0,
2575                                  /*reduction*/0,
2576                                  /*timeout*/0,
2577                                  /*getcount_only*/0);
2578         }
2579         return (ERESTART);
2580 }
2581
2582 static void
2583 dadone(struct cam_periph *periph, union ccb *done_ccb)
2584 {
2585         struct da_softc *softc;
2586         struct ccb_scsiio *csio;
2587         u_int32_t  priority;
2588         da_ccb_state state;
2589
2590         softc = (struct da_softc *)periph->softc;
2591         priority = done_ccb->ccb_h.pinfo.priority;
2592
2593         CAM_DEBUG(periph->path, CAM_DEBUG_TRACE, ("dadone\n"));
2594
2595         csio = &done_ccb->csio;
2596         state = csio->ccb_h.ccb_state & DA_CCB_TYPE_MASK;
2597         switch (state) {
2598         case DA_CCB_BUFFER_IO:
2599         case DA_CCB_DELETE:
2600         {
2601                 struct bio *bp, *bp1;
2602
2603                 bp = (struct bio *)done_ccb->ccb_h.ccb_bp;
2604                 if ((done_ccb->ccb_h.status & CAM_STATUS_MASK) != CAM_REQ_CMP) {
2605                         int error;
2606                         int sf;
2607
2608                         if ((csio->ccb_h.ccb_state & DA_CCB_RETRY_UA) != 0)
2609                                 sf = SF_RETRY_UA;
2610                         else
2611                                 sf = 0;
2612
2613                         error = daerror(done_ccb, CAM_RETRY_SELTO, sf);
2614                         if (error == ERESTART) {
2615                                 /*
2616                                  * A retry was scheduled, so
2617                                  * just return.
2618                                  */
2619                                 return;
2620                         }
2621                         bp = (struct bio *)done_ccb->ccb_h.ccb_bp;
2622                         if (error != 0) {
2623                                 int queued_error;
2624
2625                                 /*
2626                                  * return all queued I/O with EIO, so that
2627                                  * the client can retry these I/Os in the
2628                                  * proper order should it attempt to recover.
2629                                  */
2630                                 queued_error = EIO;
2631
2632                                 if (error == ENXIO
2633                                  && (softc->flags & DA_FLAG_PACK_INVALID)== 0) {
2634                                         /*
2635                                          * Catastrophic error.  Mark our pack as
2636                                          * invalid.
2637                                          */
2638                                         /*
2639                                          * XXX See if this is really a media
2640                                          * XXX change first?
2641                                          */
2642                                         xpt_print(periph->path,
2643                                             "Invalidating pack\n");
2644                                         softc->flags |= DA_FLAG_PACK_INVALID;
2645                                         queued_error = ENXIO;
2646                                 }
2647                                 bioq_flush(&softc->bio_queue, NULL,
2648                                            queued_error);
2649                                 if (bp != NULL) {
2650                                         bp->bio_error = error;
2651                                         bp->bio_resid = bp->bio_bcount;
2652                                         bp->bio_flags |= BIO_ERROR;
2653                                 }
2654                         } else if (bp != NULL) {
2655                                 bp->bio_resid = csio->resid;
2656                                 bp->bio_error = 0;
2657                                 if (bp->bio_resid != 0)
2658                                         bp->bio_flags |= BIO_ERROR;
2659                         }
2660                         if ((done_ccb->ccb_h.status & CAM_DEV_QFRZN) != 0)
2661                                 cam_release_devq(done_ccb->ccb_h.path,
2662                                                  /*relsim_flags*/0,
2663                                                  /*reduction*/0,
2664                                                  /*timeout*/0,
2665                                                  /*getcount_only*/0);
2666                 } else if (bp != NULL) {
2667                         if ((done_ccb->ccb_h.status & CAM_DEV_QFRZN) != 0)
2668                                 panic("REQ_CMP with QFRZN");
2669                         bp->bio_resid = csio->resid;
2670                         if (csio->resid > 0)
2671                                 bp->bio_flags |= BIO_ERROR;
2672                         if (softc->error_inject != 0) {
2673                                 bp->bio_error = softc->error_inject;
2674                                 bp->bio_resid = bp->bio_bcount;
2675                                 bp->bio_flags |= BIO_ERROR;
2676                                 softc->error_inject = 0;
2677                         }
2678
2679                 }
2680
2681                 /*
2682                  * Block out any asyncronous callbacks
2683                  * while we touch the pending ccb list.
2684                  */
2685                 LIST_REMOVE(&done_ccb->ccb_h, periph_links.le);
2686                 softc->outstanding_cmds--;
2687                 if (softc->outstanding_cmds == 0)
2688                         softc->flags |= DA_FLAG_WENT_IDLE;
2689
2690                 if ((softc->flags & DA_FLAG_PACK_INVALID) != 0) {
2691                         xpt_print(periph->path, "oustanding %d\n",
2692                                   softc->outstanding_cmds);
2693                 }
2694
2695                 if (state == DA_CCB_DELETE) {
2696                         while ((bp1 = bioq_takefirst(&softc->delete_run_queue))
2697                             != NULL) {
2698                                 bp1->bio_resid = bp->bio_resid;
2699                                 bp1->bio_error = bp->bio_error;
2700                                 if (bp->bio_flags & BIO_ERROR)
2701                                         bp1->bio_flags |= BIO_ERROR;
2702                                 biodone(bp1);
2703                         }
2704                         softc->delete_running = 0;
2705                         if (bp != NULL)
2706                                 biodone(bp);
2707                         daschedule(periph);
2708                 } else if (bp != NULL)
2709                         biodone(bp);
2710                 break;
2711         }
2712         case DA_CCB_PROBE_RC:
2713         case DA_CCB_PROBE_RC16:
2714         {
2715                 struct     scsi_read_capacity_data *rdcap;
2716                 struct     scsi_read_capacity_data_long *rcaplong;
2717                 char       announce_buf[80];
2718                 int        lbp;
2719
2720                 lbp = 0;
2721                 rdcap = NULL;
2722                 rcaplong = NULL;
2723                 if (state == DA_CCB_PROBE_RC)
2724                         rdcap =(struct scsi_read_capacity_data *)csio->data_ptr;
2725                 else
2726                         rcaplong = (struct scsi_read_capacity_data_long *)
2727                                 csio->data_ptr;
2728
2729                 if ((csio->ccb_h.status & CAM_STATUS_MASK) == CAM_REQ_CMP) {
2730                         struct disk_params *dp;
2731                         uint32_t block_size;
2732                         uint64_t maxsector;
2733                         u_int lbppbe;   /* LB per physical block exponent. */
2734                         u_int lalba;    /* Lowest aligned LBA. */
2735
2736                         if (state == DA_CCB_PROBE_RC) {
2737                                 block_size = scsi_4btoul(rdcap->length);
2738                                 maxsector = scsi_4btoul(rdcap->addr);
2739                                 lbppbe = 0;
2740                                 lalba = 0;
2741
2742                                 /*
2743                                  * According to SBC-2, if the standard 10
2744                                  * byte READ CAPACITY command returns 2^32,
2745                                  * we should issue the 16 byte version of
2746                                  * the command, since the device in question
2747                                  * has more sectors than can be represented
2748                                  * with the short version of the command.
2749                                  */
2750                                 if (maxsector == 0xffffffff) {
2751                                         free(rdcap, M_SCSIDA);
2752                                         xpt_release_ccb(done_ccb);
2753                                         softc->state = DA_STATE_PROBE_RC16;
2754                                         xpt_schedule(periph, priority);
2755                                         return;
2756                                 }
2757                         } else {
2758                                 block_size = scsi_4btoul(rcaplong->length);
2759                                 maxsector = scsi_8btou64(rcaplong->addr);
2760                                 lbppbe = rcaplong->prot_lbppbe & SRC16_LBPPBE;
2761                                 lalba = scsi_2btoul(rcaplong->lalba_lbp);
2762                         }
2763
2764                         /*
2765                          * Because GEOM code just will panic us if we
2766                          * give them an 'illegal' value we'll avoid that
2767                          * here.
2768                          */
2769                         if (block_size == 0 && maxsector == 0) {
2770                                 snprintf(announce_buf, sizeof(announce_buf),
2771                                         "0MB (no media?)");
2772                         } else if (block_size >= MAXPHYS || block_size == 0) {
2773                                 xpt_print(periph->path,
2774                                     "unsupportable block size %ju\n",
2775                                     (uintmax_t) block_size);
2776                                 announce_buf[0] = '\0';
2777                                 cam_periph_invalidate(periph);
2778                         } else {
2779                                 /*
2780                                  * We pass rcaplong into dasetgeom(),
2781                                  * because it will only use it if it is
2782                                  * non-NULL.
2783                                  */
2784                                 dasetgeom(periph, block_size, maxsector,
2785                                           rcaplong, sizeof(*rcaplong));
2786                                 lbp = (lalba & SRC16_LBPME_A);
2787                                 dp = &softc->params;
2788                                 snprintf(announce_buf, sizeof(announce_buf),
2789                                         "%juMB (%ju %u byte sectors: %dH %dS/T "
2790                                         "%dC)", (uintmax_t)
2791                                         (((uintmax_t)dp->secsize *
2792                                         dp->sectors) / (1024*1024)),
2793                                         (uintmax_t)dp->sectors,
2794                                         dp->secsize, dp->heads,
2795                                         dp->secs_per_track, dp->cylinders);
2796                         }
2797                 } else {
2798                         int     error;
2799
2800                         announce_buf[0] = '\0';
2801
2802                         /*
2803                          * Retry any UNIT ATTENTION type errors.  They
2804                          * are expected at boot.
2805                          */
2806                         error = daerror(done_ccb, CAM_RETRY_SELTO,
2807                                         SF_RETRY_UA|SF_NO_PRINT);
2808                         if (error == ERESTART) {
2809                                 /*
2810                                  * A retry was scheuled, so
2811                                  * just return.
2812                                  */
2813                                 return;
2814                         } else if (error != 0) {
2815                                 int asc, ascq;
2816                                 int sense_key, error_code;
2817                                 int have_sense;
2818                                 cam_status status;
2819                                 struct ccb_getdev cgd;
2820
2821                                 /* Don't wedge this device's queue */
2822                                 status = done_ccb->ccb_h.status;
2823                                 if ((status & CAM_DEV_QFRZN) != 0)
2824                                         cam_release_devq(done_ccb->ccb_h.path,
2825                                                          /*relsim_flags*/0,
2826                                                          /*reduction*/0,
2827                                                          /*timeout*/0,
2828                                                          /*getcount_only*/0);
2829
2830
2831                                 xpt_setup_ccb(&cgd.ccb_h, 
2832                                               done_ccb->ccb_h.path,
2833                                               CAM_PRIORITY_NORMAL);
2834                                 cgd.ccb_h.func_code = XPT_GDEV_TYPE;
2835                                 xpt_action((union ccb *)&cgd);
2836
2837                                 if (scsi_extract_sense_ccb(done_ccb,
2838                                     &error_code, &sense_key, &asc, &ascq))
2839                                         have_sense = TRUE;
2840                                 else
2841                                         have_sense = FALSE;
2842
2843                                 /*
2844                                  * If we tried READ CAPACITY(16) and failed,
2845                                  * fallback to READ CAPACITY(10).
2846                                  */
2847                                 if ((state == DA_CCB_PROBE_RC16) &&
2848                                     (softc->flags & DA_FLAG_CAN_RC16) &&
2849                                     (((csio->ccb_h.status & CAM_STATUS_MASK) ==
2850                                         CAM_REQ_INVALID) ||
2851                                      ((have_sense) &&
2852                                       (error_code == SSD_CURRENT_ERROR) &&
2853                                       (sense_key == SSD_KEY_ILLEGAL_REQUEST)))) {
2854                                         softc->flags &= ~DA_FLAG_CAN_RC16;
2855                                         free(rdcap, M_SCSIDA);
2856                                         xpt_release_ccb(done_ccb);
2857                                         softc->state = DA_STATE_PROBE_RC;
2858                                         xpt_schedule(periph, priority);
2859                                         return;
2860                                 } else
2861                                 /*
2862                                  * Attach to anything that claims to be a
2863                                  * direct access or optical disk device,
2864                                  * as long as it doesn't return a "Logical
2865                                  * unit not supported" (0x25) error.
2866                                  */
2867                                 if ((have_sense) && (asc != 0x25)
2868                                  && (error_code == SSD_CURRENT_ERROR)) {
2869                                         const char *sense_key_desc;
2870                                         const char *asc_desc;
2871
2872                                         scsi_sense_desc(sense_key, asc, ascq,
2873                                                         &cgd.inq_data,
2874                                                         &sense_key_desc,
2875                                                         &asc_desc);
2876                                         snprintf(announce_buf,
2877                                             sizeof(announce_buf),
2878                                                 "Attempt to query device "
2879                                                 "size failed: %s, %s",
2880                                                 sense_key_desc,
2881                                                 asc_desc);
2882                                 } else { 
2883                                         if (have_sense)
2884                                                 scsi_sense_print(
2885                                                         &done_ccb->csio);
2886                                         else {
2887                                                 xpt_print(periph->path,
2888                                                     "got CAM status %#x\n",
2889                                                     done_ccb->ccb_h.status);
2890                                         }
2891
2892                                         xpt_print(periph->path, "fatal error, "
2893                                             "failed to attach to device\n");
2894
2895                                         /*
2896                                          * Free up resources.
2897                                          */
2898                                         cam_periph_invalidate(periph);
2899                                 } 
2900                         }
2901                 }
2902                 free(csio->data_ptr, M_SCSIDA);
2903                 if (announce_buf[0] != '\0' && ((softc->flags & DA_FLAG_PROBED) == 0)) {
2904                         /*
2905                          * Create our sysctl variables, now that we know
2906                          * we have successfully attached.
2907                          */
2908                         /* increase the refcount */
2909                         if (cam_periph_acquire(periph) == CAM_REQ_CMP) {
2910                                 taskqueue_enqueue(taskqueue_thread,
2911                                                   &softc->sysctl_task);
2912                                 xpt_announce_periph(periph, announce_buf);
2913                                 xpt_announce_quirks(periph, softc->quirks,
2914                                     DA_Q_BIT_STRING);
2915                         } else {
2916                                 xpt_print(periph->path, "fatal error, "
2917                                     "could not acquire reference count\n");
2918                         }
2919                 }
2920
2921                 /* Ensure re-probe doesn't see old delete. */
2922                 softc->delete_available = 0;
2923                 if (lbp) {
2924                         /*
2925                          * Based on older SBC-3 spec revisions
2926                          * any of the UNMAP methods "may" be
2927                          * available via LBP given this flag so
2928                          * we flag all of them as availble and
2929                          * then remove those which further
2930                          * probes confirm aren't available
2931                          * later.
2932                          *
2933                          * We could also check readcap(16) p_type
2934                          * flag to exclude one or more invalid
2935                          * write same (X) types here
2936                          */
2937                         dadeleteflag(softc, DA_DELETE_WS16, 1);
2938                         dadeleteflag(softc, DA_DELETE_WS10, 1);
2939                         dadeleteflag(softc, DA_DELETE_ZERO, 1);
2940                         dadeleteflag(softc, DA_DELETE_UNMAP, 1);
2941
2942                         xpt_release_ccb(done_ccb);
2943                         softc->state = DA_STATE_PROBE_LBP;
2944                         xpt_schedule(periph, priority);
2945                         return;
2946                 }
2947
2948                 xpt_release_ccb(done_ccb);
2949                 softc->state = DA_STATE_PROBE_BDC;
2950                 xpt_schedule(periph, priority);
2951                 return;
2952         }
2953         case DA_CCB_PROBE_LBP:
2954         {
2955                 struct scsi_vpd_logical_block_prov *lbp;
2956
2957                 lbp = (struct scsi_vpd_logical_block_prov *)csio->data_ptr;
2958
2959                 if ((csio->ccb_h.status & CAM_STATUS_MASK) == CAM_REQ_CMP) {
2960                         /*
2961                          * T10/1799-D Revision 31 states at least one of these
2962                          * must be supported but we don't currently enforce this.
2963                          */
2964                         dadeleteflag(softc, DA_DELETE_WS16,
2965                                      (lbp->flags & SVPD_LBP_WS16));
2966                         dadeleteflag(softc, DA_DELETE_WS10,
2967                                      (lbp->flags & SVPD_LBP_WS10));
2968                         dadeleteflag(softc, DA_DELETE_ZERO,
2969                                      (lbp->flags & SVPD_LBP_WS10));
2970                         dadeleteflag(softc, DA_DELETE_UNMAP,
2971                                      (lbp->flags & SVPD_LBP_UNMAP));
2972
2973                         if (lbp->flags & SVPD_LBP_UNMAP) {
2974                                 free(lbp, M_SCSIDA);
2975                                 xpt_release_ccb(done_ccb);
2976                                 softc->state = DA_STATE_PROBE_BLK_LIMITS;
2977                                 xpt_schedule(periph, priority);
2978                                 return;
2979                         }
2980                 } else {
2981                         int error;
2982                         error = daerror(done_ccb, CAM_RETRY_SELTO,
2983                                         SF_RETRY_UA|SF_NO_PRINT);
2984                         if (error == ERESTART)
2985                                 return;
2986                         else if (error != 0) {
2987                                 if ((done_ccb->ccb_h.status & CAM_DEV_QFRZN) != 0) {
2988                                         /* Don't wedge this device's queue */
2989                                         cam_release_devq(done_ccb->ccb_h.path,
2990                                                          /*relsim_flags*/0,
2991                                                          /*reduction*/0,
2992                                                          /*timeout*/0,
2993                                                          /*getcount_only*/0);
2994                                 }
2995
2996                                 /*
2997                                  * Failure indicates we don't support any SBC-3
2998                                  * delete methods with UNMAP
2999                                  */
3000                         }
3001                 }
3002
3003                 free(lbp, M_SCSIDA);
3004                 xpt_release_ccb(done_ccb);
3005                 softc->state = DA_STATE_PROBE_BDC;
3006                 xpt_schedule(periph, priority);
3007                 return;
3008         }
3009         case DA_CCB_PROBE_BLK_LIMITS:
3010         {
3011                 struct scsi_vpd_block_limits *block_limits;
3012
3013                 block_limits = (struct scsi_vpd_block_limits *)csio->data_ptr;
3014
3015                 if ((csio->ccb_h.status & CAM_STATUS_MASK) == CAM_REQ_CMP) {
3016                         uint32_t max_unmap_lba_cnt = scsi_4btoul(
3017                                 block_limits->max_unmap_lba_cnt);
3018                         uint32_t max_unmap_blk_cnt = scsi_4btoul(
3019                                 block_limits->max_unmap_blk_cnt);
3020                         uint64_t ws_max_blks = scsi_8btou64(
3021                                 block_limits->max_write_same_length);
3022                         /*
3023                          * We should already support UNMAP but we check lba
3024                          * and block count to be sure
3025                          */
3026                         if (max_unmap_lba_cnt != 0x00L &&
3027                             max_unmap_blk_cnt != 0x00L) {
3028                                 softc->unmap_max_lba = max_unmap_lba_cnt;
3029                                 softc->unmap_max_ranges = min(max_unmap_blk_cnt,
3030                                         UNMAP_MAX_RANGES);
3031                         } else {
3032                                 /*
3033                                  * Unexpected UNMAP limits which means the
3034                                  * device doesn't actually support UNMAP
3035                                  */
3036                                 dadeleteflag(softc, DA_DELETE_UNMAP, 0);
3037                         }
3038
3039                         if (ws_max_blks != 0x00L)
3040                                 softc->ws_max_blks = ws_max_blks;
3041                 } else {
3042                         int error;
3043                         error = daerror(done_ccb, CAM_RETRY_SELTO,
3044                                         SF_RETRY_UA|SF_NO_PRINT);
3045                         if (error == ERESTART)
3046                                 return;
3047                         else if (error != 0) {
3048                                 if ((done_ccb->ccb_h.status & CAM_DEV_QFRZN) != 0) {
3049                                         /* Don't wedge this device's queue */
3050                                         cam_release_devq(done_ccb->ccb_h.path,
3051                                                          /*relsim_flags*/0,
3052                                                          /*reduction*/0,
3053                                                          /*timeout*/0,
3054                                                          /*getcount_only*/0);
3055                                 }
3056
3057                                 /*
3058                                  * Failure here doesn't mean UNMAP is not
3059                                  * supported as this is an optional page.
3060                                  */
3061                                 softc->unmap_max_lba = 1;
3062                                 softc->unmap_max_ranges = 1;
3063                         }
3064                 }
3065
3066                 free(block_limits, M_SCSIDA);
3067                 xpt_release_ccb(done_ccb);
3068                 softc->state = DA_STATE_PROBE_BDC;
3069                 xpt_schedule(periph, priority);
3070                 return;
3071         }
3072         case DA_CCB_PROBE_BDC:
3073         {
3074                 struct scsi_vpd_block_characteristics *bdc;
3075
3076                 bdc = (struct scsi_vpd_block_characteristics *)csio->data_ptr;
3077
3078                 if ((csio->ccb_h.status & CAM_STATUS_MASK) == CAM_REQ_CMP) {
3079                         /*
3080                          * Disable queue sorting for non-rotational media
3081                          * by default.
3082                          */
3083                         if (scsi_2btoul(bdc->medium_rotation_rate) ==
3084                             SVPD_BDC_RATE_NONE_ROTATING)
3085                                 softc->sort_io_queue = 0;
3086                 } else {
3087                         int error;
3088                         error = daerror(done_ccb, CAM_RETRY_SELTO,
3089                                         SF_RETRY_UA|SF_NO_PRINT);
3090                         if (error == ERESTART)
3091                                 return;
3092                         else if (error != 0) {
3093                                 if ((done_ccb->ccb_h.status & CAM_DEV_QFRZN) != 0) {
3094                                         /* Don't wedge this device's queue */
3095                                         cam_release_devq(done_ccb->ccb_h.path,
3096                                                          /*relsim_flags*/0,
3097                                                          /*reduction*/0,
3098                                                          /*timeout*/0,
3099                                                          /*getcount_only*/0);
3100                                 }
3101                         }
3102                 }
3103
3104                 free(bdc, M_SCSIDA);
3105                 xpt_release_ccb(done_ccb);
3106                 softc->state = DA_STATE_PROBE_ATA;
3107                 xpt_schedule(periph, priority);
3108                 return;
3109         }
3110         case DA_CCB_PROBE_ATA:
3111         {
3112                 int i;
3113                 struct ata_params *ata_params;
3114                 int16_t *ptr;
3115
3116                 ata_params = (struct ata_params *)csio->data_ptr;
3117                 ptr = (uint16_t *)ata_params;
3118
3119                 if ((csio->ccb_h.status & CAM_STATUS_MASK) == CAM_REQ_CMP) {
3120                         for (i = 0; i < sizeof(*ata_params) / 2; i++)
3121                                 ptr[i] = le16toh(ptr[i]);
3122                         if (ata_params->support_dsm & ATA_SUPPORT_DSM_TRIM) {
3123                                 dadeleteflag(softc, DA_DELETE_ATA_TRIM, 1);
3124                                 if (ata_params->max_dsm_blocks != 0)
3125                                         softc->trim_max_ranges = min(
3126                                           softc->trim_max_ranges,
3127                                           ata_params->max_dsm_blocks *
3128                                           ATA_DSM_BLK_RANGES);
3129                         }
3130                         /*
3131                          * Disable queue sorting for non-rotational media
3132                          * by default.
3133                          */
3134                         if (ata_params->media_rotation_rate == 1)
3135                                 softc->sort_io_queue = 0;
3136                 } else {
3137                         int error;
3138                         error = daerror(done_ccb, CAM_RETRY_SELTO,
3139                                         SF_RETRY_UA|SF_NO_PRINT);
3140                         if (error == ERESTART)
3141                                 return;
3142                         else if (error != 0) {
3143                                 if ((done_ccb->ccb_h.status & CAM_DEV_QFRZN) != 0) {
3144                                         /* Don't wedge this device's queue */
3145                                         cam_release_devq(done_ccb->ccb_h.path,
3146                                                          /*relsim_flags*/0,
3147                                                          /*reduction*/0,
3148                                                          /*timeout*/0,
3149                                                          /*getcount_only*/0);
3150                                 }
3151                         }
3152                 }
3153
3154                 free(ata_params, M_SCSIDA);
3155                 daprobedone(periph, done_ccb);
3156                 return;
3157         }
3158         case DA_CCB_WAITING:
3159         {
3160                 /* Caller will release the CCB */
3161                 wakeup(&done_ccb->ccb_h.cbfcnp);
3162                 return;
3163         }
3164         case DA_CCB_DUMP:
3165                 /* No-op.  We're polling */
3166                 return;
3167         case DA_CCB_TUR:
3168         {
3169                 if ((done_ccb->ccb_h.status & CAM_STATUS_MASK) != CAM_REQ_CMP) {
3170
3171                         if (daerror(done_ccb, CAM_RETRY_SELTO,
3172                             SF_RETRY_UA | SF_NO_RECOVERY | SF_NO_PRINT) ==
3173                             ERESTART)
3174                                 return;
3175                         if ((done_ccb->ccb_h.status & CAM_DEV_QFRZN) != 0)
3176                                 cam_release_devq(done_ccb->ccb_h.path,
3177                                                  /*relsim_flags*/0,
3178                                                  /*reduction*/0,
3179                                                  /*timeout*/0,
3180                                                  /*getcount_only*/0);
3181                 }
3182                 xpt_release_ccb(done_ccb);
3183                 cam_periph_release_locked(periph);
3184                 return;
3185         }
3186         default:
3187                 break;
3188         }
3189         xpt_release_ccb(done_ccb);
3190 }
3191
3192 static void
3193 dareprobe(struct cam_periph *periph)
3194 {
3195         struct da_softc   *softc;
3196         cam_status status;
3197
3198         softc = (struct da_softc *)periph->softc;
3199
3200         /* Probe in progress; don't interfere. */
3201         if (softc->state != DA_STATE_NORMAL)
3202                 return;
3203
3204         status = cam_periph_acquire(periph);
3205         KASSERT(status == CAM_REQ_CMP,
3206             ("dareprobe: cam_periph_acquire failed"));
3207
3208         if (softc->flags & DA_FLAG_CAN_RC16)
3209                 softc->state = DA_STATE_PROBE_RC16;
3210         else
3211                 softc->state = DA_STATE_PROBE_RC;
3212
3213         xpt_schedule(periph, CAM_PRIORITY_DEV);
3214 }
3215
3216 static int
3217 daerror(union ccb *ccb, u_int32_t cam_flags, u_int32_t sense_flags)
3218 {
3219         struct da_softc   *softc;
3220         struct cam_periph *periph;
3221         int error, error_code, sense_key, asc, ascq;
3222
3223         periph = xpt_path_periph(ccb->ccb_h.path);
3224         softc = (struct da_softc *)periph->softc;
3225
3226         /*
3227          * Automatically detect devices that do not support
3228          * READ(6)/WRITE(6) and upgrade to using 10 byte cdbs.
3229          */
3230         error = 0;
3231         if ((ccb->ccb_h.status & CAM_STATUS_MASK) == CAM_REQ_INVALID) {
3232                 error = cmd6workaround(ccb);
3233         } else if (scsi_extract_sense_ccb(ccb,
3234             &error_code, &sense_key, &asc, &ascq)) {
3235                 if (sense_key == SSD_KEY_ILLEGAL_REQUEST)
3236                         error = cmd6workaround(ccb);
3237                 /*
3238                  * If the target replied with CAPACITY DATA HAS CHANGED UA,
3239                  * query the capacity and notify upper layers.
3240                  */
3241                 else if (sense_key == SSD_KEY_UNIT_ATTENTION &&
3242                     asc == 0x2A && ascq == 0x09) {
3243                         xpt_print(periph->path, "capacity data has changed\n");
3244                         dareprobe(periph);
3245                         sense_flags |= SF_NO_PRINT;
3246                 } else if (sense_key == SSD_KEY_UNIT_ATTENTION &&
3247                     asc == 0x28 && ascq == 0x00)
3248                         disk_media_changed(softc->disk, M_NOWAIT);
3249                 else if (sense_key == SSD_KEY_NOT_READY &&
3250                     asc == 0x3a && (softc->flags & DA_FLAG_SAW_MEDIA)) {
3251                         softc->flags &= ~DA_FLAG_SAW_MEDIA;
3252                         disk_media_gone(softc->disk, M_NOWAIT);
3253                 }
3254         }
3255         if (error == ERESTART)
3256                 return (ERESTART);
3257
3258         /*
3259          * XXX
3260          * Until we have a better way of doing pack validation,
3261          * don't treat UAs as errors.
3262          */
3263         sense_flags |= SF_RETRY_UA;
3264         return(cam_periph_error(ccb, cam_flags, sense_flags,
3265                                 &softc->saved_ccb));
3266 }
3267
3268 static void
3269 damediapoll(void *arg)
3270 {
3271         struct cam_periph *periph = arg;
3272         struct da_softc *softc = periph->softc;
3273
3274         if (!softc->tur && softc->outstanding_cmds == 0) {
3275                 if (cam_periph_acquire(periph) == CAM_REQ_CMP) {
3276                         softc->tur = 1;
3277                         daschedule(periph);
3278                 }
3279         }
3280         /* Queue us up again */
3281         if (da_poll_period != 0)
3282                 callout_schedule(&softc->mediapoll_c, da_poll_period * hz);
3283 }
3284
3285 static void
3286 daprevent(struct cam_periph *periph, int action)
3287 {
3288         struct  da_softc *softc;
3289         union   ccb *ccb;               
3290         int     error;
3291                 
3292         softc = (struct da_softc *)periph->softc;
3293
3294         if (((action == PR_ALLOW)
3295           && (softc->flags & DA_FLAG_PACK_LOCKED) == 0)
3296          || ((action == PR_PREVENT)
3297           && (softc->flags & DA_FLAG_PACK_LOCKED) != 0)) {
3298                 return;
3299         }
3300
3301         ccb = cam_periph_getccb(periph, CAM_PRIORITY_NORMAL);
3302
3303         scsi_prevent(&ccb->csio,
3304                      /*retries*/1,
3305                      /*cbcfp*/dadone,
3306                      MSG_SIMPLE_Q_TAG,
3307                      action,
3308                      SSD_FULL_SIZE,
3309                      5000);
3310
3311         error = cam_periph_runccb(ccb, daerror, CAM_RETRY_SELTO,
3312             SF_RETRY_UA | SF_QUIET_IR, softc->disk->d_devstat);
3313
3314         if (error == 0) {
3315                 if (action == PR_ALLOW)
3316                         softc->flags &= ~DA_FLAG_PACK_LOCKED;
3317                 else
3318                         softc->flags |= DA_FLAG_PACK_LOCKED;
3319         }
3320
3321         xpt_release_ccb(ccb);
3322 }
3323
3324 static void
3325 dasetgeom(struct cam_periph *periph, uint32_t block_len, uint64_t maxsector,
3326           struct scsi_read_capacity_data_long *rcaplong, size_t rcap_len)
3327 {
3328         struct ccb_calc_geometry ccg;
3329         struct da_softc *softc;
3330         struct disk_params *dp;
3331         u_int lbppbe, lalba;
3332
3333         softc = (struct da_softc *)periph->softc;
3334
3335         dp = &softc->params;
3336         dp->secsize = block_len;
3337         dp->sectors = maxsector + 1;
3338         if (rcaplong != NULL) {
3339                 lbppbe = rcaplong->prot_lbppbe & SRC16_LBPPBE;
3340                 lalba = scsi_2btoul(rcaplong->lalba_lbp);
3341                 lalba &= SRC16_LALBA_A;
3342         } else {
3343                 lbppbe = 0;
3344                 lalba = 0;
3345         }
3346
3347         if (lbppbe > 0) {
3348                 dp->stripesize = block_len << lbppbe;
3349                 dp->stripeoffset = (dp->stripesize - block_len * lalba) %
3350                     dp->stripesize;
3351         } else if (softc->quirks & DA_Q_4K) {
3352                 dp->stripesize = 4096;
3353                 dp->stripeoffset = 0;
3354         } else {
3355                 dp->stripesize = 0;
3356                 dp->stripeoffset = 0;
3357         }
3358         /*
3359          * Have the controller provide us with a geometry
3360          * for this disk.  The only time the geometry
3361          * matters is when we boot and the controller
3362          * is the only one knowledgeable enough to come
3363          * up with something that will make this a bootable
3364          * device.
3365          */
3366         xpt_setup_ccb(&ccg.ccb_h, periph->path, CAM_PRIORITY_NORMAL);
3367         ccg.ccb_h.func_code = XPT_CALC_GEOMETRY;
3368         ccg.block_size = dp->secsize;
3369         ccg.volume_size = dp->sectors;
3370         ccg.heads = 0;
3371         ccg.secs_per_track = 0;
3372         ccg.cylinders = 0;
3373         xpt_action((union ccb*)&ccg);
3374         if ((ccg.ccb_h.status & CAM_STATUS_MASK) != CAM_REQ_CMP) {
3375                 /*
3376                  * We don't know what went wrong here- but just pick
3377                  * a geometry so we don't have nasty things like divide
3378                  * by zero.
3379                  */
3380                 dp->heads = 255;
3381                 dp->secs_per_track = 255;
3382                 dp->cylinders = dp->sectors / (255 * 255);
3383                 if (dp->cylinders == 0) {
3384                         dp->cylinders = 1;
3385                 }
3386         } else {
3387                 dp->heads = ccg.heads;
3388                 dp->secs_per_track = ccg.secs_per_track;
3389                 dp->cylinders = ccg.cylinders;
3390         }
3391
3392         /*
3393          * If the user supplied a read capacity buffer, and if it is
3394          * different than the previous buffer, update the data in the EDT.
3395          * If it's the same, we don't bother.  This avoids sending an
3396          * update every time someone opens this device.
3397          */
3398         if ((rcaplong != NULL)
3399          && (bcmp(rcaplong, &softc->rcaplong,
3400                   min(sizeof(softc->rcaplong), rcap_len)) != 0)) {
3401                 struct ccb_dev_advinfo cdai;
3402
3403                 xpt_setup_ccb(&cdai.ccb_h, periph->path, CAM_PRIORITY_NORMAL);
3404                 cdai.ccb_h.func_code = XPT_DEV_ADVINFO;
3405                 cdai.buftype = CDAI_TYPE_RCAPLONG;
3406                 cdai.flags |= CDAI_FLAG_STORE;
3407                 cdai.bufsiz = rcap_len;
3408                 cdai.buf = (uint8_t *)rcaplong;
3409                 xpt_action((union ccb *)&cdai);
3410                 if ((cdai.ccb_h.status & CAM_DEV_QFRZN) != 0)
3411                         cam_release_devq(cdai.ccb_h.path, 0, 0, 0, FALSE);
3412                 if (cdai.ccb_h.status != CAM_REQ_CMP) {
3413                         xpt_print(periph->path, "%s: failed to set read "
3414                                   "capacity advinfo\n", __func__);
3415                         /* Use cam_error_print() to decode the status */
3416                         cam_error_print((union ccb *)&cdai, CAM_ESF_CAM_STATUS,
3417                                         CAM_EPF_ALL);
3418                 } else {
3419                         bcopy(rcaplong, &softc->rcaplong,
3420                               min(sizeof(softc->rcaplong), rcap_len));
3421                 }
3422         }
3423
3424         softc->disk->d_sectorsize = softc->params.secsize;
3425         softc->disk->d_mediasize = softc->params.secsize * (off_t)softc->params.sectors;
3426         softc->disk->d_stripesize = softc->params.stripesize;
3427         softc->disk->d_stripeoffset = softc->params.stripeoffset;
3428         /* XXX: these are not actually "firmware" values, so they may be wrong */
3429         softc->disk->d_fwsectors = softc->params.secs_per_track;
3430         softc->disk->d_fwheads = softc->params.heads;
3431         softc->disk->d_devstat->block_size = softc->params.secsize;
3432         softc->disk->d_devstat->flags &= ~DEVSTAT_BS_UNAVAILABLE;
3433 }
3434
3435 static void
3436 dasendorderedtag(void *arg)
3437 {
3438         struct da_softc *softc = arg;
3439
3440         if (da_send_ordered) {
3441                 if ((softc->ordered_tag_count == 0) 
3442                  && ((softc->flags & DA_FLAG_WENT_IDLE) == 0)) {
3443                         softc->flags |= DA_FLAG_NEED_OTAG;
3444                 }
3445                 if (softc->outstanding_cmds > 0)
3446                         softc->flags &= ~DA_FLAG_WENT_IDLE;
3447
3448                 softc->ordered_tag_count = 0;
3449         }
3450         /* Queue us up again */
3451         callout_reset(&softc->sendordered_c,
3452             (da_default_timeout * hz) / DA_ORDEREDTAG_INTERVAL,
3453             dasendorderedtag, softc);
3454 }
3455
3456 /*
3457  * Step through all DA peripheral drivers, and if the device is still open,
3458  * sync the disk cache to physical media.
3459  */
3460 static void
3461 dashutdown(void * arg, int howto)
3462 {
3463         struct cam_periph *periph;
3464         struct da_softc *softc;
3465         union ccb *ccb;
3466         int error;
3467
3468         CAM_PERIPH_FOREACH(periph, &dadriver) {
3469                 cam_periph_lock(periph);
3470                 softc = (struct da_softc *)periph->softc;
3471
3472                 /*
3473                  * We only sync the cache if the drive is still open, and
3474                  * if the drive is capable of it..
3475                  */
3476                 if (((softc->flags & DA_FLAG_OPEN) == 0)
3477                  || (softc->quirks & DA_Q_NO_SYNC_CACHE)) {
3478                         cam_periph_unlock(periph);
3479                         continue;
3480                 }
3481
3482                 ccb = cam_periph_getccb(periph, CAM_PRIORITY_NORMAL);
3483                 scsi_synchronize_cache(&ccb->csio,
3484                                        /*retries*/0,
3485                                        /*cbfcnp*/dadone,
3486                                        MSG_SIMPLE_Q_TAG,
3487                                        /*begin_lba*/0, /* whole disk */
3488                                        /*lb_count*/0,
3489                                        SSD_FULL_SIZE,
3490                                        60 * 60 * 1000);
3491
3492                 error = cam_periph_runccb(ccb, daerror, /*cam_flags*/0,
3493                     /*sense_flags*/ SF_NO_RECOVERY | SF_NO_RETRY | SF_QUIET_IR,
3494                     softc->disk->d_devstat);
3495                 if (error != 0)
3496                         xpt_print(periph->path, "Synchronize cache failed\n");
3497                 xpt_release_ccb(ccb);
3498                 cam_periph_unlock(periph);
3499         }
3500 }
3501
3502 #else /* !_KERNEL */
3503
3504 /*
3505  * XXX This is only left out of the kernel build to silence warnings.  If,
3506  * for some reason this function is used in the kernel, the ifdefs should
3507  * be moved so it is included both in the kernel and userland.
3508  */
3509 void
3510 scsi_format_unit(struct ccb_scsiio *csio, u_int32_t retries,
3511                  void (*cbfcnp)(struct cam_periph *, union ccb *),
3512                  u_int8_t tag_action, u_int8_t byte2, u_int16_t ileave,
3513                  u_int8_t *data_ptr, u_int32_t dxfer_len, u_int8_t sense_len,
3514                  u_int32_t timeout)
3515 {
3516         struct scsi_format_unit *scsi_cmd;
3517
3518         scsi_cmd = (struct scsi_format_unit *)&csio->cdb_io.cdb_bytes;
3519         scsi_cmd->opcode = FORMAT_UNIT;
3520         scsi_cmd->byte2 = byte2;
3521         scsi_ulto2b(ileave, scsi_cmd->interleave);
3522
3523         cam_fill_csio(csio,
3524                       retries,
3525                       cbfcnp,
3526                       /*flags*/ (dxfer_len > 0) ? CAM_DIR_OUT : CAM_DIR_NONE,
3527                       tag_action,
3528                       data_ptr,
3529                       dxfer_len,
3530                       sense_len,
3531                       sizeof(*scsi_cmd),
3532                       timeout);
3533 }
3534
3535 #endif /* _KERNEL */