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