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