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