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