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