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