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