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