xref: /openbsd-src/sys/scsi/st.c (revision 2b0358df1d88d06ef4139321dd05bd5e05d91eaf)
1 /*	$OpenBSD: st.c,v 1.86 2009/02/16 21:19:07 miod Exp $	*/
2 /*	$NetBSD: st.c,v 1.71 1997/02/21 23:03:49 thorpej Exp $	*/
3 
4 /*
5  * Copyright (c) 1994 Charles Hannum.  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  * 2. Redistributions in binary form must reproduce the above copyright
13  *    notice, this list of conditions and the following disclaimer in the
14  *    documentation and/or other materials provided with the distribution.
15  * 3. All advertising materials mentioning features or use of this software
16  *    must display the following acknowledgement:
17  *	This product includes software developed by Charles Hannum.
18  * 4. The name of the author may not be used to endorse or promote products
19  *    derived from this software without specific prior written permission.
20  *
21  * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR
22  * IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
23  * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.
24  * IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT,
25  * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
26  * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
27  * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
28  * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
29  * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
30  * THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
31  */
32 
33 /*
34  * Originally written by Julian Elischer (julian@tfs.com)
35  * for TRW Financial Systems for use under the MACH(2.5) operating system.
36  *
37  * TRW Financial Systems, in accordance with their agreement with Carnegie
38  * Mellon University, makes this software available to CMU to distribute
39  * or use in any manner that they see fit as long as this message is kept with
40  * the software. For this reason TFS also grants any other persons or
41  * organisations permission to use or modify this software.
42  *
43  * TFS supplies this software to be publicly redistributed
44  * on the understanding that TFS is not responsible for the correct
45  * functioning of this software in any circumstances.
46  *
47  * Ported to run under 386BSD by Julian Elischer (julian@tfs.com) Sept 1992
48  * major changes by Julian Elischer (julian@jules.dialix.oz.au) May 1993
49  */
50 
51 /*
52  * To do:
53  * work out some better way of guessing what a good timeout is going
54  * to be depending on whether we expect to retension or not.
55  */
56 
57 #include <sys/types.h>
58 #include <sys/param.h>
59 #include <sys/systm.h>
60 #include <sys/timeout.h>
61 #include <sys/fcntl.h>
62 #include <sys/errno.h>
63 #include <sys/ioctl.h>
64 #include <sys/stat.h>
65 #include <sys/malloc.h>
66 #include <sys/buf.h>
67 #include <sys/proc.h>
68 #include <sys/user.h>
69 #include <sys/mtio.h>
70 #include <sys/device.h>
71 #include <sys/conf.h>
72 #include <sys/vnode.h>
73 
74 #include <scsi/scsi_all.h>
75 #include <scsi/scsi_tape.h>
76 #include <scsi/scsiconf.h>
77 
78 /* Defines for device specific stuff */
79 #define DEF_FIXED_BSIZE  512
80 
81 #define STMODE(z)	( minor(z)	 & 0x03)
82 #define STUNIT(z)	((minor(z) >> 4)       )
83 
84 #define	ST_IO_TIME	(3 * 60 * 1000)		/* 3 minutes */
85 #define	ST_CTL_TIME	(30 * 1000)		/* 30 seconds */
86 #define	ST_SPC_TIME	(4 * 60 * 60 * 1000)	/* 4 hours */
87 
88 /*
89  * Maximum density code allowed in SCSI spec (SSC2R08f, Section 8.3).
90  */
91 #define SCSI_MAX_DENSITY_CODE		0xff
92 
93 /*
94  * Define various devices that we know mis-behave in some way,
95  * and note how they are bad, so we can correct for them
96  */
97 struct modes {
98 	u_int quirks;			/* same definitions as in quirkdata */
99 	int blksize;
100 	u_int8_t density;
101 };
102 
103 struct quirkdata {
104 	u_int quirks;
105 #define	ST_Q_FORCE_BLKSIZE	0x0001
106 #define	ST_Q_SENSE_HELP		0x0002	/* must do READ for good MODE SENSE */
107 #define	ST_Q_IGNORE_LOADS	0x0004
108 #define	ST_Q_BLKSIZE		0x0008	/* variable-block media_blksize > 0 */
109 #define	ST_Q_UNIMODAL		0x0010	/* unimode drive rejects mode select */
110 	struct modes modes;
111 };
112 
113 struct st_quirk_inquiry_pattern {
114 	struct scsi_inquiry_pattern pattern;
115 	struct quirkdata quirkdata;
116 };
117 
118 const struct st_quirk_inquiry_pattern st_quirk_patterns[] = {
119 	{{T_SEQUENTIAL, T_REMOV,
120 	 "        ", "                ", "    "}, {0,
121 		{ST_Q_FORCE_BLKSIZE, 512, 0}}},		/* minor 0-3 */
122 	{{T_SEQUENTIAL, T_REMOV,
123 	 "TANDBERG", " TDC 3600       ", ""},     {0,
124 		{0, 0, 0}}},				/* minor 0-3 */
125  	{{T_SEQUENTIAL, T_REMOV,
126  	 "TANDBERG", " TDC 3800       ", ""},     {0,
127 		{ST_Q_FORCE_BLKSIZE, 512, 0}}},		/* minor 0-3 */
128 	/*
129 	 * At least -005 and -007 need this.  I'll assume they all do unless I
130 	 * hear otherwise.  - mycroft, 31MAR1994
131 	 */
132 	{{T_SEQUENTIAL, T_REMOV,
133 	 "ARCHIVE ", "VIPER 2525 25462", ""},     {0,
134 		{ST_Q_SENSE_HELP, 0, 0}}},		/* minor 0-3 */
135 	/*
136 	 * One user reports that this works for his tape drive.  It probably
137 	 * needs more work.  - mycroft, 09APR1994
138 	 */
139 	{{T_SEQUENTIAL, T_REMOV,
140 	 "SANKYO  ", "CP525           ", ""},    {0,
141 		{ST_Q_FORCE_BLKSIZE, 512, 0}}},		/* minor 0-3 */
142 	{{T_SEQUENTIAL, T_REMOV,
143 	 "ANRITSU ", "DMT780          ", ""},     {0,
144 		{ST_Q_FORCE_BLKSIZE, 512, 0}}},		/* minor 0-3 */
145 	{{T_SEQUENTIAL, T_REMOV,
146 	 "ARCHIVE ", "VIPER 150  21247", ""},     {0,
147 		{0, 0, 0}}},				/* minor 0-3 */
148 	{{T_SEQUENTIAL, T_REMOV,
149 	 "ARCHIVE ", "VIPER 150  21531", ""},     {0,
150 		{ST_Q_SENSE_HELP, 0, 0}}},		/* minor 0-3 */
151 	{{T_SEQUENTIAL, T_REMOV,
152 	 "WANGTEK ", "5099ES SCSI", ""},          {0,
153 		{ST_Q_FORCE_BLKSIZE, 512, 0}}},		/* minor 0-3 */
154 	{{T_SEQUENTIAL, T_REMOV,
155 	 "WANGTEK ", "5150ES SCSI", ""},          {0,
156 		{ST_Q_FORCE_BLKSIZE, 512, 0}}},		/* minor 0-3 */
157 	{{T_SEQUENTIAL, T_REMOV,
158 	 "WANGTEK ", "5525ES SCSI REV7", ""},     {0,
159 		{0, 0, 0}}},				/* minor 0-3 */
160 	{{T_SEQUENTIAL, T_REMOV,
161 	 "WangDAT ", "Model 1300      ", ""},     {0,
162 		{0, 0, 0}}},				/* minor 0-3 */
163 	{{T_SEQUENTIAL, T_REMOV,
164 	 "EXABYTE ", "EXB-8200        ", "263H"}, {0,
165 		{0, 0, 0}}},				/* minor 0-3 */
166 	{{T_SEQUENTIAL, T_REMOV,
167 	 "HP      ", "T4000s          ", ""},     {ST_Q_UNIMODAL,
168 		{0, 0, QIC_3095}}},			/* minor 0-3 */
169 #if 0
170 	{{T_SEQUENTIAL, T_REMOV,
171 	 "EXABYTE ", "EXB-8200        ", ""},     {0,
172 		{0, 0, 0}}},				/* minor 0-3 */
173 #endif
174 	{{T_SEQUENTIAL, T_REMOV,
175 	 "WANGTEK ", "5150ES SCSI FA15\0""01 A", "????"}, {0,
176 		{ST_Q_IGNORE_LOADS, 0, 0}}},		/* minor 0-3 */
177 	{{T_SEQUENTIAL, T_REMOV,
178 	 "TEAC    ", "MT-2ST/N50      ", ""},     {ST_Q_IGNORE_LOADS,
179 		{0, 0, 0}}},				/* minor 0-3 */
180 };
181 
182 #define NOEJECT 0
183 #define EJECT 1
184 
185 #define NOREWIND 0
186 #define DOREWIND 1
187 
188 struct st_softc {
189 	struct device sc_dev;
190 
191 	int flags;		/* see below                          */
192 	u_int quirks;		/* quirks for the open mode           */
193 	int blksize;		/* blksize we are using               */
194 	u_int8_t density;	/* present density                    */
195 	short mt_resid;		/* last (short) resid                 */
196 	short mt_erreg;		/* last error (sense key) seen        */
197 
198 	struct scsi_link *sc_link;	/* our link to the adpter etc.        */
199 
200 	int blkmin;		/* min blk size                       */
201 	int blkmax;		/* max blk size                       */
202 	const struct quirkdata *quirkdata;	/* if we have a rogue entry */
203 
204 	u_int64_t numblks;		/* nominal blocks capacity            */
205 	u_int32_t media_blksize;	/* 0 if not ST_FIXEDBLOCKS            */
206 	u_int32_t media_density;	/* this is what it said when asked    */
207 	int media_fileno;		/* relative to BOT. -1 means unknown. */
208 	int media_blkno;		/* relative to BOF. -1 means unknown. */
209 
210 	u_int drive_quirks;	/* quirks of this drive               */
211 
212 	struct modes modes;	/* plus more for each mode            */
213 	u_int8_t  modeflags;	/* flags for the modes                */
214 #define DENSITY_SET_BY_USER	0x01
215 #define DENSITY_SET_BY_QUIRK	0x02
216 #define BLKSIZE_SET_BY_USER	0x04
217 #define BLKSIZE_SET_BY_QUIRK	0x08
218 
219 	struct buf buf_queue;		/* the queue of pending IO operations */
220 	struct timeout sc_timeout;
221 };
222 
223 
224 int	stmatch(struct device *, void *, void *);
225 void	stattach(struct device *, struct device *, void *);
226 int	stactivate(struct device *, enum devact);
227 int	stdetach(struct device *, int);
228 
229 void	stminphys(struct buf *);
230 void	st_kill_buffers(struct st_softc *);
231 void	st_identify_drive(struct st_softc *, struct scsi_inquiry_data *);
232 void	st_loadquirks(struct st_softc *);
233 int	st_mount_tape(dev_t, int);
234 void	st_unmount(struct st_softc *, int, int);
235 int	st_decide_mode(struct st_softc *, int);
236 void	ststart(void *);
237 void	strestart(void *);
238 int	st_read(struct st_softc *, char *, int, int);
239 int	st_read_block_limits(struct st_softc *, int);
240 int	st_mode_sense(struct st_softc *, int);
241 int	st_mode_select(struct st_softc *, int);
242 int	st_space(struct st_softc *, int, u_int, int);
243 int	st_write_filemarks(struct st_softc *, int, int);
244 int	st_check_eod(struct st_softc *, int, int *, int);
245 int	st_load(struct st_softc *, u_int, int);
246 int	st_rewind(struct st_softc *, u_int, int);
247 int	st_interpret_sense(struct scsi_xfer *);
248 int	st_touch_tape(struct st_softc *);
249 int	st_erase(struct st_softc *, int, int);
250 
251 struct cfattach st_ca = {
252 	sizeof(struct st_softc), stmatch, stattach,
253 	stdetach, stactivate
254 };
255 
256 struct cfdriver st_cd = {
257 	NULL, "st", DV_TAPE
258 };
259 
260 struct scsi_device st_switch = {
261 	st_interpret_sense,
262 	ststart,
263 	NULL,
264 	NULL,
265 };
266 
267 #define	ST_INFO_VALID	0x0001
268 #define	ST_BLOCK_SET	0x0002	/* block size, mode set by ioctl      */
269 #define	ST_WRITTEN	0x0004	/* data have been written, EOD needed */
270 #define	ST_FIXEDBLOCKS	0x0008
271 #define	ST_AT_FILEMARK	0x0010
272 #define	ST_EIO_PENDING	0x0020	/* we couldn't report it then (had data) */
273 #define	ST_READONLY	0x0080	/* st_mode_sense says write protected */
274 #define	ST_FM_WRITTEN	0x0100	/*
275 				 * EOF file mark written  -- used with
276 				 * ~ST_WRITTEN to indicate that multiple file
277 				 * marks have been written
278 				 */
279 #define	ST_DYING	0x40	/* dying, when deactivated */
280 #define	ST_BLANK_READ	0x0200	/* BLANK CHECK encountered already */
281 #define	ST_2FM_AT_EOD	0x0400	/* write 2 file marks at EOD */
282 #define	ST_MOUNTED	0x0800	/* Device is presently mounted */
283 #define	ST_DONTBUFFER	0x1000	/* Disable buffering/caching */
284 
285 #define	ST_PER_ACTION	(ST_AT_FILEMARK | ST_EIO_PENDING | ST_BLANK_READ)
286 #define	ST_PER_MOUNT	(ST_INFO_VALID | ST_BLOCK_SET | ST_WRITTEN | \
287 			 ST_FIXEDBLOCKS | ST_READONLY | ST_FM_WRITTEN | \
288 			 ST_2FM_AT_EOD | ST_PER_ACTION)
289 
290 #define stlookup(unit) (struct st_softc *)device_lookup(&st_cd, (unit))
291 
292 const struct scsi_inquiry_pattern st_patterns[] = {
293 	{T_SEQUENTIAL, T_REMOV,
294 	 "",         "",                 ""},
295 };
296 
297 int
298 stmatch(struct device *parent, void *match, void *aux)
299 {
300 	struct scsi_attach_args *sa = aux;
301 	int priority;
302 
303 	(void)scsi_inqmatch(sa->sa_inqbuf,
304 	    st_patterns, sizeof(st_patterns)/sizeof(st_patterns[0]),
305 	    sizeof(st_patterns[0]), &priority);
306 	return (priority);
307 }
308 
309 /*
310  * The routine called by the low level scsi routine when it discovers
311  * A device suitable for this driver
312  */
313 void
314 stattach(struct device *parent, struct device *self, void *aux)
315 {
316 	struct st_softc *st = (void *)self;
317 	struct scsi_attach_args *sa = aux;
318 	struct scsi_link *sc_link = sa->sa_sc_link;
319 
320 	SC_DEBUG(sc_link, SDEV_DB2, ("stattach:\n"));
321 
322 	/*
323 	 * Store information needed to contact our base driver
324 	 */
325 	st->sc_link = sc_link;
326 	sc_link->device = &st_switch;
327 	sc_link->device_softc = st;
328 
329 	/*
330 	 * Check if the drive is a known criminal and take
331 	 * Any steps needed to bring it into line
332 	 */
333 	st_identify_drive(st, sa->sa_inqbuf);
334 	printf("\n");
335 
336 	timeout_set(&st->sc_timeout, strestart, st);
337 
338 	/*
339 	 * Set up the buf queue for this device
340 	 */
341 	st->buf_queue.b_active = 0;
342 	st->buf_queue.b_actf = 0;
343 	st->buf_queue.b_actb = &st->buf_queue.b_actf;
344 
345 	/* Start up with media position unknown. */
346 	st->media_fileno = -1;
347 	st->media_blkno = -1;
348 
349 	/*
350 	 * Reset the media loaded flag, sometimes the data
351 	 * acquired at boot time is not quite accurate.  This
352 	 * will be checked again at the first open.
353 	 */
354 	sc_link->flags &= ~SDEV_MEDIA_LOADED;
355 }
356 
357 int
358 stactivate(struct device *self, enum devact act)
359 {
360 	struct st_softc *st = (struct st_softc *)self;
361 	int rv = 0;
362 
363 	switch (act) {
364 	case DVACT_ACTIVATE:
365 		break;
366 
367 	case DVACT_DEACTIVATE:
368 		st->flags |= ST_DYING;
369 		st_kill_buffers(st);
370 		break;
371 	}
372 
373 	return (rv);
374 }
375 
376 int
377 stdetach(struct device *self, int flags)
378 {
379 	struct st_softc *st = (struct st_softc *)self;
380 	int bmaj, cmaj, mn;
381 
382 	st_kill_buffers(st);
383 
384 	/* Locate the lowest minor number to be detached. */
385 	mn = STUNIT(self->dv_unit);
386 
387 	for (bmaj = 0; bmaj < nblkdev; bmaj++)
388 		if (bdevsw[bmaj].d_open == stopen) {
389 			vdevgone(bmaj, mn, mn + 0, VBLK);
390 			vdevgone(bmaj, mn, mn + 1, VBLK);
391 			vdevgone(bmaj, mn, mn + 2, VBLK);
392 			vdevgone(bmaj, mn, mn + 3, VBLK);
393 		}
394 	for (cmaj = 0; cmaj < nchrdev; cmaj++)
395 		if (cdevsw[cmaj].d_open == stopen) {
396 			vdevgone(cmaj, mn, mn + 0, VCHR);
397 			vdevgone(cmaj, mn, mn + 1, VCHR);
398 			vdevgone(cmaj, mn, mn + 2, VCHR);
399 			vdevgone(cmaj, mn, mn + 3, VCHR);
400 		}
401 
402 	return (0);
403 }
404 
405 /*
406  * Use the inquiry routine in 'scsi_base' to get drive info so we can
407  * Further tailor our behaviour.
408  */
409 void
410 st_identify_drive(struct st_softc *st, struct scsi_inquiry_data *inqbuf)
411 {
412 	const struct st_quirk_inquiry_pattern *finger;
413 	int priority;
414 
415 	finger = (const struct st_quirk_inquiry_pattern *)scsi_inqmatch(inqbuf,
416 	    st_quirk_patterns,
417 	    sizeof(st_quirk_patterns)/sizeof(st_quirk_patterns[0]),
418 	    sizeof(st_quirk_patterns[0]), &priority);
419 	if (priority != 0) {
420 		st->quirkdata = &finger->quirkdata;
421 		st->drive_quirks = finger->quirkdata.quirks;
422 		st->quirks = finger->quirkdata.quirks;	/* start value */
423 		st_loadquirks(st);
424 	}
425 }
426 
427 /*
428  * initialise the subdevices to the default (QUIRK) state.
429  * this will remove any setting made by the system operator or previous
430  * operations.
431  */
432 void
433 st_loadquirks(struct st_softc *st)
434 {
435 	const struct	modes *mode;
436 	struct	modes *mode2;
437 
438 	mode = &st->quirkdata->modes;
439 	mode2 = &st->modes;
440 	bzero(mode2, sizeof(struct modes));
441 	st->modeflags &= ~(BLKSIZE_SET_BY_QUIRK |
442 	    DENSITY_SET_BY_QUIRK | BLKSIZE_SET_BY_USER |
443 	    DENSITY_SET_BY_USER);
444 	if ((mode->quirks | st->drive_quirks) & ST_Q_FORCE_BLKSIZE) {
445 		mode2->blksize = mode->blksize;
446 		st->modeflags |= BLKSIZE_SET_BY_QUIRK;
447 	}
448 	if (mode->density) {
449 		mode2->density = mode->density;
450 		st->modeflags |= DENSITY_SET_BY_QUIRK;
451 	}
452 }
453 
454 /*
455  * open the device.
456  */
457 int
458 stopen(dev_t dev, int flags, int fmt, struct proc *p)
459 {
460 	struct scsi_link *sc_link;
461 	struct st_softc *st;
462 	int error = 0;
463 
464 	st = stlookup(STUNIT(dev));
465 	if (st == NULL)
466 		return (ENXIO);
467 	if (st->flags & ST_DYING) {
468 		error = ENXIO;
469 		goto done;
470 	}
471 	sc_link = st->sc_link;
472 
473 	SC_DEBUG(sc_link, SDEV_DB1, ("open: dev=0x%x (unit %d (of %d))\n", dev,
474 	    STUNIT(dev), st_cd.cd_ndevs));
475 
476 	/*
477 	 * Tape is an exclusive media. Only one open at a time.
478 	 */
479 	if (sc_link->flags & SDEV_OPEN) {
480 		SC_DEBUG(sc_link, SDEV_DB4, ("already open\n"));
481 		error = EBUSY;
482 		goto done;
483 	}
484 
485 	/* Use st_interpret_sense() now. */
486 	sc_link->flags |= SDEV_OPEN;
487 
488 	/*
489 	 * Check the unit status. This clears any outstanding errors and
490 	 * will ensure that media is present.
491 	 */
492 	error = scsi_test_unit_ready(sc_link, TEST_READY_RETRIES,
493 	    SCSI_SILENT | SCSI_IGNORE_MEDIA_CHANGE |
494 	    SCSI_IGNORE_ILLEGAL_REQUEST);
495 
496 	/*
497 	 * Terminate any exising mount session if there is no media.
498 	 */
499 	if ((sc_link->flags & SDEV_MEDIA_LOADED) == 0)
500 		st_unmount(st, NOEJECT, DOREWIND);
501 
502 	if (error) {
503 		sc_link->flags &= ~SDEV_OPEN;
504 		goto done;
505 	}
506 
507 	if ((st->flags & ST_MOUNTED) == 0) {
508 		error = st_mount_tape(dev, flags);
509 		if (error) {
510 			sc_link->flags &= ~SDEV_OPEN;
511 			goto done;
512 		}
513 	}
514 
515 	/*
516 	 * Make sure that a tape opened in write-only mode will have
517 	 * file marks written on it when closed, even if not written to.
518 	 * This is for SUN compatibility
519 	 */
520 	if ((flags & O_ACCMODE) == FWRITE)
521 		st->flags |= ST_WRITTEN;
522 
523 done:
524 	SC_DEBUG(sc_link, SDEV_DB2, ("open complete\n"));
525 	device_unref(&st->sc_dev);
526 	return (error);
527 }
528 
529 /*
530  * close the device.. only called if we are the LAST
531  * occurrence of an open device
532  */
533 int
534 stclose(dev_t dev, int flags, int mode, struct proc *p)
535 {
536 	struct scsi_link *sc_link;
537 	struct st_softc *st;
538 	int error = 0;
539 
540 	st = stlookup(STUNIT(dev));
541 	if (st == NULL)
542 		return (ENXIO);
543 	if (st->flags & ST_DYING) {
544 		error = ENXIO;
545 		goto done;
546 	}
547 	sc_link = st->sc_link;
548 
549 	SC_DEBUG(sc_link, SDEV_DB1, ("closing\n"));
550 
551 	if ((st->flags & (ST_WRITTEN | ST_FM_WRITTEN)) == ST_WRITTEN)
552 		st_write_filemarks(st, 1, 0);
553 
554 	switch (STMODE(dev)) {
555 	case 0:		/* normal */
556 		st_unmount(st, NOEJECT, DOREWIND);
557 		break;
558 	case 3:		/* eject, no rewind */
559 		st_unmount(st, EJECT, NOREWIND);
560 		break;
561 	case 1:		/* no rewind */
562 		/* leave mounted unless media seems to have been removed */
563 		if (!(sc_link->flags & SDEV_MEDIA_LOADED))
564 			st_unmount(st, NOEJECT, NOREWIND);
565 		break;
566 	case 2:		/* rewind, eject */
567 		st_unmount(st, EJECT, DOREWIND);
568 		break;
569 	}
570 	sc_link->flags &= ~SDEV_OPEN;
571 	timeout_del(&st->sc_timeout);
572 
573 done:
574 	device_unref(&st->sc_dev);
575 	return (error);
576 }
577 
578 /*
579  * Start a new mount session.
580  * Copy in all the default parameters from the selected device mode.
581  * and try guess any that seem to be defaulted.
582  */
583 int
584 st_mount_tape(dev_t dev, int flags)
585 {
586 	struct st_softc *st;
587 	struct scsi_link *sc_link;
588 	int error = 0;
589 
590 	st = stlookup(STUNIT(dev));
591 	if (st == NULL)
592 		return (ENXIO);
593 	if (st->flags & ST_DYING) {
594 		error = ENXIO;
595 		goto done;
596 	}
597 	sc_link = st->sc_link;
598 
599 	SC_DEBUG(sc_link, SDEV_DB1, ("mounting\n"));
600 
601 	if (st->flags & ST_MOUNTED)
602 		goto done;
603 
604 	st->quirks = st->drive_quirks | st->modes.quirks;
605 	/*
606 	 * If the media is new, then make sure we give it a chance to
607 	 * to do a 'load' instruction.  (We assume it is new.)
608 	 */
609 	if ((error = st_load(st, LD_LOAD, 0)) != 0)
610 		goto done;
611 
612 	/*
613 	 * Throw another dummy instruction to catch
614 	 * 'Unit attention' errors. Some drives appear to give
615 	 * these after doing a Load instruction.
616 	 * (noteably some DAT drives)
617 	 */
618 	/* XXX */
619 	scsi_test_unit_ready(sc_link, TEST_READY_RETRIES, SCSI_SILENT);
620 
621 	/*
622 	 * Some devices can't tell you much until they have been
623 	 * asked to look at the media. This quirk does this.
624 	 */
625 	if (st->quirks & ST_Q_SENSE_HELP)
626 		if ((error = st_touch_tape(st)) != 0)
627 			return error;
628 	/*
629 	 * Load the physical device parameters
630 	 * loads: blkmin, blkmax
631 	 */
632 	if (!(sc_link->flags & SDEV_ATAPI) &&
633 	    (error = st_read_block_limits(st, 0)) != 0)
634 		goto done;
635 
636 	/*
637 	 * Load the media dependent parameters
638 	 * includes: media_blksize,media_density,numblks
639 	 * As we have a tape in, it should be reflected here.
640 	 * If not you may need the "quirk" above.
641 	 */
642 	if ((error = st_mode_sense(st, 0)) != 0)
643 		goto done;
644 
645 	/*
646 	 * If we have gained a permanent density from somewhere,
647 	 * then use it in preference to the one supplied by
648 	 * default by the driver.
649 	 */
650 	if (st->modeflags & (DENSITY_SET_BY_QUIRK | DENSITY_SET_BY_USER))
651 		st->density = st->modes.density;
652 	else
653 		st->density = st->media_density;
654 	/*
655 	 * If we have gained a permanent blocksize
656 	 * then use it in preference to the one supplied by
657 	 * default by the driver.
658 	 */
659 	st->flags &= ~ST_FIXEDBLOCKS;
660 	if (st->modeflags & (BLKSIZE_SET_BY_QUIRK | BLKSIZE_SET_BY_USER)) {
661 		st->blksize = st->modes.blksize;
662 		if (st->blksize)
663 			st->flags |= ST_FIXEDBLOCKS;
664 	} else {
665 		if ((error = st_decide_mode(st, FALSE)) != 0)
666 			goto done;
667 	}
668 	if ((error = st_mode_select(st, 0)) != 0) {
669 		printf("%s: cannot set selected mode\n", st->sc_dev.dv_xname);
670 		goto done;
671 	}
672 	scsi_prevent(sc_link, PR_PREVENT,
673 	    SCSI_IGNORE_ILLEGAL_REQUEST | SCSI_IGNORE_NOT_READY);
674 	st->flags |= ST_MOUNTED;
675 	sc_link->flags |= SDEV_MEDIA_LOADED;	/* move earlier? */
676 
677 done:
678 	device_unref(&st->sc_dev);
679 	return (error);
680 }
681 
682 /*
683  * End the present mount session.
684  * Rewind, and optionally eject the tape.
685  * Reset various flags to indicate that all new
686  * operations require another mount operation
687  */
688 void
689 st_unmount(struct st_softc *st, int eject, int rewind)
690 {
691 	struct scsi_link *sc_link = st->sc_link;
692 	int nmarks;
693 
694 	st->media_fileno = -1;
695 	st->media_blkno = -1;
696 
697 	if (!(st->flags & ST_MOUNTED))
698 		return;
699 	SC_DEBUG(sc_link, SDEV_DB1, ("unmounting\n"));
700 	st_check_eod(st, FALSE, &nmarks, SCSI_IGNORE_NOT_READY);
701 	if (rewind)
702 		st_rewind(st, 0, SCSI_IGNORE_NOT_READY);
703 	scsi_prevent(sc_link, PR_ALLOW,
704 	    SCSI_IGNORE_ILLEGAL_REQUEST | SCSI_IGNORE_NOT_READY);
705 	if (eject)
706 		st_load(st, LD_UNLOAD, SCSI_IGNORE_NOT_READY);
707 	st->flags &= ~ST_MOUNTED;
708 	sc_link->flags &= ~SDEV_MEDIA_LOADED;
709 }
710 
711 /*
712  * Given all we know about the device, media, mode, 'quirks' and
713  * initial operation, make a decision as to how we should be set
714  * to run (regarding blocking and EOD marks)
715  */
716 int
717 st_decide_mode(struct st_softc *st, int first_read)
718 {
719 	struct scsi_link *sc_link = st->sc_link;
720 
721 	SC_DEBUG(sc_link, SDEV_DB2, ("starting block mode decision\n"));
722 
723 	/* ATAPI tapes are always fixed blocksize. */
724 	if (sc_link->flags & SDEV_ATAPI) {
725 		st->flags |= ST_FIXEDBLOCKS;
726 		if (st->media_blksize > 0)
727 			st->blksize = st->media_blksize;
728 		else
729 			st->blksize = DEF_FIXED_BSIZE;
730 		goto done;
731 	}
732 
733 	/*
734 	 * If the drive can only handle fixed-length blocks and only at
735 	 * one size, perhaps we should just do that.
736 	 */
737 	if (st->blkmin && (st->blkmin == st->blkmax)) {
738 		st->flags |= ST_FIXEDBLOCKS;
739 		st->blksize = st->blkmin;
740 		SC_DEBUG(sc_link, SDEV_DB3,
741 		    ("blkmin == blkmax of %d\n", st->blkmin));
742 		goto done;
743 	}
744 	/*
745 	 * If the tape density mandates (or even suggests) use of fixed
746 	 * or variable-length blocks, comply.
747 	 */
748 	switch (st->density) {
749 	case HALFINCH_800:
750 	case HALFINCH_1600:
751 	case HALFINCH_6250:
752 	case DDS:
753 		st->flags &= ~ST_FIXEDBLOCKS;
754 		st->blksize = 0;
755 		SC_DEBUG(sc_link, SDEV_DB3, ("density specified variable\n"));
756 		goto done;
757 	case QIC_11:
758 	case QIC_24:
759 	case QIC_120:
760 	case QIC_150:
761 	case QIC_525:
762 	case QIC_1320:
763 		st->flags |= ST_FIXEDBLOCKS;
764 		if (st->media_blksize > 0)
765 			st->blksize = st->media_blksize;
766 		else
767 			st->blksize = DEF_FIXED_BSIZE;
768 		SC_DEBUG(sc_link, SDEV_DB3, ("density specified fixed\n"));
769 		goto done;
770 	}
771 	/*
772 	 * If we're about to read the tape, perhaps we should choose
773 	 * fixed or variable-length blocks and block size according to
774 	 * what the drive found on the tape.
775 	 */
776 	if (first_read &&
777 	    (!(st->quirks & ST_Q_BLKSIZE) || (st->media_blksize == 0) ||
778 	    (st->media_blksize == DEF_FIXED_BSIZE) ||
779 	    (st->media_blksize == 1024))) {
780 		if (st->media_blksize > 0)
781 			st->flags |= ST_FIXEDBLOCKS;
782 		else
783 			st->flags &= ~ST_FIXEDBLOCKS;
784 		st->blksize = st->media_blksize;
785 		SC_DEBUG(sc_link, SDEV_DB3,
786 		    ("Used media_blksize of %d\n", st->media_blksize));
787 		goto done;
788 	}
789 	/*
790 	 * We're getting no hints from any direction.  Choose variable-
791 	 * length blocks arbitrarily.
792 	 */
793 	st->flags &= ~ST_FIXEDBLOCKS;
794 	st->blksize = 0;
795 	SC_DEBUG(sc_link, SDEV_DB3,
796 	    ("Give up and default to variable mode\n"));
797 
798 done:
799 	/*
800 	 * Decide whether or not to write two file marks to signify end-
801 	 * of-data.  Make the decision as a function of density.  If
802 	 * the decision is not to use a second file mark, the SCSI BLANK
803 	 * CHECK condition code will be recognized as end-of-data when
804 	 * first read.
805 	 * (I think this should be a by-product of fixed/variable..julian)
806 	 */
807 	switch (st->density) {
808 /*      case 8 mm:   What is the SCSI density code for 8 mm, anyway? */
809 	case QIC_11:
810 	case QIC_24:
811 	case QIC_120:
812 	case QIC_150:
813 	case QIC_525:
814 	case QIC_1320:
815 		st->flags &= ~ST_2FM_AT_EOD;
816 		break;
817 	default:
818 		st->flags |= ST_2FM_AT_EOD;
819 	}
820 	return 0;
821 }
822 
823 /*
824  * Actually translate the requested transfer into
825  * one the physical driver can understand
826  * The transfer is described by a buf and will include
827  * only one physical transfer.
828  */
829 void
830 ststrategy(struct buf *bp)
831 {
832 	struct scsi_link *sc_link;
833 	struct st_softc *st;
834 	struct buf *dp;
835 	int error, s;
836 
837 	st = stlookup(STUNIT(bp->b_dev));
838 	if (st == NULL)
839 		return;
840 	if (st->flags & ST_DYING) {
841 		error = ENXIO;
842 		goto done;
843 	}
844 	sc_link = st->sc_link;
845 
846 	SC_DEBUG(sc_link, SDEV_DB2, ("ststrategy: %ld bytes @ blk %d\n",
847 	    bp->b_bcount, bp->b_blkno));
848 
849 	if (st->flags & ST_DYING) {
850 		bp->b_error = ENXIO;
851 		goto bad;
852 	}
853 	/*
854 	 * If it's a null transfer, return immediately.
855 	 */
856 	if (bp->b_bcount == 0)
857 		goto done;
858 	/*
859 	 * Odd sized request on fixed drives are verboten
860 	 */
861 	if (st->flags & ST_FIXEDBLOCKS) {
862 		if (bp->b_bcount % st->blksize) {
863 			printf("%s: bad request, must be multiple of %d\n",
864 			    st->sc_dev.dv_xname, st->blksize);
865 			bp->b_error = EIO;
866 			goto bad;
867 		}
868 	}
869 	/*
870 	 * as are out-of-range requests on variable drives.
871 	 */
872 	else if (bp->b_bcount < st->blkmin ||
873 		 (st->blkmax && bp->b_bcount > st->blkmax)) {
874 		printf("%s: bad request, must be between %d and %d\n",
875 		    st->sc_dev.dv_xname, st->blkmin, st->blkmax);
876 		bp->b_error = EIO;
877 		goto bad;
878 	}
879 	s = splbio();
880 
881 	/*
882 	 * Place it in the queue of activities for this tape
883 	 * at the end (a bit silly because we only have on user..
884 	 * (but it could fork()))
885 	 */
886 	dp = &st->buf_queue;
887 	bp->b_actf = NULL;
888 	bp->b_actb = dp->b_actb;
889 	*dp->b_actb = bp;
890 	dp->b_actb = &bp->b_actf;
891 
892 	/*
893 	 * Tell the device to get going on the transfer if it's
894 	 * not doing anything, otherwise just wait for completion
895 	 * (All a bit silly if we're only allowing 1 open but..)
896 	 */
897 	ststart(st);
898 
899 	splx(s);
900 	device_unref(&st->sc_dev);
901 	return;
902 bad:
903 	bp->b_flags |= B_ERROR;
904 done:
905 	device_unref(&st->sc_dev);
906 	/*
907 	 * Correctly set the buf to indicate a completed xfer
908 	 */
909 	bp->b_resid = bp->b_bcount;
910 	s = splbio();
911 	biodone(bp);
912 	splx(s);
913 }
914 
915 /*
916  * ststart looks to see if there is a buf waiting for the device
917  * and that the device is not already busy. If both are true,
918  * It dequeues the buf and creates a scsi command to perform the
919  * transfer required. The transfer request will call scsi_done
920  * on completion, which will in turn call this routine again
921  * so that the next queued transfer is performed.
922  * The bufs are queued by the strategy routine (ststrategy)
923  *
924  * This routine is also called after other non-queued requests
925  * have been made of the scsi driver, to ensure that the queue
926  * continues to be drained.
927  * ststart() is called at splbio from ststrategy, strestart and scsi_done()
928  */
929 void
930 ststart(void *v)
931 {
932 	struct st_softc *st = v;
933 	struct scsi_link *sc_link = st->sc_link;
934 	struct buf *bp, *dp;
935 	struct scsi_rw_tape cmd;
936 	int flags, error;
937 
938 	SC_DEBUG(sc_link, SDEV_DB2, ("ststart\n"));
939 
940 	if (st->flags & ST_DYING)
941 		return;
942 
943 	splassert(IPL_BIO);
944 
945 	/*
946 	 * See if there is a buf to do and we are not already
947 	 * doing one
948 	 */
949 	while (sc_link->openings > 0) {
950 		/* if a special awaits, let it proceed first */
951 		if (sc_link->flags & SDEV_WAITING) {
952 			sc_link->flags &= ~SDEV_WAITING;
953 			wakeup((caddr_t)sc_link);
954 			return;
955 		}
956 
957 		dp = &st->buf_queue;
958 		if ((bp = dp->b_actf) == NULL)
959 			return;
960 		if ((dp = bp->b_actf) != NULL)
961 			dp->b_actb = bp->b_actb;
962 		else
963 			st->buf_queue.b_actb = bp->b_actb;
964 		*bp->b_actb = dp;
965 
966 		/*
967 		 * if the device has been unmounted by the user
968 		 * then throw away all requests until done
969 		 */
970 		if (!(st->flags & ST_MOUNTED) ||
971 		    !(sc_link->flags & SDEV_MEDIA_LOADED)) {
972 			/* make sure that one implies the other.. */
973 			sc_link->flags &= ~SDEV_MEDIA_LOADED;
974 			bp->b_flags |= B_ERROR;
975 			bp->b_resid = bp->b_bcount;
976 			bp->b_error = EIO;
977 			biodone(bp);
978 			continue;
979 		}
980 		/*
981 		 * only FIXEDBLOCK devices have pending operations
982 		 */
983 		if (st->flags & ST_FIXEDBLOCKS) {
984 			/*
985 			 * If we are at a filemark but have not reported it yet
986 			 * then we should report it now
987 			 */
988 			if (st->flags & ST_AT_FILEMARK) {
989 				if ((bp->b_flags & B_READ) == B_WRITE) {
990 					/*
991 					 * Handling of ST_AT_FILEMARK in
992 					 * st_space will fill in the right file
993 					 * mark count.
994 					 * Back up over filemark
995 					 */
996 					if (st_space(st, 0, SP_FILEMARKS, 0)) {
997 						bp->b_flags |= B_ERROR;
998 						bp->b_resid = bp->b_bcount;
999 						bp->b_error = EIO;
1000 						biodone(bp);
1001 						continue;
1002 					}
1003 				} else {
1004 					bp->b_resid = bp->b_bcount;
1005 					bp->b_error = 0;
1006 					bp->b_flags &= ~B_ERROR;
1007 					st->flags &= ~ST_AT_FILEMARK;
1008 					biodone(bp);
1009 					continue;	/* seek more work */
1010 				}
1011 			}
1012 			/*
1013 			 * If we are at EIO (e.g. EOM) but have not reported it
1014 			 * yet then we should report it now
1015 			 */
1016 			if (st->flags & ST_EIO_PENDING) {
1017 				bp->b_resid = bp->b_bcount;
1018 				bp->b_error = EIO;
1019 				bp->b_flags |= B_ERROR;
1020 				st->flags &= ~ST_EIO_PENDING;
1021 				biodone(bp);
1022 				continue;	/* seek more work */
1023 			}
1024 		}
1025 
1026 		/*
1027 		 *  Fill out the scsi command
1028 		 */
1029 		bzero(&cmd, sizeof(cmd));
1030 		if ((bp->b_flags & B_READ) == B_WRITE) {
1031 			cmd.opcode = WRITE;
1032 			st->flags &= ~ST_FM_WRITTEN;
1033 			st->flags |= ST_WRITTEN;
1034 			flags = SCSI_DATA_OUT;
1035 		} else {
1036 			cmd.opcode = READ;
1037 			flags = SCSI_DATA_IN;
1038 		}
1039 
1040 		/*
1041 		 * Handle "fixed-block-mode" tape drives by using the
1042 		 * block count instead of the length.
1043 		 */
1044 		if (st->flags & ST_FIXEDBLOCKS) {
1045 			cmd.byte2 |= SRW_FIXED;
1046 			_lto3b(bp->b_bcount / st->blksize, cmd.len);
1047 		} else
1048 			_lto3b(bp->b_bcount, cmd.len);
1049 
1050 		if (st->media_blkno != -1) {
1051 			/* Update block count now, errors will set it to -1. */
1052 			if (st->flags & ST_FIXEDBLOCKS)
1053 				st->media_blkno += _3btol(cmd.len);
1054 			else if (cmd.len != 0)
1055 				st->media_blkno++;
1056 		}
1057 
1058 		/*
1059 		 * go ask the adapter to do all this for us
1060 		 */
1061 		error = scsi_scsi_cmd(sc_link, (struct scsi_generic *) &cmd,
1062 		    sizeof(cmd), (u_char *) bp->b_data, bp->b_bcount, 0,
1063 		    ST_IO_TIME, bp, flags | SCSI_NOSLEEP);
1064 		switch (error) {
1065 		case 0:
1066 			timeout_del(&st->sc_timeout);
1067 			break;
1068 		case EAGAIN:
1069 			/*
1070 			 * The device can't start another i/o. Try again later.
1071 			 */
1072 			dp->b_actf = bp;
1073 			timeout_add(&st->sc_timeout, 1);
1074 			return;
1075 		default:
1076 			printf("%s: not queued\n", st->sc_dev.dv_xname);
1077 			break;
1078 		}
1079 	} /* go back and see if we can cram more work in.. */
1080 }
1081 
1082 void
1083 strestart(void *v)
1084 {
1085 	int s;
1086 
1087 	s = splbio();
1088 	ststart(v);
1089 	splx(s);
1090 }
1091 
1092 void
1093 stminphys(struct buf *bp)
1094 {
1095 	struct st_softc *st;
1096 
1097 	st = stlookup(STUNIT(bp->b_dev));
1098 	if (st == NULL)
1099 		return;  /* can't happen */
1100 
1101 	(*st->sc_link->adapter->scsi_minphys)(bp, st->sc_link);
1102 
1103 	device_unref(&st->sc_dev);
1104 }
1105 
1106 int
1107 stread(dev_t dev, struct uio *uio, int iomode)
1108 {
1109 	struct st_softc *st;
1110 
1111 	st = stlookup(STUNIT(dev));
1112 	if (st == NULL)
1113 		return (ENXIO);
1114 
1115 	if (st->flags & ST_DYING) {
1116 		device_unref(&st->sc_dev);
1117 		return (ENXIO);
1118 	}
1119 
1120 	return (physio(ststrategy, NULL, dev, B_READ, stminphys, uio));
1121 }
1122 
1123 int
1124 stwrite(dev_t dev, struct uio *uio, int iomode)
1125 {
1126 	struct st_softc *st;
1127 
1128 	st = stlookup(STUNIT(dev));
1129 	if (st == NULL)
1130 		return (ENXIO);
1131 
1132 	if (st->flags & ST_DYING) {
1133 		device_unref(&st->sc_dev);
1134 		return (ENXIO);
1135 	}
1136 
1137 	return (physio(ststrategy, NULL, dev, B_WRITE, stminphys, uio));
1138 }
1139 
1140 /*
1141  * Perform special action on behalf of the user;
1142  * knows about the internals of this device
1143  */
1144 int
1145 stioctl(dev_t dev, u_long cmd, caddr_t arg, int flag, struct proc *p)
1146 {
1147 	int error = 0;
1148 	int nmarks;
1149 	int flags = 0;
1150 	struct st_softc *st;
1151 	int hold_blksize;
1152 	u_int8_t hold_density;
1153 	struct mtop *mt = (struct mtop *) arg;
1154 	int number;
1155 
1156 	/*
1157 	 * Find the device that the user is talking about
1158 	 */
1159 	st = stlookup(STUNIT(dev));
1160 	if (st == NULL)
1161 		return (ENXIO);
1162 
1163 	if (st->flags & ST_DYING) {
1164 		error = ENXIO;
1165 		goto done;
1166 	}
1167 
1168 	hold_blksize = st->blksize;
1169 	hold_density = st->density;
1170 
1171 	switch (cmd) {
1172 
1173 	case MTIOCGET: {
1174 		struct mtget *g = (struct mtget *) arg;
1175 
1176 		/*
1177 		 * (to get the current state of READONLY)
1178 		 */
1179 		error = st_mode_sense(st, SCSI_SILENT);
1180 		if (error)
1181 			break;
1182 
1183 		SC_DEBUG(st->sc_link, SDEV_DB1, ("[ioctl: get status]\n"));
1184 		bzero(g, sizeof(struct mtget));
1185 		g->mt_type = 0x7;	/* Ultrix compat *//*? */
1186 		g->mt_blksiz = st->blksize;
1187 		g->mt_density = st->density;
1188  		g->mt_mblksiz = st->modes.blksize;
1189  		g->mt_mdensity = st->modes.density;
1190 		if (st->flags & ST_READONLY)
1191 			g->mt_dsreg |= MT_DS_RDONLY;
1192 		if (st->flags & ST_MOUNTED)
1193 			g->mt_dsreg |= MT_DS_MOUNTED;
1194 		g->mt_resid = st->mt_resid;
1195 		g->mt_erreg = st->mt_erreg;
1196 		g->mt_fileno = st->media_fileno;
1197 		g->mt_blkno = st->media_blkno;
1198 		/*
1199 		 * clear latched errors.
1200 		 */
1201 		st->mt_resid = 0;
1202 		st->mt_erreg = 0;
1203 		break;
1204 	}
1205 	case MTIOCTOP: {
1206 
1207 		SC_DEBUG(st->sc_link, SDEV_DB1,
1208 		    ("[ioctl: op=0x%x count=0x%x]\n", mt->mt_op, mt->mt_count));
1209 
1210 		number = mt->mt_count;
1211 		switch (mt->mt_op) {
1212 		case MTWEOF:	/* write an end-of-file record */
1213 			error = st_write_filemarks(st, number, flags);
1214 			break;
1215 		case MTBSF:	/* backward space file */
1216 			number = -number;
1217 		case MTFSF:	/* forward space file */
1218 			error = st_check_eod(st, FALSE, &nmarks, flags);
1219 			if (!error)
1220 				error = st_space(st, number - nmarks,
1221 				    SP_FILEMARKS, flags);
1222 			break;
1223 		case MTBSR:	/* backward space record */
1224 			number = -number;
1225 		case MTFSR:	/* forward space record */
1226 			error = st_check_eod(st, TRUE, &nmarks, flags);
1227 			if (!error)
1228 				error = st_space(st, number, SP_BLKS, flags);
1229 			break;
1230 		case MTREW:	/* rewind */
1231 			error = st_rewind(st, 0, flags);
1232 			break;
1233 		case MTOFFL:	/* rewind and put the drive offline */
1234 			st_unmount(st, EJECT, DOREWIND);
1235 			break;
1236 		case MTNOP:	/* no operation, sets status only */
1237 			break;
1238 		case MTRETEN:	/* retension the tape */
1239 			error = st_load(st, LD_RETENSION, flags);
1240 			if (!error)
1241 				error = st_load(st, LD_LOAD, flags);
1242 			break;
1243 		case MTEOM:	/* forward space to end of media */
1244 			error = st_check_eod(st, FALSE, &nmarks, flags);
1245 			if (!error)
1246 				error = st_space(st, 1, SP_EOM, flags);
1247 			break;
1248 		case MTCACHE:	/* enable controller cache */
1249 			st->flags &= ~ST_DONTBUFFER;
1250 			goto try_new_value;
1251 		case MTNOCACHE:	/* disable controller cache */
1252 			st->flags |= ST_DONTBUFFER;
1253 			goto try_new_value;
1254 		case MTERASE:	/* erase volume */
1255 			error = st_erase(st, number, flags);
1256 			break;
1257 		case MTSETBSIZ:	/* Set block size for device */
1258 			if (number == 0) {
1259 				st->flags &= ~ST_FIXEDBLOCKS;
1260 			} else {
1261 				if ((st->blkmin || st->blkmax) &&
1262 				    (number < st->blkmin ||
1263 				    number > st->blkmax)) {
1264 					error = EINVAL;
1265 					break;
1266 				}
1267 				st->flags |= ST_FIXEDBLOCKS;
1268 			}
1269 			st->blksize = number;
1270 			st->flags |= ST_BLOCK_SET;	/*XXX */
1271 			goto try_new_value;
1272 
1273 		case MTSETDNSTY:	/* Set density for device and mode */
1274 			if (number < 0 || number > SCSI_MAX_DENSITY_CODE) {
1275 				error = EINVAL;
1276 				break;
1277 			} else
1278 				st->density = number;
1279 			goto try_new_value;
1280 
1281 		default:
1282 			error = EINVAL;
1283 		}
1284 		break;
1285 	}
1286 	case MTIOCIEOT:
1287 	case MTIOCEEOT:
1288 		break;
1289 
1290 #if 0
1291 	case MTIOCRDSPOS:
1292 		error = st_rdpos(st, 0, (u_int32_t *) arg);
1293 		break;
1294 
1295 	case MTIOCRDHPOS:
1296 		error = st_rdpos(st, 1, (u_int32_t *) arg);
1297 		break;
1298 
1299 	case MTIOCSLOCATE:
1300 		error = st_setpos(st, 0, (u_int32_t *) arg);
1301 		break;
1302 
1303 	case MTIOCHLOCATE:
1304 		error = st_setpos(st, 1, (u_int32_t *) arg);
1305 		break;
1306 #endif
1307 
1308 	default:
1309 		error = scsi_do_ioctl(st->sc_link, dev, cmd, arg, flag, p);
1310 		break;
1311 	}
1312 	goto done;
1313 
1314 try_new_value:
1315 	/*
1316 	 * Check that the mode being asked for is aggreeable to the
1317 	 * drive. If not, put it back the way it was.
1318 	 */
1319 	if ((error = st_mode_select(st, 0)) != 0) {/* put it back as it was */
1320 		printf("%s: cannot set selected mode\n", st->sc_dev.dv_xname);
1321 		st->density = hold_density;
1322 		st->blksize = hold_blksize;
1323 		if (st->blksize)
1324 			st->flags |= ST_FIXEDBLOCKS;
1325 		else
1326 			st->flags &= ~ST_FIXEDBLOCKS;
1327 		goto done;
1328 	}
1329 	/*
1330 	 * As the drive liked it, if we are setting a new default,
1331 	 * set it into the structures as such.
1332 	 */
1333 	switch (mt->mt_op) {
1334 	case MTSETBSIZ:
1335 		st->modes.blksize = st->blksize;
1336 		st->modeflags |= BLKSIZE_SET_BY_USER;
1337 		break;
1338 	case MTSETDNSTY:
1339 		st->modes.density = st->density;
1340 		st->modeflags |= DENSITY_SET_BY_USER;
1341 		break;
1342 	}
1343 
1344 done:
1345 	device_unref(&st->sc_dev);
1346 	return (error);
1347 }
1348 
1349 /*
1350  * Do a synchronous read.
1351  */
1352 int
1353 st_read(struct st_softc *st, char *buf, int size, int flags)
1354 {
1355 	struct scsi_rw_tape cmd;
1356 
1357 	/*
1358 	 * If it's a null transfer, return immediately
1359 	 */
1360 	if (size == 0)
1361 		return 0;
1362 	bzero(&cmd, sizeof(cmd));
1363 	cmd.opcode = READ;
1364 	if (st->flags & ST_FIXEDBLOCKS) {
1365 		cmd.byte2 |= SRW_FIXED;
1366 		_lto3b(size / (st->blksize ? st->blksize : DEF_FIXED_BSIZE),
1367 		    cmd.len);
1368 	} else
1369 		_lto3b(size, cmd.len);
1370 	return scsi_scsi_cmd(st->sc_link, (struct scsi_generic *) &cmd,
1371 	    sizeof(cmd), (u_char *) buf, size, 0, ST_IO_TIME, NULL,
1372 	    flags | SCSI_DATA_IN);
1373 }
1374 
1375 /*
1376  * Ask the drive what its min and max blk sizes are.
1377  */
1378 int
1379 st_read_block_limits(struct st_softc *st, int flags)
1380 {
1381 	struct scsi_block_limits cmd;
1382 	struct scsi_block_limits_data block_limits;
1383 	struct scsi_link *sc_link = st->sc_link;
1384 	int error;
1385 
1386 	/*
1387 	 * First check if we have it all loaded
1388 	 */
1389 	if ((sc_link->flags & SDEV_MEDIA_LOADED))
1390 		return 0;
1391 
1392 	/*
1393 	 * do a 'Read Block Limits'
1394 	 */
1395 	bzero(&cmd, sizeof(cmd));
1396 	cmd.opcode = READ_BLOCK_LIMITS;
1397 
1398 	/*
1399 	 * do the command, update the global values
1400 	 */
1401 	error = scsi_scsi_cmd(sc_link, (struct scsi_generic *) &cmd,
1402 	    sizeof(cmd), (u_char *) &block_limits, sizeof(block_limits),
1403 	    SCSI_RETRIES, ST_CTL_TIME, NULL, flags | SCSI_DATA_IN);
1404 	if (error)
1405 		return error;
1406 
1407 	st->blkmin = _2btol(block_limits.min_length);
1408 	st->blkmax = _3btol(block_limits.max_length);
1409 
1410 	SC_DEBUG(sc_link, SDEV_DB3,
1411 	    ("(%d <= blksize <= %d)\n", st->blkmin, st->blkmax));
1412 	return 0;
1413 }
1414 
1415 /*
1416  * Get the scsi driver to send a full inquiry to the
1417  * device and use the results to fill out the global
1418  * parameter structure.
1419  *
1420  * called from:
1421  * attach
1422  * open
1423  * ioctl (to reset original blksize)
1424  */
1425 int
1426 st_mode_sense(struct st_softc *st, int flags)
1427 {
1428 	union scsi_mode_sense_buf *data;
1429 	struct scsi_link *sc_link = st->sc_link;
1430 	u_int64_t block_count;
1431 	u_int32_t density, block_size;
1432 	u_char *page0 = NULL;
1433 	u_int8_t dev_spec;
1434 	int error, big;
1435 
1436 	data = malloc(sizeof(*data), M_TEMP, M_NOWAIT);
1437 	if (data == NULL)
1438 		return (ENOMEM);
1439 
1440 	/*
1441 	 * Ask for page 0 (vendor specific) mode sense data.
1442 	 */
1443 	error = scsi_do_mode_sense(sc_link, 0, data, (void **)&page0,
1444 	    &density, &block_count, &block_size, 1, flags | SCSI_SILENT, &big);
1445 	if (error != 0) {
1446 		free(data, M_TEMP);
1447 		return (error);
1448 	}
1449 
1450 	/* It is valid for no page0 to be available. */
1451 
1452 	if (big)
1453 		dev_spec = data->hdr_big.dev_spec;
1454 	else
1455 		dev_spec = data->hdr.dev_spec;
1456 
1457 	if (dev_spec & SMH_DSP_WRITE_PROT)
1458 		st->flags |= ST_READONLY;
1459 	else
1460 		st->flags &= ~ST_READONLY;
1461 
1462 	st->numblks = block_count;
1463 	st->media_blksize = block_size;
1464 	st->media_density = density;
1465 
1466 	SC_DEBUG(sc_link, SDEV_DB3,
1467 	    ("density code 0x%x, %d-byte blocks, write-%s, ",
1468 	    st->media_density, st->media_blksize,
1469 	    st->flags & ST_READONLY ? "protected" : "enabled"));
1470 	SC_DEBUGN(sc_link, SDEV_DB3,
1471 	    ("%sbuffered\n", dev_spec & SMH_DSP_BUFF_MODE ? "" : "un"));
1472 
1473 	sc_link->flags |= SDEV_MEDIA_LOADED;
1474 
1475 	free(data, M_TEMP);
1476 	return (0);
1477 }
1478 
1479 /*
1480  * Send a filled out parameter structure to the drive to
1481  * set it into the desire modes etc.
1482  */
1483 int
1484 st_mode_select(struct st_softc *st, int flags)
1485 {
1486 	union scsi_mode_sense_buf *inbuf, *outbuf;
1487 	struct scsi_blk_desc general;
1488 	struct scsi_link *sc_link = st->sc_link;
1489 	u_int8_t *page0 = NULL;
1490 	int error, big, page0_size;
1491 
1492 	inbuf = malloc(sizeof(*inbuf), M_TEMP, M_NOWAIT);
1493 	if (inbuf == NULL)
1494 		return (ENOMEM);
1495 	outbuf = malloc(sizeof(*outbuf), M_TEMP, M_NOWAIT | M_ZERO);
1496 	if (outbuf == NULL) {
1497 		free(inbuf, M_TEMP);
1498 		return (ENOMEM);
1499 	}
1500 
1501 	/*
1502 	 * This quirk deals with drives that have only one valid mode and think
1503 	 * this gives them license to reject all mode selects, even if the
1504 	 * selected mode is the one that is supported.
1505 	 */
1506 	if (st->quirks & ST_Q_UNIMODAL) {
1507 		SC_DEBUG(sc_link, SDEV_DB3,
1508 		    ("not setting density 0x%x blksize 0x%x\n",
1509 		    st->density, st->blksize));
1510 		free(inbuf, M_TEMP);
1511 		free(outbuf, M_TEMP);
1512 		return (0);
1513 	}
1514 
1515 	if (sc_link->flags & SDEV_ATAPI) {
1516 		free(inbuf, M_TEMP);
1517 		free(outbuf, M_TEMP);
1518 		return (0);
1519 	}
1520 
1521 	bzero(&general, sizeof(general));
1522 
1523 	general.density = st->density;
1524 	if (st->flags & ST_FIXEDBLOCKS)
1525 		_lto3b(st->blksize, general.blklen);
1526 
1527 	/*
1528 	 * Ask for page 0 (vendor specific) mode sense data.
1529 	 */
1530 	error = scsi_do_mode_sense(sc_link, 0, inbuf, (void **)&page0, NULL,
1531 	    NULL, NULL, 1, flags | SCSI_SILENT, &big);
1532 	if (error != 0) {
1533 		free(inbuf, M_TEMP);
1534 		free(outbuf, M_TEMP);
1535 		return (error);
1536 	}
1537 
1538 	if (page0 == NULL) {
1539 		page0_size = 0;
1540 	} else if (big == 0) {
1541 		page0_size = inbuf->hdr.data_length +
1542 		    sizeof(inbuf->hdr.data_length) - sizeof(inbuf->hdr) -
1543 		    inbuf->hdr.blk_desc_len;
1544 		memcpy(&outbuf->buf[sizeof(outbuf->hdr)+ sizeof(general)],
1545 		    page0, page0_size);
1546 	} else {
1547 		page0_size = _2btol(inbuf->hdr_big.data_length) +
1548 		    sizeof(inbuf->hdr_big.data_length) -
1549 		    sizeof(inbuf->hdr_big) -
1550 		   _2btol(inbuf->hdr_big.blk_desc_len);
1551 		memcpy(&outbuf->buf[sizeof(outbuf->hdr_big) + sizeof(general)],
1552 		    page0, page0_size);
1553 	}
1554 
1555 	/*
1556 	 * Set up for a mode select.
1557 	 */
1558 	if (big == 0) {
1559 		outbuf->hdr.data_length = sizeof(outbuf->hdr) +
1560 		    sizeof(general) + page0_size -
1561 		    sizeof(outbuf->hdr.data_length);
1562 		if ((st->flags & ST_DONTBUFFER) == 0)
1563 			outbuf->hdr.dev_spec = SMH_DSP_BUFF_MODE_ON;
1564 		outbuf->hdr.blk_desc_len = sizeof(general);
1565 		memcpy(&outbuf->buf[sizeof(outbuf->hdr)],
1566 		    &general, sizeof(general));
1567 		error = scsi_mode_select(st->sc_link, 0, &outbuf->hdr,
1568 		    flags, ST_CTL_TIME);
1569 		free(inbuf, M_TEMP);
1570 		free(outbuf, M_TEMP);
1571 		return (error);
1572 	}
1573 
1574 	/* MODE SENSE (10) header was returned, so use MODE SELECT (10). */
1575 	_lto2b((sizeof(outbuf->hdr_big) + sizeof(general) + page0_size -
1576 	    sizeof(outbuf->hdr_big.data_length)), outbuf->hdr_big.data_length);
1577 	if ((st->flags & ST_DONTBUFFER) == 0)
1578 		outbuf->hdr_big.dev_spec = SMH_DSP_BUFF_MODE_ON;
1579 	_lto2b(sizeof(general), outbuf->hdr_big.blk_desc_len);
1580 	memcpy(&outbuf->buf[sizeof(outbuf->hdr_big)], &general,
1581 	    sizeof(general));
1582 
1583 	error = scsi_mode_select_big(st->sc_link, 0, &outbuf->hdr_big,
1584 	    flags, ST_CTL_TIME);
1585 	free(inbuf, M_TEMP);
1586 	free(outbuf, M_TEMP);
1587 	return (error);
1588 }
1589 
1590 /*
1591  * issue an erase command
1592  */
1593 int
1594 st_erase(struct st_softc *st, int full, int flags)
1595 {
1596 	struct scsi_erase cmd;
1597 	int tmo;
1598 
1599 	/*
1600 	 * Full erase means set LONG bit in erase command, which asks
1601 	 * the drive to erase the entire unit.  Without this bit, we're
1602 	 * asking the drive to write an erase gap.
1603 	 */
1604 	bzero(&cmd, sizeof(cmd));
1605 	cmd.opcode = ERASE;
1606 	if (full) {
1607 		cmd.byte2 = SE_IMMED|SE_LONG;
1608 		tmo = ST_SPC_TIME;
1609 	} else {
1610 		cmd.byte2 = SE_IMMED;
1611 		tmo = ST_IO_TIME;
1612 	}
1613 
1614 	/*
1615 	 * XXX We always do this asynchronously, for now.  How long should
1616 	 * we wait if we want to (eventually) to it synchronously?
1617 	 */
1618 	return (scsi_scsi_cmd(st->sc_link, (struct scsi_generic *)&cmd,
1619 	    sizeof(cmd), 0, 0, SCSI_RETRIES, tmo, NULL, flags));
1620 }
1621 
1622 /*
1623  * skip N blocks/filemarks/seq filemarks/eom
1624  */
1625 int
1626 st_space(struct st_softc *st, int number, u_int what, int flags)
1627 {
1628 	struct scsi_space cmd;
1629 	int error;
1630 
1631 	switch (what) {
1632 	case SP_BLKS:
1633 		if (st->flags & ST_PER_ACTION) {
1634 			if (number > 0) {
1635 				st->flags &= ~ST_PER_ACTION;
1636 				return EIO;
1637 			} else if (number < 0) {
1638 				if (st->flags & ST_AT_FILEMARK) {
1639 					/*
1640 					 * Handling of ST_AT_FILEMARK
1641 					 * in st_space will fill in the
1642 					 * right file mark count.
1643 					 */
1644 					error = st_space(st, 0, SP_FILEMARKS,
1645 						flags);
1646 					if (error)
1647 						return error;
1648 				}
1649 				if (st->flags & ST_BLANK_READ) {
1650 					st->flags &= ~ST_BLANK_READ;
1651 					return EIO;
1652 				}
1653 				st->flags &= ~ST_EIO_PENDING;
1654 			}
1655 		}
1656 		break;
1657 	case SP_FILEMARKS:
1658 		if (st->flags & ST_EIO_PENDING) {
1659 			if (number > 0) {
1660 				/* pretend we just discovered the error */
1661 				st->flags &= ~ST_EIO_PENDING;
1662 				return EIO;
1663 			} else if (number < 0) {
1664 				/* back away from the error */
1665 				st->flags &= ~ST_EIO_PENDING;
1666 			}
1667 		}
1668 		if (st->flags & ST_AT_FILEMARK) {
1669 			st->flags &= ~ST_AT_FILEMARK;
1670 			number--;
1671 		}
1672 		if ((st->flags & ST_BLANK_READ) && (number < 0)) {
1673 			/* back away from unwritten tape */
1674 			st->flags &= ~ST_BLANK_READ;
1675 			number++;	/* XXX dubious */
1676 		}
1677 		break;
1678 	case SP_EOM:
1679 		if (st->flags & ST_EIO_PENDING) {
1680 			/* pretend we just discovered the error */
1681 			st->flags &= ~ST_EIO_PENDING;
1682 			return EIO;
1683 		}
1684 		if (st->flags & ST_AT_FILEMARK)
1685 			st->flags &= ~ST_AT_FILEMARK;
1686 		break;
1687 	}
1688 	if (number == 0)
1689 		return 0;
1690 
1691 	bzero(&cmd, sizeof(cmd));
1692 	cmd.opcode = SPACE;
1693 	cmd.byte2 = what;
1694 	_lto3b(number, cmd.number);
1695 
1696 	error = scsi_scsi_cmd(st->sc_link, (struct scsi_generic *) &cmd,
1697 	    sizeof(cmd), 0, 0, 0, ST_SPC_TIME, NULL, flags);
1698 
1699 	if (error != 0) {
1700 		st->media_fileno = -1;
1701 		st->media_blkno = -1;
1702 	} else {
1703 		switch (what) {
1704 		case SP_BLKS:
1705 			if (st->media_blkno != -1) {
1706 				st->media_blkno += number;
1707 				if (st->media_blkno < 0)
1708 					st->media_blkno = -1;
1709 			}
1710 			break;
1711 		case SP_FILEMARKS:
1712 			if (st->media_fileno != -1) {
1713 				st->media_fileno += number;
1714 				st->media_blkno = 0;
1715 			}
1716 			break;
1717 		default:
1718 			st->media_fileno = -1;
1719 			st->media_blkno = -1;
1720 			break;
1721 		}
1722 	}
1723 
1724 	return (error);
1725 }
1726 
1727 /*
1728  * write N filemarks
1729  */
1730 int
1731 st_write_filemarks(struct st_softc *st, int number, int flags)
1732 {
1733 	struct scsi_write_filemarks cmd;
1734 	int error;
1735 
1736 	/*
1737 	 * It's hard to write a negative number of file marks.
1738 	 * Don't try.
1739 	 */
1740 	if (number < 0)
1741 		return EINVAL;
1742 	switch (number) {
1743 	case 0:		/* really a command to sync the drive's buffers */
1744 		break;
1745 	case 1:
1746 		if (st->flags & ST_FM_WRITTEN)	/* already have one down */
1747 			st->flags &= ~ST_WRITTEN;
1748 		else
1749 			st->flags |= ST_FM_WRITTEN;
1750 		st->flags &= ~ST_PER_ACTION;
1751 		break;
1752 	default:
1753 		st->flags &= ~(ST_PER_ACTION | ST_WRITTEN);
1754 	}
1755 
1756 	bzero(&cmd, sizeof(cmd));
1757 	cmd.opcode = WRITE_FILEMARKS;
1758 	_lto3b(number, cmd.number);
1759 
1760 	error = scsi_scsi_cmd(st->sc_link, (struct scsi_generic *) &cmd,
1761 	    sizeof(cmd), 0, 0, 0, ST_IO_TIME * 4, NULL, flags);
1762 
1763 	if (error != 0) {
1764 		st->media_fileno = -1;
1765 		st->media_blkno = -1;
1766 	} else if (st->media_fileno != -1) {
1767 		st->media_fileno += number;
1768 		st->media_blkno = 0;
1769 	}
1770 
1771 	return (error);
1772 }
1773 
1774 /*
1775  * Make sure the right number of file marks is on tape if the
1776  * tape has been written.  If the position argument is true,
1777  * leave the tape positioned where it was originally.
1778  *
1779  * nmarks returns the number of marks to skip (or, if position
1780  * true, which were skipped) to get back original position.
1781  */
1782 int
1783 st_check_eod(struct st_softc *st, int position, int *nmarks, int flags)
1784 {
1785 	int error;
1786 
1787 	switch (st->flags & (ST_WRITTEN | ST_FM_WRITTEN | ST_2FM_AT_EOD)) {
1788 	default:
1789 		*nmarks = 0;
1790 		return 0;
1791 	case ST_WRITTEN:
1792 	case ST_WRITTEN | ST_FM_WRITTEN | ST_2FM_AT_EOD:
1793 		*nmarks = 1;
1794 		break;
1795 	case ST_WRITTEN | ST_2FM_AT_EOD:
1796 		*nmarks = 2;
1797 	}
1798 	error = st_write_filemarks(st, *nmarks, flags);
1799 	if (position && !error)
1800 		error = st_space(st, -*nmarks, SP_FILEMARKS, flags);
1801 	return error;
1802 }
1803 
1804 /*
1805  * load/unload/retension
1806  */
1807 int
1808 st_load(struct st_softc *st, u_int type, int flags)
1809 {
1810 	struct scsi_load cmd;
1811 
1812 	st->media_fileno = -1;
1813 	st->media_blkno = -1;
1814 
1815 	if (type != LD_LOAD) {
1816 		int error;
1817 		int nmarks;
1818 
1819 		error = st_check_eod(st, FALSE, &nmarks, flags);
1820 		if (error)
1821 			return error;
1822 	}
1823 	if (st->quirks & ST_Q_IGNORE_LOADS) {
1824 		if (type == LD_LOAD) {
1825 			/*
1826 			 * If we ignore loads, at least we should try a rewind.
1827 			 */
1828 			return st_rewind(st, 0, flags);
1829 		}
1830 		return (0);
1831 	}
1832 
1833 
1834 	bzero(&cmd, sizeof(cmd));
1835 	cmd.opcode = LOAD;
1836 	cmd.how = type;
1837 
1838 	return scsi_scsi_cmd(st->sc_link, (struct scsi_generic *) &cmd,
1839 	    sizeof(cmd), 0, 0, SCSI_RETRIES, ST_SPC_TIME, NULL, flags);
1840 }
1841 
1842 /*
1843  *  Rewind the device
1844  */
1845 int
1846 st_rewind(struct st_softc *st, u_int immediate, int flags)
1847 {
1848 	struct scsi_rewind cmd;
1849 	int error;
1850 	int nmarks;
1851 
1852 	error = st_check_eod(st, FALSE, &nmarks, flags);
1853 	if (error)
1854 		return error;
1855 	st->flags &= ~ST_PER_ACTION;
1856 
1857 	bzero(&cmd, sizeof(cmd));
1858 	cmd.opcode = REWIND;
1859 	cmd.byte2 = immediate;
1860 
1861 	error = scsi_scsi_cmd(st->sc_link, (struct scsi_generic *) &cmd,
1862 	    sizeof(cmd), 0, 0, SCSI_RETRIES,
1863 	    immediate ? ST_CTL_TIME: ST_SPC_TIME, NULL, flags);
1864 
1865 	if (error == 0) {
1866 		st->media_fileno = 0;
1867 		st->media_blkno = 0;
1868 	}
1869 
1870 	return (error);
1871 }
1872 
1873 /*
1874  * Look at the returned sense and act on the error and detirmine
1875  * The unix error number to pass back... (0 = report no error)
1876  *                            (-1 = continue processing)
1877  */
1878 int
1879 st_interpret_sense(struct scsi_xfer *xs)
1880 {
1881 	struct scsi_sense_data *sense = &xs->sense;
1882 	struct scsi_link *sc_link = xs->sc_link;
1883 	struct st_softc *st = sc_link->device_softc;
1884 	struct buf *bp = xs->bp;
1885 	u_int8_t serr = sense->error_code & SSD_ERRCODE;
1886 	u_int8_t skey = sense->flags & SSD_KEY;
1887 	int32_t info;
1888 
1889 	if (((sc_link->flags & SDEV_OPEN) == 0) ||
1890 	    (serr != SSD_ERRCODE_CURRENT && serr != SSD_ERRCODE_DEFERRED))
1891 		return (EJUSTRETURN); /* let the generic code handle it */
1892 
1893 	switch (skey) {
1894 
1895 	/*
1896 	 * We do custom processing in st for the unit becoming ready case.
1897 	 * in this case we do not allow xs->retries to be decremented
1898 	 * only on the "Unit Becoming Ready" case. This is because tape
1899 	 * drives report "Unit Becoming Ready" when loading media, etc.
1900 	 * and can take a long time.  Rather than having a massive timeout
1901 	 * for all operations (which would cause other problems) we allow
1902 	 * operations to wait (but be interruptable with Ctrl-C) forever
1903 	 * as long as the drive is reporting that it is becoming ready.
1904 	 * all other cases are handled as per the default.
1905 	 */
1906 
1907 	case SKEY_NOT_READY:
1908 		if ((xs->flags & SCSI_IGNORE_NOT_READY) != 0)
1909 			return (0);
1910 		switch (ASC_ASCQ(sense)) {
1911 		case SENSE_NOT_READY_BECOMING_READY:
1912 			SC_DEBUG(sc_link, SDEV_DB1, ("not ready: busy (%#x)\n",
1913 			    sense->add_sense_code_qual));
1914 			/* don't count this as a retry */
1915 			xs->retries++;
1916 			return (scsi_delay(xs, 1));
1917 		default:
1918 			return (EJUSTRETURN);
1919 	}
1920 	case SKEY_NO_SENSE:
1921 	case SKEY_RECOVERED_ERROR:
1922 	case SKEY_MEDIUM_ERROR:
1923 	case SKEY_VOLUME_OVERFLOW:
1924 	case SKEY_BLANK_CHECK:
1925 		break;
1926 	default:
1927 		return (EJUSTRETURN);
1928 	}
1929 
1930 	/*
1931 	 * Get the sense fields and work out what code
1932 	 */
1933 	if (sense->error_code & SSD_ERRCODE_VALID)
1934 		info = _4btol(sense->info);
1935 	else
1936 		info = xs->datalen;	/* bad choice if fixed blocks */
1937 	if (st->flags & ST_FIXEDBLOCKS) {
1938 		xs->resid = info * st->blksize;
1939 		if (sense->flags & SSD_EOM) {
1940 			st->flags |= ST_EIO_PENDING;
1941 			if (bp)
1942 				bp->b_resid = xs->resid;
1943 		}
1944 		if (sense->flags & SSD_FILEMARK) {
1945 			st->flags |= ST_AT_FILEMARK;
1946 			if (st->media_fileno != -1) {
1947 				st->media_fileno++;
1948 				st->media_blkno = 0;
1949 			}
1950 			if (bp)
1951 				bp->b_resid = xs->resid;
1952 		}
1953 		if (sense->flags & SSD_ILI) {
1954 			st->flags |= ST_EIO_PENDING;
1955 			if (bp)
1956 				bp->b_resid = xs->resid;
1957 			if (sense->error_code & SSD_ERRCODE_VALID &&
1958 			    (xs->flags & SCSI_SILENT) == 0)
1959 				printf("%s: block wrong size, %d blocks residual\n",
1960 				    st->sc_dev.dv_xname, info);
1961 
1962 			/*
1963 			 * This quirk code helps the drive read
1964 			 * the first tape block, regardless of
1965 			 * format.  That is required for these
1966 			 * drives to return proper MODE SENSE
1967 			 * information.
1968 			 */
1969 			if ((st->quirks & ST_Q_SENSE_HELP) &&
1970 			    !(sc_link->flags & SDEV_MEDIA_LOADED))
1971 				st->blksize -= 512;
1972 		}
1973 		/*
1974 		 * If no data was transferred, return immediately
1975 		 */
1976 		if (xs->resid >= xs->datalen) {
1977 			if (st->flags & ST_EIO_PENDING)
1978 				return EIO;
1979 			if (st->flags & ST_AT_FILEMARK) {
1980 				if (bp)
1981 					bp->b_resid = xs->resid;
1982 				return 0;
1983 			}
1984 		}
1985 	} else {		/* must be variable mode */
1986 		xs->resid = xs->datalen;	/* to be sure */
1987 		if (sense->flags & SSD_EOM)
1988 			return EIO;
1989 		if (sense->flags & SSD_FILEMARK) {
1990 			if (st->media_fileno != -1) {
1991 				st->media_fileno++;
1992 				st->media_blkno = 0;
1993 			}
1994 			if (bp)
1995 				bp->b_resid = bp->b_bcount;
1996 			return 0;
1997 		}
1998 		if (sense->flags & SSD_ILI) {
1999 			if (info < 0) {
2000 				/*
2001 				 * the record was bigger than the read
2002 				 */
2003 				if ((xs->flags & SCSI_SILENT) == 0)
2004 					printf("%s: %d-byte record too big\n",
2005 					    st->sc_dev.dv_xname,
2006 					    xs->datalen - info);
2007 				return (EIO);
2008 			} else if (info > xs->datalen) {
2009 				/*
2010 				 * huh? the residual is bigger than the request
2011 				 */
2012 				if ((xs->flags & SCSI_SILENT) == 0)
2013 					printf(
2014 					    "%s: bad residual %d out of %d\n",
2015 					    st->sc_dev.dv_xname, info,
2016 					    xs->datalen);
2017 				return (EIO);
2018 			}
2019 			xs->resid = info;
2020 			if (bp)
2021 				bp->b_resid = info;
2022 			return (0);
2023 		}
2024 	}
2025 
2026 	if (skey == SKEY_BLANK_CHECK) {
2027 		/*
2028 		 * This quirk code helps the drive read the first tape block,
2029 		 * regardless of format.  That is required for these drives to
2030 		 * return proper MODE SENSE information.
2031 		 */
2032 		if ((st->quirks & ST_Q_SENSE_HELP) &&
2033 		    !(sc_link->flags & SDEV_MEDIA_LOADED)) {
2034 			/* still starting */
2035 			st->blksize -= 512;
2036 		} else if (!(st->flags & (ST_2FM_AT_EOD | ST_BLANK_READ))) {
2037 			st->flags |= ST_BLANK_READ;
2038 			xs->resid = xs->datalen;
2039 			if (bp) {
2040 				bp->b_resid = xs->resid;
2041 				/* return an EOF */
2042 			}
2043 			return (0);
2044 		}
2045 	}
2046 
2047 	return (EJUSTRETURN);
2048 }
2049 
2050 /*
2051  * The quirk here is that the drive returns some value to st_mode_sense
2052  * incorrectly until the tape has actually passed by the head.
2053  *
2054  * The method is to set the drive to large fixed-block state (user-specified
2055  * density and 1024-byte blocks), then read and rewind to get it to sense the
2056  * tape.  If that doesn't work, try 512-byte fixed blocks.  If that doesn't
2057  * work, as a last resort, try variable- length blocks.  The result will be
2058  * the ability to do an accurate st_mode_sense.
2059  *
2060  * We know we can do a rewind because we just did a load, which implies rewind.
2061  * Rewind seems preferable to space backward if we have a virgin tape.
2062  *
2063  * The rest of the code for this quirk is in ILI processing and BLANK CHECK
2064  * error processing, both part of st_interpret_sense.
2065  */
2066 int
2067 st_touch_tape(struct st_softc *st)
2068 {
2069 	char *buf;
2070 	int readsize;
2071 	int error;
2072 
2073 	buf = malloc(1024, M_TEMP, M_NOWAIT);
2074 	if (!buf)
2075 		return ENOMEM;
2076 
2077 	if ((error = st_mode_sense(st, 0)) != 0)
2078 		goto bad;
2079 	st->blksize = 1024;
2080 	do {
2081 		switch (st->blksize) {
2082 		case 512:
2083 		case 1024:
2084 			readsize = st->blksize;
2085 			st->flags |= ST_FIXEDBLOCKS;
2086 			break;
2087 		default:
2088 			readsize = 1;
2089 			st->flags &= ~ST_FIXEDBLOCKS;
2090 		}
2091 		if ((error = st_mode_select(st, 0)) != 0)
2092 			goto bad;
2093 		st_read(st, buf, readsize, SCSI_SILENT);	/* XXX */
2094 		if ((error = st_rewind(st, 0, 0)) != 0) {
2095 bad:			free(buf, M_TEMP);
2096 			return error;
2097 		}
2098 	} while (readsize != 1 && readsize > st->blksize);
2099 
2100 	free(buf, M_TEMP);
2101 	return 0;
2102 }
2103 
2104 int
2105 stdump(dev_t dev, daddr64_t blkno, caddr_t va, size_t size)
2106 {
2107 
2108 	/* Not implemented. */
2109 	return ENXIO;
2110 }
2111 
2112 /*
2113  * Remove unprocessed buffers from queue.
2114  */
2115 void
2116 st_kill_buffers(struct st_softc *st)
2117 {
2118 	struct buf *dp, *bp;
2119 	int s;
2120 
2121 	s = splbio();
2122 	for (dp = &st->buf_queue; (bp = dp->b_actf) != NULL; ) {
2123 		dp->b_actf = bp->b_actf;
2124 
2125 		bp->b_error = ENXIO;
2126 		bp->b_flags |= B_ERROR;
2127 		biodone(bp);
2128 	}
2129 	splx(s);
2130 }
2131