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