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