]> CyberLeo.Net >> Repos - FreeBSD/stable/10.git/blob - sys/cam/ctl/scsi_ctl.c
MFC r289843: Add partial support for QUERY TMF to CAM and isp(4).
[FreeBSD/stable/10.git] / sys / cam / ctl / scsi_ctl.c
1 /*-
2  * Copyright (c) 2008, 2009 Silicon Graphics International Corp.
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, this list of conditions, and the following disclaimer,
10  *    without modification.
11  * 2. Redistributions in binary form must reproduce at minimum a disclaimer
12  *    substantially similar to the "NO WARRANTY" disclaimer below
13  *    ("Disclaimer") and any redistribution must be conditioned upon
14  *    including a substantially similar Disclaimer requirement for further
15  *    binary redistribution.
16  *
17  * NO WARRANTY
18  * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
19  * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
20  * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTIBILITY AND FITNESS FOR
21  * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
22  * HOLDERS OR CONTRIBUTORS BE LIABLE FOR SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
23  * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
24  * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
25  * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT,
26  * STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING
27  * IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
28  * POSSIBILITY OF SUCH DAMAGES.
29  *
30  * $Id: //depot/users/kenm/FreeBSD-test2/sys/cam/ctl/scsi_ctl.c#4 $
31  */
32 /*
33  * Peripheral driver interface between CAM and CTL (CAM Target Layer).
34  *
35  * Author: Ken Merry <ken@FreeBSD.org>
36  */
37
38 #include <sys/cdefs.h>
39 __FBSDID("$FreeBSD$");
40
41 #include <sys/param.h>
42 #include <sys/queue.h>
43 #include <sys/systm.h>
44 #include <sys/kernel.h>
45 #include <sys/lock.h>
46 #include <sys/mutex.h>
47 #include <sys/condvar.h>
48 #include <sys/malloc.h>
49 #include <sys/bus.h>
50 #include <sys/endian.h>
51 #include <sys/sbuf.h>
52 #include <sys/sysctl.h>
53 #include <sys/types.h>
54 #include <sys/systm.h>
55 #include <machine/bus.h>
56
57 #include <cam/cam.h>
58 #include <cam/cam_ccb.h>
59 #include <cam/cam_periph.h>
60 #include <cam/cam_queue.h>
61 #include <cam/cam_xpt_periph.h>
62 #include <cam/cam_debug.h>
63 #include <cam/cam_sim.h>
64 #include <cam/cam_xpt.h>
65
66 #include <cam/scsi/scsi_all.h>
67 #include <cam/scsi/scsi_message.h>
68
69 #include <cam/ctl/ctl_io.h>
70 #include <cam/ctl/ctl.h>
71 #include <cam/ctl/ctl_frontend.h>
72 #include <cam/ctl/ctl_util.h>
73 #include <cam/ctl/ctl_error.h>
74
75 struct ctlfe_softc {
76         struct ctl_port port;
77         path_id_t path_id;
78         target_id_t target_id;
79         u_int   maxio;
80         struct cam_sim *sim;
81         char port_name[DEV_IDLEN];
82         struct mtx lun_softc_mtx;
83         STAILQ_HEAD(, ctlfe_lun_softc) lun_softc_list;
84         STAILQ_ENTRY(ctlfe_softc) links;
85 };
86
87 STAILQ_HEAD(, ctlfe_softc) ctlfe_softc_list;
88 struct mtx ctlfe_list_mtx;
89 static char ctlfe_mtx_desc[] = "ctlfelist";
90 #ifdef CTLFE_INIT_ENABLE
91 static int ctlfe_max_targets = 1;
92 static int ctlfe_num_targets = 0;
93 #endif
94
95 typedef enum {
96         CTLFE_LUN_NONE          = 0x00,
97         CTLFE_LUN_WILDCARD      = 0x01
98 } ctlfe_lun_flags;
99
100 struct ctlfe_lun_softc {
101         struct ctlfe_softc *parent_softc;
102         struct cam_periph *periph;
103         ctlfe_lun_flags flags;
104         uint64_t ccbs_alloced;
105         uint64_t ccbs_freed;
106         uint64_t ctios_sent;
107         uint64_t ctios_returned;
108         uint64_t atios_alloced;
109         uint64_t atios_freed;
110         uint64_t inots_alloced;
111         uint64_t inots_freed;
112         /* bus_dma_tag_t dma_tag; */
113         TAILQ_HEAD(, ccb_hdr) work_queue;
114         STAILQ_ENTRY(ctlfe_lun_softc) links;
115 };
116
117 typedef enum {
118         CTLFE_CMD_NONE          = 0x00,
119         CTLFE_CMD_PIECEWISE     = 0x01
120 } ctlfe_cmd_flags;
121
122 struct ctlfe_cmd_info {
123         int cur_transfer_index;
124         size_t cur_transfer_off;
125         ctlfe_cmd_flags flags;
126         /*
127          * XXX KDM struct bus_dma_segment is 8 bytes on i386, and 16
128          * bytes on amd64.  So with 32 elements, this is 256 bytes on
129          * i386 and 512 bytes on amd64.
130          */
131 #define CTLFE_MAX_SEGS  32
132         bus_dma_segment_t cam_sglist[CTLFE_MAX_SEGS];
133 };
134
135 /*
136  * When we register the adapter/bus, request that this many ctl_ios be
137  * allocated.  This should be the maximum supported by the adapter, but we
138  * currently don't have a way to get that back from the path inquiry.
139  * XXX KDM add that to the path inquiry.
140  */
141 #define CTLFE_REQ_CTL_IO        4096
142 /*
143  * Number of Accept Target I/O CCBs to allocate and queue down to the
144  * adapter per LUN.
145  * XXX KDM should this be controlled by CTL?
146  */
147 #define CTLFE_ATIO_PER_LUN      1024
148 /*
149  * Number of Immediate Notify CCBs (used for aborts, resets, etc.) to
150  * allocate and queue down to the adapter per LUN.
151  * XXX KDM should this be controlled by CTL?
152  */
153 #define CTLFE_IN_PER_LUN        1024
154
155 /*
156  * Timeout (in seconds) on CTIO CCB allocation for doing a DMA or sending
157  * status to the initiator.  The SIM is expected to have its own timeouts,
158  * so we're not putting this timeout around the CCB execution time.  The
159  * SIM should timeout and let us know if it has an issue.
160  */
161 #define CTLFE_DMA_TIMEOUT       60
162
163 /*
164  * Turn this on to enable extra debugging prints.
165  */
166 #if 0
167 #define CTLFE_DEBUG
168 #endif
169
170 /*
171  * Use randomly assigned WWNN/WWPN values.  This is to work around an issue
172  * in the FreeBSD initiator that makes it unable to rescan the target if
173  * the target gets rebooted and the WWNN/WWPN stay the same.
174  */
175 #if 0
176 #define RANDOM_WWNN
177 #endif
178
179 MALLOC_DEFINE(M_CTLFE, "CAM CTL FE", "CAM CTL FE interface");
180
181 #define io_ptr          ppriv_ptr0
182
183 /* This is only used in the CTIO */
184 #define ccb_atio        ppriv_ptr1
185
186 int                     ctlfeinitialize(void);
187 void                    ctlfeshutdown(void);
188 static periph_init_t    ctlfeperiphinit;
189 static void             ctlfeasync(void *callback_arg, uint32_t code,
190                                    struct cam_path *path, void *arg);
191 static periph_ctor_t    ctlferegister;
192 static periph_oninv_t   ctlfeoninvalidate;
193 static periph_dtor_t    ctlfecleanup;
194 static periph_start_t   ctlfestart;
195 static void             ctlfedone(struct cam_periph *periph,
196                                   union ccb *done_ccb);
197
198 static void             ctlfe_onoffline(void *arg, int online);
199 static void             ctlfe_online(void *arg);
200 static void             ctlfe_offline(void *arg);
201 static int              ctlfe_lun_enable(void *arg, int lun_id);
202 static int              ctlfe_lun_disable(void *arg, int lun_id);
203 static void             ctlfe_dump_sim(struct cam_sim *sim);
204 static void             ctlfe_dump_queue(struct ctlfe_lun_softc *softc);
205 static void             ctlfe_datamove(union ctl_io *io);
206 static void             ctlfe_done(union ctl_io *io);
207 static void             ctlfe_dump(void);
208
209 static struct periph_driver ctlfe_driver =
210 {
211         ctlfeperiphinit, "ctl",
212         TAILQ_HEAD_INITIALIZER(ctlfe_driver.units), /*generation*/ 0,
213         CAM_PERIPH_DRV_EARLY
214 };
215
216 static struct ctl_frontend ctlfe_frontend =
217 {
218         .name = "camtgt",
219         .init = ctlfeinitialize,
220         .fe_dump = ctlfe_dump,
221         .shutdown = ctlfeshutdown,
222 };
223 CTL_FRONTEND_DECLARE(ctlfe, ctlfe_frontend);
224
225 void
226 ctlfeshutdown(void)
227 {
228         return;
229 }
230
231 int
232 ctlfeinitialize(void)
233 {
234
235         STAILQ_INIT(&ctlfe_softc_list);
236         mtx_init(&ctlfe_list_mtx, ctlfe_mtx_desc, NULL, MTX_DEF);
237         periphdriver_register(&ctlfe_driver);
238         return (0);
239 }
240
241 void
242 ctlfeperiphinit(void)
243 {
244         cam_status status;
245
246         status = xpt_register_async(AC_PATH_REGISTERED | AC_PATH_DEREGISTERED |
247                                     AC_CONTRACT, ctlfeasync, NULL, NULL);
248         if (status != CAM_REQ_CMP) {
249                 printf("ctl: Failed to attach async callback due to CAM "
250                        "status 0x%x!\n", status);
251         }
252 }
253
254 static void
255 ctlfeasync(void *callback_arg, uint32_t code, struct cam_path *path, void *arg)
256 {
257         struct ctlfe_softc *softc;
258
259 #ifdef CTLFEDEBUG
260         printf("%s: entered\n", __func__);
261 #endif
262
263         mtx_lock(&ctlfe_list_mtx);
264         STAILQ_FOREACH(softc, &ctlfe_softc_list, links) {
265                 if (softc->path_id == xpt_path_path_id(path))
266                         break;
267         }
268         mtx_unlock(&ctlfe_list_mtx);
269
270         /*
271          * When a new path gets registered, and it is capable of target
272          * mode, go ahead and attach.  Later on, we may need to be more
273          * selective, but for now this will be sufficient.
274          */
275         switch (code) {
276         case AC_PATH_REGISTERED: {
277                 struct ctl_port *port;
278                 struct ccb_pathinq *cpi;
279                 int retval;
280
281                 cpi = (struct ccb_pathinq *)arg;
282
283                 /* Don't attach if it doesn't support target mode */
284                 if ((cpi->target_sprt & PIT_PROCESSOR) == 0) {
285 #ifdef CTLFEDEBUG
286                         printf("%s: SIM %s%d doesn't support target mode\n",
287                                __func__, cpi->dev_name, cpi->unit_number);
288 #endif
289                         break;
290                 }
291
292                 if (softc != NULL) {
293 #ifdef CTLFEDEBUG
294                         printf("%s: CTL port for CAM path %u already exists\n",
295                                __func__, xpt_path_path_id(path));
296 #endif
297                         break;
298                 }
299
300 #ifdef CTLFE_INIT_ENABLE
301                 if (ctlfe_num_targets >= ctlfe_max_targets) {
302                         union ccb *ccb;
303
304                         ccb = (union ccb *)malloc(sizeof(*ccb), M_TEMP,
305                                                   M_NOWAIT | M_ZERO);
306                         if (ccb == NULL) {
307                                 printf("%s: unable to malloc CCB!\n", __func__);
308                                 return;
309                         }
310                         xpt_setup_ccb(&ccb->ccb_h, path, CAM_PRIORITY_NONE);
311
312                         ccb->ccb_h.func_code = XPT_SET_SIM_KNOB;
313                         ccb->knob.xport_specific.valid = KNOB_VALID_ROLE;
314                         ccb->knob.xport_specific.fc.role = KNOB_ROLE_INITIATOR;
315
316                         xpt_action(ccb);
317
318                         if ((ccb->ccb_h.status & CAM_STATUS_MASK) !=
319                              CAM_REQ_CMP) {
320                                 printf("%s: SIM %s%d (path id %d) initiator "
321                                        "enable failed with status %#x\n",
322                                        __func__, cpi->dev_name,
323                                        cpi->unit_number, cpi->ccb_h.path_id,
324                                        ccb->ccb_h.status);
325                         } else {
326                                 printf("%s: SIM %s%d (path id %d) initiator "
327                                        "enable succeeded\n",
328                                        __func__, cpi->dev_name,
329                                        cpi->unit_number, cpi->ccb_h.path_id);
330                         }
331
332                         free(ccb, M_TEMP);
333
334                         break;
335                 } else {
336                         ctlfe_num_targets++;
337                 }
338
339                 printf("%s: ctlfe_num_targets = %d\n", __func__,
340                        ctlfe_num_targets);
341 #endif /* CTLFE_INIT_ENABLE */
342
343                 /*
344                  * We're in an interrupt context here, so we have to
345                  * use M_NOWAIT.  Of course this means trouble if we
346                  * can't allocate memory.
347                  */
348                 softc = malloc(sizeof(*softc), M_CTLFE, M_NOWAIT | M_ZERO);
349                 if (softc == NULL) {
350                         printf("%s: unable to malloc %zd bytes for softc\n",
351                                __func__, sizeof(*softc));
352                         return;
353                 }
354
355                 softc->path_id = cpi->ccb_h.path_id;
356                 softc->target_id = cpi->initiator_id;
357                 softc->sim = xpt_path_sim(path);
358                 if (cpi->maxio != 0)
359                         softc->maxio = cpi->maxio;
360                 else
361                         softc->maxio = DFLTPHYS;
362                 mtx_init(&softc->lun_softc_mtx, "LUN softc mtx", NULL, MTX_DEF);
363                 STAILQ_INIT(&softc->lun_softc_list);
364
365                 port = &softc->port;
366                 port->frontend = &ctlfe_frontend;
367
368                 /*
369                  * XXX KDM should we be more accurate here ?
370                  */
371                 if (cpi->transport == XPORT_FC)
372                         port->port_type = CTL_PORT_FC;
373                 else if (cpi->transport == XPORT_SAS)
374                         port->port_type = CTL_PORT_SAS;
375                 else
376                         port->port_type = CTL_PORT_SCSI;
377
378                 /* XXX KDM what should the real number be here? */
379                 port->num_requested_ctl_io = 4096;
380                 snprintf(softc->port_name, sizeof(softc->port_name),
381                          "%s%d", cpi->dev_name, cpi->unit_number);
382                 /*
383                  * XXX KDM it would be nice to allocate storage in the
384                  * frontend structure itself.
385                  */
386                 port->port_name = softc->port_name;
387                 port->physical_port = cpi->bus_id;
388                 port->virtual_port = 0;
389                 port->port_online = ctlfe_online;
390                 port->port_offline = ctlfe_offline;
391                 port->onoff_arg = softc;
392                 port->lun_enable = ctlfe_lun_enable;
393                 port->lun_disable = ctlfe_lun_disable;
394                 port->targ_lun_arg = softc;
395                 port->fe_datamove = ctlfe_datamove;
396                 port->fe_done = ctlfe_done;
397                 /*
398                  * XXX KDM the path inquiry doesn't give us the maximum
399                  * number of targets supported.
400                  */
401                 port->max_targets = cpi->max_target;
402                 port->max_target_id = cpi->max_target;
403                 port->targ_port = -1;
404                 
405                 /*
406                  * XXX KDM need to figure out whether we're the master or
407                  * slave.
408                  */
409 #ifdef CTLFEDEBUG
410                 printf("%s: calling ctl_port_register() for %s%d\n",
411                        __func__, cpi->dev_name, cpi->unit_number);
412 #endif
413                 retval = ctl_port_register(port);
414                 if (retval != 0) {
415                         printf("%s: ctl_port_register() failed with "
416                                "error %d!\n", __func__, retval);
417                         mtx_destroy(&softc->lun_softc_mtx);
418                         free(softc, M_CTLFE);
419                         break;
420                 } else {
421                         mtx_lock(&ctlfe_list_mtx);
422                         STAILQ_INSERT_TAIL(&ctlfe_softc_list, softc, links);
423                         mtx_unlock(&ctlfe_list_mtx);
424                 }
425
426                 break;
427         }
428         case AC_PATH_DEREGISTERED: {
429
430                 if (softc != NULL) {
431                         /*
432                          * XXX KDM are we certain at this point that there
433                          * are no outstanding commands for this frontend?
434                          */
435                         mtx_lock(&ctlfe_list_mtx);
436                         STAILQ_REMOVE(&ctlfe_softc_list, softc, ctlfe_softc,
437                             links);
438                         mtx_unlock(&ctlfe_list_mtx);
439                         ctl_port_deregister(&softc->port);
440                         mtx_destroy(&softc->lun_softc_mtx);
441                         free(softc, M_CTLFE);
442                 }
443                 break;
444         }
445         case AC_CONTRACT: {
446                 struct ac_contract *ac;
447
448                 ac = (struct ac_contract *)arg;
449
450                 switch (ac->contract_number) {
451                 case AC_CONTRACT_DEV_CHG: {
452                         struct ac_device_changed *dev_chg;
453                         int retval;
454
455                         dev_chg = (struct ac_device_changed *)ac->contract_data;
456
457                         printf("%s: WWPN %#jx port 0x%06x path %u target %u %s\n",
458                                __func__, dev_chg->wwpn, dev_chg->port,
459                                xpt_path_path_id(path), dev_chg->target,
460                                (dev_chg->arrived == 0) ?  "left" : "arrived");
461
462                         if (softc == NULL) {
463                                 printf("%s: CTL port for CAM path %u not "
464                                        "found!\n", __func__,
465                                        xpt_path_path_id(path));
466                                 break;
467                         }
468                         if (dev_chg->arrived != 0) {
469                                 retval = ctl_add_initiator(&softc->port,
470                                     dev_chg->target, dev_chg->wwpn, NULL);
471                         } else {
472                                 retval = ctl_remove_initiator(&softc->port,
473                                     dev_chg->target);
474                         }
475
476                         if (retval < 0) {
477                                 printf("%s: could not %s port %d iid %u "
478                                        "WWPN %#jx!\n", __func__,
479                                        (dev_chg->arrived != 0) ? "add" :
480                                        "remove", softc->port.targ_port,
481                                        dev_chg->target,
482                                        (uintmax_t)dev_chg->wwpn);
483                         }
484                         break;
485                 }
486                 default:
487                         printf("%s: unsupported contract number %ju\n",
488                                __func__, (uintmax_t)ac->contract_number);
489                         break;
490                 }
491                 break;
492         }
493         default:
494                 break;
495         }
496 }
497
498 static cam_status
499 ctlferegister(struct cam_periph *periph, void *arg)
500 {
501         struct ctlfe_softc *bus_softc;
502         struct ctlfe_lun_softc *softc;
503         union ccb en_lun_ccb;
504         cam_status status;
505         int i;
506
507         softc = (struct ctlfe_lun_softc *)arg;
508         bus_softc = softc->parent_softc;
509         
510         TAILQ_INIT(&softc->work_queue);
511         softc->periph = periph;
512         periph->softc = softc;
513
514         xpt_setup_ccb(&en_lun_ccb.ccb_h, periph->path, CAM_PRIORITY_NONE);
515         en_lun_ccb.ccb_h.func_code = XPT_EN_LUN;
516         en_lun_ccb.cel.grp6_len = 0;
517         en_lun_ccb.cel.grp7_len = 0;
518         en_lun_ccb.cel.enable = 1;
519         xpt_action(&en_lun_ccb);
520         status = (en_lun_ccb.ccb_h.status & CAM_STATUS_MASK);
521         if (status != CAM_REQ_CMP) {
522                 xpt_print(periph->path, "%s: Enable LUN failed, status 0x%x\n", 
523                           __func__, en_lun_ccb.ccb_h.status);
524                 return (status);
525         }
526
527         status = CAM_REQ_CMP;
528
529         for (i = 0; i < CTLFE_ATIO_PER_LUN; i++) {
530                 union ccb *new_ccb;
531                 union ctl_io *new_io;
532                 struct ctlfe_cmd_info *cmd_info;
533
534                 new_ccb = (union ccb *)malloc(sizeof(*new_ccb), M_CTLFE,
535                                               M_ZERO|M_NOWAIT);
536                 if (new_ccb == NULL) {
537                         status = CAM_RESRC_UNAVAIL;
538                         break;
539                 }
540                 new_io = ctl_alloc_io_nowait(bus_softc->port.ctl_pool_ref);
541                 if (new_io == NULL) {
542                         free(new_ccb, M_CTLFE);
543                         status = CAM_RESRC_UNAVAIL;
544                         break;
545                 }
546                 cmd_info = malloc(sizeof(*cmd_info), M_CTLFE,
547                     M_ZERO | M_NOWAIT);
548                 if (cmd_info == NULL) {
549                         ctl_free_io(new_io);
550                         free(new_ccb, M_CTLFE);
551                         status = CAM_RESRC_UNAVAIL;
552                         break;
553                 }
554                 new_io->io_hdr.ctl_private[CTL_PRIV_FRONTEND2].ptr = cmd_info;
555                 softc->atios_alloced++;
556                 new_ccb->ccb_h.io_ptr = new_io;
557
558                 xpt_setup_ccb(&new_ccb->ccb_h, periph->path, /*priority*/ 1);
559                 new_ccb->ccb_h.func_code = XPT_ACCEPT_TARGET_IO;
560                 new_ccb->ccb_h.cbfcnp = ctlfedone;
561                 new_ccb->ccb_h.flags |= CAM_UNLOCKED;
562                 xpt_action(new_ccb);
563                 status = new_ccb->ccb_h.status;
564                 if ((status & CAM_STATUS_MASK) != CAM_REQ_INPROG) {
565                         free(cmd_info, M_CTLFE);
566                         ctl_free_io(new_io);
567                         free(new_ccb, M_CTLFE);
568                         break;
569                 }
570         }
571
572         status = cam_periph_acquire(periph);
573         if ((status & CAM_STATUS_MASK) != CAM_REQ_CMP) {
574                 xpt_print(periph->path, "%s: could not acquire reference "
575                           "count, status = %#x\n", __func__, status);
576                 return (status);
577         }
578
579         if (i == 0) {
580                 xpt_print(periph->path, "%s: could not allocate ATIO CCBs, "
581                           "status 0x%x\n", __func__, status);
582                 return (CAM_REQ_CMP_ERR);
583         }
584
585         for (i = 0; i < CTLFE_IN_PER_LUN; i++) {
586                 union ccb *new_ccb;
587                 union ctl_io *new_io;
588
589                 new_ccb = (union ccb *)malloc(sizeof(*new_ccb), M_CTLFE,
590                                               M_ZERO|M_NOWAIT);
591                 if (new_ccb == NULL) {
592                         status = CAM_RESRC_UNAVAIL;
593                         break;
594                 }
595                 new_io = ctl_alloc_io_nowait(bus_softc->port.ctl_pool_ref);
596                 if (new_io == NULL) {
597                         free(new_ccb, M_CTLFE);
598                         status = CAM_RESRC_UNAVAIL;
599                         break;
600                 }
601                 softc->inots_alloced++;
602                 new_ccb->ccb_h.io_ptr = new_io;
603
604                 xpt_setup_ccb(&new_ccb->ccb_h, periph->path, /*priority*/ 1);
605                 new_ccb->ccb_h.func_code = XPT_IMMEDIATE_NOTIFY;
606                 new_ccb->ccb_h.cbfcnp = ctlfedone;
607                 new_ccb->ccb_h.flags |= CAM_UNLOCKED;
608                 xpt_action(new_ccb);
609                 status = new_ccb->ccb_h.status;
610                 if ((status & CAM_STATUS_MASK) != CAM_REQ_INPROG) {
611                         /*
612                          * Note that we don't free the CCB here.  If the
613                          * status is not CAM_REQ_INPROG, then we're
614                          * probably talking to a SIM that says it is
615                          * target-capable but doesn't support the 
616                          * XPT_IMMEDIATE_NOTIFY CCB.  i.e. it supports the
617                          * older API.  In that case, it'll call xpt_done()
618                          * on the CCB, and we need to free it in our done
619                          * routine as a result.
620                          */
621                         break;
622                 }
623         }
624         if ((i == 0)
625          || (status != CAM_REQ_INPROG)) {
626                 xpt_print(periph->path, "%s: could not allocate immediate "
627                           "notify CCBs, status 0x%x\n", __func__, status);
628                 return (CAM_REQ_CMP_ERR);
629         }
630         mtx_lock(&bus_softc->lun_softc_mtx);
631         STAILQ_INSERT_TAIL(&bus_softc->lun_softc_list, softc, links);
632         mtx_unlock(&bus_softc->lun_softc_mtx);
633         return (CAM_REQ_CMP);
634 }
635
636 static void
637 ctlfeoninvalidate(struct cam_periph *periph)
638 {
639         union ccb en_lun_ccb;
640         cam_status status;
641         struct ctlfe_softc *bus_softc;
642         struct ctlfe_lun_softc *softc;
643
644         softc = (struct ctlfe_lun_softc *)periph->softc;
645
646         xpt_setup_ccb(&en_lun_ccb.ccb_h, periph->path, CAM_PRIORITY_NONE);
647         en_lun_ccb.ccb_h.func_code = XPT_EN_LUN;
648         en_lun_ccb.cel.grp6_len = 0;
649         en_lun_ccb.cel.grp7_len = 0;
650         en_lun_ccb.cel.enable = 0;
651         xpt_action(&en_lun_ccb);
652         status = (en_lun_ccb.ccb_h.status & CAM_STATUS_MASK);
653         if (status != CAM_REQ_CMP) {
654                 xpt_print(periph->path, "%s: Disable LUN failed, status 0x%x\n",
655                           __func__, en_lun_ccb.ccb_h.status);
656                 /*
657                  * XXX KDM what do we do now?
658                  */
659         }
660
661         bus_softc = softc->parent_softc;
662         mtx_lock(&bus_softc->lun_softc_mtx);
663         STAILQ_REMOVE(&bus_softc->lun_softc_list, softc, ctlfe_lun_softc, links);
664         mtx_unlock(&bus_softc->lun_softc_mtx);
665 }
666
667 static void
668 ctlfecleanup(struct cam_periph *periph)
669 {
670         struct ctlfe_lun_softc *softc;
671
672         softc = (struct ctlfe_lun_softc *)periph->softc;
673
674         KASSERT(softc->ccbs_freed == softc->ccbs_alloced, ("%s: "
675                 "ccbs_freed %ju != ccbs_alloced %ju", __func__,
676                 softc->ccbs_freed, softc->ccbs_alloced));
677         KASSERT(softc->ctios_returned == softc->ctios_sent, ("%s: "
678                 "ctios_returned %ju != ctios_sent %ju", __func__,
679                 softc->ctios_returned, softc->ctios_sent));
680         KASSERT(softc->atios_freed == softc->atios_alloced, ("%s: "
681                 "atios_freed %ju != atios_alloced %ju", __func__,
682                 softc->atios_freed, softc->atios_alloced));
683         KASSERT(softc->inots_freed == softc->inots_alloced, ("%s: "
684                 "inots_freed %ju != inots_alloced %ju", __func__,
685                 softc->inots_freed, softc->inots_alloced));
686
687         free(softc, M_CTLFE);
688 }
689
690 static void
691 ctlfedata(struct ctlfe_lun_softc *softc, union ctl_io *io,
692     ccb_flags *flags, uint8_t **data_ptr, uint32_t *dxfer_len,
693     u_int16_t *sglist_cnt)
694 {
695         struct ctlfe_softc *bus_softc;
696         struct ctlfe_cmd_info *cmd_info;
697         struct ctl_sg_entry *ctl_sglist;
698         bus_dma_segment_t *cam_sglist;
699         size_t off;
700         int i, idx;
701
702         cmd_info = io->io_hdr.ctl_private[CTL_PRIV_FRONTEND2].ptr;
703         bus_softc = softc->parent_softc;
704
705         /*
706          * Set the direction, relative to the initiator.
707          */
708         *flags &= ~CAM_DIR_MASK;
709         if ((io->io_hdr.flags & CTL_FLAG_DATA_MASK) == CTL_FLAG_DATA_IN)
710                 *flags |= CAM_DIR_IN;
711         else
712                 *flags |= CAM_DIR_OUT;
713
714         *flags &= ~CAM_DATA_MASK;
715         idx = cmd_info->cur_transfer_index;
716         off = cmd_info->cur_transfer_off;
717         cmd_info->flags &= ~CTLFE_CMD_PIECEWISE;
718         if (io->scsiio.kern_sg_entries == 0) {
719                 /* No S/G list. */
720                 *data_ptr = io->scsiio.kern_data_ptr + off;
721                 if (io->scsiio.kern_data_len - off <= bus_softc->maxio) {
722                         *dxfer_len = io->scsiio.kern_data_len - off;
723                 } else {
724                         *dxfer_len = bus_softc->maxio;
725                         cmd_info->cur_transfer_index = -1;
726                         cmd_info->cur_transfer_off = bus_softc->maxio;
727                         cmd_info->flags |= CTLFE_CMD_PIECEWISE;
728                 }
729                 *sglist_cnt = 0;
730
731                 if (io->io_hdr.flags & CTL_FLAG_BUS_ADDR)
732                         *flags |= CAM_DATA_PADDR;
733                 else
734                         *flags |= CAM_DATA_VADDR;
735         } else {
736                 /* S/G list with physical or virtual pointers. */
737                 ctl_sglist = (struct ctl_sg_entry *)io->scsiio.kern_data_ptr;
738                 cam_sglist = cmd_info->cam_sglist;
739                 *dxfer_len = 0;
740                 for (i = 0; i < io->scsiio.kern_sg_entries - idx; i++) {
741                         cam_sglist[i].ds_addr = (bus_addr_t)ctl_sglist[i + idx].addr + off;
742                         if (ctl_sglist[i + idx].len - off <= bus_softc->maxio - *dxfer_len) {
743                                 cam_sglist[i].ds_len = ctl_sglist[idx + i].len - off;
744                                 *dxfer_len += cam_sglist[i].ds_len;
745                         } else {
746                                 cam_sglist[i].ds_len = bus_softc->maxio - *dxfer_len;
747                                 cmd_info->cur_transfer_index = idx + i;
748                                 cmd_info->cur_transfer_off = cam_sglist[i].ds_len + off;
749                                 cmd_info->flags |= CTLFE_CMD_PIECEWISE;
750                                 *dxfer_len += cam_sglist[i].ds_len;
751                                 if (ctl_sglist[i].len != 0)
752                                         i++;
753                                 break;
754                         }
755                         if (i == (CTLFE_MAX_SEGS - 1) &&
756                             idx + i < (io->scsiio.kern_sg_entries - 1)) {
757                                 cmd_info->cur_transfer_index = idx + i + 1;
758                                 cmd_info->cur_transfer_off = 0;
759                                 cmd_info->flags |= CTLFE_CMD_PIECEWISE;
760                                 i++;
761                                 break;
762                         }
763                         off = 0;
764                 }
765                 *sglist_cnt = i;
766                 if (io->io_hdr.flags & CTL_FLAG_BUS_ADDR)
767                         *flags |= CAM_DATA_SG_PADDR;
768                 else
769                         *flags |= CAM_DATA_SG;
770                 *data_ptr = (uint8_t *)cam_sglist;
771         }
772 }
773
774 static void
775 ctlfestart(struct cam_periph *periph, union ccb *start_ccb)
776 {
777         struct ctlfe_lun_softc *softc;
778         struct ctlfe_cmd_info *cmd_info;
779         struct ccb_hdr *ccb_h;
780         struct ccb_accept_tio *atio;
781         struct ccb_scsiio *csio;
782         uint8_t *data_ptr;
783         uint32_t dxfer_len;
784         ccb_flags flags;
785         union ctl_io *io;
786         uint8_t scsi_status;
787
788         softc = (struct ctlfe_lun_softc *)periph->softc;
789         softc->ccbs_alloced++;
790
791         ccb_h = TAILQ_FIRST(&softc->work_queue);
792         if (ccb_h == NULL) {
793                 softc->ccbs_freed++;
794                 xpt_release_ccb(start_ccb);
795                 return;
796         }
797
798         /* Take the ATIO off the work queue */
799         TAILQ_REMOVE(&softc->work_queue, ccb_h, periph_links.tqe);
800         atio = (struct ccb_accept_tio *)ccb_h;
801         io = (union ctl_io *)ccb_h->io_ptr;
802         csio = &start_ccb->csio;
803
804         flags = atio->ccb_h.flags &
805                 (CAM_DIS_DISCONNECT|CAM_TAG_ACTION_VALID|CAM_DIR_MASK);
806         cmd_info = io->io_hdr.ctl_private[CTL_PRIV_FRONTEND2].ptr;
807         cmd_info->cur_transfer_index = 0;
808         cmd_info->cur_transfer_off = 0;
809         cmd_info->flags = 0;
810
811         if (io->io_hdr.flags & CTL_FLAG_DMA_QUEUED) {
812                 /*
813                  * Datamove call, we need to setup the S/G list.
814                  */
815                 scsi_status = 0;
816                 csio->cdb_len = atio->cdb_len;
817                 ctlfedata(softc, io, &flags, &data_ptr, &dxfer_len,
818                     &csio->sglist_cnt);
819                 io->scsiio.ext_data_filled += dxfer_len;
820                 if (io->scsiio.ext_data_filled > io->scsiio.kern_total_len) {
821                         xpt_print(periph->path, "%s: tag 0x%04x "
822                                   "fill len %u > total %u\n",
823                                   __func__, io->scsiio.tag_num,
824                                   io->scsiio.ext_data_filled,
825                                   io->scsiio.kern_total_len);
826                 }
827         } else {
828                 /*
829                  * We're done, send status back.
830                  */
831                 if ((io->io_hdr.flags & CTL_FLAG_ABORT) &&
832                     (io->io_hdr.flags & CTL_FLAG_ABORT_STATUS) == 0) {
833                         io->io_hdr.flags &= ~CTL_FLAG_STATUS_QUEUED;
834
835                         /*
836                          * If this command was aborted, we don't
837                          * need to send status back to the SIM.
838                          * Just free the CTIO and ctl_io, and
839                          * recycle the ATIO back to the SIM.
840                          */
841                         xpt_print(periph->path, "%s: aborted "
842                                   "command 0x%04x discarded\n",
843                                   __func__, io->scsiio.tag_num);
844                         /*
845                          * For a wildcard attachment, commands can
846                          * come in with a specific target/lun.  Reset
847                          * the target and LUN fields back to the
848                          * wildcard values before we send them back
849                          * down to the SIM.  The SIM has a wildcard
850                          * LUN enabled, not whatever target/lun
851                          * these happened to be.
852                          */
853                         if (softc->flags & CTLFE_LUN_WILDCARD) {
854                                 atio->ccb_h.target_id = CAM_TARGET_WILDCARD;
855                                 atio->ccb_h.target_lun = CAM_LUN_WILDCARD;
856                         }
857
858                         if (atio->ccb_h.func_code != XPT_ACCEPT_TARGET_IO) {
859                                 xpt_print(periph->path, "%s: func_code "
860                                           "is %#x\n", __func__,
861                                           atio->ccb_h.func_code);
862                         }
863                         start_ccb->ccb_h.func_code = XPT_ABORT;
864                         start_ccb->cab.abort_ccb = (union ccb *)atio;
865
866                         /* Tell the SIM that we've aborted this ATIO */
867                         xpt_action(start_ccb);
868                         softc->ccbs_freed++;
869                         xpt_release_ccb(start_ccb);
870
871                         /*
872                          * Send the ATIO back down to the SIM.
873                          */
874                         xpt_action((union ccb *)atio);
875
876                         /*
877                          * If we still have work to do, ask for
878                          * another CCB.  Otherwise, deactivate our
879                          * callout.
880                          */
881                         if (!TAILQ_EMPTY(&softc->work_queue))
882                                 xpt_schedule(periph, /*priority*/ 1);
883                         return;
884                 }
885                 data_ptr = NULL;
886                 dxfer_len = 0;
887                 csio->sglist_cnt = 0;
888                 scsi_status = 0;
889         }
890         if ((io->io_hdr.flags & CTL_FLAG_STATUS_QUEUED) &&
891             (cmd_info->flags & CTLFE_CMD_PIECEWISE) == 0 &&
892             ((io->io_hdr.flags & CTL_FLAG_DMA_QUEUED) == 0 ||
893              io->io_hdr.status == CTL_SUCCESS)) {
894                 flags |= CAM_SEND_STATUS;
895                 scsi_status = io->scsiio.scsi_status;
896                 csio->sense_len = io->scsiio.sense_len;
897 #ifdef CTLFEDEBUG
898                 printf("%s: tag %04x status %x\n", __func__,
899                        atio->tag_id, io->io_hdr.status);
900 #endif
901                 if (csio->sense_len != 0) {
902                         csio->sense_data = io->scsiio.sense_data;
903                         flags |= CAM_SEND_SENSE;
904                 } else if (scsi_status == SCSI_STATUS_CHECK_COND) {
905                         xpt_print(periph->path, "%s: check condition "
906                                   "with no sense\n", __func__);
907                 }
908         }
909
910 #ifdef CTLFEDEBUG
911         printf("%s: %s: tag %04x flags %x ptr %p len %u\n", __func__,
912                (flags & CAM_SEND_STATUS) ? "done" : "datamove",
913                atio->tag_id, flags, data_ptr, dxfer_len);
914 #endif
915
916         /*
917          * Valid combinations:
918          *  - CAM_SEND_STATUS, CAM_DATA_SG = 0, dxfer_len = 0,
919          *    sglist_cnt = 0
920          *  - CAM_SEND_STATUS = 0, CAM_DATA_SG = 0, dxfer_len != 0,
921          *    sglist_cnt = 0
922          *  - CAM_SEND_STATUS = 0, CAM_DATA_SG, dxfer_len != 0,
923          *    sglist_cnt != 0
924          */
925 #ifdef CTLFEDEBUG
926         if (((flags & CAM_SEND_STATUS)
927           && (((flags & CAM_DATA_SG) != 0)
928            || (dxfer_len != 0)
929            || (csio->sglist_cnt != 0)))
930          || (((flags & CAM_SEND_STATUS) == 0)
931           && (dxfer_len == 0))
932          || ((flags & CAM_DATA_SG)
933           && (csio->sglist_cnt == 0))
934          || (((flags & CAM_DATA_SG) == 0)
935           && (csio->sglist_cnt != 0))) {
936                 printf("%s: tag %04x cdb %02x flags %#x dxfer_len "
937                        "%d sg %u\n", __func__, atio->tag_id,
938                        atio->cdb_io.cdb_bytes[0], flags, dxfer_len,
939                        csio->sglist_cnt);
940                 printf("%s: tag %04x io status %#x\n", __func__,
941                        atio->tag_id, io->io_hdr.status);
942         }
943 #endif
944         cam_fill_ctio(csio,
945                       /*retries*/ 2,
946                       ctlfedone,
947                       flags,
948                       (flags & CAM_TAG_ACTION_VALID) ? MSG_SIMPLE_Q_TAG : 0,
949                       atio->tag_id,
950                       atio->init_id,
951                       scsi_status,
952                       /*data_ptr*/ data_ptr,
953                       /*dxfer_len*/ dxfer_len,
954                       /*timeout*/ 5 * 1000);
955         start_ccb->ccb_h.flags |= CAM_UNLOCKED;
956         start_ccb->ccb_h.ccb_atio = atio;
957         if (io->io_hdr.flags & CTL_FLAG_DMA_QUEUED)
958                 io->io_hdr.flags |= CTL_FLAG_DMA_INPROG;
959         io->io_hdr.flags &= ~(CTL_FLAG_DMA_QUEUED | CTL_FLAG_STATUS_QUEUED);
960
961         softc->ctios_sent++;
962
963         cam_periph_unlock(periph);
964         xpt_action(start_ccb);
965         cam_periph_lock(periph);
966
967         /*
968          * If we still have work to do, ask for another CCB.
969          */
970         if (!TAILQ_EMPTY(&softc->work_queue))
971                 xpt_schedule(periph, /*priority*/ 1);
972 }
973
974 static void
975 ctlfe_free_ccb(struct cam_periph *periph, union ccb *ccb)
976 {
977         struct ctlfe_lun_softc *softc;
978         union ctl_io *io;
979         struct ctlfe_cmd_info *cmd_info;
980
981         softc = (struct ctlfe_lun_softc *)periph->softc;
982         io = ccb->ccb_h.io_ptr;
983
984         switch (ccb->ccb_h.func_code) {
985         case XPT_ACCEPT_TARGET_IO:
986                 softc->atios_freed++;
987                 cmd_info = io->io_hdr.ctl_private[CTL_PRIV_FRONTEND2].ptr;
988                 free(cmd_info, M_CTLFE);
989                 break;
990         case XPT_IMMEDIATE_NOTIFY:
991         case XPT_NOTIFY_ACKNOWLEDGE:
992                 softc->inots_freed++;
993                 break;
994         default:
995                 break;
996         }
997
998         ctl_free_io(io);
999         free(ccb, M_CTLFE);
1000
1001         KASSERT(softc->atios_freed <= softc->atios_alloced, ("%s: "
1002                 "atios_freed %ju > atios_alloced %ju", __func__,
1003                 softc->atios_freed, softc->atios_alloced));
1004         KASSERT(softc->inots_freed <= softc->inots_alloced, ("%s: "
1005                 "inots_freed %ju > inots_alloced %ju", __func__,
1006                 softc->inots_freed, softc->inots_alloced));
1007
1008         /*
1009          * If we have received all of our CCBs, we can release our
1010          * reference on the peripheral driver.  It will probably go away
1011          * now.
1012          */
1013         if ((softc->atios_freed == softc->atios_alloced)
1014          && (softc->inots_freed == softc->inots_alloced)) {
1015                 cam_periph_release_locked(periph);
1016         }
1017 }
1018
1019 static int
1020 ctlfe_adjust_cdb(struct ccb_accept_tio *atio, uint32_t offset)
1021 {
1022         uint64_t lba;
1023         uint32_t num_blocks, nbc;
1024         uint8_t *cmdbyt = (atio->ccb_h.flags & CAM_CDB_POINTER)?
1025             atio->cdb_io.cdb_ptr : atio->cdb_io.cdb_bytes;
1026
1027         nbc = offset >> 9;      /* ASSUMING 512 BYTE BLOCKS */
1028
1029         switch (cmdbyt[0]) {
1030         case READ_6:
1031         case WRITE_6:
1032         {
1033                 struct scsi_rw_6 *cdb = (struct scsi_rw_6 *)cmdbyt;
1034                 lba = scsi_3btoul(cdb->addr);
1035                 lba &= 0x1fffff;
1036                 num_blocks = cdb->length;
1037                 if (num_blocks == 0)
1038                         num_blocks = 256;
1039                 lba += nbc;
1040                 num_blocks -= nbc;
1041                 scsi_ulto3b(lba, cdb->addr);
1042                 cdb->length = num_blocks;
1043                 break;
1044         }
1045         case READ_10:
1046         case WRITE_10:
1047         {
1048                 struct scsi_rw_10 *cdb = (struct scsi_rw_10 *)cmdbyt;
1049                 lba = scsi_4btoul(cdb->addr);
1050                 num_blocks = scsi_2btoul(cdb->length);
1051                 lba += nbc;
1052                 num_blocks -= nbc;
1053                 scsi_ulto4b(lba, cdb->addr);
1054                 scsi_ulto2b(num_blocks, cdb->length);
1055                 break;
1056         }
1057         case READ_12:
1058         case WRITE_12:
1059         {
1060                 struct scsi_rw_12 *cdb = (struct scsi_rw_12 *)cmdbyt;
1061                 lba = scsi_4btoul(cdb->addr);
1062                 num_blocks = scsi_4btoul(cdb->length);
1063                 lba += nbc;
1064                 num_blocks -= nbc;
1065                 scsi_ulto4b(lba, cdb->addr);
1066                 scsi_ulto4b(num_blocks, cdb->length);
1067                 break;
1068         }
1069         case READ_16:
1070         case WRITE_16:
1071         {
1072                 struct scsi_rw_16 *cdb = (struct scsi_rw_16 *)cmdbyt;
1073                 lba = scsi_8btou64(cdb->addr);
1074                 num_blocks = scsi_4btoul(cdb->length);
1075                 lba += nbc;
1076                 num_blocks -= nbc;
1077                 scsi_u64to8b(lba, cdb->addr);
1078                 scsi_ulto4b(num_blocks, cdb->length);
1079                 break;
1080         }
1081         default:
1082                 return -1;
1083         }
1084         return (0);
1085 }
1086
1087 static void
1088 ctlfedone(struct cam_periph *periph, union ccb *done_ccb)
1089 {
1090         struct ctlfe_lun_softc *softc;
1091         struct ctlfe_softc *bus_softc;
1092         struct ctlfe_cmd_info *cmd_info;
1093         struct ccb_accept_tio *atio = NULL;
1094         union ctl_io *io = NULL;
1095         struct mtx *mtx;
1096
1097         KASSERT((done_ccb->ccb_h.flags & CAM_UNLOCKED) != 0,
1098             ("CCB in ctlfedone() without CAM_UNLOCKED flag"));
1099 #ifdef CTLFE_DEBUG
1100         printf("%s: entered, func_code = %#x\n", __func__,
1101                done_ccb->ccb_h.func_code);
1102 #endif
1103
1104         /*
1105          * At this point CTL has no known use case for device queue freezes.
1106          * In case some SIM think different -- drop its freeze right here.
1107          */
1108         if ((done_ccb->ccb_h.status & CAM_DEV_QFRZN) != 0) {
1109                 cam_release_devq(periph->path,
1110                                  /*relsim_flags*/0,
1111                                  /*reduction*/0,
1112                                  /*timeout*/0,
1113                                  /*getcount_only*/0);
1114                 done_ccb->ccb_h.status &= ~CAM_DEV_QFRZN;
1115         }
1116
1117         softc = (struct ctlfe_lun_softc *)periph->softc;
1118         bus_softc = softc->parent_softc;
1119         mtx = cam_periph_mtx(periph);
1120         mtx_lock(mtx);
1121
1122         /*
1123          * If the peripheral is invalid, ATIOs and immediate notify CCBs
1124          * need to be freed.  Most of the ATIOs and INOTs that come back
1125          * will be CCBs that are being returned from the SIM as a result of
1126          * our disabling the LUN.
1127          *
1128          * Other CCB types are handled in their respective cases below.
1129          */
1130         if (periph->flags & CAM_PERIPH_INVALID) {
1131                 switch (done_ccb->ccb_h.func_code) {
1132                 case XPT_ACCEPT_TARGET_IO:
1133                 case XPT_IMMEDIATE_NOTIFY:
1134                 case XPT_NOTIFY_ACKNOWLEDGE:
1135                         ctlfe_free_ccb(periph, done_ccb);
1136                         goto out;
1137                 default:
1138                         break;
1139                 }
1140
1141         }
1142         switch (done_ccb->ccb_h.func_code) {
1143         case XPT_ACCEPT_TARGET_IO: {
1144
1145                 atio = &done_ccb->atio;
1146
1147  resubmit:
1148                 /*
1149                  * Allocate a ctl_io, pass it to CTL, and wait for the
1150                  * datamove or done.
1151                  */
1152                 mtx_unlock(mtx);
1153                 io = done_ccb->ccb_h.io_ptr;
1154                 cmd_info = io->io_hdr.ctl_private[CTL_PRIV_FRONTEND2].ptr;
1155                 ctl_zero_io(io);
1156
1157                 /* Save pointers on both sides */
1158                 io->io_hdr.ctl_private[CTL_PRIV_FRONTEND].ptr = done_ccb;
1159                 io->io_hdr.ctl_private[CTL_PRIV_FRONTEND2].ptr = cmd_info;
1160                 done_ccb->ccb_h.io_ptr = io;
1161
1162                 /*
1163                  * Only SCSI I/O comes down this path, resets, etc. come
1164                  * down the immediate notify path below.
1165                  */
1166                 io->io_hdr.io_type = CTL_IO_SCSI;
1167                 io->io_hdr.nexus.initid = atio->init_id;
1168                 io->io_hdr.nexus.targ_port = bus_softc->port.targ_port;
1169                 io->io_hdr.nexus.targ_lun = atio->ccb_h.target_lun;
1170                 io->scsiio.tag_num = atio->tag_id;
1171                 switch (atio->tag_action) {
1172                 case CAM_TAG_ACTION_NONE:
1173                         io->scsiio.tag_type = CTL_TAG_UNTAGGED;
1174                         break;
1175                 case MSG_SIMPLE_TASK:
1176                         io->scsiio.tag_type = CTL_TAG_SIMPLE;
1177                         break;
1178                 case MSG_HEAD_OF_QUEUE_TASK:
1179                         io->scsiio.tag_type = CTL_TAG_HEAD_OF_QUEUE;
1180                         break;
1181                 case MSG_ORDERED_TASK:
1182                         io->scsiio.tag_type = CTL_TAG_ORDERED;
1183                         break;
1184                 case MSG_ACA_TASK:
1185                         io->scsiio.tag_type = CTL_TAG_ACA;
1186                         break;
1187                 default:
1188                         io->scsiio.tag_type = CTL_TAG_UNTAGGED;
1189                         printf("%s: unhandled tag type %#x!!\n", __func__,
1190                                atio->tag_action);
1191                         break;
1192                 }
1193                 if (atio->cdb_len > sizeof(io->scsiio.cdb)) {
1194                         printf("%s: WARNING: CDB len %d > ctl_io space %zd\n",
1195                                __func__, atio->cdb_len, sizeof(io->scsiio.cdb));
1196                 }
1197                 io->scsiio.cdb_len = min(atio->cdb_len, sizeof(io->scsiio.cdb));
1198                 bcopy(atio->cdb_io.cdb_bytes, io->scsiio.cdb,
1199                       io->scsiio.cdb_len);
1200
1201 #ifdef CTLFEDEBUG
1202                 printf("%s: %u:%u:%u: tag %04x CDB %02x\n", __func__,
1203                         io->io_hdr.nexus.initid,
1204                         io->io_hdr.nexus.targ_port,
1205                         io->io_hdr.nexus.targ_lun,
1206                         io->scsiio.tag_num, io->scsiio.cdb[0]);
1207 #endif
1208
1209                 ctl_queue(io);
1210                 return;
1211         }
1212         case XPT_CONT_TARGET_IO: {
1213                 int srr = 0;
1214                 uint32_t srr_off = 0;
1215
1216                 atio = (struct ccb_accept_tio *)done_ccb->ccb_h.ccb_atio;
1217                 io = (union ctl_io *)atio->ccb_h.io_ptr;
1218
1219                 softc->ctios_returned++;
1220 #ifdef CTLFEDEBUG
1221                 printf("%s: got XPT_CONT_TARGET_IO tag %#x flags %#x\n",
1222                        __func__, atio->tag_id, done_ccb->ccb_h.flags);
1223 #endif
1224                 /*
1225                  * Handle SRR case were the data pointer is pushed back hack
1226                  */
1227                 if ((done_ccb->ccb_h.status & CAM_STATUS_MASK) == CAM_MESSAGE_RECV
1228                     && done_ccb->csio.msg_ptr != NULL
1229                     && done_ccb->csio.msg_ptr[0] == MSG_EXTENDED
1230                     && done_ccb->csio.msg_ptr[1] == 5
1231                     && done_ccb->csio.msg_ptr[2] == 0) {
1232                         srr = 1;
1233                         srr_off =
1234                             (done_ccb->csio.msg_ptr[3] << 24)
1235                             | (done_ccb->csio.msg_ptr[4] << 16)
1236                             | (done_ccb->csio.msg_ptr[5] << 8)
1237                             | (done_ccb->csio.msg_ptr[6]);
1238                 }
1239
1240                 if (srr && (io->io_hdr.flags & CTL_FLAG_DMA_INPROG) == 0) {
1241                         /*
1242                          * If status was being sent, the back end data is now
1243                          * history. Hack it up and resubmit a new command with
1244                          * the CDB adjusted. If the SIM does the right thing,
1245                          * all of the resid math should work.
1246                          */
1247                         softc->ccbs_freed++;
1248                         xpt_release_ccb(done_ccb);
1249                         if (ctlfe_adjust_cdb(atio, srr_off) == 0) {
1250                                 done_ccb = (union ccb *)atio;
1251                                 goto resubmit;
1252                         }
1253                         /*
1254                          * Fall through to doom....
1255                          */
1256                 } else if (srr) {
1257                         /*
1258                          * If we have an srr and we're still sending data, we
1259                          * should be able to adjust offsets and cycle again.
1260                          */
1261                         io->scsiio.kern_rel_offset =
1262                             io->scsiio.ext_data_filled = srr_off;
1263                         io->scsiio.ext_data_len = io->scsiio.kern_total_len -
1264                             io->scsiio.kern_rel_offset;
1265                         softc->ccbs_freed++;
1266                         io->scsiio.io_hdr.status = CTL_STATUS_NONE;
1267                         xpt_release_ccb(done_ccb);
1268                         TAILQ_INSERT_HEAD(&softc->work_queue, &atio->ccb_h,
1269                                           periph_links.tqe);
1270                         xpt_schedule(periph, /*priority*/ 1);
1271                         break;
1272                 }
1273
1274                 if ((done_ccb->ccb_h.flags & CAM_SEND_STATUS) &&
1275                     (done_ccb->ccb_h.status & CAM_STATUS_MASK) == CAM_REQ_CMP)
1276                         io->io_hdr.flags |= CTL_FLAG_STATUS_SENT;
1277
1278                 /*
1279                  * If we were sending status back to the initiator, free up
1280                  * resources.  If we were doing a datamove, call the
1281                  * datamove done routine.
1282                  */
1283                 if ((io->io_hdr.flags & CTL_FLAG_DMA_INPROG) == 0) {
1284                         softc->ccbs_freed++;
1285                         xpt_release_ccb(done_ccb);
1286                         /*
1287                          * For a wildcard attachment, commands can come in
1288                          * with a specific target/lun.  Reset the target
1289                          * and LUN fields back to the wildcard values before
1290                          * we send them back down to the SIM.  The SIM has
1291                          * a wildcard LUN enabled, not whatever target/lun
1292                          * these happened to be.
1293                          */
1294                         if (softc->flags & CTLFE_LUN_WILDCARD) {
1295                                 atio->ccb_h.target_id = CAM_TARGET_WILDCARD;
1296                                 atio->ccb_h.target_lun = CAM_LUN_WILDCARD;
1297                         }
1298                         if (periph->flags & CAM_PERIPH_INVALID) {
1299                                 ctlfe_free_ccb(periph, (union ccb *)atio);
1300                         } else {
1301                                 mtx_unlock(mtx);
1302                                 xpt_action((union ccb *)atio);
1303                                 return;
1304                         }
1305                 } else {
1306                         struct ctlfe_cmd_info *cmd_info;
1307                         struct ccb_scsiio *csio;
1308
1309                         csio = &done_ccb->csio;
1310                         cmd_info = io->io_hdr.ctl_private[CTL_PRIV_FRONTEND2].ptr;
1311
1312                         io->io_hdr.flags &= ~CTL_FLAG_DMA_INPROG;
1313
1314                         io->scsiio.ext_data_len += csio->dxfer_len;
1315                         if (io->scsiio.ext_data_len >
1316                             io->scsiio.kern_total_len) {
1317                                 xpt_print(periph->path, "%s: tag 0x%04x "
1318                                           "done len %u > total %u sent %u\n",
1319                                           __func__, io->scsiio.tag_num,
1320                                           io->scsiio.ext_data_len,
1321                                           io->scsiio.kern_total_len,
1322                                           io->scsiio.ext_data_filled);
1323                         }
1324                         /*
1325                          * Translate CAM status to CTL status.  Success
1326                          * does not change the overall, ctl_io status.  In
1327                          * that case we just set port_status to 0.  If we
1328                          * have a failure, though, set a data phase error
1329                          * for the overall ctl_io.
1330                          */
1331                         switch (done_ccb->ccb_h.status & CAM_STATUS_MASK) {
1332                         case CAM_REQ_CMP:
1333                                 io->io_hdr.port_status = 0;
1334                                 break;
1335                         default:
1336                                 /*
1337                                  * XXX KDM we probably need to figure out a
1338                                  * standard set of errors that the SIM
1339                                  * drivers should return in the event of a
1340                                  * data transfer failure.  A data phase
1341                                  * error will at least point the user to a
1342                                  * data transfer error of some sort.
1343                                  * Hopefully the SIM printed out some
1344                                  * additional information to give the user
1345                                  * a clue what happened.
1346                                  */
1347                                 io->io_hdr.port_status = 0xbad1;
1348                                 ctl_set_data_phase_error(&io->scsiio);
1349                                 /*
1350                                  * XXX KDM figure out residual.
1351                                  */
1352                                 break;
1353                         }
1354                         /*
1355                          * If we had to break this S/G list into multiple
1356                          * pieces, figure out where we are in the list, and
1357                          * continue sending pieces if necessary.
1358                          */
1359                         if ((cmd_info->flags & CTLFE_CMD_PIECEWISE)
1360                          && (io->io_hdr.port_status == 0)) {
1361                                 ccb_flags flags;
1362                                 uint8_t scsi_status;
1363                                 uint8_t *data_ptr;
1364                                 uint32_t dxfer_len;
1365
1366                                 flags = atio->ccb_h.flags &
1367                                         (CAM_DIS_DISCONNECT|
1368                                          CAM_TAG_ACTION_VALID);
1369
1370                                 ctlfedata(softc, io, &flags, &data_ptr,
1371                                     &dxfer_len, &csio->sglist_cnt);
1372
1373                                 scsi_status = 0;
1374
1375                                 if (((flags & CAM_SEND_STATUS) == 0)
1376                                  && (dxfer_len == 0)) {
1377                                         printf("%s: tag %04x no status or "
1378                                                "len cdb = %02x\n", __func__,
1379                                                atio->tag_id,
1380                                         atio->cdb_io.cdb_bytes[0]);
1381                                         printf("%s: tag %04x io status %#x\n",
1382                                                __func__, atio->tag_id,
1383                                                io->io_hdr.status);
1384                                 }
1385
1386                                 cam_fill_ctio(csio,
1387                                               /*retries*/ 2,
1388                                               ctlfedone,
1389                                               flags,
1390                                               (flags & CAM_TAG_ACTION_VALID) ?
1391                                                MSG_SIMPLE_Q_TAG : 0,
1392                                               atio->tag_id,
1393                                               atio->init_id,
1394                                               scsi_status,
1395                                               /*data_ptr*/ data_ptr,
1396                                               /*dxfer_len*/ dxfer_len,
1397                                               /*timeout*/ 5 * 1000);
1398
1399                                 csio->ccb_h.flags |= CAM_UNLOCKED;
1400                                 csio->resid = 0;
1401                                 csio->ccb_h.ccb_atio = atio;
1402                                 io->io_hdr.flags |= CTL_FLAG_DMA_INPROG;
1403                                 softc->ctios_sent++;
1404                                 mtx_unlock(mtx);
1405                                 xpt_action((union ccb *)csio);
1406                         } else {
1407                                 /*
1408                                  * Release the CTIO.  The ATIO will be sent back
1409                                  * down to the SIM once we send status.
1410                                  */
1411                                 softc->ccbs_freed++;
1412                                 xpt_release_ccb(done_ccb);
1413                                 mtx_unlock(mtx);
1414
1415                                 /* Call the backend move done callback */
1416                                 io->scsiio.be_move_done(io);
1417                         }
1418                         return;
1419                 }
1420                 break;
1421         }
1422         case XPT_IMMEDIATE_NOTIFY: {
1423                 union ctl_io *io;
1424                 struct ccb_immediate_notify *inot;
1425                 cam_status status;
1426                 int send_ctl_io;
1427
1428                 inot = &done_ccb->cin1;
1429                 printf("%s: got XPT_IMMEDIATE_NOTIFY status %#x tag %#x "
1430                        "seq %#x\n", __func__, inot->ccb_h.status,
1431                        inot->tag_id, inot->seq_id);
1432
1433                 io = done_ccb->ccb_h.io_ptr;
1434                 ctl_zero_io(io);
1435
1436                 send_ctl_io = 1;
1437
1438                 io->io_hdr.io_type = CTL_IO_TASK;
1439                 io->io_hdr.ctl_private[CTL_PRIV_FRONTEND].ptr =done_ccb;
1440                 inot->ccb_h.io_ptr = io;
1441                 io->io_hdr.nexus.initid = inot->initiator_id;
1442                 io->io_hdr.nexus.targ_port = bus_softc->port.targ_port;
1443                 io->io_hdr.nexus.targ_lun = inot->ccb_h.target_lun;
1444                 /* XXX KDM should this be the tag_id? */
1445                 io->taskio.tag_num = inot->seq_id;
1446
1447                 status = inot->ccb_h.status & CAM_STATUS_MASK;
1448                 switch (status) {
1449                 case CAM_SCSI_BUS_RESET:
1450                         io->taskio.task_action = CTL_TASK_BUS_RESET;
1451                         break;
1452                 case CAM_BDR_SENT:
1453                         io->taskio.task_action = CTL_TASK_TARGET_RESET;
1454                         break;
1455                 case CAM_MESSAGE_RECV:
1456                         switch (inot->arg) {
1457                         case MSG_ABORT_TASK_SET:
1458                                 io->taskio.task_action =
1459                                     CTL_TASK_ABORT_TASK_SET;
1460                                 break;
1461                         case MSG_TARGET_RESET:
1462                                 io->taskio.task_action = CTL_TASK_TARGET_RESET;
1463                                 break;
1464                         case MSG_ABORT_TASK:
1465                                 io->taskio.task_action = CTL_TASK_ABORT_TASK;
1466                                 break;
1467                         case MSG_LOGICAL_UNIT_RESET:
1468                                 io->taskio.task_action = CTL_TASK_LUN_RESET;
1469                                 break;
1470                         case MSG_CLEAR_TASK_SET:
1471                                 io->taskio.task_action =
1472                                     CTL_TASK_CLEAR_TASK_SET;
1473                                 break;
1474                         case MSG_CLEAR_ACA:
1475                                 io->taskio.task_action = CTL_TASK_CLEAR_ACA;
1476                                 break;
1477                         case MSG_QUERY_TASK:
1478                                 io->taskio.task_action = CTL_TASK_QUERY_TASK;
1479                                 break;
1480                         case MSG_QUERY_TASK_SET:
1481                                 io->taskio.task_action =
1482                                     CTL_TASK_QUERY_TASK_SET;
1483                                 break;
1484                         case MSG_QUERY_ASYNC_EVENT:
1485                                 io->taskio.task_action =
1486                                     CTL_TASK_QUERY_ASYNC_EVENT;
1487                                 break;
1488                         case MSG_NOOP:
1489                                 send_ctl_io = 0;
1490                                 break;
1491                         default:
1492                                 xpt_print(periph->path,
1493                                           "%s: unsupported message 0x%x\n",
1494                                           __func__, inot->arg);
1495                                 send_ctl_io = 0;
1496                                 break;
1497                         }
1498                         break;
1499                 case CAM_REQ_ABORTED:
1500                         /*
1501                          * This request was sent back by the driver.
1502                          * XXX KDM what do we do here?
1503                          */
1504                         send_ctl_io = 0;
1505                         break;
1506                 case CAM_REQ_INVALID:
1507                 case CAM_PROVIDE_FAIL:
1508                 default:
1509                         /*
1510                          * We should only get here if we're talking
1511                          * to a talking to a SIM that is target
1512                          * capable but supports the old API.  In
1513                          * that case, we need to just free the CCB.
1514                          * If we actually send a notify acknowledge,
1515                          * it will send that back with an error as
1516                          * well.
1517                          */
1518
1519                         if ((status != CAM_REQ_INVALID)
1520                          && (status != CAM_PROVIDE_FAIL))
1521                                 xpt_print(periph->path,
1522                                           "%s: unsupported CAM status 0x%x\n",
1523                                           __func__, status);
1524
1525                         ctlfe_free_ccb(periph, done_ccb);
1526
1527                         goto out;
1528                 }
1529                 if (send_ctl_io != 0) {
1530                         ctl_queue(io);
1531                 } else {
1532                         done_ccb->ccb_h.status = CAM_REQ_INPROG;
1533                         done_ccb->ccb_h.func_code = XPT_NOTIFY_ACKNOWLEDGE;
1534                         xpt_action(done_ccb);
1535                 }
1536                 break;
1537         }
1538         case XPT_NOTIFY_ACKNOWLEDGE:
1539                 /*
1540                  * Queue this back down to the SIM as an immediate notify.
1541                  */
1542                 done_ccb->ccb_h.func_code = XPT_IMMEDIATE_NOTIFY;
1543                 xpt_action(done_ccb);
1544                 break;
1545         case XPT_SET_SIM_KNOB:
1546         case XPT_GET_SIM_KNOB:
1547                 break;
1548         default:
1549                 panic("%s: unexpected CCB type %#x", __func__,
1550                       done_ccb->ccb_h.func_code);
1551                 break;
1552         }
1553
1554 out:
1555         mtx_unlock(mtx);
1556 }
1557
1558 static void
1559 ctlfe_onoffline(void *arg, int online)
1560 {
1561         struct ctlfe_softc *bus_softc;
1562         union ccb *ccb;
1563         cam_status status;
1564         struct cam_path *path;
1565         int set_wwnn;
1566
1567         bus_softc = (struct ctlfe_softc *)arg;
1568
1569         set_wwnn = 0;
1570
1571         status = xpt_create_path(&path, /*periph*/ NULL, bus_softc->path_id,
1572                 CAM_TARGET_WILDCARD, CAM_LUN_WILDCARD);
1573         if (status != CAM_REQ_CMP) {
1574                 printf("%s: unable to create path!\n", __func__);
1575                 return;
1576         }
1577         ccb = xpt_alloc_ccb();
1578         xpt_setup_ccb(&ccb->ccb_h, path, CAM_PRIORITY_NONE);
1579         ccb->ccb_h.func_code = XPT_GET_SIM_KNOB;
1580         xpt_action(ccb);
1581
1582         /*
1583          * Copan WWN format:
1584          *
1585          * Bits 63-60:  0x5             NAA, IEEE registered name
1586          * Bits 59-36:  0x000ED5        IEEE Company name assigned to Copan
1587          * Bits 35-12:                  Copan SSN (Sequential Serial Number)
1588          * Bits 11-8:                   Type of port:
1589          *                                      1 == N-Port
1590          *                                      2 == F-Port
1591          *                                      3 == NL-Port
1592          * Bits 7-0:                    0 == Node Name, >0 == Port Number
1593          */
1594         if (online != 0) {
1595                 if ((ccb->knob.xport_specific.valid & KNOB_VALID_ADDRESS) != 0){
1596 #ifdef RANDOM_WWNN
1597                         uint64_t random_bits;
1598 #endif
1599
1600                         printf("%s: %s current WWNN %#jx\n", __func__,
1601                                bus_softc->port_name,
1602                                ccb->knob.xport_specific.fc.wwnn);
1603                         printf("%s: %s current WWPN %#jx\n", __func__,
1604                                bus_softc->port_name,
1605                                ccb->knob.xport_specific.fc.wwpn);
1606
1607 #ifdef RANDOM_WWNN
1608                         arc4rand(&random_bits, sizeof(random_bits), 0);
1609 #endif
1610
1611                         /*
1612                          * XXX KDM this is a bit of a kludge for now.  We
1613                          * take the current WWNN/WWPN from the card, and
1614                          * replace the company identifier and the NL-Port
1615                          * indicator and the port number (for the WWPN).
1616                          * This should be replaced later with ddb_GetWWNN,
1617                          * or possibly a more centralized scheme.  (It
1618                          * would be nice to have the WWNN/WWPN for each
1619                          * port stored in the ctl_port structure.)
1620                          */
1621 #ifdef RANDOM_WWNN
1622                         ccb->knob.xport_specific.fc.wwnn = 
1623                                 (random_bits &
1624                                 0x0000000fffffff00ULL) |
1625                                 /* Company ID */ 0x5000ED5000000000ULL |
1626                                 /* NL-Port */    0x0300;
1627                         ccb->knob.xport_specific.fc.wwpn = 
1628                                 (random_bits &
1629                                 0x0000000fffffff00ULL) |
1630                                 /* Company ID */ 0x5000ED5000000000ULL |
1631                                 /* NL-Port */    0x3000 |
1632                                 /* Port Num */ (bus_softc->port.targ_port & 0xff);
1633
1634                         /*
1635                          * This is a bit of an API break/reversal, but if
1636                          * we're doing the random WWNN that's a little
1637                          * different anyway.  So record what we're actually
1638                          * using with the frontend code so it's reported
1639                          * accurately.
1640                          */
1641                         ctl_port_set_wwns(&bus_softc->port,
1642                             true, ccb->knob.xport_specific.fc.wwnn,
1643                             true, ccb->knob.xport_specific.fc.wwpn);
1644                         set_wwnn = 1;
1645 #else /* RANDOM_WWNN */
1646                         /*
1647                          * If the user has specified a WWNN/WWPN, send them
1648                          * down to the SIM.  Otherwise, record what the SIM
1649                          * has reported.
1650                          */
1651                         if (bus_softc->port.wwnn != 0 && bus_softc->port.wwnn
1652                             != ccb->knob.xport_specific.fc.wwnn) {
1653                                 ccb->knob.xport_specific.fc.wwnn =
1654                                     bus_softc->port.wwnn;
1655                                 set_wwnn = 1;
1656                         } else {
1657                                 ctl_port_set_wwns(&bus_softc->port,
1658                                     true, ccb->knob.xport_specific.fc.wwnn,
1659                                     false, 0);
1660                         }
1661                         if (bus_softc->port.wwpn != 0 && bus_softc->port.wwpn
1662                              != ccb->knob.xport_specific.fc.wwpn) {
1663                                 ccb->knob.xport_specific.fc.wwpn =
1664                                     bus_softc->port.wwpn;
1665                                 set_wwnn = 1;
1666                         } else {
1667                                 ctl_port_set_wwns(&bus_softc->port,
1668                                     false, 0,
1669                                     true, ccb->knob.xport_specific.fc.wwpn);
1670                         }
1671 #endif /* RANDOM_WWNN */
1672
1673
1674                         if (set_wwnn != 0) {
1675                                 printf("%s: %s new WWNN %#jx\n", __func__,
1676                                        bus_softc->port_name,
1677                                 ccb->knob.xport_specific.fc.wwnn);
1678                                 printf("%s: %s new WWPN %#jx\n", __func__,
1679                                        bus_softc->port_name,
1680                                        ccb->knob.xport_specific.fc.wwpn);
1681                         }
1682                 } else {
1683                         printf("%s: %s has no valid WWNN/WWPN\n", __func__,
1684                                bus_softc->port_name);
1685                 }
1686         }
1687         ccb->ccb_h.func_code = XPT_SET_SIM_KNOB;
1688         ccb->knob.xport_specific.valid = KNOB_VALID_ROLE;
1689         if (set_wwnn != 0)
1690                 ccb->knob.xport_specific.valid |= KNOB_VALID_ADDRESS;
1691
1692         if (online != 0)
1693                 ccb->knob.xport_specific.fc.role |= KNOB_ROLE_TARGET;
1694         else
1695                 ccb->knob.xport_specific.fc.role &= ~KNOB_ROLE_TARGET;
1696
1697         xpt_action(ccb);
1698
1699         if ((ccb->ccb_h.status & CAM_STATUS_MASK) != CAM_REQ_CMP) {
1700                 printf("%s: SIM %s (path id %d) target %s failed with "
1701                        "status %#x\n",
1702                        __func__, bus_softc->port_name, bus_softc->path_id,
1703                        (online != 0) ? "enable" : "disable",
1704                        ccb->ccb_h.status);
1705         } else {
1706                 printf("%s: SIM %s (path id %d) target %s succeeded\n",
1707                        __func__, bus_softc->port_name, bus_softc->path_id,
1708                        (online != 0) ? "enable" : "disable");
1709         }
1710
1711         xpt_free_path(path);
1712         xpt_free_ccb(ccb);
1713 }
1714
1715 static void
1716 ctlfe_online(void *arg)
1717 {
1718         struct ctlfe_softc *bus_softc;
1719         struct cam_path *path;
1720         cam_status status;
1721         struct ctlfe_lun_softc *lun_softc;
1722         struct cam_periph *periph;
1723
1724         bus_softc = (struct ctlfe_softc *)arg;
1725
1726         /*
1727          * Create the wildcard LUN before bringing the port online.
1728          */
1729         status = xpt_create_path(&path, /*periph*/ NULL,
1730                                  bus_softc->path_id, CAM_TARGET_WILDCARD,
1731                                  CAM_LUN_WILDCARD);
1732         if (status != CAM_REQ_CMP) {
1733                 printf("%s: unable to create path for wildcard periph\n",
1734                                 __func__);
1735                 return;
1736         }
1737
1738         lun_softc = malloc(sizeof(*lun_softc), M_CTLFE, M_WAITOK | M_ZERO);
1739
1740         xpt_path_lock(path);
1741         periph = cam_periph_find(path, "ctl");
1742         if (periph != NULL) {
1743                 /* We've already got a periph, no need to alloc a new one. */
1744                 xpt_path_unlock(path);
1745                 xpt_free_path(path);
1746                 free(lun_softc, M_CTLFE);
1747                 return;
1748         }
1749         lun_softc->parent_softc = bus_softc;
1750         lun_softc->flags |= CTLFE_LUN_WILDCARD;
1751
1752         status = cam_periph_alloc(ctlferegister,
1753                                   ctlfeoninvalidate,
1754                                   ctlfecleanup,
1755                                   ctlfestart,
1756                                   "ctl",
1757                                   CAM_PERIPH_BIO,
1758                                   path,
1759                                   ctlfeasync,
1760                                   0,
1761                                   lun_softc);
1762
1763         if ((status & CAM_STATUS_MASK) != CAM_REQ_CMP) {
1764                 const struct cam_status_entry *entry;
1765
1766                 entry = cam_fetch_status_entry(status);
1767                 printf("%s: CAM error %s (%#x) returned from "
1768                        "cam_periph_alloc()\n", __func__, (entry != NULL) ?
1769                        entry->status_text : "Unknown", status);
1770                 free(lun_softc, M_CTLFE);
1771         }
1772
1773         xpt_path_unlock(path);
1774         ctlfe_onoffline(arg, /*online*/ 1);
1775         xpt_free_path(path);
1776 }
1777
1778 static void
1779 ctlfe_offline(void *arg)
1780 {
1781         struct ctlfe_softc *bus_softc;
1782         struct cam_path *path;
1783         cam_status status;
1784         struct cam_periph *periph;
1785
1786         bus_softc = (struct ctlfe_softc *)arg;
1787
1788         ctlfe_onoffline(arg, /*online*/ 0);
1789
1790         /*
1791          * Disable the wildcard LUN for this port now that we have taken
1792          * the port offline.
1793          */
1794         status = xpt_create_path(&path, /*periph*/ NULL,
1795                                  bus_softc->path_id, CAM_TARGET_WILDCARD,
1796                                  CAM_LUN_WILDCARD);
1797         if (status != CAM_REQ_CMP) {
1798                 printf("%s: unable to create path for wildcard periph\n",
1799                        __func__);
1800                 return;
1801         }
1802         xpt_path_lock(path);
1803         if ((periph = cam_periph_find(path, "ctl")) != NULL)
1804                 cam_periph_invalidate(periph);
1805         xpt_path_unlock(path);
1806         xpt_free_path(path);
1807 }
1808
1809 /*
1810  * This will get called to enable a LUN on every bus that is attached to
1811  * CTL.  So we only need to create a path/periph for this particular bus.
1812  */
1813 static int
1814 ctlfe_lun_enable(void *arg, int lun_id)
1815 {
1816         struct ctlfe_softc *bus_softc;
1817         struct ctlfe_lun_softc *softc;
1818         struct cam_path *path;
1819         struct cam_periph *periph;
1820         cam_status status;
1821
1822         bus_softc = (struct ctlfe_softc *)arg;
1823
1824         status = xpt_create_path(&path, /*periph*/ NULL,
1825                                   bus_softc->path_id, bus_softc->target_id, lun_id);
1826         /* XXX KDM need some way to return status to CTL here? */
1827         if (status != CAM_REQ_CMP) {
1828                 printf("%s: could not create path, status %#x\n", __func__,
1829                        status);
1830                 return (1);
1831         }
1832
1833         softc = malloc(sizeof(*softc), M_CTLFE, M_WAITOK | M_ZERO);
1834         xpt_path_lock(path);
1835         periph = cam_periph_find(path, "ctl");
1836         if (periph != NULL) {
1837                 /* We've already got a periph, no need to alloc a new one. */
1838                 xpt_path_unlock(path);
1839                 xpt_free_path(path);
1840                 free(softc, M_CTLFE);
1841                 return (0);
1842         }
1843         softc->parent_softc = bus_softc;
1844
1845         status = cam_periph_alloc(ctlferegister,
1846                                   ctlfeoninvalidate,
1847                                   ctlfecleanup,
1848                                   ctlfestart,
1849                                   "ctl",
1850                                   CAM_PERIPH_BIO,
1851                                   path,
1852                                   ctlfeasync,
1853                                   0,
1854                                   softc);
1855
1856         if ((status & CAM_STATUS_MASK) != CAM_REQ_CMP) {
1857                 const struct cam_status_entry *entry;
1858
1859                 entry = cam_fetch_status_entry(status);
1860                 printf("%s: CAM error %s (%#x) returned from "
1861                        "cam_periph_alloc()\n", __func__, (entry != NULL) ?
1862                        entry->status_text : "Unknown", status);
1863                 free(softc, M_CTLFE);
1864         }
1865
1866         xpt_path_unlock(path);
1867         xpt_free_path(path);
1868         return (0);
1869 }
1870
1871 /*
1872  * This will get called when the user removes a LUN to disable that LUN
1873  * on every bus that is attached to CTL.  
1874  */
1875 static int
1876 ctlfe_lun_disable(void *arg, int lun_id)
1877 {
1878         struct ctlfe_softc *softc;
1879         struct ctlfe_lun_softc *lun_softc;
1880
1881         softc = (struct ctlfe_softc *)arg;
1882
1883         mtx_lock(&softc->lun_softc_mtx);
1884         STAILQ_FOREACH(lun_softc, &softc->lun_softc_list, links) {
1885                 struct cam_path *path;
1886
1887                 path = lun_softc->periph->path;
1888
1889                 if ((xpt_path_target_id(path) == softc->target_id)
1890                  && (xpt_path_lun_id(path) == lun_id)) {
1891                         break;
1892                 }
1893         }
1894         if (lun_softc == NULL) {
1895                 mtx_unlock(&softc->lun_softc_mtx);
1896                 printf("%s: can't find lun %d\n", __func__, lun_id);
1897                 return (1);
1898         }
1899         cam_periph_acquire(lun_softc->periph);
1900         mtx_unlock(&softc->lun_softc_mtx);
1901
1902         cam_periph_lock(lun_softc->periph);
1903         cam_periph_invalidate(lun_softc->periph);
1904         cam_periph_unlock(lun_softc->periph);
1905         cam_periph_release(lun_softc->periph);
1906         return (0);
1907 }
1908
1909 static void
1910 ctlfe_dump_sim(struct cam_sim *sim)
1911 {
1912
1913         printf("%s%d: max tagged openings: %d, max dev openings: %d\n",
1914                sim->sim_name, sim->unit_number,
1915                sim->max_tagged_dev_openings, sim->max_dev_openings);
1916 }
1917
1918 /*
1919  * Assumes that the SIM lock is held.
1920  */
1921 static void
1922 ctlfe_dump_queue(struct ctlfe_lun_softc *softc)
1923 {
1924         struct ccb_hdr *hdr;
1925         struct cam_periph *periph;
1926         int num_items;
1927
1928         periph = softc->periph;
1929         num_items = 0;
1930
1931         TAILQ_FOREACH(hdr, &softc->work_queue, periph_links.tqe) {
1932                 union ctl_io *io = hdr->io_ptr;
1933
1934                 num_items++;
1935
1936                 /*
1937                  * Only regular SCSI I/O is put on the work
1938                  * queue, so we can print sense here.  There may be no
1939                  * sense if it's no the queue for a DMA, but this serves to
1940                  * print out the CCB as well.
1941                  *
1942                  * XXX KDM switch this over to scsi_sense_print() when
1943                  * CTL is merged in with CAM.
1944                  */
1945                 ctl_io_error_print(io, NULL);
1946
1947                 /*
1948                  * Print DMA status if we are DMA_QUEUED.
1949                  */
1950                 if (io->io_hdr.flags & CTL_FLAG_DMA_QUEUED) {
1951                         xpt_print(periph->path,
1952                             "Total %u, Current %u, Resid %u\n",
1953                             io->scsiio.kern_total_len,
1954                             io->scsiio.kern_data_len,
1955                             io->scsiio.kern_data_resid);
1956                 }
1957         }
1958
1959         xpt_print(periph->path, "%d requests total waiting for CCBs\n",
1960                   num_items);
1961         xpt_print(periph->path, "%ju CCBs outstanding (%ju allocated, %ju "
1962                   "freed)\n", (uintmax_t)(softc->ccbs_alloced -
1963                   softc->ccbs_freed), (uintmax_t)softc->ccbs_alloced,
1964                   (uintmax_t)softc->ccbs_freed);
1965         xpt_print(periph->path, "%ju CTIOs outstanding (%ju sent, %ju "
1966                   "returned\n", (uintmax_t)(softc->ctios_sent -
1967                   softc->ctios_returned), softc->ctios_sent,
1968                   softc->ctios_returned);
1969 }
1970
1971 /*
1972  * Datamove/done routine called by CTL.  Put ourselves on the queue to
1973  * receive a CCB from CAM so we can queue the continue I/O request down
1974  * to the adapter.
1975  */
1976 static void
1977 ctlfe_datamove(union ctl_io *io)
1978 {
1979         union ccb *ccb;
1980         struct cam_periph *periph;
1981         struct ctlfe_lun_softc *softc;
1982
1983         KASSERT(io->io_hdr.io_type == CTL_IO_SCSI,
1984             ("Unexpected io_type (%d) in ctlfe_datamove", io->io_hdr.io_type));
1985
1986         ccb = io->io_hdr.ctl_private[CTL_PRIV_FRONTEND].ptr;
1987         periph = xpt_path_periph(ccb->ccb_h.path);
1988         cam_periph_lock(periph);
1989         softc = (struct ctlfe_lun_softc *)periph->softc;
1990         io->io_hdr.flags |= CTL_FLAG_DMA_QUEUED;
1991         if ((io->io_hdr.status & CTL_STATUS_MASK) != CTL_STATUS_NONE)
1992                 io->io_hdr.flags |= CTL_FLAG_STATUS_QUEUED;
1993         TAILQ_INSERT_TAIL(&softc->work_queue, &ccb->ccb_h,
1994                           periph_links.tqe);
1995         xpt_schedule(periph, /*priority*/ 1);
1996         cam_periph_unlock(periph);
1997 }
1998
1999 static void
2000 ctlfe_done(union ctl_io *io)
2001 {
2002         union ccb *ccb;
2003         struct cam_periph *periph;
2004         struct ctlfe_lun_softc *softc;
2005
2006         ccb = io->io_hdr.ctl_private[CTL_PRIV_FRONTEND].ptr;
2007         periph = xpt_path_periph(ccb->ccb_h.path);
2008         cam_periph_lock(periph);
2009         softc = (struct ctlfe_lun_softc *)periph->softc;
2010
2011         if (io->io_hdr.io_type == CTL_IO_TASK) {
2012                 /*
2013                  * Task management commands don't require any further
2014                  * communication back to the adapter.  Requeue the CCB
2015                  * to the adapter, and free the CTL I/O.
2016                  */
2017                 xpt_print(ccb->ccb_h.path, "%s: returning task I/O "
2018                           "tag %#x seq %#x\n", __func__,
2019                           ccb->cin1.tag_id, ccb->cin1.seq_id);
2020                 /*
2021                  * Send the notify acknowledge down to the SIM, to let it
2022                  * know we processed the task management command.
2023                  */
2024                 ccb->ccb_h.status = CAM_REQ_INPROG;
2025                 ccb->ccb_h.func_code = XPT_NOTIFY_ACKNOWLEDGE;
2026                 xpt_action(ccb);
2027         } else if (io->io_hdr.flags & CTL_FLAG_STATUS_SENT) {
2028                 if (softc->flags & CTLFE_LUN_WILDCARD) {
2029                         ccb->ccb_h.target_id = CAM_TARGET_WILDCARD;
2030                         ccb->ccb_h.target_lun = CAM_LUN_WILDCARD;
2031                 }
2032                 if (periph->flags & CAM_PERIPH_INVALID) {
2033                         ctlfe_free_ccb(periph, ccb);
2034                 } else {
2035                         cam_periph_unlock(periph);
2036                         xpt_action(ccb);
2037                         return;
2038                 }
2039         } else {
2040                 io->io_hdr.flags |= CTL_FLAG_STATUS_QUEUED;
2041                 TAILQ_INSERT_TAIL(&softc->work_queue, &ccb->ccb_h,
2042                                   periph_links.tqe);
2043                 xpt_schedule(periph, /*priority*/ 1);
2044         }
2045
2046         cam_periph_unlock(periph);
2047 }
2048
2049 static void
2050 ctlfe_dump(void)
2051 {
2052         struct ctlfe_softc *bus_softc;
2053         struct ctlfe_lun_softc *lun_softc;
2054
2055         STAILQ_FOREACH(bus_softc, &ctlfe_softc_list, links) {
2056                 ctlfe_dump_sim(bus_softc->sim);
2057                 STAILQ_FOREACH(lun_softc, &bus_softc->lun_softc_list, links)
2058                         ctlfe_dump_queue(lun_softc);
2059         }
2060 }