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