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