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