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