xref: /freebsd/sys/dev/mps/mps_sas_lsi.c (revision d93a896ef95946b0bf1219866fcb324b78543444)
1 /*-
2  * Copyright (c) 2011-2015 LSI Corp.
3  * Copyright (c) 2013-2015 Avago Technologies
4  * All rights reserved.
5  *
6  * Redistribution and use in source and binary forms, with or without
7  * modification, are permitted provided that the following conditions
8  * are met:
9  * 1. Redistributions of source code must retain the above copyright
10  *    notice, this list of conditions and the following disclaimer.
11  * 2. Redistributions in binary form must reproduce the above copyright
12  *    notice, this list of conditions and the following disclaimer in the
13  *    documentation and/or other materials provided with the distribution.
14  *
15  * THIS SOFTWARE IS PROVIDED BY THE AUTHOR AND CONTRIBUTORS ``AS IS'' AND
16  * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
17  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
18  * ARE DISCLAIMED.  IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE
19  * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
20  * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
21  * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
22  * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
23  * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
24  * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
25  * SUCH DAMAGE.
26  *
27  * Avago Technologies (LSI) MPT-Fusion Host Adapter FreeBSD
28  */
29 
30 #include <sys/cdefs.h>
31 __FBSDID("$FreeBSD$");
32 
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/queue.h>
50 #include <sys/kthread.h>
51 #include <sys/taskqueue.h>
52 #include <sys/sbuf.h>
53 
54 #include <machine/bus.h>
55 #include <machine/resource.h>
56 #include <sys/rman.h>
57 
58 #include <machine/stdarg.h>
59 
60 #include <cam/cam.h>
61 #include <cam/cam_ccb.h>
62 #include <cam/cam_debug.h>
63 #include <cam/cam_sim.h>
64 #include <cam/cam_xpt_sim.h>
65 #include <cam/cam_xpt_periph.h>
66 #include <cam/cam_periph.h>
67 #include <cam/scsi/scsi_all.h>
68 #include <cam/scsi/scsi_message.h>
69 
70 #include <dev/mps/mpi/mpi2_type.h>
71 #include <dev/mps/mpi/mpi2.h>
72 #include <dev/mps/mpi/mpi2_ioc.h>
73 #include <dev/mps/mpi/mpi2_sas.h>
74 #include <dev/mps/mpi/mpi2_cnfg.h>
75 #include <dev/mps/mpi/mpi2_init.h>
76 #include <dev/mps/mpi/mpi2_raid.h>
77 #include <dev/mps/mpi/mpi2_tool.h>
78 #include <dev/mps/mps_ioctl.h>
79 #include <dev/mps/mpsvar.h>
80 #include <dev/mps/mps_table.h>
81 #include <dev/mps/mps_sas.h>
82 
83 /* For Hashed SAS Address creation for SATA Drives */
84 #define MPT2SAS_SN_LEN 20
85 #define MPT2SAS_MN_LEN 40
86 
87 struct mps_fw_event_work {
88 	u16			event;
89 	void			*event_data;
90 	TAILQ_ENTRY(mps_fw_event_work)	ev_link;
91 };
92 
93 union _sata_sas_address {
94 	u8 wwid[8];
95 	struct {
96 		u32 high;
97 		u32 low;
98 	} word;
99 };
100 
101 /*
102  * define the IDENTIFY DEVICE structure
103  */
104 struct _ata_identify_device_data {
105 	u16 reserved1[10];	/* 0-9 */
106 	u16 serial_number[10];	/* 10-19 */
107 	u16 reserved2[7];	/* 20-26 */
108 	u16 model_number[20];	/* 27-46*/
109 	u16 reserved3[170];	/* 47-216 */
110 	u16 rotational_speed;	/* 217 */
111 	u16 reserved4[38];	/* 218-255 */
112 };
113 static u32 event_count;
114 static void mpssas_fw_work(struct mps_softc *sc,
115     struct mps_fw_event_work *fw_event);
116 static void mpssas_fw_event_free(struct mps_softc *,
117     struct mps_fw_event_work *);
118 static int mpssas_add_device(struct mps_softc *sc, u16 handle, u8 linkrate);
119 static int mpssas_get_sata_identify(struct mps_softc *sc, u16 handle,
120     Mpi2SataPassthroughReply_t *mpi_reply, char *id_buffer, int sz,
121     u32 devinfo);
122 static void mpssas_ata_id_timeout(void *data);
123 int mpssas_get_sas_address_for_sata_disk(struct mps_softc *sc,
124     u64 *sas_address, u16 handle, u32 device_info, u8 *is_SATA_SSD);
125 static int mpssas_volume_add(struct mps_softc *sc,
126     u16 handle);
127 static void mpssas_SSU_to_SATA_devices(struct mps_softc *sc);
128 static void mpssas_stop_unit_done(struct cam_periph *periph,
129     union ccb *done_ccb);
130 
131 void
132 mpssas_evt_handler(struct mps_softc *sc, uintptr_t data,
133     MPI2_EVENT_NOTIFICATION_REPLY *event)
134 {
135 	struct mps_fw_event_work *fw_event;
136 	u16 sz;
137 
138 	mps_dprint(sc, MPS_TRACE, "%s\n", __func__);
139 	MPS_DPRINT_EVENT(sc, sas, event);
140 	mpssas_record_event(sc, event);
141 
142 	fw_event = malloc(sizeof(struct mps_fw_event_work), M_MPT2,
143 	     M_ZERO|M_NOWAIT);
144 	if (!fw_event) {
145 		printf("%s: allocate failed for fw_event\n", __func__);
146 		return;
147 	}
148 	sz = le16toh(event->EventDataLength) * 4;
149 	fw_event->event_data = malloc(sz, M_MPT2, M_ZERO|M_NOWAIT);
150 	if (!fw_event->event_data) {
151 		printf("%s: allocate failed for event_data\n", __func__);
152 		free(fw_event, M_MPT2);
153 		return;
154 	}
155 
156 	bcopy(event->EventData, fw_event->event_data, sz);
157 	fw_event->event = event->Event;
158 	if ((event->Event == MPI2_EVENT_SAS_TOPOLOGY_CHANGE_LIST ||
159 	    event->Event == MPI2_EVENT_SAS_ENCL_DEVICE_STATUS_CHANGE ||
160 	    event->Event == MPI2_EVENT_IR_CONFIGURATION_CHANGE_LIST) &&
161 	    sc->track_mapping_events)
162 		sc->pending_map_events++;
163 
164 	/*
165 	 * When wait_for_port_enable flag is set, make sure that all the events
166 	 * are processed. Increment the startup_refcount and decrement it after
167 	 * events are processed.
168 	 */
169 	if ((event->Event == MPI2_EVENT_SAS_TOPOLOGY_CHANGE_LIST ||
170 	    event->Event == MPI2_EVENT_IR_CONFIGURATION_CHANGE_LIST) &&
171 	    sc->wait_for_port_enable)
172 		mpssas_startup_increment(sc->sassc);
173 
174 	TAILQ_INSERT_TAIL(&sc->sassc->ev_queue, fw_event, ev_link);
175 	taskqueue_enqueue(sc->sassc->ev_tq, &sc->sassc->ev_task);
176 
177 }
178 
179 static void
180 mpssas_fw_event_free(struct mps_softc *sc, struct mps_fw_event_work *fw_event)
181 {
182 
183 	free(fw_event->event_data, M_MPT2);
184 	free(fw_event, M_MPT2);
185 }
186 
187 /**
188  * _mps_fw_work - delayed task for processing firmware events
189  * @sc: per adapter object
190  * @fw_event: The fw_event_work object
191  * Context: user.
192  *
193  * Return nothing.
194  */
195 static void
196 mpssas_fw_work(struct mps_softc *sc, struct mps_fw_event_work *fw_event)
197 {
198 	struct mpssas_softc *sassc;
199 	sassc = sc->sassc;
200 
201 	mps_dprint(sc, MPS_EVENT, "(%d)->(%s) Working on  Event: [%x]\n",
202 			event_count++,__func__,fw_event->event);
203 	switch (fw_event->event) {
204 	case MPI2_EVENT_SAS_TOPOLOGY_CHANGE_LIST:
205 	{
206 		MPI2_EVENT_DATA_SAS_TOPOLOGY_CHANGE_LIST *data;
207 		MPI2_EVENT_SAS_TOPO_PHY_ENTRY *phy;
208 		int i;
209 
210 		data = (MPI2_EVENT_DATA_SAS_TOPOLOGY_CHANGE_LIST *)
211 		    fw_event->event_data;
212 
213 		mps_mapping_topology_change_event(sc, fw_event->event_data);
214 
215 		for (i = 0; i < data->NumEntries; i++) {
216 			phy = &data->PHY[i];
217 			switch (phy->PhyStatus & MPI2_EVENT_SAS_TOPO_RC_MASK) {
218 			case MPI2_EVENT_SAS_TOPO_RC_TARG_ADDED:
219 				if (mpssas_add_device(sc,
220 				    le16toh(phy->AttachedDevHandle),
221 				    phy->LinkRate)){
222 					mps_dprint(sc, MPS_ERROR, "%s: "
223 					    "failed to add device with handle "
224 					    "0x%x\n", __func__,
225 					    le16toh(phy->AttachedDevHandle));
226 					mpssas_prepare_remove(sassc, le16toh(
227 						phy->AttachedDevHandle));
228 				}
229 				break;
230 			case MPI2_EVENT_SAS_TOPO_RC_TARG_NOT_RESPONDING:
231 				mpssas_prepare_remove(sassc,le16toh(
232 					phy->AttachedDevHandle));
233 				break;
234 			case MPI2_EVENT_SAS_TOPO_RC_PHY_CHANGED:
235 			case MPI2_EVENT_SAS_TOPO_RC_NO_CHANGE:
236 			case MPI2_EVENT_SAS_TOPO_RC_DELAY_NOT_RESPONDING:
237 			default:
238 				break;
239 			}
240 		}
241 		/*
242 		 * refcount was incremented for this event in
243 		 * mpssas_evt_handler.  Decrement it here because the event has
244 		 * been processed.
245 		 */
246 		mpssas_startup_decrement(sassc);
247 		break;
248 	}
249 	case MPI2_EVENT_SAS_DISCOVERY:
250 	{
251 		MPI2_EVENT_DATA_SAS_DISCOVERY *data;
252 
253 		data = (MPI2_EVENT_DATA_SAS_DISCOVERY *)fw_event->event_data;
254 
255 		if (data->ReasonCode & MPI2_EVENT_SAS_DISC_RC_STARTED)
256 			mps_dprint(sc, MPS_TRACE,"SAS discovery start event\n");
257 		if (data->ReasonCode & MPI2_EVENT_SAS_DISC_RC_COMPLETED) {
258 			mps_dprint(sc, MPS_TRACE,"SAS discovery stop event\n");
259 			sassc->flags &= ~MPSSAS_IN_DISCOVERY;
260 			mpssas_discovery_end(sassc);
261 		}
262 		break;
263 	}
264 	case MPI2_EVENT_SAS_ENCL_DEVICE_STATUS_CHANGE:
265 	{
266 		Mpi2EventDataSasEnclDevStatusChange_t *data;
267 		data = (Mpi2EventDataSasEnclDevStatusChange_t *)
268 		    fw_event->event_data;
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 	}
594 	mps_dprint(sc, MPS_EVENT, "(%d)->(%s) Event Free: [%x]\n",event_count,__func__, fw_event->event);
595 	mpssas_fw_event_free(sc, fw_event);
596 }
597 
598 void
599 mpssas_firmware_event_work(void *arg, int pending)
600 {
601 	struct mps_fw_event_work *fw_event;
602 	struct mps_softc *sc;
603 
604 	sc = (struct mps_softc *)arg;
605 	mps_lock(sc);
606 	while ((fw_event = TAILQ_FIRST(&sc->sassc->ev_queue)) != NULL) {
607 		TAILQ_REMOVE(&sc->sassc->ev_queue, fw_event, ev_link);
608 		mpssas_fw_work(sc, fw_event);
609 	}
610 	mps_unlock(sc);
611 }
612 
613 static int
614 mpssas_add_device(struct mps_softc *sc, u16 handle, u8 linkrate){
615 	char devstring[80];
616 	struct mpssas_softc *sassc;
617 	struct mpssas_target *targ;
618 	Mpi2ConfigReply_t mpi_reply;
619 	Mpi2SasDevicePage0_t config_page;
620 	uint64_t sas_address;
621 	uint64_t parent_sas_address = 0;
622 	u32 device_info, parent_devinfo = 0;
623 	unsigned int id;
624 	int ret = 1, error = 0, i;
625 	struct mpssas_lun *lun;
626 	u8 is_SATA_SSD = 0;
627 	struct mps_command *cm;
628 
629 	sassc = sc->sassc;
630 	mpssas_startup_increment(sassc);
631 	if ((mps_config_get_sas_device_pg0(sc, &mpi_reply, &config_page,
632 	     MPI2_SAS_DEVICE_PGAD_FORM_HANDLE, handle))) {
633 		printf("%s: error reading SAS device page0\n", __func__);
634 		error = ENXIO;
635 		goto out;
636 	}
637 
638 	device_info = le32toh(config_page.DeviceInfo);
639 
640 	if (((device_info & MPI2_SAS_DEVICE_INFO_SMP_TARGET) == 0)
641 	 && (le16toh(config_page.ParentDevHandle) != 0)) {
642 		Mpi2ConfigReply_t tmp_mpi_reply;
643 		Mpi2SasDevicePage0_t parent_config_page;
644 
645 		if ((mps_config_get_sas_device_pg0(sc, &tmp_mpi_reply,
646 		     &parent_config_page, MPI2_SAS_DEVICE_PGAD_FORM_HANDLE,
647 		     le16toh(config_page.ParentDevHandle)))) {
648 			printf("%s: error reading SAS device %#x page0\n",
649 			       __func__, le16toh(config_page.ParentDevHandle));
650 		} else {
651 			parent_sas_address = parent_config_page.SASAddress.High;
652 			parent_sas_address = (parent_sas_address << 32) |
653 				parent_config_page.SASAddress.Low;
654 			parent_devinfo = le32toh(parent_config_page.DeviceInfo);
655 		}
656 	}
657 	/* TODO Check proper endianness */
658 	sas_address = config_page.SASAddress.High;
659 	sas_address = (sas_address << 32) | config_page.SASAddress.Low;
660 
661 	/*
662 	 * Always get SATA Identify information because this is used to
663 	 * determine if Start/Stop Unit should be sent to the drive when the
664 	 * system is shutdown.
665 	 */
666 	if (device_info & MPI2_SAS_DEVICE_INFO_SATA_DEVICE) {
667 		ret = mpssas_get_sas_address_for_sata_disk(sc, &sas_address,
668 		    handle, device_info, &is_SATA_SSD);
669 		if (ret) {
670 			mps_dprint(sc, MPS_INFO, "%s: failed to get disk type "
671 			    "(SSD or HDD) for SATA device with handle 0x%04x\n",
672 			    __func__, handle);
673 		} else {
674 			mps_dprint(sc, MPS_INFO, "SAS Address from SATA "
675 			    "device = %jx\n", sas_address);
676 		}
677 	}
678 
679 	/*
680 	 * use_phynum:
681 	 *  1 - use the PhyNum field as a fallback to the mapping logic
682 	 *  0 - never use the PhyNum field
683 	 * -1 - only use the PhyNum field
684 	 *
685 	 * Note that using the Phy number to map a device can cause device adds
686 	 * to fail if multiple enclosures/expanders are in the topology. For
687 	 * example, if two devices are in the same slot number in two different
688 	 * enclosures within the topology, only one of those devices will be
689 	 * added. PhyNum mapping should not be used if multiple enclosures are
690 	 * in the topology.
691 	 */
692 	id = MPS_MAP_BAD_ID;
693 	if (sc->use_phynum != -1)
694 		id = mps_mapping_get_tid(sc, sas_address, handle);
695 	if (id == MPS_MAP_BAD_ID) {
696 		if ((sc->use_phynum == 0)
697 		 || ((id = config_page.PhyNum) > sassc->maxtargets)) {
698 			mps_dprint(sc, MPS_INFO, "failure at %s:%d/%s()! "
699 			    "Could not get ID for device with handle 0x%04x\n",
700 			    __FILE__, __LINE__, __func__, handle);
701 			error = ENXIO;
702 			goto out;
703 		}
704 	}
705 	mps_dprint(sc, MPS_MAPPING, "%s: Target ID for added device is %d.\n",
706 	    __func__, id);
707 
708 	/*
709 	 * Only do the ID check and reuse check if the target is not from a
710 	 * RAID Component. For Physical Disks of a Volume, the ID will be reused
711 	 * when a volume is deleted because the mapping entry for the PD will
712 	 * still be in the mapping table. The ID check should not be done here
713 	 * either since this PD is already being used.
714 	 */
715 	targ = &sassc->targets[id];
716 	if (!(targ->flags & MPS_TARGET_FLAGS_RAID_COMPONENT)) {
717 		if (mpssas_check_id(sassc, id) != 0) {
718 			device_printf(sc->mps_dev, "Excluding target id %d\n",
719 			    id);
720 			error = ENXIO;
721 			goto out;
722 		}
723 
724 		if (targ->handle != 0x0) {
725 			mps_dprint(sc, MPS_MAPPING, "Attempting to reuse "
726 			    "target id %d handle 0x%04x\n", id, targ->handle);
727 			error = ENXIO;
728 			goto out;
729 		}
730 	}
731 
732 	mps_dprint(sc, MPS_MAPPING, "SAS Address from SAS device page0 = %jx\n",
733 	    sas_address);
734 	targ->devinfo = device_info;
735 	targ->devname = le32toh(config_page.DeviceName.High);
736 	targ->devname = (targ->devname << 32) |
737 	    le32toh(config_page.DeviceName.Low);
738 	targ->encl_handle = le16toh(config_page.EnclosureHandle);
739 	targ->encl_slot = le16toh(config_page.Slot);
740 	targ->handle = handle;
741 	targ->parent_handle = le16toh(config_page.ParentDevHandle);
742 	targ->sasaddr = mps_to_u64(&config_page.SASAddress);
743 	targ->parent_sasaddr = le64toh(parent_sas_address);
744 	targ->parent_devinfo = parent_devinfo;
745 	targ->tid = id;
746 	targ->linkrate = (linkrate>>4);
747 	targ->flags = 0;
748 	if (is_SATA_SSD) {
749 		targ->flags = MPS_TARGET_IS_SATA_SSD;
750 	}
751 	TAILQ_INIT(&targ->commands);
752 	TAILQ_INIT(&targ->timedout_commands);
753 	while(!SLIST_EMPTY(&targ->luns)) {
754 		lun = SLIST_FIRST(&targ->luns);
755 		SLIST_REMOVE_HEAD(&targ->luns, lun_link);
756 		free(lun, M_MPT2);
757 	}
758 	SLIST_INIT(&targ->luns);
759 
760 	mps_describe_devinfo(targ->devinfo, devstring, 80);
761 	mps_dprint(sc, MPS_MAPPING, "Found device <%s> <%s> <0x%04x> <%d/%d>\n",
762 	    devstring, mps_describe_table(mps_linkrate_names, targ->linkrate),
763 	    targ->handle, targ->encl_handle, targ->encl_slot);
764 
765 #if __FreeBSD_version < 1000039
766 	if ((sassc->flags & MPSSAS_IN_STARTUP) == 0)
767 #endif
768 		mpssas_rescan_target(sc, targ);
769 	mps_dprint(sc, MPS_MAPPING, "Target id 0x%x added\n", targ->tid);
770 
771 	/*
772 	 * Check all commands to see if the SATA_ID_TIMEOUT flag has been set.
773 	 * If so, send a Target Reset TM to the target that was just created.
774 	 * An Abort Task TM should be used instead of a Target Reset, but that
775 	 * would be much more difficult because targets have not been fully
776 	 * discovered yet, and LUN's haven't been setup.  So, just reset the
777 	 * target instead of the LUN.
778 	 */
779 	for (i = 1; i < sc->num_reqs; i++) {
780 		cm = &sc->commands[i];
781 		if (cm->cm_flags & MPS_CM_FLAGS_SATA_ID_TIMEOUT) {
782 			targ->timeouts++;
783 			cm->cm_state = MPS_CM_STATE_TIMEDOUT;
784 
785 			if ((targ->tm = mpssas_alloc_tm(sc)) != NULL) {
786 				mps_dprint(sc, MPS_INFO, "%s: sending Target "
787 				    "Reset for stuck SATA identify command "
788 				    "(cm = %p)\n", __func__, cm);
789 				targ->tm->cm_targ = targ;
790 				mpssas_send_reset(sc, targ->tm,
791 				    MPI2_SCSITASKMGMT_TASKTYPE_TARGET_RESET);
792 			} else {
793 				mps_dprint(sc, MPS_ERROR, "Failed to allocate "
794 				    "tm for Target Reset after SATA ID command "
795 				    "timed out (cm %p)\n", cm);
796 			}
797 			/*
798 			 * No need to check for more since the target is
799 			 * already being reset.
800 			 */
801 			break;
802 		}
803 	}
804 out:
805 	/*
806 	 * Free the commands that may not have been freed from the SATA ID call
807 	 */
808 	for (i = 1; i < sc->num_reqs; i++) {
809 		cm = &sc->commands[i];
810 		if (cm->cm_flags & MPS_CM_FLAGS_SATA_ID_TIMEOUT) {
811 			mps_free_command(sc, cm);
812 		}
813 	}
814 	mpssas_startup_decrement(sassc);
815 	return (error);
816 }
817 
818 int
819 mpssas_get_sas_address_for_sata_disk(struct mps_softc *sc,
820     u64 *sas_address, u16 handle, u32 device_info, u8 *is_SATA_SSD)
821 {
822 	Mpi2SataPassthroughReply_t mpi_reply;
823 	int i, rc, try_count;
824 	u32 *bufferptr;
825 	union _sata_sas_address hash_address;
826 	struct _ata_identify_device_data ata_identify;
827 	u8 buffer[MPT2SAS_MN_LEN + MPT2SAS_SN_LEN];
828 	u32 ioc_status;
829 	u8 sas_status;
830 
831 	memset(&ata_identify, 0, sizeof(ata_identify));
832 	try_count = 0;
833 	do {
834 		rc = mpssas_get_sata_identify(sc, handle, &mpi_reply,
835 		    (char *)&ata_identify, sizeof(ata_identify), device_info);
836 		try_count++;
837 		ioc_status = le16toh(mpi_reply.IOCStatus)
838 		    & MPI2_IOCSTATUS_MASK;
839 		sas_status = mpi_reply.SASStatus;
840 		switch (ioc_status) {
841 		case MPI2_IOCSTATUS_SUCCESS:
842 			break;
843 		case MPI2_IOCSTATUS_SCSI_PROTOCOL_ERROR:
844 			/* No sense sleeping.  this error won't get better */
845 			break;
846 		default:
847 			if (sc->spinup_wait_time > 0) {
848 				mps_dprint(sc, MPS_INFO, "Sleeping %d seconds "
849 				    "after SATA ID error to wait for spinup\n",
850 				    sc->spinup_wait_time);
851 				msleep(&sc->msleep_fake_chan, &sc->mps_mtx, 0,
852 				    "mpsid", sc->spinup_wait_time * hz);
853 			}
854 		}
855 	} while (((rc && (rc != EWOULDBLOCK)) ||
856 	    	 (ioc_status &&
857 		  (ioc_status != MPI2_IOCSTATUS_SCSI_PROTOCOL_ERROR))
858 	       || sas_status) && (try_count < 5));
859 
860 	if (rc == 0 && !ioc_status && !sas_status) {
861 		mps_dprint(sc, MPS_MAPPING, "%s: got SATA identify "
862 		    "successfully for handle = 0x%x with try_count = %d\n",
863 		    __func__, handle, try_count);
864 	} else {
865 		mps_dprint(sc, MPS_MAPPING, "%s: handle = 0x%x failed\n",
866 		    __func__, handle);
867 		return -1;
868 	}
869 	/* Copy & byteswap the 40 byte model number to a buffer */
870 	for (i = 0; i < MPT2SAS_MN_LEN; i += 2) {
871 		buffer[i] = ((u8 *)ata_identify.model_number)[i + 1];
872 		buffer[i + 1] = ((u8 *)ata_identify.model_number)[i];
873 	}
874 	/* Copy & byteswap the 20 byte serial number to a buffer */
875 	for (i = 0; i < MPT2SAS_SN_LEN; i += 2) {
876 		buffer[MPT2SAS_MN_LEN + i] =
877 		    ((u8 *)ata_identify.serial_number)[i + 1];
878 		buffer[MPT2SAS_MN_LEN + i + 1] =
879 		    ((u8 *)ata_identify.serial_number)[i];
880 	}
881 	bufferptr = (u32 *)buffer;
882 	/* There are 60 bytes to hash down to 8. 60 isn't divisible by 8,
883 	 * so loop through the first 56 bytes (7*8),
884 	 * and then add in the last dword.
885 	 */
886 	hash_address.word.low  = 0;
887 	hash_address.word.high = 0;
888 	for (i = 0; (i < ((MPT2SAS_MN_LEN+MPT2SAS_SN_LEN)/8)); i++) {
889 		hash_address.word.low += *bufferptr;
890 		bufferptr++;
891 		hash_address.word.high += *bufferptr;
892 		bufferptr++;
893 	}
894 	/* Add the last dword */
895 	hash_address.word.low += *bufferptr;
896 	/* Make sure the hash doesn't start with 5, because it could clash
897 	 * with a SAS address. Change 5 to a D.
898 	 */
899 	if ((hash_address.word.high & 0x000000F0) == (0x00000050))
900 		hash_address.word.high |= 0x00000080;
901 	*sas_address = (u64)hash_address.wwid[0] << 56 |
902 	    (u64)hash_address.wwid[1] << 48 | (u64)hash_address.wwid[2] << 40 |
903 	    (u64)hash_address.wwid[3] << 32 | (u64)hash_address.wwid[4] << 24 |
904 	    (u64)hash_address.wwid[5] << 16 | (u64)hash_address.wwid[6] <<  8 |
905 	    (u64)hash_address.wwid[7];
906 	if (ata_identify.rotational_speed == 1) {
907 		*is_SATA_SSD = 1;
908 	}
909 
910 	return 0;
911 }
912 
913 static int
914 mpssas_get_sata_identify(struct mps_softc *sc, u16 handle,
915     Mpi2SataPassthroughReply_t *mpi_reply, char *id_buffer, int sz, u32 devinfo)
916 {
917 	Mpi2SataPassthroughRequest_t *mpi_request;
918 	Mpi2SataPassthroughReply_t *reply;
919 	struct mps_command *cm;
920 	char *buffer;
921 	int error = 0;
922 
923 	buffer = malloc( sz, M_MPT2, M_NOWAIT | M_ZERO);
924 	if (!buffer)
925 		return ENOMEM;
926 
927 	if ((cm = mps_alloc_command(sc)) == NULL) {
928 		free(buffer, M_MPT2);
929 		return (EBUSY);
930 	}
931 	mpi_request = (MPI2_SATA_PASSTHROUGH_REQUEST *)cm->cm_req;
932 	bzero(mpi_request,sizeof(MPI2_SATA_PASSTHROUGH_REQUEST));
933 	mpi_request->Function = MPI2_FUNCTION_SATA_PASSTHROUGH;
934 	mpi_request->VF_ID = 0;
935 	mpi_request->DevHandle = htole16(handle);
936 	mpi_request->PassthroughFlags = (MPI2_SATA_PT_REQ_PT_FLAGS_PIO |
937 	    MPI2_SATA_PT_REQ_PT_FLAGS_READ);
938 	mpi_request->DataLength = htole32(sz);
939 	mpi_request->CommandFIS[0] = 0x27;
940 	mpi_request->CommandFIS[1] = 0x80;
941 	mpi_request->CommandFIS[2] =  (devinfo &
942 	    MPI2_SAS_DEVICE_INFO_ATAPI_DEVICE) ? 0xA1 : 0xEC;
943 	cm->cm_sge = &mpi_request->SGL;
944 	cm->cm_sglsize = sizeof(MPI2_SGE_IO_UNION);
945 	cm->cm_flags = MPS_CM_FLAGS_SGE_SIMPLE | MPS_CM_FLAGS_DATAIN;
946 	cm->cm_desc.Default.RequestFlags = MPI2_REQ_DESCRIPT_FLAGS_DEFAULT_TYPE;
947 	cm->cm_data = buffer;
948 	cm->cm_length = htole32(sz);
949 
950 	/*
951 	 * Start a timeout counter specifically for the SATA ID command. This
952 	 * is used to fix a problem where the FW does not send a reply sometimes
953 	 * when a bad disk is in the topology. So, this is used to timeout the
954 	 * command so that processing can continue normally.
955 	 */
956 	mps_dprint(sc, MPS_XINFO, "%s start timeout counter for SATA ID "
957 	    "command\n", __func__);
958 	callout_reset(&cm->cm_callout, MPS_ATA_ID_TIMEOUT * hz,
959 	    mpssas_ata_id_timeout, cm);
960 	error = mps_wait_command(sc, cm, 60, CAN_SLEEP);
961 	mps_dprint(sc, MPS_XINFO, "%s stop timeout counter for SATA ID "
962 	    "command\n", __func__);
963 	callout_stop(&cm->cm_callout);
964 
965 	reply = (Mpi2SataPassthroughReply_t *)cm->cm_reply;
966 	if (error || (reply == NULL)) {
967 		/* FIXME */
968  		/*
969  		 * If the request returns an error then we need to do a diag
970  		 * reset
971  		 */
972  		printf("%s: request for page completed with error %d",
973 		    __func__, error);
974 		error = ENXIO;
975 		goto out;
976 	}
977 	bcopy(buffer, id_buffer, sz);
978 	bcopy(reply, mpi_reply, sizeof(Mpi2SataPassthroughReply_t));
979 	if ((le16toh(reply->IOCStatus) & MPI2_IOCSTATUS_MASK) !=
980 	    MPI2_IOCSTATUS_SUCCESS) {
981 		printf("%s: error reading SATA PASSTHRU; iocstatus = 0x%x\n",
982 		    __func__, reply->IOCStatus);
983 		error = ENXIO;
984 		goto out;
985 	}
986 out:
987 	/*
988 	 * If the SATA_ID_TIMEOUT flag has been set for this command, don't free
989 	 * it.  The command will be freed after sending a target reset TM. If
990 	 * the command did timeout, use EWOULDBLOCK.
991 	 */
992 	if ((cm->cm_flags & MPS_CM_FLAGS_SATA_ID_TIMEOUT) == 0)
993 		mps_free_command(sc, cm);
994 	else if (error == 0)
995 		error = EWOULDBLOCK;
996 	free(buffer, M_MPT2);
997 	return (error);
998 }
999 
1000 static void
1001 mpssas_ata_id_timeout(void *data)
1002 {
1003 	struct mps_softc *sc;
1004 	struct mps_command *cm;
1005 
1006 	cm = (struct mps_command *)data;
1007 	sc = cm->cm_sc;
1008 	mtx_assert(&sc->mps_mtx, MA_OWNED);
1009 
1010 	mps_dprint(sc, MPS_INFO, "%s checking ATA ID command %p sc %p\n",
1011 	    __func__, cm, sc);
1012 	if ((callout_pending(&cm->cm_callout)) ||
1013 	    (!callout_active(&cm->cm_callout))) {
1014 		mps_dprint(sc, MPS_INFO, "%s ATA ID command almost timed out\n",
1015 		    __func__);
1016 		return;
1017 	}
1018 	callout_deactivate(&cm->cm_callout);
1019 
1020 	/*
1021 	 * Run the interrupt handler to make sure it's not pending.  This
1022 	 * isn't perfect because the command could have already completed
1023 	 * and been re-used, though this is unlikely.
1024 	 */
1025 	mps_intr_locked(sc);
1026 	if (cm->cm_state == MPS_CM_STATE_FREE) {
1027 		mps_dprint(sc, MPS_INFO, "%s ATA ID command almost timed out\n",
1028 		    __func__);
1029 		return;
1030 	}
1031 
1032 	mps_dprint(sc, MPS_INFO, "ATA ID command timeout cm %p\n", cm);
1033 
1034 	/*
1035 	 * Send wakeup() to the sleeping thread that issued this ATA ID command.
1036 	 * wakeup() will cause msleep to return a 0 (not EWOULDBLOCK), and this
1037 	 * will keep reinit() from being called. This way, an Abort Task TM can
1038 	 * be issued so that the timed out command can be cleared.  The Abort
1039 	 * Task cannot be sent from here because the driver has not completed
1040 	 * setting up targets.  Instead, the command is flagged so that special
1041 	 * handling will be used to send the abort.
1042 	 */
1043 	cm->cm_flags |= MPS_CM_FLAGS_SATA_ID_TIMEOUT;
1044 	wakeup(cm);
1045 }
1046 
1047 static int
1048 mpssas_volume_add(struct mps_softc *sc, u16 handle)
1049 {
1050 	struct mpssas_softc *sassc;
1051 	struct mpssas_target *targ;
1052 	u64 wwid;
1053 	unsigned int id;
1054 	int error = 0;
1055 	struct mpssas_lun *lun;
1056 
1057 	sassc = sc->sassc;
1058 	mpssas_startup_increment(sassc);
1059 	/* wwid is endian safe */
1060 	mps_config_get_volume_wwid(sc, handle, &wwid);
1061 	if (!wwid) {
1062 		printf("%s: invalid WWID; cannot add volume to mapping table\n",
1063 		    __func__);
1064 		error = ENXIO;
1065 		goto out;
1066 	}
1067 
1068 	id = mps_mapping_get_raid_tid(sc, wwid, handle);
1069 	if (id == MPS_MAP_BAD_ID) {
1070 		printf("%s: could not get ID for volume with handle 0x%04x and "
1071 		    "WWID 0x%016llx\n", __func__, handle,
1072 		    (unsigned long long)wwid);
1073 		error = ENXIO;
1074 		goto out;
1075 	}
1076 
1077 	targ = &sassc->targets[id];
1078 	targ->tid = id;
1079 	targ->handle = handle;
1080 	targ->devname = wwid;
1081 	TAILQ_INIT(&targ->commands);
1082 	TAILQ_INIT(&targ->timedout_commands);
1083 	while(!SLIST_EMPTY(&targ->luns)) {
1084 		lun = SLIST_FIRST(&targ->luns);
1085 		SLIST_REMOVE_HEAD(&targ->luns, lun_link);
1086 		free(lun, M_MPT2);
1087 	}
1088 	SLIST_INIT(&targ->luns);
1089 #if __FreeBSD_version < 1000039
1090 	if ((sassc->flags & MPSSAS_IN_STARTUP) == 0)
1091 #endif
1092 		mpssas_rescan_target(sc, targ);
1093 	mps_dprint(sc, MPS_MAPPING, "RAID target id %d added (WWID = 0x%jx)\n",
1094 	    targ->tid, wwid);
1095 out:
1096 	mpssas_startup_decrement(sassc);
1097 	return (error);
1098 }
1099 
1100 /**
1101  * mpssas_SSU_to_SATA_devices
1102  * @sc: per adapter object
1103  *
1104  * Looks through the target list and issues a StartStopUnit SCSI command to each
1105  * SATA direct-access device.  This helps to ensure that data corruption is
1106  * avoided when the system is being shut down.  This must be called after the IR
1107  * System Shutdown RAID Action is sent if in IR mode.
1108  *
1109  * Return nothing.
1110  */
1111 static void
1112 mpssas_SSU_to_SATA_devices(struct mps_softc *sc)
1113 {
1114 	struct mpssas_softc *sassc = sc->sassc;
1115 	union ccb *ccb;
1116 	path_id_t pathid = cam_sim_path(sassc->sim);
1117 	target_id_t targetid;
1118 	struct mpssas_target *target;
1119 	char path_str[64];
1120 	struct timeval cur_time, start_time;
1121 
1122 	/*
1123 	 * For each target, issue a StartStopUnit command to stop the device.
1124 	 */
1125 	sc->SSU_started = TRUE;
1126 	sc->SSU_refcount = 0;
1127 	for (targetid = 0; targetid < sc->max_devices; targetid++) {
1128 		target = &sassc->targets[targetid];
1129 		if (target->handle == 0x0) {
1130 			continue;
1131 		}
1132 
1133 		ccb = xpt_alloc_ccb_nowait();
1134 		if (ccb == NULL) {
1135 			mps_dprint(sc, MPS_FAULT, "Unable to alloc CCB to stop "
1136 			    "unit.\n");
1137 			return;
1138 		}
1139 
1140 		/*
1141 		 * The stop_at_shutdown flag will be set if this device is
1142 		 * a SATA direct-access end device.
1143 		 */
1144 		if (target->stop_at_shutdown) {
1145 			if (xpt_create_path(&ccb->ccb_h.path,
1146 			    xpt_periph, pathid, targetid,
1147 			    CAM_LUN_WILDCARD) != CAM_REQ_CMP) {
1148 				mps_dprint(sc, MPS_FAULT, "Unable to create "
1149 				    "LUN path to stop unit.\n");
1150 				xpt_free_ccb(ccb);
1151 				return;
1152 			}
1153 			xpt_path_string(ccb->ccb_h.path, path_str,
1154 			    sizeof(path_str));
1155 
1156 			mps_dprint(sc, MPS_INFO, "Sending StopUnit: path %s "
1157 			    "handle %d\n", path_str, target->handle);
1158 
1159 			/*
1160 			 * Issue a START STOP UNIT command for the target.
1161 			 * Increment the SSU counter to be used to count the
1162 			 * number of required replies.
1163 			 */
1164 			mps_dprint(sc, MPS_INFO, "Incrementing SSU count\n");
1165 			sc->SSU_refcount++;
1166 			ccb->ccb_h.target_id =
1167 			    xpt_path_target_id(ccb->ccb_h.path);
1168 			ccb->ccb_h.ppriv_ptr1 = sassc;
1169 			scsi_start_stop(&ccb->csio,
1170 			    /*retries*/0,
1171 			    mpssas_stop_unit_done,
1172 			    MSG_SIMPLE_Q_TAG,
1173 			    /*start*/FALSE,
1174 			    /*load/eject*/0,
1175 			    /*immediate*/FALSE,
1176 			    MPS_SENSE_LEN,
1177 			    /*timeout*/10000);
1178 			xpt_action(ccb);
1179 		}
1180 	}
1181 
1182 	/*
1183 	 * Wait until all of the SSU commands have completed or time has
1184 	 * expired (60 seconds).  Pause for 100ms each time through.  If any
1185 	 * command times out, the target will be reset in the SCSI command
1186 	 * timeout routine.
1187 	 */
1188 	getmicrotime(&start_time);
1189 	while (sc->SSU_refcount) {
1190 		pause("mpswait", hz/10);
1191 
1192 		getmicrotime(&cur_time);
1193 		if ((cur_time.tv_sec - start_time.tv_sec) > 60) {
1194 			mps_dprint(sc, MPS_FAULT, "Time has expired waiting "
1195 			    "for SSU commands to complete.\n");
1196 			break;
1197 		}
1198 	}
1199 }
1200 
1201 static void
1202 mpssas_stop_unit_done(struct cam_periph *periph, union ccb *done_ccb)
1203 {
1204 	struct mpssas_softc *sassc;
1205 	char path_str[64];
1206 
1207 	if (done_ccb == NULL)
1208 		return;
1209 
1210 	sassc = (struct mpssas_softc *)done_ccb->ccb_h.ppriv_ptr1;
1211 
1212 	xpt_path_string(done_ccb->ccb_h.path, path_str, sizeof(path_str));
1213 	mps_dprint(sassc->sc, MPS_INFO, "Completing stop unit for %s\n",
1214 	    path_str);
1215 
1216 	/*
1217 	 * Nothing more to do except free the CCB and path.  If the command
1218 	 * timed out, an abort reset, then target reset will be issued during
1219 	 * the SCSI Command process.
1220 	 */
1221 	xpt_free_path(done_ccb->ccb_h.path);
1222 	xpt_free_ccb(done_ccb);
1223 }
1224 
1225 /**
1226  * mpssas_ir_shutdown - IR shutdown notification
1227  * @sc: per adapter object
1228  *
1229  * Sending RAID Action to alert the Integrated RAID subsystem of the IOC that
1230  * the host system is shutting down.
1231  *
1232  * Return nothing.
1233  */
1234 void
1235 mpssas_ir_shutdown(struct mps_softc *sc)
1236 {
1237 	u16 volume_mapping_flags;
1238 	u16 ioc_pg8_flags = le16toh(sc->ioc_pg8.Flags);
1239 	struct dev_mapping_table *mt_entry;
1240 	u32 start_idx, end_idx;
1241 	unsigned int id, found_volume = 0;
1242 	struct mps_command *cm;
1243 	Mpi2RaidActionRequest_t	*action;
1244 	target_id_t targetid;
1245 	struct mpssas_target *target;
1246 
1247 	mps_dprint(sc, MPS_TRACE, "%s\n", __func__);
1248 
1249 	/* is IR firmware build loaded? */
1250 	if (!sc->ir_firmware)
1251 		goto out;
1252 
1253 	/* are there any volumes?  Look at IR target IDs. */
1254 	// TODO-later, this should be looked up in the RAID config structure
1255 	// when it is implemented.
1256 	volume_mapping_flags = le16toh(sc->ioc_pg8.IRVolumeMappingFlags) &
1257 	    MPI2_IOCPAGE8_IRFLAGS_MASK_VOLUME_MAPPING_MODE;
1258 	if (volume_mapping_flags == MPI2_IOCPAGE8_IRFLAGS_LOW_VOLUME_MAPPING) {
1259 		start_idx = 0;
1260 		if (ioc_pg8_flags & MPI2_IOCPAGE8_FLAGS_RESERVED_TARGETID_0)
1261 			start_idx = 1;
1262 	} else
1263 		start_idx = sc->max_devices - sc->max_volumes;
1264 	end_idx = start_idx + sc->max_volumes - 1;
1265 
1266 	for (id = start_idx; id < end_idx; id++) {
1267 		mt_entry = &sc->mapping_table[id];
1268 		if ((mt_entry->physical_id != 0) &&
1269 		    (mt_entry->missing_count == 0)) {
1270 			found_volume = 1;
1271 			break;
1272 		}
1273 	}
1274 
1275 	if (!found_volume)
1276 		goto out;
1277 
1278 	if ((cm = mps_alloc_command(sc)) == NULL) {
1279 		printf("%s: command alloc failed\n", __func__);
1280 		goto out;
1281 	}
1282 
1283 	action = (MPI2_RAID_ACTION_REQUEST *)cm->cm_req;
1284 	action->Function = MPI2_FUNCTION_RAID_ACTION;
1285 	action->Action = MPI2_RAID_ACTION_SYSTEM_SHUTDOWN_INITIATED;
1286 	cm->cm_desc.Default.RequestFlags = MPI2_REQ_DESCRIPT_FLAGS_DEFAULT_TYPE;
1287 	mps_lock(sc);
1288 	mps_wait_command(sc, cm, 5, CAN_SLEEP);
1289 	mps_unlock(sc);
1290 
1291 	/*
1292 	 * Don't check for reply, just leave.
1293 	 */
1294 	if (cm)
1295 		mps_free_command(sc, cm);
1296 
1297 out:
1298 	/*
1299 	 * All of the targets must have the correct value set for
1300 	 * 'stop_at_shutdown' for the current 'enable_ssu' sysctl variable.
1301 	 *
1302 	 * The possible values for the 'enable_ssu' variable are:
1303 	 * 0: disable to SSD and HDD
1304 	 * 1: disable only to HDD (default)
1305 	 * 2: disable only to SSD
1306 	 * 3: enable to SSD and HDD
1307 	 * anything else will default to 1.
1308 	 */
1309 	for (targetid = 0; targetid < sc->max_devices; targetid++) {
1310 		target = &sc->sassc->targets[targetid];
1311 		if (target->handle == 0x0) {
1312 			continue;
1313 		}
1314 
1315 		if (target->supports_SSU) {
1316 			switch (sc->enable_ssu) {
1317 			case MPS_SSU_DISABLE_SSD_DISABLE_HDD:
1318 				target->stop_at_shutdown = FALSE;
1319 				break;
1320 			case MPS_SSU_DISABLE_SSD_ENABLE_HDD:
1321 				target->stop_at_shutdown = TRUE;
1322 				if (target->flags & MPS_TARGET_IS_SATA_SSD) {
1323 					target->stop_at_shutdown = FALSE;
1324 				}
1325 				break;
1326 			case MPS_SSU_ENABLE_SSD_ENABLE_HDD:
1327 				target->stop_at_shutdown = TRUE;
1328 				break;
1329 			case MPS_SSU_ENABLE_SSD_DISABLE_HDD:
1330 			default:
1331 				target->stop_at_shutdown = TRUE;
1332 				if ((target->flags &
1333 				    MPS_TARGET_IS_SATA_SSD) == 0) {
1334 					target->stop_at_shutdown = FALSE;
1335 				}
1336 				break;
1337 			}
1338 		}
1339 	}
1340 	mpssas_SSU_to_SATA_devices(sc);
1341 }
1342