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