]> CyberLeo.Net >> Repos - FreeBSD/releng/7.2.git/blob - sys/dev/mpt/mpt_cam.c
Create releng/7.2 from stable/7 in preparation for 7.2-RELEASE.
[FreeBSD/releng/7.2.git] / sys / dev / mpt / mpt_cam.c
1 /*-
2  * FreeBSD/CAM specific routines for LSI '909 FC  adapters.
3  * FreeBSD Version.
4  *
5  * Copyright (c)  2000, 2001 by Greg Ansley
6  *
7  * Redistribution and use in source and binary forms, with or without
8  * modification, are permitted provided that the following conditions
9  * are met:
10  * 1. Redistributions of source code must retain the above copyright
11  *    notice immediately at the beginning of the file, without modification,
12  *    this list of conditions, and the following disclaimer.
13  * 2. The name of the author may not be used to endorse or promote products
14  *    derived from this software without specific prior written permission.
15  *
16  * THIS SOFTWARE IS PROVIDED BY THE AUTHOR AND CONTRIBUTORS ``AS IS'' AND
17  * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
18  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
19  * ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE FOR
20  * ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
21  * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
22  * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
23  * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
24  * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
25  * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
26  * SUCH DAMAGE.
27  */
28 /*-
29  * Copyright (c) 2002, 2006 by Matthew Jacob
30  * All rights reserved.
31  * 
32  * Redistribution and use in source and binary forms, with or without
33  * modification, are permitted provided that the following conditions are
34  * met:
35  * 1. Redistributions of source code must retain the above copyright
36  *    notice, this list of conditions and the following disclaimer.
37  * 2. Redistributions in binary form must reproduce at minimum a disclaimer
38  *    substantially similar to the "NO WARRANTY" disclaimer below
39  *    ("Disclaimer") and any redistribution must be conditioned upon including
40  *    a substantially similar Disclaimer requirement for further binary
41  *    redistribution.
42  * 3. Neither the names of the above listed copyright holders nor the names
43  *    of any contributors may be used to endorse or promote products derived
44  *    from this software without specific prior written permission.
45  * 
46  * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
47  * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
48  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
49  * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE
50  * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
51  * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
52  * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
53  * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
54  * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
55  * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF THE COPYRIGHT
56  * OWNER OR CONTRIBUTOR IS ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
57  *
58  * Support from Chris Ellsworth in order to make SAS adapters work
59  * is gratefully acknowledged.
60  *
61  * Support from LSI-Logic has also gone a great deal toward making this a
62  * workable subsystem and is gratefully acknowledged.
63  */
64 /*-
65  * Copyright (c) 2004, Avid Technology, Inc. and its contributors.
66  * Copyright (c) 2005, WHEEL Sp. z o.o.
67  * Copyright (c) 2004, 2005 Justin T. Gibbs
68  * All rights reserved.
69  * 
70  * Redistribution and use in source and binary forms, with or without
71  * modification, are permitted provided that the following conditions are
72  * met:
73  * 1. Redistributions of source code must retain the above copyright
74  *    notice, this list of conditions and the following disclaimer.
75  * 2. Redistributions in binary form must reproduce at minimum a disclaimer
76  *    substantially similar to the "NO WARRANTY" disclaimer below
77  *    ("Disclaimer") and any redistribution must be conditioned upon including
78  *    a substantially similar Disclaimer requirement for further binary
79  *    redistribution.
80  * 3. Neither the names of the above listed copyright holders nor the names
81  *    of any contributors may be used to endorse or promote products derived
82  *    from this software without specific prior written permission.
83  * 
84  * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
85  * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
86  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
87  * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE
88  * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
89  * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
90  * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
91  * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
92  * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
93  * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF THE COPYRIGHT
94  * OWNER OR CONTRIBUTOR IS ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
95  */
96 #include <sys/cdefs.h>
97 __FBSDID("$FreeBSD$");
98
99 #include <dev/mpt/mpt.h>
100 #include <dev/mpt/mpt_cam.h>
101 #include <dev/mpt/mpt_raid.h>
102
103 #include "dev/mpt/mpilib/mpi_ioc.h" /* XXX Fix Event Handling!!! */
104 #include "dev/mpt/mpilib/mpi_init.h"
105 #include "dev/mpt/mpilib/mpi_targ.h"
106 #include "dev/mpt/mpilib/mpi_fc.h"
107 #include "dev/mpt/mpilib/mpi_sas.h"
108 #if __FreeBSD_version >= 500000
109 #include <sys/sysctl.h>
110 #endif
111 #include <sys/callout.h>
112 #include <sys/kthread.h>
113
114 #if __FreeBSD_version >= 700025
115 #ifndef CAM_NEW_TRAN_CODE
116 #define CAM_NEW_TRAN_CODE       1
117 #endif
118 #endif
119
120 static void mpt_poll(struct cam_sim *);
121 static timeout_t mpt_timeout;
122 static void mpt_action(struct cam_sim *, union ccb *);
123 static int
124 mpt_get_spi_settings(struct mpt_softc *, struct ccb_trans_settings *);
125 static void mpt_setwidth(struct mpt_softc *, int, int);
126 static void mpt_setsync(struct mpt_softc *, int, int, int);
127 static int mpt_update_spi_config(struct mpt_softc *, int);
128 static void mpt_calc_geometry(struct ccb_calc_geometry *ccg, int extended);
129
130 static mpt_reply_handler_t mpt_scsi_reply_handler;
131 static mpt_reply_handler_t mpt_scsi_tmf_reply_handler;
132 static mpt_reply_handler_t mpt_fc_els_reply_handler;
133 static int mpt_scsi_reply_frame_handler(struct mpt_softc *, request_t *,
134                                         MSG_DEFAULT_REPLY *);
135 static int mpt_bus_reset(struct mpt_softc *, target_id_t, lun_id_t, int);
136 static int mpt_fc_reset_link(struct mpt_softc *, int);
137
138 static int mpt_spawn_recovery_thread(struct mpt_softc *mpt);
139 static void mpt_terminate_recovery_thread(struct mpt_softc *mpt);
140 static void mpt_recovery_thread(void *arg);
141 static void mpt_recover_commands(struct mpt_softc *mpt);
142
143 static int mpt_scsi_send_tmf(struct mpt_softc *, u_int, u_int, u_int,
144     u_int, u_int, u_int, int);
145
146 static void mpt_fc_post_els(struct mpt_softc *mpt, request_t *, int);
147 static void mpt_post_target_command(struct mpt_softc *, request_t *, int);
148 static int mpt_add_els_buffers(struct mpt_softc *mpt);
149 static int mpt_add_target_commands(struct mpt_softc *mpt);
150 static int mpt_enable_lun(struct mpt_softc *, target_id_t, lun_id_t);
151 static int mpt_disable_lun(struct mpt_softc *, target_id_t, lun_id_t);
152 static void mpt_target_start_io(struct mpt_softc *, union ccb *);
153 static cam_status mpt_abort_target_ccb(struct mpt_softc *, union ccb *);
154 static int mpt_abort_target_cmd(struct mpt_softc *, request_t *);
155 static void mpt_scsi_tgt_status(struct mpt_softc *, union ccb *, request_t *,
156     uint8_t, uint8_t const *);
157 static void
158 mpt_scsi_tgt_tsk_mgmt(struct mpt_softc *, request_t *, mpt_task_mgmt_t,
159     tgt_resource_t *, int);
160 static void mpt_tgt_dump_tgt_state(struct mpt_softc *, request_t *);
161 static void mpt_tgt_dump_req_state(struct mpt_softc *, request_t *);
162 static mpt_reply_handler_t mpt_scsi_tgt_reply_handler;
163 static mpt_reply_handler_t mpt_sata_pass_reply_handler;
164
165 static uint32_t scsi_io_handler_id = MPT_HANDLER_ID_NONE;
166 static uint32_t scsi_tmf_handler_id = MPT_HANDLER_ID_NONE;
167 static uint32_t fc_els_handler_id = MPT_HANDLER_ID_NONE;
168 static uint32_t sata_pass_handler_id = MPT_HANDLER_ID_NONE;
169
170 static mpt_probe_handler_t      mpt_cam_probe;
171 static mpt_attach_handler_t     mpt_cam_attach;
172 static mpt_enable_handler_t     mpt_cam_enable;
173 static mpt_ready_handler_t      mpt_cam_ready;
174 static mpt_event_handler_t      mpt_cam_event;
175 static mpt_reset_handler_t      mpt_cam_ioc_reset;
176 static mpt_detach_handler_t     mpt_cam_detach;
177
178 static struct mpt_personality mpt_cam_personality =
179 {
180         .name           = "mpt_cam",
181         .probe          = mpt_cam_probe,
182         .attach         = mpt_cam_attach,
183         .enable         = mpt_cam_enable,
184         .ready          = mpt_cam_ready,
185         .event          = mpt_cam_event,
186         .reset          = mpt_cam_ioc_reset,
187         .detach         = mpt_cam_detach,
188 };
189
190 DECLARE_MPT_PERSONALITY(mpt_cam, SI_ORDER_SECOND);
191 MODULE_DEPEND(mpt_cam, cam, 1, 1, 1);
192
193 int mpt_enable_sata_wc = -1;
194 TUNABLE_INT("hw.mpt.enable_sata_wc", &mpt_enable_sata_wc);
195
196 int
197 mpt_cam_probe(struct mpt_softc *mpt)
198 {
199         int role;
200
201         /*
202          * Only attach to nodes that support the initiator or target role
203          * (or want to) or have RAID physical devices that need CAM pass-thru
204          * support.
205          */
206         if (mpt->do_cfg_role) {
207                 role = mpt->cfg_role;
208         } else {
209                 role = mpt->role;
210         }
211         if ((role & (MPT_ROLE_TARGET|MPT_ROLE_INITIATOR)) != 0 ||
212             (mpt->ioc_page2 != NULL && mpt->ioc_page2->MaxPhysDisks != 0)) {
213                 return (0);
214         }
215         return (ENODEV);
216 }
217
218 int
219 mpt_cam_attach(struct mpt_softc *mpt)
220 {
221         struct cam_devq *devq;
222         mpt_handler_t    handler;
223         int              maxq;
224         int              error;
225
226         MPT_LOCK(mpt);
227         TAILQ_INIT(&mpt->request_timeout_list);
228         maxq = (mpt->ioc_facts.GlobalCredits < MPT_MAX_REQUESTS(mpt))?
229             mpt->ioc_facts.GlobalCredits : MPT_MAX_REQUESTS(mpt);
230
231         handler.reply_handler = mpt_scsi_reply_handler;
232         error = mpt_register_handler(mpt, MPT_HANDLER_REPLY, handler,
233                                      &scsi_io_handler_id);
234         if (error != 0) {
235                 MPT_UNLOCK(mpt);
236                 goto cleanup;
237         }
238
239         handler.reply_handler = mpt_scsi_tmf_reply_handler;
240         error = mpt_register_handler(mpt, MPT_HANDLER_REPLY, handler,
241                                      &scsi_tmf_handler_id);
242         if (error != 0) {
243                 MPT_UNLOCK(mpt);
244                 goto cleanup;
245         }
246
247         /*
248          * If we're fibre channel and could support target mode, we register
249          * an ELS reply handler and give it resources.
250          */
251         if (mpt->is_fc && (mpt->role & MPT_ROLE_TARGET) != 0) {
252                 handler.reply_handler = mpt_fc_els_reply_handler;
253                 error = mpt_register_handler(mpt, MPT_HANDLER_REPLY, handler,
254                     &fc_els_handler_id);
255                 if (error != 0) {
256                         MPT_UNLOCK(mpt);
257                         goto cleanup;
258                 }
259                 if (mpt_add_els_buffers(mpt) == FALSE) {
260                         error = ENOMEM;
261                         MPT_UNLOCK(mpt);
262                         goto cleanup;
263                 }
264                 maxq -= mpt->els_cmds_allocated;
265         }
266
267         /*
268          * If we support target mode, we register a reply handler for it,
269          * but don't add command resources until we actually enable target
270          * mode.
271          */
272         if (mpt->is_fc && (mpt->role & MPT_ROLE_TARGET) != 0) {
273                 handler.reply_handler = mpt_scsi_tgt_reply_handler;
274                 error = mpt_register_handler(mpt, MPT_HANDLER_REPLY, handler,
275                     &mpt->scsi_tgt_handler_id);
276                 if (error != 0) {
277                         MPT_UNLOCK(mpt);
278                         goto cleanup;
279                 }
280         }
281
282         if (mpt->is_sas) {
283                 handler.reply_handler = mpt_sata_pass_reply_handler;
284                 error = mpt_register_handler(mpt, MPT_HANDLER_REPLY, handler,
285                     &sata_pass_handler_id);
286                 if (error != 0) {
287                         MPT_UNLOCK(mpt);
288                         goto cleanup;
289                 }
290         }
291
292         /*
293          * We keep one request reserved for timeout TMF requests.
294          */
295         mpt->tmf_req = mpt_get_request(mpt, FALSE);
296         if (mpt->tmf_req == NULL) {
297                 mpt_prt(mpt, "Unable to allocate dedicated TMF request!\n");
298                 error = ENOMEM;
299                 MPT_UNLOCK(mpt);
300                 goto cleanup;
301         }
302
303         /*
304          * Mark the request as free even though not on the free list.
305          * There is only one TMF request allowed to be outstanding at
306          * a time and the TMF routines perform their own allocation
307          * tracking using the standard state flags.
308          */
309         mpt->tmf_req->state = REQ_STATE_FREE;
310         maxq--;
311
312         /*
313          * The rest of this is CAM foo, for which we need to drop our lock
314          */
315         MPT_UNLOCK(mpt);
316
317         if (mpt_spawn_recovery_thread(mpt) != 0) {
318                 mpt_prt(mpt, "Unable to spawn recovery thread!\n");
319                 error = ENOMEM;
320                 goto cleanup;
321         }
322
323         /*
324          * Create the device queue for our SIM(s).
325          */
326         devq = cam_simq_alloc(maxq);
327         if (devq == NULL) {
328                 mpt_prt(mpt, "Unable to allocate CAM SIMQ!\n");
329                 error = ENOMEM;
330                 goto cleanup;
331         }
332
333         /*
334          * Construct our SIM entry.
335          */
336         mpt->sim =
337             mpt_sim_alloc(mpt_action, mpt_poll, "mpt", mpt, 1, maxq, devq);
338         if (mpt->sim == NULL) {
339                 mpt_prt(mpt, "Unable to allocate CAM SIM!\n");
340                 cam_simq_free(devq);
341                 error = ENOMEM;
342                 goto cleanup;
343         }
344
345         /*
346          * Register exactly this bus.
347          */
348         MPT_LOCK(mpt);
349         if (mpt_xpt_bus_register(mpt->sim, mpt->dev, 0) != CAM_SUCCESS) {
350                 mpt_prt(mpt, "Bus registration Failed!\n");
351                 error = ENOMEM;
352                 MPT_UNLOCK(mpt);
353                 goto cleanup;
354         }
355
356         if (xpt_create_path(&mpt->path, NULL, cam_sim_path(mpt->sim),
357             CAM_TARGET_WILDCARD, CAM_LUN_WILDCARD) != CAM_REQ_CMP) {
358                 mpt_prt(mpt, "Unable to allocate Path!\n");
359                 error = ENOMEM;
360                 MPT_UNLOCK(mpt);
361                 goto cleanup;
362         }
363         MPT_UNLOCK(mpt);
364
365         /*
366          * Only register a second bus for RAID physical
367          * devices if the controller supports RAID.
368          */
369         if (mpt->ioc_page2 == NULL || mpt->ioc_page2->MaxPhysDisks == 0) {
370                 return (0);
371         }
372
373         /*
374          * Create a "bus" to export all hidden disks to CAM.
375          */
376         mpt->phydisk_sim =
377             mpt_sim_alloc(mpt_action, mpt_poll, "mpt", mpt, 1, maxq, devq);
378         if (mpt->phydisk_sim == NULL) {
379                 mpt_prt(mpt, "Unable to allocate Physical Disk CAM SIM!\n");
380                 error = ENOMEM;
381                 goto cleanup;
382         }
383
384         /*
385          * Register this bus.
386          */
387         MPT_LOCK(mpt);
388         if (mpt_xpt_bus_register(mpt->phydisk_sim, mpt->dev, 1) !=
389             CAM_SUCCESS) {
390                 mpt_prt(mpt, "Physical Disk Bus registration Failed!\n");
391                 error = ENOMEM;
392                 MPT_UNLOCK(mpt);
393                 goto cleanup;
394         }
395
396         if (xpt_create_path(&mpt->phydisk_path, NULL,
397             cam_sim_path(mpt->phydisk_sim),
398             CAM_TARGET_WILDCARD, CAM_LUN_WILDCARD) != CAM_REQ_CMP) {
399                 mpt_prt(mpt, "Unable to allocate Physical Disk Path!\n");
400                 error = ENOMEM;
401                 MPT_UNLOCK(mpt);
402                 goto cleanup;
403         }
404         MPT_UNLOCK(mpt);
405         mpt_lprt(mpt, MPT_PRT_DEBUG, "attached cam\n");
406         return (0);
407
408 cleanup:
409         mpt_cam_detach(mpt);
410         return (error);
411 }
412
413 /*
414  * Read FC configuration information
415  */
416 static int
417 mpt_read_config_info_fc(struct mpt_softc *mpt)
418 {
419         char *topology = NULL;
420         int rv;
421
422         rv = mpt_read_cfg_header(mpt, MPI_CONFIG_PAGETYPE_FC_PORT, 0,
423             0, &mpt->mpt_fcport_page0.Header, FALSE, 5000);
424         if (rv) {
425                 return (-1);
426         }
427         mpt_lprt(mpt, MPT_PRT_DEBUG, "FC Port Page 0 Header: %x %x %x %x\n",
428                  mpt->mpt_fcport_page0.Header.PageVersion,
429                  mpt->mpt_fcport_page0.Header.PageLength,
430                  mpt->mpt_fcport_page0.Header.PageNumber,
431                  mpt->mpt_fcport_page0.Header.PageType);
432
433
434         rv = mpt_read_cur_cfg_page(mpt, 0, &mpt->mpt_fcport_page0.Header,
435             sizeof(mpt->mpt_fcport_page0), FALSE, 5000);
436         if (rv) {
437                 mpt_prt(mpt, "failed to read FC Port Page 0\n");
438                 return (-1);
439         }
440         mpt2host_config_page_fc_port_0(&mpt->mpt_fcport_page0);
441
442         mpt->mpt_fcport_speed = mpt->mpt_fcport_page0.CurrentSpeed;
443
444         switch (mpt->mpt_fcport_page0.Flags &
445             MPI_FCPORTPAGE0_FLAGS_ATTACH_TYPE_MASK) {
446         case MPI_FCPORTPAGE0_FLAGS_ATTACH_NO_INIT:
447                 mpt->mpt_fcport_speed = 0;
448                 topology = "<NO LOOP>";
449                 break;
450         case MPI_FCPORTPAGE0_FLAGS_ATTACH_POINT_TO_POINT:
451                 topology = "N-Port";
452                 break;
453         case MPI_FCPORTPAGE0_FLAGS_ATTACH_PRIVATE_LOOP:
454                 topology = "NL-Port";
455                 break;
456         case MPI_FCPORTPAGE0_FLAGS_ATTACH_FABRIC_DIRECT:
457                 topology = "F-Port";
458                 break;
459         case MPI_FCPORTPAGE0_FLAGS_ATTACH_PUBLIC_LOOP:
460                 topology = "FL-Port";
461                 break;
462         default:
463                 mpt->mpt_fcport_speed = 0;
464                 topology = "?";
465                 break;
466         }
467
468         mpt_lprt(mpt, MPT_PRT_INFO,
469             "FC Port Page 0: Topology <%s> WWNN 0x%08x%08x WWPN 0x%08x%08x "
470             "Speed %u-Gbit\n", topology,
471             mpt->mpt_fcport_page0.WWNN.High,
472             mpt->mpt_fcport_page0.WWNN.Low,
473             mpt->mpt_fcport_page0.WWPN.High,
474             mpt->mpt_fcport_page0.WWPN.Low,
475             mpt->mpt_fcport_speed);
476 #if __FreeBSD_version >= 500000
477         MPT_UNLOCK(mpt);
478         {
479                 struct sysctl_ctx_list *ctx = device_get_sysctl_ctx(mpt->dev);
480                 struct sysctl_oid *tree = device_get_sysctl_tree(mpt->dev);
481
482                 snprintf(mpt->scinfo.fc.wwnn,
483                     sizeof (mpt->scinfo.fc.wwnn), "0x%08x%08x",
484                     mpt->mpt_fcport_page0.WWNN.High,
485                     mpt->mpt_fcport_page0.WWNN.Low);
486
487                 snprintf(mpt->scinfo.fc.wwpn,
488                     sizeof (mpt->scinfo.fc.wwpn), "0x%08x%08x",
489                     mpt->mpt_fcport_page0.WWPN.High,
490                     mpt->mpt_fcport_page0.WWPN.Low);
491
492                 SYSCTL_ADD_STRING(ctx, SYSCTL_CHILDREN(tree), OID_AUTO,
493                        "wwnn", CTLFLAG_RD, mpt->scinfo.fc.wwnn, 0,
494                        "World Wide Node Name");
495
496                 SYSCTL_ADD_STRING(ctx, SYSCTL_CHILDREN(tree), OID_AUTO,
497                        "wwpn", CTLFLAG_RD, mpt->scinfo.fc.wwpn, 0,
498                        "World Wide Port Name");
499
500         }
501         MPT_LOCK(mpt);
502 #endif
503         return (0);
504 }
505
506 /*
507  * Set FC configuration information.
508  */
509 static int
510 mpt_set_initial_config_fc(struct mpt_softc *mpt)
511 {
512         
513         CONFIG_PAGE_FC_PORT_1 fc;
514         U32 fl;
515         int r, doit = 0;
516         int role;
517
518         r = mpt_read_cfg_header(mpt, MPI_CONFIG_PAGETYPE_FC_PORT, 1, 0,
519             &fc.Header, FALSE, 5000);
520         if (r) {
521                 mpt_prt(mpt, "failed to read FC page 1 header\n");
522                 return (mpt_fc_reset_link(mpt, 1));
523         }
524
525         r = mpt_read_cfg_page(mpt, MPI_CONFIG_ACTION_PAGE_READ_NVRAM, 0,
526             &fc.Header, sizeof (fc), FALSE, 5000);
527         if (r) {
528                 mpt_prt(mpt, "failed to read FC page 1\n");
529                 return (mpt_fc_reset_link(mpt, 1));
530         }
531         mpt2host_config_page_fc_port_1(&fc);
532
533         /*
534          * Check our flags to make sure we support the role we want.
535          */
536         doit = 0;
537         role = 0;
538         fl = fc.Flags;
539
540         if (fl & MPI_FCPORTPAGE1_FLAGS_PROT_FCP_INIT) {
541                 role |= MPT_ROLE_INITIATOR;
542         }
543         if (fl & MPI_FCPORTPAGE1_FLAGS_PROT_FCP_TARG) {
544                 role |= MPT_ROLE_TARGET;
545         }
546
547         fl &= ~MPI_FCPORTPAGE1_FLAGS_PROT_MASK;
548
549         if (mpt->do_cfg_role == 0) {
550                 role = mpt->cfg_role;
551         } else {
552                 mpt->do_cfg_role = 0;
553         }
554
555         if (role != mpt->cfg_role) {
556                 if (mpt->cfg_role & MPT_ROLE_INITIATOR) {
557                         if ((role & MPT_ROLE_INITIATOR) == 0) {
558                                 mpt_prt(mpt, "adding initiator role\n");
559                                 fl |= MPI_FCPORTPAGE1_FLAGS_PROT_FCP_INIT;
560                                 doit++;
561                         } else {
562                                 mpt_prt(mpt, "keeping initiator role\n");
563                         }
564                 } else if (role & MPT_ROLE_INITIATOR) {
565                         mpt_prt(mpt, "removing initiator role\n");
566                         doit++;
567                 }
568                 if (mpt->cfg_role & MPT_ROLE_TARGET) {
569                         if ((role & MPT_ROLE_TARGET) == 0) {
570                                 mpt_prt(mpt, "adding target role\n");
571                                 fl |= MPI_FCPORTPAGE1_FLAGS_PROT_FCP_TARG;
572                                 doit++;
573                         } else {
574                                 mpt_prt(mpt, "keeping target role\n");
575                         }
576                 } else if (role & MPT_ROLE_TARGET) {
577                         mpt_prt(mpt, "removing target role\n");
578                         doit++;
579                 }
580                 mpt->role = mpt->cfg_role;
581         }
582
583         if (fl & MPI_FCPORTPAGE1_FLAGS_PROT_FCP_TARG) {
584                 if ((fl & MPI_FCPORTPAGE1_FLAGS_TARGET_MODE_OXID) == 0) {
585                         mpt_prt(mpt, "adding OXID option\n");
586                         fl |= MPI_FCPORTPAGE1_FLAGS_TARGET_MODE_OXID;
587                         doit++;
588                 }
589         }
590
591         if (doit) {
592                 fc.Flags = fl;
593                 host2mpt_config_page_fc_port_1(&fc);
594                 r = mpt_write_cfg_page(mpt,
595                     MPI_CONFIG_ACTION_PAGE_WRITE_NVRAM, 0, &fc.Header,
596                     sizeof(fc), FALSE, 5000);
597                 if (r != 0) {
598                         mpt_prt(mpt, "failed to update NVRAM with changes\n");
599                         return (0);
600                 }
601                 mpt_prt(mpt, "NOTE: NVRAM changes will not take "
602                     "effect until next reboot or IOC reset\n");
603         }
604         return (0);
605 }
606
607 static int
608 mptsas_sas_io_unit_pg0(struct mpt_softc *mpt, struct mptsas_portinfo *portinfo)
609 {
610         ConfigExtendedPageHeader_t hdr;
611         struct mptsas_phyinfo *phyinfo;
612         SasIOUnitPage0_t *buffer;
613         int error, len, i;
614
615         error = mpt_read_extcfg_header(mpt, MPI_SASIOUNITPAGE0_PAGEVERSION,
616                                        0, 0, MPI_CONFIG_EXTPAGETYPE_SAS_IO_UNIT,
617                                        &hdr, 0, 10000);
618         if (error)
619                 goto out;
620         if (hdr.ExtPageLength == 0) {
621                 error = ENXIO;
622                 goto out;
623         }
624
625         len = hdr.ExtPageLength * 4;
626         buffer = malloc(len, M_DEVBUF, M_NOWAIT|M_ZERO);
627         if (buffer == NULL) {
628                 error = ENOMEM;
629                 goto out;
630         }
631
632         error = mpt_read_extcfg_page(mpt, MPI_CONFIG_ACTION_PAGE_READ_CURRENT,
633                                      0, &hdr, buffer, len, 0, 10000);
634         if (error) {
635                 free(buffer, M_DEVBUF);
636                 goto out;
637         }
638
639         portinfo->num_phys = buffer->NumPhys;
640         portinfo->phy_info = malloc(sizeof(*portinfo->phy_info) *
641             portinfo->num_phys, M_DEVBUF, M_NOWAIT|M_ZERO);
642         if (portinfo->phy_info == NULL) {
643                 free(buffer, M_DEVBUF);
644                 error = ENOMEM;
645                 goto out;
646         }
647
648         for (i = 0; i < portinfo->num_phys; i++) {
649                 phyinfo = &portinfo->phy_info[i];
650                 phyinfo->phy_num = i;
651                 phyinfo->port_id = buffer->PhyData[i].Port;
652                 phyinfo->negotiated_link_rate =
653                     buffer->PhyData[i].NegotiatedLinkRate;
654                 phyinfo->handle =
655                     le16toh(buffer->PhyData[i].ControllerDevHandle);
656         }
657
658         free(buffer, M_DEVBUF);
659 out:
660         return (error);
661 }
662
663 static int
664 mptsas_sas_phy_pg0(struct mpt_softc *mpt, struct mptsas_phyinfo *phy_info,
665         uint32_t form, uint32_t form_specific)
666 {
667         ConfigExtendedPageHeader_t hdr;
668         SasPhyPage0_t *buffer;
669         int error;
670
671         error = mpt_read_extcfg_header(mpt, MPI_SASPHY0_PAGEVERSION, 0, 0,
672                                        MPI_CONFIG_EXTPAGETYPE_SAS_PHY, &hdr,
673                                        0, 10000);
674         if (error)
675                 goto out;
676         if (hdr.ExtPageLength == 0) {
677                 error = ENXIO;
678                 goto out;
679         }
680
681         buffer = malloc(sizeof(SasPhyPage0_t), M_DEVBUF, M_NOWAIT|M_ZERO);
682         if (buffer == NULL) {
683                 error = ENOMEM;
684                 goto out;
685         }
686
687         error = mpt_read_extcfg_page(mpt, MPI_CONFIG_ACTION_PAGE_READ_CURRENT,
688                                      form + form_specific, &hdr, buffer,
689                                      sizeof(SasPhyPage0_t), 0, 10000);
690         if (error) {
691                 free(buffer, M_DEVBUF);
692                 goto out;
693         }
694
695         phy_info->hw_link_rate = buffer->HwLinkRate;
696         phy_info->programmed_link_rate = buffer->ProgrammedLinkRate;
697         phy_info->identify.dev_handle = le16toh(buffer->OwnerDevHandle);
698         phy_info->attached.dev_handle = le16toh(buffer->AttachedDevHandle);
699
700         free(buffer, M_DEVBUF);
701 out:
702         return (error);
703 }
704
705 static int
706 mptsas_sas_device_pg0(struct mpt_softc *mpt, struct mptsas_devinfo *device_info,
707         uint32_t form, uint32_t form_specific)
708 {
709         ConfigExtendedPageHeader_t hdr;
710         SasDevicePage0_t *buffer;
711         uint64_t sas_address;
712         int error = 0;
713
714         bzero(device_info, sizeof(*device_info));
715         error = mpt_read_extcfg_header(mpt, MPI_SASDEVICE0_PAGEVERSION, 0, 0,
716                                        MPI_CONFIG_EXTPAGETYPE_SAS_DEVICE,
717                                        &hdr, 0, 10000);
718         if (error)
719                 goto out;
720         if (hdr.ExtPageLength == 0) {
721                 error = ENXIO;
722                 goto out;
723         }
724
725         buffer = malloc(sizeof(SasDevicePage0_t), M_DEVBUF, M_NOWAIT|M_ZERO);
726         if (buffer == NULL) {
727                 error = ENOMEM;
728                 goto out;
729         }
730
731         error = mpt_read_extcfg_page(mpt, MPI_CONFIG_ACTION_PAGE_READ_CURRENT,
732                                      form + form_specific, &hdr, buffer,
733                                      sizeof(SasDevicePage0_t), 0, 10000);
734         if (error) {
735                 free(buffer, M_DEVBUF);
736                 goto out;
737         }
738
739         device_info->dev_handle = le16toh(buffer->DevHandle);
740         device_info->parent_dev_handle = le16toh(buffer->ParentDevHandle);
741         device_info->enclosure_handle = le16toh(buffer->EnclosureHandle);
742         device_info->slot = le16toh(buffer->Slot);
743         device_info->phy_num = buffer->PhyNum;
744         device_info->physical_port = buffer->PhysicalPort;
745         device_info->target_id = buffer->TargetID;
746         device_info->bus = buffer->Bus;
747         bcopy(&buffer->SASAddress, &sas_address, sizeof(uint64_t));
748         device_info->sas_address = le64toh(sas_address);
749         device_info->device_info = le32toh(buffer->DeviceInfo);
750
751         free(buffer, M_DEVBUF);
752 out:
753         return (error);
754 }
755
756 /*
757  * Read SAS configuration information. Nothing to do yet.
758  */
759 static int
760 mpt_read_config_info_sas(struct mpt_softc *mpt)
761 {
762         struct mptsas_portinfo *portinfo;
763         struct mptsas_phyinfo *phyinfo;
764         int error, i;
765
766         portinfo = malloc(sizeof(*portinfo), M_DEVBUF, M_NOWAIT|M_ZERO);
767         if (portinfo == NULL)
768                 return (ENOMEM);
769
770         error = mptsas_sas_io_unit_pg0(mpt, portinfo);
771         if (error) {
772                 free(portinfo, M_DEVBUF);
773                 return (0);
774         }
775
776         for (i = 0; i < portinfo->num_phys; i++) {
777                 phyinfo = &portinfo->phy_info[i];
778                 error = mptsas_sas_phy_pg0(mpt, phyinfo,
779                     (MPI_SAS_PHY_PGAD_FORM_PHY_NUMBER <<
780                     MPI_SAS_PHY_PGAD_FORM_SHIFT), i);
781                 if (error)
782                         break;
783                 error = mptsas_sas_device_pg0(mpt, &phyinfo->identify,
784                     (MPI_SAS_DEVICE_PGAD_FORM_HANDLE <<
785                     MPI_SAS_DEVICE_PGAD_FORM_SHIFT),
786                     phyinfo->handle);
787                 if (error)
788                         break;
789                 phyinfo->identify.phy_num = phyinfo->phy_num = i;
790                 if (phyinfo->attached.dev_handle)
791                         error = mptsas_sas_device_pg0(mpt,
792                             &phyinfo->attached,
793                             (MPI_SAS_DEVICE_PGAD_FORM_HANDLE <<
794                             MPI_SAS_DEVICE_PGAD_FORM_SHIFT),
795                             phyinfo->attached.dev_handle);
796                 if (error)
797                         break;
798         }
799         mpt->sas_portinfo = portinfo;
800         return (0);
801 }
802
803 static void
804 mptsas_set_sata_wc(struct mpt_softc *mpt, struct mptsas_devinfo *devinfo,
805         int enabled)
806 {
807         SataPassthroughRequest_t        *pass;
808         request_t *req;
809         int error, status;
810
811         req = mpt_get_request(mpt, 0);
812         if (req == NULL)
813                 return;
814
815         pass = req->req_vbuf;
816         bzero(pass, sizeof(SataPassthroughRequest_t));
817         pass->Function = MPI_FUNCTION_SATA_PASSTHROUGH;
818         pass->TargetID = devinfo->target_id;
819         pass->Bus = devinfo->bus;
820         pass->PassthroughFlags = 0;
821         pass->ConnectionRate = MPI_SATA_PT_REQ_CONNECT_RATE_NEGOTIATED;
822         pass->DataLength = 0;
823         pass->MsgContext = htole32(req->index | sata_pass_handler_id);
824         pass->CommandFIS[0] = 0x27;
825         pass->CommandFIS[1] = 0x80;
826         pass->CommandFIS[2] = 0xef;
827         pass->CommandFIS[3] = (enabled) ? 0x02 : 0x82;
828         pass->CommandFIS[7] = 0x40;
829         pass->CommandFIS[15] = 0x08;
830
831         mpt_check_doorbell(mpt);
832         mpt_send_cmd(mpt, req);
833         error = mpt_wait_req(mpt, req, REQ_STATE_DONE, REQ_STATE_DONE, 0,
834                              10 * 1000);
835         if (error) {
836                 mpt_free_request(mpt, req);
837                 printf("error %d sending passthrough\n", error);
838                 return;
839         }
840
841         status = le16toh(req->IOCStatus);
842         if (status != MPI_IOCSTATUS_SUCCESS) {
843                 mpt_free_request(mpt, req);
844                 printf("IOCSTATUS %d\n", status);
845                 return;
846         }
847
848         mpt_free_request(mpt, req);
849 }
850
851 /*
852  * Set SAS configuration information. Nothing to do yet.
853  */
854 static int
855 mpt_set_initial_config_sas(struct mpt_softc *mpt)
856 {
857         struct mptsas_phyinfo *phyinfo;
858         int i;
859
860         if ((mpt_enable_sata_wc != -1) && (mpt->sas_portinfo != NULL)) {
861                 for (i = 0; i < mpt->sas_portinfo->num_phys; i++) {
862                         phyinfo = &mpt->sas_portinfo->phy_info[i];
863                         if (phyinfo->attached.dev_handle == 0)
864                                 continue;
865                         if ((phyinfo->attached.device_info &
866                             MPI_SAS_DEVICE_INFO_SATA_DEVICE) == 0)
867                                 continue;
868                         if (bootverbose)
869                                 device_printf(mpt->dev,
870                                     "%sabling SATA WC on phy %d\n",
871                                     (mpt_enable_sata_wc) ? "En" : "Dis", i);
872                         mptsas_set_sata_wc(mpt, &phyinfo->attached,
873                                            mpt_enable_sata_wc);
874                 }
875         }
876
877         return (0);
878 }
879
880 static int
881 mpt_sata_pass_reply_handler(struct mpt_softc *mpt, request_t *req,
882  uint32_t reply_desc, MSG_DEFAULT_REPLY *reply_frame)
883 {
884         if (req != NULL) {
885
886                 if (reply_frame != NULL) {
887                         MSG_SATA_PASSTHROUGH_REQUEST *pass;
888                         MSG_SATA_PASSTHROUGH_REPLY *reply;
889
890                         pass = (MSG_SATA_PASSTHROUGH_REQUEST *)req->req_vbuf;
891                         reply = (MSG_SATA_PASSTHROUGH_REPLY *)reply_frame;
892                         req->IOCStatus = le16toh(reply_frame->IOCStatus);
893                 }
894                 req->state &= ~REQ_STATE_QUEUED;
895                 req->state |= REQ_STATE_DONE;
896                 TAILQ_REMOVE(&mpt->request_pending_list, req, links);
897                 if ((req->state & REQ_STATE_NEED_WAKEUP) != 0) {
898                         wakeup(req);
899                 } else if ((req->state & REQ_STATE_TIMEDOUT) != 0) {
900                         /*
901                          * Whew- we can free this request (late completion)
902                          */
903                         mpt_free_request(mpt, req);
904                 }
905         }
906
907         return (TRUE);
908 }
909
910 /*
911  * Read SCSI configuration information
912  */
913 static int
914 mpt_read_config_info_spi(struct mpt_softc *mpt)
915 {
916         int rv, i;
917
918         rv = mpt_read_cfg_header(mpt, MPI_CONFIG_PAGETYPE_SCSI_PORT, 0, 0,
919             &mpt->mpt_port_page0.Header, FALSE, 5000);
920         if (rv) {
921                 return (-1);
922         }
923         mpt_lprt(mpt, MPT_PRT_DEBUG, "SPI Port Page 0 Header: %x %x %x %x\n",
924             mpt->mpt_port_page0.Header.PageVersion,
925             mpt->mpt_port_page0.Header.PageLength,
926             mpt->mpt_port_page0.Header.PageNumber,
927             mpt->mpt_port_page0.Header.PageType);
928
929         rv = mpt_read_cfg_header(mpt, MPI_CONFIG_PAGETYPE_SCSI_PORT, 1, 0,
930             &mpt->mpt_port_page1.Header, FALSE, 5000);
931         if (rv) {
932                 return (-1);
933         }
934         mpt_lprt(mpt, MPT_PRT_DEBUG, "SPI Port Page 1 Header: %x %x %x %x\n",
935             mpt->mpt_port_page1.Header.PageVersion,
936             mpt->mpt_port_page1.Header.PageLength,
937             mpt->mpt_port_page1.Header.PageNumber,
938             mpt->mpt_port_page1.Header.PageType);
939
940         rv = mpt_read_cfg_header(mpt, MPI_CONFIG_PAGETYPE_SCSI_PORT, 2, 0,
941             &mpt->mpt_port_page2.Header, FALSE, 5000);
942         if (rv) {
943                 return (-1);
944         }
945         mpt_lprt(mpt, MPT_PRT_DEBUG, "SPI Port Page 2 Header: %x %x %x %x\n",
946             mpt->mpt_port_page2.Header.PageVersion,
947             mpt->mpt_port_page2.Header.PageLength,
948             mpt->mpt_port_page2.Header.PageNumber,
949             mpt->mpt_port_page2.Header.PageType);
950
951         for (i = 0; i < 16; i++) {
952                 rv = mpt_read_cfg_header(mpt, MPI_CONFIG_PAGETYPE_SCSI_DEVICE,
953                     0, i, &mpt->mpt_dev_page0[i].Header, FALSE, 5000);
954                 if (rv) {
955                         return (-1);
956                 }
957                 mpt_lprt(mpt, MPT_PRT_DEBUG,
958                     "SPI Target %d Device Page 0 Header: %x %x %x %x\n", i,
959                     mpt->mpt_dev_page0[i].Header.PageVersion,
960                     mpt->mpt_dev_page0[i].Header.PageLength,
961                     mpt->mpt_dev_page0[i].Header.PageNumber,
962                     mpt->mpt_dev_page0[i].Header.PageType);
963                 
964                 rv = mpt_read_cfg_header(mpt, MPI_CONFIG_PAGETYPE_SCSI_DEVICE,
965                     1, i, &mpt->mpt_dev_page1[i].Header, FALSE, 5000);
966                 if (rv) {
967                         return (-1);
968                 }
969                 mpt_lprt(mpt, MPT_PRT_DEBUG,
970                     "SPI Target %d Device Page 1 Header: %x %x %x %x\n", i,
971                     mpt->mpt_dev_page1[i].Header.PageVersion,
972                     mpt->mpt_dev_page1[i].Header.PageLength,
973                     mpt->mpt_dev_page1[i].Header.PageNumber,
974                     mpt->mpt_dev_page1[i].Header.PageType);
975         }
976
977         /*
978          * At this point, we don't *have* to fail. As long as we have
979          * valid config header information, we can (barely) lurch
980          * along.
981          */
982
983         rv = mpt_read_cur_cfg_page(mpt, 0, &mpt->mpt_port_page0.Header,
984             sizeof(mpt->mpt_port_page0), FALSE, 5000);
985         if (rv) {
986                 mpt_prt(mpt, "failed to read SPI Port Page 0\n");
987         } else {
988                 mpt2host_config_page_scsi_port_0(&mpt->mpt_port_page0);
989                 mpt_lprt(mpt, MPT_PRT_NEGOTIATION,
990                     "SPI Port Page 0: Capabilities %x PhysicalInterface %x\n",
991                     mpt->mpt_port_page0.Capabilities,
992                     mpt->mpt_port_page0.PhysicalInterface);
993         }
994
995         rv = mpt_read_cur_cfg_page(mpt, 0, &mpt->mpt_port_page1.Header,
996             sizeof(mpt->mpt_port_page1), FALSE, 5000);
997         if (rv) {
998                 mpt_prt(mpt, "failed to read SPI Port Page 1\n");
999         } else {
1000                 mpt2host_config_page_scsi_port_1(&mpt->mpt_port_page1);
1001                 mpt_lprt(mpt, MPT_PRT_DEBUG,
1002                     "SPI Port Page 1: Configuration %x OnBusTimerValue %x\n",
1003                     mpt->mpt_port_page1.Configuration,
1004                     mpt->mpt_port_page1.OnBusTimerValue);
1005         }
1006
1007         rv = mpt_read_cur_cfg_page(mpt, 0, &mpt->mpt_port_page2.Header,
1008             sizeof(mpt->mpt_port_page2), FALSE, 5000);
1009         if (rv) {
1010                 mpt_prt(mpt, "failed to read SPI Port Page 2\n");
1011         } else {
1012                 mpt_lprt(mpt, MPT_PRT_NEGOTIATION,
1013                     "Port Page 2: Flags %x Settings %x\n",
1014                     mpt->mpt_port_page2.PortFlags,
1015                     mpt->mpt_port_page2.PortSettings);
1016                 mpt2host_config_page_scsi_port_2(&mpt->mpt_port_page2);
1017                 for (i = 0; i < 16; i++) {
1018                         mpt_lprt(mpt, MPT_PRT_NEGOTIATION,
1019                             " Port Page 2 Tgt %d: timo %x SF %x Flags %x\n",
1020                             i, mpt->mpt_port_page2.DeviceSettings[i].Timeout,
1021                             mpt->mpt_port_page2.DeviceSettings[i].SyncFactor,
1022                             mpt->mpt_port_page2.DeviceSettings[i].DeviceFlags);
1023                 }
1024         }
1025
1026         for (i = 0; i < 16; i++) {
1027                 rv = mpt_read_cur_cfg_page(mpt, i,
1028                     &mpt->mpt_dev_page0[i].Header, sizeof(*mpt->mpt_dev_page0),
1029                     FALSE, 5000);
1030                 if (rv) {
1031                         mpt_prt(mpt,
1032                             "cannot read SPI Target %d Device Page 0\n", i);
1033                         continue;
1034                 }
1035                 mpt2host_config_page_scsi_device_0(&mpt->mpt_dev_page0[i]);
1036                 mpt_lprt(mpt, MPT_PRT_NEGOTIATION,
1037                     "target %d page 0: Negotiated Params %x Information %x\n",
1038                     i, mpt->mpt_dev_page0[i].NegotiatedParameters,
1039                     mpt->mpt_dev_page0[i].Information);
1040
1041                 rv = mpt_read_cur_cfg_page(mpt, i,
1042                     &mpt->mpt_dev_page1[i].Header, sizeof(*mpt->mpt_dev_page1),
1043                     FALSE, 5000);
1044                 if (rv) {
1045                         mpt_prt(mpt,
1046                             "cannot read SPI Target %d Device Page 1\n", i);
1047                         continue;
1048                 }
1049                 mpt2host_config_page_scsi_device_1(&mpt->mpt_dev_page1[i]);
1050                 mpt_lprt(mpt, MPT_PRT_NEGOTIATION,
1051                     "target %d page 1: Requested Params %x Configuration %x\n",
1052                     i, mpt->mpt_dev_page1[i].RequestedParameters,
1053                     mpt->mpt_dev_page1[i].Configuration);
1054         }
1055         return (0);
1056 }
1057
1058 /*
1059  * Validate SPI configuration information.
1060  *
1061  * In particular, validate SPI Port Page 1.
1062  */
1063 static int
1064 mpt_set_initial_config_spi(struct mpt_softc *mpt)
1065 {
1066         int i, j, pp1val = ((1 << mpt->mpt_ini_id) << 16) | mpt->mpt_ini_id;
1067         int error;
1068
1069         mpt->mpt_disc_enable = 0xff;
1070         mpt->mpt_tag_enable = 0;
1071
1072         if (mpt->mpt_port_page1.Configuration != pp1val) {
1073                 CONFIG_PAGE_SCSI_PORT_1 tmp;
1074
1075                 mpt_prt(mpt, "SPI Port Page 1 Config value bad (%x)- should "
1076                     "be %x\n", mpt->mpt_port_page1.Configuration, pp1val);
1077                 tmp = mpt->mpt_port_page1;
1078                 tmp.Configuration = pp1val;
1079                 host2mpt_config_page_scsi_port_1(&tmp);
1080                 error = mpt_write_cur_cfg_page(mpt, 0,
1081                     &tmp.Header, sizeof(tmp), FALSE, 5000);
1082                 if (error) {
1083                         return (-1);
1084                 }
1085                 error = mpt_read_cur_cfg_page(mpt, 0,
1086                     &tmp.Header, sizeof(tmp), FALSE, 5000);
1087                 if (error) {
1088                         return (-1);
1089                 }
1090                 mpt2host_config_page_scsi_port_1(&tmp);
1091                 if (tmp.Configuration != pp1val) {
1092                         mpt_prt(mpt,
1093                             "failed to reset SPI Port Page 1 Config value\n");
1094                         return (-1);
1095                 }
1096                 mpt->mpt_port_page1 = tmp;
1097         }
1098
1099         /*
1100          * The purpose of this exercise is to get
1101          * all targets back to async/narrow.
1102          *
1103          * We skip this step if the BIOS has already negotiated
1104          * speeds with the targets and does not require us to
1105          * do Domain Validation.
1106          */
1107         i = mpt->mpt_port_page2.PortSettings &
1108             MPI_SCSIPORTPAGE2_PORT_MASK_NEGO_MASTER_SETTINGS;
1109         j = mpt->mpt_port_page2.PortFlags &
1110             MPI_SCSIPORTPAGE2_PORT_FLAGS_DV_MASK;
1111         if (i == MPI_SCSIPORTPAGE2_PORT_ALL_MASTER_SETTINGS /* &&
1112             j == MPI_SCSIPORTPAGE2_PORT_FLAGS_OFF_DV */) {
1113                 mpt_lprt(mpt, MPT_PRT_NEGOTIATION,
1114                     "honoring BIOS transfer negotiations\n");
1115         } else {
1116                 for (i = 0; i < 16; i++) {
1117                         mpt->mpt_dev_page1[i].RequestedParameters = 0;
1118                         mpt->mpt_dev_page1[i].Configuration = 0;
1119                         (void) mpt_update_spi_config(mpt, i);
1120                 }
1121         }
1122         return (0);
1123 }
1124
1125 int
1126 mpt_cam_enable(struct mpt_softc *mpt)
1127 {
1128         int error;
1129
1130         MPT_LOCK(mpt);
1131
1132         error = EIO;
1133         if (mpt->is_fc) {
1134                 if (mpt_read_config_info_fc(mpt)) {
1135                         goto out;
1136                 }
1137                 if (mpt_set_initial_config_fc(mpt)) {
1138                         goto out;
1139                 }
1140         } else if (mpt->is_sas) {
1141                 if (mpt_read_config_info_sas(mpt)) {
1142                         goto out;
1143                 }
1144                 if (mpt_set_initial_config_sas(mpt)) {
1145                         goto out;
1146                 }
1147         } else if (mpt->is_spi) {
1148                 if (mpt_read_config_info_spi(mpt)) {
1149                         goto out;
1150                 }
1151                 if (mpt_set_initial_config_spi(mpt)) {
1152                         goto out;
1153                 }
1154         }
1155         error = 0;
1156
1157 out:
1158         MPT_UNLOCK(mpt);
1159         return (error);
1160 }
1161
1162 void
1163 mpt_cam_ready(struct mpt_softc *mpt)
1164 {
1165         /*
1166          * If we're in target mode, hang out resources now
1167          * so we don't cause the world to hang talking to us.
1168          */
1169         if (mpt->is_fc && (mpt->role & MPT_ROLE_TARGET)) {
1170                 /*
1171                  * Try to add some target command resources
1172                  */
1173                 MPT_LOCK(mpt);
1174                 if (mpt_add_target_commands(mpt) == FALSE) {
1175                         mpt_prt(mpt, "failed to add target commands\n");
1176                 }
1177                 MPT_UNLOCK(mpt);
1178         }
1179         mpt->ready = 1;
1180 }
1181
1182 void
1183 mpt_cam_detach(struct mpt_softc *mpt)
1184 {
1185         mpt_handler_t handler;
1186
1187         MPT_LOCK(mpt);
1188         mpt->ready = 0;
1189         mpt_terminate_recovery_thread(mpt); 
1190
1191         handler.reply_handler = mpt_scsi_reply_handler;
1192         mpt_deregister_handler(mpt, MPT_HANDLER_REPLY, handler,
1193                                scsi_io_handler_id);
1194         handler.reply_handler = mpt_scsi_tmf_reply_handler;
1195         mpt_deregister_handler(mpt, MPT_HANDLER_REPLY, handler,
1196                                scsi_tmf_handler_id);
1197         handler.reply_handler = mpt_fc_els_reply_handler;
1198         mpt_deregister_handler(mpt, MPT_HANDLER_REPLY, handler,
1199                                fc_els_handler_id);
1200         handler.reply_handler = mpt_scsi_tgt_reply_handler;
1201         mpt_deregister_handler(mpt, MPT_HANDLER_REPLY, handler,
1202                                mpt->scsi_tgt_handler_id);
1203         handler.reply_handler = mpt_sata_pass_reply_handler;
1204         mpt_deregister_handler(mpt, MPT_HANDLER_REPLY, handler,
1205                                sata_pass_handler_id);
1206
1207         if (mpt->tmf_req != NULL) {
1208                 mpt->tmf_req->state = REQ_STATE_ALLOCATED;
1209                 mpt_free_request(mpt, mpt->tmf_req);
1210                 mpt->tmf_req = NULL;
1211         }
1212         if (mpt->sas_portinfo != NULL) {
1213                 free(mpt->sas_portinfo, M_DEVBUF);
1214                 mpt->sas_portinfo = NULL;
1215         }
1216         MPT_UNLOCK(mpt);
1217
1218         if (mpt->sim != NULL) {
1219                 xpt_free_path(mpt->path);
1220                 xpt_bus_deregister(cam_sim_path(mpt->sim));
1221                 cam_sim_free(mpt->sim, TRUE);
1222                 mpt->sim = NULL;
1223         }
1224
1225         if (mpt->phydisk_sim != NULL) {
1226                 xpt_free_path(mpt->phydisk_path);
1227                 xpt_bus_deregister(cam_sim_path(mpt->phydisk_sim));
1228                 cam_sim_free(mpt->phydisk_sim, TRUE);
1229                 mpt->phydisk_sim = NULL;
1230         }
1231 }
1232
1233 /* This routine is used after a system crash to dump core onto the swap device.
1234  */
1235 static void
1236 mpt_poll(struct cam_sim *sim)
1237 {
1238         struct mpt_softc *mpt;
1239
1240         mpt = (struct mpt_softc *)cam_sim_softc(sim);
1241         mpt_intr(mpt);
1242 }
1243
1244 /*
1245  * Watchdog timeout routine for SCSI requests.
1246  */
1247 static void
1248 mpt_timeout(void *arg)
1249 {
1250         union ccb        *ccb;
1251         struct mpt_softc *mpt;
1252         request_t        *req;
1253
1254         ccb = (union ccb *)arg;
1255         mpt = ccb->ccb_h.ccb_mpt_ptr;
1256
1257         MPT_LOCK(mpt);
1258         req = ccb->ccb_h.ccb_req_ptr;
1259         mpt_prt(mpt, "request %p:%u timed out for ccb %p (req->ccb %p)\n", req,
1260             req->serno, ccb, req->ccb);
1261 /* XXX: WHAT ARE WE TRYING TO DO HERE? */
1262         if ((req->state & REQ_STATE_QUEUED) == REQ_STATE_QUEUED) {
1263                 TAILQ_REMOVE(&mpt->request_pending_list, req, links);
1264                 TAILQ_INSERT_TAIL(&mpt->request_timeout_list, req, links);
1265                 req->state |= REQ_STATE_TIMEDOUT;
1266                 mpt_wakeup_recovery_thread(mpt);
1267         }
1268         MPT_UNLOCK(mpt);
1269 }
1270
1271 /*
1272  * Callback routine from "bus_dmamap_load" or, in simple cases, called directly.
1273  *
1274  * Takes a list of physical segments and builds the SGL for SCSI IO command
1275  * and forwards the commard to the IOC after one last check that CAM has not
1276  * aborted the transaction.
1277  */
1278 static void
1279 mpt_execute_req_a64(void *arg, bus_dma_segment_t *dm_segs, int nseg, int error)
1280 {
1281         request_t *req, *trq;
1282         char *mpt_off;
1283         union ccb *ccb;
1284         struct mpt_softc *mpt;
1285         int seg, first_lim;
1286         uint32_t flags, nxt_off;
1287         void *sglp = NULL;
1288         MSG_REQUEST_HEADER *hdrp;
1289         SGE_SIMPLE64 *se;
1290         SGE_CHAIN64 *ce;
1291         int istgt = 0;
1292
1293         req = (request_t *)arg;
1294         ccb = req->ccb;
1295
1296         mpt = ccb->ccb_h.ccb_mpt_ptr;
1297         req = ccb->ccb_h.ccb_req_ptr;
1298
1299         hdrp = req->req_vbuf;
1300         mpt_off = req->req_vbuf;
1301
1302         if (error == 0 && ((uint32_t)nseg) >= mpt->max_seg_cnt) {
1303                 error = EFBIG;
1304         }
1305
1306         if (error == 0) {
1307                 switch (hdrp->Function) {
1308                 case MPI_FUNCTION_SCSI_IO_REQUEST:
1309                 case MPI_FUNCTION_RAID_SCSI_IO_PASSTHROUGH:
1310                         istgt = 0;
1311                         sglp = &((PTR_MSG_SCSI_IO_REQUEST)hdrp)->SGL;
1312                         break;
1313                 case MPI_FUNCTION_TARGET_ASSIST:
1314                         istgt = 1;
1315                         sglp = &((PTR_MSG_TARGET_ASSIST_REQUEST)hdrp)->SGL;
1316                         break;
1317                 default:
1318                         mpt_prt(mpt, "bad fct 0x%x in mpt_execute_req_a64\n",
1319                             hdrp->Function);
1320                         error = EINVAL;
1321                         break;
1322                 }
1323         }
1324
1325         if (error == 0 && ((uint32_t)nseg) >= mpt->max_seg_cnt) {
1326                 error = EFBIG;
1327                 mpt_prt(mpt, "segment count %d too large (max %u)\n",
1328                     nseg, mpt->max_seg_cnt);
1329         }
1330
1331 bad:
1332         if (error != 0) {
1333                 if (error != EFBIG && error != ENOMEM) {
1334                         mpt_prt(mpt, "mpt_execute_req_a64: err %d\n", error);
1335                 }
1336                 if ((ccb->ccb_h.status & CAM_STATUS_MASK) == CAM_REQ_INPROG) {
1337                         cam_status status;
1338                         mpt_freeze_ccb(ccb);
1339                         if (error == EFBIG) {
1340                                 status = CAM_REQ_TOO_BIG;
1341                         } else if (error == ENOMEM) {
1342                                 if (mpt->outofbeer == 0) {
1343                                         mpt->outofbeer = 1;
1344                                         xpt_freeze_simq(mpt->sim, 1);
1345                                         mpt_lprt(mpt, MPT_PRT_DEBUG,
1346                                             "FREEZEQ\n");
1347                                 }
1348                                 status = CAM_REQUEUE_REQ;
1349                         } else {
1350                                 status = CAM_REQ_CMP_ERR;
1351                         }
1352                         mpt_set_ccb_status(ccb, status);
1353                 }
1354                 if (hdrp->Function == MPI_FUNCTION_TARGET_ASSIST) {
1355                         request_t *cmd_req =
1356                                 MPT_TAG_2_REQ(mpt, ccb->csio.tag_id);
1357                         MPT_TGT_STATE(mpt, cmd_req)->state = TGT_STATE_IN_CAM;
1358                         MPT_TGT_STATE(mpt, cmd_req)->ccb = NULL;
1359                         MPT_TGT_STATE(mpt, cmd_req)->req = NULL;
1360                 }
1361                 ccb->ccb_h.status &= ~CAM_SIM_QUEUED;
1362                 KASSERT(ccb->ccb_h.status, ("zero ccb sts at %d\n", __LINE__));
1363                 xpt_done(ccb);
1364                 CAMLOCK_2_MPTLOCK(mpt);
1365                 mpt_free_request(mpt, req);
1366                 MPTLOCK_2_CAMLOCK(mpt);
1367                 return;
1368         }
1369
1370         /*
1371          * No data to transfer?
1372          * Just make a single simple SGL with zero length.
1373          */
1374
1375         if (mpt->verbose >= MPT_PRT_DEBUG) {
1376                 int tidx = ((char *)sglp) - mpt_off;
1377                 memset(&mpt_off[tidx], 0xff, MPT_REQUEST_AREA - tidx);
1378         }
1379
1380         if (nseg == 0) {
1381                 SGE_SIMPLE32 *se1 = (SGE_SIMPLE32 *) sglp;
1382                 MPI_pSGE_SET_FLAGS(se1,
1383                     (MPI_SGE_FLAGS_LAST_ELEMENT | MPI_SGE_FLAGS_END_OF_BUFFER |
1384                     MPI_SGE_FLAGS_SIMPLE_ELEMENT | MPI_SGE_FLAGS_END_OF_LIST));
1385                 se1->FlagsLength = htole32(se1->FlagsLength);
1386                 goto out;
1387         }
1388
1389
1390         flags = MPI_SGE_FLAGS_SIMPLE_ELEMENT | MPI_SGE_FLAGS_64_BIT_ADDRESSING;
1391         if (istgt == 0) {
1392                 if ((ccb->ccb_h.flags & CAM_DIR_MASK) == CAM_DIR_OUT) {
1393                         flags |= MPI_SGE_FLAGS_HOST_TO_IOC;
1394                 }
1395         } else {
1396                 if ((ccb->ccb_h.flags & CAM_DIR_MASK) == CAM_DIR_IN) {
1397                         flags |= MPI_SGE_FLAGS_HOST_TO_IOC;
1398                 }
1399         }
1400
1401         if (!(ccb->ccb_h.flags & (CAM_SG_LIST_PHYS|CAM_DATA_PHYS))) {
1402                 bus_dmasync_op_t op;
1403                 if (istgt == 0) {
1404                         if ((ccb->ccb_h.flags & CAM_DIR_MASK) == CAM_DIR_IN) {
1405                                 op = BUS_DMASYNC_PREREAD;
1406                         } else {
1407                                 op = BUS_DMASYNC_PREWRITE;
1408                         }
1409                 } else {
1410                         if ((ccb->ccb_h.flags & CAM_DIR_MASK) == CAM_DIR_IN) {
1411                                 op = BUS_DMASYNC_PREWRITE;
1412                         } else {
1413                                 op = BUS_DMASYNC_PREREAD;
1414                         }
1415                 }
1416                 bus_dmamap_sync(mpt->buffer_dmat, req->dmap, op);
1417         }
1418
1419         /*
1420          * Okay, fill in what we can at the end of the command frame.
1421          * If we have up to MPT_NSGL_FIRST, we can fit them all into
1422          * the command frame.
1423          *
1424          * Otherwise, we fill up through MPT_NSGL_FIRST less one
1425          * SIMPLE64 pointers and start doing CHAIN64 entries after
1426          * that.
1427          */
1428
1429         if (nseg < MPT_NSGL_FIRST(mpt)) {
1430                 first_lim = nseg;
1431         } else {
1432                 /*
1433                  * Leave room for CHAIN element
1434                  */
1435                 first_lim = MPT_NSGL_FIRST(mpt) - 1;
1436         }
1437
1438         se = (SGE_SIMPLE64 *) sglp;
1439         for (seg = 0; seg < first_lim; seg++, se++, dm_segs++) {
1440                 uint32_t tf;
1441
1442                 memset(se, 0, sizeof (*se));
1443                 se->Address.Low = htole32(dm_segs->ds_addr & 0xffffffff);
1444                 if (sizeof(bus_addr_t) > 4) {
1445                         se->Address.High =
1446                             htole32(((uint64_t)dm_segs->ds_addr) >> 32);
1447                 }
1448                 MPI_pSGE_SET_LENGTH(se, dm_segs->ds_len);
1449                 tf = flags;
1450                 if (seg == first_lim - 1) {
1451                         tf |= MPI_SGE_FLAGS_LAST_ELEMENT;
1452                 }
1453                 if (seg == nseg - 1) {
1454                         tf |=   MPI_SGE_FLAGS_END_OF_LIST |
1455                                 MPI_SGE_FLAGS_END_OF_BUFFER;
1456                 }
1457                 MPI_pSGE_SET_FLAGS(se, tf);
1458                 se->FlagsLength = htole32(se->FlagsLength);
1459         }
1460
1461         if (seg == nseg) {
1462                 goto out;
1463         }
1464
1465         /*
1466          * Tell the IOC where to find the first chain element.
1467          */
1468         hdrp->ChainOffset = ((char *)se - (char *)hdrp) >> 2;
1469         nxt_off = MPT_RQSL(mpt);
1470         trq = req;
1471
1472         /*
1473          * Make up the rest of the data segments out of a chain element
1474          * (contiained in the current request frame) which points to
1475          * SIMPLE64 elements in the next request frame, possibly ending
1476          * with *another* chain element (if there's more).
1477          */
1478         while (seg < nseg) {
1479                 int this_seg_lim;
1480                 uint32_t tf, cur_off;
1481                 bus_addr_t chain_list_addr;
1482
1483                 /*
1484                  * Point to the chain descriptor. Note that the chain
1485                  * descriptor is at the end of the *previous* list (whether
1486                  * chain or simple).
1487                  */
1488                 ce = (SGE_CHAIN64 *) se;
1489
1490                 /*
1491                  * Before we change our current pointer, make  sure we won't
1492                  * overflow the request area with this frame. Note that we
1493                  * test against 'greater than' here as it's okay in this case
1494                  * to have next offset be just outside the request area.
1495                  */
1496                 if ((nxt_off + MPT_RQSL(mpt)) > MPT_REQUEST_AREA) {
1497                         nxt_off = MPT_REQUEST_AREA;
1498                         goto next_chain;
1499                 }
1500
1501                 /*
1502                  * Set our SGE element pointer to the beginning of the chain
1503                  * list and update our next chain list offset.
1504                  */
1505                 se = (SGE_SIMPLE64 *) &mpt_off[nxt_off];
1506                 cur_off = nxt_off;
1507                 nxt_off += MPT_RQSL(mpt);
1508
1509                 /*
1510                  * Now initialized the chain descriptor.
1511                  */
1512                 memset(ce, 0, sizeof (*ce));
1513
1514                 /*
1515                  * Get the physical address of the chain list.
1516                  */
1517                 chain_list_addr = trq->req_pbuf;
1518                 chain_list_addr += cur_off;
1519                 if (sizeof (bus_addr_t) > 4) {
1520                         ce->Address.High =
1521                             htole32(((uint64_t)chain_list_addr) >> 32);
1522                 }
1523                 ce->Address.Low = htole32(chain_list_addr & 0xffffffff);
1524                 ce->Flags = MPI_SGE_FLAGS_CHAIN_ELEMENT |
1525                             MPI_SGE_FLAGS_64_BIT_ADDRESSING;
1526
1527                 /*
1528                  * If we have more than a frame's worth of segments left,
1529                  * set up the chain list to have the last element be another
1530                  * chain descriptor.
1531                  */
1532                 if ((nseg - seg) > MPT_NSGL(mpt)) {
1533                         this_seg_lim = seg + MPT_NSGL(mpt) - 1;
1534                         /*
1535                          * The length of the chain is the length in bytes of the
1536                          * number of segments plus the next chain element.
1537                          *
1538                          * The next chain descriptor offset is the length,
1539                          * in words, of the number of segments.
1540                          */
1541                         ce->Length = (this_seg_lim - seg) *
1542                             sizeof (SGE_SIMPLE64);
1543                         ce->NextChainOffset = ce->Length >> 2;
1544                         ce->Length += sizeof (SGE_CHAIN64);
1545                 } else {
1546                         this_seg_lim = nseg;
1547                         ce->Length = (this_seg_lim - seg) *
1548                             sizeof (SGE_SIMPLE64);
1549                 }
1550                 ce->Length = htole16(ce->Length);
1551
1552                 /*
1553                  * Fill in the chain list SGE elements with our segment data.
1554                  *
1555                  * If we're the last element in this chain list, set the last
1556                  * element flag. If we're the completely last element period,
1557                  * set the end of list and end of buffer flags.
1558                  */
1559                 while (seg < this_seg_lim) {
1560                         memset(se, 0, sizeof (*se));
1561                         se->Address.Low = htole32(dm_segs->ds_addr &
1562                             0xffffffff);
1563                         if (sizeof (bus_addr_t) > 4) {
1564                                 se->Address.High =
1565                                     htole32(((uint64_t)dm_segs->ds_addr) >> 32);
1566                         }
1567                         MPI_pSGE_SET_LENGTH(se, dm_segs->ds_len);
1568                         tf = flags;
1569                         if (seg ==  this_seg_lim - 1) {
1570                                 tf |=   MPI_SGE_FLAGS_LAST_ELEMENT;
1571                         }
1572                         if (seg == nseg - 1) {
1573                                 tf |=   MPI_SGE_FLAGS_END_OF_LIST |
1574                                         MPI_SGE_FLAGS_END_OF_BUFFER;
1575                         }
1576                         MPI_pSGE_SET_FLAGS(se, tf);
1577                         se->FlagsLength = htole32(se->FlagsLength);
1578                         se++;
1579                         seg++;
1580                         dm_segs++;
1581                 }
1582
1583     next_chain:
1584                 /*
1585                  * If we have more segments to do and we've used up all of
1586                  * the space in a request area, go allocate another one
1587                  * and chain to that.
1588                  */
1589                 if (seg < nseg && nxt_off >= MPT_REQUEST_AREA) {
1590                         request_t *nrq;
1591
1592                         CAMLOCK_2_MPTLOCK(mpt);
1593                         nrq = mpt_get_request(mpt, FALSE);
1594                         MPTLOCK_2_CAMLOCK(mpt);
1595
1596                         if (nrq == NULL) {
1597                                 error = ENOMEM;
1598                                 goto bad;
1599                         }
1600
1601                         /*
1602                          * Append the new request area on the tail of our list.
1603                          */
1604                         if ((trq = req->chain) == NULL) {
1605                                 req->chain = nrq;
1606                         } else {
1607                                 while (trq->chain != NULL) {
1608                                         trq = trq->chain;
1609                                 }
1610                                 trq->chain = nrq;
1611                         }
1612                         trq = nrq;
1613                         mpt_off = trq->req_vbuf;
1614                         if (mpt->verbose >= MPT_PRT_DEBUG) {
1615                                 memset(mpt_off, 0xff, MPT_REQUEST_AREA);
1616                         }
1617                         nxt_off = 0;
1618                 }
1619         }
1620 out:
1621
1622         /*
1623          * Last time we need to check if this CCB needs to be aborted.
1624          */
1625         if ((ccb->ccb_h.status & CAM_STATUS_MASK) != CAM_REQ_INPROG) {
1626                 if (hdrp->Function == MPI_FUNCTION_TARGET_ASSIST) {
1627                         request_t *cmd_req =
1628                                 MPT_TAG_2_REQ(mpt, ccb->csio.tag_id);
1629                         MPT_TGT_STATE(mpt, cmd_req)->state = TGT_STATE_IN_CAM;
1630                         MPT_TGT_STATE(mpt, cmd_req)->ccb = NULL;
1631                         MPT_TGT_STATE(mpt, cmd_req)->req = NULL;
1632                 }
1633                 mpt_prt(mpt,
1634                     "mpt_execute_req_a64: I/O cancelled (status 0x%x)\n",
1635                     ccb->ccb_h.status & CAM_STATUS_MASK);
1636                 if (nseg && (ccb->ccb_h.flags & CAM_SG_LIST_PHYS) == 0) {
1637                         bus_dmamap_unload(mpt->buffer_dmat, req->dmap);
1638                 }
1639                 ccb->ccb_h.status &= ~CAM_SIM_QUEUED;
1640                 KASSERT(ccb->ccb_h.status, ("zero ccb sts at %d\n", __LINE__));
1641                 xpt_done(ccb);
1642                 CAMLOCK_2_MPTLOCK(mpt);
1643                 mpt_free_request(mpt, req);
1644                 MPTLOCK_2_CAMLOCK(mpt);
1645                 return;
1646         }
1647
1648         ccb->ccb_h.status |= CAM_SIM_QUEUED;
1649         if (ccb->ccb_h.timeout != CAM_TIME_INFINITY) {
1650                 mpt_req_timeout(req, (ccb->ccb_h.timeout * hz) / 1000,
1651                     mpt_timeout, ccb);
1652         }
1653         if (mpt->verbose > MPT_PRT_DEBUG) {
1654                 int nc = 0;
1655                 mpt_print_request(req->req_vbuf);
1656                 for (trq = req->chain; trq; trq = trq->chain) {
1657                         printf("  Additional Chain Area %d\n", nc++);
1658                         mpt_dump_sgl(trq->req_vbuf, 0);
1659                 }
1660         }
1661
1662         if (hdrp->Function == MPI_FUNCTION_TARGET_ASSIST) {
1663                 request_t *cmd_req = MPT_TAG_2_REQ(mpt, ccb->csio.tag_id);
1664                 mpt_tgt_state_t *tgt = MPT_TGT_STATE(mpt, cmd_req);
1665 #ifdef  WE_TRUST_AUTO_GOOD_STATUS
1666                 if ((ccb->ccb_h.flags & CAM_SEND_STATUS) &&
1667                     csio->scsi_status == SCSI_STATUS_OK && tgt->resid == 0) {
1668                         tgt->state = TGT_STATE_MOVING_DATA_AND_STATUS;
1669                 } else {
1670                         tgt->state = TGT_STATE_MOVING_DATA;
1671                 }
1672 #else
1673                 tgt->state = TGT_STATE_MOVING_DATA;
1674 #endif
1675         }
1676         CAMLOCK_2_MPTLOCK(mpt);
1677         mpt_send_cmd(mpt, req);
1678         MPTLOCK_2_CAMLOCK(mpt);
1679 }
1680
1681 static void
1682 mpt_execute_req(void *arg, bus_dma_segment_t *dm_segs, int nseg, int error)
1683 {
1684         request_t *req, *trq;
1685         char *mpt_off;
1686         union ccb *ccb;
1687         struct mpt_softc *mpt;
1688         int seg, first_lim;
1689         uint32_t flags, nxt_off;
1690         void *sglp = NULL;
1691         MSG_REQUEST_HEADER *hdrp;
1692         SGE_SIMPLE32 *se;
1693         SGE_CHAIN32 *ce;
1694         int istgt = 0;
1695
1696         req = (request_t *)arg;
1697         ccb = req->ccb;
1698
1699         mpt = ccb->ccb_h.ccb_mpt_ptr;
1700         req = ccb->ccb_h.ccb_req_ptr;
1701
1702         hdrp = req->req_vbuf;
1703         mpt_off = req->req_vbuf;
1704
1705
1706         if (error == 0 && ((uint32_t)nseg) >= mpt->max_seg_cnt) {
1707                 error = EFBIG;
1708         }
1709
1710         if (error == 0) {
1711                 switch (hdrp->Function) {
1712                 case MPI_FUNCTION_SCSI_IO_REQUEST:
1713                 case MPI_FUNCTION_RAID_SCSI_IO_PASSTHROUGH:
1714                         sglp = &((PTR_MSG_SCSI_IO_REQUEST)hdrp)->SGL;
1715                         break;
1716                 case MPI_FUNCTION_TARGET_ASSIST:
1717                         istgt = 1;
1718                         sglp = &((PTR_MSG_TARGET_ASSIST_REQUEST)hdrp)->SGL;
1719                         break;
1720                 default:
1721                         mpt_prt(mpt, "bad fct 0x%x in mpt_execute_req\n",
1722                             hdrp->Function);
1723                         error = EINVAL;
1724                         break;
1725                 }
1726         }
1727
1728         if (error == 0 && ((uint32_t)nseg) >= mpt->max_seg_cnt) {
1729                 error = EFBIG;
1730                 mpt_prt(mpt, "segment count %d too large (max %u)\n",
1731                     nseg, mpt->max_seg_cnt);
1732         }
1733
1734 bad:
1735         if (error != 0) {
1736                 if (error != EFBIG && error != ENOMEM) {
1737                         mpt_prt(mpt, "mpt_execute_req: err %d\n", error);
1738                 }
1739                 if ((ccb->ccb_h.status & CAM_STATUS_MASK) == CAM_REQ_INPROG) {
1740                         cam_status status;
1741                         mpt_freeze_ccb(ccb);
1742                         if (error == EFBIG) {
1743                                 status = CAM_REQ_TOO_BIG;
1744                         } else if (error == ENOMEM) {
1745                                 if (mpt->outofbeer == 0) {
1746                                         mpt->outofbeer = 1;
1747                                         xpt_freeze_simq(mpt->sim, 1);
1748                                         mpt_lprt(mpt, MPT_PRT_DEBUG,
1749                                             "FREEZEQ\n");
1750                                 }
1751                                 status = CAM_REQUEUE_REQ;
1752                         } else {
1753                                 status = CAM_REQ_CMP_ERR;
1754                         }
1755                         mpt_set_ccb_status(ccb, status);
1756                 }
1757                 if (hdrp->Function == MPI_FUNCTION_TARGET_ASSIST) {
1758                         request_t *cmd_req =
1759                                 MPT_TAG_2_REQ(mpt, ccb->csio.tag_id);
1760                         MPT_TGT_STATE(mpt, cmd_req)->state = TGT_STATE_IN_CAM;
1761                         MPT_TGT_STATE(mpt, cmd_req)->ccb = NULL;
1762                         MPT_TGT_STATE(mpt, cmd_req)->req = NULL;
1763                 }
1764                 ccb->ccb_h.status &= ~CAM_SIM_QUEUED;
1765                 KASSERT(ccb->ccb_h.status, ("zero ccb sts at %d\n", __LINE__));
1766                 xpt_done(ccb);
1767                 CAMLOCK_2_MPTLOCK(mpt);
1768                 mpt_free_request(mpt, req);
1769                 MPTLOCK_2_CAMLOCK(mpt);
1770                 return;
1771         }
1772
1773         /*
1774          * No data to transfer?
1775          * Just make a single simple SGL with zero length.
1776          */
1777
1778         if (mpt->verbose >= MPT_PRT_DEBUG) {
1779                 int tidx = ((char *)sglp) - mpt_off;
1780                 memset(&mpt_off[tidx], 0xff, MPT_REQUEST_AREA - tidx);
1781         }
1782
1783         if (nseg == 0) {
1784                 SGE_SIMPLE32 *se1 = (SGE_SIMPLE32 *) sglp;
1785                 MPI_pSGE_SET_FLAGS(se1,
1786                     (MPI_SGE_FLAGS_LAST_ELEMENT | MPI_SGE_FLAGS_END_OF_BUFFER |
1787                     MPI_SGE_FLAGS_SIMPLE_ELEMENT | MPI_SGE_FLAGS_END_OF_LIST));
1788                 se1->FlagsLength = htole32(se1->FlagsLength);
1789                 goto out;
1790         }
1791
1792
1793         flags = MPI_SGE_FLAGS_SIMPLE_ELEMENT;
1794         if (istgt == 0) {
1795                 if ((ccb->ccb_h.flags & CAM_DIR_MASK) == CAM_DIR_OUT) {
1796                         flags |= MPI_SGE_FLAGS_HOST_TO_IOC;
1797                 }
1798         } else {
1799                 if ((ccb->ccb_h.flags & CAM_DIR_MASK) == CAM_DIR_IN) {
1800                         flags |= MPI_SGE_FLAGS_HOST_TO_IOC;
1801                 }
1802         }
1803
1804         if (!(ccb->ccb_h.flags & (CAM_SG_LIST_PHYS|CAM_DATA_PHYS))) {
1805                 bus_dmasync_op_t op;
1806                 if (istgt) {
1807                         if ((ccb->ccb_h.flags & CAM_DIR_MASK) == CAM_DIR_IN) {
1808                                 op = BUS_DMASYNC_PREREAD;
1809                         } else {
1810                                 op = BUS_DMASYNC_PREWRITE;
1811                         }
1812                 } else {
1813                         if ((ccb->ccb_h.flags & CAM_DIR_MASK) == CAM_DIR_IN) {
1814                                 op = BUS_DMASYNC_PREWRITE;
1815                         } else {
1816                                 op = BUS_DMASYNC_PREREAD;
1817                         }
1818                 }
1819                 bus_dmamap_sync(mpt->buffer_dmat, req->dmap, op);
1820         }
1821
1822         /*
1823          * Okay, fill in what we can at the end of the command frame.
1824          * If we have up to MPT_NSGL_FIRST, we can fit them all into
1825          * the command frame.
1826          *
1827          * Otherwise, we fill up through MPT_NSGL_FIRST less one
1828          * SIMPLE32 pointers and start doing CHAIN32 entries after
1829          * that.
1830          */
1831
1832         if (nseg < MPT_NSGL_FIRST(mpt)) {
1833                 first_lim = nseg;
1834         } else {
1835                 /*
1836                  * Leave room for CHAIN element
1837                  */
1838                 first_lim = MPT_NSGL_FIRST(mpt) - 1;
1839         }
1840
1841         se = (SGE_SIMPLE32 *) sglp;
1842         for (seg = 0; seg < first_lim; seg++, se++, dm_segs++) {
1843                 uint32_t tf;
1844
1845                 memset(se, 0,sizeof (*se));
1846                 se->Address = htole32(dm_segs->ds_addr);
1847
1848
1849
1850                 MPI_pSGE_SET_LENGTH(se, dm_segs->ds_len);
1851                 tf = flags;
1852                 if (seg == first_lim - 1) {
1853                         tf |= MPI_SGE_FLAGS_LAST_ELEMENT;
1854                 }
1855                 if (seg == nseg - 1) {
1856                         tf |=   MPI_SGE_FLAGS_END_OF_LIST |
1857                                 MPI_SGE_FLAGS_END_OF_BUFFER;
1858                 }
1859                 MPI_pSGE_SET_FLAGS(se, tf);
1860                 se->FlagsLength = htole32(se->FlagsLength);
1861         }
1862
1863         if (seg == nseg) {
1864                 goto out;
1865         }
1866
1867         /*
1868          * Tell the IOC where to find the first chain element.
1869          */
1870         hdrp->ChainOffset = ((char *)se - (char *)hdrp) >> 2;
1871         nxt_off = MPT_RQSL(mpt);
1872         trq = req;
1873
1874         /*
1875          * Make up the rest of the data segments out of a chain element
1876          * (contiained in the current request frame) which points to
1877          * SIMPLE32 elements in the next request frame, possibly ending
1878          * with *another* chain element (if there's more).
1879          */
1880         while (seg < nseg) {
1881                 int this_seg_lim;
1882                 uint32_t tf, cur_off;
1883                 bus_addr_t chain_list_addr;
1884
1885                 /*
1886                  * Point to the chain descriptor. Note that the chain
1887                  * descriptor is at the end of the *previous* list (whether
1888                  * chain or simple).
1889                  */
1890                 ce = (SGE_CHAIN32 *) se;
1891
1892                 /*
1893                  * Before we change our current pointer, make  sure we won't
1894                  * overflow the request area with this frame. Note that we
1895                  * test against 'greater than' here as it's okay in this case
1896                  * to have next offset be just outside the request area.
1897                  */
1898                 if ((nxt_off + MPT_RQSL(mpt)) > MPT_REQUEST_AREA) {
1899                         nxt_off = MPT_REQUEST_AREA;
1900                         goto next_chain;
1901                 }
1902
1903                 /*
1904                  * Set our SGE element pointer to the beginning of the chain
1905                  * list and update our next chain list offset.
1906                  */
1907                 se = (SGE_SIMPLE32 *) &mpt_off[nxt_off];
1908                 cur_off = nxt_off;
1909                 nxt_off += MPT_RQSL(mpt);
1910
1911                 /*
1912                  * Now initialized the chain descriptor.
1913                  */
1914                 memset(ce, 0, sizeof (*ce));
1915
1916                 /*
1917                  * Get the physical address of the chain list.
1918                  */
1919                 chain_list_addr = trq->req_pbuf;
1920                 chain_list_addr += cur_off;
1921
1922
1923
1924                 ce->Address = htole32(chain_list_addr);
1925                 ce->Flags = MPI_SGE_FLAGS_CHAIN_ELEMENT;
1926
1927
1928                 /*
1929                  * If we have more than a frame's worth of segments left,
1930                  * set up the chain list to have the last element be another
1931                  * chain descriptor.
1932                  */
1933                 if ((nseg - seg) > MPT_NSGL(mpt)) {
1934                         this_seg_lim = seg + MPT_NSGL(mpt) - 1;
1935                         /*
1936                          * The length of the chain is the length in bytes of the
1937                          * number of segments plus the next chain element.
1938                          *
1939                          * The next chain descriptor offset is the length,
1940                          * in words, of the number of segments.
1941                          */
1942                         ce->Length = (this_seg_lim - seg) *
1943                             sizeof (SGE_SIMPLE32);
1944                         ce->NextChainOffset = ce->Length >> 2;
1945                         ce->Length += sizeof (SGE_CHAIN32);
1946                 } else {
1947                         this_seg_lim = nseg;
1948                         ce->Length = (this_seg_lim - seg) *
1949                             sizeof (SGE_SIMPLE32);
1950                 }
1951                 ce->Length = htole16(ce->Length);
1952
1953                 /*
1954                  * Fill in the chain list SGE elements with our segment data.
1955                  *
1956                  * If we're the last element in this chain list, set the last
1957                  * element flag. If we're the completely last element period,
1958                  * set the end of list and end of buffer flags.
1959                  */
1960                 while (seg < this_seg_lim) {
1961                         memset(se, 0, sizeof (*se));
1962                         se->Address = htole32(dm_segs->ds_addr);
1963
1964
1965
1966
1967                         MPI_pSGE_SET_LENGTH(se, dm_segs->ds_len);
1968                         tf = flags;
1969                         if (seg ==  this_seg_lim - 1) {
1970                                 tf |=   MPI_SGE_FLAGS_LAST_ELEMENT;
1971                         }
1972                         if (seg == nseg - 1) {
1973                                 tf |=   MPI_SGE_FLAGS_END_OF_LIST |
1974                                         MPI_SGE_FLAGS_END_OF_BUFFER;
1975                         }
1976                         MPI_pSGE_SET_FLAGS(se, tf);
1977                         se->FlagsLength = htole32(se->FlagsLength);
1978                         se++;
1979                         seg++;
1980                         dm_segs++;
1981                 }
1982
1983     next_chain:
1984                 /*
1985                  * If we have more segments to do and we've used up all of
1986                  * the space in a request area, go allocate another one
1987                  * and chain to that.
1988                  */
1989                 if (seg < nseg && nxt_off >= MPT_REQUEST_AREA) {
1990                         request_t *nrq;
1991
1992                         CAMLOCK_2_MPTLOCK(mpt);
1993                         nrq = mpt_get_request(mpt, FALSE);
1994                         MPTLOCK_2_CAMLOCK(mpt);
1995
1996                         if (nrq == NULL) {
1997                                 error = ENOMEM;
1998                                 goto bad;
1999                         }
2000
2001                         /*
2002                          * Append the new request area on the tail of our list.
2003                          */
2004                         if ((trq = req->chain) == NULL) {
2005                                 req->chain = nrq;
2006                         } else {
2007                                 while (trq->chain != NULL) {
2008                                         trq = trq->chain;
2009                                 }
2010                                 trq->chain = nrq;
2011                         }
2012                         trq = nrq;
2013                         mpt_off = trq->req_vbuf;
2014                         if (mpt->verbose >= MPT_PRT_DEBUG) {
2015                                 memset(mpt_off, 0xff, MPT_REQUEST_AREA);
2016                         }
2017                         nxt_off = 0;
2018                 }
2019         }
2020 out:
2021
2022         /*
2023          * Last time we need to check if this CCB needs to be aborted.
2024          */
2025         if ((ccb->ccb_h.status & CAM_STATUS_MASK) != CAM_REQ_INPROG) {
2026                 if (hdrp->Function == MPI_FUNCTION_TARGET_ASSIST) {
2027                         request_t *cmd_req =
2028                                 MPT_TAG_2_REQ(mpt, ccb->csio.tag_id);
2029                         MPT_TGT_STATE(mpt, cmd_req)->state = TGT_STATE_IN_CAM;
2030                         MPT_TGT_STATE(mpt, cmd_req)->ccb = NULL;
2031                         MPT_TGT_STATE(mpt, cmd_req)->req = NULL;
2032                 }
2033                 mpt_prt(mpt,
2034                     "mpt_execute_req: I/O cancelled (status 0x%x)\n",
2035                     ccb->ccb_h.status & CAM_STATUS_MASK);
2036                 if (nseg && (ccb->ccb_h.flags & CAM_SG_LIST_PHYS) == 0) {
2037                         bus_dmamap_unload(mpt->buffer_dmat, req->dmap);
2038                 }
2039                 ccb->ccb_h.status &= ~CAM_SIM_QUEUED;
2040                 KASSERT(ccb->ccb_h.status, ("zero ccb sts at %d\n", __LINE__));
2041                 xpt_done(ccb);
2042                 CAMLOCK_2_MPTLOCK(mpt);
2043                 mpt_free_request(mpt, req);
2044                 MPTLOCK_2_CAMLOCK(mpt);
2045                 return;
2046         }
2047
2048         ccb->ccb_h.status |= CAM_SIM_QUEUED;
2049         if (ccb->ccb_h.timeout != CAM_TIME_INFINITY) {
2050                 mpt_req_timeout(req, (ccb->ccb_h.timeout * hz) / 1000,
2051                     mpt_timeout, ccb);
2052         }
2053         if (mpt->verbose > MPT_PRT_DEBUG) {
2054                 int nc = 0;
2055                 mpt_print_request(req->req_vbuf);
2056                 for (trq = req->chain; trq; trq = trq->chain) {
2057                         printf("  Additional Chain Area %d\n", nc++);
2058                         mpt_dump_sgl(trq->req_vbuf, 0);
2059                 }
2060         }
2061
2062         if (hdrp->Function == MPI_FUNCTION_TARGET_ASSIST) {
2063                 request_t *cmd_req = MPT_TAG_2_REQ(mpt, ccb->csio.tag_id);
2064                 mpt_tgt_state_t *tgt = MPT_TGT_STATE(mpt, cmd_req);
2065 #ifdef  WE_TRUST_AUTO_GOOD_STATUS
2066                 if ((ccb->ccb_h.flags & CAM_SEND_STATUS) &&
2067                     csio->scsi_status == SCSI_STATUS_OK && tgt->resid == 0) {
2068                         tgt->state = TGT_STATE_MOVING_DATA_AND_STATUS;
2069                 } else {
2070                         tgt->state = TGT_STATE_MOVING_DATA;
2071                 }
2072 #else
2073                 tgt->state = TGT_STATE_MOVING_DATA;
2074 #endif
2075         }
2076         CAMLOCK_2_MPTLOCK(mpt);
2077         mpt_send_cmd(mpt, req);
2078         MPTLOCK_2_CAMLOCK(mpt);
2079 }
2080
2081 static void
2082 mpt_start(struct cam_sim *sim, union ccb *ccb)
2083 {
2084         request_t *req;
2085         struct mpt_softc *mpt;
2086         MSG_SCSI_IO_REQUEST *mpt_req;
2087         struct ccb_scsiio *csio = &ccb->csio;
2088         struct ccb_hdr *ccbh = &ccb->ccb_h;
2089         bus_dmamap_callback_t *cb;
2090         target_id_t tgt;
2091         int raid_passthru;
2092
2093         /* Get the pointer for the physical addapter */
2094         mpt = ccb->ccb_h.ccb_mpt_ptr;
2095         raid_passthru = (sim == mpt->phydisk_sim);
2096
2097         CAMLOCK_2_MPTLOCK(mpt);
2098         if ((req = mpt_get_request(mpt, FALSE)) == NULL) {
2099                 if (mpt->outofbeer == 0) {
2100                         mpt->outofbeer = 1;
2101                         xpt_freeze_simq(mpt->sim, 1);
2102                         mpt_lprt(mpt, MPT_PRT_DEBUG, "FREEZEQ\n");
2103                 }
2104                 ccb->ccb_h.status &= ~CAM_SIM_QUEUED;
2105                 mpt_set_ccb_status(ccb, CAM_REQUEUE_REQ);
2106                 MPTLOCK_2_CAMLOCK(mpt);
2107                 xpt_done(ccb);
2108                 return;
2109         }
2110 #ifdef  INVARIANTS
2111         mpt_req_not_spcl(mpt, req, "mpt_start", __LINE__);
2112 #endif
2113         MPTLOCK_2_CAMLOCK(mpt);
2114
2115         if (sizeof (bus_addr_t) > 4) {
2116                 cb = mpt_execute_req_a64;
2117         } else {
2118                 cb = mpt_execute_req;
2119         }
2120
2121         /*
2122          * Link the ccb and the request structure so we can find
2123          * the other knowing either the request or the ccb
2124          */
2125         req->ccb = ccb;
2126         ccb->ccb_h.ccb_req_ptr = req;
2127
2128         /* Now we build the command for the IOC */
2129         mpt_req = req->req_vbuf;
2130         memset(mpt_req, 0, sizeof (MSG_SCSI_IO_REQUEST));
2131
2132         mpt_req->Function = MPI_FUNCTION_SCSI_IO_REQUEST;
2133         if (raid_passthru) {
2134                 mpt_req->Function = MPI_FUNCTION_RAID_SCSI_IO_PASSTHROUGH;
2135                 CAMLOCK_2_MPTLOCK(mpt);
2136                 if (mpt_map_physdisk(mpt, ccb, &tgt) != 0) {
2137                         MPTLOCK_2_CAMLOCK(mpt);
2138                         ccb->ccb_h.status &= ~CAM_SIM_QUEUED;
2139                         mpt_set_ccb_status(ccb, CAM_DEV_NOT_THERE);
2140                         xpt_done(ccb);
2141                         return;
2142                 }
2143                 MPTLOCK_2_CAMLOCK(mpt);
2144                 mpt_req->Bus = 0;       /* we never set bus here */
2145         } else {
2146                 tgt = ccb->ccb_h.target_id;
2147                 mpt_req->Bus = 0;       /* XXX */
2148                 
2149         }
2150         mpt_req->SenseBufferLength =
2151                 (csio->sense_len < MPT_SENSE_SIZE) ?
2152                  csio->sense_len : MPT_SENSE_SIZE;
2153
2154         /*
2155          * We use the message context to find the request structure when we
2156          * Get the command completion interrupt from the IOC.
2157          */
2158         mpt_req->MsgContext = htole32(req->index | scsi_io_handler_id);
2159
2160         /* Which physical device to do the I/O on */
2161         mpt_req->TargetID = tgt;
2162
2163         /* We assume a single level LUN type */
2164         if (ccb->ccb_h.target_lun >= 256) {
2165                 mpt_req->LUN[0] = 0x40 | ((ccb->ccb_h.target_lun >> 8) & 0x3f);
2166                 mpt_req->LUN[1] = ccb->ccb_h.target_lun & 0xff;
2167         } else {
2168                 mpt_req->LUN[1] = ccb->ccb_h.target_lun;
2169         }
2170
2171         /* Set the direction of the transfer */
2172         if ((ccb->ccb_h.flags & CAM_DIR_MASK) == CAM_DIR_IN) {
2173                 mpt_req->Control = MPI_SCSIIO_CONTROL_READ;
2174         } else if ((ccb->ccb_h.flags & CAM_DIR_MASK) == CAM_DIR_OUT) {
2175                 mpt_req->Control = MPI_SCSIIO_CONTROL_WRITE;
2176         } else {
2177                 mpt_req->Control = MPI_SCSIIO_CONTROL_NODATATRANSFER;
2178         }
2179
2180         if ((ccb->ccb_h.flags & CAM_TAG_ACTION_VALID) != 0) {
2181                 switch(ccb->csio.tag_action) {
2182                 case MSG_HEAD_OF_Q_TAG:
2183                         mpt_req->Control |= MPI_SCSIIO_CONTROL_HEADOFQ;
2184                         break;
2185                 case MSG_ACA_TASK:
2186                         mpt_req->Control |= MPI_SCSIIO_CONTROL_ACAQ;
2187                         break;
2188                 case MSG_ORDERED_Q_TAG:
2189                         mpt_req->Control |= MPI_SCSIIO_CONTROL_ORDEREDQ;
2190                         break;
2191                 case MSG_SIMPLE_Q_TAG:
2192                 default:
2193                         mpt_req->Control |= MPI_SCSIIO_CONTROL_SIMPLEQ;
2194                         break;
2195                 }
2196         } else {
2197                 if (mpt->is_fc || mpt->is_sas) {
2198                         mpt_req->Control |= MPI_SCSIIO_CONTROL_SIMPLEQ;
2199                 } else {
2200                         /* XXX No such thing for a target doing packetized. */
2201                         mpt_req->Control |= MPI_SCSIIO_CONTROL_UNTAGGED;
2202                 }
2203         }
2204
2205         if (mpt->is_spi) {
2206                 if (ccb->ccb_h.flags & CAM_DIS_DISCONNECT) {
2207                         mpt_req->Control |= MPI_SCSIIO_CONTROL_NO_DISCONNECT;
2208                 }
2209         }
2210         mpt_req->Control = htole32(mpt_req->Control);
2211
2212         /* Copy the scsi command block into place */
2213         if ((ccb->ccb_h.flags & CAM_CDB_POINTER) != 0) {
2214                 bcopy(csio->cdb_io.cdb_ptr, mpt_req->CDB, csio->cdb_len);
2215         } else {
2216                 bcopy(csio->cdb_io.cdb_bytes, mpt_req->CDB, csio->cdb_len);
2217         }
2218
2219         mpt_req->CDBLength = csio->cdb_len;
2220         mpt_req->DataLength = htole32(csio->dxfer_len);
2221         mpt_req->SenseBufferLowAddr = htole32(req->sense_pbuf);
2222
2223         /*
2224          * Do a *short* print here if we're set to MPT_PRT_DEBUG
2225          */
2226         if (mpt->verbose == MPT_PRT_DEBUG) {
2227                 U32 df;
2228                 mpt_prt(mpt, "mpt_start: %s op 0x%x ",
2229                     (mpt_req->Function == MPI_FUNCTION_SCSI_IO_REQUEST)?
2230                     "SCSI_IO_REQUEST" : "SCSI_IO_PASSTHRU", mpt_req->CDB[0]);
2231                 df = mpt_req->Control & MPI_SCSIIO_CONTROL_DATADIRECTION_MASK;
2232                 if (df != MPI_SCSIIO_CONTROL_NODATATRANSFER) {
2233                         mpt_prtc(mpt, "(%s %u byte%s ",
2234                             (df == MPI_SCSIIO_CONTROL_READ)?
2235                             "read" : "write",  csio->dxfer_len,
2236                             (csio->dxfer_len == 1)? ")" : "s)");
2237                 }
2238                 mpt_prtc(mpt, "tgt %u lun %u req %p:%u\n", tgt,
2239                     ccb->ccb_h.target_lun, req, req->serno);
2240         }
2241
2242         /*
2243          * If we have any data to send with this command map it into bus space.
2244          */
2245         if ((ccbh->flags & CAM_DIR_MASK) != CAM_DIR_NONE) {
2246                 if ((ccbh->flags & CAM_SCATTER_VALID) == 0) {
2247                         /*
2248                          * We've been given a pointer to a single buffer.
2249                          */
2250                         if ((ccbh->flags & CAM_DATA_PHYS) == 0) {
2251                                 /*
2252                                  * Virtual address that needs to translated into
2253                                  * one or more physical address ranges.
2254                                  */
2255                                 int error;
2256                                 int s = splsoftvm();
2257                                 error = bus_dmamap_load(mpt->buffer_dmat,
2258                                     req->dmap, csio->data_ptr, csio->dxfer_len,
2259                                     cb, req, 0);
2260                                 splx(s);
2261                                 if (error == EINPROGRESS) {
2262                                         /*
2263                                          * So as to maintain ordering,
2264                                          * freeze the controller queue
2265                                          * until our mapping is
2266                                          * returned.
2267                                          */
2268                                         xpt_freeze_simq(mpt->sim, 1);
2269                                         ccbh->status |= CAM_RELEASE_SIMQ;
2270                                 }
2271                         } else {
2272                                 /*
2273                                  * We have been given a pointer to single
2274                                  * physical buffer.
2275                                  */
2276                                 struct bus_dma_segment seg;
2277                                 seg.ds_addr = 
2278                                     (bus_addr_t)(vm_offset_t)csio->data_ptr;
2279                                 seg.ds_len = csio->dxfer_len;
2280                                 (*cb)(req, &seg, 1, 0);
2281                         }
2282                 } else {
2283                         /*
2284                          * We have been given a list of addresses.
2285                          * This case could be easily supported but they are not
2286                          * currently generated by the CAM subsystem so there
2287                          * is no point in wasting the time right now.
2288                          */
2289                         struct bus_dma_segment *segs;
2290                         if ((ccbh->flags & CAM_SG_LIST_PHYS) == 0) {
2291                                 (*cb)(req, NULL, 0, EFAULT);
2292                         } else {
2293                                 /* Just use the segments provided */
2294                                 segs = (struct bus_dma_segment *)csio->data_ptr;
2295                                 (*cb)(req, segs, csio->sglist_cnt, 0);
2296                         }
2297                 }
2298         } else {
2299                 (*cb)(req, NULL, 0, 0);
2300         }
2301 }
2302
2303 static int
2304 mpt_bus_reset(struct mpt_softc *mpt, target_id_t tgt, lun_id_t lun,
2305     int sleep_ok)
2306 {
2307         int   error;
2308         uint16_t status;
2309         uint8_t response;
2310
2311         error = mpt_scsi_send_tmf(mpt,
2312             (tgt != CAM_TARGET_WILDCARD || lun != CAM_LUN_WILDCARD) ?
2313             MPI_SCSITASKMGMT_TASKTYPE_TARGET_RESET :
2314             MPI_SCSITASKMGMT_TASKTYPE_RESET_BUS,
2315             mpt->is_fc ? MPI_SCSITASKMGMT_MSGFLAGS_LIP_RESET_OPTION : 0,
2316             0,  /* XXX How do I get the channel ID? */
2317             tgt != CAM_TARGET_WILDCARD ? tgt : 0,
2318             lun != CAM_LUN_WILDCARD ? lun : 0,
2319             0, sleep_ok);
2320
2321         if (error != 0) {
2322                 /*
2323                  * mpt_scsi_send_tmf hard resets on failure, so no
2324                  * need to do so here.
2325                  */
2326                 mpt_prt(mpt,
2327                     "mpt_bus_reset: mpt_scsi_send_tmf returned %d\n", error);
2328                 return (EIO);
2329         }
2330
2331         /* Wait for bus reset to be processed by the IOC. */
2332         error = mpt_wait_req(mpt, mpt->tmf_req, REQ_STATE_DONE,
2333             REQ_STATE_DONE, sleep_ok, 5000);
2334
2335         status = le16toh(mpt->tmf_req->IOCStatus);
2336         response = mpt->tmf_req->ResponseCode;
2337         mpt->tmf_req->state = REQ_STATE_FREE;
2338
2339         if (error) {
2340                 mpt_prt(mpt, "mpt_bus_reset: Reset timed-out. "
2341                     "Resetting controller.\n");
2342                 mpt_reset(mpt, TRUE);
2343                 return (ETIMEDOUT);
2344         }
2345
2346         if ((status & MPI_IOCSTATUS_MASK) != MPI_IOCSTATUS_SUCCESS) {
2347                 mpt_prt(mpt, "mpt_bus_reset: TMF IOC Status 0x%x. "
2348                     "Resetting controller.\n", status);
2349                 mpt_reset(mpt, TRUE);
2350                 return (EIO);
2351         }
2352
2353         if (response != MPI_SCSITASKMGMT_RSP_TM_SUCCEEDED &&
2354             response != MPI_SCSITASKMGMT_RSP_TM_COMPLETE) {
2355                 mpt_prt(mpt, "mpt_bus_reset: TMF Response 0x%x. "
2356                     "Resetting controller.\n", response);
2357                 mpt_reset(mpt, TRUE);
2358                 return (EIO);
2359         }
2360         return (0);
2361 }
2362
2363 static int
2364 mpt_fc_reset_link(struct mpt_softc *mpt, int dowait)
2365 {
2366         int r = 0;
2367         request_t *req;
2368         PTR_MSG_FC_PRIMITIVE_SEND_REQUEST fc;
2369
2370         req = mpt_get_request(mpt, FALSE);
2371         if (req == NULL) {
2372                 return (ENOMEM);
2373         }
2374         fc = req->req_vbuf;
2375         memset(fc, 0, sizeof(*fc));
2376         fc->SendFlags = MPI_FC_PRIM_SEND_FLAGS_RESET_LINK;
2377         fc->Function = MPI_FUNCTION_FC_PRIMITIVE_SEND;
2378         fc->MsgContext = htole32(req->index | fc_els_handler_id);
2379         mpt_send_cmd(mpt, req);
2380         if (dowait) {
2381                 r = mpt_wait_req(mpt, req, REQ_STATE_DONE,
2382                     REQ_STATE_DONE, FALSE, 60 * 1000);
2383                 if (r == 0) {
2384                         mpt_free_request(mpt, req);
2385                 }
2386         }
2387         return (r);
2388 }
2389
2390 static int
2391 mpt_cam_event(struct mpt_softc *mpt, request_t *req,
2392               MSG_EVENT_NOTIFY_REPLY *msg)
2393 {
2394         uint32_t data0, data1;
2395
2396         data0 = le32toh(msg->Data[0]);
2397         data1 = le32toh(msg->Data[1]);
2398         switch(msg->Event & 0xFF) {
2399         case MPI_EVENT_UNIT_ATTENTION:
2400                 mpt_prt(mpt, "UNIT ATTENTION: Bus: 0x%02x TargetID: 0x%02x\n",
2401                     (data0 >> 8) & 0xff, data0 & 0xff);
2402                 break;
2403
2404         case MPI_EVENT_IOC_BUS_RESET:
2405                 /* We generated a bus reset */
2406                 mpt_prt(mpt, "IOC Generated Bus Reset Port: %d\n",
2407                     (data0 >> 8) & 0xff);
2408                 xpt_async(AC_BUS_RESET, mpt->path, NULL);
2409                 break;
2410
2411         case MPI_EVENT_EXT_BUS_RESET:
2412                 /* Someone else generated a bus reset */
2413                 mpt_prt(mpt, "External Bus Reset Detected\n");
2414                 /*
2415                  * These replies don't return EventData like the MPI
2416                  * spec says they do
2417                  */     
2418                 xpt_async(AC_BUS_RESET, mpt->path, NULL);
2419                 break;
2420
2421         case MPI_EVENT_RESCAN:
2422 #if __FreeBSD_version >= 600000
2423         {
2424                 union ccb *ccb;
2425                 uint32_t pathid;
2426                 /*
2427                  * In general this means a device has been added to the loop.
2428                  */
2429                 mpt_prt(mpt, "Rescan Port: %d\n", (data0 >> 8) & 0xff);
2430                 if (mpt->ready == 0) {
2431                         break;
2432                 }
2433                 if (mpt->phydisk_sim) {
2434                         pathid = cam_sim_path(mpt->phydisk_sim);
2435                 } else {
2436                         pathid = cam_sim_path(mpt->sim);
2437                 }
2438                 MPTLOCK_2_CAMLOCK(mpt);
2439                 /*
2440                  * Allocate a CCB, create a wildcard path for this bus,
2441                  * and schedule a rescan.
2442                  */
2443                 ccb = xpt_alloc_ccb_nowait();
2444                 if (ccb == NULL) {
2445                         mpt_prt(mpt, "unable to alloc CCB for rescan\n");
2446                         CAMLOCK_2_MPTLOCK(mpt);
2447                         break;
2448                 }
2449
2450                 if (xpt_create_path(&ccb->ccb_h.path, xpt_periph, pathid,
2451                     CAM_TARGET_WILDCARD, CAM_LUN_WILDCARD) != CAM_REQ_CMP) {
2452                         CAMLOCK_2_MPTLOCK(mpt);
2453                         mpt_prt(mpt, "unable to create path for rescan\n");
2454                         xpt_free_ccb(ccb);
2455                         break;
2456                 }
2457                 xpt_rescan(ccb);
2458                 CAMLOCK_2_MPTLOCK(mpt);
2459                 break;
2460         }
2461 #else
2462                 mpt_prt(mpt, "Rescan Port: %d\n", (data0 >> 8) & 0xff);
2463                 break;
2464 #endif
2465         case MPI_EVENT_LINK_STATUS_CHANGE:
2466                 mpt_prt(mpt, "Port %d: LinkState: %s\n",
2467                     (data1 >> 8) & 0xff,
2468                     ((data0 & 0xff) == 0)?  "Failed" : "Active");
2469                 break;
2470
2471         case MPI_EVENT_LOOP_STATE_CHANGE:
2472                 switch ((data0 >> 16) & 0xff) {
2473                 case 0x01:
2474                         mpt_prt(mpt,
2475                             "Port 0x%x: FC LinkEvent: LIP(%02x,%02x) "
2476                             "(Loop Initialization)\n",
2477                             (data1 >> 8) & 0xff,
2478                             (data0 >> 8) & 0xff,
2479                             (data0     ) & 0xff);
2480                         switch ((data0 >> 8) & 0xff) {
2481                         case 0xF7:
2482                                 if ((data0 & 0xff) == 0xF7) {
2483                                         mpt_prt(mpt, "Device needs AL_PA\n");
2484                                 } else {
2485                                         mpt_prt(mpt, "Device %02x doesn't like "
2486                                             "FC performance\n",
2487                                             data0 & 0xFF);
2488                                 }
2489                                 break;
2490                         case 0xF8:
2491                                 if ((data0 & 0xff) == 0xF7) {
2492                                         mpt_prt(mpt, "Device had loop failure "
2493                                             "at its receiver prior to acquiring"
2494                                             " AL_PA\n");
2495                                 } else {
2496                                         mpt_prt(mpt, "Device %02x detected loop"
2497                                             " failure at its receiver\n", 
2498                                             data0 & 0xFF);
2499                                 }
2500                                 break;
2501                         default:
2502                                 mpt_prt(mpt, "Device %02x requests that device "
2503                                     "%02x reset itself\n", 
2504                                     data0 & 0xFF,
2505                                     (data0 >> 8) & 0xFF);
2506                                 break;
2507                         }
2508                         break;
2509                 case 0x02:
2510                         mpt_prt(mpt, "Port 0x%x: FC LinkEvent: "
2511                             "LPE(%02x,%02x) (Loop Port Enable)\n",
2512                             (data1 >> 8) & 0xff, /* Port */
2513                             (data0 >>  8) & 0xff, /* Character 3 */
2514                             (data0      ) & 0xff  /* Character 4 */);
2515                         break;
2516                 case 0x03:
2517                         mpt_prt(mpt, "Port 0x%x: FC LinkEvent: "
2518                             "LPB(%02x,%02x) (Loop Port Bypass)\n",
2519                             (data1 >> 8) & 0xff, /* Port */
2520                             (data0 >> 8) & 0xff, /* Character 3 */
2521                             (data0     ) & 0xff  /* Character 4 */);
2522                         break;
2523                 default:
2524                         mpt_prt(mpt, "Port 0x%x: FC LinkEvent: Unknown "
2525                             "FC event (%02x %02x %02x)\n",
2526                             (data1 >> 8) & 0xff, /* Port */
2527                             (data0 >> 16) & 0xff, /* Event */
2528                             (data0 >>  8) & 0xff, /* Character 3 */
2529                             (data0      ) & 0xff  /* Character 4 */);
2530                 }
2531                 break;
2532
2533         case MPI_EVENT_LOGOUT:
2534                 mpt_prt(mpt, "FC Logout Port: %d N_PortID: %02x\n",
2535                     (data1 >> 8) & 0xff, data0);
2536                 break;
2537         case MPI_EVENT_QUEUE_FULL:
2538         {
2539                 struct cam_sim *sim;
2540                 struct cam_path *tmppath;
2541                 struct ccb_relsim crs;
2542                 PTR_EVENT_DATA_QUEUE_FULL pqf;
2543                 lun_id_t lun_id;
2544
2545                 pqf = (PTR_EVENT_DATA_QUEUE_FULL)msg->Data;
2546                 pqf->CurrentDepth = le16toh(pqf->CurrentDepth);
2547                 mpt_prt(mpt, "QUEUE FULL EVENT: Bus 0x%02x Target 0x%02x Depth "
2548                     "%d\n", pqf->Bus, pqf->TargetID, pqf->CurrentDepth);
2549                 if (mpt->phydisk_sim) {
2550                         sim = mpt->phydisk_sim;
2551                 } else {
2552                         sim = mpt->sim;
2553                 }
2554                 MPTLOCK_2_CAMLOCK(mpt);
2555                 for (lun_id = 0; lun_id < MPT_MAX_LUNS; lun_id++) {
2556                         if (xpt_create_path(&tmppath, NULL, cam_sim_path(sim),
2557                             pqf->TargetID, lun_id) != CAM_REQ_CMP) {
2558                                 mpt_prt(mpt, "unable to create a path to send "
2559                                     "XPT_REL_SIMQ");
2560                                 CAMLOCK_2_MPTLOCK(mpt);
2561                                 break;
2562                         }
2563                         xpt_setup_ccb(&crs.ccb_h, tmppath, 5);
2564                         crs.ccb_h.func_code = XPT_REL_SIMQ;
2565                         crs.release_flags = RELSIM_ADJUST_OPENINGS;
2566                         crs.openings = pqf->CurrentDepth - 1;
2567                         xpt_action((union ccb *)&crs);
2568                         if (crs.ccb_h.status != CAM_REQ_CMP) {
2569                                 mpt_prt(mpt, "XPT_REL_SIMQ failed\n");
2570                         }
2571                         xpt_free_path(tmppath);
2572                 }
2573                 CAMLOCK_2_MPTLOCK(mpt);
2574                 break;
2575         }
2576         case MPI_EVENT_EVENT_CHANGE:
2577         case MPI_EVENT_INTEGRATED_RAID:
2578         case MPI_EVENT_SAS_DEVICE_STATUS_CHANGE:
2579         case MPI_EVENT_SAS_SES:
2580                 break;
2581         default:
2582                 mpt_lprt(mpt, MPT_PRT_WARN, "mpt_cam_event: 0x%x\n",
2583                     msg->Event & 0xFF);
2584                 return (0);
2585         }
2586         return (1);
2587 }
2588
2589 /*
2590  * Reply path for all SCSI I/O requests, called from our
2591  * interrupt handler by extracting our handler index from
2592  * the MsgContext field of the reply from the IOC.
2593  *
2594  * This routine is optimized for the common case of a
2595  * completion without error.  All exception handling is
2596  * offloaded to non-inlined helper routines to minimize
2597  * cache footprint.
2598  */
2599 static int
2600 mpt_scsi_reply_handler(struct mpt_softc *mpt, request_t *req,
2601     uint32_t reply_desc, MSG_DEFAULT_REPLY *reply_frame)
2602 {
2603         MSG_SCSI_IO_REQUEST *scsi_req;
2604         union ccb *ccb;
2605         target_id_t tgt;
2606
2607         if (req->state == REQ_STATE_FREE) {
2608                 mpt_prt(mpt, "mpt_scsi_reply_handler: req already free\n");
2609                 return (TRUE);
2610         }
2611
2612         scsi_req = (MSG_SCSI_IO_REQUEST *)req->req_vbuf;
2613         ccb = req->ccb;
2614         if (ccb == NULL) {
2615                 mpt_prt(mpt, "mpt_scsi_reply_handler: req %p:%u with no ccb\n",
2616                     req, req->serno);
2617                 return (TRUE);
2618         }
2619
2620         tgt = scsi_req->TargetID;
2621         mpt_req_untimeout(req, mpt_timeout, ccb);
2622         ccb->ccb_h.status &= ~CAM_SIM_QUEUED;
2623
2624         if ((ccb->ccb_h.flags & CAM_DIR_MASK) != CAM_DIR_NONE) {
2625                 bus_dmasync_op_t op;
2626
2627                 if ((ccb->ccb_h.flags & CAM_DIR_MASK) == CAM_DIR_IN)
2628                         op = BUS_DMASYNC_POSTREAD;
2629                 else
2630                         op = BUS_DMASYNC_POSTWRITE;
2631                 bus_dmamap_sync(mpt->buffer_dmat, req->dmap, op);
2632                 bus_dmamap_unload(mpt->buffer_dmat, req->dmap);
2633         }
2634
2635         if (reply_frame == NULL) {
2636                 /*
2637                  * Context only reply, completion without error status.
2638                  */
2639                 ccb->csio.resid = 0;
2640                 mpt_set_ccb_status(ccb, CAM_REQ_CMP);
2641                 ccb->csio.scsi_status = SCSI_STATUS_OK;
2642         } else {
2643                 mpt_scsi_reply_frame_handler(mpt, req, reply_frame);
2644         }
2645
2646         if (mpt->outofbeer) {
2647                 ccb->ccb_h.status |= CAM_RELEASE_SIMQ;
2648                 mpt->outofbeer = 0;
2649                 mpt_lprt(mpt, MPT_PRT_DEBUG, "THAWQ\n");
2650         }
2651         if (scsi_req->CDB[0] == INQUIRY && (scsi_req->CDB[1] & SI_EVPD) == 0) {
2652                 struct scsi_inquiry_data *iq = 
2653                     (struct scsi_inquiry_data *)ccb->csio.data_ptr;
2654                 if (scsi_req->Function ==
2655                     MPI_FUNCTION_RAID_SCSI_IO_PASSTHROUGH) {
2656                         /*
2657                          * Fake out the device type so that only the
2658                          * pass-thru device will attach.
2659                          */
2660                         iq->device &= ~0x1F;
2661                         iq->device |= T_NODEVICE;
2662                 }
2663         }
2664         if (mpt->verbose == MPT_PRT_DEBUG) {
2665                 mpt_prt(mpt, "mpt_scsi_reply_handler: %p:%u complete\n",
2666                     req, req->serno);
2667         }
2668         KASSERT(ccb->ccb_h.status, ("zero ccb sts at %d\n", __LINE__));
2669         MPTLOCK_2_CAMLOCK(mpt);
2670         xpt_done(ccb);
2671         CAMLOCK_2_MPTLOCK(mpt);
2672         if ((req->state & REQ_STATE_TIMEDOUT) == 0) {
2673                 TAILQ_REMOVE(&mpt->request_pending_list, req, links);
2674         } else {
2675                 mpt_prt(mpt, "completing timedout/aborted req %p:%u\n",
2676                     req, req->serno);
2677                 TAILQ_REMOVE(&mpt->request_timeout_list, req, links);
2678         }
2679         KASSERT((req->state & REQ_STATE_NEED_WAKEUP) == 0,
2680             ("CCB req needed wakeup"));
2681 #ifdef  INVARIANTS
2682         mpt_req_not_spcl(mpt, req, "mpt_scsi_reply_handler", __LINE__);
2683 #endif
2684         mpt_free_request(mpt, req);
2685         return (TRUE);
2686 }
2687
2688 static int
2689 mpt_scsi_tmf_reply_handler(struct mpt_softc *mpt, request_t *req,
2690     uint32_t reply_desc, MSG_DEFAULT_REPLY *reply_frame)
2691 {
2692         MSG_SCSI_TASK_MGMT_REPLY *tmf_reply;
2693
2694         KASSERT(req == mpt->tmf_req, ("TMF Reply not using mpt->tmf_req"));
2695 #ifdef  INVARIANTS
2696         mpt_req_not_spcl(mpt, req, "mpt_scsi_tmf_reply_handler", __LINE__);
2697 #endif
2698         tmf_reply = (MSG_SCSI_TASK_MGMT_REPLY *)reply_frame;
2699         /* Record IOC Status and Response Code of TMF for any waiters. */
2700         req->IOCStatus = le16toh(tmf_reply->IOCStatus);
2701         req->ResponseCode = tmf_reply->ResponseCode;
2702
2703         mpt_lprt(mpt, MPT_PRT_DEBUG, "TMF complete: req %p:%u status 0x%x\n",
2704             req, req->serno, le16toh(tmf_reply->IOCStatus));
2705         TAILQ_REMOVE(&mpt->request_pending_list, req, links);
2706         if ((req->state & REQ_STATE_NEED_WAKEUP) != 0) {
2707                 req->state |= REQ_STATE_DONE;
2708                 wakeup(req);
2709         } else {
2710                 mpt->tmf_req->state = REQ_STATE_FREE;
2711         }
2712         return (TRUE);
2713 }
2714
2715 /*
2716  * XXX: Move to definitions file
2717  */
2718 #define ELS     0x22
2719 #define FC4LS   0x32
2720 #define ABTS    0x81
2721 #define BA_ACC  0x84
2722
2723 #define LS_RJT  0x01 
2724 #define LS_ACC  0x02
2725 #define PLOGI   0x03
2726 #define LOGO    0x05
2727 #define SRR     0x14
2728 #define PRLI    0x20
2729 #define PRLO    0x21
2730 #define ADISC   0x52
2731 #define RSCN    0x61
2732
2733 static void
2734 mpt_fc_els_send_response(struct mpt_softc *mpt, request_t *req,
2735     PTR_MSG_LINK_SERVICE_BUFFER_POST_REPLY rp, U8 length)
2736 {
2737         uint32_t fl;
2738         MSG_LINK_SERVICE_RSP_REQUEST tmp;
2739         PTR_MSG_LINK_SERVICE_RSP_REQUEST rsp;
2740
2741         /*
2742          * We are going to reuse the ELS request to send this response back.
2743          */
2744         rsp = &tmp;
2745         memset(rsp, 0, sizeof(*rsp));
2746
2747 #ifdef  USE_IMMEDIATE_LINK_DATA
2748         /*
2749          * Apparently the IMMEDIATE stuff doesn't seem to work.
2750          */
2751         rsp->RspFlags = LINK_SERVICE_RSP_FLAGS_IMMEDIATE;
2752 #endif
2753         rsp->RspLength = length;
2754         rsp->Function = MPI_FUNCTION_FC_LINK_SRVC_RSP;
2755         rsp->MsgContext = htole32(req->index | fc_els_handler_id);
2756
2757         /*
2758          * Copy over information from the original reply frame to
2759          * it's correct place in the response.
2760          */
2761         memcpy((U8 *)rsp + 0x0c, (U8 *)rp + 0x1c, 24);
2762
2763         /*
2764          * And now copy back the temporary area to the original frame.
2765          */
2766         memcpy(req->req_vbuf, rsp, sizeof (MSG_LINK_SERVICE_RSP_REQUEST));
2767         rsp = req->req_vbuf;
2768
2769 #ifdef  USE_IMMEDIATE_LINK_DATA
2770         memcpy((U8 *)&rsp->SGL, &((U8 *)req->req_vbuf)[MPT_RQSL(mpt)], length);
2771 #else
2772 {
2773         PTR_SGE_SIMPLE32 se = (PTR_SGE_SIMPLE32) &rsp->SGL;
2774         bus_addr_t paddr = req->req_pbuf;
2775         paddr += MPT_RQSL(mpt);
2776
2777         fl =
2778                 MPI_SGE_FLAGS_HOST_TO_IOC       |
2779                 MPI_SGE_FLAGS_SIMPLE_ELEMENT    |
2780                 MPI_SGE_FLAGS_LAST_ELEMENT      |
2781                 MPI_SGE_FLAGS_END_OF_LIST       |
2782                 MPI_SGE_FLAGS_END_OF_BUFFER;
2783         fl <<= MPI_SGE_FLAGS_SHIFT;
2784         fl |= (length);
2785         se->FlagsLength = htole32(fl);
2786         se->Address = htole32((uint32_t) paddr);
2787 }
2788 #endif
2789
2790         /*
2791          * Send it on...
2792          */
2793         mpt_send_cmd(mpt, req);
2794 }
2795
2796 static int
2797 mpt_fc_els_reply_handler(struct mpt_softc *mpt, request_t *req,
2798     uint32_t reply_desc, MSG_DEFAULT_REPLY *reply_frame)
2799 {
2800         PTR_MSG_LINK_SERVICE_BUFFER_POST_REPLY rp =
2801             (PTR_MSG_LINK_SERVICE_BUFFER_POST_REPLY) reply_frame;
2802         U8 rctl;
2803         U8 type;
2804         U8 cmd;
2805         U16 status = le16toh(reply_frame->IOCStatus);
2806         U32 *elsbuf;
2807         int ioindex;
2808         int do_refresh = TRUE;
2809
2810 #ifdef  INVARIANTS
2811         KASSERT(mpt_req_on_free_list(mpt, req) == 0,
2812             ("fc_els_reply_handler: req %p:%u for function %x on freelist!",
2813             req, req->serno, rp->Function));
2814         if (rp->Function != MPI_FUNCTION_FC_PRIMITIVE_SEND) {
2815                 mpt_req_spcl(mpt, req, "fc_els_reply_handler", __LINE__);
2816         } else {
2817                 mpt_req_not_spcl(mpt, req, "fc_els_reply_handler", __LINE__);
2818         }
2819 #endif
2820         mpt_lprt(mpt, MPT_PRT_DEBUG,
2821             "FC_ELS Complete: req %p:%u, reply %p function %x\n",
2822             req, req->serno, reply_frame, reply_frame->Function);
2823
2824         if  (status != MPI_IOCSTATUS_SUCCESS) {
2825                 mpt_prt(mpt, "ELS REPLY STATUS 0x%x for Function %x\n",
2826                     status, reply_frame->Function);
2827                 if (status == MPI_IOCSTATUS_INVALID_STATE) {
2828                         /*
2829                          * XXX: to get around shutdown issue
2830                          */
2831                         mpt->disabled = 1;
2832                         return (TRUE);
2833                 }
2834                 return (TRUE);
2835         }
2836
2837         /*
2838          * If the function of a link service response, we recycle the
2839          * response to be a refresh for a new link service request.
2840          *
2841          * The request pointer is bogus in this case and we have to fetch
2842          * it based upon the TransactionContext.
2843          */
2844         if (rp->Function == MPI_FUNCTION_FC_LINK_SRVC_RSP) {
2845                 /* Freddie Uncle Charlie Katie */
2846                 /* We don't get the IOINDEX as part of the Link Svc Rsp */
2847                 for (ioindex = 0; ioindex < mpt->els_cmds_allocated; ioindex++)
2848                         if (mpt->els_cmd_ptrs[ioindex] == req) {
2849                                 break;
2850                         }
2851
2852                 KASSERT(ioindex < mpt->els_cmds_allocated,
2853                     ("can't find my mommie!"));
2854
2855                 /* remove from active list as we're going to re-post it */
2856                 TAILQ_REMOVE(&mpt->request_pending_list, req, links);
2857                 req->state &= ~REQ_STATE_QUEUED;
2858                 req->state |= REQ_STATE_DONE;
2859                 mpt_fc_post_els(mpt, req, ioindex);
2860                 return (TRUE);
2861         }
2862
2863         if (rp->Function == MPI_FUNCTION_FC_PRIMITIVE_SEND) {
2864                 /* remove from active list as we're done */
2865                 TAILQ_REMOVE(&mpt->request_pending_list, req, links);
2866                 req->state &= ~REQ_STATE_QUEUED;
2867                 req->state |= REQ_STATE_DONE;
2868                 if (req->state & REQ_STATE_TIMEDOUT) {
2869                         mpt_lprt(mpt, MPT_PRT_DEBUG,
2870                             "Sync Primitive Send Completed After Timeout\n");
2871                         mpt_free_request(mpt, req);
2872                 } else if ((req->state & REQ_STATE_NEED_WAKEUP) == 0) {
2873                         mpt_lprt(mpt, MPT_PRT_DEBUG,
2874                             "Async Primitive Send Complete\n");
2875                         mpt_free_request(mpt, req);
2876                 } else {
2877                         mpt_lprt(mpt, MPT_PRT_DEBUG,
2878                             "Sync Primitive Send Complete- Waking Waiter\n");
2879                         wakeup(req);
2880                 }
2881                 return (TRUE);
2882         }
2883
2884         if (rp->Function != MPI_FUNCTION_FC_LINK_SRVC_BUF_POST) {
2885                 mpt_prt(mpt, "unexpected ELS_REPLY: Function 0x%x Flags %x "
2886                     "Length %d Message Flags %x\n", rp->Function, rp->Flags,
2887                     rp->MsgLength, rp->MsgFlags);
2888                 return (TRUE);
2889         }
2890
2891         if (rp->MsgLength <= 5) {
2892                 /*
2893                  * This is just a ack of an original ELS buffer post
2894                  */
2895                 mpt_lprt(mpt, MPT_PRT_DEBUG,
2896                     "RECV'd ACK of FC_ELS buf post %p:%u\n", req, req->serno);
2897                 return (TRUE);
2898         }
2899
2900
2901         rctl = (le32toh(rp->Rctl_Did) & MPI_FC_RCTL_MASK) >> MPI_FC_RCTL_SHIFT;
2902         type = (le32toh(rp->Type_Fctl) & MPI_FC_TYPE_MASK) >> MPI_FC_TYPE_SHIFT;
2903
2904         elsbuf = &((U32 *)req->req_vbuf)[MPT_RQSL(mpt)/sizeof (U32)];
2905         cmd = be32toh(elsbuf[0]) >> 24;
2906
2907         if (rp->Flags & MPI_LS_BUF_POST_REPLY_FLAG_NO_RSP_NEEDED) {
2908                 mpt_lprt(mpt, MPT_PRT_ALWAYS, "ELS_REPLY: response unneeded\n");
2909                 return (TRUE);
2910         }
2911
2912         ioindex = le32toh(rp->TransactionContext);
2913         req = mpt->els_cmd_ptrs[ioindex];
2914
2915         if (rctl == ELS && type == 1) {
2916                 switch (cmd) {
2917                 case PRLI:
2918                         /*
2919                          * Send back a PRLI ACC
2920                          */
2921                         mpt_prt(mpt, "PRLI from 0x%08x%08x\n",
2922                             le32toh(rp->Wwn.PortNameHigh),
2923                             le32toh(rp->Wwn.PortNameLow));
2924                         elsbuf[0] = htobe32(0x02100014);
2925                         elsbuf[1] |= htobe32(0x00000100);
2926                         elsbuf[4] = htobe32(0x00000002);
2927                         if (mpt->role & MPT_ROLE_TARGET)
2928                                 elsbuf[4] |= htobe32(0x00000010);
2929                         if (mpt->role & MPT_ROLE_INITIATOR)
2930                                 elsbuf[4] |= htobe32(0x00000020);
2931                         /* remove from active list as we're done */
2932                         TAILQ_REMOVE(&mpt->request_pending_list, req, links);
2933                         req->state &= ~REQ_STATE_QUEUED;
2934                         req->state |= REQ_STATE_DONE;
2935                         mpt_fc_els_send_response(mpt, req, rp, 20);
2936                         do_refresh = FALSE;
2937                         break;
2938                 case PRLO:
2939                         memset(elsbuf, 0, 5 * (sizeof (U32)));
2940                         elsbuf[0] = htobe32(0x02100014);
2941                         elsbuf[1] = htobe32(0x08000100);
2942                         mpt_prt(mpt, "PRLO from 0x%08x%08x\n",
2943                             le32toh(rp->Wwn.PortNameHigh),
2944                             le32toh(rp->Wwn.PortNameLow));
2945                         /* remove from active list as we're done */
2946                         TAILQ_REMOVE(&mpt->request_pending_list, req, links);
2947                         req->state &= ~REQ_STATE_QUEUED;
2948                         req->state |= REQ_STATE_DONE;
2949                         mpt_fc_els_send_response(mpt, req, rp, 20);
2950                         do_refresh = FALSE;
2951                         break;
2952                 default:
2953                         mpt_prt(mpt, "ELS TYPE 1 COMMAND: %x\n", cmd);
2954                         break;
2955                 }
2956         } else if (rctl == ABTS && type == 0) {
2957                 uint16_t rx_id = le16toh(rp->Rxid);
2958                 uint16_t ox_id = le16toh(rp->Oxid);
2959                 request_t *tgt_req = NULL;
2960
2961                 mpt_prt(mpt,
2962                     "ELS: ABTS OX_ID 0x%x RX_ID 0x%x from 0x%08x%08x\n",
2963                     ox_id, rx_id, le32toh(rp->Wwn.PortNameHigh),
2964                     le32toh(rp->Wwn.PortNameLow));
2965                 if (rx_id >= mpt->mpt_max_tgtcmds) {
2966                         mpt_prt(mpt, "Bad RX_ID 0x%x\n", rx_id);
2967                 } else if (mpt->tgt_cmd_ptrs == NULL) {
2968                         mpt_prt(mpt, "No TGT CMD PTRS\n");
2969                 } else {
2970                         tgt_req = mpt->tgt_cmd_ptrs[rx_id];
2971                 }
2972                 if (tgt_req) {
2973                         mpt_tgt_state_t *tgt = MPT_TGT_STATE(mpt, tgt_req);
2974                         uint8_t *vbuf;
2975                         union ccb *ccb = tgt->ccb;
2976                         uint32_t ct_id;
2977
2978                         vbuf = tgt_req->req_vbuf;
2979                         vbuf += MPT_RQSL(mpt);
2980
2981                         /*
2982                          * Check to make sure we have the correct command
2983                          * The reply descriptor in the target state should
2984                          * should contain an IoIndex that should match the
2985                          * RX_ID.
2986                          *
2987                          * It'd be nice to have OX_ID to crosscheck with
2988                          * as well.
2989                          */
2990                         ct_id = GET_IO_INDEX(tgt->reply_desc);
2991
2992                         if (ct_id != rx_id) {
2993                                 mpt_lprt(mpt, MPT_PRT_ERROR, "ABORT Mismatch: "
2994                                     "RX_ID received=0x%x; RX_ID in cmd=0x%x\n",
2995                                     rx_id, ct_id);
2996                                 goto skip;
2997                         }
2998
2999                         ccb = tgt->ccb;
3000                         if (ccb) {
3001                                 mpt_prt(mpt,
3002                                     "CCB (%p): lun %u flags %x status %x\n",
3003                                     ccb, ccb->ccb_h.target_lun,
3004                                     ccb->ccb_h.flags, ccb->ccb_h.status);
3005                         }
3006                         mpt_prt(mpt, "target state 0x%x resid %u xfrd %u rpwrd "
3007                             "%x nxfers %x\n", tgt->state,
3008                             tgt->resid, tgt->bytes_xfered, tgt->reply_desc,
3009                             tgt->nxfers);
3010   skip:
3011                         if (mpt_abort_target_cmd(mpt, tgt_req)) {
3012                                 mpt_prt(mpt, "unable to start TargetAbort\n");
3013                         }
3014                 } else {
3015                         mpt_prt(mpt, "no back pointer for RX_ID 0x%x\n", rx_id);
3016                 }
3017                 memset(elsbuf, 0, 5 * (sizeof (U32)));
3018                 elsbuf[0] = htobe32(0);
3019                 elsbuf[1] = htobe32((ox_id << 16) | rx_id);
3020                 elsbuf[2] = htobe32(0x000ffff);
3021                 /*
3022                  * Dork with the reply frame so that the reponse to it
3023                  * will be correct.
3024                  */
3025                 rp->Rctl_Did += ((BA_ACC - ABTS) << MPI_FC_RCTL_SHIFT);
3026                 /* remove from active list as we're done */
3027                 TAILQ_REMOVE(&mpt->request_pending_list, req, links);
3028                 req->state &= ~REQ_STATE_QUEUED;
3029                 req->state |= REQ_STATE_DONE;
3030                 mpt_fc_els_send_response(mpt, req, rp, 12);
3031                 do_refresh = FALSE;
3032         } else {
3033                 mpt_prt(mpt, "ELS: RCTL %x TYPE %x CMD %x\n", rctl, type, cmd);
3034         }
3035         if (do_refresh == TRUE) {
3036                 /* remove from active list as we're done */
3037                 TAILQ_REMOVE(&mpt->request_pending_list, req, links);
3038                 req->state &= ~REQ_STATE_QUEUED;
3039                 req->state |= REQ_STATE_DONE;
3040                 mpt_fc_post_els(mpt, req, ioindex);
3041         }
3042         return (TRUE);
3043 }
3044
3045 /*
3046  * Clean up all SCSI Initiator personality state in response
3047  * to a controller reset.
3048  */
3049 static void
3050 mpt_cam_ioc_reset(struct mpt_softc *mpt, int type)
3051 {
3052         /*
3053          * The pending list is already run down by
3054          * the generic handler.  Perform the same
3055          * operation on the timed out request list.
3056          */
3057         mpt_complete_request_chain(mpt, &mpt->request_timeout_list,
3058                                    MPI_IOCSTATUS_INVALID_STATE);
3059
3060         /*
3061          * XXX: We need to repost ELS and Target Command Buffers?
3062          */
3063
3064         /*
3065          * Inform the XPT that a bus reset has occurred.
3066          */
3067         xpt_async(AC_BUS_RESET, mpt->path, NULL);
3068 }
3069
3070 /*
3071  * Parse additional completion information in the reply
3072  * frame for SCSI I/O requests.
3073  */
3074 static int
3075 mpt_scsi_reply_frame_handler(struct mpt_softc *mpt, request_t *req,
3076                              MSG_DEFAULT_REPLY *reply_frame)
3077 {
3078         union ccb *ccb;
3079         MSG_SCSI_IO_REPLY *scsi_io_reply;
3080         u_int ioc_status;
3081         u_int sstate;
3082         u_int loginfo;
3083
3084         MPT_DUMP_REPLY_FRAME(mpt, reply_frame);
3085         KASSERT(reply_frame->Function == MPI_FUNCTION_SCSI_IO_REQUEST
3086              || reply_frame->Function == MPI_FUNCTION_RAID_SCSI_IO_PASSTHROUGH,
3087                 ("MPT SCSI I/O Handler called with incorrect reply type"));
3088         KASSERT((reply_frame->MsgFlags & MPI_MSGFLAGS_CONTINUATION_REPLY) == 0,
3089                 ("MPT SCSI I/O Handler called with continuation reply"));
3090
3091         scsi_io_reply = (MSG_SCSI_IO_REPLY *)reply_frame;
3092         ioc_status = le16toh(scsi_io_reply->IOCStatus);
3093         loginfo = ioc_status & MPI_IOCSTATUS_FLAG_LOG_INFO_AVAILABLE;
3094         ioc_status &= MPI_IOCSTATUS_MASK;
3095         sstate = scsi_io_reply->SCSIState;
3096
3097         ccb = req->ccb;
3098         ccb->csio.resid =
3099             ccb->csio.dxfer_len - le32toh(scsi_io_reply->TransferCount);
3100
3101         if ((sstate & MPI_SCSI_STATE_AUTOSENSE_VALID) != 0
3102          && (ccb->ccb_h.flags & (CAM_SENSE_PHYS | CAM_SENSE_PTR)) == 0) {
3103                 ccb->ccb_h.status |= CAM_AUTOSNS_VALID;
3104                 ccb->csio.sense_resid =
3105                     ccb->csio.sense_len - le32toh(scsi_io_reply->SenseCount);
3106                 bcopy(req->sense_vbuf, &ccb->csio.sense_data,
3107                     min(ccb->csio.sense_len,
3108                     le32toh(scsi_io_reply->SenseCount)));
3109         }
3110
3111         if ((sstate & MPI_SCSI_STATE_QUEUE_TAG_REJECTED) != 0) {
3112                 /*
3113                  * Tag messages rejected, but non-tagged retry
3114                  * was successful.
3115 XXXX
3116                 mpt_set_tags(mpt, devinfo, MPT_QUEUE_NONE);
3117                  */
3118         }
3119
3120         switch(ioc_status) {
3121         case MPI_IOCSTATUS_SCSI_RESIDUAL_MISMATCH:
3122                 /*
3123                  * XXX
3124                  * Linux driver indicates that a zero
3125                  * transfer length with this error code
3126                  * indicates a CRC error.
3127                  *
3128                  * No need to swap the bytes for checking
3129                  * against zero.
3130                  */
3131                 if (scsi_io_reply->TransferCount == 0) {
3132                         mpt_set_ccb_status(ccb, CAM_UNCOR_PARITY);
3133                         break;
3134                 }
3135                 /* FALLTHROUGH */
3136         case MPI_IOCSTATUS_SCSI_DATA_UNDERRUN:
3137         case MPI_IOCSTATUS_SUCCESS:
3138         case MPI_IOCSTATUS_SCSI_RECOVERED_ERROR:
3139                 if ((sstate & MPI_SCSI_STATE_NO_SCSI_STATUS) != 0) {
3140                         /*
3141                          * Status was never returned for this transaction.
3142                          */
3143                         mpt_set_ccb_status(ccb, CAM_UNEXP_BUSFREE);
3144                 } else if (scsi_io_reply->SCSIStatus != SCSI_STATUS_OK) {
3145                         ccb->csio.scsi_status = scsi_io_reply->SCSIStatus;
3146                         mpt_set_ccb_status(ccb, CAM_SCSI_STATUS_ERROR);
3147                         if ((sstate & MPI_SCSI_STATE_AUTOSENSE_FAILED) != 0)
3148                                 mpt_set_ccb_status(ccb, CAM_AUTOSENSE_FAIL);
3149                 } else if ((sstate & MPI_SCSI_STATE_RESPONSE_INFO_VALID) != 0) {
3150
3151                         /* XXX Handle SPI-Packet and FCP-2 reponse info. */
3152                         mpt_set_ccb_status(ccb, CAM_REQ_CMP_ERR);
3153                 } else
3154                         mpt_set_ccb_status(ccb, CAM_REQ_CMP);
3155                 break;
3156         case MPI_IOCSTATUS_SCSI_DATA_OVERRUN:
3157                 mpt_set_ccb_status(ccb, CAM_DATA_RUN_ERR);
3158                 break;
3159         case MPI_IOCSTATUS_SCSI_IO_DATA_ERROR:
3160                 mpt_set_ccb_status(ccb, CAM_UNCOR_PARITY);
3161                 break;
3162         case MPI_IOCSTATUS_SCSI_DEVICE_NOT_THERE:
3163                 /*
3164                  * Since selection timeouts and "device really not
3165                  * there" are grouped into this error code, report
3166                  * selection timeout.  Selection timeouts are
3167                  * typically retried before giving up on the device
3168                  * whereas "device not there" errors are considered
3169                  * unretryable.
3170                  */
3171                 mpt_set_ccb_status(ccb, CAM_SEL_TIMEOUT);
3172                 break;
3173         case MPI_IOCSTATUS_SCSI_PROTOCOL_ERROR:
3174                 mpt_set_ccb_status(ccb, CAM_SEQUENCE_FAIL);
3175                 break;
3176         case MPI_IOCSTATUS_SCSI_INVALID_BUS:
3177                 mpt_set_ccb_status(ccb, CAM_PATH_INVALID);
3178                 break;
3179         case MPI_IOCSTATUS_SCSI_INVALID_TARGETID:
3180                 mpt_set_ccb_status(ccb, CAM_TID_INVALID);
3181                 break;
3182         case MPI_IOCSTATUS_SCSI_TASK_MGMT_FAILED:
3183                 ccb->ccb_h.status = CAM_UA_TERMIO;
3184                 break;
3185         case MPI_IOCSTATUS_INVALID_STATE:
3186                 /*
3187                  * The IOC has been reset.  Emulate a bus reset.
3188                  */
3189                 /* FALLTHROUGH */
3190         case MPI_IOCSTATUS_SCSI_EXT_TERMINATED:
3191                 ccb->ccb_h.status = CAM_SCSI_BUS_RESET; 
3192                 break;
3193         case MPI_IOCSTATUS_SCSI_TASK_TERMINATED:
3194         case MPI_IOCSTATUS_SCSI_IOC_TERMINATED:
3195                 /*
3196                  * Don't clobber any timeout status that has
3197                  * already been set for this transaction.  We
3198                  * want the SCSI layer to be able to differentiate
3199                  * between the command we aborted due to timeout
3200                  * and any innocent bystanders.
3201                  */
3202                 if ((ccb->ccb_h.status & CAM_STATUS_MASK) != CAM_REQ_INPROG)
3203                         break;
3204                 mpt_set_ccb_status(ccb, CAM_REQ_TERMIO);
3205                 break;
3206
3207         case MPI_IOCSTATUS_INSUFFICIENT_RESOURCES:
3208                 mpt_set_ccb_status(ccb, CAM_RESRC_UNAVAIL);
3209                 break;
3210         case MPI_IOCSTATUS_BUSY:
3211                 mpt_set_ccb_status(ccb, CAM_BUSY);
3212                 break;
3213         case MPI_IOCSTATUS_INVALID_FUNCTION:
3214         case MPI_IOCSTATUS_INVALID_SGL:
3215         case MPI_IOCSTATUS_INTERNAL_ERROR:
3216         case MPI_IOCSTATUS_INVALID_FIELD:
3217         default:
3218                 /* XXX
3219                  * Some of the above may need to kick
3220                  * of a recovery action!!!!
3221                  */
3222                 ccb->ccb_h.status = CAM_UNREC_HBA_ERROR;
3223                 break;
3224         }
3225
3226         if ((ccb->ccb_h.status & CAM_STATUS_MASK) != CAM_REQ_CMP) {
3227                 mpt_freeze_ccb(ccb);
3228         }
3229
3230         return (TRUE);
3231 }
3232
3233 static void
3234 mpt_action(struct cam_sim *sim, union ccb *ccb)
3235 {
3236         struct mpt_softc *mpt;
3237         struct ccb_trans_settings *cts;
3238         target_id_t tgt;
3239         lun_id_t lun;
3240         int raid_passthru;
3241
3242         CAM_DEBUG(ccb->ccb_h.path, CAM_DEBUG_TRACE, ("mpt_action\n"));
3243
3244         mpt = (struct mpt_softc *)cam_sim_softc(sim);
3245         raid_passthru = (sim == mpt->phydisk_sim);
3246         MPT_LOCK_ASSERT(mpt);
3247
3248         tgt = ccb->ccb_h.target_id;
3249         lun = ccb->ccb_h.target_lun;
3250         if (raid_passthru &&
3251             ccb->ccb_h.func_code != XPT_PATH_INQ &&
3252             ccb->ccb_h.func_code != XPT_RESET_BUS &&
3253             ccb->ccb_h.func_code != XPT_RESET_DEV) {
3254                 CAMLOCK_2_MPTLOCK(mpt);
3255                 if (mpt_map_physdisk(mpt, ccb, &tgt) != 0) {
3256                         MPTLOCK_2_CAMLOCK(mpt);
3257                         ccb->ccb_h.status &= ~CAM_SIM_QUEUED;
3258                         mpt_set_ccb_status(ccb, CAM_DEV_NOT_THERE);
3259                         xpt_done(ccb);
3260                         return;
3261                 }
3262                 MPTLOCK_2_CAMLOCK(mpt);
3263         }
3264         ccb->ccb_h.ccb_mpt_ptr = mpt;
3265
3266         switch (ccb->ccb_h.func_code) {
3267         case XPT_SCSI_IO:       /* Execute the requested I/O operation */
3268                 /*
3269                  * Do a couple of preliminary checks...
3270                  */
3271                 if ((ccb->ccb_h.flags & CAM_CDB_POINTER) != 0) {
3272                         if ((ccb->ccb_h.flags & CAM_CDB_PHYS) != 0) {
3273                                 ccb->ccb_h.status &= ~CAM_SIM_QUEUED;
3274                                 mpt_set_ccb_status(ccb, CAM_REQ_INVALID);
3275                                 break;
3276                         }
3277                 }
3278                 /* Max supported CDB length is 16 bytes */
3279                 /* XXX Unless we implement the new 32byte message type */
3280                 if (ccb->csio.cdb_len >
3281                     sizeof (((PTR_MSG_SCSI_IO_REQUEST)0)->CDB)) {
3282                         ccb->ccb_h.status &= ~CAM_SIM_QUEUED;
3283                         mpt_set_ccb_status(ccb, CAM_REQ_INVALID);
3284                         break;
3285                 }
3286 #ifdef  MPT_TEST_MULTIPATH
3287                 if (mpt->failure_id == ccb->ccb_h.target_id) {
3288                         ccb->ccb_h.status &= ~CAM_SIM_QUEUED;
3289                         mpt_set_ccb_status(ccb, CAM_SEL_TIMEOUT);
3290                         break;
3291                 }
3292 #endif
3293                 ccb->csio.scsi_status = SCSI_STATUS_OK;
3294                 mpt_start(sim, ccb);
3295                 return;
3296
3297         case XPT_RESET_BUS:
3298                 if (raid_passthru) {
3299                         ccb->ccb_h.status &= ~CAM_SIM_QUEUED;
3300                         mpt_set_ccb_status(ccb, CAM_REQ_CMP);
3301                         break;
3302                 }
3303         case XPT_RESET_DEV:
3304                 if (ccb->ccb_h.func_code == XPT_RESET_BUS) {
3305                         if (bootverbose) {
3306                                 xpt_print(ccb->ccb_h.path, "reset bus\n");
3307                         }
3308                 } else {
3309                         xpt_print(ccb->ccb_h.path, "reset device\n");
3310                 }
3311                 CAMLOCK_2_MPTLOCK(mpt);
3312                 (void) mpt_bus_reset(mpt, tgt, lun, FALSE);
3313                 MPTLOCK_2_CAMLOCK(mpt);
3314
3315                 /*
3316                  * mpt_bus_reset is always successful in that it
3317                  * will fall back to a hard reset should a bus
3318                  * reset attempt fail.
3319                  */
3320                 ccb->ccb_h.status &= ~CAM_SIM_QUEUED;
3321                 mpt_set_ccb_status(ccb, CAM_REQ_CMP);
3322                 break;
3323                 
3324         case XPT_ABORT:
3325         {
3326                 union ccb *accb = ccb->cab.abort_ccb;
3327                 CAMLOCK_2_MPTLOCK(mpt);
3328                 switch (accb->ccb_h.func_code) {
3329                 case XPT_ACCEPT_TARGET_IO:
3330                 case XPT_IMMED_NOTIFY:
3331                         ccb->ccb_h.status = mpt_abort_target_ccb(mpt, ccb);
3332                         break;
3333                 case XPT_CONT_TARGET_IO:
3334                         mpt_prt(mpt, "cannot abort active CTIOs yet\n");
3335                         ccb->ccb_h.status = CAM_UA_ABORT;
3336                         break;
3337                 case XPT_SCSI_IO:
3338                         ccb->ccb_h.status = CAM_UA_ABORT;
3339                         break;
3340                 default:
3341                         ccb->ccb_h.status = CAM_REQ_INVALID;
3342                         break;
3343                 }
3344                 MPTLOCK_2_CAMLOCK(mpt);
3345                 break;
3346         }
3347
3348 #ifdef  CAM_NEW_TRAN_CODE
3349 #define IS_CURRENT_SETTINGS(c)  ((c)->type == CTS_TYPE_CURRENT_SETTINGS)
3350 #else
3351 #define IS_CURRENT_SETTINGS(c)  ((c)->flags & CCB_TRANS_CURRENT_SETTINGS)
3352 #endif
3353 #define DP_DISC_ENABLE  0x1
3354 #define DP_DISC_DISABL  0x2
3355 #define DP_DISC         (DP_DISC_ENABLE|DP_DISC_DISABL)
3356
3357 #define DP_TQING_ENABLE 0x4
3358 #define DP_TQING_DISABL 0x8
3359 #define DP_TQING        (DP_TQING_ENABLE|DP_TQING_DISABL)
3360
3361 #define DP_WIDE         0x10
3362 #define DP_NARROW       0x20
3363 #define DP_WIDTH        (DP_WIDE|DP_NARROW)
3364
3365 #define DP_SYNC         0x40
3366
3367         case XPT_SET_TRAN_SETTINGS:     /* Nexus Settings */
3368         {
3369 #ifdef  CAM_NEW_TRAN_CODE
3370                 struct ccb_trans_settings_scsi *scsi;
3371                 struct ccb_trans_settings_spi *spi;
3372 #endif
3373                 uint8_t dval;
3374                 u_int period;
3375                 u_int offset;
3376                 int i, j;
3377
3378                 cts = &ccb->cts;
3379
3380                 if (mpt->is_fc || mpt->is_sas) {
3381                         mpt_set_ccb_status(ccb, CAM_REQ_CMP);
3382                         break;
3383                 }
3384
3385 #ifdef  CAM_NEW_TRAN_CODE
3386                 scsi = &cts->proto_specific.scsi;
3387                 spi = &cts->xport_specific.spi;
3388
3389                 /*
3390                  * We can be called just to valid transport and proto versions
3391                  */
3392                 if (scsi->valid == 0 && spi->valid == 0) {
3393                         mpt_set_ccb_status(ccb, CAM_REQ_CMP);
3394                         break;
3395                 }
3396 #endif
3397
3398                 /*
3399                  * Skip attempting settings on RAID volume disks.
3400                  * Other devices on the bus get the normal treatment.
3401                  */
3402                 if (mpt->phydisk_sim && raid_passthru == 0 &&
3403                     mpt_is_raid_volume(mpt, tgt) != 0) {
3404                         mpt_lprt(mpt, MPT_PRT_NEGOTIATION,
3405                             "no transfer settings for RAID vols\n");
3406                         mpt_set_ccb_status(ccb, CAM_REQ_CMP);
3407                         break;
3408                 }
3409
3410                 i = mpt->mpt_port_page2.PortSettings &
3411                     MPI_SCSIPORTPAGE2_PORT_MASK_NEGO_MASTER_SETTINGS;
3412                 j = mpt->mpt_port_page2.PortFlags &
3413                     MPI_SCSIPORTPAGE2_PORT_FLAGS_DV_MASK;
3414                 if (i == MPI_SCSIPORTPAGE2_PORT_ALL_MASTER_SETTINGS &&
3415                     j == MPI_SCSIPORTPAGE2_PORT_FLAGS_OFF_DV) {
3416                         mpt_lprt(mpt, MPT_PRT_ALWAYS,
3417                             "honoring BIOS transfer negotiations\n");
3418                         mpt_set_ccb_status(ccb, CAM_REQ_CMP);
3419                         break;
3420                 }
3421
3422                 dval = 0;
3423                 period = 0;
3424                 offset = 0;
3425
3426 #ifndef CAM_NEW_TRAN_CODE
3427                 if ((cts->valid & CCB_TRANS_DISC_VALID) != 0) {
3428                         dval |= (cts->flags & CCB_TRANS_DISC_ENB) ?
3429                             DP_DISC_ENABLE : DP_DISC_DISABL;
3430                 }
3431
3432                 if ((cts->valid & CCB_TRANS_TQ_VALID) != 0) {
3433                         dval |= (cts->flags & CCB_TRANS_TAG_ENB) ?
3434                             DP_TQING_ENABLE : DP_TQING_DISABL;
3435                 }
3436
3437                 if ((cts->valid & CCB_TRANS_BUS_WIDTH_VALID) != 0) {
3438                         dval |= cts->bus_width ? DP_WIDE : DP_NARROW;
3439                 }
3440
3441                 if ((cts->valid & CCB_TRANS_SYNC_RATE_VALID) &&
3442                     (cts->valid & CCB_TRANS_SYNC_OFFSET_VALID)) {
3443                         dval |= DP_SYNC;
3444                         period = cts->sync_period;
3445                         offset = cts->sync_offset;
3446                 }
3447 #else
3448                 if ((spi->valid & CTS_SPI_VALID_DISC) != 0) {
3449                         dval |= ((spi->flags & CTS_SPI_FLAGS_DISC_ENB) != 0) ?
3450                             DP_DISC_ENABLE : DP_DISC_DISABL;
3451                 }
3452
3453                 if ((scsi->valid & CTS_SCSI_VALID_TQ) != 0) {
3454                         dval |= ((scsi->flags & CTS_SCSI_FLAGS_TAG_ENB) != 0) ?
3455                             DP_TQING_ENABLE : DP_TQING_DISABL;
3456                 }
3457
3458                 if ((spi->valid & CTS_SPI_VALID_BUS_WIDTH) != 0) {
3459                         dval |= (spi->bus_width == MSG_EXT_WDTR_BUS_16_BIT) ?
3460                             DP_WIDE : DP_NARROW;
3461                 }
3462
3463                 if (spi->valid & CTS_SPI_VALID_SYNC_OFFSET) {
3464                         dval |= DP_SYNC;
3465                         offset = spi->sync_offset;
3466                 } else {
3467                         PTR_CONFIG_PAGE_SCSI_DEVICE_1 ptr =
3468                             &mpt->mpt_dev_page1[tgt];
3469                         offset = ptr->RequestedParameters;
3470                         offset &= MPI_SCSIDEVPAGE1_RP_MAX_SYNC_OFFSET_MASK;
3471                         offset >>= MPI_SCSIDEVPAGE1_RP_SHIFT_MAX_SYNC_OFFSET;
3472                 }
3473                 if (spi->valid & CTS_SPI_VALID_SYNC_RATE) {
3474                         dval |= DP_SYNC;
3475                         period = spi->sync_period;
3476                 } else {
3477                         PTR_CONFIG_PAGE_SCSI_DEVICE_1 ptr =
3478                             &mpt->mpt_dev_page1[tgt];
3479                         period = ptr->RequestedParameters;
3480                         period &= MPI_SCSIDEVPAGE1_RP_MIN_SYNC_PERIOD_MASK;
3481                         period >>= MPI_SCSIDEVPAGE1_RP_SHIFT_MIN_SYNC_PERIOD;
3482                 }
3483 #endif
3484                 CAMLOCK_2_MPTLOCK(mpt);
3485                 if (dval & DP_DISC_ENABLE) {
3486                         mpt->mpt_disc_enable |= (1 << tgt);
3487                 } else if (dval & DP_DISC_DISABL) {
3488                         mpt->mpt_disc_enable &= ~(1 << tgt);
3489                 }
3490                 if (dval & DP_TQING_ENABLE) {
3491                         mpt->mpt_tag_enable |= (1 << tgt);
3492                 } else if (dval & DP_TQING_DISABL) {
3493                         mpt->mpt_tag_enable &= ~(1 << tgt);
3494                 }
3495                 if (dval & DP_WIDTH) {
3496                         mpt_setwidth(mpt, tgt, 1);
3497                 }
3498                 if (dval & DP_SYNC) {
3499                         mpt_setsync(mpt, tgt, period, offset);
3500                 }
3501                 if (dval == 0) {
3502                         MPTLOCK_2_CAMLOCK(mpt);
3503                         mpt_set_ccb_status(ccb, CAM_REQ_CMP);
3504                         break;
3505                 }
3506                 mpt_lprt(mpt, MPT_PRT_NEGOTIATION,
3507                     "set [%d]: 0x%x period 0x%x offset %d\n",
3508                     tgt, dval, period, offset);
3509                 if (mpt_update_spi_config(mpt, tgt)) {
3510                         mpt_set_ccb_status(ccb, CAM_REQ_CMP_ERR);
3511                 } else {
3512                         mpt_set_ccb_status(ccb, CAM_REQ_CMP);
3513                 }
3514                 MPTLOCK_2_CAMLOCK(mpt);
3515                 break;
3516         }
3517         case XPT_GET_TRAN_SETTINGS:
3518         {
3519 #ifdef  CAM_NEW_TRAN_CODE
3520                 struct ccb_trans_settings_scsi *scsi;
3521                 cts = &ccb->cts;
3522                 cts->protocol = PROTO_SCSI;
3523                 if (mpt->is_fc) {
3524                         struct ccb_trans_settings_fc *fc =
3525                             &cts->xport_specific.fc;
3526                         cts->protocol_version = SCSI_REV_SPC;
3527                         cts->transport = XPORT_FC;
3528                         cts->transport_version = 0;
3529                         fc->valid = CTS_FC_VALID_SPEED;
3530                         fc->bitrate = 100000;
3531                 } else if (mpt->is_sas) {
3532                         struct ccb_trans_settings_sas *sas =
3533                             &cts->xport_specific.sas;
3534                         cts->protocol_version = SCSI_REV_SPC2;
3535                         cts->transport = XPORT_SAS;
3536                         cts->transport_version = 0;
3537                         sas->valid = CTS_SAS_VALID_SPEED;
3538                         sas->bitrate = 300000;
3539                 } else {
3540                         cts->protocol_version = SCSI_REV_2;
3541                         cts->transport = XPORT_SPI;
3542                         cts->transport_version = 2;
3543                         if (mpt_get_spi_settings(mpt, cts) != 0) {
3544                                 mpt_set_ccb_status(ccb, CAM_REQ_CMP_ERR);
3545                                 break;
3546                         }
3547                 }
3548                 scsi = &cts->proto_specific.scsi;
3549                 scsi->valid = CTS_SCSI_VALID_TQ;
3550                 scsi->flags = CTS_SCSI_FLAGS_TAG_ENB;
3551 #else
3552                 cts = &ccb->cts;
3553                 if (mpt->is_fc) {
3554                         cts->flags = CCB_TRANS_TAG_ENB | CCB_TRANS_DISC_ENB;
3555                         cts->valid = CCB_TRANS_DISC_VALID | CCB_TRANS_TQ_VALID;
3556                         cts->bus_width = MSG_EXT_WDTR_BUS_8_BIT;
3557                 } else if (mpt->is_sas) {
3558                         cts->flags = CCB_TRANS_TAG_ENB | CCB_TRANS_DISC_ENB;
3559                         cts->valid = CCB_TRANS_DISC_VALID | CCB_TRANS_TQ_VALID;
3560                         cts->bus_width = MSG_EXT_WDTR_BUS_8_BIT;
3561                 } else if (mpt_get_spi_settings(mpt, cts) != 0) {
3562                         mpt_set_ccb_status(ccb, CAM_REQ_CMP_ERR);
3563                         break;
3564                 }
3565 #endif
3566                 mpt_set_ccb_status(ccb, CAM_REQ_CMP);
3567                 break;
3568         }
3569         case XPT_CALC_GEOMETRY:
3570         {
3571                 struct ccb_calc_geometry *ccg;
3572
3573                 ccg = &ccb->ccg;
3574                 if (ccg->block_size == 0) {
3575                         ccb->ccb_h.status &= ~CAM_SIM_QUEUED;
3576                         mpt_set_ccb_status(ccb, CAM_REQ_INVALID);
3577                         break;
3578                 }
3579                 mpt_calc_geometry(ccg, /*extended*/1);
3580                 KASSERT(ccb->ccb_h.status, ("zero ccb sts at %d\n", __LINE__));
3581                 break;
3582         }
3583         case XPT_PATH_INQ:              /* Path routing inquiry */
3584         {
3585                 struct ccb_pathinq *cpi = &ccb->cpi;
3586
3587                 cpi->version_num = 1;
3588                 cpi->target_sprt = 0;
3589                 cpi->hba_eng_cnt = 0;
3590                 cpi->max_target = mpt->port_facts[0].MaxDevices - 1;
3591                 /*
3592                  * FC cards report MAX_DEVICES of 512, but
3593                  * the MSG_SCSI_IO_REQUEST target id field
3594                  * is only 8 bits. Until we fix the driver
3595                  * to support 'channels' for bus overflow,
3596                  * just limit it.
3597                  */
3598                 if (cpi->max_target > 255) {
3599                         cpi->max_target = 255;
3600                 }
3601
3602                 /*
3603                  * VMware ESX reports > 16 devices and then dies when we probe.
3604                  */
3605                 if (mpt->is_spi && cpi->max_target > 15) {
3606                         cpi->max_target = 15;
3607                 }
3608                 cpi->max_lun = 7;
3609                 cpi->initiator_id = mpt->mpt_ini_id;
3610                 cpi->bus_id = cam_sim_bus(sim);
3611
3612                 /*
3613                  * The base speed is the speed of the underlying connection.
3614                  */
3615 #ifdef  CAM_NEW_TRAN_CODE
3616                 cpi->protocol = PROTO_SCSI;
3617                 if (mpt->is_fc) {
3618                         cpi->hba_misc = PIM_NOBUSRESET;
3619                         cpi->base_transfer_speed = 100000;
3620                         cpi->hba_inquiry = PI_TAG_ABLE;
3621                         cpi->transport = XPORT_FC;
3622                         cpi->transport_version = 0;
3623                         cpi->protocol_version = SCSI_REV_SPC;
3624                 } else if (mpt->is_sas) {
3625                         cpi->hba_misc = PIM_NOBUSRESET;
3626                         cpi->base_transfer_speed = 300000;
3627                         cpi->hba_inquiry = PI_TAG_ABLE;
3628                         cpi->transport = XPORT_SAS;
3629                         cpi->transport_version = 0;
3630                         cpi->protocol_version = SCSI_REV_SPC2;
3631                 } else {
3632                         cpi->hba_misc = PIM_SEQSCAN;
3633                         cpi->base_transfer_speed = 3300;
3634                         cpi->hba_inquiry = PI_SDTR_ABLE|PI_TAG_ABLE|PI_WIDE_16;
3635                         cpi->transport = XPORT_SPI;
3636                         cpi->transport_version = 2;
3637                         cpi->protocol_version = SCSI_REV_2;
3638                 }
3639 #else
3640                 if (mpt->is_fc) {
3641                         cpi->hba_misc = PIM_NOBUSRESET;
3642                         cpi->base_transfer_speed = 100000;
3643                         cpi->hba_inquiry = PI_TAG_ABLE;
3644                 } else if (mpt->is_sas) {
3645                         cpi->hba_misc = PIM_NOBUSRESET;
3646                         cpi->base_transfer_speed = 300000;
3647                         cpi->hba_inquiry = PI_TAG_ABLE;
3648                 } else {
3649                         cpi->hba_misc = PIM_SEQSCAN;
3650                         cpi->base_transfer_speed = 3300;
3651                         cpi->hba_inquiry = PI_SDTR_ABLE|PI_TAG_ABLE|PI_WIDE_16;
3652                 }
3653 #endif
3654
3655                 /*
3656                  * We give our fake RAID passhtru bus a width that is MaxVolumes
3657                  * wide and restrict it to one lun.
3658                  */
3659                 if (raid_passthru) {
3660                         cpi->max_target = mpt->ioc_page2->MaxPhysDisks - 1;
3661                         cpi->initiator_id = cpi->max_target + 1;
3662                         cpi->max_lun = 0;
3663                 }
3664
3665                 if ((mpt->role & MPT_ROLE_INITIATOR) == 0) {
3666                         cpi->hba_misc |= PIM_NOINITIATOR;
3667                 }
3668                 if (mpt->is_fc && (mpt->role & MPT_ROLE_TARGET)) {
3669                         cpi->target_sprt =
3670                             PIT_PROCESSOR | PIT_DISCONNECT | PIT_TERM_IO;
3671                 } else {
3672                         cpi->target_sprt = 0;
3673                 }
3674                 strncpy(cpi->sim_vid, "FreeBSD", SIM_IDLEN);
3675                 strncpy(cpi->hba_vid, "LSI", HBA_IDLEN);
3676                 strncpy(cpi->dev_name, cam_sim_name(sim), DEV_IDLEN);
3677                 cpi->unit_number = cam_sim_unit(sim);
3678                 cpi->ccb_h.status = CAM_REQ_CMP;
3679                 break;
3680         }
3681         case XPT_EN_LUN:                /* Enable LUN as a target */
3682         {
3683                 int result;
3684
3685                 CAMLOCK_2_MPTLOCK(mpt);
3686                 if (ccb->cel.enable)
3687                         result = mpt_enable_lun(mpt,
3688                             ccb->ccb_h.target_id, ccb->ccb_h.target_lun);
3689                 else
3690                         result = mpt_disable_lun(mpt,
3691                             ccb->ccb_h.target_id, ccb->ccb_h.target_lun);
3692                 MPTLOCK_2_CAMLOCK(mpt);
3693                 if (result == 0) {
3694                         mpt_set_ccb_status(ccb, CAM_REQ_CMP);
3695                 } else {
3696                         mpt_set_ccb_status(ccb, CAM_REQ_CMP_ERR);
3697                 }
3698                 break;
3699         }
3700         case XPT_NOTIFY_ACK:            /* recycle notify ack */
3701         case XPT_IMMED_NOTIFY:          /* Add Immediate Notify Resource */
3702         case XPT_ACCEPT_TARGET_IO:      /* Add Accept Target IO Resource */
3703         {
3704                 tgt_resource_t *trtp;
3705                 lun_id_t lun = ccb->ccb_h.target_lun;
3706                 ccb->ccb_h.sim_priv.entries[0].field = 0;
3707                 ccb->ccb_h.sim_priv.entries[1].ptr = mpt;
3708                 ccb->ccb_h.flags = 0;
3709
3710                 if (lun == CAM_LUN_WILDCARD) {
3711                         if (ccb->ccb_h.target_id != CAM_TARGET_WILDCARD) {
3712                                 mpt_set_ccb_status(ccb, CAM_REQ_INVALID);
3713                                 break;
3714                         }
3715                         trtp = &mpt->trt_wildcard;
3716                 } else if (lun >= MPT_MAX_LUNS) {
3717                         mpt_set_ccb_status(ccb, CAM_REQ_INVALID);
3718                         break;
3719                 } else {
3720                         trtp = &mpt->trt[lun];
3721                 }
3722                 CAMLOCK_2_MPTLOCK(mpt);
3723                 if (ccb->ccb_h.func_code == XPT_ACCEPT_TARGET_IO) {
3724                         mpt_lprt(mpt, MPT_PRT_DEBUG1,
3725                             "Put FREE ATIO %p lun %d\n", ccb, lun);
3726                         STAILQ_INSERT_TAIL(&trtp->atios, &ccb->ccb_h,
3727                             sim_links.stqe);
3728                 } else if (ccb->ccb_h.func_code == XPT_IMMED_NOTIFY) {
3729                         mpt_lprt(mpt, MPT_PRT_DEBUG1,
3730                             "Put FREE INOT lun %d\n", lun);
3731                         STAILQ_INSERT_TAIL(&trtp->inots, &ccb->ccb_h,
3732                             sim_links.stqe);
3733                 } else {
3734                         mpt_lprt(mpt, MPT_PRT_ALWAYS, "Got Notify ACK\n");
3735                 }
3736                 mpt_set_ccb_status(ccb, CAM_REQ_INPROG);
3737                 MPTLOCK_2_CAMLOCK(mpt);
3738                 return;
3739         }
3740         case XPT_CONT_TARGET_IO:
3741                 CAMLOCK_2_MPTLOCK(mpt);
3742                 mpt_target_start_io(mpt, ccb);
3743                 MPTLOCK_2_CAMLOCK(mpt);
3744                 return;
3745
3746         default:
3747                 ccb->ccb_h.status = CAM_REQ_INVALID;
3748                 break;
3749         }
3750         xpt_done(ccb);
3751 }
3752
3753 static int
3754 mpt_get_spi_settings(struct mpt_softc *mpt, struct ccb_trans_settings *cts)
3755 {
3756 #ifdef  CAM_NEW_TRAN_CODE
3757         struct ccb_trans_settings_scsi *scsi = &cts->proto_specific.scsi;
3758         struct ccb_trans_settings_spi *spi = &cts->xport_specific.spi;
3759 #endif
3760         target_id_t tgt;
3761         uint32_t dval, pval, oval;
3762         int rv;
3763
3764         if (IS_CURRENT_SETTINGS(cts) == 0) {
3765                 tgt = cts->ccb_h.target_id;
3766         } else if (xpt_path_sim(cts->ccb_h.path) == mpt->phydisk_sim) {
3767                 if (mpt_map_physdisk(mpt, (union ccb *)cts, &tgt)) {
3768                         return (-1);
3769                 }
3770         } else {
3771                 tgt = cts->ccb_h.target_id;
3772         }
3773
3774         /*
3775          * We aren't looking at Port Page 2 BIOS settings here-
3776          * sometimes these have been known to be bogus XXX.
3777          *
3778          * For user settings, we pick the max from port page 0
3779          * 
3780          * For current settings we read the current settings out from
3781          * device page 0 for that target.
3782          */
3783         if (IS_CURRENT_SETTINGS(cts)) {
3784                 CONFIG_PAGE_SCSI_DEVICE_0 tmp;
3785                 dval = 0;
3786
3787                 CAMLOCK_2_MPTLOCK(mpt);
3788                 tmp = mpt->mpt_dev_page0[tgt];
3789                 rv = mpt_read_cur_cfg_page(mpt, tgt, &tmp.Header,
3790                     sizeof(tmp), FALSE, 5000);
3791                 if (rv) {
3792                         MPTLOCK_2_CAMLOCK(mpt);
3793                         mpt_prt(mpt, "can't get tgt %d config page 0\n", tgt);
3794                         return (rv);
3795                 }
3796                 mpt2host_config_page_scsi_device_0(&tmp);
3797                 
3798                 MPTLOCK_2_CAMLOCK(mpt);
3799                 mpt_lprt(mpt, MPT_PRT_DEBUG,
3800                     "mpt_get_spi_settings[%d]: current NP %x Info %x\n", tgt,
3801                     tmp.NegotiatedParameters, tmp.Information);
3802                 dval |= (tmp.NegotiatedParameters & MPI_SCSIDEVPAGE0_NP_WIDE) ?
3803                     DP_WIDE : DP_NARROW;
3804                 dval |= (mpt->mpt_disc_enable & (1 << tgt)) ?
3805                     DP_DISC_ENABLE : DP_DISC_DISABL;
3806                 dval |= (mpt->mpt_tag_enable & (1 << tgt)) ?
3807                     DP_TQING_ENABLE : DP_TQING_DISABL;
3808                 oval = tmp.NegotiatedParameters;
3809                 oval &= MPI_SCSIDEVPAGE0_NP_NEG_SYNC_OFFSET_MASK;
3810                 oval >>= MPI_SCSIDEVPAGE0_NP_SHIFT_SYNC_OFFSET;
3811                 pval = tmp.NegotiatedParameters;
3812                 pval &= MPI_SCSIDEVPAGE0_NP_NEG_SYNC_PERIOD_MASK;
3813                 pval >>= MPI_SCSIDEVPAGE0_NP_SHIFT_SYNC_PERIOD;
3814                 mpt->mpt_dev_page0[tgt] = tmp;
3815         } else {
3816                 dval = DP_WIDE|DP_DISC_ENABLE|DP_TQING_ENABLE|DP_SYNC;
3817                 oval = mpt->mpt_port_page0.Capabilities;
3818                 oval = MPI_SCSIPORTPAGE0_CAP_GET_MAX_SYNC_OFFSET(oval);
3819                 pval = mpt->mpt_port_page0.Capabilities;
3820                 pval = MPI_SCSIPORTPAGE0_CAP_GET_MIN_SYNC_PERIOD(pval);
3821         }
3822
3823 #ifndef CAM_NEW_TRAN_CODE
3824         cts->flags &= ~(CCB_TRANS_DISC_ENB|CCB_TRANS_TAG_ENB);
3825         cts->valid = 0;
3826         cts->sync_period = pval;
3827         cts->sync_offset = oval;
3828         cts->valid |= CCB_TRANS_SYNC_RATE_VALID;
3829         cts->valid |= CCB_TRANS_SYNC_OFFSET_VALID;
3830         cts->valid |= CCB_TRANS_BUS_WIDTH_VALID;
3831         if (dval & DP_WIDE) {
3832                 cts->bus_width = MSG_EXT_WDTR_BUS_16_BIT;
3833         } else {
3834                 cts->bus_width = MSG_EXT_WDTR_BUS_8_BIT;
3835         }
3836         if (cts->ccb_h.target_lun != CAM_LUN_WILDCARD) {
3837                 cts->valid |= CCB_TRANS_DISC_VALID | CCB_TRANS_TQ_VALID;
3838                 if (dval & DP_DISC_ENABLE) {
3839                         cts->flags |= CCB_TRANS_DISC_ENB;
3840                 }
3841                 if (dval & DP_TQING_ENABLE) {
3842                         cts->flags |= CCB_TRANS_TAG_ENB;
3843                 }
3844         }
3845 #else
3846         spi->valid = 0;
3847         scsi->valid = 0;
3848         spi->flags = 0;
3849         scsi->flags = 0;
3850         spi->sync_offset = oval;
3851         spi->sync_period = pval;
3852         spi->valid |= CTS_SPI_VALID_SYNC_OFFSET;
3853         spi->valid |= CTS_SPI_VALID_SYNC_RATE;
3854         spi->valid |= CTS_SPI_VALID_BUS_WIDTH;
3855         if (dval & DP_WIDE) {
3856                 spi->bus_width = MSG_EXT_WDTR_BUS_16_BIT;
3857         } else {
3858                 spi->bus_width = MSG_EXT_WDTR_BUS_8_BIT;
3859         }
3860         if (cts->ccb_h.target_lun != CAM_LUN_WILDCARD) {
3861                 scsi->valid = CTS_SCSI_VALID_TQ;
3862                 if (dval & DP_TQING_ENABLE) {
3863                         scsi->flags |= CTS_SCSI_FLAGS_TAG_ENB;
3864                 }
3865                 spi->valid |= CTS_SPI_VALID_DISC;
3866                 if (dval & DP_DISC_ENABLE) {
3867                         spi->flags |= CTS_SPI_FLAGS_DISC_ENB;
3868                 }
3869         }
3870 #endif
3871         mpt_lprt(mpt, MPT_PRT_NEGOTIATION,
3872             "mpt_get_spi_settings[%d]: %s flags 0x%x per 0x%x off=%d\n", tgt,
3873             IS_CURRENT_SETTINGS(cts)? "ACTIVE" : "NVRAM ", dval, pval, oval);
3874         return (0);
3875 }
3876
3877 static void
3878 mpt_setwidth(struct mpt_softc *mpt, int tgt, int onoff)
3879 {
3880         PTR_CONFIG_PAGE_SCSI_DEVICE_1 ptr;
3881
3882         ptr = &mpt->mpt_dev_page1[tgt];
3883         if (onoff) {
3884                 ptr->RequestedParameters |= MPI_SCSIDEVPAGE1_RP_WIDE;
3885         } else {
3886                 ptr->RequestedParameters &= ~MPI_SCSIDEVPAGE1_RP_WIDE;
3887         }
3888 }
3889
3890 static void
3891 mpt_setsync(struct mpt_softc *mpt, int tgt, int period, int offset)
3892 {
3893         PTR_CONFIG_PAGE_SCSI_DEVICE_1 ptr;
3894
3895         ptr = &mpt->mpt_dev_page1[tgt];
3896         ptr->RequestedParameters &= ~MPI_SCSIDEVPAGE1_RP_MIN_SYNC_PERIOD_MASK;
3897         ptr->RequestedParameters &= ~MPI_SCSIDEVPAGE1_RP_MAX_SYNC_OFFSET_MASK;
3898         ptr->RequestedParameters &= ~MPI_SCSIDEVPAGE1_RP_DT;
3899         ptr->RequestedParameters &= ~MPI_SCSIDEVPAGE1_RP_QAS;
3900         ptr->RequestedParameters &= ~MPI_SCSIDEVPAGE1_RP_IU;
3901         if (period == 0) {
3902                 return;
3903         }
3904         ptr->RequestedParameters |=
3905             period << MPI_SCSIDEVPAGE1_RP_SHIFT_MIN_SYNC_PERIOD;
3906         ptr->RequestedParameters |=
3907             offset << MPI_SCSIDEVPAGE1_RP_SHIFT_MAX_SYNC_OFFSET;
3908         if (period < 0xa) {
3909                 ptr->RequestedParameters |= MPI_SCSIDEVPAGE1_RP_DT;
3910         }
3911         if (period < 0x9) {
3912                 ptr->RequestedParameters |= MPI_SCSIDEVPAGE1_RP_QAS;
3913                 ptr->RequestedParameters |= MPI_SCSIDEVPAGE1_RP_IU;
3914         }
3915 }
3916
3917 static int
3918 mpt_update_spi_config(struct mpt_softc *mpt, int tgt)
3919 {
3920         CONFIG_PAGE_SCSI_DEVICE_1 tmp;
3921         int rv;
3922
3923         mpt_lprt(mpt, MPT_PRT_NEGOTIATION,
3924             "mpt_update_spi_config[%d].page1: Requested Params 0x%08x\n",
3925             tgt, mpt->mpt_dev_page1[tgt].RequestedParameters);
3926         tmp = mpt->mpt_dev_page1[tgt];
3927         host2mpt_config_page_scsi_device_1(&tmp);
3928         rv = mpt_write_cur_cfg_page(mpt, tgt,
3929             &tmp.Header, sizeof(tmp), FALSE, 5000);
3930         if (rv) {
3931                 mpt_prt(mpt, "mpt_update_spi_config: write cur page failed\n");
3932                 return (-1);
3933         }
3934         return (0);
3935 }
3936
3937 static void
3938 mpt_calc_geometry(struct ccb_calc_geometry *ccg, int extended)
3939 {
3940 #if __FreeBSD_version >= 500000
3941         cam_calc_geometry(ccg, extended);
3942 #else
3943         uint32_t size_mb;
3944         uint32_t secs_per_cylinder;
3945
3946         if (ccg->block_size == 0) {
3947                 ccg->ccb_h.status = CAM_REQ_INVALID;
3948                 return;
3949         }
3950         size_mb = ccg->volume_size / ((1024L * 1024L) / ccg->block_size);
3951         if (size_mb > 1024 && extended) {
3952                 ccg->heads = 255;
3953                 ccg->secs_per_track = 63;
3954         } else {
3955                 ccg->heads = 64;
3956                 ccg->secs_per_track = 32;
3957         }
3958         secs_per_cylinder = ccg->heads * ccg->secs_per_track;
3959         ccg->cylinders = ccg->volume_size / secs_per_cylinder;
3960         ccg->ccb_h.status = CAM_REQ_CMP;
3961 #endif
3962 }
3963
3964 /****************************** Timeout Recovery ******************************/
3965 static int
3966 mpt_spawn_recovery_thread(struct mpt_softc *mpt)
3967 {
3968         int error;
3969
3970         error = mpt_kthread_create(mpt_recovery_thread, mpt,
3971             &mpt->recovery_thread, /*flags*/0,
3972             /*altstack*/0, "mpt_recovery%d", mpt->unit);
3973         return (error);
3974 }
3975
3976 static void
3977 mpt_terminate_recovery_thread(struct mpt_softc *mpt)
3978 {
3979         if (mpt->recovery_thread == NULL) {
3980                 return;
3981         }
3982         mpt->shutdwn_recovery = 1;
3983         wakeup(mpt);
3984         /*
3985          * Sleep on a slightly different location
3986          * for this interlock just for added safety.
3987          */
3988         mpt_sleep(mpt, &mpt->recovery_thread, PUSER, "thtrm", 0);
3989 }
3990
3991 static void
3992 mpt_recovery_thread(void *arg)
3993 {
3994         struct mpt_softc *mpt;
3995
3996         mpt = (struct mpt_softc *)arg;
3997         MPT_LOCK(mpt);
3998         for (;;) {
3999                 if (TAILQ_EMPTY(&mpt->request_timeout_list) != 0) {
4000                         if (mpt->shutdwn_recovery == 0) {
4001                                 mpt_sleep(mpt, mpt, PUSER, "idle", 0);
4002                         }
4003                 }
4004                 if (mpt->shutdwn_recovery != 0) {
4005                         break;
4006                 }
4007                 mpt_recover_commands(mpt);
4008         }
4009         mpt->recovery_thread = NULL;
4010         wakeup(&mpt->recovery_thread);
4011         MPT_UNLOCK(mpt);
4012         mpt_kthread_exit(0);
4013 }
4014
4015 static int
4016 mpt_scsi_send_tmf(struct mpt_softc *mpt, u_int type, u_int flags,
4017     u_int channel, u_int target, u_int lun, u_int abort_ctx, int sleep_ok)
4018 {
4019         MSG_SCSI_TASK_MGMT *tmf_req;
4020         int                 error;
4021
4022         /*
4023          * Wait for any current TMF request to complete.
4024          * We're only allowed to issue one TMF at a time.
4025          */
4026         error = mpt_wait_req(mpt, mpt->tmf_req, REQ_STATE_FREE, REQ_STATE_FREE,
4027             sleep_ok, MPT_TMF_MAX_TIMEOUT);
4028         if (error != 0) {
4029                 mpt_reset(mpt, TRUE);
4030                 return (ETIMEDOUT);
4031         }
4032
4033         mpt_assign_serno(mpt, mpt->tmf_req);
4034         mpt->tmf_req->state = REQ_STATE_ALLOCATED|REQ_STATE_QUEUED;
4035
4036         tmf_req = (MSG_SCSI_TASK_MGMT *)mpt->tmf_req->req_vbuf;
4037         memset(tmf_req, 0, sizeof(*tmf_req));
4038         tmf_req->TargetID = target;
4039         tmf_req->Bus = channel;
4040         tmf_req->ChainOffset = 0;
4041         tmf_req->Function = MPI_FUNCTION_SCSI_TASK_MGMT;
4042         tmf_req->Reserved = 0;
4043         tmf_req->TaskType = type;
4044         tmf_req->Reserved1 = 0;
4045         tmf_req->MsgFlags = flags;
4046         tmf_req->MsgContext =
4047             htole32(mpt->tmf_req->index | scsi_tmf_handler_id);
4048         memset(&tmf_req->LUN, 0,
4049             sizeof(tmf_req->LUN) + sizeof(tmf_req->Reserved2));
4050         if (lun > 256) {
4051                 tmf_req->LUN[0] = 0x40 | ((lun >> 8) & 0x3f);
4052                 tmf_req->LUN[1] = lun & 0xff;
4053         } else {
4054                 tmf_req->LUN[1] = lun;
4055         }
4056         tmf_req->TaskMsgContext = abort_ctx;
4057
4058         mpt_lprt(mpt, MPT_PRT_DEBUG,
4059             "Issuing TMF %p:%u with MsgContext of 0x%x\n", mpt->tmf_req,
4060             mpt->tmf_req->serno, tmf_req->MsgContext);
4061         if (mpt->verbose > MPT_PRT_DEBUG) {
4062                 mpt_print_request(tmf_req);
4063         }
4064
4065         KASSERT(mpt_req_on_pending_list(mpt, mpt->tmf_req) == 0,
4066             ("mpt_scsi_send_tmf: tmf_req already on pending list"));
4067         TAILQ_INSERT_HEAD(&mpt->request_pending_list, mpt->tmf_req, links);
4068         error = mpt_send_handshake_cmd(mpt, sizeof(*tmf_req), tmf_req);
4069         if (error != MPT_OK) {
4070                 TAILQ_REMOVE(&mpt->request_pending_list, mpt->tmf_req, links);
4071                 mpt->tmf_req->state = REQ_STATE_FREE;
4072                 mpt_reset(mpt, TRUE);
4073         }
4074         return (error);
4075 }
4076
4077 /*
4078  * When a command times out, it is placed on the requeust_timeout_list
4079  * and we wake our recovery thread.  The MPT-Fusion architecture supports
4080  * only a single TMF operation at a time, so we serially abort/bdr, etc,
4081  * the timedout transactions.  The next TMF is issued either by the
4082  * completion handler of the current TMF waking our recovery thread,
4083  * or the TMF timeout handler causing a hard reset sequence.
4084  */
4085 static void
4086 mpt_recover_commands(struct mpt_softc *mpt)
4087 {
4088         request_t          *req;
4089         union ccb          *ccb;
4090         int                 error;
4091
4092         if (TAILQ_EMPTY(&mpt->request_timeout_list) != 0) {
4093                 /*
4094                  * No work to do- leave.
4095                  */
4096                 mpt_prt(mpt, "mpt_recover_commands: no requests.\n");
4097                 return;
4098         }
4099
4100         /*
4101          * Flush any commands whose completion coincides with their timeout.
4102          */
4103         mpt_intr(mpt);
4104
4105         if (TAILQ_EMPTY(&mpt->request_timeout_list) != 0) {
4106                 /*
4107                  * The timedout commands have already
4108                  * completed.  This typically means
4109                  * that either the timeout value was on
4110                  * the hairy edge of what the device
4111                  * requires or - more likely - interrupts
4112                  * are not happening.
4113                  */
4114                 mpt_prt(mpt, "Timedout requests already complete. "
4115                     "Interrupts may not be functioning.\n");
4116                 mpt_enable_ints(mpt);
4117                 return;
4118         }
4119
4120         /*
4121          * We have no visibility into the current state of the
4122          * controller, so attempt to abort the commands in the
4123          * order they timed-out. For initiator commands, we
4124          * depend on the reply handler pulling requests off
4125          * the timeout list.
4126          */
4127         while ((req = TAILQ_FIRST(&mpt->request_timeout_list)) != NULL) {
4128                 uint16_t status;
4129                 uint8_t response;
4130                 MSG_REQUEST_HEADER *hdrp = req->req_vbuf;
4131
4132                 mpt_prt(mpt, "attempting to abort req %p:%u function %x\n",
4133                     req, req->serno, hdrp->Function);
4134                 ccb = req->ccb;
4135                 if (ccb == NULL) {
4136                         mpt_prt(mpt, "null ccb in timed out request. "
4137                             "Resetting Controller.\n");
4138                         mpt_reset(mpt, TRUE);
4139                         continue;
4140                 }
4141                 mpt_set_ccb_status(ccb, CAM_CMD_TIMEOUT);
4142
4143                 /*
4144                  * Check to see if this is not an initiator command and
4145                  * deal with it differently if it is.
4146                  */
4147                 switch (hdrp->Function) {
4148                 case MPI_FUNCTION_SCSI_IO_REQUEST:
4149                 case MPI_FUNCTION_RAID_SCSI_IO_PASSTHROUGH:
4150                         break;
4151                 default:
4152                         /*
4153                          * XXX: FIX ME: need to abort target assists...
4154                          */
4155                         mpt_prt(mpt, "just putting it back on the pend q\n");
4156                         TAILQ_REMOVE(&mpt->request_timeout_list, req, links);
4157                         TAILQ_INSERT_HEAD(&mpt->request_pending_list, req,
4158                             links);
4159                         continue;
4160                 }
4161
4162                 error = mpt_scsi_send_tmf(mpt,
4163                     MPI_SCSITASKMGMT_TASKTYPE_ABORT_TASK,
4164                     0, 0, ccb->ccb_h.target_id, ccb->ccb_h.target_lun,
4165                     htole32(req->index | scsi_io_handler_id), TRUE);
4166
4167                 if (error != 0) {
4168                         /*
4169                          * mpt_scsi_send_tmf hard resets on failure, so no
4170                          * need to do so here.  Our queue should be emptied
4171                          * by the hard reset.
4172                          */
4173                         continue;
4174                 }
4175
4176                 error = mpt_wait_req(mpt, mpt->tmf_req, REQ_STATE_DONE,
4177                     REQ_STATE_DONE, TRUE, 500);
4178
4179                 status = le16toh(mpt->tmf_req->IOCStatus);
4180                 response = mpt->tmf_req->ResponseCode;
4181                 mpt->tmf_req->state = REQ_STATE_FREE;
4182
4183                 if (error != 0) {
4184                         /*
4185                          * If we've errored out,, reset the controller.
4186                          */
4187                         mpt_prt(mpt, "mpt_recover_commands: abort timed-out. "
4188                             "Resetting controller\n");
4189                         mpt_reset(mpt, TRUE);
4190                         continue;
4191                 }
4192
4193                 if ((status & MPI_IOCSTATUS_MASK) != MPI_IOCSTATUS_SUCCESS) {
4194                         mpt_prt(mpt, "mpt_recover_commands: IOC Status 0x%x. "
4195                             "Resetting controller.\n", status);
4196                         mpt_reset(mpt, TRUE);
4197                         continue;
4198                 }
4199
4200                 if (response != MPI_SCSITASKMGMT_RSP_TM_SUCCEEDED &&
4201                     response != MPI_SCSITASKMGMT_RSP_TM_COMPLETE) {
4202                         mpt_prt(mpt, "mpt_recover_commands: TMF Response 0x%x. "
4203                             "Resetting controller.\n", response);
4204                         mpt_reset(mpt, TRUE);
4205                         continue;
4206                 }
4207                 mpt_prt(mpt, "abort of req %p:%u completed\n", req, req->serno);
4208         }
4209 }
4210
4211 /************************ Target Mode Support ****************************/
4212 static void
4213 mpt_fc_post_els(struct mpt_softc *mpt, request_t *req, int ioindex)
4214 {
4215         MSG_LINK_SERVICE_BUFFER_POST_REQUEST *fc;
4216         PTR_SGE_TRANSACTION32 tep;
4217         PTR_SGE_SIMPLE32 se;
4218         bus_addr_t paddr;
4219         uint32_t fl;
4220
4221         paddr = req->req_pbuf;
4222         paddr += MPT_RQSL(mpt);
4223
4224         fc = req->req_vbuf;
4225         memset(fc, 0, MPT_REQUEST_AREA);
4226         fc->BufferCount = 1;
4227         fc->Function = MPI_FUNCTION_FC_LINK_SRVC_BUF_POST;
4228         fc->MsgContext = htole32(req->index | fc_els_handler_id);
4229
4230         /*
4231          * Okay, set up ELS buffer pointers. ELS buffer pointers
4232          * consist of a TE SGL element (with details length of zero)
4233          * followe by a SIMPLE SGL element which holds the address
4234          * of the buffer.
4235          */
4236
4237         tep = (PTR_SGE_TRANSACTION32) &fc->SGL;
4238
4239         tep->ContextSize = 4;
4240         tep->Flags = 0;
4241         tep->TransactionContext[0] = htole32(ioindex);
4242
4243         se = (PTR_SGE_SIMPLE32) &tep->TransactionDetails[0];
4244         fl =
4245                 MPI_SGE_FLAGS_HOST_TO_IOC       |
4246                 MPI_SGE_FLAGS_SIMPLE_ELEMENT    |
4247                 MPI_SGE_FLAGS_LAST_ELEMENT      |
4248                 MPI_SGE_FLAGS_END_OF_LIST       |
4249                 MPI_SGE_FLAGS_END_OF_BUFFER;
4250         fl <<= MPI_SGE_FLAGS_SHIFT;
4251         fl |= (MPT_NRFM(mpt) - MPT_RQSL(mpt));
4252         se->FlagsLength = htole32(fl);
4253         se->Address = htole32((uint32_t) paddr);
4254         mpt_lprt(mpt, MPT_PRT_DEBUG,
4255             "add ELS index %d ioindex %d for %p:%u\n",
4256             req->index, ioindex, req, req->serno);
4257         KASSERT(((req->state & REQ_STATE_LOCKED) != 0),
4258             ("mpt_fc_post_els: request not locked"));
4259         mpt_send_cmd(mpt, req);
4260 }
4261
4262 static void
4263 mpt_post_target_command(struct mpt_softc *mpt, request_t *req, int ioindex)
4264 {
4265         PTR_MSG_TARGET_CMD_BUFFER_POST_REQUEST fc;
4266         PTR_CMD_BUFFER_DESCRIPTOR cb;
4267         bus_addr_t paddr;
4268
4269         paddr = req->req_pbuf;
4270         paddr += MPT_RQSL(mpt);
4271         memset(req->req_vbuf, 0, MPT_REQUEST_AREA);
4272         MPT_TGT_STATE(mpt, req)->state = TGT_STATE_LOADING;
4273
4274         fc = req->req_vbuf;
4275         fc->BufferCount = 1;
4276         fc->Function = MPI_FUNCTION_TARGET_CMD_BUFFER_POST;
4277         fc->MsgContext = htole32(req->index | mpt->scsi_tgt_handler_id);
4278
4279         cb = &fc->Buffer[0];
4280         cb->IoIndex = htole16(ioindex);
4281         cb->u.PhysicalAddress32 = htole32((U32) paddr);
4282
4283         mpt_check_doorbell(mpt);
4284         mpt_send_cmd(mpt, req);
4285 }
4286
4287 static int
4288 mpt_add_els_buffers(struct mpt_softc *mpt)
4289 {
4290         int i;
4291
4292         if (mpt->is_fc == 0) {
4293                 return (TRUE);
4294         }
4295
4296         if (mpt->els_cmds_allocated) {
4297                 return (TRUE);
4298         }
4299
4300         mpt->els_cmd_ptrs = malloc(MPT_MAX_ELS * sizeof (request_t *),
4301             M_DEVBUF, M_NOWAIT | M_ZERO);
4302
4303         if (mpt->els_cmd_ptrs == NULL) {
4304                 return (FALSE);
4305         }
4306
4307         /*
4308          * Feed the chip some ELS buffer resources
4309          */
4310         for (i = 0; i < MPT_MAX_ELS; i++) {
4311                 request_t *req = mpt_get_request(mpt, FALSE);
4312                 if (req == NULL) {
4313                         break;
4314                 }
4315                 req->state |= REQ_STATE_LOCKED;
4316                 mpt->els_cmd_ptrs[i] = req;
4317                 mpt_fc_post_els(mpt, req, i);
4318         }
4319
4320         if (i == 0) {
4321                 mpt_prt(mpt, "unable to add ELS buffer resources\n");
4322                 free(mpt->els_cmd_ptrs, M_DEVBUF);
4323                 mpt->els_cmd_ptrs = NULL;
4324                 return (FALSE);
4325         }
4326         if (i != MPT_MAX_ELS) {
4327                 mpt_lprt(mpt, MPT_PRT_INFO,
4328                     "only added %d of %d  ELS buffers\n", i, MPT_MAX_ELS);
4329         }
4330         mpt->els_cmds_allocated = i;
4331         return(TRUE);
4332 }
4333
4334 static int
4335 mpt_add_target_commands(struct mpt_softc *mpt)
4336 {
4337         int i, max;
4338
4339         if (mpt->tgt_cmd_ptrs) {
4340                 return (TRUE);
4341         }
4342
4343         max = MPT_MAX_REQUESTS(mpt) >> 1;
4344         if (max > mpt->mpt_max_tgtcmds) {
4345                 max = mpt->mpt_max_tgtcmds;
4346         }
4347         mpt->tgt_cmd_ptrs =
4348             malloc(max * sizeof (request_t *), M_DEVBUF, M_NOWAIT | M_ZERO);
4349         if (mpt->tgt_cmd_ptrs == NULL) {
4350                 mpt_prt(mpt,
4351                     "mpt_add_target_commands: could not allocate cmd ptrs\n");
4352                 return (FALSE);
4353         }
4354
4355         for (i = 0; i < max; i++) {
4356                 request_t *req;
4357
4358                 req = mpt_get_request(mpt, FALSE);
4359                 if (req == NULL) {
4360                         break;
4361                 }
4362                 req->state |= REQ_STATE_LOCKED;
4363                 mpt->tgt_cmd_ptrs[i] = req;
4364                 mpt_post_target_command(mpt, req, i);
4365         }
4366
4367
4368         if (i == 0) {
4369                 mpt_lprt(mpt, MPT_PRT_ERROR, "could not add any target bufs\n");
4370                 free(mpt->tgt_cmd_ptrs, M_DEVBUF);
4371                 mpt->tgt_cmd_ptrs = NULL;
4372                 return (FALSE);
4373         }
4374
4375         mpt->tgt_cmds_allocated = i;
4376
4377         if (i < max) {
4378                 mpt_lprt(mpt, MPT_PRT_INFO,
4379                     "added %d of %d target bufs\n", i, max);
4380         }
4381         return (i);
4382 }
4383
4384 static int
4385 mpt_enable_lun(struct mpt_softc *mpt, target_id_t tgt, lun_id_t lun)
4386 {
4387         if (tgt == CAM_TARGET_WILDCARD && lun == CAM_LUN_WILDCARD) {
4388                 mpt->twildcard = 1;
4389         } else if (lun >= MPT_MAX_LUNS) {
4390                 return (EINVAL);
4391         } else if (tgt != CAM_TARGET_WILDCARD && tgt != 0) {
4392                 return (EINVAL);
4393         }
4394         if (mpt->tenabled == 0) {
4395                 if (mpt->is_fc) {
4396                         (void) mpt_fc_reset_link(mpt, 0);
4397                 }
4398                 mpt->tenabled = 1;
4399         }
4400         if (lun == CAM_LUN_WILDCARD) {
4401                 mpt->trt_wildcard.enabled = 1;
4402         } else {
4403                 mpt->trt[lun].enabled = 1;
4404         }
4405         return (0);
4406 }
4407
4408 static int
4409 mpt_disable_lun(struct mpt_softc *mpt, target_id_t tgt, lun_id_t lun)
4410 {
4411         int i;
4412         if (tgt == CAM_TARGET_WILDCARD && lun == CAM_LUN_WILDCARD) {
4413                 mpt->twildcard = 0;
4414         } else if (lun >= MPT_MAX_LUNS) {
4415                 return (EINVAL);
4416         } else if (tgt != CAM_TARGET_WILDCARD && tgt != 0) {
4417                 return (EINVAL);
4418         }
4419         if (lun == CAM_LUN_WILDCARD) {
4420                 mpt->trt_wildcard.enabled = 0;
4421         } else {
4422                 mpt->trt[lun].enabled = 0;
4423         }
4424         for (i = 0; i < MPT_MAX_LUNS; i++) {
4425                 if (mpt->trt[lun].enabled) {
4426                         break;
4427                 }
4428         }
4429         if (i == MPT_MAX_LUNS && mpt->twildcard == 0) {
4430                 if (mpt->is_fc) {
4431                         (void) mpt_fc_reset_link(mpt, 0);
4432                 }
4433                 mpt->tenabled = 0;
4434         }
4435         return (0);
4436 }
4437
4438 /*
4439  * Called with MPT lock held
4440  */
4441 static void
4442 mpt_target_start_io(struct mpt_softc *mpt, union ccb *ccb)
4443 {
4444         struct ccb_scsiio *csio = &ccb->csio;
4445         request_t *cmd_req = MPT_TAG_2_REQ(mpt, csio->tag_id);
4446         mpt_tgt_state_t *tgt = MPT_TGT_STATE(mpt, cmd_req);
4447
4448         switch (tgt->state) {
4449         case TGT_STATE_IN_CAM:
4450                 break;
4451         case TGT_STATE_MOVING_DATA:
4452                 mpt_set_ccb_status(ccb, CAM_REQUEUE_REQ);
4453                 xpt_freeze_simq(mpt->sim, 1);
4454                 ccb->ccb_h.status &= ~CAM_SIM_QUEUED;
4455                 tgt->ccb->ccb_h.status |= CAM_RELEASE_SIMQ;
4456                 MPTLOCK_2_CAMLOCK(mpt);
4457                 xpt_done(ccb);
4458                 CAMLOCK_2_MPTLOCK(mpt);
4459                 return;
4460         default:
4461                 mpt_prt(mpt, "ccb %p flags 0x%x tag 0x%08x had bad request "
4462                     "starting I/O\n", ccb, csio->ccb_h.flags, csio->tag_id);
4463                 mpt_tgt_dump_req_state(mpt, cmd_req);
4464                 mpt_set_ccb_status(ccb, CAM_REQ_CMP_ERR);
4465                 MPTLOCK_2_CAMLOCK(mpt);
4466                 xpt_done(ccb);
4467                 CAMLOCK_2_MPTLOCK(mpt);
4468                 return;
4469         }
4470
4471         if (csio->dxfer_len) {
4472                 bus_dmamap_callback_t *cb;
4473                 PTR_MSG_TARGET_ASSIST_REQUEST ta;
4474                 request_t *req;
4475
4476                 KASSERT((ccb->ccb_h.flags & CAM_DIR_MASK) != CAM_DIR_NONE,
4477                     ("dxfer_len %u but direction is NONE\n", csio->dxfer_len));
4478
4479                 if ((req = mpt_get_request(mpt, FALSE)) == NULL) {
4480                         if (mpt->outofbeer == 0) {
4481                                 mpt->outofbeer = 1;
4482                                 xpt_freeze_simq(mpt->sim, 1);
4483                                 mpt_lprt(mpt, MPT_PRT_DEBUG, "FREEZEQ\n");
4484                         }
4485                         ccb->ccb_h.status &= ~CAM_SIM_QUEUED;
4486                         mpt_set_ccb_status(ccb, CAM_REQUEUE_REQ);
4487                         MPTLOCK_2_CAMLOCK(mpt);
4488                         xpt_done(ccb);
4489                         CAMLOCK_2_MPTLOCK(mpt);
4490                         return;
4491                 }
4492                 ccb->ccb_h.status = CAM_SIM_QUEUED | CAM_REQ_INPROG;
4493                 if (sizeof (bus_addr_t) > 4) {
4494                         cb = mpt_execute_req_a64;
4495                 } else {
4496                         cb = mpt_execute_req;
4497                 }
4498
4499                 req->ccb = ccb;
4500                 ccb->ccb_h.ccb_req_ptr = req;
4501
4502                 /*
4503                  * Record the currently active ccb and the
4504                  * request for it in our target state area.
4505                  */
4506                 tgt->ccb = ccb;
4507                 tgt->req = req;
4508
4509                 memset(req->req_vbuf, 0, MPT_RQSL(mpt));
4510                 ta = req->req_vbuf;
4511
4512                 if (mpt->is_sas) {
4513                         PTR_MPI_TARGET_SSP_CMD_BUFFER ssp =
4514                              cmd_req->req_vbuf;
4515                         ta->QueueTag = ssp->InitiatorTag;
4516                 } else if (mpt->is_spi) {
4517                         PTR_MPI_TARGET_SCSI_SPI_CMD_BUFFER sp =
4518                              cmd_req->req_vbuf;
4519                         ta->QueueTag = sp->Tag;
4520                 }
4521                 ta->Function = MPI_FUNCTION_TARGET_ASSIST;
4522                 ta->MsgContext = htole32(req->index | mpt->scsi_tgt_handler_id);
4523                 ta->ReplyWord = htole32(tgt->reply_desc);
4524                 if (csio->ccb_h.target_lun > 256) {
4525                         ta->LUN[0] =
4526                             0x40 | ((csio->ccb_h.target_lun >> 8) & 0x3f);
4527                         ta->LUN[1] = csio->ccb_h.target_lun & 0xff;
4528                 } else {
4529                         ta->LUN[1] = csio->ccb_h.target_lun;
4530                 }
4531
4532                 ta->RelativeOffset = tgt->bytes_xfered;
4533                 ta->DataLength = ccb->csio.dxfer_len;
4534                 if (ta->DataLength > tgt->resid) {
4535                         ta->DataLength = tgt->resid;
4536                 }
4537
4538                 /*
4539                  * XXX Should be done after data transfer completes?
4540                  */
4541                 tgt->resid -= csio->dxfer_len;
4542                 tgt->bytes_xfered += csio->dxfer_len;
4543
4544                 if ((ccb->ccb_h.flags & CAM_DIR_MASK) == CAM_DIR_IN) {
4545                         ta->TargetAssistFlags |=
4546                             TARGET_ASSIST_FLAGS_DATA_DIRECTION;
4547                 }
4548
4549 #ifdef  WE_TRUST_AUTO_GOOD_STATUS
4550                 if ((ccb->ccb_h.flags & CAM_SEND_STATUS) &&
4551                     csio->scsi_status == SCSI_STATUS_OK && tgt->resid == 0) {
4552                         ta->TargetAssistFlags |=
4553                             TARGET_ASSIST_FLAGS_AUTO_STATUS;
4554                 }
4555 #endif
4556                 tgt->state = TGT_STATE_SETTING_UP_FOR_DATA;
4557
4558                 mpt_lprt(mpt, MPT_PRT_DEBUG, 
4559                     "DATA_CCB %p tag %x %u bytes %u resid flg %x req %p:%u "
4560                     "nxtstate=%d\n", csio, csio->tag_id, csio->dxfer_len,
4561                     tgt->resid, ccb->ccb_h.flags, req, req->serno, tgt->state);
4562
4563                 MPTLOCK_2_CAMLOCK(mpt);
4564                 if ((ccb->ccb_h.flags & CAM_SCATTER_VALID) == 0) {
4565                         if ((ccb->ccb_h.flags & CAM_DATA_PHYS) == 0) {
4566                                 int error;
4567                                 int s = splsoftvm();
4568                                 error = bus_dmamap_load(mpt->buffer_dmat,
4569                                     req->dmap, csio->data_ptr, csio->dxfer_len,
4570                                     cb, req, 0);
4571                                 splx(s);
4572                                 if (error == EINPROGRESS) {
4573                                         xpt_freeze_simq(mpt->sim, 1);
4574                                         ccb->ccb_h.status |= CAM_RELEASE_SIMQ;
4575                                 }
4576                         } else {
4577                                 /*
4578                                  * We have been given a pointer to single
4579                                  * physical buffer.
4580                                  */
4581                                 struct bus_dma_segment seg;
4582                                 seg.ds_addr = (bus_addr_t)
4583                                     (vm_offset_t)csio->data_ptr;
4584                                 seg.ds_len = csio->dxfer_len;
4585                                 (*cb)(req, &seg, 1, 0);
4586                         }
4587                 } else {
4588                         /*
4589                          * We have been given a list of addresses.
4590                          * This case could be easily supported but they are not
4591                          * currently generated by the CAM subsystem so there
4592                          * is no point in wasting the time right now.
4593                          */
4594                         struct bus_dma_segment *sgs;
4595                         if ((ccb->ccb_h.flags & CAM_SG_LIST_PHYS) == 0) {
4596                                 (*cb)(req, NULL, 0, EFAULT);
4597                         } else {
4598                                 /* Just use the segments provided */
4599                                 sgs = (struct bus_dma_segment *)csio->data_ptr;
4600                                 (*cb)(req, sgs, csio->sglist_cnt, 0);
4601                         }
4602                 }
4603                 CAMLOCK_2_MPTLOCK(mpt);
4604         } else {
4605                 uint8_t *sp = NULL, sense[MPT_SENSE_SIZE];
4606
4607                 /*
4608                  * XXX: I don't know why this seems to happen, but
4609                  * XXX: completing the CCB seems to make things happy.
4610                  * XXX: This seems to happen if the initiator requests
4611                  * XXX: enough data that we have to do multiple CTIOs.
4612                  */
4613                 if ((ccb->ccb_h.flags & CAM_SEND_STATUS) == 0) {
4614                         mpt_lprt(mpt, MPT_PRT_DEBUG,
4615                             "Meaningless STATUS CCB (%p): flags %x status %x "
4616                             "resid %d bytes_xfered %u\n", ccb, ccb->ccb_h.flags,
4617                             ccb->ccb_h.status, tgt->resid, tgt->bytes_xfered);
4618                         mpt_set_ccb_status(ccb, CAM_REQ_CMP);
4619                         ccb->ccb_h.status &= ~CAM_SIM_QUEUED;
4620                         MPTLOCK_2_CAMLOCK(mpt);
4621                         xpt_done(ccb);
4622                         CAMLOCK_2_MPTLOCK(mpt);
4623                         return;
4624                 }
4625                 if (ccb->ccb_h.flags & CAM_SEND_SENSE) {
4626                         sp = sense;
4627                         memcpy(sp, &csio->sense_data,
4628                            min(csio->sense_len, MPT_SENSE_SIZE));
4629                 }
4630                 mpt_scsi_tgt_status(mpt, ccb, cmd_req, csio->scsi_status, sp);
4631         }
4632 }
4633
4634 static void
4635 mpt_scsi_tgt_local(struct mpt_softc *mpt, request_t *cmd_req,
4636     uint32_t lun, int send, uint8_t *data, size_t length)
4637 {
4638         mpt_tgt_state_t *tgt;
4639         PTR_MSG_TARGET_ASSIST_REQUEST ta;
4640         SGE_SIMPLE32 *se;
4641         uint32_t flags;
4642         uint8_t *dptr;
4643         bus_addr_t pptr;
4644         request_t *req;
4645
4646         /*
4647          * We enter with resid set to the data load for the command.
4648          */
4649         tgt = MPT_TGT_STATE(mpt, cmd_req);
4650         if (length == 0 || tgt->resid == 0) {
4651                 tgt->resid = 0;
4652                 mpt_scsi_tgt_status(mpt, NULL, cmd_req, 0, NULL);
4653                 return;
4654         }
4655
4656         if ((req = mpt_get_request(mpt, FALSE)) == NULL) {
4657                 mpt_prt(mpt, "out of resources- dropping local response\n");
4658                 return;
4659         }
4660         tgt->is_local = 1;
4661
4662
4663         memset(req->req_vbuf, 0, MPT_RQSL(mpt));
4664         ta = req->req_vbuf;
4665
4666         if (mpt->is_sas) {
4667                 PTR_MPI_TARGET_SSP_CMD_BUFFER ssp = cmd_req->req_vbuf;
4668                 ta->QueueTag = ssp->InitiatorTag;
4669         } else if (mpt->is_spi) {
4670                 PTR_MPI_TARGET_SCSI_SPI_CMD_BUFFER sp = cmd_req->req_vbuf;
4671                 ta->QueueTag = sp->Tag;
4672         }
4673         ta->Function = MPI_FUNCTION_TARGET_ASSIST;
4674         ta->MsgContext = htole32(req->index | mpt->scsi_tgt_handler_id);
4675         ta->ReplyWord = htole32(tgt->reply_desc);
4676         if (lun > 256) {
4677                 ta->LUN[0] = 0x40 | ((lun >> 8) & 0x3f);
4678                 ta->LUN[1] = lun & 0xff;
4679         } else {
4680                 ta->LUN[1] = lun;
4681         }
4682         ta->RelativeOffset = 0;
4683         ta->DataLength = length;
4684
4685         dptr = req->req_vbuf;
4686         dptr += MPT_RQSL(mpt);
4687         pptr = req->req_pbuf;
4688         pptr += MPT_RQSL(mpt);
4689         memcpy(dptr, data, min(length, MPT_RQSL(mpt)));
4690
4691         se = (SGE_SIMPLE32 *) &ta->SGL[0];
4692         memset(se, 0,sizeof (*se));
4693
4694         flags = MPI_SGE_FLAGS_SIMPLE_ELEMENT;
4695         if (send) {
4696                 ta->TargetAssistFlags |= TARGET_ASSIST_FLAGS_DATA_DIRECTION;
4697                 flags |= MPI_SGE_FLAGS_HOST_TO_IOC;
4698         }
4699         se->Address = pptr;
4700         MPI_pSGE_SET_LENGTH(se, length);
4701         flags |= MPI_SGE_FLAGS_LAST_ELEMENT;
4702         flags |= MPI_SGE_FLAGS_END_OF_LIST | MPI_SGE_FLAGS_END_OF_BUFFER;
4703         MPI_pSGE_SET_FLAGS(se, flags);
4704
4705         tgt->ccb = NULL;
4706         tgt->req = req;
4707         tgt->resid -= length;
4708         tgt->bytes_xfered = length;
4709 #ifdef  WE_TRUST_AUTO_GOOD_STATUS
4710         tgt->state = TGT_STATE_MOVING_DATA_AND_STATUS;
4711 #else
4712         tgt->state = TGT_STATE_MOVING_DATA;
4713 #endif
4714         mpt_send_cmd(mpt, req);
4715 }
4716
4717 /*
4718  * Abort queued up CCBs
4719  */
4720 static cam_status
4721 mpt_abort_target_ccb(struct mpt_softc *mpt, union ccb *ccb)
4722 {
4723         struct mpt_hdr_stailq *lp;
4724         struct ccb_hdr *srch;
4725         int found = 0;
4726         union ccb *accb = ccb->cab.abort_ccb;
4727         tgt_resource_t *trtp;
4728
4729         mpt_lprt(mpt, MPT_PRT_DEBUG, "aborting ccb %p\n", accb);
4730
4731         if (ccb->ccb_h.target_lun == CAM_LUN_WILDCARD) {
4732                 trtp = &mpt->trt_wildcard;
4733         } else {
4734                 trtp = &mpt->trt[ccb->ccb_h.target_lun];
4735         }
4736
4737         if (accb->ccb_h.func_code == XPT_ACCEPT_TARGET_IO) {
4738                 lp = &trtp->atios;
4739         } else if (accb->ccb_h.func_code == XPT_IMMED_NOTIFY) {
4740                 lp = &trtp->inots;
4741         } else {
4742                 return (CAM_REQ_INVALID);
4743         }
4744
4745         STAILQ_FOREACH(srch, lp, sim_links.stqe) {
4746                 if (srch == &accb->ccb_h) {
4747                         found = 1;
4748                         STAILQ_REMOVE(lp, srch, ccb_hdr, sim_links.stqe);
4749                         break;
4750                 }
4751         }
4752         if (found) {
4753                 accb->ccb_h.status = CAM_REQ_ABORTED;
4754                 xpt_done(accb);
4755                 return (CAM_REQ_CMP);
4756         }
4757         mpt_prt(mpt, "mpt_abort_tgt_ccb: CCB %p not found\n", ccb);
4758         return (CAM_PATH_INVALID);
4759 }
4760
4761 /*
4762  * Ask the MPT to abort the current target command
4763  */ 
4764 static int
4765 mpt_abort_target_cmd(struct mpt_softc *mpt, request_t *cmd_req)
4766 {
4767         int error;
4768         request_t *req;
4769         PTR_MSG_TARGET_MODE_ABORT abtp;
4770
4771         req = mpt_get_request(mpt, FALSE);
4772         if (req == NULL) {
4773                 return (-1);
4774         }
4775         abtp = req->req_vbuf;
4776         memset(abtp, 0, sizeof (*abtp));
4777
4778         abtp->MsgContext = htole32(req->index | mpt->scsi_tgt_handler_id);
4779         abtp->AbortType = TARGET_MODE_ABORT_TYPE_EXACT_IO;
4780         abtp->Function = MPI_FUNCTION_TARGET_MODE_ABORT;
4781         abtp->ReplyWord = htole32(MPT_TGT_STATE(mpt, cmd_req)->reply_desc);
4782         error = 0;
4783         if (mpt->is_fc || mpt->is_sas) {
4784                 mpt_send_cmd(mpt, req);
4785         } else {
4786                 error = mpt_send_handshake_cmd(mpt, sizeof(*req), req);
4787         }
4788         return (error);
4789 }
4790
4791 /*
4792  * WE_TRUST_AUTO_GOOD_STATUS- I've found that setting 
4793  * TARGET_STATUS_SEND_FLAGS_AUTO_GOOD_STATUS leads the
4794  * FC929 to set bogus FC_RSP fields (nonzero residuals
4795  * but w/o RESID fields set). This causes QLogic initiators
4796  * to think maybe that a frame was lost.
4797  *
4798  * WE_CAN_USE_AUTO_REPOST- we can't use AUTO_REPOST because
4799  * we use allocated requests to do TARGET_ASSIST and we
4800  * need to know when to release them.
4801  */
4802
4803 static void
4804 mpt_scsi_tgt_status(struct mpt_softc *mpt, union ccb *ccb, request_t *cmd_req,
4805     uint8_t status, uint8_t const *sense_data)
4806 {
4807         uint8_t *cmd_vbuf;
4808         mpt_tgt_state_t *tgt;
4809         PTR_MSG_TARGET_STATUS_SEND_REQUEST tp;
4810         request_t *req;
4811         bus_addr_t paddr;
4812         int resplen = 0;
4813         uint32_t fl;
4814
4815         cmd_vbuf = cmd_req->req_vbuf;
4816         cmd_vbuf += MPT_RQSL(mpt);
4817         tgt = MPT_TGT_STATE(mpt, cmd_req);
4818
4819         if ((req = mpt_get_request(mpt, FALSE)) == NULL) {
4820                 if (mpt->outofbeer == 0) {
4821                         mpt->outofbeer = 1;
4822                         xpt_freeze_simq(mpt->sim, 1);
4823                         mpt_lprt(mpt, MPT_PRT_DEBUG, "FREEZEQ\n");
4824                 }
4825                 if (ccb) {
4826                         ccb->ccb_h.status &= ~CAM_SIM_QUEUED;
4827                         mpt_set_ccb_status(ccb, CAM_REQUEUE_REQ);
4828                         MPTLOCK_2_CAMLOCK(mpt);
4829                         xpt_done(ccb);
4830                         CAMLOCK_2_MPTLOCK(mpt);
4831                 } else {
4832                         mpt_prt(mpt,
4833                             "could not allocate status request- dropping\n");
4834                 }
4835                 return;
4836         }
4837         req->ccb = ccb;
4838         if (ccb) {
4839                 ccb->ccb_h.ccb_mpt_ptr = mpt;
4840                 ccb->ccb_h.ccb_req_ptr = req;
4841         }
4842
4843         /*
4844          * Record the currently active ccb, if any, and the
4845          * request for it in our target state area.
4846          */
4847         tgt->ccb = ccb;
4848         tgt->req = req;
4849         tgt->state = TGT_STATE_SENDING_STATUS;
4850
4851         tp = req->req_vbuf;
4852         paddr = req->req_pbuf;
4853         paddr += MPT_RQSL(mpt);
4854
4855         memset(tp, 0, sizeof (*tp));
4856         tp->Function = MPI_FUNCTION_TARGET_STATUS_SEND;
4857         if (mpt->is_fc) {
4858                 PTR_MPI_TARGET_FCP_CMD_BUFFER fc =
4859                     (PTR_MPI_TARGET_FCP_CMD_BUFFER) cmd_vbuf;
4860                 uint8_t *sts_vbuf;
4861                 uint32_t *rsp;
4862
4863                 sts_vbuf = req->req_vbuf;
4864                 sts_vbuf += MPT_RQSL(mpt);
4865                 rsp = (uint32_t *) sts_vbuf;
4866                 memcpy(tp->LUN, fc->FcpLun, sizeof (tp->LUN));
4867
4868                 /*
4869                  * The MPI_TARGET_FCP_RSP_BUFFER define is unfortunate.
4870                  * It has to be big-endian in memory and is organized
4871                  * in 32 bit words, which are much easier to deal with
4872                  * as words which are swizzled as needed.
4873                  *
4874                  * All we're filling here is the FC_RSP payload.
4875                  * We may just have the chip synthesize it if
4876                  * we have no residual and an OK status.
4877                  *
4878                  */
4879                 memset(rsp, 0, sizeof (MPI_TARGET_FCP_RSP_BUFFER));
4880
4881                 rsp[2] = status;
4882                 if (tgt->resid) {
4883                         rsp[2] |= 0x800;        /* XXXX NEED MNEMONIC!!!! */
4884                         rsp[3] = htobe32(tgt->resid);
4885 #ifdef  WE_TRUST_AUTO_GOOD_STATUS
4886                         resplen = sizeof (MPI_TARGET_FCP_RSP_BUFFER);
4887 #endif
4888                 }
4889                 if (status == SCSI_STATUS_CHECK_COND) {
4890                         int i;
4891
4892                         rsp[2] |= 0x200;        /* XXXX NEED MNEMONIC!!!! */
4893                         rsp[4] = htobe32(MPT_SENSE_SIZE);
4894                         if (sense_data) {
4895                                 memcpy(&rsp[8], sense_data, MPT_SENSE_SIZE);
4896                         } else {
4897                                 mpt_prt(mpt, "mpt_scsi_tgt_status: CHECK CONDI"
4898                                     "TION but no sense data?\n");
4899                                 memset(&rsp, 0, MPT_SENSE_SIZE);
4900                         }
4901                         for (i = 8; i < (8 + (MPT_SENSE_SIZE >> 2)); i++) {
4902                                 rsp[i] = htobe32(rsp[i]);
4903                         }
4904 #ifdef  WE_TRUST_AUTO_GOOD_STATUS
4905                         resplen = sizeof (MPI_TARGET_FCP_RSP_BUFFER);
4906 #endif
4907                 }
4908 #ifndef WE_TRUST_AUTO_GOOD_STATUS
4909                 resplen = sizeof (MPI_TARGET_FCP_RSP_BUFFER);
4910 #endif
4911                 rsp[2] = htobe32(rsp[2]);
4912         } else if (mpt->is_sas) {
4913                 PTR_MPI_TARGET_SSP_CMD_BUFFER ssp =
4914                     (PTR_MPI_TARGET_SSP_CMD_BUFFER) cmd_vbuf;
4915                 memcpy(tp->LUN, ssp->LogicalUnitNumber, sizeof (tp->LUN));
4916         } else {
4917                 PTR_MPI_TARGET_SCSI_SPI_CMD_BUFFER sp =
4918                     (PTR_MPI_TARGET_SCSI_SPI_CMD_BUFFER) cmd_vbuf;
4919                 tp->StatusCode = status;
4920                 tp->QueueTag = htole16(sp->Tag);
4921                 memcpy(tp->LUN, sp->LogicalUnitNumber, sizeof (tp->LUN));
4922         }
4923
4924         tp->ReplyWord = htole32(tgt->reply_desc);
4925         tp->MsgContext = htole32(req->index | mpt->scsi_tgt_handler_id);
4926
4927 #ifdef  WE_CAN_USE_AUTO_REPOST
4928         tp->MsgFlags = TARGET_STATUS_SEND_FLAGS_REPOST_CMD_BUFFER;
4929 #endif
4930         if (status == SCSI_STATUS_OK && resplen == 0) {
4931                 tp->MsgFlags |= TARGET_STATUS_SEND_FLAGS_AUTO_GOOD_STATUS;
4932         } else {
4933                 tp->StatusDataSGE.u.Address32 = htole32((uint32_t) paddr);
4934                 fl =
4935                         MPI_SGE_FLAGS_HOST_TO_IOC       |
4936                         MPI_SGE_FLAGS_SIMPLE_ELEMENT    |
4937                         MPI_SGE_FLAGS_LAST_ELEMENT      |
4938                         MPI_SGE_FLAGS_END_OF_LIST       |
4939                         MPI_SGE_FLAGS_END_OF_BUFFER;
4940                 fl <<= MPI_SGE_FLAGS_SHIFT;
4941                 fl |= resplen;
4942                 tp->StatusDataSGE.FlagsLength = htole32(fl);
4943         }
4944
4945         mpt_lprt(mpt, MPT_PRT_DEBUG, 
4946             "STATUS_CCB %p (wit%s sense) tag %x req %p:%u resid %u\n",
4947             ccb, sense_data?"h" : "hout", ccb? ccb->csio.tag_id : -1, req,
4948             req->serno, tgt->resid);
4949         if (ccb) {
4950                 ccb->ccb_h.status = CAM_SIM_QUEUED | CAM_REQ_INPROG;
4951                 mpt_req_timeout(req, 60 * hz, mpt_timeout, ccb);
4952         }
4953         mpt_send_cmd(mpt, req);
4954 }
4955
4956 static void
4957 mpt_scsi_tgt_tsk_mgmt(struct mpt_softc *mpt, request_t *req, mpt_task_mgmt_t fc,
4958     tgt_resource_t *trtp, int init_id)
4959 {
4960         struct ccb_immed_notify *inot;
4961         mpt_tgt_state_t *tgt;
4962
4963         tgt = MPT_TGT_STATE(mpt, req);
4964         inot = (struct ccb_immed_notify *) STAILQ_FIRST(&trtp->inots);
4965         if (inot == NULL) {
4966                 mpt_lprt(mpt, MPT_PRT_WARN, "no INOTSs- sending back BSY\n");
4967                 mpt_scsi_tgt_status(mpt, NULL, req, SCSI_STATUS_BUSY, NULL);
4968                 return;
4969         }
4970         STAILQ_REMOVE_HEAD(&trtp->inots, sim_links.stqe);
4971         mpt_lprt(mpt, MPT_PRT_DEBUG1,
4972             "Get FREE INOT %p lun %d\n", inot, inot->ccb_h.target_lun);
4973
4974         memset(&inot->sense_data, 0, sizeof (inot->sense_data));
4975         inot->sense_len = 0;
4976         memset(inot->message_args, 0, sizeof (inot->message_args));
4977         inot->initiator_id = init_id;   /* XXX */
4978
4979         /*
4980          * This is a somewhat grotesque attempt to map from task management
4981          * to old style SCSI messages. God help us all.
4982          */
4983         switch (fc) {
4984         case MPT_ABORT_TASK_SET:
4985                 inot->message_args[0] = MSG_ABORT_TAG;
4986                 break;
4987         case MPT_CLEAR_TASK_SET:
4988                 inot->message_args[0] = MSG_CLEAR_TASK_SET;
4989                 break;
4990         case MPT_TARGET_RESET:
4991                 inot->message_args[0] = MSG_TARGET_RESET;
4992                 break;
4993         case MPT_CLEAR_ACA:
4994                 inot->message_args[0] = MSG_CLEAR_ACA;
4995                 break;
4996         case MPT_TERMINATE_TASK:
4997                 inot->message_args[0] = MSG_ABORT_TAG;
4998                 break;
4999         default:
5000                 inot->message_args[0] = MSG_NOOP;
5001                 break;
5002         }
5003         tgt->ccb = (union ccb *) inot;
5004         inot->ccb_h.status = CAM_MESSAGE_RECV|CAM_DEV_QFRZN;
5005         MPTLOCK_2_CAMLOCK(mpt);
5006         xpt_done((union ccb *)inot);
5007         CAMLOCK_2_MPTLOCK(mpt);
5008 }
5009
5010 static void
5011 mpt_scsi_tgt_atio(struct mpt_softc *mpt, request_t *req, uint32_t reply_desc)
5012 {
5013         static uint8_t null_iqd[SHORT_INQUIRY_LENGTH] = {
5014             0x7f, 0x00, 0x02, 0x02, 0x20, 0x00, 0x00, 0x32,
5015              'F',  'R',  'E',  'E',  'B',  'S',  'D',  ' ',
5016              'L',  'S',  'I',  '-',  'L',  'O',  'G',  'I',
5017              'C',  ' ',  'N',  'U',  'L',  'D',  'E',  'V',
5018              '0',  '0',  '0',  '1'
5019         };
5020         struct ccb_accept_tio *atiop;
5021         lun_id_t lun;
5022         int tag_action = 0;
5023         mpt_tgt_state_t *tgt;
5024         tgt_resource_t *trtp = NULL;
5025         U8 *lunptr;
5026         U8 *vbuf;
5027         U16 itag;
5028         U16 ioindex;
5029         mpt_task_mgmt_t fct = MPT_NIL_TMT_VALUE;
5030         uint8_t *cdbp;
5031
5032         /*
5033          * First, DMA sync the received command-
5034          * which is in the *request* * phys area.
5035          *
5036          * XXX: We could optimize this for a range
5037          */
5038         bus_dmamap_sync(mpt->request_dmat, mpt->request_dmap,
5039             BUS_DMASYNC_POSTREAD);
5040
5041         /*
5042          * Stash info for the current command where we can get at it later.
5043          */
5044         vbuf = req->req_vbuf;
5045         vbuf += MPT_RQSL(mpt);
5046
5047         /*
5048          * Get our state pointer set up.
5049          */
5050         tgt = MPT_TGT_STATE(mpt, req);
5051         if (tgt->state != TGT_STATE_LOADED) {
5052                 mpt_tgt_dump_req_state(mpt, req);
5053                 panic("bad target state in mpt_scsi_tgt_atio");
5054         }
5055         memset(tgt, 0, sizeof (mpt_tgt_state_t));
5056         tgt->state = TGT_STATE_IN_CAM;
5057         tgt->reply_desc = reply_desc;
5058         ioindex = GET_IO_INDEX(reply_desc);
5059         if (mpt->verbose >= MPT_PRT_DEBUG) {
5060                 mpt_dump_data(mpt, "mpt_scsi_tgt_atio response", vbuf,
5061                     max(sizeof (MPI_TARGET_FCP_CMD_BUFFER),
5062                     max(sizeof (MPI_TARGET_SSP_CMD_BUFFER),
5063                     sizeof (MPI_TARGET_SCSI_SPI_CMD_BUFFER))));
5064         }
5065         if (mpt->is_fc) {
5066                 PTR_MPI_TARGET_FCP_CMD_BUFFER fc;
5067                 fc = (PTR_MPI_TARGET_FCP_CMD_BUFFER) vbuf;
5068                 if (fc->FcpCntl[2]) {
5069                         /*
5070                          * Task Management Request
5071                          */
5072                         switch (fc->FcpCntl[2]) {
5073                         case 0x2:
5074                                 fct = MPT_ABORT_TASK_SET;
5075                                 break;
5076                         case 0x4:
5077                                 fct = MPT_CLEAR_TASK_SET;
5078                                 break;
5079                         case 0x20:
5080                                 fct = MPT_TARGET_RESET;
5081                                 break;
5082                         case 0x40:
5083                                 fct = MPT_CLEAR_ACA;
5084                                 break;
5085                         case 0x80:
5086                                 fct = MPT_TERMINATE_TASK;
5087                                 break;
5088                         default:
5089                                 mpt_prt(mpt, "CORRUPTED TASK MGMT BITS: 0x%x\n",
5090                                     fc->FcpCntl[2]);
5091                                 mpt_scsi_tgt_status(mpt, 0, req,
5092                                     SCSI_STATUS_OK, 0);
5093                                 return;
5094                         }
5095                 } else {
5096                         switch (fc->FcpCntl[1]) {
5097                         case 0:
5098                                 tag_action = MSG_SIMPLE_Q_TAG;
5099                                 break;
5100                         case 1:
5101                                 tag_action = MSG_HEAD_OF_Q_TAG;
5102                                 break;
5103                         case 2:
5104                                 tag_action = MSG_ORDERED_Q_TAG;
5105                                 break;
5106                         default:
5107                                 /*
5108                                  * Bah. Ignore Untagged Queing and ACA
5109                                  */
5110                                 tag_action = MSG_SIMPLE_Q_TAG;
5111                                 break;
5112                         }
5113                 }
5114                 tgt->resid = be32toh(fc->FcpDl);
5115                 cdbp = fc->FcpCdb;
5116                 lunptr = fc->FcpLun;
5117                 itag = be16toh(fc->OptionalOxid);
5118         } else if (mpt->is_sas) {
5119                 PTR_MPI_TARGET_SSP_CMD_BUFFER ssp;
5120                 ssp = (PTR_MPI_TARGET_SSP_CMD_BUFFER) vbuf;
5121                 cdbp = ssp->CDB;
5122                 lunptr = ssp->LogicalUnitNumber;
5123                 itag = ssp->InitiatorTag;
5124         } else {
5125                 PTR_MPI_TARGET_SCSI_SPI_CMD_BUFFER sp;
5126                 sp = (PTR_MPI_TARGET_SCSI_SPI_CMD_BUFFER) vbuf;
5127                 cdbp = sp->CDB;
5128                 lunptr = sp->LogicalUnitNumber;
5129                 itag = sp->Tag;
5130         }
5131
5132         /*
5133          * Generate a simple lun
5134          */
5135         switch (lunptr[0] & 0xc0) {
5136         case 0x40:
5137                 lun = ((lunptr[0] & 0x3f) << 8) | lunptr[1];
5138                 break;
5139         case 0:
5140                 lun = lunptr[1];
5141                 break;
5142         default:
5143                 mpt_lprt(mpt, MPT_PRT_ERROR, "cannot handle this type lun\n");
5144                 lun = 0xffff;
5145                 break;
5146         }
5147
5148         /*
5149          * Deal with non-enabled or bad luns here.
5150          */
5151         if (lun >= MPT_MAX_LUNS || mpt->tenabled == 0 ||
5152             mpt->trt[lun].enabled == 0) {
5153                 if (mpt->twildcard) {
5154                         trtp = &mpt->trt_wildcard;
5155                 } else if (fct == MPT_NIL_TMT_VALUE) {
5156                         /*
5157                          * In this case, we haven't got an upstream listener
5158                          * for either a specific lun or wildcard luns. We
5159                          * have to make some sensible response. For regular
5160                          * inquiry, just return some NOT HERE inquiry data.
5161                          * For VPD inquiry, report illegal field in cdb.
5162                          * For REQUEST SENSE, just return NO SENSE data.
5163                          * REPORT LUNS gets illegal command.
5164                          * All other commands get 'no such device'.
5165                          */
5166                         uint8_t *sp, cond, buf[MPT_SENSE_SIZE];
5167                         size_t len;
5168
5169                         memset(buf, 0, MPT_SENSE_SIZE);
5170                         cond = SCSI_STATUS_CHECK_COND;
5171                         buf[0] = 0xf0;
5172                         buf[2] = 0x5;
5173                         buf[7] = 0x8;
5174                         sp = buf;
5175                         tgt->tag_id = MPT_MAKE_TAGID(mpt, req, ioindex);
5176
5177                         switch (cdbp[0]) {
5178                         case INQUIRY:
5179                         {
5180                                 if (cdbp[1] != 0) {
5181                                         buf[12] = 0x26;
5182                                         buf[13] = 0x01;
5183                                         break;
5184                                 }
5185                                 len = min(tgt->resid, cdbp[4]);
5186                                 len = min(len, sizeof (null_iqd));
5187                                 mpt_lprt(mpt, MPT_PRT_DEBUG,
5188                                     "local inquiry %ld bytes\n", (long) len);
5189                                 mpt_scsi_tgt_local(mpt, req, lun, 1,
5190                                     null_iqd, len);
5191                                 return;
5192                         }
5193                         case REQUEST_SENSE:
5194                         {
5195                                 buf[2] = 0x0;
5196                                 len = min(tgt->resid, cdbp[4]);
5197                                 len = min(len, sizeof (buf));
5198                                 mpt_lprt(mpt, MPT_PRT_DEBUG,
5199                                     "local reqsense %ld bytes\n", (long) len);
5200                                 mpt_scsi_tgt_local(mpt, req, lun, 1,
5201                                     buf, len);
5202                                 return;
5203                         }
5204                         case REPORT_LUNS:
5205                                 mpt_lprt(mpt, MPT_PRT_DEBUG, "REPORT LUNS\n");
5206                                 buf[12] = 0x26;
5207                                 return;
5208                         default:
5209                                 mpt_lprt(mpt, MPT_PRT_DEBUG,
5210                                     "CMD 0x%x to unmanaged lun %u\n",
5211                                     cdbp[0], lun);
5212                                 buf[12] = 0x25;
5213                                 break;
5214                         }
5215                         mpt_scsi_tgt_status(mpt, NULL, req, cond, sp);
5216                         return;
5217                 }
5218                 /* otherwise, leave trtp NULL */
5219         } else {
5220                 trtp = &mpt->trt[lun];
5221         }
5222
5223         /*
5224          * Deal with any task management
5225          */
5226         if (fct != MPT_NIL_TMT_VALUE) {
5227                 if (trtp == NULL) {
5228                         mpt_prt(mpt, "task mgmt function %x but no listener\n",
5229                             fct);
5230                         mpt_scsi_tgt_status(mpt, 0, req,
5231                             SCSI_STATUS_OK, 0);
5232                 } else {
5233                         mpt_scsi_tgt_tsk_mgmt(mpt, req, fct, trtp,
5234                             GET_INITIATOR_INDEX(reply_desc));
5235                 }
5236                 return;
5237         }
5238
5239
5240         atiop = (struct ccb_accept_tio *) STAILQ_FIRST(&trtp->atios);
5241         if (atiop == NULL) {
5242                 mpt_lprt(mpt, MPT_PRT_WARN,
5243                     "no ATIOs for lun %u- sending back %s\n", lun,
5244                     mpt->tenabled? "QUEUE FULL" : "BUSY");
5245                 mpt_scsi_tgt_status(mpt, NULL, req,
5246                     mpt->tenabled? SCSI_STATUS_QUEUE_FULL : SCSI_STATUS_BUSY,
5247                     NULL);
5248                 return;
5249         }
5250         STAILQ_REMOVE_HEAD(&trtp->atios, sim_links.stqe);
5251         mpt_lprt(mpt, MPT_PRT_DEBUG1,
5252             "Get FREE ATIO %p lun %d\n", atiop, atiop->ccb_h.target_lun);
5253         atiop->ccb_h.ccb_mpt_ptr = mpt;
5254         atiop->ccb_h.status = CAM_CDB_RECVD;
5255         atiop->ccb_h.target_lun = lun;
5256         atiop->sense_len = 0;
5257         atiop->init_id = GET_INITIATOR_INDEX(reply_desc);
5258         atiop->cdb_len = mpt_cdblen(cdbp[0], 16);
5259         memcpy(atiop->cdb_io.cdb_bytes, cdbp, atiop->cdb_len);
5260
5261         /*
5262          * The tag we construct here allows us to find the
5263          * original request that the command came in with.
5264          *
5265          * This way we don't have to depend on anything but the
5266          * tag to find things when CCBs show back up from CAM.
5267          */
5268         atiop->tag_id = MPT_MAKE_TAGID(mpt, req, ioindex);
5269         tgt->tag_id = atiop->tag_id;
5270         if (tag_action) {
5271                 atiop->tag_action = tag_action;
5272                 atiop->ccb_h.flags = CAM_TAG_ACTION_VALID;
5273         }
5274         if (mpt->verbose >= MPT_PRT_DEBUG) {
5275                 int i;
5276                 mpt_prt(mpt, "START_CCB %p for lun %u CDB=<", atiop,
5277                     atiop->ccb_h.target_lun);
5278                 for (i = 0; i < atiop->cdb_len; i++) {
5279                         mpt_prtc(mpt, "%02x%c", cdbp[i] & 0xff,
5280                             (i == (atiop->cdb_len - 1))? '>' : ' ');
5281                 }
5282                 mpt_prtc(mpt, " itag %x tag %x rdesc %x dl=%u\n",
5283                     itag, atiop->tag_id, tgt->reply_desc, tgt->resid);
5284         }
5285         
5286         MPTLOCK_2_CAMLOCK(mpt);
5287         xpt_done((union ccb *)atiop);
5288         CAMLOCK_2_MPTLOCK(mpt);
5289 }
5290
5291 static void
5292 mpt_tgt_dump_tgt_state(struct mpt_softc *mpt, request_t *req)
5293 {
5294         mpt_tgt_state_t *tgt = MPT_TGT_STATE(mpt, req);
5295
5296         mpt_prt(mpt, "req %p:%u tgt:rdesc 0x%x resid %u xfrd %u ccb %p treq %p "
5297             "nx %d tag 0x%08x state=%d\n", req, req->serno, tgt->reply_desc,
5298             tgt->resid, tgt->bytes_xfered, tgt->ccb, tgt->req, tgt->nxfers,
5299             tgt->tag_id, tgt->state);
5300 }
5301
5302 static void
5303 mpt_tgt_dump_req_state(struct mpt_softc *mpt, request_t *req)
5304 {
5305         mpt_prt(mpt, "req %p:%u index %u (%x) state %x\n", req, req->serno,
5306             req->index, req->index, req->state);
5307         mpt_tgt_dump_tgt_state(mpt, req);
5308 }
5309
5310 static int
5311 mpt_scsi_tgt_reply_handler(struct mpt_softc *mpt, request_t *req,
5312     uint32_t reply_desc, MSG_DEFAULT_REPLY *reply_frame)
5313 {
5314         int dbg;
5315         union ccb *ccb;
5316         U16 status;
5317
5318         if (reply_frame == NULL) {
5319                 /*
5320                  * Figure out what the state of the command is.
5321                  */
5322                 mpt_tgt_state_t *tgt = MPT_TGT_STATE(mpt, req);
5323
5324 #ifdef  INVARIANTS
5325                 mpt_req_spcl(mpt, req, "turbo scsi_tgt_reply", __LINE__);
5326                 if (tgt->req) {
5327                         mpt_req_not_spcl(mpt, tgt->req,
5328                             "turbo scsi_tgt_reply associated req", __LINE__);
5329                 }
5330 #endif
5331                 switch(tgt->state) {
5332                 case TGT_STATE_LOADED:
5333                         /*
5334                          * This is a new command starting.
5335                          */
5336                         mpt_scsi_tgt_atio(mpt, req, reply_desc);
5337                         break;
5338                 case TGT_STATE_MOVING_DATA:
5339                 {
5340                         uint8_t *sp = NULL, sense[MPT_SENSE_SIZE];
5341
5342                         ccb = tgt->ccb;
5343                         if (tgt->req == NULL) {
5344                                 panic("mpt: turbo target reply with null "
5345                                     "associated request moving data");
5346                                 /* NOTREACHED */
5347                         }
5348                         if (ccb == NULL) {
5349                                 if (tgt->is_local == 0) {
5350                                         panic("mpt: turbo target reply with "
5351                                             "null associated ccb moving data");
5352                                         /* NOTREACHED */
5353                                 }
5354                                 mpt_lprt(mpt, MPT_PRT_DEBUG,
5355                                     "TARGET_ASSIST local done\n");
5356                                 TAILQ_REMOVE(&mpt->request_pending_list,
5357                                     tgt->req, links);
5358                                 mpt_free_request(mpt, tgt->req);
5359                                 tgt->req = NULL;
5360                                 mpt_scsi_tgt_status(mpt, NULL, req,
5361                                     0, NULL);
5362                                 return (TRUE);
5363                         }
5364                         tgt->ccb = NULL;
5365                         tgt->nxfers++;
5366                         mpt_req_untimeout(req, mpt_timeout, ccb);
5367                         mpt_lprt(mpt, MPT_PRT_DEBUG,
5368                             "TARGET_ASSIST %p (req %p:%u) done tag 0x%x\n",
5369                             ccb, tgt->req, tgt->req->serno, ccb->csio.tag_id);
5370                         /*
5371                          * Free the Target Assist Request
5372                          */
5373                         KASSERT(tgt->req->ccb == ccb,
5374                             ("tgt->req %p:%u tgt->req->ccb %p", tgt->req,
5375                             tgt->req->serno, tgt->req->ccb));
5376                         TAILQ_REMOVE(&mpt->request_pending_list,
5377                             tgt->req, links);
5378                         mpt_free_request(mpt, tgt->req);
5379                         tgt->req = NULL;
5380
5381                         /*
5382                          * Do we need to send status now? That is, are
5383                          * we done with all our data transfers?
5384                          */
5385                         if ((ccb->ccb_h.flags & CAM_SEND_STATUS) == 0) {
5386                                 mpt_set_ccb_status(ccb, CAM_REQ_CMP);
5387                                 ccb->ccb_h.status &= ~CAM_SIM_QUEUED;
5388                                 KASSERT(ccb->ccb_h.status,
5389                                     ("zero ccb sts at %d\n", __LINE__));
5390                                 tgt->state = TGT_STATE_IN_CAM;
5391                                 if (mpt->outofbeer) {
5392                                         ccb->ccb_h.status |= CAM_RELEASE_SIMQ;
5393                                         mpt->outofbeer = 0;
5394                                         mpt_lprt(mpt, MPT_PRT_DEBUG, "THAWQ\n");
5395                                 }
5396                                 MPTLOCK_2_CAMLOCK(mpt);
5397                                 xpt_done(ccb);
5398                                 CAMLOCK_2_MPTLOCK(mpt);
5399                                 break;
5400                         }
5401                         /*
5402                          * Otherwise, send status (and sense)
5403                          */
5404                         if (ccb->ccb_h.flags & CAM_SEND_SENSE) {
5405                                 sp = sense;
5406                                 memcpy(sp, &ccb->csio.sense_data,
5407                                    min(ccb->csio.sense_len, MPT_SENSE_SIZE));
5408                         }
5409                         mpt_scsi_tgt_status(mpt, ccb, req,
5410                             ccb->csio.scsi_status, sp);
5411                         break;
5412                 }
5413                 case TGT_STATE_SENDING_STATUS:
5414                 case TGT_STATE_MOVING_DATA_AND_STATUS:
5415                 {
5416                         int ioindex;
5417                         ccb = tgt->ccb;
5418
5419                         if (tgt->req == NULL) {
5420                                 panic("mpt: turbo target reply with null "
5421                                     "associated request sending status");
5422                                 /* NOTREACHED */
5423                         }
5424
5425                         if (ccb) {
5426                                 tgt->ccb = NULL;
5427                                 if (tgt->state ==
5428                                     TGT_STATE_MOVING_DATA_AND_STATUS) {
5429                                         tgt->nxfers++;
5430                                 }
5431                                 mpt_req_untimeout(req, mpt_timeout, ccb);
5432                                 if (ccb->ccb_h.flags & CAM_SEND_SENSE) {
5433                                         ccb->ccb_h.status |= CAM_SENT_SENSE;
5434                                 }
5435                                 mpt_lprt(mpt, MPT_PRT_DEBUG,
5436                                     "TARGET_STATUS tag %x sts %x flgs %x req "
5437                                     "%p\n", ccb->csio.tag_id, ccb->ccb_h.status,
5438                                     ccb->ccb_h.flags, tgt->req);
5439                                 /*
5440                                  * Free the Target Send Status Request
5441                                  */
5442                                 KASSERT(tgt->req->ccb == ccb,
5443                                     ("tgt->req %p:%u tgt->req->ccb %p",
5444                                     tgt->req, tgt->req->serno, tgt->req->ccb));
5445                                 /*
5446                                  * Notify CAM that we're done
5447                                  */
5448                                 mpt_set_ccb_status(ccb, CAM_REQ_CMP);
5449                                 ccb->ccb_h.status &= ~CAM_SIM_QUEUED;
5450                                 KASSERT(ccb->ccb_h.status,
5451                                     ("ZERO ccb sts at %d\n", __LINE__));
5452                                 tgt->ccb = NULL;
5453                         } else {
5454                                 mpt_lprt(mpt, MPT_PRT_DEBUG,
5455                                     "TARGET_STATUS non-CAM for  req %p:%u\n",
5456                                     tgt->req, tgt->req->serno);
5457                         }
5458                         TAILQ_REMOVE(&mpt->request_pending_list,
5459                             tgt->req, links);
5460                         mpt_free_request(mpt, tgt->req);
5461                         tgt->req = NULL;
5462
5463                         /*
5464                          * And re-post the Command Buffer.
5465                          * This will reset the state.
5466                          */
5467                         ioindex = GET_IO_INDEX(reply_desc);
5468                         TAILQ_REMOVE(&mpt->request_pending_list, req, links);
5469                         tgt->is_local = 0;
5470                         mpt_post_target_command(mpt, req, ioindex);
5471
5472                         /*
5473                          * And post a done for anyone who cares
5474                          */
5475                         if (ccb) {
5476                                 if (mpt->outofbeer) {
5477                                         ccb->ccb_h.status |= CAM_RELEASE_SIMQ;
5478                                         mpt->outofbeer = 0;
5479                                         mpt_lprt(mpt, MPT_PRT_DEBUG, "THAWQ\n");
5480                                 }
5481                                 MPTLOCK_2_CAMLOCK(mpt);
5482                                 xpt_done(ccb);
5483                                 CAMLOCK_2_MPTLOCK(mpt);
5484                         }
5485                         break;
5486                 }
5487                 case TGT_STATE_NIL:     /* XXX This Never Happens XXX */
5488                         tgt->state = TGT_STATE_LOADED;
5489                         break;
5490                 default:
5491                         mpt_prt(mpt, "Unknown Target State 0x%x in Context "
5492                             "Reply Function\n", tgt->state);
5493                 }
5494                 return (TRUE);
5495         }
5496
5497         status = le16toh(reply_frame->IOCStatus);
5498         if (status != MPI_IOCSTATUS_SUCCESS) {
5499                 dbg = MPT_PRT_ERROR;
5500         } else {
5501                 dbg = MPT_PRT_DEBUG1;
5502         }
5503
5504         mpt_lprt(mpt, dbg,
5505             "SCSI_TGT REPLY: req=%p:%u reply=%p func=%x IOCstatus 0x%x\n",
5506              req, req->serno, reply_frame, reply_frame->Function, status);
5507
5508         switch (reply_frame->Function) {
5509         case MPI_FUNCTION_TARGET_CMD_BUFFER_POST:
5510         {
5511                 mpt_tgt_state_t *tgt;
5512 #ifdef  INVARIANTS
5513                 mpt_req_spcl(mpt, req, "tgt reply BUFFER POST", __LINE__);
5514 #endif
5515                 if (status != MPI_IOCSTATUS_SUCCESS) {
5516                         /*
5517                          * XXX What to do?
5518                          */
5519                         break;
5520                 }
5521                 tgt = MPT_TGT_STATE(mpt, req);
5522                 KASSERT(tgt->state == TGT_STATE_LOADING,
5523                     ("bad state 0x%x on reply to buffer post\n", tgt->state));
5524                 mpt_assign_serno(mpt, req);
5525                 tgt->state = TGT_STATE_LOADED;
5526                 break;
5527         }
5528         case MPI_FUNCTION_TARGET_ASSIST:
5529 #ifdef  INVARIANTS
5530                 mpt_req_not_spcl(mpt, req, "tgt reply TARGET ASSIST", __LINE__);
5531 #endif
5532                 mpt_prt(mpt, "target assist completion\n");
5533                 TAILQ_REMOVE(&mpt->request_pending_list, req, links);
5534                 mpt_free_request(mpt, req);
5535                 break;
5536         case MPI_FUNCTION_TARGET_STATUS_SEND:
5537 #ifdef  INVARIANTS
5538                 mpt_req_not_spcl(mpt, req, "tgt reply STATUS SEND", __LINE__);
5539 #endif
5540                 mpt_prt(mpt, "status send completion\n");
5541                 TAILQ_REMOVE(&mpt->request_pending_list, req, links);
5542                 mpt_free_request(mpt, req);
5543                 break;
5544         case MPI_FUNCTION_TARGET_MODE_ABORT:
5545         {
5546                 PTR_MSG_TARGET_MODE_ABORT_REPLY abtrp =
5547                     (PTR_MSG_TARGET_MODE_ABORT_REPLY) reply_frame;
5548                 PTR_MSG_TARGET_MODE_ABORT abtp =
5549                     (PTR_MSG_TARGET_MODE_ABORT) req->req_vbuf;
5550                 uint32_t cc = GET_IO_INDEX(le32toh(abtp->ReplyWord));
5551 #ifdef  INVARIANTS
5552                 mpt_req_not_spcl(mpt, req, "tgt reply TMODE ABORT", __LINE__);
5553 #endif
5554                 mpt_prt(mpt, "ABORT RX_ID 0x%x Complete; status 0x%x cnt %u\n",
5555                     cc, le16toh(abtrp->IOCStatus), le32toh(abtrp->AbortCount));
5556                 TAILQ_REMOVE(&mpt->request_pending_list, req, links);
5557                 mpt_free_request(mpt, req);
5558                 break;
5559         }
5560         default:
5561                 mpt_prt(mpt, "Unknown Target Address Reply Function code: "
5562                     "0x%x\n", reply_frame->Function);
5563                 break;
5564         }
5565         return (TRUE);
5566 }