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