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