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);
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 	if (target_get_sess_cmd(&cmd->se_cmd, true) < 0)
1169 		return iscsit_add_reject_cmd(cmd,
1170 				ISCSI_REASON_WAITING_FOR_LOGOUT, buf);
1171 
1172 	cmd->sense_reason = transport_lookup_cmd_lun(&cmd->se_cmd,
1173 						     scsilun_to_int(&hdr->lun));
1174 	if (cmd->sense_reason)
1175 		goto attach_cmd;
1176 
1177 	/* only used for printks or comparing with ->ref_task_tag */
1178 	cmd->se_cmd.tag = (__force u32)cmd->init_task_tag;
1179 	cmd->sense_reason = target_setup_cmd_from_cdb(&cmd->se_cmd, hdr->cdb);
1180 	if (cmd->sense_reason) {
1181 		if (cmd->sense_reason == TCM_OUT_OF_RESOURCES) {
1182 			return iscsit_add_reject_cmd(cmd,
1183 					ISCSI_REASON_BOOKMARK_NO_RESOURCES, buf);
1184 		}
1185 
1186 		goto attach_cmd;
1187 	}
1188 
1189 	if (iscsit_build_pdu_and_seq_lists(cmd, payload_length) < 0) {
1190 		return iscsit_add_reject_cmd(cmd,
1191 				ISCSI_REASON_BOOKMARK_NO_RESOURCES, buf);
1192 	}
1193 
1194 attach_cmd:
1195 	spin_lock_bh(&conn->cmd_lock);
1196 	list_add_tail(&cmd->i_conn_node, &conn->conn_cmd_list);
1197 	spin_unlock_bh(&conn->cmd_lock);
1198 	/*
1199 	 * Check if we need to delay processing because of ALUA
1200 	 * Active/NonOptimized primary access state..
1201 	 */
1202 	core_alua_check_nonop_delay(&cmd->se_cmd);
1203 
1204 	return 0;
1205 }
1206 EXPORT_SYMBOL(iscsit_setup_scsi_cmd);
1207 
1208 void iscsit_set_unsolicited_dataout(struct iscsi_cmd *cmd)
1209 {
1210 	iscsit_set_dataout_sequence_values(cmd);
1211 
1212 	spin_lock_bh(&cmd->dataout_timeout_lock);
1213 	iscsit_start_dataout_timer(cmd, cmd->conn);
1214 	spin_unlock_bh(&cmd->dataout_timeout_lock);
1215 }
1216 EXPORT_SYMBOL(iscsit_set_unsolicited_dataout);
1217 
1218 int iscsit_process_scsi_cmd(struct iscsi_conn *conn, struct iscsi_cmd *cmd,
1219 			    struct iscsi_scsi_req *hdr)
1220 {
1221 	int cmdsn_ret = 0;
1222 	/*
1223 	 * Check the CmdSN against ExpCmdSN/MaxCmdSN here if
1224 	 * the Immediate Bit is not set, and no Immediate
1225 	 * Data is attached.
1226 	 *
1227 	 * A PDU/CmdSN carrying Immediate Data can only
1228 	 * be processed after the DataCRC has passed.
1229 	 * If the DataCRC fails, the CmdSN MUST NOT
1230 	 * be acknowledged. (See below)
1231 	 */
1232 	if (!cmd->immediate_data) {
1233 		cmdsn_ret = iscsit_sequence_cmd(conn, cmd,
1234 					(unsigned char *)hdr, hdr->cmdsn);
1235 		if (cmdsn_ret == CMDSN_ERROR_CANNOT_RECOVER)
1236 			return -1;
1237 		else if (cmdsn_ret == CMDSN_LOWER_THAN_EXP) {
1238 			target_put_sess_cmd(&cmd->se_cmd);
1239 			return 0;
1240 		}
1241 	}
1242 
1243 	iscsit_ack_from_expstatsn(conn, be32_to_cpu(hdr->exp_statsn));
1244 
1245 	/*
1246 	 * If no Immediate Data is attached, it's OK to return now.
1247 	 */
1248 	if (!cmd->immediate_data) {
1249 		if (!cmd->sense_reason && cmd->unsolicited_data)
1250 			iscsit_set_unsolicited_dataout(cmd);
1251 		if (!cmd->sense_reason)
1252 			return 0;
1253 
1254 		target_put_sess_cmd(&cmd->se_cmd);
1255 		return 0;
1256 	}
1257 
1258 	/*
1259 	 * Early CHECK_CONDITIONs with ImmediateData never make it to command
1260 	 * execution.  These exceptions are processed in CmdSN order using
1261 	 * iscsit_check_received_cmdsn() in iscsit_get_immediate_data() below.
1262 	 */
1263 	if (cmd->sense_reason)
1264 		return 1;
1265 	/*
1266 	 * Call directly into transport_generic_new_cmd() to perform
1267 	 * the backend memory allocation.
1268 	 */
1269 	cmd->sense_reason = transport_generic_new_cmd(&cmd->se_cmd);
1270 	if (cmd->sense_reason)
1271 		return 1;
1272 
1273 	return 0;
1274 }
1275 EXPORT_SYMBOL(iscsit_process_scsi_cmd);
1276 
1277 static int
1278 iscsit_get_immediate_data(struct iscsi_cmd *cmd, struct iscsi_scsi_req *hdr,
1279 			  bool dump_payload)
1280 {
1281 	int cmdsn_ret = 0, immed_ret = IMMEDIATE_DATA_NORMAL_OPERATION;
1282 	int rc;
1283 
1284 	/*
1285 	 * Special case for Unsupported SAM WRITE Opcodes and ImmediateData=Yes.
1286 	 */
1287 	if (dump_payload) {
1288 		u32 length = min(cmd->se_cmd.data_length - cmd->write_data_done,
1289 				 cmd->first_burst_len);
1290 
1291 		pr_debug("Dumping min(%d - %d, %d) = %d bytes of immediate data\n",
1292 			 cmd->se_cmd.data_length, cmd->write_data_done,
1293 			 cmd->first_burst_len, length);
1294 		rc = iscsit_dump_data_payload(cmd->conn, length, 1);
1295 		pr_debug("Finished dumping immediate data\n");
1296 		if (rc < 0)
1297 			immed_ret = IMMEDIATE_DATA_CANNOT_RECOVER;
1298 	} else {
1299 		immed_ret = iscsit_handle_immediate_data(cmd, hdr,
1300 							 cmd->first_burst_len);
1301 	}
1302 
1303 	if (immed_ret == IMMEDIATE_DATA_NORMAL_OPERATION) {
1304 		/*
1305 		 * A PDU/CmdSN carrying Immediate Data passed
1306 		 * DataCRC, check against ExpCmdSN/MaxCmdSN if
1307 		 * Immediate Bit is not set.
1308 		 */
1309 		cmdsn_ret = iscsit_sequence_cmd(cmd->conn, cmd,
1310 					(unsigned char *)hdr, hdr->cmdsn);
1311 		if (cmdsn_ret == CMDSN_ERROR_CANNOT_RECOVER)
1312 			return -1;
1313 
1314 		if (cmd->sense_reason || cmdsn_ret == CMDSN_LOWER_THAN_EXP) {
1315 			target_put_sess_cmd(&cmd->se_cmd);
1316 
1317 			return 0;
1318 		} else if (cmd->unsolicited_data)
1319 			iscsit_set_unsolicited_dataout(cmd);
1320 
1321 	} else if (immed_ret == IMMEDIATE_DATA_ERL1_CRC_FAILURE) {
1322 		/*
1323 		 * Immediate Data failed DataCRC and ERL>=1,
1324 		 * silently drop this PDU and let the initiator
1325 		 * plug the CmdSN gap.
1326 		 *
1327 		 * FIXME: Send Unsolicited NOPIN with reserved
1328 		 * TTT here to help the initiator figure out
1329 		 * the missing CmdSN, although they should be
1330 		 * intelligent enough to determine the missing
1331 		 * CmdSN and issue a retry to plug the sequence.
1332 		 */
1333 		cmd->i_state = ISTATE_REMOVE;
1334 		iscsit_add_cmd_to_immediate_queue(cmd, cmd->conn, cmd->i_state);
1335 	} else /* immed_ret == IMMEDIATE_DATA_CANNOT_RECOVER */
1336 		return -1;
1337 
1338 	return 0;
1339 }
1340 
1341 static int
1342 iscsit_handle_scsi_cmd(struct iscsi_conn *conn, struct iscsi_cmd *cmd,
1343 			   unsigned char *buf)
1344 {
1345 	struct iscsi_scsi_req *hdr = (struct iscsi_scsi_req *)buf;
1346 	int rc, immed_data;
1347 	bool dump_payload = false;
1348 
1349 	rc = iscsit_setup_scsi_cmd(conn, cmd, buf);
1350 	if (rc < 0)
1351 		return 0;
1352 	/*
1353 	 * Allocation iovecs needed for struct socket operations for
1354 	 * traditional iSCSI block I/O.
1355 	 */
1356 	if (iscsit_allocate_iovecs(cmd) < 0) {
1357 		return iscsit_reject_cmd(cmd,
1358 				ISCSI_REASON_BOOKMARK_NO_RESOURCES, buf);
1359 	}
1360 	immed_data = cmd->immediate_data;
1361 
1362 	rc = iscsit_process_scsi_cmd(conn, cmd, hdr);
1363 	if (rc < 0)
1364 		return rc;
1365 	else if (rc > 0)
1366 		dump_payload = true;
1367 
1368 	if (!immed_data)
1369 		return 0;
1370 
1371 	return iscsit_get_immediate_data(cmd, hdr, dump_payload);
1372 }
1373 
1374 static u32 iscsit_do_crypto_hash_sg(
1375 	struct ahash_request *hash,
1376 	struct iscsi_cmd *cmd,
1377 	u32 data_offset,
1378 	u32 data_length,
1379 	u32 padding,
1380 	u8 *pad_bytes)
1381 {
1382 	u32 data_crc;
1383 	struct scatterlist *sg;
1384 	unsigned int page_off;
1385 
1386 	crypto_ahash_init(hash);
1387 
1388 	sg = cmd->first_data_sg;
1389 	page_off = cmd->first_data_sg_off;
1390 
1391 	while (data_length) {
1392 		u32 cur_len = min_t(u32, data_length, (sg->length - page_off));
1393 
1394 		ahash_request_set_crypt(hash, sg, NULL, cur_len);
1395 		crypto_ahash_update(hash);
1396 
1397 		data_length -= cur_len;
1398 		page_off = 0;
1399 		/* iscsit_map_iovec has already checked for invalid sg pointers */
1400 		sg = sg_next(sg);
1401 	}
1402 
1403 	if (padding) {
1404 		struct scatterlist pad_sg;
1405 
1406 		sg_init_one(&pad_sg, pad_bytes, padding);
1407 		ahash_request_set_crypt(hash, &pad_sg, (u8 *)&data_crc,
1408 					padding);
1409 		crypto_ahash_finup(hash);
1410 	} else {
1411 		ahash_request_set_crypt(hash, NULL, (u8 *)&data_crc, 0);
1412 		crypto_ahash_final(hash);
1413 	}
1414 
1415 	return data_crc;
1416 }
1417 
1418 static void iscsit_do_crypto_hash_buf(struct ahash_request *hash,
1419 	const void *buf, u32 payload_length, u32 padding,
1420 	const void *pad_bytes, void *data_crc)
1421 {
1422 	struct scatterlist sg[2];
1423 
1424 	sg_init_table(sg, ARRAY_SIZE(sg));
1425 	sg_set_buf(sg, buf, payload_length);
1426 	if (padding)
1427 		sg_set_buf(sg + 1, pad_bytes, padding);
1428 
1429 	ahash_request_set_crypt(hash, sg, data_crc, payload_length + padding);
1430 
1431 	crypto_ahash_digest(hash);
1432 }
1433 
1434 int
1435 __iscsit_check_dataout_hdr(struct iscsi_conn *conn, void *buf,
1436 			   struct iscsi_cmd *cmd, u32 payload_length,
1437 			   bool *success)
1438 {
1439 	struct iscsi_data *hdr = buf;
1440 	struct se_cmd *se_cmd;
1441 	int rc;
1442 
1443 	/* iSCSI write */
1444 	atomic_long_add(payload_length, &conn->sess->rx_data_octets);
1445 
1446 	pr_debug("Got DataOut ITT: 0x%08x, TTT: 0x%08x,"
1447 		" DataSN: 0x%08x, Offset: %u, Length: %u, CID: %hu\n",
1448 		hdr->itt, hdr->ttt, hdr->datasn, ntohl(hdr->offset),
1449 		payload_length, conn->cid);
1450 
1451 	if (cmd->cmd_flags & ICF_GOT_LAST_DATAOUT) {
1452 		pr_err("Command ITT: 0x%08x received DataOUT after"
1453 			" last DataOUT received, dumping payload\n",
1454 			cmd->init_task_tag);
1455 		return iscsit_dump_data_payload(conn, payload_length, 1);
1456 	}
1457 
1458 	if (cmd->data_direction != DMA_TO_DEVICE) {
1459 		pr_err("Command ITT: 0x%08x received DataOUT for a"
1460 			" NON-WRITE command.\n", cmd->init_task_tag);
1461 		return iscsit_dump_data_payload(conn, payload_length, 1);
1462 	}
1463 	se_cmd = &cmd->se_cmd;
1464 	iscsit_mod_dataout_timer(cmd);
1465 
1466 	if ((be32_to_cpu(hdr->offset) + payload_length) > cmd->se_cmd.data_length) {
1467 		pr_err("DataOut Offset: %u, Length %u greater than iSCSI Command EDTL %u, protocol error.\n",
1468 		       be32_to_cpu(hdr->offset), payload_length,
1469 		       cmd->se_cmd.data_length);
1470 		return iscsit_reject_cmd(cmd, ISCSI_REASON_BOOKMARK_INVALID, buf);
1471 	}
1472 
1473 	if (cmd->unsolicited_data) {
1474 		int dump_unsolicited_data = 0;
1475 
1476 		if (conn->sess->sess_ops->InitialR2T) {
1477 			pr_err("Received unexpected unsolicited data"
1478 				" while InitialR2T=Yes, protocol error.\n");
1479 			transport_send_check_condition_and_sense(&cmd->se_cmd,
1480 					TCM_UNEXPECTED_UNSOLICITED_DATA, 0);
1481 			return -1;
1482 		}
1483 		/*
1484 		 * Special case for dealing with Unsolicited DataOUT
1485 		 * and Unsupported SAM WRITE Opcodes and SE resource allocation
1486 		 * failures;
1487 		 */
1488 
1489 		/* Something's amiss if we're not in WRITE_PENDING state... */
1490 		WARN_ON(se_cmd->t_state != TRANSPORT_WRITE_PENDING);
1491 		if (!(se_cmd->se_cmd_flags & SCF_SUPPORTED_SAM_OPCODE))
1492 			dump_unsolicited_data = 1;
1493 
1494 		if (dump_unsolicited_data) {
1495 			/*
1496 			 * Check if a delayed TASK_ABORTED status needs to
1497 			 * be sent now if the ISCSI_FLAG_CMD_FINAL has been
1498 			 * received with the unsolicited data out.
1499 			 */
1500 			if (hdr->flags & ISCSI_FLAG_CMD_FINAL)
1501 				iscsit_stop_dataout_timer(cmd);
1502 
1503 			return iscsit_dump_data_payload(conn, payload_length, 1);
1504 		}
1505 	} else {
1506 		/*
1507 		 * For the normal solicited data path:
1508 		 *
1509 		 * Check for a delayed TASK_ABORTED status and dump any
1510 		 * incoming data out payload if one exists.  Also, when the
1511 		 * ISCSI_FLAG_CMD_FINAL is set to denote the end of the current
1512 		 * data out sequence, we decrement outstanding_r2ts.  Once
1513 		 * outstanding_r2ts reaches zero, go ahead and send the delayed
1514 		 * TASK_ABORTED status.
1515 		 */
1516 		if (se_cmd->transport_state & CMD_T_ABORTED) {
1517 			if (hdr->flags & ISCSI_FLAG_CMD_FINAL &&
1518 			    --cmd->outstanding_r2ts < 1)
1519 				iscsit_stop_dataout_timer(cmd);
1520 
1521 			return iscsit_dump_data_payload(conn, payload_length, 1);
1522 		}
1523 	}
1524 	/*
1525 	 * Perform DataSN, DataSequenceInOrder, DataPDUInOrder, and
1526 	 * within-command recovery checks before receiving the payload.
1527 	 */
1528 	rc = iscsit_check_pre_dataout(cmd, buf);
1529 	if (rc == DATAOUT_WITHIN_COMMAND_RECOVERY)
1530 		return 0;
1531 	else if (rc == DATAOUT_CANNOT_RECOVER)
1532 		return -1;
1533 	*success = true;
1534 	return 0;
1535 }
1536 EXPORT_SYMBOL(__iscsit_check_dataout_hdr);
1537 
1538 int
1539 iscsit_check_dataout_hdr(struct iscsi_conn *conn, void *buf,
1540 			 struct iscsi_cmd **out_cmd)
1541 {
1542 	struct iscsi_data *hdr = buf;
1543 	struct iscsi_cmd *cmd;
1544 	u32 payload_length = ntoh24(hdr->dlength);
1545 	int rc;
1546 	bool success = false;
1547 
1548 	if (!payload_length) {
1549 		pr_warn_ratelimited("DataOUT payload is ZERO, ignoring.\n");
1550 		return 0;
1551 	}
1552 
1553 	if (payload_length > conn->conn_ops->MaxXmitDataSegmentLength) {
1554 		pr_err_ratelimited("DataSegmentLength: %u is greater than"
1555 			" MaxXmitDataSegmentLength: %u\n", payload_length,
1556 			conn->conn_ops->MaxXmitDataSegmentLength);
1557 		return iscsit_add_reject(conn, ISCSI_REASON_PROTOCOL_ERROR, buf);
1558 	}
1559 
1560 	cmd = iscsit_find_cmd_from_itt_or_dump(conn, hdr->itt, payload_length);
1561 	if (!cmd)
1562 		return 0;
1563 
1564 	rc = __iscsit_check_dataout_hdr(conn, buf, cmd, payload_length, &success);
1565 
1566 	if (success)
1567 		*out_cmd = cmd;
1568 
1569 	return rc;
1570 }
1571 EXPORT_SYMBOL(iscsit_check_dataout_hdr);
1572 
1573 static int
1574 iscsit_get_dataout(struct iscsi_conn *conn, struct iscsi_cmd *cmd,
1575 		   struct iscsi_data *hdr)
1576 {
1577 	struct kvec *iov;
1578 	u32 checksum, iov_count = 0, padding = 0, rx_got = 0, rx_size = 0;
1579 	u32 payload_length;
1580 	int iov_ret, data_crc_failed = 0;
1581 
1582 	payload_length = min_t(u32, cmd->se_cmd.data_length,
1583 			       ntoh24(hdr->dlength));
1584 	rx_size += payload_length;
1585 	iov = &cmd->iov_data[0];
1586 
1587 	iov_ret = iscsit_map_iovec(cmd, iov, cmd->orig_iov_data_count - 2,
1588 				   be32_to_cpu(hdr->offset), payload_length);
1589 	if (iov_ret < 0)
1590 		return -1;
1591 
1592 	iov_count += iov_ret;
1593 
1594 	padding = ((-payload_length) & 3);
1595 	if (padding != 0) {
1596 		iov[iov_count].iov_base	= cmd->pad_bytes;
1597 		iov[iov_count++].iov_len = padding;
1598 		rx_size += padding;
1599 		pr_debug("Receiving %u padding bytes.\n", padding);
1600 	}
1601 
1602 	if (conn->conn_ops->DataDigest) {
1603 		iov[iov_count].iov_base = &checksum;
1604 		iov[iov_count++].iov_len = ISCSI_CRC_LEN;
1605 		rx_size += ISCSI_CRC_LEN;
1606 	}
1607 
1608 	WARN_ON_ONCE(iov_count > cmd->orig_iov_data_count);
1609 	rx_got = rx_data(conn, &cmd->iov_data[0], iov_count, rx_size);
1610 
1611 	iscsit_unmap_iovec(cmd);
1612 
1613 	if (rx_got != rx_size)
1614 		return -1;
1615 
1616 	if (conn->conn_ops->DataDigest) {
1617 		u32 data_crc;
1618 
1619 		data_crc = iscsit_do_crypto_hash_sg(conn->conn_rx_hash, cmd,
1620 						    be32_to_cpu(hdr->offset),
1621 						    payload_length, padding,
1622 						    cmd->pad_bytes);
1623 
1624 		if (checksum != data_crc) {
1625 			pr_err("ITT: 0x%08x, Offset: %u, Length: %u,"
1626 				" DataSN: 0x%08x, CRC32C DataDigest 0x%08x"
1627 				" does not match computed 0x%08x\n",
1628 				hdr->itt, hdr->offset, payload_length,
1629 				hdr->datasn, checksum, data_crc);
1630 			data_crc_failed = 1;
1631 		} else {
1632 			pr_debug("Got CRC32C DataDigest 0x%08x for"
1633 				" %u bytes of Data Out\n", checksum,
1634 				payload_length);
1635 		}
1636 	}
1637 
1638 	return data_crc_failed;
1639 }
1640 
1641 int
1642 iscsit_check_dataout_payload(struct iscsi_cmd *cmd, struct iscsi_data *hdr,
1643 			     bool data_crc_failed)
1644 {
1645 	struct iscsi_conn *conn = cmd->conn;
1646 	int rc, ooo_cmdsn;
1647 	/*
1648 	 * Increment post receive data and CRC values or perform
1649 	 * within-command recovery.
1650 	 */
1651 	rc = iscsit_check_post_dataout(cmd, (unsigned char *)hdr, data_crc_failed);
1652 	if ((rc == DATAOUT_NORMAL) || (rc == DATAOUT_WITHIN_COMMAND_RECOVERY))
1653 		return 0;
1654 	else if (rc == DATAOUT_SEND_R2T) {
1655 		iscsit_set_dataout_sequence_values(cmd);
1656 		conn->conn_transport->iscsit_get_dataout(conn, cmd, false);
1657 	} else if (rc == DATAOUT_SEND_TO_TRANSPORT) {
1658 		/*
1659 		 * Handle extra special case for out of order
1660 		 * Unsolicited Data Out.
1661 		 */
1662 		spin_lock_bh(&cmd->istate_lock);
1663 		ooo_cmdsn = (cmd->cmd_flags & ICF_OOO_CMDSN);
1664 		cmd->cmd_flags |= ICF_GOT_LAST_DATAOUT;
1665 		cmd->i_state = ISTATE_RECEIVED_LAST_DATAOUT;
1666 		spin_unlock_bh(&cmd->istate_lock);
1667 
1668 		iscsit_stop_dataout_timer(cmd);
1669 		if (ooo_cmdsn)
1670 			return 0;
1671 		target_execute_cmd(&cmd->se_cmd);
1672 		return 0;
1673 	} else /* DATAOUT_CANNOT_RECOVER */
1674 		return -1;
1675 
1676 	return 0;
1677 }
1678 EXPORT_SYMBOL(iscsit_check_dataout_payload);
1679 
1680 static int iscsit_handle_data_out(struct iscsi_conn *conn, unsigned char *buf)
1681 {
1682 	struct iscsi_cmd *cmd = NULL;
1683 	struct iscsi_data *hdr = (struct iscsi_data *)buf;
1684 	int rc;
1685 	bool data_crc_failed = false;
1686 
1687 	rc = iscsit_check_dataout_hdr(conn, buf, &cmd);
1688 	if (rc < 0)
1689 		return 0;
1690 	else if (!cmd)
1691 		return 0;
1692 
1693 	rc = iscsit_get_dataout(conn, cmd, hdr);
1694 	if (rc < 0)
1695 		return rc;
1696 	else if (rc > 0)
1697 		data_crc_failed = true;
1698 
1699 	return iscsit_check_dataout_payload(cmd, hdr, data_crc_failed);
1700 }
1701 
1702 int iscsit_setup_nop_out(struct iscsi_conn *conn, struct iscsi_cmd *cmd,
1703 			 struct iscsi_nopout *hdr)
1704 {
1705 	u32 payload_length = ntoh24(hdr->dlength);
1706 
1707 	if (!(hdr->flags & ISCSI_FLAG_CMD_FINAL)) {
1708 		pr_err("NopOUT Flag's, Left Most Bit not set, protocol error.\n");
1709 		if (!cmd)
1710 			return iscsit_add_reject(conn, ISCSI_REASON_PROTOCOL_ERROR,
1711 						 (unsigned char *)hdr);
1712 
1713 		return iscsit_reject_cmd(cmd, ISCSI_REASON_PROTOCOL_ERROR,
1714 					 (unsigned char *)hdr);
1715 	}
1716 
1717 	if (hdr->itt == RESERVED_ITT && !(hdr->opcode & ISCSI_OP_IMMEDIATE)) {
1718 		pr_err("NOPOUT ITT is reserved, but Immediate Bit is"
1719 			" not set, protocol error.\n");
1720 		if (!cmd)
1721 			return iscsit_add_reject(conn, ISCSI_REASON_PROTOCOL_ERROR,
1722 						 (unsigned char *)hdr);
1723 
1724 		return iscsit_reject_cmd(cmd, ISCSI_REASON_PROTOCOL_ERROR,
1725 					 (unsigned char *)hdr);
1726 	}
1727 
1728 	if (payload_length > conn->conn_ops->MaxXmitDataSegmentLength) {
1729 		pr_err("NOPOUT Ping Data DataSegmentLength: %u is"
1730 			" greater than MaxXmitDataSegmentLength: %u, protocol"
1731 			" error.\n", payload_length,
1732 			conn->conn_ops->MaxXmitDataSegmentLength);
1733 		if (!cmd)
1734 			return iscsit_add_reject(conn, ISCSI_REASON_PROTOCOL_ERROR,
1735 						 (unsigned char *)hdr);
1736 
1737 		return iscsit_reject_cmd(cmd, ISCSI_REASON_PROTOCOL_ERROR,
1738 					 (unsigned char *)hdr);
1739 	}
1740 
1741 	pr_debug("Got NOPOUT Ping %s ITT: 0x%08x, TTT: 0x%08x,"
1742 		" CmdSN: 0x%08x, ExpStatSN: 0x%08x, Length: %u\n",
1743 		hdr->itt == RESERVED_ITT ? "Response" : "Request",
1744 		hdr->itt, hdr->ttt, hdr->cmdsn, hdr->exp_statsn,
1745 		payload_length);
1746 	/*
1747 	 * This is not a response to a Unsolicited NopIN, which means
1748 	 * it can either be a NOPOUT ping request (with a valid ITT),
1749 	 * or a NOPOUT not requesting a NOPIN (with a reserved ITT).
1750 	 * Either way, make sure we allocate an struct iscsi_cmd, as both
1751 	 * can contain ping data.
1752 	 */
1753 	if (hdr->ttt == cpu_to_be32(0xFFFFFFFF)) {
1754 		cmd->iscsi_opcode	= ISCSI_OP_NOOP_OUT;
1755 		cmd->i_state		= ISTATE_SEND_NOPIN;
1756 		cmd->immediate_cmd	= ((hdr->opcode & ISCSI_OP_IMMEDIATE) ?
1757 						1 : 0);
1758 		conn->sess->init_task_tag = cmd->init_task_tag = hdr->itt;
1759 		cmd->targ_xfer_tag	= 0xFFFFFFFF;
1760 		cmd->cmd_sn		= be32_to_cpu(hdr->cmdsn);
1761 		cmd->exp_stat_sn	= be32_to_cpu(hdr->exp_statsn);
1762 		cmd->data_direction	= DMA_NONE;
1763 	}
1764 
1765 	return 0;
1766 }
1767 EXPORT_SYMBOL(iscsit_setup_nop_out);
1768 
1769 int iscsit_process_nop_out(struct iscsi_conn *conn, struct iscsi_cmd *cmd,
1770 			   struct iscsi_nopout *hdr)
1771 {
1772 	struct iscsi_cmd *cmd_p = NULL;
1773 	int cmdsn_ret = 0;
1774 	/*
1775 	 * Initiator is expecting a NopIN ping reply..
1776 	 */
1777 	if (hdr->itt != RESERVED_ITT) {
1778 		if (!cmd)
1779 			return iscsit_add_reject(conn, ISCSI_REASON_PROTOCOL_ERROR,
1780 						(unsigned char *)hdr);
1781 
1782 		spin_lock_bh(&conn->cmd_lock);
1783 		list_add_tail(&cmd->i_conn_node, &conn->conn_cmd_list);
1784 		spin_unlock_bh(&conn->cmd_lock);
1785 
1786 		iscsit_ack_from_expstatsn(conn, be32_to_cpu(hdr->exp_statsn));
1787 
1788 		if (hdr->opcode & ISCSI_OP_IMMEDIATE) {
1789 			iscsit_add_cmd_to_response_queue(cmd, conn,
1790 							 cmd->i_state);
1791 			return 0;
1792 		}
1793 
1794 		cmdsn_ret = iscsit_sequence_cmd(conn, cmd,
1795 				(unsigned char *)hdr, hdr->cmdsn);
1796                 if (cmdsn_ret == CMDSN_LOWER_THAN_EXP)
1797 			return 0;
1798 		if (cmdsn_ret == CMDSN_ERROR_CANNOT_RECOVER)
1799 			return -1;
1800 
1801 		return 0;
1802 	}
1803 	/*
1804 	 * This was a response to a unsolicited NOPIN ping.
1805 	 */
1806 	if (hdr->ttt != cpu_to_be32(0xFFFFFFFF)) {
1807 		cmd_p = iscsit_find_cmd_from_ttt(conn, be32_to_cpu(hdr->ttt));
1808 		if (!cmd_p)
1809 			return -EINVAL;
1810 
1811 		iscsit_stop_nopin_response_timer(conn);
1812 
1813 		cmd_p->i_state = ISTATE_REMOVE;
1814 		iscsit_add_cmd_to_immediate_queue(cmd_p, conn, cmd_p->i_state);
1815 
1816 		iscsit_start_nopin_timer(conn);
1817 		return 0;
1818 	}
1819 	/*
1820 	 * Otherwise, initiator is not expecting a NOPIN is response.
1821 	 * Just ignore for now.
1822 	 */
1823 
1824 	if (cmd)
1825 		iscsit_free_cmd(cmd, false);
1826 
1827         return 0;
1828 }
1829 EXPORT_SYMBOL(iscsit_process_nop_out);
1830 
1831 static int iscsit_handle_nop_out(struct iscsi_conn *conn, struct iscsi_cmd *cmd,
1832 				 unsigned char *buf)
1833 {
1834 	unsigned char *ping_data = NULL;
1835 	struct iscsi_nopout *hdr = (struct iscsi_nopout *)buf;
1836 	struct kvec *iov = NULL;
1837 	u32 payload_length = ntoh24(hdr->dlength);
1838 	int ret;
1839 
1840 	ret = iscsit_setup_nop_out(conn, cmd, hdr);
1841 	if (ret < 0)
1842 		return 0;
1843 	/*
1844 	 * Handle NOP-OUT payload for traditional iSCSI sockets
1845 	 */
1846 	if (payload_length && hdr->ttt == cpu_to_be32(0xFFFFFFFF)) {
1847 		u32 checksum, data_crc, padding = 0;
1848 		int niov = 0, rx_got, rx_size = payload_length;
1849 
1850 		ping_data = kzalloc(payload_length + 1, GFP_KERNEL);
1851 		if (!ping_data) {
1852 			ret = -1;
1853 			goto out;
1854 		}
1855 
1856 		iov = &cmd->iov_misc[0];
1857 		iov[niov].iov_base	= ping_data;
1858 		iov[niov++].iov_len	= payload_length;
1859 
1860 		padding = ((-payload_length) & 3);
1861 		if (padding != 0) {
1862 			pr_debug("Receiving %u additional bytes"
1863 				" for padding.\n", padding);
1864 			iov[niov].iov_base	= &cmd->pad_bytes;
1865 			iov[niov++].iov_len	= padding;
1866 			rx_size += padding;
1867 		}
1868 		if (conn->conn_ops->DataDigest) {
1869 			iov[niov].iov_base	= &checksum;
1870 			iov[niov++].iov_len	= ISCSI_CRC_LEN;
1871 			rx_size += ISCSI_CRC_LEN;
1872 		}
1873 
1874 		WARN_ON_ONCE(niov > ARRAY_SIZE(cmd->iov_misc));
1875 		rx_got = rx_data(conn, &cmd->iov_misc[0], niov, rx_size);
1876 		if (rx_got != rx_size) {
1877 			ret = -1;
1878 			goto out;
1879 		}
1880 
1881 		if (conn->conn_ops->DataDigest) {
1882 			iscsit_do_crypto_hash_buf(conn->conn_rx_hash, ping_data,
1883 						  payload_length, padding,
1884 						  cmd->pad_bytes, &data_crc);
1885 
1886 			if (checksum != data_crc) {
1887 				pr_err("Ping data CRC32C DataDigest"
1888 				" 0x%08x does not match computed 0x%08x\n",
1889 					checksum, data_crc);
1890 				if (!conn->sess->sess_ops->ErrorRecoveryLevel) {
1891 					pr_err("Unable to recover from"
1892 					" NOPOUT Ping DataCRC failure while in"
1893 						" ERL=0.\n");
1894 					ret = -1;
1895 					goto out;
1896 				} else {
1897 					/*
1898 					 * Silently drop this PDU and let the
1899 					 * initiator plug the CmdSN gap.
1900 					 */
1901 					pr_debug("Dropping NOPOUT"
1902 					" Command CmdSN: 0x%08x due to"
1903 					" DataCRC error.\n", hdr->cmdsn);
1904 					ret = 0;
1905 					goto out;
1906 				}
1907 			} else {
1908 				pr_debug("Got CRC32C DataDigest"
1909 				" 0x%08x for %u bytes of ping data.\n",
1910 					checksum, payload_length);
1911 			}
1912 		}
1913 
1914 		ping_data[payload_length] = '\0';
1915 		/*
1916 		 * Attach ping data to struct iscsi_cmd->buf_ptr.
1917 		 */
1918 		cmd->buf_ptr = ping_data;
1919 		cmd->buf_ptr_size = payload_length;
1920 
1921 		pr_debug("Got %u bytes of NOPOUT ping"
1922 			" data.\n", payload_length);
1923 		pr_debug("Ping Data: \"%s\"\n", ping_data);
1924 	}
1925 
1926 	return iscsit_process_nop_out(conn, cmd, hdr);
1927 out:
1928 	if (cmd)
1929 		iscsit_free_cmd(cmd, false);
1930 
1931 	kfree(ping_data);
1932 	return ret;
1933 }
1934 
1935 static enum tcm_tmreq_table iscsit_convert_tmf(u8 iscsi_tmf)
1936 {
1937 	switch (iscsi_tmf) {
1938 	case ISCSI_TM_FUNC_ABORT_TASK:
1939 		return TMR_ABORT_TASK;
1940 	case ISCSI_TM_FUNC_ABORT_TASK_SET:
1941 		return TMR_ABORT_TASK_SET;
1942 	case ISCSI_TM_FUNC_CLEAR_ACA:
1943 		return TMR_CLEAR_ACA;
1944 	case ISCSI_TM_FUNC_CLEAR_TASK_SET:
1945 		return TMR_CLEAR_TASK_SET;
1946 	case ISCSI_TM_FUNC_LOGICAL_UNIT_RESET:
1947 		return TMR_LUN_RESET;
1948 	case ISCSI_TM_FUNC_TARGET_WARM_RESET:
1949 		return TMR_TARGET_WARM_RESET;
1950 	case ISCSI_TM_FUNC_TARGET_COLD_RESET:
1951 		return TMR_TARGET_COLD_RESET;
1952 	default:
1953 		return TMR_UNKNOWN;
1954 	}
1955 }
1956 
1957 int
1958 iscsit_handle_task_mgt_cmd(struct iscsi_conn *conn, struct iscsi_cmd *cmd,
1959 			   unsigned char *buf)
1960 {
1961 	struct se_tmr_req *se_tmr;
1962 	struct iscsi_tmr_req *tmr_req;
1963 	struct iscsi_tm *hdr;
1964 	int out_of_order_cmdsn = 0, ret;
1965 	u8 function, tcm_function = TMR_UNKNOWN;
1966 
1967 	hdr			= (struct iscsi_tm *) buf;
1968 	hdr->flags &= ~ISCSI_FLAG_CMD_FINAL;
1969 	function = hdr->flags;
1970 
1971 	pr_debug("Got Task Management Request ITT: 0x%08x, CmdSN:"
1972 		" 0x%08x, Function: 0x%02x, RefTaskTag: 0x%08x, RefCmdSN:"
1973 		" 0x%08x, CID: %hu\n", hdr->itt, hdr->cmdsn, function,
1974 		hdr->rtt, hdr->refcmdsn, conn->cid);
1975 
1976 	if ((function != ISCSI_TM_FUNC_ABORT_TASK) &&
1977 	    ((function != ISCSI_TM_FUNC_TASK_REASSIGN) &&
1978 	     hdr->rtt != RESERVED_ITT)) {
1979 		pr_err("RefTaskTag should be set to 0xFFFFFFFF.\n");
1980 		hdr->rtt = RESERVED_ITT;
1981 	}
1982 
1983 	if ((function == ISCSI_TM_FUNC_TASK_REASSIGN) &&
1984 			!(hdr->opcode & ISCSI_OP_IMMEDIATE)) {
1985 		pr_err("Task Management Request TASK_REASSIGN not"
1986 			" issued as immediate command, bad iSCSI Initiator"
1987 				"implementation\n");
1988 		return iscsit_add_reject_cmd(cmd,
1989 					     ISCSI_REASON_PROTOCOL_ERROR, buf);
1990 	}
1991 	if ((function != ISCSI_TM_FUNC_ABORT_TASK) &&
1992 	    be32_to_cpu(hdr->refcmdsn) != ISCSI_RESERVED_TAG)
1993 		hdr->refcmdsn = cpu_to_be32(ISCSI_RESERVED_TAG);
1994 
1995 	cmd->data_direction = DMA_NONE;
1996 	cmd->tmr_req = kzalloc(sizeof(*cmd->tmr_req), GFP_KERNEL);
1997 	if (!cmd->tmr_req) {
1998 		return iscsit_add_reject_cmd(cmd,
1999 					     ISCSI_REASON_BOOKMARK_NO_RESOURCES,
2000 					     buf);
2001 	}
2002 
2003 	transport_init_se_cmd(&cmd->se_cmd, &iscsi_ops,
2004 			      conn->sess->se_sess, 0, DMA_NONE,
2005 			      TCM_SIMPLE_TAG, cmd->sense_buffer + 2);
2006 
2007 	if (target_get_sess_cmd(&cmd->se_cmd, true) < 0)
2008 		return iscsit_add_reject_cmd(cmd,
2009 				ISCSI_REASON_WAITING_FOR_LOGOUT, buf);
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 					       scsilun_to_int(&hdr->lun));
2047 		if (ret < 0) {
2048 			se_tmr->response = ISCSI_TMF_RSP_NO_LUN;
2049 			goto attach;
2050 		}
2051 	}
2052 
2053 	switch (function) {
2054 	case ISCSI_TM_FUNC_ABORT_TASK:
2055 		se_tmr->response = iscsit_tmr_abort_task(cmd, buf);
2056 		if (se_tmr->response)
2057 			goto attach;
2058 		break;
2059 	case ISCSI_TM_FUNC_ABORT_TASK_SET:
2060 	case ISCSI_TM_FUNC_CLEAR_ACA:
2061 	case ISCSI_TM_FUNC_CLEAR_TASK_SET:
2062 	case ISCSI_TM_FUNC_LOGICAL_UNIT_RESET:
2063 		break;
2064 	case ISCSI_TM_FUNC_TARGET_WARM_RESET:
2065 		if (iscsit_tmr_task_warm_reset(conn, tmr_req, buf) < 0) {
2066 			se_tmr->response = ISCSI_TMF_RSP_AUTH_FAILED;
2067 			goto attach;
2068 		}
2069 		break;
2070 	case ISCSI_TM_FUNC_TARGET_COLD_RESET:
2071 		if (iscsit_tmr_task_cold_reset(conn, tmr_req, buf) < 0) {
2072 			se_tmr->response = ISCSI_TMF_RSP_AUTH_FAILED;
2073 			goto attach;
2074 		}
2075 		break;
2076 	case ISCSI_TM_FUNC_TASK_REASSIGN:
2077 		se_tmr->response = iscsit_tmr_task_reassign(cmd, buf);
2078 		/*
2079 		 * Perform sanity checks on the ExpDataSN only if the
2080 		 * TASK_REASSIGN was successful.
2081 		 */
2082 		if (se_tmr->response)
2083 			break;
2084 
2085 		if (iscsit_check_task_reassign_expdatasn(tmr_req, conn) < 0)
2086 			return iscsit_add_reject_cmd(cmd,
2087 					ISCSI_REASON_BOOKMARK_INVALID, buf);
2088 		break;
2089 	default:
2090 		pr_err("Unknown TMR function: 0x%02x, protocol"
2091 			" error.\n", function);
2092 		se_tmr->response = ISCSI_TMF_RSP_NOT_SUPPORTED;
2093 		goto attach;
2094 	}
2095 
2096 	if ((function != ISCSI_TM_FUNC_TASK_REASSIGN) &&
2097 	    (se_tmr->response == ISCSI_TMF_RSP_COMPLETE))
2098 		se_tmr->call_transport = 1;
2099 attach:
2100 	spin_lock_bh(&conn->cmd_lock);
2101 	list_add_tail(&cmd->i_conn_node, &conn->conn_cmd_list);
2102 	spin_unlock_bh(&conn->cmd_lock);
2103 
2104 	if (!(hdr->opcode & ISCSI_OP_IMMEDIATE)) {
2105 		int cmdsn_ret = iscsit_sequence_cmd(conn, cmd, buf, hdr->cmdsn);
2106 		if (cmdsn_ret == CMDSN_HIGHER_THAN_EXP) {
2107 			out_of_order_cmdsn = 1;
2108 		} else if (cmdsn_ret == CMDSN_LOWER_THAN_EXP) {
2109 			target_put_sess_cmd(&cmd->se_cmd);
2110 			return 0;
2111 		} else if (cmdsn_ret == CMDSN_ERROR_CANNOT_RECOVER) {
2112 			return -1;
2113 		}
2114 	}
2115 	iscsit_ack_from_expstatsn(conn, be32_to_cpu(hdr->exp_statsn));
2116 
2117 	if (out_of_order_cmdsn || !(hdr->opcode & ISCSI_OP_IMMEDIATE))
2118 		return 0;
2119 	/*
2120 	 * Found the referenced task, send to transport for processing.
2121 	 */
2122 	if (se_tmr->call_transport)
2123 		return transport_generic_handle_tmr(&cmd->se_cmd);
2124 
2125 	/*
2126 	 * Could not find the referenced LUN, task, or Task Management
2127 	 * command not authorized or supported.  Change state and
2128 	 * let the tx_thread send the response.
2129 	 *
2130 	 * For connection recovery, this is also the default action for
2131 	 * TMR TASK_REASSIGN.
2132 	 */
2133 	iscsit_add_cmd_to_response_queue(cmd, conn, cmd->i_state);
2134 	target_put_sess_cmd(&cmd->se_cmd);
2135 	return 0;
2136 }
2137 EXPORT_SYMBOL(iscsit_handle_task_mgt_cmd);
2138 
2139 /* #warning FIXME: Support Text Command parameters besides SendTargets */
2140 int
2141 iscsit_setup_text_cmd(struct iscsi_conn *conn, struct iscsi_cmd *cmd,
2142 		      struct iscsi_text *hdr)
2143 {
2144 	u32 payload_length = ntoh24(hdr->dlength);
2145 
2146 	if (payload_length > conn->conn_ops->MaxXmitDataSegmentLength) {
2147 		pr_err("Unable to accept text parameter length: %u"
2148 			"greater than MaxXmitDataSegmentLength %u.\n",
2149 		       payload_length, conn->conn_ops->MaxXmitDataSegmentLength);
2150 		return iscsit_reject_cmd(cmd, ISCSI_REASON_PROTOCOL_ERROR,
2151 					 (unsigned char *)hdr);
2152 	}
2153 
2154 	if (!(hdr->flags & ISCSI_FLAG_CMD_FINAL) ||
2155 	     (hdr->flags & ISCSI_FLAG_TEXT_CONTINUE)) {
2156 		pr_err("Multi sequence text commands currently not supported\n");
2157 		return iscsit_reject_cmd(cmd, ISCSI_REASON_CMD_NOT_SUPPORTED,
2158 					(unsigned char *)hdr);
2159 	}
2160 
2161 	pr_debug("Got Text Request: ITT: 0x%08x, CmdSN: 0x%08x,"
2162 		" ExpStatSN: 0x%08x, Length: %u\n", hdr->itt, hdr->cmdsn,
2163 		hdr->exp_statsn, payload_length);
2164 
2165 	cmd->iscsi_opcode	= ISCSI_OP_TEXT;
2166 	cmd->i_state		= ISTATE_SEND_TEXTRSP;
2167 	cmd->immediate_cmd	= ((hdr->opcode & ISCSI_OP_IMMEDIATE) ? 1 : 0);
2168 	conn->sess->init_task_tag = cmd->init_task_tag  = hdr->itt;
2169 	cmd->targ_xfer_tag	= 0xFFFFFFFF;
2170 	cmd->cmd_sn		= be32_to_cpu(hdr->cmdsn);
2171 	cmd->exp_stat_sn	= be32_to_cpu(hdr->exp_statsn);
2172 	cmd->data_direction	= DMA_NONE;
2173 	kfree(cmd->text_in_ptr);
2174 	cmd->text_in_ptr	= NULL;
2175 
2176 	return 0;
2177 }
2178 EXPORT_SYMBOL(iscsit_setup_text_cmd);
2179 
2180 int
2181 iscsit_process_text_cmd(struct iscsi_conn *conn, struct iscsi_cmd *cmd,
2182 			struct iscsi_text *hdr)
2183 {
2184 	unsigned char *text_in = cmd->text_in_ptr, *text_ptr;
2185 	int cmdsn_ret;
2186 
2187 	if (!text_in) {
2188 		cmd->targ_xfer_tag = be32_to_cpu(hdr->ttt);
2189 		if (cmd->targ_xfer_tag == 0xFFFFFFFF) {
2190 			pr_err("Unable to locate text_in buffer for sendtargets"
2191 			       " discovery\n");
2192 			goto reject;
2193 		}
2194 		goto empty_sendtargets;
2195 	}
2196 	if (strncmp("SendTargets=", text_in, 12) != 0) {
2197 		pr_err("Received Text Data that is not"
2198 			" SendTargets, cannot continue.\n");
2199 		goto reject;
2200 	}
2201 	/* '=' confirmed in strncmp */
2202 	text_ptr = strchr(text_in, '=');
2203 	BUG_ON(!text_ptr);
2204 	if (!strncmp("=All", text_ptr, 5)) {
2205 		cmd->cmd_flags |= ICF_SENDTARGETS_ALL;
2206 	} else if (!strncmp("=iqn.", text_ptr, 5) ||
2207 		   !strncmp("=eui.", text_ptr, 5)) {
2208 		cmd->cmd_flags |= ICF_SENDTARGETS_SINGLE;
2209 	} else {
2210 		pr_err("Unable to locate valid SendTargets%s value\n",
2211 		       text_ptr);
2212 		goto reject;
2213 	}
2214 
2215 	spin_lock_bh(&conn->cmd_lock);
2216 	list_add_tail(&cmd->i_conn_node, &conn->conn_cmd_list);
2217 	spin_unlock_bh(&conn->cmd_lock);
2218 
2219 empty_sendtargets:
2220 	iscsit_ack_from_expstatsn(conn, be32_to_cpu(hdr->exp_statsn));
2221 
2222 	if (!(hdr->opcode & ISCSI_OP_IMMEDIATE)) {
2223 		cmdsn_ret = iscsit_sequence_cmd(conn, cmd,
2224 				(unsigned char *)hdr, hdr->cmdsn);
2225 		if (cmdsn_ret == CMDSN_ERROR_CANNOT_RECOVER)
2226 			return -1;
2227 
2228 		return 0;
2229 	}
2230 
2231 	return iscsit_execute_cmd(cmd, 0);
2232 
2233 reject:
2234 	return iscsit_reject_cmd(cmd, ISCSI_REASON_PROTOCOL_ERROR,
2235 				 (unsigned char *)hdr);
2236 }
2237 EXPORT_SYMBOL(iscsit_process_text_cmd);
2238 
2239 static int
2240 iscsit_handle_text_cmd(struct iscsi_conn *conn, struct iscsi_cmd *cmd,
2241 		       unsigned char *buf)
2242 {
2243 	struct iscsi_text *hdr = (struct iscsi_text *)buf;
2244 	char *text_in = NULL;
2245 	u32 payload_length = ntoh24(hdr->dlength);
2246 	int rx_size, rc;
2247 
2248 	rc = iscsit_setup_text_cmd(conn, cmd, hdr);
2249 	if (rc < 0)
2250 		return 0;
2251 
2252 	rx_size = payload_length;
2253 	if (payload_length) {
2254 		u32 checksum = 0, data_crc = 0;
2255 		u32 padding = 0;
2256 		int niov = 0, rx_got;
2257 		struct kvec iov[2];
2258 
2259 		rx_size = ALIGN(payload_length, 4);
2260 		text_in = kzalloc(rx_size, GFP_KERNEL);
2261 		if (!text_in)
2262 			goto reject;
2263 
2264 		cmd->text_in_ptr = text_in;
2265 
2266 		memset(iov, 0, sizeof(iov));
2267 		iov[niov].iov_base	= text_in;
2268 		iov[niov++].iov_len	= rx_size;
2269 
2270 		padding = rx_size - payload_length;
2271 		if (padding)
2272 			pr_debug("Receiving %u additional bytes"
2273 					" for padding.\n", padding);
2274 		if (conn->conn_ops->DataDigest) {
2275 			iov[niov].iov_base	= &checksum;
2276 			iov[niov++].iov_len	= ISCSI_CRC_LEN;
2277 			rx_size += ISCSI_CRC_LEN;
2278 		}
2279 
2280 		WARN_ON_ONCE(niov > ARRAY_SIZE(iov));
2281 		rx_got = rx_data(conn, &iov[0], niov, rx_size);
2282 		if (rx_got != rx_size)
2283 			goto reject;
2284 
2285 		if (conn->conn_ops->DataDigest) {
2286 			iscsit_do_crypto_hash_buf(conn->conn_rx_hash,
2287 						  text_in, rx_size, 0, NULL,
2288 						  &data_crc);
2289 
2290 			if (checksum != data_crc) {
2291 				pr_err("Text data CRC32C DataDigest"
2292 					" 0x%08x does not match computed"
2293 					" 0x%08x\n", checksum, data_crc);
2294 				if (!conn->sess->sess_ops->ErrorRecoveryLevel) {
2295 					pr_err("Unable to recover from"
2296 					" Text Data digest failure while in"
2297 						" ERL=0.\n");
2298 					goto reject;
2299 				} else {
2300 					/*
2301 					 * Silently drop this PDU and let the
2302 					 * initiator plug the CmdSN gap.
2303 					 */
2304 					pr_debug("Dropping Text"
2305 					" Command CmdSN: 0x%08x due to"
2306 					" DataCRC error.\n", hdr->cmdsn);
2307 					kfree(text_in);
2308 					return 0;
2309 				}
2310 			} else {
2311 				pr_debug("Got CRC32C DataDigest"
2312 					" 0x%08x for %u bytes of text data.\n",
2313 						checksum, payload_length);
2314 			}
2315 		}
2316 		text_in[payload_length - 1] = '\0';
2317 		pr_debug("Successfully read %d bytes of text"
2318 				" data.\n", payload_length);
2319 	}
2320 
2321 	return iscsit_process_text_cmd(conn, cmd, hdr);
2322 
2323 reject:
2324 	kfree(cmd->text_in_ptr);
2325 	cmd->text_in_ptr = NULL;
2326 	return iscsit_reject_cmd(cmd, ISCSI_REASON_PROTOCOL_ERROR, buf);
2327 }
2328 
2329 int iscsit_logout_closesession(struct iscsi_cmd *cmd, struct iscsi_conn *conn)
2330 {
2331 	struct iscsi_conn *conn_p;
2332 	struct iscsi_session *sess = conn->sess;
2333 
2334 	pr_debug("Received logout request CLOSESESSION on CID: %hu"
2335 		" for SID: %u.\n", conn->cid, conn->sess->sid);
2336 
2337 	atomic_set(&sess->session_logout, 1);
2338 	atomic_set(&conn->conn_logout_remove, 1);
2339 	conn->conn_logout_reason = ISCSI_LOGOUT_REASON_CLOSE_SESSION;
2340 
2341 	iscsit_inc_conn_usage_count(conn);
2342 	iscsit_inc_session_usage_count(sess);
2343 
2344 	spin_lock_bh(&sess->conn_lock);
2345 	list_for_each_entry(conn_p, &sess->sess_conn_list, conn_list) {
2346 		if (conn_p->conn_state != TARG_CONN_STATE_LOGGED_IN)
2347 			continue;
2348 
2349 		pr_debug("Moving to TARG_CONN_STATE_IN_LOGOUT.\n");
2350 		conn_p->conn_state = TARG_CONN_STATE_IN_LOGOUT;
2351 	}
2352 	spin_unlock_bh(&sess->conn_lock);
2353 
2354 	iscsit_add_cmd_to_response_queue(cmd, conn, cmd->i_state);
2355 
2356 	return 0;
2357 }
2358 
2359 int iscsit_logout_closeconnection(struct iscsi_cmd *cmd, struct iscsi_conn *conn)
2360 {
2361 	struct iscsi_conn *l_conn;
2362 	struct iscsi_session *sess = conn->sess;
2363 
2364 	pr_debug("Received logout request CLOSECONNECTION for CID:"
2365 		" %hu on CID: %hu.\n", cmd->logout_cid, conn->cid);
2366 
2367 	/*
2368 	 * A Logout Request with a CLOSECONNECTION reason code for a CID
2369 	 * can arrive on a connection with a differing CID.
2370 	 */
2371 	if (conn->cid == cmd->logout_cid) {
2372 		spin_lock_bh(&conn->state_lock);
2373 		pr_debug("Moving to TARG_CONN_STATE_IN_LOGOUT.\n");
2374 		conn->conn_state = TARG_CONN_STATE_IN_LOGOUT;
2375 
2376 		atomic_set(&conn->conn_logout_remove, 1);
2377 		conn->conn_logout_reason = ISCSI_LOGOUT_REASON_CLOSE_CONNECTION;
2378 		iscsit_inc_conn_usage_count(conn);
2379 
2380 		spin_unlock_bh(&conn->state_lock);
2381 	} else {
2382 		/*
2383 		 * Handle all different cid CLOSECONNECTION requests in
2384 		 * iscsit_logout_post_handler_diffcid() as to give enough
2385 		 * time for any non immediate command's CmdSN to be
2386 		 * acknowledged on the connection in question.
2387 		 *
2388 		 * Here we simply make sure the CID is still around.
2389 		 */
2390 		l_conn = iscsit_get_conn_from_cid(sess,
2391 				cmd->logout_cid);
2392 		if (!l_conn) {
2393 			cmd->logout_response = ISCSI_LOGOUT_CID_NOT_FOUND;
2394 			iscsit_add_cmd_to_response_queue(cmd, conn,
2395 					cmd->i_state);
2396 			return 0;
2397 		}
2398 
2399 		iscsit_dec_conn_usage_count(l_conn);
2400 	}
2401 
2402 	iscsit_add_cmd_to_response_queue(cmd, conn, cmd->i_state);
2403 
2404 	return 0;
2405 }
2406 
2407 int iscsit_logout_removeconnforrecovery(struct iscsi_cmd *cmd, struct iscsi_conn *conn)
2408 {
2409 	struct iscsi_session *sess = conn->sess;
2410 
2411 	pr_debug("Received explicit REMOVECONNFORRECOVERY logout for"
2412 		" CID: %hu on CID: %hu.\n", cmd->logout_cid, conn->cid);
2413 
2414 	if (sess->sess_ops->ErrorRecoveryLevel != 2) {
2415 		pr_err("Received Logout Request REMOVECONNFORRECOVERY"
2416 			" while ERL!=2.\n");
2417 		cmd->logout_response = ISCSI_LOGOUT_RECOVERY_UNSUPPORTED;
2418 		iscsit_add_cmd_to_response_queue(cmd, conn, cmd->i_state);
2419 		return 0;
2420 	}
2421 
2422 	if (conn->cid == cmd->logout_cid) {
2423 		pr_err("Received Logout Request REMOVECONNFORRECOVERY"
2424 			" with CID: %hu on CID: %hu, implementation error.\n",
2425 				cmd->logout_cid, conn->cid);
2426 		cmd->logout_response = ISCSI_LOGOUT_CLEANUP_FAILED;
2427 		iscsit_add_cmd_to_response_queue(cmd, conn, cmd->i_state);
2428 		return 0;
2429 	}
2430 
2431 	iscsit_add_cmd_to_response_queue(cmd, conn, cmd->i_state);
2432 
2433 	return 0;
2434 }
2435 
2436 int
2437 iscsit_handle_logout_cmd(struct iscsi_conn *conn, struct iscsi_cmd *cmd,
2438 			unsigned char *buf)
2439 {
2440 	int cmdsn_ret, logout_remove = 0;
2441 	u8 reason_code = 0;
2442 	struct iscsi_logout *hdr;
2443 	struct iscsi_tiqn *tiqn = iscsit_snmp_get_tiqn(conn);
2444 
2445 	hdr			= (struct iscsi_logout *) buf;
2446 	reason_code		= (hdr->flags & 0x7f);
2447 
2448 	if (tiqn) {
2449 		spin_lock(&tiqn->logout_stats.lock);
2450 		if (reason_code == ISCSI_LOGOUT_REASON_CLOSE_SESSION)
2451 			tiqn->logout_stats.normal_logouts++;
2452 		else
2453 			tiqn->logout_stats.abnormal_logouts++;
2454 		spin_unlock(&tiqn->logout_stats.lock);
2455 	}
2456 
2457 	pr_debug("Got Logout Request ITT: 0x%08x CmdSN: 0x%08x"
2458 		" ExpStatSN: 0x%08x Reason: 0x%02x CID: %hu on CID: %hu\n",
2459 		hdr->itt, hdr->cmdsn, hdr->exp_statsn, reason_code,
2460 		hdr->cid, conn->cid);
2461 
2462 	if (conn->conn_state != TARG_CONN_STATE_LOGGED_IN) {
2463 		pr_err("Received logout request on connection that"
2464 			" is not in logged in state, ignoring request.\n");
2465 		iscsit_free_cmd(cmd, false);
2466 		return 0;
2467 	}
2468 
2469 	cmd->iscsi_opcode       = ISCSI_OP_LOGOUT;
2470 	cmd->i_state            = ISTATE_SEND_LOGOUTRSP;
2471 	cmd->immediate_cmd      = ((hdr->opcode & ISCSI_OP_IMMEDIATE) ? 1 : 0);
2472 	conn->sess->init_task_tag = cmd->init_task_tag  = hdr->itt;
2473 	cmd->targ_xfer_tag      = 0xFFFFFFFF;
2474 	cmd->cmd_sn             = be32_to_cpu(hdr->cmdsn);
2475 	cmd->exp_stat_sn        = be32_to_cpu(hdr->exp_statsn);
2476 	cmd->logout_cid         = be16_to_cpu(hdr->cid);
2477 	cmd->logout_reason      = reason_code;
2478 	cmd->data_direction     = DMA_NONE;
2479 
2480 	/*
2481 	 * We need to sleep in these cases (by returning 1) until the Logout
2482 	 * Response gets sent in the tx thread.
2483 	 */
2484 	if ((reason_code == ISCSI_LOGOUT_REASON_CLOSE_SESSION) ||
2485 	   ((reason_code == ISCSI_LOGOUT_REASON_CLOSE_CONNECTION) &&
2486 	    be16_to_cpu(hdr->cid) == conn->cid))
2487 		logout_remove = 1;
2488 
2489 	spin_lock_bh(&conn->cmd_lock);
2490 	list_add_tail(&cmd->i_conn_node, &conn->conn_cmd_list);
2491 	spin_unlock_bh(&conn->cmd_lock);
2492 
2493 	if (reason_code != ISCSI_LOGOUT_REASON_RECOVERY)
2494 		iscsit_ack_from_expstatsn(conn, be32_to_cpu(hdr->exp_statsn));
2495 
2496 	/*
2497 	 * Immediate commands are executed, well, immediately.
2498 	 * Non-Immediate Logout Commands are executed in CmdSN order.
2499 	 */
2500 	if (cmd->immediate_cmd) {
2501 		int ret = iscsit_execute_cmd(cmd, 0);
2502 
2503 		if (ret < 0)
2504 			return ret;
2505 	} else {
2506 		cmdsn_ret = iscsit_sequence_cmd(conn, cmd, buf, hdr->cmdsn);
2507 		if (cmdsn_ret == CMDSN_LOWER_THAN_EXP)
2508 			logout_remove = 0;
2509 		else if (cmdsn_ret == CMDSN_ERROR_CANNOT_RECOVER)
2510 			return -1;
2511 	}
2512 
2513 	return logout_remove;
2514 }
2515 EXPORT_SYMBOL(iscsit_handle_logout_cmd);
2516 
2517 int iscsit_handle_snack(
2518 	struct iscsi_conn *conn,
2519 	unsigned char *buf)
2520 {
2521 	struct iscsi_snack *hdr;
2522 
2523 	hdr			= (struct iscsi_snack *) buf;
2524 	hdr->flags		&= ~ISCSI_FLAG_CMD_FINAL;
2525 
2526 	pr_debug("Got ISCSI_INIT_SNACK, ITT: 0x%08x, ExpStatSN:"
2527 		" 0x%08x, Type: 0x%02x, BegRun: 0x%08x, RunLength: 0x%08x,"
2528 		" CID: %hu\n", hdr->itt, hdr->exp_statsn, hdr->flags,
2529 			hdr->begrun, hdr->runlength, conn->cid);
2530 
2531 	if (!conn->sess->sess_ops->ErrorRecoveryLevel) {
2532 		pr_err("Initiator sent SNACK request while in"
2533 			" ErrorRecoveryLevel=0.\n");
2534 		return iscsit_add_reject(conn, ISCSI_REASON_PROTOCOL_ERROR,
2535 					 buf);
2536 	}
2537 	/*
2538 	 * SNACK_DATA and SNACK_R2T are both 0,  so check which function to
2539 	 * call from inside iscsi_send_recovery_datain_or_r2t().
2540 	 */
2541 	switch (hdr->flags & ISCSI_FLAG_SNACK_TYPE_MASK) {
2542 	case 0:
2543 		return iscsit_handle_recovery_datain_or_r2t(conn, buf,
2544 			hdr->itt,
2545 			be32_to_cpu(hdr->ttt),
2546 			be32_to_cpu(hdr->begrun),
2547 			be32_to_cpu(hdr->runlength));
2548 	case ISCSI_FLAG_SNACK_TYPE_STATUS:
2549 		return iscsit_handle_status_snack(conn, hdr->itt,
2550 			be32_to_cpu(hdr->ttt),
2551 			be32_to_cpu(hdr->begrun), be32_to_cpu(hdr->runlength));
2552 	case ISCSI_FLAG_SNACK_TYPE_DATA_ACK:
2553 		return iscsit_handle_data_ack(conn, be32_to_cpu(hdr->ttt),
2554 			be32_to_cpu(hdr->begrun),
2555 			be32_to_cpu(hdr->runlength));
2556 	case ISCSI_FLAG_SNACK_TYPE_RDATA:
2557 		/* FIXME: Support R-Data SNACK */
2558 		pr_err("R-Data SNACK Not Supported.\n");
2559 		return iscsit_add_reject(conn, ISCSI_REASON_PROTOCOL_ERROR,
2560 					 buf);
2561 	default:
2562 		pr_err("Unknown SNACK type 0x%02x, protocol"
2563 			" error.\n", hdr->flags & 0x0f);
2564 		return iscsit_add_reject(conn, ISCSI_REASON_PROTOCOL_ERROR,
2565 					 buf);
2566 	}
2567 
2568 	return 0;
2569 }
2570 EXPORT_SYMBOL(iscsit_handle_snack);
2571 
2572 static void iscsit_rx_thread_wait_for_tcp(struct iscsi_conn *conn)
2573 {
2574 	if ((conn->sock->sk->sk_shutdown & SEND_SHUTDOWN) ||
2575 	    (conn->sock->sk->sk_shutdown & RCV_SHUTDOWN)) {
2576 		wait_for_completion_interruptible_timeout(
2577 					&conn->rx_half_close_comp,
2578 					ISCSI_RX_THREAD_TCP_TIMEOUT * HZ);
2579 	}
2580 }
2581 
2582 static int iscsit_handle_immediate_data(
2583 	struct iscsi_cmd *cmd,
2584 	struct iscsi_scsi_req *hdr,
2585 	u32 length)
2586 {
2587 	int iov_ret, rx_got = 0, rx_size = 0;
2588 	u32 checksum, iov_count = 0, padding = 0;
2589 	struct iscsi_conn *conn = cmd->conn;
2590 	struct kvec *iov;
2591 	void *overflow_buf = NULL;
2592 
2593 	BUG_ON(cmd->write_data_done > cmd->se_cmd.data_length);
2594 	rx_size = min(cmd->se_cmd.data_length - cmd->write_data_done, length);
2595 	iov_ret = iscsit_map_iovec(cmd, cmd->iov_data,
2596 				   cmd->orig_iov_data_count - 2,
2597 				   cmd->write_data_done, rx_size);
2598 	if (iov_ret < 0)
2599 		return IMMEDIATE_DATA_CANNOT_RECOVER;
2600 
2601 	iov_count = iov_ret;
2602 	iov = &cmd->iov_data[0];
2603 	if (rx_size < length) {
2604 		/*
2605 		 * Special case: length of immediate data exceeds the data
2606 		 * buffer size derived from the CDB.
2607 		 */
2608 		overflow_buf = kmalloc(length - rx_size, GFP_KERNEL);
2609 		if (!overflow_buf) {
2610 			iscsit_unmap_iovec(cmd);
2611 			return IMMEDIATE_DATA_CANNOT_RECOVER;
2612 		}
2613 		cmd->overflow_buf = overflow_buf;
2614 		iov[iov_count].iov_base = overflow_buf;
2615 		iov[iov_count].iov_len = length - rx_size;
2616 		iov_count++;
2617 		rx_size = length;
2618 	}
2619 
2620 	padding = ((-length) & 3);
2621 	if (padding != 0) {
2622 		iov[iov_count].iov_base	= cmd->pad_bytes;
2623 		iov[iov_count++].iov_len = padding;
2624 		rx_size += padding;
2625 	}
2626 
2627 	if (conn->conn_ops->DataDigest) {
2628 		iov[iov_count].iov_base		= &checksum;
2629 		iov[iov_count++].iov_len	= ISCSI_CRC_LEN;
2630 		rx_size += ISCSI_CRC_LEN;
2631 	}
2632 
2633 	WARN_ON_ONCE(iov_count > cmd->orig_iov_data_count);
2634 	rx_got = rx_data(conn, &cmd->iov_data[0], iov_count, rx_size);
2635 
2636 	iscsit_unmap_iovec(cmd);
2637 
2638 	if (rx_got != rx_size) {
2639 		iscsit_rx_thread_wait_for_tcp(conn);
2640 		return IMMEDIATE_DATA_CANNOT_RECOVER;
2641 	}
2642 
2643 	if (conn->conn_ops->DataDigest) {
2644 		u32 data_crc;
2645 
2646 		data_crc = iscsit_do_crypto_hash_sg(conn->conn_rx_hash, cmd,
2647 						    cmd->write_data_done, length, padding,
2648 						    cmd->pad_bytes);
2649 
2650 		if (checksum != data_crc) {
2651 			pr_err("ImmediateData CRC32C DataDigest 0x%08x"
2652 				" does not match computed 0x%08x\n", checksum,
2653 				data_crc);
2654 
2655 			if (!conn->sess->sess_ops->ErrorRecoveryLevel) {
2656 				pr_err("Unable to recover from"
2657 					" Immediate Data digest failure while"
2658 					" in ERL=0.\n");
2659 				iscsit_reject_cmd(cmd,
2660 						ISCSI_REASON_DATA_DIGEST_ERROR,
2661 						(unsigned char *)hdr);
2662 				return IMMEDIATE_DATA_CANNOT_RECOVER;
2663 			} else {
2664 				iscsit_reject_cmd(cmd,
2665 						ISCSI_REASON_DATA_DIGEST_ERROR,
2666 						(unsigned char *)hdr);
2667 				return IMMEDIATE_DATA_ERL1_CRC_FAILURE;
2668 			}
2669 		} else {
2670 			pr_debug("Got CRC32C DataDigest 0x%08x for"
2671 				" %u bytes of Immediate Data\n", checksum,
2672 				length);
2673 		}
2674 	}
2675 
2676 	cmd->write_data_done += length;
2677 
2678 	if (cmd->write_data_done == cmd->se_cmd.data_length) {
2679 		spin_lock_bh(&cmd->istate_lock);
2680 		cmd->cmd_flags |= ICF_GOT_LAST_DATAOUT;
2681 		cmd->i_state = ISTATE_RECEIVED_LAST_DATAOUT;
2682 		spin_unlock_bh(&cmd->istate_lock);
2683 	}
2684 
2685 	return IMMEDIATE_DATA_NORMAL_OPERATION;
2686 }
2687 
2688 /* #warning iscsi_build_conn_drop_async_message() only sends out on connections
2689 	with active network interface */
2690 static void iscsit_build_conn_drop_async_message(struct iscsi_conn *conn)
2691 {
2692 	struct iscsi_cmd *cmd;
2693 	struct iscsi_conn *conn_p;
2694 	bool found = false;
2695 
2696 	lockdep_assert_held(&conn->sess->conn_lock);
2697 
2698 	/*
2699 	 * Only send a Asynchronous Message on connections whos network
2700 	 * interface is still functional.
2701 	 */
2702 	list_for_each_entry(conn_p, &conn->sess->sess_conn_list, conn_list) {
2703 		if (conn_p->conn_state == TARG_CONN_STATE_LOGGED_IN) {
2704 			iscsit_inc_conn_usage_count(conn_p);
2705 			found = true;
2706 			break;
2707 		}
2708 	}
2709 
2710 	if (!found)
2711 		return;
2712 
2713 	cmd = iscsit_allocate_cmd(conn_p, TASK_RUNNING);
2714 	if (!cmd) {
2715 		iscsit_dec_conn_usage_count(conn_p);
2716 		return;
2717 	}
2718 
2719 	cmd->logout_cid = conn->cid;
2720 	cmd->iscsi_opcode = ISCSI_OP_ASYNC_EVENT;
2721 	cmd->i_state = ISTATE_SEND_ASYNCMSG;
2722 
2723 	spin_lock_bh(&conn_p->cmd_lock);
2724 	list_add_tail(&cmd->i_conn_node, &conn_p->conn_cmd_list);
2725 	spin_unlock_bh(&conn_p->cmd_lock);
2726 
2727 	iscsit_add_cmd_to_response_queue(cmd, conn_p, cmd->i_state);
2728 	iscsit_dec_conn_usage_count(conn_p);
2729 }
2730 
2731 static int iscsit_send_conn_drop_async_message(
2732 	struct iscsi_cmd *cmd,
2733 	struct iscsi_conn *conn)
2734 {
2735 	struct iscsi_async *hdr;
2736 
2737 	cmd->iscsi_opcode = ISCSI_OP_ASYNC_EVENT;
2738 
2739 	hdr			= (struct iscsi_async *) cmd->pdu;
2740 	hdr->opcode		= ISCSI_OP_ASYNC_EVENT;
2741 	hdr->flags		= ISCSI_FLAG_CMD_FINAL;
2742 	cmd->init_task_tag	= RESERVED_ITT;
2743 	cmd->targ_xfer_tag	= 0xFFFFFFFF;
2744 	put_unaligned_be64(0xFFFFFFFFFFFFFFFFULL, &hdr->rsvd4[0]);
2745 	cmd->stat_sn		= conn->stat_sn++;
2746 	hdr->statsn		= cpu_to_be32(cmd->stat_sn);
2747 	hdr->exp_cmdsn		= cpu_to_be32(conn->sess->exp_cmd_sn);
2748 	hdr->max_cmdsn		= cpu_to_be32((u32) atomic_read(&conn->sess->max_cmd_sn));
2749 	hdr->async_event	= ISCSI_ASYNC_MSG_DROPPING_CONNECTION;
2750 	hdr->param1		= cpu_to_be16(cmd->logout_cid);
2751 	hdr->param2		= cpu_to_be16(conn->sess->sess_ops->DefaultTime2Wait);
2752 	hdr->param3		= cpu_to_be16(conn->sess->sess_ops->DefaultTime2Retain);
2753 
2754 	pr_debug("Sending Connection Dropped Async Message StatSN:"
2755 		" 0x%08x, for CID: %hu on CID: %hu\n", cmd->stat_sn,
2756 			cmd->logout_cid, conn->cid);
2757 
2758 	return conn->conn_transport->iscsit_xmit_pdu(conn, cmd, NULL, NULL, 0);
2759 }
2760 
2761 static void iscsit_tx_thread_wait_for_tcp(struct iscsi_conn *conn)
2762 {
2763 	if ((conn->sock->sk->sk_shutdown & SEND_SHUTDOWN) ||
2764 	    (conn->sock->sk->sk_shutdown & RCV_SHUTDOWN)) {
2765 		wait_for_completion_interruptible_timeout(
2766 					&conn->tx_half_close_comp,
2767 					ISCSI_TX_THREAD_TCP_TIMEOUT * HZ);
2768 	}
2769 }
2770 
2771 void
2772 iscsit_build_datain_pdu(struct iscsi_cmd *cmd, struct iscsi_conn *conn,
2773 			struct iscsi_datain *datain, struct iscsi_data_rsp *hdr,
2774 			bool set_statsn)
2775 {
2776 	hdr->opcode		= ISCSI_OP_SCSI_DATA_IN;
2777 	hdr->flags		= datain->flags;
2778 	if (hdr->flags & ISCSI_FLAG_DATA_STATUS) {
2779 		if (cmd->se_cmd.se_cmd_flags & SCF_OVERFLOW_BIT) {
2780 			hdr->flags |= ISCSI_FLAG_DATA_OVERFLOW;
2781 			hdr->residual_count = cpu_to_be32(cmd->se_cmd.residual_count);
2782 		} else if (cmd->se_cmd.se_cmd_flags & SCF_UNDERFLOW_BIT) {
2783 			hdr->flags |= ISCSI_FLAG_DATA_UNDERFLOW;
2784 			hdr->residual_count = cpu_to_be32(cmd->se_cmd.residual_count);
2785 		}
2786 	}
2787 	hton24(hdr->dlength, datain->length);
2788 	if (hdr->flags & ISCSI_FLAG_DATA_ACK)
2789 		int_to_scsilun(cmd->se_cmd.orig_fe_lun,
2790 				(struct scsi_lun *)&hdr->lun);
2791 	else
2792 		put_unaligned_le64(0xFFFFFFFFFFFFFFFFULL, &hdr->lun);
2793 
2794 	hdr->itt		= cmd->init_task_tag;
2795 
2796 	if (hdr->flags & ISCSI_FLAG_DATA_ACK)
2797 		hdr->ttt		= cpu_to_be32(cmd->targ_xfer_tag);
2798 	else
2799 		hdr->ttt		= cpu_to_be32(0xFFFFFFFF);
2800 	if (set_statsn)
2801 		hdr->statsn		= cpu_to_be32(cmd->stat_sn);
2802 	else
2803 		hdr->statsn		= cpu_to_be32(0xFFFFFFFF);
2804 
2805 	hdr->exp_cmdsn		= cpu_to_be32(conn->sess->exp_cmd_sn);
2806 	hdr->max_cmdsn		= cpu_to_be32((u32) atomic_read(&conn->sess->max_cmd_sn));
2807 	hdr->datasn		= cpu_to_be32(datain->data_sn);
2808 	hdr->offset		= cpu_to_be32(datain->offset);
2809 
2810 	pr_debug("Built DataIN ITT: 0x%08x, StatSN: 0x%08x,"
2811 		" DataSN: 0x%08x, Offset: %u, Length: %u, CID: %hu\n",
2812 		cmd->init_task_tag, ntohl(hdr->statsn), ntohl(hdr->datasn),
2813 		ntohl(hdr->offset), datain->length, conn->cid);
2814 }
2815 EXPORT_SYMBOL(iscsit_build_datain_pdu);
2816 
2817 static int iscsit_send_datain(struct iscsi_cmd *cmd, struct iscsi_conn *conn)
2818 {
2819 	struct iscsi_data_rsp *hdr = (struct iscsi_data_rsp *)&cmd->pdu[0];
2820 	struct iscsi_datain datain;
2821 	struct iscsi_datain_req *dr;
2822 	int eodr = 0, ret;
2823 	bool set_statsn = false;
2824 
2825 	memset(&datain, 0, sizeof(struct iscsi_datain));
2826 	dr = iscsit_get_datain_values(cmd, &datain);
2827 	if (!dr) {
2828 		pr_err("iscsit_get_datain_values failed for ITT: 0x%08x\n",
2829 				cmd->init_task_tag);
2830 		return -1;
2831 	}
2832 	/*
2833 	 * Be paranoid and double check the logic for now.
2834 	 */
2835 	if ((datain.offset + datain.length) > cmd->se_cmd.data_length) {
2836 		pr_err("Command ITT: 0x%08x, datain.offset: %u and"
2837 			" datain.length: %u exceeds cmd->data_length: %u\n",
2838 			cmd->init_task_tag, datain.offset, datain.length,
2839 			cmd->se_cmd.data_length);
2840 		return -1;
2841 	}
2842 
2843 	atomic_long_add(datain.length, &conn->sess->tx_data_octets);
2844 	/*
2845 	 * Special case for successfully execution w/ both DATAIN
2846 	 * and Sense Data.
2847 	 */
2848 	if ((datain.flags & ISCSI_FLAG_DATA_STATUS) &&
2849 	    (cmd->se_cmd.se_cmd_flags & SCF_TRANSPORT_TASK_SENSE))
2850 		datain.flags &= ~ISCSI_FLAG_DATA_STATUS;
2851 	else {
2852 		if ((dr->dr_complete == DATAIN_COMPLETE_NORMAL) ||
2853 		    (dr->dr_complete == DATAIN_COMPLETE_CONNECTION_RECOVERY)) {
2854 			iscsit_increment_maxcmdsn(cmd, conn->sess);
2855 			cmd->stat_sn = conn->stat_sn++;
2856 			set_statsn = true;
2857 		} else if (dr->dr_complete ==
2858 			   DATAIN_COMPLETE_WITHIN_COMMAND_RECOVERY)
2859 			set_statsn = true;
2860 	}
2861 
2862 	iscsit_build_datain_pdu(cmd, conn, &datain, hdr, set_statsn);
2863 
2864 	ret = conn->conn_transport->iscsit_xmit_pdu(conn, cmd, dr, &datain, 0);
2865 	if (ret < 0)
2866 		return ret;
2867 
2868 	if (dr->dr_complete) {
2869 		eodr = (cmd->se_cmd.se_cmd_flags & SCF_TRANSPORT_TASK_SENSE) ?
2870 				2 : 1;
2871 		iscsit_free_datain_req(cmd, dr);
2872 	}
2873 
2874 	return eodr;
2875 }
2876 
2877 int
2878 iscsit_build_logout_rsp(struct iscsi_cmd *cmd, struct iscsi_conn *conn,
2879 			struct iscsi_logout_rsp *hdr)
2880 {
2881 	struct iscsi_conn *logout_conn = NULL;
2882 	struct iscsi_conn_recovery *cr = NULL;
2883 	struct iscsi_session *sess = conn->sess;
2884 	/*
2885 	 * The actual shutting down of Sessions and/or Connections
2886 	 * for CLOSESESSION and CLOSECONNECTION Logout Requests
2887 	 * is done in scsi_logout_post_handler().
2888 	 */
2889 	switch (cmd->logout_reason) {
2890 	case ISCSI_LOGOUT_REASON_CLOSE_SESSION:
2891 		pr_debug("iSCSI session logout successful, setting"
2892 			" logout response to ISCSI_LOGOUT_SUCCESS.\n");
2893 		cmd->logout_response = ISCSI_LOGOUT_SUCCESS;
2894 		break;
2895 	case ISCSI_LOGOUT_REASON_CLOSE_CONNECTION:
2896 		if (cmd->logout_response == ISCSI_LOGOUT_CID_NOT_FOUND)
2897 			break;
2898 		/*
2899 		 * For CLOSECONNECTION logout requests carrying
2900 		 * a matching logout CID -> local CID, the reference
2901 		 * for the local CID will have been incremented in
2902 		 * iscsi_logout_closeconnection().
2903 		 *
2904 		 * For CLOSECONNECTION logout requests carrying
2905 		 * a different CID than the connection it arrived
2906 		 * on, the connection responding to cmd->logout_cid
2907 		 * is stopped in iscsit_logout_post_handler_diffcid().
2908 		 */
2909 
2910 		pr_debug("iSCSI CID: %hu logout on CID: %hu"
2911 			" successful.\n", cmd->logout_cid, conn->cid);
2912 		cmd->logout_response = ISCSI_LOGOUT_SUCCESS;
2913 		break;
2914 	case ISCSI_LOGOUT_REASON_RECOVERY:
2915 		if ((cmd->logout_response == ISCSI_LOGOUT_RECOVERY_UNSUPPORTED) ||
2916 		    (cmd->logout_response == ISCSI_LOGOUT_CLEANUP_FAILED))
2917 			break;
2918 		/*
2919 		 * If the connection is still active from our point of view
2920 		 * force connection recovery to occur.
2921 		 */
2922 		logout_conn = iscsit_get_conn_from_cid_rcfr(sess,
2923 				cmd->logout_cid);
2924 		if (logout_conn) {
2925 			iscsit_connection_reinstatement_rcfr(logout_conn);
2926 			iscsit_dec_conn_usage_count(logout_conn);
2927 		}
2928 
2929 		cr = iscsit_get_inactive_connection_recovery_entry(
2930 				conn->sess, cmd->logout_cid);
2931 		if (!cr) {
2932 			pr_err("Unable to locate CID: %hu for"
2933 			" REMOVECONNFORRECOVERY Logout Request.\n",
2934 				cmd->logout_cid);
2935 			cmd->logout_response = ISCSI_LOGOUT_CID_NOT_FOUND;
2936 			break;
2937 		}
2938 
2939 		iscsit_discard_cr_cmds_by_expstatsn(cr, cmd->exp_stat_sn);
2940 
2941 		pr_debug("iSCSI REMOVECONNFORRECOVERY logout"
2942 			" for recovery for CID: %hu on CID: %hu successful.\n",
2943 				cmd->logout_cid, conn->cid);
2944 		cmd->logout_response = ISCSI_LOGOUT_SUCCESS;
2945 		break;
2946 	default:
2947 		pr_err("Unknown cmd->logout_reason: 0x%02x\n",
2948 				cmd->logout_reason);
2949 		return -1;
2950 	}
2951 
2952 	hdr->opcode		= ISCSI_OP_LOGOUT_RSP;
2953 	hdr->flags		|= ISCSI_FLAG_CMD_FINAL;
2954 	hdr->response		= cmd->logout_response;
2955 	hdr->itt		= cmd->init_task_tag;
2956 	cmd->stat_sn		= conn->stat_sn++;
2957 	hdr->statsn		= cpu_to_be32(cmd->stat_sn);
2958 
2959 	iscsit_increment_maxcmdsn(cmd, conn->sess);
2960 	hdr->exp_cmdsn		= cpu_to_be32(conn->sess->exp_cmd_sn);
2961 	hdr->max_cmdsn		= cpu_to_be32((u32) atomic_read(&conn->sess->max_cmd_sn));
2962 
2963 	pr_debug("Built Logout Response ITT: 0x%08x StatSN:"
2964 		" 0x%08x Response: 0x%02x CID: %hu on CID: %hu\n",
2965 		cmd->init_task_tag, cmd->stat_sn, hdr->response,
2966 		cmd->logout_cid, conn->cid);
2967 
2968 	return 0;
2969 }
2970 EXPORT_SYMBOL(iscsit_build_logout_rsp);
2971 
2972 static int
2973 iscsit_send_logout(struct iscsi_cmd *cmd, struct iscsi_conn *conn)
2974 {
2975 	int rc;
2976 
2977 	rc = iscsit_build_logout_rsp(cmd, conn,
2978 			(struct iscsi_logout_rsp *)&cmd->pdu[0]);
2979 	if (rc < 0)
2980 		return rc;
2981 
2982 	return conn->conn_transport->iscsit_xmit_pdu(conn, cmd, NULL, NULL, 0);
2983 }
2984 
2985 void
2986 iscsit_build_nopin_rsp(struct iscsi_cmd *cmd, struct iscsi_conn *conn,
2987 		       struct iscsi_nopin *hdr, bool nopout_response)
2988 {
2989 	hdr->opcode		= ISCSI_OP_NOOP_IN;
2990 	hdr->flags		|= ISCSI_FLAG_CMD_FINAL;
2991         hton24(hdr->dlength, cmd->buf_ptr_size);
2992 	if (nopout_response)
2993 		put_unaligned_le64(0xFFFFFFFFFFFFFFFFULL, &hdr->lun);
2994 	hdr->itt		= cmd->init_task_tag;
2995 	hdr->ttt		= cpu_to_be32(cmd->targ_xfer_tag);
2996 	cmd->stat_sn		= (nopout_response) ? conn->stat_sn++ :
2997 				  conn->stat_sn;
2998 	hdr->statsn		= cpu_to_be32(cmd->stat_sn);
2999 
3000 	if (nopout_response)
3001 		iscsit_increment_maxcmdsn(cmd, conn->sess);
3002 
3003 	hdr->exp_cmdsn		= cpu_to_be32(conn->sess->exp_cmd_sn);
3004 	hdr->max_cmdsn		= cpu_to_be32((u32) atomic_read(&conn->sess->max_cmd_sn));
3005 
3006 	pr_debug("Built NOPIN %s Response ITT: 0x%08x, TTT: 0x%08x,"
3007 		" StatSN: 0x%08x, Length %u\n", (nopout_response) ?
3008 		"Solicited" : "Unsolicited", cmd->init_task_tag,
3009 		cmd->targ_xfer_tag, cmd->stat_sn, cmd->buf_ptr_size);
3010 }
3011 EXPORT_SYMBOL(iscsit_build_nopin_rsp);
3012 
3013 /*
3014  *	Unsolicited NOPIN, either requesting a response or not.
3015  */
3016 static int iscsit_send_unsolicited_nopin(
3017 	struct iscsi_cmd *cmd,
3018 	struct iscsi_conn *conn,
3019 	int want_response)
3020 {
3021 	struct iscsi_nopin *hdr = (struct iscsi_nopin *)&cmd->pdu[0];
3022 	int ret;
3023 
3024 	iscsit_build_nopin_rsp(cmd, conn, hdr, false);
3025 
3026 	pr_debug("Sending Unsolicited NOPIN TTT: 0x%08x StatSN:"
3027 		" 0x%08x CID: %hu\n", hdr->ttt, cmd->stat_sn, conn->cid);
3028 
3029 	ret = conn->conn_transport->iscsit_xmit_pdu(conn, cmd, NULL, NULL, 0);
3030 	if (ret < 0)
3031 		return ret;
3032 
3033 	spin_lock_bh(&cmd->istate_lock);
3034 	cmd->i_state = want_response ?
3035 		ISTATE_SENT_NOPIN_WANT_RESPONSE : ISTATE_SENT_STATUS;
3036 	spin_unlock_bh(&cmd->istate_lock);
3037 
3038 	return 0;
3039 }
3040 
3041 static int
3042 iscsit_send_nopin(struct iscsi_cmd *cmd, struct iscsi_conn *conn)
3043 {
3044 	struct iscsi_nopin *hdr = (struct iscsi_nopin *)&cmd->pdu[0];
3045 
3046 	iscsit_build_nopin_rsp(cmd, conn, hdr, true);
3047 
3048 	/*
3049 	 * NOPOUT Ping Data is attached to struct iscsi_cmd->buf_ptr.
3050 	 * NOPOUT DataSegmentLength is at struct iscsi_cmd->buf_ptr_size.
3051 	 */
3052 	pr_debug("Echoing back %u bytes of ping data.\n", cmd->buf_ptr_size);
3053 
3054 	return conn->conn_transport->iscsit_xmit_pdu(conn, cmd, NULL,
3055 						     cmd->buf_ptr,
3056 						     cmd->buf_ptr_size);
3057 }
3058 
3059 static int iscsit_send_r2t(
3060 	struct iscsi_cmd *cmd,
3061 	struct iscsi_conn *conn)
3062 {
3063 	struct iscsi_r2t *r2t;
3064 	struct iscsi_r2t_rsp *hdr;
3065 	int ret;
3066 
3067 	r2t = iscsit_get_r2t_from_list(cmd);
3068 	if (!r2t)
3069 		return -1;
3070 
3071 	hdr			= (struct iscsi_r2t_rsp *) cmd->pdu;
3072 	memset(hdr, 0, ISCSI_HDR_LEN);
3073 	hdr->opcode		= ISCSI_OP_R2T;
3074 	hdr->flags		|= ISCSI_FLAG_CMD_FINAL;
3075 	int_to_scsilun(cmd->se_cmd.orig_fe_lun,
3076 			(struct scsi_lun *)&hdr->lun);
3077 	hdr->itt		= cmd->init_task_tag;
3078 	if (conn->conn_transport->iscsit_get_r2t_ttt)
3079 		conn->conn_transport->iscsit_get_r2t_ttt(conn, cmd, r2t);
3080 	else
3081 		r2t->targ_xfer_tag = session_get_next_ttt(conn->sess);
3082 	hdr->ttt		= cpu_to_be32(r2t->targ_xfer_tag);
3083 	hdr->statsn		= cpu_to_be32(conn->stat_sn);
3084 	hdr->exp_cmdsn		= cpu_to_be32(conn->sess->exp_cmd_sn);
3085 	hdr->max_cmdsn		= cpu_to_be32((u32) atomic_read(&conn->sess->max_cmd_sn));
3086 	hdr->r2tsn		= cpu_to_be32(r2t->r2t_sn);
3087 	hdr->data_offset	= cpu_to_be32(r2t->offset);
3088 	hdr->data_length	= cpu_to_be32(r2t->xfer_len);
3089 
3090 	pr_debug("Built %sR2T, ITT: 0x%08x, TTT: 0x%08x, StatSN:"
3091 		" 0x%08x, R2TSN: 0x%08x, Offset: %u, DDTL: %u, CID: %hu\n",
3092 		(!r2t->recovery_r2t) ? "" : "Recovery ", cmd->init_task_tag,
3093 		r2t->targ_xfer_tag, ntohl(hdr->statsn), r2t->r2t_sn,
3094 			r2t->offset, r2t->xfer_len, conn->cid);
3095 
3096 	spin_lock_bh(&cmd->r2t_lock);
3097 	r2t->sent_r2t = 1;
3098 	spin_unlock_bh(&cmd->r2t_lock);
3099 
3100 	ret = conn->conn_transport->iscsit_xmit_pdu(conn, cmd, NULL, NULL, 0);
3101 	if (ret < 0) {
3102 		return ret;
3103 	}
3104 
3105 	spin_lock_bh(&cmd->dataout_timeout_lock);
3106 	iscsit_start_dataout_timer(cmd, conn);
3107 	spin_unlock_bh(&cmd->dataout_timeout_lock);
3108 
3109 	return 0;
3110 }
3111 
3112 /*
3113  *	@recovery: If called from iscsi_task_reassign_complete_write() for
3114  *		connection recovery.
3115  */
3116 int iscsit_build_r2ts_for_cmd(
3117 	struct iscsi_conn *conn,
3118 	struct iscsi_cmd *cmd,
3119 	bool recovery)
3120 {
3121 	int first_r2t = 1;
3122 	u32 offset = 0, xfer_len = 0;
3123 
3124 	spin_lock_bh(&cmd->r2t_lock);
3125 	if (cmd->cmd_flags & ICF_SENT_LAST_R2T) {
3126 		spin_unlock_bh(&cmd->r2t_lock);
3127 		return 0;
3128 	}
3129 
3130 	if (conn->sess->sess_ops->DataSequenceInOrder &&
3131 	    !recovery)
3132 		cmd->r2t_offset = max(cmd->r2t_offset, cmd->write_data_done);
3133 
3134 	while (cmd->outstanding_r2ts < conn->sess->sess_ops->MaxOutstandingR2T) {
3135 		if (conn->sess->sess_ops->DataSequenceInOrder) {
3136 			offset = cmd->r2t_offset;
3137 
3138 			if (first_r2t && recovery) {
3139 				int new_data_end = offset +
3140 					conn->sess->sess_ops->MaxBurstLength -
3141 					cmd->next_burst_len;
3142 
3143 				if (new_data_end > cmd->se_cmd.data_length)
3144 					xfer_len = cmd->se_cmd.data_length - offset;
3145 				else
3146 					xfer_len =
3147 						conn->sess->sess_ops->MaxBurstLength -
3148 						cmd->next_burst_len;
3149 			} else {
3150 				int new_data_end = offset +
3151 					conn->sess->sess_ops->MaxBurstLength;
3152 
3153 				if (new_data_end > cmd->se_cmd.data_length)
3154 					xfer_len = cmd->se_cmd.data_length - offset;
3155 				else
3156 					xfer_len = conn->sess->sess_ops->MaxBurstLength;
3157 			}
3158 
3159 			if ((s32)xfer_len < 0) {
3160 				cmd->cmd_flags |= ICF_SENT_LAST_R2T;
3161 				break;
3162 			}
3163 
3164 			cmd->r2t_offset += xfer_len;
3165 
3166 			if (cmd->r2t_offset == cmd->se_cmd.data_length)
3167 				cmd->cmd_flags |= ICF_SENT_LAST_R2T;
3168 		} else {
3169 			struct iscsi_seq *seq;
3170 
3171 			seq = iscsit_get_seq_holder_for_r2t(cmd);
3172 			if (!seq) {
3173 				spin_unlock_bh(&cmd->r2t_lock);
3174 				return -1;
3175 			}
3176 
3177 			offset = seq->offset;
3178 			xfer_len = seq->xfer_len;
3179 
3180 			if (cmd->seq_send_order == cmd->seq_count)
3181 				cmd->cmd_flags |= ICF_SENT_LAST_R2T;
3182 		}
3183 		cmd->outstanding_r2ts++;
3184 		first_r2t = 0;
3185 
3186 		if (iscsit_add_r2t_to_list(cmd, offset, xfer_len, 0, 0) < 0) {
3187 			spin_unlock_bh(&cmd->r2t_lock);
3188 			return -1;
3189 		}
3190 
3191 		if (cmd->cmd_flags & ICF_SENT_LAST_R2T)
3192 			break;
3193 	}
3194 	spin_unlock_bh(&cmd->r2t_lock);
3195 
3196 	return 0;
3197 }
3198 EXPORT_SYMBOL(iscsit_build_r2ts_for_cmd);
3199 
3200 void iscsit_build_rsp_pdu(struct iscsi_cmd *cmd, struct iscsi_conn *conn,
3201 			bool inc_stat_sn, struct iscsi_scsi_rsp *hdr)
3202 {
3203 	if (inc_stat_sn)
3204 		cmd->stat_sn = conn->stat_sn++;
3205 
3206 	atomic_long_inc(&conn->sess->rsp_pdus);
3207 
3208 	memset(hdr, 0, ISCSI_HDR_LEN);
3209 	hdr->opcode		= ISCSI_OP_SCSI_CMD_RSP;
3210 	hdr->flags		|= ISCSI_FLAG_CMD_FINAL;
3211 	if (cmd->se_cmd.se_cmd_flags & SCF_OVERFLOW_BIT) {
3212 		hdr->flags |= ISCSI_FLAG_CMD_OVERFLOW;
3213 		hdr->residual_count = cpu_to_be32(cmd->se_cmd.residual_count);
3214 	} else if (cmd->se_cmd.se_cmd_flags & SCF_UNDERFLOW_BIT) {
3215 		hdr->flags |= ISCSI_FLAG_CMD_UNDERFLOW;
3216 		hdr->residual_count = cpu_to_be32(cmd->se_cmd.residual_count);
3217 	}
3218 	hdr->response		= cmd->iscsi_response;
3219 	hdr->cmd_status		= cmd->se_cmd.scsi_status;
3220 	hdr->itt		= cmd->init_task_tag;
3221 	hdr->statsn		= cpu_to_be32(cmd->stat_sn);
3222 
3223 	iscsit_increment_maxcmdsn(cmd, conn->sess);
3224 	hdr->exp_cmdsn		= cpu_to_be32(conn->sess->exp_cmd_sn);
3225 	hdr->max_cmdsn		= cpu_to_be32((u32) atomic_read(&conn->sess->max_cmd_sn));
3226 
3227 	pr_debug("Built SCSI Response, ITT: 0x%08x, StatSN: 0x%08x,"
3228 		" Response: 0x%02x, SAM Status: 0x%02x, CID: %hu\n",
3229 		cmd->init_task_tag, cmd->stat_sn, cmd->se_cmd.scsi_status,
3230 		cmd->se_cmd.scsi_status, conn->cid);
3231 }
3232 EXPORT_SYMBOL(iscsit_build_rsp_pdu);
3233 
3234 static int iscsit_send_response(struct iscsi_cmd *cmd, struct iscsi_conn *conn)
3235 {
3236 	struct iscsi_scsi_rsp *hdr = (struct iscsi_scsi_rsp *)&cmd->pdu[0];
3237 	bool inc_stat_sn = (cmd->i_state == ISTATE_SEND_STATUS);
3238 	void *data_buf = NULL;
3239 	u32 padding = 0, data_buf_len = 0;
3240 
3241 	iscsit_build_rsp_pdu(cmd, conn, inc_stat_sn, hdr);
3242 
3243 	/*
3244 	 * Attach SENSE DATA payload to iSCSI Response PDU
3245 	 */
3246 	if (cmd->se_cmd.sense_buffer &&
3247 	   ((cmd->se_cmd.se_cmd_flags & SCF_TRANSPORT_TASK_SENSE) ||
3248 	    (cmd->se_cmd.se_cmd_flags & SCF_EMULATED_TASK_SENSE))) {
3249 		put_unaligned_be16(cmd->se_cmd.scsi_sense_length, cmd->sense_buffer);
3250 		cmd->se_cmd.scsi_sense_length += sizeof (__be16);
3251 
3252 		padding		= -(cmd->se_cmd.scsi_sense_length) & 3;
3253 		hton24(hdr->dlength, (u32)cmd->se_cmd.scsi_sense_length);
3254 		data_buf = cmd->sense_buffer;
3255 		data_buf_len = cmd->se_cmd.scsi_sense_length + padding;
3256 
3257 		if (padding) {
3258 			memset(cmd->sense_buffer +
3259 				cmd->se_cmd.scsi_sense_length, 0, padding);
3260 			pr_debug("Adding %u bytes of padding to"
3261 				" SENSE.\n", padding);
3262 		}
3263 
3264 		pr_debug("Attaching SENSE DATA: %u bytes to iSCSI"
3265 				" Response PDU\n",
3266 				cmd->se_cmd.scsi_sense_length);
3267 	}
3268 
3269 	return conn->conn_transport->iscsit_xmit_pdu(conn, cmd, NULL, data_buf,
3270 						     data_buf_len);
3271 }
3272 
3273 static u8 iscsit_convert_tcm_tmr_rsp(struct se_tmr_req *se_tmr)
3274 {
3275 	switch (se_tmr->response) {
3276 	case TMR_FUNCTION_COMPLETE:
3277 		return ISCSI_TMF_RSP_COMPLETE;
3278 	case TMR_TASK_DOES_NOT_EXIST:
3279 		return ISCSI_TMF_RSP_NO_TASK;
3280 	case TMR_LUN_DOES_NOT_EXIST:
3281 		return ISCSI_TMF_RSP_NO_LUN;
3282 	case TMR_TASK_MGMT_FUNCTION_NOT_SUPPORTED:
3283 		return ISCSI_TMF_RSP_NOT_SUPPORTED;
3284 	case TMR_FUNCTION_REJECTED:
3285 	default:
3286 		return ISCSI_TMF_RSP_REJECTED;
3287 	}
3288 }
3289 
3290 void
3291 iscsit_build_task_mgt_rsp(struct iscsi_cmd *cmd, struct iscsi_conn *conn,
3292 			  struct iscsi_tm_rsp *hdr)
3293 {
3294 	struct se_tmr_req *se_tmr = cmd->se_cmd.se_tmr_req;
3295 
3296 	hdr->opcode		= ISCSI_OP_SCSI_TMFUNC_RSP;
3297 	hdr->flags		= ISCSI_FLAG_CMD_FINAL;
3298 	hdr->response		= iscsit_convert_tcm_tmr_rsp(se_tmr);
3299 	hdr->itt		= cmd->init_task_tag;
3300 	cmd->stat_sn		= conn->stat_sn++;
3301 	hdr->statsn		= cpu_to_be32(cmd->stat_sn);
3302 
3303 	iscsit_increment_maxcmdsn(cmd, conn->sess);
3304 	hdr->exp_cmdsn		= cpu_to_be32(conn->sess->exp_cmd_sn);
3305 	hdr->max_cmdsn		= cpu_to_be32((u32) atomic_read(&conn->sess->max_cmd_sn));
3306 
3307 	pr_debug("Built Task Management Response ITT: 0x%08x,"
3308 		" StatSN: 0x%08x, Response: 0x%02x, CID: %hu\n",
3309 		cmd->init_task_tag, cmd->stat_sn, hdr->response, conn->cid);
3310 }
3311 EXPORT_SYMBOL(iscsit_build_task_mgt_rsp);
3312 
3313 static int
3314 iscsit_send_task_mgt_rsp(struct iscsi_cmd *cmd, struct iscsi_conn *conn)
3315 {
3316 	struct iscsi_tm_rsp *hdr = (struct iscsi_tm_rsp *)&cmd->pdu[0];
3317 
3318 	iscsit_build_task_mgt_rsp(cmd, conn, hdr);
3319 
3320 	return conn->conn_transport->iscsit_xmit_pdu(conn, cmd, NULL, NULL, 0);
3321 }
3322 
3323 #define SENDTARGETS_BUF_LIMIT 32768U
3324 
3325 static int
3326 iscsit_build_sendtargets_response(struct iscsi_cmd *cmd,
3327 				  enum iscsit_transport_type network_transport,
3328 				  int skip_bytes, bool *completed)
3329 {
3330 	char *payload = NULL;
3331 	struct iscsi_conn *conn = cmd->conn;
3332 	struct iscsi_portal_group *tpg;
3333 	struct iscsi_tiqn *tiqn;
3334 	struct iscsi_tpg_np *tpg_np;
3335 	int buffer_len, end_of_buf = 0, len = 0, payload_len = 0;
3336 	int target_name_printed;
3337 	unsigned char buf[ISCSI_IQN_LEN+12]; /* iqn + "TargetName=" + \0 */
3338 	unsigned char *text_in = cmd->text_in_ptr, *text_ptr = NULL;
3339 	bool active;
3340 
3341 	buffer_len = min(conn->conn_ops->MaxRecvDataSegmentLength,
3342 			 SENDTARGETS_BUF_LIMIT);
3343 
3344 	payload = kzalloc(buffer_len, GFP_KERNEL);
3345 	if (!payload)
3346 		return -ENOMEM;
3347 
3348 	/*
3349 	 * Locate pointer to iqn./eui. string for ICF_SENDTARGETS_SINGLE
3350 	 * explicit case..
3351 	 */
3352 	if (cmd->cmd_flags & ICF_SENDTARGETS_SINGLE) {
3353 		text_ptr = strchr(text_in, '=');
3354 		if (!text_ptr) {
3355 			pr_err("Unable to locate '=' string in text_in:"
3356 			       " %s\n", text_in);
3357 			kfree(payload);
3358 			return -EINVAL;
3359 		}
3360 		/*
3361 		 * Skip over '=' character..
3362 		 */
3363 		text_ptr += 1;
3364 	}
3365 
3366 	spin_lock(&tiqn_lock);
3367 	list_for_each_entry(tiqn, &g_tiqn_list, tiqn_list) {
3368 		if ((cmd->cmd_flags & ICF_SENDTARGETS_SINGLE) &&
3369 		     strcmp(tiqn->tiqn, text_ptr)) {
3370 			continue;
3371 		}
3372 
3373 		target_name_printed = 0;
3374 
3375 		spin_lock(&tiqn->tiqn_tpg_lock);
3376 		list_for_each_entry(tpg, &tiqn->tiqn_tpg_list, tpg_list) {
3377 
3378 			/* If demo_mode_discovery=0 and generate_node_acls=0
3379 			 * (demo mode dislabed) do not return
3380 			 * TargetName+TargetAddress unless a NodeACL exists.
3381 			 */
3382 
3383 			if ((tpg->tpg_attrib.generate_node_acls == 0) &&
3384 			    (tpg->tpg_attrib.demo_mode_discovery == 0) &&
3385 			    (!target_tpg_has_node_acl(&tpg->tpg_se_tpg,
3386 				cmd->conn->sess->sess_ops->InitiatorName))) {
3387 				continue;
3388 			}
3389 
3390 			spin_lock(&tpg->tpg_state_lock);
3391 			active = (tpg->tpg_state == TPG_STATE_ACTIVE);
3392 			spin_unlock(&tpg->tpg_state_lock);
3393 
3394 			if (!active && tpg->tpg_attrib.tpg_enabled_sendtargets)
3395 				continue;
3396 
3397 			spin_lock(&tpg->tpg_np_lock);
3398 			list_for_each_entry(tpg_np, &tpg->tpg_gnp_list,
3399 						tpg_np_list) {
3400 				struct iscsi_np *np = tpg_np->tpg_np;
3401 				struct sockaddr_storage *sockaddr;
3402 
3403 				if (np->np_network_transport != network_transport)
3404 					continue;
3405 
3406 				if (!target_name_printed) {
3407 					len = sprintf(buf, "TargetName=%s",
3408 						      tiqn->tiqn);
3409 					len += 1;
3410 
3411 					if ((len + payload_len) > buffer_len) {
3412 						spin_unlock(&tpg->tpg_np_lock);
3413 						spin_unlock(&tiqn->tiqn_tpg_lock);
3414 						end_of_buf = 1;
3415 						goto eob;
3416 					}
3417 
3418 					if (skip_bytes && len <= skip_bytes) {
3419 						skip_bytes -= len;
3420 					} else {
3421 						memcpy(payload + payload_len, buf, len);
3422 						payload_len += len;
3423 						target_name_printed = 1;
3424 						if (len > skip_bytes)
3425 							skip_bytes = 0;
3426 					}
3427 				}
3428 
3429 				if (inet_addr_is_any((struct sockaddr *)&np->np_sockaddr))
3430 					sockaddr = &conn->local_sockaddr;
3431 				else
3432 					sockaddr = &np->np_sockaddr;
3433 
3434 				len = sprintf(buf, "TargetAddress="
3435 					      "%pISpc,%hu",
3436 					      sockaddr,
3437 					      tpg->tpgt);
3438 				len += 1;
3439 
3440 				if ((len + payload_len) > buffer_len) {
3441 					spin_unlock(&tpg->tpg_np_lock);
3442 					spin_unlock(&tiqn->tiqn_tpg_lock);
3443 					end_of_buf = 1;
3444 					goto eob;
3445 				}
3446 
3447 				if (skip_bytes && len <= skip_bytes) {
3448 					skip_bytes -= len;
3449 				} else {
3450 					memcpy(payload + payload_len, buf, len);
3451 					payload_len += len;
3452 					if (len > skip_bytes)
3453 						skip_bytes = 0;
3454 				}
3455 			}
3456 			spin_unlock(&tpg->tpg_np_lock);
3457 		}
3458 		spin_unlock(&tiqn->tiqn_tpg_lock);
3459 eob:
3460 		if (end_of_buf) {
3461 			*completed = false;
3462 			break;
3463 		}
3464 
3465 		if (cmd->cmd_flags & ICF_SENDTARGETS_SINGLE)
3466 			break;
3467 	}
3468 	spin_unlock(&tiqn_lock);
3469 
3470 	cmd->buf_ptr = payload;
3471 
3472 	return payload_len;
3473 }
3474 
3475 int
3476 iscsit_build_text_rsp(struct iscsi_cmd *cmd, struct iscsi_conn *conn,
3477 		      struct iscsi_text_rsp *hdr,
3478 		      enum iscsit_transport_type network_transport)
3479 {
3480 	int text_length, padding;
3481 	bool completed = true;
3482 
3483 	text_length = iscsit_build_sendtargets_response(cmd, network_transport,
3484 							cmd->read_data_done,
3485 							&completed);
3486 	if (text_length < 0)
3487 		return text_length;
3488 
3489 	if (completed) {
3490 		hdr->flags = ISCSI_FLAG_CMD_FINAL;
3491 	} else {
3492 		hdr->flags = ISCSI_FLAG_TEXT_CONTINUE;
3493 		cmd->read_data_done += text_length;
3494 		if (cmd->targ_xfer_tag == 0xFFFFFFFF)
3495 			cmd->targ_xfer_tag = session_get_next_ttt(conn->sess);
3496 	}
3497 	hdr->opcode = ISCSI_OP_TEXT_RSP;
3498 	padding = ((-text_length) & 3);
3499 	hton24(hdr->dlength, text_length);
3500 	hdr->itt = cmd->init_task_tag;
3501 	hdr->ttt = cpu_to_be32(cmd->targ_xfer_tag);
3502 	cmd->stat_sn = conn->stat_sn++;
3503 	hdr->statsn = cpu_to_be32(cmd->stat_sn);
3504 
3505 	iscsit_increment_maxcmdsn(cmd, conn->sess);
3506 	/*
3507 	 * Reset maxcmdsn_inc in multi-part text payload exchanges to
3508 	 * correctly increment MaxCmdSN for each response answering a
3509 	 * non immediate text request with a valid CmdSN.
3510 	 */
3511 	cmd->maxcmdsn_inc = 0;
3512 	hdr->exp_cmdsn = cpu_to_be32(conn->sess->exp_cmd_sn);
3513 	hdr->max_cmdsn = cpu_to_be32((u32) atomic_read(&conn->sess->max_cmd_sn));
3514 
3515 	pr_debug("Built Text Response: ITT: 0x%08x, TTT: 0x%08x, StatSN: 0x%08x,"
3516 		" Length: %u, CID: %hu F: %d C: %d\n", cmd->init_task_tag,
3517 		cmd->targ_xfer_tag, cmd->stat_sn, text_length, conn->cid,
3518 		!!(hdr->flags & ISCSI_FLAG_CMD_FINAL),
3519 		!!(hdr->flags & ISCSI_FLAG_TEXT_CONTINUE));
3520 
3521 	return text_length + padding;
3522 }
3523 EXPORT_SYMBOL(iscsit_build_text_rsp);
3524 
3525 static int iscsit_send_text_rsp(
3526 	struct iscsi_cmd *cmd,
3527 	struct iscsi_conn *conn)
3528 {
3529 	struct iscsi_text_rsp *hdr = (struct iscsi_text_rsp *)cmd->pdu;
3530 	int text_length;
3531 
3532 	text_length = iscsit_build_text_rsp(cmd, conn, hdr,
3533 				conn->conn_transport->transport_type);
3534 	if (text_length < 0)
3535 		return text_length;
3536 
3537 	return conn->conn_transport->iscsit_xmit_pdu(conn, cmd, NULL,
3538 						     cmd->buf_ptr,
3539 						     text_length);
3540 }
3541 
3542 void
3543 iscsit_build_reject(struct iscsi_cmd *cmd, struct iscsi_conn *conn,
3544 		    struct iscsi_reject *hdr)
3545 {
3546 	hdr->opcode		= ISCSI_OP_REJECT;
3547 	hdr->reason		= cmd->reject_reason;
3548 	hdr->flags		|= ISCSI_FLAG_CMD_FINAL;
3549 	hton24(hdr->dlength, ISCSI_HDR_LEN);
3550 	hdr->ffffffff		= cpu_to_be32(0xffffffff);
3551 	cmd->stat_sn		= conn->stat_sn++;
3552 	hdr->statsn		= cpu_to_be32(cmd->stat_sn);
3553 	hdr->exp_cmdsn		= cpu_to_be32(conn->sess->exp_cmd_sn);
3554 	hdr->max_cmdsn		= cpu_to_be32((u32) atomic_read(&conn->sess->max_cmd_sn));
3555 
3556 }
3557 EXPORT_SYMBOL(iscsit_build_reject);
3558 
3559 static int iscsit_send_reject(
3560 	struct iscsi_cmd *cmd,
3561 	struct iscsi_conn *conn)
3562 {
3563 	struct iscsi_reject *hdr = (struct iscsi_reject *)&cmd->pdu[0];
3564 
3565 	iscsit_build_reject(cmd, conn, hdr);
3566 
3567 	pr_debug("Built Reject PDU StatSN: 0x%08x, Reason: 0x%02x,"
3568 		" CID: %hu\n", ntohl(hdr->statsn), hdr->reason, conn->cid);
3569 
3570 	return conn->conn_transport->iscsit_xmit_pdu(conn, cmd, NULL,
3571 						     cmd->buf_ptr,
3572 						     ISCSI_HDR_LEN);
3573 }
3574 
3575 void iscsit_thread_get_cpumask(struct iscsi_conn *conn)
3576 {
3577 	int ord, cpu;
3578 	/*
3579 	 * bitmap_id is assigned from iscsit_global->ts_bitmap from
3580 	 * within iscsit_start_kthreads()
3581 	 *
3582 	 * Here we use bitmap_id to determine which CPU that this
3583 	 * iSCSI connection's RX/TX threads will be scheduled to
3584 	 * execute upon.
3585 	 */
3586 	ord = conn->bitmap_id % cpumask_weight(cpu_online_mask);
3587 	for_each_online_cpu(cpu) {
3588 		if (ord-- == 0) {
3589 			cpumask_set_cpu(cpu, conn->conn_cpumask);
3590 			return;
3591 		}
3592 	}
3593 	/*
3594 	 * This should never be reached..
3595 	 */
3596 	dump_stack();
3597 	cpumask_setall(conn->conn_cpumask);
3598 }
3599 
3600 int
3601 iscsit_immediate_queue(struct iscsi_conn *conn, struct iscsi_cmd *cmd, int state)
3602 {
3603 	int ret;
3604 
3605 	switch (state) {
3606 	case ISTATE_SEND_R2T:
3607 		ret = iscsit_send_r2t(cmd, conn);
3608 		if (ret < 0)
3609 			goto err;
3610 		break;
3611 	case ISTATE_REMOVE:
3612 		spin_lock_bh(&conn->cmd_lock);
3613 		list_del_init(&cmd->i_conn_node);
3614 		spin_unlock_bh(&conn->cmd_lock);
3615 
3616 		iscsit_free_cmd(cmd, false);
3617 		break;
3618 	case ISTATE_SEND_NOPIN_WANT_RESPONSE:
3619 		iscsit_mod_nopin_response_timer(conn);
3620 		ret = iscsit_send_unsolicited_nopin(cmd, conn, 1);
3621 		if (ret < 0)
3622 			goto err;
3623 		break;
3624 	case ISTATE_SEND_NOPIN_NO_RESPONSE:
3625 		ret = iscsit_send_unsolicited_nopin(cmd, conn, 0);
3626 		if (ret < 0)
3627 			goto err;
3628 		break;
3629 	default:
3630 		pr_err("Unknown Opcode: 0x%02x ITT:"
3631 		       " 0x%08x, i_state: %d on CID: %hu\n",
3632 		       cmd->iscsi_opcode, cmd->init_task_tag, state,
3633 		       conn->cid);
3634 		goto err;
3635 	}
3636 
3637 	return 0;
3638 
3639 err:
3640 	return -1;
3641 }
3642 EXPORT_SYMBOL(iscsit_immediate_queue);
3643 
3644 static int
3645 iscsit_handle_immediate_queue(struct iscsi_conn *conn)
3646 {
3647 	struct iscsit_transport *t = conn->conn_transport;
3648 	struct iscsi_queue_req *qr;
3649 	struct iscsi_cmd *cmd;
3650 	u8 state;
3651 	int ret;
3652 
3653 	while ((qr = iscsit_get_cmd_from_immediate_queue(conn))) {
3654 		atomic_set(&conn->check_immediate_queue, 0);
3655 		cmd = qr->cmd;
3656 		state = qr->state;
3657 		kmem_cache_free(lio_qr_cache, qr);
3658 
3659 		ret = t->iscsit_immediate_queue(conn, cmd, state);
3660 		if (ret < 0)
3661 			return ret;
3662 	}
3663 
3664 	return 0;
3665 }
3666 
3667 int
3668 iscsit_response_queue(struct iscsi_conn *conn, struct iscsi_cmd *cmd, int state)
3669 {
3670 	int ret;
3671 
3672 check_rsp_state:
3673 	switch (state) {
3674 	case ISTATE_SEND_DATAIN:
3675 		ret = iscsit_send_datain(cmd, conn);
3676 		if (ret < 0)
3677 			goto err;
3678 		else if (!ret)
3679 			/* more drs */
3680 			goto check_rsp_state;
3681 		else if (ret == 1) {
3682 			/* all done */
3683 			spin_lock_bh(&cmd->istate_lock);
3684 			cmd->i_state = ISTATE_SENT_STATUS;
3685 			spin_unlock_bh(&cmd->istate_lock);
3686 
3687 			if (atomic_read(&conn->check_immediate_queue))
3688 				return 1;
3689 
3690 			return 0;
3691 		} else if (ret == 2) {
3692 			/* Still must send status,
3693 			   SCF_TRANSPORT_TASK_SENSE was set */
3694 			spin_lock_bh(&cmd->istate_lock);
3695 			cmd->i_state = ISTATE_SEND_STATUS;
3696 			spin_unlock_bh(&cmd->istate_lock);
3697 			state = ISTATE_SEND_STATUS;
3698 			goto check_rsp_state;
3699 		}
3700 
3701 		break;
3702 	case ISTATE_SEND_STATUS:
3703 	case ISTATE_SEND_STATUS_RECOVERY:
3704 		ret = iscsit_send_response(cmd, conn);
3705 		break;
3706 	case ISTATE_SEND_LOGOUTRSP:
3707 		ret = iscsit_send_logout(cmd, conn);
3708 		break;
3709 	case ISTATE_SEND_ASYNCMSG:
3710 		ret = iscsit_send_conn_drop_async_message(
3711 			cmd, conn);
3712 		break;
3713 	case ISTATE_SEND_NOPIN:
3714 		ret = iscsit_send_nopin(cmd, conn);
3715 		break;
3716 	case ISTATE_SEND_REJECT:
3717 		ret = iscsit_send_reject(cmd, conn);
3718 		break;
3719 	case ISTATE_SEND_TASKMGTRSP:
3720 		ret = iscsit_send_task_mgt_rsp(cmd, conn);
3721 		if (ret != 0)
3722 			break;
3723 		ret = iscsit_tmr_post_handler(cmd, conn);
3724 		if (ret != 0)
3725 			iscsit_fall_back_to_erl0(conn->sess);
3726 		break;
3727 	case ISTATE_SEND_TEXTRSP:
3728 		ret = iscsit_send_text_rsp(cmd, conn);
3729 		break;
3730 	default:
3731 		pr_err("Unknown Opcode: 0x%02x ITT:"
3732 		       " 0x%08x, i_state: %d on CID: %hu\n",
3733 		       cmd->iscsi_opcode, cmd->init_task_tag,
3734 		       state, conn->cid);
3735 		goto err;
3736 	}
3737 	if (ret < 0)
3738 		goto err;
3739 
3740 	switch (state) {
3741 	case ISTATE_SEND_LOGOUTRSP:
3742 		if (!iscsit_logout_post_handler(cmd, conn))
3743 			return -ECONNRESET;
3744 		/* fall through */
3745 	case ISTATE_SEND_STATUS:
3746 	case ISTATE_SEND_ASYNCMSG:
3747 	case ISTATE_SEND_NOPIN:
3748 	case ISTATE_SEND_STATUS_RECOVERY:
3749 	case ISTATE_SEND_TEXTRSP:
3750 	case ISTATE_SEND_TASKMGTRSP:
3751 	case ISTATE_SEND_REJECT:
3752 		spin_lock_bh(&cmd->istate_lock);
3753 		cmd->i_state = ISTATE_SENT_STATUS;
3754 		spin_unlock_bh(&cmd->istate_lock);
3755 		break;
3756 	default:
3757 		pr_err("Unknown Opcode: 0x%02x ITT:"
3758 		       " 0x%08x, i_state: %d on CID: %hu\n",
3759 		       cmd->iscsi_opcode, cmd->init_task_tag,
3760 		       cmd->i_state, conn->cid);
3761 		goto err;
3762 	}
3763 
3764 	if (atomic_read(&conn->check_immediate_queue))
3765 		return 1;
3766 
3767 	return 0;
3768 
3769 err:
3770 	return -1;
3771 }
3772 EXPORT_SYMBOL(iscsit_response_queue);
3773 
3774 static int iscsit_handle_response_queue(struct iscsi_conn *conn)
3775 {
3776 	struct iscsit_transport *t = conn->conn_transport;
3777 	struct iscsi_queue_req *qr;
3778 	struct iscsi_cmd *cmd;
3779 	u8 state;
3780 	int ret;
3781 
3782 	while ((qr = iscsit_get_cmd_from_response_queue(conn))) {
3783 		cmd = qr->cmd;
3784 		state = qr->state;
3785 		kmem_cache_free(lio_qr_cache, qr);
3786 
3787 		ret = t->iscsit_response_queue(conn, cmd, state);
3788 		if (ret == 1 || ret < 0)
3789 			return ret;
3790 	}
3791 
3792 	return 0;
3793 }
3794 
3795 int iscsi_target_tx_thread(void *arg)
3796 {
3797 	int ret = 0;
3798 	struct iscsi_conn *conn = arg;
3799 	bool conn_freed = false;
3800 
3801 	/*
3802 	 * Allow ourselves to be interrupted by SIGINT so that a
3803 	 * connection recovery / failure event can be triggered externally.
3804 	 */
3805 	allow_signal(SIGINT);
3806 
3807 	while (!kthread_should_stop()) {
3808 		/*
3809 		 * Ensure that both TX and RX per connection kthreads
3810 		 * are scheduled to run on the same CPU.
3811 		 */
3812 		iscsit_thread_check_cpumask(conn, current, 1);
3813 
3814 		wait_event_interruptible(conn->queues_wq,
3815 					 !iscsit_conn_all_queues_empty(conn));
3816 
3817 		if (signal_pending(current))
3818 			goto transport_err;
3819 
3820 get_immediate:
3821 		ret = iscsit_handle_immediate_queue(conn);
3822 		if (ret < 0)
3823 			goto transport_err;
3824 
3825 		ret = iscsit_handle_response_queue(conn);
3826 		if (ret == 1) {
3827 			goto get_immediate;
3828 		} else if (ret == -ECONNRESET) {
3829 			conn_freed = true;
3830 			goto out;
3831 		} else if (ret < 0) {
3832 			goto transport_err;
3833 		}
3834 	}
3835 
3836 transport_err:
3837 	/*
3838 	 * Avoid the normal connection failure code-path if this connection
3839 	 * is still within LOGIN mode, and iscsi_np process context is
3840 	 * responsible for cleaning up the early connection failure.
3841 	 */
3842 	if (conn->conn_state != TARG_CONN_STATE_IN_LOGIN)
3843 		iscsit_take_action_for_connection_exit(conn, &conn_freed);
3844 out:
3845 	if (!conn_freed) {
3846 		while (!kthread_should_stop()) {
3847 			msleep(100);
3848 		}
3849 	}
3850 	return 0;
3851 }
3852 
3853 static int iscsi_target_rx_opcode(struct iscsi_conn *conn, unsigned char *buf)
3854 {
3855 	struct iscsi_hdr *hdr = (struct iscsi_hdr *)buf;
3856 	struct iscsi_cmd *cmd;
3857 	int ret = 0;
3858 
3859 	switch (hdr->opcode & ISCSI_OPCODE_MASK) {
3860 	case ISCSI_OP_SCSI_CMD:
3861 		cmd = iscsit_allocate_cmd(conn, TASK_INTERRUPTIBLE);
3862 		if (!cmd)
3863 			goto reject;
3864 
3865 		ret = iscsit_handle_scsi_cmd(conn, cmd, buf);
3866 		break;
3867 	case ISCSI_OP_SCSI_DATA_OUT:
3868 		ret = iscsit_handle_data_out(conn, buf);
3869 		break;
3870 	case ISCSI_OP_NOOP_OUT:
3871 		cmd = NULL;
3872 		if (hdr->ttt == cpu_to_be32(0xFFFFFFFF)) {
3873 			cmd = iscsit_allocate_cmd(conn, TASK_INTERRUPTIBLE);
3874 			if (!cmd)
3875 				goto reject;
3876 		}
3877 		ret = iscsit_handle_nop_out(conn, cmd, buf);
3878 		break;
3879 	case ISCSI_OP_SCSI_TMFUNC:
3880 		cmd = iscsit_allocate_cmd(conn, TASK_INTERRUPTIBLE);
3881 		if (!cmd)
3882 			goto reject;
3883 
3884 		ret = iscsit_handle_task_mgt_cmd(conn, cmd, buf);
3885 		break;
3886 	case ISCSI_OP_TEXT:
3887 		if (hdr->ttt != cpu_to_be32(0xFFFFFFFF)) {
3888 			cmd = iscsit_find_cmd_from_itt(conn, hdr->itt);
3889 			if (!cmd)
3890 				goto reject;
3891 		} else {
3892 			cmd = iscsit_allocate_cmd(conn, TASK_INTERRUPTIBLE);
3893 			if (!cmd)
3894 				goto reject;
3895 		}
3896 
3897 		ret = iscsit_handle_text_cmd(conn, cmd, buf);
3898 		break;
3899 	case ISCSI_OP_LOGOUT:
3900 		cmd = iscsit_allocate_cmd(conn, TASK_INTERRUPTIBLE);
3901 		if (!cmd)
3902 			goto reject;
3903 
3904 		ret = iscsit_handle_logout_cmd(conn, cmd, buf);
3905 		if (ret > 0)
3906 			wait_for_completion_timeout(&conn->conn_logout_comp,
3907 					SECONDS_FOR_LOGOUT_COMP * HZ);
3908 		break;
3909 	case ISCSI_OP_SNACK:
3910 		ret = iscsit_handle_snack(conn, buf);
3911 		break;
3912 	default:
3913 		pr_err("Got unknown iSCSI OpCode: 0x%02x\n", hdr->opcode);
3914 		if (!conn->sess->sess_ops->ErrorRecoveryLevel) {
3915 			pr_err("Cannot recover from unknown"
3916 			" opcode while ERL=0, closing iSCSI connection.\n");
3917 			return -1;
3918 		}
3919 		pr_err("Unable to recover from unknown opcode while OFMarker=No,"
3920 		       " closing iSCSI connection.\n");
3921 		ret = -1;
3922 		break;
3923 	}
3924 
3925 	return ret;
3926 reject:
3927 	return iscsit_add_reject(conn, ISCSI_REASON_BOOKMARK_NO_RESOURCES, buf);
3928 }
3929 
3930 static bool iscsi_target_check_conn_state(struct iscsi_conn *conn)
3931 {
3932 	bool ret;
3933 
3934 	spin_lock_bh(&conn->state_lock);
3935 	ret = (conn->conn_state != TARG_CONN_STATE_LOGGED_IN);
3936 	spin_unlock_bh(&conn->state_lock);
3937 
3938 	return ret;
3939 }
3940 
3941 static void iscsit_get_rx_pdu(struct iscsi_conn *conn)
3942 {
3943 	int ret;
3944 	u8 *buffer, opcode;
3945 	u32 checksum = 0, digest = 0;
3946 	struct kvec iov;
3947 
3948 	buffer = kcalloc(ISCSI_HDR_LEN, sizeof(*buffer), GFP_KERNEL);
3949 	if (!buffer)
3950 		return;
3951 
3952 	while (!kthread_should_stop()) {
3953 		/*
3954 		 * Ensure that both TX and RX per connection kthreads
3955 		 * are scheduled to run on the same CPU.
3956 		 */
3957 		iscsit_thread_check_cpumask(conn, current, 0);
3958 
3959 		memset(&iov, 0, sizeof(struct kvec));
3960 
3961 		iov.iov_base	= buffer;
3962 		iov.iov_len	= ISCSI_HDR_LEN;
3963 
3964 		ret = rx_data(conn, &iov, 1, ISCSI_HDR_LEN);
3965 		if (ret != ISCSI_HDR_LEN) {
3966 			iscsit_rx_thread_wait_for_tcp(conn);
3967 			break;
3968 		}
3969 
3970 		if (conn->conn_ops->HeaderDigest) {
3971 			iov.iov_base	= &digest;
3972 			iov.iov_len	= ISCSI_CRC_LEN;
3973 
3974 			ret = rx_data(conn, &iov, 1, ISCSI_CRC_LEN);
3975 			if (ret != ISCSI_CRC_LEN) {
3976 				iscsit_rx_thread_wait_for_tcp(conn);
3977 				break;
3978 			}
3979 
3980 			iscsit_do_crypto_hash_buf(conn->conn_rx_hash, buffer,
3981 						  ISCSI_HDR_LEN, 0, NULL,
3982 						  &checksum);
3983 
3984 			if (digest != checksum) {
3985 				pr_err("HeaderDigest CRC32C failed,"
3986 					" received 0x%08x, computed 0x%08x\n",
3987 					digest, checksum);
3988 				/*
3989 				 * Set the PDU to 0xff so it will intentionally
3990 				 * hit default in the switch below.
3991 				 */
3992 				memset(buffer, 0xff, ISCSI_HDR_LEN);
3993 				atomic_long_inc(&conn->sess->conn_digest_errors);
3994 			} else {
3995 				pr_debug("Got HeaderDigest CRC32C"
3996 						" 0x%08x\n", checksum);
3997 			}
3998 		}
3999 
4000 		if (conn->conn_state == TARG_CONN_STATE_IN_LOGOUT)
4001 			break;
4002 
4003 		opcode = buffer[0] & ISCSI_OPCODE_MASK;
4004 
4005 		if (conn->sess->sess_ops->SessionType &&
4006 		   ((!(opcode & ISCSI_OP_TEXT)) ||
4007 		    (!(opcode & ISCSI_OP_LOGOUT)))) {
4008 			pr_err("Received illegal iSCSI Opcode: 0x%02x"
4009 			" while in Discovery Session, rejecting.\n", opcode);
4010 			iscsit_add_reject(conn, ISCSI_REASON_PROTOCOL_ERROR,
4011 					  buffer);
4012 			break;
4013 		}
4014 
4015 		ret = iscsi_target_rx_opcode(conn, buffer);
4016 		if (ret < 0)
4017 			break;
4018 	}
4019 
4020 	kfree(buffer);
4021 }
4022 
4023 int iscsi_target_rx_thread(void *arg)
4024 {
4025 	int rc;
4026 	struct iscsi_conn *conn = arg;
4027 	bool conn_freed = false;
4028 
4029 	/*
4030 	 * Allow ourselves to be interrupted by SIGINT so that a
4031 	 * connection recovery / failure event can be triggered externally.
4032 	 */
4033 	allow_signal(SIGINT);
4034 	/*
4035 	 * Wait for iscsi_post_login_handler() to complete before allowing
4036 	 * incoming iscsi/tcp socket I/O, and/or failing the connection.
4037 	 */
4038 	rc = wait_for_completion_interruptible(&conn->rx_login_comp);
4039 	if (rc < 0 || iscsi_target_check_conn_state(conn))
4040 		goto out;
4041 
4042 	if (!conn->conn_transport->iscsit_get_rx_pdu)
4043 		return 0;
4044 
4045 	conn->conn_transport->iscsit_get_rx_pdu(conn);
4046 
4047 	if (!signal_pending(current))
4048 		atomic_set(&conn->transport_failed, 1);
4049 	iscsit_take_action_for_connection_exit(conn, &conn_freed);
4050 
4051 out:
4052 	if (!conn_freed) {
4053 		while (!kthread_should_stop()) {
4054 			msleep(100);
4055 		}
4056 	}
4057 
4058 	return 0;
4059 }
4060 
4061 static void iscsit_release_commands_from_conn(struct iscsi_conn *conn)
4062 {
4063 	LIST_HEAD(tmp_list);
4064 	struct iscsi_cmd *cmd = NULL, *cmd_tmp = NULL;
4065 	struct iscsi_session *sess = conn->sess;
4066 	/*
4067 	 * We expect this function to only ever be called from either RX or TX
4068 	 * thread context via iscsit_close_connection() once the other context
4069 	 * has been reset -> returned sleeping pre-handler state.
4070 	 */
4071 	spin_lock_bh(&conn->cmd_lock);
4072 	list_splice_init(&conn->conn_cmd_list, &tmp_list);
4073 
4074 	list_for_each_entry(cmd, &tmp_list, i_conn_node) {
4075 		struct se_cmd *se_cmd = &cmd->se_cmd;
4076 
4077 		if (se_cmd->se_tfo != NULL) {
4078 			spin_lock_irq(&se_cmd->t_state_lock);
4079 			se_cmd->transport_state |= CMD_T_FABRIC_STOP;
4080 			spin_unlock_irq(&se_cmd->t_state_lock);
4081 		}
4082 	}
4083 	spin_unlock_bh(&conn->cmd_lock);
4084 
4085 	list_for_each_entry_safe(cmd, cmd_tmp, &tmp_list, i_conn_node) {
4086 		list_del_init(&cmd->i_conn_node);
4087 
4088 		iscsit_increment_maxcmdsn(cmd, sess);
4089 		iscsit_free_cmd(cmd, true);
4090 
4091 	}
4092 }
4093 
4094 static void iscsit_stop_timers_for_cmds(
4095 	struct iscsi_conn *conn)
4096 {
4097 	struct iscsi_cmd *cmd;
4098 
4099 	spin_lock_bh(&conn->cmd_lock);
4100 	list_for_each_entry(cmd, &conn->conn_cmd_list, i_conn_node) {
4101 		if (cmd->data_direction == DMA_TO_DEVICE)
4102 			iscsit_stop_dataout_timer(cmd);
4103 	}
4104 	spin_unlock_bh(&conn->cmd_lock);
4105 }
4106 
4107 int iscsit_close_connection(
4108 	struct iscsi_conn *conn)
4109 {
4110 	int conn_logout = (conn->conn_state == TARG_CONN_STATE_IN_LOGOUT);
4111 	struct iscsi_session	*sess = conn->sess;
4112 
4113 	pr_debug("Closing iSCSI connection CID %hu on SID:"
4114 		" %u\n", conn->cid, sess->sid);
4115 	/*
4116 	 * Always up conn_logout_comp for the traditional TCP and HW_OFFLOAD
4117 	 * case just in case the RX Thread in iscsi_target_rx_opcode() is
4118 	 * sleeping and the logout response never got sent because the
4119 	 * connection failed.
4120 	 *
4121 	 * However for iser-target, isert_wait4logout() is using conn_logout_comp
4122 	 * to signal logout response TX interrupt completion.  Go ahead and skip
4123 	 * this for iser since isert_rx_opcode() does not wait on logout failure,
4124 	 * and to avoid iscsi_conn pointer dereference in iser-target code.
4125 	 */
4126 	if (!conn->conn_transport->rdma_shutdown)
4127 		complete(&conn->conn_logout_comp);
4128 
4129 	if (!strcmp(current->comm, ISCSI_RX_THREAD_NAME)) {
4130 		if (conn->tx_thread &&
4131 		    cmpxchg(&conn->tx_thread_active, true, false)) {
4132 			send_sig(SIGINT, conn->tx_thread, 1);
4133 			kthread_stop(conn->tx_thread);
4134 		}
4135 	} else if (!strcmp(current->comm, ISCSI_TX_THREAD_NAME)) {
4136 		if (conn->rx_thread &&
4137 		    cmpxchg(&conn->rx_thread_active, true, false)) {
4138 			send_sig(SIGINT, conn->rx_thread, 1);
4139 			kthread_stop(conn->rx_thread);
4140 		}
4141 	}
4142 
4143 	spin_lock(&iscsit_global->ts_bitmap_lock);
4144 	bitmap_release_region(iscsit_global->ts_bitmap, conn->bitmap_id,
4145 			      get_order(1));
4146 	spin_unlock(&iscsit_global->ts_bitmap_lock);
4147 
4148 	iscsit_stop_timers_for_cmds(conn);
4149 	iscsit_stop_nopin_response_timer(conn);
4150 	iscsit_stop_nopin_timer(conn);
4151 
4152 	/*
4153 	 * During Connection recovery drop unacknowledged out of order
4154 	 * commands for this connection, and prepare the other commands
4155 	 * for reallegiance.
4156 	 *
4157 	 * During normal operation clear the out of order commands (but
4158 	 * do not free the struct iscsi_ooo_cmdsn's) and release all
4159 	 * struct iscsi_cmds.
4160 	 */
4161 	if (atomic_read(&conn->connection_recovery)) {
4162 		iscsit_discard_unacknowledged_ooo_cmdsns_for_conn(conn);
4163 		iscsit_prepare_cmds_for_reallegiance(conn);
4164 	} else {
4165 		iscsit_clear_ooo_cmdsns_for_conn(conn);
4166 		iscsit_release_commands_from_conn(conn);
4167 	}
4168 	iscsit_free_queue_reqs_for_conn(conn);
4169 
4170 	/*
4171 	 * Handle decrementing session or connection usage count if
4172 	 * a logout response was not able to be sent because the
4173 	 * connection failed.  Fall back to Session Recovery here.
4174 	 */
4175 	if (atomic_read(&conn->conn_logout_remove)) {
4176 		if (conn->conn_logout_reason == ISCSI_LOGOUT_REASON_CLOSE_SESSION) {
4177 			iscsit_dec_conn_usage_count(conn);
4178 			iscsit_dec_session_usage_count(sess);
4179 		}
4180 		if (conn->conn_logout_reason == ISCSI_LOGOUT_REASON_CLOSE_CONNECTION)
4181 			iscsit_dec_conn_usage_count(conn);
4182 
4183 		atomic_set(&conn->conn_logout_remove, 0);
4184 		atomic_set(&sess->session_reinstatement, 0);
4185 		atomic_set(&sess->session_fall_back_to_erl0, 1);
4186 	}
4187 
4188 	spin_lock_bh(&sess->conn_lock);
4189 	list_del(&conn->conn_list);
4190 
4191 	/*
4192 	 * Attempt to let the Initiator know this connection failed by
4193 	 * sending an Connection Dropped Async Message on another
4194 	 * active connection.
4195 	 */
4196 	if (atomic_read(&conn->connection_recovery))
4197 		iscsit_build_conn_drop_async_message(conn);
4198 
4199 	spin_unlock_bh(&sess->conn_lock);
4200 
4201 	/*
4202 	 * If connection reinstatement is being performed on this connection,
4203 	 * up the connection reinstatement semaphore that is being blocked on
4204 	 * in iscsit_cause_connection_reinstatement().
4205 	 */
4206 	spin_lock_bh(&conn->state_lock);
4207 	if (atomic_read(&conn->sleep_on_conn_wait_comp)) {
4208 		spin_unlock_bh(&conn->state_lock);
4209 		complete(&conn->conn_wait_comp);
4210 		wait_for_completion(&conn->conn_post_wait_comp);
4211 		spin_lock_bh(&conn->state_lock);
4212 	}
4213 
4214 	/*
4215 	 * If connection reinstatement is being performed on this connection
4216 	 * by receiving a REMOVECONNFORRECOVERY logout request, up the
4217 	 * connection wait rcfr semaphore that is being blocked on
4218 	 * an iscsit_connection_reinstatement_rcfr().
4219 	 */
4220 	if (atomic_read(&conn->connection_wait_rcfr)) {
4221 		spin_unlock_bh(&conn->state_lock);
4222 		complete(&conn->conn_wait_rcfr_comp);
4223 		wait_for_completion(&conn->conn_post_wait_comp);
4224 		spin_lock_bh(&conn->state_lock);
4225 	}
4226 	atomic_set(&conn->connection_reinstatement, 1);
4227 	spin_unlock_bh(&conn->state_lock);
4228 
4229 	/*
4230 	 * If any other processes are accessing this connection pointer we
4231 	 * must wait until they have completed.
4232 	 */
4233 	iscsit_check_conn_usage_count(conn);
4234 	target_sess_cmd_list_set_waiting(sess->se_sess);
4235 	target_wait_for_sess_cmds(sess->se_sess);
4236 
4237 	if (conn->conn_transport->iscsit_wait_conn)
4238 		conn->conn_transport->iscsit_wait_conn(conn);
4239 
4240 	ahash_request_free(conn->conn_tx_hash);
4241 	if (conn->conn_rx_hash) {
4242 		struct crypto_ahash *tfm;
4243 
4244 		tfm = crypto_ahash_reqtfm(conn->conn_rx_hash);
4245 		ahash_request_free(conn->conn_rx_hash);
4246 		crypto_free_ahash(tfm);
4247 	}
4248 
4249 	if (conn->sock)
4250 		sock_release(conn->sock);
4251 
4252 	if (conn->conn_transport->iscsit_free_conn)
4253 		conn->conn_transport->iscsit_free_conn(conn);
4254 
4255 	pr_debug("Moving to TARG_CONN_STATE_FREE.\n");
4256 	conn->conn_state = TARG_CONN_STATE_FREE;
4257 	iscsit_free_conn(conn);
4258 
4259 	spin_lock_bh(&sess->conn_lock);
4260 	atomic_dec(&sess->nconn);
4261 	pr_debug("Decremented iSCSI connection count to %hu from node:"
4262 		" %s\n", atomic_read(&sess->nconn),
4263 		sess->sess_ops->InitiatorName);
4264 	/*
4265 	 * Make sure that if one connection fails in an non ERL=2 iSCSI
4266 	 * Session that they all fail.
4267 	 */
4268 	if ((sess->sess_ops->ErrorRecoveryLevel != 2) && !conn_logout &&
4269 	     !atomic_read(&sess->session_logout))
4270 		atomic_set(&sess->session_fall_back_to_erl0, 1);
4271 
4272 	/*
4273 	 * If this was not the last connection in the session, and we are
4274 	 * performing session reinstatement or falling back to ERL=0, call
4275 	 * iscsit_stop_session() without sleeping to shutdown the other
4276 	 * active connections.
4277 	 */
4278 	if (atomic_read(&sess->nconn)) {
4279 		if (!atomic_read(&sess->session_reinstatement) &&
4280 		    !atomic_read(&sess->session_fall_back_to_erl0)) {
4281 			spin_unlock_bh(&sess->conn_lock);
4282 			return 0;
4283 		}
4284 		if (!atomic_read(&sess->session_stop_active)) {
4285 			atomic_set(&sess->session_stop_active, 1);
4286 			spin_unlock_bh(&sess->conn_lock);
4287 			iscsit_stop_session(sess, 0, 0);
4288 			return 0;
4289 		}
4290 		spin_unlock_bh(&sess->conn_lock);
4291 		return 0;
4292 	}
4293 
4294 	/*
4295 	 * If this was the last connection in the session and one of the
4296 	 * following is occurring:
4297 	 *
4298 	 * Session Reinstatement is not being performed, and are falling back
4299 	 * to ERL=0 call iscsit_close_session().
4300 	 *
4301 	 * Session Logout was requested.  iscsit_close_session() will be called
4302 	 * elsewhere.
4303 	 *
4304 	 * Session Continuation is not being performed, start the Time2Retain
4305 	 * handler and check if sleep_on_sess_wait_sem is active.
4306 	 */
4307 	if (!atomic_read(&sess->session_reinstatement) &&
4308 	     atomic_read(&sess->session_fall_back_to_erl0)) {
4309 		spin_unlock_bh(&sess->conn_lock);
4310 		iscsit_close_session(sess);
4311 
4312 		return 0;
4313 	} else if (atomic_read(&sess->session_logout)) {
4314 		pr_debug("Moving to TARG_SESS_STATE_FREE.\n");
4315 		sess->session_state = TARG_SESS_STATE_FREE;
4316 		spin_unlock_bh(&sess->conn_lock);
4317 
4318 		if (atomic_read(&sess->sleep_on_sess_wait_comp))
4319 			complete(&sess->session_wait_comp);
4320 
4321 		return 0;
4322 	} else {
4323 		pr_debug("Moving to TARG_SESS_STATE_FAILED.\n");
4324 		sess->session_state = TARG_SESS_STATE_FAILED;
4325 
4326 		if (!atomic_read(&sess->session_continuation)) {
4327 			spin_unlock_bh(&sess->conn_lock);
4328 			iscsit_start_time2retain_handler(sess);
4329 		} else
4330 			spin_unlock_bh(&sess->conn_lock);
4331 
4332 		if (atomic_read(&sess->sleep_on_sess_wait_comp))
4333 			complete(&sess->session_wait_comp);
4334 
4335 		return 0;
4336 	}
4337 }
4338 
4339 /*
4340  * If the iSCSI Session for the iSCSI Initiator Node exists,
4341  * forcefully shutdown the iSCSI NEXUS.
4342  */
4343 int iscsit_close_session(struct iscsi_session *sess)
4344 {
4345 	struct iscsi_portal_group *tpg = sess->tpg;
4346 	struct se_portal_group *se_tpg = &tpg->tpg_se_tpg;
4347 
4348 	if (atomic_read(&sess->nconn)) {
4349 		pr_err("%d connection(s) still exist for iSCSI session"
4350 			" to %s\n", atomic_read(&sess->nconn),
4351 			sess->sess_ops->InitiatorName);
4352 		BUG();
4353 	}
4354 
4355 	spin_lock_bh(&se_tpg->session_lock);
4356 	atomic_set(&sess->session_logout, 1);
4357 	atomic_set(&sess->session_reinstatement, 1);
4358 	iscsit_stop_time2retain_timer(sess);
4359 	spin_unlock_bh(&se_tpg->session_lock);
4360 
4361 	/*
4362 	 * transport_deregister_session_configfs() will clear the
4363 	 * struct se_node_acl->nacl_sess pointer now as a iscsi_np process context
4364 	 * can be setting it again with __transport_register_session() in
4365 	 * iscsi_post_login_handler() again after the iscsit_stop_session()
4366 	 * completes in iscsi_np context.
4367 	 */
4368 	transport_deregister_session_configfs(sess->se_sess);
4369 
4370 	/*
4371 	 * If any other processes are accessing this session pointer we must
4372 	 * wait until they have completed.  If we are in an interrupt (the
4373 	 * time2retain handler) and contain and active session usage count we
4374 	 * restart the timer and exit.
4375 	 */
4376 	if (!in_interrupt()) {
4377 		if (iscsit_check_session_usage_count(sess) == 1)
4378 			iscsit_stop_session(sess, 1, 1);
4379 	} else {
4380 		if (iscsit_check_session_usage_count(sess) == 2) {
4381 			atomic_set(&sess->session_logout, 0);
4382 			iscsit_start_time2retain_handler(sess);
4383 			return 0;
4384 		}
4385 	}
4386 
4387 	transport_deregister_session(sess->se_sess);
4388 
4389 	if (sess->sess_ops->ErrorRecoveryLevel == 2)
4390 		iscsit_free_connection_recovery_entries(sess);
4391 
4392 	iscsit_free_all_ooo_cmdsns(sess);
4393 
4394 	spin_lock_bh(&se_tpg->session_lock);
4395 	pr_debug("Moving to TARG_SESS_STATE_FREE.\n");
4396 	sess->session_state = TARG_SESS_STATE_FREE;
4397 	pr_debug("Released iSCSI session from node: %s\n",
4398 			sess->sess_ops->InitiatorName);
4399 	tpg->nsessions--;
4400 	if (tpg->tpg_tiqn)
4401 		tpg->tpg_tiqn->tiqn_nsessions--;
4402 
4403 	pr_debug("Decremented number of active iSCSI Sessions on"
4404 		" iSCSI TPG: %hu to %u\n", tpg->tpgt, tpg->nsessions);
4405 
4406 	ida_free(&sess_ida, sess->session_index);
4407 	kfree(sess->sess_ops);
4408 	sess->sess_ops = NULL;
4409 	spin_unlock_bh(&se_tpg->session_lock);
4410 
4411 	kfree(sess);
4412 	return 0;
4413 }
4414 
4415 static void iscsit_logout_post_handler_closesession(
4416 	struct iscsi_conn *conn)
4417 {
4418 	struct iscsi_session *sess = conn->sess;
4419 	int sleep = 1;
4420 	/*
4421 	 * Traditional iscsi/tcp will invoke this logic from TX thread
4422 	 * context during session logout, so clear tx_thread_active and
4423 	 * sleep if iscsit_close_connection() has not already occured.
4424 	 *
4425 	 * Since iser-target invokes this logic from it's own workqueue,
4426 	 * always sleep waiting for RX/TX thread shutdown to complete
4427 	 * within iscsit_close_connection().
4428 	 */
4429 	if (!conn->conn_transport->rdma_shutdown) {
4430 		sleep = cmpxchg(&conn->tx_thread_active, true, false);
4431 		if (!sleep)
4432 			return;
4433 	}
4434 
4435 	atomic_set(&conn->conn_logout_remove, 0);
4436 	complete(&conn->conn_logout_comp);
4437 
4438 	iscsit_dec_conn_usage_count(conn);
4439 	iscsit_stop_session(sess, sleep, sleep);
4440 	iscsit_dec_session_usage_count(sess);
4441 	iscsit_close_session(sess);
4442 }
4443 
4444 static void iscsit_logout_post_handler_samecid(
4445 	struct iscsi_conn *conn)
4446 {
4447 	int sleep = 1;
4448 
4449 	if (!conn->conn_transport->rdma_shutdown) {
4450 		sleep = cmpxchg(&conn->tx_thread_active, true, false);
4451 		if (!sleep)
4452 			return;
4453 	}
4454 
4455 	atomic_set(&conn->conn_logout_remove, 0);
4456 	complete(&conn->conn_logout_comp);
4457 
4458 	iscsit_cause_connection_reinstatement(conn, sleep);
4459 	iscsit_dec_conn_usage_count(conn);
4460 }
4461 
4462 static void iscsit_logout_post_handler_diffcid(
4463 	struct iscsi_conn *conn,
4464 	u16 cid)
4465 {
4466 	struct iscsi_conn *l_conn;
4467 	struct iscsi_session *sess = conn->sess;
4468 	bool conn_found = false;
4469 
4470 	if (!sess)
4471 		return;
4472 
4473 	spin_lock_bh(&sess->conn_lock);
4474 	list_for_each_entry(l_conn, &sess->sess_conn_list, conn_list) {
4475 		if (l_conn->cid == cid) {
4476 			iscsit_inc_conn_usage_count(l_conn);
4477 			conn_found = true;
4478 			break;
4479 		}
4480 	}
4481 	spin_unlock_bh(&sess->conn_lock);
4482 
4483 	if (!conn_found)
4484 		return;
4485 
4486 	if (l_conn->sock)
4487 		l_conn->sock->ops->shutdown(l_conn->sock, RCV_SHUTDOWN);
4488 
4489 	spin_lock_bh(&l_conn->state_lock);
4490 	pr_debug("Moving to TARG_CONN_STATE_IN_LOGOUT.\n");
4491 	l_conn->conn_state = TARG_CONN_STATE_IN_LOGOUT;
4492 	spin_unlock_bh(&l_conn->state_lock);
4493 
4494 	iscsit_cause_connection_reinstatement(l_conn, 1);
4495 	iscsit_dec_conn_usage_count(l_conn);
4496 }
4497 
4498 /*
4499  *	Return of 0 causes the TX thread to restart.
4500  */
4501 int iscsit_logout_post_handler(
4502 	struct iscsi_cmd *cmd,
4503 	struct iscsi_conn *conn)
4504 {
4505 	int ret = 0;
4506 
4507 	switch (cmd->logout_reason) {
4508 	case ISCSI_LOGOUT_REASON_CLOSE_SESSION:
4509 		switch (cmd->logout_response) {
4510 		case ISCSI_LOGOUT_SUCCESS:
4511 		case ISCSI_LOGOUT_CLEANUP_FAILED:
4512 		default:
4513 			iscsit_logout_post_handler_closesession(conn);
4514 			break;
4515 		}
4516 		ret = 0;
4517 		break;
4518 	case ISCSI_LOGOUT_REASON_CLOSE_CONNECTION:
4519 		if (conn->cid == cmd->logout_cid) {
4520 			switch (cmd->logout_response) {
4521 			case ISCSI_LOGOUT_SUCCESS:
4522 			case ISCSI_LOGOUT_CLEANUP_FAILED:
4523 			default:
4524 				iscsit_logout_post_handler_samecid(conn);
4525 				break;
4526 			}
4527 			ret = 0;
4528 		} else {
4529 			switch (cmd->logout_response) {
4530 			case ISCSI_LOGOUT_SUCCESS:
4531 				iscsit_logout_post_handler_diffcid(conn,
4532 					cmd->logout_cid);
4533 				break;
4534 			case ISCSI_LOGOUT_CID_NOT_FOUND:
4535 			case ISCSI_LOGOUT_CLEANUP_FAILED:
4536 			default:
4537 				break;
4538 			}
4539 			ret = 1;
4540 		}
4541 		break;
4542 	case ISCSI_LOGOUT_REASON_RECOVERY:
4543 		switch (cmd->logout_response) {
4544 		case ISCSI_LOGOUT_SUCCESS:
4545 		case ISCSI_LOGOUT_CID_NOT_FOUND:
4546 		case ISCSI_LOGOUT_RECOVERY_UNSUPPORTED:
4547 		case ISCSI_LOGOUT_CLEANUP_FAILED:
4548 		default:
4549 			break;
4550 		}
4551 		ret = 1;
4552 		break;
4553 	default:
4554 		break;
4555 
4556 	}
4557 	return ret;
4558 }
4559 EXPORT_SYMBOL(iscsit_logout_post_handler);
4560 
4561 void iscsit_fail_session(struct iscsi_session *sess)
4562 {
4563 	struct iscsi_conn *conn;
4564 
4565 	spin_lock_bh(&sess->conn_lock);
4566 	list_for_each_entry(conn, &sess->sess_conn_list, conn_list) {
4567 		pr_debug("Moving to TARG_CONN_STATE_CLEANUP_WAIT.\n");
4568 		conn->conn_state = TARG_CONN_STATE_CLEANUP_WAIT;
4569 	}
4570 	spin_unlock_bh(&sess->conn_lock);
4571 
4572 	pr_debug("Moving to TARG_SESS_STATE_FAILED.\n");
4573 	sess->session_state = TARG_SESS_STATE_FAILED;
4574 }
4575 
4576 int iscsit_free_session(struct iscsi_session *sess)
4577 {
4578 	u16 conn_count = atomic_read(&sess->nconn);
4579 	struct iscsi_conn *conn, *conn_tmp = NULL;
4580 	int is_last;
4581 
4582 	spin_lock_bh(&sess->conn_lock);
4583 	atomic_set(&sess->sleep_on_sess_wait_comp, 1);
4584 
4585 	list_for_each_entry_safe(conn, conn_tmp, &sess->sess_conn_list,
4586 			conn_list) {
4587 		if (conn_count == 0)
4588 			break;
4589 
4590 		if (list_is_last(&conn->conn_list, &sess->sess_conn_list)) {
4591 			is_last = 1;
4592 		} else {
4593 			iscsit_inc_conn_usage_count(conn_tmp);
4594 			is_last = 0;
4595 		}
4596 		iscsit_inc_conn_usage_count(conn);
4597 
4598 		spin_unlock_bh(&sess->conn_lock);
4599 		iscsit_cause_connection_reinstatement(conn, 1);
4600 		spin_lock_bh(&sess->conn_lock);
4601 
4602 		iscsit_dec_conn_usage_count(conn);
4603 		if (is_last == 0)
4604 			iscsit_dec_conn_usage_count(conn_tmp);
4605 
4606 		conn_count--;
4607 	}
4608 
4609 	if (atomic_read(&sess->nconn)) {
4610 		spin_unlock_bh(&sess->conn_lock);
4611 		wait_for_completion(&sess->session_wait_comp);
4612 	} else
4613 		spin_unlock_bh(&sess->conn_lock);
4614 
4615 	iscsit_close_session(sess);
4616 	return 0;
4617 }
4618 
4619 void iscsit_stop_session(
4620 	struct iscsi_session *sess,
4621 	int session_sleep,
4622 	int connection_sleep)
4623 {
4624 	u16 conn_count = atomic_read(&sess->nconn);
4625 	struct iscsi_conn *conn, *conn_tmp = NULL;
4626 	int is_last;
4627 
4628 	spin_lock_bh(&sess->conn_lock);
4629 	if (session_sleep)
4630 		atomic_set(&sess->sleep_on_sess_wait_comp, 1);
4631 
4632 	if (connection_sleep) {
4633 		list_for_each_entry_safe(conn, conn_tmp, &sess->sess_conn_list,
4634 				conn_list) {
4635 			if (conn_count == 0)
4636 				break;
4637 
4638 			if (list_is_last(&conn->conn_list, &sess->sess_conn_list)) {
4639 				is_last = 1;
4640 			} else {
4641 				iscsit_inc_conn_usage_count(conn_tmp);
4642 				is_last = 0;
4643 			}
4644 			iscsit_inc_conn_usage_count(conn);
4645 
4646 			spin_unlock_bh(&sess->conn_lock);
4647 			iscsit_cause_connection_reinstatement(conn, 1);
4648 			spin_lock_bh(&sess->conn_lock);
4649 
4650 			iscsit_dec_conn_usage_count(conn);
4651 			if (is_last == 0)
4652 				iscsit_dec_conn_usage_count(conn_tmp);
4653 			conn_count--;
4654 		}
4655 	} else {
4656 		list_for_each_entry(conn, &sess->sess_conn_list, conn_list)
4657 			iscsit_cause_connection_reinstatement(conn, 0);
4658 	}
4659 
4660 	if (session_sleep && atomic_read(&sess->nconn)) {
4661 		spin_unlock_bh(&sess->conn_lock);
4662 		wait_for_completion(&sess->session_wait_comp);
4663 	} else
4664 		spin_unlock_bh(&sess->conn_lock);
4665 }
4666 
4667 int iscsit_release_sessions_for_tpg(struct iscsi_portal_group *tpg, int force)
4668 {
4669 	struct iscsi_session *sess;
4670 	struct se_portal_group *se_tpg = &tpg->tpg_se_tpg;
4671 	struct se_session *se_sess, *se_sess_tmp;
4672 	LIST_HEAD(free_list);
4673 	int session_count = 0;
4674 
4675 	spin_lock_bh(&se_tpg->session_lock);
4676 	if (tpg->nsessions && !force) {
4677 		spin_unlock_bh(&se_tpg->session_lock);
4678 		return -1;
4679 	}
4680 
4681 	list_for_each_entry_safe(se_sess, se_sess_tmp, &se_tpg->tpg_sess_list,
4682 			sess_list) {
4683 		sess = (struct iscsi_session *)se_sess->fabric_sess_ptr;
4684 
4685 		spin_lock(&sess->conn_lock);
4686 		if (atomic_read(&sess->session_fall_back_to_erl0) ||
4687 		    atomic_read(&sess->session_logout) ||
4688 		    (sess->time2retain_timer_flags & ISCSI_TF_EXPIRED)) {
4689 			spin_unlock(&sess->conn_lock);
4690 			continue;
4691 		}
4692 		atomic_set(&sess->session_reinstatement, 1);
4693 		atomic_set(&sess->session_fall_back_to_erl0, 1);
4694 		spin_unlock(&sess->conn_lock);
4695 
4696 		list_move_tail(&se_sess->sess_list, &free_list);
4697 	}
4698 	spin_unlock_bh(&se_tpg->session_lock);
4699 
4700 	list_for_each_entry_safe(se_sess, se_sess_tmp, &free_list, sess_list) {
4701 		sess = (struct iscsi_session *)se_sess->fabric_sess_ptr;
4702 
4703 		iscsit_free_session(sess);
4704 		session_count++;
4705 	}
4706 
4707 	pr_debug("Released %d iSCSI Session(s) from Target Portal"
4708 			" Group: %hu\n", session_count, tpg->tpgt);
4709 	return 0;
4710 }
4711 
4712 MODULE_DESCRIPTION("iSCSI-Target Driver for mainline target infrastructure");
4713 MODULE_VERSION("4.1.x");
4714 MODULE_AUTHOR("nab@Linux-iSCSI.org");
4715 MODULE_LICENSE("GPL");
4716 
4717 module_init(iscsi_target_init_module);
4718 module_exit(iscsi_target_cleanup_module);
4719