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