st.c revision 1.16
1/*	$OpenBSD: st.c,v 1.16 1997/07/11 02:18:40 tholo 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/fcntl.h>
61#include <sys/errno.h>
62#include <sys/ioctl.h>
63#include <sys/malloc.h>
64#include <sys/buf.h>
65#include <sys/proc.h>
66#include <sys/user.h>
67#include <sys/mtio.h>
68#include <sys/device.h>
69#include <sys/conf.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#define	ST_RETRIES	4	/* only on non IO commands */
78
79#define STMODE(z)	( minor(z)       & 0x03)
80#define STDSTY(z)	((minor(z) >> 2) & 0x03)
81#define STUNIT(z)	((minor(z) >> 4)       )
82#define CTLMODE	3
83
84/*
85 * Maximum density code known.
86 */
87#define SCSI_2_MAX_DENSITY_CODE		0x45
88
89/*
90 * Define various devices that we know mis-behave in some way,
91 * and note how they are bad, so we can correct for them
92 */
93struct modes {
94	u_int quirks;			/* same definitions as in quirkdata */
95	int blksize;
96	u_int8_t density;
97};
98
99struct quirkdata {
100	u_int quirks;
101#define	ST_Q_FORCE_BLKSIZE	0x0001
102#define	ST_Q_SENSE_HELP		0x0002	/* must do READ for good MODE SENSE */
103#define	ST_Q_IGNORE_LOADS	0x0004
104#define	ST_Q_BLKSIZE		0x0008	/* variable-block media_blksize > 0 */
105#define	ST_Q_UNIMODAL		0x0010	/* unimode drive rejects mode select */
106	u_int page_0_size;
107#define	MAX_PAGE_0_SIZE	64
108	struct modes modes[4];
109};
110
111struct st_quirk_inquiry_pattern {
112	struct scsi_inquiry_pattern pattern;
113	struct quirkdata quirkdata;
114};
115
116struct st_quirk_inquiry_pattern st_quirk_patterns[] = {
117	{{T_SEQUENTIAL, T_REMOV,
118	 "        ", "                ", "    "}, {0, 0, {
119		{ST_Q_FORCE_BLKSIZE, 512, 0},		/* minor 0-3 */
120		{ST_Q_FORCE_BLKSIZE, 512, QIC_24},	/* minor 4-7 */
121		{ST_Q_FORCE_BLKSIZE, 0, HALFINCH_1600},	/* minor 8-11 */
122		{ST_Q_FORCE_BLKSIZE, 0, HALFINCH_6250}	/* minor 12-15 */
123	}}},
124	{{T_SEQUENTIAL, T_REMOV,
125	 "TANDBERG", " TDC 3600       ", ""},     {0, 12, {
126		{0, 0, 0},				/* minor 0-3 */
127		{ST_Q_FORCE_BLKSIZE, 0, QIC_525},	/* minor 4-7 */
128		{0, 0, QIC_150},			/* minor 8-11 */
129		{0, 0, QIC_120}				/* minor 12-15 */
130	}}},
131 	{{T_SEQUENTIAL, T_REMOV,
132 	 "TANDBERG", " TDC 3800       ", ""},     {0, 0, {
133		{ST_Q_FORCE_BLKSIZE, 512, 0},		/* minor 0-3 */
134		{0, 0, QIC_525},			/* minor 4-7 */
135		{0, 0, QIC_150},			/* minor 8-11 */
136		{0, 0, QIC_120}				/* minor 12-15 */
137	}}},
138	/*
139	 * At least -005 and -007 need this.  I'll assume they all do unless I
140	 * hear otherwise.  - mycroft, 31MAR1994
141	 */
142	{{T_SEQUENTIAL, T_REMOV,
143	 "ARCHIVE ", "VIPER 2525 25462", ""},     {0, 0, {
144		{ST_Q_SENSE_HELP, 0, 0},		/* minor 0-3 */
145		{ST_Q_SENSE_HELP, 0, QIC_525},		/* minor 4-7 */
146		{0, 0, QIC_150},			/* minor 8-11 */
147		{0, 0, QIC_120}				/* minor 12-15 */
148	}}},
149	/*
150	 * One user reports that this works for his tape drive.  It probably
151	 * needs more work.  - mycroft, 09APR1994
152	 */
153	{{T_SEQUENTIAL, T_REMOV,
154	 "SANKYO  ", "CP525           ", ""},    {0, 0, {
155		{ST_Q_FORCE_BLKSIZE, 512, 0},		/* minor 0-3 */
156		{ST_Q_FORCE_BLKSIZE, 512, QIC_525},	/* minor 4-7 */
157		{0, 0, QIC_150},			/* minor 8-11 */
158		{0, 0, QIC_120}				/* minor 12-15 */
159	}}},
160	{{T_SEQUENTIAL, T_REMOV,
161	 "ANRITSU ", "DMT780          ", ""},     {0, 0, {
162		{ST_Q_FORCE_BLKSIZE, 512, 0},		/* minor 0-3 */
163		{ST_Q_FORCE_BLKSIZE, 512, QIC_525},	/* minor 4-7 */
164		{0, 0, QIC_150},			/* minor 8-11 */
165		{0, 0, QIC_120}				/* minor 12-15 */
166	}}},
167	{{T_SEQUENTIAL, T_REMOV,
168	 "ARCHIVE ", "VIPER 150  21247", ""},     {0, 12, {
169		{0, 0, 0},				/* minor 0-3 */
170		{0, 0, QIC_150},			/* minor 4-7 */
171		{0, 0, QIC_120},			/* minor 8-11 */
172		{0, 0, QIC_24}				/* minor 12-15 */
173	}}},
174	{{T_SEQUENTIAL, T_REMOV,
175	 "WANGTEK ", "5099ES SCSI", ""},          {0, 0, {
176		{ST_Q_FORCE_BLKSIZE, 512, 0},		/* minor 0-3 */
177		{0, 0, QIC_11},				/* minor 4-7 */
178		{0, 0, QIC_24},				/* minor 8-11 */
179		{0, 0, QIC_24}				/* minor 12-15 */
180	}}},
181	{{T_SEQUENTIAL, T_REMOV,
182	 "WANGTEK ", "5150ES SCSI", ""},          {0, 0, {
183		{ST_Q_FORCE_BLKSIZE, 512, 0},		/* minor 0-3 */
184		{0, 0, QIC_24},				/* minor 4-7 */
185		{0, 0, QIC_120},			/* minor 8-11 */
186		{0, 0, QIC_150}				/* minor 12-15 */
187	}}},
188	{{T_SEQUENTIAL, T_REMOV,
189	 "WANGTEK ", "5525ES SCSI REV7", ""},     {0, 0, {
190		{0, 0, 0},				/* minor 0-3 */
191		{ST_Q_BLKSIZE, 0, QIC_525},		/* minor 4-7 */
192		{0, 0, QIC_150},			/* minor 8-11 */
193		{0, 0, QIC_120}				/* minor 12-15 */
194	}}},
195	{{T_SEQUENTIAL, T_REMOV,
196	 "WangDAT ", "Model 1300      ", ""},     {0, 0, {
197		{0, 0, 0},				/* minor 0-3 */
198		{ST_Q_FORCE_BLKSIZE, 512, DDS},		/* minor 4-7 */
199		{ST_Q_FORCE_BLKSIZE, 1024, DDS},	/* minor 8-11 */
200		{ST_Q_FORCE_BLKSIZE, 0, DDS}		/* minor 12-15 */
201	}}},
202	{{T_SEQUENTIAL, T_REMOV,
203	 "EXABYTE ", "EXB-8200        ", "263H"}, {0, 5, {
204		{0, 0, 0},				/* minor 0-3 */
205		{0, 0, 0},				/* minor 4-7 */
206		{0, 0, 0},				/* minor 8-11 */
207		{0, 0, 0}				/* minor 12-15 */
208	}}},
209	{{T_SEQUENTIAL, T_REMOV,
210	 "HP      ", "T4000s          ", ""},     {ST_Q_UNIMODAL, 0, {
211		{0, 0, QIC_3095},			/* minor 0-3 */
212		{0, 0, QIC_3095},			/* minor 4-7 */
213		{0, 0, QIC_3095},			/* minor 8-11 */
214		{0, 0, QIC_3095},			/* minor 12-15 */
215	}}},
216#if 0
217	{{T_SEQUENTIAL, T_REMOV,
218	 "EXABYTE ", "EXB-8200        ", ""},     {0, 12, {
219		{0, 0, 0},				/* minor 0-3 */
220		{0, 0, 0},				/* minor 4-7 */
221		{0, 0, 0},				/* minor 8-11 */
222		{0, 0, 0}				/* minor 12-15 */
223	}}},
224#endif
225	{{T_SEQUENTIAL, T_REMOV,
226	 "WANGTEK ", "5150ES SCSI FA15\0""01 A", "????"}, {0, 0, {
227		{0, ST_Q_IGNORE_LOADS, 0},		/* minor 0-3 */
228		{0, 0, 0},				/* minor 4-7 */
229		{0, 0, 0},				/* minor 8-11 */
230		{0, 0, 0}				/* minor 12-15 */
231	}}},
232};
233
234#define NOEJECT 0
235#define EJECT 1
236
237#define NOREWIND 0
238#define REWIND 1
239
240struct st_softc {
241	struct device sc_dev;
242/*--------------------present operating parameters, flags etc.----------------*/
243	int flags;		/* see below                          */
244	u_int quirks;		/* quirks for the open mode           */
245	int blksize;		/* blksize we are using                */
246	u_int8_t density;	/* present density                    */
247	u_int page_0_size;	/* size of page 0 data		      */
248	u_int last_dsty;	/* last density opened               */
249/*--------------------device/scsi parameters----------------------------------*/
250	struct scsi_link *sc_link;	/* our link to the adpter etc.        */
251/*--------------------parameters reported by the device ----------------------*/
252	int blkmin;		/* min blk size                       */
253	int blkmax;		/* max blk size                       */
254	struct quirkdata *quirkdata;	/* if we have a rogue entry           */
255/*--------------------parameters reported by the device for this media--------*/
256	u_long numblks;		/* nominal blocks capacity            */
257	int media_blksize;	/* 0 if not ST_FIXEDBLOCKS            */
258	u_int8_t media_density;	/* this is what it said when asked    */
259/*--------------------quirks for the whole drive------------------------------*/
260	u_int drive_quirks;	/* quirks of this drive               */
261/*--------------------How we should set up when opening each minor device----*/
262	struct modes modes[4];	/* plus more for each mode            */
263	u_int8_t  modeflags[4];	/* flags for the modes                */
264#define DENSITY_SET_BY_USER	0x01
265#define DENSITY_SET_BY_QUIRK	0x02
266#define BLKSIZE_SET_BY_USER	0x04
267#define BLKSIZE_SET_BY_QUIRK	0x08
268/*--------------------storage for sense data returned by the drive------------*/
269	u_char sense_data[MAX_PAGE_0_SIZE];	/*
270						 * additional sense data needed
271						 * for mode sense/select.
272						 */
273	struct buf buf_queue;		/* the queue of pending IO operations */
274};
275
276
277int	stmatch __P((struct device *, void *, void *));
278void	stattach __P((struct device *, struct device *, void *));
279void	st_identify_drive __P((struct st_softc *, struct scsi_inquiry_data *));
280void	st_loadquirks __P((struct st_softc *));
281int	st_mount_tape __P((dev_t, int));
282void	st_unmount __P((struct st_softc *, boolean, boolean));
283int	st_decide_mode __P((struct st_softc *, boolean));
284void	ststart __P((void *));
285int	st_read __P((struct st_softc *, char *, int, int));
286int	st_read_block_limits __P((struct st_softc *, int));
287int	st_mode_sense __P((struct st_softc *, int));
288int	st_mode_select __P((struct st_softc *, int));
289int	st_space __P((struct st_softc *, int, u_int, int));
290int	st_write_filemarks __P((struct st_softc *, int, int));
291int	st_check_eod __P((struct st_softc *, boolean, int *, int));
292int	st_load __P((struct st_softc *, u_int, int));
293int	st_rewind __P((struct st_softc *, u_int, int));
294int	st_interpret_sense __P((struct scsi_xfer *));
295int	st_touch_tape __P((struct st_softc *));
296int	st_erase __P((struct st_softc *, int full, int flags));
297
298struct cfattach st_ca = {
299	sizeof(struct st_softc), stmatch, stattach
300};
301
302struct cfdriver st_cd = {
303	NULL, "st", DV_TAPE
304};
305
306struct scsi_device st_switch = {
307	st_interpret_sense,
308	ststart,
309	NULL,
310	NULL,
311};
312
313#define	ST_INFO_VALID	0x0001
314#define	ST_BLOCK_SET	0x0002	/* block size, mode set by ioctl      */
315#define	ST_WRITTEN	0x0004	/* data have been written, EOD needed */
316#define	ST_FIXEDBLOCKS	0x0008
317#define	ST_AT_FILEMARK	0x0010
318#define	ST_EIO_PENDING	0x0020	/* we couldn't report it then (had data) */
319#define	ST_NEW_MOUNT	0x0040	/* still need to decide mode              */
320#define	ST_READONLY	0x0080	/* st_mode_sense says write protected */
321#define	ST_FM_WRITTEN	0x0100	/*
322				 * EOF file mark written  -- used with
323				 * ~ST_WRITTEN to indicate that multiple file
324				 * marks have been written
325				 */
326#define	ST_BLANK_READ	0x0200	/* BLANK CHECK encountered already */
327#define	ST_2FM_AT_EOD	0x0400	/* write 2 file marks at EOD */
328#define	ST_MOUNTED	0x0800	/* Device is presently mounted */
329#define	ST_DONTBUFFER	0x1000	/* Disable buffering/caching */
330
331#define	ST_PER_ACTION	(ST_AT_FILEMARK | ST_EIO_PENDING | ST_BLANK_READ)
332#define	ST_PER_MOUNT	(ST_INFO_VALID | ST_BLOCK_SET | ST_WRITTEN | \
333			 ST_FIXEDBLOCKS | ST_READONLY | ST_FM_WRITTEN | \
334			 ST_2FM_AT_EOD | ST_PER_ACTION)
335
336struct scsi_inquiry_pattern st_patterns[] = {
337	{T_SEQUENTIAL, T_REMOV,
338	 "",         "",                 ""},
339};
340
341int
342stmatch(parent, match, aux)
343	struct device *parent;
344	void *match, *aux;
345{
346	struct scsibus_attach_args *sa = aux;
347	int priority;
348
349	(void)scsi_inqmatch(sa->sa_inqbuf,
350	    (caddr_t)st_patterns, sizeof(st_patterns)/sizeof(st_patterns[0]),
351	    sizeof(st_patterns[0]), &priority);
352	return (priority);
353}
354
355/*
356 * The routine called by the low level scsi routine when it discovers
357 * A device suitable for this driver
358 */
359void
360stattach(parent, self, aux)
361	struct device *parent, *self;
362	void *aux;
363{
364	struct st_softc *st = (void *)self;
365	struct scsibus_attach_args *sa = aux;
366	struct scsi_link *sc_link = sa->sa_sc_link;
367
368	SC_DEBUG(sc_link, SDEV_DB2, ("stattach: "));
369
370	/*
371	 * Store information needed to contact our base driver
372	 */
373	st->sc_link = sc_link;
374	sc_link->device = &st_switch;
375	sc_link->device_softc = st;
376	sc_link->openings = 1;
377
378	/*
379	 * Check if the drive is a known criminal and take
380	 * Any steps needed to bring it into line
381	 */
382	st_identify_drive(st, sa->sa_inqbuf);
383
384	/*
385	 * Use the subdriver to request information regarding
386	 * the drive. We cannot use interrupts yet, so the
387	 * request must specify this.
388	 */
389	printf("\n");
390	printf("%s: %s", st->sc_dev.dv_xname, st->quirkdata ? "rogue, " : "");
391	if (scsi_test_unit_ready(sc_link,
392	    SCSI_AUTOCONF | SCSI_SILENT | SCSI_IGNORE_MEDIA_CHANGE) ||
393	    st_mode_sense(st,
394	    SCSI_AUTOCONF | SCSI_SILENT | SCSI_IGNORE_MEDIA_CHANGE))
395		printf("drive empty\n");
396	else {
397		printf("density code 0x%x, ", st->media_density);
398		if (st->media_blksize > 0)
399			printf("%d-byte", st->media_blksize);
400		else
401			printf("variable");
402		printf(" blocks, write-%s\n",
403		    (st->flags & ST_READONLY) ? "protected" : "enabled");
404	}
405
406	/*
407	 * Set up the buf queue for this device
408	 */
409	st->buf_queue.b_active = 0;
410	st->buf_queue.b_actf = 0;
411	st->buf_queue.b_actb = &st->buf_queue.b_actf;
412
413	/*
414	 * Reset the media loaded flag, sometimes the data
415	 * aquired at boot time is not quite accurate.  This
416	 * will be checked again at the first open.
417	 */
418	sc_link->flags &= ~SDEV_MEDIA_LOADED;
419}
420
421/*
422 * Use the inquiry routine in 'scsi_base' to get drive info so we can
423 * Further tailor our behaviour.
424 */
425void
426st_identify_drive(st, inqbuf)
427	struct st_softc *st;
428	struct scsi_inquiry_data *inqbuf;
429{
430	struct st_quirk_inquiry_pattern *finger;
431	int priority;
432
433	finger = (struct st_quirk_inquiry_pattern *)scsi_inqmatch(inqbuf,
434	    (caddr_t)st_quirk_patterns,
435	    sizeof(st_quirk_patterns)/sizeof(st_quirk_patterns[0]),
436	    sizeof(st_quirk_patterns[0]), &priority);
437	if (priority != 0) {
438		st->quirkdata = &finger->quirkdata;
439		st->drive_quirks = finger->quirkdata.quirks;
440		st->quirks = finger->quirkdata.quirks;	/* start value */
441		st->page_0_size = finger->quirkdata.page_0_size;
442		st_loadquirks(st);
443	}
444}
445
446/*
447 * initialise the subdevices to the default (QUIRK) state.
448 * this will remove any setting made by the system operator or previous
449 * operations.
450 */
451void
452st_loadquirks(st)
453	struct st_softc *st;
454{
455	int i;
456	struct	modes *mode;
457	struct	modes *mode2;
458
459	mode = st->quirkdata->modes;
460	mode2 = st->modes;
461	for (i = 0; i < 4; i++) {
462		bzero(mode2, sizeof(struct modes));
463		st->modeflags[i] &= ~(BLKSIZE_SET_BY_QUIRK |
464		    DENSITY_SET_BY_QUIRK | BLKSIZE_SET_BY_USER |
465		    DENSITY_SET_BY_USER);
466		if ((mode->quirks | st->drive_quirks) & ST_Q_FORCE_BLKSIZE) {
467			mode2->blksize = mode->blksize;
468			st->modeflags[i] |= BLKSIZE_SET_BY_QUIRK;
469		}
470		if (mode->density) {
471			mode2->density = mode->density;
472			st->modeflags[i] |= DENSITY_SET_BY_QUIRK;
473		}
474		mode++;
475		mode2++;
476	}
477}
478
479/*
480 * open the device.
481 */
482int
483stopen(dev, flags, mode, p)
484	dev_t dev;
485	int flags;
486	int mode;
487	struct proc *p;
488{
489	int unit;
490	u_int stmode, dsty;
491	int error = 0;
492	struct st_softc *st;
493	struct scsi_link *sc_link;
494
495	unit = STUNIT(dev);
496	if (unit >= st_cd.cd_ndevs)
497		return ENXIO;
498	st = st_cd.cd_devs[unit];
499	if (!st)
500		return ENXIO;
501
502	stmode = STMODE(dev);
503	dsty = STDSTY(dev);
504	sc_link = st->sc_link;
505
506	SC_DEBUG(sc_link, SDEV_DB1, ("open: dev=0x%x (unit %d (of %d))\n", dev,
507	    unit, st_cd.cd_ndevs));
508
509	/*
510	 * Only allow one at a time
511	 */
512	if (sc_link->flags & SDEV_OPEN) {
513		printf("%s: already open\n", st->sc_dev.dv_xname);
514		return EBUSY;
515	}
516
517	/*
518	 * Catch any unit attention errors.
519	 */
520	error = scsi_test_unit_ready(sc_link,
521				     SCSI_IGNORE_MEDIA_CHANGE |
522				     (stmode == CTLMODE ?
523					SCSI_IGNORE_NOT_READY : 0));
524	if (error)
525		goto bad;
526
527	sc_link->flags |= SDEV_OPEN;	/* unit attn are now errors */
528
529	/*
530	 * If the mode is 3 (e.g. minor = 3,7,11,15)
531	 * then the device has been opened to set defaults
532	 * This mode does NOT ALLOW I/O, only ioctls
533	 */
534	if (stmode == CTLMODE)
535		return 0;
536
537	/*
538	 * if it's a different mode, or if the media has been
539	 * invalidated, unmount the tape from the previous
540	 * session but continue with open processing
541	 */
542	if (st->last_dsty != dsty || !(sc_link->flags & SDEV_MEDIA_LOADED))
543		st_unmount(st, NOEJECT, REWIND);
544
545	/*
546	 * If we are not mounted, then we should start a new
547	 * mount session.
548	 */
549	if (!(st->flags & ST_MOUNTED)) {
550		st_mount_tape(dev, flags);
551		st->last_dsty = dsty;
552	}
553
554	/*
555	 * Make sure that a tape opened in write-only mode will have
556	 * file marks written on it when closed, even if not written to.
557	 * This is for SUN compatibility
558	 */
559	if ((flags & O_ACCMODE) == FWRITE)
560		st->flags |= ST_WRITTEN;
561
562	SC_DEBUG(sc_link, SDEV_DB2, ("open complete\n"));
563	return 0;
564
565bad:
566	st_unmount(st, NOEJECT, REWIND);
567	sc_link->flags &= ~SDEV_OPEN;
568	return error;
569}
570
571/*
572 * close the device.. only called if we are the LAST
573 * occurence of an open device
574 */
575int
576stclose(dev, flags, mode, p)
577	dev_t dev;
578	int flags;
579	int mode;
580	struct proc *p;
581{
582	struct st_softc *st = st_cd.cd_devs[STUNIT(dev)];
583
584	SC_DEBUG(st->sc_link, SDEV_DB1, ("closing\n"));
585	if ((st->flags & (ST_WRITTEN | ST_FM_WRITTEN)) == ST_WRITTEN)
586		st_write_filemarks(st, 1, 0);
587	switch (STMODE(dev)) {
588	case 0:		/* normal */
589		st_unmount(st, NOEJECT, REWIND);
590		break;
591	case 3:		/* eject, no rewind */
592		st_unmount(st, EJECT, NOREWIND);
593		break;
594	case 1:		/* no rewind */
595		st_unmount(st, NOEJECT, NOREWIND);
596		break;
597	case 2:		/* rewind, eject */
598		st_unmount(st, EJECT, REWIND);
599		break;
600	}
601	st->sc_link->flags &= ~SDEV_OPEN;
602
603	return 0;
604}
605
606/*
607 * Start a new mount session.
608 * Copy in all the default parameters from the selected device mode.
609 * and try guess any that seem to be defaulted.
610 */
611int
612st_mount_tape(dev, flags)
613	dev_t dev;
614	int flags;
615{
616	int unit;
617	u_int mode, dsty;
618	struct st_softc *st;
619	struct scsi_link *sc_link;
620	int error = 0;
621
622	unit = STUNIT(dev);
623	mode = STMODE(dev);
624	dsty = STDSTY(dev);
625	st = st_cd.cd_devs[unit];
626	sc_link = st->sc_link;
627
628	if (st->flags & ST_MOUNTED)
629		return 0;
630
631	SC_DEBUG(sc_link, SDEV_DB1, ("mounting\n "));
632	st->flags |= ST_NEW_MOUNT;
633	st->quirks = st->drive_quirks | st->modes[dsty].quirks;
634	/*
635	 * If the media is new, then make sure we give it a chance to
636	 * to do a 'load' instruction.  (We assume it is new.)
637	 */
638	if ((error = st_load(st, LD_LOAD, 0)) != 0)
639		return error;
640	/*
641	 * Throw another dummy instruction to catch
642	 * 'Unit attention' errors. Some drives appear to give
643	 * these after doing a Load instruction.
644	 * (noteably some DAT drives)
645	 */
646	scsi_test_unit_ready(sc_link, SCSI_SILENT);	/* XXX */
647
648	/*
649	 * Some devices can't tell you much until they have been
650	 * asked to look at the media. This quirk does this.
651	 */
652	if (st->quirks & ST_Q_SENSE_HELP)
653		if ((error = st_touch_tape(st)) != 0)
654			return error;
655	/*
656	 * Load the physical device parameters
657	 * loads: blkmin, blkmax
658	 */
659	if ((error = st_read_block_limits(st, 0)) != 0)
660		return error;
661	/*
662	 * Load the media dependent parameters
663	 * includes: media_blksize,media_density,numblks
664	 * As we have a tape in, it should be reflected here.
665	 * If not you may need the "quirk" above.
666	 */
667	if ((error = st_mode_sense(st, 0)) != 0)
668		return error;
669	/*
670	 * If we have gained a permanent density from somewhere,
671	 * then use it in preference to the one supplied by
672	 * default by the driver.
673	 */
674	if (st->modeflags[dsty] & (DENSITY_SET_BY_QUIRK | DENSITY_SET_BY_USER))
675		st->density = st->modes[dsty].density;
676	else
677		st->density = st->media_density;
678	/*
679	 * If we have gained a permanent blocksize
680	 * then use it in preference to the one supplied by
681	 * default by the driver.
682	 */
683	st->flags &= ~ST_FIXEDBLOCKS;
684	if (st->modeflags[dsty] & (BLKSIZE_SET_BY_QUIRK | BLKSIZE_SET_BY_USER)) {
685		st->blksize = st->modes[dsty].blksize;
686		if (st->blksize)
687			st->flags |= ST_FIXEDBLOCKS;
688	} else {
689		if ((error = st_decide_mode(st, FALSE)) != 0)
690			return error;
691	}
692	if ((error = st_mode_select(st, 0)) != 0) {
693		printf("%s: cannot set selected mode\n", st->sc_dev.dv_xname);
694		return error;
695	}
696	scsi_prevent(sc_link, PR_PREVENT,
697	    SCSI_IGNORE_ILLEGAL_REQUEST | SCSI_IGNORE_NOT_READY);
698	st->flags &= ~ST_NEW_MOUNT;
699	st->flags |= ST_MOUNTED;
700	sc_link->flags |= SDEV_MEDIA_LOADED;	/* move earlier? */
701
702	return 0;
703}
704
705/*
706 * End the present mount session.
707 * Rewind, and optionally eject the tape.
708 * Reset various flags to indicate that all new
709 * operations require another mount operation
710 */
711void
712st_unmount(st, eject, rewind)
713	struct st_softc *st;
714	boolean eject, rewind;
715{
716	struct scsi_link *sc_link = st->sc_link;
717	int nmarks;
718
719	if (!(st->flags & ST_MOUNTED))
720		return;
721	SC_DEBUG(sc_link, SDEV_DB1, ("unmounting\n"));
722	st_check_eod(st, FALSE, &nmarks, SCSI_IGNORE_NOT_READY);
723	if (rewind)
724		st_rewind(st, 0, SCSI_IGNORE_NOT_READY);
725	scsi_prevent(sc_link, PR_ALLOW,
726	    SCSI_IGNORE_ILLEGAL_REQUEST | SCSI_IGNORE_NOT_READY);
727	if (eject)
728		st_load(st, LD_UNLOAD, SCSI_IGNORE_NOT_READY);
729	st->flags &= ~(ST_MOUNTED | ST_NEW_MOUNT);
730	sc_link->flags &= ~SDEV_MEDIA_LOADED;
731}
732
733/*
734 * Given all we know about the device, media, mode, 'quirks' and
735 * initial operation, make a decision as to how we should be set
736 * to run (regarding blocking and EOD marks)
737 */
738int
739st_decide_mode(st, first_read)
740	struct st_softc *st;
741	boolean	first_read;
742{
743#ifdef SCSIDEBUG
744	struct scsi_link *sc_link = st->sc_link;
745#endif
746
747	SC_DEBUG(sc_link, SDEV_DB2, ("starting block mode decision\n"));
748
749	/*
750	 * If the drive can only handle fixed-length blocks and only at
751	 * one size, perhaps we should just do that.
752	 */
753	if (st->blkmin && (st->blkmin == st->blkmax)) {
754		st->flags |= ST_FIXEDBLOCKS;
755		st->blksize = st->blkmin;
756		SC_DEBUG(sc_link, SDEV_DB3,
757		    ("blkmin == blkmax of %d\n", st->blkmin));
758		goto done;
759	}
760	/*
761	 * If the tape density mandates (or even suggests) use of fixed
762	 * or variable-length blocks, comply.
763	 */
764	switch (st->density) {
765	case HALFINCH_800:
766	case HALFINCH_1600:
767	case HALFINCH_6250:
768	case DDS:
769		st->flags &= ~ST_FIXEDBLOCKS;
770		st->blksize = 0;
771		SC_DEBUG(sc_link, SDEV_DB3, ("density specified variable\n"));
772		goto done;
773	case QIC_11:
774	case QIC_24:
775	case QIC_120:
776	case QIC_150:
777	case QIC_525:
778	case QIC_1320:
779		st->flags |= ST_FIXEDBLOCKS;
780		if (st->media_blksize > 0)
781			st->blksize = st->media_blksize;
782		else
783			st->blksize = DEF_FIXED_BSIZE;
784		SC_DEBUG(sc_link, SDEV_DB3, ("density specified fixed\n"));
785		goto done;
786	}
787	/*
788	 * If we're about to read the tape, perhaps we should choose
789	 * fixed or variable-length blocks and block size according to
790	 * what the drive found on the tape.
791	 */
792	if (first_read &&
793	    (!(st->quirks & ST_Q_BLKSIZE) || (st->media_blksize == 0) ||
794	    (st->media_blksize == DEF_FIXED_BSIZE) ||
795	    (st->media_blksize == 1024))) {
796		if (st->media_blksize > 0)
797			st->flags |= ST_FIXEDBLOCKS;
798		else
799			st->flags &= ~ST_FIXEDBLOCKS;
800		st->blksize = st->media_blksize;
801		SC_DEBUG(sc_link, SDEV_DB3,
802		    ("Used media_blksize of %d\n", st->media_blksize));
803		goto done;
804	}
805	/*
806	 * We're getting no hints from any direction.  Choose variable-
807	 * length blocks arbitrarily.
808	 */
809	st->flags &= ~ST_FIXEDBLOCKS;
810	st->blksize = 0;
811	SC_DEBUG(sc_link, SDEV_DB3,
812	    ("Give up and default to variable mode\n"));
813
814done:
815	/*
816	 * Decide whether or not to write two file marks to signify end-
817	 * of-data.  Make the decision as a function of density.  If
818	 * the decision is not to use a second file mark, the SCSI BLANK
819	 * CHECK condition code will be recognized as end-of-data when
820	 * first read.
821	 * (I think this should be a by-product of fixed/variable..julian)
822	 */
823	switch (st->density) {
824/*      case 8 mm:   What is the SCSI density code for 8 mm, anyway? */
825	case QIC_11:
826	case QIC_24:
827	case QIC_120:
828	case QIC_150:
829	case QIC_525:
830	case QIC_1320:
831		st->flags &= ~ST_2FM_AT_EOD;
832		break;
833	default:
834		st->flags |= ST_2FM_AT_EOD;
835	}
836	return 0;
837}
838
839/*
840 * Actually translate the requested transfer into
841 * one the physical driver can understand
842 * The transfer is described by a buf and will include
843 * only one physical transfer.
844 */
845void
846ststrategy(bp)
847	struct buf *bp;
848{
849	struct st_softc *st = st_cd.cd_devs[STUNIT(bp->b_dev)];
850	struct buf *dp;
851	int s;
852
853	SC_DEBUG(st->sc_link, SDEV_DB1,
854	    ("ststrategy %ld bytes @ blk %d\n", bp->b_bcount, bp->b_blkno));
855	/*
856	 * If it's a null transfer, return immediatly
857	 */
858	if (bp->b_bcount == 0)
859		goto done;
860	/*
861	 * Odd sized request on fixed drives are verboten
862	 */
863	if (st->flags & ST_FIXEDBLOCKS) {
864		if (bp->b_bcount % st->blksize) {
865			printf("%s: bad request, must be multiple of %d\n",
866			    st->sc_dev.dv_xname, st->blksize);
867			bp->b_error = EIO;
868			goto bad;
869		}
870	}
871	/*
872	 * as are out-of-range requests on variable drives.
873	 */
874	else if (bp->b_bcount < st->blkmin ||
875		 (st->blkmax && bp->b_bcount > st->blkmax)) {
876		printf("%s: bad request, must be between %d and %d\n",
877		    st->sc_dev.dv_xname, st->blkmin, st->blkmax);
878		bp->b_error = EIO;
879		goto bad;
880	}
881	s = splbio();
882
883	/*
884	 * Place it in the queue of activities for this tape
885	 * at the end (a bit silly because we only have on user..
886	 * (but it could fork()))
887	 */
888	dp = &st->buf_queue;
889	bp->b_actf = NULL;
890	bp->b_actb = dp->b_actb;
891	*dp->b_actb = bp;
892	dp->b_actb = &bp->b_actf;
893
894	/*
895	 * Tell the device to get going on the transfer if it's
896	 * not doing anything, otherwise just wait for completion
897	 * (All a bit silly if we're only allowing 1 open but..)
898	 */
899	ststart(st);
900
901	splx(s);
902	return;
903bad:
904	bp->b_flags |= B_ERROR;
905done:
906	/*
907	 * Correctly set the buf to indicate a completed xfer
908	 */
909	bp->b_resid = bp->b_bcount;
910	biodone(bp);
911	return;
912}
913
914/*
915 * ststart looks to see if there is a buf waiting for the device
916 * and that the device is not already busy. If both are true,
917 * It dequeues the buf and creates a scsi command to perform the
918 * transfer required. The transfer request will call scsi_done
919 * on completion, which will in turn call this routine again
920 * so that the next queued transfer is performed.
921 * The bufs are queued by the strategy routine (ststrategy)
922 *
923 * This routine is also called after other non-queued requests
924 * have been made of the scsi driver, to ensure that the queue
925 * continues to be drained.
926 * ststart() is called at splbio
927 */
928void
929ststart(v)
930	void *v;
931{
932	struct st_softc *st = v;
933	struct scsi_link *sc_link = st->sc_link;
934	register struct buf *bp, *dp;
935	struct scsi_rw_tape cmd;
936	int flags;
937
938	SC_DEBUG(sc_link, SDEV_DB2, ("ststart "));
939	/*
940	 * See if there is a buf to do and we are not already
941	 * doing one
942	 */
943	while (sc_link->openings > 0) {
944		/* if a special awaits, let it proceed first */
945		if (sc_link->flags & SDEV_WAITING) {
946			sc_link->flags &= ~SDEV_WAITING;
947			wakeup((caddr_t)sc_link);
948			return;
949		}
950
951		dp = &st->buf_queue;
952		if ((bp = dp->b_actf) == NULL)
953			return;
954		if ((dp = bp->b_actf) != NULL)
955			dp->b_actb = bp->b_actb;
956		else
957			st->buf_queue.b_actb = bp->b_actb;
958		*bp->b_actb = dp;
959
960		/*
961		 * if the device has been unmounted by the user
962		 * then throw away all requests until done
963		 */
964		if (!(st->flags & ST_MOUNTED) ||
965		    !(sc_link->flags & SDEV_MEDIA_LOADED)) {
966			/* make sure that one implies the other.. */
967			sc_link->flags &= ~SDEV_MEDIA_LOADED;
968			bp->b_flags |= B_ERROR;
969			bp->b_resid = bp->b_bcount;
970			bp->b_error = EIO;
971			biodone(bp);
972			continue;
973		}
974		/*
975		 * only FIXEDBLOCK devices have pending operations
976		 */
977		if (st->flags & ST_FIXEDBLOCKS) {
978			/*
979			 * If we are at a filemark but have not reported it yet
980			 * then we should report it now
981			 */
982			if (st->flags & ST_AT_FILEMARK) {
983				if ((bp->b_flags & B_READ) == B_WRITE) {
984					/*
985					 * Handling of ST_AT_FILEMARK in
986					 * st_space will fill in the right file
987					 * mark count.
988					 * Back up over filemark
989					 */
990					if (st_space(st, 0, SP_FILEMARKS, 0)) {
991						bp->b_flags |= B_ERROR;
992						bp->b_resid = bp->b_bcount;
993						bp->b_error = EIO;
994						biodone(bp);
995						continue;
996					}
997				} else {
998					bp->b_resid = bp->b_bcount;
999					bp->b_error = 0;
1000					bp->b_flags &= ~B_ERROR;
1001					st->flags &= ~ST_AT_FILEMARK;
1002					biodone(bp);
1003					continue;	/* seek more work */
1004				}
1005			}
1006			/*
1007			 * If we are at EIO (e.g. EOM) but have not reported it
1008			 * yet then we should report it now
1009			 */
1010			if (st->flags & ST_EIO_PENDING) {
1011				bp->b_resid = bp->b_bcount;
1012				bp->b_error = EIO;
1013				bp->b_flags |= B_ERROR;
1014				st->flags &= ~ST_EIO_PENDING;
1015				biodone(bp);
1016				continue;	/* seek more work */
1017			}
1018		}
1019
1020		/*
1021		 *  Fill out the scsi command
1022		 */
1023		bzero(&cmd, sizeof(cmd));
1024		if ((bp->b_flags & B_READ) == B_WRITE) {
1025			cmd.opcode = WRITE;
1026			st->flags &= ~ST_FM_WRITTEN;
1027			st->flags |= ST_WRITTEN;
1028			flags = SCSI_DATA_OUT;
1029		} else {
1030			cmd.opcode = READ;
1031			flags = SCSI_DATA_IN;
1032		}
1033
1034		/*
1035		 * Handle "fixed-block-mode" tape drives by using the
1036		 * block count instead of the length.
1037		 */
1038		if (st->flags & ST_FIXEDBLOCKS) {
1039			cmd.byte2 |= SRW_FIXED;
1040			_lto3b(bp->b_bcount / st->blksize, cmd.len);
1041		} else
1042			_lto3b(bp->b_bcount, cmd.len);
1043
1044		/*
1045		 * go ask the adapter to do all this for us
1046		 */
1047		if (scsi_scsi_cmd(sc_link, (struct scsi_generic *) &cmd,
1048		    sizeof(cmd), (u_char *) bp->b_data, bp->b_bcount, 0,
1049		    100000, bp, flags | SCSI_NOSLEEP))
1050			printf("%s: not queued\n", st->sc_dev.dv_xname);
1051	} /* go back and see if we can cram more work in.. */
1052}
1053
1054int
1055stread(dev, uio, iomode)
1056	dev_t dev;
1057	struct uio *uio;
1058	int iomode;
1059{
1060	struct st_softc *st = st_cd.cd_devs[STUNIT(dev)];
1061
1062	return (physio(ststrategy, NULL, dev, B_READ,
1063		       st->sc_link->adapter->scsi_minphys, uio));
1064}
1065
1066int
1067stwrite(dev, uio, iomode)
1068	dev_t dev;
1069	struct uio *uio;
1070	int iomode;
1071{
1072	struct st_softc *st = st_cd.cd_devs[STUNIT(dev)];
1073
1074	return (physio(ststrategy, NULL, dev, B_WRITE,
1075		       st->sc_link->adapter->scsi_minphys, uio));
1076}
1077
1078/*
1079 * Perform special action on behalf of the user;
1080 * knows about the internals of this device
1081 */
1082int
1083stioctl(dev, cmd, arg, flag, p)
1084	dev_t dev;
1085	u_long cmd;
1086	caddr_t arg;
1087	int flag;
1088	struct proc *p;
1089{
1090	int error = 0;
1091	int unit;
1092	int number, nmarks, dsty;
1093	int flags;
1094	struct st_softc *st;
1095	int hold_blksize;
1096	u_int8_t hold_density;
1097	struct mtop *mt = (struct mtop *) arg;
1098
1099	/*
1100	 * Find the device that the user is talking about
1101	 */
1102	flags = 0;		/* give error messages, act on errors etc. */
1103	unit = STUNIT(dev);
1104	dsty = STDSTY(dev);
1105	st = st_cd.cd_devs[unit];
1106	hold_blksize = st->blksize;
1107	hold_density = st->density;
1108
1109	switch (cmd) {
1110
1111	case MTIOCGET: {
1112		struct mtget *g = (struct mtget *) arg;
1113
1114		SC_DEBUG(st->sc_link, SDEV_DB1, ("[ioctl: get status]\n"));
1115		bzero(g, sizeof(struct mtget));
1116		g->mt_type = 0x7;	/* Ultrix compat *//*? */
1117		g->mt_blksiz = st->blksize;
1118		g->mt_density = st->density;
1119		g->mt_mblksiz[0] = st->modes[0].blksize;
1120		g->mt_mblksiz[1] = st->modes[1].blksize;
1121		g->mt_mblksiz[2] = st->modes[2].blksize;
1122		g->mt_mblksiz[3] = st->modes[3].blksize;
1123		g->mt_mdensity[0] = st->modes[0].density;
1124		g->mt_mdensity[1] = st->modes[1].density;
1125		g->mt_mdensity[2] = st->modes[2].density;
1126		g->mt_mdensity[3] = st->modes[3].density;
1127		break;
1128	}
1129	case MTIOCTOP: {
1130
1131		SC_DEBUG(st->sc_link, SDEV_DB1,
1132		    ("[ioctl: op=0x%x count=0x%x]\n", mt->mt_op, mt->mt_count));
1133
1134		/* compat: in U*x it is a short */
1135		number = mt->mt_count;
1136		switch ((short) (mt->mt_op)) {
1137		case MTWEOF:	/* write an end-of-file record */
1138			error = st_write_filemarks(st, number, flags);
1139			break;
1140		case MTBSF:	/* backward space file */
1141			number = -number;
1142		case MTFSF:	/* forward space file */
1143			error = st_check_eod(st, FALSE, &nmarks, flags);
1144			if (!error)
1145				error = st_space(st, number - nmarks,
1146				    SP_FILEMARKS, flags);
1147			break;
1148		case MTBSR:	/* backward space record */
1149			number = -number;
1150		case MTFSR:	/* forward space record */
1151			error = st_check_eod(st, TRUE, &nmarks, flags);
1152			if (!error)
1153				error = st_space(st, number, SP_BLKS, flags);
1154			break;
1155		case MTREW:	/* rewind */
1156			error = st_rewind(st, 0, flags);
1157			break;
1158		case MTOFFL:	/* rewind and put the drive offline */
1159			st_unmount(st, EJECT, REWIND);
1160			break;
1161		case MTNOP:	/* no operation, sets status only */
1162			break;
1163		case MTRETEN:	/* retension the tape */
1164			error = st_load(st, LD_RETENSION, flags);
1165			if (!error)
1166				error = st_load(st, LD_LOAD, flags);
1167			break;
1168		case MTEOM:	/* forward space to end of media */
1169			error = st_check_eod(st, FALSE, &nmarks, flags);
1170			if (!error)
1171				error = st_space(st, 1, SP_EOM, flags);
1172			break;
1173		case MTCACHE:	/* enable controller cache */
1174			st->flags &= ~ST_DONTBUFFER;
1175			goto try_new_value;
1176		case MTNOCACHE:	/* disable controller cache */
1177			st->flags |= ST_DONTBUFFER;
1178			goto try_new_value;
1179		case MTERASE:	/* erase volume */
1180			error = st_erase(st, number, flags);
1181			break;
1182		case MTSETBSIZ:	/* Set block size for device */
1183#ifdef	NOTYET
1184			if (!(st->flags & ST_NEW_MOUNT)) {
1185				uprintf("re-mount tape before changing blocksize");
1186				error = EINVAL;
1187				break;
1188			}
1189#endif
1190			if (number == 0) {
1191				st->flags &= ~ST_FIXEDBLOCKS;
1192			} else {
1193				if ((st->blkmin || st->blkmax) &&
1194				    (number < st->blkmin ||
1195				    number > st->blkmax)) {
1196					error = EINVAL;
1197					break;
1198				}
1199				st->flags |= ST_FIXEDBLOCKS;
1200			}
1201			st->blksize = number;
1202			st->flags |= ST_BLOCK_SET;	/*XXX */
1203			goto try_new_value;
1204
1205		case MTSETDNSTY:	/* Set density for device and mode */
1206			if (number > SCSI_2_MAX_DENSITY_CODE) {
1207				error = EINVAL;
1208				break;
1209			} else
1210				st->density = number;
1211			goto try_new_value;
1212
1213		default:
1214			error = EINVAL;
1215		}
1216		break;
1217	}
1218	case MTIOCIEOT:
1219	case MTIOCEEOT:
1220		break;
1221	default:
1222		if (STMODE(dev) == CTLMODE)
1223			error = scsi_do_safeioctl(st->sc_link, dev,
1224			    cmd, arg, flag, p);
1225		else
1226			error = ENOTTY;
1227		break;
1228	}
1229	return error;
1230/*-----------------------------*/
1231try_new_value:
1232	/*
1233	 * Check that the mode being asked for is aggreeable to the
1234	 * drive. If not, put it back the way it was.
1235	 */
1236	if ((error = st_mode_select(st, 0)) != 0) {/* put it back as it was */
1237		printf("%s: cannot set selected mode\n", st->sc_dev.dv_xname);
1238		st->density = hold_density;
1239		st->blksize = hold_blksize;
1240		if (st->blksize)
1241			st->flags |= ST_FIXEDBLOCKS;
1242		else
1243			st->flags &= ~ST_FIXEDBLOCKS;
1244		return error;
1245	}
1246	/*
1247	 * As the drive liked it, if we are setting a new default,
1248	 * set it into the structures as such.
1249	 *
1250	 * The means for deciding this are not finalised yet
1251	 */
1252	if (STMODE(dev) == 0x03) {
1253		/* special mode */
1254		/* XXX */
1255		switch ((short) (mt->mt_op)) {
1256		case MTSETBSIZ:
1257			st->modes[dsty].blksize = st->blksize;
1258			st->modeflags[dsty] |= BLKSIZE_SET_BY_USER;
1259			break;
1260		case MTSETDNSTY:
1261			st->modes[dsty].density = st->density;
1262			st->modeflags[dsty] |= DENSITY_SET_BY_USER;
1263			break;
1264		}
1265	}
1266	return 0;
1267}
1268
1269/*
1270 * Do a synchronous read.
1271 */
1272int
1273st_read(st, buf, size, flags)
1274	struct st_softc *st;
1275	int size;
1276	int flags;
1277	char *buf;
1278{
1279	struct scsi_rw_tape cmd;
1280
1281	/*
1282	 * If it's a null transfer, return immediatly
1283	 */
1284	if (size == 0)
1285		return 0;
1286	bzero(&cmd, sizeof(cmd));
1287	cmd.opcode = READ;
1288	if (st->flags & ST_FIXEDBLOCKS) {
1289		cmd.byte2 |= SRW_FIXED;
1290		_lto3b(size / (st->blksize ? st->blksize : DEF_FIXED_BSIZE),
1291		    cmd.len);
1292	} else
1293		_lto3b(size, cmd.len);
1294	return scsi_scsi_cmd(st->sc_link, (struct scsi_generic *) &cmd,
1295	    sizeof(cmd), (u_char *) buf, size, 0, 100000, NULL,
1296	    flags | SCSI_DATA_IN);
1297}
1298
1299/*
1300 * Ask the drive what it's min and max blk sizes are.
1301 */
1302int
1303st_read_block_limits(st, flags)
1304	struct st_softc *st;
1305	int flags;
1306{
1307	struct scsi_block_limits cmd;
1308	struct scsi_block_limits_data block_limits;
1309	struct scsi_link *sc_link = st->sc_link;
1310	int error;
1311
1312	/*
1313	 * First check if we have it all loaded
1314	 */
1315	if ((sc_link->flags & SDEV_MEDIA_LOADED))
1316		return 0;
1317
1318	/*
1319	 * do a 'Read Block Limits'
1320	 */
1321	bzero(&cmd, sizeof(cmd));
1322	cmd.opcode = READ_BLOCK_LIMITS;
1323
1324	/*
1325	 * do the command, update the global values
1326	 */
1327	error = scsi_scsi_cmd(sc_link, (struct scsi_generic *) &cmd,
1328			      sizeof(cmd), (u_char *) &block_limits,
1329			      sizeof(block_limits), ST_RETRIES, 5000,
1330			      NULL, flags | SCSI_DATA_IN);
1331	if (error)
1332		return error;
1333
1334	st->blkmin = _2btol(block_limits.min_length);
1335	st->blkmax = _3btol(block_limits.max_length);
1336
1337	SC_DEBUG(sc_link, SDEV_DB3,
1338	    ("(%d <= blksize <= %d)\n", st->blkmin, st->blkmax));
1339	return 0;
1340}
1341
1342/*
1343 * Get the scsi driver to send a full inquiry to the
1344 * device and use the results to fill out the global
1345 * parameter structure.
1346 *
1347 * called from:
1348 * attach
1349 * open
1350 * ioctl (to reset original blksize)
1351 */
1352int
1353st_mode_sense(st, flags)
1354	struct st_softc *st;
1355	int flags;
1356{
1357	u_int scsi_sense_len;
1358	int error;
1359	struct scsi_mode_sense cmd;
1360	struct scsi_sense {
1361		struct scsi_mode_header header;
1362		struct scsi_blk_desc blk_desc;
1363		u_char sense_data[MAX_PAGE_0_SIZE];
1364	} scsi_sense;
1365	struct scsi_link *sc_link = st->sc_link;
1366
1367	scsi_sense_len = 12 + st->page_0_size;
1368
1369	/*
1370	 * Set up a mode sense
1371	 */
1372	bzero(&cmd, sizeof(cmd));
1373	cmd.opcode = MODE_SENSE;
1374	cmd.length = scsi_sense_len;
1375
1376	/*
1377	 * do the command, but we don't need the results
1378	 * just print them for our interest's sake, if asked,
1379	 * or if we need it as a template for the mode select
1380	 * store it away.
1381	 */
1382	error = scsi_scsi_cmd(sc_link, (struct scsi_generic *) &cmd,
1383			      sizeof(cmd), (u_char *) &scsi_sense,
1384			      scsi_sense_len, ST_RETRIES, 5000, NULL,
1385			      flags | SCSI_DATA_IN);
1386	if (error)
1387		return error;
1388
1389	st->numblks = _3btol(scsi_sense.blk_desc.nblocks);
1390	st->media_blksize = _3btol(scsi_sense.blk_desc.blklen);
1391	st->media_density = scsi_sense.blk_desc.density;
1392	if (scsi_sense.header.dev_spec & SMH_DSP_WRITE_PROT)
1393		st->flags |= ST_READONLY;
1394	SC_DEBUG(sc_link, SDEV_DB3,
1395	    ("density code 0x%x, %d-byte blocks, write-%s, ",
1396	    st->media_density, st->media_blksize,
1397	    st->flags & ST_READONLY ? "protected" : "enabled"));
1398	SC_DEBUG(sc_link, SDEV_DB3,
1399	    ("%sbuffered\n",
1400	    scsi_sense.header.dev_spec & SMH_DSP_BUFF_MODE ? "" : "un"));
1401	if (st->page_0_size)
1402		bcopy(scsi_sense.sense_data, st->sense_data, st->page_0_size);
1403	sc_link->flags |= SDEV_MEDIA_LOADED;
1404	return 0;
1405}
1406
1407/*
1408 * Send a filled out parameter structure to the drive to
1409 * set it into the desire modes etc.
1410 */
1411int
1412st_mode_select(st, flags)
1413	struct st_softc *st;
1414	int flags;
1415{
1416	u_int scsi_select_len;
1417	struct scsi_mode_select cmd;
1418	struct scsi_select {
1419		struct scsi_mode_header header;
1420		struct scsi_blk_desc blk_desc;
1421		u_char sense_data[MAX_PAGE_0_SIZE];
1422	} scsi_select;
1423	struct scsi_link *sc_link = st->sc_link;
1424
1425	scsi_select_len = 12 + st->page_0_size;
1426
1427	/*
1428	 * This quirk deals with drives that have only one valid mode
1429	 * and think this gives them license to reject all mode selects,
1430	 * even if the selected mode is the one that is supported.
1431	 */
1432	if (st->quirks & ST_Q_UNIMODAL) {
1433		SC_DEBUG(sc_link, SDEV_DB3,
1434		    ("not setting density 0x%x blksize 0x%x\n",
1435		    st->density, st->blksize));
1436		return 0;
1437	}
1438
1439	/*
1440	 * Set up for a mode select
1441	 */
1442	bzero(&cmd, sizeof(cmd));
1443	cmd.opcode = MODE_SELECT;
1444	cmd.length = scsi_select_len;
1445
1446	bzero(&scsi_select, scsi_select_len);
1447	scsi_select.header.blk_desc_len = sizeof(struct scsi_blk_desc);
1448	scsi_select.header.dev_spec &= ~SMH_DSP_BUFF_MODE;
1449	scsi_select.blk_desc.density = st->density;
1450	if (st->flags & ST_DONTBUFFER)
1451		scsi_select.header.dev_spec |= SMH_DSP_BUFF_MODE_OFF;
1452	else
1453		scsi_select.header.dev_spec |= SMH_DSP_BUFF_MODE_ON;
1454	if (st->flags & ST_FIXEDBLOCKS)
1455		_lto3b(st->blksize, scsi_select.blk_desc.blklen);
1456	if (st->page_0_size)
1457		bcopy(st->sense_data, scsi_select.sense_data, st->page_0_size);
1458
1459	/*
1460	 * do the command
1461	 */
1462	return scsi_scsi_cmd(sc_link, (struct scsi_generic *) &cmd,
1463	    sizeof(cmd), (u_char *) &scsi_select, scsi_select_len,
1464	    ST_RETRIES, 5000, NULL, flags | SCSI_DATA_OUT);
1465}
1466
1467/*
1468 * issue an erase command
1469 */
1470int
1471st_erase(st, full, flags)
1472	struct st_softc *st;
1473	int full, flags;
1474{
1475	struct scsi_erase cmd;
1476
1477	/*
1478	 * Full erase means set LONG bit in erase command, which asks
1479	 * the drive to erase the entire unit.  Without this bit, we're
1480	 * asking the drive to write an erase gap.
1481	 */
1482	bzero(&cmd, sizeof(cmd));
1483	cmd.opcode = ERASE;
1484	if (full)
1485		cmd.byte2 = SE_IMMED|SE_LONG;
1486	else
1487		cmd.byte2 = SE_IMMED;
1488
1489	/*
1490	 * XXX We always do this asynchronously, for now.  How long should
1491	 * we wait if we want to (eventually) to it synchronously?
1492	 */
1493	return (scsi_scsi_cmd(st->sc_link, (struct scsi_generic *)&cmd,
1494	    sizeof(cmd), 0, 0, ST_RETRIES, 5000, NULL, flags));
1495}
1496
1497/*
1498 * skip N blocks/filemarks/seq filemarks/eom
1499 */
1500int
1501st_space(st, number, what, flags)
1502	struct st_softc *st;
1503	u_int what;
1504	int flags;
1505	int number;
1506{
1507	struct scsi_space cmd;
1508	int error;
1509
1510	switch (what) {
1511	case SP_BLKS:
1512		if (st->flags & ST_PER_ACTION) {
1513			if (number > 0) {
1514				st->flags &= ~ST_PER_ACTION;
1515				return EIO;
1516			} else if (number < 0) {
1517				if (st->flags & ST_AT_FILEMARK) {
1518					/*
1519					 * Handling of ST_AT_FILEMARK
1520					 * in st_space will fill in the
1521					 * right file mark count.
1522					 */
1523					error = st_space(st, 0, SP_FILEMARKS,
1524						flags);
1525					if (error)
1526						return error;
1527				}
1528				if (st->flags & ST_BLANK_READ) {
1529					st->flags &= ~ST_BLANK_READ;
1530					return EIO;
1531				}
1532				st->flags &= ~ST_EIO_PENDING;
1533			}
1534		}
1535		break;
1536	case SP_FILEMARKS:
1537		if (st->flags & ST_EIO_PENDING) {
1538			if (number > 0) {
1539				/* pretend we just discovered the error */
1540				st->flags &= ~ST_EIO_PENDING;
1541				return EIO;
1542			} else if (number < 0) {
1543				/* back away from the error */
1544				st->flags &= ~ST_EIO_PENDING;
1545			}
1546		}
1547		if (st->flags & ST_AT_FILEMARK) {
1548			st->flags &= ~ST_AT_FILEMARK;
1549			number--;
1550		}
1551		if ((st->flags & ST_BLANK_READ) && (number < 0)) {
1552			/* back away from unwritten tape */
1553			st->flags &= ~ST_BLANK_READ;
1554			number++;	/* XXX dubious */
1555		}
1556		break;
1557	case SP_EOM:
1558		if (st->flags & ST_EIO_PENDING) {
1559			/* pretend we just discovered the error */
1560			st->flags &= ~ST_EIO_PENDING;
1561			return EIO;
1562		}
1563		if (st->flags & ST_AT_FILEMARK)
1564			st->flags &= ~ST_AT_FILEMARK;
1565		break;
1566	}
1567	if (number == 0)
1568		return 0;
1569
1570	bzero(&cmd, sizeof(cmd));
1571	cmd.opcode = SPACE;
1572	cmd.byte2 = what;
1573	_lto3b(number, cmd.number);
1574
1575	return scsi_scsi_cmd(st->sc_link, (struct scsi_generic *) &cmd,
1576	    sizeof(cmd), 0, 0, 0, 2000000, NULL, flags);
1577}
1578
1579/*
1580 * write N filemarks
1581 */
1582int
1583st_write_filemarks(st, number, flags)
1584	struct st_softc *st;
1585	int flags;
1586	int number;
1587{
1588	struct scsi_write_filemarks cmd;
1589
1590	/*
1591	 * It's hard to write a negative number of file marks.
1592	 * Don't try.
1593	 */
1594	if (number < 0)
1595		return EINVAL;
1596	switch (number) {
1597	case 0:		/* really a command to sync the drive's buffers */
1598		break;
1599	case 1:
1600		if (st->flags & ST_FM_WRITTEN)	/* already have one down */
1601			st->flags &= ~ST_WRITTEN;
1602		else
1603			st->flags |= ST_FM_WRITTEN;
1604		st->flags &= ~ST_PER_ACTION;
1605		break;
1606	default:
1607		st->flags &= ~(ST_PER_ACTION | ST_WRITTEN);
1608	}
1609
1610	bzero(&cmd, sizeof(cmd));
1611	cmd.opcode = WRITE_FILEMARKS;
1612	_lto3b(number, cmd.number);
1613
1614	return scsi_scsi_cmd(st->sc_link, (struct scsi_generic *) &cmd,
1615	    sizeof(cmd), 0, 0, 0, 100000, NULL, flags);
1616}
1617
1618/*
1619 * Make sure the right number of file marks is on tape if the
1620 * tape has been written.  If the position argument is true,
1621 * leave the tape positioned where it was originally.
1622 *
1623 * nmarks returns the number of marks to skip (or, if position
1624 * true, which were skipped) to get back original position.
1625 */
1626int
1627st_check_eod(st, position, nmarks, flags)
1628	struct st_softc *st;
1629	boolean position;
1630	int *nmarks;
1631	int flags;
1632{
1633	int error;
1634
1635	switch (st->flags & (ST_WRITTEN | ST_FM_WRITTEN | ST_2FM_AT_EOD)) {
1636	default:
1637		*nmarks = 0;
1638		return 0;
1639	case ST_WRITTEN:
1640	case ST_WRITTEN | ST_FM_WRITTEN | ST_2FM_AT_EOD:
1641		*nmarks = 1;
1642		break;
1643	case ST_WRITTEN | ST_2FM_AT_EOD:
1644		*nmarks = 2;
1645	}
1646	error = st_write_filemarks(st, *nmarks, flags);
1647	if (position && !error)
1648		error = st_space(st, -*nmarks, SP_FILEMARKS, flags);
1649	return error;
1650}
1651
1652/*
1653 * load/unload/retension
1654 */
1655int
1656st_load(st, type, flags)
1657	struct st_softc *st;
1658	u_int type;
1659	int flags;
1660{
1661	struct scsi_load cmd;
1662
1663	if (type != LD_LOAD) {
1664		int error;
1665		int nmarks;
1666
1667		error = st_check_eod(st, FALSE, &nmarks, flags);
1668		if (error)
1669			return error;
1670	}
1671	if (st->quirks & ST_Q_IGNORE_LOADS)
1672		return 0;
1673
1674	bzero(&cmd, sizeof(cmd));
1675	cmd.opcode = LOAD;
1676	cmd.how = type;
1677
1678	return scsi_scsi_cmd(st->sc_link, (struct scsi_generic *) &cmd,
1679	    sizeof(cmd), 0, 0, ST_RETRIES, 300000, NULL, flags);
1680}
1681
1682/*
1683 *  Rewind the device
1684 */
1685int
1686st_rewind(st, immediate, flags)
1687	struct st_softc *st;
1688	u_int immediate;
1689	int flags;
1690{
1691	struct scsi_rewind cmd;
1692	int error;
1693	int nmarks;
1694
1695	error = st_check_eod(st, FALSE, &nmarks, flags);
1696	if (error)
1697		return error;
1698	st->flags &= ~ST_PER_ACTION;
1699
1700	bzero(&cmd, sizeof(cmd));
1701	cmd.opcode = REWIND;
1702	cmd.byte2 = immediate;
1703
1704	return scsi_scsi_cmd(st->sc_link, (struct scsi_generic *) &cmd,
1705	    sizeof(cmd), 0, 0, ST_RETRIES, immediate ? 5000 : 300000, NULL,
1706	    flags);
1707}
1708
1709/*
1710 * Look at the returned sense and act on the error and detirmine
1711 * The unix error number to pass back... (0 = report no error)
1712 *                            (-1 = continue processing)
1713 */
1714int
1715st_interpret_sense(xs)
1716	struct scsi_xfer *xs;
1717{
1718	struct scsi_link *sc_link = xs->sc_link;
1719	struct scsi_sense_data *sense = &xs->sense;
1720	struct buf *bp = xs->bp;
1721	struct st_softc *st = sc_link->device_softc;
1722	u_int8_t key;
1723	int32_t info;
1724
1725	/*
1726	 * Get the sense fields and work out what code
1727	 */
1728	if (sense->error_code & SSD_ERRCODE_VALID)
1729		info = _4btol(sense->info);
1730	else
1731		info = xs->datalen;	/* bad choice if fixed blocks */
1732	if ((sense->error_code & SSD_ERRCODE) != 0x70)
1733		return -1;	/* let the generic code handle it */
1734	if (st->flags & ST_FIXEDBLOCKS) {
1735		xs->resid = info * st->blksize;
1736		if (sense->flags & SSD_EOM) {
1737			st->flags |= ST_EIO_PENDING;
1738			if (bp)
1739				bp->b_resid = xs->resid;
1740		}
1741		if (sense->flags & SSD_FILEMARK) {
1742			st->flags |= ST_AT_FILEMARK;
1743			if (bp)
1744				bp->b_resid = xs->resid;
1745		}
1746		if (sense->flags & SSD_ILI) {
1747			st->flags |= ST_EIO_PENDING;
1748			if (bp)
1749				bp->b_resid = xs->resid;
1750			if (sense->error_code & SSD_ERRCODE_VALID &&
1751			    (xs->flags & SCSI_SILENT) == 0)
1752				printf("%s: block wrong size, %d blocks residual\n",
1753				    st->sc_dev.dv_xname, info);
1754
1755			/*
1756			 * This quirk code helps the drive read
1757			 * the first tape block, regardless of
1758			 * format.  That is required for these
1759			 * drives to return proper MODE SENSE
1760			 * information.
1761			 */
1762			if ((st->quirks & ST_Q_SENSE_HELP) &&
1763			    !(sc_link->flags & SDEV_MEDIA_LOADED))
1764				st->blksize -= 512;
1765		}
1766		/*
1767		 * If no data was tranfered, do it immediatly
1768		 */
1769		if (xs->resid >= xs->datalen) {
1770			if (st->flags & ST_EIO_PENDING)
1771				return EIO;
1772			if (st->flags & ST_AT_FILEMARK) {
1773				if (bp)
1774					bp->b_resid = xs->resid;
1775				return 0;
1776			}
1777		}
1778	} else {		/* must be variable mode */
1779		xs->resid = xs->datalen;	/* to be sure */
1780		if (sense->flags & SSD_EOM)
1781			return EIO;
1782		if (sense->flags & SSD_FILEMARK) {
1783			if (bp)
1784				bp->b_resid = bp->b_bcount;
1785			return 0;
1786		}
1787		if (sense->flags & SSD_ILI) {
1788			if (info < 0) {
1789				/*
1790				 * the record was bigger than the read
1791				 */
1792				if ((xs->flags & SCSI_SILENT) == 0)
1793					printf("%s: %d-byte record too big\n",
1794					    st->sc_dev.dv_xname,
1795					    xs->datalen - info);
1796				return EIO;
1797			}
1798			xs->resid = info;
1799			if (bp)
1800				bp->b_resid = info;
1801		}
1802	}
1803	key = sense->flags & SSD_KEY;
1804
1805	if (key == 0x8) {
1806		/*
1807		 * This quirk code helps the drive read the
1808		 * first tape block, regardless of format.  That
1809		 * is required for these drives to return proper
1810		 * MODE SENSE information.
1811		 */
1812		if ((st->quirks & ST_Q_SENSE_HELP) &&
1813		    !(sc_link->flags & SDEV_MEDIA_LOADED)) {
1814			/* still starting */
1815			st->blksize -= 512;
1816		} else if (!(st->flags & (ST_2FM_AT_EOD | ST_BLANK_READ))) {
1817			st->flags |= ST_BLANK_READ;
1818			xs->resid = xs->datalen;
1819			if (bp) {
1820				bp->b_resid = xs->resid;
1821				/* return an EOF */
1822			}
1823			return 0;
1824		}
1825	}
1826	return -1;		/* let the default/generic handler handle it */
1827}
1828
1829/*
1830 * The quirk here is that the drive returns some value to st_mode_sense
1831 * incorrectly until the tape has actually passed by the head.
1832 *
1833 * The method is to set the drive to large fixed-block state (user-specified
1834 * density and 1024-byte blocks), then read and rewind to get it to sense the
1835 * tape.  If that doesn't work, try 512-byte fixed blocks.  If that doesn't
1836 * work, as a last resort, try variable- length blocks.  The result will be
1837 * the ability to do an accurate st_mode_sense.
1838 *
1839 * We know we can do a rewind because we just did a load, which implies rewind.
1840 * Rewind seems preferable to space backward if we have a virgin tape.
1841 *
1842 * The rest of the code for this quirk is in ILI processing and BLANK CHECK
1843 * error processing, both part of st_interpret_sense.
1844 */
1845int
1846st_touch_tape(st)
1847	struct st_softc *st;
1848{
1849	char *buf;
1850	int readsize;
1851	int error;
1852
1853	buf = malloc(1024, M_TEMP, M_NOWAIT);
1854	if (!buf)
1855		return ENOMEM;
1856
1857	if ((error = st_mode_sense(st, 0)) != 0)
1858		goto bad;
1859	st->blksize = 1024;
1860	do {
1861		switch (st->blksize) {
1862		case 512:
1863		case 1024:
1864			readsize = st->blksize;
1865			st->flags |= ST_FIXEDBLOCKS;
1866			break;
1867		default:
1868			readsize = 1;
1869			st->flags &= ~ST_FIXEDBLOCKS;
1870		}
1871		if ((error = st_mode_select(st, 0)) != 0)
1872			goto bad;
1873		st_read(st, buf, readsize, SCSI_SILENT);	/* XXX */
1874		if ((error = st_rewind(st, 0, 0)) != 0) {
1875bad:			free(buf, M_TEMP);
1876			return error;
1877		}
1878	} while (readsize != 1 && readsize > st->blksize);
1879
1880	free(buf, M_TEMP);
1881	return 0;
1882}
1883
1884int
1885stdump(dev, blkno, va, size)
1886	dev_t dev;
1887	daddr_t blkno;
1888	caddr_t va;
1889	size_t size;
1890{
1891
1892	/* Not implemented. */
1893	return ENXIO;
1894}
1895