Merge branch 'for-next' of git://git.kernel.org/pub/scm/linux/kernel/git/nab/target...
[muen/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 <net/ipv6.h>
30 #include <scsi/scsi_proto.h>
31 #include <scsi/iscsi_proto.h>
32 #include <scsi/scsi_tcq.h>
33 #include <target/target_core_base.h>
34 #include <target/target_core_fabric.h>
35
36 #include <target/iscsi/iscsi_target_core.h>
37 #include "iscsi_target_parameters.h"
38 #include "iscsi_target_seq_pdu_list.h"
39 #include "iscsi_target_datain_values.h"
40 #include "iscsi_target_erl0.h"
41 #include "iscsi_target_erl1.h"
42 #include "iscsi_target_erl2.h"
43 #include "iscsi_target_login.h"
44 #include "iscsi_target_tmr.h"
45 #include "iscsi_target_tpg.h"
46 #include "iscsi_target_util.h"
47 #include "iscsi_target.h"
48 #include "iscsi_target_device.h"
49 #include <target/iscsi/iscsi_target_stat.h>
50
51 #include <target/iscsi/iscsi_transport.h>
52
53 static LIST_HEAD(g_tiqn_list);
54 static LIST_HEAD(g_np_list);
55 static DEFINE_SPINLOCK(tiqn_lock);
56 static DEFINE_MUTEX(np_lock);
57
58 static struct idr tiqn_idr;
59 struct idr sess_idr;
60 struct mutex auth_id_lock;
61 spinlock_t sess_idr_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 /*
312  * Called with mutex np_lock held
313  */
314 static struct iscsi_np *iscsit_get_np(
315         struct sockaddr_storage *sockaddr,
316         int network_transport)
317 {
318         struct iscsi_np *np;
319         bool match;
320
321         list_for_each_entry(np, &g_np_list, np_list) {
322                 spin_lock_bh(&np->np_thread_lock);
323                 if (np->np_thread_state != ISCSI_NP_THREAD_ACTIVE) {
324                         spin_unlock_bh(&np->np_thread_lock);
325                         continue;
326                 }
327
328                 match = iscsit_check_np_match(sockaddr, np, network_transport);
329                 if (match) {
330                         /*
331                          * Increment the np_exports reference count now to
332                          * prevent iscsit_del_np() below from being called
333                          * while iscsi_tpg_add_network_portal() is called.
334                          */
335                         np->np_exports++;
336                         spin_unlock_bh(&np->np_thread_lock);
337                         return np;
338                 }
339                 spin_unlock_bh(&np->np_thread_lock);
340         }
341
342         return NULL;
343 }
344
345 struct iscsi_np *iscsit_add_np(
346         struct sockaddr_storage *sockaddr,
347         int network_transport)
348 {
349         struct iscsi_np *np;
350         int ret;
351
352         mutex_lock(&np_lock);
353
354         /*
355          * Locate the existing struct iscsi_np if already active..
356          */
357         np = iscsit_get_np(sockaddr, network_transport);
358         if (np) {
359                 mutex_unlock(&np_lock);
360                 return np;
361         }
362
363         np = kzalloc(sizeof(*np), GFP_KERNEL);
364         if (!np) {
365                 mutex_unlock(&np_lock);
366                 return ERR_PTR(-ENOMEM);
367         }
368
369         np->np_flags |= NPF_IP_NETWORK;
370         np->np_network_transport = network_transport;
371         spin_lock_init(&np->np_thread_lock);
372         init_completion(&np->np_restart_comp);
373         INIT_LIST_HEAD(&np->np_list);
374
375         timer_setup(&np->np_login_timer, iscsi_handle_login_thread_timeout, 0);
376
377         ret = iscsi_target_setup_login_socket(np, sockaddr);
378         if (ret != 0) {
379                 kfree(np);
380                 mutex_unlock(&np_lock);
381                 return ERR_PTR(ret);
382         }
383
384         np->np_thread = kthread_run(iscsi_target_login_thread, np, "iscsi_np");
385         if (IS_ERR(np->np_thread)) {
386                 pr_err("Unable to create kthread: iscsi_np\n");
387                 ret = PTR_ERR(np->np_thread);
388                 kfree(np);
389                 mutex_unlock(&np_lock);
390                 return ERR_PTR(ret);
391         }
392         /*
393          * Increment the np_exports reference count now to prevent
394          * iscsit_del_np() below from being run while a new call to
395          * iscsi_tpg_add_network_portal() for a matching iscsi_np is
396          * active.  We don't need to hold np->np_thread_lock at this
397          * point because iscsi_np has not been added to g_np_list yet.
398          */
399         np->np_exports = 1;
400         np->np_thread_state = ISCSI_NP_THREAD_ACTIVE;
401
402         list_add_tail(&np->np_list, &g_np_list);
403         mutex_unlock(&np_lock);
404
405         pr_debug("CORE[0] - Added Network Portal: %pISpc on %s\n",
406                 &np->np_sockaddr, np->np_transport->name);
407
408         return np;
409 }
410
411 int iscsit_reset_np_thread(
412         struct iscsi_np *np,
413         struct iscsi_tpg_np *tpg_np,
414         struct iscsi_portal_group *tpg,
415         bool shutdown)
416 {
417         spin_lock_bh(&np->np_thread_lock);
418         if (np->np_thread_state == ISCSI_NP_THREAD_INACTIVE) {
419                 spin_unlock_bh(&np->np_thread_lock);
420                 return 0;
421         }
422         np->np_thread_state = ISCSI_NP_THREAD_RESET;
423         atomic_inc(&np->np_reset_count);
424
425         if (np->np_thread) {
426                 spin_unlock_bh(&np->np_thread_lock);
427                 send_sig(SIGINT, np->np_thread, 1);
428                 wait_for_completion(&np->np_restart_comp);
429                 spin_lock_bh(&np->np_thread_lock);
430         }
431         spin_unlock_bh(&np->np_thread_lock);
432
433         if (tpg_np && shutdown) {
434                 kref_put(&tpg_np->tpg_np_kref, iscsit_login_kref_put);
435
436                 wait_for_completion(&tpg_np->tpg_np_comp);
437         }
438
439         return 0;
440 }
441
442 static void iscsit_free_np(struct iscsi_np *np)
443 {
444         if (np->np_socket)
445                 sock_release(np->np_socket);
446 }
447
448 int iscsit_del_np(struct iscsi_np *np)
449 {
450         spin_lock_bh(&np->np_thread_lock);
451         np->np_exports--;
452         if (np->np_exports) {
453                 np->enabled = true;
454                 spin_unlock_bh(&np->np_thread_lock);
455                 return 0;
456         }
457         np->np_thread_state = ISCSI_NP_THREAD_SHUTDOWN;
458         spin_unlock_bh(&np->np_thread_lock);
459
460         if (np->np_thread) {
461                 /*
462                  * We need to send the signal to wakeup Linux/Net
463                  * which may be sleeping in sock_accept()..
464                  */
465                 send_sig(SIGINT, np->np_thread, 1);
466                 kthread_stop(np->np_thread);
467                 np->np_thread = NULL;
468         }
469
470         np->np_transport->iscsit_free_np(np);
471
472         mutex_lock(&np_lock);
473         list_del(&np->np_list);
474         mutex_unlock(&np_lock);
475
476         pr_debug("CORE[0] - Removed Network Portal: %pISpc on %s\n",
477                 &np->np_sockaddr, np->np_transport->name);
478
479         iscsit_put_transport(np->np_transport);
480         kfree(np);
481         return 0;
482 }
483
484 static void iscsit_get_rx_pdu(struct iscsi_conn *);
485
486 int iscsit_queue_rsp(struct iscsi_conn *conn, struct iscsi_cmd *cmd)
487 {
488         return iscsit_add_cmd_to_response_queue(cmd, cmd->conn, cmd->i_state);
489 }
490 EXPORT_SYMBOL(iscsit_queue_rsp);
491
492 void iscsit_aborted_task(struct iscsi_conn *conn, struct iscsi_cmd *cmd)
493 {
494         spin_lock_bh(&conn->cmd_lock);
495         if (!list_empty(&cmd->i_conn_node) &&
496             !(cmd->se_cmd.transport_state & CMD_T_FABRIC_STOP))
497                 list_del_init(&cmd->i_conn_node);
498         spin_unlock_bh(&conn->cmd_lock);
499
500         __iscsit_free_cmd(cmd, true);
501 }
502 EXPORT_SYMBOL(iscsit_aborted_task);
503
504 static void iscsit_do_crypto_hash_buf(struct ahash_request *, const void *,
505                                       u32, u32, const void *, void *);
506 static void iscsit_tx_thread_wait_for_tcp(struct iscsi_conn *);
507
508 static int
509 iscsit_xmit_nondatain_pdu(struct iscsi_conn *conn, struct iscsi_cmd *cmd,
510                           const void *data_buf, u32 data_buf_len)
511 {
512         struct iscsi_hdr *hdr = (struct iscsi_hdr *)cmd->pdu;
513         struct kvec *iov;
514         u32 niov = 0, tx_size = ISCSI_HDR_LEN;
515         int ret;
516
517         iov = &cmd->iov_misc[0];
518         iov[niov].iov_base      = cmd->pdu;
519         iov[niov++].iov_len     = ISCSI_HDR_LEN;
520
521         if (conn->conn_ops->HeaderDigest) {
522                 u32 *header_digest = (u32 *)&cmd->pdu[ISCSI_HDR_LEN];
523
524                 iscsit_do_crypto_hash_buf(conn->conn_tx_hash, hdr,
525                                           ISCSI_HDR_LEN, 0, NULL,
526                                           header_digest);
527
528                 iov[0].iov_len += ISCSI_CRC_LEN;
529                 tx_size += ISCSI_CRC_LEN;
530                 pr_debug("Attaching CRC32C HeaderDigest"
531                          " to opcode 0x%x 0x%08x\n",
532                          hdr->opcode, *header_digest);
533         }
534
535         if (data_buf_len) {
536                 u32 padding = ((-data_buf_len) & 3);
537
538                 iov[niov].iov_base      = (void *)data_buf;
539                 iov[niov++].iov_len     = data_buf_len;
540                 tx_size += data_buf_len;
541
542                 if (padding != 0) {
543                         iov[niov].iov_base = &cmd->pad_bytes;
544                         iov[niov++].iov_len = padding;
545                         tx_size += padding;
546                         pr_debug("Attaching %u additional"
547                                  " padding bytes.\n", padding);
548                 }
549
550                 if (conn->conn_ops->DataDigest) {
551                         iscsit_do_crypto_hash_buf(conn->conn_tx_hash,
552                                                   data_buf, data_buf_len,
553                                                   padding, &cmd->pad_bytes,
554                                                   &cmd->data_crc);
555
556                         iov[niov].iov_base = &cmd->data_crc;
557                         iov[niov++].iov_len = ISCSI_CRC_LEN;
558                         tx_size += ISCSI_CRC_LEN;
559                         pr_debug("Attached DataDigest for %u"
560                                  " bytes opcode 0x%x, CRC 0x%08x\n",
561                                  data_buf_len, hdr->opcode, cmd->data_crc);
562                 }
563         }
564
565         cmd->iov_misc_count = niov;
566         cmd->tx_size = tx_size;
567
568         ret = iscsit_send_tx_data(cmd, conn, 1);
569         if (ret < 0) {
570                 iscsit_tx_thread_wait_for_tcp(conn);
571                 return ret;
572         }
573
574         return 0;
575 }
576
577 static int iscsit_map_iovec(struct iscsi_cmd *, struct kvec *, u32, u32);
578 static void iscsit_unmap_iovec(struct iscsi_cmd *);
579 static u32 iscsit_do_crypto_hash_sg(struct ahash_request *, struct iscsi_cmd *,
580                                     u32, u32, u32, u8 *);
581 static int
582 iscsit_xmit_datain_pdu(struct iscsi_conn *conn, struct iscsi_cmd *cmd,
583                        const struct iscsi_datain *datain)
584 {
585         struct kvec *iov;
586         u32 iov_count = 0, tx_size = 0;
587         int ret, iov_ret;
588
589         iov = &cmd->iov_data[0];
590         iov[iov_count].iov_base = cmd->pdu;
591         iov[iov_count++].iov_len = ISCSI_HDR_LEN;
592         tx_size += ISCSI_HDR_LEN;
593
594         if (conn->conn_ops->HeaderDigest) {
595                 u32 *header_digest = (u32 *)&cmd->pdu[ISCSI_HDR_LEN];
596
597                 iscsit_do_crypto_hash_buf(conn->conn_tx_hash, cmd->pdu,
598                                           ISCSI_HDR_LEN, 0, NULL,
599                                           header_digest);
600
601                 iov[0].iov_len += ISCSI_CRC_LEN;
602                 tx_size += ISCSI_CRC_LEN;
603
604                 pr_debug("Attaching CRC32 HeaderDigest for DataIN PDU 0x%08x\n",
605                          *header_digest);
606         }
607
608         iov_ret = iscsit_map_iovec(cmd, &cmd->iov_data[1],
609                                    datain->offset, datain->length);
610         if (iov_ret < 0)
611                 return -1;
612
613         iov_count += iov_ret;
614         tx_size += datain->length;
615
616         cmd->padding = ((-datain->length) & 3);
617         if (cmd->padding) {
618                 iov[iov_count].iov_base         = cmd->pad_bytes;
619                 iov[iov_count++].iov_len        = cmd->padding;
620                 tx_size += cmd->padding;
621
622                 pr_debug("Attaching %u padding bytes\n", cmd->padding);
623         }
624
625         if (conn->conn_ops->DataDigest) {
626                 cmd->data_crc = iscsit_do_crypto_hash_sg(conn->conn_tx_hash,
627                                                          cmd, datain->offset,
628                                                          datain->length,
629                                                          cmd->padding,
630                                                          cmd->pad_bytes);
631
632                 iov[iov_count].iov_base = &cmd->data_crc;
633                 iov[iov_count++].iov_len = ISCSI_CRC_LEN;
634                 tx_size += ISCSI_CRC_LEN;
635
636                 pr_debug("Attached CRC32C DataDigest %d bytes, crc 0x%08x\n",
637                          datain->length + cmd->padding, cmd->data_crc);
638         }
639
640         cmd->iov_data_count = iov_count;
641         cmd->tx_size = tx_size;
642
643         ret = iscsit_fe_sendpage_sg(cmd, conn);
644
645         iscsit_unmap_iovec(cmd);
646
647         if (ret < 0) {
648                 iscsit_tx_thread_wait_for_tcp(conn);
649                 return ret;
650         }
651
652         return 0;
653 }
654
655 static int iscsit_xmit_pdu(struct iscsi_conn *conn, struct iscsi_cmd *cmd,
656                            struct iscsi_datain_req *dr, const void *buf,
657                            u32 buf_len)
658 {
659         if (dr)
660                 return iscsit_xmit_datain_pdu(conn, cmd, buf);
661         else
662                 return iscsit_xmit_nondatain_pdu(conn, cmd, buf, buf_len);
663 }
664
665 static enum target_prot_op iscsit_get_sup_prot_ops(struct iscsi_conn *conn)
666 {
667         return TARGET_PROT_NORMAL;
668 }
669
670 static struct iscsit_transport iscsi_target_transport = {
671         .name                   = "iSCSI/TCP",
672         .transport_type         = ISCSI_TCP,
673         .rdma_shutdown          = false,
674         .owner                  = NULL,
675         .iscsit_setup_np        = iscsit_setup_np,
676         .iscsit_accept_np       = iscsit_accept_np,
677         .iscsit_free_np         = iscsit_free_np,
678         .iscsit_get_login_rx    = iscsit_get_login_rx,
679         .iscsit_put_login_tx    = iscsit_put_login_tx,
680         .iscsit_get_dataout     = iscsit_build_r2ts_for_cmd,
681         .iscsit_immediate_queue = iscsit_immediate_queue,
682         .iscsit_response_queue  = iscsit_response_queue,
683         .iscsit_queue_data_in   = iscsit_queue_rsp,
684         .iscsit_queue_status    = iscsit_queue_rsp,
685         .iscsit_aborted_task    = iscsit_aborted_task,
686         .iscsit_xmit_pdu        = iscsit_xmit_pdu,
687         .iscsit_get_rx_pdu      = iscsit_get_rx_pdu,
688         .iscsit_get_sup_prot_ops = iscsit_get_sup_prot_ops,
689 };
690
691 static int __init iscsi_target_init_module(void)
692 {
693         int ret = 0, size;
694
695         pr_debug("iSCSI-Target "ISCSIT_VERSION"\n");
696         iscsit_global = kzalloc(sizeof(*iscsit_global), GFP_KERNEL);
697         if (!iscsit_global)
698                 return -1;
699
700         spin_lock_init(&iscsit_global->ts_bitmap_lock);
701         mutex_init(&auth_id_lock);
702         spin_lock_init(&sess_idr_lock);
703         idr_init(&tiqn_idr);
704         idr_init(&sess_idr);
705
706         ret = target_register_template(&iscsi_ops);
707         if (ret)
708                 goto out;
709
710         size = BITS_TO_LONGS(ISCSIT_BITMAP_BITS) * sizeof(long);
711         iscsit_global->ts_bitmap = vzalloc(size);
712         if (!iscsit_global->ts_bitmap)
713                 goto configfs_out;
714
715         lio_qr_cache = kmem_cache_create("lio_qr_cache",
716                         sizeof(struct iscsi_queue_req),
717                         __alignof__(struct iscsi_queue_req), 0, NULL);
718         if (!lio_qr_cache) {
719                 pr_err("nable to kmem_cache_create() for"
720                                 " lio_qr_cache\n");
721                 goto bitmap_out;
722         }
723
724         lio_dr_cache = kmem_cache_create("lio_dr_cache",
725                         sizeof(struct iscsi_datain_req),
726                         __alignof__(struct iscsi_datain_req), 0, NULL);
727         if (!lio_dr_cache) {
728                 pr_err("Unable to kmem_cache_create() for"
729                                 " lio_dr_cache\n");
730                 goto qr_out;
731         }
732
733         lio_ooo_cache = kmem_cache_create("lio_ooo_cache",
734                         sizeof(struct iscsi_ooo_cmdsn),
735                         __alignof__(struct iscsi_ooo_cmdsn), 0, NULL);
736         if (!lio_ooo_cache) {
737                 pr_err("Unable to kmem_cache_create() for"
738                                 " lio_ooo_cache\n");
739                 goto dr_out;
740         }
741
742         lio_r2t_cache = kmem_cache_create("lio_r2t_cache",
743                         sizeof(struct iscsi_r2t), __alignof__(struct iscsi_r2t),
744                         0, NULL);
745         if (!lio_r2t_cache) {
746                 pr_err("Unable to kmem_cache_create() for"
747                                 " lio_r2t_cache\n");
748                 goto ooo_out;
749         }
750
751         iscsit_register_transport(&iscsi_target_transport);
752
753         if (iscsit_load_discovery_tpg() < 0)
754                 goto r2t_out;
755
756         return ret;
757 r2t_out:
758         iscsit_unregister_transport(&iscsi_target_transport);
759         kmem_cache_destroy(lio_r2t_cache);
760 ooo_out:
761         kmem_cache_destroy(lio_ooo_cache);
762 dr_out:
763         kmem_cache_destroy(lio_dr_cache);
764 qr_out:
765         kmem_cache_destroy(lio_qr_cache);
766 bitmap_out:
767         vfree(iscsit_global->ts_bitmap);
768 configfs_out:
769         /* XXX: this probably wants it to be it's own unwind step.. */
770         if (iscsit_global->discovery_tpg)
771                 iscsit_tpg_disable_portal_group(iscsit_global->discovery_tpg, 1);
772         target_unregister_template(&iscsi_ops);
773 out:
774         kfree(iscsit_global);
775         return -ENOMEM;
776 }
777
778 static void __exit iscsi_target_cleanup_module(void)
779 {
780         iscsit_release_discovery_tpg();
781         iscsit_unregister_transport(&iscsi_target_transport);
782         kmem_cache_destroy(lio_qr_cache);
783         kmem_cache_destroy(lio_dr_cache);
784         kmem_cache_destroy(lio_ooo_cache);
785         kmem_cache_destroy(lio_r2t_cache);
786
787         /*
788          * Shutdown discovery sessions and disable discovery TPG
789          */
790         if (iscsit_global->discovery_tpg)
791                 iscsit_tpg_disable_portal_group(iscsit_global->discovery_tpg, 1);
792
793         target_unregister_template(&iscsi_ops);
794
795         vfree(iscsit_global->ts_bitmap);
796         kfree(iscsit_global);
797 }
798
799 int iscsit_add_reject(
800         struct iscsi_conn *conn,
801         u8 reason,
802         unsigned char *buf)
803 {
804         struct iscsi_cmd *cmd;
805
806         cmd = iscsit_allocate_cmd(conn, TASK_INTERRUPTIBLE);
807         if (!cmd)
808                 return -1;
809
810         cmd->iscsi_opcode = ISCSI_OP_REJECT;
811         cmd->reject_reason = reason;
812
813         cmd->buf_ptr = kmemdup(buf, ISCSI_HDR_LEN, GFP_KERNEL);
814         if (!cmd->buf_ptr) {
815                 pr_err("Unable to allocate memory for cmd->buf_ptr\n");
816                 iscsit_free_cmd(cmd, false);
817                 return -1;
818         }
819
820         spin_lock_bh(&conn->cmd_lock);
821         list_add_tail(&cmd->i_conn_node, &conn->conn_cmd_list);
822         spin_unlock_bh(&conn->cmd_lock);
823
824         cmd->i_state = ISTATE_SEND_REJECT;
825         iscsit_add_cmd_to_response_queue(cmd, conn, cmd->i_state);
826
827         return -1;
828 }
829 EXPORT_SYMBOL(iscsit_add_reject);
830
831 static int iscsit_add_reject_from_cmd(
832         struct iscsi_cmd *cmd,
833         u8 reason,
834         bool add_to_conn,
835         unsigned char *buf)
836 {
837         struct iscsi_conn *conn;
838         const bool do_put = cmd->se_cmd.se_tfo != NULL;
839
840         if (!cmd->conn) {
841                 pr_err("cmd->conn is NULL for ITT: 0x%08x\n",
842                                 cmd->init_task_tag);
843                 return -1;
844         }
845         conn = cmd->conn;
846
847         cmd->iscsi_opcode = ISCSI_OP_REJECT;
848         cmd->reject_reason = reason;
849
850         cmd->buf_ptr = kmemdup(buf, ISCSI_HDR_LEN, GFP_KERNEL);
851         if (!cmd->buf_ptr) {
852                 pr_err("Unable to allocate memory for cmd->buf_ptr\n");
853                 iscsit_free_cmd(cmd, false);
854                 return -1;
855         }
856
857         if (add_to_conn) {
858                 spin_lock_bh(&conn->cmd_lock);
859                 list_add_tail(&cmd->i_conn_node, &conn->conn_cmd_list);
860                 spin_unlock_bh(&conn->cmd_lock);
861         }
862
863         cmd->i_state = ISTATE_SEND_REJECT;
864         iscsit_add_cmd_to_response_queue(cmd, conn, cmd->i_state);
865         /*
866          * Perform the kref_put now if se_cmd has already been setup by
867          * scsit_setup_scsi_cmd()
868          */
869         if (do_put) {
870                 pr_debug("iscsi reject: calling target_put_sess_cmd >>>>>>\n");
871                 target_put_sess_cmd(&cmd->se_cmd);
872         }
873         return -1;
874 }
875
876 static int iscsit_add_reject_cmd(struct iscsi_cmd *cmd, u8 reason,
877                                  unsigned char *buf)
878 {
879         return iscsit_add_reject_from_cmd(cmd, reason, true, buf);
880 }
881
882 int iscsit_reject_cmd(struct iscsi_cmd *cmd, u8 reason, unsigned char *buf)
883 {
884         return iscsit_add_reject_from_cmd(cmd, reason, false, buf);
885 }
886 EXPORT_SYMBOL(iscsit_reject_cmd);
887
888 /*
889  * Map some portion of the allocated scatterlist to an iovec, suitable for
890  * kernel sockets to copy data in/out.
891  */
892 static int iscsit_map_iovec(
893         struct iscsi_cmd *cmd,
894         struct kvec *iov,
895         u32 data_offset,
896         u32 data_length)
897 {
898         u32 i = 0;
899         struct scatterlist *sg;
900         unsigned int page_off;
901
902         /*
903          * We know each entry in t_data_sg contains a page.
904          */
905         u32 ent = data_offset / PAGE_SIZE;
906
907         if (ent >= cmd->se_cmd.t_data_nents) {
908                 pr_err("Initial page entry out-of-bounds\n");
909                 return -1;
910         }
911
912         sg = &cmd->se_cmd.t_data_sg[ent];
913         page_off = (data_offset % PAGE_SIZE);
914
915         cmd->first_data_sg = sg;
916         cmd->first_data_sg_off = page_off;
917
918         while (data_length) {
919                 u32 cur_len = min_t(u32, data_length, sg->length - page_off);
920
921                 iov[i].iov_base = kmap(sg_page(sg)) + sg->offset + page_off;
922                 iov[i].iov_len = cur_len;
923
924                 data_length -= cur_len;
925                 page_off = 0;
926                 sg = sg_next(sg);
927                 i++;
928         }
929
930         cmd->kmapped_nents = i;
931
932         return i;
933 }
934
935 static void iscsit_unmap_iovec(struct iscsi_cmd *cmd)
936 {
937         u32 i;
938         struct scatterlist *sg;
939
940         sg = cmd->first_data_sg;
941
942         for (i = 0; i < cmd->kmapped_nents; i++)
943                 kunmap(sg_page(&sg[i]));
944 }
945
946 static void iscsit_ack_from_expstatsn(struct iscsi_conn *conn, u32 exp_statsn)
947 {
948         LIST_HEAD(ack_list);
949         struct iscsi_cmd *cmd, *cmd_p;
950
951         conn->exp_statsn = exp_statsn;
952
953         if (conn->sess->sess_ops->RDMAExtensions)
954                 return;
955
956         spin_lock_bh(&conn->cmd_lock);
957         list_for_each_entry_safe(cmd, cmd_p, &conn->conn_cmd_list, i_conn_node) {
958                 spin_lock(&cmd->istate_lock);
959                 if ((cmd->i_state == ISTATE_SENT_STATUS) &&
960                     iscsi_sna_lt(cmd->stat_sn, exp_statsn)) {
961                         cmd->i_state = ISTATE_REMOVE;
962                         spin_unlock(&cmd->istate_lock);
963                         list_move_tail(&cmd->i_conn_node, &ack_list);
964                         continue;
965                 }
966                 spin_unlock(&cmd->istate_lock);
967         }
968         spin_unlock_bh(&conn->cmd_lock);
969
970         list_for_each_entry_safe(cmd, cmd_p, &ack_list, i_conn_node) {
971                 list_del_init(&cmd->i_conn_node);
972                 iscsit_free_cmd(cmd, false);
973         }
974 }
975
976 static int iscsit_allocate_iovecs(struct iscsi_cmd *cmd)
977 {
978         u32 iov_count = max(1UL, DIV_ROUND_UP(cmd->se_cmd.data_length, PAGE_SIZE));
979
980         iov_count += ISCSI_IOV_DATA_BUFFER;
981         cmd->iov_data = kcalloc(iov_count, sizeof(*cmd->iov_data), GFP_KERNEL);
982         if (!cmd->iov_data)
983                 return -ENOMEM;
984
985         cmd->orig_iov_data_count = iov_count;
986         return 0;
987 }
988
989 int iscsit_setup_scsi_cmd(struct iscsi_conn *conn, struct iscsi_cmd *cmd,
990                           unsigned char *buf)
991 {
992         int data_direction, payload_length;
993         struct iscsi_scsi_req *hdr;
994         int iscsi_task_attr;
995         int sam_task_attr;
996
997         atomic_long_inc(&conn->sess->cmd_pdus);
998
999         hdr                     = (struct iscsi_scsi_req *) buf;
1000         payload_length          = ntoh24(hdr->dlength);
1001
1002         /* FIXME; Add checks for AdditionalHeaderSegment */
1003
1004         if (!(hdr->flags & ISCSI_FLAG_CMD_WRITE) &&
1005             !(hdr->flags & ISCSI_FLAG_CMD_FINAL)) {
1006                 pr_err("ISCSI_FLAG_CMD_WRITE & ISCSI_FLAG_CMD_FINAL"
1007                                 " not set. Bad iSCSI Initiator.\n");
1008                 return iscsit_add_reject_cmd(cmd,
1009                                              ISCSI_REASON_BOOKMARK_INVALID, buf);
1010         }
1011
1012         if (((hdr->flags & ISCSI_FLAG_CMD_READ) ||
1013              (hdr->flags & ISCSI_FLAG_CMD_WRITE)) && !hdr->data_length) {
1014                 /*
1015                  * From RFC-3720 Section 10.3.1:
1016                  *
1017                  * "Either or both of R and W MAY be 1 when either the
1018                  *  Expected Data Transfer Length and/or Bidirectional Read
1019                  *  Expected Data Transfer Length are 0"
1020                  *
1021                  * For this case, go ahead and clear the unnecssary bits
1022                  * to avoid any confusion with ->data_direction.
1023                  */
1024                 hdr->flags &= ~ISCSI_FLAG_CMD_READ;
1025                 hdr->flags &= ~ISCSI_FLAG_CMD_WRITE;
1026
1027                 pr_warn("ISCSI_FLAG_CMD_READ or ISCSI_FLAG_CMD_WRITE"
1028                         " set when Expected Data Transfer Length is 0 for"
1029                         " CDB: 0x%02x, Fixing up flags\n", hdr->cdb[0]);
1030         }
1031
1032         if (!(hdr->flags & ISCSI_FLAG_CMD_READ) &&
1033             !(hdr->flags & ISCSI_FLAG_CMD_WRITE) && (hdr->data_length != 0)) {
1034                 pr_err("ISCSI_FLAG_CMD_READ and/or ISCSI_FLAG_CMD_WRITE"
1035                         " MUST be set if Expected Data Transfer Length is not 0."
1036                         " Bad iSCSI Initiator\n");
1037                 return iscsit_add_reject_cmd(cmd,
1038                                              ISCSI_REASON_BOOKMARK_INVALID, buf);
1039         }
1040
1041         if ((hdr->flags & ISCSI_FLAG_CMD_READ) &&
1042             (hdr->flags & ISCSI_FLAG_CMD_WRITE)) {
1043                 pr_err("Bidirectional operations not supported!\n");
1044                 return iscsit_add_reject_cmd(cmd,
1045                                              ISCSI_REASON_BOOKMARK_INVALID, buf);
1046         }
1047
1048         if (hdr->opcode & ISCSI_OP_IMMEDIATE) {
1049                 pr_err("Illegally set Immediate Bit in iSCSI Initiator"
1050                                 " Scsi Command PDU.\n");
1051                 return iscsit_add_reject_cmd(cmd,
1052                                              ISCSI_REASON_BOOKMARK_INVALID, buf);
1053         }
1054
1055         if (payload_length && !conn->sess->sess_ops->ImmediateData) {
1056                 pr_err("ImmediateData=No but DataSegmentLength=%u,"
1057                         " protocol error.\n", payload_length);
1058                 return iscsit_add_reject_cmd(cmd,
1059                                              ISCSI_REASON_PROTOCOL_ERROR, buf);
1060         }
1061
1062         if ((be32_to_cpu(hdr->data_length) == payload_length) &&
1063             (!(hdr->flags & ISCSI_FLAG_CMD_FINAL))) {
1064                 pr_err("Expected Data Transfer Length and Length of"
1065                         " Immediate Data are the same, but ISCSI_FLAG_CMD_FINAL"
1066                         " bit is not set protocol error\n");
1067                 return iscsit_add_reject_cmd(cmd,
1068                                              ISCSI_REASON_PROTOCOL_ERROR, buf);
1069         }
1070
1071         if (payload_length > be32_to_cpu(hdr->data_length)) {
1072                 pr_err("DataSegmentLength: %u is greater than"
1073                         " EDTL: %u, protocol error.\n", payload_length,
1074                                 hdr->data_length);
1075                 return iscsit_add_reject_cmd(cmd,
1076                                              ISCSI_REASON_PROTOCOL_ERROR, buf);
1077         }
1078
1079         if (payload_length > conn->conn_ops->MaxXmitDataSegmentLength) {
1080                 pr_err("DataSegmentLength: %u is greater than"
1081                         " MaxXmitDataSegmentLength: %u, protocol error.\n",
1082                         payload_length, conn->conn_ops->MaxXmitDataSegmentLength);
1083                 return iscsit_add_reject_cmd(cmd,
1084                                              ISCSI_REASON_PROTOCOL_ERROR, buf);
1085         }
1086
1087         if (payload_length > conn->sess->sess_ops->FirstBurstLength) {
1088                 pr_err("DataSegmentLength: %u is greater than"
1089                         " FirstBurstLength: %u, protocol error.\n",
1090                         payload_length, conn->sess->sess_ops->FirstBurstLength);
1091                 return iscsit_add_reject_cmd(cmd,
1092                                              ISCSI_REASON_BOOKMARK_INVALID, buf);
1093         }
1094
1095         data_direction = (hdr->flags & ISCSI_FLAG_CMD_WRITE) ? DMA_TO_DEVICE :
1096                          (hdr->flags & ISCSI_FLAG_CMD_READ) ? DMA_FROM_DEVICE :
1097                           DMA_NONE;
1098
1099         cmd->data_direction = data_direction;
1100         iscsi_task_attr = hdr->flags & ISCSI_FLAG_CMD_ATTR_MASK;
1101         /*
1102          * Figure out the SAM Task Attribute for the incoming SCSI CDB
1103          */
1104         if ((iscsi_task_attr == ISCSI_ATTR_UNTAGGED) ||
1105             (iscsi_task_attr == ISCSI_ATTR_SIMPLE))
1106                 sam_task_attr = TCM_SIMPLE_TAG;
1107         else if (iscsi_task_attr == ISCSI_ATTR_ORDERED)
1108                 sam_task_attr = TCM_ORDERED_TAG;
1109         else if (iscsi_task_attr == ISCSI_ATTR_HEAD_OF_QUEUE)
1110                 sam_task_attr = TCM_HEAD_TAG;
1111         else if (iscsi_task_attr == ISCSI_ATTR_ACA)
1112                 sam_task_attr = TCM_ACA_TAG;
1113         else {
1114                 pr_debug("Unknown iSCSI Task Attribute: 0x%02x, using"
1115                         " TCM_SIMPLE_TAG\n", iscsi_task_attr);
1116                 sam_task_attr = TCM_SIMPLE_TAG;
1117         }
1118
1119         cmd->iscsi_opcode       = ISCSI_OP_SCSI_CMD;
1120         cmd->i_state            = ISTATE_NEW_CMD;
1121         cmd->immediate_cmd      = ((hdr->opcode & ISCSI_OP_IMMEDIATE) ? 1 : 0);
1122         cmd->immediate_data     = (payload_length) ? 1 : 0;
1123         cmd->unsolicited_data   = ((!(hdr->flags & ISCSI_FLAG_CMD_FINAL) &&
1124                                      (hdr->flags & ISCSI_FLAG_CMD_WRITE)) ? 1 : 0);
1125         if (cmd->unsolicited_data)
1126                 cmd->cmd_flags |= ICF_NON_IMMEDIATE_UNSOLICITED_DATA;
1127
1128         conn->sess->init_task_tag = cmd->init_task_tag = hdr->itt;
1129         if (hdr->flags & ISCSI_FLAG_CMD_READ)
1130                 cmd->targ_xfer_tag = session_get_next_ttt(conn->sess);
1131         else
1132                 cmd->targ_xfer_tag = 0xFFFFFFFF;
1133         cmd->cmd_sn             = be32_to_cpu(hdr->cmdsn);
1134         cmd->exp_stat_sn        = be32_to_cpu(hdr->exp_statsn);
1135         cmd->first_burst_len    = payload_length;
1136
1137         if (!conn->sess->sess_ops->RDMAExtensions &&
1138              cmd->data_direction == DMA_FROM_DEVICE) {
1139                 struct iscsi_datain_req *dr;
1140
1141                 dr = iscsit_allocate_datain_req();
1142                 if (!dr)
1143                         return iscsit_add_reject_cmd(cmd,
1144                                         ISCSI_REASON_BOOKMARK_NO_RESOURCES, buf);
1145
1146                 iscsit_attach_datain_req(cmd, dr);
1147         }
1148
1149         /*
1150          * Initialize struct se_cmd descriptor from target_core_mod infrastructure
1151          */
1152         transport_init_se_cmd(&cmd->se_cmd, &iscsi_ops,
1153                         conn->sess->se_sess, be32_to_cpu(hdr->data_length),
1154                         cmd->data_direction, sam_task_attr,
1155                         cmd->sense_buffer + 2);
1156
1157         pr_debug("Got SCSI Command, ITT: 0x%08x, CmdSN: 0x%08x,"
1158                 " ExpXferLen: %u, Length: %u, CID: %hu\n", hdr->itt,
1159                 hdr->cmdsn, be32_to_cpu(hdr->data_length), payload_length,
1160                 conn->cid);
1161
1162         target_get_sess_cmd(&cmd->se_cmd, true);
1163
1164         cmd->sense_reason = transport_lookup_cmd_lun(&cmd->se_cmd,
1165                                                      scsilun_to_int(&hdr->lun));
1166         if (cmd->sense_reason)
1167                 goto attach_cmd;
1168
1169         /* only used for printks or comparing with ->ref_task_tag */
1170         cmd->se_cmd.tag = (__force u32)cmd->init_task_tag;
1171         cmd->sense_reason = target_setup_cmd_from_cdb(&cmd->se_cmd, hdr->cdb);
1172         if (cmd->sense_reason) {
1173                 if (cmd->sense_reason == TCM_OUT_OF_RESOURCES) {
1174                         return iscsit_add_reject_cmd(cmd,
1175                                         ISCSI_REASON_BOOKMARK_NO_RESOURCES, buf);
1176                 }
1177
1178                 goto attach_cmd;
1179         }
1180
1181         if (iscsit_build_pdu_and_seq_lists(cmd, payload_length) < 0) {
1182                 return iscsit_add_reject_cmd(cmd,
1183                                 ISCSI_REASON_BOOKMARK_NO_RESOURCES, buf);
1184         }
1185
1186 attach_cmd:
1187         spin_lock_bh(&conn->cmd_lock);
1188         list_add_tail(&cmd->i_conn_node, &conn->conn_cmd_list);
1189         spin_unlock_bh(&conn->cmd_lock);
1190         /*
1191          * Check if we need to delay processing because of ALUA
1192          * Active/NonOptimized primary access state..
1193          */
1194         core_alua_check_nonop_delay(&cmd->se_cmd);
1195
1196         return 0;
1197 }
1198 EXPORT_SYMBOL(iscsit_setup_scsi_cmd);
1199
1200 void iscsit_set_unsoliticed_dataout(struct iscsi_cmd *cmd)
1201 {
1202         iscsit_set_dataout_sequence_values(cmd);
1203
1204         spin_lock_bh(&cmd->dataout_timeout_lock);
1205         iscsit_start_dataout_timer(cmd, cmd->conn);
1206         spin_unlock_bh(&cmd->dataout_timeout_lock);
1207 }
1208 EXPORT_SYMBOL(iscsit_set_unsoliticed_dataout);
1209
1210 int iscsit_process_scsi_cmd(struct iscsi_conn *conn, struct iscsi_cmd *cmd,
1211                             struct iscsi_scsi_req *hdr)
1212 {
1213         int cmdsn_ret = 0;
1214         /*
1215          * Check the CmdSN against ExpCmdSN/MaxCmdSN here if
1216          * the Immediate Bit is not set, and no Immediate
1217          * Data is attached.
1218          *
1219          * A PDU/CmdSN carrying Immediate Data can only
1220          * be processed after the DataCRC has passed.
1221          * If the DataCRC fails, the CmdSN MUST NOT
1222          * be acknowledged. (See below)
1223          */
1224         if (!cmd->immediate_data) {
1225                 cmdsn_ret = iscsit_sequence_cmd(conn, cmd,
1226                                         (unsigned char *)hdr, hdr->cmdsn);
1227                 if (cmdsn_ret == CMDSN_ERROR_CANNOT_RECOVER)
1228                         return -1;
1229                 else if (cmdsn_ret == CMDSN_LOWER_THAN_EXP) {
1230                         target_put_sess_cmd(&cmd->se_cmd);
1231                         return 0;
1232                 }
1233         }
1234
1235         iscsit_ack_from_expstatsn(conn, be32_to_cpu(hdr->exp_statsn));
1236
1237         /*
1238          * If no Immediate Data is attached, it's OK to return now.
1239          */
1240         if (!cmd->immediate_data) {
1241                 if (!cmd->sense_reason && cmd->unsolicited_data)
1242                         iscsit_set_unsoliticed_dataout(cmd);
1243                 if (!cmd->sense_reason)
1244                         return 0;
1245
1246                 target_put_sess_cmd(&cmd->se_cmd);
1247                 return 0;
1248         }
1249
1250         /*
1251          * Early CHECK_CONDITIONs with ImmediateData never make it to command
1252          * execution.  These exceptions are processed in CmdSN order using
1253          * iscsit_check_received_cmdsn() in iscsit_get_immediate_data() below.
1254          */
1255         if (cmd->sense_reason)
1256                 return 1;
1257         /*
1258          * Call directly into transport_generic_new_cmd() to perform
1259          * the backend memory allocation.
1260          */
1261         cmd->sense_reason = transport_generic_new_cmd(&cmd->se_cmd);
1262         if (cmd->sense_reason)
1263                 return 1;
1264
1265         return 0;
1266 }
1267 EXPORT_SYMBOL(iscsit_process_scsi_cmd);
1268
1269 static int
1270 iscsit_get_immediate_data(struct iscsi_cmd *cmd, struct iscsi_scsi_req *hdr,
1271                           bool dump_payload)
1272 {
1273         int cmdsn_ret = 0, immed_ret = IMMEDIATE_DATA_NORMAL_OPERATION;
1274         /*
1275          * Special case for Unsupported SAM WRITE Opcodes and ImmediateData=Yes.
1276          */
1277         if (dump_payload)
1278                 goto after_immediate_data;
1279         /*
1280          * Check for underflow case where both EDTL and immediate data payload
1281          * exceeds what is presented by CDB's TRANSFER LENGTH, and what has
1282          * already been set in target_cmd_size_check() as se_cmd->data_length.
1283          *
1284          * For this special case, fail the command and dump the immediate data
1285          * payload.
1286          */
1287         if (cmd->first_burst_len > cmd->se_cmd.data_length) {
1288                 cmd->sense_reason = TCM_INVALID_CDB_FIELD;
1289                 goto after_immediate_data;
1290         }
1291
1292         immed_ret = iscsit_handle_immediate_data(cmd, hdr,
1293                                         cmd->first_burst_len);
1294 after_immediate_data:
1295         if (immed_ret == IMMEDIATE_DATA_NORMAL_OPERATION) {
1296                 /*
1297                  * A PDU/CmdSN carrying Immediate Data passed
1298                  * DataCRC, check against ExpCmdSN/MaxCmdSN if
1299                  * Immediate Bit is not set.
1300                  */
1301                 cmdsn_ret = iscsit_sequence_cmd(cmd->conn, cmd,
1302                                         (unsigned char *)hdr, hdr->cmdsn);
1303                 if (cmdsn_ret == CMDSN_ERROR_CANNOT_RECOVER)
1304                         return -1;
1305
1306                 if (cmd->sense_reason || cmdsn_ret == CMDSN_LOWER_THAN_EXP) {
1307                         int rc;
1308
1309                         rc = iscsit_dump_data_payload(cmd->conn,
1310                                                       cmd->first_burst_len, 1);
1311                         target_put_sess_cmd(&cmd->se_cmd);
1312                         return rc;
1313                 } else if (cmd->unsolicited_data)
1314                         iscsit_set_unsoliticed_dataout(cmd);
1315
1316         } else if (immed_ret == IMMEDIATE_DATA_ERL1_CRC_FAILURE) {
1317                 /*
1318                  * Immediate Data failed DataCRC and ERL>=1,
1319                  * silently drop this PDU and let the initiator
1320                  * plug the CmdSN gap.
1321                  *
1322                  * FIXME: Send Unsolicited NOPIN with reserved
1323                  * TTT here to help the initiator figure out
1324                  * the missing CmdSN, although they should be
1325                  * intelligent enough to determine the missing
1326                  * CmdSN and issue a retry to plug the sequence.
1327                  */
1328                 cmd->i_state = ISTATE_REMOVE;
1329                 iscsit_add_cmd_to_immediate_queue(cmd, cmd->conn, cmd->i_state);
1330         } else /* immed_ret == IMMEDIATE_DATA_CANNOT_RECOVER */
1331                 return -1;
1332
1333         return 0;
1334 }
1335
1336 static int
1337 iscsit_handle_scsi_cmd(struct iscsi_conn *conn, struct iscsi_cmd *cmd,
1338                            unsigned char *buf)
1339 {
1340         struct iscsi_scsi_req *hdr = (struct iscsi_scsi_req *)buf;
1341         int rc, immed_data;
1342         bool dump_payload = false;
1343
1344         rc = iscsit_setup_scsi_cmd(conn, cmd, buf);
1345         if (rc < 0)
1346                 return 0;
1347         /*
1348          * Allocation iovecs needed for struct socket operations for
1349          * traditional iSCSI block I/O.
1350          */
1351         if (iscsit_allocate_iovecs(cmd) < 0) {
1352                 return iscsit_reject_cmd(cmd,
1353                                 ISCSI_REASON_BOOKMARK_NO_RESOURCES, buf);
1354         }
1355         immed_data = cmd->immediate_data;
1356
1357         rc = iscsit_process_scsi_cmd(conn, cmd, hdr);
1358         if (rc < 0)
1359                 return rc;
1360         else if (rc > 0)
1361                 dump_payload = true;
1362
1363         if (!immed_data)
1364                 return 0;
1365
1366         return iscsit_get_immediate_data(cmd, hdr, dump_payload);
1367 }
1368
1369 static u32 iscsit_do_crypto_hash_sg(
1370         struct ahash_request *hash,
1371         struct iscsi_cmd *cmd,
1372         u32 data_offset,
1373         u32 data_length,
1374         u32 padding,
1375         u8 *pad_bytes)
1376 {
1377         u32 data_crc;
1378         struct scatterlist *sg;
1379         unsigned int page_off;
1380
1381         crypto_ahash_init(hash);
1382
1383         sg = cmd->first_data_sg;
1384         page_off = cmd->first_data_sg_off;
1385
1386         while (data_length) {
1387                 u32 cur_len = min_t(u32, data_length, (sg->length - page_off));
1388
1389                 ahash_request_set_crypt(hash, sg, NULL, cur_len);
1390                 crypto_ahash_update(hash);
1391
1392                 data_length -= cur_len;
1393                 page_off = 0;
1394                 /* iscsit_map_iovec has already checked for invalid sg pointers */
1395                 sg = sg_next(sg);
1396         }
1397
1398         if (padding) {
1399                 struct scatterlist pad_sg;
1400
1401                 sg_init_one(&pad_sg, pad_bytes, padding);
1402                 ahash_request_set_crypt(hash, &pad_sg, (u8 *)&data_crc,
1403                                         padding);
1404                 crypto_ahash_finup(hash);
1405         } else {
1406                 ahash_request_set_crypt(hash, NULL, (u8 *)&data_crc, 0);
1407                 crypto_ahash_final(hash);
1408         }
1409
1410         return data_crc;
1411 }
1412
1413 static void iscsit_do_crypto_hash_buf(struct ahash_request *hash,
1414         const void *buf, u32 payload_length, u32 padding,
1415         const void *pad_bytes, void *data_crc)
1416 {
1417         struct scatterlist sg[2];
1418
1419         sg_init_table(sg, ARRAY_SIZE(sg));
1420         sg_set_buf(sg, buf, payload_length);
1421         sg_set_buf(sg + 1, pad_bytes, padding);
1422
1423         ahash_request_set_crypt(hash, sg, data_crc, payload_length + padding);
1424
1425         crypto_ahash_digest(hash);
1426 }
1427
1428 int
1429 __iscsit_check_dataout_hdr(struct iscsi_conn *conn, void *buf,
1430                            struct iscsi_cmd *cmd, u32 payload_length,
1431                            bool *success)
1432 {
1433         struct iscsi_data *hdr = buf;
1434         struct se_cmd *se_cmd;
1435         int rc;
1436
1437         /* iSCSI write */
1438         atomic_long_add(payload_length, &conn->sess->rx_data_octets);
1439
1440         pr_debug("Got DataOut ITT: 0x%08x, TTT: 0x%08x,"
1441                 " DataSN: 0x%08x, Offset: %u, Length: %u, CID: %hu\n",
1442                 hdr->itt, hdr->ttt, hdr->datasn, ntohl(hdr->offset),
1443                 payload_length, conn->cid);
1444
1445         if (cmd->cmd_flags & ICF_GOT_LAST_DATAOUT) {
1446                 pr_err("Command ITT: 0x%08x received DataOUT after"
1447                         " last DataOUT received, dumping payload\n",
1448                         cmd->init_task_tag);
1449                 return iscsit_dump_data_payload(conn, payload_length, 1);
1450         }
1451
1452         if (cmd->data_direction != DMA_TO_DEVICE) {
1453                 pr_err("Command ITT: 0x%08x received DataOUT for a"
1454                         " NON-WRITE command.\n", cmd->init_task_tag);
1455                 return iscsit_dump_data_payload(conn, payload_length, 1);
1456         }
1457         se_cmd = &cmd->se_cmd;
1458         iscsit_mod_dataout_timer(cmd);
1459
1460         if ((be32_to_cpu(hdr->offset) + payload_length) > cmd->se_cmd.data_length) {
1461                 pr_err("DataOut Offset: %u, Length %u greater than iSCSI Command EDTL %u, protocol error.\n",
1462                        be32_to_cpu(hdr->offset), payload_length,
1463                        cmd->se_cmd.data_length);
1464                 return iscsit_reject_cmd(cmd, ISCSI_REASON_BOOKMARK_INVALID, buf);
1465         }
1466
1467         if (cmd->unsolicited_data) {
1468                 int dump_unsolicited_data = 0;
1469
1470                 if (conn->sess->sess_ops->InitialR2T) {
1471                         pr_err("Received unexpected unsolicited data"
1472                                 " while InitialR2T=Yes, protocol error.\n");
1473                         transport_send_check_condition_and_sense(&cmd->se_cmd,
1474                                         TCM_UNEXPECTED_UNSOLICITED_DATA, 0);
1475                         return -1;
1476                 }
1477                 /*
1478                  * Special case for dealing with Unsolicited DataOUT
1479                  * and Unsupported SAM WRITE Opcodes and SE resource allocation
1480                  * failures;
1481                  */
1482
1483                 /* Something's amiss if we're not in WRITE_PENDING state... */
1484                 WARN_ON(se_cmd->t_state != TRANSPORT_WRITE_PENDING);
1485                 if (!(se_cmd->se_cmd_flags & SCF_SUPPORTED_SAM_OPCODE))
1486                         dump_unsolicited_data = 1;
1487
1488                 if (dump_unsolicited_data) {
1489                         /*
1490                          * Check if a delayed TASK_ABORTED status needs to
1491                          * be sent now if the ISCSI_FLAG_CMD_FINAL has been
1492                          * received with the unsolicited data out.
1493                          */
1494                         if (hdr->flags & ISCSI_FLAG_CMD_FINAL)
1495                                 iscsit_stop_dataout_timer(cmd);
1496
1497                         transport_check_aborted_status(se_cmd,
1498                                         (hdr->flags & ISCSI_FLAG_CMD_FINAL));
1499                         return iscsit_dump_data_payload(conn, payload_length, 1);
1500                 }
1501         } else {
1502                 /*
1503                  * For the normal solicited data path:
1504                  *
1505                  * Check for a delayed TASK_ABORTED status and dump any
1506                  * incoming data out payload if one exists.  Also, when the
1507                  * ISCSI_FLAG_CMD_FINAL is set to denote the end of the current
1508                  * data out sequence, we decrement outstanding_r2ts.  Once
1509                  * outstanding_r2ts reaches zero, go ahead and send the delayed
1510                  * TASK_ABORTED status.
1511                  */
1512                 if (se_cmd->transport_state & CMD_T_ABORTED) {
1513                         if (hdr->flags & ISCSI_FLAG_CMD_FINAL)
1514                                 if (--cmd->outstanding_r2ts < 1) {
1515                                         iscsit_stop_dataout_timer(cmd);
1516                                         transport_check_aborted_status(
1517                                                         se_cmd, 1);
1518                                 }
1519
1520                         return iscsit_dump_data_payload(conn, payload_length, 1);
1521                 }
1522         }
1523         /*
1524          * Perform DataSN, DataSequenceInOrder, DataPDUInOrder, and
1525          * within-command recovery checks before receiving the payload.
1526          */
1527         rc = iscsit_check_pre_dataout(cmd, buf);
1528         if (rc == DATAOUT_WITHIN_COMMAND_RECOVERY)
1529                 return 0;
1530         else if (rc == DATAOUT_CANNOT_RECOVER)
1531                 return -1;
1532         *success = true;
1533         return 0;
1534 }
1535 EXPORT_SYMBOL(__iscsit_check_dataout_hdr);
1536
1537 int
1538 iscsit_check_dataout_hdr(struct iscsi_conn *conn, void *buf,
1539                          struct iscsi_cmd **out_cmd)
1540 {
1541         struct iscsi_data *hdr = buf;
1542         struct iscsi_cmd *cmd;
1543         u32 payload_length = ntoh24(hdr->dlength);
1544         int rc;
1545         bool success = false;
1546
1547         if (!payload_length) {
1548                 pr_warn_ratelimited("DataOUT payload is ZERO, ignoring.\n");
1549                 return 0;
1550         }
1551
1552         if (payload_length > conn->conn_ops->MaxXmitDataSegmentLength) {
1553                 pr_err_ratelimited("DataSegmentLength: %u is greater than"
1554                         " MaxXmitDataSegmentLength: %u\n", payload_length,
1555                         conn->conn_ops->MaxXmitDataSegmentLength);
1556                 return iscsit_add_reject(conn, ISCSI_REASON_PROTOCOL_ERROR, buf);
1557         }
1558
1559         cmd = iscsit_find_cmd_from_itt_or_dump(conn, hdr->itt, payload_length);
1560         if (!cmd)
1561                 return 0;
1562
1563         rc = __iscsit_check_dataout_hdr(conn, buf, cmd, payload_length, &success);
1564
1565         if (success)
1566                 *out_cmd = cmd;
1567
1568         return rc;
1569 }
1570 EXPORT_SYMBOL(iscsit_check_dataout_hdr);
1571
1572 static int
1573 iscsit_get_dataout(struct iscsi_conn *conn, struct iscsi_cmd *cmd,
1574                    struct iscsi_data *hdr)
1575 {
1576         struct kvec *iov;
1577         u32 checksum, iov_count = 0, padding = 0, rx_got = 0, rx_size = 0;
1578         u32 payload_length = ntoh24(hdr->dlength);
1579         int iov_ret, data_crc_failed = 0;
1580
1581         rx_size += payload_length;
1582         iov = &cmd->iov_data[0];
1583
1584         iov_ret = iscsit_map_iovec(cmd, iov, be32_to_cpu(hdr->offset),
1585                                    payload_length);
1586         if (iov_ret < 0)
1587                 return -1;
1588
1589         iov_count += iov_ret;
1590
1591         padding = ((-payload_length) & 3);
1592         if (padding != 0) {
1593                 iov[iov_count].iov_base = cmd->pad_bytes;
1594                 iov[iov_count++].iov_len = padding;
1595                 rx_size += padding;
1596                 pr_debug("Receiving %u padding bytes.\n", padding);
1597         }
1598
1599         if (conn->conn_ops->DataDigest) {
1600                 iov[iov_count].iov_base = &checksum;
1601                 iov[iov_count++].iov_len = ISCSI_CRC_LEN;
1602                 rx_size += ISCSI_CRC_LEN;
1603         }
1604
1605         rx_got = rx_data(conn, &cmd->iov_data[0], iov_count, rx_size);
1606
1607         iscsit_unmap_iovec(cmd);
1608
1609         if (rx_got != rx_size)
1610                 return -1;
1611
1612         if (conn->conn_ops->DataDigest) {
1613                 u32 data_crc;
1614
1615                 data_crc = iscsit_do_crypto_hash_sg(conn->conn_rx_hash, cmd,
1616                                                     be32_to_cpu(hdr->offset),
1617                                                     payload_length, padding,
1618                                                     cmd->pad_bytes);
1619
1620                 if (checksum != data_crc) {
1621                         pr_err("ITT: 0x%08x, Offset: %u, Length: %u,"
1622                                 " DataSN: 0x%08x, CRC32C DataDigest 0x%08x"
1623                                 " does not match computed 0x%08x\n",
1624                                 hdr->itt, hdr->offset, payload_length,
1625                                 hdr->datasn, checksum, data_crc);
1626                         data_crc_failed = 1;
1627                 } else {
1628                         pr_debug("Got CRC32C DataDigest 0x%08x for"
1629                                 " %u bytes of Data Out\n", checksum,
1630                                 payload_length);
1631                 }
1632         }
1633
1634         return data_crc_failed;
1635 }
1636
1637 int
1638 iscsit_check_dataout_payload(struct iscsi_cmd *cmd, struct iscsi_data *hdr,
1639                              bool data_crc_failed)
1640 {
1641         struct iscsi_conn *conn = cmd->conn;
1642         int rc, ooo_cmdsn;
1643         /*
1644          * Increment post receive data and CRC values or perform
1645          * within-command recovery.
1646          */
1647         rc = iscsit_check_post_dataout(cmd, (unsigned char *)hdr, data_crc_failed);
1648         if ((rc == DATAOUT_NORMAL) || (rc == DATAOUT_WITHIN_COMMAND_RECOVERY))
1649                 return 0;
1650         else if (rc == DATAOUT_SEND_R2T) {
1651                 iscsit_set_dataout_sequence_values(cmd);
1652                 conn->conn_transport->iscsit_get_dataout(conn, cmd, false);
1653         } else if (rc == DATAOUT_SEND_TO_TRANSPORT) {
1654                 /*
1655                  * Handle extra special case for out of order
1656                  * Unsolicited Data Out.
1657                  */
1658                 spin_lock_bh(&cmd->istate_lock);
1659                 ooo_cmdsn = (cmd->cmd_flags & ICF_OOO_CMDSN);
1660                 cmd->cmd_flags |= ICF_GOT_LAST_DATAOUT;
1661                 cmd->i_state = ISTATE_RECEIVED_LAST_DATAOUT;
1662                 spin_unlock_bh(&cmd->istate_lock);
1663
1664                 iscsit_stop_dataout_timer(cmd);
1665                 if (ooo_cmdsn)
1666                         return 0;
1667                 target_execute_cmd(&cmd->se_cmd);
1668                 return 0;
1669         } else /* DATAOUT_CANNOT_RECOVER */
1670                 return -1;
1671
1672         return 0;
1673 }
1674 EXPORT_SYMBOL(iscsit_check_dataout_payload);
1675
1676 static int iscsit_handle_data_out(struct iscsi_conn *conn, unsigned char *buf)
1677 {
1678         struct iscsi_cmd *cmd = NULL;
1679         struct iscsi_data *hdr = (struct iscsi_data *)buf;
1680         int rc;
1681         bool data_crc_failed = false;
1682
1683         rc = iscsit_check_dataout_hdr(conn, buf, &cmd);
1684         if (rc < 0)
1685                 return 0;
1686         else if (!cmd)
1687                 return 0;
1688
1689         rc = iscsit_get_dataout(conn, cmd, hdr);
1690         if (rc < 0)
1691                 return rc;
1692         else if (rc > 0)
1693                 data_crc_failed = true;
1694
1695         return iscsit_check_dataout_payload(cmd, hdr, data_crc_failed);
1696 }
1697
1698 int iscsit_setup_nop_out(struct iscsi_conn *conn, struct iscsi_cmd *cmd,
1699                          struct iscsi_nopout *hdr)
1700 {
1701         u32 payload_length = ntoh24(hdr->dlength);
1702
1703         if (!(hdr->flags & ISCSI_FLAG_CMD_FINAL)) {
1704                 pr_err("NopOUT Flag's, Left Most Bit not set, protocol error.\n");
1705                 if (!cmd)
1706                         return iscsit_add_reject(conn, ISCSI_REASON_PROTOCOL_ERROR,
1707                                                  (unsigned char *)hdr);
1708                 
1709                 return iscsit_reject_cmd(cmd, ISCSI_REASON_PROTOCOL_ERROR,
1710                                          (unsigned char *)hdr);
1711         }
1712
1713         if (hdr->itt == RESERVED_ITT && !(hdr->opcode & ISCSI_OP_IMMEDIATE)) {
1714                 pr_err("NOPOUT ITT is reserved, but Immediate Bit is"
1715                         " not set, protocol error.\n");
1716                 if (!cmd)
1717                         return iscsit_add_reject(conn, ISCSI_REASON_PROTOCOL_ERROR,
1718                                                  (unsigned char *)hdr);
1719
1720                 return iscsit_reject_cmd(cmd, ISCSI_REASON_PROTOCOL_ERROR,
1721                                          (unsigned char *)hdr);
1722         }
1723
1724         if (payload_length > conn->conn_ops->MaxXmitDataSegmentLength) {
1725                 pr_err("NOPOUT Ping Data DataSegmentLength: %u is"
1726                         " greater than MaxXmitDataSegmentLength: %u, protocol"
1727                         " error.\n", payload_length,
1728                         conn->conn_ops->MaxXmitDataSegmentLength);
1729                 if (!cmd)
1730                         return iscsit_add_reject(conn, ISCSI_REASON_PROTOCOL_ERROR,
1731                                                  (unsigned char *)hdr);
1732
1733                 return iscsit_reject_cmd(cmd, ISCSI_REASON_PROTOCOL_ERROR,
1734                                          (unsigned char *)hdr);
1735         }
1736
1737         pr_debug("Got NOPOUT Ping %s ITT: 0x%08x, TTT: 0x%08x,"
1738                 " CmdSN: 0x%08x, ExpStatSN: 0x%08x, Length: %u\n",
1739                 hdr->itt == RESERVED_ITT ? "Response" : "Request",
1740                 hdr->itt, hdr->ttt, hdr->cmdsn, hdr->exp_statsn,
1741                 payload_length);
1742         /*
1743          * This is not a response to a Unsolicited NopIN, which means
1744          * it can either be a NOPOUT ping request (with a valid ITT),
1745          * or a NOPOUT not requesting a NOPIN (with a reserved ITT).
1746          * Either way, make sure we allocate an struct iscsi_cmd, as both
1747          * can contain ping data.
1748          */
1749         if (hdr->ttt == cpu_to_be32(0xFFFFFFFF)) {
1750                 cmd->iscsi_opcode       = ISCSI_OP_NOOP_OUT;
1751                 cmd->i_state            = ISTATE_SEND_NOPIN;
1752                 cmd->immediate_cmd      = ((hdr->opcode & ISCSI_OP_IMMEDIATE) ?
1753                                                 1 : 0);
1754                 conn->sess->init_task_tag = cmd->init_task_tag = hdr->itt;
1755                 cmd->targ_xfer_tag      = 0xFFFFFFFF;
1756                 cmd->cmd_sn             = be32_to_cpu(hdr->cmdsn);
1757                 cmd->exp_stat_sn        = be32_to_cpu(hdr->exp_statsn);
1758                 cmd->data_direction     = DMA_NONE;
1759         }
1760
1761         return 0;
1762 }
1763 EXPORT_SYMBOL(iscsit_setup_nop_out);
1764
1765 int iscsit_process_nop_out(struct iscsi_conn *conn, struct iscsi_cmd *cmd,
1766                            struct iscsi_nopout *hdr)
1767 {
1768         struct iscsi_cmd *cmd_p = NULL;
1769         int cmdsn_ret = 0;
1770         /*
1771          * Initiator is expecting a NopIN ping reply..
1772          */
1773         if (hdr->itt != RESERVED_ITT) {
1774                 if (!cmd)
1775                         return iscsit_add_reject(conn, ISCSI_REASON_PROTOCOL_ERROR,
1776                                                 (unsigned char *)hdr);
1777
1778                 spin_lock_bh(&conn->cmd_lock);
1779                 list_add_tail(&cmd->i_conn_node, &conn->conn_cmd_list);
1780                 spin_unlock_bh(&conn->cmd_lock);
1781
1782                 iscsit_ack_from_expstatsn(conn, be32_to_cpu(hdr->exp_statsn));
1783
1784                 if (hdr->opcode & ISCSI_OP_IMMEDIATE) {
1785                         iscsit_add_cmd_to_response_queue(cmd, conn,
1786                                                          cmd->i_state);
1787                         return 0;
1788                 }
1789
1790                 cmdsn_ret = iscsit_sequence_cmd(conn, cmd,
1791                                 (unsigned char *)hdr, hdr->cmdsn);
1792                 if (cmdsn_ret == CMDSN_LOWER_THAN_EXP)
1793                         return 0;
1794                 if (cmdsn_ret == CMDSN_ERROR_CANNOT_RECOVER)
1795                         return -1;
1796
1797                 return 0;
1798         }
1799         /*
1800          * This was a response to a unsolicited NOPIN ping.
1801          */
1802         if (hdr->ttt != cpu_to_be32(0xFFFFFFFF)) {
1803                 cmd_p = iscsit_find_cmd_from_ttt(conn, be32_to_cpu(hdr->ttt));
1804                 if (!cmd_p)
1805                         return -EINVAL;
1806
1807                 iscsit_stop_nopin_response_timer(conn);
1808
1809                 cmd_p->i_state = ISTATE_REMOVE;
1810                 iscsit_add_cmd_to_immediate_queue(cmd_p, conn, cmd_p->i_state);
1811
1812                 iscsit_start_nopin_timer(conn);
1813                 return 0;
1814         }
1815         /*
1816          * Otherwise, initiator is not expecting a NOPIN is response.
1817          * Just ignore for now.
1818          */
1819
1820         if (cmd)
1821                 iscsit_free_cmd(cmd, false);
1822
1823         return 0;
1824 }
1825 EXPORT_SYMBOL(iscsit_process_nop_out);
1826
1827 static int iscsit_handle_nop_out(struct iscsi_conn *conn, struct iscsi_cmd *cmd,
1828                                  unsigned char *buf)
1829 {
1830         unsigned char *ping_data = NULL;
1831         struct iscsi_nopout *hdr = (struct iscsi_nopout *)buf;
1832         struct kvec *iov = NULL;
1833         u32 payload_length = ntoh24(hdr->dlength);
1834         int ret;
1835
1836         ret = iscsit_setup_nop_out(conn, cmd, hdr);
1837         if (ret < 0)
1838                 return 0;
1839         /*
1840          * Handle NOP-OUT payload for traditional iSCSI sockets
1841          */
1842         if (payload_length && hdr->ttt == cpu_to_be32(0xFFFFFFFF)) {
1843                 u32 checksum, data_crc, padding = 0;
1844                 int niov = 0, rx_got, rx_size = payload_length;
1845
1846                 ping_data = kzalloc(payload_length + 1, GFP_KERNEL);
1847                 if (!ping_data) {
1848                         ret = -1;
1849                         goto out;
1850                 }
1851
1852                 iov = &cmd->iov_misc[0];
1853                 iov[niov].iov_base      = ping_data;
1854                 iov[niov++].iov_len     = payload_length;
1855
1856                 padding = ((-payload_length) & 3);
1857                 if (padding != 0) {
1858                         pr_debug("Receiving %u additional bytes"
1859                                 " for padding.\n", padding);
1860                         iov[niov].iov_base      = &cmd->pad_bytes;
1861                         iov[niov++].iov_len     = padding;
1862                         rx_size += padding;
1863                 }
1864                 if (conn->conn_ops->DataDigest) {
1865                         iov[niov].iov_base      = &checksum;
1866                         iov[niov++].iov_len     = ISCSI_CRC_LEN;
1867                         rx_size += ISCSI_CRC_LEN;
1868                 }
1869
1870                 rx_got = rx_data(conn, &cmd->iov_misc[0], niov, rx_size);
1871                 if (rx_got != rx_size) {
1872                         ret = -1;
1873                         goto out;
1874                 }
1875
1876                 if (conn->conn_ops->DataDigest) {
1877                         iscsit_do_crypto_hash_buf(conn->conn_rx_hash, ping_data,
1878                                                   payload_length, padding,
1879                                                   cmd->pad_bytes, &data_crc);
1880
1881                         if (checksum != data_crc) {
1882                                 pr_err("Ping data CRC32C DataDigest"
1883                                 " 0x%08x does not match computed 0x%08x\n",
1884                                         checksum, data_crc);
1885                                 if (!conn->sess->sess_ops->ErrorRecoveryLevel) {
1886                                         pr_err("Unable to recover from"
1887                                         " NOPOUT Ping DataCRC failure while in"
1888                                                 " ERL=0.\n");
1889                                         ret = -1;
1890                                         goto out;
1891                                 } else {
1892                                         /*
1893                                          * Silently drop this PDU and let the
1894                                          * initiator plug the CmdSN gap.
1895                                          */
1896                                         pr_debug("Dropping NOPOUT"
1897                                         " Command CmdSN: 0x%08x due to"
1898                                         " DataCRC error.\n", hdr->cmdsn);
1899                                         ret = 0;
1900                                         goto out;
1901                                 }
1902                         } else {
1903                                 pr_debug("Got CRC32C DataDigest"
1904                                 " 0x%08x for %u bytes of ping data.\n",
1905                                         checksum, payload_length);
1906                         }
1907                 }
1908
1909                 ping_data[payload_length] = '\0';
1910                 /*
1911                  * Attach ping data to struct iscsi_cmd->buf_ptr.
1912                  */
1913                 cmd->buf_ptr = ping_data;
1914                 cmd->buf_ptr_size = payload_length;
1915
1916                 pr_debug("Got %u bytes of NOPOUT ping"
1917                         " data.\n", payload_length);
1918                 pr_debug("Ping Data: \"%s\"\n", ping_data);
1919         }
1920
1921         return iscsit_process_nop_out(conn, cmd, hdr);
1922 out:
1923         if (cmd)
1924                 iscsit_free_cmd(cmd, false);
1925
1926         kfree(ping_data);
1927         return ret;
1928 }
1929
1930 static enum tcm_tmreq_table iscsit_convert_tmf(u8 iscsi_tmf)
1931 {
1932         switch (iscsi_tmf) {
1933         case ISCSI_TM_FUNC_ABORT_TASK:
1934                 return TMR_ABORT_TASK;
1935         case ISCSI_TM_FUNC_ABORT_TASK_SET:
1936                 return TMR_ABORT_TASK_SET;
1937         case ISCSI_TM_FUNC_CLEAR_ACA:
1938                 return TMR_CLEAR_ACA;
1939         case ISCSI_TM_FUNC_CLEAR_TASK_SET:
1940                 return TMR_CLEAR_TASK_SET;
1941         case ISCSI_TM_FUNC_LOGICAL_UNIT_RESET:
1942                 return TMR_LUN_RESET;
1943         case ISCSI_TM_FUNC_TARGET_WARM_RESET:
1944                 return TMR_TARGET_WARM_RESET;
1945         case ISCSI_TM_FUNC_TARGET_COLD_RESET:
1946                 return TMR_TARGET_COLD_RESET;
1947         default:
1948                 return TMR_UNKNOWN;
1949         }
1950 }
1951
1952 int
1953 iscsit_handle_task_mgt_cmd(struct iscsi_conn *conn, struct iscsi_cmd *cmd,
1954                            unsigned char *buf)
1955 {
1956         struct se_tmr_req *se_tmr;
1957         struct iscsi_tmr_req *tmr_req;
1958         struct iscsi_tm *hdr;
1959         int out_of_order_cmdsn = 0, ret;
1960         u8 function, tcm_function = TMR_UNKNOWN;
1961
1962         hdr                     = (struct iscsi_tm *) buf;
1963         hdr->flags &= ~ISCSI_FLAG_CMD_FINAL;
1964         function = hdr->flags;
1965
1966         pr_debug("Got Task Management Request ITT: 0x%08x, CmdSN:"
1967                 " 0x%08x, Function: 0x%02x, RefTaskTag: 0x%08x, RefCmdSN:"
1968                 " 0x%08x, CID: %hu\n", hdr->itt, hdr->cmdsn, function,
1969                 hdr->rtt, hdr->refcmdsn, conn->cid);
1970
1971         if ((function != ISCSI_TM_FUNC_ABORT_TASK) &&
1972             ((function != ISCSI_TM_FUNC_TASK_REASSIGN) &&
1973              hdr->rtt != RESERVED_ITT)) {
1974                 pr_err("RefTaskTag should be set to 0xFFFFFFFF.\n");
1975                 hdr->rtt = RESERVED_ITT;
1976         }
1977
1978         if ((function == ISCSI_TM_FUNC_TASK_REASSIGN) &&
1979                         !(hdr->opcode & ISCSI_OP_IMMEDIATE)) {
1980                 pr_err("Task Management Request TASK_REASSIGN not"
1981                         " issued as immediate command, bad iSCSI Initiator"
1982                                 "implementation\n");
1983                 return iscsit_add_reject_cmd(cmd,
1984                                              ISCSI_REASON_PROTOCOL_ERROR, buf);
1985         }
1986         if ((function != ISCSI_TM_FUNC_ABORT_TASK) &&
1987             be32_to_cpu(hdr->refcmdsn) != ISCSI_RESERVED_TAG)
1988                 hdr->refcmdsn = cpu_to_be32(ISCSI_RESERVED_TAG);
1989
1990         cmd->data_direction = DMA_NONE;
1991         cmd->tmr_req = kzalloc(sizeof(*cmd->tmr_req), GFP_KERNEL);
1992         if (!cmd->tmr_req) {
1993                 return iscsit_add_reject_cmd(cmd,
1994                                              ISCSI_REASON_BOOKMARK_NO_RESOURCES,
1995                                              buf);
1996         }
1997
1998         transport_init_se_cmd(&cmd->se_cmd, &iscsi_ops,
1999                               conn->sess->se_sess, 0, DMA_NONE,
2000                               TCM_SIMPLE_TAG, cmd->sense_buffer + 2);
2001
2002         target_get_sess_cmd(&cmd->se_cmd, true);
2003
2004         /*
2005          * TASK_REASSIGN for ERL=2 / connection stays inside of
2006          * LIO-Target $FABRIC_MOD
2007          */
2008         if (function != ISCSI_TM_FUNC_TASK_REASSIGN) {
2009                 tcm_function = iscsit_convert_tmf(function);
2010                 if (tcm_function == TMR_UNKNOWN) {
2011                         pr_err("Unknown iSCSI TMR Function:"
2012                                " 0x%02x\n", function);
2013                         return iscsit_add_reject_cmd(cmd,
2014                                 ISCSI_REASON_BOOKMARK_NO_RESOURCES, buf);
2015                 }
2016         }
2017         ret = core_tmr_alloc_req(&cmd->se_cmd, cmd->tmr_req, tcm_function,
2018                                  GFP_KERNEL);
2019         if (ret < 0)
2020                 return iscsit_add_reject_cmd(cmd,
2021                                 ISCSI_REASON_BOOKMARK_NO_RESOURCES, buf);
2022
2023         cmd->tmr_req->se_tmr_req = cmd->se_cmd.se_tmr_req;
2024
2025         cmd->iscsi_opcode       = ISCSI_OP_SCSI_TMFUNC;
2026         cmd->i_state            = ISTATE_SEND_TASKMGTRSP;
2027         cmd->immediate_cmd      = ((hdr->opcode & ISCSI_OP_IMMEDIATE) ? 1 : 0);
2028         cmd->init_task_tag      = hdr->itt;
2029         cmd->targ_xfer_tag      = 0xFFFFFFFF;
2030         cmd->cmd_sn             = be32_to_cpu(hdr->cmdsn);
2031         cmd->exp_stat_sn        = be32_to_cpu(hdr->exp_statsn);
2032         se_tmr                  = cmd->se_cmd.se_tmr_req;
2033         tmr_req                 = cmd->tmr_req;
2034         /*
2035          * Locate the struct se_lun for all TMRs not related to ERL=2 TASK_REASSIGN
2036          */
2037         if (function != ISCSI_TM_FUNC_TASK_REASSIGN) {
2038                 ret = transport_lookup_tmr_lun(&cmd->se_cmd,
2039                                                scsilun_to_int(&hdr->lun));
2040                 if (ret < 0) {
2041                         se_tmr->response = ISCSI_TMF_RSP_NO_LUN;
2042                         goto attach;
2043                 }
2044         }
2045
2046         switch (function) {
2047         case ISCSI_TM_FUNC_ABORT_TASK:
2048                 se_tmr->response = iscsit_tmr_abort_task(cmd, buf);
2049                 if (se_tmr->response)
2050                         goto attach;
2051                 break;
2052         case ISCSI_TM_FUNC_ABORT_TASK_SET:
2053         case ISCSI_TM_FUNC_CLEAR_ACA:
2054         case ISCSI_TM_FUNC_CLEAR_TASK_SET:
2055         case ISCSI_TM_FUNC_LOGICAL_UNIT_RESET:
2056                 break;
2057         case ISCSI_TM_FUNC_TARGET_WARM_RESET:
2058                 if (iscsit_tmr_task_warm_reset(conn, tmr_req, buf) < 0) {
2059                         se_tmr->response = ISCSI_TMF_RSP_AUTH_FAILED;
2060                         goto attach;
2061                 }
2062                 break;
2063         case ISCSI_TM_FUNC_TARGET_COLD_RESET:
2064                 if (iscsit_tmr_task_cold_reset(conn, tmr_req, buf) < 0) {
2065                         se_tmr->response = ISCSI_TMF_RSP_AUTH_FAILED;
2066                         goto attach;
2067                 }
2068                 break;
2069         case ISCSI_TM_FUNC_TASK_REASSIGN:
2070                 se_tmr->response = iscsit_tmr_task_reassign(cmd, buf);
2071                 /*
2072                  * Perform sanity checks on the ExpDataSN only if the
2073                  * TASK_REASSIGN was successful.
2074                  */
2075                 if (se_tmr->response)
2076                         break;
2077
2078                 if (iscsit_check_task_reassign_expdatasn(tmr_req, conn) < 0)
2079                         return iscsit_add_reject_cmd(cmd,
2080                                         ISCSI_REASON_BOOKMARK_INVALID, buf);
2081                 break;
2082         default:
2083                 pr_err("Unknown TMR function: 0x%02x, protocol"
2084                         " error.\n", function);
2085                 se_tmr->response = ISCSI_TMF_RSP_NOT_SUPPORTED;
2086                 goto attach;
2087         }
2088
2089         if ((function != ISCSI_TM_FUNC_TASK_REASSIGN) &&
2090             (se_tmr->response == ISCSI_TMF_RSP_COMPLETE))
2091                 se_tmr->call_transport = 1;
2092 attach:
2093         spin_lock_bh(&conn->cmd_lock);
2094         list_add_tail(&cmd->i_conn_node, &conn->conn_cmd_list);
2095         spin_unlock_bh(&conn->cmd_lock);
2096
2097         if (!(hdr->opcode & ISCSI_OP_IMMEDIATE)) {
2098                 int cmdsn_ret = iscsit_sequence_cmd(conn, cmd, buf, hdr->cmdsn);
2099                 if (cmdsn_ret == CMDSN_HIGHER_THAN_EXP) {
2100                         out_of_order_cmdsn = 1;
2101                 } else if (cmdsn_ret == CMDSN_LOWER_THAN_EXP) {
2102                         target_put_sess_cmd(&cmd->se_cmd);
2103                         return 0;
2104                 } else if (cmdsn_ret == CMDSN_ERROR_CANNOT_RECOVER) {
2105                         return -1;
2106                 }
2107         }
2108         iscsit_ack_from_expstatsn(conn, be32_to_cpu(hdr->exp_statsn));
2109
2110         if (out_of_order_cmdsn || !(hdr->opcode & ISCSI_OP_IMMEDIATE))
2111                 return 0;
2112         /*
2113          * Found the referenced task, send to transport for processing.
2114          */
2115         if (se_tmr->call_transport)
2116                 return transport_generic_handle_tmr(&cmd->se_cmd);
2117
2118         /*
2119          * Could not find the referenced LUN, task, or Task Management
2120          * command not authorized or supported.  Change state and
2121          * let the tx_thread send the response.
2122          *
2123          * For connection recovery, this is also the default action for
2124          * TMR TASK_REASSIGN.
2125          */
2126         iscsit_add_cmd_to_response_queue(cmd, conn, cmd->i_state);
2127         target_put_sess_cmd(&cmd->se_cmd);
2128         return 0;
2129 }
2130 EXPORT_SYMBOL(iscsit_handle_task_mgt_cmd);
2131
2132 /* #warning FIXME: Support Text Command parameters besides SendTargets */
2133 int
2134 iscsit_setup_text_cmd(struct iscsi_conn *conn, struct iscsi_cmd *cmd,
2135                       struct iscsi_text *hdr)
2136 {
2137         u32 payload_length = ntoh24(hdr->dlength);
2138
2139         if (payload_length > conn->conn_ops->MaxXmitDataSegmentLength) {
2140                 pr_err("Unable to accept text parameter length: %u"
2141                         "greater than MaxXmitDataSegmentLength %u.\n",
2142                        payload_length, conn->conn_ops->MaxXmitDataSegmentLength);
2143                 return iscsit_reject_cmd(cmd, ISCSI_REASON_PROTOCOL_ERROR,
2144                                          (unsigned char *)hdr);
2145         }
2146
2147         if (!(hdr->flags & ISCSI_FLAG_CMD_FINAL) ||
2148              (hdr->flags & ISCSI_FLAG_TEXT_CONTINUE)) {
2149                 pr_err("Multi sequence text commands currently not supported\n");
2150                 return iscsit_reject_cmd(cmd, ISCSI_REASON_CMD_NOT_SUPPORTED,
2151                                         (unsigned char *)hdr);
2152         }
2153
2154         pr_debug("Got Text Request: ITT: 0x%08x, CmdSN: 0x%08x,"
2155                 " ExpStatSN: 0x%08x, Length: %u\n", hdr->itt, hdr->cmdsn,
2156                 hdr->exp_statsn, payload_length);
2157
2158         cmd->iscsi_opcode       = ISCSI_OP_TEXT;
2159         cmd->i_state            = ISTATE_SEND_TEXTRSP;
2160         cmd->immediate_cmd      = ((hdr->opcode & ISCSI_OP_IMMEDIATE) ? 1 : 0);
2161         conn->sess->init_task_tag = cmd->init_task_tag  = hdr->itt;
2162         cmd->targ_xfer_tag      = 0xFFFFFFFF;
2163         cmd->cmd_sn             = be32_to_cpu(hdr->cmdsn);
2164         cmd->exp_stat_sn        = be32_to_cpu(hdr->exp_statsn);
2165         cmd->data_direction     = DMA_NONE;
2166         kfree(cmd->text_in_ptr);
2167         cmd->text_in_ptr        = NULL;
2168
2169         return 0;
2170 }
2171 EXPORT_SYMBOL(iscsit_setup_text_cmd);
2172
2173 int
2174 iscsit_process_text_cmd(struct iscsi_conn *conn, struct iscsi_cmd *cmd,
2175                         struct iscsi_text *hdr)
2176 {
2177         unsigned char *text_in = cmd->text_in_ptr, *text_ptr;
2178         int cmdsn_ret;
2179
2180         if (!text_in) {
2181                 cmd->targ_xfer_tag = be32_to_cpu(hdr->ttt);
2182                 if (cmd->targ_xfer_tag == 0xFFFFFFFF) {
2183                         pr_err("Unable to locate text_in buffer for sendtargets"
2184                                " discovery\n");
2185                         goto reject;
2186                 }
2187                 goto empty_sendtargets;
2188         }
2189         if (strncmp("SendTargets", text_in, 11) != 0) {
2190                 pr_err("Received Text Data that is not"
2191                         " SendTargets, cannot continue.\n");
2192                 goto reject;
2193         }
2194         text_ptr = strchr(text_in, '=');
2195         if (!text_ptr) {
2196                 pr_err("No \"=\" separator found in Text Data,"
2197                         "  cannot continue.\n");
2198                 goto reject;
2199         }
2200         if (!strncmp("=All", text_ptr, 4)) {
2201                 cmd->cmd_flags |= ICF_SENDTARGETS_ALL;
2202         } else if (!strncmp("=iqn.", text_ptr, 5) ||
2203                    !strncmp("=eui.", text_ptr, 5)) {
2204                 cmd->cmd_flags |= ICF_SENDTARGETS_SINGLE;
2205         } else {
2206                 pr_err("Unable to locate valid SendTargets=%s value\n", text_ptr);
2207                 goto reject;
2208         }
2209
2210         spin_lock_bh(&conn->cmd_lock);
2211         list_add_tail(&cmd->i_conn_node, &conn->conn_cmd_list);
2212         spin_unlock_bh(&conn->cmd_lock);
2213
2214 empty_sendtargets:
2215         iscsit_ack_from_expstatsn(conn, be32_to_cpu(hdr->exp_statsn));
2216
2217         if (!(hdr->opcode & ISCSI_OP_IMMEDIATE)) {
2218                 cmdsn_ret = iscsit_sequence_cmd(conn, cmd,
2219                                 (unsigned char *)hdr, hdr->cmdsn);
2220                 if (cmdsn_ret == CMDSN_ERROR_CANNOT_RECOVER)
2221                         return -1;
2222
2223                 return 0;
2224         }
2225
2226         return iscsit_execute_cmd(cmd, 0);
2227
2228 reject:
2229         return iscsit_reject_cmd(cmd, ISCSI_REASON_PROTOCOL_ERROR,
2230                                  (unsigned char *)hdr);
2231 }
2232 EXPORT_SYMBOL(iscsit_process_text_cmd);
2233
2234 static int
2235 iscsit_handle_text_cmd(struct iscsi_conn *conn, struct iscsi_cmd *cmd,
2236                        unsigned char *buf)
2237 {
2238         struct iscsi_text *hdr = (struct iscsi_text *)buf;
2239         char *text_in = NULL;
2240         u32 payload_length = ntoh24(hdr->dlength);
2241         int rx_size, rc;
2242
2243         rc = iscsit_setup_text_cmd(conn, cmd, hdr);
2244         if (rc < 0)
2245                 return 0;
2246
2247         rx_size = payload_length;
2248         if (payload_length) {
2249                 u32 checksum = 0, data_crc = 0;
2250                 u32 padding = 0, pad_bytes = 0;
2251                 int niov = 0, rx_got;
2252                 struct kvec iov[3];
2253
2254                 text_in = kzalloc(payload_length, GFP_KERNEL);
2255                 if (!text_in)
2256                         goto reject;
2257
2258                 cmd->text_in_ptr = text_in;
2259
2260                 memset(iov, 0, 3 * sizeof(struct kvec));
2261                 iov[niov].iov_base      = text_in;
2262                 iov[niov++].iov_len     = payload_length;
2263
2264                 padding = ((-payload_length) & 3);
2265                 if (padding != 0) {
2266                         iov[niov].iov_base = &pad_bytes;
2267                         iov[niov++].iov_len  = padding;
2268                         rx_size += padding;
2269                         pr_debug("Receiving %u additional bytes"
2270                                         " for padding.\n", padding);
2271                 }
2272                 if (conn->conn_ops->DataDigest) {
2273                         iov[niov].iov_base      = &checksum;
2274                         iov[niov++].iov_len     = ISCSI_CRC_LEN;
2275                         rx_size += ISCSI_CRC_LEN;
2276                 }
2277
2278                 rx_got = rx_data(conn, &iov[0], niov, rx_size);
2279                 if (rx_got != rx_size)
2280                         goto reject;
2281
2282                 if (conn->conn_ops->DataDigest) {
2283                         iscsit_do_crypto_hash_buf(conn->conn_rx_hash, text_in,
2284                                                   payload_length, padding,
2285                                                   &pad_bytes, &data_crc);
2286
2287                         if (checksum != data_crc) {
2288                                 pr_err("Text data CRC32C DataDigest"
2289                                         " 0x%08x does not match computed"
2290                                         " 0x%08x\n", checksum, data_crc);
2291                                 if (!conn->sess->sess_ops->ErrorRecoveryLevel) {
2292                                         pr_err("Unable to recover from"
2293                                         " Text Data digest failure while in"
2294                                                 " ERL=0.\n");
2295                                         goto reject;
2296                                 } else {
2297                                         /*
2298                                          * Silently drop this PDU and let the
2299                                          * initiator plug the CmdSN gap.
2300                                          */
2301                                         pr_debug("Dropping Text"
2302                                         " Command CmdSN: 0x%08x due to"
2303                                         " DataCRC error.\n", hdr->cmdsn);
2304                                         kfree(text_in);
2305                                         return 0;
2306                                 }
2307                         } else {
2308                                 pr_debug("Got CRC32C DataDigest"
2309                                         " 0x%08x for %u bytes of text data.\n",
2310                                                 checksum, payload_length);
2311                         }
2312                 }
2313                 text_in[payload_length - 1] = '\0';
2314                 pr_debug("Successfully read %d bytes of text"
2315                                 " data.\n", payload_length);
2316         }
2317
2318         return iscsit_process_text_cmd(conn, cmd, hdr);
2319
2320 reject:
2321         kfree(cmd->text_in_ptr);
2322         cmd->text_in_ptr = NULL;
2323         return iscsit_reject_cmd(cmd, ISCSI_REASON_PROTOCOL_ERROR, buf);
2324 }
2325
2326 int iscsit_logout_closesession(struct iscsi_cmd *cmd, struct iscsi_conn *conn)
2327 {
2328         struct iscsi_conn *conn_p;
2329         struct iscsi_session *sess = conn->sess;
2330
2331         pr_debug("Received logout request CLOSESESSION on CID: %hu"
2332                 " for SID: %u.\n", conn->cid, conn->sess->sid);
2333
2334         atomic_set(&sess->session_logout, 1);
2335         atomic_set(&conn->conn_logout_remove, 1);
2336         conn->conn_logout_reason = ISCSI_LOGOUT_REASON_CLOSE_SESSION;
2337
2338         iscsit_inc_conn_usage_count(conn);
2339         iscsit_inc_session_usage_count(sess);
2340
2341         spin_lock_bh(&sess->conn_lock);
2342         list_for_each_entry(conn_p, &sess->sess_conn_list, conn_list) {
2343                 if (conn_p->conn_state != TARG_CONN_STATE_LOGGED_IN)
2344                         continue;
2345
2346                 pr_debug("Moving to TARG_CONN_STATE_IN_LOGOUT.\n");
2347                 conn_p->conn_state = TARG_CONN_STATE_IN_LOGOUT;
2348         }
2349         spin_unlock_bh(&sess->conn_lock);
2350
2351         iscsit_add_cmd_to_response_queue(cmd, conn, cmd->i_state);
2352
2353         return 0;
2354 }
2355
2356 int iscsit_logout_closeconnection(struct iscsi_cmd *cmd, struct iscsi_conn *conn)
2357 {
2358         struct iscsi_conn *l_conn;
2359         struct iscsi_session *sess = conn->sess;
2360
2361         pr_debug("Received logout request CLOSECONNECTION for CID:"
2362                 " %hu on CID: %hu.\n", cmd->logout_cid, conn->cid);
2363
2364         /*
2365          * A Logout Request with a CLOSECONNECTION reason code for a CID
2366          * can arrive on a connection with a differing CID.
2367          */
2368         if (conn->cid == cmd->logout_cid) {
2369                 spin_lock_bh(&conn->state_lock);
2370                 pr_debug("Moving to TARG_CONN_STATE_IN_LOGOUT.\n");
2371                 conn->conn_state = TARG_CONN_STATE_IN_LOGOUT;
2372
2373                 atomic_set(&conn->conn_logout_remove, 1);
2374                 conn->conn_logout_reason = ISCSI_LOGOUT_REASON_CLOSE_CONNECTION;
2375                 iscsit_inc_conn_usage_count(conn);
2376
2377                 spin_unlock_bh(&conn->state_lock);
2378         } else {
2379                 /*
2380                  * Handle all different cid CLOSECONNECTION requests in
2381                  * iscsit_logout_post_handler_diffcid() as to give enough
2382                  * time for any non immediate command's CmdSN to be
2383                  * acknowledged on the connection in question.
2384                  *
2385                  * Here we simply make sure the CID is still around.
2386                  */
2387                 l_conn = iscsit_get_conn_from_cid(sess,
2388                                 cmd->logout_cid);
2389                 if (!l_conn) {
2390                         cmd->logout_response = ISCSI_LOGOUT_CID_NOT_FOUND;
2391                         iscsit_add_cmd_to_response_queue(cmd, conn,
2392                                         cmd->i_state);
2393                         return 0;
2394                 }
2395
2396                 iscsit_dec_conn_usage_count(l_conn);
2397         }
2398
2399         iscsit_add_cmd_to_response_queue(cmd, conn, cmd->i_state);
2400
2401         return 0;
2402 }
2403
2404 int iscsit_logout_removeconnforrecovery(struct iscsi_cmd *cmd, struct iscsi_conn *conn)
2405 {
2406         struct iscsi_session *sess = conn->sess;
2407
2408         pr_debug("Received explicit REMOVECONNFORRECOVERY logout for"
2409                 " CID: %hu on CID: %hu.\n", cmd->logout_cid, conn->cid);
2410
2411         if (sess->sess_ops->ErrorRecoveryLevel != 2) {
2412                 pr_err("Received Logout Request REMOVECONNFORRECOVERY"
2413                         " while ERL!=2.\n");
2414                 cmd->logout_response = ISCSI_LOGOUT_RECOVERY_UNSUPPORTED;
2415                 iscsit_add_cmd_to_response_queue(cmd, conn, cmd->i_state);
2416                 return 0;
2417         }
2418
2419         if (conn->cid == cmd->logout_cid) {
2420                 pr_err("Received Logout Request REMOVECONNFORRECOVERY"
2421                         " with CID: %hu on CID: %hu, implementation error.\n",
2422                                 cmd->logout_cid, conn->cid);
2423                 cmd->logout_response = ISCSI_LOGOUT_CLEANUP_FAILED;
2424                 iscsit_add_cmd_to_response_queue(cmd, conn, cmd->i_state);
2425                 return 0;
2426         }
2427
2428         iscsit_add_cmd_to_response_queue(cmd, conn, cmd->i_state);
2429
2430         return 0;
2431 }
2432
2433 int
2434 iscsit_handle_logout_cmd(struct iscsi_conn *conn, struct iscsi_cmd *cmd,
2435                         unsigned char *buf)
2436 {
2437         int cmdsn_ret, logout_remove = 0;
2438         u8 reason_code = 0;
2439         struct iscsi_logout *hdr;
2440         struct iscsi_tiqn *tiqn = iscsit_snmp_get_tiqn(conn);
2441
2442         hdr                     = (struct iscsi_logout *) buf;
2443         reason_code             = (hdr->flags & 0x7f);
2444
2445         if (tiqn) {
2446                 spin_lock(&tiqn->logout_stats.lock);
2447                 if (reason_code == ISCSI_LOGOUT_REASON_CLOSE_SESSION)
2448                         tiqn->logout_stats.normal_logouts++;
2449                 else
2450                         tiqn->logout_stats.abnormal_logouts++;
2451                 spin_unlock(&tiqn->logout_stats.lock);
2452         }
2453
2454         pr_debug("Got Logout Request ITT: 0x%08x CmdSN: 0x%08x"
2455                 " ExpStatSN: 0x%08x Reason: 0x%02x CID: %hu on CID: %hu\n",
2456                 hdr->itt, hdr->cmdsn, hdr->exp_statsn, reason_code,
2457                 hdr->cid, conn->cid);
2458
2459         if (conn->conn_state != TARG_CONN_STATE_LOGGED_IN) {
2460                 pr_err("Received logout request on connection that"
2461                         " is not in logged in state, ignoring request.\n");
2462                 iscsit_free_cmd(cmd, false);
2463                 return 0;
2464         }
2465
2466         cmd->iscsi_opcode       = ISCSI_OP_LOGOUT;
2467         cmd->i_state            = ISTATE_SEND_LOGOUTRSP;
2468         cmd->immediate_cmd      = ((hdr->opcode & ISCSI_OP_IMMEDIATE) ? 1 : 0);
2469         conn->sess->init_task_tag = cmd->init_task_tag  = hdr->itt;
2470         cmd->targ_xfer_tag      = 0xFFFFFFFF;
2471         cmd->cmd_sn             = be32_to_cpu(hdr->cmdsn);
2472         cmd->exp_stat_sn        = be32_to_cpu(hdr->exp_statsn);
2473         cmd->logout_cid         = be16_to_cpu(hdr->cid);
2474         cmd->logout_reason      = reason_code;
2475         cmd->data_direction     = DMA_NONE;
2476
2477         /*
2478          * We need to sleep in these cases (by returning 1) until the Logout
2479          * Response gets sent in the tx thread.
2480          */
2481         if ((reason_code == ISCSI_LOGOUT_REASON_CLOSE_SESSION) ||
2482            ((reason_code == ISCSI_LOGOUT_REASON_CLOSE_CONNECTION) &&
2483             be16_to_cpu(hdr->cid) == conn->cid))
2484                 logout_remove = 1;
2485
2486         spin_lock_bh(&conn->cmd_lock);
2487         list_add_tail(&cmd->i_conn_node, &conn->conn_cmd_list);
2488         spin_unlock_bh(&conn->cmd_lock);
2489
2490         if (reason_code != ISCSI_LOGOUT_REASON_RECOVERY)
2491                 iscsit_ack_from_expstatsn(conn, be32_to_cpu(hdr->exp_statsn));
2492
2493         /*
2494          * Immediate commands are executed, well, immediately.
2495          * Non-Immediate Logout Commands are executed in CmdSN order.
2496          */
2497         if (cmd->immediate_cmd) {
2498                 int ret = iscsit_execute_cmd(cmd, 0);
2499
2500                 if (ret < 0)
2501                         return ret;
2502         } else {
2503                 cmdsn_ret = iscsit_sequence_cmd(conn, cmd, buf, hdr->cmdsn);
2504                 if (cmdsn_ret == CMDSN_LOWER_THAN_EXP)
2505                         logout_remove = 0;
2506                 else if (cmdsn_ret == CMDSN_ERROR_CANNOT_RECOVER)
2507                         return -1;
2508         }
2509
2510         return logout_remove;
2511 }
2512 EXPORT_SYMBOL(iscsit_handle_logout_cmd);
2513
2514 int iscsit_handle_snack(
2515         struct iscsi_conn *conn,
2516         unsigned char *buf)
2517 {
2518         struct iscsi_snack *hdr;
2519
2520         hdr                     = (struct iscsi_snack *) buf;
2521         hdr->flags              &= ~ISCSI_FLAG_CMD_FINAL;
2522
2523         pr_debug("Got ISCSI_INIT_SNACK, ITT: 0x%08x, ExpStatSN:"
2524                 " 0x%08x, Type: 0x%02x, BegRun: 0x%08x, RunLength: 0x%08x,"
2525                 " CID: %hu\n", hdr->itt, hdr->exp_statsn, hdr->flags,
2526                         hdr->begrun, hdr->runlength, conn->cid);
2527
2528         if (!conn->sess->sess_ops->ErrorRecoveryLevel) {
2529                 pr_err("Initiator sent SNACK request while in"
2530                         " ErrorRecoveryLevel=0.\n");
2531                 return iscsit_add_reject(conn, ISCSI_REASON_PROTOCOL_ERROR,
2532                                          buf);
2533         }
2534         /*
2535          * SNACK_DATA and SNACK_R2T are both 0,  so check which function to
2536          * call from inside iscsi_send_recovery_datain_or_r2t().
2537          */
2538         switch (hdr->flags & ISCSI_FLAG_SNACK_TYPE_MASK) {
2539         case 0:
2540                 return iscsit_handle_recovery_datain_or_r2t(conn, buf,
2541                         hdr->itt,
2542                         be32_to_cpu(hdr->ttt),
2543                         be32_to_cpu(hdr->begrun),
2544                         be32_to_cpu(hdr->runlength));
2545         case ISCSI_FLAG_SNACK_TYPE_STATUS:
2546                 return iscsit_handle_status_snack(conn, hdr->itt,
2547                         be32_to_cpu(hdr->ttt),
2548                         be32_to_cpu(hdr->begrun), be32_to_cpu(hdr->runlength));
2549         case ISCSI_FLAG_SNACK_TYPE_DATA_ACK:
2550                 return iscsit_handle_data_ack(conn, be32_to_cpu(hdr->ttt),
2551                         be32_to_cpu(hdr->begrun),
2552                         be32_to_cpu(hdr->runlength));
2553         case ISCSI_FLAG_SNACK_TYPE_RDATA:
2554                 /* FIXME: Support R-Data SNACK */
2555                 pr_err("R-Data SNACK Not Supported.\n");
2556                 return iscsit_add_reject(conn, ISCSI_REASON_PROTOCOL_ERROR,
2557                                          buf);
2558         default:
2559                 pr_err("Unknown SNACK type 0x%02x, protocol"
2560                         " error.\n", hdr->flags & 0x0f);
2561                 return iscsit_add_reject(conn, ISCSI_REASON_PROTOCOL_ERROR,
2562                                          buf);
2563         }
2564
2565         return 0;
2566 }
2567 EXPORT_SYMBOL(iscsit_handle_snack);
2568
2569 static void iscsit_rx_thread_wait_for_tcp(struct iscsi_conn *conn)
2570 {
2571         if ((conn->sock->sk->sk_shutdown & SEND_SHUTDOWN) ||
2572             (conn->sock->sk->sk_shutdown & RCV_SHUTDOWN)) {
2573                 wait_for_completion_interruptible_timeout(
2574                                         &conn->rx_half_close_comp,
2575                                         ISCSI_RX_THREAD_TCP_TIMEOUT * HZ);
2576         }
2577 }
2578
2579 static int iscsit_handle_immediate_data(
2580         struct iscsi_cmd *cmd,
2581         struct iscsi_scsi_req *hdr,
2582         u32 length)
2583 {
2584         int iov_ret, rx_got = 0, rx_size = 0;
2585         u32 checksum, iov_count = 0, padding = 0;
2586         struct iscsi_conn *conn = cmd->conn;
2587         struct kvec *iov;
2588
2589         iov_ret = iscsit_map_iovec(cmd, cmd->iov_data, cmd->write_data_done, length);
2590         if (iov_ret < 0)
2591                 return IMMEDIATE_DATA_CANNOT_RECOVER;
2592
2593         rx_size = length;
2594         iov_count = iov_ret;
2595         iov = &cmd->iov_data[0];
2596
2597         padding = ((-length) & 3);
2598         if (padding != 0) {
2599                 iov[iov_count].iov_base = cmd->pad_bytes;
2600                 iov[iov_count++].iov_len = padding;
2601                 rx_size += padding;
2602         }
2603
2604         if (conn->conn_ops->DataDigest) {
2605                 iov[iov_count].iov_base         = &checksum;
2606                 iov[iov_count++].iov_len        = ISCSI_CRC_LEN;
2607                 rx_size += ISCSI_CRC_LEN;
2608         }
2609
2610         rx_got = rx_data(conn, &cmd->iov_data[0], iov_count, rx_size);
2611
2612         iscsit_unmap_iovec(cmd);
2613
2614         if (rx_got != rx_size) {
2615                 iscsit_rx_thread_wait_for_tcp(conn);
2616                 return IMMEDIATE_DATA_CANNOT_RECOVER;
2617         }
2618
2619         if (conn->conn_ops->DataDigest) {
2620                 u32 data_crc;
2621
2622                 data_crc = iscsit_do_crypto_hash_sg(conn->conn_rx_hash, cmd,
2623                                                     cmd->write_data_done, length, padding,
2624                                                     cmd->pad_bytes);
2625
2626                 if (checksum != data_crc) {
2627                         pr_err("ImmediateData CRC32C DataDigest 0x%08x"
2628                                 " does not match computed 0x%08x\n", checksum,
2629                                 data_crc);
2630
2631                         if (!conn->sess->sess_ops->ErrorRecoveryLevel) {
2632                                 pr_err("Unable to recover from"
2633                                         " Immediate Data digest failure while"
2634                                         " in ERL=0.\n");
2635                                 iscsit_reject_cmd(cmd,
2636                                                 ISCSI_REASON_DATA_DIGEST_ERROR,
2637                                                 (unsigned char *)hdr);
2638                                 return IMMEDIATE_DATA_CANNOT_RECOVER;
2639                         } else {
2640                                 iscsit_reject_cmd(cmd,
2641                                                 ISCSI_REASON_DATA_DIGEST_ERROR,
2642                                                 (unsigned char *)hdr);
2643                                 return IMMEDIATE_DATA_ERL1_CRC_FAILURE;
2644                         }
2645                 } else {
2646                         pr_debug("Got CRC32C DataDigest 0x%08x for"
2647                                 " %u bytes of Immediate Data\n", checksum,
2648                                 length);
2649                 }
2650         }
2651
2652         cmd->write_data_done += length;
2653
2654         if (cmd->write_data_done == cmd->se_cmd.data_length) {
2655                 spin_lock_bh(&cmd->istate_lock);
2656                 cmd->cmd_flags |= ICF_GOT_LAST_DATAOUT;
2657                 cmd->i_state = ISTATE_RECEIVED_LAST_DATAOUT;
2658                 spin_unlock_bh(&cmd->istate_lock);
2659         }
2660
2661         return IMMEDIATE_DATA_NORMAL_OPERATION;
2662 }
2663
2664 /*
2665  *      Called with sess->conn_lock held.
2666  */
2667 /* #warning iscsi_build_conn_drop_async_message() only sends out on connections
2668         with active network interface */
2669 static void iscsit_build_conn_drop_async_message(struct iscsi_conn *conn)
2670 {
2671         struct iscsi_cmd *cmd;
2672         struct iscsi_conn *conn_p;
2673         bool found = false;
2674
2675         /*
2676          * Only send a Asynchronous Message on connections whos network
2677          * interface is still functional.
2678          */
2679         list_for_each_entry(conn_p, &conn->sess->sess_conn_list, conn_list) {
2680                 if (conn_p->conn_state == TARG_CONN_STATE_LOGGED_IN) {
2681                         iscsit_inc_conn_usage_count(conn_p);
2682                         found = true;
2683                         break;
2684                 }
2685         }
2686
2687         if (!found)
2688                 return;
2689
2690         cmd = iscsit_allocate_cmd(conn_p, TASK_RUNNING);
2691         if (!cmd) {
2692                 iscsit_dec_conn_usage_count(conn_p);
2693                 return;
2694         }
2695
2696         cmd->logout_cid = conn->cid;
2697         cmd->iscsi_opcode = ISCSI_OP_ASYNC_EVENT;
2698         cmd->i_state = ISTATE_SEND_ASYNCMSG;
2699
2700         spin_lock_bh(&conn_p->cmd_lock);
2701         list_add_tail(&cmd->i_conn_node, &conn_p->conn_cmd_list);
2702         spin_unlock_bh(&conn_p->cmd_lock);
2703
2704         iscsit_add_cmd_to_response_queue(cmd, conn_p, cmd->i_state);
2705         iscsit_dec_conn_usage_count(conn_p);
2706 }
2707
2708 static int iscsit_send_conn_drop_async_message(
2709         struct iscsi_cmd *cmd,
2710         struct iscsi_conn *conn)
2711 {
2712         struct iscsi_async *hdr;
2713
2714         cmd->iscsi_opcode = ISCSI_OP_ASYNC_EVENT;
2715
2716         hdr                     = (struct iscsi_async *) cmd->pdu;
2717         hdr->opcode             = ISCSI_OP_ASYNC_EVENT;
2718         hdr->flags              = ISCSI_FLAG_CMD_FINAL;
2719         cmd->init_task_tag      = RESERVED_ITT;
2720         cmd->targ_xfer_tag      = 0xFFFFFFFF;
2721         put_unaligned_be64(0xFFFFFFFFFFFFFFFFULL, &hdr->rsvd4[0]);
2722         cmd->stat_sn            = conn->stat_sn++;
2723         hdr->statsn             = cpu_to_be32(cmd->stat_sn);
2724         hdr->exp_cmdsn          = cpu_to_be32(conn->sess->exp_cmd_sn);
2725         hdr->max_cmdsn          = cpu_to_be32((u32) atomic_read(&conn->sess->max_cmd_sn));
2726         hdr->async_event        = ISCSI_ASYNC_MSG_DROPPING_CONNECTION;
2727         hdr->param1             = cpu_to_be16(cmd->logout_cid);
2728         hdr->param2             = cpu_to_be16(conn->sess->sess_ops->DefaultTime2Wait);
2729         hdr->param3             = cpu_to_be16(conn->sess->sess_ops->DefaultTime2Retain);
2730
2731         pr_debug("Sending Connection Dropped Async Message StatSN:"
2732                 " 0x%08x, for CID: %hu on CID: %hu\n", cmd->stat_sn,
2733                         cmd->logout_cid, conn->cid);
2734
2735         return conn->conn_transport->iscsit_xmit_pdu(conn, cmd, NULL, NULL, 0);
2736 }
2737
2738 static void iscsit_tx_thread_wait_for_tcp(struct iscsi_conn *conn)
2739 {
2740         if ((conn->sock->sk->sk_shutdown & SEND_SHUTDOWN) ||
2741             (conn->sock->sk->sk_shutdown & RCV_SHUTDOWN)) {
2742                 wait_for_completion_interruptible_timeout(
2743                                         &conn->tx_half_close_comp,
2744                                         ISCSI_TX_THREAD_TCP_TIMEOUT * HZ);
2745         }
2746 }
2747
2748 void
2749 iscsit_build_datain_pdu(struct iscsi_cmd *cmd, struct iscsi_conn *conn,
2750                         struct iscsi_datain *datain, struct iscsi_data_rsp *hdr,
2751                         bool set_statsn)
2752 {
2753         hdr->opcode             = ISCSI_OP_SCSI_DATA_IN;
2754         hdr->flags              = datain->flags;
2755         if (hdr->flags & ISCSI_FLAG_DATA_STATUS) {
2756                 if (cmd->se_cmd.se_cmd_flags & SCF_OVERFLOW_BIT) {
2757                         hdr->flags |= ISCSI_FLAG_DATA_OVERFLOW;
2758                         hdr->residual_count = cpu_to_be32(cmd->se_cmd.residual_count);
2759                 } else if (cmd->se_cmd.se_cmd_flags & SCF_UNDERFLOW_BIT) {
2760                         hdr->flags |= ISCSI_FLAG_DATA_UNDERFLOW;
2761                         hdr->residual_count = cpu_to_be32(cmd->se_cmd.residual_count);
2762                 }
2763         }
2764         hton24(hdr->dlength, datain->length);
2765         if (hdr->flags & ISCSI_FLAG_DATA_ACK)
2766                 int_to_scsilun(cmd->se_cmd.orig_fe_lun,
2767                                 (struct scsi_lun *)&hdr->lun);
2768         else
2769                 put_unaligned_le64(0xFFFFFFFFFFFFFFFFULL, &hdr->lun);
2770
2771         hdr->itt                = cmd->init_task_tag;
2772
2773         if (hdr->flags & ISCSI_FLAG_DATA_ACK)
2774                 hdr->ttt                = cpu_to_be32(cmd->targ_xfer_tag);
2775         else
2776                 hdr->ttt                = cpu_to_be32(0xFFFFFFFF);
2777         if (set_statsn)
2778                 hdr->statsn             = cpu_to_be32(cmd->stat_sn);
2779         else
2780                 hdr->statsn             = cpu_to_be32(0xFFFFFFFF);
2781
2782         hdr->exp_cmdsn          = cpu_to_be32(conn->sess->exp_cmd_sn);
2783         hdr->max_cmdsn          = cpu_to_be32((u32) atomic_read(&conn->sess->max_cmd_sn));
2784         hdr->datasn             = cpu_to_be32(datain->data_sn);
2785         hdr->offset             = cpu_to_be32(datain->offset);
2786
2787         pr_debug("Built DataIN ITT: 0x%08x, StatSN: 0x%08x,"
2788                 " DataSN: 0x%08x, Offset: %u, Length: %u, CID: %hu\n",
2789                 cmd->init_task_tag, ntohl(hdr->statsn), ntohl(hdr->datasn),
2790                 ntohl(hdr->offset), datain->length, conn->cid);
2791 }
2792 EXPORT_SYMBOL(iscsit_build_datain_pdu);
2793
2794 static int iscsit_send_datain(struct iscsi_cmd *cmd, struct iscsi_conn *conn)
2795 {
2796         struct iscsi_data_rsp *hdr = (struct iscsi_data_rsp *)&cmd->pdu[0];
2797         struct iscsi_datain datain;
2798         struct iscsi_datain_req *dr;
2799         int eodr = 0, ret;
2800         bool set_statsn = false;
2801
2802         memset(&datain, 0, sizeof(struct iscsi_datain));
2803         dr = iscsit_get_datain_values(cmd, &datain);
2804         if (!dr) {
2805                 pr_err("iscsit_get_datain_values failed for ITT: 0x%08x\n",
2806                                 cmd->init_task_tag);
2807                 return -1;
2808         }
2809         /*
2810          * Be paranoid and double check the logic for now.
2811          */
2812         if ((datain.offset + datain.length) > cmd->se_cmd.data_length) {
2813                 pr_err("Command ITT: 0x%08x, datain.offset: %u and"
2814                         " datain.length: %u exceeds cmd->data_length: %u\n",
2815                         cmd->init_task_tag, datain.offset, datain.length,
2816                         cmd->se_cmd.data_length);
2817                 return -1;
2818         }
2819
2820         atomic_long_add(datain.length, &conn->sess->tx_data_octets);
2821         /*
2822          * Special case for successfully execution w/ both DATAIN
2823          * and Sense Data.
2824          */
2825         if ((datain.flags & ISCSI_FLAG_DATA_STATUS) &&
2826             (cmd->se_cmd.se_cmd_flags & SCF_TRANSPORT_TASK_SENSE))
2827                 datain.flags &= ~ISCSI_FLAG_DATA_STATUS;
2828         else {
2829                 if ((dr->dr_complete == DATAIN_COMPLETE_NORMAL) ||
2830                     (dr->dr_complete == DATAIN_COMPLETE_CONNECTION_RECOVERY)) {
2831                         iscsit_increment_maxcmdsn(cmd, conn->sess);
2832                         cmd->stat_sn = conn->stat_sn++;
2833                         set_statsn = true;
2834                 } else if (dr->dr_complete ==
2835                            DATAIN_COMPLETE_WITHIN_COMMAND_RECOVERY)
2836                         set_statsn = true;
2837         }
2838
2839         iscsit_build_datain_pdu(cmd, conn, &datain, hdr, set_statsn);
2840
2841         ret = conn->conn_transport->iscsit_xmit_pdu(conn, cmd, dr, &datain, 0);
2842         if (ret < 0)
2843                 return ret;
2844
2845         if (dr->dr_complete) {
2846                 eodr = (cmd->se_cmd.se_cmd_flags & SCF_TRANSPORT_TASK_SENSE) ?
2847                                 2 : 1;
2848                 iscsit_free_datain_req(cmd, dr);
2849         }
2850
2851         return eodr;
2852 }
2853
2854 int
2855 iscsit_build_logout_rsp(struct iscsi_cmd *cmd, struct iscsi_conn *conn,
2856                         struct iscsi_logout_rsp *hdr)
2857 {
2858         struct iscsi_conn *logout_conn = NULL;
2859         struct iscsi_conn_recovery *cr = NULL;
2860         struct iscsi_session *sess = conn->sess;
2861         /*
2862          * The actual shutting down of Sessions and/or Connections
2863          * for CLOSESESSION and CLOSECONNECTION Logout Requests
2864          * is done in scsi_logout_post_handler().
2865          */
2866         switch (cmd->logout_reason) {
2867         case ISCSI_LOGOUT_REASON_CLOSE_SESSION:
2868                 pr_debug("iSCSI session logout successful, setting"
2869                         " logout response to ISCSI_LOGOUT_SUCCESS.\n");
2870                 cmd->logout_response = ISCSI_LOGOUT_SUCCESS;
2871                 break;
2872         case ISCSI_LOGOUT_REASON_CLOSE_CONNECTION:
2873                 if (cmd->logout_response == ISCSI_LOGOUT_CID_NOT_FOUND)
2874                         break;
2875                 /*
2876                  * For CLOSECONNECTION logout requests carrying
2877                  * a matching logout CID -> local CID, the reference
2878                  * for the local CID will have been incremented in
2879                  * iscsi_logout_closeconnection().
2880                  *
2881                  * For CLOSECONNECTION logout requests carrying
2882                  * a different CID than the connection it arrived
2883                  * on, the connection responding to cmd->logout_cid
2884                  * is stopped in iscsit_logout_post_handler_diffcid().
2885                  */
2886
2887                 pr_debug("iSCSI CID: %hu logout on CID: %hu"
2888                         " successful.\n", cmd->logout_cid, conn->cid);
2889                 cmd->logout_response = ISCSI_LOGOUT_SUCCESS;
2890                 break;
2891         case ISCSI_LOGOUT_REASON_RECOVERY:
2892                 if ((cmd->logout_response == ISCSI_LOGOUT_RECOVERY_UNSUPPORTED) ||
2893                     (cmd->logout_response == ISCSI_LOGOUT_CLEANUP_FAILED))
2894                         break;
2895                 /*
2896                  * If the connection is still active from our point of view
2897                  * force connection recovery to occur.
2898                  */
2899                 logout_conn = iscsit_get_conn_from_cid_rcfr(sess,
2900                                 cmd->logout_cid);
2901                 if (logout_conn) {
2902                         iscsit_connection_reinstatement_rcfr(logout_conn);
2903                         iscsit_dec_conn_usage_count(logout_conn);
2904                 }
2905
2906                 cr = iscsit_get_inactive_connection_recovery_entry(
2907                                 conn->sess, cmd->logout_cid);
2908                 if (!cr) {
2909                         pr_err("Unable to locate CID: %hu for"
2910                         " REMOVECONNFORRECOVERY Logout Request.\n",
2911                                 cmd->logout_cid);
2912                         cmd->logout_response = ISCSI_LOGOUT_CID_NOT_FOUND;
2913                         break;
2914                 }
2915
2916                 iscsit_discard_cr_cmds_by_expstatsn(cr, cmd->exp_stat_sn);
2917
2918                 pr_debug("iSCSI REMOVECONNFORRECOVERY logout"
2919                         " for recovery for CID: %hu on CID: %hu successful.\n",
2920                                 cmd->logout_cid, conn->cid);
2921                 cmd->logout_response = ISCSI_LOGOUT_SUCCESS;
2922                 break;
2923         default:
2924                 pr_err("Unknown cmd->logout_reason: 0x%02x\n",
2925                                 cmd->logout_reason);
2926                 return -1;
2927         }
2928
2929         hdr->opcode             = ISCSI_OP_LOGOUT_RSP;
2930         hdr->flags              |= ISCSI_FLAG_CMD_FINAL;
2931         hdr->response           = cmd->logout_response;
2932         hdr->itt                = cmd->init_task_tag;
2933         cmd->stat_sn            = conn->stat_sn++;
2934         hdr->statsn             = cpu_to_be32(cmd->stat_sn);
2935
2936         iscsit_increment_maxcmdsn(cmd, conn->sess);
2937         hdr->exp_cmdsn          = cpu_to_be32(conn->sess->exp_cmd_sn);
2938         hdr->max_cmdsn          = cpu_to_be32((u32) atomic_read(&conn->sess->max_cmd_sn));
2939
2940         pr_debug("Built Logout Response ITT: 0x%08x StatSN:"
2941                 " 0x%08x Response: 0x%02x CID: %hu on CID: %hu\n",
2942                 cmd->init_task_tag, cmd->stat_sn, hdr->response,
2943                 cmd->logout_cid, conn->cid);
2944
2945         return 0;
2946 }
2947 EXPORT_SYMBOL(iscsit_build_logout_rsp);
2948
2949 static int
2950 iscsit_send_logout(struct iscsi_cmd *cmd, struct iscsi_conn *conn)
2951 {
2952         int rc;
2953
2954         rc = iscsit_build_logout_rsp(cmd, conn,
2955                         (struct iscsi_logout_rsp *)&cmd->pdu[0]);
2956         if (rc < 0)
2957                 return rc;
2958
2959         return conn->conn_transport->iscsit_xmit_pdu(conn, cmd, NULL, NULL, 0);
2960 }
2961
2962 void
2963 iscsit_build_nopin_rsp(struct iscsi_cmd *cmd, struct iscsi_conn *conn,
2964                        struct iscsi_nopin *hdr, bool nopout_response)
2965 {
2966         hdr->opcode             = ISCSI_OP_NOOP_IN;
2967         hdr->flags              |= ISCSI_FLAG_CMD_FINAL;
2968         hton24(hdr->dlength, cmd->buf_ptr_size);
2969         if (nopout_response)
2970                 put_unaligned_le64(0xFFFFFFFFFFFFFFFFULL, &hdr->lun);
2971         hdr->itt                = cmd->init_task_tag;
2972         hdr->ttt                = cpu_to_be32(cmd->targ_xfer_tag);
2973         cmd->stat_sn            = (nopout_response) ? conn->stat_sn++ :
2974                                   conn->stat_sn;
2975         hdr->statsn             = cpu_to_be32(cmd->stat_sn);
2976
2977         if (nopout_response)
2978                 iscsit_increment_maxcmdsn(cmd, conn->sess);
2979
2980         hdr->exp_cmdsn          = cpu_to_be32(conn->sess->exp_cmd_sn);
2981         hdr->max_cmdsn          = cpu_to_be32((u32) atomic_read(&conn->sess->max_cmd_sn));
2982
2983         pr_debug("Built NOPIN %s Response ITT: 0x%08x, TTT: 0x%08x,"
2984                 " StatSN: 0x%08x, Length %u\n", (nopout_response) ?
2985                 "Solicited" : "Unsolicited", cmd->init_task_tag,
2986                 cmd->targ_xfer_tag, cmd->stat_sn, cmd->buf_ptr_size);
2987 }
2988 EXPORT_SYMBOL(iscsit_build_nopin_rsp);
2989
2990 /*
2991  *      Unsolicited NOPIN, either requesting a response or not.
2992  */
2993 static int iscsit_send_unsolicited_nopin(
2994         struct iscsi_cmd *cmd,
2995         struct iscsi_conn *conn,
2996         int want_response)
2997 {
2998         struct iscsi_nopin *hdr = (struct iscsi_nopin *)&cmd->pdu[0];
2999         int ret;
3000
3001         iscsit_build_nopin_rsp(cmd, conn, hdr, false);
3002
3003         pr_debug("Sending Unsolicited NOPIN TTT: 0x%08x StatSN:"
3004                 " 0x%08x CID: %hu\n", hdr->ttt, cmd->stat_sn, conn->cid);
3005
3006         ret = conn->conn_transport->iscsit_xmit_pdu(conn, cmd, NULL, NULL, 0);
3007         if (ret < 0)
3008                 return ret;
3009
3010         spin_lock_bh(&cmd->istate_lock);
3011         cmd->i_state = want_response ?
3012                 ISTATE_SENT_NOPIN_WANT_RESPONSE : ISTATE_SENT_STATUS;
3013         spin_unlock_bh(&cmd->istate_lock);
3014
3015         return 0;
3016 }
3017
3018 static int
3019 iscsit_send_nopin(struct iscsi_cmd *cmd, struct iscsi_conn *conn)
3020 {
3021         struct iscsi_nopin *hdr = (struct iscsi_nopin *)&cmd->pdu[0];
3022
3023         iscsit_build_nopin_rsp(cmd, conn, hdr, true);
3024
3025         /*
3026          * NOPOUT Ping Data is attached to struct iscsi_cmd->buf_ptr.
3027          * NOPOUT DataSegmentLength is at struct iscsi_cmd->buf_ptr_size.
3028          */
3029         pr_debug("Echoing back %u bytes of ping data.\n", cmd->buf_ptr_size);
3030
3031         return conn->conn_transport->iscsit_xmit_pdu(conn, cmd, NULL,
3032                                                      cmd->buf_ptr,
3033                                                      cmd->buf_ptr_size);
3034 }
3035
3036 static int iscsit_send_r2t(
3037         struct iscsi_cmd *cmd,
3038         struct iscsi_conn *conn)
3039 {
3040         struct iscsi_r2t *r2t;
3041         struct iscsi_r2t_rsp *hdr;
3042         int ret;
3043
3044         r2t = iscsit_get_r2t_from_list(cmd);
3045         if (!r2t)
3046                 return -1;
3047
3048         hdr                     = (struct iscsi_r2t_rsp *) cmd->pdu;
3049         memset(hdr, 0, ISCSI_HDR_LEN);
3050         hdr->opcode             = ISCSI_OP_R2T;
3051         hdr->flags              |= ISCSI_FLAG_CMD_FINAL;
3052         int_to_scsilun(cmd->se_cmd.orig_fe_lun,
3053                         (struct scsi_lun *)&hdr->lun);
3054         hdr->itt                = cmd->init_task_tag;
3055         if (conn->conn_transport->iscsit_get_r2t_ttt)
3056                 conn->conn_transport->iscsit_get_r2t_ttt(conn, cmd, r2t);
3057         else
3058                 r2t->targ_xfer_tag = session_get_next_ttt(conn->sess);
3059         hdr->ttt                = cpu_to_be32(r2t->targ_xfer_tag);
3060         hdr->statsn             = cpu_to_be32(conn->stat_sn);
3061         hdr->exp_cmdsn          = cpu_to_be32(conn->sess->exp_cmd_sn);
3062         hdr->max_cmdsn          = cpu_to_be32((u32) atomic_read(&conn->sess->max_cmd_sn));
3063         hdr->r2tsn              = cpu_to_be32(r2t->r2t_sn);
3064         hdr->data_offset        = cpu_to_be32(r2t->offset);
3065         hdr->data_length        = cpu_to_be32(r2t->xfer_len);
3066
3067         pr_debug("Built %sR2T, ITT: 0x%08x, TTT: 0x%08x, StatSN:"
3068                 " 0x%08x, R2TSN: 0x%08x, Offset: %u, DDTL: %u, CID: %hu\n",
3069                 (!r2t->recovery_r2t) ? "" : "Recovery ", cmd->init_task_tag,
3070                 r2t->targ_xfer_tag, ntohl(hdr->statsn), r2t->r2t_sn,
3071                         r2t->offset, r2t->xfer_len, conn->cid);
3072
3073         spin_lock_bh(&cmd->r2t_lock);
3074         r2t->sent_r2t = 1;
3075         spin_unlock_bh(&cmd->r2t_lock);
3076
3077         ret = conn->conn_transport->iscsit_xmit_pdu(conn, cmd, NULL, NULL, 0);
3078         if (ret < 0) {
3079                 return ret;
3080         }
3081
3082         spin_lock_bh(&cmd->dataout_timeout_lock);
3083         iscsit_start_dataout_timer(cmd, conn);
3084         spin_unlock_bh(&cmd->dataout_timeout_lock);
3085
3086         return 0;
3087 }
3088
3089 /*
3090  *      @recovery: If called from iscsi_task_reassign_complete_write() for
3091  *              connection recovery.
3092  */
3093 int iscsit_build_r2ts_for_cmd(
3094         struct iscsi_conn *conn,
3095         struct iscsi_cmd *cmd,
3096         bool recovery)
3097 {
3098         int first_r2t = 1;
3099         u32 offset = 0, xfer_len = 0;
3100
3101         spin_lock_bh(&cmd->r2t_lock);
3102         if (cmd->cmd_flags & ICF_SENT_LAST_R2T) {
3103                 spin_unlock_bh(&cmd->r2t_lock);
3104                 return 0;
3105         }
3106
3107         if (conn->sess->sess_ops->DataSequenceInOrder &&
3108             !recovery)
3109                 cmd->r2t_offset = max(cmd->r2t_offset, cmd->write_data_done);
3110
3111         while (cmd->outstanding_r2ts < conn->sess->sess_ops->MaxOutstandingR2T) {
3112                 if (conn->sess->sess_ops->DataSequenceInOrder) {
3113                         offset = cmd->r2t_offset;
3114
3115                         if (first_r2t && recovery) {
3116                                 int new_data_end = offset +
3117                                         conn->sess->sess_ops->MaxBurstLength -
3118                                         cmd->next_burst_len;
3119
3120                                 if (new_data_end > cmd->se_cmd.data_length)
3121                                         xfer_len = cmd->se_cmd.data_length - offset;
3122                                 else
3123                                         xfer_len =
3124                                                 conn->sess->sess_ops->MaxBurstLength -
3125                                                 cmd->next_burst_len;
3126                         } else {
3127                                 int new_data_end = offset +
3128                                         conn->sess->sess_ops->MaxBurstLength;
3129
3130                                 if (new_data_end > cmd->se_cmd.data_length)
3131                                         xfer_len = cmd->se_cmd.data_length - offset;
3132                                 else
3133                                         xfer_len = conn->sess->sess_ops->MaxBurstLength;
3134                         }
3135                         cmd->r2t_offset += xfer_len;
3136
3137                         if (cmd->r2t_offset == cmd->se_cmd.data_length)
3138                                 cmd->cmd_flags |= ICF_SENT_LAST_R2T;
3139                 } else {
3140                         struct iscsi_seq *seq;
3141
3142                         seq = iscsit_get_seq_holder_for_r2t(cmd);
3143                         if (!seq) {
3144                                 spin_unlock_bh(&cmd->r2t_lock);
3145                                 return -1;
3146                         }
3147
3148                         offset = seq->offset;
3149                         xfer_len = seq->xfer_len;
3150
3151                         if (cmd->seq_send_order == cmd->seq_count)
3152            &