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