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