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