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