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