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