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