xref: /freebsd/sys/dev/mpr/mpr_sas_lsi.c (revision 49b49cda41feabe3439f7318e8bf40e3896c7bf4)
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 LSI MPT3 */
34 
35 /* TODO Move headers to mprvar */
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/mpr/mpi/mpi2_type.h>
71 #include <dev/mpr/mpi/mpi2.h>
72 #include <dev/mpr/mpi/mpi2_ioc.h>
73 #include <dev/mpr/mpi/mpi2_sas.h>
74 #include <dev/mpr/mpi/mpi2_cnfg.h>
75 #include <dev/mpr/mpi/mpi2_init.h>
76 #include <dev/mpr/mpi/mpi2_raid.h>
77 #include <dev/mpr/mpi/mpi2_tool.h>
78 #include <dev/mpr/mpr_ioctl.h>
79 #include <dev/mpr/mprvar.h>
80 #include <dev/mpr/mpr_table.h>
81 #include <dev/mpr/mpr_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 mpr_fw_event_work {
88 	u16			event;
89 	void			*event_data;
90 	TAILQ_ENTRY(mpr_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 mprsas_fw_work(struct mpr_softc *sc,
115     struct mpr_fw_event_work *fw_event);
116 static void mprsas_fw_event_free(struct mpr_softc *,
117     struct mpr_fw_event_work *);
118 static int mprsas_add_device(struct mpr_softc *sc, u16 handle, u8 linkrate);
119 static int mprsas_get_sata_identify(struct mpr_softc *sc, u16 handle,
120     Mpi2SataPassthroughReply_t *mpi_reply, char *id_buffer, int sz,
121     u32 devinfo);
122 static void mprsas_ata_id_timeout(void *data);
123 int mprsas_get_sas_address_for_sata_disk(struct mpr_softc *sc,
124     u64 *sas_address, u16 handle, u32 device_info, u8 *is_SATA_SSD);
125 static int mprsas_volume_add(struct mpr_softc *sc,
126     u16 handle);
127 static void mprsas_SSU_to_SATA_devices(struct mpr_softc *sc);
128 static void mprsas_stop_unit_done(struct cam_periph *periph,
129     union ccb *done_ccb);
130 
131 void
132 mprsas_evt_handler(struct mpr_softc *sc, uintptr_t data,
133     MPI2_EVENT_NOTIFICATION_REPLY *event)
134 {
135 	struct mpr_fw_event_work *fw_event;
136 	u16 sz;
137 
138 	mpr_dprint(sc, MPR_TRACE, "%s\n", __func__);
139 	mpr_print_evt_sas(sc, event);
140 	mprsas_record_event(sc, event);
141 
142 	fw_event = malloc(sizeof(struct mpr_fw_event_work), M_MPR,
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_MPR, 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_MPR);
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 		mprsas_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 mprsas_fw_event_free(struct mpr_softc *sc, struct mpr_fw_event_work *fw_event)
181 {
182 
183 	free(fw_event->event_data, M_MPR);
184 	free(fw_event, M_MPR);
185 }
186 
187 /**
188  * _mpr_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 mprsas_fw_work(struct mpr_softc *sc, struct mpr_fw_event_work *fw_event)
197 {
198 	struct mprsas_softc *sassc;
199 	sassc = sc->sassc;
200 
201 	mpr_dprint(sc, MPR_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 		mpr_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 (mprsas_add_device(sc,
220 				    le16toh(phy->AttachedDevHandle),
221 				    phy->LinkRate)) {
222 					printf("%s: failed to add device with "
223 					    "handle 0x%x\n", __func__,
224 					    le16toh(phy->AttachedDevHandle));
225 					mprsas_prepare_remove(sassc, le16toh(
226 					    phy->AttachedDevHandle));
227 				}
228 				break;
229 			case MPI2_EVENT_SAS_TOPO_RC_TARG_NOT_RESPONDING:
230 				mprsas_prepare_remove(sassc, le16toh(
231 				    phy->AttachedDevHandle));
232 				break;
233 			case MPI2_EVENT_SAS_TOPO_RC_PHY_CHANGED:
234 			case MPI2_EVENT_SAS_TOPO_RC_NO_CHANGE:
235 			case MPI2_EVENT_SAS_TOPO_RC_DELAY_NOT_RESPONDING:
236 			default:
237 				break;
238 			}
239 		}
240 		/*
241 		 * refcount was incremented for this event in
242 		 * mprsas_evt_handler.  Decrement it here because the event has
243 		 * been processed.
244 		 */
245 		mprsas_startup_decrement(sassc);
246 		break;
247 	}
248 	case MPI2_EVENT_SAS_DISCOVERY:
249 	{
250 		MPI2_EVENT_DATA_SAS_DISCOVERY *data;
251 
252 		data = (MPI2_EVENT_DATA_SAS_DISCOVERY *)fw_event->event_data;
253 
254 		if (data->ReasonCode & MPI2_EVENT_SAS_DISC_RC_STARTED)
255 			mpr_dprint(sc, MPR_TRACE,"SAS discovery start "
256 			    "event\n");
257 		if (data->ReasonCode & MPI2_EVENT_SAS_DISC_RC_COMPLETED) {
258 			mpr_dprint(sc, MPR_TRACE,"SAS discovery stop event\n");
259 			sassc->flags &= ~MPRSAS_IN_DISCOVERY;
260 			mprsas_discovery_end(sassc);
261 		}
262 		break;
263 	}
264 	case MPI2_EVENT_SAS_ENCL_DEVICE_STATUS_CHANGE:
265 	{
266 		Mpi2EventDataSasEnclDevStatusChange_t *data;
267 		data = (Mpi2EventDataSasEnclDevStatusChange_t *)
268 		    fw_event->event_data;
269 		mpr_mapping_enclosure_dev_status_change_event(sc,
270 		    fw_event->event_data);
271 		break;
272 	}
273 	case MPI2_EVENT_IR_CONFIGURATION_CHANGE_LIST:
274 	{
275 		Mpi2EventIrConfigElement_t *element;
276 		int i;
277 		u8 foreign_config, reason;
278 		u16 elementType;
279 		Mpi2EventDataIrConfigChangeList_t *event_data;
280 		struct mprsas_target *targ;
281 		unsigned int id;
282 
283 		event_data = fw_event->event_data;
284 		foreign_config = (le32toh(event_data->Flags) &
285 		    MPI2_EVENT_IR_CHANGE_FLAGS_FOREIGN_CONFIG) ? 1 : 0;
286 
287 		element =
288 		    (Mpi2EventIrConfigElement_t *)&event_data->ConfigElement[0];
289 		id = mpr_mapping_get_raid_id_from_handle(sc,
290 		    element->VolDevHandle);
291 
292 		mpr_mapping_ir_config_change_event(sc, event_data);
293 		for (i = 0; i < event_data->NumElements; i++, element++) {
294 			reason = element->ReasonCode;
295 			elementType = le16toh(element->ElementFlags) &
296 			    MPI2_EVENT_IR_CHANGE_EFLAGS_ELEMENT_TYPE_MASK;
297 			/*
298 			 * check for element type of Phys Disk or Hot Spare
299 			 */
300 			if ((elementType !=
301 			    MPI2_EVENT_IR_CHANGE_EFLAGS_VOLPHYSDISK_ELEMENT)
302 			    && (elementType !=
303 			    MPI2_EVENT_IR_CHANGE_EFLAGS_HOTSPARE_ELEMENT))
304 				// do next element
305 				goto skip_fp_send;
306 
307 			/*
308 			 * check for reason of Hide, Unhide, PD Created, or PD
309 			 * Deleted
310 			 */
311 			if ((reason != MPI2_EVENT_IR_CHANGE_RC_HIDE) &&
312 			    (reason != MPI2_EVENT_IR_CHANGE_RC_UNHIDE) &&
313 			    (reason != MPI2_EVENT_IR_CHANGE_RC_PD_CREATED) &&
314 			    (reason != MPI2_EVENT_IR_CHANGE_RC_PD_DELETED))
315 				goto skip_fp_send;
316 
317 			// check for a reason of Hide or PD Created
318 			if ((reason == MPI2_EVENT_IR_CHANGE_RC_HIDE) ||
319 			    (reason == MPI2_EVENT_IR_CHANGE_RC_PD_CREATED))
320 			{
321 				// build RAID Action message
322 				Mpi2RaidActionRequest_t	*action;
323 				Mpi2RaidActionReply_t *reply;
324 				struct mpr_command *cm;
325 				int error = 0;
326 				if ((cm = mpr_alloc_command(sc)) == NULL) {
327 					printf("%s: command alloc failed\n",
328 					    __func__);
329 					return;
330 				}
331 
332 				mpr_dprint(sc, MPR_EVENT, "Sending FP action "
333 				    "from "
334 				    "MPI2_EVENT_IR_CONFIGURATION_CHANGE_LIST "
335 				    ":\n");
336 				action = (MPI2_RAID_ACTION_REQUEST *)cm->cm_req;
337 				action->Function = MPI2_FUNCTION_RAID_ACTION;
338 				action->Action =
339 				    MPI2_RAID_ACTION_PHYSDISK_HIDDEN;
340 				action->PhysDiskNum = element->PhysDiskNum;
341 				cm->cm_desc.Default.RequestFlags =
342 				    MPI2_REQ_DESCRIPT_FLAGS_DEFAULT_TYPE;
343 				error = mpr_request_polled(sc, cm);
344 				reply = (Mpi2RaidActionReply_t *)cm->cm_reply;
345 				if (error || (reply == NULL)) {
346 					/* FIXME */
347 					/*
348 					 * If the poll returns error then we
349 					 * need to do diag reset
350 					 */
351 					printf("%s: poll for page completed "
352 					    "with error %d", __func__, error);
353 				}
354 				if (reply && (le16toh(reply->IOCStatus) &
355 				    MPI2_IOCSTATUS_MASK) !=
356 				    MPI2_IOCSTATUS_SUCCESS) {
357 					mpr_dprint(sc, MPR_ERROR, "%s: error "
358 					    "sending RaidActionPage; "
359 					    "iocstatus = 0x%x\n", __func__,
360 					    le16toh(reply->IOCStatus));
361 				}
362 
363 				if (cm)
364 					mpr_free_command(sc, cm);
365 			}
366 skip_fp_send:
367 			mpr_dprint(sc, MPR_EVENT, "Received "
368 			    "MPI2_EVENT_IR_CONFIGURATION_CHANGE_LIST Reason "
369 			    "code %x:\n", element->ReasonCode);
370 			switch (element->ReasonCode) {
371 			case MPI2_EVENT_IR_CHANGE_RC_VOLUME_CREATED:
372 			case MPI2_EVENT_IR_CHANGE_RC_ADDED:
373 				if (!foreign_config) {
374 					if (mprsas_volume_add(sc,
375 					    le16toh(element->VolDevHandle))) {
376 						printf("%s: failed to add RAID "
377 						    "volume with handle 0x%x\n",
378 						    __func__, le16toh(element->
379 						    VolDevHandle));
380 					}
381 				}
382 				break;
383 			case MPI2_EVENT_IR_CHANGE_RC_VOLUME_DELETED:
384 			case MPI2_EVENT_IR_CHANGE_RC_REMOVED:
385 				/*
386 				 * Rescan after volume is deleted or removed.
387 				 */
388 				if (!foreign_config) {
389 					if (id == MPR_MAP_BAD_ID) {
390 						printf("%s: could not get ID "
391 						    "for volume with handle "
392 						    "0x%04x\n", __func__,
393 						    le16toh(element->
394 						    VolDevHandle));
395 						break;
396 					}
397 
398 					targ = &sassc->targets[id];
399 					targ->handle = 0x0;
400 					targ->encl_slot = 0x0;
401 					targ->encl_handle = 0x0;
402 					targ->encl_level_valid = 0x0;
403 					targ->encl_level = 0x0;
404 					targ->connector_name[0] = ' ';
405 					targ->connector_name[1] = ' ';
406 					targ->connector_name[2] = ' ';
407 					targ->connector_name[3] = ' ';
408 					targ->exp_dev_handle = 0x0;
409 					targ->phy_num = 0x0;
410 					targ->linkrate = 0x0;
411 					mprsas_rescan_target(sc, targ);
412 					printf("RAID target id 0x%x removed\n",
413 					    targ->tid);
414 				}
415 				break;
416 			case MPI2_EVENT_IR_CHANGE_RC_PD_CREATED:
417 			case MPI2_EVENT_IR_CHANGE_RC_HIDE:
418 				/*
419 				 * Phys Disk of a volume has been created.  Hide
420 				 * it from the OS.
421 				 */
422 				targ = mprsas_find_target_by_handle(sassc, 0,
423 				    element->PhysDiskDevHandle);
424 				if (targ == NULL)
425 					break;
426 				targ->flags |= MPR_TARGET_FLAGS_RAID_COMPONENT;
427 				mprsas_rescan_target(sc, targ);
428 				break;
429 			case MPI2_EVENT_IR_CHANGE_RC_PD_DELETED:
430 				/*
431 				 * Phys Disk of a volume has been deleted.
432 				 * Expose it to the OS.
433 				 */
434 				if (mprsas_add_device(sc,
435 				    le16toh(element->PhysDiskDevHandle), 0)) {
436 					printf("%s: failed to add device with "
437 					    "handle 0x%x\n", __func__,
438 					    le16toh(element->
439 					    PhysDiskDevHandle));
440 					mprsas_prepare_remove(sassc,
441 					    le16toh(element->
442 					    PhysDiskDevHandle));
443 				}
444 				break;
445 			}
446 		}
447 		/*
448 		 * refcount was incremented for this event in
449 		 * mprsas_evt_handler.  Decrement it here because the event has
450 		 * been processed.
451 		 */
452 		mprsas_startup_decrement(sassc);
453 		break;
454 	}
455 	case MPI2_EVENT_IR_VOLUME:
456 	{
457 		Mpi2EventDataIrVolume_t *event_data = fw_event->event_data;
458 
459 		/*
460 		 * Informational only.
461 		 */
462 		mpr_dprint(sc, MPR_EVENT, "Received IR Volume event:\n");
463 		switch (event_data->ReasonCode) {
464 		case MPI2_EVENT_IR_VOLUME_RC_SETTINGS_CHANGED:
465   			mpr_dprint(sc, MPR_EVENT, "   Volume Settings "
466   			    "changed from 0x%x to 0x%x for Volome with "
467  			    "handle 0x%x", le32toh(event_data->PreviousValue),
468  			    le32toh(event_data->NewValue),
469  			    le16toh(event_data->VolDevHandle));
470 			break;
471 		case MPI2_EVENT_IR_VOLUME_RC_STATUS_FLAGS_CHANGED:
472   			mpr_dprint(sc, MPR_EVENT, "   Volume Status "
473   			    "changed from 0x%x to 0x%x for Volome with "
474  			    "handle 0x%x", le32toh(event_data->PreviousValue),
475  			    le32toh(event_data->NewValue),
476  			    le16toh(event_data->VolDevHandle));
477 			break;
478 		case MPI2_EVENT_IR_VOLUME_RC_STATE_CHANGED:
479   			mpr_dprint(sc, MPR_EVENT, "   Volume State "
480   			    "changed from 0x%x to 0x%x for Volome with "
481  			    "handle 0x%x", le32toh(event_data->PreviousValue),
482  			    le32toh(event_data->NewValue),
483  			    le16toh(event_data->VolDevHandle));
484 				u32 state;
485 				struct mprsas_target *targ;
486 				state = le32toh(event_data->NewValue);
487 				switch (state) {
488 				case MPI2_RAID_VOL_STATE_MISSING:
489 				case MPI2_RAID_VOL_STATE_FAILED:
490 					mprsas_prepare_volume_remove(sassc,
491 					    event_data->VolDevHandle);
492 					break;
493 
494 				case MPI2_RAID_VOL_STATE_ONLINE:
495 				case MPI2_RAID_VOL_STATE_DEGRADED:
496 				case MPI2_RAID_VOL_STATE_OPTIMAL:
497 					targ =
498 					    mprsas_find_target_by_handle(sassc,
499 					    0, event_data->VolDevHandle);
500 					if (targ) {
501 						printf("%s %d: Volume handle "
502 						    "0x%x is already added \n",
503 						    __func__, __LINE__,
504 						    event_data->VolDevHandle);
505 						break;
506 					}
507 					if (mprsas_volume_add(sc,
508 					    le16toh(event_data->
509 					    VolDevHandle))) {
510 						printf("%s: failed to add RAID "
511 						    "volume with handle 0x%x\n",
512 						    __func__, le16toh(
513 						    event_data->VolDevHandle));
514 					}
515 					break;
516 				default:
517 					break;
518 				}
519 			break;
520 		default:
521 			break;
522 		}
523 		break;
524 	}
525 	case MPI2_EVENT_IR_PHYSICAL_DISK:
526 	{
527 		Mpi2EventDataIrPhysicalDisk_t *event_data =
528 		    fw_event->event_data;
529 		struct mprsas_target *targ;
530 
531 		/*
532 		 * Informational only.
533 		 */
534 		mpr_dprint(sc, MPR_EVENT, "Received IR Phys Disk event:\n");
535 		switch (event_data->ReasonCode) {
536 		case MPI2_EVENT_IR_PHYSDISK_RC_SETTINGS_CHANGED:
537   			mpr_dprint(sc, MPR_EVENT, "   Phys Disk Settings "
538   			    "changed from 0x%x to 0x%x for Phys Disk Number "
539   			    "%d and handle 0x%x at Enclosure handle 0x%x, Slot "
540  			    "%d", le32toh(event_data->PreviousValue),
541  			    le32toh(event_data->NewValue),
542 			    event_data->PhysDiskNum,
543  			    le16toh(event_data->PhysDiskDevHandle),
544  			    le16toh(event_data->EnclosureHandle),
545 			    le16toh(event_data->Slot));
546 			break;
547 		case MPI2_EVENT_IR_PHYSDISK_RC_STATUS_FLAGS_CHANGED:
548   			mpr_dprint(sc, MPR_EVENT, "   Phys Disk Status changed "
549   			    "from 0x%x to 0x%x for Phys Disk Number %d and "
550   			    "handle 0x%x at Enclosure handle 0x%x, Slot %d",
551  			    le32toh(event_data->PreviousValue),
552  			    le32toh(event_data->NewValue),
553 			    event_data->PhysDiskNum,
554  			    le16toh(event_data->PhysDiskDevHandle),
555  			    le16toh(event_data->EnclosureHandle),
556 			    le16toh(event_data->Slot));
557 			break;
558 		case MPI2_EVENT_IR_PHYSDISK_RC_STATE_CHANGED:
559   			mpr_dprint(sc, MPR_EVENT, "   Phys Disk State changed "
560   			    "from 0x%x to 0x%x for Phys Disk Number %d and "
561   			    "handle 0x%x at Enclosure handle 0x%x, Slot %d",
562  			    le32toh(event_data->PreviousValue),
563  			    le32toh(event_data->NewValue),
564 			    event_data->PhysDiskNum,
565  			    le16toh(event_data->PhysDiskDevHandle),
566  			    le16toh(event_data->EnclosureHandle),
567 			    le16toh(event_data->Slot));
568 			switch (event_data->NewValue) {
569 				case MPI2_RAID_PD_STATE_ONLINE:
570 				case MPI2_RAID_PD_STATE_DEGRADED:
571 				case MPI2_RAID_PD_STATE_REBUILDING:
572 				case MPI2_RAID_PD_STATE_OPTIMAL:
573 				case MPI2_RAID_PD_STATE_HOT_SPARE:
574 					targ = mprsas_find_target_by_handle(
575 					    sassc, 0,
576 					    event_data->PhysDiskDevHandle);
577 					if (targ) {
578 						targ->flags |=
579 						    MPR_TARGET_FLAGS_RAID_COMPONENT;
580 						printf("%s %d: Found Target "
581 						    "for handle 0x%x.\n",
582 						    __func__, __LINE__ ,
583 						    event_data->
584 						    PhysDiskDevHandle);
585 					}
586 				break;
587 				case MPI2_RAID_PD_STATE_OFFLINE:
588 				case MPI2_RAID_PD_STATE_NOT_CONFIGURED:
589 				case MPI2_RAID_PD_STATE_NOT_COMPATIBLE:
590 				default:
591 					targ = mprsas_find_target_by_handle(
592 					    sassc, 0,
593 					    event_data->PhysDiskDevHandle);
594 					if (targ) {
595 						targ->flags |=
596 					    ~MPR_TARGET_FLAGS_RAID_COMPONENT;
597 						printf("%s %d: Found Target "
598 						    "for handle 0x%x.  \n",
599 						    __func__, __LINE__ ,
600 						    event_data->
601 						    PhysDiskDevHandle);
602 					}
603 				break;
604 			}
605 		default:
606 			break;
607 		}
608 		break;
609 	}
610 	case MPI2_EVENT_IR_OPERATION_STATUS:
611 	{
612 		Mpi2EventDataIrOperationStatus_t *event_data =
613 		    fw_event->event_data;
614 
615 		/*
616 		 * Informational only.
617 		 */
618 		mpr_dprint(sc, MPR_EVENT, "Received IR Op Status event:\n");
619 		mpr_dprint(sc, MPR_EVENT, "   RAID Operation of %d is %d "
620 		    "percent complete for Volume with handle 0x%x",
621 		    event_data->RAIDOperation, event_data->PercentComplete,
622 		    le16toh(event_data->VolDevHandle));
623 		break;
624 	}
625 	case MPI2_EVENT_TEMP_THRESHOLD:
626 	{
627 		pMpi2EventDataTemperature_t	temp_event;
628 
629 		temp_event = (pMpi2EventDataTemperature_t)fw_event->event_data;
630 
631 		/*
632 		 * The Temp Sensor Count must be greater than the event's Sensor
633 		 * Num to be valid.  If valid, print the temp thresholds that
634 		 * have been exceeded.
635 		 */
636 		if (sc->iounit_pg8.NumSensors > temp_event->SensorNum) {
637 			mpr_dprint(sc, MPR_FAULT, "Temperature Threshold flags "
638 			    "%s %s %s %s exceeded for Sensor: %d !!!\n",
639 			    ((temp_event->Status & 0x01) == 1) ? "0 " : " ",
640 			    ((temp_event->Status & 0x02) == 2) ? "1 " : " ",
641 			    ((temp_event->Status & 0x04) == 4) ? "2 " : " ",
642 			    ((temp_event->Status & 0x08) == 8) ? "3 " : " ",
643 			    temp_event->SensorNum);
644 			mpr_dprint(sc, MPR_FAULT, "Current Temp in Celsius: "
645 			    "%d\n", temp_event->CurrentTemperature);
646 		}
647 		break;
648 	}
649 	case MPI2_EVENT_SAS_DEVICE_STATUS_CHANGE:
650 	case MPI2_EVENT_SAS_BROADCAST_PRIMITIVE:
651 	default:
652 		mpr_dprint(sc, MPR_TRACE,"Unhandled event 0x%0X\n",
653 		    fw_event->event);
654 		break;
655 
656 	}
657 	mpr_dprint(sc, MPR_EVENT, "(%d)->(%s) Event Free: [%x]\n", event_count,
658 	    __func__, fw_event->event);
659 	mprsas_fw_event_free(sc, fw_event);
660 }
661 
662 void
663 mprsas_firmware_event_work(void *arg, int pending)
664 {
665 	struct mpr_fw_event_work *fw_event;
666 	struct mpr_softc *sc;
667 
668 	sc = (struct mpr_softc *)arg;
669 	mpr_lock(sc);
670 	while ((fw_event = TAILQ_FIRST(&sc->sassc->ev_queue)) != NULL) {
671 		TAILQ_REMOVE(&sc->sassc->ev_queue, fw_event, ev_link);
672 		mprsas_fw_work(sc, fw_event);
673 	}
674 	mpr_unlock(sc);
675 }
676 
677 static int
678 mprsas_add_device(struct mpr_softc *sc, u16 handle, u8 linkrate){
679 	char devstring[80];
680 	struct mprsas_softc *sassc;
681 	struct mprsas_target *targ;
682 	Mpi2ConfigReply_t mpi_reply;
683 	Mpi2SasDevicePage0_t config_page;
684 	uint64_t sas_address, parent_sas_address = 0;
685 	u32 device_info, parent_devinfo = 0;
686 	unsigned int id;
687 	int ret = 1, error = 0, i;
688 	struct mprsas_lun *lun;
689 	u8 is_SATA_SSD = 0;
690 	struct mpr_command *cm;
691 
692 	sassc = sc->sassc;
693 	mprsas_startup_increment(sassc);
694 	if ((mpr_config_get_sas_device_pg0(sc, &mpi_reply, &config_page,
695 	     MPI2_SAS_DEVICE_PGAD_FORM_HANDLE, handle))) {
696 		printf("%s: error reading SAS device page0\n", __func__);
697 		error = ENXIO;
698 		goto out;
699 	}
700 
701 	device_info = le32toh(config_page.DeviceInfo);
702 
703 	if (((device_info & MPI2_SAS_DEVICE_INFO_SMP_TARGET) == 0)
704 	    && (le16toh(config_page.ParentDevHandle) != 0)) {
705 		Mpi2ConfigReply_t tmp_mpi_reply;
706 		Mpi2SasDevicePage0_t parent_config_page;
707 
708 		if ((mpr_config_get_sas_device_pg0(sc, &tmp_mpi_reply,
709 		     &parent_config_page, MPI2_SAS_DEVICE_PGAD_FORM_HANDLE,
710 		     le16toh(config_page.ParentDevHandle)))) {
711 			printf("%s: error reading SAS device %#x page0\n",
712 			    __func__, le16toh(config_page.ParentDevHandle));
713 		} else {
714 			parent_sas_address = parent_config_page.SASAddress.High;
715 			parent_sas_address = (parent_sas_address << 32) |
716 			    parent_config_page.SASAddress.Low;
717 			parent_devinfo = le32toh(parent_config_page.DeviceInfo);
718 		}
719 	}
720 	/* TODO Check proper endianess */
721 	sas_address = config_page.SASAddress.High;
722 	sas_address = (sas_address << 32) | config_page.SASAddress.Low;
723 	mpr_dprint(sc, MPR_INFO, "SAS Address from SAS device page0 = %jx\n",
724 	    sas_address);
725 
726 	/*
727 	 * Always get SATA Identify information because this is used to
728 	 * determine if Start/Stop Unit should be sent to the drive when the
729 	 * system is shutdown.
730 	 */
731 	if (device_info & MPI2_SAS_DEVICE_INFO_SATA_DEVICE) {
732 		ret = mprsas_get_sas_address_for_sata_disk(sc, &sas_address,
733 		    handle, device_info, &is_SATA_SSD);
734 		if (ret) {
735 			mpr_dprint(sc, MPR_ERROR, "%s: failed to get disk type "
736 			    "(SSD or HDD) for SATA device with handle 0x%04x\n",
737 			    __func__, handle);
738 		} else {
739 			mpr_dprint(sc, MPR_INFO, "SAS Address from SATA "
740 			    "device = %jx\n", sas_address);
741 		}
742 	}
743 
744 	id = mpr_mapping_get_sas_id(sc, sas_address, handle);
745 	if (id == MPR_MAP_BAD_ID) {
746 		printf("failure at %s:%d/%s()! Could not get ID for device "
747 		    "with handle 0x%04x\n", __FILE__, __LINE__, __func__,
748 		    handle);
749 		error = ENXIO;
750 		goto out;
751 	}
752 
753 	if (mprsas_check_id(sassc, id) != 0) {
754 		device_printf(sc->mpr_dev, "Excluding target id %d\n", id);
755 		error = ENXIO;
756 		goto out;
757 	}
758 
759 	mpr_dprint(sc, MPR_MAPPING, "SAS Address from SAS device page0 = %jx\n",
760 	    sas_address);
761 	targ = &sassc->targets[id];
762 	targ->devinfo = device_info;
763 	targ->devname = le32toh(config_page.DeviceName.High);
764 	targ->devname = (targ->devname << 32) |
765 	    le32toh(config_page.DeviceName.Low);
766 	targ->encl_handle = le16toh(config_page.EnclosureHandle);
767 	targ->encl_slot = le16toh(config_page.Slot);
768 	targ->encl_level = config_page.EnclosureLevel;
769 	targ->connector_name[0] = config_page.ConnectorName[0];
770 	targ->connector_name[1] = config_page.ConnectorName[1];
771 	targ->connector_name[2] = config_page.ConnectorName[2];
772 	targ->connector_name[3] = config_page.ConnectorName[3];
773 	targ->handle = handle;
774 	targ->parent_handle = le16toh(config_page.ParentDevHandle);
775 	targ->sasaddr = mpr_to_u64(&config_page.SASAddress);
776 	targ->parent_sasaddr = le64toh(parent_sas_address);
777 	targ->parent_devinfo = parent_devinfo;
778 	targ->tid = id;
779 	targ->linkrate = (linkrate>>4);
780 	targ->flags = 0;
781 	if (is_SATA_SSD) {
782 		targ->flags = MPR_TARGET_IS_SATA_SSD;
783 	}
784 	if (le16toh(config_page.Flags) &
785 	    MPI25_SAS_DEVICE0_FLAGS_FAST_PATH_CAPABLE) {
786 		targ->scsi_req_desc_type =
787 		    MPI25_REQ_DESCRIPT_FLAGS_FAST_PATH_SCSI_IO;
788 	}
789 	if (le16toh(config_page.Flags) &
790 	    MPI2_SAS_DEVICE0_FLAGS_ENCL_LEVEL_VALID) {
791 		targ->encl_level_valid = TRUE;
792 	}
793 	TAILQ_INIT(&targ->commands);
794 	TAILQ_INIT(&targ->timedout_commands);
795 	while (!SLIST_EMPTY(&targ->luns)) {
796 		lun = SLIST_FIRST(&targ->luns);
797 		SLIST_REMOVE_HEAD(&targ->luns, lun_link);
798 		free(lun, M_MPR);
799 	}
800 	SLIST_INIT(&targ->luns);
801 
802 	mpr_describe_devinfo(targ->devinfo, devstring, 80);
803 	mpr_dprint(sc, (MPR_INFO|MPR_MAPPING), "Found device <%s> <%s> "
804 	    "handle<0x%04x> enclosureHandle<0x%04x> slot %d\n", devstring,
805 	    mpr_describe_table(mpr_linkrate_names, targ->linkrate),
806 	    targ->handle, targ->encl_handle, targ->encl_slot);
807 	if (targ->encl_level_valid) {
808 		mpr_dprint(sc, (MPR_INFO|MPR_MAPPING), "At enclosure level %d "
809 		    "and connector name (%4s)\n", targ->encl_level,
810 		    targ->connector_name);
811 	}
812 #if ((__FreeBSD_version >= 1000000) && (__FreeBSD_version < 1000039)) || \
813     (__FreeBSD_version < 902502)
814 	if ((sassc->flags & MPRSAS_IN_STARTUP) == 0)
815 #endif
816 		mprsas_rescan_target(sc, targ);
817 	mpr_dprint(sc, MPR_MAPPING, "Target id 0x%x added\n", targ->tid);
818 
819 	/*
820 	 * Check all commands to see if the SATA_ID_TIMEOUT flag has been set.
821 	 * If so, send a Target Reset TM to the target that was just created.
822 	 * An Abort Task TM should be used instead of a Target Reset, but that
823 	 * would be much more difficult because targets have not been fully
824 	 * discovered yet, and LUN's haven't been setup.  So, just reset the
825 	 * target instead of the LUN.
826 	 */
827 	for (i = 1; i < sc->num_reqs; i++) {
828 		cm = &sc->commands[i];
829 		if (cm->cm_flags & MPR_CM_FLAGS_SATA_ID_TIMEOUT) {
830 			targ->timeouts++;
831 			cm->cm_state = MPR_CM_STATE_TIMEDOUT;
832 
833 			if ((targ->tm = mprsas_alloc_tm(sc)) != NULL) {
834 				mpr_dprint(sc, MPR_INFO, "%s: sending Target "
835 				    "Reset for stuck SATA identify command "
836 				    "(cm = %p)\n", __func__, cm);
837 				targ->tm->cm_targ = targ;
838 				mprsas_send_reset(sc, targ->tm,
839 				    MPI2_SCSITASKMGMT_TASKTYPE_TARGET_RESET);
840 			} else {
841 				mpr_dprint(sc, MPR_ERROR, "Failed to allocate "
842 				    "tm for Target Reset after SATA ID "
843 				    "command timed out (cm %p)\n", cm);
844 			}
845 			/*
846 			 * No need to check for more since the target is
847 			 * already being reset.
848 			 */
849 			break;
850 		}
851 	}
852 out:
853 	/*
854 	 * Free the commands that may not have been freed from the SATA ID call
855 	 */
856 	for (i = 1; i < sc->num_reqs; i++) {
857 		cm = &sc->commands[i];
858 		if (cm->cm_flags & MPR_CM_FLAGS_SATA_ID_TIMEOUT) {
859 			mpr_free_command(sc, cm);
860 		}
861 	}
862 	mprsas_startup_decrement(sassc);
863 	return (error);
864 }
865 
866 int
867 mprsas_get_sas_address_for_sata_disk(struct mpr_softc *sc,
868     u64 *sas_address, u16 handle, u32 device_info, u8 *is_SATA_SSD)
869 {
870 	Mpi2SataPassthroughReply_t mpi_reply;
871 	int i, rc, try_count;
872 	u32 *bufferptr;
873 	union _sata_sas_address hash_address;
874 	struct _ata_identify_device_data ata_identify;
875 	u8 buffer[MPT2SAS_MN_LEN + MPT2SAS_SN_LEN];
876 	u32 ioc_status;
877 	u8 sas_status;
878 
879 	memset(&ata_identify, 0, sizeof(ata_identify));
880 	try_count = 0;
881 	do {
882 		rc = mprsas_get_sata_identify(sc, handle, &mpi_reply,
883 		    (char *)&ata_identify, sizeof(ata_identify), device_info);
884 		try_count++;
885 		ioc_status = le16toh(mpi_reply.IOCStatus)
886 		    & MPI2_IOCSTATUS_MASK;
887 		sas_status = mpi_reply.SASStatus;
888 		switch (ioc_status) {
889 		case MPI2_IOCSTATUS_SUCCESS:
890 			break;
891 		case MPI2_IOCSTATUS_SCSI_PROTOCOL_ERROR:
892 			/* No sense sleeping.  this error won't get better */
893 			break;
894 		default:
895 			if (sc->spinup_wait_time > 0) {
896 				mpr_dprint(sc, MPR_INFO, "Sleeping %d seconds "
897 				    "after SATA ID error to wait for spinup\n",
898 				    sc->spinup_wait_time);
899 				msleep(&sc->msleep_fake_chan, &sc->mpr_mtx, 0,
900 				    "mprid", sc->spinup_wait_time * hz);
901 			}
902 		}
903 	} while (((rc && (rc != EWOULDBLOCK)) ||
904 	         (ioc_status &&
905 		  (ioc_status != MPI2_IOCSTATUS_SCSI_PROTOCOL_ERROR))
906 	       || sas_status) && (try_count < 5));
907 
908 	if (rc == 0 && !ioc_status && !sas_status) {
909 		mpr_dprint(sc, MPR_MAPPING, "%s: got SATA identify "
910 		    "successfully for handle = 0x%x with try_count = %d\n",
911 		    __func__, handle, try_count);
912 	} else {
913 		mpr_dprint(sc, MPR_MAPPING, "%s: handle = 0x%x failed\n",
914 		    __func__, handle);
915 		return -1;
916 	}
917 	/* Copy & byteswap the 40 byte model number to a buffer */
918 	for (i = 0; i < MPT2SAS_MN_LEN; i += 2) {
919 		buffer[i] = ((u8 *)ata_identify.model_number)[i + 1];
920 		buffer[i + 1] = ((u8 *)ata_identify.model_number)[i];
921 	}
922 	/* Copy & byteswap the 20 byte serial number to a buffer */
923 	for (i = 0; i < MPT2SAS_SN_LEN; i += 2) {
924 		buffer[MPT2SAS_MN_LEN + i] =
925 		    ((u8 *)ata_identify.serial_number)[i + 1];
926 		buffer[MPT2SAS_MN_LEN + i + 1] =
927 		    ((u8 *)ata_identify.serial_number)[i];
928 	}
929 	bufferptr = (u32 *)buffer;
930 	/* There are 60 bytes to hash down to 8. 60 isn't divisible by 8,
931 	 * so loop through the first 56 bytes (7*8),
932 	 * and then add in the last dword.
933 	 */
934 	hash_address.word.low  = 0;
935 	hash_address.word.high = 0;
936 	for (i = 0; (i < ((MPT2SAS_MN_LEN+MPT2SAS_SN_LEN)/8)); i++) {
937 		hash_address.word.low += *bufferptr;
938 		bufferptr++;
939 		hash_address.word.high += *bufferptr;
940 		bufferptr++;
941 	}
942 	/* Add the last dword */
943 	hash_address.word.low += *bufferptr;
944 	/* Make sure the hash doesn't start with 5, because it could clash
945 	 * with a SAS address. Change 5 to a D.
946 	 */
947 	if ((hash_address.word.high & 0x000000F0) == (0x00000050))
948 		hash_address.word.high |= 0x00000080;
949 	*sas_address = (u64)hash_address.wwid[0] << 56 |
950 	    (u64)hash_address.wwid[1] << 48 | (u64)hash_address.wwid[2] << 40 |
951 	    (u64)hash_address.wwid[3] << 32 | (u64)hash_address.wwid[4] << 24 |
952 	    (u64)hash_address.wwid[5] << 16 | (u64)hash_address.wwid[6] <<  8 |
953 	    (u64)hash_address.wwid[7];
954 	if (ata_identify.rotational_speed == 1) {
955 		*is_SATA_SSD = 1;
956 	}
957 
958 	return 0;
959 }
960 
961 static int
962 mprsas_get_sata_identify(struct mpr_softc *sc, u16 handle,
963     Mpi2SataPassthroughReply_t *mpi_reply, char *id_buffer, int sz, u32 devinfo)
964 {
965 	Mpi2SataPassthroughRequest_t *mpi_request;
966 	Mpi2SataPassthroughReply_t *reply;
967 	struct mpr_command *cm;
968 	char *buffer;
969 	int error = 0;
970 
971 	buffer = malloc( sz, M_MPR, M_NOWAIT | M_ZERO);
972 	if (!buffer)
973 		return ENOMEM;
974 
975 	if ((cm = mpr_alloc_command(sc)) == NULL) {
976 		free(buffer, M_MPR);
977 		return (EBUSY);
978 	}
979 	mpi_request = (MPI2_SATA_PASSTHROUGH_REQUEST *)cm->cm_req;
980 	bzero(mpi_request,sizeof(MPI2_SATA_PASSTHROUGH_REQUEST));
981 	mpi_request->Function = MPI2_FUNCTION_SATA_PASSTHROUGH;
982 	mpi_request->VF_ID = 0;
983 	mpi_request->DevHandle = htole16(handle);
984 	mpi_request->PassthroughFlags = (MPI2_SATA_PT_REQ_PT_FLAGS_PIO |
985 	    MPI2_SATA_PT_REQ_PT_FLAGS_READ);
986 	mpi_request->DataLength = htole32(sz);
987 	mpi_request->CommandFIS[0] = 0x27;
988 	mpi_request->CommandFIS[1] = 0x80;
989 	mpi_request->CommandFIS[2] =  (devinfo &
990 	    MPI2_SAS_DEVICE_INFO_ATAPI_DEVICE) ? 0xA1 : 0xEC;
991 	cm->cm_sge = &mpi_request->SGL;
992 	cm->cm_sglsize = sizeof(MPI2_SGE_IO_UNION);
993 	cm->cm_flags = MPR_CM_FLAGS_DATAIN;
994 	cm->cm_desc.Default.RequestFlags = MPI2_REQ_DESCRIPT_FLAGS_DEFAULT_TYPE;
995 	cm->cm_data = buffer;
996 	cm->cm_length = htole32(sz);
997 
998 	/*
999 	 * Start a timeout counter specifically for the SATA ID command. This
1000 	 * is used to fix a problem where the FW does not send a reply sometimes
1001 	 * when a bad disk is in the topology. So, this is used to timeout the
1002 	 * command so that processing can continue normally.
1003 	 */
1004 	mpr_dprint(sc, MPR_XINFO, "%s start timeout counter for SATA ID "
1005 	    "command\n", __func__);
1006 	callout_reset(&cm->cm_callout, MPR_ATA_ID_TIMEOUT * hz,
1007 	    mprsas_ata_id_timeout, cm);
1008 	error = mpr_wait_command(sc, cm, 60, CAN_SLEEP);
1009 	mpr_dprint(sc, MPR_XINFO, "%s stop timeout counter for SATA ID "
1010 	    "command\n", __func__);
1011 	callout_stop(&cm->cm_callout);
1012 
1013 	reply = (Mpi2SataPassthroughReply_t *)cm->cm_reply;
1014 	if (error || (reply == NULL)) {
1015 		/* FIXME */
1016 		/*
1017 		 * If the request returns an error then we need to do a diag
1018 		 * reset
1019 		 */
1020 		printf("%s: request for page completed with error %d",
1021 		    __func__, error);
1022 		error = ENXIO;
1023 		goto out;
1024 	}
1025 	bcopy(buffer, id_buffer, sz);
1026 	bcopy(reply, mpi_reply, sizeof(Mpi2SataPassthroughReply_t));
1027 	if ((le16toh(reply->IOCStatus) & MPI2_IOCSTATUS_MASK) !=
1028 	    MPI2_IOCSTATUS_SUCCESS) {
1029 		printf("%s: error reading SATA PASSTHRU; iocstatus = 0x%x\n",
1030 		    __func__, reply->IOCStatus);
1031 		error = ENXIO;
1032 		goto out;
1033 	}
1034 out:
1035 	/*
1036 	 * If the SATA_ID_TIMEOUT flag has been set for this command, don't free
1037 	 * it.  The command will be freed after sending a target reset TM. If
1038 	 * the command did timeout, use EWOULDBLOCK.
1039 	 */
1040 	if ((cm->cm_flags & MPR_CM_FLAGS_SATA_ID_TIMEOUT) == 0)
1041 		mpr_free_command(sc, cm);
1042 	else if (error == 0)
1043 		error = EWOULDBLOCK;
1044 	free(buffer, M_MPR);
1045 	return (error);
1046 }
1047 
1048 static void
1049 mprsas_ata_id_timeout(void *data)
1050 {
1051 	struct mpr_softc *sc;
1052 	struct mpr_command *cm;
1053 
1054 	cm = (struct mpr_command *)data;
1055 	sc = cm->cm_sc;
1056 	mtx_assert(&sc->mpr_mtx, MA_OWNED);
1057 
1058 	mpr_dprint(sc, MPR_INFO, "%s checking ATA ID command %p sc %p\n",
1059 	    __func__, cm, sc);
1060 	if ((callout_pending(&cm->cm_callout)) ||
1061 	    (!callout_active(&cm->cm_callout))) {
1062 		mpr_dprint(sc, MPR_INFO, "%s ATA ID command almost timed "
1063 		    "out\n", __func__);
1064 		return;
1065 	}
1066 	callout_deactivate(&cm->cm_callout);
1067 
1068 	/*
1069 	 * Run the interrupt handler to make sure it's not pending.  This
1070 	 * isn't perfect because the command could have already completed
1071 	 * and been re-used, though this is unlikely.
1072 	 */
1073 	mpr_intr_locked(sc);
1074 	if (cm->cm_state == MPR_CM_STATE_FREE) {
1075 		mpr_dprint(sc, MPR_INFO, "%s ATA ID command almost timed "
1076 		    "out\n", __func__);
1077 		return;
1078 	}
1079 
1080 	mpr_dprint(sc, MPR_INFO, "ATA ID command timeout cm %p\n", cm);
1081 
1082 	/*
1083 	 * Send wakeup() to the sleeping thread that issued this ATA ID
1084 	 * command. wakeup() will cause msleep to return a 0 (not EWOULDBLOCK),
1085 	 * and this will keep reinit() from being called. This way, an Abort
1086 	 * Task TM can be issued so that the timed out command can be cleared.
1087 	 * The Abort Task cannot be sent from here because the driver has not
1088 	 * completed setting up targets.  Instead, the command is flagged so
1089 	 * that special handling will be used to send the abort.
1090 	 */
1091 	cm->cm_flags |= MPR_CM_FLAGS_SATA_ID_TIMEOUT;
1092 	wakeup(cm);
1093 }
1094 
1095 static int
1096 mprsas_volume_add(struct mpr_softc *sc, u16 handle)
1097 {
1098 	struct mprsas_softc *sassc;
1099 	struct mprsas_target *targ;
1100 	u64 wwid;
1101 	unsigned int id;
1102 	int error = 0;
1103 	struct mprsas_lun *lun;
1104 
1105 	sassc = sc->sassc;
1106 	mprsas_startup_increment(sassc);
1107 	/* wwid is endian safe */
1108 	mpr_config_get_volume_wwid(sc, handle, &wwid);
1109 	if (!wwid) {
1110 		printf("%s: invalid WWID; cannot add volume to mapping table\n",
1111 		    __func__);
1112 		error = ENXIO;
1113 		goto out;
1114 	}
1115 
1116 	id = mpr_mapping_get_raid_id(sc, wwid, handle);
1117 	if (id == MPR_MAP_BAD_ID) {
1118 		printf("%s: could not get ID for volume with handle 0x%04x and "
1119 		    "WWID 0x%016llx\n", __func__, handle,
1120 		    (unsigned long long)wwid);
1121 		error = ENXIO;
1122 		goto out;
1123 	}
1124 
1125 	targ = &sassc->targets[id];
1126 	targ->tid = id;
1127 	targ->handle = handle;
1128 	targ->devname = wwid;
1129 	TAILQ_INIT(&targ->commands);
1130 	TAILQ_INIT(&targ->timedout_commands);
1131 	while (!SLIST_EMPTY(&targ->luns)) {
1132 		lun = SLIST_FIRST(&targ->luns);
1133 		SLIST_REMOVE_HEAD(&targ->luns, lun_link);
1134 		free(lun, M_MPR);
1135 	}
1136 	SLIST_INIT(&targ->luns);
1137 #if ((__FreeBSD_version >= 1000000) && (__FreeBSD_version < 1000039)) || \
1138     (__FreeBSD_version < 902502)
1139 	if ((sassc->flags & MPRSAS_IN_STARTUP) == 0)
1140 #endif
1141 		mprsas_rescan_target(sc, targ);
1142 	mpr_dprint(sc, MPR_MAPPING, "RAID target id %d added (WWID = 0x%jx)\n",
1143 	    targ->tid, wwid);
1144 out:
1145 	mprsas_startup_decrement(sassc);
1146 	return (error);
1147 }
1148 
1149 /**
1150  * mprsas_SSU_to_SATA_devices
1151  * @sc: per adapter object
1152  *
1153  * Looks through the target list and issues a StartStopUnit SCSI command to each
1154  * SATA direct-access device.  This helps to ensure that data corruption is
1155  * avoided when the system is being shut down.  This must be called after the IR
1156  * System Shutdown RAID Action is sent if in IR mode.
1157  *
1158  * Return nothing.
1159  */
1160 static void
1161 mprsas_SSU_to_SATA_devices(struct mpr_softc *sc)
1162 {
1163 	struct mprsas_softc *sassc = sc->sassc;
1164 	union ccb *ccb;
1165 	path_id_t pathid = cam_sim_path(sassc->sim);
1166 	target_id_t targetid;
1167 	struct mprsas_target *target;
1168 	char path_str[64];
1169 	struct timeval cur_time, start_time;
1170 
1171 	mpr_lock(sc);
1172 
1173 	/*
1174 	 * For each target, issue a StartStopUnit command to stop the device.
1175 	 */
1176 	sc->SSU_started = TRUE;
1177 	sc->SSU_refcount = 0;
1178 	for (targetid = 0; targetid < sc->facts->MaxTargets; targetid++) {
1179 		target = &sassc->targets[targetid];
1180 		if (target->handle == 0x0) {
1181 			continue;
1182 		}
1183 
1184 		ccb = xpt_alloc_ccb_nowait();
1185 		if (ccb == NULL) {
1186 			mpr_dprint(sc, MPR_FAULT, "Unable to alloc CCB to stop "
1187 			    "unit.\n");
1188 			return;
1189 		}
1190 
1191 		/*
1192 		 * The stop_at_shutdown flag will be set if this device is
1193 		 * a SATA direct-access end device.
1194 		 */
1195 		if (target->stop_at_shutdown) {
1196 			if (xpt_create_path(&ccb->ccb_h.path, xpt_periph,
1197 			    pathid, targetid, CAM_LUN_WILDCARD) !=
1198 			    CAM_REQ_CMP) {
1199 				mpr_dprint(sc, MPR_ERROR, "Unable to create "
1200 				    "path to stop unit.\n");
1201 				xpt_free_ccb(ccb);
1202 				return;
1203 			}
1204 			xpt_path_string(ccb->ccb_h.path, path_str,
1205 			    sizeof(path_str));
1206 
1207 			mpr_dprint(sc, MPR_INFO, "Sending StopUnit: path %s "
1208 			    "handle %d\n", path_str, target->handle);
1209 
1210 			/*
1211 			 * Issue a START STOP UNIT command for the target.
1212 			 * Increment the SSU counter to be used to count the
1213 			 * number of required replies.
1214 			 */
1215 			mpr_dprint(sc, MPR_INFO, "Incrementing SSU count\n");
1216 			sc->SSU_refcount++;
1217 			ccb->ccb_h.target_id =
1218 			    xpt_path_target_id(ccb->ccb_h.path);
1219 			ccb->ccb_h.ppriv_ptr1 = sassc;
1220 			scsi_start_stop(&ccb->csio,
1221 			    /*retries*/0,
1222 			    mprsas_stop_unit_done,
1223 			    MSG_SIMPLE_Q_TAG,
1224 			    /*start*/FALSE,
1225 			    /*load/eject*/0,
1226 			    /*immediate*/FALSE,
1227 			    MPR_SENSE_LEN,
1228 			    /*timeout*/10000);
1229 			xpt_action(ccb);
1230 		}
1231 	}
1232 
1233 	mpr_unlock(sc);
1234 
1235 	/*
1236 	 * Wait until all of the SSU commands have completed or time has
1237 	 * expired (60 seconds).  Pause for 100ms each time through.  If any
1238 	 * command times out, the target will be reset in the SCSI command
1239 	 * timeout routine.
1240 	 */
1241 	getmicrotime(&start_time);
1242 	while (sc->SSU_refcount) {
1243 		pause("mprwait", hz/10);
1244 
1245 		getmicrotime(&cur_time);
1246 		if ((cur_time.tv_sec - start_time.tv_sec) > 60) {
1247 			mpr_dprint(sc, MPR_ERROR, "Time has expired waiting "
1248 			    "for SSU commands to complete.\n");
1249 			break;
1250 		}
1251 	}
1252 }
1253 
1254 static void
1255 mprsas_stop_unit_done(struct cam_periph *periph, union ccb *done_ccb)
1256 {
1257 	struct mprsas_softc *sassc;
1258 	char path_str[64];
1259 
1260 	sassc = (struct mprsas_softc *)done_ccb->ccb_h.ppriv_ptr1;
1261 
1262 	xpt_path_string(done_ccb->ccb_h.path, path_str, sizeof(path_str));
1263 	mpr_dprint(sassc->sc, MPR_INFO, "Completing stop unit for %s\n",
1264 	    path_str);
1265 
1266 	if (done_ccb == NULL)
1267 		return;
1268 
1269 	/*
1270 	 * Nothing more to do except free the CCB and path.  If the command
1271 	 * timed out, an abort reset, then target reset will be issued during
1272 	 * the SCSI Command process.
1273 	 */
1274 	xpt_free_path(done_ccb->ccb_h.path);
1275 	xpt_free_ccb(done_ccb);
1276 }
1277 
1278 /**
1279  * mprsas_ir_shutdown - IR shutdown notification
1280  * @sc: per adapter object
1281  *
1282  * Sending RAID Action to alert the Integrated RAID subsystem of the IOC that
1283  * the host system is shutting down.
1284  *
1285  * Return nothing.
1286  */
1287 void
1288 mprsas_ir_shutdown(struct mpr_softc *sc)
1289 {
1290 	u16 volume_mapping_flags;
1291 	u16 ioc_pg8_flags = le16toh(sc->ioc_pg8.Flags);
1292 	struct dev_mapping_table *mt_entry;
1293 	u32 start_idx, end_idx;
1294 	unsigned int id, found_volume = 0;
1295 	struct mpr_command *cm;
1296 	Mpi2RaidActionRequest_t	*action;
1297 	target_id_t targetid;
1298 	struct mprsas_target *target;
1299 
1300 	mpr_dprint(sc, MPR_TRACE, "%s\n", __func__);
1301 
1302 	/* is IR firmware build loaded? */
1303 	if (!sc->ir_firmware)
1304 		goto out;
1305 
1306 	/* are there any volumes?  Look at IR target IDs. */
1307 	// TODO-later, this should be looked up in the RAID config structure
1308 	// when it is implemented.
1309 	volume_mapping_flags = le16toh(sc->ioc_pg8.IRVolumeMappingFlags) &
1310 	    MPI2_IOCPAGE8_IRFLAGS_MASK_VOLUME_MAPPING_MODE;
1311 	if (volume_mapping_flags == MPI2_IOCPAGE8_IRFLAGS_LOW_VOLUME_MAPPING) {
1312 		start_idx = 0;
1313 		if (ioc_pg8_flags & MPI2_IOCPAGE8_FLAGS_RESERVED_TARGETID_0)
1314 			start_idx = 1;
1315 	} else
1316 		start_idx = sc->max_devices - sc->max_volumes;
1317 	end_idx = start_idx + sc->max_volumes - 1;
1318 
1319 	for (id = start_idx; id < end_idx; id++) {
1320 		mt_entry = &sc->mapping_table[id];
1321 		if ((mt_entry->physical_id != 0) &&
1322 		    (mt_entry->missing_count == 0)) {
1323 			found_volume = 1;
1324 			break;
1325 		}
1326 	}
1327 
1328 	if (!found_volume)
1329 		goto out;
1330 
1331 	if ((cm = mpr_alloc_command(sc)) == NULL) {
1332 		printf("%s: command alloc failed\n", __func__);
1333 		goto out;
1334 	}
1335 
1336 	action = (MPI2_RAID_ACTION_REQUEST *)cm->cm_req;
1337 	action->Function = MPI2_FUNCTION_RAID_ACTION;
1338 	action->Action = MPI2_RAID_ACTION_SYSTEM_SHUTDOWN_INITIATED;
1339 	cm->cm_desc.Default.RequestFlags = MPI2_REQ_DESCRIPT_FLAGS_DEFAULT_TYPE;
1340 	mpr_lock(sc);
1341 	mpr_wait_command(sc, cm, 5, CAN_SLEEP);
1342 	mpr_unlock(sc);
1343 
1344 	/*
1345 	 * Don't check for reply, just leave.
1346 	 */
1347 	if (cm)
1348 		mpr_free_command(sc, cm);
1349 
1350 out:
1351 	/*
1352 	 * All of the targets must have the correct value set for
1353 	 * 'stop_at_shutdown' for the current 'enable_ssu' sysctl variable.
1354 	 *
1355 	 * The possible values for the 'enable_ssu' variable are:
1356 	 * 0: disable to SSD and HDD
1357 	 * 1: disable only to HDD (default)
1358 	 * 2: disable only to SSD
1359 	 * 3: enable to SSD and HDD
1360 	 * anything else will default to 1.
1361 	 */
1362 	for (targetid = 0; targetid < sc->facts->MaxTargets; targetid++) {
1363 		target = &sc->sassc->targets[targetid];
1364 		if (target->handle == 0x0) {
1365 			continue;
1366 		}
1367 
1368 		if (target->supports_SSU) {
1369 			switch (sc->enable_ssu) {
1370 			case MPR_SSU_DISABLE_SSD_DISABLE_HDD:
1371 				target->stop_at_shutdown = FALSE;
1372 				break;
1373 			case MPR_SSU_DISABLE_SSD_ENABLE_HDD:
1374 				target->stop_at_shutdown = TRUE;
1375 				if (target->flags & MPR_TARGET_IS_SATA_SSD) {
1376 					target->stop_at_shutdown = FALSE;
1377 				}
1378 				break;
1379 			case MPR_SSU_ENABLE_SSD_ENABLE_HDD:
1380 				target->stop_at_shutdown = TRUE;
1381 				break;
1382 			case MPR_SSU_ENABLE_SSD_DISABLE_HDD:
1383 			default:
1384 				target->stop_at_shutdown = TRUE;
1385 				if ((target->flags &
1386 				    MPR_TARGET_IS_SATA_SSD) == 0) {
1387 					target->stop_at_shutdown = FALSE;
1388 				}
1389 				break;
1390 			}
1391 		}
1392 	}
1393 	mprsas_SSU_to_SATA_devices(sc);
1394 }
1395