]> CyberLeo.Net >> Repos - FreeBSD/FreeBSD.git/blob - sys/dev/isp/isp_freebsd.c
Update mandoc to cvs snaphot from 20150302
[FreeBSD/FreeBSD.git] / sys / dev / isp / isp_freebsd.c
1 /*-
2  * Copyright (c) 1997-2009 by Matthew Jacob
3  * All rights reserved.
4  *
5  * Redistribution and use in source and binary forms, with or without
6  * modification, are permitted provided that the following conditions
7  * are met:
8  * 1. Redistributions of source code must retain the above copyright
9  *    notice immediately at the beginning of the file, without modification,
10  *    this list of conditions, and the following disclaimer.
11  * 2. The name of the author may not be used to endorse or promote products
12  *    derived from this software without specific prior written permission.
13  *
14  * THIS SOFTWARE IS PROVIDED BY THE AUTHOR AND CONTRIBUTORS ``AS IS'' AND
15  * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
16  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
17  * ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE FOR
18  * ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
19  * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
20  * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
21  * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
22  * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
23  * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
24  * SUCH DAMAGE.
25  */
26
27 /*
28  * Platform (FreeBSD) dependent common attachment code for Qlogic adapters.
29  */
30 #include <sys/cdefs.h>
31 __FBSDID("$FreeBSD$");
32
33 #include <dev/isp/isp_freebsd.h>
34 #include <sys/unistd.h>
35 #include <sys/kthread.h>
36 #include <sys/conf.h>
37 #include <sys/module.h>
38 #include <sys/ioccom.h>
39 #include <dev/isp/isp_ioctl.h>
40 #include <sys/devicestat.h>
41 #include <cam/cam_periph.h>
42 #include <cam/cam_xpt_periph.h>
43
44 #if     __FreeBSD_version < 800002 
45 #define THREAD_CREATE   kthread_create
46 #else
47 #define THREAD_CREATE   kproc_create
48 #endif
49
50 MODULE_VERSION(isp, 1);
51 MODULE_DEPEND(isp, cam, 1, 1, 1);
52 int isp_announced = 0;
53 int isp_fabric_hysteresis = 5;
54 int isp_loop_down_limit = 60;   /* default loop down limit */
55 int isp_change_is_bad = 0;      /* "changed" devices are bad */
56 int isp_quickboot_time = 7;     /* don't wait more than N secs for loop up */
57 int isp_gone_device_time = 30;  /* grace time before reporting device lost */
58 int isp_autoconfig = 1;         /* automatically attach/detach devices */
59 static const char prom3[] = "Chan %d PortID 0x%06x Departed from Target %u because of %s";
60
61 static void isp_freeze_loopdown(ispsoftc_t *, int, char *);
62 static d_ioctl_t ispioctl;
63 static void isp_intr_enable(void *);
64 static void isp_cam_async(void *, uint32_t, struct cam_path *, void *);
65 static void isp_poll(struct cam_sim *);
66 static timeout_t isp_watchdog;
67 static timeout_t isp_gdt;
68 static task_fn_t isp_gdt_task;
69 static timeout_t isp_ldt;
70 static task_fn_t isp_ldt_task;
71 static void isp_kthread(void *);
72 static void isp_action(struct cam_sim *, union ccb *);
73 #ifdef  ISP_INTERNAL_TARGET
74 static void isp_target_thread_pi(void *);
75 static void isp_target_thread_fc(void *);
76 #endif
77 static int isp_timer_count;
78 static void isp_timer(void *);
79
80 static struct cdevsw isp_cdevsw = {
81         .d_version =    D_VERSION,
82         .d_ioctl =      ispioctl,
83         .d_name =       "isp",
84 };
85
86 static int
87 isp_attach_chan(ispsoftc_t *isp, struct cam_devq *devq, int chan)
88 {
89         struct ccb_setasync csa;
90         struct cam_sim *sim;
91         struct cam_path *path;
92
93         /*
94          * Construct our SIM entry.
95          */
96         sim = cam_sim_alloc(isp_action, isp_poll, "isp", isp, device_get_unit(isp->isp_dev), &isp->isp_osinfo.lock, isp->isp_maxcmds, isp->isp_maxcmds, devq);
97
98         if (sim == NULL) {
99                 return (ENOMEM);
100         }
101
102         ISP_LOCK(isp);
103         if (xpt_bus_register(sim, isp->isp_dev, chan) != CAM_SUCCESS) {
104                 ISP_UNLOCK(isp);
105                 cam_sim_free(sim, FALSE);
106                 return (EIO);
107         }
108         ISP_UNLOCK(isp);
109         if (xpt_create_path(&path, NULL, cam_sim_path(sim), CAM_TARGET_WILDCARD, CAM_LUN_WILDCARD) != CAM_REQ_CMP) {
110                 ISP_LOCK(isp);
111                 xpt_bus_deregister(cam_sim_path(sim));
112                 ISP_UNLOCK(isp);
113                 cam_sim_free(sim, FALSE);
114                 return (ENXIO);
115         }
116         xpt_setup_ccb(&csa.ccb_h, path, 5);
117         csa.ccb_h.func_code = XPT_SASYNC_CB;
118         csa.event_enable = AC_LOST_DEVICE;
119         csa.callback = isp_cam_async;
120         csa.callback_arg = sim;
121
122         ISP_LOCK(isp);
123         xpt_action((union ccb *)&csa);
124         ISP_UNLOCK(isp);
125
126         if (IS_SCSI(isp)) {
127                 struct isp_spi *spi = ISP_SPI_PC(isp, chan);
128                 spi->sim = sim;
129                 spi->path = path;
130 #ifdef  ISP_INTERNAL_TARGET
131                 ISP_SET_PC(isp, chan, proc_active, 1);
132                 if (THREAD_CREATE(isp_target_thread_pi, spi, &spi->target_proc, 0, 0, "%s: isp_test_tgt%d", device_get_nameunit(isp->isp_osinfo.dev), chan)) {
133                         ISP_SET_PC(isp, chan, proc_active, 0);
134                         isp_prt(isp, ISP_LOGERR, "cannot create test target thread");
135                 }
136                 ISP_SPI_PC(isp, chan)->num_threads += 1;
137 #endif
138         } else {
139                 fcparam *fcp = FCPARAM(isp, chan);
140                 struct isp_fc *fc = ISP_FC_PC(isp, chan);
141
142                 ISP_LOCK(isp);
143                 fc->sim = sim;
144                 fc->path = path;
145                 fc->isp = isp;
146                 fc->ready = 1;
147
148                 callout_init_mtx(&fc->ldt, &isp->isp_osinfo.lock, 0);
149                 callout_init_mtx(&fc->gdt, &isp->isp_osinfo.lock, 0);
150                 TASK_INIT(&fc->ltask, 1, isp_ldt_task, fc);
151                 TASK_INIT(&fc->gtask, 1, isp_gdt_task, fc);
152
153                 /*
154                  * We start by being "loop down" if we have an initiator role
155                  */
156                 if (fcp->role & ISP_ROLE_INITIATOR) {
157                         isp_freeze_loopdown(isp, chan, "isp_attach");
158                         callout_reset(&fc->ldt, isp_quickboot_time * hz, isp_ldt, fc);
159                         isp_prt(isp, ISP_LOG_SANCFG|ISP_LOGDEBUG0, "Starting Initial Loop Down Timer @ %lu", (unsigned long) time_uptime);
160                 }
161                 ISP_UNLOCK(isp);
162                 if (THREAD_CREATE(isp_kthread, fc, &fc->kproc, 0, 0, "%s: fc_thrd%d", device_get_nameunit(isp->isp_osinfo.dev), chan)) {
163                         xpt_free_path(fc->path);
164                         ISP_LOCK(isp);
165                         if (callout_active(&fc->ldt))
166                                 callout_stop(&fc->ldt);
167                         xpt_bus_deregister(cam_sim_path(fc->sim));
168                         ISP_UNLOCK(isp);
169                         cam_sim_free(fc->sim, FALSE);
170                         return (ENOMEM);
171                 }
172                 ISP_FC_PC(isp, chan)->num_threads += 1;
173 #ifdef  ISP_INTERNAL_TARGET
174                 ISP_SET_PC(isp, chan, proc_active, 1);
175                 if (THREAD_CREATE(isp_target_thread_fc, fc, &fc->target_proc, 0, 0, "%s: isp_test_tgt%d", device_get_nameunit(isp->isp_osinfo.dev), chan)) {
176                         ISP_SET_PC(isp, chan, proc_active, 0);
177                         isp_prt(isp, ISP_LOGERR, "cannot create test target thread");
178                 }
179                 ISP_FC_PC(isp, chan)->num_threads += 1;
180 #endif
181                 if (chan == 0) {
182                         struct sysctl_ctx_list *ctx = device_get_sysctl_ctx(isp->isp_osinfo.dev);
183                         struct sysctl_oid *tree = device_get_sysctl_tree(isp->isp_osinfo.dev);
184                         SYSCTL_ADD_QUAD(ctx, SYSCTL_CHILDREN(tree), OID_AUTO, "wwnn", CTLFLAG_RD, &FCPARAM(isp, 0)->isp_wwnn, "World Wide Node Name");
185                         SYSCTL_ADD_QUAD(ctx, SYSCTL_CHILDREN(tree), OID_AUTO, "wwpn", CTLFLAG_RD, &FCPARAM(isp, 0)->isp_wwpn, "World Wide Port Name");
186                         SYSCTL_ADD_UINT(ctx, SYSCTL_CHILDREN(tree), OID_AUTO, "loop_down_limit", CTLFLAG_RW, &ISP_FC_PC(isp, 0)->loop_down_limit, 0, "Loop Down Limit");
187                         SYSCTL_ADD_UINT(ctx, SYSCTL_CHILDREN(tree), OID_AUTO, "gone_device_time", CTLFLAG_RW, &ISP_FC_PC(isp, 0)->gone_device_time, 0, "Gone Device Time");
188 #if defined(ISP_TARGET_MODE) && defined(DEBUG)
189                         SYSCTL_ADD_UINT(ctx, SYSCTL_CHILDREN(tree), OID_AUTO, "inject_lost_data_frame", CTLFLAG_RW, &ISP_FC_PC(isp, 0)->inject_lost_data_frame, 0, "Cause a Lost Frame on a Read");
190 #endif
191                 }
192         }
193         return (0);
194 }
195
196 static void
197 isp_detach_internal_target(ispsoftc_t *isp, int chan)
198 {
199 #ifdef ISP_INTERNAL_TARGET
200         void *wchan;
201
202         ISP_GET_PC(isp, chan, target_proc, wchan);
203         ISP_SET_PC(isp, chan, proc_active, 0);
204         wakeup(wchan);
205 #endif
206 }
207
208 static void
209 isp_detach_chan(ispsoftc_t *isp, int chan)
210 {
211         struct cam_sim *sim;
212         struct cam_path *path;
213         struct ccb_setasync csa;
214         int *num_threads;
215
216         ISP_GET_PC(isp, chan, sim, sim);
217         ISP_GET_PC(isp, chan, path, path);
218         ISP_GET_PC_ADDR(isp, chan, num_threads, num_threads);
219
220         xpt_setup_ccb(&csa.ccb_h, path, 5);
221         csa.ccb_h.func_code = XPT_SASYNC_CB;
222         csa.event_enable = 0;
223         csa.callback = isp_cam_async;
224         csa.callback_arg = sim;
225         xpt_action((union ccb *)&csa);
226         xpt_free_path(path);
227         xpt_bus_deregister(cam_sim_path(sim));
228         cam_sim_free(sim, FALSE);
229
230         /* Wait for the channel's spawned threads to exit. */
231         wakeup(isp->isp_osinfo.pc.ptr);
232         isp_detach_internal_target(isp, chan);
233         while (*num_threads != 0)
234                 mtx_sleep(isp, &isp->isp_osinfo.lock, PRIBIO, "isp_reap", 100);
235 }
236
237 int
238 isp_attach(ispsoftc_t *isp)
239 {
240         const char *nu = device_get_nameunit(isp->isp_osinfo.dev);
241         int du = device_get_unit(isp->isp_dev);
242         int chan;
243
244         isp->isp_osinfo.ehook.ich_func = isp_intr_enable;
245         isp->isp_osinfo.ehook.ich_arg = isp;
246         /*
247          * Haha. Set this first, because if we're loaded as a module isp_intr_enable
248          * will be called right awawy, which will clear isp_osinfo.ehook_active,
249          * which would be unwise to then set again later.
250          */
251         isp->isp_osinfo.ehook_active = 1;
252         if (config_intrhook_establish(&isp->isp_osinfo.ehook) != 0) {
253                 isp_prt(isp, ISP_LOGERR, "could not establish interrupt enable hook");
254                 return (-EIO);
255         }
256
257         /*
258          * Create the device queue for our SIM(s).
259          */
260         isp->isp_osinfo.devq = cam_simq_alloc(isp->isp_maxcmds);
261         if (isp->isp_osinfo.devq == NULL) {
262                 config_intrhook_disestablish(&isp->isp_osinfo.ehook);
263                 return (EIO);
264         }
265
266         for (chan = 0; chan < isp->isp_nchan; chan++) {
267                 if (isp_attach_chan(isp, isp->isp_osinfo.devq, chan)) {
268                         goto unwind;
269                 }
270         }
271
272         callout_init_mtx(&isp->isp_osinfo.tmo, &isp->isp_osinfo.lock, 0);
273         isp_timer_count = hz >> 2;
274         callout_reset(&isp->isp_osinfo.tmo, isp_timer_count, isp_timer, isp);
275         isp->isp_osinfo.timer_active = 1;
276
277         isp->isp_osinfo.cdev = make_dev(&isp_cdevsw, du, UID_ROOT, GID_OPERATOR, 0600, "%s", nu);
278         if (isp->isp_osinfo.cdev) {
279                 isp->isp_osinfo.cdev->si_drv1 = isp;
280         }
281         return (0);
282
283 unwind:
284         while (--chan >= 0) {
285                 struct cam_sim *sim;
286                 struct cam_path *path;
287
288                 ISP_GET_PC(isp, chan, sim, sim);
289                 ISP_GET_PC(isp, chan, path, path);
290                 xpt_free_path(path);
291                 ISP_LOCK(isp);
292                 xpt_bus_deregister(cam_sim_path(sim));
293                 ISP_UNLOCK(isp);
294                 cam_sim_free(sim, FALSE);
295         }
296         if (isp->isp_osinfo.ehook_active) {
297                 config_intrhook_disestablish(&isp->isp_osinfo.ehook);
298                 isp->isp_osinfo.ehook_active = 0;
299         }
300         if (isp->isp_osinfo.cdev) {
301                 destroy_dev(isp->isp_osinfo.cdev);
302                 isp->isp_osinfo.cdev = NULL;
303         }
304         cam_simq_free(isp->isp_osinfo.devq);
305         isp->isp_osinfo.devq = NULL;
306         return (-1);
307 }
308
309 int
310 isp_detach(ispsoftc_t *isp)
311 {
312         struct cam_sim *sim;
313         int chan;
314
315         ISP_LOCK(isp);
316         for (chan = isp->isp_nchan - 1; chan >= 0; chan -= 1) {
317                 ISP_GET_PC(isp, chan, sim, sim);
318                 if (sim->refcount > 2) {
319                         ISP_UNLOCK(isp);
320                         return (EBUSY);
321                 }
322         }
323         /* Tell spawned threads that we're exiting. */
324         isp->isp_osinfo.is_exiting = 1;
325         if (isp->isp_osinfo.timer_active) {
326                 callout_stop(&isp->isp_osinfo.tmo);
327                 isp->isp_osinfo.timer_active = 0;
328         }
329         for (chan = isp->isp_nchan - 1; chan >= 0; chan -= 1)
330                 isp_detach_chan(isp, chan);
331         ISP_UNLOCK(isp);
332
333         if (isp->isp_osinfo.cdev) {
334                 destroy_dev(isp->isp_osinfo.cdev);
335                 isp->isp_osinfo.cdev = NULL;
336         }
337         if (isp->isp_osinfo.ehook_active) {
338                 config_intrhook_disestablish(&isp->isp_osinfo.ehook);
339                 isp->isp_osinfo.ehook_active = 0;
340         }
341         if (isp->isp_osinfo.devq != NULL) {
342                 cam_simq_free(isp->isp_osinfo.devq);
343                 isp->isp_osinfo.devq = NULL;
344         }
345         return (0);
346 }
347
348 static void
349 isp_freeze_loopdown(ispsoftc_t *isp, int chan, char *msg)
350 {
351         if (IS_FC(isp)) {
352                 struct isp_fc *fc = ISP_FC_PC(isp, chan);
353                 if (fc->simqfrozen == 0) {
354                         isp_prt(isp, ISP_LOGDEBUG0, "%s: freeze simq (loopdown) chan %d", msg, chan);
355                         fc->simqfrozen = SIMQFRZ_LOOPDOWN;
356                         xpt_freeze_simq(fc->sim, 1);
357                 } else {
358                         isp_prt(isp, ISP_LOGDEBUG0, "%s: mark frozen (loopdown) chan %d", msg, chan);
359                         fc->simqfrozen |= SIMQFRZ_LOOPDOWN;
360                 }
361         }
362 }
363
364 static void
365 isp_unfreeze_loopdown(ispsoftc_t *isp, int chan)
366 {
367         if (IS_FC(isp)) {
368                 struct isp_fc *fc = ISP_FC_PC(isp, chan);
369                 int wasfrozen = fc->simqfrozen & SIMQFRZ_LOOPDOWN;
370                 fc->simqfrozen &= ~SIMQFRZ_LOOPDOWN;
371                 if (wasfrozen && fc->simqfrozen == 0) {
372                         isp_prt(isp, ISP_LOG_SANCFG|ISP_LOGDEBUG0, "%s: Chan %d releasing simq", __func__, chan);
373                         xpt_release_simq(fc->sim, 1);
374                 }
375         }
376 }
377
378
379 static int
380 ispioctl(struct cdev *dev, u_long c, caddr_t addr, int flags, struct thread *td)
381 {
382         ispsoftc_t *isp;
383         int nr, chan, retval = ENOTTY;
384
385         isp = dev->si_drv1;
386
387         switch (c) {
388         case ISP_SDBLEV:
389         {
390                 int olddblev = isp->isp_dblev;
391                 isp->isp_dblev = *(int *)addr;
392                 *(int *)addr = olddblev;
393                 retval = 0;
394                 break;
395         }
396         case ISP_GETROLE:
397                 chan = *(int *)addr;
398                 if (chan < 0 || chan >= isp->isp_nchan) {
399                         retval = -ENXIO;
400                         break;
401                 }
402                 if (IS_FC(isp)) {
403                         *(int *)addr = FCPARAM(isp, chan)->role;
404                 } else {
405                         *(int *)addr = SDPARAM(isp, chan)->role;
406                 }
407                 retval = 0;
408                 break;
409         case ISP_SETROLE:
410                 nr = *(int *)addr;
411                 chan = nr >> 8;
412                 if (chan < 0 || chan >= isp->isp_nchan) {
413                         retval = -ENXIO;
414                         break;
415                 }
416                 nr &= 0xff;
417                 if (nr & ~(ISP_ROLE_INITIATOR|ISP_ROLE_TARGET)) {
418                         retval = EINVAL;
419                         break;
420                 }
421                 if (IS_FC(isp)) {
422                         /*
423                          * We don't really support dual role at present on FC cards.
424                          *
425                          * We should, but a bunch of things are currently broken,
426                          * so don't allow it.
427                          */
428                         if (nr == ISP_ROLE_BOTH) {
429                                 isp_prt(isp, ISP_LOGERR, "cannot support dual role at present");
430                                 retval = EINVAL;
431                                 break;
432                         }
433                         *(int *)addr = FCPARAM(isp, chan)->role;
434 #ifdef  ISP_INTERNAL_TARGET
435                         ISP_LOCK(isp);
436                         retval = isp_fc_change_role(isp, chan, nr);
437                         ISP_UNLOCK(isp);
438 #else
439                         FCPARAM(isp, chan)->role = nr;
440 #endif
441                 } else {
442                         *(int *)addr = SDPARAM(isp, chan)->role;
443                         SDPARAM(isp, chan)->role = nr;
444                 }
445                 retval = 0;
446                 break;
447
448         case ISP_RESETHBA:
449                 ISP_LOCK(isp);
450 #ifdef  ISP_TARGET_MODE
451                 isp_del_all_wwn_entries(isp, ISP_NOCHAN);
452 #endif
453                 isp_reinit(isp, 0);
454                 ISP_UNLOCK(isp);
455                 retval = 0;
456                 break;
457
458         case ISP_RESCAN:
459                 if (IS_FC(isp)) {
460                         chan = *(int *)addr;
461                         if (chan < 0 || chan >= isp->isp_nchan) {
462                                 retval = -ENXIO;
463                                 break;
464                         }
465                         ISP_LOCK(isp);
466                         if (isp_fc_runstate(isp, chan, 5 * 1000000)) {
467                                 retval = EIO;
468                         } else {
469                                 retval = 0;
470                         }
471                         ISP_UNLOCK(isp);
472                 }
473                 break;
474
475         case ISP_FC_LIP:
476                 if (IS_FC(isp)) {
477                         chan = *(int *)addr;
478                         if (chan < 0 || chan >= isp->isp_nchan) {
479                                 retval = -ENXIO;
480                                 break;
481                         }
482                         ISP_LOCK(isp);
483                         if (isp_control(isp, ISPCTL_SEND_LIP, chan)) {
484                                 retval = EIO;
485                         } else {
486                                 retval = 0;
487                         }
488                         ISP_UNLOCK(isp);
489                 }
490                 break;
491         case ISP_FC_GETDINFO:
492         {
493                 struct isp_fc_device *ifc = (struct isp_fc_device *) addr;
494                 fcportdb_t *lp;
495
496                 if (IS_SCSI(isp)) {
497                         break;
498                 }
499                 if (ifc->loopid >= MAX_FC_TARG) {
500                         retval = EINVAL;
501                         break;
502                 }
503                 lp = &FCPARAM(isp, ifc->chan)->portdb[ifc->loopid];
504                 if (lp->state == FC_PORTDB_STATE_VALID || lp->target_mode) {
505                         ifc->role = (lp->prli_word3 & SVC3_ROLE_MASK) >> SVC3_ROLE_SHIFT;
506                         ifc->loopid = lp->handle;
507                         ifc->portid = lp->portid;
508                         ifc->node_wwn = lp->node_wwn;
509                         ifc->port_wwn = lp->port_wwn;
510                         retval = 0;
511                 } else {
512                         retval = ENODEV;
513                 }
514                 break;
515         }
516         case ISP_GET_STATS:
517         {
518                 isp_stats_t *sp = (isp_stats_t *) addr;
519
520                 ISP_MEMZERO(sp, sizeof (*sp));
521                 sp->isp_stat_version = ISP_STATS_VERSION;
522                 sp->isp_type = isp->isp_type;
523                 sp->isp_revision = isp->isp_revision;
524                 ISP_LOCK(isp);
525                 sp->isp_stats[ISP_INTCNT] = isp->isp_intcnt;
526                 sp->isp_stats[ISP_INTBOGUS] = isp->isp_intbogus;
527                 sp->isp_stats[ISP_INTMBOXC] = isp->isp_intmboxc;
528                 sp->isp_stats[ISP_INGOASYNC] = isp->isp_intoasync;
529                 sp->isp_stats[ISP_RSLTCCMPLT] = isp->isp_rsltccmplt;
530                 sp->isp_stats[ISP_FPHCCMCPLT] = isp->isp_fphccmplt;
531                 sp->isp_stats[ISP_RSCCHIWAT] = isp->isp_rscchiwater;
532                 sp->isp_stats[ISP_FPCCHIWAT] = isp->isp_fpcchiwater;
533                 ISP_UNLOCK(isp);
534                 retval = 0;
535                 break;
536         }
537         case ISP_CLR_STATS:
538                 ISP_LOCK(isp);
539                 isp->isp_intcnt = 0;
540                 isp->isp_intbogus = 0;
541                 isp->isp_intmboxc = 0;
542                 isp->isp_intoasync = 0;
543                 isp->isp_rsltccmplt = 0;
544                 isp->isp_fphccmplt = 0;
545                 isp->isp_rscchiwater = 0;
546                 isp->isp_fpcchiwater = 0;
547                 ISP_UNLOCK(isp);
548                 retval = 0;
549                 break;
550         case ISP_FC_GETHINFO:
551         {
552                 struct isp_hba_device *hba = (struct isp_hba_device *) addr;
553                 int chan = hba->fc_channel;
554
555                 if (chan < 0 || chan >= isp->isp_nchan) {
556                         retval = ENXIO;
557                         break;
558                 }
559                 hba->fc_fw_major = ISP_FW_MAJORX(isp->isp_fwrev);
560                 hba->fc_fw_minor = ISP_FW_MINORX(isp->isp_fwrev);
561                 hba->fc_fw_micro = ISP_FW_MICROX(isp->isp_fwrev);
562                 hba->fc_nchannels = isp->isp_nchan;
563                 if (IS_FC(isp)) {
564                         hba->fc_nports = MAX_FC_TARG;
565                         hba->fc_speed = FCPARAM(isp, hba->fc_channel)->isp_gbspeed;
566                         hba->fc_topology = FCPARAM(isp, chan)->isp_topo + 1;
567                         hba->fc_loopid = FCPARAM(isp, chan)->isp_loopid;
568                         hba->nvram_node_wwn = FCPARAM(isp, chan)->isp_wwnn_nvram;
569                         hba->nvram_port_wwn = FCPARAM(isp, chan)->isp_wwpn_nvram;
570                         hba->active_node_wwn = FCPARAM(isp, chan)->isp_wwnn;
571                         hba->active_port_wwn = FCPARAM(isp, chan)->isp_wwpn;
572                 } else {
573                         hba->fc_nports = MAX_TARGETS;
574                         hba->fc_speed = 0;
575                         hba->fc_topology = 0;
576                         hba->nvram_node_wwn = 0ull;
577                         hba->nvram_port_wwn = 0ull;
578                         hba->active_node_wwn = 0ull;
579                         hba->active_port_wwn = 0ull;
580                 }
581                 retval = 0;
582                 break;
583         }
584         case ISP_TSK_MGMT:
585         {
586                 int needmarker;
587                 struct isp_fc_tsk_mgmt *fct = (struct isp_fc_tsk_mgmt *) addr;
588                 uint16_t loopid;
589                 mbreg_t mbs;
590
591                 if (IS_SCSI(isp)) {
592                         break;
593                 }
594
595                 chan = fct->chan;
596                 if (chan < 0 || chan >= isp->isp_nchan) {
597                         retval = -ENXIO;
598                         break;
599                 }
600
601                 needmarker = retval = 0;
602                 loopid = fct->loopid;
603                 ISP_LOCK(isp);
604                 if (IS_24XX(isp)) {
605                         uint8_t local[QENTRY_LEN];
606                         isp24xx_tmf_t *tmf;
607                         isp24xx_statusreq_t *sp;
608                         fcparam *fcp = FCPARAM(isp, chan);
609                         fcportdb_t *lp;
610                         int i;
611
612                         for (i = 0; i < MAX_FC_TARG; i++) {
613                                 lp = &fcp->portdb[i];
614                                 if (lp->handle == loopid) {
615                                         break;
616                                 }
617                         }
618                         if (i == MAX_FC_TARG) {
619                                 retval = ENXIO;
620                                 ISP_UNLOCK(isp);
621                                 break;
622                         }
623                         /* XXX VALIDATE LP XXX */
624                         tmf = (isp24xx_tmf_t *) local;
625                         ISP_MEMZERO(tmf, QENTRY_LEN);
626                         tmf->tmf_header.rqs_entry_type = RQSTYPE_TSK_MGMT;
627                         tmf->tmf_header.rqs_entry_count = 1;
628                         tmf->tmf_nphdl = lp->handle;
629                         tmf->tmf_delay = 2;
630                         tmf->tmf_timeout = 2;
631                         tmf->tmf_tidlo = lp->portid;
632                         tmf->tmf_tidhi = lp->portid >> 16;
633                         tmf->tmf_vpidx = ISP_GET_VPIDX(isp, chan);
634                         tmf->tmf_lun[1] = fct->lun & 0xff;
635                         if (fct->lun >= 256) {
636                                 tmf->tmf_lun[0] = 0x40 | (fct->lun >> 8);
637                         }
638                         switch (fct->action) {
639                         case IPT_CLEAR_ACA:
640                                 tmf->tmf_flags = ISP24XX_TMF_CLEAR_ACA;
641                                 break;
642                         case IPT_TARGET_RESET:
643                                 tmf->tmf_flags = ISP24XX_TMF_TARGET_RESET;
644                                 needmarker = 1;
645                                 break;
646                         case IPT_LUN_RESET:
647                                 tmf->tmf_flags = ISP24XX_TMF_LUN_RESET;
648                                 needmarker = 1;
649                                 break;
650                         case IPT_CLEAR_TASK_SET:
651                                 tmf->tmf_flags = ISP24XX_TMF_CLEAR_TASK_SET;
652                                 needmarker = 1;
653                                 break;
654                         case IPT_ABORT_TASK_SET:
655                                 tmf->tmf_flags = ISP24XX_TMF_ABORT_TASK_SET;
656                                 needmarker = 1;
657                                 break;
658                         default:
659                                 retval = EINVAL;
660                                 break;
661                         }
662                         if (retval) {
663                                 ISP_UNLOCK(isp);
664                                 break;
665                         }
666                         MBSINIT(&mbs, MBOX_EXEC_COMMAND_IOCB_A64, MBLOGALL, 5000000);
667                         mbs.param[1] = QENTRY_LEN;
668                         mbs.param[2] = DMA_WD1(fcp->isp_scdma);
669                         mbs.param[3] = DMA_WD0(fcp->isp_scdma);
670                         mbs.param[6] = DMA_WD3(fcp->isp_scdma);
671                         mbs.param[7] = DMA_WD2(fcp->isp_scdma);
672
673                         if (FC_SCRATCH_ACQUIRE(isp, chan)) {
674                                 ISP_UNLOCK(isp);
675                                 retval = ENOMEM;
676                                 break;
677                         }
678                         isp_put_24xx_tmf(isp, tmf, fcp->isp_scratch);
679                         MEMORYBARRIER(isp, SYNC_SFORDEV, 0, QENTRY_LEN, chan);
680                         sp = (isp24xx_statusreq_t *) local;
681                         sp->req_completion_status = 1;
682                         retval = isp_control(isp, ISPCTL_RUN_MBOXCMD, &mbs);
683                         MEMORYBARRIER(isp, SYNC_SFORCPU, QENTRY_LEN, QENTRY_LEN, chan);
684                         isp_get_24xx_response(isp, &((isp24xx_statusreq_t *)fcp->isp_scratch)[1], sp);
685                         FC_SCRATCH_RELEASE(isp, chan);
686                         if (retval || sp->req_completion_status != 0) {
687                                 FC_SCRATCH_RELEASE(isp, chan);
688                                 retval = EIO;
689                         }
690                         if (retval == 0) {
691                                 if (needmarker) {
692                                         fcp->sendmarker = 1;
693                                 }
694                         }
695                 } else {
696                         MBSINIT(&mbs, 0, MBLOGALL, 0);
697                         if (ISP_CAP_2KLOGIN(isp) == 0) {
698                                 loopid <<= 8;
699                         }
700                         switch (fct->action) {
701                         case IPT_CLEAR_ACA:
702                                 mbs.param[0] = MBOX_CLEAR_ACA;
703                                 mbs.param[1] = loopid;
704                                 mbs.param[2] = fct->lun;
705                                 break;
706                         case IPT_TARGET_RESET:
707                                 mbs.param[0] = MBOX_TARGET_RESET;
708                                 mbs.param[1] = loopid;
709                                 needmarker = 1;
710                                 break;
711                         case IPT_LUN_RESET:
712                                 mbs.param[0] = MBOX_LUN_RESET;
713                                 mbs.param[1] = loopid;
714                                 mbs.param[2] = fct->lun;
715                                 needmarker = 1;
716                                 break;
717                         case IPT_CLEAR_TASK_SET:
718                                 mbs.param[0] = MBOX_CLEAR_TASK_SET;
719                                 mbs.param[1] = loopid;
720                                 mbs.param[2] = fct->lun;
721                                 needmarker = 1;
722                                 break;
723                         case IPT_ABORT_TASK_SET:
724                                 mbs.param[0] = MBOX_ABORT_TASK_SET;
725                                 mbs.param[1] = loopid;
726                                 mbs.param[2] = fct->lun;
727                                 needmarker = 1;
728                                 break;
729                         default:
730                                 retval = EINVAL;
731                                 break;
732                         }
733                         if (retval == 0) {
734                                 if (needmarker) {
735                                         FCPARAM(isp, chan)->sendmarker = 1;
736                                 }
737                                 retval = isp_control(isp, ISPCTL_RUN_MBOXCMD, &mbs);
738                                 if (retval) {
739                                         retval = EIO;
740                                 }
741                         }
742                 }
743                 ISP_UNLOCK(isp);
744                 break;
745         }
746         default:
747                 break;
748         }
749         return (retval);
750 }
751
752 static void
753 isp_intr_enable(void *arg)
754 {
755         int chan;
756         ispsoftc_t *isp = arg;
757         ISP_LOCK(isp);
758         for (chan = 0; chan < isp->isp_nchan; chan++) {
759                 if (IS_FC(isp)) {
760                         if (FCPARAM(isp, chan)->role != ISP_ROLE_NONE) {
761                                 ISP_ENABLE_INTS(isp);
762                                 break;
763                         }
764                 } else {
765                         if (SDPARAM(isp, chan)->role != ISP_ROLE_NONE) {
766                                 ISP_ENABLE_INTS(isp);
767                                 break;
768                         }
769                 }
770         }
771         isp->isp_osinfo.ehook_active = 0;
772         ISP_UNLOCK(isp);
773         /* Release our hook so that the boot can continue. */
774         config_intrhook_disestablish(&isp->isp_osinfo.ehook);
775 }
776
777 /*
778  * Local Inlines
779  */
780
781 static ISP_INLINE int isp_get_pcmd(ispsoftc_t *, union ccb *);
782 static ISP_INLINE void isp_free_pcmd(ispsoftc_t *, union ccb *);
783
784 static ISP_INLINE int
785 isp_get_pcmd(ispsoftc_t *isp, union ccb *ccb)
786 {
787         ISP_PCMD(ccb) = isp->isp_osinfo.pcmd_free;
788         if (ISP_PCMD(ccb) == NULL) {
789                 return (-1);
790         }
791         isp->isp_osinfo.pcmd_free = ((struct isp_pcmd *)ISP_PCMD(ccb))->next;
792         return (0);
793 }
794
795 static ISP_INLINE void
796 isp_free_pcmd(ispsoftc_t *isp, union ccb *ccb)
797 {
798         if (ISP_PCMD(ccb)) {
799 #ifdef  ISP_TARGET_MODE
800                 PISP_PCMD(ccb)->datalen = 0;
801                 PISP_PCMD(ccb)->totslen = 0;
802                 PISP_PCMD(ccb)->cumslen = 0;
803                 PISP_PCMD(ccb)->crn = 0;
804 #endif
805                 PISP_PCMD(ccb)->next = isp->isp_osinfo.pcmd_free;
806                 isp->isp_osinfo.pcmd_free = ISP_PCMD(ccb);
807                 ISP_PCMD(ccb) = NULL;
808         }
809 }
810
811 /*
812  * Put the target mode functions here, because some are inlines
813  */
814 #ifdef  ISP_TARGET_MODE
815 static ISP_INLINE void isp_tmlock(ispsoftc_t *, const char *);
816 static ISP_INLINE void isp_tmunlk(ispsoftc_t *);
817 static ISP_INLINE int is_any_lun_enabled(ispsoftc_t *, int);
818 static ISP_INLINE int is_lun_enabled(ispsoftc_t *, int, lun_id_t);
819 static ISP_INLINE tstate_t *get_lun_statep(ispsoftc_t *, int, lun_id_t);
820 static ISP_INLINE tstate_t *get_lun_statep_from_tag(ispsoftc_t *, int, uint32_t);
821 static ISP_INLINE void rls_lun_statep(ispsoftc_t *, tstate_t *);
822 static ISP_INLINE inot_private_data_t *get_ntp_from_tagdata(ispsoftc_t *, uint32_t, uint32_t, tstate_t **);
823 static ISP_INLINE atio_private_data_t *isp_get_atpd(ispsoftc_t *, tstate_t *, uint32_t);
824 static ISP_INLINE atio_private_data_t *isp_find_atpd(ispsoftc_t *, tstate_t *, uint32_t);
825 static ISP_INLINE void isp_put_atpd(ispsoftc_t *, tstate_t *, atio_private_data_t *);
826 static ISP_INLINE inot_private_data_t *isp_get_ntpd(ispsoftc_t *, tstate_t *);
827 static ISP_INLINE inot_private_data_t *isp_find_ntpd(ispsoftc_t *, tstate_t *, uint32_t, uint32_t);
828 static ISP_INLINE void isp_put_ntpd(ispsoftc_t *, tstate_t *, inot_private_data_t *);
829 static cam_status create_lun_state(ispsoftc_t *, int, struct cam_path *, tstate_t **);
830 static void destroy_lun_state(ispsoftc_t *, tstate_t *);
831 static void isp_enable_lun(ispsoftc_t *, union ccb *);
832 static cam_status isp_enable_deferred_luns(ispsoftc_t *, int);
833 static cam_status isp_enable_deferred(ispsoftc_t *, int, lun_id_t);
834 static void isp_disable_lun(ispsoftc_t *, union ccb *);
835 static int isp_enable_target_mode(ispsoftc_t *, int);
836 static int isp_disable_target_mode(ispsoftc_t *, int);
837 static void isp_ledone(ispsoftc_t *, lun_entry_t *);
838 static timeout_t isp_refire_putback_atio;
839 static timeout_t isp_refire_notify_ack;
840 static void isp_complete_ctio(union ccb *);
841 static void isp_target_putback_atio(union ccb *);
842 enum Start_Ctio_How { FROM_CAM, FROM_TIMER, FROM_SRR, FROM_CTIO_DONE };
843 static void isp_target_start_ctio(ispsoftc_t *, union ccb *, enum Start_Ctio_How);
844 static void isp_handle_platform_atio(ispsoftc_t *, at_entry_t *);
845 static void isp_handle_platform_atio2(ispsoftc_t *, at2_entry_t *);
846 static void isp_handle_platform_atio7(ispsoftc_t *, at7_entry_t *);
847 static void isp_handle_platform_ctio(ispsoftc_t *, void *);
848 static void isp_handle_platform_notify_scsi(ispsoftc_t *, in_entry_t *);
849 static void isp_handle_platform_notify_fc(ispsoftc_t *, in_fcentry_t *);
850 static void isp_handle_platform_notify_24xx(ispsoftc_t *, in_fcentry_24xx_t *);
851 static int isp_handle_platform_target_notify_ack(ispsoftc_t *, isp_notify_t *);
852 static void isp_handle_platform_target_tmf(ispsoftc_t *, isp_notify_t *);
853 static void isp_target_mark_aborted(ispsoftc_t *, union ccb *);
854 static void isp_target_mark_aborted_early(ispsoftc_t *, tstate_t *, uint32_t);
855
856 static ISP_INLINE void
857 isp_tmlock(ispsoftc_t *isp, const char *msg)
858 {
859         while (isp->isp_osinfo.tmbusy) {
860                 isp->isp_osinfo.tmwanted = 1;
861                 mtx_sleep(isp, &isp->isp_lock, PRIBIO, msg, 0);
862         }
863         isp->isp_osinfo.tmbusy = 1;
864 }
865
866 static ISP_INLINE void
867 isp_tmunlk(ispsoftc_t *isp)
868 {
869         isp->isp_osinfo.tmbusy = 0;
870         if (isp->isp_osinfo.tmwanted) {
871                 isp->isp_osinfo.tmwanted = 0;
872                 wakeup(isp);
873         }
874 }
875
876 static ISP_INLINE int
877 is_any_lun_enabled(ispsoftc_t *isp, int bus)
878 {
879         struct tslist *lhp;
880         int i;
881
882         for (i = 0; i < LUN_HASH_SIZE; i++) {
883                 ISP_GET_PC_ADDR(isp, bus, lun_hash[i], lhp);
884                 if (SLIST_FIRST(lhp))
885                         return (1);
886         }
887         return (0);
888 }
889
890 static ISP_INLINE int
891 is_lun_enabled(ispsoftc_t *isp, int bus, lun_id_t lun)
892 {
893         tstate_t *tptr;
894         struct tslist *lhp;
895
896         ISP_GET_PC_ADDR(isp, bus, lun_hash[LUN_HASH_FUNC(lun)], lhp);
897         SLIST_FOREACH(tptr, lhp, next) {
898                 if (tptr->ts_lun == lun) {
899                         return (1);
900                 }
901         }
902         return (0);
903 }
904
905 static void
906 dump_tstates(ispsoftc_t *isp, int bus)
907 {
908         int i, j;
909         struct tslist *lhp;
910         tstate_t *tptr = NULL;
911
912         if (bus >= isp->isp_nchan) {
913                 return;
914         }
915         for (i = 0; i < LUN_HASH_SIZE; i++) {
916                 ISP_GET_PC_ADDR(isp, bus, lun_hash[i], lhp);
917                 j = 0;
918                 SLIST_FOREACH(tptr, lhp, next) {
919                         xpt_print(tptr->owner, "[%d, %d] atio_cnt=%d inot_cnt=%d\n", i, j, tptr->atio_count, tptr->inot_count);
920                         j++;
921                 }
922         }
923 }
924
925 static ISP_INLINE tstate_t *
926 get_lun_statep(ispsoftc_t *isp, int bus, lun_id_t lun)
927 {
928         tstate_t *tptr = NULL;
929         struct tslist *lhp;
930
931         if (bus < isp->isp_nchan) {
932                 ISP_GET_PC_ADDR(isp, bus, lun_hash[LUN_HASH_FUNC(lun)], lhp);
933                 SLIST_FOREACH(tptr, lhp, next) {
934                         if (tptr->ts_lun == lun) {
935                                 tptr->hold++;
936                                 return (tptr);
937                         }
938                 }
939         }
940         return (NULL);
941 }
942
943 static ISP_INLINE tstate_t *
944 get_lun_statep_from_tag(ispsoftc_t *isp, int bus, uint32_t tagval)
945 {
946         tstate_t *tptr = NULL;
947         atio_private_data_t *atp;
948         struct tslist *lhp;
949         int i;
950
951         if (bus < isp->isp_nchan && tagval != 0) {
952                 for (i = 0; i < LUN_HASH_SIZE; i++) {
953                         ISP_GET_PC_ADDR(isp, bus, lun_hash[i], lhp);
954                         SLIST_FOREACH(tptr, lhp, next) {
955                                 atp = isp_find_atpd(isp, tptr, tagval);
956                                 if (atp) {
957                                         tptr->hold++;
958                                         return (tptr);
959                                 }
960                         }
961                 }
962         }
963         return (NULL);
964 }
965
966 static ISP_INLINE inot_private_data_t *
967 get_ntp_from_tagdata(ispsoftc_t *isp, uint32_t tag_id, uint32_t seq_id, tstate_t **rslt)
968 {
969         inot_private_data_t *ntp;
970         tstate_t *tptr;
971         struct tslist *lhp;
972         int bus, i;
973
974         for (bus = 0; bus < isp->isp_nchan; bus++) {
975                 for (i = 0; i < LUN_HASH_SIZE; i++) {
976                         ISP_GET_PC_ADDR(isp, bus, lun_hash[i], lhp);
977                         SLIST_FOREACH(tptr, lhp, next) {
978                                 ntp = isp_find_ntpd(isp, tptr, tag_id, seq_id);
979                                 if (ntp) {
980                                         *rslt = tptr;
981                                         tptr->hold++;
982                                         return (ntp);
983                                 }
984                         }
985                 }
986         }
987         return (NULL);
988 }
989
990 static ISP_INLINE void
991 rls_lun_statep(ispsoftc_t *isp, tstate_t *tptr)
992 {
993         KASSERT((tptr->hold), ("tptr not held"));
994         tptr->hold--;
995 }
996
997 static void
998 isp_tmcmd_restart(ispsoftc_t *isp)
999 {
1000         inot_private_data_t *ntp;
1001         inot_private_data_t *restart_queue;
1002         tstate_t *tptr;
1003         union ccb *ccb;
1004         struct tslist *lhp;
1005         int bus, i;
1006
1007         for (bus = 0; bus < isp->isp_nchan; bus++) {
1008                 for (i = 0; i < LUN_HASH_SIZE; i++) {
1009                         ISP_GET_PC_ADDR(isp, bus, lun_hash[i], lhp);
1010                         SLIST_FOREACH(tptr, lhp, next) {
1011                                 if ((restart_queue = tptr->restart_queue) != NULL)
1012                                         tptr->restart_queue = NULL;
1013                                 while (restart_queue) {
1014                                         ntp = restart_queue;
1015                                         restart_queue = ntp->rd.nt.nt_hba;
1016                                         if (IS_24XX(isp)) {
1017                                                 isp_prt(isp, ISP_LOGTDEBUG0, "%s: restarting resrc deprived %x", __func__, ((at7_entry_t *)ntp->rd.data)->at_rxid);
1018                                                 isp_handle_platform_atio7(isp, (at7_entry_t *) ntp->rd.data);
1019                                         } else {
1020                                                 isp_prt(isp, ISP_LOGTDEBUG0, "%s: restarting resrc deprived %x", __func__, ((at2_entry_t *)ntp->rd.data)->at_rxid);
1021                                                 isp_handle_platform_atio2(isp, (at2_entry_t *) ntp->rd.data);
1022                                         }
1023                                         isp_put_ntpd(isp, tptr, ntp);
1024                                         if (tptr->restart_queue && restart_queue != NULL) {
1025                                                 ntp = tptr->restart_queue;
1026                                                 tptr->restart_queue = restart_queue;
1027                                                 while (restart_queue->rd.nt.nt_hba) {
1028                                                         restart_queue = restart_queue->rd.nt.nt_hba;
1029                                                 }
1030                                                 restart_queue->rd.nt.nt_hba = ntp;
1031                                                 break;
1032                                         }
1033                                 }
1034                                 /*
1035                                  * We only need to do this once per tptr
1036                                  */
1037                                 if (!TAILQ_EMPTY(&tptr->waitq)) {
1038                                         ccb = (union ccb *)TAILQ_LAST(&tptr->waitq, isp_ccbq);
1039                                         TAILQ_REMOVE(&tptr->waitq, &ccb->ccb_h, periph_links.tqe);
1040                                         isp_target_start_ctio(isp, ccb, FROM_TIMER);
1041                                 }
1042                         }
1043                 }
1044         }
1045 }
1046
1047 static ISP_INLINE atio_private_data_t *
1048 isp_get_atpd(ispsoftc_t *isp, tstate_t *tptr, uint32_t tag)
1049 {
1050         atio_private_data_t *atp;
1051
1052         atp = LIST_FIRST(&tptr->atfree);
1053         if (atp) {
1054                 LIST_REMOVE(atp, next);
1055                 atp->tag = tag;
1056                 LIST_INSERT_HEAD(&tptr->atused[ATPDPHASH(tag)], atp, next);
1057         }
1058         return (atp);
1059 }
1060
1061 static ISP_INLINE atio_private_data_t *
1062 isp_find_atpd(ispsoftc_t *isp, tstate_t *tptr, uint32_t tag)
1063 {
1064         atio_private_data_t *atp;
1065
1066         LIST_FOREACH(atp, &tptr->atused[ATPDPHASH(tag)], next) {
1067                 if (atp->tag == tag)
1068                         return (atp);
1069         }
1070         return (NULL);
1071 }
1072
1073 static ISP_INLINE void
1074 isp_put_atpd(ispsoftc_t *isp, tstate_t *tptr, atio_private_data_t *atp)
1075 {
1076         if (atp->ests) {
1077                 isp_put_ecmd(isp, atp->ests);
1078         }
1079         LIST_REMOVE(atp, next);
1080         memset(atp, 0, sizeof (*atp));
1081         LIST_INSERT_HEAD(&tptr->atfree, atp, next);
1082 }
1083
1084 static void
1085 isp_dump_atpd(ispsoftc_t *isp, tstate_t *tptr)
1086 {
1087         atio_private_data_t *atp;
1088         const char *states[8] = { "Free", "ATIO", "CAM", "CTIO", "LAST_CTIO", "PDON", "?6", "7" };
1089
1090         for (atp = tptr->atpool; atp < &tptr->atpool[ATPDPSIZE]; atp++) {
1091                 xpt_print(tptr->owner, "ATP: [0x%x] origdlen %u bytes_xfrd %u lun %u nphdl 0x%04x s_id 0x%06x d_id 0x%06x oxid 0x%04x state %s\n",
1092                     atp->tag, atp->orig_datalen, atp->bytes_xfered, atp->lun, atp->nphdl, atp->sid, atp->portid, atp->oxid, states[atp->state & 0x7]);
1093         }
1094 }
1095
1096
1097 static ISP_INLINE inot_private_data_t *
1098 isp_get_ntpd(ispsoftc_t *isp, tstate_t *tptr)
1099 {
1100         inot_private_data_t *ntp;
1101         ntp = tptr->ntfree;
1102         if (ntp) {
1103                 tptr->ntfree = ntp->next;
1104         }
1105         return (ntp);
1106 }
1107
1108 static ISP_INLINE inot_private_data_t *
1109 isp_find_ntpd(ispsoftc_t *isp, tstate_t *tptr, uint32_t tag_id, uint32_t seq_id)
1110 {
1111         inot_private_data_t *ntp;
1112         for (ntp = tptr->ntpool; ntp < &tptr->ntpool[ATPDPSIZE]; ntp++) {
1113                 if (ntp->rd.tag_id == tag_id && ntp->rd.seq_id == seq_id) {
1114                         return (ntp);
1115                 }
1116         }
1117         return (NULL);
1118 }
1119
1120 static ISP_INLINE void
1121 isp_put_ntpd(ispsoftc_t *isp, tstate_t *tptr, inot_private_data_t *ntp)
1122 {
1123         ntp->rd.tag_id = ntp->rd.seq_id = 0;
1124         ntp->next = tptr->ntfree;
1125         tptr->ntfree = ntp;
1126 }
1127
1128 static cam_status
1129 create_lun_state(ispsoftc_t *isp, int bus, struct cam_path *path, tstate_t **rslt)
1130 {
1131         cam_status status;
1132         lun_id_t lun;
1133         struct tslist *lhp;
1134         tstate_t *tptr;
1135         int i;
1136
1137         lun = xpt_path_lun_id(path);
1138         if (lun != CAM_LUN_WILDCARD) {
1139                 if (lun >= ISP_MAX_LUNS(isp)) {
1140                         return (CAM_LUN_INVALID);
1141                 }
1142         }
1143         if (is_lun_enabled(isp, bus, lun)) {
1144                 return (CAM_LUN_ALRDY_ENA);
1145         }
1146         tptr = malloc(sizeof (tstate_t), M_DEVBUF, M_NOWAIT|M_ZERO);
1147         if (tptr == NULL) {
1148                 return (CAM_RESRC_UNAVAIL);
1149         }
1150         tptr->ts_lun = lun;
1151         status = xpt_create_path(&tptr->owner, NULL, xpt_path_path_id(path), xpt_path_target_id(path), lun);
1152         if (status != CAM_REQ_CMP) {
1153                 free(tptr, M_DEVBUF);
1154                 return (status);
1155         }
1156         SLIST_INIT(&tptr->atios);
1157         SLIST_INIT(&tptr->inots);
1158         TAILQ_INIT(&tptr->waitq);
1159         LIST_INIT(&tptr->atfree);
1160         for (i = ATPDPSIZE-1; i >= 0; i--)
1161                 LIST_INSERT_HEAD(&tptr->atfree, &tptr->atpool[i], next);
1162         for (i = 0; i < ATPDPHASHSIZE; i++)
1163                 LIST_INIT(&tptr->atused[i]);
1164         for (i = 0; i < ATPDPSIZE-1; i++)
1165                 tptr->ntpool[i].next = &tptr->ntpool[i+1];
1166         tptr->ntfree = tptr->ntpool;
1167         tptr->hold = 1;
1168         ISP_GET_PC_ADDR(isp, bus, lun_hash[LUN_HASH_FUNC(lun)], lhp);
1169         SLIST_INSERT_HEAD(lhp, tptr, next);
1170         *rslt = tptr;
1171         ISP_PATH_PRT(isp, ISP_LOGTDEBUG0, path, "created tstate\n");
1172         return (CAM_REQ_CMP);
1173 }
1174
1175 static ISP_INLINE void
1176 destroy_lun_state(ispsoftc_t *isp, tstate_t *tptr)
1177 {
1178         union ccb *ccb;
1179         struct tslist *lhp;
1180
1181         KASSERT((tptr->hold != 0), ("tptr is not held"));
1182         KASSERT((tptr->hold == 1), ("tptr still held (%d)", tptr->hold));
1183         do {
1184                 ccb = (union ccb *)SLIST_FIRST(&tptr->atios);
1185                 if (ccb) {
1186                         SLIST_REMOVE_HEAD(&tptr->atios, sim_links.sle);
1187                         ccb->ccb_h.status = CAM_REQ_ABORTED;
1188                         xpt_done(ccb);
1189                 }
1190         } while (ccb);
1191         do {
1192                 ccb = (union ccb *)SLIST_FIRST(&tptr->inots);
1193                 if (ccb) {
1194                         SLIST_REMOVE_HEAD(&tptr->inots, sim_links.sle);
1195                         ccb->ccb_h.status = CAM_REQ_ABORTED;
1196                         xpt_done(ccb);
1197                 }
1198         } while (ccb);
1199         ISP_GET_PC_ADDR(isp, cam_sim_bus(xpt_path_sim(tptr->owner)), lun_hash[LUN_HASH_FUNC(tptr->ts_lun)], lhp);
1200         SLIST_REMOVE(lhp, tptr, tstate, next);
1201         ISP_PATH_PRT(isp, ISP_LOGTDEBUG0, tptr->owner, "destroyed tstate\n");
1202         xpt_free_path(tptr->owner);
1203         free(tptr, M_DEVBUF);
1204 }
1205
1206 /*
1207  * Enable a lun.
1208  */
1209 static void
1210 isp_enable_lun(ispsoftc_t *isp, union ccb *ccb)
1211 {
1212         tstate_t *tptr = NULL;
1213         int bus, tm_enabled, target_role;
1214         target_id_t target;
1215         lun_id_t lun;
1216
1217
1218         /*
1219          * We only support either a wildcard target/lun or a target ID of zero and a non-wildcard lun
1220          */
1221         bus = XS_CHANNEL(ccb);
1222         target = ccb->ccb_h.target_id;
1223         lun = ccb->ccb_h.target_lun;
1224         ISP_PATH_PRT(isp, ISP_LOGTDEBUG0|ISP_LOGCONFIG, ccb->ccb_h.path, "enabling lun %u\n", lun);
1225         if (target != CAM_TARGET_WILDCARD && target != 0) {
1226                 ccb->ccb_h.status = CAM_TID_INVALID;
1227                 xpt_done(ccb);
1228                 return;
1229         }
1230         if (target == CAM_TARGET_WILDCARD && lun != CAM_LUN_WILDCARD) {
1231                 ccb->ccb_h.status = CAM_LUN_INVALID;
1232                 xpt_done(ccb);
1233                 return;
1234         }
1235
1236         if (target != CAM_TARGET_WILDCARD && lun == CAM_LUN_WILDCARD) {
1237                 ccb->ccb_h.status = CAM_LUN_INVALID;
1238                 xpt_done(ccb);
1239                 return;
1240         }
1241         if (isp->isp_dblev & ISP_LOGTDEBUG0) {
1242                 xpt_print(ccb->ccb_h.path, "enabling lun 0x%x on channel %d\n", lun, bus);
1243         }
1244
1245         /*
1246          * Wait until we're not busy with the lun enables subsystem
1247          */
1248         isp_tmlock(isp, "isp_enable_lun");
1249
1250         /*
1251          * This is as a good a place as any to check f/w capabilities.
1252          */
1253
1254         if (IS_FC(isp)) {
1255                 if (ISP_CAP_TMODE(isp) == 0) {
1256                         xpt_print(ccb->ccb_h.path, "firmware does not support target mode\n");
1257                         ccb->ccb_h.status = CAM_FUNC_NOTAVAIL;
1258                         goto done;
1259                 }
1260                 /*
1261                  * We *could* handle non-SCCLUN f/w, but we'd have to
1262                  * dork with our already fragile enable/disable code.
1263                  */
1264                 if (ISP_CAP_SCCFW(isp) == 0) {
1265                         xpt_print(ccb->ccb_h.path, "firmware not SCCLUN capable\n");
1266                         ccb->ccb_h.status = CAM_FUNC_NOTAVAIL;
1267                         goto done;
1268                 }
1269
1270                 target_role = (FCPARAM(isp, bus)->role & ISP_ROLE_TARGET) != 0;
1271
1272         } else {
1273                 target_role = (SDPARAM(isp, bus)->role & ISP_ROLE_TARGET) != 0;
1274         }
1275
1276         /*
1277          * Create the state pointer.
1278          * It should not already exist.
1279          */
1280         tptr = get_lun_statep(isp, bus, lun);
1281         if (tptr) {
1282                 ccb->ccb_h.status = CAM_LUN_ALRDY_ENA;
1283                 goto done;
1284         }
1285         ccb->ccb_h.status = create_lun_state(isp, bus, ccb->ccb_h.path, &tptr);
1286         if (ccb->ccb_h.status != CAM_REQ_CMP) {
1287                 goto done;
1288         }
1289
1290         /*
1291          * We have a tricky maneuver to perform here.
1292          *
1293          * If target mode isn't already enabled here,
1294          * *and* our current role includes target mode,
1295          * we enable target mode here.
1296          *
1297          */
1298         ISP_GET_PC(isp, bus, tm_enabled, tm_enabled);
1299         if (tm_enabled == 0 && target_role != 0) {
1300                 if (isp_enable_target_mode(isp, bus)) {
1301                         ccb->ccb_h.status = CAM_REQ_CMP_ERR;
1302                         destroy_lun_state(isp, tptr);
1303                         tptr = NULL;
1304                         goto done;
1305                 }
1306                 tm_enabled = 1;
1307         }
1308
1309         /*
1310          * Now check to see whether this bus is in target mode already.
1311          *
1312          * If not, a later role change into target mode will finish the job.
1313          */
1314         if (tm_enabled == 0) {
1315                 ISP_SET_PC(isp, bus, tm_enable_defer, 1);
1316                 ccb->ccb_h.status = CAM_REQ_CMP;
1317                 xpt_print(ccb->ccb_h.path, "Target Mode not enabled yet- lun enable deferred\n");
1318                 goto done1;
1319         }
1320
1321         /*
1322          * Enable the lun.
1323          */
1324         ccb->ccb_h.status = isp_enable_deferred(isp, bus, lun);
1325
1326 done:
1327         if (ccb->ccb_h.status != CAM_REQ_CMP)  {
1328                 if (tptr) {
1329                         destroy_lun_state(isp, tptr);
1330                         tptr = NULL;
1331                 }
1332         } else {
1333                 tptr->enabled = 1;
1334         }
1335 done1:
1336         if (tptr) {
1337                 rls_lun_statep(isp, tptr);
1338         }
1339
1340         /*
1341          * And we're outta here....
1342          */
1343         isp_tmunlk(isp);
1344         xpt_done(ccb);
1345 }
1346
1347 static cam_status
1348 isp_enable_deferred_luns(ispsoftc_t *isp, int bus)
1349 {
1350         tstate_t *tptr = NULL;
1351         struct tslist *lhp;
1352         int i, n;
1353
1354
1355         ISP_GET_PC(isp, bus, tm_enabled, i);
1356         if (i == 1) {
1357                 return (CAM_REQ_CMP);
1358         }
1359         ISP_GET_PC(isp, bus, tm_enable_defer, i);
1360         if (i == 0) {
1361                 return (CAM_REQ_CMP);
1362         }
1363         /*
1364          * If this succeeds, it will set tm_enable
1365          */
1366         if (isp_enable_target_mode(isp, bus)) {
1367                 return (CAM_REQ_CMP_ERR);
1368         }
1369         isp_tmlock(isp, "isp_enable_deferred_luns");
1370         for (n = i = 0; i < LUN_HASH_SIZE; i++) {
1371                 ISP_GET_PC_ADDR(isp, bus, lun_hash[i], lhp);
1372                 SLIST_FOREACH(tptr, lhp, next) {
1373                         tptr->hold++;
1374                         if (tptr->enabled == 0) {
1375                                 if (isp_enable_deferred(isp, bus, tptr->ts_lun) == CAM_REQ_CMP) {
1376                                         tptr->enabled = 1;
1377                                         n++;
1378                                 }
1379                         } else {
1380                                 n++;
1381                         }
1382                         tptr->hold--;
1383                 }
1384         }
1385         isp_tmunlk(isp);
1386         if (n == 0) {
1387                 return (CAM_REQ_CMP_ERR);
1388         }
1389         ISP_SET_PC(isp, bus, tm_enable_defer, 0);
1390         return (CAM_REQ_CMP);
1391 }
1392
1393 static cam_status
1394 isp_enable_deferred(ispsoftc_t *isp, int bus, lun_id_t lun)
1395 {
1396         cam_status status;
1397         int luns_already_enabled;
1398
1399         ISP_GET_PC(isp, bus, tm_luns_enabled, luns_already_enabled);
1400         isp_prt(isp, ISP_LOGTINFO, "%s: bus %d lun %jx luns_enabled %d", __func__, bus, (uintmax_t)lun, luns_already_enabled);
1401         if (IS_24XX(isp) || (IS_FC(isp) && luns_already_enabled)) {
1402                 status = CAM_REQ_CMP;
1403         } else {
1404                 int cmd_cnt, not_cnt;
1405
1406                 if (IS_23XX(isp)) {
1407                         cmd_cnt = DFLT_CMND_CNT;
1408                         not_cnt = DFLT_INOT_CNT;
1409                 } else {
1410                         cmd_cnt = 64;
1411                         not_cnt = 8;
1412                 }
1413                 status = CAM_REQ_INPROG;
1414                 isp->isp_osinfo.rptr = &status;
1415                 if (isp_lun_cmd(isp, RQSTYPE_ENABLE_LUN, bus, lun == CAM_LUN_WILDCARD? 0 : lun, cmd_cnt, not_cnt)) {
1416                         status = CAM_RESRC_UNAVAIL;
1417                 } else {
1418                         mtx_sleep(&status, &isp->isp_lock, PRIBIO, "isp_enable_deferred", 0);
1419                 }
1420                 isp->isp_osinfo.rptr = NULL;
1421         }
1422         if (status == CAM_REQ_CMP) {
1423                 ISP_SET_PC(isp, bus, tm_luns_enabled, 1);
1424                 isp_prt(isp, ISP_LOGCONFIG|ISP_LOGTINFO, "bus %d lun %jx now enabled for target mode", bus, (uintmax_t)lun);
1425         }
1426         return (status);
1427 }
1428
1429 static void
1430 isp_disable_lun(ispsoftc_t *isp, union ccb *ccb)
1431 {
1432         tstate_t *tptr = NULL;
1433         int bus;
1434         cam_status status;
1435         target_id_t target;
1436         lun_id_t lun;
1437
1438         bus = XS_CHANNEL(ccb);
1439         target = ccb->ccb_h.target_id;
1440         lun = ccb->ccb_h.target_lun;
1441         ISP_PATH_PRT(isp, ISP_LOGTDEBUG0|ISP_LOGCONFIG, ccb->ccb_h.path, "disabling lun %u\n", lun);
1442         if (target != CAM_TARGET_WILDCARD && target != 0) {
1443                 ccb->ccb_h.status = CAM_TID_INVALID;
1444                 xpt_done(ccb);
1445                 return;
1446         }
1447
1448         if (target == CAM_TARGET_WILDCARD && lun != CAM_LUN_WILDCARD) {
1449                 ccb->ccb_h.status = CAM_LUN_INVALID;
1450                 xpt_done(ccb);
1451                 return;
1452         }
1453
1454         if (target != CAM_TARGET_WILDCARD && lun == CAM_LUN_WILDCARD) {
1455                 ccb->ccb_h.status = CAM_LUN_INVALID;
1456                 xpt_done(ccb);
1457                 return;
1458         }
1459
1460         /*
1461          * See if we're busy disabling a lun now.
1462          */
1463         isp_tmlock(isp, "isp_disable_lun");
1464         status = CAM_REQ_INPROG;
1465
1466         /*
1467          * Find the state pointer.
1468          */
1469         if ((tptr = get_lun_statep(isp, bus, lun)) == NULL) {
1470                 status = CAM_PATH_INVALID;
1471                 goto done;
1472         }
1473
1474         /*
1475          * If we're a 24XX card, we're done.
1476          */
1477         if (IS_24XX(isp)) {
1478                 status = CAM_REQ_CMP;
1479                 goto done;
1480         }
1481
1482         /*
1483          * For SCC FW, we only deal with lun zero.
1484          */
1485         if (IS_FC(isp) && lun > 0) {
1486                 status = CAM_REQ_CMP;
1487                 goto done;
1488         }
1489         isp->isp_osinfo.rptr = &status;
1490         if (isp_lun_cmd(isp, RQSTYPE_ENABLE_LUN, bus, lun, 0, 0)) {
1491                 status = CAM_RESRC_UNAVAIL;
1492         } else {
1493                 mtx_sleep(ccb, &isp->isp_lock, PRIBIO, "isp_disable_lun", 0);
1494         }
1495         isp->isp_osinfo.rptr = NULL;
1496 done:
1497         if (status == CAM_REQ_CMP) {
1498                 tptr->enabled = 0;
1499                 /*
1500                  * If we have no more luns enabled for this bus,
1501                  * delete all tracked wwns for it (if we are FC), 
1502                  * and disable target mode.
1503                  */
1504                 if (is_any_lun_enabled(isp, bus) == 0) {
1505                         isp_del_all_wwn_entries(isp, bus);
1506                         if (isp_disable_target_mode(isp, bus)) {
1507                                 status = CAM_REQ_CMP_ERR;
1508                         }
1509                 }
1510         }
1511         ccb->ccb_h.status = status;
1512         if (status == CAM_REQ_CMP) {
1513                 destroy_lun_state(isp, tptr);
1514                 xpt_print(ccb->ccb_h.path, "lun now disabled for target mode\n");
1515         } else {
1516                 if (tptr)
1517                         rls_lun_statep(isp, tptr);
1518         }
1519         isp_tmunlk(isp);
1520         xpt_done(ccb);
1521 }
1522
1523 static int
1524 isp_enable_target_mode(ispsoftc_t *isp, int bus)
1525 {
1526         int tm_enabled;
1527
1528         ISP_GET_PC(isp, bus, tm_enabled, tm_enabled);
1529         if (tm_enabled != 0) {
1530                 return (0);
1531         }
1532         if (IS_SCSI(isp)) {
1533                 mbreg_t mbs;
1534                 MBSINIT(&mbs, MBOX_ENABLE_TARGET_MODE, MBLOGALL, 0);
1535                 mbs.param[0] = MBOX_ENABLE_TARGET_MODE;
1536                 mbs.param[1] = ENABLE_TARGET_FLAG|ENABLE_TQING_FLAG;
1537                 mbs.param[2] = bus << 7;
1538                 if (isp_control(isp, ISPCTL_RUN_MBOXCMD, &mbs) < 0 || mbs.param[0] != MBOX_COMMAND_COMPLETE) {
1539                         isp_prt(isp, ISP_LOGERR, "Unable to enable Target Role on Bus %d", bus);
1540                         return (EIO);
1541                 }
1542         }
1543         ISP_SET_PC(isp, bus, tm_enabled, 1);
1544         isp_prt(isp, ISP_LOGINFO, "Target Role enabled on Bus %d", bus);
1545         return (0);
1546 }
1547
1548 static int
1549 isp_disable_target_mode(ispsoftc_t *isp, int bus)
1550 {
1551         int tm_enabled;
1552
1553         ISP_GET_PC(isp, bus, tm_enabled, tm_enabled);
1554         if (tm_enabled == 0) {
1555                 return (0);
1556         }
1557         if (IS_SCSI(isp)) {
1558                 mbreg_t mbs;
1559                 MBSINIT(&mbs, MBOX_ENABLE_TARGET_MODE, MBLOGALL, 0);
1560                 mbs.param[2] = bus << 7;
1561                 if (isp_control(isp, ISPCTL_RUN_MBOXCMD, &mbs) < 0 || mbs.param[0] != MBOX_COMMAND_COMPLETE) {
1562                         isp_prt(isp, ISP_LOGERR, "Unable to disable Target Role on Bus %d", bus);
1563                         return (EIO);
1564                 }
1565         }
1566         ISP_SET_PC(isp, bus, tm_enabled, 0);
1567         isp_prt(isp, ISP_LOGINFO, "Target Role disabled on Bus %d", bus);
1568         return (0);
1569 }
1570
1571 static void
1572 isp_ledone(ispsoftc_t *isp, lun_entry_t *lep)
1573 {
1574         uint32_t *rptr;
1575
1576         rptr = isp->isp_osinfo.rptr;
1577         if (lep->le_status != LUN_OK) {
1578                 isp_prt(isp, ISP_LOGERR, "ENABLE/MODIFY LUN returned 0x%x", lep->le_status);
1579                 if (rptr) {
1580                         *rptr = CAM_REQ_CMP_ERR;
1581                         wakeup_one(rptr);
1582                 }
1583         } else {
1584                 if (rptr) {
1585                         *rptr = CAM_REQ_CMP;
1586                         wakeup_one(rptr);
1587                 }
1588         }
1589 }
1590
1591 static void
1592 isp_target_start_ctio(ispsoftc_t *isp, union ccb *ccb, enum Start_Ctio_How how)
1593 {
1594         int fctape, sendstatus, resid;
1595         tstate_t *tptr;
1596         fcparam *fcp;
1597         atio_private_data_t *atp;
1598         struct ccb_scsiio *cso;
1599         uint32_t dmaresult, handle, xfrlen, sense_length, tmp;
1600         uint8_t local[QENTRY_LEN];
1601
1602         tptr = get_lun_statep(isp, XS_CHANNEL(ccb), XS_LUN(ccb));
1603         if (tptr == NULL) {
1604                 tptr = get_lun_statep(isp, XS_CHANNEL(ccb), CAM_LUN_WILDCARD);
1605                 if (tptr == NULL) {
1606                         isp_prt(isp, ISP_LOGERR, "%s: [0x%x] cannot find tstate pointer", __func__, ccb->csio.tag_id);
1607                         ccb->ccb_h.status = CAM_DEV_NOT_THERE;
1608                         xpt_done(ccb);
1609                         return;
1610                 }
1611         }
1612         isp_prt(isp, ISP_LOGTDEBUG0, "%s: ENTRY[0x%x] how %u xfrlen %u sendstatus %d sense_len %u", __func__, ccb->csio.tag_id, how, ccb->csio.dxfer_len,
1613             (ccb->ccb_h.flags & CAM_SEND_STATUS) != 0, ((ccb->ccb_h.flags & CAM_SEND_SENSE)? ccb->csio.sense_len : 0));
1614
1615         switch (how) {
1616         case FROM_TIMER:
1617         case FROM_CAM:
1618                 /*
1619                  * Insert at the tail of the list, if any, waiting CTIO CCBs
1620                  */
1621                 TAILQ_INSERT_TAIL(&tptr->waitq, &ccb->ccb_h, periph_links.tqe); 
1622                 break;
1623         case FROM_SRR:
1624         case FROM_CTIO_DONE:
1625                 TAILQ_INSERT_HEAD(&tptr->waitq, &ccb->ccb_h, periph_links.tqe); 
1626                 break;
1627         }
1628
1629         while (TAILQ_FIRST(&tptr->waitq) != NULL) {
1630                 ccb = (union ccb *) TAILQ_FIRST(&tptr->waitq);
1631                 TAILQ_REMOVE(&tptr->waitq, &ccb->ccb_h, periph_links.tqe);
1632
1633                 cso = &ccb->csio;
1634                 xfrlen = cso->dxfer_len;
1635                 if (xfrlen == 0) {
1636                         if ((ccb->ccb_h.flags & CAM_SEND_STATUS) == 0) {
1637                                 ISP_PATH_PRT(isp, ISP_LOGERR, ccb->ccb_h.path, "a data transfer length of zero but no status to send is wrong\n");
1638                                 ccb->ccb_h.status = CAM_REQ_INVALID;
1639                                 xpt_done(ccb);
1640                                 continue;
1641                         }
1642                 }
1643
1644                 atp = isp_find_atpd(isp, tptr, cso->tag_id);
1645                 if (atp == NULL) {
1646                         isp_prt(isp, ISP_LOGERR, "%s: [0x%x] cannot find private data adjunct in %s", __func__, cso->tag_id, __func__);
1647                         isp_dump_atpd(isp, tptr);
1648                         ccb->ccb_h.status = CAM_REQ_CMP_ERR;
1649                         xpt_done(ccb);
1650                         continue;
1651                 }
1652
1653                 /*
1654                  * Is this command a dead duck?
1655                  */
1656                 if (atp->dead) {
1657                         isp_prt(isp, ISP_LOGERR, "%s: [0x%x] not sending a CTIO for a dead command", __func__, cso->tag_id);
1658                         ccb->ccb_h.status = CAM_REQ_ABORTED;
1659                         xpt_done(ccb);
1660                         continue;
1661                 }
1662
1663                 /*
1664                  * Check to make sure we're still in target mode.
1665                  */
1666                 fcp = FCPARAM(isp, XS_CHANNEL(ccb));
1667                 if ((fcp->role & ISP_ROLE_TARGET) == 0) {
1668                         isp_prt(isp, ISP_LOGERR, "%s: [0x%x] stopping sending a CTIO because we're no longer in target mode", __func__, cso->tag_id);
1669                         ccb->ccb_h.status = CAM_PROVIDE_FAIL;
1670                         xpt_done(ccb);
1671                         continue;
1672                 }
1673
1674                 /*
1675                  * We're only handling ATPD_CCB_OUTSTANDING outstanding CCB at a time (one of which
1676                  * could be split into two CTIOs to split data and status).
1677                  */
1678                 if (atp->ctcnt >= ATPD_CCB_OUTSTANDING) {
1679                         isp_prt(isp, ISP_LOGTINFO, "[0x%x] handling only %d CCBs at a time (flags for this ccb: 0x%x)", cso->tag_id, ATPD_CCB_OUTSTANDING, ccb->ccb_h.flags);
1680                         TAILQ_INSERT_HEAD(&tptr->waitq, &ccb->ccb_h, periph_links.tqe); 
1681                         break;
1682                 }
1683
1684                 /*
1685                  * Does the initiator expect FC-Tape style responses?
1686                  */
1687                 if ((atp->word3 & PRLI_WD3_RETRY) && fcp->fctape_enabled) {
1688                         fctape = 1;
1689                 } else {
1690                         fctape = 0;
1691                 }
1692
1693                 /*
1694                  * If we already did the data xfer portion of a CTIO that sends data
1695                  * and status, don't do it again and do the status portion now.
1696                  */
1697                 if (atp->sendst) {
1698                         isp_prt(isp, ISP_LOGTINFO, "[0x%x] now sending synthesized status orig_dl=%u xfered=%u bit=%u",
1699                             cso->tag_id, atp->orig_datalen, atp->bytes_xfered, atp->bytes_in_transit);
1700                         xfrlen = 0;     /* we already did the data transfer */
1701                         atp->sendst = 0;
1702                 }
1703                 if (ccb->ccb_h.flags & CAM_SEND_STATUS) {
1704                         sendstatus = 1;
1705                 } else {
1706                         sendstatus = 0;
1707                 }
1708
1709                 if (ccb->ccb_h.flags & CAM_SEND_SENSE) {
1710                         KASSERT((sendstatus != 0), ("how can you have CAM_SEND_SENSE w/o CAM_SEND_STATUS?"));
1711                         /*
1712                          * Sense length is not the entire sense data structure size. Periph
1713                          * drivers don't seem to be setting sense_len to reflect the actual
1714                          * size. We'll peek inside to get the right amount.
1715                          */
1716                         sense_length = cso->sense_len;
1717
1718                         /*
1719                          * This 'cannot' happen
1720                          */
1721                         if (sense_length > (XCMD_SIZE - MIN_FCP_RESPONSE_SIZE)) {
1722                                 sense_length = XCMD_SIZE - MIN_FCP_RESPONSE_SIZE;
1723                         }
1724                 } else {
1725                         sense_length = 0;
1726                 }
1727
1728                 memset(local, 0, QENTRY_LEN);
1729
1730                 /*
1731                  * Check for overflow
1732                  */
1733                 tmp = atp->bytes_xfered + atp->bytes_in_transit + xfrlen;
1734                 if (tmp > atp->orig_datalen) {
1735                         isp_prt(isp, ISP_LOGERR, "%s: [0x%x] data overflow by %u bytes", __func__, cso->tag_id, tmp - atp->orig_datalen);
1736                         ccb->ccb_h.status = CAM_DATA_RUN_ERR;
1737                         xpt_done(ccb);
1738                         continue;
1739                 }
1740
1741                 if (IS_24XX(isp)) {
1742                         ct7_entry_t *cto = (ct7_entry_t *) local;
1743
1744                         cto->ct_header.rqs_entry_type = RQSTYPE_CTIO7;
1745                         cto->ct_header.rqs_entry_count = 1;
1746                         cto->ct_header.rqs_seqno |= ATPD_SEQ_NOTIFY_CAM;
1747                         ATPD_SET_SEQNO(cto, atp);
1748                         cto->ct_nphdl = atp->nphdl;
1749                         cto->ct_rxid = atp->tag;
1750                         cto->ct_iid_lo = atp->portid;
1751                         cto->ct_iid_hi = atp->portid >> 16;
1752                         cto->ct_oxid = atp->oxid;
1753                         cto->ct_vpidx = ISP_GET_VPIDX(isp, XS_CHANNEL(ccb));
1754                         cto->ct_timeout = 120;
1755                         cto->ct_flags = atp->tattr << CT7_TASK_ATTR_SHIFT;
1756
1757                         /*
1758                          * Mode 1, status, no data. Only possible when we are sending status, have
1759                          * no data to transfer, and any sense data can fit into a ct7_entry_t.
1760                          *
1761                          * Mode 2, status, no data. We have to use this in the case that
1762                          * the sense data won't fit into a ct7_entry_t.
1763                          *
1764                          */
1765                         if (sendstatus && xfrlen == 0) {
1766                                 cto->ct_flags |= CT7_SENDSTATUS | CT7_NO_DATA;
1767                                 resid = atp->orig_datalen - atp->bytes_xfered - atp->bytes_in_transit;
1768                                 if (sense_length <= MAXRESPLEN_24XX) {
1769                                         if (resid < 0) {
1770                                                 cto->ct_resid = -resid;
1771                                         } else if (resid > 0) {
1772                                                 cto->ct_resid = resid;
1773                                         }
1774                                         cto->ct_flags |= CT7_FLAG_MODE1;
1775                                         cto->ct_scsi_status = cso->scsi_status;
1776                                         if (resid < 0) {
1777                                                 cto->ct_scsi_status |= (FCP_RESID_OVERFLOW << 8);
1778                                         } else if (resid > 0) {
1779                                                 cto->ct_scsi_status |= (FCP_RESID_UNDERFLOW << 8);
1780                                         }
1781                                         if (fctape) {
1782                                                 cto->ct_flags |= CT7_CONFIRM|CT7_EXPLCT_CONF;
1783                                         }
1784                                         if (sense_length) {
1785                                                 cto->ct_scsi_status |= (FCP_SNSLEN_VALID << 8);
1786                                                 cto->rsp.m1.ct_resplen = cto->ct_senselen = sense_length;
1787                                                 memcpy(cto->rsp.m1.ct_resp, &cso->sense_data, sense_length);
1788                                         }
1789                                 } else {
1790                                         bus_addr_t addr;
1791                                         char buf[XCMD_SIZE];
1792                                         fcp_rsp_iu_t *rp;
1793
1794                                         if (atp->ests == NULL) {
1795                                                 atp->ests = isp_get_ecmd(isp);
1796                                                 if (atp->ests == NULL) {
1797                                                         TAILQ_INSERT_HEAD(&tptr->waitq, &ccb->ccb_h, periph_links.tqe); 
1798                                                         break;
1799                                                 }
1800                                         }
1801                                         memset(buf, 0, sizeof (buf));
1802                                         rp = (fcp_rsp_iu_t *)buf;
1803                                         if (fctape) {
1804                                                 cto->ct_flags |= CT7_CONFIRM|CT7_EXPLCT_CONF;
1805                                                 rp->fcp_rsp_bits |= FCP_CONF_REQ;
1806                                         }
1807                                         cto->ct_flags |= CT7_FLAG_MODE2;
1808                                         rp->fcp_rsp_scsi_status = cso->scsi_status;
1809                                         if (resid < 0) {
1810                                                 rp->fcp_rsp_resid = -resid;
1811                                                 rp->fcp_rsp_bits |= FCP_RESID_OVERFLOW;
1812                                         } else if (resid > 0) {
1813                                                 rp->fcp_rsp_resid = resid;
1814                                                 rp->fcp_rsp_bits |= FCP_RESID_UNDERFLOW;
1815                                         }
1816                                         if (sense_length) {
1817                                                 rp->fcp_rsp_snslen = sense_length;
1818                                                 cto->ct_senselen = sense_length;
1819                                                 rp->fcp_rsp_bits |= FCP_SNSLEN_VALID;
1820                                                 isp_put_fcp_rsp_iu(isp, rp, atp->ests);
1821                                                 memcpy(((fcp_rsp_iu_t *)atp->ests)->fcp_rsp_extra, &cso->sense_data, sense_length);
1822                                         } else {
1823                                                 isp_put_fcp_rsp_iu(isp, rp, atp->ests);
1824                                         }
1825                                         if (isp->isp_dblev & ISP_LOGTDEBUG1) {
1826                                                 isp_print_bytes(isp, "FCP Response Frame After Swizzling", MIN_FCP_RESPONSE_SIZE + sense_length, atp->ests);
1827                                         }
1828                                         addr = isp->isp_osinfo.ecmd_dma;
1829                                         addr += ((((isp_ecmd_t *)atp->ests) - isp->isp_osinfo.ecmd_base) * XCMD_SIZE);
1830                                         isp_prt(isp, ISP_LOGTDEBUG0, "%s: ests base %p vaddr %p ecmd_dma %jx addr %jx len %u", __func__, isp->isp_osinfo.ecmd_base, atp->ests,
1831                                             (uintmax_t) isp->isp_osinfo.ecmd_dma, (uintmax_t)addr, MIN_FCP_RESPONSE_SIZE + sense_length);
1832                                         cto->rsp.m2.ct_datalen = MIN_FCP_RESPONSE_SIZE + sense_length;
1833                                         cto->rsp.m2.ct_fcp_rsp_iudata.ds_base = DMA_LO32(addr);
1834                                         cto->rsp.m2.ct_fcp_rsp_iudata.ds_basehi = DMA_HI32(addr);
1835                                         cto->rsp.m2.ct_fcp_rsp_iudata.ds_count = MIN_FCP_RESPONSE_SIZE + sense_length;
1836                                 }
1837                                 if (sense_length) {
1838                                         isp_prt(isp, ISP_LOGTDEBUG0, "%s: CTIO7[0x%x] seq %u nc %d CDB0=%x sstatus=0x%x flags=0x%x resid=%d slen %u sense: %x %x/%x/%x", __func__,
1839                                             cto->ct_rxid, ATPD_GET_SEQNO(cto), ATPD_GET_NCAM(cto), atp->cdb0, cto->ct_scsi_status, cto->ct_flags, cto->ct_resid, sense_length,
1840                                             cso->sense_data.error_code, cso->sense_data.sense_buf[1], cso->sense_data.sense_buf[11], cso->sense_data.sense_buf[12]);
1841                                 } else {
1842                                         isp_prt(isp, ISP_LOGDEBUG0, "%s: CTIO7[0x%x] seq %u nc %d CDB0=%x sstatus=0x%x flags=0x%x resid=%d", __func__,
1843                                             cto->ct_rxid, ATPD_GET_SEQNO(cto), ATPD_GET_NCAM(cto), atp->cdb0, cto->ct_scsi_status, cto->ct_flags, cto->ct_resid);
1844                                 }
1845                                 atp->state = ATPD_STATE_LAST_CTIO;
1846                         }
1847
1848                         /*
1849                          * Mode 0 data transfers, *possibly* with status.
1850                          */
1851                         if (xfrlen != 0) {
1852                                 cto->ct_flags |= CT7_FLAG_MODE0;
1853                                 if ((cso->ccb_h.flags & CAM_DIR_MASK) == CAM_DIR_IN) {
1854                                         cto->ct_flags |= CT7_DATA_IN;
1855                                 } else {
1856                                         cto->ct_flags |= CT7_DATA_OUT;
1857                                 }
1858
1859                                 cto->rsp.m0.reloff = atp->bytes_xfered + atp->bytes_in_transit;
1860                                 cto->rsp.m0.ct_xfrlen = xfrlen;
1861
1862 #ifdef  DEBUG
1863                                 if (ISP_FC_PC(isp, XS_CHANNEL(ccb))->inject_lost_data_frame && xfrlen > ISP_FC_PC(isp, XS_CHANNEL(ccb))->inject_lost_data_frame) {
1864                                         isp_prt(isp, ISP_LOGWARN, "%s: truncating data frame with xfrlen %d to %d", __func__, xfrlen, xfrlen - (xfrlen >> 2));
1865                                         ISP_FC_PC(isp, XS_CHANNEL(ccb))->inject_lost_data_frame = 0;
1866                                         cto->rsp.m0.ct_xfrlen -= xfrlen >> 2;
1867                                 }
1868 #endif
1869                                 if (sendstatus) {
1870                                         resid = atp->orig_datalen - atp->bytes_xfered - xfrlen;
1871                                         if (cso->scsi_status == SCSI_STATUS_OK && resid == 0 /* && fctape == 0 */) {
1872                                                 cto->ct_flags |= CT7_SENDSTATUS;
1873                                                 atp->state = ATPD_STATE_LAST_CTIO;
1874                                                 if (fctape) {
1875                                                         cto->ct_flags |= CT7_CONFIRM|CT7_EXPLCT_CONF;
1876                                                 }
1877                                         } else {
1878                                                 atp->sendst = 1;        /* send status later */
1879                                                 cto->ct_header.rqs_seqno &= ~ATPD_SEQ_NOTIFY_CAM;
1880                                                 atp->state = ATPD_STATE_CTIO;
1881                                         }
1882                                 } else {
1883                                         atp->state = ATPD_STATE_CTIO;
1884                                 }
1885                                 isp_prt(isp, ISP_LOGTDEBUG0, "%s: CTIO7[0x%x] seq %u nc %d CDB0=%x sstatus=0x%x flags=0x%x xfrlen=%u off=%u", __func__,
1886                                     cto->ct_rxid, ATPD_GET_SEQNO(cto), ATPD_GET_NCAM(cto), atp->cdb0, cto->ct_scsi_status, cto->ct_flags, xfrlen, atp->bytes_xfered);
1887                         }
1888                 } else if (IS_FC(isp)) {
1889                         ct2_entry_t *cto = (ct2_entry_t *) local;
1890
1891                         if (isp->isp_osinfo.sixtyfourbit)
1892                                 cto->ct_header.rqs_entry_type = RQSTYPE_CTIO3;
1893                         else
1894                                 cto->ct_header.rqs_entry_type = RQSTYPE_CTIO2;
1895                         cto->ct_header.rqs_entry_count = 1;
1896                         cto->ct_header.rqs_seqno |= ATPD_SEQ_NOTIFY_CAM;
1897                         ATPD_SET_SEQNO(cto, atp);
1898                         if (ISP_CAP_2KLOGIN(isp) == 0) {
1899                                 ((ct2e_entry_t *)cto)->ct_iid = cso->init_id;
1900                         } else {
1901                                 cto->ct_iid = cso->init_id;
1902                                 if (ISP_CAP_SCCFW(isp) == 0) {
1903                                         cto->ct_lun = ccb->ccb_h.target_lun;
1904                                 }
1905                         }
1906                         cto->ct_timeout = 10;
1907                         cto->ct_rxid = cso->tag_id;
1908
1909                         /*
1910                          * Mode 1, status, no data. Only possible when we are sending status, have
1911                          * no data to transfer, and the sense length can fit in the ct7_entry.
1912                          *
1913                          * Mode 2, status, no data. We have to use this in the case the response
1914                          * length won't fit into a ct2_entry_t.
1915                          *
1916                          * We'll fill out this structure with information as if this were a
1917                          * Mode 1. The hardware layer will create the Mode 2 FCP RSP IU as
1918                          * needed based upon this.
1919                          */
1920                         if (sendstatus && xfrlen == 0) {
1921                                 cto->ct_flags |= CT2_SENDSTATUS | CT2_NO_DATA;
1922                                 resid = atp->orig_datalen - atp->bytes_xfered - atp->bytes_in_transit;
1923                                 if (sense_length <= MAXRESPLEN) {
1924                                         if (resid < 0) {
1925                                                 cto->ct_resid = -resid;
1926                                         } else if (resid > 0) {
1927                                                 cto->ct_resid = resid;
1928                                         }
1929                                         cto->ct_flags |= CT2_FLAG_MODE1;
1930                                         cto->rsp.m1.ct_scsi_status = cso->scsi_status;
1931                                         if (resid < 0) {
1932                                                 cto->rsp.m1.ct_scsi_status |= CT2_DATA_OVER;
1933                                         } else if (resid > 0) {
1934                                                 cto->rsp.m1.ct_scsi_status |= CT2_DATA_UNDER;
1935                                         }
1936                                         if (fctape) {
1937                                                 cto->ct_flags |= CT2_CONFIRM;
1938                                         }
1939                                         if (sense_length) {
1940                                                 cto->rsp.m1.ct_scsi_status |= CT2_SNSLEN_VALID;
1941                                                 cto->rsp.m1.ct_resplen = cto->rsp.m1.ct_senselen = sense_length;
1942                                                 memcpy(cto->rsp.m1.ct_resp, &cso->sense_data, sense_length);
1943                                         }
1944                                 } else {
1945                                         bus_addr_t addr;
1946                                         char buf[XCMD_SIZE];
1947                                         fcp_rsp_iu_t *rp;
1948
1949                                         if (atp->ests == NULL) {
1950                                                 atp->ests = isp_get_ecmd(isp);
1951                                                 if (atp->ests == NULL) {
1952                                                         TAILQ_INSERT_HEAD(&tptr->waitq, &ccb->ccb_h, periph_links.tqe); 
1953                                                         break;
1954                                                 }
1955                                         }
1956                                         memset(buf, 0, sizeof (buf));
1957                                         rp = (fcp_rsp_iu_t *)buf;
1958                                         if (fctape) {
1959                                                 cto->ct_flags |= CT2_CONFIRM;
1960                                                 rp->fcp_rsp_bits |= FCP_CONF_REQ;
1961                                         }
1962                                         cto->ct_flags |= CT2_FLAG_MODE2;
1963                                         rp->fcp_rsp_scsi_status = cso->scsi_status;
1964                                         if (resid < 0) {
1965                                                 rp->fcp_rsp_resid = -resid;
1966                                                 rp->fcp_rsp_bits |= FCP_RESID_OVERFLOW;
1967                                         } else if (resid > 0) {
1968                                                 rp->fcp_rsp_resid = resid;
1969                                                 rp->fcp_rsp_bits |= FCP_RESID_UNDERFLOW;
1970                                         }
1971                                         if (sense_length) {
1972                                                 rp->fcp_rsp_snslen = sense_length;
1973                                                 rp->fcp_rsp_bits |= FCP_SNSLEN_VALID;
1974                                                 isp_put_fcp_rsp_iu(isp, rp, atp->ests);
1975                                                 memcpy(((fcp_rsp_iu_t *)atp->ests)->fcp_rsp_extra, &cso->sense_data, sense_length);
1976                                         } else {
1977                                                 isp_put_fcp_rsp_iu(isp, rp, atp->ests);
1978                                         }
1979                                         if (isp->isp_dblev & ISP_LOGTDEBUG1) {
1980                                                 isp_print_bytes(isp, "FCP Response Frame After Swizzling", MIN_FCP_RESPONSE_SIZE + sense_length, atp->ests);
1981                                         }
1982                                         addr = isp->isp_osinfo.ecmd_dma;
1983                                         addr += ((((isp_ecmd_t *)atp->ests) - isp->isp_osinfo.ecmd_base) * XCMD_SIZE);
1984                                         isp_prt(isp, ISP_LOGTDEBUG0, "%s: ests base %p vaddr %p ecmd_dma %jx addr %jx len %u", __func__, isp->isp_osinfo.ecmd_base, atp->ests,
1985                                             (uintmax_t) isp->isp_osinfo.ecmd_dma, (uintmax_t)addr, MIN_FCP_RESPONSE_SIZE + sense_length);
1986                                         cto->rsp.m2.ct_datalen = MIN_FCP_RESPONSE_SIZE + sense_length;
1987                                         if (isp->isp_osinfo.sixtyfourbit) {
1988                                                 cto->rsp.m2.u.ct_fcp_rsp_iudata_64.ds_base = DMA_LO32(addr);
1989                                                 cto->rsp.m2.u.ct_fcp_rsp_iudata_64.ds_basehi = DMA_HI32(addr);
1990                                                 cto->rsp.m2.u.ct_fcp_rsp_iudata_64.ds_count = MIN_FCP_RESPONSE_SIZE + sense_length;
1991                                         } else {
1992                                                 cto->rsp.m2.u.ct_fcp_rsp_iudata_32.ds_base = DMA_LO32(addr);
1993                                                 cto->rsp.m2.u.ct_fcp_rsp_iudata_32.ds_count = MIN_FCP_RESPONSE_SIZE + sense_length;
1994                                         }
1995                                 }
1996                                 if (sense_length) {
1997                                         isp_prt(isp, ISP_LOGTDEBUG0, "%s: CTIO2[0x%x] seq %u nc %d CDB0=%x sstatus=0x%x flags=0x%x resid=%d sense: %x %x/%x/%x", __func__,
1998                                             cto->ct_rxid, ATPD_GET_SEQNO(cto), ATPD_GET_NCAM(cto), atp->cdb0, cso->scsi_status, cto->ct_flags, cto->ct_resid,
1999                                             cso->sense_data.error_code, cso->sense_data.sense_buf[1], cso->sense_data.sense_buf[11], cso->sense_data.sense_buf[12]);
2000                                 } else {
2001                                         isp_prt(isp, ISP_LOGTDEBUG0, "%s: CTIO2[0x%x] seq %u nc %d CDB0=%x sstatus=0x%x flags=0x%x resid=%d", __func__, cto->ct_rxid,
2002                                             ATPD_GET_SEQNO(cto), ATPD_GET_NCAM(cto), atp->cdb0, cso->scsi_status, cto->ct_flags, cto->ct_resid);
2003                                 }
2004                                 atp->state = ATPD_STATE_LAST_CTIO;
2005                         }
2006
2007                         if (xfrlen != 0) {
2008                                 cto->ct_flags |= CT2_FLAG_MODE0;
2009                                 if ((cso->ccb_h.flags & CAM_DIR_MASK) == CAM_DIR_IN) {
2010                                         cto->ct_flags |= CT2_DATA_IN;
2011                                 } else {
2012                                         cto->ct_flags |= CT2_DATA_OUT;
2013                                 }
2014
2015                                 cto->ct_reloff = atp->bytes_xfered + atp->bytes_in_transit;
2016                                 cto->rsp.m0.ct_xfrlen = xfrlen;
2017
2018                                 if (sendstatus) {
2019                                         resid = atp->orig_datalen - atp->bytes_xfered - xfrlen;
2020                                         if (cso->scsi_status == SCSI_STATUS_OK && resid == 0 /*&& fctape == 0*/) {
2021                                                 cto->ct_flags |= CT2_SENDSTATUS;
2022                                                 atp->state = ATPD_STATE_LAST_CTIO;
2023                                                 if (fctape) {
2024                                                         cto->ct_flags |= CT2_CONFIRM;
2025                                                 }
2026                                         } else {
2027                                                 atp->sendst = 1;        /* send status later */
2028                                                 cto->ct_header.rqs_seqno &= ~ATPD_SEQ_NOTIFY_CAM;
2029                                                 atp->state = ATPD_STATE_CTIO;
2030                                         }
2031                                 } else {
2032                                         atp->state = ATPD_STATE_CTIO;
2033                                 }
2034                         }
2035                         isp_prt(isp, ISP_LOGTDEBUG0, "%s: CTIO2[%x] seq %u nc %d CDB0=%x scsi status %x flags %x resid %d xfrlen %u offset %u", __func__, cto->ct_rxid,
2036                             ATPD_GET_SEQNO(cto), ATPD_GET_NCAM(cto), atp->cdb0, cso->scsi_status, cto->ct_flags, cto->ct_resid, cso->dxfer_len, atp->bytes_xfered);
2037                 } else {
2038                         ct_entry_t *cto = (ct_entry_t *) local;
2039
2040                         cto->ct_header.rqs_entry_type = RQSTYPE_CTIO;
2041                         cto->ct_header.rqs_entry_count = 1;
2042                         cto->ct_header.rqs_seqno |= ATPD_SEQ_NOTIFY_CAM;
2043                         ATPD_SET_SEQNO(cto, atp);
2044                         cto->ct_iid = cso->init_id;
2045                         cto->ct_iid |= XS_CHANNEL(ccb) << 7;
2046                         cto->ct_tgt = ccb->ccb_h.target_id;
2047                         cto->ct_lun = ccb->ccb_h.target_lun;
2048                         cto->ct_fwhandle = cso->tag_id;
2049                         if (atp->rxid) {
2050                                 cto->ct_tag_val = atp->rxid;
2051                                 cto->ct_flags |= CT_TQAE;
2052                         }
2053                         if (ccb->ccb_h.flags & CAM_DIS_DISCONNECT) {
2054                                 cto->ct_flags |= CT_NODISC;
2055                         }
2056                         if (cso->dxfer_len == 0) {
2057                                 cto->ct_flags |= CT_NO_DATA;
2058                         } else if ((cso->ccb_h.flags & CAM_DIR_MASK) == CAM_DIR_IN) {
2059                                 cto->ct_flags |= CT_DATA_IN;
2060                         } else {
2061                                 cto->ct_flags |= CT_DATA_OUT;
2062                         }
2063                         if (ccb->ccb_h.flags & CAM_SEND_STATUS) {
2064                                 cto->ct_flags |= CT_SENDSTATUS|CT_CCINCR;
2065                                 cto->ct_scsi_status = cso->scsi_status;
2066                                 cto->ct_resid = atp->orig_datalen - atp->bytes_xfered - atp->bytes_in_transit - xfrlen;
2067                                 isp_prt(isp, ISP_LOGTDEBUG0, "%s: CTIO[%x] seq %u nc %d scsi status %x resid %d tag_id %x", __func__,
2068                                     cto->ct_fwhandle, ATPD_GET_SEQNO(cto), ATPD_GET_NCAM(cto), cso->scsi_status, cso->resid, cso->tag_id);
2069                         }
2070                         ccb->ccb_h.flags &= ~CAM_SEND_SENSE;
2071                         cto->ct_timeout = 10;
2072                 }
2073
2074                 if (isp_get_pcmd(isp, ccb)) {
2075                         ISP_PATH_PRT(isp, ISP_LOGWARN, ccb->ccb_h.path, "out of PCMDs\n");
2076                         TAILQ_INSERT_HEAD(&tptr->waitq, &ccb->ccb_h, periph_links.tqe); 
2077                         break;
2078                 }
2079                 if (isp_allocate_xs_tgt(isp, ccb, &handle)) {
2080                         ISP_PATH_PRT(isp, ISP_LOGWARN, ccb->ccb_h.path, "No XFLIST pointers for %s\n", __func__);
2081                         TAILQ_INSERT_HEAD(&tptr->waitq, &ccb->ccb_h, periph_links.tqe); 
2082                         isp_free_pcmd(isp, ccb);
2083                         break;
2084                 }
2085                 atp->bytes_in_transit += xfrlen;
2086                 PISP_PCMD(ccb)->datalen = xfrlen;
2087
2088
2089                 /*
2090                  * Call the dma setup routines for this entry (and any subsequent
2091                  * CTIOs) if there's data to move, and then tell the f/w it's got
2092                  * new things to play with. As with isp_start's usage of DMA setup,
2093                  * any swizzling is done in the machine dependent layer. Because
2094                  * of this, we put the request onto the queue area first in native
2095                  * format.
2096                  */
2097
2098                 if (IS_24XX(isp)) {
2099                         ct7_entry_t *cto = (ct7_entry_t *) local;
2100                         cto->ct_syshandle = handle;
2101                 } else if (IS_FC(isp)) {
2102                         ct2_entry_t *cto = (ct2_entry_t *) local;
2103                         cto->ct_syshandle = handle;
2104                 } else {
2105                         ct_entry_t *cto = (ct_entry_t *) local;
2106                         cto->ct_syshandle = handle;
2107                 }
2108
2109                 dmaresult = ISP_DMASETUP(isp, cso, (ispreq_t *) local);
2110                 if (dmaresult != CMD_QUEUED) {
2111                         isp_destroy_tgt_handle(isp, handle);
2112                         isp_free_pcmd(isp, ccb);
2113                         if (dmaresult == CMD_EAGAIN) {
2114                                 TAILQ_INSERT_HEAD(&tptr->waitq, &ccb->ccb_h, periph_links.tqe); 
2115                                 break;
2116                         }
2117                         ccb->ccb_h.status = CAM_REQ_CMP_ERR;
2118                         xpt_done(ccb);
2119                         continue;
2120                 }
2121                 isp->isp_nactive++;
2122                 ccb->ccb_h.status = CAM_REQ_INPROG | CAM_SIM_QUEUED;
2123                 if (xfrlen) {
2124                         ccb->ccb_h.spriv_field0 = atp->bytes_xfered;
2125                 } else {
2126                         ccb->ccb_h.spriv_field0 = ~0;
2127                 }
2128                 atp->ctcnt++;
2129                 atp->seqno++;
2130         }
2131         rls_lun_statep(isp, tptr);
2132 }
2133
2134 static void
2135 isp_refire_putback_atio(void *arg)
2136 {
2137         union ccb *ccb = arg;
2138
2139         ISP_ASSERT_LOCKED((ispsoftc_t *)XS_ISP(ccb));
2140         isp_target_putback_atio(ccb);
2141 }
2142
2143 static void
2144 isp_refire_notify_ack(void *arg)
2145 {
2146         isp_tna_t *tp  = arg;
2147         ispsoftc_t *isp = tp->isp;
2148
2149         ISP_ASSERT_LOCKED(isp);
2150         if (isp_notify_ack(isp, tp->not)) {
2151                 callout_schedule(&tp->timer, 5);
2152         } else {
2153                 free(tp, M_DEVBUF);
2154         }
2155 }
2156
2157
2158 static void
2159 isp_target_putback_atio(union ccb *ccb)
2160 {
2161         ispsoftc_t *isp;
2162         struct ccb_scsiio *cso;
2163         void *qe;
2164
2165         isp = XS_ISP(ccb);
2166
2167         qe = isp_getrqentry(isp);
2168         if (qe == NULL) {
2169                 xpt_print(ccb->ccb_h.path,
2170                     "%s: Request Queue Overflow\n", __func__);
2171                 callout_reset(&PISP_PCMD(ccb)->wdog, 10,
2172                     isp_refire_putback_atio, ccb);
2173                 return;
2174         }
2175         memset(qe, 0, QENTRY_LEN);
2176         cso = &ccb->csio;
2177         if (IS_FC(isp)) {
2178                 at2_entry_t local, *at = &local;
2179                 ISP_MEMZERO(at, sizeof (at2_entry_t));
2180                 at->at_header.rqs_entry_type = RQSTYPE_ATIO2;
2181                 at->at_header.rqs_entry_count = 1;
2182                 if (ISP_CAP_SCCFW(isp)) {
2183                         at->at_scclun = (uint16_t) ccb->ccb_h.target_lun;
2184                 } else {
2185                         at->at_lun = (uint8_t) ccb->ccb_h.target_lun;
2186                 }
2187                 at->at_status = CT_OK;
2188                 at->at_rxid = cso->tag_id;
2189                 at->at_iid = cso->ccb_h.target_id;
2190                 isp_put_atio2(isp, at, qe);
2191         } else {
2192                 at_entry_t local, *at = &local;
2193                 ISP_MEMZERO(at, sizeof (at_entry_t));
2194                 at->at_header.rqs_entry_type = RQSTYPE_ATIO;
2195                 at->at_header.rqs_entry_count = 1;
2196                 at->at_iid = cso->init_id;
2197                 at->at_iid |= XS_CHANNEL(ccb) << 7;
2198                 at->at_tgt = cso->ccb_h.target_id;
2199                 at->at_lun = cso->ccb_h.target_lun;
2200                 at->at_status = CT_OK;
2201                 at->at_tag_val = AT_GET_TAG(cso->tag_id);
2202                 at->at_handle = AT_GET_HANDLE(cso->tag_id);
2203                 isp_put_atio(isp, at, qe);
2204         }
2205         ISP_TDQE(isp, "isp_target_putback_atio", isp->isp_reqidx, qe);
2206         ISP_SYNC_REQUEST(isp);
2207         isp_complete_ctio(ccb);
2208 }
2209
2210 static void
2211 isp_complete_ctio(union ccb *ccb)
2212 {
2213         if ((ccb->ccb_h.status & CAM_STATUS_MASK) != CAM_REQ_INPROG) {
2214                 ccb->ccb_h.status &= ~CAM_SIM_QUEUED;
2215                 xpt_done(ccb);
2216         }
2217 }
2218
2219 /*
2220  * Handle ATIO stuff that the generic code can't.
2221  * This means handling CDBs.
2222  */
2223
2224 static void
2225 isp_handle_platform_atio(ispsoftc_t *isp, at_entry_t *aep)
2226 {
2227         tstate_t *tptr;
2228         int status, bus;
2229         struct ccb_accept_tio *atiop;
2230         atio_private_data_t *atp;
2231
2232         /*
2233          * The firmware status (except for the QLTM_SVALID bit)
2234          * indicates why this ATIO was sent to us.
2235          *
2236          * If QLTM_SVALID is set, the firmware has recommended Sense Data.
2237          *
2238          * If the DISCONNECTS DISABLED bit is set in the flags field,
2239          * we're still connected on the SCSI bus.
2240          */
2241         status = aep->at_status;
2242         if ((status & ~QLTM_SVALID) == AT_PHASE_ERROR) {
2243                 /*
2244                  * Bus Phase Sequence error. We should have sense data
2245                  * suggested by the f/w. I'm not sure quite yet what
2246                  * to do about this for CAM.
2247                  */
2248                 isp_prt(isp, ISP_LOGWARN, "PHASE ERROR");
2249                 isp_endcmd(isp, aep, SCSI_STATUS_BUSY, 0);
2250                 return;
2251         }
2252         if ((status & ~QLTM_SVALID) != AT_CDB) {
2253                 isp_prt(isp, ISP_LOGWARN, "bad atio (0x%x) leaked to platform", status);
2254                 isp_endcmd(isp, aep, SCSI_STATUS_BUSY, 0);
2255                 return;
2256         }
2257
2258         bus = GET_BUS_VAL(aep->at_iid);
2259         tptr = get_lun_statep(isp, bus, aep->at_lun);
2260         if (tptr == NULL) {
2261                 tptr = get_lun_statep(isp, bus, CAM_LUN_WILDCARD);
2262                 if (tptr == NULL) {
2263                         /*
2264                          * Because we can't autofeed sense data back with
2265                          * a command for parallel SCSI, we can't give back
2266                          * a CHECK CONDITION. We'll give back a BUSY status
2267                          * instead. This works out okay because the only
2268                          * time we should, in fact, get this, is in the
2269                          * case that somebody configured us without the
2270                          * blackhole driver, so they get what they deserve.
2271                          */
2272                         isp_endcmd(isp, aep, SCSI_STATUS_BUSY, 0);
2273                         return;
2274                 }
2275         }
2276
2277         atp = isp_get_atpd(isp, tptr, aep->at_handle);
2278         atiop = (struct ccb_accept_tio *) SLIST_FIRST(&tptr->atios);
2279         if (atiop == NULL || atp == NULL) {
2280                 /*
2281                  * Because we can't autofeed sense data back with
2282                  * a command for parallel SCSI, we can't give back
2283                  * a CHECK CONDITION. We'll give back a QUEUE FULL status
2284                  * instead. This works out okay because the only time we
2285                  * should, in fact, get this, is in the case that we've
2286                  * run out of ATIOS.
2287                  */
2288                 xpt_print(tptr->owner, "no %s for lun %d from initiator %d\n", (atp == NULL && atiop == NULL)? "ATIOs *or* ATPS" :
2289                     ((atp == NULL)? "ATPs" : "ATIOs"), aep->at_lun, aep->at_iid);
2290                 isp_endcmd(isp, aep, SCSI_STATUS_BUSY, 0);
2291                 if (atp) {
2292                         isp_put_atpd(isp, tptr, atp);
2293                 }
2294                 rls_lun_statep(isp, tptr);
2295                 return;
2296         }
2297         atp->rxid = aep->at_tag_val;
2298         atp->state = ATPD_STATE_ATIO;
2299         SLIST_REMOVE_HEAD(&tptr->atios, sim_links.sle);
2300         tptr->atio_count--;
2301         ISP_PATH_PRT(isp, ISP_LOGTDEBUG2, atiop->ccb_h.path, "Take FREE ATIO count now %d\n", tptr->atio_count);
2302         atiop->ccb_h.target_id = aep->at_tgt;
2303         atiop->ccb_h.target_lun = aep->at_lun;
2304         if (aep->at_flags & AT_NODISC) {
2305                 atiop->ccb_h.flags |= CAM_DIS_DISCONNECT;
2306         } else {
2307                 atiop->ccb_h.flags &= ~CAM_DIS_DISCONNECT;
2308         }
2309
2310         if (status & QLTM_SVALID) {
2311                 size_t amt = ISP_MIN(QLTM_SENSELEN, sizeof (atiop->sense_data));
2312                 atiop->sense_len = amt;
2313                 ISP_MEMCPY(&atiop->sense_data, aep->at_sense, amt);
2314         } else {
2315                 atiop->sense_len = 0;
2316         }
2317
2318         atiop->init_id = GET_IID_VAL(aep->at_iid);
2319         atiop->cdb_len = aep->at_cdblen;
2320         ISP_MEMCPY(atiop->cdb_io.cdb_bytes, aep->at_cdb, aep->at_cdblen);
2321         atiop->ccb_h.status = CAM_CDB_RECVD;
2322         /*
2323          * Construct a tag 'id' based upon tag value (which may be 0..255)
2324          * and the handle (which we have to preserve).
2325          */
2326         atiop->tag_id = atp->tag;
2327         if (aep->at_flags & AT_TQAE) {
2328                 atiop->tag_action = aep->at_tag_type;
2329                 atiop->ccb_h.status |= CAM_TAG_ACTION_VALID;
2330         }
2331         atp->orig_datalen = 0;
2332         atp->bytes_xfered = 0;
2333         atp->lun = aep->at_lun;
2334         atp->nphdl = aep->at_iid;
2335         atp->portid = PORT_NONE;
2336         atp->oxid = 0;
2337         atp->cdb0 = atiop->cdb_io.cdb_bytes[0];
2338         atp->tattr = aep->at_tag_type;
2339         atp->state = ATPD_STATE_CAM;
2340         isp_prt(isp, ISP_LOGTDEBUG0, "ATIO[0x%x] CDB=0x%x lun %d", aep->at_tag_val, atp->cdb0, atp->lun);
2341         rls_lun_statep(isp, tptr);
2342 }
2343
2344 static void
2345 isp_handle_platform_atio2(ispsoftc_t *isp, at2_entry_t *aep)
2346 {
2347         lun_id_t lun;
2348         fcportdb_t *lp;
2349         tstate_t *tptr;
2350         struct ccb_accept_tio *atiop;
2351         uint16_t nphdl;
2352         atio_private_data_t *atp;
2353         inot_private_data_t *ntp;
2354
2355         /*
2356          * The firmware status (except for the QLTM_SVALID bit)
2357          * indicates why this ATIO was sent to us.
2358          *
2359          * If QLTM_SVALID is set, the firmware has recommended Sense Data.
2360          */
2361         if ((aep->at_status & ~QLTM_SVALID) != AT_CDB) {
2362                 isp_prt(isp, ISP_LOGWARN, "bogus atio (0x%x) leaked to platform", aep->at_status);
2363                 isp_endcmd(isp, aep, SCSI_STATUS_BUSY, 0);
2364                 return;
2365         }
2366
2367         if (ISP_CAP_SCCFW(isp)) {
2368                 lun = aep->at_scclun;
2369         } else {
2370                 lun = aep->at_lun;
2371         }
2372         if (ISP_CAP_2KLOGIN(isp)) {
2373                 nphdl = ((at2e_entry_t *)aep)->at_iid;
2374         } else {
2375                 nphdl = aep->at_iid;
2376         }
2377         tptr = get_lun_statep(isp, 0, lun);
2378         if (tptr == NULL) {
2379                 tptr = get_lun_statep(isp, 0, CAM_LUN_WILDCARD);
2380                 if (tptr == NULL) {
2381                         isp_prt(isp, ISP_LOGWARN, "%s: [0x%x] no state pointer for lun %jx or wildcard", __func__, aep->at_rxid, (uintmax_t)lun);
2382                         if (lun == 0) {
2383                                 isp_endcmd(isp, aep, SCSI_STATUS_BUSY, 0);
2384                         } else {
2385                                 isp_endcmd(isp, aep, SCSI_STATUS_CHECK_COND | ECMD_SVALID | (0x5 << 12) | (0x25 << 16), 0);
2386                         }
2387                         return;
2388                 }
2389         }
2390
2391         /*
2392          * Start any commands pending resources first.
2393          */
2394         if (tptr->restart_queue) {
2395                 inot_private_data_t *restart_queue = tptr->restart_queue;
2396                 tptr->restart_queue = NULL;
2397                 while (restart_queue) {
2398                         ntp = restart_queue;
2399                         restart_queue = ntp->rd.nt.nt_hba;
2400                         isp_prt(isp, ISP_LOGTDEBUG0, "%s: restarting resrc deprived %x", __func__, ((at2_entry_t *)ntp->rd.data)->at_rxid);
2401                         isp_handle_platform_atio2(isp, (at2_entry_t *) ntp->rd.data);
2402                         isp_put_ntpd(isp, tptr, ntp);
2403                         /*
2404                          * If a recursion caused the restart queue to start to fill again,
2405                          * stop and splice the new list on top of the old list and restore
2406                          * it and go to noresrc.
2407                          */
2408                         if (tptr->restart_queue) {
2409                                 ntp = tptr->restart_queue;
2410                                 tptr->restart_queue = restart_queue;
2411                                 while (restart_queue->rd.nt.nt_hba) {
2412                                         restart_queue = restart_queue->rd.nt.nt_hba;
2413                                 }
2414                                 restart_queue->rd.nt.nt_hba = ntp;
2415                                 goto noresrc;
2416                         }
2417                 }
2418         }
2419
2420         atiop = (struct ccb_accept_tio *) SLIST_FIRST(&tptr->atios);
2421         if (atiop == NULL) {
2422                 goto noresrc;
2423         }
2424
2425         atp = isp_get_atpd(isp, tptr, aep->at_rxid);
2426         if (atp == NULL) {
2427                 goto noresrc;
2428         }
2429
2430         atp->state = ATPD_STATE_ATIO;
2431         SLIST_REMOVE_HEAD(&tptr->atios, sim_links.sle);
2432         tptr->atio_count--;
2433         isp_prt(isp, ISP_LOGTDEBUG2, "Take FREE ATIO count now %d", tptr->atio_count);
2434         atiop->ccb_h.target_id = FCPARAM(isp, 0)->isp_loopid;
2435         atiop->ccb_h.target_lun = lun;
2436
2437         /*
2438          * We don't get 'suggested' sense data as we do with SCSI cards.
2439          */
2440         atiop->sense_len = 0;
2441         if (ISP_CAP_2KLOGIN(isp)) {
2442                 /*
2443                  * NB: We could not possibly have 2K logins if we
2444                  * NB: also did not have SCC FW.
2445                  */
2446                 atiop->init_id = ((at2e_entry_t *)aep)->at_iid;
2447         } else {
2448                 atiop->init_id = aep->at_iid;
2449         }
2450
2451         /*
2452          * If we're not in the port database, add ourselves.
2453          */
2454         if (!IS_2100(isp) && isp_find_pdb_by_loopid(isp, 0, atiop->init_id, &lp) == 0) {
2455                 uint64_t iid =
2456                         (((uint64_t) aep->at_wwpn[0]) << 48) |
2457                         (((uint64_t) aep->at_wwpn[1]) << 32) |
2458                         (((uint64_t) aep->at_wwpn[2]) << 16) |
2459                         (((uint64_t) aep->at_wwpn[3]) <<  0);
2460                 /*
2461                  * However, make sure we delete ourselves if otherwise
2462                  * we were there but at a different loop id.
2463                  */
2464                 if (isp_find_pdb_by_wwn(isp, 0, iid, &lp)) {
2465                         isp_del_wwn_entry(isp, 0, iid, lp->handle, lp->portid);
2466                 }
2467                 isp_add_wwn_entry(isp, 0, iid, atiop->init_id, PORT_ANY, 0);
2468         }
2469         atiop->cdb_len = ATIO2_CDBLEN;
2470         ISP_MEMCPY(atiop->cdb_io.cdb_bytes, aep->at_cdb, ATIO2_CDBLEN);
2471         atiop->ccb_h.status = CAM_CDB_RECVD;
2472         atiop->tag_id = atp->tag;
2473         switch (aep->at_taskflags & ATIO2_TC_ATTR_MASK) {
2474         case ATIO2_TC_ATTR_SIMPLEQ:
2475                 atiop->ccb_h.flags |= CAM_TAG_ACTION_VALID;
2476                 atiop->tag_action = MSG_SIMPLE_Q_TAG;
2477                 break;
2478         case ATIO2_TC_ATTR_HEADOFQ:
2479                 atiop->ccb_h.flags |= CAM_TAG_ACTION_VALID;
2480                 atiop->tag_action = MSG_HEAD_OF_Q_TAG;
2481                 break;
2482         case ATIO2_TC_ATTR_ORDERED:
2483                 atiop->ccb_h.flags |= CAM_TAG_ACTION_VALID;
2484                 atiop->tag_action = MSG_ORDERED_Q_TAG;
2485                 break;
2486         case ATIO2_TC_ATTR_ACAQ:                /* ?? */
2487         case ATIO2_TC_ATTR_UNTAGGED:
2488         default:
2489                 atiop->tag_action = 0;
2490                 break;
2491         }
2492
2493         atp->orig_datalen = aep->at_datalen;
2494         atp->bytes_xfered = 0;
2495         atp->lun = lun;
2496         atp->nphdl = atiop->init_id;
2497         atp->sid = PORT_ANY;
2498         atp->oxid = aep->at_oxid;
2499         atp->cdb0 = aep->at_cdb[0];
2500         atp->tattr = aep->at_taskflags & ATIO2_TC_ATTR_MASK;
2501         atp->state = ATPD_STATE_CAM;
2502         xpt_done((union ccb *)atiop);
2503         isp_prt(isp, ISP_LOGTDEBUG0, "ATIO2[0x%x] CDB=0x%x lun %jx datalen %u", aep->at_rxid, atp->cdb0, (uintmax_t)lun, atp->orig_datalen);
2504         rls_lun_statep(isp, tptr);
2505         return;
2506 noresrc:
2507         ntp = isp_get_ntpd(isp, tptr);
2508         if (ntp == NULL) {
2509                 rls_lun_statep(isp, tptr);
2510                 isp_endcmd(isp, aep, nphdl, 0, SCSI_STATUS_BUSY, 0);
2511                 return;
2512         }
2513         memcpy(ntp->rd.data, aep, QENTRY_LEN);
2514         ntp->rd.nt.nt_hba = tptr->restart_queue;
2515         tptr->restart_queue = ntp;
2516         rls_lun_statep(isp, tptr);
2517 }
2518
2519 static void
2520 isp_handle_platform_atio7(ispsoftc_t *isp, at7_entry_t *aep)
2521 {
2522         int cdbxlen;
2523         uint16_t lun, chan, nphdl = NIL_HANDLE;
2524         uint32_t did, sid;
2525         uint64_t wwn = INI_NONE;
2526         fcportdb_t *lp;
2527         tstate_t *tptr;
2528         struct ccb_accept_tio *atiop;
2529         atio_private_data_t *atp = NULL;
2530         atio_private_data_t *oatp;
2531         inot_private_data_t *ntp;
2532
2533         did = (aep->at_hdr.d_id[0] << 16) | (aep->at_hdr.d_id[1] << 8) | aep->at_hdr.d_id[2];
2534         sid = (aep->at_hdr.s_id[0] << 16) | (aep->at_hdr.s_id[1] << 8) | aep->at_hdr.s_id[2];
2535         lun = (aep->at_cmnd.fcp_cmnd_lun[0] << 8) | aep->at_cmnd.fcp_cmnd_lun[1];
2536
2537         /*
2538          * Find the N-port handle, and Virtual Port Index for this command.
2539          *
2540          * If we can't, we're somewhat in trouble because we can't actually respond w/o that information.
2541          * We also, as a matter of course, need to know the WWN of the initiator too.
2542          */
2543         if (ISP_CAP_MULTI_ID(isp)) {
2544                 /*
2545                  * Find the right channel based upon D_ID
2546                  */
2547                 isp_find_chan_by_did(isp, did, &chan);
2548
2549                 if (chan == ISP_NOCHAN) {
2550                         NANOTIME_T now;
2551
2552                         /*
2553                          * If we don't recognizer our own D_DID, terminate the exchange, unless we're within 2 seconds of startup
2554                          * It's a bit tricky here as we need to stash this command *somewhere*.
2555                          */
2556                         GET_NANOTIME(&now);
2557                         if (NANOTIME_SUB(&isp->isp_init_time, &now) > 2000000000ULL) {
2558                                 isp_prt(isp, ISP_LOGWARN, "%s: [RX_ID 0x%x] D_ID %x not found on any channel- dropping", __func__, aep->at_rxid, did);
2559                                 isp_endcmd(isp, aep, NIL_HANDLE, ISP_NOCHAN, ECMD_TERMINATE, 0);
2560                                 return;
2561                         }
2562                         tptr = get_lun_statep(isp, 0, 0);
2563                         if (tptr == NULL) {
2564                                 tptr = get_lun_statep(isp, 0, CAM_LUN_WILDCARD);
2565                                 if (tptr == NULL) {
2566                                         isp_prt(isp, ISP_LOGWARN, "%s: [RX_ID 0x%x] D_ID %x not found on any channel and no tptr- dropping", __func__, aep->at_rxid, did);
2567                                         isp_endcmd(isp, aep, NIL_HANDLE, ISP_NOCHAN, ECMD_TERMINATE, 0);
2568                                         return;
2569                                 }
2570                         }
2571                         isp_prt(isp, ISP_LOGWARN, "%s: [RX_ID 0x%x] D_ID %x not found on any channel- deferring", __func__, aep->at_rxid, did);
2572                         goto noresrc;
2573                 }
2574                 isp_prt(isp, ISP_LOGTDEBUG0, "%s: [RX_ID 0x%x] D_ID 0x%06x found on Chan %d for S_ID 0x%06x", __func__, aep->at_rxid, did, chan, sid);
2575         } else {
2576                 chan = 0;
2577         }
2578
2579         /*
2580          * Find the PDB entry for this initiator
2581          */
2582         if (isp_find_pdb_by_sid(isp, chan, sid, &lp) == 0) {
2583                 /*
2584                  * If we're not in the port database terminate the exchange.
2585                  */
2586                 isp_prt(isp, ISP_LOGTINFO, "%s: [RX_ID 0x%x] D_ID 0x%06x found on Chan %d for S_ID 0x%06x wasn't in PDB already",
2587                     __func__, aep->at_rxid, did, chan, sid);
2588                 isp_endcmd(isp, aep, NIL_HANDLE, chan, ECMD_TERMINATE, 0);
2589                 return;
2590         }
2591         nphdl = lp->handle;
2592         wwn = lp->port_wwn;
2593
2594         /*
2595          * Get the tstate pointer
2596          */
2597         tptr = get_lun_statep(isp, chan, lun);
2598         if (tptr == NULL) {
2599                 tptr = get_lun_statep(isp, chan, CAM_LUN_WILDCARD);
2600                 if (tptr == NULL) {
2601                         isp_prt(isp, ISP_LOGWARN, "%s: [0x%x] no state pointer for lun %d or wildcard", __func__, aep->at_rxid, lun);
2602                         if (lun == 0) {
2603                                 isp_endcmd(isp, aep, nphdl, SCSI_STATUS_BUSY, 0);
2604                         } else {
2605                                 isp_endcmd(isp, aep, nphdl, chan, SCSI_STATUS_CHECK_COND | ECMD_SVALID | (0x5 << 12) | (0x25 << 16), 0);
2606                         }
2607                         return;
2608                 }
2609         }
2610
2611         /*
2612          * Start any commands pending resources first.
2613          */
2614         if (tptr->restart_queue) {
2615                 inot_private_data_t *restart_queue = tptr->restart_queue;
2616                 tptr->restart_queue = NULL;
2617                 while (restart_queue) {
2618                         ntp = restart_queue;
2619                         restart_queue = ntp->rd.nt.nt_hba;
2620                         isp_prt(isp, ISP_LOGTDEBUG0, "%s: restarting resrc deprived %x", __func__, ((at7_entry_t *)ntp->rd.data)->at_rxid);
2621                         isp_handle_platform_atio7(isp, (at7_entry_t *) ntp->rd.data);
2622                         isp_put_ntpd(isp, tptr, ntp);
2623                         /*
2624                          * If a recursion caused the restart queue to start to fill again,
2625                          * stop and splice the new list on top of the old list and restore
2626                          * it and go to noresrc.
2627                          */
2628                         if (tptr->restart_queue) {
2629                                 isp_prt(isp, ISP_LOGTDEBUG0, "%s: restart queue refilling", __func__);
2630                                 if (restart_queue) {
2631                                         ntp = tptr->restart_queue;
2632                                         tptr->restart_queue = restart_queue;
2633                                         while (restart_queue->rd.nt.nt_hba) {
2634                                                 restart_queue = restart_queue->rd.nt.nt_hba;
2635                                         }
2636                                         restart_queue->rd.nt.nt_hba = ntp;
2637                                 }
2638                                 goto noresrc;
2639                         }
2640                 }
2641         }
2642
2643         /*
2644          * If the f/w is out of resources, just send a BUSY status back.
2645          */
2646         if (aep->at_rxid == AT7_NORESRC_RXID) {
2647                 rls_lun_statep(isp, tptr);
2648                 isp_endcmd(isp, aep, nphdl, chan, SCSI_BUSY, 0);
2649                 return;
2650         }
2651
2652         /*
2653          * If we're out of resources, just send a BUSY status back.
2654          */
2655         atiop = (struct ccb_accept_tio *) SLIST_FIRST(&tptr->atios);
2656         if (atiop == NULL) {
2657                 isp_prt(isp, ISP_LOGTDEBUG0, "[0x%x] out of atios", aep->at_rxid);
2658                 goto noresrc;
2659         }
2660
2661         oatp = isp_find_atpd(isp, tptr, aep->at_rxid);
2662         if (oatp) {
2663                 isp_prt(isp, ISP_LOGTDEBUG0, "[0x%x] tag wraparound in isp_handle_platforms_atio7 (N-Port Handle 0x%04x S_ID 0x%04x OX_ID 0x%04x) oatp state %d",
2664                     aep->at_rxid, nphdl, sid, aep->at_hdr.ox_id, oatp->state);
2665                 /*
2666                  * It's not a "no resource" condition- but we can treat it like one
2667                  */
2668                 goto noresrc;
2669         }
2670         atp = isp_get_atpd(isp, tptr, aep->at_rxid);
2671         if (atp == NULL) {
2672                 isp_prt(isp, ISP_LOGTDEBUG0, "[0x%x] out of atps", aep->at_rxid);
2673                 goto noresrc;
2674         }
2675         atp->word3 = lp->prli_word3;
2676         atp->state = ATPD_STATE_ATIO;
2677         SLIST_REMOVE_HEAD(&tptr->atios, sim_links.sle);
2678         tptr->atio_count--;
2679         ISP_PATH_PRT(isp, ISP_LOGTDEBUG2, atiop->ccb_h.path, "Take FREE ATIO count now %d\n", tptr->atio_count);
2680         atiop->init_id = nphdl;
2681         atiop->ccb_h.target_id = FCPARAM(isp, chan)->isp_loopid;
2682         atiop->ccb_h.target_lun = lun;
2683         atiop->sense_len = 0;
2684         cdbxlen = aep->at_cmnd.fcp_cmnd_alen_datadir >> FCP_CMND_ADDTL_CDBLEN_SHIFT;
2685         if (cdbxlen) {
2686                 isp_prt(isp, ISP_LOGWARN, "additional CDBLEN ignored");
2687         }
2688         cdbxlen = sizeof (aep->at_cmnd.cdb_dl.sf.fcp_cmnd_cdb);
2689         ISP_MEMCPY(atiop->cdb_io.cdb_bytes, aep->at_cmnd.cdb_dl.sf.fcp_cmnd_cdb, cdbxlen);
2690         atiop->cdb_len = cdbxlen;
2691         atiop->ccb_h.status = CAM_CDB_RECVD;
2692         atiop->tag_id = atp->tag;
2693         switch (aep->at_cmnd.fcp_cmnd_task_attribute & FCP_CMND_TASK_ATTR_MASK) {
2694         case FCP_CMND_TASK_ATTR_SIMPLE:
2695                 atiop->ccb_h.flags |= CAM_TAG_ACTION_VALID;
2696                 atiop->tag_action = MSG_SIMPLE_Q_TAG;
2697                 break;
2698         case FCP_CMND_TASK_ATTR_HEAD:
2699                 atiop->ccb_h.flags |= CAM_TAG_ACTION_VALID;
2700                 atiop->tag_action = MSG_HEAD_OF_Q_TAG;
2701                 break;
2702         case FCP_CMND_TASK_ATTR_ORDERED:
2703                 atiop->ccb_h.flags |= CAM_TAG_ACTION_VALID;
2704                 atiop->tag_action = MSG_ORDERED_Q_TAG;
2705                 break;
2706         default:
2707                 /* FALLTHROUGH */
2708         case FCP_CMND_TASK_ATTR_ACA:
2709         case FCP_CMND_TASK_ATTR_UNTAGGED:
2710                 atiop->tag_action = 0;
2711                 break;
2712         }
2713         atp->orig_datalen = aep->at_cmnd.cdb_dl.sf.fcp_cmnd_dl;
2714         atp->bytes_xfered = 0;
2715         atp->lun = lun;
2716         atp->nphdl = nphdl;
2717         atp->portid = sid;
2718         atp->oxid = aep->at_hdr.ox_id;
2719         atp->rxid = aep->at_hdr.rx_id;
2720         atp->cdb0 = atiop->cdb_io.cdb_bytes[0];
2721         atp->tattr = aep->at_cmnd.fcp_cmnd_task_attribute & FCP_CMND_TASK_ATTR_MASK;
2722         atp->state = ATPD_STATE_CAM;
2723         isp_prt(isp, ISP_LOGTDEBUG0, "ATIO7[0x%x] CDB=0x%x lun %d datalen %u", aep->at_rxid, atp->cdb0, lun, atp->orig_datalen);
2724         xpt_done((union ccb *)atiop);
2725         rls_lun_statep(isp, tptr);
2726         return;
2727 noresrc:
2728         if (atp) {
2729                 isp_put_atpd(isp, tptr, atp);
2730         }
2731         ntp = isp_get_ntpd(isp, tptr);
2732         if (ntp == NULL) {
2733                 rls_lun_statep(isp, tptr);
2734                 isp_endcmd(isp, aep, nphdl, chan, SCSI_STATUS_BUSY, 0);
2735                 return;
2736         }
2737         memcpy(ntp->rd.data, aep, QENTRY_LEN);
2738         ntp->rd.nt.nt_hba = tptr->restart_queue;
2739         tptr->restart_queue = ntp;
2740         rls_lun_statep(isp, tptr);
2741 }
2742
2743
2744 /*
2745  * Handle starting an SRR (sequence retransmit request)
2746  * We get here when we've gotten the immediate notify
2747  * and the return of all outstanding CTIOs for this
2748  * transaction.
2749  */
2750 static void
2751 isp_handle_srr_start(ispsoftc_t *isp, tstate_t *tptr, atio_private_data_t *atp)
2752 {
2753         in_fcentry_24xx_t *inot;
2754         uint32_t srr_off, ccb_off, ccb_len, ccb_end;
2755         union ccb *ccb;
2756
2757         inot = (in_fcentry_24xx_t *)atp->srr;
2758         srr_off = inot->in_srr_reloff_lo | (inot->in_srr_reloff_hi << 16);
2759         ccb = atp->srr_ccb;
2760         atp->srr_ccb = NULL;
2761         atp->nsrr++;
2762         if (ccb == NULL) {
2763                 isp_prt(isp, ISP_LOGWARN, "SRR[0x%x] null ccb", atp->tag);
2764                 goto fail;
2765         }
2766
2767         ccb_off = ccb->ccb_h.spriv_field0;
2768         ccb_len = ccb->csio.dxfer_len;
2769         ccb_end = (ccb_off == ~0)? ~0 : ccb_off + ccb_len;
2770
2771         switch (inot->in_srr_iu) {
2772         case R_CTL_INFO_SOLICITED_DATA:
2773                 /*
2774                  * We have to restart a FCP_DATA data out transaction
2775                  */
2776                 atp->sendst = 0;
2777                 atp->bytes_xfered = srr_off;
2778                 if (ccb_len == 0) {
2779                         isp_prt(isp, ISP_LOGWARN, "SRR[0x%x] SRR offset 0x%x but current CCB doesn't transfer data", atp->tag, srr_off);
2780                         goto mdp;
2781                 }
2782                 if (srr_off < ccb_off || ccb_off > srr_off + ccb_len) {
2783                         isp_prt(isp, ISP_LOGWARN, "SRR[0x%x] SRR offset 0x%x not covered by current CCB data range [0x%x..0x%x]", atp->tag, srr_off, ccb_off, ccb_end);
2784                         goto mdp;
2785                 }
2786                 isp_prt(isp, ISP_LOGWARN, "SRR[0x%x] SRR offset 0x%x covered by current CCB data range [0x%x..0x%x]", atp->tag, srr_off, ccb_off, ccb_end);
2787                 break;
2788         case R_CTL_INFO_COMMAND_STATUS:
2789                 isp_prt(isp, ISP_LOGTINFO, "SRR[0x%x] Got an FCP RSP SRR- resending status", atp->tag);
2790                 atp->sendst = 1;
2791                 /*
2792                  * We have to restart a FCP_RSP IU transaction
2793                  */
2794                 break;
2795         case R_CTL_INFO_DATA_DESCRIPTOR:
2796                 /*
2797                  * We have to restart an FCP DATA in transaction
2798                  */
2799                 isp_prt(isp, ISP_LOGWARN, "Got an FCP DATA IN SRR- dropping");
2800                 goto fail;
2801                 
2802         default:
2803                 isp_prt(isp, ISP_LOGWARN, "Got an unknown information (%x) SRR- dropping", inot->in_srr_iu);
2804                 goto fail;
2805         }
2806
2807         /*
2808          * We can't do anything until this is acked, so we might as well start it now.
2809          * We aren't going to do the usual asynchronous ack issue because we need
2810          * to make sure this gets on the wire first.
2811          */
2812         if (isp_notify_ack(isp, inot)) {
2813                 isp_prt(isp, ISP_LOGWARN, "could not push positive ack for SRR- you lose");
2814                 goto fail;
2815         }
2816         isp_target_start_ctio(isp, ccb, FROM_SRR);
2817         return;
2818 fail:
2819         inot->in_reserved = 1;
2820         isp_async(isp, ISPASYNC_TARGET_NOTIFY_ACK, inot);
2821         ccb->ccb_h.status &= ~CAM_STATUS_MASK;
2822         ccb->ccb_h.status |= CAM_REQ_CMP_ERR;
2823         isp_complete_ctio(ccb);
2824         return;
2825 mdp:
2826         if (isp_notify_ack(isp, inot)) {
2827                 isp_prt(isp, ISP_LOGWARN, "could not push positive ack for SRR- you lose");
2828                 goto fail;
2829         }
2830         ccb->ccb_h.status &= ~CAM_STATUS_MASK;
2831         ccb->ccb_h.status = CAM_MESSAGE_RECV;
2832         /*
2833          * This is not a strict interpretation of MDP, but it's close
2834          */
2835         ccb->csio.msg_ptr = &ccb->csio.sense_data.sense_buf[SSD_FULL_SIZE - 16];
2836         ccb->csio.msg_len = 7;
2837         ccb->csio.msg_ptr[0] = MSG_EXTENDED;
2838         ccb->csio.msg_ptr[1] = 5;
2839         ccb->csio.msg_ptr[2] = 0;       /* modify data pointer */
2840         ccb->csio.msg_ptr[3] = srr_off >> 24;
2841         ccb->csio.msg_ptr[4] = srr_off >> 16;
2842         ccb->csio.msg_ptr[5] = srr_off >> 8;
2843         ccb->csio.msg_ptr[6] = srr_off;
2844         isp_complete_ctio(ccb);
2845 }
2846
2847
2848 static void
2849 isp_handle_srr_notify(ispsoftc_t *isp, void *inot_raw)
2850 {
2851         tstate_t *tptr;
2852         in_fcentry_24xx_t *inot = inot_raw;
2853         atio_private_data_t *atp;
2854         uint32_t tag = inot->in_rxid;
2855         uint32_t bus = inot->in_vpidx;
2856
2857         if (!IS_24XX(isp)) {
2858                 isp_async(isp, ISPASYNC_TARGET_NOTIFY_ACK, inot_raw);
2859                 return;
2860         }
2861
2862         tptr = get_lun_statep_from_tag(isp, bus, tag);
2863         if (tptr == NULL) {
2864                 isp_prt(isp, ISP_LOGERR, "%s: cannot find tptr for tag %x in SRR Notify", __func__, tag);
2865                 isp_async(isp, ISPASYNC_TARGET_NOTIFY_ACK, inot);
2866                 return;
2867         }
2868         atp = isp_find_atpd(isp, tptr, tag);
2869         if (atp == NULL) {
2870                 rls_lun_statep(isp, tptr);
2871                 isp_prt(isp, ISP_LOGERR, "%s: cannot find adjunct for %x in SRR Notify", __func__, tag);
2872                 isp_async(isp, ISPASYNC_TARGET_NOTIFY_ACK, inot);
2873                 return;
2874         }
2875         atp->srr_notify_rcvd = 1;
2876         memcpy(atp->srr, inot, sizeof (atp->srr));
2877         isp_prt(isp, ISP_LOGTINFO /* ISP_LOGTDEBUG0 */, "SRR[0x%x] inot->in_rxid flags 0x%x srr_iu=%x reloff 0x%x", inot->in_rxid, inot->in_flags, inot->in_srr_iu,
2878             inot->in_srr_reloff_lo | (inot->in_srr_reloff_hi << 16));
2879         if (atp->srr_ccb)
2880                 isp_handle_srr_start(isp, tptr, atp);
2881         rls_lun_statep(isp, tptr);
2882 }
2883
2884 static void
2885 isp_handle_platform_ctio(ispsoftc_t *isp, void *arg)
2886 {
2887         union ccb *ccb;
2888         int sentstatus = 0, ok = 0, notify_cam = 0, resid = 0, failure = 0;
2889         tstate_t *tptr = NULL;
2890         atio_private_data_t *atp = NULL;
2891         int bus;
2892         uint32_t handle, moved_data = 0, data_requested;
2893
2894         /*
2895          * CTIO handles are 16 bits.
2896          * CTIO2 and CTIO7 are 32 bits.
2897          */
2898
2899         if (IS_SCSI(isp)) {
2900                 handle = ((ct_entry_t *)arg)->ct_syshandle;
2901         } else {
2902                 handle = ((ct2_entry_t *)arg)->ct_syshandle;
2903         }
2904         ccb = isp_find_xs_tgt(isp, handle);
2905         if (ccb == NULL) {
2906                 isp_print_bytes(isp, "null ccb in isp_handle_platform_ctio", QENTRY_LEN, arg);
2907                 return;
2908         }
2909         isp_destroy_tgt_handle(isp, handle);
2910         data_requested = PISP_PCMD(ccb)->datalen;
2911         isp_free_pcmd(isp, ccb);
2912         if (isp->isp_nactive) {
2913                 isp->isp_nactive--;
2914         }
2915
2916         bus = XS_CHANNEL(ccb);
2917         tptr = get_lun_statep(isp, bus, XS_LUN(ccb));
2918         if (tptr == NULL) {
2919                 tptr = get_lun_statep(isp, bus, CAM_LUN_WILDCARD);
2920         }
2921         if (tptr == NULL) {
2922                 isp_prt(isp, ISP_LOGERR, "%s: cannot find tptr for tag %x after I/O", __func__, ccb->csio.tag_id);
2923                 return;
2924         }
2925
2926         if (IS_24XX(isp)) {
2927                 atp = isp_find_atpd(isp, tptr, ((ct7_entry_t *)arg)->ct_rxid);
2928         } else if (IS_FC(isp)) {
2929                 atp = isp_find_atpd(isp, tptr, ((ct2_entry_t *)arg)->ct_rxid);
2930         } else {
2931                 atp = isp_find_atpd(isp, tptr, ((ct_entry_t *)arg)->ct_fwhandle);
2932         }
2933         if (atp == NULL) {
2934                 rls_lun_statep(isp, tptr);
2935                 isp_prt(isp, ISP_LOGERR, "%s: cannot find adjunct for %x after I/O", __func__, ccb->csio.tag_id);
2936                 return;
2937         }
2938         KASSERT((atp->ctcnt > 0), ("ctio count not greater than zero"));
2939         atp->bytes_in_transit -= data_requested;
2940         atp->ctcnt -= 1;
2941         ccb->ccb_h.status &= ~CAM_STATUS_MASK;
2942
2943         if (IS_24XX(isp)) {
2944                 ct7_entry_t *ct = arg;
2945
2946                 if (ct->ct_nphdl == CT7_SRR) {
2947                         atp->srr_ccb = ccb;
2948                         if (atp->srr_notify_rcvd)
2949                                 isp_handle_srr_start(isp, tptr, atp);
2950                         rls_lun_statep(isp, tptr);
2951                         return;
2952                 }
2953                 if (ct->ct_nphdl == CT_HBA_RESET) {
2954                         failure = CAM_UNREC_HBA_ERROR;
2955                 } else {
2956                         sentstatus = ct->ct_flags & CT7_SENDSTATUS;
2957                         ok = (ct->ct_nphdl == CT7_OK);
2958                         notify_cam = (ct->ct_header.rqs_seqno & ATPD_SEQ_NOTIFY_CAM) != 0;
2959                         if ((ct->ct_flags & CT7_DATAMASK) != CT7_NO_DATA) {
2960                                 resid = ct->ct_resid;
2961                                 moved_data = data_requested - resid;
2962                         }
2963                 }
2964                 isp_prt(isp, ok? ISP_LOGTDEBUG0 : ISP_LOGWARN, "%s: CTIO7[%x] seq %u nc %d sts 0x%x flg 0x%x sns %d resid %d %s", __func__, ct->ct_rxid, ATPD_GET_SEQNO(ct),
2965                    notify_cam, ct->ct_nphdl, ct->ct_flags, (ccb->ccb_h.status & CAM_SENT_SENSE) != 0, resid, sentstatus? "FIN" : "MID");
2966         } else if (IS_FC(isp)) {
2967                 ct2_entry_t *ct = arg;
2968                 if (ct->ct_status == CT_SRR) {
2969                         atp->srr_ccb = ccb;
2970                         if (atp->srr_notify_rcvd)
2971                                 isp_handle_srr_start(isp, tptr, atp);
2972                         rls_lun_statep(isp, tptr);
2973                         isp_target_putback_atio(ccb);
2974                         return;
2975                 }
2976                 if (ct->ct_status == CT_HBA_RESET) {
2977                         failure = CAM_UNREC_HBA_ERROR;
2978                 } else {
2979                         sentstatus = ct->ct_flags & CT2_SENDSTATUS;
2980                         ok = (ct->ct_status & ~QLTM_SVALID) == CT_OK;
2981                         notify_cam = (ct->ct_header.rqs_seqno & ATPD_SEQ_NOTIFY_CAM) != 0;
2982                         if ((ct->ct_flags & CT2_DATAMASK) != CT2_NO_DATA) {
2983                                 resid = ct->ct_resid;
2984                                 moved_data = data_requested - resid;
2985                         }
2986                 }
2987                 isp_prt(isp, ok? ISP_LOGTDEBUG0 : ISP_LOGWARN, "%s: CTIO2[%x] seq %u nc %d sts 0x%x flg 0x%x sns %d resid %d %s", __func__, ct->ct_rxid, ATPD_GET_SEQNO(ct),
2988                     notify_cam, ct->ct_status, ct->ct_flags, (ccb->ccb_h.status & CAM_SENT_SENSE) != 0, resid, sentstatus? "FIN" : "MID");
2989         } else {
2990                 ct_entry_t *ct = arg;
2991
2992                 if (ct->ct_status == (CT_HBA_RESET & 0xff)) {
2993                         failure = CAM_UNREC_HBA_ERROR;
2994                 } else {
2995                         sentstatus = ct->ct_flags & CT_SENDSTATUS;
2996                         ok = (ct->ct_status  & ~QLTM_SVALID) == CT_OK;
2997                         notify_cam = (ct->ct_header.rqs_seqno & ATPD_SEQ_NOTIFY_CAM) != 0;
2998                 }
2999                 if ((ct->ct_flags & CT_DATAMASK) != CT_NO_DATA) {
3000                         resid = ct->ct_resid;
3001                         moved_data = data_requested - resid;
3002                 }
3003                 isp_prt(isp, ISP_LOGTDEBUG0, "%s: CTIO[%x] seq %u nc %d tag %x S_ID 0x%x lun %d sts %x flg %x resid %d %s", __func__, ct->ct_fwhandle, ATPD_GET_SEQNO(ct),
3004                     notify_cam, ct->ct_tag_val, ct->ct_iid, ct->ct_lun, ct->ct_status, ct->ct_flags, resid, sentstatus? "FIN" : "MID");
3005         }
3006         if (ok) {
3007                 if (moved_data) {
3008                         atp->bytes_xfered += moved_data;
3009                         ccb->csio.resid = atp->orig_datalen - atp->bytes_xfered - atp->bytes_in_transit;
3010                 }
3011                 if (sentstatus && (ccb->ccb_h.flags & CAM_SEND_SENSE)) {
3012                         ccb->ccb_h.status |= CAM_SENT_SENSE;
3013                 }
3014                 ccb->ccb_h.status |= CAM_REQ_CMP;
3015         } else {
3016                 notify_cam = 1;
3017                 if (failure == CAM_UNREC_HBA_ERROR)
3018                         ccb->ccb_h.status |= CAM_UNREC_HBA_ERROR;
3019                 else
3020                         ccb->ccb_h.status |= CAM_REQ_CMP_ERR;
3021         }
3022         atp->state = ATPD_STATE_PDON;
3023         rls_lun_statep(isp, tptr);
3024
3025         /*
3026          * We never *not* notify CAM when there has been any error (ok == 0),
3027          * so we never need to do an ATIO putback if we're not notifying CAM.
3028          */
3029         isp_prt(isp, ISP_LOGTDEBUG0, "%s CTIO[0x%x] done (ok=%d nc=%d nowsendstatus=%d ccb ss=%d)",
3030             (sentstatus)? "  FINAL " : "MIDTERM ", atp->tag, ok, notify_cam, atp->sendst, (ccb->ccb_h.flags & CAM_SEND_STATUS) != 0);
3031         if (notify_cam == 0) {
3032                 if (atp->sendst) {
3033                         isp_target_start_ctio(isp, ccb, FROM_CTIO_DONE);
3034                 }
3035                 return;
3036         }
3037
3038         /*
3039          * We're telling CAM we're done with this CTIO transaction.
3040          *
3041          * 24XX cards never need an ATIO put back.
3042          *
3043          * Other cards need one put back only on error.
3044          * In the latter case, a timeout will re-fire
3045          * and try again in case we didn't have
3046          * queue resources to do so at first. In any case,
3047          * once the putback is done we do the completion
3048          * call.
3049          */
3050         if (ok || IS_24XX(isp)) {
3051                 isp_complete_ctio(ccb);
3052         } else {
3053                 isp_target_putback_atio(ccb);
3054         }
3055 }
3056
3057 static void
3058 isp_handle_platform_notify_scsi(ispsoftc_t *isp, in_entry_t *inot)
3059 {
3060         isp_async(isp, ISPASYNC_TARGET_NOTIFY_ACK, inot);
3061 }
3062
3063 static void
3064 isp_handle_platform_notify_fc(ispsoftc_t *isp, in_fcentry_t *inp)
3065 {
3066         int needack = 1;
3067         switch (inp->in_status) {
3068         case IN_PORT_LOGOUT:
3069                 /*
3070                  * XXX: Need to delete this initiator's WWN from the database
3071                  * XXX: Need to send this LOGOUT upstream
3072                  */
3073                 isp_prt(isp, ISP_LOGWARN, "port logout of S_ID 0x%x", inp->in_iid);
3074                 break;
3075         case IN_PORT_CHANGED:
3076                 isp_prt(isp, ISP_LOGWARN, "port changed for S_ID 0x%x", inp->in_iid);
3077                 break;
3078         case IN_GLOBAL_LOGO:
3079                 isp_del_all_wwn_entries(isp, 0);
3080                 isp_prt(isp, ISP_LOGINFO, "all ports logged out");
3081                 break;
3082         case IN_ABORT_TASK:
3083         {
3084                 tstate_t *tptr;
3085                 uint16_t lun;
3086                 uint32_t loopid;
3087                 uint64_t wwn;
3088                 atio_private_data_t *atp;
3089                 fcportdb_t *lp;
3090                 struct ccb_immediate_notify *inot = NULL;
3091
3092                 if (ISP_CAP_SCCFW(isp)) {
3093                         lun = inp->in_scclun;
3094                 } else {
3095                         lun = inp->in_lun;
3096                 }
3097                 if (ISP_CAP_2KLOGIN(isp)) {
3098                         loopid = ((in_fcentry_e_t *)inp)->in_iid;
3099                 } else {
3100                         loopid = inp->in_iid;
3101                 }
3102                 if (isp_find_pdb_by_loopid(isp, 0, loopid, &lp)) {
3103                         wwn = lp->port_wwn;
3104                 } else {
3105                         wwn = INI_ANY;
3106                 }
3107                 tptr = get_lun_statep(isp, 0, lun);
3108                 if (tptr == NULL) {
3109                         tptr = get_lun_statep(isp, 0, CAM_LUN_WILDCARD);
3110                         if (tptr == NULL) {
3111                                 isp_prt(isp, ISP_LOGWARN, "ABORT TASK for lun %u- but no tstate", lun);
3112                                 return;
3113                         }
3114                 }
3115                 atp = isp_find_atpd(isp, tptr, inp->in_seqid);
3116
3117                 if (atp) {
3118                         inot = (struct ccb_immediate_notify *) SLIST_FIRST(&tptr->inots);
3119                         isp_prt(isp, ISP_LOGTDEBUG0, "ABORT TASK RX_ID %x WWN 0x%016llx state %d", inp->in_seqid, (unsigned long long) wwn, atp->state);
3120                         if (inot) {
3121                                 tptr->inot_count--;
3122                                 SLIST_REMOVE_HEAD(&tptr->inots, sim_links.sle);
3123                                 ISP_PATH_PRT(isp, ISP_LOGTDEBUG2, inot->ccb_h.path, "%s: Take FREE INOT count now %d\n", __func__, tptr->inot_count);
3124                         } else {
3125                                 ISP_PATH_PRT(isp, ISP_LOGWARN, tptr->owner, "out of INOT structures\n");
3126                         }
3127                 } else {
3128                         ISP_PATH_PRT(isp, ISP_LOGWARN, tptr->owner, "abort task RX_ID %x from wwn 0x%016llx, state unknown\n", inp->in_seqid, wwn);
3129                 }
3130                 if (inot) {
3131                         isp_notify_t tmp, *nt = &tmp;
3132                         ISP_MEMZERO(nt, sizeof (isp_notify_t));
3133                         nt->nt_hba = isp;
3134                         nt->nt_tgt = FCPARAM(isp, 0)->isp_wwpn;
3135                         nt->nt_wwn = wwn;
3136                         nt->nt_nphdl = loopid;
3137                         nt->nt_sid = PORT_ANY;
3138                         nt->nt_did = PORT_ANY;
3139                         nt->nt_lun = lun;
3140                         nt->nt_need_ack = 1;
3141                         nt->nt_channel = 0;
3142                         nt->nt_ncode = NT_ABORT_TASK;
3143                         nt->nt_lreserved = inot;
3144                         isp_handle_platform_target_tmf(isp, nt);
3145                         needack = 0;
3146                 }
3147                 rls_lun_statep(isp, tptr);
3148                 break;
3149         }
3150         default:
3151                 break;
3152         }
3153         if (needack) {
3154                 isp_async(isp, ISPASYNC_TARGET_NOTIFY_ACK, inp);
3155         }
3156 }
3157
3158 static void
3159 isp_handle_platform_notify_24xx(ispsoftc_t *isp, in_fcentry_24xx_t *inot)
3160 {
3161         uint16_t nphdl;
3162         uint16_t prli_options = 0;
3163         uint32_t portid;
3164         fcportdb_t *lp;
3165         uint8_t *ptr = NULL;
3166         uint64_t wwn;
3167
3168         nphdl = inot->in_nphdl;
3169         if (nphdl != NIL_HANDLE) {
3170                 portid = inot->in_portid_hi << 16 | inot->in_portid_lo;
3171         } else {
3172                 portid = PORT_ANY;
3173         }
3174
3175         switch (inot->in_status) {
3176         case IN24XX_ELS_RCVD:
3177         {
3178                 char buf[16], *msg;
3179                 int chan = ISP_GET_VPIDX(isp, inot->in_vpidx);
3180
3181                 /*
3182                  * Note that we're just getting notification that an ELS was received
3183                  * (possibly with some associated information sent upstream). This is
3184                  * *not* the same as being given the ELS frame to accept or reject.
3185                  */
3186                 switch (inot->in_status_subcode) {
3187                 case LOGO:
3188                         msg = "LOGO";
3189                         if (ISP_FW_NEWER_THAN(isp, 4, 0, 25)) {
3190                                 ptr = (uint8_t *)inot;  /* point to unswizzled entry! */
3191                                 wwn =   (((uint64_t) ptr[IN24XX_LOGO_WWPN_OFF])   << 56) |
3192                                         (((uint64_t) ptr[IN24XX_LOGO_WWPN_OFF+1]) << 48) |
3193                                         (((uint64_t) ptr[IN24XX_LOGO_WWPN_OFF+2]) << 40) |
3194                                         (((uint64_t) ptr[IN24XX_LOGO_WWPN_OFF+3]) << 32) |
3195                                         (((uint64_t) ptr[IN24XX_LOGO_WWPN_OFF+4]) << 24) |
3196                                         (((uint64_t) ptr[IN24XX_LOGO_WWPN_OFF+5]) << 16) |
3197                                         (((uint64_t) ptr[IN24XX_LOGO_WWPN_OFF+6]) <<  8) |
3198                                         (((uint64_t) ptr[IN24XX_LOGO_WWPN_OFF+7]));
3199                         } else {
3200                                 wwn = INI_ANY;
3201                         }
3202                         isp_del_wwn_entry(isp, chan, wwn, nphdl, portid);
3203                         break;
3204                 case PRLO:
3205                         msg = "PRLO";
3206                         break;
3207                 case PLOGI:
3208                 case PRLI:
3209                         /*
3210                          * Treat PRLI the same as PLOGI and make a database entry for it.
3211                          */
3212                         if (inot->in_status_subcode == PLOGI) {
3213                                 msg = "PLOGI";
3214                         } else {
3215                                 prli_options = inot->in_prli_options;
3216                                 msg = "PRLI";
3217                         }
3218                         if (ISP_FW_NEWER_THAN(isp, 4, 0, 25)) {
3219                                 ptr = (uint8_t *)inot;  /* point to unswizzled entry! */
3220                                 wwn =   (((uint64_t) ptr[IN24XX_PLOGI_WWPN_OFF])   << 56) |
3221                                         (((uint64_t) ptr[IN24XX_PLOGI_WWPN_OFF+1]) << 48) |
3222                                         (((uint64_t) ptr[IN24XX_PLOGI_WWPN_OFF+2]) << 40) |
3223                                         (((uint64_t) ptr[IN24XX_PLOGI_WWPN_OFF+3]) << 32) |
3224                                         (((uint64_t) ptr[IN24XX_PLOGI_WWPN_OFF+4]) << 24) |
3225                                         (((uint64_t) ptr[IN24XX_PLOGI_WWPN_OFF+5]) << 16) |
3226                                         (((uint64_t) ptr[IN24XX_PLOGI_WWPN_OFF+6]) <<  8) |
3227                                         (((uint64_t) ptr[IN24XX_PLOGI_WWPN_OFF+7]));
3228                         } else {
3229                                 wwn = INI_NONE;
3230                         }
3231                         isp_add_wwn_entry(isp, chan, wwn, nphdl, portid, prli_options);
3232                         break;
3233                 case PDISC:
3234                         msg = "PDISC";
3235                         break;
3236                 case ADISC:
3237                         msg = "ADISC";
3238                         break;
3239                 default:
3240                         ISP_SNPRINTF(buf, sizeof (buf), "ELS 0x%x", inot->in_status_subcode);
3241                         msg = buf;
3242                         break;
3243                 }
3244                 if (inot->in_flags & IN24XX_FLAG_PUREX_IOCB) {
3245                         isp_prt(isp, ISP_LOGERR, "%s Chan %d ELS N-port handle %x PortID 0x%06x marked as needing a PUREX response", msg, chan, nphdl, portid);
3246                         break;
3247                 }
3248                 isp_prt(isp, ISP_LOGTDEBUG0, "%s Chan %d ELS N-port handle %x PortID 0x%06x RX_ID 0x%x OX_ID 0x%x", msg, chan, nphdl, portid,
3249                     inot->in_rxid, inot->in_oxid);
3250                 isp_async(isp, ISPASYNC_TARGET_NOTIFY_ACK, inot);
3251                 break;
3252         }
3253
3254         case IN24XX_PORT_LOGOUT:
3255                 ptr = "PORT LOGOUT";
3256                 if (isp_find_pdb_by_loopid(isp, ISP_GET_VPIDX(isp, inot->in_vpidx), nphdl, &lp)) {
3257                         isp_del_wwn_entry(isp, ISP_GET_VPIDX(isp, inot->in_vpidx), lp->port_wwn, nphdl, lp->portid);
3258                 }
3259                 /* FALLTHROUGH */
3260         case IN24XX_PORT_CHANGED:
3261                 if (ptr == NULL) {
3262                         ptr = "PORT CHANGED";
3263                 }
3264                 /* FALLTHROUGH */
3265         case IN24XX_LIP_RESET: 
3266                 if (ptr == NULL) {
3267                         ptr = "LIP RESET";
3268                 }
3269                 isp_prt(isp, ISP_LOGINFO, "Chan %d %s (sub-status 0x%x) for N-port handle 0x%x", ISP_GET_VPIDX(isp, inot->in_vpidx), ptr, inot->in_status_subcode, nphdl);
3270
3271                 /*
3272                  * All subcodes here are irrelevant. What is relevant
3273                  * is that we need to terminate all active commands from
3274                  * this initiator (known by N-port handle).
3275                  */
3276                 /* XXX IMPLEMENT XXX */
3277                 isp_async(isp, ISPASYNC_TARGET_NOTIFY_ACK, inot);
3278                 break;
3279
3280         case IN24XX_SRR_RCVD:
3281 #ifdef  ISP_TARGET_MODE
3282                 isp_handle_srr_notify(isp, inot);
3283                 break;
3284 #else
3285                 if (ptr == NULL) {
3286                         ptr = "SRR RCVD";
3287                 }
3288                 /* FALLTHROUGH */
3289 #endif
3290         case IN24XX_LINK_RESET:
3291                 if (ptr == NULL) {
3292                         ptr = "LINK RESET";
3293                 }
3294         case IN24XX_LINK_FAILED:
3295                 if (ptr == NULL) {
3296                         ptr = "LINK FAILED";
3297                 }
3298         default:
3299                 isp_prt(isp, ISP_LOGWARN, "Chan %d %s", ISP_GET_VPIDX(isp, inot->in_vpidx), ptr);
3300                 isp_async(isp, ISPASYNC_TARGET_NOTIFY_ACK, inot);
3301                 break;
3302         }
3303 }
3304
3305 static int
3306 isp_handle_platform_target_notify_ack(ispsoftc_t *isp, isp_notify_t *mp)
3307 {
3308
3309         if (isp->isp_state != ISP_RUNSTATE) {
3310                 isp_prt(isp, ISP_LOGTINFO, "Notify Code 0x%x (qevalid=%d) acked- h/w not ready (dropping)", mp->nt_ncode, mp->nt_lreserved != NULL);
3311                 return (0);
3312         }
3313
3314         /*
3315          * This case is for a Task Management Function, which shows up as an ATIO7 entry.
3316          */
3317         if (IS_24XX(isp) && mp->nt_lreserved && ((isphdr_t *)mp->nt_lreserved)->rqs_entry_type == RQSTYPE_ATIO) {
3318                 ct7_entry_t local, *cto = &local;
3319                 at7_entry_t *aep = (at7_entry_t *)mp->nt_lreserved;
3320                 fcportdb_t *lp;
3321                 uint32_t sid;
3322                 uint16_t nphdl;
3323
3324                 sid = (aep->at_hdr.s_id[0] << 16) | (aep->at_hdr.s_id[1] << 8) | aep->at_hdr.s_id[2];
3325                 if (isp_find_pdb_by_sid(isp, mp->nt_channel, sid, &lp)) {
3326                         nphdl = lp->handle;
3327                 } else {
3328                         nphdl = NIL_HANDLE;
3329                 }
3330                 ISP_MEMZERO(&local, sizeof (local));
3331                 cto->ct_header.rqs_entry_type = RQSTYPE_CTIO7;
3332                 cto->ct_header.rqs_entry_count = 1;
3333                 cto->ct_nphdl = nphdl;
3334                 cto->ct_rxid = aep->at_rxid;
3335                 cto->ct_vpidx = mp->nt_channel;
3336                 cto->ct_iid_lo = sid;
3337                 cto->ct_iid_hi = sid >> 16;
3338                 cto->ct_oxid = aep->at_hdr.ox_id;
3339                 cto->ct_flags = CT7_SENDSTATUS|CT7_NOACK|CT7_NO_DATA|CT7_FLAG_MODE1;
3340                 cto->ct_flags |= (aep->at_ta_len >> 12) << CT7_TASK_ATTR_SHIFT;
3341                 return (isp_target_put_entry(isp, &local));
3342         }
3343
3344         /*
3345          * This case is for a responding to an ABTS frame
3346          */
3347         if (IS_24XX(isp) && mp->nt_lreserved && ((isphdr_t *)mp->nt_lreserved)->rqs_entry_type == RQSTYPE_ABTS_RCVD) {
3348
3349                 /*
3350                  * Overload nt_need_ack here to mark whether we've terminated the associated command.
3351                  */
3352                 if (mp->nt_need_ack) {
3353                         uint8_t storage[QENTRY_LEN];
3354                         ct7_entry_t *cto = (ct7_entry_t *) storage;
3355                         abts_t *abts = (abts_t *)mp->nt_lreserved;
3356
3357                         ISP_MEMZERO(cto, sizeof (ct7_entry_t));
3358                         isp_prt(isp, ISP_LOGTDEBUG0, "%s: [%x] terminating after ABTS received", __func__, abts->abts_rxid_task);
3359                         cto->ct_header.rqs_entry_type = RQSTYPE_CTIO7;
3360                         cto->ct_header.rqs_entry_count = 1;
3361                         cto->ct_nphdl = mp->nt_nphdl;
3362                         cto->ct_rxid = abts->abts_rxid_task;
3363                         cto->ct_iid_lo = mp->nt_sid;
3364                         cto->ct_iid_hi = mp->nt_sid >> 16;
3365                         cto->ct_oxid = abts->abts_ox_id;
3366                         cto->ct_vpidx = mp->nt_channel;
3367                         cto->ct_flags = CT7_NOACK|CT7_TERMINATE;
3368                         if (isp_target_put_entry(isp, cto)) {
3369                                 return (ENOMEM);
3370                         }
3371                         mp->nt_need_ack = 0;
3372                 }
3373                 if (isp_acknak_abts(isp, mp->nt_lreserved, 0) == ENOMEM) {
3374                         return (ENOMEM);
3375                 } else {
3376                         return (0);
3377                 }
3378         }
3379
3380         /*
3381          * Handle logout cases here
3382          */
3383         if (mp->nt_ncode == NT_GLOBAL_LOGOUT) {
3384                 isp_del_all_wwn_entries(isp, mp->nt_channel);
3385         }
3386
3387         if (mp->nt_ncode == NT_LOGOUT) {
3388                 if (!IS_2100(isp) && IS_FC(isp)) {
3389                         isp_del_wwn_entries(isp, mp);
3390                 }
3391         }
3392
3393         /*
3394          * General purpose acknowledgement
3395          */
3396         if (mp->nt_need_ack) {
3397                 isp_prt(isp, ISP_LOGTINFO, "Notify Code 0x%x (qevalid=%d) being acked", mp->nt_ncode, mp->nt_lreserved != NULL);
3398                 /*
3399                  * Don't need to use the guaranteed send because the caller can retry
3400                  */
3401                 return (isp_notify_ack(isp, mp->nt_lreserved));
3402         }
3403         return (0);
3404 }
3405
3406 /*
3407  * Handle task management functions.
3408  *
3409  * We show up here with a notify structure filled out.
3410  *
3411  * The nt_lreserved tag points to the original queue entry
3412  */
3413 static void
3414 isp_handle_platform_target_tmf(ispsoftc_t *isp, isp_notify_t *notify)
3415 {
3416         tstate_t *tptr;
3417         fcportdb_t *lp;
3418         struct ccb_immediate_notify *inot;
3419         inot_private_data_t *ntp = NULL;
3420         lun_id_t lun;
3421
3422         isp_prt(isp, ISP_LOGTDEBUG0, "%s: code 0x%x sid  0x%x tagval 0x%016llx chan %d lun 0x%x", __func__, notify->nt_ncode,
3423             notify->nt_sid, (unsigned long long) notify->nt_tagval, notify->nt_channel, notify->nt_lun);
3424         /*
3425          * NB: This assignment is necessary because of tricky type conversion.
3426          * XXX: This is tricky and I need to check this. If the lun isn't known
3427          * XXX: for the task management function, it does not of necessity follow
3428          * XXX: that it should go up stream to the wildcard listener.
3429          */
3430         if (notify->nt_lun == LUN_ANY) {
3431                 lun = CAM_LUN_WILDCARD;
3432         } else {
3433                 lun = notify->nt_lun;
3434         }
3435         tptr = get_lun_statep(isp, notify->nt_channel, lun);
3436         if (tptr == NULL) {
3437                 tptr = get_lun_statep(isp, notify->nt_channel, CAM_LUN_WILDCARD);
3438                 if (tptr == NULL) {
3439                         isp_prt(isp, ISP_LOGWARN, "%s: no state pointer found for chan %d lun %#jx", __func__, notify->nt_channel, (uintmax_t)lun);
3440                         goto bad;
3441                 }
3442         }
3443         inot = (struct ccb_immediate_notify *) SLIST_FIRST(&tptr->inots);
3444         if (inot == NULL) {
3445                 isp_prt(isp, ISP_LOGWARN, "%s: out of immediate notify structures for chan %d lun %#jx", __func__, notify->nt_channel, (uintmax_t)lun);
3446                 goto bad;
3447         }
3448
3449         if (isp_find_pdb_by_sid(isp, notify->nt_channel, notify->nt_sid, &lp) == 0) {
3450                 inot->initiator_id = CAM_TARGET_WILDCARD;
3451         } else {
3452                 inot->initiator_id = lp->handle;
3453         }
3454         inot->seq_id = notify->nt_tagval;
3455         inot->tag_id = notify->nt_tagval >> 32;
3456
3457         switch (notify->nt_ncode) {
3458         case NT_ABORT_TASK:
3459                 isp_target_mark_aborted_early(isp, tptr, inot->tag_id);
3460                 inot->arg = MSG_ABORT_TASK;
3461                 break;
3462         case NT_ABORT_TASK_SET:
3463                 isp_target_mark_aborted_early(isp, tptr, TAG_ANY);
3464                 inot->arg = MSG_ABORT_TASK_SET;
3465                 break;
3466         case NT_CLEAR_ACA:
3467                 inot->arg = MSG_CLEAR_ACA;
3468                 break;
3469         case NT_CLEAR_TASK_SET:
3470                 inot->arg = MSG_CLEAR_TASK_SET;
3471                 break;
3472         case NT_LUN_RESET:
3473                 inot->arg = MSG_LOGICAL_UNIT_RESET;
3474                 break;
3475         case NT_TARGET_RESET:
3476                 inot->arg = MSG_TARGET_RESET;
3477                 break;
3478         default:
3479                 isp_prt(isp, ISP_LOGWARN, "%s: unknown TMF code 0x%x for chan %d lun %#jx", __func__, notify->nt_ncode, notify->nt_channel, (uintmax_t)lun);
3480                 goto bad;
3481         }
3482
3483         ntp = isp_get_ntpd(isp, tptr);
3484         if (ntp == NULL) {
3485                 isp_prt(isp, ISP_LOGWARN, "%s: out of inotify private structures", __func__);
3486                 goto bad;
3487         }
3488         ISP_MEMCPY(&ntp->rd.nt, notify, sizeof (isp_notify_t));
3489         if (notify->nt_lreserved) {
3490                 ISP_MEMCPY(&ntp->rd.data, notify->nt_lreserved, QENTRY_LEN);
3491                 ntp->rd.nt.nt_lreserved = &ntp->rd.data;
3492         }
3493         ntp->rd.seq_id = notify->nt_tagval;
3494         ntp->rd.tag_id = notify->nt_tagval >> 32;
3495
3496         tptr->inot_count--;
3497         SLIST_REMOVE_HEAD(&tptr->inots, sim_links.sle);
3498         rls_lun_statep(isp, tptr);
3499         ISP_PATH_PRT(isp, ISP_LOGTDEBUG2, inot->ccb_h.path, "%s: Take FREE INOT count now %d\n", __func__, tptr->inot_count);
3500         inot->ccb_h.status = CAM_MESSAGE_RECV;
3501         xpt_done((union ccb *)inot);
3502         return;
3503 bad:
3504         if (tptr) {
3505                 rls_lun_statep(isp, tptr);
3506         }
3507         if (notify->nt_need_ack && notify->nt_lreserved) {
3508                 if (((isphdr_t *)notify->nt_lreserved)->rqs_entry_type == RQSTYPE_ABTS_RCVD) {
3509                         if (isp_acknak_abts(isp, notify->nt_lreserved, ENOMEM)) {
3510                                 isp_prt(isp, ISP_LOGWARN, "you lose- unable to send an ACKNAK");
3511                         }
3512                 } else {
3513                         isp_async(isp, ISPASYNC_TARGET_NOTIFY_ACK, notify->nt_lreserved);
3514                 }
3515         }
3516 }
3517
3518 /*
3519  * Find the associated private data and mark it as dead so
3520  * we don't try to work on it any further.
3521  */
3522 static void
3523 isp_target_mark_aborted(ispsoftc_t *isp, union ccb *ccb)
3524 {
3525         tstate_t *tptr;
3526         atio_private_data_t *atp;
3527         union ccb *accb = ccb->cab.abort_ccb;
3528
3529         tptr = get_lun_statep(isp, XS_CHANNEL(accb), XS_LUN(accb));
3530         if (tptr == NULL) {
3531                 tptr = get_lun_statep(isp, XS_CHANNEL(accb), CAM_LUN_WILDCARD);
3532                 if (tptr == NULL) {
3533                         ccb->ccb_h.status = CAM_REQ_INVALID;
3534                         return;
3535                 }
3536         }
3537
3538         atp = isp_find_atpd(isp, tptr, accb->atio.tag_id);
3539         if (atp == NULL) {
3540                 ccb->ccb_h.status = CAM_REQ_INVALID;
3541         } else {
3542                 atp->dead = 1;
3543                 ccb->ccb_h.status = CAM_REQ_CMP;
3544         }
3545         rls_lun_statep(isp, tptr);
3546 }
3547
3548 static void
3549 isp_target_mark_aborted_early(ispsoftc_t *isp, tstate_t *tptr, uint32_t tag_id)
3550 {
3551         atio_private_data_t *atp;
3552         inot_private_data_t *restart_queue = tptr->restart_queue;
3553
3554         /*
3555          * First, clean any commands pending restart
3556          */
3557         tptr->restart_queue = NULL;
3558         while (restart_queue) {
3559                 uint32_t this_tag_id;
3560                 inot_private_data_t *ntp = restart_queue;
3561
3562                 restart_queue = ntp->rd.nt.nt_hba;
3563
3564                 if (IS_24XX(isp)) {
3565                         this_tag_id = ((at7_entry_t *)ntp->rd.data)->at_rxid;
3566                 } else {
3567                         this_tag_id = ((at2_entry_t *)ntp->rd.data)->at_rxid;
3568                 }
3569                 if ((uint64_t)tag_id == TAG_ANY || tag_id == this_tag_id) {
3570                         isp_put_ntpd(isp, tptr, ntp);
3571                 } else {
3572                         ntp->rd.nt.nt_hba = tptr->restart_queue;
3573                         tptr->restart_queue = ntp;
3574                 }
3575         }
3576
3577         /*
3578          * Now mark other ones dead as well.
3579          */
3580         for (atp = tptr->atpool; atp < &tptr->atpool[ATPDPSIZE]; atp++) {
3581                 if ((uint64_t)tag_id == TAG_ANY || atp->tag == tag_id) {
3582                         atp->dead = 1;
3583                 }
3584         }
3585 }
3586
3587
3588 #ifdef  ISP_INTERNAL_TARGET
3589 //#define       ISP_SEPARATE_STATUS     1
3590 #define ISP_MULTI_CCBS          1
3591 #if defined(ISP_MULTI_CCBS) && !defined(ISP_SEPARATE_STATUS)
3592 #define ISP_SEPARATE_STATUS 1
3593 #endif
3594
3595 typedef struct periph_private_data_t {
3596         union ccb *ccb;                 /* original ATIO or Immediate Notify */
3597         unsigned long   offset;         /* current offset */
3598         int             sequence;       /* current CTIO sequence */
3599         int             ctio_cnt;       /* current # of ctio's outstanding */
3600         int
3601                 status_sent     : 1,
3602                 on_queue        : 1;    /* on restart queue */
3603 } ppd_t;
3604 /*
3605  * Each ATIO we allocate will have periph private data associated with it
3606  * that maintains per-command state. This private to each ATIO.
3607  */
3608 #define ATIO_PPD(ccb)           ((ppd_t *)(((struct ccb_hdr *)ccb)->ppriv_ptr0))
3609 /*
3610  * Each CTIO we send downstream will get a pointer to the ATIO itself
3611  * so that on completion we can retrieve that pointer.
3612  */
3613 #define ccb_atio                ppriv_ptr1
3614 #define ccb_inot                ppriv_ptr1
3615
3616 /*
3617  * Each CTIO we send downstream will contain a sequence number
3618  */
3619 #define CTIO_SEQ(ccb)           ccb->ccb_h.ppriv_field0
3620
3621 #define MAX_ISP_TARG_TRANSFER   (2 << 20)
3622 #define NISP_TARG_CMDS          64
3623 #define NISP_TARG_NOTIFIES      64
3624 #define DISK_SHIFT              9
3625 #define JUNK_SIZE               256
3626 #define MULTI_CCB_DATA_LIM      8192
3627 //#define       MULTI_CCB_DATA_CNT      64
3628 #define MULTI_CCB_DATA_CNT      8
3629
3630 extern u_int vm_kmem_size;
3631 static int ca;
3632 static uint32_t disk_size;
3633 static uint8_t *disk_data = NULL;
3634 static uint8_t *junk_data;
3635 static MALLOC_DEFINE(M_ISPTARG, "ISPTARG", "ISP TARGET data");
3636 struct isptarg_softc {
3637         /* CCBs (CTIOs, ATIOs, INOTs) pending on the controller */
3638         struct isp_ccbq         work_queue;
3639         struct isp_ccbq         rework_queue;
3640         struct isp_ccbq         running_queue;
3641         struct isp_ccbq         inot_queue;
3642         struct cam_periph       *periph;
3643         struct cam_path         *path;
3644         ispsoftc_t              *isp;
3645 };
3646 static periph_ctor_t    isptargctor;
3647 static periph_dtor_t    isptargdtor;
3648 static periph_start_t   isptargstart;
3649 static periph_init_t    isptarginit;
3650 static void             isptarg_done(struct cam_periph *, union ccb *);
3651 static void             isptargasync(void *, u_int32_t, struct cam_path *, void *);
3652
3653
3654 static int isptarg_rwparm(uint8_t *, uint8_t *, uint64_t, uint32_t, uint8_t **, uint32_t *, int *);
3655
3656 static struct periph_driver isptargdriver =
3657 {
3658         isptarginit, "isptarg", TAILQ_HEAD_INITIALIZER(isptargdriver.units), 0
3659 };
3660
3661 static void
3662 isptarginit(void)
3663 {
3664 }
3665
3666 static void
3667 isptargnotify(ispsoftc_t *isp, union ccb *iccb, struct ccb_immediate_notify *inot)
3668 {
3669         struct ccb_notify_acknowledge *ack = &iccb->cna2;
3670
3671         ISP_PATH_PRT(isp, ISP_LOGTDEBUG0, inot->ccb_h.path, "%s: [0x%x] immediate notify for 0x%x from 0x%x status 0x%x arg 0x%x\n", __func__,
3672             inot->tag_id, inot->initiator_id, inot->seq_id, inot->ccb_h.status, inot->arg);
3673         ack->ccb_h.func_code = XPT_NOTIFY_ACKNOWLEDGE;
3674         ack->ccb_h.flags = 0;
3675         ack->ccb_h.retry_count = 0;
3676         ack->ccb_h.cbfcnp = isptarg_done;
3677         ack->ccb_h.timeout = 0;
3678         ack->ccb_h.ccb_inot = inot;
3679         ack->tag_id = inot->tag_id;
3680         ack->seq_id = inot->seq_id;
3681         ack->initiator_id = inot->initiator_id;
3682         xpt_action(iccb);
3683 }
3684
3685 static void
3686 isptargstart(struct cam_periph *periph, union ccb *iccb)
3687 {
3688         const uint8_t niliqd[SHORT_INQUIRY_LENGTH] = {
3689                 0x7f, 0x0, 0x5, 0x2, 32, 0, 0, 0x32,
3690                 'F', 'R', 'E', 'E', 'B', 'S', 'D', ' ',
3691                 'S', 'C', 'S', 'I', ' ', 'N', 'U', 'L',
3692                 'L', ' ', 'D', 'E', 'V', 'I', 'C', 'E',
3693                 '0', '0', '0', '1'
3694         };
3695         const uint8_t iqd[SHORT_INQUIRY_LENGTH] = {
3696                 0, 0x0, 0x5, 0x2, 32, 0, 0, 0x32,
3697                 'F', 'R', 'E', 'E', 'B', 'S', 'D', ' ',
3698                 'S', 'C', 'S', 'I', ' ', 'M', 'E', 'M',
3699                 'O', 'R', 'Y', ' ', 'D', 'I', 'S', 'K',
3700                 '0', '0', '0', '1'
3701         };
3702         int r, i, more = 0, last, is_data_cmd = 0, is_write;
3703         char *queue;
3704         struct isptarg_softc *softc = periph->softc;
3705         struct ccb_scsiio *csio;
3706         lun_id_t return_lun;
3707         struct ccb_accept_tio *atio;
3708         uint8_t *cdb, *ptr, status;
3709         uint8_t *data_ptr;
3710         uint32_t data_len, flags;
3711         struct ccb_hdr *ccbh;
3712             
3713         mtx_assert(periph->sim->mtx, MA_OWNED);
3714         ISP_PATH_PRT(softc->isp, ISP_LOGTDEBUG1, iccb->ccb_h.path, "%s: function code 0x%x INOTQ=%c WORKQ=%c REWORKQ=%c\n", __func__, iccb->ccb_h.func_code,
3715             TAILQ_FIRST(&softc->inot_queue)? 'y' : 'n', TAILQ_FIRST(&softc->work_queue)? 'y' : 'n', TAILQ_FIRST(&softc->rework_queue)? 'y' : 'n');
3716         /*
3717          * Check for immediate notifies first
3718          */
3719         ccbh = TAILQ_FIRST(&softc->inot_queue);
3720         if (ccbh) {
3721                 TAILQ_REMOVE(&softc->inot_queue, ccbh, periph_links.tqe);
3722                 if (TAILQ_FIRST(&softc->inot_queue) || TAILQ_FIRST(&softc->work_queue) || TAILQ_FIRST(&softc->rework_queue)) {
3723                         xpt_schedule(periph, 1);
3724                 }
3725                 isptargnotify(softc->isp, iccb, (struct ccb_immediate_notify *)ccbh);
3726                 return;
3727         }
3728
3729         /*
3730          * Check the rework (continuation) work queue first.
3731          */
3732         ccbh = TAILQ_FIRST(&softc->rework_queue);
3733         if (ccbh) {
3734                 atio = (struct ccb_accept_tio *)ccbh;
3735                 TAILQ_REMOVE(&softc->rework_queue, ccbh, periph_links.tqe);
3736                 more = TAILQ_FIRST(&softc->work_queue) || TAILQ_FIRST(&softc->rework_queue);
3737                 queue = "rework";
3738         } else {
3739                 ccbh = TAILQ_FIRST(&softc->work_queue);
3740                 if (ccbh == NULL) {
3741                         xpt_release_ccb(iccb);
3742                         return;
3743                 }
3744                 atio = (struct ccb_accept_tio *)ccbh;
3745                 TAILQ_REMOVE(&softc->work_queue, ccbh, periph_links.tqe);
3746                 more = TAILQ_FIRST(&softc->work_queue) != NULL;
3747                 queue = "work";
3748         }
3749         ATIO_PPD(atio)->on_queue = 0;
3750
3751         if (atio->tag_id == 0xffffffff || atio->ccb_h.func_code != XPT_ACCEPT_TARGET_IO) {
3752                 panic("BAD ATIO");
3753         }
3754
3755         data_len = is_write = 0;
3756         data_ptr = NULL;
3757         csio = &iccb->csio;
3758         status = SCSI_STATUS_OK;
3759         flags = CAM_SEND_STATUS;
3760         memset(&atio->sense_data, 0, sizeof (atio->sense_data));
3761         cdb = atio->cdb_io.cdb_bytes;
3762         ISP_PATH_PRT(softc->isp, ISP_LOGTDEBUG0, ccbh->path, "%s: [0x%x] processing ATIO from %s queue initiator 0x%x CDB=0x%x data_offset=%u\n", __func__, atio->tag_id,
3763             queue, atio->init_id, cdb[0], ATIO_PPD(atio)->offset);
3764
3765         return_lun = XS_LUN(atio);
3766         if (return_lun != 0) {
3767                 xpt_print(atio->ccb_h.path, "[0x%x] Non-Zero Lun %d: cdb0=0x%x\n", atio->tag_id, return_lun, cdb[0]);
3768                 if (cdb[0] != INQUIRY && cdb[0] != REPORT_LUNS && cdb[0] != REQUEST_SENSE) {
3769                         status = SCSI_STATUS_CHECK_COND;
3770                         SDFIXED(atio->sense_data)->error_code = SSD_ERRCODE_VALID|SSD_CURRENT_ERROR;
3771                         SDFIXED(atio->sense_data)->flags = SSD_KEY_ILLEGAL_REQUEST;
3772                         SDFIXED(atio->sense_data)->add_sense_code = 0x25;       /* LOGICAL UNIT NOT SUPPORTED */
3773                         atio->sense_len = SSD_MIN_SIZE;
3774                 }
3775                 return_lun = CAM_LUN_WILDCARD;
3776         }
3777
3778         switch (cdb[0]) {
3779         case REQUEST_SENSE:
3780                 flags |= CAM_DIR_IN;
3781                 data_len = sizeof (atio->sense_data);
3782                 junk_data[0] = SSD_ERRCODE_VALID|SSD_CURRENT_ERROR|SSD_KEY_NO_SENSE;
3783                 memset(junk_data+1, 0, data_len-1);
3784                 if (data_len > cdb[4]) {
3785                         data_len = cdb[4];
3786                 }
3787                 if (data_len) {
3788                         data_ptr = junk_data;
3789                 }
3790                 break;
3791         case WRITE_6:
3792         case WRITE_10:
3793         case WRITE_12:
3794         case WRITE_16:
3795                 is_write = 1;
3796                 /* FALLTHROUGH */
3797         case READ_6:
3798         case READ_10:
3799         case READ_12:
3800         case READ_16:
3801                 is_data_cmd = 1;
3802                 r = isptarg_rwparm(cdb, disk_data, disk_size, ATIO_PPD(atio)->offset, &data_ptr, &data_len, &last);
3803                 if (r != 0) {
3804                         status = SCSI_STATUS_CHECK_COND;
3805                         SDFIXED(atio->sense_data)->error_code = SSD_ERRCODE_VALID|SSD_CURRENT_ERROR;
3806                         SDFIXED(atio->sense_data)->flags = SSD_KEY_ILLEGAL_REQUEST;
3807                         if (r == -1) {
3808                                 SDFIXED(atio->sense_data)->add_sense_code = 0x21;       /* LOGICAL BLOCK ADDRESS OUT OF RANGE */
3809                         } else {
3810                                 SDFIXED(atio->sense_data)->add_sense_code = 0x20;       /* INVALID COMMAND OPERATION CODE */
3811                         }
3812                         atio->sense_len = SSD_MIN_SIZE;
3813                 } else {
3814 #ifdef  ISP_SEPARATE_STATUS
3815                         if (last && data_len) {
3816                                 last = 0;
3817                         }
3818 #endif
3819                         if (last == 0) {
3820                                 flags &= ~CAM_SEND_STATUS;
3821                         }
3822                         if (data_len) {
3823                                 ATIO_PPD(atio)->offset += data_len;
3824                                 if (is_write)
3825                                         flags |= CAM_DIR_OUT;
3826                                 else
3827                                         flags |= CAM_DIR_IN;
3828                         } else {
3829                                 flags |= CAM_DIR_NONE;
3830                         }
3831                 }
3832                 break;
3833         case INQUIRY:
3834                 flags |= CAM_DIR_IN;
3835                 if (cdb[1] || cdb[2] || cdb[3]) {
3836                         status = SCSI_STATUS_CHECK_COND;
3837                         SDFIXED(atio->sense_data)->error_code = SSD_ERRCODE_VALID|SSD_CURRENT_ERROR;
3838                         SDFIXED(atio->sense_data)->flags = SSD_KEY_UNIT_ATTENTION;
3839                         SDFIXED(atio->sense_data)->add_sense_code = 0x24;       /* INVALID FIELD IN CDB */
3840                         atio->sense_len = SSD_MIN_SIZE;
3841                         break;
3842                 }
3843                 data_len = sizeof (iqd);
3844                 if (data_len > cdb[4]) {
3845                         data_len = cdb[4];
3846                 }
3847                 if (data_len) {
3848                         if (XS_LUN(iccb) != 0) {
3849                                 memcpy(junk_data, niliqd, sizeof (iqd));
3850                         } else {
3851                                 memcpy(junk_data, iqd, sizeof (iqd));
3852                         }
3853                         data_ptr = junk_data;
3854                 }
3855                 break;
3856         case TEST_UNIT_READY:
3857                 flags |= CAM_DIR_NONE;
3858                 if (ca) {
3859                         ca = 0;
3860                         status = SCSI_STATUS_CHECK_COND;
3861                         SDFIXED(atio->sense_data)->error_code = SSD_ERRCODE_VALID|SSD_CURRENT_ERROR;
3862                         SDFIXED(atio->sense_data)->flags = SSD_KEY_UNIT_ATTENTION;
3863                         SDFIXED(atio->sense_data)->add_sense_code = 0x29;       /* POWER ON, RESET, OR BUS DEVICE RESET OCCURRED */
3864                         atio->sense_len = SSD_MIN_SIZE;
3865                 }
3866                 break;
3867         case SYNCHRONIZE_CACHE:
3868         case START_STOP:
3869         case RESERVE:
3870         case RELEASE:
3871         case VERIFY_10:
3872                 flags |= CAM_DIR_NONE;
3873                 break;
3874
3875         case READ_CAPACITY:
3876                 flags |= CAM_DIR_IN;
3877                 if (cdb[2] || cdb[3] || cdb[4] || cdb[5]) {
3878                         status = SCSI_STATUS_CHECK_COND;
3879                         SDFIXED(atio->sense_data)->error_code = SSD_ERRCODE_VALID|SSD_CURRENT_ERROR;
3880                         SDFIXED(atio->sense_data)->flags = SSD_KEY_ILLEGAL_REQUEST;
3881                         SDFIXED(atio->sense_data)->add_sense_code =  0x24;      /* INVALID FIELD IN CDB */
3882                         atio->sense_len = SSD_MIN_SIZE;
3883                         break;
3884                 }
3885                 if (cdb[8] & 0x1) { /* PMI */
3886                         junk_data[0] = 0xff;
3887                         junk_data[1] = 0xff;
3888                         junk_data[2] = 0xff;
3889                         junk_data[3] = 0xff;
3890                 } else {
3891                         uint64_t last_blk = (disk_size >> DISK_SHIFT) - 1;
3892                         if (last_blk < 0xffffffffULL) {
3893                             junk_data[0] = (last_blk >> 24) & 0xff;
3894                             junk_data[1] = (last_blk >> 16) & 0xff;
3895                             junk_data[2] = (last_blk >>  8) & 0xff;
3896                             junk_data[3] = (last_blk) & 0xff;
3897                         } else {
3898                             junk_data[0] = 0xff;
3899                             junk_data[1] = 0xff;
3900                             junk_data[2] = 0xff;
3901                             junk_data[3] = 0xff;
3902                         }
3903                 }
3904                 junk_data[4] = ((1 << DISK_SHIFT) >> 24) & 0xff;
3905                 junk_data[5] = ((1 << DISK_SHIFT) >> 16) & 0xff;
3906                 junk_data[6] = ((1 << DISK_SHIFT) >>  8) & 0xff;
3907                 junk_data[7] = ((1 << DISK_SHIFT)) & 0xff;
3908                 data_ptr = junk_data;
3909                 data_len = 8;
3910                 break;
3911         case REPORT_LUNS:
3912                 flags |= CAM_DIR_IN;
3913                 memset(junk_data, 0, JUNK_SIZE);
3914                 junk_data[0] = (1 << 3) >> 24;
3915                 junk_data[1] = (1 << 3) >> 16;
3916                 junk_data[2] = (1 << 3) >> 8;
3917                 junk_data[3] = (1 << 3);
3918                 ptr = NULL;
3919                 for (i = 0; i < 1; i++) {
3920                         ptr = &junk_data[8 + (i << 3)];
3921                         if (i >= 256) {
3922                                 ptr[0] = 0x40 | ((i >> 8) & 0x3f);
3923                         }
3924                         ptr[1] = i;
3925                 }
3926                 data_ptr = junk_data;
3927                 data_len = (ptr + 8) - junk_data;
3928                 break;
3929
3930         default:
3931                 flags |= CAM_DIR_NONE;
3932                 status = SCSI_STATUS_CHECK_COND;
3933                 SDFIXED(atio->sense_data)->error_code = SSD_ERRCODE_VALID|SSD_CURRENT_ERROR;
3934                 SDFIXED(atio->sense_data)->flags = SSD_KEY_ILLEGAL_REQUEST;
3935                 SDFIXED(atio->sense_data)->add_sense_code = 0x20;       /* INVALID COMMAND OPERATION CODE */
3936                 atio->sense_len = SSD_MIN_SIZE;
3937                 break;
3938         }
3939
3940         /*
3941          * If we are done with the transaction, tell the
3942          * controller to send status and perform a CMD_CMPLT.
3943          * If we have associated sense data, see if we can
3944          * send that too.
3945          */
3946         if (status == SCSI_STATUS_CHECK_COND) {
3947                 flags |= CAM_SEND_SENSE;
3948                 csio->sense_len = atio->sense_len;
3949                 csio->sense_data = atio->sense_data;
3950                 flags &= ~CAM_DIR_MASK;
3951                 data_len = 0;
3952                 data_ptr = NULL;
3953         }
3954         cam_fill_ctio(csio, 0, isptarg_done, flags, MSG_SIMPLE_Q_TAG, atio->tag_id, atio->init_id, status, data_ptr, data_len, 30 * hz);
3955         iccb->ccb_h.target_id = atio->ccb_h.target_id;
3956         iccb->ccb_h.target_lun = return_lun;
3957         iccb->ccb_h.ccb_atio = atio;
3958         CTIO_SEQ(iccb) = ATIO_PPD(atio)->sequence++;
3959         ATIO_PPD(atio)->ctio_cnt++;
3960         if (flags & CAM_SEND_STATUS) {
3961                 KASSERT((ATIO_PPD(atio)->status_sent == 0), ("we have already sent status for 0x%x in %s", atio->tag_id, __func__));
3962                 ATIO_PPD(atio)->status_sent = 1;
3963         }
3964         ISP_PATH_PRT(softc->isp, ISP_LOGTDEBUG0, atio->ccb_h.path, "%s: sending downstream for  0x%x sequence %u len %u flags %x\n", __func__, atio->tag_id, CTIO_SEQ(iccb), data_len, flags);
3965         xpt_action(iccb);
3966
3967         if ((atio->ccb_h.status & CAM_DEV_QFRZN) != 0) {
3968                 cam_release_devq(periph->path, 0, 0, 0, 0); 
3969                 atio->ccb_h.status &= ~CAM_DEV_QFRZN;
3970         }
3971 #ifdef  ISP_MULTI_CCBS
3972         if (is_data_cmd && ATIO_PPD(atio)->status_sent == 0 && ATIO_PPD(atio)->ctio_cnt < MULTI_CCB_DATA_CNT && ATIO_PPD(atio)->on_queue == 0) {
3973                 ISP_PATH_PRT(softc->isp, ISP_LOGTDEBUG0, atio->ccb_h.path, "%s: more still to do for 0x%x\n", __func__, atio->tag_id);
3974                 TAILQ_INSERT_TAIL(&softc->rework_queue, &atio->ccb_h, periph_links.tqe); 
3975                 ATIO_PPD(atio)->on_queue = 1;
3976                 more = 1;
3977         }
3978 #endif
3979         if (more) {
3980                 xpt_schedule(periph, 1);
3981         }
3982 }
3983
3984 static cam_status
3985 isptargctor(struct cam_periph *periph, void *arg)
3986 {
3987         struct isptarg_softc *softc;
3988
3989         softc = (struct isptarg_softc *)arg;
3990         periph->softc = softc;
3991         softc->periph = periph;
3992         softc->path = periph->path;
3993         ISP_PATH_PRT(softc->isp, ISP_LOGTDEBUG1, periph->path, "%s called\n", __func__);
3994         return (CAM_REQ_CMP);
3995 }
3996
3997 static void
3998 isptargdtor(struct cam_periph *periph)
3999 {
4000         struct isptarg_softc *softc;
4001         softc = (struct isptarg_softc *)periph->softc;
4002         ISP_PATH_PRT(softc->isp, ISP_LOGTDEBUG1, periph->path, "%s called\n", __func__);
4003         softc->periph = NULL;
4004         softc->path = NULL;
4005         periph->softc = NULL;
4006 }
4007
4008 static void
4009 isptarg_done(struct cam_periph *periph, union ccb *ccb)
4010 {
4011         struct isptarg_softc *softc;
4012         ispsoftc_t *isp;
4013         uint32_t newoff;
4014         struct ccb_accept_tio *atio;
4015         struct ccb_immediate_notify *inot;
4016         cam_status status;
4017
4018         softc = (struct isptarg_softc *)periph->softc;
4019         isp = softc->isp;
4020         status = ccb->ccb_h.status & CAM_STATUS_MASK;
4021
4022         switch (ccb->ccb_h.func_code) {
4023         case XPT_ACCEPT_TARGET_IO:
4024                 atio = (struct ccb_accept_tio *) ccb;
4025                 ISP_PATH_PRT(isp, ISP_LOGTDEBUG0, ccb->ccb_h.path, "[0x%x] ATIO seen in %s\n", atio->tag_id, __func__);
4026                 memset(ATIO_PPD(atio), 0, sizeof (ppd_t));
4027                 TAILQ_INSERT_TAIL(&softc->work_queue, &ccb->ccb_h, periph_links.tqe); 
4028                 ATIO_PPD(atio)->on_queue = 1;
4029                 xpt_schedule(periph, 1);
4030                 break;
4031         case XPT_IMMEDIATE_NOTIFY:
4032                 inot = (struct ccb_immediate_notify *) ccb;
4033                 ISP_PATH_PRT(isp, ISP_LOGTDEBUG0, ccb->ccb_h.path, "[0x%x] INOT for 0x%x seen in %s\n", inot->tag_id, inot->seq_id, __func__);
4034                 TAILQ_INSERT_TAIL(&softc->inot_queue, &ccb->ccb_h, periph_links.tqe); 
4035                 xpt_schedule(periph, 1);
4036                 break;
4037         case XPT_CONT_TARGET_IO:
4038                 atio = ccb->ccb_h.ccb_atio;
4039                 KASSERT((ATIO_PPD(atio)->ctio_cnt != 0), ("ctio zero when finishing a CTIO"));
4040                 ATIO_PPD(atio)->ctio_cnt--;
4041                 if ((ccb->ccb_h.status & CAM_STATUS_MASK) != CAM_REQ_CMP) {
4042                         switch (ccb->ccb_h.status & CAM_STATUS_MASK) {
4043                         case CAM_MESSAGE_RECV:
4044                                 newoff = (ccb->csio.msg_ptr[3] << 24) | (ccb->csio.msg_ptr[4] << 16) | (ccb->csio.msg_ptr[5] << 8) | (ccb->csio.msg_ptr[6]);
4045                                 ISP_PATH_PRT(isp, ISP_LOGWARN, ccb->ccb_h.path, "[0x%x] got message to return to reset offset to 0x%x at sequence %u\n", atio->tag_id, newoff, CTIO_SEQ(ccb));
4046                                 ATIO_PPD(atio)->offset = newoff;
4047                                 ATIO_PPD(atio)->status_sent = 0;
4048                                 if (ATIO_PPD(atio)->on_queue == 0) {
4049                                         TAILQ_INSERT_TAIL(&softc->rework_queue, &atio->ccb_h, periph_links.tqe); 
4050                                         ATIO_PPD(atio)->on_queue = 1;
4051                                 }
4052                                 xpt_schedule(periph, 1);
4053                                 break;
4054                         default:
4055                                 cam_error_print(ccb, CAM_ESF_ALL, CAM_EPF_ALL);
4056                                 xpt_action((union ccb *)atio);
4057                                 break;
4058                         }
4059                 } else if ((ccb->ccb_h.flags & CAM_SEND_STATUS) == 0) {
4060                         ISP_PATH_PRT(isp, ISP_LOGTDEBUG0, ccb->ccb_h.path, "[0x%x] MID CTIO sequence %u seen in %s\n", atio->tag_id, CTIO_SEQ(ccb), __func__);
4061                         if (ATIO_PPD(atio)->status_sent == 0 && ATIO_PPD(atio)->on_queue == 0) {
4062                                 TAILQ_INSERT_TAIL(&softc->rework_queue, &atio->ccb_h, periph_links.tqe); 
4063                                 ATIO_PPD(atio)->on_queue = 1;
4064                         }
4065                         xpt_schedule(periph, 1);
4066                 } else {
4067                         KASSERT((ATIO_PPD(atio)->ctio_cnt == 0), ("ctio count still %d when we think we've sent the STATUS ctio", ATIO_PPD(atio)->ctio_cnt));
4068                         ISP_PATH_PRT(isp, ISP_LOGTDEBUG0, ccb->ccb_h.path, "[0x%x] FINAL CTIO sequence %u seen in %s\n", atio->tag_id, CTIO_SEQ(ccb), __func__);
4069                         xpt_action((union ccb *)atio);
4070                 }
4071                 if ((ccb->ccb_h.status & CAM_DEV_QFRZN) != 0) {
4072                         cam_release_devq(ccb->ccb_h.path, 0, 0, 0, 0); 
4073                         ccb->ccb_h.status &= ~CAM_DEV_QFRZN;
4074                 }
4075                 xpt_release_ccb(ccb);
4076                 break;
4077         case XPT_NOTIFY_ACKNOWLEDGE:
4078                 if ((ccb->ccb_h.status & CAM_DEV_QFRZN) != 0) {
4079                         cam_release_devq(ccb->ccb_h.path, 0, 0, 0, 0); 
4080                         ccb->ccb_h.status &= ~CAM_DEV_QFRZN;
4081                 }
4082                 inot = ccb->ccb_h.ccb_inot;
4083                 ISP_PATH_PRT(isp, ISP_LOGTDEBUG1, inot->ccb_h.path, "[0x%x] recycle notify for tag 0x%x\n", inot->tag_id, inot->seq_id);
4084                 xpt_release_ccb(ccb);
4085                 xpt_action((union ccb *)inot);
4086                 break;
4087         default:
4088                 xpt_print(ccb->ccb_h.path, "unexpected code 0x%x\n", ccb->ccb_h.func_code);
4089                 break;
4090         }
4091 }
4092
4093 static void
4094 isptargasync(void *callback_arg, u_int32_t code, struct cam_path *path, void *arg)
4095 {
4096         struct ac_contract *acp = arg;
4097         struct ac_device_changed *fc = (struct ac_device_changed *) acp->contract_data;
4098
4099         if (code != AC_CONTRACT) {
4100                 return;
4101         }
4102         xpt_print(path, "0x%016llx Port ID 0x%06x %s\n", (unsigned long long) fc->wwpn, fc->port, fc->arrived? "arrived" : "departed");
4103 }
4104
4105 static void
4106 isp_target_thread(ispsoftc_t *isp, int chan)
4107 {
4108         union ccb *ccb = NULL;
4109         int i;
4110         void *wchan;
4111         cam_status status;
4112         struct isptarg_softc *softc = NULL;
4113         struct cam_periph *periph = NULL, *wperiph = NULL;
4114         struct cam_path *path, *wpath;
4115         struct cam_sim *sim;
4116
4117         if (disk_data == NULL) {
4118                 disk_size = roundup2(vm_kmem_size >> 1, (1ULL << 20));
4119                 if (disk_size < (50 << 20)) {
4120                         disk_size = 50 << 20;
4121                 }
4122                 disk_data = malloc(disk_size, M_ISPTARG, M_WAITOK | M_ZERO);
4123                 if (disk_data == NULL) {
4124                         isp_prt(isp, ISP_LOGERR, "%s: could not allocate disk data", __func__);
4125                         goto out;
4126                 }
4127                 isp_prt(isp, ISP_LOGINFO, "allocated a %ju MiB disk", (uintmax_t) (disk_size >> 20));
4128         }
4129         junk_data = malloc(JUNK_SIZE, M_ISPTARG, M_WAITOK | M_ZERO);
4130         if (junk_data == NULL) {
4131                 isp_prt(isp, ISP_LOGERR, "%s: could not allocate junk", __func__);
4132                 goto out;
4133         }
4134
4135
4136         softc = malloc(sizeof (*softc), M_ISPTARG, M_WAITOK | M_ZERO);
4137         if (softc == NULL) {
4138                 isp_prt(isp, ISP_LOGERR, "%s: could not allocate softc", __func__);
4139                 goto out;
4140         }
4141         TAILQ_INIT(&softc->work_queue);
4142         TAILQ_INIT(&softc->rework_queue);
4143         TAILQ_INIT(&softc->running_queue);
4144         TAILQ_INIT(&softc->inot_queue);
4145         softc->isp = isp;
4146
4147         periphdriver_register(&isptargdriver);
4148         ISP_GET_PC(isp, chan, sim, sim);
4149         ISP_GET_PC(isp, chan, path,  path);
4150         status = xpt_create_path(&wpath, NULL, cam_sim_path(sim), CAM_TARGET_WILDCARD, CAM_LUN_WILDCARD);
4151         if (status != CAM_REQ_CMP) {
4152                 isp_prt(isp, ISP_LOGERR, "%s: could not allocate wildcard path", __func__);
4153                 return;
4154         }
4155         status = xpt_create_path(&path, NULL, cam_sim_path(sim), 0, 0);
4156         if (status != CAM_REQ_CMP) {
4157                 xpt_free_path(wpath);
4158                 isp_prt(isp, ISP_LOGERR, "%s: could not allocate path", __func__);
4159                 return;
4160         }
4161
4162         ISP_LOCK(isp);
4163         status = cam_periph_alloc(isptargctor, NULL, isptargdtor, isptargstart, "isptarg", CAM_PERIPH_BIO, wpath, NULL, 0, softc);
4164         if (status != CAM_REQ_CMP) {
4165                 ISP_UNLOCK(isp);
4166                 isp_prt(isp, ISP_LOGERR, "%s: cam_periph_alloc for wildcard failed", __func__);
4167                 goto out;
4168         }
4169         wperiph = cam_periph_find(wpath, "isptarg");
4170         if (wperiph == NULL) {
4171                 ISP_UNLOCK(isp);
4172                 isp_prt(isp, ISP_LOGERR, "%s: wildcard periph already allocated but doesn't exist", __func__);
4173                 goto out;
4174         }
4175
4176         status = cam_periph_alloc(isptargctor, NULL, isptargdtor, isptargstart, "isptarg", CAM_PERIPH_BIO, path, NULL, 0, softc);
4177         if (status != CAM_REQ_CMP) {
4178                 ISP_UNLOCK(isp);
4179                 isp_prt(isp, ISP_LOGERR, "%s: cam_periph_alloc failed", __func__);
4180                 goto out;
4181         }
4182
4183         periph = cam_periph_find(path, "isptarg");
4184         if (periph == NULL) {
4185                 ISP_UNLOCK(isp);
4186                 isp_prt(isp, ISP_LOGERR, "%s: periph already allocated but doesn't exist", __func__);
4187                 goto out;
4188         }
4189
4190         status = xpt_register_async(AC_CONTRACT, isptargasync, isp, wpath);
4191         if (status != CAM_REQ_CMP) {
4192                 ISP_UNLOCK(isp);
4193                 isp_prt(isp, ISP_LOGERR, "%s: xpt_register_async failed", __func__);
4194                 goto out;
4195         }
4196
4197         ISP_UNLOCK(isp);
4198
4199         ccb = xpt_alloc_ccb();
4200
4201         /*
4202          * Make sure role is none.
4203          */
4204         xpt_setup_ccb(&ccb->ccb_h, periph->path, 10);
4205         ccb->ccb_h.func_code = XPT_SET_SIM_KNOB;
4206         ccb->knob.xport_specific.fc.role = KNOB_ROLE_NONE;
4207         ccb->knob.xport_specific.fc.valid = KNOB_VALID_ROLE;
4208
4209         ISP_LOCK(isp);
4210         xpt_action(ccb);
4211         ISP_UNLOCK(isp);
4212
4213         /*
4214          * Now enable luns
4215          */
4216         xpt_setup_ccb(&ccb->ccb_h, periph->path, 10);
4217         ccb->ccb_h.func_code = XPT_EN_LUN;
4218         ccb->cel.enable = 1;
4219         ISP_LOCK(isp);
4220         xpt_action(ccb);
4221         ISP_UNLOCK(isp);
4222         if (ccb->ccb_h.status != CAM_REQ_CMP) {
4223                 xpt_free_ccb(ccb);
4224                 xpt_print(periph->path, "failed to enable lun (0x%x)\n", ccb->ccb_h.status);
4225                 goto out;
4226         }
4227
4228         xpt_setup_ccb(&ccb->ccb_h, wperiph->path, 10);
4229         ccb->ccb_h.func_code = XPT_EN_LUN;
4230         ccb->cel.enable = 1;
4231         ISP_LOCK(isp);
4232         xpt_action(ccb);
4233         ISP_UNLOCK(isp);
4234         if (ccb->ccb_h.status != CAM_REQ_CMP) {
4235                 xpt_free_ccb(ccb);
4236                 xpt_print(wperiph->path, "failed to enable lun (0x%x)\n", ccb->ccb_h.status);
4237                 goto out;
4238         }
4239         xpt_free_ccb(ccb);
4240
4241         /*
4242          * Add resources
4243          */
4244         ISP_GET_PC(isp, chan, target_proc, wchan);
4245         for (i = 0; i < 4; i++) {
4246                 ccb = malloc(sizeof (*ccb), M_ISPTARG, M_WAITOK | M_ZERO);
4247                 xpt_setup_ccb(&ccb->ccb_h, wperiph->path, 1);
4248                 ccb->ccb_h.func_code = XPT_ACCEPT_TARGET_IO;
4249                 ccb->ccb_h.cbfcnp = isptarg_done;
4250                 ccb->ccb_h.ppriv_ptr0 = malloc(sizeof (ppd_t), M_ISPTARG, M_WAITOK | M_ZERO);
4251                 ISP_LOCK(isp);
4252                 xpt_action(ccb);
4253                 ISP_UNLOCK(isp);
4254         }
4255         for (i = 0; i < NISP_TARG_CMDS; i++) {
4256                 ccb = malloc(sizeof (*ccb), M_ISPTARG, M_WAITOK | M_ZERO);
4257                 xpt_setup_ccb(&ccb->ccb_h, periph->path, 1);
4258                 ccb->ccb_h.func_code = XPT_ACCEPT_TARGET_IO;
4259                 ccb->ccb_h.cbfcnp = isptarg_done;
4260                 ccb->ccb_h.ppriv_ptr0 = malloc(sizeof (ppd_t), M_ISPTARG, M_WAITOK | M_ZERO);
4261                 ISP_LOCK(isp);
4262                 xpt_action(ccb);
4263                 ISP_UNLOCK(isp);
4264         }
4265         for (i = 0; i < 4; i++) {
4266                 ccb = malloc(sizeof (*ccb), M_ISPTARG, M_WAITOK | M_ZERO);
4267                 xpt_setup_ccb(&ccb->ccb_h, wperiph->path, 1);
4268                 ccb->ccb_h.func_code = XPT_IMMEDIATE_NOTIFY;
4269                 ccb->ccb_h.cbfcnp = isptarg_done;
4270                 ISP_LOCK(isp);
4271                 xpt_action(ccb);
4272                 ISP_UNLOCK(isp);
4273         }
4274         for (i = 0; i < NISP_TARG_NOTIFIES; i++) {
4275                 ccb = malloc(sizeof (*ccb), M_ISPTARG, M_WAITOK | M_ZERO);
4276                 xpt_setup_ccb(&ccb->ccb_h, periph->path, 1);
4277                 ccb->ccb_h.func_code = XPT_IMMEDIATE_NOTIFY;
4278                 ccb->ccb_h.cbfcnp = isptarg_done;
4279                 ISP_LOCK(isp);
4280                 xpt_action(ccb);
4281                 ISP_UNLOCK(isp);
4282         }
4283
4284         /*
4285          * Now turn it all back on
4286          */
4287         xpt_setup_ccb(&ccb->ccb_h, periph->path, 10);
4288         ccb->ccb_h.func_code = XPT_SET_SIM_KNOB;
4289         ccb->knob.xport_specific.fc.valid = KNOB_VALID_ROLE;
4290         ccb->knob.xport_specific.fc.role = KNOB_ROLE_TARGET;
4291         ISP_LOCK(isp);
4292         xpt_action(ccb);
4293         ISP_UNLOCK(isp);
4294
4295         /*
4296          * Okay, while things are still active, sleep...
4297          */
4298         ISP_LOCK(isp);
4299         for (;;) {
4300                 ISP_GET_PC(isp, chan, proc_active, i);
4301                 if (i == 0) {
4302                         break;
4303                 }
4304                 msleep(wchan, &isp->isp_lock, PUSER, "tsnooze", 0);
4305         }
4306         ISP_UNLOCK(isp);
4307
4308 out:
4309         if (wperiph) {
4310                 cam_periph_invalidate(wperiph);
4311         }
4312         if (periph) {
4313                 cam_periph_invalidate(periph);
4314         }
4315         if (junk_data) {
4316                 free(junk_data, M_ISPTARG);
4317         }
4318         if (disk_data) {
4319                 free(disk_data, M_ISPTARG);
4320         }
4321         if (softc) {
4322                 free(softc, M_ISPTARG);
4323         }
4324         xpt_free_path(path);
4325         xpt_free_path(wpath);
4326 }
4327
4328 static void
4329 isp_target_thread_pi(void *arg)
4330 {
4331         struct isp_spi *pi = arg;
4332         ispsoftc_t *isp = cam_sim_softc(pi->sim);
4333         int chan = cam_sim_bus(pi->sim);
4334
4335         isp_target_thread(isp, chan);
4336         ISP_SPI_PC(isp, chan)->num_threads -= 1;
4337         kthread_exit();
4338 }
4339
4340 static void
4341 isp_target_thread_fc(void *arg)
4342 {
4343         struct isp_fc *fc = arg;
4344         ispsoftc_t *isp = cam_sim_softc(pi->sim);
4345         int chan = cam_sim_bus(pi->sim);
4346
4347         isp_target_thread(isp, chan);
4348         ISP_FC_PC(isp, chan)->num_threads -= 1;
4349         kthread_exit();
4350 }
4351
4352 static int
4353 isptarg_rwparm(uint8_t *cdb, uint8_t *dp, uint64_t dl, uint32_t offset, uint8_t **kp, uint32_t *tl, int *lp)
4354 {
4355         uint32_t cnt, curcnt;
4356         uint64_t lba;
4357
4358         switch (cdb[0]) {
4359         case WRITE_16:
4360         case READ_16:
4361                 cnt =   (((uint32_t)cdb[10]) <<  24) |
4362                         (((uint32_t)cdb[11]) <<  16) |
4363                         (((uint32_t)cdb[12]) <<   8) |
4364                         ((uint32_t)cdb[13]);
4365
4366                 lba =   (((uint64_t)cdb[2]) << 56) |
4367                         (((uint64_t)cdb[3]) << 48) |
4368                         (((uint64_t)cdb[4]) << 40) |
4369                         (((uint64_t)cdb[5]) << 32) |
4370                         (((uint64_t)cdb[6]) << 24) |
4371                         (((uint64_t)cdb[7]) << 16) |
4372                         (((uint64_t)cdb[8]) <<  8) |
4373                         ((uint64_t)cdb[9]);
4374                 break;
4375         case WRITE_12:
4376         case READ_12:
4377                 cnt =   (((uint32_t)cdb[6]) <<  16) |
4378                         (((uint32_t)cdb[7]) <<   8) |
4379                         ((u_int32_t)cdb[8]);
4380
4381                 lba =   (((uint32_t)cdb[2]) << 24) |
4382                         (((uint32_t)cdb[3]) << 16) |
4383                         (((uint32_t)cdb[4]) <<  8) |
4384                         ((uint32_t)cdb[5]);
4385                 break;
4386         case WRITE_10:
4387         case READ_10:
4388                 cnt =   (((uint32_t)cdb[7]) <<  8) |
4389                         ((u_int32_t)cdb[8]);
4390
4391                 lba =   (((uint32_t)cdb[2]) << 24) |
4392                         (((uint32_t)cdb[3]) << 16) |
4393                         (((uint32_t)cdb[4]) <<  8) |
4394                         ((uint32_t)cdb[5]);
4395                 break;
4396         case WRITE_6:
4397         case READ_6:
4398                 cnt = cdb[4];
4399                 if (cnt == 0) {
4400                         cnt = 256;
4401                 }
4402                 lba =   (((uint32_t)cdb[1] & 0x1f) << 16) |
4403                         (((uint32_t)cdb[2]) << 8) |
4404                         ((uint32_t)cdb[3]);
4405                 break;
4406         default:
4407                 return (-1);
4408         }
4409
4410         cnt <<= DISK_SHIFT;
4411         lba <<= DISK_SHIFT;
4412
4413         if (offset == cnt) {
4414                 *lp = 1;
4415                 return (0);
4416         }
4417
4418         if (lba + cnt > dl) {
4419                 return (-2);
4420         }
4421
4422         curcnt = MAX_ISP_TARG_TRANSFER;
4423         if (offset + curcnt >= cnt) {
4424                 curcnt = cnt - offset;
4425                 *lp = 1;
4426         } else {
4427                 *lp = 0;
4428         }
4429 #ifdef  ISP_MULTI_CCBS
4430         if (curcnt > MULTI_CCB_DATA_LIM)
4431                 curcnt = MULTI_CCB_DATA_LIM;
4432 #endif
4433         *tl = curcnt;
4434         *kp = &dp[lba + offset];
4435         return (0);
4436 }
4437
4438 #endif
4439 #endif
4440
4441 static void
4442 isp_cam_async(void *cbarg, uint32_t code, struct cam_path *path, void *arg)
4443 {
4444         struct cam_sim *sim;
4445         int bus, tgt;
4446         ispsoftc_t *isp;
4447
4448         sim = (struct cam_sim *)cbarg;
4449         isp = (ispsoftc_t *) cam_sim_softc(sim);
4450         bus = cam_sim_bus(sim);
4451         tgt = xpt_path_target_id(path);
4452
4453         switch (code) {
4454         case AC_LOST_DEVICE:
4455                 if (IS_SCSI(isp)) {
4456                         uint16_t oflags, nflags;
4457                         sdparam *sdp = SDPARAM(isp, bus);
4458
4459                         if (tgt >= 0) {
4460                                 nflags = sdp->isp_devparam[tgt].nvrm_flags;
4461 #ifndef ISP_TARGET_MODE
4462                                 nflags &= DPARM_SAFE_DFLT;
4463                                 if (isp->isp_loaded_fw) {
4464                                         nflags |= DPARM_NARROW | DPARM_ASYNC;
4465                                 }
4466 #else
4467                                 nflags = DPARM_DEFAULT;
4468 #endif
4469                                 oflags = sdp->isp_devparam[tgt].goal_flags;
4470                                 sdp->isp_devparam[tgt].goal_flags = nflags;
4471                                 sdp->isp_devparam[tgt].dev_update = 1;
4472                                 sdp->update = 1;
4473                                 (void) isp_control(isp, ISPCTL_UPDATE_PARAMS, bus);
4474                                 sdp->isp_devparam[tgt].goal_flags = oflags;
4475                         }
4476                 }
4477                 break;
4478         default:
4479                 isp_prt(isp, ISP_LOGWARN, "isp_cam_async: Code 0x%x", code);
4480                 break;
4481         }
4482 }
4483
4484 static void
4485 isp_poll(struct cam_sim *sim)
4486 {
4487         ispsoftc_t *isp = cam_sim_softc(sim);
4488         uint32_t isr;
4489         uint16_t sema, mbox;
4490
4491         if (ISP_READ_ISR(isp, &isr, &sema, &mbox)) {
4492                 isp_intr(isp, isr, sema, mbox);
4493         }
4494 }
4495
4496
4497 static void
4498 isp_watchdog(void *arg)
4499 {
4500         struct ccb_scsiio *xs = arg;
4501         ispsoftc_t *isp;
4502         uint32_t ohandle = ISP_HANDLE_FREE, handle;
4503
4504         isp = XS_ISP(xs);
4505
4506         handle = isp_find_handle(isp, xs);
4507
4508         /*
4509          * Hand crank the interrupt code just to be sure the command isn't stuck somewhere.
4510          */
4511         if (handle != ISP_HANDLE_FREE) {
4512                 uint32_t isr;
4513                 uint16_t sema, mbox;
4514                 if (ISP_READ_ISR(isp, &isr, &sema, &mbox) != 0) {
4515                         isp_intr(isp, isr, sema, mbox);
4516                 }
4517                 ohandle = handle;
4518                 handle = isp_find_handle(isp, xs);
4519         }
4520         if (handle != ISP_HANDLE_FREE) {
4521                 /*
4522                  * Try and make sure the command is really dead before
4523                  * we release the handle (and DMA resources) for reuse.
4524                  *
4525                  * If we are successful in aborting the command then
4526                  * we're done here because we'll get the command returned
4527                  * back separately.
4528                  */
4529                 if (isp_control(isp, ISPCTL_ABORT_CMD, xs) == 0) {
4530                         return;
4531                 }
4532
4533                 /*
4534                  * Note that after calling the above, the command may in
4535                  * fact have been completed.
4536                  */
4537                 xs = isp_find_xs(isp, handle);
4538
4539                 /*
4540                  * If the command no longer exists, then we won't
4541                  * be able to find the xs again with this handle.
4542                  */
4543                 if (xs == NULL) {
4544                         return;
4545                 }
4546
4547                 /*
4548                  * After this point, the command is really dead.
4549                  */
4550                 if (XS_XFRLEN(xs)) {
4551                         ISP_DMAFREE(isp, xs, handle);
4552                 } 
4553                 isp_destroy_handle(isp, handle);
4554                 isp_prt(isp, ISP_LOGERR, "%s: timeout for handle 0x%x", __func__, handle);
4555                 xs->ccb_h.status &= ~CAM_STATUS_MASK;
4556                 xs->ccb_h.status |= CAM_CMD_TIMEOUT;
4557                 isp_prt_endcmd(isp, xs);
4558                 isp_done(xs);
4559         } else {
4560                 if (ohandle != ISP_HANDLE_FREE) {
4561                         isp_prt(isp, ISP_LOGWARN, "%s: timeout for handle 0x%x, recovered during interrupt", __func__, ohandle);
4562                 } else {
4563                         isp_prt(isp, ISP_LOGWARN, "%s: timeout for handle already free", __func__);
4564                 }
4565         }
4566 }
4567
4568 static void
4569 isp_make_here(ispsoftc_t *isp, fcportdb_t *fcp, int chan, int tgt)
4570 {
4571         union ccb *ccb;
4572         struct isp_fc *fc = ISP_FC_PC(isp, chan);
4573
4574         if (isp_autoconfig == 0) {
4575                 return;
4576         }
4577
4578         /*
4579          * Allocate a CCB, create a wildcard path for this target and schedule a rescan.
4580          */
4581         ccb = xpt_alloc_ccb_nowait();
4582         if (ccb == NULL) {
4583                 isp_prt(isp, ISP_LOGWARN, "Chan %d unable to alloc CCB for rescan", chan);
4584                 return;
4585         }
4586         if (xpt_create_path(&ccb->ccb_h.path, NULL, cam_sim_path(fc->sim),
4587             tgt, CAM_LUN_WILDCARD) != CAM_REQ_CMP) {
4588                 isp_prt(isp, ISP_LOGWARN, "unable to create path for rescan");
4589                 xpt_free_ccb(ccb);
4590                 return;
4591         }
4592
4593         /*
4594          * Since we're about to issue a rescan, mark this device as not
4595          * reported gone.
4596          */
4597         fcp->reported_gone = 0;
4598
4599         xpt_rescan(ccb);
4600 }
4601
4602 static void
4603 isp_make_gone(ispsoftc_t *isp, fcportdb_t *fcp, int chan, int tgt)
4604 {
4605         struct cam_path *tp;
4606         struct isp_fc *fc = ISP_FC_PC(isp, chan);
4607
4608         if (isp_autoconfig == 0) {
4609                 return;
4610         }
4611         if (xpt_create_path(&tp, NULL, cam_sim_path(fc->sim), tgt, CAM_LUN_WILDCARD) == CAM_REQ_CMP) {
4612                 /*
4613                  * We're about to send out the lost device async
4614                  * notification, so indicate that we have reported it gone.
4615                  */
4616                 fcp->reported_gone = 1;
4617                 xpt_async(AC_LOST_DEVICE, tp, NULL);
4618                 xpt_free_path(tp);
4619         }
4620 }
4621
4622 /*
4623  * Gone Device Timer Function- when we have decided that a device has gone
4624  * away, we wait a specific period of time prior to telling the OS it has
4625  * gone away.
4626  *
4627  * This timer function fires once a second and then scans the port database
4628  * for devices that are marked dead but still have a virtual target assigned.
4629  * We decrement a counter for that port database entry, and when it hits zero,
4630  * we tell the OS the device has gone away.
4631  */
4632 static void
4633 isp_gdt(void *arg)
4634 {
4635         struct isp_fc *fc = arg;
4636         taskqueue_enqueue(taskqueue_thread, &fc->gtask);
4637 }
4638
4639 static void
4640 isp_gdt_task(void *arg, int pending)
4641 {
4642         struct isp_fc *fc = arg;
4643         ispsoftc_t *isp = fc->isp;
4644         int chan = fc - isp->isp_osinfo.pc.fc;
4645         fcportdb_t *lp;
4646         int dbidx, tgt, more_to_do = 0;
4647
4648         ISP_LOCK(isp);
4649         isp_prt(isp, ISP_LOGDEBUG0, "Chan %d GDT timer expired", chan);
4650         for (dbidx = 0; dbidx < MAX_FC_TARG; dbidx++) {
4651                 lp = &FCPARAM(isp, chan)->portdb[dbidx];
4652
4653                 if (lp->state != FC_PORTDB_STATE_ZOMBIE) {
4654                         continue;
4655                 }
4656                 if (lp->dev_map_idx == 0 || lp->target_mode) {
4657                         continue;
4658                 }
4659                 if (lp->gone_timer != 0) {
4660                         isp_prt(isp, ISP_LOG_SANCFG, "%s: Chan %d more to do for target %u (timer=%u)", __func__, chan, lp->dev_map_idx - 1, lp->gone_timer);
4661                         lp->gone_timer -= 1;
4662                         more_to_do++;
4663                         continue;
4664                 }
4665                 tgt = lp->dev_map_idx - 1;
4666                 FCPARAM(isp, chan)->isp_dev_map[tgt] = 0;
4667                 lp->dev_map_idx = 0;
4668                 lp->state = FC_PORTDB_STATE_NIL;
4669                 isp_prt(isp, ISP_LOGCONFIG, prom3, chan, lp->portid, tgt, "Gone Device Timeout");
4670                 isp_make_gone(isp, lp, chan, tgt);
4671         }
4672         if (fc->ready) {
4673                 if (more_to_do) {
4674                         callout_reset(&fc->gdt, hz, isp_gdt, fc);
4675                 } else {
4676                         callout_deactivate(&fc->gdt);
4677                         isp_prt(isp, ISP_LOG_SANCFG, "Chan %d Stopping Gone Device Timer @ %lu", chan, (unsigned long) time_uptime);
4678                 }
4679         }
4680         ISP_UNLOCK(isp);
4681 }
4682
4683 /*
4684  * Loop Down Timer Function- when loop goes down, a timer is started and
4685  * and after it expires we come here and take all probational devices that
4686  * the OS knows about and the tell the OS that they've gone away.
4687  * 
4688  * We don't clear the devices out of our port database because, when loop
4689  * come back up, we have to do some actual cleanup with the chip at that
4690  * point (implicit PLOGO, e.g., to get the chip's port database state right).
4691  */
4692 static void
4693 isp_ldt(void *arg)
4694 {
4695         struct isp_fc *fc = arg;
4696         taskqueue_enqueue(taskqueue_thread, &fc->ltask);
4697 }
4698
4699 static void
4700 isp_ldt_task(void *arg, int pending)
4701 {
4702         struct isp_fc *fc = arg;
4703         ispsoftc_t *isp = fc->isp;
4704         int chan = fc - isp->isp_osinfo.pc.fc;
4705         fcportdb_t *lp;
4706         int dbidx, tgt, i;
4707
4708         ISP_LOCK(isp);
4709         isp_prt(isp, ISP_LOG_SANCFG|ISP_LOGDEBUG0, "Chan %d Loop Down Timer expired @ %lu", chan, (unsigned long) time_uptime);
4710         callout_deactivate(&fc->ldt);
4711
4712         /*
4713          * Notify to the OS all targets who we now consider have departed.
4714          */
4715         for (dbidx = 0; dbidx < MAX_FC_TARG; dbidx++) {
4716                 lp = &FCPARAM(isp, chan)->portdb[dbidx];
4717
4718                 if (lp->state != FC_PORTDB_STATE_PROBATIONAL) {
4719                         continue;
4720                 }
4721                 if (lp->dev_map_idx == 0 || lp->target_mode) {
4722                         continue;
4723                 }
4724
4725                 /*
4726                  * XXX: CLEAN UP AND COMPLETE ANY PENDING COMMANDS FIRST!
4727                  */
4728
4729
4730                 for (i = 0; i < isp->isp_maxcmds; i++) {
4731                         struct ccb_scsiio *xs;
4732
4733                         if (!ISP_VALID_HANDLE(isp, isp->isp_xflist[i].handle)) {
4734                                 continue;
4735                         }
4736                         if ((xs = isp->isp_xflist[i].cmd) == NULL) {
4737                                 continue;
4738                         }
4739                         if (dbidx != (FCPARAM(isp, chan)->isp_dev_map[XS_TGT(xs)] - 1)) {
4740                                 continue;
4741                         }
4742                         isp_prt(isp, ISP_LOGWARN, "command handle 0x%x for %d.%d.%d orphaned by loop down timeout",
4743                             isp->isp_xflist[i].handle, chan, XS_TGT(xs), XS_LUN(xs));
4744                 }
4745
4746                 /*
4747                  * Mark that we've announced that this device is gone....
4748                  */
4749                 lp->announced = 1;
4750
4751                 /*
4752                  * but *don't* change the state of the entry. Just clear
4753                  * any target id stuff and announce to CAM that the
4754                  * device is gone. This way any necessary PLOGO stuff
4755                  * will happen when loop comes back up.
4756                  */
4757
4758                 tgt = lp->dev_map_idx - 1;
4759                 FCPARAM(isp, chan)->isp_dev_map[tgt] = 0;
4760                 lp->dev_map_idx = 0;
4761                 lp->state = FC_PORTDB_STATE_NIL;
4762                 isp_prt(isp, ISP_LOGCONFIG, prom3, chan, lp->portid, tgt, "Loop Down Timeout");
4763                 isp_make_gone(isp, lp, chan, tgt);
4764         }
4765
4766         if (FCPARAM(isp, chan)->role & ISP_ROLE_INITIATOR) {
4767                 isp_unfreeze_loopdown(isp, chan);
4768         }
4769         /*
4770          * The loop down timer has expired. Wake up the kthread
4771          * to notice that fact (or make it false).
4772          */
4773         fc->loop_dead = 1;
4774         fc->loop_down_time = fc->loop_down_limit+1;
4775         wakeup(fc);
4776         ISP_UNLOCK(isp);
4777 }
4778
4779 static void
4780 isp_kthread(void *arg)
4781 {
4782         struct isp_fc *fc = arg;
4783         ispsoftc_t *isp = fc->isp;
4784         int chan = fc - isp->isp_osinfo.pc.fc;
4785         int slp = 0;
4786
4787         mtx_lock(&isp->isp_osinfo.lock);
4788
4789         while (isp->isp_osinfo.is_exiting == 0) {
4790                 int lb, lim;
4791
4792                 isp_prt(isp, ISP_LOG_SANCFG|ISP_LOGDEBUG0, "%s: Chan %d checking FC state", __func__, chan);
4793                 lb = isp_fc_runstate(isp, chan, 250000);
4794
4795                 /*
4796                  * Our action is different based upon whether we're supporting
4797                  * Initiator mode or not. If we are, we might freeze the simq
4798                  * when loop is down and set all sorts of different delays to
4799                  * check again.
4800                  *
4801                  * If not, we simply just wait for loop to come up.
4802                  */
4803                 if (lb && (FCPARAM(isp, chan)->role & ISP_ROLE_INITIATOR)) {
4804                         /*
4805                          * Increment loop down time by the last sleep interval
4806                          */
4807                         fc->loop_down_time += slp;
4808
4809                         if (lb < 0) {
4810                                 isp_prt(isp, ISP_LOG_SANCFG|ISP_LOGDEBUG0, "%s: Chan %d FC loop not up (down count %d)", __func__, chan, fc->loop_down_time);
4811                         } else {
4812                                 isp_prt(isp, ISP_LOG_SANCFG|ISP_LOGDEBUG0, "%s: Chan %d FC got to %d (down count %d)", __func__, chan, lb, fc->loop_down_time);
4813                         }
4814
4815                         /*
4816                          * If we've never seen loop up and we've waited longer
4817                          * than quickboot time, or we've seen loop up but we've
4818                          * waited longer than loop_down_limit, give up and go
4819                          * to sleep until loop comes up.
4820                          */
4821                         if (FCPARAM(isp, chan)->loop_seen_once == 0) {
4822                                 lim = isp_quickboot_time;
4823                         } else {
4824                                 lim = fc->loop_down_limit;
4825                         }
4826                         if (fc->loop_down_time >= lim) {
4827                                 isp_freeze_loopdown(isp, chan, "loop limit hit");
4828                                 slp = 0;
4829                         } else if (fc->loop_down_time < 10) {
4830                                 slp = 1;
4831                         } else if (fc->loop_down_time < 30) {
4832                                 slp = 5;
4833                         } else if (fc->loop_down_time < 60) {
4834                                 slp = 10;
4835                         } else if (fc->loop_down_time < 120) {
4836                                 slp = 20;
4837                         } else {
4838                                 slp = 30;
4839                         }
4840
4841                 } else if (lb) {
4842                         isp_prt(isp, ISP_LOG_SANCFG|ISP_LOGDEBUG0, "%s: Chan %d FC Loop Down", __func__, chan);
4843                         fc->loop_down_time += slp;
4844                         if (fc->loop_down_time > 300)
4845                                 slp = 0;
4846                         else
4847                                 slp = 60;
4848                 } else {
4849                         isp_prt(isp, ISP_LOG_SANCFG|ISP_LOGDEBUG0, "%s: Chan %d FC state OK", __func__, chan);
4850                         fc->loop_down_time = 0;
4851                         slp = 0;
4852                 }
4853
4854
4855                 /*
4856                  * If this is past the first loop up or the loop is dead and if we'd frozen the simq, unfreeze it
4857                  * now so that CAM can start sending us commands.
4858                  *
4859                  * If the FC state isn't okay yet, they'll hit that in isp_start which will freeze the queue again
4860                  * or kill the commands, as appropriate.
4861                  */
4862
4863                 if (FCPARAM(isp, chan)->loop_seen_once || fc->loop_dead) {
4864                         isp_unfreeze_loopdown(isp, chan);
4865                 }
4866
4867                 isp_prt(isp, ISP_LOG_SANCFG|ISP_LOGDEBUG0, "%s: Chan %d sleep time %d", __func__, chan, slp);
4868
4869                 msleep(fc, &isp->isp_osinfo.lock, PRIBIO, "ispf", slp * hz);
4870
4871                 /*
4872                  * If slp is zero, we're waking up for the first time after
4873                  * things have been okay. In this case, we set a deferral state
4874                  * for all commands and delay hysteresis seconds before starting
4875                  * the FC state evaluation. This gives the loop/fabric a chance
4876                  * to settle.
4877                  */
4878                 if (slp == 0 && fc->hysteresis) {
4879                         isp_prt(isp, ISP_LOG_SANCFG|ISP_LOGDEBUG0, "%s: Chan %d sleep hysteresis ticks %d", __func__, chan, fc->hysteresis * hz);
4880                         mtx_unlock(&isp->isp_osinfo.lock);
4881                         pause("ispt", fc->hysteresis * hz);
4882                         mtx_lock(&isp->isp_osinfo.lock);
4883                 }
4884         }
4885         fc->num_threads -= 1;
4886         mtx_unlock(&isp->isp_osinfo.lock);
4887         kthread_exit();
4888 }
4889
4890 static void
4891 isp_action(struct cam_sim *sim, union ccb *ccb)
4892 {
4893         int bus, tgt, ts, error, lim;
4894         ispsoftc_t *isp;
4895         struct ccb_trans_settings *cts;
4896
4897         CAM_DEBUG(ccb->ccb_h.path, CAM_DEBUG_TRACE, ("isp_action\n"));
4898
4899         isp = (ispsoftc_t *)cam_sim_softc(sim);
4900         mtx_assert(&isp->isp_lock, MA_OWNED);
4901
4902         if (isp->isp_state != ISP_RUNSTATE && ccb->ccb_h.func_code == XPT_SCSI_IO) {
4903                 isp_init(isp);
4904                 if (isp->isp_state != ISP_INITSTATE) {
4905                         /*
4906                          * Lie. Say it was a selection timeout.
4907                          */
4908                         ccb->ccb_h.status = CAM_SEL_TIMEOUT | CAM_DEV_QFRZN;
4909                         xpt_freeze_devq(ccb->ccb_h.path, 1);
4910                         xpt_done(ccb);
4911                         return;
4912                 }
4913                 isp->isp_state = ISP_RUNSTATE;
4914         }
4915         isp_prt(isp, ISP_LOGDEBUG2, "isp_action code %x", ccb->ccb_h.func_code);
4916         ISP_PCMD(ccb) = NULL;
4917
4918         switch (ccb->ccb_h.func_code) {
4919         case XPT_SCSI_IO:       /* Execute the requested I/O operation */
4920                 bus = XS_CHANNEL(ccb);
4921                 /*
4922                  * Do a couple of preliminary checks...
4923                  */
4924                 if ((ccb->ccb_h.flags & CAM_CDB_POINTER) != 0) {
4925                         if ((ccb->ccb_h.flags & CAM_CDB_PHYS) != 0) {
4926                                 ccb->ccb_h.status = CAM_REQ_INVALID;
4927                                 xpt_done(ccb);
4928                                 break;
4929                         }
4930                 }
4931                 ccb->csio.req_map = NULL;
4932 #ifdef  DIAGNOSTIC
4933                 if (ccb->ccb_h.target_id > (ISP_MAX_TARGETS(isp) - 1)) {
4934                         xpt_print(ccb->ccb_h.path, "invalid target\n");
4935                         ccb->ccb_h.status = CAM_PATH_INVALID;
4936                 } else if (ccb->ccb_h.target_lun > (ISP_MAX_LUNS(isp) - 1)) {
4937                         xpt_print(ccb->ccb_h.path, "invalid lun\n");
4938                         ccb->ccb_h.status = CAM_PATH_INVALID;
4939                 }
4940                 if (ccb->ccb_h.status == CAM_PATH_INVALID) {
4941                         xpt_done(ccb);
4942                         break;
4943                 }
4944 #endif
4945                 ccb->csio.scsi_status = SCSI_STATUS_OK;
4946                 if (isp_get_pcmd(isp, ccb)) {
4947                         isp_prt(isp, ISP_LOGWARN, "out of PCMDs");
4948                         cam_freeze_devq(ccb->ccb_h.path);
4949                         cam_release_devq(ccb->ccb_h.path, RELSIM_RELEASE_AFTER_TIMEOUT, 0, 250, 0);
4950                         xpt_done(ccb);
4951                         break;
4952                 }
4953                 error = isp_start((XS_T *) ccb);
4954                 switch (error) {
4955                 case CMD_QUEUED:
4956                         ccb->ccb_h.status |= CAM_SIM_QUEUED;
4957                         if (ccb->ccb_h.timeout == CAM_TIME_INFINITY) {
4958                                 break;
4959                         }
4960                         ts = ccb->ccb_h.timeout;
4961                         if (ts == CAM_TIME_DEFAULT) {
4962                                 ts = 60*1000;
4963                         }
4964                         ts = isp_mstohz(ts);
4965                         callout_reset(&PISP_PCMD(ccb)->wdog, ts, isp_watchdog, ccb);
4966                         break;
4967                 case CMD_RQLATER:
4968                         /*
4969                          * We get this result for FC devices if the loop state isn't ready yet
4970                          * or if the device in question has gone zombie on us.
4971                          *
4972                          * If we've never seen Loop UP at all, we requeue this request and wait
4973                          * for the initial loop up delay to expire.
4974                          */
4975                         lim = ISP_FC_PC(isp, bus)->loop_down_limit;
4976                         if (FCPARAM(isp, bus)->loop_seen_once == 0 || ISP_FC_PC(isp, bus)->loop_down_time >= lim) {
4977                                 if (FCPARAM(isp, bus)->loop_seen_once == 0) {
4978                                         isp_prt(isp, ISP_LOGDEBUG0, "%d.%d loop not seen yet @ %lu", XS_TGT(ccb), XS_LUN(ccb), (unsigned long) time_uptime);
4979                                 } else {
4980                                         isp_prt(isp, ISP_LOGDEBUG0, "%d.%d downtime (%d) > lim (%d)", XS_TGT(ccb), XS_LUN(ccb), ISP_FC_PC(isp, bus)->loop_down_time, lim);
4981                                 }
4982                                 ccb->ccb_h.status = CAM_SEL_TIMEOUT|CAM_DEV_QFRZN;
4983                                 xpt_freeze_devq(ccb->ccb_h.path, 1);
4984                                 isp_free_pcmd(isp, ccb);
4985                                 xpt_done(ccb);
4986                                 break;
4987                         }
4988                         isp_prt(isp, ISP_LOGDEBUG0, "%d.%d retry later", XS_TGT(ccb), XS_LUN(ccb));
4989                         cam_freeze_devq(ccb->ccb_h.path);
4990                         cam_release_devq(ccb->ccb_h.path, RELSIM_RELEASE_AFTER_TIMEOUT, 0, 1000, 0);
4991                         ccb->ccb_h.status = CAM_REQUEUE_REQ;
4992                         isp_free_pcmd(isp, ccb);
4993                         xpt_done(ccb);
4994                         break;
4995                 case CMD_EAGAIN:
4996                         isp_free_pcmd(isp, ccb);
4997                         cam_freeze_devq(ccb->ccb_h.path);
4998                         cam_release_devq(ccb->ccb_h.path, RELSIM_RELEASE_AFTER_TIMEOUT, 0, 100, 0);
4999                         ccb->ccb_h.status = CAM_REQUEUE_REQ;
5000                         xpt_done(ccb);
5001                         break;
5002                 case CMD_COMPLETE:
5003                         isp_done((struct ccb_scsiio *) ccb);
5004                         break;
5005                 default:
5006                         isp_prt(isp, ISP_LOGERR, "What's this? 0x%x at %d in file %s", error, __LINE__, __FILE__);
5007                         ccb->ccb_h.status = CAM_REQUEUE_REQ;
5008                         isp_free_pcmd(isp, ccb);
5009                         xpt_done(ccb);
5010                 }
5011                 break;
5012
5013 #ifdef  ISP_TARGET_MODE
5014         case XPT_EN_LUN:                /* Enable/Disable LUN as a target */
5015                 if (ccb->cel.enable) {
5016                         isp_enable_lun(isp, ccb);
5017                 } else {
5018                         isp_disable_lun(isp, ccb);
5019                 }
5020                 break;
5021         case XPT_IMMED_NOTIFY:
5022         case XPT_IMMEDIATE_NOTIFY:      /* Add Immediate Notify Resource */
5023         case XPT_ACCEPT_TARGET_IO:      /* Add Accept Target IO Resource */
5024         {
5025                 tstate_t *tptr = get_lun_statep(isp, XS_CHANNEL(ccb), ccb->ccb_h.target_lun);
5026                 if (tptr == NULL) {
5027                         tptr = get_lun_statep(isp, XS_CHANNEL(ccb), CAM_LUN_WILDCARD);
5028                 }
5029                 if (tptr == NULL) {
5030                         const char *str;
5031                         uint32_t tag;
5032
5033                         if (ccb->ccb_h.func_code == XPT_IMMEDIATE_NOTIFY) {
5034                                 str = "XPT_IMMEDIATE_NOTIFY";
5035                                 tag = ccb->cin1.seq_id;
5036                         } else {
5037                                 tag = ccb->atio.tag_id;
5038                                 str = "XPT_ACCEPT_TARGET_IO";
5039                         }
5040                         ISP_PATH_PRT(isp, ISP_LOGWARN, ccb->ccb_h.path, "%s: [0x%x] no state pointer found for %s\n", __func__, tag, str);
5041                         dump_tstates(isp, XS_CHANNEL(ccb));
5042                         ccb->ccb_h.status = CAM_DEV_NOT_THERE;
5043                         break;
5044                 }
5045                 ccb->ccb_h.spriv_field0 = 0;
5046                 ccb->ccb_h.spriv_ptr1 = isp;
5047
5048                 if (ccb->ccb_h.func_code == XPT_ACCEPT_TARGET_IO) {
5049                         if (ccb->atio.tag_id) {
5050                                 atio_private_data_t *atp = isp_find_atpd(isp, tptr, ccb->atio.tag_id);
5051                                 if (atp) {
5052                                         isp_put_atpd(isp, tptr, atp);
5053                                 }
5054                         }
5055                         tptr->atio_count++;
5056                         SLIST_INSERT_HEAD(&tptr->atios, &ccb->ccb_h, sim_links.sle);
5057                         ISP_PATH_PRT(isp, ISP_LOGTDEBUG2, ccb->ccb_h.path, "Put FREE ATIO (tag id 0x%x), count now %d\n",
5058                             ccb->atio.tag_id, tptr->atio_count);
5059                         ccb->atio.tag_id = 0;
5060                 } else if (ccb->ccb_h.func_code == XPT_IMMEDIATE_NOTIFY) {
5061                         if (ccb->cin1.tag_id) {
5062                                 inot_private_data_t *ntp = isp_find_ntpd(isp, tptr, ccb->cin1.tag_id, ccb->cin1.seq_id);
5063                                 if (ntp) {
5064                                         isp_put_ntpd(isp, tptr, ntp);
5065                                 }
5066                         }
5067                         tptr->inot_count++;
5068                         SLIST_INSERT_HEAD(&tptr->inots, &ccb->ccb_h, sim_links.sle);
5069                         ISP_PATH_PRT(isp, ISP_LOGTDEBUG2, ccb->ccb_h.path, "Put FREE INOT, (seq id 0x%x) count now %d\n",
5070                             ccb->cin1.seq_id, tptr->inot_count);
5071                         ccb->cin1.seq_id = 0;
5072                 } else if (ccb->ccb_h.func_code == XPT_IMMED_NOTIFY) {
5073                         tptr->inot_count++;
5074                         SLIST_INSERT_HEAD(&tptr->inots, &ccb->ccb_h, sim_links.sle);
5075                         ISP_PATH_PRT(isp, ISP_LOGTDEBUG2, ccb->ccb_h.path, "Put FREE INOT, (seq id 0x%x) count now %d\n",
5076                             ccb->cin1.seq_id, tptr->inot_count);
5077                         ccb->cin1.seq_id = 0;
5078                 }
5079                 rls_lun_statep(isp, tptr);
5080                 ccb->ccb_h.status = CAM_REQ_INPROG;
5081                 break;
5082         }
5083         case XPT_NOTIFY_ACK:
5084                 ccb->ccb_h.status = CAM_REQ_CMP_ERR;
5085                 break;
5086         case XPT_NOTIFY_ACKNOWLEDGE:            /* notify ack */
5087         {
5088                 tstate_t *tptr;
5089                 inot_private_data_t *ntp;
5090
5091                 /*
5092                  * XXX: Because we cannot guarantee that the path information in the notify acknowledge ccb
5093                  * XXX: matches that for the immediate notify, we have to *search* for the notify structure
5094                  */
5095                 /*
5096                  * All the relevant path information is in the associated immediate notify
5097                  */
5098                 ISP_PATH_PRT(isp, ISP_LOGTDEBUG0, ccb->ccb_h.path, "%s: [0x%x] NOTIFY ACKNOWLEDGE for 0x%x seen\n", __func__, ccb->cna2.tag_id, ccb->cna2.seq_id);
5099                 ntp = get_ntp_from_tagdata(isp, ccb->cna2.tag_id, ccb->cna2.seq_id, &tptr);
5100                 if (ntp == NULL) {
5101                         ISP_PATH_PRT(isp, ISP_LOGWARN, ccb->ccb_h.path, "%s: [0x%x] XPT_NOTIFY_ACKNOWLEDGE of 0x%x cannot find ntp private data\n", __func__,
5102                              ccb->cna2.tag_id, ccb->cna2.seq_id);
5103                         ccb->ccb_h.status = CAM_DEV_NOT_THERE;
5104                         xpt_done(ccb);
5105                         break;
5106                 }
5107                 if (isp_handle_platform_target_notify_ack(isp, &ntp->rd.nt)) {
5108                         rls_lun_statep(isp, tptr);
5109                         cam_freeze_devq(ccb->ccb_h.path);
5110                         cam_release_devq(ccb->ccb_h.path, RELSIM_RELEASE_AFTER_TIMEOUT, 0, 1000, 0);
5111                         ccb->ccb_h.status &= ~CAM_STATUS_MASK;
5112                         ccb->ccb_h.status |= CAM_REQUEUE_REQ;
5113                         break;
5114                 }
5115                 isp_put_ntpd(isp, tptr, ntp);
5116                 rls_lun_statep(isp, tptr);
5117                 ccb->ccb_h.status = CAM_REQ_CMP;
5118                 ISP_PATH_PRT(isp, ISP_LOGTDEBUG0, ccb->ccb_h.path, "%s: [0x%x] calling xpt_done for tag 0x%x\n", __func__, ccb->cna2.tag_id, ccb->cna2.seq_id);
5119                 xpt_done(ccb);
5120                 break;
5121         }
5122         case XPT_CONT_TARGET_IO:
5123                 isp_target_start_ctio(isp, ccb, FROM_CAM);
5124                 break;
5125 #endif
5126         case XPT_RESET_DEV:             /* BDR the specified SCSI device */
5127         {
5128                 struct isp_fc *fc;
5129
5130                 bus = cam_sim_bus(xpt_path_sim(ccb->ccb_h.path));
5131                 tgt = ccb->ccb_h.target_id;
5132                 tgt |= (bus << 16);
5133                 if (IS_FC(isp))
5134                         fc = ISP_FC_PC(isp, bus);
5135                 else
5136                         fc = NULL;
5137
5138                 error = isp_control(isp, ISPCTL_RESET_DEV, bus, tgt);
5139                 if (error) {
5140                         ccb->ccb_h.status = CAM_REQ_CMP_ERR;
5141                 } else {
5142                         /*
5143                          * If we have a FC device, reset the Command
5144                          * Reference Number, because the target will expect
5145                          * that we re-start the CRN at 1 after a reset.
5146                          */
5147                         if (fc != NULL)
5148                                 isp_fcp_reset_crn(fc, tgt, /*tgt_set*/ 1);
5149
5150                         ccb->ccb_h.status = CAM_REQ_CMP;
5151                 }
5152                 xpt_done(ccb);
5153                 break;
5154         }
5155         case XPT_ABORT:                 /* Abort the specified CCB */
5156         {
5157                 union ccb *accb = ccb->cab.abort_ccb;
5158                 switch (accb->ccb_h.func_code) {
5159 #ifdef  ISP_TARGET_MODE
5160                 case XPT_ACCEPT_TARGET_IO:
5161                         isp_target_mark_aborted(isp, ccb);
5162                         break;
5163 #endif
5164                 case XPT_SCSI_IO:
5165                         error = isp_control(isp, ISPCTL_ABORT_CMD, accb);
5166                         if (error) {
5167                                 ccb->ccb_h.status = CAM_UA_ABORT;
5168                         } else {
5169                                 ccb->ccb_h.status = CAM_REQ_CMP;
5170                         }
5171                         break;
5172                 default:
5173                         ccb->ccb_h.status = CAM_REQ_INVALID;
5174                         break;
5175                 }
5176                 /*
5177                  * This is not a queued CCB, so the caller expects it to be
5178                  * complete when control is returned.
5179                  */
5180                 break;
5181         }
5182 #define IS_CURRENT_SETTINGS(c)  (c->type == CTS_TYPE_CURRENT_SETTINGS)
5183         case XPT_SET_TRAN_SETTINGS:     /* Nexus Settings */
5184                 cts = &ccb->cts;
5185                 if (!IS_CURRENT_SETTINGS(cts)) {
5186                         ccb->ccb_h.status = CAM_REQ_INVALID;
5187                         xpt_done(ccb);
5188                         break;
5189                 }
5190                 tgt = cts->ccb_h.target_id;
5191                 bus = cam_sim_bus(xpt_path_sim(cts->ccb_h.path));
5192                 if (IS_SCSI(isp)) {
5193                         struct ccb_trans_settings_scsi *scsi = &cts->proto_specific.scsi;
5194                         struct ccb_trans_settings_spi *spi = &cts->xport_specific.spi;
5195                         sdparam *sdp = SDPARAM(isp, bus);
5196                         uint16_t *dptr;
5197
5198                         if (spi->valid == 0 && scsi->valid == 0) {
5199                                 ccb->ccb_h.status = CAM_REQ_CMP;
5200                                 xpt_done(ccb);
5201                                 break;
5202                         }
5203
5204                         /*
5205                          * We always update (internally) from goal_flags
5206                          * so any request to change settings just gets
5207                          * vectored to that location.
5208                          */
5209                         dptr = &sdp->isp_devparam[tgt].goal_flags;
5210
5211                         if ((spi->valid & CTS_SPI_VALID_DISC) != 0) {
5212                                 if ((spi->flags & CTS_SPI_FLAGS_DISC_ENB) != 0)
5213                                         *dptr |= DPARM_DISC;
5214                                 else
5215                                         *dptr &= ~DPARM_DISC;
5216                         }
5217
5218                         if ((scsi->valid & CTS_SCSI_VALID_TQ) != 0) {
5219                                 if ((scsi->flags & CTS_SCSI_FLAGS_TAG_ENB) != 0)
5220                                         *dptr |= DPARM_TQING;
5221                                 else
5222                                         *dptr &= ~DPARM_TQING;
5223                         }
5224
5225                         if ((spi->valid & CTS_SPI_VALID_BUS_WIDTH) != 0) {
5226                                 if (spi->bus_width == MSG_EXT_WDTR_BUS_16_BIT)
5227                                         *dptr |= DPARM_WIDE;
5228                                 else
5229                                         *dptr &= ~DPARM_WIDE;
5230                         }
5231
5232                         /*
5233                          * XXX: FIX ME
5234                          */
5235                         if ((spi->valid & CTS_SPI_VALID_SYNC_OFFSET) && (spi->valid & CTS_SPI_VALID_SYNC_RATE) && (spi->sync_period && spi->sync_offset)) {
5236                                 *dptr |= DPARM_SYNC;
5237                                 /*
5238                                  * XXX: CHECK FOR LEGALITY
5239                                  */
5240                                 sdp->isp_devparam[tgt].goal_period = spi->sync_period;
5241                                 sdp->isp_devparam[tgt].goal_offset = spi->sync_offset;
5242                         } else {
5243                                 *dptr &= ~DPARM_SYNC;
5244                         }
5245                         isp_prt(isp, ISP_LOGDEBUG0, "SET (%d.%d.%jx) to flags %x off %x per %x", bus, tgt, (uintmax_t)cts->ccb_h.target_lun, sdp->isp_devparam[tgt].goal_flags,
5246                             sdp->isp_devparam[tgt].goal_offset, sdp->isp_devparam[tgt].goal_period);
5247                         sdp->isp_devparam[tgt].dev_update = 1;
5248                         sdp->update = 1;
5249                 }
5250                 ccb->ccb_h.status = CAM_REQ_CMP;
5251                 xpt_done(ccb);
5252                 break;
5253         case XPT_GET_TRAN_SETTINGS:
5254                 cts = &ccb->cts;
5255                 tgt = cts->ccb_h.target_id;
5256                 bus = cam_sim_bus(xpt_path_sim(cts->ccb_h.path));
5257                 if (IS_FC(isp)) {
5258                         fcparam *fcp = FCPARAM(isp, bus);
5259                         struct ccb_trans_settings_scsi *scsi = &cts->proto_specific.scsi;
5260                         struct ccb_trans_settings_fc *fc = &cts->xport_specific.fc;
5261                         unsigned int hdlidx;
5262
5263                         cts->protocol = PROTO_SCSI;
5264                         cts->protocol_version = SCSI_REV_2;
5265                         cts->transport = XPORT_FC;
5266                         cts->transport_version = 0;
5267
5268                         scsi->valid = CTS_SCSI_VALID_TQ;
5269                         scsi->flags = CTS_SCSI_FLAGS_TAG_ENB;
5270                         fc->valid = CTS_FC_VALID_SPEED;
5271                         fc->bitrate = 100000;
5272                         fc->bitrate *= fcp->isp_gbspeed;
5273                         hdlidx = fcp->isp_dev_map[tgt] - 1;
5274                         if (hdlidx < MAX_FC_TARG) {
5275                                 fcportdb_t *lp = &fcp->portdb[hdlidx];
5276                                 fc->wwnn = lp->node_wwn;
5277                                 fc->wwpn = lp->port_wwn;
5278                                 fc->port = lp->portid;
5279                                 fc->valid |= CTS_FC_VALID_WWNN | CTS_FC_VALID_WWPN | CTS_FC_VALID_PORT;
5280                         }
5281                 } else {
5282                         struct ccb_trans_settings_scsi *scsi = &cts->proto_specific.scsi;
5283                         struct ccb_trans_settings_spi *spi = &cts->xport_specific.spi;
5284                         sdparam *sdp = SDPARAM(isp, bus);
5285                         uint16_t dval, pval, oval;
5286
5287                         if (IS_CURRENT_SETTINGS(cts)) {
5288                                 sdp->isp_devparam[tgt].dev_refresh = 1;
5289                                 sdp->update = 1;
5290                                 (void) isp_control(isp, ISPCTL_UPDATE_PARAMS, bus);
5291                                 dval = sdp->isp_devparam[tgt].actv_flags;
5292                                 oval = sdp->isp_devparam[tgt].actv_offset;
5293                                 pval = sdp->isp_devparam[tgt].actv_period;
5294                         } else {
5295                                 dval = sdp->isp_devparam[tgt].nvrm_flags;
5296                                 oval = sdp->isp_devparam[tgt].nvrm_offset;
5297                                 pval = sdp->isp_devparam[tgt].nvrm_period;
5298                         }
5299
5300                         cts->protocol = PROTO_SCSI;
5301                         cts->protocol_version = SCSI_REV_2;
5302                         cts->transport = XPORT_SPI;
5303                         cts->transport_version = 2;
5304
5305                         spi->valid = 0;
5306                         scsi->valid = 0;
5307                         spi->flags = 0;
5308                         scsi->flags = 0;
5309                         if (dval & DPARM_DISC) {
5310                                 spi->flags |= CTS_SPI_FLAGS_DISC_ENB;
5311                         }
5312                         if ((dval & DPARM_SYNC) && oval && pval) {
5313                                 spi->sync_offset = oval;
5314                                 spi->sync_period = pval;
5315                         } else {
5316                                 spi->sync_offset = 0;
5317                                 spi->sync_period = 0;
5318                         }
5319                         spi->valid |= CTS_SPI_VALID_SYNC_OFFSET;
5320                         spi->valid |= CTS_SPI_VALID_SYNC_RATE;
5321                         spi->valid |= CTS_SPI_VALID_BUS_WIDTH;
5322                         if (dval & DPARM_WIDE) {
5323                                 spi->bus_width = MSG_EXT_WDTR_BUS_16_BIT;
5324                         } else {
5325                                 spi->bus_width = MSG_EXT_WDTR_BUS_8_BIT;
5326                         }
5327                         if (cts->ccb_h.target_lun != CAM_LUN_WILDCARD) {
5328                                 scsi->valid = CTS_SCSI_VALID_TQ;
5329                                 if (dval & DPARM_TQING) {
5330                                         scsi->flags |= CTS_SCSI_FLAGS_TAG_ENB;
5331                                 }
5332                                 spi->valid |= CTS_SPI_VALID_DISC;
5333                         }
5334                         isp_prt(isp, ISP_LOGDEBUG0, "GET %s (%d.%d.%jx) to flags %x off %x per %x", IS_CURRENT_SETTINGS(cts)? "ACTIVE" : "NVRAM",
5335                             bus, tgt, (uintmax_t)cts->ccb_h.target_lun, dval, oval, pval);
5336                 }
5337                 ccb->ccb_h.status = CAM_REQ_CMP;
5338                 xpt_done(ccb);
5339                 break;
5340
5341         case XPT_CALC_GEOMETRY:
5342                 cam_calc_geometry(&ccb->ccg, 1);
5343                 xpt_done(ccb);
5344                 break;
5345
5346         case XPT_RESET_BUS:             /* Reset the specified bus */
5347                 bus = cam_sim_bus(sim);
5348                 error = isp_control(isp, ISPCTL_RESET_BUS, bus);
5349                 if (error) {
5350                         ccb->ccb_h.status = CAM_REQ_CMP_ERR;
5351                         xpt_done(ccb);
5352                         break;
5353                 }
5354                 if (bootverbose) {
5355                         xpt_print(ccb->ccb_h.path, "reset bus on channel %d\n", bus);
5356                 }
5357                 if (IS_FC(isp)) {
5358                         xpt_async(AC_BUS_RESET, ISP_FC_PC(isp, bus)->path, 0);
5359                 } else {
5360                         xpt_async(AC_BUS_RESET, ISP_SPI_PC(isp, bus)->path, 0);
5361                 }
5362                 ccb->ccb_h.status = CAM_REQ_CMP;
5363                 xpt_done(ccb);
5364                 break;
5365
5366         case XPT_TERM_IO:               /* Terminate the I/O process */
5367                 ccb->ccb_h.status = CAM_REQ_INVALID;
5368                 xpt_done(ccb);
5369                 break;
5370
5371         case XPT_SET_SIM_KNOB:          /* Set SIM knobs */
5372         {
5373                 struct ccb_sim_knob *kp = &ccb->knob;
5374                 fcparam *fcp;
5375
5376                 if (!IS_FC(isp)) {
5377                         ccb->ccb_h.status = CAM_REQ_INVALID;
5378                         xpt_done(ccb);
5379                         break;
5380                 }
5381
5382                 bus = cam_sim_bus(xpt_path_sim(kp->ccb_h.path));
5383                 fcp = FCPARAM(isp, bus);
5384
5385                 if (kp->xport_specific.fc.valid & KNOB_VALID_ADDRESS) {
5386                         fcp->isp_wwnn = ISP_FC_PC(isp, bus)->def_wwnn = kp->xport_specific.fc.wwnn;
5387                         fcp->isp_wwpn = ISP_FC_PC(isp, bus)->def_wwpn = kp->xport_specific.fc.wwpn;
5388                         isp_prt(isp, ISP_LOGALL, "Setting Channel %d wwns to 0x%jx 0x%jx", bus, fcp->isp_wwnn, fcp->isp_wwpn);
5389                 }
5390                 ccb->ccb_h.status = CAM_REQ_CMP;
5391                 if (kp->xport_specific.fc.valid & KNOB_VALID_ROLE) {
5392                         int rchange = 0;
5393                         int newrole = 0;
5394
5395                         switch (kp->xport_specific.fc.role) {
5396                         case KNOB_ROLE_NONE:
5397                                 if (fcp->role != ISP_ROLE_NONE) {
5398                                         rchange = 1;
5399                                         newrole = ISP_ROLE_NONE;
5400                                 }
5401                                 break;
5402                         case KNOB_ROLE_TARGET:
5403                                 if (fcp->role != ISP_ROLE_TARGET) {
5404                                         rchange = 1;
5405                                         newrole = ISP_ROLE_TARGET;
5406                                 }
5407                                 break;
5408                         case KNOB_ROLE_INITIATOR:
5409                                 if (fcp->role != ISP_ROLE_INITIATOR) {
5410                                         rchange = 1;
5411                                         newrole = ISP_ROLE_INITIATOR;
5412                                 }
5413                                 break;
5414                         case KNOB_ROLE_BOTH:
5415 #if 0
5416                                 if (fcp->role != ISP_ROLE_BOTH) {
5417                                         rchange = 1;
5418                                         newrole = ISP_ROLE_BOTH;
5419                                 }
5420 #else
5421                                 /*
5422                                  * We don't really support dual role at present on FC cards.
5423                                  *
5424                                  * We should, but a bunch of things are currently broken,
5425                                  * so don't allow it.
5426                                  */
5427                                 isp_prt(isp, ISP_LOGERR, "cannot support dual role at present");
5428                                 ccb->ccb_h.status = CAM_REQ_INVALID;
5429 #endif
5430                                 break;
5431                         }
5432                         if (rchange) {
5433                                 ISP_PATH_PRT(isp, ISP_LOGCONFIG, ccb->ccb_h.path, "changing role on from %d to %d\n", fcp->role, newrole);
5434 #ifdef  ISP_TARGET_MODE
5435                                 ISP_SET_PC(isp, bus, tm_enabled, 0);
5436                                 ISP_SET_PC(isp, bus, tm_luns_enabled, 0);
5437 #endif
5438                                 if (isp_fc_change_role(isp, bus, newrole) != 0) {
5439                                         ccb->ccb_h.status = CAM_REQ_CMP_ERR;
5440                                         xpt_done(ccb);
5441                                         break;
5442                                 }
5443 #ifdef  ISP_TARGET_MODE
5444                                 if (newrole == ISP_ROLE_TARGET || newrole == ISP_ROLE_BOTH) {
5445                                         /*
5446                                          * Give the new role a chance to complain and settle
5447                                          */
5448                                         msleep(isp, &isp->isp_lock, PRIBIO, "taking a breather", 2);
5449                                         ccb->ccb_h.status = isp_enable_deferred_luns(isp, bus);
5450                                 }
5451 #endif
5452                         }
5453                 }
5454                 xpt_done(ccb);
5455                 break;
5456         }
5457         case XPT_GET_SIM_KNOB:          /* Get SIM knobs */
5458         {
5459                 struct ccb_sim_knob *kp = &ccb->knob;
5460
5461                 if (IS_FC(isp)) {
5462                         fcparam *fcp;
5463
5464                         bus = cam_sim_bus(xpt_path_sim(kp->ccb_h.path));
5465                         fcp = FCPARAM(isp, bus);
5466
5467                         kp->xport_specific.fc.wwnn = fcp->isp_wwnn;
5468                         kp->xport_specific.fc.wwpn = fcp->isp_wwpn;
5469                         switch (fcp->role) {
5470                         case ISP_ROLE_NONE:
5471                                 kp->xport_specific.fc.role = KNOB_ROLE_NONE;
5472                                 break;
5473                         case ISP_ROLE_TARGET:
5474                                 kp->xport_specific.fc.role = KNOB_ROLE_TARGET;
5475                                 break;
5476                         case ISP_ROLE_INITIATOR:
5477                                 kp->xport_specific.fc.role = KNOB_ROLE_INITIATOR;
5478                                 break;
5479                         case ISP_ROLE_BOTH:
5480                                 kp->xport_specific.fc.role = KNOB_ROLE_BOTH;
5481                                 break;
5482                         }
5483                         kp->xport_specific.fc.valid = KNOB_VALID_ADDRESS | KNOB_VALID_ROLE;
5484                         ccb->ccb_h.status = CAM_REQ_CMP;
5485                 } else {
5486                         ccb->ccb_h.status = CAM_REQ_INVALID;
5487                 }
5488                 xpt_done(ccb);
5489                 break;
5490         }
5491         case XPT_PATH_INQ:              /* Path routing inquiry */
5492         {
5493                 struct ccb_pathinq *cpi = &ccb->cpi;
5494
5495                 cpi->version_num = 1;
5496 #ifdef  ISP_TARGET_MODE
5497                 cpi->target_sprt = PIT_PROCESSOR | PIT_DISCONNECT | PIT_TERM_IO;
5498 #else
5499                 cpi->target_sprt = 0;
5500 #endif
5501                 cpi->hba_eng_cnt = 0;
5502                 cpi->max_target = ISP_MAX_TARGETS(isp) - 1;
5503                 cpi->max_lun = ISP_MAX_LUNS(isp) - 1;
5504                 cpi->bus_id = cam_sim_bus(sim);
5505                 if (isp->isp_osinfo.sixtyfourbit)
5506                         cpi->maxio = (ISP_NSEG64_MAX - 1) * PAGE_SIZE;
5507                 else
5508                         cpi->maxio = (ISP_NSEG_MAX - 1) * PAGE_SIZE;
5509
5510                 bus = cam_sim_bus(xpt_path_sim(cpi->ccb_h.path));
5511                 if (IS_FC(isp)) {
5512                         fcparam *fcp = FCPARAM(isp, bus);
5513
5514                         cpi->hba_misc = PIM_NOBUSRESET | PIM_UNMAPPED;
5515
5516                         /*
5517                          * Because our loop ID can shift from time to time,
5518                          * make our initiator ID out of range of our bus.
5519                          */
5520                         cpi->initiator_id = cpi->max_target + 1;
5521
5522                         /*
5523                          * Set base transfer capabilities for Fibre Channel, for this HBA.
5524                          */
5525                         if (IS_25XX(isp)) {
5526                                 cpi->base_transfer_speed = 8000000;
5527                         } else if (IS_24XX(isp)) {
5528                                 cpi->base_transfer_speed = 4000000;
5529                         } else if (IS_23XX(isp)) {
5530                                 cpi->base_transfer_speed = 2000000;
5531                         } else {
5532                                 cpi->base_transfer_speed = 1000000;
5533                         }
5534                         cpi->hba_inquiry = PI_TAG_ABLE;
5535                         cpi->transport = XPORT_FC;
5536                         cpi->transport_version = 0;
5537                         cpi->xport_specific.fc.wwnn = fcp->isp_wwnn;
5538                         cpi->xport_specific.fc.wwpn = fcp->isp_wwpn;
5539                         cpi->xport_specific.fc.port = fcp->isp_portid;
5540                         cpi->xport_specific.fc.bitrate = fcp->isp_gbspeed * 1000;
5541                 } else {
5542                         sdparam *sdp = SDPARAM(isp, bus);
5543                         cpi->hba_inquiry = PI_SDTR_ABLE|PI_TAG_ABLE|PI_WIDE_16;
5544                         cpi->hba_misc = PIM_UNMAPPED;
5545                         cpi->initiator_id = sdp->isp_initiator_id;
5546                         cpi->base_transfer_speed = 3300;
5547                         cpi->transport = XPORT_SPI;
5548                         cpi->transport_version = 2;
5549                 }
5550                 cpi->protocol = PROTO_SCSI;
5551                 cpi->protocol_version = SCSI_REV_2;
5552                 strncpy(cpi->sim_vid, "FreeBSD", SIM_IDLEN);
5553                 strncpy(cpi->hba_vid, "Qlogic", HBA_IDLEN);
5554                 strncpy(cpi->dev_name, cam_sim_name(sim), DEV_IDLEN);
5555                 cpi->unit_number = cam_sim_unit(sim);
5556                 cpi->ccb_h.status = CAM_REQ_CMP;
5557                 xpt_done(ccb);
5558                 break;
5559         }
5560         default:
5561                 ccb->ccb_h.status = CAM_REQ_INVALID;
5562                 xpt_done(ccb);
5563                 break;
5564         }
5565 }
5566
5567 #define ISPDDB  (CAM_DEBUG_INFO|CAM_DEBUG_TRACE|CAM_DEBUG_CDB)
5568
5569 void
5570 isp_done(XS_T *sccb)
5571 {
5572         ispsoftc_t *isp = XS_ISP(sccb);
5573         uint32_t status;
5574
5575         if (XS_NOERR(sccb))
5576                 XS_SETERR(sccb, CAM_REQ_CMP);
5577
5578         if ((sccb->ccb_h.status & CAM_STATUS_MASK) == CAM_REQ_CMP && (sccb->scsi_status != SCSI_STATUS_OK)) {
5579                 sccb->ccb_h.status &= ~CAM_STATUS_MASK;
5580                 if ((sccb->scsi_status == SCSI_STATUS_CHECK_COND) && (sccb->ccb_h.status & CAM_AUTOSNS_VALID) == 0) {
5581                         sccb->ccb_h.status |= CAM_AUTOSENSE_FAIL;
5582                 } else {
5583                         sccb->ccb_h.status |= CAM_SCSI_STATUS_ERROR;
5584                 }
5585         }
5586
5587         sccb->ccb_h.status &= ~CAM_SIM_QUEUED;
5588         status = sccb->ccb_h.status & CAM_STATUS_MASK;
5589         if (status != CAM_REQ_CMP) {
5590                 if (status != CAM_SEL_TIMEOUT)
5591                         isp_prt(isp, ISP_LOGDEBUG0, "target %d lun %d CAM status 0x%x SCSI status 0x%x", XS_TGT(sccb), XS_LUN(sccb), sccb->ccb_h.status, sccb->scsi_status);
5592                 else if ((IS_FC(isp))
5593                       && (XS_TGT(sccb) < MAX_FC_TARG)) {
5594                         fcparam *fcp;
5595                         int hdlidx;
5596
5597                         fcp = FCPARAM(isp, XS_CHANNEL(sccb));
5598                         hdlidx = fcp->isp_dev_map[XS_TGT(sccb)] - 1;
5599                         /*
5600                          * Note that we have reported that this device is
5601                          * gone.  If it reappears, we'll need to issue a
5602                          * rescan.
5603                          */
5604                         if (hdlidx > 0 && hdlidx < MAX_FC_TARG)
5605                                 fcp->portdb[hdlidx].reported_gone = 1;
5606                 }
5607                 if ((sccb->ccb_h.status & CAM_DEV_QFRZN) == 0) {
5608                         sccb->ccb_h.status |= CAM_DEV_QFRZN;
5609                         xpt_freeze_devq(sccb->ccb_h.path, 1);
5610                 }
5611         }
5612
5613         if ((CAM_DEBUGGED(sccb->ccb_h.path, ISPDDB)) && (sccb->ccb_h.status & CAM_STATUS_MASK) != CAM_REQ_CMP) {
5614                 xpt_print(sccb->ccb_h.path, "cam completion status 0x%x\n", sccb->ccb_h.status);
5615         }
5616
5617         if (callout_active(&PISP_PCMD(sccb)->wdog))
5618                 callout_stop(&PISP_PCMD(sccb)->wdog);
5619         isp_free_pcmd(isp, (union ccb *) sccb);
5620         xpt_done((union ccb *) sccb);
5621 }
5622
5623 void
5624 isp_async(ispsoftc_t *isp, ispasync_t cmd, ...)
5625 {
5626         int bus;
5627         static const char prom0[] = "Chan %d PortID 0x%06x handle 0x%x %s %s WWPN 0x%08x%08x";
5628         static const char prom2[] = "Chan %d PortID 0x%06x handle 0x%x %s %s tgt %u WWPN 0x%08x%08x";
5629         char buf[64];
5630         char *msg = NULL;
5631         target_id_t tgt;
5632         fcportdb_t *lp;
5633         struct isp_fc *fc;
5634         struct cam_path *tmppath;
5635         va_list ap;
5636
5637         switch (cmd) {
5638         case ISPASYNC_NEW_TGT_PARAMS:
5639         {
5640                 struct ccb_trans_settings_scsi *scsi;
5641                 struct ccb_trans_settings_spi *spi;
5642                 int flags, tgt;
5643                 sdparam *sdp;
5644                 struct ccb_trans_settings cts;
5645
5646                 memset(&cts, 0, sizeof (struct ccb_trans_settings));
5647
5648                 va_start(ap, cmd);
5649                 bus = va_arg(ap, int);
5650                 tgt = va_arg(ap, int);
5651                 va_end(ap);
5652                 sdp = SDPARAM(isp, bus);
5653
5654                 if (xpt_create_path(&tmppath, NULL, cam_sim_path(ISP_SPI_PC(isp, bus)->sim), tgt, CAM_LUN_WILDCARD) != CAM_REQ_CMP) {
5655                         isp_prt(isp, ISP_LOGWARN, "isp_async cannot make temp path for %d.%d", tgt, bus);
5656                         break;
5657                 }
5658                 flags = sdp->isp_devparam[tgt].actv_flags;
5659                 cts.type = CTS_TYPE_CURRENT_SETTINGS;
5660                 cts.protocol = PROTO_SCSI;
5661                 cts.transport = XPORT_SPI;
5662
5663                 scsi = &cts.proto_specific.scsi;
5664                 spi = &cts.xport_specific.spi;
5665
5666                 if (flags & DPARM_TQING) {
5667                         scsi->valid |= CTS_SCSI_VALID_TQ;
5668                         scsi->flags |= CTS_SCSI_FLAGS_TAG_ENB;
5669                 }
5670
5671                 if (flags & DPARM_DISC) {
5672                         spi->valid |= CTS_SPI_VALID_DISC;
5673                         spi->flags |= CTS_SPI_FLAGS_DISC_ENB;
5674                 }
5675                 spi->flags |= CTS_SPI_VALID_BUS_WIDTH;
5676                 if (flags & DPARM_WIDE) {
5677                         spi->bus_width = MSG_EXT_WDTR_BUS_16_BIT;
5678                 } else {
5679                         spi->bus_width = MSG_EXT_WDTR_BUS_8_BIT;
5680                 }
5681                 if (flags & DPARM_SYNC) {
5682                         spi->valid |= CTS_SPI_VALID_SYNC_RATE;
5683                         spi->valid |= CTS_SPI_VALID_SYNC_OFFSET;
5684                         spi->sync_period = sdp->isp_devparam[tgt].actv_period;
5685                         spi->sync_offset = sdp->isp_devparam[tgt].actv_offset;
5686                 }
5687                 isp_prt(isp, ISP_LOGDEBUG2, "NEW_TGT_PARAMS bus %d tgt %d period %x offset %x flags %x", bus, tgt, sdp->isp_devparam[tgt].actv_period, sdp->isp_devparam[tgt].actv_offset, flags);
5688                 xpt_setup_ccb(&cts.ccb_h, tmppath, 1);
5689                 xpt_async(AC_TRANSFER_NEG, tmppath, &cts);
5690                 xpt_free_path(tmppath);
5691                 break;
5692         }
5693         case ISPASYNC_BUS_RESET:
5694         {
5695                 va_start(ap, cmd);
5696                 bus = va_arg(ap, int);
5697                 va_end(ap);
5698                 isp_prt(isp, ISP_LOGINFO, "SCSI bus reset on bus %d detected", bus);
5699                 if (IS_FC(isp)) {
5700                         xpt_async(AC_BUS_RESET, ISP_FC_PC(isp, bus)->path, NULL);
5701                 } else {
5702                         xpt_async(AC_BUS_RESET, ISP_SPI_PC(isp, bus)->path, NULL);
5703                 }
5704                 break;
5705         }
5706         case ISPASYNC_LIP:
5707                 if (msg == NULL) {
5708                         msg = "LIP Received";
5709                 }
5710                 /* FALLTHROUGH */
5711         case ISPASYNC_LOOP_RESET:
5712                 if (msg == NULL) {
5713                         msg = "LOOP Reset";
5714                 }
5715                 /* FALLTHROUGH */
5716         case ISPASYNC_LOOP_DOWN:
5717         {
5718                 if (msg == NULL) {
5719                         msg = "LOOP Down";
5720                 }
5721                 va_start(ap, cmd);
5722                 bus = va_arg(ap, int);
5723                 va_end(ap);
5724
5725                 FCPARAM(isp, bus)->link_active = 0;
5726
5727                 fc = ISP_FC_PC(isp, bus);
5728                 if (cmd == ISPASYNC_LOOP_DOWN && fc->ready) {
5729                         /*
5730                          * We don't do any simq freezing if we are only in target mode
5731                          */
5732                         if (FCPARAM(isp, bus)->role & ISP_ROLE_INITIATOR) {
5733                                 if (fc->path) {
5734                                         isp_freeze_loopdown(isp, bus, msg);
5735                                 }
5736                                 if (!callout_active(&fc->ldt)) {
5737                                         callout_reset(&fc->ldt, fc->loop_down_limit * hz, isp_ldt, fc);
5738                                         isp_prt(isp, ISP_LOG_SANCFG|ISP_LOGDEBUG0, "Starting Loop Down Timer @ %lu", (unsigned long) time_uptime);
5739                                 }
5740                         }
5741                 }
5742                 isp_fcp_reset_crn(fc, /*tgt*/0, /*tgt_set*/ 0);
5743
5744                 isp_prt(isp, ISP_LOGINFO, "Chan %d: %s", bus, msg);
5745                 break;
5746         }
5747         case ISPASYNC_LOOP_UP:
5748                 va_start(ap, cmd);
5749                 bus = va_arg(ap, int);
5750                 va_end(ap);
5751                 fc = ISP_FC_PC(isp, bus);
5752                 /*
5753                  * Now we just note that Loop has come up. We don't
5754                  * actually do anything because we're waiting for a
5755                  * Change Notify before activating the FC cleanup
5756                  * thread to look at the state of the loop again.
5757                  */
5758                 FCPARAM(isp, bus)->link_active = 1;
5759                 fc->loop_dead = 0;
5760                 fc->loop_down_time = 0;
5761                 isp_prt(isp, ISP_LOGINFO, "Chan %d Loop UP", bus);
5762                 break;
5763         case ISPASYNC_DEV_ARRIVED:
5764                 va_start(ap, cmd);
5765                 bus = va_arg(ap, int);
5766                 lp = va_arg(ap, fcportdb_t *);
5767                 va_end(ap);
5768                 fc = ISP_FC_PC(isp, bus);
5769                 lp->announced = 0;
5770                 lp->gone_timer = 0;
5771                 if ((FCPARAM(isp, bus)->role & ISP_ROLE_INITIATOR) && (lp->prli_word3 & PRLI_WD3_TARGET_FUNCTION)) {
5772                         int dbidx = lp - FCPARAM(isp, bus)->portdb;
5773                         int i;
5774
5775                         for (i = 0; i < MAX_FC_TARG; i++) {
5776                                 if (i >= FL_ID && i <= SNS_ID) {
5777                                         continue;
5778                                 }
5779                                 if (FCPARAM(isp, bus)->isp_dev_map[i] == 0) {
5780                                         break;
5781                                 }
5782                         }
5783                         if (i < MAX_FC_TARG) {
5784                                 FCPARAM(isp, bus)->isp_dev_map[i] = dbidx + 1;
5785                                 lp->dev_map_idx = i + 1;
5786                         } else {
5787                                 isp_prt(isp, ISP_LOGWARN, "out of target ids");
5788                                 isp_dump_portdb(isp, bus);
5789                         }
5790                 }
5791                 isp_gen_role_str(buf, sizeof (buf), lp->prli_word3);
5792                 if (lp->dev_map_idx) {
5793                         tgt = lp->dev_map_idx - 1;
5794                         isp_prt(isp, ISP_LOGCONFIG, prom2, bus, lp->portid, lp->handle, buf, "arrived at", tgt, (uint32_t) (lp->port_wwn >> 32), (uint32_t) lp->port_wwn);
5795                         isp_fcp_reset_crn(fc, tgt, /*tgt_set*/ 1);
5796                         isp_make_here(isp, lp, bus, tgt);
5797                 } else {
5798                         isp_prt(isp, ISP_LOGCONFIG, prom0, bus, lp->portid, lp->handle, buf, "arrived", (uint32_t) (lp->port_wwn >> 32), (uint32_t) lp->port_wwn);
5799                 }
5800                 break;
5801         case ISPASYNC_DEV_CHANGED:
5802                 va_start(ap, cmd);
5803                 bus = va_arg(ap, int);
5804                 lp = va_arg(ap, fcportdb_t *);
5805                 va_end(ap);
5806                 fc = ISP_FC_PC(isp, bus);
5807                 lp->announced = 0;
5808                 lp->gone_timer = 0;
5809                 if (isp_change_is_bad) {
5810                         lp->state = FC_PORTDB_STATE_NIL;
5811                         if (lp->dev_map_idx) {
5812                                 tgt = lp->dev_map_idx - 1;
5813                                 FCPARAM(isp, bus)->isp_dev_map[tgt] = 0;
5814                                 lp->dev_map_idx = 0;
5815                                 isp_prt(isp, ISP_LOGCONFIG, prom3, bus, lp->portid, tgt, "change is bad");
5816                                 isp_make_gone(isp, lp, bus, tgt);
5817                         } else {
5818                                 isp_gen_role_str(buf, sizeof (buf), lp->prli_word3);
5819                                 isp_prt(isp, ISP_LOGCONFIG, prom0, bus, lp->portid, lp->handle, buf, "changed and departed",
5820                                     (uint32_t) (lp->port_wwn >> 32), (uint32_t) lp->port_wwn);
5821                         }
5822                 } else {
5823                         lp->portid = lp->new_portid;
5824                         lp->prli_word3 = lp->new_prli_word3;
5825                         isp_gen_role_str(buf, sizeof (buf), lp->prli_word3);
5826                         if (lp->dev_map_idx) {
5827                                 int t = lp->dev_map_idx - 1;
5828                                 FCPARAM(isp, bus)->isp_dev_map[t] = (lp - FCPARAM(isp, bus)->portdb) + 1;
5829                                 tgt = lp->dev_map_idx - 1;
5830                                 isp_prt(isp, ISP_LOGCONFIG, prom2, bus, lp->portid, lp->handle, buf, "changed at", tgt,
5831                                     (uint32_t) (lp->port_wwn >> 32), (uint32_t) lp->port_wwn);
5832                                 isp_fcp_reset_crn(fc, tgt, /*tgt_set*/ 1);
5833                         } else {
5834                                 isp_prt(isp, ISP_LOGCONFIG, prom0, bus, lp->portid, lp->handle, buf, "changed", (uint32_t) (lp->port_wwn >> 32), (uint32_t) lp->port_wwn);
5835                         }
5836                 }
5837                 break;
5838         case ISPASYNC_DEV_STAYED:
5839                 va_start(ap, cmd);
5840                 bus = va_arg(ap, int);
5841                 lp = va_arg(ap, fcportdb_t *);
5842                 va_end(ap);
5843                 isp_gen_role_str(buf, sizeof (buf), lp->prli_word3);
5844                 if (lp->dev_map_idx) {
5845                         fc = ISP_FC_PC(isp, bus);
5846                         tgt = lp->dev_map_idx - 1;
5847                         isp_prt(isp, ISP_LOGCONFIG, prom2, bus, lp->portid, lp->handle, buf, "stayed at", tgt,
5848                             (uint32_t) (lp->port_wwn >> 32), (uint32_t) lp->port_wwn);
5849                         /*
5850                          * Only issue a rescan if we've actually reported
5851                          * that this device is gone.
5852                          */
5853                         if (lp->reported_gone != 0) {
5854                                 isp_prt(isp, ISP_LOGCONFIG, prom2, bus, lp->portid, lp->handle, buf, "rescanned at", tgt, 
5855                                     (uint32_t) (lp->port_wwn >> 32), (uint32_t) lp->port_wwn);
5856                                 isp_make_here(isp, lp, bus, tgt);
5857                         }
5858                 } else {
5859                         isp_prt(isp, ISP_LOGCONFIG, prom0, bus, lp->portid, lp->handle, buf, "stayed",
5860                             (uint32_t) (lp->port_wwn >> 32), (uint32_t) lp->port_wwn);
5861                 }
5862                 break;
5863         case ISPASYNC_DEV_GONE:
5864                 va_start(ap, cmd);
5865                 bus = va_arg(ap, int);
5866                 lp = va_arg(ap, fcportdb_t *);
5867                 va_end(ap);
5868                 fc = ISP_FC_PC(isp, bus);
5869                 /*
5870                  * If this has a virtual target and we haven't marked it
5871                  * that we're going to have isp_gdt tell the OS it's gone,
5872                  * set the isp_gdt timer running on it.
5873                  *
5874                  * If it isn't marked that isp_gdt is going to get rid of it,
5875                  * announce that it's gone.
5876                  *
5877                  */
5878                 isp_gen_role_str(buf, sizeof (buf), lp->prli_word3);
5879                 if (lp->dev_map_idx && lp->announced == 0) {
5880                         lp->announced = 1;
5881                         lp->state = FC_PORTDB_STATE_ZOMBIE;
5882                         lp->gone_timer = ISP_FC_PC(isp, bus)->gone_device_time;
5883                         if (fc->ready && !callout_active(&fc->gdt)) {
5884                                 isp_prt(isp, ISP_LOG_SANCFG|ISP_LOGDEBUG0, "Chan %d Starting Gone Device Timer with %u seconds time now %lu", bus, lp->gone_timer, (unsigned long)time_uptime);
5885                                 callout_reset(&fc->gdt, hz, isp_gdt, fc);
5886                         }
5887                         tgt = lp->dev_map_idx - 1;
5888                         isp_prt(isp, ISP_LOGCONFIG, prom2, bus, lp->portid, lp->handle, buf, "gone zombie at", tgt, (uint32_t) (lp->port_wwn >> 32), (uint32_t) lp->port_wwn);
5889                         isp_fcp_reset_crn(fc, tgt, /*tgt_set*/ 1);
5890                 } else if (lp->announced == 0) {
5891                         isp_prt(isp, ISP_LOGCONFIG, prom0, bus, lp->portid, lp->handle, buf, "departed", (uint32_t) (lp->port_wwn >> 32), (uint32_t) lp->port_wwn);
5892                 }
5893                 break;
5894         case ISPASYNC_CHANGE_NOTIFY:
5895         {
5896                 char *msg;
5897                 int evt, nphdl, nlstate, reason;
5898
5899                 va_start(ap, cmd);
5900                 bus = va_arg(ap, int);
5901                 evt = va_arg(ap, int);
5902                 if (IS_24XX(isp) && evt == ISPASYNC_CHANGE_PDB) {
5903                         nphdl = va_arg(ap, int);
5904                         nlstate = va_arg(ap, int);
5905                         reason = va_arg(ap, int);
5906                 } else {
5907                         nphdl = NIL_HANDLE;
5908                         nlstate = reason = 0;
5909                 }
5910                 va_end(ap);
5911                 fc = ISP_FC_PC(isp, bus);
5912
5913                 if (evt == ISPASYNC_CHANGE_PDB) {
5914                         msg = "Chan %d Port Database Changed";
5915                 } else if (evt == ISPASYNC_CHANGE_SNS) {
5916                         msg = "Chan %d Name Server Database Changed";
5917                 } else {
5918                         msg = "Chan %d Other Change Notify";
5919                 }
5920
5921                 /*
5922                  * If the loop down timer is running, cancel it.
5923                  */
5924                 if (fc->ready && callout_active(&fc->ldt)) {
5925                         isp_prt(isp, ISP_LOG_SANCFG|ISP_LOGDEBUG0, "Stopping Loop Down Timer @ %lu", (unsigned long) time_uptime);
5926                         callout_stop(&fc->ldt);
5927                 }
5928                 isp_prt(isp, ISP_LOGINFO, msg, bus);
5929                 if (FCPARAM(isp, bus)->role & ISP_ROLE_INITIATOR) {
5930                         isp_freeze_loopdown(isp, bus, msg);
5931                 }
5932                 wakeup(fc);
5933                 break;
5934         }
5935 #ifdef  ISP_TARGET_MODE
5936         case ISPASYNC_TARGET_NOTIFY:
5937         {
5938                 isp_notify_t *notify;
5939                 va_start(ap, cmd);
5940                 notify = va_arg(ap, isp_notify_t *);
5941                 va_end(ap);
5942                 switch (notify->nt_ncode) {
5943                 case NT_ABORT_TASK:
5944                 case NT_ABORT_TASK_SET:
5945                 case NT_CLEAR_ACA:
5946                 case NT_CLEAR_TASK_SET:
5947                 case NT_LUN_RESET:
5948                 case NT_TARGET_RESET:
5949                         /*
5950                          * These are task management functions.
5951                          */
5952                         isp_handle_platform_target_tmf(isp, notify);
5953                         break;
5954                 case NT_BUS_RESET:
5955                 case NT_LIP_RESET:
5956                 case NT_LINK_UP:
5957                 case NT_LINK_DOWN:
5958                         /*
5959                          * No action need be taken here.
5960                          */
5961                         break;
5962                 case NT_HBA_RESET:
5963                         isp_del_all_wwn_entries(isp, ISP_NOCHAN);
5964                         break;
5965                 case NT_GLOBAL_LOGOUT:
5966                 case NT_LOGOUT:
5967                         /*
5968                          * This is device arrival/departure notification
5969                          */
5970                         isp_handle_platform_target_notify_ack(isp, notify);
5971                         break;
5972                 case NT_ARRIVED:
5973                 {
5974                         struct ac_contract ac;
5975                         struct ac_device_changed *fc;
5976
5977                         ac.contract_number = AC_CONTRACT_DEV_CHG;
5978                         fc = (struct ac_device_changed *) ac.contract_data;
5979                         fc->wwpn = notify->nt_wwn;
5980                         fc->port = notify->nt_sid;
5981                         fc->target = notify->nt_nphdl;
5982                         fc->arrived = 1;
5983                         xpt_async(AC_CONTRACT, ISP_FC_PC(isp, notify->nt_channel)->path, &ac);
5984                         break;
5985                 }
5986                 case NT_DEPARTED:
5987                 {
5988                         struct ac_contract ac;
5989                         struct ac_device_changed *fc;
5990
5991                         ac.contract_number = AC_CONTRACT_DEV_CHG;
5992                         fc = (struct ac_device_changed *) ac.contract_data;
5993                         fc->wwpn = notify->nt_wwn;
5994                         fc->port = notify->nt_sid;
5995                         fc->target = notify->nt_nphdl;
5996                         fc->arrived = 0;
5997                         xpt_async(AC_CONTRACT, ISP_FC_PC(isp, notify->nt_channel)->path, &ac);
5998                         break;
5999                 }
6000                 default:
6001                         isp_prt(isp, ISP_LOGALL, "target notify code 0x%x", notify->nt_ncode);
6002                         isp_handle_platform_target_notify_ack(isp, notify);
6003                         break;
6004                 }
6005                 break;
6006         }
6007         case ISPASYNC_TARGET_NOTIFY_ACK:
6008         {
6009                 void *inot;
6010                 va_start(ap, cmd);
6011                 inot = va_arg(ap, void *);
6012                 va_end(ap);
6013                 if (isp_notify_ack(isp, inot)) {
6014                         isp_tna_t *tp = malloc(sizeof (*tp), M_DEVBUF, M_NOWAIT);
6015                         if (tp) {
6016                                 tp->isp = isp;
6017                                 if (inot) {
6018                                         memcpy(tp->data, inot, sizeof (tp->data));
6019                                         tp->not = tp->data;
6020                                 } else {
6021                                         tp->not = NULL;
6022                                 }
6023                                 callout_init_mtx(&tp->timer, &isp->isp_lock, 0);
6024                                 callout_reset(&tp->timer, 5,
6025                                     isp_refire_notify_ack, tp);
6026                         } else {
6027                                 isp_prt(isp, ISP_LOGERR, "you lose- cannot allocate a notify refire");
6028                         }
6029                 }
6030                 break;
6031         }
6032         case ISPASYNC_TARGET_ACTION:
6033         {
6034                 isphdr_t *hp;
6035
6036                 va_start(ap, cmd);
6037                 hp = va_arg(ap, isphdr_t *);
6038                 va_end(ap);
6039                 switch (hp->rqs_entry_type) {
6040                 default:
6041                         isp_prt(isp, ISP_LOGWARN, "%s: unhandled target action 0x%x", __func__, hp->rqs_entry_type);
6042                         break;
6043                 case RQSTYPE_NOTIFY:
6044                         if (IS_SCSI(isp)) {
6045                                 isp_handle_platform_notify_scsi(isp, (in_entry_t *) hp);
6046                         } else if (IS_24XX(isp)) {
6047                                 isp_handle_platform_notify_24xx(isp, (in_fcentry_24xx_t *) hp);
6048                         } else {
6049                                 isp_handle_platform_notify_fc(isp, (in_fcentry_t *) hp);
6050                         }
6051                         break;
6052                 case RQSTYPE_ATIO:
6053                         if (IS_24XX(isp)) {
6054                                 isp_handle_platform_atio7(isp, (at7_entry_t *) hp);
6055                         } else {
6056                                 isp_handle_platform_atio(isp, (at_entry_t *) hp);
6057                         }
6058                         break;
6059                 case RQSTYPE_ATIO2:
6060                         isp_handle_platform_atio2(isp, (at2_entry_t *) hp);
6061                         break;
6062                 case RQSTYPE_CTIO7:
6063                 case RQSTYPE_CTIO3:
6064                 case RQSTYPE_CTIO2:
6065                 case RQSTYPE_CTIO:
6066                         isp_handle_platform_ctio(isp, hp);
6067                         break;
6068                 case RQSTYPE_ABTS_RCVD:
6069                 {
6070                         abts_t *abts = (abts_t *)hp;
6071                         isp_notify_t notify, *nt = &notify;
6072                         tstate_t *tptr;
6073                         fcportdb_t *lp;
6074                         uint16_t chan;
6075                         uint32_t sid, did;
6076
6077                         did = (abts->abts_did_hi << 16) | abts->abts_did_lo;
6078                         sid = (abts->abts_sid_hi << 16) | abts->abts_sid_lo;
6079                         ISP_MEMZERO(nt, sizeof (isp_notify_t));
6080
6081                         nt->nt_hba = isp;
6082                         nt->nt_did = did;
6083                         nt->nt_nphdl = abts->abts_nphdl;
6084                         nt->nt_sid = sid;
6085                         isp_find_chan_by_did(isp, did, &chan);
6086                         if (chan == ISP_NOCHAN) {
6087                                 nt->nt_tgt = TGT_ANY;
6088                         } else {
6089                                 nt->nt_tgt = FCPARAM(isp, chan)->isp_wwpn;
6090                                 if (isp_find_pdb_by_loopid(isp, chan, abts->abts_nphdl, &lp)) {
6091                                         nt->nt_wwn = lp->port_wwn;
6092                                 } else {
6093                                         nt->nt_wwn = INI_ANY;
6094                                 }
6095                         }
6096                         /*
6097                          * Try hard to find the lun for this command.
6098                          */
6099                         tptr = get_lun_statep_from_tag(isp, chan, abts->abts_rxid_task);
6100                         if (tptr) {
6101                                 nt->nt_lun = tptr->ts_lun;
6102                                 rls_lun_statep(isp, tptr);
6103                         } else {
6104                                 nt->nt_lun = LUN_ANY;
6105                         }
6106                         nt->nt_need_ack = 1;
6107                         nt->nt_tagval = abts->abts_rxid_task;
6108                         nt->nt_tagval |= (((uint64_t) abts->abts_rxid_abts) << 32);
6109                         if (abts->abts_rxid_task == ISP24XX_NO_TASK) {
6110                                 isp_prt(isp, ISP_LOGTINFO, "[0x%x] ABTS from N-Port handle 0x%x Port 0x%06x has no task id (rx_id 0x%04x ox_id 0x%04x)",
6111                                     abts->abts_rxid_abts, abts->abts_nphdl, sid, abts->abts_rx_id, abts->abts_ox_id);
6112                         } else {
6113                                 isp_prt(isp, ISP_LOGTINFO, "[0x%x] ABTS from N-Port handle 0x%x Port 0x%06x for task 0x%x (rx_id 0x%04x ox_id 0x%04x)",
6114                                     abts->abts_rxid_abts, abts->abts_nphdl, sid, abts->abts_rxid_task, abts->abts_rx_id, abts->abts_ox_id);
6115                         }
6116                         nt->nt_channel = chan;
6117                         nt->nt_ncode = NT_ABORT_TASK;
6118                         nt->nt_lreserved = hp;
6119                         isp_handle_platform_target_tmf(isp, nt);
6120                         break;
6121                 }
6122                 case RQSTYPE_ENABLE_LUN:
6123                 case RQSTYPE_MODIFY_LUN:
6124                         isp_ledone(isp, (lun_entry_t *) hp);
6125                         break;
6126                 }
6127                 break;
6128         }
6129 #endif
6130         case ISPASYNC_FW_CRASH:
6131         {
6132                 uint16_t mbox1, mbox6;
6133                 mbox1 = ISP_READ(isp, OUTMAILBOX1);
6134                 if (IS_DUALBUS(isp)) { 
6135                         mbox6 = ISP_READ(isp, OUTMAILBOX6);
6136                 } else {
6137                         mbox6 = 0;
6138                 }
6139                 isp_prt(isp, ISP_LOGERR, "Internal Firmware Error on bus %d @ RISC Address 0x%x", mbox6, mbox1);
6140                 mbox1 = isp->isp_osinfo.mbox_sleep_ok;
6141                 isp->isp_osinfo.mbox_sleep_ok = 0;
6142                 isp_reinit(isp, 1);
6143                 isp->isp_osinfo.mbox_sleep_ok = mbox1;
6144                 isp_async(isp, ISPASYNC_FW_RESTARTED, NULL);
6145                 break;
6146         }
6147         default:
6148                 isp_prt(isp, ISP_LOGERR, "unknown isp_async event %d", cmd);
6149                 break;
6150         }
6151 }
6152
6153
6154 /*
6155  * Locks are held before coming here.
6156  */
6157 void
6158 isp_uninit(ispsoftc_t *isp)
6159 {
6160         if (IS_24XX(isp)) {
6161                 ISP_WRITE(isp, BIU2400_HCCR, HCCR_2400_CMD_RESET);
6162         } else {
6163                 ISP_WRITE(isp, HCCR, HCCR_CMD_RESET);
6164         }
6165         ISP_DISABLE_INTS(isp);
6166 }
6167
6168 /*
6169  * When we want to get the 'default' WWNs (when lacking NVRAM), we pick them
6170  * up from our platform default (defww{p|n}n) and morph them based upon
6171  * channel.
6172  * 
6173  * When we want to get the 'active' WWNs, we get NVRAM WWNs and then morph them
6174  * based upon channel.
6175  */
6176
6177 uint64_t
6178 isp_default_wwn(ispsoftc_t * isp, int chan, int isactive, int iswwnn)
6179 {
6180         uint64_t seed;
6181         struct isp_fc *fc = ISP_FC_PC(isp, chan);
6182
6183         /*
6184          * If we're asking for a active WWN, the default overrides get
6185          * returned, otherwise the NVRAM value is picked.
6186          * 
6187          * If we're asking for a default WWN, we just pick the default override.
6188          */
6189         if (isactive) {
6190                 seed = iswwnn ? fc->def_wwnn : fc->def_wwpn;
6191                 if (seed) {
6192                         return (seed);
6193                 }
6194                 seed = iswwnn ? FCPARAM(isp, chan)->isp_wwnn_nvram : FCPARAM(isp, chan)->isp_wwpn_nvram;
6195                 if (seed) {
6196                         return (seed);
6197                 }
6198                 return (0x400000007F000009ull);
6199         }
6200
6201         seed = iswwnn ? fc->def_wwnn : fc->def_wwpn;
6202
6203         /*
6204          * For channel zero just return what we have. For either ACTIVE or
6205          * DEFAULT cases, we depend on default override of NVRAM values for
6206          * channel zero.
6207          */
6208         if (chan == 0) {
6209                 return (seed);
6210         }
6211
6212         /*
6213          * For other channels, we are doing one of three things:
6214          * 
6215          * 1. If what we have now is non-zero, return it. Otherwise we morph
6216          * values from channel 0. 2. If we're here for a WWPN we synthesize
6217          * it if Channel 0's wwpn has a type 2 NAA. 3. If we're here for a
6218          * WWNN we synthesize it if Channel 0's wwnn has a type 2 NAA.
6219          */
6220
6221         if (seed) {
6222                 return (seed);
6223         }
6224         seed = iswwnn ? ISP_FC_PC(isp, 0)->def_wwnn : ISP_FC_PC(isp, 0)->def_wwpn;
6225         if (seed == 0)
6226                 seed = iswwnn ? FCPARAM(isp, 0)->isp_wwnn_nvram : FCPARAM(isp, 0)->isp_wwpn_nvram;
6227
6228         if (((seed >> 60) & 0xf) == 2) {
6229                 /*
6230                  * The type 2 NAA fields for QLogic cards appear be laid out
6231                  * thusly:
6232                  * 
6233                  * bits 63..60 NAA == 2 bits 59..57 unused/zero bit 56
6234                  * port (1) or node (0) WWN distinguishor bit 48
6235                  * physical port on dual-port chips (23XX/24XX)
6236                  * 
6237                  * This is somewhat nutty, particularly since bit 48 is
6238                  * irrelevant as they assign separate serial numbers to
6239                  * different physical ports anyway.
6240                  * 
6241                  * We'll stick our channel number plus one first into bits
6242                  * 57..59 and thence into bits 52..55 which allows for 8 bits
6243                  * of channel which is comfortably more than our maximum
6244                  * (126) now.
6245                  */
6246                 seed &= ~0x0FF0000000000000ULL;
6247                 if (iswwnn == 0) {
6248                         seed |= ((uint64_t) (chan + 1) & 0xf) << 56;
6249                         seed |= ((uint64_t) ((chan + 1) >> 4) & 0xf) << 52;
6250                 }
6251         } else {
6252                 seed = 0;
6253         }
6254         return (seed);
6255 }
6256
6257 void
6258 isp_prt(ispsoftc_t *isp, int level, const char *fmt, ...)
6259 {
6260         int loc;
6261         char lbuf[200];
6262         va_list ap;
6263
6264         if (level != ISP_LOGALL && (level & isp->isp_dblev) == 0) {
6265                 return;
6266         }
6267         snprintf(lbuf, sizeof (lbuf), "%s: ", device_get_nameunit(isp->isp_dev));
6268         loc = strlen(lbuf);
6269         va_start(ap, fmt);
6270         vsnprintf(&lbuf[loc], sizeof (lbuf) - loc - 1, fmt, ap); 
6271         va_end(ap);
6272         printf("%s\n", lbuf);
6273 }
6274
6275 void
6276 isp_xs_prt(ispsoftc_t *isp, XS_T *xs, int level, const char *fmt, ...)
6277 {
6278         va_list ap;
6279         if (level != ISP_LOGALL && (level & isp->isp_dblev) == 0) {
6280                 return;
6281         }
6282         xpt_print_path(xs->ccb_h.path);
6283         va_start(ap, fmt);
6284         vprintf(fmt, ap);
6285         va_end(ap);
6286         printf("\n");
6287 }
6288
6289 uint64_t
6290 isp_nanotime_sub(struct timespec *b, struct timespec *a)
6291 {
6292         uint64_t elapsed;
6293         struct timespec x = *b;
6294         timespecsub(&x, a);
6295         elapsed = GET_NANOSEC(&x);
6296         if (elapsed == 0)
6297                 elapsed++;
6298         return (elapsed);
6299 }
6300
6301 int
6302 isp_mbox_acquire(ispsoftc_t *isp)
6303 {
6304         if (isp->isp_osinfo.mboxbsy) {
6305                 return (1);
6306         } else {
6307                 isp->isp_osinfo.mboxcmd_done = 0;
6308                 isp->isp_osinfo.mboxbsy = 1;
6309                 return (0);
6310         }
6311 }
6312
6313 void
6314 isp_mbox_wait_complete(ispsoftc_t *isp, mbreg_t *mbp)
6315 {
6316         unsigned int usecs = mbp->timeout;
6317         unsigned int max, olim, ilim;
6318
6319         if (usecs == 0) {
6320                 usecs = MBCMD_DEFAULT_TIMEOUT;
6321         }
6322         max = isp->isp_mbxwrk0 + 1;
6323
6324         if (isp->isp_osinfo.mbox_sleep_ok) {
6325                 unsigned int ms = (usecs + 999) / 1000;
6326
6327                 isp->isp_osinfo.mbox_sleep_ok = 0;
6328                 isp->isp_osinfo.mbox_sleeping = 1;
6329                 for (olim = 0; olim < max; olim++) {
6330                         msleep(&isp->isp_mbxworkp, &isp->isp_osinfo.lock, PRIBIO, "ispmbx_sleep", isp_mstohz(ms));
6331                         if (isp->isp_osinfo.mboxcmd_done) {
6332                                 break;
6333                         }
6334                 }
6335                 isp->isp_osinfo.mbox_sleep_ok = 1;
6336                 isp->isp_osinfo.mbox_sleeping = 0;
6337         } else {
6338                 for (olim = 0; olim < max; olim++) {
6339                         for (ilim = 0; ilim < usecs; ilim += 100) {
6340                                 uint32_t isr;
6341                                 uint16_t sema, mbox;
6342                                 if (isp->isp_osinfo.mboxcmd_done) {
6343                                         break;
6344                                 }
6345                                 if (ISP_READ_ISR(isp, &isr, &sema, &mbox)) {
6346                                         isp_intr(isp, isr, sema, mbox);
6347                                         if (isp->isp_osinfo.mboxcmd_done) {
6348                                                 break;
6349                                         }
6350                                 }
6351                                 ISP_DELAY(100);
6352                         }
6353                         if (isp->isp_osinfo.mboxcmd_done) {
6354                                 break;
6355                         }
6356                 }
6357         }
6358         if (isp->isp_osinfo.mboxcmd_done == 0) {
6359                 isp_prt(isp, ISP_LOGWARN, "%s Mailbox Command (0x%x) Timeout (%uus) (started @ %s:%d)",
6360                     isp->isp_osinfo.mbox_sleep_ok? "Interrupting" : "Polled", isp->isp_lastmbxcmd, usecs, mbp->func, mbp->lineno);
6361                 mbp->param[0] = MBOX_TIMEOUT;
6362                 isp->isp_osinfo.mboxcmd_done = 1;
6363         }
6364 }
6365
6366 void
6367 isp_mbox_notify_done(ispsoftc_t *isp)
6368 {
6369         if (isp->isp_osinfo.mbox_sleeping) {
6370                 wakeup(&isp->isp_mbxworkp);
6371         }
6372         isp->isp_osinfo.mboxcmd_done = 1;
6373 }
6374
6375 void
6376 isp_mbox_release(ispsoftc_t *isp)
6377 {
6378         isp->isp_osinfo.mboxbsy = 0;
6379 }
6380
6381 int
6382 isp_fc_scratch_acquire(ispsoftc_t *isp, int chan)
6383 {
6384         int ret = 0;
6385         if (isp->isp_osinfo.pc.fc[chan].fcbsy) {
6386                 ret = -1;
6387         } else {
6388                 isp->isp_osinfo.pc.fc[chan].fcbsy = 1;
6389         }
6390         return (ret);
6391 }
6392
6393 int
6394 isp_mstohz(int ms)
6395 {
6396         int hz;
6397         struct timeval t;
6398         t.tv_sec = ms / 1000;
6399         t.tv_usec = (ms % 1000) * 1000;
6400         hz = tvtohz(&t);
6401         if (hz < 0) {
6402                 hz = 0x7fffffff;
6403         }
6404         if (hz == 0) {
6405                 hz = 1;
6406         }
6407         return (hz);
6408 }
6409
6410 void
6411 isp_platform_intr(void *arg)
6412 {
6413         ispsoftc_t *isp = arg;
6414         uint32_t isr;
6415         uint16_t sema, mbox;
6416
6417         ISP_LOCK(isp);
6418         isp->isp_intcnt++;
6419         if (ISP_READ_ISR(isp, &isr, &sema, &mbox) == 0) {
6420                 isp->isp_intbogus++;
6421         } else {
6422                 isp_intr(isp, isr, sema, mbox);
6423         }
6424         ISP_UNLOCK(isp);
6425 }
6426
6427 void
6428 isp_common_dmateardown(ispsoftc_t *isp, struct ccb_scsiio *csio, uint32_t hdl)
6429 {
6430         if ((csio->ccb_h.flags & CAM_DIR_MASK) == CAM_DIR_IN) {
6431                 bus_dmamap_sync(isp->isp_osinfo.dmat, PISP_PCMD(csio)->dmap, BUS_DMASYNC_POSTREAD);
6432         } else {
6433                 bus_dmamap_sync(isp->isp_osinfo.dmat, PISP_PCMD(csio)->dmap, BUS_DMASYNC_POSTWRITE);
6434         }
6435         bus_dmamap_unload(isp->isp_osinfo.dmat, PISP_PCMD(csio)->dmap);
6436 }
6437
6438 /*
6439  * Reset the command reference number for all LUNs on a specific target
6440  * (needed when a target arrives again) or for all targets on a port
6441  * (needed for events like a LIP).
6442  */
6443 void
6444 isp_fcp_reset_crn(struct isp_fc *fc, uint32_t tgt, int tgt_set)
6445 {
6446         int i;
6447         struct isp_nexus *nxp;
6448
6449         if (tgt_set == 0)
6450                 isp_prt(fc->isp, ISP_LOG_SANCFG, "resetting CRN on all targets");
6451         else
6452                 isp_prt(fc->isp, ISP_LOG_SANCFG, "resetting CRN target %u", tgt);
6453
6454         for (i = 0; i < NEXUS_HASH_WIDTH; i++) {
6455                 nxp = fc->nexus_hash[i];
6456                 while (nxp) {
6457                         if ((tgt_set != 0) && (tgt == nxp->tgt))
6458                                 nxp->crnseed = 0;
6459
6460                         nxp = nxp->next;
6461                 }
6462         }
6463 }
6464
6465 int
6466 isp_fcp_next_crn(ispsoftc_t *isp, uint8_t *crnp, XS_T *cmd)
6467 {
6468         uint32_t chan, tgt, lun;
6469         struct isp_fc *fc;
6470         struct isp_nexus *nxp;
6471         int idx;
6472
6473         if (isp->isp_type < ISP_HA_FC_2300)
6474                 return (0);
6475
6476         chan = XS_CHANNEL(cmd);
6477         tgt = XS_TGT(cmd);
6478         lun = XS_LUN(cmd);
6479         fc = &isp->isp_osinfo.pc.fc[chan];
6480         idx = NEXUS_HASH(tgt, lun);
6481         nxp = fc->nexus_hash[idx];
6482
6483         while (nxp) {
6484                 if (nxp->tgt == tgt && nxp->lun == lun)
6485                         break;
6486                 nxp = nxp->next;
6487         }
6488         if (nxp == NULL) {
6489                 nxp = fc->nexus_free_list;
6490                 if (nxp == NULL) {
6491                         nxp = malloc(sizeof (struct isp_nexus), M_DEVBUF, M_ZERO|M_NOWAIT);
6492                         if (nxp == NULL) {
6493                                 return (-1);
6494                         }
6495                 } else {
6496                         fc->nexus_free_list = nxp->next;
6497                 }
6498                 nxp->tgt = tgt;
6499                 nxp->lun = lun;
6500                 nxp->next = fc->nexus_hash[idx];
6501                 fc->nexus_hash[idx] = nxp;
6502         }
6503         if (nxp) {
6504                 if (nxp->crnseed == 0)
6505                         nxp->crnseed = 1;
6506                 if (cmd)
6507                         PISP_PCMD(cmd)->crn = nxp->crnseed;
6508                 *crnp = nxp->crnseed++;
6509                 return (0);
6510         }
6511         return (-1);
6512 }
6513
6514 /*
6515  * We enter with the lock held
6516  */
6517 void
6518 isp_timer(void *arg)
6519 {
6520         ispsoftc_t *isp = arg;
6521 #ifdef  ISP_TARGET_MODE
6522         isp_tmcmd_restart(isp);
6523 #endif
6524         callout_reset(&isp->isp_osinfo.tmo, isp_timer_count, isp_timer, isp);
6525 }
6526
6527 isp_ecmd_t *
6528 isp_get_ecmd(ispsoftc_t *isp)
6529 {
6530         isp_ecmd_t *ecmd = isp->isp_osinfo.ecmd_free;
6531         if (ecmd) {
6532                 isp->isp_osinfo.ecmd_free = ecmd->next;
6533         }
6534         return (ecmd);
6535 }
6536
6537 void
6538 isp_put_ecmd(ispsoftc_t *isp, isp_ecmd_t *ecmd)
6539 {
6540         ecmd->next = isp->isp_osinfo.ecmd_free;
6541         isp->isp_osinfo.ecmd_free = ecmd;
6542 }