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