xref: /freebsd/sys/cam/ctl/ctl_frontend_iscsi.c (revision 63d1fd5970ec814904aa0f4580b10a0d302d08b2)
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_recv_data_segment_length = cihp->max_recv_data_segment_length;
1516 	cs->cs_max_send_data_segment_length = cihp->max_send_data_segment_length;
1517 	cs->cs_max_burst_length = cihp->max_burst_length;
1518 	cs->cs_first_burst_length = cihp->first_burst_length;
1519 	cs->cs_immediate_data = !!cihp->immediate_data;
1520 	if (cihp->header_digest == CTL_ISCSI_DIGEST_CRC32C)
1521 		cs->cs_conn->ic_header_crc32c = true;
1522 	if (cihp->data_digest == CTL_ISCSI_DIGEST_CRC32C)
1523 		cs->cs_conn->ic_data_crc32c = true;
1524 
1525 	strlcpy(cs->cs_initiator_name,
1526 	    cihp->initiator_name, sizeof(cs->cs_initiator_name));
1527 	strlcpy(cs->cs_initiator_addr,
1528 	    cihp->initiator_addr, sizeof(cs->cs_initiator_addr));
1529 	strlcpy(cs->cs_initiator_alias,
1530 	    cihp->initiator_alias, sizeof(cs->cs_initiator_alias));
1531 	memcpy(cs->cs_initiator_isid,
1532 	    cihp->initiator_isid, sizeof(cs->cs_initiator_isid));
1533 	snprintf(cs->cs_initiator_id, sizeof(cs->cs_initiator_id),
1534 	    "%s,i,0x%02x%02x%02x%02x%02x%02x", cs->cs_initiator_name,
1535 	    cihp->initiator_isid[0], cihp->initiator_isid[1],
1536 	    cihp->initiator_isid[2], cihp->initiator_isid[3],
1537 	    cihp->initiator_isid[4], cihp->initiator_isid[5]);
1538 
1539 	mtx_lock(&softc->lock);
1540 	if (ct->ct_online == 0) {
1541 		mtx_unlock(&softc->lock);
1542 		cfiscsi_session_terminate(cs);
1543 		cfiscsi_target_release(ct);
1544 		ci->status = CTL_ISCSI_ERROR;
1545 		snprintf(ci->error_str, sizeof(ci->error_str),
1546 		    "%s: port offline", __func__);
1547 		return;
1548 	}
1549 	cs->cs_target = ct;
1550 	mtx_unlock(&softc->lock);
1551 
1552 	refcount_acquire(&cs->cs_outstanding_ctl_pdus);
1553 restart:
1554 	if (!cs->cs_terminating) {
1555 		mtx_lock(&softc->lock);
1556 		TAILQ_FOREACH(cs2, &softc->sessions, cs_next) {
1557 			if (cs2 != cs && cs2->cs_tasks_aborted == false &&
1558 			    cs->cs_target == cs2->cs_target &&
1559 			    strcmp(cs->cs_initiator_id, cs2->cs_initiator_id) == 0) {
1560 				if (strcmp(cs->cs_initiator_addr,
1561 				    cs2->cs_initiator_addr) != 0) {
1562 					CFISCSI_SESSION_WARN(cs2,
1563 					    "session reinstatement from "
1564 					    "different address %s",
1565 					    cs->cs_initiator_addr);
1566 				} else {
1567 					CFISCSI_SESSION_DEBUG(cs2,
1568 					    "session reinstatement");
1569 				}
1570 				cfiscsi_session_terminate(cs2);
1571 				mtx_unlock(&softc->lock);
1572 				pause("cfiscsi_reinstate", 1);
1573 				goto restart;
1574 			}
1575 		}
1576 		mtx_unlock(&softc->lock);
1577 	}
1578 
1579 	/*
1580 	 * Register initiator with CTL.
1581 	 */
1582 	cfiscsi_session_register_initiator(cs);
1583 
1584 #ifdef ICL_KERNEL_PROXY
1585 	if (cihp->socket > 0) {
1586 #endif
1587 		error = icl_conn_handoff(cs->cs_conn, cihp->socket);
1588 		if (error != 0) {
1589 			cfiscsi_session_terminate(cs);
1590 			refcount_release(&cs->cs_outstanding_ctl_pdus);
1591 			ci->status = CTL_ISCSI_ERROR;
1592 			snprintf(ci->error_str, sizeof(ci->error_str),
1593 			    "%s: icl_conn_handoff failed with error %d",
1594 			    __func__, error);
1595 			return;
1596 		}
1597 #ifdef ICL_KERNEL_PROXY
1598 	}
1599 #endif
1600 
1601 #ifdef ICL_KERNEL_PROXY
1602 	cs->cs_login_phase = false;
1603 
1604 	/*
1605 	 * First PDU of the Full Feature phase has likely already arrived.
1606 	 * We have to pick it up and execute properly.
1607 	 */
1608 	if (cs->cs_login_pdu != NULL) {
1609 		CFISCSI_SESSION_DEBUG(cs, "picking up first PDU");
1610 		cfiscsi_pdu_handle(cs->cs_login_pdu);
1611 		cs->cs_login_pdu = NULL;
1612 	}
1613 #endif
1614 
1615 	refcount_release(&cs->cs_outstanding_ctl_pdus);
1616 	ci->status = CTL_ISCSI_OK;
1617 }
1618 
1619 static void
1620 cfiscsi_ioctl_list(struct ctl_iscsi *ci)
1621 {
1622 	struct ctl_iscsi_list_params *cilp;
1623 	struct cfiscsi_session *cs;
1624 	struct cfiscsi_softc *softc;
1625 	struct sbuf *sb;
1626 	int error;
1627 
1628 	cilp = (struct ctl_iscsi_list_params *)&(ci->data);
1629 	softc = &cfiscsi_softc;
1630 
1631 	sb = sbuf_new(NULL, NULL, cilp->alloc_len, SBUF_FIXEDLEN);
1632 	if (sb == NULL) {
1633 		ci->status = CTL_ISCSI_ERROR;
1634 		snprintf(ci->error_str, sizeof(ci->error_str),
1635 		    "Unable to allocate %d bytes for iSCSI session list",
1636 		    cilp->alloc_len);
1637 		return;
1638 	}
1639 
1640 	sbuf_printf(sb, "<ctlislist>\n");
1641 	mtx_lock(&softc->lock);
1642 	TAILQ_FOREACH(cs, &softc->sessions, cs_next) {
1643 #ifdef ICL_KERNEL_PROXY
1644 		if (cs->cs_target == NULL)
1645 			continue;
1646 #endif
1647 		error = sbuf_printf(sb, "<connection id=\"%d\">"
1648 		    "<initiator>%s</initiator>"
1649 		    "<initiator_addr>%s</initiator_addr>"
1650 		    "<initiator_alias>%s</initiator_alias>"
1651 		    "<target>%s</target>"
1652 		    "<target_alias>%s</target_alias>"
1653 		    "<target_portal_group_tag>%u</target_portal_group_tag>"
1654 		    "<header_digest>%s</header_digest>"
1655 		    "<data_digest>%s</data_digest>"
1656 		    "<max_recv_data_segment_length>%d</max_recv_data_segment_length>"
1657 		    "<max_send_data_segment_length>%d</max_send_data_segment_length>"
1658 		    "<max_burst_length>%d</max_burst_length>"
1659 		    "<first_burst_length>%d</first_burst_length>"
1660 		    "<immediate_data>%d</immediate_data>"
1661 		    "<iser>%d</iser>"
1662 		    "<offload>%s</offload>"
1663 		    "</connection>\n",
1664 		    cs->cs_id,
1665 		    cs->cs_initiator_name, cs->cs_initiator_addr, cs->cs_initiator_alias,
1666 		    cs->cs_target->ct_name, cs->cs_target->ct_alias,
1667 		    cs->cs_target->ct_tag,
1668 		    cs->cs_conn->ic_header_crc32c ? "CRC32C" : "None",
1669 		    cs->cs_conn->ic_data_crc32c ? "CRC32C" : "None",
1670 		    cs->cs_max_recv_data_segment_length,
1671 		    cs->cs_max_send_data_segment_length,
1672 		    cs->cs_max_burst_length,
1673 		    cs->cs_first_burst_length,
1674 		    cs->cs_immediate_data,
1675 		    cs->cs_conn->ic_iser,
1676 		    cs->cs_conn->ic_offload);
1677 		if (error != 0)
1678 			break;
1679 	}
1680 	mtx_unlock(&softc->lock);
1681 	error = sbuf_printf(sb, "</ctlislist>\n");
1682 	if (error != 0) {
1683 		sbuf_delete(sb);
1684 		ci->status = CTL_ISCSI_LIST_NEED_MORE_SPACE;
1685 		snprintf(ci->error_str, sizeof(ci->error_str),
1686 		    "Out of space, %d bytes is too small", cilp->alloc_len);
1687 		return;
1688 	}
1689 	sbuf_finish(sb);
1690 
1691 	error = copyout(sbuf_data(sb), cilp->conn_xml, sbuf_len(sb) + 1);
1692 	cilp->fill_len = sbuf_len(sb) + 1;
1693 	ci->status = CTL_ISCSI_OK;
1694 	sbuf_delete(sb);
1695 }
1696 
1697 static void
1698 cfiscsi_ioctl_logout(struct ctl_iscsi *ci)
1699 {
1700 	struct icl_pdu *response;
1701 	struct iscsi_bhs_asynchronous_message *bhsam;
1702 	struct ctl_iscsi_logout_params *cilp;
1703 	struct cfiscsi_session *cs;
1704 	struct cfiscsi_softc *softc;
1705 	int found = 0;
1706 
1707 	cilp = (struct ctl_iscsi_logout_params *)&(ci->data);
1708 	softc = &cfiscsi_softc;
1709 
1710 	mtx_lock(&softc->lock);
1711 	TAILQ_FOREACH(cs, &softc->sessions, cs_next) {
1712 		if (cilp->all == 0 && cs->cs_id != cilp->connection_id &&
1713 		    strcmp(cs->cs_initiator_name, cilp->initiator_name) != 0 &&
1714 		    strcmp(cs->cs_initiator_addr, cilp->initiator_addr) != 0)
1715 			continue;
1716 
1717 		response = icl_pdu_new(cs->cs_conn, M_NOWAIT);
1718 		if (response == NULL) {
1719 			ci->status = CTL_ISCSI_ERROR;
1720 			snprintf(ci->error_str, sizeof(ci->error_str),
1721 			    "Unable to allocate memory");
1722 			mtx_unlock(&softc->lock);
1723 			return;
1724 		}
1725 		bhsam =
1726 		    (struct iscsi_bhs_asynchronous_message *)response->ip_bhs;
1727 		bhsam->bhsam_opcode = ISCSI_BHS_OPCODE_ASYNC_MESSAGE;
1728 		bhsam->bhsam_flags = 0x80;
1729 		bhsam->bhsam_async_event = BHSAM_EVENT_TARGET_REQUESTS_LOGOUT;
1730 		bhsam->bhsam_parameter3 = htons(10);
1731 		cfiscsi_pdu_queue(response);
1732 		found++;
1733 	}
1734 	mtx_unlock(&softc->lock);
1735 
1736 	if (found == 0) {
1737 		ci->status = CTL_ISCSI_SESSION_NOT_FOUND;
1738 		snprintf(ci->error_str, sizeof(ci->error_str),
1739 		    "No matching connections found");
1740 		return;
1741 	}
1742 
1743 	ci->status = CTL_ISCSI_OK;
1744 }
1745 
1746 static void
1747 cfiscsi_ioctl_terminate(struct ctl_iscsi *ci)
1748 {
1749 	struct icl_pdu *response;
1750 	struct iscsi_bhs_asynchronous_message *bhsam;
1751 	struct ctl_iscsi_terminate_params *citp;
1752 	struct cfiscsi_session *cs;
1753 	struct cfiscsi_softc *softc;
1754 	int found = 0;
1755 
1756 	citp = (struct ctl_iscsi_terminate_params *)&(ci->data);
1757 	softc = &cfiscsi_softc;
1758 
1759 	mtx_lock(&softc->lock);
1760 	TAILQ_FOREACH(cs, &softc->sessions, cs_next) {
1761 		if (citp->all == 0 && cs->cs_id != citp->connection_id &&
1762 		    strcmp(cs->cs_initiator_name, citp->initiator_name) != 0 &&
1763 		    strcmp(cs->cs_initiator_addr, citp->initiator_addr) != 0)
1764 			continue;
1765 
1766 		response = icl_pdu_new(cs->cs_conn, M_NOWAIT);
1767 		if (response == NULL) {
1768 			/*
1769 			 * Oh well.  Just terminate the connection.
1770 			 */
1771 		} else {
1772 			bhsam = (struct iscsi_bhs_asynchronous_message *)
1773 			    response->ip_bhs;
1774 			bhsam->bhsam_opcode = ISCSI_BHS_OPCODE_ASYNC_MESSAGE;
1775 			bhsam->bhsam_flags = 0x80;
1776 			bhsam->bhsam_0xffffffff = 0xffffffff;
1777 			bhsam->bhsam_async_event =
1778 			    BHSAM_EVENT_TARGET_TERMINATES_SESSION;
1779 			cfiscsi_pdu_queue(response);
1780 		}
1781 		cfiscsi_session_terminate(cs);
1782 		found++;
1783 	}
1784 	mtx_unlock(&softc->lock);
1785 
1786 	if (found == 0) {
1787 		ci->status = CTL_ISCSI_SESSION_NOT_FOUND;
1788 		snprintf(ci->error_str, sizeof(ci->error_str),
1789 		    "No matching connections found");
1790 		return;
1791 	}
1792 
1793 	ci->status = CTL_ISCSI_OK;
1794 }
1795 
1796 static void
1797 cfiscsi_ioctl_limits(struct ctl_iscsi *ci)
1798 {
1799 	struct ctl_iscsi_limits_params *cilp;
1800 	struct icl_drv_limits idl;
1801 	int error;
1802 
1803 	cilp = (struct ctl_iscsi_limits_params *)&(ci->data);
1804 
1805 	error = icl_limits(cilp->offload, false, &idl);
1806 	if (error != 0) {
1807 		ci->status = CTL_ISCSI_ERROR;
1808 		snprintf(ci->error_str, sizeof(ci->error_str),
1809 			"%s: icl_limits failed with error %d",
1810 			__func__, error);
1811 		return;
1812 	}
1813 
1814 	cilp->max_recv_data_segment_length =
1815 	    idl.idl_max_recv_data_segment_length;
1816 	cilp->max_send_data_segment_length =
1817 	    idl.idl_max_send_data_segment_length;
1818 	cilp->max_burst_length = idl.idl_max_burst_length;
1819 	cilp->first_burst_length = idl.idl_first_burst_length;
1820 
1821 	ci->status = CTL_ISCSI_OK;
1822 }
1823 
1824 #ifdef ICL_KERNEL_PROXY
1825 static void
1826 cfiscsi_ioctl_listen(struct ctl_iscsi *ci)
1827 {
1828 	struct ctl_iscsi_listen_params *cilp;
1829 	struct sockaddr *sa;
1830 	int error;
1831 
1832 	cilp = (struct ctl_iscsi_listen_params *)&(ci->data);
1833 
1834 	if (cfiscsi_softc.listener == NULL) {
1835 		CFISCSI_DEBUG("no listener");
1836 		snprintf(ci->error_str, sizeof(ci->error_str), "no listener");
1837 		ci->status = CTL_ISCSI_ERROR;
1838 		return;
1839 	}
1840 
1841 	error = getsockaddr(&sa, (void *)cilp->addr, cilp->addrlen);
1842 	if (error != 0) {
1843 		CFISCSI_DEBUG("getsockaddr, error %d", error);
1844 		snprintf(ci->error_str, sizeof(ci->error_str), "getsockaddr failed");
1845 		ci->status = CTL_ISCSI_ERROR;
1846 		return;
1847 	}
1848 
1849 	error = icl_listen_add(cfiscsi_softc.listener, cilp->iser, cilp->domain,
1850 	    cilp->socktype, cilp->protocol, sa, cilp->portal_id);
1851 	if (error != 0) {
1852 		free(sa, M_SONAME);
1853 		CFISCSI_DEBUG("icl_listen_add, error %d", error);
1854 		snprintf(ci->error_str, sizeof(ci->error_str),
1855 		    "icl_listen_add failed, error %d", error);
1856 		ci->status = CTL_ISCSI_ERROR;
1857 		return;
1858 	}
1859 
1860 	ci->status = CTL_ISCSI_OK;
1861 }
1862 
1863 static void
1864 cfiscsi_ioctl_accept(struct ctl_iscsi *ci)
1865 {
1866 	struct ctl_iscsi_accept_params *ciap;
1867 	struct cfiscsi_session *cs;
1868 	int error;
1869 
1870 	ciap = (struct ctl_iscsi_accept_params *)&(ci->data);
1871 
1872 	mtx_lock(&cfiscsi_softc.lock);
1873 	for (;;) {
1874 		TAILQ_FOREACH(cs, &cfiscsi_softc.sessions, cs_next) {
1875 			if (cs->cs_waiting_for_ctld)
1876 				break;
1877 		}
1878 		if (cs != NULL)
1879 			break;
1880 		error = cv_wait_sig(&cfiscsi_softc.accept_cv, &cfiscsi_softc.lock);
1881 		if (error != 0) {
1882 			mtx_unlock(&cfiscsi_softc.lock);
1883 			snprintf(ci->error_str, sizeof(ci->error_str), "interrupted");
1884 			ci->status = CTL_ISCSI_ERROR;
1885 			return;
1886 		}
1887 	}
1888 	mtx_unlock(&cfiscsi_softc.lock);
1889 
1890 	cs->cs_waiting_for_ctld = false;
1891 	cs->cs_login_phase = true;
1892 
1893 	ciap->connection_id = cs->cs_id;
1894 	ciap->portal_id = cs->cs_portal_id;
1895 	ciap->initiator_addrlen = cs->cs_initiator_sa->sa_len;
1896 	error = copyout(cs->cs_initiator_sa, ciap->initiator_addr,
1897 	    cs->cs_initiator_sa->sa_len);
1898 	if (error != 0) {
1899 		snprintf(ci->error_str, sizeof(ci->error_str),
1900 		    "copyout failed with error %d", error);
1901 		ci->status = CTL_ISCSI_ERROR;
1902 		return;
1903 	}
1904 
1905 	ci->status = CTL_ISCSI_OK;
1906 }
1907 
1908 static void
1909 cfiscsi_ioctl_send(struct ctl_iscsi *ci)
1910 {
1911 	struct ctl_iscsi_send_params *cisp;
1912 	struct cfiscsi_session *cs;
1913 	struct icl_pdu *ip;
1914 	size_t datalen;
1915 	void *data;
1916 	int error;
1917 
1918 	cisp = (struct ctl_iscsi_send_params *)&(ci->data);
1919 
1920 	mtx_lock(&cfiscsi_softc.lock);
1921 	TAILQ_FOREACH(cs, &cfiscsi_softc.sessions, cs_next) {
1922 		if (cs->cs_id == cisp->connection_id)
1923 			break;
1924 	}
1925 	if (cs == NULL) {
1926 		mtx_unlock(&cfiscsi_softc.lock);
1927 		snprintf(ci->error_str, sizeof(ci->error_str), "connection not found");
1928 		ci->status = CTL_ISCSI_ERROR;
1929 		return;
1930 	}
1931 	mtx_unlock(&cfiscsi_softc.lock);
1932 
1933 #if 0
1934 	if (cs->cs_login_phase == false)
1935 		return (EBUSY);
1936 #endif
1937 
1938 	if (cs->cs_terminating) {
1939 		snprintf(ci->error_str, sizeof(ci->error_str), "connection is terminating");
1940 		ci->status = CTL_ISCSI_ERROR;
1941 		return;
1942 	}
1943 
1944 	datalen = cisp->data_segment_len;
1945 	/*
1946 	 * XXX
1947 	 */
1948 	//if (datalen > CFISCSI_MAX_DATA_SEGMENT_LENGTH) {
1949 	if (datalen > 65535) {
1950 		snprintf(ci->error_str, sizeof(ci->error_str), "data segment too big");
1951 		ci->status = CTL_ISCSI_ERROR;
1952 		return;
1953 	}
1954 	if (datalen > 0) {
1955 		data = malloc(datalen, M_CFISCSI, M_WAITOK);
1956 		error = copyin(cisp->data_segment, data, datalen);
1957 		if (error != 0) {
1958 			free(data, M_CFISCSI);
1959 			snprintf(ci->error_str, sizeof(ci->error_str), "copyin error %d", error);
1960 			ci->status = CTL_ISCSI_ERROR;
1961 			return;
1962 		}
1963 	}
1964 
1965 	ip = icl_pdu_new(cs->cs_conn, M_WAITOK);
1966 	memcpy(ip->ip_bhs, cisp->bhs, sizeof(*ip->ip_bhs));
1967 	if (datalen > 0) {
1968 		icl_pdu_append_data(ip, data, datalen, M_WAITOK);
1969 		free(data, M_CFISCSI);
1970 	}
1971 	CFISCSI_SESSION_LOCK(cs);
1972 	icl_pdu_queue(ip);
1973 	CFISCSI_SESSION_UNLOCK(cs);
1974 	ci->status = CTL_ISCSI_OK;
1975 }
1976 
1977 static void
1978 cfiscsi_ioctl_receive(struct ctl_iscsi *ci)
1979 {
1980 	struct ctl_iscsi_receive_params *cirp;
1981 	struct cfiscsi_session *cs;
1982 	struct icl_pdu *ip;
1983 	void *data;
1984 	int error;
1985 
1986 	cirp = (struct ctl_iscsi_receive_params *)&(ci->data);
1987 
1988 	mtx_lock(&cfiscsi_softc.lock);
1989 	TAILQ_FOREACH(cs, &cfiscsi_softc.sessions, cs_next) {
1990 		if (cs->cs_id == cirp->connection_id)
1991 			break;
1992 	}
1993 	if (cs == NULL) {
1994 		mtx_unlock(&cfiscsi_softc.lock);
1995 		snprintf(ci->error_str, sizeof(ci->error_str),
1996 		    "connection not found");
1997 		ci->status = CTL_ISCSI_ERROR;
1998 		return;
1999 	}
2000 	mtx_unlock(&cfiscsi_softc.lock);
2001 
2002 #if 0
2003 	if (is->is_login_phase == false)
2004 		return (EBUSY);
2005 #endif
2006 
2007 	CFISCSI_SESSION_LOCK(cs);
2008 	while (cs->cs_login_pdu == NULL && cs->cs_terminating == false) {
2009 		error = cv_wait_sig(&cs->cs_login_cv, &cs->cs_lock);
2010 		if (error != 0) {
2011 			CFISCSI_SESSION_UNLOCK(cs);
2012 			snprintf(ci->error_str, sizeof(ci->error_str),
2013 			    "interrupted by signal");
2014 			ci->status = CTL_ISCSI_ERROR;
2015 			return;
2016 		}
2017 	}
2018 
2019 	if (cs->cs_terminating) {
2020 		CFISCSI_SESSION_UNLOCK(cs);
2021 		snprintf(ci->error_str, sizeof(ci->error_str),
2022 		    "connection terminating");
2023 		ci->status = CTL_ISCSI_ERROR;
2024 		return;
2025 	}
2026 	ip = cs->cs_login_pdu;
2027 	cs->cs_login_pdu = NULL;
2028 	CFISCSI_SESSION_UNLOCK(cs);
2029 
2030 	if (ip->ip_data_len > cirp->data_segment_len) {
2031 		icl_pdu_free(ip);
2032 		snprintf(ci->error_str, sizeof(ci->error_str),
2033 		    "data segment too big");
2034 		ci->status = CTL_ISCSI_ERROR;
2035 		return;
2036 	}
2037 
2038 	copyout(ip->ip_bhs, cirp->bhs, sizeof(*ip->ip_bhs));
2039 	if (ip->ip_data_len > 0) {
2040 		data = malloc(ip->ip_data_len, M_CFISCSI, M_WAITOK);
2041 		icl_pdu_get_data(ip, 0, data, ip->ip_data_len);
2042 		copyout(data, cirp->data_segment, ip->ip_data_len);
2043 		free(data, M_CFISCSI);
2044 	}
2045 
2046 	icl_pdu_free(ip);
2047 	ci->status = CTL_ISCSI_OK;
2048 }
2049 
2050 #endif /* !ICL_KERNEL_PROXY */
2051 
2052 static void
2053 cfiscsi_ioctl_port_create(struct ctl_req *req)
2054 {
2055 	struct cfiscsi_target *ct;
2056 	struct ctl_port *port;
2057 	const char *target, *alias, *tags;
2058 	struct scsi_vpd_id_descriptor *desc;
2059 	ctl_options_t opts;
2060 	int retval, len, idlen;
2061 	uint16_t tag;
2062 
2063 	ctl_init_opts(&opts, req->num_args, req->kern_args);
2064 	target = ctl_get_opt(&opts, "cfiscsi_target");
2065 	alias = ctl_get_opt(&opts, "cfiscsi_target_alias");
2066 	tags = ctl_get_opt(&opts, "cfiscsi_portal_group_tag");
2067 	if (target == NULL || tags == NULL) {
2068 		req->status = CTL_LUN_ERROR;
2069 		snprintf(req->error_str, sizeof(req->error_str),
2070 		    "Missing required argument");
2071 		ctl_free_opts(&opts);
2072 		return;
2073 	}
2074 	tag = strtol(tags, (char **)NULL, 10);
2075 	ct = cfiscsi_target_find_or_create(&cfiscsi_softc, target, alias, tag);
2076 	if (ct == NULL) {
2077 		req->status = CTL_LUN_ERROR;
2078 		snprintf(req->error_str, sizeof(req->error_str),
2079 		    "failed to create target \"%s\"", target);
2080 		ctl_free_opts(&opts);
2081 		return;
2082 	}
2083 	if (ct->ct_state == CFISCSI_TARGET_STATE_ACTIVE) {
2084 		req->status = CTL_LUN_ERROR;
2085 		snprintf(req->error_str, sizeof(req->error_str),
2086 		    "target \"%s\" already exists", target);
2087 		cfiscsi_target_release(ct);
2088 		ctl_free_opts(&opts);
2089 		return;
2090 	}
2091 	port = &ct->ct_port;
2092 	// WAT
2093 	if (ct->ct_state == CFISCSI_TARGET_STATE_DYING)
2094 		goto done;
2095 
2096 	port->frontend = &cfiscsi_frontend;
2097 	port->port_type = CTL_PORT_ISCSI;
2098 	/* XXX KDM what should the real number be here? */
2099 	port->num_requested_ctl_io = 4096;
2100 	port->port_name = "iscsi";
2101 	port->physical_port = tag;
2102 	port->virtual_port = ct->ct_target_id;
2103 	port->port_online = cfiscsi_online;
2104 	port->port_offline = cfiscsi_offline;
2105 	port->port_info = cfiscsi_info;
2106 	port->onoff_arg = ct;
2107 	port->fe_datamove = cfiscsi_datamove;
2108 	port->fe_done = cfiscsi_done;
2109 
2110 	/* XXX KDM what should we report here? */
2111 	/* XXX These should probably be fetched from CTL. */
2112 	port->max_targets = 1;
2113 	port->max_target_id = 15;
2114 	port->targ_port = -1;
2115 
2116 	port->options = opts;
2117 	STAILQ_INIT(&opts);
2118 
2119 	/* Generate Port ID. */
2120 	idlen = strlen(target) + strlen(",t,0x0001") + 1;
2121 	idlen = roundup2(idlen, 4);
2122 	len = sizeof(struct scsi_vpd_device_id) + idlen;
2123 	port->port_devid = malloc(sizeof(struct ctl_devid) + len,
2124 	    M_CTL, M_WAITOK | M_ZERO);
2125 	port->port_devid->len = len;
2126 	desc = (struct scsi_vpd_id_descriptor *)port->port_devid->data;
2127 	desc->proto_codeset = (SCSI_PROTO_ISCSI << 4) | SVPD_ID_CODESET_UTF8;
2128 	desc->id_type = SVPD_ID_PIV | SVPD_ID_ASSOC_PORT |
2129 	    SVPD_ID_TYPE_SCSI_NAME;
2130 	desc->length = idlen;
2131 	snprintf(desc->identifier, idlen, "%s,t,0x%4.4x", target, tag);
2132 
2133 	/* Generate Target ID. */
2134 	idlen = strlen(target) + 1;
2135 	idlen = roundup2(idlen, 4);
2136 	len = sizeof(struct scsi_vpd_device_id) + idlen;
2137 	port->target_devid = malloc(sizeof(struct ctl_devid) + len,
2138 	    M_CTL, M_WAITOK | M_ZERO);
2139 	port->target_devid->len = len;
2140 	desc = (struct scsi_vpd_id_descriptor *)port->target_devid->data;
2141 	desc->proto_codeset = (SCSI_PROTO_ISCSI << 4) | SVPD_ID_CODESET_UTF8;
2142 	desc->id_type = SVPD_ID_PIV | SVPD_ID_ASSOC_TARGET |
2143 	    SVPD_ID_TYPE_SCSI_NAME;
2144 	desc->length = idlen;
2145 	strlcpy(desc->identifier, target, idlen);
2146 
2147 	retval = ctl_port_register(port);
2148 	if (retval != 0) {
2149 		ctl_free_opts(&port->options);
2150 		cfiscsi_target_release(ct);
2151 		free(port->port_devid, M_CFISCSI);
2152 		free(port->target_devid, M_CFISCSI);
2153 		req->status = CTL_LUN_ERROR;
2154 		snprintf(req->error_str, sizeof(req->error_str),
2155 		    "ctl_port_register() failed with error %d", retval);
2156 		return;
2157 	}
2158 done:
2159 	ct->ct_state = CFISCSI_TARGET_STATE_ACTIVE;
2160 	req->status = CTL_LUN_OK;
2161 	memcpy(req->kern_args[0].kvalue, &port->targ_port,
2162 	    sizeof(port->targ_port)); //XXX
2163 }
2164 
2165 static void
2166 cfiscsi_ioctl_port_remove(struct ctl_req *req)
2167 {
2168 	struct cfiscsi_target *ct;
2169 	const char *target, *tags;
2170 	ctl_options_t opts;
2171 	uint16_t tag;
2172 
2173 	ctl_init_opts(&opts, req->num_args, req->kern_args);
2174 	target = ctl_get_opt(&opts, "cfiscsi_target");
2175 	tags = ctl_get_opt(&opts, "cfiscsi_portal_group_tag");
2176 	if (target == NULL || tags == NULL) {
2177 		ctl_free_opts(&opts);
2178 		req->status = CTL_LUN_ERROR;
2179 		snprintf(req->error_str, sizeof(req->error_str),
2180 		    "Missing required argument");
2181 		return;
2182 	}
2183 	tag = strtol(tags, (char **)NULL, 10);
2184 	ct = cfiscsi_target_find(&cfiscsi_softc, target, tag);
2185 	if (ct == NULL) {
2186 		ctl_free_opts(&opts);
2187 		req->status = CTL_LUN_ERROR;
2188 		snprintf(req->error_str, sizeof(req->error_str),
2189 		    "can't find target \"%s\"", target);
2190 		return;
2191 	}
2192 	if (ct->ct_state != CFISCSI_TARGET_STATE_ACTIVE) {
2193 		ctl_free_opts(&opts);
2194 		req->status = CTL_LUN_ERROR;
2195 		snprintf(req->error_str, sizeof(req->error_str),
2196 		    "target \"%s\" is already dying", target);
2197 		return;
2198 	}
2199 	ctl_free_opts(&opts);
2200 
2201 	ct->ct_state = CFISCSI_TARGET_STATE_DYING;
2202 	ctl_port_offline(&ct->ct_port);
2203 	cfiscsi_target_release(ct);
2204 	cfiscsi_target_release(ct);
2205 	req->status = CTL_LUN_OK;
2206 }
2207 
2208 static int
2209 cfiscsi_ioctl(struct cdev *dev,
2210     u_long cmd, caddr_t addr, int flag, struct thread *td)
2211 {
2212 	struct ctl_iscsi *ci;
2213 	struct ctl_req *req;
2214 
2215 	if (cmd == CTL_PORT_REQ) {
2216 		req = (struct ctl_req *)addr;
2217 		switch (req->reqtype) {
2218 		case CTL_REQ_CREATE:
2219 			cfiscsi_ioctl_port_create(req);
2220 			break;
2221 		case CTL_REQ_REMOVE:
2222 			cfiscsi_ioctl_port_remove(req);
2223 			break;
2224 		default:
2225 			req->status = CTL_LUN_ERROR;
2226 			snprintf(req->error_str, sizeof(req->error_str),
2227 			    "Unsupported request type %d", req->reqtype);
2228 		}
2229 		return (0);
2230 	}
2231 
2232 	if (cmd != CTL_ISCSI)
2233 		return (ENOTTY);
2234 
2235 	ci = (struct ctl_iscsi *)addr;
2236 	switch (ci->type) {
2237 	case CTL_ISCSI_HANDOFF:
2238 		cfiscsi_ioctl_handoff(ci);
2239 		break;
2240 	case CTL_ISCSI_LIST:
2241 		cfiscsi_ioctl_list(ci);
2242 		break;
2243 	case CTL_ISCSI_LOGOUT:
2244 		cfiscsi_ioctl_logout(ci);
2245 		break;
2246 	case CTL_ISCSI_TERMINATE:
2247 		cfiscsi_ioctl_terminate(ci);
2248 		break;
2249 	case CTL_ISCSI_LIMITS:
2250 		cfiscsi_ioctl_limits(ci);
2251 		break;
2252 #ifdef ICL_KERNEL_PROXY
2253 	case CTL_ISCSI_LISTEN:
2254 		cfiscsi_ioctl_listen(ci);
2255 		break;
2256 	case CTL_ISCSI_ACCEPT:
2257 		cfiscsi_ioctl_accept(ci);
2258 		break;
2259 	case CTL_ISCSI_SEND:
2260 		cfiscsi_ioctl_send(ci);
2261 		break;
2262 	case CTL_ISCSI_RECEIVE:
2263 		cfiscsi_ioctl_receive(ci);
2264 		break;
2265 #else
2266 	case CTL_ISCSI_LISTEN:
2267 	case CTL_ISCSI_ACCEPT:
2268 	case CTL_ISCSI_SEND:
2269 	case CTL_ISCSI_RECEIVE:
2270 		ci->status = CTL_ISCSI_ERROR;
2271 		snprintf(ci->error_str, sizeof(ci->error_str),
2272 		    "%s: CTL compiled without ICL_KERNEL_PROXY",
2273 		    __func__);
2274 		break;
2275 #endif /* !ICL_KERNEL_PROXY */
2276 	default:
2277 		ci->status = CTL_ISCSI_ERROR;
2278 		snprintf(ci->error_str, sizeof(ci->error_str),
2279 		    "%s: invalid iSCSI request type %d", __func__, ci->type);
2280 		break;
2281 	}
2282 
2283 	return (0);
2284 }
2285 
2286 static void
2287 cfiscsi_target_hold(struct cfiscsi_target *ct)
2288 {
2289 
2290 	refcount_acquire(&ct->ct_refcount);
2291 }
2292 
2293 static void
2294 cfiscsi_target_release(struct cfiscsi_target *ct)
2295 {
2296 	struct cfiscsi_softc *softc;
2297 
2298 	softc = ct->ct_softc;
2299 	mtx_lock(&softc->lock);
2300 	if (refcount_release(&ct->ct_refcount)) {
2301 		TAILQ_REMOVE(&softc->targets, ct, ct_next);
2302 		mtx_unlock(&softc->lock);
2303 		if (ct->ct_state != CFISCSI_TARGET_STATE_INVALID) {
2304 			ct->ct_state = CFISCSI_TARGET_STATE_INVALID;
2305 			if (ctl_port_deregister(&ct->ct_port) != 0)
2306 				printf("%s: ctl_port_deregister() failed\n",
2307 				    __func__);
2308 		}
2309 		free(ct, M_CFISCSI);
2310 
2311 		return;
2312 	}
2313 	mtx_unlock(&softc->lock);
2314 }
2315 
2316 static struct cfiscsi_target *
2317 cfiscsi_target_find(struct cfiscsi_softc *softc, const char *name, uint16_t tag)
2318 {
2319 	struct cfiscsi_target *ct;
2320 
2321 	mtx_lock(&softc->lock);
2322 	TAILQ_FOREACH(ct, &softc->targets, ct_next) {
2323 		if (ct->ct_tag != tag ||
2324 		    strcmp(name, ct->ct_name) != 0 ||
2325 		    ct->ct_state != CFISCSI_TARGET_STATE_ACTIVE)
2326 			continue;
2327 		cfiscsi_target_hold(ct);
2328 		mtx_unlock(&softc->lock);
2329 		return (ct);
2330 	}
2331 	mtx_unlock(&softc->lock);
2332 
2333 	return (NULL);
2334 }
2335 
2336 static struct cfiscsi_target *
2337 cfiscsi_target_find_or_create(struct cfiscsi_softc *softc, const char *name,
2338     const char *alias, uint16_t tag)
2339 {
2340 	struct cfiscsi_target *ct, *newct;
2341 
2342 	if (name[0] == '\0' || strlen(name) >= CTL_ISCSI_NAME_LEN)
2343 		return (NULL);
2344 
2345 	newct = malloc(sizeof(*newct), M_CFISCSI, M_WAITOK | M_ZERO);
2346 
2347 	mtx_lock(&softc->lock);
2348 	TAILQ_FOREACH(ct, &softc->targets, ct_next) {
2349 		if (ct->ct_tag != tag ||
2350 		    strcmp(name, ct->ct_name) != 0 ||
2351 		    ct->ct_state == CFISCSI_TARGET_STATE_INVALID)
2352 			continue;
2353 		cfiscsi_target_hold(ct);
2354 		mtx_unlock(&softc->lock);
2355 		free(newct, M_CFISCSI);
2356 		return (ct);
2357 	}
2358 
2359 	strlcpy(newct->ct_name, name, sizeof(newct->ct_name));
2360 	if (alias != NULL)
2361 		strlcpy(newct->ct_alias, alias, sizeof(newct->ct_alias));
2362 	newct->ct_tag = tag;
2363 	refcount_init(&newct->ct_refcount, 1);
2364 	newct->ct_softc = softc;
2365 	if (TAILQ_EMPTY(&softc->targets))
2366 		softc->last_target_id = 0;
2367 	newct->ct_target_id = ++softc->last_target_id;
2368 	TAILQ_INSERT_TAIL(&softc->targets, newct, ct_next);
2369 	mtx_unlock(&softc->lock);
2370 
2371 	return (newct);
2372 }
2373 
2374 static void
2375 cfiscsi_datamove_in(union ctl_io *io)
2376 {
2377 	struct cfiscsi_session *cs;
2378 	struct icl_pdu *request, *response;
2379 	const struct iscsi_bhs_scsi_command *bhssc;
2380 	struct iscsi_bhs_data_in *bhsdi;
2381 	struct ctl_sg_entry ctl_sg_entry, *ctl_sglist;
2382 	size_t len, expected_len, sg_len, buffer_offset;
2383 	const char *sg_addr;
2384 	int ctl_sg_count, error, i;
2385 
2386 	request = io->io_hdr.ctl_private[CTL_PRIV_FRONTEND].ptr;
2387 	cs = PDU_SESSION(request);
2388 
2389 	bhssc = (const struct iscsi_bhs_scsi_command *)request->ip_bhs;
2390 	KASSERT((bhssc->bhssc_opcode & ~ISCSI_BHS_OPCODE_IMMEDIATE) ==
2391 	    ISCSI_BHS_OPCODE_SCSI_COMMAND,
2392 	    ("bhssc->bhssc_opcode != ISCSI_BHS_OPCODE_SCSI_COMMAND"));
2393 
2394 	if (io->scsiio.kern_sg_entries > 0) {
2395 		ctl_sglist = (struct ctl_sg_entry *)io->scsiio.kern_data_ptr;
2396 		ctl_sg_count = io->scsiio.kern_sg_entries;
2397 	} else {
2398 		ctl_sglist = &ctl_sg_entry;
2399 		ctl_sglist->addr = io->scsiio.kern_data_ptr;
2400 		ctl_sglist->len = io->scsiio.kern_data_len;
2401 		ctl_sg_count = 1;
2402 	}
2403 
2404 	/*
2405 	 * This is the total amount of data to be transferred within the current
2406 	 * SCSI command.  We need to record it so that we can properly report
2407 	 * underflow/underflow.
2408 	 */
2409 	PDU_TOTAL_TRANSFER_LEN(request) = io->scsiio.kern_total_len;
2410 
2411 	/*
2412 	 * This is the offset within the current SCSI command; for the first
2413 	 * call to cfiscsi_datamove() it will be 0, and for subsequent ones
2414 	 * it will be the sum of lengths of previous ones.
2415 	 */
2416 	buffer_offset = io->scsiio.kern_rel_offset;
2417 
2418 	/*
2419 	 * This is the transfer length expected by the initiator.  In theory,
2420 	 * it could be different from the correct amount of data from the SCSI
2421 	 * point of view, even if that doesn't make any sense.
2422 	 */
2423 	expected_len = ntohl(bhssc->bhssc_expected_data_transfer_length);
2424 #if 0
2425 	if (expected_len != io->scsiio.kern_total_len) {
2426 		CFISCSI_SESSION_DEBUG(cs, "expected transfer length %zd, "
2427 		    "actual length %zd", expected_len,
2428 		    (size_t)io->scsiio.kern_total_len);
2429 	}
2430 #endif
2431 
2432 	if (buffer_offset >= expected_len) {
2433 #if 0
2434 		CFISCSI_SESSION_DEBUG(cs, "buffer_offset = %zd, "
2435 		    "already sent the expected len", buffer_offset);
2436 #endif
2437 		io->scsiio.be_move_done(io);
2438 		return;
2439 	}
2440 
2441 	i = 0;
2442 	sg_addr = NULL;
2443 	sg_len = 0;
2444 	response = NULL;
2445 	bhsdi = NULL;
2446 	for (;;) {
2447 		if (response == NULL) {
2448 			response = cfiscsi_pdu_new_response(request, M_NOWAIT);
2449 			if (response == NULL) {
2450 				CFISCSI_SESSION_WARN(cs, "failed to "
2451 				    "allocate memory; dropping connection");
2452 				ctl_set_busy(&io->scsiio);
2453 				io->scsiio.be_move_done(io);
2454 				cfiscsi_session_terminate(cs);
2455 				return;
2456 			}
2457 			bhsdi = (struct iscsi_bhs_data_in *)response->ip_bhs;
2458 			bhsdi->bhsdi_opcode = ISCSI_BHS_OPCODE_SCSI_DATA_IN;
2459 			bhsdi->bhsdi_initiator_task_tag =
2460 			    bhssc->bhssc_initiator_task_tag;
2461 			bhsdi->bhsdi_target_transfer_tag = 0xffffffff;
2462 			bhsdi->bhsdi_datasn = htonl(PDU_EXPDATASN(request));
2463 			PDU_EXPDATASN(request)++;
2464 			bhsdi->bhsdi_buffer_offset = htonl(buffer_offset);
2465 		}
2466 
2467 		KASSERT(i < ctl_sg_count, ("i >= ctl_sg_count"));
2468 		if (sg_len == 0) {
2469 			sg_addr = ctl_sglist[i].addr;
2470 			sg_len = ctl_sglist[i].len;
2471 			KASSERT(sg_len > 0, ("sg_len <= 0"));
2472 		}
2473 
2474 		len = sg_len;
2475 
2476 		/*
2477 		 * Truncate to maximum data segment length.
2478 		 */
2479 		KASSERT(response->ip_data_len < cs->cs_max_send_data_segment_length,
2480 		    ("ip_data_len %zd >= max_send_data_segment_length %d",
2481 		    response->ip_data_len, cs->cs_max_send_data_segment_length));
2482 		if (response->ip_data_len + len >
2483 		    cs->cs_max_send_data_segment_length) {
2484 			len = cs->cs_max_send_data_segment_length -
2485 			    response->ip_data_len;
2486 			KASSERT(len <= sg_len, ("len %zd > sg_len %zd",
2487 			    len, sg_len));
2488 		}
2489 
2490 		/*
2491 		 * Truncate to expected data transfer length.
2492 		 */
2493 		KASSERT(buffer_offset + response->ip_data_len < expected_len,
2494 		    ("buffer_offset %zd + ip_data_len %zd >= expected_len %zd",
2495 		    buffer_offset, response->ip_data_len, expected_len));
2496 		if (buffer_offset + response->ip_data_len + len > expected_len) {
2497 			CFISCSI_SESSION_DEBUG(cs, "truncating from %zd "
2498 			    "to expected data transfer length %zd",
2499 			    buffer_offset + response->ip_data_len + len, expected_len);
2500 			len = expected_len - (buffer_offset + response->ip_data_len);
2501 			KASSERT(len <= sg_len, ("len %zd > sg_len %zd",
2502 			    len, sg_len));
2503 		}
2504 
2505 		error = icl_pdu_append_data(response, sg_addr, len, M_NOWAIT);
2506 		if (error != 0) {
2507 			CFISCSI_SESSION_WARN(cs, "failed to "
2508 			    "allocate memory; dropping connection");
2509 			icl_pdu_free(response);
2510 			ctl_set_busy(&io->scsiio);
2511 			io->scsiio.be_move_done(io);
2512 			cfiscsi_session_terminate(cs);
2513 			return;
2514 		}
2515 		sg_addr += len;
2516 		sg_len -= len;
2517 
2518 		KASSERT(buffer_offset + response->ip_data_len <= expected_len,
2519 		    ("buffer_offset %zd + ip_data_len %zd > expected_len %zd",
2520 		    buffer_offset, response->ip_data_len, expected_len));
2521 		if (buffer_offset + response->ip_data_len == expected_len) {
2522 			/*
2523 			 * Already have the amount of data the initiator wanted.
2524 			 */
2525 			break;
2526 		}
2527 
2528 		if (sg_len == 0) {
2529 			/*
2530 			 * End of scatter-gather segment;
2531 			 * proceed to the next one...
2532 			 */
2533 			if (i == ctl_sg_count - 1) {
2534 				/*
2535 				 * ... unless this was the last one.
2536 				 */
2537 				break;
2538 			}
2539 			i++;
2540 		}
2541 
2542 		if (response->ip_data_len == cs->cs_max_send_data_segment_length) {
2543 			/*
2544 			 * Can't stuff more data into the current PDU;
2545 			 * queue it.  Note that's not enough to check
2546 			 * for kern_data_resid == 0 instead; there
2547 			 * may be several Data-In PDUs for the final
2548 			 * call to cfiscsi_datamove(), and we want
2549 			 * to set the F flag only on the last of them.
2550 			 */
2551 			buffer_offset += response->ip_data_len;
2552 			if (buffer_offset == io->scsiio.kern_total_len ||
2553 			    buffer_offset == expected_len) {
2554 				buffer_offset -= response->ip_data_len;
2555 				break;
2556 			}
2557 			cfiscsi_pdu_queue(response);
2558 			response = NULL;
2559 			bhsdi = NULL;
2560 		}
2561 	}
2562 	if (response != NULL) {
2563 		buffer_offset += response->ip_data_len;
2564 		if (buffer_offset == io->scsiio.kern_total_len ||
2565 		    buffer_offset == expected_len) {
2566 			bhsdi->bhsdi_flags |= BHSDI_FLAGS_F;
2567 			if (io->io_hdr.status == CTL_SUCCESS) {
2568 				bhsdi->bhsdi_flags |= BHSDI_FLAGS_S;
2569 				if (PDU_TOTAL_TRANSFER_LEN(request) <
2570 				    ntohl(bhssc->bhssc_expected_data_transfer_length)) {
2571 					bhsdi->bhsdi_flags |= BHSSR_FLAGS_RESIDUAL_UNDERFLOW;
2572 					bhsdi->bhsdi_residual_count =
2573 					    htonl(ntohl(bhssc->bhssc_expected_data_transfer_length) -
2574 					    PDU_TOTAL_TRANSFER_LEN(request));
2575 				} else if (PDU_TOTAL_TRANSFER_LEN(request) >
2576 				    ntohl(bhssc->bhssc_expected_data_transfer_length)) {
2577 					bhsdi->bhsdi_flags |= BHSSR_FLAGS_RESIDUAL_OVERFLOW;
2578 					bhsdi->bhsdi_residual_count =
2579 					    htonl(PDU_TOTAL_TRANSFER_LEN(request) -
2580 					    ntohl(bhssc->bhssc_expected_data_transfer_length));
2581 				}
2582 				bhsdi->bhsdi_status = io->scsiio.scsi_status;
2583 				io->io_hdr.flags |= CTL_FLAG_STATUS_SENT;
2584 			}
2585 		}
2586 		KASSERT(response->ip_data_len > 0, ("sending empty Data-In"));
2587 		cfiscsi_pdu_queue(response);
2588 	}
2589 
2590 	io->scsiio.be_move_done(io);
2591 }
2592 
2593 static void
2594 cfiscsi_datamove_out(union ctl_io *io)
2595 {
2596 	struct cfiscsi_session *cs;
2597 	struct icl_pdu *request, *response;
2598 	const struct iscsi_bhs_scsi_command *bhssc;
2599 	struct iscsi_bhs_r2t *bhsr2t;
2600 	struct cfiscsi_data_wait *cdw;
2601 	struct ctl_sg_entry ctl_sg_entry, *ctl_sglist;
2602 	uint32_t expected_len, r2t_off, r2t_len;
2603 	uint32_t target_transfer_tag;
2604 	bool done;
2605 
2606 	request = io->io_hdr.ctl_private[CTL_PRIV_FRONTEND].ptr;
2607 	cs = PDU_SESSION(request);
2608 
2609 	bhssc = (const struct iscsi_bhs_scsi_command *)request->ip_bhs;
2610 	KASSERT((bhssc->bhssc_opcode & ~ISCSI_BHS_OPCODE_IMMEDIATE) ==
2611 	    ISCSI_BHS_OPCODE_SCSI_COMMAND,
2612 	    ("bhssc->bhssc_opcode != ISCSI_BHS_OPCODE_SCSI_COMMAND"));
2613 
2614 	/*
2615 	 * We need to record it so that we can properly report
2616 	 * underflow/underflow.
2617 	 */
2618 	PDU_TOTAL_TRANSFER_LEN(request) = io->scsiio.kern_total_len;
2619 
2620 	/*
2621 	 * Report write underflow as error since CTL and backends don't
2622 	 * really support it, and SCSI does not tell how to do it right.
2623 	 */
2624 	expected_len = ntohl(bhssc->bhssc_expected_data_transfer_length);
2625 	if (io->scsiio.kern_rel_offset + io->scsiio.kern_data_len >
2626 	    expected_len) {
2627 		io->scsiio.io_hdr.port_status = 43;
2628 		io->scsiio.be_move_done(io);
2629 		return;
2630 	}
2631 
2632 	target_transfer_tag =
2633 	    atomic_fetchadd_32(&cs->cs_target_transfer_tag, 1);
2634 	cdw = cfiscsi_data_wait_new(cs, io, bhssc->bhssc_initiator_task_tag,
2635 	    &target_transfer_tag);
2636 	if (cdw == NULL) {
2637 		CFISCSI_SESSION_WARN(cs, "failed to "
2638 		    "allocate memory; dropping connection");
2639 		ctl_set_busy(&io->scsiio);
2640 		io->scsiio.be_move_done(io);
2641 		cfiscsi_session_terminate(cs);
2642 		return;
2643 	}
2644 #if 0
2645 	CFISCSI_SESSION_DEBUG(cs, "expecting Data-Out with initiator "
2646 	    "task tag 0x%x, target transfer tag 0x%x",
2647 	    bhssc->bhssc_initiator_task_tag, target_transfer_tag);
2648 #endif
2649 
2650 	cdw->cdw_ctl_io = io;
2651 	cdw->cdw_target_transfer_tag = target_transfer_tag;
2652 	cdw->cdw_initiator_task_tag = bhssc->bhssc_initiator_task_tag;
2653 	cdw->cdw_r2t_end = io->scsiio.kern_data_len;
2654 	cdw->cdw_datasn = 0;
2655 
2656 	/* Set initial data pointer for the CDW respecting ext_data_filled. */
2657 	if (io->scsiio.kern_sg_entries > 0) {
2658 		ctl_sglist = (struct ctl_sg_entry *)io->scsiio.kern_data_ptr;
2659 	} else {
2660 		ctl_sglist = &ctl_sg_entry;
2661 		ctl_sglist->addr = io->scsiio.kern_data_ptr;
2662 		ctl_sglist->len = io->scsiio.kern_data_len;
2663 	}
2664 	cdw->cdw_sg_index = 0;
2665 	cdw->cdw_sg_addr = ctl_sglist[cdw->cdw_sg_index].addr;
2666 	cdw->cdw_sg_len = ctl_sglist[cdw->cdw_sg_index].len;
2667 	r2t_off = io->scsiio.ext_data_filled;
2668 	while (r2t_off > 0) {
2669 		if (r2t_off >= cdw->cdw_sg_len) {
2670 			r2t_off -= cdw->cdw_sg_len;
2671 			cdw->cdw_sg_index++;
2672 			cdw->cdw_sg_addr = ctl_sglist[cdw->cdw_sg_index].addr;
2673 			cdw->cdw_sg_len = ctl_sglist[cdw->cdw_sg_index].len;
2674 			continue;
2675 		}
2676 		cdw->cdw_sg_addr += r2t_off;
2677 		cdw->cdw_sg_len -= r2t_off;
2678 		r2t_off = 0;
2679 	}
2680 
2681 	if (cs->cs_immediate_data &&
2682 	    io->scsiio.kern_rel_offset + io->scsiio.ext_data_filled <
2683 	    icl_pdu_data_segment_length(request)) {
2684 		done = cfiscsi_handle_data_segment(request, cdw);
2685 		if (done) {
2686 			cfiscsi_data_wait_free(cs, cdw);
2687 			io->scsiio.be_move_done(io);
2688 			return;
2689 		}
2690 	}
2691 
2692 	r2t_off = io->scsiio.kern_rel_offset + io->scsiio.ext_data_filled;
2693 	r2t_len = MIN(io->scsiio.kern_data_len - io->scsiio.ext_data_filled,
2694 	    cs->cs_max_burst_length);
2695 	cdw->cdw_r2t_end = io->scsiio.ext_data_filled + r2t_len;
2696 
2697 	CFISCSI_SESSION_LOCK(cs);
2698 	TAILQ_INSERT_TAIL(&cs->cs_waiting_for_data_out, cdw, cdw_next);
2699 	CFISCSI_SESSION_UNLOCK(cs);
2700 
2701 	/*
2702 	 * XXX: We should limit the number of outstanding R2T PDUs
2703 	 * 	per task to MaxOutstandingR2T.
2704 	 */
2705 	response = cfiscsi_pdu_new_response(request, M_NOWAIT);
2706 	if (response == NULL) {
2707 		CFISCSI_SESSION_WARN(cs, "failed to "
2708 		    "allocate memory; dropping connection");
2709 		ctl_set_busy(&io->scsiio);
2710 		io->scsiio.be_move_done(io);
2711 		cfiscsi_session_terminate(cs);
2712 		return;
2713 	}
2714 	io->io_hdr.flags |= CTL_FLAG_DMA_INPROG;
2715 	bhsr2t = (struct iscsi_bhs_r2t *)response->ip_bhs;
2716 	bhsr2t->bhsr2t_opcode = ISCSI_BHS_OPCODE_R2T;
2717 	bhsr2t->bhsr2t_flags = 0x80;
2718 	bhsr2t->bhsr2t_lun = bhssc->bhssc_lun;
2719 	bhsr2t->bhsr2t_initiator_task_tag = bhssc->bhssc_initiator_task_tag;
2720 	bhsr2t->bhsr2t_target_transfer_tag = target_transfer_tag;
2721 	/*
2722 	 * XXX: Here we assume that cfiscsi_datamove() won't ever
2723 	 *	be running concurrently on several CPUs for a given
2724 	 *	command.
2725 	 */
2726 	bhsr2t->bhsr2t_r2tsn = htonl(PDU_R2TSN(request));
2727 	PDU_R2TSN(request)++;
2728 	/*
2729 	 * This is the offset within the current SCSI command;
2730 	 * i.e. for the first call of datamove(), it will be 0,
2731 	 * and for subsequent ones it will be the sum of lengths
2732 	 * of previous ones.
2733 	 *
2734 	 * The ext_data_filled is to account for unsolicited
2735 	 * (immediate) data that might have already arrived.
2736 	 */
2737 	bhsr2t->bhsr2t_buffer_offset = htonl(r2t_off);
2738 	/*
2739 	 * This is the total length (sum of S/G lengths) this call
2740 	 * to cfiscsi_datamove() is supposed to handle, limited by
2741 	 * MaxBurstLength.
2742 	 */
2743 	bhsr2t->bhsr2t_desired_data_transfer_length = htonl(r2t_len);
2744 	cfiscsi_pdu_queue(response);
2745 }
2746 
2747 static void
2748 cfiscsi_datamove(union ctl_io *io)
2749 {
2750 
2751 	if ((io->io_hdr.flags & CTL_FLAG_DATA_MASK) == CTL_FLAG_DATA_IN)
2752 		cfiscsi_datamove_in(io);
2753 	else {
2754 		/* We hadn't received anything during this datamove yet. */
2755 		io->scsiio.ext_data_filled = 0;
2756 		cfiscsi_datamove_out(io);
2757 	}
2758 }
2759 
2760 static void
2761 cfiscsi_scsi_command_done(union ctl_io *io)
2762 {
2763 	struct icl_pdu *request, *response;
2764 	struct iscsi_bhs_scsi_command *bhssc;
2765 	struct iscsi_bhs_scsi_response *bhssr;
2766 #ifdef DIAGNOSTIC
2767 	struct cfiscsi_data_wait *cdw;
2768 #endif
2769 	struct cfiscsi_session *cs;
2770 	uint16_t sense_length;
2771 
2772 	request = io->io_hdr.ctl_private[CTL_PRIV_FRONTEND].ptr;
2773 	cs = PDU_SESSION(request);
2774 	bhssc = (struct iscsi_bhs_scsi_command *)request->ip_bhs;
2775 	KASSERT((bhssc->bhssc_opcode & ~ISCSI_BHS_OPCODE_IMMEDIATE) ==
2776 	    ISCSI_BHS_OPCODE_SCSI_COMMAND,
2777 	    ("replying to wrong opcode 0x%x", bhssc->bhssc_opcode));
2778 
2779 	//CFISCSI_SESSION_DEBUG(cs, "initiator task tag 0x%x",
2780 	//    bhssc->bhssc_initiator_task_tag);
2781 
2782 #ifdef DIAGNOSTIC
2783 	CFISCSI_SESSION_LOCK(cs);
2784 	TAILQ_FOREACH(cdw, &cs->cs_waiting_for_data_out, cdw_next)
2785 		KASSERT(bhssc->bhssc_initiator_task_tag !=
2786 		    cdw->cdw_initiator_task_tag, ("dangling cdw"));
2787 	CFISCSI_SESSION_UNLOCK(cs);
2788 #endif
2789 
2790 	/*
2791 	 * Do not return status for aborted commands.
2792 	 * There are exceptions, but none supported by CTL yet.
2793 	 */
2794 	if (((io->io_hdr.flags & CTL_FLAG_ABORT) &&
2795 	     (io->io_hdr.flags & CTL_FLAG_ABORT_STATUS) == 0) ||
2796 	    (io->io_hdr.flags & CTL_FLAG_STATUS_SENT)) {
2797 		ctl_free_io(io);
2798 		icl_pdu_free(request);
2799 		return;
2800 	}
2801 
2802 	response = cfiscsi_pdu_new_response(request, M_WAITOK);
2803 	bhssr = (struct iscsi_bhs_scsi_response *)response->ip_bhs;
2804 	bhssr->bhssr_opcode = ISCSI_BHS_OPCODE_SCSI_RESPONSE;
2805 	bhssr->bhssr_flags = 0x80;
2806 	/*
2807 	 * XXX: We don't deal with bidirectional under/overflows;
2808 	 *	does anything actually support those?
2809 	 */
2810 	if (PDU_TOTAL_TRANSFER_LEN(request) <
2811 	    ntohl(bhssc->bhssc_expected_data_transfer_length)) {
2812 		bhssr->bhssr_flags |= BHSSR_FLAGS_RESIDUAL_UNDERFLOW;
2813 		bhssr->bhssr_residual_count =
2814 		    htonl(ntohl(bhssc->bhssc_expected_data_transfer_length) -
2815 		    PDU_TOTAL_TRANSFER_LEN(request));
2816 		//CFISCSI_SESSION_DEBUG(cs, "underflow; residual count %d",
2817 		//    ntohl(bhssr->bhssr_residual_count));
2818 	} else if (PDU_TOTAL_TRANSFER_LEN(request) >
2819 	    ntohl(bhssc->bhssc_expected_data_transfer_length)) {
2820 		bhssr->bhssr_flags |= BHSSR_FLAGS_RESIDUAL_OVERFLOW;
2821 		bhssr->bhssr_residual_count =
2822 		    htonl(PDU_TOTAL_TRANSFER_LEN(request) -
2823 		    ntohl(bhssc->bhssc_expected_data_transfer_length));
2824 		//CFISCSI_SESSION_DEBUG(cs, "overflow; residual count %d",
2825 		//    ntohl(bhssr->bhssr_residual_count));
2826 	}
2827 	bhssr->bhssr_response = BHSSR_RESPONSE_COMMAND_COMPLETED;
2828 	bhssr->bhssr_status = io->scsiio.scsi_status;
2829 	bhssr->bhssr_initiator_task_tag = bhssc->bhssc_initiator_task_tag;
2830 	bhssr->bhssr_expdatasn = htonl(PDU_EXPDATASN(request));
2831 
2832 	if (io->scsiio.sense_len > 0) {
2833 #if 0
2834 		CFISCSI_SESSION_DEBUG(cs, "returning %d bytes of sense data",
2835 		    io->scsiio.sense_len);
2836 #endif
2837 		sense_length = htons(io->scsiio.sense_len);
2838 		icl_pdu_append_data(response,
2839 		    &sense_length, sizeof(sense_length), M_WAITOK);
2840 		icl_pdu_append_data(response,
2841 		    &io->scsiio.sense_data, io->scsiio.sense_len, M_WAITOK);
2842 	}
2843 
2844 	ctl_free_io(io);
2845 	icl_pdu_free(request);
2846 	cfiscsi_pdu_queue(response);
2847 }
2848 
2849 static void
2850 cfiscsi_task_management_done(union ctl_io *io)
2851 {
2852 	struct icl_pdu *request, *response;
2853 	struct iscsi_bhs_task_management_request *bhstmr;
2854 	struct iscsi_bhs_task_management_response *bhstmr2;
2855 	struct cfiscsi_data_wait *cdw, *tmpcdw;
2856 	struct cfiscsi_session *cs, *tcs;
2857 	struct cfiscsi_softc *softc;
2858 	int cold_reset = 0;
2859 
2860 	request = io->io_hdr.ctl_private[CTL_PRIV_FRONTEND].ptr;
2861 	cs = PDU_SESSION(request);
2862 	bhstmr = (struct iscsi_bhs_task_management_request *)request->ip_bhs;
2863 	KASSERT((bhstmr->bhstmr_opcode & ~ISCSI_BHS_OPCODE_IMMEDIATE) ==
2864 	    ISCSI_BHS_OPCODE_TASK_REQUEST,
2865 	    ("replying to wrong opcode 0x%x", bhstmr->bhstmr_opcode));
2866 
2867 #if 0
2868 	CFISCSI_SESSION_DEBUG(cs, "initiator task tag 0x%x; referenced task tag 0x%x",
2869 	    bhstmr->bhstmr_initiator_task_tag,
2870 	    bhstmr->bhstmr_referenced_task_tag);
2871 #endif
2872 
2873 	if ((bhstmr->bhstmr_function & ~0x80) ==
2874 	    BHSTMR_FUNCTION_ABORT_TASK) {
2875 		/*
2876 		 * Make sure we no longer wait for Data-Out for this command.
2877 		 */
2878 		CFISCSI_SESSION_LOCK(cs);
2879 		TAILQ_FOREACH_SAFE(cdw,
2880 		    &cs->cs_waiting_for_data_out, cdw_next, tmpcdw) {
2881 			if (bhstmr->bhstmr_referenced_task_tag !=
2882 			    cdw->cdw_initiator_task_tag)
2883 				continue;
2884 
2885 #if 0
2886 			CFISCSI_SESSION_DEBUG(cs, "removing csw for initiator task "
2887 			    "tag 0x%x", bhstmr->bhstmr_initiator_task_tag);
2888 #endif
2889 			TAILQ_REMOVE(&cs->cs_waiting_for_data_out,
2890 			    cdw, cdw_next);
2891 			io->io_hdr.flags &= ~CTL_FLAG_DMA_INPROG;
2892 			cdw->cdw_ctl_io->scsiio.io_hdr.port_status = 43;
2893 			cdw->cdw_ctl_io->scsiio.be_move_done(cdw->cdw_ctl_io);
2894 			cfiscsi_data_wait_free(cs, cdw);
2895 		}
2896 		CFISCSI_SESSION_UNLOCK(cs);
2897 	}
2898 	if ((bhstmr->bhstmr_function & ~0x80) ==
2899 	    BHSTMR_FUNCTION_TARGET_COLD_RESET &&
2900 	    io->io_hdr.status == CTL_SUCCESS)
2901 		cold_reset = 1;
2902 
2903 	response = cfiscsi_pdu_new_response(request, M_WAITOK);
2904 	bhstmr2 = (struct iscsi_bhs_task_management_response *)
2905 	    response->ip_bhs;
2906 	bhstmr2->bhstmr_opcode = ISCSI_BHS_OPCODE_TASK_RESPONSE;
2907 	bhstmr2->bhstmr_flags = 0x80;
2908 	switch (io->taskio.task_status) {
2909 	case CTL_TASK_FUNCTION_COMPLETE:
2910 		bhstmr2->bhstmr_response = BHSTMR_RESPONSE_FUNCTION_COMPLETE;
2911 		break;
2912 	case CTL_TASK_FUNCTION_SUCCEEDED:
2913 		bhstmr2->bhstmr_response = BHSTMR_RESPONSE_FUNCTION_SUCCEEDED;
2914 		break;
2915 	case CTL_TASK_LUN_DOES_NOT_EXIST:
2916 		bhstmr2->bhstmr_response = BHSTMR_RESPONSE_LUN_DOES_NOT_EXIST;
2917 		break;
2918 	case CTL_TASK_FUNCTION_NOT_SUPPORTED:
2919 	default:
2920 		bhstmr2->bhstmr_response = BHSTMR_RESPONSE_FUNCTION_NOT_SUPPORTED;
2921 		break;
2922 	}
2923 	memcpy(bhstmr2->bhstmr_additional_reponse_information,
2924 	    io->taskio.task_resp, sizeof(io->taskio.task_resp));
2925 	bhstmr2->bhstmr_initiator_task_tag = bhstmr->bhstmr_initiator_task_tag;
2926 
2927 	ctl_free_io(io);
2928 	icl_pdu_free(request);
2929 	cfiscsi_pdu_queue(response);
2930 
2931 	if (cold_reset) {
2932 		softc = cs->cs_target->ct_softc;
2933 		mtx_lock(&softc->lock);
2934 		TAILQ_FOREACH(tcs, &softc->sessions, cs_next) {
2935 			if (tcs->cs_target == cs->cs_target)
2936 				cfiscsi_session_terminate(tcs);
2937 		}
2938 		mtx_unlock(&softc->lock);
2939 	}
2940 }
2941 
2942 static void
2943 cfiscsi_done(union ctl_io *io)
2944 {
2945 	struct icl_pdu *request;
2946 	struct cfiscsi_session *cs;
2947 
2948 	KASSERT(((io->io_hdr.status & CTL_STATUS_MASK) != CTL_STATUS_NONE),
2949 		("invalid CTL status %#x", io->io_hdr.status));
2950 
2951 	if (io->io_hdr.io_type == CTL_IO_TASK &&
2952 	    io->taskio.task_action == CTL_TASK_I_T_NEXUS_RESET) {
2953 		/*
2954 		 * Implicit task termination has just completed; nothing to do.
2955 		 */
2956 		cs = io->io_hdr.ctl_private[CTL_PRIV_FRONTEND].ptr;
2957 		cs->cs_tasks_aborted = true;
2958 		refcount_release(&cs->cs_outstanding_ctl_pdus);
2959 		wakeup(__DEVOLATILE(void *, &cs->cs_outstanding_ctl_pdus));
2960 		ctl_free_io(io);
2961 		return;
2962 	}
2963 
2964 	request = io->io_hdr.ctl_private[CTL_PRIV_FRONTEND].ptr;
2965 	cs = PDU_SESSION(request);
2966 
2967 	switch (request->ip_bhs->bhs_opcode & ~ISCSI_BHS_OPCODE_IMMEDIATE) {
2968 	case ISCSI_BHS_OPCODE_SCSI_COMMAND:
2969 		cfiscsi_scsi_command_done(io);
2970 		break;
2971 	case ISCSI_BHS_OPCODE_TASK_REQUEST:
2972 		cfiscsi_task_management_done(io);
2973 		break;
2974 	default:
2975 		panic("cfiscsi_done called with wrong opcode 0x%x",
2976 		    request->ip_bhs->bhs_opcode);
2977 	}
2978 
2979 	refcount_release(&cs->cs_outstanding_ctl_pdus);
2980 }
2981