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