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