xref: /freebsd/sys/dev/mps/mps_sas_lsi.c (revision d9f0ce31900a48d1a2bfc1c8c86f79d1e831451a)
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_print_evt_sas(sc, 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), phy->LinkRate)){
221 					printf("%s: failed to add device with "
222 					    "handle 0x%x\n", __func__,
223 					    le16toh(phy->AttachedDevHandle));
224 					mpssas_prepare_remove(sassc, le16toh(
225 						phy->AttachedDevHandle));
226 				}
227 				break;
228 			case MPI2_EVENT_SAS_TOPO_RC_TARG_NOT_RESPONDING:
229 				mpssas_prepare_remove(sassc,le16toh(
230 					phy->AttachedDevHandle));
231 				break;
232 			case MPI2_EVENT_SAS_TOPO_RC_PHY_CHANGED:
233 			case MPI2_EVENT_SAS_TOPO_RC_NO_CHANGE:
234 			case MPI2_EVENT_SAS_TOPO_RC_DELAY_NOT_RESPONDING:
235 			default:
236 				break;
237 			}
238 		}
239 		/*
240 		 * refcount was incremented for this event in
241 		 * mpssas_evt_handler.  Decrement it here because the event has
242 		 * been processed.
243 		 */
244 		mpssas_startup_decrement(sassc);
245 		break;
246 	}
247 	case MPI2_EVENT_SAS_DISCOVERY:
248 	{
249 		MPI2_EVENT_DATA_SAS_DISCOVERY *data;
250 
251 		data = (MPI2_EVENT_DATA_SAS_DISCOVERY *)fw_event->event_data;
252 
253 		if (data->ReasonCode & MPI2_EVENT_SAS_DISC_RC_STARTED)
254 			mps_dprint(sc, MPS_TRACE,"SAS discovery start event\n");
255 		if (data->ReasonCode & MPI2_EVENT_SAS_DISC_RC_COMPLETED) {
256 			mps_dprint(sc, MPS_TRACE,"SAS discovery stop event\n");
257 			sassc->flags &= ~MPSSAS_IN_DISCOVERY;
258 			mpssas_discovery_end(sassc);
259 		}
260 		break;
261 	}
262 	case MPI2_EVENT_SAS_ENCL_DEVICE_STATUS_CHANGE:
263 	{
264 		Mpi2EventDataSasEnclDevStatusChange_t *data;
265 		data = (Mpi2EventDataSasEnclDevStatusChange_t *)
266 		    fw_event->event_data;
267 		mps_mapping_enclosure_dev_status_change_event(sc,
268 		    fw_event->event_data);
269 		break;
270 	}
271 	case MPI2_EVENT_IR_CONFIGURATION_CHANGE_LIST:
272 	{
273 		Mpi2EventIrConfigElement_t *element;
274 		int i;
275 		u8 foreign_config;
276 		Mpi2EventDataIrConfigChangeList_t *event_data;
277 		struct mpssas_target *targ;
278 		unsigned int id;
279 
280 		event_data = fw_event->event_data;
281 		foreign_config = (le32toh(event_data->Flags) &
282 		    MPI2_EVENT_IR_CHANGE_FLAGS_FOREIGN_CONFIG) ? 1 : 0;
283 
284 		element =
285 		    (Mpi2EventIrConfigElement_t *)&event_data->ConfigElement[0];
286 		id = mps_mapping_get_raid_id_from_handle
287 		    (sc, element->VolDevHandle);
288 
289 		mps_mapping_ir_config_change_event(sc, event_data);
290 
291 		for (i = 0; i < event_data->NumElements; i++, element++) {
292 			switch (element->ReasonCode) {
293 			case MPI2_EVENT_IR_CHANGE_RC_VOLUME_CREATED:
294 			case MPI2_EVENT_IR_CHANGE_RC_ADDED:
295 				if (!foreign_config) {
296 					if (mpssas_volume_add(sc, le16toh(element->VolDevHandle))){
297 						printf("%s: failed to add RAID "
298 						    "volume with handle 0x%x\n",
299 						    __func__, le16toh(element->
300 						    VolDevHandle));
301 					}
302 				}
303 				break;
304 			case MPI2_EVENT_IR_CHANGE_RC_VOLUME_DELETED:
305 			case MPI2_EVENT_IR_CHANGE_RC_REMOVED:
306 				/*
307 				 * Rescan after volume is deleted or removed.
308 				 */
309 				if (!foreign_config) {
310 					if (id == MPS_MAP_BAD_ID) {
311 						printf("%s: could not get ID "
312 						    "for volume with handle "
313 						    "0x%04x\n", __func__,
314 						    le16toh(element->VolDevHandle));
315 						break;
316 					}
317 
318 					targ = &sassc->targets[id];
319 					targ->handle = 0x0;
320 					targ->encl_slot = 0x0;
321 					targ->encl_handle = 0x0;
322 					targ->exp_dev_handle = 0x0;
323 					targ->phy_num = 0x0;
324 					targ->linkrate = 0x0;
325 					mpssas_rescan_target(sc, targ);
326 					printf("RAID target id 0x%x removed\n",
327 					    targ->tid);
328 				}
329 				break;
330 			case MPI2_EVENT_IR_CHANGE_RC_PD_CREATED:
331 			case MPI2_EVENT_IR_CHANGE_RC_HIDE:
332 				/*
333 				 * Phys Disk of a volume has been created.  Hide
334 				 * it from the OS.
335 				 */
336 				targ = mpssas_find_target_by_handle(sassc, 0, element->PhysDiskDevHandle);
337 				if (targ == NULL)
338 					break;
339 
340 				/* Set raid component flags only if it is not WD.
341 				 * OR WrapDrive with WD_HIDE_ALWAYS/WD_HIDE_IF_VOLUME is set in NVRAM
342 				 */
343 				if((!sc->WD_available) ||
344 				((sc->WD_available &&
345 				(sc->WD_hide_expose == MPS_WD_HIDE_ALWAYS)) ||
346 				(sc->WD_valid_config && (sc->WD_hide_expose ==
347 				MPS_WD_HIDE_IF_VOLUME)))) {
348 					targ->flags |= MPS_TARGET_FLAGS_RAID_COMPONENT;
349 				}
350 				mpssas_rescan_target(sc, targ);
351 
352 				break;
353 			case MPI2_EVENT_IR_CHANGE_RC_PD_DELETED:
354 				/*
355 				 * Phys Disk of a volume has been deleted.
356 				 * Expose it to the OS.
357 				 */
358 				if (mpssas_add_device(sc,
359 				    le16toh(element->PhysDiskDevHandle), 0)){
360 					printf("%s: failed to add device with "
361 					    "handle 0x%x\n", __func__,
362 					    le16toh(element->PhysDiskDevHandle));
363 					mpssas_prepare_remove(sassc, le16toh(element->
364 					    PhysDiskDevHandle));
365 				}
366 				break;
367 			}
368 		}
369 		/*
370 		 * refcount was incremented for this event in
371 		 * mpssas_evt_handler.  Decrement it here because the event has
372 		 * been processed.
373 		 */
374 		mpssas_startup_decrement(sassc);
375 		break;
376 	}
377 	case MPI2_EVENT_IR_VOLUME:
378 	{
379 		Mpi2EventDataIrVolume_t *event_data = fw_event->event_data;
380 
381 		/*
382 		 * Informational only.
383 		 */
384 		mps_dprint(sc, MPS_EVENT, "Received IR Volume event:\n");
385 		switch (event_data->ReasonCode) {
386 		case MPI2_EVENT_IR_VOLUME_RC_SETTINGS_CHANGED:
387   			mps_dprint(sc, MPS_EVENT, "   Volume Settings "
388   			    "changed from 0x%x to 0x%x for Volome with "
389  			    "handle 0x%x", le32toh(event_data->PreviousValue),
390  			    le32toh(event_data->NewValue),
391  			    le16toh(event_data->VolDevHandle));
392 			break;
393 		case MPI2_EVENT_IR_VOLUME_RC_STATUS_FLAGS_CHANGED:
394   			mps_dprint(sc, MPS_EVENT, "   Volume Status "
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_STATE_CHANGED:
401   			mps_dprint(sc, MPS_EVENT, "   Volume State "
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 				u32 state;
407 				struct mpssas_target *targ;
408 				state = le32toh(event_data->NewValue);
409 				switch (state) {
410 				case MPI2_RAID_VOL_STATE_MISSING:
411 				case MPI2_RAID_VOL_STATE_FAILED:
412 					mpssas_prepare_volume_remove(sassc, event_data->
413 							VolDevHandle);
414 					break;
415 
416 				case MPI2_RAID_VOL_STATE_ONLINE:
417 				case MPI2_RAID_VOL_STATE_DEGRADED:
418 				case MPI2_RAID_VOL_STATE_OPTIMAL:
419 					targ = mpssas_find_target_by_handle(sassc, 0, event_data->VolDevHandle);
420 					if (targ) {
421 						printf("%s %d: Volume handle 0x%x is already added \n",
422 							       	__func__, __LINE__ , event_data->VolDevHandle);
423 						break;
424 					}
425 					if (mpssas_volume_add(sc, le16toh(event_data->VolDevHandle))) {
426 						printf("%s: failed to add RAID "
427 							"volume with handle 0x%x\n",
428 							__func__, le16toh(event_data->
429 							VolDevHandle));
430 					}
431 					break;
432 				default:
433 					break;
434 				}
435 			break;
436 		default:
437 			break;
438 		}
439 		break;
440 	}
441 	case MPI2_EVENT_IR_PHYSICAL_DISK:
442 	{
443 		Mpi2EventDataIrPhysicalDisk_t *event_data =
444 		    fw_event->event_data;
445 		struct mpssas_target *targ;
446 
447 		/*
448 		 * Informational only.
449 		 */
450 		mps_dprint(sc, MPS_EVENT, "Received IR Phys Disk event:\n");
451 		switch (event_data->ReasonCode) {
452 		case MPI2_EVENT_IR_PHYSDISK_RC_SETTINGS_CHANGED:
453   			mps_dprint(sc, MPS_EVENT, "   Phys Disk Settings "
454   			    "changed from 0x%x to 0x%x for Phys Disk Number "
455   			    "%d and handle 0x%x at Enclosure handle 0x%x, Slot "
456  			    "%d", le32toh(event_data->PreviousValue),
457  			    le32toh(event_data->NewValue),
458  				event_data->PhysDiskNum,
459  			    le16toh(event_data->PhysDiskDevHandle),
460  			    le16toh(event_data->EnclosureHandle), le16toh(event_data->Slot));
461 			break;
462 		case MPI2_EVENT_IR_PHYSDISK_RC_STATUS_FLAGS_CHANGED:
463   			mps_dprint(sc, MPS_EVENT, "   Phys Disk Status changed "
464   			    "from 0x%x to 0x%x for Phys Disk Number %d and "
465   			    "handle 0x%x at Enclosure handle 0x%x, Slot %d",
466  				le32toh(event_data->PreviousValue),
467  			    le32toh(event_data->NewValue), 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_STATE_CHANGED:
472   			mps_dprint(sc, MPS_EVENT, "   Phys Disk State 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 			switch (event_data->NewValue) {
480 				case MPI2_RAID_PD_STATE_ONLINE:
481 				case MPI2_RAID_PD_STATE_DEGRADED:
482 				case MPI2_RAID_PD_STATE_REBUILDING:
483 				case MPI2_RAID_PD_STATE_OPTIMAL:
484 				case MPI2_RAID_PD_STATE_HOT_SPARE:
485 					targ = mpssas_find_target_by_handle(sassc, 0,
486 							event_data->PhysDiskDevHandle);
487 					if (targ) {
488 						if(!sc->WD_available) {
489 							targ->flags |= MPS_TARGET_FLAGS_RAID_COMPONENT;
490 							printf("%s %d: Found Target for handle 0x%x.  \n",
491 							__func__, __LINE__ , event_data->PhysDiskDevHandle);
492 						} else if ((sc->WD_available &&
493 							(sc->WD_hide_expose == MPS_WD_HIDE_ALWAYS)) ||
494         						(sc->WD_valid_config && (sc->WD_hide_expose ==
495         						MPS_WD_HIDE_IF_VOLUME))) {
496 							targ->flags |= MPS_TARGET_FLAGS_RAID_COMPONENT;
497 							printf("%s %d: WD: Found Target for handle 0x%x.  \n",
498 							__func__, __LINE__ , event_data->PhysDiskDevHandle);
499 						}
500  					}
501 				break;
502 				case MPI2_RAID_PD_STATE_OFFLINE:
503 				case MPI2_RAID_PD_STATE_NOT_CONFIGURED:
504 				case MPI2_RAID_PD_STATE_NOT_COMPATIBLE:
505 				default:
506 					targ = mpssas_find_target_by_handle(sassc, 0,
507 							event_data->PhysDiskDevHandle);
508 					if (targ) {
509 						targ->flags |= ~MPS_TARGET_FLAGS_RAID_COMPONENT;
510 						printf("%s %d: Found Target for handle 0x%x.  \n",
511 						__func__, __LINE__ , event_data->PhysDiskDevHandle);
512 					}
513 				break;
514 			}
515 		default:
516 			break;
517 		}
518 		break;
519 	}
520 	case MPI2_EVENT_IR_OPERATION_STATUS:
521 	{
522 		Mpi2EventDataIrOperationStatus_t *event_data =
523 		    fw_event->event_data;
524 
525 		/*
526 		 * Informational only.
527 		 */
528 		mps_dprint(sc, MPS_EVENT, "Received IR Op Status event:\n");
529 		mps_dprint(sc, MPS_EVENT, "   RAID Operation of %d is %d "
530 		    "percent complete for Volume with handle 0x%x",
531 		    event_data->RAIDOperation, event_data->PercentComplete,
532 		    le16toh(event_data->VolDevHandle));
533 		break;
534 	}
535 	case MPI2_EVENT_LOG_ENTRY_ADDED:
536 	{
537 		pMpi2EventDataLogEntryAdded_t	logEntry;
538 		uint16_t			logQualifier;
539 		uint8_t				logCode;
540 
541 		logEntry = (pMpi2EventDataLogEntryAdded_t)fw_event->event_data;
542 		logQualifier = logEntry->LogEntryQualifier;
543 
544 		if (logQualifier == MPI2_WD_LOG_ENTRY) {
545 			logCode = logEntry->LogData[0];
546 
547 			switch (logCode) {
548 			case MPI2_WD_SSD_THROTTLING:
549 				printf("WarpDrive Warning: IO Throttling has "
550 				    "occurred in the WarpDrive subsystem. "
551 				    "Check WarpDrive documentation for "
552 				    "additional details\n");
553 				break;
554 			case MPI2_WD_DRIVE_LIFE_WARN:
555 				printf("WarpDrive Warning: Program/Erase "
556 				    "Cycles for the WarpDrive subsystem in "
557 				    "degraded range. Check WarpDrive "
558 				    "documentation for additional details\n");
559 				break;
560 			case MPI2_WD_DRIVE_LIFE_DEAD:
561 				printf("WarpDrive Fatal Error: There are no "
562 				    "Program/Erase Cycles for the WarpDrive "
563 				    "subsystem. The storage device will be in "
564 				    "read-only mode. Check WarpDrive "
565 				    "documentation for additional details\n");
566 				break;
567 			case MPI2_WD_RAIL_MON_FAIL:
568 				printf("WarpDrive Fatal Error: The Backup Rail "
569 				    "Monitor has failed on the WarpDrive "
570 				    "subsystem. Check WarpDrive documentation "
571 				    "for additional details\n");
572 				break;
573 			default:
574 				break;
575 			}
576 		}
577 		break;
578 	}
579 	case MPI2_EVENT_SAS_DEVICE_STATUS_CHANGE:
580 	case MPI2_EVENT_SAS_BROADCAST_PRIMITIVE:
581 	default:
582 		mps_dprint(sc, MPS_TRACE,"Unhandled event 0x%0X\n",
583 		    fw_event->event);
584 		break;
585 
586 	}
587 	mps_dprint(sc, MPS_EVENT, "(%d)->(%s) Event Free: [%x]\n",event_count,__func__, fw_event->event);
588 	mpssas_fw_event_free(sc, fw_event);
589 }
590 
591 void
592 mpssas_firmware_event_work(void *arg, int pending)
593 {
594 	struct mps_fw_event_work *fw_event;
595 	struct mps_softc *sc;
596 
597 	sc = (struct mps_softc *)arg;
598 	mps_lock(sc);
599 	while ((fw_event = TAILQ_FIRST(&sc->sassc->ev_queue)) != NULL) {
600 		TAILQ_REMOVE(&sc->sassc->ev_queue, fw_event, ev_link);
601 		mpssas_fw_work(sc, fw_event);
602 	}
603 	mps_unlock(sc);
604 }
605 
606 static int
607 mpssas_add_device(struct mps_softc *sc, u16 handle, u8 linkrate){
608 	char devstring[80];
609 	struct mpssas_softc *sassc;
610 	struct mpssas_target *targ;
611 	Mpi2ConfigReply_t mpi_reply;
612 	Mpi2SasDevicePage0_t config_page;
613 	uint64_t sas_address;
614 	uint64_t parent_sas_address = 0;
615 	u32 device_info, parent_devinfo = 0;
616 	unsigned int id;
617 	int ret = 1, error = 0, i;
618 	struct mpssas_lun *lun;
619 	u8 is_SATA_SSD = 0;
620 	struct mps_command *cm;
621 
622 	sassc = sc->sassc;
623 	mpssas_startup_increment(sassc);
624 	if ((mps_config_get_sas_device_pg0(sc, &mpi_reply, &config_page,
625 	     MPI2_SAS_DEVICE_PGAD_FORM_HANDLE, handle))) {
626 		printf("%s: error reading SAS device page0\n", __func__);
627 		error = ENXIO;
628 		goto out;
629 	}
630 
631 	device_info = le32toh(config_page.DeviceInfo);
632 
633 	if (((device_info & MPI2_SAS_DEVICE_INFO_SMP_TARGET) == 0)
634 	 && (le16toh(config_page.ParentDevHandle) != 0)) {
635 		Mpi2ConfigReply_t tmp_mpi_reply;
636 		Mpi2SasDevicePage0_t parent_config_page;
637 
638 		if ((mps_config_get_sas_device_pg0(sc, &tmp_mpi_reply,
639 		     &parent_config_page, MPI2_SAS_DEVICE_PGAD_FORM_HANDLE,
640 		     le16toh(config_page.ParentDevHandle)))) {
641 			printf("%s: error reading SAS device %#x page0\n",
642 			       __func__, le16toh(config_page.ParentDevHandle));
643 		} else {
644 			parent_sas_address = parent_config_page.SASAddress.High;
645 			parent_sas_address = (parent_sas_address << 32) |
646 				parent_config_page.SASAddress.Low;
647 			parent_devinfo = le32toh(parent_config_page.DeviceInfo);
648 		}
649 	}
650 	/* TODO Check proper endianess */
651 	sas_address = config_page.SASAddress.High;
652 	sas_address = (sas_address << 32) | config_page.SASAddress.Low;
653 
654 	/*
655 	 * Always get SATA Identify information because this is used to
656 	 * determine if Start/Stop Unit should be sent to the drive when the
657 	 * system is shutdown.
658 	 */
659 	if (device_info & MPI2_SAS_DEVICE_INFO_SATA_DEVICE) {
660 		ret = mpssas_get_sas_address_for_sata_disk(sc, &sas_address,
661 		    handle, device_info, &is_SATA_SSD);
662 		if (ret) {
663 			mps_dprint(sc, MPS_INFO, "%s: failed to get disk type "
664 			    "(SSD or HDD) for SATA device with handle 0x%04x\n",
665 			    __func__, handle);
666 		} else {
667 			mps_dprint(sc, MPS_INFO, "SAS Address from SATA "
668 			    "device = %jx\n", sas_address);
669 		}
670 	}
671 
672 	id = mps_mapping_get_sas_id(sc, sas_address, handle);
673 	if (id == MPS_MAP_BAD_ID) {
674 		printf("failure at %s:%d/%s()! Could not get ID for device "
675 		    "with handle 0x%04x\n", __FILE__, __LINE__, __func__,
676 		    handle);
677 		error = ENXIO;
678 		goto out;
679 	}
680 
681 	if (mpssas_check_id(sassc, id) != 0) {
682 		device_printf(sc->mps_dev, "Excluding target id %d\n", id);
683 		error = ENXIO;
684 		goto out;
685 	}
686 
687 	mps_dprint(sc, MPS_MAPPING, "SAS Address from SAS device page0 = %jx\n",
688 	    sas_address);
689 	targ = &sassc->targets[id];
690 	targ->devinfo = device_info;
691 	targ->devname = le32toh(config_page.DeviceName.High);
692 	targ->devname = (targ->devname << 32) |
693 	    le32toh(config_page.DeviceName.Low);
694 	targ->encl_handle = le16toh(config_page.EnclosureHandle);
695 	targ->encl_slot = le16toh(config_page.Slot);
696 	targ->handle = handle;
697 	targ->parent_handle = le16toh(config_page.ParentDevHandle);
698 	targ->sasaddr = mps_to_u64(&config_page.SASAddress);
699 	targ->parent_sasaddr = le64toh(parent_sas_address);
700 	targ->parent_devinfo = parent_devinfo;
701 	targ->tid = id;
702 	targ->linkrate = (linkrate>>4);
703 	targ->flags = 0;
704 	if (is_SATA_SSD) {
705 		targ->flags = MPS_TARGET_IS_SATA_SSD;
706 	}
707 	TAILQ_INIT(&targ->commands);
708 	TAILQ_INIT(&targ->timedout_commands);
709 	while(!SLIST_EMPTY(&targ->luns)) {
710 		lun = SLIST_FIRST(&targ->luns);
711 		SLIST_REMOVE_HEAD(&targ->luns, lun_link);
712 		free(lun, M_MPT2);
713 	}
714 	SLIST_INIT(&targ->luns);
715 
716 	mps_describe_devinfo(targ->devinfo, devstring, 80);
717 	mps_dprint(sc, MPS_MAPPING, "Found device <%s> <%s> <0x%04x> <%d/%d>\n",
718 	    devstring, mps_describe_table(mps_linkrate_names, targ->linkrate),
719 	    targ->handle, targ->encl_handle, targ->encl_slot);
720 
721 #if __FreeBSD_version < 1000039
722 	if ((sassc->flags & MPSSAS_IN_STARTUP) == 0)
723 #endif
724 		mpssas_rescan_target(sc, targ);
725 	mps_dprint(sc, MPS_MAPPING, "Target id 0x%x added\n", targ->tid);
726 
727 	/*
728 	 * Check all commands to see if the SATA_ID_TIMEOUT flag has been set.
729 	 * If so, send a Target Reset TM to the target that was just created.
730 	 * An Abort Task TM should be used instead of a Target Reset, but that
731 	 * would be much more difficult because targets have not been fully
732 	 * discovered yet, and LUN's haven't been setup.  So, just reset the
733 	 * target instead of the LUN.
734 	 */
735 	for (i = 1; i < sc->num_reqs; i++) {
736 		cm = &sc->commands[i];
737 		if (cm->cm_flags & MPS_CM_FLAGS_SATA_ID_TIMEOUT) {
738 			targ->timeouts++;
739 			cm->cm_state = MPS_CM_STATE_TIMEDOUT;
740 
741 			if ((targ->tm = mpssas_alloc_tm(sc)) != NULL) {
742 				mps_dprint(sc, MPS_INFO, "%s: sending Target "
743 				    "Reset for stuck SATA identify command "
744 				    "(cm = %p)\n", __func__, cm);
745 				targ->tm->cm_targ = targ;
746 				mpssas_send_reset(sc, targ->tm,
747 				    MPI2_SCSITASKMGMT_TASKTYPE_TARGET_RESET);
748 			} else {
749 				mps_dprint(sc, MPS_ERROR, "Failed to allocate "
750 				    "tm for Target Reset after SATA ID command "
751 				    "timed out (cm %p)\n", cm);
752 			}
753 			/*
754 			 * No need to check for more since the target is
755 			 * already being reset.
756 			 */
757 			break;
758 		}
759 	}
760 out:
761 	/*
762 	 * Free the commands that may not have been freed from the SATA ID call
763 	 */
764 	for (i = 1; i < sc->num_reqs; i++) {
765 		cm = &sc->commands[i];
766 		if (cm->cm_flags & MPS_CM_FLAGS_SATA_ID_TIMEOUT) {
767 			mps_free_command(sc, cm);
768 		}
769 	}
770 	mpssas_startup_decrement(sassc);
771 	return (error);
772 
773 }
774 
775 int
776 mpssas_get_sas_address_for_sata_disk(struct mps_softc *sc,
777     u64 *sas_address, u16 handle, u32 device_info, u8 *is_SATA_SSD)
778 {
779 	Mpi2SataPassthroughReply_t mpi_reply;
780 	int i, rc, try_count;
781 	u32 *bufferptr;
782 	union _sata_sas_address hash_address;
783 	struct _ata_identify_device_data ata_identify;
784 	u8 buffer[MPT2SAS_MN_LEN + MPT2SAS_SN_LEN];
785 	u32 ioc_status;
786 	u8 sas_status;
787 
788 	memset(&ata_identify, 0, sizeof(ata_identify));
789 	try_count = 0;
790 	do {
791 		rc = mpssas_get_sata_identify(sc, handle, &mpi_reply,
792 		    (char *)&ata_identify, sizeof(ata_identify), device_info);
793 		try_count++;
794 		ioc_status = le16toh(mpi_reply.IOCStatus)
795 		    & MPI2_IOCSTATUS_MASK;
796 		sas_status = mpi_reply.SASStatus;
797 		switch (ioc_status) {
798 		case MPI2_IOCSTATUS_SUCCESS:
799 			break;
800 		case MPI2_IOCSTATUS_SCSI_PROTOCOL_ERROR:
801 			/* No sense sleeping.  this error won't get better */
802 			break;
803 		default:
804 			if (sc->spinup_wait_time > 0) {
805 				mps_dprint(sc, MPS_INFO, "Sleeping %d seconds "
806 				    "after SATA ID error to wait for spinup\n",
807 				    sc->spinup_wait_time);
808 				msleep(&sc->msleep_fake_chan, &sc->mps_mtx, 0,
809 				    "mpsid", sc->spinup_wait_time * hz);
810 			}
811 		}
812 	} while (((rc && (rc != EWOULDBLOCK)) ||
813 	    	 (ioc_status &&
814 		  (ioc_status != MPI2_IOCSTATUS_SCSI_PROTOCOL_ERROR))
815 	       || sas_status) && (try_count < 5));
816 
817 	if (rc == 0 && !ioc_status && !sas_status) {
818 		mps_dprint(sc, MPS_MAPPING, "%s: got SATA identify "
819 		    "successfully for handle = 0x%x with try_count = %d\n",
820 		    __func__, handle, try_count);
821 	} else {
822 		mps_dprint(sc, MPS_MAPPING, "%s: handle = 0x%x failed\n",
823 		    __func__, handle);
824 		return -1;
825 	}
826 	/* Copy & byteswap the 40 byte model number to a buffer */
827 	for (i = 0; i < MPT2SAS_MN_LEN; i += 2) {
828 		buffer[i] = ((u8 *)ata_identify.model_number)[i + 1];
829 		buffer[i + 1] = ((u8 *)ata_identify.model_number)[i];
830 	}
831 	/* Copy & byteswap the 20 byte serial number to a buffer */
832 	for (i = 0; i < MPT2SAS_SN_LEN; i += 2) {
833 		buffer[MPT2SAS_MN_LEN + i] =
834 		    ((u8 *)ata_identify.serial_number)[i + 1];
835 		buffer[MPT2SAS_MN_LEN + i + 1] =
836 		    ((u8 *)ata_identify.serial_number)[i];
837 	}
838 	bufferptr = (u32 *)buffer;
839 	/* There are 60 bytes to hash down to 8. 60 isn't divisible by 8,
840 	 * so loop through the first 56 bytes (7*8),
841 	 * and then add in the last dword.
842 	 */
843 	hash_address.word.low  = 0;
844 	hash_address.word.high = 0;
845 	for (i = 0; (i < ((MPT2SAS_MN_LEN+MPT2SAS_SN_LEN)/8)); i++) {
846 		hash_address.word.low += *bufferptr;
847 		bufferptr++;
848 		hash_address.word.high += *bufferptr;
849 		bufferptr++;
850 	}
851 	/* Add the last dword */
852 	hash_address.word.low += *bufferptr;
853 	/* Make sure the hash doesn't start with 5, because it could clash
854 	 * with a SAS address. Change 5 to a D.
855 	 */
856 	if ((hash_address.word.high & 0x000000F0) == (0x00000050))
857 		hash_address.word.high |= 0x00000080;
858 	*sas_address = (u64)hash_address.wwid[0] << 56 |
859 	    (u64)hash_address.wwid[1] << 48 | (u64)hash_address.wwid[2] << 40 |
860 	    (u64)hash_address.wwid[3] << 32 | (u64)hash_address.wwid[4] << 24 |
861 	    (u64)hash_address.wwid[5] << 16 | (u64)hash_address.wwid[6] <<  8 |
862 	    (u64)hash_address.wwid[7];
863 	if (ata_identify.rotational_speed == 1) {
864 		*is_SATA_SSD = 1;
865 	}
866 
867 	return 0;
868 }
869 
870 static int
871 mpssas_get_sata_identify(struct mps_softc *sc, u16 handle,
872     Mpi2SataPassthroughReply_t *mpi_reply, char *id_buffer, int sz, u32 devinfo)
873 {
874 	Mpi2SataPassthroughRequest_t *mpi_request;
875 	Mpi2SataPassthroughReply_t *reply;
876 	struct mps_command *cm;
877 	char *buffer;
878 	int error = 0;
879 
880 	buffer = malloc( sz, M_MPT2, M_NOWAIT | M_ZERO);
881 	if (!buffer)
882 		return ENOMEM;
883 
884 	if ((cm = mps_alloc_command(sc)) == NULL) {
885 		free(buffer, M_MPT2);
886 		return (EBUSY);
887 	}
888 	mpi_request = (MPI2_SATA_PASSTHROUGH_REQUEST *)cm->cm_req;
889 	bzero(mpi_request,sizeof(MPI2_SATA_PASSTHROUGH_REQUEST));
890 	mpi_request->Function = MPI2_FUNCTION_SATA_PASSTHROUGH;
891 	mpi_request->VF_ID = 0;
892 	mpi_request->DevHandle = htole16(handle);
893 	mpi_request->PassthroughFlags = (MPI2_SATA_PT_REQ_PT_FLAGS_PIO |
894 	    MPI2_SATA_PT_REQ_PT_FLAGS_READ);
895 	mpi_request->DataLength = htole32(sz);
896 	mpi_request->CommandFIS[0] = 0x27;
897 	mpi_request->CommandFIS[1] = 0x80;
898 	mpi_request->CommandFIS[2] =  (devinfo &
899 	    MPI2_SAS_DEVICE_INFO_ATAPI_DEVICE) ? 0xA1 : 0xEC;
900 	cm->cm_sge = &mpi_request->SGL;
901 	cm->cm_sglsize = sizeof(MPI2_SGE_IO_UNION);
902 	cm->cm_flags = MPS_CM_FLAGS_SGE_SIMPLE | MPS_CM_FLAGS_DATAIN;
903 	cm->cm_desc.Default.RequestFlags = MPI2_REQ_DESCRIPT_FLAGS_DEFAULT_TYPE;
904 	cm->cm_data = buffer;
905 	cm->cm_length = htole32(sz);
906 
907 	/*
908 	 * Start a timeout counter specifically for the SATA ID command. This
909 	 * is used to fix a problem where the FW does not send a reply sometimes
910 	 * when a bad disk is in the topology. So, this is used to timeout the
911 	 * command so that processing can continue normally.
912 	 */
913 	mps_dprint(sc, MPS_XINFO, "%s start timeout counter for SATA ID "
914 	    "command\n", __func__);
915 	callout_reset(&cm->cm_callout, MPS_ATA_ID_TIMEOUT * hz,
916 	    mpssas_ata_id_timeout, cm);
917 	error = mps_wait_command(sc, cm, 60, CAN_SLEEP);
918 	mps_dprint(sc, MPS_XINFO, "%s stop timeout counter for SATA ID "
919 	    "command\n", __func__);
920 	callout_stop(&cm->cm_callout);
921 
922 	reply = (Mpi2SataPassthroughReply_t *)cm->cm_reply;
923 	if (error || (reply == NULL)) {
924 		/* FIXME */
925  		/*
926  		 * If the request returns an error then we need to do a diag
927  		 * reset
928  		 */
929  		printf("%s: request for page completed with error %d",
930 		    __func__, error);
931 		error = ENXIO;
932 		goto out;
933 	}
934 	bcopy(buffer, id_buffer, sz);
935 	bcopy(reply, mpi_reply, sizeof(Mpi2SataPassthroughReply_t));
936 	if ((le16toh(reply->IOCStatus) & MPI2_IOCSTATUS_MASK) !=
937 	    MPI2_IOCSTATUS_SUCCESS) {
938 		printf("%s: error reading SATA PASSTHRU; iocstatus = 0x%x\n",
939 		    __func__, reply->IOCStatus);
940 		error = ENXIO;
941 		goto out;
942 	}
943 out:
944 	/*
945 	 * If the SATA_ID_TIMEOUT flag has been set for this command, don't free
946 	 * it.  The command will be freed after sending a target reset TM. If
947 	 * the command did timeout, use EWOULDBLOCK.
948 	 */
949 	if ((cm->cm_flags & MPS_CM_FLAGS_SATA_ID_TIMEOUT) == 0)
950 		mps_free_command(sc, cm);
951 	else if (error == 0)
952 		error = EWOULDBLOCK;
953 	free(buffer, M_MPT2);
954 	return (error);
955 }
956 
957 static void
958 mpssas_ata_id_timeout(void *data)
959 {
960 	struct mps_softc *sc;
961 	struct mps_command *cm;
962 
963 	cm = (struct mps_command *)data;
964 	sc = cm->cm_sc;
965 	mtx_assert(&sc->mps_mtx, MA_OWNED);
966 
967 	mps_dprint(sc, MPS_INFO, "%s checking ATA ID command %p sc %p\n",
968 	    __func__, cm, sc);
969 	if ((callout_pending(&cm->cm_callout)) ||
970 	    (!callout_active(&cm->cm_callout))) {
971 		mps_dprint(sc, MPS_INFO, "%s ATA ID command almost timed out\n",
972 		    __func__);
973 		return;
974 	}
975 	callout_deactivate(&cm->cm_callout);
976 
977 	/*
978 	 * Run the interrupt handler to make sure it's not pending.  This
979 	 * isn't perfect because the command could have already completed
980 	 * and been re-used, though this is unlikely.
981 	 */
982 	mps_intr_locked(sc);
983 	if (cm->cm_state == MPS_CM_STATE_FREE) {
984 		mps_dprint(sc, MPS_INFO, "%s ATA ID command almost timed out\n",
985 		    __func__);
986 		return;
987 	}
988 
989 	mps_dprint(sc, MPS_INFO, "ATA ID command timeout cm %p\n", cm);
990 
991 	/*
992 	 * Send wakeup() to the sleeping thread that issued this ATA ID command.
993 	 * wakeup() will cause msleep to return a 0 (not EWOULDBLOCK), and this
994 	 * will keep reinit() from being called. This way, an Abort Task TM can
995 	 * be issued so that the timed out command can be cleared.  The Abort
996 	 * Task cannot be sent from here because the driver has not completed
997 	 * setting up targets.  Instead, the command is flagged so that special
998 	 * handling will be used to send the abort.
999 	 */
1000 	cm->cm_flags |= MPS_CM_FLAGS_SATA_ID_TIMEOUT;
1001 	wakeup(cm);
1002 }
1003 
1004 static int
1005 mpssas_volume_add(struct mps_softc *sc, u16 handle)
1006 {
1007 	struct mpssas_softc *sassc;
1008 	struct mpssas_target *targ;
1009 	u64 wwid;
1010 	unsigned int id;
1011 	int error = 0;
1012 	struct mpssas_lun *lun;
1013 
1014 	sassc = sc->sassc;
1015 	mpssas_startup_increment(sassc);
1016 	/* wwid is endian safe */
1017 	mps_config_get_volume_wwid(sc, handle, &wwid);
1018 	if (!wwid) {
1019 		printf("%s: invalid WWID; cannot add volume to mapping table\n",
1020 		    __func__);
1021 		error = ENXIO;
1022 		goto out;
1023 	}
1024 
1025 	id = mps_mapping_get_raid_id(sc, wwid, handle);
1026 	if (id == MPS_MAP_BAD_ID) {
1027 		printf("%s: could not get ID for volume with handle 0x%04x and "
1028 		    "WWID 0x%016llx\n", __func__, handle,
1029 		    (unsigned long long)wwid);
1030 		error = ENXIO;
1031 		goto out;
1032 	}
1033 
1034 	targ = &sassc->targets[id];
1035 	targ->tid = id;
1036 	targ->handle = handle;
1037 	targ->devname = wwid;
1038 	TAILQ_INIT(&targ->commands);
1039 	TAILQ_INIT(&targ->timedout_commands);
1040 	while(!SLIST_EMPTY(&targ->luns)) {
1041 		lun = SLIST_FIRST(&targ->luns);
1042 		SLIST_REMOVE_HEAD(&targ->luns, lun_link);
1043 		free(lun, M_MPT2);
1044 	}
1045 	SLIST_INIT(&targ->luns);
1046 #if __FreeBSD_version < 1000039
1047 	if ((sassc->flags & MPSSAS_IN_STARTUP) == 0)
1048 #endif
1049 		mpssas_rescan_target(sc, targ);
1050 	mps_dprint(sc, MPS_MAPPING, "RAID target id %d added (WWID = 0x%jx)\n",
1051 	    targ->tid, wwid);
1052 out:
1053 	mpssas_startup_decrement(sassc);
1054 	return (error);
1055 }
1056 
1057 /**
1058  * mpssas_SSU_to_SATA_devices
1059  * @sc: per adapter object
1060  *
1061  * Looks through the target list and issues a StartStopUnit SCSI command to each
1062  * SATA direct-access device.  This helps to ensure that data corruption is
1063  * avoided when the system is being shut down.  This must be called after the IR
1064  * System Shutdown RAID Action is sent if in IR mode.
1065  *
1066  * Return nothing.
1067  */
1068 static void
1069 mpssas_SSU_to_SATA_devices(struct mps_softc *sc)
1070 {
1071 	struct mpssas_softc *sassc = sc->sassc;
1072 	union ccb *ccb;
1073 	path_id_t pathid = cam_sim_path(sassc->sim);
1074 	target_id_t targetid;
1075 	struct mpssas_target *target;
1076 	char path_str[64];
1077 	struct timeval cur_time, start_time;
1078 
1079 	/*
1080 	 * For each target, issue a StartStopUnit command to stop the device.
1081 	 */
1082 	sc->SSU_started = TRUE;
1083 	sc->SSU_refcount = 0;
1084 	for (targetid = 0; targetid < sc->facts->MaxTargets; targetid++) {
1085 		target = &sassc->targets[targetid];
1086 		if (target->handle == 0x0) {
1087 			continue;
1088 		}
1089 
1090 		ccb = xpt_alloc_ccb_nowait();
1091 		if (ccb == NULL) {
1092 			mps_dprint(sc, MPS_FAULT, "Unable to alloc CCB to stop "
1093 			    "unit.\n");
1094 			return;
1095 		}
1096 
1097 		/*
1098 		 * The stop_at_shutdown flag will be set if this device is
1099 		 * a SATA direct-access end device.
1100 		 */
1101 		if (target->stop_at_shutdown) {
1102 			if (xpt_create_path(&ccb->ccb_h.path,
1103 			    xpt_periph, pathid, targetid,
1104 			    CAM_LUN_WILDCARD) != CAM_REQ_CMP) {
1105 				mps_dprint(sc, MPS_FAULT, "Unable to create "
1106 				    "LUN path to stop unit.\n");
1107 				xpt_free_ccb(ccb);
1108 				return;
1109 			}
1110 			xpt_path_string(ccb->ccb_h.path, path_str,
1111 			    sizeof(path_str));
1112 
1113 			mps_dprint(sc, MPS_INFO, "Sending StopUnit: path %s "
1114 			    "handle %d\n", path_str, target->handle);
1115 
1116 			/*
1117 			 * Issue a START STOP UNIT command for the target.
1118 			 * Increment the SSU counter to be used to count the
1119 			 * number of required replies.
1120 			 */
1121 			mps_dprint(sc, MPS_INFO, "Incrementing SSU count\n");
1122 			sc->SSU_refcount++;
1123 			ccb->ccb_h.target_id =
1124 			    xpt_path_target_id(ccb->ccb_h.path);
1125 			ccb->ccb_h.ppriv_ptr1 = sassc;
1126 			scsi_start_stop(&ccb->csio,
1127 			    /*retries*/0,
1128 			    mpssas_stop_unit_done,
1129 			    MSG_SIMPLE_Q_TAG,
1130 			    /*start*/FALSE,
1131 			    /*load/eject*/0,
1132 			    /*immediate*/FALSE,
1133 			    MPS_SENSE_LEN,
1134 			    /*timeout*/10000);
1135 			xpt_action(ccb);
1136 		}
1137 	}
1138 
1139 	/*
1140 	 * Wait until all of the SSU commands have completed or time has
1141 	 * expired (60 seconds).  Pause for 100ms each time through.  If any
1142 	 * command times out, the target will be reset in the SCSI command
1143 	 * timeout routine.
1144 	 */
1145 	getmicrotime(&start_time);
1146 	while (sc->SSU_refcount) {
1147 		pause("mpswait", hz/10);
1148 
1149 		getmicrotime(&cur_time);
1150 		if ((cur_time.tv_sec - start_time.tv_sec) > 60) {
1151 			mps_dprint(sc, MPS_FAULT, "Time has expired waiting "
1152 			    "for SSU commands to complete.\n");
1153 			break;
1154 		}
1155 	}
1156 }
1157 
1158 static void
1159 mpssas_stop_unit_done(struct cam_periph *periph, union ccb *done_ccb)
1160 {
1161 	struct mpssas_softc *sassc;
1162 	char path_str[64];
1163 
1164 	sassc = (struct mpssas_softc *)done_ccb->ccb_h.ppriv_ptr1;
1165 
1166 	xpt_path_string(done_ccb->ccb_h.path, path_str, sizeof(path_str));
1167 	mps_dprint(sassc->sc, MPS_INFO, "Completing stop unit for %s\n",
1168 	    path_str);
1169 
1170 	if (done_ccb == NULL)
1171 		return;
1172 
1173 	/*
1174 	 * Nothing more to do except free the CCB and path.  If the command
1175 	 * timed out, an abort reset, then target reset will be issued during
1176 	 * the SCSI Command process.
1177 	 */
1178 	xpt_free_path(done_ccb->ccb_h.path);
1179 	xpt_free_ccb(done_ccb);
1180 }
1181 
1182 /**
1183  * mpssas_ir_shutdown - IR shutdown notification
1184  * @sc: per adapter object
1185  *
1186  * Sending RAID Action to alert the Integrated RAID subsystem of the IOC that
1187  * the host system is shutting down.
1188  *
1189  * Return nothing.
1190  */
1191 void
1192 mpssas_ir_shutdown(struct mps_softc *sc)
1193 {
1194 	u16 volume_mapping_flags;
1195 	u16 ioc_pg8_flags = le16toh(sc->ioc_pg8.Flags);
1196 	struct dev_mapping_table *mt_entry;
1197 	u32 start_idx, end_idx;
1198 	unsigned int id, found_volume = 0;
1199 	struct mps_command *cm;
1200 	Mpi2RaidActionRequest_t	*action;
1201 	target_id_t targetid;
1202 	struct mpssas_target *target;
1203 
1204 	mps_dprint(sc, MPS_TRACE, "%s\n", __func__);
1205 
1206 	/* is IR firmware build loaded? */
1207 	if (!sc->ir_firmware)
1208 		goto out;
1209 
1210 	/* are there any volumes?  Look at IR target IDs. */
1211 	// TODO-later, this should be looked up in the RAID config structure
1212 	// when it is implemented.
1213 	volume_mapping_flags = le16toh(sc->ioc_pg8.IRVolumeMappingFlags) &
1214 	    MPI2_IOCPAGE8_IRFLAGS_MASK_VOLUME_MAPPING_MODE;
1215 	if (volume_mapping_flags == MPI2_IOCPAGE8_IRFLAGS_LOW_VOLUME_MAPPING) {
1216 		start_idx = 0;
1217 		if (ioc_pg8_flags & MPI2_IOCPAGE8_FLAGS_RESERVED_TARGETID_0)
1218 			start_idx = 1;
1219 	} else
1220 		start_idx = sc->max_devices - sc->max_volumes;
1221 	end_idx = start_idx + sc->max_volumes - 1;
1222 
1223 	for (id = start_idx; id < end_idx; id++) {
1224 		mt_entry = &sc->mapping_table[id];
1225 		if ((mt_entry->physical_id != 0) &&
1226 		    (mt_entry->missing_count == 0)) {
1227 			found_volume = 1;
1228 			break;
1229 		}
1230 	}
1231 
1232 	if (!found_volume)
1233 		goto out;
1234 
1235 	if ((cm = mps_alloc_command(sc)) == NULL) {
1236 		printf("%s: command alloc failed\n", __func__);
1237 		goto out;
1238 	}
1239 
1240 	action = (MPI2_RAID_ACTION_REQUEST *)cm->cm_req;
1241 	action->Function = MPI2_FUNCTION_RAID_ACTION;
1242 	action->Action = MPI2_RAID_ACTION_SYSTEM_SHUTDOWN_INITIATED;
1243 	cm->cm_desc.Default.RequestFlags = MPI2_REQ_DESCRIPT_FLAGS_DEFAULT_TYPE;
1244 	mps_lock(sc);
1245 	mps_wait_command(sc, cm, 5, CAN_SLEEP);
1246 	mps_unlock(sc);
1247 
1248 	/*
1249 	 * Don't check for reply, just leave.
1250 	 */
1251 	if (cm)
1252 		mps_free_command(sc, cm);
1253 
1254 out:
1255 	/*
1256 	 * All of the targets must have the correct value set for
1257 	 * 'stop_at_shutdown' for the current 'enable_ssu' sysctl variable.
1258 	 *
1259 	 * The possible values for the 'enable_ssu' variable are:
1260 	 * 0: disable to SSD and HDD
1261 	 * 1: disable only to HDD (default)
1262 	 * 2: disable only to SSD
1263 	 * 3: enable to SSD and HDD
1264 	 * anything else will default to 1.
1265 	 */
1266 	for (targetid = 0; targetid < sc->facts->MaxTargets; targetid++) {
1267 		target = &sc->sassc->targets[targetid];
1268 		if (target->handle == 0x0) {
1269 			continue;
1270 		}
1271 
1272 		if (target->supports_SSU) {
1273 			switch (sc->enable_ssu) {
1274 			case MPS_SSU_DISABLE_SSD_DISABLE_HDD:
1275 				target->stop_at_shutdown = FALSE;
1276 				break;
1277 			case MPS_SSU_DISABLE_SSD_ENABLE_HDD:
1278 				target->stop_at_shutdown = TRUE;
1279 				if (target->flags & MPS_TARGET_IS_SATA_SSD) {
1280 					target->stop_at_shutdown = FALSE;
1281 				}
1282 				break;
1283 			case MPS_SSU_ENABLE_SSD_ENABLE_HDD:
1284 				target->stop_at_shutdown = TRUE;
1285 				break;
1286 			case MPS_SSU_ENABLE_SSD_DISABLE_HDD:
1287 			default:
1288 				target->stop_at_shutdown = TRUE;
1289 				if ((target->flags &
1290 				    MPS_TARGET_IS_SATA_SSD) == 0) {
1291 					target->stop_at_shutdown = FALSE;
1292 				}
1293 				break;
1294 			}
1295 		}
1296 	}
1297 	mpssas_SSU_to_SATA_devices(sc);
1298 }
1299