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