]> CyberLeo.Net >> Repos - FreeBSD/FreeBSD.git/blob - sys/cam/ctl/ctl_frontend_iscsi.c
Extend the meaning of the CTLFLAG_TUN flag to automatically check if
[FreeBSD/FreeBSD.git] / sys / cam / ctl / ctl_frontend_iscsi.c
1 /*-
2  * Copyright (c) 2012 The FreeBSD Foundation
3  * All rights reserved.
4  *
5  * This software was developed by Edward Tomasz Napierala under sponsorship
6  * from the FreeBSD Foundation.
7  *
8  * Redistribution and use in source and binary forms, with or without
9  * modification, are permitted provided that the following conditions
10  * are met:
11  * 1. Redistributions of source code must retain the above copyright
12  *    notice, this list of conditions and the following disclaimer.
13  * 2. Redistributions in binary form must reproduce the above copyright
14  *    notice, this list of conditions and the following disclaimer in the
15  *    documentation and/or other materials provided with the distribution.
16  *
17  * THIS SOFTWARE IS PROVIDED BY THE AUTHOR AND CONTRIBUTORS ``AS IS'' AND
18  * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
19  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
20  * ARE DISCLAIMED.  IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE
21  * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
22  * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
23  * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
24  * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
25  * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
26  * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
27  * SUCH DAMAGE.
28  *
29  * $FreeBSD$
30  */
31
32 /*
33  * CTL frontend for the iSCSI protocol.
34  */
35
36 #include <sys/cdefs.h>
37 __FBSDID("$FreeBSD$");
38
39 #include <sys/param.h>
40 #include <sys/capsicum.h>
41 #include <sys/condvar.h>
42 #include <sys/file.h>
43 #include <sys/kernel.h>
44 #include <sys/kthread.h>
45 #include <sys/lock.h>
46 #include <sys/malloc.h>
47 #include <sys/module.h>
48 #include <sys/mutex.h>
49 #include <sys/queue.h>
50 #include <sys/sbuf.h>
51 #include <sys/sysctl.h>
52 #include <sys/systm.h>
53 #include <sys/uio.h>
54 #include <sys/unistd.h>
55 #include <vm/uma.h>
56
57 #include <cam/scsi/scsi_all.h>
58 #include <cam/scsi/scsi_da.h>
59 #include <cam/ctl/ctl_io.h>
60 #include <cam/ctl/ctl.h>
61 #include <cam/ctl/ctl_backend.h>
62 #include <cam/ctl/ctl_error.h>
63 #include <cam/ctl/ctl_frontend.h>
64 #include <cam/ctl/ctl_frontend_internal.h>
65 #include <cam/ctl/ctl_debug.h>
66 #include <cam/ctl/ctl_ha.h>
67 #include <cam/ctl/ctl_ioctl.h>
68 #include <cam/ctl/ctl_private.h>
69
70 #include "../../dev/iscsi/icl.h"
71 #include "../../dev/iscsi/iscsi_proto.h"
72 #include "ctl_frontend_iscsi.h"
73
74 #ifdef ICL_KERNEL_PROXY
75 #include <sys/socketvar.h>
76 #endif
77
78 #ifdef ICL_KERNEL_PROXY
79 FEATURE(cfiscsi_kernel_proxy, "iSCSI target built with ICL_KERNEL_PROXY");
80 #endif
81
82 static MALLOC_DEFINE(M_CFISCSI, "cfiscsi", "Memory used for CTL iSCSI frontend");
83 static uma_zone_t cfiscsi_data_wait_zone;
84
85 SYSCTL_NODE(_kern_cam_ctl, OID_AUTO, iscsi, CTLFLAG_RD, 0,
86     "CAM Target Layer iSCSI Frontend");
87 static int debug = 3;
88 SYSCTL_INT(_kern_cam_ctl_iscsi, OID_AUTO, debug, CTLFLAG_RWTUN,
89     &debug, 1, "Enable debug messages");
90 static int ping_timeout = 5;
91 SYSCTL_INT(_kern_cam_ctl_iscsi, OID_AUTO, ping_timeout, CTLFLAG_RWTUN,
92     &ping_timeout, 5, "Interval between ping (NOP-Out) requests, in seconds");
93 static int login_timeout = 60;
94 SYSCTL_INT(_kern_cam_ctl_iscsi, OID_AUTO, login_timeout, CTLFLAG_RWTUN,
95     &login_timeout, 60, "Time to wait for ctld(8) to finish Login Phase, in seconds");
96 static int maxcmdsn_delta = 256;
97 SYSCTL_INT(_kern_cam_ctl_iscsi, OID_AUTO, maxcmdsn_delta, CTLFLAG_RWTUN,
98     &maxcmdsn_delta, 256, "Number of commands the initiator can send "
99     "without confirmation");
100
101 #define CFISCSI_DEBUG(X, ...)                                           \
102         do {                                                            \
103                 if (debug > 1) {                                        \
104                         printf("%s: " X "\n",                           \
105                             __func__, ## __VA_ARGS__);                  \
106                 }                                                       \
107         } while (0)
108
109 #define CFISCSI_WARN(X, ...)                                            \
110         do {                                                            \
111                 if (debug > 0) {                                        \
112                         printf("WARNING: %s: " X "\n",                  \
113                             __func__, ## __VA_ARGS__);                  \
114                 }                                                       \
115         } while (0)
116
117 #define CFISCSI_SESSION_DEBUG(S, X, ...)                                \
118         do {                                                            \
119                 if (debug > 1) {                                        \
120                         printf("%s: %s (%s): " X "\n",                  \
121                             __func__, S->cs_initiator_addr,             \
122                             S->cs_initiator_name, ## __VA_ARGS__);      \
123                 }                                                       \
124         } while (0)
125
126 #define CFISCSI_SESSION_WARN(S, X, ...)                                 \
127         do  {                                                           \
128                 if (debug > 0) {                                        \
129                         printf("WARNING: %s (%s): " X "\n",             \
130                             S->cs_initiator_addr,                       \
131                             S->cs_initiator_name, ## __VA_ARGS__);      \
132                 }                                                       \
133         } while (0)
134
135 #define CFISCSI_SESSION_LOCK(X)         mtx_lock(&X->cs_lock)
136 #define CFISCSI_SESSION_UNLOCK(X)       mtx_unlock(&X->cs_lock)
137 #define CFISCSI_SESSION_LOCK_ASSERT(X)  mtx_assert(&X->cs_lock, MA_OWNED)
138
139 #define CONN_SESSION(X)                 ((struct cfiscsi_session *)(X)->ic_prv0)
140 #define PDU_SESSION(X)                  CONN_SESSION((X)->ip_conn)
141 #define PDU_EXPDATASN(X)                (X)->ip_prv0
142 #define PDU_TOTAL_TRANSFER_LEN(X)       (X)->ip_prv1
143 #define PDU_R2TSN(X)                    (X)->ip_prv2
144
145 int             cfiscsi_init(void);
146 static void     cfiscsi_online(void *arg);
147 static void     cfiscsi_offline(void *arg);
148 static int      cfiscsi_targ_enable(void *arg, struct ctl_id targ_id);
149 static int      cfiscsi_targ_disable(void *arg, struct ctl_id targ_id);
150 static int      cfiscsi_lun_enable(void *arg,
151                     struct ctl_id target_id, int lun_id);
152 static int      cfiscsi_lun_disable(void *arg,
153                     struct ctl_id target_id, int lun_id);
154 static int      cfiscsi_ioctl(struct cdev *dev,
155                     u_long cmd, caddr_t addr, int flag, struct thread *td);
156 static int      cfiscsi_devid(struct ctl_scsiio *ctsio, int alloc_len);
157 static void     cfiscsi_datamove(union ctl_io *io);
158 static void     cfiscsi_done(union ctl_io *io);
159 static uint32_t cfiscsi_map_lun(void *arg, uint32_t lun);
160 static bool     cfiscsi_pdu_update_cmdsn(const struct icl_pdu *request);
161 static void     cfiscsi_pdu_handle_nop_out(struct icl_pdu *request);
162 static void     cfiscsi_pdu_handle_scsi_command(struct icl_pdu *request);
163 static void     cfiscsi_pdu_handle_task_request(struct icl_pdu *request);
164 static void     cfiscsi_pdu_handle_data_out(struct icl_pdu *request);
165 static void     cfiscsi_pdu_handle_logout_request(struct icl_pdu *request);
166 static void     cfiscsi_session_terminate(struct cfiscsi_session *cs);
167 static struct cfiscsi_target    *cfiscsi_target_find(struct cfiscsi_softc
168                     *softc, const char *name);
169 static void     cfiscsi_target_release(struct cfiscsi_target *ct);
170 static void     cfiscsi_session_delete(struct cfiscsi_session *cs);
171
172 static struct cfiscsi_softc cfiscsi_softc;
173 extern struct ctl_softc *control_softc;
174
175 static int cfiscsi_module_event_handler(module_t, int /*modeventtype_t*/, void *);
176
177 static moduledata_t cfiscsi_moduledata = {
178         "ctlcfiscsi",
179         cfiscsi_module_event_handler,
180         NULL
181 };
182
183 DECLARE_MODULE(ctlcfiscsi, cfiscsi_moduledata, SI_SUB_CONFIGURE, SI_ORDER_FOURTH);
184 MODULE_VERSION(ctlcfiscsi, 1);
185 MODULE_DEPEND(ctlcfiscsi, ctl, 1, 1, 1);
186 MODULE_DEPEND(ctlcfiscsi, icl, 1, 1, 1);
187
188 static struct icl_pdu *
189 cfiscsi_pdu_new_response(struct icl_pdu *request, int flags)
190 {
191
192         return (icl_pdu_new_bhs(request->ip_conn, flags));
193 }
194
195 static bool
196 cfiscsi_pdu_update_cmdsn(const struct icl_pdu *request)
197 {
198         const struct iscsi_bhs_scsi_command *bhssc;
199         struct cfiscsi_session *cs;
200         uint32_t cmdsn, expstatsn;
201
202         cs = PDU_SESSION(request);
203
204         /*
205          * Every incoming PDU - not just NOP-Out - resets the ping timer.
206          * The purpose of the timeout is to reset the connection when it stalls;
207          * we don't want this to happen when NOP-In or NOP-Out ends up delayed
208          * in some queue.
209          *
210          * XXX: Locking?
211          */
212         cs->cs_timeout = 0;
213
214         /*
215          * Data-Out PDUs don't contain CmdSN.
216          */
217         if ((request->ip_bhs->bhs_opcode & ~ISCSI_BHS_OPCODE_IMMEDIATE) ==
218             ISCSI_BHS_OPCODE_SCSI_DATA_OUT)
219                 return (false);
220
221         /*
222          * We're only using fields common for all the request
223          * (initiator -> target) PDUs.
224          */
225         bhssc = (const struct iscsi_bhs_scsi_command *)request->ip_bhs;
226         cmdsn = ntohl(bhssc->bhssc_cmdsn);
227         expstatsn = ntohl(bhssc->bhssc_expstatsn);
228
229         CFISCSI_SESSION_LOCK(cs);
230 #if 0
231         if (expstatsn != cs->cs_statsn) {
232                 CFISCSI_SESSION_DEBUG(cs, "received PDU with ExpStatSN %d, "
233                     "while current StatSN is %d", expstatsn,
234                     cs->cs_statsn);
235         }
236 #endif
237
238         /*
239          * The target MUST silently ignore any non-immediate command outside
240          * of this range.
241          */
242         if (cmdsn < cs->cs_cmdsn || cmdsn > cs->cs_cmdsn + maxcmdsn_delta) {
243                 CFISCSI_SESSION_UNLOCK(cs);
244                 CFISCSI_SESSION_WARN(cs, "received PDU with CmdSN %d, "
245                     "while expected CmdSN was %d", cmdsn, cs->cs_cmdsn);
246                 return (true);
247         }
248
249         if ((request->ip_bhs->bhs_opcode & ISCSI_BHS_OPCODE_IMMEDIATE) == 0)
250                 cs->cs_cmdsn++;
251
252         CFISCSI_SESSION_UNLOCK(cs);
253
254         return (false);
255 }
256
257 static void
258 cfiscsi_pdu_handle(struct icl_pdu *request)
259 {
260         struct cfiscsi_session *cs;
261         bool ignore;
262
263         cs = PDU_SESSION(request);
264
265         ignore = cfiscsi_pdu_update_cmdsn(request);
266         if (ignore) {
267                 icl_pdu_free(request);
268                 return;
269         }
270
271         /*
272          * Handle the PDU; this includes e.g. receiving the remaining
273          * part of PDU and submitting the SCSI command to CTL
274          * or queueing a reply.  The handling routine is responsible
275          * for freeing the PDU when it's no longer needed.
276          */
277         switch (request->ip_bhs->bhs_opcode &
278             ~ISCSI_BHS_OPCODE_IMMEDIATE) {
279         case ISCSI_BHS_OPCODE_NOP_OUT:
280                 cfiscsi_pdu_handle_nop_out(request);
281                 break;
282         case ISCSI_BHS_OPCODE_SCSI_COMMAND:
283                 cfiscsi_pdu_handle_scsi_command(request);
284                 break;
285         case ISCSI_BHS_OPCODE_TASK_REQUEST:
286                 cfiscsi_pdu_handle_task_request(request);
287                 break;
288         case ISCSI_BHS_OPCODE_SCSI_DATA_OUT:
289                 cfiscsi_pdu_handle_data_out(request);
290                 break;
291         case ISCSI_BHS_OPCODE_LOGOUT_REQUEST:
292                 cfiscsi_pdu_handle_logout_request(request);
293                 break;
294         default:
295                 CFISCSI_SESSION_WARN(cs, "received PDU with unsupported "
296                     "opcode 0x%x; dropping connection",
297                     request->ip_bhs->bhs_opcode);
298                 icl_pdu_free(request);
299                 cfiscsi_session_terminate(cs);
300         }
301
302 }
303
304 static void
305 cfiscsi_receive_callback(struct icl_pdu *request)
306 {
307         struct cfiscsi_session *cs;
308
309         cs = PDU_SESSION(request);
310
311 #ifdef ICL_KERNEL_PROXY
312         if (cs->cs_waiting_for_ctld || cs->cs_login_phase) {
313                 if (cs->cs_login_pdu == NULL)
314                         cs->cs_login_pdu = request;
315                 else
316                         icl_pdu_free(request);
317                 cv_signal(&cs->cs_login_cv);
318                 return;
319         }
320 #endif
321
322         cfiscsi_pdu_handle(request);
323 }
324
325 static void
326 cfiscsi_error_callback(struct icl_conn *ic)
327 {
328         struct cfiscsi_session *cs;
329
330         cs = CONN_SESSION(ic);
331
332         CFISCSI_SESSION_WARN(cs, "connection error; dropping connection");
333         cfiscsi_session_terminate(cs);
334 }
335
336 static int
337 cfiscsi_pdu_prepare(struct icl_pdu *response)
338 {
339         struct cfiscsi_session *cs;
340         struct iscsi_bhs_scsi_response *bhssr;
341         bool advance_statsn = true;
342
343         cs = PDU_SESSION(response);
344
345         CFISCSI_SESSION_LOCK_ASSERT(cs);
346
347         /*
348          * We're only using fields common for all the response
349          * (target -> initiator) PDUs.
350          */
351         bhssr = (struct iscsi_bhs_scsi_response *)response->ip_bhs;
352
353         /*
354          * 10.8.3: "The StatSN for this connection is not advanced
355          * after this PDU is sent."
356          */
357         if (bhssr->bhssr_opcode == ISCSI_BHS_OPCODE_R2T)
358                 advance_statsn = false;
359
360         /*
361          * 10.19.2: "However, when the Initiator Task Tag is set to 0xffffffff,
362          * StatSN for the connection is not advanced after this PDU is sent."
363          */
364         if (bhssr->bhssr_opcode == ISCSI_BHS_OPCODE_NOP_IN && 
365             bhssr->bhssr_initiator_task_tag == 0xffffffff)
366                 advance_statsn = false;
367
368         /*
369          * See the comment below - StatSN is not meaningful and must
370          * not be advanced.
371          */
372         if (bhssr->bhssr_opcode == ISCSI_BHS_OPCODE_SCSI_DATA_IN)
373                 advance_statsn = false;
374
375         /*
376          * 10.7.3: "The fields StatSN, Status, and Residual Count
377          * only have meaningful content if the S bit is set to 1."
378          */
379         if (bhssr->bhssr_opcode != ISCSI_BHS_OPCODE_SCSI_DATA_IN)
380                 bhssr->bhssr_statsn = htonl(cs->cs_statsn);
381         bhssr->bhssr_expcmdsn = htonl(cs->cs_cmdsn);
382         bhssr->bhssr_maxcmdsn = htonl(cs->cs_cmdsn + maxcmdsn_delta);
383
384         if (advance_statsn)
385                 cs->cs_statsn++;
386
387         return (0);
388 }
389
390 static void
391 cfiscsi_pdu_queue(struct icl_pdu *response)
392 {
393         struct cfiscsi_session *cs;
394
395         cs = PDU_SESSION(response);
396
397         CFISCSI_SESSION_LOCK(cs);
398         cfiscsi_pdu_prepare(response);
399         icl_pdu_queue(response);
400         CFISCSI_SESSION_UNLOCK(cs);
401 }
402
403 static uint32_t
404 cfiscsi_decode_lun(uint64_t encoded)
405 {
406         uint8_t lun[8];
407         uint32_t result;
408
409         /*
410          * The LUN field in iSCSI PDUs may look like an ordinary 64 bit number,
411          * but is in fact an evil, multidimensional structure defined
412          * in SCSI Architecture Model 5 (SAM-5), section 4.6.
413          */
414         memcpy(lun, &encoded, sizeof(lun));
415         switch (lun[0] & 0xC0) {
416         case 0x00:
417                 if ((lun[0] & 0x3f) != 0 || lun[2] != 0 || lun[3] != 0 ||
418                     lun[4] != 0 || lun[5] != 0 || lun[6] != 0 || lun[7] != 0) {
419                         CFISCSI_WARN("malformed LUN "
420                             "(peripheral device addressing method): 0x%jx",
421                             (uintmax_t)encoded);
422                         result = 0xffffffff;
423                         break;
424                 }
425                 result = lun[1];
426                 break;
427         case 0x40:
428                 if (lun[2] != 0 || lun[3] != 0 || lun[4] != 0 || lun[5] != 0 ||
429                     lun[6] != 0 || lun[7] != 0) {
430                         CFISCSI_WARN("malformed LUN "
431                             "(flat address space addressing method): 0x%jx",
432                             (uintmax_t)encoded);
433                         result = 0xffffffff;
434                         break;
435                 }
436                 result = ((lun[0] & 0x3f) << 8) + lun[1];
437                 break;
438         case 0xC0:
439                 if (lun[0] != 0xD2 || lun[4] != 0 || lun[5] != 0 ||
440                     lun[6] != 0 || lun[7] != 0) {
441                         CFISCSI_WARN("malformed LUN (extended flat "
442                             "address space addressing method): 0x%jx",
443                             (uintmax_t)encoded);
444                         result = 0xffffffff;
445                         break;
446                 }
447                 result = (lun[1] << 16) + (lun[2] << 8) + lun[3];
448         default:
449                 CFISCSI_WARN("unsupported LUN format 0x%jx",
450                     (uintmax_t)encoded);
451                 result = 0xffffffff;
452                 break;
453         }
454
455         return (result);
456 }
457
458 static void
459 cfiscsi_pdu_handle_nop_out(struct icl_pdu *request)
460 {
461         struct cfiscsi_session *cs;
462         struct iscsi_bhs_nop_out *bhsno;
463         struct iscsi_bhs_nop_in *bhsni;
464         struct icl_pdu *response;
465         void *data = NULL;
466         size_t datasize;
467         int error;
468
469         cs = PDU_SESSION(request);
470         bhsno = (struct iscsi_bhs_nop_out *)request->ip_bhs;
471
472         if (bhsno->bhsno_initiator_task_tag == 0xffffffff) {
473                 /*
474                  * Nothing to do, iscsi_pdu_update_statsn() already
475                  * zeroed the timeout.
476                  */
477                 icl_pdu_free(request);
478                 return;
479         }
480
481         datasize = icl_pdu_data_segment_length(request);
482         if (datasize > 0) {
483                 data = malloc(datasize, M_CFISCSI, M_NOWAIT | M_ZERO);
484                 if (data == NULL) {
485                         CFISCSI_SESSION_WARN(cs, "failed to allocate memory; "
486                             "dropping connection");
487                         icl_pdu_free(request);
488                         cfiscsi_session_terminate(cs);
489                         return;
490                 }
491                 icl_pdu_get_data(request, 0, data, datasize);
492         }
493
494         response = cfiscsi_pdu_new_response(request, M_NOWAIT);
495         if (response == NULL) {
496                 CFISCSI_SESSION_WARN(cs, "failed to allocate memory; "
497                     "droppping connection");
498                 free(data, M_CFISCSI);
499                 icl_pdu_free(request);
500                 cfiscsi_session_terminate(cs);
501                 return;
502         }
503         bhsni = (struct iscsi_bhs_nop_in *)response->ip_bhs;
504         bhsni->bhsni_opcode = ISCSI_BHS_OPCODE_NOP_IN;
505         bhsni->bhsni_flags = 0x80;
506         bhsni->bhsni_initiator_task_tag = bhsno->bhsno_initiator_task_tag;
507         bhsni->bhsni_target_transfer_tag = 0xffffffff;
508         if (datasize > 0) {
509                 error = icl_pdu_append_data(response, data, datasize, M_NOWAIT);
510                 if (error != 0) {
511                         CFISCSI_SESSION_WARN(cs, "failed to allocate memory; "
512                             "dropping connection");
513                         free(data, M_CFISCSI);
514                         icl_pdu_free(request);
515                         icl_pdu_free(response);
516                         cfiscsi_session_terminate(cs);
517                         return;
518                 }
519                 free(data, M_CFISCSI);
520         }
521
522         icl_pdu_free(request);
523         cfiscsi_pdu_queue(response);
524 }
525
526 static void
527 cfiscsi_pdu_handle_scsi_command(struct icl_pdu *request)
528 {
529         struct iscsi_bhs_scsi_command *bhssc;
530         struct cfiscsi_session *cs;
531         union ctl_io *io;
532         int error;
533
534         cs = PDU_SESSION(request);
535         bhssc = (struct iscsi_bhs_scsi_command *)request->ip_bhs;
536         //CFISCSI_SESSION_DEBUG(cs, "initiator task tag 0x%x",
537         //    bhssc->bhssc_initiator_task_tag);
538
539         if (request->ip_data_len > 0 && cs->cs_immediate_data == false) {
540                 CFISCSI_SESSION_WARN(cs, "unsolicited data with "
541                     "ImmediateData=No; dropping connection");
542                 icl_pdu_free(request);
543                 cfiscsi_session_terminate(cs);
544                 return;
545         }
546         io = ctl_alloc_io(cs->cs_target->ct_softc->fe.ctl_pool_ref);
547         if (io == NULL) {
548                 CFISCSI_SESSION_WARN(cs, "can't allocate ctl_io; "
549                     "dropping connection");
550                 icl_pdu_free(request);
551                 cfiscsi_session_terminate(cs);
552                 return;
553         }
554         ctl_zero_io(io);
555         io->io_hdr.ctl_private[CTL_PRIV_FRONTEND].ptr = request;
556         io->io_hdr.io_type = CTL_IO_SCSI;
557         io->io_hdr.nexus.initid.id = cs->cs_ctl_initid;
558         io->io_hdr.nexus.targ_port = cs->cs_target->ct_softc->fe.targ_port;
559         io->io_hdr.nexus.targ_target.id = 0;
560         io->io_hdr.nexus.targ_lun = cfiscsi_decode_lun(bhssc->bhssc_lun);
561         io->io_hdr.nexus.lun_map_fn = cfiscsi_map_lun;
562         io->io_hdr.nexus.lun_map_arg = cs;
563         io->scsiio.tag_num = bhssc->bhssc_initiator_task_tag;
564         switch ((bhssc->bhssc_flags & BHSSC_FLAGS_ATTR)) {
565         case BHSSC_FLAGS_ATTR_UNTAGGED:
566                 io->scsiio.tag_type = CTL_TAG_UNTAGGED;
567                 break;
568         case BHSSC_FLAGS_ATTR_SIMPLE:
569                 io->scsiio.tag_type = CTL_TAG_SIMPLE;
570                 break;
571         case BHSSC_FLAGS_ATTR_ORDERED:
572                 io->scsiio.tag_type = CTL_TAG_ORDERED;
573                 break;
574         case BHSSC_FLAGS_ATTR_HOQ:
575                 io->scsiio.tag_type = CTL_TAG_HEAD_OF_QUEUE;
576                 break;
577         case BHSSC_FLAGS_ATTR_ACA:
578                 io->scsiio.tag_type = CTL_TAG_ACA;
579                 break;
580         default:
581                 io->scsiio.tag_type = CTL_TAG_UNTAGGED;
582                 CFISCSI_SESSION_WARN(cs, "unhandled tag type %d",
583                     bhssc->bhssc_flags & BHSSC_FLAGS_ATTR);
584                 break;
585         }
586         io->scsiio.cdb_len = sizeof(bhssc->bhssc_cdb); /* Which is 16. */
587         memcpy(io->scsiio.cdb, bhssc->bhssc_cdb, sizeof(bhssc->bhssc_cdb));
588         refcount_acquire(&cs->cs_outstanding_ctl_pdus);
589         error = ctl_queue(io);
590         if (error != CTL_RETVAL_COMPLETE) {
591                 CFISCSI_SESSION_WARN(cs, "ctl_queue() failed; error %d; "
592                     "dropping connection", error);
593                 ctl_free_io(io);
594                 refcount_release(&cs->cs_outstanding_ctl_pdus);
595                 icl_pdu_free(request);
596                 cfiscsi_session_terminate(cs);
597         }
598 }
599
600 static void
601 cfiscsi_pdu_handle_task_request(struct icl_pdu *request)
602 {
603         struct iscsi_bhs_task_management_request *bhstmr;
604         struct iscsi_bhs_task_management_response *bhstmr2;
605         struct icl_pdu *response;
606         struct cfiscsi_session *cs;
607         union ctl_io *io;
608         int error;
609
610         cs = PDU_SESSION(request);
611         bhstmr = (struct iscsi_bhs_task_management_request *)request->ip_bhs;
612         io = ctl_alloc_io(cs->cs_target->ct_softc->fe.ctl_pool_ref);
613         if (io == NULL) {
614                 CFISCSI_SESSION_WARN(cs, "can't allocate ctl_io;"
615                     "dropping connection");
616                 icl_pdu_free(request);
617                 cfiscsi_session_terminate(cs);
618                 return;
619         }
620         ctl_zero_io(io);
621         io->io_hdr.ctl_private[CTL_PRIV_FRONTEND].ptr = request;
622         io->io_hdr.io_type = CTL_IO_TASK;
623         io->io_hdr.nexus.initid.id = cs->cs_ctl_initid;
624         io->io_hdr.nexus.targ_port = cs->cs_target->ct_softc->fe.targ_port;
625         io->io_hdr.nexus.targ_target.id = 0;
626         io->io_hdr.nexus.targ_lun = cfiscsi_decode_lun(bhstmr->bhstmr_lun);
627         io->io_hdr.nexus.lun_map_fn = cfiscsi_map_lun;
628         io->io_hdr.nexus.lun_map_arg = cs;
629         io->taskio.tag_type = CTL_TAG_SIMPLE; /* XXX */
630
631         switch (bhstmr->bhstmr_function & ~0x80) {
632         case BHSTMR_FUNCTION_ABORT_TASK:
633 #if 0
634                 CFISCSI_SESSION_DEBUG(cs, "BHSTMR_FUNCTION_ABORT_TASK");
635 #endif
636                 io->taskio.task_action = CTL_TASK_ABORT_TASK;
637                 io->taskio.tag_num = bhstmr->bhstmr_referenced_task_tag;
638                 break;
639         case BHSTMR_FUNCTION_LOGICAL_UNIT_RESET:
640 #if 0
641                 CFISCSI_SESSION_DEBUG(cs, "BHSTMR_FUNCTION_LOGICAL_UNIT_RESET");
642 #endif
643                 io->taskio.task_action = CTL_TASK_LUN_RESET;
644                 break;
645         case BHSTMR_FUNCTION_TARGET_WARM_RESET:
646 #if 0
647                 CFISCSI_SESSION_DEBUG(cs, "BHSTMR_FUNCTION_TARGET_WARM_RESET");
648 #endif
649                 io->taskio.task_action = CTL_TASK_TARGET_RESET;
650                 break;
651         default:
652                 CFISCSI_SESSION_DEBUG(cs, "unsupported function 0x%x",
653                     bhstmr->bhstmr_function & ~0x80);
654                 ctl_free_io(io);
655
656                 response = cfiscsi_pdu_new_response(request, M_NOWAIT);
657                 if (response == NULL) {
658                         CFISCSI_SESSION_WARN(cs, "failed to allocate memory; "
659                             "dropping connection");
660                         icl_pdu_free(request);
661                         cfiscsi_session_terminate(cs);
662                         return;
663                 }
664                 bhstmr2 = (struct iscsi_bhs_task_management_response *)
665                     response->ip_bhs;
666                 bhstmr2->bhstmr_opcode = ISCSI_BHS_OPCODE_TASK_RESPONSE;
667                 bhstmr2->bhstmr_flags = 0x80;
668                 bhstmr2->bhstmr_response =
669                     BHSTMR_RESPONSE_FUNCTION_NOT_SUPPORTED;
670                 bhstmr2->bhstmr_initiator_task_tag =
671                     bhstmr->bhstmr_initiator_task_tag;
672                 icl_pdu_free(request);
673                 cfiscsi_pdu_queue(response);
674                 return;
675         }
676
677         refcount_acquire(&cs->cs_outstanding_ctl_pdus);
678         error = ctl_queue(io);
679         if (error != CTL_RETVAL_COMPLETE) {
680                 CFISCSI_SESSION_WARN(cs, "ctl_queue() failed; error %d; "
681                     "dropping connection", error);
682                 ctl_free_io(io);
683                 refcount_release(&cs->cs_outstanding_ctl_pdus);
684                 icl_pdu_free(request);
685                 cfiscsi_session_terminate(cs);
686         }
687 }
688
689 static bool
690 cfiscsi_handle_data_segment(struct icl_pdu *request, struct cfiscsi_data_wait *cdw)
691 {
692         struct iscsi_bhs_data_out *bhsdo;
693         struct cfiscsi_session *cs;
694         struct ctl_sg_entry ctl_sg_entry, *ctl_sglist;
695         size_t copy_len, len, off, buffer_offset;
696         int ctl_sg_count;
697         union ctl_io *io;
698
699         cs = PDU_SESSION(request);
700
701         KASSERT((request->ip_bhs->bhs_opcode & ~ISCSI_BHS_OPCODE_IMMEDIATE) ==
702             ISCSI_BHS_OPCODE_SCSI_DATA_OUT ||
703             (request->ip_bhs->bhs_opcode & ~ISCSI_BHS_OPCODE_IMMEDIATE) ==
704             ISCSI_BHS_OPCODE_SCSI_COMMAND,
705             ("bad opcode 0x%x", request->ip_bhs->bhs_opcode));
706
707         /*
708          * We're only using fields common for Data-Out and SCSI Command PDUs.
709          */
710         bhsdo = (struct iscsi_bhs_data_out *)request->ip_bhs;
711
712         io = cdw->cdw_ctl_io;
713         KASSERT((io->io_hdr.flags & CTL_FLAG_DATA_MASK) != CTL_FLAG_DATA_IN,
714             ("CTL_FLAG_DATA_IN"));
715
716 #if 0
717         CFISCSI_SESSION_DEBUG(cs, "received %zd bytes out of %d",
718             request->ip_data_len, io->scsiio.kern_total_len);
719 #endif
720
721         if (io->scsiio.kern_sg_entries > 0) {
722                 ctl_sglist = (struct ctl_sg_entry *)io->scsiio.kern_data_ptr;
723                 ctl_sg_count = io->scsiio.kern_sg_entries;
724         } else {
725                 ctl_sglist = &ctl_sg_entry;
726                 ctl_sglist->addr = io->scsiio.kern_data_ptr;
727                 ctl_sglist->len = io->scsiio.kern_data_len;
728                 ctl_sg_count = 1;
729         }
730
731         if ((request->ip_bhs->bhs_opcode & ~ISCSI_BHS_OPCODE_IMMEDIATE) ==
732             ISCSI_BHS_OPCODE_SCSI_DATA_OUT)
733                 buffer_offset = ntohl(bhsdo->bhsdo_buffer_offset);
734         else
735                 buffer_offset = 0;
736         len = icl_pdu_data_segment_length(request);
737
738         /*
739          * Make sure the offset, as sent by the initiator, matches the offset
740          * we're supposed to be at in the scatter-gather list.
741          */
742         if (buffer_offset >
743             io->scsiio.kern_rel_offset + io->scsiio.ext_data_filled ||
744             buffer_offset + len <=
745             io->scsiio.kern_rel_offset + io->scsiio.ext_data_filled) {
746                 CFISCSI_SESSION_WARN(cs, "received bad buffer offset %zd, "
747                     "expected %zd; dropping connection", buffer_offset,
748                     (size_t)io->scsiio.kern_rel_offset +
749                     (size_t)io->scsiio.ext_data_filled);
750                 ctl_set_data_phase_error(&io->scsiio);
751                 cfiscsi_session_terminate(cs);
752                 return (true);
753         }
754
755         /*
756          * This is the offset within the PDU data segment, as opposed
757          * to buffer_offset, which is the offset within the task (SCSI
758          * command).
759          */
760         off = io->scsiio.kern_rel_offset + io->scsiio.ext_data_filled -
761             buffer_offset;
762
763         /*
764          * Iterate over the scatter/gather segments, filling them with data
765          * from the PDU data segment.  Note that this can get called multiple
766          * times for one SCSI command; the cdw structure holds state for the
767          * scatter/gather list.
768          */
769         for (;;) {
770                 KASSERT(cdw->cdw_sg_index < ctl_sg_count,
771                     ("cdw->cdw_sg_index >= ctl_sg_count"));
772                 if (cdw->cdw_sg_len == 0) {
773                         cdw->cdw_sg_addr = ctl_sglist[cdw->cdw_sg_index].addr;
774                         cdw->cdw_sg_len = ctl_sglist[cdw->cdw_sg_index].len;
775                 }
776                 KASSERT(off <= len, ("len > off"));
777                 copy_len = len - off;
778                 if (copy_len > cdw->cdw_sg_len)
779                         copy_len = cdw->cdw_sg_len;
780
781                 icl_pdu_get_data(request, off, cdw->cdw_sg_addr, copy_len);
782                 cdw->cdw_sg_addr += copy_len;
783                 cdw->cdw_sg_len -= copy_len;
784                 off += copy_len;
785                 io->scsiio.ext_data_filled += copy_len;
786
787                 if (cdw->cdw_sg_len == 0) {
788                         /*
789                          * End of current segment.
790                          */
791                         if (cdw->cdw_sg_index == ctl_sg_count - 1) {
792                                 /*
793                                  * Last segment in scatter/gather list.
794                                  */
795                                 break;
796                         }
797                         cdw->cdw_sg_index++;
798                 }
799
800                 if (off == len) {
801                         /*
802                          * End of PDU payload.
803                          */
804                         break;
805                 }
806         }
807
808         if (len > off) {
809                 /*
810                  * In case of unsolicited data, it's possible that the buffer
811                  * provided by CTL is smaller than negotiated FirstBurstLength.
812                  * Just ignore the superfluous data; will ask for them with R2T
813                  * on next call to cfiscsi_datamove().
814                  *
815                  * This obviously can only happen with SCSI Command PDU. 
816                  */
817                 if ((request->ip_bhs->bhs_opcode & ~ISCSI_BHS_OPCODE_IMMEDIATE) ==
818                     ISCSI_BHS_OPCODE_SCSI_COMMAND)
819                         return (true);
820
821                 CFISCSI_SESSION_WARN(cs, "received too much data: got %zd bytes, "
822                     "expected %zd; dropping connection",
823                     icl_pdu_data_segment_length(request), off);
824                 ctl_set_data_phase_error(&io->scsiio);
825                 cfiscsi_session_terminate(cs);
826                 return (true);
827         }
828
829         if (io->scsiio.ext_data_filled == io->scsiio.kern_data_len &&
830             (bhsdo->bhsdo_flags & BHSDO_FLAGS_F) == 0) {
831                 CFISCSI_SESSION_WARN(cs, "got the final packet without "
832                     "the F flag; flags = 0x%x; dropping connection",
833                     bhsdo->bhsdo_flags);
834                 ctl_set_data_phase_error(&io->scsiio);
835                 cfiscsi_session_terminate(cs);
836                 return (true);
837         }
838
839         if (io->scsiio.ext_data_filled != io->scsiio.kern_data_len &&
840             (bhsdo->bhsdo_flags & BHSDO_FLAGS_F) != 0) {
841                 if ((request->ip_bhs->bhs_opcode & ~ISCSI_BHS_OPCODE_IMMEDIATE) ==
842                     ISCSI_BHS_OPCODE_SCSI_DATA_OUT) {
843                         CFISCSI_SESSION_WARN(cs, "got the final packet, but the "
844                             "transmitted size was %zd bytes instead of %d; "
845                             "dropping connection",
846                             (size_t)io->scsiio.ext_data_filled,
847                             io->scsiio.kern_data_len);
848                         ctl_set_data_phase_error(&io->scsiio);
849                         cfiscsi_session_terminate(cs);
850                         return (true);
851                 } else {
852                         /*
853                          * For SCSI Command PDU, this just means we need to
854                          * solicit more data by sending R2T.
855                          */
856                         return (false);
857                 }
858         }
859
860         if (io->scsiio.ext_data_filled == io->scsiio.kern_data_len) {
861 #if 0
862                 CFISCSI_SESSION_DEBUG(cs, "no longer expecting Data-Out with target "
863                     "transfer tag 0x%x", cdw->cdw_target_transfer_tag);
864 #endif
865
866                 return (true);
867         }
868
869         return (false);
870 }
871
872 static void
873 cfiscsi_pdu_handle_data_out(struct icl_pdu *request)
874 {
875         struct iscsi_bhs_data_out *bhsdo;
876         struct cfiscsi_session *cs;
877         struct cfiscsi_data_wait *cdw = NULL;
878         union ctl_io *io;
879         bool done;
880
881         cs = PDU_SESSION(request);
882         bhsdo = (struct iscsi_bhs_data_out *)request->ip_bhs;
883
884         CFISCSI_SESSION_LOCK(cs);
885         TAILQ_FOREACH(cdw, &cs->cs_waiting_for_data_out, cdw_next) {
886 #if 0
887                 CFISCSI_SESSION_DEBUG(cs, "have ttt 0x%x, itt 0x%x; looking for "
888                     "ttt 0x%x, itt 0x%x",
889                     bhsdo->bhsdo_target_transfer_tag,
890                     bhsdo->bhsdo_initiator_task_tag,
891                     cdw->cdw_target_transfer_tag, cdw->cdw_initiator_task_tag));
892 #endif
893                 if (bhsdo->bhsdo_target_transfer_tag ==
894                     cdw->cdw_target_transfer_tag)
895                         break;
896         }
897         CFISCSI_SESSION_UNLOCK(cs);
898         if (cdw == NULL) {
899                 CFISCSI_SESSION_WARN(cs, "data transfer tag 0x%x, initiator task tag "
900                     "0x%x, not found; dropping connection",
901                     bhsdo->bhsdo_target_transfer_tag, bhsdo->bhsdo_initiator_task_tag);
902                 icl_pdu_free(request);
903                 cfiscsi_session_terminate(cs);
904                 return;
905         }
906
907         io = cdw->cdw_ctl_io;
908         KASSERT((io->io_hdr.flags & CTL_FLAG_DATA_MASK) != CTL_FLAG_DATA_IN,
909             ("CTL_FLAG_DATA_IN"));
910
911         done = cfiscsi_handle_data_segment(request, cdw);
912         if (done) {
913                 CFISCSI_SESSION_LOCK(cs);
914                 TAILQ_REMOVE(&cs->cs_waiting_for_data_out, cdw, cdw_next);
915                 CFISCSI_SESSION_UNLOCK(cs);
916                 uma_zfree(cfiscsi_data_wait_zone, cdw);
917                 io->scsiio.be_move_done(io);
918         }
919
920         icl_pdu_free(request);
921 }
922
923 static void
924 cfiscsi_pdu_handle_logout_request(struct icl_pdu *request)
925 {
926         struct iscsi_bhs_logout_request *bhslr;
927         struct iscsi_bhs_logout_response *bhslr2;
928         struct icl_pdu *response;
929         struct cfiscsi_session *cs;
930
931         cs = PDU_SESSION(request);
932         bhslr = (struct iscsi_bhs_logout_request *)request->ip_bhs;
933         switch (bhslr->bhslr_reason & 0x7f) {
934         case BHSLR_REASON_CLOSE_SESSION:
935         case BHSLR_REASON_CLOSE_CONNECTION:
936                 response = cfiscsi_pdu_new_response(request, M_NOWAIT);
937                 if (response == NULL) {
938                         CFISCSI_SESSION_DEBUG(cs, "failed to allocate memory");
939                         icl_pdu_free(request);
940                         cfiscsi_session_terminate(cs);
941                         return;
942                 }
943                 bhslr2 = (struct iscsi_bhs_logout_response *)response->ip_bhs;
944                 bhslr2->bhslr_opcode = ISCSI_BHS_OPCODE_LOGOUT_RESPONSE;
945                 bhslr2->bhslr_flags = 0x80;
946                 bhslr2->bhslr_response = BHSLR_RESPONSE_CLOSED_SUCCESSFULLY;
947                 bhslr2->bhslr_initiator_task_tag =
948                     bhslr->bhslr_initiator_task_tag;
949                 icl_pdu_free(request);
950                 cfiscsi_pdu_queue(response);
951                 cfiscsi_session_terminate(cs);
952                 break;
953         case BHSLR_REASON_REMOVE_FOR_RECOVERY:
954                 response = cfiscsi_pdu_new_response(request, M_NOWAIT);
955                 if (response == NULL) {
956                         CFISCSI_SESSION_WARN(cs,
957                             "failed to allocate memory; dropping connection");
958                         icl_pdu_free(request);
959                         cfiscsi_session_terminate(cs);
960                         return;
961                 }
962                 bhslr2 = (struct iscsi_bhs_logout_response *)response->ip_bhs;
963                 bhslr2->bhslr_opcode = ISCSI_BHS_OPCODE_LOGOUT_RESPONSE;
964                 bhslr2->bhslr_flags = 0x80;
965                 bhslr2->bhslr_response = BHSLR_RESPONSE_RECOVERY_NOT_SUPPORTED;
966                 bhslr2->bhslr_initiator_task_tag =
967                     bhslr->bhslr_initiator_task_tag;
968                 icl_pdu_free(request);
969                 cfiscsi_pdu_queue(response);
970                 break;
971         default:
972                 CFISCSI_SESSION_WARN(cs, "invalid reason 0%x; dropping connection",
973                     bhslr->bhslr_reason);
974                 icl_pdu_free(request);
975                 cfiscsi_session_terminate(cs);
976                 break;
977         }
978 }
979
980 static void
981 cfiscsi_callout(void *context)
982 {
983         struct icl_pdu *cp;
984         struct iscsi_bhs_nop_in *bhsni;
985         struct cfiscsi_session *cs;
986
987         cs = context;
988
989         if (cs->cs_terminating) 
990                 return;
991
992         callout_schedule(&cs->cs_callout, 1 * hz);
993
994         atomic_add_int(&cs->cs_timeout, 1);
995
996 #ifdef ICL_KERNEL_PROXY
997         if (cs->cs_waiting_for_ctld || cs->cs_login_phase) {
998                 if (cs->cs_timeout > login_timeout) {
999                         CFISCSI_SESSION_WARN(cs, "login timed out after "
1000                             "%d seconds; dropping connection", cs->cs_timeout);
1001                         cfiscsi_session_terminate(cs);
1002                 }
1003                 return;
1004         }
1005 #endif
1006
1007         if (cs->cs_timeout >= ping_timeout) {
1008                 CFISCSI_SESSION_WARN(cs, "no ping reply (NOP-Out) after %d seconds; "
1009                     "dropping connection",  ping_timeout);
1010                 cfiscsi_session_terminate(cs);
1011                 return;
1012         }
1013
1014         /*
1015          * If the ping was reset less than one second ago - which means
1016          * that we've received some PDU during the last second - assume
1017          * the traffic flows correctly and don't bother sending a NOP-Out.
1018          *
1019          * (It's 2 - one for one second, and one for incrementing is_timeout
1020          * earlier in this routine.)
1021          */
1022         if (cs->cs_timeout < 2)
1023                 return;
1024
1025         cp = icl_pdu_new_bhs(cs->cs_conn, M_NOWAIT);
1026         if (cp == NULL) {
1027                 CFISCSI_SESSION_WARN(cs, "failed to allocate memory");
1028                 return;
1029         }
1030         bhsni = (struct iscsi_bhs_nop_in *)cp->ip_bhs;
1031         bhsni->bhsni_opcode = ISCSI_BHS_OPCODE_NOP_IN;
1032         bhsni->bhsni_flags = 0x80;
1033         bhsni->bhsni_initiator_task_tag = 0xffffffff;
1034
1035         cfiscsi_pdu_queue(cp);
1036 }
1037
1038 static void
1039 cfiscsi_session_terminate_tasks(struct cfiscsi_session *cs)
1040 {
1041         struct cfiscsi_data_wait *cdw, *tmpcdw;
1042         union ctl_io *io;
1043         int error, last;
1044
1045 #ifdef notyet
1046         io = ctl_alloc_io(cs->cs_target->ct_softc->fe.ctl_pool_ref);
1047         if (io == NULL) {
1048                 CFISCSI_SESSION_WARN(cs, "can't allocate ctl_io");
1049                 return;
1050         }
1051         ctl_zero_io(io);
1052         io->io_hdr.ctl_private[CTL_PRIV_FRONTEND].ptr = NULL;
1053         io->io_hdr.io_type = CTL_IO_TASK;
1054         io->io_hdr.nexus.initid.id = cs->cs_ctl_initid;
1055         io->io_hdr.nexus.targ_port = cs->cs_target->ct_softc->fe.targ_port;
1056         io->io_hdr.nexus.targ_target.id = 0;
1057         io->io_hdr.nexus.targ_lun = lun;
1058         io->taskio.tag_type = CTL_TAG_SIMPLE; /* XXX */
1059         io->taskio.task_action = CTL_TASK_ABORT_TASK_SET;
1060         error = ctl_queue(io);
1061         if (error != CTL_RETVAL_COMPLETE) {
1062                 CFISCSI_SESSION_WARN(cs, "ctl_queue() failed; error %d", error);
1063                 ctl_free_io(io);
1064         }
1065 #else
1066         /*
1067          * CTL doesn't currently support CTL_TASK_ABORT_TASK_SET, so instead
1068          * just iterate over tasks that are waiting for something - data - and
1069          * terminate those.
1070          */
1071         CFISCSI_SESSION_LOCK(cs);
1072         TAILQ_FOREACH_SAFE(cdw,
1073             &cs->cs_waiting_for_data_out, cdw_next, tmpcdw) {
1074                 io = ctl_alloc_io(cs->cs_target->ct_softc->fe.ctl_pool_ref);
1075                 if (io == NULL) {
1076                         CFISCSI_SESSION_WARN(cs, "can't allocate ctl_io");
1077                         return;
1078                 }
1079                 ctl_zero_io(io);
1080                 io->io_hdr.ctl_private[CTL_PRIV_FRONTEND].ptr = NULL;
1081                 io->io_hdr.io_type = CTL_IO_TASK;
1082                 io->io_hdr.nexus.initid.id = cs->cs_ctl_initid;
1083                 io->io_hdr.nexus.targ_port =
1084                     cs->cs_target->ct_softc->fe.targ_port;
1085                 io->io_hdr.nexus.targ_target.id = 0;
1086                 //io->io_hdr.nexus.targ_lun = lun; /* Not needed? */
1087                 io->taskio.tag_type = CTL_TAG_SIMPLE; /* XXX */
1088                 io->taskio.task_action = CTL_TASK_ABORT_TASK;
1089                 io->taskio.tag_num = cdw->cdw_initiator_task_tag;
1090                 error = ctl_queue(io);
1091                 if (error != CTL_RETVAL_COMPLETE) {
1092                         CFISCSI_SESSION_WARN(cs, "ctl_queue() failed; error %d", error);
1093                         ctl_free_io(io);
1094                         return;
1095                 }
1096 #if 0
1097                 CFISCSI_SESSION_DEBUG(cs, "removing csw for initiator task tag "
1098                     "0x%x", cdw->cdw_initiator_task_tag);
1099 #endif
1100                 /*
1101                  * Set nonzero port status; this prevents backends from
1102                  * assuming that the data transfer actually succeeded
1103                  * and writing uninitialized data to disk.
1104                  */
1105                 cdw->cdw_ctl_io->scsiio.io_hdr.port_status = 42;
1106                 cdw->cdw_ctl_io->scsiio.be_move_done(cdw->cdw_ctl_io);
1107                 TAILQ_REMOVE(&cs->cs_waiting_for_data_out, cdw, cdw_next);
1108                 uma_zfree(cfiscsi_data_wait_zone, cdw);
1109         }
1110         CFISCSI_SESSION_UNLOCK(cs);
1111 #endif
1112
1113         /*
1114          * Wait for CTL to terminate all the tasks.
1115          */
1116         for (;;) {
1117                 refcount_acquire(&cs->cs_outstanding_ctl_pdus);
1118                 last = refcount_release(&cs->cs_outstanding_ctl_pdus);
1119                 if (last != 0)
1120                         break;
1121                 CFISCSI_SESSION_WARN(cs, "waiting for CTL to terminate tasks, "
1122                     "%d remaining", cs->cs_outstanding_ctl_pdus);
1123                 pause("cfiscsi_terminate", 1);
1124         }
1125 }
1126
1127 static void
1128 cfiscsi_maintenance_thread(void *arg)
1129 {
1130         struct cfiscsi_session *cs;
1131
1132         cs = arg;
1133
1134         for (;;) {
1135                 CFISCSI_SESSION_LOCK(cs);
1136                 if (cs->cs_terminating == false)
1137                         cv_wait(&cs->cs_maintenance_cv, &cs->cs_lock);
1138                 CFISCSI_SESSION_UNLOCK(cs);
1139
1140                 if (cs->cs_terminating) {
1141
1142                         /*
1143                          * We used to wait up to 30 seconds to deliver queued
1144                          * PDUs to the initiator.  We also tried hard to deliver
1145                          * SCSI Responses for the aborted PDUs.  We don't do
1146                          * that anymore.  We might need to revisit that.
1147                          */
1148                         callout_drain(&cs->cs_callout);
1149                         icl_conn_shutdown(cs->cs_conn);
1150                         icl_conn_close(cs->cs_conn);
1151
1152                         /*
1153                          * At this point ICL receive thread is no longer
1154                          * running; no new tasks can be queued.
1155                          */
1156                         cfiscsi_session_terminate_tasks(cs);
1157                         cfiscsi_session_delete(cs);
1158                         kthread_exit();
1159                         return;
1160                 }
1161                 CFISCSI_SESSION_DEBUG(cs, "nothing to do");
1162         }
1163 }
1164
1165 static void
1166 cfiscsi_session_terminate(struct cfiscsi_session *cs)
1167 {
1168
1169         if (cs->cs_terminating)
1170                 return;
1171         cs->cs_terminating = true;
1172         cv_signal(&cs->cs_maintenance_cv);
1173 #ifdef ICL_KERNEL_PROXY
1174         cv_signal(&cs->cs_login_cv);
1175 #endif
1176 }
1177
1178 static int
1179 cfiscsi_session_register_initiator(struct cfiscsi_session *cs)
1180 {
1181         int error, i;
1182         struct cfiscsi_softc *softc;
1183
1184         KASSERT(cs->cs_ctl_initid == -1, ("already registered"));
1185
1186         softc = &cfiscsi_softc;
1187
1188         mtx_lock(&softc->lock);
1189         for (i = 0; i < softc->max_initiators; i++) {
1190                 if (softc->ctl_initids[i] == 0)
1191                         break;
1192         }
1193         if (i == softc->max_initiators) {
1194                 CFISCSI_SESSION_WARN(cs, "too many concurrent sessions (%d)",
1195                     softc->max_initiators);
1196                 mtx_unlock(&softc->lock);
1197                 return (1);
1198         }
1199         softc->ctl_initids[i] = 1;
1200         mtx_unlock(&softc->lock);
1201
1202 #if 0
1203         CFISCSI_SESSION_DEBUG(cs, "adding initiator id %d, max %d",
1204             i, softc->max_initiators);
1205 #endif
1206         cs->cs_ctl_initid = i;
1207         error = ctl_add_initiator(0x0, softc->fe.targ_port, cs->cs_ctl_initid);
1208         if (error != 0) {
1209                 CFISCSI_SESSION_WARN(cs, "ctl_add_initiator failed with error %d", error);
1210                 mtx_lock(&softc->lock);
1211                 softc->ctl_initids[cs->cs_ctl_initid] = 0;
1212                 mtx_unlock(&softc->lock);
1213                 cs->cs_ctl_initid = -1;
1214                 return (1);
1215         }
1216
1217         return (0);
1218 }
1219
1220 static void
1221 cfiscsi_session_unregister_initiator(struct cfiscsi_session *cs)
1222 {
1223         int error;
1224         struct cfiscsi_softc *softc;
1225
1226         if (cs->cs_ctl_initid == -1)
1227                 return;
1228
1229         softc = &cfiscsi_softc;
1230
1231         error = ctl_remove_initiator(softc->fe.targ_port, cs->cs_ctl_initid);
1232         if (error != 0) {
1233                 CFISCSI_SESSION_WARN(cs, "ctl_remove_initiator failed with error %d",
1234                     error);
1235         }
1236         mtx_lock(&softc->lock);
1237         softc->ctl_initids[cs->cs_ctl_initid] = 0;
1238         mtx_unlock(&softc->lock);
1239         cs->cs_ctl_initid = -1;
1240 }
1241
1242 static struct cfiscsi_session *
1243 cfiscsi_session_new(struct cfiscsi_softc *softc)
1244 {
1245         struct cfiscsi_session *cs;
1246         int error;
1247
1248         cs = malloc(sizeof(*cs), M_CFISCSI, M_NOWAIT | M_ZERO);
1249         if (cs == NULL) {
1250                 CFISCSI_WARN("malloc failed");
1251                 return (NULL);
1252         }
1253         cs->cs_ctl_initid = -1;
1254
1255         refcount_init(&cs->cs_outstanding_ctl_pdus, 0);
1256         TAILQ_INIT(&cs->cs_waiting_for_data_out);
1257         mtx_init(&cs->cs_lock, "cfiscsi_lock", NULL, MTX_DEF);
1258         cv_init(&cs->cs_maintenance_cv, "cfiscsi_mt");
1259 #ifdef ICL_KERNEL_PROXY
1260         cv_init(&cs->cs_login_cv, "cfiscsi_login");
1261 #endif
1262
1263         cs->cs_conn = icl_conn_new("cfiscsi", &cs->cs_lock);
1264         cs->cs_conn->ic_receive = cfiscsi_receive_callback;
1265         cs->cs_conn->ic_error = cfiscsi_error_callback;
1266         cs->cs_conn->ic_prv0 = cs;
1267
1268         error = kthread_add(cfiscsi_maintenance_thread, cs, NULL, NULL, 0, 0, "cfiscsimt");
1269         if (error != 0) {
1270                 CFISCSI_SESSION_WARN(cs, "kthread_add(9) failed with error %d", error);
1271                 free(cs, M_CFISCSI);
1272                 return (NULL);
1273         }
1274
1275         mtx_lock(&softc->lock);
1276         cs->cs_id = softc->last_session_id + 1;
1277         softc->last_session_id++;
1278         mtx_unlock(&softc->lock);
1279
1280         mtx_lock(&softc->lock);
1281         TAILQ_INSERT_TAIL(&softc->sessions, cs, cs_next);
1282         mtx_unlock(&softc->lock);
1283
1284         /*
1285          * Start pinging the initiator.
1286          */
1287         callout_init(&cs->cs_callout, 1);
1288         callout_reset(&cs->cs_callout, 1 * hz, cfiscsi_callout, cs);
1289
1290         return (cs);
1291 }
1292
1293 static void
1294 cfiscsi_session_delete(struct cfiscsi_session *cs)
1295 {
1296         struct cfiscsi_softc *softc;
1297
1298         softc = &cfiscsi_softc;
1299
1300         KASSERT(cs->cs_outstanding_ctl_pdus == 0,
1301             ("destroying session with outstanding CTL pdus"));
1302         KASSERT(TAILQ_EMPTY(&cs->cs_waiting_for_data_out),
1303             ("destroying session with non-empty queue"));
1304
1305         cfiscsi_session_unregister_initiator(cs);
1306         if (cs->cs_target != NULL)
1307                 cfiscsi_target_release(cs->cs_target);
1308         icl_conn_close(cs->cs_conn);
1309         icl_conn_free(cs->cs_conn);
1310
1311         mtx_lock(&softc->lock);
1312         TAILQ_REMOVE(&softc->sessions, cs, cs_next);
1313         mtx_unlock(&softc->lock);
1314
1315         free(cs, M_CFISCSI);
1316 }
1317
1318 int
1319 cfiscsi_init(void)
1320 {
1321         struct cfiscsi_softc *softc;
1322         struct ctl_frontend *fe;
1323         int retval;
1324
1325         softc = &cfiscsi_softc;
1326         retval = 0;
1327         bzero(softc, sizeof(*softc));
1328         mtx_init(&softc->lock, "cfiscsi", NULL, MTX_DEF);
1329
1330 #ifdef ICL_KERNEL_PROXY
1331         cv_init(&softc->accept_cv, "cfiscsi_accept");
1332 #endif
1333         TAILQ_INIT(&softc->sessions);
1334         TAILQ_INIT(&softc->targets);
1335
1336         fe = &softc->fe;
1337         fe->port_type = CTL_PORT_ISCSI;
1338         /* XXX KDM what should the real number be here? */
1339         fe->num_requested_ctl_io = 4096;
1340         snprintf(softc->port_name, sizeof(softc->port_name), "iscsi");
1341         fe->port_name = softc->port_name;
1342         fe->port_online = cfiscsi_online;
1343         fe->port_offline = cfiscsi_offline;
1344         fe->onoff_arg = softc;
1345         fe->targ_enable = cfiscsi_targ_enable;
1346         fe->targ_disable = cfiscsi_targ_disable;
1347         fe->lun_enable = cfiscsi_lun_enable;
1348         fe->lun_disable = cfiscsi_lun_disable;
1349         fe->targ_lun_arg = softc;
1350         fe->ioctl = cfiscsi_ioctl;
1351         fe->devid = cfiscsi_devid;
1352         fe->fe_datamove = cfiscsi_datamove;
1353         fe->fe_done = cfiscsi_done;
1354
1355         /* XXX KDM what should we report here? */
1356         /* XXX These should probably be fetched from CTL. */
1357         fe->max_targets = 1;
1358         fe->max_target_id = 15;
1359
1360         retval = ctl_frontend_register(fe, /*master_SC*/ 1);
1361         if (retval != 0) {
1362                 CFISCSI_WARN("ctl_frontend_register() failed with error %d",
1363                     retval);
1364                 retval = 1;
1365                 goto bailout;
1366         }
1367
1368         softc->max_initiators = fe->max_initiators;
1369
1370         cfiscsi_data_wait_zone = uma_zcreate("cfiscsi_data_wait",
1371             sizeof(struct cfiscsi_data_wait), NULL, NULL, NULL, NULL,
1372             UMA_ALIGN_PTR, 0);
1373
1374         return (0);
1375
1376 bailout:
1377         return (retval);
1378 }
1379
1380 static int
1381 cfiscsi_module_event_handler(module_t mod, int what, void *arg)
1382 {
1383
1384         switch (what) {
1385         case MOD_LOAD:
1386                 return (cfiscsi_init());
1387         case MOD_UNLOAD:
1388                 return (EBUSY);
1389         default:
1390                 return (EOPNOTSUPP);
1391         }
1392 }
1393
1394 #ifdef ICL_KERNEL_PROXY
1395 static void
1396 cfiscsi_accept(struct socket *so, struct sockaddr *sa, int portal_id)
1397 {
1398         struct cfiscsi_session *cs;
1399
1400         cs = cfiscsi_session_new(&cfiscsi_softc);
1401         if (cs == NULL) {
1402                 CFISCSI_WARN("failed to create session");
1403                 return;
1404         }
1405
1406         icl_conn_handoff_sock(cs->cs_conn, so);
1407         cs->cs_initiator_sa = sa;
1408         cs->cs_portal_id = portal_id;
1409         cs->cs_waiting_for_ctld = true;
1410         cv_signal(&cfiscsi_softc.accept_cv);
1411 }
1412 #endif
1413
1414 static void
1415 cfiscsi_online(void *arg)
1416 {
1417         struct cfiscsi_softc *softc;
1418
1419         softc = (struct cfiscsi_softc *)arg;
1420
1421         softc->online = 1;
1422 #ifdef ICL_KERNEL_PROXY
1423         if (softc->listener != NULL)
1424                 icl_listen_free(softc->listener);
1425         softc->listener = icl_listen_new(cfiscsi_accept);
1426 #endif
1427 }
1428
1429 static void
1430 cfiscsi_offline(void *arg)
1431 {
1432         struct cfiscsi_softc *softc;
1433         struct cfiscsi_session *cs;
1434
1435         softc = (struct cfiscsi_softc *)arg;
1436
1437         softc->online = 0;
1438
1439         mtx_lock(&softc->lock);
1440         TAILQ_FOREACH(cs, &softc->sessions, cs_next)
1441                 cfiscsi_session_terminate(cs);
1442         mtx_unlock(&softc->lock);
1443
1444 #ifdef ICL_KERNEL_PROXY
1445         icl_listen_free(softc->listener);
1446         softc->listener = NULL;
1447 #endif
1448 }
1449
1450 static int
1451 cfiscsi_targ_enable(void *arg, struct ctl_id targ_id)
1452 {
1453
1454         return (0);
1455 }
1456
1457 static int
1458 cfiscsi_targ_disable(void *arg, struct ctl_id targ_id)
1459 {
1460
1461         return (0);
1462 }
1463
1464 static void
1465 cfiscsi_ioctl_handoff(struct ctl_iscsi *ci)
1466 {
1467         struct cfiscsi_softc *softc;
1468         struct cfiscsi_session *cs;
1469         struct cfiscsi_target *ct;
1470         struct ctl_iscsi_handoff_params *cihp;
1471         int error;
1472
1473         cihp = (struct ctl_iscsi_handoff_params *)&(ci->data);
1474         softc = &cfiscsi_softc;
1475
1476         CFISCSI_DEBUG("new connection from %s (%s) to %s",
1477             cihp->initiator_name, cihp->initiator_addr,
1478             cihp->target_name);
1479
1480         if (softc->online == 0) {
1481                 ci->status = CTL_ISCSI_ERROR;
1482                 snprintf(ci->error_str, sizeof(ci->error_str),
1483                     "%s: port offline", __func__);
1484                 return;
1485         }
1486
1487         ct = cfiscsi_target_find(softc, cihp->target_name);
1488         if (ct == NULL) {
1489                 ci->status = CTL_ISCSI_ERROR;
1490                 snprintf(ci->error_str, sizeof(ci->error_str),
1491                     "%s: target not found", __func__);
1492                 return;
1493         }
1494
1495 #ifdef ICL_KERNEL_PROXY
1496         if (cihp->socket > 0 && cihp->connection_id > 0) {
1497                 snprintf(ci->error_str, sizeof(ci->error_str),
1498                     "both socket and connection_id set");
1499                 ci->status = CTL_ISCSI_ERROR;
1500                 cfiscsi_target_release(ct);
1501                 return;
1502         }
1503         if (cihp->socket == 0) {
1504                 mtx_lock(&cfiscsi_softc.lock);
1505                 TAILQ_FOREACH(cs, &cfiscsi_softc.sessions, cs_next) {
1506                         if (cs->cs_id == cihp->socket)
1507                                 break;
1508                 }
1509                 if (cs == NULL) {
1510                         mtx_unlock(&cfiscsi_softc.lock);
1511                         snprintf(ci->error_str, sizeof(ci->error_str),
1512                             "connection not found");
1513                         ci->status = CTL_ISCSI_ERROR;
1514                         cfiscsi_target_release(ct);
1515                         return;
1516                 }
1517                 mtx_unlock(&cfiscsi_softc.lock);
1518         } else {
1519 #endif
1520                 cs = cfiscsi_session_new(softc);
1521                 if (cs == NULL) {
1522                         ci->status = CTL_ISCSI_ERROR;
1523                         snprintf(ci->error_str, sizeof(ci->error_str),
1524                             "%s: cfiscsi_session_new failed", __func__);
1525                         cfiscsi_target_release(ct);
1526                         return;
1527                 }
1528 #ifdef ICL_KERNEL_PROXY
1529         }
1530 #endif
1531         cs->cs_target = ct;
1532
1533         /*
1534          * First PDU of Full Feature phase has the same CmdSN as the last
1535          * PDU from the Login Phase received from the initiator.  Thus,
1536          * the -1 below.
1537          */
1538         cs->cs_portal_group_tag = cihp->portal_group_tag;
1539         cs->cs_cmdsn = cihp->cmdsn;
1540         cs->cs_statsn = cihp->statsn;
1541         cs->cs_max_data_segment_length = cihp->max_recv_data_segment_length;
1542         cs->cs_max_burst_length = cihp->max_burst_length;
1543         cs->cs_immediate_data = !!cihp->immediate_data;
1544         if (cihp->header_digest == CTL_ISCSI_DIGEST_CRC32C)
1545                 cs->cs_conn->ic_header_crc32c = true;
1546         if (cihp->data_digest == CTL_ISCSI_DIGEST_CRC32C)
1547                 cs->cs_conn->ic_data_crc32c = true;
1548
1549         strlcpy(cs->cs_initiator_name,
1550             cihp->initiator_name, sizeof(cs->cs_initiator_name));
1551         strlcpy(cs->cs_initiator_addr,
1552             cihp->initiator_addr, sizeof(cs->cs_initiator_addr));
1553         strlcpy(cs->cs_initiator_alias,
1554             cihp->initiator_alias, sizeof(cs->cs_initiator_alias));
1555
1556 #ifdef ICL_KERNEL_PROXY
1557         if (cihp->socket > 0) {
1558 #endif
1559                 error = icl_conn_handoff(cs->cs_conn, cihp->socket);
1560                 if (error != 0) {
1561                         cfiscsi_session_delete(cs);
1562                         ci->status = CTL_ISCSI_ERROR;
1563                         snprintf(ci->error_str, sizeof(ci->error_str),
1564                             "%s: icl_conn_handoff failed with error %d",
1565                             __func__, error);
1566                         return;
1567                 }
1568 #ifdef ICL_KERNEL_PROXY
1569         }
1570 #endif
1571
1572         /*
1573          * Register initiator with CTL.
1574          */
1575         cfiscsi_session_register_initiator(cs);
1576
1577 #ifdef ICL_KERNEL_PROXY
1578         cs->cs_login_phase = false;
1579
1580         /*
1581          * First PDU of the Full Feature phase has likely already arrived.
1582          * We have to pick it up and execute properly.
1583          */
1584         if (cs->cs_login_pdu != NULL) {
1585                 CFISCSI_SESSION_DEBUG(cs, "picking up first PDU");
1586                 cfiscsi_pdu_handle(cs->cs_login_pdu);
1587                 cs->cs_login_pdu = NULL;
1588         }
1589 #endif
1590
1591         ci->status = CTL_ISCSI_OK;
1592 }
1593
1594 static void
1595 cfiscsi_ioctl_list(struct ctl_iscsi *ci)
1596 {
1597         struct ctl_iscsi_list_params *cilp;
1598         struct cfiscsi_session *cs;
1599         struct cfiscsi_softc *softc;
1600         struct sbuf *sb;
1601         int error;
1602
1603         cilp = (struct ctl_iscsi_list_params *)&(ci->data);
1604         softc = &cfiscsi_softc;
1605
1606         sb = sbuf_new(NULL, NULL, cilp->alloc_len, SBUF_FIXEDLEN);
1607         if (sb == NULL) {
1608                 ci->status = CTL_ISCSI_ERROR;
1609                 snprintf(ci->error_str, sizeof(ci->error_str),
1610                     "Unable to allocate %d bytes for iSCSI session list",
1611                     cilp->alloc_len);
1612                 return;
1613         }
1614
1615         sbuf_printf(sb, "<ctlislist>\n");
1616         mtx_lock(&softc->lock);
1617         TAILQ_FOREACH(cs, &softc->sessions, cs_next) {
1618 #ifdef ICL_KERNEL_PROXY
1619                 if (cs->cs_target == NULL)
1620                         continue;
1621 #endif
1622                 error = sbuf_printf(sb, "<connection id=\"%d\">"
1623                     "<initiator>%s</initiator>"
1624                     "<initiator_addr>%s</initiator_addr>"
1625                     "<initiator_alias>%s</initiator_alias>"
1626                     "<target>%s</target>"
1627                     "<target_alias>%s</target_alias>"
1628                     "<header_digest>%s</header_digest>"
1629                     "<data_digest>%s</data_digest>"
1630                     "<max_data_segment_length>%zd</max_data_segment_length>"
1631                     "<immediate_data>%d</immediate_data>"
1632                     "<iser>%d</iser>"
1633                     "</connection>\n",
1634                     cs->cs_id,
1635                     cs->cs_initiator_name, cs->cs_initiator_addr, cs->cs_initiator_alias,
1636                     cs->cs_target->ct_name, cs->cs_target->ct_alias,
1637                     cs->cs_conn->ic_header_crc32c ? "CRC32C" : "None",
1638                     cs->cs_conn->ic_data_crc32c ? "CRC32C" : "None",
1639                     cs->cs_max_data_segment_length,
1640                     cs->cs_immediate_data,
1641                     cs->cs_conn->ic_iser);
1642                 if (error != 0)
1643                         break;
1644         }
1645         mtx_unlock(&softc->lock);
1646         error = sbuf_printf(sb, "</ctlislist>\n");
1647         if (error != 0) {
1648                 sbuf_delete(sb);
1649                 ci->status = CTL_ISCSI_LIST_NEED_MORE_SPACE;
1650                 snprintf(ci->error_str, sizeof(ci->error_str),
1651                     "Out of space, %d bytes is too small", cilp->alloc_len);
1652                 return;
1653         }
1654         sbuf_finish(sb);
1655
1656         error = copyout(sbuf_data(sb), cilp->conn_xml, sbuf_len(sb) + 1);
1657         cilp->fill_len = sbuf_len(sb) + 1;
1658         ci->status = CTL_ISCSI_OK;
1659         sbuf_delete(sb);
1660 }
1661
1662 static void
1663 cfiscsi_ioctl_terminate(struct ctl_iscsi *ci)
1664 {
1665         struct icl_pdu *response;
1666         struct iscsi_bhs_asynchronous_message *bhsam;
1667         struct ctl_iscsi_terminate_params *citp;
1668         struct cfiscsi_session *cs;
1669         struct cfiscsi_softc *softc;
1670         int found = 0;
1671
1672         citp = (struct ctl_iscsi_terminate_params *)&(ci->data);
1673         softc = &cfiscsi_softc;
1674
1675         mtx_lock(&softc->lock);
1676         TAILQ_FOREACH(cs, &softc->sessions, cs_next) {
1677                 if (citp->all == 0 && cs->cs_id != citp->connection_id &&
1678                     strcmp(cs->cs_initiator_name, citp->initiator_name) != 0 &&
1679                     strcmp(cs->cs_initiator_addr, citp->initiator_addr) != 0)
1680                         continue;
1681
1682                 response = icl_pdu_new_bhs(cs->cs_conn, M_NOWAIT);
1683                 if (response == NULL) {
1684                         /*
1685                          * Oh well.  Just terminate the connection.
1686                          */
1687                 } else {
1688                         bhsam = (struct iscsi_bhs_asynchronous_message *)
1689                             response->ip_bhs;
1690                         bhsam->bhsam_opcode = ISCSI_BHS_OPCODE_ASYNC_MESSAGE;
1691                         bhsam->bhsam_flags = 0x80;
1692                         bhsam->bhsam_0xffffffff = 0xffffffff;
1693                         bhsam->bhsam_async_event =
1694                             BHSAM_EVENT_TARGET_TERMINATES_SESSION;
1695                         cfiscsi_pdu_queue(response);
1696                 }
1697                 cfiscsi_session_terminate(cs);
1698                 found++;
1699         }
1700         mtx_unlock(&softc->lock);
1701
1702         if (found == 0) {
1703                 ci->status = CTL_ISCSI_SESSION_NOT_FOUND;
1704                 snprintf(ci->error_str, sizeof(ci->error_str),
1705                     "No matching connections found");
1706                 return;
1707         }
1708
1709         ci->status = CTL_ISCSI_OK;
1710 }
1711
1712 static void
1713 cfiscsi_ioctl_logout(struct ctl_iscsi *ci)
1714 {
1715         struct icl_pdu *response;
1716         struct iscsi_bhs_asynchronous_message *bhsam;
1717         struct ctl_iscsi_logout_params *cilp;
1718         struct cfiscsi_session *cs;
1719         struct cfiscsi_softc *softc;
1720         int found = 0;
1721
1722         cilp = (struct ctl_iscsi_logout_params *)&(ci->data);
1723         softc = &cfiscsi_softc;
1724
1725         mtx_lock(&softc->lock);
1726         TAILQ_FOREACH(cs, &softc->sessions, cs_next) {
1727                 if (cilp->all == 0 && cs->cs_id != cilp->connection_id &&
1728                     strcmp(cs->cs_initiator_name, cilp->initiator_name) != 0 &&
1729                     strcmp(cs->cs_initiator_addr, cilp->initiator_addr) != 0)
1730                         continue;
1731
1732                 response = icl_pdu_new_bhs(cs->cs_conn, M_NOWAIT);
1733                 if (response == NULL) {
1734                         ci->status = CTL_ISCSI_ERROR;
1735                         snprintf(ci->error_str, sizeof(ci->error_str),
1736                             "Unable to allocate memory");
1737                         mtx_unlock(&softc->lock);
1738                         return;
1739                 }
1740                 bhsam =
1741                     (struct iscsi_bhs_asynchronous_message *)response->ip_bhs;
1742                 bhsam->bhsam_opcode = ISCSI_BHS_OPCODE_ASYNC_MESSAGE;
1743                 bhsam->bhsam_flags = 0x80;
1744                 bhsam->bhsam_async_event = BHSAM_EVENT_TARGET_REQUESTS_LOGOUT;
1745                 bhsam->bhsam_parameter3 = htons(10);
1746                 cfiscsi_pdu_queue(response);
1747                 found++;
1748         }
1749         mtx_unlock(&softc->lock);
1750
1751         if (found == 0) {
1752                 ci->status = CTL_ISCSI_SESSION_NOT_FOUND;
1753                 snprintf(ci->error_str, sizeof(ci->error_str),
1754                     "No matching connections found");
1755                 return;
1756         }
1757
1758         ci->status = CTL_ISCSI_OK;
1759 }
1760
1761 #ifdef ICL_KERNEL_PROXY
1762 static void
1763 cfiscsi_ioctl_listen(struct ctl_iscsi *ci)
1764 {
1765         struct ctl_iscsi_listen_params *cilp;
1766         struct sockaddr *sa;
1767         int error;
1768
1769         cilp = (struct ctl_iscsi_listen_params *)&(ci->data);
1770
1771         if (cfiscsi_softc.listener == NULL) {
1772                 CFISCSI_DEBUG("no listener");
1773                 snprintf(ci->error_str, sizeof(ci->error_str), "no listener");
1774                 ci->status = CTL_ISCSI_ERROR;
1775                 return;
1776         }
1777
1778         error = getsockaddr(&sa, (void *)cilp->addr, cilp->addrlen);
1779         if (error != 0) {
1780                 CFISCSI_DEBUG("getsockaddr, error %d", error);
1781                 snprintf(ci->error_str, sizeof(ci->error_str), "getsockaddr failed");
1782                 ci->status = CTL_ISCSI_ERROR;
1783                 return;
1784         }
1785
1786         error = icl_listen_add(cfiscsi_softc.listener, cilp->iser, cilp->domain,
1787             cilp->socktype, cilp->protocol, sa, cilp->portal_id);
1788         if (error != 0) {
1789                 free(sa, M_SONAME);
1790                 CFISCSI_DEBUG("icl_listen_add, error %d", error);
1791                 snprintf(ci->error_str, sizeof(ci->error_str),
1792                     "icl_listen_add failed, error %d", error);
1793                 ci->status = CTL_ISCSI_ERROR;
1794                 return;
1795         }
1796
1797         ci->status = CTL_ISCSI_OK;
1798 }
1799
1800 static void
1801 cfiscsi_ioctl_accept(struct ctl_iscsi *ci)
1802 {
1803         struct ctl_iscsi_accept_params *ciap;
1804         struct cfiscsi_session *cs;
1805         int error;
1806
1807         ciap = (struct ctl_iscsi_accept_params *)&(ci->data);
1808
1809         mtx_lock(&cfiscsi_softc.lock);
1810         for (;;) {
1811                 TAILQ_FOREACH(cs, &cfiscsi_softc.sessions, cs_next) {
1812                         if (cs->cs_waiting_for_ctld)
1813                                 break;
1814                 }
1815                 if (cs != NULL)
1816                         break;
1817                 error = cv_wait_sig(&cfiscsi_softc.accept_cv, &cfiscsi_softc.lock);
1818                 if (error != 0) {
1819                         mtx_unlock(&cfiscsi_softc.lock);
1820                         snprintf(ci->error_str, sizeof(ci->error_str), "interrupted");
1821                         ci->status = CTL_ISCSI_ERROR;
1822                         return;
1823                 }
1824         }
1825         mtx_unlock(&cfiscsi_softc.lock);
1826
1827         cs->cs_waiting_for_ctld = false;
1828         cs->cs_login_phase = true;
1829
1830         ciap->connection_id = cs->cs_id;
1831         ciap->portal_id = cs->cs_portal_id;
1832         ciap->initiator_addrlen = cs->cs_initiator_sa->sa_len;
1833         error = copyout(cs->cs_initiator_sa, ciap->initiator_addr,
1834             cs->cs_initiator_sa->sa_len);
1835         if (error != 0) {
1836                 snprintf(ci->error_str, sizeof(ci->error_str),
1837                     "copyout failed with error %d", error);
1838                 ci->status = CTL_ISCSI_ERROR;
1839                 return;
1840         }
1841
1842         ci->status = CTL_ISCSI_OK;
1843 }
1844
1845 static void
1846 cfiscsi_ioctl_send(struct ctl_iscsi *ci)
1847 {
1848         struct ctl_iscsi_send_params *cisp;
1849         struct cfiscsi_session *cs;
1850         struct icl_pdu *ip;
1851         size_t datalen;
1852         void *data;
1853         int error;
1854
1855         cisp = (struct ctl_iscsi_send_params *)&(ci->data);
1856
1857         mtx_lock(&cfiscsi_softc.lock);
1858         TAILQ_FOREACH(cs, &cfiscsi_softc.sessions, cs_next) {
1859                 if (cs->cs_id == cisp->connection_id)
1860                         break;
1861         }
1862         if (cs == NULL) {
1863                 mtx_unlock(&cfiscsi_softc.lock);
1864                 snprintf(ci->error_str, sizeof(ci->error_str), "connection not found");
1865                 ci->status = CTL_ISCSI_ERROR;
1866                 return;
1867         }
1868         mtx_unlock(&cfiscsi_softc.lock);
1869
1870 #if 0
1871         if (cs->cs_login_phase == false)
1872                 return (EBUSY);
1873 #endif
1874
1875         if (cs->cs_terminating) {
1876                 snprintf(ci->error_str, sizeof(ci->error_str), "connection is terminating");
1877                 ci->status = CTL_ISCSI_ERROR;
1878                 return;
1879         }
1880
1881         datalen = cisp->data_segment_len;
1882         /*
1883          * XXX
1884          */
1885         //if (datalen > CFISCSI_MAX_DATA_SEGMENT_LENGTH) {
1886         if (datalen > 65535) {
1887                 snprintf(ci->error_str, sizeof(ci->error_str), "data segment too big");
1888                 ci->status = CTL_ISCSI_ERROR;
1889                 return;
1890         }
1891         if (datalen > 0) {
1892                 data = malloc(datalen, M_CFISCSI, M_WAITOK);
1893                 error = copyin(cisp->data_segment, data, datalen);
1894                 if (error != 0) {
1895                         free(data, M_CFISCSI);
1896                         snprintf(ci->error_str, sizeof(ci->error_str), "copyin error %d", error);
1897                         ci->status = CTL_ISCSI_ERROR;
1898                         return;
1899                 }
1900         }
1901
1902         ip = icl_pdu_new_bhs(cs->cs_conn, M_WAITOK);
1903         memcpy(ip->ip_bhs, cisp->bhs, sizeof(*ip->ip_bhs));
1904         if (datalen > 0) {
1905                 icl_pdu_append_data(ip, data, datalen, M_WAITOK);
1906                 free(data, M_CFISCSI);
1907         }
1908         CFISCSI_SESSION_LOCK(cs);
1909         icl_pdu_queue(ip);
1910         CFISCSI_SESSION_UNLOCK(cs);
1911         ci->status = CTL_ISCSI_OK;
1912 }
1913
1914 static void
1915 cfiscsi_ioctl_receive(struct ctl_iscsi *ci)
1916 {
1917         struct ctl_iscsi_receive_params *cirp;
1918         struct cfiscsi_session *cs;
1919         struct icl_pdu *ip;
1920         void *data;
1921         int error;
1922
1923         cirp = (struct ctl_iscsi_receive_params *)&(ci->data);
1924
1925         mtx_lock(&cfiscsi_softc.lock);
1926         TAILQ_FOREACH(cs, &cfiscsi_softc.sessions, cs_next) {
1927                 if (cs->cs_id == cirp->connection_id)
1928                         break;
1929         }
1930         if (cs == NULL) {
1931                 mtx_unlock(&cfiscsi_softc.lock);
1932                 snprintf(ci->error_str, sizeof(ci->error_str),
1933                     "connection not found");
1934                 ci->status = CTL_ISCSI_ERROR;
1935                 return;
1936         }
1937         mtx_unlock(&cfiscsi_softc.lock);
1938
1939 #if 0
1940         if (is->is_login_phase == false)
1941                 return (EBUSY);
1942 #endif
1943
1944         CFISCSI_SESSION_LOCK(cs);
1945         while (cs->cs_login_pdu == NULL && cs->cs_terminating == false) {
1946                 error = cv_wait_sig(&cs->cs_login_cv, &cs->cs_lock);
1947                 if (error != 0) {
1948                         CFISCSI_SESSION_UNLOCK(cs);
1949                         snprintf(ci->error_str, sizeof(ci->error_str),
1950                             "interrupted by signal");
1951                         ci->status = CTL_ISCSI_ERROR;
1952                         return;
1953                 }
1954         }
1955
1956         if (cs->cs_terminating) {
1957                 CFISCSI_SESSION_UNLOCK(cs);
1958                 snprintf(ci->error_str, sizeof(ci->error_str),
1959                     "connection terminating");
1960                 ci->status = CTL_ISCSI_ERROR;
1961                 return;
1962         }
1963         ip = cs->cs_login_pdu;
1964         cs->cs_login_pdu = NULL;
1965         CFISCSI_SESSION_UNLOCK(cs);
1966
1967         if (ip->ip_data_len > cirp->data_segment_len) {
1968                 icl_pdu_free(ip);
1969                 snprintf(ci->error_str, sizeof(ci->error_str),
1970                     "data segment too big");
1971                 ci->status = CTL_ISCSI_ERROR;
1972                 return;
1973         }
1974
1975         copyout(ip->ip_bhs, cirp->bhs, sizeof(*ip->ip_bhs));
1976         if (ip->ip_data_len > 0) {
1977                 data = malloc(ip->ip_data_len, M_CFISCSI, M_WAITOK);
1978                 icl_pdu_get_data(ip, 0, data, ip->ip_data_len);
1979                 copyout(data, cirp->data_segment, ip->ip_data_len);
1980                 free(data, M_CFISCSI);
1981         }
1982
1983         icl_pdu_free(ip);
1984         ci->status = CTL_ISCSI_OK;
1985 }
1986
1987 #endif /* !ICL_KERNEL_PROXY */
1988
1989 static int
1990 cfiscsi_ioctl(struct cdev *dev,
1991     u_long cmd, caddr_t addr, int flag, struct thread *td)
1992 {
1993         struct ctl_iscsi *ci;
1994
1995         if (cmd != CTL_ISCSI)
1996                 return (ENOTTY);
1997
1998         ci = (struct ctl_iscsi *)addr;
1999         switch (ci->type) {
2000         case CTL_ISCSI_HANDOFF:
2001                 cfiscsi_ioctl_handoff(ci);
2002                 break;
2003         case CTL_ISCSI_LIST:
2004                 cfiscsi_ioctl_list(ci);
2005                 break;
2006         case CTL_ISCSI_TERMINATE:
2007                 cfiscsi_ioctl_terminate(ci);
2008                 break;
2009         case CTL_ISCSI_LOGOUT:
2010                 cfiscsi_ioctl_logout(ci);
2011                 break;
2012 #ifdef ICL_KERNEL_PROXY
2013         case CTL_ISCSI_LISTEN:
2014                 cfiscsi_ioctl_listen(ci);
2015                 break;
2016         case CTL_ISCSI_ACCEPT:
2017                 cfiscsi_ioctl_accept(ci);
2018                 break;
2019         case CTL_ISCSI_SEND:
2020                 cfiscsi_ioctl_send(ci);
2021                 break;
2022         case CTL_ISCSI_RECEIVE:
2023                 cfiscsi_ioctl_receive(ci);
2024                 break;
2025 #else
2026         case CTL_ISCSI_LISTEN:
2027         case CTL_ISCSI_ACCEPT:
2028         case CTL_ISCSI_SEND:
2029         case CTL_ISCSI_RECEIVE:
2030                 ci->status = CTL_ISCSI_ERROR;
2031                 snprintf(ci->error_str, sizeof(ci->error_str),
2032                     "%s: CTL compiled without ICL_KERNEL_PROXY",
2033                     __func__);
2034                 break;
2035 #endif /* !ICL_KERNEL_PROXY */
2036         default:
2037                 ci->status = CTL_ISCSI_ERROR;
2038                 snprintf(ci->error_str, sizeof(ci->error_str),
2039                     "%s: invalid iSCSI request type %d", __func__, ci->type);
2040                 break;
2041         }
2042
2043         return (0);
2044 }
2045
2046 static int
2047 cfiscsi_devid(struct ctl_scsiio *ctsio, int alloc_len)
2048 {
2049         struct cfiscsi_session *cs;
2050         struct scsi_vpd_device_id *devid_ptr;
2051         struct scsi_vpd_id_descriptor *desc, *desc1, *desc2, *desc3, *desc4;
2052         struct scsi_vpd_id_descriptor *desc5;
2053         struct scsi_vpd_id_t10 *t10id;
2054         struct ctl_lun *lun;
2055         const struct icl_pdu *request;
2056         int i, ret;
2057         char *val;
2058         size_t data_len, devid_len, wwnn_len, wwpn_len, lun_name_len;
2059
2060         lun = (struct ctl_lun *)ctsio->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
2061         request = ctsio->io_hdr.ctl_private[CTL_PRIV_FRONTEND].ptr;
2062         cs = PDU_SESSION(request);
2063
2064         wwpn_len = strlen(cs->cs_target->ct_name);
2065         wwpn_len += strlen(",t,0x0001");
2066         wwpn_len += 1; /* '\0' */
2067         if ((wwpn_len % 4) != 0)
2068                 wwpn_len += (4 - (wwpn_len % 4));
2069
2070         wwnn_len = strlen(cs->cs_target->ct_name);
2071         wwnn_len += 1; /* '\0' */
2072         if ((wwnn_len % 4) != 0)
2073                 wwnn_len += (4 - (wwnn_len % 4));
2074
2075         if (lun == NULL) {
2076                 devid_len = CTL_DEVID_MIN_LEN;
2077                 lun_name_len = 0;
2078         } else {
2079                 devid_len = max(CTL_DEVID_MIN_LEN,
2080                     strnlen(lun->be_lun->device_id, CTL_DEVID_LEN));
2081                 lun_name_len = strlen(cs->cs_target->ct_name);
2082                 lun_name_len += strlen(",lun,XXXXXXXX");
2083                 lun_name_len += 1; /* '\0' */
2084                 if ((lun_name_len % 4) != 0)
2085                         lun_name_len += (4 - (lun_name_len % 4));
2086         }
2087
2088         data_len = sizeof(struct scsi_vpd_device_id) +
2089                 sizeof(struct scsi_vpd_id_descriptor) +
2090                 sizeof(struct scsi_vpd_id_t10) + devid_len +
2091                 sizeof(struct scsi_vpd_id_descriptor) + lun_name_len +
2092                 sizeof(struct scsi_vpd_id_descriptor) + wwnn_len +
2093                 sizeof(struct scsi_vpd_id_descriptor) + wwpn_len +
2094                 sizeof(struct scsi_vpd_id_descriptor) +
2095                 sizeof(struct scsi_vpd_id_rel_trgt_port_id) +
2096                 sizeof(struct scsi_vpd_id_descriptor) +
2097                 sizeof(struct scsi_vpd_id_trgt_port_grp_id);
2098
2099         ctsio->kern_data_ptr = malloc(data_len, M_CTL, M_WAITOK | M_ZERO);
2100         devid_ptr = (struct scsi_vpd_device_id *)ctsio->kern_data_ptr;
2101         ctsio->kern_sg_entries = 0;
2102
2103         if (data_len < alloc_len) {
2104                 ctsio->residual = alloc_len - data_len;
2105                 ctsio->kern_data_len = data_len;
2106                 ctsio->kern_total_len = data_len;
2107         } else {
2108                 ctsio->residual = 0;
2109                 ctsio->kern_data_len = alloc_len;
2110                 ctsio->kern_total_len = alloc_len;
2111         }
2112         ctsio->kern_data_resid = 0;
2113         ctsio->kern_rel_offset = 0;
2114         ctsio->kern_sg_entries = 0;
2115
2116         desc = (struct scsi_vpd_id_descriptor *)devid_ptr->desc_list;
2117         t10id = (struct scsi_vpd_id_t10 *)&desc->identifier[0];
2118         desc1 = (struct scsi_vpd_id_descriptor *)(&desc->identifier[0] +
2119             sizeof(struct scsi_vpd_id_t10) + devid_len);
2120         desc2 = (struct scsi_vpd_id_descriptor *)(&desc1->identifier[0] +
2121             lun_name_len);
2122         desc3 = (struct scsi_vpd_id_descriptor *)(&desc2->identifier[0] +
2123             wwnn_len);
2124         desc4 = (struct scsi_vpd_id_descriptor *)(&desc3->identifier[0] +
2125             wwpn_len);
2126         desc5 = (struct scsi_vpd_id_descriptor *)(&desc4->identifier[0] +
2127             sizeof(struct scsi_vpd_id_rel_trgt_port_id));
2128
2129         if (lun != NULL)
2130                 devid_ptr->device = (SID_QUAL_LU_CONNECTED << 5) |
2131                     lun->be_lun->lun_type;
2132         else
2133                 devid_ptr->device = (SID_QUAL_LU_OFFLINE << 5) | T_DIRECT;
2134
2135         devid_ptr->page_code = SVPD_DEVICE_ID;
2136
2137         scsi_ulto2b(data_len - 4, devid_ptr->length);
2138
2139         /*
2140          * We're using a LUN association here.  i.e., this device ID is a
2141          * per-LUN identifier.
2142          */
2143         desc->proto_codeset = (SCSI_PROTO_ISCSI << 4) | SVPD_ID_CODESET_ASCII;
2144         desc->id_type = SVPD_ID_PIV | SVPD_ID_ASSOC_LUN | SVPD_ID_TYPE_T10;
2145         desc->length = sizeof(*t10id) + devid_len;
2146         if (lun == NULL || (val = ctl_get_opt(lun->be_lun, "vendor")) == NULL) {
2147                 strncpy((char *)t10id->vendor, CTL_VENDOR, sizeof(t10id->vendor));
2148         } else {
2149                 memset(t10id->vendor, ' ', sizeof(t10id->vendor));
2150                 strncpy(t10id->vendor, val,
2151                     min(sizeof(t10id->vendor), strlen(val)));
2152         }
2153
2154         /*
2155          * If we've actually got a backend, copy the device id from the
2156          * per-LUN data.  Otherwise, set it to all spaces.
2157          */
2158         if (lun != NULL) {
2159                 /*
2160                  * Copy the backend's LUN ID.
2161                  */
2162                 strncpy((char *)t10id->vendor_spec_id,
2163                     (char *)lun->be_lun->device_id, devid_len);
2164         } else {
2165                 /*
2166                  * No backend, set this to spaces.
2167                  */
2168                 memset(t10id->vendor_spec_id, 0x20, devid_len);
2169         }
2170
2171         /*
2172          * desc1 is for the unique LUN name.
2173          *
2174          * XXX: According to SPC-3, LUN must report the same ID through
2175          *      all the ports.  The code below, however, reports the
2176          *      ID only via iSCSI.
2177          */
2178         desc1->proto_codeset = (SCSI_PROTO_ISCSI << 4) | SVPD_ID_CODESET_UTF8;
2179         desc1->id_type = SVPD_ID_PIV | SVPD_ID_ASSOC_LUN |
2180                 SVPD_ID_TYPE_SCSI_NAME;
2181         desc1->length = lun_name_len;
2182         if (lun != NULL) {
2183                 /*
2184                  * Find the per-target LUN number.
2185                  */
2186                 for (i = 0; i < CTL_MAX_LUNS; i++) {
2187                         if (cs->cs_target->ct_luns[i] == lun->lun)
2188                                 break;
2189                 }
2190                 KASSERT(i < CTL_MAX_LUNS,
2191                     ("lun %jd not found", (uintmax_t)lun->lun));
2192                 ret = snprintf(desc1->identifier, lun_name_len, "%s,lun,%d",
2193                     cs->cs_target->ct_name, i);
2194                 KASSERT(ret > 0 && ret <= lun_name_len, ("bad snprintf"));
2195         } else {
2196                 KASSERT(lun_name_len == 0, ("no lun, but lun_name_len != 0"));
2197         }
2198
2199         /*
2200          * desc2 is for the Target Name.
2201          */
2202         desc2->proto_codeset = (SCSI_PROTO_ISCSI << 4) | SVPD_ID_CODESET_UTF8;
2203         desc2->id_type = SVPD_ID_PIV | SVPD_ID_ASSOC_TARGET |
2204             SVPD_ID_TYPE_SCSI_NAME;
2205         desc2->length = wwnn_len;
2206         snprintf(desc2->identifier, wwnn_len, "%s", cs->cs_target->ct_name);
2207
2208         /*
2209          * desc3 is for the WWPN which is a port asscociation.
2210          */
2211         desc3->proto_codeset = (SCSI_PROTO_ISCSI << 4) | SVPD_ID_CODESET_UTF8;
2212         desc3->id_type = SVPD_ID_PIV | SVPD_ID_ASSOC_PORT |
2213             SVPD_ID_TYPE_SCSI_NAME;
2214         desc3->length = wwpn_len;
2215         snprintf(desc3->identifier, wwpn_len, "%s,t,0x%4.4x",
2216             cs->cs_target->ct_name, cs->cs_portal_group_tag);
2217
2218         /*
2219          * desc3 is for the Relative Target Port(type 4h) identifier
2220          */
2221         desc4->proto_codeset = (SCSI_PROTO_ISCSI << 4) | SVPD_ID_CODESET_BINARY;
2222         desc4->id_type = SVPD_ID_PIV | SVPD_ID_ASSOC_PORT |
2223             SVPD_ID_TYPE_RELTARG;
2224         desc4->length = 4;
2225         desc4->identifier[3] = 1;
2226
2227         /*
2228          * desc4 is for the Target Port Group(type 5h) identifier
2229          */
2230         desc5->proto_codeset = (SCSI_PROTO_ISCSI << 4) | SVPD_ID_CODESET_BINARY;
2231         desc5->id_type = SVPD_ID_PIV | SVPD_ID_ASSOC_PORT |
2232             SVPD_ID_TYPE_TPORTGRP;
2233         desc5->length = 4;
2234         desc5->identifier[3] = 1;
2235
2236         ctsio->scsi_status = SCSI_STATUS_OK;
2237
2238         ctsio->io_hdr.flags |= CTL_FLAG_ALLOCATED;
2239         ctsio->be_move_done = ctl_config_move_done;
2240         ctl_datamove((union ctl_io *)ctsio);
2241
2242         return (CTL_RETVAL_COMPLETE);
2243 }
2244
2245 static void
2246 cfiscsi_target_hold(struct cfiscsi_target *ct)
2247 {
2248
2249         refcount_acquire(&ct->ct_refcount);
2250 }
2251
2252 static void
2253 cfiscsi_target_release(struct cfiscsi_target *ct)
2254 {
2255         struct cfiscsi_softc *softc;
2256
2257         softc = ct->ct_softc;
2258         mtx_lock(&softc->lock);
2259         if (refcount_release(&ct->ct_refcount)) {
2260                 TAILQ_REMOVE(&softc->targets, ct, ct_next);
2261                 mtx_unlock(&softc->lock);
2262                 free(ct, M_CFISCSI);
2263
2264                 return;
2265         }
2266         mtx_unlock(&softc->lock);
2267 }
2268
2269 static struct cfiscsi_target *
2270 cfiscsi_target_find(struct cfiscsi_softc *softc, const char *name)
2271 {
2272         struct cfiscsi_target *ct;
2273
2274         mtx_lock(&softc->lock);
2275         TAILQ_FOREACH(ct, &softc->targets, ct_next) {
2276                 if (strcmp(name, ct->ct_name) != 0)
2277                         continue;
2278                 cfiscsi_target_hold(ct);
2279                 mtx_unlock(&softc->lock);
2280                 return (ct);
2281         }
2282         mtx_unlock(&softc->lock);
2283
2284         return (NULL);
2285 }
2286
2287 static struct cfiscsi_target *
2288 cfiscsi_target_find_or_create(struct cfiscsi_softc *softc, const char *name,
2289     const char *alias)
2290 {
2291         struct cfiscsi_target *ct, *newct;
2292         int i;
2293
2294         if (name[0] == '\0' || strlen(name) >= CTL_ISCSI_NAME_LEN)
2295                 return (NULL);
2296
2297         newct = malloc(sizeof(*newct), M_CFISCSI, M_WAITOK | M_ZERO);
2298
2299         mtx_lock(&softc->lock);
2300         TAILQ_FOREACH(ct, &softc->targets, ct_next) {
2301                 if (strcmp(name, ct->ct_name) != 0)
2302                         continue;
2303                 cfiscsi_target_hold(ct);
2304                 mtx_unlock(&softc->lock);
2305                 free(newct, M_CFISCSI);
2306                 return (ct);
2307         }
2308
2309         for (i = 0; i < CTL_MAX_LUNS; i++)
2310                 newct->ct_luns[i] = -1;
2311
2312         strlcpy(newct->ct_name, name, sizeof(newct->ct_name));
2313         if (alias != NULL)
2314                 strlcpy(newct->ct_alias, alias, sizeof(newct->ct_alias));
2315         refcount_init(&newct->ct_refcount, 1);
2316         newct->ct_softc = softc;
2317         TAILQ_INSERT_TAIL(&softc->targets, newct, ct_next);
2318         mtx_unlock(&softc->lock);
2319
2320         return (newct);
2321 }
2322
2323 /*
2324  * Takes LUN from the target space and returns LUN from the CTL space.
2325  */
2326 static uint32_t
2327 cfiscsi_map_lun(void *arg, uint32_t lun)
2328 {
2329         struct cfiscsi_session *cs;
2330
2331         cs = arg;
2332
2333         if (lun >= CTL_MAX_LUNS) {
2334                 CFISCSI_DEBUG("requested lun number %d is higher "
2335                     "than maximum %d", lun, CTL_MAX_LUNS - 1);
2336                 return (0xffffffff);
2337         }
2338
2339         if (cs->cs_target->ct_luns[lun] < 0)
2340                 return (0xffffffff);
2341
2342         return (cs->cs_target->ct_luns[lun]);
2343 }
2344
2345 static int
2346 cfiscsi_target_set_lun(struct cfiscsi_target *ct,
2347     unsigned long lun_id, unsigned long ctl_lun_id)
2348 {
2349
2350         if (lun_id >= CTL_MAX_LUNS) {
2351                 CFISCSI_WARN("requested lun number %ld is higher "
2352                     "than maximum %d", lun_id, CTL_MAX_LUNS - 1);
2353                 return (-1);
2354         }
2355
2356         if (ct->ct_luns[lun_id] >= 0) {
2357                 /*
2358                  * CTL calls cfiscsi_lun_enable() twice for each LUN - once
2359                  * when the LUN is created, and a second time just before
2360                  * the port is brought online; don't emit warnings
2361                  * for that case.
2362                  */
2363                 if (ct->ct_luns[lun_id] == ctl_lun_id)
2364                         return (0);
2365                 CFISCSI_WARN("lun %ld already allocated", lun_id);
2366                 return (-1);
2367         }
2368
2369 #if 0
2370         CFISCSI_DEBUG("adding mapping for lun %ld, target %s "
2371             "to ctl lun %ld", lun_id, ct->ct_name, ctl_lun_id);
2372 #endif
2373
2374         ct->ct_luns[lun_id] = ctl_lun_id;
2375         cfiscsi_target_hold(ct);
2376
2377         return (0);
2378 }
2379
2380 static int
2381 cfiscsi_target_unset_lun(struct cfiscsi_target *ct, unsigned long lun_id)
2382 {
2383
2384         if (ct->ct_luns[lun_id] < 0) {
2385                 CFISCSI_WARN("lun %ld not allocated", lun_id);
2386                 return (-1);
2387         }
2388
2389         ct->ct_luns[lun_id] = -1;
2390         cfiscsi_target_release(ct);
2391
2392         return (0);
2393 }
2394
2395 static int
2396 cfiscsi_lun_enable(void *arg, struct ctl_id target_id, int lun_id)
2397 {
2398         struct cfiscsi_softc *softc;
2399         struct cfiscsi_target *ct;
2400         const char *target = NULL, *target_alias = NULL;
2401         const char *lun = NULL;
2402         unsigned long tmp;
2403
2404         softc = (struct cfiscsi_softc *)arg;
2405
2406         target = ctl_get_opt(control_softc->ctl_luns[lun_id]->be_lun,
2407             "cfiscsi_target");
2408         target_alias = ctl_get_opt(control_softc->ctl_luns[lun_id]->be_lun,
2409             "cfiscsi_target_alias");
2410         lun = ctl_get_opt(control_softc->ctl_luns[lun_id]->be_lun,
2411             "cfiscsi_lun");
2412
2413         if (target == NULL && lun == NULL)
2414                 return (0);
2415
2416         if (target == NULL || lun == NULL) {
2417                 CFISCSI_WARN("lun added with cfiscsi_target, but without "
2418                     "cfiscsi_lun, or the other way around; ignoring");
2419                 return (0);
2420         }
2421
2422         ct = cfiscsi_target_find_or_create(softc, target, target_alias);
2423         if (ct == NULL) {
2424                 CFISCSI_WARN("failed to create target \"%s\"", target);
2425                 return (0);
2426         }
2427
2428         tmp = strtoul(lun, NULL, 10);
2429         cfiscsi_target_set_lun(ct, tmp, lun_id);
2430         cfiscsi_target_release(ct);
2431         return (0);
2432 }
2433
2434 static int
2435 cfiscsi_lun_disable(void *arg, struct ctl_id target_id, int lun_id)
2436 {
2437         struct cfiscsi_softc *softc;
2438         struct cfiscsi_target *ct;
2439         int i;
2440
2441         softc = (struct cfiscsi_softc *)arg;
2442
2443         mtx_lock(&softc->lock);
2444         TAILQ_FOREACH(ct, &softc->targets, ct_next) {
2445                 for (i = 0; i < CTL_MAX_LUNS; i++) {
2446                         if (ct->ct_luns[i] < 0)
2447                                 continue;
2448                         if (ct->ct_luns[i] != lun_id)
2449                                 continue;
2450                         mtx_unlock(&softc->lock);
2451                         cfiscsi_target_unset_lun(ct, i);
2452                         return (0);
2453                 }
2454         }
2455         mtx_unlock(&softc->lock);
2456         return (0);
2457 }
2458
2459 static void
2460 cfiscsi_datamove_in(union ctl_io *io)
2461 {
2462         struct cfiscsi_session *cs;
2463         struct icl_pdu *request, *response;
2464         const struct iscsi_bhs_scsi_command *bhssc;
2465         struct iscsi_bhs_data_in *bhsdi;
2466         struct ctl_sg_entry ctl_sg_entry, *ctl_sglist;
2467         size_t len, expected_len, sg_len, buffer_offset;
2468         const char *sg_addr;
2469         int ctl_sg_count, error, i;
2470
2471         request = io->io_hdr.ctl_private[CTL_PRIV_FRONTEND].ptr;
2472         cs = PDU_SESSION(request);
2473
2474         bhssc = (const struct iscsi_bhs_scsi_command *)request->ip_bhs;
2475         KASSERT((bhssc->bhssc_opcode & ~ISCSI_BHS_OPCODE_IMMEDIATE) ==
2476             ISCSI_BHS_OPCODE_SCSI_COMMAND,
2477             ("bhssc->bhssc_opcode != ISCSI_BHS_OPCODE_SCSI_COMMAND"));
2478
2479         if (io->scsiio.kern_sg_entries > 0) {
2480                 ctl_sglist = (struct ctl_sg_entry *)io->scsiio.kern_data_ptr;
2481                 ctl_sg_count = io->scsiio.kern_sg_entries;
2482         } else {
2483                 ctl_sglist = &ctl_sg_entry;
2484                 ctl_sglist->addr = io->scsiio.kern_data_ptr;
2485                 ctl_sglist->len = io->scsiio.kern_data_len;
2486                 ctl_sg_count = 1;
2487         }
2488
2489         /*
2490          * This is the total amount of data to be transferred within the current
2491          * SCSI command.  We need to record it so that we can properly report
2492          * underflow/underflow.
2493          */
2494         PDU_TOTAL_TRANSFER_LEN(request) = io->scsiio.kern_total_len;
2495
2496         /*
2497          * This is the offset within the current SCSI command; for the first
2498          * call to cfiscsi_datamove() it will be 0, and for subsequent ones
2499          * it will be the sum of lengths of previous ones.
2500          */
2501         buffer_offset = io->scsiio.kern_rel_offset;
2502
2503         /*
2504          * This is the transfer length expected by the initiator.  In theory,
2505          * it could be different from the correct amount of data from the SCSI
2506          * point of view, even if that doesn't make any sense.
2507          */
2508         expected_len = ntohl(bhssc->bhssc_expected_data_transfer_length);
2509 #if 0
2510         if (expected_len != io->scsiio.kern_total_len) {
2511                 CFISCSI_SESSION_DEBUG(cs, "expected transfer length %zd, "
2512                     "actual length %zd", expected_len,
2513                     (size_t)io->scsiio.kern_total_len);
2514         }
2515 #endif
2516
2517         if (buffer_offset >= expected_len) {
2518 #if 0
2519                 CFISCSI_SESSION_DEBUG(cs, "buffer_offset = %zd, "
2520                     "already sent the expected len", buffer_offset);
2521 #endif
2522                 io->scsiio.be_move_done(io);
2523                 return;
2524         }
2525
2526         i = 0;
2527         sg_addr = NULL;
2528         sg_len = 0;
2529         response = NULL;
2530         bhsdi = NULL;
2531         for (;;) {
2532                 if (response == NULL) {
2533                         response = cfiscsi_pdu_new_response(request, M_NOWAIT);
2534                         if (response == NULL) {
2535                                 CFISCSI_SESSION_WARN(cs, "failed to "
2536                                     "allocate memory; dropping connection");
2537                                 ctl_set_busy(&io->scsiio);
2538                                 io->scsiio.be_move_done(io);
2539                                 cfiscsi_session_terminate(cs);
2540                                 return;
2541                         }
2542                         bhsdi = (struct iscsi_bhs_data_in *)response->ip_bhs;
2543                         bhsdi->bhsdi_opcode = ISCSI_BHS_OPCODE_SCSI_DATA_IN;
2544                         bhsdi->bhsdi_initiator_task_tag =
2545                             bhssc->bhssc_initiator_task_tag;
2546                         bhsdi->bhsdi_datasn = htonl(PDU_EXPDATASN(request));
2547                         PDU_EXPDATASN(request)++;
2548                         bhsdi->bhsdi_buffer_offset = htonl(buffer_offset);
2549                 }
2550
2551                 KASSERT(i < ctl_sg_count, ("i >= ctl_sg_count"));
2552                 if (sg_len == 0) {
2553                         sg_addr = ctl_sglist[i].addr;
2554                         sg_len = ctl_sglist[i].len;
2555                         KASSERT(sg_len > 0, ("sg_len <= 0"));
2556                 }
2557
2558                 len = sg_len;
2559
2560                 /*
2561                  * Truncate to maximum data segment length.
2562                  */
2563                 KASSERT(response->ip_data_len < cs->cs_max_data_segment_length,
2564                     ("ip_data_len %zd >= max_data_segment_length %zd",
2565                     response->ip_data_len, cs->cs_max_data_segment_length));
2566                 if (response->ip_data_len + len >
2567                     cs->cs_max_data_segment_length) {
2568                         len = cs->cs_max_data_segment_length -
2569                             response->ip_data_len;
2570                         KASSERT(len <= sg_len, ("len %zd > sg_len %zd",
2571                             len, sg_len));
2572                 }
2573
2574                 /*
2575                  * Truncate to expected data transfer length.
2576                  */
2577                 KASSERT(buffer_offset + response->ip_data_len < expected_len,
2578                     ("buffer_offset %zd + ip_data_len %zd >= expected_len %zd",
2579                     buffer_offset, response->ip_data_len, expected_len));
2580                 if (buffer_offset + response->ip_data_len + len > expected_len) {
2581                         CFISCSI_SESSION_DEBUG(cs, "truncating from %zd "
2582                             "to expected data transfer length %zd",
2583                             buffer_offset + response->ip_data_len + len, expected_len);
2584                         len = expected_len - (buffer_offset + response->ip_data_len);
2585                         KASSERT(len <= sg_len, ("len %zd > sg_len %zd",
2586                             len, sg_len));
2587                 }
2588
2589                 error = icl_pdu_append_data(response, sg_addr, len, M_NOWAIT);
2590                 if (error != 0) {
2591                         CFISCSI_SESSION_WARN(cs, "failed to "
2592                             "allocate memory; dropping connection");
2593                         icl_pdu_free(response);
2594                         ctl_set_busy(&io->scsiio);
2595                         io->scsiio.be_move_done(io);
2596                         cfiscsi_session_terminate(cs);
2597                         return;
2598                 }
2599                 sg_addr += len;
2600                 sg_len -= len;
2601
2602                 KASSERT(buffer_offset + request->ip_data_len <= expected_len,
2603                     ("buffer_offset %zd + ip_data_len %zd > expected_len %zd",
2604                     buffer_offset, request->ip_data_len, expected_len));
2605                 if (buffer_offset + request->ip_data_len == expected_len) {
2606                         /*
2607                          * Already have the amount of data the initiator wanted.
2608                          */
2609                         break;
2610                 }
2611
2612                 if (sg_len == 0) {
2613                         /*
2614                          * End of scatter-gather segment;
2615                          * proceed to the next one...
2616                          */
2617                         if (i == ctl_sg_count - 1) {
2618                                 /*
2619                                  * ... unless this was the last one.
2620                                  */
2621                                 break;
2622                         }
2623                         i++;
2624                 }
2625
2626                 if (response->ip_data_len == cs->cs_max_data_segment_length) {
2627                         /*
2628                          * Can't stuff more data into the current PDU;
2629                          * queue it.  Note that's not enough to check
2630                          * for kern_data_resid == 0 instead; there
2631                          * may be several Data-In PDUs for the final
2632                          * call to cfiscsi_datamove(), and we want
2633                          * to set the F flag only on the last of them.
2634                          */
2635                         buffer_offset += response->ip_data_len;
2636                         if (buffer_offset == io->scsiio.kern_total_len ||
2637                             buffer_offset == expected_len)
2638                                 bhsdi->bhsdi_flags |= BHSDI_FLAGS_F;
2639                         cfiscsi_pdu_queue(response);
2640                         response = NULL;
2641                         bhsdi = NULL;
2642                 }
2643         }
2644         if (response != NULL) {
2645                 buffer_offset += response->ip_data_len;
2646                 if (buffer_offset == io->scsiio.kern_total_len ||
2647                     buffer_offset == expected_len)
2648                         bhsdi->bhsdi_flags |= BHSDI_FLAGS_F;
2649                 KASSERT(response->ip_data_len > 0, ("sending empty Data-In"));
2650                 cfiscsi_pdu_queue(response);
2651         }
2652
2653         io->scsiio.be_move_done(io);
2654 }
2655
2656 static void
2657 cfiscsi_datamove_out(union ctl_io *io)
2658 {
2659         struct cfiscsi_session *cs;
2660         struct icl_pdu *request, *response;
2661         const struct iscsi_bhs_scsi_command *bhssc;
2662         struct iscsi_bhs_r2t *bhsr2t;
2663         struct cfiscsi_data_wait *cdw;
2664         uint32_t target_transfer_tag;
2665         bool done;
2666
2667         request = io->io_hdr.ctl_private[CTL_PRIV_FRONTEND].ptr;
2668         cs = PDU_SESSION(request);
2669
2670         bhssc = (const struct iscsi_bhs_scsi_command *)request->ip_bhs;
2671         KASSERT((bhssc->bhssc_opcode & ~ISCSI_BHS_OPCODE_IMMEDIATE) ==
2672             ISCSI_BHS_OPCODE_SCSI_COMMAND,
2673             ("bhssc->bhssc_opcode != ISCSI_BHS_OPCODE_SCSI_COMMAND"));
2674
2675         /*
2676          * We need to record it so that we can properly report
2677          * underflow/underflow.
2678          */
2679         PDU_TOTAL_TRANSFER_LEN(request) = io->scsiio.kern_total_len;
2680
2681         /*
2682          * We hadn't received anything during this datamove yet.
2683          */
2684         io->scsiio.ext_data_filled = 0;
2685
2686         target_transfer_tag =
2687             atomic_fetchadd_32(&cs->cs_target_transfer_tag, 1);
2688
2689 #if 0
2690         CFISCSI_SESSION_DEBUG(cs, "expecting Data-Out with initiator "
2691             "task tag 0x%x, target transfer tag 0x%x",
2692             bhssc->bhssc_initiator_task_tag, target_transfer_tag);
2693 #endif
2694         cdw = uma_zalloc(cfiscsi_data_wait_zone, M_NOWAIT | M_ZERO);
2695         if (cdw == NULL) {
2696                 CFISCSI_SESSION_WARN(cs, "failed to "
2697                     "allocate memory; dropping connection");
2698                 ctl_set_busy(&io->scsiio);
2699                 io->scsiio.be_move_done(io);
2700                 cfiscsi_session_terminate(cs);
2701                 return;
2702         }
2703         cdw->cdw_ctl_io = io;
2704         cdw->cdw_target_transfer_tag = target_transfer_tag;
2705         cdw->cdw_initiator_task_tag = bhssc->bhssc_initiator_task_tag;
2706
2707         if (cs->cs_immediate_data && io->scsiio.kern_rel_offset <
2708             icl_pdu_data_segment_length(request)) {
2709                 done = cfiscsi_handle_data_segment(request, cdw);
2710                 if (done) {
2711                         uma_zfree(cfiscsi_data_wait_zone, cdw);
2712                         io->scsiio.be_move_done(io);
2713                         return;
2714                 }
2715         }
2716
2717         CFISCSI_SESSION_LOCK(cs);
2718         TAILQ_INSERT_TAIL(&cs->cs_waiting_for_data_out, cdw, cdw_next);
2719         CFISCSI_SESSION_UNLOCK(cs);
2720
2721         /*
2722          * XXX: We should limit the number of outstanding R2T PDUs
2723          *      per task to MaxOutstandingR2T.
2724          */
2725         response = cfiscsi_pdu_new_response(request, M_NOWAIT);
2726         if (response == NULL) {
2727                 CFISCSI_SESSION_WARN(cs, "failed to "
2728                     "allocate memory; dropping connection");
2729                 ctl_set_busy(&io->scsiio);
2730                 io->scsiio.be_move_done(io);
2731                 cfiscsi_session_terminate(cs);
2732                 return;
2733         }
2734         bhsr2t = (struct iscsi_bhs_r2t *)response->ip_bhs;
2735         bhsr2t->bhsr2t_opcode = ISCSI_BHS_OPCODE_R2T;
2736         bhsr2t->bhsr2t_flags = 0x80;
2737         bhsr2t->bhsr2t_lun = bhssc->bhssc_lun;
2738         bhsr2t->bhsr2t_initiator_task_tag = bhssc->bhssc_initiator_task_tag;
2739         bhsr2t->bhsr2t_target_transfer_tag = target_transfer_tag;
2740         /*
2741          * XXX: Here we assume that cfiscsi_datamove() won't ever
2742          *      be running concurrently on several CPUs for a given
2743          *      command.
2744          */
2745         bhsr2t->bhsr2t_r2tsn = htonl(PDU_R2TSN(request));
2746         PDU_R2TSN(request)++;
2747         /*
2748          * This is the offset within the current SCSI command;
2749          * i.e. for the first call of datamove(), it will be 0,
2750          * and for subsequent ones it will be the sum of lengths
2751          * of previous ones.
2752          *
2753          * The ext_data_filled is to account for unsolicited
2754          * (immediate) data that might have already arrived.
2755          */
2756         bhsr2t->bhsr2t_buffer_offset =
2757             htonl(io->scsiio.kern_rel_offset + io->scsiio.ext_data_filled);
2758         /*
2759          * This is the total length (sum of S/G lengths) this call
2760          * to cfiscsi_datamove() is supposed to handle.
2761          *
2762          * XXX: Limit it to MaxBurstLength.
2763          */
2764         bhsr2t->bhsr2t_desired_data_transfer_length =
2765             htonl(io->scsiio.kern_data_len - io->scsiio.ext_data_filled);
2766         cfiscsi_pdu_queue(response);
2767 }
2768
2769 static void
2770 cfiscsi_datamove(union ctl_io *io)
2771 {
2772
2773         if ((io->io_hdr.flags & CTL_FLAG_DATA_MASK) == CTL_FLAG_DATA_IN)
2774                 cfiscsi_datamove_in(io);
2775         else
2776                 cfiscsi_datamove_out(io);
2777 }
2778
2779 static void
2780 cfiscsi_scsi_command_done(union ctl_io *io)
2781 {
2782         struct icl_pdu *request, *response;
2783         struct iscsi_bhs_scsi_command *bhssc;
2784         struct iscsi_bhs_scsi_response *bhssr;
2785 #ifdef DIAGNOSTIC
2786         struct cfiscsi_data_wait *cdw;
2787 #endif
2788         struct cfiscsi_session *cs;
2789         uint16_t sense_length;
2790
2791         request = io->io_hdr.ctl_private[CTL_PRIV_FRONTEND].ptr;
2792         cs = PDU_SESSION(request);
2793         bhssc = (struct iscsi_bhs_scsi_command *)request->ip_bhs;
2794         KASSERT((bhssc->bhssc_opcode & ~ISCSI_BHS_OPCODE_IMMEDIATE) ==
2795             ISCSI_BHS_OPCODE_SCSI_COMMAND,
2796             ("replying to wrong opcode 0x%x", bhssc->bhssc_opcode));
2797
2798         //CFISCSI_SESSION_DEBUG(cs, "initiator task tag 0x%x",
2799         //    bhssc->bhssc_initiator_task_tag);
2800
2801 #ifdef DIAGNOSTIC
2802         CFISCSI_SESSION_LOCK(cs);
2803         TAILQ_FOREACH(cdw, &cs->cs_waiting_for_data_out, cdw_next)
2804                 KASSERT(bhssc->bhssc_initiator_task_tag !=
2805                     cdw->cdw_initiator_task_tag, ("dangling cdw"));
2806         CFISCSI_SESSION_UNLOCK(cs);
2807 #endif
2808
2809         response = cfiscsi_pdu_new_response(request, M_WAITOK);
2810         bhssr = (struct iscsi_bhs_scsi_response *)response->ip_bhs;
2811         bhssr->bhssr_opcode = ISCSI_BHS_OPCODE_SCSI_RESPONSE;
2812         bhssr->bhssr_flags = 0x80;
2813         /*
2814          * XXX: We don't deal with bidirectional under/overflows;
2815          *      does anything actually support those?
2816          */
2817         if (PDU_TOTAL_TRANSFER_LEN(request) <
2818             ntohl(bhssc->bhssc_expected_data_transfer_length)) {
2819                 bhssr->bhssr_flags |= BHSSR_FLAGS_RESIDUAL_UNDERFLOW;
2820                 bhssr->bhssr_residual_count =
2821                     htonl(ntohl(bhssc->bhssc_expected_data_transfer_length) -
2822                     PDU_TOTAL_TRANSFER_LEN(request));
2823                 //CFISCSI_SESSION_DEBUG(cs, "underflow; residual count %d",
2824                 //    ntohl(bhssr->bhssr_residual_count));
2825         } else if (PDU_TOTAL_TRANSFER_LEN(request) > 
2826             ntohl(bhssc->bhssc_expected_data_transfer_length)) {
2827                 bhssr->bhssr_flags |= BHSSR_FLAGS_RESIDUAL_OVERFLOW;
2828                 bhssr->bhssr_residual_count =
2829                     htonl(PDU_TOTAL_TRANSFER_LEN(request) -
2830                     ntohl(bhssc->bhssc_expected_data_transfer_length));
2831                 //CFISCSI_SESSION_DEBUG(cs, "overflow; residual count %d",
2832                 //    ntohl(bhssr->bhssr_residual_count));
2833         }
2834         bhssr->bhssr_response = BHSSR_RESPONSE_COMMAND_COMPLETED;
2835         bhssr->bhssr_status = io->scsiio.scsi_status;
2836         bhssr->bhssr_initiator_task_tag = bhssc->bhssc_initiator_task_tag;
2837         bhssr->bhssr_expdatasn = htonl(PDU_EXPDATASN(request));
2838
2839         if (io->scsiio.sense_len > 0) {
2840 #if 0
2841                 CFISCSI_SESSION_DEBUG(cs, "returning %d bytes of sense data",
2842                     io->scsiio.sense_len);
2843 #endif
2844                 sense_length = htons(io->scsiio.sense_len);
2845                 icl_pdu_append_data(response,
2846                     &sense_length, sizeof(sense_length), M_WAITOK);
2847                 icl_pdu_append_data(response,
2848                     &io->scsiio.sense_data, io->scsiio.sense_len, M_WAITOK);
2849         }
2850
2851         ctl_free_io(io);
2852         icl_pdu_free(request);
2853         cfiscsi_pdu_queue(response);
2854 }
2855
2856 static void
2857 cfiscsi_task_management_done(union ctl_io *io)
2858 {
2859         struct icl_pdu *request, *response;
2860         struct iscsi_bhs_task_management_request *bhstmr;
2861         struct iscsi_bhs_task_management_response *bhstmr2;
2862         struct cfiscsi_data_wait *cdw, *tmpcdw;
2863         struct cfiscsi_session *cs;
2864
2865         request = io->io_hdr.ctl_private[CTL_PRIV_FRONTEND].ptr;
2866         cs = PDU_SESSION(request);
2867         bhstmr = (struct iscsi_bhs_task_management_request *)request->ip_bhs;
2868         KASSERT((bhstmr->bhstmr_opcode & ~ISCSI_BHS_OPCODE_IMMEDIATE) ==
2869             ISCSI_BHS_OPCODE_TASK_REQUEST,
2870             ("replying to wrong opcode 0x%x", bhstmr->bhstmr_opcode));
2871
2872 #if 0
2873         CFISCSI_SESSION_DEBUG(cs, "initiator task tag 0x%x; referenced task tag 0x%x",
2874             bhstmr->bhstmr_initiator_task_tag,
2875             bhstmr->bhstmr_referenced_task_tag);
2876 #endif
2877
2878         if ((bhstmr->bhstmr_function & ~0x80) ==
2879             BHSTMR_FUNCTION_ABORT_TASK) {
2880                 /*
2881                  * Make sure we no longer wait for Data-Out for this command.
2882                  */
2883                 CFISCSI_SESSION_LOCK(cs);
2884                 TAILQ_FOREACH_SAFE(cdw,
2885                     &cs->cs_waiting_for_data_out, cdw_next, tmpcdw) {
2886                         if (bhstmr->bhstmr_referenced_task_tag !=
2887                             cdw->cdw_initiator_task_tag)
2888                                 continue;
2889
2890 #if 0
2891                         CFISCSI_SESSION_DEBUG(cs, "removing csw for initiator task "
2892                             "tag 0x%x", bhstmr->bhstmr_initiator_task_tag);
2893 #endif
2894                         TAILQ_REMOVE(&cs->cs_waiting_for_data_out,
2895                             cdw, cdw_next);
2896                         cdw->cdw_ctl_io->scsiio.be_move_done(cdw->cdw_ctl_io);
2897                         uma_zfree(cfiscsi_data_wait_zone, cdw);
2898                 }
2899                 CFISCSI_SESSION_UNLOCK(cs);
2900         }
2901
2902         response = cfiscsi_pdu_new_response(request, M_WAITOK);
2903         bhstmr2 = (struct iscsi_bhs_task_management_response *)
2904             response->ip_bhs;
2905         bhstmr2->bhstmr_opcode = ISCSI_BHS_OPCODE_TASK_RESPONSE;
2906         bhstmr2->bhstmr_flags = 0x80;
2907         if (io->io_hdr.status == CTL_SUCCESS) {
2908                 bhstmr2->bhstmr_response = BHSTMR_RESPONSE_FUNCTION_COMPLETE;
2909         } else {
2910                 /*
2911                  * XXX: How to figure out what exactly went wrong?  iSCSI spec
2912                  *      expects us to provide detailed error, e.g. "Task does
2913                  *      not exist" or "LUN does not exist".
2914                  */
2915                 CFISCSI_SESSION_DEBUG(cs, "BHSTMR_RESPONSE_FUNCTION_NOT_SUPPORTED");
2916                 bhstmr2->bhstmr_response =
2917                     BHSTMR_RESPONSE_FUNCTION_NOT_SUPPORTED;
2918         }
2919         bhstmr2->bhstmr_initiator_task_tag = bhstmr->bhstmr_initiator_task_tag;
2920
2921         ctl_free_io(io);
2922         icl_pdu_free(request);
2923         cfiscsi_pdu_queue(response);
2924 }
2925
2926 static void
2927 cfiscsi_done(union ctl_io *io)
2928 {
2929         struct icl_pdu *request;
2930         struct cfiscsi_session *cs;
2931
2932         KASSERT(((io->io_hdr.status & CTL_STATUS_MASK) != CTL_STATUS_NONE),
2933                 ("invalid CTL status %#x", io->io_hdr.status));
2934
2935         request = io->io_hdr.ctl_private[CTL_PRIV_FRONTEND].ptr;
2936         if (request == NULL) {
2937                 /*
2938                  * Implicit task termination has just completed; nothing to do.
2939                  */
2940                 return;
2941         }
2942
2943         cs = PDU_SESSION(request);
2944         refcount_release(&cs->cs_outstanding_ctl_pdus);
2945
2946         switch (request->ip_bhs->bhs_opcode & ~ISCSI_BHS_OPCODE_IMMEDIATE) {
2947         case ISCSI_BHS_OPCODE_SCSI_COMMAND:
2948                 cfiscsi_scsi_command_done(io);
2949                 break;
2950         case ISCSI_BHS_OPCODE_TASK_REQUEST:
2951                 cfiscsi_task_management_done(io);
2952                 break;
2953         default:
2954                 panic("cfiscsi_done called with wrong opcode 0x%x",
2955                     request->ip_bhs->bhs_opcode);
2956         }
2957 }