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