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