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