scsi_enc.c revision 331633
117683Spst/*-
239291Sfenner * Copyright (c) 2000 Matthew Jacob
317683Spst * All rights reserved.
417683Spst *
517683Spst * Redistribution and use in source and binary forms, with or without
617683Spst * modification, are permitted provided that the following conditions
717683Spst * are met:
817683Spst * 1. Redistributions of source code must retain the above copyright
917683Spst *    notice, this list of conditions, and the following disclaimer,
1017683Spst *    without modification, immediately at the beginning of the file.
1117683Spst * 2. The name of the author may not be used to endorse or promote products
1217683Spst *    derived from this software without specific prior written permission.
1317683Spst *
1417683Spst * THIS SOFTWARE IS PROVIDED BY THE AUTHOR AND CONTRIBUTORS ``AS IS'' AND
1517683Spst * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
1617683Spst * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
1717683Spst * ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE FOR
1817683Spst * ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
1917683Spst * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
2026175Sfenner * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
2117683Spst * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
2217683Spst * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
2317683Spst * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
2417683Spst * SUCH DAMAGE.
2517683Spst */
2617683Spst
2717683Spst#include <sys/cdefs.h>
2817683Spst__FBSDID("$FreeBSD: stable/10/sys/cam/scsi/scsi_enc.c 331633 2018-03-27 17:43:03Z brooks $");
2917683Spst
3017683Spst#include "opt_compat.h"
3175107Sfenner
3275107Sfenner#include <sys/param.h>
3375107Sfenner
3475107Sfenner#include <sys/conf.h>
35214518Srpaulo#include <sys/errno.h>
36214518Srpaulo#include <sys/fcntl.h>
37214518Srpaulo#include <sys/kernel.h>
38214518Srpaulo#include <sys/kthread.h>
39214518Srpaulo#include <sys/lock.h>
40214518Srpaulo#include <sys/malloc.h>
41214518Srpaulo#include <sys/mutex.h>
42214518Srpaulo#include <sys/proc.h>
43214518Srpaulo#include <sys/queue.h>
44214518Srpaulo#include <sys/sx.h>
45214518Srpaulo#include <sys/sysent.h>
46214518Srpaulo#include <sys/systm.h>
47214518Srpaulo#include <sys/sysctl.h>
48214518Srpaulo#include <sys/types.h>
4917683Spst
5017683Spst#include <machine/stdarg.h>
5117683Spst
5217683Spst#include <cam/cam.h>
5375107Sfenner#include <cam/cam_ccb.h>
5417683Spst#include <cam/cam_debug.h>
5517683Spst#include <cam/cam_periph.h>
56190225Srpaulo#include <cam/cam_xpt_periph.h>
5717683Spst
5817683Spst#include <cam/scsi/scsi_all.h>
5917683Spst#include <cam/scsi/scsi_message.h>
6017683Spst#include <cam/scsi/scsi_enc.h>
6117683Spst#include <cam/scsi/scsi_enc_internal.h>
62214518Srpaulo
63214518Srpaulo#include <opt_ses.h>
6417683Spst
6517683SpstMALLOC_DEFINE(M_SCSIENC, "SCSI ENC", "SCSI ENC buffers");
66146768Ssam
67146768Ssam/* Enclosure type independent driver */
68146768Ssam
69147894Ssamstatic	d_open_t	enc_open;
70146768Ssamstatic	d_close_t	enc_close;
71146768Ssamstatic	d_ioctl_t	enc_ioctl;
72146768Ssamstatic	periph_init_t	enc_init;
73146768Ssamstatic  periph_ctor_t	enc_ctor;
74146768Ssamstatic	periph_oninv_t	enc_oninvalidate;
75146768Ssamstatic  periph_dtor_t   enc_dtor;
76146768Ssam
77146768Ssamstatic void enc_async(void *, uint32_t, struct cam_path *, void *);
7817683Spststatic enctyp enc_type(struct ccb_getdev *);
79127664Sbms
80127664SbmsSYSCTL_NODE(_kern_cam, OID_AUTO, enc, CTLFLAG_RD, 0,
81127664Sbms            "CAM Enclosure Services driver");
82127664Sbms
83127664Sbmsstatic struct periph_driver encdriver = {
84127664Sbms	enc_init, "ses",
85127664Sbms	TAILQ_HEAD_INITIALIZER(encdriver.units), /* generation */ 0
86127664Sbms};
87127664Sbms
88127664SbmsPERIPHDRIVER_DECLARE(enc, encdriver);
89127664Sbms
90127664Sbmsstatic struct cdevsw enc_cdevsw = {
91127664Sbms	.d_version =	D_VERSION,
92235426Sdelphij	.d_open =	enc_open,
93235426Sdelphij	.d_close =	enc_close,
94235426Sdelphij	.d_ioctl =	enc_ioctl,
95235426Sdelphij	.d_name =	"ses",
96235426Sdelphij	.d_flags =	D_TRACKCLOSE,
97235426Sdelphij};
98127664Sbms
99235426Sdelphijstatic void
100235426Sdelphijenc_init(void)
101235426Sdelphij{
102127664Sbms	cam_status status;
103127664Sbms
104127664Sbms	/*
105127664Sbms	 * Install a global async callback.  This callback will
106127664Sbms	 * receive async callbacks like "new device found".
107127664Sbms	 */
108127664Sbms	status = xpt_register_async(AC_FOUND_DEVICE, enc_async, NULL, NULL);
109127664Sbms
110127664Sbms	if (status != CAM_REQ_CMP) {
111127664Sbms		printf("enc: Failed to attach master async callback "
112190225Srpaulo		       "due to status 0x%x!\n", status);
113146768Ssam	}
114190225Srpaulo}
115190225Srpaulo
116190225Srpaulostatic void
117190225Srpauloenc_devgonecb(void *arg)
118190225Srpaulo{
119190225Srpaulo	struct cam_periph *periph;
120190225Srpaulo	struct enc_softc  *enc;
121190225Srpaulo	struct mtx *mtx;
122190225Srpaulo	int i;
123190225Srpaulo
124190225Srpaulo	periph = (struct cam_periph *)arg;
125190225Srpaulo	mtx = cam_periph_mtx(periph);
126190225Srpaulo	mtx_lock(mtx);
127190225Srpaulo	enc = (struct enc_softc *)periph->softc;
128190225Srpaulo
129190225Srpaulo	/*
130190225Srpaulo	 * When we get this callback, we will get no more close calls from
131190225Srpaulo	 * devfs.  So if we have any dangling opens, we need to release the
132190225Srpaulo	 * reference held for that particular context.
133190225Srpaulo	 */
134190225Srpaulo	for (i = 0; i < enc->open_count; i++)
135190225Srpaulo		cam_periph_release_locked(periph);
136190225Srpaulo
137190225Srpaulo	enc->open_count = 0;
138190225Srpaulo
139146768Ssam	/*
140146768Ssam	 * Release the reference held for the device node, it is gone now.
141146768Ssam	 */
142146768Ssam	cam_periph_release_locked(periph);
143146768Ssam
144146768Ssam	/*
145146768Ssam	 * We reference the lock directly here, instead of using
146147894Ssam	 * cam_periph_unlock().  The reason is that the final call to
147147894Ssam	 * cam_periph_release_locked() above could result in the periph
148147894Ssam	 * getting freed.  If that is the case, dereferencing the periph
149147894Ssam	 * with a cam_periph_unlock() call would cause a page fault.
150147894Ssam	 */
151162012Ssam	mtx_unlock(mtx);
152147894Ssam}
153147894Ssam
154147894Ssamstatic void
155147894Ssamenc_oninvalidate(struct cam_periph *periph)
156147894Ssam{
157147894Ssam	struct enc_softc *enc;
158276768Sdelphij
159190225Srpaulo	enc = periph->softc;
160127664Sbms
161276768Sdelphij	enc->enc_flags |= ENC_FLAG_INVALID;
162276768Sdelphij
163214518Srpaulo	/* If the sub-driver has an invalidate routine, call it */
164214518Srpaulo	if (enc->enc_vec.softc_invalidate != NULL)
165235426Sdelphij		enc->enc_vec.softc_invalidate(enc);
166127664Sbms
167127664Sbms	/*
16817683Spst	 * Unregister any async callbacks.
169276768Sdelphij	 */
170276768Sdelphij	xpt_register_async(0, enc_async, periph, periph->path);
17117683Spst
172146768Ssam	/*
173146768Ssam	 * Shutdown our daemon.
174146768Ssam	 */
175146768Ssam	enc->enc_flags |= ENC_FLAG_SHUTDOWN;
176147894Ssam	if (enc->enc_daemon != NULL) {
177146768Ssam		/* Signal the ses daemon to terminate. */
178147894Ssam		wakeup(enc->enc_daemon);
179147894Ssam	}
180147894Ssam	callout_drain(&enc->status_updater);
181147894Ssam
182147894Ssam	destroy_dev_sched_cb(enc->enc_dev, enc_devgonecb, periph);
183147894Ssam}
184147894Ssam
185147894Ssamstatic void
186146768Ssamenc_dtor(struct cam_periph *periph)
187146768Ssam{
188146768Ssam	struct enc_softc *enc;
189146768Ssam
190146768Ssam	enc = periph->softc;
191146768Ssam
192146768Ssam	/* If the sub-driver has a cleanup routine, call it */
193146768Ssam	if (enc->enc_vec.softc_cleanup != NULL)
194146768Ssam		enc->enc_vec.softc_cleanup(enc);
195146768Ssam
196146768Ssam	if (enc->enc_boot_hold_ch.ich_func != NULL) {
197146768Ssam		config_intrhook_disestablish(&enc->enc_boot_hold_ch);
198276768Sdelphij		enc->enc_boot_hold_ch.ich_func = NULL;
199146768Ssam	}
200146768Ssam
201146768Ssam	ENC_FREE(enc);
202146768Ssam}
203146768Ssam
204146768Ssamstatic void
205146768Ssamenc_async(void *callback_arg, uint32_t code, struct cam_path *path, void *arg)
206276768Sdelphij{
207276768Sdelphij	struct cam_periph *periph;
208276768Sdelphij
209276768Sdelphij	periph = (struct cam_periph *)callback_arg;
210276768Sdelphij
211276768Sdelphij	switch(code) {
212276768Sdelphij	case AC_FOUND_DEVICE:
213190225Srpaulo	{
214276768Sdelphij		struct ccb_getdev *cgd;
215276768Sdelphij		cam_status status;
216190225Srpaulo		path_id_t path_id;
217190225Srpaulo
218190225Srpaulo		cgd = (struct ccb_getdev *)arg;
219190225Srpaulo		if (arg == NULL) {
220190225Srpaulo			break;
221190225Srpaulo		}
222190225Srpaulo
223190225Srpaulo		if (enc_type(cgd) == ENC_NONE) {
224190225Srpaulo			/*
225190225Srpaulo			 * Schedule announcement of the ENC bindings for
226190225Srpaulo			 * this device if it is managed by a SEP.
227190225Srpaulo			 */
228190225Srpaulo			path_id = xpt_path_path_id(path);
229190225Srpaulo			xpt_lock_buses();
230190225Srpaulo			TAILQ_FOREACH(periph, &encdriver.units, unit_links) {
231190225Srpaulo				struct enc_softc *softc;
232190225Srpaulo
233190225Srpaulo				softc = (struct enc_softc *)periph->softc;
234276768Sdelphij				if (xpt_path_path_id(periph->path) != path_id
235276768Sdelphij				 || softc == NULL
236190225Srpaulo				 || (softc->enc_flags & ENC_FLAG_INITIALIZED)
237276768Sdelphij				  == 0
238276768Sdelphij				 || softc->enc_vec.device_found == NULL)
239276768Sdelphij					continue;
240276768Sdelphij
241276768Sdelphij				softc->enc_vec.device_found(softc);
242276768Sdelphij			}
243190225Srpaulo			xpt_unlock_buses();
244190225Srpaulo			return;
245276768Sdelphij		}
246214518Srpaulo
247214518Srpaulo		status = cam_periph_alloc(enc_ctor, enc_oninvalidate,
248214518Srpaulo		    enc_dtor, NULL, "ses", CAM_PERIPH_BIO,
249214518Srpaulo		    path, enc_async, AC_FOUND_DEVICE, cgd);
250214518Srpaulo
251214518Srpaulo		if (status != CAM_REQ_CMP && status != CAM_REQ_INPROG) {
252190225Srpaulo			printf("enc_async: Unable to probe new device due to "
253190225Srpaulo			    "status 0x%x\n", status);
254190225Srpaulo		}
255146768Ssam		break;
256276768Sdelphij	}
257276768Sdelphij	default:
258146768Ssam		cam_periph_async(periph, code, path, arg);
25917683Spst		break;
260214518Srpaulo	}
261146768Ssam}
262214518Srpaulo
263276768Sdelphijstatic int
26417683Spstenc_open(struct cdev *dev, int flags, int fmt, struct thread *td)
265214518Srpaulo{
266214518Srpaulo	struct cam_periph *periph;
267214518Srpaulo	struct enc_softc *softc;
268214518Srpaulo	int error = 0;
269214518Srpaulo
270214518Srpaulo	periph = (struct cam_periph *)dev->si_drv1;
271214518Srpaulo	if (cam_periph_acquire(periph) != CAM_REQ_CMP)
272214518Srpaulo		return (ENXIO);
273214518Srpaulo
274146768Ssam	cam_periph_lock(periph);
275146768Ssam
276146768Ssam	softc = (struct enc_softc *)periph->softc;
27775107Sfenner
278146768Ssam	if ((softc->enc_flags & ENC_FLAG_INITIALIZED) == 0) {
279146768Ssam		error = ENXIO;
280146768Ssam		goto out;
281214518Srpaulo	}
282146768Ssam	if (softc->enc_flags & ENC_FLAG_INVALID) {
28317683Spst		error = ENXIO;
284276768Sdelphij		goto out;
28517683Spst	}
286214518Srpauloout:
287214518Srpaulo	if (error != 0)
288214518Srpaulo		cam_periph_release_locked(periph);
289214518Srpaulo	else
290214518Srpaulo		softc->open_count++;
291276768Sdelphij
292276768Sdelphij	cam_periph_unlock(periph);
293276768Sdelphij
294276768Sdelphij	return (error);
295276768Sdelphij}
296276768Sdelphij
297214518Srpaulostatic int
298214518Srpauloenc_close(struct cdev *dev, int flag, int fmt, struct thread *td)
299214518Srpaulo{
300276768Sdelphij	struct cam_periph *periph;
30117683Spst	struct enc_softc  *enc;
30217683Spst	struct mtx *mtx;
30317683Spst
304214518Srpaulo	periph = (struct cam_periph *)dev->si_drv1;
305214518Srpaulo	mtx = cam_periph_mtx(periph);
306214518Srpaulo	mtx_lock(mtx);
307214518Srpaulo
308276768Sdelphij	enc = periph->softc;
30917683Spst	enc->open_count--;
310214518Srpaulo
311276768Sdelphij	cam_periph_release_locked(periph);
31217683Spst
313146768Ssam	/*
314146768Ssam	 * We reference the lock directly here, instead of using
31517683Spst	 * cam_periph_unlock().  The reason is that the call to
316146768Ssam	 * cam_periph_release_locked() above could result in the periph
317127664Sbms	 * getting freed.  If that is the case, dereferencing the periph
318127664Sbms	 * with a cam_periph_unlock() call would cause a page fault.
319127664Sbms	 *
320127664Sbms	 * cam_periph_release() avoids this problem using the same method,
321127664Sbms	 * but we're manually acquiring and dropping the lock here to
322127664Sbms	 * protect the open count and avoid another lock acquisition and
323127664Sbms	 * release.
324127664Sbms	 */
325127664Sbms	mtx_unlock(mtx);
326127664Sbms
327127664Sbms	return (0);
328146768Ssam}
329127664Sbms
330147894Ssamint
331127664Sbmsenc_error(union ccb *ccb, uint32_t cflags, uint32_t sflags)
332127664Sbms{
333127664Sbms	struct enc_softc *softc;
334127664Sbms	struct cam_periph *periph;
335190225Srpaulo
336190225Srpaulo	periph = xpt_path_periph(ccb->ccb_h.path);
337190225Srpaulo	softc = (struct enc_softc *)periph->softc;
338190225Srpaulo
339190225Srpaulo	return (cam_periph_error(ccb, cflags, sflags, &softc->saved_ccb));
340276768Sdelphij}
341276768Sdelphij
342276768Sdelphijstatic int
343276768Sdelphijenc_ioctl(struct cdev *dev, u_long cmd, caddr_t arg_addr, int flag,
344276768Sdelphij	 struct thread *td)
345276768Sdelphij{
346276768Sdelphij	struct cam_periph *periph;
347190225Srpaulo	encioc_enc_status_t tmp;
348127664Sbms	encioc_string_t sstr;
34917683Spst	encioc_elm_status_t elms;
35017683Spst	encioc_elm_desc_t elmd;
35117683Spst	encioc_elm_devnames_t elmdn;
352276768Sdelphij	encioc_element_t *uelm;
353276768Sdelphij	enc_softc_t *enc;
354276768Sdelphij	enc_cache_t *cache;
355276768Sdelphij	void *addr;
356276768Sdelphij	int error, i;
357276768Sdelphij
358276768Sdelphij#ifdef	COMPAT_FREEBSD32
359276768Sdelphij	if (SV_PROC_FLAG(td->td_proc, SV_ILP32))
360276768Sdelphij		return (ENOTTY);
361276768Sdelphij#endif
36217683Spst
363214518Srpaulo	if (arg_addr)
364214518Srpaulo		addr = *((caddr_t *) arg_addr);
36517683Spst	else
36617683Spst		addr = NULL;
36717683Spst
36817683Spst	periph = (struct cam_periph *)dev->si_drv1;
36917683Spst	CAM_DEBUG(periph->path, CAM_DEBUG_TRACE, ("entering encioctl\n"));
370146768Ssam
37117683Spst	cam_periph_lock(periph);
37217683Spst	enc = (struct enc_softc *)periph->softc;
373214518Srpaulo	cache = &enc->enc_cache;
37417683Spst
37517683Spst	/*
37617683Spst	 * Now check to see whether we're initialized or not.
37717683Spst	 * This actually should never fail as we're not supposed
378127664Sbms	 * to get past enc_open w/o successfully initializing
379127664Sbms	 * things.
380127664Sbms	 */
381127664Sbms	if ((enc->enc_flags & ENC_FLAG_INITIALIZED) == 0) {
382127664Sbms		cam_periph_unlock(periph);
383127664Sbms		return (ENXIO);
384127664Sbms	}
385127664Sbms	cam_periph_unlock(periph);
386127664Sbms
387127664Sbms	error = 0;
388127664Sbms
389127664Sbms	CAM_DEBUG(periph->path, CAM_DEBUG_TRACE,
390127664Sbms	    ("trying to do ioctl %#lx\n", cmd));
391127664Sbms
392127664Sbms	/*
393127664Sbms	 * If this command can change the device's state,
394127664Sbms	 * we must have the device open for writing.
395276768Sdelphij	 *
39617683Spst	 * For commands that get information about the
39717683Spst	 * device- we don't need to lock the peripheral
39817683Spst	 * if we aren't running a command.  The periph
39917683Spst	 * also can't go away while a user process has
40017683Spst	 * it open.
40117683Spst	 */
402146768Ssam	switch (cmd) {
403235426Sdelphij	case ENCIOC_GETNELM:
404214518Srpaulo	case ENCIOC_GETELMMAP:
40517683Spst	case ENCIOC_GETENCSTAT:
40617683Spst	case ENCIOC_GETELMSTAT:
40717683Spst	case ENCIOC_GETELMDESC:
40817683Spst	case ENCIOC_GETELMDEVNAMES:
40917683Spst	case ENCIOC_GETENCNAME:
41017683Spst	case ENCIOC_GETENCID:
41117683Spst		break;
412	default:
413		if ((flag & FWRITE) == 0) {
414			return (EBADF);
415		}
416	}
417
418	/*
419	 * XXX The values read here are only valid for the current
420	 *     configuration generation.  We need these ioctls
421	 *     to also pass in/out a generation number.
422	 */
423	sx_slock(&enc->enc_cache_lock);
424	switch (cmd) {
425	case ENCIOC_GETNELM:
426		error = copyout(&cache->nelms, addr, sizeof (cache->nelms));
427		break;
428
429	case ENCIOC_GETELMMAP:
430		for (uelm = addr, i = 0; i != cache->nelms; i++) {
431			encioc_element_t kelm;
432			kelm.elm_idx = i;
433			kelm.elm_subenc_id = cache->elm_map[i].subenclosure;
434			kelm.elm_type = cache->elm_map[i].enctype;
435			error = copyout(&kelm, &uelm[i], sizeof(kelm));
436			if (error)
437				break;
438		}
439		break;
440
441	case ENCIOC_GETENCSTAT:
442		cam_periph_lock(periph);
443		error = enc->enc_vec.get_enc_status(enc, 1);
444		if (error) {
445			cam_periph_unlock(periph);
446			break;
447		}
448		tmp = cache->enc_status;
449		cam_periph_unlock(periph);
450		error = copyout(&tmp, addr, sizeof(tmp));
451		cache->enc_status = tmp;
452		break;
453
454	case ENCIOC_SETENCSTAT:
455		error = copyin(addr, &tmp, sizeof(tmp));
456		if (error)
457			break;
458		cam_periph_lock(periph);
459		error = enc->enc_vec.set_enc_status(enc, tmp, 1);
460		cam_periph_unlock(periph);
461		break;
462
463	case ENCIOC_GETSTRING:
464	case ENCIOC_SETSTRING:
465	case ENCIOC_GETENCNAME:
466	case ENCIOC_GETENCID:
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		break;
478
479	case ENCIOC_GETELMSTAT:
480		error = copyin(addr, &elms, sizeof(elms));
481		if (error)
482			break;
483		if (elms.elm_idx >= cache->nelms) {
484			error = EINVAL;
485			break;
486		}
487		cam_periph_lock(periph);
488		error = enc->enc_vec.get_elm_status(enc, &elms, 1);
489		cam_periph_unlock(periph);
490		if (error)
491			break;
492		error = copyout(&elms, addr, sizeof(elms));
493		break;
494
495	case ENCIOC_GETELMDESC:
496		error = copyin(addr, &elmd, sizeof(elmd));
497		if (error)
498			break;
499		if (elmd.elm_idx >= cache->nelms) {
500			error = EINVAL;
501			break;
502		}
503		if (enc->enc_vec.get_elm_desc != NULL) {
504			error = enc->enc_vec.get_elm_desc(enc, &elmd);
505			if (error)
506				break;
507		} else
508			elmd.elm_desc_len = 0;
509		error = copyout(&elmd, addr, sizeof(elmd));
510		break;
511
512	case ENCIOC_GETELMDEVNAMES:
513		if (enc->enc_vec.get_elm_devnames == NULL) {
514			error = EINVAL;
515			break;
516		}
517		error = copyin(addr, &elmdn, sizeof(elmdn));
518		if (error)
519			break;
520		if (elmdn.elm_idx >= cache->nelms) {
521			error = EINVAL;
522			break;
523		}
524		cam_periph_lock(periph);
525		error = (*enc->enc_vec.get_elm_devnames)(enc, &elmdn);
526		cam_periph_unlock(periph);
527		if (error)
528			break;
529		error = copyout(&elmdn, addr, sizeof(elmdn));
530		break;
531
532	case ENCIOC_SETELMSTAT:
533		error = copyin(addr, &elms, sizeof(elms));
534		if (error)
535			break;
536
537		if (elms.elm_idx >= cache->nelms) {
538			error = EINVAL;
539			break;
540		}
541		cam_periph_lock(periph);
542		error = enc->enc_vec.set_elm_status(enc, &elms, 1);
543		cam_periph_unlock(periph);
544
545		break;
546
547	case ENCIOC_INIT:
548
549		cam_periph_lock(periph);
550		error = enc->enc_vec.init_enc(enc);
551		cam_periph_unlock(periph);
552		break;
553
554	default:
555		cam_periph_lock(periph);
556		error = cam_periph_ioctl(periph, cmd, arg_addr, enc_error);
557		cam_periph_unlock(periph);
558		break;
559	}
560	sx_sunlock(&enc->enc_cache_lock);
561	return (error);
562}
563
564int
565enc_runcmd(struct enc_softc *enc, char *cdb, int cdbl, char *dptr, int *dlenp)
566{
567	int error, dlen, tdlen;
568	ccb_flags ddf;
569	union ccb *ccb;
570
571	CAM_DEBUG(enc->periph->path, CAM_DEBUG_TRACE,
572	    ("entering enc_runcmd\n"));
573	if (dptr) {
574		if ((dlen = *dlenp) < 0) {
575			dlen = -dlen;
576			ddf = CAM_DIR_OUT;
577		} else {
578			ddf = CAM_DIR_IN;
579		}
580	} else {
581		dlen = 0;
582		ddf = CAM_DIR_NONE;
583	}
584
585	if (cdbl > IOCDBLEN) {
586		cdbl = IOCDBLEN;
587	}
588
589	ccb = cam_periph_getccb(enc->periph, CAM_PRIORITY_NORMAL);
590	if (enc->enc_type == ENC_SEMB_SES || enc->enc_type == ENC_SEMB_SAFT) {
591		tdlen = min(dlen, 1020);
592		tdlen = (tdlen + 3) & ~3;
593		cam_fill_ataio(&ccb->ataio, 0, NULL, ddf, 0, dptr, tdlen,
594		    30 * 1000);
595		if (cdb[0] == RECEIVE_DIAGNOSTIC)
596			ata_28bit_cmd(&ccb->ataio,
597			    ATA_SEP_ATTN, cdb[2], 0x02, tdlen / 4);
598		else if (cdb[0] == SEND_DIAGNOSTIC)
599			ata_28bit_cmd(&ccb->ataio,
600			    ATA_SEP_ATTN, dlen > 0 ? dptr[0] : 0,
601			    0x82, tdlen / 4);
602		else if (cdb[0] == READ_BUFFER)
603			ata_28bit_cmd(&ccb->ataio,
604			    ATA_SEP_ATTN, cdb[2], 0x00, tdlen / 4);
605		else
606			ata_28bit_cmd(&ccb->ataio,
607			    ATA_SEP_ATTN, dlen > 0 ? dptr[0] : 0,
608			    0x80, tdlen / 4);
609	} else {
610		tdlen = dlen;
611		cam_fill_csio(&ccb->csio, 0, NULL, ddf, MSG_SIMPLE_Q_TAG,
612		    dptr, dlen, sizeof (struct scsi_sense_data), cdbl,
613		    60 * 1000);
614		bcopy(cdb, ccb->csio.cdb_io.cdb_bytes, cdbl);
615	}
616
617	error = cam_periph_runccb(ccb, enc_error, ENC_CFLAGS, ENC_FLAGS, NULL);
618	if (error) {
619		if (dptr) {
620			*dlenp = dlen;
621		}
622	} else {
623		if (dptr) {
624			if (ccb->ccb_h.func_code == XPT_ATA_IO)
625				*dlenp = ccb->ataio.resid;
626			else
627				*dlenp = ccb->csio.resid;
628			*dlenp += tdlen - dlen;
629		}
630	}
631	xpt_release_ccb(ccb);
632	CAM_DEBUG(enc->periph->path, CAM_DEBUG_SUBTRACE,
633	    ("exiting enc_runcmd: *dlenp = %d\n", *dlenp));
634	return (error);
635}
636
637void
638enc_log(struct enc_softc *enc, const char *fmt, ...)
639{
640	va_list ap;
641
642	printf("%s%d: ", enc->periph->periph_name, enc->periph->unit_number);
643	va_start(ap, fmt);
644	vprintf(fmt, ap);
645	va_end(ap);
646}
647
648/*
649 * The code after this point runs on many platforms,
650 * so forgive the slightly awkward and nonconforming
651 * appearance.
652 */
653
654/*
655 * Is this a device that supports enclosure services?
656 *
657 * It's a pretty simple ruleset- if it is device type
658 * 0x0D (13), it's an ENCLOSURE device.
659 */
660
661#define	SAFTE_START	44
662#define	SAFTE_END	50
663#define	SAFTE_LEN	SAFTE_END-SAFTE_START
664
665static enctyp
666enc_type(struct ccb_getdev *cgd)
667{
668	int buflen;
669	unsigned char *iqd;
670
671	if (cgd->protocol == PROTO_SEMB) {
672		iqd = (unsigned char *)&cgd->ident_data;
673		if (STRNCMP(iqd + 43, "S-E-S", 5) == 0)
674			return (ENC_SEMB_SES);
675		else if (STRNCMP(iqd + 43, "SAF-TE", 6) == 0)
676			return (ENC_SEMB_SAFT);
677		return (ENC_NONE);
678
679	} else if (cgd->protocol != PROTO_SCSI)
680		return (ENC_NONE);
681
682	iqd = (unsigned char *)&cgd->inq_data;
683	buflen = min(sizeof(cgd->inq_data),
684	    SID_ADDITIONAL_LENGTH(&cgd->inq_data));
685
686	if ((iqd[0] & 0x1f) == T_ENCLOSURE) {
687		if ((iqd[2] & 0x7) > 2) {
688			return (ENC_SES);
689		} else {
690			return (ENC_SES_SCSI2);
691		}
692		return (ENC_NONE);
693	}
694
695#ifdef	SES_ENABLE_PASSTHROUGH
696	if ((iqd[6] & 0x40) && (iqd[2] & 0x7) >= 2) {
697		/*
698		 * PassThrough Device.
699		 */
700		return (ENC_SES_PASSTHROUGH);
701	}
702#endif
703
704	/*
705	 * The comparison is short for a reason-
706	 * some vendors were chopping it short.
707	 */
708
709	if (buflen < SAFTE_END - 2) {
710		return (ENC_NONE);
711	}
712
713	if (STRNCMP((char *)&iqd[SAFTE_START], "SAF-TE", SAFTE_LEN - 2) == 0) {
714		return (ENC_SAFT);
715	}
716	return (ENC_NONE);
717}
718
719/*================== Enclosure Monitoring/Processing Daemon ==================*/
720/**
721 * \brief Queue an update request for a given action, if needed.
722 *
723 * \param enc		SES softc to queue the request for.
724 * \param action	Action requested.
725 */
726void
727enc_update_request(enc_softc_t *enc, uint32_t action)
728{
729	if ((enc->pending_actions & (0x1 << action)) == 0) {
730		enc->pending_actions |= (0x1 << action);
731		ENC_DLOG(enc, "%s: queing requested action %d\n",
732		    __func__, action);
733		if (enc->current_action == ENC_UPDATE_NONE)
734			wakeup(enc->enc_daemon);
735	} else {
736		ENC_DLOG(enc, "%s: ignoring requested action %d - "
737		    "Already queued\n", __func__, action);
738	}
739}
740
741/**
742 * \brief Invoke the handler of the highest priority pending
743 *	  state in the SES state machine.
744 *
745 * \param enc  The SES instance invoking the state machine.
746 */
747static void
748enc_fsm_step(enc_softc_t *enc)
749{
750	union ccb            *ccb;
751	uint8_t              *buf;
752	struct enc_fsm_state *cur_state;
753	int		      error;
754	uint32_t	      xfer_len;
755
756	ENC_DLOG(enc, "%s enter %p\n", __func__, enc);
757
758	enc->current_action   = ffs(enc->pending_actions) - 1;
759	enc->pending_actions &= ~(0x1 << enc->current_action);
760
761	cur_state = &enc->enc_fsm_states[enc->current_action];
762
763	buf = NULL;
764	if (cur_state->buf_size != 0) {
765		cam_periph_unlock(enc->periph);
766		buf = malloc(cur_state->buf_size, M_SCSIENC, M_WAITOK|M_ZERO);
767		cam_periph_lock(enc->periph);
768	}
769
770	error = 0;
771	ccb   = NULL;
772	if (cur_state->fill != NULL) {
773		ccb = cam_periph_getccb(enc->periph, CAM_PRIORITY_NORMAL);
774
775		error = cur_state->fill(enc, cur_state, ccb, buf);
776		if (error != 0)
777			goto done;
778
779		error = cam_periph_runccb(ccb, cur_state->error,
780					  ENC_CFLAGS,
781					  ENC_FLAGS|SF_QUIET_IR, NULL);
782	}
783
784	if (ccb != NULL) {
785		if (ccb->ccb_h.func_code == XPT_ATA_IO)
786			xfer_len = ccb->ataio.dxfer_len - ccb->ataio.resid;
787		else
788			xfer_len = ccb->csio.dxfer_len - ccb->csio.resid;
789	} else
790		xfer_len = 0;
791
792	cam_periph_unlock(enc->periph);
793	cur_state->done(enc, cur_state, ccb, &buf, error, xfer_len);
794	cam_periph_lock(enc->periph);
795
796done:
797	ENC_DLOG(enc, "%s exit - result %d\n", __func__, error);
798	ENC_FREE_AND_NULL(buf);
799	if (ccb != NULL)
800		xpt_release_ccb(ccb);
801}
802
803/**
804 * \invariant Called with cam_periph mutex held.
805 */
806static void
807enc_status_updater(void *arg)
808{
809	enc_softc_t *enc;
810
811	enc = arg;
812	if (enc->enc_vec.poll_status != NULL)
813		enc->enc_vec.poll_status(enc);
814}
815
816static void
817enc_daemon(void *arg)
818{
819	enc_softc_t *enc;
820
821	enc = arg;
822
823	cam_periph_lock(enc->periph);
824	while ((enc->enc_flags & ENC_FLAG_SHUTDOWN) == 0) {
825		if (enc->pending_actions == 0) {
826			struct intr_config_hook *hook;
827
828			/*
829			 * Reset callout and msleep, or
830			 * issue timed task completion
831			 * status command.
832			 */
833			enc->current_action = ENC_UPDATE_NONE;
834
835			/*
836			 * We've been through our state machine at least
837			 * once.  Allow the transition to userland.
838			 */
839			hook = &enc->enc_boot_hold_ch;
840			if (hook->ich_func != NULL) {
841				config_intrhook_disestablish(hook);
842				hook->ich_func = NULL;
843			}
844
845			callout_reset(&enc->status_updater, 60*hz,
846				      enc_status_updater, enc);
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
860static int
861enc_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) != CAM_REQ_CMP)
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/**
884 * \brief Interrupt configuration hook callback associated with
885 *        enc_boot_hold_ch.
886 *
887 * Since interrupts are always functional at the time of enclosure
888 * configuration, there is nothing to be done when the callback occurs.
889 * This hook is only registered to hold up boot processing while initial
890 * eclosure processing occurs.
891 *
892 * \param arg  The enclosure softc, but currently unused in this callback.
893 */
894static void
895enc_nop_confighook_cb(void *arg __unused)
896{
897}
898
899static cam_status
900enc_ctor(struct cam_periph *periph, void *arg)
901{
902	cam_status status = CAM_REQ_CMP_ERR;
903	int err;
904	enc_softc_t *enc;
905	struct ccb_getdev *cgd;
906	char *tname;
907	struct make_dev_args args;
908
909	cgd = (struct ccb_getdev *)arg;
910	if (cgd == NULL) {
911		printf("enc_ctor: no getdev CCB, can't register device\n");
912		goto out;
913	}
914
915	enc = ENC_MALLOCZ(sizeof(*enc));
916	if (enc == NULL) {
917		printf("enc_ctor: Unable to probe new device. "
918		       "Unable to allocate enc\n");
919		goto out;
920	}
921	enc->periph = periph;
922	enc->current_action = ENC_UPDATE_INVALID;
923
924	enc->enc_type = enc_type(cgd);
925	sx_init(&enc->enc_cache_lock, "enccache");
926
927	switch (enc->enc_type) {
928	case ENC_SES:
929	case ENC_SES_SCSI2:
930	case ENC_SES_PASSTHROUGH:
931	case ENC_SEMB_SES:
932		err = ses_softc_init(enc);
933		break;
934	case ENC_SAFT:
935	case ENC_SEMB_SAFT:
936		err = safte_softc_init(enc);
937		break;
938	case ENC_NONE:
939	default:
940		ENC_FREE(enc);
941		return (CAM_REQ_CMP_ERR);
942	}
943
944	if (err) {
945		xpt_print(periph->path, "error %d initializing\n", err);
946		goto out;
947	}
948
949	/*
950	 * Hold off userland until we have made at least one pass
951	 * through our state machine so that physical path data is
952	 * present.
953	 */
954	if (enc->enc_vec.poll_status != NULL) {
955		enc->enc_boot_hold_ch.ich_func = enc_nop_confighook_cb;
956		enc->enc_boot_hold_ch.ich_arg = enc;
957		config_intrhook_establish(&enc->enc_boot_hold_ch);
958	}
959
960	/*
961	 * The softc field is set only once the enc is fully initialized
962	 * so that we can rely on this field to detect partially
963	 * initialized periph objects in the AC_FOUND_DEVICE handler.
964	 */
965	periph->softc = enc;
966
967	cam_periph_unlock(periph);
968	if (enc->enc_vec.poll_status != NULL) {
969		err = enc_kproc_init(enc);
970		if (err) {
971			xpt_print(periph->path,
972				  "error %d starting enc_daemon\n", err);
973			goto out;
974		}
975	}
976
977	/*
978	 * Acquire a reference to the periph before we create the devfs
979	 * instance for it.  We'll release this reference once the devfs
980	 * instance has been freed.
981	 */
982	if (cam_periph_acquire(periph) != CAM_REQ_CMP) {
983		xpt_print(periph->path, "%s: lost periph during "
984			  "registration!\n", __func__);
985		cam_periph_lock(periph);
986
987		return (CAM_REQ_CMP_ERR);
988	}
989
990	make_dev_args_init(&args);
991	args.mda_devsw = &enc_cdevsw;
992	args.mda_unit = periph->unit_number;
993	args.mda_uid = UID_ROOT;
994	args.mda_gid = GID_OPERATOR;
995	args.mda_mode = 0600;
996	args.mda_si_drv1 = periph;
997	err = make_dev_s(&args, &enc->enc_dev, "%s%d", periph->periph_name,
998	    periph->unit_number);
999	cam_periph_lock(periph);
1000	if (err != 0) {
1001		cam_periph_release_locked(periph);
1002		return (CAM_REQ_CMP_ERR);
1003	}
1004
1005	enc->enc_flags |= ENC_FLAG_INITIALIZED;
1006
1007	/*
1008	 * Add an async callback so that we get notified if this
1009	 * device goes away.
1010	 */
1011	xpt_register_async(AC_LOST_DEVICE, enc_async, periph, periph->path);
1012
1013	switch (enc->enc_type) {
1014	default:
1015	case ENC_NONE:
1016		tname = "No ENC device";
1017		break;
1018	case ENC_SES_SCSI2:
1019		tname = "SCSI-2 ENC Device";
1020		break;
1021	case ENC_SES:
1022		tname = "SCSI-3 ENC Device";
1023		break;
1024        case ENC_SES_PASSTHROUGH:
1025		tname = "ENC Passthrough Device";
1026		break;
1027        case ENC_SAFT:
1028		tname = "SAF-TE Compliant Device";
1029		break;
1030	case ENC_SEMB_SES:
1031		tname = "SEMB SES Device";
1032		break;
1033	case ENC_SEMB_SAFT:
1034		tname = "SEMB SAF-TE Device";
1035		break;
1036	}
1037	xpt_announce_periph(periph, tname);
1038	status = CAM_REQ_CMP;
1039
1040out:
1041	if (status != CAM_REQ_CMP)
1042		enc_dtor(periph);
1043	return (status);
1044}
1045
1046