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