]> CyberLeo.Net >> Repos - FreeBSD/stable/10.git/blob - sys/cam/ctl/scsi_ctl.c
MFC r287621: Reimplement CTL High Availability.
[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         case WRITE_ATOMIC_16:
1072         {
1073                 struct scsi_rw_16 *cdb = (struct scsi_rw_16 *)cmdbyt;
1074                 lba = scsi_8btou64(cdb->addr);
1075                 num_blocks = scsi_4btoul(cdb->length);
1076                 lba += nbc;
1077                 num_blocks -= nbc;
1078                 scsi_u64to8b(lba, cdb->addr);
1079                 scsi_ulto4b(num_blocks, cdb->length);
1080                 break;
1081         }
1082         default:
1083                 return -1;
1084         }
1085         return (0);
1086 }
1087
1088 static void
1089 ctlfedone(struct cam_periph *periph, union ccb *done_ccb)
1090 {
1091         struct ctlfe_lun_softc *softc;
1092         struct ctlfe_softc *bus_softc;
1093         struct ctlfe_cmd_info *cmd_info;
1094         struct ccb_accept_tio *atio = NULL;
1095         union ctl_io *io = NULL;
1096         struct mtx *mtx;
1097
1098         KASSERT((done_ccb->ccb_h.flags & CAM_UNLOCKED) != 0,
1099             ("CCB in ctlfedone() without CAM_UNLOCKED flag"));
1100 #ifdef CTLFE_DEBUG
1101         printf("%s: entered, func_code = %#x\n", __func__,
1102                done_ccb->ccb_h.func_code);
1103 #endif
1104
1105         /*
1106          * At this point CTL has no known use case for device queue freezes.
1107          * In case some SIM think different -- drop its freeze right here.
1108          */
1109         if ((done_ccb->ccb_h.status & CAM_DEV_QFRZN) != 0) {
1110                 cam_release_devq(periph->path,
1111                                  /*relsim_flags*/0,
1112                                  /*reduction*/0,
1113                                  /*timeout*/0,
1114                                  /*getcount_only*/0);
1115                 done_ccb->ccb_h.status &= ~CAM_DEV_QFRZN;
1116         }
1117
1118         softc = (struct ctlfe_lun_softc *)periph->softc;
1119         bus_softc = softc->parent_softc;
1120         mtx = cam_periph_mtx(periph);
1121         mtx_lock(mtx);
1122
1123         /*
1124          * If the peripheral is invalid, ATIOs and immediate notify CCBs
1125          * need to be freed.  Most of the ATIOs and INOTs that come back
1126          * will be CCBs that are being returned from the SIM as a result of
1127          * our disabling the LUN.
1128          *
1129          * Other CCB types are handled in their respective cases below.
1130          */
1131         if (periph->flags & CAM_PERIPH_INVALID) {
1132                 switch (done_ccb->ccb_h.func_code) {
1133                 case XPT_ACCEPT_TARGET_IO:
1134                 case XPT_IMMEDIATE_NOTIFY:
1135                 case XPT_NOTIFY_ACKNOWLEDGE:
1136                         ctlfe_free_ccb(periph, done_ccb);
1137                         goto out;
1138                 default:
1139                         break;
1140                 }
1141
1142         }
1143         switch (done_ccb->ccb_h.func_code) {
1144         case XPT_ACCEPT_TARGET_IO: {
1145
1146                 atio = &done_ccb->atio;
1147
1148  resubmit:
1149                 /*
1150                  * Allocate a ctl_io, pass it to CTL, and wait for the
1151                  * datamove or done.
1152                  */
1153                 mtx_unlock(mtx);
1154                 io = done_ccb->ccb_h.io_ptr;
1155                 cmd_info = io->io_hdr.ctl_private[CTL_PRIV_FRONTEND2].ptr;
1156                 ctl_zero_io(io);
1157
1158                 /* Save pointers on both sides */
1159                 io->io_hdr.ctl_private[CTL_PRIV_FRONTEND].ptr = done_ccb;
1160                 io->io_hdr.ctl_private[CTL_PRIV_FRONTEND2].ptr = cmd_info;
1161                 done_ccb->ccb_h.io_ptr = io;
1162
1163                 /*
1164                  * Only SCSI I/O comes down this path, resets, etc. come
1165                  * down the immediate notify path below.
1166                  */
1167                 io->io_hdr.io_type = CTL_IO_SCSI;
1168                 io->io_hdr.nexus.initid = atio->init_id;
1169                 io->io_hdr.nexus.targ_port = bus_softc->port.targ_port;
1170                 io->io_hdr.nexus.targ_lun = atio->ccb_h.target_lun;
1171                 io->scsiio.tag_num = atio->tag_id;
1172                 switch (atio->tag_action) {
1173                 case CAM_TAG_ACTION_NONE:
1174                         io->scsiio.tag_type = CTL_TAG_UNTAGGED;
1175                         break;
1176                 case MSG_SIMPLE_TASK:
1177                         io->scsiio.tag_type = CTL_TAG_SIMPLE;
1178                         break;
1179                 case MSG_HEAD_OF_QUEUE_TASK:
1180                         io->scsiio.tag_type = CTL_TAG_HEAD_OF_QUEUE;
1181                         break;
1182                 case MSG_ORDERED_TASK:
1183                         io->scsiio.tag_type = CTL_TAG_ORDERED;
1184                         break;
1185                 case MSG_ACA_TASK:
1186                         io->scsiio.tag_type = CTL_TAG_ACA;
1187                         break;
1188                 default:
1189                         io->scsiio.tag_type = CTL_TAG_UNTAGGED;
1190                         printf("%s: unhandled tag type %#x!!\n", __func__,
1191                                atio->tag_action);
1192                         break;
1193                 }
1194                 if (atio->cdb_len > sizeof(io->scsiio.cdb)) {
1195                         printf("%s: WARNING: CDB len %d > ctl_io space %zd\n",
1196                                __func__, atio->cdb_len, sizeof(io->scsiio.cdb));
1197                 }
1198                 io->scsiio.cdb_len = min(atio->cdb_len, sizeof(io->scsiio.cdb));
1199                 bcopy(atio->cdb_io.cdb_bytes, io->scsiio.cdb,
1200                       io->scsiio.cdb_len);
1201
1202 #ifdef CTLFEDEBUG
1203                 printf("%s: %u:%u:%u: tag %04x CDB %02x\n", __func__,
1204                         io->io_hdr.nexus.initid,
1205                         io->io_hdr.nexus.targ_port,
1206                         io->io_hdr.nexus.targ_lun,
1207                         io->scsiio.tag_num, io->scsiio.cdb[0]);
1208 #endif
1209
1210                 ctl_queue(io);
1211                 return;
1212         }
1213         case XPT_CONT_TARGET_IO: {
1214                 int srr = 0;
1215                 uint32_t srr_off = 0;
1216
1217                 atio = (struct ccb_accept_tio *)done_ccb->ccb_h.ccb_atio;
1218                 io = (union ctl_io *)atio->ccb_h.io_ptr;
1219
1220                 softc->ctios_returned++;
1221 #ifdef CTLFEDEBUG
1222                 printf("%s: got XPT_CONT_TARGET_IO tag %#x flags %#x\n",
1223                        __func__, atio->tag_id, done_ccb->ccb_h.flags);
1224 #endif
1225                 /*
1226                  * Handle SRR case were the data pointer is pushed back hack
1227                  */
1228                 if ((done_ccb->ccb_h.status & CAM_STATUS_MASK) == CAM_MESSAGE_RECV
1229                     && done_ccb->csio.msg_ptr != NULL
1230                     && done_ccb->csio.msg_ptr[0] == MSG_EXTENDED
1231                     && done_ccb->csio.msg_ptr[1] == 5
1232                     && done_ccb->csio.msg_ptr[2] == 0) {
1233                         srr = 1;
1234                         srr_off =
1235                             (done_ccb->csio.msg_ptr[3] << 24)
1236                             | (done_ccb->csio.msg_ptr[4] << 16)
1237                             | (done_ccb->csio.msg_ptr[5] << 8)
1238                             | (done_ccb->csio.msg_ptr[6]);
1239                 }
1240
1241                 if (srr && (io->io_hdr.flags & CTL_FLAG_DMA_INPROG) == 0) {
1242                         /*
1243                          * If status was being sent, the back end data is now
1244                          * history. Hack it up and resubmit a new command with
1245                          * the CDB adjusted. If the SIM does the right thing,
1246                          * all of the resid math should work.
1247                          */
1248                         softc->ccbs_freed++;
1249                         xpt_release_ccb(done_ccb);
1250                         if (ctlfe_adjust_cdb(atio, srr_off) == 0) {
1251                                 done_ccb = (union ccb *)atio;
1252                                 goto resubmit;
1253                         }
1254                         /*
1255                          * Fall through to doom....
1256                          */
1257                 } else if (srr) {
1258                         /*
1259                          * If we have an srr and we're still sending data, we
1260                          * should be able to adjust offsets and cycle again.
1261                          */
1262                         io->scsiio.kern_rel_offset =
1263                             io->scsiio.ext_data_filled = srr_off;
1264                         io->scsiio.ext_data_len = io->scsiio.kern_total_len -
1265                             io->scsiio.kern_rel_offset;
1266                         softc->ccbs_freed++;
1267                         io->scsiio.io_hdr.status = CTL_STATUS_NONE;
1268                         xpt_release_ccb(done_ccb);
1269                         TAILQ_INSERT_HEAD(&softc->work_queue, &atio->ccb_h,
1270                                           periph_links.tqe);
1271                         xpt_schedule(periph, /*priority*/ 1);
1272                         break;
1273                 }
1274
1275                 if ((done_ccb->ccb_h.flags & CAM_SEND_STATUS) &&
1276                     (done_ccb->ccb_h.status & CAM_STATUS_MASK) == CAM_REQ_CMP)
1277                         io->io_hdr.flags |= CTL_FLAG_STATUS_SENT;
1278
1279                 /*
1280                  * If we were sending status back to the initiator, free up
1281                  * resources.  If we were doing a datamove, call the
1282                  * datamove done routine.
1283                  */
1284                 if ((io->io_hdr.flags & CTL_FLAG_DMA_INPROG) == 0) {
1285                         softc->ccbs_freed++;
1286                         xpt_release_ccb(done_ccb);
1287                         /*
1288                          * For a wildcard attachment, commands can come in
1289                          * with a specific target/lun.  Reset the target
1290                          * and LUN fields back to the wildcard values before
1291                          * we send them back down to the SIM.  The SIM has
1292                          * a wildcard LUN enabled, not whatever target/lun
1293                          * these happened to be.
1294                          */
1295                         if (softc->flags & CTLFE_LUN_WILDCARD) {
1296                                 atio->ccb_h.target_id = CAM_TARGET_WILDCARD;
1297                                 atio->ccb_h.target_lun = CAM_LUN_WILDCARD;
1298                         }
1299                         if (periph->flags & CAM_PERIPH_INVALID) {
1300                                 ctlfe_free_ccb(periph, (union ccb *)atio);
1301                         } else {
1302                                 mtx_unlock(mtx);
1303                                 xpt_action((union ccb *)atio);
1304                                 return;
1305                         }
1306                 } else {
1307                         struct ctlfe_cmd_info *cmd_info;
1308                         struct ccb_scsiio *csio;
1309
1310                         csio = &done_ccb->csio;
1311                         cmd_info = io->io_hdr.ctl_private[CTL_PRIV_FRONTEND2].ptr;
1312
1313                         io->io_hdr.flags &= ~CTL_FLAG_DMA_INPROG;
1314
1315                         io->scsiio.ext_data_len += csio->dxfer_len;
1316                         if (io->scsiio.ext_data_len >
1317                             io->scsiio.kern_total_len) {
1318                                 xpt_print(periph->path, "%s: tag 0x%04x "
1319                                           "done len %u > total %u sent %u\n",
1320                                           __func__, io->scsiio.tag_num,
1321                                           io->scsiio.ext_data_len,
1322                                           io->scsiio.kern_total_len,
1323                                           io->scsiio.ext_data_filled);
1324                         }
1325                         /*
1326                          * Translate CAM status to CTL status.  Success
1327                          * does not change the overall, ctl_io status.  In
1328                          * that case we just set port_status to 0.  If we
1329                          * have a failure, though, set a data phase error
1330                          * for the overall ctl_io.
1331                          */
1332                         switch (done_ccb->ccb_h.status & CAM_STATUS_MASK) {
1333                         case CAM_REQ_CMP:
1334                                 io->io_hdr.port_status = 0;
1335                                 break;
1336                         default:
1337                                 /*
1338                                  * XXX KDM we probably need to figure out a
1339                                  * standard set of errors that the SIM
1340                                  * drivers should return in the event of a
1341                                  * data transfer failure.  A data phase
1342                                  * error will at least point the user to a
1343                                  * data transfer error of some sort.
1344                                  * Hopefully the SIM printed out some
1345                                  * additional information to give the user
1346                                  * a clue what happened.
1347                                  */
1348                                 io->io_hdr.port_status = 0xbad1;
1349                                 ctl_set_data_phase_error(&io->scsiio);
1350                                 /*
1351                                  * XXX KDM figure out residual.
1352                                  */
1353                                 break;
1354                         }
1355                         /*
1356                          * If we had to break this S/G list into multiple
1357                          * pieces, figure out where we are in the list, and
1358                          * continue sending pieces if necessary.
1359                          */
1360                         if ((cmd_info->flags & CTLFE_CMD_PIECEWISE)
1361                          && (io->io_hdr.port_status == 0)) {
1362                                 ccb_flags flags;
1363                                 uint8_t scsi_status;
1364                                 uint8_t *data_ptr;
1365                                 uint32_t dxfer_len;
1366
1367                                 flags = atio->ccb_h.flags &
1368                                         (CAM_DIS_DISCONNECT|
1369                                          CAM_TAG_ACTION_VALID);
1370
1371                                 ctlfedata(softc, io, &flags, &data_ptr,
1372                                     &dxfer_len, &csio->sglist_cnt);
1373
1374                                 scsi_status = 0;
1375
1376                                 if (((flags & CAM_SEND_STATUS) == 0)
1377                                  && (dxfer_len == 0)) {
1378                                         printf("%s: tag %04x no status or "
1379                                                "len cdb = %02x\n", __func__,
1380                                                atio->tag_id,
1381                                         atio->cdb_io.cdb_bytes[0]);
1382                                         printf("%s: tag %04x io status %#x\n",
1383                                                __func__, atio->tag_id,
1384                                                io->io_hdr.status);
1385                                 }
1386
1387                                 cam_fill_ctio(csio,
1388                                               /*retries*/ 2,
1389                                               ctlfedone,
1390                                               flags,
1391                                               (flags & CAM_TAG_ACTION_VALID) ?
1392                                                MSG_SIMPLE_Q_TAG : 0,
1393                                               atio->tag_id,
1394                                               atio->init_id,
1395                                               scsi_status,
1396                                               /*data_ptr*/ data_ptr,
1397                                               /*dxfer_len*/ dxfer_len,
1398                                               /*timeout*/ 5 * 1000);
1399
1400                                 csio->ccb_h.flags |= CAM_UNLOCKED;
1401                                 csio->resid = 0;
1402                                 csio->ccb_h.ccb_atio = atio;
1403                                 io->io_hdr.flags |= CTL_FLAG_DMA_INPROG;
1404                                 softc->ctios_sent++;
1405                                 mtx_unlock(mtx);
1406                                 xpt_action((union ccb *)csio);
1407                         } else {
1408                                 /*
1409                                  * Release the CTIO.  The ATIO will be sent back
1410                                  * down to the SIM once we send status.
1411                                  */
1412                                 softc->ccbs_freed++;
1413                                 xpt_release_ccb(done_ccb);
1414                                 mtx_unlock(mtx);
1415
1416                                 /* Call the backend move done callback */
1417                                 io->scsiio.be_move_done(io);
1418                         }
1419                         return;
1420                 }
1421                 break;
1422         }
1423         case XPT_IMMEDIATE_NOTIFY: {
1424                 union ctl_io *io;
1425                 struct ccb_immediate_notify *inot;
1426                 cam_status status;
1427                 int send_ctl_io;
1428
1429                 inot = &done_ccb->cin1;
1430                 printf("%s: got XPT_IMMEDIATE_NOTIFY status %#x tag %#x "
1431                        "seq %#x\n", __func__, inot->ccb_h.status,
1432                        inot->tag_id, inot->seq_id);
1433
1434                 io = done_ccb->ccb_h.io_ptr;
1435                 ctl_zero_io(io);
1436
1437                 send_ctl_io = 1;
1438
1439                 io->io_hdr.io_type = CTL_IO_TASK;
1440                 io->io_hdr.ctl_private[CTL_PRIV_FRONTEND].ptr =done_ccb;
1441                 inot->ccb_h.io_ptr = io;
1442                 io->io_hdr.nexus.initid = inot->initiator_id;
1443                 io->io_hdr.nexus.targ_port = bus_softc->port.targ_port;
1444                 io->io_hdr.nexus.targ_lun = inot->ccb_h.target_lun;
1445                 /* XXX KDM should this be the tag_id? */
1446                 io->taskio.tag_num = inot->seq_id;
1447
1448                 status = inot->ccb_h.status & CAM_STATUS_MASK;
1449                 switch (status) {
1450                 case CAM_SCSI_BUS_RESET:
1451                         io->taskio.task_action = CTL_TASK_BUS_RESET;
1452                         break;
1453                 case CAM_BDR_SENT:
1454                         io->taskio.task_action = CTL_TASK_TARGET_RESET;
1455                         break;
1456                 case CAM_MESSAGE_RECV:
1457                         switch (inot->arg) {
1458                         case MSG_ABORT_TASK_SET:
1459                                 io->taskio.task_action =
1460                                     CTL_TASK_ABORT_TASK_SET;
1461                                 break;
1462                         case MSG_TARGET_RESET:
1463                                 io->taskio.task_action =
1464                                         CTL_TASK_TARGET_RESET;
1465                                 break;
1466                         case MSG_ABORT_TASK:
1467                                 io->taskio.task_action =
1468                                         CTL_TASK_ABORT_TASK;
1469                                 break;
1470                         case MSG_LOGICAL_UNIT_RESET:
1471                                 io->taskio.task_action =
1472                                         CTL_TASK_LUN_RESET;
1473                                 break;
1474                         case MSG_CLEAR_TASK_SET:
1475                                 io->taskio.task_action =
1476                                         CTL_TASK_CLEAR_TASK_SET;
1477                                 break;
1478                         case MSG_CLEAR_ACA:
1479                                 io->taskio.task_action =
1480                                         CTL_TASK_CLEAR_ACA;
1481                                 break;
1482                         case MSG_NOOP:
1483                                 send_ctl_io = 0;
1484                                 break;
1485                         default:
1486                                 xpt_print(periph->path,
1487                                           "%s: unsupported message 0x%x\n",
1488                                           __func__, inot->arg);
1489                                 send_ctl_io = 0;
1490                                 break;
1491                         }
1492                         break;
1493                 case CAM_REQ_ABORTED:
1494                         /*
1495                          * This request was sent back by the driver.
1496                          * XXX KDM what do we do here?
1497                          */
1498                         send_ctl_io = 0;
1499                         break;
1500                 case CAM_REQ_INVALID:
1501                 case CAM_PROVIDE_FAIL:
1502                 default:
1503                         /*
1504                          * We should only get here if we're talking
1505                          * to a talking to a SIM that is target
1506                          * capable but supports the old API.  In
1507                          * that case, we need to just free the CCB.
1508                          * If we actually send a notify acknowledge,
1509                          * it will send that back with an error as
1510                          * well.
1511                          */
1512
1513                         if ((status != CAM_REQ_INVALID)
1514                          && (status != CAM_PROVIDE_FAIL))
1515                                 xpt_print(periph->path,
1516                                           "%s: unsupported CAM status 0x%x\n",
1517                                           __func__, status);
1518
1519                         ctlfe_free_ccb(periph, done_ccb);
1520
1521                         goto out;
1522                 }
1523                 if (send_ctl_io != 0) {
1524                         ctl_queue(io);
1525                 } else {
1526                         done_ccb->ccb_h.status = CAM_REQ_INPROG;
1527                         done_ccb->ccb_h.func_code = XPT_NOTIFY_ACKNOWLEDGE;
1528                         xpt_action(done_ccb);
1529                 }
1530                 break;
1531         }
1532         case XPT_NOTIFY_ACKNOWLEDGE:
1533                 /*
1534                  * Queue this back down to the SIM as an immediate notify.
1535                  */
1536                 done_ccb->ccb_h.func_code = XPT_IMMEDIATE_NOTIFY;
1537                 xpt_action(done_ccb);
1538                 break;
1539         case XPT_SET_SIM_KNOB:
1540         case XPT_GET_SIM_KNOB:
1541                 break;
1542         default:
1543                 panic("%s: unexpected CCB type %#x", __func__,
1544                       done_ccb->ccb_h.func_code);
1545                 break;
1546         }
1547
1548 out:
1549         mtx_unlock(mtx);
1550 }
1551
1552 static void
1553 ctlfe_onoffline(void *arg, int online)
1554 {
1555         struct ctlfe_softc *bus_softc;
1556         union ccb *ccb;
1557         cam_status status;
1558         struct cam_path *path;
1559         int set_wwnn;
1560
1561         bus_softc = (struct ctlfe_softc *)arg;
1562
1563         set_wwnn = 0;
1564
1565         status = xpt_create_path(&path, /*periph*/ NULL, bus_softc->path_id,
1566                 CAM_TARGET_WILDCARD, CAM_LUN_WILDCARD);
1567         if (status != CAM_REQ_CMP) {
1568                 printf("%s: unable to create path!\n", __func__);
1569                 return;
1570         }
1571         ccb = xpt_alloc_ccb();
1572         xpt_setup_ccb(&ccb->ccb_h, path, CAM_PRIORITY_NONE);
1573         ccb->ccb_h.func_code = XPT_GET_SIM_KNOB;
1574         xpt_action(ccb);
1575
1576         /*
1577          * Copan WWN format:
1578          *
1579          * Bits 63-60:  0x5             NAA, IEEE registered name
1580          * Bits 59-36:  0x000ED5        IEEE Company name assigned to Copan
1581          * Bits 35-12:                  Copan SSN (Sequential Serial Number)
1582          * Bits 11-8:                   Type of port:
1583          *                                      1 == N-Port
1584          *                                      2 == F-Port
1585          *                                      3 == NL-Port
1586          * Bits 7-0:                    0 == Node Name, >0 == Port Number
1587          */
1588         if (online != 0) {
1589                 if ((ccb->knob.xport_specific.valid & KNOB_VALID_ADDRESS) != 0){
1590 #ifdef RANDOM_WWNN
1591                         uint64_t random_bits;
1592 #endif
1593
1594                         printf("%s: %s current WWNN %#jx\n", __func__,
1595                                bus_softc->port_name,
1596                                ccb->knob.xport_specific.fc.wwnn);
1597                         printf("%s: %s current WWPN %#jx\n", __func__,
1598                                bus_softc->port_name,
1599                                ccb->knob.xport_specific.fc.wwpn);
1600
1601 #ifdef RANDOM_WWNN
1602                         arc4rand(&random_bits, sizeof(random_bits), 0);
1603 #endif
1604
1605                         /*
1606                          * XXX KDM this is a bit of a kludge for now.  We
1607                          * take the current WWNN/WWPN from the card, and
1608                          * replace the company identifier and the NL-Port
1609                          * indicator and the port number (for the WWPN).
1610                          * This should be replaced later with ddb_GetWWNN,
1611                          * or possibly a more centralized scheme.  (It
1612                          * would be nice to have the WWNN/WWPN for each
1613                          * port stored in the ctl_port structure.)
1614                          */
1615 #ifdef RANDOM_WWNN
1616                         ccb->knob.xport_specific.fc.wwnn = 
1617                                 (random_bits &
1618                                 0x0000000fffffff00ULL) |
1619                                 /* Company ID */ 0x5000ED5000000000ULL |
1620                                 /* NL-Port */    0x0300;
1621                         ccb->knob.xport_specific.fc.wwpn = 
1622                                 (random_bits &
1623                                 0x0000000fffffff00ULL) |
1624                                 /* Company ID */ 0x5000ED5000000000ULL |
1625                                 /* NL-Port */    0x3000 |
1626                                 /* Port Num */ (bus_softc->port.targ_port & 0xff);
1627
1628                         /*
1629                          * This is a bit of an API break/reversal, but if
1630                          * we're doing the random WWNN that's a little
1631                          * different anyway.  So record what we're actually
1632                          * using with the frontend code so it's reported
1633                          * accurately.
1634                          */
1635                         ctl_port_set_wwns(&bus_softc->port,
1636                             true, ccb->knob.xport_specific.fc.wwnn,
1637                             true, ccb->knob.xport_specific.fc.wwpn);
1638                         set_wwnn = 1;
1639 #else /* RANDOM_WWNN */
1640                         /*
1641                          * If the user has specified a WWNN/WWPN, send them
1642                          * down to the SIM.  Otherwise, record what the SIM
1643                          * has reported.
1644                          */
1645                         if (bus_softc->port.wwnn != 0 && bus_softc->port.wwnn
1646                             != ccb->knob.xport_specific.fc.wwnn) {
1647                                 ccb->knob.xport_specific.fc.wwnn =
1648                                     bus_softc->port.wwnn;
1649                                 set_wwnn = 1;
1650                         } else {
1651                                 ctl_port_set_wwns(&bus_softc->port,
1652                                     true, ccb->knob.xport_specific.fc.wwnn,
1653                                     false, 0);
1654                         }
1655                         if (bus_softc->port.wwpn != 0 && bus_softc->port.wwpn
1656                              != ccb->knob.xport_specific.fc.wwpn) {
1657                                 ccb->knob.xport_specific.fc.wwpn =
1658                                     bus_softc->port.wwpn;
1659                                 set_wwnn = 1;
1660                         } else {
1661                                 ctl_port_set_wwns(&bus_softc->port,
1662                                     false, 0,
1663                                     true, ccb->knob.xport_specific.fc.wwpn);
1664                         }
1665 #endif /* RANDOM_WWNN */
1666
1667
1668                         if (set_wwnn != 0) {
1669                                 printf("%s: %s new WWNN %#jx\n", __func__,
1670                                        bus_softc->port_name,
1671                                 ccb->knob.xport_specific.fc.wwnn);
1672                                 printf("%s: %s new WWPN %#jx\n", __func__,
1673                                        bus_softc->port_name,
1674                                        ccb->knob.xport_specific.fc.wwpn);
1675                         }
1676                 } else {
1677                         printf("%s: %s has no valid WWNN/WWPN\n", __func__,
1678                                bus_softc->port_name);
1679                 }
1680         }
1681         ccb->ccb_h.func_code = XPT_SET_SIM_KNOB;
1682         ccb->knob.xport_specific.valid = KNOB_VALID_ROLE;
1683         if (set_wwnn != 0)
1684                 ccb->knob.xport_specific.valid |= KNOB_VALID_ADDRESS;
1685
1686         if (online != 0)
1687                 ccb->knob.xport_specific.fc.role |= KNOB_ROLE_TARGET;
1688         else
1689                 ccb->knob.xport_specific.fc.role &= ~KNOB_ROLE_TARGET;
1690
1691         xpt_action(ccb);
1692
1693         if ((ccb->ccb_h.status & CAM_STATUS_MASK) != CAM_REQ_CMP) {
1694                 printf("%s: SIM %s (path id %d) target %s failed with "
1695                        "status %#x\n",
1696                        __func__, bus_softc->port_name, bus_softc->path_id,
1697                        (online != 0) ? "enable" : "disable",
1698                        ccb->ccb_h.status);
1699         } else {
1700                 printf("%s: SIM %s (path id %d) target %s succeeded\n",
1701                        __func__, bus_softc->port_name, bus_softc->path_id,
1702                        (online != 0) ? "enable" : "disable");
1703         }
1704
1705         xpt_free_path(path);
1706         xpt_free_ccb(ccb);
1707 }
1708
1709 static void
1710 ctlfe_online(void *arg)
1711 {
1712         struct ctlfe_softc *bus_softc;
1713         struct cam_path *path;
1714         cam_status status;
1715         struct ctlfe_lun_softc *lun_softc;
1716         struct cam_periph *periph;
1717
1718         bus_softc = (struct ctlfe_softc *)arg;
1719
1720         /*
1721          * Create the wildcard LUN before bringing the port online.
1722          */
1723         status = xpt_create_path(&path, /*periph*/ NULL,
1724                                  bus_softc->path_id, CAM_TARGET_WILDCARD,
1725                                  CAM_LUN_WILDCARD);
1726         if (status != CAM_REQ_CMP) {
1727                 printf("%s: unable to create path for wildcard periph\n",
1728                                 __func__);
1729                 return;
1730         }
1731
1732         lun_softc = malloc(sizeof(*lun_softc), M_CTLFE, M_WAITOK | M_ZERO);
1733
1734         xpt_path_lock(path);
1735         periph = cam_periph_find(path, "ctl");
1736         if (periph != NULL) {
1737                 /* We've already got a periph, no need to alloc a new one. */
1738                 xpt_path_unlock(path);
1739                 xpt_free_path(path);
1740                 free(lun_softc, M_CTLFE);
1741                 return;
1742         }
1743         lun_softc->parent_softc = bus_softc;
1744         lun_softc->flags |= CTLFE_LUN_WILDCARD;
1745
1746         status = cam_periph_alloc(ctlferegister,
1747                                   ctlfeoninvalidate,
1748                                   ctlfecleanup,
1749                                   ctlfestart,
1750                                   "ctl",
1751                                   CAM_PERIPH_BIO,
1752                                   path,
1753                                   ctlfeasync,
1754                                   0,
1755                                   lun_softc);
1756
1757         if ((status & CAM_STATUS_MASK) != CAM_REQ_CMP) {
1758                 const struct cam_status_entry *entry;
1759
1760                 entry = cam_fetch_status_entry(status);
1761                 printf("%s: CAM error %s (%#x) returned from "
1762                        "cam_periph_alloc()\n", __func__, (entry != NULL) ?
1763                        entry->status_text : "Unknown", status);
1764                 free(lun_softc, M_CTLFE);
1765         }
1766
1767         xpt_path_unlock(path);
1768         ctlfe_onoffline(arg, /*online*/ 1);
1769         xpt_free_path(path);
1770 }
1771
1772 static void
1773 ctlfe_offline(void *arg)
1774 {
1775         struct ctlfe_softc *bus_softc;
1776         struct cam_path *path;
1777         cam_status status;
1778         struct cam_periph *periph;
1779
1780         bus_softc = (struct ctlfe_softc *)arg;
1781
1782         ctlfe_onoffline(arg, /*online*/ 0);
1783
1784         /*
1785          * Disable the wildcard LUN for this port now that we have taken
1786          * the port offline.
1787          */
1788         status = xpt_create_path(&path, /*periph*/ NULL,
1789                                  bus_softc->path_id, CAM_TARGET_WILDCARD,
1790                                  CAM_LUN_WILDCARD);
1791         if (status != CAM_REQ_CMP) {
1792                 printf("%s: unable to create path for wildcard periph\n",
1793                        __func__);
1794                 return;
1795         }
1796         xpt_path_lock(path);
1797         if ((periph = cam_periph_find(path, "ctl")) != NULL)
1798                 cam_periph_invalidate(periph);
1799         xpt_path_unlock(path);
1800         xpt_free_path(path);
1801 }
1802
1803 /*
1804  * This will get called to enable a LUN on every bus that is attached to
1805  * CTL.  So we only need to create a path/periph for this particular bus.
1806  */
1807 static int
1808 ctlfe_lun_enable(void *arg, int lun_id)
1809 {
1810         struct ctlfe_softc *bus_softc;
1811         struct ctlfe_lun_softc *softc;
1812         struct cam_path *path;
1813         struct cam_periph *periph;
1814         cam_status status;
1815
1816         bus_softc = (struct ctlfe_softc *)arg;
1817
1818         status = xpt_create_path(&path, /*periph*/ NULL,
1819                                   bus_softc->path_id, bus_softc->target_id, lun_id);
1820         /* XXX KDM need some way to return status to CTL here? */
1821         if (status != CAM_REQ_CMP) {
1822                 printf("%s: could not create path, status %#x\n", __func__,
1823                        status);
1824                 return (1);
1825         }
1826
1827         softc = malloc(sizeof(*softc), M_CTLFE, M_WAITOK | M_ZERO);
1828         xpt_path_lock(path);
1829         periph = cam_periph_find(path, "ctl");
1830         if (periph != NULL) {
1831                 /* We've already got a periph, no need to alloc a new one. */
1832                 xpt_path_unlock(path);
1833                 xpt_free_path(path);
1834                 free(softc, M_CTLFE);
1835                 return (0);
1836         }
1837         softc->parent_softc = bus_softc;
1838
1839         status = cam_periph_alloc(ctlferegister,
1840                                   ctlfeoninvalidate,
1841                                   ctlfecleanup,
1842                                   ctlfestart,
1843                                   "ctl",
1844                                   CAM_PERIPH_BIO,
1845                                   path,
1846                                   ctlfeasync,
1847                                   0,
1848                                   softc);
1849
1850         if ((status & CAM_STATUS_MASK) != CAM_REQ_CMP) {
1851                 const struct cam_status_entry *entry;
1852
1853                 entry = cam_fetch_status_entry(status);
1854                 printf("%s: CAM error %s (%#x) returned from "
1855                        "cam_periph_alloc()\n", __func__, (entry != NULL) ?
1856                        entry->status_text : "Unknown", status);
1857                 free(softc, M_CTLFE);
1858         }
1859
1860         xpt_path_unlock(path);
1861         xpt_free_path(path);
1862         return (0);
1863 }
1864
1865 /*
1866  * This will get called when the user removes a LUN to disable that LUN
1867  * on every bus that is attached to CTL.  
1868  */
1869 static int
1870 ctlfe_lun_disable(void *arg, int lun_id)
1871 {
1872         struct ctlfe_softc *softc;
1873         struct ctlfe_lun_softc *lun_softc;
1874
1875         softc = (struct ctlfe_softc *)arg;
1876
1877         mtx_lock(&softc->lun_softc_mtx);
1878         STAILQ_FOREACH(lun_softc, &softc->lun_softc_list, links) {
1879                 struct cam_path *path;
1880
1881                 path = lun_softc->periph->path;
1882
1883                 if ((xpt_path_target_id(path) == 0)
1884                  && (xpt_path_lun_id(path) == lun_id)) {
1885                         break;
1886                 }
1887         }
1888         if (lun_softc == NULL) {
1889                 mtx_unlock(&softc->lun_softc_mtx);
1890                 printf("%s: can't find lun %d\n", __func__, lun_id);
1891                 return (1);
1892         }
1893         cam_periph_acquire(lun_softc->periph);
1894         mtx_unlock(&softc->lun_softc_mtx);
1895
1896         cam_periph_lock(lun_softc->periph);
1897         cam_periph_invalidate(lun_softc->periph);
1898         cam_periph_unlock(lun_softc->periph);
1899         cam_periph_release(lun_softc->periph);
1900         return (0);
1901 }
1902
1903 static void
1904 ctlfe_dump_sim(struct cam_sim *sim)
1905 {
1906
1907         printf("%s%d: max tagged openings: %d, max dev openings: %d\n",
1908                sim->sim_name, sim->unit_number,
1909                sim->max_tagged_dev_openings, sim->max_dev_openings);
1910 }
1911
1912 /*
1913  * Assumes that the SIM lock is held.
1914  */
1915 static void
1916 ctlfe_dump_queue(struct ctlfe_lun_softc *softc)
1917 {
1918         struct ccb_hdr *hdr;
1919         struct cam_periph *periph;
1920         int num_items;
1921
1922         periph = softc->periph;
1923         num_items = 0;
1924
1925         TAILQ_FOREACH(hdr, &softc->work_queue, periph_links.tqe) {
1926                 union ctl_io *io = hdr->io_ptr;
1927
1928                 num_items++;
1929
1930                 /*
1931                  * Only regular SCSI I/O is put on the work
1932                  * queue, so we can print sense here.  There may be no
1933                  * sense if it's no the queue for a DMA, but this serves to
1934                  * print out the CCB as well.
1935                  *
1936                  * XXX KDM switch this over to scsi_sense_print() when
1937                  * CTL is merged in with CAM.
1938                  */
1939                 ctl_io_error_print(io, NULL);
1940
1941                 /*
1942                  * Print DMA status if we are DMA_QUEUED.
1943                  */
1944                 if (io->io_hdr.flags & CTL_FLAG_DMA_QUEUED) {
1945                         xpt_print(periph->path,
1946                             "Total %u, Current %u, Resid %u\n",
1947                             io->scsiio.kern_total_len,
1948                             io->scsiio.kern_data_len,
1949                             io->scsiio.kern_data_resid);
1950                 }
1951         }
1952
1953         xpt_print(periph->path, "%d requests total waiting for CCBs\n",
1954                   num_items);
1955         xpt_print(periph->path, "%ju CCBs outstanding (%ju allocated, %ju "
1956                   "freed)\n", (uintmax_t)(softc->ccbs_alloced -
1957                   softc->ccbs_freed), (uintmax_t)softc->ccbs_alloced,
1958                   (uintmax_t)softc->ccbs_freed);
1959         xpt_print(periph->path, "%ju CTIOs outstanding (%ju sent, %ju "
1960                   "returned\n", (uintmax_t)(softc->ctios_sent -
1961                   softc->ctios_returned), softc->ctios_sent,
1962                   softc->ctios_returned);
1963 }
1964
1965 /*
1966  * Datamove/done routine called by CTL.  Put ourselves on the queue to
1967  * receive a CCB from CAM so we can queue the continue I/O request down
1968  * to the adapter.
1969  */
1970 static void
1971 ctlfe_datamove(union ctl_io *io)
1972 {
1973         union ccb *ccb;
1974         struct cam_periph *periph;
1975         struct ctlfe_lun_softc *softc;
1976
1977         KASSERT(io->io_hdr.io_type == CTL_IO_SCSI,
1978             ("Unexpected io_type (%d) in ctlfe_datamove", io->io_hdr.io_type));
1979
1980         ccb = io->io_hdr.ctl_private[CTL_PRIV_FRONTEND].ptr;
1981         periph = xpt_path_periph(ccb->ccb_h.path);
1982         cam_periph_lock(periph);
1983         softc = (struct ctlfe_lun_softc *)periph->softc;
1984         io->io_hdr.flags |= CTL_FLAG_DMA_QUEUED;
1985         if ((io->io_hdr.status & CTL_STATUS_MASK) != CTL_STATUS_NONE)
1986                 io->io_hdr.flags |= CTL_FLAG_STATUS_QUEUED;
1987         TAILQ_INSERT_TAIL(&softc->work_queue, &ccb->ccb_h,
1988                           periph_links.tqe);
1989         xpt_schedule(periph, /*priority*/ 1);
1990         cam_periph_unlock(periph);
1991 }
1992
1993 static void
1994 ctlfe_done(union ctl_io *io)
1995 {
1996         union ccb *ccb;
1997         struct cam_periph *periph;
1998         struct ctlfe_lun_softc *softc;
1999
2000         ccb = io->io_hdr.ctl_private[CTL_PRIV_FRONTEND].ptr;
2001         periph = xpt_path_periph(ccb->ccb_h.path);
2002         cam_periph_lock(periph);
2003         softc = (struct ctlfe_lun_softc *)periph->softc;
2004
2005         if (io->io_hdr.io_type == CTL_IO_TASK) {
2006                 /*
2007                  * Task management commands don't require any further
2008                  * communication back to the adapter.  Requeue the CCB
2009                  * to the adapter, and free the CTL I/O.
2010                  */
2011                 xpt_print(ccb->ccb_h.path, "%s: returning task I/O "
2012                           "tag %#x seq %#x\n", __func__,
2013                           ccb->cin1.tag_id, ccb->cin1.seq_id);
2014                 /*
2015                  * Send the notify acknowledge down to the SIM, to let it
2016                  * know we processed the task management command.
2017                  */
2018                 ccb->ccb_h.status = CAM_REQ_INPROG;
2019                 ccb->ccb_h.func_code = XPT_NOTIFY_ACKNOWLEDGE;
2020                 xpt_action(ccb);
2021         } else if (io->io_hdr.flags & CTL_FLAG_STATUS_SENT) {
2022                 if (softc->flags & CTLFE_LUN_WILDCARD) {
2023                         ccb->ccb_h.target_id = CAM_TARGET_WILDCARD;
2024                         ccb->ccb_h.target_lun = CAM_LUN_WILDCARD;
2025                 }
2026                 if (periph->flags & CAM_PERIPH_INVALID) {
2027                         ctlfe_free_ccb(periph, ccb);
2028                 } else {
2029                         cam_periph_unlock(periph);
2030                         xpt_action(ccb);
2031                         return;
2032                 }
2033         } else {
2034                 io->io_hdr.flags |= CTL_FLAG_STATUS_QUEUED;
2035                 TAILQ_INSERT_TAIL(&softc->work_queue, &ccb->ccb_h,
2036                                   periph_links.tqe);
2037                 xpt_schedule(periph, /*priority*/ 1);
2038         }
2039
2040         cam_periph_unlock(periph);
2041 }
2042
2043 static void
2044 ctlfe_dump(void)
2045 {
2046         struct ctlfe_softc *bus_softc;
2047         struct ctlfe_lun_softc *lun_softc;
2048
2049         STAILQ_FOREACH(bus_softc, &ctlfe_softc_list, links) {
2050                 ctlfe_dump_sim(bus_softc->sim);
2051                 STAILQ_FOREACH(lun_softc, &bus_softc->lun_softc_list, links)
2052                         ctlfe_dump_queue(lun_softc);
2053         }
2054 }