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