xref: /freebsd/sys/cam/scsi/scsi_sa.c (revision 22cf89c938886d14f5796fc49f9f020c23ea8eaf)
1 /*-
2  * Implementation of SCSI Sequential Access Peripheral driver for CAM.
3  *
4  * SPDX-License-Identifier: BSD-2-Clause
5  *
6  * Copyright (c) 1999, 2000 Matthew Jacob
7  * Copyright (c) 2013, 2014, 2015, 2021 Spectra Logic Corporation
8  * All rights reserved.
9  *
10  * Redistribution and use in source and binary forms, with or without
11  * modification, are permitted provided that the following conditions
12  * are met:
13  * 1. Redistributions of source code must retain the above copyright
14  *    notice, this list of conditions, and the following disclaimer,
15  *    without modification, immediately at the beginning of the file.
16  * 2. The name of the author may not be used to endorse or promote products
17  *    derived from this software without specific prior written permission.
18  *
19  * THIS SOFTWARE IS PROVIDED BY THE AUTHOR AND CONTRIBUTORS ``AS IS'' AND
20  * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
21  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
22  * ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE FOR
23  * ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
24  * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
25  * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
26  * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
27  * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
28  * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
29  * SUCH DAMAGE.
30  */
31 
32 #include <sys/cdefs.h>
33 #include <sys/param.h>
34 #include <sys/queue.h>
35 #ifdef _KERNEL
36 #include <sys/systm.h>
37 #include <sys/kernel.h>
38 #endif
39 #include <sys/types.h>
40 #include <sys/time.h>
41 #include <sys/bio.h>
42 #include <sys/limits.h>
43 #include <sys/malloc.h>
44 #include <sys/mtio.h>
45 #ifdef _KERNEL
46 #include <sys/conf.h>
47 #include <sys/sbuf.h>
48 #include <sys/sysctl.h>
49 #include <sys/taskqueue.h>
50 #endif
51 #include <sys/fcntl.h>
52 #include <sys/devicestat.h>
53 
54 #ifndef _KERNEL
55 #include <stdio.h>
56 #include <string.h>
57 #endif
58 
59 #include <cam/cam.h>
60 #include <cam/cam_ccb.h>
61 #include <cam/cam_periph.h>
62 #include <cam/cam_xpt_periph.h>
63 #include <cam/cam_debug.h>
64 
65 #include <cam/scsi/scsi_all.h>
66 #include <cam/scsi/scsi_message.h>
67 #include <cam/scsi/scsi_sa.h>
68 
69 #ifdef _KERNEL
70 
71 #include "opt_sa.h"
72 
73 #ifndef SA_IO_TIMEOUT
74 #define SA_IO_TIMEOUT		32
75 #endif
76 #ifndef SA_SPACE_TIMEOUT
77 #define SA_SPACE_TIMEOUT	1 * 60
78 #endif
79 #ifndef SA_REWIND_TIMEOUT
80 #define SA_REWIND_TIMEOUT	2 * 60
81 #endif
82 #ifndef SA_ERASE_TIMEOUT
83 #define SA_ERASE_TIMEOUT	4 * 60
84 #endif
85 #ifndef SA_REP_DENSITY_TIMEOUT
86 #define SA_REP_DENSITY_TIMEOUT	1
87 #endif
88 
89 #define	SCSIOP_TIMEOUT		(60 * 1000)	/* not an option */
90 
91 #define	IO_TIMEOUT		(SA_IO_TIMEOUT * 60 * 1000)
92 #define	REWIND_TIMEOUT		(SA_REWIND_TIMEOUT * 60 * 1000)
93 #define	ERASE_TIMEOUT		(SA_ERASE_TIMEOUT * 60 * 1000)
94 #define	SPACE_TIMEOUT		(SA_SPACE_TIMEOUT * 60 * 1000)
95 #define	REP_DENSITY_TIMEOUT	(SA_REP_DENSITY_TIMEOUT * 60 * 1000)
96 
97 /*
98  * Additional options that can be set for config: SA_1FM_AT_EOT
99  */
100 
101 #ifndef	UNUSED_PARAMETER
102 #define	UNUSED_PARAMETER(x)	x = x
103 #endif
104 
105 #define	QFRLS(ccb)	\
106 	if (((ccb)->ccb_h.status & CAM_DEV_QFRZN) != 0)	\
107 		cam_release_devq((ccb)->ccb_h.path, 0, 0, 0, FALSE)
108 
109 /*
110  * Driver states
111  */
112 
113 static MALLOC_DEFINE(M_SCSISA, "SCSI sa", "SCSI sequential access buffers");
114 
115 typedef enum {
116 	SA_STATE_NORMAL, SA_STATE_PROBE, SA_STATE_ABNORMAL
117 } sa_state;
118 
119 #define ccb_pflags	ppriv_field0
120 #define ccb_bp	 	ppriv_ptr1
121 
122 /* bits in ccb_pflags */
123 #define	SA_POSITION_UPDATED	0x1
124 
125 typedef enum {
126 	SA_FLAG_OPEN		= 0x00001,
127 	SA_FLAG_FIXED		= 0x00002,
128 	SA_FLAG_TAPE_LOCKED	= 0x00004,
129 	SA_FLAG_TAPE_MOUNTED	= 0x00008,
130 	SA_FLAG_TAPE_WP		= 0x00010,
131 	SA_FLAG_TAPE_WRITTEN	= 0x00020,
132 	SA_FLAG_EOM_PENDING	= 0x00040,
133 	SA_FLAG_EIO_PENDING	= 0x00080,
134 	SA_FLAG_EOF_PENDING	= 0x00100,
135 	SA_FLAG_ERR_PENDING	= (SA_FLAG_EOM_PENDING|SA_FLAG_EIO_PENDING|
136 				   SA_FLAG_EOF_PENDING),
137 	SA_FLAG_INVALID		= 0x00200,
138 	SA_FLAG_COMP_ENABLED	= 0x00400,
139 	SA_FLAG_COMP_SUPP	= 0x00800,
140 	SA_FLAG_COMP_UNSUPP	= 0x01000,
141 	SA_FLAG_TAPE_FROZEN	= 0x02000,
142 	SA_FLAG_PROTECT_SUPP	= 0x04000,
143 
144 	SA_FLAG_COMPRESSION	= (SA_FLAG_COMP_SUPP|SA_FLAG_COMP_ENABLED|
145 				   SA_FLAG_COMP_UNSUPP),
146 	SA_FLAG_SCTX_INIT	= 0x08000,
147 	SA_FLAG_RSOC_TO_TRY	= 0x10000,
148 } sa_flags;
149 
150 typedef enum {
151 	SA_MODE_REWIND		= 0x00,
152 	SA_MODE_NOREWIND	= 0x01,
153 	SA_MODE_OFFLINE		= 0x02
154 } sa_mode;
155 
156 typedef enum {
157 	SA_TIMEOUT_ERASE,
158 	SA_TIMEOUT_LOAD,
159 	SA_TIMEOUT_LOCATE,
160 	SA_TIMEOUT_MODE_SELECT,
161 	SA_TIMEOUT_MODE_SENSE,
162 	SA_TIMEOUT_PREVENT,
163 	SA_TIMEOUT_READ,
164 	SA_TIMEOUT_READ_BLOCK_LIMITS,
165 	SA_TIMEOUT_READ_POSITION,
166 	SA_TIMEOUT_REP_DENSITY,
167 	SA_TIMEOUT_RESERVE,
168 	SA_TIMEOUT_REWIND,
169 	SA_TIMEOUT_SPACE,
170 	SA_TIMEOUT_TUR,
171 	SA_TIMEOUT_WRITE,
172 	SA_TIMEOUT_WRITE_FILEMARKS,
173 	SA_TIMEOUT_TYPE_MAX
174 } sa_timeout_types;
175 
176 /*
177  * These are the default timeout values that apply to all tape drives.
178  *
179  * We get timeouts from the following places in order of increasing
180  * priority:
181  * 1. Driver default timeouts. (Set in the structure below.)
182  * 2. Timeouts loaded from the drive via REPORT SUPPORTED OPERATION
183  *    CODES.  (If the drive supports it, SPC-4/LTO-5 and newer should.)
184  * 3. Global loader tunables, used for all sa(4) driver instances on
185  *    a machine.
186  * 4. Instance-specific loader tunables, used for say sa5.
187  * 5. On the fly user sysctl changes.
188  *
189  * Each step will overwrite the timeout value set from the one
190  * before, so you go from general to most specific.
191  */
192 static struct sa_timeout_desc {
193 	const char *desc;
194 	int value;
195 } sa_default_timeouts[SA_TIMEOUT_TYPE_MAX] = {
196 	{"erase", 		ERASE_TIMEOUT},
197 	{"load",		REWIND_TIMEOUT},
198 	{"locate",		SPACE_TIMEOUT},
199 	{"mode_select", 	SCSIOP_TIMEOUT},
200 	{"mode_sense",		SCSIOP_TIMEOUT},
201 	{"prevent",		SCSIOP_TIMEOUT},
202 	{"read",		IO_TIMEOUT},
203 	{"read_block_limits",	SCSIOP_TIMEOUT},
204 	{"read_position",	SCSIOP_TIMEOUT},
205 	{"report_density",	REP_DENSITY_TIMEOUT},
206 	{"reserve",		SCSIOP_TIMEOUT},
207 	{"rewind",		REWIND_TIMEOUT},
208 	{"space",		SPACE_TIMEOUT},
209 	{"tur",			SCSIOP_TIMEOUT},
210 	{"write", 		IO_TIMEOUT},
211 	{"write_filemarks",	IO_TIMEOUT},
212 };
213 
214 typedef enum {
215 	SA_PARAM_NONE		= 0x000,
216 	SA_PARAM_BLOCKSIZE	= 0x001,
217 	SA_PARAM_DENSITY	= 0x002,
218 	SA_PARAM_COMPRESSION	= 0x004,
219 	SA_PARAM_BUFF_MODE	= 0x008,
220 	SA_PARAM_NUMBLOCKS	= 0x010,
221 	SA_PARAM_WP		= 0x020,
222 	SA_PARAM_SPEED		= 0x040,
223 	SA_PARAM_DENSITY_EXT	= 0x080,
224 	SA_PARAM_LBP		= 0x100,
225 	SA_PARAM_ALL		= 0x1ff
226 } sa_params;
227 
228 typedef enum {
229 	SA_QUIRK_NONE		= 0x000,
230 	SA_QUIRK_NOCOMP		= 0x001, /* Can't deal with compression at all*/
231 	SA_QUIRK_FIXED		= 0x002, /* Force fixed mode */
232 	SA_QUIRK_VARIABLE	= 0x004, /* Force variable mode */
233 	SA_QUIRK_2FM		= 0x008, /* Needs Two File Marks at EOD */
234 	SA_QUIRK_1FM		= 0x010, /* No more than 1 File Mark at EOD */
235 	SA_QUIRK_NODREAD	= 0x020, /* Don't try and dummy read density */
236 	SA_QUIRK_NO_MODESEL	= 0x040, /* Don't do mode select at all */
237 	SA_QUIRK_NO_CPAGE	= 0x080, /* Don't use DEVICE COMPRESSION page */
238 	SA_QUIRK_NO_LONG_POS	= 0x100  /* No long position information */
239 } sa_quirks;
240 
241 #define SA_QUIRK_BIT_STRING	\
242 	"\020"			\
243 	"\001NOCOMP"		\
244 	"\002FIXED"		\
245 	"\003VARIABLE"		\
246 	"\0042FM"		\
247 	"\0051FM"		\
248 	"\006NODREAD"		\
249 	"\007NO_MODESEL"	\
250 	"\010NO_CPAGE"		\
251 	"\011NO_LONG_POS"
252 
253 #define	SAMODE(z)	(dev2unit(z) & 0x3)
254 #define	SA_IS_CTRL(z)	(dev2unit(z) & (1 << 4))
255 
256 #define SA_NOT_CTLDEV	0
257 #define SA_CTLDEV	1
258 
259 #define SA_ATYPE_R	0
260 #define SA_ATYPE_NR	1
261 #define SA_ATYPE_ER	2
262 #define SA_NUM_ATYPES	3
263 
264 #define	SAMINOR(ctl, access) \
265 	((ctl << 4) | (access & 0x3))
266 
267 struct sa_devs {
268 	struct cdev *ctl_dev;
269 	struct cdev *r_dev;
270 	struct cdev *nr_dev;
271 	struct cdev *er_dev;
272 };
273 
274 #define	SASBADDBASE(sb, indent, data, xfmt, name, type, xsize, desc)	\
275 	sbuf_printf(sb, "%*s<%s type=\"%s\" size=\"%zd\" "		\
276 	    "fmt=\"%s\" desc=\"%s\">" #xfmt "</%s>\n", indent, "", 	\
277 	    #name, #type, xsize, #xfmt, desc ? desc : "", data, #name);
278 
279 #define	SASBADDINT(sb, indent, data, fmt, name)				\
280 	SASBADDBASE(sb, indent, data, fmt, name, int, sizeof(data),	\
281 		    NULL)
282 
283 #define	SASBADDINTDESC(sb, indent, data, fmt, name, desc)		\
284 	SASBADDBASE(sb, indent, data, fmt, name, int, sizeof(data),	\
285 		    desc)
286 
287 #define	SASBADDUINT(sb, indent, data, fmt, name)			\
288 	SASBADDBASE(sb, indent, data, fmt, name, uint, sizeof(data), 	\
289 		    NULL)
290 
291 #define	SASBADDUINTDESC(sb, indent, data, fmt, name, desc)		\
292 	SASBADDBASE(sb, indent, data, fmt, name, uint, sizeof(data), 	\
293 		    desc)
294 
295 #define	SASBADDFIXEDSTR(sb, indent, data, fmt, name)			\
296 	SASBADDBASE(sb, indent, data, fmt, name, str, sizeof(data),	\
297 		    NULL)
298 
299 #define	SASBADDFIXEDSTRDESC(sb, indent, data, fmt, name, desc)		\
300 	SASBADDBASE(sb, indent, data, fmt, name, str, sizeof(data),	\
301 		    desc)
302 
303 #define	SASBADDVARSTR(sb, indent, data, fmt, name, maxlen)		\
304 	SASBADDBASE(sb, indent, data, fmt, name, str, maxlen, NULL)
305 
306 #define	SASBADDVARSTRDESC(sb, indent, data, fmt, name, maxlen, desc)	\
307 	SASBADDBASE(sb, indent, data, fmt, name, str, maxlen, desc)
308 
309 #define	SASBADDNODE(sb, indent, name) {					\
310 	sbuf_printf(sb, "%*s<%s type=\"%s\">\n", indent, "", #name,	\
311 	    "node");							\
312 	indent += 2;							\
313 }
314 
315 #define	SASBADDNODENUM(sb, indent, name, num) {				\
316 	sbuf_printf(sb, "%*s<%s type=\"%s\" num=\"%d\">\n", indent, "",	\
317 	    #name, "node", num);					\
318 	indent += 2;							\
319 }
320 
321 #define	SASBENDNODE(sb, indent, name) {					\
322 	indent -= 2;							\
323 	sbuf_printf(sb, "%*s</%s>\n", indent, "", #name);		\
324 }
325 
326 #define	SA_DENSITY_TYPES	4
327 
328 struct sa_prot_state {
329 	int initialized;
330 	uint32_t prot_method;
331 	uint32_t pi_length;
332 	uint32_t lbp_w;
333 	uint32_t lbp_r;
334 	uint32_t rbdp;
335 };
336 
337 struct sa_prot_info {
338 	struct sa_prot_state cur_prot_state;
339 	struct sa_prot_state pending_prot_state;
340 };
341 
342 /*
343  * A table mapping protection parameters to their types and values.
344  */
345 struct sa_prot_map {
346 	char *name;
347 	mt_param_set_type param_type;
348 	off_t offset;
349 	uint32_t min_val;
350 	uint32_t max_val;
351 	uint32_t *value;
352 } sa_prot_table[] = {
353 	{ "prot_method", MT_PARAM_SET_UNSIGNED,
354 	  __offsetof(struct sa_prot_state, prot_method),
355 	  /*min_val*/ 0, /*max_val*/ 255, NULL },
356 	{ "pi_length", MT_PARAM_SET_UNSIGNED,
357 	  __offsetof(struct sa_prot_state, pi_length),
358 	  /*min_val*/ 0, /*max_val*/ SA_CTRL_DP_PI_LENGTH_MASK, NULL },
359 	{ "lbp_w", MT_PARAM_SET_UNSIGNED,
360 	  __offsetof(struct sa_prot_state, lbp_w),
361 	  /*min_val*/ 0, /*max_val*/ 1, NULL },
362 	{ "lbp_r", MT_PARAM_SET_UNSIGNED,
363 	  __offsetof(struct sa_prot_state, lbp_r),
364 	  /*min_val*/ 0, /*max_val*/ 1, NULL },
365 	{ "rbdp", MT_PARAM_SET_UNSIGNED,
366 	  __offsetof(struct sa_prot_state, rbdp),
367 	  /*min_val*/ 0, /*max_val*/ 1, NULL }
368 };
369 
370 #define	SA_NUM_PROT_ENTS nitems(sa_prot_table)
371 
372 #define	SA_PROT_ENABLED(softc) ((softc->flags & SA_FLAG_PROTECT_SUPP)	\
373 	&& (softc->prot_info.cur_prot_state.initialized != 0)		\
374 	&& (softc->prot_info.cur_prot_state.prot_method != 0))
375 
376 #define	SA_PROT_LEN(softc)	softc->prot_info.cur_prot_state.pi_length
377 
378 struct sa_softc {
379 	sa_state	state;
380 	sa_flags	flags;
381 	sa_quirks	quirks;
382 	u_int		si_flags;
383 	struct cam_periph *periph;
384 	struct		bio_queue_head bio_queue;
385 	int		queue_count;
386 	struct		devstat *device_stats;
387 	struct sa_devs	devs;
388 	int		open_count;
389 	int		num_devs_to_destroy;
390 	int		blk_gran;
391 	int		blk_mask;
392 	int		blk_shift;
393 	uint32_t	max_blk;
394 	uint32_t	min_blk;
395 	uint32_t	maxio;
396 	uint32_t	cpi_maxio;
397 	int		allow_io_split;
398 	int		inject_eom;
399 	int		set_pews_status;
400 	uint32_t	comp_algorithm;
401 	uint32_t	saved_comp_algorithm;
402 	uint32_t	media_blksize;
403 	uint32_t	last_media_blksize;
404 	uint32_t	media_numblks;
405 	uint8_t	media_density;
406 	uint8_t	speed;
407 	uint8_t	scsi_rev;
408 	uint8_t	dsreg;		/* mtio mt_dsreg, redux */
409 	int		buffer_mode;
410 	int		filemarks;
411 	int		last_resid_was_io;
412 	uint8_t		density_type_bits[SA_DENSITY_TYPES];
413 	int		density_info_valid[SA_DENSITY_TYPES];
414 	uint8_t		density_info[SA_DENSITY_TYPES][SRDS_MAX_LENGTH];
415 	int		timeout_info[SA_TIMEOUT_TYPE_MAX];
416 
417 	struct sa_prot_info	prot_info;
418 
419 	int		sili;
420 	int		eot_warn;
421 
422 	/*
423 	 * Current position information.  -1 means that the given value is
424 	 * unknown.  fileno and blkno are always calculated.  blkno is
425 	 * relative to the previous file mark.  rep_fileno and rep_blkno
426 	 * are as reported by the drive, if it supports the long form
427 	 * report for the READ POSITION command.  rep_blkno is relative to
428 	 * the beginning of the partition.
429 	 *
430 	 * bop means that the drive is at the beginning of the partition.
431 	 * eop means that the drive is between early warning and end of
432 	 * partition, inside the current partition.
433 	 * bpew means that the position is in a PEWZ (Programmable Early
434 	 * Warning Zone)
435 	 */
436 	daddr_t		partition;	/* Absolute from BOT */
437 	daddr_t		fileno;		/* Relative to beginning of partition */
438 	daddr_t		blkno;		/* Relative to last file mark */
439 	daddr_t		rep_blkno;	/* Relative to beginning of partition */
440 	daddr_t		rep_fileno;	/* Relative to beginning of partition */
441 	int		bop;		/* Beginning of Partition */
442 	int		eop;		/* End of Partition */
443 	int		bpew;		/* Beyond Programmable Early Warning */
444 
445 	/*
446 	 * Latched Error Info
447 	 */
448 	struct {
449 		struct scsi_sense_data _last_io_sense;
450 		uint64_t _last_io_resid;
451 		uint8_t _last_io_cdb[CAM_MAX_CDBLEN];
452 		struct scsi_sense_data _last_ctl_sense;
453 		uint64_t _last_ctl_resid;
454 		uint8_t _last_ctl_cdb[CAM_MAX_CDBLEN];
455 #define	last_io_sense	errinfo._last_io_sense
456 #define	last_io_resid	errinfo._last_io_resid
457 #define	last_io_cdb	errinfo._last_io_cdb
458 #define	last_ctl_sense	errinfo._last_ctl_sense
459 #define	last_ctl_resid	errinfo._last_ctl_resid
460 #define	last_ctl_cdb	errinfo._last_ctl_cdb
461 	} errinfo;
462 	/*
463 	 * Misc other flags/state
464 	 */
465 	uint32_t
466 					: 29,
467 		open_rdonly		: 1,	/* open read-only */
468 		open_pending_mount	: 1,	/* open pending mount */
469 		ctrl_mode		: 1;	/* control device open */
470 
471 	struct task		sysctl_task;
472 	struct sysctl_ctx_list	sysctl_ctx;
473 	struct sysctl_oid	*sysctl_tree;
474 	struct sysctl_ctx_list	sysctl_timeout_ctx;
475 	struct sysctl_oid	*sysctl_timeout_tree;
476 };
477 
478 struct sa_quirk_entry {
479 	struct scsi_inquiry_pattern inq_pat;	/* matching pattern */
480 	sa_quirks quirks;	/* specific quirk type */
481 	uint32_t prefblk;	/* preferred blocksize when in fixed mode */
482 };
483 
484 static struct sa_quirk_entry sa_quirk_table[] =
485 {
486 	{
487 		{ T_SEQUENTIAL, SIP_MEDIA_REMOVABLE, "OnStream",
488 		  "ADR*", "*"}, SA_QUIRK_FIXED|SA_QUIRK_NODREAD |
489 		   SA_QUIRK_1FM|SA_QUIRK_NO_MODESEL, 32768
490 	},
491 	{
492 		{ T_SEQUENTIAL, SIP_MEDIA_REMOVABLE, "ARCHIVE",
493 		  "Python 06408*", "*"}, SA_QUIRK_NODREAD, 0
494 	},
495 	{
496 		{ T_SEQUENTIAL, SIP_MEDIA_REMOVABLE, "ARCHIVE",
497 		  "Python 25601*", "*"}, SA_QUIRK_NOCOMP|SA_QUIRK_NODREAD, 0
498 	},
499 	{
500 		{ T_SEQUENTIAL, SIP_MEDIA_REMOVABLE, "ARCHIVE",
501 		  "Python*", "*"}, SA_QUIRK_NODREAD, 0
502 	},
503 	{
504 		{ T_SEQUENTIAL, SIP_MEDIA_REMOVABLE, "ARCHIVE",
505 		  "VIPER 150*", "*"}, SA_QUIRK_FIXED|SA_QUIRK_1FM, 512
506 	},
507 	{
508 		{ T_SEQUENTIAL, SIP_MEDIA_REMOVABLE, "ARCHIVE",
509 		  "VIPER 2525 25462", "-011"},
510 		  SA_QUIRK_NOCOMP|SA_QUIRK_1FM|SA_QUIRK_NODREAD, 0
511 	},
512 	{
513 		{ T_SEQUENTIAL, SIP_MEDIA_REMOVABLE, "ARCHIVE",
514 		  "VIPER 2525*", "*"}, SA_QUIRK_FIXED|SA_QUIRK_1FM, 1024
515 	},
516 #if	0
517 	{
518 		{ T_SEQUENTIAL, SIP_MEDIA_REMOVABLE, "HP",
519 		  "C15*", "*"}, SA_QUIRK_VARIABLE|SA_QUIRK_NO_CPAGE, 0,
520 	},
521 #endif
522  	{
523  		{ T_SEQUENTIAL, SIP_MEDIA_REMOVABLE, "HP",
524 		  "C56*", "*"}, SA_QUIRK_VARIABLE|SA_QUIRK_2FM, 0
525 	},
526 	{
527 		{ T_SEQUENTIAL, SIP_MEDIA_REMOVABLE, "HP",
528 		  "T20*", "*"}, SA_QUIRK_FIXED|SA_QUIRK_1FM, 512
529 	},
530 	{
531 		{ T_SEQUENTIAL, SIP_MEDIA_REMOVABLE, "HP",
532 		  "T4000*", "*"}, SA_QUIRK_FIXED|SA_QUIRK_1FM, 512
533 	},
534 	{
535 		{ T_SEQUENTIAL, SIP_MEDIA_REMOVABLE, "HP",
536 		  "HP-88780*", "*"}, SA_QUIRK_VARIABLE|SA_QUIRK_2FM, 0
537 	},
538 	{
539 		{ T_SEQUENTIAL, SIP_MEDIA_REMOVABLE, "KENNEDY",
540 		  "*", "*"}, SA_QUIRK_VARIABLE|SA_QUIRK_2FM, 0
541 	},
542 	{
543 		{ T_SEQUENTIAL, SIP_MEDIA_REMOVABLE, "M4 DATA",
544 		  "123107 SCSI*", "*"}, SA_QUIRK_VARIABLE|SA_QUIRK_2FM, 0
545 	},
546 	{	/* jreynold@primenet.com */
547 		{ T_SEQUENTIAL, SIP_MEDIA_REMOVABLE, "Seagate",
548 		"STT8000N*", "*"}, SA_QUIRK_1FM, 0
549 	},
550 	{	/* mike@sentex.net */
551 		{ T_SEQUENTIAL, SIP_MEDIA_REMOVABLE, "Seagate",
552 		"STT20000*", "*"}, SA_QUIRK_1FM, 0
553 	},
554 	{
555 		{ T_SEQUENTIAL, SIP_MEDIA_REMOVABLE, "SEAGATE",
556 		"DAT    06241-XXX", "*"}, SA_QUIRK_VARIABLE|SA_QUIRK_2FM, 0
557 	},
558 	{
559 		{ T_SEQUENTIAL, SIP_MEDIA_REMOVABLE, "TANDBERG",
560 		  " TDC 3600", "U07:"}, SA_QUIRK_NOCOMP|SA_QUIRK_1FM, 512
561 	},
562 	{
563 		{ T_SEQUENTIAL, SIP_MEDIA_REMOVABLE, "TANDBERG",
564 		  " TDC 3800", "*"}, SA_QUIRK_NOCOMP|SA_QUIRK_1FM, 512
565 	},
566 	{
567 		{ T_SEQUENTIAL, SIP_MEDIA_REMOVABLE, "TANDBERG",
568 		  " TDC 4100", "*"}, SA_QUIRK_NOCOMP|SA_QUIRK_1FM, 512
569 	},
570 	{
571 		{ T_SEQUENTIAL, SIP_MEDIA_REMOVABLE, "TANDBERG",
572 		  " TDC 4200", "*"}, SA_QUIRK_NOCOMP|SA_QUIRK_1FM, 512
573 	},
574 	{
575 		{ T_SEQUENTIAL, SIP_MEDIA_REMOVABLE, "TANDBERG",
576 		  " SLR*", "*"}, SA_QUIRK_1FM, 0
577 	},
578 	{
579 		{ T_SEQUENTIAL, SIP_MEDIA_REMOVABLE, "WANGTEK",
580 		  "5525ES*", "*"}, SA_QUIRK_FIXED|SA_QUIRK_1FM, 512
581 	},
582 	{
583 		{ T_SEQUENTIAL, SIP_MEDIA_REMOVABLE, "WANGTEK",
584 		  "51000*", "*"}, SA_QUIRK_FIXED|SA_QUIRK_1FM, 1024
585 	}
586 };
587 
588 static	d_open_t	saopen;
589 static	d_close_t	saclose;
590 static	d_strategy_t	sastrategy;
591 static	d_ioctl_t	saioctl;
592 static	periph_init_t	sainit;
593 static	periph_ctor_t	saregister;
594 static	periph_oninv_t	saoninvalidate;
595 static	periph_dtor_t	sacleanup;
596 static	periph_start_t	sastart;
597 static	void		saasync(void *callback_arg, uint32_t code,
598 				struct cam_path *path, void *arg);
599 static	void		sadone(struct cam_periph *periph,
600 			       union ccb *start_ccb);
601 static  int		saerror(union ccb *ccb, uint32_t cam_flags,
602 				uint32_t sense_flags);
603 static int		samarkswanted(struct cam_periph *);
604 static int		sacheckeod(struct cam_periph *periph);
605 static int		sagetparams(struct cam_periph *periph,
606 				    sa_params params_to_get,
607 				    uint32_t *blocksize, uint8_t *density,
608 				    uint32_t *numblocks, int *buff_mode,
609 				    uint8_t *write_protect, uint8_t *speed,
610 				    int *comp_supported, int *comp_enabled,
611 				    uint32_t *comp_algorithm,
612 				    sa_comp_t *comp_page,
613 				    struct scsi_control_data_prot_subpage
614 				    *prot_page, int dp_size,
615 				    int prot_changeable);
616 static int		sasetprot(struct cam_periph *periph,
617 				  struct sa_prot_state *new_prot);
618 static int		sasetparams(struct cam_periph *periph,
619 				    sa_params params_to_set,
620 				    uint32_t blocksize, uint8_t density,
621 				    uint32_t comp_algorithm,
622 				    uint32_t sense_flags);
623 static int		sasetsili(struct cam_periph *periph,
624 				  struct mtparamset *ps, int num_params);
625 static int		saseteotwarn(struct cam_periph *periph,
626 				     struct mtparamset *ps, int num_params);
627 static void		safillprot(struct sa_softc *softc, int *indent,
628 				   struct sbuf *sb);
629 static void		sapopulateprots(struct sa_prot_state *cur_state,
630 					struct sa_prot_map *new_table,
631 					int table_ents);
632 static struct sa_prot_map *safindprotent(char *name, struct sa_prot_map *table,
633 					 int table_ents);
634 static int		sasetprotents(struct cam_periph *periph,
635 				      struct mtparamset *ps, int num_params);
636 static struct sa_param_ent *safindparament(struct mtparamset *ps);
637 static int		saparamsetlist(struct cam_periph *periph,
638 				       struct mtsetlist *list, int need_copy);
639 static	int		saextget(struct cdev *dev, struct cam_periph *periph,
640 				 struct sbuf *sb, struct mtextget *g);
641 static	int		saparamget(struct sa_softc *softc, struct sbuf *sb);
642 static void		saprevent(struct cam_periph *periph, int action);
643 static int		sarewind(struct cam_periph *periph);
644 static int		saspace(struct cam_periph *periph, int count,
645 				scsi_space_code code);
646 static void		sadevgonecb(void *arg);
647 static void		sasetupdev(struct sa_softc *softc, struct cdev *dev);
648 static void		saloadtotunables(struct sa_softc *softc);
649 static void		sasysctlinit(void *context, int pending);
650 static int		samount(struct cam_periph *, int, struct cdev *);
651 static int		saretension(struct cam_periph *periph);
652 static int		sareservereleaseunit(struct cam_periph *periph,
653 					     int reserve);
654 static int		saloadunload(struct cam_periph *periph, int load);
655 static int		saerase(struct cam_periph *periph, int longerase);
656 static int		sawritefilemarks(struct cam_periph *periph,
657 					 int nmarks, int setmarks, int immed);
658 static int		sagetpos(struct cam_periph *periph);
659 static int		sardpos(struct cam_periph *periph, int, uint32_t *);
660 static int		sasetpos(struct cam_periph *periph, int,
661 				 struct mtlocate *);
662 static void		safilldenstypesb(struct sbuf *sb, int *indent,
663 					 uint8_t *buf, int buf_len,
664 					 int is_density);
665 static void		safilldensitysb(struct sa_softc *softc, int *indent,
666 					struct sbuf *sb);
667 static void		saloadtimeouts(struct sa_softc *softc, union ccb *ccb);
668 
669 #ifndef	SA_DEFAULT_IO_SPLIT
670 #define	SA_DEFAULT_IO_SPLIT	0
671 #endif
672 
673 static int sa_allow_io_split = SA_DEFAULT_IO_SPLIT;
674 
675 /*
676  * Tunable to allow the user to set a global allow_io_split value.  Note
677  * that this WILL GO AWAY in FreeBSD 11.0.  Silently splitting the I/O up
678  * is bad behavior, because it hides the true tape block size from the
679  * application.
680  */
681 static SYSCTL_NODE(_kern_cam, OID_AUTO, sa, CTLFLAG_RD | CTLFLAG_MPSAFE, 0,
682     "CAM Sequential Access Tape Driver");
683 SYSCTL_INT(_kern_cam_sa, OID_AUTO, allow_io_split, CTLFLAG_RDTUN,
684     &sa_allow_io_split, 0, "Default I/O split value");
685 
686 static struct periph_driver sadriver =
687 {
688 	sainit, "sa",
689 	TAILQ_HEAD_INITIALIZER(sadriver.units), /* generation */ 0
690 };
691 
692 PERIPHDRIVER_DECLARE(sa, sadriver);
693 
694 /* For 2.2-stable support */
695 #ifndef D_TAPE
696 #define D_TAPE 0
697 #endif
698 
699 static struct cdevsw sa_cdevsw = {
700 	.d_version =	D_VERSION,
701 	.d_open =	saopen,
702 	.d_close =	saclose,
703 	.d_read =	physread,
704 	.d_write =	physwrite,
705 	.d_ioctl =	saioctl,
706 	.d_strategy =	sastrategy,
707 	.d_name =	"sa",
708 	.d_flags =	D_TAPE | D_TRACKCLOSE,
709 };
710 
711 static int
712 saopen(struct cdev *dev, int flags, int fmt, struct thread *td)
713 {
714 	struct cam_periph *periph;
715 	struct sa_softc *softc;
716 	int error;
717 
718 	periph = (struct cam_periph *)dev->si_drv1;
719 	if (cam_periph_acquire(periph) != 0) {
720 		return (ENXIO);
721 	}
722 
723 	cam_periph_lock(periph);
724 
725 	softc = (struct sa_softc *)periph->softc;
726 
727 	CAM_DEBUG(periph->path, CAM_DEBUG_TRACE|CAM_DEBUG_INFO,
728 	    ("saopen(%s): softc=0x%x\n", devtoname(dev), softc->flags));
729 
730 	if (SA_IS_CTRL(dev)) {
731 		softc->ctrl_mode = 1;
732 		softc->open_count++;
733 		cam_periph_unlock(periph);
734 		return (0);
735 	}
736 
737 	if ((error = cam_periph_hold(periph, PRIBIO|PCATCH)) != 0) {
738 		cam_periph_unlock(periph);
739 		cam_periph_release(periph);
740 		return (error);
741 	}
742 
743 	if (softc->flags & SA_FLAG_OPEN) {
744 		error = EBUSY;
745 	} else if (softc->flags & SA_FLAG_INVALID) {
746 		error = ENXIO;
747 	} else {
748 		/*
749 		 * Preserve whether this is a read_only open.
750 		 */
751 		softc->open_rdonly = (flags & O_RDWR) == O_RDONLY;
752 
753 		/*
754 		 * The function samount ensures media is loaded and ready.
755 		 * It also does a device RESERVE if the tape isn't yet mounted.
756 		 *
757 		 * If the mount fails and this was a non-blocking open,
758 		 * make this a 'open_pending_mount' action.
759 		 */
760 		error = samount(periph, flags, dev);
761 		if (error && (flags & O_NONBLOCK)) {
762 			softc->flags |= SA_FLAG_OPEN;
763 			softc->open_pending_mount = 1;
764 			softc->open_count++;
765 			cam_periph_unhold(periph);
766 			cam_periph_unlock(periph);
767 			return (0);
768 		}
769 	}
770 
771 	if (error) {
772 		cam_periph_unhold(periph);
773 		cam_periph_unlock(periph);
774 		cam_periph_release(periph);
775 		return (error);
776 	}
777 
778 	saprevent(periph, PR_PREVENT);
779 	softc->flags |= SA_FLAG_OPEN;
780 	softc->open_count++;
781 
782 	cam_periph_unhold(periph);
783 	cam_periph_unlock(periph);
784 	return (error);
785 }
786 
787 static int
788 saclose(struct cdev *dev, int flag, int fmt, struct thread *td)
789 {
790 	struct	cam_periph *periph;
791 	struct	sa_softc *softc;
792 	int	mode, error, writing, tmp, i;
793 	int	closedbits = SA_FLAG_OPEN;
794 
795 	mode = SAMODE(dev);
796 	periph = (struct cam_periph *)dev->si_drv1;
797 	cam_periph_lock(periph);
798 
799 	softc = (struct sa_softc *)periph->softc;
800 
801 	CAM_DEBUG(periph->path, CAM_DEBUG_TRACE|CAM_DEBUG_INFO,
802 	    ("saclose(%s): softc=0x%x\n", devtoname(dev), softc->flags));
803 
804 	softc->open_rdonly = 0;
805 	if (SA_IS_CTRL(dev)) {
806 		softc->ctrl_mode = 0;
807 		softc->open_count--;
808 		cam_periph_unlock(periph);
809 		cam_periph_release(periph);
810 		return (0);
811 	}
812 
813 	if (softc->open_pending_mount) {
814 		softc->flags &= ~SA_FLAG_OPEN;
815 		softc->open_pending_mount = 0;
816 		softc->open_count--;
817 		cam_periph_unlock(periph);
818 		cam_periph_release(periph);
819 		return (0);
820 	}
821 
822 	if ((error = cam_periph_hold(periph, PRIBIO)) != 0) {
823 		cam_periph_unlock(periph);
824 		return (error);
825 	}
826 
827 	/*
828 	 * Were we writing the tape?
829 	 */
830 	writing = (softc->flags & SA_FLAG_TAPE_WRITTEN) != 0;
831 
832 	/*
833 	 * See whether or not we need to write filemarks. If this
834 	 * fails, we probably have to assume we've lost tape
835 	 * position.
836 	 */
837 	error = sacheckeod(periph);
838 	if (error) {
839 		xpt_print(periph->path,
840 		    "failed to write terminating filemark(s)\n");
841 		softc->flags |= SA_FLAG_TAPE_FROZEN;
842 	}
843 
844 	/*
845 	 * Whatever we end up doing, allow users to eject tapes from here on.
846 	 */
847 	saprevent(periph, PR_ALLOW);
848 
849 	/*
850 	 * Decide how to end...
851 	 */
852 	if ((softc->flags & SA_FLAG_TAPE_MOUNTED) == 0) {
853 		closedbits |= SA_FLAG_TAPE_FROZEN;
854 	} else switch (mode) {
855 	case SA_MODE_OFFLINE:
856 		/*
857 		 * An 'offline' close is an unconditional release of
858 		 * frozen && mount conditions, irrespective of whether
859 		 * these operations succeeded. The reason for this is
860 		 * to allow at least some kind of programmatic way
861 		 * around our state getting all fouled up. If somebody
862 		 * issues an 'offline' command, that will be allowed
863 		 * to clear state.
864 		 */
865 		(void) sarewind(periph);
866 		(void) saloadunload(periph, FALSE);
867 		closedbits |= SA_FLAG_TAPE_MOUNTED|SA_FLAG_TAPE_FROZEN;
868 		break;
869 	case SA_MODE_REWIND:
870 		/*
871 		 * If the rewind fails, return an error- if anyone cares,
872 		 * but not overwriting any previous error.
873 		 *
874 		 * We don't clear the notion of mounted here, but we do
875 		 * clear the notion of frozen if we successfully rewound.
876 		 */
877 		tmp = sarewind(periph);
878 		if (tmp) {
879 			if (error != 0)
880 				error = tmp;
881 		} else {
882 			closedbits |= SA_FLAG_TAPE_FROZEN;
883 		}
884 		break;
885 	case SA_MODE_NOREWIND:
886 		/*
887 		 * If we're not rewinding/unloading the tape, find out
888 		 * whether we need to back up over one of two filemarks
889 		 * we wrote (if we wrote two filemarks) so that appends
890 		 * from this point on will be sane.
891 		 */
892 		if (error == 0 && writing && (softc->quirks & SA_QUIRK_2FM)) {
893 			tmp = saspace(periph, -1, SS_FILEMARKS);
894 			if (tmp) {
895 				xpt_print(periph->path, "unable to backspace "
896 				    "over one of double filemarks at end of "
897 				    "tape\n");
898 				xpt_print(periph->path, "it is possible that "
899 				    "this device needs a SA_QUIRK_1FM quirk set"
900 				    "for it\n");
901 				softc->flags |= SA_FLAG_TAPE_FROZEN;
902 			}
903 		}
904 		break;
905 	default:
906 		xpt_print(periph->path, "unknown mode 0x%x in saclose\n", mode);
907 		/* NOTREACHED */
908 		break;
909 	}
910 
911 	/*
912 	 * We wish to note here that there are no more filemarks to be written.
913 	 */
914 	softc->filemarks = 0;
915 	softc->flags &= ~SA_FLAG_TAPE_WRITTEN;
916 
917 	/*
918 	 * And we are no longer open for business.
919 	 */
920 	softc->flags &= ~closedbits;
921 	softc->open_count--;
922 
923 	/*
924 	 * Invalidate any density information that depends on having tape
925 	 * media in the drive.
926 	 */
927 	for (i = 0; i < SA_DENSITY_TYPES; i++) {
928 		if (softc->density_type_bits[i] & SRDS_MEDIA)
929 			softc->density_info_valid[i] = 0;
930 	}
931 
932 	/*
933 	 * Inform users if tape state if frozen....
934 	 */
935 	if (softc->flags & SA_FLAG_TAPE_FROZEN) {
936 		xpt_print(periph->path, "tape is now frozen- use an OFFLINE, "
937 		    "REWIND or MTEOM command to clear this state.\n");
938 	}
939 
940 	/* release the device if it is no longer mounted */
941 	if ((softc->flags & SA_FLAG_TAPE_MOUNTED) == 0)
942 		sareservereleaseunit(periph, FALSE);
943 
944 	cam_periph_unhold(periph);
945 	cam_periph_unlock(periph);
946 	cam_periph_release(periph);
947 
948 	return (error);
949 }
950 
951 /*
952  * Actually translate the requested transfer into one the physical driver
953  * can understand.  The transfer is described by a buf and will include
954  * only one physical transfer.
955  */
956 static void
957 sastrategy(struct bio *bp)
958 {
959 	struct cam_periph *periph;
960 	struct sa_softc *softc;
961 
962 	bp->bio_resid = bp->bio_bcount;
963 	if (SA_IS_CTRL(bp->bio_dev)) {
964 		biofinish(bp, NULL, EINVAL);
965 		return;
966 	}
967 	periph = (struct cam_periph *)bp->bio_dev->si_drv1;
968 	cam_periph_lock(periph);
969 
970 	softc = (struct sa_softc *)periph->softc;
971 
972 	if (softc->flags & SA_FLAG_INVALID) {
973 		cam_periph_unlock(periph);
974 		biofinish(bp, NULL, ENXIO);
975 		return;
976 	}
977 
978 	if (softc->flags & SA_FLAG_TAPE_FROZEN) {
979 		cam_periph_unlock(periph);
980 		biofinish(bp, NULL, EPERM);
981 		return;
982 	}
983 
984 	/*
985 	 * This should actually never occur as the write(2)
986 	 * system call traps attempts to write to a read-only
987 	 * file descriptor.
988 	 */
989 	if (bp->bio_cmd == BIO_WRITE && softc->open_rdonly) {
990 		cam_periph_unlock(periph);
991 		biofinish(bp, NULL, EBADF);
992 		return;
993 	}
994 
995 	if (softc->open_pending_mount) {
996 		int error = samount(periph, 0, bp->bio_dev);
997 		if (error) {
998 			cam_periph_unlock(periph);
999 			biofinish(bp, NULL, ENXIO);
1000 			return;
1001 		}
1002 		saprevent(periph, PR_PREVENT);
1003 		softc->open_pending_mount = 0;
1004 	}
1005 
1006 	/*
1007 	 * If it's a null transfer, return immediately
1008 	 */
1009 	if (bp->bio_bcount == 0) {
1010 		cam_periph_unlock(periph);
1011 		biodone(bp);
1012 		return;
1013 	}
1014 
1015 	/* valid request?  */
1016 	if (softc->flags & SA_FLAG_FIXED) {
1017 		/*
1018 		 * Fixed block device.  The byte count must
1019 		 * be a multiple of our block size.
1020 		 */
1021 		if (((softc->blk_mask != ~0) &&
1022 		    ((bp->bio_bcount & softc->blk_mask) != 0)) ||
1023 		    ((softc->blk_mask == ~0) &&
1024 		    ((bp->bio_bcount % softc->min_blk) != 0))) {
1025 			xpt_print(periph->path, "Invalid request.  Fixed block "
1026 			    "device requests must be a multiple of %d bytes\n",
1027 			    softc->min_blk);
1028 			cam_periph_unlock(periph);
1029 			biofinish(bp, NULL, EINVAL);
1030 			return;
1031 		}
1032 	} else if ((bp->bio_bcount > softc->max_blk) ||
1033 		   (bp->bio_bcount < softc->min_blk) ||
1034 		   (bp->bio_bcount & softc->blk_mask) != 0) {
1035 		xpt_print_path(periph->path);
1036 		printf("Invalid request.  Variable block "
1037 		    "device requests must be ");
1038 		if (softc->blk_mask != 0) {
1039 			printf("a multiple of %d ", (0x1 << softc->blk_gran));
1040 		}
1041 		printf("between %d and %d bytes\n", softc->min_blk,
1042 		    softc->max_blk);
1043 		cam_periph_unlock(periph);
1044 		biofinish(bp, NULL, EINVAL);
1045 		return;
1046         }
1047 
1048 	/*
1049 	 * Place it at the end of the queue.
1050 	 */
1051 	bioq_insert_tail(&softc->bio_queue, bp);
1052 	softc->queue_count++;
1053 #if	0
1054 	CAM_DEBUG(periph->path, CAM_DEBUG_INFO,
1055 	    ("sastrategy: queuing a %ld %s byte %s\n", bp->bio_bcount,
1056  	    (softc->flags & SA_FLAG_FIXED)?  "fixed" : "variable",
1057 	    (bp->bio_cmd == BIO_READ)? "read" : "write"));
1058 #endif
1059 	if (softc->queue_count > 1) {
1060 		CAM_DEBUG(periph->path, CAM_DEBUG_INFO,
1061 		    ("sastrategy: queue count now %d\n", softc->queue_count));
1062 	}
1063 
1064 	/*
1065 	 * Schedule ourselves for performing the work.
1066 	 */
1067 	xpt_schedule(periph, CAM_PRIORITY_NORMAL);
1068 	cam_periph_unlock(periph);
1069 
1070 	return;
1071 }
1072 
1073 static int
1074 sasetsili(struct cam_periph *periph, struct mtparamset *ps, int num_params)
1075 {
1076 	uint32_t sili_blocksize;
1077 	struct sa_softc *softc;
1078 	int error;
1079 
1080 	error = 0;
1081 	softc = (struct sa_softc *)periph->softc;
1082 
1083 	if (ps->value_type != MT_PARAM_SET_SIGNED) {
1084 		snprintf(ps->error_str, sizeof(ps->error_str),
1085 		    "sili is a signed parameter");
1086 		goto bailout;
1087 	}
1088 	if ((ps->value.value_signed < 0)
1089 	 || (ps->value.value_signed > 1)) {
1090 		snprintf(ps->error_str, sizeof(ps->error_str),
1091 		    "invalid sili value %jd", (intmax_t)ps->value.value_signed);
1092 		goto bailout_error;
1093 	}
1094 	/*
1095 	 * We only set the SILI flag in variable block
1096 	 * mode.  You'll get a check condition in fixed
1097 	 * block mode if things don't line up in any case.
1098 	 */
1099 	if (softc->flags & SA_FLAG_FIXED) {
1100 		snprintf(ps->error_str, sizeof(ps->error_str),
1101 		    "can't set sili bit in fixed block mode");
1102 		goto bailout_error;
1103 	}
1104 	if (softc->sili == ps->value.value_signed)
1105 		goto bailout;
1106 
1107 	if (ps->value.value_signed == 1)
1108 		sili_blocksize = 4;
1109 	else
1110 		sili_blocksize = 0;
1111 
1112 	error = sasetparams(periph, SA_PARAM_BLOCKSIZE,
1113 			    sili_blocksize, 0, 0, SF_QUIET_IR);
1114 	if (error != 0) {
1115 		snprintf(ps->error_str, sizeof(ps->error_str),
1116 		    "sasetparams() returned error %d", error);
1117 		goto bailout_error;
1118 	}
1119 
1120 	softc->sili = ps->value.value_signed;
1121 
1122 bailout:
1123 	ps->status = MT_PARAM_STATUS_OK;
1124 	return (error);
1125 
1126 bailout_error:
1127 	ps->status = MT_PARAM_STATUS_ERROR;
1128 	if (error == 0)
1129 		error = EINVAL;
1130 
1131 	return (error);
1132 }
1133 
1134 static int
1135 saseteotwarn(struct cam_periph *periph, struct mtparamset *ps, int num_params)
1136 {
1137 	struct sa_softc *softc;
1138 	int error;
1139 
1140 	error = 0;
1141 	softc = (struct sa_softc *)periph->softc;
1142 
1143 	if (ps->value_type != MT_PARAM_SET_SIGNED) {
1144 		snprintf(ps->error_str, sizeof(ps->error_str),
1145 		    "eot_warn is a signed parameter");
1146 		ps->status = MT_PARAM_STATUS_ERROR;
1147 		goto bailout;
1148 	}
1149 	if ((ps->value.value_signed < 0)
1150 	 || (ps->value.value_signed > 1)) {
1151 		snprintf(ps->error_str, sizeof(ps->error_str),
1152 		    "invalid eot_warn value %jd\n",
1153 		    (intmax_t)ps->value.value_signed);
1154 		ps->status = MT_PARAM_STATUS_ERROR;
1155 		goto bailout;
1156 	}
1157 	softc->eot_warn = ps->value.value_signed;
1158 	ps->status = MT_PARAM_STATUS_OK;
1159 bailout:
1160 	if (ps->status != MT_PARAM_STATUS_OK)
1161 		error = EINVAL;
1162 
1163 	return (error);
1164 }
1165 
1166 static void
1167 safillprot(struct sa_softc *softc, int *indent, struct sbuf *sb)
1168 {
1169 	int tmpint;
1170 
1171 	SASBADDNODE(sb, *indent, protection);
1172 	if (softc->flags & SA_FLAG_PROTECT_SUPP)
1173 		tmpint = 1;
1174 	else
1175 		tmpint = 0;
1176 	SASBADDINTDESC(sb, *indent, tmpint, %d, protection_supported,
1177 	    "Set to 1 if protection information is supported");
1178 
1179 	if ((tmpint != 0)
1180 	 && (softc->prot_info.cur_prot_state.initialized != 0)) {
1181 		struct sa_prot_state *prot;
1182 
1183 		prot = &softc->prot_info.cur_prot_state;
1184 
1185 		SASBADDUINTDESC(sb, *indent, prot->prot_method, %u,
1186 		    prot_method, "Current Protection Method");
1187 		SASBADDUINTDESC(sb, *indent, prot->pi_length, %u,
1188 		    pi_length, "Length of Protection Information");
1189 		SASBADDUINTDESC(sb, *indent, prot->lbp_w, %u,
1190 		    lbp_w, "Check Protection on Writes");
1191 		SASBADDUINTDESC(sb, *indent, prot->lbp_r, %u,
1192 		    lbp_r, "Check and Include Protection on Reads");
1193 		SASBADDUINTDESC(sb, *indent, prot->rbdp, %u,
1194 		    rbdp, "Transfer Protection Information for RECOVER "
1195 		    "BUFFERED DATA command");
1196 	}
1197 	SASBENDNODE(sb, *indent, protection);
1198 }
1199 
1200 static void
1201 sapopulateprots(struct sa_prot_state *cur_state, struct sa_prot_map *new_table,
1202     int table_ents)
1203 {
1204 	int i;
1205 
1206 	bcopy(sa_prot_table, new_table, min(table_ents * sizeof(*new_table),
1207 	    sizeof(sa_prot_table)));
1208 
1209 	table_ents = min(table_ents, SA_NUM_PROT_ENTS);
1210 
1211 	for (i = 0; i < table_ents; i++)
1212 		new_table[i].value = (uint32_t *)((uint8_t *)cur_state +
1213 		    new_table[i].offset);
1214 
1215 	return;
1216 }
1217 
1218 static struct sa_prot_map *
1219 safindprotent(char *name, struct sa_prot_map *table, int table_ents)
1220 {
1221 	char *prot_name = "protection.";
1222 	int i, prot_len;
1223 
1224 	prot_len = strlen(prot_name);
1225 
1226 	/*
1227 	 * This shouldn't happen, but we check just in case.
1228 	 */
1229 	if (strncmp(name, prot_name, prot_len) != 0)
1230 		goto bailout;
1231 
1232 	for (i = 0; i < table_ents; i++) {
1233 		if (strcmp(&name[prot_len], table[i].name) != 0)
1234 			continue;
1235 		return (&table[i]);
1236 	}
1237 bailout:
1238 	return (NULL);
1239 }
1240 
1241 static int
1242 sasetprotents(struct cam_periph *periph, struct mtparamset *ps, int num_params)
1243 {
1244 	struct sa_softc *softc;
1245 	struct sa_prot_map prot_ents[SA_NUM_PROT_ENTS];
1246 	struct sa_prot_state new_state;
1247 	int error;
1248 	int i;
1249 
1250 	softc = (struct sa_softc *)periph->softc;
1251 	error = 0;
1252 
1253 	/*
1254 	 * Make sure that this tape drive supports protection information.
1255 	 * Otherwise we can't set anything.
1256 	 */
1257 	if ((softc->flags & SA_FLAG_PROTECT_SUPP) == 0) {
1258 		snprintf(ps[0].error_str, sizeof(ps[0].error_str),
1259 		    "Protection information is not supported for this device");
1260 		ps[0].status = MT_PARAM_STATUS_ERROR;
1261 		goto bailout;
1262 	}
1263 
1264 	/*
1265 	 * We can't operate with physio(9) splitting enabled, because there
1266 	 * is no way to insure (especially in variable block mode) that
1267 	 * what the user writes (with a checksum block at the end) will
1268 	 * make it into the sa(4) driver intact.
1269 	 */
1270 	if ((softc->si_flags & SI_NOSPLIT) == 0) {
1271 		snprintf(ps[0].error_str, sizeof(ps[0].error_str),
1272 		    "Protection information cannot be enabled with I/O "
1273 		    "splitting");
1274 		ps[0].status = MT_PARAM_STATUS_ERROR;
1275 		goto bailout;
1276 	}
1277 
1278 	/*
1279 	 * Take the current cached protection state and use that as the
1280 	 * basis for our new entries.
1281 	 */
1282 	bcopy(&softc->prot_info.cur_prot_state, &new_state, sizeof(new_state));
1283 
1284 	/*
1285 	 * Populate the table mapping property names to pointers into the
1286 	 * state structure.
1287 	 */
1288 	sapopulateprots(&new_state, prot_ents, SA_NUM_PROT_ENTS);
1289 
1290 	/*
1291 	 * For each parameter the user passed in, make sure the name, type
1292 	 * and value are valid.
1293 	 */
1294 	for (i = 0; i < num_params; i++) {
1295 		struct sa_prot_map *ent;
1296 
1297 		ent = safindprotent(ps[i].value_name, prot_ents,
1298 		    SA_NUM_PROT_ENTS);
1299 		if (ent == NULL) {
1300 			ps[i].status = MT_PARAM_STATUS_ERROR;
1301 			snprintf(ps[i].error_str, sizeof(ps[i].error_str),
1302 			    "Invalid protection entry name %s",
1303 			    ps[i].value_name);
1304 			error = EINVAL;
1305 			goto bailout;
1306 		}
1307 		if (ent->param_type != ps[i].value_type) {
1308 			ps[i].status = MT_PARAM_STATUS_ERROR;
1309 			snprintf(ps[i].error_str, sizeof(ps[i].error_str),
1310 			    "Supplied type %d does not match actual type %d",
1311 			    ps[i].value_type, ent->param_type);
1312 			error = EINVAL;
1313 			goto bailout;
1314 		}
1315 		if ((ps[i].value.value_unsigned < ent->min_val)
1316 		 || (ps[i].value.value_unsigned > ent->max_val)) {
1317 			ps[i].status = MT_PARAM_STATUS_ERROR;
1318 			snprintf(ps[i].error_str, sizeof(ps[i].error_str),
1319 			    "Value %ju is outside valid range %u - %u",
1320 			    (uintmax_t)ps[i].value.value_unsigned, ent->min_val,
1321 			    ent->max_val);
1322 			error = EINVAL;
1323 			goto bailout;
1324 		}
1325 		*(ent->value) = ps[i].value.value_unsigned;
1326 	}
1327 
1328 	/*
1329 	 * Actually send the protection settings to the drive.
1330 	 */
1331 	error = sasetprot(periph, &new_state);
1332 	if (error != 0) {
1333 		for (i = 0; i < num_params; i++) {
1334 			ps[i].status = MT_PARAM_STATUS_ERROR;
1335 			snprintf(ps[i].error_str, sizeof(ps[i].error_str),
1336 			    "Unable to set parameter, see dmesg(8)");
1337 		}
1338 		goto bailout;
1339 	}
1340 
1341 	/*
1342 	 * Let the user know that his settings were stored successfully.
1343 	 */
1344 	for (i = 0; i < num_params; i++)
1345 		ps[i].status = MT_PARAM_STATUS_OK;
1346 
1347 bailout:
1348 	return (error);
1349 }
1350 /*
1351  * Entry handlers generally only handle a single entry.  Node handlers will
1352  * handle a contiguous range of parameters to set in a single call.
1353  */
1354 typedef enum {
1355 	SA_PARAM_TYPE_ENTRY,
1356 	SA_PARAM_TYPE_NODE
1357 } sa_param_type;
1358 
1359 struct sa_param_ent {
1360 	char *name;
1361 	sa_param_type param_type;
1362 	int (*set_func)(struct cam_periph *periph, struct mtparamset *ps,
1363 			int num_params);
1364 } sa_param_table[] = {
1365 	{"sili", SA_PARAM_TYPE_ENTRY, sasetsili },
1366 	{"eot_warn", SA_PARAM_TYPE_ENTRY, saseteotwarn },
1367 	{"protection.", SA_PARAM_TYPE_NODE, sasetprotents }
1368 };
1369 
1370 static struct sa_param_ent *
1371 safindparament(struct mtparamset *ps)
1372 {
1373 	unsigned int i;
1374 
1375 	for (i = 0; i < nitems(sa_param_table); i++){
1376 		/*
1377 		 * For entries, we compare all of the characters.  For
1378 		 * nodes, we only compare the first N characters.  The node
1379 		 * handler will decode the rest.
1380 		 */
1381 		if (sa_param_table[i].param_type == SA_PARAM_TYPE_ENTRY) {
1382 			if (strcmp(ps->value_name, sa_param_table[i].name) != 0)
1383 				continue;
1384 		} else {
1385 			if (strncmp(ps->value_name, sa_param_table[i].name,
1386 			    strlen(sa_param_table[i].name)) != 0)
1387 				continue;
1388 		}
1389 		return (&sa_param_table[i]);
1390 	}
1391 
1392 	return (NULL);
1393 }
1394 
1395 /*
1396  * Go through a list of parameters, coalescing contiguous parameters with
1397  * the same parent node into a single call to a set_func.
1398  */
1399 static int
1400 saparamsetlist(struct cam_periph *periph, struct mtsetlist *list,
1401     int need_copy)
1402 {
1403 	int i, contig_ents;
1404 	int error;
1405 	struct mtparamset *params, *first;
1406 	struct sa_param_ent *first_ent;
1407 
1408 	error = 0;
1409 	params = NULL;
1410 
1411 	if (list->num_params == 0)
1412 		/* Nothing to do */
1413 		goto bailout;
1414 
1415 	/*
1416 	 * Verify that the user has the correct structure size.
1417 	 */
1418 	if ((list->num_params * sizeof(struct mtparamset)) !=
1419 	     list->param_len) {
1420 		xpt_print(periph->path, "%s: length of params %d != "
1421 		    "sizeof(struct mtparamset) %zd * num_params %d\n",
1422 		    __func__, list->param_len, sizeof(struct mtparamset),
1423 		    list->num_params);
1424 		error = EINVAL;
1425 		goto bailout;
1426 	}
1427 
1428 	if (need_copy != 0) {
1429 		/*
1430 		 * XXX KDM will dropping the lock cause an issue here?
1431 		 */
1432 		cam_periph_unlock(periph);
1433 		params = malloc(list->param_len, M_SCSISA, M_WAITOK | M_ZERO);
1434 		error = copyin(list->params, params, list->param_len);
1435 		cam_periph_lock(periph);
1436 
1437 		if (error != 0)
1438 			goto bailout;
1439 	} else {
1440 		params = list->params;
1441 	}
1442 
1443 	contig_ents = 0;
1444 	first = NULL;
1445 	first_ent = NULL;
1446 	for (i = 0; i < list->num_params; i++) {
1447 		struct sa_param_ent *ent;
1448 
1449 		ent = safindparament(&params[i]);
1450 		if (ent == NULL) {
1451 			snprintf(params[i].error_str,
1452 			    sizeof(params[i].error_str),
1453 			    "%s: cannot find parameter %s", __func__,
1454 			    params[i].value_name);
1455 			params[i].status = MT_PARAM_STATUS_ERROR;
1456 			break;
1457 		}
1458 
1459 		if (first != NULL) {
1460 			if (first_ent == ent) {
1461 				/*
1462 				 * We're still in a contiguous list of
1463 				 * parameters that can be handled by one
1464 				 * node handler.
1465 				 */
1466 				contig_ents++;
1467 				continue;
1468 			} else {
1469 				error = first_ent->set_func(periph, first,
1470 				    contig_ents);
1471 				first = NULL;
1472 				first_ent = NULL;
1473 				contig_ents = 0;
1474 				if (error != 0) {
1475 					error = 0;
1476 					break;
1477 				}
1478 			}
1479 		}
1480 		if (ent->param_type == SA_PARAM_TYPE_NODE) {
1481 			first = &params[i];
1482 			first_ent = ent;
1483 			contig_ents = 1;
1484 		} else {
1485 			error = ent->set_func(periph, &params[i], 1);
1486 			if (error != 0) {
1487 				error = 0;
1488 				break;
1489 			}
1490 		}
1491 	}
1492 	if (first != NULL)
1493 		first_ent->set_func(periph, first, contig_ents);
1494 
1495 bailout:
1496 	if (need_copy != 0) {
1497 		if (error != EFAULT) {
1498 			cam_periph_unlock(periph);
1499 			copyout(params, list->params, list->param_len);
1500 			cam_periph_lock(periph);
1501 		}
1502 		free(params, M_SCSISA);
1503 	}
1504 	return (error);
1505 }
1506 
1507 static int
1508 sagetparams_common(struct cdev *dev, struct cam_periph *periph)
1509 {
1510 	struct sa_softc *softc;
1511 	uint8_t write_protect;
1512 	int comp_enabled, comp_supported, error;
1513 
1514 	softc = (struct sa_softc *)periph->softc;
1515 
1516 	if (softc->open_pending_mount)
1517 		return (0);
1518 
1519 	/* The control device may issue getparams() if there are no opens. */
1520 	if (SA_IS_CTRL(dev) && (softc->flags & SA_FLAG_OPEN) != 0)
1521 		return (0);
1522 
1523 	error = sagetparams(periph, SA_PARAM_ALL, &softc->media_blksize,
1524 	    &softc->media_density, &softc->media_numblks, &softc->buffer_mode,
1525 	    &write_protect, &softc->speed, &comp_supported, &comp_enabled,
1526 	    &softc->comp_algorithm, NULL, NULL, 0, 0);
1527 	if (error)
1528 		return (error);
1529 	if (write_protect)
1530 		softc->flags |= SA_FLAG_TAPE_WP;
1531 	else
1532 		softc->flags &= ~SA_FLAG_TAPE_WP;
1533 	softc->flags &= ~SA_FLAG_COMPRESSION;
1534 	if (comp_supported) {
1535 		if (softc->saved_comp_algorithm == 0)
1536 			softc->saved_comp_algorithm =
1537 			    softc->comp_algorithm;
1538 		softc->flags |= SA_FLAG_COMP_SUPP;
1539 		if (comp_enabled)
1540 			softc->flags |= SA_FLAG_COMP_ENABLED;
1541 	} else
1542 		softc->flags |= SA_FLAG_COMP_UNSUPP;
1543 
1544 	return (0);
1545 }
1546 
1547 #define	PENDING_MOUNT_CHECK(softc, periph, dev)		\
1548 	if (softc->open_pending_mount) {		\
1549 		error = samount(periph, 0, dev);	\
1550 		if (error) {				\
1551 			break;				\
1552 		}					\
1553 		saprevent(periph, PR_PREVENT);		\
1554 		softc->open_pending_mount = 0;		\
1555 	}
1556 
1557 static int
1558 saioctl(struct cdev *dev, u_long cmd, caddr_t arg, int flag, struct thread *td)
1559 {
1560 	struct cam_periph *periph;
1561 	struct sa_softc *softc;
1562 	scsi_space_code spaceop;
1563 	int didlockperiph = 0;
1564 	int mode;
1565 	int error = 0;
1566 
1567 	mode = SAMODE(dev);
1568 	error = 0;		/* shut up gcc */
1569 	spaceop = 0;		/* shut up gcc */
1570 
1571 	periph = (struct cam_periph *)dev->si_drv1;
1572 	cam_periph_lock(periph);
1573 	softc = (struct sa_softc *)periph->softc;
1574 
1575 	/*
1576 	 * Check for control mode accesses. We allow MTIOCGET and
1577 	 * MTIOCERRSTAT (but need to be the only one open in order
1578 	 * to clear latched status), and MTSETBSIZE, MTSETDNSTY
1579 	 * and MTCOMP (but need to be the only one accessing this
1580 	 * device to run those).
1581 	 */
1582 
1583 	if (SA_IS_CTRL(dev)) {
1584 		switch (cmd) {
1585 		case MTIOCGETEOTMODEL:
1586 		case MTIOCGET:
1587 		case MTIOCEXTGET:
1588 		case MTIOCPARAMGET:
1589 		case MTIOCRBLIM:
1590 			break;
1591 		case MTIOCERRSTAT:
1592 			/*
1593 			 * If the periph isn't already locked, lock it
1594 			 * so our MTIOCERRSTAT can reset latched error stats.
1595 			 *
1596 			 * If the periph is already locked, skip it because
1597 			 * we're just getting status and it'll be up to the
1598 			 * other thread that has this device open to do
1599 			 * an MTIOCERRSTAT that would clear latched status.
1600 			 */
1601 			if ((periph->flags & CAM_PERIPH_LOCKED) == 0) {
1602 				error = cam_periph_hold(periph, PRIBIO|PCATCH);
1603 				if (error != 0) {
1604 					cam_periph_unlock(periph);
1605 					return (error);
1606 				}
1607 				didlockperiph = 1;
1608 			}
1609 			break;
1610 
1611 		case MTIOCTOP:
1612 		{
1613 			struct mtop *mt = (struct mtop *) arg;
1614 
1615 			/*
1616 			 * Check to make sure it's an OP we can perform
1617 			 * with no media inserted.
1618 			 */
1619 			switch (mt->mt_op) {
1620 			case MTSETBSIZ:
1621 			case MTSETDNSTY:
1622 			case MTCOMP:
1623 				mt = NULL;
1624 				/* FALLTHROUGH */
1625 			default:
1626 				break;
1627 			}
1628 			if (mt != NULL) {
1629 				break;
1630 			}
1631 			/* FALLTHROUGH */
1632 		}
1633 		case MTIOCSETEOTMODEL:
1634 			/*
1635 			 * We need to acquire the peripheral here rather
1636 			 * than at open time because we are sharing writable
1637 			 * access to data structures.
1638 			 */
1639 			error = cam_periph_hold(periph, PRIBIO|PCATCH);
1640 			if (error != 0) {
1641 				cam_periph_unlock(periph);
1642 				return (error);
1643 			}
1644 			didlockperiph = 1;
1645 			break;
1646 
1647 		default:
1648 			cam_periph_unlock(periph);
1649 			return (EINVAL);
1650 		}
1651 	}
1652 
1653 	/*
1654 	 * Find the device that the user is talking about
1655 	 */
1656 	switch (cmd) {
1657 	case MTIOCGET:
1658 	{
1659 		struct mtget *g = (struct mtget *)arg;
1660 
1661 		error = sagetparams_common(dev, periph);
1662 		if (error)
1663 			break;
1664 		bzero(g, sizeof(struct mtget));
1665 		g->mt_type = MT_ISAR;
1666 		if (softc->flags & SA_FLAG_COMP_UNSUPP) {
1667 			g->mt_comp = MT_COMP_UNSUPP;
1668 			g->mt_comp0 = MT_COMP_UNSUPP;
1669 			g->mt_comp1 = MT_COMP_UNSUPP;
1670 			g->mt_comp2 = MT_COMP_UNSUPP;
1671 			g->mt_comp3 = MT_COMP_UNSUPP;
1672 		} else {
1673 			if ((softc->flags & SA_FLAG_COMP_ENABLED) == 0) {
1674 				g->mt_comp = MT_COMP_DISABLED;
1675 			} else {
1676 				g->mt_comp = softc->comp_algorithm;
1677 			}
1678 			g->mt_comp0 = softc->comp_algorithm;
1679 			g->mt_comp1 = softc->comp_algorithm;
1680 			g->mt_comp2 = softc->comp_algorithm;
1681 			g->mt_comp3 = softc->comp_algorithm;
1682 		}
1683 		g->mt_density = softc->media_density;
1684 		g->mt_density0 = softc->media_density;
1685 		g->mt_density1 = softc->media_density;
1686 		g->mt_density2 = softc->media_density;
1687 		g->mt_density3 = softc->media_density;
1688 		g->mt_blksiz = softc->media_blksize;
1689 		g->mt_blksiz0 = softc->media_blksize;
1690 		g->mt_blksiz1 = softc->media_blksize;
1691 		g->mt_blksiz2 = softc->media_blksize;
1692 		g->mt_blksiz3 = softc->media_blksize;
1693 		g->mt_fileno = softc->fileno;
1694 		g->mt_blkno = softc->blkno;
1695 		g->mt_dsreg = (short) softc->dsreg;
1696 		/*
1697 		 * Yes, we know that this is likely to overflow
1698 		 */
1699 		if (softc->last_resid_was_io) {
1700 			if ((g->mt_resid = (short) softc->last_io_resid) != 0) {
1701 				if (SA_IS_CTRL(dev) == 0 || didlockperiph) {
1702 					softc->last_io_resid = 0;
1703 				}
1704 			}
1705 		} else {
1706 			if ((g->mt_resid = (short)softc->last_ctl_resid) != 0) {
1707 				if (SA_IS_CTRL(dev) == 0 || didlockperiph) {
1708 					softc->last_ctl_resid = 0;
1709 				}
1710 			}
1711 		}
1712 		error = 0;
1713 		break;
1714 	}
1715 	case MTIOCEXTGET:
1716 	case MTIOCPARAMGET:
1717 	{
1718 		struct mtextget *g = (struct mtextget *)arg;
1719 		char *tmpstr2;
1720 		struct sbuf *sb;
1721 
1722 		/*
1723 		 * Report drive status using an XML format.
1724 		 */
1725 
1726 		/*
1727 		 * XXX KDM will dropping the lock cause any problems here?
1728 		 */
1729 		cam_periph_unlock(periph);
1730 		sb = sbuf_new(NULL, NULL, g->alloc_len, SBUF_FIXEDLEN);
1731 		if (sb == NULL) {
1732 			g->status = MT_EXT_GET_ERROR;
1733 			snprintf(g->error_str, sizeof(g->error_str),
1734 				 "Unable to allocate %d bytes for status info",
1735 				 g->alloc_len);
1736 			cam_periph_lock(periph);
1737 			goto extget_bailout;
1738 		}
1739 		cam_periph_lock(periph);
1740 
1741 		if (cmd == MTIOCEXTGET)
1742 			error = saextget(dev, periph, sb, g);
1743 		else
1744 			error = saparamget(softc, sb);
1745 
1746 		if (error != 0)
1747 			goto extget_bailout;
1748 
1749 		error = sbuf_finish(sb);
1750 		if (error == ENOMEM) {
1751 			g->status = MT_EXT_GET_NEED_MORE_SPACE;
1752 			error = 0;
1753 		} else if (error != 0) {
1754 			g->status = MT_EXT_GET_ERROR;
1755 			snprintf(g->error_str, sizeof(g->error_str),
1756 			    "Error %d returned from sbuf_finish()", error);
1757 		} else
1758 			g->status = MT_EXT_GET_OK;
1759 
1760 		error = 0;
1761 		tmpstr2 = sbuf_data(sb);
1762 		g->fill_len = strlen(tmpstr2) + 1;
1763 		cam_periph_unlock(periph);
1764 
1765 		error = copyout(tmpstr2, g->status_xml, g->fill_len);
1766 
1767 		cam_periph_lock(periph);
1768 
1769 extget_bailout:
1770 		sbuf_delete(sb);
1771 		break;
1772 	}
1773 	case MTIOCPARAMSET:
1774 	{
1775 		struct mtsetlist list;
1776 		struct mtparamset *ps = (struct mtparamset *)arg;
1777 
1778 		bzero(&list, sizeof(list));
1779 		list.num_params = 1;
1780 		list.param_len = sizeof(*ps);
1781 		list.params = ps;
1782 
1783 		error = saparamsetlist(periph, &list, /*need_copy*/ 0);
1784 		break;
1785 	}
1786 	case MTIOCSETLIST:
1787 	{
1788 		struct mtsetlist *list = (struct mtsetlist *)arg;
1789 
1790 		error = saparamsetlist(periph, list, /*need_copy*/ 1);
1791 		break;
1792 	}
1793 	case MTIOCERRSTAT:
1794 	{
1795 		struct scsi_tape_errors *sep =
1796 		    &((union mterrstat *)arg)->scsi_errstat;
1797 
1798 		CAM_DEBUG(periph->path, CAM_DEBUG_TRACE,
1799 		    ("saioctl: MTIOCERRSTAT\n"));
1800 
1801 		bzero(sep, sizeof(*sep));
1802 		sep->io_resid = softc->last_io_resid;
1803 		bcopy((caddr_t) &softc->last_io_sense, sep->io_sense,
1804 		    sizeof (sep->io_sense));
1805 		bcopy((caddr_t) &softc->last_io_cdb, sep->io_cdb,
1806 		    sizeof (sep->io_cdb));
1807 		sep->ctl_resid = softc->last_ctl_resid;
1808 		bcopy((caddr_t) &softc->last_ctl_sense, sep->ctl_sense,
1809 		    sizeof (sep->ctl_sense));
1810 		bcopy((caddr_t) &softc->last_ctl_cdb, sep->ctl_cdb,
1811 		    sizeof (sep->ctl_cdb));
1812 
1813 		if ((SA_IS_CTRL(dev) == 0 && !softc->open_pending_mount) ||
1814 		    didlockperiph)
1815 			bzero((caddr_t) &softc->errinfo,
1816 			    sizeof (softc->errinfo));
1817 		error = 0;
1818 		break;
1819 	}
1820 	case MTIOCTOP:
1821 	{
1822 		struct mtop *mt;
1823 		int    count;
1824 
1825 		PENDING_MOUNT_CHECK(softc, periph, dev);
1826 
1827 		mt = (struct mtop *)arg;
1828 
1829 		CAM_DEBUG(periph->path, CAM_DEBUG_TRACE,
1830 			 ("saioctl: op=0x%x count=0x%x\n",
1831 			  mt->mt_op, mt->mt_count));
1832 
1833 		count = mt->mt_count;
1834 		switch (mt->mt_op) {
1835 		case MTWEOF:	/* write an end-of-file marker */
1836 			/*
1837 			 * We don't need to clear the SA_FLAG_TAPE_WRITTEN
1838 			 * flag because by keeping track of filemarks
1839 			 * we have last written we know whether or not
1840 			 * we need to write more when we close the device.
1841 			 */
1842 			error = sawritefilemarks(periph, count, FALSE, FALSE);
1843 			break;
1844 		case MTWEOFI:
1845 			/* write an end-of-file marker without waiting */
1846 			error = sawritefilemarks(periph, count, FALSE, TRUE);
1847 			break;
1848 		case MTWSS:	/* write a setmark */
1849 			error = sawritefilemarks(periph, count, TRUE, FALSE);
1850 			break;
1851 		case MTBSR:	/* backward space record */
1852 		case MTFSR:	/* forward space record */
1853 		case MTBSF:	/* backward space file */
1854 		case MTFSF:	/* forward space file */
1855 		case MTBSS:	/* backward space setmark */
1856 		case MTFSS:	/* forward space setmark */
1857 		case MTEOD:	/* space to end of recorded medium */
1858 		{
1859 			int nmarks;
1860 
1861 			spaceop = SS_FILEMARKS;
1862 			nmarks = softc->filemarks;
1863 			error = sacheckeod(periph);
1864 			if (error) {
1865 				xpt_print(periph->path,
1866 				    "EOD check prior to spacing failed\n");
1867 				softc->flags |= SA_FLAG_EIO_PENDING;
1868 				break;
1869 			}
1870 			nmarks -= softc->filemarks;
1871 			switch(mt->mt_op) {
1872 			case MTBSR:
1873 				count = -count;
1874 				/* FALLTHROUGH */
1875 			case MTFSR:
1876 				spaceop = SS_BLOCKS;
1877 				break;
1878 			case MTBSF:
1879 				count = -count;
1880 				/* FALLTHROUGH */
1881 			case MTFSF:
1882 				break;
1883 			case MTBSS:
1884 				count = -count;
1885 				/* FALLTHROUGH */
1886 			case MTFSS:
1887 				spaceop = SS_SETMARKS;
1888 				break;
1889 			case MTEOD:
1890 				spaceop = SS_EOD;
1891 				count = 0;
1892 				nmarks = 0;
1893 				break;
1894 			default:
1895 				error = EINVAL;
1896 				break;
1897 			}
1898 			if (error)
1899 				break;
1900 
1901 			nmarks = softc->filemarks;
1902 			/*
1903 			 * XXX: Why are we checking again?
1904 			 */
1905 			error = sacheckeod(periph);
1906 			if (error)
1907 				break;
1908 			nmarks -= softc->filemarks;
1909 			error = saspace(periph, count - nmarks, spaceop);
1910 			/*
1911 			 * At this point, clear that we've written the tape
1912 			 * and that we've written any filemarks. We really
1913 			 * don't know what the applications wishes to do next-
1914 			 * the sacheckeod's will make sure we terminated the
1915 			 * tape correctly if we'd been writing, but the next
1916 			 * action the user application takes will set again
1917 			 * whether we need to write filemarks.
1918 			 */
1919 			softc->flags &=
1920 			    ~(SA_FLAG_TAPE_WRITTEN|SA_FLAG_TAPE_FROZEN);
1921 			softc->filemarks = 0;
1922 			break;
1923 		}
1924 		case MTREW:	/* rewind */
1925 			PENDING_MOUNT_CHECK(softc, periph, dev);
1926 			(void) sacheckeod(periph);
1927 			error = sarewind(periph);
1928 			/* see above */
1929 			softc->flags &=
1930 			    ~(SA_FLAG_TAPE_WRITTEN|SA_FLAG_TAPE_FROZEN);
1931 			softc->flags &= ~SA_FLAG_ERR_PENDING;
1932 			softc->filemarks = 0;
1933 			break;
1934 		case MTERASE:	/* erase */
1935 			PENDING_MOUNT_CHECK(softc, periph, dev);
1936 			error = saerase(periph, count);
1937 			softc->flags &=
1938 			    ~(SA_FLAG_TAPE_WRITTEN|SA_FLAG_TAPE_FROZEN);
1939 			softc->flags &= ~SA_FLAG_ERR_PENDING;
1940 			break;
1941 		case MTRETENS:	/* re-tension tape */
1942 			PENDING_MOUNT_CHECK(softc, periph, dev);
1943 			error = saretension(periph);
1944 			softc->flags &=
1945 			    ~(SA_FLAG_TAPE_WRITTEN|SA_FLAG_TAPE_FROZEN);
1946 			softc->flags &= ~SA_FLAG_ERR_PENDING;
1947 			break;
1948 		case MTOFFL:	/* rewind and put the drive offline */
1949 
1950 			PENDING_MOUNT_CHECK(softc, periph, dev);
1951 
1952 			(void) sacheckeod(periph);
1953 			/* see above */
1954 			softc->flags &= ~SA_FLAG_TAPE_WRITTEN;
1955 			softc->filemarks = 0;
1956 
1957 			error = sarewind(periph);
1958 			/* clear the frozen flag anyway */
1959 			softc->flags &= ~SA_FLAG_TAPE_FROZEN;
1960 
1961 			/*
1962 			 * Be sure to allow media removal before ejecting.
1963 			 */
1964 
1965 			saprevent(periph, PR_ALLOW);
1966 			if (error == 0) {
1967 				error = saloadunload(periph, FALSE);
1968 				if (error == 0) {
1969 					softc->flags &= ~SA_FLAG_TAPE_MOUNTED;
1970 				}
1971 			}
1972 			break;
1973 
1974 		case MTLOAD:
1975 			error = saloadunload(periph, TRUE);
1976 			break;
1977 		case MTNOP:	/* no operation, sets status only */
1978 		case MTCACHE:	/* enable controller cache */
1979 		case MTNOCACHE:	/* disable controller cache */
1980 			error = 0;
1981 			break;
1982 
1983 		case MTSETBSIZ:	/* Set block size for device */
1984 
1985 			PENDING_MOUNT_CHECK(softc, periph, dev);
1986 
1987 			if ((softc->sili != 0)
1988 			 && (count != 0)) {
1989 				xpt_print(periph->path, "Can't enter fixed "
1990 				    "block mode with SILI enabled\n");
1991 				error = EINVAL;
1992 				break;
1993 			}
1994 			error = sasetparams(periph, SA_PARAM_BLOCKSIZE, count,
1995 					    0, 0, 0);
1996 			if (error == 0) {
1997 				softc->last_media_blksize =
1998 				    softc->media_blksize;
1999 				softc->media_blksize = count;
2000 				if (count) {
2001 					softc->flags |= SA_FLAG_FIXED;
2002 					if (powerof2(count)) {
2003 						softc->blk_shift =
2004 						    ffs(count) - 1;
2005 						softc->blk_mask = count - 1;
2006 					} else {
2007 						softc->blk_mask = ~0;
2008 						softc->blk_shift = 0;
2009 					}
2010 					/*
2011 					 * Make the user's desire 'persistent'.
2012 					 */
2013 					softc->quirks &= ~SA_QUIRK_VARIABLE;
2014 					softc->quirks |= SA_QUIRK_FIXED;
2015 				} else {
2016 					softc->flags &= ~SA_FLAG_FIXED;
2017 					if (softc->max_blk == 0) {
2018 						softc->max_blk = ~0;
2019 					}
2020 					softc->blk_shift = 0;
2021 					if (softc->blk_gran != 0) {
2022 						softc->blk_mask =
2023 						    softc->blk_gran - 1;
2024 					} else {
2025 						softc->blk_mask = 0;
2026 					}
2027 					/*
2028 					 * Make the user's desire 'persistent'.
2029 					 */
2030 					softc->quirks |= SA_QUIRK_VARIABLE;
2031 					softc->quirks &= ~SA_QUIRK_FIXED;
2032 				}
2033 			}
2034 			break;
2035 		case MTSETDNSTY:	/* Set density for device and mode */
2036 			PENDING_MOUNT_CHECK(softc, periph, dev);
2037 
2038 			if (count > UCHAR_MAX) {
2039 				error = EINVAL;
2040 				break;
2041 			} else {
2042 				error = sasetparams(periph, SA_PARAM_DENSITY,
2043 						    0, count, 0, 0);
2044 			}
2045 			break;
2046 		case MTCOMP:	/* enable compression */
2047 			PENDING_MOUNT_CHECK(softc, periph, dev);
2048 			/*
2049 			 * Some devices don't support compression, and
2050 			 * don't like it if you ask them for the
2051 			 * compression page.
2052 			 */
2053 			if ((softc->quirks & SA_QUIRK_NOCOMP) ||
2054 			    (softc->flags & SA_FLAG_COMP_UNSUPP)) {
2055 				error = ENODEV;
2056 				break;
2057 			}
2058 			error = sasetparams(periph, SA_PARAM_COMPRESSION,
2059 			    0, 0, count, SF_NO_PRINT);
2060 			break;
2061 		default:
2062 			error = EINVAL;
2063 		}
2064 		break;
2065 	}
2066 	case MTIOCIEOT:
2067 	case MTIOCEEOT:
2068 		error = 0;
2069 		break;
2070 	case MTIOCRDSPOS:
2071 		PENDING_MOUNT_CHECK(softc, periph, dev);
2072 		error = sardpos(periph, 0, (uint32_t *) arg);
2073 		break;
2074 	case MTIOCRDHPOS:
2075 		PENDING_MOUNT_CHECK(softc, periph, dev);
2076 		error = sardpos(periph, 1, (uint32_t *) arg);
2077 		break;
2078 	case MTIOCSLOCATE:
2079 	case MTIOCHLOCATE: {
2080 		struct mtlocate locate_info;
2081 		int hard;
2082 
2083 		bzero(&locate_info, sizeof(locate_info));
2084 		locate_info.logical_id = *((uint32_t *)arg);
2085 		if (cmd == MTIOCSLOCATE)
2086 			hard = 0;
2087 		else
2088 			hard = 1;
2089 
2090 		PENDING_MOUNT_CHECK(softc, periph, dev);
2091 
2092 		error = sasetpos(periph, hard, &locate_info);
2093 		break;
2094 	}
2095 	case MTIOCEXTLOCATE:
2096 		PENDING_MOUNT_CHECK(softc, periph, dev);
2097 		error = sasetpos(periph, /*hard*/ 0, (struct mtlocate *)arg);
2098 		softc->flags &=
2099 		    ~(SA_FLAG_TAPE_WRITTEN|SA_FLAG_TAPE_FROZEN);
2100 		softc->flags &= ~SA_FLAG_ERR_PENDING;
2101 		softc->filemarks = 0;
2102 		break;
2103 	case MTIOCGETEOTMODEL:
2104 		error = 0;
2105 		if (softc->quirks & SA_QUIRK_1FM)
2106 			mode = 1;
2107 		else
2108 			mode = 2;
2109 		*((uint32_t *) arg) = mode;
2110 		break;
2111 	case MTIOCSETEOTMODEL:
2112 		error = 0;
2113 		switch (*((uint32_t *) arg)) {
2114 		case 1:
2115 			softc->quirks &= ~SA_QUIRK_2FM;
2116 			softc->quirks |= SA_QUIRK_1FM;
2117 			break;
2118 		case 2:
2119 			softc->quirks &= ~SA_QUIRK_1FM;
2120 			softc->quirks |= SA_QUIRK_2FM;
2121 			break;
2122 		default:
2123 			error = EINVAL;
2124 			break;
2125 		}
2126 		break;
2127 	case MTIOCRBLIM: {
2128 		struct mtrblim *rblim;
2129 
2130 		rblim = (struct mtrblim *)arg;
2131 
2132 		rblim->granularity = softc->blk_gran;
2133 		rblim->min_block_length = softc->min_blk;
2134 		rblim->max_block_length = softc->max_blk;
2135 		break;
2136 	}
2137 	default:
2138 		error = cam_periph_ioctl(periph, cmd, arg, saerror);
2139 		break;
2140 	}
2141 
2142 	/*
2143 	 * Check to see if we cleared a frozen state
2144 	 */
2145 	if (error == 0 && (softc->flags & SA_FLAG_TAPE_FROZEN)) {
2146 		switch(cmd) {
2147 		case MTIOCRDSPOS:
2148 		case MTIOCRDHPOS:
2149 		case MTIOCSLOCATE:
2150 		case MTIOCHLOCATE:
2151 			/*
2152 			 * XXX KDM look at this.
2153 			 */
2154 			softc->fileno = (daddr_t) -1;
2155 			softc->blkno = (daddr_t) -1;
2156 			softc->rep_blkno = (daddr_t) -1;
2157 			softc->rep_fileno = (daddr_t) -1;
2158 			softc->partition = (daddr_t) -1;
2159 			softc->flags &= ~SA_FLAG_TAPE_FROZEN;
2160 			xpt_print(periph->path,
2161 			    "tape state now unfrozen.\n");
2162 			break;
2163 		default:
2164 			break;
2165 		}
2166 	}
2167 	if (didlockperiph) {
2168 		cam_periph_unhold(periph);
2169 	}
2170 	cam_periph_unlock(periph);
2171 	return (error);
2172 }
2173 
2174 static void
2175 sainit(void)
2176 {
2177 	cam_status status;
2178 
2179 	/*
2180 	 * Install a global async callback.
2181 	 */
2182 	status = xpt_register_async(AC_FOUND_DEVICE, saasync, NULL, NULL);
2183 
2184 	if (status != CAM_REQ_CMP) {
2185 		printf("sa: Failed to attach master async callback "
2186 		       "due to status 0x%x!\n", status);
2187 	}
2188 }
2189 
2190 static void
2191 sadevgonecb(void *arg)
2192 {
2193 	struct cam_periph *periph;
2194 	struct mtx *mtx;
2195 	struct sa_softc *softc;
2196 
2197 	periph = (struct cam_periph *)arg;
2198 	softc = (struct sa_softc *)periph->softc;
2199 
2200 	mtx = cam_periph_mtx(periph);
2201 	mtx_lock(mtx);
2202 
2203 	softc->num_devs_to_destroy--;
2204 	if (softc->num_devs_to_destroy == 0) {
2205 		int i;
2206 
2207 		/*
2208 		 * When we have gotten all of our callbacks, we will get
2209 		 * no more close calls from devfs.  So if we have any
2210 		 * dangling opens, we need to release the reference held
2211 		 * for that particular context.
2212 		 */
2213 		for (i = 0; i < softc->open_count; i++)
2214 			cam_periph_release_locked(periph);
2215 
2216 		softc->open_count = 0;
2217 
2218 		/*
2219 		 * Release the reference held for devfs, all of our
2220 		 * instances are gone now.
2221 		 */
2222 		cam_periph_release_locked(periph);
2223 	}
2224 
2225 	/*
2226 	 * We reference the lock directly here, instead of using
2227 	 * cam_periph_unlock().  The reason is that the final call to
2228 	 * cam_periph_release_locked() above could result in the periph
2229 	 * getting freed.  If that is the case, dereferencing the periph
2230 	 * with a cam_periph_unlock() call would cause a page fault.
2231 	 */
2232 	mtx_unlock(mtx);
2233 }
2234 
2235 static void
2236 saoninvalidate(struct cam_periph *periph)
2237 {
2238 	struct sa_softc *softc;
2239 
2240 	softc = (struct sa_softc *)periph->softc;
2241 
2242 	/*
2243 	 * De-register any async callbacks.
2244 	 */
2245 	xpt_register_async(0, saasync, periph, periph->path);
2246 
2247 	softc->flags |= SA_FLAG_INVALID;
2248 
2249 	/*
2250 	 * Return all queued I/O with ENXIO.
2251 	 * XXX Handle any transactions queued to the card
2252 	 *     with XPT_ABORT_CCB.
2253 	 */
2254 	bioq_flush(&softc->bio_queue, NULL, ENXIO);
2255 	softc->queue_count = 0;
2256 
2257 	/*
2258 	 * Tell devfs that all of our devices have gone away, and ask for a
2259 	 * callback when it has cleaned up its state.
2260 	 */
2261 	destroy_dev_sched_cb(softc->devs.ctl_dev, sadevgonecb, periph);
2262 	destroy_dev_sched_cb(softc->devs.r_dev, sadevgonecb, periph);
2263 	destroy_dev_sched_cb(softc->devs.nr_dev, sadevgonecb, periph);
2264 	destroy_dev_sched_cb(softc->devs.er_dev, sadevgonecb, periph);
2265 }
2266 
2267 static void
2268 sacleanup(struct cam_periph *periph)
2269 {
2270 	struct sa_softc *softc;
2271 
2272 	softc = (struct sa_softc *)periph->softc;
2273 
2274 	cam_periph_unlock(periph);
2275 
2276 	if ((softc->flags & SA_FLAG_SCTX_INIT) != 0
2277 	 && (((softc->sysctl_timeout_tree != NULL)
2278 	   && (sysctl_ctx_free(&softc->sysctl_timeout_ctx) != 0))
2279 	  || sysctl_ctx_free(&softc->sysctl_ctx) != 0))
2280 		xpt_print(periph->path, "can't remove sysctl context\n");
2281 
2282 	cam_periph_lock(periph);
2283 
2284 	devstat_remove_entry(softc->device_stats);
2285 
2286 	free(softc, M_SCSISA);
2287 }
2288 
2289 static void
2290 saasync(void *callback_arg, uint32_t code,
2291 	struct cam_path *path, void *arg)
2292 {
2293 	struct cam_periph *periph;
2294 
2295 	periph = (struct cam_periph *)callback_arg;
2296 	switch (code) {
2297 	case AC_FOUND_DEVICE:
2298 	{
2299 		struct ccb_getdev *cgd;
2300 		cam_status status;
2301 
2302 		cgd = (struct ccb_getdev *)arg;
2303 		if (cgd == NULL)
2304 			break;
2305 
2306 		if (cgd->protocol != PROTO_SCSI)
2307 			break;
2308 		if (SID_QUAL(&cgd->inq_data) != SID_QUAL_LU_CONNECTED)
2309 			break;
2310 		if (SID_TYPE(&cgd->inq_data) != T_SEQUENTIAL)
2311 			break;
2312 
2313 		/*
2314 		 * Allocate a peripheral instance for
2315 		 * this device and start the probe
2316 		 * process.
2317 		 */
2318 		status = cam_periph_alloc(saregister, saoninvalidate,
2319 					  sacleanup, sastart,
2320 					  "sa", CAM_PERIPH_BIO, path,
2321 					  saasync, AC_FOUND_DEVICE, cgd);
2322 
2323 		if (status != CAM_REQ_CMP
2324 		 && status != CAM_REQ_INPROG)
2325 			printf("saasync: Unable to probe new device "
2326 				"due to status 0x%x\n", status);
2327 		break;
2328 	}
2329 	default:
2330 		cam_periph_async(periph, code, path, arg);
2331 		break;
2332 	}
2333 }
2334 
2335 static void
2336 sasetupdev(struct sa_softc *softc, struct cdev *dev)
2337 {
2338 
2339 	dev->si_iosize_max = softc->maxio;
2340 	dev->si_flags |= softc->si_flags;
2341 	/*
2342 	 * Keep a count of how many non-alias devices we have created,
2343 	 * so we can make sure we clean them all up on shutdown.  Aliases
2344 	 * are cleaned up when we destroy the device they're an alias for.
2345 	 */
2346 	if ((dev->si_flags & SI_ALIAS) == 0)
2347 		softc->num_devs_to_destroy++;
2348 }
2349 
2350 /*
2351  * Load the global (for all sa(4) instances) and per-instance tunable
2352  * values for timeouts for various sa(4) commands.  This should be run
2353  * after the default timeouts are fetched from the drive, so the user's
2354  * preference will override the drive's defaults.
2355  */
2356 static void
2357 saloadtotunables(struct sa_softc *softc)
2358 {
2359 	int i;
2360 	char tmpstr[80];
2361 
2362 	for (i = 0; i < SA_TIMEOUT_TYPE_MAX; i++) {
2363 		int tmpval, retval;
2364 
2365 		/* First grab any global timeout setting */
2366 		snprintf(tmpstr, sizeof(tmpstr), "kern.cam.sa.timeout.%s",
2367 		    sa_default_timeouts[i].desc);
2368 		retval = TUNABLE_INT_FETCH(tmpstr, &tmpval);
2369 		if (retval != 0)
2370 			softc->timeout_info[i] = tmpval;
2371 
2372 		/*
2373 		 * Then overwrite any global timeout settings with
2374 		 * per-instance timeout settings.
2375 		 */
2376 		snprintf(tmpstr, sizeof(tmpstr), "kern.cam.sa.%u.timeout.%s",
2377 		    softc->periph->unit_number, sa_default_timeouts[i].desc);
2378 		retval = TUNABLE_INT_FETCH(tmpstr, &tmpval);
2379 		if (retval != 0)
2380 			softc->timeout_info[i] = tmpval;
2381 	}
2382 }
2383 
2384 static void
2385 sasysctlinit(void *context, int pending)
2386 {
2387 	struct cam_periph *periph;
2388 	struct sa_softc *softc;
2389 	char tmpstr[64], tmpstr2[16];
2390 	int i;
2391 
2392 	periph = (struct cam_periph *)context;
2393 	/*
2394 	 * If the periph is invalid, no need to setup the sysctls.
2395 	 */
2396 	if (periph->flags & CAM_PERIPH_INVALID)
2397 		goto bailout;
2398 
2399 	softc = (struct sa_softc *)periph->softc;
2400 
2401 	snprintf(tmpstr, sizeof(tmpstr), "CAM SA unit %d", periph->unit_number);
2402 	snprintf(tmpstr2, sizeof(tmpstr2), "%u", periph->unit_number);
2403 
2404 	sysctl_ctx_init(&softc->sysctl_ctx);
2405 	softc->flags |= SA_FLAG_SCTX_INIT;
2406 	softc->sysctl_tree = SYSCTL_ADD_NODE_WITH_LABEL(&softc->sysctl_ctx,
2407 	    SYSCTL_STATIC_CHILDREN(_kern_cam_sa), OID_AUTO, tmpstr2,
2408 	    CTLFLAG_RD | CTLFLAG_MPSAFE, 0, tmpstr, "device_index");
2409 	if (softc->sysctl_tree == NULL)
2410 		goto bailout;
2411 
2412 	SYSCTL_ADD_INT(&softc->sysctl_ctx, SYSCTL_CHILDREN(softc->sysctl_tree),
2413 	    OID_AUTO, "allow_io_split", CTLFLAG_RDTUN | CTLFLAG_NOFETCH,
2414 	    &softc->allow_io_split, 0, "Allow Splitting I/O");
2415 	SYSCTL_ADD_INT(&softc->sysctl_ctx, SYSCTL_CHILDREN(softc->sysctl_tree),
2416 	    OID_AUTO, "maxio", CTLFLAG_RD,
2417 	    &softc->maxio, 0, "Maximum I/O size");
2418 	SYSCTL_ADD_INT(&softc->sysctl_ctx, SYSCTL_CHILDREN(softc->sysctl_tree),
2419 	    OID_AUTO, "cpi_maxio", CTLFLAG_RD,
2420 	    &softc->cpi_maxio, 0, "Maximum Controller I/O size");
2421 	SYSCTL_ADD_INT(&softc->sysctl_ctx, SYSCTL_CHILDREN(softc->sysctl_tree),
2422 	    OID_AUTO, "inject_eom", CTLFLAG_RW,
2423 	    &softc->inject_eom, 0, "Queue EOM for the next write/read");
2424 
2425 	sysctl_ctx_init(&softc->sysctl_timeout_ctx);
2426 	softc->sysctl_timeout_tree = SYSCTL_ADD_NODE(&softc->sysctl_timeout_ctx,
2427 	    SYSCTL_CHILDREN(softc->sysctl_tree), OID_AUTO, "timeout",
2428 	    CTLFLAG_RD | CTLFLAG_MPSAFE, 0, "Timeouts");
2429 	if (softc->sysctl_timeout_tree == NULL)
2430 		goto bailout;
2431 
2432 	for (i = 0; i < SA_TIMEOUT_TYPE_MAX; i++) {
2433 		snprintf(tmpstr, sizeof(tmpstr), "%s timeout",
2434 		    sa_default_timeouts[i].desc);
2435 
2436 		/*
2437 		 * Do NOT change this sysctl declaration to also load any
2438 		 * tunable values for this sa(4) instance.  In other words,
2439 		 * do not change this to CTLFLAG_RWTUN.  This function is
2440 		 * run in parallel with the probe routine that fetches
2441 		 * recommended timeout values from the tape drive, and we
2442 		 * don't want the values from the drive to override the
2443 		 * user's preference.
2444 		 */
2445 		SYSCTL_ADD_INT(&softc->sysctl_timeout_ctx,
2446 		    SYSCTL_CHILDREN(softc->sysctl_timeout_tree),
2447 	            OID_AUTO, sa_default_timeouts[i].desc, CTLFLAG_RW,
2448 		    &softc->timeout_info[i], 0, tmpstr);
2449 	}
2450 
2451 bailout:
2452 	/*
2453 	 * Release the reference that was held when this task was enqueued.
2454 	 */
2455 	cam_periph_release(periph);
2456 }
2457 
2458 static cam_status
2459 saregister(struct cam_periph *periph, void *arg)
2460 {
2461 	struct sa_softc *softc;
2462 	struct ccb_getdev *cgd;
2463 	struct ccb_pathinq cpi;
2464 	struct make_dev_args args;
2465 	caddr_t match;
2466 	char tmpstr[80];
2467 	int error;
2468 	int i;
2469 
2470 	cgd = (struct ccb_getdev *)arg;
2471 	if (cgd == NULL) {
2472 		printf("saregister: no getdev CCB, can't register device\n");
2473 		return (CAM_REQ_CMP_ERR);
2474 	}
2475 
2476 	softc = (struct sa_softc *)
2477 	    malloc(sizeof (*softc), M_SCSISA, M_NOWAIT | M_ZERO);
2478 	if (softc == NULL) {
2479 		printf("saregister: Unable to probe new device. "
2480 		       "Unable to allocate softc\n");
2481 		return (CAM_REQ_CMP_ERR);
2482 	}
2483 	softc->scsi_rev = SID_ANSI_REV(&cgd->inq_data);
2484 	softc->state = SA_STATE_NORMAL;
2485 	softc->fileno = (daddr_t) -1;
2486 	softc->blkno = (daddr_t) -1;
2487 	softc->rep_fileno = (daddr_t) -1;
2488 	softc->rep_blkno = (daddr_t) -1;
2489 	softc->partition = (daddr_t) -1;
2490 	softc->bop = -1;
2491 	softc->eop = -1;
2492 	softc->bpew = -1;
2493 
2494 	bioq_init(&softc->bio_queue);
2495 	softc->periph = periph;
2496 	periph->softc = softc;
2497 
2498 	/*
2499 	 * See if this device has any quirks.
2500 	 */
2501 	match = cam_quirkmatch((caddr_t)&cgd->inq_data,
2502 			       (caddr_t)sa_quirk_table,
2503 			       nitems(sa_quirk_table),
2504 			       sizeof(*sa_quirk_table), scsi_inquiry_match);
2505 
2506 	if (match != NULL) {
2507 		softc->quirks = ((struct sa_quirk_entry *)match)->quirks;
2508 		softc->last_media_blksize =
2509 		    ((struct sa_quirk_entry *)match)->prefblk;
2510 	} else
2511 		softc->quirks = SA_QUIRK_NONE;
2512 
2513 
2514 	/*
2515 	 * Initialize the default timeouts.  If this drive supports
2516 	 * timeout descriptors we'll overwrite these values with the
2517 	 * recommended timeouts from the drive.
2518 	 */
2519 	for (i = 0; i < SA_TIMEOUT_TYPE_MAX; i++)
2520 		softc->timeout_info[i] = sa_default_timeouts[i].value;
2521 
2522 	/*
2523 	 * Long format data for READ POSITION was introduced in SSC, which
2524 	 * was after SCSI-2.  (Roughly equivalent to SCSI-3.)  If the drive
2525 	 * reports that it is SCSI-2 or older, it is unlikely to support
2526 	 * long position data, but it might.  Some drives from that era
2527 	 * claim to be SCSI-2, but do support long position information.
2528 	 * So, instead of immediately disabling long position information
2529 	 * for SCSI-2 devices, we'll try one pass through sagetpos(), and
2530 	 * then disable long position information if we get an error.
2531 	 */
2532 	if (cgd->inq_data.version <= SCSI_REV_CCS)
2533 		softc->quirks |= SA_QUIRK_NO_LONG_POS;
2534 
2535 	/*
2536 	 * The SCSI REPORT SUPPORTED OPERATION CODES command was added in
2537 	 * SPC-4.  That command optionally includes timeout data for
2538 	 * different commands.  Timeout values can vary wildly among
2539 	 * different drives, so if the drive itself has recommended values,
2540 	 * we will try to use them.  Set this flag to indicate we're going
2541 	 * to ask the drive for timeout data.  This flag also tells us to
2542 	 * wait on loading timeout tunables so we can properly override
2543 	 * timeouts with any user-specified values.
2544 	 */
2545 	if (SID_ANSI_REV(&cgd->inq_data) >= SCSI_REV_SPC4)
2546 		softc->flags |= SA_FLAG_RSOC_TO_TRY;
2547 
2548 	if (cgd->inq_data.spc3_flags & SPC3_SID_PROTECT) {
2549 		struct ccb_dev_advinfo cdai;
2550 		struct scsi_vpd_extended_inquiry_data ext_inq;
2551 
2552 		bzero(&ext_inq, sizeof(ext_inq));
2553 
2554 		memset(&cdai, 0, sizeof(cdai));
2555 		xpt_setup_ccb(&cdai.ccb_h, periph->path, CAM_PRIORITY_NORMAL);
2556 
2557 		cdai.ccb_h.func_code = XPT_DEV_ADVINFO;
2558 		cdai.flags = CDAI_FLAG_NONE;
2559 		cdai.buftype = CDAI_TYPE_EXT_INQ;
2560 		cdai.bufsiz = sizeof(ext_inq);
2561 		cdai.buf = (uint8_t *)&ext_inq;
2562 		xpt_action((union ccb *)&cdai);
2563 
2564 		if ((cdai.ccb_h.status & CAM_DEV_QFRZN) != 0)
2565 			cam_release_devq(cdai.ccb_h.path, 0, 0, 0, FALSE);
2566 		if ((cdai.ccb_h.status == CAM_REQ_CMP)
2567 		 && (ext_inq.flags1 & SVPD_EID_SA_SPT_LBP))
2568 			softc->flags |= SA_FLAG_PROTECT_SUPP;
2569 	}
2570 
2571 	xpt_path_inq(&cpi, periph->path);
2572 
2573 	/*
2574 	 * The SA driver supports a blocksize, but we don't know the
2575 	 * blocksize until we media is inserted.  So, set a flag to
2576 	 * indicate that the blocksize is unavailable right now.
2577 	 */
2578 	cam_periph_unlock(periph);
2579 	softc->device_stats = devstat_new_entry("sa", periph->unit_number, 0,
2580 	    DEVSTAT_BS_UNAVAILABLE, SID_TYPE(&cgd->inq_data) |
2581 	    XPORT_DEVSTAT_TYPE(cpi.transport), DEVSTAT_PRIORITY_TAPE);
2582 
2583 	/*
2584 	 * Load the default value that is either compiled in, or loaded
2585 	 * in the global kern.cam.sa.allow_io_split tunable.
2586 	 */
2587 	softc->allow_io_split = sa_allow_io_split;
2588 
2589 	/*
2590 	 * Load a per-instance tunable, if it exists.  NOTE that this
2591 	 * tunable WILL GO AWAY in FreeBSD 11.0.
2592 	 */
2593 	snprintf(tmpstr, sizeof(tmpstr), "kern.cam.sa.%u.allow_io_split",
2594 		 periph->unit_number);
2595 	TUNABLE_INT_FETCH(tmpstr, &softc->allow_io_split);
2596 
2597 	/*
2598 	 * If maxio isn't set, we fall back to DFLTPHYS.  Otherwise we take
2599 	 * the smaller of cpi.maxio or maxphys.
2600 	 */
2601 	if (cpi.maxio == 0)
2602 		softc->maxio = DFLTPHYS;
2603 	else if (cpi.maxio > maxphys)
2604 		softc->maxio = maxphys;
2605 	else
2606 		softc->maxio = cpi.maxio;
2607 
2608 	/*
2609 	 * Record the controller's maximum I/O size so we can report it to
2610 	 * the user later.
2611 	 */
2612 	softc->cpi_maxio = cpi.maxio;
2613 
2614 	/*
2615 	 * By default we tell physio that we do not want our I/O split.
2616 	 * The user needs to have a 1:1 mapping between the size of his
2617 	 * write to a tape character device and the size of the write
2618 	 * that actually goes down to the drive.
2619 	 */
2620 	if (softc->allow_io_split == 0)
2621 		softc->si_flags = SI_NOSPLIT;
2622 	else
2623 		softc->si_flags = 0;
2624 
2625 	TASK_INIT(&softc->sysctl_task, 0, sasysctlinit, periph);
2626 
2627 	/*
2628 	 * If the SIM supports unmapped I/O, let physio know that we can
2629 	 * handle unmapped buffers.
2630 	 */
2631 	if (cpi.hba_misc & PIM_UNMAPPED)
2632 		softc->si_flags |= SI_UNMAPPED;
2633 
2634 	/*
2635 	 * Acquire a reference to the periph before we create the devfs
2636 	 * instances for it.  We'll release this reference once the devfs
2637 	 * instances have been freed.
2638 	 */
2639 	if (cam_periph_acquire(periph) != 0) {
2640 		xpt_print(periph->path, "%s: lost periph during "
2641 			  "registration!\n", __func__);
2642 		cam_periph_lock(periph);
2643 		return (CAM_REQ_CMP_ERR);
2644 	}
2645 
2646 	make_dev_args_init(&args);
2647 	args.mda_devsw = &sa_cdevsw;
2648 	args.mda_si_drv1 = softc->periph;
2649 	args.mda_uid = UID_ROOT;
2650 	args.mda_gid = GID_OPERATOR;
2651 	args.mda_mode = 0660;
2652 
2653 	args.mda_unit = SAMINOR(SA_CTLDEV, SA_ATYPE_R);
2654 	error = make_dev_s(&args, &softc->devs.ctl_dev, "%s%d.ctl",
2655 	    periph->periph_name, periph->unit_number);
2656 	if (error != 0) {
2657 		cam_periph_lock(periph);
2658 		return (CAM_REQ_CMP_ERR);
2659 	}
2660 	sasetupdev(softc, softc->devs.ctl_dev);
2661 
2662 	args.mda_unit = SAMINOR(SA_NOT_CTLDEV, SA_ATYPE_R);
2663 	error = make_dev_s(&args, &softc->devs.r_dev, "%s%d",
2664 	    periph->periph_name, periph->unit_number);
2665 	if (error != 0) {
2666 		cam_periph_lock(periph);
2667 		return (CAM_REQ_CMP_ERR);
2668 	}
2669 	sasetupdev(softc, softc->devs.r_dev);
2670 
2671 	args.mda_unit = SAMINOR(SA_NOT_CTLDEV, SA_ATYPE_NR);
2672 	error = make_dev_s(&args, &softc->devs.nr_dev, "n%s%d",
2673 	    periph->periph_name, periph->unit_number);
2674 	if (error != 0) {
2675 		cam_periph_lock(periph);
2676 		return (CAM_REQ_CMP_ERR);
2677 	}
2678 	sasetupdev(softc, softc->devs.nr_dev);
2679 
2680 	args.mda_unit = SAMINOR(SA_NOT_CTLDEV, SA_ATYPE_ER);
2681 	error = make_dev_s(&args, &softc->devs.er_dev, "e%s%d",
2682 	    periph->periph_name, periph->unit_number);
2683 	if (error != 0) {
2684 		cam_periph_lock(periph);
2685 		return (CAM_REQ_CMP_ERR);
2686 	}
2687 	sasetupdev(softc, softc->devs.er_dev);
2688 
2689 	cam_periph_lock(periph);
2690 
2691 	softc->density_type_bits[0] = 0;
2692 	softc->density_type_bits[1] = SRDS_MEDIA;
2693 	softc->density_type_bits[2] = SRDS_MEDIUM_TYPE;
2694 	softc->density_type_bits[3] = SRDS_MEDIUM_TYPE | SRDS_MEDIA;
2695 	/*
2696 	 * Bump the peripheral refcount for the sysctl thread, in case we
2697 	 * get invalidated before the thread has a chance to run.  Note
2698 	 * that this runs in parallel with the probe for the timeout
2699 	 * values.
2700 	 */
2701 	cam_periph_acquire(periph);
2702 	taskqueue_enqueue(taskqueue_thread, &softc->sysctl_task);
2703 
2704 	/*
2705 	 * Add an async callback so that we get
2706 	 * notified if this device goes away.
2707 	 */
2708 	xpt_register_async(AC_LOST_DEVICE, saasync, periph, periph->path);
2709 
2710 	/*
2711 	 * See comment above, try fetching timeout values for drives that
2712 	 * might support it.  Otherwise, use the defaults.
2713 	 *
2714 	 * We get timeouts from the following places in order of increasing
2715 	 * priority:
2716 	 * 1. Driver default timeouts.
2717 	 * 2. Timeouts loaded from the drive via REPORT SUPPORTED OPERATION
2718 	 *    CODES. (We kick that off here if SA_FLAG_RSOC_TO_TRY is set.)
2719 	 * 3. Global loader tunables, used for all sa(4) driver instances on
2720 	 *    a machine.
2721 	 * 4. Instance-specific loader tunables, used for say sa5.
2722 	 * 5. On the fly user sysctl changes.
2723 	 *
2724 	 * Each step will overwrite the timeout value set from the one
2725 	 * before, so you go from general to most specific.
2726 	 */
2727 	if (softc->flags & SA_FLAG_RSOC_TO_TRY) {
2728 		/*
2729 		 * Bump the peripheral refcount while we are probing.
2730 		 */
2731 		cam_periph_acquire(periph);
2732 		softc->state = SA_STATE_PROBE;
2733 		xpt_schedule(periph, CAM_PRIORITY_DEV);
2734 	} else {
2735 		/*
2736 		 * This drive doesn't support Report Supported Operation
2737 		 * Codes, so we load the tunables at this point to bring
2738 		 * in any user preferences.
2739 		 */
2740 		saloadtotunables(softc);
2741 
2742 		xpt_announce_periph(periph, NULL);
2743 		xpt_announce_quirks(periph, softc->quirks, SA_QUIRK_BIT_STRING);
2744 	}
2745 
2746 	return (CAM_REQ_CMP);
2747 }
2748 
2749 static void
2750 sastart(struct cam_periph *periph, union ccb *start_ccb)
2751 {
2752 	struct sa_softc *softc;
2753 
2754 	softc = (struct sa_softc *)periph->softc;
2755 
2756 	CAM_DEBUG(periph->path, CAM_DEBUG_TRACE, ("sastart\n"));
2757 
2758 	switch (softc->state) {
2759 	case SA_STATE_NORMAL:
2760 	{
2761 		/* Pull a buffer from the queue and get going on it */
2762 		struct bio *bp;
2763 
2764 		/*
2765 		 * See if there is a buf with work for us to do..
2766 		 */
2767 		bp = bioq_first(&softc->bio_queue);
2768 		if (bp == NULL) {
2769 			xpt_release_ccb(start_ccb);
2770 		} else if (((softc->flags & SA_FLAG_ERR_PENDING) != 0)
2771 			|| (softc->inject_eom != 0)) {
2772 			struct bio *done_bp;
2773 
2774 			if (softc->inject_eom != 0) {
2775 				softc->flags |= SA_FLAG_EOM_PENDING;
2776 				softc->inject_eom = 0;
2777 				/*
2778 				 * If we're injecting EOM for writes, we
2779 				 * need to keep PEWS set for 3 queries
2780 				 * to cover 2 position requests from the
2781 				 * kernel via sagetpos(), and then allow
2782 				 * for one for the user to see the BPEW
2783 				 * flag (e.g. via mt status).  After that,
2784 				 * it will be cleared.
2785 				 */
2786 				if (bp->bio_cmd == BIO_WRITE)
2787 					softc->set_pews_status = 3;
2788 				else
2789 					softc->set_pews_status = 1;
2790 			}
2791 again:
2792 			softc->queue_count--;
2793 			bioq_remove(&softc->bio_queue, bp);
2794 			bp->bio_resid = bp->bio_bcount;
2795 			done_bp = bp;
2796 			if ((softc->flags & SA_FLAG_EOM_PENDING) != 0) {
2797 				/*
2798 				 * We have two different behaviors for
2799 				 * writes when we hit either Early Warning
2800 				 * or the PEWZ (Programmable Early Warning
2801 				 * Zone).  The default behavior is that
2802 				 * for all writes that are currently
2803 				 * queued after the write where we saw the
2804 				 * early warning, we will return the write
2805 				 * with the residual equal to the count.
2806 				 * i.e. tell the application that 0 bytes
2807 				 * were written.
2808 				 *
2809 				 * The alternate behavior, which is enabled
2810 				 * when eot_warn is set, is that in
2811 				 * addition to setting the residual equal
2812 				 * to the count, we will set the error
2813 				 * to ENOSPC.
2814 				 *
2815 				 * In either case, once queued writes are
2816 				 * cleared out, we clear the error flag
2817 				 * (see below) and the application is free to
2818 				 * attempt to write more.
2819 				 */
2820 				if (softc->eot_warn != 0) {
2821 					bp->bio_flags |= BIO_ERROR;
2822 					bp->bio_error = ENOSPC;
2823 				} else
2824 					bp->bio_error = 0;
2825 			} else if ((softc->flags & SA_FLAG_EOF_PENDING) != 0) {
2826 				/*
2827 				 * This can only happen if we're reading
2828 				 * in fixed length mode. In this case,
2829 				 * we dump the rest of the list the
2830 				 * same way.
2831 				 */
2832 				bp->bio_error = 0;
2833 				if (bioq_first(&softc->bio_queue) != NULL) {
2834 					biodone(done_bp);
2835 					goto again;
2836 				}
2837 			} else if ((softc->flags & SA_FLAG_EIO_PENDING) != 0) {
2838 				bp->bio_error = EIO;
2839 				bp->bio_flags |= BIO_ERROR;
2840 			}
2841 			bp = bioq_first(&softc->bio_queue);
2842 			/*
2843 			 * Only if we have no other buffers queued up
2844 			 * do we clear the pending error flag.
2845 			 */
2846 			if (bp == NULL)
2847 				softc->flags &= ~SA_FLAG_ERR_PENDING;
2848 			CAM_DEBUG(periph->path, CAM_DEBUG_INFO,
2849 			    ("sastart- ERR_PENDING now 0x%x, bp is %sNULL, "
2850 			    "%d more buffers queued up\n",
2851 			    (softc->flags & SA_FLAG_ERR_PENDING),
2852 			    (bp != NULL)? "not " : " ", softc->queue_count));
2853 			xpt_release_ccb(start_ccb);
2854 			biodone(done_bp);
2855 		} else {
2856 			uint32_t length;
2857 
2858 			bioq_remove(&softc->bio_queue, bp);
2859 			softc->queue_count--;
2860 
2861 			if ((bp->bio_cmd != BIO_READ) &&
2862 			    (bp->bio_cmd != BIO_WRITE)) {
2863 				biofinish(bp, NULL, EOPNOTSUPP);
2864 				xpt_release_ccb(start_ccb);
2865 				return;
2866 			}
2867 			length = bp->bio_bcount;
2868 
2869 			if ((softc->flags & SA_FLAG_FIXED) != 0) {
2870 				if (softc->blk_shift != 0) {
2871 					length = length >> softc->blk_shift;
2872 				} else if (softc->media_blksize != 0) {
2873 					length = length / softc->media_blksize;
2874 				} else {
2875 					bp->bio_error = EIO;
2876 					xpt_print(periph->path, "zero blocksize"
2877 					    " for FIXED length writes?\n");
2878 					biodone(bp);
2879 					break;
2880 				}
2881 #if	0
2882 				CAM_DEBUG(start_ccb->ccb_h.path, CAM_DEBUG_INFO,
2883 				    ("issuing a %d fixed record %s\n",
2884 				    length,  (bp->bio_cmd == BIO_READ)? "read" :
2885 				    "write"));
2886 #endif
2887 			} else {
2888 #if	0
2889 				CAM_DEBUG(start_ccb->ccb_h.path, CAM_DEBUG_INFO,
2890 				    ("issuing a %d variable byte %s\n",
2891 				    length,  (bp->bio_cmd == BIO_READ)? "read" :
2892 				    "write"));
2893 #endif
2894 			}
2895 			devstat_start_transaction_bio(softc->device_stats, bp);
2896 			/*
2897 			 * Some people have theorized that we should
2898 			 * suppress illegal length indication if we are
2899 			 * running in variable block mode so that we don't
2900 			 * have to request sense every time our requested
2901 			 * block size is larger than the written block.
2902 			 * The residual information from the ccb allows
2903 			 * us to identify this situation anyway.  The only
2904 			 * problem with this is that we will not get
2905 			 * information about blocks that are larger than
2906 			 * our read buffer unless we set the block size
2907 			 * in the mode page to something other than 0.
2908 			 *
2909 			 * I believe that this is a non-issue. If user apps
2910 			 * don't adjust their read size to match our record
2911 			 * size, that's just life. Anyway, the typical usage
2912 			 * would be to issue, e.g., 64KB reads and occasionally
2913 			 * have to do deal with 512 byte or 1KB intermediate
2914 			 * records.
2915 			 *
2916 			 * That said, though, we now support setting the
2917 			 * SILI bit on reads, and we set the blocksize to 4
2918 			 * bytes when we do that.  This gives us
2919 			 * compatibility with software that wants this,
2920 			 * although the only real difference between that
2921 			 * and not setting the SILI bit on reads is that we
2922 			 * won't get a check condition on reads where our
2923 			 * request size is larger than the block on tape.
2924 			 * That probably only makes a real difference in
2925 			 * non-packetized SCSI, where you have to go back
2926 			 * to the drive to request sense and thus incur
2927 			 * more latency.
2928 			 */
2929 			softc->dsreg = (bp->bio_cmd == BIO_READ)?
2930 			    MTIO_DSREG_RD : MTIO_DSREG_WR;
2931 			scsi_sa_read_write(&start_ccb->csio, 0, sadone,
2932 			    MSG_SIMPLE_Q_TAG, (bp->bio_cmd == BIO_READ ?
2933 			    SCSI_RW_READ : SCSI_RW_WRITE) |
2934 			    ((bp->bio_flags & BIO_UNMAPPED) != 0 ?
2935 			    SCSI_RW_BIO : 0), softc->sili,
2936 			    (softc->flags & SA_FLAG_FIXED) != 0, length,
2937 			    (bp->bio_flags & BIO_UNMAPPED) != 0 ? (void *)bp :
2938 			    bp->bio_data, bp->bio_bcount, SSD_FULL_SIZE,
2939 			    (bp->bio_cmd == BIO_READ) ?
2940 			    softc->timeout_info[SA_TIMEOUT_READ] :
2941 			    softc->timeout_info[SA_TIMEOUT_WRITE]);
2942 			start_ccb->ccb_h.ccb_pflags &= ~SA_POSITION_UPDATED;
2943 			start_ccb->ccb_h.ccb_bp = bp;
2944 			bp = bioq_first(&softc->bio_queue);
2945 			xpt_action(start_ccb);
2946 		}
2947 
2948 		if (bp != NULL) {
2949 			/* Have more work to do, so ensure we stay scheduled */
2950 			xpt_schedule(periph, CAM_PRIORITY_NORMAL);
2951 		}
2952 		break;
2953 	}
2954 	case SA_STATE_PROBE: {
2955 		int num_opcodes;
2956 		size_t alloc_len;
2957 		uint8_t *params;
2958 
2959 		/*
2960 		 * This is an arbitrary number.  An IBM LTO-6 drive reports
2961 		 * 67 entries, and an IBM LTO-9 drive reports 71 entries.
2962 		 * There can theoretically be more than 256 because
2963 		 * service actions of a particular opcode are reported
2964 		 * separately, but we're far enough ahead of the practical
2965 		 * number here that we don't need to implement logic to
2966 		 * retry if we don't get all the timeout descriptors.
2967 		 */
2968 		num_opcodes = 256;
2969 
2970 		alloc_len = num_opcodes *
2971 		    (sizeof(struct scsi_report_supported_opcodes_descr) +
2972 		     sizeof(struct scsi_report_supported_opcodes_timeout));
2973 
2974 		params = malloc(alloc_len, M_SCSISA, M_NOWAIT| M_ZERO);
2975 		if (params == NULL) {
2976 			/*
2977 			 * If this happens, go with default
2978 			 * timeouts and announce the drive.
2979 			 */
2980 			saloadtotunables(softc);
2981 
2982 			softc->state = SA_STATE_NORMAL;
2983 
2984 			xpt_announce_periph(periph, NULL);
2985 			xpt_announce_quirks(periph, softc->quirks,
2986 					    SA_QUIRK_BIT_STRING);
2987 			xpt_release_ccb(start_ccb);
2988 			cam_periph_release_locked(periph);
2989 			return;
2990 		}
2991 
2992 		scsi_report_supported_opcodes(&start_ccb->csio,
2993 		    /*retries*/ 3,
2994 		    /*cbfcnp*/ sadone,
2995 		    /*tag_action*/ MSG_SIMPLE_Q_TAG,
2996 		    /*options*/ RSO_RCTD,
2997 		    /*req_opcode*/ 0,
2998 		    /*req_service_action*/ 0,
2999 		    /*data_ptr*/ params,
3000 		    /*dxfer_len*/ alloc_len,
3001 		    /*sense_len*/ SSD_FULL_SIZE,
3002 		    /*timeout*/ softc->timeout_info[SA_TIMEOUT_TUR]);
3003 
3004 		xpt_action(start_ccb);
3005 		break;
3006 	}
3007 	case SA_STATE_ABNORMAL:
3008 	default:
3009 		panic("state 0x%x in sastart", softc->state);
3010 		break;
3011 	}
3012 }
3013 
3014 static void
3015 sadone(struct cam_periph *periph, union ccb *done_ccb)
3016 {
3017 	struct sa_softc *softc;
3018 	struct ccb_scsiio *csio;
3019 	struct bio *bp;
3020 	int error;
3021 
3022 	softc = (struct sa_softc *)periph->softc;
3023 	csio = &done_ccb->csio;
3024 	error = 0;
3025 
3026 	if (softc->state == SA_STATE_NORMAL) {
3027 		softc->dsreg = MTIO_DSREG_REST;
3028 		bp = (struct bio *)done_ccb->ccb_h.ccb_bp;
3029 
3030 		if ((done_ccb->ccb_h.status & CAM_STATUS_MASK) != CAM_REQ_CMP) {
3031 			if ((error = saerror(done_ccb, 0, 0)) == ERESTART) {
3032 				/*
3033 				 * A retry was scheduled, so just return.
3034 				 */
3035 				return;
3036 			}
3037 		}
3038 	} else if (softc->state == SA_STATE_PROBE) {
3039 		bp = NULL;
3040 		if ((done_ccb->ccb_h.status & CAM_STATUS_MASK) != CAM_REQ_CMP) {
3041 			/*
3042 			 * Note that on probe, we just run through
3043 			 * cam_periph_error(), since saerror() has a lot of
3044 			 * special handling for I/O errors.  We don't need
3045 			 * that to get the opcodes.  We either succeed
3046 			 * after a retry or two, or give up.  We don't
3047 			 * print sense, we don't need to worry the user if
3048 			 * this drive doesn't support timeout descriptors.
3049 			 */
3050 			if ((error = cam_periph_error(done_ccb, 0,
3051 			     SF_NO_PRINT)) == ERESTART) {
3052 				/*
3053 				 * A retry was scheduled, so just return.
3054 				 */
3055 				return;
3056 			} else if (error != 0) {
3057 				/* We failed to get opcodes.  Give up. */
3058 
3059 				saloadtotunables(softc);
3060 
3061 				softc->state = SA_STATE_NORMAL;
3062 
3063 				xpt_release_ccb(done_ccb);
3064 
3065 				xpt_announce_periph(periph, NULL);
3066 				xpt_announce_quirks(periph, softc->quirks,
3067 						    SA_QUIRK_BIT_STRING);
3068 				cam_periph_release_locked(periph);
3069 				return;
3070 			}
3071 		}
3072 		/*
3073 		 * At this point, we have succeeded, so load the timeouts
3074 		 * and go into the normal state.
3075 		 */
3076 		softc->state = SA_STATE_NORMAL;
3077 
3078 		/*
3079 		 * First, load the timeouts we got from the drive.
3080 		 */
3081 		saloadtimeouts(softc, done_ccb);
3082 
3083 		/*
3084 		 * Next, overwrite the timeouts from the drive with any
3085 		 * loader tunables that the user set.
3086 		 */
3087 		saloadtotunables(softc);
3088 
3089 		xpt_release_ccb(done_ccb);
3090 		xpt_announce_periph(periph, NULL);
3091 		xpt_announce_quirks(periph, softc->quirks,
3092 				    SA_QUIRK_BIT_STRING);
3093 		cam_periph_release_locked(periph);
3094 		return;
3095 	} else {
3096 		panic("state 0x%x in sadone", softc->state);
3097 	}
3098 
3099 	if (error == EIO) {
3100 		/*
3101 		 * Catastrophic error. Mark the tape as frozen
3102 		 * (we no longer know tape position).
3103 		 *
3104 		 * Return all queued I/O with EIO, and unfreeze
3105 		 * our queue so that future transactions that
3106 		 * attempt to fix this problem can get to the
3107 		 * device.
3108 		 *
3109 		 */
3110 
3111 		softc->flags |= SA_FLAG_TAPE_FROZEN;
3112 		bioq_flush(&softc->bio_queue, NULL, EIO);
3113 	}
3114 	if (error != 0) {
3115 		bp->bio_resid = bp->bio_bcount;
3116 		bp->bio_error = error;
3117 		bp->bio_flags |= BIO_ERROR;
3118 		/*
3119 		 * In the error case, position is updated in saerror.
3120 		 */
3121 	} else {
3122 		bp->bio_resid = csio->resid;
3123 		bp->bio_error = 0;
3124 		if (csio->resid != 0) {
3125 			bp->bio_flags |= BIO_ERROR;
3126 		}
3127 		if (bp->bio_cmd == BIO_WRITE) {
3128 			softc->flags |= SA_FLAG_TAPE_WRITTEN;
3129 			softc->filemarks = 0;
3130 		}
3131 		if (!(csio->ccb_h.ccb_pflags & SA_POSITION_UPDATED) &&
3132 		    (softc->blkno != (daddr_t) -1)) {
3133 			if ((softc->flags & SA_FLAG_FIXED) != 0) {
3134 				uint32_t l;
3135 				if (softc->blk_shift != 0) {
3136 					l = bp->bio_bcount >>
3137 						softc->blk_shift;
3138 				} else {
3139 					l = bp->bio_bcount /
3140 						softc->media_blksize;
3141 				}
3142 				softc->blkno += (daddr_t) l;
3143 			} else {
3144 				softc->blkno++;
3145 			}
3146 		}
3147 	}
3148 	/*
3149 	 * If we had an error (immediate or pending),
3150 	 * release the device queue now.
3151 	 */
3152 	if (error || (softc->flags & SA_FLAG_ERR_PENDING))
3153 		cam_release_devq(done_ccb->ccb_h.path, 0, 0, 0, 0);
3154 	if (error || bp->bio_resid) {
3155 		CAM_DEBUG(periph->path, CAM_DEBUG_INFO,
3156 		    	  ("error %d resid %ld count %ld\n", error,
3157 			  bp->bio_resid, bp->bio_bcount));
3158 	}
3159 	biofinish(bp, softc->device_stats, 0);
3160 	xpt_release_ccb(done_ccb);
3161 }
3162 
3163 /*
3164  * Mount the tape (make sure it's ready for I/O).
3165  */
3166 static int
3167 samount(struct cam_periph *periph, int oflags, struct cdev *dev)
3168 {
3169 	struct	sa_softc *softc;
3170 	union	ccb *ccb;
3171 	int	error;
3172 
3173 	/*
3174 	 * oflags can be checked for 'kind' of open (read-only check) - later
3175 	 * dev can be checked for a control-mode or compression open - later
3176 	 */
3177 	UNUSED_PARAMETER(oflags);
3178 	UNUSED_PARAMETER(dev);
3179 
3180 	softc = (struct sa_softc *)periph->softc;
3181 
3182 	/*
3183 	 * This should determine if something has happened since the last
3184 	 * open/mount that would invalidate the mount. We do *not* want
3185 	 * to retry this command- we just want the status. But we only
3186 	 * do this if we're mounted already- if we're not mounted,
3187 	 * we don't care about the unit read state and can instead use
3188 	 * this opportunity to attempt to reserve the tape unit.
3189 	 */
3190 
3191 	if (softc->flags & SA_FLAG_TAPE_MOUNTED) {
3192 		ccb = cam_periph_getccb(periph, 1);
3193 		scsi_test_unit_ready(&ccb->csio, 0, NULL,
3194 		    MSG_SIMPLE_Q_TAG, SSD_FULL_SIZE,
3195 		    softc->timeout_info[SA_TIMEOUT_TUR]);
3196 		error = cam_periph_runccb(ccb, saerror, 0, SF_NO_PRINT,
3197 		    softc->device_stats);
3198 		if (error == ENXIO) {
3199 			softc->flags &= ~SA_FLAG_TAPE_MOUNTED;
3200 			scsi_test_unit_ready(&ccb->csio, 0, NULL,
3201 			    MSG_SIMPLE_Q_TAG, SSD_FULL_SIZE,
3202 			    softc->timeout_info[SA_TIMEOUT_TUR]);
3203 			error = cam_periph_runccb(ccb, saerror, 0, SF_NO_PRINT,
3204 			    softc->device_stats);
3205 		} else if (error) {
3206 			/*
3207 			 * We don't need to freeze the tape because we
3208 			 * will now attempt to rewind/load it.
3209 			 */
3210 			softc->flags &= ~SA_FLAG_TAPE_MOUNTED;
3211 			if (CAM_DEBUGGED(periph->path, CAM_DEBUG_INFO)) {
3212 				xpt_print(periph->path,
3213 				    "error %d on TUR in samount\n", error);
3214 			}
3215 		}
3216 	} else {
3217 		error = sareservereleaseunit(periph, TRUE);
3218 		if (error) {
3219 			return (error);
3220 		}
3221 		ccb = cam_periph_getccb(periph, 1);
3222 		scsi_test_unit_ready(&ccb->csio, 0, NULL,
3223 		    MSG_SIMPLE_Q_TAG, SSD_FULL_SIZE,
3224 		    softc->timeout_info[SA_TIMEOUT_TUR]);
3225 		error = cam_periph_runccb(ccb, saerror, 0, SF_NO_PRINT,
3226 		    softc->device_stats);
3227 	}
3228 
3229 	if ((softc->flags & SA_FLAG_TAPE_MOUNTED) == 0) {
3230 		struct scsi_read_block_limits_data *rblim = NULL;
3231 		int comp_enabled, comp_supported;
3232 		uint8_t write_protect, guessing = 0;
3233 
3234 		/*
3235 		 * Clear out old state.
3236 		 */
3237 		softc->flags &= ~(SA_FLAG_TAPE_WP|SA_FLAG_TAPE_WRITTEN|
3238 				  SA_FLAG_ERR_PENDING|SA_FLAG_COMPRESSION);
3239 		softc->filemarks = 0;
3240 
3241 		/*
3242 		 * *Very* first off, make sure we're loaded to BOT.
3243 		 */
3244 		scsi_load_unload(&ccb->csio, 2, NULL, MSG_SIMPLE_Q_TAG, FALSE,
3245 		    FALSE, FALSE, 1, SSD_FULL_SIZE,
3246 		    softc->timeout_info[SA_TIMEOUT_LOAD]);
3247 		error = cam_periph_runccb(ccb, saerror, 0, SF_NO_PRINT,
3248 		    softc->device_stats);
3249 
3250 		/*
3251 		 * In case this doesn't work, do a REWIND instead
3252 		 */
3253 		if (error) {
3254 			scsi_rewind(&ccb->csio, 2, NULL, MSG_SIMPLE_Q_TAG,
3255 			    FALSE, SSD_FULL_SIZE,
3256 			    softc->timeout_info[SA_TIMEOUT_REWIND]);
3257 			error = cam_periph_runccb(ccb, saerror, 0, SF_NO_PRINT,
3258 				softc->device_stats);
3259 		}
3260 		if (error) {
3261 			xpt_release_ccb(ccb);
3262 			goto exit;
3263 		}
3264 
3265 		/*
3266 		 * Do a dummy test read to force access to the
3267 		 * media so that the drive will really know what's
3268 		 * there. We actually don't really care what the
3269 		 * blocksize on tape is and don't expect to really
3270 		 * read a full record.
3271 		 */
3272 		rblim = (struct  scsi_read_block_limits_data *)
3273 		    malloc(8192, M_SCSISA, M_NOWAIT);
3274 		if (rblim == NULL) {
3275 			xpt_print(periph->path, "no memory for test read\n");
3276 			xpt_release_ccb(ccb);
3277 			error = ENOMEM;
3278 			goto exit;
3279 		}
3280 
3281 		if ((softc->quirks & SA_QUIRK_NODREAD) == 0) {
3282 			scsi_sa_read_write(&ccb->csio, 0, NULL,
3283 			    MSG_SIMPLE_Q_TAG, 1, FALSE, 0, 8192,
3284 			    (void *) rblim, 8192, SSD_FULL_SIZE,
3285 			    softc->timeout_info[SA_TIMEOUT_READ]);
3286 			(void) cam_periph_runccb(ccb, saerror, 0, SF_NO_PRINT,
3287 			    softc->device_stats);
3288 			scsi_rewind(&ccb->csio, 1, NULL, MSG_SIMPLE_Q_TAG,
3289 			    FALSE, SSD_FULL_SIZE,
3290 			    softc->timeout_info[SA_TIMEOUT_REWIND]);
3291 			error = cam_periph_runccb(ccb, saerror, CAM_RETRY_SELTO,
3292 			    SF_NO_PRINT | SF_RETRY_UA,
3293 			    softc->device_stats);
3294 			if (error) {
3295 				xpt_print(periph->path,
3296 				    "unable to rewind after test read\n");
3297 				xpt_release_ccb(ccb);
3298 				goto exit;
3299 			}
3300 		}
3301 
3302 		/*
3303 		 * Next off, determine block limits.
3304 		 */
3305 		scsi_read_block_limits(&ccb->csio, 5, NULL, MSG_SIMPLE_Q_TAG,
3306 		    rblim, SSD_FULL_SIZE,
3307 		    softc->timeout_info[SA_TIMEOUT_READ_BLOCK_LIMITS]);
3308 
3309 		error = cam_periph_runccb(ccb, saerror, CAM_RETRY_SELTO,
3310 		    SF_NO_PRINT | SF_RETRY_UA, softc->device_stats);
3311 
3312 		xpt_release_ccb(ccb);
3313 
3314 		if (error != 0) {
3315 			/*
3316 			 * If it's less than SCSI-2, READ BLOCK LIMITS is not
3317 			 * a MANDATORY command. Anyway- it doesn't matter-
3318 			 * we can proceed anyway.
3319 			 */
3320 			softc->blk_gran = 0;
3321 			softc->max_blk = ~0;
3322 			softc->min_blk = 0;
3323 		} else {
3324 			if (softc->scsi_rev >= SCSI_REV_SPC) {
3325 				softc->blk_gran = RBL_GRAN(rblim);
3326 			} else {
3327 				softc->blk_gran = 0;
3328 			}
3329 			/*
3330 			 * We take max_blk == min_blk to mean a default to
3331 			 * fixed mode- but note that whatever we get out of
3332 			 * sagetparams below will actually determine whether
3333 			 * we are actually *in* fixed mode.
3334 			 */
3335 			softc->max_blk = scsi_3btoul(rblim->maximum);
3336 			softc->min_blk = scsi_2btoul(rblim->minimum);
3337 		}
3338 		/*
3339 		 * Next, perform a mode sense to determine
3340 		 * current density, blocksize, compression etc.
3341 		 */
3342 		error = sagetparams(periph, SA_PARAM_ALL,
3343 				    &softc->media_blksize,
3344 				    &softc->media_density,
3345 				    &softc->media_numblks,
3346 				    &softc->buffer_mode, &write_protect,
3347 				    &softc->speed, &comp_supported,
3348 				    &comp_enabled, &softc->comp_algorithm,
3349 				    NULL, NULL, 0, 0);
3350 
3351 		if (error != 0) {
3352 			/*
3353 			 * We could work a little harder here. We could
3354 			 * adjust our attempts to get information. It
3355 			 * might be an ancient tape drive. If someone
3356 			 * nudges us, we'll do that.
3357 			 */
3358 			goto exit;
3359 		}
3360 
3361 		/*
3362 		 * If no quirk has determined that this is a device that is
3363 		 * preferred to be in fixed or variable mode, now is the time
3364 		 * to find out.
3365 	 	 */
3366 		if ((softc->quirks & (SA_QUIRK_FIXED|SA_QUIRK_VARIABLE)) == 0) {
3367 			guessing = 1;
3368 			/*
3369 			 * This could be expensive to find out. Luckily we
3370 			 * only need to do this once. If we start out in
3371 			 * 'default' mode, try and set ourselves to one
3372 			 * of the densities that would determine a wad
3373 			 * of other stuff. Go from highest to lowest.
3374 			 */
3375 			if (softc->media_density == SCSI_DEFAULT_DENSITY) {
3376 				int i;
3377 				static uint8_t ctry[] = {
3378 					SCSI_DENSITY_HALFINCH_PE,
3379 					SCSI_DENSITY_HALFINCH_6250C,
3380 					SCSI_DENSITY_HALFINCH_6250,
3381 					SCSI_DENSITY_HALFINCH_1600,
3382 					SCSI_DENSITY_HALFINCH_800,
3383 					SCSI_DENSITY_QIC_4GB,
3384 					SCSI_DENSITY_QIC_2GB,
3385 					SCSI_DENSITY_QIC_525_320,
3386 					SCSI_DENSITY_QIC_150,
3387 					SCSI_DENSITY_QIC_120,
3388 					SCSI_DENSITY_QIC_24,
3389 					SCSI_DENSITY_QIC_11_9TRK,
3390 					SCSI_DENSITY_QIC_11_4TRK,
3391 					SCSI_DENSITY_QIC_1320,
3392 					SCSI_DENSITY_QIC_3080,
3393 					0
3394 				};
3395 				for (i = 0; ctry[i]; i++) {
3396 					error = sasetparams(periph,
3397 					    SA_PARAM_DENSITY, 0, ctry[i],
3398 					    0, SF_NO_PRINT);
3399 					if (error == 0) {
3400 						softc->media_density = ctry[i];
3401 						break;
3402 					}
3403 				}
3404 			}
3405 			switch (softc->media_density) {
3406 			case SCSI_DENSITY_QIC_11_4TRK:
3407 			case SCSI_DENSITY_QIC_11_9TRK:
3408 			case SCSI_DENSITY_QIC_24:
3409 			case SCSI_DENSITY_QIC_120:
3410 			case SCSI_DENSITY_QIC_150:
3411 			case SCSI_DENSITY_QIC_525_320:
3412 			case SCSI_DENSITY_QIC_1320:
3413 			case SCSI_DENSITY_QIC_3080:
3414 				softc->quirks &= ~SA_QUIRK_2FM;
3415 				softc->quirks |= SA_QUIRK_FIXED|SA_QUIRK_1FM;
3416 				softc->last_media_blksize = 512;
3417 				break;
3418 			case SCSI_DENSITY_QIC_4GB:
3419 			case SCSI_DENSITY_QIC_2GB:
3420 				softc->quirks &= ~SA_QUIRK_2FM;
3421 				softc->quirks |= SA_QUIRK_FIXED|SA_QUIRK_1FM;
3422 				softc->last_media_blksize = 1024;
3423 				break;
3424 			default:
3425 				softc->last_media_blksize =
3426 				    softc->media_blksize;
3427 				softc->quirks |= SA_QUIRK_VARIABLE;
3428 				break;
3429 			}
3430 		}
3431 
3432 		/*
3433 		 * If no quirk has determined that this is a device that needs
3434 		 * to have 2 Filemarks at EOD, now is the time to find out.
3435 		 */
3436 
3437 		if ((softc->quirks & SA_QUIRK_2FM) == 0) {
3438 			switch (softc->media_density) {
3439 			case SCSI_DENSITY_HALFINCH_800:
3440 			case SCSI_DENSITY_HALFINCH_1600:
3441 			case SCSI_DENSITY_HALFINCH_6250:
3442 			case SCSI_DENSITY_HALFINCH_6250C:
3443 			case SCSI_DENSITY_HALFINCH_PE:
3444 				softc->quirks &= ~SA_QUIRK_1FM;
3445 				softc->quirks |= SA_QUIRK_2FM;
3446 				break;
3447 			default:
3448 				break;
3449 			}
3450 		}
3451 
3452 		/*
3453 		 * Now validate that some info we got makes sense.
3454 		 */
3455 		if ((softc->max_blk < softc->media_blksize) ||
3456 		    (softc->min_blk > softc->media_blksize &&
3457 		    softc->media_blksize)) {
3458 			xpt_print(periph->path,
3459 			    "BLOCK LIMITS (%d..%d) could not match current "
3460 			    "block settings (%d)- adjusting\n", softc->min_blk,
3461 			    softc->max_blk, softc->media_blksize);
3462 			softc->max_blk = softc->min_blk =
3463 			    softc->media_blksize;
3464 		}
3465 
3466 		/*
3467 		 * Now put ourselves into the right frame of mind based
3468 		 * upon quirks...
3469 		 */
3470 tryagain:
3471 		/*
3472 		 * If we want to be in FIXED mode and our current blocksize
3473 		 * is not equal to our last blocksize (if nonzero), try and
3474 		 * set ourselves to this last blocksize (as the 'preferred'
3475 		 * block size).  The initial quirkmatch at registry sets the
3476 		 * initial 'last' blocksize. If, for whatever reason, this
3477 		 * 'last' blocksize is zero, set the blocksize to 512,
3478 		 * or min_blk if that's larger.
3479 		 */
3480 		if ((softc->quirks & SA_QUIRK_FIXED) &&
3481 		    (softc->quirks & SA_QUIRK_NO_MODESEL) == 0 &&
3482 		    (softc->media_blksize != softc->last_media_blksize)) {
3483 			softc->media_blksize = softc->last_media_blksize;
3484 			if (softc->media_blksize == 0) {
3485 				softc->media_blksize = 512;
3486 				if (softc->media_blksize < softc->min_blk) {
3487 					softc->media_blksize = softc->min_blk;
3488 				}
3489 			}
3490 			error = sasetparams(periph, SA_PARAM_BLOCKSIZE,
3491 			    softc->media_blksize, 0, 0, SF_NO_PRINT);
3492 			if (error) {
3493 				xpt_print(periph->path,
3494 				    "unable to set fixed blocksize to %d\n",
3495 				    softc->media_blksize);
3496 				goto exit;
3497 			}
3498 		}
3499 
3500 		if ((softc->quirks & SA_QUIRK_VARIABLE) &&
3501 		    (softc->media_blksize != 0)) {
3502 			softc->last_media_blksize = softc->media_blksize;
3503 			softc->media_blksize = 0;
3504 			error = sasetparams(periph, SA_PARAM_BLOCKSIZE,
3505 			    0, 0, 0, SF_NO_PRINT);
3506 			if (error) {
3507 				/*
3508 				 * If this fails and we were guessing, just
3509 				 * assume that we got it wrong and go try
3510 				 * fixed block mode. Don't even check against
3511 				 * density code at this point.
3512 				 */
3513 				if (guessing) {
3514 					softc->quirks &= ~SA_QUIRK_VARIABLE;
3515 					softc->quirks |= SA_QUIRK_FIXED;
3516 					if (softc->last_media_blksize == 0)
3517 						softc->last_media_blksize = 512;
3518 					goto tryagain;
3519 				}
3520 				xpt_print(periph->path,
3521 				    "unable to set variable blocksize\n");
3522 				goto exit;
3523 			}
3524 		}
3525 
3526 		/*
3527 		 * Now that we have the current block size,
3528 		 * set up some parameters for sastart's usage.
3529 		 */
3530 		if (softc->media_blksize) {
3531 			softc->flags |= SA_FLAG_FIXED;
3532 			if (powerof2(softc->media_blksize)) {
3533 				softc->blk_shift =
3534 				    ffs(softc->media_blksize) - 1;
3535 				softc->blk_mask = softc->media_blksize - 1;
3536 			} else {
3537 				softc->blk_mask = ~0;
3538 				softc->blk_shift = 0;
3539 			}
3540 		} else {
3541 			/*
3542 			 * The SCSI-3 spec allows 0 to mean "unspecified".
3543 			 * The SCSI-1 spec allows 0 to mean 'infinite'.
3544 			 *
3545 			 * Either works here.
3546 			 */
3547 			if (softc->max_blk == 0) {
3548 				softc->max_blk = ~0;
3549 			}
3550 			softc->blk_shift = 0;
3551 			if (softc->blk_gran != 0) {
3552 				softc->blk_mask = softc->blk_gran - 1;
3553 			} else {
3554 				softc->blk_mask = 0;
3555 			}
3556 		}
3557 
3558 		if (write_protect)
3559 			softc->flags |= SA_FLAG_TAPE_WP;
3560 
3561 		if (comp_supported) {
3562 			if (softc->saved_comp_algorithm == 0)
3563 				softc->saved_comp_algorithm =
3564 				    softc->comp_algorithm;
3565 			softc->flags |= SA_FLAG_COMP_SUPP;
3566 			if (comp_enabled)
3567 				softc->flags |= SA_FLAG_COMP_ENABLED;
3568 		} else
3569 			softc->flags |= SA_FLAG_COMP_UNSUPP;
3570 
3571 		if ((softc->buffer_mode == SMH_SA_BUF_MODE_NOBUF) &&
3572 		    (softc->quirks & SA_QUIRK_NO_MODESEL) == 0) {
3573 			error = sasetparams(periph, SA_PARAM_BUFF_MODE, 0,
3574 			    0, 0, SF_NO_PRINT);
3575 			if (error == 0) {
3576 				softc->buffer_mode = SMH_SA_BUF_MODE_SIBUF;
3577 			} else {
3578 				xpt_print(periph->path,
3579 				    "unable to set buffered mode\n");
3580 			}
3581 			error = 0;	/* not an error */
3582 		}
3583 
3584 		if (error == 0) {
3585 			softc->flags |= SA_FLAG_TAPE_MOUNTED;
3586 		}
3587 exit:
3588 		if (rblim != NULL)
3589 			free(rblim, M_SCSISA);
3590 
3591 		if (error != 0) {
3592 			softc->dsreg = MTIO_DSREG_NIL;
3593 		} else {
3594 			softc->fileno = softc->blkno = 0;
3595 			softc->rep_fileno = softc->rep_blkno = -1;
3596 			softc->partition = 0;
3597 			softc->dsreg = MTIO_DSREG_REST;
3598 		}
3599 #ifdef	SA_1FM_AT_EOD
3600 		if ((softc->quirks & SA_QUIRK_2FM) == 0)
3601 			softc->quirks |= SA_QUIRK_1FM;
3602 #else
3603 		if ((softc->quirks & SA_QUIRK_1FM) == 0)
3604 			softc->quirks |= SA_QUIRK_2FM;
3605 #endif
3606 	} else
3607 		xpt_release_ccb(ccb);
3608 
3609 	/*
3610 	 * If we return an error, we're not mounted any more,
3611 	 * so release any device reservation.
3612 	 */
3613 	if (error != 0) {
3614 		(void) sareservereleaseunit(periph, FALSE);
3615 	} else {
3616 		/*
3617 		 * Clear I/O residual.
3618 		 */
3619 		softc->last_io_resid = 0;
3620 		softc->last_ctl_resid = 0;
3621 	}
3622 	return (error);
3623 }
3624 
3625 /*
3626  * How many filemarks do we need to write if we were to terminate the
3627  * tape session right now? Note that this can be a negative number
3628  */
3629 
3630 static int
3631 samarkswanted(struct cam_periph *periph)
3632 {
3633 	int	markswanted;
3634 	struct	sa_softc *softc;
3635 
3636 	softc = (struct sa_softc *)periph->softc;
3637 	markswanted = 0;
3638 	if ((softc->flags & SA_FLAG_TAPE_WRITTEN) != 0) {
3639 		markswanted++;
3640 		if (softc->quirks & SA_QUIRK_2FM)
3641 			markswanted++;
3642 	}
3643 	markswanted -= softc->filemarks;
3644 	return (markswanted);
3645 }
3646 
3647 static int
3648 sacheckeod(struct cam_periph *periph)
3649 {
3650 	int	error;
3651 	int	markswanted;
3652 
3653 	markswanted = samarkswanted(periph);
3654 
3655 	if (markswanted > 0) {
3656 		error = sawritefilemarks(periph, markswanted, FALSE, FALSE);
3657 	} else {
3658 		error = 0;
3659 	}
3660 	return (error);
3661 }
3662 
3663 static int
3664 saerror(union ccb *ccb, uint32_t cflgs, uint32_t sflgs)
3665 {
3666 	static const char *toobig =
3667 	    "%d-byte tape record bigger than supplied buffer\n";
3668 	struct	cam_periph *periph;
3669 	struct	sa_softc *softc;
3670 	struct	ccb_scsiio *csio;
3671 	struct	scsi_sense_data *sense;
3672 	uint64_t resid = 0;
3673 	int64_t	info = 0;
3674 	cam_status status;
3675 	int error_code, sense_key, asc, ascq, error, aqvalid, stream_valid;
3676 	int sense_len;
3677 	uint8_t stream_bits;
3678 
3679 	periph = xpt_path_periph(ccb->ccb_h.path);
3680 	softc = (struct sa_softc *)periph->softc;
3681 	csio = &ccb->csio;
3682 	sense = &csio->sense_data;
3683 	sense_len = csio->sense_len - csio->sense_resid;
3684 	scsi_extract_sense_len(sense, sense_len, &error_code, &sense_key,
3685 	    &asc, &ascq, /*show_errors*/ 1);
3686 	if (asc != -1 && ascq != -1)
3687 		aqvalid = 1;
3688 	else
3689 		aqvalid = 0;
3690 	if (scsi_get_stream_info(sense, sense_len, NULL, &stream_bits) == 0)
3691 		stream_valid = 1;
3692 	else
3693 		stream_valid = 0;
3694 	error = 0;
3695 
3696 	status = csio->ccb_h.status & CAM_STATUS_MASK;
3697 
3698 	/*
3699 	 * Calculate/latch up, any residuals... We do this in a funny 2-step
3700 	 * so we can print stuff here if we have CAM_DEBUG enabled for this
3701 	 * unit.
3702 	 */
3703 	if (status == CAM_SCSI_STATUS_ERROR) {
3704 		if (scsi_get_sense_info(sense, sense_len, SSD_DESC_INFO, &resid,
3705 					&info) == 0) {
3706 			if ((softc->flags & SA_FLAG_FIXED) != 0)
3707 				resid *= softc->media_blksize;
3708 		} else {
3709 			resid = csio->dxfer_len;
3710 			info = resid;
3711 			if ((softc->flags & SA_FLAG_FIXED) != 0) {
3712 				if (softc->media_blksize)
3713 					info /= softc->media_blksize;
3714 			}
3715 		}
3716 		if (csio->cdb_io.cdb_bytes[0] == SA_READ ||
3717 		    csio->cdb_io.cdb_bytes[0] == SA_WRITE) {
3718 			bcopy((caddr_t) sense, (caddr_t) &softc->last_io_sense,
3719 			    sizeof (struct scsi_sense_data));
3720 			bcopy(csio->cdb_io.cdb_bytes, softc->last_io_cdb,
3721 			    (int) csio->cdb_len);
3722 			softc->last_io_resid = resid;
3723 			softc->last_resid_was_io = 1;
3724 		} else {
3725 			bcopy((caddr_t) sense, (caddr_t) &softc->last_ctl_sense,
3726 			    sizeof (struct scsi_sense_data));
3727 			bcopy(csio->cdb_io.cdb_bytes, softc->last_ctl_cdb,
3728 			    (int) csio->cdb_len);
3729 			softc->last_ctl_resid = resid;
3730 			softc->last_resid_was_io = 0;
3731 		}
3732 		CAM_DEBUG(periph->path, CAM_DEBUG_INFO, ("CDB[0]=0x%x Key 0x%x "
3733 		    "ASC/ASCQ 0x%x/0x%x CAM STATUS 0x%x flags 0x%x resid %jd "
3734 		    "dxfer_len %d\n", csio->cdb_io.cdb_bytes[0] & 0xff,
3735 		    sense_key, asc, ascq, status,
3736 		    (stream_valid) ? stream_bits : 0, (intmax_t)resid,
3737 		    csio->dxfer_len));
3738 	} else {
3739 		CAM_DEBUG(periph->path, CAM_DEBUG_INFO,
3740 		    ("Cam Status 0x%x\n", status));
3741 	}
3742 
3743 	switch (status) {
3744 	case CAM_REQ_CMP:
3745 		return (0);
3746 	case CAM_SCSI_STATUS_ERROR:
3747 		/*
3748 		 * If a read/write command, we handle it here.
3749 		 */
3750 		if (csio->cdb_io.cdb_bytes[0] == SA_READ ||
3751 		    csio->cdb_io.cdb_bytes[0] == SA_WRITE) {
3752 			break;
3753 		}
3754 		/*
3755 		 * If this was just EOM/EOP, Filemark, Setmark, ILI or
3756 		 * PEW detected on a non read/write command, we assume
3757 		 * it's not an error and propagate the residual and return.
3758 		 */
3759 		if ((aqvalid && asc == 0 && ((ascq > 0 && ascq <= 5)
3760 		  || (ascq == 0x07)))
3761 		 || (aqvalid == 0 && sense_key == SSD_KEY_NO_SENSE)) {
3762 			csio->resid = resid;
3763 			QFRLS(ccb);
3764 			return (0);
3765 		}
3766 		/*
3767 		 * Otherwise, we let the common code handle this.
3768 		 */
3769 		return (cam_periph_error(ccb, cflgs, sflgs));
3770 
3771 	/*
3772 	 * XXX: To Be Fixed
3773 	 * We cannot depend upon CAM honoring retry counts for these.
3774 	 */
3775 	case CAM_SCSI_BUS_RESET:
3776 	case CAM_BDR_SENT:
3777 		if (ccb->ccb_h.retry_count <= 0) {
3778 			return (EIO);
3779 		}
3780 		/* FALLTHROUGH */
3781 	default:
3782 		return (cam_periph_error(ccb, cflgs, sflgs));
3783 	}
3784 
3785 	/*
3786 	 * Handle filemark, end of tape, mismatched record sizes....
3787 	 * From this point out, we're only handling read/write cases.
3788 	 * Handle writes && reads differently.
3789 	 */
3790 
3791 	if (csio->cdb_io.cdb_bytes[0] == SA_WRITE) {
3792 		if (sense_key == SSD_KEY_VOLUME_OVERFLOW) {
3793 			csio->resid = resid;
3794 			error = ENOSPC;
3795 		} else if ((stream_valid != 0) && (stream_bits & SSD_EOM)) {
3796 			softc->flags |= SA_FLAG_EOM_PENDING;
3797 			/*
3798 			 * Grotesque as it seems, the few times
3799 			 * I've actually seen a non-zero resid,
3800 			 * the tape drive actually lied and had
3801 			 * written all the data!.
3802 			 */
3803 			csio->resid = 0;
3804 		}
3805 	} else {
3806 		csio->resid = resid;
3807 		if (sense_key == SSD_KEY_BLANK_CHECK) {
3808 			if (softc->quirks & SA_QUIRK_1FM) {
3809 				error = 0;
3810 				softc->flags |= SA_FLAG_EOM_PENDING;
3811 			} else {
3812 				error = EIO;
3813 			}
3814 		} else if ((stream_valid != 0) && (stream_bits & SSD_FILEMARK)){
3815 			if (softc->flags & SA_FLAG_FIXED) {
3816 				error = -1;
3817 				softc->flags |= SA_FLAG_EOF_PENDING;
3818 			}
3819 			/*
3820 			 * Unconditionally, if we detected a filemark on a read,
3821 			 * mark that we've run moved a file ahead.
3822 			 */
3823 			if (softc->fileno != (daddr_t) -1) {
3824 				softc->fileno++;
3825 				softc->blkno = 0;
3826 				csio->ccb_h.ccb_pflags |= SA_POSITION_UPDATED;
3827 			}
3828 		}
3829 	}
3830 
3831 	/*
3832 	 * Incorrect Length usually applies to read, but can apply to writes.
3833 	 */
3834 	if (error == 0 && (stream_valid != 0) && (stream_bits & SSD_ILI)) {
3835 		if (info < 0) {
3836 			xpt_print(csio->ccb_h.path, toobig,
3837 			    csio->dxfer_len - info);
3838 			csio->resid = csio->dxfer_len;
3839 			error = EIO;
3840 		} else {
3841 			csio->resid = resid;
3842 			if (softc->flags & SA_FLAG_FIXED) {
3843 				softc->flags |= SA_FLAG_EIO_PENDING;
3844 			}
3845 			/*
3846 			 * Bump the block number if we hadn't seen a filemark.
3847 			 * Do this independent of errors (we've moved anyway).
3848 			 */
3849 			if ((stream_valid == 0) ||
3850 			    (stream_bits & SSD_FILEMARK) == 0) {
3851 				if (softc->blkno != (daddr_t) -1) {
3852 					softc->blkno++;
3853 					csio->ccb_h.ccb_pflags |=
3854 					   SA_POSITION_UPDATED;
3855 				}
3856 			}
3857 		}
3858 	}
3859 
3860 	if (error <= 0) {
3861 		/*
3862 		 * Unfreeze the queue if frozen as we're not returning anything
3863 		 * to our waiters that would indicate an I/O error has occurred
3864 		 * (yet).
3865 		 */
3866 		QFRLS(ccb);
3867 		error = 0;
3868 	}
3869 	return (error);
3870 }
3871 
3872 static int
3873 sagetparams(struct cam_periph *periph, sa_params params_to_get,
3874 	    uint32_t *blocksize, uint8_t *density, uint32_t *numblocks,
3875 	    int *buff_mode, uint8_t *write_protect, uint8_t *speed,
3876 	    int *comp_supported, int *comp_enabled, uint32_t *comp_algorithm,
3877 	    sa_comp_t *tcs, struct scsi_control_data_prot_subpage *prot_page,
3878 	    int dp_size, int prot_changeable)
3879 {
3880 	union ccb *ccb;
3881 	void *mode_buffer;
3882 	struct scsi_mode_header_6 *mode_hdr;
3883 	struct scsi_mode_blk_desc *mode_blk;
3884 	int mode_buffer_len;
3885 	struct sa_softc *softc;
3886 	uint8_t cpage;
3887 	int error;
3888 	cam_status status;
3889 
3890 	softc = (struct sa_softc *)periph->softc;
3891 	ccb = cam_periph_getccb(periph, 1);
3892 	if (softc->quirks & SA_QUIRK_NO_CPAGE)
3893 		cpage = SA_DEVICE_CONFIGURATION_PAGE;
3894 	else
3895 		cpage = SA_DATA_COMPRESSION_PAGE;
3896 
3897 retry:
3898 	mode_buffer_len = sizeof(*mode_hdr) + sizeof(*mode_blk);
3899 
3900 	if (params_to_get & SA_PARAM_COMPRESSION) {
3901 		if (softc->quirks & SA_QUIRK_NOCOMP) {
3902 			*comp_supported = FALSE;
3903 			params_to_get &= ~SA_PARAM_COMPRESSION;
3904 		} else
3905 			mode_buffer_len += sizeof (sa_comp_t);
3906 	}
3907 
3908 	/* XXX Fix M_NOWAIT */
3909 	mode_buffer = malloc(mode_buffer_len, M_SCSISA, M_NOWAIT | M_ZERO);
3910 	if (mode_buffer == NULL) {
3911 		xpt_release_ccb(ccb);
3912 		return (ENOMEM);
3913 	}
3914 	mode_hdr = (struct scsi_mode_header_6 *)mode_buffer;
3915 	mode_blk = (struct scsi_mode_blk_desc *)&mode_hdr[1];
3916 
3917 	/* it is safe to retry this */
3918 	scsi_mode_sense(&ccb->csio, 5, NULL, MSG_SIMPLE_Q_TAG, FALSE,
3919 	    SMS_PAGE_CTRL_CURRENT, (params_to_get & SA_PARAM_COMPRESSION) ?
3920 	    cpage : SMS_VENDOR_SPECIFIC_PAGE, mode_buffer, mode_buffer_len,
3921 	    SSD_FULL_SIZE, softc->timeout_info[SA_TIMEOUT_MODE_SENSE]);
3922 
3923 	error = cam_periph_runccb(ccb, saerror, 0, SF_NO_PRINT,
3924 	    softc->device_stats);
3925 
3926 	status = ccb->ccb_h.status & CAM_STATUS_MASK;
3927 
3928 	if (error == EINVAL && (params_to_get & SA_PARAM_COMPRESSION) != 0) {
3929 		/*
3930 		 * Hmm. Let's see if we can try another page...
3931 		 * If we've already done that, give up on compression
3932 		 * for this device and remember this for the future
3933 		 * and attempt the request without asking for compression
3934 		 * info.
3935 		 */
3936 		if (cpage == SA_DATA_COMPRESSION_PAGE) {
3937 			cpage = SA_DEVICE_CONFIGURATION_PAGE;
3938 			goto retry;
3939 		}
3940 		softc->quirks |= SA_QUIRK_NOCOMP;
3941 		free(mode_buffer, M_SCSISA);
3942 		goto retry;
3943 	} else if (status == CAM_SCSI_STATUS_ERROR) {
3944 		/* Tell the user about the fatal error. */
3945 		scsi_sense_print(&ccb->csio);
3946 		goto sagetparamsexit;
3947 	}
3948 
3949 	/*
3950 	 * If the user only wants the compression information, and
3951 	 * the device doesn't send back the block descriptor, it's
3952 	 * no big deal.  If the user wants more than just
3953 	 * compression, though, and the device doesn't pass back the
3954 	 * block descriptor, we need to send another mode sense to
3955 	 * get the block descriptor.
3956 	 */
3957 	if ((mode_hdr->blk_desc_len == 0) &&
3958 	    (params_to_get & SA_PARAM_COMPRESSION) &&
3959 	    (params_to_get & ~(SA_PARAM_COMPRESSION))) {
3960 		/*
3961 		 * Decrease the mode buffer length by the size of
3962 		 * the compression page, to make sure the data
3963 		 * there doesn't get overwritten.
3964 		 */
3965 		mode_buffer_len -= sizeof (sa_comp_t);
3966 
3967 		/*
3968 		 * Now move the compression page that we presumably
3969 		 * got back down the memory chunk a little bit so
3970 		 * it doesn't get spammed.
3971 		 */
3972 		bcopy(&mode_hdr[0], &mode_hdr[1], sizeof (sa_comp_t));
3973 		bzero(&mode_hdr[0], sizeof (mode_hdr[0]));
3974 
3975 		/*
3976 		 * Now, we issue another mode sense and just ask
3977 		 * for the block descriptor, etc.
3978 		 */
3979 
3980 		scsi_mode_sense(&ccb->csio, 2, NULL, MSG_SIMPLE_Q_TAG, FALSE,
3981 		    SMS_PAGE_CTRL_CURRENT, SMS_VENDOR_SPECIFIC_PAGE,
3982 		    mode_buffer, mode_buffer_len, SSD_FULL_SIZE,
3983 		    softc->timeout_info[SA_TIMEOUT_MODE_SENSE]);
3984 
3985 		error = cam_periph_runccb(ccb, saerror, 0, SF_NO_PRINT,
3986 		    softc->device_stats);
3987 
3988 		if (error != 0)
3989 			goto sagetparamsexit;
3990 	}
3991 
3992 	if (params_to_get & SA_PARAM_BLOCKSIZE)
3993 		*blocksize = scsi_3btoul(mode_blk->blklen);
3994 
3995 	if (params_to_get & SA_PARAM_NUMBLOCKS)
3996 		*numblocks = scsi_3btoul(mode_blk->nblocks);
3997 
3998 	if (params_to_get & SA_PARAM_BUFF_MODE)
3999 		*buff_mode = mode_hdr->dev_spec & SMH_SA_BUF_MODE_MASK;
4000 
4001 	if (params_to_get & SA_PARAM_DENSITY)
4002 		*density = mode_blk->density;
4003 
4004 	if (params_to_get & SA_PARAM_WP)
4005 		*write_protect = (mode_hdr->dev_spec & SMH_SA_WP)? TRUE : FALSE;
4006 
4007 	if (params_to_get & SA_PARAM_SPEED)
4008 		*speed = mode_hdr->dev_spec & SMH_SA_SPEED_MASK;
4009 
4010 	if (params_to_get & SA_PARAM_COMPRESSION) {
4011 		sa_comp_t *ntcs = (sa_comp_t *) &mode_blk[1];
4012 		if (cpage == SA_DATA_COMPRESSION_PAGE) {
4013 			struct scsi_data_compression_page *cp = &ntcs->dcomp;
4014 			*comp_supported =
4015 			    (cp->dce_and_dcc & SA_DCP_DCC)? TRUE : FALSE;
4016 			*comp_enabled =
4017 			    (cp->dce_and_dcc & SA_DCP_DCE)? TRUE : FALSE;
4018 			*comp_algorithm = scsi_4btoul(cp->comp_algorithm);
4019 		} else {
4020 			struct scsi_dev_conf_page *cp = &ntcs->dconf;
4021 			/*
4022 			 * We don't really know whether this device supports
4023 			 * Data Compression if the algorithm field is
4024 			 * zero. Just say we do.
4025 			 */
4026 			*comp_supported = TRUE;
4027 			*comp_enabled =
4028 			    (cp->sel_comp_alg != SA_COMP_NONE)? TRUE : FALSE;
4029 			*comp_algorithm = cp->sel_comp_alg;
4030 		}
4031 		if (tcs != NULL)
4032 			bcopy(ntcs, tcs, sizeof (sa_comp_t));
4033 	}
4034 
4035 	if ((params_to_get & SA_PARAM_DENSITY_EXT)
4036 	 && (softc->scsi_rev >= SCSI_REV_SPC)) {
4037 		int i;
4038 
4039 		for (i = 0; i < SA_DENSITY_TYPES; i++) {
4040 			scsi_report_density_support(&ccb->csio,
4041 			    /*retries*/ 1,
4042 			    /*cbfcnp*/ NULL,
4043 			    /*tag_action*/ MSG_SIMPLE_Q_TAG,
4044 			    /*media*/ softc->density_type_bits[i] & SRDS_MEDIA,
4045 			    /*medium_type*/ softc->density_type_bits[i] &
4046 					    SRDS_MEDIUM_TYPE,
4047 			    /*data_ptr*/ softc->density_info[i],
4048 			    /*length*/ sizeof(softc->density_info[i]),
4049 			    /*sense_len*/ SSD_FULL_SIZE,
4050 			    /*timeout*/
4051 			        softc->timeout_info[SA_TIMEOUT_REP_DENSITY]);
4052 			error = cam_periph_runccb(ccb, saerror, 0, SF_NO_PRINT,
4053 			    softc->device_stats);
4054 			status = ccb->ccb_h.status & CAM_STATUS_MASK;
4055 
4056 			/*
4057 			 * Some tape drives won't support this command at
4058 			 * all, but hopefully we'll minimize that with the
4059 			 * check for SPC or greater support above.  If they
4060 			 * don't support the default report (neither the
4061 			 * MEDIA or MEDIUM_TYPE bits set), then there is
4062 			 * really no point in continuing on to look for
4063 			 * other reports.
4064 			 */
4065 			if ((error != 0)
4066 			 || (status != CAM_REQ_CMP)) {
4067 				error = 0;
4068 				softc->density_info_valid[i] = 0;
4069 				if (softc->density_type_bits[i] == 0)
4070 					break;
4071 				else
4072 					continue;
4073 			}
4074 			softc->density_info_valid[i] = ccb->csio.dxfer_len -
4075 			    ccb->csio.resid;
4076 		}
4077 	}
4078 
4079 	/*
4080 	 * Get logical block protection parameters if the drive supports it.
4081 	 */
4082 	if ((params_to_get & SA_PARAM_LBP)
4083 	 && (softc->flags & SA_FLAG_PROTECT_SUPP)) {
4084 		struct scsi_mode_header_10 *mode10_hdr;
4085 		struct scsi_control_data_prot_subpage *dp_page;
4086 		struct scsi_mode_sense_10 *cdb;
4087 		struct sa_prot_state *prot;
4088 		int dp_len, returned_len;
4089 
4090 		if (dp_size == 0)
4091 			dp_size = sizeof(*dp_page);
4092 
4093 		dp_len = sizeof(*mode10_hdr) + dp_size;
4094 		mode10_hdr = malloc(dp_len, M_SCSISA, M_NOWAIT | M_ZERO);
4095 		if (mode10_hdr == NULL) {
4096 			error = ENOMEM;
4097 			goto sagetparamsexit;
4098 		}
4099 
4100 		scsi_mode_sense_len(&ccb->csio,
4101 				    /*retries*/ 5,
4102 				    /*cbfcnp*/ NULL,
4103 				    /*tag_action*/ MSG_SIMPLE_Q_TAG,
4104 				    /*dbd*/ TRUE,
4105 				    /*page_code*/ (prot_changeable == 0) ?
4106 						  SMS_PAGE_CTRL_CURRENT :
4107 						  SMS_PAGE_CTRL_CHANGEABLE,
4108 				    /*page*/ SMS_CONTROL_MODE_PAGE,
4109 				    /*param_buf*/ (uint8_t *)mode10_hdr,
4110 				    /*param_len*/ dp_len,
4111 				    /*minimum_cmd_size*/ 10,
4112 				    /*sense_len*/ SSD_FULL_SIZE,
4113 				    /*timeout*/
4114 				    softc->timeout_info[SA_TIMEOUT_MODE_SENSE]);
4115 		/*
4116 		 * XXX KDM we need to be able to set the subpage in the
4117 		 * fill function.
4118 		 */
4119 		cdb = (struct scsi_mode_sense_10 *)ccb->csio.cdb_io.cdb_bytes;
4120 		cdb->subpage = SA_CTRL_DP_SUBPAGE_CODE;
4121 
4122 		error = cam_periph_runccb(ccb, saerror, 0, SF_NO_PRINT,
4123 		    softc->device_stats);
4124 		if (error != 0) {
4125 			free(mode10_hdr, M_SCSISA);
4126 			goto sagetparamsexit;
4127 		}
4128 
4129 		status = ccb->ccb_h.status & CAM_STATUS_MASK;
4130 		if (status != CAM_REQ_CMP) {
4131 			error = EINVAL;
4132 			free(mode10_hdr, M_SCSISA);
4133 			goto sagetparamsexit;
4134 		}
4135 
4136 		/*
4137 		 * The returned data length at least has to be long enough
4138 		 * for us to look at length in the mode page header.
4139 		 */
4140 		returned_len = ccb->csio.dxfer_len - ccb->csio.resid;
4141 		if (returned_len < sizeof(mode10_hdr->data_length)) {
4142 			error = EINVAL;
4143 			free(mode10_hdr, M_SCSISA);
4144 			goto sagetparamsexit;
4145 		}
4146 
4147 		returned_len = min(returned_len,
4148 		    sizeof(mode10_hdr->data_length) +
4149 		    scsi_2btoul(mode10_hdr->data_length));
4150 
4151 		dp_page = (struct scsi_control_data_prot_subpage *)
4152 		    &mode10_hdr[1];
4153 
4154 		/*
4155 		 * We also have to have enough data to include the prot_bits
4156 		 * in the subpage.
4157 		 */
4158 		if (returned_len < (sizeof(*mode10_hdr) +
4159 		    __offsetof(struct scsi_control_data_prot_subpage, prot_bits)
4160 		    + sizeof(dp_page->prot_bits))) {
4161 			error = EINVAL;
4162 			free(mode10_hdr, M_SCSISA);
4163 			goto sagetparamsexit;
4164 		}
4165 
4166 		prot = &softc->prot_info.cur_prot_state;
4167 		prot->prot_method = dp_page->prot_method;
4168 		prot->pi_length = dp_page->pi_length &
4169 		    SA_CTRL_DP_PI_LENGTH_MASK;
4170 		prot->lbp_w = (dp_page->prot_bits & SA_CTRL_DP_LBP_W) ? 1 :0;
4171 		prot->lbp_r = (dp_page->prot_bits & SA_CTRL_DP_LBP_R) ? 1 :0;
4172 		prot->rbdp = (dp_page->prot_bits & SA_CTRL_DP_RBDP) ? 1 :0;
4173 		prot->initialized = 1;
4174 
4175 		if (prot_page != NULL)
4176 			bcopy(dp_page, prot_page, min(sizeof(*prot_page),
4177 			    sizeof(*dp_page)));
4178 
4179 		free(mode10_hdr, M_SCSISA);
4180 	}
4181 
4182 	if (CAM_DEBUGGED(periph->path, CAM_DEBUG_INFO)) {
4183 		int idx;
4184 		char *xyz = mode_buffer;
4185 		xpt_print_path(periph->path);
4186 		printf("Mode Sense Data=");
4187 		for (idx = 0; idx < mode_buffer_len; idx++)
4188 			printf(" 0x%02x", xyz[idx] & 0xff);
4189 		printf("\n");
4190 	}
4191 
4192 sagetparamsexit:
4193 
4194 	xpt_release_ccb(ccb);
4195 	free(mode_buffer, M_SCSISA);
4196 	return (error);
4197 }
4198 
4199 /*
4200  * Set protection information to the pending protection information stored
4201  * in the softc.
4202  */
4203 static int
4204 sasetprot(struct cam_periph *periph, struct sa_prot_state *new_prot)
4205 {
4206 	struct sa_softc *softc;
4207 	struct scsi_control_data_prot_subpage *dp_page, *dp_changeable;
4208 	struct scsi_mode_header_10 *mode10_hdr, *mode10_changeable;
4209 	union ccb *ccb;
4210 	uint8_t current_speed;
4211 	size_t dp_size, dp_page_length;
4212 	int dp_len, buff_mode;
4213 	int error;
4214 
4215 	softc = (struct sa_softc *)periph->softc;
4216 	mode10_hdr = NULL;
4217 	mode10_changeable = NULL;
4218 	ccb = NULL;
4219 
4220 	/*
4221 	 * Start off with the size set to the actual length of the page
4222 	 * that we have defined.
4223 	 */
4224 	dp_size = sizeof(*dp_changeable);
4225 	dp_page_length = dp_size -
4226 	    __offsetof(struct scsi_control_data_prot_subpage, prot_method);
4227 
4228 retry_length:
4229 
4230 	dp_len = sizeof(*mode10_changeable) + dp_size;
4231 	mode10_changeable = malloc(dp_len, M_SCSISA, M_NOWAIT | M_ZERO);
4232 	if (mode10_changeable == NULL) {
4233 		error = ENOMEM;
4234 		goto bailout;
4235 	}
4236 
4237 	dp_changeable =
4238 	    (struct scsi_control_data_prot_subpage *)&mode10_changeable[1];
4239 
4240 	/*
4241 	 * First get the data protection page changeable parameters mask.
4242 	 * We need to know which parameters the drive supports changing.
4243 	 * We also need to know what the drive claims that its page length
4244 	 * is.  The reason is that IBM drives in particular are very picky
4245 	 * about the page length.  They want it (the length set in the
4246 	 * page structure itself) to be 28 bytes, and they want the
4247 	 * parameter list length specified in the mode select header to be
4248 	 * 40 bytes.  So, to work with IBM drives as well as any other tape
4249 	 * drive, find out what the drive claims the page length is, and
4250 	 * make sure that we match that.
4251 	 */
4252 	error = sagetparams(periph, SA_PARAM_SPEED | SA_PARAM_LBP,
4253 	    NULL, NULL, NULL, &buff_mode, NULL, &current_speed, NULL, NULL,
4254 	    NULL, NULL, dp_changeable, dp_size, /*prot_changeable*/ 1);
4255 	if (error != 0)
4256 		goto bailout;
4257 
4258 	if (scsi_2btoul(dp_changeable->length) > dp_page_length) {
4259 		dp_page_length = scsi_2btoul(dp_changeable->length);
4260 		dp_size = dp_page_length +
4261 		    __offsetof(struct scsi_control_data_prot_subpage,
4262 		    prot_method);
4263 		free(mode10_changeable, M_SCSISA);
4264 		mode10_changeable = NULL;
4265 		goto retry_length;
4266 	}
4267 
4268 	mode10_hdr = malloc(dp_len, M_SCSISA, M_NOWAIT | M_ZERO);
4269 	if (mode10_hdr == NULL) {
4270 		error = ENOMEM;
4271 		goto bailout;
4272 	}
4273 
4274 	dp_page = (struct scsi_control_data_prot_subpage *)&mode10_hdr[1];
4275 
4276 	/*
4277 	 * Now grab the actual current settings in the page.
4278 	 */
4279 	error = sagetparams(periph, SA_PARAM_SPEED | SA_PARAM_LBP,
4280 	    NULL, NULL, NULL, &buff_mode, NULL, &current_speed, NULL, NULL,
4281 	    NULL, NULL, dp_page, dp_size, /*prot_changeable*/ 0);
4282 	if (error != 0)
4283 		goto bailout;
4284 
4285 	/* These two fields need to be 0 for MODE SELECT */
4286 	scsi_ulto2b(0, mode10_hdr->data_length);
4287 	mode10_hdr->medium_type = 0;
4288 	/* We are not including a block descriptor */
4289 	scsi_ulto2b(0, mode10_hdr->blk_desc_len);
4290 
4291 	mode10_hdr->dev_spec = current_speed;
4292 	/* if set, set single-initiator buffering mode */
4293 	if (softc->buffer_mode == SMH_SA_BUF_MODE_SIBUF) {
4294 		mode10_hdr->dev_spec |= SMH_SA_BUF_MODE_SIBUF;
4295 	}
4296 
4297 	/*
4298 	 * For each field, make sure that the drive allows changing it
4299 	 * before bringing in the user's setting.
4300 	 */
4301 	if (dp_changeable->prot_method != 0)
4302 		dp_page->prot_method = new_prot->prot_method;
4303 
4304 	if (dp_changeable->pi_length & SA_CTRL_DP_PI_LENGTH_MASK) {
4305 		dp_page->pi_length &= ~SA_CTRL_DP_PI_LENGTH_MASK;
4306 		dp_page->pi_length |= (new_prot->pi_length &
4307 		    SA_CTRL_DP_PI_LENGTH_MASK);
4308 	}
4309 	if (dp_changeable->prot_bits & SA_CTRL_DP_LBP_W) {
4310 		if (new_prot->lbp_w)
4311 			dp_page->prot_bits |= SA_CTRL_DP_LBP_W;
4312 		else
4313 			dp_page->prot_bits &= ~SA_CTRL_DP_LBP_W;
4314 	}
4315 
4316 	if (dp_changeable->prot_bits & SA_CTRL_DP_LBP_R) {
4317 		if (new_prot->lbp_r)
4318 			dp_page->prot_bits |= SA_CTRL_DP_LBP_R;
4319 		else
4320 			dp_page->prot_bits &= ~SA_CTRL_DP_LBP_R;
4321 	}
4322 
4323 	if (dp_changeable->prot_bits & SA_CTRL_DP_RBDP) {
4324 		if (new_prot->rbdp)
4325 			dp_page->prot_bits |= SA_CTRL_DP_RBDP;
4326 		else
4327 			dp_page->prot_bits &= ~SA_CTRL_DP_RBDP;
4328 	}
4329 
4330 	ccb = cam_periph_getccb(periph, 1);
4331 
4332 	scsi_mode_select_len(&ccb->csio,
4333 			     /*retries*/ 5,
4334 			     /*cbfcnp*/ NULL,
4335 			     /*tag_action*/ MSG_SIMPLE_Q_TAG,
4336 			     /*scsi_page_fmt*/ TRUE,
4337 			     /*save_pages*/ FALSE,
4338 			     /*param_buf*/ (uint8_t *)mode10_hdr,
4339 			     /*param_len*/ dp_len,
4340 			     /*minimum_cmd_size*/ 10,
4341 			     /*sense_len*/ SSD_FULL_SIZE,
4342 			     /*timeout*/
4343 			           softc->timeout_info[SA_TIMEOUT_MODE_SELECT]);
4344 
4345 	error = cam_periph_runccb(ccb, saerror, 0, 0, softc->device_stats);
4346 	if (error != 0)
4347 		goto bailout;
4348 
4349 	if ((ccb->ccb_h.status & CAM_STATUS_MASK) != CAM_REQ_CMP) {
4350 		error = EINVAL;
4351 		goto bailout;
4352 	}
4353 
4354 	/*
4355 	 * The operation was successful.  We could just copy the settings
4356 	 * the user requested, but just in case the drive ignored some of
4357 	 * our settings, let's ask for status again.
4358 	 */
4359 	error = sagetparams(periph, SA_PARAM_SPEED | SA_PARAM_LBP,
4360 	    NULL, NULL, NULL, &buff_mode, NULL, &current_speed, NULL, NULL,
4361 	    NULL, NULL, dp_page, dp_size, 0);
4362 
4363 bailout:
4364 	if (ccb != NULL)
4365 		xpt_release_ccb(ccb);
4366 	free(mode10_hdr, M_SCSISA);
4367 	free(mode10_changeable, M_SCSISA);
4368 	return (error);
4369 }
4370 
4371 /*
4372  * The purpose of this function is to set one of four different parameters
4373  * for a tape drive:
4374  *	- blocksize
4375  *	- density
4376  *	- compression / compression algorithm
4377  *	- buffering mode
4378  *
4379  * The assumption is that this will be called from saioctl(), and therefore
4380  * from a process context.  Thus the waiting malloc calls below.  If that
4381  * assumption ever changes, the malloc calls should be changed to be
4382  * NOWAIT mallocs.
4383  *
4384  * Any or all of the four parameters may be set when this function is
4385  * called.  It should handle setting more than one parameter at once.
4386  */
4387 static int
4388 sasetparams(struct cam_periph *periph, sa_params params_to_set,
4389 	    uint32_t blocksize, uint8_t density, uint32_t calg,
4390 	    uint32_t sense_flags)
4391 {
4392 	struct sa_softc *softc;
4393 	uint32_t current_blocksize;
4394 	uint32_t current_calg;
4395 	uint8_t current_density;
4396 	uint8_t current_speed;
4397 	int comp_enabled, comp_supported;
4398 	void *mode_buffer;
4399 	int mode_buffer_len;
4400 	struct scsi_mode_header_6 *mode_hdr;
4401 	struct scsi_mode_blk_desc *mode_blk;
4402 	sa_comp_t *ccomp, *cpage;
4403 	int buff_mode;
4404 	union ccb *ccb = NULL;
4405 	int error;
4406 
4407 	softc = (struct sa_softc *)periph->softc;
4408 
4409 	ccomp = malloc(sizeof (sa_comp_t), M_SCSISA, M_NOWAIT);
4410 	if (ccomp == NULL)
4411 		return (ENOMEM);
4412 
4413 	/*
4414 	 * Since it doesn't make sense to set the number of blocks, or
4415 	 * write protection, we won't try to get the current value.  We
4416 	 * always want to get the blocksize, so we can set it back to the
4417 	 * proper value.
4418 	 */
4419 	error = sagetparams(periph,
4420 	    params_to_set | SA_PARAM_BLOCKSIZE | SA_PARAM_SPEED,
4421 	    &current_blocksize, &current_density, NULL, &buff_mode, NULL,
4422 	    &current_speed, &comp_supported, &comp_enabled,
4423 	    &current_calg, ccomp, NULL, 0, 0);
4424 
4425 	if (error != 0) {
4426 		free(ccomp, M_SCSISA);
4427 		return (error);
4428 	}
4429 
4430 	mode_buffer_len = sizeof(*mode_hdr) + sizeof(*mode_blk);
4431 	if (params_to_set & SA_PARAM_COMPRESSION)
4432 		mode_buffer_len += sizeof (sa_comp_t);
4433 
4434 	mode_buffer = malloc(mode_buffer_len, M_SCSISA, M_NOWAIT | M_ZERO);
4435 	if (mode_buffer == NULL) {
4436 		free(ccomp, M_SCSISA);
4437 		return (ENOMEM);
4438 	}
4439 
4440 	mode_hdr = (struct scsi_mode_header_6 *)mode_buffer;
4441 	mode_blk = (struct scsi_mode_blk_desc *)&mode_hdr[1];
4442 
4443 	ccb = cam_periph_getccb(periph, 1);
4444 
4445 retry:
4446 
4447 	if (params_to_set & SA_PARAM_COMPRESSION) {
4448 		if (mode_blk) {
4449 			cpage = (sa_comp_t *)&mode_blk[1];
4450 		} else {
4451 			cpage = (sa_comp_t *)&mode_hdr[1];
4452 		}
4453 		bcopy(ccomp, cpage, sizeof (sa_comp_t));
4454 		cpage->hdr.pagecode &= ~0x80;
4455 	} else
4456 		cpage = NULL;
4457 
4458 	/*
4459 	 * If the caller wants us to set the blocksize, use the one they
4460 	 * pass in.  Otherwise, use the blocksize we got back from the
4461 	 * mode select above.
4462 	 */
4463 	if (mode_blk) {
4464 		if (params_to_set & SA_PARAM_BLOCKSIZE)
4465 			scsi_ulto3b(blocksize, mode_blk->blklen);
4466 		else
4467 			scsi_ulto3b(current_blocksize, mode_blk->blklen);
4468 
4469 		/*
4470 		 * Set density if requested, else preserve old density.
4471 		 * SCSI_SAME_DENSITY only applies to SCSI-2 or better
4472 		 * devices, else density we've latched up in our softc.
4473 		 */
4474 		if (params_to_set & SA_PARAM_DENSITY) {
4475 			mode_blk->density = density;
4476 		} else if (softc->scsi_rev > SCSI_REV_CCS) {
4477 			mode_blk->density = SCSI_SAME_DENSITY;
4478 		} else {
4479 			mode_blk->density = softc->media_density;
4480 		}
4481 	}
4482 
4483 	/*
4484 	 * For mode selects, these two fields must be zero.
4485 	 */
4486 	mode_hdr->data_length = 0;
4487 	mode_hdr->medium_type = 0;
4488 
4489 	/* set the speed to the current value */
4490 	mode_hdr->dev_spec = current_speed;
4491 
4492 	/* if set, set single-initiator buffering mode */
4493 	if (softc->buffer_mode == SMH_SA_BUF_MODE_SIBUF) {
4494 		mode_hdr->dev_spec |= SMH_SA_BUF_MODE_SIBUF;
4495 	}
4496 
4497 	if (mode_blk)
4498 		mode_hdr->blk_desc_len = sizeof(struct scsi_mode_blk_desc);
4499 	else
4500 		mode_hdr->blk_desc_len = 0;
4501 
4502 	/*
4503 	 * First, if the user wants us to set the compression algorithm or
4504 	 * just turn compression on, check to make sure that this drive
4505 	 * supports compression.
4506 	 */
4507 	if (params_to_set & SA_PARAM_COMPRESSION) {
4508 		/*
4509 		 * If the compression algorithm is 0, disable compression.
4510 		 * If the compression algorithm is non-zero, enable
4511 		 * compression and set the compression type to the
4512 		 * specified compression algorithm, unless the algorithm is
4513 		 * MT_COMP_ENABLE.  In that case, we look at the
4514 		 * compression algorithm that is currently set and if it is
4515 		 * non-zero, we leave it as-is.  If it is zero, and we have
4516 		 * saved a compression algorithm from a time when
4517 		 * compression was enabled before, set the compression to
4518 		 * the saved value.
4519 		 */
4520 		switch (ccomp->hdr.pagecode & ~0x80) {
4521 		case SA_DEVICE_CONFIGURATION_PAGE:
4522 		{
4523 			struct scsi_dev_conf_page *dcp = &cpage->dconf;
4524 			if (calg == 0) {
4525 				dcp->sel_comp_alg = SA_COMP_NONE;
4526 				break;
4527 			}
4528 			if (calg != MT_COMP_ENABLE) {
4529 				dcp->sel_comp_alg = calg;
4530 			} else if (dcp->sel_comp_alg == SA_COMP_NONE &&
4531 			    softc->saved_comp_algorithm != 0) {
4532 				dcp->sel_comp_alg = softc->saved_comp_algorithm;
4533 			}
4534 			break;
4535 		}
4536 		case SA_DATA_COMPRESSION_PAGE:
4537 		if (ccomp->dcomp.dce_and_dcc & SA_DCP_DCC) {
4538 			struct scsi_data_compression_page *dcp = &cpage->dcomp;
4539 			if (calg == 0) {
4540 				/*
4541 				 * Disable compression, but leave the
4542 				 * decompression and the capability bit
4543 				 * alone.
4544 				 */
4545 				dcp->dce_and_dcc = SA_DCP_DCC;
4546 				dcp->dde_and_red |= SA_DCP_DDE;
4547 				break;
4548 			}
4549 			/* enable compression && decompression */
4550 			dcp->dce_and_dcc = SA_DCP_DCE | SA_DCP_DCC;
4551 			dcp->dde_and_red |= SA_DCP_DDE;
4552 			/*
4553 			 * If there, use compression algorithm from caller.
4554 			 * Otherwise, if there's a saved compression algorithm
4555 			 * and there is no current algorithm, use the saved
4556 			 * algorithm. Else parrot back what we got and hope
4557 			 * for the best.
4558 			 */
4559 			if (calg != MT_COMP_ENABLE) {
4560 				scsi_ulto4b(calg, dcp->comp_algorithm);
4561 				scsi_ulto4b(calg, dcp->decomp_algorithm);
4562 			} else if (scsi_4btoul(dcp->comp_algorithm) == 0 &&
4563 			    softc->saved_comp_algorithm != 0) {
4564 				scsi_ulto4b(softc->saved_comp_algorithm,
4565 				    dcp->comp_algorithm);
4566 				scsi_ulto4b(softc->saved_comp_algorithm,
4567 				    dcp->decomp_algorithm);
4568 			}
4569 			break;
4570 		}
4571 		/*
4572 		 * Compression does not appear to be supported-
4573 		 * at least via the DATA COMPRESSION page. It
4574 		 * would be too much to ask us to believe that
4575 		 * the page itself is supported, but incorrectly
4576 		 * reports an ability to manipulate data compression,
4577 		 * so we'll assume that this device doesn't support
4578 		 * compression. We can just fall through for that.
4579 		 */
4580 		/* FALLTHROUGH */
4581 		default:
4582 			/*
4583 			 * The drive doesn't seem to support compression,
4584 			 * so turn off the set compression bit.
4585 			 */
4586 			params_to_set &= ~SA_PARAM_COMPRESSION;
4587 			xpt_print(periph->path,
4588 			    "device does not seem to support compression\n");
4589 
4590 			/*
4591 			 * If that was the only thing the user wanted us to set,
4592 			 * clean up allocated resources and return with
4593 			 * 'operation not supported'.
4594 			 */
4595 			if (params_to_set == SA_PARAM_NONE) {
4596 				free(mode_buffer, M_SCSISA);
4597 				xpt_release_ccb(ccb);
4598 				return (ENODEV);
4599 			}
4600 
4601 			/*
4602 			 * That wasn't the only thing the user wanted us to set.
4603 			 * So, decrease the stated mode buffer length by the
4604 			 * size of the compression mode page.
4605 			 */
4606 			mode_buffer_len -= sizeof(sa_comp_t);
4607 		}
4608 	}
4609 
4610 	/* It is safe to retry this operation */
4611 	scsi_mode_select(&ccb->csio, 5, NULL, MSG_SIMPLE_Q_TAG,
4612 	    (params_to_set & SA_PARAM_COMPRESSION)? TRUE : FALSE,
4613 	    FALSE, mode_buffer, mode_buffer_len, SSD_FULL_SIZE,
4614 	    softc->timeout_info[SA_TIMEOUT_MODE_SELECT]);
4615 
4616 	error = cam_periph_runccb(ccb, saerror, 0,
4617 	    sense_flags, softc->device_stats);
4618 
4619 	if (CAM_DEBUGGED(periph->path, CAM_DEBUG_INFO)) {
4620 		int idx;
4621 		char *xyz = mode_buffer;
4622 		xpt_print_path(periph->path);
4623 		printf("Err%d, Mode Select Data=", error);
4624 		for (idx = 0; idx < mode_buffer_len; idx++)
4625 			printf(" 0x%02x", xyz[idx] & 0xff);
4626 		printf("\n");
4627 	}
4628 
4629 	if (error) {
4630 		/*
4631 		 * If we can, try without setting density/blocksize.
4632 		 */
4633 		if (mode_blk) {
4634 			if ((params_to_set &
4635 			    (SA_PARAM_DENSITY|SA_PARAM_BLOCKSIZE)) == 0) {
4636 				mode_blk = NULL;
4637 				goto retry;
4638 			}
4639 		} else {
4640 			mode_blk = (struct scsi_mode_blk_desc *)&mode_hdr[1];
4641 			cpage = (sa_comp_t *)&mode_blk[1];
4642 		}
4643 
4644 		/*
4645 		 * If we were setting the blocksize, and that failed, we
4646 		 * want to set it to its original value.  If we weren't
4647 		 * setting the blocksize, we don't want to change it.
4648 		 */
4649 		scsi_ulto3b(current_blocksize, mode_blk->blklen);
4650 
4651 		/*
4652 		 * Set density if requested, else preserve old density.
4653 		 * SCSI_SAME_DENSITY only applies to SCSI-2 or better
4654 		 * devices, else density we've latched up in our softc.
4655 		 */
4656 		if (params_to_set & SA_PARAM_DENSITY) {
4657 			mode_blk->density = current_density;
4658 		} else if (softc->scsi_rev > SCSI_REV_CCS) {
4659 			mode_blk->density = SCSI_SAME_DENSITY;
4660 		} else {
4661 			mode_blk->density = softc->media_density;
4662 		}
4663 
4664 		if (params_to_set & SA_PARAM_COMPRESSION)
4665 			bcopy(ccomp, cpage, sizeof (sa_comp_t));
4666 
4667 		/*
4668 		 * The retry count is the only CCB field that might have been
4669 		 * changed that we care about, so reset it back to 1.
4670 		 */
4671 		ccb->ccb_h.retry_count = 1;
4672 		cam_periph_runccb(ccb, saerror, 0, sense_flags,
4673 		    softc->device_stats);
4674 	}
4675 
4676 	xpt_release_ccb(ccb);
4677 
4678 	if (ccomp != NULL)
4679 		free(ccomp, M_SCSISA);
4680 
4681 	if (params_to_set & SA_PARAM_COMPRESSION) {
4682 		if (error) {
4683 			softc->flags &= ~SA_FLAG_COMP_ENABLED;
4684 			/*
4685 			 * Even if we get an error setting compression,
4686 			 * do not say that we don't support it. We could
4687 			 * have been wrong, or it may be media specific.
4688 			 *	softc->flags &= ~SA_FLAG_COMP_SUPP;
4689 			 */
4690 			softc->saved_comp_algorithm = softc->comp_algorithm;
4691 			softc->comp_algorithm = 0;
4692 		} else {
4693 			softc->flags |= SA_FLAG_COMP_ENABLED;
4694 			softc->comp_algorithm = calg;
4695 		}
4696 	}
4697 
4698 	free(mode_buffer, M_SCSISA);
4699 	return (error);
4700 }
4701 
4702 static int
4703 saextget(struct cdev *dev, struct cam_periph *periph, struct sbuf *sb,
4704     struct mtextget *g)
4705 {
4706 	int indent, error;
4707 	char tmpstr[80];
4708 	struct sa_softc *softc;
4709 	int tmpint;
4710 	uint32_t maxio_tmp;
4711 	struct ccb_getdev cgd;
4712 
4713 	softc = (struct sa_softc *)periph->softc;
4714 
4715 	error = 0;
4716 
4717 	error = sagetparams_common(dev, periph);
4718 	if (error)
4719 		goto extget_bailout;
4720 	if (!SA_IS_CTRL(dev) && !softc->open_pending_mount)
4721 		sagetpos(periph);
4722 
4723 	indent = 0;
4724 	SASBADDNODE(sb, indent, mtextget);
4725 	/*
4726 	 * Basic CAM peripheral information.
4727 	 */
4728 	SASBADDVARSTR(sb, indent, periph->periph_name, %s, periph_name,
4729 	    strlen(periph->periph_name) + 1);
4730 	SASBADDUINT(sb, indent, periph->unit_number, %u, unit_number);
4731 	memset(&cgd, 0, sizeof(cgd));
4732 	xpt_setup_ccb(&cgd.ccb_h,
4733 		      periph->path,
4734 		      CAM_PRIORITY_NORMAL);
4735 	cgd.ccb_h.func_code = XPT_GDEV_TYPE;
4736 	xpt_action((union ccb *)&cgd);
4737 	if ((cgd.ccb_h.status & CAM_STATUS_MASK) != CAM_REQ_CMP) {
4738 		g->status = MT_EXT_GET_ERROR;
4739 		snprintf(g->error_str, sizeof(g->error_str),
4740 		    "Error %#x returned for XPT_GDEV_TYPE CCB",
4741 		    cgd.ccb_h.status);
4742 		goto extget_bailout;
4743 	}
4744 
4745 	cam_strvis(tmpstr, cgd.inq_data.vendor,
4746 	    sizeof(cgd.inq_data.vendor), sizeof(tmpstr));
4747 	SASBADDVARSTRDESC(sb, indent, tmpstr, %s, vendor,
4748 	    sizeof(cgd.inq_data.vendor) + 1, "SCSI Vendor ID");
4749 
4750 	cam_strvis(tmpstr, cgd.inq_data.product,
4751 	    sizeof(cgd.inq_data.product), sizeof(tmpstr));
4752 	SASBADDVARSTRDESC(sb, indent, tmpstr, %s, product,
4753 	    sizeof(cgd.inq_data.product) + 1, "SCSI Product ID");
4754 
4755 	cam_strvis(tmpstr, cgd.inq_data.revision,
4756 	    sizeof(cgd.inq_data.revision), sizeof(tmpstr));
4757 	SASBADDVARSTRDESC(sb, indent, tmpstr, %s, revision,
4758 	    sizeof(cgd.inq_data.revision) + 1, "SCSI Revision");
4759 
4760 	if (cgd.serial_num_len > 0) {
4761 		char *tmpstr2;
4762 		size_t ts2_len;
4763 		int ts2_malloc;
4764 
4765 		ts2_len = 0;
4766 
4767 		if (cgd.serial_num_len > sizeof(tmpstr)) {
4768 			ts2_len = cgd.serial_num_len + 1;
4769 			ts2_malloc = 1;
4770 			tmpstr2 = malloc(ts2_len, M_SCSISA, M_NOWAIT | M_ZERO);
4771 			/*
4772 			 * The 80 characters allocated on the stack above
4773 			 * will handle the vast majority of serial numbers.
4774 			 * If we run into one that is larger than that, and
4775 			 * we can't malloc the length without blocking,
4776 			 * bail out with an out of memory error.
4777 			 */
4778 			if (tmpstr2 == NULL) {
4779 				error = ENOMEM;
4780 				goto extget_bailout;
4781 			}
4782 		} else {
4783 			ts2_len = sizeof(tmpstr);
4784 			ts2_malloc = 0;
4785 			tmpstr2 = tmpstr;
4786 		}
4787 
4788 		cam_strvis(tmpstr2, cgd.serial_num, cgd.serial_num_len,
4789 		    ts2_len);
4790 
4791 		SASBADDVARSTRDESC(sb, indent, tmpstr2, %s, serial_num,
4792 		    (ssize_t)cgd.serial_num_len + 1, "Serial Number");
4793 		if (ts2_malloc != 0)
4794 			free(tmpstr2, M_SCSISA);
4795 	} else {
4796 		/*
4797 		 * We return a serial_num element in any case, but it will
4798 		 * be empty if the device has no serial number.
4799 		 */
4800 		tmpstr[0] = '\0';
4801 		SASBADDVARSTRDESC(sb, indent, tmpstr, %s, serial_num,
4802 		    (ssize_t)0, "Serial Number");
4803 	}
4804 
4805 	SASBADDUINTDESC(sb, indent, softc->maxio, %u, maxio,
4806 	    "Maximum I/O size allowed by driver and controller");
4807 
4808 	SASBADDUINTDESC(sb, indent, softc->cpi_maxio, %u, cpi_maxio,
4809 	    "Maximum I/O size reported by controller");
4810 
4811 	SASBADDUINTDESC(sb, indent, softc->max_blk, %u, max_blk,
4812 	    "Maximum block size supported by tape drive and media");
4813 
4814 	SASBADDUINTDESC(sb, indent, softc->min_blk, %u, min_blk,
4815 	    "Minimum block size supported by tape drive and media");
4816 
4817 	SASBADDUINTDESC(sb, indent, softc->blk_gran, %u, blk_gran,
4818 	    "Block granularity supported by tape drive and media");
4819 
4820 	maxio_tmp = min(softc->max_blk, softc->maxio);
4821 
4822 	SASBADDUINTDESC(sb, indent, maxio_tmp, %u, max_effective_iosize,
4823 	    "Maximum possible I/O size");
4824 
4825 	SASBADDINTDESC(sb, indent, softc->flags & SA_FLAG_FIXED ? 1 : 0, %d,
4826 	    fixed_mode, "Set to 1 for fixed block mode, 0 for variable block");
4827 
4828 	/*
4829 	 * XXX KDM include SIM, bus, target, LUN?
4830 	 */
4831 	if (softc->flags & SA_FLAG_COMP_UNSUPP)
4832 		tmpint = 0;
4833 	else
4834 		tmpint = 1;
4835 	SASBADDINTDESC(sb, indent, tmpint, %d, compression_supported,
4836 	    "Set to 1 if compression is supported, 0 if not");
4837 	if (softc->flags & SA_FLAG_COMP_ENABLED)
4838 		tmpint = 1;
4839 	else
4840 		tmpint = 0;
4841 	SASBADDINTDESC(sb, indent, tmpint, %d, compression_enabled,
4842 	    "Set to 1 if compression is enabled, 0 if not");
4843 	SASBADDUINTDESC(sb, indent, softc->comp_algorithm, %u,
4844 	    compression_algorithm, "Numeric compression algorithm");
4845 
4846 	safillprot(softc, &indent, sb);
4847 
4848 	SASBADDUINTDESC(sb, indent, softc->media_blksize, %u,
4849 	    media_blocksize, "Block size reported by drive or set by user");
4850 	SASBADDINTDESC(sb, indent, (intmax_t)softc->fileno, %jd,
4851 	    calculated_fileno, "Calculated file number, -1 if unknown");
4852 	SASBADDINTDESC(sb, indent, (intmax_t)softc->blkno, %jd,
4853 	    calculated_rel_blkno, "Calculated block number relative to file, "
4854 	    "set to -1 if unknown");
4855 	SASBADDINTDESC(sb, indent, (intmax_t)softc->rep_fileno, %jd,
4856 	    reported_fileno, "File number reported by drive, -1 if unknown");
4857 	SASBADDINTDESC(sb, indent, (intmax_t)softc->rep_blkno, %jd,
4858 	    reported_blkno, "Block number relative to BOP/BOT reported by "
4859 	    "drive, -1 if unknown");
4860 	SASBADDINTDESC(sb, indent, (intmax_t)softc->partition, %jd,
4861 	    partition, "Current partition number, 0 is the default");
4862 	SASBADDINTDESC(sb, indent, softc->bop, %d, bop,
4863 	    "Set to 1 if drive is at the beginning of partition/tape, 0 if "
4864 	    "not, -1 if unknown");
4865 	SASBADDINTDESC(sb, indent, softc->eop, %d, eop,
4866 	    "Set to 1 if drive is past early warning, 0 if not, -1 if unknown");
4867 	SASBADDINTDESC(sb, indent, softc->bpew, %d, bpew,
4868 	    "Set to 1 if drive is past programmable early warning, 0 if not, "
4869 	    "-1 if unknown");
4870 	SASBADDINTDESC(sb, indent, (intmax_t)softc->last_io_resid, %jd,
4871 	    residual, "Residual for the last I/O");
4872 	/*
4873 	 * XXX KDM should we send a string with the current driver
4874 	 * status already decoded instead of a numeric value?
4875 	 */
4876 	SASBADDINTDESC(sb, indent, softc->dsreg, %d, dsreg,
4877 	    "Current state of the driver");
4878 
4879 	safilldensitysb(softc, &indent, sb);
4880 
4881 	SASBENDNODE(sb, indent, mtextget);
4882 
4883 extget_bailout:
4884 
4885 	return (error);
4886 }
4887 
4888 static int
4889 saparamget(struct sa_softc *softc, struct sbuf *sb)
4890 {
4891 	int indent;
4892 
4893 	indent = 0;
4894 	SASBADDNODE(sb, indent, mtparamget);
4895 	SASBADDINTDESC(sb, indent, softc->sili, %d, sili,
4896 	    "Suppress an error on underlength variable reads");
4897 	SASBADDINTDESC(sb, indent, softc->eot_warn, %d, eot_warn,
4898 	    "Return an error to warn that end of tape is approaching");
4899 	safillprot(softc, &indent, sb);
4900 	SASBENDNODE(sb, indent, mtparamget);
4901 
4902 	return (0);
4903 }
4904 
4905 static void
4906 saprevent(struct cam_periph *periph, int action)
4907 {
4908 	struct	sa_softc *softc;
4909 	union	ccb *ccb;
4910 	int	error, sf;
4911 
4912 	softc = (struct sa_softc *)periph->softc;
4913 
4914 	if ((action == PR_ALLOW) && (softc->flags & SA_FLAG_TAPE_LOCKED) == 0)
4915 		return;
4916 	if ((action == PR_PREVENT) && (softc->flags & SA_FLAG_TAPE_LOCKED) != 0)
4917 		return;
4918 
4919 	/*
4920 	 * We can be quiet about illegal requests.
4921 	 */
4922 	if (CAM_DEBUGGED(periph->path, CAM_DEBUG_INFO)) {
4923 		sf = 0;
4924 	} else
4925 		sf = SF_QUIET_IR;
4926 
4927 	ccb = cam_periph_getccb(periph, 1);
4928 
4929 	/* It is safe to retry this operation */
4930 	scsi_prevent(&ccb->csio, 5, NULL, MSG_SIMPLE_Q_TAG, action,
4931 	    SSD_FULL_SIZE, softc->timeout_info[SA_TIMEOUT_PREVENT]);
4932 
4933 	error = cam_periph_runccb(ccb, saerror, 0, sf, softc->device_stats);
4934 	if (error == 0) {
4935 		if (action == PR_ALLOW)
4936 			softc->flags &= ~SA_FLAG_TAPE_LOCKED;
4937 		else
4938 			softc->flags |= SA_FLAG_TAPE_LOCKED;
4939 	}
4940 
4941 	xpt_release_ccb(ccb);
4942 }
4943 
4944 static int
4945 sarewind(struct cam_periph *periph)
4946 {
4947 	union	ccb *ccb;
4948 	struct	sa_softc *softc;
4949 	int	error;
4950 
4951 	softc = (struct sa_softc *)periph->softc;
4952 
4953 	ccb = cam_periph_getccb(periph, 1);
4954 
4955 	/* It is safe to retry this operation */
4956 	scsi_rewind(&ccb->csio, 2, NULL, MSG_SIMPLE_Q_TAG, FALSE,
4957 	    SSD_FULL_SIZE, softc->timeout_info[SA_TIMEOUT_REWIND]);
4958 
4959 	softc->dsreg = MTIO_DSREG_REW;
4960 	error = cam_periph_runccb(ccb, saerror, 0, 0, softc->device_stats);
4961 	softc->dsreg = MTIO_DSREG_REST;
4962 
4963 	xpt_release_ccb(ccb);
4964 	if (error == 0) {
4965 		softc->partition = softc->fileno = softc->blkno = (daddr_t) 0;
4966 		softc->rep_fileno = softc->rep_blkno = (daddr_t) 0;
4967 	} else {
4968 		softc->fileno = softc->blkno = (daddr_t) -1;
4969 		softc->partition = (daddr_t) -1;
4970 		softc->rep_fileno = softc->rep_blkno = (daddr_t) -1;
4971 	}
4972 	return (error);
4973 }
4974 
4975 static int
4976 saspace(struct cam_periph *periph, int count, scsi_space_code code)
4977 {
4978 	union	ccb *ccb;
4979 	struct	sa_softc *softc;
4980 	int	error;
4981 
4982 	softc = (struct sa_softc *)periph->softc;
4983 
4984 	ccb = cam_periph_getccb(periph, 1);
4985 
4986 	/* This cannot be retried */
4987 
4988 	scsi_space(&ccb->csio, 0, NULL, MSG_SIMPLE_Q_TAG, code, count,
4989 	    SSD_FULL_SIZE, softc->timeout_info[SA_TIMEOUT_SPACE]);
4990 
4991 	/*
4992 	 * Clear residual because we will be using it.
4993 	 */
4994 	softc->last_ctl_resid = 0;
4995 
4996 	softc->dsreg = (count < 0)? MTIO_DSREG_REV : MTIO_DSREG_FWD;
4997 	error = cam_periph_runccb(ccb, saerror, 0, 0, softc->device_stats);
4998 	softc->dsreg = MTIO_DSREG_REST;
4999 
5000 	xpt_release_ccb(ccb);
5001 
5002 	/*
5003 	 * If a spacing operation has failed, we need to invalidate
5004 	 * this mount.
5005 	 *
5006 	 * If the spacing operation was setmarks or to end of recorded data,
5007 	 * we no longer know our relative position.
5008 	 *
5009 	 * If the spacing operations was spacing files in reverse, we
5010 	 * take account of the residual, but still check against less
5011 	 * than zero- if we've gone negative, we must have hit BOT.
5012 	 *
5013 	 * If the spacing operations was spacing records in reverse and
5014 	 * we have a residual, we've either hit BOT or hit a filemark.
5015 	 * In the former case, we know our new record number (0). In
5016 	 * the latter case, we have absolutely no idea what the real
5017 	 * record number is- we've stopped between the end of the last
5018 	 * record in the previous file and the filemark that stopped
5019 	 * our spacing backwards.
5020 	 */
5021 	if (error) {
5022 		softc->fileno = softc->blkno = (daddr_t) -1;
5023 		softc->rep_blkno = softc->partition = (daddr_t) -1;
5024 		softc->rep_fileno = (daddr_t) -1;
5025 	} else if (code == SS_SETMARKS || code == SS_EOD) {
5026 		softc->fileno = softc->blkno = (daddr_t) -1;
5027 	} else if (code == SS_FILEMARKS && softc->fileno != (daddr_t) -1) {
5028 		softc->fileno += (count - softc->last_ctl_resid);
5029 		if (softc->fileno < 0)	/* we must of hit BOT */
5030 			softc->fileno = 0;
5031 		softc->blkno = 0;
5032 	} else if (code == SS_BLOCKS && softc->blkno != (daddr_t) -1) {
5033 		softc->blkno += (count - softc->last_ctl_resid);
5034 		if (count < 0) {
5035 			if (softc->last_ctl_resid || softc->blkno < 0) {
5036 				if (softc->fileno == 0) {
5037 					softc->blkno = 0;
5038 				} else {
5039 					softc->blkno = (daddr_t) -1;
5040 				}
5041 			}
5042 		}
5043 	}
5044 	if (error == 0)
5045 		sagetpos(periph);
5046 
5047 	return (error);
5048 }
5049 
5050 static int
5051 sawritefilemarks(struct cam_periph *periph, int nmarks, int setmarks, int immed)
5052 {
5053 	union	ccb *ccb;
5054 	struct	sa_softc *softc;
5055 	int	error, nwm = 0;
5056 
5057 	softc = (struct sa_softc *)periph->softc;
5058 	if (softc->open_rdonly)
5059 		return (EBADF);
5060 
5061 	ccb = cam_periph_getccb(periph, 1);
5062 	/*
5063 	 * Clear residual because we will be using it.
5064 	 */
5065 	softc->last_ctl_resid = 0;
5066 
5067 	softc->dsreg = MTIO_DSREG_FMK;
5068 	/* this *must* not be retried */
5069 	scsi_write_filemarks(&ccb->csio, 0, NULL, MSG_SIMPLE_Q_TAG,
5070 	    immed, setmarks, nmarks, SSD_FULL_SIZE,
5071 	    softc->timeout_info[SA_TIMEOUT_WRITE_FILEMARKS]);
5072 	softc->dsreg = MTIO_DSREG_REST;
5073 
5074 	error = cam_periph_runccb(ccb, saerror, 0, 0, softc->device_stats);
5075 
5076 	if (error == 0 && nmarks) {
5077 		struct sa_softc *softc = (struct sa_softc *)periph->softc;
5078 		nwm = nmarks - softc->last_ctl_resid;
5079 		softc->filemarks += nwm;
5080 	}
5081 
5082 	xpt_release_ccb(ccb);
5083 
5084 	/*
5085 	 * Update relative positions (if we're doing that).
5086 	 */
5087 	if (error) {
5088 		softc->fileno = softc->blkno = softc->partition = (daddr_t) -1;
5089 	} else if (softc->fileno != (daddr_t) -1) {
5090 		softc->fileno += nwm;
5091 		softc->blkno = 0;
5092 	}
5093 
5094 	/*
5095 	 * Ask the tape drive for position information.
5096 	 */
5097 	sagetpos(periph);
5098 
5099 	/*
5100 	 * If we got valid position information, since we just wrote a file
5101 	 * mark, we know we're at the file mark and block 0 after that
5102 	 * filemark.
5103 	 */
5104 	if (softc->rep_fileno != (daddr_t) -1) {
5105 		softc->fileno = softc->rep_fileno;
5106 		softc->blkno = 0;
5107 	}
5108 
5109 	return (error);
5110 }
5111 
5112 static int
5113 sagetpos(struct cam_periph *periph)
5114 {
5115 	union ccb *ccb;
5116 	struct scsi_tape_position_long_data long_pos;
5117 	struct sa_softc *softc = (struct sa_softc *)periph->softc;
5118 	int error;
5119 
5120 	if (softc->quirks & SA_QUIRK_NO_LONG_POS) {
5121 		softc->rep_fileno = (daddr_t) -1;
5122 		softc->rep_blkno = (daddr_t) -1;
5123 		softc->bop = softc->eop = softc->bpew = -1;
5124 		return (EOPNOTSUPP);
5125 	}
5126 
5127 	bzero(&long_pos, sizeof(long_pos));
5128 
5129 	ccb = cam_periph_getccb(periph, CAM_PRIORITY_NORMAL);
5130 	scsi_read_position_10(&ccb->csio,
5131 			      /*retries*/ 1,
5132 			      /*cbfcnp*/ NULL,
5133 			      /*tag_action*/ MSG_SIMPLE_Q_TAG,
5134 			      /*service_action*/ SA_RPOS_LONG_FORM,
5135 			      /*data_ptr*/ (uint8_t *)&long_pos,
5136 			      /*length*/ sizeof(long_pos),
5137 			      /*sense_len*/ SSD_FULL_SIZE,
5138 			      /*timeout*/
5139 				 softc->timeout_info[SA_TIMEOUT_READ_POSITION]);
5140 
5141 	softc->dsreg = MTIO_DSREG_RBSY;
5142 	error = cam_periph_runccb(ccb, saerror, 0, SF_QUIET_IR,
5143 				  softc->device_stats);
5144 	softc->dsreg = MTIO_DSREG_REST;
5145 
5146 	if (error == 0) {
5147 		if (long_pos.flags & SA_RPOS_LONG_MPU) {
5148 			/*
5149 			 * If the drive doesn't know what file mark it is
5150 			 * on, our calculated filemark isn't going to be
5151 			 * accurate either.
5152 			 */
5153 			softc->fileno = (daddr_t) -1;
5154 			softc->rep_fileno = (daddr_t) -1;
5155 		} else {
5156 			softc->fileno = softc->rep_fileno =
5157 			    scsi_8btou64(long_pos.logical_file_num);
5158 		}
5159 
5160 		if (long_pos.flags & SA_RPOS_LONG_LONU) {
5161 			softc->partition = (daddr_t) -1;
5162 			softc->rep_blkno = (daddr_t) -1;
5163 			/*
5164 			 * If the tape drive doesn't know its block
5165 			 * position, we can't claim to know it either.
5166 			 */
5167 			softc->blkno = (daddr_t) -1;
5168 		} else {
5169 			softc->partition = scsi_4btoul(long_pos.partition);
5170 			softc->rep_blkno =
5171 			    scsi_8btou64(long_pos.logical_object_num);
5172 		}
5173 		if (long_pos.flags & SA_RPOS_LONG_BOP)
5174 			softc->bop = 1;
5175 		else
5176 			softc->bop = 0;
5177 
5178 		if (long_pos.flags & SA_RPOS_LONG_EOP)
5179 			softc->eop = 1;
5180 		else
5181 			softc->eop = 0;
5182 
5183 		if ((long_pos.flags & SA_RPOS_LONG_BPEW)
5184 		 || (softc->set_pews_status != 0)) {
5185 			softc->bpew = 1;
5186 			if (softc->set_pews_status > 0)
5187 				softc->set_pews_status--;
5188 		} else
5189 			softc->bpew = 0;
5190 	} else if (error == EINVAL) {
5191 		/*
5192 		 * If this drive returned an invalid-request type error,
5193 		 * then it likely doesn't support the long form report.
5194 		 */
5195 		softc->quirks |= SA_QUIRK_NO_LONG_POS;
5196 	}
5197 
5198 	if (error != 0) {
5199 		softc->rep_fileno = softc->rep_blkno = (daddr_t) -1;
5200 		softc->partition = (daddr_t) -1;
5201 		softc->bop = softc->eop = softc->bpew = -1;
5202 	}
5203 
5204 	xpt_release_ccb(ccb);
5205 
5206 	return (error);
5207 }
5208 
5209 static int
5210 sardpos(struct cam_periph *periph, int hard, uint32_t *blkptr)
5211 {
5212 	struct scsi_tape_position_data loc;
5213 	union ccb *ccb;
5214 	struct sa_softc *softc = (struct sa_softc *)periph->softc;
5215 	int error;
5216 
5217 	/*
5218 	 * We try and flush any buffered writes here if we were writing
5219 	 * and we're trying to get hardware block position. It eats
5220 	 * up performance substantially, but I'm wary of drive firmware.
5221 	 *
5222 	 * I think that *logical* block position is probably okay-
5223 	 * but hardware block position might have to wait for data
5224 	 * to hit media to be valid. Caveat Emptor.
5225 	 */
5226 
5227 	if (hard && (softc->flags & SA_FLAG_TAPE_WRITTEN)) {
5228 		error = sawritefilemarks(periph, 0, 0, 0);
5229 		if (error && error != EACCES)
5230 			return (error);
5231 	}
5232 
5233 	ccb = cam_periph_getccb(periph, 1);
5234 	scsi_read_position(&ccb->csio, 1, NULL, MSG_SIMPLE_Q_TAG,
5235 	    hard, &loc, SSD_FULL_SIZE,
5236 	    softc->timeout_info[SA_TIMEOUT_READ_POSITION]);
5237 	softc->dsreg = MTIO_DSREG_RBSY;
5238 	error = cam_periph_runccb(ccb, saerror, 0, 0, softc->device_stats);
5239 	softc->dsreg = MTIO_DSREG_REST;
5240 
5241 	if (error == 0) {
5242 		if (loc.flags & SA_RPOS_UNCERTAIN) {
5243 			error = EINVAL;		/* nothing is certain */
5244 		} else {
5245 			*blkptr = scsi_4btoul(loc.firstblk);
5246 		}
5247 	}
5248 
5249 	xpt_release_ccb(ccb);
5250 	return (error);
5251 }
5252 
5253 static int
5254 sasetpos(struct cam_periph *periph, int hard, struct mtlocate *locate_info)
5255 {
5256 	union ccb *ccb;
5257 	struct sa_softc *softc;
5258 	int locate16;
5259 	int immed, cp;
5260 	int error;
5261 
5262 	/*
5263 	 * We used to try and flush any buffered writes here.
5264 	 * Now we push this onto user applications to either
5265 	 * flush the pending writes themselves (via a zero count
5266 	 * WRITE FILEMARKS command) or they can trust their tape
5267 	 * drive to do this correctly for them.
5268  	 */
5269 
5270 	softc = (struct sa_softc *)periph->softc;
5271 	ccb = cam_periph_getccb(periph, 1);
5272 
5273 	cp = locate_info->flags & MT_LOCATE_FLAG_CHANGE_PART ? 1 : 0;
5274 	immed = locate_info->flags & MT_LOCATE_FLAG_IMMED ? 1 : 0;
5275 
5276 	/*
5277 	 * Determine whether we have to use LOCATE or LOCATE16.  The hard
5278 	 * bit is only possible with LOCATE, but the new ioctls do not
5279 	 * allow setting that bit.  So we can't get into the situation of
5280 	 * having the hard bit set with a block address that is larger than
5281 	 * 32-bits.
5282 	 */
5283 	if (hard != 0)
5284 		locate16 = 0;
5285 	else if ((locate_info->dest_type != MT_LOCATE_DEST_OBJECT)
5286 	      || (locate_info->block_address_mode != MT_LOCATE_BAM_IMPLICIT)
5287 	      || (locate_info->logical_id > SA_SPOS_MAX_BLK))
5288 		locate16 = 1;
5289 	else
5290 		locate16 = 0;
5291 
5292 	if (locate16 != 0) {
5293 		scsi_locate_16(&ccb->csio,
5294 			       /*retries*/ 1,
5295 			       /*cbfcnp*/ NULL,
5296 			       /*tag_action*/ MSG_SIMPLE_Q_TAG,
5297 			       /*immed*/ immed,
5298 			       /*cp*/ cp,
5299 			       /*dest_type*/ locate_info->dest_type,
5300 			       /*bam*/ locate_info->block_address_mode,
5301 			       /*partition*/ locate_info->partition,
5302 			       /*logical_id*/ locate_info->logical_id,
5303 			       /*sense_len*/ SSD_FULL_SIZE,
5304 			       /*timeout*/
5305 				   softc->timeout_info[SA_TIMEOUT_LOCATE]);
5306 	} else {
5307 		scsi_locate_10(&ccb->csio,
5308 			       /*retries*/ 1,
5309 			       /*cbfcnp*/ NULL,
5310 			       /*tag_action*/ MSG_SIMPLE_Q_TAG,
5311 			       /*immed*/ immed,
5312 			       /*cp*/ cp,
5313 			       /*hard*/ hard,
5314 			       /*partition*/ locate_info->partition,
5315 			       /*block_address*/ locate_info->logical_id,
5316 			       /*sense_len*/ SSD_FULL_SIZE,
5317 			       /*timeout*/
5318 				   softc->timeout_info[SA_TIMEOUT_LOCATE]);
5319 	}
5320 
5321 	softc->dsreg = MTIO_DSREG_POS;
5322 	error = cam_periph_runccb(ccb, saerror, 0, 0, softc->device_stats);
5323 	softc->dsreg = MTIO_DSREG_REST;
5324 	xpt_release_ccb(ccb);
5325 
5326 	/*
5327 	 * We assume the calculated file and block numbers are unknown
5328 	 * unless we have enough information to populate them.
5329 	 */
5330 	softc->fileno = softc->blkno = (daddr_t) -1;
5331 
5332 	/*
5333 	 * If the user requested changing the partition and the request
5334 	 * succeeded, note the partition.
5335 	 */
5336 	if ((error == 0)
5337 	 && (cp != 0))
5338 		softc->partition = locate_info->partition;
5339 	else
5340 		softc->partition = (daddr_t) -1;
5341 
5342 	if (error == 0) {
5343 		switch (locate_info->dest_type) {
5344 		case MT_LOCATE_DEST_FILE:
5345 			/*
5346 			 * This is the only case where we can reliably
5347 			 * calculate the file and block numbers.
5348 			 */
5349 			softc->fileno = locate_info->logical_id;
5350 			softc->blkno = 0;
5351 			break;
5352 		case MT_LOCATE_DEST_OBJECT:
5353 		case MT_LOCATE_DEST_SET:
5354 		case MT_LOCATE_DEST_EOD:
5355 		default:
5356 			break;
5357 		}
5358 	}
5359 
5360 	/*
5361 	 * Ask the drive for current position information.
5362 	 */
5363 	sagetpos(periph);
5364 
5365 	return (error);
5366 }
5367 
5368 static int
5369 saretension(struct cam_periph *periph)
5370 {
5371 	union ccb *ccb;
5372 	struct sa_softc *softc;
5373 	int error;
5374 
5375 	softc = (struct sa_softc *)periph->softc;
5376 
5377 	ccb = cam_periph_getccb(periph, 1);
5378 
5379 	/* It is safe to retry this operation */
5380 	scsi_load_unload(&ccb->csio, 5, NULL, MSG_SIMPLE_Q_TAG, FALSE,
5381 	    FALSE, TRUE,  TRUE, SSD_FULL_SIZE,
5382 	    softc->timeout_info[SA_TIMEOUT_LOAD]);
5383 
5384 	softc->dsreg = MTIO_DSREG_TEN;
5385 	error = cam_periph_runccb(ccb, saerror, 0, 0, softc->device_stats);
5386 	softc->dsreg = MTIO_DSREG_REST;
5387 
5388 	xpt_release_ccb(ccb);
5389 	if (error == 0) {
5390 		softc->partition = softc->fileno = softc->blkno = (daddr_t) 0;
5391 		sagetpos(periph);
5392 	} else
5393 		softc->partition = softc->fileno = softc->blkno = (daddr_t) -1;
5394 	return (error);
5395 }
5396 
5397 static int
5398 sareservereleaseunit(struct cam_periph *periph, int reserve)
5399 {
5400 	union ccb *ccb;
5401 	struct sa_softc *softc;
5402 	int error;
5403 
5404 	softc = (struct sa_softc *)periph->softc;
5405 	ccb = cam_periph_getccb(periph,  1);
5406 
5407 	/* It is safe to retry this operation */
5408 	scsi_reserve_release_unit(&ccb->csio, 2, NULL, MSG_SIMPLE_Q_TAG,
5409 	    FALSE,  0, SSD_FULL_SIZE,  softc->timeout_info[SA_TIMEOUT_RESERVE],
5410 	    reserve);
5411 	softc->dsreg = MTIO_DSREG_RBSY;
5412 	error = cam_periph_runccb(ccb, saerror, 0,
5413 	    SF_RETRY_UA | SF_NO_PRINT, softc->device_stats);
5414 	softc->dsreg = MTIO_DSREG_REST;
5415 	xpt_release_ccb(ccb);
5416 
5417 	/*
5418 	 * If the error was Illegal Request, then the device doesn't support
5419 	 * RESERVE/RELEASE. This is not an error.
5420 	 */
5421 	if (error == EINVAL) {
5422 		error = 0;
5423 	}
5424 
5425 	return (error);
5426 }
5427 
5428 static int
5429 saloadunload(struct cam_periph *periph, int load)
5430 {
5431 	union	ccb *ccb;
5432 	struct	sa_softc *softc;
5433 	int	error;
5434 
5435 	softc = (struct sa_softc *)periph->softc;
5436 
5437 	ccb = cam_periph_getccb(periph, 1);
5438 
5439 	/* It is safe to retry this operation */
5440 	scsi_load_unload(&ccb->csio, 5, NULL, MSG_SIMPLE_Q_TAG, FALSE,
5441 	    FALSE, FALSE, load, SSD_FULL_SIZE,
5442 	    softc->timeout_info[SA_TIMEOUT_LOAD]);
5443 
5444 	softc->dsreg = (load)? MTIO_DSREG_LD : MTIO_DSREG_UNL;
5445 	error = cam_periph_runccb(ccb, saerror, 0, 0, softc->device_stats);
5446 	softc->dsreg = MTIO_DSREG_REST;
5447 	xpt_release_ccb(ccb);
5448 
5449 	if (error || load == 0) {
5450 		softc->partition = softc->fileno = softc->blkno = (daddr_t) -1;
5451 		softc->rep_fileno = softc->rep_blkno = (daddr_t) -1;
5452 	} else if (error == 0) {
5453 		softc->partition = softc->fileno = softc->blkno = (daddr_t) 0;
5454 		sagetpos(periph);
5455 	}
5456 	return (error);
5457 }
5458 
5459 static int
5460 saerase(struct cam_periph *periph, int longerase)
5461 {
5462 
5463 	union	ccb *ccb;
5464 	struct	sa_softc *softc;
5465 	int error;
5466 
5467 	softc = (struct sa_softc *)periph->softc;
5468 	if (softc->open_rdonly)
5469 		return (EBADF);
5470 
5471 	ccb = cam_periph_getccb(periph, 1);
5472 
5473 	scsi_erase(&ccb->csio, 1, NULL, MSG_SIMPLE_Q_TAG, FALSE, longerase,
5474 	    SSD_FULL_SIZE, softc->timeout_info[SA_TIMEOUT_ERASE]);
5475 
5476 	softc->dsreg = MTIO_DSREG_ZER;
5477 	error = cam_periph_runccb(ccb, saerror, 0, 0, softc->device_stats);
5478 	softc->dsreg = MTIO_DSREG_REST;
5479 
5480 	xpt_release_ccb(ccb);
5481 	return (error);
5482 }
5483 
5484 /*
5485  * Fill an sbuf with density data in XML format.  This particular macro
5486  * works for multi-byte integer fields.
5487  *
5488  * Note that 1 byte fields aren't supported here.  The reason is that the
5489  * compiler does not evaluate the sizeof(), and assumes that any of the
5490  * sizes are possible for a given field.  So passing in a multi-byte
5491  * field will result in a warning that the assignment makes an integer
5492  * from a pointer without a cast, if there is an assignment in the 1 byte
5493  * case.
5494  */
5495 #define	SAFILLDENSSB(dens_data, sb, indent, field, desc_remain, 	\
5496 		     len_to_go, cur_offset, desc){			\
5497 	size_t cur_field_len;						\
5498 									\
5499 	cur_field_len = sizeof(dens_data->field);			\
5500 	if (desc_remain < cur_field_len) {				\
5501 		len_to_go -= desc_remain;				\
5502 		cur_offset += desc_remain;				\
5503 		continue;						\
5504 	}								\
5505 	len_to_go -= cur_field_len;					\
5506 	cur_offset += cur_field_len;					\
5507 	desc_remain -= cur_field_len;					\
5508 									\
5509 	switch (sizeof(dens_data->field)) {				\
5510 	case 1:								\
5511 		KASSERT(1 == 0, ("Programmer error, invalid 1 byte "	\
5512 			"field width for SAFILLDENSFIELD"));		\
5513 		break;							\
5514 	case 2:								\
5515 		SASBADDUINTDESC(sb, indent,				\
5516 		    scsi_2btoul(dens_data->field), %u, field, desc);	\
5517 		break;							\
5518 	case 3:								\
5519 		SASBADDUINTDESC(sb, indent,				\
5520 		    scsi_3btoul(dens_data->field), %u, field, desc);	\
5521 		break;							\
5522 	case 4:								\
5523 		SASBADDUINTDESC(sb, indent,				\
5524 		    scsi_4btoul(dens_data->field), %u, field, desc);	\
5525 		break;							\
5526 	case 8:								\
5527 		SASBADDUINTDESC(sb, indent, 				\
5528 		    (uintmax_t)scsi_8btou64(dens_data->field),	%ju, 	\
5529 		    field, desc);					\
5530 		break;							\
5531 	default:							\
5532 		break;							\
5533 	}								\
5534 };
5535 /*
5536  * Fill an sbuf with density data in XML format.  This particular macro
5537  * works for strings.
5538  */
5539 #define	SAFILLDENSSBSTR(dens_data, sb, indent, field, desc_remain, 	\
5540 			len_to_go, cur_offset, desc){			\
5541 	size_t cur_field_len;						\
5542 	char tmpstr[32];						\
5543 									\
5544 	cur_field_len = sizeof(dens_data->field);			\
5545 	if (desc_remain < cur_field_len) {				\
5546 		len_to_go -= desc_remain;				\
5547 		cur_offset += desc_remain;				\
5548 		continue;						\
5549 	}								\
5550 	len_to_go -= cur_field_len;					\
5551 	cur_offset += cur_field_len;					\
5552 	desc_remain -= cur_field_len;					\
5553 									\
5554 	cam_strvis(tmpstr, dens_data->field,				\
5555 	    sizeof(dens_data->field), sizeof(tmpstr));			\
5556 	SASBADDVARSTRDESC(sb, indent, tmpstr, %s, field,		\
5557 	    strlen(tmpstr) + 1, desc);					\
5558 };
5559 
5560 /*
5561  * Fill an sbuf with density data descriptors.
5562  */
5563 static void
5564 safilldenstypesb(struct sbuf *sb, int *indent, uint8_t *buf, int buf_len,
5565     int is_density)
5566 {
5567 	struct scsi_density_hdr *hdr;
5568 	uint32_t hdr_len;
5569 	int len_to_go, cur_offset;
5570 	int length_offset;
5571 	int num_reports, need_close;
5572 
5573 	/*
5574 	 * We need at least the header length.  Note that this isn't an
5575 	 * error, not all tape drives will have every data type.
5576 	 */
5577 	if (buf_len < sizeof(*hdr))
5578 		goto bailout;
5579 
5580 	hdr = (struct scsi_density_hdr *)buf;
5581 	hdr_len = scsi_2btoul(hdr->length);
5582 	len_to_go = min(buf_len - sizeof(*hdr), hdr_len);
5583 	if (is_density) {
5584 		length_offset = __offsetof(struct scsi_density_data,
5585 		    bits_per_mm);
5586 	} else {
5587 		length_offset = __offsetof(struct scsi_medium_type_data,
5588 		    num_density_codes);
5589 	}
5590 	cur_offset = sizeof(*hdr);
5591 
5592 	num_reports = 0;
5593 	need_close = 0;
5594 
5595 	while (len_to_go > length_offset) {
5596 		struct scsi_density_data *dens_data;
5597 		struct scsi_medium_type_data *type_data;
5598 		int desc_remain;
5599 		size_t cur_field_len;
5600 
5601 		dens_data = NULL;
5602 		type_data = NULL;
5603 
5604 		if (is_density) {
5605 			dens_data =(struct scsi_density_data *)&buf[cur_offset];
5606 			if (dens_data->byte2 & SDD_DLV)
5607 				desc_remain = scsi_2btoul(dens_data->length);
5608 			else
5609 				desc_remain = SDD_DEFAULT_LENGTH -
5610 				    length_offset;
5611 		} else {
5612 			type_data = (struct scsi_medium_type_data *)
5613 			    &buf[cur_offset];
5614 			desc_remain = scsi_2btoul(type_data->length);
5615 		}
5616 
5617 		len_to_go -= length_offset;
5618 		desc_remain = min(desc_remain, len_to_go);
5619 		cur_offset += length_offset;
5620 
5621 		if (need_close != 0) {
5622 			SASBENDNODE(sb, *indent, density_entry);
5623 		}
5624 
5625 		SASBADDNODENUM(sb, *indent, density_entry, num_reports);
5626 		num_reports++;
5627 		need_close = 1;
5628 
5629 		if (is_density) {
5630 			SASBADDUINTDESC(sb, *indent,
5631 			    dens_data->primary_density_code, %u,
5632 			    primary_density_code, "Primary Density Code");
5633 			SASBADDUINTDESC(sb, *indent,
5634 			    dens_data->secondary_density_code, %u,
5635 			    secondary_density_code, "Secondary Density Code");
5636 			SASBADDUINTDESC(sb, *indent,
5637 			    dens_data->byte2 & ~SDD_DLV, %#x, density_flags,
5638 			    "Density Flags");
5639 
5640 			SAFILLDENSSB(dens_data, sb, *indent, bits_per_mm,
5641 			    desc_remain, len_to_go, cur_offset, "Bits per mm");
5642 			SAFILLDENSSB(dens_data, sb, *indent, media_width,
5643 			    desc_remain, len_to_go, cur_offset, "Media width");
5644 			SAFILLDENSSB(dens_data, sb, *indent, tracks,
5645 			    desc_remain, len_to_go, cur_offset,
5646 			    "Number of Tracks");
5647 			SAFILLDENSSB(dens_data, sb, *indent, capacity,
5648 			    desc_remain, len_to_go, cur_offset, "Capacity");
5649 
5650 			SAFILLDENSSBSTR(dens_data, sb, *indent, assigning_org,
5651 			    desc_remain, len_to_go, cur_offset,
5652 			    "Assigning Organization");
5653 
5654 			SAFILLDENSSBSTR(dens_data, sb, *indent, density_name,
5655 			    desc_remain, len_to_go, cur_offset, "Density Name");
5656 
5657 			SAFILLDENSSBSTR(dens_data, sb, *indent, description,
5658 			    desc_remain, len_to_go, cur_offset, "Description");
5659 		} else {
5660 			int i;
5661 
5662 			SASBADDUINTDESC(sb, *indent, type_data->medium_type,
5663 			    %u, medium_type, "Medium Type");
5664 
5665 			cur_field_len =
5666 			    __offsetof(struct scsi_medium_type_data,
5667 				       media_width) -
5668 			    __offsetof(struct scsi_medium_type_data,
5669 				       num_density_codes);
5670 
5671 			if (desc_remain < cur_field_len) {
5672 				len_to_go -= desc_remain;
5673 				cur_offset += desc_remain;
5674 				continue;
5675 			}
5676 			len_to_go -= cur_field_len;
5677 			cur_offset += cur_field_len;
5678 			desc_remain -= cur_field_len;
5679 
5680 			SASBADDINTDESC(sb, *indent,
5681 			    type_data->num_density_codes, %d,
5682 			    num_density_codes, "Number of Density Codes");
5683 			SASBADDNODE(sb, *indent, density_code_list);
5684 			for (i = 0; i < type_data->num_density_codes;
5685 			     i++) {
5686 				SASBADDUINTDESC(sb, *indent,
5687 				    type_data->primary_density_codes[i], %u,
5688 				    density_code, "Density Code");
5689 			}
5690 			SASBENDNODE(sb, *indent, density_code_list);
5691 
5692 			SAFILLDENSSB(type_data, sb, *indent, media_width,
5693 			    desc_remain, len_to_go, cur_offset,
5694 			    "Media width");
5695 			SAFILLDENSSB(type_data, sb, *indent, medium_length,
5696 			    desc_remain, len_to_go, cur_offset,
5697 			    "Medium length");
5698 
5699 			/*
5700 			 * Account for the two reserved bytes.
5701 			 */
5702 			cur_field_len = sizeof(type_data->reserved2);
5703 			if (desc_remain < cur_field_len) {
5704 				len_to_go -= desc_remain;
5705 				cur_offset += desc_remain;
5706 				continue;
5707 			}
5708 			len_to_go -= cur_field_len;
5709 			cur_offset += cur_field_len;
5710 			desc_remain -= cur_field_len;
5711 
5712 			SAFILLDENSSBSTR(type_data, sb, *indent, assigning_org,
5713 			    desc_remain, len_to_go, cur_offset,
5714 			    "Assigning Organization");
5715 			SAFILLDENSSBSTR(type_data, sb, *indent,
5716 			    medium_type_name, desc_remain, len_to_go,
5717 			    cur_offset, "Medium type name");
5718 			SAFILLDENSSBSTR(type_data, sb, *indent, description,
5719 			    desc_remain, len_to_go, cur_offset, "Description");
5720 		}
5721 	}
5722 	if (need_close != 0) {
5723 		SASBENDNODE(sb, *indent, density_entry);
5724 	}
5725 
5726 bailout:
5727 	return;
5728 }
5729 
5730 /*
5731  * Fill an sbuf with density data information
5732  */
5733 static void
5734 safilldensitysb(struct sa_softc *softc, int *indent, struct sbuf *sb)
5735 {
5736 	int i, is_density;
5737 
5738 	SASBADDNODE(sb, *indent, mtdensity);
5739 	SASBADDUINTDESC(sb, *indent, softc->media_density, %u, media_density,
5740 	    "Current Medium Density");
5741 	is_density = 0;
5742 	for (i = 0; i < SA_DENSITY_TYPES; i++) {
5743 		int tmpint;
5744 
5745 		if (softc->density_info_valid[i] == 0)
5746 			continue;
5747 
5748 		SASBADDNODE(sb, *indent, density_report);
5749 		if (softc->density_type_bits[i] & SRDS_MEDIUM_TYPE) {
5750 			tmpint = 1;
5751 			is_density = 0;
5752 		} else {
5753 			tmpint = 0;
5754 			is_density = 1;
5755 		}
5756 		SASBADDINTDESC(sb, *indent, tmpint, %d, medium_type_report,
5757 		    "Medium type report");
5758 
5759 		if (softc->density_type_bits[i] & SRDS_MEDIA)
5760 			tmpint = 1;
5761 		else
5762 			tmpint = 0;
5763 		SASBADDINTDESC(sb, *indent, tmpint, %d, media_report,
5764 		    "Media report");
5765 
5766 		safilldenstypesb(sb, indent, softc->density_info[i],
5767 		    softc->density_info_valid[i], is_density);
5768 		SASBENDNODE(sb, *indent, density_report);
5769 	}
5770 	SASBENDNODE(sb, *indent, mtdensity);
5771 }
5772 
5773 /*
5774  * Given a completed REPORT SUPPORTED OPERATION CODES command with timeout
5775  * descriptors, go through the descriptors and set the sa(4) driver
5776  * timeouts to the recommended values.
5777  */
5778 static void
5779 saloadtimeouts(struct sa_softc *softc, union ccb *ccb)
5780 {
5781 	uint32_t valid_len, avail_len = 0, used_len = 0;
5782 	struct scsi_report_supported_opcodes_all *hdr;
5783 	struct scsi_report_supported_opcodes_descr *desc;
5784 	uint8_t *buf;
5785 
5786 	hdr = (struct scsi_report_supported_opcodes_all *)ccb->csio.data_ptr;
5787 	valid_len = ccb->csio.dxfer_len - ccb->csio.resid;
5788 
5789 	if (valid_len < sizeof(*hdr))
5790 		return;
5791 
5792 	avail_len = scsi_4btoul(hdr->length) + sizeof(hdr->length);
5793 	if ((avail_len != 0)
5794 	 && (avail_len > valid_len)) {
5795 		xpt_print(softc->periph->path, "WARNING: available timeout "
5796 		    "descriptor len %zu > valid len %u\n", avail_len,valid_len);
5797 	}
5798 
5799 	used_len = sizeof(hdr->length);
5800 	avail_len = MIN(avail_len, valid_len - sizeof(*hdr));
5801 	buf = ccb->csio.data_ptr;
5802 	while ((avail_len - used_len) > sizeof(*desc)) {
5803 		struct scsi_report_supported_opcodes_timeout *td;
5804 		uint32_t td_len;
5805 		uint32_t rec_time;
5806 		uint8_t *cur_ptr;
5807 
5808 		cur_ptr = &buf[used_len];
5809 		desc = (struct scsi_report_supported_opcodes_descr *)cur_ptr;
5810 
5811 		used_len += sizeof(*desc);
5812 		/* If there's no timeout descriptor, keep going */
5813 		if ((desc->flags & RSO_CTDP) == 0)
5814 			continue;
5815 
5816 		/*
5817 		 * If we don't have enough space to fit a timeout
5818 		 * descriptor then we're done.
5819 		 */
5820 		if ((avail_len - used_len) < sizeof(*td)) {
5821 			used_len = avail_len;
5822 			continue;
5823 		}
5824 
5825 		cur_ptr = &buf[used_len];
5826 		td = (struct scsi_report_supported_opcodes_timeout *)cur_ptr;
5827 		td_len = scsi_2btoul(td->length);
5828 		td_len += sizeof(td->length);
5829 		used_len += td_len;
5830 
5831 		if (td_len < sizeof(*td))
5832 			continue;
5833 
5834 		/*
5835 		 * Use the recommended timeout.  The nominal time is the
5836 		 * time to wait before querying for status.
5837 		 */
5838 		rec_time = scsi_4btoul(td->recommended_time);
5839 
5840 		/*
5841 		 * Our timeouts are set in thousandths of a seconds.
5842 		 */
5843 		rec_time *= 1000;
5844 
5845 		switch(desc->opcode) {
5846 		case ERASE:
5847 			softc->timeout_info[SA_TIMEOUT_ERASE] = rec_time;
5848 			break;
5849 		case LOAD_UNLOAD:
5850 			softc->timeout_info[SA_TIMEOUT_LOAD] = rec_time;
5851 			break;
5852 		case LOCATE:
5853 		case LOCATE_16:
5854 			/*
5855 			 * We are assuming these are the same timeout.
5856 			 */
5857 			softc->timeout_info[SA_TIMEOUT_LOCATE] = rec_time;
5858 			break;
5859 		case MODE_SELECT_6:
5860 		case MODE_SELECT_10:
5861 			/*
5862 			 * We are assuming these are the same timeout.
5863 			 */
5864 			softc->timeout_info[SA_TIMEOUT_MODE_SELECT] = rec_time;
5865 			break;
5866 		case MODE_SENSE_6:
5867 		case MODE_SENSE_10:
5868 			/*
5869 			 * We are assuming these are the same timeout.
5870 			 */
5871 			softc->timeout_info[SA_TIMEOUT_MODE_SENSE] = rec_time;
5872 			break;
5873 		case PREVENT_ALLOW:
5874 			softc->timeout_info[SA_TIMEOUT_PREVENT] = rec_time;
5875 			break;
5876 		case SA_READ:
5877 			softc->timeout_info[SA_TIMEOUT_READ] = rec_time;
5878 			break;
5879 		case READ_BLOCK_LIMITS:
5880 			softc->timeout_info[SA_TIMEOUT_READ_BLOCK_LIMITS] =
5881 			    rec_time;
5882 			break;
5883 		case READ_POSITION:
5884 			/*
5885 			 * Note that this may show up multiple times for
5886 			 * the short form, long form and extended form
5887 			 * service actions.  We're assuming they are all
5888 			 * the same.
5889 			 */
5890 			softc->timeout_info[SA_TIMEOUT_READ_POSITION] =rec_time;
5891 			break;
5892 		case REPORT_DENSITY_SUPPORT:
5893 			softc->timeout_info[SA_TIMEOUT_REP_DENSITY] = rec_time;
5894 			break;
5895 		case RESERVE_UNIT:
5896 		case RELEASE_UNIT:
5897 			/* We are assuming these are the same timeout.*/
5898 			softc->timeout_info[SA_TIMEOUT_RESERVE] = rec_time;
5899 			break;
5900 		case REWIND:
5901 			softc->timeout_info[SA_TIMEOUT_REWIND] = rec_time;
5902 			break;
5903 		case SPACE:
5904 			softc->timeout_info[SA_TIMEOUT_SPACE] = rec_time;
5905 			break;
5906 		case TEST_UNIT_READY:
5907 			softc->timeout_info[SA_TIMEOUT_TUR] = rec_time;
5908 			break;
5909 		case SA_WRITE:
5910 			softc->timeout_info[SA_TIMEOUT_WRITE] = rec_time;
5911 			break;
5912 		case WRITE_FILEMARKS:
5913 			softc->timeout_info[SA_TIMEOUT_WRITE_FILEMARKS] =
5914 			    rec_time;
5915 			break;
5916 		default:
5917 			/*
5918 			 * We have explicit cases for all of the timeouts
5919 			 * we use.
5920 			 */
5921 			break;
5922 		}
5923 	}
5924 }
5925 
5926 #endif /* _KERNEL */
5927 
5928 /*
5929  * Read tape block limits command.
5930  */
5931 void
5932 scsi_read_block_limits(struct ccb_scsiio *csio, uint32_t retries,
5933 		   void (*cbfcnp)(struct cam_periph *, union ccb *),
5934 		   uint8_t tag_action,
5935 		   struct scsi_read_block_limits_data *rlimit_buf,
5936 		   uint8_t sense_len, uint32_t timeout)
5937 {
5938 	struct scsi_read_block_limits *scsi_cmd;
5939 
5940 	cam_fill_csio(csio, retries, cbfcnp, CAM_DIR_IN, tag_action,
5941 	     (uint8_t *)rlimit_buf, sizeof(*rlimit_buf), sense_len,
5942 	     sizeof(*scsi_cmd), timeout);
5943 
5944 	scsi_cmd = (struct scsi_read_block_limits *)&csio->cdb_io.cdb_bytes;
5945 	bzero(scsi_cmd, sizeof(*scsi_cmd));
5946 	scsi_cmd->opcode = READ_BLOCK_LIMITS;
5947 }
5948 
5949 void
5950 scsi_sa_read_write(struct ccb_scsiio *csio, uint32_t retries,
5951 		   void (*cbfcnp)(struct cam_periph *, union ccb *),
5952 		   uint8_t tag_action, int readop, int sli,
5953 		   int fixed, uint32_t length, uint8_t *data_ptr,
5954 		   uint32_t dxfer_len, uint8_t sense_len, uint32_t timeout)
5955 {
5956 	struct scsi_sa_rw *scsi_cmd;
5957 	int read;
5958 
5959 	read = (readop & SCSI_RW_DIRMASK) == SCSI_RW_READ;
5960 
5961 	scsi_cmd = (struct scsi_sa_rw *)&csio->cdb_io.cdb_bytes;
5962 	scsi_cmd->opcode = read ? SA_READ : SA_WRITE;
5963 	scsi_cmd->sli_fixed = 0;
5964 	if (sli && read)
5965 		scsi_cmd->sli_fixed |= SAR_SLI;
5966 	if (fixed)
5967 		scsi_cmd->sli_fixed |= SARW_FIXED;
5968 	scsi_ulto3b(length, scsi_cmd->length);
5969 	scsi_cmd->control = 0;
5970 
5971 	cam_fill_csio(csio, retries, cbfcnp, (read ? CAM_DIR_IN : CAM_DIR_OUT) |
5972 	    ((readop & SCSI_RW_BIO) != 0 ? CAM_DATA_BIO : 0),
5973 	    tag_action, data_ptr, dxfer_len, sense_len,
5974 	    sizeof(*scsi_cmd), timeout);
5975 }
5976 
5977 void
5978 scsi_load_unload(struct ccb_scsiio *csio, uint32_t retries,
5979 		 void (*cbfcnp)(struct cam_periph *, union ccb *),
5980 		 uint8_t tag_action, int immediate, int eot,
5981 		 int reten, int load, uint8_t sense_len,
5982 		 uint32_t timeout)
5983 {
5984 	struct scsi_load_unload *scsi_cmd;
5985 
5986 	scsi_cmd = (struct scsi_load_unload *)&csio->cdb_io.cdb_bytes;
5987 	bzero(scsi_cmd, sizeof(*scsi_cmd));
5988 	scsi_cmd->opcode = LOAD_UNLOAD;
5989 	if (immediate)
5990 		scsi_cmd->immediate = SLU_IMMED;
5991 	if (eot)
5992 		scsi_cmd->eot_reten_load |= SLU_EOT;
5993 	if (reten)
5994 		scsi_cmd->eot_reten_load |= SLU_RETEN;
5995 	if (load)
5996 		scsi_cmd->eot_reten_load |= SLU_LOAD;
5997 
5998 	cam_fill_csio(csio, retries, cbfcnp, CAM_DIR_NONE, tag_action,
5999 	    NULL, 0, sense_len, sizeof(*scsi_cmd), timeout);
6000 }
6001 
6002 void
6003 scsi_rewind(struct ccb_scsiio *csio, uint32_t retries,
6004 	    void (*cbfcnp)(struct cam_periph *, union ccb *),
6005 	    uint8_t tag_action, int immediate, uint8_t sense_len,
6006 	    uint32_t timeout)
6007 {
6008 	struct scsi_rewind *scsi_cmd;
6009 
6010 	scsi_cmd = (struct scsi_rewind *)&csio->cdb_io.cdb_bytes;
6011 	bzero(scsi_cmd, sizeof(*scsi_cmd));
6012 	scsi_cmd->opcode = REWIND;
6013 	if (immediate)
6014 		scsi_cmd->immediate = SREW_IMMED;
6015 
6016 	cam_fill_csio(csio, retries, cbfcnp, CAM_DIR_NONE, tag_action, NULL,
6017 	    0, sense_len, sizeof(*scsi_cmd), timeout);
6018 }
6019 
6020 void
6021 scsi_space(struct ccb_scsiio *csio, uint32_t retries,
6022 	   void (*cbfcnp)(struct cam_periph *, union ccb *),
6023 	   uint8_t tag_action, scsi_space_code code,
6024 	   uint32_t count, uint8_t sense_len, uint32_t timeout)
6025 {
6026 	struct scsi_space *scsi_cmd;
6027 
6028 	scsi_cmd = (struct scsi_space *)&csio->cdb_io.cdb_bytes;
6029 	scsi_cmd->opcode = SPACE;
6030 	scsi_cmd->code = code;
6031 	scsi_ulto3b(count, scsi_cmd->count);
6032 	scsi_cmd->control = 0;
6033 
6034 	cam_fill_csio(csio, retries, cbfcnp, CAM_DIR_NONE, tag_action, NULL,
6035 	    0, sense_len, sizeof(*scsi_cmd), timeout);
6036 }
6037 
6038 void
6039 scsi_write_filemarks(struct ccb_scsiio *csio, uint32_t retries,
6040 		     void (*cbfcnp)(struct cam_periph *, union ccb *),
6041 		     uint8_t tag_action, int immediate, int setmark,
6042 		     uint32_t num_marks, uint8_t sense_len,
6043 		     uint32_t timeout)
6044 {
6045 	struct scsi_write_filemarks *scsi_cmd;
6046 
6047 	scsi_cmd = (struct scsi_write_filemarks *)&csio->cdb_io.cdb_bytes;
6048 	bzero(scsi_cmd, sizeof(*scsi_cmd));
6049 	scsi_cmd->opcode = WRITE_FILEMARKS;
6050 	if (immediate)
6051 		scsi_cmd->byte2 |= SWFMRK_IMMED;
6052 	if (setmark)
6053 		scsi_cmd->byte2 |= SWFMRK_WSMK;
6054 
6055 	scsi_ulto3b(num_marks, scsi_cmd->num_marks);
6056 
6057 	cam_fill_csio(csio, retries, cbfcnp, CAM_DIR_NONE, tag_action, NULL,
6058 	    0, sense_len, sizeof(*scsi_cmd), timeout);
6059 }
6060 
6061 /*
6062  * The reserve and release unit commands differ only by their opcodes.
6063  */
6064 void
6065 scsi_reserve_release_unit(struct ccb_scsiio *csio, uint32_t retries,
6066 			  void (*cbfcnp)(struct cam_periph *, union ccb *),
6067 			  uint8_t tag_action, int third_party,
6068 			  int third_party_id, uint8_t sense_len,
6069 			  uint32_t timeout, int reserve)
6070 {
6071 	struct scsi_reserve_release_unit *scsi_cmd;
6072 
6073 	scsi_cmd = (struct scsi_reserve_release_unit *)&csio->cdb_io.cdb_bytes;
6074 	bzero(scsi_cmd, sizeof(*scsi_cmd));
6075 
6076 	if (reserve)
6077 		scsi_cmd->opcode = RESERVE_UNIT;
6078 	else
6079 		scsi_cmd->opcode = RELEASE_UNIT;
6080 
6081 	if (third_party) {
6082 		scsi_cmd->lun_thirdparty |= SRRU_3RD_PARTY;
6083 		scsi_cmd->lun_thirdparty |=
6084 			((third_party_id << SRRU_3RD_SHAMT) & SRRU_3RD_MASK);
6085 	}
6086 
6087 	cam_fill_csio(csio, retries, cbfcnp, CAM_DIR_NONE, tag_action, NULL,
6088 	    0, sense_len, sizeof(*scsi_cmd), timeout);
6089 }
6090 
6091 void
6092 scsi_erase(struct ccb_scsiio *csio, uint32_t retries,
6093 	   void (*cbfcnp)(struct cam_periph *, union ccb *),
6094 	   uint8_t tag_action, int immediate, int long_erase,
6095 	   uint8_t sense_len, uint32_t timeout)
6096 {
6097 	struct scsi_erase *scsi_cmd;
6098 
6099 	scsi_cmd = (struct scsi_erase *)&csio->cdb_io.cdb_bytes;
6100 	bzero(scsi_cmd, sizeof(*scsi_cmd));
6101 
6102 	scsi_cmd->opcode = ERASE;
6103 
6104 	if (immediate)
6105 		scsi_cmd->lun_imm_long |= SE_IMMED;
6106 
6107 	if (long_erase)
6108 		scsi_cmd->lun_imm_long |= SE_LONG;
6109 
6110 	cam_fill_csio(csio, retries, cbfcnp, CAM_DIR_NONE, tag_action, NULL,
6111 	    0, sense_len, sizeof(*scsi_cmd), timeout);
6112 }
6113 
6114 /*
6115  * Read Tape Position command.
6116  */
6117 void
6118 scsi_read_position(struct ccb_scsiio *csio, uint32_t retries,
6119 		   void (*cbfcnp)(struct cam_periph *, union ccb *),
6120 		   uint8_t tag_action, int hardsoft,
6121 		   struct scsi_tape_position_data *sbp,
6122 		   uint8_t sense_len, uint32_t timeout)
6123 {
6124 	struct scsi_tape_read_position *scmd;
6125 
6126 	cam_fill_csio(csio, retries, cbfcnp, CAM_DIR_IN, tag_action,
6127 	    (uint8_t *)sbp, sizeof (*sbp), sense_len, sizeof(*scmd), timeout);
6128 	scmd = (struct scsi_tape_read_position *)&csio->cdb_io.cdb_bytes;
6129 	bzero(scmd, sizeof(*scmd));
6130 	scmd->opcode = READ_POSITION;
6131 	scmd->byte1 = hardsoft;
6132 }
6133 
6134 /*
6135  * Read Tape Position command.
6136  */
6137 void
6138 scsi_read_position_10(struct ccb_scsiio *csio, uint32_t retries,
6139 		      void (*cbfcnp)(struct cam_periph *, union ccb *),
6140 		      uint8_t tag_action, int service_action,
6141 		      uint8_t *data_ptr, uint32_t length,
6142 		      uint32_t sense_len, uint32_t timeout)
6143 {
6144 	struct scsi_tape_read_position *scmd;
6145 
6146 	cam_fill_csio(csio,
6147 		      retries,
6148 		      cbfcnp,
6149 		      /*flags*/CAM_DIR_IN,
6150 		      tag_action,
6151 		      /*data_ptr*/data_ptr,
6152 		      /*dxfer_len*/length,
6153 		      sense_len,
6154 		      sizeof(*scmd),
6155 		      timeout);
6156 
6157 	scmd = (struct scsi_tape_read_position *)&csio->cdb_io.cdb_bytes;
6158 	bzero(scmd, sizeof(*scmd));
6159 	scmd->opcode = READ_POSITION;
6160 	scmd->byte1 = service_action;
6161 	/*
6162 	 * The length is only currently set (as of SSC4r03) if the extended
6163 	 * form is specified.  The other forms have fixed lengths.
6164 	 */
6165 	if (service_action == SA_RPOS_EXTENDED_FORM)
6166 		scsi_ulto2b(length, scmd->length);
6167 }
6168 
6169 /*
6170  * Set Tape Position command.
6171  */
6172 void
6173 scsi_set_position(struct ccb_scsiio *csio, uint32_t retries,
6174 		   void (*cbfcnp)(struct cam_periph *, union ccb *),
6175 		   uint8_t tag_action, int hardsoft, uint32_t blkno,
6176 		   uint8_t sense_len, uint32_t timeout)
6177 {
6178 	struct scsi_tape_locate *scmd;
6179 
6180 	cam_fill_csio(csio, retries, cbfcnp, CAM_DIR_NONE, tag_action,
6181 	    (uint8_t *)NULL, 0, sense_len, sizeof(*scmd), timeout);
6182 	scmd = (struct scsi_tape_locate *)&csio->cdb_io.cdb_bytes;
6183 	bzero(scmd, sizeof(*scmd));
6184 	scmd->opcode = LOCATE;
6185 	if (hardsoft)
6186 		scmd->byte1 |= SA_SPOS_BT;
6187 	scsi_ulto4b(blkno, scmd->blkaddr);
6188 }
6189 
6190 /*
6191  * XXX KDM figure out how to make a compatibility function.
6192  */
6193 void
6194 scsi_locate_10(struct ccb_scsiio *csio, uint32_t retries,
6195 	       void (*cbfcnp)(struct cam_periph *, union ccb *),
6196 	       uint8_t tag_action, int immed, int cp, int hard,
6197 	       int64_t partition, uint32_t block_address,
6198 	       int sense_len, uint32_t timeout)
6199 {
6200 	struct scsi_tape_locate *scmd;
6201 
6202 	cam_fill_csio(csio,
6203 		      retries,
6204 		      cbfcnp,
6205 		      CAM_DIR_NONE,
6206 		      tag_action,
6207 		      /*data_ptr*/ NULL,
6208 		      /*dxfer_len*/ 0,
6209 		      sense_len,
6210 		      sizeof(*scmd),
6211 		      timeout);
6212 	scmd = (struct scsi_tape_locate *)&csio->cdb_io.cdb_bytes;
6213 	bzero(scmd, sizeof(*scmd));
6214 	scmd->opcode = LOCATE;
6215 	if (immed)
6216 		scmd->byte1 |= SA_SPOS_IMMED;
6217 	if (cp)
6218 		scmd->byte1 |= SA_SPOS_CP;
6219 	if (hard)
6220 		scmd->byte1 |= SA_SPOS_BT;
6221 	scsi_ulto4b(block_address, scmd->blkaddr);
6222 	scmd->partition = partition;
6223 }
6224 
6225 void
6226 scsi_locate_16(struct ccb_scsiio *csio, uint32_t retries,
6227 	       void (*cbfcnp)(struct cam_periph *, union ccb *),
6228 	       uint8_t tag_action, int immed, int cp, uint8_t dest_type,
6229 	       int bam, int64_t partition, uint64_t logical_id,
6230 	       int sense_len, uint32_t timeout)
6231 {
6232 
6233 	struct scsi_locate_16 *scsi_cmd;
6234 
6235 	cam_fill_csio(csio,
6236 		      retries,
6237 		      cbfcnp,
6238 		      /*flags*/CAM_DIR_NONE,
6239 		      tag_action,
6240 		      /*data_ptr*/NULL,
6241 		      /*dxfer_len*/0,
6242 		      sense_len,
6243 		      sizeof(*scsi_cmd),
6244 		      timeout);
6245 
6246 	scsi_cmd = (struct scsi_locate_16 *)&csio->cdb_io.cdb_bytes;
6247 	bzero(scsi_cmd, sizeof(*scsi_cmd));
6248 	scsi_cmd->opcode = LOCATE_16;
6249 	if (immed)
6250 		scsi_cmd->byte1 |= SA_LC_IMMEDIATE;
6251 	if (cp)
6252 		scsi_cmd->byte1 |= SA_LC_CP;
6253 	scsi_cmd->byte1 |= (dest_type << SA_LC_DEST_TYPE_SHIFT);
6254 
6255 	scsi_cmd->byte2 |= bam;
6256 	scsi_cmd->partition = partition;
6257 	scsi_u64to8b(logical_id, scsi_cmd->logical_id);
6258 }
6259 
6260 void
6261 scsi_report_density_support(struct ccb_scsiio *csio, uint32_t retries,
6262 			    void (*cbfcnp)(struct cam_periph *, union ccb *),
6263 			    uint8_t tag_action, int media, int medium_type,
6264 			    uint8_t *data_ptr, uint32_t length,
6265 			    uint32_t sense_len, uint32_t timeout)
6266 {
6267 	struct scsi_report_density_support *scsi_cmd;
6268 
6269 	scsi_cmd =(struct scsi_report_density_support *)&csio->cdb_io.cdb_bytes;
6270 	bzero(scsi_cmd, sizeof(*scsi_cmd));
6271 
6272 	scsi_cmd->opcode = REPORT_DENSITY_SUPPORT;
6273 	if (media != 0)
6274 		scsi_cmd->byte1 |= SRDS_MEDIA;
6275 	if (medium_type != 0)
6276 		scsi_cmd->byte1 |= SRDS_MEDIUM_TYPE;
6277 
6278 	scsi_ulto2b(length, scsi_cmd->length);
6279 
6280 	cam_fill_csio(csio,
6281 		      retries,
6282 		      cbfcnp,
6283 		      /*flags*/CAM_DIR_IN,
6284 		      tag_action,
6285 		      /*data_ptr*/data_ptr,
6286 		      /*dxfer_len*/length,
6287 		      sense_len,
6288 		      sizeof(*scsi_cmd),
6289 		      timeout);
6290 }
6291 
6292 void
6293 scsi_set_capacity(struct ccb_scsiio *csio, uint32_t retries,
6294 		  void (*cbfcnp)(struct cam_periph *, union ccb *),
6295 		  uint8_t tag_action, int byte1, uint32_t proportion,
6296 		  uint32_t sense_len, uint32_t timeout)
6297 {
6298 	struct scsi_set_capacity *scsi_cmd;
6299 
6300 	scsi_cmd = (struct scsi_set_capacity *)&csio->cdb_io.cdb_bytes;
6301 	bzero(scsi_cmd, sizeof(*scsi_cmd));
6302 
6303 	scsi_cmd->opcode = SET_CAPACITY;
6304 
6305 	scsi_cmd->byte1 = byte1;
6306 	scsi_ulto2b(proportion, scsi_cmd->cap_proportion);
6307 
6308 	cam_fill_csio(csio,
6309 		      retries,
6310 		      cbfcnp,
6311 		      /*flags*/CAM_DIR_NONE,
6312 		      tag_action,
6313 		      /*data_ptr*/NULL,
6314 		      /*dxfer_len*/0,
6315 		      sense_len,
6316 		      sizeof(*scsi_cmd),
6317 		      timeout);
6318 }
6319 
6320 void
6321 scsi_format_medium(struct ccb_scsiio *csio, uint32_t retries,
6322 		   void (*cbfcnp)(struct cam_periph *, union ccb *),
6323 		   uint8_t tag_action, int byte1, int byte2,
6324 		   uint8_t *data_ptr, uint32_t dxfer_len,
6325 		   uint32_t sense_len, uint32_t timeout)
6326 {
6327 	struct scsi_format_medium *scsi_cmd;
6328 
6329 	scsi_cmd = (struct scsi_format_medium*)&csio->cdb_io.cdb_bytes;
6330 	bzero(scsi_cmd, sizeof(*scsi_cmd));
6331 
6332 	scsi_cmd->opcode = FORMAT_MEDIUM;
6333 
6334 	scsi_cmd->byte1 = byte1;
6335 	scsi_cmd->byte2 = byte2;
6336 
6337 	scsi_ulto2b(dxfer_len, scsi_cmd->length);
6338 
6339 	cam_fill_csio(csio,
6340 		      retries,
6341 		      cbfcnp,
6342 		      /*flags*/(dxfer_len > 0) ? CAM_DIR_OUT : CAM_DIR_NONE,
6343 		      tag_action,
6344 		      /*data_ptr*/ data_ptr,
6345 		      /*dxfer_len*/ dxfer_len,
6346 		      sense_len,
6347 		      sizeof(*scsi_cmd),
6348 		      timeout);
6349 }
6350 
6351 void
6352 scsi_allow_overwrite(struct ccb_scsiio *csio, uint32_t retries,
6353 		   void (*cbfcnp)(struct cam_periph *, union ccb *),
6354 		   uint8_t tag_action, int allow_overwrite, int partition,
6355 		   uint64_t logical_id, uint32_t sense_len, uint32_t timeout)
6356 {
6357 	struct scsi_allow_overwrite *scsi_cmd;
6358 
6359 	scsi_cmd = (struct scsi_allow_overwrite *)&csio->cdb_io.cdb_bytes;
6360 	bzero(scsi_cmd, sizeof(*scsi_cmd));
6361 
6362 	scsi_cmd->opcode = ALLOW_OVERWRITE;
6363 
6364 	scsi_cmd->allow_overwrite = allow_overwrite;
6365 	scsi_cmd->partition = partition;
6366 	scsi_u64to8b(logical_id, scsi_cmd->logical_id);
6367 
6368 	cam_fill_csio(csio,
6369 		      retries,
6370 		      cbfcnp,
6371 		      CAM_DIR_NONE,
6372 		      tag_action,
6373 		      /*data_ptr*/ NULL,
6374 		      /*dxfer_len*/ 0,
6375 		      sense_len,
6376 		      sizeof(*scsi_cmd),
6377 		      timeout);
6378 }
6379