xref: /freebsd/sys/dev/mps/mps_sas_lsi.c (revision 22cf89c938886d14f5796fc49f9f020c23ea8eaf)
1 /*-
2  * SPDX-License-Identifier: BSD-2-Clause
3  *
4  * Copyright (c) 2011-2015 LSI Corp.
5  * Copyright (c) 2013-2015 Avago Technologies
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  * 2. Redistributions in binary form must reproduce the above copyright
14  *    notice, this list of conditions and the following disclaimer in the
15  *    documentation and/or other materials provided with the distribution.
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
21  * FOR 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  * Avago Technologies (LSI) MPT-Fusion Host Adapter FreeBSD
30  */
31 
32 #include <sys/cdefs.h>
33 /* Communications core for Avago Technologies (LSI) MPT2 */
34 
35 /* TODO Move headers to mpsvar */
36 #include <sys/types.h>
37 #include <sys/param.h>
38 #include <sys/systm.h>
39 #include <sys/kernel.h>
40 #include <sys/selinfo.h>
41 #include <sys/module.h>
42 #include <sys/bus.h>
43 #include <sys/conf.h>
44 #include <sys/bio.h>
45 #include <sys/malloc.h>
46 #include <sys/uio.h>
47 #include <sys/sysctl.h>
48 #include <sys/endian.h>
49 #include <sys/proc.h>
50 #include <sys/queue.h>
51 #include <sys/kthread.h>
52 #include <sys/taskqueue.h>
53 #include <sys/sbuf.h>
54 #include <sys/reboot.h>
55 
56 #include <machine/bus.h>
57 #include <machine/resource.h>
58 #include <sys/rman.h>
59 
60 #include <machine/stdarg.h>
61 
62 #include <cam/cam.h>
63 #include <cam/cam_ccb.h>
64 #include <cam/cam_debug.h>
65 #include <cam/cam_sim.h>
66 #include <cam/cam_xpt_sim.h>
67 #include <cam/cam_xpt_periph.h>
68 #include <cam/cam_periph.h>
69 #include <cam/scsi/scsi_all.h>
70 #include <cam/scsi/scsi_message.h>
71 
72 #include <dev/mps/mpi/mpi2_type.h>
73 #include <dev/mps/mpi/mpi2.h>
74 #include <dev/mps/mpi/mpi2_ioc.h>
75 #include <dev/mps/mpi/mpi2_sas.h>
76 #include <dev/mps/mpi/mpi2_cnfg.h>
77 #include <dev/mps/mpi/mpi2_init.h>
78 #include <dev/mps/mpi/mpi2_raid.h>
79 #include <dev/mps/mpi/mpi2_tool.h>
80 #include <dev/mps/mps_ioctl.h>
81 #include <dev/mps/mpsvar.h>
82 #include <dev/mps/mps_table.h>
83 #include <dev/mps/mps_sas.h>
84 
85 /* For Hashed SAS Address creation for SATA Drives */
86 #define MPT2SAS_SN_LEN 20
87 #define MPT2SAS_MN_LEN 40
88 
89 struct mps_fw_event_work {
90 	u16			event;
91 	void			*event_data;
92 	TAILQ_ENTRY(mps_fw_event_work)	ev_link;
93 };
94 
95 union _sata_sas_address {
96 	u8 wwid[8];
97 	struct {
98 		u32 high;
99 		u32 low;
100 	} word;
101 };
102 
103 /*
104  * define the IDENTIFY DEVICE structure
105  */
106 struct _ata_identify_device_data {
107 	u16 reserved1[10];	/* 0-9 */
108 	u16 serial_number[10];	/* 10-19 */
109 	u16 reserved2[7];	/* 20-26 */
110 	u16 model_number[20];	/* 27-46*/
111 	u16 reserved3[170];	/* 47-216 */
112 	u16 rotational_speed;	/* 217 */
113 	u16 reserved4[38];	/* 218-255 */
114 };
115 static u32 event_count;
116 static void mpssas_fw_work(struct mps_softc *sc,
117     struct mps_fw_event_work *fw_event);
118 static void mpssas_fw_event_free(struct mps_softc *,
119     struct mps_fw_event_work *);
120 static int mpssas_add_device(struct mps_softc *sc, u16 handle, u8 linkrate);
121 static int mpssas_get_sata_identify(struct mps_softc *sc, u16 handle,
122     Mpi2SataPassthroughReply_t *mpi_reply, char *id_buffer, int sz,
123     u32 devinfo);
124 static void mpssas_ata_id_complete(struct mps_softc *, struct mps_command *);
125 static void mpssas_ata_id_timeout(struct mps_softc *, struct mps_command *);
126 int mpssas_get_sas_address_for_sata_disk(struct mps_softc *sc,
127     u64 *sas_address, u16 handle, u32 device_info, u8 *is_SATA_SSD);
128 static int mpssas_volume_add(struct mps_softc *sc,
129     u16 handle);
130 static void mpssas_SSU_to_SATA_devices(struct mps_softc *sc, int howto);
131 static void mpssas_stop_unit_done(struct cam_periph *periph,
132     union ccb *done_ccb);
133 
134 void
135 mpssas_evt_handler(struct mps_softc *sc, uintptr_t data,
136     MPI2_EVENT_NOTIFICATION_REPLY *event)
137 {
138 	struct mps_fw_event_work *fw_event;
139 	u16 sz;
140 
141 	mps_dprint(sc, MPS_TRACE, "%s\n", __func__);
142 	MPS_DPRINT_EVENT(sc, sas, event);
143 	mpssas_record_event(sc, event);
144 
145 	fw_event = malloc(sizeof(struct mps_fw_event_work), M_MPT2,
146 	     M_ZERO|M_NOWAIT);
147 	if (!fw_event) {
148 		printf("%s: allocate failed for fw_event\n", __func__);
149 		return;
150 	}
151 	sz = le16toh(event->EventDataLength) * 4;
152 	fw_event->event_data = malloc(sz, M_MPT2, M_ZERO|M_NOWAIT);
153 	if (!fw_event->event_data) {
154 		printf("%s: allocate failed for event_data\n", __func__);
155 		free(fw_event, M_MPT2);
156 		return;
157 	}
158 
159 	bcopy(event->EventData, fw_event->event_data, sz);
160 	fw_event->event = event->Event;
161 	if ((event->Event == MPI2_EVENT_SAS_TOPOLOGY_CHANGE_LIST ||
162 	    event->Event == MPI2_EVENT_SAS_ENCL_DEVICE_STATUS_CHANGE ||
163 	    event->Event == MPI2_EVENT_IR_CONFIGURATION_CHANGE_LIST) &&
164 	    sc->track_mapping_events)
165 		sc->pending_map_events++;
166 
167 	/*
168 	 * When wait_for_port_enable flag is set, make sure that all the events
169 	 * are processed. Increment the startup_refcount and decrement it after
170 	 * events are processed.
171 	 */
172 	if ((event->Event == MPI2_EVENT_SAS_TOPOLOGY_CHANGE_LIST ||
173 	    event->Event == MPI2_EVENT_IR_CONFIGURATION_CHANGE_LIST) &&
174 	    sc->wait_for_port_enable)
175 		mpssas_startup_increment(sc->sassc);
176 
177 	TAILQ_INSERT_TAIL(&sc->sassc->ev_queue, fw_event, ev_link);
178 	taskqueue_enqueue(sc->sassc->ev_tq, &sc->sassc->ev_task);
179 
180 }
181 
182 static void
183 mpssas_fw_event_free(struct mps_softc *sc, struct mps_fw_event_work *fw_event)
184 {
185 
186 	free(fw_event->event_data, M_MPT2);
187 	free(fw_event, M_MPT2);
188 }
189 
190 /**
191  * _mps_fw_work - delayed task for processing firmware events
192  * @sc: per adapter object
193  * @fw_event: The fw_event_work object
194  * Context: user.
195  *
196  * Return nothing.
197  */
198 static void
199 mpssas_fw_work(struct mps_softc *sc, struct mps_fw_event_work *fw_event)
200 {
201 	struct mpssas_softc *sassc;
202 	sassc = sc->sassc;
203 
204 	mps_dprint(sc, MPS_EVENT, "(%d)->(%s) Working on  Event: [%x]\n",
205 			event_count++,__func__,fw_event->event);
206 	switch (fw_event->event) {
207 	case MPI2_EVENT_SAS_TOPOLOGY_CHANGE_LIST:
208 	{
209 		MPI2_EVENT_DATA_SAS_TOPOLOGY_CHANGE_LIST *data;
210 		MPI2_EVENT_SAS_TOPO_PHY_ENTRY *phy;
211 		int i;
212 
213 		data = (MPI2_EVENT_DATA_SAS_TOPOLOGY_CHANGE_LIST *)
214 		    fw_event->event_data;
215 
216 		mps_mapping_topology_change_event(sc, fw_event->event_data);
217 
218 		for (i = 0; i < data->NumEntries; i++) {
219 			phy = &data->PHY[i];
220 			switch (phy->PhyStatus & MPI2_EVENT_SAS_TOPO_RC_MASK) {
221 			case MPI2_EVENT_SAS_TOPO_RC_TARG_ADDED:
222 				if (mpssas_add_device(sc,
223 				    le16toh(phy->AttachedDevHandle),
224 				    phy->LinkRate)){
225 					mps_dprint(sc, MPS_ERROR, "%s: "
226 					    "failed to add device with handle "
227 					    "0x%x\n", __func__,
228 					    le16toh(phy->AttachedDevHandle));
229 					mpssas_prepare_remove(sassc, le16toh(
230 						phy->AttachedDevHandle));
231 				}
232 				break;
233 			case MPI2_EVENT_SAS_TOPO_RC_TARG_NOT_RESPONDING:
234 				mpssas_prepare_remove(sassc,le16toh(
235 					phy->AttachedDevHandle));
236 				break;
237 			case MPI2_EVENT_SAS_TOPO_RC_PHY_CHANGED:
238 			case MPI2_EVENT_SAS_TOPO_RC_NO_CHANGE:
239 			case MPI2_EVENT_SAS_TOPO_RC_DELAY_NOT_RESPONDING:
240 			default:
241 				break;
242 			}
243 		}
244 		/*
245 		 * refcount was incremented for this event in
246 		 * mpssas_evt_handler.  Decrement it here because the event has
247 		 * been processed.
248 		 */
249 		mpssas_startup_decrement(sassc);
250 		break;
251 	}
252 	case MPI2_EVENT_SAS_DISCOVERY:
253 	{
254 		MPI2_EVENT_DATA_SAS_DISCOVERY *data;
255 
256 		data = (MPI2_EVENT_DATA_SAS_DISCOVERY *)fw_event->event_data;
257 
258 		if (data->ReasonCode & MPI2_EVENT_SAS_DISC_RC_STARTED)
259 			mps_dprint(sc, MPS_TRACE,"SAS discovery start event\n");
260 		if (data->ReasonCode & MPI2_EVENT_SAS_DISC_RC_COMPLETED) {
261 			mps_dprint(sc, MPS_TRACE,"SAS discovery stop event\n");
262 			sassc->flags &= ~MPSSAS_IN_DISCOVERY;
263 			mpssas_discovery_end(sassc);
264 		}
265 		break;
266 	}
267 	case MPI2_EVENT_SAS_ENCL_DEVICE_STATUS_CHANGE:
268 	{
269 		mps_mapping_enclosure_dev_status_change_event(sc,
270 		    fw_event->event_data);
271 		break;
272 	}
273 	case MPI2_EVENT_IR_CONFIGURATION_CHANGE_LIST:
274 	{
275 		Mpi2EventIrConfigElement_t *element;
276 		int i;
277 		u8 foreign_config;
278 		Mpi2EventDataIrConfigChangeList_t *event_data;
279 		struct mpssas_target *targ;
280 		unsigned int id;
281 
282 		event_data = fw_event->event_data;
283 		foreign_config = (le32toh(event_data->Flags) &
284 		    MPI2_EVENT_IR_CHANGE_FLAGS_FOREIGN_CONFIG) ? 1 : 0;
285 
286 		element =
287 		    (Mpi2EventIrConfigElement_t *)&event_data->ConfigElement[0];
288 		id = mps_mapping_get_raid_tid_from_handle(sc,
289 		    element->VolDevHandle);
290 
291 		mps_mapping_ir_config_change_event(sc, event_data);
292 
293 		for (i = 0; i < event_data->NumElements; i++, element++) {
294 			switch (element->ReasonCode) {
295 			case MPI2_EVENT_IR_CHANGE_RC_VOLUME_CREATED:
296 			case MPI2_EVENT_IR_CHANGE_RC_ADDED:
297 				if (!foreign_config) {
298 					if (mpssas_volume_add(sc,
299 					    le16toh(element->VolDevHandle))){
300 						printf("%s: failed to add RAID "
301 						    "volume with handle 0x%x\n",
302 						    __func__, le16toh(element->
303 						    VolDevHandle));
304 					}
305 				}
306 				break;
307 			case MPI2_EVENT_IR_CHANGE_RC_VOLUME_DELETED:
308 			case MPI2_EVENT_IR_CHANGE_RC_REMOVED:
309 				/*
310 				 * Rescan after volume is deleted or removed.
311 				 */
312 				if (!foreign_config) {
313 					if (id == MPS_MAP_BAD_ID) {
314 						printf("%s: could not get ID "
315 						    "for volume with handle "
316 						    "0x%04x\n", __func__,
317 						    le16toh(element->VolDevHandle));
318 						break;
319 					}
320 
321 					targ = &sassc->targets[id];
322 					targ->handle = 0x0;
323 					targ->encl_slot = 0x0;
324 					targ->encl_handle = 0x0;
325 					targ->exp_dev_handle = 0x0;
326 					targ->phy_num = 0x0;
327 					targ->linkrate = 0x0;
328 					mpssas_rescan_target(sc, targ);
329 					printf("RAID target id 0x%x removed\n",
330 					    targ->tid);
331 				}
332 				break;
333 			case MPI2_EVENT_IR_CHANGE_RC_PD_CREATED:
334 			case MPI2_EVENT_IR_CHANGE_RC_HIDE:
335 				/*
336 				 * Phys Disk of a volume has been created.  Hide
337 				 * it from the OS.
338 				 */
339 				targ = mpssas_find_target_by_handle(sassc, 0,
340 				    element->PhysDiskDevHandle);
341 				if (targ == NULL)
342 					break;
343 
344 				/*
345 				 * Set raid component flags only if it is not
346 				 * WD. OR WrapDrive with
347 				 * WD_HIDE_ALWAYS/WD_HIDE_IF_VOLUME is set in
348 				 * NVRAM
349 				 */
350 				if((!sc->WD_available) ||
351 				((sc->WD_available &&
352 				(sc->WD_hide_expose == MPS_WD_HIDE_ALWAYS)) ||
353 				(sc->WD_valid_config && (sc->WD_hide_expose ==
354 				MPS_WD_HIDE_IF_VOLUME)))) {
355 					targ->flags |= MPS_TARGET_FLAGS_RAID_COMPONENT;
356 				}
357 				mpssas_rescan_target(sc, targ);
358 
359 				break;
360 			case MPI2_EVENT_IR_CHANGE_RC_PD_DELETED:
361 				/*
362 				 * Phys Disk of a volume has been deleted.
363 				 * Expose it to the OS.
364 				 */
365 				if (mpssas_add_device(sc,
366 				    le16toh(element->PhysDiskDevHandle), 0)){
367 					printf("%s: failed to add device with "
368 					    "handle 0x%x\n", __func__,
369 					    le16toh(element->PhysDiskDevHandle));
370 					mpssas_prepare_remove(sassc, le16toh(element->
371 					    PhysDiskDevHandle));
372 				}
373 				break;
374 			}
375 		}
376 		/*
377 		 * refcount was incremented for this event in
378 		 * mpssas_evt_handler.  Decrement it here because the event has
379 		 * been processed.
380 		 */
381 		mpssas_startup_decrement(sassc);
382 		break;
383 	}
384 	case MPI2_EVENT_IR_VOLUME:
385 	{
386 		Mpi2EventDataIrVolume_t *event_data = fw_event->event_data;
387 
388 		/*
389 		 * Informational only.
390 		 */
391 		mps_dprint(sc, MPS_EVENT, "Received IR Volume event:\n");
392 		switch (event_data->ReasonCode) {
393 		case MPI2_EVENT_IR_VOLUME_RC_SETTINGS_CHANGED:
394   			mps_dprint(sc, MPS_EVENT, "   Volume Settings "
395   			    "changed from 0x%x to 0x%x for Volome with "
396  			    "handle 0x%x", le32toh(event_data->PreviousValue),
397  			    le32toh(event_data->NewValue),
398  			    le16toh(event_data->VolDevHandle));
399 			break;
400 		case MPI2_EVENT_IR_VOLUME_RC_STATUS_FLAGS_CHANGED:
401   			mps_dprint(sc, MPS_EVENT, "   Volume Status "
402   			    "changed from 0x%x to 0x%x for Volome with "
403  			    "handle 0x%x", le32toh(event_data->PreviousValue),
404  			    le32toh(event_data->NewValue),
405  			    le16toh(event_data->VolDevHandle));
406 			break;
407 		case MPI2_EVENT_IR_VOLUME_RC_STATE_CHANGED:
408   			mps_dprint(sc, MPS_EVENT, "   Volume State "
409   			    "changed from 0x%x to 0x%x for Volome with "
410  			    "handle 0x%x", le32toh(event_data->PreviousValue),
411  			    le32toh(event_data->NewValue),
412  			    le16toh(event_data->VolDevHandle));
413 				u32 state;
414 				struct mpssas_target *targ;
415 				state = le32toh(event_data->NewValue);
416 				switch (state) {
417 				case MPI2_RAID_VOL_STATE_MISSING:
418 				case MPI2_RAID_VOL_STATE_FAILED:
419 					mpssas_prepare_volume_remove(sassc, event_data->
420 							VolDevHandle);
421 					break;
422 
423 				case MPI2_RAID_VOL_STATE_ONLINE:
424 				case MPI2_RAID_VOL_STATE_DEGRADED:
425 				case MPI2_RAID_VOL_STATE_OPTIMAL:
426 					targ = mpssas_find_target_by_handle(sassc, 0, event_data->VolDevHandle);
427 					if (targ) {
428 						printf("%s %d: Volume handle 0x%x is already added \n",
429 							       	__func__, __LINE__ , event_data->VolDevHandle);
430 						break;
431 					}
432 					if (mpssas_volume_add(sc, le16toh(event_data->VolDevHandle))) {
433 						printf("%s: failed to add RAID "
434 							"volume with handle 0x%x\n",
435 							__func__, le16toh(event_data->
436 							VolDevHandle));
437 					}
438 					break;
439 				default:
440 					break;
441 				}
442 			break;
443 		default:
444 			break;
445 		}
446 		break;
447 	}
448 	case MPI2_EVENT_IR_PHYSICAL_DISK:
449 	{
450 		Mpi2EventDataIrPhysicalDisk_t *event_data =
451 		    fw_event->event_data;
452 		struct mpssas_target *targ;
453 
454 		/*
455 		 * Informational only.
456 		 */
457 		mps_dprint(sc, MPS_EVENT, "Received IR Phys Disk event:\n");
458 		switch (event_data->ReasonCode) {
459 		case MPI2_EVENT_IR_PHYSDISK_RC_SETTINGS_CHANGED:
460   			mps_dprint(sc, MPS_EVENT, "   Phys Disk Settings "
461   			    "changed from 0x%x to 0x%x for Phys Disk Number "
462   			    "%d and handle 0x%x at Enclosure handle 0x%x, Slot "
463  			    "%d", le32toh(event_data->PreviousValue),
464  			    le32toh(event_data->NewValue),
465  				event_data->PhysDiskNum,
466  			    le16toh(event_data->PhysDiskDevHandle),
467  			    le16toh(event_data->EnclosureHandle), le16toh(event_data->Slot));
468 			break;
469 		case MPI2_EVENT_IR_PHYSDISK_RC_STATUS_FLAGS_CHANGED:
470   			mps_dprint(sc, MPS_EVENT, "   Phys Disk Status changed "
471   			    "from 0x%x to 0x%x for Phys Disk Number %d and "
472   			    "handle 0x%x at Enclosure handle 0x%x, Slot %d",
473  				le32toh(event_data->PreviousValue),
474  			    le32toh(event_data->NewValue), event_data->PhysDiskNum,
475  			    le16toh(event_data->PhysDiskDevHandle),
476  			    le16toh(event_data->EnclosureHandle), le16toh(event_data->Slot));
477 			break;
478 		case MPI2_EVENT_IR_PHYSDISK_RC_STATE_CHANGED:
479   			mps_dprint(sc, MPS_EVENT, "   Phys Disk State changed "
480   			    "from 0x%x to 0x%x for Phys Disk Number %d and "
481   			    "handle 0x%x at Enclosure handle 0x%x, Slot %d",
482  				le32toh(event_data->PreviousValue),
483  			    le32toh(event_data->NewValue), event_data->PhysDiskNum,
484  			    le16toh(event_data->PhysDiskDevHandle),
485  			    le16toh(event_data->EnclosureHandle), le16toh(event_data->Slot));
486 			switch (event_data->NewValue) {
487 				case MPI2_RAID_PD_STATE_ONLINE:
488 				case MPI2_RAID_PD_STATE_DEGRADED:
489 				case MPI2_RAID_PD_STATE_REBUILDING:
490 				case MPI2_RAID_PD_STATE_OPTIMAL:
491 				case MPI2_RAID_PD_STATE_HOT_SPARE:
492 					targ = mpssas_find_target_by_handle(sassc, 0,
493 							event_data->PhysDiskDevHandle);
494 					if (targ) {
495 						if(!sc->WD_available) {
496 							targ->flags |= MPS_TARGET_FLAGS_RAID_COMPONENT;
497 							printf("%s %d: Found Target for handle 0x%x.  \n",
498 							__func__, __LINE__ , event_data->PhysDiskDevHandle);
499 						} else if ((sc->WD_available &&
500 							(sc->WD_hide_expose == MPS_WD_HIDE_ALWAYS)) ||
501         						(sc->WD_valid_config && (sc->WD_hide_expose ==
502         						MPS_WD_HIDE_IF_VOLUME))) {
503 							targ->flags |= MPS_TARGET_FLAGS_RAID_COMPONENT;
504 							printf("%s %d: WD: Found Target for handle 0x%x.  \n",
505 							__func__, __LINE__ , event_data->PhysDiskDevHandle);
506 						}
507  					}
508 				break;
509 				case MPI2_RAID_PD_STATE_OFFLINE:
510 				case MPI2_RAID_PD_STATE_NOT_CONFIGURED:
511 				case MPI2_RAID_PD_STATE_NOT_COMPATIBLE:
512 				default:
513 					targ = mpssas_find_target_by_handle(sassc, 0,
514 							event_data->PhysDiskDevHandle);
515 					if (targ) {
516 						targ->flags |= ~MPS_TARGET_FLAGS_RAID_COMPONENT;
517 						printf("%s %d: Found Target for handle 0x%x.  \n",
518 						__func__, __LINE__ , event_data->PhysDiskDevHandle);
519 					}
520 				break;
521 			}
522 		default:
523 			break;
524 		}
525 		break;
526 	}
527 	case MPI2_EVENT_IR_OPERATION_STATUS:
528 	{
529 		Mpi2EventDataIrOperationStatus_t *event_data =
530 		    fw_event->event_data;
531 
532 		/*
533 		 * Informational only.
534 		 */
535 		mps_dprint(sc, MPS_EVENT, "Received IR Op Status event:\n");
536 		mps_dprint(sc, MPS_EVENT, "   RAID Operation of %d is %d "
537 		    "percent complete for Volume with handle 0x%x",
538 		    event_data->RAIDOperation, event_data->PercentComplete,
539 		    le16toh(event_data->VolDevHandle));
540 		break;
541 	}
542 	case MPI2_EVENT_LOG_ENTRY_ADDED:
543 	{
544 		pMpi2EventDataLogEntryAdded_t	logEntry;
545 		uint16_t			logQualifier;
546 		uint8_t				logCode;
547 
548 		logEntry = (pMpi2EventDataLogEntryAdded_t)fw_event->event_data;
549 		logQualifier = logEntry->LogEntryQualifier;
550 
551 		if (logQualifier == MPI2_WD_LOG_ENTRY) {
552 			logCode = logEntry->LogData[0];
553 
554 			switch (logCode) {
555 			case MPI2_WD_SSD_THROTTLING:
556 				printf("WarpDrive Warning: IO Throttling has "
557 				    "occurred in the WarpDrive subsystem. "
558 				    "Check WarpDrive documentation for "
559 				    "additional details\n");
560 				break;
561 			case MPI2_WD_DRIVE_LIFE_WARN:
562 				printf("WarpDrive Warning: Program/Erase "
563 				    "Cycles for the WarpDrive subsystem in "
564 				    "degraded range. Check WarpDrive "
565 				    "documentation for additional details\n");
566 				break;
567 			case MPI2_WD_DRIVE_LIFE_DEAD:
568 				printf("WarpDrive Fatal Error: There are no "
569 				    "Program/Erase Cycles for the WarpDrive "
570 				    "subsystem. The storage device will be in "
571 				    "read-only mode. Check WarpDrive "
572 				    "documentation for additional details\n");
573 				break;
574 			case MPI2_WD_RAIL_MON_FAIL:
575 				printf("WarpDrive Fatal Error: The Backup Rail "
576 				    "Monitor has failed on the WarpDrive "
577 				    "subsystem. Check WarpDrive documentation "
578 				    "for additional details\n");
579 				break;
580 			default:
581 				break;
582 			}
583 		}
584 		break;
585 	}
586 	case MPI2_EVENT_SAS_DEVICE_STATUS_CHANGE:
587 	case MPI2_EVENT_SAS_BROADCAST_PRIMITIVE:
588 	default:
589 		mps_dprint(sc, MPS_TRACE,"Unhandled event 0x%0X\n",
590 		    fw_event->event);
591 		break;
592 	}
593 	mps_dprint(sc, MPS_EVENT, "(%d)->(%s) Event Free: [%x]\n",event_count,__func__, fw_event->event);
594 	mpssas_fw_event_free(sc, fw_event);
595 }
596 
597 void
598 mpssas_firmware_event_work(void *arg, int pending)
599 {
600 	struct mps_fw_event_work *fw_event;
601 	struct mps_softc *sc;
602 
603 	sc = (struct mps_softc *)arg;
604 	mps_lock(sc);
605 	while ((fw_event = TAILQ_FIRST(&sc->sassc->ev_queue)) != NULL) {
606 		TAILQ_REMOVE(&sc->sassc->ev_queue, fw_event, ev_link);
607 		mpssas_fw_work(sc, fw_event);
608 	}
609 	mps_unlock(sc);
610 }
611 
612 static int
613 mpssas_add_device(struct mps_softc *sc, u16 handle, u8 linkrate){
614 	char devstring[80];
615 	struct mpssas_softc *sassc;
616 	struct mpssas_target *targ;
617 	Mpi2ConfigReply_t mpi_reply;
618 	Mpi2SasDevicePage0_t config_page;
619 	uint64_t sas_address;
620 	uint64_t parent_sas_address = 0;
621 	u32 device_info, parent_devinfo = 0;
622 	unsigned int id;
623 	int ret = 1, error = 0, i;
624 	struct mpssas_lun *lun;
625 	u8 is_SATA_SSD = 0;
626 	struct mps_command *cm;
627 
628 	sassc = sc->sassc;
629 	mpssas_startup_increment(sassc);
630 	if (mps_config_get_sas_device_pg0(sc, &mpi_reply, &config_page,
631 	    MPI2_SAS_DEVICE_PGAD_FORM_HANDLE, handle) != 0) {
632 		mps_dprint(sc, MPS_INFO|MPS_MAPPING|MPS_FAULT,
633 		    "Error reading SAS device %#x page0, iocstatus= 0x%x\n",
634 		    handle, mpi_reply.IOCStatus);
635 		error = ENXIO;
636 		goto out;
637 	}
638 
639 	device_info = le32toh(config_page.DeviceInfo);
640 
641 	if (((device_info & MPI2_SAS_DEVICE_INFO_SMP_TARGET) == 0)
642 	 && (le16toh(config_page.ParentDevHandle) != 0)) {
643 		Mpi2ConfigReply_t tmp_mpi_reply;
644 		Mpi2SasDevicePage0_t parent_config_page;
645 
646 		if (mps_config_get_sas_device_pg0(sc, &tmp_mpi_reply,
647 		    &parent_config_page, MPI2_SAS_DEVICE_PGAD_FORM_HANDLE,
648 		    le16toh(config_page.ParentDevHandle)) != 0) {
649 			mps_dprint(sc, MPS_MAPPING|MPS_FAULT,
650 			    "Error reading parent SAS device %#x page0, "
651 			    "iocstatus= 0x%x\n",
652 			    le16toh(config_page.ParentDevHandle),
653 			    tmp_mpi_reply.IOCStatus);
654 		} else {
655 			parent_sas_address = parent_config_page.SASAddress.High;
656 			parent_sas_address = (parent_sas_address << 32) |
657 				parent_config_page.SASAddress.Low;
658 			parent_devinfo = le32toh(parent_config_page.DeviceInfo);
659 		}
660 	}
661 	/* TODO Check proper endianness */
662 	sas_address = config_page.SASAddress.High;
663 	sas_address = (sas_address << 32) | config_page.SASAddress.Low;
664         mps_dprint(sc, MPS_MAPPING, "Handle 0x%04x SAS Address from SAS device "
665             "page0 = %jx\n", handle, sas_address);
666 
667 	/*
668 	 * Always get SATA Identify information because this is used to
669 	 * determine if Start/Stop Unit should be sent to the drive when the
670 	 * system is shutdown.
671 	 */
672 	if (device_info & MPI2_SAS_DEVICE_INFO_SATA_DEVICE) {
673 		ret = mpssas_get_sas_address_for_sata_disk(sc, &sas_address,
674 		    handle, device_info, &is_SATA_SSD);
675 		if (ret) {
676 			mps_dprint(sc, MPS_MAPPING|MPS_ERROR,
677 			    "%s: failed to get disk type (SSD or HDD) for SATA "
678 			    "device with handle 0x%04x\n",
679 			    __func__, handle);
680 		} else {
681 			mps_dprint(sc, MPS_MAPPING, "Handle 0x%04x SAS Address "
682 			    "from SATA device = %jx\n", handle, sas_address);
683 		}
684 	}
685 
686 	/*
687 	 * use_phynum:
688 	 *  1 - use the PhyNum field as a fallback to the mapping logic
689 	 *  0 - never use the PhyNum field
690 	 * -1 - only use the PhyNum field
691 	 *
692 	 * Note that using the Phy number to map a device can cause device adds
693 	 * to fail if multiple enclosures/expanders are in the topology. For
694 	 * example, if two devices are in the same slot number in two different
695 	 * enclosures within the topology, only one of those devices will be
696 	 * added. PhyNum mapping should not be used if multiple enclosures are
697 	 * in the topology.
698 	 */
699 	id = MPS_MAP_BAD_ID;
700 	if (sc->use_phynum != -1)
701 		id = mps_mapping_get_tid(sc, sas_address, handle);
702 	if (id == MPS_MAP_BAD_ID) {
703 		if ((sc->use_phynum == 0)
704 		 || ((id = config_page.PhyNum) > sassc->maxtargets)) {
705 			mps_dprint(sc, MPS_INFO, "failure at %s:%d/%s()! "
706 			    "Could not get ID for device with handle 0x%04x\n",
707 			    __FILE__, __LINE__, __func__, handle);
708 			error = ENXIO;
709 			goto out;
710 		}
711 	}
712 	mps_dprint(sc, MPS_MAPPING, "%s: Target ID for added device is %d.\n",
713 	    __func__, id);
714 
715 	/*
716 	 * Only do the ID check and reuse check if the target is not from a
717 	 * RAID Component. For Physical Disks of a Volume, the ID will be reused
718 	 * when a volume is deleted because the mapping entry for the PD will
719 	 * still be in the mapping table. The ID check should not be done here
720 	 * either since this PD is already being used.
721 	 */
722 	targ = &sassc->targets[id];
723 	if (!(targ->flags & MPS_TARGET_FLAGS_RAID_COMPONENT)) {
724 		if (mpssas_check_id(sassc, id) != 0) {
725 			mps_dprint(sc, MPS_MAPPING|MPS_INFO,
726 			    "Excluding target id %d\n", id);
727 			error = ENXIO;
728 			goto out;
729 		}
730 
731 		if (targ->handle != 0x0) {
732 			mps_dprint(sc, MPS_MAPPING, "Attempting to reuse "
733 			    "target id %d handle 0x%04x\n", id, targ->handle);
734 			error = ENXIO;
735 			goto out;
736 		}
737 	}
738 
739 	targ->devinfo = device_info;
740 	targ->devname = le32toh(config_page.DeviceName.High);
741 	targ->devname = (targ->devname << 32) |
742 	    le32toh(config_page.DeviceName.Low);
743 	targ->encl_handle = le16toh(config_page.EnclosureHandle);
744 	targ->encl_slot = le16toh(config_page.Slot);
745 	targ->handle = handle;
746 	targ->parent_handle = le16toh(config_page.ParentDevHandle);
747 	targ->sasaddr = mps_to_u64(&config_page.SASAddress);
748 	targ->parent_sasaddr = le64toh(parent_sas_address);
749 	targ->parent_devinfo = parent_devinfo;
750 	targ->tid = id;
751 	targ->linkrate = (linkrate>>4);
752 	targ->flags = 0;
753 	if (is_SATA_SSD) {
754 		targ->flags = MPS_TARGET_IS_SATA_SSD;
755 	}
756 	TAILQ_INIT(&targ->commands);
757 	TAILQ_INIT(&targ->timedout_commands);
758 	while(!SLIST_EMPTY(&targ->luns)) {
759 		lun = SLIST_FIRST(&targ->luns);
760 		SLIST_REMOVE_HEAD(&targ->luns, lun_link);
761 		free(lun, M_MPT2);
762 	}
763 	SLIST_INIT(&targ->luns);
764 
765 	mps_describe_devinfo(targ->devinfo, devstring, 80);
766 	mps_dprint(sc, MPS_MAPPING, "Found device <%s> <%s> <0x%04x> <%d/%d>\n",
767 	    devstring, mps_describe_table(mps_linkrate_names, targ->linkrate),
768 	    targ->handle, targ->encl_handle, targ->encl_slot);
769 
770 	mpssas_rescan_target(sc, targ);
771 	mps_dprint(sc, MPS_MAPPING, "Target id 0x%x added\n", targ->tid);
772 
773 	/*
774 	 * Check all commands to see if the SATA_ID_TIMEOUT flag has been set.
775 	 * If so, send a Target Reset TM to the target that was just created.
776 	 * An Abort Task TM should be used instead of a Target Reset, but that
777 	 * would be much more difficult because targets have not been fully
778 	 * discovered yet, and LUN's haven't been setup.  So, just reset the
779 	 * target instead of the LUN.  The commands should complete once the
780 	 * target has been reset.
781 	 */
782 	for (i = 1; i < sc->num_reqs; i++) {
783 		cm = &sc->commands[i];
784 		if (cm->cm_flags & MPS_CM_FLAGS_SATA_ID_TIMEOUT) {
785 			targ->timeouts++;
786 			cm->cm_flags |= MPS_CM_FLAGS_TIMEDOUT;
787 
788 			if ((targ->tm = mpssas_alloc_tm(sc)) != NULL) {
789 				mps_dprint(sc, MPS_INFO, "%s: sending Target "
790 				    "Reset for stuck SATA identify command "
791 				    "(cm = %p)\n", __func__, cm);
792 				targ->tm->cm_targ = targ;
793 				mpssas_send_reset(sc, targ->tm,
794 				    MPI2_SCSITASKMGMT_TASKTYPE_TARGET_RESET);
795 			} else {
796 				mps_dprint(sc, MPS_ERROR, "Failed to allocate "
797 				    "tm for Target Reset after SATA ID command "
798 				    "timed out (cm %p)\n", cm);
799 			}
800 			/*
801 			 * No need to check for more since the target is
802 			 * already being reset.
803 			 */
804 			break;
805 		}
806 	}
807 out:
808 	mpssas_startup_decrement(sassc);
809 	return (error);
810 }
811 
812 int
813 mpssas_get_sas_address_for_sata_disk(struct mps_softc *sc,
814     u64 *sas_address, u16 handle, u32 device_info, u8 *is_SATA_SSD)
815 {
816 	Mpi2SataPassthroughReply_t mpi_reply;
817 	int i, rc, try_count;
818 	u32 *bufferptr;
819 	union _sata_sas_address hash_address;
820 	struct _ata_identify_device_data ata_identify;
821 	u8 buffer[MPT2SAS_MN_LEN + MPT2SAS_SN_LEN];
822 	u32 ioc_status;
823 	u8 sas_status;
824 
825 	memset(&ata_identify, 0, sizeof(ata_identify));
826 	try_count = 0;
827 	do {
828 		rc = mpssas_get_sata_identify(sc, handle, &mpi_reply,
829 		    (char *)&ata_identify, sizeof(ata_identify), device_info);
830 		try_count++;
831 		ioc_status = le16toh(mpi_reply.IOCStatus)
832 		    & MPI2_IOCSTATUS_MASK;
833 		sas_status = mpi_reply.SASStatus;
834 		switch (ioc_status) {
835 		case MPI2_IOCSTATUS_SUCCESS:
836 			break;
837 		case MPI2_IOCSTATUS_SCSI_PROTOCOL_ERROR:
838 			/* No sense sleeping.  this error won't get better */
839 			break;
840 		default:
841 			if (sc->spinup_wait_time > 0) {
842 				mps_dprint(sc, MPS_INFO, "Sleeping %d seconds "
843 				    "after SATA ID error to wait for spinup\n",
844 				    sc->spinup_wait_time);
845 				msleep(&sc->msleep_fake_chan, &sc->mps_mtx, 0,
846 				    "mpsid", sc->spinup_wait_time * hz);
847 			}
848 		}
849 	} while (((rc && (rc != EWOULDBLOCK)) ||
850 	    	 (ioc_status &&
851 		  (ioc_status != MPI2_IOCSTATUS_SCSI_PROTOCOL_ERROR))
852 	       || sas_status) && (try_count < 5));
853 
854 	if (rc == 0 && !ioc_status && !sas_status) {
855 		mps_dprint(sc, MPS_MAPPING, "%s: got SATA identify "
856 		    "successfully for handle = 0x%x with try_count = %d\n",
857 		    __func__, handle, try_count);
858 	} else {
859 		mps_dprint(sc, MPS_MAPPING, "%s: handle = 0x%x failed\n",
860 		    __func__, handle);
861 		return -1;
862 	}
863 	/* Copy & byteswap the 40 byte model number to a buffer */
864 	for (i = 0; i < MPT2SAS_MN_LEN; i += 2) {
865 		buffer[i] = ((u8 *)ata_identify.model_number)[i + 1];
866 		buffer[i + 1] = ((u8 *)ata_identify.model_number)[i];
867 	}
868 	/* Copy & byteswap the 20 byte serial number to a buffer */
869 	for (i = 0; i < MPT2SAS_SN_LEN; i += 2) {
870 		buffer[MPT2SAS_MN_LEN + i] =
871 		    ((u8 *)ata_identify.serial_number)[i + 1];
872 		buffer[MPT2SAS_MN_LEN + i + 1] =
873 		    ((u8 *)ata_identify.serial_number)[i];
874 	}
875 	bufferptr = (u32 *)buffer;
876 	/* There are 60 bytes to hash down to 8. 60 isn't divisible by 8,
877 	 * so loop through the first 56 bytes (7*8),
878 	 * and then add in the last dword.
879 	 */
880 	hash_address.word.low  = 0;
881 	hash_address.word.high = 0;
882 	for (i = 0; (i < ((MPT2SAS_MN_LEN+MPT2SAS_SN_LEN)/8)); i++) {
883 		hash_address.word.low += *bufferptr;
884 		bufferptr++;
885 		hash_address.word.high += *bufferptr;
886 		bufferptr++;
887 	}
888 	/* Add the last dword */
889 	hash_address.word.low += *bufferptr;
890 	/* Make sure the hash doesn't start with 5, because it could clash
891 	 * with a SAS address. Change 5 to a D.
892 	 */
893 	if ((hash_address.word.high & 0x000000F0) == (0x00000050))
894 		hash_address.word.high |= 0x00000080;
895 	*sas_address = (u64)hash_address.wwid[0] << 56 |
896 	    (u64)hash_address.wwid[1] << 48 | (u64)hash_address.wwid[2] << 40 |
897 	    (u64)hash_address.wwid[3] << 32 | (u64)hash_address.wwid[4] << 24 |
898 	    (u64)hash_address.wwid[5] << 16 | (u64)hash_address.wwid[6] <<  8 |
899 	    (u64)hash_address.wwid[7];
900 	if (ata_identify.rotational_speed == 1) {
901 		*is_SATA_SSD = 1;
902 	}
903 
904 	return 0;
905 }
906 
907 static int
908 mpssas_get_sata_identify(struct mps_softc *sc, u16 handle,
909     Mpi2SataPassthroughReply_t *mpi_reply, char *id_buffer, int sz, u32 devinfo)
910 {
911 	Mpi2SataPassthroughRequest_t *mpi_request;
912 	Mpi2SataPassthroughReply_t *reply = NULL;
913 	struct mps_command *cm;
914 	char *buffer;
915 	int error = 0;
916 
917 	buffer = malloc( sz, M_MPT2, M_NOWAIT | M_ZERO);
918 	if (!buffer)
919 		return ENOMEM;
920 
921 	if ((cm = mps_alloc_command(sc)) == NULL) {
922 		free(buffer, M_MPT2);
923 		return (EBUSY);
924 	}
925 	mpi_request = (MPI2_SATA_PASSTHROUGH_REQUEST *)cm->cm_req;
926 	bzero(mpi_request,sizeof(MPI2_SATA_PASSTHROUGH_REQUEST));
927 	mpi_request->Function = MPI2_FUNCTION_SATA_PASSTHROUGH;
928 	mpi_request->VF_ID = 0;
929 	mpi_request->DevHandle = htole16(handle);
930 	mpi_request->PassthroughFlags = (MPI2_SATA_PT_REQ_PT_FLAGS_PIO |
931 	    MPI2_SATA_PT_REQ_PT_FLAGS_READ);
932 	mpi_request->DataLength = htole32(sz);
933 	mpi_request->CommandFIS[0] = 0x27;
934 	mpi_request->CommandFIS[1] = 0x80;
935 	mpi_request->CommandFIS[2] =  (devinfo &
936 	    MPI2_SAS_DEVICE_INFO_ATAPI_DEVICE) ? 0xA1 : 0xEC;
937 	cm->cm_sge = &mpi_request->SGL;
938 	cm->cm_sglsize = sizeof(MPI2_SGE_IO_UNION);
939 	cm->cm_flags = MPS_CM_FLAGS_SGE_SIMPLE | MPS_CM_FLAGS_DATAIN;
940 	cm->cm_desc.Default.RequestFlags = MPI2_REQ_DESCRIPT_FLAGS_DEFAULT_TYPE;
941 	cm->cm_data = buffer;
942 	cm->cm_length = htole32(sz);
943 
944 	/*
945 	 * Use a custom handler to avoid reinit'ing the controller on timeout.
946 	 * This fixes a problem where the FW does not send a reply sometimes
947 	 * when a bad disk is in the topology. So, this is used to timeout the
948 	 * command so that processing can continue normally.
949 	 */
950 	cm->cm_timeout_handler = mpssas_ata_id_timeout;
951 
952 	error = mps_wait_command(sc, &cm, MPS_ATA_ID_TIMEOUT, CAN_SLEEP);
953 
954 	/* mpssas_ata_id_timeout does not reset controller */
955 	KASSERT(cm != NULL, ("%s: surprise command freed", __func__));
956 
957 	reply = (Mpi2SataPassthroughReply_t *)cm->cm_reply;
958 	if (error || (reply == NULL)) {
959 		/* FIXME */
960  		/*
961  		 * If the request returns an error then we need to do a diag
962  		 * reset
963  		 */
964  		mps_dprint(sc, MPS_INFO|MPS_FAULT|MPS_MAPPING,
965 		    "Request for SATA PASSTHROUGH page completed with error %d\n",
966 		    error);
967 		error = ENXIO;
968 		goto out;
969 	}
970 	bcopy(buffer, id_buffer, sz);
971 	bcopy(reply, mpi_reply, sizeof(Mpi2SataPassthroughReply_t));
972 	if ((le16toh(reply->IOCStatus) & MPI2_IOCSTATUS_MASK) !=
973 	    MPI2_IOCSTATUS_SUCCESS) {
974 		mps_dprint(sc, MPS_INFO|MPS_MAPPING|MPS_FAULT,
975 		    "Error reading device %#x SATA PASSTHRU; iocstatus= 0x%x\n",
976 		    handle, reply->IOCStatus);
977 		error = ENXIO;
978 		goto out;
979 	}
980 out:
981 	/*
982 	 * If the SATA_ID_TIMEOUT flag has been set for this command, don't free
983 	 * it.  The command and buffer will be freed after we send a Target
984 	 * Reset TM and the command comes back from the controller.
985 	 */
986 	if ((cm->cm_flags & MPS_CM_FLAGS_SATA_ID_TIMEOUT) == 0) {
987 		mps_free_command(sc, cm);
988 		free(buffer, M_MPT2);
989 	}
990 	return (error);
991 }
992 
993 /*
994  * This is completion handler to make sure that commands and allocated
995  * buffers get freed when timed out SATA ID commands finally complete after
996  * we've reset the target.  In the normal case, we wait for the command to
997  * complete.
998  */
999 static void
1000 mpssas_ata_id_complete(struct mps_softc *sc, struct mps_command *cm)
1001 {
1002 	mps_dprint(sc, MPS_INFO, "%s ATA ID completed late cm %p sc %p\n",
1003 	    __func__, cm, sc);
1004 
1005 	free(cm->cm_data, M_MPT2);
1006 	mps_free_command(sc, cm);
1007 }
1008 
1009 
1010 static void
1011 mpssas_ata_id_timeout(struct mps_softc *sc, struct mps_command *cm)
1012 {
1013 	mps_dprint(sc, MPS_INFO, "%s ATA ID command timeout cm %p sc %p\n",
1014 	    __func__, cm, sc);
1015 
1016 	/*
1017 	 * The Abort Task cannot be sent from here because the driver has not
1018 	 * completed setting up targets.  Instead, the command is flagged so
1019 	 * that special handling will be used to send a target reset.
1020 	 */
1021 	cm->cm_flags |= MPS_CM_FLAGS_SATA_ID_TIMEOUT;
1022 
1023 	/*
1024 	 * Since we will no longer be waiting for the command to complete,
1025 	 * set a completion handler to make sure we free all resources.
1026 	 */
1027 	cm->cm_complete = mpssas_ata_id_complete;
1028 }
1029 
1030 static int
1031 mpssas_volume_add(struct mps_softc *sc, u16 handle)
1032 {
1033 	struct mpssas_softc *sassc;
1034 	struct mpssas_target *targ;
1035 	u64 wwid;
1036 	unsigned int id;
1037 	int error = 0;
1038 	struct mpssas_lun *lun;
1039 
1040 	sassc = sc->sassc;
1041 	mpssas_startup_increment(sassc);
1042 	/* wwid is endian safe */
1043 	mps_config_get_volume_wwid(sc, handle, &wwid);
1044 	if (!wwid) {
1045 		printf("%s: invalid WWID; cannot add volume to mapping table\n",
1046 		    __func__);
1047 		error = ENXIO;
1048 		goto out;
1049 	}
1050 
1051 	id = mps_mapping_get_raid_tid(sc, wwid, handle);
1052 	if (id == MPS_MAP_BAD_ID) {
1053 		printf("%s: could not get ID for volume with handle 0x%04x and "
1054 		    "WWID 0x%016llx\n", __func__, handle,
1055 		    (unsigned long long)wwid);
1056 		error = ENXIO;
1057 		goto out;
1058 	}
1059 
1060 	targ = &sassc->targets[id];
1061 	targ->tid = id;
1062 	targ->handle = handle;
1063 	targ->devname = wwid;
1064 	TAILQ_INIT(&targ->commands);
1065 	TAILQ_INIT(&targ->timedout_commands);
1066 	while(!SLIST_EMPTY(&targ->luns)) {
1067 		lun = SLIST_FIRST(&targ->luns);
1068 		SLIST_REMOVE_HEAD(&targ->luns, lun_link);
1069 		free(lun, M_MPT2);
1070 	}
1071 	SLIST_INIT(&targ->luns);
1072 	mpssas_rescan_target(sc, targ);
1073 	mps_dprint(sc, MPS_MAPPING, "RAID target id %d added (WWID = 0x%jx)\n",
1074 	    targ->tid, wwid);
1075 out:
1076 	mpssas_startup_decrement(sassc);
1077 	return (error);
1078 }
1079 
1080 /**
1081  * mpssas_SSU_to_SATA_devices
1082  * @sc: per adapter object
1083  * @howto: mast of RB_* bits for how we're rebooting
1084  *
1085  * Looks through the target list and issues a StartStopUnit SCSI command to each
1086  * SATA direct-access device.  This helps to ensure that data corruption is
1087  * avoided when the system is being shut down.  This must be called after the IR
1088  * System Shutdown RAID Action is sent if in IR mode.
1089  *
1090  * Return nothing.
1091  */
1092 static void
1093 mpssas_SSU_to_SATA_devices(struct mps_softc *sc, int howto)
1094 {
1095 	struct mpssas_softc *sassc = sc->sassc;
1096 	union ccb *ccb;
1097 	path_id_t pathid = cam_sim_path(sassc->sim);
1098 	target_id_t targetid;
1099 	struct mpssas_target *target;
1100 	char path_str[64];
1101 	int timeout;
1102 
1103 	/*
1104 	 * For each target, issue a StartStopUnit command to stop the device.
1105 	 */
1106 	sc->SSU_started = TRUE;
1107 	sc->SSU_refcount = 0;
1108 	for (targetid = 0; targetid < sc->max_devices; targetid++) {
1109 		target = &sassc->targets[targetid];
1110 		if (target->handle == 0x0) {
1111 			continue;
1112 		}
1113 
1114 		ccb = xpt_alloc_ccb_nowait();
1115 		if (ccb == NULL) {
1116 			mps_dprint(sc, MPS_FAULT, "Unable to alloc CCB to stop "
1117 			    "unit.\n");
1118 			return;
1119 		}
1120 
1121 		/*
1122 		 * The stop_at_shutdown flag will be set if this device is
1123 		 * a SATA direct-access end device.
1124 		 */
1125 		if (target->stop_at_shutdown) {
1126 			if (xpt_create_path(&ccb->ccb_h.path,
1127 			    xpt_periph, pathid, targetid,
1128 			    CAM_LUN_WILDCARD) != CAM_REQ_CMP) {
1129 				mps_dprint(sc, MPS_FAULT, "Unable to create "
1130 				    "LUN path to stop unit.\n");
1131 				xpt_free_ccb(ccb);
1132 				return;
1133 			}
1134 			xpt_path_string(ccb->ccb_h.path, path_str,
1135 			    sizeof(path_str));
1136 
1137 			mps_dprint(sc, MPS_INFO, "Sending StopUnit: path %s "
1138 			    "handle %d\n", path_str, target->handle);
1139 
1140 			/*
1141 			 * Issue a START STOP UNIT command for the target.
1142 			 * Increment the SSU counter to be used to count the
1143 			 * number of required replies.
1144 			 */
1145 			mps_dprint(sc, MPS_INFO, "Incrementing SSU count\n");
1146 			sc->SSU_refcount++;
1147 			ccb->ccb_h.target_id =
1148 			    xpt_path_target_id(ccb->ccb_h.path);
1149 			ccb->ccb_h.ppriv_ptr1 = sassc;
1150 			scsi_start_stop(&ccb->csio,
1151 			    /*retries*/0,
1152 			    mpssas_stop_unit_done,
1153 			    MSG_SIMPLE_Q_TAG,
1154 			    /*start*/FALSE,
1155 			    /*load/eject*/0,
1156 			    /*immediate*/FALSE,
1157 			    MPS_SENSE_LEN,
1158 			    /*timeout*/10000);
1159 			xpt_action(ccb);
1160 		}
1161 	}
1162 
1163 	/*
1164 	 * Timeout after 60 seconds by default or 10 seconds if howto has
1165 	 * RB_NOSYNC set which indicates we're likely handling a panic.
1166 	 */
1167 	timeout = 600;
1168 	if (howto & RB_NOSYNC)
1169 		timeout = 100;
1170 
1171 	/*
1172 	 * Wait until all of the SSU commands have completed or timeout has
1173 	 * expired.  Pause for 100ms each time through.  If any command
1174 	 * times out, the target will be reset in the SCSI command timeout
1175 	 * routine.
1176 	 */
1177 	while (sc->SSU_refcount > 0) {
1178 		pause("mpswait", hz/10);
1179 		if (SCHEDULER_STOPPED())
1180 			xpt_sim_poll(sassc->sim);
1181 
1182 		if (--timeout == 0) {
1183 			mps_dprint(sc, MPS_FAULT, "Time has expired waiting "
1184 			    "for SSU commands to complete.\n");
1185 			break;
1186 		}
1187 	}
1188 }
1189 
1190 static void
1191 mpssas_stop_unit_done(struct cam_periph *periph, union ccb *done_ccb)
1192 {
1193 	struct mpssas_softc *sassc;
1194 	char path_str[64];
1195 
1196 	if (done_ccb == NULL)
1197 		return;
1198 
1199 	sassc = (struct mpssas_softc *)done_ccb->ccb_h.ppriv_ptr1;
1200 
1201 	xpt_path_string(done_ccb->ccb_h.path, path_str, sizeof(path_str));
1202 	mps_dprint(sassc->sc, MPS_INFO, "Completing stop unit for %s\n",
1203 	    path_str);
1204 
1205 	/*
1206 	 * Nothing more to do except free the CCB and path.  If the command
1207 	 * timed out, an abort reset, then target reset will be issued during
1208 	 * the SCSI Command process.
1209 	 */
1210 	xpt_free_path(done_ccb->ccb_h.path);
1211 	xpt_free_ccb(done_ccb);
1212 }
1213 
1214 /**
1215  * mpssas_ir_shutdown - IR shutdown notification
1216  * @sc: per adapter object
1217  * @howto: mast of RB_* bits for how we're rebooting
1218  *
1219  * Sending RAID Action to alert the Integrated RAID subsystem of the IOC that
1220  * the host system is shutting down.
1221  *
1222  * Return nothing.
1223  */
1224 void
1225 mpssas_ir_shutdown(struct mps_softc *sc, int howto)
1226 {
1227 	u16 volume_mapping_flags;
1228 	u16 ioc_pg8_flags = le16toh(sc->ioc_pg8.Flags);
1229 	struct dev_mapping_table *mt_entry;
1230 	u32 start_idx, end_idx;
1231 	unsigned int id, found_volume = 0;
1232 	struct mps_command *cm;
1233 	Mpi2RaidActionRequest_t	*action;
1234 	target_id_t targetid;
1235 	struct mpssas_target *target;
1236 
1237 	mps_dprint(sc, MPS_TRACE, "%s\n", __func__);
1238 
1239 	/* is IR firmware build loaded? */
1240 	if (!sc->ir_firmware)
1241 		goto out;
1242 
1243 	/* are there any volumes?  Look at IR target IDs. */
1244 	// TODO-later, this should be looked up in the RAID config structure
1245 	// when it is implemented.
1246 	volume_mapping_flags = le16toh(sc->ioc_pg8.IRVolumeMappingFlags) &
1247 	    MPI2_IOCPAGE8_IRFLAGS_MASK_VOLUME_MAPPING_MODE;
1248 	if (volume_mapping_flags == MPI2_IOCPAGE8_IRFLAGS_LOW_VOLUME_MAPPING) {
1249 		start_idx = 0;
1250 		if (ioc_pg8_flags & MPI2_IOCPAGE8_FLAGS_RESERVED_TARGETID_0)
1251 			start_idx = 1;
1252 	} else
1253 		start_idx = sc->max_devices - sc->max_volumes;
1254 	end_idx = start_idx + sc->max_volumes - 1;
1255 
1256 	for (id = start_idx; id < end_idx; id++) {
1257 		mt_entry = &sc->mapping_table[id];
1258 		if ((mt_entry->physical_id != 0) &&
1259 		    (mt_entry->missing_count == 0)) {
1260 			found_volume = 1;
1261 			break;
1262 		}
1263 	}
1264 
1265 	if (!found_volume)
1266 		goto out;
1267 
1268 	if ((cm = mps_alloc_command(sc)) == NULL) {
1269 		printf("%s: command alloc failed\n", __func__);
1270 		goto out;
1271 	}
1272 
1273 	action = (MPI2_RAID_ACTION_REQUEST *)cm->cm_req;
1274 	action->Function = MPI2_FUNCTION_RAID_ACTION;
1275 	action->Action = MPI2_RAID_ACTION_SYSTEM_SHUTDOWN_INITIATED;
1276 	cm->cm_desc.Default.RequestFlags = MPI2_REQ_DESCRIPT_FLAGS_DEFAULT_TYPE;
1277 	mps_lock(sc);
1278 	mps_wait_command(sc, &cm, 5, CAN_SLEEP);
1279 	mps_unlock(sc);
1280 
1281 	/*
1282 	 * Don't check for reply, just leave.
1283 	 */
1284 	if (cm)
1285 		mps_free_command(sc, cm);
1286 
1287 out:
1288 	/*
1289 	 * All of the targets must have the correct value set for
1290 	 * 'stop_at_shutdown' for the current 'enable_ssu' sysctl variable.
1291 	 *
1292 	 * The possible values for the 'enable_ssu' variable are:
1293 	 * 0: disable to SSD and HDD
1294 	 * 1: disable only to HDD (default)
1295 	 * 2: disable only to SSD
1296 	 * 3: enable to SSD and HDD
1297 	 * anything else will default to 1.
1298 	 */
1299 	for (targetid = 0; targetid < sc->max_devices; targetid++) {
1300 		target = &sc->sassc->targets[targetid];
1301 		if (target->handle == 0x0) {
1302 			continue;
1303 		}
1304 
1305 		if (target->supports_SSU) {
1306 			switch (sc->enable_ssu) {
1307 			case MPS_SSU_DISABLE_SSD_DISABLE_HDD:
1308 				target->stop_at_shutdown = FALSE;
1309 				break;
1310 			case MPS_SSU_DISABLE_SSD_ENABLE_HDD:
1311 				target->stop_at_shutdown = TRUE;
1312 				if (target->flags & MPS_TARGET_IS_SATA_SSD) {
1313 					target->stop_at_shutdown = FALSE;
1314 				}
1315 				break;
1316 			case MPS_SSU_ENABLE_SSD_ENABLE_HDD:
1317 				target->stop_at_shutdown = TRUE;
1318 				break;
1319 			case MPS_SSU_ENABLE_SSD_DISABLE_HDD:
1320 			default:
1321 				target->stop_at_shutdown = TRUE;
1322 				if ((target->flags &
1323 				    MPS_TARGET_IS_SATA_SSD) == 0) {
1324 					target->stop_at_shutdown = FALSE;
1325 				}
1326 				break;
1327 			}
1328 		}
1329 	}
1330 	mpssas_SSU_to_SATA_devices(sc, howto);
1331 }
1332