xref: /freebsd/sys/cam/scsi/scsi_ch.c (revision 6990ffd8a95caaba6858ad44ff1b3157d1efba8f)
1 /*
2  * Copyright (c) 1997 Justin T. Gibbs.
3  * Copyright (c) 1997, 1998, 1999 Kenneth D. Merry.
4  * All rights reserved.
5  *
6  * Redistribution and use in source and binary forms, with or without
7  * modification, are permitted provided that the following conditions
8  * are met:
9  * 1. Redistributions of source code must retain the above copyright
10  *    notice, this list of conditions, and the following disclaimer,
11  *    without modification, immediately at the beginning of the file.
12  * 2. The name of the author may not be used to endorse or promote products
13  *    derived from this software without specific prior written permission.
14  *
15  * THIS SOFTWARE IS PROVIDED BY THE AUTHOR AND CONTRIBUTORS ``AS IS'' AND
16  * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
17  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
18  * ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE FOR
19  * ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
20  * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
21  * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
22  * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
23  * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
24  * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
25  * SUCH DAMAGE.
26  *
27  * $FreeBSD$
28  */
29 /*
30  * Derived from the NetBSD SCSI changer driver.
31  *
32  *	$NetBSD: ch.c,v 1.32 1998/01/12 09:49:12 thorpej Exp $
33  *
34  */
35 /*
36  * Copyright (c) 1996, 1997 Jason R. Thorpe <thorpej@and.com>
37  * All rights reserved.
38  *
39  * Partially based on an autochanger driver written by Stefan Grefen
40  * and on an autochanger driver written by the Systems Programming Group
41  * at the University of Utah Computer Science Department.
42  *
43  * Redistribution and use in source and binary forms, with or without
44  * modification, are permitted provided that the following conditions
45  * are met:
46  * 1. Redistributions of source code must retain the above copyright
47  *    notice, this list of conditions and the following disclaimer.
48  * 2. Redistributions in binary form must reproduce the above copyright
49  *    notice, this list of conditions and the following disclaimer in the
50  *    documentation and/or other materials provided with the distribution.
51  * 3. All advertising materials mentioning features or use of this software
52  *    must display the following acknowledgements:
53  *	This product includes software developed by Jason R. Thorpe
54  *	for And Communications, http://www.and.com/
55  * 4. The name of the author may not be used to endorse or promote products
56  *    derived from this software without specific prior written permission.
57  *
58  * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR
59  * IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
60  * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.
61  * IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT,
62  * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,
63  * BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
64  * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED
65  * AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
66  * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
67  * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
68  * SUCH DAMAGE.
69  */
70 
71 #include <sys/param.h>
72 #include <sys/queue.h>
73 #include <sys/systm.h>
74 #include <sys/kernel.h>
75 #include <sys/types.h>
76 #include <sys/malloc.h>
77 #include <sys/fcntl.h>
78 #include <sys/conf.h>
79 #include <sys/chio.h>
80 #include <sys/errno.h>
81 #include <sys/devicestat.h>
82 
83 #include <cam/cam.h>
84 #include <cam/cam_ccb.h>
85 #include <cam/cam_extend.h>
86 #include <cam/cam_periph.h>
87 #include <cam/cam_xpt_periph.h>
88 #include <cam/cam_debug.h>
89 
90 #include <cam/scsi/scsi_all.h>
91 #include <cam/scsi/scsi_message.h>
92 #include <cam/scsi/scsi_ch.h>
93 
94 /*
95  * Timeout definitions for various changer related commands.  They may
96  * be too short for some devices (especially the timeout for INITIALIZE
97  * ELEMENT STATUS).
98  */
99 
100 static const u_int32_t	CH_TIMEOUT_MODE_SENSE                = 6000;
101 static const u_int32_t	CH_TIMEOUT_MOVE_MEDIUM               = 100000;
102 static const u_int32_t	CH_TIMEOUT_EXCHANGE_MEDIUM           = 100000;
103 static const u_int32_t	CH_TIMEOUT_POSITION_TO_ELEMENT       = 100000;
104 static const u_int32_t	CH_TIMEOUT_READ_ELEMENT_STATUS       = 10000;
105 static const u_int32_t	CH_TIMEOUT_SEND_VOLTAG		     = 10000;
106 static const u_int32_t	CH_TIMEOUT_INITIALIZE_ELEMENT_STATUS = 500000;
107 
108 typedef enum {
109 	CH_FLAG_INVALID		= 0x001,
110 	CH_FLAG_OPEN		= 0x002
111 } ch_flags;
112 
113 typedef enum {
114 	CH_STATE_PROBE,
115 	CH_STATE_NORMAL
116 } ch_state;
117 
118 typedef enum {
119 	CH_CCB_PROBE,
120 	CH_CCB_WAITING
121 } ch_ccb_types;
122 
123 typedef enum {
124 	CH_Q_NONE	= 0x00,
125 	CH_Q_NO_DBD	= 0x01
126 } ch_quirks;
127 
128 #define ccb_state	ppriv_field0
129 #define ccb_bp		ppriv_ptr1
130 
131 struct scsi_mode_sense_data {
132 	struct scsi_mode_header_6 header;
133 	struct scsi_mode_blk_desc blk_desc;
134 	union {
135 		struct page_element_address_assignment ea;
136 		struct page_transport_geometry_parameters tg;
137 		struct page_device_capabilities cap;
138 	} pages;
139 };
140 
141 struct ch_softc {
142 	ch_flags	flags;
143 	ch_state	state;
144 	ch_quirks	quirks;
145 	union ccb	saved_ccb;
146 	struct devstat	device_stats;
147 	dev_t		dev;
148 
149 	int		sc_picker;	/* current picker */
150 
151 	/*
152 	 * The following information is obtained from the
153 	 * element address assignment page.
154 	 */
155 	int		sc_firsts[4];	/* firsts, indexed by CHET_* */
156 	int		sc_counts[4];	/* counts, indexed by CHET_* */
157 
158 	/*
159 	 * The following mask defines the legal combinations
160 	 * of elements for the MOVE MEDIUM command.
161 	 */
162 	u_int8_t	sc_movemask[4];
163 
164 	/*
165 	 * As above, but for EXCHANGE MEDIUM.
166 	 */
167 	u_int8_t	sc_exchangemask[4];
168 
169 	/*
170 	 * Quirks; see below.  XXX KDM not implemented yet
171 	 */
172 	int		sc_settledelay;	/* delay for settle */
173 };
174 
175 #define CHUNIT(x)       (minor((x)))
176 #define CH_CDEV_MAJOR	17
177 
178 static	d_open_t	chopen;
179 static	d_close_t	chclose;
180 static	d_ioctl_t	chioctl;
181 static	periph_init_t	chinit;
182 static  periph_ctor_t	chregister;
183 static	periph_oninv_t	choninvalidate;
184 static  periph_dtor_t   chcleanup;
185 static  periph_start_t  chstart;
186 static	void		chasync(void *callback_arg, u_int32_t code,
187 				struct cam_path *path, void *arg);
188 static	void		chdone(struct cam_periph *periph,
189 			       union ccb *done_ccb);
190 static	int		cherror(union ccb *ccb, u_int32_t cam_flags,
191 				u_int32_t sense_flags);
192 static	int		chmove(struct cam_periph *periph,
193 			       struct changer_move *cm);
194 static	int		chexchange(struct cam_periph *periph,
195 				   struct changer_exchange *ce);
196 static	int		chposition(struct cam_periph *periph,
197 				   struct changer_position *cp);
198 static	int		chgetelemstatus(struct cam_periph *periph,
199 				struct changer_element_status_request *csr);
200 static	int		chsetvoltag(struct cam_periph *periph,
201 				    struct changer_set_voltag_request *csvr);
202 static	int		chielem(struct cam_periph *periph,
203 				unsigned int timeout);
204 static	int		chgetparams(struct cam_periph *periph);
205 
206 static struct periph_driver chdriver =
207 {
208 	chinit, "ch",
209 	TAILQ_HEAD_INITIALIZER(chdriver.units), /* generation */ 0
210 };
211 
212 PERIPHDRIVER_DECLARE(ch, chdriver);
213 
214 static struct cdevsw ch_cdevsw = {
215 	/* open */	chopen,
216 	/* close */	chclose,
217 	/* read */	noread,
218 	/* write */	nowrite,
219 	/* ioctl */	chioctl,
220 	/* poll */	nopoll,
221 	/* mmap */	nommap,
222 	/* strategy */	nostrategy,
223 	/* name */	"ch",
224 	/* maj */	CH_CDEV_MAJOR,
225 	/* dump */	nodump,
226 	/* psize */	nopsize,
227 	/* flags */	0,
228 };
229 
230 static struct extend_array *chperiphs;
231 
232 void
233 chinit(void)
234 {
235 	cam_status status;
236 	struct cam_path *path;
237 
238 	/*
239 	 * Create our extend array for storing the devices we attach to.
240 	 */
241 	chperiphs = cam_extend_new();
242 	if (chperiphs == NULL) {
243 		printf("ch: Failed to alloc extend array!\n");
244 		return;
245 	}
246 
247 	/*
248 	 * Install a global async callback.  This callback will
249 	 * receive async callbacks like "new device found".
250 	 */
251 	status = xpt_create_path(&path, /*periph*/NULL, CAM_XPT_PATH_ID,
252 				 CAM_TARGET_WILDCARD, CAM_LUN_WILDCARD);
253 
254 	if (status == CAM_REQ_CMP) {
255 		struct ccb_setasync csa;
256 
257                 xpt_setup_ccb(&csa.ccb_h, path, /*priority*/5);
258                 csa.ccb_h.func_code = XPT_SASYNC_CB;
259                 csa.event_enable = AC_FOUND_DEVICE;
260                 csa.callback = chasync;
261                 csa.callback_arg = NULL;
262                 xpt_action((union ccb *)&csa);
263 		status = csa.ccb_h.status;
264                 xpt_free_path(path);
265         }
266 
267 	if (status != CAM_REQ_CMP) {
268 		printf("ch: Failed to attach master async callback "
269 		       "due to status 0x%x!\n", status);
270 	}
271 }
272 
273 static void
274 choninvalidate(struct cam_periph *periph)
275 {
276 	struct ch_softc *softc;
277 	struct ccb_setasync csa;
278 
279 	softc = (struct ch_softc *)periph->softc;
280 
281 	/*
282 	 * De-register any async callbacks.
283 	 */
284 	xpt_setup_ccb(&csa.ccb_h, periph->path,
285 		      /* priority */ 5);
286 	csa.ccb_h.func_code = XPT_SASYNC_CB;
287 	csa.event_enable = 0;
288 	csa.callback = chasync;
289 	csa.callback_arg = periph;
290 	xpt_action((union ccb *)&csa);
291 
292 	softc->flags |= CH_FLAG_INVALID;
293 
294 	xpt_print_path(periph->path);
295 	printf("lost device\n");
296 
297 }
298 
299 static void
300 chcleanup(struct cam_periph *periph)
301 {
302 	struct ch_softc *softc;
303 
304 	softc = (struct ch_softc *)periph->softc;
305 
306 	devstat_remove_entry(&softc->device_stats);
307 	destroy_dev(softc->dev);
308 	cam_extend_release(chperiphs, periph->unit_number);
309 	xpt_print_path(periph->path);
310 	printf("removing device entry\n");
311 	free(softc, M_DEVBUF);
312 }
313 
314 static void
315 chasync(void *callback_arg, u_int32_t code, struct cam_path *path, void *arg)
316 {
317 	struct cam_periph *periph;
318 
319 	periph = (struct cam_periph *)callback_arg;
320 
321 	switch(code) {
322 	case AC_FOUND_DEVICE:
323 	{
324 		struct ccb_getdev *cgd;
325 		cam_status status;
326 
327 		cgd = (struct ccb_getdev *)arg;
328 		if (cgd == NULL)
329 			break;
330 
331 		if (SID_TYPE(&cgd->inq_data)!= T_CHANGER)
332 			break;
333 
334 		/*
335 		 * Allocate a peripheral instance for
336 		 * this device and start the probe
337 		 * process.
338 		 */
339 		status = cam_periph_alloc(chregister, choninvalidate,
340 					  chcleanup, chstart, "ch",
341 					  CAM_PERIPH_BIO, cgd->ccb_h.path,
342 					  chasync, AC_FOUND_DEVICE, cgd);
343 
344 		if (status != CAM_REQ_CMP
345 		 && status != CAM_REQ_INPROG)
346 			printf("chasync: Unable to probe new device "
347 			       "due to status 0x%x\n", status);
348 
349 		break;
350 
351 	}
352 	default:
353 		cam_periph_async(periph, code, path, arg);
354 		break;
355 	}
356 }
357 
358 static cam_status
359 chregister(struct cam_periph *periph, void *arg)
360 {
361 	struct ch_softc *softc;
362 	struct ccb_setasync csa;
363 	struct ccb_getdev *cgd;
364 
365 	cgd = (struct ccb_getdev *)arg;
366 	if (periph == NULL) {
367 		printf("chregister: periph was NULL!!\n");
368 		return(CAM_REQ_CMP_ERR);
369 	}
370 
371 	if (cgd == NULL) {
372 		printf("chregister: no getdev CCB, can't register device\n");
373 		return(CAM_REQ_CMP_ERR);
374 	}
375 
376 	softc = (struct ch_softc *)malloc(sizeof(*softc),M_DEVBUF,M_NOWAIT);
377 
378 	if (softc == NULL) {
379 		printf("chregister: Unable to probe new device. "
380 		       "Unable to allocate softc\n");
381 		return(CAM_REQ_CMP_ERR);
382 	}
383 
384 	bzero(softc, sizeof(*softc));
385 	softc->state = CH_STATE_PROBE;
386 	periph->softc = softc;
387 	cam_extend_set(chperiphs, periph->unit_number, periph);
388 	softc->quirks = CH_Q_NONE;
389 
390 	/*
391 	 * Changers don't have a blocksize, and obviously don't support
392 	 * tagged queueing.
393 	 */
394 	devstat_add_entry(&softc->device_stats, "ch",
395 			  periph->unit_number, 0,
396 			  DEVSTAT_NO_BLOCKSIZE | DEVSTAT_NO_ORDERED_TAGS,
397 			  SID_TYPE(&cgd->inq_data)| DEVSTAT_TYPE_IF_SCSI,
398 			  DEVSTAT_PRIORITY_OTHER);
399 
400 	/* Register the device */
401 	softc->dev = make_dev(&ch_cdevsw, periph->unit_number, UID_ROOT,
402 			      GID_OPERATOR, 0600, "%s%d", periph->periph_name,
403 			      periph->unit_number);
404 
405 	/*
406 	 * Add an async callback so that we get
407 	 * notified if this device goes away.
408 	 */
409 	xpt_setup_ccb(&csa.ccb_h, periph->path, /* priority */ 5);
410 	csa.ccb_h.func_code = XPT_SASYNC_CB;
411 	csa.event_enable = AC_LOST_DEVICE;
412 	csa.callback = chasync;
413 	csa.callback_arg = periph;
414 	xpt_action((union ccb *)&csa);
415 
416 	/*
417 	 * Lock this peripheral until we are setup.
418 	 * This first call can't block
419 	 */
420 	(void)cam_periph_lock(periph, PRIBIO);
421 	xpt_schedule(periph, /*priority*/5);
422 
423 	return(CAM_REQ_CMP);
424 }
425 
426 static int
427 chopen(dev_t dev, int flags, int fmt, struct thread *td)
428 {
429 	struct cam_periph *periph;
430 	struct ch_softc *softc;
431 	int unit, error;
432 	int s;
433 
434 	unit = CHUNIT(dev);
435 	periph = cam_extend_get(chperiphs, unit);
436 
437 	if (periph == NULL)
438 		return(ENXIO);
439 
440 	softc = (struct ch_softc *)periph->softc;
441 
442 	s = splsoftcam();
443 	if (softc->flags & CH_FLAG_INVALID) {
444 		splx(s);
445 		return(ENXIO);
446 	}
447 
448 	if ((error = cam_periph_lock(periph, PRIBIO | PCATCH)) != 0) {
449 		splx(s);
450 		return (error);
451 	}
452 
453 	splx(s);
454 
455 	if ((softc->flags & CH_FLAG_OPEN) == 0) {
456 		if (cam_periph_acquire(periph) != CAM_REQ_CMP)
457 			return(ENXIO);
458 		softc->flags |= CH_FLAG_OPEN;
459 	}
460 
461 	/*
462 	 * Load information about this changer device into the softc.
463 	 */
464 	if ((error = chgetparams(periph)) != 0) {
465 		softc->flags &= ~CH_FLAG_OPEN;
466 		cam_periph_unlock(periph);
467 		cam_periph_release(periph);
468 		return(error);
469 	}
470 
471 	cam_periph_unlock(periph);
472 
473 	return(error);
474 }
475 
476 static int
477 chclose(dev_t dev, int flag, int fmt, struct thread *td)
478 {
479 	struct	cam_periph *periph;
480 	struct	ch_softc *softc;
481 	int	unit, error;
482 
483 	error = 0;
484 
485 	unit = CHUNIT(dev);
486 	periph = cam_extend_get(chperiphs, unit);
487 	if (periph == NULL)
488 		return(ENXIO);
489 
490 	softc = (struct ch_softc *)periph->softc;
491 
492 	if ((error = cam_periph_lock(periph, PRIBIO)) != 0)
493 		return(error);
494 
495 	softc->flags &= ~CH_FLAG_OPEN;
496 
497 	cam_periph_unlock(periph);
498 	cam_periph_release(periph);
499 
500 	return(0);
501 }
502 
503 static void
504 chstart(struct cam_periph *periph, union ccb *start_ccb)
505 {
506 	struct ch_softc *softc;
507 	int s;
508 
509 	softc = (struct ch_softc *)periph->softc;
510 
511 	switch (softc->state) {
512 	case CH_STATE_NORMAL:
513 	{
514 		s = splbio();
515 		if (periph->immediate_priority <= periph->pinfo.priority){
516 			start_ccb->ccb_h.ccb_state = CH_CCB_WAITING;
517 
518 			SLIST_INSERT_HEAD(&periph->ccb_list, &start_ccb->ccb_h,
519 					  periph_links.sle);
520 			periph->immediate_priority = CAM_PRIORITY_NONE;
521 			splx(s);
522 			wakeup(&periph->ccb_list);
523 		} else
524 			splx(s);
525 		break;
526 	}
527 	case CH_STATE_PROBE:
528 	{
529 		int mode_buffer_len;
530 		void *mode_buffer;
531 
532 		/*
533 		 * Include the block descriptor when calculating the mode
534 		 * buffer length,
535 		 */
536 		mode_buffer_len = sizeof(struct scsi_mode_header_6) +
537 				  sizeof(struct scsi_mode_blk_desc) +
538 				 sizeof(struct page_element_address_assignment);
539 
540 		mode_buffer = malloc(mode_buffer_len, M_TEMP, M_NOWAIT);
541 
542 		if (mode_buffer == NULL) {
543 			printf("chstart: couldn't malloc mode sense data\n");
544 			break;
545 		}
546 		bzero(mode_buffer, mode_buffer_len);
547 
548 		/*
549 		 * Get the element address assignment page.
550 		 */
551 		scsi_mode_sense(&start_ccb->csio,
552 				/* retries */ 1,
553 				/* cbfcnp */ chdone,
554 				/* tag_action */ MSG_SIMPLE_Q_TAG,
555 				/* dbd */ (softc->quirks & CH_Q_NO_DBD) ?
556 					FALSE : TRUE,
557 				/* page_code */ SMS_PAGE_CTRL_CURRENT,
558 				/* page */ CH_ELEMENT_ADDR_ASSIGN_PAGE,
559 				/* param_buf */ (u_int8_t *)mode_buffer,
560 				/* param_len */ mode_buffer_len,
561 				/* sense_len */ SSD_FULL_SIZE,
562 				/* timeout */ CH_TIMEOUT_MODE_SENSE);
563 
564 		start_ccb->ccb_h.ccb_bp = NULL;
565 		start_ccb->ccb_h.ccb_state = CH_CCB_PROBE;
566 		xpt_action(start_ccb);
567 		break;
568 	}
569 	}
570 }
571 
572 static void
573 chdone(struct cam_periph *periph, union ccb *done_ccb)
574 {
575 	struct ch_softc *softc;
576 	struct ccb_scsiio *csio;
577 
578 	softc = (struct ch_softc *)periph->softc;
579 	csio = &done_ccb->csio;
580 
581 	switch(done_ccb->ccb_h.ccb_state) {
582 	case CH_CCB_PROBE:
583 	{
584 		struct scsi_mode_header_6 *mode_header;
585 		struct page_element_address_assignment *ea;
586 		char announce_buf[80];
587 
588 
589 		mode_header = (struct scsi_mode_header_6 *)csio->data_ptr;
590 
591 		ea = (struct page_element_address_assignment *)
592 			find_mode_page_6(mode_header);
593 
594 		if ((done_ccb->ccb_h.status & CAM_STATUS_MASK) == CAM_REQ_CMP){
595 
596 			softc->sc_firsts[CHET_MT] = scsi_2btoul(ea->mtea);
597 			softc->sc_counts[CHET_MT] = scsi_2btoul(ea->nmte);
598 			softc->sc_firsts[CHET_ST] = scsi_2btoul(ea->fsea);
599 			softc->sc_counts[CHET_ST] = scsi_2btoul(ea->nse);
600 			softc->sc_firsts[CHET_IE] = scsi_2btoul(ea->fieea);
601 			softc->sc_counts[CHET_IE] = scsi_2btoul(ea->niee);
602 			softc->sc_firsts[CHET_DT] = scsi_2btoul(ea->fdtea);
603 			softc->sc_counts[CHET_DT] = scsi_2btoul(ea->ndte);
604 			softc->sc_picker = softc->sc_firsts[CHET_MT];
605 
606 #define PLURAL(c)	(c) == 1 ? "" : "s"
607 			snprintf(announce_buf, sizeof(announce_buf),
608 				"%d slot%s, %d drive%s, "
609 				"%d picker%s, %d portal%s",
610 		    		softc->sc_counts[CHET_ST],
611 				PLURAL(softc->sc_counts[CHET_ST]),
612 		    		softc->sc_counts[CHET_DT],
613 				PLURAL(softc->sc_counts[CHET_DT]),
614 		    		softc->sc_counts[CHET_MT],
615 				PLURAL(softc->sc_counts[CHET_MT]),
616 		    		softc->sc_counts[CHET_IE],
617 				PLURAL(softc->sc_counts[CHET_IE]));
618 #undef PLURAL
619 		} else {
620 			int error;
621 
622 			error = cherror(done_ccb, CAM_RETRY_SELTO,
623 					SF_RETRY_UA | SF_NO_PRINT);
624 			/*
625 			 * Retry any UNIT ATTENTION type errors.  They
626 			 * are expected at boot.
627 			 */
628 			if (error == ERESTART) {
629 				/*
630 				 * A retry was scheuled, so
631 				 * just return.
632 				 */
633 				return;
634 			} else if (error != 0) {
635 				int retry_scheduled;
636 				struct scsi_mode_sense_6 *sms;
637 
638 				sms = (struct scsi_mode_sense_6 *)
639 					done_ccb->csio.cdb_io.cdb_bytes;
640 
641 				/*
642 				 * Check to see if block descriptors were
643 				 * disabled.  Some devices don't like that.
644 				 * We're taking advantage of the fact that
645 				 * the first few bytes of the 6 and 10 byte
646 				 * mode sense commands are the same.  If
647 				 * block descriptors were disabled, enable
648 				 * them and re-send the command.
649 				 */
650 				if (sms->byte2 & SMS_DBD) {
651 					sms->byte2 &= ~SMS_DBD;
652 					xpt_action(done_ccb);
653 					softc->quirks |= CH_Q_NO_DBD;
654 					retry_scheduled = 1;
655 				} else
656 					retry_scheduled = 0;
657 
658 				/* Don't wedge this device's queue */
659 				cam_release_devq(done_ccb->ccb_h.path,
660 						 /*relsim_flags*/0,
661 						 /*reduction*/0,
662 						 /*timeout*/0,
663 						 /*getcount_only*/0);
664 
665 				if (retry_scheduled)
666 					return;
667 
668 				if ((done_ccb->ccb_h.status & CAM_STATUS_MASK)
669 				    == CAM_SCSI_STATUS_ERROR)
670 					scsi_sense_print(&done_ccb->csio);
671 				else {
672 					xpt_print_path(periph->path);
673 					printf("got CAM status %#x\n",
674 					       done_ccb->ccb_h.status);
675 				}
676 				xpt_print_path(periph->path);
677 				printf("fatal error, failed to attach to"
678 				       " device\n");
679 
680 				cam_periph_invalidate(periph);
681 
682 				announce_buf[0] = '\0';
683 			}
684 		}
685 		if (announce_buf[0] != '\0')
686 			xpt_announce_periph(periph, announce_buf);
687 		softc->state = CH_STATE_NORMAL;
688 		free(mode_header, M_TEMP);
689 		/*
690 		 * Since our peripheral may be invalidated by an error
691 		 * above or an external event, we must release our CCB
692 		 * before releasing the probe lock on the peripheral.
693 		 * The peripheral will only go away once the last lock
694 		 * is removed, and we need it around for the CCB release
695 		 * operation.
696 		 */
697 		xpt_release_ccb(done_ccb);
698 		cam_periph_unlock(periph);
699 		return;
700 	}
701 	case CH_CCB_WAITING:
702 	{
703 		/* Caller will release the CCB */
704 		wakeup(&done_ccb->ccb_h.cbfcnp);
705 		return;
706 	}
707 	default:
708 		break;
709 	}
710 	xpt_release_ccb(done_ccb);
711 }
712 
713 static int
714 cherror(union ccb *ccb, u_int32_t cam_flags, u_int32_t sense_flags)
715 {
716 	struct ch_softc *softc;
717 	struct cam_periph *periph;
718 
719 	periph = xpt_path_periph(ccb->ccb_h.path);
720 	softc = (struct ch_softc *)periph->softc;
721 
722 	return (cam_periph_error(ccb, cam_flags, sense_flags,
723 				 &softc->saved_ccb));
724 }
725 
726 static int
727 chioctl(dev_t dev, u_long cmd, caddr_t addr, int flag, struct thread *td)
728 {
729 	struct cam_periph *periph;
730 	struct ch_softc *softc;
731 	u_int8_t unit;
732 	int error;
733 
734 	unit = CHUNIT(dev);
735 
736 	periph = cam_extend_get(chperiphs, unit);
737 	if (periph == NULL)
738 		return(ENXIO);
739 
740 	CAM_DEBUG(periph->path, CAM_DEBUG_TRACE, ("entering chioctl\n"));
741 
742 	softc = (struct ch_softc *)periph->softc;
743 
744 	error = 0;
745 
746 	CAM_DEBUG(periph->path, CAM_DEBUG_TRACE,
747 		  ("trying to do ioctl %#lx\n", cmd));
748 
749 	/*
750 	 * If this command can change the device's state, we must
751 	 * have the device open for writing.
752 	 */
753 	switch (cmd) {
754 	case CHIOGPICKER:
755 	case CHIOGPARAMS:
756 	case CHIOGSTATUS:
757 		break;
758 
759 	default:
760 		if ((flag & FWRITE) == 0)
761 			return (EBADF);
762 	}
763 
764 	switch (cmd) {
765 	case CHIOMOVE:
766 		error = chmove(periph, (struct changer_move *)addr);
767 		break;
768 
769 	case CHIOEXCHANGE:
770 		error = chexchange(periph, (struct changer_exchange *)addr);
771 		break;
772 
773 	case CHIOPOSITION:
774 		error = chposition(periph, (struct changer_position *)addr);
775 		break;
776 
777 	case CHIOGPICKER:
778 		*(int *)addr = softc->sc_picker - softc->sc_firsts[CHET_MT];
779 		break;
780 
781 	case CHIOSPICKER:
782 	{
783 		int new_picker = *(int *)addr;
784 
785 		if (new_picker > (softc->sc_counts[CHET_MT] - 1))
786 			return (EINVAL);
787 		softc->sc_picker = softc->sc_firsts[CHET_MT] + new_picker;
788 		break;
789 	}
790 	case CHIOGPARAMS:
791 	{
792 		struct changer_params *cp = (struct changer_params *)addr;
793 
794 		cp->cp_npickers = softc->sc_counts[CHET_MT];
795 		cp->cp_nslots = softc->sc_counts[CHET_ST];
796 		cp->cp_nportals = softc->sc_counts[CHET_IE];
797 		cp->cp_ndrives = softc->sc_counts[CHET_DT];
798 		break;
799 	}
800 	case CHIOIELEM:
801 		error = chielem(periph, *(unsigned int *)addr);
802 		break;
803 
804 	case CHIOGSTATUS:
805 	{
806 		error = chgetelemstatus(periph,
807 			       (struct changer_element_status_request *) addr);
808 		break;
809 	}
810 
811 	case CHIOSETVOLTAG:
812 	{
813 		error = chsetvoltag(periph,
814 				    (struct changer_set_voltag_request *) addr);
815 		break;
816 	}
817 
818 	/* Implement prevent/allow? */
819 
820 	default:
821 		error = cam_periph_ioctl(periph, cmd, addr, cherror);
822 		break;
823 	}
824 
825 	return (error);
826 }
827 
828 static int
829 chmove(struct cam_periph *periph, struct changer_move *cm)
830 {
831 	struct ch_softc *softc;
832 	u_int16_t fromelem, toelem;
833 	union ccb *ccb;
834 	int error;
835 
836 	error = 0;
837 	softc = (struct ch_softc *)periph->softc;
838 
839 	/*
840 	 * Check arguments.
841 	 */
842 	if ((cm->cm_fromtype > CHET_DT) || (cm->cm_totype > CHET_DT))
843 		return (EINVAL);
844 	if ((cm->cm_fromunit > (softc->sc_counts[cm->cm_fromtype] - 1)) ||
845 	    (cm->cm_tounit > (softc->sc_counts[cm->cm_totype] - 1)))
846 		return (ENODEV);
847 
848 	/*
849 	 * Check the request against the changer's capabilities.
850 	 */
851 	if ((softc->sc_movemask[cm->cm_fromtype] & (1 << cm->cm_totype)) == 0)
852 		return (ENODEV);
853 
854 	/*
855 	 * Calculate the source and destination elements.
856 	 */
857 	fromelem = softc->sc_firsts[cm->cm_fromtype] + cm->cm_fromunit;
858 	toelem = softc->sc_firsts[cm->cm_totype] + cm->cm_tounit;
859 
860 	ccb = cam_periph_getccb(periph, /*priority*/ 1);
861 
862 	scsi_move_medium(&ccb->csio,
863 			 /* retries */ 1,
864 			 /* cbfcnp */ chdone,
865 			 /* tag_action */ MSG_SIMPLE_Q_TAG,
866 			 /* tea */ softc->sc_picker,
867 			 /* src */ fromelem,
868 			 /* dst */ toelem,
869 			 /* invert */ (cm->cm_flags & CM_INVERT) ? TRUE : FALSE,
870 			 /* sense_len */ SSD_FULL_SIZE,
871 			 /* timeout */ CH_TIMEOUT_MOVE_MEDIUM);
872 
873 	error = cam_periph_runccb(ccb, cherror, /*cam_flags*/CAM_RETRY_SELTO,
874 				  /*sense_flags*/ SF_RETRY_UA,
875 				  &softc->device_stats);
876 
877 	xpt_release_ccb(ccb);
878 
879 	return(error);
880 }
881 
882 static int
883 chexchange(struct cam_periph *periph, struct changer_exchange *ce)
884 {
885 	struct ch_softc *softc;
886 	u_int16_t src, dst1, dst2;
887 	union ccb *ccb;
888 	int error;
889 
890 	error = 0;
891 	softc = (struct ch_softc *)periph->softc;
892 	/*
893 	 * Check arguments.
894 	 */
895 	if ((ce->ce_srctype > CHET_DT) || (ce->ce_fdsttype > CHET_DT) ||
896 	    (ce->ce_sdsttype > CHET_DT))
897 		return (EINVAL);
898 	if ((ce->ce_srcunit > (softc->sc_counts[ce->ce_srctype] - 1)) ||
899 	    (ce->ce_fdstunit > (softc->sc_counts[ce->ce_fdsttype] - 1)) ||
900 	    (ce->ce_sdstunit > (softc->sc_counts[ce->ce_sdsttype] - 1)))
901 		return (ENODEV);
902 
903 	/*
904 	 * Check the request against the changer's capabilities.
905 	 */
906 	if (((softc->sc_exchangemask[ce->ce_srctype] &
907 	     (1 << ce->ce_fdsttype)) == 0) ||
908 	    ((softc->sc_exchangemask[ce->ce_fdsttype] &
909 	     (1 << ce->ce_sdsttype)) == 0))
910 		return (ENODEV);
911 
912 	/*
913 	 * Calculate the source and destination elements.
914 	 */
915 	src = softc->sc_firsts[ce->ce_srctype] + ce->ce_srcunit;
916 	dst1 = softc->sc_firsts[ce->ce_fdsttype] + ce->ce_fdstunit;
917 	dst2 = softc->sc_firsts[ce->ce_sdsttype] + ce->ce_sdstunit;
918 
919 	ccb = cam_periph_getccb(periph, /*priority*/ 1);
920 
921 	scsi_exchange_medium(&ccb->csio,
922 			     /* retries */ 1,
923 			     /* cbfcnp */ chdone,
924 			     /* tag_action */ MSG_SIMPLE_Q_TAG,
925 			     /* tea */ softc->sc_picker,
926 			     /* src */ src,
927 			     /* dst1 */ dst1,
928 			     /* dst2 */ dst2,
929 			     /* invert1 */ (ce->ce_flags & CE_INVERT1) ?
930 			                   TRUE : FALSE,
931 			     /* invert2 */ (ce->ce_flags & CE_INVERT2) ?
932 			                   TRUE : FALSE,
933 			     /* sense_len */ SSD_FULL_SIZE,
934 			     /* timeout */ CH_TIMEOUT_EXCHANGE_MEDIUM);
935 
936 	error = cam_periph_runccb(ccb, cherror, /*cam_flags*/CAM_RETRY_SELTO,
937 				  /*sense_flags*/ SF_RETRY_UA,
938 				  &softc->device_stats);
939 
940 	xpt_release_ccb(ccb);
941 
942 	return(error);
943 }
944 
945 static int
946 chposition(struct cam_periph *periph, struct changer_position *cp)
947 {
948 	struct ch_softc *softc;
949 	u_int16_t dst;
950 	union ccb *ccb;
951 	int error;
952 
953 	error = 0;
954 	softc = (struct ch_softc *)periph->softc;
955 
956 	/*
957 	 * Check arguments.
958 	 */
959 	if (cp->cp_type > CHET_DT)
960 		return (EINVAL);
961 	if (cp->cp_unit > (softc->sc_counts[cp->cp_type] - 1))
962 		return (ENODEV);
963 
964 	/*
965 	 * Calculate the destination element.
966 	 */
967 	dst = softc->sc_firsts[cp->cp_type] + cp->cp_unit;
968 
969 	ccb = cam_periph_getccb(periph, /*priority*/ 1);
970 
971 	scsi_position_to_element(&ccb->csio,
972 				 /* retries */ 1,
973 				 /* cbfcnp */ chdone,
974 				 /* tag_action */ MSG_SIMPLE_Q_TAG,
975 				 /* tea */ softc->sc_picker,
976 				 /* dst */ dst,
977 				 /* invert */ (cp->cp_flags & CP_INVERT) ?
978 					      TRUE : FALSE,
979 				 /* sense_len */ SSD_FULL_SIZE,
980 				 /* timeout */ CH_TIMEOUT_POSITION_TO_ELEMENT);
981 
982 	error = cam_periph_runccb(ccb, cherror, /*cam_flags*/ CAM_RETRY_SELTO,
983 				  /*sense_flags*/ SF_RETRY_UA,
984 				  &softc->device_stats);
985 
986 	xpt_release_ccb(ccb);
987 
988 	return(error);
989 }
990 
991 /*
992  * Copy a volume tag to a volume_tag struct, converting SCSI byte order
993  * to host native byte order in the volume serial number.  The volume
994  * label as returned by the changer is transferred to user mode as
995  * nul-terminated string.  Volume labels are truncated at the first
996  * space, as suggested by SCSI-2.
997  */
998 static	void
999 copy_voltag(struct changer_voltag *uvoltag, struct volume_tag *voltag)
1000 {
1001 	int i;
1002 	for (i=0; i<CH_VOLTAG_MAXLEN; i++) {
1003 		char c = voltag->vif[i];
1004 		if (c && c != ' ')
1005 			uvoltag->cv_volid[i] = c;
1006 	        else
1007 			break;
1008 	}
1009 	uvoltag->cv_serial = scsi_2btoul(voltag->vsn);
1010 }
1011 
1012 /*
1013  * Copy an an element status descriptor to a user-mode
1014  * changer_element_status structure.
1015  */
1016 
1017 static	void
1018 copy_element_status(struct ch_softc *softc,
1019 		    u_int16_t flags,
1020 		    struct read_element_status_descriptor *desc,
1021 		    struct changer_element_status *ces)
1022 {
1023 	u_int16_t eaddr = scsi_2btoul(desc->eaddr);
1024 	u_int16_t et;
1025 
1026 	ces->ces_int_addr = eaddr;
1027 	/* set up logical address in element status */
1028 	for (et = CHET_MT; et <= CHET_DT; et++) {
1029 		if ((softc->sc_firsts[et] <= eaddr)
1030 		    && ((softc->sc_firsts[et] + softc->sc_counts[et])
1031 			> eaddr)) {
1032 			ces->ces_addr = eaddr - softc->sc_firsts[et];
1033 			ces->ces_type = et;
1034 			break;
1035 		}
1036 	}
1037 
1038 	ces->ces_flags = desc->flags1;
1039 
1040 	ces->ces_sensecode = desc->sense_code;
1041 	ces->ces_sensequal = desc->sense_qual;
1042 
1043 	if (desc->flags2 & READ_ELEMENT_STATUS_INVERT)
1044 		ces->ces_flags |= CES_INVERT;
1045 
1046 	if (desc->flags2 & READ_ELEMENT_STATUS_SVALID) {
1047 
1048 		eaddr = scsi_2btoul(desc->ssea);
1049 
1050 		/* convert source address to logical format */
1051 		for (et = CHET_MT; et <= CHET_DT; et++) {
1052 			if ((softc->sc_firsts[et] <= eaddr)
1053 			    && ((softc->sc_firsts[et] + softc->sc_counts[et])
1054 				> eaddr)) {
1055 				ces->ces_source_addr =
1056 					eaddr - softc->sc_firsts[et];
1057 				ces->ces_source_type = et;
1058 				ces->ces_flags |= CES_SOURCE_VALID;
1059 				break;
1060 			}
1061 		}
1062 
1063 		if (!(ces->ces_flags & CES_SOURCE_VALID))
1064 			printf("ch: warning: could not map element source "
1065 			       "address %ud to a valid element type\n",
1066 			       eaddr);
1067 	}
1068 
1069 
1070 	if (flags & READ_ELEMENT_STATUS_PVOLTAG)
1071 		copy_voltag(&(ces->ces_pvoltag), &(desc->pvoltag));
1072 	if (flags & READ_ELEMENT_STATUS_AVOLTAG)
1073 		copy_voltag(&(ces->ces_avoltag), &(desc->avoltag));
1074 
1075 	if (desc->dt_scsi_flags & READ_ELEMENT_STATUS_DT_IDVALID) {
1076 		ces->ces_flags |= CES_SCSIID_VALID;
1077 		ces->ces_scsi_id = desc->dt_scsi_addr;
1078 	}
1079 
1080 	if (desc->dt_scsi_addr & READ_ELEMENT_STATUS_DT_LUVALID) {
1081 		ces->ces_flags |= CES_LUN_VALID;
1082 		ces->ces_scsi_lun =
1083 			desc->dt_scsi_flags & READ_ELEMENT_STATUS_DT_LUNMASK;
1084 	}
1085 }
1086 
1087 static int
1088 chgetelemstatus(struct cam_periph *periph,
1089 		struct changer_element_status_request *cesr)
1090 {
1091 	struct read_element_status_header *st_hdr;
1092 	struct read_element_status_page_header *pg_hdr;
1093 	struct read_element_status_descriptor *desc;
1094 	caddr_t data = NULL;
1095 	size_t size, desclen;
1096 	int avail, i, error = 0;
1097 	struct changer_element_status *user_data = NULL;
1098 	struct ch_softc *softc;
1099 	union ccb *ccb;
1100 	int chet = cesr->cesr_element_type;
1101 	int want_voltags = (cesr->cesr_flags & CESR_VOLTAGS) ? 1 : 0;
1102 
1103 	softc = (struct ch_softc *)periph->softc;
1104 
1105 	/* perform argument checking */
1106 
1107 	/*
1108 	 * Perform a range check on the cesr_element_{base,count}
1109 	 * request argument fields.
1110 	 */
1111 	if ((softc->sc_counts[chet] - cesr->cesr_element_base) <= 0
1112 	    || (cesr->cesr_element_base + cesr->cesr_element_count)
1113 	        > softc->sc_counts[chet])
1114 		return (EINVAL);
1115 
1116 	/*
1117 	 * Request one descriptor for the given element type.  This
1118 	 * is used to determine the size of the descriptor so that
1119 	 * we can allocate enough storage for all of them.  We assume
1120 	 * that the first one can fit into 1k.
1121 	 */
1122 	data = (caddr_t)malloc(1024, M_DEVBUF, M_WAITOK);
1123 
1124 	ccb = cam_periph_getccb(periph, /*priority*/ 1);
1125 
1126 	scsi_read_element_status(&ccb->csio,
1127 				 /* retries */ 1,
1128 				 /* cbfcnp */ chdone,
1129 				 /* tag_action */ MSG_SIMPLE_Q_TAG,
1130 				 /* voltag */ want_voltags,
1131 				 /* sea */ softc->sc_firsts[chet],
1132 				 /* count */ 1,
1133 				 /* data_ptr */ data,
1134 				 /* dxfer_len */ 1024,
1135 				 /* sense_len */ SSD_FULL_SIZE,
1136 				 /* timeout */ CH_TIMEOUT_READ_ELEMENT_STATUS);
1137 
1138 	error = cam_periph_runccb(ccb, cherror, /*cam_flags*/ CAM_RETRY_SELTO,
1139 				  /*sense_flags*/ SF_RETRY_UA,
1140 				  &softc->device_stats);
1141 
1142 	if (error)
1143 		goto done;
1144 
1145 	st_hdr = (struct read_element_status_header *)data;
1146 	pg_hdr = (struct read_element_status_page_header *)((uintptr_t)st_hdr +
1147 		  sizeof(struct read_element_status_header));
1148 	desclen = scsi_2btoul(pg_hdr->edl);
1149 
1150 	size = sizeof(struct read_element_status_header) +
1151 	       sizeof(struct read_element_status_page_header) +
1152 	       (desclen * cesr->cesr_element_count);
1153 
1154 	/*
1155 	 * Reallocate storage for descriptors and get them from the
1156 	 * device.
1157 	 */
1158 	free(data, M_DEVBUF);
1159 	data = (caddr_t)malloc(size, M_DEVBUF, M_WAITOK);
1160 
1161 	scsi_read_element_status(&ccb->csio,
1162 				 /* retries */ 1,
1163 				 /* cbfcnp */ chdone,
1164 				 /* tag_action */ MSG_SIMPLE_Q_TAG,
1165 				 /* voltag */ want_voltags,
1166 				 /* sea */ softc->sc_firsts[chet]
1167 				 + cesr->cesr_element_base,
1168 				 /* count */ cesr->cesr_element_count,
1169 				 /* data_ptr */ data,
1170 				 /* dxfer_len */ size,
1171 				 /* sense_len */ SSD_FULL_SIZE,
1172 				 /* timeout */ CH_TIMEOUT_READ_ELEMENT_STATUS);
1173 
1174 	error = cam_periph_runccb(ccb, cherror, /*cam_flags*/ CAM_RETRY_SELTO,
1175 				  /*sense_flags*/ SF_RETRY_UA,
1176 				  &softc->device_stats);
1177 
1178 	if (error)
1179 		goto done;
1180 
1181 	/*
1182 	 * Fill in the user status array.
1183 	 */
1184 	st_hdr = (struct read_element_status_header *)data;
1185 	avail = scsi_2btoul(st_hdr->count);
1186 
1187 	if (avail != cesr->cesr_element_count) {
1188 		xpt_print_path(periph->path);
1189 		printf("warning, READ ELEMENT STATUS avail != count\n");
1190 	}
1191 
1192 	user_data = (struct changer_element_status *)
1193 		malloc(avail * sizeof(struct changer_element_status),
1194 		       M_DEVBUF, M_WAITOK | M_ZERO);
1195 
1196 	desc = (struct read_element_status_descriptor *)((uintptr_t)data +
1197 		sizeof(struct read_element_status_header) +
1198 		sizeof(struct read_element_status_page_header));
1199 	/*
1200 	 * Set up the individual element status structures
1201 	 */
1202 	for (i = 0; i < avail; ++i) {
1203 		struct changer_element_status *ces = &(user_data[i]);
1204 
1205 		copy_element_status(softc, pg_hdr->flags, desc, ces);
1206 
1207 		desc = (struct read_element_status_descriptor *)
1208 		       ((uintptr_t)desc + desclen);
1209 	}
1210 
1211 	/* Copy element status structures out to userspace. */
1212 	error = copyout(user_data,
1213 			cesr->cesr_element_status,
1214 			avail * sizeof(struct changer_element_status));
1215 
1216  done:
1217 	xpt_release_ccb(ccb);
1218 
1219 	if (data != NULL)
1220 		free(data, M_DEVBUF);
1221 	if (user_data != NULL)
1222 		free(user_data, M_DEVBUF);
1223 
1224 	return (error);
1225 }
1226 
1227 static int
1228 chielem(struct cam_periph *periph,
1229 	unsigned int timeout)
1230 {
1231 	union ccb *ccb;
1232 	struct ch_softc *softc;
1233 	int error;
1234 
1235 	if (!timeout) {
1236 		timeout = CH_TIMEOUT_INITIALIZE_ELEMENT_STATUS;
1237 	} else {
1238 		timeout *= 1000;
1239 	}
1240 
1241 	error = 0;
1242 	softc = (struct ch_softc *)periph->softc;
1243 
1244 	ccb = cam_periph_getccb(periph, /*priority*/ 1);
1245 
1246 	scsi_initialize_element_status(&ccb->csio,
1247 				      /* retries */ 1,
1248 				      /* cbfcnp */ chdone,
1249 				      /* tag_action */ MSG_SIMPLE_Q_TAG,
1250 				      /* sense_len */ SSD_FULL_SIZE,
1251 				      /* timeout */ timeout);
1252 
1253 	error = cam_periph_runccb(ccb, cherror, /*cam_flags*/ CAM_RETRY_SELTO,
1254 				  /*sense_flags*/ SF_RETRY_UA,
1255 				  &softc->device_stats);
1256 
1257 	xpt_release_ccb(ccb);
1258 
1259 	return(error);
1260 }
1261 
1262 static int
1263 chsetvoltag(struct cam_periph *periph,
1264 	    struct changer_set_voltag_request *csvr)
1265 {
1266 	union ccb *ccb;
1267 	struct ch_softc *softc;
1268 	u_int16_t ea;
1269 	u_int8_t sac;
1270 	struct scsi_send_volume_tag_parameters ssvtp;
1271 	int error;
1272 	int i;
1273 
1274 	error = 0;
1275 	softc = (struct ch_softc *)periph->softc;
1276 
1277 	bzero(&ssvtp, sizeof(ssvtp));
1278 	for (i=0; i<sizeof(ssvtp.vitf); i++) {
1279 		ssvtp.vitf[i] = ' ';
1280 	}
1281 
1282 	/*
1283 	 * Check arguments.
1284 	 */
1285 	if (csvr->csvr_type > CHET_DT)
1286 		return EINVAL;
1287 	if (csvr->csvr_addr > (softc->sc_counts[csvr->csvr_type] - 1))
1288 		return ENODEV;
1289 
1290 	ea = softc->sc_firsts[csvr->csvr_type] + csvr->csvr_addr;
1291 
1292 	if (csvr->csvr_flags & CSVR_ALTERNATE) {
1293 		switch (csvr->csvr_flags & CSVR_MODE_MASK) {
1294 		case CSVR_MODE_SET:
1295 			sac = SEND_VOLUME_TAG_ASSERT_ALTERNATE;
1296 			break;
1297 		case CSVR_MODE_REPLACE:
1298 			sac = SEND_VOLUME_TAG_REPLACE_ALTERNATE;
1299 			break;
1300 		case CSVR_MODE_CLEAR:
1301 			sac = SEND_VOLUME_TAG_UNDEFINED_ALTERNATE;
1302 			break;
1303 		default:
1304 			error = EINVAL;
1305 			goto out;
1306 		}
1307 	} else {
1308 		switch (csvr->csvr_flags & CSVR_MODE_MASK) {
1309 		case CSVR_MODE_SET:
1310 			sac = SEND_VOLUME_TAG_ASSERT_PRIMARY;
1311 			break;
1312 		case CSVR_MODE_REPLACE:
1313 			sac = SEND_VOLUME_TAG_REPLACE_PRIMARY;
1314 			break;
1315 		case CSVR_MODE_CLEAR:
1316 			sac = SEND_VOLUME_TAG_UNDEFINED_PRIMARY;
1317 			break;
1318 		default:
1319 			error = EINVAL;
1320 			goto out;
1321 		}
1322 	}
1323 
1324 	memcpy(ssvtp.vitf, csvr->csvr_voltag.cv_volid,
1325 	       min(strlen(csvr->csvr_voltag.cv_volid), sizeof(ssvtp.vitf)));
1326 	scsi_ulto2b(csvr->csvr_voltag.cv_serial, ssvtp.minvsn);
1327 
1328 	ccb = cam_periph_getccb(periph, /*priority*/ 1);
1329 
1330 	scsi_send_volume_tag(&ccb->csio,
1331 			     /* retries */ 1,
1332 			     /* cbfcnp */ chdone,
1333 			     /* tag_action */ MSG_SIMPLE_Q_TAG,
1334 			     /* element_address */ ea,
1335 			     /* send_action_code */ sac,
1336 			     /* parameters */ &ssvtp,
1337 			     /* sense_len */ SSD_FULL_SIZE,
1338 			     /* timeout */ CH_TIMEOUT_SEND_VOLTAG);
1339 
1340 	error = cam_periph_runccb(ccb, cherror, /*cam_flags*/ CAM_RETRY_SELTO,
1341 				  /*sense_flags*/ SF_RETRY_UA,
1342 				  &softc->device_stats);
1343 
1344 	xpt_release_ccb(ccb);
1345 
1346  out:
1347 	return error;
1348 }
1349 
1350 static int
1351 chgetparams(struct cam_periph *periph)
1352 {
1353 	union ccb *ccb;
1354 	struct ch_softc *softc;
1355 	void *mode_buffer;
1356 	int mode_buffer_len;
1357 	struct page_element_address_assignment *ea;
1358 	struct page_device_capabilities *cap;
1359 	int error, from, dbd;
1360 	u_int8_t *moves, *exchanges;
1361 
1362 	error = 0;
1363 
1364 	softc = (struct ch_softc *)periph->softc;
1365 
1366 	ccb = cam_periph_getccb(periph, /*priority*/ 1);
1367 
1368 	/*
1369 	 * The scsi_mode_sense_data structure is just a convenience
1370 	 * structure that allows us to easily calculate the worst-case
1371 	 * storage size of the mode sense buffer.
1372 	 */
1373 	mode_buffer_len = sizeof(struct scsi_mode_sense_data);
1374 
1375 	mode_buffer = malloc(mode_buffer_len, M_TEMP, M_NOWAIT);
1376 
1377 	if (mode_buffer == NULL) {
1378 		printf("chgetparams: couldn't malloc mode sense data\n");
1379 		return(ENOSPC);
1380 	}
1381 
1382 	bzero(mode_buffer, mode_buffer_len);
1383 
1384 	if (softc->quirks & CH_Q_NO_DBD)
1385 		dbd = FALSE;
1386 	else
1387 		dbd = TRUE;
1388 
1389 	/*
1390 	 * Get the element address assignment page.
1391 	 */
1392 	scsi_mode_sense(&ccb->csio,
1393 			/* retries */ 1,
1394 			/* cbfcnp */ chdone,
1395 			/* tag_action */ MSG_SIMPLE_Q_TAG,
1396 			/* dbd */ dbd,
1397 			/* page_code */ SMS_PAGE_CTRL_CURRENT,
1398 			/* page */ CH_ELEMENT_ADDR_ASSIGN_PAGE,
1399 			/* param_buf */ (u_int8_t *)mode_buffer,
1400 			/* param_len */ mode_buffer_len,
1401 			/* sense_len */ SSD_FULL_SIZE,
1402 			/* timeout */ CH_TIMEOUT_MODE_SENSE);
1403 
1404 	error = cam_periph_runccb(ccb, cherror, /*cam_flags*/ CAM_RETRY_SELTO,
1405 				  /* sense_flags */ SF_RETRY_UA|SF_NO_PRINT,
1406 				  &softc->device_stats);
1407 
1408 	if (error) {
1409 		if (dbd) {
1410 			struct scsi_mode_sense_6 *sms;
1411 
1412 			sms = (struct scsi_mode_sense_6 *)
1413 				ccb->csio.cdb_io.cdb_bytes;
1414 
1415 			sms->byte2 &= ~SMS_DBD;
1416 			error = cam_periph_runccb(ccb, cherror,
1417 						  /*cam_flags*/ CAM_RETRY_SELTO,
1418 				  		  /*sense_flags*/ SF_RETRY_UA,
1419 						  &softc->device_stats);
1420 		} else {
1421 			/*
1422 			 * Since we disabled sense printing above, print
1423 			 * out the sense here since we got an error.
1424 			 */
1425 			scsi_sense_print(&ccb->csio);
1426 		}
1427 
1428 		if (error) {
1429 			xpt_print_path(periph->path);
1430 			printf("chgetparams: error getting element "
1431 			       "address page\n");
1432 			xpt_release_ccb(ccb);
1433 			free(mode_buffer, M_TEMP);
1434 			return(error);
1435 		}
1436 	}
1437 
1438 	ea = (struct page_element_address_assignment *)
1439 		find_mode_page_6((struct scsi_mode_header_6 *)mode_buffer);
1440 
1441 	softc->sc_firsts[CHET_MT] = scsi_2btoul(ea->mtea);
1442 	softc->sc_counts[CHET_MT] = scsi_2btoul(ea->nmte);
1443 	softc->sc_firsts[CHET_ST] = scsi_2btoul(ea->fsea);
1444 	softc->sc_counts[CHET_ST] = scsi_2btoul(ea->nse);
1445 	softc->sc_firsts[CHET_IE] = scsi_2btoul(ea->fieea);
1446 	softc->sc_counts[CHET_IE] = scsi_2btoul(ea->niee);
1447 	softc->sc_firsts[CHET_DT] = scsi_2btoul(ea->fdtea);
1448 	softc->sc_counts[CHET_DT] = scsi_2btoul(ea->ndte);
1449 
1450 	bzero(mode_buffer, mode_buffer_len);
1451 
1452 	/*
1453 	 * Now get the device capabilities page.
1454 	 */
1455 	scsi_mode_sense(&ccb->csio,
1456 			/* retries */ 1,
1457 			/* cbfcnp */ chdone,
1458 			/* tag_action */ MSG_SIMPLE_Q_TAG,
1459 			/* dbd */ dbd,
1460 			/* page_code */ SMS_PAGE_CTRL_CURRENT,
1461 			/* page */ CH_DEVICE_CAP_PAGE,
1462 			/* param_buf */ (u_int8_t *)mode_buffer,
1463 			/* param_len */ mode_buffer_len,
1464 			/* sense_len */ SSD_FULL_SIZE,
1465 			/* timeout */ CH_TIMEOUT_MODE_SENSE);
1466 
1467 	error = cam_periph_runccb(ccb, cherror, /*cam_flags*/ CAM_RETRY_SELTO,
1468 				  /* sense_flags */ SF_RETRY_UA | SF_NO_PRINT,
1469 				  &softc->device_stats);
1470 
1471 	if (error) {
1472 		if (dbd) {
1473 			struct scsi_mode_sense_6 *sms;
1474 
1475 			sms = (struct scsi_mode_sense_6 *)
1476 				ccb->csio.cdb_io.cdb_bytes;
1477 
1478 			sms->byte2 &= ~SMS_DBD;
1479 			error = cam_periph_runccb(ccb, cherror,
1480 						  /*cam_flags*/ CAM_RETRY_SELTO,
1481 				  		  /*sense_flags*/ SF_RETRY_UA,
1482 						  &softc->device_stats);
1483 		} else {
1484 			/*
1485 			 * Since we disabled sense printing above, print
1486 			 * out the sense here since we got an error.
1487 			 */
1488 			scsi_sense_print(&ccb->csio);
1489 		}
1490 
1491 		if (error) {
1492 			xpt_print_path(periph->path);
1493 			printf("chgetparams: error getting device "
1494 			       "capabilities page\n");
1495 			xpt_release_ccb(ccb);
1496 			free(mode_buffer, M_TEMP);
1497 			return(error);
1498 		}
1499 	}
1500 
1501 	xpt_release_ccb(ccb);
1502 
1503 	cap = (struct page_device_capabilities *)
1504 		find_mode_page_6((struct scsi_mode_header_6 *)mode_buffer);
1505 
1506 	bzero(softc->sc_movemask, sizeof(softc->sc_movemask));
1507 	bzero(softc->sc_exchangemask, sizeof(softc->sc_exchangemask));
1508 	moves = &cap->move_from_mt;
1509 	exchanges = &cap->exchange_with_mt;
1510 	for (from = CHET_MT; from <= CHET_DT; ++from) {
1511 		softc->sc_movemask[from] = moves[from];
1512 		softc->sc_exchangemask[from] = exchanges[from];
1513 	}
1514 
1515 	free(mode_buffer, M_TEMP);
1516 
1517 	return(error);
1518 }
1519 
1520 void
1521 scsi_move_medium(struct ccb_scsiio *csio, u_int32_t retries,
1522 		 void (*cbfcnp)(struct cam_periph *, union ccb *),
1523 		 u_int8_t tag_action, u_int32_t tea, u_int32_t src,
1524 		 u_int32_t dst, int invert, u_int8_t sense_len,
1525 		 u_int32_t timeout)
1526 {
1527 	struct scsi_move_medium *scsi_cmd;
1528 
1529 	scsi_cmd = (struct scsi_move_medium *)&csio->cdb_io.cdb_bytes;
1530 	bzero(scsi_cmd, sizeof(*scsi_cmd));
1531 
1532 	scsi_cmd->opcode = MOVE_MEDIUM;
1533 
1534 	scsi_ulto2b(tea, scsi_cmd->tea);
1535 	scsi_ulto2b(src, scsi_cmd->src);
1536 	scsi_ulto2b(dst, scsi_cmd->dst);
1537 
1538 	if (invert)
1539 		scsi_cmd->invert |= MOVE_MEDIUM_INVERT;
1540 
1541 	cam_fill_csio(csio,
1542 		      retries,
1543 		      cbfcnp,
1544 		      /*flags*/ CAM_DIR_NONE,
1545 		      tag_action,
1546 		      /*data_ptr*/ NULL,
1547 		      /*dxfer_len*/ 0,
1548 		      sense_len,
1549 		      sizeof(*scsi_cmd),
1550 		      timeout);
1551 }
1552 
1553 void
1554 scsi_exchange_medium(struct ccb_scsiio *csio, u_int32_t retries,
1555 		     void (*cbfcnp)(struct cam_periph *, union ccb *),
1556 		     u_int8_t tag_action, u_int32_t tea, u_int32_t src,
1557 		     u_int32_t dst1, u_int32_t dst2, int invert1,
1558 		     int invert2, u_int8_t sense_len, u_int32_t timeout)
1559 {
1560 	struct scsi_exchange_medium *scsi_cmd;
1561 
1562 	scsi_cmd = (struct scsi_exchange_medium *)&csio->cdb_io.cdb_bytes;
1563 	bzero(scsi_cmd, sizeof(*scsi_cmd));
1564 
1565 	scsi_cmd->opcode = EXCHANGE_MEDIUM;
1566 
1567 	scsi_ulto2b(tea, scsi_cmd->tea);
1568 	scsi_ulto2b(src, scsi_cmd->src);
1569 	scsi_ulto2b(dst1, scsi_cmd->fdst);
1570 	scsi_ulto2b(dst2, scsi_cmd->sdst);
1571 
1572 	if (invert1)
1573 		scsi_cmd->invert |= EXCHANGE_MEDIUM_INV1;
1574 
1575 	if (invert2)
1576 		scsi_cmd->invert |= EXCHANGE_MEDIUM_INV2;
1577 
1578 	cam_fill_csio(csio,
1579 		      retries,
1580 		      cbfcnp,
1581 		      /*flags*/ CAM_DIR_NONE,
1582 		      tag_action,
1583 		      /*data_ptr*/ NULL,
1584 		      /*dxfer_len*/ 0,
1585 		      sense_len,
1586 		      sizeof(*scsi_cmd),
1587 		      timeout);
1588 }
1589 
1590 void
1591 scsi_position_to_element(struct ccb_scsiio *csio, u_int32_t retries,
1592 			 void (*cbfcnp)(struct cam_periph *, union ccb *),
1593 			 u_int8_t tag_action, u_int32_t tea, u_int32_t dst,
1594 			 int invert, u_int8_t sense_len, u_int32_t timeout)
1595 {
1596 	struct scsi_position_to_element *scsi_cmd;
1597 
1598 	scsi_cmd = (struct scsi_position_to_element *)&csio->cdb_io.cdb_bytes;
1599 	bzero(scsi_cmd, sizeof(*scsi_cmd));
1600 
1601 	scsi_cmd->opcode = POSITION_TO_ELEMENT;
1602 
1603 	scsi_ulto2b(tea, scsi_cmd->tea);
1604 	scsi_ulto2b(dst, scsi_cmd->dst);
1605 
1606 	if (invert)
1607 		scsi_cmd->invert |= POSITION_TO_ELEMENT_INVERT;
1608 
1609 	cam_fill_csio(csio,
1610 		      retries,
1611 		      cbfcnp,
1612 		      /*flags*/ CAM_DIR_NONE,
1613 		      tag_action,
1614 		      /*data_ptr*/ NULL,
1615 		      /*dxfer_len*/ 0,
1616 		      sense_len,
1617 		      sizeof(*scsi_cmd),
1618 		      timeout);
1619 }
1620 
1621 void
1622 scsi_read_element_status(struct ccb_scsiio *csio, u_int32_t retries,
1623 			 void (*cbfcnp)(struct cam_periph *, union ccb *),
1624 			 u_int8_t tag_action, int voltag, u_int32_t sea,
1625 			 u_int32_t count, u_int8_t *data_ptr,
1626 			 u_int32_t dxfer_len, u_int8_t sense_len,
1627 			 u_int32_t timeout)
1628 {
1629 	struct scsi_read_element_status *scsi_cmd;
1630 
1631 	scsi_cmd = (struct scsi_read_element_status *)&csio->cdb_io.cdb_bytes;
1632 	bzero(scsi_cmd, sizeof(*scsi_cmd));
1633 
1634 	scsi_cmd->opcode = READ_ELEMENT_STATUS;
1635 
1636 	scsi_ulto2b(sea, scsi_cmd->sea);
1637 	scsi_ulto2b(count, scsi_cmd->count);
1638 	scsi_ulto3b(dxfer_len, scsi_cmd->len);
1639 
1640 	if (voltag)
1641 		scsi_cmd->byte2 |= READ_ELEMENT_STATUS_VOLTAG;
1642 
1643 	cam_fill_csio(csio,
1644 		      retries,
1645 		      cbfcnp,
1646 		      /*flags*/ CAM_DIR_IN,
1647 		      tag_action,
1648 		      data_ptr,
1649 		      dxfer_len,
1650 		      sense_len,
1651 		      sizeof(*scsi_cmd),
1652 		      timeout);
1653 }
1654 
1655 void
1656 scsi_initialize_element_status(struct ccb_scsiio *csio, u_int32_t retries,
1657 			       void (*cbfcnp)(struct cam_periph *, union ccb *),
1658 			       u_int8_t tag_action, u_int8_t sense_len,
1659 			       u_int32_t timeout)
1660 {
1661 	struct scsi_initialize_element_status *scsi_cmd;
1662 
1663 	scsi_cmd = (struct scsi_initialize_element_status *)
1664 		    &csio->cdb_io.cdb_bytes;
1665 	bzero(scsi_cmd, sizeof(*scsi_cmd));
1666 
1667 	scsi_cmd->opcode = INITIALIZE_ELEMENT_STATUS;
1668 
1669 	cam_fill_csio(csio,
1670 		      retries,
1671 		      cbfcnp,
1672 		      /*flags*/ CAM_DIR_NONE,
1673 		      tag_action,
1674 		      /* data_ptr */ NULL,
1675 		      /* dxfer_len */ 0,
1676 		      sense_len,
1677 		      sizeof(*scsi_cmd),
1678 		      timeout);
1679 }
1680 
1681 void
1682 scsi_send_volume_tag(struct ccb_scsiio *csio, u_int32_t retries,
1683 		     void (*cbfcnp)(struct cam_periph *, union ccb *),
1684 		     u_int8_t tag_action,
1685 		     u_int16_t element_address,
1686 		     u_int8_t send_action_code,
1687 		     struct scsi_send_volume_tag_parameters *parameters,
1688 		     u_int8_t sense_len, u_int32_t timeout)
1689 {
1690 	struct scsi_send_volume_tag *scsi_cmd;
1691 
1692 	scsi_cmd = (struct scsi_send_volume_tag *) &csio->cdb_io.cdb_bytes;
1693 	bzero(scsi_cmd, sizeof(*scsi_cmd));
1694 
1695 	scsi_cmd->opcode = SEND_VOLUME_TAG;
1696 	scsi_ulto2b(element_address, scsi_cmd->ea);
1697 	scsi_cmd->sac = send_action_code;
1698 	scsi_ulto2b(sizeof(*parameters), scsi_cmd->pll);
1699 
1700 	cam_fill_csio(csio,
1701 		      retries,
1702 		      cbfcnp,
1703 		      /*flags*/ CAM_DIR_OUT,
1704 		      tag_action,
1705 		      /* data_ptr */ (u_int8_t *) parameters,
1706 		      sizeof(*parameters),
1707 		      sense_len,
1708 		      sizeof(*scsi_cmd),
1709 		      timeout);
1710 }
1711