]> CyberLeo.Net >> Repos - FreeBSD/releng/10.1.git/blob - sys/cam/ctl/ctl_frontend_iscsi.c
Copy stable/10@r272459 to releng/10.1 as part of
[FreeBSD/releng/10.1.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 <cam/ctl/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_info(void *arg, struct sbuf *sb);
153 static int      cfiscsi_lun_enable(void *arg,
154                     struct ctl_id target_id, int lun_id);
155 static int      cfiscsi_lun_disable(void *arg,
156                     struct ctl_id target_id, int lun_id);
157 static uint32_t cfiscsi_lun_map(void *arg, uint32_t lun);
158 static int      cfiscsi_ioctl(struct cdev *dev,
159                     u_long cmd, caddr_t addr, int flag, struct thread *td);
160 static void     cfiscsi_datamove(union ctl_io *io);
161 static void     cfiscsi_done(union ctl_io *io);
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 struct cfiscsi_target    *cfiscsi_target_find_or_create(
172     struct cfiscsi_softc *softc, const char *name, const char *alias);
173 static void     cfiscsi_target_release(struct cfiscsi_target *ct);
174 static void     cfiscsi_session_delete(struct cfiscsi_session *cs);
175
176 static struct cfiscsi_softc cfiscsi_softc;
177 extern struct ctl_softc *control_softc;
178
179 static struct ctl_frontend cfiscsi_frontend =
180 {
181         .name = "iscsi",
182         .init = cfiscsi_init,
183         .ioctl = cfiscsi_ioctl,
184 };
185 CTL_FRONTEND_DECLARE(ctlcfiscsi, cfiscsi_frontend);
186 MODULE_DEPEND(ctlcfiscsi, icl, 1, 1, 1);
187
188 static struct icl_pdu *
189 cfiscsi_pdu_new_response(struct icl_pdu *request, int flags)
190 {
191
192         return (icl_pdu_new_bhs(request->ip_conn, flags));
193 }
194
195 static bool
196 cfiscsi_pdu_update_cmdsn(const struct icl_pdu *request)
197 {
198         const struct iscsi_bhs_scsi_command *bhssc;
199         struct cfiscsi_session *cs;
200         uint32_t cmdsn, expstatsn;
201
202         cs = PDU_SESSION(request);
203
204         /*
205          * Every incoming PDU - not just NOP-Out - resets the ping timer.
206          * The purpose of the timeout is to reset the connection when it stalls;
207          * we don't want this to happen when NOP-In or NOP-Out ends up delayed
208          * in some queue.
209          *
210          * XXX: Locking?
211          */
212         cs->cs_timeout = 0;
213
214         /*
215          * Data-Out PDUs don't contain CmdSN.
216          */
217         if ((request->ip_bhs->bhs_opcode & ~ISCSI_BHS_OPCODE_IMMEDIATE) ==
218             ISCSI_BHS_OPCODE_SCSI_DATA_OUT)
219                 return (false);
220
221         /*
222          * We're only using fields common for all the request
223          * (initiator -> target) PDUs.
224          */
225         bhssc = (const struct iscsi_bhs_scsi_command *)request->ip_bhs;
226         cmdsn = ntohl(bhssc->bhssc_cmdsn);
227         expstatsn = ntohl(bhssc->bhssc_expstatsn);
228
229         CFISCSI_SESSION_LOCK(cs);
230 #if 0
231         if (expstatsn != cs->cs_statsn) {
232                 CFISCSI_SESSION_DEBUG(cs, "received PDU with ExpStatSN %d, "
233                     "while current StatSN is %d", expstatsn,
234                     cs->cs_statsn);
235         }
236 #endif
237
238         /*
239          * The target MUST silently ignore any non-immediate command outside
240          * of this range.
241          */
242         if (cmdsn < cs->cs_cmdsn || cmdsn > cs->cs_cmdsn + maxcmdsn_delta) {
243                 CFISCSI_SESSION_UNLOCK(cs);
244                 CFISCSI_SESSION_WARN(cs, "received PDU with CmdSN %d, "
245                     "while expected CmdSN was %d", cmdsn, cs->cs_cmdsn);
246                 return (true);
247         }
248
249         if ((request->ip_bhs->bhs_opcode & ISCSI_BHS_OPCODE_IMMEDIATE) == 0)
250                 cs->cs_cmdsn++;
251
252         CFISCSI_SESSION_UNLOCK(cs);
253
254         return (false);
255 }
256
257 static void
258 cfiscsi_pdu_handle(struct icl_pdu *request)
259 {
260         struct cfiscsi_session *cs;
261         bool ignore;
262
263         cs = PDU_SESSION(request);
264
265         ignore = cfiscsi_pdu_update_cmdsn(request);
266         if (ignore) {
267                 icl_pdu_free(request);
268                 return;
269         }
270
271         /*
272          * Handle the PDU; this includes e.g. receiving the remaining
273          * part of PDU and submitting the SCSI command to CTL
274          * or queueing a reply.  The handling routine is responsible
275          * for freeing the PDU when it's no longer needed.
276          */
277         switch (request->ip_bhs->bhs_opcode &
278             ~ISCSI_BHS_OPCODE_IMMEDIATE) {
279         case ISCSI_BHS_OPCODE_NOP_OUT:
280                 cfiscsi_pdu_handle_nop_out(request);
281                 break;
282         case ISCSI_BHS_OPCODE_SCSI_COMMAND:
283                 cfiscsi_pdu_handle_scsi_command(request);
284                 break;
285         case ISCSI_BHS_OPCODE_TASK_REQUEST:
286                 cfiscsi_pdu_handle_task_request(request);
287                 break;
288         case ISCSI_BHS_OPCODE_SCSI_DATA_OUT:
289                 cfiscsi_pdu_handle_data_out(request);
290                 break;
291         case ISCSI_BHS_OPCODE_LOGOUT_REQUEST:
292                 cfiscsi_pdu_handle_logout_request(request);
293                 break;
294         default:
295                 CFISCSI_SESSION_WARN(cs, "received PDU with unsupported "
296                     "opcode 0x%x; dropping connection",
297                     request->ip_bhs->bhs_opcode);
298                 icl_pdu_free(request);
299                 cfiscsi_session_terminate(cs);
300         }
301
302 }
303
304 static void
305 cfiscsi_receive_callback(struct icl_pdu *request)
306 {
307         struct cfiscsi_session *cs;
308
309         cs = PDU_SESSION(request);
310
311 #ifdef ICL_KERNEL_PROXY
312         if (cs->cs_waiting_for_ctld || cs->cs_login_phase) {
313                 if (cs->cs_login_pdu == NULL)
314                         cs->cs_login_pdu = request;
315                 else
316                         icl_pdu_free(request);
317                 cv_signal(&cs->cs_login_cv);
318                 return;
319         }
320 #endif
321
322         cfiscsi_pdu_handle(request);
323 }
324
325 static void
326 cfiscsi_error_callback(struct icl_conn *ic)
327 {
328         struct cfiscsi_session *cs;
329
330         cs = CONN_SESSION(ic);
331
332         CFISCSI_SESSION_WARN(cs, "connection error; dropping connection");
333         cfiscsi_session_terminate(cs);
334 }
335
336 static int
337 cfiscsi_pdu_prepare(struct icl_pdu *response)
338 {
339         struct cfiscsi_session *cs;
340         struct iscsi_bhs_scsi_response *bhssr;
341         bool advance_statsn = true;
342
343         cs = PDU_SESSION(response);
344
345         CFISCSI_SESSION_LOCK_ASSERT(cs);
346
347         /*
348          * We're only using fields common for all the response
349          * (target -> initiator) PDUs.
350          */
351         bhssr = (struct iscsi_bhs_scsi_response *)response->ip_bhs;
352
353         /*
354          * 10.8.3: "The StatSN for this connection is not advanced
355          * after this PDU is sent."
356          */
357         if (bhssr->bhssr_opcode == ISCSI_BHS_OPCODE_R2T)
358                 advance_statsn = false;
359
360         /*
361          * 10.19.2: "However, when the Initiator Task Tag is set to 0xffffffff,
362          * StatSN for the connection is not advanced after this PDU is sent."
363          */
364         if (bhssr->bhssr_opcode == ISCSI_BHS_OPCODE_NOP_IN && 
365             bhssr->bhssr_initiator_task_tag == 0xffffffff)
366                 advance_statsn = false;
367
368         /*
369          * See the comment below - StatSN is not meaningful and must
370          * not be advanced.
371          */
372         if (bhssr->bhssr_opcode == ISCSI_BHS_OPCODE_SCSI_DATA_IN)
373                 advance_statsn = false;
374
375         /*
376          * 10.7.3: "The fields StatSN, Status, and Residual Count
377          * only have meaningful content if the S bit is set to 1."
378          */
379         if (bhssr->bhssr_opcode != ISCSI_BHS_OPCODE_SCSI_DATA_IN)
380                 bhssr->bhssr_statsn = htonl(cs->cs_statsn);
381         bhssr->bhssr_expcmdsn = htonl(cs->cs_cmdsn);
382         bhssr->bhssr_maxcmdsn = htonl(cs->cs_cmdsn + maxcmdsn_delta);
383
384         if (advance_statsn)
385                 cs->cs_statsn++;
386
387         return (0);
388 }
389
390 static void
391 cfiscsi_pdu_queue(struct icl_pdu *response)
392 {
393         struct cfiscsi_session *cs;
394
395         cs = PDU_SESSION(response);
396
397         CFISCSI_SESSION_LOCK(cs);
398         cfiscsi_pdu_prepare(response);
399         icl_pdu_queue(response);
400         CFISCSI_SESSION_UNLOCK(cs);
401 }
402
403 static uint32_t
404 cfiscsi_decode_lun(uint64_t encoded)
405 {
406         uint8_t lun[8];
407         uint32_t result;
408
409         /*
410          * The LUN field in iSCSI PDUs may look like an ordinary 64 bit number,
411          * but is in fact an evil, multidimensional structure defined
412          * in SCSI Architecture Model 5 (SAM-5), section 4.6.
413          */
414         memcpy(lun, &encoded, sizeof(lun));
415         switch (lun[0] & 0xC0) {
416         case 0x00:
417                 if ((lun[0] & 0x3f) != 0 || lun[2] != 0 || lun[3] != 0 ||
418                     lun[4] != 0 || lun[5] != 0 || lun[6] != 0 || lun[7] != 0) {
419                         CFISCSI_WARN("malformed LUN "
420                             "(peripheral device addressing method): 0x%jx",
421                             (uintmax_t)encoded);
422                         result = 0xffffffff;
423                         break;
424                 }
425                 result = lun[1];
426                 break;
427         case 0x40:
428                 if (lun[2] != 0 || lun[3] != 0 || lun[4] != 0 || lun[5] != 0 ||
429                     lun[6] != 0 || lun[7] != 0) {
430                         CFISCSI_WARN("malformed LUN "
431                             "(flat address space addressing method): 0x%jx",
432                             (uintmax_t)encoded);
433                         result = 0xffffffff;
434                         break;
435                 }
436                 result = ((lun[0] & 0x3f) << 8) + lun[1];
437                 break;
438         case 0xC0:
439                 if (lun[0] != 0xD2 || lun[4] != 0 || lun[5] != 0 ||
440                     lun[6] != 0 || lun[7] != 0) {
441                         CFISCSI_WARN("malformed LUN (extended flat "
442                             "address space addressing method): 0x%jx",
443                             (uintmax_t)encoded);
444                         result = 0xffffffff;
445                         break;
446                 }
447                 result = (lun[1] << 16) + (lun[2] << 8) + lun[3];
448         default:
449                 CFISCSI_WARN("unsupported LUN format 0x%jx",
450                     (uintmax_t)encoded);
451                 result = 0xffffffff;
452                 break;
453         }
454
455         return (result);
456 }
457
458 static void
459 cfiscsi_pdu_handle_nop_out(struct icl_pdu *request)
460 {
461         struct cfiscsi_session *cs;
462         struct iscsi_bhs_nop_out *bhsno;
463         struct iscsi_bhs_nop_in *bhsni;
464         struct icl_pdu *response;
465         void *data = NULL;
466         size_t datasize;
467         int error;
468
469         cs = PDU_SESSION(request);
470         bhsno = (struct iscsi_bhs_nop_out *)request->ip_bhs;
471
472         if (bhsno->bhsno_initiator_task_tag == 0xffffffff) {
473                 /*
474                  * Nothing to do, iscsi_pdu_update_statsn() already
475                  * zeroed the timeout.
476                  */
477                 icl_pdu_free(request);
478                 return;
479         }
480
481         datasize = icl_pdu_data_segment_length(request);
482         if (datasize > 0) {
483                 data = malloc(datasize, M_CFISCSI, M_NOWAIT | M_ZERO);
484                 if (data == NULL) {
485                         CFISCSI_SESSION_WARN(cs, "failed to allocate memory; "
486                             "dropping connection");
487                         icl_pdu_free(request);
488                         cfiscsi_session_terminate(cs);
489                         return;
490                 }
491                 icl_pdu_get_data(request, 0, data, datasize);
492         }
493
494         response = cfiscsi_pdu_new_response(request, M_NOWAIT);
495         if (response == NULL) {
496                 CFISCSI_SESSION_WARN(cs, "failed to allocate memory; "
497                     "droppping connection");
498                 free(data, M_CFISCSI);
499                 icl_pdu_free(request);
500                 cfiscsi_session_terminate(cs);
501                 return;
502         }
503         bhsni = (struct iscsi_bhs_nop_in *)response->ip_bhs;
504         bhsni->bhsni_opcode = ISCSI_BHS_OPCODE_NOP_IN;
505         bhsni->bhsni_flags = 0x80;
506         bhsni->bhsni_initiator_task_tag = bhsno->bhsno_initiator_task_tag;
507         bhsni->bhsni_target_transfer_tag = 0xffffffff;
508         if (datasize > 0) {
509                 error = icl_pdu_append_data(response, data, datasize, M_NOWAIT);
510                 if (error != 0) {
511                         CFISCSI_SESSION_WARN(cs, "failed to allocate memory; "
512                             "dropping connection");
513                         free(data, M_CFISCSI);
514                         icl_pdu_free(request);
515                         icl_pdu_free(response);
516                         cfiscsi_session_terminate(cs);
517                         return;
518                 }
519                 free(data, M_CFISCSI);
520         }
521
522         icl_pdu_free(request);
523         cfiscsi_pdu_queue(response);
524 }
525
526 static void
527 cfiscsi_pdu_handle_scsi_command(struct icl_pdu *request)
528 {
529         struct iscsi_bhs_scsi_command *bhssc;
530         struct cfiscsi_session *cs;
531         union ctl_io *io;
532         int error;
533
534         cs = PDU_SESSION(request);
535         bhssc = (struct iscsi_bhs_scsi_command *)request->ip_bhs;
536         //CFISCSI_SESSION_DEBUG(cs, "initiator task tag 0x%x",
537         //    bhssc->bhssc_initiator_task_tag);
538
539         if (request->ip_data_len > 0 && cs->cs_immediate_data == false) {
540                 CFISCSI_SESSION_WARN(cs, "unsolicited data with "
541                     "ImmediateData=No; dropping connection");
542                 icl_pdu_free(request);
543                 cfiscsi_session_terminate(cs);
544                 return;
545         }
546         io = ctl_alloc_io(cs->cs_target->ct_port.ctl_pool_ref);
547         if (io == NULL) {
548                 CFISCSI_SESSION_WARN(cs, "can't allocate ctl_io; "
549                     "dropping connection");
550                 icl_pdu_free(request);
551                 cfiscsi_session_terminate(cs);
552                 return;
553         }
554         ctl_zero_io(io);
555         io->io_hdr.ctl_private[CTL_PRIV_FRONTEND].ptr = request;
556         io->io_hdr.io_type = CTL_IO_SCSI;
557         io->io_hdr.nexus.initid.id = cs->cs_ctl_initid;
558         io->io_hdr.nexus.targ_port = cs->cs_target->ct_port.targ_port;
559         io->io_hdr.nexus.targ_target.id = 0;
560         io->io_hdr.nexus.targ_lun = cfiscsi_decode_lun(bhssc->bhssc_lun);
561         io->scsiio.tag_num = bhssc->bhssc_initiator_task_tag;
562         switch ((bhssc->bhssc_flags & BHSSC_FLAGS_ATTR)) {
563         case BHSSC_FLAGS_ATTR_UNTAGGED:
564                 io->scsiio.tag_type = CTL_TAG_UNTAGGED;
565                 break;
566         case BHSSC_FLAGS_ATTR_SIMPLE:
567                 io->scsiio.tag_type = CTL_TAG_SIMPLE;
568                 break;
569         case BHSSC_FLAGS_ATTR_ORDERED:
570                 io->scsiio.tag_type = CTL_TAG_ORDERED;
571                 break;
572         case BHSSC_FLAGS_ATTR_HOQ:
573                 io->scsiio.tag_type = CTL_TAG_HEAD_OF_QUEUE;
574                 break;
575         case BHSSC_FLAGS_ATTR_ACA:
576                 io->scsiio.tag_type = CTL_TAG_ACA;
577                 break;
578         default:
579                 io->scsiio.tag_type = CTL_TAG_UNTAGGED;
580                 CFISCSI_SESSION_WARN(cs, "unhandled tag type %d",
581                     bhssc->bhssc_flags & BHSSC_FLAGS_ATTR);
582                 break;
583         }
584         io->scsiio.cdb_len = sizeof(bhssc->bhssc_cdb); /* Which is 16. */
585         memcpy(io->scsiio.cdb, bhssc->bhssc_cdb, sizeof(bhssc->bhssc_cdb));
586         refcount_acquire(&cs->cs_outstanding_ctl_pdus);
587         error = ctl_queue(io);
588         if (error != CTL_RETVAL_COMPLETE) {
589                 CFISCSI_SESSION_WARN(cs, "ctl_queue() failed; error %d; "
590                     "dropping connection", error);
591                 ctl_free_io(io);
592                 refcount_release(&cs->cs_outstanding_ctl_pdus);
593                 icl_pdu_free(request);
594                 cfiscsi_session_terminate(cs);
595         }
596 }
597
598 static void
599 cfiscsi_pdu_handle_task_request(struct icl_pdu *request)
600 {
601         struct iscsi_bhs_task_management_request *bhstmr;
602         struct iscsi_bhs_task_management_response *bhstmr2;
603         struct icl_pdu *response;
604         struct cfiscsi_session *cs;
605         union ctl_io *io;
606         int error;
607
608         cs = PDU_SESSION(request);
609         bhstmr = (struct iscsi_bhs_task_management_request *)request->ip_bhs;
610         io = ctl_alloc_io(cs->cs_target->ct_port.ctl_pool_ref);
611         if (io == NULL) {
612                 CFISCSI_SESSION_WARN(cs, "can't allocate ctl_io;"
613                     "dropping connection");
614                 icl_pdu_free(request);
615                 cfiscsi_session_terminate(cs);
616                 return;
617         }
618         ctl_zero_io(io);
619         io->io_hdr.ctl_private[CTL_PRIV_FRONTEND].ptr = request;
620         io->io_hdr.io_type = CTL_IO_TASK;
621         io->io_hdr.nexus.initid.id = cs->cs_ctl_initid;
622         io->io_hdr.nexus.targ_port = cs->cs_target->ct_port.targ_port;
623         io->io_hdr.nexus.targ_target.id = 0;
624         io->io_hdr.nexus.targ_lun = cfiscsi_decode_lun(bhstmr->bhstmr_lun);
625         io->taskio.tag_type = CTL_TAG_SIMPLE; /* XXX */
626
627         switch (bhstmr->bhstmr_function & ~0x80) {
628         case BHSTMR_FUNCTION_ABORT_TASK:
629 #if 0
630                 CFISCSI_SESSION_DEBUG(cs, "BHSTMR_FUNCTION_ABORT_TASK");
631 #endif
632                 io->taskio.task_action = CTL_TASK_ABORT_TASK;
633                 io->taskio.tag_num = bhstmr->bhstmr_referenced_task_tag;
634                 break;
635         case BHSTMR_FUNCTION_ABORT_TASK_SET:
636 #if 0
637                 CFISCSI_SESSION_DEBUG(cs, "BHSTMR_FUNCTION_ABORT_TASK_SET");
638 #endif
639                 io->taskio.task_action = CTL_TASK_ABORT_TASK_SET;
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 (ping_timeout <= 0) {
1010                 /*
1011                  * Pings are disabled.  Don't send NOP-In in this case;
1012                  * user might have disabled pings to work around problems
1013                  * with certain initiators that can't properly handle
1014                  * NOP-In, such as iPXE.  Reset the timeout, to avoid
1015                  * triggering reconnection, should the user decide to
1016                  * reenable them.
1017                  */
1018                 cs->cs_timeout = 0;
1019                 return;
1020         }
1021
1022         if (cs->cs_timeout >= ping_timeout) {
1023                 CFISCSI_SESSION_WARN(cs, "no ping reply (NOP-Out) after %d seconds; "
1024                     "dropping connection",  ping_timeout);
1025                 cfiscsi_session_terminate(cs);
1026                 return;
1027         }
1028
1029         /*
1030          * If the ping was reset less than one second ago - which means
1031          * that we've received some PDU during the last second - assume
1032          * the traffic flows correctly and don't bother sending a NOP-Out.
1033          *
1034          * (It's 2 - one for one second, and one for incrementing is_timeout
1035          * earlier in this routine.)
1036          */
1037         if (cs->cs_timeout < 2)
1038                 return;
1039
1040         cp = icl_pdu_new_bhs(cs->cs_conn, M_NOWAIT);
1041         if (cp == NULL) {
1042                 CFISCSI_SESSION_WARN(cs, "failed to allocate memory");
1043                 return;
1044         }
1045         bhsni = (struct iscsi_bhs_nop_in *)cp->ip_bhs;
1046         bhsni->bhsni_opcode = ISCSI_BHS_OPCODE_NOP_IN;
1047         bhsni->bhsni_flags = 0x80;
1048         bhsni->bhsni_initiator_task_tag = 0xffffffff;
1049
1050         cfiscsi_pdu_queue(cp);
1051 }
1052
1053 static void
1054 cfiscsi_session_terminate_tasks(struct cfiscsi_session *cs)
1055 {
1056         struct cfiscsi_data_wait *cdw;
1057         union ctl_io *io;
1058         int error, last;
1059
1060         io = ctl_alloc_io(cs->cs_target->ct_port.ctl_pool_ref);
1061         if (io == NULL) {
1062                 CFISCSI_SESSION_WARN(cs, "can't allocate ctl_io");
1063                 return;
1064         }
1065         ctl_zero_io(io);
1066         io->io_hdr.ctl_private[CTL_PRIV_FRONTEND].ptr = cs;
1067         io->io_hdr.io_type = CTL_IO_TASK;
1068         io->io_hdr.nexus.initid.id = cs->cs_ctl_initid;
1069         io->io_hdr.nexus.targ_port = cs->cs_target->ct_port.targ_port;
1070         io->io_hdr.nexus.targ_target.id = 0;
1071         io->io_hdr.nexus.targ_lun = 0;
1072         io->taskio.tag_type = CTL_TAG_SIMPLE; /* XXX */
1073         io->taskio.task_action = CTL_TASK_I_T_NEXUS_RESET;
1074         refcount_acquire(&cs->cs_outstanding_ctl_pdus);
1075         error = ctl_queue(io);
1076         if (error != CTL_RETVAL_COMPLETE) {
1077                 CFISCSI_SESSION_WARN(cs, "ctl_queue() failed; error %d", error);
1078                 refcount_release(&cs->cs_outstanding_ctl_pdus);
1079                 ctl_free_io(io);
1080         }
1081
1082         CFISCSI_SESSION_LOCK(cs);
1083         while ((cdw = TAILQ_FIRST(&cs->cs_waiting_for_data_out)) != NULL) {
1084                 TAILQ_REMOVE(&cs->cs_waiting_for_data_out, cdw, cdw_next);
1085                 CFISCSI_SESSION_UNLOCK(cs);
1086                 /*
1087                  * Set nonzero port status; this prevents backends from
1088                  * assuming that the data transfer actually succeeded
1089                  * and writing uninitialized data to disk.
1090                  */
1091                 cdw->cdw_ctl_io->scsiio.io_hdr.port_status = 42;
1092                 cdw->cdw_ctl_io->scsiio.be_move_done(cdw->cdw_ctl_io);
1093                 uma_zfree(cfiscsi_data_wait_zone, cdw);
1094                 CFISCSI_SESSION_LOCK(cs);
1095         }
1096         CFISCSI_SESSION_UNLOCK(cs);
1097
1098         /*
1099          * Wait for CTL to terminate all the tasks.
1100          */
1101         for (;;) {
1102                 refcount_acquire(&cs->cs_outstanding_ctl_pdus);
1103                 last = refcount_release(&cs->cs_outstanding_ctl_pdus);
1104                 if (last != 0)
1105                         break;
1106                 CFISCSI_SESSION_WARN(cs, "waiting for CTL to terminate tasks, "
1107                     "%d remaining", cs->cs_outstanding_ctl_pdus);
1108                 tsleep(__DEVOLATILE(void *, &cs->cs_outstanding_ctl_pdus),
1109                     0, "cfiscsi_terminate", hz / 100);
1110         }
1111 }
1112
1113 static void
1114 cfiscsi_maintenance_thread(void *arg)
1115 {
1116         struct cfiscsi_session *cs;
1117
1118         cs = arg;
1119
1120         for (;;) {
1121                 CFISCSI_SESSION_LOCK(cs);
1122                 if (cs->cs_terminating == false)
1123                         cv_wait(&cs->cs_maintenance_cv, &cs->cs_lock);
1124                 CFISCSI_SESSION_UNLOCK(cs);
1125
1126                 if (cs->cs_terminating) {
1127
1128                         /*
1129                          * We used to wait up to 30 seconds to deliver queued
1130                          * PDUs to the initiator.  We also tried hard to deliver
1131                          * SCSI Responses for the aborted PDUs.  We don't do
1132                          * that anymore.  We might need to revisit that.
1133                          */
1134                         callout_drain(&cs->cs_callout);
1135                         icl_conn_shutdown(cs->cs_conn);
1136                         icl_conn_close(cs->cs_conn);
1137
1138                         /*
1139                          * At this point ICL receive thread is no longer
1140                          * running; no new tasks can be queued.
1141                          */
1142                         cfiscsi_session_terminate_tasks(cs);
1143                         cfiscsi_session_delete(cs);
1144                         kthread_exit();
1145                         return;
1146                 }
1147                 CFISCSI_SESSION_DEBUG(cs, "nothing to do");
1148         }
1149 }
1150
1151 static void
1152 cfiscsi_session_terminate(struct cfiscsi_session *cs)
1153 {
1154
1155         if (cs->cs_terminating)
1156                 return;
1157         cs->cs_terminating = true;
1158         cv_signal(&cs->cs_maintenance_cv);
1159 #ifdef ICL_KERNEL_PROXY
1160         cv_signal(&cs->cs_login_cv);
1161 #endif
1162 }
1163
1164 static int
1165 cfiscsi_session_register_initiator(struct cfiscsi_session *cs)
1166 {
1167         struct cfiscsi_target *ct;
1168         char *name;
1169         int i;
1170
1171         KASSERT(cs->cs_ctl_initid == -1, ("already registered"));
1172
1173         ct = cs->cs_target;
1174         name = strdup(cs->cs_initiator_id, M_CTL);
1175         i = ctl_add_initiator(&ct->ct_port, -1, 0, name);
1176         if (i < 0) {
1177                 CFISCSI_SESSION_WARN(cs, "ctl_add_initiator failed with error %d",
1178                     i);
1179                 cs->cs_ctl_initid = -1;
1180                 return (1);
1181         }
1182         cs->cs_ctl_initid = i;
1183 #if 0
1184         CFISCSI_SESSION_DEBUG(cs, "added initiator id %d", i);
1185 #endif
1186
1187         return (0);
1188 }
1189
1190 static void
1191 cfiscsi_session_unregister_initiator(struct cfiscsi_session *cs)
1192 {
1193         int error;
1194
1195         if (cs->cs_ctl_initid == -1)
1196                 return;
1197
1198         error = ctl_remove_initiator(&cs->cs_target->ct_port, cs->cs_ctl_initid);
1199         if (error != 0) {
1200                 CFISCSI_SESSION_WARN(cs, "ctl_remove_initiator failed with error %d",
1201                     error);
1202         }
1203         cs->cs_ctl_initid = -1;
1204 }
1205
1206 static struct cfiscsi_session *
1207 cfiscsi_session_new(struct cfiscsi_softc *softc)
1208 {
1209         struct cfiscsi_session *cs;
1210         int error;
1211
1212         cs = malloc(sizeof(*cs), M_CFISCSI, M_NOWAIT | M_ZERO);
1213         if (cs == NULL) {
1214                 CFISCSI_WARN("malloc failed");
1215                 return (NULL);
1216         }
1217         cs->cs_ctl_initid = -1;
1218
1219         refcount_init(&cs->cs_outstanding_ctl_pdus, 0);
1220         TAILQ_INIT(&cs->cs_waiting_for_data_out);
1221         mtx_init(&cs->cs_lock, "cfiscsi_lock", NULL, MTX_DEF);
1222         cv_init(&cs->cs_maintenance_cv, "cfiscsi_mt");
1223 #ifdef ICL_KERNEL_PROXY
1224         cv_init(&cs->cs_login_cv, "cfiscsi_login");
1225 #endif
1226
1227         cs->cs_conn = icl_conn_new("cfiscsi", &cs->cs_lock);
1228         cs->cs_conn->ic_receive = cfiscsi_receive_callback;
1229         cs->cs_conn->ic_error = cfiscsi_error_callback;
1230         cs->cs_conn->ic_prv0 = cs;
1231
1232         error = kthread_add(cfiscsi_maintenance_thread, cs, NULL, NULL, 0, 0, "cfiscsimt");
1233         if (error != 0) {
1234                 CFISCSI_SESSION_WARN(cs, "kthread_add(9) failed with error %d", error);
1235                 free(cs, M_CFISCSI);
1236                 return (NULL);
1237         }
1238
1239         mtx_lock(&softc->lock);
1240         cs->cs_id = softc->last_session_id + 1;
1241         softc->last_session_id++;
1242         mtx_unlock(&softc->lock);
1243
1244         mtx_lock(&softc->lock);
1245         TAILQ_INSERT_TAIL(&softc->sessions, cs, cs_next);
1246         mtx_unlock(&softc->lock);
1247
1248         /*
1249          * Start pinging the initiator.
1250          */
1251         callout_init(&cs->cs_callout, 1);
1252         callout_reset(&cs->cs_callout, 1 * hz, cfiscsi_callout, cs);
1253
1254         return (cs);
1255 }
1256
1257 static void
1258 cfiscsi_session_delete(struct cfiscsi_session *cs)
1259 {
1260         struct cfiscsi_softc *softc;
1261
1262         softc = &cfiscsi_softc;
1263
1264         KASSERT(cs->cs_outstanding_ctl_pdus == 0,
1265             ("destroying session with outstanding CTL pdus"));
1266         KASSERT(TAILQ_EMPTY(&cs->cs_waiting_for_data_out),
1267             ("destroying session with non-empty queue"));
1268
1269         cfiscsi_session_unregister_initiator(cs);
1270         if (cs->cs_target != NULL)
1271                 cfiscsi_target_release(cs->cs_target);
1272         icl_conn_close(cs->cs_conn);
1273         icl_conn_free(cs->cs_conn);
1274
1275         mtx_lock(&softc->lock);
1276         TAILQ_REMOVE(&softc->sessions, cs, cs_next);
1277         mtx_unlock(&softc->lock);
1278
1279         free(cs, M_CFISCSI);
1280 }
1281
1282 int
1283 cfiscsi_init(void)
1284 {
1285         struct cfiscsi_softc *softc;
1286         int retval;
1287
1288         softc = &cfiscsi_softc;
1289         retval = 0;
1290         bzero(softc, sizeof(*softc));
1291         mtx_init(&softc->lock, "cfiscsi", NULL, MTX_DEF);
1292
1293 #ifdef ICL_KERNEL_PROXY
1294         cv_init(&softc->accept_cv, "cfiscsi_accept");
1295 #endif
1296         TAILQ_INIT(&softc->sessions);
1297         TAILQ_INIT(&softc->targets);
1298
1299         cfiscsi_data_wait_zone = uma_zcreate("cfiscsi_data_wait",
1300             sizeof(struct cfiscsi_data_wait), NULL, NULL, NULL, NULL,
1301             UMA_ALIGN_PTR, 0);
1302
1303         return (0);
1304 }
1305
1306 #ifdef ICL_KERNEL_PROXY
1307 static void
1308 cfiscsi_accept(struct socket *so, struct sockaddr *sa, int portal_id)
1309 {
1310         struct cfiscsi_session *cs;
1311
1312         cs = cfiscsi_session_new(&cfiscsi_softc);
1313         if (cs == NULL) {
1314                 CFISCSI_WARN("failed to create session");
1315                 return;
1316         }
1317
1318         icl_conn_handoff_sock(cs->cs_conn, so);
1319         cs->cs_initiator_sa = sa;
1320         cs->cs_portal_id = portal_id;
1321         cs->cs_waiting_for_ctld = true;
1322         cv_signal(&cfiscsi_softc.accept_cv);
1323 }
1324 #endif
1325
1326 static void
1327 cfiscsi_online(void *arg)
1328 {
1329         struct cfiscsi_softc *softc;
1330         struct cfiscsi_target *ct;
1331         int online;
1332
1333         ct = (struct cfiscsi_target *)arg;
1334         softc = ct->ct_softc;
1335
1336         mtx_lock(&softc->lock);
1337         if (ct->ct_online) {
1338                 mtx_unlock(&softc->lock);
1339                 return;
1340         }
1341         ct->ct_online = 1;
1342         online = softc->online++;
1343         mtx_unlock(&softc->lock);
1344         if (online > 0)
1345                 return;
1346
1347 #ifdef ICL_KERNEL_PROXY
1348         if (softc->listener != NULL)
1349                 icl_listen_free(softc->listener);
1350         softc->listener = icl_listen_new(cfiscsi_accept);
1351 #endif
1352 }
1353
1354 static void
1355 cfiscsi_offline(void *arg)
1356 {
1357         struct cfiscsi_softc *softc;
1358         struct cfiscsi_target *ct;
1359         struct cfiscsi_session *cs;
1360         int online;
1361
1362         ct = (struct cfiscsi_target *)arg;
1363         softc = ct->ct_softc;
1364
1365         mtx_lock(&softc->lock);
1366         if (!ct->ct_online) {
1367                 mtx_unlock(&softc->lock);
1368                 return;
1369         }
1370         ct->ct_online = 0;
1371         online = --softc->online;
1372
1373         TAILQ_FOREACH(cs, &softc->sessions, cs_next) {
1374                 if (cs->cs_target == ct)
1375                         cfiscsi_session_terminate(cs);
1376         }
1377         mtx_unlock(&softc->lock);
1378         if (online > 0)
1379                 return;
1380
1381 #ifdef ICL_KERNEL_PROXY
1382         icl_listen_free(softc->listener);
1383         softc->listener = NULL;
1384 #endif
1385 }
1386
1387 static int
1388 cfiscsi_info(void *arg, struct sbuf *sb)
1389 {
1390         struct cfiscsi_target *ct = (struct cfiscsi_target *)arg;
1391         int retval;
1392
1393         retval = sbuf_printf(sb, "\t<cfiscsi_state>%d</cfiscsi_state>\n",
1394             ct->ct_state);
1395         return (retval);
1396 }
1397
1398 static void
1399 cfiscsi_ioctl_handoff(struct ctl_iscsi *ci)
1400 {
1401         struct cfiscsi_softc *softc;
1402         struct cfiscsi_session *cs, *cs2;
1403         struct cfiscsi_target *ct;
1404         struct ctl_iscsi_handoff_params *cihp;
1405         int error;
1406
1407         cihp = (struct ctl_iscsi_handoff_params *)&(ci->data);
1408         softc = &cfiscsi_softc;
1409
1410         CFISCSI_DEBUG("new connection from %s (%s) to %s",
1411             cihp->initiator_name, cihp->initiator_addr,
1412             cihp->target_name);
1413
1414         ct = cfiscsi_target_find(softc, cihp->target_name);
1415         if (ct == NULL) {
1416                 ci->status = CTL_ISCSI_ERROR;
1417                 snprintf(ci->error_str, sizeof(ci->error_str),
1418                     "%s: target not found", __func__);
1419                 return;
1420         }
1421
1422         if (ct->ct_online == 0) {
1423                 ci->status = CTL_ISCSI_ERROR;
1424                 snprintf(ci->error_str, sizeof(ci->error_str),
1425                     "%s: port offline", __func__);
1426                 cfiscsi_target_release(ct);
1427                 return;
1428         }
1429
1430 #ifdef ICL_KERNEL_PROXY
1431         if (cihp->socket > 0 && cihp->connection_id > 0) {
1432                 snprintf(ci->error_str, sizeof(ci->error_str),
1433                     "both socket and connection_id set");
1434                 ci->status = CTL_ISCSI_ERROR;
1435                 cfiscsi_target_release(ct);
1436                 return;
1437         }
1438         if (cihp->socket == 0) {
1439                 mtx_lock(&cfiscsi_softc.lock);
1440                 TAILQ_FOREACH(cs, &cfiscsi_softc.sessions, cs_next) {
1441                         if (cs->cs_id == cihp->socket)
1442                                 break;
1443                 }
1444                 if (cs == NULL) {
1445                         mtx_unlock(&cfiscsi_softc.lock);
1446                         snprintf(ci->error_str, sizeof(ci->error_str),
1447                             "connection not found");
1448                         ci->status = CTL_ISCSI_ERROR;
1449                         cfiscsi_target_release(ct);
1450                         return;
1451                 }
1452                 mtx_unlock(&cfiscsi_softc.lock);
1453         } else {
1454 #endif
1455                 cs = cfiscsi_session_new(softc);
1456                 if (cs == NULL) {
1457                         ci->status = CTL_ISCSI_ERROR;
1458                         snprintf(ci->error_str, sizeof(ci->error_str),
1459                             "%s: cfiscsi_session_new failed", __func__);
1460                         cfiscsi_target_release(ct);
1461                         return;
1462                 }
1463 #ifdef ICL_KERNEL_PROXY
1464         }
1465 #endif
1466         cs->cs_target = ct;
1467
1468         /*
1469          * First PDU of Full Feature phase has the same CmdSN as the last
1470          * PDU from the Login Phase received from the initiator.  Thus,
1471          * the -1 below.
1472          */
1473         cs->cs_portal_group_tag = cihp->portal_group_tag;
1474         cs->cs_cmdsn = cihp->cmdsn;
1475         cs->cs_statsn = cihp->statsn;
1476         cs->cs_max_data_segment_length = cihp->max_recv_data_segment_length;
1477         cs->cs_max_burst_length = cihp->max_burst_length;
1478         cs->cs_immediate_data = !!cihp->immediate_data;
1479         if (cihp->header_digest == CTL_ISCSI_DIGEST_CRC32C)
1480                 cs->cs_conn->ic_header_crc32c = true;
1481         if (cihp->data_digest == CTL_ISCSI_DIGEST_CRC32C)
1482                 cs->cs_conn->ic_data_crc32c = true;
1483
1484         strlcpy(cs->cs_initiator_name,
1485             cihp->initiator_name, sizeof(cs->cs_initiator_name));
1486         strlcpy(cs->cs_initiator_addr,
1487             cihp->initiator_addr, sizeof(cs->cs_initiator_addr));
1488         strlcpy(cs->cs_initiator_alias,
1489             cihp->initiator_alias, sizeof(cs->cs_initiator_alias));
1490         memcpy(cs->cs_initiator_isid,
1491             cihp->initiator_isid, sizeof(cs->cs_initiator_isid));
1492         snprintf(cs->cs_initiator_id, sizeof(cs->cs_initiator_id),
1493             "%s,i,0x%02x%02x%02x%02x%02x%02x", cs->cs_initiator_name,
1494             cihp->initiator_isid[0], cihp->initiator_isid[1],
1495             cihp->initiator_isid[2], cihp->initiator_isid[3],
1496             cihp->initiator_isid[4], cihp->initiator_isid[5]);
1497
1498         refcount_acquire(&cs->cs_outstanding_ctl_pdus);
1499 restart:
1500         if (!cs->cs_terminating) {
1501                 mtx_lock(&softc->lock);
1502                 TAILQ_FOREACH(cs2, &softc->sessions, cs_next) {
1503                         if (cs2 != cs && cs2->cs_tasks_aborted == false &&
1504                             cs->cs_target == cs2->cs_target &&
1505                             cs->cs_portal_group_tag == cs2->cs_portal_group_tag &&
1506                             strcmp(cs->cs_initiator_id, cs2->cs_initiator_id) == 0) {
1507                                 cfiscsi_session_terminate(cs2);
1508                                 mtx_unlock(&softc->lock);
1509                                 pause("cfiscsi_reinstate", 1);
1510                                 goto restart;
1511                         }
1512                 }
1513                 mtx_unlock(&softc->lock);
1514         }
1515
1516         /*
1517          * Register initiator with CTL.
1518          */
1519         cfiscsi_session_register_initiator(cs);
1520
1521 #ifdef ICL_KERNEL_PROXY
1522         if (cihp->socket > 0) {
1523 #endif
1524                 error = icl_conn_handoff(cs->cs_conn, cihp->socket);
1525                 if (error != 0) {
1526                         cfiscsi_session_terminate(cs);
1527                         refcount_release(&cs->cs_outstanding_ctl_pdus);
1528                         ci->status = CTL_ISCSI_ERROR;
1529                         snprintf(ci->error_str, sizeof(ci->error_str),
1530                             "%s: icl_conn_handoff failed with error %d",
1531                             __func__, error);
1532                         return;
1533                 }
1534 #ifdef ICL_KERNEL_PROXY
1535         }
1536 #endif
1537
1538 #ifdef ICL_KERNEL_PROXY
1539         cs->cs_login_phase = false;
1540
1541         /*
1542          * First PDU of the Full Feature phase has likely already arrived.
1543          * We have to pick it up and execute properly.
1544          */
1545         if (cs->cs_login_pdu != NULL) {
1546                 CFISCSI_SESSION_DEBUG(cs, "picking up first PDU");
1547                 cfiscsi_pdu_handle(cs->cs_login_pdu);
1548                 cs->cs_login_pdu = NULL;
1549         }
1550 #endif
1551
1552         refcount_release(&cs->cs_outstanding_ctl_pdus);
1553         ci->status = CTL_ISCSI_OK;
1554 }
1555
1556 static void
1557 cfiscsi_ioctl_list(struct ctl_iscsi *ci)
1558 {
1559         struct ctl_iscsi_list_params *cilp;
1560         struct cfiscsi_session *cs;
1561         struct cfiscsi_softc *softc;
1562         struct sbuf *sb;
1563         int error;
1564
1565         cilp = (struct ctl_iscsi_list_params *)&(ci->data);
1566         softc = &cfiscsi_softc;
1567
1568         sb = sbuf_new(NULL, NULL, cilp->alloc_len, SBUF_FIXEDLEN);
1569         if (sb == NULL) {
1570                 ci->status = CTL_ISCSI_ERROR;
1571                 snprintf(ci->error_str, sizeof(ci->error_str),
1572                     "Unable to allocate %d bytes for iSCSI session list",
1573                     cilp->alloc_len);
1574                 return;
1575         }
1576
1577         sbuf_printf(sb, "<ctlislist>\n");
1578         mtx_lock(&softc->lock);
1579         TAILQ_FOREACH(cs, &softc->sessions, cs_next) {
1580 #ifdef ICL_KERNEL_PROXY
1581                 if (cs->cs_target == NULL)
1582                         continue;
1583 #endif
1584                 error = sbuf_printf(sb, "<connection id=\"%d\">"
1585                     "<initiator>%s</initiator>"
1586                     "<initiator_addr>%s</initiator_addr>"
1587                     "<initiator_alias>%s</initiator_alias>"
1588                     "<target>%s</target>"
1589                     "<target_alias>%s</target_alias>"
1590                     "<header_digest>%s</header_digest>"
1591                     "<data_digest>%s</data_digest>"
1592                     "<max_data_segment_length>%zd</max_data_segment_length>"
1593                     "<immediate_data>%d</immediate_data>"
1594                     "<iser>%d</iser>"
1595                     "</connection>\n",
1596                     cs->cs_id,
1597                     cs->cs_initiator_name, cs->cs_initiator_addr, cs->cs_initiator_alias,
1598                     cs->cs_target->ct_name, cs->cs_target->ct_alias,
1599                     cs->cs_conn->ic_header_crc32c ? "CRC32C" : "None",
1600                     cs->cs_conn->ic_data_crc32c ? "CRC32C" : "None",
1601                     cs->cs_max_data_segment_length,
1602                     cs->cs_immediate_data,
1603                     cs->cs_conn->ic_iser);
1604                 if (error != 0)
1605                         break;
1606         }
1607         mtx_unlock(&softc->lock);
1608         error = sbuf_printf(sb, "</ctlislist>\n");
1609         if (error != 0) {
1610                 sbuf_delete(sb);
1611                 ci->status = CTL_ISCSI_LIST_NEED_MORE_SPACE;
1612                 snprintf(ci->error_str, sizeof(ci->error_str),
1613                     "Out of space, %d bytes is too small", cilp->alloc_len);
1614                 return;
1615         }
1616         sbuf_finish(sb);
1617
1618         error = copyout(sbuf_data(sb), cilp->conn_xml, sbuf_len(sb) + 1);
1619         cilp->fill_len = sbuf_len(sb) + 1;
1620         ci->status = CTL_ISCSI_OK;
1621         sbuf_delete(sb);
1622 }
1623
1624 static void
1625 cfiscsi_ioctl_terminate(struct ctl_iscsi *ci)
1626 {
1627         struct icl_pdu *response;
1628         struct iscsi_bhs_asynchronous_message *bhsam;
1629         struct ctl_iscsi_terminate_params *citp;
1630         struct cfiscsi_session *cs;
1631         struct cfiscsi_softc *softc;
1632         int found = 0;
1633
1634         citp = (struct ctl_iscsi_terminate_params *)&(ci->data);
1635         softc = &cfiscsi_softc;
1636
1637         mtx_lock(&softc->lock);
1638         TAILQ_FOREACH(cs, &softc->sessions, cs_next) {
1639                 if (citp->all == 0 && cs->cs_id != citp->connection_id &&
1640                     strcmp(cs->cs_initiator_name, citp->initiator_name) != 0 &&
1641                     strcmp(cs->cs_initiator_addr, citp->initiator_addr) != 0)
1642                         continue;
1643
1644                 response = icl_pdu_new_bhs(cs->cs_conn, M_NOWAIT);
1645                 if (response == NULL) {
1646                         /*
1647                          * Oh well.  Just terminate the connection.
1648                          */
1649                 } else {
1650                         bhsam = (struct iscsi_bhs_asynchronous_message *)
1651                             response->ip_bhs;
1652                         bhsam->bhsam_opcode = ISCSI_BHS_OPCODE_ASYNC_MESSAGE;
1653                         bhsam->bhsam_flags = 0x80;
1654                         bhsam->bhsam_0xffffffff = 0xffffffff;
1655                         bhsam->bhsam_async_event =
1656                             BHSAM_EVENT_TARGET_TERMINATES_SESSION;
1657                         cfiscsi_pdu_queue(response);
1658                 }
1659                 cfiscsi_session_terminate(cs);
1660                 found++;
1661         }
1662         mtx_unlock(&softc->lock);
1663
1664         if (found == 0) {
1665                 ci->status = CTL_ISCSI_SESSION_NOT_FOUND;
1666                 snprintf(ci->error_str, sizeof(ci->error_str),
1667                     "No matching connections found");
1668                 return;
1669         }
1670
1671         ci->status = CTL_ISCSI_OK;
1672 }
1673
1674 static void
1675 cfiscsi_ioctl_logout(struct ctl_iscsi *ci)
1676 {
1677         struct icl_pdu *response;
1678         struct iscsi_bhs_asynchronous_message *bhsam;
1679         struct ctl_iscsi_logout_params *cilp;
1680         struct cfiscsi_session *cs;
1681         struct cfiscsi_softc *softc;
1682         int found = 0;
1683
1684         cilp = (struct ctl_iscsi_logout_params *)&(ci->data);
1685         softc = &cfiscsi_softc;
1686
1687         mtx_lock(&softc->lock);
1688         TAILQ_FOREACH(cs, &softc->sessions, cs_next) {
1689                 if (cilp->all == 0 && cs->cs_id != cilp->connection_id &&
1690                     strcmp(cs->cs_initiator_name, cilp->initiator_name) != 0 &&
1691                     strcmp(cs->cs_initiator_addr, cilp->initiator_addr) != 0)
1692                         continue;
1693
1694                 response = icl_pdu_new_bhs(cs->cs_conn, M_NOWAIT);
1695                 if (response == NULL) {
1696                         ci->status = CTL_ISCSI_ERROR;
1697                         snprintf(ci->error_str, sizeof(ci->error_str),
1698                             "Unable to allocate memory");
1699                         mtx_unlock(&softc->lock);
1700                         return;
1701                 }
1702                 bhsam =
1703                     (struct iscsi_bhs_asynchronous_message *)response->ip_bhs;
1704                 bhsam->bhsam_opcode = ISCSI_BHS_OPCODE_ASYNC_MESSAGE;
1705                 bhsam->bhsam_flags = 0x80;
1706                 bhsam->bhsam_async_event = BHSAM_EVENT_TARGET_REQUESTS_LOGOUT;
1707                 bhsam->bhsam_parameter3 = htons(10);
1708                 cfiscsi_pdu_queue(response);
1709                 found++;
1710         }
1711         mtx_unlock(&softc->lock);
1712
1713         if (found == 0) {
1714                 ci->status = CTL_ISCSI_SESSION_NOT_FOUND;
1715                 snprintf(ci->error_str, sizeof(ci->error_str),
1716                     "No matching connections found");
1717                 return;
1718         }
1719
1720         ci->status = CTL_ISCSI_OK;
1721 }
1722
1723 #ifdef ICL_KERNEL_PROXY
1724 static void
1725 cfiscsi_ioctl_listen(struct ctl_iscsi *ci)
1726 {
1727         struct ctl_iscsi_listen_params *cilp;
1728         struct sockaddr *sa;
1729         int error;
1730
1731         cilp = (struct ctl_iscsi_listen_params *)&(ci->data);
1732
1733         if (cfiscsi_softc.listener == NULL) {
1734                 CFISCSI_DEBUG("no listener");
1735                 snprintf(ci->error_str, sizeof(ci->error_str), "no listener");
1736                 ci->status = CTL_ISCSI_ERROR;
1737                 return;
1738         }
1739
1740         error = getsockaddr(&sa, (void *)cilp->addr, cilp->addrlen);
1741         if (error != 0) {
1742                 CFISCSI_DEBUG("getsockaddr, error %d", error);
1743                 snprintf(ci->error_str, sizeof(ci->error_str), "getsockaddr failed");
1744                 ci->status = CTL_ISCSI_ERROR;
1745                 return;
1746         }
1747
1748         error = icl_listen_add(cfiscsi_softc.listener, cilp->iser, cilp->domain,
1749             cilp->socktype, cilp->protocol, sa, cilp->portal_id);
1750         if (error != 0) {
1751                 free(sa, M_SONAME);
1752                 CFISCSI_DEBUG("icl_listen_add, error %d", error);
1753                 snprintf(ci->error_str, sizeof(ci->error_str),
1754                     "icl_listen_add failed, error %d", error);
1755                 ci->status = CTL_ISCSI_ERROR;
1756                 return;
1757         }
1758
1759         ci->status = CTL_ISCSI_OK;
1760 }
1761
1762 static void
1763 cfiscsi_ioctl_accept(struct ctl_iscsi *ci)
1764 {
1765         struct ctl_iscsi_accept_params *ciap;
1766         struct cfiscsi_session *cs;
1767         int error;
1768
1769         ciap = (struct ctl_iscsi_accept_params *)&(ci->data);
1770
1771         mtx_lock(&cfiscsi_softc.lock);
1772         for (;;) {
1773                 TAILQ_FOREACH(cs, &cfiscsi_softc.sessions, cs_next) {
1774                         if (cs->cs_waiting_for_ctld)
1775                                 break;
1776                 }
1777                 if (cs != NULL)
1778                         break;
1779                 error = cv_wait_sig(&cfiscsi_softc.accept_cv, &cfiscsi_softc.lock);
1780                 if (error != 0) {
1781                         mtx_unlock(&cfiscsi_softc.lock);
1782                         snprintf(ci->error_str, sizeof(ci->error_str), "interrupted");
1783                         ci->status = CTL_ISCSI_ERROR;
1784                         return;
1785                 }
1786         }
1787         mtx_unlock(&cfiscsi_softc.lock);
1788
1789         cs->cs_waiting_for_ctld = false;
1790         cs->cs_login_phase = true;
1791
1792         ciap->connection_id = cs->cs_id;
1793         ciap->portal_id = cs->cs_portal_id;
1794         ciap->initiator_addrlen = cs->cs_initiator_sa->sa_len;
1795         error = copyout(cs->cs_initiator_sa, ciap->initiator_addr,
1796             cs->cs_initiator_sa->sa_len);
1797         if (error != 0) {
1798                 snprintf(ci->error_str, sizeof(ci->error_str),
1799                     "copyout failed with error %d", error);
1800                 ci->status = CTL_ISCSI_ERROR;
1801                 return;
1802         }
1803
1804         ci->status = CTL_ISCSI_OK;
1805 }
1806
1807 static void
1808 cfiscsi_ioctl_send(struct ctl_iscsi *ci)
1809 {
1810         struct ctl_iscsi_send_params *cisp;
1811         struct cfiscsi_session *cs;
1812         struct icl_pdu *ip;
1813         size_t datalen;
1814         void *data;
1815         int error;
1816
1817         cisp = (struct ctl_iscsi_send_params *)&(ci->data);
1818
1819         mtx_lock(&cfiscsi_softc.lock);
1820         TAILQ_FOREACH(cs, &cfiscsi_softc.sessions, cs_next) {
1821                 if (cs->cs_id == cisp->connection_id)
1822                         break;
1823         }
1824         if (cs == NULL) {
1825                 mtx_unlock(&cfiscsi_softc.lock);
1826                 snprintf(ci->error_str, sizeof(ci->error_str), "connection not found");
1827                 ci->status = CTL_ISCSI_ERROR;
1828                 return;
1829         }
1830         mtx_unlock(&cfiscsi_softc.lock);
1831
1832 #if 0
1833         if (cs->cs_login_phase == false)
1834                 return (EBUSY);
1835 #endif
1836
1837         if (cs->cs_terminating) {
1838                 snprintf(ci->error_str, sizeof(ci->error_str), "connection is terminating");
1839                 ci->status = CTL_ISCSI_ERROR;
1840                 return;
1841         }
1842
1843         datalen = cisp->data_segment_len;
1844         /*
1845          * XXX
1846          */
1847         //if (datalen > CFISCSI_MAX_DATA_SEGMENT_LENGTH) {
1848         if (datalen > 65535) {
1849                 snprintf(ci->error_str, sizeof(ci->error_str), "data segment too big");
1850                 ci->status = CTL_ISCSI_ERROR;
1851                 return;
1852         }
1853         if (datalen > 0) {
1854                 data = malloc(datalen, M_CFISCSI, M_WAITOK);
1855                 error = copyin(cisp->data_segment, data, datalen);
1856                 if (error != 0) {
1857                         free(data, M_CFISCSI);
1858                         snprintf(ci->error_str, sizeof(ci->error_str), "copyin error %d", error);
1859                         ci->status = CTL_ISCSI_ERROR;
1860                         return;
1861                 }
1862         }
1863
1864         ip = icl_pdu_new_bhs(cs->cs_conn, M_WAITOK);
1865         memcpy(ip->ip_bhs, cisp->bhs, sizeof(*ip->ip_bhs));
1866         if (datalen > 0) {
1867                 icl_pdu_append_data(ip, data, datalen, M_WAITOK);
1868                 free(data, M_CFISCSI);
1869         }
1870         CFISCSI_SESSION_LOCK(cs);
1871         icl_pdu_queue(ip);
1872         CFISCSI_SESSION_UNLOCK(cs);
1873         ci->status = CTL_ISCSI_OK;
1874 }
1875
1876 static void
1877 cfiscsi_ioctl_receive(struct ctl_iscsi *ci)
1878 {
1879         struct ctl_iscsi_receive_params *cirp;
1880         struct cfiscsi_session *cs;
1881         struct icl_pdu *ip;
1882         void *data;
1883         int error;
1884
1885         cirp = (struct ctl_iscsi_receive_params *)&(ci->data);
1886
1887         mtx_lock(&cfiscsi_softc.lock);
1888         TAILQ_FOREACH(cs, &cfiscsi_softc.sessions, cs_next) {
1889                 if (cs->cs_id == cirp->connection_id)
1890                         break;
1891         }
1892         if (cs == NULL) {
1893                 mtx_unlock(&cfiscsi_softc.lock);
1894                 snprintf(ci->error_str, sizeof(ci->error_str),
1895                     "connection not found");
1896                 ci->status = CTL_ISCSI_ERROR;
1897                 return;
1898         }
1899         mtx_unlock(&cfiscsi_softc.lock);
1900
1901 #if 0
1902         if (is->is_login_phase == false)
1903                 return (EBUSY);
1904 #endif
1905
1906         CFISCSI_SESSION_LOCK(cs);
1907         while (cs->cs_login_pdu == NULL && cs->cs_terminating == false) {
1908                 error = cv_wait_sig(&cs->cs_login_cv, &cs->cs_lock);
1909                 if (error != 0) {
1910                         CFISCSI_SESSION_UNLOCK(cs);
1911                         snprintf(ci->error_str, sizeof(ci->error_str),
1912                             "interrupted by signal");
1913                         ci->status = CTL_ISCSI_ERROR;
1914                         return;
1915                 }
1916         }
1917
1918         if (cs->cs_terminating) {
1919                 CFISCSI_SESSION_UNLOCK(cs);
1920                 snprintf(ci->error_str, sizeof(ci->error_str),
1921                     "connection terminating");
1922                 ci->status = CTL_ISCSI_ERROR;
1923                 return;
1924         }
1925         ip = cs->cs_login_pdu;
1926         cs->cs_login_pdu = NULL;
1927         CFISCSI_SESSION_UNLOCK(cs);
1928
1929         if (ip->ip_data_len > cirp->data_segment_len) {
1930                 icl_pdu_free(ip);
1931                 snprintf(ci->error_str, sizeof(ci->error_str),
1932                     "data segment too big");
1933                 ci->status = CTL_ISCSI_ERROR;
1934                 return;
1935         }
1936
1937         copyout(ip->ip_bhs, cirp->bhs, sizeof(*ip->ip_bhs));
1938         if (ip->ip_data_len > 0) {
1939                 data = malloc(ip->ip_data_len, M_CFISCSI, M_WAITOK);
1940                 icl_pdu_get_data(ip, 0, data, ip->ip_data_len);
1941                 copyout(data, cirp->data_segment, ip->ip_data_len);
1942                 free(data, M_CFISCSI);
1943         }
1944
1945         icl_pdu_free(ip);
1946         ci->status = CTL_ISCSI_OK;
1947 }
1948
1949 #endif /* !ICL_KERNEL_PROXY */
1950
1951 static void
1952 cfiscsi_ioctl_port_create(struct ctl_req *req)
1953 {
1954         struct cfiscsi_target *ct;
1955         struct ctl_port *port;
1956         const char *target, *alias, *tag;
1957         struct scsi_vpd_id_descriptor *desc;
1958         ctl_options_t opts;
1959         int retval, len, idlen;
1960
1961         ctl_init_opts(&opts, req->num_args, req->kern_args);
1962         target = ctl_get_opt(&opts, "cfiscsi_target");
1963         alias = ctl_get_opt(&opts, "cfiscsi_target_alias");
1964         tag = ctl_get_opt(&opts, "cfiscsi_portal_group_tag");
1965         if (target == NULL || tag == NULL) {
1966                 req->status = CTL_LUN_ERROR;
1967                 snprintf(req->error_str, sizeof(req->error_str),
1968                     "Missing required argument");
1969                 ctl_free_opts(&opts);
1970                 return;
1971         }
1972         ct = cfiscsi_target_find_or_create(&cfiscsi_softc, target, alias);
1973         if (ct == NULL) {
1974                 req->status = CTL_LUN_ERROR;
1975                 snprintf(req->error_str, sizeof(req->error_str),
1976                     "failed to create target \"%s\"", target);
1977                 ctl_free_opts(&opts);
1978                 return;
1979         }
1980         if (ct->ct_state == CFISCSI_TARGET_STATE_ACTIVE) {
1981                 req->status = CTL_LUN_ERROR;
1982                 snprintf(req->error_str, sizeof(req->error_str),
1983                     "target \"%s\" already exist", target);
1984                 cfiscsi_target_release(ct);
1985                 ctl_free_opts(&opts);
1986                 return;
1987         }
1988         port = &ct->ct_port;
1989         if (ct->ct_state == CFISCSI_TARGET_STATE_DYING)
1990                 goto done;
1991
1992         port->frontend = &cfiscsi_frontend;
1993         port->port_type = CTL_PORT_ISCSI;
1994         /* XXX KDM what should the real number be here? */
1995         port->num_requested_ctl_io = 4096;
1996         port->port_name = "iscsi";
1997         port->virtual_port = strtoul(tag, NULL, 0);
1998         port->port_online = cfiscsi_online;
1999         port->port_offline = cfiscsi_offline;
2000         port->port_info = cfiscsi_info;
2001         port->onoff_arg = ct;
2002         port->lun_enable = cfiscsi_lun_enable;
2003         port->lun_disable = cfiscsi_lun_disable;
2004         port->lun_map = cfiscsi_lun_map;
2005         port->targ_lun_arg = ct;
2006         port->fe_datamove = cfiscsi_datamove;
2007         port->fe_done = cfiscsi_done;
2008
2009         /* XXX KDM what should we report here? */
2010         /* XXX These should probably be fetched from CTL. */
2011         port->max_targets = 1;
2012         port->max_target_id = 15;
2013
2014         port->options = opts;
2015         STAILQ_INIT(&opts);
2016
2017         /* Generate Port ID. */
2018         idlen = strlen(target) + strlen(",t,0x0001") + 1;
2019         idlen = roundup2(idlen, 4);
2020         len = sizeof(struct scsi_vpd_device_id) + idlen;
2021         port->port_devid = malloc(sizeof(struct ctl_devid) + len,
2022             M_CTL, M_WAITOK | M_ZERO);
2023         port->port_devid->len = len;
2024         desc = (struct scsi_vpd_id_descriptor *)port->port_devid->data;
2025         desc->proto_codeset = (SCSI_PROTO_ISCSI << 4) | SVPD_ID_CODESET_UTF8;
2026         desc->id_type = SVPD_ID_PIV | SVPD_ID_ASSOC_PORT |
2027             SVPD_ID_TYPE_SCSI_NAME;
2028         desc->length = idlen;
2029         snprintf(desc->identifier, idlen, "%s,t,0x%4.4x",
2030             target, port->virtual_port);
2031
2032         /* Generate Target ID. */
2033         idlen = strlen(target) + 1;
2034         idlen = roundup2(idlen, 4);
2035         len = sizeof(struct scsi_vpd_device_id) + idlen;
2036         port->target_devid = malloc(sizeof(struct ctl_devid) + len,
2037             M_CTL, M_WAITOK | M_ZERO);
2038         port->target_devid->len = len;
2039         desc = (struct scsi_vpd_id_descriptor *)port->target_devid->data;
2040         desc->proto_codeset = (SCSI_PROTO_ISCSI << 4) | SVPD_ID_CODESET_UTF8;
2041         desc->id_type = SVPD_ID_PIV | SVPD_ID_ASSOC_TARGET |
2042             SVPD_ID_TYPE_SCSI_NAME;
2043         desc->length = idlen;
2044         strlcpy(desc->identifier, target, idlen);
2045
2046         retval = ctl_port_register(port, /*master_SC*/ 1);
2047         if (retval != 0) {
2048                 ctl_free_opts(&port->options);
2049                 cfiscsi_target_release(ct);
2050                 free(port->port_devid, M_CFISCSI);
2051                 free(port->target_devid, M_CFISCSI);
2052                 req->status = CTL_LUN_ERROR;
2053                 snprintf(req->error_str, sizeof(req->error_str),
2054                     "ctl_frontend_register() failed with error %d", retval);
2055                 return;
2056         }
2057 done:
2058         ct->ct_state = CFISCSI_TARGET_STATE_ACTIVE;
2059         req->status = CTL_LUN_OK;
2060         memcpy(req->kern_args[0].kvalue, &port->targ_port,
2061             sizeof(port->targ_port)); //XXX
2062 }
2063
2064 static void
2065 cfiscsi_ioctl_port_remove(struct ctl_req *req)
2066 {
2067         struct cfiscsi_target *ct;
2068         const char *target;
2069         ctl_options_t opts;
2070
2071         ctl_init_opts(&opts, req->num_args, req->kern_args);
2072         target = ctl_get_opt(&opts, "cfiscsi_target");
2073         if (target == NULL) {
2074                 ctl_free_opts(&opts);
2075                 req->status = CTL_LUN_ERROR;
2076                 snprintf(req->error_str, sizeof(req->error_str),
2077                     "Missing required argument");
2078                 return;
2079         }
2080         ct = cfiscsi_target_find(&cfiscsi_softc, target);
2081         if (ct == NULL) {
2082                 ctl_free_opts(&opts);
2083                 req->status = CTL_LUN_ERROR;
2084                 snprintf(req->error_str, sizeof(req->error_str),
2085                     "can't find target \"%s\"", target);
2086                 return;
2087         }
2088         if (ct->ct_state != CFISCSI_TARGET_STATE_ACTIVE) {
2089                 ctl_free_opts(&opts);
2090                 req->status = CTL_LUN_ERROR;
2091                 snprintf(req->error_str, sizeof(req->error_str),
2092                     "target \"%s\" is already dying", target);
2093                 return;
2094         }
2095         ctl_free_opts(&opts);
2096
2097         ct->ct_state = CFISCSI_TARGET_STATE_DYING;
2098         ctl_port_offline(&ct->ct_port);
2099         cfiscsi_target_release(ct);
2100         cfiscsi_target_release(ct);
2101 }
2102
2103 static int
2104 cfiscsi_ioctl(struct cdev *dev,
2105     u_long cmd, caddr_t addr, int flag, struct thread *td)
2106 {
2107         struct ctl_iscsi *ci;
2108         struct ctl_req *req;
2109
2110         if (cmd == CTL_PORT_REQ) {
2111                 req = (struct ctl_req *)addr;
2112                 switch (req->reqtype) {
2113                 case CTL_REQ_CREATE:
2114                         cfiscsi_ioctl_port_create(req);
2115                         break;
2116                 case CTL_REQ_REMOVE:
2117                         cfiscsi_ioctl_port_remove(req);
2118                         break;
2119                 default:
2120                         req->status = CTL_LUN_ERROR;
2121                         snprintf(req->error_str, sizeof(req->error_str),
2122                             "Unsupported request type %d", req->reqtype);
2123                 }
2124                 return (0);
2125         }
2126
2127         if (cmd != CTL_ISCSI)
2128                 return (ENOTTY);
2129
2130         ci = (struct ctl_iscsi *)addr;
2131         switch (ci->type) {
2132         case CTL_ISCSI_HANDOFF:
2133                 cfiscsi_ioctl_handoff(ci);
2134                 break;
2135         case CTL_ISCSI_LIST:
2136                 cfiscsi_ioctl_list(ci);
2137                 break;
2138         case CTL_ISCSI_TERMINATE:
2139                 cfiscsi_ioctl_terminate(ci);
2140                 break;
2141         case CTL_ISCSI_LOGOUT:
2142                 cfiscsi_ioctl_logout(ci);
2143                 break;
2144 #ifdef ICL_KERNEL_PROXY
2145         case CTL_ISCSI_LISTEN:
2146                 cfiscsi_ioctl_listen(ci);
2147                 break;
2148         case CTL_ISCSI_ACCEPT:
2149                 cfiscsi_ioctl_accept(ci);
2150                 break;
2151         case CTL_ISCSI_SEND:
2152                 cfiscsi_ioctl_send(ci);
2153                 break;
2154         case CTL_ISCSI_RECEIVE:
2155                 cfiscsi_ioctl_receive(ci);
2156                 break;
2157 #else
2158         case CTL_ISCSI_LISTEN:
2159         case CTL_ISCSI_ACCEPT:
2160         case CTL_ISCSI_SEND:
2161         case CTL_ISCSI_RECEIVE:
2162                 ci->status = CTL_ISCSI_ERROR;
2163                 snprintf(ci->error_str, sizeof(ci->error_str),
2164                     "%s: CTL compiled without ICL_KERNEL_PROXY",
2165                     __func__);
2166                 break;
2167 #endif /* !ICL_KERNEL_PROXY */
2168         default:
2169                 ci->status = CTL_ISCSI_ERROR;
2170                 snprintf(ci->error_str, sizeof(ci->error_str),
2171                     "%s: invalid iSCSI request type %d", __func__, ci->type);
2172                 break;
2173         }
2174
2175         return (0);
2176 }
2177
2178 static void
2179 cfiscsi_target_hold(struct cfiscsi_target *ct)
2180 {
2181
2182         refcount_acquire(&ct->ct_refcount);
2183 }
2184
2185 static void
2186 cfiscsi_target_release(struct cfiscsi_target *ct)
2187 {
2188         struct cfiscsi_softc *softc;
2189
2190         softc = ct->ct_softc;
2191         mtx_lock(&softc->lock);
2192         if (refcount_release(&ct->ct_refcount)) {
2193                 TAILQ_REMOVE(&softc->targets, ct, ct_next);
2194                 mtx_unlock(&softc->lock);
2195                 if (ct->ct_state != CFISCSI_TARGET_STATE_INVALID) {
2196                         ct->ct_state = CFISCSI_TARGET_STATE_INVALID;
2197                         if (ctl_port_deregister(&ct->ct_port) != 0)
2198                                 printf("%s: ctl_port_deregister() failed\n",
2199                                     __func__);
2200                 }
2201                 free(ct, M_CFISCSI);
2202
2203                 return;
2204         }
2205         mtx_unlock(&softc->lock);
2206 }
2207
2208 static struct cfiscsi_target *
2209 cfiscsi_target_find(struct cfiscsi_softc *softc, const char *name)
2210 {
2211         struct cfiscsi_target *ct;
2212
2213         mtx_lock(&softc->lock);
2214         TAILQ_FOREACH(ct, &softc->targets, ct_next) {
2215                 if (strcmp(name, ct->ct_name) != 0 ||
2216                     ct->ct_state != CFISCSI_TARGET_STATE_ACTIVE)
2217                         continue;
2218                 cfiscsi_target_hold(ct);
2219                 mtx_unlock(&softc->lock);
2220                 return (ct);
2221         }
2222         mtx_unlock(&softc->lock);
2223
2224         return (NULL);
2225 }
2226
2227 static struct cfiscsi_target *
2228 cfiscsi_target_find_or_create(struct cfiscsi_softc *softc, const char *name,
2229     const char *alias)
2230 {
2231         struct cfiscsi_target *ct, *newct;
2232         int i;
2233
2234         if (name[0] == '\0' || strlen(name) >= CTL_ISCSI_NAME_LEN)
2235                 return (NULL);
2236
2237         newct = malloc(sizeof(*newct), M_CFISCSI, M_WAITOK | M_ZERO);
2238
2239         mtx_lock(&softc->lock);
2240         TAILQ_FOREACH(ct, &softc->targets, ct_next) {
2241                 if (strcmp(name, ct->ct_name) != 0 ||
2242                     ct->ct_state == CFISCSI_TARGET_STATE_INVALID)
2243                         continue;
2244                 cfiscsi_target_hold(ct);
2245                 mtx_unlock(&softc->lock);
2246                 free(newct, M_CFISCSI);
2247                 return (ct);
2248         }
2249
2250         for (i = 0; i < CTL_MAX_LUNS; i++)
2251                 newct->ct_luns[i] = UINT32_MAX;
2252
2253         strlcpy(newct->ct_name, name, sizeof(newct->ct_name));
2254         if (alias != NULL)
2255                 strlcpy(newct->ct_alias, alias, sizeof(newct->ct_alias));
2256         refcount_init(&newct->ct_refcount, 1);
2257         newct->ct_softc = softc;
2258         TAILQ_INSERT_TAIL(&softc->targets, newct, ct_next);
2259         mtx_unlock(&softc->lock);
2260
2261         return (newct);
2262 }
2263
2264 /*
2265  * Takes LUN from the target space and returns LUN from the CTL space.
2266  */
2267 static uint32_t
2268 cfiscsi_lun_map(void *arg, uint32_t lun)
2269 {
2270         struct cfiscsi_target *ct = arg;
2271
2272         if (lun >= CTL_MAX_LUNS) {
2273                 CFISCSI_DEBUG("requested lun number %d is higher "
2274                     "than maximum %d", lun, CTL_MAX_LUNS - 1);
2275                 return (UINT32_MAX);
2276         }
2277         return (ct->ct_luns[lun]);
2278 }
2279
2280 static int
2281 cfiscsi_target_set_lun(struct cfiscsi_target *ct,
2282     unsigned long lun_id, unsigned long ctl_lun_id)
2283 {
2284
2285         if (lun_id >= CTL_MAX_LUNS) {
2286                 CFISCSI_WARN("requested lun number %ld is higher "
2287                     "than maximum %d", lun_id, CTL_MAX_LUNS - 1);
2288                 return (-1);
2289         }
2290
2291         if (ct->ct_luns[lun_id] < CTL_MAX_LUNS) {
2292                 /*
2293                  * CTL calls cfiscsi_lun_enable() twice for each LUN - once
2294                  * when the LUN is created, and a second time just before
2295                  * the port is brought online; don't emit warnings
2296                  * for that case.
2297                  */
2298                 if (ct->ct_luns[lun_id] == ctl_lun_id)
2299                         return (0);
2300                 CFISCSI_WARN("lun %ld already allocated", lun_id);
2301                 return (-1);
2302         }
2303
2304 #if 0
2305         CFISCSI_DEBUG("adding mapping for lun %ld, target %s "
2306             "to ctl lun %ld", lun_id, ct->ct_name, ctl_lun_id);
2307 #endif
2308
2309         ct->ct_luns[lun_id] = ctl_lun_id;
2310
2311         return (0);
2312 }
2313
2314 static int
2315 cfiscsi_lun_enable(void *arg, struct ctl_id target_id, int lun_id)
2316 {
2317         struct cfiscsi_softc *softc;
2318         struct cfiscsi_target *ct;
2319         const char *target = NULL;
2320         const char *lun = NULL;
2321         unsigned long tmp;
2322
2323         ct = (struct cfiscsi_target *)arg;
2324         softc = ct->ct_softc;
2325
2326         target = ctl_get_opt(&control_softc->ctl_luns[lun_id]->be_lun->options,
2327             "cfiscsi_target");
2328         lun = ctl_get_opt(&control_softc->ctl_luns[lun_id]->be_lun->options,
2329             "cfiscsi_lun");
2330
2331         if (target == NULL && lun == NULL)
2332                 return (0);
2333
2334         if (target == NULL || lun == NULL) {
2335                 CFISCSI_WARN("lun added with cfiscsi_target, but without "
2336                     "cfiscsi_lun, or the other way around; ignoring");
2337                 return (0);
2338         }
2339
2340         if (strcmp(target, ct->ct_name) != 0)
2341                 return (0);
2342
2343         tmp = strtoul(lun, NULL, 10);
2344         cfiscsi_target_set_lun(ct, tmp, lun_id);
2345         return (0);
2346 }
2347
2348 static int
2349 cfiscsi_lun_disable(void *arg, struct ctl_id target_id, int lun_id)
2350 {
2351         struct cfiscsi_softc *softc;
2352         struct cfiscsi_target *ct;
2353         int i;
2354
2355         ct = (struct cfiscsi_target *)arg;
2356         softc = ct->ct_softc;
2357
2358         mtx_lock(&softc->lock);
2359         for (i = 0; i < CTL_MAX_LUNS; i++) {
2360                 if (ct->ct_luns[i] != lun_id)
2361                         continue;
2362                 ct->ct_luns[i] = UINT32_MAX;
2363                 break;
2364         }
2365         mtx_unlock(&softc->lock);
2366         return (0);
2367 }
2368
2369 static void
2370 cfiscsi_datamove_in(union ctl_io *io)
2371 {
2372         struct cfiscsi_session *cs;
2373         struct icl_pdu *request, *response;
2374         const struct iscsi_bhs_scsi_command *bhssc;
2375         struct iscsi_bhs_data_in *bhsdi;
2376         struct ctl_sg_entry ctl_sg_entry, *ctl_sglist;
2377         size_t len, expected_len, sg_len, buffer_offset;
2378         const char *sg_addr;
2379         int ctl_sg_count, error, i;
2380
2381         request = io->io_hdr.ctl_private[CTL_PRIV_FRONTEND].ptr;
2382         cs = PDU_SESSION(request);
2383
2384         bhssc = (const struct iscsi_bhs_scsi_command *)request->ip_bhs;
2385         KASSERT((bhssc->bhssc_opcode & ~ISCSI_BHS_OPCODE_IMMEDIATE) ==
2386             ISCSI_BHS_OPCODE_SCSI_COMMAND,
2387             ("bhssc->bhssc_opcode != ISCSI_BHS_OPCODE_SCSI_COMMAND"));
2388
2389         if (io->scsiio.kern_sg_entries > 0) {
2390                 ctl_sglist = (struct ctl_sg_entry *)io->scsiio.kern_data_ptr;
2391                 ctl_sg_count = io->scsiio.kern_sg_entries;
2392         } else {
2393                 ctl_sglist = &ctl_sg_entry;
2394                 ctl_sglist->addr = io->scsiio.kern_data_ptr;
2395                 ctl_sglist->len = io->scsiio.kern_data_len;
2396                 ctl_sg_count = 1;
2397         }
2398
2399         /*
2400          * This is the total amount of data to be transferred within the current
2401          * SCSI command.  We need to record it so that we can properly report
2402          * underflow/underflow.
2403          */
2404         PDU_TOTAL_TRANSFER_LEN(request) = io->scsiio.kern_total_len;
2405
2406         /*
2407          * This is the offset within the current SCSI command; for the first
2408          * call to cfiscsi_datamove() it will be 0, and for subsequent ones
2409          * it will be the sum of lengths of previous ones.
2410          */
2411         buffer_offset = io->scsiio.kern_rel_offset;
2412
2413         /*
2414          * This is the transfer length expected by the initiator.  In theory,
2415          * it could be different from the correct amount of data from the SCSI
2416          * point of view, even if that doesn't make any sense.
2417          */
2418         expected_len = ntohl(bhssc->bhssc_expected_data_transfer_length);
2419 #if 0
2420         if (expected_len != io->scsiio.kern_total_len) {
2421                 CFISCSI_SESSION_DEBUG(cs, "expected transfer length %zd, "
2422                     "actual length %zd", expected_len,
2423                     (size_t)io->scsiio.kern_total_len);
2424         }
2425 #endif
2426
2427         if (buffer_offset >= expected_len) {
2428 #if 0
2429                 CFISCSI_SESSION_DEBUG(cs, "buffer_offset = %zd, "
2430                     "already sent the expected len", buffer_offset);
2431 #endif
2432                 io->scsiio.be_move_done(io);
2433                 return;
2434         }
2435
2436         i = 0;
2437         sg_addr = NULL;
2438         sg_len = 0;
2439         response = NULL;
2440         bhsdi = NULL;
2441         for (;;) {
2442                 if (response == NULL) {
2443                         response = cfiscsi_pdu_new_response(request, M_NOWAIT);
2444                         if (response == NULL) {
2445                                 CFISCSI_SESSION_WARN(cs, "failed to "
2446                                     "allocate memory; dropping connection");
2447                                 ctl_set_busy(&io->scsiio);
2448                                 io->scsiio.be_move_done(io);
2449                                 cfiscsi_session_terminate(cs);
2450                                 return;
2451                         }
2452                         bhsdi = (struct iscsi_bhs_data_in *)response->ip_bhs;
2453                         bhsdi->bhsdi_opcode = ISCSI_BHS_OPCODE_SCSI_DATA_IN;
2454                         bhsdi->bhsdi_initiator_task_tag =
2455                             bhssc->bhssc_initiator_task_tag;
2456                         bhsdi->bhsdi_datasn = htonl(PDU_EXPDATASN(request));
2457                         PDU_EXPDATASN(request)++;
2458                         bhsdi->bhsdi_buffer_offset = htonl(buffer_offset);
2459                 }
2460
2461                 KASSERT(i < ctl_sg_count, ("i >= ctl_sg_count"));
2462                 if (sg_len == 0) {
2463                         sg_addr = ctl_sglist[i].addr;
2464                         sg_len = ctl_sglist[i].len;
2465                         KASSERT(sg_len > 0, ("sg_len <= 0"));
2466                 }
2467
2468                 len = sg_len;
2469
2470                 /*
2471                  * Truncate to maximum data segment length.
2472                  */
2473                 KASSERT(response->ip_data_len < cs->cs_max_data_segment_length,
2474                     ("ip_data_len %zd >= max_data_segment_length %zd",
2475                     response->ip_data_len, cs->cs_max_data_segment_length));
2476                 if (response->ip_data_len + len >
2477                     cs->cs_max_data_segment_length) {
2478                         len = cs->cs_max_data_segment_length -
2479                             response->ip_data_len;
2480                         KASSERT(len <= sg_len, ("len %zd > sg_len %zd",
2481                             len, sg_len));
2482                 }
2483
2484                 /*
2485                  * Truncate to expected data transfer length.
2486                  */
2487                 KASSERT(buffer_offset + response->ip_data_len < expected_len,
2488                     ("buffer_offset %zd + ip_data_len %zd >= expected_len %zd",
2489                     buffer_offset, response->ip_data_len, expected_len));
2490                 if (buffer_offset + response->ip_data_len + len > expected_len) {
2491                         CFISCSI_SESSION_DEBUG(cs, "truncating from %zd "
2492                             "to expected data transfer length %zd",
2493                             buffer_offset + response->ip_data_len + len, expected_len);
2494                         len = expected_len - (buffer_offset + response->ip_data_len);
2495                         KASSERT(len <= sg_len, ("len %zd > sg_len %zd",
2496                             len, sg_len));
2497                 }
2498
2499                 error = icl_pdu_append_data(response, sg_addr, len, M_NOWAIT);
2500                 if (error != 0) {
2501                         CFISCSI_SESSION_WARN(cs, "failed to "
2502                             "allocate memory; dropping connection");
2503                         icl_pdu_free(response);
2504                         ctl_set_busy(&io->scsiio);
2505                         io->scsiio.be_move_done(io);
2506                         cfiscsi_session_terminate(cs);
2507                         return;
2508                 }
2509                 sg_addr += len;
2510                 sg_len -= len;
2511
2512                 KASSERT(buffer_offset + response->ip_data_len <= expected_len,
2513                     ("buffer_offset %zd + ip_data_len %zd > expected_len %zd",
2514                     buffer_offset, response->ip_data_len, expected_len));
2515                 if (buffer_offset + response->ip_data_len == expected_len) {
2516                         /*
2517                          * Already have the amount of data the initiator wanted.
2518                          */
2519                         break;
2520                 }
2521
2522                 if (sg_len == 0) {
2523                         /*
2524                          * End of scatter-gather segment;
2525                          * proceed to the next one...
2526                          */
2527                         if (i == ctl_sg_count - 1) {
2528                                 /*
2529                                  * ... unless this was the last one.
2530                                  */
2531                                 break;
2532                         }
2533                         i++;
2534                 }
2535
2536                 if (response->ip_data_len == cs->cs_max_data_segment_length) {
2537                         /*
2538                          * Can't stuff more data into the current PDU;
2539                          * queue it.  Note that's not enough to check
2540                          * for kern_data_resid == 0 instead; there
2541                          * may be several Data-In PDUs for the final
2542                          * call to cfiscsi_datamove(), and we want
2543                          * to set the F flag only on the last of them.
2544                          */
2545                         buffer_offset += response->ip_data_len;
2546                         if (buffer_offset == io->scsiio.kern_total_len ||
2547                             buffer_offset == expected_len)
2548                                 bhsdi->bhsdi_flags |= BHSDI_FLAGS_F;
2549                         cfiscsi_pdu_queue(response);
2550                         response = NULL;
2551                         bhsdi = NULL;
2552                 }
2553         }
2554         if (response != NULL) {
2555                 buffer_offset += response->ip_data_len;
2556                 if (buffer_offset == io->scsiio.kern_total_len ||
2557                     buffer_offset == expected_len)
2558                         bhsdi->bhsdi_flags |= BHSDI_FLAGS_F;
2559                 KASSERT(response->ip_data_len > 0, ("sending empty Data-In"));
2560                 cfiscsi_pdu_queue(response);
2561         }
2562
2563         io->scsiio.be_move_done(io);
2564 }
2565
2566 static void
2567 cfiscsi_datamove_out(union ctl_io *io)
2568 {
2569         struct cfiscsi_session *cs;
2570         struct icl_pdu *request, *response;
2571         const struct iscsi_bhs_scsi_command *bhssc;
2572         struct iscsi_bhs_r2t *bhsr2t;
2573         struct cfiscsi_data_wait *cdw;
2574         uint32_t target_transfer_tag;
2575         bool done;
2576
2577         request = io->io_hdr.ctl_private[CTL_PRIV_FRONTEND].ptr;
2578         cs = PDU_SESSION(request);
2579
2580         bhssc = (const struct iscsi_bhs_scsi_command *)request->ip_bhs;
2581         KASSERT((bhssc->bhssc_opcode & ~ISCSI_BHS_OPCODE_IMMEDIATE) ==
2582             ISCSI_BHS_OPCODE_SCSI_COMMAND,
2583             ("bhssc->bhssc_opcode != ISCSI_BHS_OPCODE_SCSI_COMMAND"));
2584
2585         /*
2586          * We need to record it so that we can properly report
2587          * underflow/underflow.
2588          */
2589         PDU_TOTAL_TRANSFER_LEN(request) = io->scsiio.kern_total_len;
2590
2591         /*
2592          * We hadn't received anything during this datamove yet.
2593          */
2594         io->scsiio.ext_data_filled = 0;
2595
2596         target_transfer_tag =
2597             atomic_fetchadd_32(&cs->cs_target_transfer_tag, 1);
2598
2599 #if 0
2600         CFISCSI_SESSION_DEBUG(cs, "expecting Data-Out with initiator "
2601             "task tag 0x%x, target transfer tag 0x%x",
2602             bhssc->bhssc_initiator_task_tag, target_transfer_tag);
2603 #endif
2604         cdw = uma_zalloc(cfiscsi_data_wait_zone, M_NOWAIT | M_ZERO);
2605         if (cdw == NULL) {
2606                 CFISCSI_SESSION_WARN(cs, "failed to "
2607                     "allocate memory; dropping connection");
2608                 ctl_set_busy(&io->scsiio);
2609                 io->scsiio.be_move_done(io);
2610                 cfiscsi_session_terminate(cs);
2611                 return;
2612         }
2613         cdw->cdw_ctl_io = io;
2614         cdw->cdw_target_transfer_tag = target_transfer_tag;
2615         cdw->cdw_initiator_task_tag = bhssc->bhssc_initiator_task_tag;
2616
2617         if (cs->cs_immediate_data && io->scsiio.kern_rel_offset <
2618             icl_pdu_data_segment_length(request)) {
2619                 done = cfiscsi_handle_data_segment(request, cdw);
2620                 if (done) {
2621                         uma_zfree(cfiscsi_data_wait_zone, cdw);
2622                         io->scsiio.be_move_done(io);
2623                         return;
2624                 }
2625         }
2626
2627         CFISCSI_SESSION_LOCK(cs);
2628         TAILQ_INSERT_TAIL(&cs->cs_waiting_for_data_out, cdw, cdw_next);
2629         CFISCSI_SESSION_UNLOCK(cs);
2630
2631         /*
2632          * XXX: We should limit the number of outstanding R2T PDUs
2633          *      per task to MaxOutstandingR2T.
2634          */
2635         response = cfiscsi_pdu_new_response(request, M_NOWAIT);
2636         if (response == NULL) {
2637                 CFISCSI_SESSION_WARN(cs, "failed to "
2638                     "allocate memory; dropping connection");
2639                 ctl_set_busy(&io->scsiio);
2640                 io->scsiio.be_move_done(io);
2641                 cfiscsi_session_terminate(cs);
2642                 return;
2643         }
2644         bhsr2t = (struct iscsi_bhs_r2t *)response->ip_bhs;
2645         bhsr2t->bhsr2t_opcode = ISCSI_BHS_OPCODE_R2T;
2646         bhsr2t->bhsr2t_flags = 0x80;
2647         bhsr2t->bhsr2t_lun = bhssc->bhssc_lun;
2648         bhsr2t->bhsr2t_initiator_task_tag = bhssc->bhssc_initiator_task_tag;
2649         bhsr2t->bhsr2t_target_transfer_tag = target_transfer_tag;
2650         /*
2651          * XXX: Here we assume that cfiscsi_datamove() won't ever
2652          *      be running concurrently on several CPUs for a given
2653          *      command.
2654          */
2655         bhsr2t->bhsr2t_r2tsn = htonl(PDU_R2TSN(request));
2656         PDU_R2TSN(request)++;
2657         /*
2658          * This is the offset within the current SCSI command;
2659          * i.e. for the first call of datamove(), it will be 0,
2660          * and for subsequent ones it will be the sum of lengths
2661          * of previous ones.
2662          *
2663          * The ext_data_filled is to account for unsolicited
2664          * (immediate) data that might have already arrived.
2665          */
2666         bhsr2t->bhsr2t_buffer_offset =
2667             htonl(io->scsiio.kern_rel_offset + io->scsiio.ext_data_filled);
2668         /*
2669          * This is the total length (sum of S/G lengths) this call
2670          * to cfiscsi_datamove() is supposed to handle.
2671          *
2672          * XXX: Limit it to MaxBurstLength.
2673          */
2674         bhsr2t->bhsr2t_desired_data_transfer_length =
2675             htonl(io->scsiio.kern_data_len - io->scsiio.ext_data_filled);
2676         cfiscsi_pdu_queue(response);
2677 }
2678
2679 static void
2680 cfiscsi_datamove(union ctl_io *io)
2681 {
2682
2683         if ((io->io_hdr.flags & CTL_FLAG_DATA_MASK) == CTL_FLAG_DATA_IN)
2684                 cfiscsi_datamove_in(io);
2685         else
2686                 cfiscsi_datamove_out(io);
2687 }
2688
2689 static void
2690 cfiscsi_scsi_command_done(union ctl_io *io)
2691 {
2692         struct icl_pdu *request, *response;
2693         struct iscsi_bhs_scsi_command *bhssc;
2694         struct iscsi_bhs_scsi_response *bhssr;
2695 #ifdef DIAGNOSTIC
2696         struct cfiscsi_data_wait *cdw;
2697 #endif
2698         struct cfiscsi_session *cs;
2699         uint16_t sense_length;
2700
2701         request = io->io_hdr.ctl_private[CTL_PRIV_FRONTEND].ptr;
2702         cs = PDU_SESSION(request);
2703         bhssc = (struct iscsi_bhs_scsi_command *)request->ip_bhs;
2704         KASSERT((bhssc->bhssc_opcode & ~ISCSI_BHS_OPCODE_IMMEDIATE) ==
2705             ISCSI_BHS_OPCODE_SCSI_COMMAND,
2706             ("replying to wrong opcode 0x%x", bhssc->bhssc_opcode));
2707
2708         //CFISCSI_SESSION_DEBUG(cs, "initiator task tag 0x%x",
2709         //    bhssc->bhssc_initiator_task_tag);
2710
2711 #ifdef DIAGNOSTIC
2712         CFISCSI_SESSION_LOCK(cs);
2713         TAILQ_FOREACH(cdw, &cs->cs_waiting_for_data_out, cdw_next)
2714                 KASSERT(bhssc->bhssc_initiator_task_tag !=
2715                     cdw->cdw_initiator_task_tag, ("dangling cdw"));
2716         CFISCSI_SESSION_UNLOCK(cs);
2717 #endif
2718
2719         /*
2720          * Do not return status for aborted commands.
2721          * There are exceptions, but none supported by CTL yet.
2722          */
2723         if ((io->io_hdr.flags & CTL_FLAG_ABORT) &&
2724             (io->io_hdr.flags & CTL_FLAG_ABORT_STATUS) == 0) {
2725                 ctl_free_io(io);
2726                 icl_pdu_free(request);
2727                 return;
2728         }
2729
2730         response = cfiscsi_pdu_new_response(request, M_WAITOK);
2731         bhssr = (struct iscsi_bhs_scsi_response *)response->ip_bhs;
2732         bhssr->bhssr_opcode = ISCSI_BHS_OPCODE_SCSI_RESPONSE;
2733         bhssr->bhssr_flags = 0x80;
2734         /*
2735          * XXX: We don't deal with bidirectional under/overflows;
2736          *      does anything actually support those?
2737          */
2738         if (PDU_TOTAL_TRANSFER_LEN(request) <
2739             ntohl(bhssc->bhssc_expected_data_transfer_length)) {
2740                 bhssr->bhssr_flags |= BHSSR_FLAGS_RESIDUAL_UNDERFLOW;
2741                 bhssr->bhssr_residual_count =
2742                     htonl(ntohl(bhssc->bhssc_expected_data_transfer_length) -
2743                     PDU_TOTAL_TRANSFER_LEN(request));
2744                 //CFISCSI_SESSION_DEBUG(cs, "underflow; residual count %d",
2745                 //    ntohl(bhssr->bhssr_residual_count));
2746         } else if (PDU_TOTAL_TRANSFER_LEN(request) > 
2747             ntohl(bhssc->bhssc_expected_data_transfer_length)) {
2748                 bhssr->bhssr_flags |= BHSSR_FLAGS_RESIDUAL_OVERFLOW;
2749                 bhssr->bhssr_residual_count =
2750                     htonl(PDU_TOTAL_TRANSFER_LEN(request) -
2751                     ntohl(bhssc->bhssc_expected_data_transfer_length));
2752                 //CFISCSI_SESSION_DEBUG(cs, "overflow; residual count %d",
2753                 //    ntohl(bhssr->bhssr_residual_count));
2754         }
2755         bhssr->bhssr_response = BHSSR_RESPONSE_COMMAND_COMPLETED;
2756         bhssr->bhssr_status = io->scsiio.scsi_status;
2757         bhssr->bhssr_initiator_task_tag = bhssc->bhssc_initiator_task_tag;
2758         bhssr->bhssr_expdatasn = htonl(PDU_EXPDATASN(request));
2759
2760         if (io->scsiio.sense_len > 0) {
2761 #if 0
2762                 CFISCSI_SESSION_DEBUG(cs, "returning %d bytes of sense data",
2763                     io->scsiio.sense_len);
2764 #endif
2765                 sense_length = htons(io->scsiio.sense_len);
2766                 icl_pdu_append_data(response,
2767                     &sense_length, sizeof(sense_length), M_WAITOK);
2768                 icl_pdu_append_data(response,
2769                     &io->scsiio.sense_data, io->scsiio.sense_len, M_WAITOK);
2770         }
2771
2772         ctl_free_io(io);
2773         icl_pdu_free(request);
2774         cfiscsi_pdu_queue(response);
2775 }
2776
2777 static void
2778 cfiscsi_task_management_done(union ctl_io *io)
2779 {
2780         struct icl_pdu *request, *response;
2781         struct iscsi_bhs_task_management_request *bhstmr;
2782         struct iscsi_bhs_task_management_response *bhstmr2;
2783         struct cfiscsi_data_wait *cdw, *tmpcdw;
2784         struct cfiscsi_session *cs;
2785
2786         request = io->io_hdr.ctl_private[CTL_PRIV_FRONTEND].ptr;
2787         cs = PDU_SESSION(request);
2788         bhstmr = (struct iscsi_bhs_task_management_request *)request->ip_bhs;
2789         KASSERT((bhstmr->bhstmr_opcode & ~ISCSI_BHS_OPCODE_IMMEDIATE) ==
2790             ISCSI_BHS_OPCODE_TASK_REQUEST,
2791             ("replying to wrong opcode 0x%x", bhstmr->bhstmr_opcode));
2792
2793 #if 0
2794         CFISCSI_SESSION_DEBUG(cs, "initiator task tag 0x%x; referenced task tag 0x%x",
2795             bhstmr->bhstmr_initiator_task_tag,
2796             bhstmr->bhstmr_referenced_task_tag);
2797 #endif
2798
2799         if ((bhstmr->bhstmr_function & ~0x80) ==
2800             BHSTMR_FUNCTION_ABORT_TASK) {
2801                 /*
2802                  * Make sure we no longer wait for Data-Out for this command.
2803                  */
2804                 CFISCSI_SESSION_LOCK(cs);
2805                 TAILQ_FOREACH_SAFE(cdw,
2806                     &cs->cs_waiting_for_data_out, cdw_next, tmpcdw) {
2807                         if (bhstmr->bhstmr_referenced_task_tag !=
2808                             cdw->cdw_initiator_task_tag)
2809                                 continue;
2810
2811 #if 0
2812                         CFISCSI_SESSION_DEBUG(cs, "removing csw for initiator task "
2813                             "tag 0x%x", bhstmr->bhstmr_initiator_task_tag);
2814 #endif
2815                         TAILQ_REMOVE(&cs->cs_waiting_for_data_out,
2816                             cdw, cdw_next);
2817                         cdw->cdw_ctl_io->scsiio.be_move_done(cdw->cdw_ctl_io);
2818                         uma_zfree(cfiscsi_data_wait_zone, cdw);
2819                 }
2820                 CFISCSI_SESSION_UNLOCK(cs);
2821         }
2822
2823         response = cfiscsi_pdu_new_response(request, M_WAITOK);
2824         bhstmr2 = (struct iscsi_bhs_task_management_response *)
2825             response->ip_bhs;
2826         bhstmr2->bhstmr_opcode = ISCSI_BHS_OPCODE_TASK_RESPONSE;
2827         bhstmr2->bhstmr_flags = 0x80;
2828         if (io->io_hdr.status == CTL_SUCCESS) {
2829                 bhstmr2->bhstmr_response = BHSTMR_RESPONSE_FUNCTION_COMPLETE;
2830         } else {
2831                 /*
2832                  * XXX: How to figure out what exactly went wrong?  iSCSI spec
2833                  *      expects us to provide detailed error, e.g. "Task does
2834                  *      not exist" or "LUN does not exist".
2835                  */
2836                 CFISCSI_SESSION_DEBUG(cs, "BHSTMR_RESPONSE_FUNCTION_NOT_SUPPORTED");
2837                 bhstmr2->bhstmr_response =
2838                     BHSTMR_RESPONSE_FUNCTION_NOT_SUPPORTED;
2839         }
2840         bhstmr2->bhstmr_initiator_task_tag = bhstmr->bhstmr_initiator_task_tag;
2841
2842         ctl_free_io(io);
2843         icl_pdu_free(request);
2844         cfiscsi_pdu_queue(response);
2845 }
2846
2847 static void
2848 cfiscsi_done(union ctl_io *io)
2849 {
2850         struct icl_pdu *request;
2851         struct cfiscsi_session *cs;
2852
2853         KASSERT(((io->io_hdr.status & CTL_STATUS_MASK) != CTL_STATUS_NONE),
2854                 ("invalid CTL status %#x", io->io_hdr.status));
2855
2856         if (io->io_hdr.io_type == CTL_IO_TASK &&
2857             io->taskio.task_action == CTL_TASK_I_T_NEXUS_RESET) {
2858                 /*
2859                  * Implicit task termination has just completed; nothing to do.
2860                  */
2861                 cs = io->io_hdr.ctl_private[CTL_PRIV_FRONTEND].ptr;
2862                 cs->cs_tasks_aborted = true;
2863                 refcount_release(&cs->cs_outstanding_ctl_pdus);
2864                 wakeup(__DEVOLATILE(void *, &cs->cs_outstanding_ctl_pdus));
2865                 ctl_free_io(io);
2866                 return;
2867         }
2868
2869         request = io->io_hdr.ctl_private[CTL_PRIV_FRONTEND].ptr;
2870         cs = PDU_SESSION(request);
2871         refcount_release(&cs->cs_outstanding_ctl_pdus);
2872
2873         switch (request->ip_bhs->bhs_opcode & ~ISCSI_BHS_OPCODE_IMMEDIATE) {
2874         case ISCSI_BHS_OPCODE_SCSI_COMMAND:
2875                 cfiscsi_scsi_command_done(io);
2876                 break;
2877         case ISCSI_BHS_OPCODE_TASK_REQUEST:
2878                 cfiscsi_task_management_done(io);
2879                 break;
2880         default:
2881                 panic("cfiscsi_done called with wrong opcode 0x%x",
2882                     request->ip_bhs->bhs_opcode);
2883         }
2884 }