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