]> CyberLeo.Net >> Repos - FreeBSD/FreeBSD.git/blob - sys/dev/mrsas/mrsas_cam.c
vmx(4): add native netmap support
[FreeBSD/FreeBSD.git] / sys / dev / mrsas / mrsas_cam.c
1 /*
2  * Copyright (c) 2015, AVAGO Tech. All rights reserved. Author: Marian Choy
3  * Copyright (c) 2014, LSI Corp. All rights reserved. Author: Marian Choy
4  * Support: freebsdraid@avagotech.com
5  *
6  * Redistribution and use in source and binary forms, with or without
7  * modification, are permitted provided that the following conditions are
8  * met:
9  *
10  * 1. Redistributions of source code must retain the above copyright notice,
11  * this list of conditions and the following disclaimer. 2. Redistributions
12  * in binary form must reproduce the above copyright notice, this list of
13  * conditions and the following disclaimer in the documentation and/or other
14  * materials provided with the distribution. 3. Neither the name of the
15  * <ORGANIZATION> nor the names of its contributors may be used to endorse or
16  * promote products derived from this software without specific prior written
17  * permission.
18  *
19  * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
20  * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
21  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
22  * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE
23  * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
24  * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
25  * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
26  * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
27  * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
28  * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
29  * POSSIBILITY OF SUCH DAMAGE.
30  *
31  */
32
33 #include <sys/cdefs.h>
34 __FBSDID("$FreeBSD$");
35
36 #include "dev/mrsas/mrsas.h"
37
38 #include <cam/cam.h>
39 #include <cam/cam_ccb.h>
40 #include <cam/cam_sim.h>
41 #include <cam/cam_xpt_sim.h>
42 #include <cam/cam_debug.h>
43 #include <cam/cam_periph.h>
44 #include <cam/cam_xpt_periph.h>
45
46 #include <cam/scsi/scsi_all.h>
47 #include <cam/scsi/scsi_message.h>
48 #include <sys/taskqueue.h>
49 #include <sys/kernel.h>
50
51 #include <sys/time.h>                   /* XXX for pcpu.h */
52 #include <sys/pcpu.h>                   /* XXX for PCPU_GET */
53
54 #define smp_processor_id()  PCPU_GET(cpuid)
55
56 /*
57  * Function prototypes
58  */
59 int     mrsas_cam_attach(struct mrsas_softc *sc);
60 int     mrsas_find_io_type(struct cam_sim *sim, union ccb *ccb);
61 int     mrsas_bus_scan(struct mrsas_softc *sc);
62 int     mrsas_bus_scan_sim(struct mrsas_softc *sc, struct cam_sim *sim);
63 int 
64 mrsas_map_request(struct mrsas_softc *sc,
65     struct mrsas_mpt_cmd *cmd, union ccb *ccb);
66 int
67 mrsas_build_ldio_rw(struct mrsas_softc *sc, struct mrsas_mpt_cmd *cmd,
68     union ccb *ccb);
69 int
70 mrsas_build_ldio_nonrw(struct mrsas_softc *sc, struct mrsas_mpt_cmd *cmd,
71     union ccb *ccb);
72 int
73 mrsas_build_syspdio(struct mrsas_softc *sc, struct mrsas_mpt_cmd *cmd,
74     union ccb *ccb, struct cam_sim *sim, u_int8_t fp_possible);
75 int
76 mrsas_setup_io(struct mrsas_softc *sc, struct mrsas_mpt_cmd *cmd,
77     union ccb *ccb, u_int32_t device_id,
78     MRSAS_RAID_SCSI_IO_REQUEST * io_request);
79 void    mrsas_xpt_freeze(struct mrsas_softc *sc);
80 void    mrsas_xpt_release(struct mrsas_softc *sc);
81 void    mrsas_cam_detach(struct mrsas_softc *sc);
82 void    mrsas_release_mpt_cmd(struct mrsas_mpt_cmd *cmd);
83 void    mrsas_unmap_request(struct mrsas_softc *sc, struct mrsas_mpt_cmd *cmd);
84 void    mrsas_cmd_done(struct mrsas_softc *sc, struct mrsas_mpt_cmd *cmd);
85 void
86 mrsas_fire_cmd(struct mrsas_softc *sc, u_int32_t req_desc_lo,
87     u_int32_t req_desc_hi);
88 void
89 mrsas_set_pd_lba(MRSAS_RAID_SCSI_IO_REQUEST * io_request,
90     u_int8_t cdb_len, struct IO_REQUEST_INFO *io_info, union ccb *ccb,
91     MR_DRV_RAID_MAP_ALL * local_map_ptr, u_int32_t ref_tag,
92     u_int32_t ld_block_size);
93 static void mrsas_freeze_simq(struct mrsas_mpt_cmd *cmd, struct cam_sim *sim);
94 static void mrsas_cam_poll(struct cam_sim *sim);
95 static void mrsas_action(struct cam_sim *sim, union ccb *ccb);
96 static void mrsas_scsiio_timeout(void *data);
97 static int mrsas_track_scsiio(struct mrsas_softc *sc, target_id_t id, u_int32_t bus_id);
98 static void mrsas_tm_response_code(struct mrsas_softc *sc,
99     MPI2_SCSI_TASK_MANAGE_REPLY *mpi_reply);
100 static int mrsas_issue_tm(struct mrsas_softc *sc,
101     MRSAS_REQUEST_DESCRIPTOR_UNION *req_desc);
102 static void
103 mrsas_data_load_cb(void *arg, bus_dma_segment_t *segs,
104     int nseg, int error);
105 static int32_t
106 mrsas_startio(struct mrsas_softc *sc, struct cam_sim *sim,
107     union ccb *ccb);
108
109 static boolean_t mrsas_is_prp_possible(struct mrsas_mpt_cmd *cmd,
110         bus_dma_segment_t *segs, int nsegs);
111 static void mrsas_build_ieee_sgl(struct mrsas_mpt_cmd *cmd,
112         bus_dma_segment_t *segs, int nseg);
113 static void mrsas_build_prp_nvme(struct mrsas_mpt_cmd *cmd,
114         bus_dma_segment_t *segs, int nseg);
115
116 struct mrsas_mpt_cmd *mrsas_get_mpt_cmd(struct mrsas_softc *sc);
117 MRSAS_REQUEST_DESCRIPTOR_UNION *
118         mrsas_get_request_desc(struct mrsas_softc *sc, u_int16_t index);
119
120 extern int mrsas_reset_targets(struct mrsas_softc *sc);
121 extern u_int16_t MR_TargetIdToLdGet(u_int32_t ldTgtId, MR_DRV_RAID_MAP_ALL * map);
122 extern u_int32_t
123 MR_LdBlockSizeGet(u_int32_t ldTgtId, MR_DRV_RAID_MAP_ALL * map,
124     struct mrsas_softc *sc);
125 extern void mrsas_isr(void *arg);
126 extern void mrsas_aen_handler(struct mrsas_softc *sc);
127 extern u_int8_t
128 MR_BuildRaidContext(struct mrsas_softc *sc,
129     struct IO_REQUEST_INFO *io_info, RAID_CONTEXT * pRAID_Context,
130     MR_DRV_RAID_MAP_ALL * map);
131 extern u_int16_t
132 MR_LdSpanArrayGet(u_int32_t ld, u_int32_t span,
133     MR_DRV_RAID_MAP_ALL * map);
134 extern u_int16_t 
135 mrsas_get_updated_dev_handle(struct mrsas_softc *sc,
136     PLD_LOAD_BALANCE_INFO lbInfo, struct IO_REQUEST_INFO *io_info);
137 extern int mrsas_complete_cmd(struct mrsas_softc *sc, u_int32_t MSIxIndex);
138 extern MR_LD_RAID *MR_LdRaidGet(u_int32_t ld, MR_DRV_RAID_MAP_ALL * map);
139 extern void mrsas_disable_intr(struct mrsas_softc *sc);
140 extern void mrsas_enable_intr(struct mrsas_softc *sc);
141 void mrsas_prepare_secondRaid1_IO(struct mrsas_softc *sc,
142     struct mrsas_mpt_cmd *cmd);
143
144 /*
145  * mrsas_cam_attach:    Main entry to CAM subsystem
146  * input:                               Adapter instance soft state
147  *
148  * This function is called from mrsas_attach() during initialization to perform
149  * SIM allocations and XPT bus registration.  If the kernel version is 7.4 or
150  * earlier, it would also initiate a bus scan.
151  */
152 int
153 mrsas_cam_attach(struct mrsas_softc *sc)
154 {
155         struct cam_devq *devq;
156         int mrsas_cam_depth;
157
158         mrsas_cam_depth = sc->max_scsi_cmds;
159
160         if ((devq = cam_simq_alloc(mrsas_cam_depth)) == NULL) {
161                 device_printf(sc->mrsas_dev, "Cannot allocate SIM queue\n");
162                 return (ENOMEM);
163         }
164         /*
165          * Create SIM for bus 0 and register, also create path
166          */
167         sc->sim_0 = cam_sim_alloc(mrsas_action, mrsas_cam_poll, "mrsas", sc,
168             device_get_unit(sc->mrsas_dev), &sc->sim_lock, mrsas_cam_depth,
169             mrsas_cam_depth, devq);
170         if (sc->sim_0 == NULL) {
171                 cam_simq_free(devq);
172                 device_printf(sc->mrsas_dev, "Cannot register SIM\n");
173                 return (ENXIO);
174         }
175         /* Initialize taskqueue for Event Handling */
176         TASK_INIT(&sc->ev_task, 0, (void *)mrsas_aen_handler, sc);
177         sc->ev_tq = taskqueue_create("mrsas_taskq", M_NOWAIT | M_ZERO,
178             taskqueue_thread_enqueue, &sc->ev_tq);
179
180         /* Run the task queue with lowest priority */
181         taskqueue_start_threads(&sc->ev_tq, 1, 255, "%s taskq",
182             device_get_nameunit(sc->mrsas_dev));
183         mtx_lock(&sc->sim_lock);
184         if (xpt_bus_register(sc->sim_0, sc->mrsas_dev, 0) != CAM_SUCCESS) {
185                 cam_sim_free(sc->sim_0, TRUE);  /* passing true frees the devq */
186                 mtx_unlock(&sc->sim_lock);
187                 return (ENXIO);
188         }
189         if (xpt_create_path(&sc->path_0, NULL, cam_sim_path(sc->sim_0),
190             CAM_TARGET_WILDCARD, CAM_LUN_WILDCARD) != CAM_REQ_CMP) {
191                 xpt_bus_deregister(cam_sim_path(sc->sim_0));
192                 cam_sim_free(sc->sim_0, TRUE);  /* passing true will free the
193                                                  * devq */
194                 mtx_unlock(&sc->sim_lock);
195                 return (ENXIO);
196         }
197         mtx_unlock(&sc->sim_lock);
198
199         /*
200          * Create SIM for bus 1 and register, also create path
201          */
202         sc->sim_1 = cam_sim_alloc(mrsas_action, mrsas_cam_poll, "mrsas", sc,
203             device_get_unit(sc->mrsas_dev), &sc->sim_lock, mrsas_cam_depth,
204             mrsas_cam_depth, devq);
205         if (sc->sim_1 == NULL) {
206                 cam_simq_free(devq);
207                 device_printf(sc->mrsas_dev, "Cannot register SIM\n");
208                 return (ENXIO);
209         }
210         mtx_lock(&sc->sim_lock);
211         if (xpt_bus_register(sc->sim_1, sc->mrsas_dev, 1) != CAM_SUCCESS) {
212                 cam_sim_free(sc->sim_1, TRUE);  /* passing true frees the devq */
213                 mtx_unlock(&sc->sim_lock);
214                 return (ENXIO);
215         }
216         if (xpt_create_path(&sc->path_1, NULL, cam_sim_path(sc->sim_1),
217             CAM_TARGET_WILDCARD,
218             CAM_LUN_WILDCARD) != CAM_REQ_CMP) {
219                 xpt_bus_deregister(cam_sim_path(sc->sim_1));
220                 cam_sim_free(sc->sim_1, TRUE);
221                 mtx_unlock(&sc->sim_lock);
222                 return (ENXIO);
223         }
224         mtx_unlock(&sc->sim_lock);
225
226 #if (__FreeBSD_version <= 704000)
227         if (mrsas_bus_scan(sc)) {
228                 device_printf(sc->mrsas_dev, "Error in bus scan.\n");
229                 return (1);
230         }
231 #endif
232         return (0);
233 }
234
235 /*
236  * mrsas_cam_detach:    De-allocates and teardown CAM
237  * input:                               Adapter instance soft state
238  *
239  * De-registers and frees the paths and SIMs.
240  */
241 void
242 mrsas_cam_detach(struct mrsas_softc *sc)
243 {
244         if (sc->ev_tq != NULL)
245                 taskqueue_free(sc->ev_tq);
246         mtx_lock(&sc->sim_lock);
247         if (sc->path_0)
248                 xpt_free_path(sc->path_0);
249         if (sc->sim_0) {
250                 xpt_bus_deregister(cam_sim_path(sc->sim_0));
251                 cam_sim_free(sc->sim_0, FALSE);
252         }
253         if (sc->path_1)
254                 xpt_free_path(sc->path_1);
255         if (sc->sim_1) {
256                 xpt_bus_deregister(cam_sim_path(sc->sim_1));
257                 cam_sim_free(sc->sim_1, TRUE);
258         }
259         mtx_unlock(&sc->sim_lock);
260 }
261
262 /*
263  * mrsas_action:        SIM callback entry point
264  * input:                       pointer to SIM pointer to CAM Control Block
265  *
266  * This function processes CAM subsystem requests. The type of request is stored
267  * in ccb->ccb_h.func_code.  The preprocessor #ifdef is necessary because
268  * ccb->cpi.maxio is not supported for FreeBSD version 7.4 or earlier.
269  */
270 static void
271 mrsas_action(struct cam_sim *sim, union ccb *ccb)
272 {
273         struct mrsas_softc *sc = (struct mrsas_softc *)cam_sim_softc(sim);
274         struct ccb_hdr *ccb_h = &(ccb->ccb_h);
275         u_int32_t device_id;
276
277         /*
278      * Check if the system going down
279      * or the adapter is in unrecoverable critical error
280      */
281     if (sc->remove_in_progress ||
282         (sc->adprecovery == MRSAS_HW_CRITICAL_ERROR)) {
283         ccb->ccb_h.status |= CAM_DEV_NOT_THERE;
284         xpt_done(ccb);
285         return;
286     }
287
288         switch (ccb->ccb_h.func_code) {
289         case XPT_SCSI_IO:
290                 {
291                         device_id = ccb_h->target_id;
292
293                         /*
294                          * bus 0 is LD, bus 1 is for system-PD
295                          */
296                         if (cam_sim_bus(sim) == 1 &&
297                             sc->pd_list[device_id].driveState != MR_PD_STATE_SYSTEM) {
298                                 ccb->ccb_h.status |= CAM_DEV_NOT_THERE;
299                                 xpt_done(ccb);
300                         } else {
301                                 if (mrsas_startio(sc, sim, ccb)) {
302                                         ccb->ccb_h.status |= CAM_REQ_INVALID;
303                                         xpt_done(ccb);
304                                 }
305                         }
306                         break;
307                 }
308         case XPT_ABORT:
309                 {
310                         ccb->ccb_h.status = CAM_UA_ABORT;
311                         xpt_done(ccb);
312                         break;
313                 }
314         case XPT_RESET_BUS:
315                 {
316                         xpt_done(ccb);
317                         break;
318                 }
319         case XPT_GET_TRAN_SETTINGS:
320                 {
321                         ccb->cts.protocol = PROTO_SCSI;
322                         ccb->cts.protocol_version = SCSI_REV_2;
323                         ccb->cts.transport = XPORT_SPI;
324                         ccb->cts.transport_version = 2;
325                         ccb->cts.xport_specific.spi.valid = CTS_SPI_VALID_DISC;
326                         ccb->cts.xport_specific.spi.flags = CTS_SPI_FLAGS_DISC_ENB;
327                         ccb->cts.proto_specific.scsi.valid = CTS_SCSI_VALID_TQ;
328                         ccb->cts.proto_specific.scsi.flags = CTS_SCSI_FLAGS_TAG_ENB;
329                         ccb->ccb_h.status = CAM_REQ_CMP;
330                         xpt_done(ccb);
331                         break;
332                 }
333         case XPT_SET_TRAN_SETTINGS:
334                 {
335                         ccb->ccb_h.status = CAM_FUNC_NOTAVAIL;
336                         xpt_done(ccb);
337                         break;
338                 }
339         case XPT_CALC_GEOMETRY:
340                 {
341                         cam_calc_geometry(&ccb->ccg, 1);
342                         xpt_done(ccb);
343                         break;
344                 }
345         case XPT_PATH_INQ:
346                 {
347                         ccb->cpi.version_num = 1;
348                         ccb->cpi.hba_inquiry = 0;
349                         ccb->cpi.target_sprt = 0;
350 #if (__FreeBSD_version >= 902001)
351                         ccb->cpi.hba_misc = PIM_UNMAPPED;
352 #else
353                         ccb->cpi.hba_misc = 0;
354 #endif
355                         ccb->cpi.hba_eng_cnt = 0;
356                         ccb->cpi.max_lun = MRSAS_SCSI_MAX_LUNS;
357                         ccb->cpi.unit_number = cam_sim_unit(sim);
358                         ccb->cpi.bus_id = cam_sim_bus(sim);
359                         ccb->cpi.initiator_id = MRSAS_SCSI_INITIATOR_ID;
360                         ccb->cpi.base_transfer_speed = 150000;
361                         strlcpy(ccb->cpi.sim_vid, "FreeBSD", SIM_IDLEN);
362                         strlcpy(ccb->cpi.hba_vid, "AVAGO", HBA_IDLEN);
363                         strlcpy(ccb->cpi.dev_name, cam_sim_name(sim), DEV_IDLEN);
364                         ccb->cpi.transport = XPORT_SPI;
365                         ccb->cpi.transport_version = 2;
366                         ccb->cpi.protocol = PROTO_SCSI;
367                         ccb->cpi.protocol_version = SCSI_REV_2;
368                         if (ccb->cpi.bus_id == 0)
369                                 ccb->cpi.max_target = MRSAS_MAX_PD - 1;
370                         else
371                                 ccb->cpi.max_target = MRSAS_MAX_LD_IDS - 1;
372 #if (__FreeBSD_version > 704000)
373                         ccb->cpi.maxio = sc->max_num_sge * MRSAS_PAGE_SIZE;
374 #endif
375                         ccb->ccb_h.status = CAM_REQ_CMP;
376                         xpt_done(ccb);
377                         break;
378                 }
379         default:
380                 {
381                         ccb->ccb_h.status = CAM_REQ_INVALID;
382                         xpt_done(ccb);
383                         break;
384                 }
385         }
386 }
387
388 /*
389  * mrsas_scsiio_timeout:        Callback function for IO timed out
390  * input:                                       mpt command context
391  *
392  * This function will execute after timeout value provided by ccb header from
393  * CAM layer, if timer expires. Driver will run timer for all DCDM and LDIO
394  * coming from CAM layer. This function is callback function for IO timeout
395  * and it runs in no-sleep context. Set do_timedout_reset in Adapter context
396  * so that it will execute OCR/Kill adpter from ocr_thread context.
397  */
398 static void
399 mrsas_scsiio_timeout(void *data)
400 {
401         struct mrsas_mpt_cmd *cmd;
402         struct mrsas_softc *sc;
403         u_int32_t target_id;
404
405         if (!data)
406                 return;
407
408         cmd = (struct mrsas_mpt_cmd *)data;
409         sc = cmd->sc;
410
411         if (cmd->ccb_ptr == NULL) {
412                 printf("command timeout with NULL ccb\n");
413                 return;
414         }
415
416         /*
417          * Below callout is dummy entry so that it will be cancelled from
418          * mrsas_cmd_done(). Now Controller will go to OCR/Kill Adapter based
419          * on OCR enable/disable property of Controller from ocr_thread
420          * context.
421          */
422 #if (__FreeBSD_version >= 1000510)
423         callout_reset_sbt(&cmd->cm_callout, SBT_1S * 180, 0,
424             mrsas_scsiio_timeout, cmd, 0);
425 #else
426         callout_reset(&cmd->cm_callout, (180000 * hz) / 1000,
427             mrsas_scsiio_timeout, cmd);
428 #endif
429
430         if (cmd->ccb_ptr->cpi.bus_id == 0)
431                 target_id = cmd->ccb_ptr->ccb_h.target_id;
432         else
433                 target_id = (cmd->ccb_ptr->ccb_h.target_id + (MRSAS_MAX_PD - 1));
434
435         /* Save the cmd to be processed for TM, if it is not there in the array */
436         if (sc->target_reset_pool[target_id] == NULL) {
437                 sc->target_reset_pool[target_id] = cmd;
438                 mrsas_atomic_inc(&sc->target_reset_outstanding);
439         }
440
441         return;
442 }
443
444 /*
445  * mrsas_startio:       SCSI IO entry point
446  * input:                       Adapter instance soft state
447  *                                      pointer to CAM Control Block
448  *
449  * This function is the SCSI IO entry point and it initiates IO processing. It
450  * copies the IO and depending if the IO is read/write or inquiry, it would
451  * call mrsas_build_ldio() or mrsas_build_dcdb(), respectively.  It returns 0
452  * if the command is sent to firmware successfully, otherwise it returns 1.
453  */
454 static int32_t
455 mrsas_startio(struct mrsas_softc *sc, struct cam_sim *sim,
456     union ccb *ccb)
457 {
458         struct mrsas_mpt_cmd *cmd, *r1_cmd = NULL;
459         struct ccb_hdr *ccb_h = &(ccb->ccb_h);
460         struct ccb_scsiio *csio = &(ccb->csio);
461         MRSAS_REQUEST_DESCRIPTOR_UNION *req_desc;
462         u_int8_t cmd_type;
463
464         if ((csio->cdb_io.cdb_bytes[0]) == SYNCHRONIZE_CACHE &&
465                 (!sc->fw_sync_cache_support)) {
466                 ccb->ccb_h.status = CAM_REQ_CMP;
467                 xpt_done(ccb);
468                 return (0);
469         }
470         ccb_h->status |= CAM_SIM_QUEUED;
471         cmd = mrsas_get_mpt_cmd(sc);
472
473         if (!cmd) {
474                 ccb_h->status |= CAM_REQUEUE_REQ;
475                 xpt_done(ccb);
476                 return (0);
477         }
478
479         if ((ccb_h->flags & CAM_DIR_MASK) != CAM_DIR_NONE) {
480                 if (ccb_h->flags & CAM_DIR_IN)
481                         cmd->flags |= MRSAS_DIR_IN;
482                 if (ccb_h->flags & CAM_DIR_OUT)
483                         cmd->flags |= MRSAS_DIR_OUT;
484         } else
485                 cmd->flags = MRSAS_DIR_NONE;    /* no data */
486
487 /* For FreeBSD 9.2 and higher */
488 #if (__FreeBSD_version >= 902001)
489         /*
490          * XXX We don't yet support physical addresses here.
491          */
492         switch ((ccb->ccb_h.flags & CAM_DATA_MASK)) {
493         case CAM_DATA_PADDR:
494         case CAM_DATA_SG_PADDR:
495                 device_printf(sc->mrsas_dev, "%s: physical addresses not supported\n",
496                     __func__);
497                 mrsas_release_mpt_cmd(cmd);
498                 ccb_h->status = CAM_REQ_INVALID;
499                 ccb_h->status &= ~CAM_SIM_QUEUED;
500                 goto done;
501         case CAM_DATA_SG:
502                 device_printf(sc->mrsas_dev, "%s: scatter gather is not supported\n",
503                     __func__);
504                 mrsas_release_mpt_cmd(cmd);
505                 ccb_h->status = CAM_REQ_INVALID;
506                 goto done;
507         case CAM_DATA_VADDR:
508                 if (csio->dxfer_len > (sc->max_num_sge * MRSAS_PAGE_SIZE)) {
509                         mrsas_release_mpt_cmd(cmd);
510                         ccb_h->status = CAM_REQ_TOO_BIG;
511                         goto done;
512                 }
513                 cmd->length = csio->dxfer_len;
514                 if (cmd->length)
515                         cmd->data = csio->data_ptr;
516                 break;
517         case CAM_DATA_BIO:
518                 if (csio->dxfer_len > (sc->max_num_sge * MRSAS_PAGE_SIZE)) {
519                         mrsas_release_mpt_cmd(cmd);
520                         ccb_h->status = CAM_REQ_TOO_BIG;
521                         goto done;
522                 }
523                 cmd->length = csio->dxfer_len;
524                 if (cmd->length)
525                         cmd->data = csio->data_ptr;
526                 break;
527         default:
528                 ccb->ccb_h.status = CAM_REQ_INVALID;
529                 goto done;
530         }
531 #else
532         if (!(ccb_h->flags & CAM_DATA_PHYS)) {  /* Virtual data address */
533                 if (!(ccb_h->flags & CAM_SCATTER_VALID)) {
534                         if (csio->dxfer_len > (sc->max_num_sge * MRSAS_PAGE_SIZE)) {
535                                 mrsas_release_mpt_cmd(cmd);
536                                 ccb_h->status = CAM_REQ_TOO_BIG;
537                                 goto done;
538                         }
539                         cmd->length = csio->dxfer_len;
540                         if (cmd->length)
541                                 cmd->data = csio->data_ptr;
542                 } else {
543                         mrsas_release_mpt_cmd(cmd);
544                         ccb_h->status = CAM_REQ_INVALID;
545                         goto done;
546                 }
547         } else {                        /* Data addresses are physical. */
548                 mrsas_release_mpt_cmd(cmd);
549                 ccb_h->status = CAM_REQ_INVALID;
550                 ccb_h->status &= ~CAM_SIM_QUEUED;
551                 goto done;
552         }
553 #endif
554         /* save ccb ptr */
555         cmd->ccb_ptr = ccb;
556
557         req_desc = mrsas_get_request_desc(sc, (cmd->index) - 1);
558         if (!req_desc) {
559                 device_printf(sc->mrsas_dev, "Cannot get request_descriptor.\n");
560                 return (FAIL);
561         }
562         memset(req_desc, 0, sizeof(MRSAS_REQUEST_DESCRIPTOR_UNION));
563         cmd->request_desc = req_desc;
564
565         if (ccb_h->flags & CAM_CDB_POINTER)
566                 bcopy(csio->cdb_io.cdb_ptr, cmd->io_request->CDB.CDB32, csio->cdb_len);
567         else
568                 bcopy(csio->cdb_io.cdb_bytes, cmd->io_request->CDB.CDB32, csio->cdb_len);
569         mtx_lock(&sc->raidmap_lock);
570
571         /* Check for IO type READ-WRITE targeted for Logical Volume */
572         cmd_type = mrsas_find_io_type(sim, ccb);
573         switch (cmd_type) {
574         case READ_WRITE_LDIO:
575                 /* Build READ-WRITE IO for Logical Volume  */
576                 if (mrsas_build_ldio_rw(sc, cmd, ccb)) {
577                         device_printf(sc->mrsas_dev, "Build RW LDIO failed.\n");
578                         mtx_unlock(&sc->raidmap_lock);
579                         mrsas_release_mpt_cmd(cmd);
580                         return (1);
581                 }
582                 break;
583         case NON_READ_WRITE_LDIO:
584                 /* Build NON READ-WRITE IO for Logical Volume  */
585                 if (mrsas_build_ldio_nonrw(sc, cmd, ccb)) {
586                         device_printf(sc->mrsas_dev, "Build NON-RW LDIO failed.\n");
587                         mtx_unlock(&sc->raidmap_lock);
588                         mrsas_release_mpt_cmd(cmd);
589                         return (1);
590                 }
591                 break;
592         case READ_WRITE_SYSPDIO:
593         case NON_READ_WRITE_SYSPDIO:
594                 if (sc->secure_jbod_support &&
595                     (cmd_type == NON_READ_WRITE_SYSPDIO)) {
596                         /* Build NON-RW IO for JBOD */
597                         if (mrsas_build_syspdio(sc, cmd, ccb, sim, 0)) {
598                                 device_printf(sc->mrsas_dev,
599                                     "Build SYSPDIO failed.\n");
600                                 mtx_unlock(&sc->raidmap_lock);
601                                 mrsas_release_mpt_cmd(cmd);
602                                 return (1);
603                         }
604                 } else {
605                         /* Build RW IO for JBOD */
606                         if (mrsas_build_syspdio(sc, cmd, ccb, sim, 1)) {
607                                 device_printf(sc->mrsas_dev,
608                                     "Build SYSPDIO failed.\n");
609                                 mtx_unlock(&sc->raidmap_lock);
610                                 mrsas_release_mpt_cmd(cmd);
611                                 return (1);
612                         }
613                 }
614         }
615         mtx_unlock(&sc->raidmap_lock);
616
617         if (cmd->flags == MRSAS_DIR_IN) /* from device */
618                 cmd->io_request->Control |= MPI2_SCSIIO_CONTROL_READ;
619         else if (cmd->flags == MRSAS_DIR_OUT)   /* to device */
620                 cmd->io_request->Control |= MPI2_SCSIIO_CONTROL_WRITE;
621
622         cmd->io_request->SGLFlags = MPI2_SGE_FLAGS_64_BIT_ADDRESSING;
623         cmd->io_request->SGLOffset0 = offsetof(MRSAS_RAID_SCSI_IO_REQUEST, SGL) / 4;
624         cmd->io_request->SenseBufferLowAddress = cmd->sense_phys_addr;
625         cmd->io_request->SenseBufferLength = MRSAS_SCSI_SENSE_BUFFERSIZE;
626
627         req_desc = cmd->request_desc;
628         req_desc->SCSIIO.SMID = cmd->index;
629
630         /*
631          * Start timer for IO timeout. Default timeout value is 90 second.
632          */
633         cmd->callout_owner = true;
634 #if (__FreeBSD_version >= 1000510)
635         callout_reset_sbt(&cmd->cm_callout, SBT_1S * 180, 0,
636             mrsas_scsiio_timeout, cmd, 0);
637 #else
638         callout_reset(&cmd->cm_callout, (180000 * hz) / 1000,
639             mrsas_scsiio_timeout, cmd);
640 #endif
641
642         if (mrsas_atomic_inc_return(&sc->fw_outstanding) > sc->io_cmds_highwater)
643                 sc->io_cmds_highwater++;
644
645         /*
646          *  if it is raid 1/10 fp write capable.
647          *  try to get second command from pool and construct it.
648          *  From FW, it has confirmed that lba values of two PDs corresponds to
649          *  single R1/10 LD are always same
650          *
651          */
652         /*
653          * driver side count always should be less than max_fw_cmds to get
654          * new command
655          */
656         if (cmd->r1_alt_dev_handle != MR_DEVHANDLE_INVALID) {
657                 mrsas_atomic_inc(&sc->fw_outstanding);
658                 mrsas_prepare_secondRaid1_IO(sc, cmd);
659                 mrsas_fire_cmd(sc, req_desc->addr.u.low,
660                         req_desc->addr.u.high);
661                 r1_cmd = cmd->peer_cmd;
662                 mrsas_fire_cmd(sc, r1_cmd->request_desc->addr.u.low,
663                                 r1_cmd->request_desc->addr.u.high);
664         } else {
665                 mrsas_fire_cmd(sc, req_desc->addr.u.low,
666                         req_desc->addr.u.high);
667         }
668
669         return (0);
670
671 done:
672         xpt_done(ccb);
673         return (0);
674 }
675
676 /*
677  * mrsas_find_io_type:  Determines if IO is read/write or inquiry
678  * input:                       pointer to CAM Control Block
679  *
680  * This function determines if the IO is read/write or inquiry.  It returns a 1
681  * if the IO is read/write and 0 if it is inquiry.
682  */
683 int 
684 mrsas_find_io_type(struct cam_sim *sim, union ccb *ccb)
685 {
686         struct ccb_scsiio *csio = &(ccb->csio);
687
688         switch (csio->cdb_io.cdb_bytes[0]) {
689         case READ_10:
690         case WRITE_10:
691         case READ_12:
692         case WRITE_12:
693         case READ_6:
694         case WRITE_6:
695         case READ_16:
696         case WRITE_16:
697                 return (cam_sim_bus(sim) ?
698                     READ_WRITE_SYSPDIO : READ_WRITE_LDIO);
699         default:
700                 return (cam_sim_bus(sim) ?
701                     NON_READ_WRITE_SYSPDIO : NON_READ_WRITE_LDIO);
702         }
703 }
704
705 /*
706  * mrsas_get_mpt_cmd:   Get a cmd from free command pool
707  * input:                               Adapter instance soft state
708  *
709  * This function removes an MPT command from the command free list and
710  * initializes it.
711  */
712 struct mrsas_mpt_cmd *
713 mrsas_get_mpt_cmd(struct mrsas_softc *sc)
714 {
715         struct mrsas_mpt_cmd *cmd = NULL;
716
717         mtx_lock(&sc->mpt_cmd_pool_lock);
718         if (!TAILQ_EMPTY(&sc->mrsas_mpt_cmd_list_head)) {
719                 cmd = TAILQ_FIRST(&sc->mrsas_mpt_cmd_list_head);
720                 TAILQ_REMOVE(&sc->mrsas_mpt_cmd_list_head, cmd, next);
721         } else {
722                 goto out;
723         }
724
725         memset((uint8_t *)cmd->io_request, 0, MRSAS_MPI2_RAID_DEFAULT_IO_FRAME_SIZE);
726         cmd->data = NULL;
727         cmd->length = 0;
728         cmd->flags = 0;
729         cmd->error_code = 0;
730         cmd->load_balance = 0;
731         cmd->ccb_ptr = NULL;
732 out:
733         mtx_unlock(&sc->mpt_cmd_pool_lock);
734         return cmd;
735 }
736
737 /*
738  * mrsas_release_mpt_cmd:       Return a cmd to free command pool
739  * input:                                       Command packet for return to free command pool
740  *
741  * This function returns an MPT command to the free command list.
742  */
743 void
744 mrsas_release_mpt_cmd(struct mrsas_mpt_cmd *cmd)
745 {
746         struct mrsas_softc *sc = cmd->sc;
747
748         mtx_lock(&sc->mpt_cmd_pool_lock);
749         cmd->r1_alt_dev_handle = MR_DEVHANDLE_INVALID;
750         cmd->sync_cmd_idx = (u_int32_t)MRSAS_ULONG_MAX;
751         cmd->peer_cmd = NULL;
752         cmd->cmd_completed = 0;
753         memset((uint8_t *)cmd->io_request, 0,
754                 sizeof(MRSAS_RAID_SCSI_IO_REQUEST));
755         TAILQ_INSERT_HEAD(&(sc->mrsas_mpt_cmd_list_head), cmd, next);
756         mtx_unlock(&sc->mpt_cmd_pool_lock);
757
758         return;
759 }
760
761 /*
762  * mrsas_get_request_desc:      Get request descriptor from array
763  * input:                                       Adapter instance soft state
764  *                                                      SMID index
765  *
766  * This function returns a pointer to the request descriptor.
767  */
768 MRSAS_REQUEST_DESCRIPTOR_UNION *
769 mrsas_get_request_desc(struct mrsas_softc *sc, u_int16_t index)
770 {
771         u_int8_t *p;
772
773         KASSERT(index < sc->max_fw_cmds, ("req_desc is out of range"));
774         p = sc->req_desc + sizeof(MRSAS_REQUEST_DESCRIPTOR_UNION) * index;
775
776         return (MRSAS_REQUEST_DESCRIPTOR_UNION *) p;
777 }
778
779
780
781
782 /* mrsas_prepare_secondRaid1_IO
783  * It prepares the raid 1 second IO
784  */
785 void
786 mrsas_prepare_secondRaid1_IO(struct mrsas_softc *sc,
787     struct mrsas_mpt_cmd *cmd)
788 {
789         MRSAS_REQUEST_DESCRIPTOR_UNION *req_desc, *req_desc2 = NULL;
790         struct mrsas_mpt_cmd *r1_cmd;
791
792         r1_cmd = cmd->peer_cmd;
793         req_desc = cmd->request_desc;
794
795         /*
796          * copy the io request frame as well as 8 SGEs data for r1
797          * command
798          */
799         memcpy(r1_cmd->io_request, cmd->io_request,
800             (sizeof(MRSAS_RAID_SCSI_IO_REQUEST)));
801         memcpy(&r1_cmd->io_request->SGL, &cmd->io_request->SGL,
802             (sc->max_sge_in_main_msg * sizeof(MPI2_SGE_IO_UNION)));
803
804         /* sense buffer is different for r1 command */
805         r1_cmd->io_request->SenseBufferLowAddress = r1_cmd->sense_phys_addr;
806         r1_cmd->ccb_ptr = cmd->ccb_ptr;
807
808         req_desc2 = mrsas_get_request_desc(sc, r1_cmd->index - 1);
809         req_desc2->addr.Words = 0;
810         r1_cmd->request_desc = req_desc2;
811         req_desc2->SCSIIO.SMID = r1_cmd->index;
812         req_desc2->SCSIIO.RequestFlags = req_desc->SCSIIO.RequestFlags;
813         r1_cmd->request_desc->SCSIIO.DevHandle = cmd->r1_alt_dev_handle;
814         r1_cmd->r1_alt_dev_handle =  cmd->io_request->DevHandle;
815         r1_cmd->io_request->DevHandle = cmd->r1_alt_dev_handle;
816         cmd->io_request->RaidContext.raid_context_g35.smid.peerSMID =
817             r1_cmd->index;
818         r1_cmd->io_request->RaidContext.raid_context_g35.smid.peerSMID =
819                 cmd->index;
820         /*
821          * MSIxIndex of both commands request descriptors
822          * should be same
823          */
824         r1_cmd->request_desc->SCSIIO.MSIxIndex = cmd->request_desc->SCSIIO.MSIxIndex;
825         /* span arm is different for r1 cmd */
826         r1_cmd->io_request->RaidContext.raid_context_g35.spanArm =
827             cmd->io_request->RaidContext.raid_context_g35.spanArm + 1;
828
829 }
830
831
832 /*
833  * mrsas_build_ldio_rw: Builds an LDIO command
834  * input:                               Adapter instance soft state
835  *                                              Pointer to command packet
836  *                                              Pointer to CCB
837  *
838  * This function builds the LDIO command packet.  It returns 0 if the command is
839  * built successfully, otherwise it returns a 1.
840  */
841 int
842 mrsas_build_ldio_rw(struct mrsas_softc *sc, struct mrsas_mpt_cmd *cmd,
843     union ccb *ccb)
844 {
845         struct ccb_hdr *ccb_h = &(ccb->ccb_h);
846         struct ccb_scsiio *csio = &(ccb->csio);
847         u_int32_t device_id;
848         MRSAS_RAID_SCSI_IO_REQUEST *io_request;
849
850         device_id = ccb_h->target_id;
851
852         io_request = cmd->io_request;
853         io_request->RaidContext.raid_context.VirtualDiskTgtId = device_id;
854         io_request->RaidContext.raid_context.status = 0;
855         io_request->RaidContext.raid_context.exStatus = 0;
856
857         /* just the cdb len, other flags zero, and ORed-in later for FP */
858         io_request->IoFlags = csio->cdb_len;
859
860         if (mrsas_setup_io(sc, cmd, ccb, device_id, io_request) != SUCCESS)
861                 device_printf(sc->mrsas_dev, "Build ldio or fpio error\n");
862
863         io_request->DataLength = cmd->length;
864
865         if (mrsas_map_request(sc, cmd, ccb) == SUCCESS) {
866                 if (cmd->sge_count > sc->max_num_sge) {
867                         device_printf(sc->mrsas_dev, "Error: sge_count (0x%x) exceeds"
868                             "max (0x%x) allowed\n", cmd->sge_count, sc->max_num_sge);
869                         return (FAIL);
870                 }
871                 if (sc->is_ventura || sc->is_aero)
872                         io_request->RaidContext.raid_context_g35.numSGE = cmd->sge_count;
873                 else {
874                         /*
875                          * numSGE store lower 8 bit of sge_count. numSGEExt store
876                          * higher 8 bit of sge_count
877                          */
878                         io_request->RaidContext.raid_context.numSGE = cmd->sge_count;
879                         io_request->RaidContext.raid_context.numSGEExt = (uint8_t)(cmd->sge_count >> 8);
880                 }
881
882         } else {
883                 device_printf(sc->mrsas_dev, "Data map/load failed.\n");
884                 return (FAIL);
885         }
886         return (0);
887 }
888
889 /* stream detection on read and and write IOs */
890 static void
891 mrsas_stream_detect(struct mrsas_softc *sc, struct mrsas_mpt_cmd *cmd,
892     struct IO_REQUEST_INFO *io_info)
893 {
894         u_int32_t device_id = io_info->ldTgtId;
895         LD_STREAM_DETECT *current_ld_SD = sc->streamDetectByLD[device_id];
896         u_int32_t *track_stream = &current_ld_SD->mruBitMap;
897         u_int32_t streamNum, shiftedValues, unshiftedValues;
898         u_int32_t indexValueMask, shiftedValuesMask;
899         int i;
900         boolean_t isReadAhead = false;
901         STREAM_DETECT *current_SD;
902
903         /* find possible stream */
904         for (i = 0; i < MAX_STREAMS_TRACKED; ++i) {
905                 streamNum = (*track_stream >> (i * BITS_PER_INDEX_STREAM)) &
906                                 STREAM_MASK;
907                 current_SD = &current_ld_SD->streamTrack[streamNum];
908                 /*
909                  * if we found a stream, update the raid context and
910                  * also update the mruBitMap
911                  */
912                 if (current_SD->nextSeqLBA &&
913                     io_info->ldStartBlock >= current_SD->nextSeqLBA &&
914                     (io_info->ldStartBlock <= (current_SD->nextSeqLBA+32)) &&
915                     (current_SD->isRead == io_info->isRead)) {
916                         if (io_info->ldStartBlock != current_SD->nextSeqLBA &&
917                             (!io_info->isRead || !isReadAhead)) {
918                                 /*
919                                  * Once the API availible we need to change this.
920                                  * At this point we are not allowing any gap
921                                  */
922                                 continue;
923                         }
924                         cmd->io_request->RaidContext.raid_context_g35.streamDetected = TRUE;
925                         current_SD->nextSeqLBA = io_info->ldStartBlock + io_info->numBlocks;
926                         /*
927                          * update the mruBitMap LRU
928                          */
929                         shiftedValuesMask = (1 << i * BITS_PER_INDEX_STREAM) - 1 ;
930                         shiftedValues = ((*track_stream & shiftedValuesMask) <<
931                             BITS_PER_INDEX_STREAM);
932                         indexValueMask = STREAM_MASK << i * BITS_PER_INDEX_STREAM;
933                         unshiftedValues = (*track_stream) &
934                             (~(shiftedValuesMask | indexValueMask));
935                         *track_stream =
936                             (unshiftedValues | shiftedValues | streamNum);
937                         return;
938                 }
939         }
940         /*
941          * if we did not find any stream, create a new one from the least recently used
942          */
943         streamNum = (*track_stream >>
944             ((MAX_STREAMS_TRACKED - 1) * BITS_PER_INDEX_STREAM)) & STREAM_MASK;
945         current_SD = &current_ld_SD->streamTrack[streamNum];
946         current_SD->isRead = io_info->isRead;
947         current_SD->nextSeqLBA = io_info->ldStartBlock + io_info->numBlocks;
948         *track_stream = (((*track_stream & ZERO_LAST_STREAM) << 4) | streamNum);
949         return;
950 }
951
952
953 /*
954  * mrsas_setup_io:      Set up data including Fast Path I/O
955  * input:                       Adapter instance soft state
956  *                                      Pointer to command packet
957  *                                      Pointer to CCB
958  *
959  * This function builds the DCDB inquiry command.  It returns 0 if the command
960  * is built successfully, otherwise it returns a 1.
961  */
962 int
963 mrsas_setup_io(struct mrsas_softc *sc, struct mrsas_mpt_cmd *cmd,
964     union ccb *ccb, u_int32_t device_id,
965     MRSAS_RAID_SCSI_IO_REQUEST * io_request)
966 {
967         struct ccb_hdr *ccb_h = &(ccb->ccb_h);
968         struct ccb_scsiio *csio = &(ccb->csio);
969         struct IO_REQUEST_INFO io_info;
970         MR_DRV_RAID_MAP_ALL *map_ptr;
971         struct mrsas_mpt_cmd *r1_cmd = NULL;
972
973         MR_LD_RAID *raid;
974         u_int8_t fp_possible;
975         u_int32_t start_lba_hi, start_lba_lo, ld_block_size, ld;
976         u_int32_t datalength = 0;
977
978         io_request->RaidContext.raid_context.VirtualDiskTgtId = device_id;
979
980         start_lba_lo = 0;
981         start_lba_hi = 0;
982         fp_possible = 0;
983
984         /*
985          * READ_6 (0x08) or WRITE_6 (0x0A) cdb
986          */
987         if (csio->cdb_len == 6) {
988                 datalength = (u_int32_t)csio->cdb_io.cdb_bytes[4];
989                 start_lba_lo = ((u_int32_t)csio->cdb_io.cdb_bytes[1] << 16) |
990                     ((u_int32_t)csio->cdb_io.cdb_bytes[2] << 8) |
991                     (u_int32_t)csio->cdb_io.cdb_bytes[3];
992                 start_lba_lo &= 0x1FFFFF;
993         }
994         /*
995          * READ_10 (0x28) or WRITE_6 (0x2A) cdb
996          */
997         else if (csio->cdb_len == 10) {
998                 datalength = (u_int32_t)csio->cdb_io.cdb_bytes[8] |
999                     ((u_int32_t)csio->cdb_io.cdb_bytes[7] << 8);
1000                 start_lba_lo = ((u_int32_t)csio->cdb_io.cdb_bytes[2] << 24) |
1001                     ((u_int32_t)csio->cdb_io.cdb_bytes[3] << 16) |
1002                     (u_int32_t)csio->cdb_io.cdb_bytes[4] << 8 |
1003                     ((u_int32_t)csio->cdb_io.cdb_bytes[5]);
1004         }
1005         /*
1006          * READ_12 (0xA8) or WRITE_12 (0xAA) cdb
1007          */
1008         else if (csio->cdb_len == 12) {
1009                 datalength = (u_int32_t)csio->cdb_io.cdb_bytes[6] << 24 |
1010                     ((u_int32_t)csio->cdb_io.cdb_bytes[7] << 16) |
1011                     ((u_int32_t)csio->cdb_io.cdb_bytes[8] << 8) |
1012                     ((u_int32_t)csio->cdb_io.cdb_bytes[9]);
1013                 start_lba_lo = ((u_int32_t)csio->cdb_io.cdb_bytes[2] << 24) |
1014                     ((u_int32_t)csio->cdb_io.cdb_bytes[3] << 16) |
1015                     (u_int32_t)csio->cdb_io.cdb_bytes[4] << 8 |
1016                     ((u_int32_t)csio->cdb_io.cdb_bytes[5]);
1017         }
1018         /*
1019          * READ_16 (0x88) or WRITE_16 (0xx8A) cdb
1020          */
1021         else if (csio->cdb_len == 16) {
1022                 datalength = (u_int32_t)csio->cdb_io.cdb_bytes[10] << 24 |
1023                     ((u_int32_t)csio->cdb_io.cdb_bytes[11] << 16) |
1024                     ((u_int32_t)csio->cdb_io.cdb_bytes[12] << 8) |
1025                     ((u_int32_t)csio->cdb_io.cdb_bytes[13]);
1026                 start_lba_lo = ((u_int32_t)csio->cdb_io.cdb_bytes[6] << 24) |
1027                     ((u_int32_t)csio->cdb_io.cdb_bytes[7] << 16) |
1028                     (u_int32_t)csio->cdb_io.cdb_bytes[8] << 8 |
1029                     ((u_int32_t)csio->cdb_io.cdb_bytes[9]);
1030                 start_lba_hi = ((u_int32_t)csio->cdb_io.cdb_bytes[2] << 24) |
1031                     ((u_int32_t)csio->cdb_io.cdb_bytes[3] << 16) |
1032                     (u_int32_t)csio->cdb_io.cdb_bytes[4] << 8 |
1033                     ((u_int32_t)csio->cdb_io.cdb_bytes[5]);
1034         }
1035         memset(&io_info, 0, sizeof(struct IO_REQUEST_INFO));
1036         io_info.ldStartBlock = ((u_int64_t)start_lba_hi << 32) | start_lba_lo;
1037         io_info.numBlocks = datalength;
1038         io_info.ldTgtId = device_id;
1039         io_info.r1_alt_dev_handle = MR_DEVHANDLE_INVALID;
1040
1041         io_request->DataLength = cmd->length;
1042
1043         switch (ccb_h->flags & CAM_DIR_MASK) {
1044         case CAM_DIR_IN:
1045                 io_info.isRead = 1;
1046                 break;
1047         case CAM_DIR_OUT:
1048                 io_info.isRead = 0;
1049                 break;
1050         case CAM_DIR_NONE:
1051         default:
1052                 mrsas_dprint(sc, MRSAS_TRACE, "From %s : DMA Flag is %d \n", __func__, ccb_h->flags & CAM_DIR_MASK);
1053                 break;
1054         }
1055
1056         map_ptr = sc->ld_drv_map[(sc->map_id & 1)];
1057         ld_block_size = MR_LdBlockSizeGet(device_id, map_ptr, sc);
1058
1059         ld = MR_TargetIdToLdGet(device_id, map_ptr);
1060         if ((ld >= MAX_LOGICAL_DRIVES_EXT) || (!sc->fast_path_io)) {
1061                 io_request->RaidContext.raid_context.regLockFlags = 0;
1062                 fp_possible = 0;
1063         } else {
1064                 if (MR_BuildRaidContext(sc, &io_info, &io_request->RaidContext.raid_context, map_ptr))
1065                         fp_possible = io_info.fpOkForIo;
1066         }
1067
1068         raid = MR_LdRaidGet(ld, map_ptr);
1069         /* Store the TM capability value in cmd */
1070         cmd->tmCapable = raid->capability.tmCapable;
1071
1072         cmd->request_desc->SCSIIO.MSIxIndex =
1073             sc->msix_vectors ? smp_processor_id() % sc->msix_vectors : 0;
1074
1075         if (sc->is_ventura || sc->is_aero) {
1076                 if (sc->streamDetectByLD) {
1077                         mtx_lock(&sc->stream_lock);
1078                         mrsas_stream_detect(sc, cmd, &io_info);
1079                         mtx_unlock(&sc->stream_lock);
1080                         /* In ventura if stream detected for a read and
1081                          * it is read ahead capable make this IO as LDIO */
1082                         if (io_request->RaidContext.raid_context_g35.streamDetected &&
1083                                         io_info.isRead && io_info.raCapable)
1084                                 fp_possible = FALSE;
1085                 }
1086
1087                 /* Set raid 1/10 fast path write capable bit in io_info.
1088                  * Note - reset peer_cmd and r1_alt_dev_handle if fp_possible
1089                  * disabled after this point. Try not to add more check for
1090                  * fp_possible toggle after this.
1091                  */
1092                 if (fp_possible &&
1093                                 (io_info.r1_alt_dev_handle != MR_DEVHANDLE_INVALID) &&
1094                                 (raid->level == 1) && !io_info.isRead) {
1095                         r1_cmd = mrsas_get_mpt_cmd(sc);
1096                         if (!r1_cmd) {
1097                                 fp_possible = FALSE;
1098                                 printf("Avago debug fp disable from %s %d \n",
1099                                         __func__, __LINE__);
1100                         } else {
1101                                 cmd->peer_cmd = r1_cmd;
1102                                 r1_cmd->peer_cmd = cmd;
1103                         }
1104                 }
1105         }
1106
1107         if (fp_possible) {
1108                 mrsas_set_pd_lba(io_request, csio->cdb_len, &io_info, ccb, map_ptr,
1109                     start_lba_lo, ld_block_size);
1110                 io_request->Function = MPI2_FUNCTION_SCSI_IO_REQUEST;
1111                 cmd->request_desc->SCSIIO.RequestFlags =
1112                     (MPI2_REQ_DESCRIPT_FLAGS_FP_IO <<
1113                     MRSAS_REQ_DESCRIPT_FLAGS_TYPE_SHIFT);
1114                 if (sc->mrsas_gen3_ctrl) {
1115                         if (io_request->RaidContext.raid_context.regLockFlags == REGION_TYPE_UNUSED)
1116                                 cmd->request_desc->SCSIIO.RequestFlags =
1117                                     (MRSAS_REQ_DESCRIPT_FLAGS_NO_LOCK <<
1118                                     MRSAS_REQ_DESCRIPT_FLAGS_TYPE_SHIFT);
1119                         io_request->RaidContext.raid_context.Type = MPI2_TYPE_CUDA;
1120                         io_request->RaidContext.raid_context.nseg = 0x1;
1121                         io_request->IoFlags |= MPI25_SAS_DEVICE0_FLAGS_ENABLED_FAST_PATH;
1122                         io_request->RaidContext.raid_context.regLockFlags |=
1123                             (MR_RL_FLAGS_GRANT_DESTINATION_CUDA |
1124                             MR_RL_FLAGS_SEQ_NUM_ENABLE);
1125                 } else if (sc->is_ventura || sc->is_aero) {
1126                         io_request->RaidContext.raid_context_g35.Type = MPI2_TYPE_CUDA;
1127                         io_request->RaidContext.raid_context_g35.nseg = 0x1;
1128                         io_request->RaidContext.raid_context_g35.routingFlags.bits.sqn = 1;
1129                         io_request->IoFlags |= MPI25_SAS_DEVICE0_FLAGS_ENABLED_FAST_PATH;
1130                         if (io_request->RaidContext.raid_context_g35.routingFlags.bits.sld) {
1131                                         io_request->RaidContext.raid_context_g35.RAIDFlags =
1132                                         (MR_RAID_FLAGS_IO_SUB_TYPE_CACHE_BYPASS
1133                                         << MR_RAID_CTX_RAID_FLAGS_IO_SUB_TYPE_SHIFT);
1134                         }
1135                 }
1136                 if ((sc->load_balance_info[device_id].loadBalanceFlag) &&
1137                     (io_info.isRead)) {
1138                         io_info.devHandle =
1139                             mrsas_get_updated_dev_handle(sc,
1140                             &sc->load_balance_info[device_id], &io_info);
1141                         cmd->load_balance = MRSAS_LOAD_BALANCE_FLAG;
1142                         cmd->pd_r1_lb = io_info.pd_after_lb;
1143                         if (sc->is_ventura || sc->is_aero)
1144                                 io_request->RaidContext.raid_context_g35.spanArm = io_info.span_arm;
1145                         else
1146                                 io_request->RaidContext.raid_context.spanArm = io_info.span_arm;
1147                 } else
1148                         cmd->load_balance = 0;
1149
1150                 if (sc->is_ventura || sc->is_aero)
1151                                 cmd->r1_alt_dev_handle = io_info.r1_alt_dev_handle;
1152                 else
1153                                 cmd->r1_alt_dev_handle = MR_DEVHANDLE_INVALID;
1154
1155                 cmd->request_desc->SCSIIO.DevHandle = io_info.devHandle;
1156                 io_request->DevHandle = io_info.devHandle;
1157                 cmd->pdInterface = io_info.pdInterface;
1158         } else {
1159                 /* Not FP IO */
1160                 io_request->RaidContext.raid_context.timeoutValue = map_ptr->raidMap.fpPdIoTimeoutSec;
1161                 cmd->request_desc->SCSIIO.RequestFlags =
1162                     (MRSAS_REQ_DESCRIPT_FLAGS_LD_IO <<
1163                     MRSAS_REQ_DESCRIPT_FLAGS_TYPE_SHIFT);
1164                 if (sc->mrsas_gen3_ctrl) {
1165                         if (io_request->RaidContext.raid_context.regLockFlags == REGION_TYPE_UNUSED)
1166                                 cmd->request_desc->SCSIIO.RequestFlags =
1167                                     (MRSAS_REQ_DESCRIPT_FLAGS_NO_LOCK <<
1168                                     MRSAS_REQ_DESCRIPT_FLAGS_TYPE_SHIFT);
1169                         io_request->RaidContext.raid_context.Type = MPI2_TYPE_CUDA;
1170                         io_request->RaidContext.raid_context.regLockFlags |=
1171                             (MR_RL_FLAGS_GRANT_DESTINATION_CPU0 |
1172                             MR_RL_FLAGS_SEQ_NUM_ENABLE);
1173                         io_request->RaidContext.raid_context.nseg = 0x1;
1174                 } else if (sc->is_ventura || sc->is_aero) {
1175                         io_request->RaidContext.raid_context_g35.Type = MPI2_TYPE_CUDA;
1176                         io_request->RaidContext.raid_context_g35.routingFlags.bits.sqn = 1;
1177                         io_request->RaidContext.raid_context_g35.nseg = 0x1;
1178                 }
1179                 io_request->Function = MRSAS_MPI2_FUNCTION_LD_IO_REQUEST;
1180                 io_request->DevHandle = device_id;
1181         }
1182         return (0);
1183 }
1184
1185 /*
1186  * mrsas_build_ldio_nonrw:      Builds an LDIO command
1187  * input:                               Adapter instance soft state
1188  *                                              Pointer to command packet
1189  *                                              Pointer to CCB
1190  *
1191  * This function builds the LDIO command packet.  It returns 0 if the command is
1192  * built successfully, otherwise it returns a 1.
1193  */
1194 int
1195 mrsas_build_ldio_nonrw(struct mrsas_softc *sc, struct mrsas_mpt_cmd *cmd,
1196     union ccb *ccb)
1197 {
1198         struct ccb_hdr *ccb_h = &(ccb->ccb_h);
1199         u_int32_t device_id, ld;
1200         MR_DRV_RAID_MAP_ALL *map_ptr;
1201         MR_LD_RAID *raid;
1202         RAID_CONTEXT *pRAID_Context;
1203         MRSAS_RAID_SCSI_IO_REQUEST *io_request;
1204
1205         io_request = cmd->io_request;
1206         device_id = ccb_h->target_id;
1207
1208         map_ptr = sc->ld_drv_map[(sc->map_id & 1)];
1209         ld = MR_TargetIdToLdGet(device_id, map_ptr);
1210         raid = MR_LdRaidGet(ld, map_ptr);
1211         /* get RAID_Context pointer */
1212         pRAID_Context = &io_request->RaidContext.raid_context;
1213         /* Store the TM capability value in cmd */
1214         cmd->tmCapable = raid->capability.tmCapable;
1215
1216         /* FW path for LD Non-RW (SCSI management commands) */
1217         io_request->Function = MRSAS_MPI2_FUNCTION_LD_IO_REQUEST;
1218         io_request->DevHandle = device_id;
1219         cmd->request_desc->SCSIIO.RequestFlags =
1220             (MPI2_REQ_DESCRIPT_FLAGS_SCSI_IO <<
1221             MRSAS_REQ_DESCRIPT_FLAGS_TYPE_SHIFT);
1222
1223         io_request->RaidContext.raid_context.VirtualDiskTgtId = device_id;
1224         io_request->LUN[1] = ccb_h->target_lun & 0xF;
1225         io_request->DataLength = cmd->length;
1226
1227         if (mrsas_map_request(sc, cmd, ccb) == SUCCESS) {
1228                 if (cmd->sge_count > sc->max_num_sge) {
1229                         device_printf(sc->mrsas_dev, "Error: sge_count (0x%x) exceeds"
1230                             "max (0x%x) allowed\n", cmd->sge_count, sc->max_num_sge);
1231                         return (1);
1232                 }
1233                 if (sc->is_ventura || sc->is_aero)
1234                         io_request->RaidContext.raid_context_g35.numSGE = cmd->sge_count;
1235                 else {
1236                         /*
1237                          * numSGE store lower 8 bit of sge_count. numSGEExt store
1238                          * higher 8 bit of sge_count
1239                          */
1240                         io_request->RaidContext.raid_context.numSGE = cmd->sge_count;
1241                         io_request->RaidContext.raid_context.numSGEExt = (uint8_t)(cmd->sge_count >> 8);
1242                 }
1243         } else {
1244                 device_printf(sc->mrsas_dev, "Data map/load failed.\n");
1245                 return (1);
1246         }
1247         return (0);
1248 }
1249
1250 /*
1251  * mrsas_build_syspdio: Builds an DCDB command
1252  * input:                               Adapter instance soft state
1253  *                                              Pointer to command packet
1254  *                                              Pointer to CCB
1255  *
1256  * This function builds the DCDB inquiry command.  It returns 0 if the command
1257  * is built successfully, otherwise it returns a 1.
1258  */
1259 int
1260 mrsas_build_syspdio(struct mrsas_softc *sc, struct mrsas_mpt_cmd *cmd,
1261     union ccb *ccb, struct cam_sim *sim, u_int8_t fp_possible)
1262 {
1263         struct ccb_hdr *ccb_h = &(ccb->ccb_h);
1264         u_int32_t device_id;
1265         MR_DRV_RAID_MAP_ALL *local_map_ptr;
1266         MRSAS_RAID_SCSI_IO_REQUEST *io_request;
1267         RAID_CONTEXT *pRAID_Context;
1268         struct MR_PD_CFG_SEQ_NUM_SYNC *pd_sync;
1269
1270         io_request = cmd->io_request;
1271         /* get RAID_Context pointer */
1272         pRAID_Context = &io_request->RaidContext.raid_context;
1273         device_id = ccb_h->target_id;
1274         local_map_ptr = sc->ld_drv_map[(sc->map_id & 1)];
1275         io_request->RaidContext.raid_context.RAIDFlags = MR_RAID_FLAGS_IO_SUB_TYPE_SYSTEM_PD
1276             << MR_RAID_CTX_RAID_FLAGS_IO_SUB_TYPE_SHIFT;
1277         io_request->RaidContext.raid_context.regLockFlags = 0;
1278         io_request->RaidContext.raid_context.regLockRowLBA = 0;
1279         io_request->RaidContext.raid_context.regLockLength = 0;
1280
1281         cmd->pdInterface = sc->target_list[device_id].interface_type;
1282
1283         /* If FW supports PD sequence number */
1284         if (sc->use_seqnum_jbod_fp &&
1285             sc->pd_list[device_id].driveType == 0x00) {
1286                 //printf("Using Drv seq num\n");
1287                 pd_sync = (void *)sc->jbodmap_mem[(sc->pd_seq_map_id - 1) & 1];
1288                 cmd->tmCapable = pd_sync->seq[device_id].capability.tmCapable;
1289                 /* More than 256 PD/JBOD support for Ventura */
1290                 if (sc->support_morethan256jbod)
1291                         io_request->RaidContext.raid_context.VirtualDiskTgtId =
1292                                 pd_sync->seq[device_id].pdTargetId;
1293                 else
1294                         io_request->RaidContext.raid_context.VirtualDiskTgtId =
1295                                 device_id + 255;
1296                 io_request->RaidContext.raid_context.configSeqNum = pd_sync->seq[device_id].seqNum;
1297                 io_request->DevHandle = pd_sync->seq[device_id].devHandle;
1298                 if (sc->is_ventura || sc->is_aero)
1299                         io_request->RaidContext.raid_context_g35.routingFlags.bits.sqn = 1;
1300                 else
1301                         io_request->RaidContext.raid_context.regLockFlags |=
1302                             (MR_RL_FLAGS_SEQ_NUM_ENABLE | MR_RL_FLAGS_GRANT_DESTINATION_CUDA);
1303                 /* raid_context.Type = MPI2_TYPE_CUDA is valid only,
1304                  * if FW support Jbod Sequence number
1305                  */
1306                 io_request->RaidContext.raid_context.Type = MPI2_TYPE_CUDA;
1307                 io_request->RaidContext.raid_context.nseg = 0x1;
1308         } else if (sc->fast_path_io) {
1309                 //printf("Using LD RAID map\n");
1310                 io_request->RaidContext.raid_context.VirtualDiskTgtId = device_id;
1311                 io_request->RaidContext.raid_context.configSeqNum = 0;
1312                 local_map_ptr = sc->ld_drv_map[(sc->map_id & 1)];
1313                 io_request->DevHandle =
1314                     local_map_ptr->raidMap.devHndlInfo[device_id].curDevHdl;
1315         } else {
1316                 //printf("Using FW PATH\n");
1317                 /* Want to send all IO via FW path */
1318                 io_request->RaidContext.raid_context.VirtualDiskTgtId = device_id;
1319                 io_request->RaidContext.raid_context.configSeqNum = 0;
1320                 io_request->DevHandle = MR_DEVHANDLE_INVALID;
1321         }
1322
1323         cmd->request_desc->SCSIIO.DevHandle = io_request->DevHandle;
1324         cmd->request_desc->SCSIIO.MSIxIndex =
1325             sc->msix_vectors ? smp_processor_id() % sc->msix_vectors : 0;
1326
1327         if (!fp_possible) {
1328                 /* system pd firmware path */
1329                 io_request->Function = MRSAS_MPI2_FUNCTION_LD_IO_REQUEST;
1330                 cmd->request_desc->SCSIIO.RequestFlags =
1331                     (MPI2_REQ_DESCRIPT_FLAGS_SCSI_IO <<
1332                     MRSAS_REQ_DESCRIPT_FLAGS_TYPE_SHIFT);
1333                 io_request->RaidContext.raid_context.timeoutValue =
1334                     local_map_ptr->raidMap.fpPdIoTimeoutSec;
1335                 io_request->RaidContext.raid_context.VirtualDiskTgtId = device_id;
1336         } else {
1337                 /* system pd fast path */
1338                 io_request->Function = MPI2_FUNCTION_SCSI_IO_REQUEST;
1339                 io_request->RaidContext.raid_context.timeoutValue = local_map_ptr->raidMap.fpPdIoTimeoutSec;
1340
1341                 /*
1342                  * NOTE - For system pd RW cmds only IoFlags will be FAST_PATH
1343                  * Because the NON RW cmds will now go via FW Queue
1344                  * and not the Exception queue
1345                  */
1346                 if (sc->mrsas_gen3_ctrl || sc->is_ventura || sc->is_aero)
1347                         io_request->IoFlags |= MPI25_SAS_DEVICE0_FLAGS_ENABLED_FAST_PATH;
1348
1349                 cmd->request_desc->SCSIIO.RequestFlags =
1350                     (MPI2_REQ_DESCRIPT_FLAGS_FP_IO <<
1351                     MRSAS_REQ_DESCRIPT_FLAGS_TYPE_SHIFT);
1352         }
1353
1354         io_request->LUN[1] = ccb_h->target_lun & 0xF;
1355         io_request->DataLength = cmd->length;
1356
1357         if (mrsas_map_request(sc, cmd, ccb) == SUCCESS) {
1358                 if (cmd->sge_count > sc->max_num_sge) {
1359                         device_printf(sc->mrsas_dev, "Error: sge_count (0x%x) exceeds"
1360                             "max (0x%x) allowed\n", cmd->sge_count, sc->max_num_sge);
1361                         return (1);
1362                 }
1363                 if (sc->is_ventura || sc->is_aero)
1364                         io_request->RaidContext.raid_context_g35.numSGE = cmd->sge_count;
1365                 else {
1366                         /*
1367                          * numSGE store lower 8 bit of sge_count. numSGEExt store
1368                          * higher 8 bit of sge_count
1369                          */
1370                         io_request->RaidContext.raid_context.numSGE = cmd->sge_count;
1371                         io_request->RaidContext.raid_context.numSGEExt = (uint8_t)(cmd->sge_count >> 8);
1372                 }
1373         } else {
1374                 device_printf(sc->mrsas_dev, "Data map/load failed.\n");
1375                 return (1);
1376         }
1377         return (0);
1378 }
1379
1380 /*
1381  * mrsas_is_prp_possible:       This function will tell whether PRPs should be built or not
1382  * sc:                                          Adapter instance soft state
1383  * cmd:                                         MPT command frame pointer
1384  * nsesg:                                       Number of OS SGEs
1385  *
1386  * This function will check whether IO is qualified to build PRPs
1387  * return:                              true: if PRP should be built
1388  *                                              false: if IEEE SGLs should be built
1389  */
1390 static boolean_t mrsas_is_prp_possible(struct mrsas_mpt_cmd *cmd,
1391         bus_dma_segment_t *segs, int nsegs)
1392 {
1393         struct mrsas_softc *sc = cmd->sc;
1394         int i;
1395         u_int32_t data_length = 0;
1396         bool build_prp = false;
1397         u_int32_t mr_nvme_pg_size;
1398
1399         mr_nvme_pg_size = max(sc->nvme_page_size, MR_DEFAULT_NVME_PAGE_SIZE);
1400         data_length = cmd->length;
1401
1402         if (data_length > (mr_nvme_pg_size * 5))
1403                 build_prp = true;
1404         else if ((data_length > (mr_nvme_pg_size * 4)) &&
1405                 (data_length <= (mr_nvme_pg_size * 5)))  {
1406                 /* check if 1st SG entry size is < residual beyond 4 pages */
1407                 if ((segs[0].ds_len) < (data_length - (mr_nvme_pg_size * 4)))
1408                         build_prp = true;
1409         }
1410
1411         /*check for SGE holes here*/
1412         for (i = 0; i < nsegs; i++) {
1413                 /* check for mid SGEs */
1414                 if ((i != 0) && (i != (nsegs - 1))) {
1415                                 if ((segs[i].ds_addr % mr_nvme_pg_size) ||
1416                                         (segs[i].ds_len % mr_nvme_pg_size)) {
1417                                         build_prp = false;
1418                                         mrsas_atomic_inc(&sc->sge_holes);
1419                                         break;
1420                                 }
1421                 }
1422
1423                 /* check for first SGE*/
1424                 if ((nsegs > 1) && (i == 0)) {
1425                                 if ((segs[i].ds_addr + segs[i].ds_len) % mr_nvme_pg_size) {
1426                                         build_prp = false;
1427                                         mrsas_atomic_inc(&sc->sge_holes);
1428                                         break;
1429                                 }
1430                 }
1431
1432                 /* check for Last SGE*/
1433                 if ((nsegs > 1) && (i == (nsegs - 1))) {
1434                                 if (segs[i].ds_addr % mr_nvme_pg_size) {
1435                                         build_prp = false;
1436                                         mrsas_atomic_inc(&sc->sge_holes);
1437                                         break;
1438                                 }
1439                 }
1440
1441         }
1442
1443         return build_prp;
1444 }
1445
1446 /*
1447  * mrsas_map_request:   Map and load data
1448  * input:                               Adapter instance soft state
1449  *                                              Pointer to command packet
1450  *
1451  * For data from OS, map and load the data buffer into bus space.  The SG list
1452  * is built in the callback.  If the  bus dmamap load is not successful,
1453  * cmd->error_code will contain the  error code and a 1 is returned.
1454  */
1455 int 
1456 mrsas_map_request(struct mrsas_softc *sc,
1457     struct mrsas_mpt_cmd *cmd, union ccb *ccb)
1458 {
1459         u_int32_t retcode = 0;
1460         struct cam_sim *sim;
1461
1462         sim = xpt_path_sim(cmd->ccb_ptr->ccb_h.path);
1463
1464         if (cmd->data != NULL) {
1465                 /* Map data buffer into bus space */
1466                 mtx_lock(&sc->io_lock);
1467 #if (__FreeBSD_version >= 902001)
1468                 retcode = bus_dmamap_load_ccb(sc->data_tag, cmd->data_dmamap, ccb,
1469                     mrsas_data_load_cb, cmd, 0);
1470 #else
1471                 retcode = bus_dmamap_load(sc->data_tag, cmd->data_dmamap, cmd->data,
1472                     cmd->length, mrsas_data_load_cb, cmd, BUS_DMA_NOWAIT);
1473 #endif
1474                 mtx_unlock(&sc->io_lock);
1475                 if (retcode)
1476                         device_printf(sc->mrsas_dev, "bus_dmamap_load(): retcode = %d\n", retcode);
1477                 if (retcode == EINPROGRESS) {
1478                         device_printf(sc->mrsas_dev, "request load in progress\n");
1479                         mrsas_freeze_simq(cmd, sim);
1480                 }
1481         }
1482         if (cmd->error_code)
1483                 return (1);
1484         return (retcode);
1485 }
1486
1487 /*
1488  * mrsas_unmap_request: Unmap and unload data
1489  * input:                               Adapter instance soft state
1490  *                                              Pointer to command packet
1491  *
1492  * This function unmaps and unloads data from OS.
1493  */
1494 void
1495 mrsas_unmap_request(struct mrsas_softc *sc, struct mrsas_mpt_cmd *cmd)
1496 {
1497         if (cmd->data != NULL) {
1498                 if (cmd->flags & MRSAS_DIR_IN)
1499                         bus_dmamap_sync(sc->data_tag, cmd->data_dmamap, BUS_DMASYNC_POSTREAD);
1500                 if (cmd->flags & MRSAS_DIR_OUT)
1501                         bus_dmamap_sync(sc->data_tag, cmd->data_dmamap, BUS_DMASYNC_POSTWRITE);
1502                 mtx_lock(&sc->io_lock);
1503                 bus_dmamap_unload(sc->data_tag, cmd->data_dmamap);
1504                 mtx_unlock(&sc->io_lock);
1505         }
1506 }
1507
1508 /**
1509  * mrsas_build_ieee_sgl -       Prepare IEEE SGLs
1510  * @sc:                                         Adapter soft state
1511  * @segs:                                       OS SGEs pointers
1512  * @nseg:                                       Number of OS SGEs
1513  * @cmd:                                        Fusion command frame
1514  * return:                                      void
1515  */
1516 static void mrsas_build_ieee_sgl(struct mrsas_mpt_cmd *cmd, bus_dma_segment_t *segs, int nseg)
1517 {
1518         struct mrsas_softc *sc = cmd->sc;
1519         MRSAS_RAID_SCSI_IO_REQUEST *io_request;
1520         pMpi25IeeeSgeChain64_t sgl_ptr;
1521         int i = 0, sg_processed = 0;
1522
1523         io_request = cmd->io_request;
1524         sgl_ptr = (pMpi25IeeeSgeChain64_t)&io_request->SGL;
1525
1526         if (sc->mrsas_gen3_ctrl || sc->is_ventura || sc->is_aero) {
1527                 pMpi25IeeeSgeChain64_t sgl_ptr_end = sgl_ptr;
1528
1529                 sgl_ptr_end += sc->max_sge_in_main_msg - 1;
1530                 sgl_ptr_end->Flags = 0;
1531         }
1532         if (nseg != 0) {
1533                 for (i = 0; i < nseg; i++) {
1534                         sgl_ptr->Address = segs[i].ds_addr;
1535                         sgl_ptr->Length = segs[i].ds_len;
1536                         sgl_ptr->Flags = 0;
1537                         if (sc->mrsas_gen3_ctrl || sc->is_ventura || sc->is_aero) {
1538                                 if (i == nseg - 1)
1539                                         sgl_ptr->Flags = IEEE_SGE_FLAGS_END_OF_LIST;
1540                         }
1541                         sgl_ptr++;
1542                         sg_processed = i + 1;
1543                         if ((sg_processed == (sc->max_sge_in_main_msg - 1)) &&
1544                                 (nseg > sc->max_sge_in_main_msg)) {
1545                                 pMpi25IeeeSgeChain64_t sg_chain;
1546
1547                                 if (sc->mrsas_gen3_ctrl || sc->is_ventura || sc->is_aero) {
1548                                         if ((cmd->io_request->IoFlags & MPI25_SAS_DEVICE0_FLAGS_ENABLED_FAST_PATH)
1549                                                 != MPI25_SAS_DEVICE0_FLAGS_ENABLED_FAST_PATH)
1550                                                 cmd->io_request->ChainOffset = sc->chain_offset_io_request;
1551                                         else
1552                                                 cmd->io_request->ChainOffset = 0;
1553                                 } else
1554                                         cmd->io_request->ChainOffset = sc->chain_offset_io_request;
1555                                 sg_chain = sgl_ptr;
1556                                 if (sc->mrsas_gen3_ctrl || sc->is_ventura || sc->is_aero)
1557                                         sg_chain->Flags = IEEE_SGE_FLAGS_CHAIN_ELEMENT;
1558                                 else
1559                                         sg_chain->Flags = (IEEE_SGE_FLAGS_CHAIN_ELEMENT | MPI2_IEEE_SGE_FLAGS_IOCPLBNTA_ADDR);
1560                                 sg_chain->Length = (sizeof(MPI2_SGE_IO_UNION) * (nseg - sg_processed));
1561                                 sg_chain->Address = cmd->chain_frame_phys_addr;
1562                                 sgl_ptr = (pMpi25IeeeSgeChain64_t)cmd->chain_frame;
1563                         }
1564                 }
1565         }
1566 }
1567
1568 /**
1569  * mrsas_build_prp_nvme - Prepare PRPs(Physical Region Page)- SGLs specific to NVMe drives only
1570  * @sc:                                         Adapter soft state
1571  * @segs:                                       OS SGEs pointers
1572  * @nseg:                                       Number of OS SGEs
1573  * @cmd:                                        Fusion command frame
1574  * return:                                      void
1575  */
1576 static void mrsas_build_prp_nvme(struct mrsas_mpt_cmd *cmd, bus_dma_segment_t *segs, int nseg)
1577 {
1578         struct mrsas_softc *sc = cmd->sc;
1579         int sge_len, offset, num_prp_in_chain = 0;
1580         pMpi25IeeeSgeChain64_t main_chain_element, ptr_first_sgl, sgl_ptr;
1581         u_int64_t *ptr_sgl;
1582         bus_addr_t ptr_sgl_phys;
1583         u_int64_t sge_addr;
1584         u_int32_t page_mask, page_mask_result, i = 0;
1585         u_int32_t first_prp_len;
1586         int data_len = cmd->length;
1587         u_int32_t mr_nvme_pg_size = max(sc->nvme_page_size,
1588                                         MR_DEFAULT_NVME_PAGE_SIZE);
1589
1590         sgl_ptr = (pMpi25IeeeSgeChain64_t) &cmd->io_request->SGL;
1591         /*
1592          * NVMe has a very convoluted PRP format.  One PRP is required
1593          * for each page or partial page.  We need to split up OS SG
1594          * entries if they are longer than one page or cross a page
1595          * boundary.  We also have to insert a PRP list pointer entry as
1596          * the last entry in each physical page of the PRP list.
1597          *
1598          * NOTE: The first PRP "entry" is actually placed in the first
1599          * SGL entry in the main message in IEEE 64 format.  The 2nd
1600          * entry in the main message is the chain element, and the rest
1601          * of the PRP entries are built in the contiguous PCIe buffer.
1602          */
1603         page_mask = mr_nvme_pg_size - 1;
1604         ptr_sgl = (u_int64_t *) cmd->chain_frame;
1605         ptr_sgl_phys = cmd->chain_frame_phys_addr;
1606         memset(ptr_sgl, 0, sc->max_chain_frame_sz);
1607
1608         /* Build chain frame element which holds all PRPs except first*/
1609         main_chain_element = (pMpi25IeeeSgeChain64_t)
1610             ((u_int8_t *)sgl_ptr + sizeof(MPI25_IEEE_SGE_CHAIN64));
1611
1612
1613         main_chain_element->Address = cmd->chain_frame_phys_addr;
1614         main_chain_element->NextChainOffset = 0;
1615         main_chain_element->Flags = IEEE_SGE_FLAGS_CHAIN_ELEMENT |
1616                                         IEEE_SGE_FLAGS_SYSTEM_ADDR |
1617                                         MPI26_IEEE_SGE_FLAGS_NSF_NVME_PRP;
1618
1619
1620         /* Build first PRP, SGE need not to be PAGE aligned*/
1621         ptr_first_sgl = sgl_ptr;
1622         sge_addr = segs[i].ds_addr;
1623         sge_len = segs[i].ds_len;
1624         i++;
1625
1626         offset = (u_int32_t) (sge_addr & page_mask);
1627         first_prp_len = mr_nvme_pg_size - offset;
1628
1629         ptr_first_sgl->Address = sge_addr;
1630         ptr_first_sgl->Length = first_prp_len;
1631
1632         data_len -= first_prp_len;
1633
1634         if (sge_len > first_prp_len) {
1635                 sge_addr += first_prp_len;
1636                 sge_len -= first_prp_len;
1637         } else if (sge_len == first_prp_len) {
1638                 sge_addr = segs[i].ds_addr;
1639                 sge_len = segs[i].ds_len;
1640                 i++;
1641         }
1642
1643         for (;;) {
1644
1645                 offset = (u_int32_t) (sge_addr & page_mask);
1646
1647                 /* Put PRP pointer due to page boundary*/
1648                 page_mask_result = (uintptr_t)(ptr_sgl + 1) & page_mask;
1649                 if (!page_mask_result) {
1650                         device_printf(sc->mrsas_dev, "BRCM: Put prp pointer as we are at page boundary"
1651                                         " ptr_sgl: 0x%p\n", ptr_sgl);
1652                         ptr_sgl_phys++;
1653                         *ptr_sgl = (uintptr_t)ptr_sgl_phys;
1654                         ptr_sgl++;
1655                         num_prp_in_chain++;
1656                 }
1657
1658                 *ptr_sgl = sge_addr;
1659                 ptr_sgl++;
1660                 ptr_sgl_phys++;
1661                 num_prp_in_chain++;
1662
1663
1664                 sge_addr += mr_nvme_pg_size;
1665                 sge_len -= mr_nvme_pg_size;
1666                 data_len -= mr_nvme_pg_size;
1667
1668                 if (data_len <= 0)
1669                         break;
1670
1671                 if (sge_len > 0)
1672                         continue;
1673
1674                 sge_addr = segs[i].ds_addr;
1675                 sge_len = segs[i].ds_len;
1676                 i++;
1677         }
1678
1679         main_chain_element->Length = num_prp_in_chain * sizeof(u_int64_t);
1680         mrsas_atomic_inc(&sc->prp_count);
1681
1682 }
1683
1684 /*
1685  * mrsas_data_load_cb:  Callback entry point to build SGLs
1686  * input:                               Pointer to command packet as argument
1687  *                                              Pointer to segment
1688  *                                              Number of segments Error
1689  *
1690  * This is the callback function of the bus dma map load.  It builds SG list
1691  */
1692 static void
1693 mrsas_data_load_cb(void *arg, bus_dma_segment_t *segs, int nseg, int error)
1694 {
1695         struct mrsas_mpt_cmd *cmd = (struct mrsas_mpt_cmd *)arg;
1696         struct mrsas_softc *sc = cmd->sc;
1697         boolean_t build_prp = false;
1698
1699         if (error) {
1700                 cmd->error_code = error;
1701                 device_printf(sc->mrsas_dev, "mrsas_data_load_cb_prp: error=%d\n", error);
1702                 if (error == EFBIG) {
1703                         cmd->ccb_ptr->ccb_h.status = CAM_REQ_TOO_BIG;
1704                         return;
1705                 }
1706         }
1707         if (cmd->flags & MRSAS_DIR_IN)
1708                 bus_dmamap_sync(cmd->sc->data_tag, cmd->data_dmamap,
1709                     BUS_DMASYNC_PREREAD);
1710         if (cmd->flags & MRSAS_DIR_OUT)
1711                 bus_dmamap_sync(cmd->sc->data_tag, cmd->data_dmamap,
1712                     BUS_DMASYNC_PREWRITE);
1713         if (nseg > sc->max_num_sge) {
1714                 device_printf(sc->mrsas_dev, "SGE count is too large or 0.\n");
1715                 return;
1716         }
1717
1718         /* Check for whether PRPs should be built or IEEE SGLs*/
1719         if ((cmd->io_request->IoFlags & MPI25_SAS_DEVICE0_FLAGS_ENABLED_FAST_PATH) &&
1720                         (cmd->pdInterface == NVME_PD))
1721                 build_prp = mrsas_is_prp_possible(cmd, segs, nseg);
1722
1723         if (build_prp == true)
1724                 mrsas_build_prp_nvme(cmd, segs, nseg);
1725         else
1726                 mrsas_build_ieee_sgl(cmd, segs, nseg);
1727
1728         cmd->sge_count = nseg;
1729 }
1730
1731 /*
1732  * mrsas_freeze_simq:   Freeze SIM queue
1733  * input:                               Pointer to command packet
1734  *                                              Pointer to SIM
1735  *
1736  * This function freezes the sim queue.
1737  */
1738 static void
1739 mrsas_freeze_simq(struct mrsas_mpt_cmd *cmd, struct cam_sim *sim)
1740 {
1741         union ccb *ccb = (union ccb *)(cmd->ccb_ptr);
1742
1743         xpt_freeze_simq(sim, 1);
1744         ccb->ccb_h.status |= CAM_RELEASE_SIMQ;
1745         ccb->ccb_h.status |= CAM_REQUEUE_REQ;
1746 }
1747
1748 void
1749 mrsas_xpt_freeze(struct mrsas_softc *sc)
1750 {
1751         xpt_freeze_simq(sc->sim_0, 1);
1752         xpt_freeze_simq(sc->sim_1, 1);
1753 }
1754
1755 void
1756 mrsas_xpt_release(struct mrsas_softc *sc)
1757 {
1758         xpt_release_simq(sc->sim_0, 1);
1759         xpt_release_simq(sc->sim_1, 1);
1760 }
1761
1762 /*
1763  * mrsas_cmd_done:      Perform remaining command completion
1764  * input:                       Adapter instance soft state  Pointer to command packet
1765  *
1766  * This function calls ummap request and releases the MPT command.
1767  */
1768 void
1769 mrsas_cmd_done(struct mrsas_softc *sc, struct mrsas_mpt_cmd *cmd)
1770 {
1771         mrsas_unmap_request(sc, cmd);
1772         
1773         mtx_lock(&sc->sim_lock);
1774         if (cmd->callout_owner) {
1775                 callout_stop(&cmd->cm_callout);
1776                 cmd->callout_owner  = false;
1777         }
1778         xpt_done(cmd->ccb_ptr);
1779         cmd->ccb_ptr = NULL;
1780         mtx_unlock(&sc->sim_lock);
1781         mrsas_release_mpt_cmd(cmd);
1782 }
1783
1784 /*
1785  * mrsas_cam_poll:      Polling entry point
1786  * input:                       Pointer to SIM
1787  *
1788  * This is currently a stub function.
1789  */
1790 static void
1791 mrsas_cam_poll(struct cam_sim *sim)
1792 {
1793         int i;
1794         struct mrsas_softc *sc = (struct mrsas_softc *)cam_sim_softc(sim);
1795
1796         if (sc->msix_vectors != 0){
1797                 for (i=0; i<sc->msix_vectors; i++){
1798                         mrsas_complete_cmd(sc, i);
1799                 }
1800         } else {
1801                 mrsas_complete_cmd(sc, 0);
1802         }
1803 }
1804
1805 /*
1806  * mrsas_bus_scan:      Perform bus scan
1807  * input:                       Adapter instance soft state
1808  *
1809  * This mrsas_bus_scan function is needed for FreeBSD 7.x.  Also, it should not
1810  * be called in FreeBSD 8.x and later versions, where the bus scan is
1811  * automatic.
1812  */
1813 int
1814 mrsas_bus_scan(struct mrsas_softc *sc)
1815 {
1816         union ccb *ccb_0;
1817         union ccb *ccb_1;
1818
1819         if ((ccb_0 = xpt_alloc_ccb()) == NULL) {
1820                 return (ENOMEM);
1821         }
1822         if ((ccb_1 = xpt_alloc_ccb()) == NULL) {
1823                 xpt_free_ccb(ccb_0);
1824                 return (ENOMEM);
1825         }
1826         mtx_lock(&sc->sim_lock);
1827         if (xpt_create_path(&ccb_0->ccb_h.path, xpt_periph, cam_sim_path(sc->sim_0),
1828             CAM_TARGET_WILDCARD, CAM_LUN_WILDCARD) != CAM_REQ_CMP) {
1829                 xpt_free_ccb(ccb_0);
1830                 xpt_free_ccb(ccb_1);
1831                 mtx_unlock(&sc->sim_lock);
1832                 return (EIO);
1833         }
1834         if (xpt_create_path(&ccb_1->ccb_h.path, xpt_periph, cam_sim_path(sc->sim_1),
1835             CAM_TARGET_WILDCARD, CAM_LUN_WILDCARD) != CAM_REQ_CMP) {
1836                 xpt_free_ccb(ccb_0);
1837                 xpt_free_ccb(ccb_1);
1838                 mtx_unlock(&sc->sim_lock);
1839                 return (EIO);
1840         }
1841         mtx_unlock(&sc->sim_lock);
1842         xpt_rescan(ccb_0);
1843         xpt_rescan(ccb_1);
1844
1845         return (0);
1846 }
1847
1848 /*
1849  * mrsas_bus_scan_sim:  Perform bus scan per SIM
1850  * input:                               adapter instance soft state
1851  *
1852  * This function will be called from Event handler on LD creation/deletion,
1853  * JBOD on/off.
1854  */
1855 int
1856 mrsas_bus_scan_sim(struct mrsas_softc *sc, struct cam_sim *sim)
1857 {
1858         union ccb *ccb;
1859
1860         if ((ccb = xpt_alloc_ccb()) == NULL) {
1861                 return (ENOMEM);
1862         }
1863         mtx_lock(&sc->sim_lock);
1864         if (xpt_create_path(&ccb->ccb_h.path, xpt_periph, cam_sim_path(sim),
1865             CAM_TARGET_WILDCARD, CAM_LUN_WILDCARD) != CAM_REQ_CMP) {
1866                 xpt_free_ccb(ccb);
1867                 mtx_unlock(&sc->sim_lock);
1868                 return (EIO);
1869         }
1870         mtx_unlock(&sc->sim_lock);
1871         xpt_rescan(ccb);
1872
1873         return (0);
1874 }
1875
1876 /*
1877  * mrsas_track_scsiio:  Track IOs for a given target in the mpt_cmd_list
1878  * input:           Adapter instance soft state
1879  *                  Target ID of target
1880  *                  Bus ID of the target
1881  *
1882  * This function checks for any pending IO in the whole mpt_cmd_list pool
1883  * with the bus_id and target_id passed in arguments. If some IO is found
1884  * that means target reset is not successfully completed.
1885  *
1886  * Returns FAIL if IOs pending to the target device, else return SUCCESS
1887  */
1888 static int
1889 mrsas_track_scsiio(struct mrsas_softc *sc, target_id_t tgt_id, u_int32_t bus_id)
1890 {
1891         int i;
1892         struct mrsas_mpt_cmd *mpt_cmd = NULL;
1893
1894         for (i = 0 ; i < sc->max_fw_cmds; i++) {
1895                 mpt_cmd = sc->mpt_cmd_list[i];
1896
1897         /*
1898          * Check if the target_id and bus_id is same as the timeout IO
1899          */
1900         if (mpt_cmd->ccb_ptr) {
1901                 /* bus_id = 1 denotes a VD */
1902                 if (bus_id == 1)
1903                         tgt_id = (mpt_cmd->ccb_ptr->ccb_h.target_id - (MRSAS_MAX_PD - 1));
1904
1905                         if (mpt_cmd->ccb_ptr->cpi.bus_id == bus_id &&
1906                             mpt_cmd->ccb_ptr->ccb_h.target_id == tgt_id) {
1907                                 device_printf(sc->mrsas_dev,
1908                                     "IO commands pending to target id %d\n", tgt_id);
1909                                 return FAIL;
1910                         }
1911                 }
1912         }
1913
1914         return SUCCESS;
1915 }
1916
1917 #if TM_DEBUG
1918 /*
1919  * mrsas_tm_response_code: Prints TM response code received from FW
1920  * input:           Adapter instance soft state
1921  *                  MPI reply returned from firmware
1922  *
1923  * Returns nothing.
1924  */
1925 static void
1926 mrsas_tm_response_code(struct mrsas_softc *sc,
1927         MPI2_SCSI_TASK_MANAGE_REPLY *mpi_reply)
1928 {
1929         char *desc;
1930
1931         switch (mpi_reply->ResponseCode) {
1932         case MPI2_SCSITASKMGMT_RSP_TM_COMPLETE:
1933                 desc = "task management request completed";
1934                 break;
1935         case MPI2_SCSITASKMGMT_RSP_INVALID_FRAME:
1936                 desc = "invalid frame";
1937                 break;
1938         case MPI2_SCSITASKMGMT_RSP_TM_NOT_SUPPORTED:
1939                 desc = "task management request not supported";
1940                 break;
1941         case MPI2_SCSITASKMGMT_RSP_TM_FAILED:
1942                 desc = "task management request failed";
1943                 break;
1944         case MPI2_SCSITASKMGMT_RSP_TM_SUCCEEDED:
1945                 desc = "task management request succeeded";
1946                 break;
1947         case MPI2_SCSITASKMGMT_RSP_TM_INVALID_LUN:
1948                 desc = "invalid lun";
1949                 break;
1950         case 0xA:
1951                 desc = "overlapped tag attempted";
1952                 break;
1953         case MPI2_SCSITASKMGMT_RSP_IO_QUEUED_ON_IOC:
1954                 desc = "task queued, however not sent to target";
1955                 break;
1956         default:
1957                 desc = "unknown";
1958                 break;
1959         }
1960         device_printf(sc->mrsas_dev, "response_code(%01x): %s\n",
1961             mpi_reply->ResponseCode, desc);
1962         device_printf(sc->mrsas_dev,
1963             "TerminationCount/DevHandle/Function/TaskType/IOCStat/IOCLoginfo\n"
1964             "0x%x/0x%x/0x%x/0x%x/0x%x/0x%x\n",
1965             mpi_reply->TerminationCount, mpi_reply->DevHandle,
1966             mpi_reply->Function, mpi_reply->TaskType,
1967             mpi_reply->IOCStatus, mpi_reply->IOCLogInfo);
1968 }
1969 #endif
1970
1971 /*
1972  * mrsas_issue_tm:  Fires the TM command to FW and waits for completion
1973  * input:           Adapter instance soft state
1974  *                  reqest descriptor compiled by mrsas_reset_targets
1975  *
1976  * Returns FAIL if TM command TIMEDOUT from FW else SUCCESS.
1977  */
1978 static int
1979 mrsas_issue_tm(struct mrsas_softc *sc,
1980         MRSAS_REQUEST_DESCRIPTOR_UNION *req_desc)
1981 {
1982         int sleep_stat;
1983
1984         mrsas_fire_cmd(sc, req_desc->addr.u.low, req_desc->addr.u.high);
1985         sleep_stat = msleep(&sc->ocr_chan, &sc->sim_lock, PRIBIO, "tm_sleep", 50*hz);
1986
1987         if (sleep_stat == EWOULDBLOCK) {
1988                 device_printf(sc->mrsas_dev, "tm cmd TIMEDOUT\n");
1989                 return FAIL;
1990         }
1991
1992         return SUCCESS;
1993 }
1994
1995 /*
1996  * mrsas_reset_targets : Gathers info to fire a target reset command
1997  * input:           Adapter instance soft state
1998  *
1999  * This function compiles data for a target reset command to be fired to the FW
2000  * and then traverse the target_reset_pool to see targets with TIMEDOUT IOs.
2001  *
2002  * Returns SUCCESS or FAIL
2003  */
2004 int mrsas_reset_targets(struct mrsas_softc *sc)
2005 {
2006         struct mrsas_mpt_cmd *tm_mpt_cmd = NULL;
2007         struct mrsas_mpt_cmd *tgt_mpt_cmd = NULL;
2008         MR_TASK_MANAGE_REQUEST *mr_request;
2009         MPI2_SCSI_TASK_MANAGE_REQUEST *tm_mpi_request;
2010         MRSAS_REQUEST_DESCRIPTOR_UNION *req_desc;
2011         int retCode = FAIL, count, i, outstanding;
2012         u_int32_t MSIxIndex, bus_id;
2013         target_id_t tgt_id;
2014 #if TM_DEBUG
2015         MPI2_SCSI_TASK_MANAGE_REPLY *mpi_reply;
2016 #endif
2017
2018         outstanding = mrsas_atomic_read(&sc->fw_outstanding);
2019
2020         if (!outstanding) {
2021                 device_printf(sc->mrsas_dev, "NO IOs pending...\n");
2022                 mrsas_atomic_set(&sc->target_reset_outstanding, 0);
2023                 retCode = SUCCESS;
2024                 goto return_status;
2025         } else if (sc->adprecovery != MRSAS_HBA_OPERATIONAL) {
2026                 device_printf(sc->mrsas_dev, "Controller is not operational\n");
2027                 goto return_status;
2028         } else {
2029                 /* Some more error checks will be added in future */
2030         }
2031
2032         /* Get an mpt frame and an index to fire the TM cmd */
2033         tm_mpt_cmd = mrsas_get_mpt_cmd(sc);
2034         if (!tm_mpt_cmd) {
2035                 retCode = FAIL;
2036                 goto return_status;
2037         }
2038
2039         req_desc = mrsas_get_request_desc(sc, (tm_mpt_cmd->index) - 1);
2040         if (!req_desc) {
2041                 device_printf(sc->mrsas_dev, "Cannot get request_descriptor for tm.\n");
2042                 retCode = FAIL;
2043                 goto release_mpt;
2044         }
2045         memset(req_desc, 0, sizeof(MRSAS_REQUEST_DESCRIPTOR_UNION));
2046
2047         req_desc->HighPriority.SMID = tm_mpt_cmd->index;
2048         req_desc->HighPriority.RequestFlags =
2049             (MPI2_REQ_DESCRIPT_FLAGS_HIGH_PRIORITY <<
2050             MRSAS_REQ_DESCRIPT_FLAGS_TYPE_SHIFT);
2051         req_desc->HighPriority.MSIxIndex =  0;
2052         req_desc->HighPriority.LMID = 0;
2053         req_desc->HighPriority.Reserved1 = 0;
2054         tm_mpt_cmd->request_desc = req_desc;
2055
2056         mr_request = (MR_TASK_MANAGE_REQUEST *) tm_mpt_cmd->io_request;
2057         memset(mr_request, 0, sizeof(MR_TASK_MANAGE_REQUEST));
2058
2059         tm_mpi_request = (MPI2_SCSI_TASK_MANAGE_REQUEST *) &mr_request->TmRequest;
2060         tm_mpi_request->Function = MPI2_FUNCTION_SCSI_TASK_MGMT;
2061         tm_mpi_request->TaskType = MPI2_SCSITASKMGMT_TASKTYPE_TARGET_RESET;
2062         tm_mpi_request->TaskMID = 0; /* smid task */
2063         tm_mpi_request->LUN[1] = 0;
2064
2065         /* Traverse the tm_mpt pool to get valid entries */
2066         for (i = 0 ; i < MRSAS_MAX_TM_TARGETS; i++) {
2067                 if(!sc->target_reset_pool[i]) {
2068                         continue;
2069                 } else {
2070                         tgt_mpt_cmd = sc->target_reset_pool[i];
2071                 }
2072
2073                 tgt_id = i;
2074
2075                 /* See if the target is tm capable or NOT */
2076                 if (!tgt_mpt_cmd->tmCapable) {
2077                         device_printf(sc->mrsas_dev, "Task management NOT SUPPORTED for "
2078                             "CAM target:%d\n", tgt_id);
2079
2080                         retCode = FAIL;
2081                         goto release_mpt;
2082                 }
2083
2084                 tm_mpi_request->DevHandle = tgt_mpt_cmd->io_request->DevHandle;
2085
2086                 if (i < (MRSAS_MAX_PD - 1)) {
2087                         mr_request->uTmReqReply.tmReqFlags.isTMForPD = 1;
2088                         bus_id = 0;
2089                 } else {
2090                         mr_request->uTmReqReply.tmReqFlags.isTMForLD = 1;
2091                         bus_id = 1;
2092                 }
2093
2094                 device_printf(sc->mrsas_dev, "TM will be fired for "
2095                     "CAM target:%d and bus_id %d\n", tgt_id, bus_id);
2096
2097                 sc->ocr_chan = (void *)&tm_mpt_cmd;
2098                 retCode = mrsas_issue_tm(sc, req_desc);
2099                 if (retCode == FAIL)
2100                         goto release_mpt;
2101
2102 #if TM_DEBUG
2103                 mpi_reply =
2104                     (MPI2_SCSI_TASK_MANAGE_REPLY *) &mr_request->uTmReqReply.TMReply;
2105                 mrsas_tm_response_code(sc, mpi_reply);
2106 #endif
2107                 mrsas_atomic_dec(&sc->target_reset_outstanding);
2108                 sc->target_reset_pool[i] = NULL;
2109
2110                 /* Check for pending cmds in the mpt_cmd_pool with the tgt_id */
2111                 mrsas_disable_intr(sc);
2112                 /* Wait for 1 second to complete parallel ISR calling same
2113                  * mrsas_complete_cmd()
2114                  */
2115                 msleep(&sc->ocr_chan, &sc->sim_lock, PRIBIO, "mrsas_reset_wakeup",
2116                    1 * hz);
2117                 count = sc->msix_vectors > 0 ? sc->msix_vectors : 1;
2118                 mtx_unlock(&sc->sim_lock);
2119                 for (MSIxIndex = 0; MSIxIndex < count; MSIxIndex++)
2120                     mrsas_complete_cmd(sc, MSIxIndex);
2121                 mtx_lock(&sc->sim_lock);
2122                 retCode = mrsas_track_scsiio(sc, tgt_id, bus_id);
2123                 mrsas_enable_intr(sc);
2124
2125                 if (retCode == FAIL)
2126                         goto release_mpt;
2127         }
2128
2129         device_printf(sc->mrsas_dev, "Number of targets outstanding "
2130             "after reset: %d\n", mrsas_atomic_read(&sc->target_reset_outstanding));
2131
2132 release_mpt:
2133         mrsas_release_mpt_cmd(tm_mpt_cmd);
2134 return_status:
2135         device_printf(sc->mrsas_dev, "target reset %s!!\n",
2136                 (retCode == SUCCESS) ? "SUCCESS" : "FAIL");
2137
2138         return retCode;
2139 }
2140