xref: /freebsd/sys/dev/iscsi/iscsi.c (revision ce3adf4362fcca6a43e500b2531f0038adbfbd21)
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_WAITOK);
562 	bhsno = (struct iscsi_bhs_nop_out *)request->ip_bhs;
563 	bhsno->bhsno_opcode = ISCSI_BHS_OPCODE_NOP_OUT |
564 	    ISCSI_BHS_OPCODE_IMMEDIATE;
565 	bhsno->bhsno_flags = 0x80;
566 	bhsno->bhsno_target_transfer_tag = 0xffffffff;
567 	iscsi_pdu_queue(request);
568 	return;
569 
570 out:
571 	ISCSI_SESSION_UNLOCK(is);
572 
573 	if (reconnect_needed)
574 		iscsi_session_reconnect(is);
575 }
576 
577 static void
578 iscsi_pdu_update_statsn(const struct icl_pdu *response)
579 {
580 	const struct iscsi_bhs_data_in *bhsdi;
581 	struct iscsi_session *is;
582 	uint32_t expcmdsn, maxcmdsn;
583 
584 	is = PDU_SESSION(response);
585 
586 	ISCSI_SESSION_LOCK_ASSERT(is);
587 
588 	/*
589 	 * We're only using fields common for all the response
590 	 * (target -> initiator) PDUs.
591 	 */
592 	bhsdi = (const struct iscsi_bhs_data_in *)response->ip_bhs;
593 	/*
594 	 * Ok, I lied.  In case of Data-In, "The fields StatSN, Status,
595 	 * and Residual Count only have meaningful content if the S bit
596 	 * is set to 1", so we also need to check the bit specific for
597 	 * Data-In PDU.
598 	 */
599 	if (bhsdi->bhsdi_opcode != ISCSI_BHS_OPCODE_SCSI_DATA_IN ||
600 	    (bhsdi->bhsdi_flags & BHSDI_FLAGS_S) != 0) {
601 		if (ntohl(bhsdi->bhsdi_statsn) < is->is_statsn) {
602 			ISCSI_SESSION_WARN(is,
603 			    "PDU StatSN %d >= session StatSN %d, opcode 0x%x",
604 			    is->is_statsn, ntohl(bhsdi->bhsdi_statsn),
605 			    bhsdi->bhsdi_opcode);
606 		}
607 		is->is_statsn = ntohl(bhsdi->bhsdi_statsn);
608 	}
609 
610 	expcmdsn = ntohl(bhsdi->bhsdi_expcmdsn);
611 	maxcmdsn = ntohl(bhsdi->bhsdi_maxcmdsn);
612 
613 	/*
614 	 * XXX: Compare using Serial Arithmetic Sense.
615 	 */
616 	if (maxcmdsn + 1 < expcmdsn) {
617 		ISCSI_SESSION_DEBUG(is, "PDU MaxCmdSN %d + 1 < PDU ExpCmdSN %d; ignoring",
618 		    maxcmdsn, expcmdsn);
619 	} else {
620 		if (maxcmdsn > is->is_maxcmdsn) {
621 			is->is_maxcmdsn = maxcmdsn;
622 
623 			/*
624 			 * Command window increased; kick the maintanance thread
625 			 * to send out postponed commands.
626 			 */
627 			if (!TAILQ_EMPTY(&is->is_postponed))
628 				cv_signal(&is->is_maintenance_cv);
629 		} else if (maxcmdsn < is->is_maxcmdsn) {
630 			ISCSI_SESSION_DEBUG(is, "PDU MaxCmdSN %d < session MaxCmdSN %d; ignoring",
631 			    maxcmdsn, is->is_maxcmdsn);
632 		}
633 
634 		if (expcmdsn > is->is_expcmdsn) {
635 			is->is_expcmdsn = expcmdsn;
636 		} else if (expcmdsn < is->is_expcmdsn) {
637 			ISCSI_SESSION_DEBUG(is, "PDU ExpCmdSN %d < session ExpCmdSN %d; ignoring",
638 			    expcmdsn, is->is_expcmdsn);
639 		}
640 	}
641 
642 	/*
643 	 * Every incoming PDU - not just NOP-In - resets the ping timer.
644 	 * The purpose of the timeout is to reset the connection when it stalls;
645 	 * we don't want this to happen when NOP-In or NOP-Out ends up delayed
646 	 * in some queue.
647 	 */
648 	is->is_timeout = 0;
649 }
650 
651 static void
652 iscsi_receive_callback(struct icl_pdu *response)
653 {
654 	struct iscsi_session *is;
655 
656 	is = PDU_SESSION(response);
657 
658 	ISCSI_SESSION_LOCK(is);
659 
660 #ifdef ICL_KERNEL_PROXY
661 	if (is->is_login_phase) {
662 		if (is->is_login_pdu == NULL)
663 			is->is_login_pdu = response;
664 		else
665 			icl_pdu_free(response);
666 		ISCSI_SESSION_UNLOCK(is);
667 		cv_signal(&is->is_login_cv);
668 		return;
669 	}
670 #endif
671 
672 	iscsi_pdu_update_statsn(response);
673 
674 	/*
675 	 * The handling routine is responsible for freeing the PDU
676 	 * when it's no longer needed.
677 	 */
678 	switch (response->ip_bhs->bhs_opcode) {
679 	case ISCSI_BHS_OPCODE_NOP_IN:
680 		iscsi_pdu_handle_nop_in(response);
681 		break;
682 	case ISCSI_BHS_OPCODE_SCSI_RESPONSE:
683 		iscsi_pdu_handle_scsi_response(response);
684 		break;
685 	case ISCSI_BHS_OPCODE_SCSI_DATA_IN:
686 		iscsi_pdu_handle_data_in(response);
687 		break;
688 	case ISCSI_BHS_OPCODE_LOGOUT_RESPONSE:
689 		iscsi_pdu_handle_logout_response(response);
690 		break;
691 	case ISCSI_BHS_OPCODE_R2T:
692 		iscsi_pdu_handle_r2t(response);
693 		break;
694 	case ISCSI_BHS_OPCODE_ASYNC_MESSAGE:
695 		iscsi_pdu_handle_async_message(response);
696 		break;
697 	case ISCSI_BHS_OPCODE_REJECT:
698 		iscsi_pdu_handle_reject(response);
699 		break;
700 	default:
701 		ISCSI_SESSION_WARN(is, "received PDU with unsupported "
702 		    "opcode 0x%x; reconnecting",
703 		    response->ip_bhs->bhs_opcode);
704 		iscsi_session_reconnect(is);
705 		icl_pdu_free(response);
706 	}
707 
708 	ISCSI_SESSION_UNLOCK(is);
709 }
710 
711 static void
712 iscsi_error_callback(struct icl_conn *ic)
713 {
714 	struct iscsi_session *is;
715 
716 	is = CONN_SESSION(ic);
717 
718 	ISCSI_SESSION_WARN(is, "connection error; reconnecting");
719 	iscsi_session_reconnect(is);
720 }
721 
722 static void
723 iscsi_pdu_handle_nop_in(struct icl_pdu *response)
724 {
725 	struct iscsi_bhs_nop_out *bhsno;
726 	struct iscsi_bhs_nop_in *bhsni;
727 	struct icl_pdu *request;
728 
729 	bhsni = (struct iscsi_bhs_nop_in *)response->ip_bhs;
730 
731 	if (bhsni->bhsni_target_transfer_tag == 0xffffffff) {
732 		/*
733 		 * Nothing to do; iscsi_pdu_update_statsn() already
734 		 * zeroed the timeout.
735 		 */
736 		icl_pdu_free(response);
737 		return;
738 	}
739 
740 	request = icl_pdu_new_bhs(response->ip_conn, M_NOWAIT);
741 	if (request == NULL) {
742 		icl_pdu_free(response);
743 		return;
744 	}
745 	bhsno = (struct iscsi_bhs_nop_out *)request->ip_bhs;
746 	bhsno->bhsno_opcode = ISCSI_BHS_OPCODE_NOP_OUT |
747 	    ISCSI_BHS_OPCODE_IMMEDIATE;
748 	bhsno->bhsno_flags = 0x80;
749 	bhsno->bhsno_initiator_task_tag = 0xffffffff; /* XXX */
750 	bhsno->bhsno_target_transfer_tag = bhsni->bhsni_target_transfer_tag;
751 
752 	request->ip_data_len = response->ip_data_len;
753 	request->ip_data_mbuf = response->ip_data_mbuf;
754 	response->ip_data_len = 0;
755 	response->ip_data_mbuf = NULL;
756 
757 	icl_pdu_free(response);
758 	iscsi_pdu_queue_locked(request);
759 }
760 
761 static void
762 iscsi_pdu_handle_scsi_response(struct icl_pdu *response)
763 {
764 	struct iscsi_bhs_scsi_response *bhssr;
765 	struct iscsi_outstanding *io;
766 	struct iscsi_session *is;
767 	struct ccb_scsiio *csio;
768 	size_t data_segment_len;
769 	uint16_t sense_len;
770 
771 	is = PDU_SESSION(response);
772 
773 	bhssr = (struct iscsi_bhs_scsi_response *)response->ip_bhs;
774 	io = iscsi_outstanding_find(is, bhssr->bhssr_initiator_task_tag);
775 	if (io == NULL) {
776 		ISCSI_SESSION_WARN(is, "bad itt 0x%x", bhssr->bhssr_initiator_task_tag);
777 		icl_pdu_free(response);
778 		iscsi_session_reconnect(is);
779 		return;
780 	}
781 
782 	if (bhssr->bhssr_response != BHSSR_RESPONSE_COMMAND_COMPLETED) {
783 		ISCSI_SESSION_WARN(is, "service response 0x%x", bhssr->bhssr_response);
784  		if ((io->io_ccb->ccb_h.status & CAM_DEV_QFRZN) == 0) {
785  			xpt_freeze_devq(io->io_ccb->ccb_h.path, 1);
786 			ISCSI_SESSION_DEBUG(is, "freezing devq");
787 		}
788  		io->io_ccb->ccb_h.status = CAM_REQ_CMP_ERR | CAM_DEV_QFRZN;
789 	} else if (bhssr->bhssr_status == 0) {
790 		io->io_ccb->ccb_h.status = CAM_REQ_CMP;
791 	} else {
792  		if ((io->io_ccb->ccb_h.status & CAM_DEV_QFRZN) == 0) {
793  			xpt_freeze_devq(io->io_ccb->ccb_h.path, 1);
794 			ISCSI_SESSION_DEBUG(is, "freezing devq");
795 		}
796  		io->io_ccb->ccb_h.status = CAM_SCSI_STATUS_ERROR | CAM_DEV_QFRZN;
797 		io->io_ccb->csio.scsi_status = bhssr->bhssr_status;
798 	}
799 
800 	if (bhssr->bhssr_flags & BHSSR_FLAGS_RESIDUAL_OVERFLOW) {
801 		ISCSI_SESSION_WARN(is, "target indicated residual overflow");
802 		icl_pdu_free(response);
803 		iscsi_session_reconnect(is);
804 		return;
805 	}
806 
807 	csio = &io->io_ccb->csio;
808 
809 	data_segment_len = icl_pdu_data_segment_length(response);
810 	if (data_segment_len > 0) {
811 		if (data_segment_len < sizeof(sense_len)) {
812 			ISCSI_SESSION_WARN(is, "truncated data segment (%zd bytes)",
813 			    data_segment_len);
814 			if ((io->io_ccb->ccb_h.status & CAM_DEV_QFRZN) == 0) {
815 				xpt_freeze_devq(io->io_ccb->ccb_h.path, 1);
816 				ISCSI_SESSION_DEBUG(is, "freezing devq");
817 			}
818 			io->io_ccb->ccb_h.status = CAM_REQ_CMP_ERR | CAM_DEV_QFRZN;
819 			goto out;
820 		}
821 		icl_pdu_get_data(response, 0, &sense_len, sizeof(sense_len));
822 		sense_len = ntohs(sense_len);
823 #if 0
824 		ISCSI_SESSION_DEBUG(is, "sense_len %d, data len %zd",
825 		    sense_len, data_segment_len);
826 #endif
827 		if (sizeof(sense_len) + sense_len > data_segment_len) {
828 			ISCSI_SESSION_WARN(is, "truncated data segment "
829 			    "(%zd bytes, should be %zd)",
830 			    data_segment_len, sizeof(sense_len) + sense_len);
831 			if ((io->io_ccb->ccb_h.status & CAM_DEV_QFRZN) == 0) {
832 				xpt_freeze_devq(io->io_ccb->ccb_h.path, 1);
833 				ISCSI_SESSION_DEBUG(is, "freezing devq");
834 			}
835 			io->io_ccb->ccb_h.status = CAM_REQ_CMP_ERR | CAM_DEV_QFRZN;
836 			goto out;
837 		} else if (sizeof(sense_len) + sense_len < data_segment_len)
838 			ISCSI_SESSION_WARN(is, "oversize data segment "
839 			    "(%zd bytes, should be %zd)",
840 			    data_segment_len, sizeof(sense_len) + sense_len);
841 		if (sense_len > csio->sense_len) {
842 			ISCSI_SESSION_DEBUG(is, "truncating sense from %d to %d",
843 			    sense_len, csio->sense_len);
844 			sense_len = csio->sense_len;
845 		}
846 		icl_pdu_get_data(response, sizeof(sense_len), &csio->sense_data, sense_len);
847 		csio->sense_resid = csio->sense_len - sense_len;
848 		io->io_ccb->ccb_h.status |= CAM_AUTOSNS_VALID;
849 	}
850 
851 out:
852 	if (bhssr->bhssr_flags & BHSSR_FLAGS_RESIDUAL_UNDERFLOW)
853 		csio->resid = ntohl(bhssr->bhssr_residual_count);
854 
855 	if ((csio->ccb_h.flags & CAM_DIR_MASK) == CAM_DIR_IN) {
856 		KASSERT(io->io_received <= csio->dxfer_len,
857 		    ("io->io_received > csio->dxfer_len"));
858 		if (io->io_received < csio->dxfer_len) {
859 			if (csio->resid != csio->dxfer_len - io->io_received) {
860 				ISCSI_SESSION_WARN(is, "underflow mismatch: "
861 				    "target indicates %d, we calculated %zd",
862 				    csio->resid,
863 				    csio->dxfer_len - io->io_received);
864 			}
865 			csio->resid = csio->dxfer_len - io->io_received;
866 		}
867 	}
868 
869 	xpt_done(io->io_ccb);
870 	iscsi_outstanding_remove(is, io);
871 	icl_pdu_free(response);
872 }
873 
874 static void
875 iscsi_pdu_handle_data_in(struct icl_pdu *response)
876 {
877 	struct iscsi_bhs_data_in *bhsdi;
878 	struct iscsi_outstanding *io;
879 	struct iscsi_session *is;
880 	struct ccb_scsiio *csio;
881 	size_t data_segment_len;
882 
883 	is = PDU_SESSION(response);
884 	bhsdi = (struct iscsi_bhs_data_in *)response->ip_bhs;
885 	io = iscsi_outstanding_find(is, bhsdi->bhsdi_initiator_task_tag);
886 	if (io == NULL) {
887 		ISCSI_SESSION_WARN(is, "bad itt 0x%x", bhsdi->bhsdi_initiator_task_tag);
888 		icl_pdu_free(response);
889 		iscsi_session_reconnect(is);
890 		return;
891 	}
892 
893 	data_segment_len = icl_pdu_data_segment_length(response);
894 	if (data_segment_len == 0) {
895 		/*
896 		 * "The sending of 0 length data segments should be avoided,
897 		 * but initiators and targets MUST be able to properly receive
898 		 * 0 length data segments."
899 		 */
900 		icl_pdu_free(response);
901 		return;
902 	}
903 
904 	/*
905 	 * We need to track this for security reasons - without it, malicious target
906 	 * could respond to SCSI READ without sending Data-In PDUs, which would result
907 	 * in read operation on the initiator side returning random kernel data.
908 	 */
909 	if (ntohl(bhsdi->bhsdi_buffer_offset) != io->io_received) {
910 		ISCSI_SESSION_WARN(is, "data out of order; expected offset %zd, got %zd",
911 		    io->io_received, (size_t)ntohl(bhsdi->bhsdi_buffer_offset));
912 		icl_pdu_free(response);
913 		iscsi_session_reconnect(is);
914 		return;
915 	}
916 
917 	csio = &io->io_ccb->csio;
918 
919 	if (ntohl(bhsdi->bhsdi_buffer_offset) + data_segment_len >
920 	    csio->dxfer_len) {
921 		ISCSI_SESSION_WARN(is, "oversize data segment (%zd bytes "
922 		    "at offset %d, buffer is %d)",
923 		    data_segment_len, ntohl(bhsdi->bhsdi_buffer_offset),
924 		    csio->dxfer_len);
925 		icl_pdu_free(response);
926 		iscsi_session_reconnect(is);
927 		return;
928 	}
929 
930 	icl_pdu_get_data(response, 0, csio->data_ptr + ntohl(bhsdi->bhsdi_buffer_offset), data_segment_len);
931 	io->io_received += data_segment_len;
932 
933 	/*
934 	 * XXX: Check DataSN.
935 	 * XXX: Check F.
936 	 */
937 	if (bhsdi->bhsdi_flags & BHSDI_FLAGS_S) {
938 		//ISCSI_SESSION_DEBUG(is, "got S flag; status 0x%x", bhsdi->bhsdi_status);
939 		if (bhsdi->bhsdi_status == 0) {
940 			io->io_ccb->ccb_h.status = CAM_REQ_CMP;
941 		} else {
942 			if ((io->io_ccb->ccb_h.status & CAM_DEV_QFRZN) == 0) {
943 				xpt_freeze_devq(io->io_ccb->ccb_h.path, 1);
944 				ISCSI_SESSION_DEBUG(is, "freezing devq");
945 			}
946 			io->io_ccb->ccb_h.status = CAM_SCSI_STATUS_ERROR | CAM_DEV_QFRZN;
947 			csio->scsi_status = bhsdi->bhsdi_status;
948 		}
949 		xpt_done(io->io_ccb);
950 		iscsi_outstanding_remove(is, io);
951 	}
952 
953 	icl_pdu_free(response);
954 }
955 
956 static void
957 iscsi_pdu_handle_logout_response(struct icl_pdu *response)
958 {
959 
960 	ISCSI_SESSION_DEBUG(PDU_SESSION(response), "logout response");
961 	icl_pdu_free(response);
962 }
963 
964 static void
965 iscsi_pdu_handle_r2t(struct icl_pdu *response)
966 {
967 	struct icl_pdu *request;
968 	struct iscsi_session *is;
969 	struct iscsi_bhs_r2t *bhsr2t;
970 	struct iscsi_bhs_data_out *bhsdo;
971 	struct iscsi_outstanding *io;
972 	struct ccb_scsiio *csio;
973 	size_t off, len, total_len;
974 	int error;
975 
976 	is = PDU_SESSION(response);
977 
978 	bhsr2t = (struct iscsi_bhs_r2t *)response->ip_bhs;
979 	io = iscsi_outstanding_find(is, bhsr2t->bhsr2t_initiator_task_tag);
980 	if (io == NULL) {
981 		ISCSI_SESSION_WARN(is, "bad itt 0x%x; reconnecting",
982 		    bhsr2t->bhsr2t_initiator_task_tag);
983 		icl_pdu_free(response);
984 		iscsi_session_reconnect(is);
985 		return;
986 	}
987 
988 	csio = &io->io_ccb->csio;
989 
990 	if ((csio->ccb_h.flags & CAM_DIR_MASK) != CAM_DIR_OUT) {
991 		ISCSI_SESSION_WARN(is, "received R2T for read command; reconnecting");
992 		icl_pdu_free(response);
993 		iscsi_session_reconnect(is);
994 		return;
995 	}
996 
997 	/*
998 	 * XXX: Verify R2TSN.
999 	 */
1000 
1001 	io->io_datasn = 0;
1002 	off = ntohl(bhsr2t->bhsr2t_buffer_offset);
1003 	total_len = ntohl(bhsr2t->bhsr2t_desired_data_transfer_length);
1004 
1005 	//ISCSI_SESSION_DEBUG(is, "r2t; off %zd, len %zd", off, total_len);
1006 
1007 	for (;;) {
1008 		len = total_len;
1009 
1010 		if (len > is->is_max_data_segment_length)
1011 			len = is->is_max_data_segment_length;
1012 
1013 		if (off + len > csio->dxfer_len) {
1014 			ISCSI_SESSION_WARN(is, "bad off %zd, len %d",
1015 			    off + len, csio->dxfer_len);
1016 			icl_pdu_free(response);
1017 			iscsi_session_reconnect(is);
1018 			return;
1019 		}
1020 
1021 		request = icl_pdu_new_bhs(response->ip_conn, M_NOWAIT);
1022 		if (request == NULL) {
1023 			icl_pdu_free(response);
1024 			iscsi_session_reconnect(is);
1025 			return;
1026 		}
1027 
1028 		bhsdo = (struct iscsi_bhs_data_out *)request->ip_bhs;
1029 		bhsdo->bhsdo_opcode = ISCSI_BHS_OPCODE_SCSI_DATA_OUT;
1030 		bhsdo->bhsdo_lun = bhsr2t->bhsr2t_lun;
1031 		bhsdo->bhsdo_initiator_task_tag =
1032 		    bhsr2t->bhsr2t_initiator_task_tag;
1033 		bhsdo->bhsdo_target_transfer_tag =
1034 		    bhsr2t->bhsr2t_target_transfer_tag;
1035 		bhsdo->bhsdo_datasn = htonl(io->io_datasn++);
1036 		bhsdo->bhsdo_buffer_offset = htonl(off);
1037 		error = icl_pdu_append_data(request, csio->data_ptr + off, len, M_NOWAIT);
1038 		if (error != 0) {
1039 			icl_pdu_free(request);
1040 			icl_pdu_free(response);
1041 			iscsi_session_reconnect(is);
1042 			return;
1043 		}
1044 
1045 		off += len;
1046 		total_len -= len;
1047 
1048 		if (total_len == 0) {
1049 			bhsdo->bhsdo_flags |= BHSDO_FLAGS_F;
1050 			//ISCSI_SESSION_DEBUG(is, "setting F, off %zd", off);
1051 		} else {
1052 			//ISCSI_SESSION_DEBUG(is, "not finished, off %zd", off);
1053 		}
1054 
1055 		iscsi_pdu_queue_locked(request);
1056 
1057 		if (total_len == 0)
1058 			break;
1059 	}
1060 
1061 	icl_pdu_free(response);
1062 }
1063 
1064 static void
1065 iscsi_pdu_handle_async_message(struct icl_pdu *response)
1066 {
1067 	struct iscsi_bhs_asynchronous_message *bhsam;
1068 	struct iscsi_session *is;
1069 
1070 	is = PDU_SESSION(response);
1071 	bhsam = (struct iscsi_bhs_asynchronous_message *)response->ip_bhs;
1072 	switch (bhsam->bhsam_async_event) {
1073 	case BHSAM_EVENT_TARGET_REQUESTS_LOGOUT:
1074 		ISCSI_SESSION_WARN(is, "target requests logout; removing session");
1075 		iscsi_session_logout(is);
1076 		iscsi_session_terminate(is);
1077 		break;
1078 	case BHSAM_EVENT_TARGET_TERMINATES_CONNECTION:
1079 		ISCSI_SESSION_WARN(is, "target indicates it will drop drop the connection");
1080 		break;
1081 	case BHSAM_EVENT_TARGET_TERMINATES_SESSION:
1082 		ISCSI_SESSION_WARN(is, "target indicates it will drop drop the session");
1083 		break;
1084 	default:
1085 		/*
1086 		 * XXX: Technically, we're obligated to also handle
1087 		 * 	parameter renegotiation.
1088 		 */
1089 		ISCSI_SESSION_WARN(is, "ignoring AsyncEvent %d", bhsam->bhsam_async_event);
1090 		break;
1091 	}
1092 
1093 	icl_pdu_free(response);
1094 }
1095 
1096 static void
1097 iscsi_pdu_handle_reject(struct icl_pdu *response)
1098 {
1099 	struct iscsi_bhs_reject *bhsr;
1100 	struct iscsi_session *is;
1101 
1102 	is = PDU_SESSION(response);
1103 	bhsr = (struct iscsi_bhs_reject *)response->ip_bhs;
1104 	ISCSI_SESSION_WARN(is, "received Reject PDU, reason 0x%x; protocol error?",
1105 	    bhsr->bhsr_reason);
1106 
1107 	icl_pdu_free(response);
1108 }
1109 
1110 static int
1111 iscsi_ioctl_daemon_wait(struct iscsi_softc *sc,
1112     struct iscsi_daemon_request *request)
1113 {
1114 	struct iscsi_session *is;
1115 	int error;
1116 
1117 	sx_slock(&sc->sc_lock);
1118 	for (;;) {
1119 		TAILQ_FOREACH(is, &sc->sc_sessions, is_next) {
1120 			if (is->is_waiting_for_iscsid)
1121 				break;
1122 		}
1123 
1124 		if (is == NULL) {
1125 			/*
1126 			 * No session requires attention from iscsid(8); wait.
1127 			 */
1128 			error = cv_wait_sig(&sc->sc_cv, &sc->sc_lock);
1129 			if (error != 0) {
1130 				sx_sunlock(&sc->sc_lock);
1131 				return (error);
1132 			}
1133 			continue;
1134 		}
1135 
1136 		ISCSI_SESSION_LOCK(is);
1137 		is->is_waiting_for_iscsid = false;
1138 		is->is_login_phase = true;
1139 		is->is_reason[0] = '\0';
1140 		ISCSI_SESSION_UNLOCK(is);
1141 
1142 		request->idr_session_id = is->is_id;
1143 		memcpy(&request->idr_conf, &is->is_conf,
1144 		    sizeof(request->idr_conf));
1145 
1146 		sx_sunlock(&sc->sc_lock);
1147 		return (0);
1148 	}
1149 }
1150 
1151 static int
1152 iscsi_ioctl_daemon_handoff(struct iscsi_softc *sc,
1153     struct iscsi_daemon_handoff *handoff)
1154 {
1155 	struct iscsi_session *is;
1156 	int error;
1157 
1158 	sx_slock(&sc->sc_lock);
1159 
1160 	/*
1161 	 * Find the session to hand off socket to.
1162 	 */
1163 	TAILQ_FOREACH(is, &sc->sc_sessions, is_next) {
1164 		if (is->is_id == handoff->idh_session_id)
1165 			break;
1166 	}
1167 	if (is == NULL) {
1168 		sx_sunlock(&sc->sc_lock);
1169 		return (ESRCH);
1170 	}
1171 	ISCSI_SESSION_LOCK(is);
1172 	if (is->is_conf.isc_discovery || is->is_terminating) {
1173 		ISCSI_SESSION_UNLOCK(is);
1174 		sx_sunlock(&sc->sc_lock);
1175 		return (EINVAL);
1176 	}
1177 
1178 	strlcpy(is->is_target_alias, handoff->idh_target_alias,
1179 	    sizeof(is->is_target_alias));
1180 	memcpy(is->is_isid, handoff->idh_isid, sizeof(is->is_isid));
1181 	is->is_statsn = handoff->idh_statsn;
1182 	is->is_initial_r2t = handoff->idh_initial_r2t;
1183 	is->is_immediate_data = handoff->idh_immediate_data;
1184 	is->is_max_data_segment_length = handoff->idh_max_data_segment_length;
1185 	is->is_max_burst_length = handoff->idh_max_burst_length;
1186 	is->is_first_burst_length = handoff->idh_first_burst_length;
1187 
1188 	if (handoff->idh_header_digest == ISCSI_DIGEST_CRC32C)
1189 		is->is_conn->ic_header_crc32c = true;
1190 	else
1191 		is->is_conn->ic_header_crc32c = false;
1192 	if (handoff->idh_data_digest == ISCSI_DIGEST_CRC32C)
1193 		is->is_conn->ic_data_crc32c = true;
1194 	else
1195 		is->is_conn->ic_data_crc32c = false;
1196 
1197 	is->is_cmdsn = 0;
1198 	is->is_expcmdsn = 1;
1199 	is->is_maxcmdsn = 1;
1200 	is->is_waiting_for_iscsid = false;
1201 	is->is_login_phase = false;
1202 	is->is_timeout = 0;
1203 	is->is_connected = true;
1204 	is->is_reason[0] = '\0';
1205 
1206 	ISCSI_SESSION_UNLOCK(is);
1207 
1208 #ifndef ICL_KERNEL_PROXY
1209 	error = icl_conn_handoff(is->is_conn, handoff->idh_socket);
1210 	if (error != 0) {
1211 		sx_sunlock(&sc->sc_lock);
1212 		iscsi_session_terminate(is);
1213 		return (error);
1214 	}
1215 #endif
1216 
1217 	sx_sunlock(&sc->sc_lock);
1218 
1219 	if (is->is_sim != NULL) {
1220 		/*
1221 		 * When reconnecting, there already is SIM allocated for the session.
1222 		 */
1223 		KASSERT(is->is_simq_frozen, ("reconnect without frozen simq"));
1224 		ISCSI_SESSION_LOCK(is);
1225 		ISCSI_SESSION_DEBUG(is, "releasing");
1226 		xpt_release_simq(is->is_sim, 1);
1227 		is->is_simq_frozen = false;
1228 		ISCSI_SESSION_UNLOCK(is);
1229 
1230 	} else {
1231 		ISCSI_SESSION_LOCK(is);
1232 		is->is_devq = cam_simq_alloc(maxtags);
1233 		if (is->is_devq == NULL) {
1234 			ISCSI_SESSION_WARN(is, "failed to allocate simq");
1235 			iscsi_session_terminate(is);
1236 			return (ENOMEM);
1237 		}
1238 
1239 		is->is_sim = cam_sim_alloc(iscsi_action, iscsi_poll, "iscsi",
1240 		    is, is->is_id /* unit */, &is->is_lock,
1241 		    maxtags, maxtags, is->is_devq);
1242 		if (is->is_sim == NULL) {
1243 			ISCSI_SESSION_UNLOCK(is);
1244 			ISCSI_SESSION_WARN(is, "failed to allocate SIM");
1245 			cam_simq_free(is->is_devq);
1246 			iscsi_session_terminate(is);
1247 			return (ENOMEM);
1248 		}
1249 
1250 		error = xpt_bus_register(is->is_sim, NULL, 0);
1251 		if (error != 0) {
1252 			ISCSI_SESSION_UNLOCK(is);
1253 			ISCSI_SESSION_WARN(is, "failed to register bus");
1254 			iscsi_session_terminate(is);
1255 			return (ENOMEM);
1256 		}
1257 
1258 		error = xpt_create_path(&is->is_path, /*periph*/NULL,
1259 		    cam_sim_path(is->is_sim), CAM_TARGET_WILDCARD,
1260 		    CAM_LUN_WILDCARD);
1261 		if (error != CAM_REQ_CMP) {
1262 			ISCSI_SESSION_UNLOCK(is);
1263 			ISCSI_SESSION_WARN(is, "failed to create path");
1264 			iscsi_session_terminate(is);
1265 			return (ENOMEM);
1266 		}
1267 		ISCSI_SESSION_UNLOCK(is);
1268 	}
1269 
1270 	return (0);
1271 }
1272 
1273 static int
1274 iscsi_ioctl_daemon_fail(struct iscsi_softc *sc,
1275     struct iscsi_daemon_fail *fail)
1276 {
1277 	struct iscsi_session *is;
1278 
1279 	sx_slock(&sc->sc_lock);
1280 
1281 	TAILQ_FOREACH(is, &sc->sc_sessions, is_next) {
1282 		if (is->is_id == fail->idf_session_id)
1283 			break;
1284 	}
1285 	if (is == NULL) {
1286 		sx_sunlock(&sc->sc_lock);
1287 		return (ESRCH);
1288 	}
1289 	ISCSI_SESSION_LOCK(is);
1290 	ISCSI_SESSION_DEBUG(is, "iscsid(8) failed: %s",
1291 	    fail->idf_reason);
1292 	strlcpy(is->is_reason, fail->idf_reason, sizeof(is->is_reason));
1293 	//is->is_waiting_for_iscsid = false;
1294 	//is->is_login_phase = true;
1295 	//iscsi_session_reconnect(is);
1296 	ISCSI_SESSION_UNLOCK(is);
1297 	sx_sunlock(&sc->sc_lock);
1298 
1299 	return (0);
1300 }
1301 
1302 #ifdef ICL_KERNEL_PROXY
1303 static int
1304 iscsi_ioctl_daemon_connect(struct iscsi_softc *sc,
1305     struct iscsi_daemon_connect *idc)
1306 {
1307 	struct iscsi_session *is;
1308 	struct sockaddr *from_sa, *to_sa;
1309 	int error;
1310 
1311 	sx_slock(&sc->sc_lock);
1312 	TAILQ_FOREACH(is, &sc->sc_sessions, is_next) {
1313 		if (is->is_id == idc->idc_session_id)
1314 			break;
1315 	}
1316 	if (is == NULL) {
1317 		sx_sunlock(&sc->sc_lock);
1318 		return (ESRCH);
1319 	}
1320 	sx_sunlock(&sc->sc_lock);
1321 
1322 	if (idc->idc_from_addrlen > 0) {
1323 		error = getsockaddr(&from_sa, (void *)idc->idc_from_addr, idc->idc_from_addrlen);
1324 		if (error != 0)
1325 			return (error);
1326 	} else {
1327 		from_sa = NULL;
1328 	}
1329 	error = getsockaddr(&to_sa, (void *)idc->idc_to_addr, idc->idc_to_addrlen);
1330 	if (error != 0) {
1331 		free(from_sa, M_SONAME);
1332 		return (error);
1333 	}
1334 
1335 	ISCSI_SESSION_LOCK(is);
1336 	is->is_waiting_for_iscsid = false;
1337 	is->is_login_phase = true;
1338 	is->is_timeout = 0;
1339 	ISCSI_SESSION_UNLOCK(is);
1340 
1341 	error = icl_conn_connect(is->is_conn, idc->idc_iser, idc->idc_domain,
1342 	    idc->idc_socktype, idc->idc_protocol, from_sa, to_sa);
1343 	free(from_sa, M_SONAME);
1344 	free(to_sa, M_SONAME);
1345 
1346 	/*
1347 	 * Digests are always disabled during login phase.
1348 	 */
1349 	is->is_conn->ic_header_crc32c = false;
1350 	is->is_conn->ic_data_crc32c = false;
1351 
1352 	return (error);
1353 }
1354 
1355 static int
1356 iscsi_ioctl_daemon_send(struct iscsi_softc *sc,
1357     struct iscsi_daemon_send *ids)
1358 {
1359 	struct iscsi_session *is;
1360 	struct icl_pdu *ip;
1361 	size_t datalen;
1362 	void *data;
1363 	int error;
1364 
1365 	sx_slock(&sc->sc_lock);
1366 	TAILQ_FOREACH(is, &sc->sc_sessions, is_next) {
1367 		if (is->is_id == ids->ids_session_id)
1368 			break;
1369 	}
1370 	if (is == NULL) {
1371 		sx_sunlock(&sc->sc_lock);
1372 		return (ESRCH);
1373 	}
1374 	sx_sunlock(&sc->sc_lock);
1375 
1376 	if (is->is_login_phase == false)
1377 		return (EBUSY);
1378 
1379 	if (is->is_terminating || is->is_reconnecting)
1380 		return (EIO);
1381 
1382 	datalen = ids->ids_data_segment_len;
1383 	if (datalen > ISCSI_MAX_DATA_SEGMENT_LENGTH)
1384 		return (EINVAL);
1385 	if (datalen > 0) {
1386 		data = malloc(datalen, M_ISCSI, M_WAITOK);
1387 		error = copyin(ids->ids_data_segment, data, datalen);
1388 		if (error != 0) {
1389 			free(data, M_ISCSI);
1390 			return (error);
1391 		}
1392 	}
1393 
1394 	ip = icl_pdu_new_bhs(is->is_conn, M_WAITOK);
1395 	memcpy(ip->ip_bhs, ids->ids_bhs, sizeof(*ip->ip_bhs));
1396 	if (datalen > 0) {
1397 		error = icl_pdu_append_data(ip, data, datalen, M_WAITOK);
1398 		KASSERT(error == 0, ("icl_pdu_append_data(..., M_WAITOK) failed"));
1399 		free(data, M_ISCSI);
1400 	}
1401 	icl_pdu_queue(ip);
1402 
1403 	return (0);
1404 }
1405 
1406 static int
1407 iscsi_ioctl_daemon_receive(struct iscsi_softc *sc,
1408     struct iscsi_daemon_receive *idr)
1409 {
1410 	struct iscsi_session *is;
1411 	struct icl_pdu *ip;
1412 	void *data;
1413 
1414 	sx_slock(&sc->sc_lock);
1415 	TAILQ_FOREACH(is, &sc->sc_sessions, is_next) {
1416 		if (is->is_id == idr->idr_session_id)
1417 			break;
1418 	}
1419 	if (is == NULL) {
1420 		sx_sunlock(&sc->sc_lock);
1421 		return (ESRCH);
1422 	}
1423 	sx_sunlock(&sc->sc_lock);
1424 
1425 	if (is->is_login_phase == false)
1426 		return (EBUSY);
1427 
1428 	ISCSI_SESSION_LOCK(is);
1429 	while (is->is_login_pdu == NULL &&
1430 	    is->is_terminating == false &&
1431 	    is->is_reconnecting == false)
1432 		cv_wait(&is->is_login_cv, &is->is_lock);
1433 	if (is->is_terminating || is->is_reconnecting) {
1434 		ISCSI_SESSION_UNLOCK(is);
1435 		return (EIO);
1436 	}
1437 	ip = is->is_login_pdu;
1438 	is->is_login_pdu = NULL;
1439 	ISCSI_SESSION_UNLOCK(is);
1440 
1441 	if (ip->ip_data_len > idr->idr_data_segment_len) {
1442 		icl_pdu_free(ip);
1443 		return (EMSGSIZE);
1444 	}
1445 
1446 	copyout(ip->ip_bhs, idr->idr_bhs, sizeof(*ip->ip_bhs));
1447 	if (ip->ip_data_len > 0) {
1448 		data = malloc(ip->ip_data_len, M_ISCSI, M_WAITOK);
1449 		icl_pdu_get_data(ip, 0, data, ip->ip_data_len);
1450 		copyout(data, idr->idr_data_segment, ip->ip_data_len);
1451 		free(data, M_ISCSI);
1452 	}
1453 
1454 	icl_pdu_free(ip);
1455 
1456 	return (0);
1457 }
1458 
1459 static int
1460 iscsi_ioctl_daemon_close(struct iscsi_softc *sc,
1461     struct iscsi_daemon_close *idc)
1462 {
1463 	struct iscsi_session *is;
1464 
1465 	sx_slock(&sc->sc_lock);
1466 	TAILQ_FOREACH(is, &sc->sc_sessions, is_next) {
1467 		if (is->is_id == idc->idc_session_id)
1468 			break;
1469 	}
1470 	if (is == NULL) {
1471 		sx_sunlock(&sc->sc_lock);
1472 		return (ESRCH);
1473 	}
1474 	sx_sunlock(&sc->sc_lock);
1475 
1476 	iscsi_session_reconnect(is);
1477 
1478 	return (0);
1479 }
1480 #endif /* ICL_KERNEL_PROXY */
1481 
1482 static void
1483 iscsi_sanitize_session_conf(struct iscsi_session_conf *isc)
1484 {
1485 	/*
1486 	 * Just make sure all the fields are null-terminated.
1487 	 *
1488 	 * XXX: This is not particularly secure.  We should
1489 	 * 	create our own conf and then copy in relevant
1490 	 * 	fields.
1491 	 */
1492 	isc->isc_initiator[ISCSI_NAME_LEN - 1] = '\0';
1493 	isc->isc_initiator_addr[ISCSI_ADDR_LEN - 1] = '\0';
1494 	isc->isc_initiator_alias[ISCSI_ALIAS_LEN - 1] = '\0';
1495 	isc->isc_target[ISCSI_NAME_LEN - 1] = '\0';
1496 	isc->isc_target_addr[ISCSI_ADDR_LEN - 1] = '\0';
1497 	isc->isc_user[ISCSI_NAME_LEN - 1] = '\0';
1498 	isc->isc_secret[ISCSI_SECRET_LEN - 1] = '\0';
1499 	isc->isc_mutual_user[ISCSI_NAME_LEN - 1] = '\0';
1500 	isc->isc_mutual_secret[ISCSI_SECRET_LEN - 1] = '\0';
1501 }
1502 
1503 static int
1504 iscsi_ioctl_session_add(struct iscsi_softc *sc, struct iscsi_session_add *isa)
1505 {
1506 	struct iscsi_session *is;
1507 	const struct iscsi_session *is2;
1508 	int error;
1509 
1510 	iscsi_sanitize_session_conf(&isa->isa_conf);
1511 
1512 	is = malloc(sizeof(*is), M_ISCSI, M_ZERO | M_WAITOK);
1513 	memcpy(&is->is_conf, &isa->isa_conf, sizeof(is->is_conf));
1514 
1515 	if (is->is_conf.isc_initiator[0] == '\0' ||
1516 	    is->is_conf.isc_target_addr[0] == '\0') {
1517 		free(is, M_ISCSI);
1518 		return (EINVAL);
1519 	}
1520 
1521 	if ((is->is_conf.isc_discovery != 0 && is->is_conf.isc_target[0] != 0) ||
1522 	    (is->is_conf.isc_discovery == 0 && is->is_conf.isc_target[0] == 0)) {
1523 		free(is, M_ISCSI);
1524 		return (EINVAL);
1525 	}
1526 
1527 	sx_xlock(&sc->sc_lock);
1528 
1529 	/*
1530 	 * Prevent duplicates.
1531 	 */
1532 	TAILQ_FOREACH(is2, &sc->sc_sessions, is_next) {
1533 		if (!!is->is_conf.isc_discovery !=
1534 		    !!is2->is_conf.isc_discovery)
1535 			continue;
1536 
1537 		if (strcmp(is->is_conf.isc_target_addr,
1538 		    is2->is_conf.isc_target_addr) != 0)
1539 			continue;
1540 
1541 		if (is->is_conf.isc_discovery == 0 &&
1542 		    strcmp(is->is_conf.isc_target,
1543 		    is2->is_conf.isc_target) != 0)
1544 			continue;
1545 
1546 		sx_xunlock(&sc->sc_lock);
1547 		free(is, M_ISCSI);
1548 		return (EBUSY);
1549 	}
1550 
1551 	is->is_conn = icl_conn_new();
1552 	is->is_conn->ic_receive = iscsi_receive_callback;
1553 	is->is_conn->ic_error = iscsi_error_callback;
1554 	is->is_conn->ic_prv0 = is;
1555 	TAILQ_INIT(&is->is_outstanding);
1556 	TAILQ_INIT(&is->is_postponed);
1557 	mtx_init(&is->is_lock, "iscsi_lock", NULL, MTX_DEF);
1558 	cv_init(&is->is_maintenance_cv, "iscsi_mt");
1559 #ifdef ICL_KERNEL_PROXY
1560 	cv_init(&is->is_login_cv, "iscsi_login");
1561 #endif
1562 
1563 	is->is_softc = sc;
1564 	sc->sc_last_session_id++;
1565 	is->is_id = sc->sc_last_session_id;
1566 	callout_init(&is->is_callout, 1);
1567 	callout_reset(&is->is_callout, 1 * hz, iscsi_callout, is);
1568 	TAILQ_INSERT_TAIL(&sc->sc_sessions, is, is_next);
1569 
1570 	error = kthread_add(iscsi_maintenance_thread, is, NULL, NULL, 0, 0, "iscsimt");
1571 	if (error != 0) {
1572 		ISCSI_SESSION_WARN(is, "kthread_add(9) failed with error %d", error);
1573 		return (error);
1574 	}
1575 
1576 	/*
1577 	 * Trigger immediate reconnection.
1578 	 */
1579 	is->is_waiting_for_iscsid = true;
1580 	strlcpy(is->is_reason, "Waiting for iscsid(8)", sizeof(is->is_reason));
1581 	cv_signal(&sc->sc_cv);
1582 
1583 	sx_xunlock(&sc->sc_lock);
1584 
1585 	return (0);
1586 }
1587 
1588 static bool
1589 iscsi_session_conf_matches(unsigned int id1, const struct iscsi_session_conf *c1,
1590     unsigned int id2, const struct iscsi_session_conf *c2)
1591 {
1592 	if (id2 == 0 && c2->isc_target[0] == '\0' &&
1593 	    c2->isc_target_addr[0] == '\0')
1594 		return (true);
1595 	if (id2 != 0 && id2 == id1)
1596 		return (true);
1597 	if (c2->isc_target[0] != '\0' &&
1598 	    strcmp(c1->isc_target, c2->isc_target) == 0)
1599 		return (true);
1600 	if (c2->isc_target_addr[0] != '\0' &&
1601 	    strcmp(c1->isc_target_addr, c2->isc_target_addr) == 0)
1602 		return (true);
1603 	return (false);
1604 }
1605 
1606 static int
1607 iscsi_ioctl_session_remove(struct iscsi_softc *sc,
1608     struct iscsi_session_remove *isr)
1609 {
1610 	struct iscsi_session *is, *tmp;
1611 	bool found = false;
1612 
1613 	iscsi_sanitize_session_conf(&isr->isr_conf);
1614 
1615 	sx_xlock(&sc->sc_lock);
1616 	TAILQ_FOREACH_SAFE(is, &sc->sc_sessions, is_next, tmp) {
1617 		ISCSI_SESSION_LOCK(is);
1618 		if (iscsi_session_conf_matches(is->is_id, &is->is_conf,
1619 		    isr->isr_session_id, &isr->isr_conf)) {
1620 			found = true;
1621 			iscsi_session_logout(is);
1622 			iscsi_session_terminate(is);
1623 		}
1624 		ISCSI_SESSION_UNLOCK(is);
1625 	}
1626 	sx_xunlock(&sc->sc_lock);
1627 
1628 	if (!found)
1629 		return (ESRCH);
1630 
1631 	return (0);
1632 }
1633 
1634 static int
1635 iscsi_ioctl_session_list(struct iscsi_softc *sc, struct iscsi_session_list *isl)
1636 {
1637 	int error;
1638 	unsigned int i = 0;
1639 	struct iscsi_session *is;
1640 	struct iscsi_session_state iss;
1641 
1642 	sx_slock(&sc->sc_lock);
1643 	TAILQ_FOREACH(is, &sc->sc_sessions, is_next) {
1644 		if (i >= isl->isl_nentries) {
1645 			sx_sunlock(&sc->sc_lock);
1646 			return (EMSGSIZE);
1647 		}
1648 		memset(&iss, 0, sizeof(iss));
1649 		memcpy(&iss.iss_conf, &is->is_conf, sizeof(iss.iss_conf));
1650 		iss.iss_id = is->is_id;
1651 		strlcpy(iss.iss_target_alias, is->is_target_alias, sizeof(iss.iss_target_alias));
1652 		strlcpy(iss.iss_reason, is->is_reason, sizeof(iss.iss_reason));
1653 
1654 		if (is->is_conn->ic_header_crc32c)
1655 			iss.iss_header_digest = ISCSI_DIGEST_CRC32C;
1656 		else
1657 			iss.iss_header_digest = ISCSI_DIGEST_NONE;
1658 
1659 		if (is->is_conn->ic_data_crc32c)
1660 			iss.iss_data_digest = ISCSI_DIGEST_CRC32C;
1661 		else
1662 			iss.iss_data_digest = ISCSI_DIGEST_NONE;
1663 
1664 		iss.iss_max_data_segment_length = is->is_max_data_segment_length;
1665 		iss.iss_immediate_data = is->is_immediate_data;
1666 		iss.iss_connected = is->is_connected;
1667 
1668 		error = copyout(&iss, isl->isl_pstates + i, sizeof(iss));
1669 		if (error != 0) {
1670 			sx_sunlock(&sc->sc_lock);
1671 			return (error);
1672 		}
1673 		i++;
1674 	}
1675 	sx_sunlock(&sc->sc_lock);
1676 
1677 	isl->isl_nentries = i;
1678 
1679 	return (0);
1680 }
1681 
1682 static int
1683 iscsi_ioctl(struct cdev *dev, u_long cmd, caddr_t arg, int mode,
1684     struct thread *td)
1685 {
1686 	struct iscsi_softc *sc;
1687 
1688 	sc = dev->si_drv1;
1689 
1690 	switch (cmd) {
1691 	case ISCSIDWAIT:
1692 		return (iscsi_ioctl_daemon_wait(sc,
1693 		    (struct iscsi_daemon_request *)arg));
1694 	case ISCSIDHANDOFF:
1695 		return (iscsi_ioctl_daemon_handoff(sc,
1696 		    (struct iscsi_daemon_handoff *)arg));
1697 	case ISCSIDFAIL:
1698 		return (iscsi_ioctl_daemon_fail(sc,
1699 		    (struct iscsi_daemon_fail *)arg));
1700 #ifdef ICL_KERNEL_PROXY
1701 	case ISCSIDCONNECT:
1702 		return (iscsi_ioctl_daemon_connect(sc,
1703 		    (struct iscsi_daemon_connect *)arg));
1704 	case ISCSIDSEND:
1705 		return (iscsi_ioctl_daemon_send(sc,
1706 		    (struct iscsi_daemon_send *)arg));
1707 	case ISCSIDRECEIVE:
1708 		return (iscsi_ioctl_daemon_receive(sc,
1709 		    (struct iscsi_daemon_receive *)arg));
1710 	case ISCSIDCLOSE:
1711 		return (iscsi_ioctl_daemon_close(sc,
1712 		    (struct iscsi_daemon_close *)arg));
1713 #endif /* ICL_KERNEL_PROXY */
1714 	case ISCSISADD:
1715 		return (iscsi_ioctl_session_add(sc,
1716 		    (struct iscsi_session_add *)arg));
1717 	case ISCSISREMOVE:
1718 		return (iscsi_ioctl_session_remove(sc,
1719 		    (struct iscsi_session_remove *)arg));
1720 	case ISCSISLIST:
1721 		return (iscsi_ioctl_session_list(sc,
1722 		    (struct iscsi_session_list *)arg));
1723 	default:
1724 		return (EINVAL);
1725 	}
1726 }
1727 
1728 static uint64_t
1729 iscsi_encode_lun(uint32_t lun)
1730 {
1731 	uint8_t encoded[8];
1732 	uint64_t result;
1733 
1734 	memset(encoded, 0, sizeof(encoded));
1735 
1736 	if (lun < 256) {
1737 		/*
1738 		 * Peripheral device addressing.
1739 		 */
1740 		encoded[1] = lun;
1741 	} else if (lun < 16384) {
1742 		/*
1743 		 * Flat space addressing.
1744 		 */
1745 		encoded[0] = 0x40;
1746 		encoded[0] |= (lun >> 8) & 0x3f;
1747 		encoded[1] = lun & 0xff;
1748 	} else {
1749 		/*
1750 		 * Extended flat space addressing.
1751 		 */
1752 		encoded[0] = 0xd2;
1753 		encoded[1] = lun >> 16;
1754 		encoded[2] = lun >> 8;
1755 		encoded[3] = lun;
1756 	}
1757 
1758 	memcpy(&result, encoded, sizeof(result));
1759 	return (result);
1760 }
1761 
1762 static struct iscsi_outstanding *
1763 iscsi_outstanding_find(struct iscsi_session *is, uint32_t initiator_task_tag)
1764 {
1765 	struct iscsi_outstanding *io;
1766 
1767 	ISCSI_SESSION_LOCK_ASSERT(is);
1768 
1769 	TAILQ_FOREACH(io, &is->is_outstanding, io_next) {
1770 		if (io->io_initiator_task_tag == initiator_task_tag)
1771 			return (io);
1772 	}
1773 	return (NULL);
1774 }
1775 
1776 static int
1777 iscsi_outstanding_add(struct iscsi_session *is,
1778     uint32_t initiator_task_tag, union ccb *ccb)
1779 {
1780 	struct iscsi_outstanding *io;
1781 
1782 	ISCSI_SESSION_LOCK_ASSERT(is);
1783 
1784 	KASSERT(iscsi_outstanding_find(is, initiator_task_tag) == NULL,
1785 	    ("initiator_task_tag 0x%x already added", initiator_task_tag));
1786 
1787 	io = uma_zalloc(iscsi_outstanding_zone, M_NOWAIT | M_ZERO);
1788 	if (io == NULL) {
1789 		ISCSI_SESSION_WARN(is, "failed to allocate %zd bytes", sizeof(*io));
1790 		return (ENOMEM);
1791 	}
1792 	io->io_initiator_task_tag = initiator_task_tag;
1793 	io->io_ccb = ccb;
1794 	TAILQ_INSERT_TAIL(&is->is_outstanding, io, io_next);
1795 	return (0);
1796 }
1797 
1798 static void
1799 iscsi_outstanding_remove(struct iscsi_session *is, struct iscsi_outstanding *io)
1800 {
1801 
1802 	ISCSI_SESSION_LOCK_ASSERT(is);
1803 
1804 	TAILQ_REMOVE(&is->is_outstanding, io, io_next);
1805 	uma_zfree(iscsi_outstanding_zone, io);
1806 }
1807 
1808 static void
1809 iscsi_action_scsiio(struct iscsi_session *is, union ccb *ccb)
1810 {
1811 	struct icl_pdu *request;
1812 	struct iscsi_bhs_scsi_command *bhssc;
1813 	struct ccb_scsiio *csio;
1814 	size_t len;
1815 	int error;
1816 
1817 	ISCSI_SESSION_LOCK_ASSERT(is);
1818 
1819 #if 0
1820 	KASSERT(is->is_login_phase == false, ("%s called during Login Phase", __func__));
1821 #else
1822 	if (is->is_login_phase) {
1823 		ISCSI_SESSION_DEBUG(is, "called during login phase");
1824 		if ((ccb->ccb_h.status & CAM_DEV_QFRZN) == 0) {
1825 			xpt_freeze_devq(ccb->ccb_h.path, 1);
1826 			ISCSI_SESSION_DEBUG(is, "freezing devq");
1827 		}
1828 		ccb->ccb_h.status = CAM_REQ_ABORTED | CAM_DEV_QFRZN;
1829 		xpt_done(ccb);
1830 		return;
1831 	}
1832 #endif
1833 
1834 	request = icl_pdu_new_bhs(is->is_conn, M_NOWAIT);
1835 	if (request == NULL) {
1836 		if ((ccb->ccb_h.status & CAM_DEV_QFRZN) == 0) {
1837 			xpt_freeze_devq(ccb->ccb_h.path, 1);
1838 			ISCSI_SESSION_DEBUG(is, "freezing devq");
1839 		}
1840 		ccb->ccb_h.status = CAM_RESRC_UNAVAIL | CAM_DEV_QFRZN;
1841 		xpt_done(ccb);
1842 		return;
1843 	}
1844 
1845 	csio = &ccb->csio;
1846 	bhssc = (struct iscsi_bhs_scsi_command *)request->ip_bhs;
1847 	bhssc->bhssc_opcode = ISCSI_BHS_OPCODE_SCSI_COMMAND;
1848 	bhssc->bhssc_flags |= BHSSC_FLAGS_F;
1849 	switch (csio->ccb_h.flags & CAM_DIR_MASK) {
1850 	case CAM_DIR_IN:
1851 		bhssc->bhssc_flags |= BHSSC_FLAGS_R;
1852 		break;
1853 	case CAM_DIR_OUT:
1854 		bhssc->bhssc_flags |= BHSSC_FLAGS_W;
1855 		break;
1856 	}
1857 
1858         switch (csio->tag_action) {
1859         case MSG_HEAD_OF_Q_TAG:
1860 		bhssc->bhssc_flags |= BHSSC_FLAGS_ATTR_HOQ;
1861 		break;
1862                 break;
1863         case MSG_ORDERED_Q_TAG:
1864 		bhssc->bhssc_flags |= BHSSC_FLAGS_ATTR_ORDERED;
1865                 break;
1866         case MSG_ACA_TASK:
1867 		bhssc->bhssc_flags |= BHSSC_FLAGS_ATTR_ACA;
1868                 break;
1869         case CAM_TAG_ACTION_NONE:
1870         case MSG_SIMPLE_Q_TAG:
1871         default:
1872 		bhssc->bhssc_flags |= BHSSC_FLAGS_ATTR_SIMPLE;
1873                 break;
1874         }
1875 
1876 	bhssc->bhssc_lun = iscsi_encode_lun(csio->ccb_h.target_lun);
1877 	bhssc->bhssc_initiator_task_tag = is->is_initiator_task_tag;
1878 	is->is_initiator_task_tag++;
1879 	bhssc->bhssc_expected_data_transfer_length = htonl(csio->dxfer_len);
1880 	KASSERT(csio->cdb_len <= sizeof(bhssc->bhssc_cdb),
1881 	    ("unsupported CDB size %zd", (size_t)csio->cdb_len));
1882 
1883 	if (csio->ccb_h.flags & CAM_CDB_POINTER)
1884 		memcpy(&bhssc->bhssc_cdb, csio->cdb_io.cdb_ptr, csio->cdb_len);
1885 	else
1886 		memcpy(&bhssc->bhssc_cdb, csio->cdb_io.cdb_bytes, csio->cdb_len);
1887 
1888 	error = iscsi_outstanding_add(is, bhssc->bhssc_initiator_task_tag, ccb);
1889 	if (error != 0) {
1890 		icl_pdu_free(request);
1891 		if ((ccb->ccb_h.status & CAM_DEV_QFRZN) == 0) {
1892 			xpt_freeze_devq(ccb->ccb_h.path, 1);
1893 			ISCSI_SESSION_DEBUG(is, "freezing devq");
1894 		}
1895 		ccb->ccb_h.status = CAM_RESRC_UNAVAIL | CAM_DEV_QFRZN;
1896 		xpt_done(ccb);
1897 		return;
1898 	}
1899 
1900 	if (is->is_immediate_data &&
1901 	    (csio->ccb_h.flags & CAM_DIR_MASK) == CAM_DIR_OUT) {
1902 		len = csio->dxfer_len;
1903 		//ISCSI_SESSION_DEBUG(is, "adding %zd of immediate data", len);
1904 		if (len > is->is_first_burst_length) {
1905 			ISCSI_SESSION_DEBUG(is, "len %zd -> %zd", len, is->is_first_burst_length);
1906 			len = is->is_first_burst_length;
1907 		}
1908 
1909 		error = icl_pdu_append_data(request, csio->data_ptr, len, M_NOWAIT);
1910 		if (error != 0) {
1911 			icl_pdu_free(request);
1912 			if ((ccb->ccb_h.status & CAM_DEV_QFRZN) == 0) {
1913 				xpt_freeze_devq(ccb->ccb_h.path, 1);
1914 				ISCSI_SESSION_DEBUG(is, "freezing devq");
1915 			}
1916 			ccb->ccb_h.status = CAM_RESRC_UNAVAIL | CAM_DEV_QFRZN;
1917 			xpt_done(ccb);
1918 			return;
1919 		}
1920 	}
1921 	iscsi_pdu_queue_locked(request);
1922 }
1923 
1924 static void
1925 iscsi_action(struct cam_sim *sim, union ccb *ccb)
1926 {
1927 	struct iscsi_session *is;
1928 
1929 	is = cam_sim_softc(sim);
1930 
1931 	ISCSI_SESSION_LOCK_ASSERT(is);
1932 
1933 	if (is->is_terminating) {
1934 		ISCSI_SESSION_DEBUG(is, "called during termination");
1935 		ccb->ccb_h.status = CAM_DEV_NOT_THERE;
1936 		xpt_done(ccb);
1937 		return;
1938 	}
1939 
1940 	switch (ccb->ccb_h.func_code) {
1941 	case XPT_PATH_INQ:
1942 	{
1943 		struct ccb_pathinq *cpi = &ccb->cpi;
1944 
1945 		cpi->version_num = 1;
1946 		cpi->hba_inquiry = PI_TAG_ABLE;
1947 		cpi->target_sprt = 0;
1948 		//cpi->hba_misc = PIM_NOBUSRESET;
1949 		cpi->hba_misc = 0;
1950 		cpi->hba_eng_cnt = 0;
1951 		cpi->max_target = 0;
1952 		cpi->max_lun = 255;
1953 		//cpi->initiator_id = 0; /* XXX */
1954 		cpi->initiator_id = 64; /* XXX */
1955 		strlcpy(cpi->sim_vid, "FreeBSD", SIM_IDLEN);
1956 		strlcpy(cpi->hba_vid, "iSCSI", HBA_IDLEN);
1957 		strlcpy(cpi->dev_name, cam_sim_name(sim), DEV_IDLEN);
1958 		cpi->unit_number = cam_sim_unit(sim);
1959 		cpi->bus_id = cam_sim_bus(sim);
1960 		cpi->base_transfer_speed = 150000; /* XXX */
1961 		cpi->transport = XPORT_ISCSI;
1962 		cpi->transport_version = 0;
1963 		cpi->protocol = PROTO_SCSI;
1964 		cpi->protocol_version = SCSI_REV_SPC3;
1965 		cpi->maxio = MAXPHYS;
1966 		cpi->ccb_h.status = CAM_REQ_CMP;
1967 		break;
1968 	}
1969 	case XPT_CALC_GEOMETRY:
1970 		cam_calc_geometry(&ccb->ccg, /*extended*/1);
1971 		ccb->ccb_h.status = CAM_REQ_CMP;
1972 		break;
1973 #if 0
1974 	/*
1975 	 * XXX: What's the point?
1976 	 */
1977 	case XPT_RESET_BUS:
1978 	case XPT_ABORT:
1979 	case XPT_TERM_IO:
1980 		ISCSI_SESSION_DEBUG(is, "faking success for reset, abort, or term_io");
1981 		ccb->ccb_h.status = CAM_REQ_CMP;
1982 		break;
1983 #endif
1984 	case XPT_SCSI_IO:
1985 		iscsi_action_scsiio(is, ccb);
1986 		return;
1987 	default:
1988 #if 0
1989 		ISCSI_SESSION_DEBUG(is, "got unsupported code 0x%x", ccb->ccb_h.func_code);
1990 #endif
1991 		ccb->ccb_h.status = CAM_FUNC_NOTAVAIL;
1992 		break;
1993 	}
1994 	xpt_done(ccb);
1995 }
1996 
1997 static void
1998 iscsi_poll(struct cam_sim *sim)
1999 {
2000 
2001 	KASSERT(0, ("%s: you're not supposed to be here", __func__));
2002 }
2003 
2004 static void
2005 iscsi_shutdown(struct iscsi_softc *sc)
2006 {
2007 	struct iscsi_session *is;
2008 
2009 	ISCSI_DEBUG("removing all sessions due to shutdown");
2010 
2011 	sx_slock(&sc->sc_lock);
2012 	TAILQ_FOREACH(is, &sc->sc_sessions, is_next)
2013 		iscsi_session_terminate(is);
2014 	sx_sunlock(&sc->sc_lock);
2015 }
2016 
2017 static int
2018 iscsi_load(void)
2019 {
2020 	int error;
2021 
2022 	sc = malloc(sizeof(*sc), M_ISCSI, M_ZERO | M_WAITOK);
2023 	sx_init(&sc->sc_lock, "iscsi");
2024 	TAILQ_INIT(&sc->sc_sessions);
2025 	cv_init(&sc->sc_cv, "iscsi_cv");
2026 
2027 	iscsi_outstanding_zone = uma_zcreate("iscsi_outstanding",
2028 	    sizeof(struct iscsi_outstanding), NULL, NULL, NULL, NULL,
2029 	    UMA_ALIGN_PTR, UMA_ZONE_NOFREE);
2030 
2031 	error = make_dev_p(MAKEDEV_CHECKNAME, &sc->sc_cdev, &iscsi_cdevsw,
2032 	    NULL, UID_ROOT, GID_WHEEL, 0600, "iscsi");
2033 	if (error != 0) {
2034 		ISCSI_WARN("failed to create device node, error %d", error);
2035 		sx_destroy(&sc->sc_lock);
2036 		cv_destroy(&sc->sc_cv);
2037 		uma_zdestroy(iscsi_outstanding_zone);
2038 		free(sc, M_ISCSI);
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 	/*
2056 	 * XXX: kldunload hangs on "devdrn".
2057 	 */
2058 	struct iscsi_session *is, *tmp;
2059 
2060 	ISCSI_DEBUG("removing device node");
2061 	destroy_dev(sc->sc_cdev);
2062 	ISCSI_DEBUG("device node removed");
2063 
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