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