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