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