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