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