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