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