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