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