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