Merge branch 'for-next' of git://git.kernel.org/pub/scm/linux/kernel/git/nab/target...
[platform/adaptation/renesas_rcar/renesas_kernel.git] / drivers / target / iscsi / iscsi_target.c
1 /*******************************************************************************
2  * This file contains main functions related to the iSCSI Target Core Driver.
3  *
4  * (c) Copyright 2007-2013 Datera, Inc.
5  *
6  * Author: Nicholas A. Bellinger <nab@linux-iscsi.org>
7  *
8  * This program is free software; you can redistribute it and/or modify
9  * it under the terms of the GNU General Public License as published by
10  * the Free Software Foundation; either version 2 of the License, or
11  * (at your option) any later version.
12  *
13  * This program is distributed in the hope that it will be useful,
14  * but WITHOUT ANY WARRANTY; without even the implied warranty of
15  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
16  * GNU General Public License for more details.
17  ******************************************************************************/
18
19 #include <linux/string.h>
20 #include <linux/kthread.h>
21 #include <linux/crypto.h>
22 #include <linux/completion.h>
23 #include <linux/module.h>
24 #include <linux/idr.h>
25 #include <asm/unaligned.h>
26 #include <scsi/scsi_device.h>
27 #include <scsi/iscsi_proto.h>
28 #include <scsi/scsi_tcq.h>
29 #include <target/target_core_base.h>
30 #include <target/target_core_fabric.h>
31 #include <target/target_core_configfs.h>
32
33 #include "iscsi_target_core.h"
34 #include "iscsi_target_parameters.h"
35 #include "iscsi_target_seq_pdu_list.h"
36 #include "iscsi_target_tq.h"
37 #include "iscsi_target_configfs.h"
38 #include "iscsi_target_datain_values.h"
39 #include "iscsi_target_erl0.h"
40 #include "iscsi_target_erl1.h"
41 #include "iscsi_target_erl2.h"
42 #include "iscsi_target_login.h"
43 #include "iscsi_target_tmr.h"
44 #include "iscsi_target_tpg.h"
45 #include "iscsi_target_util.h"
46 #include "iscsi_target.h"
47 #include "iscsi_target_device.h"
48 #include "iscsi_target_stat.h"
49
50 #include <target/iscsi/iscsi_transport.h>
51
52 static LIST_HEAD(g_tiqn_list);
53 static LIST_HEAD(g_np_list);
54 static DEFINE_SPINLOCK(tiqn_lock);
55 static DEFINE_SPINLOCK(np_lock);
56
57 static struct idr tiqn_idr;
58 struct idr sess_idr;
59 struct mutex auth_id_lock;
60 spinlock_t sess_idr_lock;
61
62 struct iscsit_global *iscsit_global;
63
64 struct kmem_cache *lio_qr_cache;
65 struct kmem_cache *lio_dr_cache;
66 struct kmem_cache *lio_ooo_cache;
67 struct kmem_cache *lio_r2t_cache;
68
69 static int iscsit_handle_immediate_data(struct iscsi_cmd *,
70                         struct iscsi_scsi_req *, u32);
71
72 struct iscsi_tiqn *iscsit_get_tiqn_for_login(unsigned char *buf)
73 {
74         struct iscsi_tiqn *tiqn = NULL;
75
76         spin_lock(&tiqn_lock);
77         list_for_each_entry(tiqn, &g_tiqn_list, tiqn_list) {
78                 if (!strcmp(tiqn->tiqn, buf)) {
79
80                         spin_lock(&tiqn->tiqn_state_lock);
81                         if (tiqn->tiqn_state == TIQN_STATE_ACTIVE) {
82                                 tiqn->tiqn_access_count++;
83                                 spin_unlock(&tiqn->tiqn_state_lock);
84                                 spin_unlock(&tiqn_lock);
85                                 return tiqn;
86                         }
87                         spin_unlock(&tiqn->tiqn_state_lock);
88                 }
89         }
90         spin_unlock(&tiqn_lock);
91
92         return NULL;
93 }
94
95 static int iscsit_set_tiqn_shutdown(struct iscsi_tiqn *tiqn)
96 {
97         spin_lock(&tiqn->tiqn_state_lock);
98         if (tiqn->tiqn_state == TIQN_STATE_ACTIVE) {
99                 tiqn->tiqn_state = TIQN_STATE_SHUTDOWN;
100                 spin_unlock(&tiqn->tiqn_state_lock);
101                 return 0;
102         }
103         spin_unlock(&tiqn->tiqn_state_lock);
104
105         return -1;
106 }
107
108 void iscsit_put_tiqn_for_login(struct iscsi_tiqn *tiqn)
109 {
110         spin_lock(&tiqn->tiqn_state_lock);
111         tiqn->tiqn_access_count--;
112         spin_unlock(&tiqn->tiqn_state_lock);
113 }
114
115 /*
116  * Note that IQN formatting is expected to be done in userspace, and
117  * no explict IQN format checks are done here.
118  */
119 struct iscsi_tiqn *iscsit_add_tiqn(unsigned char *buf)
120 {
121         struct iscsi_tiqn *tiqn = NULL;
122         int ret;
123
124         if (strlen(buf) >= ISCSI_IQN_LEN) {
125                 pr_err("Target IQN exceeds %d bytes\n",
126                                 ISCSI_IQN_LEN);
127                 return ERR_PTR(-EINVAL);
128         }
129
130         tiqn = kzalloc(sizeof(struct iscsi_tiqn), GFP_KERNEL);
131         if (!tiqn) {
132                 pr_err("Unable to allocate struct iscsi_tiqn\n");
133                 return ERR_PTR(-ENOMEM);
134         }
135
136         sprintf(tiqn->tiqn, "%s", buf);
137         INIT_LIST_HEAD(&tiqn->tiqn_list);
138         INIT_LIST_HEAD(&tiqn->tiqn_tpg_list);
139         spin_lock_init(&tiqn->tiqn_state_lock);
140         spin_lock_init(&tiqn->tiqn_tpg_lock);
141         spin_lock_init(&tiqn->sess_err_stats.lock);
142         spin_lock_init(&tiqn->login_stats.lock);
143         spin_lock_init(&tiqn->logout_stats.lock);
144
145         tiqn->tiqn_state = TIQN_STATE_ACTIVE;
146
147         idr_preload(GFP_KERNEL);
148         spin_lock(&tiqn_lock);
149
150         ret = idr_alloc(&tiqn_idr, NULL, 0, 0, GFP_NOWAIT);
151         if (ret < 0) {
152                 pr_err("idr_alloc() failed for tiqn->tiqn_index\n");
153                 spin_unlock(&tiqn_lock);
154                 idr_preload_end();
155                 kfree(tiqn);
156                 return ERR_PTR(ret);
157         }
158         tiqn->tiqn_index = ret;
159         list_add_tail(&tiqn->tiqn_list, &g_tiqn_list);
160
161         spin_unlock(&tiqn_lock);
162         idr_preload_end();
163
164         pr_debug("CORE[0] - Added iSCSI Target IQN: %s\n", tiqn->tiqn);
165
166         return tiqn;
167
168 }
169
170 static void iscsit_wait_for_tiqn(struct iscsi_tiqn *tiqn)
171 {
172         /*
173          * Wait for accesses to said struct iscsi_tiqn to end.
174          */
175         spin_lock(&tiqn->tiqn_state_lock);
176         while (tiqn->tiqn_access_count != 0) {
177                 spin_unlock(&tiqn->tiqn_state_lock);
178                 msleep(10);
179                 spin_lock(&tiqn->tiqn_state_lock);
180         }
181         spin_unlock(&tiqn->tiqn_state_lock);
182 }
183
184 void iscsit_del_tiqn(struct iscsi_tiqn *tiqn)
185 {
186         /*
187          * iscsit_set_tiqn_shutdown sets tiqn->tiqn_state = TIQN_STATE_SHUTDOWN
188          * while holding tiqn->tiqn_state_lock.  This means that all subsequent
189          * attempts to access this struct iscsi_tiqn will fail from both transport
190          * fabric and control code paths.
191          */
192         if (iscsit_set_tiqn_shutdown(tiqn) < 0) {
193                 pr_err("iscsit_set_tiqn_shutdown() failed\n");
194                 return;
195         }
196
197         iscsit_wait_for_tiqn(tiqn);
198
199         spin_lock(&tiqn_lock);
200         list_del(&tiqn->tiqn_list);
201         idr_remove(&tiqn_idr, tiqn->tiqn_index);
202         spin_unlock(&tiqn_lock);
203
204         pr_debug("CORE[0] - Deleted iSCSI Target IQN: %s\n",
205                         tiqn->tiqn);
206         kfree(tiqn);
207 }
208
209 int iscsit_access_np(struct iscsi_np *np, struct iscsi_portal_group *tpg)
210 {
211         int ret;
212         /*
213          * Determine if the network portal is accepting storage traffic.
214          */
215         spin_lock_bh(&np->np_thread_lock);
216         if (np->np_thread_state != ISCSI_NP_THREAD_ACTIVE) {
217                 spin_unlock_bh(&np->np_thread_lock);
218                 return -1;
219         }
220         spin_unlock_bh(&np->np_thread_lock);
221         /*
222          * Determine if the portal group is accepting storage traffic.
223          */
224         spin_lock_bh(&tpg->tpg_state_lock);
225         if (tpg->tpg_state != TPG_STATE_ACTIVE) {
226                 spin_unlock_bh(&tpg->tpg_state_lock);
227                 return -1;
228         }
229         spin_unlock_bh(&tpg->tpg_state_lock);
230
231         /*
232          * Here we serialize access across the TIQN+TPG Tuple.
233          */
234         ret = down_interruptible(&tpg->np_login_sem);
235         if ((ret != 0) || signal_pending(current))
236                 return -1;
237
238         spin_lock_bh(&tpg->tpg_state_lock);
239         if (tpg->tpg_state != TPG_STATE_ACTIVE) {
240                 spin_unlock_bh(&tpg->tpg_state_lock);
241                 up(&tpg->np_login_sem);
242                 return -1;
243         }
244         spin_unlock_bh(&tpg->tpg_state_lock);
245
246         return 0;
247 }
248
249 void iscsit_login_kref_put(struct kref *kref)
250 {
251         struct iscsi_tpg_np *tpg_np = container_of(kref,
252                                 struct iscsi_tpg_np, tpg_np_kref);
253
254         complete(&tpg_np->tpg_np_comp);
255 }
256
257 int iscsit_deaccess_np(struct iscsi_np *np, struct iscsi_portal_group *tpg,
258                        struct iscsi_tpg_np *tpg_np)
259 {
260         struct iscsi_tiqn *tiqn = tpg->tpg_tiqn;
261
262         up(&tpg->np_login_sem);
263
264         if (tpg_np)
265                 kref_put(&tpg_np->tpg_np_kref, iscsit_login_kref_put);
266
267         if (tiqn)
268                 iscsit_put_tiqn_for_login(tiqn);
269
270         return 0;
271 }
272
273 bool iscsit_check_np_match(
274         struct __kernel_sockaddr_storage *sockaddr,
275         struct iscsi_np *np,
276         int network_transport)
277 {
278         struct sockaddr_in *sock_in, *sock_in_e;
279         struct sockaddr_in6 *sock_in6, *sock_in6_e;
280         bool ip_match = false;
281         u16 port;
282
283         if (sockaddr->ss_family == AF_INET6) {
284                 sock_in6 = (struct sockaddr_in6 *)sockaddr;
285                 sock_in6_e = (struct sockaddr_in6 *)&np->np_sockaddr;
286
287                 if (!memcmp(&sock_in6->sin6_addr.in6_u,
288                             &sock_in6_e->sin6_addr.in6_u,
289                             sizeof(struct in6_addr)))
290                         ip_match = true;
291
292                 port = ntohs(sock_in6->sin6_port);
293         } else {
294                 sock_in = (struct sockaddr_in *)sockaddr;
295                 sock_in_e = (struct sockaddr_in *)&np->np_sockaddr;
296
297                 if (sock_in->sin_addr.s_addr == sock_in_e->sin_addr.s_addr)
298                         ip_match = true;
299
300                 port = ntohs(sock_in->sin_port);
301         }
302
303         if ((ip_match == true) && (np->np_port == port) &&
304             (np->np_network_transport == network_transport))
305                 return true;
306
307         return false;
308 }
309
310 static struct iscsi_np *iscsit_get_np(
311         struct __kernel_sockaddr_storage *sockaddr,
312         int network_transport)
313 {
314         struct iscsi_np *np;
315         bool match;
316
317         spin_lock_bh(&np_lock);
318         list_for_each_entry(np, &g_np_list, np_list) {
319                 spin_lock(&np->np_thread_lock);
320                 if (np->np_thread_state != ISCSI_NP_THREAD_ACTIVE) {
321                         spin_unlock(&np->np_thread_lock);
322                         continue;
323                 }
324
325                 match = iscsit_check_np_match(sockaddr, np, network_transport);
326                 if (match == true) {
327                         /*
328                          * Increment the np_exports reference count now to
329                          * prevent iscsit_del_np() below from being called
330                          * while iscsi_tpg_add_network_portal() is called.
331                          */
332                         np->np_exports++;
333                         spin_unlock(&np->np_thread_lock);
334                         spin_unlock_bh(&np_lock);
335                         return np;
336                 }
337                 spin_unlock(&np->np_thread_lock);
338         }
339         spin_unlock_bh(&np_lock);
340
341         return NULL;
342 }
343
344 struct iscsi_np *iscsit_add_np(
345         struct __kernel_sockaddr_storage *sockaddr,
346         char *ip_str,
347         int network_transport)
348 {
349         struct sockaddr_in *sock_in;
350         struct sockaddr_in6 *sock_in6;
351         struct iscsi_np *np;
352         int ret;
353         /*
354          * Locate the existing struct iscsi_np if already active..
355          */
356         np = iscsit_get_np(sockaddr, network_transport);
357         if (np)
358                 return np;
359
360         np = kzalloc(sizeof(struct iscsi_np), GFP_KERNEL);
361         if (!np) {
362                 pr_err("Unable to allocate memory for struct iscsi_np\n");
363                 return ERR_PTR(-ENOMEM);
364         }
365
366         np->np_flags |= NPF_IP_NETWORK;
367         if (sockaddr->ss_family == AF_INET6) {
368                 sock_in6 = (struct sockaddr_in6 *)sockaddr;
369                 snprintf(np->np_ip, IPV6_ADDRESS_SPACE, "%s", ip_str);
370                 np->np_port = ntohs(sock_in6->sin6_port);
371         } else {
372                 sock_in = (struct sockaddr_in *)sockaddr;
373                 sprintf(np->np_ip, "%s", ip_str);
374                 np->np_port = ntohs(sock_in->sin_port);
375         }
376
377         np->np_network_transport = network_transport;
378         spin_lock_init(&np->np_thread_lock);
379         init_completion(&np->np_restart_comp);
380         INIT_LIST_HEAD(&np->np_list);
381
382         ret = iscsi_target_setup_login_socket(np, sockaddr);
383         if (ret != 0) {
384                 kfree(np);
385                 return ERR_PTR(ret);
386         }
387
388         np->np_thread = kthread_run(iscsi_target_login_thread, np, "iscsi_np");
389         if (IS_ERR(np->np_thread)) {
390                 pr_err("Unable to create kthread: iscsi_np\n");
391                 ret = PTR_ERR(np->np_thread);
392                 kfree(np);
393                 return ERR_PTR(ret);
394         }
395         /*
396          * Increment the np_exports reference count now to prevent
397          * iscsit_del_np() below from being run while a new call to
398          * iscsi_tpg_add_network_portal() for a matching iscsi_np is
399          * active.  We don't need to hold np->np_thread_lock at this
400          * point because iscsi_np has not been added to g_np_list yet.
401          */
402         np->np_exports = 1;
403
404         spin_lock_bh(&np_lock);
405         list_add_tail(&np->np_list, &g_np_list);
406         spin_unlock_bh(&np_lock);
407
408         pr_debug("CORE[0] - Added Network Portal: %s:%hu on %s\n",
409                 np->np_ip, np->np_port, np->np_transport->name);
410
411         return np;
412 }
413
414 int iscsit_reset_np_thread(
415         struct iscsi_np *np,
416         struct iscsi_tpg_np *tpg_np,
417         struct iscsi_portal_group *tpg,
418         bool shutdown)
419 {
420         spin_lock_bh(&np->np_thread_lock);
421         if (np->np_thread_state == ISCSI_NP_THREAD_INACTIVE) {
422                 spin_unlock_bh(&np->np_thread_lock);
423                 return 0;
424         }
425         np->np_thread_state = ISCSI_NP_THREAD_RESET;
426
427         if (np->np_thread) {
428                 spin_unlock_bh(&np->np_thread_lock);
429                 send_sig(SIGINT, np->np_thread, 1);
430                 wait_for_completion(&np->np_restart_comp);
431                 spin_lock_bh(&np->np_thread_lock);
432         }
433         spin_unlock_bh(&np->np_thread_lock);
434
435         if (tpg_np && shutdown) {
436                 kref_put(&tpg_np->tpg_np_kref, iscsit_login_kref_put);
437
438                 wait_for_completion(&tpg_np->tpg_np_comp);
439         }
440
441         return 0;
442 }
443
444 static void iscsit_free_np(struct iscsi_np *np)
445 {
446         if (np->np_socket)
447                 sock_release(np->np_socket);
448 }
449
450 int iscsit_del_np(struct iscsi_np *np)
451 {
452         spin_lock_bh(&np->np_thread_lock);
453         np->np_exports--;
454         if (np->np_exports) {
455                 spin_unlock_bh(&np->np_thread_lock);
456                 return 0;
457         }
458         np->np_thread_state = ISCSI_NP_THREAD_SHUTDOWN;
459         spin_unlock_bh(&np->np_thread_lock);
460
461         if (np->np_thread) {
462                 /*
463                  * We need to send the signal to wakeup Linux/Net
464                  * which may be sleeping in sock_accept()..
465                  */
466                 send_sig(SIGINT, np->np_thread, 1);
467                 kthread_stop(np->np_thread);
468         }
469
470         np->np_transport->iscsit_free_np(np);
471
472         spin_lock_bh(&np_lock);
473         list_del(&np->np_list);
474         spin_unlock_bh(&np_lock);
475
476         pr_debug("CORE[0] - Removed Network Portal: %s:%hu on %s\n",
477                 np->np_ip, np->np_port, np->np_transport->name);
478
479         iscsit_put_transport(np->np_transport);
480         kfree(np);
481         return 0;
482 }
483
484 static int iscsit_immediate_queue(struct iscsi_conn *, struct iscsi_cmd *, int);
485 static int iscsit_response_queue(struct iscsi_conn *, struct iscsi_cmd *, int);
486
487 static int iscsit_queue_rsp(struct iscsi_conn *conn, struct iscsi_cmd *cmd)
488 {
489         iscsit_add_cmd_to_response_queue(cmd, cmd->conn, cmd->i_state);
490         return 0;
491 }
492
493 static struct iscsit_transport iscsi_target_transport = {
494         .name                   = "iSCSI/TCP",
495         .transport_type         = ISCSI_TCP,
496         .owner                  = NULL,
497         .iscsit_setup_np        = iscsit_setup_np,
498         .iscsit_accept_np       = iscsit_accept_np,
499         .iscsit_free_np         = iscsit_free_np,
500         .iscsit_get_login_rx    = iscsit_get_login_rx,
501         .iscsit_put_login_tx    = iscsit_put_login_tx,
502         .iscsit_get_dataout     = iscsit_build_r2ts_for_cmd,
503         .iscsit_immediate_queue = iscsit_immediate_queue,
504         .iscsit_response_queue  = iscsit_response_queue,
505         .iscsit_queue_data_in   = iscsit_queue_rsp,
506         .iscsit_queue_status    = iscsit_queue_rsp,
507 };
508
509 static int __init iscsi_target_init_module(void)
510 {
511         int ret = 0;
512
513         pr_debug("iSCSI-Target "ISCSIT_VERSION"\n");
514
515         iscsit_global = kzalloc(sizeof(struct iscsit_global), GFP_KERNEL);
516         if (!iscsit_global) {
517                 pr_err("Unable to allocate memory for iscsit_global\n");
518                 return -1;
519         }
520         mutex_init(&auth_id_lock);
521         spin_lock_init(&sess_idr_lock);
522         idr_init(&tiqn_idr);
523         idr_init(&sess_idr);
524
525         ret = iscsi_target_register_configfs();
526         if (ret < 0)
527                 goto out;
528
529         ret = iscsi_thread_set_init();
530         if (ret < 0)
531                 goto configfs_out;
532
533         if (iscsi_allocate_thread_sets(TARGET_THREAD_SET_COUNT) !=
534                         TARGET_THREAD_SET_COUNT) {
535                 pr_err("iscsi_allocate_thread_sets() returned"
536                         " unexpected value!\n");
537                 goto ts_out1;
538         }
539
540         lio_qr_cache = kmem_cache_create("lio_qr_cache",
541                         sizeof(struct iscsi_queue_req),
542                         __alignof__(struct iscsi_queue_req), 0, NULL);
543         if (!lio_qr_cache) {
544                 pr_err("nable to kmem_cache_create() for"
545                                 " lio_qr_cache\n");
546                 goto ts_out2;
547         }
548
549         lio_dr_cache = kmem_cache_create("lio_dr_cache",
550                         sizeof(struct iscsi_datain_req),
551                         __alignof__(struct iscsi_datain_req), 0, NULL);
552         if (!lio_dr_cache) {
553                 pr_err("Unable to kmem_cache_create() for"
554                                 " lio_dr_cache\n");
555                 goto qr_out;
556         }
557
558         lio_ooo_cache = kmem_cache_create("lio_ooo_cache",
559                         sizeof(struct iscsi_ooo_cmdsn),
560                         __alignof__(struct iscsi_ooo_cmdsn), 0, NULL);
561         if (!lio_ooo_cache) {
562                 pr_err("Unable to kmem_cache_create() for"
563                                 " lio_ooo_cache\n");
564                 goto dr_out;
565         }
566
567         lio_r2t_cache = kmem_cache_create("lio_r2t_cache",
568                         sizeof(struct iscsi_r2t), __alignof__(struct iscsi_r2t),
569                         0, NULL);
570         if (!lio_r2t_cache) {
571                 pr_err("Unable to kmem_cache_create() for"
572                                 " lio_r2t_cache\n");
573                 goto ooo_out;
574         }
575
576         iscsit_register_transport(&iscsi_target_transport);
577
578         if (iscsit_load_discovery_tpg() < 0)
579                 goto r2t_out;
580
581         return ret;
582 r2t_out:
583         kmem_cache_destroy(lio_r2t_cache);
584 ooo_out:
585         kmem_cache_destroy(lio_ooo_cache);
586 dr_out:
587         kmem_cache_destroy(lio_dr_cache);
588 qr_out:
589         kmem_cache_destroy(lio_qr_cache);
590 ts_out2:
591         iscsi_deallocate_thread_sets();
592 ts_out1:
593         iscsi_thread_set_free();
594 configfs_out:
595         iscsi_target_deregister_configfs();
596 out:
597         kfree(iscsit_global);
598         return -ENOMEM;
599 }
600
601 static void __exit iscsi_target_cleanup_module(void)
602 {
603         iscsi_deallocate_thread_sets();
604         iscsi_thread_set_free();
605         iscsit_release_discovery_tpg();
606         iscsit_unregister_transport(&iscsi_target_transport);
607         kmem_cache_destroy(lio_qr_cache);
608         kmem_cache_destroy(lio_dr_cache);
609         kmem_cache_destroy(lio_ooo_cache);
610         kmem_cache_destroy(lio_r2t_cache);
611
612         iscsi_target_deregister_configfs();
613
614         kfree(iscsit_global);
615 }
616
617 static int iscsit_add_reject(
618         struct iscsi_conn *conn,
619         u8 reason,
620         unsigned char *buf)
621 {
622         struct iscsi_cmd *cmd;
623
624         cmd = iscsit_allocate_cmd(conn, GFP_KERNEL);
625         if (!cmd)
626                 return -1;
627
628         cmd->iscsi_opcode = ISCSI_OP_REJECT;
629         cmd->reject_reason = reason;
630
631         cmd->buf_ptr = kmemdup(buf, ISCSI_HDR_LEN, GFP_KERNEL);
632         if (!cmd->buf_ptr) {
633                 pr_err("Unable to allocate memory for cmd->buf_ptr\n");
634                 iscsit_free_cmd(cmd, false);
635                 return -1;
636         }
637
638         spin_lock_bh(&conn->cmd_lock);
639         list_add_tail(&cmd->i_conn_node, &conn->conn_cmd_list);
640         spin_unlock_bh(&conn->cmd_lock);
641
642         cmd->i_state = ISTATE_SEND_REJECT;
643         iscsit_add_cmd_to_response_queue(cmd, conn, cmd->i_state);
644
645         return -1;
646 }
647
648 static int iscsit_add_reject_from_cmd(
649         struct iscsi_cmd *cmd,
650         u8 reason,
651         bool add_to_conn,
652         unsigned char *buf)
653 {
654         struct iscsi_conn *conn;
655
656         if (!cmd->conn) {
657                 pr_err("cmd->conn is NULL for ITT: 0x%08x\n",
658                                 cmd->init_task_tag);
659                 return -1;
660         }
661         conn = cmd->conn;
662
663         cmd->iscsi_opcode = ISCSI_OP_REJECT;
664         cmd->reject_reason = reason;
665
666         cmd->buf_ptr = kmemdup(buf, ISCSI_HDR_LEN, GFP_KERNEL);
667         if (!cmd->buf_ptr) {
668                 pr_err("Unable to allocate memory for cmd->buf_ptr\n");
669                 iscsit_free_cmd(cmd, false);
670                 return -1;
671         }
672
673         if (add_to_conn) {
674                 spin_lock_bh(&conn->cmd_lock);
675                 list_add_tail(&cmd->i_conn_node, &conn->conn_cmd_list);
676                 spin_unlock_bh(&conn->cmd_lock);
677         }
678
679         cmd->i_state = ISTATE_SEND_REJECT;
680         iscsit_add_cmd_to_response_queue(cmd, conn, cmd->i_state);
681         /*
682          * Perform the kref_put now if se_cmd has already been setup by
683          * scsit_setup_scsi_cmd()
684          */
685         if (cmd->se_cmd.se_tfo != NULL) {
686                 pr_debug("iscsi reject: calling target_put_sess_cmd >>>>>>\n");
687                 target_put_sess_cmd(conn->sess->se_sess, &cmd->se_cmd);
688         }
689         return -1;
690 }
691
692 static int iscsit_add_reject_cmd(struct iscsi_cmd *cmd, u8 reason,
693                                  unsigned char *buf)
694 {
695         return iscsit_add_reject_from_cmd(cmd, reason, true, buf);
696 }
697
698 int iscsit_reject_cmd(struct iscsi_cmd *cmd, u8 reason, unsigned char *buf)
699 {
700         return iscsit_add_reject_from_cmd(cmd, reason, false, buf);
701 }
702
703 /*
704  * Map some portion of the allocated scatterlist to an iovec, suitable for
705  * kernel sockets to copy data in/out.
706  */
707 static int iscsit_map_iovec(
708         struct iscsi_cmd *cmd,
709         struct kvec *iov,
710         u32 data_offset,
711         u32 data_length)
712 {
713         u32 i = 0;
714         struct scatterlist *sg;
715         unsigned int page_off;
716
717         /*
718          * We know each entry in t_data_sg contains a page.
719          */
720         sg = &cmd->se_cmd.t_data_sg[data_offset / PAGE_SIZE];
721         page_off = (data_offset % PAGE_SIZE);
722
723         cmd->first_data_sg = sg;
724         cmd->first_data_sg_off = page_off;
725
726         while (data_length) {
727                 u32 cur_len = min_t(u32, data_length, sg->length - page_off);
728
729                 iov[i].iov_base = kmap(sg_page(sg)) + sg->offset + page_off;
730                 iov[i].iov_len = cur_len;
731
732                 data_length -= cur_len;
733                 page_off = 0;
734                 sg = sg_next(sg);
735                 i++;
736         }
737
738         cmd->kmapped_nents = i;
739
740         return i;
741 }
742
743 static void iscsit_unmap_iovec(struct iscsi_cmd *cmd)
744 {
745         u32 i;
746         struct scatterlist *sg;
747
748         sg = cmd->first_data_sg;
749
750         for (i = 0; i < cmd->kmapped_nents; i++)
751                 kunmap(sg_page(&sg[i]));
752 }
753
754 static void iscsit_ack_from_expstatsn(struct iscsi_conn *conn, u32 exp_statsn)
755 {
756         struct iscsi_cmd *cmd;
757
758         conn->exp_statsn = exp_statsn;
759
760         if (conn->sess->sess_ops->RDMAExtensions)
761                 return;
762
763         spin_lock_bh(&conn->cmd_lock);
764         list_for_each_entry(cmd, &conn->conn_cmd_list, i_conn_node) {
765                 spin_lock(&cmd->istate_lock);
766                 if ((cmd->i_state == ISTATE_SENT_STATUS) &&
767                     iscsi_sna_lt(cmd->stat_sn, exp_statsn)) {
768                         cmd->i_state = ISTATE_REMOVE;
769                         spin_unlock(&cmd->istate_lock);
770                         iscsit_add_cmd_to_immediate_queue(cmd, conn,
771                                                 cmd->i_state);
772                         continue;
773                 }
774                 spin_unlock(&cmd->istate_lock);
775         }
776         spin_unlock_bh(&conn->cmd_lock);
777 }
778
779 static int iscsit_allocate_iovecs(struct iscsi_cmd *cmd)
780 {
781         u32 iov_count = max(1UL, DIV_ROUND_UP(cmd->se_cmd.data_length, PAGE_SIZE));
782
783         iov_count += ISCSI_IOV_DATA_BUFFER;
784
785         cmd->iov_data = kzalloc(iov_count * sizeof(struct kvec), GFP_KERNEL);
786         if (!cmd->iov_data) {
787                 pr_err("Unable to allocate cmd->iov_data\n");
788                 return -ENOMEM;
789         }
790
791         cmd->orig_iov_data_count = iov_count;
792         return 0;
793 }
794
795 int iscsit_setup_scsi_cmd(struct iscsi_conn *conn, struct iscsi_cmd *cmd,
796                           unsigned char *buf)
797 {
798         int data_direction, payload_length;
799         struct iscsi_scsi_req *hdr;
800         int iscsi_task_attr;
801         int sam_task_attr;
802
803         spin_lock_bh(&conn->sess->session_stats_lock);
804         conn->sess->cmd_pdus++;
805         if (conn->sess->se_sess->se_node_acl) {
806                 spin_lock(&conn->sess->se_sess->se_node_acl->stats_lock);
807                 conn->sess->se_sess->se_node_acl->num_cmds++;
808                 spin_unlock(&conn->sess->se_sess->se_node_acl->stats_lock);
809         }
810         spin_unlock_bh(&conn->sess->session_stats_lock);
811
812         hdr                     = (struct iscsi_scsi_req *) buf;
813         payload_length          = ntoh24(hdr->dlength);
814
815         /* FIXME; Add checks for AdditionalHeaderSegment */
816
817         if (!(hdr->flags & ISCSI_FLAG_CMD_WRITE) &&
818             !(hdr->flags & ISCSI_FLAG_CMD_FINAL)) {
819                 pr_err("ISCSI_FLAG_CMD_WRITE & ISCSI_FLAG_CMD_FINAL"
820                                 " not set. Bad iSCSI Initiator.\n");
821                 return iscsit_add_reject_cmd(cmd,
822                                              ISCSI_REASON_BOOKMARK_INVALID, buf);
823         }
824
825         if (((hdr->flags & ISCSI_FLAG_CMD_READ) ||
826              (hdr->flags & ISCSI_FLAG_CMD_WRITE)) && !hdr->data_length) {
827                 /*
828                  * Vmware ESX v3.0 uses a modified Cisco Initiator (v3.4.2)
829                  * that adds support for RESERVE/RELEASE.  There is a bug
830                  * add with this new functionality that sets R/W bits when
831                  * neither CDB carries any READ or WRITE datapayloads.
832                  */
833                 if ((hdr->cdb[0] == 0x16) || (hdr->cdb[0] == 0x17)) {
834                         hdr->flags &= ~ISCSI_FLAG_CMD_READ;
835                         hdr->flags &= ~ISCSI_FLAG_CMD_WRITE;
836                         goto done;
837                 }
838
839                 pr_err("ISCSI_FLAG_CMD_READ or ISCSI_FLAG_CMD_WRITE"
840                         " set when Expected Data Transfer Length is 0 for"
841                         " CDB: 0x%02x. Bad iSCSI Initiator.\n", hdr->cdb[0]);
842                 return iscsit_add_reject_cmd(cmd,
843                                              ISCSI_REASON_BOOKMARK_INVALID, buf);
844         }
845 done:
846
847         if (!(hdr->flags & ISCSI_FLAG_CMD_READ) &&
848             !(hdr->flags & ISCSI_FLAG_CMD_WRITE) && (hdr->data_length != 0)) {
849                 pr_err("ISCSI_FLAG_CMD_READ and/or ISCSI_FLAG_CMD_WRITE"
850                         " MUST be set if Expected Data Transfer Length is not 0."
851                         " Bad iSCSI Initiator\n");
852                 return iscsit_add_reject_cmd(cmd,
853                                              ISCSI_REASON_BOOKMARK_INVALID, buf);
854         }
855
856         if ((hdr->flags & ISCSI_FLAG_CMD_READ) &&
857             (hdr->flags & ISCSI_FLAG_CMD_WRITE)) {
858                 pr_err("Bidirectional operations not supported!\n");
859                 return iscsit_add_reject_cmd(cmd,
860                                              ISCSI_REASON_BOOKMARK_INVALID, buf);
861         }
862
863         if (hdr->opcode & ISCSI_OP_IMMEDIATE) {
864                 pr_err("Illegally set Immediate Bit in iSCSI Initiator"
865                                 " Scsi Command PDU.\n");
866                 return iscsit_add_reject_cmd(cmd,
867                                              ISCSI_REASON_BOOKMARK_INVALID, buf);
868         }
869
870         if (payload_length && !conn->sess->sess_ops->ImmediateData) {
871                 pr_err("ImmediateData=No but DataSegmentLength=%u,"
872                         " protocol error.\n", payload_length);
873                 return iscsit_add_reject_cmd(cmd,
874                                              ISCSI_REASON_PROTOCOL_ERROR, buf);
875         }
876
877         if ((be32_to_cpu(hdr->data_length) == payload_length) &&
878             (!(hdr->flags & ISCSI_FLAG_CMD_FINAL))) {
879                 pr_err("Expected Data Transfer Length and Length of"
880                         " Immediate Data are the same, but ISCSI_FLAG_CMD_FINAL"
881                         " bit is not set protocol error\n");
882                 return iscsit_add_reject_cmd(cmd,
883                                              ISCSI_REASON_PROTOCOL_ERROR, buf);
884         }
885
886         if (payload_length > be32_to_cpu(hdr->data_length)) {
887                 pr_err("DataSegmentLength: %u is greater than"
888                         " EDTL: %u, protocol error.\n", payload_length,
889                                 hdr->data_length);
890                 return iscsit_add_reject_cmd(cmd,
891                                              ISCSI_REASON_PROTOCOL_ERROR, buf);
892         }
893
894         if (payload_length > conn->conn_ops->MaxXmitDataSegmentLength) {
895                 pr_err("DataSegmentLength: %u is greater than"
896                         " MaxXmitDataSegmentLength: %u, protocol error.\n",
897                         payload_length, conn->conn_ops->MaxXmitDataSegmentLength);
898                 return iscsit_add_reject_cmd(cmd,
899                                              ISCSI_REASON_PROTOCOL_ERROR, buf);
900         }
901
902         if (payload_length > conn->sess->sess_ops->FirstBurstLength) {
903                 pr_err("DataSegmentLength: %u is greater than"
904                         " FirstBurstLength: %u, protocol error.\n",
905                         payload_length, conn->sess->sess_ops->FirstBurstLength);
906                 return iscsit_add_reject_cmd(cmd,
907                                              ISCSI_REASON_BOOKMARK_INVALID, buf);
908         }
909
910         data_direction = (hdr->flags & ISCSI_FLAG_CMD_WRITE) ? DMA_TO_DEVICE :
911                          (hdr->flags & ISCSI_FLAG_CMD_READ) ? DMA_FROM_DEVICE :
912                           DMA_NONE;
913
914         cmd->data_direction = data_direction;
915         iscsi_task_attr = hdr->flags & ISCSI_FLAG_CMD_ATTR_MASK;
916         /*
917          * Figure out the SAM Task Attribute for the incoming SCSI CDB
918          */
919         if ((iscsi_task_attr == ISCSI_ATTR_UNTAGGED) ||
920             (iscsi_task_attr == ISCSI_ATTR_SIMPLE))
921                 sam_task_attr = MSG_SIMPLE_TAG;
922         else if (iscsi_task_attr == ISCSI_ATTR_ORDERED)
923                 sam_task_attr = MSG_ORDERED_TAG;
924         else if (iscsi_task_attr == ISCSI_ATTR_HEAD_OF_QUEUE)
925                 sam_task_attr = MSG_HEAD_TAG;
926         else if (iscsi_task_attr == ISCSI_ATTR_ACA)
927                 sam_task_attr = MSG_ACA_TAG;
928         else {
929                 pr_debug("Unknown iSCSI Task Attribute: 0x%02x, using"
930                         " MSG_SIMPLE_TAG\n", iscsi_task_attr);
931                 sam_task_attr = MSG_SIMPLE_TAG;
932         }
933
934         cmd->iscsi_opcode       = ISCSI_OP_SCSI_CMD;
935         cmd->i_state            = ISTATE_NEW_CMD;
936         cmd->immediate_cmd      = ((hdr->opcode & ISCSI_OP_IMMEDIATE) ? 1 : 0);
937         cmd->immediate_data     = (payload_length) ? 1 : 0;
938         cmd->unsolicited_data   = ((!(hdr->flags & ISCSI_FLAG_CMD_FINAL) &&
939                                      (hdr->flags & ISCSI_FLAG_CMD_WRITE)) ? 1 : 0);
940         if (cmd->unsolicited_data)
941                 cmd->cmd_flags |= ICF_NON_IMMEDIATE_UNSOLICITED_DATA;
942
943         conn->sess->init_task_tag = cmd->init_task_tag = hdr->itt;
944         if (hdr->flags & ISCSI_FLAG_CMD_READ) {
945                 spin_lock_bh(&conn->sess->ttt_lock);
946                 cmd->targ_xfer_tag = conn->sess->targ_xfer_tag++;
947                 if (cmd->targ_xfer_tag == 0xFFFFFFFF)
948                         cmd->targ_xfer_tag = conn->sess->targ_xfer_tag++;
949                 spin_unlock_bh(&conn->sess->ttt_lock);
950         } else if (hdr->flags & ISCSI_FLAG_CMD_WRITE)
951                 cmd->targ_xfer_tag = 0xFFFFFFFF;
952         cmd->cmd_sn             = be32_to_cpu(hdr->cmdsn);
953         cmd->exp_stat_sn        = be32_to_cpu(hdr->exp_statsn);
954         cmd->first_burst_len    = payload_length;
955
956         if (!conn->sess->sess_ops->RDMAExtensions &&
957              cmd->data_direction == DMA_FROM_DEVICE) {
958                 struct iscsi_datain_req *dr;
959
960                 dr = iscsit_allocate_datain_req();
961                 if (!dr)
962                         return iscsit_add_reject_cmd(cmd,
963                                         ISCSI_REASON_BOOKMARK_NO_RESOURCES, buf);
964
965                 iscsit_attach_datain_req(cmd, dr);
966         }
967
968         /*
969          * Initialize struct se_cmd descriptor from target_core_mod infrastructure
970          */
971         transport_init_se_cmd(&cmd->se_cmd, &lio_target_fabric_configfs->tf_ops,
972                         conn->sess->se_sess, be32_to_cpu(hdr->data_length),
973                         cmd->data_direction, sam_task_attr,
974                         cmd->sense_buffer + 2);
975
976         pr_debug("Got SCSI Command, ITT: 0x%08x, CmdSN: 0x%08x,"
977                 " ExpXferLen: %u, Length: %u, CID: %hu\n", hdr->itt,
978                 hdr->cmdsn, be32_to_cpu(hdr->data_length), payload_length,
979                 conn->cid);
980
981         target_get_sess_cmd(conn->sess->se_sess, &cmd->se_cmd, true);
982
983         cmd->sense_reason = transport_lookup_cmd_lun(&cmd->se_cmd,
984                                                      scsilun_to_int(&hdr->lun));
985         if (cmd->sense_reason)
986                 goto attach_cmd;
987
988         cmd->sense_reason = target_setup_cmd_from_cdb(&cmd->se_cmd, hdr->cdb);
989         if (cmd->sense_reason) {
990                 if (cmd->sense_reason == TCM_OUT_OF_RESOURCES) {
991                         return iscsit_add_reject_cmd(cmd,
992                                         ISCSI_REASON_BOOKMARK_NO_RESOURCES, buf);
993                 }
994
995                 goto attach_cmd;
996         }
997
998         if (iscsit_build_pdu_and_seq_lists(cmd, payload_length) < 0) {
999                 return iscsit_add_reject_cmd(cmd,
1000                                 ISCSI_REASON_BOOKMARK_NO_RESOURCES, buf);
1001         }
1002
1003 attach_cmd:
1004         spin_lock_bh(&conn->cmd_lock);
1005         list_add_tail(&cmd->i_conn_node, &conn->conn_cmd_list);
1006         spin_unlock_bh(&conn->cmd_lock);
1007         /*
1008          * Check if we need to delay processing because of ALUA
1009          * Active/NonOptimized primary access state..
1010          */
1011         core_alua_check_nonop_delay(&cmd->se_cmd);
1012
1013         return 0;
1014 }
1015 EXPORT_SYMBOL(iscsit_setup_scsi_cmd);
1016
1017 void iscsit_set_unsoliticed_dataout(struct iscsi_cmd *cmd)
1018 {
1019         iscsit_set_dataout_sequence_values(cmd);
1020
1021         spin_lock_bh(&cmd->dataout_timeout_lock);
1022         iscsit_start_dataout_timer(cmd, cmd->conn);
1023         spin_unlock_bh(&cmd->dataout_timeout_lock);
1024 }
1025 EXPORT_SYMBOL(iscsit_set_unsoliticed_dataout);
1026
1027 int iscsit_process_scsi_cmd(struct iscsi_conn *conn, struct iscsi_cmd *cmd,
1028                             struct iscsi_scsi_req *hdr)
1029 {
1030         int cmdsn_ret = 0;
1031         /*
1032          * Check the CmdSN against ExpCmdSN/MaxCmdSN here if
1033          * the Immediate Bit is not set, and no Immediate
1034          * Data is attached.
1035          *
1036          * A PDU/CmdSN carrying Immediate Data can only
1037          * be processed after the DataCRC has passed.
1038          * If the DataCRC fails, the CmdSN MUST NOT
1039          * be acknowledged. (See below)
1040          */
1041         if (!cmd->immediate_data) {
1042                 cmdsn_ret = iscsit_sequence_cmd(conn, cmd,
1043                                         (unsigned char *)hdr, hdr->cmdsn);
1044                 if (cmdsn_ret == CMDSN_ERROR_CANNOT_RECOVER)
1045                         return -1;
1046                 else if (cmdsn_ret == CMDSN_LOWER_THAN_EXP) {
1047                         target_put_sess_cmd(conn->sess->se_sess, &cmd->se_cmd);
1048                         return 0;
1049                 }
1050         }
1051
1052         iscsit_ack_from_expstatsn(conn, be32_to_cpu(hdr->exp_statsn));
1053
1054         /*
1055          * If no Immediate Data is attached, it's OK to return now.
1056          */
1057         if (!cmd->immediate_data) {
1058                 if (!cmd->sense_reason && cmd->unsolicited_data)
1059                         iscsit_set_unsoliticed_dataout(cmd);
1060                 if (!cmd->sense_reason)
1061                         return 0;
1062
1063                 target_put_sess_cmd(conn->sess->se_sess, &cmd->se_cmd);
1064                 return 0;
1065         }
1066
1067         /*
1068          * Early CHECK_CONDITIONs with ImmediateData never make it to command
1069          * execution.  These exceptions are processed in CmdSN order using
1070          * iscsit_check_received_cmdsn() in iscsit_get_immediate_data() below.
1071          */
1072         if (cmd->sense_reason) {
1073                 if (cmd->reject_reason)
1074                         return 0;
1075
1076                 return 1;
1077         }
1078         /*
1079          * Call directly into transport_generic_new_cmd() to perform
1080          * the backend memory allocation.
1081          */
1082         cmd->sense_reason = transport_generic_new_cmd(&cmd->se_cmd);
1083         if (cmd->sense_reason)
1084                 return 1;
1085
1086         return 0;
1087 }
1088 EXPORT_SYMBOL(iscsit_process_scsi_cmd);
1089
1090 static int
1091 iscsit_get_immediate_data(struct iscsi_cmd *cmd, struct iscsi_scsi_req *hdr,
1092                           bool dump_payload)
1093 {
1094         struct iscsi_conn *conn = cmd->conn;
1095         int cmdsn_ret = 0, immed_ret = IMMEDIATE_DATA_NORMAL_OPERATION;
1096         /*
1097          * Special case for Unsupported SAM WRITE Opcodes and ImmediateData=Yes.
1098          */
1099         if (dump_payload == true)
1100                 goto after_immediate_data;
1101
1102         immed_ret = iscsit_handle_immediate_data(cmd, hdr,
1103                                         cmd->first_burst_len);
1104 after_immediate_data:
1105         if (immed_ret == IMMEDIATE_DATA_NORMAL_OPERATION) {
1106                 /*
1107                  * A PDU/CmdSN carrying Immediate Data passed
1108                  * DataCRC, check against ExpCmdSN/MaxCmdSN if
1109                  * Immediate Bit is not set.
1110                  */
1111                 cmdsn_ret = iscsit_sequence_cmd(cmd->conn, cmd,
1112                                         (unsigned char *)hdr, hdr->cmdsn);
1113                 if (cmdsn_ret == CMDSN_ERROR_CANNOT_RECOVER)
1114                         return -1;
1115
1116                 if (cmd->sense_reason || cmdsn_ret == CMDSN_LOWER_THAN_EXP) {
1117                         int rc;
1118
1119                         rc = iscsit_dump_data_payload(cmd->conn,
1120                                                       cmd->first_burst_len, 1);
1121                         target_put_sess_cmd(conn->sess->se_sess, &cmd->se_cmd);
1122                         return rc;
1123                 } else if (cmd->unsolicited_data)
1124                         iscsit_set_unsoliticed_dataout(cmd);
1125
1126         } else if (immed_ret == IMMEDIATE_DATA_ERL1_CRC_FAILURE) {
1127                 /*
1128                  * Immediate Data failed DataCRC and ERL>=1,
1129                  * silently drop this PDU and let the initiator
1130                  * plug the CmdSN gap.
1131                  *
1132                  * FIXME: Send Unsolicited NOPIN with reserved
1133                  * TTT here to help the initiator figure out
1134                  * the missing CmdSN, although they should be
1135                  * intelligent enough to determine the missing
1136                  * CmdSN and issue a retry to plug the sequence.
1137                  */
1138                 cmd->i_state = ISTATE_REMOVE;
1139                 iscsit_add_cmd_to_immediate_queue(cmd, cmd->conn, cmd->i_state);
1140         } else /* immed_ret == IMMEDIATE_DATA_CANNOT_RECOVER */
1141                 return -1;
1142
1143         return 0;
1144 }
1145
1146 static int
1147 iscsit_handle_scsi_cmd(struct iscsi_conn *conn, struct iscsi_cmd *cmd,
1148                            unsigned char *buf)
1149 {
1150         struct iscsi_scsi_req *hdr = (struct iscsi_scsi_req *)buf;
1151         int rc, immed_data;
1152         bool dump_payload = false;
1153
1154         rc = iscsit_setup_scsi_cmd(conn, cmd, buf);
1155         if (rc < 0)
1156                 return 0;
1157         /*
1158          * Allocation iovecs needed for struct socket operations for
1159          * traditional iSCSI block I/O.
1160          */
1161         if (iscsit_allocate_iovecs(cmd) < 0) {
1162                 return iscsit_add_reject_cmd(cmd,
1163                                 ISCSI_REASON_BOOKMARK_NO_RESOURCES, buf);
1164         }
1165         immed_data = cmd->immediate_data;
1166
1167         rc = iscsit_process_scsi_cmd(conn, cmd, hdr);
1168         if (rc < 0)
1169                 return rc;
1170         else if (rc > 0)
1171                 dump_payload = true;
1172
1173         if (!immed_data)
1174                 return 0;
1175
1176         return iscsit_get_immediate_data(cmd, hdr, dump_payload);
1177 }
1178
1179 static u32 iscsit_do_crypto_hash_sg(
1180         struct hash_desc *hash,
1181         struct iscsi_cmd *cmd,
1182         u32 data_offset,
1183         u32 data_length,
1184         u32 padding,
1185         u8 *pad_bytes)
1186 {
1187         u32 data_crc;
1188         u32 i;
1189         struct scatterlist *sg;
1190         unsigned int page_off;
1191
1192         crypto_hash_init(hash);
1193
1194         sg = cmd->first_data_sg;
1195         page_off = cmd->first_data_sg_off;
1196
1197         i = 0;
1198         while (data_length) {
1199                 u32 cur_len = min_t(u32, data_length, (sg[i].length - page_off));
1200
1201                 crypto_hash_update(hash, &sg[i], cur_len);
1202
1203                 data_length -= cur_len;
1204                 page_off = 0;
1205                 i++;
1206         }
1207
1208         if (padding) {
1209                 struct scatterlist pad_sg;
1210
1211                 sg_init_one(&pad_sg, pad_bytes, padding);
1212                 crypto_hash_update(hash, &pad_sg, padding);
1213         }
1214         crypto_hash_final(hash, (u8 *) &data_crc);
1215
1216         return data_crc;
1217 }
1218
1219 static void iscsit_do_crypto_hash_buf(
1220         struct hash_desc *hash,
1221         const void *buf,
1222         u32 payload_length,
1223         u32 padding,
1224         u8 *pad_bytes,
1225         u8 *data_crc)
1226 {
1227         struct scatterlist sg;
1228
1229         crypto_hash_init(hash);
1230
1231         sg_init_one(&sg, buf, payload_length);
1232         crypto_hash_update(hash, &sg, payload_length);
1233
1234         if (padding) {
1235                 sg_init_one(&sg, pad_bytes, padding);
1236                 crypto_hash_update(hash, &sg, padding);
1237         }
1238         crypto_hash_final(hash, data_crc);
1239 }
1240
1241 int
1242 iscsit_check_dataout_hdr(struct iscsi_conn *conn, unsigned char *buf,
1243                           struct iscsi_cmd **out_cmd)
1244 {
1245         struct iscsi_data *hdr = (struct iscsi_data *)buf;
1246         struct iscsi_cmd *cmd = NULL;
1247         struct se_cmd *se_cmd;
1248         u32 payload_length = ntoh24(hdr->dlength);
1249         int rc;
1250
1251         if (!payload_length) {
1252                 pr_err("DataOUT payload is ZERO, protocol error.\n");
1253                 return iscsit_add_reject(conn, ISCSI_REASON_PROTOCOL_ERROR,
1254                                          buf);
1255         }
1256
1257         /* iSCSI write */
1258         spin_lock_bh(&conn->sess->session_stats_lock);
1259         conn->sess->rx_data_octets += payload_length;
1260         if (conn->sess->se_sess->se_node_acl) {
1261                 spin_lock(&conn->sess->se_sess->se_node_acl->stats_lock);
1262                 conn->sess->se_sess->se_node_acl->write_bytes += payload_length;
1263                 spin_unlock(&conn->sess->se_sess->se_node_acl->stats_lock);
1264         }
1265         spin_unlock_bh(&conn->sess->session_stats_lock);
1266
1267         if (payload_length > conn->conn_ops->MaxXmitDataSegmentLength) {
1268                 pr_err("DataSegmentLength: %u is greater than"
1269                         " MaxXmitDataSegmentLength: %u\n", payload_length,
1270                         conn->conn_ops->MaxXmitDataSegmentLength);
1271                 return iscsit_add_reject(conn, ISCSI_REASON_PROTOCOL_ERROR,
1272                                          buf);
1273         }
1274
1275         cmd = iscsit_find_cmd_from_itt_or_dump(conn, hdr->itt,
1276                         payload_length);
1277         if (!cmd)
1278                 return 0;
1279
1280         pr_debug("Got DataOut ITT: 0x%08x, TTT: 0x%08x,"
1281                 " DataSN: 0x%08x, Offset: %u, Length: %u, CID: %hu\n",
1282                 hdr->itt, hdr->ttt, hdr->datasn, ntohl(hdr->offset),
1283                 payload_length, conn->cid);
1284
1285         if (cmd->cmd_flags & ICF_GOT_LAST_DATAOUT) {
1286                 pr_err("Command ITT: 0x%08x received DataOUT after"
1287                         " last DataOUT received, dumping payload\n",
1288                         cmd->init_task_tag);
1289                 return iscsit_dump_data_payload(conn, payload_length, 1);
1290         }
1291
1292         if (cmd->data_direction != DMA_TO_DEVICE) {
1293                 pr_err("Command ITT: 0x%08x received DataOUT for a"
1294                         " NON-WRITE command.\n", cmd->init_task_tag);
1295                 return iscsit_reject_cmd(cmd, ISCSI_REASON_PROTOCOL_ERROR, buf);
1296         }
1297         se_cmd = &cmd->se_cmd;
1298         iscsit_mod_dataout_timer(cmd);
1299
1300         if ((be32_to_cpu(hdr->offset) + payload_length) > cmd->se_cmd.data_length) {
1301                 pr_err("DataOut Offset: %u, Length %u greater than"
1302                         " iSCSI Command EDTL %u, protocol error.\n",
1303                         hdr->offset, payload_length, cmd->se_cmd.data_length);
1304                 return iscsit_reject_cmd(cmd, ISCSI_REASON_BOOKMARK_INVALID, buf);
1305         }
1306
1307         if (cmd->unsolicited_data) {
1308                 int dump_unsolicited_data = 0;
1309
1310                 if (conn->sess->sess_ops->InitialR2T) {
1311                         pr_err("Received unexpected unsolicited data"
1312                                 " while InitialR2T=Yes, protocol error.\n");
1313                         transport_send_check_condition_and_sense(&cmd->se_cmd,
1314                                         TCM_UNEXPECTED_UNSOLICITED_DATA, 0);
1315                         return -1;
1316                 }
1317                 /*
1318                  * Special case for dealing with Unsolicited DataOUT
1319                  * and Unsupported SAM WRITE Opcodes and SE resource allocation
1320                  * failures;
1321                  */
1322
1323                 /* Something's amiss if we're not in WRITE_PENDING state... */
1324                 WARN_ON(se_cmd->t_state != TRANSPORT_WRITE_PENDING);
1325                 if (!(se_cmd->se_cmd_flags & SCF_SUPPORTED_SAM_OPCODE))
1326                         dump_unsolicited_data = 1;
1327
1328                 if (dump_unsolicited_data) {
1329                         /*
1330                          * Check if a delayed TASK_ABORTED status needs to
1331                          * be sent now if the ISCSI_FLAG_CMD_FINAL has been
1332                          * received with the unsolicitied data out.
1333                          */
1334                         if (hdr->flags & ISCSI_FLAG_CMD_FINAL)
1335                                 iscsit_stop_dataout_timer(cmd);
1336
1337                         transport_check_aborted_status(se_cmd,
1338                                         (hdr->flags & ISCSI_FLAG_CMD_FINAL));
1339                         return iscsit_dump_data_payload(conn, payload_length, 1);
1340                 }
1341         } else {
1342                 /*
1343                  * For the normal solicited data path:
1344                  *
1345                  * Check for a delayed TASK_ABORTED status and dump any
1346                  * incoming data out payload if one exists.  Also, when the
1347                  * ISCSI_FLAG_CMD_FINAL is set to denote the end of the current
1348                  * data out sequence, we decrement outstanding_r2ts.  Once
1349                  * outstanding_r2ts reaches zero, go ahead and send the delayed
1350                  * TASK_ABORTED status.
1351                  */
1352                 if (se_cmd->transport_state & CMD_T_ABORTED) {
1353                         if (hdr->flags & ISCSI_FLAG_CMD_FINAL)
1354                                 if (--cmd->outstanding_r2ts < 1) {
1355                                         iscsit_stop_dataout_timer(cmd);
1356                                         transport_check_aborted_status(
1357                                                         se_cmd, 1);
1358                                 }
1359
1360                         return iscsit_dump_data_payload(conn, payload_length, 1);
1361                 }
1362         }
1363         /*
1364          * Preform DataSN, DataSequenceInOrder, DataPDUInOrder, and
1365          * within-command recovery checks before receiving the payload.
1366          */
1367         rc = iscsit_check_pre_dataout(cmd, buf);
1368         if (rc == DATAOUT_WITHIN_COMMAND_RECOVERY)
1369                 return 0;
1370         else if (rc == DATAOUT_CANNOT_RECOVER)
1371                 return -1;
1372
1373         *out_cmd = cmd;
1374         return 0;
1375 }
1376 EXPORT_SYMBOL(iscsit_check_dataout_hdr);
1377
1378 static int
1379 iscsit_get_dataout(struct iscsi_conn *conn, struct iscsi_cmd *cmd,
1380                    struct iscsi_data *hdr)
1381 {
1382         struct kvec *iov;
1383         u32 checksum, iov_count = 0, padding = 0, rx_got = 0, rx_size = 0;
1384         u32 payload_length = ntoh24(hdr->dlength);
1385         int iov_ret, data_crc_failed = 0;
1386
1387         rx_size += payload_length;
1388         iov = &cmd->iov_data[0];
1389
1390         iov_ret = iscsit_map_iovec(cmd, iov, be32_to_cpu(hdr->offset),
1391                                    payload_length);
1392         if (iov_ret < 0)
1393                 return -1;
1394
1395         iov_count += iov_ret;
1396
1397         padding = ((-payload_length) & 3);
1398         if (padding != 0) {
1399                 iov[iov_count].iov_base = cmd->pad_bytes;
1400                 iov[iov_count++].iov_len = padding;
1401                 rx_size += padding;
1402                 pr_debug("Receiving %u padding bytes.\n", padding);
1403         }
1404
1405         if (conn->conn_ops->DataDigest) {
1406                 iov[iov_count].iov_base = &checksum;
1407                 iov[iov_count++].iov_len = ISCSI_CRC_LEN;
1408                 rx_size += ISCSI_CRC_LEN;
1409         }
1410
1411         rx_got = rx_data(conn, &cmd->iov_data[0], iov_count, rx_size);
1412
1413         iscsit_unmap_iovec(cmd);
1414
1415         if (rx_got != rx_size)
1416                 return -1;
1417
1418         if (conn->conn_ops->DataDigest) {
1419                 u32 data_crc;
1420
1421                 data_crc = iscsit_do_crypto_hash_sg(&conn->conn_rx_hash, cmd,
1422                                                     be32_to_cpu(hdr->offset),
1423                                                     payload_length, padding,
1424                                                     cmd->pad_bytes);
1425
1426                 if (checksum != data_crc) {
1427                         pr_err("ITT: 0x%08x, Offset: %u, Length: %u,"
1428                                 " DataSN: 0x%08x, CRC32C DataDigest 0x%08x"
1429                                 " does not match computed 0x%08x\n",
1430                                 hdr->itt, hdr->offset, payload_length,
1431                                 hdr->datasn, checksum, data_crc);
1432                         data_crc_failed = 1;
1433                 } else {
1434                         pr_debug("Got CRC32C DataDigest 0x%08x for"
1435                                 " %u bytes of Data Out\n", checksum,
1436                                 payload_length);
1437                 }
1438         }
1439
1440         return data_crc_failed;
1441 }
1442
1443 int
1444 iscsit_check_dataout_payload(struct iscsi_cmd *cmd, struct iscsi_data *hdr,
1445                              bool data_crc_failed)
1446 {
1447         struct iscsi_conn *conn = cmd->conn;
1448         int rc, ooo_cmdsn;
1449         /*
1450          * Increment post receive data and CRC values or perform
1451          * within-command recovery.
1452          */
1453         rc = iscsit_check_post_dataout(cmd, (unsigned char *)hdr, data_crc_failed);
1454         if ((rc == DATAOUT_NORMAL) || (rc == DATAOUT_WITHIN_COMMAND_RECOVERY))
1455                 return 0;
1456         else if (rc == DATAOUT_SEND_R2T) {
1457                 iscsit_set_dataout_sequence_values(cmd);
1458                 conn->conn_transport->iscsit_get_dataout(conn, cmd, false);
1459         } else if (rc == DATAOUT_SEND_TO_TRANSPORT) {
1460                 /*
1461                  * Handle extra special case for out of order
1462                  * Unsolicited Data Out.
1463                  */
1464                 spin_lock_bh(&cmd->istate_lock);
1465                 ooo_cmdsn = (cmd->cmd_flags & ICF_OOO_CMDSN);
1466                 cmd->cmd_flags |= ICF_GOT_LAST_DATAOUT;
1467                 cmd->i_state = ISTATE_RECEIVED_LAST_DATAOUT;
1468                 spin_unlock_bh(&cmd->istate_lock);
1469
1470                 iscsit_stop_dataout_timer(cmd);
1471                 if (ooo_cmdsn)
1472                         return 0;
1473                 target_execute_cmd(&cmd->se_cmd);
1474                 return 0;
1475         } else /* DATAOUT_CANNOT_RECOVER */
1476                 return -1;
1477
1478         return 0;
1479 }
1480 EXPORT_SYMBOL(iscsit_check_dataout_payload);
1481
1482 static int iscsit_handle_data_out(struct iscsi_conn *conn, unsigned char *buf)
1483 {
1484         struct iscsi_cmd *cmd;
1485         struct iscsi_data *hdr = (struct iscsi_data *)buf;
1486         int rc;
1487         bool data_crc_failed = false;
1488
1489         rc = iscsit_check_dataout_hdr(conn, buf, &cmd);
1490         if (rc < 0)
1491                 return 0;
1492         else if (!cmd)
1493                 return 0;
1494
1495         rc = iscsit_get_dataout(conn, cmd, hdr);
1496         if (rc < 0)
1497                 return rc;
1498         else if (rc > 0)
1499                 data_crc_failed = true;
1500
1501         return iscsit_check_dataout_payload(cmd, hdr, data_crc_failed);
1502 }
1503
1504 int iscsit_setup_nop_out(struct iscsi_conn *conn, struct iscsi_cmd *cmd,
1505                          struct iscsi_nopout *hdr)
1506 {
1507         u32 payload_length = ntoh24(hdr->dlength);
1508
1509         if (hdr->itt == RESERVED_ITT && !(hdr->opcode & ISCSI_OP_IMMEDIATE)) {
1510                 pr_err("NOPOUT ITT is reserved, but Immediate Bit is"
1511                         " not set, protocol error.\n");
1512                 if (!cmd)
1513                         return iscsit_add_reject(conn, ISCSI_REASON_PROTOCOL_ERROR,
1514                                                  (unsigned char *)hdr);
1515
1516                 return iscsit_reject_cmd(cmd, ISCSI_REASON_PROTOCOL_ERROR,
1517                                          (unsigned char *)hdr);
1518         }
1519
1520         if (payload_length > conn->conn_ops->MaxXmitDataSegmentLength) {
1521                 pr_err("NOPOUT Ping Data DataSegmentLength: %u is"
1522                         " greater than MaxXmitDataSegmentLength: %u, protocol"
1523                         " error.\n", payload_length,
1524                         conn->conn_ops->MaxXmitDataSegmentLength);
1525                 if (!cmd)
1526                         return iscsit_add_reject(conn, ISCSI_REASON_PROTOCOL_ERROR,
1527                                                  (unsigned char *)hdr);
1528
1529                 return iscsit_reject_cmd(cmd, ISCSI_REASON_PROTOCOL_ERROR,
1530                                          (unsigned char *)hdr);
1531         }
1532
1533         pr_debug("Got NOPOUT Ping %s ITT: 0x%08x, TTT: 0x%08x,"
1534                 " CmdSN: 0x%08x, ExpStatSN: 0x%08x, Length: %u\n",
1535                 hdr->itt == RESERVED_ITT ? "Response" : "Request",
1536                 hdr->itt, hdr->ttt, hdr->cmdsn, hdr->exp_statsn,
1537                 payload_length);
1538         /*
1539          * This is not a response to a Unsolicited NopIN, which means
1540          * it can either be a NOPOUT ping request (with a valid ITT),
1541          * or a NOPOUT not requesting a NOPIN (with a reserved ITT).
1542          * Either way, make sure we allocate an struct iscsi_cmd, as both
1543          * can contain ping data.
1544          */
1545         if (hdr->ttt == cpu_to_be32(0xFFFFFFFF)) {
1546                 cmd->iscsi_opcode       = ISCSI_OP_NOOP_OUT;
1547                 cmd->i_state            = ISTATE_SEND_NOPIN;
1548                 cmd->immediate_cmd      = ((hdr->opcode & ISCSI_OP_IMMEDIATE) ?
1549                                                 1 : 0);
1550                 conn->sess->init_task_tag = cmd->init_task_tag = hdr->itt;
1551                 cmd->targ_xfer_tag      = 0xFFFFFFFF;
1552                 cmd->cmd_sn             = be32_to_cpu(hdr->cmdsn);
1553                 cmd->exp_stat_sn        = be32_to_cpu(hdr->exp_statsn);
1554                 cmd->data_direction     = DMA_NONE;
1555         }
1556
1557         return 0;
1558 }
1559 EXPORT_SYMBOL(iscsit_setup_nop_out);
1560
1561 int iscsit_process_nop_out(struct iscsi_conn *conn, struct iscsi_cmd *cmd,
1562                            struct iscsi_nopout *hdr)
1563 {
1564         struct iscsi_cmd *cmd_p = NULL;
1565         int cmdsn_ret = 0;
1566         /*
1567          * Initiator is expecting a NopIN ping reply..
1568          */
1569         if (hdr->itt != RESERVED_ITT) {
1570                 BUG_ON(!cmd);
1571
1572                 spin_lock_bh(&conn->cmd_lock);
1573                 list_add_tail(&cmd->i_conn_node, &conn->conn_cmd_list);
1574                 spin_unlock_bh(&conn->cmd_lock);
1575
1576                 iscsit_ack_from_expstatsn(conn, be32_to_cpu(hdr->exp_statsn));
1577
1578                 if (hdr->opcode & ISCSI_OP_IMMEDIATE) {
1579                         iscsit_add_cmd_to_response_queue(cmd, conn,
1580                                                          cmd->i_state);
1581                         return 0;
1582                 }
1583
1584                 cmdsn_ret = iscsit_sequence_cmd(conn, cmd,
1585                                 (unsigned char *)hdr, hdr->cmdsn);
1586                 if (cmdsn_ret == CMDSN_LOWER_THAN_EXP)
1587                         return 0;
1588                 if (cmdsn_ret == CMDSN_ERROR_CANNOT_RECOVER)
1589                         return -1;
1590
1591                 return 0;
1592         }
1593         /*
1594          * This was a response to a unsolicited NOPIN ping.
1595          */
1596         if (hdr->ttt != cpu_to_be32(0xFFFFFFFF)) {
1597                 cmd_p = iscsit_find_cmd_from_ttt(conn, be32_to_cpu(hdr->ttt));
1598                 if (!cmd_p)
1599                         return -EINVAL;
1600
1601                 iscsit_stop_nopin_response_timer(conn);
1602
1603                 cmd_p->i_state = ISTATE_REMOVE;
1604                 iscsit_add_cmd_to_immediate_queue(cmd_p, conn, cmd_p->i_state);
1605
1606                 iscsit_start_nopin_timer(conn);
1607                 return 0;
1608         }
1609         /*
1610          * Otherwise, initiator is not expecting a NOPIN is response.
1611          * Just ignore for now.
1612          */
1613         return 0;
1614 }
1615 EXPORT_SYMBOL(iscsit_process_nop_out);
1616
1617 static int iscsit_handle_nop_out(struct iscsi_conn *conn, struct iscsi_cmd *cmd,
1618                                  unsigned char *buf)
1619 {
1620         unsigned char *ping_data = NULL;
1621         struct iscsi_nopout *hdr = (struct iscsi_nopout *)buf;
1622         struct kvec *iov = NULL;
1623         u32 payload_length = ntoh24(hdr->dlength);
1624         int ret;
1625
1626         ret = iscsit_setup_nop_out(conn, cmd, hdr);
1627         if (ret < 0)
1628                 return 0;
1629         /*
1630          * Handle NOP-OUT payload for traditional iSCSI sockets
1631          */
1632         if (payload_length && hdr->ttt == cpu_to_be32(0xFFFFFFFF)) {
1633                 u32 checksum, data_crc, padding = 0;
1634                 int niov = 0, rx_got, rx_size = payload_length;
1635
1636                 ping_data = kzalloc(payload_length + 1, GFP_KERNEL);
1637                 if (!ping_data) {
1638                         pr_err("Unable to allocate memory for"
1639                                 " NOPOUT ping data.\n");
1640                         ret = -1;
1641                         goto out;
1642                 }
1643
1644                 iov = &cmd->iov_misc[0];
1645                 iov[niov].iov_base      = ping_data;
1646                 iov[niov++].iov_len     = payload_length;
1647
1648                 padding = ((-payload_length) & 3);
1649                 if (padding != 0) {
1650                         pr_debug("Receiving %u additional bytes"
1651                                 " for padding.\n", padding);
1652                         iov[niov].iov_base      = &cmd->pad_bytes;
1653                         iov[niov++].iov_len     = padding;
1654                         rx_size += padding;
1655                 }
1656                 if (conn->conn_ops->DataDigest) {
1657                         iov[niov].iov_base      = &checksum;
1658                         iov[niov++].iov_len     = ISCSI_CRC_LEN;
1659                         rx_size += ISCSI_CRC_LEN;
1660                 }
1661
1662                 rx_got = rx_data(conn, &cmd->iov_misc[0], niov, rx_size);
1663                 if (rx_got != rx_size) {
1664                         ret = -1;
1665                         goto out;
1666                 }
1667
1668                 if (conn->conn_ops->DataDigest) {
1669                         iscsit_do_crypto_hash_buf(&conn->conn_rx_hash,
1670                                         ping_data, payload_length,
1671                                         padding, cmd->pad_bytes,
1672                                         (u8 *)&data_crc);
1673
1674                         if (checksum != data_crc) {
1675                                 pr_err("Ping data CRC32C DataDigest"
1676                                 " 0x%08x does not match computed 0x%08x\n",
1677                                         checksum, data_crc);
1678                                 if (!conn->sess->sess_ops->ErrorRecoveryLevel) {
1679                                         pr_err("Unable to recover from"
1680                                         " NOPOUT Ping DataCRC failure while in"
1681                                                 " ERL=0.\n");
1682                                         ret = -1;
1683                                         goto out;
1684                                 } else {
1685                                         /*
1686                                          * Silently drop this PDU and let the
1687                                          * initiator plug the CmdSN gap.
1688                                          */
1689                                         pr_debug("Dropping NOPOUT"
1690                                         " Command CmdSN: 0x%08x due to"
1691                                         " DataCRC error.\n", hdr->cmdsn);
1692                                         ret = 0;
1693                                         goto out;
1694                                 }
1695                         } else {
1696                                 pr_debug("Got CRC32C DataDigest"
1697                                 " 0x%08x for %u bytes of ping data.\n",
1698                                         checksum, payload_length);
1699                         }
1700                 }
1701
1702                 ping_data[payload_length] = '\0';
1703                 /*
1704                  * Attach ping data to struct iscsi_cmd->buf_ptr.
1705                  */
1706                 cmd->buf_ptr = ping_data;
1707                 cmd->buf_ptr_size = payload_length;
1708
1709                 pr_debug("Got %u bytes of NOPOUT ping"
1710                         " data.\n", payload_length);
1711                 pr_debug("Ping Data: \"%s\"\n", ping_data);
1712         }
1713
1714         return iscsit_process_nop_out(conn, cmd, hdr);
1715 out:
1716         if (cmd)
1717                 iscsit_free_cmd(cmd, false);
1718
1719         kfree(ping_data);
1720         return ret;
1721 }
1722
1723 int
1724 iscsit_handle_task_mgt_cmd(struct iscsi_conn *conn, struct iscsi_cmd *cmd,
1725                            unsigned char *buf)
1726 {
1727         struct se_tmr_req *se_tmr;
1728         struct iscsi_tmr_req *tmr_req;
1729         struct iscsi_tm *hdr;
1730         int out_of_order_cmdsn = 0, ret;
1731         bool sess_ref = false;
1732         u8 function;
1733
1734         hdr                     = (struct iscsi_tm *) buf;
1735         hdr->flags &= ~ISCSI_FLAG_CMD_FINAL;
1736         function = hdr->flags;
1737
1738         pr_debug("Got Task Management Request ITT: 0x%08x, CmdSN:"
1739                 " 0x%08x, Function: 0x%02x, RefTaskTag: 0x%08x, RefCmdSN:"
1740                 " 0x%08x, CID: %hu\n", hdr->itt, hdr->cmdsn, function,
1741                 hdr->rtt, hdr->refcmdsn, conn->cid);
1742
1743         if ((function != ISCSI_TM_FUNC_ABORT_TASK) &&
1744             ((function != ISCSI_TM_FUNC_TASK_REASSIGN) &&
1745              hdr->rtt != RESERVED_ITT)) {
1746                 pr_err("RefTaskTag should be set to 0xFFFFFFFF.\n");
1747                 hdr->rtt = RESERVED_ITT;
1748         }
1749
1750         if ((function == ISCSI_TM_FUNC_TASK_REASSIGN) &&
1751                         !(hdr->opcode & ISCSI_OP_IMMEDIATE)) {
1752                 pr_err("Task Management Request TASK_REASSIGN not"
1753                         " issued as immediate command, bad iSCSI Initiator"
1754                                 "implementation\n");
1755                 return iscsit_add_reject_cmd(cmd,
1756                                              ISCSI_REASON_PROTOCOL_ERROR, buf);
1757         }
1758         if ((function != ISCSI_TM_FUNC_ABORT_TASK) &&
1759             be32_to_cpu(hdr->refcmdsn) != ISCSI_RESERVED_TAG)
1760                 hdr->refcmdsn = cpu_to_be32(ISCSI_RESERVED_TAG);
1761
1762         cmd->data_direction = DMA_NONE;
1763
1764         cmd->tmr_req = kzalloc(sizeof(struct iscsi_tmr_req), GFP_KERNEL);
1765         if (!cmd->tmr_req) {
1766                 pr_err("Unable to allocate memory for"
1767                         " Task Management command!\n");
1768                 return iscsit_add_reject_cmd(cmd,
1769                                              ISCSI_REASON_BOOKMARK_NO_RESOURCES,
1770                                              buf);
1771         }
1772
1773         /*
1774          * TASK_REASSIGN for ERL=2 / connection stays inside of
1775          * LIO-Target $FABRIC_MOD
1776          */
1777         if (function != ISCSI_TM_FUNC_TASK_REASSIGN) {
1778
1779                 u8 tcm_function;
1780                 int ret;
1781
1782                 transport_init_se_cmd(&cmd->se_cmd,
1783                                       &lio_target_fabric_configfs->tf_ops,
1784                                       conn->sess->se_sess, 0, DMA_NONE,
1785                                       MSG_SIMPLE_TAG, cmd->sense_buffer + 2);
1786
1787                 target_get_sess_cmd(conn->sess->se_sess, &cmd->se_cmd, true);
1788                 sess_ref = true;
1789
1790                 switch (function) {
1791                 case ISCSI_TM_FUNC_ABORT_TASK:
1792                         tcm_function = TMR_ABORT_TASK;
1793                         break;
1794                 case ISCSI_TM_FUNC_ABORT_TASK_SET:
1795                         tcm_function = TMR_ABORT_TASK_SET;
1796                         break;
1797                 case ISCSI_TM_FUNC_CLEAR_ACA:
1798                         tcm_function = TMR_CLEAR_ACA;
1799                         break;
1800                 case ISCSI_TM_FUNC_CLEAR_TASK_SET:
1801                         tcm_function = TMR_CLEAR_TASK_SET;
1802                         break;
1803                 case ISCSI_TM_FUNC_LOGICAL_UNIT_RESET:
1804                         tcm_function = TMR_LUN_RESET;
1805                         break;
1806                 case ISCSI_TM_FUNC_TARGET_WARM_RESET:
1807                         tcm_function = TMR_TARGET_WARM_RESET;
1808                         break;
1809                 case ISCSI_TM_FUNC_TARGET_COLD_RESET:
1810                         tcm_function = TMR_TARGET_COLD_RESET;
1811                         break;
1812                 default:
1813                         pr_err("Unknown iSCSI TMR Function:"
1814                                " 0x%02x\n", function);
1815                         return iscsit_add_reject_cmd(cmd,
1816                                 ISCSI_REASON_BOOKMARK_NO_RESOURCES, buf);
1817                 }
1818
1819                 ret = core_tmr_alloc_req(&cmd->se_cmd, cmd->tmr_req,
1820                                          tcm_function, GFP_KERNEL);
1821                 if (ret < 0)
1822                         return iscsit_add_reject_cmd(cmd,
1823                                 ISCSI_REASON_BOOKMARK_NO_RESOURCES, buf);
1824
1825                 cmd->tmr_req->se_tmr_req = cmd->se_cmd.se_tmr_req;
1826         }
1827
1828         cmd->iscsi_opcode       = ISCSI_OP_SCSI_TMFUNC;
1829         cmd->i_state            = ISTATE_SEND_TASKMGTRSP;
1830         cmd->immediate_cmd      = ((hdr->opcode & ISCSI_OP_IMMEDIATE) ? 1 : 0);
1831         cmd->init_task_tag      = hdr->itt;
1832         cmd->targ_xfer_tag      = 0xFFFFFFFF;
1833         cmd->cmd_sn             = be32_to_cpu(hdr->cmdsn);
1834         cmd->exp_stat_sn        = be32_to_cpu(hdr->exp_statsn);
1835         se_tmr                  = cmd->se_cmd.se_tmr_req;
1836         tmr_req                 = cmd->tmr_req;
1837         /*
1838          * Locate the struct se_lun for all TMRs not related to ERL=2 TASK_REASSIGN
1839          */
1840         if (function != ISCSI_TM_FUNC_TASK_REASSIGN) {
1841                 ret = transport_lookup_tmr_lun(&cmd->se_cmd,
1842                                                scsilun_to_int(&hdr->lun));
1843                 if (ret < 0) {
1844                         se_tmr->response = ISCSI_TMF_RSP_NO_LUN;
1845                         goto attach;
1846                 }
1847         }
1848
1849         switch (function) {
1850         case ISCSI_TM_FUNC_ABORT_TASK:
1851                 se_tmr->response = iscsit_tmr_abort_task(cmd, buf);
1852                 if (se_tmr->response)
1853                         goto attach;
1854                 break;
1855         case ISCSI_TM_FUNC_ABORT_TASK_SET:
1856         case ISCSI_TM_FUNC_CLEAR_ACA:
1857         case ISCSI_TM_FUNC_CLEAR_TASK_SET:
1858         case ISCSI_TM_FUNC_LOGICAL_UNIT_RESET:
1859                 break;
1860         case ISCSI_TM_FUNC_TARGET_WARM_RESET:
1861                 if (iscsit_tmr_task_warm_reset(conn, tmr_req, buf) < 0) {
1862                         se_tmr->response = ISCSI_TMF_RSP_AUTH_FAILED;
1863                         goto attach;
1864                 }
1865                 break;
1866         case ISCSI_TM_FUNC_TARGET_COLD_RESET:
1867                 if (iscsit_tmr_task_cold_reset(conn, tmr_req, buf) < 0) {
1868                         se_tmr->response = ISCSI_TMF_RSP_AUTH_FAILED;
1869                         goto attach;
1870                 }
1871                 break;
1872         case ISCSI_TM_FUNC_TASK_REASSIGN:
1873                 se_tmr->response = iscsit_tmr_task_reassign(cmd, buf);
1874                 /*
1875                  * Perform sanity checks on the ExpDataSN only if the
1876                  * TASK_REASSIGN was successful.
1877                  */
1878                 if (se_tmr->response)
1879                         break;
1880
1881                 if (iscsit_check_task_reassign_expdatasn(tmr_req, conn) < 0)
1882                         return iscsit_add_reject_cmd(cmd,
1883                                         ISCSI_REASON_BOOKMARK_INVALID, buf);
1884                 break;
1885         default:
1886                 pr_err("Unknown TMR function: 0x%02x, protocol"
1887                         " error.\n", function);
1888                 se_tmr->response = ISCSI_TMF_RSP_NOT_SUPPORTED;
1889                 goto attach;
1890         }
1891
1892         if ((function != ISCSI_TM_FUNC_TASK_REASSIGN) &&
1893             (se_tmr->response == ISCSI_TMF_RSP_COMPLETE))
1894                 se_tmr->call_transport = 1;
1895 attach:
1896         spin_lock_bh(&conn->cmd_lock);
1897         list_add_tail(&cmd->i_conn_node, &conn->conn_cmd_list);
1898         spin_unlock_bh(&conn->cmd_lock);
1899
1900         if (!(hdr->opcode & ISCSI_OP_IMMEDIATE)) {
1901                 int cmdsn_ret = iscsit_sequence_cmd(conn, cmd, buf, hdr->cmdsn);
1902                 if (cmdsn_ret == CMDSN_HIGHER_THAN_EXP)
1903                         out_of_order_cmdsn = 1;
1904                 else if (cmdsn_ret == CMDSN_LOWER_THAN_EXP)
1905                         return 0;
1906                 else if (cmdsn_ret == CMDSN_ERROR_CANNOT_RECOVER)
1907                         return -1;
1908         }
1909         iscsit_ack_from_expstatsn(conn, be32_to_cpu(hdr->exp_statsn));
1910
1911         if (out_of_order_cmdsn || !(hdr->opcode & ISCSI_OP_IMMEDIATE))
1912                 return 0;
1913         /*
1914          * Found the referenced task, send to transport for processing.
1915          */
1916         if (se_tmr->call_transport)
1917                 return transport_generic_handle_tmr(&cmd->se_cmd);
1918
1919         /*
1920          * Could not find the referenced LUN, task, or Task Management
1921          * command not authorized or supported.  Change state and
1922          * let the tx_thread send the response.
1923          *
1924          * For connection recovery, this is also the default action for
1925          * TMR TASK_REASSIGN.
1926          */
1927         if (sess_ref) {
1928                 pr_debug("Handle TMR, using sess_ref=true check\n");
1929                 target_put_sess_cmd(conn->sess->se_sess, &cmd->se_cmd);
1930         }
1931
1932         iscsit_add_cmd_to_response_queue(cmd, conn, cmd->i_state);
1933         return 0;
1934 }
1935 EXPORT_SYMBOL(iscsit_handle_task_mgt_cmd);
1936
1937 /* #warning FIXME: Support Text Command parameters besides SendTargets */
1938 int
1939 iscsit_setup_text_cmd(struct iscsi_conn *conn, struct iscsi_cmd *cmd,
1940                       struct iscsi_text *hdr)
1941 {
1942         u32 payload_length = ntoh24(hdr->dlength);
1943
1944         if (payload_length > conn->conn_ops->MaxXmitDataSegmentLength) {
1945                 pr_err("Unable to accept text parameter length: %u"
1946                         "greater than MaxXmitDataSegmentLength %u.\n",
1947                        payload_length, conn->conn_ops->MaxXmitDataSegmentLength);
1948                 return iscsit_reject_cmd(cmd, ISCSI_REASON_PROTOCOL_ERROR,
1949                                          (unsigned char *)hdr);
1950         }
1951
1952         pr_debug("Got Text Request: ITT: 0x%08x, CmdSN: 0x%08x,"
1953                 " ExpStatSN: 0x%08x, Length: %u\n", hdr->itt, hdr->cmdsn,
1954                 hdr->exp_statsn, payload_length);
1955
1956         cmd->iscsi_opcode       = ISCSI_OP_TEXT;
1957         cmd->i_state            = ISTATE_SEND_TEXTRSP;
1958         cmd->immediate_cmd      = ((hdr->opcode & ISCSI_OP_IMMEDIATE) ? 1 : 0);
1959         conn->sess->init_task_tag = cmd->init_task_tag  = hdr->itt;
1960         cmd->targ_xfer_tag      = 0xFFFFFFFF;
1961         cmd->cmd_sn             = be32_to_cpu(hdr->cmdsn);
1962         cmd->exp_stat_sn        = be32_to_cpu(hdr->exp_statsn);
1963         cmd->data_direction     = DMA_NONE;
1964
1965         return 0;
1966 }
1967 EXPORT_SYMBOL(iscsit_setup_text_cmd);
1968
1969 int
1970 iscsit_process_text_cmd(struct iscsi_conn *conn, struct iscsi_cmd *cmd,
1971                         struct iscsi_text *hdr)
1972 {
1973         unsigned char *text_in = cmd->text_in_ptr, *text_ptr;
1974         int cmdsn_ret;
1975
1976         if (!text_in) {
1977                 pr_err("Unable to locate text_in buffer for sendtargets"
1978                        " discovery\n");
1979                 goto reject;
1980         }
1981         if (strncmp("SendTargets", text_in, 11) != 0) {
1982                 pr_err("Received Text Data that is not"
1983                         " SendTargets, cannot continue.\n");
1984                 goto reject;
1985         }
1986         text_ptr = strchr(text_in, '=');
1987         if (!text_ptr) {
1988                 pr_err("No \"=\" separator found in Text Data,"
1989                         "  cannot continue.\n");
1990                 goto reject;
1991         }
1992         if (!strncmp("=All", text_ptr, 4)) {
1993                 cmd->cmd_flags |= IFC_SENDTARGETS_ALL;
1994         } else if (!strncmp("=iqn.", text_ptr, 5) ||
1995                    !strncmp("=eui.", text_ptr, 5)) {
1996                 cmd->cmd_flags |= IFC_SENDTARGETS_SINGLE;
1997         } else {
1998                 pr_err("Unable to locate valid SendTargets=%s value\n", text_ptr);
1999                 goto reject;
2000         }
2001
2002         spin_lock_bh(&conn->cmd_lock);
2003         list_add_tail(&cmd->i_conn_node, &conn->conn_cmd_list);
2004         spin_unlock_bh(&conn->cmd_lock);
2005
2006         iscsit_ack_from_expstatsn(conn, be32_to_cpu(hdr->exp_statsn));
2007
2008         if (!(hdr->opcode & ISCSI_OP_IMMEDIATE)) {
2009                 cmdsn_ret = iscsit_sequence_cmd(conn, cmd,
2010                                 (unsigned char *)hdr, hdr->cmdsn);
2011                 if (cmdsn_ret == CMDSN_ERROR_CANNOT_RECOVER)
2012                         return -1;
2013
2014                 return 0;
2015         }
2016
2017         return iscsit_execute_cmd(cmd, 0);
2018
2019 reject:
2020         return iscsit_reject_cmd(cmd, ISCSI_REASON_PROTOCOL_ERROR,
2021                                  (unsigned char *)hdr);
2022 }
2023 EXPORT_SYMBOL(iscsit_process_text_cmd);
2024
2025 static int
2026 iscsit_handle_text_cmd(struct iscsi_conn *conn, struct iscsi_cmd *cmd,
2027                        unsigned char *buf)
2028 {
2029         struct iscsi_text *hdr = (struct iscsi_text *)buf;
2030         char *text_in = NULL;
2031         u32 payload_length = ntoh24(hdr->dlength);
2032         int rx_size, rc;
2033
2034         rc = iscsit_setup_text_cmd(conn, cmd, hdr);
2035         if (rc < 0)
2036                 return 0;
2037
2038         rx_size = payload_length;
2039         if (payload_length) {
2040                 u32 checksum = 0, data_crc = 0;
2041                 u32 padding = 0, pad_bytes = 0;
2042                 int niov = 0, rx_got;
2043                 struct kvec iov[3];
2044
2045                 text_in = kzalloc(payload_length, GFP_KERNEL);
2046                 if (!text_in) {
2047                         pr_err("Unable to allocate memory for"
2048                                 " incoming text parameters\n");
2049                         goto reject;
2050                 }
2051                 cmd->text_in_ptr = text_in;
2052
2053                 memset(iov, 0, 3 * sizeof(struct kvec));
2054                 iov[niov].iov_base      = text_in;
2055                 iov[niov++].iov_len     = payload_length;
2056
2057                 padding = ((-payload_length) & 3);
2058                 if (padding != 0) {
2059                         iov[niov].iov_base = &pad_bytes;
2060                         iov[niov++].iov_len  = padding;
2061                         rx_size += padding;
2062                         pr_debug("Receiving %u additional bytes"
2063                                         " for padding.\n", padding);
2064                 }
2065                 if (conn->conn_ops->DataDigest) {
2066                         iov[niov].iov_base      = &checksum;
2067                         iov[niov++].iov_len     = ISCSI_CRC_LEN;
2068                         rx_size += ISCSI_CRC_LEN;
2069                 }
2070
2071                 rx_got = rx_data(conn, &iov[0], niov, rx_size);
2072                 if (rx_got != rx_size)
2073                         goto reject;
2074
2075                 if (conn->conn_ops->DataDigest) {
2076                         iscsit_do_crypto_hash_buf(&conn->conn_rx_hash,
2077                                         text_in, payload_length,
2078                                         padding, (u8 *)&pad_bytes,
2079                                         (u8 *)&data_crc);
2080
2081                         if (checksum != data_crc) {
2082                                 pr_err("Text data CRC32C DataDigest"
2083                                         " 0x%08x does not match computed"
2084                                         " 0x%08x\n", checksum, data_crc);
2085                                 if (!conn->sess->sess_ops->ErrorRecoveryLevel) {
2086                                         pr_err("Unable to recover from"
2087                                         " Text Data digest failure while in"
2088                                                 " ERL=0.\n");
2089                                         goto reject;
2090                                 } else {
2091                                         /*
2092                                          * Silently drop this PDU and let the
2093                                          * initiator plug the CmdSN gap.
2094                                          */
2095                                         pr_debug("Dropping Text"
2096                                         " Command CmdSN: 0x%08x due to"
2097                                         " DataCRC error.\n", hdr->cmdsn);
2098                                         kfree(text_in);
2099                                         return 0;
2100                                 }
2101                         } else {
2102                                 pr_debug("Got CRC32C DataDigest"
2103                                         " 0x%08x for %u bytes of text data.\n",
2104                                                 checksum, payload_length);
2105                         }
2106                 }
2107                 text_in[payload_length - 1] = '\0';
2108                 pr_debug("Successfully read %d bytes of text"
2109                                 " data.\n", payload_length);
2110         }
2111
2112         return iscsit_process_text_cmd(conn, cmd, hdr);
2113
2114 reject:
2115         kfree(cmd->text_in_ptr);
2116         cmd->text_in_ptr = NULL;
2117         return iscsit_reject_cmd(cmd, ISCSI_REASON_PROTOCOL_ERROR, buf);
2118 }
2119 EXPORT_SYMBOL(iscsit_handle_text_cmd);
2120
2121 int iscsit_logout_closesession(struct iscsi_cmd *cmd, struct iscsi_conn *conn)
2122 {
2123         struct iscsi_conn *conn_p;
2124         struct iscsi_session *sess = conn->sess;
2125
2126         pr_debug("Received logout request CLOSESESSION on CID: %hu"
2127                 " for SID: %u.\n", conn->cid, conn->sess->sid);
2128
2129         atomic_set(&sess->session_logout, 1);
2130         atomic_set(&conn->conn_logout_remove, 1);
2131         conn->conn_logout_reason = ISCSI_LOGOUT_REASON_CLOSE_SESSION;
2132
2133         iscsit_inc_conn_usage_count(conn);
2134         iscsit_inc_session_usage_count(sess);
2135
2136         spin_lock_bh(&sess->conn_lock);
2137         list_for_each_entry(conn_p, &sess->sess_conn_list, conn_list) {
2138                 if (conn_p->conn_state != TARG_CONN_STATE_LOGGED_IN)
2139                         continue;
2140
2141                 pr_debug("Moving to TARG_CONN_STATE_IN_LOGOUT.\n");
2142                 conn_p->conn_state = TARG_CONN_STATE_IN_LOGOUT;
2143         }
2144         spin_unlock_bh(&sess->conn_lock);
2145
2146         iscsit_add_cmd_to_response_queue(cmd, conn, cmd->i_state);
2147
2148         return 0;
2149 }
2150
2151 int iscsit_logout_closeconnection(struct iscsi_cmd *cmd, struct iscsi_conn *conn)
2152 {
2153         struct iscsi_conn *l_conn;
2154         struct iscsi_session *sess = conn->sess;
2155
2156         pr_debug("Received logout request CLOSECONNECTION for CID:"
2157                 " %hu on CID: %hu.\n", cmd->logout_cid, conn->cid);
2158
2159         /*
2160          * A Logout Request with a CLOSECONNECTION reason code for a CID
2161          * can arrive on a connection with a differing CID.
2162          */
2163         if (conn->cid == cmd->logout_cid) {
2164                 spin_lock_bh(&conn->state_lock);
2165                 pr_debug("Moving to TARG_CONN_STATE_IN_LOGOUT.\n");
2166                 conn->conn_state = TARG_CONN_STATE_IN_LOGOUT;
2167
2168                 atomic_set(&conn->conn_logout_remove, 1);
2169                 conn->conn_logout_reason = ISCSI_LOGOUT_REASON_CLOSE_CONNECTION;
2170                 iscsit_inc_conn_usage_count(conn);
2171
2172                 spin_unlock_bh(&conn->state_lock);
2173         } else {
2174                 /*
2175                  * Handle all different cid CLOSECONNECTION requests in
2176                  * iscsit_logout_post_handler_diffcid() as to give enough
2177                  * time for any non immediate command's CmdSN to be
2178                  * acknowledged on the connection in question.
2179                  *
2180                  * Here we simply make sure the CID is still around.
2181                  */
2182                 l_conn = iscsit_get_conn_from_cid(sess,
2183                                 cmd->logout_cid);
2184                 if (!l_conn) {
2185                         cmd->logout_response = ISCSI_LOGOUT_CID_NOT_FOUND;
2186                         iscsit_add_cmd_to_response_queue(cmd, conn,
2187                                         cmd->i_state);
2188                         return 0;
2189                 }
2190
2191                 iscsit_dec_conn_usage_count(l_conn);
2192         }
2193
2194         iscsit_add_cmd_to_response_queue(cmd, conn, cmd->i_state);
2195
2196         return 0;
2197 }
2198
2199 int iscsit_logout_removeconnforrecovery(struct iscsi_cmd *cmd, struct iscsi_conn *conn)
2200 {
2201         struct iscsi_session *sess = conn->sess;
2202
2203         pr_debug("Received explicit REMOVECONNFORRECOVERY logout for"
2204                 " CID: %hu on CID: %hu.\n", cmd->logout_cid, conn->cid);
2205
2206         if (sess->sess_ops->ErrorRecoveryLevel != 2) {
2207                 pr_err("Received Logout Request REMOVECONNFORRECOVERY"
2208                         " while ERL!=2.\n");
2209                 cmd->logout_response = ISCSI_LOGOUT_RECOVERY_UNSUPPORTED;
2210                 iscsit_add_cmd_to_response_queue(cmd, conn, cmd->i_state);
2211                 return 0;
2212         }
2213
2214         if (conn->cid == cmd->logout_cid) {
2215                 pr_err("Received Logout Request REMOVECONNFORRECOVERY"
2216                         " with CID: %hu on CID: %hu, implementation error.\n",
2217                                 cmd->logout_cid, conn->cid);
2218                 cmd->logout_response = ISCSI_LOGOUT_CLEANUP_FAILED;
2219                 iscsit_add_cmd_to_response_queue(cmd, conn, cmd->i_state);
2220                 return 0;
2221         }
2222
2223         iscsit_add_cmd_to_response_queue(cmd, conn, cmd->i_state);
2224
2225         return 0;
2226 }
2227
2228 int
2229 iscsit_handle_logout_cmd(struct iscsi_conn *conn, struct iscsi_cmd *cmd,
2230                         unsigned char *buf)
2231 {
2232         int cmdsn_ret, logout_remove = 0;
2233         u8 reason_code = 0;
2234         struct iscsi_logout *hdr;
2235         struct iscsi_tiqn *tiqn = iscsit_snmp_get_tiqn(conn);
2236
2237         hdr                     = (struct iscsi_logout *) buf;
2238         reason_code             = (hdr->flags & 0x7f);
2239
2240         if (tiqn) {
2241                 spin_lock(&tiqn->logout_stats.lock);
2242                 if (reason_code == ISCSI_LOGOUT_REASON_CLOSE_SESSION)
2243                         tiqn->logout_stats.normal_logouts++;
2244                 else
2245                         tiqn->logout_stats.abnormal_logouts++;
2246                 spin_unlock(&tiqn->logout_stats.lock);
2247         }
2248
2249         pr_debug("Got Logout Request ITT: 0x%08x CmdSN: 0x%08x"
2250                 " ExpStatSN: 0x%08x Reason: 0x%02x CID: %hu on CID: %hu\n",
2251                 hdr->itt, hdr->cmdsn, hdr->exp_statsn, reason_code,
2252                 hdr->cid, conn->cid);
2253
2254         if (conn->conn_state != TARG_CONN_STATE_LOGGED_IN) {
2255                 pr_err("Received logout request on connection that"
2256                         " is not in logged in state, ignoring request.\n");
2257                 iscsit_free_cmd(cmd, false);
2258                 return 0;
2259         }
2260
2261         cmd->iscsi_opcode       = ISCSI_OP_LOGOUT;
2262         cmd->i_state            = ISTATE_SEND_LOGOUTRSP;
2263         cmd->immediate_cmd      = ((hdr->opcode & ISCSI_OP_IMMEDIATE) ? 1 : 0);
2264         conn->sess->init_task_tag = cmd->init_task_tag  = hdr->itt;
2265         cmd->targ_xfer_tag      = 0xFFFFFFFF;
2266         cmd->cmd_sn             = be32_to_cpu(hdr->cmdsn);
2267         cmd->exp_stat_sn        = be32_to_cpu(hdr->exp_statsn);
2268         cmd->logout_cid         = be16_to_cpu(hdr->cid);
2269         cmd->logout_reason      = reason_code;
2270         cmd->data_direction     = DMA_NONE;
2271
2272         /*
2273          * We need to sleep in these cases (by returning 1) until the Logout
2274          * Response gets sent in the tx thread.
2275          */
2276         if ((reason_code == ISCSI_LOGOUT_REASON_CLOSE_SESSION) ||
2277            ((reason_code == ISCSI_LOGOUT_REASON_CLOSE_CONNECTION) &&
2278             be16_to_cpu(hdr->cid) == conn->cid))
2279                 logout_remove = 1;
2280
2281         spin_lock_bh(&conn->cmd_lock);
2282         list_add_tail(&cmd->i_conn_node, &conn->conn_cmd_list);
2283         spin_unlock_bh(&conn->cmd_lock);
2284
2285         if (reason_code != ISCSI_LOGOUT_REASON_RECOVERY)
2286                 iscsit_ack_from_expstatsn(conn, be32_to_cpu(hdr->exp_statsn));
2287
2288         /*
2289          * Immediate commands are executed, well, immediately.
2290          * Non-Immediate Logout Commands are executed in CmdSN order.
2291          */
2292         if (cmd->immediate_cmd) {
2293                 int ret = iscsit_execute_cmd(cmd, 0);
2294
2295                 if (ret < 0)
2296                         return ret;
2297         } else {
2298                 cmdsn_ret = iscsit_sequence_cmd(conn, cmd, buf, hdr->cmdsn);
2299                 if (cmdsn_ret == CMDSN_LOWER_THAN_EXP)
2300                         logout_remove = 0;
2301                 else if (cmdsn_ret == CMDSN_ERROR_CANNOT_RECOVER)
2302                         return -1;
2303         }
2304
2305         return logout_remove;
2306 }
2307 EXPORT_SYMBOL(iscsit_handle_logout_cmd);
2308
2309 static int iscsit_handle_snack(
2310         struct iscsi_conn *conn,
2311         unsigned char *buf)
2312 {
2313         struct iscsi_snack *hdr;
2314
2315         hdr                     = (struct iscsi_snack *) buf;
2316         hdr->flags              &= ~ISCSI_FLAG_CMD_FINAL;
2317
2318         pr_debug("Got ISCSI_INIT_SNACK, ITT: 0x%08x, ExpStatSN:"
2319                 " 0x%08x, Type: 0x%02x, BegRun: 0x%08x, RunLength: 0x%08x,"
2320                 " CID: %hu\n", hdr->itt, hdr->exp_statsn, hdr->flags,
2321                         hdr->begrun, hdr->runlength, conn->cid);
2322
2323         if (!conn->sess->sess_ops->ErrorRecoveryLevel) {
2324                 pr_err("Initiator sent SNACK request while in"
2325                         " ErrorRecoveryLevel=0.\n");
2326                 return iscsit_add_reject(conn, ISCSI_REASON_PROTOCOL_ERROR,
2327                                          buf);
2328         }
2329         /*
2330          * SNACK_DATA and SNACK_R2T are both 0,  so check which function to
2331          * call from inside iscsi_send_recovery_datain_or_r2t().
2332          */
2333         switch (hdr->flags & ISCSI_FLAG_SNACK_TYPE_MASK) {
2334         case 0:
2335                 return iscsit_handle_recovery_datain_or_r2t(conn, buf,
2336                         hdr->itt,
2337                         be32_to_cpu(hdr->ttt),
2338                         be32_to_cpu(hdr->begrun),
2339                         be32_to_cpu(hdr->runlength));
2340         case ISCSI_FLAG_SNACK_TYPE_STATUS:
2341                 return iscsit_handle_status_snack(conn, hdr->itt,
2342                         be32_to_cpu(hdr->ttt),
2343                         be32_to_cpu(hdr->begrun), be32_to_cpu(hdr->runlength));
2344         case ISCSI_FLAG_SNACK_TYPE_DATA_ACK:
2345                 return iscsit_handle_data_ack(conn, be32_to_cpu(hdr->ttt),
2346                         be32_to_cpu(hdr->begrun),
2347                         be32_to_cpu(hdr->runlength));
2348         case ISCSI_FLAG_SNACK_TYPE_RDATA:
2349                 /* FIXME: Support R-Data SNACK */
2350                 pr_err("R-Data SNACK Not Supported.\n");
2351                 return iscsit_add_reject(conn, ISCSI_REASON_PROTOCOL_ERROR,
2352                                          buf);
2353         default:
2354                 pr_err("Unknown SNACK type 0x%02x, protocol"
2355                         " error.\n", hdr->flags & 0x0f);
2356                 return iscsit_add_reject(conn, ISCSI_REASON_PROTOCOL_ERROR,
2357                                          buf);
2358         }
2359
2360         return 0;
2361 }
2362
2363 static void iscsit_rx_thread_wait_for_tcp(struct iscsi_conn *conn)
2364 {
2365         if ((conn->sock->sk->sk_shutdown & SEND_SHUTDOWN) ||
2366             (conn->sock->sk->sk_shutdown & RCV_SHUTDOWN)) {
2367                 wait_for_completion_interruptible_timeout(
2368                                         &conn->rx_half_close_comp,
2369                                         ISCSI_RX_THREAD_TCP_TIMEOUT * HZ);
2370         }
2371 }
2372
2373 static int iscsit_handle_immediate_data(
2374         struct iscsi_cmd *cmd,
2375         struct iscsi_scsi_req *hdr,
2376         u32 length)
2377 {
2378         int iov_ret, rx_got = 0, rx_size = 0;
2379         u32 checksum, iov_count = 0, padding = 0;
2380         struct iscsi_conn *conn = cmd->conn;
2381         struct kvec *iov;
2382
2383         iov_ret = iscsit_map_iovec(cmd, cmd->iov_data, cmd->write_data_done, length);
2384         if (iov_ret < 0)
2385                 return IMMEDIATE_DATA_CANNOT_RECOVER;
2386
2387         rx_size = length;
2388         iov_count = iov_ret;
2389         iov = &cmd->iov_data[0];
2390
2391         padding = ((-length) & 3);
2392         if (padding != 0) {
2393                 iov[iov_count].iov_base = cmd->pad_bytes;
2394                 iov[iov_count++].iov_len = padding;
2395                 rx_size += padding;
2396         }
2397
2398         if (conn->conn_ops->DataDigest) {
2399                 iov[iov_count].iov_base         = &checksum;
2400                 iov[iov_count++].iov_len        = ISCSI_CRC_LEN;
2401                 rx_size += ISCSI_CRC_LEN;
2402         }
2403
2404         rx_got = rx_data(conn, &cmd->iov_data[0], iov_count, rx_size);
2405
2406         iscsit_unmap_iovec(cmd);
2407
2408         if (rx_got != rx_size) {
2409                 iscsit_rx_thread_wait_for_tcp(conn);
2410                 return IMMEDIATE_DATA_CANNOT_RECOVER;
2411         }
2412
2413         if (conn->conn_ops->DataDigest) {
2414                 u32 data_crc;
2415
2416                 data_crc = iscsit_do_crypto_hash_sg(&conn->conn_rx_hash, cmd,
2417                                                     cmd->write_data_done, length, padding,
2418                                                     cmd->pad_bytes);
2419
2420                 if (checksum != data_crc) {
2421                         pr_err("ImmediateData CRC32C DataDigest 0x%08x"
2422                                 " does not match computed 0x%08x\n", checksum,
2423                                 data_crc);
2424
2425                         if (!conn->sess->sess_ops->ErrorRecoveryLevel) {
2426                                 pr_err("Unable to recover from"
2427                                         " Immediate Data digest failure while"
2428                                         " in ERL=0.\n");
2429                                 iscsit_reject_cmd(cmd,
2430                                                 ISCSI_REASON_DATA_DIGEST_ERROR,
2431                                                 (unsigned char *)hdr);
2432                                 return IMMEDIATE_DATA_CANNOT_RECOVER;
2433                         } else {
2434                                 iscsit_reject_cmd(cmd,
2435                                                 ISCSI_REASON_DATA_DIGEST_ERROR,
2436                                                 (unsigned char *)hdr);
2437                                 return IMMEDIATE_DATA_ERL1_CRC_FAILURE;
2438                         }
2439                 } else {
2440                         pr_debug("Got CRC32C DataDigest 0x%08x for"
2441                                 " %u bytes of Immediate Data\n", checksum,
2442                                 length);
2443                 }
2444         }
2445
2446         cmd->write_data_done += length;
2447
2448         if (cmd->write_data_done == cmd->se_cmd.data_length) {
2449                 spin_lock_bh(&cmd->istate_lock);
2450                 cmd->cmd_flags |= ICF_GOT_LAST_DATAOUT;
2451                 cmd->i_state = ISTATE_RECEIVED_LAST_DATAOUT;
2452                 spin_unlock_bh(&cmd->istate_lock);
2453         }
2454
2455         return IMMEDIATE_DATA_NORMAL_OPERATION;
2456 }
2457
2458 /*
2459  *      Called with sess->conn_lock held.
2460  */
2461 /* #warning iscsi_build_conn_drop_async_message() only sends out on connections
2462         with active network interface */
2463 static void iscsit_build_conn_drop_async_message(struct iscsi_conn *conn)
2464 {
2465         struct iscsi_cmd *cmd;
2466         struct iscsi_conn *conn_p;
2467
2468         /*
2469          * Only send a Asynchronous Message on connections whos network
2470          * interface is still functional.
2471          */
2472         list_for_each_entry(conn_p, &conn->sess->sess_conn_list, conn_list) {
2473                 if (conn_p->conn_state == TARG_CONN_STATE_LOGGED_IN) {
2474                         iscsit_inc_conn_usage_count(conn_p);
2475                         break;
2476                 }
2477         }
2478
2479         if (!conn_p)
2480                 return;
2481
2482         cmd = iscsit_allocate_cmd(conn_p, GFP_ATOMIC);
2483         if (!cmd) {
2484                 iscsit_dec_conn_usage_count(conn_p);
2485                 return;
2486         }
2487
2488         cmd->logout_cid = conn->cid;
2489         cmd->iscsi_opcode = ISCSI_OP_ASYNC_EVENT;
2490         cmd->i_state = ISTATE_SEND_ASYNCMSG;
2491
2492         spin_lock_bh(&conn_p->cmd_lock);
2493         list_add_tail(&cmd->i_conn_node, &conn_p->conn_cmd_list);
2494         spin_unlock_bh(&conn_p->cmd_lock);
2495
2496         iscsit_add_cmd_to_response_queue(cmd, conn_p, cmd->i_state);
2497         iscsit_dec_conn_usage_count(conn_p);
2498 }
2499
2500 static int iscsit_send_conn_drop_async_message(
2501         struct iscsi_cmd *cmd,
2502         struct iscsi_conn *conn)
2503 {
2504         struct iscsi_async *hdr;
2505
2506         cmd->tx_size = ISCSI_HDR_LEN;
2507         cmd->iscsi_opcode = ISCSI_OP_ASYNC_EVENT;
2508
2509         hdr                     = (struct iscsi_async *) cmd->pdu;
2510         hdr->opcode             = ISCSI_OP_ASYNC_EVENT;
2511         hdr->flags              = ISCSI_FLAG_CMD_FINAL;
2512         cmd->init_task_tag      = RESERVED_ITT;
2513         cmd->targ_xfer_tag      = 0xFFFFFFFF;
2514         put_unaligned_be64(0xFFFFFFFFFFFFFFFFULL, &hdr->rsvd4[0]);
2515         cmd->stat_sn            = conn->stat_sn++;
2516         hdr->statsn             = cpu_to_be32(cmd->stat_sn);
2517         hdr->exp_cmdsn          = cpu_to_be32(conn->sess->exp_cmd_sn);
2518         hdr->max_cmdsn          = cpu_to_be32(conn->sess->max_cmd_sn);
2519         hdr->async_event        = ISCSI_ASYNC_MSG_DROPPING_CONNECTION;
2520         hdr->param1             = cpu_to_be16(cmd->logout_cid);
2521         hdr->param2             = cpu_to_be16(conn->sess->sess_ops->DefaultTime2Wait);
2522         hdr->param3             = cpu_to_be16(conn->sess->sess_ops->DefaultTime2Retain);
2523
2524         if (conn->conn_ops->HeaderDigest) {
2525                 u32 *header_digest = (u32 *)&cmd->pdu[ISCSI_HDR_LEN];
2526
2527                 iscsit_do_crypto_hash_buf(&conn->conn_tx_hash, hdr,
2528                                 ISCSI_HDR_LEN, 0, NULL, (u8 *)header_digest);
2529
2530                 cmd->tx_size += ISCSI_CRC_LEN;
2531                 pr_debug("Attaching CRC32C HeaderDigest to"
2532                         " Async Message 0x%08x\n", *header_digest);
2533         }
2534
2535         cmd->iov_misc[0].iov_base       = cmd->pdu;
2536         cmd->iov_misc[0].iov_len        = cmd->tx_size;
2537         cmd->iov_misc_count             = 1;
2538
2539         pr_debug("Sending Connection Dropped Async Message StatSN:"
2540                 " 0x%08x, for CID: %hu on CID: %hu\n", cmd->stat_sn,
2541                         cmd->logout_cid, conn->cid);
2542         return 0;
2543 }
2544
2545 static void iscsit_tx_thread_wait_for_tcp(struct iscsi_conn *conn)
2546 {
2547         if ((conn->sock->sk->sk_shutdown & SEND_SHUTDOWN) ||
2548             (conn->sock->sk->sk_shutdown & RCV_SHUTDOWN)) {
2549                 wait_for_completion_interruptible_timeout(
2550                                         &conn->tx_half_close_comp,
2551                                         ISCSI_TX_THREAD_TCP_TIMEOUT * HZ);
2552         }
2553 }
2554
2555 static void
2556 iscsit_build_datain_pdu(struct iscsi_cmd *cmd, struct iscsi_conn *conn,
2557                         struct iscsi_datain *datain, struct iscsi_data_rsp *hdr,
2558                         bool set_statsn)
2559 {
2560         hdr->opcode             = ISCSI_OP_SCSI_DATA_IN;
2561         hdr->flags              = datain->flags;
2562         if (hdr->flags & ISCSI_FLAG_DATA_STATUS) {
2563                 if (cmd->se_cmd.se_cmd_flags & SCF_OVERFLOW_BIT) {
2564                         hdr->flags |= ISCSI_FLAG_DATA_OVERFLOW;
2565                         hdr->residual_count = cpu_to_be32(cmd->se_cmd.residual_count);
2566                 } else if (cmd->se_cmd.se_cmd_flags & SCF_UNDERFLOW_BIT) {
2567                         hdr->flags |= ISCSI_FLAG_DATA_UNDERFLOW;
2568                         hdr->residual_count = cpu_to_be32(cmd->se_cmd.residual_count);
2569                 }
2570         }
2571         hton24(hdr->dlength, datain->length);
2572         if (hdr->flags & ISCSI_FLAG_DATA_ACK)
2573                 int_to_scsilun(cmd->se_cmd.orig_fe_lun,
2574                                 (struct scsi_lun *)&hdr->lun);
2575         else
2576                 put_unaligned_le64(0xFFFFFFFFFFFFFFFFULL, &hdr->lun);
2577
2578         hdr->itt                = cmd->init_task_tag;
2579
2580         if (hdr->flags & ISCSI_FLAG_DATA_ACK)
2581                 hdr->ttt                = cpu_to_be32(cmd->targ_xfer_tag);
2582         else
2583                 hdr->ttt                = cpu_to_be32(0xFFFFFFFF);
2584         if (set_statsn)
2585                 hdr->statsn             = cpu_to_be32(cmd->stat_sn);
2586         else
2587                 hdr->statsn             = cpu_to_be32(0xFFFFFFFF);
2588
2589         hdr->exp_cmdsn          = cpu_to_be32(conn->sess->exp_cmd_sn);
2590         hdr->max_cmdsn          = cpu_to_be32(conn->sess->max_cmd_sn);
2591         hdr->datasn             = cpu_to_be32(datain->data_sn);
2592         hdr->offset             = cpu_to_be32(datain->offset);
2593
2594         pr_debug("Built DataIN ITT: 0x%08x, StatSN: 0x%08x,"
2595                 " DataSN: 0x%08x, Offset: %u, Length: %u, CID: %hu\n",
2596                 cmd->init_task_tag, ntohl(hdr->statsn), ntohl(hdr->datasn),
2597                 ntohl(hdr->offset), datain->length, conn->cid);
2598 }
2599
2600 static int iscsit_send_datain(struct iscsi_cmd *cmd, struct iscsi_conn *conn)
2601 {
2602         struct iscsi_data_rsp *hdr = (struct iscsi_data_rsp *)&cmd->pdu[0];
2603         struct iscsi_datain datain;
2604         struct iscsi_datain_req *dr;
2605         struct kvec *iov;
2606         u32 iov_count = 0, tx_size = 0;
2607         int eodr = 0, ret, iov_ret;
2608         bool set_statsn = false;
2609
2610         memset(&datain, 0, sizeof(struct iscsi_datain));
2611         dr = iscsit_get_datain_values(cmd, &datain);
2612         if (!dr) {
2613                 pr_err("iscsit_get_datain_values failed for ITT: 0x%08x\n",
2614                                 cmd->init_task_tag);
2615                 return -1;
2616         }
2617         /*
2618          * Be paranoid and double check the logic for now.
2619          */
2620         if ((datain.offset + datain.length) > cmd->se_cmd.data_length) {
2621                 pr_err("Command ITT: 0x%08x, datain.offset: %u and"
2622                         " datain.length: %u exceeds cmd->data_length: %u\n",
2623                         cmd->init_task_tag, datain.offset, datain.length,
2624                         cmd->se_cmd.data_length);
2625                 return -1;
2626         }
2627
2628         spin_lock_bh(&conn->sess->session_stats_lock);
2629         conn->sess->tx_data_octets += datain.length;
2630         if (conn->sess->se_sess->se_node_acl) {
2631                 spin_lock(&conn->sess->se_sess->se_node_acl->stats_lock);
2632                 conn->sess->se_sess->se_node_acl->read_bytes += datain.length;
2633                 spin_unlock(&conn->sess->se_sess->se_node_acl->stats_lock);
2634         }
2635         spin_unlock_bh(&conn->sess->session_stats_lock);
2636         /*
2637          * Special case for successfully execution w/ both DATAIN
2638          * and Sense Data.
2639          */
2640         if ((datain.flags & ISCSI_FLAG_DATA_STATUS) &&
2641             (cmd->se_cmd.se_cmd_flags & SCF_TRANSPORT_TASK_SENSE))
2642                 datain.flags &= ~ISCSI_FLAG_DATA_STATUS;
2643         else {
2644                 if ((dr->dr_complete == DATAIN_COMPLETE_NORMAL) ||
2645                     (dr->dr_complete == DATAIN_COMPLETE_CONNECTION_RECOVERY)) {
2646                         iscsit_increment_maxcmdsn(cmd, conn->sess);
2647                         cmd->stat_sn = conn->stat_sn++;
2648                         set_statsn = true;
2649                 } else if (dr->dr_complete ==
2650                            DATAIN_COMPLETE_WITHIN_COMMAND_RECOVERY)
2651                         set_statsn = true;
2652         }
2653
2654         iscsit_build_datain_pdu(cmd, conn, &datain, hdr, set_statsn);
2655
2656         iov = &cmd->iov_data[0];
2657         iov[iov_count].iov_base = cmd->pdu;
2658         iov[iov_count++].iov_len        = ISCSI_HDR_LEN;
2659         tx_size += ISCSI_HDR_LEN;
2660
2661         if (conn->conn_ops->HeaderDigest) {
2662                 u32 *header_digest = (u32 *)&cmd->pdu[ISCSI_HDR_LEN];
2663
2664                 iscsit_do_crypto_hash_buf(&conn->conn_tx_hash, cmd->pdu,
2665                                 ISCSI_HDR_LEN, 0, NULL, (u8 *)header_digest);
2666
2667                 iov[0].iov_len += ISCSI_CRC_LEN;
2668                 tx_size += ISCSI_CRC_LEN;
2669
2670                 pr_debug("Attaching CRC32 HeaderDigest"
2671                         " for DataIN PDU 0x%08x\n", *header_digest);
2672         }
2673
2674         iov_ret = iscsit_map_iovec(cmd, &cmd->iov_data[1],
2675                                 datain.offset, datain.length);
2676         if (iov_ret < 0)
2677                 return -1;
2678
2679         iov_count += iov_ret;
2680         tx_size += datain.length;
2681
2682         cmd->padding = ((-datain.length) & 3);
2683         if (cmd->padding) {
2684                 iov[iov_count].iov_base         = cmd->pad_bytes;
2685                 iov[iov_count++].iov_len        = cmd->padding;
2686                 tx_size += cmd->padding;
2687
2688                 pr_debug("Attaching %u padding bytes\n",
2689                                 cmd->padding);
2690         }
2691         if (conn->conn_ops->DataDigest) {
2692                 cmd->data_crc = iscsit_do_crypto_hash_sg(&conn->conn_tx_hash, cmd,
2693                          datain.offset, datain.length, cmd->padding, cmd->pad_bytes);
2694
2695                 iov[iov_count].iov_base = &cmd->data_crc;
2696                 iov[iov_count++].iov_len = ISCSI_CRC_LEN;
2697                 tx_size += ISCSI_CRC_LEN;
2698
2699                 pr_debug("Attached CRC32C DataDigest %d bytes, crc"
2700                         " 0x%08x\n", datain.length+cmd->padding, cmd->data_crc);
2701         }
2702
2703         cmd->iov_data_count = iov_count;
2704         cmd->tx_size = tx_size;
2705
2706         /* sendpage is preferred but can't insert markers */
2707         if (!conn->conn_ops->IFMarker)
2708                 ret = iscsit_fe_sendpage_sg(cmd, conn);
2709         else
2710                 ret = iscsit_send_tx_data(cmd, conn, 0);
2711
2712         iscsit_unmap_iovec(cmd);
2713
2714         if (ret < 0) {
2715                 iscsit_tx_thread_wait_for_tcp(conn);
2716                 return ret;
2717         }
2718
2719         if (dr->dr_complete) {
2720                 eodr = (cmd->se_cmd.se_cmd_flags & SCF_TRANSPORT_TASK_SENSE) ?
2721                                 2 : 1;
2722                 iscsit_free_datain_req(cmd, dr);
2723         }
2724
2725         return eodr;
2726 }
2727
2728 int
2729 iscsit_build_logout_rsp(struct iscsi_cmd *cmd, struct iscsi_conn *conn,
2730                         struct iscsi_logout_rsp *hdr)
2731 {
2732         struct iscsi_conn *logout_conn = NULL;
2733         struct iscsi_conn_recovery *cr = NULL;
2734         struct iscsi_session *sess = conn->sess;
2735         /*
2736          * The actual shutting down of Sessions and/or Connections
2737          * for CLOSESESSION and CLOSECONNECTION Logout Requests
2738          * is done in scsi_logout_post_handler().
2739          */
2740         switch (cmd->logout_reason) {
2741         case ISCSI_LOGOUT_REASON_CLOSE_SESSION:
2742                 pr_debug("iSCSI session logout successful, setting"
2743                         " logout response to ISCSI_LOGOUT_SUCCESS.\n");
2744                 cmd->logout_response = ISCSI_LOGOUT_SUCCESS;
2745                 break;
2746         case ISCSI_LOGOUT_REASON_CLOSE_CONNECTION:
2747                 if (cmd->logout_response == ISCSI_LOGOUT_CID_NOT_FOUND)
2748                         break;
2749                 /*
2750                  * For CLOSECONNECTION logout requests carrying
2751                  * a matching logout CID -> local CID, the reference
2752                  * for the local CID will have been incremented in
2753                  * iscsi_logout_closeconnection().
2754                  *
2755                  * For CLOSECONNECTION logout requests carrying
2756                  * a different CID than the connection it arrived
2757                  * on, the connection responding to cmd->logout_cid
2758                  * is stopped in iscsit_logout_post_handler_diffcid().
2759                  */
2760
2761                 pr_debug("iSCSI CID: %hu logout on CID: %hu"
2762                         " successful.\n", cmd->logout_cid, conn->cid);
2763                 cmd->logout_response = ISCSI_LOGOUT_SUCCESS;
2764                 break;
2765         case ISCSI_LOGOUT_REASON_RECOVERY:
2766                 if ((cmd->logout_response == ISCSI_LOGOUT_RECOVERY_UNSUPPORTED) ||
2767                     (cmd->logout_response == ISCSI_LOGOUT_CLEANUP_FAILED))
2768                         break;
2769                 /*
2770                  * If the connection is still active from our point of view
2771                  * force connection recovery to occur.
2772                  */
2773                 logout_conn = iscsit_get_conn_from_cid_rcfr(sess,
2774                                 cmd->logout_cid);
2775                 if (logout_conn) {
2776                         iscsit_connection_reinstatement_rcfr(logout_conn);
2777                         iscsit_dec_conn_usage_count(logout_conn);
2778                 }
2779
2780                 cr = iscsit_get_inactive_connection_recovery_entry(
2781                                 conn->sess, cmd->logout_cid);
2782                 if (!cr) {
2783                         pr_err("Unable to locate CID: %hu for"
2784                         " REMOVECONNFORRECOVERY Logout Request.\n",
2785                                 cmd->logout_cid);
2786                         cmd->logout_response = ISCSI_LOGOUT_CID_NOT_FOUND;
2787                         break;
2788                 }
2789
2790                 iscsit_discard_cr_cmds_by_expstatsn(cr, cmd->exp_stat_sn);
2791
2792                 pr_debug("iSCSI REMOVECONNFORRECOVERY logout"
2793                         " for recovery for CID: %hu on CID: %hu successful.\n",
2794                                 cmd->logout_cid, conn->cid);
2795                 cmd->logout_response = ISCSI_LOGOUT_SUCCESS;
2796                 break;
2797         default:
2798                 pr_err("Unknown cmd->logout_reason: 0x%02x\n",
2799                                 cmd->logout_reason);
2800                 return -1;
2801         }
2802
2803         hdr->opcode             = ISCSI_OP_LOGOUT_RSP;
2804         hdr->flags              |= ISCSI_FLAG_CMD_FINAL;
2805         hdr->response           = cmd->logout_response;
2806         hdr->itt                = cmd->init_task_tag;
2807         cmd->stat_sn            = conn->stat_sn++;
2808         hdr->statsn             = cpu_to_be32(cmd->stat_sn);
2809
2810         iscsit_increment_maxcmdsn(cmd, conn->sess);
2811         hdr->exp_cmdsn          = cpu_to_be32(conn->sess->exp_cmd_sn);
2812         hdr->max_cmdsn          = cpu_to_be32(conn->sess->max_cmd_sn);
2813
2814         pr_debug("Built Logout Response ITT: 0x%08x StatSN:"
2815                 " 0x%08x Response: 0x%02x CID: %hu on CID: %hu\n",
2816                 cmd->init_task_tag, cmd->stat_sn, hdr->response,
2817                 cmd->logout_cid, conn->cid);
2818
2819         return 0;
2820 }
2821 EXPORT_SYMBOL(iscsit_build_logout_rsp);
2822
2823 static int
2824 iscsit_send_logout(struct iscsi_cmd *cmd, struct iscsi_conn *conn)
2825 {
2826         struct kvec *iov;
2827         int niov = 0, tx_size, rc;
2828
2829         rc = iscsit_build_logout_rsp(cmd, conn,
2830                         (struct iscsi_logout_rsp *)&cmd->pdu[0]);
2831         if (rc < 0)
2832                 return rc;
2833
2834         tx_size = ISCSI_HDR_LEN;
2835         iov = &cmd->iov_misc[0];
2836         iov[niov].iov_base      = cmd->pdu;
2837         iov[niov++].iov_len     = ISCSI_HDR_LEN;
2838
2839         if (conn->conn_ops->HeaderDigest) {
2840                 u32 *header_digest = (u32 *)&cmd->pdu[ISCSI_HDR_LEN];
2841
2842                 iscsit_do_crypto_hash_buf(&conn->conn_tx_hash, &cmd->pdu[0],
2843                                 ISCSI_HDR_LEN, 0, NULL, (u8 *)header_digest);
2844
2845                 iov[0].iov_len += ISCSI_CRC_LEN;
2846                 tx_size += ISCSI_CRC_LEN;
2847                 pr_debug("Attaching CRC32C HeaderDigest to"
2848                         " Logout Response 0x%08x\n", *header_digest);
2849         }
2850         cmd->iov_misc_count = niov;
2851         cmd->tx_size = tx_size;
2852
2853         return 0;
2854 }
2855
2856 void
2857 iscsit_build_nopin_rsp(struct iscsi_cmd *cmd, struct iscsi_conn *conn,
2858                        struct iscsi_nopin *hdr, bool nopout_response)
2859 {
2860         hdr->opcode             = ISCSI_OP_NOOP_IN;
2861         hdr->flags              |= ISCSI_FLAG_CMD_FINAL;
2862         hton24(hdr->dlength, cmd->buf_ptr_size);
2863         if (nopout_response)
2864                 put_unaligned_le64(0xFFFFFFFFFFFFFFFFULL, &hdr->lun);
2865         hdr->itt                = cmd->init_task_tag;
2866         hdr->ttt                = cpu_to_be32(cmd->targ_xfer_tag);
2867         cmd->stat_sn            = (nopout_response) ? conn->stat_sn++ :
2868                                   conn->stat_sn;
2869         hdr->statsn             = cpu_to_be32(cmd->stat_sn);
2870
2871         if (nopout_response)
2872                 iscsit_increment_maxcmdsn(cmd, conn->sess);
2873
2874         hdr->exp_cmdsn          = cpu_to_be32(conn->sess->exp_cmd_sn);
2875         hdr->max_cmdsn          = cpu_to_be32(conn->sess->max_cmd_sn);
2876
2877         pr_debug("Built NOPIN %s Response ITT: 0x%08x, TTT: 0x%08x,"
2878                 " StatSN: 0x%08x, Length %u\n", (nopout_response) ?
2879                 "Solicitied" : "Unsolicitied", cmd->init_task_tag,
2880                 cmd->targ_xfer_tag, cmd->stat_sn, cmd->buf_ptr_size);
2881 }
2882 EXPORT_SYMBOL(iscsit_build_nopin_rsp);
2883
2884 /*
2885  *      Unsolicited NOPIN, either requesting a response or not.
2886  */
2887 static int iscsit_send_unsolicited_nopin(
2888         struct iscsi_cmd *cmd,
2889         struct iscsi_conn *conn,
2890         int want_response)
2891 {
2892         struct iscsi_nopin *hdr = (struct iscsi_nopin *)&cmd->pdu[0];
2893         int tx_size = ISCSI_HDR_LEN, ret;
2894
2895         iscsit_build_nopin_rsp(cmd, conn, hdr, false);
2896
2897         if (conn->conn_ops->HeaderDigest) {
2898                 u32 *header_digest = (u32 *)&cmd->pdu[ISCSI_HDR_LEN];
2899
2900                 iscsit_do_crypto_hash_buf(&conn->conn_tx_hash, hdr,
2901                                 ISCSI_HDR_LEN, 0, NULL, (u8 *)header_digest);
2902
2903                 tx_size += ISCSI_CRC_LEN;
2904                 pr_debug("Attaching CRC32C HeaderDigest to"
2905                         " NopIN 0x%08x\n", *header_digest);
2906         }
2907
2908         cmd->iov_misc[0].iov_base       = cmd->pdu;
2909         cmd->iov_misc[0].iov_len        = tx_size;
2910         cmd->iov_misc_count     = 1;
2911         cmd->tx_size            = tx_size;
2912
2913         pr_debug("Sending Unsolicited NOPIN TTT: 0x%08x StatSN:"
2914                 " 0x%08x CID: %hu\n", hdr->ttt, cmd->stat_sn, conn->cid);
2915
2916         ret = iscsit_send_tx_data(cmd, conn, 1);
2917         if (ret < 0) {
2918                 iscsit_tx_thread_wait_for_tcp(conn);
2919                 return ret;
2920         }
2921
2922         spin_lock_bh(&cmd->istate_lock);
2923         cmd->i_state = want_response ?
2924                 ISTATE_SENT_NOPIN_WANT_RESPONSE : ISTATE_SENT_STATUS;
2925         spin_unlock_bh(&cmd->istate_lock);
2926
2927         return 0;
2928 }
2929
2930 static int
2931 iscsit_send_nopin(struct iscsi_cmd *cmd, struct iscsi_conn *conn)
2932 {
2933         struct iscsi_nopin *hdr = (struct iscsi_nopin *)&cmd->pdu[0];
2934         struct kvec *iov;
2935         u32 padding = 0;
2936         int niov = 0, tx_size;
2937
2938         iscsit_build_nopin_rsp(cmd, conn, hdr, true);
2939
2940         tx_size = ISCSI_HDR_LEN;
2941         iov = &cmd->iov_misc[0];
2942         iov[niov].iov_base      = cmd->pdu;
2943         iov[niov++].iov_len     = ISCSI_HDR_LEN;
2944
2945         if (conn->conn_ops->HeaderDigest) {
2946                 u32 *header_digest = (u32 *)&cmd->pdu[ISCSI_HDR_LEN];
2947
2948                 iscsit_do_crypto_hash_buf(&conn->conn_tx_hash, hdr,
2949                                 ISCSI_HDR_LEN, 0, NULL, (u8 *)header_digest);
2950
2951                 iov[0].iov_len += ISCSI_CRC_LEN;
2952                 tx_size += ISCSI_CRC_LEN;
2953                 pr_debug("Attaching CRC32C HeaderDigest"
2954                         " to NopIn 0x%08x\n", *header_digest);
2955         }
2956
2957         /*
2958          * NOPOUT Ping Data is attached to struct iscsi_cmd->buf_ptr.
2959          * NOPOUT DataSegmentLength is at struct iscsi_cmd->buf_ptr_size.
2960          */
2961         if (cmd->buf_ptr_size) {
2962                 iov[niov].iov_base      = cmd->buf_ptr;
2963                 iov[niov++].iov_len     = cmd->buf_ptr_size;
2964                 tx_size += cmd->buf_ptr_size;
2965
2966                 pr_debug("Echoing back %u bytes of ping"
2967                         " data.\n", cmd->buf_ptr_size);
2968
2969                 padding = ((-cmd->buf_ptr_size) & 3);
2970                 if (padding != 0) {
2971                         iov[niov].iov_base = &cmd->pad_bytes;
2972                         iov[niov++].iov_len = padding;
2973                         tx_size += padding;
2974                         pr_debug("Attaching %u additional"
2975                                 " padding bytes.\n", padding);
2976                 }
2977                 if (conn->conn_ops->DataDigest) {
2978                         iscsit_do_crypto_hash_buf(&conn->conn_tx_hash,
2979                                 cmd->buf_ptr, cmd->buf_ptr_size,
2980                                 padding, (u8 *)&cmd->pad_bytes,
2981                                 (u8 *)&cmd->data_crc);
2982
2983                         iov[niov].iov_base = &cmd->data_crc;
2984                         iov[niov++].iov_len = ISCSI_CRC_LEN;
2985                         tx_size += ISCSI_CRC_LEN;
2986                         pr_debug("Attached DataDigest for %u"
2987                                 " bytes of ping data, CRC 0x%08x\n",
2988                                 cmd->buf_ptr_size, cmd->data_crc);
2989                 }
2990         }
2991
2992         cmd->iov_misc_count = niov;
2993         cmd->tx_size = tx_size;
2994
2995         return 0;
2996 }
2997
2998 static int iscsit_send_r2t(
2999         struct iscsi_cmd *cmd,
3000         struct iscsi_conn *conn)
3001 {
3002         int tx_size = 0;
3003         struct iscsi_r2t *r2t;
3004         struct iscsi_r2t_rsp *hdr;
3005         int ret;
3006
3007         r2t = iscsit_get_r2t_from_list(cmd);
3008         if (!r2t)
3009                 return -1;
3010
3011         hdr                     = (struct iscsi_r2t_rsp *) cmd->pdu;
3012         memset(hdr, 0, ISCSI_HDR_LEN);
3013         hdr->opcode             = ISCSI_OP_R2T;
3014         hdr->flags              |= ISCSI_FLAG_CMD_FINAL;
3015         int_to_scsilun(cmd->se_cmd.orig_fe_lun,
3016                         (struct scsi_lun *)&hdr->lun);
3017         hdr->itt                = cmd->init_task_tag;
3018         spin_lock_bh(&conn->sess->ttt_lock);
3019         r2t->targ_xfer_tag      = conn->sess->targ_xfer_tag++;
3020         if (r2t->targ_xfer_tag == 0xFFFFFFFF)
3021                 r2t->targ_xfer_tag = conn->sess->targ_xfer_tag++;
3022         spin_unlock_bh(&conn->sess->ttt_lock);
3023         hdr->ttt                = cpu_to_be32(r2t->targ_xfer_tag);
3024         hdr->statsn             = cpu_to_be32(conn->stat_sn);
3025         hdr->exp_cmdsn          = cpu_to_be32(conn->sess->exp_cmd_sn);
3026         hdr->max_cmdsn          = cpu_to_be32(conn->sess->max_cmd_sn);
3027         hdr->r2tsn              = cpu_to_be32(r2t->r2t_sn);
3028         hdr->data_offset        = cpu_to_be32(r2t->offset);
3029         hdr->data_length        = cpu_to_be32(r2t->xfer_len);
3030
3031         cmd->iov_misc[0].iov_base       = cmd->pdu;
3032         cmd->iov_misc[0].iov_len        = ISCSI_HDR_LEN;
3033         tx_size += ISCSI_HDR_LEN;
3034
3035         if (conn->conn_ops->HeaderDigest) {
3036                 u32 *header_digest = (u32 *)&cmd->pdu[ISCSI_HDR_LEN];
3037
3038                 iscsit_do_crypto_hash_buf(&conn->conn_tx_hash, hdr,
3039                                 ISCSI_HDR_LEN, 0, NULL, (u8 *)header_digest);
3040
3041                 cmd->iov_misc[0].iov_len += ISCSI_CRC_LEN;
3042                 tx_size += ISCSI_CRC_LEN;
3043                 pr_debug("Attaching CRC32 HeaderDigest for R2T"
3044                         " PDU 0x%08x\n", *header_digest);
3045         }
3046
3047         pr_debug("Built %sR2T, ITT: 0x%08x, TTT: 0x%08x, StatSN:"
3048                 " 0x%08x, R2TSN: 0x%08x, Offset: %u, DDTL: %u, CID: %hu\n",
3049                 (!r2t->recovery_r2t) ? "" : "Recovery ", cmd->init_task_tag,
3050                 r2t->targ_xfer_tag, ntohl(hdr->statsn), r2t->r2t_sn,
3051                         r2t->offset, r2t->xfer_len, conn->cid);
3052
3053         cmd->iov_misc_count = 1;
3054         cmd->tx_size = tx_size;
3055
3056         spin_lock_bh(&cmd->r2t_lock);
3057         r2t->sent_r2t = 1;
3058         spin_unlock_bh(&cmd->r2t_lock);
3059
3060         ret = iscsit_send_tx_data(cmd, conn, 1);
3061         if (ret < 0) {
3062                 iscsit_tx_thread_wait_for_tcp(conn);
3063                 return ret;
3064         }
3065
3066         spin_lock_bh(&cmd->dataout_timeout_lock);
3067         iscsit_start_dataout_timer(cmd, conn);
3068         spin_unlock_bh(&cmd->dataout_timeout_lock);
3069
3070         return 0;
3071 }
3072
3073 /*
3074  *      @recovery: If called from iscsi_task_reassign_complete_write() for
3075  *              connection recovery.
3076  */
3077 int iscsit_build_r2ts_for_cmd(
3078         struct iscsi_conn *conn,
3079         struct iscsi_cmd *cmd,
3080         bool recovery)
3081 {
3082         int first_r2t = 1;
3083         u32 offset = 0, xfer_len = 0;
3084
3085         spin_lock_bh(&cmd->r2t_lock);
3086         if (cmd->cmd_flags & ICF_SENT_LAST_R2T) {
3087                 spin_unlock_bh(&cmd->r2t_lock);
3088                 return 0;
3089         }
3090
3091         if (conn->sess->sess_ops->DataSequenceInOrder &&
3092             !recovery)
3093                 cmd->r2t_offset = max(cmd->r2t_offset, cmd->write_data_done);
3094
3095         while (cmd->outstanding_r2ts < conn->sess->sess_ops->MaxOutstandingR2T) {
3096                 if (conn->sess->sess_ops->DataSequenceInOrder) {
3097                         offset = cmd->r2t_offset;
3098
3099                         if (first_r2t && recovery) {
3100                                 int new_data_end = offset +
3101                                         conn->sess->sess_ops->MaxBurstLength -
3102                                         cmd->next_burst_len;
3103
3104                                 if (new_data_end > cmd->se_cmd.data_length)
3105                                         xfer_len = cmd->se_cmd.data_length - offset;
3106                                 else
3107                                         xfer_len =
3108                                                 conn->sess->sess_ops->MaxBurstLength -
3109                                                 cmd->next_burst_len;
3110                         } else {
3111                                 int new_data_end = offset +
3112                                         conn->sess->sess_ops->MaxBurstLength;
3113
3114                                 if (new_data_end > cmd->se_cmd.data_length)
3115                                         xfer_len = cmd->se_cmd.data_length - offset;
3116                                 else
3117                                         xfer_len = conn->sess->sess_ops->MaxBurstLength;
3118                         }
3119                         cmd->r2t_offset += xfer_len;
3120
3121                         if (cmd->r2t_offset == cmd->se_cmd.data_length)
3122                                 cmd->cmd_flags |= ICF_SENT_LAST_R2T;
3123                 } else {
3124                         struct iscsi_seq *seq;
3125
3126                         seq = iscsit_get_seq_holder_for_r2t(cmd);
3127                         if (!seq) {
3128                                 spin_unlock_bh(&cmd->r2t_lock);
3129                                 return -1;
3130                         }
3131
3132                         offset = seq->offset;
3133                         xfer_len = seq->xfer_len;
3134
3135                         if (cmd->seq_send_order == cmd->seq_count)
3136                                 cmd->cmd_flags |= ICF_SENT_LAST_R2T;
3137                 }
3138                 cmd->outstanding_r2ts++;
3139                 first_r2t = 0;
3140
3141                 if (iscsit_add_r2t_to_list(cmd, offset, xfer_len, 0, 0) < 0) {
3142                         spin_unlock_bh(&cmd->r2t_lock);
3143                         return -1;
3144                 }
3145
3146                 if (cmd->cmd_flags & ICF_SENT_LAST_R2T)
3147                         break;
3148         }
3149         spin_unlock_bh(&cmd->r2t_lock);
3150
3151         return 0;
3152 }
3153
3154 void iscsit_build_rsp_pdu(struct iscsi_cmd *cmd, struct iscsi_conn *conn,
3155                         bool inc_stat_sn, struct iscsi_scsi_rsp *hdr)
3156 {
3157         if (inc_stat_sn)
3158                 cmd->stat_sn = conn->stat_sn++;
3159
3160         spin_lock_bh(&conn->sess->session_stats_lock);
3161         conn->sess->rsp_pdus++;
3162         spin_unlock_bh(&conn->sess->session_stats_lock);
3163
3164         memset(hdr, 0, ISCSI_HDR_LEN);
3165         hdr->opcode             = ISCSI_OP_SCSI_CMD_RSP;
3166         hdr->flags              |= ISCSI_FLAG_CMD_FINAL;
3167         if (cmd->se_cmd.se_cmd_flags & SCF_OVERFLOW_BIT) {
3168                 hdr->flags |= ISCSI_FLAG_CMD_OVERFLOW;
3169                 hdr->residual_count = cpu_to_be32(cmd->se_cmd.residual_count);
3170         } else if (cmd->se_cmd.se_cmd_flags & SCF_UNDERFLOW_BIT) {
3171                 hdr->flags |= ISCSI_FLAG_CMD_UNDERFLOW;
3172                 hdr->residual_count = cpu_to_be32(cmd->se_cmd.residual_count);
3173         }
3174         hdr->response           = cmd->iscsi_response;
3175         hdr->cmd_status         = cmd->se_cmd.scsi_status;
3176         hdr->itt                = cmd->init_task_tag;
3177         hdr->statsn             = cpu_to_be32(cmd->stat_sn);
3178
3179         iscsit_increment_maxcmdsn(cmd, conn->sess);
3180         hdr->exp_cmdsn          = cpu_to_be32(conn->sess->exp_cmd_sn);
3181         hdr->max_cmdsn          = cpu_to_be32(conn->sess->max_cmd_sn);
3182
3183         pr_debug("Built SCSI Response, ITT: 0x%08x, StatSN: 0x%08x,"
3184                 " Response: 0x%02x, SAM Status: 0x%02x, CID: %hu\n",
3185                 cmd->init_task_tag, cmd->stat_sn, cmd->se_cmd.scsi_status,
3186                 cmd->se_cmd.scsi_status, conn->cid);
3187 }
3188 EXPORT_SYMBOL(iscsit_build_rsp_pdu);
3189
3190 static int iscsit_send_response(struct iscsi_cmd *cmd, struct iscsi_conn *conn)
3191 {
3192         struct iscsi_scsi_rsp *hdr = (struct iscsi_scsi_rsp *)&cmd->pdu[0];
3193         struct kvec *iov;
3194         u32 padding = 0, tx_size = 0;
3195         int iov_count = 0;
3196         bool inc_stat_sn = (cmd->i_state == ISTATE_SEND_STATUS);
3197
3198         iscsit_build_rsp_pdu(cmd, conn, inc_stat_sn, hdr);
3199
3200         iov = &cmd->iov_misc[0];
3201         iov[iov_count].iov_base = cmd->pdu;
3202         iov[iov_count++].iov_len = ISCSI_HDR_LEN;
3203         tx_size += ISCSI_HDR_LEN;
3204
3205         /*
3206          * Attach SENSE DATA payload to iSCSI Response PDU
3207          */
3208         if (cmd->se_cmd.sense_buffer &&
3209            ((cmd->se_cmd.se_cmd_flags & SCF_TRANSPORT_TASK_SENSE) ||
3210             (cmd->se_cmd.se_cmd_flags & SCF_EMULATED_TASK_SENSE))) {
3211                 put_unaligned_be16(cmd->se_cmd.scsi_sense_length, cmd->sense_buffer);
3212                 cmd->se_cmd.scsi_sense_length += sizeof (__be16);
3213
3214                 padding         = -(cmd->se_cmd.scsi_sense_length) & 3;
3215                 hton24(hdr->dlength, (u32)cmd->se_cmd.scsi_sense_length);
3216                 iov[iov_count].iov_base = cmd->sense_buffer;
3217                 iov[iov_count++].iov_len =
3218                                 (cmd->se_cmd.scsi_sense_length + padding);
3219                 tx_size += cmd->se_cmd.scsi_sense_length;
3220
3221                 if (padding) {
3222                         memset(cmd->sense_buffer +
3223                                 cmd->se_cmd.scsi_sense_length, 0, padding);
3224                         tx_size += padding;
3225                         pr_debug("Adding %u bytes of padding to"
3226                                 " SENSE.\n", padding);
3227                 }
3228
3229                 if (conn->conn_ops->DataDigest) {
3230                         iscsit_do_crypto_hash_buf(&conn->conn_tx_hash,
3231                                 cmd->sense_buffer,
3232                                 (cmd->se_cmd.scsi_sense_length + padding),
3233                                 0, NULL, (u8 *)&cmd->data_crc);
3234
3235                         iov[iov_count].iov_base    = &cmd->data_crc;
3236                         iov[iov_count++].iov_len     = ISCSI_CRC_LEN;
3237                         tx_size += ISCSI_CRC_LEN;
3238
3239                         pr_debug("Attaching CRC32 DataDigest for"
3240                                 " SENSE, %u bytes CRC 0x%08x\n",
3241                                 (cmd->se_cmd.scsi_sense_length + padding),
3242                                 cmd->data_crc);
3243                 }
3244
3245                 pr_debug("Attaching SENSE DATA: %u bytes to iSCSI"
3246                                 " Response PDU\n",
3247                                 cmd->se_cmd.scsi_sense_length);
3248         }
3249
3250         if (conn->conn_ops->HeaderDigest) {
3251                 u32 *header_digest = (u32 *)&cmd->pdu[ISCSI_HDR_LEN];
3252
3253                 iscsit_do_crypto_hash_buf(&conn->conn_tx_hash, cmd->pdu,
3254                                 ISCSI_HDR_LEN, 0, NULL, (u8 *)header_digest);
3255
3256                 iov[0].iov_len += ISCSI_CRC_LEN;
3257                 tx_size += ISCSI_CRC_LEN;
3258                 pr_debug("Attaching CRC32 HeaderDigest for Response"
3259                                 " PDU 0x%08x\n", *header_digest);
3260         }
3261
3262         cmd->iov_misc_count = iov_count;
3263         cmd->tx_size = tx_size;
3264
3265         return 0;
3266 }
3267
3268 static u8 iscsit_convert_tcm_tmr_rsp(struct se_tmr_req *se_tmr)
3269 {
3270         switch (se_tmr->response) {
3271         case TMR_FUNCTION_COMPLETE:
3272                 return ISCSI_TMF_RSP_COMPLETE;
3273         case TMR_TASK_DOES_NOT_EXIST:
3274                 return ISCSI_TMF_RSP_NO_TASK;
3275         case TMR_LUN_DOES_NOT_EXIST:
3276                 return ISCSI_TMF_RSP_NO_LUN;
3277         case TMR_TASK_MGMT_FUNCTION_NOT_SUPPORTED:
3278                 return ISCSI_TMF_RSP_NOT_SUPPORTED;
3279         case TMR_FUNCTION_REJECTED:
3280         default:
3281                 return ISCSI_TMF_RSP_REJECTED;
3282         }
3283 }
3284
3285 void
3286 iscsit_build_task_mgt_rsp(struct iscsi_cmd *cmd, struct iscsi_conn *conn,
3287                           struct iscsi_tm_rsp *hdr)
3288 {
3289         struct se_tmr_req *se_tmr = cmd->se_cmd.se_tmr_req;
3290
3291         hdr->opcode             = ISCSI_OP_SCSI_TMFUNC_RSP;
3292         hdr->flags              = ISCSI_FLAG_CMD_FINAL;
3293         hdr->response           = iscsit_convert_tcm_tmr_rsp(se_tmr);
3294         hdr->itt                = cmd->init_task_tag;
3295         cmd->stat_sn            = conn->stat_sn++;
3296         hdr->statsn             = cpu_to_be32(cmd->stat_sn);
3297
3298         iscsit_increment_maxcmdsn(cmd, conn->sess);
3299         hdr->exp_cmdsn          = cpu_to_be32(conn->sess->exp_cmd_sn);
3300         hdr->max_cmdsn          = cpu_to_be32(conn->sess->max_cmd_sn);
3301
3302         pr_debug("Built Task Management Response ITT: 0x%08x,"
3303                 " StatSN: 0x%08x, Response: 0x%02x, CID: %hu\n",
3304                 cmd->init_task_tag, cmd->stat_sn, hdr->response, conn->cid);
3305 }
3306 EXPORT_SYMBOL(iscsit_build_task_mgt_rsp);
3307
3308 static int
3309 iscsit_send_task_mgt_rsp(struct iscsi_cmd *cmd, struct iscsi_conn *conn)
3310 {
3311         struct iscsi_tm_rsp *hdr = (struct iscsi_tm_rsp *)&cmd->pdu[0];
3312         u32 tx_size = 0;
3313
3314         iscsit_build_task_mgt_rsp(cmd, conn, hdr);
3315
3316         cmd->iov_misc[0].iov_base       = cmd->pdu;
3317         cmd->iov_misc[0].iov_len        = ISCSI_HDR_LEN;
3318         tx_size += ISCSI_HDR_LEN;
3319
3320         if (conn->conn_ops->HeaderDigest) {
3321                 u32 *header_digest = (u32 *)&cmd->pdu[ISCSI_HDR_LEN];
3322
3323                 iscsit_do_crypto_hash_buf(&conn->conn_tx_hash, hdr,
3324                                 ISCSI_HDR_LEN, 0, NULL, (u8 *)header_digest);
3325
3326                 cmd->iov_misc[0].iov_len += ISCSI_CRC_LEN;
3327                 tx_size += ISCSI_CRC_LEN;
3328                 pr_debug("Attaching CRC32 HeaderDigest for Task"
3329                         " Mgmt Response PDU 0x%08x\n", *header_digest);
3330         }
3331
3332         cmd->iov_misc_count = 1;
3333         cmd->tx_size = tx_size;
3334
3335         return 0;
3336 }
3337
3338 static bool iscsit_check_inaddr_any(struct iscsi_np *np)
3339 {
3340         bool ret = false;
3341
3342         if (np->np_sockaddr.ss_family == AF_INET6) {
3343                 const struct sockaddr_in6 sin6 = {
3344                         .sin6_addr = IN6ADDR_ANY_INIT };
3345                 struct sockaddr_in6 *sock_in6 =
3346                          (struct sockaddr_in6 *)&np->np_sockaddr;
3347
3348                 if (!memcmp(sock_in6->sin6_addr.s6_addr,
3349                                 sin6.sin6_addr.s6_addr, 16))
3350                         ret = true;
3351         } else {
3352                 struct sockaddr_in * sock_in =
3353                         (struct sockaddr_in *)&np->np_sockaddr;
3354
3355                 if (sock_in->sin_addr.s_addr == htonl(INADDR_ANY))
3356                         ret = true;
3357         }
3358
3359         return ret;
3360 }
3361
3362 #define SENDTARGETS_BUF_LIMIT 32768U
3363
3364 static int iscsit_build_sendtargets_response(struct iscsi_cmd *cmd)
3365 {
3366         char *payload = NULL;
3367         struct iscsi_conn *conn = cmd->conn;
3368         struct iscsi_portal_group *tpg;
3369         struct iscsi_tiqn *tiqn;
3370         struct iscsi_tpg_np *tpg_np;
3371         int buffer_len, end_of_buf = 0, len = 0, payload_len = 0;
3372         unsigned char buf[ISCSI_IQN_LEN+12]; /* iqn + "TargetName=" + \0 */
3373         unsigned char *text_in = cmd->text_in_ptr, *text_ptr = NULL;
3374
3375         buffer_len = max(conn->conn_ops->MaxRecvDataSegmentLength,
3376                          SENDTARGETS_BUF_LIMIT);
3377
3378         payload = kzalloc(buffer_len, GFP_KERNEL);
3379         if (!payload) {
3380                 pr_err("Unable to allocate memory for sendtargets"
3381                                 " response.\n");
3382                 return -ENOMEM;
3383         }
3384         /*
3385          * Locate pointer to iqn./eui. string for IFC_SENDTARGETS_SINGLE
3386          * explicit case..
3387          */
3388         if (cmd->cmd_flags & IFC_SENDTARGETS_SINGLE) {
3389                 text_ptr = strchr(text_in, '=');
3390                 if (!text_ptr) {
3391                         pr_err("Unable to locate '=' string in text_in:"
3392                                " %s\n", text_in);
3393                         kfree(payload);
3394                         return -EINVAL;
3395                 }
3396                 /*
3397                  * Skip over '=' character..
3398                  */
3399                 text_ptr += 1;
3400         }
3401
3402         spin_lock(&tiqn_lock);
3403         list_for_each_entry(tiqn, &g_tiqn_list, tiqn_list) {
3404                 if ((cmd->cmd_flags & IFC_SENDTARGETS_SINGLE) &&
3405                      strcmp(tiqn->tiqn, text_ptr)) {
3406                         continue;
3407                 }
3408
3409                 len = sprintf(buf, "TargetName=%s", tiqn->tiqn);
3410                 len += 1;
3411
3412                 if ((len + payload_len) > buffer_len) {
3413                         end_of_buf = 1;
3414                         goto eob;
3415                 }
3416                 memcpy(payload + payload_len, buf, len);
3417                 payload_len += len;
3418
3419                 spin_lock(&tiqn->tiqn_tpg_lock);
3420                 list_for_each_entry(tpg, &tiqn->tiqn_tpg_list, tpg_list) {
3421
3422                         spin_lock(&tpg->tpg_state_lock);
3423                         if ((tpg->tpg_state == TPG_STATE_FREE) ||
3424                             (tpg->tpg_state == TPG_STATE_INACTIVE)) {
3425                                 spin_unlock(&tpg->tpg_state_lock);
3426                                 continue;
3427                         }
3428                         spin_unlock(&tpg->tpg_state_lock);
3429
3430                         spin_lock(&tpg->tpg_np_lock);
3431                         list_for_each_entry(tpg_np, &tpg->tpg_gnp_list,
3432                                                 tpg_np_list) {
3433                                 struct iscsi_np *np = tpg_np->tpg_np;
3434                                 bool inaddr_any = iscsit_check_inaddr_any(np);
3435
3436                                 len = sprintf(buf, "TargetAddress="
3437                                         "%s:%hu,%hu",
3438                                         (inaddr_any == false) ?
3439                                                 np->np_ip : conn->local_ip,
3440                                         (inaddr_any == false) ?
3441                                                 np->np_port : conn->local_port,
3442                                         tpg->tpgt);
3443                                 len += 1;
3444
3445                                 if ((len + payload_len) > buffer_len) {
3446                                         spin_unlock(&tpg->tpg_np_lock);
3447                                         spin_unlock(&tiqn->tiqn_tpg_lock);
3448                                         end_of_buf = 1;
3449                                         goto eob;
3450                                 }
3451                                 memcpy(payload + payload_len, buf, len);
3452                                 payload_len += len;
3453                         }
3454                         spin_unlock(&tpg->tpg_np_lock);
3455                 }
3456                 spin_unlock(&tiqn->tiqn_tpg_lock);
3457 eob:
3458                 if (end_of_buf)
3459                         break;
3460
3461                 if (cmd->cmd_flags & IFC_SENDTARGETS_SINGLE)
3462                         break;
3463         }
3464         spin_unlock(&tiqn_lock);
3465
3466         cmd->buf_ptr = payload;
3467
3468         return payload_len;
3469 }
3470
3471 int
3472 iscsit_build_text_rsp(struct iscsi_cmd *cmd, struct iscsi_conn *conn,
3473                       struct iscsi_text_rsp *hdr)
3474 {
3475         int text_length, padding;
3476
3477         text_length = iscsit_build_sendtargets_response(cmd);
3478         if (text_length < 0)
3479                 return text_length;
3480
3481         hdr->opcode = ISCSI_OP_TEXT_RSP;
3482         hdr->flags |= ISCSI_FLAG_CMD_FINAL;
3483         padding = ((-text_length) & 3);
3484         hton24(hdr->dlength, text_length);
3485         hdr->itt = cmd->init_task_tag;
3486         hdr->ttt = cpu_to_be32(cmd->targ_xfer_tag);
3487         cmd->stat_sn = conn->stat_sn++;
3488         hdr->statsn = cpu_to_be32(cmd->stat_sn);
3489
3490         iscsit_increment_maxcmdsn(cmd, conn->sess);
3491         hdr->exp_cmdsn = cpu_to_be32(conn->sess->exp_cmd_sn);
3492         hdr->max_cmdsn = cpu_to_be32(conn->sess->max_cmd_sn);
3493
3494         pr_debug("Built Text Response: ITT: 0x%08x, StatSN: 0x%08x,"
3495                 " Length: %u, CID: %hu\n", cmd->init_task_tag, cmd->stat_sn,
3496                 text_length, conn->cid);
3497
3498         return text_length + padding;
3499 }
3500 EXPORT_SYMBOL(iscsit_build_text_rsp);
3501
3502 /*
3503  *      FIXME: Add support for F_BIT and C_BIT when the length is longer than
3504  *      MaxRecvDataSegmentLength.
3505  */
3506 static int iscsit_send_text_rsp(
3507         struct iscsi_cmd *cmd,
3508         struct iscsi_conn *conn)
3509 {
3510         struct iscsi_text_rsp *hdr = (struct iscsi_text_rsp *)cmd->pdu;
3511         struct kvec *iov;
3512         u32 tx_size = 0;
3513         int text_length, iov_count = 0, rc;
3514
3515         rc = iscsit_build_text_rsp(cmd, conn, hdr);
3516         if (rc < 0)
3517                 return rc;
3518
3519         text_length = rc;
3520         iov = &cmd->iov_misc[0];
3521         iov[iov_count].iov_base = cmd->pdu;
3522         iov[iov_count++].iov_len = ISCSI_HDR_LEN;
3523         iov[iov_count].iov_base = cmd->buf_ptr;
3524         iov[iov_count++].iov_len = text_length;
3525
3526         tx_size += (ISCSI_HDR_LEN + text_length);
3527
3528         if (conn->conn_ops->HeaderDigest) {
3529                 u32 *header_digest = (u32 *)&cmd->pdu[ISCSI_HDR_LEN];
3530
3531                 iscsit_do_crypto_hash_buf(&conn->conn_tx_hash, hdr,
3532                                 ISCSI_HDR_LEN, 0, NULL, (u8 *)header_digest);
3533
3534                 iov[0].iov_len += ISCSI_CRC_LEN;
3535                 tx_size += ISCSI_CRC_LEN;
3536                 pr_debug("Attaching CRC32 HeaderDigest for"
3537                         " Text Response PDU 0x%08x\n", *header_digest);
3538         }
3539
3540         if (conn->conn_ops->DataDigest) {
3541                 iscsit_do_crypto_hash_buf(&conn->conn_tx_hash,
3542                                 cmd->buf_ptr, text_length,
3543                                 0, NULL, (u8 *)&cmd->data_crc);
3544
3545                 iov[iov_count].iov_base = &cmd->data_crc;
3546                 iov[iov_count++].iov_len = ISCSI_CRC_LEN;
3547                 tx_size += ISCSI_CRC_LEN;
3548
3549                 pr_debug("Attaching DataDigest for %u bytes of text"
3550                         " data, CRC 0x%08x\n", text_length,
3551                         cmd->data_crc);
3552         }
3553
3554         cmd->iov_misc_count = iov_count;
3555         cmd->tx_size = tx_size;
3556
3557         return 0;
3558 }
3559
3560 void
3561 iscsit_build_reject(struct iscsi_cmd *cmd, struct iscsi_conn *conn,
3562                     struct iscsi_reject *hdr)
3563 {
3564         hdr->opcode             = ISCSI_OP_REJECT;
3565         hdr->reason             = cmd->reject_reason;
3566         hdr->flags              |= ISCSI_FLAG_CMD_FINAL;
3567         hton24(hdr->dlength, ISCSI_HDR_LEN);
3568         hdr->ffffffff           = cpu_to_be32(0xffffffff);
3569         cmd->stat_sn            = conn->stat_sn++;
3570         hdr->statsn             = cpu_to_be32(cmd->stat_sn);
3571         hdr->exp_cmdsn          = cpu_to_be32(conn->sess->exp_cmd_sn);
3572         hdr->max_cmdsn          = cpu_to_be32(conn->sess->max_cmd_sn);
3573
3574 }
3575 EXPORT_SYMBOL(iscsit_build_reject);
3576
3577 static int iscsit_send_reject(
3578         struct iscsi_cmd *cmd,
3579         struct iscsi_conn *conn)
3580 {
3581         struct iscsi_reject *hdr = (struct iscsi_reject *)&cmd->pdu[0];
3582         struct kvec *iov;
3583         u32 iov_count = 0, tx_size;
3584
3585         iscsit_build_reject(cmd, conn, hdr);
3586
3587         iov = &cmd->iov_misc[0];
3588         iov[iov_count].iov_base = cmd->pdu;
3589         iov[iov_count++].iov_len = ISCSI_HDR_LEN;
3590         iov[iov_count].iov_base = cmd->buf_ptr;
3591         iov[iov_count++].iov_len = ISCSI_HDR_LEN;
3592
3593         tx_size = (ISCSI_HDR_LEN + ISCSI_HDR_LEN);
3594
3595         if (conn->conn_ops->HeaderDigest) {
3596                 u32 *header_digest = (u32 *)&cmd->pdu[ISCSI_HDR_LEN];
3597
3598                 iscsit_do_crypto_hash_buf(&conn->conn_tx_hash, hdr,
3599                                 ISCSI_HDR_LEN, 0, NULL, (u8 *)header_digest);
3600
3601                 iov[0].iov_len += ISCSI_CRC_LEN;
3602                 tx_size += ISCSI_CRC_LEN;
3603                 pr_debug("Attaching CRC32 HeaderDigest for"
3604                         " REJECT PDU 0x%08x\n", *header_digest);
3605         }
3606
3607         if (conn->conn_ops->DataDigest) {
3608                 iscsit_do_crypto_hash_buf(&conn->conn_tx_hash, cmd->buf_ptr,
3609                                 ISCSI_HDR_LEN, 0, NULL, (u8 *)&cmd->data_crc);
3610
3611                 iov[iov_count].iov_base = &cmd->data_crc;
3612                 iov[iov_count++].iov_len  = ISCSI_CRC_LEN;
3613                 tx_size += ISCSI_CRC_LEN;
3614                 pr_debug("Attaching CRC32 DataDigest for REJECT"
3615                                 " PDU 0x%08x\n", cmd->data_crc);
3616         }
3617
3618         cmd->iov_misc_count = iov_count;
3619         cmd->tx_size = tx_size;
3620
3621         pr_debug("Built Reject PDU StatSN: 0x%08x, Reason: 0x%02x,"
3622                 " CID: %hu\n", ntohl(hdr->statsn), hdr->reason, conn->cid);
3623
3624         return 0;
3625 }
3626
3627 void iscsit_thread_get_cpumask(struct iscsi_conn *conn)
3628 {
3629         struct iscsi_thread_set *ts = conn->thread_set;
3630         int ord, cpu;
3631         /*
3632          * thread_id is assigned from iscsit_global->ts_bitmap from
3633          * within iscsi_thread_set.c:iscsi_allocate_thread_sets()
3634          *
3635          * Here we use thread_id to determine which CPU that this
3636          * iSCSI connection's iscsi_thread_set will be scheduled to
3637          * execute upon.
3638          */
3639         ord = ts->thread_id % cpumask_weight(cpu_online_mask);
3640         for_each_online_cpu(cpu) {
3641                 if (ord-- == 0) {
3642                         cpumask_set_cpu(cpu, conn->conn_cpumask);
3643                         return;
3644                 }
3645         }
3646         /*
3647          * This should never be reached..
3648          */
3649         dump_stack();
3650         cpumask_setall(conn->conn_cpumask);
3651 }
3652
3653 static inline void iscsit_thread_check_cpumask(
3654         struct iscsi_conn *conn,
3655         struct task_struct *p,
3656         int mode)
3657 {
3658         char buf[128];
3659         /*
3660          * mode == 1 signals iscsi_target_tx_thread() usage.
3661          * mode == 0 signals iscsi_target_rx_thread() usage.
3662          */
3663         if (mode == 1) {
3664                 if (!conn->conn_tx_reset_cpumask)
3665                         return;
3666                 conn->conn_tx_reset_cpumask = 0;
3667         } else {
3668                 if (!conn->conn_rx_reset_cpumask)
3669                         return;
3670                 conn->conn_rx_reset_cpumask = 0;
3671         }
3672         /*
3673          * Update the CPU mask for this single kthread so that
3674          * both TX and RX kthreads are scheduled to run on the
3675          * same CPU.
3676          */
3677         memset(buf, 0, 128);
3678         cpumask_scnprintf(buf, 128, conn->conn_cpumask);
3679         set_cpus_allowed_ptr(p, conn->conn_cpumask);
3680 }
3681
3682 static int
3683 iscsit_immediate_queue(struct iscsi_conn *conn, struct iscsi_cmd *cmd, int state)
3684 {
3685         int ret;
3686
3687         switch (state) {
3688         case ISTATE_SEND_R2T:
3689                 ret = iscsit_send_r2t(cmd, conn);
3690                 if (ret < 0)
3691                         goto err;
3692                 break;
3693         case ISTATE_REMOVE:
3694                 spin_lock_bh(&conn->cmd_lock);
3695                 list_del(&cmd->i_conn_node);
3696                 spin_unlock_bh(&conn->cmd_lock);
3697
3698                 iscsit_free_cmd(cmd, false);
3699                 break;
3700         case ISTATE_SEND_NOPIN_WANT_RESPONSE:
3701                 iscsit_mod_nopin_response_timer(conn);
3702                 ret = iscsit_send_unsolicited_nopin(cmd, conn, 1);
3703                 if (ret < 0)
3704                         goto err;
3705                 break;
3706         case ISTATE_SEND_NOPIN_NO_RESPONSE:
3707                 ret = iscsit_send_unsolicited_nopin(cmd, conn, 0);
3708                 if (ret < 0)
3709                         goto err;
3710                 break;
3711         default:
3712                 pr_err("Unknown Opcode: 0x%02x ITT:"
3713                        " 0x%08x, i_state: %d on CID: %hu\n",
3714                        cmd->iscsi_opcode, cmd->init_task_tag, state,
3715                        conn->cid);
3716                 goto err;
3717         }
3718
3719         return 0;
3720
3721 err:
3722         return -1;
3723 }
3724
3725 static int
3726 iscsit_handle_immediate_queue(struct iscsi_conn *conn)
3727 {
3728         struct iscsit_transport *t = conn->conn_transport;
3729         struct iscsi_queue_req *qr;
3730         struct iscsi_cmd *cmd;
3731         u8 state;
3732         int ret;
3733
3734         while ((qr = iscsit_get_cmd_from_immediate_queue(conn))) {
3735                 atomic_set(&conn->check_immediate_queue, 0);
3736                 cmd = qr->cmd;
3737                 state = qr->state;
3738                 kmem_cache_free(lio_qr_cache, qr);
3739
3740                 ret = t->iscsit_immediate_queue(conn, cmd, state);
3741                 if (ret < 0)
3742                         return ret;
3743         }
3744
3745         return 0;
3746 }
3747
3748 static int
3749 iscsit_response_queue(struct iscsi_conn *conn, struct iscsi_cmd *cmd, int state)
3750 {
3751         int ret;
3752
3753 check_rsp_state:
3754         switch (state) {
3755         case ISTATE_SEND_DATAIN:
3756                 ret = iscsit_send_datain(cmd, conn);
3757                 if (ret < 0)
3758                         goto err;
3759                 else if (!ret)
3760                         /* more drs */
3761                         goto check_rsp_state;
3762                 else if (ret == 1) {
3763                         /* all done */
3764                         spin_lock_bh(&cmd->istate_lock);
3765                         cmd->i_state = ISTATE_SENT_STATUS;
3766                         spin_unlock_bh(&cmd->istate_lock);
3767
3768                         if (atomic_read(&conn->check_immediate_queue))
3769                                 return 1;
3770
3771                         return 0;
3772                 } else if (ret == 2) {
3773                         /* Still must send status,
3774                            SCF_TRANSPORT_TASK_SENSE was set */
3775                         spin_lock_bh(&cmd->istate_lock);
3776                         cmd->i_state = ISTATE_SEND_STATUS;
3777                         spin_unlock_bh(&cmd->istate_lock);
3778                         state = ISTATE_SEND_STATUS;
3779                         goto check_rsp_state;
3780                 }
3781
3782                 break;
3783         case ISTATE_SEND_STATUS:
3784         case ISTATE_SEND_STATUS_RECOVERY:
3785                 ret = iscsit_send_response(cmd, conn);
3786                 break;
3787         case ISTATE_SEND_LOGOUTRSP:
3788                 ret = iscsit_send_logout(cmd, conn);
3789                 break;
3790         case ISTATE_SEND_ASYNCMSG:
3791                 ret = iscsit_send_conn_drop_async_message(
3792                         cmd, conn);
3793                 break;
3794         case ISTATE_SEND_NOPIN:
3795                 ret = iscsit_send_nopin(cmd, conn);
3796                 break;
3797         case ISTATE_SEND_REJECT:
3798                 ret = iscsit_send_reject(cmd, conn);
3799                 break;
3800         case ISTATE_SEND_TASKMGTRSP:
3801                 ret = iscsit_send_task_mgt_rsp(cmd, conn);
3802                 if (ret != 0)
3803                         break;
3804                 ret = iscsit_tmr_post_handler(cmd, conn);
3805                 if (ret != 0)
3806                         iscsit_fall_back_to_erl0(conn->sess);
3807                 break;
3808         case ISTATE_SEND_TEXTRSP:
3809                 ret = iscsit_send_text_rsp(cmd, conn);
3810                 break;
3811         default:
3812                 pr_err("Unknown Opcode: 0x%02x ITT:"
3813                        " 0x%08x, i_state: %d on CID: %hu\n",
3814                        cmd->iscsi_opcode, cmd->init_task_tag,
3815                        state, conn->cid);
3816                 goto err;
3817         }
3818         if (ret < 0)
3819                 goto err;
3820
3821         if (iscsit_send_tx_data(cmd, conn, 1) < 0) {
3822                 iscsit_tx_thread_wait_for_tcp(conn);
3823                 iscsit_unmap_iovec(cmd);
3824                 goto err;
3825         }
3826         iscsit_unmap_iovec(cmd);
3827
3828         switch (state) {
3829         case ISTATE_SEND_LOGOUTRSP:
3830                 if (!iscsit_logout_post_handler(cmd, conn))
3831                         goto restart;
3832                 /* fall through */
3833         case ISTATE_SEND_STATUS:
3834         case ISTATE_SEND_ASYNCMSG:
3835         case ISTATE_SEND_NOPIN:
3836         case ISTATE_SEND_STATUS_RECOVERY:
3837         case ISTATE_SEND_TEXTRSP:
3838         case ISTATE_SEND_TASKMGTRSP:
3839         case ISTATE_SEND_REJECT:
3840                 spin_lock_bh(&cmd->istate_lock);
3841                 cmd->i_state = ISTATE_SENT_STATUS;
3842                 spin_unlock_bh(&cmd->istate_lock);
3843                 break;
3844         default:
3845                 pr_err("Unknown Opcode: 0x%02x ITT:"
3846                        " 0x%08x, i_state: %d on CID: %hu\n",
3847                        cmd->iscsi_opcode, cmd->init_task_tag,
3848                        cmd->i_state, conn->cid);
3849                 goto err;
3850         }
3851
3852         if (atomic_read(&conn->check_immediate_queue))
3853                 return 1;
3854
3855         return 0;
3856
3857 err:
3858         return -1;
3859 restart:
3860         return -EAGAIN;
3861 }
3862
3863 static int iscsit_handle_response_queue(struct iscsi_conn *conn)
3864 {
3865         struct iscsit_transport *t = conn->conn_transport;
3866         struct iscsi_queue_req *qr;
3867         struct iscsi_cmd *cmd;
3868         u8 state;
3869         int ret;
3870
3871         while ((qr = iscsit_get_cmd_from_response_queue(conn))) {
3872                 cmd = qr->cmd;
3873                 state = qr->state;
3874                 kmem_cache_free(lio_qr_cache, qr);
3875
3876                 ret = t->iscsit_response_queue(conn, cmd, state);
3877                 if (ret == 1 || ret < 0)
3878                         return ret;
3879         }
3880
3881         return 0;
3882 }
3883
3884 int iscsi_target_tx_thread(void *arg)
3885 {
3886         int ret = 0;
3887         struct iscsi_conn *conn;
3888         struct iscsi_thread_set *ts = arg;
3889         /*
3890          * Allow ourselves to be interrupted by SIGINT so that a
3891          * connection recovery / failure event can be triggered externally.
3892          */
3893         allow_signal(SIGINT);
3894
3895 restart:
3896         conn = iscsi_tx_thread_pre_handler(ts);
3897         if (!conn)
3898                 goto out;
3899
3900         ret = 0;
3901
3902         while (!kthread_should_stop()) {
3903                 /*
3904                  * Ensure that both TX and RX per connection kthreads
3905                  * are scheduled to run on the same CPU.
3906                  */
3907                 iscsit_thread_check_cpumask(conn, current, 1);
3908
3909                 wait_event_interruptible(conn->queues_wq,
3910                                          !iscsit_conn_all_queues_empty(conn) ||
3911                                          ts->status == ISCSI_THREAD_SET_RESET);
3912
3913                 if ((ts->status == ISCSI_THREAD_SET_RESET) ||
3914                      signal_pending(current))
3915                         goto transport_err;
3916
3917 get_immediate:
3918                 ret = iscsit_handle_immediate_queue(conn);
3919                 if (ret < 0)
3920                         goto transport_err;
3921
3922                 ret = iscsit_handle_response_queue(conn);
3923                 if (ret == 1)
3924                         goto get_immediate;
3925                 else if (ret == -EAGAIN)
3926                         goto restart;
3927                 else if (ret < 0)
3928                         goto transport_err;
3929         }
3930
3931 transport_err:
3932         iscsit_take_action_for_connection_exit(conn);
3933         goto restart;
3934 out:
3935         return 0;
3936 }
3937
3938 static int iscsi_target_rx_opcode(struct iscsi_conn *conn, unsigned char *buf)
3939 {
3940         struct iscsi_hdr *hdr = (struct iscsi_hdr *)buf;
3941         struct iscsi_cmd *cmd;
3942         int ret = 0;
3943
3944         switch (hdr->opcode & ISCSI_OPCODE_MASK) {
3945         case ISCSI_OP_SCSI_CMD:
3946                 cmd = iscsit_allocate_cmd(conn, GFP_KERNEL);
3947                 if (!cmd)
3948                         goto reject;
3949
3950                 ret = iscsit_handle_scsi_cmd(conn, cmd, buf);
3951                 break;
3952         case ISCSI_OP_SCSI_DATA_OUT:
3953                 ret = iscsit_handle_data_out(conn, buf);
3954                 break;
3955         case ISCSI_OP_NOOP_OUT:
3956                 cmd = NULL;
3957                 if (hdr->ttt == cpu_to_be32(0xFFFFFFFF)) {
3958                         cmd = iscsit_allocate_cmd(conn, GFP_KERNEL);
3959                         if (!cmd)
3960                                 goto reject;
3961                 }
3962                 ret = iscsit_handle_nop_out(conn, cmd, buf);
3963                 break;
3964         case ISCSI_OP_SCSI_TMFUNC:
3965                 cmd = iscsit_allocate_cmd(conn, GFP_KERNEL);
3966                 if (!cmd)
3967                         goto reject;
3968
3969                 ret = iscsit_handle_task_mgt_cmd(conn, cmd, buf);
3970                 break;
3971         case ISCSI_OP_TEXT:
3972                 cmd = iscsit_allocate_cmd(conn, GFP_KERNEL);
3973                 if (!cmd)
3974                         goto reject;
3975
3976                 ret = iscsit_handle_text_cmd(conn, cmd, buf);
3977                 break;
3978         case ISCSI_OP_LOGOUT:
3979                 cmd = iscsit_allocate_cmd(conn, GFP_KERNEL);
3980                 if (!cmd)
3981                         goto reject;
3982
3983                 ret = iscsit_handle_logout_cmd(conn, cmd, buf);
3984                 if (ret > 0)
3985                         wait_for_completion_timeout(&conn->conn_logout_comp,
3986                                         SECONDS_FOR_LOGOUT_COMP * HZ);
3987                 break;
3988         case ISCSI_OP_SNACK:
3989                 ret = iscsit_handle_snack(conn, buf);
3990                 break;
3991         default:
3992                 pr_err("Got unknown iSCSI OpCode: 0x%02x\n", hdr->opcode);
3993                 if (!conn->sess->sess_ops->ErrorRecoveryLevel) {
3994                         pr_err("Cannot recover from unknown"
3995                         " opcode while ERL=0, closing iSCSI connection.\n");
3996                         return -1;
3997                 }
3998                 if (!conn->conn_ops->OFMarker) {
3999                         pr_err("Unable to recover from unknown"
4000                         " opcode while OFMarker=No, closing iSCSI"
4001                                 " connection.\n");
4002                         return -1;
4003                 }
4004                 if (iscsit_recover_from_unknown_opcode(conn) < 0) {
4005                         pr_err("Unable to recover from unknown"
4006                                 " opcode, closing iSCSI connection.\n");
4007                         return -1;
4008                 }
4009                 break;
4010         }
4011
4012         return ret;
4013 reject:
4014         return iscsit_add_reject(conn, ISCSI_REASON_BOOKMARK_NO_RESOURCES, buf);
4015 }
4016
4017 int iscsi_target_rx_thread(void *arg)
4018 {
4019         int ret;
4020         u8 buffer[ISCSI_HDR_LEN], opcode;
4021         u32 checksum = 0, digest = 0;
4022         struct iscsi_conn *conn = NULL;
4023         struct iscsi_thread_set *ts = arg;
4024         struct kvec iov;
4025         /*
4026          * Allow ourselves to be interrupted by SIGINT so that a
4027          * connection recovery / failure event can be triggered externally.
4028          */
4029         allow_signal(SIGINT);
4030
4031 restart:
4032         conn = iscsi_rx_thread_pre_handler(ts);
4033         if (!conn)
4034                 goto out;
4035
4036         if (conn->conn_transport->transport_type == ISCSI_INFINIBAND) {
4037                 struct completion comp;
4038                 int rc;
4039
4040                 init_completion(&comp);
4041                 rc = wait_for_completion_interruptible(&comp);
4042                 if (rc < 0)
4043                         goto transport_err;
4044
4045                 goto out;
4046         }
4047
4048         while (!kthread_should_stop()) {
4049                 /*
4050                  * Ensure that both TX and RX per connection kthreads
4051                  * are scheduled to run on the same CPU.
4052                  */
4053                 iscsit_thread_check_cpumask(conn, current, 0);
4054
4055                 memset(buffer, 0, ISCSI_HDR_LEN);
4056                 memset(&iov, 0, sizeof(struct kvec));
4057
4058                 iov.iov_base    = buffer;
4059                 iov.iov_len     = ISCSI_HDR_LEN;
4060
4061                 ret = rx_data(conn, &iov, 1, ISCSI_HDR_LEN);
4062                 if (ret != ISCSI_HDR_LEN) {
4063                         iscsit_rx_thread_wait_for_tcp(conn);
4064                         goto transport_err;
4065                 }
4066
4067                 if (conn->conn_ops->HeaderDigest) {
4068                         iov.iov_base    = &digest;
4069                         iov.iov_len     = ISCSI_CRC_LEN;
4070
4071                         ret = rx_data(conn, &iov, 1, ISCSI_CRC_LEN);
4072                         if (ret != ISCSI_CRC_LEN) {
4073                                 iscsit_rx_thread_wait_for_tcp(conn);
4074                                 goto transport_err;
4075                         }
4076
4077                         iscsit_do_crypto_hash_buf(&conn->conn_rx_hash,
4078                                         buffer, ISCSI_HDR_LEN,
4079                                         0, NULL, (u8 *)&checksum);
4080
4081                         if (digest != checksum) {
4082                                 pr_err("HeaderDigest CRC32C failed,"
4083                                         " received 0x%08x, computed 0x%08x\n",
4084                                         digest, checksum);
4085                                 /*
4086                                  * Set the PDU to 0xff so it will intentionally
4087                                  * hit default in the switch below.
4088                                  */
4089                                 memset(buffer, 0xff, ISCSI_HDR_LEN);
4090                                 spin_lock_bh(&conn->sess->session_stats_lock);
4091                                 conn->sess->conn_digest_errors++;
4092                                 spin_unlock_bh(&conn->sess->session_stats_lock);
4093                         } else {
4094                                 pr_debug("Got HeaderDigest CRC32C"
4095                                                 " 0x%08x\n", checksum);
4096                         }
4097                 }
4098
4099                 if (conn->conn_state == TARG_CONN_STATE_IN_LOGOUT)
4100                         goto transport_err;
4101
4102                 opcode = buffer[0] & ISCSI_OPCODE_MASK;
4103
4104                 if (conn->sess->sess_ops->SessionType &&
4105                    ((!(opcode & ISCSI_OP_TEXT)) ||
4106                     (!(opcode & ISCSI_OP_LOGOUT)))) {
4107                         pr_err("Received illegal iSCSI Opcode: 0x%02x"
4108                         " while in Discovery Session, rejecting.\n", opcode);
4109                         iscsit_add_reject(conn, ISCSI_REASON_PROTOCOL_ERROR,
4110                                           buffer);
4111                         goto transport_err;
4112                 }
4113
4114                 ret = iscsi_target_rx_opcode(conn, buffer);
4115                 if (ret < 0)
4116                         goto transport_err;
4117         }
4118
4119 transport_err:
4120         if (!signal_pending(current))
4121                 atomic_set(&conn->transport_failed, 1);
4122         iscsit_take_action_for_connection_exit(conn);
4123         goto restart;
4124 out:
4125         return 0;
4126 }
4127
4128 static void iscsit_release_commands_from_conn(struct iscsi_conn *conn)
4129 {
4130         struct iscsi_cmd *cmd = NULL, *cmd_tmp = NULL;
4131         struct iscsi_session *sess = conn->sess;
4132         /*
4133          * We expect this function to only ever be called from either RX or TX
4134          * thread context via iscsit_close_connection() once the other context
4135          * has been reset -> returned sleeping pre-handler state.
4136          */
4137         spin_lock_bh(&conn->cmd_lock);
4138         list_for_each_entry_safe(cmd, cmd_tmp, &conn->conn_cmd_list, i_conn_node) {
4139
4140                 list_del(&cmd->i_conn_node);
4141                 spin_unlock_bh(&conn->cmd_lock);
4142
4143                 iscsit_increment_maxcmdsn(cmd, sess);
4144
4145                 iscsit_free_cmd(cmd, true);
4146
4147                 spin_lock_bh(&conn->cmd_lock);
4148         }
4149         spin_unlock_bh(&conn->cmd_lock);
4150 }
4151
4152 static void iscsit_stop_timers_for_cmds(
4153         struct iscsi_conn *conn)
4154 {
4155         struct iscsi_cmd *cmd;
4156
4157         spin_lock_bh(&conn->cmd_lock);
4158         list_for_each_entry(cmd, &conn->conn_cmd_list, i_conn_node) {
4159                 if (cmd->data_direction == DMA_TO_DEVICE)
4160                         iscsit_stop_dataout_timer(cmd);
4161         }
4162         spin_unlock_bh(&conn->cmd_lock);
4163 }
4164
4165 int iscsit_close_connection(
4166         struct iscsi_conn *conn)
4167 {
4168         int conn_logout = (conn->conn_state == TARG_CONN_STATE_IN_LOGOUT);
4169         struct iscsi_session    *sess = conn->sess;
4170
4171         pr_debug("Closing iSCSI connection CID %hu on SID:"
4172                 " %u\n", conn->cid, sess->sid);
4173         /*
4174          * Always up conn_logout_comp just in case the RX Thread is sleeping
4175          * and the logout response never got sent because the connection
4176          * failed.
4177          */
4178         complete(&conn->conn_logout_comp);
4179
4180         iscsi_release_thread_set(conn);
4181
4182         iscsit_stop_timers_for_cmds(conn);
4183         iscsit_stop_nopin_response_timer(conn);
4184         iscsit_stop_nopin_timer(conn);
4185         iscsit_free_queue_reqs_for_conn(conn);
4186
4187         /*
4188          * During Connection recovery drop unacknowledged out of order
4189          * commands for this connection, and prepare the other commands
4190          * for realligence.
4191          *
4192          * During normal operation clear the out of order commands (but
4193          * do not free the struct iscsi_ooo_cmdsn's) and release all
4194          * struct iscsi_cmds.
4195          */
4196         if (atomic_read(&conn->connection_recovery)) {
4197                 iscsit_discard_unacknowledged_ooo_cmdsns_for_conn(conn);
4198                 iscsit_prepare_cmds_for_realligance(conn);
4199         } else {
4200                 iscsit_clear_ooo_cmdsns_for_conn(conn);
4201                 iscsit_release_commands_from_conn(conn);
4202         }
4203
4204         /*
4205          * Handle decrementing session or connection usage count if
4206          * a logout response was not able to be sent because the
4207          * connection failed.  Fall back to Session Recovery here.
4208          */
4209         if (atomic_read(&conn->conn_logout_remove)) {
4210                 if (conn->conn_logout_reason == ISCSI_LOGOUT_REASON_CLOSE_SESSION) {
4211                         iscsit_dec_conn_usage_count(conn);
4212                         iscsit_dec_session_usage_count(sess);
4213                 }
4214                 if (conn->conn_logout_reason == ISCSI_LOGOUT_REASON_CLOSE_CONNECTION)
4215                         iscsit_dec_conn_usage_count(conn);
4216
4217                 atomic_set(&conn->conn_logout_remove, 0);
4218                 atomic_set(&sess->session_reinstatement, 0);
4219                 atomic_set(&sess->session_fall_back_to_erl0, 1);
4220         }
4221
4222         spin_lock_bh(&sess->conn_lock);
4223         list_del(&conn->conn_list);
4224
4225         /*
4226          * Attempt to let the Initiator know this connection failed by
4227          * sending an Connection Dropped Async Message on another
4228          * active connection.
4229          */
4230         if (atomic_read(&conn->connection_recovery))
4231                 iscsit_build_conn_drop_async_message(conn);
4232
4233         spin_unlock_bh(&sess->conn_lock);
4234
4235         /*
4236          * If connection reinstatement is being performed on this connection,
4237          * up the connection reinstatement semaphore that is being blocked on
4238          * in iscsit_cause_connection_reinstatement().
4239          */
4240         spin_lock_bh(&conn->state_lock);
4241         if (atomic_read(&conn->sleep_on_conn_wait_comp)) {
4242                 spin_unlock_bh(&conn->state_lock);
4243                 complete(&conn->conn_wait_comp);
4244                 wait_for_completion(&conn->conn_post_wait_comp);
4245                 spin_lock_bh(&conn->state_lock);
4246         }
4247
4248         /*
4249          * If connection reinstatement is being performed on this connection
4250          * by receiving a REMOVECONNFORRECOVERY logout request, up the
4251          * connection wait rcfr semaphore that is being blocked on
4252          * an iscsit_connection_reinstatement_rcfr().
4253          */
4254         if (atomic_read(&conn->connection_wait_rcfr)) {
4255                 spin_unlock_bh(&conn->state_lock);
4256                 complete(&conn->conn_wait_rcfr_comp);
4257                 wait_for_completion(&conn->conn_post_wait_comp);
4258                 spin_lock_bh(&conn->state_lock);
4259         }
4260         atomic_set(&conn->connection_reinstatement, 1);
4261         spin_unlock_bh(&conn->state_lock);
4262
4263         /*
4264          * If any other processes are accessing this connection pointer we
4265          * must wait until they have completed.
4266          */
4267         iscsit_check_conn_usage_count(conn);
4268
4269         if (conn->conn_rx_hash.tfm)
4270                 crypto_free_hash(conn->conn_rx_hash.tfm);
4271         if (conn->conn_tx_hash.tfm)
4272                 crypto_free_hash(conn->conn_tx_hash.tfm);
4273
4274         if (conn->conn_cpumask)
4275                 free_cpumask_var(conn->conn_cpumask);
4276
4277         kfree(conn->conn_ops);
4278         conn->conn_ops = NULL;
4279
4280         if (conn->sock)
4281                 sock_release(conn->sock);
4282
4283         if (conn->conn_transport->iscsit_free_conn)
4284                 conn->conn_transport->iscsit_free_conn(conn);
4285
4286         iscsit_put_transport(conn->conn_transport);
4287
4288         conn->thread_set = NULL;
4289
4290         pr_debug("Moving to TARG_CONN_STATE_FREE.\n");
4291         conn->conn_state = TARG_CONN_STATE_FREE;
4292         kfree(conn);
4293
4294         spin_lock_bh(&sess->conn_lock);
4295         atomic_dec(&sess->nconn);
4296         pr_debug("Decremented iSCSI connection count to %hu from node:"
4297                 " %s\n", atomic_read(&sess->nconn),
4298                 sess->sess_ops->InitiatorName);
4299         /*
4300          * Make sure that if one connection fails in an non ERL=2 iSCSI
4301          * Session that they all fail.
4302          */
4303         if ((sess->sess_ops->ErrorRecoveryLevel != 2) && !conn_logout &&
4304              !atomic_read(&sess->session_logout))
4305                 atomic_set(&sess->session_fall_back_to_erl0, 1);
4306
4307         /*
4308          * If this was not the last connection in the session, and we are
4309          * performing session reinstatement or falling back to ERL=0, call
4310          * iscsit_stop_session() without sleeping to shutdown the other
4311          * active connections.
4312          */
4313         if (atomic_read(&sess->nconn)) {
4314                 if (!atomic_read(&sess->session_reinstatement) &&
4315                     !atomic_read(&sess->session_fall_back_to_erl0)) {
4316                         spin_unlock_bh(&sess->conn_lock);
4317                         return 0;
4318                 }
4319                 if (!atomic_read(&sess->session_stop_active)) {
4320                         atomic_set(&sess->session_stop_active, 1);
4321                         spin_unlock_bh(&sess->conn_lock);
4322                         iscsit_stop_session(sess, 0, 0);
4323                         return 0;
4324                 }
4325                 spin_unlock_bh(&sess->conn_lock);
4326                 return 0;
4327         }
4328
4329         /*
4330          * If this was the last connection in the session and one of the
4331          * following is occurring:
4332          *
4333          * Session Reinstatement is not being performed, and are falling back
4334          * to ERL=0 call iscsit_close_session().
4335          *
4336          * Session Logout was requested.  iscsit_close_session() will be called
4337          * elsewhere.
4338          *
4339          * Session Continuation is not being performed, start the Time2Retain
4340          * handler and check if sleep_on_sess_wait_sem is active.
4341          */
4342         if (!atomic_read(&sess->session_reinstatement) &&
4343              atomic_read(&sess->session_fall_back_to_erl0)) {
4344                 spin_unlock_bh(&sess->conn_lock);
4345                 target_put_session(sess->se_sess);
4346
4347                 return 0;
4348         } else if (atomic_read(&sess->session_logout)) {
4349                 pr_debug("Moving to TARG_SESS_STATE_FREE.\n");
4350                 sess->session_state = TARG_SESS_STATE_FREE;
4351                 spin_unlock_bh(&sess->conn_lock);
4352
4353                 if (atomic_read(&sess->sleep_on_sess_wait_comp))
4354                         complete(&sess->session_wait_comp);
4355
4356                 return 0;
4357         } else {
4358                 pr_debug("Moving to TARG_SESS_STATE_FAILED.\n");
4359                 sess->session_state = TARG_SESS_STATE_FAILED;
4360
4361                 if (!atomic_read(&sess->session_continuation)) {
4362                         spin_unlock_bh(&sess->conn_lock);
4363                         iscsit_start_time2retain_handler(sess);
4364                 } else
4365                         spin_unlock_bh(&sess->conn_lock);
4366
4367                 if (atomic_read(&sess->sleep_on_sess_wait_comp))
4368                         complete(&sess->session_wait_comp);
4369
4370                 return 0;
4371         }
4372         spin_unlock_bh(&sess->conn_lock);
4373
4374         return 0;
4375 }
4376
4377 int iscsit_close_session(struct iscsi_session *sess)
4378 {
4379         struct iscsi_portal_group *tpg = ISCSI_TPG_S(sess);
4380         struct se_portal_group *se_tpg = &tpg->tpg_se_tpg;
4381
4382         if (atomic_read(&sess->nconn)) {
4383                 pr_err("%d connection(s) still exist for iSCSI session"
4384                         " to %s\n", atomic_read(&sess->nconn),
4385                         sess->sess_ops->InitiatorName);
4386                 BUG();
4387         }
4388
4389         spin_lock_bh(&se_tpg->session_lock);
4390         atomic_set(&sess->session_logout, 1);
4391         atomic_set(&sess->session_reinstatement, 1);
4392         iscsit_stop_time2retain_timer(sess);
4393         spin_unlock_bh(&se_tpg->session_lock);
4394
4395         /*
4396          * transport_deregister_session_configfs() will clear the
4397          * struct se_node_acl->nacl_sess pointer now as a iscsi_np process context
4398          * can be setting it again with __transport_register_session() in
4399          * iscsi_post_login_handler() again after the iscsit_stop_session()
4400          * completes in iscsi_np context.
4401          */
4402         transport_deregister_session_configfs(sess->se_sess);
4403
4404         /*
4405          * If any other processes are accessing this session pointer we must
4406          * wait until they have completed.  If we are in an interrupt (the
4407          * time2retain handler) and contain and active session usage count we
4408          * restart the timer and exit.
4409          */
4410         if (!in_interrupt()) {
4411                 if (iscsit_check_session_usage_count(sess) == 1)
4412                         iscsit_stop_session(sess, 1, 1);
4413         } else {
4414                 if (iscsit_check_session_usage_count(sess) == 2) {
4415                         atomic_set(&sess->session_logout, 0);
4416                         iscsit_start_time2retain_handler(sess);
4417                         return 0;
4418                 }
4419         }
4420
4421         transport_deregister_session(sess->se_sess);
4422
4423         if (sess->sess_ops->ErrorRecoveryLevel == 2)
4424                 iscsit_free_connection_recovery_entires(sess);
4425
4426         iscsit_free_all_ooo_cmdsns(sess);
4427
4428         spin_lock_bh(&se_tpg->session_lock);
4429         pr_debug("Moving to TARG_SESS_STATE_FREE.\n");
4430         sess->session_state = TARG_SESS_STATE_FREE;
4431         pr_debug("Released iSCSI session from node: %s\n",
4432                         sess->sess_ops->InitiatorName);
4433         tpg->nsessions--;
4434         if (tpg->tpg_tiqn)
4435                 tpg->tpg_tiqn->tiqn_nsessions--;
4436
4437         pr_debug("Decremented number of active iSCSI Sessions on"
4438                 " iSCSI TPG: %hu to %u\n", tpg->tpgt, tpg->nsessions);
4439
4440         spin_lock(&sess_idr_lock);
4441         idr_remove(&sess_idr, sess->session_index);
4442         spin_unlock(&sess_idr_lock);
4443
4444         kfree(sess->sess_ops);
4445         sess->sess_ops = NULL;
4446         spin_unlock_bh(&se_tpg->session_lock);
4447
4448         kfree(sess);
4449         return 0;
4450 }
4451
4452 static void iscsit_logout_post_handler_closesession(
4453         struct iscsi_conn *conn)
4454 {
4455         struct iscsi_session *sess = conn->sess;
4456
4457         iscsi_set_thread_clear(conn, ISCSI_CLEAR_TX_THREAD);
4458         iscsi_set_thread_set_signal(conn, ISCSI_SIGNAL_TX_THREAD);
4459
4460         atomic_set(&conn->conn_logout_remove, 0);
4461         complete(&conn->conn_logout_comp);
4462
4463         iscsit_dec_conn_usage_count(conn);
4464         iscsit_stop_session(sess, 1, 1);
4465         iscsit_dec_session_usage_count(sess);
4466         target_put_session(sess->se_sess);
4467 }
4468
4469 static void iscsit_logout_post_handler_samecid(
4470         struct iscsi_conn *conn)
4471 {
4472         iscsi_set_thread_clear(conn, ISCSI_CLEAR_TX_THREAD);
4473         iscsi_set_thread_set_signal(conn, ISCSI_SIGNAL_TX_THREAD);
4474
4475         atomic_set(&conn->conn_logout_remove, 0);
4476         complete(&conn->conn_logout_comp);
4477
4478         iscsit_cause_connection_reinstatement(conn, 1);
4479         iscsit_dec_conn_usage_count(conn);
4480 }
4481
4482 static void iscsit_logout_post_handler_diffcid(
4483         struct iscsi_conn *conn,
4484         u16 cid)
4485 {
4486         struct iscsi_conn *l_conn;
4487         struct iscsi_session *sess = conn->sess;
4488
4489         if (!sess)
4490                 return;
4491
4492         spin_lock_bh(&sess->conn_lock);
4493         list_for_each_entry(l_conn, &sess->sess_conn_list, conn_list) {
4494                 if (l_conn->cid == cid) {
4495                         iscsit_inc_conn_usage_count(l_conn);
4496                         break;
4497                 }
4498         }
4499         spin_unlock_bh(&sess->conn_lock);
4500
4501         if (!l_conn)
4502                 return;
4503
4504         if (l_conn->sock)
4505                 l_conn->sock->ops->shutdown(l_conn->sock, RCV_SHUTDOWN);
4506
4507         spin_lock_bh(&l_conn->state_lock);
4508         pr_debug("Moving to TARG_CONN_STATE_IN_LOGOUT.\n");
4509         l_conn->conn_state = TARG_CONN_STATE_IN_LOGOUT;
4510         spin_unlock_bh(&l_conn->state_lock);
4511
4512         iscsit_cause_connection_reinstatement(l_conn, 1);
4513         iscsit_dec_conn_usage_count(l_conn);
4514 }
4515
4516 /*
4517  *      Return of 0 causes the TX thread to restart.
4518  */
4519 int iscsit_logout_post_handler(
4520         struct iscsi_cmd *cmd,
4521         struct iscsi_conn *conn)
4522 {
4523         int ret = 0;
4524
4525         switch (cmd->logout_reason) {
4526         case ISCSI_LOGOUT_REASON_CLOSE_SESSION:
4527                 switch (cmd->logout_response) {
4528                 case ISCSI_LOGOUT_SUCCESS:
4529                 case ISCSI_LOGOUT_CLEANUP_FAILED:
4530                 default:
4531                         iscsit_logout_post_handler_closesession(conn);
4532                         break;
4533                 }
4534                 ret = 0;
4535                 break;
4536         case ISCSI_LOGOUT_REASON_CLOSE_CONNECTION:
4537                 if (conn->cid == cmd->logout_cid) {
4538                         switch (cmd->logout_response) {
4539                         case ISCSI_LOGOUT_SUCCESS:
4540                         case ISCSI_LOGOUT_CLEANUP_FAILED:
4541                         default:
4542                                 iscsit_logout_post_handler_samecid(conn);
4543                                 break;
4544                         }
4545                         ret = 0;
4546                 } else {
4547                         switch (cmd->logout_response) {
4548                         case ISCSI_LOGOUT_SUCCESS:
4549                                 iscsit_logout_post_handler_diffcid(conn,
4550                                         cmd->logout_cid);
4551                                 break;
4552                         case ISCSI_LOGOUT_CID_NOT_FOUND:
4553                         case ISCSI_LOGOUT_CLEANUP_FAILED:
4554                         default:
4555                                 break;
4556                         }
4557                         ret = 1;
4558                 }
4559                 break;
4560         case ISCSI_LOGOUT_REASON_RECOVERY:
4561                 switch (cmd->logout_response) {
4562                 case ISCSI_LOGOUT_SUCCESS:
4563                 case ISCSI_LOGOUT_CID_NOT_FOUND:
4564                 case ISCSI_LOGOUT_RECOVERY_UNSUPPORTED:
4565                 case ISCSI_LOGOUT_CLEANUP_FAILED:
4566                 default:
4567                         break;
4568                 }
4569                 ret = 1;
4570                 break;
4571         default:
4572                 break;
4573
4574         }
4575         return ret;
4576 }
4577 EXPORT_SYMBOL(iscsit_logout_post_handler);
4578
4579 void iscsit_fail_session(struct iscsi_session *sess)
4580 {
4581         struct iscsi_conn *conn;
4582
4583         spin_lock_bh(&sess->conn_lock);
4584         list_for_each_entry(conn, &sess->sess_conn_list, conn_list) {
4585                 pr_debug("Moving to TARG_CONN_STATE_CLEANUP_WAIT.\n");
4586                 conn->conn_state = TARG_CONN_STATE_CLEANUP_WAIT;
4587         }
4588         spin_unlock_bh(&sess->conn_lock);
4589
4590         pr_debug("Moving to TARG_SESS_STATE_FAILED.\n");
4591         sess->session_state = TARG_SESS_STATE_FAILED;
4592 }
4593
4594 int iscsit_free_session(struct iscsi_session *sess)
4595 {
4596         u16 conn_count = atomic_read(&sess->nconn);
4597         struct iscsi_conn *conn, *conn_tmp = NULL;
4598         int is_last;
4599
4600         spin_lock_bh(&sess->conn_lock);
4601         atomic_set(&sess->sleep_on_sess_wait_comp, 1);
4602
4603         list_for_each_entry_safe(conn, conn_tmp, &sess->sess_conn_list,
4604                         conn_list) {
4605                 if (conn_count == 0)
4606                         break;
4607
4608                 if (list_is_last(&conn->conn_list, &sess->sess_conn_list)) {
4609                         is_last = 1;
4610                 } else {
4611                         iscsit_inc_conn_usage_count(conn_tmp);
4612                         is_last = 0;
4613                 }
4614                 iscsit_inc_conn_usage_count(conn);
4615
4616                 spin_unlock_bh(&sess->conn_lock);
4617                 iscsit_cause_connection_reinstatement(conn, 1);
4618                 spin_lock_bh(&sess->conn_lock);
4619
4620                 iscsit_dec_conn_usage_count(conn);
4621                 if (is_last == 0)
4622                         iscsit_dec_conn_usage_count(conn_tmp);
4623
4624                 conn_count--;
4625         }
4626
4627         if (atomic_read(&sess->nconn)) {
4628                 spin_unlock_bh(&sess->conn_lock);
4629                 wait_for_completion(&sess->session_wait_comp);
4630         } else
4631                 spin_unlock_bh(&sess->conn_lock);
4632
4633         target_put_session(sess->se_sess);
4634         return 0;
4635 }
4636
4637 void iscsit_stop_session(
4638         struct iscsi_session *sess,
4639         int session_sleep,
4640         int connection_sleep)
4641 {
4642         u16 conn_count = atomic_read(&sess->nconn);
4643         struct iscsi_conn *conn, *conn_tmp = NULL;
4644         int is_last;
4645
4646         spin_lock_bh(&sess->conn_lock);
4647         if (session_sleep)
4648                 atomic_set(&sess->sleep_on_sess_wait_comp, 1);
4649
4650         if (connection_sleep) {
4651                 list_for_each_entry_safe(conn, conn_tmp, &sess->sess_conn_list,
4652                                 conn_list) {
4653                         if (conn_count == 0)
4654                                 break;
4655
4656                         if (list_is_last(&conn->conn_list, &sess->sess_conn_list)) {
4657                                 is_last = 1;
4658                         } else {
4659                                 iscsit_inc_conn_usage_count(conn_tmp);
4660                                 is_last = 0;
4661                         }
4662                         iscsit_inc_conn_usage_count(conn);
4663
4664                         spin_unlock_bh(&sess->conn_lock);
4665                         iscsit_cause_connection_reinstatement(conn, 1);
4666                         spin_lock_bh(&sess->conn_lock);
4667
4668                         iscsit_dec_conn_usage_count(conn);
4669                         if (is_last == 0)
4670                                 iscsit_dec_conn_usage_count(conn_tmp);
4671                         conn_count--;
4672                 }
4673         } else {
4674                 list_for_each_entry(conn, &sess->sess_conn_list, conn_list)
4675                         iscsit_cause_connection_reinstatement(conn, 0);
4676         }
4677
4678         if (session_sleep && atomic_read(&sess->nconn)) {
4679                 spin_unlock_bh(&sess->conn_lock);
4680                 wait_for_completion(&sess->session_wait_comp);
4681         } else
4682                 spin_unlock_bh(&sess->conn_lock);
4683 }
4684
4685 int iscsit_release_sessions_for_tpg(struct iscsi_portal_group *tpg, int force)
4686 {
4687         struct iscsi_session *sess;
4688         struct se_portal_group *se_tpg = &tpg->tpg_se_tpg;
4689         struct se_session *se_sess, *se_sess_tmp;
4690         int session_count = 0;
4691
4692         spin_lock_bh(&se_tpg->session_lock);
4693         if (tpg->nsessions && !force) {
4694                 spin_unlock_bh(&se_tpg->session_lock);
4695                 return -1;
4696         }
4697
4698         list_for_each_entry_safe(se_sess, se_sess_tmp, &se_tpg->tpg_sess_list,
4699                         sess_list) {
4700                 sess = (struct iscsi_session *)se_sess->fabric_sess_ptr;
4701
4702                 spin_lock(&sess->conn_lock);
4703                 if (atomic_read(&sess->session_fall_back_to_erl0) ||
4704                     atomic_read(&sess->session_logout) ||
4705                     (sess->time2retain_timer_flags & ISCSI_TF_EXPIRED)) {
4706                         spin_unlock(&sess->conn_lock);
4707                         continue;
4708                 }
4709                 atomic_set(&sess->session_reinstatement, 1);
4710                 spin_unlock(&sess->conn_lock);
4711                 spin_unlock_bh(&se_tpg->session_lock);
4712
4713                 iscsit_free_session(sess);
4714                 spin_lock_bh(&se_tpg->session_lock);
4715
4716                 session_count++;
4717         }
4718         spin_unlock_bh(&se_tpg->session_lock);
4719
4720         pr_debug("Released %d iSCSI Session(s) from Target Portal"
4721                         " Group: %hu\n", session_count, tpg->tpgt);
4722         return 0;
4723 }
4724
4725 MODULE_DESCRIPTION("iSCSI-Target Driver for mainline target infrastructure");
4726 MODULE_VERSION("4.1.x");
4727 MODULE_AUTHOR("nab@Linux-iSCSI.org");
4728 MODULE_LICENSE("GPL");
4729
4730 module_init(iscsi_target_init_module);
4731 module_exit(iscsi_target_cleanup_module);