xref: /freebsd/sys/cam/scsi/scsi_enc.c (revision 0b3105a37d7adcadcb720112fed4dc4e8040be99)
1 /*-
2  * Copyright (c) 2000 Matthew Jacob
3  * All rights reserved.
4  *
5  * Redistribution and use in source and binary forms, with or without
6  * modification, are permitted provided that the following conditions
7  * are met:
8  * 1. Redistributions of source code must retain the above copyright
9  *    notice, this list of conditions, and the following disclaimer,
10  *    without modification, immediately at the beginning of the file.
11  * 2. The name of the author may not be used to endorse or promote products
12  *    derived from this software without specific prior written permission.
13  *
14  * THIS SOFTWARE IS PROVIDED BY THE AUTHOR AND CONTRIBUTORS ``AS IS'' AND
15  * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
16  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
17  * ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE FOR
18  * ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
19  * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
20  * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
21  * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
22  * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
23  * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
24  * SUCH DAMAGE.
25  */
26 
27 #include <sys/cdefs.h>
28 __FBSDID("$FreeBSD$");
29 
30 #include <sys/param.h>
31 
32 #include <sys/conf.h>
33 #include <sys/errno.h>
34 #include <sys/fcntl.h>
35 #include <sys/kernel.h>
36 #include <sys/kthread.h>
37 #include <sys/lock.h>
38 #include <sys/malloc.h>
39 #include <sys/mutex.h>
40 #include <sys/queue.h>
41 #include <sys/sx.h>
42 #include <sys/systm.h>
43 #include <sys/sysctl.h>
44 #include <sys/types.h>
45 
46 #include <machine/stdarg.h>
47 
48 #include <cam/cam.h>
49 #include <cam/cam_ccb.h>
50 #include <cam/cam_debug.h>
51 #include <cam/cam_periph.h>
52 #include <cam/cam_xpt_periph.h>
53 
54 #include <cam/scsi/scsi_all.h>
55 #include <cam/scsi/scsi_message.h>
56 #include <cam/scsi/scsi_enc.h>
57 #include <cam/scsi/scsi_enc_internal.h>
58 
59 #include <opt_ses.h>
60 
61 MALLOC_DEFINE(M_SCSIENC, "SCSI ENC", "SCSI ENC buffers");
62 
63 /* Enclosure type independent driver */
64 
65 static	d_open_t	enc_open;
66 static	d_close_t	enc_close;
67 static	d_ioctl_t	enc_ioctl;
68 static	periph_init_t	enc_init;
69 static  periph_ctor_t	enc_ctor;
70 static	periph_oninv_t	enc_oninvalidate;
71 static  periph_dtor_t   enc_dtor;
72 
73 static void enc_async(void *, uint32_t, struct cam_path *, void *);
74 static enctyp enc_type(struct ccb_getdev *);
75 
76 SYSCTL_NODE(_kern_cam, OID_AUTO, enc, CTLFLAG_RD, 0,
77             "CAM Enclosure Services driver");
78 
79 static struct periph_driver encdriver = {
80 	enc_init, "ses",
81 	TAILQ_HEAD_INITIALIZER(encdriver.units), /* generation */ 0
82 };
83 
84 PERIPHDRIVER_DECLARE(enc, encdriver);
85 
86 static struct cdevsw enc_cdevsw = {
87 	.d_version =	D_VERSION,
88 	.d_open =	enc_open,
89 	.d_close =	enc_close,
90 	.d_ioctl =	enc_ioctl,
91 	.d_name =	"ses",
92 	.d_flags =	D_TRACKCLOSE,
93 };
94 
95 static void
96 enc_init(void)
97 {
98 	cam_status status;
99 
100 	/*
101 	 * Install a global async callback.  This callback will
102 	 * receive async callbacks like "new device found".
103 	 */
104 	status = xpt_register_async(AC_FOUND_DEVICE, enc_async, NULL, NULL);
105 
106 	if (status != CAM_REQ_CMP) {
107 		printf("enc: Failed to attach master async callback "
108 		       "due to status 0x%x!\n", status);
109 	}
110 }
111 
112 static void
113 enc_devgonecb(void *arg)
114 {
115 	struct cam_periph *periph;
116 	struct enc_softc  *enc;
117 	struct mtx *mtx;
118 	int i;
119 
120 	periph = (struct cam_periph *)arg;
121 	mtx = cam_periph_mtx(periph);
122 	mtx_lock(mtx);
123 	enc = (struct enc_softc *)periph->softc;
124 
125 	/*
126 	 * When we get this callback, we will get no more close calls from
127 	 * devfs.  So if we have any dangling opens, we need to release the
128 	 * reference held for that particular context.
129 	 */
130 	for (i = 0; i < enc->open_count; i++)
131 		cam_periph_release_locked(periph);
132 
133 	enc->open_count = 0;
134 
135 	/*
136 	 * Release the reference held for the device node, it is gone now.
137 	 */
138 	cam_periph_release_locked(periph);
139 
140 	/*
141 	 * We reference the lock directly here, instead of using
142 	 * cam_periph_unlock().  The reason is that the final call to
143 	 * cam_periph_release_locked() above could result in the periph
144 	 * getting freed.  If that is the case, dereferencing the periph
145 	 * with a cam_periph_unlock() call would cause a page fault.
146 	 */
147 	mtx_unlock(mtx);
148 }
149 
150 static void
151 enc_oninvalidate(struct cam_periph *periph)
152 {
153 	struct enc_softc *enc;
154 
155 	enc = periph->softc;
156 
157 	enc->enc_flags |= ENC_FLAG_INVALID;
158 
159 	/* If the sub-driver has an invalidate routine, call it */
160 	if (enc->enc_vec.softc_invalidate != NULL)
161 		enc->enc_vec.softc_invalidate(enc);
162 
163 	/*
164 	 * Unregister any async callbacks.
165 	 */
166 	xpt_register_async(0, enc_async, periph, periph->path);
167 
168 	/*
169 	 * Shutdown our daemon.
170 	 */
171 	enc->enc_flags |= ENC_FLAG_SHUTDOWN;
172 	if (enc->enc_daemon != NULL) {
173 		/* Signal the ses daemon to terminate. */
174 		wakeup(enc->enc_daemon);
175 	}
176 	callout_drain(&enc->status_updater);
177 
178 	destroy_dev_sched_cb(enc->enc_dev, enc_devgonecb, periph);
179 }
180 
181 static void
182 enc_dtor(struct cam_periph *periph)
183 {
184 	struct enc_softc *enc;
185 
186 	enc = periph->softc;
187 
188 	/* If the sub-driver has a cleanup routine, call it */
189 	if (enc->enc_vec.softc_cleanup != NULL)
190 		enc->enc_vec.softc_cleanup(enc);
191 
192 	if (enc->enc_boot_hold_ch.ich_func != NULL) {
193 		config_intrhook_disestablish(&enc->enc_boot_hold_ch);
194 		enc->enc_boot_hold_ch.ich_func = NULL;
195 	}
196 
197 	ENC_FREE(enc);
198 }
199 
200 static void
201 enc_async(void *callback_arg, uint32_t code, struct cam_path *path, void *arg)
202 {
203 	struct cam_periph *periph;
204 
205 	periph = (struct cam_periph *)callback_arg;
206 
207 	switch(code) {
208 	case AC_FOUND_DEVICE:
209 	{
210 		struct ccb_getdev *cgd;
211 		cam_status status;
212 		path_id_t path_id;
213 
214 		cgd = (struct ccb_getdev *)arg;
215 		if (arg == NULL) {
216 			break;
217 		}
218 
219 		if (enc_type(cgd) == ENC_NONE) {
220 			/*
221 			 * Schedule announcement of the ENC bindings for
222 			 * this device if it is managed by a SEP.
223 			 */
224 			path_id = xpt_path_path_id(path);
225 			xpt_lock_buses();
226 			TAILQ_FOREACH(periph, &encdriver.units, unit_links) {
227 				struct enc_softc *softc;
228 
229 				softc = (struct enc_softc *)periph->softc;
230 				if (xpt_path_path_id(periph->path) != path_id
231 				 || softc == NULL
232 				 || (softc->enc_flags & ENC_FLAG_INITIALIZED)
233 				  == 0
234 				 || softc->enc_vec.device_found == NULL)
235 					continue;
236 
237 				softc->enc_vec.device_found(softc);
238 			}
239 			xpt_unlock_buses();
240 			return;
241 		}
242 
243 		status = cam_periph_alloc(enc_ctor, enc_oninvalidate,
244 		    enc_dtor, NULL, "ses", CAM_PERIPH_BIO,
245 		    path, enc_async, AC_FOUND_DEVICE, cgd);
246 
247 		if (status != CAM_REQ_CMP && status != CAM_REQ_INPROG) {
248 			printf("enc_async: Unable to probe new device due to "
249 			    "status 0x%x\n", status);
250 		}
251 		break;
252 	}
253 	default:
254 		cam_periph_async(periph, code, path, arg);
255 		break;
256 	}
257 }
258 
259 static int
260 enc_open(struct cdev *dev, int flags, int fmt, struct thread *td)
261 {
262 	struct cam_periph *periph;
263 	struct enc_softc *softc;
264 	int error = 0;
265 
266 	periph = (struct cam_periph *)dev->si_drv1;
267 	if (cam_periph_acquire(periph) != CAM_REQ_CMP)
268 		return (ENXIO);
269 
270 	cam_periph_lock(periph);
271 
272 	softc = (struct enc_softc *)periph->softc;
273 
274 	if ((softc->enc_flags & ENC_FLAG_INITIALIZED) == 0) {
275 		error = ENXIO;
276 		goto out;
277 	}
278 	if (softc->enc_flags & ENC_FLAG_INVALID) {
279 		error = ENXIO;
280 		goto out;
281 	}
282 out:
283 	if (error != 0)
284 		cam_periph_release_locked(periph);
285 	else
286 		softc->open_count++;
287 
288 	cam_periph_unlock(periph);
289 
290 	return (error);
291 }
292 
293 static int
294 enc_close(struct cdev *dev, int flag, int fmt, struct thread *td)
295 {
296 	struct cam_periph *periph;
297 	struct enc_softc  *enc;
298 	struct mtx *mtx;
299 
300 	periph = (struct cam_periph *)dev->si_drv1;
301 	mtx = cam_periph_mtx(periph);
302 	mtx_lock(mtx);
303 
304 	enc = periph->softc;
305 	enc->open_count--;
306 
307 	cam_periph_release_locked(periph);
308 
309 	/*
310 	 * We reference the lock directly here, instead of using
311 	 * cam_periph_unlock().  The reason is that the call to
312 	 * cam_periph_release_locked() above could result in the periph
313 	 * getting freed.  If that is the case, dereferencing the periph
314 	 * with a cam_periph_unlock() call would cause a page fault.
315 	 *
316 	 * cam_periph_release() avoids this problem using the same method,
317 	 * but we're manually acquiring and dropping the lock here to
318 	 * protect the open count and avoid another lock acquisition and
319 	 * release.
320 	 */
321 	mtx_unlock(mtx);
322 
323 	return (0);
324 }
325 
326 int
327 enc_error(union ccb *ccb, uint32_t cflags, uint32_t sflags)
328 {
329 	struct enc_softc *softc;
330 	struct cam_periph *periph;
331 
332 	periph = xpt_path_periph(ccb->ccb_h.path);
333 	softc = (struct enc_softc *)periph->softc;
334 
335 	return (cam_periph_error(ccb, cflags, sflags, &softc->saved_ccb));
336 }
337 
338 static int
339 enc_ioctl(struct cdev *dev, u_long cmd, caddr_t arg_addr, int flag,
340 	 struct thread *td)
341 {
342 	struct cam_periph *periph;
343 	encioc_enc_status_t tmp;
344 	encioc_string_t sstr;
345 	encioc_elm_status_t elms;
346 	encioc_elm_desc_t elmd;
347 	encioc_elm_devnames_t elmdn;
348 	encioc_element_t *uelm;
349 	enc_softc_t *enc;
350 	enc_cache_t *cache;
351 	void *addr;
352 	int error, i;
353 
354 
355 	if (arg_addr)
356 		addr = *((caddr_t *) arg_addr);
357 	else
358 		addr = NULL;
359 
360 	periph = (struct cam_periph *)dev->si_drv1;
361 	CAM_DEBUG(periph->path, CAM_DEBUG_TRACE, ("entering encioctl\n"));
362 
363 	cam_periph_lock(periph);
364 	enc = (struct enc_softc *)periph->softc;
365 	cache = &enc->enc_cache;
366 
367 	/*
368 	 * Now check to see whether we're initialized or not.
369 	 * This actually should never fail as we're not supposed
370 	 * to get past enc_open w/o successfully initializing
371 	 * things.
372 	 */
373 	if ((enc->enc_flags & ENC_FLAG_INITIALIZED) == 0) {
374 		cam_periph_unlock(periph);
375 		return (ENXIO);
376 	}
377 	cam_periph_unlock(periph);
378 
379 	error = 0;
380 
381 	CAM_DEBUG(periph->path, CAM_DEBUG_TRACE,
382 	    ("trying to do ioctl %#lx\n", cmd));
383 
384 	/*
385 	 * If this command can change the device's state,
386 	 * we must have the device open for writing.
387 	 *
388 	 * For commands that get information about the
389 	 * device- we don't need to lock the peripheral
390 	 * if we aren't running a command.  The periph
391 	 * also can't go away while a user process has
392 	 * it open.
393 	 */
394 	switch (cmd) {
395 	case ENCIOC_GETNELM:
396 	case ENCIOC_GETELMMAP:
397 	case ENCIOC_GETENCSTAT:
398 	case ENCIOC_GETELMSTAT:
399 	case ENCIOC_GETELMDESC:
400 	case ENCIOC_GETELMDEVNAMES:
401 	case ENCIOC_GETENCNAME:
402 	case ENCIOC_GETENCID:
403 		break;
404 	default:
405 		if ((flag & FWRITE) == 0) {
406 			return (EBADF);
407 		}
408 	}
409 
410 	/*
411 	 * XXX The values read here are only valid for the current
412 	 *     configuration generation.  We need these ioctls
413 	 *     to also pass in/out a generation number.
414 	 */
415 	sx_slock(&enc->enc_cache_lock);
416 	switch (cmd) {
417 	case ENCIOC_GETNELM:
418 		error = copyout(&cache->nelms, addr, sizeof (cache->nelms));
419 		break;
420 
421 	case ENCIOC_GETELMMAP:
422 		for (uelm = addr, i = 0; i != cache->nelms; i++) {
423 			encioc_element_t kelm;
424 			kelm.elm_idx = i;
425 			kelm.elm_subenc_id = cache->elm_map[i].subenclosure;
426 			kelm.elm_type = cache->elm_map[i].enctype;
427 			error = copyout(&kelm, &uelm[i], sizeof(kelm));
428 			if (error)
429 				break;
430 		}
431 		break;
432 
433 	case ENCIOC_GETENCSTAT:
434 		cam_periph_lock(periph);
435 		error = enc->enc_vec.get_enc_status(enc, 1);
436 		if (error) {
437 			cam_periph_unlock(periph);
438 			break;
439 		}
440 		tmp = cache->enc_status;
441 		cam_periph_unlock(periph);
442 		error = copyout(&tmp, addr, sizeof(tmp));
443 		cache->enc_status = tmp;
444 		break;
445 
446 	case ENCIOC_SETENCSTAT:
447 		error = copyin(addr, &tmp, sizeof(tmp));
448 		if (error)
449 			break;
450 		cam_periph_lock(periph);
451 		error = enc->enc_vec.set_enc_status(enc, tmp, 1);
452 		cam_periph_unlock(periph);
453 		break;
454 
455 	case ENCIOC_GETSTRING:
456 	case ENCIOC_SETSTRING:
457 	case ENCIOC_GETENCNAME:
458 	case ENCIOC_GETENCID:
459 		if (enc->enc_vec.handle_string == NULL) {
460 			error = EINVAL;
461 			break;
462 		}
463 		error = copyin(addr, &sstr, sizeof(sstr));
464 		if (error)
465 			break;
466 		cam_periph_lock(periph);
467 		error = enc->enc_vec.handle_string(enc, &sstr, cmd);
468 		cam_periph_unlock(periph);
469 		break;
470 
471 	case ENCIOC_GETELMSTAT:
472 		error = copyin(addr, &elms, sizeof(elms));
473 		if (error)
474 			break;
475 		if (elms.elm_idx >= cache->nelms) {
476 			error = EINVAL;
477 			break;
478 		}
479 		cam_periph_lock(periph);
480 		error = enc->enc_vec.get_elm_status(enc, &elms, 1);
481 		cam_periph_unlock(periph);
482 		if (error)
483 			break;
484 		error = copyout(&elms, addr, sizeof(elms));
485 		break;
486 
487 	case ENCIOC_GETELMDESC:
488 		error = copyin(addr, &elmd, sizeof(elmd));
489 		if (error)
490 			break;
491 		if (elmd.elm_idx >= cache->nelms) {
492 			error = EINVAL;
493 			break;
494 		}
495 		if (enc->enc_vec.get_elm_desc != NULL) {
496 			error = enc->enc_vec.get_elm_desc(enc, &elmd);
497 			if (error)
498 				break;
499 		} else
500 			elmd.elm_desc_len = 0;
501 		error = copyout(&elmd, addr, sizeof(elmd));
502 		break;
503 
504 	case ENCIOC_GETELMDEVNAMES:
505 		if (enc->enc_vec.get_elm_devnames == NULL) {
506 			error = EINVAL;
507 			break;
508 		}
509 		error = copyin(addr, &elmdn, sizeof(elmdn));
510 		if (error)
511 			break;
512 		if (elmdn.elm_idx >= cache->nelms) {
513 			error = EINVAL;
514 			break;
515 		}
516 		cam_periph_lock(periph);
517 		error = (*enc->enc_vec.get_elm_devnames)(enc, &elmdn);
518 		cam_periph_unlock(periph);
519 		if (error)
520 			break;
521 		error = copyout(&elmdn, addr, sizeof(elmdn));
522 		break;
523 
524 	case ENCIOC_SETELMSTAT:
525 		error = copyin(addr, &elms, sizeof(elms));
526 		if (error)
527 			break;
528 
529 		if (elms.elm_idx >= cache->nelms) {
530 			error = EINVAL;
531 			break;
532 		}
533 		cam_periph_lock(periph);
534 		error = enc->enc_vec.set_elm_status(enc, &elms, 1);
535 		cam_periph_unlock(periph);
536 
537 		break;
538 
539 	case ENCIOC_INIT:
540 
541 		cam_periph_lock(periph);
542 		error = enc->enc_vec.init_enc(enc);
543 		cam_periph_unlock(periph);
544 		break;
545 
546 	default:
547 		cam_periph_lock(periph);
548 		error = cam_periph_ioctl(periph, cmd, arg_addr, enc_error);
549 		cam_periph_unlock(periph);
550 		break;
551 	}
552 	sx_sunlock(&enc->enc_cache_lock);
553 	return (error);
554 }
555 
556 int
557 enc_runcmd(struct enc_softc *enc, char *cdb, int cdbl, char *dptr, int *dlenp)
558 {
559 	int error, dlen, tdlen;
560 	ccb_flags ddf;
561 	union ccb *ccb;
562 
563 	CAM_DEBUG(enc->periph->path, CAM_DEBUG_TRACE,
564 	    ("entering enc_runcmd\n"));
565 	if (dptr) {
566 		if ((dlen = *dlenp) < 0) {
567 			dlen = -dlen;
568 			ddf = CAM_DIR_OUT;
569 		} else {
570 			ddf = CAM_DIR_IN;
571 		}
572 	} else {
573 		dlen = 0;
574 		ddf = CAM_DIR_NONE;
575 	}
576 
577 	if (cdbl > IOCDBLEN) {
578 		cdbl = IOCDBLEN;
579 	}
580 
581 	ccb = cam_periph_getccb(enc->periph, CAM_PRIORITY_NORMAL);
582 	if (enc->enc_type == ENC_SEMB_SES || enc->enc_type == ENC_SEMB_SAFT) {
583 		tdlen = min(dlen, 1020);
584 		tdlen = (tdlen + 3) & ~3;
585 		cam_fill_ataio(&ccb->ataio, 0, NULL, ddf, 0, dptr, tdlen,
586 		    30 * 1000);
587 		if (cdb[0] == RECEIVE_DIAGNOSTIC)
588 			ata_28bit_cmd(&ccb->ataio,
589 			    ATA_SEP_ATTN, cdb[2], 0x02, tdlen / 4);
590 		else if (cdb[0] == SEND_DIAGNOSTIC)
591 			ata_28bit_cmd(&ccb->ataio,
592 			    ATA_SEP_ATTN, dlen > 0 ? dptr[0] : 0,
593 			    0x82, tdlen / 4);
594 		else if (cdb[0] == READ_BUFFER)
595 			ata_28bit_cmd(&ccb->ataio,
596 			    ATA_SEP_ATTN, cdb[2], 0x00, tdlen / 4);
597 		else
598 			ata_28bit_cmd(&ccb->ataio,
599 			    ATA_SEP_ATTN, dlen > 0 ? dptr[0] : 0,
600 			    0x80, tdlen / 4);
601 	} else {
602 		tdlen = dlen;
603 		cam_fill_csio(&ccb->csio, 0, NULL, ddf, MSG_SIMPLE_Q_TAG,
604 		    dptr, dlen, sizeof (struct scsi_sense_data), cdbl,
605 		    60 * 1000);
606 		bcopy(cdb, ccb->csio.cdb_io.cdb_bytes, cdbl);
607 	}
608 
609 	error = cam_periph_runccb(ccb, enc_error, ENC_CFLAGS, ENC_FLAGS, NULL);
610 	if (error) {
611 		if (dptr) {
612 			*dlenp = dlen;
613 		}
614 	} else {
615 		if (dptr) {
616 			if (ccb->ccb_h.func_code == XPT_ATA_IO)
617 				*dlenp = ccb->ataio.resid;
618 			else
619 				*dlenp = ccb->csio.resid;
620 			*dlenp += tdlen - dlen;
621 		}
622 	}
623 	xpt_release_ccb(ccb);
624 	CAM_DEBUG(enc->periph->path, CAM_DEBUG_SUBTRACE,
625 	    ("exiting enc_runcmd: *dlenp = %d\n", *dlenp));
626 	return (error);
627 }
628 
629 void
630 enc_log(struct enc_softc *enc, const char *fmt, ...)
631 {
632 	va_list ap;
633 
634 	printf("%s%d: ", enc->periph->periph_name, enc->periph->unit_number);
635 	va_start(ap, fmt);
636 	vprintf(fmt, ap);
637 	va_end(ap);
638 }
639 
640 /*
641  * The code after this point runs on many platforms,
642  * so forgive the slightly awkward and nonconforming
643  * appearance.
644  */
645 
646 /*
647  * Is this a device that supports enclosure services?
648  *
649  * It's a pretty simple ruleset- if it is device type
650  * 0x0D (13), it's an ENCLOSURE device.
651  */
652 
653 #define	SAFTE_START	44
654 #define	SAFTE_END	50
655 #define	SAFTE_LEN	SAFTE_END-SAFTE_START
656 
657 static enctyp
658 enc_type(struct ccb_getdev *cgd)
659 {
660 	int buflen;
661 	unsigned char *iqd;
662 
663 	if (cgd->protocol == PROTO_SEMB) {
664 		iqd = (unsigned char *)&cgd->ident_data;
665 		if (STRNCMP(iqd + 43, "S-E-S", 5) == 0)
666 			return (ENC_SEMB_SES);
667 		else if (STRNCMP(iqd + 43, "SAF-TE", 6) == 0)
668 			return (ENC_SEMB_SAFT);
669 		return (ENC_NONE);
670 
671 	} else if (cgd->protocol != PROTO_SCSI)
672 		return (ENC_NONE);
673 
674 	iqd = (unsigned char *)&cgd->inq_data;
675 	buflen = min(sizeof(cgd->inq_data),
676 	    SID_ADDITIONAL_LENGTH(&cgd->inq_data));
677 
678 	if ((iqd[0] & 0x1f) == T_ENCLOSURE) {
679 		if ((iqd[2] & 0x7) > 2) {
680 			return (ENC_SES);
681 		} else {
682 			return (ENC_SES_SCSI2);
683 		}
684 		return (ENC_NONE);
685 	}
686 
687 #ifdef	SES_ENABLE_PASSTHROUGH
688 	if ((iqd[6] & 0x40) && (iqd[2] & 0x7) >= 2) {
689 		/*
690 		 * PassThrough Device.
691 		 */
692 		return (ENC_SES_PASSTHROUGH);
693 	}
694 #endif
695 
696 	/*
697 	 * The comparison is short for a reason-
698 	 * some vendors were chopping it short.
699 	 */
700 
701 	if (buflen < SAFTE_END - 2) {
702 		return (ENC_NONE);
703 	}
704 
705 	if (STRNCMP((char *)&iqd[SAFTE_START], "SAF-TE", SAFTE_LEN - 2) == 0) {
706 		return (ENC_SAFT);
707 	}
708 	return (ENC_NONE);
709 }
710 
711 /*================== Enclosure Monitoring/Processing Daemon ==================*/
712 /**
713  * \brief Queue an update request for a given action, if needed.
714  *
715  * \param enc		SES softc to queue the request for.
716  * \param action	Action requested.
717  */
718 void
719 enc_update_request(enc_softc_t *enc, uint32_t action)
720 {
721 	if ((enc->pending_actions & (0x1 << action)) == 0) {
722 		enc->pending_actions |= (0x1 << action);
723 		ENC_DLOG(enc, "%s: queing requested action %d\n",
724 		    __func__, action);
725 		if (enc->current_action == ENC_UPDATE_NONE)
726 			wakeup(enc->enc_daemon);
727 	} else {
728 		ENC_DLOG(enc, "%s: ignoring requested action %d - "
729 		    "Already queued\n", __func__, action);
730 	}
731 }
732 
733 /**
734  * \brief Invoke the handler of the highest priority pending
735  *	  state in the SES state machine.
736  *
737  * \param enc  The SES instance invoking the state machine.
738  */
739 static void
740 enc_fsm_step(enc_softc_t *enc)
741 {
742 	union ccb            *ccb;
743 	uint8_t              *buf;
744 	struct enc_fsm_state *cur_state;
745 	int		      error;
746 	uint32_t	      xfer_len;
747 
748 	ENC_DLOG(enc, "%s enter %p\n", __func__, enc);
749 
750 	enc->current_action   = ffs(enc->pending_actions) - 1;
751 	enc->pending_actions &= ~(0x1 << enc->current_action);
752 
753 	cur_state = &enc->enc_fsm_states[enc->current_action];
754 
755 	buf = NULL;
756 	if (cur_state->buf_size != 0) {
757 		cam_periph_unlock(enc->periph);
758 		buf = malloc(cur_state->buf_size, M_SCSIENC, M_WAITOK|M_ZERO);
759 		cam_periph_lock(enc->periph);
760 	}
761 
762 	error = 0;
763 	ccb   = NULL;
764 	if (cur_state->fill != NULL) {
765 		ccb = cam_periph_getccb(enc->periph, CAM_PRIORITY_NORMAL);
766 
767 		error = cur_state->fill(enc, cur_state, ccb, buf);
768 		if (error != 0)
769 			goto done;
770 
771 		error = cam_periph_runccb(ccb, cur_state->error,
772 					  ENC_CFLAGS,
773 					  ENC_FLAGS|SF_QUIET_IR, NULL);
774 	}
775 
776 	if (ccb != NULL) {
777 		if (ccb->ccb_h.func_code == XPT_ATA_IO)
778 			xfer_len = ccb->ataio.dxfer_len - ccb->ataio.resid;
779 		else
780 			xfer_len = ccb->csio.dxfer_len - ccb->csio.resid;
781 	} else
782 		xfer_len = 0;
783 
784 	cam_periph_unlock(enc->periph);
785 	cur_state->done(enc, cur_state, ccb, &buf, error, xfer_len);
786 	cam_periph_lock(enc->periph);
787 
788 done:
789 	ENC_DLOG(enc, "%s exit - result %d\n", __func__, error);
790 	ENC_FREE_AND_NULL(buf);
791 	if (ccb != NULL)
792 		xpt_release_ccb(ccb);
793 }
794 
795 /**
796  * \invariant Called with cam_periph mutex held.
797  */
798 static void
799 enc_status_updater(void *arg)
800 {
801 	enc_softc_t *enc;
802 
803 	enc = arg;
804 	if (enc->enc_vec.poll_status != NULL)
805 		enc->enc_vec.poll_status(enc);
806 }
807 
808 static void
809 enc_daemon(void *arg)
810 {
811 	enc_softc_t *enc;
812 
813 	enc = arg;
814 
815 	cam_periph_lock(enc->periph);
816 	while ((enc->enc_flags & ENC_FLAG_SHUTDOWN) == 0) {
817 		if (enc->pending_actions == 0) {
818 			struct intr_config_hook *hook;
819 
820 			/*
821 			 * Reset callout and msleep, or
822 			 * issue timed task completion
823 			 * status command.
824 			 */
825 			enc->current_action = ENC_UPDATE_NONE;
826 
827 			/*
828 			 * We've been through our state machine at least
829 			 * once.  Allow the transition to userland.
830 			 */
831 			hook = &enc->enc_boot_hold_ch;
832 			if (hook->ich_func != NULL) {
833 				config_intrhook_disestablish(hook);
834 				hook->ich_func = NULL;
835 			}
836 
837 			callout_reset(&enc->status_updater, 60*hz,
838 				      enc_status_updater, enc);
839 
840 			cam_periph_sleep(enc->periph, enc->enc_daemon,
841 					 PUSER, "idle", 0);
842 		} else {
843 			enc_fsm_step(enc);
844 		}
845 	}
846 	enc->enc_daemon = NULL;
847 	cam_periph_unlock(enc->periph);
848 	cam_periph_release(enc->periph);
849 	kproc_exit(0);
850 }
851 
852 static int
853 enc_kproc_init(enc_softc_t *enc)
854 {
855 	int result;
856 
857 	callout_init_mtx(&enc->status_updater, cam_periph_mtx(enc->periph), 0);
858 
859 	if (cam_periph_acquire(enc->periph) != CAM_REQ_CMP)
860 		return (ENXIO);
861 
862 	result = kproc_create(enc_daemon, enc, &enc->enc_daemon, /*flags*/0,
863 			      /*stackpgs*/0, "enc_daemon%d",
864 			      enc->periph->unit_number);
865 	if (result == 0) {
866 		/* Do an initial load of all page data. */
867 		cam_periph_lock(enc->periph);
868 		enc->enc_vec.poll_status(enc);
869 		cam_periph_unlock(enc->periph);
870 	} else
871 		cam_periph_release(enc->periph);
872 	return (result);
873 }
874 
875 /**
876  * \brief Interrupt configuration hook callback associated with
877  *        enc_boot_hold_ch.
878  *
879  * Since interrupts are always functional at the time of enclosure
880  * configuration, there is nothing to be done when the callback occurs.
881  * This hook is only registered to hold up boot processing while initial
882  * eclosure processing occurs.
883  *
884  * \param arg  The enclosure softc, but currently unused in this callback.
885  */
886 static void
887 enc_nop_confighook_cb(void *arg __unused)
888 {
889 }
890 
891 static cam_status
892 enc_ctor(struct cam_periph *periph, void *arg)
893 {
894 	cam_status status = CAM_REQ_CMP_ERR;
895 	int err;
896 	enc_softc_t *enc;
897 	struct ccb_getdev *cgd;
898 	char *tname;
899 	struct make_dev_args args;
900 
901 	cgd = (struct ccb_getdev *)arg;
902 	if (cgd == NULL) {
903 		printf("enc_ctor: no getdev CCB, can't register device\n");
904 		goto out;
905 	}
906 
907 	enc = ENC_MALLOCZ(sizeof(*enc));
908 	if (enc == NULL) {
909 		printf("enc_ctor: Unable to probe new device. "
910 		       "Unable to allocate enc\n");
911 		goto out;
912 	}
913 	enc->periph = periph;
914 	enc->current_action = ENC_UPDATE_INVALID;
915 
916 	enc->enc_type = enc_type(cgd);
917 	sx_init(&enc->enc_cache_lock, "enccache");
918 
919 	switch (enc->enc_type) {
920 	case ENC_SES:
921 	case ENC_SES_SCSI2:
922 	case ENC_SES_PASSTHROUGH:
923 	case ENC_SEMB_SES:
924 		err = ses_softc_init(enc);
925 		break;
926 	case ENC_SAFT:
927 	case ENC_SEMB_SAFT:
928 		err = safte_softc_init(enc);
929 		break;
930 	case ENC_NONE:
931 	default:
932 		ENC_FREE(enc);
933 		return (CAM_REQ_CMP_ERR);
934 	}
935 
936 	if (err) {
937 		xpt_print(periph->path, "error %d initializing\n", err);
938 		goto out;
939 	}
940 
941 	/*
942 	 * Hold off userland until we have made at least one pass
943 	 * through our state machine so that physical path data is
944 	 * present.
945 	 */
946 	if (enc->enc_vec.poll_status != NULL) {
947 		enc->enc_boot_hold_ch.ich_func = enc_nop_confighook_cb;
948 		enc->enc_boot_hold_ch.ich_arg = enc;
949 		config_intrhook_establish(&enc->enc_boot_hold_ch);
950 	}
951 
952 	/*
953 	 * The softc field is set only once the enc is fully initialized
954 	 * so that we can rely on this field to detect partially
955 	 * initialized periph objects in the AC_FOUND_DEVICE handler.
956 	 */
957 	periph->softc = enc;
958 
959 	cam_periph_unlock(periph);
960 	if (enc->enc_vec.poll_status != NULL) {
961 		err = enc_kproc_init(enc);
962 		if (err) {
963 			xpt_print(periph->path,
964 				  "error %d starting enc_daemon\n", err);
965 			goto out;
966 		}
967 	}
968 
969 	/*
970 	 * Acquire a reference to the periph before we create the devfs
971 	 * instance for it.  We'll release this reference once the devfs
972 	 * instance has been freed.
973 	 */
974 	if (cam_periph_acquire(periph) != CAM_REQ_CMP) {
975 		xpt_print(periph->path, "%s: lost periph during "
976 			  "registration!\n", __func__);
977 		cam_periph_lock(periph);
978 
979 		return (CAM_REQ_CMP_ERR);
980 	}
981 
982 	make_dev_args_init(&args);
983 	args.mda_devsw = &enc_cdevsw;
984 	args.mda_unit = periph->unit_number;
985 	args.mda_uid = UID_ROOT;
986 	args.mda_gid = GID_OPERATOR;
987 	args.mda_mode = 0600;
988 	args.mda_si_drv1 = periph;
989 	err = make_dev_s(&args, &enc->enc_dev, "%s%d", periph->periph_name,
990 	    periph->unit_number);
991 	cam_periph_lock(periph);
992 	if (err != 0) {
993 		cam_periph_release_locked(periph);
994 		return (CAM_REQ_CMP_ERR);
995 	}
996 
997 	enc->enc_flags |= ENC_FLAG_INITIALIZED;
998 
999 	/*
1000 	 * Add an async callback so that we get notified if this
1001 	 * device goes away.
1002 	 */
1003 	xpt_register_async(AC_LOST_DEVICE, enc_async, periph, periph->path);
1004 
1005 	switch (enc->enc_type) {
1006 	default:
1007 	case ENC_NONE:
1008 		tname = "No ENC device";
1009 		break;
1010 	case ENC_SES_SCSI2:
1011 		tname = "SCSI-2 ENC Device";
1012 		break;
1013 	case ENC_SES:
1014 		tname = "SCSI-3 ENC Device";
1015 		break;
1016         case ENC_SES_PASSTHROUGH:
1017 		tname = "ENC Passthrough Device";
1018 		break;
1019         case ENC_SAFT:
1020 		tname = "SAF-TE Compliant Device";
1021 		break;
1022 	case ENC_SEMB_SES:
1023 		tname = "SEMB SES Device";
1024 		break;
1025 	case ENC_SEMB_SAFT:
1026 		tname = "SEMB SAF-TE Device";
1027 		break;
1028 	}
1029 	xpt_announce_periph(periph, tname);
1030 	status = CAM_REQ_CMP;
1031 
1032 out:
1033 	if (status != CAM_REQ_CMP)
1034 		enc_dtor(periph);
1035 	return (status);
1036 }
1037 
1038