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