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