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