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