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