xref: /freebsd/sys/cam/scsi/scsi_sa.c (revision ce3adf4362fcca6a43e500b2531f0038adbfbd21)
1 /*-
2  * Implementation of SCSI Sequential Access Peripheral driver for CAM.
3  *
4  * Copyright (c) 1999, 2000 Matthew Jacob
5  * All rights reserved.
6  *
7  * Redistribution and use in source and binary forms, with or without
8  * modification, are permitted provided that the following conditions
9  * are met:
10  * 1. Redistributions of source code must retain the above copyright
11  *    notice, this list of conditions, and the following disclaimer,
12  *    without modification, immediately at the beginning of the file.
13  * 2. The name of the author may not be used to endorse or promote products
14  *    derived from this software without specific prior written permission.
15  *
16  * THIS SOFTWARE IS PROVIDED BY THE AUTHOR AND CONTRIBUTORS ``AS IS'' AND
17  * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
18  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
19  * ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE FOR
20  * ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
21  * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
22  * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
23  * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
24  * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
25  * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
26  * SUCH DAMAGE.
27  */
28 
29 #include <sys/cdefs.h>
30 __FBSDID("$FreeBSD$");
31 
32 #include <sys/param.h>
33 #include <sys/queue.h>
34 #ifdef _KERNEL
35 #include <sys/systm.h>
36 #include <sys/kernel.h>
37 #endif
38 #include <sys/types.h>
39 #include <sys/time.h>
40 #include <sys/bio.h>
41 #include <sys/limits.h>
42 #include <sys/malloc.h>
43 #include <sys/mtio.h>
44 #ifdef _KERNEL
45 #include <sys/conf.h>
46 #include <sys/sysctl.h>
47 #include <sys/taskqueue.h>
48 #endif
49 #include <sys/fcntl.h>
50 #include <sys/devicestat.h>
51 
52 #ifndef _KERNEL
53 #include <stdio.h>
54 #include <string.h>
55 #endif
56 
57 #include <cam/cam.h>
58 #include <cam/cam_ccb.h>
59 #include <cam/cam_periph.h>
60 #include <cam/cam_xpt_periph.h>
61 #include <cam/cam_debug.h>
62 
63 #include <cam/scsi/scsi_all.h>
64 #include <cam/scsi/scsi_message.h>
65 #include <cam/scsi/scsi_sa.h>
66 
67 #ifdef _KERNEL
68 
69 #include <opt_sa.h>
70 
71 #ifndef SA_IO_TIMEOUT
72 #define SA_IO_TIMEOUT		4
73 #endif
74 #ifndef SA_SPACE_TIMEOUT
75 #define SA_SPACE_TIMEOUT	1 * 60
76 #endif
77 #ifndef SA_REWIND_TIMEOUT
78 #define SA_REWIND_TIMEOUT	2 * 60
79 #endif
80 #ifndef SA_ERASE_TIMEOUT
81 #define SA_ERASE_TIMEOUT	4 * 60
82 #endif
83 
84 #define	SCSIOP_TIMEOUT		(60 * 1000)	/* not an option */
85 
86 #define	IO_TIMEOUT		(SA_IO_TIMEOUT * 60 * 1000)
87 #define	REWIND_TIMEOUT		(SA_REWIND_TIMEOUT * 60 * 1000)
88 #define	ERASE_TIMEOUT		(SA_ERASE_TIMEOUT * 60 * 1000)
89 #define	SPACE_TIMEOUT		(SA_SPACE_TIMEOUT * 60 * 1000)
90 
91 /*
92  * Additional options that can be set for config: SA_1FM_AT_EOT
93  */
94 
95 #ifndef	UNUSED_PARAMETER
96 #define	UNUSED_PARAMETER(x)	x = x
97 #endif
98 
99 #define	QFRLS(ccb)	\
100 	if (((ccb)->ccb_h.status & CAM_DEV_QFRZN) != 0)	\
101 		cam_release_devq((ccb)->ccb_h.path, 0, 0, 0, FALSE)
102 
103 /*
104  * Driver states
105  */
106 
107 static MALLOC_DEFINE(M_SCSISA, "SCSI sa", "SCSI sequential access buffers");
108 
109 typedef enum {
110 	SA_STATE_NORMAL, SA_STATE_ABNORMAL
111 } sa_state;
112 
113 #define ccb_pflags	ppriv_field0
114 #define ccb_bp	 	ppriv_ptr1
115 
116 #define	SA_CCB_BUFFER_IO	0x0
117 #define	SA_CCB_WAITING		0x1
118 #define	SA_CCB_TYPEMASK		0x1
119 #define	SA_POSITION_UPDATED	0x2
120 
121 #define	Set_CCB_Type(x, type)				\
122 	x->ccb_h.ccb_pflags &= ~SA_CCB_TYPEMASK;	\
123 	x->ccb_h.ccb_pflags |= type
124 
125 #define	CCB_Type(x)	(x->ccb_h.ccb_pflags & SA_CCB_TYPEMASK)
126 
127 
128 
129 typedef enum {
130 	SA_FLAG_OPEN		= 0x0001,
131 	SA_FLAG_FIXED		= 0x0002,
132 	SA_FLAG_TAPE_LOCKED	= 0x0004,
133 	SA_FLAG_TAPE_MOUNTED	= 0x0008,
134 	SA_FLAG_TAPE_WP		= 0x0010,
135 	SA_FLAG_TAPE_WRITTEN	= 0x0020,
136 	SA_FLAG_EOM_PENDING	= 0x0040,
137 	SA_FLAG_EIO_PENDING	= 0x0080,
138 	SA_FLAG_EOF_PENDING	= 0x0100,
139 	SA_FLAG_ERR_PENDING	= (SA_FLAG_EOM_PENDING|SA_FLAG_EIO_PENDING|
140 				   SA_FLAG_EOF_PENDING),
141 	SA_FLAG_INVALID		= 0x0200,
142 	SA_FLAG_COMP_ENABLED	= 0x0400,
143 	SA_FLAG_COMP_SUPP	= 0x0800,
144 	SA_FLAG_COMP_UNSUPP	= 0x1000,
145 	SA_FLAG_TAPE_FROZEN	= 0x2000
146 } sa_flags;
147 
148 typedef enum {
149 	SA_MODE_REWIND		= 0x00,
150 	SA_MODE_NOREWIND	= 0x01,
151 	SA_MODE_OFFLINE		= 0x02
152 } sa_mode;
153 
154 typedef enum {
155 	SA_PARAM_NONE		= 0x00,
156 	SA_PARAM_BLOCKSIZE	= 0x01,
157 	SA_PARAM_DENSITY	= 0x02,
158 	SA_PARAM_COMPRESSION	= 0x04,
159 	SA_PARAM_BUFF_MODE	= 0x08,
160 	SA_PARAM_NUMBLOCKS	= 0x10,
161 	SA_PARAM_WP		= 0x20,
162 	SA_PARAM_SPEED		= 0x40,
163 	SA_PARAM_ALL		= 0x7f
164 } sa_params;
165 
166 typedef enum {
167 	SA_QUIRK_NONE		= 0x00,
168 	SA_QUIRK_NOCOMP		= 0x01,	/* Can't deal with compression at all */
169 	SA_QUIRK_FIXED		= 0x02,	/* Force fixed mode */
170 	SA_QUIRK_VARIABLE	= 0x04,	/* Force variable mode */
171 	SA_QUIRK_2FM		= 0x08,	/* Needs Two File Marks at EOD */
172 	SA_QUIRK_1FM		= 0x10,	/* No more than 1 File Mark at EOD */
173 	SA_QUIRK_NODREAD	= 0x20,	/* Don't try and dummy read density */
174 	SA_QUIRK_NO_MODESEL	= 0x40,	/* Don't do mode select at all */
175 	SA_QUIRK_NO_CPAGE	= 0x80	/* Don't use DEVICE COMPRESSION page */
176 } sa_quirks;
177 
178 #define SA_QUIRK_BIT_STRING	\
179 	"\020"			\
180 	"\001NOCOMP"		\
181 	"\002FIXED"		\
182 	"\003VARIABLE"		\
183 	"\0042FM"		\
184 	"\0051FM"		\
185 	"\006NODREAD"		\
186 	"\007NO_MODESEL"	\
187 	"\010NO_CPAGE"
188 
189 #define	SAMODE(z)	(dev2unit(z) & 0x3)
190 #define	SADENSITY(z)	((dev2unit(z) >> 2) & 0x3)
191 #define	SA_IS_CTRL(z)	(dev2unit(z) & (1 << 4))
192 
193 #define SA_NOT_CTLDEV	0
194 #define SA_CTLDEV	1
195 
196 #define SA_ATYPE_R	0
197 #define SA_ATYPE_NR	1
198 #define SA_ATYPE_ER	2
199 
200 #define	SAMINOR(ctl, mode, access) \
201 	((ctl << 4) | (mode << 2) | (access & 0x3))
202 
203 #define SA_NUM_MODES	4
204 struct sa_devs {
205 	struct cdev *ctl_dev;
206 	struct sa_mode_devs {
207 		struct cdev *r_dev;
208 		struct cdev *nr_dev;
209 		struct cdev *er_dev;
210 	} mode_devs[SA_NUM_MODES];
211 };
212 
213 struct sa_softc {
214 	sa_state	state;
215 	sa_flags	flags;
216 	sa_quirks	quirks;
217 	u_int		si_flags;
218 	struct		bio_queue_head bio_queue;
219 	int		queue_count;
220 	struct		devstat *device_stats;
221 	struct sa_devs	devs;
222 	int		blk_gran;
223 	int		blk_mask;
224 	int		blk_shift;
225 	u_int32_t	max_blk;
226 	u_int32_t	min_blk;
227 	u_int32_t	maxio;
228 	u_int32_t	cpi_maxio;
229 	int		allow_io_split;
230 	u_int32_t	comp_algorithm;
231 	u_int32_t	saved_comp_algorithm;
232 	u_int32_t	media_blksize;
233 	u_int32_t	last_media_blksize;
234 	u_int32_t	media_numblks;
235 	u_int8_t	media_density;
236 	u_int8_t	speed;
237 	u_int8_t	scsi_rev;
238 	u_int8_t	dsreg;		/* mtio mt_dsreg, redux */
239 	int		buffer_mode;
240 	int		filemarks;
241 	union		ccb saved_ccb;
242 	int		last_resid_was_io;
243 
244 	/*
245 	 * Relative to BOT Location.
246 	 */
247 	daddr_t		fileno;
248 	daddr_t		blkno;
249 
250 	/*
251 	 * Latched Error Info
252 	 */
253 	struct {
254 		struct scsi_sense_data _last_io_sense;
255 		u_int64_t _last_io_resid;
256 		u_int8_t _last_io_cdb[CAM_MAX_CDBLEN];
257 		struct scsi_sense_data _last_ctl_sense;
258 		u_int64_t _last_ctl_resid;
259 		u_int8_t _last_ctl_cdb[CAM_MAX_CDBLEN];
260 #define	last_io_sense	errinfo._last_io_sense
261 #define	last_io_resid	errinfo._last_io_resid
262 #define	last_io_cdb	errinfo._last_io_cdb
263 #define	last_ctl_sense	errinfo._last_ctl_sense
264 #define	last_ctl_resid	errinfo._last_ctl_resid
265 #define	last_ctl_cdb	errinfo._last_ctl_cdb
266 	} errinfo;
267 	/*
268 	 * Misc other flags/state
269 	 */
270 	u_int32_t
271 					: 29,
272 		open_rdonly		: 1,	/* open read-only */
273 		open_pending_mount	: 1,	/* open pending mount */
274 		ctrl_mode		: 1;	/* control device open */
275 
276 	struct task		sysctl_task;
277 	struct sysctl_ctx_list	sysctl_ctx;
278 	struct sysctl_oid	*sysctl_tree;
279 };
280 
281 struct sa_quirk_entry {
282 	struct scsi_inquiry_pattern inq_pat;	/* matching pattern */
283 	sa_quirks quirks;	/* specific quirk type */
284 	u_int32_t prefblk;	/* preferred blocksize when in fixed mode */
285 };
286 
287 static struct sa_quirk_entry sa_quirk_table[] =
288 {
289 	{
290 		{ T_SEQUENTIAL, SIP_MEDIA_REMOVABLE, "OnStream",
291 		  "ADR*", "*"}, SA_QUIRK_FIXED|SA_QUIRK_NODREAD |
292 		   SA_QUIRK_1FM|SA_QUIRK_NO_MODESEL, 32768
293 	},
294 	{
295 		{ T_SEQUENTIAL, SIP_MEDIA_REMOVABLE, "ARCHIVE",
296 		  "Python 06408*", "*"}, SA_QUIRK_NODREAD, 0
297 	},
298 	{
299 		{ T_SEQUENTIAL, SIP_MEDIA_REMOVABLE, "ARCHIVE",
300 		  "Python 25601*", "*"}, SA_QUIRK_NOCOMP|SA_QUIRK_NODREAD, 0
301 	},
302 	{
303 		{ T_SEQUENTIAL, SIP_MEDIA_REMOVABLE, "ARCHIVE",
304 		  "Python*", "*"}, SA_QUIRK_NODREAD, 0
305 	},
306 	{
307 		{ T_SEQUENTIAL, SIP_MEDIA_REMOVABLE, "ARCHIVE",
308 		  "VIPER 150*", "*"}, SA_QUIRK_FIXED|SA_QUIRK_1FM, 512
309 	},
310 	{
311 		{ T_SEQUENTIAL, SIP_MEDIA_REMOVABLE, "ARCHIVE",
312 		  "VIPER 2525 25462", "-011"},
313 		  SA_QUIRK_NOCOMP|SA_QUIRK_1FM|SA_QUIRK_NODREAD, 0
314 	},
315 	{
316 		{ T_SEQUENTIAL, SIP_MEDIA_REMOVABLE, "ARCHIVE",
317 		  "VIPER 2525*", "*"}, SA_QUIRK_FIXED|SA_QUIRK_1FM, 1024
318 	},
319 #if	0
320 	{
321 		{ T_SEQUENTIAL, SIP_MEDIA_REMOVABLE, "HP",
322 		  "C15*", "*"}, SA_QUIRK_VARIABLE|SA_QUIRK_NO_CPAGE, 0,
323 	},
324 #endif
325  	{
326  		{ T_SEQUENTIAL, SIP_MEDIA_REMOVABLE, "HP",
327 		  "C56*", "*"}, SA_QUIRK_VARIABLE|SA_QUIRK_2FM, 0
328 	},
329 	{
330 		{ T_SEQUENTIAL, SIP_MEDIA_REMOVABLE, "HP",
331 		  "T20*", "*"}, SA_QUIRK_FIXED|SA_QUIRK_1FM, 512
332 	},
333 	{
334 		{ T_SEQUENTIAL, SIP_MEDIA_REMOVABLE, "HP",
335 		  "T4000*", "*"}, SA_QUIRK_FIXED|SA_QUIRK_1FM, 512
336 	},
337 	{
338 		{ T_SEQUENTIAL, SIP_MEDIA_REMOVABLE, "HP",
339 		  "HP-88780*", "*"}, SA_QUIRK_VARIABLE|SA_QUIRK_2FM, 0
340 	},
341 	{
342 		{ T_SEQUENTIAL, SIP_MEDIA_REMOVABLE, "KENNEDY",
343 		  "*", "*"}, SA_QUIRK_VARIABLE|SA_QUIRK_2FM, 0
344 	},
345 	{
346 		{ T_SEQUENTIAL, SIP_MEDIA_REMOVABLE, "M4 DATA",
347 		  "123107 SCSI*", "*"}, SA_QUIRK_VARIABLE|SA_QUIRK_2FM, 0
348 	},
349 	{	/* jreynold@primenet.com */
350 		{ T_SEQUENTIAL, SIP_MEDIA_REMOVABLE, "Seagate",
351 		"STT8000N*", "*"}, SA_QUIRK_1FM, 0
352 	},
353 	{	/* mike@sentex.net */
354 		{ T_SEQUENTIAL, SIP_MEDIA_REMOVABLE, "Seagate",
355 		"STT20000*", "*"}, SA_QUIRK_1FM, 0
356 	},
357 	{
358 		{ T_SEQUENTIAL, SIP_MEDIA_REMOVABLE, "SEAGATE",
359 		"DAT    06241-XXX", "*"}, SA_QUIRK_VARIABLE|SA_QUIRK_2FM, 0
360 	},
361 	{
362 		{ T_SEQUENTIAL, SIP_MEDIA_REMOVABLE, "TANDBERG",
363 		  " TDC 3600", "U07:"}, SA_QUIRK_NOCOMP|SA_QUIRK_1FM, 512
364 	},
365 	{
366 		{ T_SEQUENTIAL, SIP_MEDIA_REMOVABLE, "TANDBERG",
367 		  " TDC 3800", "*"}, SA_QUIRK_NOCOMP|SA_QUIRK_1FM, 512
368 	},
369 	{
370 		{ T_SEQUENTIAL, SIP_MEDIA_REMOVABLE, "TANDBERG",
371 		  " TDC 4100", "*"}, SA_QUIRK_NOCOMP|SA_QUIRK_1FM, 512
372 	},
373 	{
374 		{ T_SEQUENTIAL, SIP_MEDIA_REMOVABLE, "TANDBERG",
375 		  " TDC 4200", "*"}, SA_QUIRK_NOCOMP|SA_QUIRK_1FM, 512
376 	},
377 	{
378 		{ T_SEQUENTIAL, SIP_MEDIA_REMOVABLE, "TANDBERG",
379 		  " SLR*", "*"}, SA_QUIRK_1FM, 0
380 	},
381 	{
382 		{ T_SEQUENTIAL, SIP_MEDIA_REMOVABLE, "WANGTEK",
383 		  "5525ES*", "*"}, SA_QUIRK_FIXED|SA_QUIRK_1FM, 512
384 	},
385 	{
386 		{ T_SEQUENTIAL, SIP_MEDIA_REMOVABLE, "WANGTEK",
387 		  "51000*", "*"}, SA_QUIRK_FIXED|SA_QUIRK_1FM, 1024
388 	}
389 };
390 
391 static	d_open_t	saopen;
392 static	d_close_t	saclose;
393 static	d_strategy_t	sastrategy;
394 static	d_ioctl_t	saioctl;
395 static	periph_init_t	sainit;
396 static	periph_ctor_t	saregister;
397 static	periph_oninv_t	saoninvalidate;
398 static	periph_dtor_t	sacleanup;
399 static	periph_start_t	sastart;
400 static	void		saasync(void *callback_arg, u_int32_t code,
401 				struct cam_path *path, void *arg);
402 static	void		sadone(struct cam_periph *periph,
403 			       union ccb *start_ccb);
404 static  int		saerror(union ccb *ccb, u_int32_t cam_flags,
405 				u_int32_t sense_flags);
406 static int		samarkswanted(struct cam_periph *);
407 static int		sacheckeod(struct cam_periph *periph);
408 static int		sagetparams(struct cam_periph *periph,
409 				    sa_params params_to_get,
410 				    u_int32_t *blocksize, u_int8_t *density,
411 				    u_int32_t *numblocks, int *buff_mode,
412 				    u_int8_t *write_protect, u_int8_t *speed,
413 				    int *comp_supported, int *comp_enabled,
414 				    u_int32_t *comp_algorithm,
415 				    sa_comp_t *comp_page);
416 static int		sasetparams(struct cam_periph *periph,
417 				    sa_params params_to_set,
418 				    u_int32_t blocksize, u_int8_t density,
419 				    u_int32_t comp_algorithm,
420 				    u_int32_t sense_flags);
421 static void		saprevent(struct cam_periph *periph, int action);
422 static int		sarewind(struct cam_periph *periph);
423 static int		saspace(struct cam_periph *periph, int count,
424 				scsi_space_code code);
425 static int		samount(struct cam_periph *, int, struct cdev *);
426 static int		saretension(struct cam_periph *periph);
427 static int		sareservereleaseunit(struct cam_periph *periph,
428 					     int reserve);
429 static int		saloadunload(struct cam_periph *periph, int load);
430 static int		saerase(struct cam_periph *periph, int longerase);
431 static int		sawritefilemarks(struct cam_periph *periph,
432 					 int nmarks, int setmarks);
433 static int		sardpos(struct cam_periph *periph, int, u_int32_t *);
434 static int		sasetpos(struct cam_periph *periph, int, u_int32_t *);
435 
436 
437 #ifndef	SA_DEFAULT_IO_SPLIT
438 #define	SA_DEFAULT_IO_SPLIT	0
439 #endif
440 
441 static int sa_allow_io_split = SA_DEFAULT_IO_SPLIT;
442 
443 /*
444  * Tunable to allow the user to set a global allow_io_split value.  Note
445  * that this WILL GO AWAY in FreeBSD 11.0.  Silently splitting the I/O up
446  * is bad behavior, because it hides the true tape block size from the
447  * application.
448  */
449 TUNABLE_INT("kern.cam.sa.allow_io_split", &sa_allow_io_split);
450 static SYSCTL_NODE(_kern_cam, OID_AUTO, sa, CTLFLAG_RD, 0,
451 		  "CAM Sequential Access Tape Driver");
452 
453 static struct periph_driver sadriver =
454 {
455 	sainit, "sa",
456 	TAILQ_HEAD_INITIALIZER(sadriver.units), /* generation */ 0
457 };
458 
459 PERIPHDRIVER_DECLARE(sa, sadriver);
460 
461 /* For 2.2-stable support */
462 #ifndef D_TAPE
463 #define D_TAPE 0
464 #endif
465 
466 
467 static struct cdevsw sa_cdevsw = {
468 	.d_version =	D_VERSION,
469 	.d_open =	saopen,
470 	.d_close =	saclose,
471 	.d_read =	physread,
472 	.d_write =	physwrite,
473 	.d_ioctl =	saioctl,
474 	.d_strategy =	sastrategy,
475 	.d_name =	"sa",
476 	.d_flags =	D_TAPE,
477 };
478 
479 static int
480 saopen(struct cdev *dev, int flags, int fmt, struct thread *td)
481 {
482 	struct cam_periph *periph;
483 	struct sa_softc *softc;
484 	int error;
485 
486 	periph = (struct cam_periph *)dev->si_drv1;
487 	if (cam_periph_acquire(periph) != CAM_REQ_CMP) {
488 		return (ENXIO);
489 	}
490 
491 	cam_periph_lock(periph);
492 
493 	softc = (struct sa_softc *)periph->softc;
494 
495 	CAM_DEBUG(periph->path, CAM_DEBUG_TRACE|CAM_DEBUG_INFO,
496 	    ("saopen(%s): softc=0x%x\n", devtoname(dev), softc->flags));
497 
498 	if (SA_IS_CTRL(dev)) {
499 		softc->ctrl_mode = 1;
500 		cam_periph_unlock(periph);
501 		return (0);
502 	}
503 
504 	if ((error = cam_periph_hold(periph, PRIBIO|PCATCH)) != 0) {
505 		cam_periph_unlock(periph);
506 		cam_periph_release(periph);
507 		return (error);
508 	}
509 
510 	if (softc->flags & SA_FLAG_OPEN) {
511 		error = EBUSY;
512 	} else if (softc->flags & SA_FLAG_INVALID) {
513 		error = ENXIO;
514 	} else {
515 		/*
516 		 * Preserve whether this is a read_only open.
517 		 */
518 		softc->open_rdonly = (flags & O_RDWR) == O_RDONLY;
519 
520 		/*
521 		 * The function samount ensures media is loaded and ready.
522 		 * It also does a device RESERVE if the tape isn't yet mounted.
523 		 *
524 		 * If the mount fails and this was a non-blocking open,
525 		 * make this a 'open_pending_mount' action.
526 		 */
527 		error = samount(periph, flags, dev);
528 		if (error && (flags & O_NONBLOCK)) {
529 			softc->flags |= SA_FLAG_OPEN;
530 			softc->open_pending_mount = 1;
531 			cam_periph_unhold(periph);
532 			cam_periph_unlock(periph);
533 			return (0);
534 		}
535 	}
536 
537 	if (error) {
538 		cam_periph_unhold(periph);
539 		cam_periph_unlock(periph);
540 		cam_periph_release(periph);
541 		return (error);
542 	}
543 
544 	saprevent(periph, PR_PREVENT);
545 	softc->flags |= SA_FLAG_OPEN;
546 
547 	cam_periph_unhold(periph);
548 	cam_periph_unlock(periph);
549 	return (error);
550 }
551 
552 static int
553 saclose(struct cdev *dev, int flag, int fmt, struct thread *td)
554 {
555 	struct	cam_periph *periph;
556 	struct	sa_softc *softc;
557 	int	mode, error, writing, tmp;
558 	int	closedbits = SA_FLAG_OPEN;
559 
560 	mode = SAMODE(dev);
561 	periph = (struct cam_periph *)dev->si_drv1;
562 	if (periph == NULL)
563 		return (ENXIO);
564 
565 	cam_periph_lock(periph);
566 
567 	softc = (struct sa_softc *)periph->softc;
568 
569 	CAM_DEBUG(periph->path, CAM_DEBUG_TRACE|CAM_DEBUG_INFO,
570 	    ("saclose(%s): softc=0x%x\n", devtoname(dev), softc->flags));
571 
572 
573 	softc->open_rdonly = 0;
574 	if (SA_IS_CTRL(dev)) {
575 		softc->ctrl_mode = 0;
576 		cam_periph_unlock(periph);
577 		cam_periph_release(periph);
578 		return (0);
579 	}
580 
581 	if (softc->open_pending_mount) {
582 		softc->flags &= ~SA_FLAG_OPEN;
583 		softc->open_pending_mount = 0;
584 		cam_periph_unlock(periph);
585 		cam_periph_release(periph);
586 		return (0);
587 	}
588 
589 	if ((error = cam_periph_hold(periph, PRIBIO)) != 0) {
590 		cam_periph_unlock(periph);
591 		return (error);
592 	}
593 
594 	/*
595 	 * Were we writing the tape?
596 	 */
597 	writing = (softc->flags & SA_FLAG_TAPE_WRITTEN) != 0;
598 
599 	/*
600 	 * See whether or not we need to write filemarks. If this
601 	 * fails, we probably have to assume we've lost tape
602 	 * position.
603 	 */
604 	error = sacheckeod(periph);
605 	if (error) {
606 		xpt_print(periph->path,
607 		    "failed to write terminating filemark(s)\n");
608 		softc->flags |= SA_FLAG_TAPE_FROZEN;
609 	}
610 
611 	/*
612 	 * Whatever we end up doing, allow users to eject tapes from here on.
613 	 */
614 	saprevent(periph, PR_ALLOW);
615 
616 	/*
617 	 * Decide how to end...
618 	 */
619 	if ((softc->flags & SA_FLAG_TAPE_MOUNTED) == 0) {
620 		closedbits |= SA_FLAG_TAPE_FROZEN;
621 	} else switch (mode) {
622 	case SA_MODE_OFFLINE:
623 		/*
624 		 * An 'offline' close is an unconditional release of
625 		 * frozen && mount conditions, irrespective of whether
626 		 * these operations succeeded. The reason for this is
627 		 * to allow at least some kind of programmatic way
628 		 * around our state getting all fouled up. If somebody
629 		 * issues an 'offline' command, that will be allowed
630 		 * to clear state.
631 		 */
632 		(void) sarewind(periph);
633 		(void) saloadunload(periph, FALSE);
634 		closedbits |= SA_FLAG_TAPE_MOUNTED|SA_FLAG_TAPE_FROZEN;
635 		break;
636 	case SA_MODE_REWIND:
637 		/*
638 		 * If the rewind fails, return an error- if anyone cares,
639 		 * but not overwriting any previous error.
640 		 *
641 		 * We don't clear the notion of mounted here, but we do
642 		 * clear the notion of frozen if we successfully rewound.
643 		 */
644 		tmp = sarewind(periph);
645 		if (tmp) {
646 			if (error != 0)
647 				error = tmp;
648 		} else {
649 			closedbits |= SA_FLAG_TAPE_FROZEN;
650 		}
651 		break;
652 	case SA_MODE_NOREWIND:
653 		/*
654 		 * If we're not rewinding/unloading the tape, find out
655 		 * whether we need to back up over one of two filemarks
656 		 * we wrote (if we wrote two filemarks) so that appends
657 		 * from this point on will be sane.
658 		 */
659 		if (error == 0 && writing && (softc->quirks & SA_QUIRK_2FM)) {
660 			tmp = saspace(periph, -1, SS_FILEMARKS);
661 			if (tmp) {
662 				xpt_print(periph->path, "unable to backspace "
663 				    "over one of double filemarks at end of "
664 				    "tape\n");
665 				xpt_print(periph->path, "it is possible that "
666 				    "this device needs a SA_QUIRK_1FM quirk set"
667 				    "for it\n");
668 				softc->flags |= SA_FLAG_TAPE_FROZEN;
669 			}
670 		}
671 		break;
672 	default:
673 		xpt_print(periph->path, "unknown mode 0x%x in saclose\n", mode);
674 		/* NOTREACHED */
675 		break;
676 	}
677 
678 	/*
679 	 * We wish to note here that there are no more filemarks to be written.
680 	 */
681 	softc->filemarks = 0;
682 	softc->flags &= ~SA_FLAG_TAPE_WRITTEN;
683 
684 	/*
685 	 * And we are no longer open for business.
686 	 */
687 	softc->flags &= ~closedbits;
688 
689 	/*
690 	 * Inform users if tape state if frozen....
691 	 */
692 	if (softc->flags & SA_FLAG_TAPE_FROZEN) {
693 		xpt_print(periph->path, "tape is now frozen- use an OFFLINE, "
694 		    "REWIND or MTEOM command to clear this state.\n");
695 	}
696 
697 	/* release the device if it is no longer mounted */
698 	if ((softc->flags & SA_FLAG_TAPE_MOUNTED) == 0)
699 		sareservereleaseunit(periph, FALSE);
700 
701 	cam_periph_unhold(periph);
702 	cam_periph_unlock(periph);
703 	cam_periph_release(periph);
704 
705 	return (error);
706 }
707 
708 /*
709  * Actually translate the requested transfer into one the physical driver
710  * can understand.  The transfer is described by a buf and will include
711  * only one physical transfer.
712  */
713 static void
714 sastrategy(struct bio *bp)
715 {
716 	struct cam_periph *periph;
717 	struct sa_softc *softc;
718 
719 	bp->bio_resid = bp->bio_bcount;
720 	if (SA_IS_CTRL(bp->bio_dev)) {
721 		biofinish(bp, NULL, EINVAL);
722 		return;
723 	}
724 	periph = (struct cam_periph *)bp->bio_dev->si_drv1;
725 	if (periph == NULL) {
726 		biofinish(bp, NULL, ENXIO);
727 		return;
728 	}
729 	cam_periph_lock(periph);
730 
731 	softc = (struct sa_softc *)periph->softc;
732 
733 	if (softc->flags & SA_FLAG_INVALID) {
734 		cam_periph_unlock(periph);
735 		biofinish(bp, NULL, ENXIO);
736 		return;
737 	}
738 
739 	if (softc->flags & SA_FLAG_TAPE_FROZEN) {
740 		cam_periph_unlock(periph);
741 		biofinish(bp, NULL, EPERM);
742 		return;
743 	}
744 
745 	/*
746 	 * This should actually never occur as the write(2)
747 	 * system call traps attempts to write to a read-only
748 	 * file descriptor.
749 	 */
750 	if (bp->bio_cmd == BIO_WRITE && softc->open_rdonly) {
751 		cam_periph_unlock(periph);
752 		biofinish(bp, NULL, EBADF);
753 		return;
754 	}
755 
756 	if (softc->open_pending_mount) {
757 		int error = samount(periph, 0, bp->bio_dev);
758 		if (error) {
759 			cam_periph_unlock(periph);
760 			biofinish(bp, NULL, ENXIO);
761 			return;
762 		}
763 		saprevent(periph, PR_PREVENT);
764 		softc->open_pending_mount = 0;
765 	}
766 
767 
768 	/*
769 	 * If it's a null transfer, return immediately
770 	 */
771 	if (bp->bio_bcount == 0) {
772 		cam_periph_unlock(periph);
773 		biodone(bp);
774 		return;
775 	}
776 
777 	/* valid request?  */
778 	if (softc->flags & SA_FLAG_FIXED) {
779 		/*
780 		 * Fixed block device.  The byte count must
781 		 * be a multiple of our block size.
782 		 */
783 		if (((softc->blk_mask != ~0) &&
784 		    ((bp->bio_bcount & softc->blk_mask) != 0)) ||
785 		    ((softc->blk_mask == ~0) &&
786 		    ((bp->bio_bcount % softc->min_blk) != 0))) {
787 			xpt_print(periph->path, "Invalid request.  Fixed block "
788 			    "device requests must be a multiple of %d bytes\n",
789 			    softc->min_blk);
790 			cam_periph_unlock(periph);
791 			biofinish(bp, NULL, EINVAL);
792 			return;
793 		}
794 	} else if ((bp->bio_bcount > softc->max_blk) ||
795 		   (bp->bio_bcount < softc->min_blk) ||
796 		   (bp->bio_bcount & softc->blk_mask) != 0) {
797 
798 		xpt_print_path(periph->path);
799 		printf("Invalid request.  Variable block "
800 		    "device requests must be ");
801 		if (softc->blk_mask != 0) {
802 			printf("a multiple of %d ", (0x1 << softc->blk_gran));
803 		}
804 		printf("between %d and %d bytes\n", softc->min_blk,
805 		    softc->max_blk);
806 		cam_periph_unlock(periph);
807 		biofinish(bp, NULL, EINVAL);
808 		return;
809         }
810 
811 	/*
812 	 * Place it at the end of the queue.
813 	 */
814 	bioq_insert_tail(&softc->bio_queue, bp);
815 	softc->queue_count++;
816 #if	0
817 	CAM_DEBUG(periph->path, CAM_DEBUG_INFO,
818 	    ("sastrategy: queuing a %ld %s byte %s\n", bp->bio_bcount,
819  	    (softc->flags & SA_FLAG_FIXED)?  "fixed" : "variable",
820 	    (bp->bio_cmd == BIO_READ)? "read" : "write"));
821 #endif
822 	if (softc->queue_count > 1) {
823 		CAM_DEBUG(periph->path, CAM_DEBUG_INFO,
824 		    ("sastrategy: queue count now %d\n", softc->queue_count));
825 	}
826 
827 	/*
828 	 * Schedule ourselves for performing the work.
829 	 */
830 	xpt_schedule(periph, CAM_PRIORITY_NORMAL);
831 	cam_periph_unlock(periph);
832 
833 	return;
834 }
835 
836 
837 #define	PENDING_MOUNT_CHECK(softc, periph, dev)		\
838 	if (softc->open_pending_mount) {		\
839 		error = samount(periph, 0, dev);	\
840 		if (error) {				\
841 			break;				\
842 		}					\
843 		saprevent(periph, PR_PREVENT);		\
844 		softc->open_pending_mount = 0;		\
845 	}
846 
847 static int
848 saioctl(struct cdev *dev, u_long cmd, caddr_t arg, int flag, struct thread *td)
849 {
850 	struct cam_periph *periph;
851 	struct sa_softc *softc;
852 	scsi_space_code spaceop;
853 	int didlockperiph = 0;
854 	int mode;
855 	int error = 0;
856 
857 	mode = SAMODE(dev);
858 	error = 0;		/* shut up gcc */
859 	spaceop = 0;		/* shut up gcc */
860 
861 	periph = (struct cam_periph *)dev->si_drv1;
862 	if (periph == NULL)
863 		return (ENXIO);
864 
865 	cam_periph_lock(periph);
866 	softc = (struct sa_softc *)periph->softc;
867 
868 	/*
869 	 * Check for control mode accesses. We allow MTIOCGET and
870 	 * MTIOCERRSTAT (but need to be the only one open in order
871 	 * to clear latched status), and MTSETBSIZE, MTSETDNSTY
872 	 * and MTCOMP (but need to be the only one accessing this
873 	 * device to run those).
874 	 */
875 
876 	if (SA_IS_CTRL(dev)) {
877 		switch (cmd) {
878 		case MTIOCGETEOTMODEL:
879 		case MTIOCGET:
880 			break;
881 		case MTIOCERRSTAT:
882 			/*
883 			 * If the periph isn't already locked, lock it
884 			 * so our MTIOCERRSTAT can reset latched error stats.
885 			 *
886 			 * If the periph is already locked, skip it because
887 			 * we're just getting status and it'll be up to the
888 			 * other thread that has this device open to do
889 			 * an MTIOCERRSTAT that would clear latched status.
890 			 */
891 			if ((periph->flags & CAM_PERIPH_LOCKED) == 0) {
892 				error = cam_periph_hold(periph, PRIBIO|PCATCH);
893 				if (error != 0) {
894 					cam_periph_unlock(periph);
895 					return (error);
896 				}
897 				didlockperiph = 1;
898 			}
899 			break;
900 
901 		case MTIOCTOP:
902 		{
903 			struct mtop *mt = (struct mtop *) arg;
904 
905 			/*
906 			 * Check to make sure it's an OP we can perform
907 			 * with no media inserted.
908 			 */
909 			switch (mt->mt_op) {
910 			case MTSETBSIZ:
911 			case MTSETDNSTY:
912 			case MTCOMP:
913 				mt = NULL;
914 				/* FALLTHROUGH */
915 			default:
916 				break;
917 			}
918 			if (mt != NULL) {
919 				break;
920 			}
921 			/* FALLTHROUGH */
922 		}
923 		case MTIOCSETEOTMODEL:
924 			/*
925 			 * We need to acquire the peripheral here rather
926 			 * than at open time because we are sharing writable
927 			 * access to data structures.
928 			 */
929 			error = cam_periph_hold(periph, PRIBIO|PCATCH);
930 			if (error != 0) {
931 				cam_periph_unlock(periph);
932 				return (error);
933 			}
934 			didlockperiph = 1;
935 			break;
936 
937 		default:
938 			cam_periph_unlock(periph);
939 			return (EINVAL);
940 		}
941 	}
942 
943 	/*
944 	 * Find the device that the user is talking about
945 	 */
946 	switch (cmd) {
947 	case MTIOCGET:
948 	{
949 		struct mtget *g = (struct mtget *)arg;
950 
951 		/*
952 		 * If this isn't the control mode device, actually go out
953 		 * and ask the drive again what it's set to.
954 		 */
955 		if (!SA_IS_CTRL(dev) && !softc->open_pending_mount) {
956 			u_int8_t write_protect;
957 			int comp_enabled, comp_supported;
958 			error = sagetparams(periph, SA_PARAM_ALL,
959 			    &softc->media_blksize, &softc->media_density,
960 			    &softc->media_numblks, &softc->buffer_mode,
961 			    &write_protect, &softc->speed, &comp_supported,
962 			    &comp_enabled, &softc->comp_algorithm, NULL);
963 			if (error)
964 				break;
965 			if (write_protect)
966 				softc->flags |= SA_FLAG_TAPE_WP;
967 			else
968 				softc->flags &= ~SA_FLAG_TAPE_WP;
969 			softc->flags &= ~(SA_FLAG_COMP_SUPP|
970 			    SA_FLAG_COMP_ENABLED|SA_FLAG_COMP_UNSUPP);
971 			if (comp_supported) {
972 				if (softc->saved_comp_algorithm == 0)
973 					softc->saved_comp_algorithm =
974 					    softc->comp_algorithm;
975 				softc->flags |= SA_FLAG_COMP_SUPP;
976 				if (comp_enabled)
977 					softc->flags |= SA_FLAG_COMP_ENABLED;
978 			} else
979 				softc->flags |= SA_FLAG_COMP_UNSUPP;
980 		}
981 		bzero(g, sizeof(struct mtget));
982 		g->mt_type = MT_ISAR;
983 		if (softc->flags & SA_FLAG_COMP_UNSUPP) {
984 			g->mt_comp = MT_COMP_UNSUPP;
985 			g->mt_comp0 = MT_COMP_UNSUPP;
986 			g->mt_comp1 = MT_COMP_UNSUPP;
987 			g->mt_comp2 = MT_COMP_UNSUPP;
988 			g->mt_comp3 = MT_COMP_UNSUPP;
989 		} else {
990 			if ((softc->flags & SA_FLAG_COMP_ENABLED) == 0) {
991 				g->mt_comp = MT_COMP_DISABLED;
992 			} else {
993 				g->mt_comp = softc->comp_algorithm;
994 			}
995 			g->mt_comp0 = softc->comp_algorithm;
996 			g->mt_comp1 = softc->comp_algorithm;
997 			g->mt_comp2 = softc->comp_algorithm;
998 			g->mt_comp3 = softc->comp_algorithm;
999 		}
1000 		g->mt_density = softc->media_density;
1001 		g->mt_density0 = softc->media_density;
1002 		g->mt_density1 = softc->media_density;
1003 		g->mt_density2 = softc->media_density;
1004 		g->mt_density3 = softc->media_density;
1005 		g->mt_blksiz = softc->media_blksize;
1006 		g->mt_blksiz0 = softc->media_blksize;
1007 		g->mt_blksiz1 = softc->media_blksize;
1008 		g->mt_blksiz2 = softc->media_blksize;
1009 		g->mt_blksiz3 = softc->media_blksize;
1010 		g->mt_fileno = softc->fileno;
1011 		g->mt_blkno = softc->blkno;
1012 		g->mt_dsreg = (short) softc->dsreg;
1013 		/*
1014 		 * Yes, we know that this is likely to overflow
1015 		 */
1016 		if (softc->last_resid_was_io) {
1017 			if ((g->mt_resid = (short) softc->last_io_resid) != 0) {
1018 				if (SA_IS_CTRL(dev) == 0 || didlockperiph) {
1019 					softc->last_io_resid = 0;
1020 				}
1021 			}
1022 		} else {
1023 			if ((g->mt_resid = (short)softc->last_ctl_resid) != 0) {
1024 				if (SA_IS_CTRL(dev) == 0 || didlockperiph) {
1025 					softc->last_ctl_resid = 0;
1026 				}
1027 			}
1028 		}
1029 		error = 0;
1030 		break;
1031 	}
1032 	case MTIOCERRSTAT:
1033 	{
1034 		struct scsi_tape_errors *sep =
1035 		    &((union mterrstat *)arg)->scsi_errstat;
1036 
1037 		CAM_DEBUG(periph->path, CAM_DEBUG_TRACE,
1038 		    ("saioctl: MTIOCERRSTAT\n"));
1039 
1040 		bzero(sep, sizeof(*sep));
1041 		sep->io_resid = softc->last_io_resid;
1042 		bcopy((caddr_t) &softc->last_io_sense, sep->io_sense,
1043 		    sizeof (sep->io_sense));
1044 		bcopy((caddr_t) &softc->last_io_cdb, sep->io_cdb,
1045 		    sizeof (sep->io_cdb));
1046 		sep->ctl_resid = softc->last_ctl_resid;
1047 		bcopy((caddr_t) &softc->last_ctl_sense, sep->ctl_sense,
1048 		    sizeof (sep->ctl_sense));
1049 		bcopy((caddr_t) &softc->last_ctl_cdb, sep->ctl_cdb,
1050 		    sizeof (sep->ctl_cdb));
1051 
1052 		if ((SA_IS_CTRL(dev) == 0 && softc->open_pending_mount) ||
1053 		    didlockperiph)
1054 			bzero((caddr_t) &softc->errinfo,
1055 			    sizeof (softc->errinfo));
1056 		error = 0;
1057 		break;
1058 	}
1059 	case MTIOCTOP:
1060 	{
1061 		struct mtop *mt;
1062 		int    count;
1063 
1064 		PENDING_MOUNT_CHECK(softc, periph, dev);
1065 
1066 		mt = (struct mtop *)arg;
1067 
1068 
1069 		CAM_DEBUG(periph->path, CAM_DEBUG_TRACE,
1070 			 ("saioctl: op=0x%x count=0x%x\n",
1071 			  mt->mt_op, mt->mt_count));
1072 
1073 		count = mt->mt_count;
1074 		switch (mt->mt_op) {
1075 		case MTWEOF:	/* write an end-of-file marker */
1076 			/*
1077 			 * We don't need to clear the SA_FLAG_TAPE_WRITTEN
1078 			 * flag because by keeping track of filemarks
1079 			 * we have last written we know ehether or not
1080 			 * we need to write more when we close the device.
1081 			 */
1082 			error = sawritefilemarks(periph, count, FALSE);
1083 			break;
1084 		case MTWSS:	/* write a setmark */
1085 			error = sawritefilemarks(periph, count, TRUE);
1086 			break;
1087 		case MTBSR:	/* backward space record */
1088 		case MTFSR:	/* forward space record */
1089 		case MTBSF:	/* backward space file */
1090 		case MTFSF:	/* forward space file */
1091 		case MTBSS:	/* backward space setmark */
1092 		case MTFSS:	/* forward space setmark */
1093 		case MTEOD:	/* space to end of recorded medium */
1094 		{
1095 			int nmarks;
1096 
1097 			spaceop = SS_FILEMARKS;
1098 			nmarks = softc->filemarks;
1099 			error = sacheckeod(periph);
1100 			if (error) {
1101 				xpt_print(periph->path,
1102 				    "EOD check prior to spacing failed\n");
1103 				softc->flags |= SA_FLAG_EIO_PENDING;
1104 				break;
1105 			}
1106 			nmarks -= softc->filemarks;
1107 			switch(mt->mt_op) {
1108 			case MTBSR:
1109 				count = -count;
1110 				/* FALLTHROUGH */
1111 			case MTFSR:
1112 				spaceop = SS_BLOCKS;
1113 				break;
1114 			case MTBSF:
1115 				count = -count;
1116 				/* FALLTHROUGH */
1117 			case MTFSF:
1118 				break;
1119 			case MTBSS:
1120 				count = -count;
1121 				/* FALLTHROUGH */
1122 			case MTFSS:
1123 				spaceop = SS_SETMARKS;
1124 				break;
1125 			case MTEOD:
1126 				spaceop = SS_EOD;
1127 				count = 0;
1128 				nmarks = 0;
1129 				break;
1130 			default:
1131 				error = EINVAL;
1132 				break;
1133 			}
1134 			if (error)
1135 				break;
1136 
1137 			nmarks = softc->filemarks;
1138 			/*
1139 			 * XXX: Why are we checking again?
1140 			 */
1141 			error = sacheckeod(periph);
1142 			if (error)
1143 				break;
1144 			nmarks -= softc->filemarks;
1145 			error = saspace(periph, count - nmarks, spaceop);
1146 			/*
1147 			 * At this point, clear that we've written the tape
1148 			 * and that we've written any filemarks. We really
1149 			 * don't know what the applications wishes to do next-
1150 			 * the sacheckeod's will make sure we terminated the
1151 			 * tape correctly if we'd been writing, but the next
1152 			 * action the user application takes will set again
1153 			 * whether we need to write filemarks.
1154 			 */
1155 			softc->flags &=
1156 			    ~(SA_FLAG_TAPE_WRITTEN|SA_FLAG_TAPE_FROZEN);
1157 			softc->filemarks = 0;
1158 			break;
1159 		}
1160 		case MTREW:	/* rewind */
1161 			PENDING_MOUNT_CHECK(softc, periph, dev);
1162 			(void) sacheckeod(periph);
1163 			error = sarewind(periph);
1164 			/* see above */
1165 			softc->flags &=
1166 			    ~(SA_FLAG_TAPE_WRITTEN|SA_FLAG_TAPE_FROZEN);
1167 			softc->flags &= ~SA_FLAG_ERR_PENDING;
1168 			softc->filemarks = 0;
1169 			break;
1170 		case MTERASE:	/* erase */
1171 			PENDING_MOUNT_CHECK(softc, periph, dev);
1172 			error = saerase(periph, count);
1173 			softc->flags &=
1174 			    ~(SA_FLAG_TAPE_WRITTEN|SA_FLAG_TAPE_FROZEN);
1175 			softc->flags &= ~SA_FLAG_ERR_PENDING;
1176 			break;
1177 		case MTRETENS:	/* re-tension tape */
1178 			PENDING_MOUNT_CHECK(softc, periph, dev);
1179 			error = saretension(periph);
1180 			softc->flags &=
1181 			    ~(SA_FLAG_TAPE_WRITTEN|SA_FLAG_TAPE_FROZEN);
1182 			softc->flags &= ~SA_FLAG_ERR_PENDING;
1183 			break;
1184 		case MTOFFL:	/* rewind and put the drive offline */
1185 
1186 			PENDING_MOUNT_CHECK(softc, periph, dev);
1187 
1188 			(void) sacheckeod(periph);
1189 			/* see above */
1190 			softc->flags &= ~SA_FLAG_TAPE_WRITTEN;
1191 			softc->filemarks = 0;
1192 
1193 			error = sarewind(periph);
1194 			/* clear the frozen flag anyway */
1195 			softc->flags &= ~SA_FLAG_TAPE_FROZEN;
1196 
1197 			/*
1198 			 * Be sure to allow media removal before ejecting.
1199 			 */
1200 
1201 			saprevent(periph, PR_ALLOW);
1202 			if (error == 0) {
1203 				error = saloadunload(periph, FALSE);
1204 				if (error == 0) {
1205 					softc->flags &= ~SA_FLAG_TAPE_MOUNTED;
1206 				}
1207 			}
1208 			break;
1209 
1210 		case MTNOP:	/* no operation, sets status only */
1211 		case MTCACHE:	/* enable controller cache */
1212 		case MTNOCACHE:	/* disable controller cache */
1213 			error = 0;
1214 			break;
1215 
1216 		case MTSETBSIZ:	/* Set block size for device */
1217 
1218 			PENDING_MOUNT_CHECK(softc, periph, dev);
1219 
1220 			error = sasetparams(periph, SA_PARAM_BLOCKSIZE, count,
1221 					    0, 0, 0);
1222 			if (error == 0) {
1223 				softc->last_media_blksize =
1224 				    softc->media_blksize;
1225 				softc->media_blksize = count;
1226 				if (count) {
1227 					softc->flags |= SA_FLAG_FIXED;
1228 					if (powerof2(count)) {
1229 						softc->blk_shift =
1230 						    ffs(count) - 1;
1231 						softc->blk_mask = count - 1;
1232 					} else {
1233 						softc->blk_mask = ~0;
1234 						softc->blk_shift = 0;
1235 					}
1236 					/*
1237 					 * Make the user's desire 'persistent'.
1238 					 */
1239 					softc->quirks &= ~SA_QUIRK_VARIABLE;
1240 					softc->quirks |= SA_QUIRK_FIXED;
1241 				} else {
1242 					softc->flags &= ~SA_FLAG_FIXED;
1243 					if (softc->max_blk == 0) {
1244 						softc->max_blk = ~0;
1245 					}
1246 					softc->blk_shift = 0;
1247 					if (softc->blk_gran != 0) {
1248 						softc->blk_mask =
1249 						    softc->blk_gran - 1;
1250 					} else {
1251 						softc->blk_mask = 0;
1252 					}
1253 					/*
1254 					 * Make the user's desire 'persistent'.
1255 					 */
1256 					softc->quirks |= SA_QUIRK_VARIABLE;
1257 					softc->quirks &= ~SA_QUIRK_FIXED;
1258 				}
1259 			}
1260 			break;
1261 		case MTSETDNSTY:	/* Set density for device and mode */
1262 			PENDING_MOUNT_CHECK(softc, periph, dev);
1263 
1264 			if (count > UCHAR_MAX) {
1265 				error = EINVAL;
1266 				break;
1267 			} else {
1268 				error = sasetparams(periph, SA_PARAM_DENSITY,
1269 						    0, count, 0, 0);
1270 			}
1271 			break;
1272 		case MTCOMP:	/* enable compression */
1273 			PENDING_MOUNT_CHECK(softc, periph, dev);
1274 			/*
1275 			 * Some devices don't support compression, and
1276 			 * don't like it if you ask them for the
1277 			 * compression page.
1278 			 */
1279 			if ((softc->quirks & SA_QUIRK_NOCOMP) ||
1280 			    (softc->flags & SA_FLAG_COMP_UNSUPP)) {
1281 				error = ENODEV;
1282 				break;
1283 			}
1284 			error = sasetparams(periph, SA_PARAM_COMPRESSION,
1285 			    0, 0, count, SF_NO_PRINT);
1286 			break;
1287 		default:
1288 			error = EINVAL;
1289 		}
1290 		break;
1291 	}
1292 	case MTIOCIEOT:
1293 	case MTIOCEEOT:
1294 		error = 0;
1295 		break;
1296 	case MTIOCRDSPOS:
1297 		PENDING_MOUNT_CHECK(softc, periph, dev);
1298 		error = sardpos(periph, 0, (u_int32_t *) arg);
1299 		break;
1300 	case MTIOCRDHPOS:
1301 		PENDING_MOUNT_CHECK(softc, periph, dev);
1302 		error = sardpos(periph, 1, (u_int32_t *) arg);
1303 		break;
1304 	case MTIOCSLOCATE:
1305 		PENDING_MOUNT_CHECK(softc, periph, dev);
1306 		error = sasetpos(periph, 0, (u_int32_t *) arg);
1307 		break;
1308 	case MTIOCHLOCATE:
1309 		PENDING_MOUNT_CHECK(softc, periph, dev);
1310 		error = sasetpos(periph, 1, (u_int32_t *) arg);
1311 		break;
1312 	case MTIOCGETEOTMODEL:
1313 		error = 0;
1314 		if (softc->quirks & SA_QUIRK_1FM)
1315 			mode = 1;
1316 		else
1317 			mode = 2;
1318 		*((u_int32_t *) arg) = mode;
1319 		break;
1320 	case MTIOCSETEOTMODEL:
1321 		error = 0;
1322 		switch (*((u_int32_t *) arg)) {
1323 		case 1:
1324 			softc->quirks &= ~SA_QUIRK_2FM;
1325 			softc->quirks |= SA_QUIRK_1FM;
1326 			break;
1327 		case 2:
1328 			softc->quirks &= ~SA_QUIRK_1FM;
1329 			softc->quirks |= SA_QUIRK_2FM;
1330 			break;
1331 		default:
1332 			error = EINVAL;
1333 			break;
1334 		}
1335 		break;
1336 	default:
1337 		error = cam_periph_ioctl(periph, cmd, arg, saerror);
1338 		break;
1339 	}
1340 
1341 	/*
1342 	 * Check to see if we cleared a frozen state
1343 	 */
1344 	if (error == 0 && (softc->flags & SA_FLAG_TAPE_FROZEN)) {
1345 		switch(cmd) {
1346 		case MTIOCRDSPOS:
1347 		case MTIOCRDHPOS:
1348 		case MTIOCSLOCATE:
1349 		case MTIOCHLOCATE:
1350 			softc->fileno = (daddr_t) -1;
1351 			softc->blkno = (daddr_t) -1;
1352 			softc->flags &= ~SA_FLAG_TAPE_FROZEN;
1353 			xpt_print(periph->path,
1354 			    "tape state now unfrozen.\n");
1355 			break;
1356 		default:
1357 			break;
1358 		}
1359 	}
1360 	if (didlockperiph) {
1361 		cam_periph_unhold(periph);
1362 	}
1363 	cam_periph_unlock(periph);
1364 	return (error);
1365 }
1366 
1367 static void
1368 sainit(void)
1369 {
1370 	cam_status status;
1371 
1372 	/*
1373 	 * Install a global async callback.
1374 	 */
1375 	status = xpt_register_async(AC_FOUND_DEVICE, saasync, NULL, NULL);
1376 
1377 	if (status != CAM_REQ_CMP) {
1378 		printf("sa: Failed to attach master async callback "
1379 		       "due to status 0x%x!\n", status);
1380 	}
1381 }
1382 
1383 static void
1384 saoninvalidate(struct cam_periph *periph)
1385 {
1386 	struct sa_softc *softc;
1387 
1388 	softc = (struct sa_softc *)periph->softc;
1389 
1390 	/*
1391 	 * De-register any async callbacks.
1392 	 */
1393 	xpt_register_async(0, saasync, periph, periph->path);
1394 
1395 	softc->flags |= SA_FLAG_INVALID;
1396 
1397 	/*
1398 	 * Return all queued I/O with ENXIO.
1399 	 * XXX Handle any transactions queued to the card
1400 	 *     with XPT_ABORT_CCB.
1401 	 */
1402 	bioq_flush(&softc->bio_queue, NULL, ENXIO);
1403 	softc->queue_count = 0;
1404 
1405 	xpt_print(periph->path, "lost device\n");
1406 
1407 }
1408 
1409 static void
1410 sacleanup(struct cam_periph *periph)
1411 {
1412 	struct sa_softc *softc;
1413 	int i;
1414 
1415 	softc = (struct sa_softc *)periph->softc;
1416 
1417 	xpt_print(periph->path, "removing device entry\n");
1418 	devstat_remove_entry(softc->device_stats);
1419 	cam_periph_unlock(periph);
1420 	destroy_dev(softc->devs.ctl_dev);
1421 	for (i = 0; i < SA_NUM_MODES; i++) {
1422 		destroy_dev(softc->devs.mode_devs[i].r_dev);
1423 		destroy_dev(softc->devs.mode_devs[i].nr_dev);
1424 		destroy_dev(softc->devs.mode_devs[i].er_dev);
1425 	}
1426 	cam_periph_lock(periph);
1427 	free(softc, M_SCSISA);
1428 }
1429 
1430 static void
1431 saasync(void *callback_arg, u_int32_t code,
1432 	struct cam_path *path, void *arg)
1433 {
1434 	struct cam_periph *periph;
1435 
1436 	periph = (struct cam_periph *)callback_arg;
1437 	switch (code) {
1438 	case AC_FOUND_DEVICE:
1439 	{
1440 		struct ccb_getdev *cgd;
1441 		cam_status status;
1442 
1443 		cgd = (struct ccb_getdev *)arg;
1444 		if (cgd == NULL)
1445 			break;
1446 
1447 		if (cgd->protocol != PROTO_SCSI)
1448 			break;
1449 
1450 		if (SID_TYPE(&cgd->inq_data) != T_SEQUENTIAL)
1451 			break;
1452 
1453 		/*
1454 		 * Allocate a peripheral instance for
1455 		 * this device and start the probe
1456 		 * process.
1457 		 */
1458 		status = cam_periph_alloc(saregister, saoninvalidate,
1459 					  sacleanup, sastart,
1460 					  "sa", CAM_PERIPH_BIO, cgd->ccb_h.path,
1461 					  saasync, AC_FOUND_DEVICE, cgd);
1462 
1463 		if (status != CAM_REQ_CMP
1464 		 && status != CAM_REQ_INPROG)
1465 			printf("saasync: Unable to probe new device "
1466 				"due to status 0x%x\n", status);
1467 		break;
1468 	}
1469 	default:
1470 		cam_periph_async(periph, code, path, arg);
1471 		break;
1472 	}
1473 }
1474 
1475 static void
1476 sasysctlinit(void *context, int pending)
1477 {
1478 	struct cam_periph *periph;
1479 	struct sa_softc *softc;
1480 	char tmpstr[80], tmpstr2[80];
1481 
1482 	periph = (struct cam_periph *)context;
1483 	/*
1484 	 * If the periph is invalid, no need to setup the sysctls.
1485 	 */
1486 	if (periph->flags & CAM_PERIPH_INVALID)
1487 		goto bailout;
1488 
1489 	softc = (struct sa_softc *)periph->softc;
1490 
1491 	snprintf(tmpstr, sizeof(tmpstr), "CAM SA unit %d", periph->unit_number);
1492 	snprintf(tmpstr2, sizeof(tmpstr2), "%u", periph->unit_number);
1493 
1494 	sysctl_ctx_init(&softc->sysctl_ctx);
1495 	softc->sysctl_tree = SYSCTL_ADD_NODE(&softc->sysctl_ctx,
1496 	    SYSCTL_STATIC_CHILDREN(_kern_cam_sa), OID_AUTO, tmpstr2,
1497                     CTLFLAG_RD, 0, tmpstr);
1498 	if (softc->sysctl_tree == NULL)
1499 		goto bailout;
1500 
1501 	SYSCTL_ADD_INT(&softc->sysctl_ctx, SYSCTL_CHILDREN(softc->sysctl_tree),
1502 	    OID_AUTO, "allow_io_split", CTLTYPE_INT | CTLFLAG_RDTUN,
1503 	    &softc->allow_io_split, 0, "Allow Splitting I/O");
1504 	SYSCTL_ADD_INT(&softc->sysctl_ctx, SYSCTL_CHILDREN(softc->sysctl_tree),
1505 	    OID_AUTO, "maxio", CTLTYPE_INT | CTLFLAG_RD,
1506 	    &softc->maxio, 0, "Maximum I/O size");
1507 	SYSCTL_ADD_INT(&softc->sysctl_ctx, SYSCTL_CHILDREN(softc->sysctl_tree),
1508 	    OID_AUTO, "cpi_maxio", CTLTYPE_INT | CTLFLAG_RD,
1509 	    &softc->cpi_maxio, 0, "Maximum Controller I/O size");
1510 
1511 bailout:
1512 	/*
1513 	 * Release the reference that was held when this task was enqueued.
1514 	 */
1515 	cam_periph_release(periph);
1516 }
1517 
1518 static cam_status
1519 saregister(struct cam_periph *periph, void *arg)
1520 {
1521 	struct sa_softc *softc;
1522 	struct ccb_getdev *cgd;
1523 	struct ccb_pathinq cpi;
1524 	caddr_t match;
1525 	char tmpstr[80];
1526 	int i;
1527 
1528 	cgd = (struct ccb_getdev *)arg;
1529 	if (cgd == NULL) {
1530 		printf("saregister: no getdev CCB, can't register device\n");
1531 		return (CAM_REQ_CMP_ERR);
1532 	}
1533 
1534 	softc = (struct sa_softc *)
1535 	    malloc(sizeof (*softc), M_SCSISA, M_NOWAIT | M_ZERO);
1536 	if (softc == NULL) {
1537 		printf("saregister: Unable to probe new device. "
1538 		       "Unable to allocate softc\n");
1539 		return (CAM_REQ_CMP_ERR);
1540 	}
1541 	softc->scsi_rev = SID_ANSI_REV(&cgd->inq_data);
1542 	softc->state = SA_STATE_NORMAL;
1543 	softc->fileno = (daddr_t) -1;
1544 	softc->blkno = (daddr_t) -1;
1545 
1546 	bioq_init(&softc->bio_queue);
1547 	periph->softc = softc;
1548 
1549 	/*
1550 	 * See if this device has any quirks.
1551 	 */
1552 	match = cam_quirkmatch((caddr_t)&cgd->inq_data,
1553 			       (caddr_t)sa_quirk_table,
1554 			       sizeof(sa_quirk_table)/sizeof(*sa_quirk_table),
1555 			       sizeof(*sa_quirk_table), scsi_inquiry_match);
1556 
1557 	if (match != NULL) {
1558 		softc->quirks = ((struct sa_quirk_entry *)match)->quirks;
1559 		softc->last_media_blksize =
1560 		    ((struct sa_quirk_entry *)match)->prefblk;
1561 	} else
1562 		softc->quirks = SA_QUIRK_NONE;
1563 
1564 	bzero(&cpi, sizeof(cpi));
1565 	xpt_setup_ccb(&cpi.ccb_h, periph->path, CAM_PRIORITY_NORMAL);
1566 	cpi.ccb_h.func_code = XPT_PATH_INQ;
1567 	xpt_action((union ccb *)&cpi);
1568 
1569 	/*
1570 	 * The SA driver supports a blocksize, but we don't know the
1571 	 * blocksize until we media is inserted.  So, set a flag to
1572 	 * indicate that the blocksize is unavailable right now.
1573 	 */
1574 	cam_periph_unlock(periph);
1575 	softc->device_stats = devstat_new_entry("sa", periph->unit_number, 0,
1576 	    DEVSTAT_BS_UNAVAILABLE, SID_TYPE(&cgd->inq_data) |
1577 	    XPORT_DEVSTAT_TYPE(cpi.transport), DEVSTAT_PRIORITY_TAPE);
1578 
1579 	/*
1580 	 * Load the default value that is either compiled in, or loaded
1581 	 * in the global kern.cam.sa.allow_io_split tunable.
1582 	 */
1583 	softc->allow_io_split = sa_allow_io_split;
1584 
1585 	/*
1586 	 * Load a per-instance tunable, if it exists.  NOTE that this
1587 	 * tunable WILL GO AWAY in FreeBSD 11.0.
1588 	 */
1589 	snprintf(tmpstr, sizeof(tmpstr), "kern.cam.sa.%u.allow_io_split",
1590 		 periph->unit_number);
1591 	TUNABLE_INT_FETCH(tmpstr, &softc->allow_io_split);
1592 
1593 	/*
1594 	 * If maxio isn't set, we fall back to DFLTPHYS.  Otherwise we take
1595 	 * the smaller of cpi.maxio or MAXPHYS.
1596 	 */
1597 	if (cpi.maxio == 0)
1598 		softc->maxio = DFLTPHYS;
1599 	else if (cpi.maxio > MAXPHYS)
1600 		softc->maxio = MAXPHYS;
1601 	else
1602 		softc->maxio = cpi.maxio;
1603 
1604 	/*
1605 	 * Record the controller's maximum I/O size so we can report it to
1606 	 * the user later.
1607 	 */
1608 	softc->cpi_maxio = cpi.maxio;
1609 
1610 	/*
1611 	 * By default we tell physio that we do not want our I/O split.
1612 	 * The user needs to have a 1:1 mapping between the size of his
1613 	 * write to a tape character device and the size of the write
1614 	 * that actually goes down to the drive.
1615 	 */
1616 	if (softc->allow_io_split == 0)
1617 		softc->si_flags = SI_NOSPLIT;
1618 	else
1619 		softc->si_flags = 0;
1620 
1621 	TASK_INIT(&softc->sysctl_task, 0, sasysctlinit, periph);
1622 
1623 	/*
1624 	 * If the SIM supports unmapped I/O, let physio know that we can
1625 	 * handle unmapped buffers.
1626 	 */
1627 	if (cpi.hba_misc & PIM_UNMAPPED)
1628 		softc->si_flags |= SI_UNMAPPED;
1629 
1630 	softc->devs.ctl_dev = make_dev(&sa_cdevsw, SAMINOR(SA_CTLDEV,
1631 	    0, SA_ATYPE_R), UID_ROOT, GID_OPERATOR,
1632 	    0660, "%s%d.ctl", periph->periph_name, periph->unit_number);
1633 	softc->devs.ctl_dev->si_drv1 = periph;
1634 	softc->devs.ctl_dev->si_iosize_max = softc->maxio;
1635 	softc->devs.ctl_dev->si_flags |= softc->si_flags;
1636 
1637 	for (i = 0; i < SA_NUM_MODES; i++) {
1638 
1639 		softc->devs.mode_devs[i].r_dev = make_dev(&sa_cdevsw,
1640 		    SAMINOR(SA_NOT_CTLDEV, i, SA_ATYPE_R),
1641 		    UID_ROOT, GID_OPERATOR, 0660, "%s%d.%d",
1642 		    periph->periph_name, periph->unit_number, i);
1643 		softc->devs.mode_devs[i].r_dev->si_drv1 = periph;
1644 		softc->devs.mode_devs[i].r_dev->si_iosize_max = softc->maxio;
1645 		softc->devs.mode_devs[i].r_dev->si_flags |= softc->si_flags;
1646 
1647 		softc->devs.mode_devs[i].nr_dev = make_dev(&sa_cdevsw,
1648 		    SAMINOR(SA_NOT_CTLDEV, i, SA_ATYPE_NR),
1649 		    UID_ROOT, GID_OPERATOR, 0660, "n%s%d.%d",
1650 		    periph->periph_name, periph->unit_number, i);
1651 		softc->devs.mode_devs[i].nr_dev->si_drv1 = periph;
1652 		softc->devs.mode_devs[i].nr_dev->si_iosize_max = softc->maxio;
1653 		softc->devs.mode_devs[i].nr_dev->si_flags |= softc->si_flags;
1654 
1655 		softc->devs.mode_devs[i].er_dev = make_dev(&sa_cdevsw,
1656 		    SAMINOR(SA_NOT_CTLDEV, i, SA_ATYPE_ER),
1657 		    UID_ROOT, GID_OPERATOR, 0660, "e%s%d.%d",
1658 		    periph->periph_name, periph->unit_number, i);
1659 		softc->devs.mode_devs[i].er_dev->si_drv1 = periph;
1660 		softc->devs.mode_devs[i].er_dev->si_iosize_max = softc->maxio;
1661 		softc->devs.mode_devs[i].er_dev->si_flags |= softc->si_flags;
1662 
1663 		/*
1664 		 * Make the (well known) aliases for the first mode.
1665 		 */
1666 		if (i == 0) {
1667 			struct cdev *alias;
1668 
1669 			alias = make_dev_alias(softc->devs.mode_devs[i].r_dev,
1670 			   "%s%d", periph->periph_name, periph->unit_number);
1671 			alias->si_drv1 = periph;
1672 			alias->si_iosize_max = softc->maxio;
1673 			alias->si_flags |= softc->si_flags;
1674 
1675 			alias = make_dev_alias(softc->devs.mode_devs[i].nr_dev,
1676 			    "n%s%d", periph->periph_name, periph->unit_number);
1677 			alias->si_drv1 = periph;
1678 			alias->si_iosize_max = softc->maxio;
1679 			alias->si_flags |= softc->si_flags;
1680 
1681 			alias = make_dev_alias(softc->devs.mode_devs[i].er_dev,
1682 			    "e%s%d", periph->periph_name, periph->unit_number);
1683 			alias->si_drv1 = periph;
1684 			alias->si_iosize_max = softc->maxio;
1685 			alias->si_flags |= softc->si_flags;
1686 		}
1687 	}
1688 	cam_periph_lock(periph);
1689 
1690 	/*
1691 	 * Bump the peripheral refcount for the sysctl thread, in case we
1692 	 * get invalidated before the thread has a chance to run.
1693 	 */
1694 	cam_periph_acquire(periph);
1695 	taskqueue_enqueue(taskqueue_thread, &softc->sysctl_task);
1696 
1697 	/*
1698 	 * Add an async callback so that we get
1699 	 * notified if this device goes away.
1700 	 */
1701 	xpt_register_async(AC_LOST_DEVICE, saasync, periph, periph->path);
1702 
1703 	xpt_announce_periph(periph, NULL);
1704 	xpt_announce_quirks(periph, softc->quirks, SA_QUIRK_BIT_STRING);
1705 
1706 	return (CAM_REQ_CMP);
1707 }
1708 
1709 static void
1710 sastart(struct cam_periph *periph, union ccb *start_ccb)
1711 {
1712 	struct sa_softc *softc;
1713 
1714 	softc = (struct sa_softc *)periph->softc;
1715 
1716 	CAM_DEBUG(periph->path, CAM_DEBUG_TRACE, ("sastart\n"));
1717 
1718 
1719 	switch (softc->state) {
1720 	case SA_STATE_NORMAL:
1721 	{
1722 		/* Pull a buffer from the queue and get going on it */
1723 		struct bio *bp;
1724 
1725 		/*
1726 		 * See if there is a buf with work for us to do..
1727 		 */
1728 		bp = bioq_first(&softc->bio_queue);
1729 		if (periph->immediate_priority <= periph->pinfo.priority) {
1730 			CAM_DEBUG_PRINT(CAM_DEBUG_SUBTRACE,
1731 					("queuing for immediate ccb\n"));
1732 			Set_CCB_Type(start_ccb, SA_CCB_WAITING);
1733 			SLIST_INSERT_HEAD(&periph->ccb_list, &start_ccb->ccb_h,
1734 					  periph_links.sle);
1735 			periph->immediate_priority = CAM_PRIORITY_NONE;
1736 			wakeup(&periph->ccb_list);
1737 		} else if (bp == NULL) {
1738 			xpt_release_ccb(start_ccb);
1739 		} else if ((softc->flags & SA_FLAG_ERR_PENDING) != 0) {
1740 			struct bio *done_bp;
1741 again:
1742 			softc->queue_count--;
1743 			bioq_remove(&softc->bio_queue, bp);
1744 			bp->bio_resid = bp->bio_bcount;
1745 			done_bp = bp;
1746 			if ((softc->flags & SA_FLAG_EOM_PENDING) != 0) {
1747 				/*
1748 				 * We now just clear errors in this case
1749 				 * and let the residual be the notifier.
1750 				 */
1751 				bp->bio_error = 0;
1752 			} else if ((softc->flags & SA_FLAG_EOF_PENDING) != 0) {
1753 				/*
1754 				 * This can only happen if we're reading
1755 				 * in fixed length mode. In this case,
1756 				 * we dump the rest of the list the
1757 				 * same way.
1758 				 */
1759 				bp->bio_error = 0;
1760 				if (bioq_first(&softc->bio_queue) != NULL) {
1761 					biodone(done_bp);
1762 					goto again;
1763 				}
1764 			} else if ((softc->flags & SA_FLAG_EIO_PENDING) != 0) {
1765 				bp->bio_error = EIO;
1766 				bp->bio_flags |= BIO_ERROR;
1767 			}
1768 			bp = bioq_first(&softc->bio_queue);
1769 			/*
1770 			 * Only if we have no other buffers queued up
1771 			 * do we clear the pending error flag.
1772 			 */
1773 			if (bp == NULL)
1774 				softc->flags &= ~SA_FLAG_ERR_PENDING;
1775 			CAM_DEBUG(periph->path, CAM_DEBUG_INFO,
1776 			    ("sastart- ERR_PENDING now 0x%x, bp is %sNULL, "
1777 			    "%d more buffers queued up\n",
1778 			    (softc->flags & SA_FLAG_ERR_PENDING),
1779 			    (bp != NULL)? "not " : " ", softc->queue_count));
1780 			xpt_release_ccb(start_ccb);
1781 			biodone(done_bp);
1782 		} else {
1783 			u_int32_t length;
1784 
1785 			bioq_remove(&softc->bio_queue, bp);
1786 			softc->queue_count--;
1787 
1788 			if ((softc->flags & SA_FLAG_FIXED) != 0) {
1789 				if (softc->blk_shift != 0) {
1790 					length =
1791 					    bp->bio_bcount >> softc->blk_shift;
1792 				} else if (softc->media_blksize != 0) {
1793 					length = bp->bio_bcount /
1794 					    softc->media_blksize;
1795 				} else {
1796 					bp->bio_error = EIO;
1797 					xpt_print(periph->path, "zero blocksize"
1798 					    " for FIXED length writes?\n");
1799 					biodone(bp);
1800 					break;
1801 				}
1802 #if	0
1803 				CAM_DEBUG(start_ccb->ccb_h.path, CAM_DEBUG_INFO,
1804 				    ("issuing a %d fixed record %s\n",
1805 				    length,  (bp->bio_cmd == BIO_READ)? "read" :
1806 				    "write"));
1807 #endif
1808 			} else {
1809 				length = bp->bio_bcount;
1810 #if	0
1811 				CAM_DEBUG(start_ccb->ccb_h.path, CAM_DEBUG_INFO,
1812 				    ("issuing a %d variable byte %s\n",
1813 				    length,  (bp->bio_cmd == BIO_READ)? "read" :
1814 				    "write"));
1815 #endif
1816 			}
1817 			devstat_start_transaction_bio(softc->device_stats, bp);
1818 			/*
1819 			 * Some people have theorized that we should
1820 			 * suppress illegal length indication if we are
1821 			 * running in variable block mode so that we don't
1822 			 * have to request sense every time our requested
1823 			 * block size is larger than the written block.
1824 			 * The residual information from the ccb allows
1825 			 * us to identify this situation anyway.  The only
1826 			 * problem with this is that we will not get
1827 			 * information about blocks that are larger than
1828 			 * our read buffer unless we set the block size
1829 			 * in the mode page to something other than 0.
1830 			 *
1831 			 * I believe that this is a non-issue. If user apps
1832 			 * don't adjust their read size to match our record
1833 			 * size, that's just life. Anyway, the typical usage
1834 			 * would be to issue, e.g., 64KB reads and occasionally
1835 			 * have to do deal with 512 byte or 1KB intermediate
1836 			 * records.
1837 			 */
1838 			softc->dsreg = (bp->bio_cmd == BIO_READ)?
1839 			    MTIO_DSREG_RD : MTIO_DSREG_WR;
1840 			scsi_sa_read_write(&start_ccb->csio, 0, sadone,
1841 			    MSG_SIMPLE_Q_TAG, (bp->bio_cmd == BIO_READ ?
1842 			    SCSI_RW_READ : SCSI_RW_WRITE) |
1843 			    ((bp->bio_flags & BIO_UNMAPPED) != 0 ?
1844 			    SCSI_RW_BIO : 0), FALSE,
1845 			    (softc->flags & SA_FLAG_FIXED) != 0, length,
1846 			    (bp->bio_flags & BIO_UNMAPPED) != 0 ? (void *)bp :
1847 			    bp->bio_data, bp->bio_bcount, SSD_FULL_SIZE,
1848 			    IO_TIMEOUT);
1849 			start_ccb->ccb_h.ccb_pflags &= ~SA_POSITION_UPDATED;
1850 			Set_CCB_Type(start_ccb, SA_CCB_BUFFER_IO);
1851 			start_ccb->ccb_h.ccb_bp = bp;
1852 			bp = bioq_first(&softc->bio_queue);
1853 			xpt_action(start_ccb);
1854 		}
1855 
1856 		if (bp != NULL) {
1857 			/* Have more work to do, so ensure we stay scheduled */
1858 			xpt_schedule(periph, CAM_PRIORITY_NORMAL);
1859 		}
1860 		break;
1861 	}
1862 	case SA_STATE_ABNORMAL:
1863 	default:
1864 		panic("state 0x%x in sastart", softc->state);
1865 		break;
1866 	}
1867 }
1868 
1869 
1870 static void
1871 sadone(struct cam_periph *periph, union ccb *done_ccb)
1872 {
1873 	struct sa_softc *softc;
1874 	struct ccb_scsiio *csio;
1875 
1876 	softc = (struct sa_softc *)periph->softc;
1877 	csio = &done_ccb->csio;
1878 	switch (CCB_Type(csio)) {
1879 	case SA_CCB_BUFFER_IO:
1880 	{
1881 		struct bio *bp;
1882 		int error;
1883 
1884 		softc->dsreg = MTIO_DSREG_REST;
1885 		bp = (struct bio *)done_ccb->ccb_h.ccb_bp;
1886 		error = 0;
1887 		if ((done_ccb->ccb_h.status & CAM_STATUS_MASK) != CAM_REQ_CMP) {
1888 			if ((error = saerror(done_ccb, 0, 0)) == ERESTART) {
1889 				/*
1890 				 * A retry was scheduled, so just return.
1891 				 */
1892 				return;
1893 			}
1894 		}
1895 
1896 		if (error == EIO) {
1897 
1898 			/*
1899 			 * Catastrophic error. Mark the tape as frozen
1900 			 * (we no longer know tape position).
1901 			 *
1902 			 * Return all queued I/O with EIO, and unfreeze
1903 			 * our queue so that future transactions that
1904 			 * attempt to fix this problem can get to the
1905 			 * device.
1906 			 *
1907 			 */
1908 
1909 			softc->flags |= SA_FLAG_TAPE_FROZEN;
1910 			bioq_flush(&softc->bio_queue, NULL, EIO);
1911 		}
1912 		if (error != 0) {
1913 			bp->bio_resid = bp->bio_bcount;
1914 			bp->bio_error = error;
1915 			bp->bio_flags |= BIO_ERROR;
1916 			/*
1917 			 * In the error case, position is updated in saerror.
1918 			 */
1919 		} else {
1920 			bp->bio_resid = csio->resid;
1921 			bp->bio_error = 0;
1922 			if (csio->resid != 0) {
1923 				bp->bio_flags |= BIO_ERROR;
1924 			}
1925 			if (bp->bio_cmd == BIO_WRITE) {
1926 				softc->flags |= SA_FLAG_TAPE_WRITTEN;
1927 				softc->filemarks = 0;
1928 			}
1929 			if (!(csio->ccb_h.ccb_pflags & SA_POSITION_UPDATED) &&
1930 			    (softc->blkno != (daddr_t) -1)) {
1931 				if ((softc->flags & SA_FLAG_FIXED) != 0) {
1932 					u_int32_t l;
1933 					if (softc->blk_shift != 0) {
1934 						l = bp->bio_bcount >>
1935 							softc->blk_shift;
1936 					} else {
1937 						l = bp->bio_bcount /
1938 							softc->media_blksize;
1939 					}
1940 					softc->blkno += (daddr_t) l;
1941 				} else {
1942 					softc->blkno++;
1943 				}
1944 			}
1945 		}
1946 		/*
1947 		 * If we had an error (immediate or pending),
1948 		 * release the device queue now.
1949 		 */
1950 		if (error || (softc->flags & SA_FLAG_ERR_PENDING))
1951 			cam_release_devq(done_ccb->ccb_h.path, 0, 0, 0, 0);
1952 		if (error || bp->bio_resid) {
1953 			CAM_DEBUG(periph->path, CAM_DEBUG_INFO,
1954 			    	  ("error %d resid %ld count %ld\n", error,
1955 				  bp->bio_resid, bp->bio_bcount));
1956 		}
1957 		biofinish(bp, softc->device_stats, 0);
1958 		break;
1959 	}
1960 	case SA_CCB_WAITING:
1961 	{
1962 		/* Caller will release the CCB */
1963 		wakeup(&done_ccb->ccb_h.cbfcnp);
1964 		return;
1965 	}
1966 	}
1967 	xpt_release_ccb(done_ccb);
1968 }
1969 
1970 /*
1971  * Mount the tape (make sure it's ready for I/O).
1972  */
1973 static int
1974 samount(struct cam_periph *periph, int oflags, struct cdev *dev)
1975 {
1976 	struct	sa_softc *softc;
1977 	union	ccb *ccb;
1978 	int	error;
1979 
1980 	/*
1981 	 * oflags can be checked for 'kind' of open (read-only check) - later
1982 	 * dev can be checked for a control-mode or compression open - later
1983 	 */
1984 	UNUSED_PARAMETER(oflags);
1985 	UNUSED_PARAMETER(dev);
1986 
1987 
1988 	softc = (struct sa_softc *)periph->softc;
1989 
1990 	/*
1991 	 * This should determine if something has happend since the last
1992 	 * open/mount that would invalidate the mount. We do *not* want
1993 	 * to retry this command- we just want the status. But we only
1994 	 * do this if we're mounted already- if we're not mounted,
1995 	 * we don't care about the unit read state and can instead use
1996 	 * this opportunity to attempt to reserve the tape unit.
1997 	 */
1998 
1999 	if (softc->flags & SA_FLAG_TAPE_MOUNTED) {
2000 		ccb = cam_periph_getccb(periph, 1);
2001 		scsi_test_unit_ready(&ccb->csio, 0, sadone,
2002 		    MSG_SIMPLE_Q_TAG, SSD_FULL_SIZE, IO_TIMEOUT);
2003 		error = cam_periph_runccb(ccb, saerror, 0, SF_NO_PRINT,
2004 		    softc->device_stats);
2005 		if (error == ENXIO) {
2006 			softc->flags &= ~SA_FLAG_TAPE_MOUNTED;
2007 			scsi_test_unit_ready(&ccb->csio, 0, sadone,
2008 			    MSG_SIMPLE_Q_TAG, SSD_FULL_SIZE, IO_TIMEOUT);
2009 			error = cam_periph_runccb(ccb, saerror, 0, SF_NO_PRINT,
2010 			    softc->device_stats);
2011 		} else if (error) {
2012 			/*
2013 			 * We don't need to freeze the tape because we
2014 			 * will now attempt to rewind/load it.
2015 			 */
2016 			softc->flags &= ~SA_FLAG_TAPE_MOUNTED;
2017 			if (CAM_DEBUGGED(periph->path, CAM_DEBUG_INFO)) {
2018 				xpt_print(periph->path,
2019 				    "error %d on TUR in samount\n", error);
2020 			}
2021 		}
2022 	} else {
2023 		error = sareservereleaseunit(periph, TRUE);
2024 		if (error) {
2025 			return (error);
2026 		}
2027 		ccb = cam_periph_getccb(periph, 1);
2028 		scsi_test_unit_ready(&ccb->csio, 0, sadone,
2029 		    MSG_SIMPLE_Q_TAG, SSD_FULL_SIZE, IO_TIMEOUT);
2030 		error = cam_periph_runccb(ccb, saerror, 0, SF_NO_PRINT,
2031 		    softc->device_stats);
2032 	}
2033 
2034 	if ((softc->flags & SA_FLAG_TAPE_MOUNTED) == 0) {
2035 		struct scsi_read_block_limits_data *rblim = NULL;
2036 		int comp_enabled, comp_supported;
2037 		u_int8_t write_protect, guessing = 0;
2038 
2039 		/*
2040 		 * Clear out old state.
2041 		 */
2042 		softc->flags &= ~(SA_FLAG_TAPE_WP|SA_FLAG_TAPE_WRITTEN|
2043 				  SA_FLAG_ERR_PENDING|SA_FLAG_COMP_ENABLED|
2044 				  SA_FLAG_COMP_SUPP|SA_FLAG_COMP_UNSUPP);
2045 		softc->filemarks = 0;
2046 
2047 		/*
2048 		 * *Very* first off, make sure we're loaded to BOT.
2049 		 */
2050 		scsi_load_unload(&ccb->csio, 2, sadone, MSG_SIMPLE_Q_TAG, FALSE,
2051 		    FALSE, FALSE, 1, SSD_FULL_SIZE, REWIND_TIMEOUT);
2052 		error = cam_periph_runccb(ccb, saerror, 0, SF_NO_PRINT,
2053 		    softc->device_stats);
2054 
2055 		/*
2056 		 * In case this doesn't work, do a REWIND instead
2057 		 */
2058 		if (error) {
2059 			scsi_rewind(&ccb->csio, 2, sadone, MSG_SIMPLE_Q_TAG,
2060 			    FALSE, SSD_FULL_SIZE, REWIND_TIMEOUT);
2061 			error = cam_periph_runccb(ccb, saerror, 0, SF_NO_PRINT,
2062 				softc->device_stats);
2063 		}
2064 		if (error) {
2065 			xpt_release_ccb(ccb);
2066 			goto exit;
2067 		}
2068 
2069 		/*
2070 		 * Do a dummy test read to force access to the
2071 		 * media so that the drive will really know what's
2072 		 * there. We actually don't really care what the
2073 		 * blocksize on tape is and don't expect to really
2074 		 * read a full record.
2075 		 */
2076 		rblim = (struct  scsi_read_block_limits_data *)
2077 		    malloc(8192, M_SCSISA, M_NOWAIT);
2078 		if (rblim == NULL) {
2079 			xpt_print(periph->path, "no memory for test read\n");
2080 			xpt_release_ccb(ccb);
2081 			error = ENOMEM;
2082 			goto exit;
2083 		}
2084 
2085 		if ((softc->quirks & SA_QUIRK_NODREAD) == 0) {
2086 			scsi_sa_read_write(&ccb->csio, 0, sadone,
2087 			    MSG_SIMPLE_Q_TAG, 1, FALSE, 0, 8192,
2088 			    (void *) rblim, 8192, SSD_FULL_SIZE,
2089 			    IO_TIMEOUT);
2090 			(void) cam_periph_runccb(ccb, saerror, 0, SF_NO_PRINT,
2091 			    softc->device_stats);
2092 			scsi_rewind(&ccb->csio, 1, sadone, MSG_SIMPLE_Q_TAG,
2093 			    FALSE, SSD_FULL_SIZE, REWIND_TIMEOUT);
2094 			error = cam_periph_runccb(ccb, saerror, CAM_RETRY_SELTO,
2095 			    SF_NO_PRINT | SF_RETRY_UA,
2096 			    softc->device_stats);
2097 			if (error) {
2098 				xpt_print(periph->path,
2099 				    "unable to rewind after test read\n");
2100 				xpt_release_ccb(ccb);
2101 				goto exit;
2102 			}
2103 		}
2104 
2105 		/*
2106 		 * Next off, determine block limits.
2107 		 */
2108 		scsi_read_block_limits(&ccb->csio, 5, sadone, MSG_SIMPLE_Q_TAG,
2109 		    rblim, SSD_FULL_SIZE, SCSIOP_TIMEOUT);
2110 
2111 		error = cam_periph_runccb(ccb, saerror, CAM_RETRY_SELTO,
2112 		    SF_NO_PRINT | SF_RETRY_UA, softc->device_stats);
2113 
2114 		xpt_release_ccb(ccb);
2115 
2116 		if (error != 0) {
2117 			/*
2118 			 * If it's less than SCSI-2, READ BLOCK LIMITS is not
2119 			 * a MANDATORY command. Anyway- it doesn't matter-
2120 			 * we can proceed anyway.
2121 			 */
2122 			softc->blk_gran = 0;
2123 			softc->max_blk = ~0;
2124 			softc->min_blk = 0;
2125 		} else {
2126 			if (softc->scsi_rev >= SCSI_REV_SPC) {
2127 				softc->blk_gran = RBL_GRAN(rblim);
2128 			} else {
2129 				softc->blk_gran = 0;
2130 			}
2131 			/*
2132 			 * We take max_blk == min_blk to mean a default to
2133 			 * fixed mode- but note that whatever we get out of
2134 			 * sagetparams below will actually determine whether
2135 			 * we are actually *in* fixed mode.
2136 			 */
2137 			softc->max_blk = scsi_3btoul(rblim->maximum);
2138 			softc->min_blk = scsi_2btoul(rblim->minimum);
2139 
2140 
2141 		}
2142 		/*
2143 		 * Next, perform a mode sense to determine
2144 		 * current density, blocksize, compression etc.
2145 		 */
2146 		error = sagetparams(periph, SA_PARAM_ALL,
2147 				    &softc->media_blksize,
2148 				    &softc->media_density,
2149 				    &softc->media_numblks,
2150 				    &softc->buffer_mode, &write_protect,
2151 				    &softc->speed, &comp_supported,
2152 				    &comp_enabled, &softc->comp_algorithm,
2153 				    NULL);
2154 
2155 		if (error != 0) {
2156 			/*
2157 			 * We could work a little harder here. We could
2158 			 * adjust our attempts to get information. It
2159 			 * might be an ancient tape drive. If someone
2160 			 * nudges us, we'll do that.
2161 			 */
2162 			goto exit;
2163 		}
2164 
2165 		/*
2166 		 * If no quirk has determined that this is a device that is
2167 		 * preferred to be in fixed or variable mode, now is the time
2168 		 * to find out.
2169 	 	 */
2170 		if ((softc->quirks & (SA_QUIRK_FIXED|SA_QUIRK_VARIABLE)) == 0) {
2171 			guessing = 1;
2172 			/*
2173 			 * This could be expensive to find out. Luckily we
2174 			 * only need to do this once. If we start out in
2175 			 * 'default' mode, try and set ourselves to one
2176 			 * of the densities that would determine a wad
2177 			 * of other stuff. Go from highest to lowest.
2178 			 */
2179 			if (softc->media_density == SCSI_DEFAULT_DENSITY) {
2180 				int i;
2181 				static u_int8_t ctry[] = {
2182 					SCSI_DENSITY_HALFINCH_PE,
2183 					SCSI_DENSITY_HALFINCH_6250C,
2184 					SCSI_DENSITY_HALFINCH_6250,
2185 					SCSI_DENSITY_HALFINCH_1600,
2186 					SCSI_DENSITY_HALFINCH_800,
2187 					SCSI_DENSITY_QIC_4GB,
2188 					SCSI_DENSITY_QIC_2GB,
2189 					SCSI_DENSITY_QIC_525_320,
2190 					SCSI_DENSITY_QIC_150,
2191 					SCSI_DENSITY_QIC_120,
2192 					SCSI_DENSITY_QIC_24,
2193 					SCSI_DENSITY_QIC_11_9TRK,
2194 					SCSI_DENSITY_QIC_11_4TRK,
2195 					SCSI_DENSITY_QIC_1320,
2196 					SCSI_DENSITY_QIC_3080,
2197 					0
2198 				};
2199 				for (i = 0; ctry[i]; i++) {
2200 					error = sasetparams(periph,
2201 					    SA_PARAM_DENSITY, 0, ctry[i],
2202 					    0, SF_NO_PRINT);
2203 					if (error == 0) {
2204 						softc->media_density = ctry[i];
2205 						break;
2206 					}
2207 				}
2208 			}
2209 			switch (softc->media_density) {
2210 			case SCSI_DENSITY_QIC_11_4TRK:
2211 			case SCSI_DENSITY_QIC_11_9TRK:
2212 			case SCSI_DENSITY_QIC_24:
2213 			case SCSI_DENSITY_QIC_120:
2214 			case SCSI_DENSITY_QIC_150:
2215 			case SCSI_DENSITY_QIC_525_320:
2216 			case SCSI_DENSITY_QIC_1320:
2217 			case SCSI_DENSITY_QIC_3080:
2218 				softc->quirks &= ~SA_QUIRK_2FM;
2219 				softc->quirks |= SA_QUIRK_FIXED|SA_QUIRK_1FM;
2220 				softc->last_media_blksize = 512;
2221 				break;
2222 			case SCSI_DENSITY_QIC_4GB:
2223 			case SCSI_DENSITY_QIC_2GB:
2224 				softc->quirks &= ~SA_QUIRK_2FM;
2225 				softc->quirks |= SA_QUIRK_FIXED|SA_QUIRK_1FM;
2226 				softc->last_media_blksize = 1024;
2227 				break;
2228 			default:
2229 				softc->last_media_blksize =
2230 				    softc->media_blksize;
2231 				softc->quirks |= SA_QUIRK_VARIABLE;
2232 				break;
2233 			}
2234 		}
2235 
2236 		/*
2237 		 * If no quirk has determined that this is a device that needs
2238 		 * to have 2 Filemarks at EOD, now is the time to find out.
2239 		 */
2240 
2241 		if ((softc->quirks & SA_QUIRK_2FM) == 0) {
2242 			switch (softc->media_density) {
2243 			case SCSI_DENSITY_HALFINCH_800:
2244 			case SCSI_DENSITY_HALFINCH_1600:
2245 			case SCSI_DENSITY_HALFINCH_6250:
2246 			case SCSI_DENSITY_HALFINCH_6250C:
2247 			case SCSI_DENSITY_HALFINCH_PE:
2248 				softc->quirks &= ~SA_QUIRK_1FM;
2249 				softc->quirks |= SA_QUIRK_2FM;
2250 				break;
2251 			default:
2252 				break;
2253 			}
2254 		}
2255 
2256 		/*
2257 		 * Now validate that some info we got makes sense.
2258 		 */
2259 		if ((softc->max_blk < softc->media_blksize) ||
2260 		    (softc->min_blk > softc->media_blksize &&
2261 		    softc->media_blksize)) {
2262 			xpt_print(periph->path,
2263 			    "BLOCK LIMITS (%d..%d) could not match current "
2264 			    "block settings (%d)- adjusting\n", softc->min_blk,
2265 			    softc->max_blk, softc->media_blksize);
2266 			softc->max_blk = softc->min_blk =
2267 			    softc->media_blksize;
2268 		}
2269 
2270 		/*
2271 		 * Now put ourselves into the right frame of mind based
2272 		 * upon quirks...
2273 		 */
2274 tryagain:
2275 		/*
2276 		 * If we want to be in FIXED mode and our current blocksize
2277 		 * is not equal to our last blocksize (if nonzero), try and
2278 		 * set ourselves to this last blocksize (as the 'preferred'
2279 		 * block size).  The initial quirkmatch at registry sets the
2280 		 * initial 'last' blocksize. If, for whatever reason, this
2281 		 * 'last' blocksize is zero, set the blocksize to 512,
2282 		 * or min_blk if that's larger.
2283 		 */
2284 		if ((softc->quirks & SA_QUIRK_FIXED) &&
2285 		    (softc->quirks & SA_QUIRK_NO_MODESEL) == 0 &&
2286 		    (softc->media_blksize != softc->last_media_blksize)) {
2287 			softc->media_blksize = softc->last_media_blksize;
2288 			if (softc->media_blksize == 0) {
2289 				softc->media_blksize = 512;
2290 				if (softc->media_blksize < softc->min_blk) {
2291 					softc->media_blksize = softc->min_blk;
2292 				}
2293 			}
2294 			error = sasetparams(periph, SA_PARAM_BLOCKSIZE,
2295 			    softc->media_blksize, 0, 0, SF_NO_PRINT);
2296 			if (error) {
2297 				xpt_print(periph->path,
2298 				    "unable to set fixed blocksize to %d\n",
2299 				    softc->media_blksize);
2300 				goto exit;
2301 			}
2302 		}
2303 
2304 		if ((softc->quirks & SA_QUIRK_VARIABLE) &&
2305 		    (softc->media_blksize != 0)) {
2306 			softc->last_media_blksize = softc->media_blksize;
2307 			softc->media_blksize = 0;
2308 			error = sasetparams(periph, SA_PARAM_BLOCKSIZE,
2309 			    0, 0, 0, SF_NO_PRINT);
2310 			if (error) {
2311 				/*
2312 				 * If this fails and we were guessing, just
2313 				 * assume that we got it wrong and go try
2314 				 * fixed block mode. Don't even check against
2315 				 * density code at this point.
2316 				 */
2317 				if (guessing) {
2318 					softc->quirks &= ~SA_QUIRK_VARIABLE;
2319 					softc->quirks |= SA_QUIRK_FIXED;
2320 					if (softc->last_media_blksize == 0)
2321 						softc->last_media_blksize = 512;
2322 					goto tryagain;
2323 				}
2324 				xpt_print(periph->path,
2325 				    "unable to set variable blocksize\n");
2326 				goto exit;
2327 			}
2328 		}
2329 
2330 		/*
2331 		 * Now that we have the current block size,
2332 		 * set up some parameters for sastart's usage.
2333 		 */
2334 		if (softc->media_blksize) {
2335 			softc->flags |= SA_FLAG_FIXED;
2336 			if (powerof2(softc->media_blksize)) {
2337 				softc->blk_shift =
2338 				    ffs(softc->media_blksize) - 1;
2339 				softc->blk_mask = softc->media_blksize - 1;
2340 			} else {
2341 				softc->blk_mask = ~0;
2342 				softc->blk_shift = 0;
2343 			}
2344 		} else {
2345 			/*
2346 			 * The SCSI-3 spec allows 0 to mean "unspecified".
2347 			 * The SCSI-1 spec allows 0 to mean 'infinite'.
2348 			 *
2349 			 * Either works here.
2350 			 */
2351 			if (softc->max_blk == 0) {
2352 				softc->max_blk = ~0;
2353 			}
2354 			softc->blk_shift = 0;
2355 			if (softc->blk_gran != 0) {
2356 				softc->blk_mask = softc->blk_gran - 1;
2357 			} else {
2358 				softc->blk_mask = 0;
2359 			}
2360 		}
2361 
2362 		if (write_protect)
2363 			softc->flags |= SA_FLAG_TAPE_WP;
2364 
2365 		if (comp_supported) {
2366 			if (softc->saved_comp_algorithm == 0)
2367 				softc->saved_comp_algorithm =
2368 				    softc->comp_algorithm;
2369 			softc->flags |= SA_FLAG_COMP_SUPP;
2370 			if (comp_enabled)
2371 				softc->flags |= SA_FLAG_COMP_ENABLED;
2372 		} else
2373 			softc->flags |= SA_FLAG_COMP_UNSUPP;
2374 
2375 		if ((softc->buffer_mode == SMH_SA_BUF_MODE_NOBUF) &&
2376 		    (softc->quirks & SA_QUIRK_NO_MODESEL) == 0) {
2377 			error = sasetparams(periph, SA_PARAM_BUFF_MODE, 0,
2378 			    0, 0, SF_NO_PRINT);
2379 			if (error == 0) {
2380 				softc->buffer_mode = SMH_SA_BUF_MODE_SIBUF;
2381 			} else {
2382 				xpt_print(periph->path,
2383 				    "unable to set buffered mode\n");
2384 			}
2385 			error = 0;	/* not an error */
2386 		}
2387 
2388 
2389 		if (error == 0) {
2390 			softc->flags |= SA_FLAG_TAPE_MOUNTED;
2391 		}
2392 exit:
2393 		if (rblim != NULL)
2394 			free(rblim, M_SCSISA);
2395 
2396 		if (error != 0) {
2397 			softc->dsreg = MTIO_DSREG_NIL;
2398 		} else {
2399 			softc->fileno = softc->blkno = 0;
2400 			softc->dsreg = MTIO_DSREG_REST;
2401 		}
2402 #ifdef	SA_1FM_AT_EOD
2403 		if ((softc->quirks & SA_QUIRK_2FM) == 0)
2404 			softc->quirks |= SA_QUIRK_1FM;
2405 #else
2406 		if ((softc->quirks & SA_QUIRK_1FM) == 0)
2407 			softc->quirks |= SA_QUIRK_2FM;
2408 #endif
2409 	} else
2410 		xpt_release_ccb(ccb);
2411 
2412 	/*
2413 	 * If we return an error, we're not mounted any more,
2414 	 * so release any device reservation.
2415 	 */
2416 	if (error != 0) {
2417 		(void) sareservereleaseunit(periph, FALSE);
2418 	} else {
2419 		/*
2420 		 * Clear I/O residual.
2421 		 */
2422 		softc->last_io_resid = 0;
2423 		softc->last_ctl_resid = 0;
2424 	}
2425 	return (error);
2426 }
2427 
2428 /*
2429  * How many filemarks do we need to write if we were to terminate the
2430  * tape session right now? Note that this can be a negative number
2431  */
2432 
2433 static int
2434 samarkswanted(struct cam_periph *periph)
2435 {
2436 	int	markswanted;
2437 	struct	sa_softc *softc;
2438 
2439 	softc = (struct sa_softc *)periph->softc;
2440 	markswanted = 0;
2441 	if ((softc->flags & SA_FLAG_TAPE_WRITTEN) != 0) {
2442 		markswanted++;
2443 		if (softc->quirks & SA_QUIRK_2FM)
2444 			markswanted++;
2445 	}
2446 	markswanted -= softc->filemarks;
2447 	return (markswanted);
2448 }
2449 
2450 static int
2451 sacheckeod(struct cam_periph *periph)
2452 {
2453 	int	error;
2454 	int	markswanted;
2455 
2456 	markswanted = samarkswanted(periph);
2457 
2458 	if (markswanted > 0) {
2459 		error = sawritefilemarks(periph, markswanted, FALSE);
2460 	} else {
2461 		error = 0;
2462 	}
2463 	return (error);
2464 }
2465 
2466 static int
2467 saerror(union ccb *ccb, u_int32_t cflgs, u_int32_t sflgs)
2468 {
2469 	static const char *toobig =
2470 	    "%d-byte tape record bigger than supplied buffer\n";
2471 	struct	cam_periph *periph;
2472 	struct	sa_softc *softc;
2473 	struct	ccb_scsiio *csio;
2474 	struct	scsi_sense_data *sense;
2475 	uint64_t resid = 0;
2476 	int64_t	info = 0;
2477 	cam_status status;
2478 	int error_code, sense_key, asc, ascq, error, aqvalid, stream_valid;
2479 	int sense_len;
2480 	uint8_t stream_bits;
2481 
2482 	periph = xpt_path_periph(ccb->ccb_h.path);
2483 	softc = (struct sa_softc *)periph->softc;
2484 	csio = &ccb->csio;
2485 	sense = &csio->sense_data;
2486 	sense_len = csio->sense_len - csio->sense_resid;
2487 	scsi_extract_sense_len(sense, sense_len, &error_code, &sense_key,
2488 	    &asc, &ascq, /*show_errors*/ 1);
2489 	if (asc != -1 && ascq != -1)
2490 		aqvalid = 1;
2491 	else
2492 		aqvalid = 0;
2493 	if (scsi_get_stream_info(sense, sense_len, NULL, &stream_bits) == 0)
2494 		stream_valid = 1;
2495 	else
2496 		stream_valid = 0;
2497 	error = 0;
2498 
2499 	status = csio->ccb_h.status & CAM_STATUS_MASK;
2500 
2501 	/*
2502 	 * Calculate/latch up, any residuals... We do this in a funny 2-step
2503 	 * so we can print stuff here if we have CAM_DEBUG enabled for this
2504 	 * unit.
2505 	 */
2506 	if (status == CAM_SCSI_STATUS_ERROR) {
2507 		if (scsi_get_sense_info(sense, sense_len, SSD_DESC_INFO, &resid,
2508 					&info) == 0) {
2509 			if ((softc->flags & SA_FLAG_FIXED) != 0)
2510 				resid *= softc->media_blksize;
2511 		} else {
2512 			resid = csio->dxfer_len;
2513 			info = resid;
2514 			if ((softc->flags & SA_FLAG_FIXED) != 0) {
2515 				if (softc->media_blksize)
2516 					info /= softc->media_blksize;
2517 			}
2518 		}
2519 		if (CCB_Type(csio) == SA_CCB_BUFFER_IO) {
2520 			bcopy((caddr_t) sense, (caddr_t) &softc->last_io_sense,
2521 			    sizeof (struct scsi_sense_data));
2522 			bcopy(csio->cdb_io.cdb_bytes, softc->last_io_cdb,
2523 			    (int) csio->cdb_len);
2524 			softc->last_io_resid = resid;
2525 			softc->last_resid_was_io = 1;
2526 		} else {
2527 			bcopy((caddr_t) sense, (caddr_t) &softc->last_ctl_sense,
2528 			    sizeof (struct scsi_sense_data));
2529 			bcopy(csio->cdb_io.cdb_bytes, softc->last_ctl_cdb,
2530 			    (int) csio->cdb_len);
2531 			softc->last_ctl_resid = resid;
2532 			softc->last_resid_was_io = 0;
2533 		}
2534 		CAM_DEBUG(periph->path, CAM_DEBUG_INFO, ("CDB[0]=0x%x Key 0x%x "
2535 		    "ASC/ASCQ 0x%x/0x%x CAM STATUS 0x%x flags 0x%x resid %jd "
2536 		    "dxfer_len %d\n", csio->cdb_io.cdb_bytes[0] & 0xff,
2537 		    sense_key, asc, ascq, status,
2538 		    (stream_valid) ? stream_bits : 0, (intmax_t)resid,
2539 		    csio->dxfer_len));
2540 	} else {
2541 		CAM_DEBUG(periph->path, CAM_DEBUG_INFO,
2542 		    ("Cam Status 0x%x\n", status));
2543 	}
2544 
2545 	switch (status) {
2546 	case CAM_REQ_CMP:
2547 		return (0);
2548 	case CAM_SCSI_STATUS_ERROR:
2549 		/*
2550 		 * If a read/write command, we handle it here.
2551 		 */
2552 		if (CCB_Type(csio) != SA_CCB_WAITING) {
2553 			break;
2554 		}
2555 		/*
2556 		 * If this was just EOM/EOP, Filemark, Setmark or ILI detected
2557 		 * on a non read/write command, we assume it's not an error
2558 		 * and propagate the residule and return.
2559 		 */
2560 		if ((aqvalid && asc == 0 && ascq > 0 && ascq <= 5) ||
2561 		    (aqvalid == 0 && sense_key == SSD_KEY_NO_SENSE)) {
2562 			csio->resid = resid;
2563 			QFRLS(ccb);
2564 			return (0);
2565 		}
2566 		/*
2567 		 * Otherwise, we let the common code handle this.
2568 		 */
2569 		return (cam_periph_error(ccb, cflgs, sflgs, &softc->saved_ccb));
2570 
2571 	/*
2572 	 * XXX: To Be Fixed
2573 	 * We cannot depend upon CAM honoring retry counts for these.
2574 	 */
2575 	case CAM_SCSI_BUS_RESET:
2576 	case CAM_BDR_SENT:
2577 		if (ccb->ccb_h.retry_count <= 0) {
2578 			return (EIO);
2579 		}
2580 		/* FALLTHROUGH */
2581 	default:
2582 		return (cam_periph_error(ccb, cflgs, sflgs, &softc->saved_ccb));
2583 	}
2584 
2585 	/*
2586 	 * Handle filemark, end of tape, mismatched record sizes....
2587 	 * From this point out, we're only handling read/write cases.
2588 	 * Handle writes && reads differently.
2589 	 */
2590 
2591 	if (csio->cdb_io.cdb_bytes[0] == SA_WRITE) {
2592 		if (sense_key == SSD_KEY_VOLUME_OVERFLOW) {
2593 			csio->resid = resid;
2594 			error = ENOSPC;
2595 		} else if ((stream_valid != 0) && (stream_bits & SSD_EOM)) {
2596 			softc->flags |= SA_FLAG_EOM_PENDING;
2597 			/*
2598 			 * Grotesque as it seems, the few times
2599 			 * I've actually seen a non-zero resid,
2600 			 * the tape drive actually lied and had
2601 			 * written all the data!.
2602 			 */
2603 			csio->resid = 0;
2604 		}
2605 	} else {
2606 		csio->resid = resid;
2607 		if (sense_key == SSD_KEY_BLANK_CHECK) {
2608 			if (softc->quirks & SA_QUIRK_1FM) {
2609 				error = 0;
2610 				softc->flags |= SA_FLAG_EOM_PENDING;
2611 			} else {
2612 				error = EIO;
2613 			}
2614 		} else if ((stream_valid != 0) && (stream_bits & SSD_FILEMARK)){
2615 			if (softc->flags & SA_FLAG_FIXED) {
2616 				error = -1;
2617 				softc->flags |= SA_FLAG_EOF_PENDING;
2618 			}
2619 			/*
2620 			 * Unconditionally, if we detected a filemark on a read,
2621 			 * mark that we've run moved a file ahead.
2622 			 */
2623 			if (softc->fileno != (daddr_t) -1) {
2624 				softc->fileno++;
2625 				softc->blkno = 0;
2626 				csio->ccb_h.ccb_pflags |= SA_POSITION_UPDATED;
2627 			}
2628 		}
2629 	}
2630 
2631 	/*
2632 	 * Incorrect Length usually applies to read, but can apply to writes.
2633 	 */
2634 	if (error == 0 && (stream_valid != 0) && (stream_bits & SSD_ILI)) {
2635 		if (info < 0) {
2636 			xpt_print(csio->ccb_h.path, toobig,
2637 			    csio->dxfer_len - info);
2638 			csio->resid = csio->dxfer_len;
2639 			error = EIO;
2640 		} else {
2641 			csio->resid = resid;
2642 			if (softc->flags & SA_FLAG_FIXED) {
2643 				softc->flags |= SA_FLAG_EIO_PENDING;
2644 			}
2645 			/*
2646 			 * Bump the block number if we hadn't seen a filemark.
2647 			 * Do this independent of errors (we've moved anyway).
2648 			 */
2649 			if ((stream_valid == 0) ||
2650 			    (stream_bits & SSD_FILEMARK) == 0) {
2651 				if (softc->blkno != (daddr_t) -1) {
2652 					softc->blkno++;
2653 					csio->ccb_h.ccb_pflags |=
2654 					   SA_POSITION_UPDATED;
2655 				}
2656 			}
2657 		}
2658 	}
2659 
2660 	if (error <= 0) {
2661 		/*
2662 		 * Unfreeze the queue if frozen as we're not returning anything
2663 		 * to our waiters that would indicate an I/O error has occurred
2664 		 * (yet).
2665 		 */
2666 		QFRLS(ccb);
2667 		error = 0;
2668 	}
2669 	return (error);
2670 }
2671 
2672 static int
2673 sagetparams(struct cam_periph *periph, sa_params params_to_get,
2674 	    u_int32_t *blocksize, u_int8_t *density, u_int32_t *numblocks,
2675 	    int *buff_mode, u_int8_t *write_protect, u_int8_t *speed,
2676 	    int *comp_supported, int *comp_enabled, u_int32_t *comp_algorithm,
2677 	    sa_comp_t *tcs)
2678 {
2679 	union ccb *ccb;
2680 	void *mode_buffer;
2681 	struct scsi_mode_header_6 *mode_hdr;
2682 	struct scsi_mode_blk_desc *mode_blk;
2683 	int mode_buffer_len;
2684 	struct sa_softc *softc;
2685 	u_int8_t cpage;
2686 	int error;
2687 	cam_status status;
2688 
2689 	softc = (struct sa_softc *)periph->softc;
2690 	ccb = cam_periph_getccb(periph, 1);
2691 	if (softc->quirks & SA_QUIRK_NO_CPAGE)
2692 		cpage = SA_DEVICE_CONFIGURATION_PAGE;
2693 	else
2694 		cpage = SA_DATA_COMPRESSION_PAGE;
2695 
2696 retry:
2697 	mode_buffer_len = sizeof(*mode_hdr) + sizeof(*mode_blk);
2698 
2699 	if (params_to_get & SA_PARAM_COMPRESSION) {
2700 		if (softc->quirks & SA_QUIRK_NOCOMP) {
2701 			*comp_supported = FALSE;
2702 			params_to_get &= ~SA_PARAM_COMPRESSION;
2703 		} else
2704 			mode_buffer_len += sizeof (sa_comp_t);
2705 	}
2706 
2707 	/* XXX Fix M_NOWAIT */
2708 	mode_buffer = malloc(mode_buffer_len, M_SCSISA, M_NOWAIT | M_ZERO);
2709 	if (mode_buffer == NULL) {
2710 		xpt_release_ccb(ccb);
2711 		return (ENOMEM);
2712 	}
2713 	mode_hdr = (struct scsi_mode_header_6 *)mode_buffer;
2714 	mode_blk = (struct scsi_mode_blk_desc *)&mode_hdr[1];
2715 
2716 	/* it is safe to retry this */
2717 	scsi_mode_sense(&ccb->csio, 5, sadone, MSG_SIMPLE_Q_TAG, FALSE,
2718 	    SMS_PAGE_CTRL_CURRENT, (params_to_get & SA_PARAM_COMPRESSION) ?
2719 	    cpage : SMS_VENDOR_SPECIFIC_PAGE, mode_buffer, mode_buffer_len,
2720 	    SSD_FULL_SIZE, SCSIOP_TIMEOUT);
2721 
2722 	error = cam_periph_runccb(ccb, saerror, 0, SF_NO_PRINT,
2723 	    softc->device_stats);
2724 
2725 	status = ccb->ccb_h.status & CAM_STATUS_MASK;
2726 
2727 	if (error == EINVAL && (params_to_get & SA_PARAM_COMPRESSION) != 0) {
2728 		/*
2729 		 * Hmm. Let's see if we can try another page...
2730 		 * If we've already done that, give up on compression
2731 		 * for this device and remember this for the future
2732 		 * and attempt the request without asking for compression
2733 		 * info.
2734 		 */
2735 		if (cpage == SA_DATA_COMPRESSION_PAGE) {
2736 			cpage = SA_DEVICE_CONFIGURATION_PAGE;
2737 			goto retry;
2738 		}
2739 		softc->quirks |= SA_QUIRK_NOCOMP;
2740 		free(mode_buffer, M_SCSISA);
2741 		goto retry;
2742 	} else if (status == CAM_SCSI_STATUS_ERROR) {
2743 		/* Tell the user about the fatal error. */
2744 		scsi_sense_print(&ccb->csio);
2745 		goto sagetparamsexit;
2746 	}
2747 
2748 	/*
2749 	 * If the user only wants the compression information, and
2750 	 * the device doesn't send back the block descriptor, it's
2751 	 * no big deal.  If the user wants more than just
2752 	 * compression, though, and the device doesn't pass back the
2753 	 * block descriptor, we need to send another mode sense to
2754 	 * get the block descriptor.
2755 	 */
2756 	if ((mode_hdr->blk_desc_len == 0) &&
2757 	    (params_to_get & SA_PARAM_COMPRESSION) &&
2758 	    (params_to_get & ~(SA_PARAM_COMPRESSION))) {
2759 
2760 		/*
2761 		 * Decrease the mode buffer length by the size of
2762 		 * the compression page, to make sure the data
2763 		 * there doesn't get overwritten.
2764 		 */
2765 		mode_buffer_len -= sizeof (sa_comp_t);
2766 
2767 		/*
2768 		 * Now move the compression page that we presumably
2769 		 * got back down the memory chunk a little bit so
2770 		 * it doesn't get spammed.
2771 		 */
2772 		bcopy(&mode_hdr[0], &mode_hdr[1], sizeof (sa_comp_t));
2773 		bzero(&mode_hdr[0], sizeof (mode_hdr[0]));
2774 
2775 		/*
2776 		 * Now, we issue another mode sense and just ask
2777 		 * for the block descriptor, etc.
2778 		 */
2779 
2780 		scsi_mode_sense(&ccb->csio, 2, sadone, MSG_SIMPLE_Q_TAG, FALSE,
2781 		    SMS_PAGE_CTRL_CURRENT, SMS_VENDOR_SPECIFIC_PAGE,
2782 		    mode_buffer, mode_buffer_len, SSD_FULL_SIZE,
2783 		    SCSIOP_TIMEOUT);
2784 
2785 		error = cam_periph_runccb(ccb, saerror, 0, SF_NO_PRINT,
2786 		    softc->device_stats);
2787 
2788 		if (error != 0)
2789 			goto sagetparamsexit;
2790 	}
2791 
2792 	if (params_to_get & SA_PARAM_BLOCKSIZE)
2793 		*blocksize = scsi_3btoul(mode_blk->blklen);
2794 
2795 	if (params_to_get & SA_PARAM_NUMBLOCKS)
2796 		*numblocks = scsi_3btoul(mode_blk->nblocks);
2797 
2798 	if (params_to_get & SA_PARAM_BUFF_MODE)
2799 		*buff_mode = mode_hdr->dev_spec & SMH_SA_BUF_MODE_MASK;
2800 
2801 	if (params_to_get & SA_PARAM_DENSITY)
2802 		*density = mode_blk->density;
2803 
2804 	if (params_to_get & SA_PARAM_WP)
2805 		*write_protect = (mode_hdr->dev_spec & SMH_SA_WP)? TRUE : FALSE;
2806 
2807 	if (params_to_get & SA_PARAM_SPEED)
2808 		*speed = mode_hdr->dev_spec & SMH_SA_SPEED_MASK;
2809 
2810 	if (params_to_get & SA_PARAM_COMPRESSION) {
2811 		sa_comp_t *ntcs = (sa_comp_t *) &mode_blk[1];
2812 		if (cpage == SA_DATA_COMPRESSION_PAGE) {
2813 			struct scsi_data_compression_page *cp = &ntcs->dcomp;
2814 			*comp_supported =
2815 			    (cp->dce_and_dcc & SA_DCP_DCC)? TRUE : FALSE;
2816 			*comp_enabled =
2817 			    (cp->dce_and_dcc & SA_DCP_DCE)? TRUE : FALSE;
2818 			*comp_algorithm = scsi_4btoul(cp->comp_algorithm);
2819 		} else {
2820 			struct scsi_dev_conf_page *cp = &ntcs->dconf;
2821 			/*
2822 			 * We don't really know whether this device supports
2823 			 * Data Compression if the algorithm field is
2824 			 * zero. Just say we do.
2825 			 */
2826 			*comp_supported = TRUE;
2827 			*comp_enabled =
2828 			    (cp->sel_comp_alg != SA_COMP_NONE)? TRUE : FALSE;
2829 			*comp_algorithm = cp->sel_comp_alg;
2830 		}
2831 		if (tcs != NULL)
2832 			bcopy(ntcs, tcs, sizeof (sa_comp_t));
2833 	}
2834 
2835 	if (CAM_DEBUGGED(periph->path, CAM_DEBUG_INFO)) {
2836 		int idx;
2837 		char *xyz = mode_buffer;
2838 		xpt_print_path(periph->path);
2839 		printf("Mode Sense Data=");
2840 		for (idx = 0; idx < mode_buffer_len; idx++)
2841 			printf(" 0x%02x", xyz[idx] & 0xff);
2842 		printf("\n");
2843 	}
2844 
2845 sagetparamsexit:
2846 
2847 	xpt_release_ccb(ccb);
2848 	free(mode_buffer, M_SCSISA);
2849 	return (error);
2850 }
2851 
2852 /*
2853  * The purpose of this function is to set one of four different parameters
2854  * for a tape drive:
2855  *	- blocksize
2856  *	- density
2857  *	- compression / compression algorithm
2858  *	- buffering mode
2859  *
2860  * The assumption is that this will be called from saioctl(), and therefore
2861  * from a process context.  Thus the waiting malloc calls below.  If that
2862  * assumption ever changes, the malloc calls should be changed to be
2863  * NOWAIT mallocs.
2864  *
2865  * Any or all of the four parameters may be set when this function is
2866  * called.  It should handle setting more than one parameter at once.
2867  */
2868 static int
2869 sasetparams(struct cam_periph *periph, sa_params params_to_set,
2870 	    u_int32_t blocksize, u_int8_t density, u_int32_t calg,
2871 	    u_int32_t sense_flags)
2872 {
2873 	struct sa_softc *softc;
2874 	u_int32_t current_blocksize;
2875 	u_int32_t current_calg;
2876 	u_int8_t current_density;
2877 	u_int8_t current_speed;
2878 	int comp_enabled, comp_supported;
2879 	void *mode_buffer;
2880 	int mode_buffer_len;
2881 	struct scsi_mode_header_6 *mode_hdr;
2882 	struct scsi_mode_blk_desc *mode_blk;
2883 	sa_comp_t *ccomp, *cpage;
2884 	int buff_mode;
2885 	union ccb *ccb = NULL;
2886 	int error;
2887 
2888 	softc = (struct sa_softc *)periph->softc;
2889 
2890 	ccomp = malloc(sizeof (sa_comp_t), M_SCSISA, M_NOWAIT);
2891 	if (ccomp == NULL)
2892 		return (ENOMEM);
2893 
2894 	/*
2895 	 * Since it doesn't make sense to set the number of blocks, or
2896 	 * write protection, we won't try to get the current value.  We
2897 	 * always want to get the blocksize, so we can set it back to the
2898 	 * proper value.
2899 	 */
2900 	error = sagetparams(periph,
2901 	    params_to_set | SA_PARAM_BLOCKSIZE | SA_PARAM_SPEED,
2902 	    &current_blocksize, &current_density, NULL, &buff_mode, NULL,
2903 	    &current_speed, &comp_supported, &comp_enabled,
2904 	    &current_calg, ccomp);
2905 
2906 	if (error != 0) {
2907 		free(ccomp, M_SCSISA);
2908 		return (error);
2909 	}
2910 
2911 	mode_buffer_len = sizeof(*mode_hdr) + sizeof(*mode_blk);
2912 	if (params_to_set & SA_PARAM_COMPRESSION)
2913 		mode_buffer_len += sizeof (sa_comp_t);
2914 
2915 	mode_buffer = malloc(mode_buffer_len, M_SCSISA, M_NOWAIT | M_ZERO);
2916 	if (mode_buffer == NULL) {
2917 		free(ccomp, M_SCSISA);
2918 		return (ENOMEM);
2919 	}
2920 
2921 	mode_hdr = (struct scsi_mode_header_6 *)mode_buffer;
2922 	mode_blk = (struct scsi_mode_blk_desc *)&mode_hdr[1];
2923 
2924 	ccb = cam_periph_getccb(periph, 1);
2925 
2926 retry:
2927 
2928 	if (params_to_set & SA_PARAM_COMPRESSION) {
2929 		if (mode_blk) {
2930 			cpage = (sa_comp_t *)&mode_blk[1];
2931 		} else {
2932 			cpage = (sa_comp_t *)&mode_hdr[1];
2933 		}
2934 		bcopy(ccomp, cpage, sizeof (sa_comp_t));
2935 		cpage->hdr.pagecode &= ~0x80;
2936 	} else
2937 		cpage = NULL;
2938 
2939 	/*
2940 	 * If the caller wants us to set the blocksize, use the one they
2941 	 * pass in.  Otherwise, use the blocksize we got back from the
2942 	 * mode select above.
2943 	 */
2944 	if (mode_blk) {
2945 		if (params_to_set & SA_PARAM_BLOCKSIZE)
2946 			scsi_ulto3b(blocksize, mode_blk->blklen);
2947 		else
2948 			scsi_ulto3b(current_blocksize, mode_blk->blklen);
2949 
2950 		/*
2951 		 * Set density if requested, else preserve old density.
2952 		 * SCSI_SAME_DENSITY only applies to SCSI-2 or better
2953 		 * devices, else density we've latched up in our softc.
2954 		 */
2955 		if (params_to_set & SA_PARAM_DENSITY) {
2956 			mode_blk->density = density;
2957 		} else if (softc->scsi_rev > SCSI_REV_CCS) {
2958 			mode_blk->density = SCSI_SAME_DENSITY;
2959 		} else {
2960 			mode_blk->density = softc->media_density;
2961 		}
2962 	}
2963 
2964 	/*
2965 	 * For mode selects, these two fields must be zero.
2966 	 */
2967 	mode_hdr->data_length = 0;
2968 	mode_hdr->medium_type = 0;
2969 
2970 	/* set the speed to the current value */
2971 	mode_hdr->dev_spec = current_speed;
2972 
2973 	/* if set, set single-initiator buffering mode */
2974 	if (softc->buffer_mode == SMH_SA_BUF_MODE_SIBUF) {
2975 		mode_hdr->dev_spec |= SMH_SA_BUF_MODE_SIBUF;
2976 	}
2977 
2978 	if (mode_blk)
2979 		mode_hdr->blk_desc_len = sizeof(struct scsi_mode_blk_desc);
2980 	else
2981 		mode_hdr->blk_desc_len = 0;
2982 
2983 	/*
2984 	 * First, if the user wants us to set the compression algorithm or
2985 	 * just turn compression on, check to make sure that this drive
2986 	 * supports compression.
2987 	 */
2988 	if (params_to_set & SA_PARAM_COMPRESSION) {
2989 		/*
2990 		 * If the compression algorithm is 0, disable compression.
2991 		 * If the compression algorithm is non-zero, enable
2992 		 * compression and set the compression type to the
2993 		 * specified compression algorithm, unless the algorithm is
2994 		 * MT_COMP_ENABLE.  In that case, we look at the
2995 		 * compression algorithm that is currently set and if it is
2996 		 * non-zero, we leave it as-is.  If it is zero, and we have
2997 		 * saved a compression algorithm from a time when
2998 		 * compression was enabled before, set the compression to
2999 		 * the saved value.
3000 		 */
3001 		switch (ccomp->hdr.pagecode & ~0x80) {
3002 		case SA_DEVICE_CONFIGURATION_PAGE:
3003 		{
3004 			struct scsi_dev_conf_page *dcp = &cpage->dconf;
3005 			if (calg == 0) {
3006 				dcp->sel_comp_alg = SA_COMP_NONE;
3007 				break;
3008 			}
3009 			if (calg != MT_COMP_ENABLE) {
3010 				dcp->sel_comp_alg = calg;
3011 			} else if (dcp->sel_comp_alg == SA_COMP_NONE &&
3012 			    softc->saved_comp_algorithm != 0) {
3013 				dcp->sel_comp_alg = softc->saved_comp_algorithm;
3014 			}
3015 			break;
3016 		}
3017 		case SA_DATA_COMPRESSION_PAGE:
3018 		if (ccomp->dcomp.dce_and_dcc & SA_DCP_DCC) {
3019 			struct scsi_data_compression_page *dcp = &cpage->dcomp;
3020 			if (calg == 0) {
3021 				/*
3022 				 * Disable compression, but leave the
3023 				 * decompression and the capability bit
3024 				 * alone.
3025 				 */
3026 				dcp->dce_and_dcc = SA_DCP_DCC;
3027 				dcp->dde_and_red |= SA_DCP_DDE;
3028 				break;
3029 			}
3030 			/* enable compression && decompression */
3031 			dcp->dce_and_dcc = SA_DCP_DCE | SA_DCP_DCC;
3032 			dcp->dde_and_red |= SA_DCP_DDE;
3033 			/*
3034 			 * If there, use compression algorithm from caller.
3035 			 * Otherwise, if there's a saved compression algorithm
3036 			 * and there is no current algorithm, use the saved
3037 			 * algorithm. Else parrot back what we got and hope
3038 			 * for the best.
3039 			 */
3040 			if (calg != MT_COMP_ENABLE) {
3041 				scsi_ulto4b(calg, dcp->comp_algorithm);
3042 				scsi_ulto4b(calg, dcp->decomp_algorithm);
3043 			} else if (scsi_4btoul(dcp->comp_algorithm) == 0 &&
3044 			    softc->saved_comp_algorithm != 0) {
3045 				scsi_ulto4b(softc->saved_comp_algorithm,
3046 				    dcp->comp_algorithm);
3047 				scsi_ulto4b(softc->saved_comp_algorithm,
3048 				    dcp->decomp_algorithm);
3049 			}
3050 			break;
3051 		}
3052 		/*
3053 		 * Compression does not appear to be supported-
3054 		 * at least via the DATA COMPRESSION page. It
3055 		 * would be too much to ask us to believe that
3056 		 * the page itself is supported, but incorrectly
3057 		 * reports an ability to manipulate data compression,
3058 		 * so we'll assume that this device doesn't support
3059 		 * compression. We can just fall through for that.
3060 		 */
3061 		/* FALLTHROUGH */
3062 		default:
3063 			/*
3064 			 * The drive doesn't seem to support compression,
3065 			 * so turn off the set compression bit.
3066 			 */
3067 			params_to_set &= ~SA_PARAM_COMPRESSION;
3068 			xpt_print(periph->path,
3069 			    "device does not seem to support compression\n");
3070 
3071 			/*
3072 			 * If that was the only thing the user wanted us to set,
3073 			 * clean up allocated resources and return with
3074 			 * 'operation not supported'.
3075 			 */
3076 			if (params_to_set == SA_PARAM_NONE) {
3077 				free(mode_buffer, M_SCSISA);
3078 				xpt_release_ccb(ccb);
3079 				return (ENODEV);
3080 			}
3081 
3082 			/*
3083 			 * That wasn't the only thing the user wanted us to set.
3084 			 * So, decrease the stated mode buffer length by the
3085 			 * size of the compression mode page.
3086 			 */
3087 			mode_buffer_len -= sizeof(sa_comp_t);
3088 		}
3089 	}
3090 
3091 	/* It is safe to retry this operation */
3092 	scsi_mode_select(&ccb->csio, 5, sadone, MSG_SIMPLE_Q_TAG,
3093 	    (params_to_set & SA_PARAM_COMPRESSION)? TRUE : FALSE,
3094 	    FALSE, mode_buffer, mode_buffer_len, SSD_FULL_SIZE, SCSIOP_TIMEOUT);
3095 
3096 	error = cam_periph_runccb(ccb, saerror, 0,
3097 	    sense_flags, softc->device_stats);
3098 
3099 	if (CAM_DEBUGGED(periph->path, CAM_DEBUG_INFO)) {
3100 		int idx;
3101 		char *xyz = mode_buffer;
3102 		xpt_print_path(periph->path);
3103 		printf("Err%d, Mode Select Data=", error);
3104 		for (idx = 0; idx < mode_buffer_len; idx++)
3105 			printf(" 0x%02x", xyz[idx] & 0xff);
3106 		printf("\n");
3107 	}
3108 
3109 
3110 	if (error) {
3111 		/*
3112 		 * If we can, try without setting density/blocksize.
3113 		 */
3114 		if (mode_blk) {
3115 			if ((params_to_set &
3116 			    (SA_PARAM_DENSITY|SA_PARAM_BLOCKSIZE)) == 0) {
3117 				mode_blk = NULL;
3118 				goto retry;
3119 			}
3120 		} else {
3121 			mode_blk = (struct scsi_mode_blk_desc *)&mode_hdr[1];
3122 			cpage = (sa_comp_t *)&mode_blk[1];
3123 		}
3124 
3125 		/*
3126 		 * If we were setting the blocksize, and that failed, we
3127 		 * want to set it to its original value.  If we weren't
3128 		 * setting the blocksize, we don't want to change it.
3129 		 */
3130 		scsi_ulto3b(current_blocksize, mode_blk->blklen);
3131 
3132 		/*
3133 		 * Set density if requested, else preserve old density.
3134 		 * SCSI_SAME_DENSITY only applies to SCSI-2 or better
3135 		 * devices, else density we've latched up in our softc.
3136 		 */
3137 		if (params_to_set & SA_PARAM_DENSITY) {
3138 			mode_blk->density = current_density;
3139 		} else if (softc->scsi_rev > SCSI_REV_CCS) {
3140 			mode_blk->density = SCSI_SAME_DENSITY;
3141 		} else {
3142 			mode_blk->density = softc->media_density;
3143 		}
3144 
3145 		if (params_to_set & SA_PARAM_COMPRESSION)
3146 			bcopy(ccomp, cpage, sizeof (sa_comp_t));
3147 
3148 		/*
3149 		 * The retry count is the only CCB field that might have been
3150 		 * changed that we care about, so reset it back to 1.
3151 		 */
3152 		ccb->ccb_h.retry_count = 1;
3153 		cam_periph_runccb(ccb, saerror, 0, sense_flags,
3154 		    softc->device_stats);
3155 	}
3156 
3157 	xpt_release_ccb(ccb);
3158 
3159 	if (ccomp != NULL)
3160 		free(ccomp, M_SCSISA);
3161 
3162 	if (params_to_set & SA_PARAM_COMPRESSION) {
3163 		if (error) {
3164 			softc->flags &= ~SA_FLAG_COMP_ENABLED;
3165 			/*
3166 			 * Even if we get an error setting compression,
3167 			 * do not say that we don't support it. We could
3168 			 * have been wrong, or it may be media specific.
3169 			 *	softc->flags &= ~SA_FLAG_COMP_SUPP;
3170 			 */
3171 			softc->saved_comp_algorithm = softc->comp_algorithm;
3172 			softc->comp_algorithm = 0;
3173 		} else {
3174 			softc->flags |= SA_FLAG_COMP_ENABLED;
3175 			softc->comp_algorithm = calg;
3176 		}
3177 	}
3178 
3179 	free(mode_buffer, M_SCSISA);
3180 	return (error);
3181 }
3182 
3183 static void
3184 saprevent(struct cam_periph *periph, int action)
3185 {
3186 	struct	sa_softc *softc;
3187 	union	ccb *ccb;
3188 	int	error, sf;
3189 
3190 	softc = (struct sa_softc *)periph->softc;
3191 
3192 	if ((action == PR_ALLOW) && (softc->flags & SA_FLAG_TAPE_LOCKED) == 0)
3193 		return;
3194 	if ((action == PR_PREVENT) && (softc->flags & SA_FLAG_TAPE_LOCKED) != 0)
3195 		return;
3196 
3197 	/*
3198 	 * We can be quiet about illegal requests.
3199 	 */
3200 	if (CAM_DEBUGGED(periph->path, CAM_DEBUG_INFO)) {
3201 		sf = 0;
3202 	} else
3203 		sf = SF_QUIET_IR;
3204 
3205 	ccb = cam_periph_getccb(periph, 1);
3206 
3207 	/* It is safe to retry this operation */
3208 	scsi_prevent(&ccb->csio, 5, sadone, MSG_SIMPLE_Q_TAG, action,
3209 	    SSD_FULL_SIZE, SCSIOP_TIMEOUT);
3210 
3211 	error = cam_periph_runccb(ccb, saerror, 0, sf, softc->device_stats);
3212 	if (error == 0) {
3213 		if (action == PR_ALLOW)
3214 			softc->flags &= ~SA_FLAG_TAPE_LOCKED;
3215 		else
3216 			softc->flags |= SA_FLAG_TAPE_LOCKED;
3217 	}
3218 
3219 	xpt_release_ccb(ccb);
3220 }
3221 
3222 static int
3223 sarewind(struct cam_periph *periph)
3224 {
3225 	union	ccb *ccb;
3226 	struct	sa_softc *softc;
3227 	int	error;
3228 
3229 	softc = (struct sa_softc *)periph->softc;
3230 
3231 	ccb = cam_periph_getccb(periph, 1);
3232 
3233 	/* It is safe to retry this operation */
3234 	scsi_rewind(&ccb->csio, 2, sadone, MSG_SIMPLE_Q_TAG, FALSE,
3235 	    SSD_FULL_SIZE, REWIND_TIMEOUT);
3236 
3237 	softc->dsreg = MTIO_DSREG_REW;
3238 	error = cam_periph_runccb(ccb, saerror, 0, 0, softc->device_stats);
3239 	softc->dsreg = MTIO_DSREG_REST;
3240 
3241 	xpt_release_ccb(ccb);
3242 	if (error == 0)
3243 		softc->fileno = softc->blkno = (daddr_t) 0;
3244 	else
3245 		softc->fileno = softc->blkno = (daddr_t) -1;
3246 	return (error);
3247 }
3248 
3249 static int
3250 saspace(struct cam_periph *periph, int count, scsi_space_code code)
3251 {
3252 	union	ccb *ccb;
3253 	struct	sa_softc *softc;
3254 	int	error;
3255 
3256 	softc = (struct sa_softc *)periph->softc;
3257 
3258 	ccb = cam_periph_getccb(periph, 1);
3259 
3260 	/* This cannot be retried */
3261 
3262 	scsi_space(&ccb->csio, 0, sadone, MSG_SIMPLE_Q_TAG, code, count,
3263 	    SSD_FULL_SIZE, SPACE_TIMEOUT);
3264 
3265 	/*
3266 	 * Clear residual because we will be using it.
3267 	 */
3268 	softc->last_ctl_resid = 0;
3269 
3270 	softc->dsreg = (count < 0)? MTIO_DSREG_REV : MTIO_DSREG_FWD;
3271 	error = cam_periph_runccb(ccb, saerror, 0, 0, softc->device_stats);
3272 	softc->dsreg = MTIO_DSREG_REST;
3273 
3274 	xpt_release_ccb(ccb);
3275 
3276 	/*
3277 	 * If a spacing operation has failed, we need to invalidate
3278 	 * this mount.
3279 	 *
3280 	 * If the spacing operation was setmarks or to end of recorded data,
3281 	 * we no longer know our relative position.
3282 	 *
3283 	 * If the spacing operations was spacing files in reverse, we
3284 	 * take account of the residual, but still check against less
3285 	 * than zero- if we've gone negative, we must have hit BOT.
3286 	 *
3287 	 * If the spacing operations was spacing records in reverse and
3288 	 * we have a residual, we've either hit BOT or hit a filemark.
3289 	 * In the former case, we know our new record number (0). In
3290 	 * the latter case, we have absolutely no idea what the real
3291 	 * record number is- we've stopped between the end of the last
3292 	 * record in the previous file and the filemark that stopped
3293 	 * our spacing backwards.
3294 	 */
3295 	if (error) {
3296 		softc->fileno = softc->blkno = (daddr_t) -1;
3297 	} else if (code == SS_SETMARKS || code == SS_EOD) {
3298 		softc->fileno = softc->blkno = (daddr_t) -1;
3299 	} else if (code == SS_FILEMARKS && softc->fileno != (daddr_t) -1) {
3300 		softc->fileno += (count - softc->last_ctl_resid);
3301 		if (softc->fileno < 0)	/* we must of hit BOT */
3302 			softc->fileno = 0;
3303 		softc->blkno = 0;
3304 	} else if (code == SS_BLOCKS && softc->blkno != (daddr_t) -1) {
3305 		softc->blkno += (count - softc->last_ctl_resid);
3306 		if (count < 0) {
3307 			if (softc->last_ctl_resid || softc->blkno < 0) {
3308 				if (softc->fileno == 0) {
3309 					softc->blkno = 0;
3310 				} else {
3311 					softc->blkno = (daddr_t) -1;
3312 				}
3313 			}
3314 		}
3315 	}
3316 	return (error);
3317 }
3318 
3319 static int
3320 sawritefilemarks(struct cam_periph *periph, int nmarks, int setmarks)
3321 {
3322 	union	ccb *ccb;
3323 	struct	sa_softc *softc;
3324 	int	error, nwm = 0;
3325 
3326 	softc = (struct sa_softc *)periph->softc;
3327 	if (softc->open_rdonly)
3328 		return (EBADF);
3329 
3330 	ccb = cam_periph_getccb(periph, 1);
3331 	/*
3332 	 * Clear residual because we will be using it.
3333 	 */
3334 	softc->last_ctl_resid = 0;
3335 
3336 	softc->dsreg = MTIO_DSREG_FMK;
3337 	/* this *must* not be retried */
3338 	scsi_write_filemarks(&ccb->csio, 0, sadone, MSG_SIMPLE_Q_TAG,
3339 	    FALSE, setmarks, nmarks, SSD_FULL_SIZE, IO_TIMEOUT);
3340 	softc->dsreg = MTIO_DSREG_REST;
3341 
3342 
3343 	error = cam_periph_runccb(ccb, saerror, 0, 0, softc->device_stats);
3344 
3345 	if (error == 0 && nmarks) {
3346 		struct sa_softc *softc = (struct sa_softc *)periph->softc;
3347 		nwm = nmarks - softc->last_ctl_resid;
3348 		softc->filemarks += nwm;
3349 	}
3350 
3351 	xpt_release_ccb(ccb);
3352 
3353 	/*
3354 	 * Update relative positions (if we're doing that).
3355 	 */
3356 	if (error) {
3357 		softc->fileno = softc->blkno = (daddr_t) -1;
3358 	} else if (softc->fileno != (daddr_t) -1) {
3359 		softc->fileno += nwm;
3360 		softc->blkno = 0;
3361 	}
3362 	return (error);
3363 }
3364 
3365 static int
3366 sardpos(struct cam_periph *periph, int hard, u_int32_t *blkptr)
3367 {
3368 	struct scsi_tape_position_data loc;
3369 	union ccb *ccb;
3370 	struct sa_softc *softc = (struct sa_softc *)periph->softc;
3371 	int error;
3372 
3373 	/*
3374 	 * We try and flush any buffered writes here if we were writing
3375 	 * and we're trying to get hardware block position. It eats
3376 	 * up performance substantially, but I'm wary of drive firmware.
3377 	 *
3378 	 * I think that *logical* block position is probably okay-
3379 	 * but hardware block position might have to wait for data
3380 	 * to hit media to be valid. Caveat Emptor.
3381 	 */
3382 
3383 	if (hard && (softc->flags & SA_FLAG_TAPE_WRITTEN)) {
3384 		error = sawritefilemarks(periph, 0, 0);
3385 		if (error && error != EACCES)
3386 			return (error);
3387 	}
3388 
3389 	ccb = cam_periph_getccb(periph, 1);
3390 	scsi_read_position(&ccb->csio, 1, sadone, MSG_SIMPLE_Q_TAG,
3391 	    hard, &loc, SSD_FULL_SIZE, SCSIOP_TIMEOUT);
3392 	softc->dsreg = MTIO_DSREG_RBSY;
3393 	error = cam_periph_runccb(ccb, saerror, 0, 0, softc->device_stats);
3394 	softc->dsreg = MTIO_DSREG_REST;
3395 
3396 	if (error == 0) {
3397 		if (loc.flags & SA_RPOS_UNCERTAIN) {
3398 			error = EINVAL;		/* nothing is certain */
3399 		} else {
3400 			*blkptr = scsi_4btoul(loc.firstblk);
3401 		}
3402 	}
3403 
3404 	xpt_release_ccb(ccb);
3405 	return (error);
3406 }
3407 
3408 static int
3409 sasetpos(struct cam_periph *periph, int hard, u_int32_t *blkptr)
3410 {
3411 	union ccb *ccb;
3412 	struct sa_softc *softc;
3413 	int error;
3414 
3415 	/*
3416 	 * We used to try and flush any buffered writes here.
3417 	 * Now we push this onto user applications to either
3418 	 * flush the pending writes themselves (via a zero count
3419 	 * WRITE FILEMARKS command) or they can trust their tape
3420 	 * drive to do this correctly for them.
3421  	 */
3422 
3423 	softc = (struct sa_softc *)periph->softc;
3424 	ccb = cam_periph_getccb(periph, 1);
3425 
3426 
3427 	scsi_set_position(&ccb->csio, 1, sadone, MSG_SIMPLE_Q_TAG,
3428 	    hard, *blkptr, SSD_FULL_SIZE, SPACE_TIMEOUT);
3429 
3430 
3431 	softc->dsreg = MTIO_DSREG_POS;
3432 	error = cam_periph_runccb(ccb, saerror, 0, 0, softc->device_stats);
3433 	softc->dsreg = MTIO_DSREG_REST;
3434 	xpt_release_ccb(ccb);
3435 	/*
3436 	 * Note relative file && block number position as now unknown.
3437 	 */
3438 	softc->fileno = softc->blkno = (daddr_t) -1;
3439 	return (error);
3440 }
3441 
3442 static int
3443 saretension(struct cam_periph *periph)
3444 {
3445 	union ccb *ccb;
3446 	struct sa_softc *softc;
3447 	int error;
3448 
3449 	softc = (struct sa_softc *)periph->softc;
3450 
3451 	ccb = cam_periph_getccb(periph, 1);
3452 
3453 	/* It is safe to retry this operation */
3454 	scsi_load_unload(&ccb->csio, 5, sadone, MSG_SIMPLE_Q_TAG, FALSE,
3455 	    FALSE, TRUE,  TRUE, SSD_FULL_SIZE, ERASE_TIMEOUT);
3456 
3457 	softc->dsreg = MTIO_DSREG_TEN;
3458 	error = cam_periph_runccb(ccb, saerror, 0, 0, softc->device_stats);
3459 	softc->dsreg = MTIO_DSREG_REST;
3460 
3461 	xpt_release_ccb(ccb);
3462 	if (error == 0)
3463 		softc->fileno = softc->blkno = (daddr_t) 0;
3464 	else
3465 		softc->fileno = softc->blkno = (daddr_t) -1;
3466 	return (error);
3467 }
3468 
3469 static int
3470 sareservereleaseunit(struct cam_periph *periph, int reserve)
3471 {
3472 	union ccb *ccb;
3473 	struct sa_softc *softc;
3474 	int error;
3475 
3476 	softc = (struct sa_softc *)periph->softc;
3477 	ccb = cam_periph_getccb(periph,  1);
3478 
3479 	/* It is safe to retry this operation */
3480 	scsi_reserve_release_unit(&ccb->csio, 2, sadone, MSG_SIMPLE_Q_TAG,
3481 	    FALSE,  0, SSD_FULL_SIZE,  SCSIOP_TIMEOUT, reserve);
3482 	softc->dsreg = MTIO_DSREG_RBSY;
3483 	error = cam_periph_runccb(ccb, saerror, 0,
3484 	    SF_RETRY_UA | SF_NO_PRINT, softc->device_stats);
3485 	softc->dsreg = MTIO_DSREG_REST;
3486 	xpt_release_ccb(ccb);
3487 
3488 	/*
3489 	 * If the error was Illegal Request, then the device doesn't support
3490 	 * RESERVE/RELEASE. This is not an error.
3491 	 */
3492 	if (error == EINVAL) {
3493 		error = 0;
3494 	}
3495 
3496 	return (error);
3497 }
3498 
3499 static int
3500 saloadunload(struct cam_periph *periph, int load)
3501 {
3502 	union	ccb *ccb;
3503 	struct	sa_softc *softc;
3504 	int	error;
3505 
3506 	softc = (struct sa_softc *)periph->softc;
3507 
3508 	ccb = cam_periph_getccb(periph, 1);
3509 
3510 	/* It is safe to retry this operation */
3511 	scsi_load_unload(&ccb->csio, 5, sadone, MSG_SIMPLE_Q_TAG, FALSE,
3512 	    FALSE, FALSE, load, SSD_FULL_SIZE, REWIND_TIMEOUT);
3513 
3514 	softc->dsreg = (load)? MTIO_DSREG_LD : MTIO_DSREG_UNL;
3515 	error = cam_periph_runccb(ccb, saerror, 0, 0, softc->device_stats);
3516 	softc->dsreg = MTIO_DSREG_REST;
3517 	xpt_release_ccb(ccb);
3518 
3519 	if (error || load == 0)
3520 		softc->fileno = softc->blkno = (daddr_t) -1;
3521 	else if (error == 0)
3522 		softc->fileno = softc->blkno = (daddr_t) 0;
3523 	return (error);
3524 }
3525 
3526 static int
3527 saerase(struct cam_periph *periph, int longerase)
3528 {
3529 
3530 	union	ccb *ccb;
3531 	struct	sa_softc *softc;
3532 	int error;
3533 
3534 	softc = (struct sa_softc *)periph->softc;
3535 	if (softc->open_rdonly)
3536 		return (EBADF);
3537 
3538 	ccb = cam_periph_getccb(periph, 1);
3539 
3540 	scsi_erase(&ccb->csio, 1, sadone, MSG_SIMPLE_Q_TAG, FALSE, longerase,
3541 	    SSD_FULL_SIZE, ERASE_TIMEOUT);
3542 
3543 	softc->dsreg = MTIO_DSREG_ZER;
3544 	error = cam_periph_runccb(ccb, saerror, 0, 0, softc->device_stats);
3545 	softc->dsreg = MTIO_DSREG_REST;
3546 
3547 	xpt_release_ccb(ccb);
3548 	return (error);
3549 }
3550 
3551 #endif /* _KERNEL */
3552 
3553 /*
3554  * Read tape block limits command.
3555  */
3556 void
3557 scsi_read_block_limits(struct ccb_scsiio *csio, u_int32_t retries,
3558 		   void (*cbfcnp)(struct cam_periph *, union ccb *),
3559 		   u_int8_t tag_action,
3560 		   struct scsi_read_block_limits_data *rlimit_buf,
3561 		   u_int8_t sense_len, u_int32_t timeout)
3562 {
3563 	struct scsi_read_block_limits *scsi_cmd;
3564 
3565 	cam_fill_csio(csio, retries, cbfcnp, CAM_DIR_IN, tag_action,
3566 	     (u_int8_t *)rlimit_buf, sizeof(*rlimit_buf), sense_len,
3567 	     sizeof(*scsi_cmd), timeout);
3568 
3569 	scsi_cmd = (struct scsi_read_block_limits *)&csio->cdb_io.cdb_bytes;
3570 	bzero(scsi_cmd, sizeof(*scsi_cmd));
3571 	scsi_cmd->opcode = READ_BLOCK_LIMITS;
3572 }
3573 
3574 void
3575 scsi_sa_read_write(struct ccb_scsiio *csio, u_int32_t retries,
3576 		   void (*cbfcnp)(struct cam_periph *, union ccb *),
3577 		   u_int8_t tag_action, int readop, int sli,
3578 		   int fixed, u_int32_t length, u_int8_t *data_ptr,
3579 		   u_int32_t dxfer_len, u_int8_t sense_len, u_int32_t timeout)
3580 {
3581 	struct scsi_sa_rw *scsi_cmd;
3582 	int read;
3583 
3584 	read = (readop & SCSI_RW_DIRMASK) == SCSI_RW_READ;
3585 
3586 	scsi_cmd = (struct scsi_sa_rw *)&csio->cdb_io.cdb_bytes;
3587 	scsi_cmd->opcode = read ? SA_READ : SA_WRITE;
3588 	scsi_cmd->sli_fixed = 0;
3589 	if (sli && read)
3590 		scsi_cmd->sli_fixed |= SAR_SLI;
3591 	if (fixed)
3592 		scsi_cmd->sli_fixed |= SARW_FIXED;
3593 	scsi_ulto3b(length, scsi_cmd->length);
3594 	scsi_cmd->control = 0;
3595 
3596 	cam_fill_csio(csio, retries, cbfcnp, (read ? CAM_DIR_IN : CAM_DIR_OUT) |
3597 	    ((readop & SCSI_RW_BIO) != 0 ? CAM_DATA_BIO : 0),
3598 	    tag_action, data_ptr, dxfer_len, sense_len,
3599 	    sizeof(*scsi_cmd), timeout);
3600 }
3601 
3602 void
3603 scsi_load_unload(struct ccb_scsiio *csio, u_int32_t retries,
3604 		 void (*cbfcnp)(struct cam_periph *, union ccb *),
3605 		 u_int8_t tag_action, int immediate, int eot,
3606 		 int reten, int load, u_int8_t sense_len,
3607 		 u_int32_t timeout)
3608 {
3609 	struct scsi_load_unload *scsi_cmd;
3610 
3611 	scsi_cmd = (struct scsi_load_unload *)&csio->cdb_io.cdb_bytes;
3612 	bzero(scsi_cmd, sizeof(*scsi_cmd));
3613 	scsi_cmd->opcode = LOAD_UNLOAD;
3614 	if (immediate)
3615 		scsi_cmd->immediate = SLU_IMMED;
3616 	if (eot)
3617 		scsi_cmd->eot_reten_load |= SLU_EOT;
3618 	if (reten)
3619 		scsi_cmd->eot_reten_load |= SLU_RETEN;
3620 	if (load)
3621 		scsi_cmd->eot_reten_load |= SLU_LOAD;
3622 
3623 	cam_fill_csio(csio, retries, cbfcnp, CAM_DIR_NONE, tag_action,
3624 	    NULL, 0, sense_len, sizeof(*scsi_cmd), timeout);
3625 }
3626 
3627 void
3628 scsi_rewind(struct ccb_scsiio *csio, u_int32_t retries,
3629 	    void (*cbfcnp)(struct cam_periph *, union ccb *),
3630 	    u_int8_t tag_action, int immediate, u_int8_t sense_len,
3631 	    u_int32_t timeout)
3632 {
3633 	struct scsi_rewind *scsi_cmd;
3634 
3635 	scsi_cmd = (struct scsi_rewind *)&csio->cdb_io.cdb_bytes;
3636 	bzero(scsi_cmd, sizeof(*scsi_cmd));
3637 	scsi_cmd->opcode = REWIND;
3638 	if (immediate)
3639 		scsi_cmd->immediate = SREW_IMMED;
3640 
3641 	cam_fill_csio(csio, retries, cbfcnp, CAM_DIR_NONE, tag_action, NULL,
3642 	    0, sense_len, sizeof(*scsi_cmd), timeout);
3643 }
3644 
3645 void
3646 scsi_space(struct ccb_scsiio *csio, u_int32_t retries,
3647 	   void (*cbfcnp)(struct cam_periph *, union ccb *),
3648 	   u_int8_t tag_action, scsi_space_code code,
3649 	   u_int32_t count, u_int8_t sense_len, u_int32_t timeout)
3650 {
3651 	struct scsi_space *scsi_cmd;
3652 
3653 	scsi_cmd = (struct scsi_space *)&csio->cdb_io.cdb_bytes;
3654 	scsi_cmd->opcode = SPACE;
3655 	scsi_cmd->code = code;
3656 	scsi_ulto3b(count, scsi_cmd->count);
3657 	scsi_cmd->control = 0;
3658 
3659 	cam_fill_csio(csio, retries, cbfcnp, CAM_DIR_NONE, tag_action, NULL,
3660 	    0, sense_len, sizeof(*scsi_cmd), timeout);
3661 }
3662 
3663 void
3664 scsi_write_filemarks(struct ccb_scsiio *csio, u_int32_t retries,
3665 		     void (*cbfcnp)(struct cam_periph *, union ccb *),
3666 		     u_int8_t tag_action, int immediate, int setmark,
3667 		     u_int32_t num_marks, u_int8_t sense_len,
3668 		     u_int32_t timeout)
3669 {
3670 	struct scsi_write_filemarks *scsi_cmd;
3671 
3672 	scsi_cmd = (struct scsi_write_filemarks *)&csio->cdb_io.cdb_bytes;
3673 	bzero(scsi_cmd, sizeof(*scsi_cmd));
3674 	scsi_cmd->opcode = WRITE_FILEMARKS;
3675 	if (immediate)
3676 		scsi_cmd->byte2 |= SWFMRK_IMMED;
3677 	if (setmark)
3678 		scsi_cmd->byte2 |= SWFMRK_WSMK;
3679 
3680 	scsi_ulto3b(num_marks, scsi_cmd->num_marks);
3681 
3682 	cam_fill_csio(csio, retries, cbfcnp, CAM_DIR_NONE, tag_action, NULL,
3683 	    0, sense_len, sizeof(*scsi_cmd), timeout);
3684 }
3685 
3686 /*
3687  * The reserve and release unit commands differ only by their opcodes.
3688  */
3689 void
3690 scsi_reserve_release_unit(struct ccb_scsiio *csio, u_int32_t retries,
3691 			  void (*cbfcnp)(struct cam_periph *, union ccb *),
3692 			  u_int8_t tag_action, int third_party,
3693 			  int third_party_id, u_int8_t sense_len,
3694 			  u_int32_t timeout, int reserve)
3695 {
3696 	struct scsi_reserve_release_unit *scsi_cmd;
3697 
3698 	scsi_cmd = (struct scsi_reserve_release_unit *)&csio->cdb_io.cdb_bytes;
3699 	bzero(scsi_cmd, sizeof(*scsi_cmd));
3700 
3701 	if (reserve)
3702 		scsi_cmd->opcode = RESERVE_UNIT;
3703 	else
3704 		scsi_cmd->opcode = RELEASE_UNIT;
3705 
3706 	if (third_party) {
3707 		scsi_cmd->lun_thirdparty |= SRRU_3RD_PARTY;
3708 		scsi_cmd->lun_thirdparty |=
3709 			((third_party_id << SRRU_3RD_SHAMT) & SRRU_3RD_MASK);
3710 	}
3711 
3712 	cam_fill_csio(csio, retries, cbfcnp, CAM_DIR_NONE, tag_action, NULL,
3713 	    0, sense_len, sizeof(*scsi_cmd), timeout);
3714 }
3715 
3716 void
3717 scsi_erase(struct ccb_scsiio *csio, u_int32_t retries,
3718 	   void (*cbfcnp)(struct cam_periph *, union ccb *),
3719 	   u_int8_t tag_action, int immediate, int long_erase,
3720 	   u_int8_t sense_len, u_int32_t timeout)
3721 {
3722 	struct scsi_erase *scsi_cmd;
3723 
3724 	scsi_cmd = (struct scsi_erase *)&csio->cdb_io.cdb_bytes;
3725 	bzero(scsi_cmd, sizeof(*scsi_cmd));
3726 
3727 	scsi_cmd->opcode = ERASE;
3728 
3729 	if (immediate)
3730 		scsi_cmd->lun_imm_long |= SE_IMMED;
3731 
3732 	if (long_erase)
3733 		scsi_cmd->lun_imm_long |= SE_LONG;
3734 
3735 	cam_fill_csio(csio, retries, cbfcnp, CAM_DIR_NONE, tag_action, NULL,
3736 	    0, sense_len, sizeof(*scsi_cmd), timeout);
3737 }
3738 
3739 /*
3740  * Read Tape Position command.
3741  */
3742 void
3743 scsi_read_position(struct ccb_scsiio *csio, u_int32_t retries,
3744 		   void (*cbfcnp)(struct cam_periph *, union ccb *),
3745 		   u_int8_t tag_action, int hardsoft,
3746 		   struct scsi_tape_position_data *sbp,
3747 		   u_int8_t sense_len, u_int32_t timeout)
3748 {
3749 	struct scsi_tape_read_position *scmd;
3750 
3751 	cam_fill_csio(csio, retries, cbfcnp, CAM_DIR_IN, tag_action,
3752 	    (u_int8_t *)sbp, sizeof (*sbp), sense_len, sizeof(*scmd), timeout);
3753 	scmd = (struct scsi_tape_read_position *)&csio->cdb_io.cdb_bytes;
3754 	bzero(scmd, sizeof(*scmd));
3755 	scmd->opcode = READ_POSITION;
3756 	scmd->byte1 = hardsoft;
3757 }
3758 
3759 /*
3760  * Set Tape Position command.
3761  */
3762 void
3763 scsi_set_position(struct ccb_scsiio *csio, u_int32_t retries,
3764 		   void (*cbfcnp)(struct cam_periph *, union ccb *),
3765 		   u_int8_t tag_action, int hardsoft, u_int32_t blkno,
3766 		   u_int8_t sense_len, u_int32_t timeout)
3767 {
3768 	struct scsi_tape_locate *scmd;
3769 
3770 	cam_fill_csio(csio, retries, cbfcnp, CAM_DIR_NONE, tag_action,
3771 	    (u_int8_t *)NULL, 0, sense_len, sizeof(*scmd), timeout);
3772 	scmd = (struct scsi_tape_locate *)&csio->cdb_io.cdb_bytes;
3773 	bzero(scmd, sizeof(*scmd));
3774 	scmd->opcode = LOCATE;
3775 	if (hardsoft)
3776 		scmd->byte1 |= SA_SPOS_BT;
3777 	scsi_ulto4b(blkno, scmd->blkaddr);
3778 }
3779