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