ctl_frontend_iscsi.c revision 275203
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 275203 2014-11-28 08:56:37Z 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 275203 2014-11-28 08:56:37Z 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 = 3;
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	io = ctl_alloc_io(cs->cs_target->ct_port.ctl_pool_ref);
1068	if (io == NULL) {
1069		CFISCSI_SESSION_WARN(cs, "can't allocate ctl_io");
1070		return;
1071	}
1072	ctl_zero_io(io);
1073	io->io_hdr.ctl_private[CTL_PRIV_FRONTEND].ptr = cs;
1074	io->io_hdr.io_type = CTL_IO_TASK;
1075	io->io_hdr.nexus.initid.id = cs->cs_ctl_initid;
1076	io->io_hdr.nexus.targ_port = cs->cs_target->ct_port.targ_port;
1077	io->io_hdr.nexus.targ_target.id = 0;
1078	io->io_hdr.nexus.targ_lun = 0;
1079	io->taskio.tag_type = CTL_TAG_SIMPLE; /* XXX */
1080	io->taskio.task_action = CTL_TASK_I_T_NEXUS_RESET;
1081	wait = cs->cs_outstanding_ctl_pdus;
1082	refcount_acquire(&cs->cs_outstanding_ctl_pdus);
1083	error = ctl_queue(io);
1084	if (error != CTL_RETVAL_COMPLETE) {
1085		CFISCSI_SESSION_WARN(cs, "ctl_queue() failed; error %d", error);
1086		refcount_release(&cs->cs_outstanding_ctl_pdus);
1087		ctl_free_io(io);
1088	}
1089
1090	CFISCSI_SESSION_LOCK(cs);
1091	while ((cdw = TAILQ_FIRST(&cs->cs_waiting_for_data_out)) != NULL) {
1092		TAILQ_REMOVE(&cs->cs_waiting_for_data_out, cdw, cdw_next);
1093		CFISCSI_SESSION_UNLOCK(cs);
1094		/*
1095		 * Set nonzero port status; this prevents backends from
1096		 * assuming that the data transfer actually succeeded
1097		 * and writing uninitialized data to disk.
1098		 */
1099		cdw->cdw_ctl_io->scsiio.io_hdr.port_status = 42;
1100		cdw->cdw_ctl_io->scsiio.be_move_done(cdw->cdw_ctl_io);
1101		uma_zfree(cfiscsi_data_wait_zone, cdw);
1102		CFISCSI_SESSION_LOCK(cs);
1103	}
1104	CFISCSI_SESSION_UNLOCK(cs);
1105
1106	/*
1107	 * Wait for CTL to terminate all the tasks.
1108	 */
1109	if (wait > 0)
1110		CFISCSI_SESSION_WARN(cs,
1111		    "waiting for CTL to terminate %d tasks", wait);
1112	for (;;) {
1113		refcount_acquire(&cs->cs_outstanding_ctl_pdus);
1114		last = refcount_release(&cs->cs_outstanding_ctl_pdus);
1115		if (last != 0)
1116			break;
1117		tsleep(__DEVOLATILE(void *, &cs->cs_outstanding_ctl_pdus),
1118		    0, "cfiscsi_terminate", hz / 100);
1119	}
1120	if (wait > 0)
1121		CFISCSI_SESSION_WARN(cs, "tasks terminated");
1122}
1123
1124static void
1125cfiscsi_maintenance_thread(void *arg)
1126{
1127	struct cfiscsi_session *cs;
1128
1129	cs = arg;
1130
1131	for (;;) {
1132		CFISCSI_SESSION_LOCK(cs);
1133		if (cs->cs_terminating == false)
1134			cv_wait(&cs->cs_maintenance_cv, &cs->cs_lock);
1135		CFISCSI_SESSION_UNLOCK(cs);
1136
1137		if (cs->cs_terminating) {
1138
1139			/*
1140			 * We used to wait up to 30 seconds to deliver queued
1141			 * PDUs to the initiator.  We also tried hard to deliver
1142			 * SCSI Responses for the aborted PDUs.  We don't do
1143			 * that anymore.  We might need to revisit that.
1144			 */
1145			callout_drain(&cs->cs_callout);
1146			icl_conn_close(cs->cs_conn);
1147
1148			/*
1149			 * At this point ICL receive thread is no longer
1150			 * running; no new tasks can be queued.
1151			 */
1152			cfiscsi_session_terminate_tasks(cs);
1153			cfiscsi_session_delete(cs);
1154			kthread_exit();
1155			return;
1156		}
1157		CFISCSI_SESSION_DEBUG(cs, "nothing to do");
1158	}
1159}
1160
1161static void
1162cfiscsi_session_terminate(struct cfiscsi_session *cs)
1163{
1164
1165	if (cs->cs_terminating)
1166		return;
1167	cs->cs_terminating = true;
1168	cv_signal(&cs->cs_maintenance_cv);
1169#ifdef ICL_KERNEL_PROXY
1170	cv_signal(&cs->cs_login_cv);
1171#endif
1172}
1173
1174static int
1175cfiscsi_session_register_initiator(struct cfiscsi_session *cs)
1176{
1177	struct cfiscsi_target *ct;
1178	char *name;
1179	int i;
1180
1181	KASSERT(cs->cs_ctl_initid == -1, ("already registered"));
1182
1183	ct = cs->cs_target;
1184	name = strdup(cs->cs_initiator_id, M_CTL);
1185	i = ctl_add_initiator(&ct->ct_port, -1, 0, name);
1186	if (i < 0) {
1187		CFISCSI_SESSION_WARN(cs, "ctl_add_initiator failed with error %d",
1188		    i);
1189		cs->cs_ctl_initid = -1;
1190		return (1);
1191	}
1192	cs->cs_ctl_initid = i;
1193#if 0
1194	CFISCSI_SESSION_DEBUG(cs, "added initiator id %d", i);
1195#endif
1196
1197	return (0);
1198}
1199
1200static void
1201cfiscsi_session_unregister_initiator(struct cfiscsi_session *cs)
1202{
1203	int error;
1204
1205	if (cs->cs_ctl_initid == -1)
1206		return;
1207
1208	error = ctl_remove_initiator(&cs->cs_target->ct_port, cs->cs_ctl_initid);
1209	if (error != 0) {
1210		CFISCSI_SESSION_WARN(cs, "ctl_remove_initiator failed with error %d",
1211		    error);
1212	}
1213	cs->cs_ctl_initid = -1;
1214}
1215
1216static struct cfiscsi_session *
1217cfiscsi_session_new(struct cfiscsi_softc *softc)
1218{
1219	struct cfiscsi_session *cs;
1220	int error;
1221
1222	cs = malloc(sizeof(*cs), M_CFISCSI, M_NOWAIT | M_ZERO);
1223	if (cs == NULL) {
1224		CFISCSI_WARN("malloc failed");
1225		return (NULL);
1226	}
1227	cs->cs_ctl_initid = -1;
1228
1229	refcount_init(&cs->cs_outstanding_ctl_pdus, 0);
1230	TAILQ_INIT(&cs->cs_waiting_for_data_out);
1231	mtx_init(&cs->cs_lock, "cfiscsi_lock", NULL, MTX_DEF);
1232	cv_init(&cs->cs_maintenance_cv, "cfiscsi_mt");
1233#ifdef ICL_KERNEL_PROXY
1234	cv_init(&cs->cs_login_cv, "cfiscsi_login");
1235#endif
1236
1237	cs->cs_conn = icl_conn_new("cfiscsi", &cs->cs_lock);
1238	cs->cs_conn->ic_receive = cfiscsi_receive_callback;
1239	cs->cs_conn->ic_error = cfiscsi_error_callback;
1240	cs->cs_conn->ic_prv0 = cs;
1241
1242	error = kthread_add(cfiscsi_maintenance_thread, cs, NULL, NULL, 0, 0, "cfiscsimt");
1243	if (error != 0) {
1244		CFISCSI_SESSION_WARN(cs, "kthread_add(9) failed with error %d", error);
1245		free(cs, M_CFISCSI);
1246		return (NULL);
1247	}
1248
1249	mtx_lock(&softc->lock);
1250	cs->cs_id = softc->last_session_id + 1;
1251	softc->last_session_id++;
1252	mtx_unlock(&softc->lock);
1253
1254	mtx_lock(&softc->lock);
1255	TAILQ_INSERT_TAIL(&softc->sessions, cs, cs_next);
1256	mtx_unlock(&softc->lock);
1257
1258	/*
1259	 * Start pinging the initiator.
1260	 */
1261	callout_init(&cs->cs_callout, 1);
1262	callout_reset(&cs->cs_callout, 1 * hz, cfiscsi_callout, cs);
1263
1264	return (cs);
1265}
1266
1267static void
1268cfiscsi_session_delete(struct cfiscsi_session *cs)
1269{
1270	struct cfiscsi_softc *softc;
1271
1272	softc = &cfiscsi_softc;
1273
1274	KASSERT(cs->cs_outstanding_ctl_pdus == 0,
1275	    ("destroying session with outstanding CTL pdus"));
1276	KASSERT(TAILQ_EMPTY(&cs->cs_waiting_for_data_out),
1277	    ("destroying session with non-empty queue"));
1278
1279	cfiscsi_session_unregister_initiator(cs);
1280	if (cs->cs_target != NULL)
1281		cfiscsi_target_release(cs->cs_target);
1282	icl_conn_close(cs->cs_conn);
1283	icl_conn_free(cs->cs_conn);
1284
1285	mtx_lock(&softc->lock);
1286	TAILQ_REMOVE(&softc->sessions, cs, cs_next);
1287	mtx_unlock(&softc->lock);
1288
1289	free(cs, M_CFISCSI);
1290}
1291
1292int
1293cfiscsi_init(void)
1294{
1295	struct cfiscsi_softc *softc;
1296	int retval;
1297
1298	softc = &cfiscsi_softc;
1299	retval = 0;
1300	bzero(softc, sizeof(*softc));
1301	mtx_init(&softc->lock, "cfiscsi", NULL, MTX_DEF);
1302
1303#ifdef ICL_KERNEL_PROXY
1304	cv_init(&softc->accept_cv, "cfiscsi_accept");
1305#endif
1306	TAILQ_INIT(&softc->sessions);
1307	TAILQ_INIT(&softc->targets);
1308
1309	cfiscsi_data_wait_zone = uma_zcreate("cfiscsi_data_wait",
1310	    sizeof(struct cfiscsi_data_wait), NULL, NULL, NULL, NULL,
1311	    UMA_ALIGN_PTR, 0);
1312
1313	return (0);
1314}
1315
1316#ifdef ICL_KERNEL_PROXY
1317static void
1318cfiscsi_accept(struct socket *so, struct sockaddr *sa, int portal_id)
1319{
1320	struct cfiscsi_session *cs;
1321
1322	cs = cfiscsi_session_new(&cfiscsi_softc);
1323	if (cs == NULL) {
1324		CFISCSI_WARN("failed to create session");
1325		return;
1326	}
1327
1328	icl_conn_handoff_sock(cs->cs_conn, so);
1329	cs->cs_initiator_sa = sa;
1330	cs->cs_portal_id = portal_id;
1331	cs->cs_waiting_for_ctld = true;
1332	cv_signal(&cfiscsi_softc.accept_cv);
1333}
1334#endif
1335
1336static void
1337cfiscsi_online(void *arg)
1338{
1339	struct cfiscsi_softc *softc;
1340	struct cfiscsi_target *ct;
1341	int online;
1342
1343	ct = (struct cfiscsi_target *)arg;
1344	softc = ct->ct_softc;
1345
1346	mtx_lock(&softc->lock);
1347	if (ct->ct_online) {
1348		mtx_unlock(&softc->lock);
1349		return;
1350	}
1351	ct->ct_online = 1;
1352	online = softc->online++;
1353	mtx_unlock(&softc->lock);
1354	if (online > 0)
1355		return;
1356
1357#ifdef ICL_KERNEL_PROXY
1358	if (softc->listener != NULL)
1359		icl_listen_free(softc->listener);
1360	softc->listener = icl_listen_new(cfiscsi_accept);
1361#endif
1362}
1363
1364static void
1365cfiscsi_offline(void *arg)
1366{
1367	struct cfiscsi_softc *softc;
1368	struct cfiscsi_target *ct;
1369	struct cfiscsi_session *cs;
1370	int online;
1371
1372	ct = (struct cfiscsi_target *)arg;
1373	softc = ct->ct_softc;
1374
1375	mtx_lock(&softc->lock);
1376	if (!ct->ct_online) {
1377		mtx_unlock(&softc->lock);
1378		return;
1379	}
1380	ct->ct_online = 0;
1381	online = --softc->online;
1382
1383	TAILQ_FOREACH(cs, &softc->sessions, cs_next) {
1384		if (cs->cs_target == ct)
1385			cfiscsi_session_terminate(cs);
1386	}
1387	mtx_unlock(&softc->lock);
1388	if (online > 0)
1389		return;
1390
1391#ifdef ICL_KERNEL_PROXY
1392	icl_listen_free(softc->listener);
1393	softc->listener = NULL;
1394#endif
1395}
1396
1397static int
1398cfiscsi_info(void *arg, struct sbuf *sb)
1399{
1400	struct cfiscsi_target *ct = (struct cfiscsi_target *)arg;
1401	int retval;
1402
1403	retval = sbuf_printf(sb, "\t<cfiscsi_state>%d</cfiscsi_state>\n",
1404	    ct->ct_state);
1405	return (retval);
1406}
1407
1408static void
1409cfiscsi_ioctl_handoff(struct ctl_iscsi *ci)
1410{
1411	struct cfiscsi_softc *softc;
1412	struct cfiscsi_session *cs, *cs2;
1413	struct cfiscsi_target *ct;
1414	struct ctl_iscsi_handoff_params *cihp;
1415	int error;
1416
1417	cihp = (struct ctl_iscsi_handoff_params *)&(ci->data);
1418	softc = &cfiscsi_softc;
1419
1420	CFISCSI_DEBUG("new connection from %s (%s) to %s",
1421	    cihp->initiator_name, cihp->initiator_addr,
1422	    cihp->target_name);
1423
1424	ct = cfiscsi_target_find(softc, cihp->target_name);
1425	if (ct == NULL) {
1426		ci->status = CTL_ISCSI_ERROR;
1427		snprintf(ci->error_str, sizeof(ci->error_str),
1428		    "%s: target not found", __func__);
1429		return;
1430	}
1431
1432	if (ct->ct_online == 0) {
1433		ci->status = CTL_ISCSI_ERROR;
1434		snprintf(ci->error_str, sizeof(ci->error_str),
1435		    "%s: port offline", __func__);
1436		cfiscsi_target_release(ct);
1437		return;
1438	}
1439
1440#ifdef ICL_KERNEL_PROXY
1441	if (cihp->socket > 0 && cihp->connection_id > 0) {
1442		snprintf(ci->error_str, sizeof(ci->error_str),
1443		    "both socket and connection_id set");
1444		ci->status = CTL_ISCSI_ERROR;
1445		cfiscsi_target_release(ct);
1446		return;
1447	}
1448	if (cihp->socket == 0) {
1449		mtx_lock(&cfiscsi_softc.lock);
1450		TAILQ_FOREACH(cs, &cfiscsi_softc.sessions, cs_next) {
1451			if (cs->cs_id == cihp->socket)
1452				break;
1453		}
1454		if (cs == NULL) {
1455			mtx_unlock(&cfiscsi_softc.lock);
1456			snprintf(ci->error_str, sizeof(ci->error_str),
1457			    "connection not found");
1458			ci->status = CTL_ISCSI_ERROR;
1459			cfiscsi_target_release(ct);
1460			return;
1461		}
1462		mtx_unlock(&cfiscsi_softc.lock);
1463	} else {
1464#endif
1465		cs = cfiscsi_session_new(softc);
1466		if (cs == NULL) {
1467			ci->status = CTL_ISCSI_ERROR;
1468			snprintf(ci->error_str, sizeof(ci->error_str),
1469			    "%s: cfiscsi_session_new failed", __func__);
1470			cfiscsi_target_release(ct);
1471			return;
1472		}
1473#ifdef ICL_KERNEL_PROXY
1474	}
1475#endif
1476	cs->cs_target = ct;
1477
1478	/*
1479	 * First PDU of Full Feature phase has the same CmdSN as the last
1480	 * PDU from the Login Phase received from the initiator.  Thus,
1481	 * the -1 below.
1482	 */
1483	cs->cs_portal_group_tag = cihp->portal_group_tag;
1484	cs->cs_cmdsn = cihp->cmdsn;
1485	cs->cs_statsn = cihp->statsn;
1486	cs->cs_max_data_segment_length = cihp->max_recv_data_segment_length;
1487	cs->cs_max_burst_length = cihp->max_burst_length;
1488	cs->cs_immediate_data = !!cihp->immediate_data;
1489	if (cihp->header_digest == CTL_ISCSI_DIGEST_CRC32C)
1490		cs->cs_conn->ic_header_crc32c = true;
1491	if (cihp->data_digest == CTL_ISCSI_DIGEST_CRC32C)
1492		cs->cs_conn->ic_data_crc32c = true;
1493
1494	strlcpy(cs->cs_initiator_name,
1495	    cihp->initiator_name, sizeof(cs->cs_initiator_name));
1496	strlcpy(cs->cs_initiator_addr,
1497	    cihp->initiator_addr, sizeof(cs->cs_initiator_addr));
1498	strlcpy(cs->cs_initiator_alias,
1499	    cihp->initiator_alias, sizeof(cs->cs_initiator_alias));
1500	memcpy(cs->cs_initiator_isid,
1501	    cihp->initiator_isid, sizeof(cs->cs_initiator_isid));
1502	snprintf(cs->cs_initiator_id, sizeof(cs->cs_initiator_id),
1503	    "%s,i,0x%02x%02x%02x%02x%02x%02x", cs->cs_initiator_name,
1504	    cihp->initiator_isid[0], cihp->initiator_isid[1],
1505	    cihp->initiator_isid[2], cihp->initiator_isid[3],
1506	    cihp->initiator_isid[4], cihp->initiator_isid[5]);
1507
1508	refcount_acquire(&cs->cs_outstanding_ctl_pdus);
1509restart:
1510	if (!cs->cs_terminating) {
1511		mtx_lock(&softc->lock);
1512		TAILQ_FOREACH(cs2, &softc->sessions, cs_next) {
1513			if (cs2 != cs && cs2->cs_tasks_aborted == false &&
1514			    cs->cs_target == cs2->cs_target &&
1515			    cs->cs_portal_group_tag == cs2->cs_portal_group_tag &&
1516			    strcmp(cs->cs_initiator_id, cs2->cs_initiator_id) == 0) {
1517				cfiscsi_session_terminate(cs2);
1518				mtx_unlock(&softc->lock);
1519				pause("cfiscsi_reinstate", 1);
1520				goto restart;
1521			}
1522		}
1523		mtx_unlock(&softc->lock);
1524	}
1525
1526	/*
1527	 * Register initiator with CTL.
1528	 */
1529	cfiscsi_session_register_initiator(cs);
1530
1531#ifdef ICL_KERNEL_PROXY
1532	if (cihp->socket > 0) {
1533#endif
1534		error = icl_conn_handoff(cs->cs_conn, cihp->socket);
1535		if (error != 0) {
1536			cfiscsi_session_terminate(cs);
1537			refcount_release(&cs->cs_outstanding_ctl_pdus);
1538			ci->status = CTL_ISCSI_ERROR;
1539			snprintf(ci->error_str, sizeof(ci->error_str),
1540			    "%s: icl_conn_handoff failed with error %d",
1541			    __func__, error);
1542			return;
1543		}
1544#ifdef ICL_KERNEL_PROXY
1545	}
1546#endif
1547
1548#ifdef ICL_KERNEL_PROXY
1549	cs->cs_login_phase = false;
1550
1551	/*
1552	 * First PDU of the Full Feature phase has likely already arrived.
1553	 * We have to pick it up and execute properly.
1554	 */
1555	if (cs->cs_login_pdu != NULL) {
1556		CFISCSI_SESSION_DEBUG(cs, "picking up first PDU");
1557		cfiscsi_pdu_handle(cs->cs_login_pdu);
1558		cs->cs_login_pdu = NULL;
1559	}
1560#endif
1561
1562	refcount_release(&cs->cs_outstanding_ctl_pdus);
1563	ci->status = CTL_ISCSI_OK;
1564}
1565
1566static void
1567cfiscsi_ioctl_list(struct ctl_iscsi *ci)
1568{
1569	struct ctl_iscsi_list_params *cilp;
1570	struct cfiscsi_session *cs;
1571	struct cfiscsi_softc *softc;
1572	struct sbuf *sb;
1573	int error;
1574
1575	cilp = (struct ctl_iscsi_list_params *)&(ci->data);
1576	softc = &cfiscsi_softc;
1577
1578	sb = sbuf_new(NULL, NULL, cilp->alloc_len, SBUF_FIXEDLEN);
1579	if (sb == NULL) {
1580		ci->status = CTL_ISCSI_ERROR;
1581		snprintf(ci->error_str, sizeof(ci->error_str),
1582		    "Unable to allocate %d bytes for iSCSI session list",
1583		    cilp->alloc_len);
1584		return;
1585	}
1586
1587	sbuf_printf(sb, "<ctlislist>\n");
1588	mtx_lock(&softc->lock);
1589	TAILQ_FOREACH(cs, &softc->sessions, cs_next) {
1590#ifdef ICL_KERNEL_PROXY
1591		if (cs->cs_target == NULL)
1592			continue;
1593#endif
1594		error = sbuf_printf(sb, "<connection id=\"%d\">"
1595		    "<initiator>%s</initiator>"
1596		    "<initiator_addr>%s</initiator_addr>"
1597		    "<initiator_alias>%s</initiator_alias>"
1598		    "<target>%s</target>"
1599		    "<target_alias>%s</target_alias>"
1600		    "<header_digest>%s</header_digest>"
1601		    "<data_digest>%s</data_digest>"
1602		    "<max_data_segment_length>%zd</max_data_segment_length>"
1603		    "<immediate_data>%d</immediate_data>"
1604		    "<iser>%d</iser>"
1605		    "</connection>\n",
1606		    cs->cs_id,
1607		    cs->cs_initiator_name, cs->cs_initiator_addr, cs->cs_initiator_alias,
1608		    cs->cs_target->ct_name, cs->cs_target->ct_alias,
1609		    cs->cs_conn->ic_header_crc32c ? "CRC32C" : "None",
1610		    cs->cs_conn->ic_data_crc32c ? "CRC32C" : "None",
1611		    cs->cs_max_data_segment_length,
1612		    cs->cs_immediate_data,
1613		    cs->cs_conn->ic_iser);
1614		if (error != 0)
1615			break;
1616	}
1617	mtx_unlock(&softc->lock);
1618	error = sbuf_printf(sb, "</ctlislist>\n");
1619	if (error != 0) {
1620		sbuf_delete(sb);
1621		ci->status = CTL_ISCSI_LIST_NEED_MORE_SPACE;
1622		snprintf(ci->error_str, sizeof(ci->error_str),
1623		    "Out of space, %d bytes is too small", cilp->alloc_len);
1624		return;
1625	}
1626	sbuf_finish(sb);
1627
1628	error = copyout(sbuf_data(sb), cilp->conn_xml, sbuf_len(sb) + 1);
1629	cilp->fill_len = sbuf_len(sb) + 1;
1630	ci->status = CTL_ISCSI_OK;
1631	sbuf_delete(sb);
1632}
1633
1634static void
1635cfiscsi_ioctl_terminate(struct ctl_iscsi *ci)
1636{
1637	struct icl_pdu *response;
1638	struct iscsi_bhs_asynchronous_message *bhsam;
1639	struct ctl_iscsi_terminate_params *citp;
1640	struct cfiscsi_session *cs;
1641	struct cfiscsi_softc *softc;
1642	int found = 0;
1643
1644	citp = (struct ctl_iscsi_terminate_params *)&(ci->data);
1645	softc = &cfiscsi_softc;
1646
1647	mtx_lock(&softc->lock);
1648	TAILQ_FOREACH(cs, &softc->sessions, cs_next) {
1649		if (citp->all == 0 && cs->cs_id != citp->connection_id &&
1650		    strcmp(cs->cs_initiator_name, citp->initiator_name) != 0 &&
1651		    strcmp(cs->cs_initiator_addr, citp->initiator_addr) != 0)
1652			continue;
1653
1654		response = icl_pdu_new_bhs(cs->cs_conn, M_NOWAIT);
1655		if (response == NULL) {
1656			/*
1657			 * Oh well.  Just terminate the connection.
1658			 */
1659		} else {
1660			bhsam = (struct iscsi_bhs_asynchronous_message *)
1661			    response->ip_bhs;
1662			bhsam->bhsam_opcode = ISCSI_BHS_OPCODE_ASYNC_MESSAGE;
1663			bhsam->bhsam_flags = 0x80;
1664			bhsam->bhsam_0xffffffff = 0xffffffff;
1665			bhsam->bhsam_async_event =
1666			    BHSAM_EVENT_TARGET_TERMINATES_SESSION;
1667			cfiscsi_pdu_queue(response);
1668		}
1669		cfiscsi_session_terminate(cs);
1670		found++;
1671	}
1672	mtx_unlock(&softc->lock);
1673
1674	if (found == 0) {
1675		ci->status = CTL_ISCSI_SESSION_NOT_FOUND;
1676		snprintf(ci->error_str, sizeof(ci->error_str),
1677		    "No matching connections found");
1678		return;
1679	}
1680
1681	ci->status = CTL_ISCSI_OK;
1682}
1683
1684static void
1685cfiscsi_ioctl_logout(struct ctl_iscsi *ci)
1686{
1687	struct icl_pdu *response;
1688	struct iscsi_bhs_asynchronous_message *bhsam;
1689	struct ctl_iscsi_logout_params *cilp;
1690	struct cfiscsi_session *cs;
1691	struct cfiscsi_softc *softc;
1692	int found = 0;
1693
1694	cilp = (struct ctl_iscsi_logout_params *)&(ci->data);
1695	softc = &cfiscsi_softc;
1696
1697	mtx_lock(&softc->lock);
1698	TAILQ_FOREACH(cs, &softc->sessions, cs_next) {
1699		if (cilp->all == 0 && cs->cs_id != cilp->connection_id &&
1700		    strcmp(cs->cs_initiator_name, cilp->initiator_name) != 0 &&
1701		    strcmp(cs->cs_initiator_addr, cilp->initiator_addr) != 0)
1702			continue;
1703
1704		response = icl_pdu_new_bhs(cs->cs_conn, M_NOWAIT);
1705		if (response == NULL) {
1706			ci->status = CTL_ISCSI_ERROR;
1707			snprintf(ci->error_str, sizeof(ci->error_str),
1708			    "Unable to allocate memory");
1709			mtx_unlock(&softc->lock);
1710			return;
1711		}
1712		bhsam =
1713		    (struct iscsi_bhs_asynchronous_message *)response->ip_bhs;
1714		bhsam->bhsam_opcode = ISCSI_BHS_OPCODE_ASYNC_MESSAGE;
1715		bhsam->bhsam_flags = 0x80;
1716		bhsam->bhsam_async_event = BHSAM_EVENT_TARGET_REQUESTS_LOGOUT;
1717		bhsam->bhsam_parameter3 = htons(10);
1718		cfiscsi_pdu_queue(response);
1719		found++;
1720	}
1721	mtx_unlock(&softc->lock);
1722
1723	if (found == 0) {
1724		ci->status = CTL_ISCSI_SESSION_NOT_FOUND;
1725		snprintf(ci->error_str, sizeof(ci->error_str),
1726		    "No matching connections found");
1727		return;
1728	}
1729
1730	ci->status = CTL_ISCSI_OK;
1731}
1732
1733#ifdef ICL_KERNEL_PROXY
1734static void
1735cfiscsi_ioctl_listen(struct ctl_iscsi *ci)
1736{
1737	struct ctl_iscsi_listen_params *cilp;
1738	struct sockaddr *sa;
1739	int error;
1740
1741	cilp = (struct ctl_iscsi_listen_params *)&(ci->data);
1742
1743	if (cfiscsi_softc.listener == NULL) {
1744		CFISCSI_DEBUG("no listener");
1745		snprintf(ci->error_str, sizeof(ci->error_str), "no listener");
1746		ci->status = CTL_ISCSI_ERROR;
1747		return;
1748	}
1749
1750	error = getsockaddr(&sa, (void *)cilp->addr, cilp->addrlen);
1751	if (error != 0) {
1752		CFISCSI_DEBUG("getsockaddr, error %d", error);
1753		snprintf(ci->error_str, sizeof(ci->error_str), "getsockaddr failed");
1754		ci->status = CTL_ISCSI_ERROR;
1755		return;
1756	}
1757
1758	error = icl_listen_add(cfiscsi_softc.listener, cilp->iser, cilp->domain,
1759	    cilp->socktype, cilp->protocol, sa, cilp->portal_id);
1760	if (error != 0) {
1761		free(sa, M_SONAME);
1762		CFISCSI_DEBUG("icl_listen_add, error %d", error);
1763		snprintf(ci->error_str, sizeof(ci->error_str),
1764		    "icl_listen_add failed, error %d", error);
1765		ci->status = CTL_ISCSI_ERROR;
1766		return;
1767	}
1768
1769	ci->status = CTL_ISCSI_OK;
1770}
1771
1772static void
1773cfiscsi_ioctl_accept(struct ctl_iscsi *ci)
1774{
1775	struct ctl_iscsi_accept_params *ciap;
1776	struct cfiscsi_session *cs;
1777	int error;
1778
1779	ciap = (struct ctl_iscsi_accept_params *)&(ci->data);
1780
1781	mtx_lock(&cfiscsi_softc.lock);
1782	for (;;) {
1783		TAILQ_FOREACH(cs, &cfiscsi_softc.sessions, cs_next) {
1784			if (cs->cs_waiting_for_ctld)
1785				break;
1786		}
1787		if (cs != NULL)
1788			break;
1789		error = cv_wait_sig(&cfiscsi_softc.accept_cv, &cfiscsi_softc.lock);
1790		if (error != 0) {
1791			mtx_unlock(&cfiscsi_softc.lock);
1792			snprintf(ci->error_str, sizeof(ci->error_str), "interrupted");
1793			ci->status = CTL_ISCSI_ERROR;
1794			return;
1795		}
1796	}
1797	mtx_unlock(&cfiscsi_softc.lock);
1798
1799	cs->cs_waiting_for_ctld = false;
1800	cs->cs_login_phase = true;
1801
1802	ciap->connection_id = cs->cs_id;
1803	ciap->portal_id = cs->cs_portal_id;
1804	ciap->initiator_addrlen = cs->cs_initiator_sa->sa_len;
1805	error = copyout(cs->cs_initiator_sa, ciap->initiator_addr,
1806	    cs->cs_initiator_sa->sa_len);
1807	if (error != 0) {
1808		snprintf(ci->error_str, sizeof(ci->error_str),
1809		    "copyout failed with error %d", error);
1810		ci->status = CTL_ISCSI_ERROR;
1811		return;
1812	}
1813
1814	ci->status = CTL_ISCSI_OK;
1815}
1816
1817static void
1818cfiscsi_ioctl_send(struct ctl_iscsi *ci)
1819{
1820	struct ctl_iscsi_send_params *cisp;
1821	struct cfiscsi_session *cs;
1822	struct icl_pdu *ip;
1823	size_t datalen;
1824	void *data;
1825	int error;
1826
1827	cisp = (struct ctl_iscsi_send_params *)&(ci->data);
1828
1829	mtx_lock(&cfiscsi_softc.lock);
1830	TAILQ_FOREACH(cs, &cfiscsi_softc.sessions, cs_next) {
1831		if (cs->cs_id == cisp->connection_id)
1832			break;
1833	}
1834	if (cs == NULL) {
1835		mtx_unlock(&cfiscsi_softc.lock);
1836		snprintf(ci->error_str, sizeof(ci->error_str), "connection not found");
1837		ci->status = CTL_ISCSI_ERROR;
1838		return;
1839	}
1840	mtx_unlock(&cfiscsi_softc.lock);
1841
1842#if 0
1843	if (cs->cs_login_phase == false)
1844		return (EBUSY);
1845#endif
1846
1847	if (cs->cs_terminating) {
1848		snprintf(ci->error_str, sizeof(ci->error_str), "connection is terminating");
1849		ci->status = CTL_ISCSI_ERROR;
1850		return;
1851	}
1852
1853	datalen = cisp->data_segment_len;
1854	/*
1855	 * XXX
1856	 */
1857	//if (datalen > CFISCSI_MAX_DATA_SEGMENT_LENGTH) {
1858	if (datalen > 65535) {
1859		snprintf(ci->error_str, sizeof(ci->error_str), "data segment too big");
1860		ci->status = CTL_ISCSI_ERROR;
1861		return;
1862	}
1863	if (datalen > 0) {
1864		data = malloc(datalen, M_CFISCSI, M_WAITOK);
1865		error = copyin(cisp->data_segment, data, datalen);
1866		if (error != 0) {
1867			free(data, M_CFISCSI);
1868			snprintf(ci->error_str, sizeof(ci->error_str), "copyin error %d", error);
1869			ci->status = CTL_ISCSI_ERROR;
1870			return;
1871		}
1872	}
1873
1874	ip = icl_pdu_new_bhs(cs->cs_conn, M_WAITOK);
1875	memcpy(ip->ip_bhs, cisp->bhs, sizeof(*ip->ip_bhs));
1876	if (datalen > 0) {
1877		icl_pdu_append_data(ip, data, datalen, M_WAITOK);
1878		free(data, M_CFISCSI);
1879	}
1880	CFISCSI_SESSION_LOCK(cs);
1881	icl_pdu_queue(ip);
1882	CFISCSI_SESSION_UNLOCK(cs);
1883	ci->status = CTL_ISCSI_OK;
1884}
1885
1886static void
1887cfiscsi_ioctl_receive(struct ctl_iscsi *ci)
1888{
1889	struct ctl_iscsi_receive_params *cirp;
1890	struct cfiscsi_session *cs;
1891	struct icl_pdu *ip;
1892	void *data;
1893	int error;
1894
1895	cirp = (struct ctl_iscsi_receive_params *)&(ci->data);
1896
1897	mtx_lock(&cfiscsi_softc.lock);
1898	TAILQ_FOREACH(cs, &cfiscsi_softc.sessions, cs_next) {
1899		if (cs->cs_id == cirp->connection_id)
1900			break;
1901	}
1902	if (cs == NULL) {
1903		mtx_unlock(&cfiscsi_softc.lock);
1904		snprintf(ci->error_str, sizeof(ci->error_str),
1905		    "connection not found");
1906		ci->status = CTL_ISCSI_ERROR;
1907		return;
1908	}
1909	mtx_unlock(&cfiscsi_softc.lock);
1910
1911#if 0
1912	if (is->is_login_phase == false)
1913		return (EBUSY);
1914#endif
1915
1916	CFISCSI_SESSION_LOCK(cs);
1917	while (cs->cs_login_pdu == NULL && cs->cs_terminating == false) {
1918		error = cv_wait_sig(&cs->cs_login_cv, &cs->cs_lock);
1919		if (error != 0) {
1920			CFISCSI_SESSION_UNLOCK(cs);
1921			snprintf(ci->error_str, sizeof(ci->error_str),
1922			    "interrupted by signal");
1923			ci->status = CTL_ISCSI_ERROR;
1924			return;
1925		}
1926	}
1927
1928	if (cs->cs_terminating) {
1929		CFISCSI_SESSION_UNLOCK(cs);
1930		snprintf(ci->error_str, sizeof(ci->error_str),
1931		    "connection terminating");
1932		ci->status = CTL_ISCSI_ERROR;
1933		return;
1934	}
1935	ip = cs->cs_login_pdu;
1936	cs->cs_login_pdu = NULL;
1937	CFISCSI_SESSION_UNLOCK(cs);
1938
1939	if (ip->ip_data_len > cirp->data_segment_len) {
1940		icl_pdu_free(ip);
1941		snprintf(ci->error_str, sizeof(ci->error_str),
1942		    "data segment too big");
1943		ci->status = CTL_ISCSI_ERROR;
1944		return;
1945	}
1946
1947	copyout(ip->ip_bhs, cirp->bhs, sizeof(*ip->ip_bhs));
1948	if (ip->ip_data_len > 0) {
1949		data = malloc(ip->ip_data_len, M_CFISCSI, M_WAITOK);
1950		icl_pdu_get_data(ip, 0, data, ip->ip_data_len);
1951		copyout(data, cirp->data_segment, ip->ip_data_len);
1952		free(data, M_CFISCSI);
1953	}
1954
1955	icl_pdu_free(ip);
1956	ci->status = CTL_ISCSI_OK;
1957}
1958
1959#endif /* !ICL_KERNEL_PROXY */
1960
1961static void
1962cfiscsi_ioctl_port_create(struct ctl_req *req)
1963{
1964	struct cfiscsi_target *ct;
1965	struct ctl_port *port;
1966	const char *target, *alias, *tag;
1967	struct scsi_vpd_id_descriptor *desc;
1968	ctl_options_t opts;
1969	int retval, len, idlen;
1970
1971	ctl_init_opts(&opts, req->num_args, req->kern_args);
1972	target = ctl_get_opt(&opts, "cfiscsi_target");
1973	alias = ctl_get_opt(&opts, "cfiscsi_target_alias");
1974	tag = ctl_get_opt(&opts, "cfiscsi_portal_group_tag");
1975	if (target == NULL || tag == NULL) {
1976		req->status = CTL_LUN_ERROR;
1977		snprintf(req->error_str, sizeof(req->error_str),
1978		    "Missing required argument");
1979		ctl_free_opts(&opts);
1980		return;
1981	}
1982	ct = cfiscsi_target_find_or_create(&cfiscsi_softc, target, alias);
1983	if (ct == NULL) {
1984		req->status = CTL_LUN_ERROR;
1985		snprintf(req->error_str, sizeof(req->error_str),
1986		    "failed to create target \"%s\"", target);
1987		ctl_free_opts(&opts);
1988		return;
1989	}
1990	if (ct->ct_state == CFISCSI_TARGET_STATE_ACTIVE) {
1991		req->status = CTL_LUN_ERROR;
1992		snprintf(req->error_str, sizeof(req->error_str),
1993		    "target \"%s\" already exist", target);
1994		cfiscsi_target_release(ct);
1995		ctl_free_opts(&opts);
1996		return;
1997	}
1998	port = &ct->ct_port;
1999	if (ct->ct_state == CFISCSI_TARGET_STATE_DYING)
2000		goto done;
2001
2002	port->frontend = &cfiscsi_frontend;
2003	port->port_type = CTL_PORT_ISCSI;
2004	/* XXX KDM what should the real number be here? */
2005	port->num_requested_ctl_io = 4096;
2006	port->port_name = "iscsi";
2007	port->physical_port = strtoul(tag, NULL, 0);
2008	port->virtual_port = ct->ct_target_id;
2009	port->port_online = cfiscsi_online;
2010	port->port_offline = cfiscsi_offline;
2011	port->port_info = cfiscsi_info;
2012	port->onoff_arg = ct;
2013	port->lun_enable = cfiscsi_lun_enable;
2014	port->lun_disable = cfiscsi_lun_disable;
2015	port->lun_map = cfiscsi_lun_map;
2016	port->targ_lun_arg = ct;
2017	port->fe_datamove = cfiscsi_datamove;
2018	port->fe_done = cfiscsi_done;
2019
2020	/* XXX KDM what should we report here? */
2021	/* XXX These should probably be fetched from CTL. */
2022	port->max_targets = 1;
2023	port->max_target_id = 15;
2024
2025	port->options = opts;
2026	STAILQ_INIT(&opts);
2027
2028	/* Generate Port ID. */
2029	idlen = strlen(target) + strlen(",t,0x0001") + 1;
2030	idlen = roundup2(idlen, 4);
2031	len = sizeof(struct scsi_vpd_device_id) + idlen;
2032	port->port_devid = malloc(sizeof(struct ctl_devid) + len,
2033	    M_CTL, M_WAITOK | M_ZERO);
2034	port->port_devid->len = len;
2035	desc = (struct scsi_vpd_id_descriptor *)port->port_devid->data;
2036	desc->proto_codeset = (SCSI_PROTO_ISCSI << 4) | SVPD_ID_CODESET_UTF8;
2037	desc->id_type = SVPD_ID_PIV | SVPD_ID_ASSOC_PORT |
2038	    SVPD_ID_TYPE_SCSI_NAME;
2039	desc->length = idlen;
2040	snprintf(desc->identifier, idlen, "%s,t,0x%4.4x",
2041	    target, port->physical_port);
2042
2043	/* Generate Target ID. */
2044	idlen = strlen(target) + 1;
2045	idlen = roundup2(idlen, 4);
2046	len = sizeof(struct scsi_vpd_device_id) + idlen;
2047	port->target_devid = malloc(sizeof(struct ctl_devid) + len,
2048	    M_CTL, M_WAITOK | M_ZERO);
2049	port->target_devid->len = len;
2050	desc = (struct scsi_vpd_id_descriptor *)port->target_devid->data;
2051	desc->proto_codeset = (SCSI_PROTO_ISCSI << 4) | SVPD_ID_CODESET_UTF8;
2052	desc->id_type = SVPD_ID_PIV | SVPD_ID_ASSOC_TARGET |
2053	    SVPD_ID_TYPE_SCSI_NAME;
2054	desc->length = idlen;
2055	strlcpy(desc->identifier, target, idlen);
2056
2057	retval = ctl_port_register(port, /*master_SC*/ 1);
2058	if (retval != 0) {
2059		ctl_free_opts(&port->options);
2060		cfiscsi_target_release(ct);
2061		free(port->port_devid, M_CFISCSI);
2062		free(port->target_devid, M_CFISCSI);
2063		req->status = CTL_LUN_ERROR;
2064		snprintf(req->error_str, sizeof(req->error_str),
2065		    "ctl_frontend_register() failed with error %d", retval);
2066		return;
2067	}
2068done:
2069	ct->ct_state = CFISCSI_TARGET_STATE_ACTIVE;
2070	req->status = CTL_LUN_OK;
2071	memcpy(req->kern_args[0].kvalue, &port->targ_port,
2072	    sizeof(port->targ_port)); //XXX
2073}
2074
2075static void
2076cfiscsi_ioctl_port_remove(struct ctl_req *req)
2077{
2078	struct cfiscsi_target *ct;
2079	const char *target;
2080	ctl_options_t opts;
2081
2082	ctl_init_opts(&opts, req->num_args, req->kern_args);
2083	target = ctl_get_opt(&opts, "cfiscsi_target");
2084	if (target == NULL) {
2085		ctl_free_opts(&opts);
2086		req->status = CTL_LUN_ERROR;
2087		snprintf(req->error_str, sizeof(req->error_str),
2088		    "Missing required argument");
2089		return;
2090	}
2091	ct = cfiscsi_target_find(&cfiscsi_softc, target);
2092	if (ct == NULL) {
2093		ctl_free_opts(&opts);
2094		req->status = CTL_LUN_ERROR;
2095		snprintf(req->error_str, sizeof(req->error_str),
2096		    "can't find target \"%s\"", target);
2097		return;
2098	}
2099	if (ct->ct_state != CFISCSI_TARGET_STATE_ACTIVE) {
2100		ctl_free_opts(&opts);
2101		req->status = CTL_LUN_ERROR;
2102		snprintf(req->error_str, sizeof(req->error_str),
2103		    "target \"%s\" is already dying", target);
2104		return;
2105	}
2106	ctl_free_opts(&opts);
2107
2108	ct->ct_state = CFISCSI_TARGET_STATE_DYING;
2109	ctl_port_offline(&ct->ct_port);
2110	cfiscsi_target_release(ct);
2111	cfiscsi_target_release(ct);
2112}
2113
2114static int
2115cfiscsi_ioctl(struct cdev *dev,
2116    u_long cmd, caddr_t addr, int flag, struct thread *td)
2117{
2118	struct ctl_iscsi *ci;
2119	struct ctl_req *req;
2120
2121	if (cmd == CTL_PORT_REQ) {
2122		req = (struct ctl_req *)addr;
2123		switch (req->reqtype) {
2124		case CTL_REQ_CREATE:
2125			cfiscsi_ioctl_port_create(req);
2126			break;
2127		case CTL_REQ_REMOVE:
2128			cfiscsi_ioctl_port_remove(req);
2129			break;
2130		default:
2131			req->status = CTL_LUN_ERROR;
2132			snprintf(req->error_str, sizeof(req->error_str),
2133			    "Unsupported request type %d", req->reqtype);
2134		}
2135		return (0);
2136	}
2137
2138	if (cmd != CTL_ISCSI)
2139		return (ENOTTY);
2140
2141	ci = (struct ctl_iscsi *)addr;
2142	switch (ci->type) {
2143	case CTL_ISCSI_HANDOFF:
2144		cfiscsi_ioctl_handoff(ci);
2145		break;
2146	case CTL_ISCSI_LIST:
2147		cfiscsi_ioctl_list(ci);
2148		break;
2149	case CTL_ISCSI_TERMINATE:
2150		cfiscsi_ioctl_terminate(ci);
2151		break;
2152	case CTL_ISCSI_LOGOUT:
2153		cfiscsi_ioctl_logout(ci);
2154		break;
2155#ifdef ICL_KERNEL_PROXY
2156	case CTL_ISCSI_LISTEN:
2157		cfiscsi_ioctl_listen(ci);
2158		break;
2159	case CTL_ISCSI_ACCEPT:
2160		cfiscsi_ioctl_accept(ci);
2161		break;
2162	case CTL_ISCSI_SEND:
2163		cfiscsi_ioctl_send(ci);
2164		break;
2165	case CTL_ISCSI_RECEIVE:
2166		cfiscsi_ioctl_receive(ci);
2167		break;
2168#else
2169	case CTL_ISCSI_LISTEN:
2170	case CTL_ISCSI_ACCEPT:
2171	case CTL_ISCSI_SEND:
2172	case CTL_ISCSI_RECEIVE:
2173		ci->status = CTL_ISCSI_ERROR;
2174		snprintf(ci->error_str, sizeof(ci->error_str),
2175		    "%s: CTL compiled without ICL_KERNEL_PROXY",
2176		    __func__);
2177		break;
2178#endif /* !ICL_KERNEL_PROXY */
2179	default:
2180		ci->status = CTL_ISCSI_ERROR;
2181		snprintf(ci->error_str, sizeof(ci->error_str),
2182		    "%s: invalid iSCSI request type %d", __func__, ci->type);
2183		break;
2184	}
2185
2186	return (0);
2187}
2188
2189static void
2190cfiscsi_target_hold(struct cfiscsi_target *ct)
2191{
2192
2193	refcount_acquire(&ct->ct_refcount);
2194}
2195
2196static void
2197cfiscsi_target_release(struct cfiscsi_target *ct)
2198{
2199	struct cfiscsi_softc *softc;
2200
2201	softc = ct->ct_softc;
2202	mtx_lock(&softc->lock);
2203	if (refcount_release(&ct->ct_refcount)) {
2204		TAILQ_REMOVE(&softc->targets, ct, ct_next);
2205		mtx_unlock(&softc->lock);
2206		if (ct->ct_state != CFISCSI_TARGET_STATE_INVALID) {
2207			ct->ct_state = CFISCSI_TARGET_STATE_INVALID;
2208			if (ctl_port_deregister(&ct->ct_port) != 0)
2209				printf("%s: ctl_port_deregister() failed\n",
2210				    __func__);
2211		}
2212		free(ct, M_CFISCSI);
2213
2214		return;
2215	}
2216	mtx_unlock(&softc->lock);
2217}
2218
2219static struct cfiscsi_target *
2220cfiscsi_target_find(struct cfiscsi_softc *softc, const char *name)
2221{
2222	struct cfiscsi_target *ct;
2223
2224	mtx_lock(&softc->lock);
2225	TAILQ_FOREACH(ct, &softc->targets, ct_next) {
2226		if (strcmp(name, ct->ct_name) != 0 ||
2227		    ct->ct_state != CFISCSI_TARGET_STATE_ACTIVE)
2228			continue;
2229		cfiscsi_target_hold(ct);
2230		mtx_unlock(&softc->lock);
2231		return (ct);
2232	}
2233	mtx_unlock(&softc->lock);
2234
2235	return (NULL);
2236}
2237
2238static struct cfiscsi_target *
2239cfiscsi_target_find_or_create(struct cfiscsi_softc *softc, const char *name,
2240    const char *alias)
2241{
2242	struct cfiscsi_target *ct, *newct;
2243	int i;
2244
2245	if (name[0] == '\0' || strlen(name) >= CTL_ISCSI_NAME_LEN)
2246		return (NULL);
2247
2248	newct = malloc(sizeof(*newct), M_CFISCSI, M_WAITOK | M_ZERO);
2249
2250	mtx_lock(&softc->lock);
2251	TAILQ_FOREACH(ct, &softc->targets, ct_next) {
2252		if (strcmp(name, ct->ct_name) != 0 ||
2253		    ct->ct_state == CFISCSI_TARGET_STATE_INVALID)
2254			continue;
2255		cfiscsi_target_hold(ct);
2256		mtx_unlock(&softc->lock);
2257		free(newct, M_CFISCSI);
2258		return (ct);
2259	}
2260
2261	for (i = 0; i < CTL_MAX_LUNS; i++)
2262		newct->ct_luns[i] = UINT32_MAX;
2263
2264	strlcpy(newct->ct_name, name, sizeof(newct->ct_name));
2265	if (alias != NULL)
2266		strlcpy(newct->ct_alias, alias, sizeof(newct->ct_alias));
2267	refcount_init(&newct->ct_refcount, 1);
2268	newct->ct_softc = softc;
2269	if (TAILQ_EMPTY(&softc->targets))
2270		softc->last_target_id = 0;
2271	newct->ct_target_id = ++softc->last_target_id;
2272	TAILQ_INSERT_TAIL(&softc->targets, newct, ct_next);
2273	mtx_unlock(&softc->lock);
2274
2275	return (newct);
2276}
2277
2278/*
2279 * Takes LUN from the target space and returns LUN from the CTL space.
2280 */
2281static uint32_t
2282cfiscsi_lun_map(void *arg, uint32_t lun)
2283{
2284	struct cfiscsi_target *ct = arg;
2285
2286	if (lun >= CTL_MAX_LUNS) {
2287		CFISCSI_DEBUG("requested lun number %d is higher "
2288		    "than maximum %d", lun, CTL_MAX_LUNS - 1);
2289		return (UINT32_MAX);
2290	}
2291	return (ct->ct_luns[lun]);
2292}
2293
2294static int
2295cfiscsi_target_set_lun(struct cfiscsi_target *ct,
2296    unsigned long lun_id, unsigned long ctl_lun_id)
2297{
2298
2299	if (lun_id >= CTL_MAX_LUNS) {
2300		CFISCSI_WARN("requested lun number %ld is higher "
2301		    "than maximum %d", lun_id, CTL_MAX_LUNS - 1);
2302		return (-1);
2303	}
2304
2305	if (ct->ct_luns[lun_id] < CTL_MAX_LUNS) {
2306		/*
2307		 * CTL calls cfiscsi_lun_enable() twice for each LUN - once
2308		 * when the LUN is created, and a second time just before
2309		 * the port is brought online; don't emit warnings
2310		 * for that case.
2311		 */
2312		if (ct->ct_luns[lun_id] == ctl_lun_id)
2313			return (0);
2314		CFISCSI_WARN("lun %ld already allocated", lun_id);
2315		return (-1);
2316	}
2317
2318#if 0
2319	CFISCSI_DEBUG("adding mapping for lun %ld, target %s "
2320	    "to ctl lun %ld", lun_id, ct->ct_name, ctl_lun_id);
2321#endif
2322
2323	ct->ct_luns[lun_id] = ctl_lun_id;
2324
2325	return (0);
2326}
2327
2328static int
2329cfiscsi_lun_enable(void *arg, struct ctl_id target_id, int lun_id)
2330{
2331	struct cfiscsi_softc *softc;
2332	struct cfiscsi_target *ct;
2333	const char *target = NULL;
2334	const char *lun = NULL;
2335	unsigned long tmp;
2336
2337	ct = (struct cfiscsi_target *)arg;
2338	softc = ct->ct_softc;
2339
2340	target = ctl_get_opt(&control_softc->ctl_luns[lun_id]->be_lun->options,
2341	    "cfiscsi_target");
2342	lun = ctl_get_opt(&control_softc->ctl_luns[lun_id]->be_lun->options,
2343	    "cfiscsi_lun");
2344
2345	if (target == NULL && lun == NULL)
2346		return (0);
2347
2348	if (target == NULL || lun == NULL) {
2349		CFISCSI_WARN("lun added with cfiscsi_target, but without "
2350		    "cfiscsi_lun, or the other way around; ignoring");
2351		return (0);
2352	}
2353
2354	if (strcmp(target, ct->ct_name) != 0)
2355		return (0);
2356
2357	tmp = strtoul(lun, NULL, 10);
2358	cfiscsi_target_set_lun(ct, tmp, lun_id);
2359	return (0);
2360}
2361
2362static int
2363cfiscsi_lun_disable(void *arg, struct ctl_id target_id, int lun_id)
2364{
2365	struct cfiscsi_softc *softc;
2366	struct cfiscsi_target *ct;
2367	int i;
2368
2369	ct = (struct cfiscsi_target *)arg;
2370	softc = ct->ct_softc;
2371
2372	mtx_lock(&softc->lock);
2373	for (i = 0; i < CTL_MAX_LUNS; i++) {
2374		if (ct->ct_luns[i] != lun_id)
2375			continue;
2376		ct->ct_luns[i] = UINT32_MAX;
2377		break;
2378	}
2379	mtx_unlock(&softc->lock);
2380	return (0);
2381}
2382
2383static void
2384cfiscsi_datamove_in(union ctl_io *io)
2385{
2386	struct cfiscsi_session *cs;
2387	struct icl_pdu *request, *response;
2388	const struct iscsi_bhs_scsi_command *bhssc;
2389	struct iscsi_bhs_data_in *bhsdi;
2390	struct ctl_sg_entry ctl_sg_entry, *ctl_sglist;
2391	size_t len, expected_len, sg_len, buffer_offset;
2392	const char *sg_addr;
2393	int ctl_sg_count, error, i;
2394
2395	request = io->io_hdr.ctl_private[CTL_PRIV_FRONTEND].ptr;
2396	cs = PDU_SESSION(request);
2397
2398	bhssc = (const struct iscsi_bhs_scsi_command *)request->ip_bhs;
2399	KASSERT((bhssc->bhssc_opcode & ~ISCSI_BHS_OPCODE_IMMEDIATE) ==
2400	    ISCSI_BHS_OPCODE_SCSI_COMMAND,
2401	    ("bhssc->bhssc_opcode != ISCSI_BHS_OPCODE_SCSI_COMMAND"));
2402
2403	if (io->scsiio.kern_sg_entries > 0) {
2404		ctl_sglist = (struct ctl_sg_entry *)io->scsiio.kern_data_ptr;
2405		ctl_sg_count = io->scsiio.kern_sg_entries;
2406	} else {
2407		ctl_sglist = &ctl_sg_entry;
2408		ctl_sglist->addr = io->scsiio.kern_data_ptr;
2409		ctl_sglist->len = io->scsiio.kern_data_len;
2410		ctl_sg_count = 1;
2411	}
2412
2413	/*
2414	 * This is the total amount of data to be transferred within the current
2415	 * SCSI command.  We need to record it so that we can properly report
2416	 * underflow/underflow.
2417	 */
2418	PDU_TOTAL_TRANSFER_LEN(request) = io->scsiio.kern_total_len;
2419
2420	/*
2421	 * This is the offset within the current SCSI command; for the first
2422	 * call to cfiscsi_datamove() it will be 0, and for subsequent ones
2423	 * it will be the sum of lengths of previous ones.
2424	 */
2425	buffer_offset = io->scsiio.kern_rel_offset;
2426
2427	/*
2428	 * This is the transfer length expected by the initiator.  In theory,
2429	 * it could be different from the correct amount of data from the SCSI
2430	 * point of view, even if that doesn't make any sense.
2431	 */
2432	expected_len = ntohl(bhssc->bhssc_expected_data_transfer_length);
2433#if 0
2434	if (expected_len != io->scsiio.kern_total_len) {
2435		CFISCSI_SESSION_DEBUG(cs, "expected transfer length %zd, "
2436		    "actual length %zd", expected_len,
2437		    (size_t)io->scsiio.kern_total_len);
2438	}
2439#endif
2440
2441	if (buffer_offset >= expected_len) {
2442#if 0
2443		CFISCSI_SESSION_DEBUG(cs, "buffer_offset = %zd, "
2444		    "already sent the expected len", buffer_offset);
2445#endif
2446		io->scsiio.be_move_done(io);
2447		return;
2448	}
2449
2450	i = 0;
2451	sg_addr = NULL;
2452	sg_len = 0;
2453	response = NULL;
2454	bhsdi = NULL;
2455	for (;;) {
2456		if (response == NULL) {
2457			response = cfiscsi_pdu_new_response(request, M_NOWAIT);
2458			if (response == NULL) {
2459				CFISCSI_SESSION_WARN(cs, "failed to "
2460				    "allocate memory; dropping connection");
2461				ctl_set_busy(&io->scsiio);
2462				io->scsiio.be_move_done(io);
2463				cfiscsi_session_terminate(cs);
2464				return;
2465			}
2466			bhsdi = (struct iscsi_bhs_data_in *)response->ip_bhs;
2467			bhsdi->bhsdi_opcode = ISCSI_BHS_OPCODE_SCSI_DATA_IN;
2468			bhsdi->bhsdi_initiator_task_tag =
2469			    bhssc->bhssc_initiator_task_tag;
2470			bhsdi->bhsdi_datasn = htonl(PDU_EXPDATASN(request));
2471			PDU_EXPDATASN(request)++;
2472			bhsdi->bhsdi_buffer_offset = htonl(buffer_offset);
2473		}
2474
2475		KASSERT(i < ctl_sg_count, ("i >= ctl_sg_count"));
2476		if (sg_len == 0) {
2477			sg_addr = ctl_sglist[i].addr;
2478			sg_len = ctl_sglist[i].len;
2479			KASSERT(sg_len > 0, ("sg_len <= 0"));
2480		}
2481
2482		len = sg_len;
2483
2484		/*
2485		 * Truncate to maximum data segment length.
2486		 */
2487		KASSERT(response->ip_data_len < cs->cs_max_data_segment_length,
2488		    ("ip_data_len %zd >= max_data_segment_length %zd",
2489		    response->ip_data_len, cs->cs_max_data_segment_length));
2490		if (response->ip_data_len + len >
2491		    cs->cs_max_data_segment_length) {
2492			len = cs->cs_max_data_segment_length -
2493			    response->ip_data_len;
2494			KASSERT(len <= sg_len, ("len %zd > sg_len %zd",
2495			    len, sg_len));
2496		}
2497
2498		/*
2499		 * Truncate to expected data transfer length.
2500		 */
2501		KASSERT(buffer_offset + response->ip_data_len < expected_len,
2502		    ("buffer_offset %zd + ip_data_len %zd >= expected_len %zd",
2503		    buffer_offset, response->ip_data_len, expected_len));
2504		if (buffer_offset + response->ip_data_len + len > expected_len) {
2505			CFISCSI_SESSION_DEBUG(cs, "truncating from %zd "
2506			    "to expected data transfer length %zd",
2507			    buffer_offset + response->ip_data_len + len, expected_len);
2508			len = expected_len - (buffer_offset + response->ip_data_len);
2509			KASSERT(len <= sg_len, ("len %zd > sg_len %zd",
2510			    len, sg_len));
2511		}
2512
2513		error = icl_pdu_append_data(response, sg_addr, len, M_NOWAIT);
2514		if (error != 0) {
2515			CFISCSI_SESSION_WARN(cs, "failed to "
2516			    "allocate memory; dropping connection");
2517			icl_pdu_free(response);
2518			ctl_set_busy(&io->scsiio);
2519			io->scsiio.be_move_done(io);
2520			cfiscsi_session_terminate(cs);
2521			return;
2522		}
2523		sg_addr += len;
2524		sg_len -= len;
2525
2526		KASSERT(buffer_offset + response->ip_data_len <= expected_len,
2527		    ("buffer_offset %zd + ip_data_len %zd > expected_len %zd",
2528		    buffer_offset, response->ip_data_len, expected_len));
2529		if (buffer_offset + response->ip_data_len == expected_len) {
2530			/*
2531			 * Already have the amount of data the initiator wanted.
2532			 */
2533			break;
2534		}
2535
2536		if (sg_len == 0) {
2537			/*
2538			 * End of scatter-gather segment;
2539			 * proceed to the next one...
2540			 */
2541			if (i == ctl_sg_count - 1) {
2542				/*
2543				 * ... unless this was the last one.
2544				 */
2545				break;
2546			}
2547			i++;
2548		}
2549
2550		if (response->ip_data_len == cs->cs_max_data_segment_length) {
2551			/*
2552			 * Can't stuff more data into the current PDU;
2553			 * queue it.  Note that's not enough to check
2554			 * for kern_data_resid == 0 instead; there
2555			 * may be several Data-In PDUs for the final
2556			 * call to cfiscsi_datamove(), and we want
2557			 * to set the F flag only on the last of them.
2558			 */
2559			buffer_offset += response->ip_data_len;
2560			if (buffer_offset == io->scsiio.kern_total_len ||
2561			    buffer_offset == expected_len)
2562				bhsdi->bhsdi_flags |= BHSDI_FLAGS_F;
2563			cfiscsi_pdu_queue(response);
2564			response = NULL;
2565			bhsdi = NULL;
2566		}
2567	}
2568	if (response != NULL) {
2569		buffer_offset += response->ip_data_len;
2570		if (buffer_offset == io->scsiio.kern_total_len ||
2571		    buffer_offset == expected_len)
2572			bhsdi->bhsdi_flags |= BHSDI_FLAGS_F;
2573		KASSERT(response->ip_data_len > 0, ("sending empty Data-In"));
2574		cfiscsi_pdu_queue(response);
2575	}
2576
2577	io->scsiio.be_move_done(io);
2578}
2579
2580static void
2581cfiscsi_datamove_out(union ctl_io *io)
2582{
2583	struct cfiscsi_session *cs;
2584	struct icl_pdu *request, *response;
2585	const struct iscsi_bhs_scsi_command *bhssc;
2586	struct iscsi_bhs_r2t *bhsr2t;
2587	struct cfiscsi_data_wait *cdw;
2588	struct ctl_sg_entry ctl_sg_entry, *ctl_sglist;
2589	uint32_t expected_len, r2t_off, r2t_len;
2590	uint32_t target_transfer_tag;
2591	bool done;
2592
2593	request = io->io_hdr.ctl_private[CTL_PRIV_FRONTEND].ptr;
2594	cs = PDU_SESSION(request);
2595
2596	bhssc = (const struct iscsi_bhs_scsi_command *)request->ip_bhs;
2597	KASSERT((bhssc->bhssc_opcode & ~ISCSI_BHS_OPCODE_IMMEDIATE) ==
2598	    ISCSI_BHS_OPCODE_SCSI_COMMAND,
2599	    ("bhssc->bhssc_opcode != ISCSI_BHS_OPCODE_SCSI_COMMAND"));
2600
2601	/*
2602	 * We need to record it so that we can properly report
2603	 * underflow/underflow.
2604	 */
2605	PDU_TOTAL_TRANSFER_LEN(request) = io->scsiio.kern_total_len;
2606
2607	/*
2608	 * Report write underflow as error since CTL and backends don't
2609	 * really support it, and SCSI does not tell how to do it right.
2610	 */
2611	expected_len = ntohl(bhssc->bhssc_expected_data_transfer_length);
2612	if (io->scsiio.kern_rel_offset + io->scsiio.kern_data_len >
2613	    expected_len) {
2614		io->scsiio.io_hdr.port_status = 43;
2615		io->scsiio.be_move_done(io);
2616		return;
2617	}
2618
2619	target_transfer_tag =
2620	    atomic_fetchadd_32(&cs->cs_target_transfer_tag, 1);
2621
2622#if 0
2623	CFISCSI_SESSION_DEBUG(cs, "expecting Data-Out with initiator "
2624	    "task tag 0x%x, target transfer tag 0x%x",
2625	    bhssc->bhssc_initiator_task_tag, target_transfer_tag);
2626#endif
2627	cdw = uma_zalloc(cfiscsi_data_wait_zone, M_NOWAIT | M_ZERO);
2628	if (cdw == NULL) {
2629		CFISCSI_SESSION_WARN(cs, "failed to "
2630		    "allocate memory; dropping connection");
2631		ctl_set_busy(&io->scsiio);
2632		io->scsiio.be_move_done(io);
2633		cfiscsi_session_terminate(cs);
2634		return;
2635	}
2636	cdw->cdw_ctl_io = io;
2637	cdw->cdw_target_transfer_tag = target_transfer_tag;
2638	cdw->cdw_initiator_task_tag = bhssc->bhssc_initiator_task_tag;
2639	cdw->cdw_r2t_end = io->scsiio.kern_data_len;
2640
2641	/* Set initial data pointer for the CDW respecting ext_data_filled. */
2642	if (io->scsiio.kern_sg_entries > 0) {
2643		ctl_sglist = (struct ctl_sg_entry *)io->scsiio.kern_data_ptr;
2644	} else {
2645		ctl_sglist = &ctl_sg_entry;
2646		ctl_sglist->addr = io->scsiio.kern_data_ptr;
2647		ctl_sglist->len = io->scsiio.kern_data_len;
2648	}
2649	cdw->cdw_sg_index = 0;
2650	cdw->cdw_sg_addr = ctl_sglist[cdw->cdw_sg_index].addr;
2651	cdw->cdw_sg_len = ctl_sglist[cdw->cdw_sg_index].len;
2652	r2t_off = io->scsiio.ext_data_filled;
2653	while (r2t_off > 0) {
2654		if (r2t_off >= cdw->cdw_sg_len) {
2655			r2t_off -= cdw->cdw_sg_len;
2656			cdw->cdw_sg_index++;
2657			cdw->cdw_sg_addr = ctl_sglist[cdw->cdw_sg_index].addr;
2658			cdw->cdw_sg_len = ctl_sglist[cdw->cdw_sg_index].len;
2659			continue;
2660		}
2661		cdw->cdw_sg_addr += r2t_off;
2662		cdw->cdw_sg_len -= r2t_off;
2663		r2t_off = 0;
2664	}
2665
2666	if (cs->cs_immediate_data &&
2667	    io->scsiio.kern_rel_offset + io->scsiio.ext_data_filled <
2668	    icl_pdu_data_segment_length(request)) {
2669		done = cfiscsi_handle_data_segment(request, cdw);
2670		if (done) {
2671			uma_zfree(cfiscsi_data_wait_zone, cdw);
2672			io->scsiio.be_move_done(io);
2673			return;
2674		}
2675	}
2676
2677	r2t_off = io->scsiio.kern_rel_offset + io->scsiio.ext_data_filled;
2678	r2t_len = MIN(io->scsiio.kern_data_len - io->scsiio.ext_data_filled,
2679	    cs->cs_max_burst_length);
2680	cdw->cdw_r2t_end = io->scsiio.ext_data_filled + r2t_len;
2681
2682	CFISCSI_SESSION_LOCK(cs);
2683	TAILQ_INSERT_TAIL(&cs->cs_waiting_for_data_out, cdw, cdw_next);
2684	CFISCSI_SESSION_UNLOCK(cs);
2685
2686	/*
2687	 * XXX: We should limit the number of outstanding R2T PDUs
2688	 * 	per task to MaxOutstandingR2T.
2689	 */
2690	response = cfiscsi_pdu_new_response(request, M_NOWAIT);
2691	if (response == NULL) {
2692		CFISCSI_SESSION_WARN(cs, "failed to "
2693		    "allocate memory; dropping connection");
2694		ctl_set_busy(&io->scsiio);
2695		io->scsiio.be_move_done(io);
2696		cfiscsi_session_terminate(cs);
2697		return;
2698	}
2699	bhsr2t = (struct iscsi_bhs_r2t *)response->ip_bhs;
2700	bhsr2t->bhsr2t_opcode = ISCSI_BHS_OPCODE_R2T;
2701	bhsr2t->bhsr2t_flags = 0x80;
2702	bhsr2t->bhsr2t_lun = bhssc->bhssc_lun;
2703	bhsr2t->bhsr2t_initiator_task_tag = bhssc->bhssc_initiator_task_tag;
2704	bhsr2t->bhsr2t_target_transfer_tag = target_transfer_tag;
2705	/*
2706	 * XXX: Here we assume that cfiscsi_datamove() won't ever
2707	 *	be running concurrently on several CPUs for a given
2708	 *	command.
2709	 */
2710	bhsr2t->bhsr2t_r2tsn = htonl(PDU_R2TSN(request));
2711	PDU_R2TSN(request)++;
2712	/*
2713	 * This is the offset within the current SCSI command;
2714	 * i.e. for the first call of datamove(), it will be 0,
2715	 * and for subsequent ones it will be the sum of lengths
2716	 * of previous ones.
2717	 *
2718	 * The ext_data_filled is to account for unsolicited
2719	 * (immediate) data that might have already arrived.
2720	 */
2721	bhsr2t->bhsr2t_buffer_offset = htonl(r2t_off);
2722	/*
2723	 * This is the total length (sum of S/G lengths) this call
2724	 * to cfiscsi_datamove() is supposed to handle, limited by
2725	 * MaxBurstLength.
2726	 */
2727	bhsr2t->bhsr2t_desired_data_transfer_length = htonl(r2t_len);
2728	cfiscsi_pdu_queue(response);
2729}
2730
2731static void
2732cfiscsi_datamove(union ctl_io *io)
2733{
2734
2735	if ((io->io_hdr.flags & CTL_FLAG_DATA_MASK) == CTL_FLAG_DATA_IN)
2736		cfiscsi_datamove_in(io);
2737	else {
2738		/* We hadn't received anything during this datamove yet. */
2739		io->scsiio.ext_data_filled = 0;
2740		cfiscsi_datamove_out(io);
2741	}
2742}
2743
2744static void
2745cfiscsi_scsi_command_done(union ctl_io *io)
2746{
2747	struct icl_pdu *request, *response;
2748	struct iscsi_bhs_scsi_command *bhssc;
2749	struct iscsi_bhs_scsi_response *bhssr;
2750#ifdef DIAGNOSTIC
2751	struct cfiscsi_data_wait *cdw;
2752#endif
2753	struct cfiscsi_session *cs;
2754	uint16_t sense_length;
2755
2756	request = io->io_hdr.ctl_private[CTL_PRIV_FRONTEND].ptr;
2757	cs = PDU_SESSION(request);
2758	bhssc = (struct iscsi_bhs_scsi_command *)request->ip_bhs;
2759	KASSERT((bhssc->bhssc_opcode & ~ISCSI_BHS_OPCODE_IMMEDIATE) ==
2760	    ISCSI_BHS_OPCODE_SCSI_COMMAND,
2761	    ("replying to wrong opcode 0x%x", bhssc->bhssc_opcode));
2762
2763	//CFISCSI_SESSION_DEBUG(cs, "initiator task tag 0x%x",
2764	//    bhssc->bhssc_initiator_task_tag);
2765
2766#ifdef DIAGNOSTIC
2767	CFISCSI_SESSION_LOCK(cs);
2768	TAILQ_FOREACH(cdw, &cs->cs_waiting_for_data_out, cdw_next)
2769		KASSERT(bhssc->bhssc_initiator_task_tag !=
2770		    cdw->cdw_initiator_task_tag, ("dangling cdw"));
2771	CFISCSI_SESSION_UNLOCK(cs);
2772#endif
2773
2774	/*
2775	 * Do not return status for aborted commands.
2776	 * There are exceptions, but none supported by CTL yet.
2777	 */
2778	if ((io->io_hdr.flags & CTL_FLAG_ABORT) &&
2779	    (io->io_hdr.flags & CTL_FLAG_ABORT_STATUS) == 0) {
2780		ctl_free_io(io);
2781		icl_pdu_free(request);
2782		return;
2783	}
2784
2785	response = cfiscsi_pdu_new_response(request, M_WAITOK);
2786	bhssr = (struct iscsi_bhs_scsi_response *)response->ip_bhs;
2787	bhssr->bhssr_opcode = ISCSI_BHS_OPCODE_SCSI_RESPONSE;
2788	bhssr->bhssr_flags = 0x80;
2789	/*
2790	 * XXX: We don't deal with bidirectional under/overflows;
2791	 *	does anything actually support those?
2792	 */
2793	if (PDU_TOTAL_TRANSFER_LEN(request) <
2794	    ntohl(bhssc->bhssc_expected_data_transfer_length)) {
2795		bhssr->bhssr_flags |= BHSSR_FLAGS_RESIDUAL_UNDERFLOW;
2796		bhssr->bhssr_residual_count =
2797		    htonl(ntohl(bhssc->bhssc_expected_data_transfer_length) -
2798		    PDU_TOTAL_TRANSFER_LEN(request));
2799		//CFISCSI_SESSION_DEBUG(cs, "underflow; residual count %d",
2800		//    ntohl(bhssr->bhssr_residual_count));
2801	} else if (PDU_TOTAL_TRANSFER_LEN(request) >
2802	    ntohl(bhssc->bhssc_expected_data_transfer_length)) {
2803		bhssr->bhssr_flags |= BHSSR_FLAGS_RESIDUAL_OVERFLOW;
2804		bhssr->bhssr_residual_count =
2805		    htonl(PDU_TOTAL_TRANSFER_LEN(request) -
2806		    ntohl(bhssc->bhssc_expected_data_transfer_length));
2807		//CFISCSI_SESSION_DEBUG(cs, "overflow; residual count %d",
2808		//    ntohl(bhssr->bhssr_residual_count));
2809	}
2810	bhssr->bhssr_response = BHSSR_RESPONSE_COMMAND_COMPLETED;
2811	bhssr->bhssr_status = io->scsiio.scsi_status;
2812	bhssr->bhssr_initiator_task_tag = bhssc->bhssc_initiator_task_tag;
2813	bhssr->bhssr_expdatasn = htonl(PDU_EXPDATASN(request));
2814
2815	if (io->scsiio.sense_len > 0) {
2816#if 0
2817		CFISCSI_SESSION_DEBUG(cs, "returning %d bytes of sense data",
2818		    io->scsiio.sense_len);
2819#endif
2820		sense_length = htons(io->scsiio.sense_len);
2821		icl_pdu_append_data(response,
2822		    &sense_length, sizeof(sense_length), M_WAITOK);
2823		icl_pdu_append_data(response,
2824		    &io->scsiio.sense_data, io->scsiio.sense_len, M_WAITOK);
2825	}
2826
2827	ctl_free_io(io);
2828	icl_pdu_free(request);
2829	cfiscsi_pdu_queue(response);
2830}
2831
2832static void
2833cfiscsi_task_management_done(union ctl_io *io)
2834{
2835	struct icl_pdu *request, *response;
2836	struct iscsi_bhs_task_management_request *bhstmr;
2837	struct iscsi_bhs_task_management_response *bhstmr2;
2838	struct cfiscsi_data_wait *cdw, *tmpcdw;
2839	struct cfiscsi_session *cs;
2840
2841	request = io->io_hdr.ctl_private[CTL_PRIV_FRONTEND].ptr;
2842	cs = PDU_SESSION(request);
2843	bhstmr = (struct iscsi_bhs_task_management_request *)request->ip_bhs;
2844	KASSERT((bhstmr->bhstmr_opcode & ~ISCSI_BHS_OPCODE_IMMEDIATE) ==
2845	    ISCSI_BHS_OPCODE_TASK_REQUEST,
2846	    ("replying to wrong opcode 0x%x", bhstmr->bhstmr_opcode));
2847
2848#if 0
2849	CFISCSI_SESSION_DEBUG(cs, "initiator task tag 0x%x; referenced task tag 0x%x",
2850	    bhstmr->bhstmr_initiator_task_tag,
2851	    bhstmr->bhstmr_referenced_task_tag);
2852#endif
2853
2854	if ((bhstmr->bhstmr_function & ~0x80) ==
2855	    BHSTMR_FUNCTION_ABORT_TASK) {
2856		/*
2857		 * Make sure we no longer wait for Data-Out for this command.
2858		 */
2859		CFISCSI_SESSION_LOCK(cs);
2860		TAILQ_FOREACH_SAFE(cdw,
2861		    &cs->cs_waiting_for_data_out, cdw_next, tmpcdw) {
2862			if (bhstmr->bhstmr_referenced_task_tag !=
2863			    cdw->cdw_initiator_task_tag)
2864				continue;
2865
2866#if 0
2867			CFISCSI_SESSION_DEBUG(cs, "removing csw for initiator task "
2868			    "tag 0x%x", bhstmr->bhstmr_initiator_task_tag);
2869#endif
2870			TAILQ_REMOVE(&cs->cs_waiting_for_data_out,
2871			    cdw, cdw_next);
2872			cdw->cdw_ctl_io->scsiio.be_move_done(cdw->cdw_ctl_io);
2873			uma_zfree(cfiscsi_data_wait_zone, cdw);
2874		}
2875		CFISCSI_SESSION_UNLOCK(cs);
2876	}
2877
2878	response = cfiscsi_pdu_new_response(request, M_WAITOK);
2879	bhstmr2 = (struct iscsi_bhs_task_management_response *)
2880	    response->ip_bhs;
2881	bhstmr2->bhstmr_opcode = ISCSI_BHS_OPCODE_TASK_RESPONSE;
2882	bhstmr2->bhstmr_flags = 0x80;
2883	if (io->io_hdr.status == CTL_SUCCESS) {
2884		bhstmr2->bhstmr_response = BHSTMR_RESPONSE_FUNCTION_COMPLETE;
2885	} else {
2886		/*
2887		 * XXX: How to figure out what exactly went wrong?  iSCSI spec
2888		 * 	expects us to provide detailed error, e.g. "Task does
2889		 * 	not exist" or "LUN does not exist".
2890		 */
2891		CFISCSI_SESSION_DEBUG(cs, "BHSTMR_RESPONSE_FUNCTION_NOT_SUPPORTED");
2892		bhstmr2->bhstmr_response =
2893		    BHSTMR_RESPONSE_FUNCTION_NOT_SUPPORTED;
2894	}
2895	bhstmr2->bhstmr_initiator_task_tag = bhstmr->bhstmr_initiator_task_tag;
2896
2897	ctl_free_io(io);
2898	icl_pdu_free(request);
2899	cfiscsi_pdu_queue(response);
2900}
2901
2902static void
2903cfiscsi_done(union ctl_io *io)
2904{
2905	struct icl_pdu *request;
2906	struct cfiscsi_session *cs;
2907
2908	KASSERT(((io->io_hdr.status & CTL_STATUS_MASK) != CTL_STATUS_NONE),
2909		("invalid CTL status %#x", io->io_hdr.status));
2910
2911	if (io->io_hdr.io_type == CTL_IO_TASK &&
2912	    io->taskio.task_action == CTL_TASK_I_T_NEXUS_RESET) {
2913		/*
2914		 * Implicit task termination has just completed; nothing to do.
2915		 */
2916		cs = io->io_hdr.ctl_private[CTL_PRIV_FRONTEND].ptr;
2917		cs->cs_tasks_aborted = true;
2918		refcount_release(&cs->cs_outstanding_ctl_pdus);
2919		wakeup(__DEVOLATILE(void *, &cs->cs_outstanding_ctl_pdus));
2920		ctl_free_io(io);
2921		return;
2922	}
2923
2924	request = io->io_hdr.ctl_private[CTL_PRIV_FRONTEND].ptr;
2925	cs = PDU_SESSION(request);
2926	refcount_release(&cs->cs_outstanding_ctl_pdus);
2927
2928	switch (request->ip_bhs->bhs_opcode & ~ISCSI_BHS_OPCODE_IMMEDIATE) {
2929	case ISCSI_BHS_OPCODE_SCSI_COMMAND:
2930		cfiscsi_scsi_command_done(io);
2931		break;
2932	case ISCSI_BHS_OPCODE_TASK_REQUEST:
2933		cfiscsi_task_management_done(io);
2934		break;
2935	default:
2936		panic("cfiscsi_done called with wrong opcode 0x%x",
2937		    request->ip_bhs->bhs_opcode);
2938	}
2939}
2940