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