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