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