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