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