scsi_enc_ses.c revision 320474
118334Speter/*-
2169689Skan * Copyright (c) 2000 Matthew Jacob
390075Sobrien * Copyright (c) 2010 Spectra Logic Corporation
418334Speter * All rights reserved.
590075Sobrien *
618334Speter * Redistribution and use in source and binary forms, with or without
790075Sobrien * modification, are permitted provided that the following conditions
890075Sobrien * are met:
990075Sobrien * 1. Redistributions of source code must retain the above copyright
1090075Sobrien *    notice, this list of conditions, and the following disclaimer,
1118334Speter *    without modification, immediately at the beginning of the file.
1290075Sobrien * 2. The name of the author may not be used to endorse or promote products
1390075Sobrien *    derived from this software without specific prior written permission.
1490075Sobrien *
1590075Sobrien * THIS SOFTWARE IS PROVIDED BY THE AUTHOR AND CONTRIBUTORS ``AS IS'' AND
1618334Speter * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
1718334Speter * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
1890075Sobrien * ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE FOR
19169689Skan * ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
20169689Skan * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
2118334Speter * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
2290075Sobrien * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
2390075Sobrien * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
2452284Sobrien * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
25169689Skan * SUCH DAMAGE.
26169689Skan */
27169689Skan
28169689Skan/**
29169689Skan * \file scsi_enc_ses.c
30169689Skan *
31169689Skan * Structures and routines specific && private to SES only
32169689Skan */
33169689Skan
34169689Skan#include <sys/cdefs.h>
35169689Skan__FBSDID("$FreeBSD: stable/10/sys/cam/scsi/scsi_enc_ses.c 320474 2017-06-29 17:29:07Z markj $");
36169689Skan
37169689Skan#include <sys/param.h>
38169689Skan
39169689Skan#include <sys/ctype.h>
40169689Skan#include <sys/errno.h>
41169689Skan#include <sys/kernel.h>
42169689Skan#include <sys/lock.h>
43169689Skan#include <sys/malloc.h>
44169689Skan#include <sys/mutex.h>
45169689Skan#include <sys/queue.h>
46169689Skan#include <sys/sbuf.h>
47169689Skan#include <sys/sx.h>
48169689Skan#include <sys/systm.h>
49169689Skan#include <sys/types.h>
50169689Skan
51169689Skan#include <cam/cam.h>
52117395Skan#include <cam/cam_ccb.h>
53117395Skan#include <cam/cam_xpt_periph.h>
54117395Skan#include <cam/cam_periph.h>
55117395Skan
56117395Skan#include <cam/scsi/scsi_message.h>
57117395Skan#include <cam/scsi/scsi_enc.h>
5818334Speter#include <cam/scsi/scsi_enc_internal.h>
5918334Speter
60132718Skan/* SES Native Type Device Support */
6152284Sobrien
6252284Sobrien/* SES Diagnostic Page Codes */
6352284Sobrientypedef enum {
6452284Sobrien	SesSupportedPages	= 0x0,
6552284Sobrien	SesConfigPage		= 0x1,
6652284Sobrien	SesControlPage		= 0x2,
6752284Sobrien	SesStatusPage		= SesControlPage,
6852284Sobrien	SesHelpTxt		= 0x3,
6952284Sobrien	SesStringOut		= 0x4,
7052284Sobrien	SesStringIn		= SesStringOut,
7152284Sobrien	SesThresholdOut		= 0x5,
7252284Sobrien	SesThresholdIn		= SesThresholdOut,
7352284Sobrien	SesArrayControl		= 0x6,	/* Obsolete in SES v2 */
74169689Skan	SesArrayStatus		= SesArrayControl,
75169689Skan	SesElementDescriptor	= 0x7,
76169689Skan	SesShortStatus		= 0x8,
77169689Skan	SesEnclosureBusy	= 0x9,
78169689Skan	SesAddlElementStatus	= 0xa
79169689Skan} SesDiagPageCodes;
80169689Skan
81132718Skantypedef struct ses_type {
8252284Sobrien	const struct ses_elm_type_desc  *hdr;
83169689Skan	const char			*text;
84169689Skan} ses_type_t;
85169689Skan
86169689Skantypedef struct ses_comstat {
87169689Skan	uint8_t	comstatus;
88169689Skan	uint8_t	comstat[3];
89169689Skan} ses_comstat_t;
90132718Skan
91169689Skantypedef union ses_addl_data {
92132718Skan	struct ses_elm_sas_device_phy *sasdev_phys;
93132718Skan	struct ses_elm_sas_expander_phy *sasexp_phys;
9452284Sobrien	struct ses_elm_sas_port_phy *sasport_phys;
95169689Skan	struct ses_fcobj_port *fc_ports;
9652284Sobrien} ses_add_data_t;
97169689Skan
98169689Skantypedef struct ses_addl_status {
99169689Skan	struct ses_elm_addlstatus_base_hdr *hdr;
100169689Skan	union {
101169689Skan		union ses_fcobj_hdr *fc;
102169689Skan		union ses_elm_sas_hdr *sas;
103169689Skan	} proto_hdr;
104169689Skan	union ses_addl_data proto_data;	/* array sizes stored in header */
105169689Skan} ses_add_status_t;
106169689Skan
107169689Skantypedef struct ses_element {
108169689Skan	uint8_t eip;			/* eip bit is set */
109169689Skan	uint16_t descr_len;		/* length of the descriptor */
110169689Skan	char *descr;			/* descriptor for this object */
111169689Skan	struct ses_addl_status addl;	/* additional status info */
11290075Sobrien} ses_element_t;
113
114typedef struct ses_control_request {
115	int	      elm_idx;
116	ses_comstat_t elm_stat;
117	int	      result;
118	TAILQ_ENTRY(ses_control_request) links;
119} ses_control_request_t;
120TAILQ_HEAD(ses_control_reqlist, ses_control_request);
121typedef struct ses_control_reqlist ses_control_reqlist_t;
122enum {
123	SES_SETSTATUS_ENC_IDX = -1
124};
125
126static void
127ses_terminate_control_requests(ses_control_reqlist_t *reqlist, int result)
128{
129	ses_control_request_t *req;
130
131	while ((req = TAILQ_FIRST(reqlist)) != NULL) {
132		TAILQ_REMOVE(reqlist, req, links);
133		req->result = result;
134		wakeup(req);
135	}
136}
137
138enum ses_iter_index_values {
139	/**
140	 * \brief  Value of an initialized but invalid index
141	 *         in a ses_iterator object.
142	 *
143	 * This value is used for the  individual_element_index of
144	 * overal status elements and for all index types when
145	 * an iterator is first initialized.
146	 */
147	ITERATOR_INDEX_INVALID = -1,
148
149	/**
150	 * \brief  Value of an index in a ses_iterator object
151	 *	   when the iterator has traversed past the last
152	 *	   valid element..
153	 */
154	ITERATOR_INDEX_END     = INT_MAX
155};
156
157/**
158 * \brief Structure encapsulating all data necessary to traverse the
159 *        elements of a SES configuration.
160 *
161 * The ses_iterator object simplifies the task of iterating through all
162 * elements detected via the SES configuration page by tracking the numerous
163 * element indexes that, instead of memoizing in the softc, we calculate
164 * on the fly during the traversal of the element objects.  The various
165 * indexes are necessary due to the varying needs of matching objects in
166 * the different SES pages.  Some pages (e.g. Status/Control) contain all
167 * elements, while others (e.g. Additional Element Status) only contain
168 * individual elements (no overal status elements) of particular types.
169 *
170 * To use an iterator, initialize it with ses_iter_init(), and then
171 * use ses_iter_next() to traverse the elements (including the first) in
172 * the configuration.  Once an iterator is initiailized with ses_iter_init(),
173 * you may also seek to any particular element by either it's global or
174 * individual element index via the ses_iter_seek_to() function.  You may
175 * also return an iterator to the position just before the first element
176 * (i.e. the same state as after an ses_iter_init()), with ses_iter_reset().
177 */
178struct ses_iterator {
179	/**
180	 * \brief Backlink to the overal software configuration structure.
181	 *
182	 * This is included for convenience so the iteration functions
183	 * need only take a single, struct ses_iterator *, argument.
184	 */
185	enc_softc_t *enc;
186
187	enc_cache_t *cache;
188
189	/**
190	 * \brief Index of the type of the current element within the
191	 *        ses_cache's ses_types array.
192	 */
193	int	          type_index;
194
195	/**
196	 * \brief The position (0 based) of this element relative to all other
197	 *        elements of this type.
198	 *
199	 * This index resets to zero every time the iterator transitions
200	 * to elements of a new type in the configuration.
201	 */
202	int	          type_element_index;
203
204	/**
205	 * \brief The position (0 based) of this element relative to all
206	 *        other individual status elements in the configuration.
207	 *
208	 * This index ranges from 0 through the number of individual
209	 * elements in the configuration.  When the iterator returns
210	 * an overall status element, individual_element_index is
211	 * set to ITERATOR_INDEX_INVALID, to indicate that it does
212	 * not apply to the current element.
213	 */
214	int	          individual_element_index;
215
216	/**
217	 * \brief The position (0 based) of this element relative to
218	 *        all elements in the configration.
219	 *
220	 * This index is appropriate for indexing into enc->ses_elm_map.
221	 */
222	int	          global_element_index;
223
224	/**
225	 * \brief The last valid individual element index of this
226	 *        iterator.
227	 *
228	 * When an iterator traverses an overal status element, the
229	 * individual element index is reset to ITERATOR_INDEX_INVALID
230	 * to prevent unintential use of the individual_element_index
231	 * field.  The saved_individual_element_index allows the iterator
232	 * to restore it's position in the individual elements upon
233	 * reaching the next individual element.
234	 */
235	int	          saved_individual_element_index;
236};
237
238typedef enum {
239	SES_UPDATE_NONE,
240	SES_UPDATE_PAGES,
241	SES_UPDATE_GETCONFIG,
242	SES_UPDATE_GETSTATUS,
243	SES_UPDATE_GETELMDESCS,
244	SES_UPDATE_GETELMADDLSTATUS,
245	SES_PROCESS_CONTROL_REQS,
246	SES_PUBLISH_PHYSPATHS,
247	SES_PUBLISH_CACHE,
248	SES_NUM_UPDATE_STATES
249} ses_update_action;
250
251static enc_softc_cleanup_t ses_softc_cleanup;
252
253#define	SCSZ	0x8000
254
255static fsm_fill_handler_t ses_fill_rcv_diag_io;
256static fsm_fill_handler_t ses_fill_control_request;
257static fsm_done_handler_t ses_process_pages;
258static fsm_done_handler_t ses_process_config;
259static fsm_done_handler_t ses_process_status;
260static fsm_done_handler_t ses_process_elm_descs;
261static fsm_done_handler_t ses_process_elm_addlstatus;
262static fsm_done_handler_t ses_process_control_request;
263static fsm_done_handler_t ses_publish_physpaths;
264static fsm_done_handler_t ses_publish_cache;
265
266static struct enc_fsm_state enc_fsm_states[SES_NUM_UPDATE_STATES] =
267{
268	{ "SES_UPDATE_NONE", 0, 0, 0, NULL, NULL, NULL },
269	{
270		"SES_UPDATE_PAGES",
271		SesSupportedPages,
272		SCSZ,
273		60 * 1000,
274		ses_fill_rcv_diag_io,
275		ses_process_pages,
276		enc_error
277	},
278	{
279		"SES_UPDATE_GETCONFIG",
280		SesConfigPage,
281		SCSZ,
282		60 * 1000,
283		ses_fill_rcv_diag_io,
284		ses_process_config,
285		enc_error
286	},
287	{
288		"SES_UPDATE_GETSTATUS",
289		SesStatusPage,
290		SCSZ,
291		60 * 1000,
292		ses_fill_rcv_diag_io,
293		ses_process_status,
294		enc_error
295	},
296	{
297		"SES_UPDATE_GETELMDESCS",
298		SesElementDescriptor,
299		SCSZ,
300		60 * 1000,
301		ses_fill_rcv_diag_io,
302		ses_process_elm_descs,
303		enc_error
304	},
305	{
306		"SES_UPDATE_GETELMADDLSTATUS",
307		SesAddlElementStatus,
308		SCSZ,
309		60 * 1000,
310		ses_fill_rcv_diag_io,
311		ses_process_elm_addlstatus,
312		enc_error
313	},
314	{
315		"SES_PROCESS_CONTROL_REQS",
316		SesControlPage,
317		SCSZ,
318		60 * 1000,
319		ses_fill_control_request,
320		ses_process_control_request,
321		enc_error
322	},
323	{
324		"SES_PUBLISH_PHYSPATHS",
325		0,
326		0,
327		0,
328		NULL,
329		ses_publish_physpaths,
330		NULL
331	},
332	{
333		"SES_PUBLISH_CACHE",
334		0,
335		0,
336		0,
337		NULL,
338		ses_publish_cache,
339		NULL
340	}
341};
342
343typedef struct ses_cache {
344	/* Source for all the configuration data pointers */
345	const struct ses_cfg_page		*cfg_page;
346
347	/* References into the config page. */
348	int					 ses_nsubencs;
349	const struct ses_enc_desc * const	*subencs;
350	int					 ses_ntypes;
351	const ses_type_t			*ses_types;
352
353	/* Source for all the status pointers */
354	const struct ses_status_page		*status_page;
355
356	/* Source for all the object descriptor pointers */
357	const struct ses_elem_descr_page	*elm_descs_page;
358
359	/* Source for all the additional object status pointers */
360	const struct ses_addl_elem_status_page  *elm_addlstatus_page;
361
362} ses_cache_t;
363
364typedef struct ses_softc {
365	uint32_t		ses_flags;
366#define	SES_FLAG_TIMEDCOMP	0x01
367#define	SES_FLAG_ADDLSTATUS	0x02
368#define	SES_FLAG_DESC		0x04
369
370	ses_control_reqlist_t	ses_requests;
371	ses_control_reqlist_t	ses_pending_requests;
372} ses_softc_t;
373
374/**
375 * \brief Reset a SES iterator to just before the first element
376 *        in the configuration.
377 *
378 * \param iter  The iterator object to reset.
379 *
380 * The indexes within a reset iterator are invalid and will only
381 * become valid upon completion of a ses_iter_seek_to() or a
382 * ses_iter_next().
383 */
384static void
385ses_iter_reset(struct ses_iterator *iter)
386{
387	/*
388	 * Set our indexes to just before the first valid element
389	 * of the first type (ITERATOR_INDEX_INVALID == -1).  This
390	 * simplifies the implementation of ses_iter_next().
391	 */
392	iter->type_index                     = 0;
393	iter->type_element_index             = ITERATOR_INDEX_INVALID;
394	iter->global_element_index           = ITERATOR_INDEX_INVALID;
395	iter->individual_element_index       = ITERATOR_INDEX_INVALID;
396	iter->saved_individual_element_index = ITERATOR_INDEX_INVALID;
397}
398
399/**
400 * \brief Initialize the storage of a SES iterator and reset it to
401 *        the position just before the first element of the
402 *        configuration.
403 *
404 * \param enc	The SES softc for the SES instance whose configuration
405 *              will be enumerated by this iterator.
406 * \param iter  The iterator object to initialize.
407 */
408static void
409ses_iter_init(enc_softc_t *enc, enc_cache_t *cache, struct ses_iterator *iter)
410{
411	iter->enc = enc;
412	iter->cache = cache;
413	ses_iter_reset(iter);
414}
415
416/**
417 * \brief Traverse the provided SES iterator to the next element
418 *        within the configuraiton.
419 *
420 * \param iter  The iterator to move.
421 *
422 * \return  If a valid next element exists, a pointer to it's enc_element_t.
423 *          Otherwise NULL.
424 */
425static enc_element_t *
426ses_iter_next(struct ses_iterator *iter)
427{
428	ses_cache_t	 *ses_cache;
429	const ses_type_t *element_type;
430
431	ses_cache = iter->cache->private;
432
433	/*
434	 * Note: Treat nelms as signed, so we will hit this case
435	 *       and immediately terminate the iteration if the
436	 *	 configuration has 0 objects.
437	 */
438	if (iter->global_element_index >= (int)iter->cache->nelms - 1) {
439
440		/* Elements exhausted. */
441		iter->type_index	       = ITERATOR_INDEX_END;
442		iter->type_element_index       = ITERATOR_INDEX_END;
443		iter->global_element_index     = ITERATOR_INDEX_END;
444		iter->individual_element_index = ITERATOR_INDEX_END;
445		return (NULL);
446	}
447
448	KASSERT((iter->type_index < ses_cache->ses_ntypes),
449		("Corrupted element iterator. %d not less than %d",
450		 iter->type_index, ses_cache->ses_ntypes));
451
452	element_type = &ses_cache->ses_types[iter->type_index];
453	iter->global_element_index++;
454	iter->type_element_index++;
455
456	/*
457	 * There is an object for overal type status in addition
458	 * to one for each allowed element, but only if the element
459	 * count is non-zero.
460	 */
461	if (iter->type_element_index > element_type->hdr->etype_maxelt) {
462
463		/*
464		 * We've exhausted the elements of this type.
465		 * This next element belongs to the next type.
466		 */
467		iter->type_index++;
468		iter->type_element_index = 0;
469		iter->saved_individual_element_index
470		    = iter->individual_element_index;
471		iter->individual_element_index = ITERATOR_INDEX_INVALID;
472	}
473
474	if (iter->type_element_index > 0) {
475		if (iter->type_element_index == 1) {
476			iter->individual_element_index
477			    = iter->saved_individual_element_index;
478		}
479		iter->individual_element_index++;
480	}
481
482	return (&iter->cache->elm_map[iter->global_element_index]);
483}
484
485/**
486 * Element index types tracked by a SES iterator.
487 */
488typedef enum {
489	/**
490	 * Index relative to all elements (overall and individual)
491	 * in the system.
492	 */
493	SES_ELEM_INDEX_GLOBAL,
494
495	/**
496	 * \brief Index relative to all individual elements in the system.
497	 *
498	 * This index counts only individual elements, skipping overall
499	 * status elements.  This is the index space of the additional
500	 * element status page (page 0xa).
501	 */
502	SES_ELEM_INDEX_INDIVIDUAL
503} ses_elem_index_type_t;
504
505/**
506 * \brief Move the provided iterator forwards or backwards to the object
507 *        having the give index.
508 *
509 * \param iter           The iterator on which to perform the seek.
510 * \param element_index  The index of the element to find.
511 * \param index_type     The type (global or individual) of element_index.
512 *
513 * \return  If the element is found, a pointer to it's enc_element_t.
514 *          Otherwise NULL.
515 */
516static enc_element_t *
517ses_iter_seek_to(struct ses_iterator *iter, int element_index,
518		 ses_elem_index_type_t index_type)
519{
520	enc_element_t	*element;
521	int		*cur_index;
522
523	if (index_type == SES_ELEM_INDEX_GLOBAL)
524		cur_index = &iter->global_element_index;
525	else
526		cur_index = &iter->individual_element_index;
527
528	if (*cur_index == element_index) {
529		/* Already there. */
530		return (&iter->cache->elm_map[iter->global_element_index]);
531	}
532
533	ses_iter_reset(iter);
534	while ((element = ses_iter_next(iter)) != NULL
535	    && *cur_index != element_index)
536		;
537
538	if (*cur_index != element_index)
539		return (NULL);
540
541	return (element);
542}
543
544#if 0
545static int ses_encode(enc_softc_t *, uint8_t *, int, int,
546    struct ses_comstat *);
547#endif
548static int ses_set_timed_completion(enc_softc_t *, uint8_t);
549#if 0
550static int ses_putstatus(enc_softc_t *, int, struct ses_comstat *);
551#endif
552
553static void ses_poll_status(enc_softc_t *);
554static void ses_print_addl_data(enc_softc_t *, enc_element_t *);
555
556/*=========================== SES cleanup routines ===========================*/
557
558static void
559ses_cache_free_elm_addlstatus(enc_softc_t *enc, enc_cache_t *cache)
560{
561	ses_cache_t   *ses_cache;
562	ses_cache_t   *other_ses_cache;
563	enc_element_t *cur_elm;
564	enc_element_t *last_elm;
565
566	ENC_DLOG(enc, "%s: enter\n", __func__);
567	ses_cache = cache->private;
568	if (ses_cache->elm_addlstatus_page == NULL)
569		return;
570
571	for (cur_elm = cache->elm_map,
572	     last_elm = &cache->elm_map[cache->nelms];
573	     cur_elm != last_elm; cur_elm++) {
574		ses_element_t *elmpriv;
575
576		elmpriv = cur_elm->elm_private;
577
578		/* Clear references to the additional status page. */
579		bzero(&elmpriv->addl, sizeof(elmpriv->addl));
580	}
581
582	other_ses_cache = enc_other_cache(enc, cache)->private;
583	if (other_ses_cache->elm_addlstatus_page
584	 != ses_cache->elm_addlstatus_page)
585		ENC_FREE(ses_cache->elm_addlstatus_page);
586	ses_cache->elm_addlstatus_page = NULL;
587}
588
589static void
590ses_cache_free_elm_descs(enc_softc_t *enc, enc_cache_t *cache)
591{
592	ses_cache_t   *ses_cache;
593	ses_cache_t   *other_ses_cache;
594	enc_element_t *cur_elm;
595	enc_element_t *last_elm;
596
597	ENC_DLOG(enc, "%s: enter\n", __func__);
598	ses_cache = cache->private;
599	if (ses_cache->elm_descs_page == NULL)
600		return;
601
602	for (cur_elm = cache->elm_map,
603	     last_elm = &cache->elm_map[cache->nelms];
604	     cur_elm != last_elm; cur_elm++) {
605		ses_element_t *elmpriv;
606
607		elmpriv = cur_elm->elm_private;
608		elmpriv->descr_len = 0;
609		elmpriv->descr = NULL;
610	}
611
612	other_ses_cache = enc_other_cache(enc, cache)->private;
613	if (other_ses_cache->elm_descs_page
614	 != ses_cache->elm_descs_page)
615		ENC_FREE(ses_cache->elm_descs_page);
616	ses_cache->elm_descs_page = NULL;
617}
618
619static void
620ses_cache_free_status(enc_softc_t *enc, enc_cache_t *cache)
621{
622	ses_cache_t *ses_cache;
623	ses_cache_t *other_ses_cache;
624
625	ENC_DLOG(enc, "%s: enter\n", __func__);
626	ses_cache   = cache->private;
627	if (ses_cache->status_page == NULL)
628		return;
629
630	other_ses_cache = enc_other_cache(enc, cache)->private;
631	if (other_ses_cache->status_page != ses_cache->status_page)
632		ENC_FREE(ses_cache->status_page);
633	ses_cache->status_page = NULL;
634}
635
636static void
637ses_cache_free_elm_map(enc_softc_t *enc, enc_cache_t *cache)
638{
639	enc_element_t *cur_elm;
640	enc_element_t *last_elm;
641
642	ENC_DLOG(enc, "%s: enter\n", __func__);
643	if (cache->elm_map == NULL)
644		return;
645
646	ses_cache_free_elm_descs(enc, cache);
647	ses_cache_free_elm_addlstatus(enc, cache);
648	for (cur_elm = cache->elm_map,
649	     last_elm = &cache->elm_map[cache->nelms];
650	     cur_elm != last_elm; cur_elm++) {
651
652		ENC_FREE_AND_NULL(cur_elm->elm_private);
653	}
654	ENC_FREE_AND_NULL(cache->elm_map);
655	cache->nelms = 0;
656	ENC_DLOG(enc, "%s: exit\n", __func__);
657}
658
659static void
660ses_cache_free(enc_softc_t *enc, enc_cache_t *cache)
661{
662	ses_cache_t *other_ses_cache;
663	ses_cache_t *ses_cache;
664
665	ENC_DLOG(enc, "%s: enter\n", __func__);
666	ses_cache_free_elm_addlstatus(enc, cache);
667	ses_cache_free_status(enc, cache);
668	ses_cache_free_elm_map(enc, cache);
669
670	ses_cache = cache->private;
671	ses_cache->ses_ntypes = 0;
672
673	other_ses_cache = enc_other_cache(enc, cache)->private;
674	if (other_ses_cache->subencs != ses_cache->subencs)
675		ENC_FREE(ses_cache->subencs);
676	ses_cache->subencs = NULL;
677
678	if (other_ses_cache->ses_types != ses_cache->ses_types)
679		ENC_FREE(ses_cache->ses_types);
680	ses_cache->ses_types = NULL;
681
682	if (other_ses_cache->cfg_page != ses_cache->cfg_page)
683		ENC_FREE(ses_cache->cfg_page);
684	ses_cache->cfg_page = NULL;
685
686	ENC_DLOG(enc, "%s: exit\n", __func__);
687}
688
689static void
690ses_cache_clone(enc_softc_t *enc, enc_cache_t *src, enc_cache_t *dst)
691{
692	ses_cache_t   *dst_ses_cache;
693	ses_cache_t   *src_ses_cache;
694	enc_element_t *src_elm;
695	enc_element_t *dst_elm;
696	enc_element_t *last_elm;
697
698	ses_cache_free(enc, dst);
699	src_ses_cache = src->private;
700	dst_ses_cache = dst->private;
701
702	/*
703	 * The cloned enclosure cache and ses specific cache are
704	 * mostly identical to the source.
705	 */
706	*dst = *src;
707	*dst_ses_cache = *src_ses_cache;
708
709	/*
710	 * But the ses cache storage is still independent.  Restore
711	 * the pointer that was clobbered by the structure copy above.
712	 */
713	dst->private = dst_ses_cache;
714
715	/*
716	 * The element map is independent even though it starts out
717	 * pointing to the same constant page data.
718	 */
719	dst->elm_map = malloc(dst->nelms * sizeof(enc_element_t),
720	    M_SCSIENC, M_WAITOK);
721	memcpy(dst->elm_map, src->elm_map, dst->nelms * sizeof(enc_element_t));
722	for (dst_elm = dst->elm_map, src_elm = src->elm_map,
723	     last_elm = &src->elm_map[src->nelms];
724	     src_elm != last_elm; src_elm++, dst_elm++) {
725
726		dst_elm->elm_private = malloc(sizeof(ses_element_t),
727		    M_SCSIENC, M_WAITOK);
728		memcpy(dst_elm->elm_private, src_elm->elm_private,
729		       sizeof(ses_element_t));
730	}
731}
732
733/* Structure accessors.  These are strongly typed to avoid errors. */
734
735int
736ses_elm_sas_descr_type(union ses_elm_sas_hdr *obj)
737{
738	return ((obj)->base_hdr.byte1 >> 6);
739}
740int
741ses_elm_addlstatus_proto(struct ses_elm_addlstatus_base_hdr *hdr)
742{
743	return ((hdr)->byte0 & 0xf);
744}
745int
746ses_elm_addlstatus_eip(struct ses_elm_addlstatus_base_hdr *hdr)
747{
748	return ((hdr)->byte0 >> 4) & 0x1;
749}
750int
751ses_elm_addlstatus_invalid(struct ses_elm_addlstatus_base_hdr *hdr)
752{
753	return ((hdr)->byte0 >> 7);
754}
755int
756ses_elm_sas_type0_not_all_phys(union ses_elm_sas_hdr *hdr)
757{
758	return ((hdr)->type0_noneip.byte1 & 0x1);
759}
760int
761ses_elm_sas_dev_phy_sata_dev(struct ses_elm_sas_device_phy *phy)
762{
763	return ((phy)->target_ports & 0x1);
764}
765int
766ses_elm_sas_dev_phy_sata_port(struct ses_elm_sas_device_phy *phy)
767{
768	return ((phy)->target_ports >> 7);
769}
770int
771ses_elm_sas_dev_phy_dev_type(struct ses_elm_sas_device_phy *phy)
772{
773	return (((phy)->byte0 >> 4) & 0x7);
774}
775
776/**
777 * \brief Verify that the cached configuration data in our softc
778 *        is valid for processing the page data corresponding to
779 *        the provided page header.
780 *
781 * \param ses_cache The SES cache to validate.
782 * \param gen_code  The 4 byte generation code from a SES diagnostic
783 *		    page header.
784 *
785 * \return  non-zero if true, 0 if false.
786 */
787static int
788ses_config_cache_valid(ses_cache_t *ses_cache, const uint8_t *gen_code)
789{
790	uint32_t cache_gc;
791	uint32_t cur_gc;
792
793	if (ses_cache->cfg_page == NULL)
794		return (0);
795
796	cache_gc = scsi_4btoul(ses_cache->cfg_page->hdr.gen_code);
797	cur_gc   = scsi_4btoul(gen_code);
798	return (cache_gc == cur_gc);
799}
800
801/**
802 * Function signature for consumers of the ses_devids_iter() interface.
803 */
804typedef void ses_devid_callback_t(enc_softc_t *, enc_element_t *,
805				  struct scsi_vpd_id_descriptor *, void *);
806
807/**
808 * \brief Iterate over and create vpd device id records from the
809 *        additional element status data for elm, passing that data
810 *        to the provided callback.
811 *
812 * \param enc	        SES instance containing elm
813 * \param elm	        Element for which to extract device ID data.
814 * \param callback      The callback function to invoke on each generated
815 *                      device id descriptor for elm.
816 * \param callback_arg  Argument passed through to callback on each invocation.
817 */
818static void
819ses_devids_iter(enc_softc_t *enc, enc_element_t *elm,
820		ses_devid_callback_t *callback, void *callback_arg)
821{
822	ses_element_t           *elmpriv;
823	struct ses_addl_status *addl;
824	u_int                   i;
825	size_t			devid_record_size;
826
827	elmpriv = elm->elm_private;
828	addl = &(elmpriv->addl);
829
830	/*
831	 * Don't assume this object has additional status information, or
832	 * that it is a SAS device, or that it is a device slot device.
833	 */
834	if (addl->hdr == NULL || addl->proto_hdr.sas == NULL
835	 || addl->proto_data.sasdev_phys == NULL)
836		return;
837
838	devid_record_size = SVPD_DEVICE_ID_DESC_HDR_LEN
839			  + sizeof(struct scsi_vpd_id_naa_ieee_reg);
840	for (i = 0; i < addl->proto_hdr.sas->base_hdr.num_phys; i++) {
841		uint8_t			       devid_buf[devid_record_size];
842		struct scsi_vpd_id_descriptor *devid;
843		uint8_t			      *phy_addr;
844
845		devid = (struct scsi_vpd_id_descriptor *)devid_buf;
846		phy_addr = addl->proto_data.sasdev_phys[i].phy_addr;
847		devid->proto_codeset = (SCSI_PROTO_SAS << SVPD_ID_PROTO_SHIFT)
848				     | SVPD_ID_CODESET_BINARY;
849		devid->id_type       = SVPD_ID_PIV
850				     | SVPD_ID_ASSOC_PORT
851				     | SVPD_ID_TYPE_NAA;
852		devid->reserved	     = 0;
853		devid->length	     = sizeof(struct scsi_vpd_id_naa_ieee_reg);
854		memcpy(devid->identifier, phy_addr, devid->length);
855
856		callback(enc, elm, devid, callback_arg);
857	}
858}
859
860/**
861 * Function signature for consumers of the ses_paths_iter() interface.
862 */
863typedef void ses_path_callback_t(enc_softc_t *, enc_element_t *,
864				 struct cam_path *, void *);
865
866/**
867 * Argument package passed through ses_devids_iter() by
868 * ses_paths_iter() to ses_path_iter_devid_callback().
869 */
870typedef struct ses_path_iter_args {
871	ses_path_callback_t *callback;
872	void		    *callback_arg;
873} ses_path_iter_args_t;
874
875/**
876 * ses_devids_iter() callback function used by ses_paths_iter()
877 * to map device ids to peripheral driver instances.
878 *
879 * \param enc	  SES instance containing elm
880 * \param elm	  Element on which device ID matching is active.
881 * \param periph  A device ID corresponding to elm.
882 * \param arg     Argument passed through to callback on each invocation.
883 */
884static void
885ses_path_iter_devid_callback(enc_softc_t *enc, enc_element_t *elem,
886			       struct scsi_vpd_id_descriptor *devid,
887			       void *arg)
888{
889	struct ccb_dev_match         cdm;
890	struct dev_match_pattern     match_pattern;
891	struct dev_match_result      match_result;
892	struct device_match_result  *device_match;
893	struct device_match_pattern *device_pattern;
894	ses_path_iter_args_t	    *args;
895
896	args = (ses_path_iter_args_t *)arg;
897	match_pattern.type = DEV_MATCH_DEVICE;
898	device_pattern = &match_pattern.pattern.device_pattern;
899	device_pattern->flags = DEV_MATCH_DEVID;
900	device_pattern->data.devid_pat.id_len =
901	    offsetof(struct scsi_vpd_id_descriptor, identifier)
902	  + devid->length;
903	memcpy(device_pattern->data.devid_pat.id, devid,
904	       device_pattern->data.devid_pat.id_len);
905
906	memset(&cdm, 0, sizeof(cdm));
907	if (xpt_create_path(&cdm.ccb_h.path, /*periph*/NULL,
908			     CAM_XPT_PATH_ID,
909			     CAM_TARGET_WILDCARD,
910			     CAM_LUN_WILDCARD) != CAM_REQ_CMP)
911		return;
912
913	cdm.ccb_h.func_code = XPT_DEV_MATCH;
914	cdm.num_patterns    = 1;
915	cdm.patterns        = &match_pattern;
916	cdm.pattern_buf_len = sizeof(match_pattern);
917	cdm.match_buf_len   = sizeof(match_result);
918	cdm.matches         = &match_result;
919
920	xpt_action((union ccb *)&cdm);
921	xpt_free_path(cdm.ccb_h.path);
922
923	if ((cdm.ccb_h.status & CAM_STATUS_MASK) != CAM_REQ_CMP
924	 || (cdm.status != CAM_DEV_MATCH_LAST
925	  && cdm.status != CAM_DEV_MATCH_MORE)
926	 || cdm.num_matches == 0)
927		return;
928
929	device_match = &match_result.result.device_result;
930	if (xpt_create_path(&cdm.ccb_h.path, /*periph*/NULL,
931			     device_match->path_id,
932			     device_match->target_id,
933			     device_match->target_lun) != CAM_REQ_CMP)
934		return;
935
936	args->callback(enc, elem, cdm.ccb_h.path, args->callback_arg);
937
938	xpt_free_path(cdm.ccb_h.path);
939}
940
941/**
942 * \brief Iterate over and find the matching periph objects for the
943 *        specified element.
944 *
945 * \param enc	        SES instance containing elm
946 * \param elm	        Element for which to perform periph object matching.
947 * \param callback      The callback function to invoke with each matching
948 *                      periph object.
949 * \param callback_arg  Argument passed through to callback on each invocation.
950 */
951static void
952ses_paths_iter(enc_softc_t *enc, enc_element_t *elm,
953	       ses_path_callback_t *callback, void *callback_arg)
954{
955	ses_path_iter_args_t args;
956
957	args.callback     = callback;
958	args.callback_arg = callback_arg;
959	ses_devids_iter(enc, elm, ses_path_iter_devid_callback, &args);
960}
961
962/**
963 * ses_paths_iter() callback function used by ses_get_elmdevname()
964 * to record periph driver instance strings corresponding to a SES
965 * element.
966 *
967 * \param enc	  SES instance containing elm
968 * \param elm	  Element on which periph matching is active.
969 * \param periph  A periph instance that matches elm.
970 * \param arg     Argument passed through to callback on each invocation.
971 */
972static void
973ses_elmdevname_callback(enc_softc_t *enc, enc_element_t *elem,
974			struct cam_path *path, void *arg)
975{
976	struct sbuf *sb;
977
978	sb = (struct sbuf *)arg;
979	cam_periph_list(path, sb);
980}
981
982/**
983 * Argument package passed through ses_paths_iter() to
984 * ses_getcampath_callback.
985 */
986typedef struct ses_setphyspath_callback_args {
987	struct sbuf *physpath;
988	int          num_set;
989} ses_setphyspath_callback_args_t;
990
991/**
992 * \brief ses_paths_iter() callback to set the physical path on the
993 *        CAM EDT entries corresponding to a given SES element.
994 *
995 * \param enc	  SES instance containing elm
996 * \param elm	  Element on which periph matching is active.
997 * \param periph  A periph instance that matches elm.
998 * \param arg     Argument passed through to callback on each invocation.
999 */
1000static void
1001ses_setphyspath_callback(enc_softc_t *enc, enc_element_t *elm,
1002			 struct cam_path *path, void *arg)
1003{
1004	struct ccb_dev_advinfo cdai;
1005	ses_setphyspath_callback_args_t *args;
1006	char *old_physpath;
1007
1008	args = (ses_setphyspath_callback_args_t *)arg;
1009	old_physpath = malloc(MAXPATHLEN, M_SCSIENC, M_WAITOK|M_ZERO);
1010	cam_periph_lock(enc->periph);
1011	xpt_setup_ccb(&cdai.ccb_h, path, CAM_PRIORITY_NORMAL);
1012	cdai.ccb_h.func_code = XPT_DEV_ADVINFO;
1013	cdai.buftype = CDAI_TYPE_PHYS_PATH;
1014	cdai.flags = CDAI_FLAG_NONE;
1015	cdai.bufsiz = MAXPATHLEN;
1016	cdai.buf = old_physpath;
1017	xpt_action((union ccb *)&cdai);
1018	if ((cdai.ccb_h.status & CAM_DEV_QFRZN) != 0)
1019		cam_release_devq(cdai.ccb_h.path, 0, 0, 0, FALSE);
1020
1021	if (strcmp(old_physpath, sbuf_data(args->physpath)) != 0) {
1022
1023		xpt_setup_ccb(&cdai.ccb_h, path, CAM_PRIORITY_NORMAL);
1024		cdai.ccb_h.func_code = XPT_DEV_ADVINFO;
1025		cdai.buftype = CDAI_TYPE_PHYS_PATH;
1026		cdai.flags = CDAI_FLAG_STORE;
1027		cdai.bufsiz = sbuf_len(args->physpath);
1028		cdai.buf = sbuf_data(args->physpath);
1029		xpt_action((union ccb *)&cdai);
1030		if ((cdai.ccb_h.status & CAM_DEV_QFRZN) != 0)
1031			cam_release_devq(cdai.ccb_h.path, 0, 0, 0, FALSE);
1032		if (cdai.ccb_h.status == CAM_REQ_CMP)
1033			args->num_set++;
1034	}
1035	cam_periph_unlock(enc->periph);
1036	free(old_physpath, M_SCSIENC);
1037}
1038
1039/**
1040 * \brief Set a device's physical path string in CAM XPT.
1041 *
1042 * \param enc	SES instance containing elm
1043 * \param elm	Element to publish physical path string for
1044 * \param iter	Iterator whose state corresponds to elm
1045 *
1046 * \return	0 on success, errno otherwise.
1047 */
1048static int
1049ses_set_physpath(enc_softc_t *enc, enc_element_t *elm,
1050		 struct ses_iterator *iter)
1051{
1052	struct ccb_dev_advinfo cdai;
1053	ses_setphyspath_callback_args_t args;
1054	int i, ret;
1055	struct sbuf sb;
1056	struct scsi_vpd_id_descriptor *idd;
1057	uint8_t *devid;
1058	ses_element_t *elmpriv;
1059	const char *c;
1060
1061	ret = EIO;
1062	devid = NULL;
1063
1064	/*
1065	 * Assemble the components of the physical path starting with
1066	 * the device ID of the enclosure itself.
1067	 */
1068	xpt_setup_ccb(&cdai.ccb_h, enc->periph->path, CAM_PRIORITY_NORMAL);
1069	cdai.ccb_h.func_code = XPT_DEV_ADVINFO;
1070	cdai.flags = CDAI_FLAG_NONE;
1071	cdai.buftype = CDAI_TYPE_SCSI_DEVID;
1072	cdai.bufsiz = CAM_SCSI_DEVID_MAXLEN;
1073	cdai.buf = devid = malloc(cdai.bufsiz, M_SCSIENC, M_WAITOK|M_ZERO);
1074	cam_periph_lock(enc->periph);
1075	xpt_action((union ccb *)&cdai);
1076	if ((cdai.ccb_h.status & CAM_DEV_QFRZN) != 0)
1077		cam_release_devq(cdai.ccb_h.path, 0, 0, 0, FALSE);
1078	cam_periph_unlock(enc->periph);
1079	if (cdai.ccb_h.status != CAM_REQ_CMP)
1080		goto out;
1081
1082	idd = scsi_get_devid((struct scsi_vpd_device_id *)cdai.buf,
1083	    cdai.provsiz, scsi_devid_is_naa_ieee_reg);
1084	if (idd == NULL)
1085		goto out;
1086
1087	if (sbuf_new(&sb, NULL, 128, SBUF_AUTOEXTEND) == NULL) {
1088		ret = ENOMEM;
1089		goto out;
1090	}
1091	/* Next, generate the physical path string */
1092	sbuf_printf(&sb, "id1,enc@n%jx/type@%x/slot@%x",
1093	    scsi_8btou64(idd->identifier), iter->type_index,
1094	    iter->type_element_index);
1095	/* Append the element descriptor if one exists */
1096	elmpriv = elm->elm_private;
1097	if (elmpriv->descr != NULL && elmpriv->descr_len > 0) {
1098		sbuf_cat(&sb, "/elmdesc@");
1099		for (i = 0, c = elmpriv->descr; i < elmpriv->descr_len;
1100		    i++, c++) {
1101			if (!isprint(*c) || isspace(*c) || *c == '/')
1102				sbuf_putc(&sb, '_');
1103			else
1104				sbuf_putc(&sb, *c);
1105		}
1106	}
1107	sbuf_finish(&sb);
1108
1109	/*
1110	 * Set this physical path on any CAM devices with a device ID
1111	 * descriptor that matches one created from the SES additional
1112	 * status data for this element.
1113	 */
1114	args.physpath= &sb;
1115	args.num_set = 0;
1116	ses_paths_iter(enc, elm, ses_setphyspath_callback, &args);
1117	sbuf_delete(&sb);
1118
1119	ret = args.num_set == 0 ? ENOENT : 0;
1120
1121out:
1122	if (devid != NULL)
1123		ENC_FREE(devid);
1124	return (ret);
1125}
1126
1127/**
1128 * \brief Helper to set the CDB fields appropriately.
1129 *
1130 * \param cdb		Buffer containing the cdb.
1131 * \param pagenum	SES diagnostic page to query for.
1132 * \param dir		Direction of query.
1133 */
1134static void
1135ses_page_cdb(char *cdb, int bufsiz, SesDiagPageCodes pagenum, int dir)
1136{
1137
1138	/* Ref: SPC-4 r25 Section 6.20 Table 223 */
1139	if (dir == CAM_DIR_IN) {
1140		cdb[0] = RECEIVE_DIAGNOSTIC;
1141		cdb[1] = 1; /* Set page code valid bit */
1142		cdb[2] = pagenum;
1143	} else {
1144		cdb[0] = SEND_DIAGNOSTIC;
1145		cdb[1] = 0x10;
1146		cdb[2] = pagenum;
1147	}
1148	cdb[3] = bufsiz >> 8;	/* high bits */
1149	cdb[4] = bufsiz & 0xff;	/* low bits */
1150	cdb[5] = 0;
1151}
1152
1153/**
1154 * \brief Discover whether this instance supports timed completion of a
1155 * 	  RECEIVE DIAGNOSTIC RESULTS command requesting the Enclosure Status
1156 * 	  page, and store the result in the softc, updating if necessary.
1157 *
1158 * \param enc	SES instance to query and update.
1159 * \param tc_en	Value of timed completion to set (see \return).
1160 *
1161 * \return	1 if timed completion enabled, 0 otherwise.
1162 */
1163static int
1164ses_set_timed_completion(enc_softc_t *enc, uint8_t tc_en)
1165{
1166	int err;
1167	union ccb *ccb;
1168	struct cam_periph *periph;
1169	struct ses_mgmt_mode_page *mgmt;
1170	uint8_t *mode_buf;
1171	size_t mode_buf_len;
1172	ses_softc_t *ses;
1173
1174	periph = enc->periph;
1175	ses = enc->enc_private;
1176	ccb = cam_periph_getccb(periph, CAM_PRIORITY_NORMAL);
1177
1178	mode_buf_len = sizeof(struct ses_mgmt_mode_page);
1179	mode_buf = ENC_MALLOCZ(mode_buf_len);
1180	if (mode_buf == NULL)
1181		goto out;
1182
1183	scsi_mode_sense(&ccb->csio, /*retries*/4, NULL, MSG_SIMPLE_Q_TAG,
1184	    /*dbd*/FALSE, SMS_PAGE_CTRL_CURRENT, SES_MGMT_MODE_PAGE_CODE,
1185	    mode_buf, mode_buf_len, SSD_FULL_SIZE, /*timeout*/60 * 1000);
1186
1187	/*
1188	 * Ignore illegal request errors, as they are quite common and we
1189	 * will print something out in that case anyway.
1190	 */
1191	err = cam_periph_runccb(ccb, enc_error, ENC_CFLAGS,
1192	    ENC_FLAGS|SF_QUIET_IR, NULL);
1193	if (ccb->ccb_h.status != CAM_REQ_CMP) {
1194		ENC_VLOG(enc, "Timed Completion Unsupported\n");
1195		goto release;
1196	}
1197
1198	/* Skip the mode select if the desired value is already set */
1199	mgmt = (struct ses_mgmt_mode_page *)mode_buf;
1200	if ((mgmt->byte5 & SES_MGMT_TIMED_COMP_EN) == tc_en)
1201		goto done;
1202
1203	/* Value is not what we wanted, set it */
1204	if (tc_en)
1205		mgmt->byte5 |= SES_MGMT_TIMED_COMP_EN;
1206	else
1207		mgmt->byte5 &= ~SES_MGMT_TIMED_COMP_EN;
1208	/* SES2r20: a completion time of zero means as long as possible */
1209	bzero(&mgmt->max_comp_time, sizeof(mgmt->max_comp_time));
1210
1211	scsi_mode_select(&ccb->csio, 5, NULL, MSG_SIMPLE_Q_TAG,
1212	    /*page_fmt*/FALSE, /*save_pages*/TRUE, mode_buf, mode_buf_len,
1213	    SSD_FULL_SIZE, /*timeout*/60 * 1000);
1214
1215	err = cam_periph_runccb(ccb, enc_error, ENC_CFLAGS, ENC_FLAGS, NULL);
1216	if (ccb->ccb_h.status != CAM_REQ_CMP) {
1217		ENC_VLOG(enc, "Timed Completion Set Failed\n");
1218		goto release;
1219	}
1220
1221done:
1222	if ((mgmt->byte5 & SES_MGMT_TIMED_COMP_EN) != 0) {
1223		ENC_LOG(enc, "Timed Completion Enabled\n");
1224		ses->ses_flags |= SES_FLAG_TIMEDCOMP;
1225	} else {
1226		ENC_LOG(enc, "Timed Completion Disabled\n");
1227		ses->ses_flags &= ~SES_FLAG_TIMEDCOMP;
1228	}
1229release:
1230	ENC_FREE(mode_buf);
1231	xpt_release_ccb(ccb);
1232out:
1233	return (ses->ses_flags & SES_FLAG_TIMEDCOMP);
1234}
1235
1236/**
1237 * \brief Process the list of supported pages and update flags.
1238 *
1239 * \param enc       SES device to query.
1240 * \param buf       Buffer containing the config page.
1241 * \param xfer_len  Length of the config page in the buffer.
1242 *
1243 * \return  0 on success, errno otherwise.
1244 */
1245static int
1246ses_process_pages(enc_softc_t *enc, struct enc_fsm_state *state,
1247    union ccb *ccb, uint8_t **bufp, int error, int xfer_len)
1248{
1249	ses_softc_t *ses;
1250	struct scsi_diag_page *page;
1251	int err, i, length;
1252
1253	CAM_DEBUG(enc->periph->path, CAM_DEBUG_SUBTRACE,
1254	    ("entering %s(%p, %d)\n", __func__, bufp, xfer_len));
1255	ses = enc->enc_private;
1256	err = -1;
1257
1258	if (error != 0) {
1259		err = error;
1260		goto out;
1261	}
1262	if (xfer_len < sizeof(*page)) {
1263		ENC_VLOG(enc, "Unable to parse Diag Pages List Header\n");
1264		err = EIO;
1265		goto out;
1266	}
1267	page = (struct scsi_diag_page *)*bufp;
1268	length = scsi_2btoul(page->length);
1269	if (length + offsetof(struct scsi_diag_page, params) > xfer_len) {
1270		ENC_VLOG(enc, "Diag Pages List Too Long\n");
1271		goto out;
1272	}
1273	ENC_DLOG(enc, "%s: page length %d, xfer_len %d\n",
1274		 __func__, length, xfer_len);
1275
1276	err = 0;
1277	for (i = 0; i < length; i++) {
1278		if (page->params[i] == SesElementDescriptor)
1279			ses->ses_flags |= SES_FLAG_DESC;
1280		else if (page->params[i] == SesAddlElementStatus)
1281			ses->ses_flags |= SES_FLAG_ADDLSTATUS;
1282	}
1283
1284out:
1285	ENC_DLOG(enc, "%s: exiting with err %d\n", __func__, err);
1286	return (err);
1287}
1288
1289/**
1290 * \brief Process the config page and update associated structures.
1291 *
1292 * \param enc       SES device to query.
1293 * \param buf       Buffer containing the config page.
1294 * \param xfer_len  Length of the config page in the buffer.
1295 *
1296 * \return  0 on success, errno otherwise.
1297 */
1298static int
1299ses_process_config(enc_softc_t *enc, struct enc_fsm_state *state,
1300    union ccb *ccb, uint8_t **bufp, int error, int xfer_len)
1301{
1302	struct ses_iterator iter;
1303	ses_softc_t *ses;
1304	enc_cache_t *enc_cache;
1305	ses_cache_t *ses_cache;
1306	uint8_t *buf;
1307	int length;
1308	int err;
1309	int nelm;
1310	int ntype;
1311	struct ses_cfg_page *cfg_page;
1312	struct ses_enc_desc *buf_subenc;
1313	const struct ses_enc_desc **subencs;
1314	const struct ses_enc_desc **cur_subenc;
1315	const struct ses_enc_desc **last_subenc;
1316	ses_type_t *ses_types;
1317	ses_type_t *sestype;
1318	const struct ses_elm_type_desc *cur_buf_type;
1319	const struct ses_elm_type_desc *last_buf_type;
1320	uint8_t *last_valid_byte;
1321	enc_element_t *element;
1322	const char *type_text;
1323
1324	CAM_DEBUG(enc->periph->path, CAM_DEBUG_SUBTRACE,
1325	    ("entering %s(%p, %d)\n", __func__, bufp, xfer_len));
1326	ses = enc->enc_private;
1327	enc_cache = &enc->enc_daemon_cache;
1328	ses_cache = enc_cache->private;
1329	buf = *bufp;
1330	err = -1;
1331
1332	if (error != 0) {
1333		err = error;
1334		goto out;
1335	}
1336	if (xfer_len < sizeof(cfg_page->hdr)) {
1337		ENC_VLOG(enc, "Unable to parse SES Config Header\n");
1338		err = EIO;
1339		goto out;
1340	}
1341
1342	cfg_page = (struct ses_cfg_page *)buf;
1343	length = ses_page_length(&cfg_page->hdr);
1344	if (length > xfer_len) {
1345		ENC_VLOG(enc, "Enclosure Config Page Too Long\n");
1346		goto out;
1347	}
1348	last_valid_byte = &buf[length - 1];
1349
1350	ENC_DLOG(enc, "%s: total page length %d, xfer_len %d\n",
1351		 __func__, length, xfer_len);
1352
1353	err = 0;
1354	if (ses_config_cache_valid(ses_cache, cfg_page->hdr.gen_code)) {
1355
1356		/* Our cache is still valid.  Proceed to fetching status. */
1357		goto out;
1358	}
1359
1360	/* Cache is no longer valid.  Free old data to make way for new. */
1361	ses_cache_free(enc, enc_cache);
1362	ENC_VLOG(enc, "Generation Code 0x%x has %d SubEnclosures\n",
1363	    scsi_4btoul(cfg_page->hdr.gen_code),
1364	    ses_cfg_page_get_num_subenc(cfg_page));
1365
1366	/* Take ownership of the buffer. */
1367	ses_cache->cfg_page = cfg_page;
1368	*bufp = NULL;
1369
1370	/*
1371	 * Now waltz through all the subenclosures summing the number of
1372	 * types available in each.
1373	 */
1374	subencs = malloc(ses_cfg_page_get_num_subenc(cfg_page)
1375	    * sizeof(*subencs), M_SCSIENC, M_WAITOK|M_ZERO);
1376	/*
1377	 * Sub-enclosure data is const after construction (i.e. when
1378	 * accessed via our cache object.
1379	 *
1380	 * The cast here is not required in C++ but C99 is not so
1381	 * sophisticated (see C99 6.5.16.1(1)).
1382	 */
1383	ses_cache->ses_nsubencs = ses_cfg_page_get_num_subenc(cfg_page);
1384	ses_cache->subencs = subencs;
1385
1386	buf_subenc = cfg_page->subencs;
1387	cur_subenc = subencs;
1388	last_subenc = &subencs[ses_cache->ses_nsubencs - 1];
1389	ntype = 0;
1390	while (cur_subenc <= last_subenc) {
1391
1392		if (!ses_enc_desc_is_complete(buf_subenc, last_valid_byte)) {
1393			ENC_VLOG(enc, "Enclosure %d Beyond End of "
1394			    "Descriptors\n", cur_subenc - subencs);
1395			err = EIO;
1396			goto out;
1397		}
1398
1399		ENC_VLOG(enc, " SubEnclosure ID %d, %d Types With this ID, "
1400		    "Descriptor Length %d, offset %d\n", buf_subenc->subenc_id,
1401		    buf_subenc->num_types, buf_subenc->length,
1402		    &buf_subenc->byte0 - buf);
1403		ENC_VLOG(enc, "WWN: %jx\n",
1404		    (uintmax_t)scsi_8btou64(buf_subenc->logical_id));
1405
1406		ntype += buf_subenc->num_types;
1407		*cur_subenc = buf_subenc;
1408		cur_subenc++;
1409		buf_subenc = ses_enc_desc_next(buf_subenc);
1410	}
1411
1412	/* Process the type headers. */
1413	ses_types = malloc(ntype * sizeof(*ses_types),
1414	    M_SCSIENC, M_WAITOK|M_ZERO);
1415	/*
1416	 * Type data is const after construction (i.e. when accessed via
1417	 * our cache object.
1418	 */
1419	ses_cache->ses_ntypes = ntype;
1420	ses_cache->ses_types = ses_types;
1421
1422	cur_buf_type = (const struct ses_elm_type_desc *)
1423	    (&(*last_subenc)->length + (*last_subenc)->length + 1);
1424	last_buf_type = cur_buf_type + ntype - 1;
1425	type_text = (const uint8_t *)(last_buf_type + 1);
1426	nelm = 0;
1427	sestype = ses_types;
1428	while (cur_buf_type <= last_buf_type) {
1429		if (&cur_buf_type->etype_txt_len > last_valid_byte) {
1430			ENC_VLOG(enc, "Runt Enclosure Type Header %d\n",
1431			    sestype - ses_types);
1432			err = EIO;
1433			goto out;
1434		}
1435		sestype->hdr  = cur_buf_type;
1436		sestype->text = type_text;
1437		type_text += cur_buf_type->etype_txt_len;
1438		ENC_VLOG(enc, " Type Desc[%d]: Type 0x%x, MaxElt %d, In Subenc "
1439		    "%d, Text Length %d: %.*s\n", sestype - ses_types,
1440		    sestype->hdr->etype_elm_type, sestype->hdr->etype_maxelt,
1441		    sestype->hdr->etype_subenc, sestype->hdr->etype_txt_len,
1442		    sestype->hdr->etype_txt_len, sestype->text);
1443
1444		nelm += sestype->hdr->etype_maxelt
1445		      + /*overall status element*/1;
1446		sestype++;
1447		cur_buf_type++;
1448	}
1449
1450	/* Create the object map. */
1451	enc_cache->elm_map = malloc(nelm * sizeof(enc_element_t),
1452	    M_SCSIENC, M_WAITOK|M_ZERO);
1453	enc_cache->nelms = nelm;
1454
1455	ses_iter_init(enc, enc_cache, &iter);
1456	while ((element = ses_iter_next(&iter)) != NULL) {
1457		const struct ses_elm_type_desc *thdr;
1458
1459		ENC_DLOG(enc, "%s: checking obj %d(%d,%d)\n", __func__,
1460		    iter.global_element_index, iter.type_index, nelm,
1461		    iter.type_element_index);
1462		thdr = ses_cache->ses_types[iter.type_index].hdr;
1463		element->subenclosure = thdr->etype_subenc;
1464		element->enctype = thdr->etype_elm_type;
1465		element->overall_status_elem = iter.type_element_index == 0;
1466		element->elm_private = malloc(sizeof(ses_element_t),
1467		    M_SCSIENC, M_WAITOK|M_ZERO);
1468		ENC_DLOG(enc, "%s: creating elmpriv %d(%d,%d) subenc %d "
1469		    "type 0x%x\n", __func__, iter.global_element_index,
1470		    iter.type_index, iter.type_element_index,
1471		    thdr->etype_subenc, thdr->etype_elm_type);
1472	}
1473
1474	err = 0;
1475
1476out:
1477	if (err)
1478		ses_cache_free(enc, enc_cache);
1479	else {
1480		ses_poll_status(enc);
1481		enc_update_request(enc, SES_PUBLISH_CACHE);
1482	}
1483	ENC_DLOG(enc, "%s: exiting with err %d\n", __func__, err);
1484	return (err);
1485}
1486
1487/**
1488 * \brief Update the status page and associated structures.
1489 *
1490 * \param enc   SES softc to update for.
1491 * \param buf   Buffer containing the status page.
1492 * \param bufsz	Amount of data in the buffer.
1493 *
1494 * \return	0 on success, errno otherwise.
1495 */
1496static int
1497ses_process_status(enc_softc_t *enc, struct enc_fsm_state *state,
1498    union ccb *ccb, uint8_t **bufp, int error, int xfer_len)
1499{
1500	struct ses_iterator iter;
1501	enc_element_t *element;
1502	ses_softc_t *ses;
1503	enc_cache_t *enc_cache;
1504	ses_cache_t *ses_cache;
1505	uint8_t *buf;
1506	int err = -1;
1507	int length;
1508	struct ses_status_page *page;
1509	union ses_status_element *cur_stat;
1510	union ses_status_element *last_stat;
1511
1512	ses = enc->enc_private;
1513	enc_cache = &enc->enc_daemon_cache;
1514	ses_cache = enc_cache->private;
1515	buf = *bufp;
1516
1517	ENC_DLOG(enc, "%s: enter (%p, %p, %d)\n", __func__, enc, buf, xfer_len);
1518	page = (struct ses_status_page *)buf;
1519	length = ses_page_length(&page->hdr);
1520
1521	if (error != 0) {
1522		err = error;
1523		goto out;
1524	}
1525	/*
1526	 * Make sure the length fits in the buffer.
1527	 *
1528	 * XXX all this means is that the page is larger than the space
1529	 * we allocated.  Since we use a statically sized buffer, this
1530	 * could happen... Need to use dynamic discovery of the size.
1531	 */
1532	if (length > xfer_len) {
1533		ENC_VLOG(enc, "Enclosure Status Page Too Long\n");
1534		goto out;
1535	}
1536
1537	/* Check for simple enclosure reporting short enclosure status. */
1538	if (length >= 4 && page->hdr.page_code == SesShortStatus) {
1539		ENC_DLOG(enc, "Got Short Enclosure Status page\n");
1540		ses->ses_flags &= ~(SES_FLAG_ADDLSTATUS | SES_FLAG_DESC);
1541		ses_cache_free(enc, enc_cache);
1542		enc_cache->enc_status = page->hdr.page_specific_flags;
1543		enc_update_request(enc, SES_PUBLISH_CACHE);
1544		err = 0;
1545		goto out;
1546	}
1547
1548	/* Make sure the length contains at least one header and status */
1549	if (length < (sizeof(*page) + sizeof(*page->elements))) {
1550		ENC_VLOG(enc, "Enclosure Status Page Too Short\n");
1551		goto out;
1552	}
1553
1554	if (!ses_config_cache_valid(ses_cache, page->hdr.gen_code)) {
1555		ENC_DLOG(enc, "%s: Generation count change detected\n",
1556		    __func__);
1557		enc_update_request(enc, SES_UPDATE_GETCONFIG);
1558		goto out;
1559	}
1560
1561	ses_cache_free_status(enc, enc_cache);
1562	ses_cache->status_page = page;
1563	*bufp = NULL;
1564
1565	enc_cache->enc_status = page->hdr.page_specific_flags;
1566
1567	/*
1568	 * Read in individual element status.  The element order
1569	 * matches the order reported in the config page (i.e. the
1570	 * order of an unfiltered iteration of the config objects)..
1571	 */
1572	ses_iter_init(enc, enc_cache, &iter);
1573	cur_stat  = page->elements;
1574	last_stat = (union ses_status_element *)
1575	    &buf[length - sizeof(*last_stat)];
1576	ENC_DLOG(enc, "%s: total page length %d, xfer_len %d\n",
1577		__func__, length, xfer_len);
1578	while (cur_stat <= last_stat
1579	    && (element = ses_iter_next(&iter)) != NULL) {
1580
1581		ENC_DLOG(enc, "%s: obj %d(%d,%d) off=0x%tx status=%jx\n",
1582		    __func__, iter.global_element_index, iter.type_index,
1583		    iter.type_element_index, (uint8_t *)cur_stat - buf,
1584		    scsi_4btoul(cur_stat->bytes));
1585
1586		memcpy(&element->encstat, cur_stat, sizeof(element->encstat));
1587		element->svalid = 1;
1588		cur_stat++;
1589	}
1590
1591	if (ses_iter_next(&iter) != NULL) {
1592		ENC_VLOG(enc, "Status page, length insufficient for "
1593			"expected number of objects\n");
1594	} else {
1595		if (cur_stat <= last_stat)
1596			ENC_VLOG(enc, "Status page, exhausted objects before "
1597				"exhausing page\n");
1598		enc_update_request(enc, SES_PUBLISH_CACHE);
1599		err = 0;
1600	}
1601out:
1602	ENC_DLOG(enc, "%s: exiting with error %d\n", __func__, err);
1603	return (err);
1604}
1605
1606typedef enum {
1607	/**
1608	 * The enclosure should not provide additional element
1609	 * status for this element type in page 0x0A.
1610	 *
1611	 * \note  This status is returned for any types not
1612	 *        listed SES3r02.  Further types added in a
1613	 *        future specification will be incorrectly
1614	 *        classified.
1615	 */
1616	TYPE_ADDLSTATUS_NONE,
1617
1618	/**
1619	 * The element type provides additional element status
1620	 * in page 0x0A.
1621	 */
1622	TYPE_ADDLSTATUS_MANDATORY,
1623
1624	/**
1625	 * The element type may provide additional element status
1626	 * in page 0x0A, but i
1627	 */
1628	TYPE_ADDLSTATUS_OPTIONAL
1629} ses_addlstatus_avail_t;
1630
1631/**
1632 * \brief Check to see whether a given type (as obtained via type headers) is
1633 *	  supported by the additional status command.
1634 *
1635 * \param enc     SES softc to check.
1636 * \param typidx  Type index to check for.
1637 *
1638 * \return  An enumeration indicating if additional status is mandatory,
1639 *          optional, or not required for this type.
1640 */
1641static ses_addlstatus_avail_t
1642ses_typehasaddlstatus(enc_softc_t *enc, uint8_t typidx)
1643{
1644	enc_cache_t *enc_cache;
1645	ses_cache_t *ses_cache;
1646
1647	enc_cache = &enc->enc_daemon_cache;
1648	ses_cache = enc_cache->private;
1649	switch(ses_cache->ses_types[typidx].hdr->etype_elm_type) {
1650	case ELMTYP_DEVICE:
1651	case ELMTYP_ARRAY_DEV:
1652	case ELMTYP_SAS_EXP:
1653		return (TYPE_ADDLSTATUS_MANDATORY);
1654	case ELMTYP_SCSI_INI:
1655	case ELMTYP_SCSI_TGT:
1656	case ELMTYP_ESCC:
1657		return (TYPE_ADDLSTATUS_OPTIONAL);
1658	default:
1659		/* No additional status information available. */
1660		break;
1661	}
1662	return (TYPE_ADDLSTATUS_NONE);
1663}
1664
1665static int ses_get_elm_addlstatus_fc(enc_softc_t *, enc_cache_t *,
1666				     uint8_t *, int);
1667static int ses_get_elm_addlstatus_sas(enc_softc_t *, enc_cache_t *, uint8_t *,
1668				      int, int, int, int);
1669
1670/**
1671 * \brief Parse the additional status element data for each object.
1672 *
1673 * \param enc       The SES softc to update.
1674 * \param buf       The buffer containing the additional status
1675 *                  element response.
1676 * \param xfer_len  Size of the buffer.
1677 *
1678 * \return  0 on success, errno otherwise.
1679 */
1680static int
1681ses_process_elm_addlstatus(enc_softc_t *enc, struct enc_fsm_state *state,
1682    union ccb *ccb, uint8_t **bufp, int error, int xfer_len)
1683{
1684	struct ses_iterator iter, titer;
1685	int eip;
1686	int err;
1687	int ignore_index = 0;
1688	int length;
1689	int offset;
1690	enc_cache_t *enc_cache;
1691	ses_cache_t *ses_cache;
1692	uint8_t *buf;
1693	ses_element_t *elmpriv;
1694	const struct ses_page_hdr *hdr;
1695	enc_element_t *element, *telement;
1696
1697	enc_cache = &enc->enc_daemon_cache;
1698	ses_cache = enc_cache->private;
1699	buf = *bufp;
1700	err = -1;
1701
1702	if (error != 0) {
1703		err = error;
1704		goto out;
1705	}
1706	ses_cache_free_elm_addlstatus(enc, enc_cache);
1707	ses_cache->elm_addlstatus_page =
1708	    (struct ses_addl_elem_status_page *)buf;
1709	*bufp = NULL;
1710
1711	/*
1712	 * The objects appear in the same order here as in Enclosure Status,
1713	 * which itself is ordered by the Type Descriptors from the Config
1714	 * page.  However, it is necessary to skip elements that are not
1715	 * supported by this page when counting them.
1716	 */
1717	hdr = &ses_cache->elm_addlstatus_page->hdr;
1718	length = ses_page_length(hdr);
1719	ENC_DLOG(enc, "Additional Element Status Page Length 0x%x\n", length);
1720	/* Make sure the length includes at least one header. */
1721	if (length < sizeof(*hdr)+sizeof(struct ses_elm_addlstatus_base_hdr)) {
1722		ENC_VLOG(enc, "Runt Additional Element Status Page\n");
1723		goto out;
1724	}
1725	if (length > xfer_len) {
1726		ENC_VLOG(enc, "Additional Element Status Page Too Long\n");
1727		goto out;
1728	}
1729
1730	if (!ses_config_cache_valid(ses_cache, hdr->gen_code)) {
1731		ENC_DLOG(enc, "%s: Generation count change detected\n",
1732		    __func__);
1733		enc_update_request(enc, SES_UPDATE_GETCONFIG);
1734		goto out;
1735	}
1736
1737	offset = sizeof(struct ses_page_hdr);
1738	ses_iter_init(enc, enc_cache, &iter);
1739	while (offset < length
1740	    && (element = ses_iter_next(&iter)) != NULL) {
1741		struct ses_elm_addlstatus_base_hdr *elm_hdr;
1742		int proto_info_len;
1743		ses_addlstatus_avail_t status_type;
1744
1745		/*
1746		 * Additional element status is only provided for
1747		 * individual elements (i.e. overal status elements
1748		 * are excluded) and those of the types specified
1749		 * in the SES spec.
1750		 */
1751		status_type = ses_typehasaddlstatus(enc, iter.type_index);
1752		if (iter.individual_element_index == ITERATOR_INDEX_INVALID
1753		 || status_type == TYPE_ADDLSTATUS_NONE)
1754			continue;
1755
1756		elm_hdr = (struct ses_elm_addlstatus_base_hdr *)&buf[offset];
1757		eip = ses_elm_addlstatus_eip(elm_hdr);
1758		if (eip && !ignore_index) {
1759			struct ses_elm_addlstatus_eip_hdr *eip_hdr;
1760			int expected_index, index;
1761			ses_elem_index_type_t index_type;
1762
1763			eip_hdr = (struct ses_elm_addlstatus_eip_hdr *)elm_hdr;
1764			if (eip_hdr->byte2 & SES_ADDL_EIP_EIIOE) {
1765				index_type = SES_ELEM_INDEX_GLOBAL;
1766				expected_index = iter.global_element_index;
1767			} else {
1768				index_type = SES_ELEM_INDEX_INDIVIDUAL;
1769				expected_index = iter.individual_element_index;
1770			}
1771			titer = iter;
1772			telement = ses_iter_seek_to(&titer,
1773			    eip_hdr->element_index, index_type);
1774			if (telement != NULL &&
1775			    (ses_typehasaddlstatus(enc, titer.type_index) !=
1776			     TYPE_ADDLSTATUS_NONE ||
1777			     titer.type_index > ELMTYP_SAS_CONN)) {
1778				iter = titer;
1779				element = telement;
1780			} else
1781				ignore_index = 1;
1782
1783			if (eip_hdr->byte2 & SES_ADDL_EIP_EIIOE)
1784				index = iter.global_element_index;
1785			else
1786				index = iter.individual_element_index;
1787			if (index > expected_index
1788			 && status_type == TYPE_ADDLSTATUS_MANDATORY) {
1789				ENC_VLOG(enc, "%s: provided %s element"
1790					"index %d skips mandatory status "
1791					" element at index %d\n",
1792					__func__, (eip_hdr->byte2 &
1793					SES_ADDL_EIP_EIIOE) ? "global " : "",
1794					index, expected_index);
1795			}
1796		}
1797		elmpriv = element->elm_private;
1798		elmpriv->addl.hdr = elm_hdr;
1799		ENC_DLOG(enc, "%s: global element index=%d, type index=%d "
1800		    "type element index=%d, offset=0x%x, "
1801		    "byte0=0x%x, length=0x%x\n", __func__,
1802		    iter.global_element_index, iter.type_index,
1803		    iter.type_element_index, offset, elmpriv->addl.hdr->byte0,
1804		    elmpriv->addl.hdr->length);
1805
1806		/* Skip to after the length field */
1807		offset += sizeof(struct ses_elm_addlstatus_base_hdr);
1808
1809		/* Make sure the descriptor is within bounds */
1810		if ((offset + elmpriv->addl.hdr->length) > length) {
1811			ENC_VLOG(enc, "Element %d Beyond End "
1812			    "of Additional Element Status Descriptors\n",
1813			    iter.global_element_index);
1814			break;
1815		}
1816
1817		/* Advance to the protocol data, skipping eip bytes if needed */
1818		offset += (eip * SES_EIP_HDR_EXTRA_LEN);
1819		proto_info_len = elmpriv->addl.hdr->length
1820			       - (eip * SES_EIP_HDR_EXTRA_LEN);
1821
1822		/* Errors in this block are ignored as they are non-fatal */
1823		switch(ses_elm_addlstatus_proto(elmpriv->addl.hdr)) {
1824		case SPSP_PROTO_FC:
1825			if (elmpriv->addl.hdr->length == 0)
1826				break;
1827			ses_get_elm_addlstatus_fc(enc, enc_cache,
1828						  &buf[offset], proto_info_len);
1829			break;
1830		case SPSP_PROTO_SAS:
1831			if (elmpriv->addl.hdr->length <= 2)
1832				break;
1833			ses_get_elm_addlstatus_sas(enc, enc_cache,
1834						   &buf[offset],
1835						   proto_info_len,
1836						   eip, iter.type_index,
1837						   iter.global_element_index);
1838			break;
1839		default:
1840			ENC_VLOG(enc, "Element %d: Unknown Additional Element "
1841			    "Protocol 0x%x\n", iter.global_element_index,
1842			    ses_elm_addlstatus_proto(elmpriv->addl.hdr));
1843			break;
1844		}
1845
1846		offset += proto_info_len;
1847	}
1848	err = 0;
1849out:
1850	if (err)
1851		ses_cache_free_elm_addlstatus(enc, enc_cache);
1852	enc_update_request(enc, SES_PUBLISH_PHYSPATHS);
1853	enc_update_request(enc, SES_PUBLISH_CACHE);
1854	return (err);
1855}
1856
1857static int
1858ses_process_control_request(enc_softc_t *enc, struct enc_fsm_state *state,
1859    union ccb *ccb, uint8_t **bufp, int error, int xfer_len)
1860{
1861	ses_softc_t *ses;
1862
1863	ses = enc->enc_private;
1864	/*
1865	 * Possible errors:
1866	 *  o Generation count wrong.
1867	 *  o Some SCSI status error.
1868	 */
1869	ses_terminate_control_requests(&ses->ses_pending_requests, error);
1870	ses_poll_status(enc);
1871	return (0);
1872}
1873
1874static int
1875ses_publish_physpaths(enc_softc_t *enc, struct enc_fsm_state *state,
1876    union ccb *ccb, uint8_t **bufp, int error, int xfer_len)
1877{
1878	struct ses_iterator iter;
1879	enc_cache_t *enc_cache;
1880	ses_cache_t *ses_cache;
1881	enc_element_t *element;
1882
1883	enc_cache = &enc->enc_daemon_cache;
1884	ses_cache = enc_cache->private;
1885
1886	ses_iter_init(enc, enc_cache, &iter);
1887	while ((element = ses_iter_next(&iter)) != NULL) {
1888		/*
1889		 * ses_set_physpath() returns success if we changed
1890		 * the physpath of any element.  This allows us to
1891		 * only announce devices once regardless of how
1892		 * many times we process additional element status.
1893		 */
1894		if (ses_set_physpath(enc, element, &iter) == 0)
1895			ses_print_addl_data(enc, element);
1896	}
1897
1898	return (0);
1899}
1900
1901static int
1902ses_publish_cache(enc_softc_t *enc, struct enc_fsm_state *state,
1903    union ccb *ccb, uint8_t **bufp, int error, int xfer_len)
1904{
1905
1906	sx_xlock(&enc->enc_cache_lock);
1907	ses_cache_clone(enc, /*src*/&enc->enc_daemon_cache,
1908			/*dst*/&enc->enc_cache);
1909	sx_xunlock(&enc->enc_cache_lock);
1910
1911	return (0);
1912}
1913
1914/**
1915 * \brief Parse the descriptors for each object.
1916 *
1917 * \param enc       The SES softc to update.
1918 * \param buf       The buffer containing the descriptor list response.
1919 * \param xfer_len  Size of the buffer.
1920 *
1921 * \return	0 on success, errno otherwise.
1922 */
1923static int
1924ses_process_elm_descs(enc_softc_t *enc, struct enc_fsm_state *state,
1925    union ccb *ccb, uint8_t **bufp, int error, int xfer_len)
1926{
1927	ses_softc_t *ses;
1928	struct ses_iterator iter;
1929	enc_element_t *element;
1930	int err;
1931	int offset;
1932	u_long length, plength;
1933	enc_cache_t *enc_cache;
1934	ses_cache_t *ses_cache;
1935	uint8_t *buf;
1936	ses_element_t *elmpriv;
1937	const struct ses_page_hdr *phdr;
1938	const struct ses_elm_desc_hdr *hdr;
1939
1940	ses = enc->enc_private;
1941	enc_cache = &enc->enc_daemon_cache;
1942	ses_cache = enc_cache->private;
1943	buf = *bufp;
1944	err = -1;
1945
1946	if (error != 0) {
1947		err = error;
1948		goto out;
1949	}
1950	ses_cache_free_elm_descs(enc, enc_cache);
1951	ses_cache->elm_descs_page = (struct ses_elem_descr_page *)buf;
1952	*bufp = NULL;
1953
1954	phdr = &ses_cache->elm_descs_page->hdr;
1955	plength = ses_page_length(phdr);
1956	if (xfer_len < sizeof(struct ses_page_hdr)) {
1957		ENC_VLOG(enc, "Runt Element Descriptor Page\n");
1958		goto out;
1959	}
1960	if (plength > xfer_len) {
1961		ENC_VLOG(enc, "Element Descriptor Page Too Long\n");
1962		goto out;
1963	}
1964
1965	if (!ses_config_cache_valid(ses_cache, phdr->gen_code)) {
1966		ENC_VLOG(enc, "%s: Generation count change detected\n",
1967		    __func__);
1968		enc_update_request(enc, SES_UPDATE_GETCONFIG);
1969		goto out;
1970	}
1971
1972	offset = sizeof(struct ses_page_hdr);
1973
1974	ses_iter_init(enc, enc_cache, &iter);
1975	while (offset < plength
1976	    && (element = ses_iter_next(&iter)) != NULL) {
1977
1978		if ((offset + sizeof(struct ses_elm_desc_hdr)) > plength) {
1979			ENC_VLOG(enc, "Element %d Descriptor Header Past "
1980			    "End of Buffer\n", iter.global_element_index);
1981			goto out;
1982		}
1983		hdr = (struct ses_elm_desc_hdr *)&buf[offset];
1984		length = scsi_2btoul(hdr->length);
1985		ENC_DLOG(enc, "%s: obj %d(%d,%d) length=%d off=%d\n", __func__,
1986		    iter.global_element_index, iter.type_index,
1987		    iter.type_element_index, length, offset);
1988		if ((offset + sizeof(*hdr) + length) > plength) {
1989			ENC_VLOG(enc, "Element%d Descriptor Past "
1990			    "End of Buffer\n", iter.global_element_index);
1991			goto out;
1992		}
1993		offset += sizeof(*hdr);
1994
1995		if (length > 0) {
1996			elmpriv = element->elm_private;
1997			elmpriv->descr_len = length;
1998			elmpriv->descr = &buf[offset];
1999		}
2000
2001		/* skip over the descriptor itself */
2002		offset += length;
2003	}
2004
2005	err = 0;
2006out:
2007	if (err == 0) {
2008		if (ses->ses_flags & SES_FLAG_ADDLSTATUS)
2009			enc_update_request(enc, SES_UPDATE_GETELMADDLSTATUS);
2010	}
2011	enc_update_request(enc, SES_PUBLISH_CACHE);
2012	return (err);
2013}
2014
2015static int
2016ses_fill_rcv_diag_io(enc_softc_t *enc, struct enc_fsm_state *state,
2017		       union ccb *ccb, uint8_t *buf)
2018{
2019
2020	if (enc->enc_type == ENC_SEMB_SES) {
2021		semb_receive_diagnostic_results(&ccb->ataio, /*retries*/5,
2022					NULL, MSG_SIMPLE_Q_TAG, /*pcv*/1,
2023					state->page_code, buf, state->buf_size,
2024					state->timeout);
2025	} else {
2026		scsi_receive_diagnostic_results(&ccb->csio, /*retries*/5,
2027					NULL, MSG_SIMPLE_Q_TAG, /*pcv*/1,
2028					state->page_code, buf, state->buf_size,
2029					SSD_FULL_SIZE, state->timeout);
2030	}
2031	return (0);
2032}
2033
2034/**
2035 * \brief Encode the object status into the response buffer, which is
2036 *	  expected to contain the current enclosure status.  This function
2037 *	  turns off all the 'select' bits for the objects except for the
2038 *	  object specified, then sends it back to the enclosure.
2039 *
2040 * \param enc	SES enclosure the change is being applied to.
2041 * \param buf	Buffer containing the current enclosure status response.
2042 * \param amt	Length of the response in the buffer.
2043 * \param req	The control request to be applied to buf.
2044 *
2045 * \return	0 on success, errno otherwise.
2046 */
2047static int
2048ses_encode(enc_softc_t *enc, uint8_t *buf, int amt, ses_control_request_t *req)
2049{
2050	struct ses_iterator iter;
2051	enc_element_t *element;
2052	int offset;
2053	struct ses_control_page_hdr *hdr;
2054
2055	ses_iter_init(enc, &enc->enc_cache, &iter);
2056	hdr = (struct ses_control_page_hdr *)buf;
2057	if (req->elm_idx == -1) {
2058		/* for enclosure status, at least 2 bytes are needed */
2059		if (amt < 2)
2060			return EIO;
2061		hdr->control_flags =
2062		    req->elm_stat.comstatus & SES_SET_STATUS_MASK;
2063		ENC_DLOG(enc, "Set EncStat %x\n", hdr->control_flags);
2064		return (0);
2065	}
2066
2067	element = ses_iter_seek_to(&iter, req->elm_idx, SES_ELEM_INDEX_GLOBAL);
2068	if (element == NULL)
2069		return (ENXIO);
2070
2071	/*
2072	 * Seek to the type set that corresponds to the requested object.
2073	 * The +1 is for the overall status element for the type.
2074	 */
2075	offset = sizeof(struct ses_control_page_hdr)
2076	       + (iter.global_element_index * sizeof(struct ses_comstat));
2077
2078	/* Check for buffer overflow. */
2079	if (offset + sizeof(struct ses_comstat) > amt)
2080		return (EIO);
2081
2082	/* Set the status. */
2083	memcpy(&buf[offset], &req->elm_stat, sizeof(struct ses_comstat));
2084
2085	ENC_DLOG(enc, "Set Type 0x%x Obj 0x%x (offset %d) with %x %x %x %x\n",
2086	    iter.type_index, iter.global_element_index, offset,
2087	    req->elm_stat.comstatus, req->elm_stat.comstat[0],
2088	    req->elm_stat.comstat[1], req->elm_stat.comstat[2]);
2089
2090	return (0);
2091}
2092
2093static int
2094ses_fill_control_request(enc_softc_t *enc, struct enc_fsm_state *state,
2095			 union ccb *ccb, uint8_t *buf)
2096{
2097	ses_softc_t			*ses;
2098	enc_cache_t			*enc_cache;
2099	ses_cache_t			*ses_cache;
2100	struct ses_control_page_hdr	*hdr;
2101	ses_control_request_t		*req;
2102	size_t				 plength;
2103	size_t				 offset;
2104
2105	ses = enc->enc_private;
2106	enc_cache = &enc->enc_daemon_cache;
2107	ses_cache = enc_cache->private;
2108	hdr = (struct ses_control_page_hdr *)buf;
2109
2110	if (ses_cache->status_page == NULL) {
2111		ses_terminate_control_requests(&ses->ses_requests, EIO);
2112		return (EIO);
2113	}
2114
2115	plength = ses_page_length(&ses_cache->status_page->hdr);
2116	memcpy(buf, ses_cache->status_page, plength);
2117
2118	/* Disable the select bits in all status entries.  */
2119	offset = sizeof(struct ses_control_page_hdr);
2120	for (offset = sizeof(struct ses_control_page_hdr);
2121	     offset < plength; offset += sizeof(struct ses_comstat)) {
2122		buf[offset] &= ~SESCTL_CSEL;
2123	}
2124
2125	/* And make sure the INVOP bit is clear.  */
2126	hdr->control_flags &= ~SES_ENCSTAT_INVOP;
2127
2128	/* Apply incoming requests. */
2129	while ((req = TAILQ_FIRST(&ses->ses_requests)) != NULL) {
2130
2131		TAILQ_REMOVE(&ses->ses_requests, req, links);
2132		req->result = ses_encode(enc, buf, plength, req);
2133		if (req->result != 0) {
2134			wakeup(req);
2135			continue;
2136		}
2137		TAILQ_INSERT_TAIL(&ses->ses_pending_requests, req, links);
2138	}
2139
2140	if (TAILQ_EMPTY(&ses->ses_pending_requests) != 0)
2141		return (ENOENT);
2142
2143	/* Fill out the ccb */
2144	if (enc->enc_type == ENC_SEMB_SES) {
2145		semb_send_diagnostic(&ccb->ataio, /*retries*/5, NULL,
2146			     MSG_SIMPLE_Q_TAG,
2147			     buf, ses_page_length(&ses_cache->status_page->hdr),
2148			     state->timeout);
2149	} else {
2150		scsi_send_diagnostic(&ccb->csio, /*retries*/5, NULL,
2151			     MSG_SIMPLE_Q_TAG, /*unit_offline*/0,
2152			     /*device_offline*/0, /*self_test*/0,
2153			     /*page_format*/1, /*self_test_code*/0,
2154			     buf, ses_page_length(&ses_cache->status_page->hdr),
2155			     SSD_FULL_SIZE, state->timeout);
2156	}
2157	return (0);
2158}
2159
2160static int
2161ses_get_elm_addlstatus_fc(enc_softc_t *enc, enc_cache_t *enc_cache,
2162			  uint8_t *buf, int bufsiz)
2163{
2164	ENC_VLOG(enc, "FC Device Support Stubbed in Additional Status Page\n");
2165	return (ENODEV);
2166}
2167
2168#define	SES_PRINT_PORTS(p, type) do {					\
2169	sbuf_printf(sbp, " %s(", type);					\
2170	if (((p) & SES_SASOBJ_DEV_PHY_PROTOMASK) == 0)			\
2171		sbuf_printf(sbp, " None");				\
2172	else {								\
2173		if ((p) & SES_SASOBJ_DEV_PHY_SMP)			\
2174			sbuf_printf(sbp, " SMP");			\
2175		if ((p) & SES_SASOBJ_DEV_PHY_STP)			\
2176			sbuf_printf(sbp, " STP");			\
2177		if ((p) & SES_SASOBJ_DEV_PHY_SSP)			\
2178			sbuf_printf(sbp, " SSP");			\
2179	}								\
2180	sbuf_printf(sbp, " )");						\
2181} while(0)
2182
2183/**
2184 * \brief Print the additional element status data for this object, for SAS
2185 * 	  type 0 objects.  See SES2 r20 Section 6.1.13.3.2.
2186 *
2187 * \param sesname	SES device name associated with the object.
2188 * \param sbp		Sbuf to print to.
2189 * \param obj		The object to print the data for.
2190 * \param periph_name	Peripheral string associated with the object.
2191 */
2192static void
2193ses_print_addl_data_sas_type0(char *sesname, struct sbuf *sbp,
2194			      enc_element_t *obj, char *periph_name)
2195{
2196	int i;
2197	ses_element_t *elmpriv;
2198	struct ses_addl_status *addl;
2199	struct ses_elm_sas_device_phy *phy;
2200
2201	elmpriv = obj->elm_private;
2202	addl = &(elmpriv->addl);
2203	if (addl->proto_hdr.sas == NULL)
2204		return;
2205	sbuf_printf(sbp, "%s: %s: SAS Device Slot Element:",
2206	    sesname, periph_name);
2207	sbuf_printf(sbp, " %d Phys", addl->proto_hdr.sas->base_hdr.num_phys);
2208	if (ses_elm_addlstatus_eip(addl->hdr))
2209		sbuf_printf(sbp, " at Slot %d",
2210		    addl->proto_hdr.sas->type0_eip.dev_slot_num);
2211	if (ses_elm_sas_type0_not_all_phys(addl->proto_hdr.sas))
2212		sbuf_printf(sbp, ", Not All Phys");
2213	sbuf_printf(sbp, "\n");
2214	if (addl->proto_data.sasdev_phys == NULL)
2215		return;
2216	for (i = 0;i < addl->proto_hdr.sas->base_hdr.num_phys;i++) {
2217		phy = &addl->proto_data.sasdev_phys[i];
2218		sbuf_printf(sbp, "%s:  phy %d:", sesname, i);
2219		if (ses_elm_sas_dev_phy_sata_dev(phy))
2220			/* Spec says all other fields are specific values */
2221			sbuf_printf(sbp, " SATA device\n");
2222		else {
2223			sbuf_printf(sbp, " SAS device type %d id %d\n",
2224			    ses_elm_sas_dev_phy_dev_type(phy), phy->phy_id);
2225			sbuf_printf(sbp, "%s:  phy %d: protocols:", sesname, i);
2226			SES_PRINT_PORTS(phy->initiator_ports, "Initiator");
2227			SES_PRINT_PORTS(phy->target_ports, "Target");
2228			sbuf_printf(sbp, "\n");
2229		}
2230		sbuf_printf(sbp, "%s:  phy %d: parent %jx addr %jx\n",
2231		    sesname, i,
2232		    (uintmax_t)scsi_8btou64(phy->parent_addr),
2233		    (uintmax_t)scsi_8btou64(phy->phy_addr));
2234	}
2235}
2236#undef SES_PRINT_PORTS
2237
2238/**
2239 * \brief Report whether a given enclosure object is an expander.
2240 *
2241 * \param enc	SES softc associated with object.
2242 * \param obj	Enclosure object to report for.
2243 *
2244 * \return	1 if true, 0 otherwise.
2245 */
2246static int
2247ses_obj_is_expander(enc_softc_t *enc, enc_element_t *obj)
2248{
2249	return (obj->enctype == ELMTYP_SAS_EXP);
2250}
2251
2252/**
2253 * \brief Print the additional element status data for this object, for SAS
2254 *	  type 1 objects.  See SES2 r20 Sections 6.1.13.3.3 and 6.1.13.3.4.
2255 *
2256 * \param enc		SES enclosure, needed for type identification.
2257 * \param sesname	SES device name associated with the object.
2258 * \param sbp		Sbuf to print to.
2259 * \param obj		The object to print the data for.
2260 * \param periph_name	Peripheral string associated with the object.
2261 */
2262static void
2263ses_print_addl_data_sas_type1(enc_softc_t *enc, char *sesname,
2264    struct sbuf *sbp, enc_element_t *obj, char *periph_name)
2265{
2266	int i, num_phys;
2267	ses_element_t *elmpriv;
2268	struct ses_addl_status *addl;
2269	struct ses_elm_sas_expander_phy *exp_phy;
2270	struct ses_elm_sas_port_phy *port_phy;
2271
2272	elmpriv = obj->elm_private;
2273	addl = &(elmpriv->addl);
2274	if (addl->proto_hdr.sas == NULL)
2275		return;
2276	sbuf_printf(sbp, "%s: %s: SAS ", sesname, periph_name);
2277	if (ses_obj_is_expander(enc, obj)) {
2278		num_phys = addl->proto_hdr.sas->base_hdr.num_phys;
2279		sbuf_printf(sbp, "Expander: %d Phys", num_phys);
2280		if (addl->proto_data.sasexp_phys == NULL)
2281			return;
2282		for (i = 0;i < num_phys;i++) {
2283			exp_phy = &addl->proto_data.sasexp_phys[i];
2284			sbuf_printf(sbp, "%s:  phy %d: connector %d other %d\n",
2285			    sesname, i, exp_phy->connector_index,
2286			    exp_phy->other_index);
2287		}
2288	} else {
2289		num_phys = addl->proto_hdr.sas->base_hdr.num_phys;
2290		sbuf_printf(sbp, "Port: %d Phys", num_phys);
2291		if (addl->proto_data.sasport_phys == NULL)
2292			return;
2293		for (i = 0;i < num_phys;i++) {
2294			port_phy = &addl->proto_data.sasport_phys[i];
2295			sbuf_printf(sbp,
2296			    "%s:  phy %d: id %d connector %d other %d\n",
2297			    sesname, i, port_phy->phy_id,
2298			    port_phy->connector_index, port_phy->other_index);
2299			sbuf_printf(sbp, "%s:  phy %d: addr %jx\n", sesname, i,
2300			    (uintmax_t)scsi_8btou64(port_phy->phy_addr));
2301		}
2302	}
2303}
2304
2305/**
2306 * \brief Print the additional element status data for this object.
2307 *
2308 * \param enc		SES softc associated with the object.
2309 * \param obj		The object to print the data for.
2310 */
2311static void
2312ses_print_addl_data(enc_softc_t *enc, enc_element_t *obj)
2313{
2314	ses_element_t *elmpriv;
2315	struct ses_addl_status *addl;
2316	struct sbuf sesname, name, out;
2317
2318	elmpriv = obj->elm_private;
2319	if (elmpriv == NULL)
2320		return;
2321
2322	addl = &(elmpriv->addl);
2323	if (addl->hdr == NULL)
2324		return;
2325
2326	sbuf_new(&sesname, NULL, 16, SBUF_AUTOEXTEND);
2327	sbuf_new(&name, NULL, 16, SBUF_AUTOEXTEND);
2328	sbuf_new(&out, NULL, 512, SBUF_AUTOEXTEND);
2329	ses_paths_iter(enc, obj, ses_elmdevname_callback, &name);
2330	if (sbuf_len(&name) == 0)
2331		sbuf_printf(&name, "(none)");
2332	sbuf_finish(&name);
2333	sbuf_printf(&sesname, "%s%d", enc->periph->periph_name,
2334	    enc->periph->unit_number);
2335	sbuf_finish(&sesname);
2336	if (elmpriv->descr != NULL)
2337		sbuf_printf(&out, "%s: %s: Element descriptor: '%s'\n",
2338		    sbuf_data(&sesname), sbuf_data(&name), elmpriv->descr);
2339	switch(ses_elm_addlstatus_proto(addl->hdr)) {
2340	case SPSP_PROTO_SAS:
2341		switch(ses_elm_sas_descr_type(addl->proto_hdr.sas)) {
2342		case SES_SASOBJ_TYPE_SLOT:
2343			ses_print_addl_data_sas_type0(sbuf_data(&sesname),
2344			    &out, obj, sbuf_data(&name));
2345			break;
2346		case SES_SASOBJ_TYPE_OTHER:
2347			ses_print_addl_data_sas_type1(enc, sbuf_data(&sesname),
2348			    &out, obj, sbuf_data(&name));
2349			break;
2350		default:
2351			break;
2352		}
2353		break;
2354	case SPSP_PROTO_FC:	/* stubbed for now */
2355		break;
2356	default:
2357		break;
2358	}
2359	sbuf_finish(&out);
2360	printf("%s", sbuf_data(&out));
2361	sbuf_delete(&out);
2362	sbuf_delete(&name);
2363	sbuf_delete(&sesname);
2364}
2365
2366/**
2367 * \brief Update the softc with the additional element status data for this
2368 * 	  object, for SAS type 0 objects.
2369 *
2370 * \param enc		SES softc to be updated.
2371 * \param buf		The additional element status response buffer.
2372 * \param bufsiz	Size of the response buffer.
2373 * \param eip		The EIP bit value.
2374 * \param nobj		Number of objects attached to the SES softc.
2375 *
2376 * \return		0 on success, errno otherwise.
2377 */
2378static int
2379ses_get_elm_addlstatus_sas_type0(enc_softc_t *enc, enc_cache_t *enc_cache,
2380				 uint8_t *buf, int bufsiz, int eip, int nobj)
2381{
2382	int err, offset, physz;
2383	enc_element_t *obj;
2384	ses_element_t *elmpriv;
2385	struct ses_addl_status *addl;
2386
2387	err = offset = 0;
2388
2389	/* basic object setup */
2390	obj = &(enc_cache->elm_map[nobj]);
2391	elmpriv = obj->elm_private;
2392	addl = &(elmpriv->addl);
2393
2394	addl->proto_hdr.sas = (union ses_elm_sas_hdr *)&buf[offset];
2395
2396	/* Don't assume this object has any phys */
2397	bzero(&addl->proto_data, sizeof(addl->proto_data));
2398	if (addl->proto_hdr.sas->base_hdr.num_phys == 0)
2399		goto out;
2400
2401	/* Skip forward to the phy list */
2402	if (eip)
2403		offset += sizeof(struct ses_elm_sas_type0_eip_hdr);
2404	else
2405		offset += sizeof(struct ses_elm_sas_type0_base_hdr);
2406
2407	/* Make sure the phy list fits in the buffer */
2408	physz = addl->proto_hdr.sas->base_hdr.num_phys;
2409	physz *= sizeof(struct ses_elm_sas_device_phy);
2410	if (physz > (bufsiz - offset + 4)) {
2411		ENC_VLOG(enc, "Element %d Device Phy List Beyond End Of Buffer\n",
2412		    nobj);
2413		err = EIO;
2414		goto out;
2415	}
2416
2417	/* Point to the phy list */
2418	addl->proto_data.sasdev_phys =
2419	    (struct ses_elm_sas_device_phy *)&buf[offset];
2420
2421out:
2422	return (err);
2423}
2424
2425/**
2426 * \brief Update the softc with the additional element status data for this
2427 * 	  object, for SAS type 1 objects.
2428 *
2429 * \param enc		SES softc to be updated.
2430 * \param buf		The additional element status response buffer.
2431 * \param bufsiz	Size of the response buffer.
2432 * \param eip		The EIP bit value.
2433 * \param nobj		Number of objects attached to the SES softc.
2434 *
2435 * \return		0 on success, errno otherwise.
2436 */
2437static int
2438ses_get_elm_addlstatus_sas_type1(enc_softc_t *enc, enc_cache_t *enc_cache,
2439			         uint8_t *buf, int bufsiz, int eip, int nobj)
2440{
2441	int err, offset, physz;
2442	enc_element_t *obj;
2443	ses_element_t *elmpriv;
2444	struct ses_addl_status *addl;
2445
2446	err = offset = 0;
2447
2448	/* basic object setup */
2449	obj = &(enc_cache->elm_map[nobj]);
2450	elmpriv = obj->elm_private;
2451	addl = &(elmpriv->addl);
2452
2453	addl->proto_hdr.sas = (union ses_elm_sas_hdr *)&buf[offset];
2454
2455	/* Don't assume this object has any phys */
2456	bzero(&addl->proto_data, sizeof(addl->proto_data));
2457	if (addl->proto_hdr.sas->base_hdr.num_phys == 0)
2458		goto out;
2459
2460	/* Process expanders differently from other type1 cases */
2461	if (ses_obj_is_expander(enc, obj)) {
2462		offset += sizeof(struct ses_elm_sas_type1_expander_hdr);
2463		physz = addl->proto_hdr.sas->base_hdr.num_phys *
2464		    sizeof(struct ses_elm_sas_expander_phy);
2465		if (physz > (bufsiz - offset)) {
2466			ENC_VLOG(enc, "Element %d: Expander Phy List Beyond "
2467			    "End Of Buffer\n", nobj);
2468			err = EIO;
2469			goto out;
2470		}
2471		addl->proto_data.sasexp_phys =
2472		    (struct ses_elm_sas_expander_phy *)&buf[offset];
2473	} else {
2474		offset += sizeof(struct ses_elm_sas_type1_nonexpander_hdr);
2475		physz = addl->proto_hdr.sas->base_hdr.num_phys *
2476		    sizeof(struct ses_elm_sas_port_phy);
2477		if (physz > (bufsiz - offset + 4)) {
2478			ENC_VLOG(enc, "Element %d: Port Phy List Beyond End "
2479			    "Of Buffer\n", nobj);
2480			err = EIO;
2481			goto out;
2482		}
2483		addl->proto_data.sasport_phys =
2484		    (struct ses_elm_sas_port_phy *)&buf[offset];
2485	}
2486
2487out:
2488	return (err);
2489}
2490
2491/**
2492 * \brief Update the softc with the additional element status data for this
2493 * 	  object, for SAS objects.
2494 *
2495 * \param enc		SES softc to be updated.
2496 * \param buf		The additional element status response buffer.
2497 * \param bufsiz	Size of the response buffer.
2498 * \param eip		The EIP bit value.
2499 * \param tidx		Type index for this object.
2500 * \param nobj		Number of objects attached to the SES softc.
2501 *
2502 * \return		0 on success, errno otherwise.
2503 */
2504static int
2505ses_get_elm_addlstatus_sas(enc_softc_t *enc, enc_cache_t *enc_cache,
2506			   uint8_t *buf, int bufsiz, int eip, int tidx,
2507			   int nobj)
2508{
2509	int dtype, err;
2510	ses_cache_t *ses_cache;
2511	union ses_elm_sas_hdr *hdr;
2512
2513	/* Need to be able to read the descriptor type! */
2514	if (bufsiz < sizeof(union ses_elm_sas_hdr)) {
2515		err = EIO;
2516		goto out;
2517	}
2518
2519	ses_cache = enc_cache->private;
2520
2521	hdr = (union ses_elm_sas_hdr *)buf;
2522	dtype = ses_elm_sas_descr_type(hdr);
2523	switch(dtype) {
2524	case SES_SASOBJ_TYPE_SLOT:
2525		switch(ses_cache->ses_types[tidx].hdr->etype_elm_type) {
2526		case ELMTYP_DEVICE:
2527		case ELMTYP_ARRAY_DEV:
2528			break;
2529		default:
2530			ENC_VLOG(enc, "Element %d has Additional Status type 0, "
2531			    "invalid for SES element type 0x%x\n", nobj,
2532			    ses_cache->ses_types[tidx].hdr->etype_elm_type);
2533			err = ENODEV;
2534			goto out;
2535		}
2536		err = ses_get_elm_addlstatus_sas_type0(enc, enc_cache,
2537						       buf, bufsiz, eip,
2538		    nobj);
2539		break;
2540	case SES_SASOBJ_TYPE_OTHER:
2541		switch(ses_cache->ses_types[tidx].hdr->etype_elm_type) {
2542		case ELMTYP_SAS_EXP:
2543		case ELMTYP_SCSI_INI:
2544		case ELMTYP_SCSI_TGT:
2545		case ELMTYP_ESCC:
2546			break;
2547		default:
2548			ENC_VLOG(enc, "Element %d has Additional Status type 1, "
2549			    "invalid for SES element type 0x%x\n", nobj,
2550			    ses_cache->ses_types[tidx].hdr->etype_elm_type);
2551			err = ENODEV;
2552			goto out;
2553		}
2554		err = ses_get_elm_addlstatus_sas_type1(enc, enc_cache, buf,
2555						       bufsiz, eip, nobj);
2556		break;
2557	default:
2558		ENC_VLOG(enc, "Element %d of type 0x%x has Additional Status "
2559		    "of unknown type 0x%x\n", nobj,
2560		    ses_cache->ses_types[tidx].hdr->etype_elm_type, dtype);
2561		err = ENODEV;
2562		break;
2563	}
2564
2565out:
2566	return (err);
2567}
2568
2569static void
2570ses_softc_invalidate(enc_softc_t *enc)
2571{
2572	ses_softc_t *ses;
2573
2574	ses = enc->enc_private;
2575	ses_terminate_control_requests(&ses->ses_requests, ENXIO);
2576}
2577
2578static void
2579ses_softc_cleanup(enc_softc_t *enc)
2580{
2581
2582	ses_cache_free(enc, &enc->enc_cache);
2583	ses_cache_free(enc, &enc->enc_daemon_cache);
2584	ENC_FREE_AND_NULL(enc->enc_private);
2585	ENC_FREE_AND_NULL(enc->enc_cache.private);
2586	ENC_FREE_AND_NULL(enc->enc_daemon_cache.private);
2587}
2588
2589static int
2590ses_init_enc(enc_softc_t *enc)
2591{
2592	return (0);
2593}
2594
2595static int
2596ses_get_enc_status(enc_softc_t *enc, int slpflag)
2597{
2598	/* Automatically updated, caller checks enc_cache->encstat itself */
2599	return (0);
2600}
2601
2602static int
2603ses_set_enc_status(enc_softc_t *enc, uint8_t encstat, int slpflag)
2604{
2605	ses_control_request_t req;
2606	ses_softc_t	     *ses;
2607
2608	ses = enc->enc_private;
2609	req.elm_idx = SES_SETSTATUS_ENC_IDX;
2610	req.elm_stat.comstatus = encstat & 0xf;
2611
2612	TAILQ_INSERT_TAIL(&ses->ses_requests, &req, links);
2613	enc_update_request(enc, SES_PROCESS_CONTROL_REQS);
2614	cam_periph_sleep(enc->periph, &req, PUSER, "encstat", 0);
2615
2616	return (req.result);
2617}
2618
2619static int
2620ses_get_elm_status(enc_softc_t *enc, encioc_elm_status_t *elms, int slpflag)
2621{
2622	unsigned int i = elms->elm_idx;
2623
2624	memcpy(elms->cstat, &enc->enc_cache.elm_map[i].encstat, 4);
2625	return (0);
2626}
2627
2628static int
2629ses_set_elm_status(enc_softc_t *enc, encioc_elm_status_t *elms, int slpflag)
2630{
2631	ses_control_request_t req;
2632	ses_softc_t	     *ses;
2633
2634	/* If this is clear, we don't do diddly.  */
2635	if ((elms->cstat[0] & SESCTL_CSEL) == 0)
2636		return (0);
2637
2638	ses = enc->enc_private;
2639	req.elm_idx = elms->elm_idx;
2640	memcpy(&req.elm_stat, elms->cstat, sizeof(req.elm_stat));
2641
2642	TAILQ_INSERT_TAIL(&ses->ses_requests, &req, links);
2643	enc_update_request(enc, SES_PROCESS_CONTROL_REQS);
2644	cam_periph_sleep(enc->periph, &req, PUSER, "encstat", 0);
2645
2646	return (req.result);
2647}
2648
2649static int
2650ses_get_elm_desc(enc_softc_t *enc, encioc_elm_desc_t *elmd)
2651{
2652	int i = (int)elmd->elm_idx;
2653	ses_element_t *elmpriv;
2654
2655	/* Assume caller has already checked obj_id validity */
2656	elmpriv = enc->enc_cache.elm_map[i].elm_private;
2657	/* object might not have a descriptor */
2658	if (elmpriv == NULL || elmpriv->descr == NULL) {
2659		elmd->elm_desc_len = 0;
2660		return (0);
2661	}
2662	if (elmd->elm_desc_len > elmpriv->descr_len)
2663		elmd->elm_desc_len = elmpriv->descr_len;
2664	copyout(elmpriv->descr, elmd->elm_desc_str, elmd->elm_desc_len);
2665	return (0);
2666}
2667
2668/**
2669 * \brief Respond to ENCIOC_GETELMDEVNAME, providing a device name for the
2670 *	  given object id if one is available.
2671 *
2672 * \param enc	SES softc to examine.
2673 * \param objdn	ioctl structure to read/write device name info.
2674 *
2675 * \return	0 on success, errno otherwise.
2676 */
2677static int
2678ses_get_elm_devnames(enc_softc_t *enc, encioc_elm_devnames_t *elmdn)
2679{
2680	struct sbuf sb;
2681	int len;
2682
2683	len = elmdn->elm_names_size;
2684	if (len < 0)
2685		return (EINVAL);
2686
2687	cam_periph_unlock(enc->periph);
2688	sbuf_new(&sb, NULL, len, SBUF_FIXEDLEN);
2689	ses_paths_iter(enc, &enc->enc_cache.elm_map[elmdn->elm_idx],
2690	    ses_elmdevname_callback, &sb);
2691	sbuf_finish(&sb);
2692	elmdn->elm_names_len = sbuf_len(&sb);
2693	copyout(sbuf_data(&sb), elmdn->elm_devnames, elmdn->elm_names_len + 1);
2694	sbuf_delete(&sb);
2695	cam_periph_lock(enc->periph);
2696	return (elmdn->elm_names_len > 0 ? 0 : ENODEV);
2697}
2698
2699/**
2700 * \brief Send a string to the primary subenclosure using the String Out
2701 * 	  SES diagnostic page.
2702 *
2703 * \param enc	SES enclosure to run the command on.
2704 * \param sstr	SES string structure to operate on
2705 * \param ioc	Ioctl being performed
2706 *
2707 * \return	0 on success, errno otherwise.
2708 */
2709static int
2710ses_handle_string(enc_softc_t *enc, encioc_string_t *sstr, int ioc)
2711{
2712	ses_softc_t *ses;
2713	enc_cache_t *enc_cache;
2714	ses_cache_t *ses_cache;
2715	const struct ses_enc_desc *enc_desc;
2716	int amt, payload, ret;
2717	char cdb[6];
2718	char str[32];
2719	char vendor[9];
2720	char product[17];
2721	char rev[5];
2722	uint8_t *buf;
2723	size_t size, rsize;
2724
2725	ses = enc->enc_private;
2726	enc_cache = &enc->enc_daemon_cache;
2727	ses_cache = enc_cache->private;
2728
2729	/* Implement SES2r20 6.1.6 */
2730	if (sstr->bufsiz > 0xffff)
2731		return (EINVAL); /* buffer size too large */
2732
2733	if (ioc == ENCIOC_SETSTRING) {
2734		payload = sstr->bufsiz + 4; /* header for SEND DIAGNOSTIC */
2735		amt = 0 - payload;
2736		buf = ENC_MALLOC(payload);
2737		if (buf == NULL)
2738			return ENOMEM;
2739
2740		ses_page_cdb(cdb, payload, 0, CAM_DIR_OUT);
2741		/* Construct the page request */
2742		buf[0] = SesStringOut;
2743		buf[1] = 0;
2744		buf[2] = sstr->bufsiz >> 8;
2745		buf[3] = sstr->bufsiz & 0xff;
2746		memcpy(&buf[4], sstr->buf, sstr->bufsiz);
2747	} else if (ioc == ENCIOC_GETSTRING) {
2748		payload = sstr->bufsiz;
2749		amt = payload;
2750		ses_page_cdb(cdb, payload, SesStringIn, CAM_DIR_IN);
2751		buf = sstr->buf;
2752	} else if (ioc == ENCIOC_GETENCNAME) {
2753		if (ses_cache->ses_nsubencs < 1)
2754			return (ENODEV);
2755		enc_desc = ses_cache->subencs[0];
2756		cam_strvis(vendor, enc_desc->vendor_id,
2757		    sizeof(enc_desc->vendor_id), sizeof(vendor));
2758		cam_strvis(product, enc_desc->product_id,
2759		    sizeof(enc_desc->product_id), sizeof(product));
2760		cam_strvis(rev, enc_desc->product_rev,
2761		    sizeof(enc_desc->product_rev), sizeof(rev));
2762		rsize = snprintf(str, sizeof(str), "%s %s %s",
2763		    vendor, product, rev) + 1;
2764		if (rsize > sizeof(str))
2765			rsize = sizeof(str);
2766		copyout(&rsize, &sstr->bufsiz, sizeof(rsize));
2767		size = rsize;
2768		if (size > sstr->bufsiz)
2769			size = sstr->bufsiz;
2770		copyout(str, sstr->buf, size);
2771		return (size == rsize ? 0 : ENOMEM);
2772	} else if (ioc == ENCIOC_GETENCID) {
2773		if (ses_cache->ses_nsubencs < 1)
2774			return (ENODEV);
2775		enc_desc = ses_cache->subencs[0];
2776		rsize = snprintf(str, sizeof(str), "%16jx",
2777		    scsi_8btou64(enc_desc->logical_id)) + 1;
2778		if (rsize > sizeof(str))
2779			rsize = sizeof(str);
2780		copyout(&rsize, &sstr->bufsiz, sizeof(rsize));
2781		size = rsize;
2782		if (size > sstr->bufsiz)
2783			size = sstr->bufsiz;
2784		copyout(str, sstr->buf, size);
2785		return (size == rsize ? 0 : ENOMEM);
2786	} else
2787		return EINVAL;
2788
2789	ret = enc_runcmd(enc, cdb, 6, buf, &amt);
2790	if (ioc == ENCIOC_SETSTRING)
2791		ENC_FREE(buf);
2792	return ret;
2793}
2794
2795/**
2796 * \invariant Called with cam_periph mutex held.
2797 */
2798static void
2799ses_poll_status(enc_softc_t *enc)
2800{
2801	ses_softc_t *ses;
2802
2803	ses = enc->enc_private;
2804	enc_update_request(enc, SES_UPDATE_GETSTATUS);
2805	if (ses->ses_flags & SES_FLAG_DESC)
2806		enc_update_request(enc, SES_UPDATE_GETELMDESCS);
2807	if (ses->ses_flags & SES_FLAG_ADDLSTATUS)
2808		enc_update_request(enc, SES_UPDATE_GETELMADDLSTATUS);
2809}
2810
2811/**
2812 * \brief Notification received when CAM detects a new device in the
2813 *        SCSI domain in which this SEP resides.
2814 *
2815 * \param enc	SES enclosure instance.
2816 */
2817static void
2818ses_device_found(enc_softc_t *enc)
2819{
2820	ses_poll_status(enc);
2821	enc_update_request(enc, SES_PUBLISH_PHYSPATHS);
2822}
2823
2824static struct enc_vec ses_enc_vec =
2825{
2826	.softc_invalidate	= ses_softc_invalidate,
2827	.softc_cleanup		= ses_softc_cleanup,
2828	.init_enc		= ses_init_enc,
2829	.get_enc_status		= ses_get_enc_status,
2830	.set_enc_status		= ses_set_enc_status,
2831	.get_elm_status		= ses_get_elm_status,
2832	.set_elm_status		= ses_set_elm_status,
2833	.get_elm_desc		= ses_get_elm_desc,
2834	.get_elm_devnames	= ses_get_elm_devnames,
2835	.handle_string		= ses_handle_string,
2836	.device_found		= ses_device_found,
2837	.poll_status		= ses_poll_status
2838};
2839
2840/**
2841 * \brief Initialize a new SES instance.
2842 *
2843 * \param enc		SES softc structure to set up the instance in.
2844 * \param doinit	Do the initialization (see main driver).
2845 *
2846 * \return		0 on success, errno otherwise.
2847 */
2848int
2849ses_softc_init(enc_softc_t *enc)
2850{
2851	ses_softc_t *ses_softc;
2852
2853	CAM_DEBUG(enc->periph->path, CAM_DEBUG_SUBTRACE,
2854	    ("entering enc_softc_init(%p)\n", enc));
2855
2856	enc->enc_vec = ses_enc_vec;
2857	enc->enc_fsm_states = enc_fsm_states;
2858
2859	if (enc->enc_private == NULL)
2860		enc->enc_private = ENC_MALLOCZ(sizeof(ses_softc_t));
2861	if (enc->enc_cache.private == NULL)
2862		enc->enc_cache.private = ENC_MALLOCZ(sizeof(ses_cache_t));
2863	if (enc->enc_daemon_cache.private == NULL)
2864		enc->enc_daemon_cache.private =
2865		     ENC_MALLOCZ(sizeof(ses_cache_t));
2866
2867	if (enc->enc_private == NULL
2868	 || enc->enc_cache.private == NULL
2869	 || enc->enc_daemon_cache.private == NULL) {
2870		ENC_FREE_AND_NULL(enc->enc_private);
2871		ENC_FREE_AND_NULL(enc->enc_cache.private);
2872		ENC_FREE_AND_NULL(enc->enc_daemon_cache.private);
2873		return (ENOMEM);
2874	}
2875
2876	ses_softc = enc->enc_private;
2877	TAILQ_INIT(&ses_softc->ses_requests);
2878	TAILQ_INIT(&ses_softc->ses_pending_requests);
2879
2880	enc_update_request(enc, SES_UPDATE_PAGES);
2881
2882	// XXX: Move this to the FSM so it doesn't hang init
2883	if (0) (void) ses_set_timed_completion(enc, 1);
2884
2885	return (0);
2886}
2887
2888