xref: /freebsd/sys/dev/iscsi/icl.c (revision 95d45410b5100e07f6f98450bcd841a8945d4726)
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$
30  */
31 
32 /*
33  * iSCSI Common Layer.  It's used by both the initiator and target to send
34  * and receive iSCSI PDUs.
35  */
36 
37 #include <sys/param.h>
38 #include <sys/capsicum.h>
39 #include <sys/condvar.h>
40 #include <sys/conf.h>
41 #include <sys/file.h>
42 #include <sys/kernel.h>
43 #include <sys/kthread.h>
44 #include <sys/lock.h>
45 #include <sys/mbuf.h>
46 #include <sys/mutex.h>
47 #include <sys/module.h>
48 #include <sys/protosw.h>
49 #include <sys/socket.h>
50 #include <sys/socketvar.h>
51 #include <sys/sysctl.h>
52 #include <sys/systm.h>
53 #include <sys/sx.h>
54 #include <sys/uio.h>
55 #include <vm/uma.h>
56 #include <netinet/in.h>
57 #include <netinet/tcp.h>
58 
59 #include "icl.h"
60 #include "iscsi_proto.h"
61 
62 SYSCTL_NODE(_kern, OID_AUTO, icl, CTLFLAG_RD, 0, "iSCSI Common Layer");
63 static int debug = 1;
64 SYSCTL_INT(_kern_icl, OID_AUTO, debug, CTLFLAG_RWTUN,
65     &debug, 0, "Enable debug messages");
66 static int coalesce = 1;
67 SYSCTL_INT(_kern_icl, OID_AUTO, coalesce, CTLFLAG_RWTUN,
68     &coalesce, 0, "Try to coalesce PDUs before sending");
69 static int partial_receive_len = 128 * 1024;
70 SYSCTL_INT(_kern_icl, OID_AUTO, partial_receive_len, CTLFLAG_RWTUN,
71     &partial_receive_len, 0, "Minimum read size for partially received "
72     "data segment");
73 static int sendspace = 1048576;
74 SYSCTL_INT(_kern_icl, OID_AUTO, sendspace, CTLFLAG_RWTUN,
75     &sendspace, 0, "Default send socket buffer size");
76 static int recvspace = 1048576;
77 SYSCTL_INT(_kern_icl, OID_AUTO, recvspace, CTLFLAG_RWTUN,
78     &recvspace, 0, "Default receive socket buffer size");
79 
80 static uma_zone_t icl_conn_zone;
81 static uma_zone_t icl_pdu_zone;
82 
83 static volatile u_int	icl_ncons;
84 
85 #define	ICL_DEBUG(X, ...)						\
86 	do {								\
87 		if (debug > 1)						\
88 			printf("%s: " X "\n", __func__, ## __VA_ARGS__);\
89 	} while (0)
90 
91 #define	ICL_WARN(X, ...)						\
92 	do {								\
93 		if (debug > 0) {					\
94 			printf("WARNING: %s: " X "\n",			\
95 			    __func__, ## __VA_ARGS__);			\
96 		}							\
97 	} while (0)
98 
99 #define ICL_CONN_LOCK(X)		mtx_lock(X->ic_lock)
100 #define ICL_CONN_UNLOCK(X)		mtx_unlock(X->ic_lock)
101 #define ICL_CONN_LOCK_ASSERT(X)		mtx_assert(X->ic_lock, MA_OWNED)
102 #define ICL_CONN_LOCK_ASSERT_NOT(X)	mtx_assert(X->ic_lock, MA_NOTOWNED)
103 
104 STAILQ_HEAD(icl_pdu_stailq, icl_pdu);
105 
106 static void
107 icl_conn_fail(struct icl_conn *ic)
108 {
109 	if (ic->ic_socket == NULL)
110 		return;
111 
112 	/*
113 	 * XXX
114 	 */
115 	ic->ic_socket->so_error = EDOOFUS;
116 	(ic->ic_error)(ic);
117 }
118 
119 static struct mbuf *
120 icl_conn_receive(struct icl_conn *ic, size_t len)
121 {
122 	struct uio uio;
123 	struct socket *so;
124 	struct mbuf *m;
125 	int error, flags;
126 
127 	so = ic->ic_socket;
128 
129 	memset(&uio, 0, sizeof(uio));
130 	uio.uio_resid = len;
131 
132 	flags = MSG_DONTWAIT;
133 	error = soreceive(so, NULL, &uio, &m, NULL, &flags);
134 	if (error != 0) {
135 		ICL_DEBUG("soreceive error %d", error);
136 		return (NULL);
137 	}
138 	if (uio.uio_resid != 0) {
139 		m_freem(m);
140 		ICL_DEBUG("short read");
141 		return (NULL);
142 	}
143 
144 	return (m);
145 }
146 
147 static struct icl_pdu *
148 icl_pdu_new(struct icl_conn *ic, int flags)
149 {
150 	struct icl_pdu *ip;
151 
152 #ifdef DIAGNOSTIC
153 	refcount_acquire(&ic->ic_outstanding_pdus);
154 #endif
155 	ip = uma_zalloc(icl_pdu_zone, flags | M_ZERO);
156 	if (ip == NULL) {
157 		ICL_WARN("failed to allocate %zd bytes", sizeof(*ip));
158 #ifdef DIAGNOSTIC
159 		refcount_release(&ic->ic_outstanding_pdus);
160 #endif
161 		return (NULL);
162 	}
163 
164 	ip->ip_conn = ic;
165 
166 	return (ip);
167 }
168 
169 void
170 icl_pdu_free(struct icl_pdu *ip)
171 {
172 	struct icl_conn *ic;
173 
174 	ic = ip->ip_conn;
175 
176 	m_freem(ip->ip_bhs_mbuf);
177 	m_freem(ip->ip_ahs_mbuf);
178 	m_freem(ip->ip_data_mbuf);
179 	uma_zfree(icl_pdu_zone, ip);
180 #ifdef DIAGNOSTIC
181 	refcount_release(&ic->ic_outstanding_pdus);
182 #endif
183 }
184 
185 /*
186  * Allocate icl_pdu with empty BHS to fill up by the caller.
187  */
188 struct icl_pdu *
189 icl_pdu_new_bhs(struct icl_conn *ic, int flags)
190 {
191 	struct icl_pdu *ip;
192 
193 	ip = icl_pdu_new(ic, flags);
194 	if (ip == NULL)
195 		return (NULL);
196 
197 	ip->ip_bhs_mbuf = m_getm2(NULL, sizeof(struct iscsi_bhs),
198 	    flags, MT_DATA, M_PKTHDR);
199 	if (ip->ip_bhs_mbuf == NULL) {
200 		ICL_WARN("failed to allocate %zd bytes", sizeof(*ip));
201 		icl_pdu_free(ip);
202 		return (NULL);
203 	}
204 	ip->ip_bhs = mtod(ip->ip_bhs_mbuf, struct iscsi_bhs *);
205 	memset(ip->ip_bhs, 0, sizeof(struct iscsi_bhs));
206 	ip->ip_bhs_mbuf->m_len = sizeof(struct iscsi_bhs);
207 
208 	return (ip);
209 }
210 
211 static int
212 icl_pdu_ahs_length(const struct icl_pdu *request)
213 {
214 
215 	return (request->ip_bhs->bhs_total_ahs_len * 4);
216 }
217 
218 size_t
219 icl_pdu_data_segment_length(const struct icl_pdu *request)
220 {
221 	uint32_t len = 0;
222 
223 	len += request->ip_bhs->bhs_data_segment_len[0];
224 	len <<= 8;
225 	len += request->ip_bhs->bhs_data_segment_len[1];
226 	len <<= 8;
227 	len += request->ip_bhs->bhs_data_segment_len[2];
228 
229 	return (len);
230 }
231 
232 static void
233 icl_pdu_set_data_segment_length(struct icl_pdu *response, uint32_t len)
234 {
235 
236 	response->ip_bhs->bhs_data_segment_len[2] = len;
237 	response->ip_bhs->bhs_data_segment_len[1] = len >> 8;
238 	response->ip_bhs->bhs_data_segment_len[0] = len >> 16;
239 }
240 
241 static size_t
242 icl_pdu_padding(const struct icl_pdu *ip)
243 {
244 
245 	if ((ip->ip_data_len % 4) != 0)
246 		return (4 - (ip->ip_data_len % 4));
247 
248 	return (0);
249 }
250 
251 static size_t
252 icl_pdu_size(const struct icl_pdu *response)
253 {
254 	size_t len;
255 
256 	KASSERT(response->ip_ahs_len == 0, ("responding with AHS"));
257 
258 	len = sizeof(struct iscsi_bhs) + response->ip_data_len +
259 	    icl_pdu_padding(response);
260 	if (response->ip_conn->ic_header_crc32c)
261 		len += ISCSI_HEADER_DIGEST_SIZE;
262 	if (response->ip_data_len != 0 && response->ip_conn->ic_data_crc32c)
263 		len += ISCSI_DATA_DIGEST_SIZE;
264 
265 	return (len);
266 }
267 
268 static int
269 icl_pdu_receive_bhs(struct icl_pdu *request, size_t *availablep)
270 {
271 	struct mbuf *m;
272 
273 	m = icl_conn_receive(request->ip_conn, sizeof(struct iscsi_bhs));
274 	if (m == NULL) {
275 		ICL_DEBUG("failed to receive BHS");
276 		return (-1);
277 	}
278 
279 	request->ip_bhs_mbuf = m_pullup(m, sizeof(struct iscsi_bhs));
280 	if (request->ip_bhs_mbuf == NULL) {
281 		ICL_WARN("m_pullup failed");
282 		return (-1);
283 	}
284 	request->ip_bhs = mtod(request->ip_bhs_mbuf, struct iscsi_bhs *);
285 
286 	/*
287 	 * XXX: For architectures with strict alignment requirements
288 	 * 	we may need to allocate ip_bhs and copy the data into it.
289 	 * 	For some reason, though, not doing this doesn't seem
290 	 * 	to cause problems; tested on sparc64.
291 	 */
292 
293 	*availablep -= sizeof(struct iscsi_bhs);
294 	return (0);
295 }
296 
297 static int
298 icl_pdu_receive_ahs(struct icl_pdu *request, size_t *availablep)
299 {
300 
301 	request->ip_ahs_len = icl_pdu_ahs_length(request);
302 	if (request->ip_ahs_len == 0)
303 		return (0);
304 
305 	request->ip_ahs_mbuf = icl_conn_receive(request->ip_conn,
306 	    request->ip_ahs_len);
307 	if (request->ip_ahs_mbuf == NULL) {
308 		ICL_DEBUG("failed to receive AHS");
309 		return (-1);
310 	}
311 
312 	*availablep -= request->ip_ahs_len;
313 	return (0);
314 }
315 
316 static uint32_t
317 icl_mbuf_to_crc32c(const struct mbuf *m0)
318 {
319 	uint32_t digest = 0xffffffff;
320 	const struct mbuf *m;
321 
322 	for (m = m0; m != NULL; m = m->m_next)
323 		digest = calculate_crc32c(digest,
324 		    mtod(m, const void *), m->m_len);
325 
326 	digest = digest ^ 0xffffffff;
327 
328 	return (digest);
329 }
330 
331 static int
332 icl_pdu_check_header_digest(struct icl_pdu *request, size_t *availablep)
333 {
334 	struct mbuf *m;
335 	uint32_t received_digest, valid_digest;
336 
337 	if (request->ip_conn->ic_header_crc32c == false)
338 		return (0);
339 
340 	m = icl_conn_receive(request->ip_conn, ISCSI_HEADER_DIGEST_SIZE);
341 	if (m == NULL) {
342 		ICL_DEBUG("failed to receive header digest");
343 		return (-1);
344 	}
345 
346 	CTASSERT(sizeof(received_digest) == ISCSI_HEADER_DIGEST_SIZE);
347 	m_copydata(m, 0, ISCSI_HEADER_DIGEST_SIZE, (void *)&received_digest);
348 	m_freem(m);
349 
350 	*availablep -= ISCSI_HEADER_DIGEST_SIZE;
351 
352 	/*
353 	 * XXX: Handle AHS.
354 	 */
355 	valid_digest = icl_mbuf_to_crc32c(request->ip_bhs_mbuf);
356 	if (received_digest != valid_digest) {
357 		ICL_WARN("header digest check failed; got 0x%x, "
358 		    "should be 0x%x", received_digest, valid_digest);
359 		return (-1);
360 	}
361 
362 	return (0);
363 }
364 
365 /*
366  * Return the number of bytes that should be waiting in the receive socket
367  * before icl_pdu_receive_data_segment() gets called.
368  */
369 static size_t
370 icl_pdu_data_segment_receive_len(const struct icl_pdu *request)
371 {
372 	size_t len;
373 
374 	len = icl_pdu_data_segment_length(request);
375 	if (len == 0)
376 		return (0);
377 
378 	/*
379 	 * Account for the parts of data segment already read from
380 	 * the socket buffer.
381 	 */
382 	KASSERT(len > request->ip_data_len, ("len <= request->ip_data_len"));
383 	len -= request->ip_data_len;
384 
385 	/*
386 	 * Don't always wait for the full data segment to be delivered
387 	 * to the socket; this might badly affect performance due to
388 	 * TCP window scaling.
389 	 */
390 	if (len > partial_receive_len) {
391 #if 0
392 		ICL_DEBUG("need %zd bytes of data, limiting to %zd",
393 		    len, partial_receive_len));
394 #endif
395 		len = partial_receive_len;
396 
397 		return (len);
398 	}
399 
400 	/*
401 	 * Account for padding.  Note that due to the way code is written,
402 	 * the icl_pdu_receive_data_segment() must always receive padding
403 	 * along with the last part of data segment, because it would be
404 	 * impossible to tell whether we've already received the full data
405 	 * segment including padding, or without it.
406 	 */
407 	if ((len % 4) != 0)
408 		len += 4 - (len % 4);
409 
410 #if 0
411 	ICL_DEBUG("need %zd bytes of data", len));
412 #endif
413 
414 	return (len);
415 }
416 
417 static int
418 icl_pdu_receive_data_segment(struct icl_pdu *request,
419     size_t *availablep, bool *more_neededp)
420 {
421 	struct icl_conn *ic;
422 	size_t len, padding = 0;
423 	struct mbuf *m;
424 
425 	ic = request->ip_conn;
426 
427 	*more_neededp = false;
428 	ic->ic_receive_len = 0;
429 
430 	len = icl_pdu_data_segment_length(request);
431 	if (len == 0)
432 		return (0);
433 
434 	if ((len % 4) != 0)
435 		padding = 4 - (len % 4);
436 
437 	/*
438 	 * Account for already received parts of data segment.
439 	 */
440 	KASSERT(len > request->ip_data_len, ("len <= request->ip_data_len"));
441 	len -= request->ip_data_len;
442 
443 	if (len + padding > *availablep) {
444 		/*
445 		 * Not enough data in the socket buffer.  Receive as much
446 		 * as we can.  Don't receive padding, since, obviously, it's
447 		 * not the end of data segment yet.
448 		 */
449 #if 0
450 		ICL_DEBUG("limited from %zd to %zd",
451 		    len + padding, *availablep - padding));
452 #endif
453 		len = *availablep - padding;
454 		*more_neededp = true;
455 		padding = 0;
456 	}
457 
458 	/*
459 	 * Must not try to receive padding without at least one byte
460 	 * of actual data segment.
461 	 */
462 	if (len > 0) {
463 		m = icl_conn_receive(request->ip_conn, len + padding);
464 		if (m == NULL) {
465 			ICL_DEBUG("failed to receive data segment");
466 			return (-1);
467 		}
468 
469 		if (request->ip_data_mbuf == NULL)
470 			request->ip_data_mbuf = m;
471 		else
472 			m_cat(request->ip_data_mbuf, m);
473 
474 		request->ip_data_len += len;
475 		*availablep -= len + padding;
476 	} else
477 		ICL_DEBUG("len 0");
478 
479 	if (*more_neededp)
480 		ic->ic_receive_len =
481 		    icl_pdu_data_segment_receive_len(request);
482 
483 	return (0);
484 }
485 
486 static int
487 icl_pdu_check_data_digest(struct icl_pdu *request, size_t *availablep)
488 {
489 	struct mbuf *m;
490 	uint32_t received_digest, valid_digest;
491 
492 	if (request->ip_conn->ic_data_crc32c == false)
493 		return (0);
494 
495 	if (request->ip_data_len == 0)
496 		return (0);
497 
498 	m = icl_conn_receive(request->ip_conn, ISCSI_DATA_DIGEST_SIZE);
499 	if (m == NULL) {
500 		ICL_DEBUG("failed to receive data digest");
501 		return (-1);
502 	}
503 
504 	CTASSERT(sizeof(received_digest) == ISCSI_DATA_DIGEST_SIZE);
505 	m_copydata(m, 0, ISCSI_DATA_DIGEST_SIZE, (void *)&received_digest);
506 	m_freem(m);
507 
508 	*availablep -= ISCSI_DATA_DIGEST_SIZE;
509 
510 	/*
511 	 * Note that ip_data_mbuf also contains padding; since digest
512 	 * calculation is supposed to include that, we iterate over
513 	 * the entire ip_data_mbuf chain, not just ip_data_len bytes of it.
514 	 */
515 	valid_digest = icl_mbuf_to_crc32c(request->ip_data_mbuf);
516 	if (received_digest != valid_digest) {
517 		ICL_WARN("data digest check failed; got 0x%x, "
518 		    "should be 0x%x", received_digest, valid_digest);
519 		return (-1);
520 	}
521 
522 	return (0);
523 }
524 
525 /*
526  * Somewhat contrary to the name, this attempts to receive only one
527  * "part" of PDU at a time; call it repeatedly until it returns non-NULL.
528  */
529 static struct icl_pdu *
530 icl_conn_receive_pdu(struct icl_conn *ic, size_t *availablep)
531 {
532 	struct icl_pdu *request;
533 	struct socket *so;
534 	size_t len;
535 	int error;
536 	bool more_needed;
537 
538 	so = ic->ic_socket;
539 
540 	if (ic->ic_receive_state == ICL_CONN_STATE_BHS) {
541 		KASSERT(ic->ic_receive_pdu == NULL,
542 		    ("ic->ic_receive_pdu != NULL"));
543 		request = icl_pdu_new(ic, M_NOWAIT);
544 		if (request == NULL) {
545 			ICL_DEBUG("failed to allocate PDU; "
546 			    "dropping connection");
547 			icl_conn_fail(ic);
548 			return (NULL);
549 		}
550 		ic->ic_receive_pdu = request;
551 	} else {
552 		KASSERT(ic->ic_receive_pdu != NULL,
553 		    ("ic->ic_receive_pdu == NULL"));
554 		request = ic->ic_receive_pdu;
555 	}
556 
557 	if (*availablep < ic->ic_receive_len) {
558 #if 0
559 		ICL_DEBUG("not enough data; need %zd, "
560 		    "have %zd", ic->ic_receive_len, *availablep);
561 #endif
562 		return (NULL);
563 	}
564 
565 	switch (ic->ic_receive_state) {
566 	case ICL_CONN_STATE_BHS:
567 		//ICL_DEBUG("receiving BHS");
568 		error = icl_pdu_receive_bhs(request, availablep);
569 		if (error != 0) {
570 			ICL_DEBUG("failed to receive BHS; "
571 			    "dropping connection");
572 			break;
573 		}
574 
575 		/*
576 		 * We don't enforce any limit for AHS length;
577 		 * its length is stored in 8 bit field.
578 		 */
579 
580 		len = icl_pdu_data_segment_length(request);
581 		if (len > ic->ic_max_data_segment_length) {
582 			ICL_WARN("received data segment "
583 			    "length %zd is larger than negotiated "
584 			    "MaxDataSegmentLength %zd; "
585 			    "dropping connection",
586 			    len, ic->ic_max_data_segment_length);
587 			error = EINVAL;
588 			break;
589 		}
590 
591 		ic->ic_receive_state = ICL_CONN_STATE_AHS;
592 		ic->ic_receive_len = icl_pdu_ahs_length(request);
593 		break;
594 
595 	case ICL_CONN_STATE_AHS:
596 		//ICL_DEBUG("receiving AHS");
597 		error = icl_pdu_receive_ahs(request, availablep);
598 		if (error != 0) {
599 			ICL_DEBUG("failed to receive AHS; "
600 			    "dropping connection");
601 			break;
602 		}
603 		ic->ic_receive_state = ICL_CONN_STATE_HEADER_DIGEST;
604 		if (ic->ic_header_crc32c == false)
605 			ic->ic_receive_len = 0;
606 		else
607 			ic->ic_receive_len = ISCSI_HEADER_DIGEST_SIZE;
608 		break;
609 
610 	case ICL_CONN_STATE_HEADER_DIGEST:
611 		//ICL_DEBUG("receiving header digest");
612 		error = icl_pdu_check_header_digest(request, availablep);
613 		if (error != 0) {
614 			ICL_DEBUG("header digest failed; "
615 			    "dropping connection");
616 			break;
617 		}
618 
619 		ic->ic_receive_state = ICL_CONN_STATE_DATA;
620 		ic->ic_receive_len =
621 		    icl_pdu_data_segment_receive_len(request);
622 		break;
623 
624 	case ICL_CONN_STATE_DATA:
625 		//ICL_DEBUG("receiving data segment");
626 		error = icl_pdu_receive_data_segment(request, availablep,
627 		    &more_needed);
628 		if (error != 0) {
629 			ICL_DEBUG("failed to receive data segment;"
630 			    "dropping connection");
631 			break;
632 		}
633 
634 		if (more_needed)
635 			break;
636 
637 		ic->ic_receive_state = ICL_CONN_STATE_DATA_DIGEST;
638 		if (request->ip_data_len == 0 || ic->ic_data_crc32c == false)
639 			ic->ic_receive_len = 0;
640 		else
641 			ic->ic_receive_len = ISCSI_DATA_DIGEST_SIZE;
642 		break;
643 
644 	case ICL_CONN_STATE_DATA_DIGEST:
645 		//ICL_DEBUG("receiving data digest");
646 		error = icl_pdu_check_data_digest(request, availablep);
647 		if (error != 0) {
648 			ICL_DEBUG("data digest failed; "
649 			    "dropping connection");
650 			break;
651 		}
652 
653 		/*
654 		 * We've received complete PDU; reset the receive state machine
655 		 * and return the PDU.
656 		 */
657 		ic->ic_receive_state = ICL_CONN_STATE_BHS;
658 		ic->ic_receive_len = sizeof(struct iscsi_bhs);
659 		ic->ic_receive_pdu = NULL;
660 		return (request);
661 
662 	default:
663 		panic("invalid ic_receive_state %d\n", ic->ic_receive_state);
664 	}
665 
666 	if (error != 0) {
667 		icl_pdu_free(request);
668 		icl_conn_fail(ic);
669 	}
670 
671 	return (NULL);
672 }
673 
674 static void
675 icl_conn_receive_pdus(struct icl_conn *ic, size_t available)
676 {
677 	struct icl_pdu *response;
678 	struct socket *so;
679 
680 	so = ic->ic_socket;
681 
682 	/*
683 	 * This can never happen; we're careful to only mess with ic->ic_socket
684 	 * pointer when the send/receive threads are not running.
685 	 */
686 	KASSERT(so != NULL, ("NULL socket"));
687 
688 	for (;;) {
689 		if (ic->ic_disconnecting)
690 			return;
691 
692 		if (so->so_error != 0) {
693 			ICL_DEBUG("connection error %d; "
694 			    "dropping connection", so->so_error);
695 			icl_conn_fail(ic);
696 			return;
697 		}
698 
699 		/*
700 		 * Loop until we have a complete PDU or there is not enough
701 		 * data in the socket buffer.
702 		 */
703 		if (available < ic->ic_receive_len) {
704 #if 0
705 			ICL_DEBUG("not enough data; have %zd, "
706 			    "need %zd", available,
707 			    ic->ic_receive_len);
708 #endif
709 			return;
710 		}
711 
712 		response = icl_conn_receive_pdu(ic, &available);
713 		if (response == NULL)
714 			continue;
715 
716 		if (response->ip_ahs_len > 0) {
717 			ICL_WARN("received PDU with unsupported "
718 			    "AHS; opcode 0x%x; dropping connection",
719 			    response->ip_bhs->bhs_opcode);
720 			icl_pdu_free(response);
721 			icl_conn_fail(ic);
722 			return;
723 		}
724 
725 		(ic->ic_receive)(response);
726 	}
727 }
728 
729 static void
730 icl_receive_thread(void *arg)
731 {
732 	struct icl_conn *ic;
733 	size_t available;
734 	struct socket *so;
735 
736 	ic = arg;
737 	so = ic->ic_socket;
738 
739 	ICL_CONN_LOCK(ic);
740 	ic->ic_receive_running = true;
741 	ICL_CONN_UNLOCK(ic);
742 
743 	for (;;) {
744 		if (ic->ic_disconnecting) {
745 			//ICL_DEBUG("terminating");
746 			break;
747 		}
748 
749 		/*
750 		 * Set the low watermark, to be checked by
751 		 * soreadable() in icl_soupcall_receive()
752 		 * to avoid unneccessary wakeups until there
753 		 * is enough data received to read the PDU.
754 		 */
755 		SOCKBUF_LOCK(&so->so_rcv);
756 		available = so->so_rcv.sb_cc;
757 		if (available < ic->ic_receive_len) {
758 			so->so_rcv.sb_lowat = ic->ic_receive_len;
759 			cv_wait(&ic->ic_receive_cv, &so->so_rcv.sb_mtx);
760 		} else
761 			so->so_rcv.sb_lowat = so->so_rcv.sb_hiwat + 1;
762 		SOCKBUF_UNLOCK(&so->so_rcv);
763 
764 		icl_conn_receive_pdus(ic, available);
765 	}
766 
767 	ICL_CONN_LOCK(ic);
768 	ic->ic_receive_running = false;
769 	ICL_CONN_UNLOCK(ic);
770 	kthread_exit();
771 }
772 
773 static int
774 icl_soupcall_receive(struct socket *so, void *arg, int waitflag)
775 {
776 	struct icl_conn *ic;
777 
778 	if (!soreadable(so))
779 		return (SU_OK);
780 
781 	ic = arg;
782 	cv_signal(&ic->ic_receive_cv);
783 	return (SU_OK);
784 }
785 
786 static int
787 icl_pdu_finalize(struct icl_pdu *request)
788 {
789 	size_t padding, pdu_len;
790 	uint32_t digest, zero = 0;
791 	int ok;
792 	struct icl_conn *ic;
793 
794 	ic = request->ip_conn;
795 
796 	icl_pdu_set_data_segment_length(request, request->ip_data_len);
797 
798 	pdu_len = icl_pdu_size(request);
799 
800 	if (ic->ic_header_crc32c) {
801 		digest = icl_mbuf_to_crc32c(request->ip_bhs_mbuf);
802 		ok = m_append(request->ip_bhs_mbuf, sizeof(digest),
803 		    (void *)&digest);
804 		if (ok != 1) {
805 			ICL_WARN("failed to append header digest");
806 			return (1);
807 		}
808 	}
809 
810 	if (request->ip_data_len != 0) {
811 		padding = icl_pdu_padding(request);
812 		if (padding > 0) {
813 			ok = m_append(request->ip_data_mbuf, padding,
814 			    (void *)&zero);
815 			if (ok != 1) {
816 				ICL_WARN("failed to append padding");
817 				return (1);
818 			}
819 		}
820 
821 		if (ic->ic_data_crc32c) {
822 			digest = icl_mbuf_to_crc32c(request->ip_data_mbuf);
823 
824 			ok = m_append(request->ip_data_mbuf, sizeof(digest),
825 			    (void *)&digest);
826 			if (ok != 1) {
827 				ICL_WARN("failed to append data digest");
828 				return (1);
829 			}
830 		}
831 
832 		m_cat(request->ip_bhs_mbuf, request->ip_data_mbuf);
833 		request->ip_data_mbuf = NULL;
834 	}
835 
836 	request->ip_bhs_mbuf->m_pkthdr.len = pdu_len;
837 
838 	return (0);
839 }
840 
841 static void
842 icl_conn_send_pdus(struct icl_conn *ic, struct icl_pdu_stailq *queue)
843 {
844 	struct icl_pdu *request, *request2;
845 	struct socket *so;
846 	size_t available, size, size2;
847 	int coalesced, error;
848 
849 	ICL_CONN_LOCK_ASSERT_NOT(ic);
850 
851 	so = ic->ic_socket;
852 
853 	SOCKBUF_LOCK(&so->so_snd);
854 	/*
855 	 * Check how much space do we have for transmit.  We can't just
856 	 * call sosend() and retry when we get EWOULDBLOCK or EMSGSIZE,
857 	 * as it always frees the mbuf chain passed to it, even in case
858 	 * of error.
859 	 */
860 	available = sbspace(&so->so_snd);
861 
862 	/*
863 	 * Notify the socket upcall that we don't need wakeups
864 	 * for the time being.
865 	 */
866 	so->so_snd.sb_lowat = so->so_snd.sb_hiwat + 1;
867 	SOCKBUF_UNLOCK(&so->so_snd);
868 
869 	while (!STAILQ_EMPTY(queue)) {
870 		if (ic->ic_disconnecting)
871 			return;
872 		request = STAILQ_FIRST(queue);
873 		size = icl_pdu_size(request);
874 		if (available < size) {
875 
876 			/*
877 			 * Set the low watermark, to be checked by
878 			 * sowriteable() in icl_soupcall_send()
879 			 * to avoid unneccessary wakeups until there
880 			 * is enough space for the PDU to fit.
881 			 */
882 			SOCKBUF_LOCK(&so->so_snd);
883 			available = sbspace(&so->so_snd);
884 			if (available < size) {
885 #if 1
886 				ICL_DEBUG("no space to send; "
887 				    "have %zd, need %zd",
888 				    available, size);
889 #endif
890 				so->so_snd.sb_lowat = size;
891 				SOCKBUF_UNLOCK(&so->so_snd);
892 				return;
893 			}
894 			SOCKBUF_UNLOCK(&so->so_snd);
895 		}
896 		STAILQ_REMOVE_HEAD(queue, ip_next);
897 		error = icl_pdu_finalize(request);
898 		if (error != 0) {
899 			ICL_DEBUG("failed to finalize PDU; "
900 			    "dropping connection");
901 			icl_conn_fail(ic);
902 			icl_pdu_free(request);
903 			return;
904 		}
905 		if (coalesce) {
906 			coalesced = 1;
907 			for (;;) {
908 				request2 = STAILQ_FIRST(queue);
909 				if (request2 == NULL)
910 					break;
911 				size2 = icl_pdu_size(request2);
912 				if (available < size + size2)
913 					break;
914 				STAILQ_REMOVE_HEAD(queue, ip_next);
915 				error = icl_pdu_finalize(request2);
916 				if (error != 0) {
917 					ICL_DEBUG("failed to finalize PDU; "
918 					    "dropping connection");
919 					icl_conn_fail(ic);
920 					icl_pdu_free(request);
921 					icl_pdu_free(request2);
922 					return;
923 				}
924 				m_cat(request->ip_bhs_mbuf, request2->ip_bhs_mbuf);
925 				request2->ip_bhs_mbuf = NULL;
926 				request->ip_bhs_mbuf->m_pkthdr.len += size2;
927 				size += size2;
928 				STAILQ_REMOVE_AFTER(queue, request, ip_next);
929 				icl_pdu_free(request2);
930 				coalesced++;
931 			}
932 #if 0
933 			if (coalesced > 1) {
934 				ICL_DEBUG("coalesced %d PDUs into %zd bytes",
935 				    coalesced, size);
936 			}
937 #endif
938 		}
939 		available -= size;
940 		error = sosend(so, NULL, NULL, request->ip_bhs_mbuf,
941 		    NULL, MSG_DONTWAIT, curthread);
942 		request->ip_bhs_mbuf = NULL; /* Sosend consumes the mbuf. */
943 		if (error != 0) {
944 			ICL_DEBUG("failed to send PDU, error %d; "
945 			    "dropping connection", error);
946 			icl_conn_fail(ic);
947 			icl_pdu_free(request);
948 			return;
949 		}
950 		icl_pdu_free(request);
951 	}
952 }
953 
954 static void
955 icl_send_thread(void *arg)
956 {
957 	struct icl_conn *ic;
958 	struct icl_pdu_stailq queue;
959 
960 	ic = arg;
961 
962 	STAILQ_INIT(&queue);
963 
964 	ICL_CONN_LOCK(ic);
965 	ic->ic_send_running = true;
966 
967 	for (;;) {
968 		if (ic->ic_disconnecting) {
969 			//ICL_DEBUG("terminating");
970 			break;
971 		}
972 
973 		for (;;) {
974 			/*
975 			 * If the local queue is empty, populate it from
976 			 * the main one.  This way the icl_conn_send_pdus()
977 			 * can go through all the queued PDUs without holding
978 			 * any locks.
979 			 */
980 			if (STAILQ_EMPTY(&queue))
981 				STAILQ_SWAP(&ic->ic_to_send, &queue, icl_pdu);
982 
983 			ic->ic_check_send_space = false;
984 			ICL_CONN_UNLOCK(ic);
985 			icl_conn_send_pdus(ic, &queue);
986 			ICL_CONN_LOCK(ic);
987 
988 			/*
989 			 * The icl_soupcall_send() was called since the last
990 			 * call to sbspace(); go around;
991 			 */
992 			if (ic->ic_check_send_space)
993 				continue;
994 
995 			/*
996 			 * Local queue is empty, but we still have PDUs
997 			 * in the main one; go around.
998 			 */
999 			if (STAILQ_EMPTY(&queue) &&
1000 			    !STAILQ_EMPTY(&ic->ic_to_send))
1001 				continue;
1002 
1003 			/*
1004 			 * There might be some stuff in the local queue,
1005 			 * which didn't get sent due to not having enough send
1006 			 * space.  Wait for socket upcall.
1007 			 */
1008 			break;
1009 		}
1010 
1011 		cv_wait(&ic->ic_send_cv, ic->ic_lock);
1012 	}
1013 
1014 	/*
1015 	 * We're exiting; move PDUs back to the main queue, so they can
1016 	 * get freed properly.  At this point ordering doesn't matter.
1017 	 */
1018 	STAILQ_CONCAT(&ic->ic_to_send, &queue);
1019 
1020 	ic->ic_send_running = false;
1021 	ICL_CONN_UNLOCK(ic);
1022 	kthread_exit();
1023 }
1024 
1025 static int
1026 icl_soupcall_send(struct socket *so, void *arg, int waitflag)
1027 {
1028 	struct icl_conn *ic;
1029 
1030 	if (!sowriteable(so))
1031 		return (SU_OK);
1032 
1033 	ic = arg;
1034 
1035 	ICL_CONN_LOCK(ic);
1036 	ic->ic_check_send_space = true;
1037 	ICL_CONN_UNLOCK(ic);
1038 
1039 	cv_signal(&ic->ic_send_cv);
1040 
1041 	return (SU_OK);
1042 }
1043 
1044 int
1045 icl_pdu_append_data(struct icl_pdu *request, const void *addr, size_t len,
1046     int flags)
1047 {
1048 	struct mbuf *mb, *newmb;
1049 	size_t copylen, off = 0;
1050 
1051 	KASSERT(len > 0, ("len == 0"));
1052 
1053 	newmb = m_getm2(NULL, len, flags, MT_DATA, M_PKTHDR);
1054 	if (newmb == NULL) {
1055 		ICL_WARN("failed to allocate mbuf for %zd bytes", len);
1056 		return (ENOMEM);
1057 	}
1058 
1059 	for (mb = newmb; mb != NULL; mb = mb->m_next) {
1060 		copylen = min(M_TRAILINGSPACE(mb), len - off);
1061 		memcpy(mtod(mb, char *), (const char *)addr + off, copylen);
1062 		mb->m_len = copylen;
1063 		off += copylen;
1064 	}
1065 	KASSERT(off == len, ("%s: off != len", __func__));
1066 
1067 	if (request->ip_data_mbuf == NULL) {
1068 		request->ip_data_mbuf = newmb;
1069 		request->ip_data_len = len;
1070 	} else {
1071 		m_cat(request->ip_data_mbuf, newmb);
1072 		request->ip_data_len += len;
1073 	}
1074 
1075 	return (0);
1076 }
1077 
1078 void
1079 icl_pdu_get_data(struct icl_pdu *ip, size_t off, void *addr, size_t len)
1080 {
1081 
1082 	m_copydata(ip->ip_data_mbuf, off, len, addr);
1083 }
1084 
1085 void
1086 icl_pdu_queue(struct icl_pdu *ip)
1087 {
1088 	struct icl_conn *ic;
1089 
1090 	ic = ip->ip_conn;
1091 
1092 	ICL_CONN_LOCK_ASSERT(ic);
1093 
1094 	if (ic->ic_disconnecting || ic->ic_socket == NULL) {
1095 		ICL_DEBUG("icl_pdu_queue on closed connection");
1096 		icl_pdu_free(ip);
1097 		return;
1098 	}
1099 
1100 	if (!STAILQ_EMPTY(&ic->ic_to_send)) {
1101 		STAILQ_INSERT_TAIL(&ic->ic_to_send, ip, ip_next);
1102 		/*
1103 		 * If the queue is not empty, someone else had already
1104 		 * signaled the send thread; no need to do that again,
1105 		 * just return.
1106 		 */
1107 		return;
1108 	}
1109 
1110 	STAILQ_INSERT_TAIL(&ic->ic_to_send, ip, ip_next);
1111 	cv_signal(&ic->ic_send_cv);
1112 }
1113 
1114 struct icl_conn *
1115 icl_conn_new(const char *name, struct mtx *lock)
1116 {
1117 	struct icl_conn *ic;
1118 
1119 	refcount_acquire(&icl_ncons);
1120 
1121 	ic = uma_zalloc(icl_conn_zone, M_WAITOK | M_ZERO);
1122 
1123 	STAILQ_INIT(&ic->ic_to_send);
1124 	ic->ic_lock = lock;
1125 	cv_init(&ic->ic_send_cv, "icl_tx");
1126 	cv_init(&ic->ic_receive_cv, "icl_rx");
1127 #ifdef DIAGNOSTIC
1128 	refcount_init(&ic->ic_outstanding_pdus, 0);
1129 #endif
1130 	ic->ic_max_data_segment_length = ICL_MAX_DATA_SEGMENT_LENGTH;
1131 	ic->ic_name = name;
1132 
1133 	return (ic);
1134 }
1135 
1136 void
1137 icl_conn_free(struct icl_conn *ic)
1138 {
1139 
1140 	cv_destroy(&ic->ic_send_cv);
1141 	cv_destroy(&ic->ic_receive_cv);
1142 	uma_zfree(icl_conn_zone, ic);
1143 	refcount_release(&icl_ncons);
1144 }
1145 
1146 static int
1147 icl_conn_start(struct icl_conn *ic)
1148 {
1149 	size_t minspace;
1150 	struct sockopt opt;
1151 	int error, one = 1;
1152 
1153 	ICL_CONN_LOCK(ic);
1154 
1155 	/*
1156 	 * XXX: Ugly hack.
1157 	 */
1158 	if (ic->ic_socket == NULL) {
1159 		ICL_CONN_UNLOCK(ic);
1160 		return (EINVAL);
1161 	}
1162 
1163 	ic->ic_receive_state = ICL_CONN_STATE_BHS;
1164 	ic->ic_receive_len = sizeof(struct iscsi_bhs);
1165 	ic->ic_disconnecting = false;
1166 
1167 	ICL_CONN_UNLOCK(ic);
1168 
1169 	/*
1170 	 * For sendspace, this is required because the current code cannot
1171 	 * send a PDU in pieces; thus, the minimum buffer size is equal
1172 	 * to the maximum PDU size.  "+4" is to account for possible padding.
1173 	 *
1174 	 * What we should actually do here is to use autoscaling, but set
1175 	 * some minimal buffer size to "minspace".  I don't know a way to do
1176 	 * that, though.
1177 	 */
1178 	minspace = sizeof(struct iscsi_bhs) + ic->ic_max_data_segment_length +
1179 	    ISCSI_HEADER_DIGEST_SIZE + ISCSI_DATA_DIGEST_SIZE + 4;
1180 	if (sendspace < minspace) {
1181 		ICL_WARN("kern.icl.sendspace too low; must be at least %zd",
1182 		    minspace);
1183 		sendspace = minspace;
1184 	}
1185 	if (recvspace < minspace) {
1186 		ICL_WARN("kern.icl.recvspace too low; must be at least %zd",
1187 		    minspace);
1188 		recvspace = minspace;
1189 	}
1190 
1191 	error = soreserve(ic->ic_socket, sendspace, recvspace);
1192 	if (error != 0) {
1193 		ICL_WARN("soreserve failed with error %d", error);
1194 		icl_conn_close(ic);
1195 		return (error);
1196 	}
1197 
1198 	/*
1199 	 * Disable Nagle.
1200 	 */
1201 	bzero(&opt, sizeof(opt));
1202 	opt.sopt_dir = SOPT_SET;
1203 	opt.sopt_level = IPPROTO_TCP;
1204 	opt.sopt_name = TCP_NODELAY;
1205 	opt.sopt_val = &one;
1206 	opt.sopt_valsize = sizeof(one);
1207 	error = sosetopt(ic->ic_socket, &opt);
1208 	if (error != 0) {
1209 		ICL_WARN("disabling TCP_NODELAY failed with error %d", error);
1210 		icl_conn_close(ic);
1211 		return (error);
1212 	}
1213 
1214 	/*
1215 	 * Start threads.
1216 	 */
1217 	error = kthread_add(icl_send_thread, ic, NULL, NULL, 0, 0, "%stx",
1218 	    ic->ic_name);
1219 	if (error != 0) {
1220 		ICL_WARN("kthread_add(9) failed with error %d", error);
1221 		icl_conn_close(ic);
1222 		return (error);
1223 	}
1224 
1225 	error = kthread_add(icl_receive_thread, ic, NULL, NULL, 0, 0, "%srx",
1226 	    ic->ic_name);
1227 	if (error != 0) {
1228 		ICL_WARN("kthread_add(9) failed with error %d", error);
1229 		icl_conn_close(ic);
1230 		return (error);
1231 	}
1232 
1233 	/*
1234 	 * Register socket upcall, to get notified about incoming PDUs
1235 	 * and free space to send outgoing ones.
1236 	 */
1237 	SOCKBUF_LOCK(&ic->ic_socket->so_snd);
1238 	soupcall_set(ic->ic_socket, SO_SND, icl_soupcall_send, ic);
1239 	SOCKBUF_UNLOCK(&ic->ic_socket->so_snd);
1240 	SOCKBUF_LOCK(&ic->ic_socket->so_rcv);
1241 	soupcall_set(ic->ic_socket, SO_RCV, icl_soupcall_receive, ic);
1242 	SOCKBUF_UNLOCK(&ic->ic_socket->so_rcv);
1243 
1244 	return (0);
1245 }
1246 
1247 int
1248 icl_conn_handoff(struct icl_conn *ic, int fd)
1249 {
1250 	struct file *fp;
1251 	struct socket *so;
1252 	cap_rights_t rights;
1253 	int error;
1254 
1255 	ICL_CONN_LOCK_ASSERT_NOT(ic);
1256 
1257 	/*
1258 	 * Steal the socket from userland.
1259 	 */
1260 	error = fget(curthread, fd,
1261 	    cap_rights_init(&rights, CAP_SOCK_CLIENT), &fp);
1262 	if (error != 0)
1263 		return (error);
1264 	if (fp->f_type != DTYPE_SOCKET) {
1265 		fdrop(fp, curthread);
1266 		return (EINVAL);
1267 	}
1268 	so = fp->f_data;
1269 	if (so->so_type != SOCK_STREAM) {
1270 		fdrop(fp, curthread);
1271 		return (EINVAL);
1272 	}
1273 
1274 	ICL_CONN_LOCK(ic);
1275 
1276 	if (ic->ic_socket != NULL) {
1277 		ICL_CONN_UNLOCK(ic);
1278 		fdrop(fp, curthread);
1279 		return (EBUSY);
1280 	}
1281 
1282 	ic->ic_socket = fp->f_data;
1283 	fp->f_ops = &badfileops;
1284 	fp->f_data = NULL;
1285 	fdrop(fp, curthread);
1286 	ICL_CONN_UNLOCK(ic);
1287 
1288 	error = icl_conn_start(ic);
1289 
1290 	return (error);
1291 }
1292 
1293 void
1294 icl_conn_shutdown(struct icl_conn *ic)
1295 {
1296 	ICL_CONN_LOCK_ASSERT_NOT(ic);
1297 
1298 	ICL_CONN_LOCK(ic);
1299 	if (ic->ic_socket == NULL) {
1300 		ICL_CONN_UNLOCK(ic);
1301 		return;
1302 	}
1303 	ICL_CONN_UNLOCK(ic);
1304 
1305 	soshutdown(ic->ic_socket, SHUT_RDWR);
1306 }
1307 
1308 void
1309 icl_conn_close(struct icl_conn *ic)
1310 {
1311 	struct icl_pdu *pdu;
1312 
1313 	ICL_CONN_LOCK_ASSERT_NOT(ic);
1314 
1315 	ICL_CONN_LOCK(ic);
1316 	if (ic->ic_socket == NULL) {
1317 		ICL_CONN_UNLOCK(ic);
1318 		return;
1319 	}
1320 
1321 	/*
1322 	 * Deregister socket upcalls.
1323 	 */
1324 	ICL_CONN_UNLOCK(ic);
1325 	SOCKBUF_LOCK(&ic->ic_socket->so_snd);
1326 	if (ic->ic_socket->so_snd.sb_upcall != NULL)
1327 		soupcall_clear(ic->ic_socket, SO_SND);
1328 	SOCKBUF_UNLOCK(&ic->ic_socket->so_snd);
1329 	SOCKBUF_LOCK(&ic->ic_socket->so_rcv);
1330 	if (ic->ic_socket->so_rcv.sb_upcall != NULL)
1331 		soupcall_clear(ic->ic_socket, SO_RCV);
1332 	SOCKBUF_UNLOCK(&ic->ic_socket->so_rcv);
1333 	ICL_CONN_LOCK(ic);
1334 
1335 	ic->ic_disconnecting = true;
1336 
1337 	/*
1338 	 * Wake up the threads, so they can properly terminate.
1339 	 */
1340 	cv_signal(&ic->ic_receive_cv);
1341 	cv_signal(&ic->ic_send_cv);
1342 	while (ic->ic_receive_running || ic->ic_send_running) {
1343 		//ICL_DEBUG("waiting for send/receive threads to terminate");
1344 		ICL_CONN_UNLOCK(ic);
1345 		cv_signal(&ic->ic_receive_cv);
1346 		cv_signal(&ic->ic_send_cv);
1347 		pause("icl_close", 1 * hz);
1348 		ICL_CONN_LOCK(ic);
1349 	}
1350 	//ICL_DEBUG("send/receive threads terminated");
1351 
1352 	ICL_CONN_UNLOCK(ic);
1353 	soclose(ic->ic_socket);
1354 	ICL_CONN_LOCK(ic);
1355 	ic->ic_socket = NULL;
1356 
1357 	if (ic->ic_receive_pdu != NULL) {
1358 		//ICL_DEBUG("freeing partially received PDU");
1359 		icl_pdu_free(ic->ic_receive_pdu);
1360 		ic->ic_receive_pdu = NULL;
1361 	}
1362 
1363 	/*
1364 	 * Remove any outstanding PDUs from the send queue.
1365 	 */
1366 	while (!STAILQ_EMPTY(&ic->ic_to_send)) {
1367 		pdu = STAILQ_FIRST(&ic->ic_to_send);
1368 		STAILQ_REMOVE_HEAD(&ic->ic_to_send, ip_next);
1369 		icl_pdu_free(pdu);
1370 	}
1371 
1372 	KASSERT(STAILQ_EMPTY(&ic->ic_to_send),
1373 	    ("destroying session with non-empty send queue"));
1374 #ifdef DIAGNOSTIC
1375 	KASSERT(ic->ic_outstanding_pdus == 0,
1376 	    ("destroying session with %d outstanding PDUs",
1377 	     ic->ic_outstanding_pdus));
1378 #endif
1379 	ICL_CONN_UNLOCK(ic);
1380 }
1381 
1382 bool
1383 icl_conn_connected(struct icl_conn *ic)
1384 {
1385 	ICL_CONN_LOCK_ASSERT_NOT(ic);
1386 
1387 	ICL_CONN_LOCK(ic);
1388 	if (ic->ic_socket == NULL) {
1389 		ICL_CONN_UNLOCK(ic);
1390 		return (false);
1391 	}
1392 	if (ic->ic_socket->so_error != 0) {
1393 		ICL_CONN_UNLOCK(ic);
1394 		return (false);
1395 	}
1396 	ICL_CONN_UNLOCK(ic);
1397 	return (true);
1398 }
1399 
1400 #ifdef ICL_KERNEL_PROXY
1401 int
1402 icl_conn_handoff_sock(struct icl_conn *ic, struct socket *so)
1403 {
1404 	int error;
1405 
1406 	ICL_CONN_LOCK_ASSERT_NOT(ic);
1407 
1408 	if (so->so_type != SOCK_STREAM)
1409 		return (EINVAL);
1410 
1411 	ICL_CONN_LOCK(ic);
1412 	if (ic->ic_socket != NULL) {
1413 		ICL_CONN_UNLOCK(ic);
1414 		return (EBUSY);
1415 	}
1416 	ic->ic_socket = so;
1417 	ICL_CONN_UNLOCK(ic);
1418 
1419 	error = icl_conn_start(ic);
1420 
1421 	return (error);
1422 }
1423 #endif /* ICL_KERNEL_PROXY */
1424 
1425 static int
1426 icl_unload(void)
1427 {
1428 
1429 	if (icl_ncons != 0)
1430 		return (EBUSY);
1431 
1432 	uma_zdestroy(icl_conn_zone);
1433 	uma_zdestroy(icl_pdu_zone);
1434 
1435 	return (0);
1436 }
1437 
1438 static void
1439 icl_load(void)
1440 {
1441 
1442 	icl_conn_zone = uma_zcreate("icl_conn",
1443 	    sizeof(struct icl_conn), NULL, NULL, NULL, NULL,
1444 	    UMA_ALIGN_PTR, 0);
1445 	icl_pdu_zone = uma_zcreate("icl_pdu",
1446 	    sizeof(struct icl_pdu), NULL, NULL, NULL, NULL,
1447 	    UMA_ALIGN_PTR, 0);
1448 
1449 	refcount_init(&icl_ncons, 0);
1450 }
1451 
1452 static int
1453 icl_modevent(module_t mod, int what, void *arg)
1454 {
1455 
1456 	switch (what) {
1457 	case MOD_LOAD:
1458 		icl_load();
1459 		return (0);
1460 	case MOD_UNLOAD:
1461 		return (icl_unload());
1462 	default:
1463 		return (EINVAL);
1464 	}
1465 }
1466 
1467 moduledata_t icl_data = {
1468 	"icl",
1469 	icl_modevent,
1470 	0
1471 };
1472 
1473 DECLARE_MODULE(icl, icl_data, SI_SUB_DRIVERS, SI_ORDER_FIRST);
1474 MODULE_VERSION(icl, 1);
1475