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