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