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