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