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