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