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