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