xref: /freebsd/sys/dev/iscsi/iscsi.c (revision 5608fd23c27fa1e8ee595d7b678cbfd35d657fbe)
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 #include <sys/param.h>
33 #include <sys/condvar.h>
34 #include <sys/conf.h>
35 #include <sys/endian.h>
36 #include <sys/eventhandler.h>
37 #include <sys/file.h>
38 #include <sys/kernel.h>
39 #include <sys/kthread.h>
40 #include <sys/lock.h>
41 #include <sys/malloc.h>
42 #include <sys/mutex.h>
43 #include <sys/module.h>
44 #include <sys/sysctl.h>
45 #include <sys/systm.h>
46 #include <sys/sx.h>
47 #include <vm/uma.h>
48 
49 #include <cam/cam.h>
50 #include <cam/cam_ccb.h>
51 #include <cam/cam_xpt.h>
52 #include <cam/cam_debug.h>
53 #include <cam/cam_sim.h>
54 #include <cam/cam_xpt_sim.h>
55 #include <cam/cam_xpt_periph.h>
56 #include <cam/cam_periph.h>
57 #include <cam/scsi/scsi_all.h>
58 #include <cam/scsi/scsi_message.h>
59 
60 #include "iscsi_ioctl.h"
61 #include "iscsi.h"
62 #include "icl.h"
63 #include "iscsi_proto.h"
64 
65 #ifdef ICL_KERNEL_PROXY
66 #include <sys/socketvar.h>
67 #endif
68 
69 #ifdef ICL_KERNEL_PROXY
70 FEATURE(iscsi_kernel_proxy, "iSCSI initiator built with ICL_KERNEL_PROXY");
71 #endif
72 
73 /*
74  * XXX: This is global so the iscsi_unload() can access it.
75  * 	Think about how to do this properly.
76  */
77 static struct iscsi_softc	*sc;
78 
79 SYSCTL_NODE(_kern, OID_AUTO, iscsi, CTLFLAG_RD, 0, "iSCSI initiator");
80 static int debug = 1;
81 SYSCTL_INT(_kern_iscsi, OID_AUTO, debug, CTLFLAG_RWTUN,
82     &debug, 0, "Enable debug messages");
83 static int ping_timeout = 5;
84 SYSCTL_INT(_kern_iscsi, OID_AUTO, ping_timeout, CTLFLAG_RWTUN, &ping_timeout,
85     0, "Timeout for ping (NOP-Out) requests, in seconds");
86 static int iscsid_timeout = 60;
87 SYSCTL_INT(_kern_iscsi, OID_AUTO, iscsid_timeout, CTLFLAG_RWTUN, &iscsid_timeout,
88     0, "Time to wait for iscsid(8) to handle reconnection, in seconds");
89 static int login_timeout = 60;
90 SYSCTL_INT(_kern_iscsi, OID_AUTO, login_timeout, CTLFLAG_RWTUN, &login_timeout,
91     0, "Time to wait for iscsid(8) to finish Login Phase, in seconds");
92 static int maxtags = 255;
93 SYSCTL_INT(_kern_iscsi, OID_AUTO, maxtags, CTLFLAG_RWTUN, &maxtags,
94     0, "Max number of IO requests queued");
95 static int fail_on_disconnection = 0;
96 SYSCTL_INT(_kern_iscsi, OID_AUTO, fail_on_disconnection, CTLFLAG_RWTUN,
97     &fail_on_disconnection, 0, "Destroy CAM SIM on connection failure");
98 
99 static MALLOC_DEFINE(M_ISCSI, "iSCSI", "iSCSI initiator");
100 static uma_zone_t iscsi_outstanding_zone;
101 
102 #define	CONN_SESSION(X)	((struct iscsi_session *)X->ic_prv0)
103 #define	PDU_SESSION(X)	(CONN_SESSION(X->ip_conn))
104 
105 #define	ISCSI_DEBUG(X, ...)						\
106 	do {								\
107 		if (debug > 1) 						\
108 			printf("%s: " X "\n", __func__, ## __VA_ARGS__);\
109 	} while (0)
110 
111 #define	ISCSI_WARN(X, ...)						\
112 	do {								\
113 		if (debug > 0) {					\
114 			printf("WARNING: %s: " X "\n",			\
115 			    __func__, ## __VA_ARGS__);			\
116 		}							\
117 	} while (0)
118 
119 #define	ISCSI_SESSION_DEBUG(S, X, ...)					\
120 	do {								\
121 		if (debug > 1) {					\
122 			printf("%s: %s (%s): " X "\n",			\
123 			    __func__, S->is_conf.isc_target_addr,	\
124 			    S->is_conf.isc_target, ## __VA_ARGS__);	\
125 		}							\
126 	} while (0)
127 
128 #define	ISCSI_SESSION_WARN(S, X, ...)					\
129 	do {								\
130 		if (debug > 0) {					\
131 			printf("WARNING: %s (%s): " X "\n",		\
132 			    S->is_conf.isc_target_addr,			\
133 			    S->is_conf.isc_target, ## __VA_ARGS__);	\
134 		}							\
135 	} while (0)
136 
137 #define ISCSI_SESSION_LOCK(X)		mtx_lock(&X->is_lock)
138 #define ISCSI_SESSION_UNLOCK(X)		mtx_unlock(&X->is_lock)
139 #define ISCSI_SESSION_LOCK_ASSERT(X)	mtx_assert(&X->is_lock, MA_OWNED)
140 
141 static int	iscsi_ioctl(struct cdev *dev, u_long cmd, caddr_t arg,
142 		    int mode, struct thread *td);
143 
144 static struct cdevsw iscsi_cdevsw = {
145      .d_version = D_VERSION,
146      .d_ioctl   = iscsi_ioctl,
147      .d_name    = "iscsi",
148 };
149 
150 static void	iscsi_pdu_queue_locked(struct icl_pdu *request);
151 static void	iscsi_pdu_queue(struct icl_pdu *request);
152 static void	iscsi_pdu_update_statsn(const struct icl_pdu *response);
153 static void	iscsi_pdu_handle_nop_in(struct icl_pdu *response);
154 static void	iscsi_pdu_handle_scsi_response(struct icl_pdu *response);
155 static void	iscsi_pdu_handle_task_response(struct icl_pdu *response);
156 static void	iscsi_pdu_handle_data_in(struct icl_pdu *response);
157 static void	iscsi_pdu_handle_logout_response(struct icl_pdu *response);
158 static void	iscsi_pdu_handle_r2t(struct icl_pdu *response);
159 static void	iscsi_pdu_handle_async_message(struct icl_pdu *response);
160 static void	iscsi_pdu_handle_reject(struct icl_pdu *response);
161 static void	iscsi_session_reconnect(struct iscsi_session *is);
162 static void	iscsi_session_terminate(struct iscsi_session *is);
163 static void	iscsi_action(struct cam_sim *sim, union ccb *ccb);
164 static void	iscsi_poll(struct cam_sim *sim);
165 static struct iscsi_outstanding	*iscsi_outstanding_find(struct iscsi_session *is,
166 		    uint32_t initiator_task_tag);
167 static struct iscsi_outstanding	*iscsi_outstanding_add(struct iscsi_session *is,
168 		    uint32_t initiator_task_tag, union ccb *ccb);
169 static void	iscsi_outstanding_remove(struct iscsi_session *is,
170 		    struct iscsi_outstanding *io);
171 
172 static bool
173 iscsi_pdu_prepare(struct icl_pdu *request)
174 {
175 	struct iscsi_session *is;
176 	struct iscsi_bhs_scsi_command *bhssc;
177 
178 	is = PDU_SESSION(request);
179 
180 	ISCSI_SESSION_LOCK_ASSERT(is);
181 
182 	/*
183 	 * We're only using fields common for all the request
184 	 * (initiator -> target) PDUs.
185 	 */
186 	bhssc = (struct iscsi_bhs_scsi_command *)request->ip_bhs;
187 
188 	/*
189 	 * Data-Out PDU does not contain CmdSN.
190 	 */
191 	if (bhssc->bhssc_opcode != ISCSI_BHS_OPCODE_SCSI_DATA_OUT) {
192 		if (is->is_cmdsn > is->is_maxcmdsn &&
193 		    (bhssc->bhssc_opcode & ISCSI_BHS_OPCODE_IMMEDIATE) == 0) {
194 			/*
195 			 * Current MaxCmdSN prevents us from sending any more
196 			 * SCSI Command PDUs to the target; postpone the PDU.
197 			 * It will get resent by either iscsi_pdu_queue(),
198 			 * or by maintenance thread.
199 			 */
200 #if 0
201 			ISCSI_SESSION_DEBUG(is, "postponing send, CmdSN %d, ExpCmdSN %d, MaxCmdSN %d, opcode 0x%x",
202 			    is->is_cmdsn, is->is_expcmdsn, is->is_maxcmdsn, bhssc->bhssc_opcode);
203 #endif
204 			return (true);
205 		}
206 		bhssc->bhssc_cmdsn = htonl(is->is_cmdsn);
207 		if ((bhssc->bhssc_opcode & ISCSI_BHS_OPCODE_IMMEDIATE) == 0)
208 			is->is_cmdsn++;
209 	}
210 	bhssc->bhssc_expstatsn = htonl(is->is_statsn + 1);
211 
212 	return (false);
213 }
214 
215 static void
216 iscsi_session_send_postponed(struct iscsi_session *is)
217 {
218 	struct icl_pdu *request;
219 	bool postpone;
220 
221 	ISCSI_SESSION_LOCK_ASSERT(is);
222 
223 	while (!STAILQ_EMPTY(&is->is_postponed)) {
224 		request = STAILQ_FIRST(&is->is_postponed);
225 		postpone = iscsi_pdu_prepare(request);
226 		if (postpone)
227 			break;
228 		STAILQ_REMOVE_HEAD(&is->is_postponed, ip_next);
229 		icl_pdu_queue(request);
230 	}
231 }
232 
233 static void
234 iscsi_pdu_queue_locked(struct icl_pdu *request)
235 {
236 	struct iscsi_session *is;
237 	bool postpone;
238 
239 	is = PDU_SESSION(request);
240 	ISCSI_SESSION_LOCK_ASSERT(is);
241 	iscsi_session_send_postponed(is);
242 	postpone = iscsi_pdu_prepare(request);
243 	if (postpone) {
244 		STAILQ_INSERT_TAIL(&is->is_postponed, request, ip_next);
245 		return;
246 	}
247 	icl_pdu_queue(request);
248 }
249 
250 static void
251 iscsi_pdu_queue(struct icl_pdu *request)
252 {
253 	struct iscsi_session *is;
254 
255 	is = PDU_SESSION(request);
256 	ISCSI_SESSION_LOCK(is);
257 	iscsi_pdu_queue_locked(request);
258 	ISCSI_SESSION_UNLOCK(is);
259 }
260 
261 static void
262 iscsi_session_logout(struct iscsi_session *is)
263 {
264 	struct icl_pdu *request;
265 	struct iscsi_bhs_logout_request *bhslr;
266 
267 	request = icl_pdu_new_bhs(is->is_conn, M_NOWAIT);
268 	if (request == NULL)
269 		return;
270 
271 	bhslr = (struct iscsi_bhs_logout_request *)request->ip_bhs;
272 	bhslr->bhslr_opcode = ISCSI_BHS_OPCODE_LOGOUT_REQUEST;
273 	bhslr->bhslr_reason = BHSLR_REASON_CLOSE_SESSION;
274 	iscsi_pdu_queue_locked(request);
275 }
276 
277 static void
278 iscsi_session_terminate_task(struct iscsi_session *is,
279     struct iscsi_outstanding *io, bool requeue)
280 {
281 
282 	if (io->io_ccb != NULL) {
283 		io->io_ccb->ccb_h.status &= ~(CAM_SIM_QUEUED | CAM_STATUS_MASK);
284 		if (requeue)
285 			io->io_ccb->ccb_h.status |= CAM_REQUEUE_REQ;
286 		else
287 			io->io_ccb->ccb_h.status |= CAM_REQ_ABORTED;
288 		if ((io->io_ccb->ccb_h.status & CAM_DEV_QFRZN) == 0) {
289 			io->io_ccb->ccb_h.status |= CAM_DEV_QFRZN;
290 			xpt_freeze_devq(io->io_ccb->ccb_h.path, 1);
291 			ISCSI_SESSION_DEBUG(is, "freezing devq");
292 		}
293 		xpt_done(io->io_ccb);
294 	}
295 	iscsi_outstanding_remove(is, io);
296 }
297 
298 static void
299 iscsi_session_terminate_tasks(struct iscsi_session *is, bool requeue)
300 {
301 	struct iscsi_outstanding *io, *tmp;
302 
303 	ISCSI_SESSION_LOCK_ASSERT(is);
304 
305 	TAILQ_FOREACH_SAFE(io, &is->is_outstanding, io_next, tmp) {
306 		iscsi_session_terminate_task(is, io, requeue);
307 	}
308 }
309 
310 static void
311 iscsi_session_cleanup(struct iscsi_session *is, bool destroy_sim)
312 {
313 	struct icl_pdu *pdu;
314 
315 	ISCSI_SESSION_LOCK_ASSERT(is);
316 
317 	/*
318 	 * Don't queue any new PDUs.
319 	 */
320 	if (is->is_sim != NULL && is->is_simq_frozen == false) {
321 		ISCSI_SESSION_DEBUG(is, "freezing");
322 		xpt_freeze_simq(is->is_sim, 1);
323 		is->is_simq_frozen = true;
324 	}
325 
326 	/*
327 	 * Remove postponed PDUs.
328 	 */
329 	while (!STAILQ_EMPTY(&is->is_postponed)) {
330 		pdu = STAILQ_FIRST(&is->is_postponed);
331 		STAILQ_REMOVE_HEAD(&is->is_postponed, ip_next);
332 		icl_pdu_free(pdu);
333 	}
334 
335 	if (destroy_sim == false) {
336 		/*
337 		 * Terminate SCSI tasks, asking CAM to requeue them.
338 		 */
339 		iscsi_session_terminate_tasks(is, true);
340 		return;
341 	}
342 
343 	iscsi_session_terminate_tasks(is, false);
344 
345 	if (is->is_sim == NULL)
346 		return;
347 
348 	ISCSI_SESSION_DEBUG(is, "deregistering SIM");
349 	xpt_async(AC_LOST_DEVICE, is->is_path, NULL);
350 
351 	if (is->is_simq_frozen) {
352 		xpt_release_simq(is->is_sim, 1);
353 		is->is_simq_frozen = false;
354 	}
355 
356 	xpt_free_path(is->is_path);
357 	is->is_path = NULL;
358 	xpt_bus_deregister(cam_sim_path(is->is_sim));
359 	cam_sim_free(is->is_sim, TRUE /*free_devq*/);
360 	is->is_sim = NULL;
361 	is->is_devq = NULL;
362 }
363 
364 static void
365 iscsi_maintenance_thread_reconnect(struct iscsi_session *is)
366 {
367 
368 	icl_conn_shutdown(is->is_conn);
369 	icl_conn_close(is->is_conn);
370 
371 	ISCSI_SESSION_LOCK(is);
372 
373 	is->is_connected = false;
374 	is->is_reconnecting = false;
375 	is->is_login_phase = false;
376 
377 #ifdef ICL_KERNEL_PROXY
378 	if (is->is_login_pdu != NULL) {
379 		icl_pdu_free(is->is_login_pdu);
380 		is->is_login_pdu = NULL;
381 	}
382 	cv_signal(&is->is_login_cv);
383 #endif
384 
385 	if (fail_on_disconnection) {
386 		ISCSI_SESSION_DEBUG(is, "connection failed, destroying devices");
387 		iscsi_session_cleanup(is, true);
388 	} else {
389 		iscsi_session_cleanup(is, false);
390 	}
391 
392 	KASSERT(TAILQ_EMPTY(&is->is_outstanding),
393 	    ("destroying session with active tasks"));
394 	KASSERT(STAILQ_EMPTY(&is->is_postponed),
395 	    ("destroying session with postponed PDUs"));
396 
397 	/*
398 	 * Request immediate reconnection from iscsid(8).
399 	 */
400 	//ISCSI_SESSION_DEBUG(is, "waking up iscsid(8)");
401 	is->is_waiting_for_iscsid = true;
402 	strlcpy(is->is_reason, "Waiting for iscsid(8)", sizeof(is->is_reason));
403 	is->is_timeout = 0;
404 	ISCSI_SESSION_UNLOCK(is);
405 	cv_signal(&is->is_softc->sc_cv);
406 }
407 
408 static void
409 iscsi_maintenance_thread_terminate(struct iscsi_session *is)
410 {
411 	struct iscsi_softc *sc;
412 
413 	sc = is->is_softc;
414 	sx_xlock(&sc->sc_lock);
415 	TAILQ_REMOVE(&sc->sc_sessions, is, is_next);
416 	sx_xunlock(&sc->sc_lock);
417 
418 	icl_conn_close(is->is_conn);
419 
420 	ISCSI_SESSION_LOCK(is);
421 
422 	KASSERT(is->is_terminating, ("is_terminating == false"));
423 
424 #ifdef ICL_KERNEL_PROXY
425 	if (is->is_login_pdu != NULL) {
426 		icl_pdu_free(is->is_login_pdu);
427 		is->is_login_pdu = NULL;
428 	}
429 	cv_signal(&is->is_login_cv);
430 #endif
431 
432 	callout_drain(&is->is_callout);
433 
434 	iscsi_session_cleanup(is, true);
435 
436 	KASSERT(TAILQ_EMPTY(&is->is_outstanding),
437 	    ("destroying session with active tasks"));
438 	KASSERT(STAILQ_EMPTY(&is->is_postponed),
439 	    ("destroying session with postponed PDUs"));
440 
441 	ISCSI_SESSION_UNLOCK(is);
442 
443 	icl_conn_free(is->is_conn);
444 	mtx_destroy(&is->is_lock);
445 	cv_destroy(&is->is_maintenance_cv);
446 #ifdef ICL_KERNEL_PROXY
447 	cv_destroy(&is->is_login_cv);
448 #endif
449 	ISCSI_SESSION_DEBUG(is, "terminated");
450 	free(is, M_ISCSI);
451 
452 	/*
453 	 * The iscsi_unload() routine might be waiting.
454 	 */
455 	cv_signal(&sc->sc_cv);
456 }
457 
458 static void
459 iscsi_maintenance_thread(void *arg)
460 {
461 	struct iscsi_session *is;
462 
463 	is = arg;
464 
465 	for (;;) {
466 		ISCSI_SESSION_LOCK(is);
467 		if (is->is_reconnecting == false &&
468 		    is->is_terminating == false &&
469 		    STAILQ_EMPTY(&is->is_postponed))
470 			cv_wait(&is->is_maintenance_cv, &is->is_lock);
471 
472 		if (is->is_reconnecting) {
473 			ISCSI_SESSION_UNLOCK(is);
474 			iscsi_maintenance_thread_reconnect(is);
475 			continue;
476 		}
477 
478 		if (is->is_terminating) {
479 			ISCSI_SESSION_UNLOCK(is);
480 			iscsi_maintenance_thread_terminate(is);
481 			kthread_exit();
482 			return;
483 		}
484 
485 		iscsi_session_send_postponed(is);
486 		ISCSI_SESSION_UNLOCK(is);
487 	}
488 }
489 
490 static void
491 iscsi_session_reconnect(struct iscsi_session *is)
492 {
493 
494 	/*
495 	 * XXX: We can't use locking here, because
496 	 * 	it's being called from various contexts.
497 	 * 	Hope it doesn't break anything.
498 	 */
499 	if (is->is_reconnecting)
500 		return;
501 
502 	is->is_reconnecting = true;
503 	cv_signal(&is->is_maintenance_cv);
504 }
505 
506 static void
507 iscsi_session_terminate(struct iscsi_session *is)
508 {
509 	if (is->is_terminating)
510 		return;
511 
512 	is->is_terminating = true;
513 
514 #if 0
515 	iscsi_session_logout(is);
516 #endif
517 	cv_signal(&is->is_maintenance_cv);
518 }
519 
520 static void
521 iscsi_callout(void *context)
522 {
523 	struct icl_pdu *request;
524 	struct iscsi_bhs_nop_out *bhsno;
525 	struct iscsi_session *is;
526 	bool reconnect_needed = false;
527 
528 	is = context;
529 
530 	if (is->is_terminating)
531 		return;
532 
533 	callout_schedule(&is->is_callout, 1 * hz);
534 
535 	ISCSI_SESSION_LOCK(is);
536 	is->is_timeout++;
537 
538 	if (is->is_waiting_for_iscsid) {
539 		if (is->is_timeout > iscsid_timeout) {
540 			ISCSI_SESSION_WARN(is, "timed out waiting for iscsid(8) "
541 			    "for %d seconds; reconnecting",
542 			    is->is_timeout);
543 			reconnect_needed = true;
544 		}
545 		goto out;
546 	}
547 
548 	if (is->is_login_phase) {
549 		if (is->is_timeout > login_timeout) {
550 			ISCSI_SESSION_WARN(is, "login timed out after %d seconds; "
551 			    "reconnecting", is->is_timeout);
552 			reconnect_needed = true;
553 		}
554 		goto out;
555 	}
556 
557 	if (is->is_timeout >= ping_timeout) {
558 		ISCSI_SESSION_WARN(is, "no ping reply (NOP-In) after %d seconds; "
559 		    "reconnecting", ping_timeout);
560 		reconnect_needed = true;
561 		goto out;
562 	}
563 
564 	ISCSI_SESSION_UNLOCK(is);
565 
566 	/*
567 	 * If the ping was reset less than one second ago - which means
568 	 * that we've received some PDU during the last second - assume
569 	 * the traffic flows correctly and don't bother sending a NOP-Out.
570 	 *
571 	 * (It's 2 - one for one second, and one for incrementing is_timeout
572 	 * earlier in this routine.)
573 	 */
574 	if (is->is_timeout < 2)
575 		return;
576 
577 	request = icl_pdu_new_bhs(is->is_conn, M_NOWAIT);
578 	if (request == NULL) {
579 		ISCSI_SESSION_WARN(is, "failed to allocate PDU");
580 		return;
581 	}
582 	bhsno = (struct iscsi_bhs_nop_out *)request->ip_bhs;
583 	bhsno->bhsno_opcode = ISCSI_BHS_OPCODE_NOP_OUT |
584 	    ISCSI_BHS_OPCODE_IMMEDIATE;
585 	bhsno->bhsno_flags = 0x80;
586 	bhsno->bhsno_target_transfer_tag = 0xffffffff;
587 	iscsi_pdu_queue(request);
588 	return;
589 
590 out:
591 	ISCSI_SESSION_UNLOCK(is);
592 
593 	if (reconnect_needed)
594 		iscsi_session_reconnect(is);
595 }
596 
597 static void
598 iscsi_pdu_update_statsn(const struct icl_pdu *response)
599 {
600 	const struct iscsi_bhs_data_in *bhsdi;
601 	struct iscsi_session *is;
602 	uint32_t expcmdsn, maxcmdsn;
603 
604 	is = PDU_SESSION(response);
605 
606 	ISCSI_SESSION_LOCK_ASSERT(is);
607 
608 	/*
609 	 * We're only using fields common for all the response
610 	 * (target -> initiator) PDUs.
611 	 */
612 	bhsdi = (const struct iscsi_bhs_data_in *)response->ip_bhs;
613 	/*
614 	 * Ok, I lied.  In case of Data-In, "The fields StatSN, Status,
615 	 * and Residual Count only have meaningful content if the S bit
616 	 * is set to 1", so we also need to check the bit specific for
617 	 * Data-In PDU.
618 	 */
619 	if (bhsdi->bhsdi_opcode != ISCSI_BHS_OPCODE_SCSI_DATA_IN ||
620 	    (bhsdi->bhsdi_flags & BHSDI_FLAGS_S) != 0) {
621 		if (ntohl(bhsdi->bhsdi_statsn) < is->is_statsn) {
622 			ISCSI_SESSION_WARN(is,
623 			    "PDU StatSN %d >= session StatSN %d, opcode 0x%x",
624 			    is->is_statsn, ntohl(bhsdi->bhsdi_statsn),
625 			    bhsdi->bhsdi_opcode);
626 		}
627 		is->is_statsn = ntohl(bhsdi->bhsdi_statsn);
628 	}
629 
630 	expcmdsn = ntohl(bhsdi->bhsdi_expcmdsn);
631 	maxcmdsn = ntohl(bhsdi->bhsdi_maxcmdsn);
632 
633 	/*
634 	 * XXX: Compare using Serial Arithmetic Sense.
635 	 */
636 	if (maxcmdsn + 1 < expcmdsn) {
637 		ISCSI_SESSION_DEBUG(is, "PDU MaxCmdSN %d + 1 < PDU ExpCmdSN %d; ignoring",
638 		    maxcmdsn, expcmdsn);
639 	} else {
640 		if (maxcmdsn > is->is_maxcmdsn) {
641 			is->is_maxcmdsn = maxcmdsn;
642 
643 			/*
644 			 * Command window increased; kick the maintanance thread
645 			 * to send out postponed commands.
646 			 */
647 			if (!STAILQ_EMPTY(&is->is_postponed))
648 				cv_signal(&is->is_maintenance_cv);
649 		} else if (maxcmdsn < is->is_maxcmdsn) {
650 			ISCSI_SESSION_DEBUG(is, "PDU MaxCmdSN %d < session MaxCmdSN %d; ignoring",
651 			    maxcmdsn, is->is_maxcmdsn);
652 		}
653 
654 		if (expcmdsn > is->is_expcmdsn) {
655 			is->is_expcmdsn = expcmdsn;
656 		} else if (expcmdsn < is->is_expcmdsn) {
657 			ISCSI_SESSION_DEBUG(is, "PDU ExpCmdSN %d < session ExpCmdSN %d; ignoring",
658 			    expcmdsn, is->is_expcmdsn);
659 		}
660 	}
661 
662 	/*
663 	 * Every incoming PDU - not just NOP-In - resets the ping timer.
664 	 * The purpose of the timeout is to reset the connection when it stalls;
665 	 * we don't want this to happen when NOP-In or NOP-Out ends up delayed
666 	 * in some queue.
667 	 */
668 	is->is_timeout = 0;
669 }
670 
671 static void
672 iscsi_receive_callback(struct icl_pdu *response)
673 {
674 	struct iscsi_session *is;
675 
676 	is = PDU_SESSION(response);
677 
678 	ISCSI_SESSION_LOCK(is);
679 
680 #ifdef ICL_KERNEL_PROXY
681 	if (is->is_login_phase) {
682 		if (is->is_login_pdu == NULL)
683 			is->is_login_pdu = response;
684 		else
685 			icl_pdu_free(response);
686 		ISCSI_SESSION_UNLOCK(is);
687 		cv_signal(&is->is_login_cv);
688 		return;
689 	}
690 #endif
691 
692 	iscsi_pdu_update_statsn(response);
693 
694 	/*
695 	 * The handling routine is responsible for freeing the PDU
696 	 * when it's no longer needed.
697 	 */
698 	switch (response->ip_bhs->bhs_opcode) {
699 	case ISCSI_BHS_OPCODE_NOP_IN:
700 		iscsi_pdu_handle_nop_in(response);
701 		break;
702 	case ISCSI_BHS_OPCODE_SCSI_RESPONSE:
703 		iscsi_pdu_handle_scsi_response(response);
704 		break;
705 	case ISCSI_BHS_OPCODE_TASK_RESPONSE:
706 		iscsi_pdu_handle_task_response(response);
707 		break;
708 	case ISCSI_BHS_OPCODE_SCSI_DATA_IN:
709 		iscsi_pdu_handle_data_in(response);
710 		break;
711 	case ISCSI_BHS_OPCODE_LOGOUT_RESPONSE:
712 		iscsi_pdu_handle_logout_response(response);
713 		break;
714 	case ISCSI_BHS_OPCODE_R2T:
715 		iscsi_pdu_handle_r2t(response);
716 		break;
717 	case ISCSI_BHS_OPCODE_ASYNC_MESSAGE:
718 		iscsi_pdu_handle_async_message(response);
719 		break;
720 	case ISCSI_BHS_OPCODE_REJECT:
721 		iscsi_pdu_handle_reject(response);
722 		break;
723 	default:
724 		ISCSI_SESSION_WARN(is, "received PDU with unsupported "
725 		    "opcode 0x%x; reconnecting",
726 		    response->ip_bhs->bhs_opcode);
727 		iscsi_session_reconnect(is);
728 		icl_pdu_free(response);
729 	}
730 
731 	ISCSI_SESSION_UNLOCK(is);
732 }
733 
734 static void
735 iscsi_error_callback(struct icl_conn *ic)
736 {
737 	struct iscsi_session *is;
738 
739 	is = CONN_SESSION(ic);
740 
741 	ISCSI_SESSION_WARN(is, "connection error; reconnecting");
742 	iscsi_session_reconnect(is);
743 }
744 
745 static void
746 iscsi_pdu_handle_nop_in(struct icl_pdu *response)
747 {
748 	struct iscsi_session *is;
749 	struct iscsi_bhs_nop_out *bhsno;
750 	struct iscsi_bhs_nop_in *bhsni;
751 	struct icl_pdu *request;
752 	void *data = NULL;
753 	size_t datasize;
754 	int error;
755 
756 	is = PDU_SESSION(response);
757 	bhsni = (struct iscsi_bhs_nop_in *)response->ip_bhs;
758 
759 	if (bhsni->bhsni_target_transfer_tag == 0xffffffff) {
760 		/*
761 		 * Nothing to do; iscsi_pdu_update_statsn() already
762 		 * zeroed the timeout.
763 		 */
764 		icl_pdu_free(response);
765 		return;
766 	}
767 
768 	datasize = icl_pdu_data_segment_length(response);
769 	if (datasize > 0) {
770 		data = malloc(datasize, M_ISCSI, M_NOWAIT | M_ZERO);
771 		if (data == NULL) {
772 			ISCSI_SESSION_WARN(is, "failed to allocate memory; "
773 			    "reconnecting");
774 			icl_pdu_free(response);
775 			iscsi_session_reconnect(is);
776 			return;
777 		}
778 		icl_pdu_get_data(response, 0, data, datasize);
779 	}
780 
781 	request = icl_pdu_new_bhs(response->ip_conn, M_NOWAIT);
782 	if (request == NULL) {
783 		ISCSI_SESSION_WARN(is, "failed to allocate memory; "
784 		    "reconnecting");
785 		free(data, M_ISCSI);
786 		icl_pdu_free(response);
787 		iscsi_session_reconnect(is);
788 		return;
789 	}
790 	bhsno = (struct iscsi_bhs_nop_out *)request->ip_bhs;
791 	bhsno->bhsno_opcode = ISCSI_BHS_OPCODE_NOP_OUT |
792 	    ISCSI_BHS_OPCODE_IMMEDIATE;
793 	bhsno->bhsno_flags = 0x80;
794 	bhsno->bhsno_initiator_task_tag = 0xffffffff;
795 	bhsno->bhsno_target_transfer_tag = bhsni->bhsni_target_transfer_tag;
796 	if (datasize > 0) {
797 		error = icl_pdu_append_data(request, data, datasize, M_NOWAIT);
798 		if (error != 0) {
799 			ISCSI_SESSION_WARN(is, "failed to allocate memory; "
800 			    "reconnecting");
801 			free(data, M_ISCSI);
802 			icl_pdu_free(request);
803 			icl_pdu_free(response);
804 			iscsi_session_reconnect(is);
805 			return;
806 		}
807 		free(data, M_ISCSI);
808 	}
809 
810 	icl_pdu_free(response);
811 	iscsi_pdu_queue_locked(request);
812 }
813 
814 static void
815 iscsi_pdu_handle_scsi_response(struct icl_pdu *response)
816 {
817 	struct iscsi_bhs_scsi_response *bhssr;
818 	struct iscsi_outstanding *io;
819 	struct iscsi_session *is;
820 	struct ccb_scsiio *csio;
821 	size_t data_segment_len;
822 	uint16_t sense_len;
823 
824 	is = PDU_SESSION(response);
825 
826 	bhssr = (struct iscsi_bhs_scsi_response *)response->ip_bhs;
827 	io = iscsi_outstanding_find(is, bhssr->bhssr_initiator_task_tag);
828 	if (io == NULL || io->io_ccb == NULL) {
829 		ISCSI_SESSION_WARN(is, "bad itt 0x%x", bhssr->bhssr_initiator_task_tag);
830 		icl_pdu_free(response);
831 		iscsi_session_reconnect(is);
832 		return;
833 	}
834 
835 	if (bhssr->bhssr_response != BHSSR_RESPONSE_COMMAND_COMPLETED) {
836 		ISCSI_SESSION_WARN(is, "service response 0x%x", bhssr->bhssr_response);
837  		if ((io->io_ccb->ccb_h.status & CAM_DEV_QFRZN) == 0) {
838  			xpt_freeze_devq(io->io_ccb->ccb_h.path, 1);
839 			ISCSI_SESSION_DEBUG(is, "freezing devq");
840 		}
841  		io->io_ccb->ccb_h.status = CAM_REQ_CMP_ERR | CAM_DEV_QFRZN;
842 	} else if (bhssr->bhssr_status == 0) {
843 		io->io_ccb->ccb_h.status = CAM_REQ_CMP;
844 	} else {
845  		if ((io->io_ccb->ccb_h.status & CAM_DEV_QFRZN) == 0) {
846  			xpt_freeze_devq(io->io_ccb->ccb_h.path, 1);
847 			ISCSI_SESSION_DEBUG(is, "freezing devq");
848 		}
849  		io->io_ccb->ccb_h.status = CAM_SCSI_STATUS_ERROR | CAM_DEV_QFRZN;
850 		io->io_ccb->csio.scsi_status = bhssr->bhssr_status;
851 	}
852 
853 	if (bhssr->bhssr_flags & BHSSR_FLAGS_RESIDUAL_OVERFLOW) {
854 		ISCSI_SESSION_WARN(is, "target indicated residual overflow");
855 		icl_pdu_free(response);
856 		iscsi_session_reconnect(is);
857 		return;
858 	}
859 
860 	csio = &io->io_ccb->csio;
861 
862 	data_segment_len = icl_pdu_data_segment_length(response);
863 	if (data_segment_len > 0) {
864 		if (data_segment_len < sizeof(sense_len)) {
865 			ISCSI_SESSION_WARN(is, "truncated data segment (%zd bytes)",
866 			    data_segment_len);
867 			if ((io->io_ccb->ccb_h.status & CAM_DEV_QFRZN) == 0) {
868 				xpt_freeze_devq(io->io_ccb->ccb_h.path, 1);
869 				ISCSI_SESSION_DEBUG(is, "freezing devq");
870 			}
871 			io->io_ccb->ccb_h.status = CAM_REQ_CMP_ERR | CAM_DEV_QFRZN;
872 			goto out;
873 		}
874 		icl_pdu_get_data(response, 0, &sense_len, sizeof(sense_len));
875 		sense_len = ntohs(sense_len);
876 #if 0
877 		ISCSI_SESSION_DEBUG(is, "sense_len %d, data len %zd",
878 		    sense_len, data_segment_len);
879 #endif
880 		if (sizeof(sense_len) + sense_len > data_segment_len) {
881 			ISCSI_SESSION_WARN(is, "truncated data segment "
882 			    "(%zd bytes, should be %zd)",
883 			    data_segment_len, sizeof(sense_len) + sense_len);
884 			if ((io->io_ccb->ccb_h.status & CAM_DEV_QFRZN) == 0) {
885 				xpt_freeze_devq(io->io_ccb->ccb_h.path, 1);
886 				ISCSI_SESSION_DEBUG(is, "freezing devq");
887 			}
888 			io->io_ccb->ccb_h.status = CAM_REQ_CMP_ERR | CAM_DEV_QFRZN;
889 			goto out;
890 		} else if (sizeof(sense_len) + sense_len < data_segment_len)
891 			ISCSI_SESSION_WARN(is, "oversize data segment "
892 			    "(%zd bytes, should be %zd)",
893 			    data_segment_len, sizeof(sense_len) + sense_len);
894 		if (sense_len > csio->sense_len) {
895 			ISCSI_SESSION_DEBUG(is, "truncating sense from %d to %d",
896 			    sense_len, csio->sense_len);
897 			sense_len = csio->sense_len;
898 		}
899 		icl_pdu_get_data(response, sizeof(sense_len), &csio->sense_data, sense_len);
900 		csio->sense_resid = csio->sense_len - sense_len;
901 		io->io_ccb->ccb_h.status |= CAM_AUTOSNS_VALID;
902 	}
903 
904 out:
905 	if (bhssr->bhssr_flags & BHSSR_FLAGS_RESIDUAL_UNDERFLOW)
906 		csio->resid = ntohl(bhssr->bhssr_residual_count);
907 
908 	if ((csio->ccb_h.flags & CAM_DIR_MASK) == CAM_DIR_IN) {
909 		KASSERT(io->io_received <= csio->dxfer_len,
910 		    ("io->io_received > csio->dxfer_len"));
911 		if (io->io_received < csio->dxfer_len) {
912 			if (csio->resid != csio->dxfer_len - io->io_received) {
913 				ISCSI_SESSION_WARN(is, "underflow mismatch: "
914 				    "target indicates %d, we calculated %zd",
915 				    csio->resid,
916 				    csio->dxfer_len - io->io_received);
917 			}
918 			csio->resid = csio->dxfer_len - io->io_received;
919 		}
920 	}
921 
922 	xpt_done(io->io_ccb);
923 	iscsi_outstanding_remove(is, io);
924 	icl_pdu_free(response);
925 }
926 
927 static void
928 iscsi_pdu_handle_task_response(struct icl_pdu *response)
929 {
930 	struct iscsi_bhs_task_management_response *bhstmr;
931 	struct iscsi_outstanding *io, *aio;
932 	struct iscsi_session *is;
933 
934 	is = PDU_SESSION(response);
935 
936 	bhstmr = (struct iscsi_bhs_task_management_response *)response->ip_bhs;
937 	io = iscsi_outstanding_find(is, bhstmr->bhstmr_initiator_task_tag);
938 	if (io == NULL || io->io_ccb != NULL) {
939 		ISCSI_SESSION_WARN(is, "bad itt 0x%x",
940 		    bhstmr->bhstmr_initiator_task_tag);
941 		icl_pdu_free(response);
942 		iscsi_session_reconnect(is);
943 		return;
944 	}
945 
946 	if (bhstmr->bhstmr_response != BHSTMR_RESPONSE_FUNCTION_COMPLETE) {
947 		ISCSI_SESSION_WARN(is, "task response 0x%x",
948 		    bhstmr->bhstmr_response);
949 	} else {
950 		aio = iscsi_outstanding_find(is, io->io_datasn);
951 		if (aio != NULL && aio->io_ccb != NULL)
952 			iscsi_session_terminate_task(is, aio, false);
953 	}
954 
955 	iscsi_outstanding_remove(is, io);
956 	icl_pdu_free(response);
957 }
958 
959 static void
960 iscsi_pdu_handle_data_in(struct icl_pdu *response)
961 {
962 	struct iscsi_bhs_data_in *bhsdi;
963 	struct iscsi_outstanding *io;
964 	struct iscsi_session *is;
965 	struct ccb_scsiio *csio;
966 	size_t data_segment_len;
967 
968 	is = PDU_SESSION(response);
969 	bhsdi = (struct iscsi_bhs_data_in *)response->ip_bhs;
970 	io = iscsi_outstanding_find(is, bhsdi->bhsdi_initiator_task_tag);
971 	if (io == NULL || io->io_ccb == NULL) {
972 		ISCSI_SESSION_WARN(is, "bad itt 0x%x", bhsdi->bhsdi_initiator_task_tag);
973 		icl_pdu_free(response);
974 		iscsi_session_reconnect(is);
975 		return;
976 	}
977 
978 	data_segment_len = icl_pdu_data_segment_length(response);
979 	if (data_segment_len == 0) {
980 		/*
981 		 * "The sending of 0 length data segments should be avoided,
982 		 * but initiators and targets MUST be able to properly receive
983 		 * 0 length data segments."
984 		 */
985 		icl_pdu_free(response);
986 		return;
987 	}
988 
989 	/*
990 	 * We need to track this for security reasons - without it, malicious target
991 	 * could respond to SCSI READ without sending Data-In PDUs, which would result
992 	 * in read operation on the initiator side returning random kernel data.
993 	 */
994 	if (ntohl(bhsdi->bhsdi_buffer_offset) != io->io_received) {
995 		ISCSI_SESSION_WARN(is, "data out of order; expected offset %zd, got %zd",
996 		    io->io_received, (size_t)ntohl(bhsdi->bhsdi_buffer_offset));
997 		icl_pdu_free(response);
998 		iscsi_session_reconnect(is);
999 		return;
1000 	}
1001 
1002 	csio = &io->io_ccb->csio;
1003 
1004 	if (io->io_received + data_segment_len > csio->dxfer_len) {
1005 		ISCSI_SESSION_WARN(is, "oversize data segment (%zd bytes "
1006 		    "at offset %zd, buffer is %d)",
1007 		    data_segment_len, io->io_received, csio->dxfer_len);
1008 		icl_pdu_free(response);
1009 		iscsi_session_reconnect(is);
1010 		return;
1011 	}
1012 
1013 	icl_pdu_get_data(response, 0, csio->data_ptr + io->io_received, data_segment_len);
1014 	io->io_received += data_segment_len;
1015 
1016 	/*
1017 	 * XXX: Check DataSN.
1018 	 * XXX: Check F.
1019 	 */
1020 	if ((bhsdi->bhsdi_flags & BHSDI_FLAGS_S) == 0) {
1021 		/*
1022 		 * Nothing more to do.
1023 		 */
1024 		icl_pdu_free(response);
1025 		return;
1026 	}
1027 
1028 	//ISCSI_SESSION_DEBUG(is, "got S flag; status 0x%x", bhsdi->bhsdi_status);
1029 	if (bhsdi->bhsdi_status == 0) {
1030 		io->io_ccb->ccb_h.status = CAM_REQ_CMP;
1031 	} else {
1032 		if ((io->io_ccb->ccb_h.status & CAM_DEV_QFRZN) == 0) {
1033 			xpt_freeze_devq(io->io_ccb->ccb_h.path, 1);
1034 			ISCSI_SESSION_DEBUG(is, "freezing devq");
1035 		}
1036 		io->io_ccb->ccb_h.status = CAM_SCSI_STATUS_ERROR | CAM_DEV_QFRZN;
1037 		csio->scsi_status = bhsdi->bhsdi_status;
1038 	}
1039 
1040 	if ((csio->ccb_h.flags & CAM_DIR_MASK) == CAM_DIR_IN) {
1041 		KASSERT(io->io_received <= csio->dxfer_len,
1042 		    ("io->io_received > csio->dxfer_len"));
1043 		if (io->io_received < csio->dxfer_len) {
1044 			csio->resid = ntohl(bhsdi->bhsdi_residual_count);
1045 			if (csio->resid != csio->dxfer_len - io->io_received) {
1046 				ISCSI_SESSION_WARN(is, "underflow mismatch: "
1047 				    "target indicates %d, we calculated %zd",
1048 				    csio->resid,
1049 				    csio->dxfer_len - io->io_received);
1050 			}
1051 			csio->resid = csio->dxfer_len - io->io_received;
1052 		}
1053 	}
1054 
1055 	xpt_done(io->io_ccb);
1056 	iscsi_outstanding_remove(is, io);
1057 	icl_pdu_free(response);
1058 }
1059 
1060 static void
1061 iscsi_pdu_handle_logout_response(struct icl_pdu *response)
1062 {
1063 
1064 	ISCSI_SESSION_DEBUG(PDU_SESSION(response), "logout response");
1065 	icl_pdu_free(response);
1066 }
1067 
1068 static void
1069 iscsi_pdu_handle_r2t(struct icl_pdu *response)
1070 {
1071 	struct icl_pdu *request;
1072 	struct iscsi_session *is;
1073 	struct iscsi_bhs_r2t *bhsr2t;
1074 	struct iscsi_bhs_data_out *bhsdo;
1075 	struct iscsi_outstanding *io;
1076 	struct ccb_scsiio *csio;
1077 	size_t off, len, total_len;
1078 	int error;
1079 
1080 	is = PDU_SESSION(response);
1081 
1082 	bhsr2t = (struct iscsi_bhs_r2t *)response->ip_bhs;
1083 	io = iscsi_outstanding_find(is, bhsr2t->bhsr2t_initiator_task_tag);
1084 	if (io == NULL || io->io_ccb == NULL) {
1085 		ISCSI_SESSION_WARN(is, "bad itt 0x%x; reconnecting",
1086 		    bhsr2t->bhsr2t_initiator_task_tag);
1087 		icl_pdu_free(response);
1088 		iscsi_session_reconnect(is);
1089 		return;
1090 	}
1091 
1092 	csio = &io->io_ccb->csio;
1093 
1094 	if ((csio->ccb_h.flags & CAM_DIR_MASK) != CAM_DIR_OUT) {
1095 		ISCSI_SESSION_WARN(is, "received R2T for read command; reconnecting");
1096 		icl_pdu_free(response);
1097 		iscsi_session_reconnect(is);
1098 		return;
1099 	}
1100 
1101 	/*
1102 	 * XXX: Verify R2TSN.
1103 	 */
1104 
1105 	io->io_datasn = 0;
1106 
1107 	off = ntohl(bhsr2t->bhsr2t_buffer_offset);
1108 	if (off > csio->dxfer_len) {
1109 		ISCSI_SESSION_WARN(is, "target requested invalid offset "
1110 		    "%zd, buffer is is %d; reconnecting", off, csio->dxfer_len);
1111 		icl_pdu_free(response);
1112 		iscsi_session_reconnect(is);
1113 		return;
1114 	}
1115 
1116 	total_len = ntohl(bhsr2t->bhsr2t_desired_data_transfer_length);
1117 	if (total_len == 0 || total_len > csio->dxfer_len) {
1118 		ISCSI_SESSION_WARN(is, "target requested invalid length "
1119 		    "%zd, buffer is %d; reconnecting", total_len, csio->dxfer_len);
1120 		icl_pdu_free(response);
1121 		iscsi_session_reconnect(is);
1122 		return;
1123 	}
1124 
1125 	//ISCSI_SESSION_DEBUG(is, "r2t; off %zd, len %zd", off, total_len);
1126 
1127 	for (;;) {
1128 		len = total_len;
1129 
1130 		if (len > is->is_max_data_segment_length)
1131 			len = is->is_max_data_segment_length;
1132 
1133 		if (off + len > csio->dxfer_len) {
1134 			ISCSI_SESSION_WARN(is, "target requested invalid "
1135 			    "length/offset %zd, buffer is %d; reconnecting",
1136 			    off + len, csio->dxfer_len);
1137 			icl_pdu_free(response);
1138 			iscsi_session_reconnect(is);
1139 			return;
1140 		}
1141 
1142 		request = icl_pdu_new_bhs(response->ip_conn, M_NOWAIT);
1143 		if (request == NULL) {
1144 			icl_pdu_free(response);
1145 			iscsi_session_reconnect(is);
1146 			return;
1147 		}
1148 
1149 		bhsdo = (struct iscsi_bhs_data_out *)request->ip_bhs;
1150 		bhsdo->bhsdo_opcode = ISCSI_BHS_OPCODE_SCSI_DATA_OUT;
1151 		bhsdo->bhsdo_lun = bhsr2t->bhsr2t_lun;
1152 		bhsdo->bhsdo_initiator_task_tag =
1153 		    bhsr2t->bhsr2t_initiator_task_tag;
1154 		bhsdo->bhsdo_target_transfer_tag =
1155 		    bhsr2t->bhsr2t_target_transfer_tag;
1156 		bhsdo->bhsdo_datasn = htonl(io->io_datasn++);
1157 		bhsdo->bhsdo_buffer_offset = htonl(off);
1158 		error = icl_pdu_append_data(request, csio->data_ptr + off, len,
1159 		    M_NOWAIT);
1160 		if (error != 0) {
1161 			ISCSI_SESSION_WARN(is, "failed to allocate memory; "
1162 			    "reconnecting");
1163 			icl_pdu_free(request);
1164 			icl_pdu_free(response);
1165 			iscsi_session_reconnect(is);
1166 			return;
1167 		}
1168 
1169 		off += len;
1170 		total_len -= len;
1171 
1172 		if (total_len == 0) {
1173 			bhsdo->bhsdo_flags |= BHSDO_FLAGS_F;
1174 			//ISCSI_SESSION_DEBUG(is, "setting F, off %zd", off);
1175 		} else {
1176 			//ISCSI_SESSION_DEBUG(is, "not finished, off %zd", off);
1177 		}
1178 
1179 		iscsi_pdu_queue_locked(request);
1180 
1181 		if (total_len == 0)
1182 			break;
1183 	}
1184 
1185 	icl_pdu_free(response);
1186 }
1187 
1188 static void
1189 iscsi_pdu_handle_async_message(struct icl_pdu *response)
1190 {
1191 	struct iscsi_bhs_asynchronous_message *bhsam;
1192 	struct iscsi_session *is;
1193 
1194 	is = PDU_SESSION(response);
1195 	bhsam = (struct iscsi_bhs_asynchronous_message *)response->ip_bhs;
1196 	switch (bhsam->bhsam_async_event) {
1197 	case BHSAM_EVENT_TARGET_REQUESTS_LOGOUT:
1198 		ISCSI_SESSION_WARN(is, "target requests logout; removing session");
1199 		iscsi_session_logout(is);
1200 		iscsi_session_terminate(is);
1201 		break;
1202 	case BHSAM_EVENT_TARGET_TERMINATES_CONNECTION:
1203 		ISCSI_SESSION_WARN(is, "target indicates it will drop drop the connection");
1204 		break;
1205 	case BHSAM_EVENT_TARGET_TERMINATES_SESSION:
1206 		ISCSI_SESSION_WARN(is, "target indicates it will drop drop the session");
1207 		break;
1208 	default:
1209 		/*
1210 		 * XXX: Technically, we're obligated to also handle
1211 		 * 	parameter renegotiation.
1212 		 */
1213 		ISCSI_SESSION_WARN(is, "ignoring AsyncEvent %d", bhsam->bhsam_async_event);
1214 		break;
1215 	}
1216 
1217 	icl_pdu_free(response);
1218 }
1219 
1220 static void
1221 iscsi_pdu_handle_reject(struct icl_pdu *response)
1222 {
1223 	struct iscsi_bhs_reject *bhsr;
1224 	struct iscsi_session *is;
1225 
1226 	is = PDU_SESSION(response);
1227 	bhsr = (struct iscsi_bhs_reject *)response->ip_bhs;
1228 	ISCSI_SESSION_WARN(is, "received Reject PDU, reason 0x%x; protocol error?",
1229 	    bhsr->bhsr_reason);
1230 
1231 	icl_pdu_free(response);
1232 }
1233 
1234 static int
1235 iscsi_ioctl_daemon_wait(struct iscsi_softc *sc,
1236     struct iscsi_daemon_request *request)
1237 {
1238 	struct iscsi_session *is;
1239 	int error;
1240 
1241 	sx_slock(&sc->sc_lock);
1242 	for (;;) {
1243 		TAILQ_FOREACH(is, &sc->sc_sessions, is_next) {
1244 			ISCSI_SESSION_LOCK(is);
1245 			if (is->is_waiting_for_iscsid)
1246 				break;
1247 			ISCSI_SESSION_UNLOCK(is);
1248 		}
1249 
1250 		if (is == NULL) {
1251 			/*
1252 			 * No session requires attention from iscsid(8); wait.
1253 			 */
1254 			error = cv_wait_sig(&sc->sc_cv, &sc->sc_lock);
1255 			if (error != 0) {
1256 				sx_sunlock(&sc->sc_lock);
1257 				return (error);
1258 			}
1259 			continue;
1260 		}
1261 
1262 		is->is_waiting_for_iscsid = false;
1263 		is->is_login_phase = true;
1264 		is->is_reason[0] = '\0';
1265 		ISCSI_SESSION_UNLOCK(is);
1266 
1267 		request->idr_session_id = is->is_id;
1268 		memcpy(&request->idr_isid, &is->is_isid,
1269 		    sizeof(request->idr_isid));
1270 		request->idr_tsih = 0;	/* New or reinstated session. */
1271 		memcpy(&request->idr_conf, &is->is_conf,
1272 		    sizeof(request->idr_conf));
1273 
1274 		sx_sunlock(&sc->sc_lock);
1275 		return (0);
1276 	}
1277 }
1278 
1279 static int
1280 iscsi_ioctl_daemon_handoff(struct iscsi_softc *sc,
1281     struct iscsi_daemon_handoff *handoff)
1282 {
1283 	struct iscsi_session *is;
1284 	int error;
1285 
1286 	sx_slock(&sc->sc_lock);
1287 
1288 	/*
1289 	 * Find the session to hand off socket to.
1290 	 */
1291 	TAILQ_FOREACH(is, &sc->sc_sessions, is_next) {
1292 		if (is->is_id == handoff->idh_session_id)
1293 			break;
1294 	}
1295 	if (is == NULL) {
1296 		sx_sunlock(&sc->sc_lock);
1297 		return (ESRCH);
1298 	}
1299 	ISCSI_SESSION_LOCK(is);
1300 	if (is->is_conf.isc_discovery || is->is_terminating) {
1301 		ISCSI_SESSION_UNLOCK(is);
1302 		sx_sunlock(&sc->sc_lock);
1303 		return (EINVAL);
1304 	}
1305 	if (is->is_connected) {
1306 		/*
1307 		 * This might have happened because another iscsid(8)
1308 		 * instance handed off the connection in the meantime.
1309 		 * Just return.
1310 		 */
1311 		ISCSI_SESSION_WARN(is, "handoff on already connected "
1312 		    "session");
1313 		ISCSI_SESSION_UNLOCK(is);
1314 		sx_sunlock(&sc->sc_lock);
1315 		return (EBUSY);
1316 	}
1317 
1318 	strlcpy(is->is_target_alias, handoff->idh_target_alias,
1319 	    sizeof(is->is_target_alias));
1320 	is->is_tsih = handoff->idh_tsih;
1321 	is->is_statsn = handoff->idh_statsn;
1322 	is->is_initial_r2t = handoff->idh_initial_r2t;
1323 	is->is_immediate_data = handoff->idh_immediate_data;
1324 	is->is_max_data_segment_length = handoff->idh_max_data_segment_length;
1325 	is->is_max_burst_length = handoff->idh_max_burst_length;
1326 	is->is_first_burst_length = handoff->idh_first_burst_length;
1327 
1328 	if (handoff->idh_header_digest == ISCSI_DIGEST_CRC32C)
1329 		is->is_conn->ic_header_crc32c = true;
1330 	else
1331 		is->is_conn->ic_header_crc32c = false;
1332 	if (handoff->idh_data_digest == ISCSI_DIGEST_CRC32C)
1333 		is->is_conn->ic_data_crc32c = true;
1334 	else
1335 		is->is_conn->ic_data_crc32c = false;
1336 
1337 	is->is_cmdsn = 0;
1338 	is->is_expcmdsn = 0;
1339 	is->is_maxcmdsn = 0;
1340 	is->is_waiting_for_iscsid = false;
1341 	is->is_login_phase = false;
1342 	is->is_timeout = 0;
1343 	is->is_connected = true;
1344 	is->is_reason[0] = '\0';
1345 
1346 	ISCSI_SESSION_UNLOCK(is);
1347 
1348 #ifdef ICL_KERNEL_PROXY
1349 	if (handoff->idh_socket != 0) {
1350 #endif
1351 		/*
1352 		 * Handoff without using ICL proxy.
1353 		 */
1354 		error = icl_conn_handoff(is->is_conn, handoff->idh_socket);
1355 		if (error != 0) {
1356 			sx_sunlock(&sc->sc_lock);
1357 			iscsi_session_terminate(is);
1358 			return (error);
1359 		}
1360 #ifdef ICL_KERNEL_PROXY
1361 	}
1362 #endif
1363 
1364 	sx_sunlock(&sc->sc_lock);
1365 
1366 	if (is->is_sim != NULL) {
1367 		/*
1368 		 * When reconnecting, there already is SIM allocated for the session.
1369 		 */
1370 		KASSERT(is->is_simq_frozen, ("reconnect without frozen simq"));
1371 		ISCSI_SESSION_LOCK(is);
1372 		ISCSI_SESSION_DEBUG(is, "releasing");
1373 		xpt_release_simq(is->is_sim, 1);
1374 		is->is_simq_frozen = false;
1375 		ISCSI_SESSION_UNLOCK(is);
1376 
1377 	} else {
1378 		ISCSI_SESSION_LOCK(is);
1379 		is->is_devq = cam_simq_alloc(maxtags);
1380 		if (is->is_devq == NULL) {
1381 			ISCSI_SESSION_WARN(is, "failed to allocate simq");
1382 			iscsi_session_terminate(is);
1383 			return (ENOMEM);
1384 		}
1385 
1386 		is->is_sim = cam_sim_alloc(iscsi_action, iscsi_poll, "iscsi",
1387 		    is, is->is_id /* unit */, &is->is_lock,
1388 		    1, maxtags, is->is_devq);
1389 		if (is->is_sim == NULL) {
1390 			ISCSI_SESSION_UNLOCK(is);
1391 			ISCSI_SESSION_WARN(is, "failed to allocate SIM");
1392 			cam_simq_free(is->is_devq);
1393 			iscsi_session_terminate(is);
1394 			return (ENOMEM);
1395 		}
1396 
1397 		error = xpt_bus_register(is->is_sim, NULL, 0);
1398 		if (error != 0) {
1399 			ISCSI_SESSION_UNLOCK(is);
1400 			ISCSI_SESSION_WARN(is, "failed to register bus");
1401 			iscsi_session_terminate(is);
1402 			return (ENOMEM);
1403 		}
1404 
1405 		error = xpt_create_path(&is->is_path, /*periph*/NULL,
1406 		    cam_sim_path(is->is_sim), CAM_TARGET_WILDCARD,
1407 		    CAM_LUN_WILDCARD);
1408 		if (error != CAM_REQ_CMP) {
1409 			ISCSI_SESSION_UNLOCK(is);
1410 			ISCSI_SESSION_WARN(is, "failed to create path");
1411 			iscsi_session_terminate(is);
1412 			return (ENOMEM);
1413 		}
1414 		ISCSI_SESSION_UNLOCK(is);
1415 	}
1416 
1417 	return (0);
1418 }
1419 
1420 static int
1421 iscsi_ioctl_daemon_fail(struct iscsi_softc *sc,
1422     struct iscsi_daemon_fail *fail)
1423 {
1424 	struct iscsi_session *is;
1425 
1426 	sx_slock(&sc->sc_lock);
1427 
1428 	TAILQ_FOREACH(is, &sc->sc_sessions, is_next) {
1429 		if (is->is_id == fail->idf_session_id)
1430 			break;
1431 	}
1432 	if (is == NULL) {
1433 		sx_sunlock(&sc->sc_lock);
1434 		return (ESRCH);
1435 	}
1436 	ISCSI_SESSION_LOCK(is);
1437 	ISCSI_SESSION_DEBUG(is, "iscsid(8) failed: %s",
1438 	    fail->idf_reason);
1439 	strlcpy(is->is_reason, fail->idf_reason, sizeof(is->is_reason));
1440 	//is->is_waiting_for_iscsid = false;
1441 	//is->is_login_phase = true;
1442 	//iscsi_session_reconnect(is);
1443 	ISCSI_SESSION_UNLOCK(is);
1444 	sx_sunlock(&sc->sc_lock);
1445 
1446 	return (0);
1447 }
1448 
1449 #ifdef ICL_KERNEL_PROXY
1450 static int
1451 iscsi_ioctl_daemon_connect(struct iscsi_softc *sc,
1452     struct iscsi_daemon_connect *idc)
1453 {
1454 	struct iscsi_session *is;
1455 	struct sockaddr *from_sa, *to_sa;
1456 	int error;
1457 
1458 	sx_slock(&sc->sc_lock);
1459 	TAILQ_FOREACH(is, &sc->sc_sessions, is_next) {
1460 		if (is->is_id == idc->idc_session_id)
1461 			break;
1462 	}
1463 	if (is == NULL) {
1464 		sx_sunlock(&sc->sc_lock);
1465 		return (ESRCH);
1466 	}
1467 	sx_sunlock(&sc->sc_lock);
1468 
1469 	if (idc->idc_from_addrlen > 0) {
1470 		error = getsockaddr(&from_sa, (void *)idc->idc_from_addr, idc->idc_from_addrlen);
1471 		if (error != 0) {
1472 			ISCSI_SESSION_WARN(is,
1473 			    "getsockaddr failed with error %d", error);
1474 			return (error);
1475 		}
1476 	} else {
1477 		from_sa = NULL;
1478 	}
1479 	error = getsockaddr(&to_sa, (void *)idc->idc_to_addr, idc->idc_to_addrlen);
1480 	if (error != 0) {
1481 		ISCSI_SESSION_WARN(is, "getsockaddr failed with error %d",
1482 		    error);
1483 		free(from_sa, M_SONAME);
1484 		return (error);
1485 	}
1486 
1487 	ISCSI_SESSION_LOCK(is);
1488 	is->is_waiting_for_iscsid = false;
1489 	is->is_login_phase = true;
1490 	is->is_timeout = 0;
1491 	ISCSI_SESSION_UNLOCK(is);
1492 
1493 	error = icl_conn_connect(is->is_conn, idc->idc_iser, idc->idc_domain,
1494 	    idc->idc_socktype, idc->idc_protocol, from_sa, to_sa);
1495 	free(from_sa, M_SONAME);
1496 	free(to_sa, M_SONAME);
1497 
1498 	/*
1499 	 * Digests are always disabled during login phase.
1500 	 */
1501 	is->is_conn->ic_header_crc32c = false;
1502 	is->is_conn->ic_data_crc32c = false;
1503 
1504 	return (error);
1505 }
1506 
1507 static int
1508 iscsi_ioctl_daemon_send(struct iscsi_softc *sc,
1509     struct iscsi_daemon_send *ids)
1510 {
1511 	struct iscsi_session *is;
1512 	struct icl_pdu *ip;
1513 	size_t datalen;
1514 	void *data;
1515 	int error;
1516 
1517 	sx_slock(&sc->sc_lock);
1518 	TAILQ_FOREACH(is, &sc->sc_sessions, is_next) {
1519 		if (is->is_id == ids->ids_session_id)
1520 			break;
1521 	}
1522 	if (is == NULL) {
1523 		sx_sunlock(&sc->sc_lock);
1524 		return (ESRCH);
1525 	}
1526 	sx_sunlock(&sc->sc_lock);
1527 
1528 	if (is->is_login_phase == false)
1529 		return (EBUSY);
1530 
1531 	if (is->is_terminating || is->is_reconnecting)
1532 		return (EIO);
1533 
1534 	datalen = ids->ids_data_segment_len;
1535 	if (datalen > ISCSI_MAX_DATA_SEGMENT_LENGTH)
1536 		return (EINVAL);
1537 	if (datalen > 0) {
1538 		data = malloc(datalen, M_ISCSI, M_WAITOK);
1539 		error = copyin(ids->ids_data_segment, data, datalen);
1540 		if (error != 0) {
1541 			free(data, M_ISCSI);
1542 			return (error);
1543 		}
1544 	}
1545 
1546 	ip = icl_pdu_new_bhs(is->is_conn, M_WAITOK);
1547 	memcpy(ip->ip_bhs, ids->ids_bhs, sizeof(*ip->ip_bhs));
1548 	if (datalen > 0) {
1549 		error = icl_pdu_append_data(ip, data, datalen, M_WAITOK);
1550 		KASSERT(error == 0, ("icl_pdu_append_data(..., M_WAITOK) failed"));
1551 		free(data, M_ISCSI);
1552 	}
1553 	icl_pdu_queue(ip);
1554 
1555 	return (0);
1556 }
1557 
1558 static int
1559 iscsi_ioctl_daemon_receive(struct iscsi_softc *sc,
1560     struct iscsi_daemon_receive *idr)
1561 {
1562 	struct iscsi_session *is;
1563 	struct icl_pdu *ip;
1564 	void *data;
1565 
1566 	sx_slock(&sc->sc_lock);
1567 	TAILQ_FOREACH(is, &sc->sc_sessions, is_next) {
1568 		if (is->is_id == idr->idr_session_id)
1569 			break;
1570 	}
1571 	if (is == NULL) {
1572 		sx_sunlock(&sc->sc_lock);
1573 		return (ESRCH);
1574 	}
1575 	sx_sunlock(&sc->sc_lock);
1576 
1577 	if (is->is_login_phase == false)
1578 		return (EBUSY);
1579 
1580 	ISCSI_SESSION_LOCK(is);
1581 	while (is->is_login_pdu == NULL &&
1582 	    is->is_terminating == false &&
1583 	    is->is_reconnecting == false)
1584 		cv_wait(&is->is_login_cv, &is->is_lock);
1585 	if (is->is_terminating || is->is_reconnecting) {
1586 		ISCSI_SESSION_UNLOCK(is);
1587 		return (EIO);
1588 	}
1589 	ip = is->is_login_pdu;
1590 	is->is_login_pdu = NULL;
1591 	ISCSI_SESSION_UNLOCK(is);
1592 
1593 	if (ip->ip_data_len > idr->idr_data_segment_len) {
1594 		icl_pdu_free(ip);
1595 		return (EMSGSIZE);
1596 	}
1597 
1598 	copyout(ip->ip_bhs, idr->idr_bhs, sizeof(*ip->ip_bhs));
1599 	if (ip->ip_data_len > 0) {
1600 		data = malloc(ip->ip_data_len, M_ISCSI, M_WAITOK);
1601 		icl_pdu_get_data(ip, 0, data, ip->ip_data_len);
1602 		copyout(data, idr->idr_data_segment, ip->ip_data_len);
1603 		free(data, M_ISCSI);
1604 	}
1605 
1606 	icl_pdu_free(ip);
1607 
1608 	return (0);
1609 }
1610 #endif /* ICL_KERNEL_PROXY */
1611 
1612 static void
1613 iscsi_sanitize_session_conf(struct iscsi_session_conf *isc)
1614 {
1615 	/*
1616 	 * Just make sure all the fields are null-terminated.
1617 	 *
1618 	 * XXX: This is not particularly secure.  We should
1619 	 * 	create our own conf and then copy in relevant
1620 	 * 	fields.
1621 	 */
1622 	isc->isc_initiator[ISCSI_NAME_LEN - 1] = '\0';
1623 	isc->isc_initiator_addr[ISCSI_ADDR_LEN - 1] = '\0';
1624 	isc->isc_initiator_alias[ISCSI_ALIAS_LEN - 1] = '\0';
1625 	isc->isc_target[ISCSI_NAME_LEN - 1] = '\0';
1626 	isc->isc_target_addr[ISCSI_ADDR_LEN - 1] = '\0';
1627 	isc->isc_user[ISCSI_NAME_LEN - 1] = '\0';
1628 	isc->isc_secret[ISCSI_SECRET_LEN - 1] = '\0';
1629 	isc->isc_mutual_user[ISCSI_NAME_LEN - 1] = '\0';
1630 	isc->isc_mutual_secret[ISCSI_SECRET_LEN - 1] = '\0';
1631 }
1632 
1633 static bool
1634 iscsi_valid_session_conf(const struct iscsi_session_conf *isc)
1635 {
1636 
1637 	if (isc->isc_initiator[0] == '\0') {
1638 		ISCSI_DEBUG("empty isc_initiator");
1639 		return (false);
1640 	}
1641 
1642 	if (isc->isc_target_addr[0] == '\0') {
1643 		ISCSI_DEBUG("empty isc_target_addr");
1644 		return (false);
1645 	}
1646 
1647 	if (isc->isc_discovery != 0 && isc->isc_target[0] != 0) {
1648 		ISCSI_DEBUG("non-empty isc_target for discovery session");
1649 		return (false);
1650 	}
1651 
1652 	if (isc->isc_discovery == 0 && isc->isc_target[0] == 0) {
1653 		ISCSI_DEBUG("empty isc_target for non-discovery session");
1654 		return (false);
1655 	}
1656 
1657 	return (true);
1658 }
1659 
1660 static int
1661 iscsi_ioctl_session_add(struct iscsi_softc *sc, struct iscsi_session_add *isa)
1662 {
1663 	struct iscsi_session *is;
1664 	const struct iscsi_session *is2;
1665 	int error;
1666 
1667 	iscsi_sanitize_session_conf(&isa->isa_conf);
1668 	if (iscsi_valid_session_conf(&isa->isa_conf) == false)
1669 		return (EINVAL);
1670 
1671 	is = malloc(sizeof(*is), M_ISCSI, M_ZERO | M_WAITOK);
1672 	memcpy(&is->is_conf, &isa->isa_conf, sizeof(is->is_conf));
1673 
1674 	sx_xlock(&sc->sc_lock);
1675 
1676 	/*
1677 	 * Prevent duplicates.
1678 	 */
1679 	TAILQ_FOREACH(is2, &sc->sc_sessions, is_next) {
1680 		if (!!is->is_conf.isc_discovery !=
1681 		    !!is2->is_conf.isc_discovery)
1682 			continue;
1683 
1684 		if (strcmp(is->is_conf.isc_target_addr,
1685 		    is2->is_conf.isc_target_addr) != 0)
1686 			continue;
1687 
1688 		if (is->is_conf.isc_discovery == 0 &&
1689 		    strcmp(is->is_conf.isc_target,
1690 		    is2->is_conf.isc_target) != 0)
1691 			continue;
1692 
1693 		sx_xunlock(&sc->sc_lock);
1694 		free(is, M_ISCSI);
1695 		return (EBUSY);
1696 	}
1697 
1698 	is->is_conn = icl_conn_new("iscsi", &is->is_lock);
1699 	is->is_conn->ic_receive = iscsi_receive_callback;
1700 	is->is_conn->ic_error = iscsi_error_callback;
1701 	is->is_conn->ic_prv0 = is;
1702 	TAILQ_INIT(&is->is_outstanding);
1703 	STAILQ_INIT(&is->is_postponed);
1704 	mtx_init(&is->is_lock, "iscsi_lock", NULL, MTX_DEF);
1705 	cv_init(&is->is_maintenance_cv, "iscsi_mt");
1706 #ifdef ICL_KERNEL_PROXY
1707 	cv_init(&is->is_login_cv, "iscsi_login");
1708 #endif
1709 
1710 	is->is_softc = sc;
1711 	sc->sc_last_session_id++;
1712 	is->is_id = sc->sc_last_session_id;
1713 	is->is_isid[0] = 0x80; /* RFC 3720, 10.12.5: 10b, "Random" ISID. */
1714 	arc4rand(&is->is_isid[1], 5, 0);
1715 	is->is_tsih = 0;
1716 	callout_init(&is->is_callout, 1);
1717 	callout_reset(&is->is_callout, 1 * hz, iscsi_callout, is);
1718 	TAILQ_INSERT_TAIL(&sc->sc_sessions, is, is_next);
1719 
1720 	error = kthread_add(iscsi_maintenance_thread, is, NULL, NULL, 0, 0, "iscsimt");
1721 	if (error != 0) {
1722 		ISCSI_SESSION_WARN(is, "kthread_add(9) failed with error %d", error);
1723 		return (error);
1724 	}
1725 
1726 	/*
1727 	 * Trigger immediate reconnection.
1728 	 */
1729 	ISCSI_SESSION_LOCK(is);
1730 	is->is_waiting_for_iscsid = true;
1731 	strlcpy(is->is_reason, "Waiting for iscsid(8)", sizeof(is->is_reason));
1732 	ISCSI_SESSION_UNLOCK(is);
1733 	cv_signal(&sc->sc_cv);
1734 
1735 	sx_xunlock(&sc->sc_lock);
1736 
1737 	return (0);
1738 }
1739 
1740 static bool
1741 iscsi_session_conf_matches(unsigned int id1, const struct iscsi_session_conf *c1,
1742     unsigned int id2, const struct iscsi_session_conf *c2)
1743 {
1744 	if (id2 == 0 && c2->isc_target[0] == '\0' &&
1745 	    c2->isc_target_addr[0] == '\0')
1746 		return (true);
1747 	if (id2 != 0 && id2 == id1)
1748 		return (true);
1749 	if (c2->isc_target[0] != '\0' &&
1750 	    strcmp(c1->isc_target, c2->isc_target) == 0)
1751 		return (true);
1752 	if (c2->isc_target_addr[0] != '\0' &&
1753 	    strcmp(c1->isc_target_addr, c2->isc_target_addr) == 0)
1754 		return (true);
1755 	return (false);
1756 }
1757 
1758 static int
1759 iscsi_ioctl_session_remove(struct iscsi_softc *sc,
1760     struct iscsi_session_remove *isr)
1761 {
1762 	struct iscsi_session *is, *tmp;
1763 	bool found = false;
1764 
1765 	iscsi_sanitize_session_conf(&isr->isr_conf);
1766 
1767 	sx_xlock(&sc->sc_lock);
1768 	TAILQ_FOREACH_SAFE(is, &sc->sc_sessions, is_next, tmp) {
1769 		ISCSI_SESSION_LOCK(is);
1770 		if (iscsi_session_conf_matches(is->is_id, &is->is_conf,
1771 		    isr->isr_session_id, &isr->isr_conf)) {
1772 			found = true;
1773 			iscsi_session_logout(is);
1774 			iscsi_session_terminate(is);
1775 		}
1776 		ISCSI_SESSION_UNLOCK(is);
1777 	}
1778 	sx_xunlock(&sc->sc_lock);
1779 
1780 	if (!found)
1781 		return (ESRCH);
1782 
1783 	return (0);
1784 }
1785 
1786 static int
1787 iscsi_ioctl_session_list(struct iscsi_softc *sc, struct iscsi_session_list *isl)
1788 {
1789 	int error;
1790 	unsigned int i = 0;
1791 	struct iscsi_session *is;
1792 	struct iscsi_session_state iss;
1793 
1794 	sx_slock(&sc->sc_lock);
1795 	TAILQ_FOREACH(is, &sc->sc_sessions, is_next) {
1796 		if (i >= isl->isl_nentries) {
1797 			sx_sunlock(&sc->sc_lock);
1798 			return (EMSGSIZE);
1799 		}
1800 		memset(&iss, 0, sizeof(iss));
1801 		memcpy(&iss.iss_conf, &is->is_conf, sizeof(iss.iss_conf));
1802 		iss.iss_id = is->is_id;
1803 		strlcpy(iss.iss_target_alias, is->is_target_alias, sizeof(iss.iss_target_alias));
1804 		strlcpy(iss.iss_reason, is->is_reason, sizeof(iss.iss_reason));
1805 
1806 		if (is->is_conn->ic_header_crc32c)
1807 			iss.iss_header_digest = ISCSI_DIGEST_CRC32C;
1808 		else
1809 			iss.iss_header_digest = ISCSI_DIGEST_NONE;
1810 
1811 		if (is->is_conn->ic_data_crc32c)
1812 			iss.iss_data_digest = ISCSI_DIGEST_CRC32C;
1813 		else
1814 			iss.iss_data_digest = ISCSI_DIGEST_NONE;
1815 
1816 		iss.iss_max_data_segment_length = is->is_max_data_segment_length;
1817 		iss.iss_immediate_data = is->is_immediate_data;
1818 		iss.iss_connected = is->is_connected;
1819 
1820 		error = copyout(&iss, isl->isl_pstates + i, sizeof(iss));
1821 		if (error != 0) {
1822 			sx_sunlock(&sc->sc_lock);
1823 			return (error);
1824 		}
1825 		i++;
1826 	}
1827 	sx_sunlock(&sc->sc_lock);
1828 
1829 	isl->isl_nentries = i;
1830 
1831 	return (0);
1832 }
1833 
1834 static int
1835 iscsi_ioctl_session_modify(struct iscsi_softc *sc,
1836     struct iscsi_session_modify *ism)
1837 {
1838 	struct iscsi_session *is;
1839 
1840 	iscsi_sanitize_session_conf(&ism->ism_conf);
1841 	if (iscsi_valid_session_conf(&ism->ism_conf) == false)
1842 		return (EINVAL);
1843 
1844 	sx_xlock(&sc->sc_lock);
1845 	TAILQ_FOREACH(is, &sc->sc_sessions, is_next) {
1846 		ISCSI_SESSION_LOCK(is);
1847 		if (is->is_id == ism->ism_session_id)
1848 			break;
1849 		ISCSI_SESSION_UNLOCK(is);
1850 	}
1851 	if (is == NULL) {
1852 		sx_xunlock(&sc->sc_lock);
1853 		return (ESRCH);
1854 	}
1855 	sx_xunlock(&sc->sc_lock);
1856 
1857 	memcpy(&is->is_conf, &ism->ism_conf, sizeof(is->is_conf));
1858 	ISCSI_SESSION_UNLOCK(is);
1859 
1860 	iscsi_session_reconnect(is);
1861 
1862 	return (0);
1863 }
1864 
1865 static int
1866 iscsi_ioctl(struct cdev *dev, u_long cmd, caddr_t arg, int mode,
1867     struct thread *td)
1868 {
1869 	struct iscsi_softc *sc;
1870 
1871 	sc = dev->si_drv1;
1872 
1873 	switch (cmd) {
1874 	case ISCSIDWAIT:
1875 		return (iscsi_ioctl_daemon_wait(sc,
1876 		    (struct iscsi_daemon_request *)arg));
1877 	case ISCSIDHANDOFF:
1878 		return (iscsi_ioctl_daemon_handoff(sc,
1879 		    (struct iscsi_daemon_handoff *)arg));
1880 	case ISCSIDFAIL:
1881 		return (iscsi_ioctl_daemon_fail(sc,
1882 		    (struct iscsi_daemon_fail *)arg));
1883 #ifdef ICL_KERNEL_PROXY
1884 	case ISCSIDCONNECT:
1885 		return (iscsi_ioctl_daemon_connect(sc,
1886 		    (struct iscsi_daemon_connect *)arg));
1887 	case ISCSIDSEND:
1888 		return (iscsi_ioctl_daemon_send(sc,
1889 		    (struct iscsi_daemon_send *)arg));
1890 	case ISCSIDRECEIVE:
1891 		return (iscsi_ioctl_daemon_receive(sc,
1892 		    (struct iscsi_daemon_receive *)arg));
1893 #endif /* ICL_KERNEL_PROXY */
1894 	case ISCSISADD:
1895 		return (iscsi_ioctl_session_add(sc,
1896 		    (struct iscsi_session_add *)arg));
1897 	case ISCSISREMOVE:
1898 		return (iscsi_ioctl_session_remove(sc,
1899 		    (struct iscsi_session_remove *)arg));
1900 	case ISCSISLIST:
1901 		return (iscsi_ioctl_session_list(sc,
1902 		    (struct iscsi_session_list *)arg));
1903 	case ISCSISMODIFY:
1904 		return (iscsi_ioctl_session_modify(sc,
1905 		    (struct iscsi_session_modify *)arg));
1906 	default:
1907 		return (EINVAL);
1908 	}
1909 }
1910 
1911 static struct iscsi_outstanding *
1912 iscsi_outstanding_find(struct iscsi_session *is, uint32_t initiator_task_tag)
1913 {
1914 	struct iscsi_outstanding *io;
1915 
1916 	ISCSI_SESSION_LOCK_ASSERT(is);
1917 
1918 	TAILQ_FOREACH(io, &is->is_outstanding, io_next) {
1919 		if (io->io_initiator_task_tag == initiator_task_tag)
1920 			return (io);
1921 	}
1922 	return (NULL);
1923 }
1924 
1925 static struct iscsi_outstanding *
1926 iscsi_outstanding_find_ccb(struct iscsi_session *is, union ccb *ccb)
1927 {
1928 	struct iscsi_outstanding *io;
1929 
1930 	ISCSI_SESSION_LOCK_ASSERT(is);
1931 
1932 	TAILQ_FOREACH(io, &is->is_outstanding, io_next) {
1933 		if (io->io_ccb == ccb)
1934 			return (io);
1935 	}
1936 	return (NULL);
1937 }
1938 
1939 static struct iscsi_outstanding *
1940 iscsi_outstanding_add(struct iscsi_session *is,
1941     uint32_t initiator_task_tag, union ccb *ccb)
1942 {
1943 	struct iscsi_outstanding *io;
1944 
1945 	ISCSI_SESSION_LOCK_ASSERT(is);
1946 
1947 	KASSERT(iscsi_outstanding_find(is, initiator_task_tag) == NULL,
1948 	    ("initiator_task_tag 0x%x already added", initiator_task_tag));
1949 
1950 	io = uma_zalloc(iscsi_outstanding_zone, M_NOWAIT | M_ZERO);
1951 	if (io == NULL) {
1952 		ISCSI_SESSION_WARN(is, "failed to allocate %zd bytes", sizeof(*io));
1953 		return (NULL);
1954 	}
1955 	io->io_initiator_task_tag = initiator_task_tag;
1956 	io->io_ccb = ccb;
1957 	TAILQ_INSERT_TAIL(&is->is_outstanding, io, io_next);
1958 	return (io);
1959 }
1960 
1961 static void
1962 iscsi_outstanding_remove(struct iscsi_session *is, struct iscsi_outstanding *io)
1963 {
1964 
1965 	ISCSI_SESSION_LOCK_ASSERT(is);
1966 
1967 	TAILQ_REMOVE(&is->is_outstanding, io, io_next);
1968 	uma_zfree(iscsi_outstanding_zone, io);
1969 }
1970 
1971 static void
1972 iscsi_action_abort(struct iscsi_session *is, union ccb *ccb)
1973 {
1974 	struct icl_pdu *request;
1975 	struct iscsi_bhs_task_management_request *bhstmr;
1976 	struct ccb_abort *cab = &ccb->cab;
1977 	struct iscsi_outstanding *io, *aio;
1978 
1979 	ISCSI_SESSION_LOCK_ASSERT(is);
1980 
1981 #if 0
1982 	KASSERT(is->is_login_phase == false, ("%s called during Login Phase", __func__));
1983 #else
1984 	if (is->is_login_phase) {
1985 		ccb->ccb_h.status = CAM_REQ_ABORTED;
1986 		xpt_done(ccb);
1987 		return;
1988 	}
1989 #endif
1990 
1991 	aio = iscsi_outstanding_find_ccb(is, cab->abort_ccb);
1992 	if (aio == NULL) {
1993 		ccb->ccb_h.status = CAM_REQ_CMP;
1994 		xpt_done(ccb);
1995 		return;
1996 	}
1997 
1998 	request = icl_pdu_new_bhs(is->is_conn, M_NOWAIT);
1999 	if (request == NULL) {
2000 		ccb->ccb_h.status = CAM_RESRC_UNAVAIL;
2001 		xpt_done(ccb);
2002 		return;
2003 	}
2004 
2005 	bhstmr = (struct iscsi_bhs_task_management_request *)request->ip_bhs;
2006 	bhstmr->bhstmr_opcode = ISCSI_BHS_OPCODE_TASK_REQUEST;
2007 	bhstmr->bhstmr_function = 0x80 | BHSTMR_FUNCTION_ABORT_TASK;
2008 
2009 	bhstmr->bhstmr_lun = htobe64(CAM_EXTLUN_BYTE_SWIZZLE(ccb->ccb_h.target_lun));
2010 	bhstmr->bhstmr_initiator_task_tag = is->is_initiator_task_tag;
2011 	is->is_initiator_task_tag++;
2012 	bhstmr->bhstmr_referenced_task_tag = aio->io_initiator_task_tag;
2013 
2014 	io = iscsi_outstanding_add(is, bhstmr->bhstmr_initiator_task_tag, NULL);
2015 	if (io == NULL) {
2016 		icl_pdu_free(request);
2017 		ccb->ccb_h.status = CAM_RESRC_UNAVAIL;
2018 		xpt_done(ccb);
2019 		return;
2020 	}
2021 	io->io_datasn = aio->io_initiator_task_tag;
2022 	iscsi_pdu_queue_locked(request);
2023 }
2024 
2025 static void
2026 iscsi_action_scsiio(struct iscsi_session *is, union ccb *ccb)
2027 {
2028 	struct icl_pdu *request;
2029 	struct iscsi_bhs_scsi_command *bhssc;
2030 	struct ccb_scsiio *csio;
2031 	struct iscsi_outstanding *io;
2032 	size_t len;
2033 	int error;
2034 
2035 	ISCSI_SESSION_LOCK_ASSERT(is);
2036 
2037 #if 0
2038 	KASSERT(is->is_login_phase == false, ("%s called during Login Phase", __func__));
2039 #else
2040 	if (is->is_login_phase) {
2041 		ISCSI_SESSION_DEBUG(is, "called during login phase");
2042 		if ((ccb->ccb_h.status & CAM_DEV_QFRZN) == 0) {
2043 			xpt_freeze_devq(ccb->ccb_h.path, 1);
2044 			ISCSI_SESSION_DEBUG(is, "freezing devq");
2045 		}
2046 		ccb->ccb_h.status = CAM_REQ_ABORTED | CAM_DEV_QFRZN;
2047 		xpt_done(ccb);
2048 		return;
2049 	}
2050 #endif
2051 
2052 	request = icl_pdu_new_bhs(is->is_conn, M_NOWAIT);
2053 	if (request == NULL) {
2054 		if ((ccb->ccb_h.status & CAM_DEV_QFRZN) == 0) {
2055 			xpt_freeze_devq(ccb->ccb_h.path, 1);
2056 			ISCSI_SESSION_DEBUG(is, "freezing devq");
2057 		}
2058 		ccb->ccb_h.status = CAM_RESRC_UNAVAIL | CAM_DEV_QFRZN;
2059 		xpt_done(ccb);
2060 		return;
2061 	}
2062 
2063 	csio = &ccb->csio;
2064 	bhssc = (struct iscsi_bhs_scsi_command *)request->ip_bhs;
2065 	bhssc->bhssc_opcode = ISCSI_BHS_OPCODE_SCSI_COMMAND;
2066 	bhssc->bhssc_flags |= BHSSC_FLAGS_F;
2067 	switch (csio->ccb_h.flags & CAM_DIR_MASK) {
2068 	case CAM_DIR_IN:
2069 		bhssc->bhssc_flags |= BHSSC_FLAGS_R;
2070 		break;
2071 	case CAM_DIR_OUT:
2072 		bhssc->bhssc_flags |= BHSSC_FLAGS_W;
2073 		break;
2074 	}
2075 
2076 	if ((ccb->ccb_h.flags & CAM_TAG_ACTION_VALID) != 0) {
2077 		switch (csio->tag_action) {
2078 		case MSG_HEAD_OF_Q_TAG:
2079 			bhssc->bhssc_flags |= BHSSC_FLAGS_ATTR_HOQ;
2080 			break;
2081 		case MSG_ORDERED_Q_TAG:
2082 			bhssc->bhssc_flags |= BHSSC_FLAGS_ATTR_ORDERED;
2083 			break;
2084 		case MSG_ACA_TASK:
2085 			bhssc->bhssc_flags |= BHSSC_FLAGS_ATTR_ACA;
2086 			break;
2087 		case MSG_SIMPLE_Q_TAG:
2088 		default:
2089 			bhssc->bhssc_flags |= BHSSC_FLAGS_ATTR_SIMPLE;
2090 			break;
2091 		}
2092 	} else
2093 		bhssc->bhssc_flags |= BHSSC_FLAGS_ATTR_UNTAGGED;
2094 
2095 	bhssc->bhssc_lun = htobe64(CAM_EXTLUN_BYTE_SWIZZLE(ccb->ccb_h.target_lun));
2096 	bhssc->bhssc_initiator_task_tag = is->is_initiator_task_tag;
2097 	is->is_initiator_task_tag++;
2098 	bhssc->bhssc_expected_data_transfer_length = htonl(csio->dxfer_len);
2099 	KASSERT(csio->cdb_len <= sizeof(bhssc->bhssc_cdb),
2100 	    ("unsupported CDB size %zd", (size_t)csio->cdb_len));
2101 
2102 	if (csio->ccb_h.flags & CAM_CDB_POINTER)
2103 		memcpy(&bhssc->bhssc_cdb, csio->cdb_io.cdb_ptr, csio->cdb_len);
2104 	else
2105 		memcpy(&bhssc->bhssc_cdb, csio->cdb_io.cdb_bytes, csio->cdb_len);
2106 
2107 	io = iscsi_outstanding_add(is, bhssc->bhssc_initiator_task_tag, ccb);
2108 	if (io == NULL) {
2109 		icl_pdu_free(request);
2110 		if ((ccb->ccb_h.status & CAM_DEV_QFRZN) == 0) {
2111 			xpt_freeze_devq(ccb->ccb_h.path, 1);
2112 			ISCSI_SESSION_DEBUG(is, "freezing devq");
2113 		}
2114 		ccb->ccb_h.status = CAM_RESRC_UNAVAIL | CAM_DEV_QFRZN;
2115 		xpt_done(ccb);
2116 		return;
2117 	}
2118 
2119 	if (is->is_immediate_data &&
2120 	    (csio->ccb_h.flags & CAM_DIR_MASK) == CAM_DIR_OUT) {
2121 		len = csio->dxfer_len;
2122 		//ISCSI_SESSION_DEBUG(is, "adding %zd of immediate data", len);
2123 		if (len > is->is_first_burst_length) {
2124 			ISCSI_SESSION_DEBUG(is, "len %zd -> %zd", len, is->is_first_burst_length);
2125 			len = is->is_first_burst_length;
2126 		}
2127 
2128 		error = icl_pdu_append_data(request, csio->data_ptr, len, M_NOWAIT);
2129 		if (error != 0) {
2130 			icl_pdu_free(request);
2131 			if ((ccb->ccb_h.status & CAM_DEV_QFRZN) == 0) {
2132 				xpt_freeze_devq(ccb->ccb_h.path, 1);
2133 				ISCSI_SESSION_DEBUG(is, "freezing devq");
2134 			}
2135 			ccb->ccb_h.status = CAM_RESRC_UNAVAIL | CAM_DEV_QFRZN;
2136 			xpt_done(ccb);
2137 			return;
2138 		}
2139 	}
2140 	iscsi_pdu_queue_locked(request);
2141 }
2142 
2143 static void
2144 iscsi_action(struct cam_sim *sim, union ccb *ccb)
2145 {
2146 	struct iscsi_session *is;
2147 
2148 	is = cam_sim_softc(sim);
2149 
2150 	ISCSI_SESSION_LOCK_ASSERT(is);
2151 
2152 	if (is->is_terminating ||
2153 	    (is->is_connected == false && fail_on_disconnection)) {
2154 		ccb->ccb_h.status = CAM_DEV_NOT_THERE;
2155 		xpt_done(ccb);
2156 		return;
2157 	}
2158 
2159 	switch (ccb->ccb_h.func_code) {
2160 	case XPT_PATH_INQ:
2161 	{
2162 		struct ccb_pathinq *cpi = &ccb->cpi;
2163 
2164 		cpi->version_num = 1;
2165 		cpi->hba_inquiry = PI_TAG_ABLE;
2166 		cpi->target_sprt = 0;
2167 		cpi->hba_misc = PIM_EXTLUNS;
2168 		cpi->hba_eng_cnt = 0;
2169 		cpi->max_target = 0;
2170 		cpi->max_lun = 0;
2171 		cpi->initiator_id = ~0;
2172 		strlcpy(cpi->sim_vid, "FreeBSD", SIM_IDLEN);
2173 		strlcpy(cpi->hba_vid, "iSCSI", HBA_IDLEN);
2174 		strlcpy(cpi->dev_name, cam_sim_name(sim), DEV_IDLEN);
2175 		cpi->unit_number = cam_sim_unit(sim);
2176 		cpi->bus_id = cam_sim_bus(sim);
2177 		cpi->base_transfer_speed = 150000; /* XXX */
2178 		cpi->transport = XPORT_ISCSI;
2179 		cpi->transport_version = 0;
2180 		cpi->protocol = PROTO_SCSI;
2181 		cpi->protocol_version = SCSI_REV_SPC3;
2182 		cpi->maxio = MAXPHYS;
2183 		cpi->ccb_h.status = CAM_REQ_CMP;
2184 		break;
2185 	}
2186 	case XPT_GET_TRAN_SETTINGS:
2187 	{
2188 		struct ccb_trans_settings	*cts;
2189 		struct ccb_trans_settings_scsi	*scsi;
2190 
2191 		cts = &ccb->cts;
2192 		scsi = &cts->proto_specific.scsi;
2193 
2194 		cts->protocol = PROTO_SCSI;
2195 		cts->protocol_version = SCSI_REV_SPC3;
2196 		cts->transport = XPORT_ISCSI;
2197 		cts->transport_version = 0;
2198 		scsi->valid = CTS_SCSI_VALID_TQ;
2199 		scsi->flags = CTS_SCSI_FLAGS_TAG_ENB;
2200 		cts->ccb_h.status = CAM_REQ_CMP;
2201 		break;
2202 	}
2203 	case XPT_CALC_GEOMETRY:
2204 		cam_calc_geometry(&ccb->ccg, /*extended*/1);
2205 		ccb->ccb_h.status = CAM_REQ_CMP;
2206 		break;
2207 #if 0
2208 	/*
2209 	 * XXX: What's the point?
2210 	 */
2211 	case XPT_RESET_BUS:
2212 	case XPT_TERM_IO:
2213 		ISCSI_SESSION_DEBUG(is, "faking success for reset, abort, or term_io");
2214 		ccb->ccb_h.status = CAM_REQ_CMP;
2215 		break;
2216 #endif
2217 	case XPT_ABORT:
2218 		iscsi_action_abort(is, ccb);
2219 		return;
2220 	case XPT_SCSI_IO:
2221 		iscsi_action_scsiio(is, ccb);
2222 		return;
2223 	default:
2224 #if 0
2225 		ISCSI_SESSION_DEBUG(is, "got unsupported code 0x%x", ccb->ccb_h.func_code);
2226 #endif
2227 		ccb->ccb_h.status = CAM_FUNC_NOTAVAIL;
2228 		break;
2229 	}
2230 	xpt_done(ccb);
2231 }
2232 
2233 static void
2234 iscsi_poll(struct cam_sim *sim)
2235 {
2236 
2237 	KASSERT(0, ("%s: you're not supposed to be here", __func__));
2238 }
2239 
2240 static void
2241 iscsi_shutdown(struct iscsi_softc *sc)
2242 {
2243 	struct iscsi_session *is;
2244 
2245 	ISCSI_DEBUG("removing all sessions due to shutdown");
2246 
2247 	sx_slock(&sc->sc_lock);
2248 	TAILQ_FOREACH(is, &sc->sc_sessions, is_next)
2249 		iscsi_session_terminate(is);
2250 	sx_sunlock(&sc->sc_lock);
2251 }
2252 
2253 static int
2254 iscsi_load(void)
2255 {
2256 	int error;
2257 
2258 	sc = malloc(sizeof(*sc), M_ISCSI, M_ZERO | M_WAITOK);
2259 	sx_init(&sc->sc_lock, "iscsi");
2260 	TAILQ_INIT(&sc->sc_sessions);
2261 	cv_init(&sc->sc_cv, "iscsi_cv");
2262 
2263 	iscsi_outstanding_zone = uma_zcreate("iscsi_outstanding",
2264 	    sizeof(struct iscsi_outstanding), NULL, NULL, NULL, NULL,
2265 	    UMA_ALIGN_PTR, 0);
2266 
2267 	error = make_dev_p(MAKEDEV_CHECKNAME, &sc->sc_cdev, &iscsi_cdevsw,
2268 	    NULL, UID_ROOT, GID_WHEEL, 0600, "iscsi");
2269 	if (error != 0) {
2270 		ISCSI_WARN("failed to create device node, error %d", error);
2271 		return (error);
2272 	}
2273 	sc->sc_cdev->si_drv1 = sc;
2274 
2275 	/*
2276 	 * Note that this needs to get run before dashutdown().  Otherwise,
2277 	 * when rebooting with iSCSI session with outstanding requests,
2278 	 * but disconnected, dashutdown() will hang on cam_periph_runccb().
2279 	 */
2280 	sc->sc_shutdown_eh = EVENTHANDLER_REGISTER(shutdown_post_sync,
2281 	    iscsi_shutdown, sc, SHUTDOWN_PRI_FIRST);
2282 
2283 	return (0);
2284 }
2285 
2286 static int
2287 iscsi_unload(void)
2288 {
2289 	struct iscsi_session *is, *tmp;
2290 
2291 	if (sc->sc_cdev != NULL) {
2292 		ISCSI_DEBUG("removing device node");
2293 		destroy_dev(sc->sc_cdev);
2294 		ISCSI_DEBUG("device node removed");
2295 	}
2296 
2297 	if (sc->sc_shutdown_eh != NULL)
2298 		EVENTHANDLER_DEREGISTER(shutdown_post_sync, sc->sc_shutdown_eh);
2299 
2300 	sx_slock(&sc->sc_lock);
2301 	TAILQ_FOREACH_SAFE(is, &sc->sc_sessions, is_next, tmp)
2302 		iscsi_session_terminate(is);
2303 	while(!TAILQ_EMPTY(&sc->sc_sessions)) {
2304 		ISCSI_DEBUG("waiting for sessions to terminate");
2305 		cv_wait(&sc->sc_cv, &sc->sc_lock);
2306 	}
2307 	ISCSI_DEBUG("all sessions terminated");
2308 	sx_sunlock(&sc->sc_lock);
2309 
2310 	uma_zdestroy(iscsi_outstanding_zone);
2311 	sx_destroy(&sc->sc_lock);
2312 	cv_destroy(&sc->sc_cv);
2313 	free(sc, M_ISCSI);
2314 	return (0);
2315 }
2316 
2317 static int
2318 iscsi_quiesce(void)
2319 {
2320 	sx_slock(&sc->sc_lock);
2321 	if (!TAILQ_EMPTY(&sc->sc_sessions)) {
2322 		sx_sunlock(&sc->sc_lock);
2323 		return (EBUSY);
2324 	}
2325 	sx_sunlock(&sc->sc_lock);
2326 	return (0);
2327 }
2328 
2329 static int
2330 iscsi_modevent(module_t mod, int what, void *arg)
2331 {
2332 	int error;
2333 
2334 	switch (what) {
2335 	case MOD_LOAD:
2336 		error = iscsi_load();
2337 		break;
2338 	case MOD_UNLOAD:
2339 		error = iscsi_unload();
2340 		break;
2341 	case MOD_QUIESCE:
2342 		error = iscsi_quiesce();
2343 		break;
2344 	default:
2345 		error = EINVAL;
2346 		break;
2347 	}
2348 	return (error);
2349 }
2350 
2351 moduledata_t iscsi_data = {
2352 	"iscsi",
2353 	iscsi_modevent,
2354 	0
2355 };
2356 
2357 DECLARE_MODULE(iscsi, iscsi_data, SI_SUB_DRIVERS, SI_ORDER_MIDDLE);
2358 MODULE_DEPEND(iscsi, cam, 1, 1, 1);
2359 MODULE_DEPEND(iscsi, icl, 1, 1, 1);
2360