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