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