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