xref: /netbsd-src/sys/dev/scsipi/st.c (revision 23c8222edbfb0f0932d88a8351d3a0cf817dfb9e)
1 /*	$NetBSD: st.c,v 1.173 2004/10/28 07:07:45 yamt Exp $ */
2 
3 /*-
4  * Copyright (c) 1998, 2004 The NetBSD Foundation, Inc.
5  * All rights reserved.
6  *
7  * This code is derived from software contributed to The NetBSD Foundation
8  * by Charles M. Hannum.
9  *
10  * Redistribution and use in source and binary forms, with or without
11  * modification, are permitted provided that the following conditions
12  * are met:
13  * 1. Redistributions of source code must retain the above copyright
14  *    notice, this list of conditions and the following disclaimer.
15  * 2. Redistributions in binary form must reproduce the above copyright
16  *    notice, this list of conditions and the following disclaimer in the
17  *    documentation and/or other materials provided with the distribution.
18  * 3. All advertising materials mentioning features or use of this software
19  *    must display the following acknowledgement:
20  *        This product includes software developed by the NetBSD
21  *        Foundation, Inc. and its contributors.
22  * 4. Neither the name of The NetBSD Foundation nor the names of its
23  *    contributors may be used to endorse or promote products derived
24  *    from this software without specific prior written permission.
25  *
26  * THIS SOFTWARE IS PROVIDED BY THE NETBSD FOUNDATION, INC. AND CONTRIBUTORS
27  * ``AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED
28  * TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
29  * PURPOSE ARE DISCLAIMED.  IN NO EVENT SHALL THE FOUNDATION OR CONTRIBUTORS
30  * BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
31  * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
32  * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
33  * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
34  * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
35  * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
36  * POSSIBILITY OF SUCH DAMAGE.
37  */
38 
39 /*
40  * Originally written by Julian Elischer (julian@tfs.com)
41  * for TRW Financial Systems for use under the MACH(2.5) operating system.
42  *
43  * TRW Financial Systems, in accordance with their agreement with Carnegie
44  * Mellon University, makes this software available to CMU to distribute
45  * or use in any manner that they see fit as long as this message is kept with
46  * the software. For this reason TFS also grants any other persons or
47  * organisations permission to use or modify this software.
48  *
49  * TFS supplies this software to be publicly redistributed
50  * on the understanding that TFS is not responsible for the correct
51  * functioning of this software in any circumstances.
52  *
53  * Ported to run under 386BSD by Julian Elischer (julian@tfs.com) Sept 1992
54  * major changes by Julian Elischer (julian@jules.dialix.oz.au) May 1993
55  *
56  * A lot of rewhacking done by mjacob (mjacob@nas.nasa.gov).
57  */
58 
59 #include <sys/cdefs.h>
60 __KERNEL_RCSID(0, "$NetBSD: st.c,v 1.173 2004/10/28 07:07:45 yamt Exp $");
61 
62 #include "opt_scsi.h"
63 
64 #include <sys/param.h>
65 #include <sys/systm.h>
66 #include <sys/fcntl.h>
67 #include <sys/errno.h>
68 #include <sys/ioctl.h>
69 #include <sys/malloc.h>
70 #include <sys/buf.h>
71 #include <sys/bufq.h>
72 #include <sys/proc.h>
73 #include <sys/user.h>
74 #include <sys/mtio.h>
75 #include <sys/device.h>
76 #include <sys/conf.h>
77 #include <sys/kernel.h>
78 #include <sys/vnode.h>
79 
80 #include <dev/scsipi/scsipi_all.h>
81 #include <dev/scsipi/scsi_all.h>
82 #include <dev/scsipi/scsi_tape.h>
83 #include <dev/scsipi/scsipiconf.h>
84 #include <dev/scsipi/scsipi_base.h>
85 #include <dev/scsipi/stvar.h>
86 
87 /* Defines for device specific stuff */
88 #define DEF_FIXED_BSIZE  512
89 
90 #define STMODE(z)	( minor(z)       & 0x03)
91 #define STDSTY(z)	((minor(z) >> 2) & 0x03)
92 #define STUNIT(z)	((minor(z) >> 4)       )
93 #define STNMINOR	16
94 
95 #define NORMAL_MODE	0
96 #define NOREW_MODE	1
97 #define EJECT_MODE	2
98 #define CTRL_MODE	3
99 
100 #define	FALSE		0
101 #define	TRUE		1
102 
103 #ifndef		ST_MOUNT_DELAY
104 #define		ST_MOUNT_DELAY		0
105 #endif
106 
107 static dev_type_open(stopen);
108 static dev_type_close(stclose);
109 static dev_type_read(stread);
110 static dev_type_write(stwrite);
111 static dev_type_ioctl(stioctl);
112 static dev_type_strategy(ststrategy);
113 static dev_type_dump(stdump);
114 
115 const struct bdevsw st_bdevsw = {
116 	stopen, stclose, ststrategy, stioctl, stdump, nosize, D_TAPE
117 };
118 
119 const struct cdevsw st_cdevsw = {
120 	stopen, stclose, stread, stwrite, stioctl,
121 	nostop, notty, nopoll, nommap, nokqfilter, D_TAPE
122 };
123 
124 /*
125  * Define various devices that we know mis-behave in some way,
126  * and note how they are bad, so we can correct for them
127  */
128 
129 static const struct st_quirk_inquiry_pattern st_quirk_patterns[] = {
130 	{{T_SEQUENTIAL, T_REMOV,
131 	 "        ", "                ", "    "}, {0, 0, {
132 		{ST_Q_FORCE_BLKSIZE, 512, 0},		/* minor 0-3 */
133 		{ST_Q_FORCE_BLKSIZE, 512, QIC_24},	/* minor 4-7 */
134 		{ST_Q_FORCE_BLKSIZE, 0, HALFINCH_1600},	/* minor 8-11 */
135 		{ST_Q_FORCE_BLKSIZE, 0, HALFINCH_6250}	/* minor 12-15 */
136 	}}},
137 	{{T_SEQUENTIAL, T_REMOV,
138 	 "TANDBERG", " TDC 3600       ", ""},     {0, 12, {
139 		{0, 0, 0},				/* minor 0-3 */
140 		{ST_Q_FORCE_BLKSIZE, 0, QIC_525},	/* minor 4-7 */
141 		{0, 0, QIC_150},			/* minor 8-11 */
142 		{0, 0, QIC_120}				/* minor 12-15 */
143 	}}},
144  	{{T_SEQUENTIAL, T_REMOV,
145  	 "TANDBERG", " TDC 3800       ", ""},     {0, 0, {
146 		{ST_Q_FORCE_BLKSIZE, 512, 0},		/* minor 0-3 */
147 		{0, 0, QIC_525},			/* minor 4-7 */
148 		{0, 0, QIC_150},			/* minor 8-11 */
149 		{0, 0, QIC_120}				/* minor 12-15 */
150 	}}},
151 	{{T_SEQUENTIAL, T_REMOV,
152 	  "TANDBERG", " SLR5 4/8GB     ", ""},     {0, 0, {
153 		{ST_Q_FORCE_BLKSIZE, 1024, 0},		/* minor 0-3 */
154 		{0, 0, 0},				/* minor 4-7 */
155 		{0, 0, 0},				/* minor 8-11 */
156 		{0, 0, 0}				/* minor 12-15 */
157 	}}},
158 	/*
159 	 * lacking a manual for the 4200, it's not clear what the
160 	 * specific density codes should be- the device is a 2.5GB
161 	 * capable QIC drive, those density codes aren't readily
162 	 * availabel. The 'default' will just have to do.
163 	 */
164  	{{T_SEQUENTIAL, T_REMOV,
165  	 "TANDBERG", " TDC 4200       ", ""},     {0, 0, {
166 		{ST_Q_FORCE_BLKSIZE, 512, 0},		/* minor 0-3 */
167 		{0, 0, QIC_525},			/* minor 4-7 */
168 		{0, 0, QIC_150},			/* minor 8-11 */
169 		{0, 0, QIC_120}				/* minor 12-15 */
170 	}}},
171 	/*
172 	 * At least -005 and -007 need this.  I'll assume they all do unless I
173 	 * hear otherwise.  - mycroft, 31MAR1994
174 	 */
175 	{{T_SEQUENTIAL, T_REMOV,
176 	 "ARCHIVE ", "VIPER 2525 25462", ""},     {0, 0, {
177 		{ST_Q_SENSE_HELP, 0, 0},		/* minor 0-3 */
178 		{ST_Q_SENSE_HELP, 0, QIC_525},		/* minor 4-7 */
179 		{0, 0, QIC_150},			/* minor 8-11 */
180 		{0, 0, QIC_120}				/* minor 12-15 */
181 	}}},
182 	/*
183 	 * One user reports that this works for his tape drive.  It probably
184 	 * needs more work.  - mycroft, 09APR1994
185 	 */
186 	{{T_SEQUENTIAL, T_REMOV,
187 	 "SANKYO  ", "CP525           ", ""},    {0, 0, {
188 		{ST_Q_FORCE_BLKSIZE, 512, 0},		/* minor 0-3 */
189 		{ST_Q_FORCE_BLKSIZE, 512, QIC_525},	/* minor 4-7 */
190 		{0, 0, QIC_150},			/* minor 8-11 */
191 		{0, 0, QIC_120}				/* minor 12-15 */
192 	}}},
193 	{{T_SEQUENTIAL, T_REMOV,
194 	 "ANRITSU ", "DMT780          ", ""},     {0, 0, {
195 		{ST_Q_FORCE_BLKSIZE, 512, 0},		/* minor 0-3 */
196 		{ST_Q_FORCE_BLKSIZE, 512, QIC_525},	/* minor 4-7 */
197 		{0, 0, QIC_150},			/* minor 8-11 */
198 		{0, 0, QIC_120}				/* minor 12-15 */
199 	}}},
200 	{{T_SEQUENTIAL, T_REMOV,
201 	 "ARCHIVE ", "VIPER 150  21247", ""},     {ST_Q_ERASE_NOIMM, 12, {
202 		{ST_Q_SENSE_HELP, 0, 0},		/* minor 0-3 */
203 		{0, 0, QIC_150},			/* minor 4-7 */
204 		{0, 0, QIC_120},			/* minor 8-11 */
205 		{0, 0, QIC_24}				/* minor 12-15 */
206 	}}},
207 	{{T_SEQUENTIAL, T_REMOV,
208 	 "ARCHIVE ", "VIPER 150  21531", ""},     {ST_Q_ERASE_NOIMM, 12, {
209 		{ST_Q_SENSE_HELP, 0, 0},		/* minor 0-3 */
210 		{0, 0, QIC_150},			/* minor 4-7 */
211 		{0, 0, QIC_120},			/* minor 8-11 */
212 		{0, 0, QIC_24}				/* minor 12-15 */
213 	}}},
214 	{{T_SEQUENTIAL, T_REMOV,
215 	 "WANGTEK ", "5099ES SCSI", ""},          {0, 0, {
216 		{ST_Q_FORCE_BLKSIZE, 512, 0},		/* minor 0-3 */
217 		{0, 0, QIC_11},				/* minor 4-7 */
218 		{0, 0, QIC_24},				/* minor 8-11 */
219 		{0, 0, QIC_24}				/* minor 12-15 */
220 	}}},
221 	{{T_SEQUENTIAL, T_REMOV,
222 	 "WANGTEK ", "5150ES SCSI", ""},          {0, 0, {
223 		{ST_Q_FORCE_BLKSIZE, 512, 0},		/* minor 0-3 */
224 		{0, 0, QIC_24},				/* minor 4-7 */
225 		{0, 0, QIC_120},			/* minor 8-11 */
226 		{0, 0, QIC_150}				/* minor 12-15 */
227 	}}},
228 	{{T_SEQUENTIAL, T_REMOV,
229 	 "WANGTEK ", "5525ES SCSI REV7", ""},     {0, 0, {
230 		{0, 0, 0},				/* minor 0-3 */
231 		{ST_Q_BLKSIZE, 0, QIC_525},		/* minor 4-7 */
232 		{0, 0, QIC_150},			/* minor 8-11 */
233 		{0, 0, QIC_120}				/* minor 12-15 */
234 	}}},
235 	{{T_SEQUENTIAL, T_REMOV,
236 	 "WangDAT ", "Model 1300      ", ""},     {0, 0, {
237 		{0, 0, 0},				/* minor 0-3 */
238 		{ST_Q_FORCE_BLKSIZE, 512, DDS},		/* minor 4-7 */
239 		{ST_Q_FORCE_BLKSIZE, 1024, DDS},	/* minor 8-11 */
240 		{ST_Q_FORCE_BLKSIZE, 0, DDS}		/* minor 12-15 */
241 	}}},
242 	{{T_SEQUENTIAL, T_REMOV,
243 	 "EXABYTE ", "EXB-8200        ", "263H"}, {0, 5, {
244 		{0, 0, 0},				/* minor 0-3 */
245 		{0, 0, 0},				/* minor 4-7 */
246 		{0, 0, 0},				/* minor 8-11 */
247 		{0, 0, 0}				/* minor 12-15 */
248 	}}},
249 	{{T_SEQUENTIAL, T_REMOV,
250 	 "STK",      "9490",             ""},
251 				{ST_Q_FORCE_BLKSIZE, 0, {
252 		{0, 0, 0},				/* minor 0-3 */
253 		{0, 0, 0},				/* minor 4-7 */
254 		{0, 0, 0},				/* minor 8-11 */
255 		{0, 0, 0}				/* minor 12-15 */
256 	}}},
257 	{{T_SEQUENTIAL, T_REMOV,
258 	 "STK",      "SD-3",             ""},
259 				{ST_Q_FORCE_BLKSIZE, 0, {
260 		{0, 0, 0},				/* minor 0-3 */
261 		{0, 0, 0},				/* minor 4-7 */
262 		{0, 0, 0},				/* minor 8-11 */
263 		{0, 0, 0}				/* minor 12-15 */
264 	}}},
265 	{{T_SEQUENTIAL, T_REMOV,
266 	 "IBM",      "03590",            ""},     {ST_Q_IGNORE_LOADS, 0, {
267 		{0, 0, 0},				/* minor 0-3 */
268 		{0, 0, 0},				/* minor 4-7 */
269 		{0, 0, 0},				/* minor 8-11 */
270 		{0, 0, 0}				/* minor 12-15 */
271 	}}},
272 	{{T_SEQUENTIAL, T_REMOV,
273 	 "HP      ", "T4000s          ", ""},     {ST_Q_UNIMODAL, 0, {
274 		{0, 0, QIC_3095},			/* minor 0-3 */
275 		{0, 0, QIC_3095},			/* minor 4-7 */
276 		{0, 0, QIC_3095},			/* minor 8-11 */
277 		{0, 0, QIC_3095},			/* minor 12-15 */
278 	}}},
279 #if 0
280 	{{T_SEQUENTIAL, T_REMOV,
281 	 "EXABYTE ", "EXB-8200        ", ""},     {0, 12, {
282 		{0, 0, 0},				/* minor 0-3 */
283 		{0, 0, 0},				/* minor 4-7 */
284 		{0, 0, 0},				/* minor 8-11 */
285 		{0, 0, 0}				/* minor 12-15 */
286 	}}},
287 #endif
288 	{{T_SEQUENTIAL, T_REMOV,
289 	 "TEAC    ", "MT-2ST/N50      ", ""},     {ST_Q_IGNORE_LOADS, 0, {
290 		{0, 0, 0},			        /* minor 0-3 */
291 		{0, 0, 0},			        /* minor 4-7 */
292 		{0, 0, 0},			        /* minor 8-11 */
293 		{0, 0, 0}			        /* minor 12-15 */
294 	}}},
295 	{{T_SEQUENTIAL, T_REMOV,
296 	 "OnStream", "ADR50 Drive", ""},	  {ST_Q_UNIMODAL, 0, {
297 		{ST_Q_FORCE_BLKSIZE, 512, 0},	        /* minor 0-3 */
298 		{ST_Q_FORCE_BLKSIZE, 512, 0},	        /* minor 4-7 */
299 		{ST_Q_FORCE_BLKSIZE, 512, 0},	        /* minor 8-11 */
300 		{ST_Q_FORCE_BLKSIZE, 512, 0},	        /* minor 12-15 */
301 	}}},
302 	{{T_SEQUENTIAL, T_REMOV,
303 	 "OnStream DI-30",      "",   "1.0"},  {ST_Q_NOFILEMARKS, 0, {
304 		{0, 0, 0},                              /* minor 0-3 */
305 		{0, 0, 0},                              /* minor 4-7 */
306 		{0, 0, 0},                              /* minor 8-11 */
307 		{0, 0, 0}                               /* minor 12-15 */
308 	}}},
309 	{{T_SEQUENTIAL, T_REMOV,
310 	 "NCR H621", "0-STD-03-46F880 ", ""},     {ST_Q_NOPREVENT, 0, {
311 		{0, 0, 0},			       /* minor 0-3 */
312 		{0, 0, 0},			       /* minor 4-7 */
313 		{0, 0, 0},			       /* minor 8-11 */
314 		{0, 0, 0}			       /* minor 12-15 */
315 	}}},
316 };
317 
318 #define NOEJECT 0
319 #define EJECT 1
320 
321 static void	st_identify_drive(struct st_softc *,
322 		    struct scsipi_inquiry_pattern *);
323 static void	st_loadquirks(struct st_softc *);
324 static int	st_mount_tape(dev_t, int);
325 static void	st_unmount(struct st_softc *, boolean);
326 static int	st_decide_mode(struct st_softc *, boolean);
327 static void	ststart(struct scsipi_periph *);
328 static void	strestart(void *);
329 static void	stdone(struct scsipi_xfer *, int);
330 static int	st_read(struct st_softc *, char *, int, int);
331 static int	st_space(struct st_softc *, int, u_int, int);
332 static int	st_write_filemarks(struct st_softc *, int, int);
333 static int	st_check_eod(struct st_softc *, boolean, int *, int);
334 static int	st_load(struct st_softc *, u_int, int);
335 static int	st_rewind(struct st_softc *, u_int, int);
336 static int	st_interpret_sense(struct scsipi_xfer *);
337 static int	st_touch_tape(struct st_softc *);
338 static int	st_erase(struct st_softc *, int full, int flags);
339 static int	st_rdpos(struct st_softc *, int, u_int32_t *);
340 static int	st_setpos(struct st_softc *, int, u_int32_t *);
341 
342 static const struct scsipi_periphsw st_switch = {
343 	st_interpret_sense,
344 	ststart,
345 	NULL,
346 	stdone
347 };
348 
349 #if	defined(ST_ENABLE_EARLYWARN)
350 #define	ST_INIT_FLAGS	ST_EARLYWARN
351 #else
352 #define	ST_INIT_FLAGS	0
353 #endif
354 
355 /*
356  * The routine called by the low level scsi routine when it discovers
357  * A device suitable for this driver
358  */
359 void
360 stattach(struct device *parent, struct st_softc *st, void *aux)
361 {
362 	struct scsipibus_attach_args *sa = aux;
363 	struct scsipi_periph *periph = sa->sa_periph;
364 
365 	SC_DEBUG(periph, SCSIPI_DB2, ("stattach: "));
366 
367 	/*
368 	 * Store information needed to contact our base driver
369 	 */
370 	st->sc_periph = periph;
371 	periph->periph_dev = &st->sc_dev;
372 	periph->periph_switch = &st_switch;
373 
374 	/*
375 	 * Set initial flags
376 	 */
377 
378 	st->flags = ST_INIT_FLAGS;
379 
380 	/*
381 	 * Set up the buf queue for this device
382 	 */
383 	bufq_alloc(&st->buf_queue, BUFQ_FCFS);
384 
385 	callout_init(&st->sc_callout);
386 
387 	/*
388 	 * Check if the drive is a known criminal and take
389 	 * Any steps needed to bring it into line
390 	 */
391 	st_identify_drive(st, &sa->sa_inqbuf);
392 	/*
393 	 * Use the subdriver to request information regarding the drive.
394 	 */
395 	printf("\n");
396 	printf("%s: %s", st->sc_dev.dv_xname, st->quirkdata ? "rogue, " : "");
397 	if (scsipi_test_unit_ready(periph,
398 	    XS_CTL_DISCOVERY | XS_CTL_SILENT | XS_CTL_IGNORE_MEDIA_CHANGE) ||
399 	    st->ops(st, ST_OPS_MODESENSE,
400 	    XS_CTL_DISCOVERY | XS_CTL_SILENT | XS_CTL_IGNORE_MEDIA_CHANGE))
401 		printf("drive empty\n");
402 	else {
403 		printf("density code %d, ", st->media_density);
404 		if (st->media_blksize > 0)
405 			printf("%d-byte", st->media_blksize);
406 		else
407 			printf("variable");
408 		printf(" blocks, write-%s\n",
409 		    (st->flags & ST_READONLY) ? "protected" : "enabled");
410 	}
411 
412 #if NRND > 0
413 	rnd_attach_source(&st->rnd_source, st->sc_dev.dv_xname,
414 			  RND_TYPE_TAPE, 0);
415 #endif
416 }
417 
418 int
419 stactivate(struct device *self, enum devact act)
420 {
421 	int rv = 0;
422 
423 	switch (act) {
424 	case DVACT_ACTIVATE:
425 		rv = EOPNOTSUPP;
426 		break;
427 
428 	case DVACT_DEACTIVATE:
429 		/*
430 		 * Nothing to do; we key off the device's DVF_ACTIVE.
431 		 */
432 		break;
433 	}
434 	return (rv);
435 }
436 
437 int
438 stdetach(struct device *self, int flags)
439 {
440 	struct st_softc *st = (struct st_softc *)self;
441 	struct buf *bp;
442 	int s, bmaj, cmaj, mn;
443 
444 	/* locate the major number */
445 	bmaj = bdevsw_lookup_major(&st_bdevsw);
446 	cmaj = cdevsw_lookup_major(&st_cdevsw);
447 
448 	/* kill any pending restart */
449 	callout_stop(&st->sc_callout);
450 
451 	s = splbio();
452 
453 	/* Kill off any queued buffers. */
454 	while ((bp = BUFQ_GET(&st->buf_queue)) != NULL) {
455 		bp->b_error = EIO;
456 		bp->b_flags |= B_ERROR;
457 		bp->b_resid = bp->b_bcount;
458 		biodone(bp);
459 	}
460 
461 	bufq_free(&st->buf_queue);
462 
463 	/* Kill off any pending commands. */
464 	scsipi_kill_pending(st->sc_periph);
465 
466 	splx(s);
467 
468 	/* Nuke the vnodes for any open instances */
469 	mn = STUNIT(self->dv_unit);
470 	vdevgone(bmaj, mn, mn+STNMINOR-1, VBLK);
471 	vdevgone(cmaj, mn, mn+STNMINOR-1, VCHR);
472 
473 
474 #if NRND > 0
475 	/* Unhook the entropy source. */
476 	rnd_detach_source(&st->rnd_source);
477 #endif
478 
479 	return (0);
480 }
481 
482 /*
483  * Use the inquiry routine in 'scsi_base' to get drive info so we can
484  * Further tailor our behaviour.
485  */
486 static void
487 st_identify_drive(struct st_softc *st, struct scsipi_inquiry_pattern *inqbuf)
488 {
489 	struct st_quirk_inquiry_pattern *finger;
490 	int priority;
491 
492 	finger = (struct st_quirk_inquiry_pattern *)scsipi_inqmatch(inqbuf,
493 	    (caddr_t)st_quirk_patterns,
494 	    sizeof(st_quirk_patterns) / sizeof(st_quirk_patterns[0]),
495 	    sizeof(st_quirk_patterns[0]), &priority);
496 	if (priority != 0) {
497 		st->quirkdata = &finger->quirkdata;
498 		st->drive_quirks = finger->quirkdata.quirks;
499 		st->quirks = finger->quirkdata.quirks;	/* start value */
500 		st->page_0_size = finger->quirkdata.page_0_size;
501 		st_loadquirks(st);
502 	}
503 }
504 
505 /*
506  * initialise the subdevices to the default (QUIRK) state.
507  * this will remove any setting made by the system operator or previous
508  * operations.
509  */
510 static void
511 st_loadquirks(struct st_softc *st)
512 {
513 	int i;
514 	struct	modes *mode;
515 	struct	modes *mode2;
516 
517 	mode = st->quirkdata->modes;
518 	mode2 = st->modes;
519 	for (i = 0; i < 4; i++) {
520 		memset(mode2, 0, sizeof(struct modes));
521 		st->modeflags[i] &= ~(BLKSIZE_SET_BY_QUIRK |
522 		    DENSITY_SET_BY_QUIRK | BLKSIZE_SET_BY_USER |
523 		    DENSITY_SET_BY_USER);
524 		if ((mode->quirks | st->drive_quirks) & ST_Q_FORCE_BLKSIZE) {
525 			mode2->blksize = mode->blksize;
526 			st->modeflags[i] |= BLKSIZE_SET_BY_QUIRK;
527 		}
528 		if (mode->density) {
529 			mode2->density = mode->density;
530 			st->modeflags[i] |= DENSITY_SET_BY_QUIRK;
531 		}
532 		mode2->quirks |= mode->quirks;
533 		mode++;
534 		mode2++;
535 	}
536 }
537 
538 /*
539  * open the device.
540  */
541 static int
542 stopen(dev_t dev, int flags, int mode, struct proc *p)
543 {
544 	u_int stmode, dsty;
545 	int error, sflags, unit, tries, ntries;
546 	struct st_softc *st;
547 	struct scsipi_periph *periph;
548 	struct scsipi_adapter *adapt;
549 
550 	unit = STUNIT(dev);
551 	if (unit >= st_cd.cd_ndevs)
552 		return (ENXIO);
553 	st = st_cd.cd_devs[unit];
554 	if (st == NULL)
555 		return (ENXIO);
556 
557 	stmode = STMODE(dev);
558 	dsty = STDSTY(dev);
559 
560 	periph = st->sc_periph;
561 	adapt = periph->periph_channel->chan_adapter;
562 
563 	SC_DEBUG(periph, SCSIPI_DB1, ("open: dev=0x%x (unit %d (of %d))\n", dev,
564 	    unit, st_cd.cd_ndevs));
565 
566 
567 	/*
568 	 * Only allow one at a time
569 	 */
570 	if (periph->periph_flags & PERIPH_OPEN) {
571 		printf("%s: already open\n", st->sc_dev.dv_xname);
572 		return (EBUSY);
573 	}
574 
575 	if ((error = scsipi_adapter_addref(adapt)) != 0)
576 		return (error);
577 
578 	/*
579 	 * clear any latched errors.
580 	 */
581 	st->mt_resid = 0;
582 	st->mt_erreg = 0;
583 	st->asc = 0;
584 	st->ascq = 0;
585 
586 	/*
587 	 * Catch any unit attention errors. Be silent about this
588 	 * unless we're already mounted. We ignore media change
589 	 * if we're in control mode or not mounted yet.
590 	 */
591 	if ((st->flags & ST_MOUNTED) == 0 || stmode == CTRL_MODE) {
592 #ifdef SCSIDEBUG
593 		sflags = XS_CTL_IGNORE_MEDIA_CHANGE;
594 #else
595 		sflags = XS_CTL_SILENT|XS_CTL_IGNORE_MEDIA_CHANGE;
596 #endif
597 	} else
598 		sflags = 0;
599 
600 	/*
601 	 * If we're already mounted or we aren't configured for
602 	 * a mount delay, only try a test unit ready once. Otherwise,
603 	 * try up to ST_MOUNT_DELAY times with a rest interval of
604 	 * one second between each try.
605 	 */
606 
607 	if ((st->flags & ST_MOUNTED) || ST_MOUNT_DELAY == 0) {
608 		ntries = 1;
609 	} else {
610 		ntries = ST_MOUNT_DELAY;
611 	}
612 
613 	for (error = tries = 0; tries < ntries; tries++) {
614 		int slpintr, oflags;
615 
616 		/*
617 		 * If we had no error, or we're opening the control mode
618 		 * device, we jump out right away.
619 		 */
620 
621 		error = scsipi_test_unit_ready(periph, sflags);
622 		if (error == 0 || stmode == CTRL_MODE) {
623 			break;
624 		}
625 
626 		/*
627 		 * We had an error.
628 		 *
629 		 * If we're already mounted or we aren't configured for
630 		 * a mount delay, or the error isn't a NOT READY error,
631 		 * skip to the error exit now.
632 		 */
633 		if ((st->flags & ST_MOUNTED) || ST_MOUNT_DELAY == 0 ||
634 		    (st->mt_key != SKEY_NOT_READY)) {
635 			goto bad;
636 		}
637 
638 		/*
639 		 * clear any latched errors.
640 		 */
641 		st->mt_resid = 0;
642 		st->mt_erreg = 0;
643 		st->asc = 0;
644 		st->ascq = 0;
645 
646 		/*
647 		 * Fake that we have the device open so
648 		 * we block other apps from getting in.
649 		 */
650 
651 		oflags = periph->periph_flags;
652 		periph->periph_flags |= PERIPH_OPEN;
653 
654 		slpintr = tsleep(&lbolt, PUSER|PCATCH, "stload", 0);
655 
656 		periph->periph_flags = oflags;	/* restore flags */
657 		if (slpintr) {
658 			goto bad;
659 		}
660 	}
661 
662 
663 	/*
664 	 * If the mode is 3 (e.g. minor = 3,7,11,15) then the device has
665 	 * been opened to set defaults and perform other, usually non-I/O
666 	 * related, operations. In this case, do a quick check to see
667 	 * whether the unit actually had a tape loaded (this will be known
668 	 * as to whether or not we got a NOT READY for the above
669 	 * unit attention). If a tape is there, go do a mount sequence.
670 	 */
671 	if (stmode == CTRL_MODE && st->mt_key == SKEY_NOT_READY) {
672 		periph->periph_flags |= PERIPH_OPEN;
673 		return (0);
674 	}
675 
676 	/*
677 	 * If we get this far and had an error set, that means we failed
678 	 * to pass the 'test unit ready' test for the non-controlmode device,
679 	 * so we bounce the open.
680 	 */
681 
682 	if (error)
683 		return (error);
684 
685 	/*
686 	 * Else, we're now committed to saying we're open.
687 	 */
688 
689 	periph->periph_flags |= PERIPH_OPEN; /* unit attn are now errors */
690 
691 	/*
692 	 * If it's a different mode, or if the media has been
693 	 * invalidated, unmount the tape from the previous
694 	 * session but continue with open processing
695 	 */
696 	if (st->last_dsty != dsty ||
697 	    (periph->periph_flags & PERIPH_MEDIA_LOADED) == 0)
698 		st_unmount(st, NOEJECT);
699 
700 	/*
701 	 * If we are not mounted, then we should start a new
702 	 * mount session.
703 	 */
704 	if (!(st->flags & ST_MOUNTED)) {
705 		if ((error = st_mount_tape(dev, flags)) != 0)
706 			goto bad;
707 		st->last_dsty = dsty;
708 	}
709 	if (!(st->quirks & ST_Q_NOPREVENT)) {
710 		scsipi_prevent(periph, PR_PREVENT,
711 		    XS_CTL_IGNORE_ILLEGAL_REQUEST | XS_CTL_IGNORE_NOT_READY);
712 	}
713 
714 	SC_DEBUG(periph, SCSIPI_DB2, ("open complete\n"));
715 	return (0);
716 
717 bad:
718 	st_unmount(st, NOEJECT);
719 	scsipi_adapter_delref(adapt);
720 	periph->periph_flags &= ~PERIPH_OPEN;
721 	return (error);
722 }
723 
724 /*
725  * close the device.. only called if we are the LAST
726  * occurence of an open device
727  */
728 static int
729 stclose(dev_t dev, int flags, int mode, struct proc *p)
730 {
731 	int stxx, error = 0;
732 	struct st_softc *st = st_cd.cd_devs[STUNIT(dev)];
733 	struct scsipi_periph *periph = st->sc_periph;
734 	struct scsipi_adapter *adapt = periph->periph_channel->chan_adapter;
735 
736 	SC_DEBUG(st->sc_periph, SCSIPI_DB1, ("closing\n"));
737 
738 	/*
739 	 * Make sure that a tape opened in write-only mode will have
740 	 * file marks written on it when closed, even if not written to.
741 	 *
742 	 * This is for SUN compatibility. Actually, the Sun way of
743 	 * things is to:
744 	 *
745 	 *	only write filemarks if there are fmks to be written and
746 	 *   		- open for write (possibly read/write)
747 	 *		- the last operation was a write
748 	 * 	or:
749 	 *		- opened for wronly
750 	 *		- no data was written (including filemarks)
751 	 */
752 
753 	stxx = st->flags & (ST_WRITTEN | ST_FM_WRITTEN);
754 	if (((flags & FWRITE) && stxx == ST_WRITTEN) ||
755 	    ((flags & O_ACCMODE) == FWRITE && stxx == 0)) {
756 		int nm;
757 		error = st_check_eod(st, FALSE, &nm, 0);
758 	}
759 
760 	/*
761 	 * Allow robots to eject tape if needed.
762 	 */
763 	scsipi_prevent(periph, PR_ALLOW,
764 	    XS_CTL_IGNORE_ILLEGAL_REQUEST | XS_CTL_IGNORE_NOT_READY);
765 
766 	switch (STMODE(dev)) {
767 	case NORMAL_MODE:
768 		st_unmount(st, NOEJECT);
769 		break;
770 	case NOREW_MODE:
771 	case CTRL_MODE:
772 		/*
773 		 * Leave mounted unless media seems to have been removed.
774 		 *
775 		 * Otherwise, if we're to terminate a tape with more than one
776 		 * filemark [ and because we're not rewinding here ], backspace
777 		 * one filemark so that later appends will see an unbroken
778 		 * sequence of:
779 		 *
780 		 *	file - FMK - file - FMK ... file - FMK FMK (EOM)
781 		 */
782 		if ((periph->periph_flags & PERIPH_MEDIA_LOADED) == 0) {
783 			st_unmount(st, NOEJECT);
784 		} else if (error == 0) {
785 			/*
786 			 * ST_WRITTEN was preserved from above.
787 			 *
788 			 * All we need to know here is:
789 			 *
790 			 *	Were we writing this tape and was the last
791 			 *	operation a write?
792 			 *
793 			 *	Are there supposed to be 2FM at EOD?
794 			 *
795 			 * If both statements are true, then we backspace
796 			 * one filemark.
797 			 */
798 			stxx |= (st->flags & ST_2FM_AT_EOD);
799 			if ((flags & FWRITE) != 0 &&
800 			    (stxx == (ST_2FM_AT_EOD|ST_WRITTEN))) {
801 				error = st_space(st, -1, SP_FILEMARKS, 0);
802 			}
803 		}
804 		break;
805 	case EJECT_MODE:
806 		st_unmount(st, EJECT);
807 		break;
808 	}
809 
810 	scsipi_wait_drain(periph);
811 
812 	scsipi_adapter_delref(adapt);
813 	periph->periph_flags &= ~PERIPH_OPEN;
814 
815 	return (error);
816 }
817 
818 /*
819  * Start a new mount session.
820  * Copy in all the default parameters from the selected device mode.
821  * and try guess any that seem to be defaulted.
822  */
823 static int
824 st_mount_tape(dev_t dev, int flags)
825 {
826 	int unit;
827 	u_int dsty;
828 	struct st_softc *st;
829 	struct scsipi_periph *periph;
830 	int error = 0;
831 
832 	unit = STUNIT(dev);
833 	dsty = STDSTY(dev);
834 	st = st_cd.cd_devs[unit];
835 	periph = st->sc_periph;
836 
837 	if (st->flags & ST_MOUNTED)
838 		return (0);
839 
840 	SC_DEBUG(periph, SCSIPI_DB1, ("mounting\n "));
841 	st->flags |= ST_NEW_MOUNT;
842 	st->quirks = st->drive_quirks | st->modes[dsty].quirks;
843 	/*
844 	 * If the media is new, then make sure we give it a chance to
845 	 * to do a 'load' instruction.  (We assume it is new.)
846 	 */
847 	if ((error = st_load(st, LD_LOAD, XS_CTL_SILENT)) != 0)
848 		return (error);
849 	/*
850 	 * Throw another dummy instruction to catch
851 	 * 'Unit attention' errors. Many drives give
852 	 * these after doing a Load instruction (with
853 	 * the MEDIUM MAY HAVE CHANGED asc/ascq).
854 	 */
855 	scsipi_test_unit_ready(periph, XS_CTL_SILENT);	/* XXX */
856 
857 	/*
858 	 * Some devices can't tell you much until they have been
859 	 * asked to look at the media. This quirk does this.
860 	 */
861 	if (st->quirks & ST_Q_SENSE_HELP)
862 		if ((error = st_touch_tape(st)) != 0)
863 			return (error);
864 	/*
865 	 * Load the physical device parameters
866 	 * loads: blkmin, blkmax
867 	 */
868 	if ((error = st->ops(st, ST_OPS_RBL, 0)) != 0)
869 		return (error);
870 	/*
871 	 * Load the media dependent parameters
872 	 * includes: media_blksize,media_density,numblks
873 	 * As we have a tape in, it should be reflected here.
874 	 * If not you may need the "quirk" above.
875 	 */
876 	if ((error = st->ops(st, ST_OPS_MODESENSE, 0)) != 0)
877 		return (error);
878 	/*
879 	 * If we have gained a permanent density from somewhere,
880 	 * then use it in preference to the one supplied by
881 	 * default by the driver.
882 	 */
883 	if (st->modeflags[dsty] & (DENSITY_SET_BY_QUIRK | DENSITY_SET_BY_USER))
884 		st->density = st->modes[dsty].density;
885 	else
886 		st->density = st->media_density;
887 	/*
888 	 * If we have gained a permanent blocksize
889 	 * then use it in preference to the one supplied by
890 	 * default by the driver.
891 	 */
892 	st->flags &= ~ST_FIXEDBLOCKS;
893 	if (st->modeflags[dsty] &
894 	    (BLKSIZE_SET_BY_QUIRK | BLKSIZE_SET_BY_USER)) {
895 		st->blksize = st->modes[dsty].blksize;
896 		if (st->blksize)
897 			st->flags |= ST_FIXEDBLOCKS;
898 	} else {
899 		if ((error = st_decide_mode(st, FALSE)) != 0)
900 			return (error);
901 	}
902 	if ((error = st->ops(st, ST_OPS_MODESELECT, 0)) != 0) {
903 		/* ATAPI will return ENODEV for this, and this may be OK */
904 		if (error != ENODEV) {
905 			printf("%s: cannot set selected mode\n",
906 			    st->sc_dev.dv_xname);
907 			return (error);
908 		}
909 	}
910 	st->flags &= ~ST_NEW_MOUNT;
911 	st->flags |= ST_MOUNTED;
912 	periph->periph_flags |= PERIPH_MEDIA_LOADED;	/* move earlier? */
913 	st->blkno = st->fileno = (daddr_t) 0;
914 	return (0);
915 }
916 
917 /*
918  * End the present mount session.
919  * Rewind, and optionally eject the tape.
920  * Reset various flags to indicate that all new
921  * operations require another mount operation
922  */
923 static void
924 st_unmount(struct st_softc *st, boolean eject)
925 {
926 	struct scsipi_periph *periph = st->sc_periph;
927 	int nmarks;
928 
929 	if ((st->flags & ST_MOUNTED) == 0)
930 		return;
931 	SC_DEBUG(periph, SCSIPI_DB1, ("unmounting\n"));
932 	st_check_eod(st, FALSE, &nmarks, XS_CTL_IGNORE_NOT_READY);
933 	st_rewind(st, 0, XS_CTL_IGNORE_NOT_READY);
934 
935 	/*
936 	 * Section 9.3.3 of the SCSI specs states that a device shall return
937 	 * the density value specified in the last succesfull MODE SELECT
938 	 * after an unload operation, in case it is not able to
939 	 * automatically determine the density of the new medium.
940 	 *
941 	 * So we instruct the device to use the default density, which will
942 	 * prevent the use of stale density values (in particular,
943 	 * in st_touch_tape().
944 	 */
945 	st->density = 0;
946 	if (st->ops(st, ST_OPS_MODESELECT, 0) != 0) {
947 		printf("%s: WARNING: cannot revert to default density\n",
948 			st->sc_dev.dv_xname);
949 	}
950 
951 	if (eject) {
952 		if (!(st->quirks & ST_Q_NOPREVENT)) {
953 			scsipi_prevent(periph, PR_ALLOW,
954 			    XS_CTL_IGNORE_ILLEGAL_REQUEST |
955 			    XS_CTL_IGNORE_NOT_READY);
956 		}
957 		st_load(st, LD_UNLOAD, XS_CTL_IGNORE_NOT_READY);
958 		st->blkno = st->fileno = (daddr_t) -1;
959 	} else {
960 		st->blkno = st->fileno = (daddr_t) 0;
961 	}
962 	st->flags &= ~(ST_MOUNTED | ST_NEW_MOUNT);
963 	periph->periph_flags &= ~PERIPH_MEDIA_LOADED;
964 }
965 
966 /*
967  * Given all we know about the device, media, mode, 'quirks' and
968  * initial operation, make a decision as to how we should be set
969  * to run (regarding blocking and EOD marks)
970  */
971 int
972 st_decide_mode(struct st_softc *st, boolean first_read)
973 {
974 
975 	SC_DEBUG(st->sc_periph, SCSIPI_DB2, ("starting block mode decision\n"));
976 
977 	/*
978 	 * If the drive can only handle fixed-length blocks and only at
979 	 * one size, perhaps we should just do that.
980 	 */
981 	if (st->blkmin && (st->blkmin == st->blkmax)) {
982 		st->flags |= ST_FIXEDBLOCKS;
983 		st->blksize = st->blkmin;
984 		SC_DEBUG(st->sc_periph, SCSIPI_DB3,
985 		    ("blkmin == blkmax of %d\n", st->blkmin));
986 		goto done;
987 	}
988 	/*
989 	 * If the tape density mandates (or even suggests) use of fixed
990 	 * or variable-length blocks, comply.
991 	 */
992 	switch (st->density) {
993 	case HALFINCH_800:
994 	case HALFINCH_1600:
995 	case HALFINCH_6250:
996 	case DDS:
997 		st->flags &= ~ST_FIXEDBLOCKS;
998 		st->blksize = 0;
999 		SC_DEBUG(st->sc_periph, SCSIPI_DB3,
1000 		    ("density specified variable\n"));
1001 		goto done;
1002 	case QIC_11:
1003 	case QIC_24:
1004 	case QIC_120:
1005 	case QIC_150:
1006 	case QIC_525:
1007 	case QIC_1320:
1008 	case QIC_3095:
1009 	case QIC_3220:
1010 		st->flags |= ST_FIXEDBLOCKS;
1011 		if (st->media_blksize > 0)
1012 			st->blksize = st->media_blksize;
1013 		else
1014 			st->blksize = DEF_FIXED_BSIZE;
1015 		SC_DEBUG(st->sc_periph, SCSIPI_DB3,
1016 		    ("density specified fixed\n"));
1017 		goto done;
1018 	}
1019 	/*
1020 	 * If we're about to read the tape, perhaps we should choose
1021 	 * fixed or variable-length blocks and block size according to
1022 	 * what the drive found on the tape.
1023 	 */
1024 	if (first_read &&
1025 	    (!(st->quirks & ST_Q_BLKSIZE) || (st->media_blksize == 0) ||
1026 	    (st->media_blksize == DEF_FIXED_BSIZE) ||
1027 	    (st->media_blksize == 1024))) {
1028 		if (st->media_blksize > 0)
1029 			st->flags |= ST_FIXEDBLOCKS;
1030 		else
1031 			st->flags &= ~ST_FIXEDBLOCKS;
1032 		st->blksize = st->media_blksize;
1033 		SC_DEBUG(st->sc_periph, SCSIPI_DB3,
1034 		    ("Used media_blksize of %d\n", st->media_blksize));
1035 		goto done;
1036 	}
1037 	/*
1038 	 * We're getting no hints from any direction.  Choose variable-
1039 	 * length blocks arbitrarily.
1040 	 */
1041 	st->flags &= ~ST_FIXEDBLOCKS;
1042 	st->blksize = 0;
1043 	SC_DEBUG(st->sc_periph, SCSIPI_DB3,
1044 	    ("Give up and default to variable mode\n"));
1045 
1046 done:
1047 	/*
1048 	 * Decide whether or not to write two file marks to signify end-
1049 	 * of-data.  Make the decision as a function of density.  If
1050 	 * the decision is not to use a second file mark, the SCSI BLANK
1051 	 * CHECK condition code will be recognized as end-of-data when
1052 	 * first read.
1053 	 * (I think this should be a by-product of fixed/variable..julian)
1054 	 */
1055 	switch (st->density) {
1056 /*      case 8 mm:   What is the SCSI density code for 8 mm, anyway? */
1057 	case QIC_11:
1058 	case QIC_24:
1059 	case QIC_120:
1060 	case QIC_150:
1061 	case QIC_525:
1062 	case QIC_1320:
1063 	case QIC_3095:
1064 	case QIC_3220:
1065 		st->flags &= ~ST_2FM_AT_EOD;
1066 		break;
1067 	default:
1068 		st->flags |= ST_2FM_AT_EOD;
1069 	}
1070 	return (0);
1071 }
1072 
1073 /*
1074  * Actually translate the requested transfer into
1075  * one the physical driver can understand
1076  * The transfer is described by a buf and will include
1077  * only one physical transfer.
1078  */
1079 static void
1080 ststrategy(struct buf *bp)
1081 {
1082 	struct st_softc *st = st_cd.cd_devs[STUNIT(bp->b_dev)];
1083 	int s;
1084 
1085 	SC_DEBUG(st->sc_periph, SCSIPI_DB1,
1086 	    ("ststrategy %d bytes @ blk %" PRId64 "\n", bp->b_bcount, bp->b_blkno));
1087 	/*
1088 	 * If it's a null transfer, return immediatly
1089 	 */
1090 	if (bp->b_bcount == 0)
1091 		goto done;
1092 
1093 	/* If offset is negative, error */
1094 	if (bp->b_blkno < 0) {
1095 		bp->b_error = EINVAL;
1096 		goto bad;
1097 	}
1098 
1099 	/*
1100 	 * Odd sized request on fixed drives are verboten
1101 	 */
1102 	if (st->flags & ST_FIXEDBLOCKS) {
1103 		if (bp->b_bcount % st->blksize) {
1104 			printf("%s: bad request, must be multiple of %d\n",
1105 			    st->sc_dev.dv_xname, st->blksize);
1106 			bp->b_error = EIO;
1107 			goto bad;
1108 		}
1109 	}
1110 	/*
1111 	 * as are out-of-range requests on variable drives.
1112 	 */
1113 	else if (bp->b_bcount < st->blkmin ||
1114 	    (st->blkmax && bp->b_bcount > st->blkmax)) {
1115 		printf("%s: bad request, must be between %d and %d\n",
1116 		    st->sc_dev.dv_xname, st->blkmin, st->blkmax);
1117 		bp->b_error = EIO;
1118 		goto bad;
1119 	}
1120 	s = splbio();
1121 
1122 	/*
1123 	 * Place it in the queue of activities for this tape
1124 	 * at the end (a bit silly because we only have on user..
1125 	 * (but it could fork()))
1126 	 */
1127 	BUFQ_PUT(&st->buf_queue, bp);
1128 
1129 	/*
1130 	 * Tell the device to get going on the transfer if it's
1131 	 * not doing anything, otherwise just wait for completion
1132 	 * (All a bit silly if we're only allowing 1 open but..)
1133 	 */
1134 	ststart(st->sc_periph);
1135 
1136 	splx(s);
1137 	return;
1138 bad:
1139 	bp->b_flags |= B_ERROR;
1140 done:
1141 	/*
1142 	 * Correctly set the buf to indicate a completed xfer
1143 	 */
1144 	bp->b_resid = bp->b_bcount;
1145 	biodone(bp);
1146 	return;
1147 }
1148 
1149 /*
1150  * ststart looks to see if there is a buf waiting for the device
1151  * and that the device is not already busy. If both are true,
1152  * It dequeues the buf and creates a scsi command to perform the
1153  * transfer required. The transfer request will call scsipi_done
1154  * on completion, which will in turn call this routine again
1155  * so that the next queued transfer is performed.
1156  * The bufs are queued by the strategy routine (ststrategy)
1157  *
1158  * This routine is also called after other non-queued requests
1159  * have been made of the scsi driver, to ensure that the queue
1160  * continues to be drained.
1161  * ststart() is called at splbio
1162  */
1163 static void
1164 ststart(struct scsipi_periph *periph)
1165 {
1166 	struct st_softc *st = (void *)periph->periph_dev;
1167 	struct buf *bp;
1168 	struct scsi_rw_tape cmd;
1169 	struct scsipi_xfer *xs;
1170 	int flags, error;
1171 
1172 	SC_DEBUG(periph, SCSIPI_DB2, ("ststart "));
1173 	/*
1174 	 * See if there is a buf to do and we are not already
1175 	 * doing one
1176 	 */
1177 	while (periph->periph_active < periph->periph_openings) {
1178 		/* if a special awaits, let it proceed first */
1179 		if (periph->periph_flags & PERIPH_WAITING) {
1180 			periph->periph_flags &= ~PERIPH_WAITING;
1181 			wakeup((caddr_t)periph);
1182 			return;
1183 		}
1184 
1185 		/*
1186 		 * If the device has been unmounted by the user
1187 		 * then throw away all requests until done.
1188 		 */
1189 		if (__predict_false((st->flags & ST_MOUNTED) == 0 ||
1190 		    (periph->periph_flags & PERIPH_MEDIA_LOADED) == 0)) {
1191 			if ((bp = BUFQ_GET(&st->buf_queue)) != NULL) {
1192 				/* make sure that one implies the other.. */
1193 				periph->periph_flags &= ~PERIPH_MEDIA_LOADED;
1194 				bp->b_flags |= B_ERROR;
1195 				bp->b_error = EIO;
1196 				bp->b_resid = bp->b_bcount;
1197 				biodone(bp);
1198 				continue;
1199 			} else {
1200 				return;
1201 			}
1202 		}
1203 
1204 		if ((bp = BUFQ_PEEK(&st->buf_queue)) == NULL)
1205 			return;
1206 
1207 		/*
1208 		 * only FIXEDBLOCK devices have pending I/O or space operations.
1209 		 */
1210 		if (st->flags & ST_FIXEDBLOCKS) {
1211 			/*
1212 			 * If we are at a filemark but have not reported it yet
1213 			 * then we should report it now
1214 			 */
1215 			if (st->flags & ST_AT_FILEMARK) {
1216 				if ((bp->b_flags & B_READ) == B_WRITE) {
1217 					/*
1218 					 * Handling of ST_AT_FILEMARK in
1219 					 * st_space will fill in the right file
1220 					 * mark count.
1221 					 * Back up over filemark
1222 					 */
1223 					if (st_space(st, 0, SP_FILEMARKS, 0)) {
1224 						BUFQ_GET(&st->buf_queue);
1225 						bp->b_flags |= B_ERROR;
1226 						bp->b_error = EIO;
1227 						biodone(bp);
1228 						continue;
1229 					}
1230 				} else {
1231 					BUFQ_GET(&st->buf_queue);
1232 					bp->b_resid = bp->b_bcount;
1233 					bp->b_error = 0;
1234 					bp->b_flags &= ~B_ERROR;
1235 					st->flags &= ~ST_AT_FILEMARK;
1236 					biodone(bp);
1237 					continue;	/* seek more work */
1238 				}
1239 			}
1240 		}
1241 		/*
1242 		 * If we are at EOM but have not reported it
1243 		 * yet then we should report it now.
1244 		 */
1245 		if (st->flags & (ST_EOM_PENDING|ST_EIO_PENDING)) {
1246 			BUFQ_GET(&st->buf_queue);
1247 			bp->b_resid = bp->b_bcount;
1248 			if (st->flags & ST_EIO_PENDING) {
1249 				bp->b_error = EIO;
1250 				bp->b_flags |= B_ERROR;
1251 			}
1252 			st->flags &= ~(ST_EOM_PENDING|ST_EIO_PENDING);
1253 			biodone(bp);
1254 			continue;	/* seek more work */
1255 		}
1256 
1257 		/*
1258 		 * Fill out the scsi command
1259 		 */
1260 		memset(&cmd, 0, sizeof(cmd));
1261 		flags = XS_CTL_NOSLEEP | XS_CTL_ASYNC;
1262 		if ((bp->b_flags & B_READ) == B_WRITE) {
1263 			cmd.opcode = WRITE;
1264 			st->flags &= ~ST_FM_WRITTEN;
1265 			flags |= XS_CTL_DATA_OUT;
1266 		} else {
1267 			cmd.opcode = READ;
1268 			flags |= XS_CTL_DATA_IN;
1269 		}
1270 
1271 		/*
1272 		 * Handle "fixed-block-mode" tape drives by using the
1273 		 * block count instead of the length.
1274 		 */
1275 		if (st->flags & ST_FIXEDBLOCKS) {
1276 			cmd.byte2 |= SRW_FIXED;
1277 			_lto3b(bp->b_bcount / st->blksize, cmd.len);
1278 		} else
1279 			_lto3b(bp->b_bcount, cmd.len);
1280 
1281 		/*
1282 		 * Clear 'position updated' indicator
1283 		 */
1284 		st->flags &= ~ST_POSUPDATED;
1285 
1286 		/*
1287 		 * go ask the adapter to do all this for us
1288 		 */
1289 		xs = scsipi_make_xs(periph,
1290 		    (struct scsipi_generic *)&cmd, sizeof(cmd),
1291 		    (u_char *)bp->b_data, bp->b_bcount,
1292 		    0, ST_IO_TIME, bp, flags);
1293 		if (__predict_false(xs == NULL)) {
1294 			/*
1295 			 * out of memory. Keep this buffer in the queue, and
1296 			 * retry later.
1297 			 */
1298 			callout_reset(&st->sc_callout, hz / 2, strestart,
1299 			    periph);
1300 			return;
1301 		}
1302 		/*
1303 		 * need to dequeue the buffer before queuing the command,
1304 		 * because cdstart may be called recursively from the
1305 		 * HBA driver
1306 		 */
1307 #ifdef DIAGNOSTIC
1308 		if (BUFQ_GET(&st->buf_queue) != bp)
1309 			panic("ststart(): dequeued wrong buf");
1310 #else
1311 		BUFQ_GET(&st->buf_queue);
1312 #endif
1313 		error = scsipi_execute_xs(xs);
1314 		/* with a scsipi_xfer preallocated, scsipi_command can't fail */
1315 		KASSERT(error == 0);
1316 	} /* go back and see if we can cram more work in.. */
1317 }
1318 
1319 static void
1320 strestart(void *v)
1321 {
1322 	int s = splbio();
1323 	ststart((struct scsipi_periph *)v);
1324 	splx(s);
1325 }
1326 
1327 
1328 static void
1329 stdone(struct scsipi_xfer *xs, int error)
1330 {
1331 	struct st_softc *st = (void *)xs->xs_periph->periph_dev;
1332 	struct buf *bp = xs->bp;
1333 
1334 	if (bp) {
1335 		bp->b_error = error;
1336 		bp->b_resid = xs->resid;
1337 		if (error)
1338 			bp->b_flags |= B_ERROR;
1339 
1340 		if ((bp->b_flags & B_READ) == B_WRITE)
1341 			st->flags |= ST_WRITTEN;
1342 		else
1343 			st->flags &= ~ST_WRITTEN;
1344 #if NRND > 0
1345 		rnd_add_uint32(&st->rnd_source, bp->b_blkno);
1346 #endif
1347 
1348 		if ((st->flags & ST_POSUPDATED) == 0) {
1349 			if (error) {
1350 				st->fileno = st->blkno = -1;
1351 			} else if (st->blkno != -1) {
1352 				if (st->flags & ST_FIXEDBLOCKS)
1353 					st->blkno +=
1354 					    (bp->b_bcount / st->blksize);
1355 				else
1356 					st->blkno++;
1357 			}
1358 		}
1359 
1360 		biodone(bp);
1361 	}
1362 }
1363 
1364 static int
1365 stread(dev_t dev, struct uio *uio, int iomode)
1366 {
1367 	struct st_softc *st = st_cd.cd_devs[STUNIT(dev)];
1368 
1369 	return (physio(ststrategy, NULL, dev, B_READ,
1370 	    st->sc_periph->periph_channel->chan_adapter->adapt_minphys, uio));
1371 }
1372 
1373 static int
1374 stwrite(dev_t dev, struct uio *uio, int iomode)
1375 {
1376 	struct st_softc *st = st_cd.cd_devs[STUNIT(dev)];
1377 
1378 	return (physio(ststrategy, NULL, dev, B_WRITE,
1379 	    st->sc_periph->periph_channel->chan_adapter->adapt_minphys, uio));
1380 }
1381 
1382 /*
1383  * Perform special action on behalf of the user;
1384  * knows about the internals of this device
1385  */
1386 static int
1387 stioctl(dev_t dev, u_long cmd, caddr_t arg, int flag, struct proc *p)
1388 {
1389 	int error = 0;
1390 	int unit;
1391 	int number, nmarks, dsty;
1392 	int flags;
1393 	struct st_softc *st;
1394 	int hold_blksize;
1395 	u_int8_t hold_density;
1396 	struct mtop *mt = (struct mtop *) arg;
1397 
1398 	/*
1399 	 * Find the device that the user is talking about
1400 	 */
1401 	flags = 0;		/* give error messages, act on errors etc. */
1402 	unit = STUNIT(dev);
1403 	dsty = STDSTY(dev);
1404 	st = st_cd.cd_devs[unit];
1405 	hold_blksize = st->blksize;
1406 	hold_density = st->density;
1407 
1408 	switch ((u_int) cmd) {
1409 
1410 	case MTIOCGET: {
1411 		struct mtget *g = (struct mtget *) arg;
1412 		/*
1413 		 * (to get the current state of READONLY)
1414 		 */
1415 		error = st->ops(st, ST_OPS_MODESENSE, XS_CTL_SILENT);
1416 		if (error) {
1417 			/*
1418 			 * Ignore the error if in control mode;
1419 			 * this is mandated by st(4).
1420 			 */
1421 			if (STMODE(dev) != CTRL_MODE)
1422 				break;
1423 			error = 0;
1424 		}
1425 		SC_DEBUG(st->sc_periph, SCSIPI_DB1, ("[ioctl: get status]\n"));
1426 		memset(g, 0, sizeof(struct mtget));
1427 		g->mt_type = 0x7;	/* Ultrix compat *//*? */
1428 		g->mt_blksiz = st->blksize;
1429 		g->mt_density = st->density;
1430 		g->mt_mblksiz[0] = st->modes[0].blksize;
1431 		g->mt_mblksiz[1] = st->modes[1].blksize;
1432 		g->mt_mblksiz[2] = st->modes[2].blksize;
1433 		g->mt_mblksiz[3] = st->modes[3].blksize;
1434 		g->mt_mdensity[0] = st->modes[0].density;
1435 		g->mt_mdensity[1] = st->modes[1].density;
1436 		g->mt_mdensity[2] = st->modes[2].density;
1437 		g->mt_mdensity[3] = st->modes[3].density;
1438 		g->mt_fileno = st->fileno;
1439 		g->mt_blkno = st->blkno;
1440 		if (st->flags & ST_READONLY)
1441 			g->mt_dsreg |= MT_DS_RDONLY;
1442 		if (st->flags & ST_MOUNTED)
1443 			g->mt_dsreg |= MT_DS_MOUNTED;
1444 		g->mt_resid = st->mt_resid;
1445 		g->mt_erreg = st->mt_erreg;
1446 		/*
1447 		 * clear latched errors.
1448 		 */
1449 		st->mt_resid = 0;
1450 		st->mt_erreg = 0;
1451 		st->asc = 0;
1452 		st->ascq = 0;
1453 		break;
1454 	}
1455 	case MTIOCTOP: {
1456 
1457 		SC_DEBUG(st->sc_periph, SCSIPI_DB1,
1458 		    ("[ioctl: op=0x%x count=0x%x]\n", mt->mt_op,
1459 			mt->mt_count));
1460 
1461 		/* compat: in U*x it is a short */
1462 		number = mt->mt_count;
1463 		switch ((short) (mt->mt_op)) {
1464 		case MTWEOF:	/* write an end-of-file record */
1465 			error = st_write_filemarks(st, number, flags);
1466 			break;
1467 		case MTBSF:	/* backward space file */
1468 			number = -number;
1469 		case MTFSF:	/* forward space file */
1470 			error = st_check_eod(st, FALSE, &nmarks, flags);
1471 			if (!error)
1472 				error = st_space(st, number - nmarks,
1473 				    SP_FILEMARKS, flags);
1474 			break;
1475 		case MTBSR:	/* backward space record */
1476 			number = -number;
1477 		case MTFSR:	/* forward space record */
1478 			error = st_check_eod(st, TRUE, &nmarks, flags);
1479 			if (!error)
1480 				error = st_space(st, number, SP_BLKS, flags);
1481 			break;
1482 		case MTREW:	/* rewind */
1483 			error = st_rewind(st, 0, flags);
1484 			break;
1485 		case MTOFFL:	/* rewind and put the drive offline */
1486 			st_unmount(st, EJECT);
1487 			break;
1488 		case MTNOP:	/* no operation, sets status only */
1489 			break;
1490 		case MTRETEN:	/* retension the tape */
1491 			error = st_load(st, LD_RETENSION, flags);
1492 			if (!error)
1493 				error = st_load(st, LD_LOAD, flags);
1494 			break;
1495 		case MTEOM:	/* forward space to end of media */
1496 			error = st_check_eod(st, FALSE, &nmarks, flags);
1497 			if (!error)
1498 				error = st_space(st, 1, SP_EOM, flags);
1499 			break;
1500 		case MTCACHE:	/* enable controller cache */
1501 			st->flags &= ~ST_DONTBUFFER;
1502 			goto try_new_value;
1503 		case MTNOCACHE:	/* disable controller cache */
1504 			st->flags |= ST_DONTBUFFER;
1505 			goto try_new_value;
1506 		case MTERASE:	/* erase volume */
1507 			error = st_erase(st, number, flags);
1508 			break;
1509 		case MTSETBSIZ:	/* Set block size for device */
1510 #ifdef	NOTYET
1511 			if (!(st->flags & ST_NEW_MOUNT)) {
1512 				uprintf("re-mount tape before changing blocksize");
1513 				error = EINVAL;
1514 				break;
1515 			}
1516 #endif
1517 			if (number == 0)
1518 				st->flags &= ~ST_FIXEDBLOCKS;
1519 			else {
1520 				if ((st->blkmin || st->blkmax) &&
1521 				    (number < st->blkmin ||
1522 				    number > st->blkmax)) {
1523 					error = EINVAL;
1524 					break;
1525 				}
1526 				st->flags |= ST_FIXEDBLOCKS;
1527 			}
1528 			st->blksize = number;
1529 			st->flags |= ST_BLOCK_SET;	/*XXX */
1530 			goto try_new_value;
1531 
1532 		case MTSETDNSTY:	/* Set density for device and mode */
1533 			/*
1534 			 * Any number >= 0 and <= 0xff is legal. Numbers
1535 			 * above 0x80 are 'vendor unique'.
1536 			 */
1537 			if (number < 0 || number > 255) {
1538 				error = EINVAL;
1539 				break;
1540 			} else
1541 				st->density = number;
1542 			goto try_new_value;
1543 
1544 		case MTCMPRESS:
1545 			error = st->ops(st, (number == 0) ?
1546 			    ST_OPS_CMPRSS_OFF : ST_OPS_CMPRSS_ON,
1547 			    XS_CTL_SILENT);
1548 			break;
1549 
1550 		case MTEWARN:
1551 			if (number)
1552 				st->flags |= ST_EARLYWARN;
1553 			else
1554 				st->flags &= ~ST_EARLYWARN;
1555 			break;
1556 
1557 		default:
1558 			error = EINVAL;
1559 		}
1560 		break;
1561 	}
1562 	case MTIOCIEOT:
1563 	case MTIOCEEOT:
1564 		break;
1565 
1566 	case MTIOCRDSPOS:
1567 		error = st_rdpos(st, 0, (u_int32_t *) arg);
1568 		break;
1569 
1570 	case MTIOCRDHPOS:
1571 		error = st_rdpos(st, 1, (u_int32_t *) arg);
1572 		break;
1573 
1574 	case MTIOCSLOCATE:
1575 		error = st_setpos(st, 0, (u_int32_t *) arg);
1576 		break;
1577 
1578 	case MTIOCHLOCATE:
1579 		error = st_setpos(st, 1, (u_int32_t *) arg);
1580 		break;
1581 
1582 
1583 	default:
1584 		error = scsipi_do_ioctl(st->sc_periph, dev, cmd, arg,
1585 					flag, p);
1586 		break;
1587 	}
1588 	return (error);
1589 /*-----------------------------*/
1590 try_new_value:
1591 	/*
1592 	 * Check that the mode being asked for is aggreeable to the
1593 	 * drive. If not, put it back the way it was.
1594 	 *
1595 	 * If in control mode, we can make (persistent) mode changes
1596 	 * even if no medium is loaded (see st(4)).
1597 	 */
1598 	if ((STMODE(dev) != CTRL_MODE || (st->flags & ST_MOUNTED) != 0) &&
1599 	    (error = st->ops(st, ST_OPS_MODESELECT, 0)) != 0) {
1600 		/* put it back as it was */
1601 		printf("%s: cannot set selected mode\n", st->sc_dev.dv_xname);
1602 		st->density = hold_density;
1603 		st->blksize = hold_blksize;
1604 		if (st->blksize)
1605 			st->flags |= ST_FIXEDBLOCKS;
1606 		else
1607 			st->flags &= ~ST_FIXEDBLOCKS;
1608 		return (error);
1609 	}
1610 	/*
1611 	 * As the drive liked it, if we are setting a new default,
1612 	 * set it into the structures as such.
1613 	 *
1614 	 * The means for deciding this are not finalised yet- but
1615 	 * if the device was opened in Control Mode, the values
1616 	 * are persistent now across mounts.
1617 	 */
1618 	if (STMODE(dev) == CTRL_MODE) {
1619 		switch ((short) (mt->mt_op)) {
1620 		case MTSETBSIZ:
1621 			st->modes[dsty].blksize = st->blksize;
1622 			st->modeflags[dsty] |= BLKSIZE_SET_BY_USER;
1623 			break;
1624 		case MTSETDNSTY:
1625 			st->modes[dsty].density = st->density;
1626 			st->modeflags[dsty] |= DENSITY_SET_BY_USER;
1627 			break;
1628 		}
1629 	}
1630 	return (0);
1631 }
1632 
1633 /*
1634  * Do a synchronous read.
1635  */
1636 static int
1637 st_read(struct st_softc *st, char *buf, int size, int flags)
1638 {
1639 	struct scsi_rw_tape cmd;
1640 
1641 	/*
1642 	 * If it's a null transfer, return immediatly
1643 	 */
1644 	if (size == 0)
1645 		return (0);
1646 	memset(&cmd, 0, sizeof(cmd));
1647 	cmd.opcode = READ;
1648 	if (st->flags & ST_FIXEDBLOCKS) {
1649 		cmd.byte2 |= SRW_FIXED;
1650 		_lto3b(size / (st->blksize ? st->blksize : DEF_FIXED_BSIZE),
1651 		    cmd.len);
1652 	} else
1653 		_lto3b(size, cmd.len);
1654 	return (scsipi_command(st->sc_periph,
1655 	    (void *)&cmd, sizeof(cmd), (void *)buf, size, 0, ST_IO_TIME, NULL,
1656 	    flags | XS_CTL_DATA_IN));
1657 }
1658 
1659 /*
1660  * issue an erase command
1661  */
1662 static int
1663 st_erase(struct st_softc *st, int full, int flags)
1664 {
1665 	int tmo;
1666 	struct scsi_erase cmd;
1667 
1668 	/*
1669 	 * Full erase means set LONG bit in erase command, which asks
1670 	 * the drive to erase the entire unit.  Without this bit, we're
1671 	 * asking the drive to write an erase gap.
1672 	 */
1673 	memset(&cmd, 0, sizeof(cmd));
1674 	cmd.opcode = ERASE;
1675 	if (full) {
1676 		cmd.byte2 = SE_LONG;
1677 		tmo = ST_SPC_TIME;
1678 	} else {
1679 		tmo = ST_IO_TIME;
1680 	}
1681 
1682 	/*
1683 	 * XXX We always do this asynchronously, for now, unless the device
1684 	 * has the ST_Q_ERASE_NOIMM quirk.  How long should we wait if we
1685 	 * want to (eventually) to it synchronously?
1686 	 */
1687 	if ((st->quirks & ST_Q_ERASE_NOIMM) == 0)
1688 		cmd.byte2 |= SE_IMMED;
1689 
1690 	return (scsipi_command(st->sc_periph, (void *)&cmd, sizeof(cmd), 0, 0,
1691 	    ST_RETRIES, tmo, NULL, flags));
1692 }
1693 
1694 /*
1695  * skip N blocks/filemarks/seq filemarks/eom
1696  */
1697 static int
1698 st_space(struct st_softc *st, int number, u_int what, int flags)
1699 {
1700 	struct scsi_space cmd;
1701 	int error;
1702 
1703 	switch (what) {
1704 	case SP_BLKS:
1705 		if (st->flags & ST_PER_ACTION) {
1706 			if (number > 0) {
1707 				st->flags &= ~ST_PER_ACTION;
1708 				return (EIO);
1709 			} else if (number < 0) {
1710 				if (st->flags & ST_AT_FILEMARK) {
1711 					/*
1712 					 * Handling of ST_AT_FILEMARK
1713 					 * in st_space will fill in the
1714 					 * right file mark count.
1715 					 */
1716 					error = st_space(st, 0, SP_FILEMARKS,
1717 					    flags);
1718 					if (error)
1719 						return (error);
1720 				}
1721 				if (st->flags & ST_BLANK_READ) {
1722 					st->flags &= ~ST_BLANK_READ;
1723 					return (EIO);
1724 				}
1725 				st->flags &= ~(ST_EIO_PENDING|ST_EOM_PENDING);
1726 			}
1727 		}
1728 		break;
1729 	case SP_FILEMARKS:
1730 		if (st->flags & ST_EIO_PENDING) {
1731 			if (number > 0) {
1732 				/* pretend we just discovered the error */
1733 				st->flags &= ~ST_EIO_PENDING;
1734 				return (EIO);
1735 			} else if (number < 0) {
1736 				/* back away from the error */
1737 				st->flags &= ~ST_EIO_PENDING;
1738 			}
1739 		}
1740 		if (st->flags & ST_AT_FILEMARK) {
1741 			st->flags &= ~ST_AT_FILEMARK;
1742 			number--;
1743 		}
1744 		if ((st->flags & ST_BLANK_READ) && (number < 0)) {
1745 			/* back away from unwritten tape */
1746 			st->flags &= ~ST_BLANK_READ;
1747 			number++;	/* XXX dubious */
1748 		}
1749 		break;
1750 	case SP_EOM:
1751 		if (st->flags & ST_EOM_PENDING) {
1752 			/* we're already there */
1753 			st->flags &= ~ST_EOM_PENDING;
1754 			return (0);
1755 		}
1756 		if (st->flags & ST_EIO_PENDING) {
1757 			/* pretend we just discovered the error */
1758 			st->flags &= ~ST_EIO_PENDING;
1759 			return (EIO);
1760 		}
1761 		if (st->flags & ST_AT_FILEMARK)
1762 			st->flags &= ~ST_AT_FILEMARK;
1763 		break;
1764 	}
1765 	if (number == 0)
1766 		return (0);
1767 
1768 	memset(&cmd, 0, sizeof(cmd));
1769 	cmd.opcode = SPACE;
1770 	cmd.byte2 = what;
1771 	_lto3b(number, cmd.number);
1772 
1773 	st->flags &= ~ST_POSUPDATED;
1774 	st->last_ctl_resid = 0;
1775 	error = scsipi_command(st->sc_periph, (void *)&cmd, sizeof(cmd), 0, 0,
1776 	    0, ST_SPC_TIME, NULL, flags);
1777 
1778 	if (error == 0 && (st->flags & ST_POSUPDATED) == 0) {
1779 		number = number - st->last_ctl_resid;
1780 		if (what == SP_BLKS) {
1781 			if (st->blkno != -1) {
1782 				st->blkno += number;
1783 			}
1784 		} else if (what == SP_FILEMARKS) {
1785 			if (st->fileno != -1) {
1786 				st->fileno += number;
1787 				if (number > 0) {
1788 					st->blkno = 0;
1789 				} else if (number < 0) {
1790 					st->blkno = -1;
1791 				}
1792 			}
1793 		} else if (what == SP_EOM) {
1794 			/*
1795 			 * This loses us relative position.
1796 			 */
1797 			st->fileno = st->blkno = -1;
1798 		}
1799 	}
1800 	return (error);
1801 }
1802 
1803 /*
1804  * write N filemarks
1805  */
1806 static int
1807 st_write_filemarks(struct st_softc *st, int number, int flags)
1808 {
1809 	int error;
1810 	struct scsi_write_filemarks cmd;
1811 
1812 	/*
1813 	 * It's hard to write a negative number of file marks.
1814 	 * Don't try.
1815 	 */
1816 	if (number < 0)
1817 		return (EINVAL);
1818 	switch (number) {
1819 	case 0:		/* really a command to sync the drive's buffers */
1820 		break;
1821 	case 1:
1822 		if (st->flags & ST_FM_WRITTEN)	/* already have one down */
1823 			st->flags &= ~ST_WRITTEN;
1824 		else
1825 			st->flags |= ST_FM_WRITTEN;
1826 		st->flags &= ~ST_PER_ACTION;
1827 		break;
1828 	default:
1829 		st->flags &= ~(ST_PER_ACTION | ST_WRITTEN);
1830 	}
1831 
1832 	memset(&cmd, 0, sizeof(cmd));
1833 	cmd.opcode = WRITE_FILEMARKS;
1834 	if (scsipi_periph_bustype(st->sc_periph) == SCSIPI_BUSTYPE_ATAPI)
1835 		cmd.byte2 = SR_IMMED;
1836 	/*
1837 	 * The ATAPI Onstream DI-30 doesn't support writing filemarks, but
1838 	 * WRITE_FILEMARKS is still used to flush the buffer
1839 	 */
1840 	if ((st->quirks & ST_Q_NOFILEMARKS) == 0)
1841 		_lto3b(number, cmd.number);
1842 
1843 	/* XXX WE NEED TO BE ABLE TO GET A RESIDIUAL XXX */
1844 	error = scsipi_command(st->sc_periph, (void *)&cmd, sizeof(cmd), 0, 0,
1845 	    0, ST_IO_TIME * 4, NULL, flags);
1846 	if (error == 0 && st->fileno != -1) {
1847 		st->fileno += number;
1848 	}
1849 	return (error);
1850 }
1851 
1852 /*
1853  * Make sure the right number of file marks is on tape if the
1854  * tape has been written.  If the position argument is true,
1855  * leave the tape positioned where it was originally.
1856  *
1857  * nmarks returns the number of marks to skip (or, if position
1858  * true, which were skipped) to get back original position.
1859  */
1860 static int
1861 st_check_eod(struct st_softc *st, boolean position, int *nmarks, int flags)
1862 {
1863 	int error;
1864 
1865 	switch (st->flags & (ST_WRITTEN | ST_FM_WRITTEN | ST_2FM_AT_EOD)) {
1866 	default:
1867 		*nmarks = 0;
1868 		return (0);
1869 	case ST_WRITTEN:
1870 	case ST_WRITTEN | ST_FM_WRITTEN | ST_2FM_AT_EOD:
1871 		*nmarks = 1;
1872 		break;
1873 	case ST_WRITTEN | ST_2FM_AT_EOD:
1874 		*nmarks = 2;
1875 	}
1876 	error = st_write_filemarks(st, *nmarks, flags);
1877 	if (position && !error)
1878 		error = st_space(st, -*nmarks, SP_FILEMARKS, flags);
1879 	return (error);
1880 }
1881 
1882 /*
1883  * load/unload/retension
1884  */
1885 static int
1886 st_load(struct st_softc *st, u_int type, int flags)
1887 {
1888 	int error;
1889 	struct scsi_load cmd;
1890 
1891 	if (type != LD_LOAD) {
1892 		int nmarks;
1893 
1894 		error = st_check_eod(st, FALSE, &nmarks, flags);
1895 		if (error) {
1896 			printf("%s: failed to write closing filemarks at "
1897 			    "unload, errno=%d\n", st->sc_dev.dv_xname, error);
1898 			return (error);
1899 		}
1900 	}
1901 	if (st->quirks & ST_Q_IGNORE_LOADS) {
1902 		if (type == LD_LOAD) {
1903 			/*
1904 			 * If we ignore loads, at least we should try a rewind.
1905 			 */
1906 			return st_rewind(st, 0, flags);
1907 		}
1908 		/* otherwise, we should do what's asked of us */
1909 	}
1910 
1911 	memset(&cmd, 0, sizeof(cmd));
1912 	cmd.opcode = LOAD;
1913 	if (scsipi_periph_bustype(st->sc_periph) == SCSIPI_BUSTYPE_ATAPI)
1914 		cmd.byte2 = SR_IMMED;
1915 	cmd.how = type;
1916 
1917 	error = scsipi_command(st->sc_periph, (void *)&cmd, sizeof(cmd), 0, 0,
1918 	    ST_RETRIES, ST_SPC_TIME, NULL, flags);
1919 	if (error) {
1920 		printf("%s: error %d in st_load (op %d)\n",
1921 		    st->sc_dev.dv_xname, error, type);
1922 	}
1923 	return (error);
1924 }
1925 
1926 /*
1927  *  Rewind the device
1928  */
1929 static int
1930 st_rewind(struct st_softc *st, u_int immediate, int flags)
1931 {
1932 	struct scsi_rewind cmd;
1933 	int error;
1934 	int nmarks;
1935 
1936 	error = st_check_eod(st, FALSE, &nmarks, flags);
1937 	if (error) {
1938 		printf("%s: failed to write closing filemarks at "
1939 		    "rewind, errno=%d\n", st->sc_dev.dv_xname, error);
1940 		return (error);
1941 	}
1942 	st->flags &= ~ST_PER_ACTION;
1943 
1944 	/*
1945 	 * ATAPI tapes always need immediate to be set
1946 	 */
1947 	if (scsipi_periph_bustype(st->sc_periph) == SCSIPI_BUSTYPE_ATAPI)
1948 		immediate = SR_IMMED;
1949 
1950 	memset(&cmd, 0, sizeof(cmd));
1951 	cmd.opcode = REWIND;
1952 	cmd.byte2 = immediate;
1953 
1954 	error = scsipi_command(st->sc_periph, (void *)&cmd, sizeof(cmd), 0, 0,
1955 	    ST_RETRIES, immediate ? ST_CTL_TIME: ST_SPC_TIME, NULL, flags);
1956 	if (error) {
1957 		printf("%s: error %d trying to rewind\n",
1958 		    st->sc_dev.dv_xname, error);
1959 		/* lost position */
1960 		st->fileno = st->blkno = -1;
1961 	} else {
1962 		st->fileno = st->blkno = 0;
1963 	}
1964 	return (error);
1965 }
1966 
1967 static int
1968 st_rdpos(struct st_softc *st, int hard, u_int32_t *blkptr)
1969 {
1970 	int error;
1971 	u_int8_t posdata[20];
1972 	struct scsi_tape_read_position cmd;
1973 
1974 	/*
1975 	 * We try and flush any buffered writes here if we were writing
1976 	 * and we're trying to get hardware block position. It eats
1977 	 * up performance substantially, but I'm wary of drive firmware.
1978 	 *
1979 	 * I think that *logical* block position is probably okay-
1980 	 * but hardware block position might have to wait for data
1981 	 * to hit media to be valid. Caveat Emptor.
1982 	 */
1983 
1984 	if (hard && (st->flags & ST_WRITTEN)) {
1985 		/*
1986 		 * First flush any pending writes...
1987 		 */
1988 		error = st_write_filemarks(st, 0, XS_CTL_SILENT);
1989 		/*
1990 		 * The latter case is for 'write protected' tapes
1991 		 * which are too stupid to recognize a zero count
1992 		 * for writing filemarks as a no-op.
1993 		 */
1994 		if (error != 0 && error != EACCES && error != EROFS)
1995 			return (error);
1996 	}
1997 
1998 	memset(&cmd, 0, sizeof(cmd));
1999 	memset(&posdata, 0, sizeof(posdata));
2000 	cmd.opcode = READ_POSITION;
2001 	if (hard)
2002 		cmd.byte1 = 1;
2003 
2004 	error = scsipi_command(st->sc_periph, (void *)&cmd, sizeof(cmd),
2005 	    (void *)&posdata, sizeof(posdata), ST_RETRIES, ST_CTL_TIME, NULL,
2006 	    XS_CTL_SILENT | XS_CTL_DATA_IN | XS_CTL_DATA_ONSTACK);
2007 
2008 	if (error == 0) {
2009 #if	0
2010 		printf("posdata:");
2011 		for (hard = 0; hard < sizeof(posdata); hard++)
2012 			printf("%02x ", posdata[hard] & 0xff);
2013 		printf("\n");
2014 #endif
2015 		if (posdata[0] & 0x4)	/* Block Position Unknown */
2016 			error = EINVAL;
2017 		else
2018 			*blkptr = _4btol(&posdata[4]);
2019 	}
2020 	return (error);
2021 }
2022 
2023 static int
2024 st_setpos(struct st_softc *st, int hard, u_int32_t *blkptr)
2025 {
2026 	int error;
2027 	struct scsi_tape_locate cmd;
2028 
2029 	/*
2030 	 * We used to try and flush any buffered writes here.
2031 	 * Now we push this onto user applications to either
2032 	 * flush the pending writes themselves (via a zero count
2033 	 * WRITE FILEMARKS command) or they can trust their tape
2034 	 * drive to do this correctly for them.
2035 	 *
2036 	 * There are very ugly performance limitations otherwise.
2037 	 */
2038 
2039 	memset(&cmd, 0, sizeof(cmd));
2040 	cmd.opcode = LOCATE;
2041 	if (hard)
2042 		cmd.byte2 = 1 << 2;
2043 	_lto4b(*blkptr, cmd.blkaddr);
2044 	error = scsipi_command(st->sc_periph, (void *)&cmd, sizeof(cmd), 0, 0,
2045 	    ST_RETRIES, ST_SPC_TIME, NULL, 0);
2046 	/*
2047 	 * Note file && block number position now unknown (if
2048 	 * these things ever start being maintained in this driver)
2049 	 */
2050 	st->fileno = st->blkno = -1;
2051 	return (error);
2052 }
2053 
2054 
2055 /*
2056  * Look at the returned sense and act on the error and determine
2057  * the unix error number to pass back..., 0 (== report no error),
2058  * -1 = retry the operation, -2 continue error processing.
2059  */
2060 static int
2061 st_interpret_sense(struct scsipi_xfer *xs)
2062 {
2063 	struct scsipi_periph *periph = xs->xs_periph;
2064 	struct scsipi_sense_data *sense = &xs->sense.scsi_sense;
2065 	struct buf *bp = xs->bp;
2066 	struct st_softc *st = (void *)periph->periph_dev;
2067 	int retval = EJUSTRETURN;
2068 	int doprint = ((xs->xs_control & XS_CTL_SILENT) == 0);
2069 	u_int8_t key;
2070 	int32_t info;
2071 
2072 	/*
2073 	 * If it isn't a extended or extended/deferred error, let
2074 	 * the generic code handle it.
2075 	 */
2076 	if ((sense->error_code & SSD_ERRCODE) != 0x70 &&
2077 	    (sense->error_code & SSD_ERRCODE) != 0x71) {	/* DEFFERRED */
2078 		return (retval);
2079 	}
2080 
2081 	if (sense->error_code & SSD_ERRCODE_VALID)
2082 		info = _4btol(sense->info);
2083 	else
2084 		info = (st->flags & ST_FIXEDBLOCKS) ?
2085 		    xs->datalen / st->blksize : xs->datalen;
2086 	key = sense->flags & SSD_KEY;
2087 	st->mt_erreg = key;
2088 	st->asc = sense->add_sense_code;
2089 	st->ascq = sense->add_sense_code_qual;
2090 	st->mt_resid = (short) info;
2091 
2092 	if (key == SKEY_NOT_READY && st->asc == 0x4 && st->ascq == 0x1) {
2093 		/* Not Ready, Logical Unit Is in Process Of Becoming Ready */
2094 		if (!callout_pending(&periph->periph_callout))
2095 			scsipi_periph_freeze(periph, 1);
2096 		callout_reset(&periph->periph_callout,
2097 		    hz, scsipi_periph_timed_thaw, periph);
2098 		return (ERESTART);
2099 	}
2100 
2101 	/*
2102 	 * If the device is not open yet, let generic handle
2103 	 */
2104 	if ((periph->periph_flags & PERIPH_OPEN) == 0) {
2105 		return (retval);
2106 	}
2107 
2108 	xs->resid = info;
2109 	if (st->flags & ST_FIXEDBLOCKS) {
2110 		if (bp) {
2111 			xs->resid *= st->blksize;
2112 			st->last_io_resid = xs->resid;
2113 		} else {
2114 			st->last_ctl_resid = xs->resid;
2115 		}
2116 		if (key == SKEY_VOLUME_OVERFLOW) {
2117 			st->flags |= ST_EIO_PENDING;
2118 			if (bp)
2119 				bp->b_resid = xs->resid;
2120 		} else if (sense->flags & SSD_EOM) {
2121 			if ((st->flags & ST_EARLYWARN) == 0)
2122 				st->flags |= ST_EIO_PENDING;
2123 			st->flags |= ST_EOM_PENDING;
2124 			if (bp) {
2125 #if 0
2126 				bp->b_resid = xs->resid;
2127 #else
2128 				/*
2129 				 * Grotesque as it seems, the few times
2130 				 * I've actually seen a non-zero resid,
2131 				 * the tape drive actually lied and had
2132 				 * written all the data!
2133 				 */
2134 				bp->b_resid = 0;
2135 #endif
2136 			}
2137 		}
2138 		if (sense->flags & SSD_FILEMARK) {
2139 			st->flags |= ST_AT_FILEMARK;
2140 			if (bp)
2141 				bp->b_resid = xs->resid;
2142 			if (st->fileno != (daddr_t) -1) {
2143 				st->fileno++;
2144 				st->blkno = 0;
2145 				st->flags |= ST_POSUPDATED;
2146 			}
2147 		}
2148 		if (sense->flags & SSD_ILI) {
2149 			st->flags |= ST_EIO_PENDING;
2150 			if (bp)
2151 				bp->b_resid = xs->resid;
2152 			if (sense->error_code & SSD_ERRCODE_VALID &&
2153 			    (xs->xs_control & XS_CTL_SILENT) == 0)
2154 				printf("%s: block wrong size, %d blocks "
2155 				    "residual\n", st->sc_dev.dv_xname, info);
2156 
2157 			/*
2158 			 * This quirk code helps the drive read
2159 			 * the first tape block, regardless of
2160 			 * format.  That is required for these
2161 			 * drives to return proper MODE SENSE
2162 			 * information.
2163 			 */
2164 			if ((st->quirks & ST_Q_SENSE_HELP) &&
2165 			    (periph->periph_flags & PERIPH_MEDIA_LOADED) == 0)
2166 				st->blksize -= 512;
2167 			else if ((st->flags & ST_POSUPDATED) == 0) {
2168 				if (st->blkno != (daddr_t) -1) {
2169 					st->blkno +=
2170 					    (xs->datalen / st->blksize);
2171 					st->flags |= ST_POSUPDATED;
2172 				}
2173 			}
2174 		}
2175 		/*
2176 		 * If data wanted and no data was transferred, do it immediately
2177 		 */
2178 		if (xs->datalen && xs->resid >= xs->datalen) {
2179 			if (st->flags & ST_EIO_PENDING)
2180 				return (EIO);
2181 			if (st->flags & ST_AT_FILEMARK) {
2182 				if (bp)
2183 					bp->b_resid = xs->resid;
2184 				return (0);
2185 			}
2186 		}
2187 	} else {		/* must be variable mode */
2188 		if (bp) {
2189 			st->last_io_resid = xs->resid;
2190 		} else {
2191 			st->last_ctl_resid = xs->resid;
2192 		}
2193 		if (sense->flags & SSD_EOM) {
2194 			/*
2195 			 * The current semantics of this
2196 			 * driver requires EOM detection
2197 			 * to return EIO unless early
2198 			 * warning detection is enabled
2199 			 * for variable mode (this is always
2200 			 * on for fixed block mode).
2201 			 */
2202 			if (st->flags & ST_EARLYWARN) {
2203 				st->flags |= ST_EOM_PENDING;
2204 				retval = 0;
2205 			} else {
2206 				retval = EIO;
2207 			}
2208 
2209 			/*
2210 			 * If it's an unadorned EOM detection,
2211 			 * suppress printing an error.
2212 			 */
2213 			if (key == SKEY_NO_SENSE) {
2214 				doprint = 0;
2215 			}
2216 		} else if (sense->flags & SSD_FILEMARK) {
2217 			retval = 0;
2218 			if (st->fileno != (daddr_t) -1) {
2219 				st->fileno++;
2220 				st->blkno = 0;
2221 				st->flags |= ST_POSUPDATED;
2222 			}
2223 		} else if (sense->flags & SSD_ILI) {
2224 			if (info < 0) {
2225 				/*
2226 				 * The tape record was bigger than the read
2227 				 * we issued.
2228 				 */
2229 				if ((xs->xs_control & XS_CTL_SILENT) == 0) {
2230 					printf("%s: %d-byte tape record too big"
2231 					    " for %d-byte user buffer\n",
2232 					    st->sc_dev.dv_xname,
2233 					    xs->datalen - info, xs->datalen);
2234 				}
2235 				retval = EIO;
2236 			} else {
2237 				retval = 0;
2238 				if (st->blkno != (daddr_t) -1) {
2239 					st->blkno++;
2240 					st->flags |= ST_POSUPDATED;
2241 				}
2242 			}
2243 		}
2244 		if (bp)
2245 			bp->b_resid = info;
2246 	}
2247 
2248 #ifndef SCSIPI_DEBUG
2249 	if (retval == 0 && key == SKEY_NO_SENSE)
2250 		doprint = 0;
2251 #endif
2252 	if (key == SKEY_BLANK_CHECK) {
2253 		/*
2254 		 * This quirk code helps the drive read the
2255 		 * first tape block, regardless of format.  That
2256 		 * is required for these drives to return proper
2257 		 * MODE SENSE information.
2258 		 */
2259 		if ((st->quirks & ST_Q_SENSE_HELP) &&
2260 		    (periph->periph_flags & PERIPH_MEDIA_LOADED) == 0) {
2261 			/* still starting */
2262 			st->blksize -= 512;
2263 		} else if (!(st->flags & (ST_2FM_AT_EOD | ST_BLANK_READ))) {
2264 			st->flags |= ST_BLANK_READ;
2265 			xs->resid = xs->datalen;
2266 			if (bp) {
2267 				bp->b_resid = xs->resid;
2268 				/* return an EOF */
2269 			}
2270 			retval = 0;
2271 			/* lost position */
2272 			st->fileno = st->blkno = -1;
2273 		}
2274 	}
2275 
2276 	/*
2277 	 * If generic sense processing will continue, we should not
2278 	 * print sense info here.
2279 	 */
2280 	if (retval == EJUSTRETURN)
2281 		doprint = 0;
2282 
2283 	if (doprint) {
2284 #ifdef	SCSIVERBOSE
2285 		scsipi_print_sense(xs, 0);
2286 #else
2287 		scsipi_printaddr(periph);
2288 		printf("Sense Key 0x%02x", key);
2289 		if ((sense->error_code & SSD_ERRCODE_VALID) != 0) {
2290 			switch (key) {
2291 			case SKEY_NOT_READY:
2292 			case SKEY_ILLEGAL_REQUEST:
2293 			case SKEY_UNIT_ATTENTION:
2294 			case SKEY_WRITE_PROTECT:
2295 				break;
2296 			case SKEY_VOLUME_OVERFLOW:
2297 			case SKEY_BLANK_CHECK:
2298 				printf(", requested size: %d (decimal)", info);
2299 				break;
2300 			case SKEY_ABORTED_COMMAND:
2301 				if (xs->xs_retries)
2302 					printf(", retrying");
2303 				printf(", cmd 0x%x, info 0x%x",
2304 				    xs->cmd->opcode, info);
2305 				break;
2306 			default:
2307 				printf(", info = %d (decimal)", info);
2308 			}
2309 		}
2310 		if (sense->extra_len != 0) {
2311 			int n;
2312 			printf(", data =");
2313 			for (n = 0; n < sense->extra_len; n++)
2314 				printf(" %02x", sense->cmd_spec_info[n]);
2315 		}
2316 		printf("\n");
2317 #endif
2318 	}
2319 	return (retval);
2320 }
2321 
2322 /*
2323  * The quirk here is that the drive returns some value to st_mode_sense
2324  * incorrectly until the tape has actually passed by the head.
2325  *
2326  * The method is to set the drive to large fixed-block state (user-specified
2327  * density and 1024-byte blocks), then read and rewind to get it to sense the
2328  * tape.  If that doesn't work, try 512-byte fixed blocks.  If that doesn't
2329  * work, as a last resort, try variable- length blocks.  The result will be
2330  * the ability to do an accurate st_mode_sense.
2331  *
2332  * We know we can do a rewind because we just did a load, which implies rewind.
2333  * Rewind seems preferable to space backward if we have a virgin tape.
2334  *
2335  * The rest of the code for this quirk is in ILI processing and BLANK CHECK
2336  * error processing, both part of st_interpret_sense.
2337  */
2338 static int
2339 st_touch_tape(struct st_softc *st)
2340 {
2341 	char *buf;
2342 	int readsize;
2343 	int error;
2344 
2345 	buf = malloc(1024, M_TEMP, M_NOWAIT);
2346 	if (buf == NULL)
2347 		return (ENOMEM);
2348 
2349 	if ((error = st->ops(st, ST_OPS_MODESENSE, 0)) != 0)
2350 		goto bad;
2351 
2352 	/*
2353 	 * If the block size is already known from the
2354 	 * sense data, use it. Else start probing at 1024.
2355 	 */
2356 	if (st->media_blksize > 0)
2357 		st->blksize = st->media_blksize;
2358 	else
2359 		st->blksize = 1024;
2360 
2361 	do {
2362 		switch (st->blksize) {
2363 		case 512:
2364 		case 1024:
2365 			readsize = st->blksize;
2366 			st->flags |= ST_FIXEDBLOCKS;
2367 			break;
2368 		default:
2369 			readsize = 1;
2370 			st->flags &= ~ST_FIXEDBLOCKS;
2371 		}
2372 		if ((error = st->ops(st, ST_OPS_MODESELECT, XS_CTL_SILENT))
2373 		    != 0) {
2374 			/*
2375 			 * The device did not agree with the proposed
2376 			 * block size. If we exhausted our options,
2377 			 * return failure, else try another.
2378 			 */
2379 			if (readsize == 1)
2380 				goto bad;
2381 			st->blksize -= 512;
2382 			continue;
2383 		}
2384 		st_read(st, buf, readsize, XS_CTL_SILENT);	/* XXX */
2385 		if ((error = st_rewind(st, 0, 0)) != 0) {
2386 bad:			free(buf, M_TEMP);
2387 			return (error);
2388 		}
2389 	} while (readsize != 1 && readsize > st->blksize);
2390 
2391 	free(buf, M_TEMP);
2392 	return (0);
2393 }
2394 
2395 static int
2396 stdump(dev_t dev, daddr_t blkno, caddr_t va, size_t size)
2397 {
2398 
2399 	/* Not implemented. */
2400 	return (ENXIO);
2401 }
2402