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