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