1/*-
2 * Copyright (c) 2000 Matthew Jacob
3 * All rights reserved.
4 *
5 * Redistribution and use in source and binary forms, with or without
6 * modification, are permitted provided that the following conditions
7 * are met:
8 * 1. Redistributions of source code must retain the above copyright
9 *    notice, this list of conditions, and the following disclaimer,
10 *    without modification, immediately at the beginning of the file.
11 * 2. The name of the author may not be used to endorse or promote products
12 *    derived from this software without specific prior written permission.
13 *
14 * THIS SOFTWARE IS PROVIDED BY THE AUTHOR AND CONTRIBUTORS ``AS IS'' AND
15 * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
16 * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
17 * ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE FOR
18 * ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
19 * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
20 * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
21 * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
22 * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
23 * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
24 * SUCH DAMAGE.
25 */
26
27#include <sys/cdefs.h>
28__FBSDID("$FreeBSD: stable/10/sys/cam/scsi/scsi_enc.c 331633 2018-03-27 17:43:03Z brooks $");
29
30#include "opt_compat.h"
31
32#include <sys/param.h>
33
34#include <sys/conf.h>
35#include <sys/errno.h>
36#include <sys/fcntl.h>
37#include <sys/kernel.h>
38#include <sys/kthread.h>
39#include <sys/lock.h>
40#include <sys/malloc.h>
41#include <sys/mutex.h>
42#include <sys/proc.h>
43#include <sys/queue.h>
44#include <sys/sx.h>
45#include <sys/sysent.h>
46#include <sys/systm.h>
47#include <sys/sysctl.h>
48#include <sys/types.h>
49
50#include <machine/stdarg.h>
51
52#include <cam/cam.h>
53#include <cam/cam_ccb.h>
54#include <cam/cam_debug.h>
55#include <cam/cam_periph.h>
56#include <cam/cam_xpt_periph.h>
57
58#include <cam/scsi/scsi_all.h>
59#include <cam/scsi/scsi_message.h>
60#include <cam/scsi/scsi_enc.h>
61#include <cam/scsi/scsi_enc_internal.h>
62
63#include <opt_ses.h>
64
65MALLOC_DEFINE(M_SCSIENC, "SCSI ENC", "SCSI ENC buffers");
66
67/* Enclosure type independent driver */
68
69static	d_open_t	enc_open;
70static	d_close_t	enc_close;
71static	d_ioctl_t	enc_ioctl;
72static	periph_init_t	enc_init;
73static  periph_ctor_t	enc_ctor;
74static	periph_oninv_t	enc_oninvalidate;
75static  periph_dtor_t   enc_dtor;
76
77static void enc_async(void *, uint32_t, struct cam_path *, void *);
78static enctyp enc_type(struct ccb_getdev *);
79
80SYSCTL_NODE(_kern_cam, OID_AUTO, enc, CTLFLAG_RD, 0,
81            "CAM Enclosure Services driver");
82
83static struct periph_driver encdriver = {
84	enc_init, "ses",
85	TAILQ_HEAD_INITIALIZER(encdriver.units), /* generation */ 0
86};
87
88PERIPHDRIVER_DECLARE(enc, encdriver);
89
90static struct cdevsw enc_cdevsw = {
91	.d_version =	D_VERSION,
92	.d_open =	enc_open,
93	.d_close =	enc_close,
94	.d_ioctl =	enc_ioctl,
95	.d_name =	"ses",
96	.d_flags =	D_TRACKCLOSE,
97};
98
99static void
100enc_init(void)
101{
102	cam_status status;
103
104	/*
105	 * Install a global async callback.  This callback will
106	 * receive async callbacks like "new device found".
107	 */
108	status = xpt_register_async(AC_FOUND_DEVICE, enc_async, NULL, NULL);
109
110	if (status != CAM_REQ_CMP) {
111		printf("enc: Failed to attach master async callback "
112		       "due to status 0x%x!\n", status);
113	}
114}
115
116static void
117enc_devgonecb(void *arg)
118{
119	struct cam_periph *periph;
120	struct enc_softc  *enc;
121	struct mtx *mtx;
122	int i;
123
124	periph = (struct cam_periph *)arg;
125	mtx = cam_periph_mtx(periph);
126	mtx_lock(mtx);
127	enc = (struct enc_softc *)periph->softc;
128
129	/*
130	 * When we get this callback, we will get no more close calls from
131	 * devfs.  So if we have any dangling opens, we need to release the
132	 * reference held for that particular context.
133	 */
134	for (i = 0; i < enc->open_count; i++)
135		cam_periph_release_locked(periph);
136
137	enc->open_count = 0;
138
139	/*
140	 * Release the reference held for the device node, it is gone now.
141	 */
142	cam_periph_release_locked(periph);
143
144	/*
145	 * We reference the lock directly here, instead of using
146	 * cam_periph_unlock().  The reason is that the final call to
147	 * cam_periph_release_locked() above could result in the periph
148	 * getting freed.  If that is the case, dereferencing the periph
149	 * with a cam_periph_unlock() call would cause a page fault.
150	 */
151	mtx_unlock(mtx);
152}
153
154static void
155enc_oninvalidate(struct cam_periph *periph)
156{
157	struct enc_softc *enc;
158
159	enc = periph->softc;
160
161	enc->enc_flags |= ENC_FLAG_INVALID;
162
163	/* If the sub-driver has an invalidate routine, call it */
164	if (enc->enc_vec.softc_invalidate != NULL)
165		enc->enc_vec.softc_invalidate(enc);
166
167	/*
168	 * Unregister any async callbacks.
169	 */
170	xpt_register_async(0, enc_async, periph, periph->path);
171
172	/*
173	 * Shutdown our daemon.
174	 */
175	enc->enc_flags |= ENC_FLAG_SHUTDOWN;
176	if (enc->enc_daemon != NULL) {
177		/* Signal the ses daemon to terminate. */
178		wakeup(enc->enc_daemon);
179	}
180	callout_drain(&enc->status_updater);
181
182	destroy_dev_sched_cb(enc->enc_dev, enc_devgonecb, periph);
183}
184
185static void
186enc_dtor(struct cam_periph *periph)
187{
188	struct enc_softc *enc;
189
190	enc = periph->softc;
191
192	/* If the sub-driver has a cleanup routine, call it */
193	if (enc->enc_vec.softc_cleanup != NULL)
194		enc->enc_vec.softc_cleanup(enc);
195
196	if (enc->enc_boot_hold_ch.ich_func != NULL) {
197		config_intrhook_disestablish(&enc->enc_boot_hold_ch);
198		enc->enc_boot_hold_ch.ich_func = NULL;
199	}
200
201	ENC_FREE(enc);
202}
203
204static void
205enc_async(void *callback_arg, uint32_t code, struct cam_path *path, void *arg)
206{
207	struct cam_periph *periph;
208
209	periph = (struct cam_periph *)callback_arg;
210
211	switch(code) {
212	case AC_FOUND_DEVICE:
213	{
214		struct ccb_getdev *cgd;
215		cam_status status;
216		path_id_t path_id;
217
218		cgd = (struct ccb_getdev *)arg;
219		if (arg == NULL) {
220			break;
221		}
222
223		if (enc_type(cgd) == ENC_NONE) {
224			/*
225			 * Schedule announcement of the ENC bindings for
226			 * this device if it is managed by a SEP.
227			 */
228			path_id = xpt_path_path_id(path);
229			xpt_lock_buses();
230			TAILQ_FOREACH(periph, &encdriver.units, unit_links) {
231				struct enc_softc *softc;
232
233				softc = (struct enc_softc *)periph->softc;
234				if (xpt_path_path_id(periph->path) != path_id
235				 || softc == NULL
236				 || (softc->enc_flags & ENC_FLAG_INITIALIZED)
237				  == 0
238				 || softc->enc_vec.device_found == NULL)
239					continue;
240
241				softc->enc_vec.device_found(softc);
242			}
243			xpt_unlock_buses();
244			return;
245		}
246
247		status = cam_periph_alloc(enc_ctor, enc_oninvalidate,
248		    enc_dtor, NULL, "ses", CAM_PERIPH_BIO,
249		    path, enc_async, AC_FOUND_DEVICE, cgd);
250
251		if (status != CAM_REQ_CMP && status != CAM_REQ_INPROG) {
252			printf("enc_async: Unable to probe new device due to "
253			    "status 0x%x\n", status);
254		}
255		break;
256	}
257	default:
258		cam_periph_async(periph, code, path, arg);
259		break;
260	}
261}
262
263static int
264enc_open(struct cdev *dev, int flags, int fmt, struct thread *td)
265{
266	struct cam_periph *periph;
267	struct enc_softc *softc;
268	int error = 0;
269
270	periph = (struct cam_periph *)dev->si_drv1;
271	if (cam_periph_acquire(periph) != CAM_REQ_CMP)
272		return (ENXIO);
273
274	cam_periph_lock(periph);
275
276	softc = (struct enc_softc *)periph->softc;
277
278	if ((softc->enc_flags & ENC_FLAG_INITIALIZED) == 0) {
279		error = ENXIO;
280		goto out;
281	}
282	if (softc->enc_flags & ENC_FLAG_INVALID) {
283		error = ENXIO;
284		goto out;
285	}
286out:
287	if (error != 0)
288		cam_periph_release_locked(periph);
289	else
290		softc->open_count++;
291
292	cam_periph_unlock(periph);
293
294	return (error);
295}
296
297static int
298enc_close(struct cdev *dev, int flag, int fmt, struct thread *td)
299{
300	struct cam_periph *periph;
301	struct enc_softc  *enc;
302	struct mtx *mtx;
303
304	periph = (struct cam_periph *)dev->si_drv1;
305	mtx = cam_periph_mtx(periph);
306	mtx_lock(mtx);
307
308	enc = periph->softc;
309	enc->open_count--;
310
311	cam_periph_release_locked(periph);
312
313	/*
314	 * We reference the lock directly here, instead of using
315	 * cam_periph_unlock().  The reason is that the call to
316	 * cam_periph_release_locked() above could result in the periph
317	 * getting freed.  If that is the case, dereferencing the periph
318	 * with a cam_periph_unlock() call would cause a page fault.
319	 *
320	 * cam_periph_release() avoids this problem using the same method,
321	 * but we're manually acquiring and dropping the lock here to
322	 * protect the open count and avoid another lock acquisition and
323	 * release.
324	 */
325	mtx_unlock(mtx);
326
327	return (0);
328}
329
330int
331enc_error(union ccb *ccb, uint32_t cflags, uint32_t sflags)
332{
333	struct enc_softc *softc;
334	struct cam_periph *periph;
335
336	periph = xpt_path_periph(ccb->ccb_h.path);
337	softc = (struct enc_softc *)periph->softc;
338
339	return (cam_periph_error(ccb, cflags, sflags, &softc->saved_ccb));
340}
341
342static int
343enc_ioctl(struct cdev *dev, u_long cmd, caddr_t arg_addr, int flag,
344	 struct thread *td)
345{
346	struct cam_periph *periph;
347	encioc_enc_status_t tmp;
348	encioc_string_t sstr;
349	encioc_elm_status_t elms;
350	encioc_elm_desc_t elmd;
351	encioc_elm_devnames_t elmdn;
352	encioc_element_t *uelm;
353	enc_softc_t *enc;
354	enc_cache_t *cache;
355	void *addr;
356	int error, i;
357
358#ifdef	COMPAT_FREEBSD32
359	if (SV_PROC_FLAG(td->td_proc, SV_ILP32))
360		return (ENOTTY);
361#endif
362
363	if (arg_addr)
364		addr = *((caddr_t *) arg_addr);
365	else
366		addr = NULL;
367
368	periph = (struct cam_periph *)dev->si_drv1;
369	CAM_DEBUG(periph->path, CAM_DEBUG_TRACE, ("entering encioctl\n"));
370
371	cam_periph_lock(periph);
372	enc = (struct enc_softc *)periph->softc;
373	cache = &enc->enc_cache;
374
375	/*
376	 * Now check to see whether we're initialized or not.
377	 * This actually should never fail as we're not supposed
378	 * to get past enc_open w/o successfully initializing
379	 * things.
380	 */
381	if ((enc->enc_flags & ENC_FLAG_INITIALIZED) == 0) {
382		cam_periph_unlock(periph);
383		return (ENXIO);
384	}
385	cam_periph_unlock(periph);
386
387	error = 0;
388
389	CAM_DEBUG(periph->path, CAM_DEBUG_TRACE,
390	    ("trying to do ioctl %#lx\n", cmd));
391
392	/*
393	 * If this command can change the device's state,
394	 * we must have the device open for writing.
395	 *
396	 * For commands that get information about the
397	 * device- we don't need to lock the peripheral
398	 * if we aren't running a command.  The periph
399	 * also can't go away while a user process has
400	 * it open.
401	 */
402	switch (cmd) {
403	case ENCIOC_GETNELM:
404	case ENCIOC_GETELMMAP:
405	case ENCIOC_GETENCSTAT:
406	case ENCIOC_GETELMSTAT:
407	case ENCIOC_GETELMDESC:
408	case ENCIOC_GETELMDEVNAMES:
409	case ENCIOC_GETENCNAME:
410	case ENCIOC_GETENCID:
411		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