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