xref: /spdk/lib/iscsi/iscsi.c (revision db35950a13859f8680bb97c961337d3317a974b2)
1 /*-
2  *   BSD LICENSE
3  *
4  *   Copyright (C) 2008-2012 Daisuke Aoyama <aoyama@peach.ne.jp>.
5  *   Copyright (c) Intel Corporation.
6  *   All rights reserved.
7  *
8  *   Redistribution and use in source and binary forms, with or without
9  *   modification, are permitted provided that the following conditions
10  *   are met:
11  *
12  *     * Redistributions of source code must retain the above copyright
13  *       notice, this list of conditions and the following disclaimer.
14  *     * Redistributions in binary form must reproduce the above copyright
15  *       notice, this list of conditions and the following disclaimer in
16  *       the documentation and/or other materials provided with the
17  *       distribution.
18  *     * Neither the name of Intel Corporation nor the names of its
19  *       contributors may be used to endorse or promote products derived
20  *       from this software without specific prior written permission.
21  *
22  *   THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
23  *   "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
24  *   LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
25  *   A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
26  *   OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
27  *   SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
28  *   LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
29  *   DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
30  *   THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
31  *   (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
32  *   OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
33  */
34 
35 #include "spdk/stdinc.h"
36 
37 #include "spdk/base64.h"
38 #include "spdk/crc32.h"
39 #include "spdk/endian.h"
40 #include "spdk/env.h"
41 #include "spdk/likely.h"
42 #include "spdk/trace.h"
43 #include "spdk/sock.h"
44 #include "spdk/string.h"
45 #include "spdk/queue.h"
46 #include "spdk/net.h"
47 
48 #include "iscsi/md5.h"
49 #include "iscsi/iscsi.h"
50 #include "iscsi/param.h"
51 #include "iscsi/tgt_node.h"
52 #include "iscsi/task.h"
53 #include "iscsi/conn.h"
54 #include "spdk/scsi.h"
55 #include "spdk/bdev.h"
56 #include "iscsi/portal_grp.h"
57 
58 #include "spdk/log.h"
59 
60 #include "spdk_internal/sgl.h"
61 
62 #define MAX_TMPBUF 1024
63 
64 #ifdef __FreeBSD__
65 #define HAVE_SRANDOMDEV 1
66 #define HAVE_ARC4RANDOM 1
67 #endif
68 
69 struct spdk_iscsi_globals g_iscsi = {
70 	.mutex = PTHREAD_MUTEX_INITIALIZER,
71 	.portal_head = TAILQ_HEAD_INITIALIZER(g_iscsi.portal_head),
72 	.pg_head = TAILQ_HEAD_INITIALIZER(g_iscsi.pg_head),
73 	.ig_head = TAILQ_HEAD_INITIALIZER(g_iscsi.ig_head),
74 	.target_head = TAILQ_HEAD_INITIALIZER(g_iscsi.target_head),
75 	.auth_group_head = TAILQ_HEAD_INITIALIZER(g_iscsi.auth_group_head),
76 	.poll_group_head = TAILQ_HEAD_INITIALIZER(g_iscsi.poll_group_head),
77 };
78 
79 #define MATCH_DIGEST_WORD(BUF, CRC32C) \
80 	(    ((((uint32_t) *((uint8_t *)(BUF)+0)) << 0)		\
81 	    | (((uint32_t) *((uint8_t *)(BUF)+1)) << 8)		\
82 	    | (((uint32_t) *((uint8_t *)(BUF)+2)) << 16)	\
83 	    | (((uint32_t) *((uint8_t *)(BUF)+3)) << 24))	\
84 	    == (CRC32C))
85 
86 #ifndef HAVE_SRANDOMDEV
87 static void
88 srandomdev(void)
89 {
90 	unsigned long seed;
91 	time_t now;
92 	pid_t pid;
93 
94 	pid = getpid();
95 	now = time(NULL);
96 	seed = pid ^ now;
97 	srandom(seed);
98 }
99 #endif /* HAVE_SRANDOMDEV */
100 
101 #ifndef HAVE_ARC4RANDOM
102 static int g_arc4random_initialized = 0;
103 
104 static uint32_t
105 arc4random(void)
106 {
107 	uint32_t r;
108 	uint32_t r1, r2;
109 
110 	if (!g_arc4random_initialized) {
111 		srandomdev();
112 		g_arc4random_initialized = 1;
113 	}
114 	r1 = (uint32_t)(random() & 0xffff);
115 	r2 = (uint32_t)(random() & 0xffff);
116 	r = (r1 << 16) | r2;
117 	return r;
118 }
119 #endif /* HAVE_ARC4RANDOM */
120 
121 static void
122 gen_random(uint8_t *buf, size_t len)
123 {
124 	uint32_t r;
125 	size_t idx;
126 
127 	for (idx = 0; idx < len; idx++) {
128 		r = arc4random();
129 		buf[idx] = (uint8_t) r;
130 	}
131 }
132 
133 static uint64_t
134 iscsi_get_isid(const uint8_t isid[6])
135 {
136 	return (uint64_t)isid[0] << 40 |
137 	       (uint64_t)isid[1] << 32 |
138 	       (uint64_t)isid[2] << 24 |
139 	       (uint64_t)isid[3] << 16 |
140 	       (uint64_t)isid[4] << 8 |
141 	       (uint64_t)isid[5];
142 }
143 
144 static int
145 bin2hex(char *buf, size_t len, const uint8_t *data, size_t data_len)
146 {
147 	const char *digits = "0123456789ABCDEF";
148 	size_t total = 0;
149 	size_t idx;
150 
151 	if (len < 3) {
152 		return -1;
153 	}
154 	buf[total] = '0';
155 	total++;
156 	buf[total] = 'x';
157 	total++;
158 	buf[total] = '\0';
159 
160 	for (idx = 0; idx < data_len; idx++) {
161 		if (total + 3 > len) {
162 			buf[total] = '\0';
163 			return - 1;
164 		}
165 		buf[total] = digits[(data[idx] >> 4) & 0x0fU];
166 		total++;
167 		buf[total] = digits[data[idx] & 0x0fU];
168 		total++;
169 	}
170 	buf[total] = '\0';
171 	return total;
172 }
173 
174 static int
175 hex2bin(uint8_t *data, size_t data_len, const char *str)
176 {
177 	const char *digits = "0123456789ABCDEF";
178 	const char *dp;
179 	const char *p;
180 	size_t total = 0;
181 	int n0, n1;
182 
183 	p = str;
184 	if (p[0] != '0' && (p[1] != 'x' && p[1] != 'X')) {
185 		return -1;
186 	}
187 	p += 2;
188 
189 	while (p[0] != '\0' && p[1] != '\0') {
190 		if (total >= data_len) {
191 			return -1;
192 		}
193 		dp = strchr(digits, toupper((int) p[0]));
194 		if (dp == NULL) {
195 			return -1;
196 		}
197 		n0 = (int)(dp - digits);
198 		dp = strchr(digits, toupper((int) p[1]));
199 		if (dp == NULL) {
200 			return -1;
201 		}
202 		n1 = (int)(dp - digits);
203 
204 		data[total] = (uint8_t)(((n0 & 0x0fU) << 4) | (n1 & 0x0fU));
205 		total++;
206 		p += 2;
207 	}
208 	return total;
209 }
210 
211 static int
212 iscsi_reject(struct spdk_iscsi_conn *conn, struct spdk_iscsi_pdu *pdu,
213 	     int reason)
214 {
215 	struct spdk_iscsi_pdu *rsp_pdu;
216 	struct iscsi_bhs_reject *rsph;
217 	uint8_t *data;
218 	int total_ahs_len;
219 	int data_len;
220 	int alloc_len;
221 
222 	pdu->is_rejected = true;
223 
224 	total_ahs_len = pdu->bhs.total_ahs_len;
225 	data_len = 0;
226 	alloc_len = ISCSI_BHS_LEN + (4 * total_ahs_len);
227 
228 	if (conn->header_digest) {
229 		alloc_len += ISCSI_DIGEST_LEN;
230 	}
231 
232 	data = calloc(1, alloc_len);
233 	if (!data) {
234 		SPDK_ERRLOG("calloc() failed for data segment\n");
235 		return -ENOMEM;
236 	}
237 
238 	SPDK_DEBUGLOG(iscsi, "Reject PDU reason=%d\n", reason);
239 
240 	if (conn->sess != NULL) {
241 		SPDK_DEBUGLOG(iscsi,
242 			      "StatSN=%u, ExpCmdSN=%u, MaxCmdSN=%u\n",
243 			      conn->StatSN, conn->sess->ExpCmdSN,
244 			      conn->sess->MaxCmdSN);
245 	} else {
246 		SPDK_DEBUGLOG(iscsi, "StatSN=%u\n", conn->StatSN);
247 	}
248 
249 	memcpy(data, &pdu->bhs, ISCSI_BHS_LEN);
250 	data_len += ISCSI_BHS_LEN;
251 
252 	if (total_ahs_len != 0) {
253 		total_ahs_len = spdk_min((4 * total_ahs_len), ISCSI_AHS_LEN);
254 		memcpy(data + data_len, pdu->ahs, total_ahs_len);
255 		data_len += total_ahs_len;
256 	}
257 
258 	if (conn->header_digest) {
259 		memcpy(data + data_len, pdu->header_digest, ISCSI_DIGEST_LEN);
260 		data_len += ISCSI_DIGEST_LEN;
261 	}
262 
263 	rsp_pdu = iscsi_get_pdu(conn);
264 	if (rsp_pdu == NULL) {
265 		free(data);
266 		return -ENOMEM;
267 	}
268 
269 	rsph = (struct iscsi_bhs_reject *)&rsp_pdu->bhs;
270 	rsp_pdu->data = data;
271 	rsph->opcode = ISCSI_OP_REJECT;
272 	rsph->flags |= 0x80;	/* bit 0 is default to 1 */
273 	rsph->reason = reason;
274 	DSET24(rsph->data_segment_len, data_len);
275 
276 	rsph->ffffffff = 0xffffffffU;
277 	to_be32(&rsph->stat_sn, conn->StatSN);
278 	conn->StatSN++;
279 
280 	if (conn->sess != NULL) {
281 		to_be32(&rsph->exp_cmd_sn, conn->sess->ExpCmdSN);
282 		to_be32(&rsph->max_cmd_sn, conn->sess->MaxCmdSN);
283 	} else {
284 		to_be32(&rsph->exp_cmd_sn, 1);
285 		to_be32(&rsph->max_cmd_sn, 1);
286 	}
287 
288 	SPDK_LOGDUMP(iscsi, "PDU", (void *)&rsp_pdu->bhs, ISCSI_BHS_LEN);
289 
290 	iscsi_conn_write_pdu(conn, rsp_pdu, iscsi_conn_pdu_generic_complete, NULL);
291 
292 	return 0;
293 }
294 
295 uint32_t
296 iscsi_pdu_calc_header_digest(struct spdk_iscsi_pdu *pdu)
297 {
298 	uint32_t crc32c;
299 	uint32_t ahs_len_bytes = pdu->bhs.total_ahs_len * 4;
300 
301 	crc32c = SPDK_CRC32C_INITIAL;
302 	crc32c = spdk_crc32c_update(&pdu->bhs, ISCSI_BHS_LEN, crc32c);
303 
304 	if (ahs_len_bytes) {
305 		crc32c = spdk_crc32c_update(pdu->ahs, ahs_len_bytes, crc32c);
306 	}
307 
308 	/* BHS and AHS are always 4-byte multiples in length, so no padding is necessary. */
309 	crc32c = crc32c ^ SPDK_CRC32C_XOR;
310 	return crc32c;
311 }
312 
313 static void
314 _iscsi_pdu_calc_data_digest(struct spdk_iscsi_pdu *pdu)
315 {
316 	struct iovec iov;
317 	uint32_t num_blocks;
318 
319 	if (spdk_likely(!pdu->dif_insert_or_strip)) {
320 		pdu->crc32c = spdk_crc32c_update(pdu->data,
321 						 pdu->data_valid_bytes - pdu->data_offset,
322 						 pdu->crc32c);
323 	} else {
324 		iov.iov_base = pdu->data;
325 		iov.iov_len = pdu->data_buf_len;
326 		num_blocks = pdu->data_buf_len / pdu->dif_ctx.block_size;
327 
328 		spdk_dif_update_crc32c(&iov, 1, num_blocks, &pdu->crc32c, &pdu->dif_ctx);
329 	}
330 }
331 
332 static uint32_t
333 _iscsi_pdu_finalize_data_digest(struct spdk_iscsi_pdu *pdu)
334 {
335 	uint32_t crc32c = pdu->crc32c;
336 	uint32_t mod;
337 
338 	mod = pdu->data_valid_bytes % ISCSI_ALIGNMENT;
339 	if (mod != 0) {
340 		uint32_t pad_length = ISCSI_ALIGNMENT - mod;
341 		uint8_t pad[3] = {0, 0, 0};
342 
343 		assert(pad_length > 0);
344 		assert(pad_length <= sizeof(pad));
345 		crc32c = spdk_crc32c_update(pad, pad_length, crc32c);
346 	}
347 
348 	crc32c = crc32c ^ SPDK_CRC32C_XOR;
349 	return crc32c;
350 }
351 
352 uint32_t
353 iscsi_pdu_calc_data_digest(struct spdk_iscsi_pdu *pdu)
354 {
355 	_iscsi_pdu_calc_data_digest(pdu);
356 	return _iscsi_pdu_finalize_data_digest(pdu);
357 }
358 
359 static int
360 iscsi_conn_read_data_segment(struct spdk_iscsi_conn *conn,
361 			     struct spdk_iscsi_pdu *pdu,
362 			     uint32_t data_offset, uint32_t data_len)
363 {
364 	struct iovec buf_iov, iovs[32];
365 	int rc, _rc;
366 
367 	if (spdk_likely(!pdu->dif_insert_or_strip)) {
368 		return iscsi_conn_read_data(conn, data_len, pdu->data + data_offset);
369 	} else {
370 		buf_iov.iov_base = pdu->data;
371 		buf_iov.iov_len = pdu->data_buf_len;
372 		rc = spdk_dif_set_md_interleave_iovs(iovs, 32, &buf_iov, 1,
373 						     data_offset, data_len, NULL,
374 						     &pdu->dif_ctx);
375 		if (rc > 0) {
376 			rc = iscsi_conn_readv_data(conn, iovs, rc);
377 			if (rc > 0) {
378 				_rc = spdk_dif_generate_stream(&buf_iov, 1, data_offset, rc,
379 							       &pdu->dif_ctx);
380 				if (_rc != 0) {
381 					SPDK_ERRLOG("DIF generate failed\n");
382 					rc = _rc;
383 				}
384 			}
385 		} else {
386 			SPDK_ERRLOG("Setup iovs for interleaved metadata failed\n");
387 		}
388 		return rc;
389 	}
390 }
391 
392 /* Build iovec array to leave metadata space for every data block
393  * when reading data segment from socket.
394  */
395 static inline bool
396 _iscsi_sgl_append_with_md(struct spdk_iov_sgl *s,
397 			  void *buf, uint32_t buf_len, uint32_t data_len,
398 			  struct spdk_dif_ctx *dif_ctx)
399 {
400 	int rc;
401 	uint32_t total_size = 0;
402 	struct iovec buf_iov;
403 
404 	if (s->iov_offset >= data_len) {
405 		s->iov_offset -= data_len;
406 	} else {
407 		buf_iov.iov_base = buf;
408 		buf_iov.iov_len = buf_len;
409 		rc = spdk_dif_set_md_interleave_iovs(s->iov, s->iovcnt, &buf_iov, 1,
410 						     s->iov_offset, data_len - s->iov_offset,
411 						     &total_size, dif_ctx);
412 		if (rc < 0) {
413 			SPDK_ERRLOG("Failed to setup iovs for DIF strip\n");
414 			return false;
415 		}
416 
417 		s->total_size += total_size;
418 		s->iov_offset = 0;
419 		assert(s->iovcnt >= rc);
420 		s->iovcnt -= rc;
421 		s->iov += rc;
422 
423 		if (s->iovcnt == 0) {
424 			return false;
425 		}
426 	}
427 
428 	return true;
429 }
430 
431 int
432 iscsi_build_iovs(struct spdk_iscsi_conn *conn, struct iovec *iovs, int iovcnt,
433 		 struct spdk_iscsi_pdu *pdu, uint32_t *_mapped_length)
434 {
435 	struct spdk_iov_sgl sgl;
436 	int enable_digest;
437 	uint32_t total_ahs_len;
438 	uint32_t data_len;
439 
440 	if (iovcnt == 0) {
441 		return 0;
442 	}
443 
444 	total_ahs_len = pdu->bhs.total_ahs_len;
445 	data_len = DGET24(pdu->bhs.data_segment_len);
446 	data_len = ISCSI_ALIGN(data_len);
447 
448 	enable_digest = 1;
449 	if (pdu->bhs.opcode == ISCSI_OP_LOGIN_RSP) {
450 		/* this PDU should be sent without digest */
451 		enable_digest = 0;
452 	}
453 
454 	spdk_iov_sgl_init(&sgl, iovs, iovcnt, pdu->writev_offset);
455 
456 	/* BHS */
457 	if (!spdk_iov_sgl_append(&sgl, (uint8_t *)&pdu->bhs, ISCSI_BHS_LEN)) {
458 		goto end;
459 	}
460 	/* AHS */
461 	if (total_ahs_len > 0) {
462 		if (!spdk_iov_sgl_append(&sgl, pdu->ahs, 4 * total_ahs_len)) {
463 			goto end;
464 		}
465 	}
466 
467 	/* Header Digest */
468 	if (enable_digest && conn->header_digest) {
469 		if (!spdk_iov_sgl_append(&sgl, pdu->header_digest, ISCSI_DIGEST_LEN)) {
470 			goto end;
471 		}
472 	}
473 
474 	/* Data Segment */
475 	if (data_len > 0) {
476 		if (!pdu->dif_insert_or_strip) {
477 			if (!spdk_iov_sgl_append(&sgl, pdu->data, data_len)) {
478 				goto end;
479 			}
480 		} else {
481 			if (!_iscsi_sgl_append_with_md(&sgl, pdu->data, pdu->data_buf_len,
482 						       data_len, &pdu->dif_ctx)) {
483 				goto end;
484 			}
485 		}
486 	}
487 
488 	/* Data Digest */
489 	if (enable_digest && conn->data_digest && data_len != 0) {
490 		spdk_iov_sgl_append(&sgl, pdu->data_digest, ISCSI_DIGEST_LEN);
491 	}
492 
493 end:
494 	if (_mapped_length != NULL) {
495 		*_mapped_length = sgl.total_size;
496 	}
497 
498 	return iovcnt - sgl.iovcnt;
499 }
500 
501 void iscsi_free_sess(struct spdk_iscsi_sess *sess)
502 {
503 	if (sess == NULL) {
504 		return;
505 	}
506 
507 	sess->tag = 0;
508 	sess->target = NULL;
509 	sess->session_type = SESSION_TYPE_INVALID;
510 	iscsi_param_free(sess->params);
511 	free(sess->conns);
512 	spdk_scsi_port_free(&sess->initiator_port);
513 	spdk_mempool_put(g_iscsi.session_pool, (void *)sess);
514 }
515 
516 static int
517 create_iscsi_sess(struct spdk_iscsi_conn *conn,
518 		  struct spdk_iscsi_tgt_node *target,
519 		  enum session_type session_type)
520 {
521 	struct spdk_iscsi_sess *sess;
522 	int rc;
523 
524 	sess = spdk_mempool_get(g_iscsi.session_pool);
525 	if (!sess) {
526 		SPDK_ERRLOG("Unable to get session object\n");
527 		SPDK_ERRLOG("MaxSessions set to %d\n", g_iscsi.MaxSessions);
528 		return -ENOMEM;
529 	}
530 
531 	/* configuration values */
532 	pthread_mutex_lock(&g_iscsi.mutex);
533 
534 	sess->MaxConnections = g_iscsi.MaxConnectionsPerSession;
535 	sess->MaxOutstandingR2T = DEFAULT_MAXOUTSTANDINGR2T;
536 
537 	sess->DefaultTime2Wait = g_iscsi.DefaultTime2Wait;
538 	sess->DefaultTime2Retain = g_iscsi.DefaultTime2Retain;
539 	sess->FirstBurstLength = g_iscsi.FirstBurstLength;
540 	sess->MaxBurstLength = SPDK_ISCSI_MAX_BURST_LENGTH;
541 	sess->InitialR2T = DEFAULT_INITIALR2T;
542 	sess->ImmediateData = g_iscsi.ImmediateData;
543 	sess->DataPDUInOrder = DEFAULT_DATAPDUINORDER;
544 	sess->DataSequenceInOrder = DEFAULT_DATASEQUENCEINORDER;
545 	sess->ErrorRecoveryLevel = g_iscsi.ErrorRecoveryLevel;
546 
547 	pthread_mutex_unlock(&g_iscsi.mutex);
548 
549 	sess->tag = conn->pg_tag;
550 
551 	sess->conns = calloc(sess->MaxConnections, sizeof(*sess->conns));
552 	if (!sess->conns) {
553 		SPDK_ERRLOG("calloc() failed for connection array\n");
554 		return -ENOMEM;
555 	}
556 
557 	sess->connections = 0;
558 
559 	sess->conns[sess->connections] = conn;
560 	sess->connections++;
561 
562 	sess->params = NULL;
563 	sess->target = target;
564 	sess->isid = 0;
565 	sess->session_type = session_type;
566 	sess->current_text_itt = 0xffffffffU;
567 
568 	/* set default params */
569 	rc = iscsi_sess_params_init(&sess->params);
570 	if (rc < 0) {
571 		SPDK_ERRLOG("iscsi_sess_params_init() failed\n");
572 		goto error_return;
573 	}
574 	/* replace with config value */
575 	rc = iscsi_param_set_int(sess->params, "MaxConnections",
576 				 sess->MaxConnections);
577 	if (rc < 0) {
578 		SPDK_ERRLOG("iscsi_param_set_int() failed\n");
579 		goto error_return;
580 	}
581 
582 	rc = iscsi_param_set_int(sess->params, "MaxOutstandingR2T",
583 				 sess->MaxOutstandingR2T);
584 	if (rc < 0) {
585 		SPDK_ERRLOG("iscsi_param_set_int() failed\n");
586 		goto error_return;
587 	}
588 
589 	rc = iscsi_param_set_int(sess->params, "DefaultTime2Wait",
590 				 sess->DefaultTime2Wait);
591 	if (rc < 0) {
592 		SPDK_ERRLOG("iscsi_param_set_int() failed\n");
593 		goto error_return;
594 	}
595 
596 	rc = iscsi_param_set_int(sess->params, "DefaultTime2Retain",
597 				 sess->DefaultTime2Retain);
598 	if (rc < 0) {
599 		SPDK_ERRLOG("iscsi_param_set_int() failed\n");
600 		goto error_return;
601 	}
602 
603 	rc = iscsi_param_set_int(sess->params, "FirstBurstLength",
604 				 sess->FirstBurstLength);
605 	if (rc < 0) {
606 		SPDK_ERRLOG("iscsi_param_set_int() failed\n");
607 		goto error_return;
608 	}
609 
610 	rc = iscsi_param_set_int(sess->params, "MaxBurstLength",
611 				 sess->MaxBurstLength);
612 	if (rc < 0) {
613 		SPDK_ERRLOG("iscsi_param_set_int() failed\n");
614 		goto error_return;
615 	}
616 
617 	rc = iscsi_param_set(sess->params, "InitialR2T",
618 			     sess->InitialR2T ? "Yes" : "No");
619 	if (rc < 0) {
620 		SPDK_ERRLOG("iscsi_param_set() failed\n");
621 		goto error_return;
622 	}
623 
624 	rc = iscsi_param_set(sess->params, "ImmediateData",
625 			     sess->ImmediateData ? "Yes" : "No");
626 	if (rc < 0) {
627 		SPDK_ERRLOG("iscsi_param_set() failed\n");
628 		goto error_return;
629 	}
630 
631 	rc = iscsi_param_set(sess->params, "DataPDUInOrder",
632 			     sess->DataPDUInOrder ? "Yes" : "No");
633 	if (rc < 0) {
634 		SPDK_ERRLOG("iscsi_param_set() failed\n");
635 		goto error_return;
636 	}
637 
638 	rc = iscsi_param_set(sess->params, "DataSequenceInOrder",
639 			     sess->DataSequenceInOrder ? "Yes" : "No");
640 	if (rc < 0) {
641 		SPDK_ERRLOG("iscsi_param_set() failed\n");
642 		goto error_return;
643 	}
644 
645 	rc = iscsi_param_set_int(sess->params, "ErrorRecoveryLevel",
646 				 sess->ErrorRecoveryLevel);
647 	if (rc < 0) {
648 		SPDK_ERRLOG("iscsi_param_set_int() failed\n");
649 		goto error_return;
650 	}
651 
652 	/* realloc buffer */
653 	rc = iscsi_param_set_int(conn->params, "MaxRecvDataSegmentLength",
654 				 conn->MaxRecvDataSegmentLength);
655 	if (rc < 0) {
656 		SPDK_ERRLOG("iscsi_param_set_int() failed\n");
657 		goto error_return;
658 	}
659 
660 	/* sess for first connection of session */
661 	conn->sess = sess;
662 	return 0;
663 
664 error_return:
665 	iscsi_free_sess(sess);
666 	conn->sess = NULL;
667 	return -1;
668 }
669 
670 static struct spdk_iscsi_sess *
671 get_iscsi_sess_by_tsih(uint16_t tsih)
672 {
673 	struct spdk_iscsi_sess *session;
674 
675 	if (tsih == 0 || tsih > g_iscsi.MaxSessions) {
676 		return NULL;
677 	}
678 
679 	session = g_iscsi.session[tsih - 1];
680 	assert(tsih == session->tsih);
681 
682 	return session;
683 }
684 
685 static uint8_t
686 append_iscsi_sess(struct spdk_iscsi_conn *conn,
687 		  const char *initiator_port_name, uint16_t tsih, uint16_t cid)
688 {
689 	struct spdk_iscsi_sess *sess;
690 
691 	SPDK_DEBUGLOG(iscsi, "append session: init port name=%s, tsih=%u, cid=%u\n",
692 		      initiator_port_name, tsih, cid);
693 
694 	sess = get_iscsi_sess_by_tsih(tsih);
695 	if (sess == NULL) {
696 		SPDK_ERRLOG("spdk_get_iscsi_sess_by_tsih failed\n");
697 		return ISCSI_LOGIN_CONN_ADD_FAIL;
698 	}
699 	if ((conn->pg_tag != sess->tag) ||
700 	    (strcasecmp(initiator_port_name, spdk_scsi_port_get_name(sess->initiator_port)) != 0) ||
701 	    (conn->target != sess->target)) {
702 		/* no match */
703 		SPDK_ERRLOG("no MCS session for init port name=%s, tsih=%d, cid=%d\n",
704 			    initiator_port_name, tsih, cid);
705 		return ISCSI_LOGIN_CONN_ADD_FAIL;
706 	}
707 
708 	if (sess->connections >= sess->MaxConnections) {
709 		/* no slot for connection */
710 		SPDK_ERRLOG("too many connections for init port name=%s, tsih=%d, cid=%d\n",
711 			    initiator_port_name, tsih, cid);
712 		return ISCSI_LOGIN_TOO_MANY_CONNECTIONS;
713 	}
714 
715 	SPDK_DEBUGLOG(iscsi, "Connections (tsih %d): %d\n", sess->tsih, sess->connections);
716 	conn->sess = sess;
717 
718 	/*
719 	 * TODO: need a mutex or other sync mechanism to protect the session's
720 	 *  connection list.
721 	 */
722 	sess->conns[sess->connections] = conn;
723 	sess->connections++;
724 
725 	return 0;
726 }
727 
728 static int
729 iscsi_append_text(const char *key, const char *val, uint8_t *data,
730 		  int alloc_len, int data_len)
731 {
732 	int total;
733 	int len;
734 
735 	total = data_len;
736 	if (alloc_len < 1) {
737 		return 0;
738 	}
739 	if (total > alloc_len) {
740 		total = alloc_len;
741 		data[total - 1] = '\0';
742 		return total;
743 	}
744 
745 	if (alloc_len - total < 1) {
746 		SPDK_ERRLOG("data space small %d\n", alloc_len);
747 		return total;
748 	}
749 	len = snprintf((char *) data + total, alloc_len - total, "%s=%s", key, val);
750 	total += len + 1;
751 
752 	return total;
753 }
754 
755 static int
756 iscsi_append_param(struct spdk_iscsi_conn *conn, const char *key,
757 		   uint8_t *data, int alloc_len, int data_len)
758 {
759 	struct iscsi_param *param;
760 
761 	param = iscsi_param_find(conn->params, key);
762 	if (param == NULL) {
763 		param = iscsi_param_find(conn->sess->params, key);
764 		if (param == NULL) {
765 			SPDK_DEBUGLOG(iscsi, "no key %.64s\n", key);
766 			return data_len;
767 		}
768 	}
769 	return iscsi_append_text(param->key, param->val, data,
770 				 alloc_len, data_len);
771 }
772 
773 static int
774 iscsi_auth_params(struct spdk_iscsi_conn *conn,
775 		  struct iscsi_param *params, const char *method, uint8_t *data,
776 		  int alloc_len, int data_len)
777 {
778 	char *in_val;
779 	char *in_next;
780 	char *new_val;
781 	const char *algorithm;
782 	const char *name;
783 	const char *response;
784 	const char *identifier;
785 	const char *challenge;
786 	int total;
787 	int rc;
788 
789 	if (conn == NULL || params == NULL || method == NULL) {
790 		return -1;
791 	}
792 	if (strcasecmp(method, "CHAP") == 0) {
793 		/* method OK */
794 	} else {
795 		SPDK_ERRLOG("unsupported AuthMethod %.64s\n", method);
796 		return -1;
797 	}
798 
799 	total = data_len;
800 	if (alloc_len < 1) {
801 		return 0;
802 	}
803 	if (total > alloc_len) {
804 		total = alloc_len;
805 		data[total - 1] = '\0';
806 		return total;
807 	}
808 
809 	/* for temporary store */
810 	in_val = malloc(ISCSI_TEXT_MAX_VAL_LEN + 1);
811 	if (!in_val) {
812 		SPDK_ERRLOG("malloc() failed for temporary store\n");
813 		return -ENOMEM;
814 	}
815 
816 	/* CHAP method (RFC1994) */
817 	if ((algorithm = iscsi_param_get_val(params, "CHAP_A")) != NULL) {
818 		if (conn->auth.chap_phase != ISCSI_CHAP_PHASE_WAIT_A) {
819 			SPDK_ERRLOG("CHAP sequence error\n");
820 			goto error_return;
821 		}
822 
823 		/* CHAP_A is LIST type */
824 		snprintf(in_val, ISCSI_TEXT_MAX_VAL_LEN + 1, "%s", algorithm);
825 		in_next = in_val;
826 		while ((new_val = spdk_strsepq(&in_next, ",")) != NULL) {
827 			if (strcasecmp(new_val, "5") == 0) {
828 				/* CHAP with MD5 */
829 				break;
830 			}
831 		}
832 		if (new_val == NULL) {
833 			snprintf(in_val, ISCSI_TEXT_MAX_VAL_LEN + 1, "%s", "Reject");
834 			new_val = in_val;
835 			iscsi_append_text("CHAP_A", new_val, data, alloc_len, total);
836 			goto error_return;
837 		}
838 		/* selected algorithm is 5 (MD5) */
839 		SPDK_DEBUGLOG(iscsi, "got CHAP_A=%s\n", new_val);
840 		total = iscsi_append_text("CHAP_A", new_val, data, alloc_len, total);
841 
842 		/* Identifier is one octet */
843 		gen_random(conn->auth.chap_id, 1);
844 		snprintf(in_val, ISCSI_TEXT_MAX_VAL_LEN, "%d",
845 			 (int) conn->auth.chap_id[0]);
846 		total = iscsi_append_text("CHAP_I", in_val, data, alloc_len, total);
847 
848 		/* Challenge Value is a variable stream of octets */
849 		/* (binary length MUST not exceed 1024 bytes) */
850 		conn->auth.chap_challenge_len = ISCSI_CHAP_CHALLENGE_LEN;
851 		gen_random(conn->auth.chap_challenge, conn->auth.chap_challenge_len);
852 		bin2hex(in_val, ISCSI_TEXT_MAX_VAL_LEN,
853 			conn->auth.chap_challenge, conn->auth.chap_challenge_len);
854 		total = iscsi_append_text("CHAP_C", in_val, data, alloc_len, total);
855 
856 		conn->auth.chap_phase = ISCSI_CHAP_PHASE_WAIT_NR;
857 	} else if ((name = iscsi_param_get_val(params, "CHAP_N")) != NULL) {
858 		uint8_t resmd5[SPDK_MD5DIGEST_LEN];
859 		uint8_t tgtmd5[SPDK_MD5DIGEST_LEN];
860 		struct spdk_md5ctx md5ctx;
861 		size_t decoded_len = 0;
862 
863 		if (conn->auth.chap_phase != ISCSI_CHAP_PHASE_WAIT_NR) {
864 			SPDK_ERRLOG("CHAP sequence error\n");
865 			goto error_return;
866 		}
867 
868 		response = iscsi_param_get_val(params, "CHAP_R");
869 		if (response == NULL) {
870 			SPDK_ERRLOG("no response\n");
871 			goto error_return;
872 		}
873 		if (response[0] == '0' &&
874 		    (response[1] == 'x' || response[1] == 'X')) {
875 			rc = hex2bin(resmd5, SPDK_MD5DIGEST_LEN, response);
876 			if (rc < 0 || rc != SPDK_MD5DIGEST_LEN) {
877 				SPDK_ERRLOG("response format error\n");
878 				goto error_return;
879 			}
880 		} else if (response[0] == '0' &&
881 			   (response[1] == 'b' || response[1] == 'B')) {
882 			response += 2;
883 			rc = spdk_base64_decode(resmd5, &decoded_len, response);
884 			if (rc < 0 || decoded_len != SPDK_MD5DIGEST_LEN) {
885 				SPDK_ERRLOG("response format error\n");
886 				goto error_return;
887 			}
888 		} else {
889 			SPDK_ERRLOG("response format error\n");
890 			goto error_return;
891 		}
892 		SPDK_DEBUGLOG(iscsi, "got CHAP_N/CHAP_R\n");
893 
894 		SPDK_DEBUGLOG(iscsi, "ag_tag=%d\n", conn->chap_group);
895 
896 		rc = iscsi_chap_get_authinfo(&conn->auth, name, conn->chap_group);
897 		if (rc < 0) {
898 			/* SPDK_ERRLOG("auth user or secret is missing\n"); */
899 			SPDK_ERRLOG("iscsi_chap_get_authinfo() failed\n");
900 			goto error_return;
901 		}
902 		if (conn->auth.user[0] == '\0' || conn->auth.secret[0] == '\0') {
903 			/* SPDK_ERRLOG("auth user or secret is missing\n"); */
904 			SPDK_ERRLOG("auth failed (name %.64s)\n", name);
905 			goto error_return;
906 		}
907 
908 		md5init(&md5ctx);
909 		/* Identifier */
910 		md5update(&md5ctx, conn->auth.chap_id, 1);
911 		/* followed by secret */
912 		md5update(&md5ctx, conn->auth.secret,
913 			  strlen(conn->auth.secret));
914 		/* followed by Challenge Value */
915 		md5update(&md5ctx, conn->auth.chap_challenge,
916 			  conn->auth.chap_challenge_len);
917 		/* tgtmd5 is expecting Response Value */
918 		md5final(tgtmd5, &md5ctx);
919 
920 		bin2hex(in_val, ISCSI_TEXT_MAX_VAL_LEN, tgtmd5, SPDK_MD5DIGEST_LEN);
921 
922 #if 0
923 		SPDK_DEBUGLOG(iscsi, "tgtmd5=%s, resmd5=%s\n", in_val, response);
924 		spdk_dump("tgtmd5", tgtmd5, SPDK_MD5DIGEST_LEN);
925 		spdk_dump("resmd5", resmd5, SPDK_MD5DIGEST_LEN);
926 #endif
927 
928 		/* compare MD5 digest */
929 		if (memcmp(tgtmd5, resmd5, SPDK_MD5DIGEST_LEN) != 0) {
930 			/* not match */
931 			/* SPDK_ERRLOG("auth user or secret is missing\n"); */
932 			SPDK_ERRLOG("auth failed (name %.64s)\n", name);
933 			goto error_return;
934 		}
935 		/* OK initiator's secret */
936 		conn->authenticated = true;
937 
938 		/* mutual CHAP? */
939 		identifier = iscsi_param_get_val(params, "CHAP_I");
940 		if (identifier != NULL) {
941 			conn->auth.chap_mid[0] = (uint8_t) strtol(identifier, NULL, 10);
942 			challenge = iscsi_param_get_val(params, "CHAP_C");
943 			if (challenge == NULL) {
944 				SPDK_ERRLOG("CHAP sequence error\n");
945 				goto error_return;
946 			}
947 			if (challenge[0] == '0' &&
948 			    (challenge[1] == 'x' || challenge[1] == 'X')) {
949 				rc = hex2bin(conn->auth.chap_mchallenge,
950 					     ISCSI_CHAP_CHALLENGE_LEN, challenge);
951 				if (rc < 0) {
952 					SPDK_ERRLOG("challenge format error\n");
953 					goto error_return;
954 				}
955 				conn->auth.chap_mchallenge_len = rc;
956 			} else if (challenge[0] == '0' &&
957 				   (challenge[1] == 'b' || challenge[1] == 'B')) {
958 				challenge += 2;
959 				rc = spdk_base64_decode(conn->auth.chap_mchallenge,
960 							&decoded_len, challenge);
961 				if (rc < 0) {
962 					SPDK_ERRLOG("challenge format error\n");
963 					goto error_return;
964 				}
965 				conn->auth.chap_mchallenge_len = decoded_len;
966 			} else {
967 				SPDK_ERRLOG("challenge format error\n");
968 				goto error_return;
969 			}
970 #if 0
971 			spdk_dump("MChallenge", conn->auth.chap_mchallenge,
972 				  conn->auth.chap_mchallenge_len);
973 #endif
974 			SPDK_DEBUGLOG(iscsi, "got CHAP_I/CHAP_C\n");
975 
976 			if (conn->auth.muser[0] == '\0' || conn->auth.msecret[0] == '\0') {
977 				/* SPDK_ERRLOG("mutual auth user or secret is missing\n"); */
978 				SPDK_ERRLOG("auth failed (name %.64s)\n", name);
979 				goto error_return;
980 			}
981 
982 			md5init(&md5ctx);
983 			/* Identifier */
984 			md5update(&md5ctx, conn->auth.chap_mid, 1);
985 			/* followed by secret */
986 			md5update(&md5ctx, conn->auth.msecret,
987 				  strlen(conn->auth.msecret));
988 			/* followed by Challenge Value */
989 			md5update(&md5ctx, conn->auth.chap_mchallenge,
990 				  conn->auth.chap_mchallenge_len);
991 			/* tgtmd5 is Response Value */
992 			md5final(tgtmd5, &md5ctx);
993 
994 			bin2hex(in_val, ISCSI_TEXT_MAX_VAL_LEN, tgtmd5, SPDK_MD5DIGEST_LEN);
995 
996 			total = iscsi_append_text("CHAP_N", conn->auth.muser, data,
997 						  alloc_len, total);
998 			total = iscsi_append_text("CHAP_R", in_val, data, alloc_len, total);
999 		} else {
1000 			/* not mutual */
1001 			if (conn->mutual_chap) {
1002 				SPDK_ERRLOG("required mutual CHAP\n");
1003 				goto error_return;
1004 			}
1005 		}
1006 
1007 		conn->auth.chap_phase = ISCSI_CHAP_PHASE_END;
1008 	} else {
1009 		/* not found CHAP keys */
1010 		SPDK_DEBUGLOG(iscsi, "start CHAP\n");
1011 		conn->auth.chap_phase = ISCSI_CHAP_PHASE_WAIT_A;
1012 	}
1013 
1014 	free(in_val);
1015 	return total;
1016 
1017 error_return:
1018 	conn->auth.chap_phase = ISCSI_CHAP_PHASE_WAIT_A;
1019 	free(in_val);
1020 	return -1;
1021 }
1022 
1023 static int
1024 iscsi_check_values(struct spdk_iscsi_conn *conn)
1025 {
1026 	if (conn->sess->FirstBurstLength > conn->sess->MaxBurstLength) {
1027 		SPDK_ERRLOG("FirstBurstLength(%d) > MaxBurstLength(%d)\n",
1028 			    conn->sess->FirstBurstLength,
1029 			    conn->sess->MaxBurstLength);
1030 		return -1;
1031 	}
1032 	if (conn->sess->FirstBurstLength > g_iscsi.FirstBurstLength) {
1033 		SPDK_ERRLOG("FirstBurstLength(%d) > iSCSI target restriction(%d)\n",
1034 			    conn->sess->FirstBurstLength, g_iscsi.FirstBurstLength);
1035 		return -1;
1036 	}
1037 	if (conn->sess->MaxBurstLength > 0x00ffffff) {
1038 		SPDK_ERRLOG("MaxBurstLength(%d) > 0x00ffffff\n",
1039 			    conn->sess->MaxBurstLength);
1040 		return -1;
1041 	}
1042 
1043 	if (conn->MaxRecvDataSegmentLength < 512) {
1044 		SPDK_ERRLOG("MaxRecvDataSegmentLength(%d) < 512\n",
1045 			    conn->MaxRecvDataSegmentLength);
1046 		return -1;
1047 	}
1048 	if (conn->MaxRecvDataSegmentLength > 0x00ffffff) {
1049 		SPDK_ERRLOG("MaxRecvDataSegmentLength(%d) > 0x00ffffff\n",
1050 			    conn->MaxRecvDataSegmentLength);
1051 		return -1;
1052 	}
1053 	return 0;
1054 }
1055 
1056 static int
1057 iscsi_conn_params_update(struct spdk_iscsi_conn *conn)
1058 {
1059 	int rc;
1060 	uint32_t recv_buf_size;
1061 
1062 	/* update internal variables */
1063 	rc = iscsi_copy_param2var(conn);
1064 	if (rc < 0) {
1065 		SPDK_ERRLOG("iscsi_copy_param2var() failed\n");
1066 		if (conn->state < ISCSI_CONN_STATE_EXITING) {
1067 			conn->state = ISCSI_CONN_STATE_EXITING;
1068 		}
1069 		return rc;
1070 	}
1071 
1072 	/* check value */
1073 	rc = iscsi_check_values(conn);
1074 	if (rc < 0) {
1075 		SPDK_ERRLOG("iscsi_check_values() failed\n");
1076 		if (conn->state < ISCSI_CONN_STATE_EXITING) {
1077 			conn->state = ISCSI_CONN_STATE_EXITING;
1078 		}
1079 	}
1080 
1081 	/* The socket receive buffer may need to be adjusted based on the new parameters */
1082 
1083 	/* Don't allow the recv buffer to be 0 or very large. */
1084 	recv_buf_size = spdk_max(0x1000, spdk_min(0x2000, conn->sess->FirstBurstLength));
1085 
1086 	/* Add in extra space for the PDU */
1087 	recv_buf_size += ISCSI_BHS_LEN + ISCSI_AHS_LEN;
1088 
1089 	if (conn->header_digest) {
1090 		recv_buf_size += ISCSI_DIGEST_LEN;
1091 	}
1092 
1093 	if (conn->data_digest) {
1094 		recv_buf_size += ISCSI_DIGEST_LEN;
1095 	}
1096 
1097 	/* Set up to buffer up to 4 commands with immediate data at once */
1098 	if (spdk_sock_set_recvbuf(conn->sock, recv_buf_size * 4) < 0) {
1099 		/* Not fatal. */
1100 	}
1101 
1102 	return rc;
1103 }
1104 
1105 static void
1106 iscsi_conn_login_pdu_err_complete(void *arg)
1107 {
1108 	struct spdk_iscsi_conn *conn = arg;
1109 
1110 	if (conn->full_feature) {
1111 		iscsi_conn_params_update(conn);
1112 	}
1113 }
1114 
1115 static void
1116 iscsi_conn_login_pdu_success_complete(void *arg)
1117 {
1118 	struct spdk_iscsi_conn *conn = arg;
1119 
1120 
1121 	if (conn->state >= ISCSI_CONN_STATE_EXITING) {
1122 		/* Connection is being exited before this callback is executed. */
1123 		SPDK_DEBUGLOG(iscsi, "Connection is already exited.\n");
1124 		return;
1125 	}
1126 	if (conn->full_feature) {
1127 		if (iscsi_conn_params_update(conn) != 0) {
1128 			return;
1129 		}
1130 	}
1131 	conn->state = ISCSI_CONN_STATE_RUNNING;
1132 	if (conn->full_feature != 0) {
1133 		iscsi_conn_schedule(conn);
1134 	}
1135 }
1136 
1137 /*
1138  * The response function of spdk_iscsi_op_login
1139  */
1140 static void
1141 iscsi_op_login_response(struct spdk_iscsi_conn *conn,
1142 			struct spdk_iscsi_pdu *rsp_pdu, struct iscsi_param *params,
1143 			iscsi_conn_xfer_complete_cb cb_fn)
1144 {
1145 	struct iscsi_bhs_login_rsp *rsph;
1146 
1147 	rsph = (struct iscsi_bhs_login_rsp *)&rsp_pdu->bhs;
1148 	rsph->version_max = ISCSI_VERSION;
1149 	rsph->version_act = ISCSI_VERSION;
1150 	DSET24(rsph->data_segment_len, rsp_pdu->data_segment_len);
1151 
1152 	to_be32(&rsph->stat_sn, conn->StatSN);
1153 	conn->StatSN++;
1154 
1155 	if (conn->sess != NULL) {
1156 		to_be32(&rsph->exp_cmd_sn, conn->sess->ExpCmdSN);
1157 		to_be32(&rsph->max_cmd_sn, conn->sess->MaxCmdSN);
1158 	} else {
1159 		to_be32(&rsph->exp_cmd_sn, rsp_pdu->cmd_sn);
1160 		to_be32(&rsph->max_cmd_sn, rsp_pdu->cmd_sn);
1161 	}
1162 
1163 	SPDK_LOGDUMP(iscsi, "PDU", (uint8_t *)rsph, ISCSI_BHS_LEN);
1164 	SPDK_LOGDUMP(iscsi, "DATA", rsp_pdu->data, rsp_pdu->data_segment_len);
1165 
1166 	/* Set T/CSG/NSG to reserved if login error. */
1167 	if (rsph->status_class != 0) {
1168 		rsph->flags &= ~(ISCSI_LOGIN_TRANSIT | ISCSI_LOGIN_CURRENT_STAGE_MASK |
1169 				 ISCSI_LOGIN_NEXT_STAGE_MASK);
1170 	}
1171 	iscsi_param_free(params);
1172 	iscsi_conn_write_pdu(conn, rsp_pdu, cb_fn, conn);
1173 }
1174 
1175 /*
1176  * The function which is used to initialize the internal response data
1177  * structure of iscsi login function.
1178  * return:
1179  * 0, success;
1180  * otherwise, error;
1181  */
1182 static int
1183 iscsi_op_login_rsp_init(struct spdk_iscsi_conn *conn,
1184 			struct spdk_iscsi_pdu *pdu, struct spdk_iscsi_pdu *rsp_pdu)
1185 {
1186 	struct iscsi_bhs_login_req *reqh;
1187 	struct iscsi_bhs_login_rsp *rsph;
1188 
1189 	rsph = (struct iscsi_bhs_login_rsp *)&rsp_pdu->bhs;
1190 	rsph->opcode = ISCSI_OP_LOGIN_RSP;
1191 	rsph->status_class = ISCSI_CLASS_SUCCESS;
1192 	rsph->status_detail = ISCSI_LOGIN_ACCEPT;
1193 	rsp_pdu->data_segment_len = 0;
1194 
1195 	/* The default MaxRecvDataSegmentLength 8192 is used during login. - RFC3720 */
1196 	rsp_pdu->data = calloc(1, 8192);
1197 	if (!rsp_pdu->data) {
1198 		SPDK_ERRLOG("calloc() failed for data segment\n");
1199 		rsph->status_class = ISCSI_CLASS_TARGET_ERROR;
1200 		rsph->status_detail = ISCSI_LOGIN_STATUS_NO_RESOURCES;
1201 		return SPDK_ISCSI_LOGIN_ERROR_RESPONSE;
1202 	}
1203 	rsp_pdu->data_buf_len = 8192;
1204 
1205 	reqh = (struct iscsi_bhs_login_req *)&pdu->bhs;
1206 	rsph->flags |= (reqh->flags & (ISCSI_LOGIN_TRANSIT | ISCSI_LOGIN_CONTINUE |
1207 				       ISCSI_LOGIN_CURRENT_STAGE_MASK));
1208 	if (ISCSI_BHS_LOGIN_GET_TBIT(rsph->flags)) {
1209 		rsph->flags |= (reqh->flags & ISCSI_LOGIN_NEXT_STAGE_MASK);
1210 	}
1211 
1212 	/* We don't need to convert from network byte order. Just store it */
1213 	memcpy(&rsph->isid, reqh->isid, 6);
1214 	rsph->tsih = reqh->tsih;
1215 	rsph->itt = reqh->itt;
1216 	rsp_pdu->cmd_sn = from_be32(&reqh->cmd_sn);
1217 
1218 	if (rsph->tsih) {
1219 		rsph->stat_sn = reqh->exp_stat_sn;
1220 	}
1221 
1222 	SPDK_LOGDUMP(iscsi, "PDU", (uint8_t *)&pdu->bhs, ISCSI_BHS_LEN);
1223 
1224 	SPDK_DEBUGLOG(iscsi,
1225 		      "T=%d, C=%d, CSG=%d, NSG=%d, Min=%d, Max=%d, ITT=%x\n",
1226 		      ISCSI_BHS_LOGIN_GET_TBIT(rsph->flags),
1227 		      ISCSI_BHS_LOGIN_GET_CBIT(rsph->flags),
1228 		      ISCSI_BHS_LOGIN_GET_CSG(rsph->flags),
1229 		      ISCSI_BHS_LOGIN_GET_NSG(rsph->flags),
1230 		      reqh->version_min, reqh->version_max, from_be32(&rsph->itt));
1231 
1232 	if (conn->sess != NULL) {
1233 		SPDK_DEBUGLOG(iscsi,
1234 			      "CmdSN=%u, ExpStatSN=%u, StatSN=%u, ExpCmdSN=%u,"
1235 			      "MaxCmdSN=%u\n", rsp_pdu->cmd_sn,
1236 			      from_be32(&rsph->stat_sn), conn->StatSN,
1237 			      conn->sess->ExpCmdSN,
1238 			      conn->sess->MaxCmdSN);
1239 	} else {
1240 		SPDK_DEBUGLOG(iscsi,
1241 			      "CmdSN=%u, ExpStatSN=%u, StatSN=%u\n",
1242 			      rsp_pdu->cmd_sn, from_be32(&rsph->stat_sn),
1243 			      conn->StatSN);
1244 	}
1245 
1246 	if (ISCSI_BHS_LOGIN_GET_TBIT(rsph->flags) &&
1247 	    ISCSI_BHS_LOGIN_GET_CBIT(rsph->flags)) {
1248 		SPDK_ERRLOG("transit error\n");
1249 		rsph->status_class = ISCSI_CLASS_INITIATOR_ERROR;
1250 		rsph->status_detail = ISCSI_LOGIN_INITIATOR_ERROR;
1251 		return SPDK_ISCSI_LOGIN_ERROR_RESPONSE;
1252 	}
1253 	/* make sure reqh->version_max < ISCSI_VERSION */
1254 	if (reqh->version_min > ISCSI_VERSION) {
1255 		SPDK_ERRLOG("unsupported version min %d/max %d, expecting %d\n", reqh->version_min,
1256 			    reqh->version_max, ISCSI_VERSION);
1257 		/* Unsupported version */
1258 		/* set all reserved flag to zero */
1259 		rsph->status_class = ISCSI_CLASS_INITIATOR_ERROR;
1260 		rsph->status_detail = ISCSI_LOGIN_UNSUPPORTED_VERSION;
1261 		return SPDK_ISCSI_LOGIN_ERROR_RESPONSE;
1262 	}
1263 
1264 	if ((ISCSI_BHS_LOGIN_GET_NSG(rsph->flags) == ISCSI_NSG_RESERVED_CODE) &&
1265 	    ISCSI_BHS_LOGIN_GET_TBIT(rsph->flags)) {
1266 		/* set NSG and other bits to zero */
1267 		rsph->flags &= ~(ISCSI_LOGIN_NEXT_STAGE_MASK | ISCSI_LOGIN_TRANSIT |
1268 				 ISCSI_LOGIN_CURRENT_STAGE_MASK);
1269 		SPDK_ERRLOG("Received reserved NSG code: %d\n", ISCSI_NSG_RESERVED_CODE);
1270 		/* Initiator error */
1271 		rsph->status_class = ISCSI_CLASS_INITIATOR_ERROR;
1272 		rsph->status_detail = ISCSI_LOGIN_INITIATOR_ERROR;
1273 		return SPDK_ISCSI_LOGIN_ERROR_RESPONSE;
1274 	}
1275 
1276 	return 0;
1277 }
1278 
1279 static int
1280 iscsi_op_login_store_incoming_params(struct spdk_iscsi_conn *conn,
1281 				     struct spdk_iscsi_pdu *pdu, struct spdk_iscsi_pdu *rsp_pdu,
1282 				     struct iscsi_param **params)
1283 {
1284 	struct iscsi_bhs_login_req *reqh;
1285 	struct iscsi_bhs_login_rsp *rsph;
1286 	int rc;
1287 
1288 	reqh = (struct iscsi_bhs_login_req *)&pdu->bhs;
1289 	rsph = (struct iscsi_bhs_login_rsp *)&rsp_pdu->bhs;
1290 
1291 	rc = iscsi_parse_params(params, pdu->data,
1292 				pdu->data_segment_len, ISCSI_BHS_LOGIN_GET_CBIT(reqh->flags),
1293 				&conn->partial_text_parameter);
1294 	if (rc < 0) {
1295 		SPDK_ERRLOG("iscsi_parse_params() failed\n");
1296 		iscsi_param_free(*params);
1297 		rsph->status_class = ISCSI_CLASS_INITIATOR_ERROR;
1298 		rsph->status_detail = ISCSI_LOGIN_INITIATOR_ERROR;
1299 		return SPDK_ISCSI_LOGIN_ERROR_PARAMETER;
1300 	}
1301 
1302 	return 0;
1303 }
1304 
1305 /*
1306  * This function is used to initialize the port info
1307  * return
1308  * 0: success
1309  * otherwise: error
1310  */
1311 static int
1312 iscsi_op_login_initialize_port(struct spdk_iscsi_conn *conn,
1313 			       struct spdk_iscsi_pdu *rsp_pdu,
1314 			       char *initiator_port_name,
1315 			       uint32_t name_length,
1316 			       struct iscsi_param *params)
1317 {
1318 	const char *val;
1319 	struct iscsi_bhs_login_rsp *rsph;
1320 	rsph = (struct iscsi_bhs_login_rsp *)&rsp_pdu->bhs;
1321 
1322 	/* Initiator Name and Port */
1323 	val = iscsi_param_get_val(params, "InitiatorName");
1324 	if (val == NULL) {
1325 		SPDK_ERRLOG("InitiatorName is empty\n");
1326 		/* Missing parameter */
1327 		rsph->status_class = ISCSI_CLASS_INITIATOR_ERROR;
1328 		rsph->status_detail = ISCSI_LOGIN_MISSING_PARMS;
1329 		return SPDK_ISCSI_LOGIN_ERROR_RESPONSE;
1330 	}
1331 	snprintf(conn->initiator_name, sizeof(conn->initiator_name), "%s", val);
1332 	snprintf(initiator_port_name, name_length,
1333 		 "%s,i,0x%12.12" PRIx64, val, iscsi_get_isid(rsph->isid));
1334 	spdk_strlwr(conn->initiator_name);
1335 	spdk_strlwr(initiator_port_name);
1336 	SPDK_DEBUGLOG(iscsi, "Initiator name: %s\n", conn->initiator_name);
1337 	SPDK_DEBUGLOG(iscsi, "Initiator port: %s\n", initiator_port_name);
1338 
1339 	return 0;
1340 }
1341 
1342 /*
1343  * This function is used to judge the session type
1344  * return
1345  * 0: success
1346  * Other value: error
1347  */
1348 static int
1349 iscsi_op_login_session_type(struct spdk_iscsi_conn *conn,
1350 			    struct spdk_iscsi_pdu *rsp_pdu,
1351 			    enum session_type *session_type,
1352 			    struct iscsi_param *params)
1353 {
1354 	const char *session_type_str;
1355 	struct iscsi_bhs_login_rsp *rsph;
1356 
1357 	rsph = (struct iscsi_bhs_login_rsp *)&rsp_pdu->bhs;
1358 	session_type_str = iscsi_param_get_val(params, "SessionType");
1359 	if (session_type_str == NULL) {
1360 		if (rsph->tsih != 0) {
1361 			*session_type = SESSION_TYPE_NORMAL;
1362 		} else {
1363 			SPDK_ERRLOG("SessionType is empty\n");
1364 			/* Missing parameter */
1365 			rsph->status_class = ISCSI_CLASS_INITIATOR_ERROR;
1366 			rsph->status_detail = ISCSI_LOGIN_MISSING_PARMS;
1367 			return SPDK_ISCSI_LOGIN_ERROR_RESPONSE;
1368 		}
1369 	} else {
1370 		if (strcasecmp(session_type_str, "Discovery") == 0) {
1371 			*session_type = SESSION_TYPE_DISCOVERY;
1372 		} else if (strcasecmp(session_type_str, "Normal") == 0) {
1373 			*session_type = SESSION_TYPE_NORMAL;
1374 		} else {
1375 			*session_type = SESSION_TYPE_INVALID;
1376 			SPDK_ERRLOG("SessionType is invalid\n");
1377 			/* Missing parameter */
1378 			rsph->status_class = ISCSI_CLASS_INITIATOR_ERROR;
1379 			rsph->status_detail = ISCSI_LOGIN_MISSING_PARMS;
1380 			return SPDK_ISCSI_LOGIN_ERROR_RESPONSE;
1381 		}
1382 	}
1383 	SPDK_DEBUGLOG(iscsi, "Session Type: %s\n", session_type_str);
1384 
1385 	return 0;
1386 }
1387 
1388 /*
1389  * This function is used to check the target info
1390  * return:
1391  * 0: success
1392  * otherwise: error
1393  */
1394 static int
1395 iscsi_op_login_check_target(struct spdk_iscsi_conn *conn,
1396 			    struct spdk_iscsi_pdu *rsp_pdu,
1397 			    const char *target_name,
1398 			    struct spdk_iscsi_tgt_node **target)
1399 {
1400 	struct iscsi_bhs_login_rsp *rsph;
1401 	char buf[MAX_TMPBUF] = {};
1402 
1403 	rsph = (struct iscsi_bhs_login_rsp *)&rsp_pdu->bhs;
1404 	*target = iscsi_find_tgt_node(target_name);
1405 	if (*target == NULL) {
1406 		SPDK_WARNLOG("target %s not found\n", target_name);
1407 		/* Not found */
1408 		rsph->status_class = ISCSI_CLASS_INITIATOR_ERROR;
1409 		rsph->status_detail = ISCSI_LOGIN_TARGET_NOT_FOUND;
1410 		return SPDK_ISCSI_LOGIN_ERROR_RESPONSE;
1411 	}
1412 	if (iscsi_tgt_node_is_destructed(*target)) {
1413 		SPDK_ERRLOG("target %s is removed\n", target_name);
1414 		rsph->status_class = ISCSI_CLASS_INITIATOR_ERROR;
1415 		rsph->status_detail = ISCSI_LOGIN_TARGET_REMOVED;
1416 		return SPDK_ISCSI_LOGIN_ERROR_RESPONSE;
1417 	}
1418 	if (iscsi_tgt_node_is_redirected(conn, *target, buf, MAX_TMPBUF)) {
1419 		SPDK_INFOLOG(iscsi, "target %s is redirectd\n", target_name);
1420 		rsp_pdu->data_segment_len = iscsi_append_text("TargetAddress",
1421 					    buf,
1422 					    rsp_pdu->data,
1423 					    rsp_pdu->data_buf_len,
1424 					    rsp_pdu->data_segment_len);
1425 		rsph->status_class = ISCSI_CLASS_REDIRECT;
1426 		rsph->status_detail = ISCSI_LOGIN_TARGET_TEMPORARILY_MOVED;
1427 		return SPDK_ISCSI_LOGIN_ERROR_RESPONSE;
1428 	}
1429 	if (!iscsi_tgt_node_access(conn, *target, conn->initiator_name,
1430 				   conn->initiator_addr)) {
1431 		SPDK_ERRLOG("access denied\n");
1432 		rsph->status_class = ISCSI_CLASS_INITIATOR_ERROR;
1433 		rsph->status_detail = ISCSI_LOGIN_AUTHORIZATION_FAIL;
1434 		return SPDK_ISCSI_LOGIN_ERROR_RESPONSE;
1435 	}
1436 
1437 	return 0;
1438 }
1439 
1440 /*
1441  * This function use to check the session
1442  * return:
1443  * 0, success
1444  * otherwise: error
1445  */
1446 static int
1447 iscsi_op_login_check_session(struct spdk_iscsi_conn *conn,
1448 			     struct spdk_iscsi_pdu *rsp_pdu,
1449 			     char *initiator_port_name, int cid)
1450 
1451 {
1452 	int rc = 0;
1453 	struct iscsi_bhs_login_rsp *rsph;
1454 
1455 	rsph = (struct iscsi_bhs_login_rsp *)&rsp_pdu->bhs;
1456 	/* check existing session */
1457 	SPDK_DEBUGLOG(iscsi, "isid=%"PRIx64", tsih=%u, cid=%u\n",
1458 		      iscsi_get_isid(rsph->isid), from_be16(&rsph->tsih), cid);
1459 	if (rsph->tsih != 0) {
1460 		/* multiple connections */
1461 		rc = append_iscsi_sess(conn, initiator_port_name,
1462 				       from_be16(&rsph->tsih), cid);
1463 		if (rc != 0) {
1464 			SPDK_ERRLOG("isid=%"PRIx64", tsih=%u, cid=%u:"
1465 				    "spdk_append_iscsi_sess() failed\n",
1466 				    iscsi_get_isid(rsph->isid), from_be16(&rsph->tsih),
1467 				    cid);
1468 			/* Can't include in session */
1469 			rsph->status_class = ISCSI_CLASS_INITIATOR_ERROR;
1470 			rsph->status_detail = rc;
1471 			return SPDK_ISCSI_LOGIN_ERROR_RESPONSE;
1472 		}
1473 	} else if (!g_iscsi.AllowDuplicateIsid) {
1474 		/* new session, drop old sess by the initiator */
1475 		iscsi_drop_conns(conn, initiator_port_name, 0 /* drop old */);
1476 	}
1477 
1478 	return rc;
1479 }
1480 
1481 /*
1482  * This function is used to del the original param and update it with new
1483  * value
1484  * return:
1485  * 0: success
1486  * otherwise: error
1487  */
1488 static int
1489 iscsi_op_login_update_param(struct spdk_iscsi_conn *conn,
1490 			    const char *key, const char *value,
1491 			    const char *list)
1492 {
1493 	int rc = 0;
1494 	struct iscsi_param *new_param, *orig_param;
1495 	int index;
1496 
1497 	orig_param = iscsi_param_find(conn->params, key);
1498 	if (orig_param == NULL) {
1499 		SPDK_ERRLOG("orig_param %s not found\n", key);
1500 		return SPDK_ISCSI_LOGIN_ERROR_PARAMETER;
1501 	}
1502 
1503 	index = orig_param->state_index;
1504 	rc = iscsi_param_del(&conn->params, key);
1505 	if (rc < 0) {
1506 		SPDK_ERRLOG("iscsi_param_del(%s) failed\n", key);
1507 		return SPDK_ISCSI_LOGIN_ERROR_PARAMETER;
1508 	}
1509 	rc = iscsi_param_add(&conn->params, key, value, list, ISPT_LIST);
1510 	if (rc < 0) {
1511 		SPDK_ERRLOG("iscsi_param_add() failed\n");
1512 		return SPDK_ISCSI_LOGIN_ERROR_PARAMETER;
1513 	}
1514 	new_param = iscsi_param_find(conn->params, key);
1515 	if (new_param == NULL) {
1516 		SPDK_ERRLOG("iscsi_param_find() failed\n");
1517 		return SPDK_ISCSI_LOGIN_ERROR_PARAMETER;
1518 	}
1519 	new_param->state_index = index;
1520 	return rc;
1521 }
1522 
1523 static int
1524 iscsi_negotiate_chap_param(struct spdk_iscsi_conn *conn)
1525 {
1526 	int rc = 0;
1527 
1528 	if (conn->disable_chap) {
1529 		rc = iscsi_op_login_update_param(conn, "AuthMethod", "None", "None");
1530 	} else if (conn->require_chap) {
1531 		rc = iscsi_op_login_update_param(conn, "AuthMethod", "CHAP", "CHAP");
1532 	}
1533 
1534 	return rc;
1535 }
1536 
1537 /*
1538  * The function which is used to handle the part of session discovery
1539  * return:
1540  * 0, success;
1541  * otherwise: error;
1542  */
1543 static int
1544 iscsi_op_login_session_discovery_chap(struct spdk_iscsi_conn *conn)
1545 {
1546 	return iscsi_negotiate_chap_param(conn);
1547 }
1548 
1549 /*
1550  * This function is used to update the param related with chap
1551  * return:
1552  * 0: success
1553  * otherwise: error
1554  */
1555 static int
1556 iscsi_op_login_negotiate_chap_param(struct spdk_iscsi_conn *conn,
1557 				    struct spdk_iscsi_tgt_node *target)
1558 {
1559 	conn->disable_chap = target->disable_chap;
1560 	conn->require_chap = target->require_chap;
1561 	conn->mutual_chap = target->mutual_chap;
1562 	conn->chap_group = target->chap_group;
1563 
1564 	return iscsi_negotiate_chap_param(conn);
1565 }
1566 
1567 static int
1568 iscsi_op_login_negotiate_digest_param(struct spdk_iscsi_conn *conn,
1569 				      struct spdk_iscsi_tgt_node *target)
1570 {
1571 	int rc;
1572 
1573 	if (target->header_digest) {
1574 		/*
1575 		 * User specified header digests, so update the list of
1576 		 *  HeaderDigest values to remove "None" so that only
1577 		 *  initiators who support CRC32C can connect.
1578 		 */
1579 		rc = iscsi_op_login_update_param(conn, "HeaderDigest", "CRC32C", "CRC32C");
1580 		if (rc < 0) {
1581 			return rc;
1582 		}
1583 	}
1584 
1585 	if (target->data_digest) {
1586 		/*
1587 		 * User specified data digests, so update the list of
1588 		 *  DataDigest values to remove "None" so that only
1589 		 *  initiators who support CRC32C can connect.
1590 		 */
1591 		rc = iscsi_op_login_update_param(conn, "DataDigest", "CRC32C", "CRC32C");
1592 		if (rc < 0) {
1593 			return rc;
1594 		}
1595 	}
1596 
1597 	return 0;
1598 }
1599 
1600 /*
1601  * The function which is used to handle the part of normal login session
1602  * return:
1603  * 0, success;
1604  * SPDK_ISCSI_LOGIN_ERROR_PARAMETER, parameter error;
1605  */
1606 static int
1607 iscsi_op_login_session_normal(struct spdk_iscsi_conn *conn,
1608 			      struct spdk_iscsi_pdu *rsp_pdu,
1609 			      char *initiator_port_name,
1610 			      struct iscsi_param *params,
1611 			      int cid)
1612 {
1613 	struct spdk_iscsi_tgt_node *target = NULL;
1614 	const char *target_name;
1615 	const char *target_short_name;
1616 	struct iscsi_bhs_login_rsp *rsph;
1617 	int rc = 0;
1618 
1619 	rsph = (struct iscsi_bhs_login_rsp *)&rsp_pdu->bhs;
1620 	target_name = iscsi_param_get_val(params, "TargetName");
1621 
1622 	if (target_name == NULL) {
1623 		SPDK_ERRLOG("TargetName is empty\n");
1624 		/* Missing parameter */
1625 		rsph->status_class = ISCSI_CLASS_INITIATOR_ERROR;
1626 		rsph->status_detail = ISCSI_LOGIN_MISSING_PARMS;
1627 		return SPDK_ISCSI_LOGIN_ERROR_RESPONSE;
1628 	}
1629 
1630 	memset(conn->target_short_name, 0, MAX_TARGET_NAME);
1631 	target_short_name = strstr(target_name, ":");
1632 	if (target_short_name != NULL) {
1633 		target_short_name++; /* Advance past the ':' */
1634 		if (strlen(target_short_name) >= MAX_TARGET_NAME) {
1635 			SPDK_ERRLOG("Target Short Name (%s) is more than %u characters\n",
1636 				    target_short_name, MAX_TARGET_NAME);
1637 			/* Invalid request */
1638 			rsph->status_class = ISCSI_CLASS_INITIATOR_ERROR;
1639 			rsph->status_detail = ISCSI_LOGIN_INVALID_LOGIN_REQUEST;
1640 			return SPDK_ISCSI_LOGIN_ERROR_RESPONSE;
1641 		}
1642 		snprintf(conn->target_short_name, MAX_TARGET_NAME, "%s",
1643 			 target_short_name);
1644 	}
1645 
1646 	pthread_mutex_lock(&g_iscsi.mutex);
1647 	rc = iscsi_op_login_check_target(conn, rsp_pdu, target_name, &target);
1648 	pthread_mutex_unlock(&g_iscsi.mutex);
1649 
1650 	if (rc < 0) {
1651 		return rc;
1652 	}
1653 
1654 	conn->target = target;
1655 	conn->dev = target->dev;
1656 	conn->target_port = spdk_scsi_dev_find_port_by_id(target->dev,
1657 			    conn->pg_tag);
1658 
1659 	rc = iscsi_op_login_check_session(conn, rsp_pdu,
1660 					  initiator_port_name, cid);
1661 	if (rc < 0) {
1662 		return rc;
1663 	}
1664 
1665 	/* force target flags */
1666 	pthread_mutex_lock(&target->mutex);
1667 	rc = iscsi_op_login_negotiate_chap_param(conn, target);
1668 	pthread_mutex_unlock(&target->mutex);
1669 
1670 	if (rc == 0) {
1671 		rc = iscsi_op_login_negotiate_digest_param(conn, target);
1672 	}
1673 
1674 	if (rc != 0) {
1675 		/* Invalid request */
1676 		rsph->status_class = ISCSI_CLASS_INITIATOR_ERROR;
1677 		rsph->status_detail = ISCSI_LOGIN_INVALID_LOGIN_REQUEST;
1678 	}
1679 
1680 	return rc;
1681 }
1682 
1683 /*
1684  * This function is used to set the info in the connection data structure
1685  * return
1686  * 0: success
1687  * otherwise: error
1688  */
1689 static int
1690 iscsi_op_login_set_conn_info(struct spdk_iscsi_conn *conn,
1691 			     struct spdk_iscsi_pdu *rsp_pdu,
1692 			     char *initiator_port_name,
1693 			     enum session_type session_type, int cid)
1694 {
1695 	int rc = 0;
1696 	struct spdk_iscsi_tgt_node *target;
1697 	struct iscsi_bhs_login_rsp *rsph;
1698 	struct spdk_scsi_port *initiator_port;
1699 
1700 	target = conn->target;
1701 
1702 	rsph = (struct iscsi_bhs_login_rsp *)&rsp_pdu->bhs;
1703 	conn->authenticated = false;
1704 	conn->auth.chap_phase = ISCSI_CHAP_PHASE_WAIT_A;
1705 	conn->cid = cid;
1706 
1707 	if (conn->sess == NULL) {
1708 		/* create initiator port */
1709 		initiator_port = spdk_scsi_port_create(iscsi_get_isid(rsph->isid), 0, initiator_port_name);
1710 		if (initiator_port == NULL) {
1711 			SPDK_ERRLOG("create_port() failed\n");
1712 			rsph->status_class = ISCSI_CLASS_TARGET_ERROR;
1713 			rsph->status_detail = ISCSI_LOGIN_STATUS_NO_RESOURCES;
1714 			return SPDK_ISCSI_LOGIN_ERROR_RESPONSE;
1715 		}
1716 
1717 		/* new session */
1718 		rc = create_iscsi_sess(conn, target, session_type);
1719 		if (rc < 0) {
1720 			spdk_scsi_port_free(&initiator_port);
1721 			SPDK_ERRLOG("create_sess() failed\n");
1722 			rsph->status_class = ISCSI_CLASS_TARGET_ERROR;
1723 			rsph->status_detail = ISCSI_LOGIN_STATUS_NO_RESOURCES;
1724 			return SPDK_ISCSI_LOGIN_ERROR_RESPONSE;
1725 		}
1726 		/* initialize parameters */
1727 		conn->sess->initiator_port = initiator_port;
1728 		conn->StatSN = from_be32(&rsph->stat_sn);
1729 		conn->sess->isid = iscsi_get_isid(rsph->isid);
1730 
1731 		/* Initiator port TransportID */
1732 		spdk_scsi_port_set_iscsi_transport_id(conn->sess->initiator_port,
1733 						      conn->initiator_name,
1734 						      conn->sess->isid);
1735 
1736 		/* Discovery sessions will not have a target. */
1737 		if (target != NULL) {
1738 			conn->sess->queue_depth = target->queue_depth;
1739 		} else {
1740 			/*
1741 			 * Assume discovery sessions have an effective command
1742 			 *  windows size of 1.
1743 			 */
1744 			conn->sess->queue_depth = 1;
1745 		}
1746 		conn->sess->ExpCmdSN = rsp_pdu->cmd_sn;
1747 		conn->sess->MaxCmdSN = rsp_pdu->cmd_sn + conn->sess->queue_depth - 1;
1748 	}
1749 
1750 	conn->initiator_port = conn->sess->initiator_port;
1751 
1752 	return 0;
1753 }
1754 
1755 /*
1756  * This function is used to set the target info
1757  * return
1758  * 0: success
1759  * otherwise: error
1760  */
1761 static int
1762 iscsi_op_login_set_target_info(struct spdk_iscsi_conn *conn,
1763 			       struct spdk_iscsi_pdu *rsp_pdu,
1764 			       enum session_type session_type)
1765 {
1766 	char buf[MAX_TMPBUF];
1767 	const char *val;
1768 	int rc = 0;
1769 	struct spdk_iscsi_tgt_node *target = conn->target;
1770 
1771 	/* declarative parameters */
1772 	if (target != NULL) {
1773 		pthread_mutex_lock(&target->mutex);
1774 		if (target->alias[0] != '\0') {
1775 			snprintf(buf, sizeof buf, "%s", target->alias);
1776 		} else {
1777 			snprintf(buf, sizeof buf, "%s", "");
1778 		}
1779 		pthread_mutex_unlock(&target->mutex);
1780 		rc = iscsi_param_set(conn->sess->params, "TargetAlias", buf);
1781 		if (rc < 0) {
1782 			SPDK_ERRLOG("iscsi_param_set() failed\n");
1783 			return SPDK_ISCSI_LOGIN_ERROR_PARAMETER;
1784 		}
1785 	}
1786 	snprintf(buf, sizeof buf, "%s:%s,%d", conn->portal_host, conn->portal_port,
1787 		 conn->pg_tag);
1788 	rc = iscsi_param_set(conn->sess->params, "TargetAddress", buf);
1789 	if (rc < 0) {
1790 		SPDK_ERRLOG("iscsi_param_set() failed\n");
1791 		return SPDK_ISCSI_LOGIN_ERROR_PARAMETER;
1792 	}
1793 	snprintf(buf, sizeof buf, "%d", conn->pg_tag);
1794 	rc = iscsi_param_set(conn->sess->params, "TargetPortalGroupTag", buf);
1795 	if (rc < 0) {
1796 		SPDK_ERRLOG("iscsi_param_set() failed\n");
1797 		return SPDK_ISCSI_LOGIN_ERROR_PARAMETER;
1798 	}
1799 
1800 	/* write in response */
1801 	if (target != NULL) {
1802 		val = iscsi_param_get_val(conn->sess->params, "TargetAlias");
1803 		if (val != NULL && strlen(val) != 0) {
1804 			rsp_pdu->data_segment_len = iscsi_append_param(conn,
1805 						    "TargetAlias",
1806 						    rsp_pdu->data,
1807 						    rsp_pdu->data_buf_len,
1808 						    rsp_pdu->data_segment_len);
1809 		}
1810 		if (session_type == SESSION_TYPE_DISCOVERY) {
1811 			rsp_pdu->data_segment_len = iscsi_append_param(conn,
1812 						    "TargetAddress",
1813 						    rsp_pdu->data,
1814 						    rsp_pdu->data_buf_len,
1815 						    rsp_pdu->data_segment_len);
1816 		}
1817 		rsp_pdu->data_segment_len = iscsi_append_param(conn,
1818 					    "TargetPortalGroupTag",
1819 					    rsp_pdu->data,
1820 					    rsp_pdu->data_buf_len,
1821 					    rsp_pdu->data_segment_len);
1822 	}
1823 
1824 	return rc;
1825 }
1826 
1827 /*
1828  * This function is used to handle the login of iscsi initiator when there is
1829  * no session
1830  * return:
1831  * 0, success;
1832  * SPDK_ISCSI_LOGIN_ERROR_PARAMETER, parameter error;
1833  * SPDK_ISCSI_LOGIN_ERROR_RESPONSE,  used to notify the login fail.
1834  */
1835 static int
1836 iscsi_op_login_phase_none(struct spdk_iscsi_conn *conn,
1837 			  struct spdk_iscsi_pdu *rsp_pdu,
1838 			  struct iscsi_param *params, int cid)
1839 {
1840 	enum session_type session_type;
1841 	char initiator_port_name[MAX_INITIATOR_PORT_NAME];
1842 	struct iscsi_bhs_login_rsp *rsph;
1843 	int rc = 0;
1844 	rsph = (struct iscsi_bhs_login_rsp *)&rsp_pdu->bhs;
1845 
1846 	conn->target = NULL;
1847 	conn->dev = NULL;
1848 
1849 	rc = iscsi_op_login_initialize_port(conn, rsp_pdu, initiator_port_name,
1850 					    MAX_INITIATOR_PORT_NAME, params);
1851 	if (rc < 0) {
1852 		return rc;
1853 	}
1854 
1855 	rc = iscsi_op_login_session_type(conn, rsp_pdu, &session_type, params);
1856 	if (rc < 0) {
1857 		return rc;
1858 	}
1859 
1860 	/* Target Name and Port */
1861 	if (session_type == SESSION_TYPE_NORMAL) {
1862 		rc = iscsi_op_login_session_normal(conn, rsp_pdu,
1863 						   initiator_port_name,
1864 						   params, cid);
1865 		if (rc < 0) {
1866 			return rc;
1867 		}
1868 
1869 	} else if (session_type == SESSION_TYPE_DISCOVERY) {
1870 		rsph->tsih = 0;
1871 
1872 		/* force target flags */
1873 		pthread_mutex_lock(&g_iscsi.mutex);
1874 		rc = iscsi_op_login_session_discovery_chap(conn);
1875 		pthread_mutex_unlock(&g_iscsi.mutex);
1876 		if (rc < 0) {
1877 			return rc;
1878 		}
1879 	} else {
1880 		SPDK_ERRLOG("unknown session type\n");
1881 		/* Missing parameter */
1882 		rsph->status_class = ISCSI_CLASS_INITIATOR_ERROR;
1883 		rsph->status_detail = ISCSI_LOGIN_MISSING_PARMS;
1884 		return SPDK_ISCSI_LOGIN_ERROR_RESPONSE;
1885 	}
1886 
1887 	rc = iscsi_op_login_set_conn_info(conn, rsp_pdu, initiator_port_name,
1888 					  session_type, cid);
1889 	if (rc < 0) {
1890 		return rc;
1891 	}
1892 
1893 	/* limit conns on discovery session */
1894 	if (session_type == SESSION_TYPE_DISCOVERY) {
1895 		conn->sess->MaxConnections = 1;
1896 		rc = iscsi_param_set_int(conn->sess->params,
1897 					 "MaxConnections",
1898 					 conn->sess->MaxConnections);
1899 		if (rc < 0) {
1900 			SPDK_ERRLOG("iscsi_param_set_int() failed\n");
1901 			return SPDK_ISCSI_LOGIN_ERROR_PARAMETER;
1902 		}
1903 	}
1904 
1905 	return iscsi_op_login_set_target_info(conn, rsp_pdu, session_type);
1906 }
1907 
1908 /*
1909  * This function is used to set the csg bit case in rsp
1910  * return:
1911  * 0, success
1912  * otherwise: error
1913  */
1914 static int
1915 iscsi_op_login_rsp_handle_csg_bit(struct spdk_iscsi_conn *conn,
1916 				  struct spdk_iscsi_pdu *rsp_pdu,
1917 				  struct iscsi_param *params)
1918 {
1919 	const char *auth_method;
1920 	int rc;
1921 	struct iscsi_bhs_login_rsp *rsph;
1922 	rsph = (struct iscsi_bhs_login_rsp *)&rsp_pdu->bhs;
1923 
1924 	switch (ISCSI_BHS_LOGIN_GET_CSG(rsph->flags)) {
1925 	case ISCSI_SECURITY_NEGOTIATION_PHASE:
1926 		/* SecurityNegotiation */
1927 		auth_method = iscsi_param_get_val(conn->params, "AuthMethod");
1928 		if (auth_method == NULL) {
1929 			SPDK_ERRLOG("AuthMethod is empty\n");
1930 			/* Missing parameter */
1931 			rsph->status_class = ISCSI_CLASS_INITIATOR_ERROR;
1932 			rsph->status_detail = ISCSI_LOGIN_MISSING_PARMS;
1933 			return SPDK_ISCSI_LOGIN_ERROR_RESPONSE;
1934 		}
1935 		if (strcasecmp(auth_method, "None") == 0) {
1936 			conn->authenticated = true;
1937 		} else {
1938 			rc = iscsi_auth_params(conn, params, auth_method,
1939 					       rsp_pdu->data, rsp_pdu->data_buf_len,
1940 					       rsp_pdu->data_segment_len);
1941 			if (rc < 0) {
1942 				SPDK_ERRLOG("iscsi_auth_params() failed\n");
1943 				/* Authentication failure */
1944 				rsph->status_class = ISCSI_CLASS_INITIATOR_ERROR;
1945 				rsph->status_detail = ISCSI_LOGIN_AUTHENT_FAIL;
1946 				return SPDK_ISCSI_LOGIN_ERROR_RESPONSE;
1947 			}
1948 			rsp_pdu->data_segment_len = rc;
1949 			if (!conn->authenticated) {
1950 				/* not complete */
1951 				rsph->flags &= ~ISCSI_LOGIN_TRANSIT;
1952 			} else {
1953 				if (conn->auth.chap_phase != ISCSI_CHAP_PHASE_END) {
1954 					SPDK_DEBUGLOG(iscsi, "CHAP phase not complete");
1955 				}
1956 			}
1957 
1958 			SPDK_LOGDUMP(iscsi, "Negotiated Auth Params",
1959 				     rsp_pdu->data, rsp_pdu->data_segment_len);
1960 		}
1961 		break;
1962 
1963 	case ISCSI_OPERATIONAL_NEGOTIATION_PHASE:
1964 		/* LoginOperationalNegotiation */
1965 		if (conn->state == ISCSI_CONN_STATE_INVALID) {
1966 			if (conn->require_chap) {
1967 				/* Authentication failure */
1968 				rsph->status_class = ISCSI_CLASS_INITIATOR_ERROR;
1969 				rsph->status_detail = ISCSI_LOGIN_AUTHENT_FAIL;
1970 				return SPDK_ISCSI_LOGIN_ERROR_RESPONSE;
1971 			} else {
1972 				/* AuthMethod=None */
1973 				conn->authenticated = true;
1974 			}
1975 		}
1976 		if (!conn->authenticated) {
1977 			SPDK_ERRLOG("authentication error\n");
1978 			/* Authentication failure */
1979 			rsph->status_class = ISCSI_CLASS_INITIATOR_ERROR;
1980 			rsph->status_detail = ISCSI_LOGIN_AUTHENT_FAIL;
1981 			return SPDK_ISCSI_LOGIN_ERROR_RESPONSE;
1982 		}
1983 		break;
1984 
1985 	case ISCSI_FULL_FEATURE_PHASE:
1986 		/* FullFeaturePhase */
1987 		SPDK_ERRLOG("XXX Login in FullFeaturePhase\n");
1988 		/* Initiator error */
1989 		rsph->status_class = ISCSI_CLASS_INITIATOR_ERROR;
1990 		rsph->status_detail = ISCSI_LOGIN_INITIATOR_ERROR;
1991 		return SPDK_ISCSI_LOGIN_ERROR_RESPONSE;
1992 
1993 	default:
1994 		SPDK_ERRLOG("unknown stage\n");
1995 		/* Initiator error */
1996 		rsph->status_class = ISCSI_CLASS_INITIATOR_ERROR;
1997 		rsph->status_detail = ISCSI_LOGIN_INITIATOR_ERROR;
1998 		return SPDK_ISCSI_LOGIN_ERROR_RESPONSE;
1999 	}
2000 
2001 	return 0;
2002 }
2003 
2004 /* This function is used to notify the session info
2005  * return
2006  * 0: success
2007  * otherwise: error
2008  */
2009 static int
2010 iscsi_op_login_notify_session_info(struct spdk_iscsi_conn *conn,
2011 				   struct spdk_iscsi_pdu *rsp_pdu)
2012 {
2013 	struct iscsi_bhs_login_rsp *rsph;
2014 
2015 	rsph = (struct iscsi_bhs_login_rsp *)&rsp_pdu->bhs;
2016 	if (conn->sess->session_type == SESSION_TYPE_NORMAL) {
2017 		/* normal session */
2018 		SPDK_DEBUGLOG(iscsi, "Login from %s (%s) on %s tgt_node%d"
2019 			      " (%s:%s,%d), ISID=%"PRIx64", TSIH=%u,"
2020 			      " CID=%u, HeaderDigest=%s, DataDigest=%s\n",
2021 			      conn->initiator_name, conn->initiator_addr,
2022 			      conn->target->name, conn->target->num,
2023 			      conn->portal_host, conn->portal_port, conn->pg_tag,
2024 			      conn->sess->isid, conn->sess->tsih, conn->cid,
2025 			      (iscsi_param_eq_val(conn->params, "HeaderDigest", "CRC32C")
2026 			       ? "on" : "off"),
2027 			      (iscsi_param_eq_val(conn->params, "DataDigest", "CRC32C")
2028 			       ? "on" : "off"));
2029 	} else if (conn->sess->session_type == SESSION_TYPE_DISCOVERY) {
2030 		/* discovery session */
2031 		SPDK_DEBUGLOG(iscsi, "Login(discovery) from %s (%s) on"
2032 			      " (%s:%s,%d), ISID=%"PRIx64", TSIH=%u,"
2033 			      " CID=%u, HeaderDigest=%s, DataDigest=%s\n",
2034 			      conn->initiator_name, conn->initiator_addr,
2035 			      conn->portal_host, conn->portal_port, conn->pg_tag,
2036 			      conn->sess->isid, conn->sess->tsih, conn->cid,
2037 			      (iscsi_param_eq_val(conn->params, "HeaderDigest", "CRC32C")
2038 			       ? "on" : "off"),
2039 			      (iscsi_param_eq_val(conn->params, "DataDigest", "CRC32C")
2040 			       ? "on" : "off"));
2041 	} else {
2042 		SPDK_ERRLOG("unknown session type\n");
2043 		/* Initiator error */
2044 		rsph->status_class = ISCSI_CLASS_INITIATOR_ERROR;
2045 		rsph->status_detail = ISCSI_LOGIN_INITIATOR_ERROR;
2046 		return SPDK_ISCSI_LOGIN_ERROR_RESPONSE;
2047 	}
2048 
2049 	return 0;
2050 }
2051 
2052 /*
2053  * This function is to handle the tbit cases
2054  * return
2055  * 0: success
2056  * otherwise error
2057  */
2058 static int
2059 iscsi_op_login_rsp_handle_t_bit(struct spdk_iscsi_conn *conn,
2060 				struct spdk_iscsi_pdu *rsp_pdu)
2061 {
2062 	int rc;
2063 	struct iscsi_bhs_login_rsp *rsph;
2064 	rsph = (struct iscsi_bhs_login_rsp *)&rsp_pdu->bhs;
2065 
2066 	switch (ISCSI_BHS_LOGIN_GET_NSG(rsph->flags)) {
2067 	case ISCSI_SECURITY_NEGOTIATION_PHASE:
2068 		/* SecurityNegotiation */
2069 		conn->login_phase = ISCSI_SECURITY_NEGOTIATION_PHASE;
2070 		break;
2071 
2072 	case ISCSI_OPERATIONAL_NEGOTIATION_PHASE:
2073 		/* LoginOperationalNegotiation */
2074 		conn->login_phase = ISCSI_OPERATIONAL_NEGOTIATION_PHASE;
2075 		break;
2076 
2077 	case ISCSI_FULL_FEATURE_PHASE:
2078 		/* FullFeaturePhase */
2079 		conn->login_phase = ISCSI_FULL_FEATURE_PHASE;
2080 		to_be16(&rsph->tsih, conn->sess->tsih);
2081 
2082 		rc = iscsi_op_login_notify_session_info(conn, rsp_pdu);
2083 		if (rc < 0) {
2084 			return rc;
2085 		}
2086 
2087 		conn->full_feature = 1;
2088 		break;
2089 
2090 	default:
2091 		SPDK_ERRLOG("unknown stage\n");
2092 		/* Initiator error */
2093 		rsph->status_class = ISCSI_CLASS_INITIATOR_ERROR;
2094 		rsph->status_detail = ISCSI_LOGIN_INITIATOR_ERROR;
2095 		return SPDK_ISCSI_LOGIN_ERROR_RESPONSE;
2096 	}
2097 
2098 	return 0;
2099 }
2100 
2101 /*
2102  * This function is used to set the values of the internal data structure used
2103  * by spdk_iscsi_op_login function
2104  * return:
2105  * 0, used to notify the a successful login
2106  * SPDK_ISCSI_LOGIN_ERROR_RESPONSE,  used to notify a failure login.
2107  */
2108 static int
2109 iscsi_op_login_rsp_handle(struct spdk_iscsi_conn *conn,
2110 			  struct spdk_iscsi_pdu *rsp_pdu, struct iscsi_param **params)
2111 {
2112 	int rc;
2113 	struct iscsi_bhs_login_rsp *rsph;
2114 	rsph = (struct iscsi_bhs_login_rsp *)&rsp_pdu->bhs;
2115 
2116 	/* negotiate parameters */
2117 	rc = iscsi_negotiate_params(conn, params, rsp_pdu->data,
2118 				    rsp_pdu->data_buf_len,
2119 				    rsp_pdu->data_segment_len);
2120 	if (rc < 0) {
2121 		/*
2122 		 * iscsi_negotiate_params just returns -1 on failure,
2123 		 *  so translate this into meaningful response codes and
2124 		 *  return values.
2125 		 */
2126 		rsph->status_class = ISCSI_CLASS_INITIATOR_ERROR;
2127 		rsph->status_detail = ISCSI_LOGIN_INITIATOR_ERROR;
2128 		return SPDK_ISCSI_LOGIN_ERROR_RESPONSE;
2129 	}
2130 
2131 	rsp_pdu->data_segment_len = rc;
2132 	SPDK_LOGDUMP(iscsi, "Negotiated Params", rsp_pdu->data, rc);
2133 
2134 	/* handle the CSG bit case */
2135 	rc = iscsi_op_login_rsp_handle_csg_bit(conn, rsp_pdu, *params);
2136 	if (rc < 0) {
2137 		return rc;
2138 	}
2139 
2140 	/* handle the T bit case */
2141 	if (ISCSI_BHS_LOGIN_GET_TBIT(rsph->flags)) {
2142 		rc = iscsi_op_login_rsp_handle_t_bit(conn, rsp_pdu);
2143 	}
2144 
2145 	return rc;
2146 }
2147 
2148 static int
2149 iscsi_pdu_hdr_op_login(struct spdk_iscsi_conn *conn, struct spdk_iscsi_pdu *pdu)
2150 {
2151 	int rc;
2152 	struct iscsi_bhs_login_req *reqh;
2153 	struct spdk_iscsi_pdu *rsp_pdu;
2154 
2155 	if (conn->full_feature && conn->sess != NULL &&
2156 	    conn->sess->session_type == SESSION_TYPE_DISCOVERY) {
2157 		return SPDK_ISCSI_CONNECTION_FATAL;
2158 	}
2159 
2160 	reqh = (struct iscsi_bhs_login_req *)&pdu->bhs;
2161 	pdu->cmd_sn = from_be32(&reqh->cmd_sn);
2162 
2163 	/* During login processing, use the 8KB default FirstBurstLength as
2164 	 *  our maximum data segment length value.
2165 	 */
2166 	if (pdu->data_segment_len > SPDK_ISCSI_FIRST_BURST_LENGTH) {
2167 		return iscsi_reject(conn, pdu, ISCSI_REASON_PROTOCOL_ERROR);
2168 	}
2169 
2170 	rsp_pdu = iscsi_get_pdu(conn);
2171 	if (rsp_pdu == NULL) {
2172 		return SPDK_ISCSI_CONNECTION_FATAL;
2173 	}
2174 	rc = iscsi_op_login_rsp_init(conn, pdu, rsp_pdu);
2175 	if (rc < 0) {
2176 		iscsi_op_login_response(conn, rsp_pdu, NULL, iscsi_conn_login_pdu_err_complete);
2177 		return 0;
2178 	}
2179 
2180 	conn->login_rsp_pdu = rsp_pdu;
2181 	return 0;
2182 }
2183 
2184 static int
2185 iscsi_pdu_payload_op_login(struct spdk_iscsi_conn *conn, struct spdk_iscsi_pdu *pdu)
2186 {
2187 	int rc;
2188 	struct iscsi_bhs_login_req *reqh;
2189 	struct spdk_iscsi_pdu *rsp_pdu;
2190 	struct iscsi_param *params = NULL;
2191 	int cid;
2192 
2193 	if (conn->login_rsp_pdu == NULL) {
2194 		return 0;
2195 	}
2196 
2197 	spdk_poller_unregister(&conn->login_timer);
2198 	rsp_pdu = conn->login_rsp_pdu;
2199 
2200 	reqh = (struct iscsi_bhs_login_req *)&pdu->bhs;
2201 	cid = from_be16(&reqh->cid);
2202 
2203 	rc = iscsi_op_login_store_incoming_params(conn, pdu, rsp_pdu, &params);
2204 	if (rc < 0) {
2205 		iscsi_op_login_response(conn, rsp_pdu, NULL, iscsi_conn_login_pdu_err_complete);
2206 		return 0;
2207 	}
2208 
2209 	if (conn->state == ISCSI_CONN_STATE_INVALID) {
2210 		rc = iscsi_op_login_phase_none(conn, rsp_pdu, params, cid);
2211 		if (rc == SPDK_ISCSI_LOGIN_ERROR_RESPONSE || rc == SPDK_ISCSI_LOGIN_ERROR_PARAMETER) {
2212 			iscsi_op_login_response(conn, rsp_pdu, params, iscsi_conn_login_pdu_err_complete);
2213 			return 0;
2214 		}
2215 	}
2216 
2217 	rc = iscsi_op_login_rsp_handle(conn, rsp_pdu, &params);
2218 	if (rc == SPDK_ISCSI_LOGIN_ERROR_RESPONSE) {
2219 		iscsi_op_login_response(conn, rsp_pdu, params, iscsi_conn_login_pdu_err_complete);
2220 		return 0;
2221 	}
2222 
2223 	iscsi_op_login_response(conn, rsp_pdu, params, iscsi_conn_login_pdu_success_complete);
2224 	return 0;
2225 }
2226 
2227 static int
2228 iscsi_pdu_hdr_op_text(struct spdk_iscsi_conn *conn, struct spdk_iscsi_pdu *pdu)
2229 {
2230 	uint32_t task_tag;
2231 	uint32_t ExpStatSN;
2232 	int F_bit, C_bit;
2233 	struct iscsi_bhs_text_req *reqh;
2234 
2235 	if (pdu->data_segment_len > iscsi_get_max_immediate_data_size()) {
2236 		SPDK_ERRLOG("data segment len(=%zu) > immediate data len(=%"PRIu32")\n",
2237 			    pdu->data_segment_len, iscsi_get_max_immediate_data_size());
2238 		return iscsi_reject(conn, pdu, ISCSI_REASON_PROTOCOL_ERROR);
2239 	}
2240 
2241 	reqh = (struct iscsi_bhs_text_req *)&pdu->bhs;
2242 
2243 	F_bit = !!(reqh->flags & ISCSI_FLAG_FINAL);
2244 	C_bit = !!(reqh->flags & ISCSI_TEXT_CONTINUE);
2245 	task_tag = from_be32(&reqh->itt);
2246 	ExpStatSN = from_be32(&reqh->exp_stat_sn);
2247 
2248 	SPDK_DEBUGLOG(iscsi, "I=%d, F=%d, C=%d, ITT=%x, TTT=%x\n",
2249 		      reqh->immediate, F_bit, C_bit, task_tag, from_be32(&reqh->ttt));
2250 
2251 	SPDK_DEBUGLOG(iscsi,
2252 		      "CmdSN=%u, ExpStatSN=%u, StatSN=%u, ExpCmdSN=%u, MaxCmdSN=%u\n",
2253 		      pdu->cmd_sn, ExpStatSN, conn->StatSN, conn->sess->ExpCmdSN,
2254 		      conn->sess->MaxCmdSN);
2255 
2256 	if (ExpStatSN != conn->StatSN) {
2257 #if 0
2258 		SPDK_ERRLOG("StatSN(%u) error\n", ExpStatSN);
2259 		return -1;
2260 #else
2261 		/* StarPort have a bug */
2262 		SPDK_DEBUGLOG(iscsi, "StatSN(%u) rewound\n", ExpStatSN);
2263 		conn->StatSN = ExpStatSN;
2264 #endif
2265 	}
2266 
2267 	if (F_bit && C_bit) {
2268 		SPDK_ERRLOG("final and continue\n");
2269 		return -1;
2270 	}
2271 
2272 	/*
2273 	 * If this is the first text op in a sequence, save the ITT so we can
2274 	 * compare it against the ITT for subsequent ops in the same sequence.
2275 	 * If a subsequent text op in same sequence has a different ITT, reject
2276 	 * that PDU.
2277 	 */
2278 	if (conn->sess->current_text_itt == 0xffffffffU) {
2279 		conn->sess->current_text_itt = task_tag;
2280 	} else if (conn->sess->current_text_itt != task_tag) {
2281 		SPDK_ERRLOG("The correct itt is %u, and the current itt is %u...\n",
2282 			    conn->sess->current_text_itt, task_tag);
2283 		return iscsi_reject(conn, pdu, ISCSI_REASON_PROTOCOL_ERROR);
2284 	}
2285 
2286 	return 0;
2287 }
2288 
2289 static void
2290 iscsi_conn_text_pdu_complete(void *arg)
2291 {
2292 	struct spdk_iscsi_conn *conn = arg;
2293 
2294 	iscsi_conn_params_update(conn);
2295 }
2296 
2297 static int
2298 iscsi_pdu_payload_op_text(struct spdk_iscsi_conn *conn, struct spdk_iscsi_pdu *pdu)
2299 {
2300 	struct iscsi_param *params = NULL;
2301 	struct spdk_iscsi_pdu *rsp_pdu;
2302 	uint8_t *data;
2303 	uint64_t lun;
2304 	uint32_t task_tag;
2305 	const char *val;
2306 	int F_bit, C_bit;
2307 	int data_len;
2308 	int alloc_len;
2309 	int rc;
2310 	struct iscsi_bhs_text_req *reqh;
2311 	struct iscsi_bhs_text_resp *rsph;
2312 
2313 	data_len = 0;
2314 	alloc_len = conn->MaxRecvDataSegmentLength;
2315 
2316 	reqh = (struct iscsi_bhs_text_req *)&pdu->bhs;
2317 
2318 	F_bit = !!(reqh->flags & ISCSI_FLAG_FINAL);
2319 	C_bit = !!(reqh->flags & ISCSI_TEXT_CONTINUE);
2320 	lun = from_be64(&reqh->lun);
2321 	task_tag = from_be32(&reqh->itt);
2322 
2323 	/* store incoming parameters */
2324 	rc = iscsi_parse_params(&params, pdu->data, pdu->data_segment_len,
2325 				C_bit, &conn->partial_text_parameter);
2326 	if (rc < 0) {
2327 		SPDK_ERRLOG("iscsi_parse_params() failed\n");
2328 		iscsi_param_free(params);
2329 		return -1;
2330 	}
2331 
2332 	if (pdu->data_segment_len == 0 && params == NULL) {
2333 		params = conn->params_text;
2334 		conn->params_text = NULL;
2335 	}
2336 
2337 	data = calloc(1, alloc_len);
2338 	if (!data) {
2339 		SPDK_ERRLOG("calloc() failed for data segment\n");
2340 		iscsi_param_free(params);
2341 		return -ENOMEM;
2342 	}
2343 
2344 	/* negotiate parameters */
2345 	data_len = iscsi_negotiate_params(conn, &params,
2346 					  data, alloc_len, data_len);
2347 	if (data_len < 0) {
2348 		SPDK_ERRLOG("iscsi_negotiate_params() failed\n");
2349 		iscsi_param_free(params);
2350 		free(data);
2351 		return -1;
2352 	}
2353 
2354 	/* sendtargets is special case */
2355 	val = iscsi_param_get_val(params, "SendTargets");
2356 	if (val != NULL) {
2357 		if (iscsi_param_eq_val(conn->sess->params,
2358 				       "SessionType", "Discovery")) {
2359 			if (strcasecmp(val, "") == 0) {
2360 				val = "ALL";
2361 			}
2362 
2363 			data_len = iscsi_send_tgts(conn,
2364 						   conn->initiator_name,
2365 						   val, data, alloc_len,
2366 						   data_len);
2367 		} else {
2368 			if (strcasecmp(val, "") == 0) {
2369 				val = conn->target->name;
2370 			}
2371 
2372 			if (strcasecmp(val, "ALL") == 0) {
2373 				/* not in discovery session */
2374 				data_len = iscsi_append_text("SendTargets", "Reject",
2375 							     data, alloc_len, data_len);
2376 			} else {
2377 				data_len = iscsi_send_tgts(conn,
2378 							   conn->initiator_name,
2379 							   val, data, alloc_len,
2380 							   data_len);
2381 			}
2382 		}
2383 
2384 		if (conn->send_tgt_completed_size != 0) {
2385 			F_bit = 0;
2386 			C_bit = 1;
2387 		}
2388 	} else {
2389 		if (iscsi_param_eq_val(conn->sess->params, "SessionType", "Discovery")) {
2390 			iscsi_param_free(params);
2391 			free(data);
2392 			return SPDK_ISCSI_CONNECTION_FATAL;
2393 		}
2394 	}
2395 
2396 	if (spdk_likely(conn->send_tgt_completed_size == 0)) {
2397 		iscsi_param_free(params);
2398 	} else {
2399 		conn->params_text = params;
2400 	}
2401 	SPDK_LOGDUMP(iscsi, "Negotiated Params", data, data_len);
2402 
2403 	/* response PDU */
2404 	rsp_pdu = iscsi_get_pdu(conn);
2405 	if (rsp_pdu == NULL) {
2406 		free(data);
2407 		return SPDK_ISCSI_CONNECTION_FATAL;
2408 	}
2409 	rsph = (struct iscsi_bhs_text_resp *)&rsp_pdu->bhs;
2410 
2411 	rsp_pdu->data = data;
2412 	rsph->opcode = ISCSI_OP_TEXT_RSP;
2413 
2414 	if (F_bit) {
2415 		rsph->flags |= ISCSI_FLAG_FINAL;
2416 	}
2417 
2418 	if (C_bit) {
2419 		rsph->flags |= ISCSI_TEXT_CONTINUE;
2420 	}
2421 
2422 	DSET24(rsph->data_segment_len, data_len);
2423 	to_be64(&rsph->lun, lun);
2424 	to_be32(&rsph->itt, task_tag);
2425 
2426 	if (F_bit) {
2427 		rsph->ttt = 0xffffffffU;
2428 		conn->sess->current_text_itt = 0xffffffffU;
2429 	} else {
2430 		to_be32(&rsph->ttt, 1 + conn->id);
2431 	}
2432 
2433 	to_be32(&rsph->stat_sn, conn->StatSN);
2434 	conn->StatSN++;
2435 
2436 	if (reqh->immediate == 0) {
2437 		conn->sess->MaxCmdSN++;
2438 	}
2439 
2440 	to_be32(&rsph->exp_cmd_sn, conn->sess->ExpCmdSN);
2441 	to_be32(&rsph->max_cmd_sn, conn->sess->MaxCmdSN);
2442 
2443 	iscsi_conn_write_pdu(conn, rsp_pdu, iscsi_conn_text_pdu_complete, conn);
2444 	return 0;
2445 }
2446 
2447 static void iscsi_conn_logout_pdu_complete(void *arg)
2448 {
2449 	struct spdk_iscsi_conn *conn = arg;
2450 
2451 	if (conn->sess == NULL) {
2452 		/*
2453 		 * login failed but initiator still sent a logout rather than
2454 		 *  just closing the TCP connection.
2455 		 */
2456 		SPDK_DEBUGLOG(iscsi, "Logout(login failed) from %s (%s) on"
2457 			      " (%s:%s,%d)\n",
2458 			      conn->initiator_name, conn->initiator_addr,
2459 			      conn->portal_host, conn->portal_port, conn->pg_tag);
2460 	} else if (iscsi_param_eq_val(conn->sess->params, "SessionType", "Normal")) {
2461 		SPDK_DEBUGLOG(iscsi, "Logout from %s (%s) on %s tgt_node%d"
2462 			      " (%s:%s,%d), ISID=%"PRIx64", TSIH=%u,"
2463 			      " CID=%u, HeaderDigest=%s, DataDigest=%s\n",
2464 			      conn->initiator_name, conn->initiator_addr,
2465 			      conn->target->name, conn->target->num,
2466 			      conn->portal_host, conn->portal_port, conn->pg_tag,
2467 			      conn->sess->isid, conn->sess->tsih, conn->cid,
2468 			      (iscsi_param_eq_val(conn->params, "HeaderDigest", "CRC32C")
2469 			       ? "on" : "off"),
2470 			      (iscsi_param_eq_val(conn->params, "DataDigest", "CRC32C")
2471 			       ? "on" : "off"));
2472 	} else {
2473 		/* discovery session */
2474 		SPDK_DEBUGLOG(iscsi, "Logout(discovery) from %s (%s) on"
2475 			      " (%s:%s,%d), ISID=%"PRIx64", TSIH=%u,"
2476 			      " CID=%u, HeaderDigest=%s, DataDigest=%s\n",
2477 			      conn->initiator_name, conn->initiator_addr,
2478 			      conn->portal_host, conn->portal_port, conn->pg_tag,
2479 			      conn->sess->isid, conn->sess->tsih, conn->cid,
2480 			      (iscsi_param_eq_val(conn->params, "HeaderDigest", "CRC32C")
2481 			       ? "on" : "off"),
2482 			      (iscsi_param_eq_val(conn->params, "DataDigest", "CRC32C")
2483 			       ? "on" : "off"));
2484 	}
2485 }
2486 
2487 static int
2488 iscsi_pdu_hdr_op_logout(struct spdk_iscsi_conn *conn, struct spdk_iscsi_pdu *pdu)
2489 {
2490 	struct spdk_iscsi_pdu *rsp_pdu;
2491 	uint32_t task_tag;
2492 	uint32_t ExpStatSN;
2493 	int response;
2494 	struct iscsi_bhs_logout_req *reqh;
2495 	struct iscsi_bhs_logout_resp *rsph;
2496 	uint16_t cid;
2497 
2498 	reqh = (struct iscsi_bhs_logout_req *)&pdu->bhs;
2499 
2500 	cid = from_be16(&reqh->cid);
2501 	task_tag = from_be32(&reqh->itt);
2502 	ExpStatSN = from_be32(&reqh->exp_stat_sn);
2503 
2504 	SPDK_DEBUGLOG(iscsi, "reason=%d, ITT=%x, cid=%d\n",
2505 		      reqh->reason, task_tag, cid);
2506 
2507 	if (conn->sess != NULL) {
2508 		if (conn->sess->session_type == SESSION_TYPE_DISCOVERY &&
2509 		    reqh->reason != ISCSI_LOGOUT_REASON_CLOSE_SESSION) {
2510 			SPDK_ERRLOG("Target can accept logout only with reason \"close the session\" "
2511 				    "on discovery session. %d is not acceptable reason.\n",
2512 				    reqh->reason);
2513 			return SPDK_ISCSI_CONNECTION_FATAL;
2514 		}
2515 
2516 		SPDK_DEBUGLOG(iscsi,
2517 			      "CmdSN=%u, ExpStatSN=%u, StatSN=%u, ExpCmdSN=%u, MaxCmdSN=%u\n",
2518 			      pdu->cmd_sn, ExpStatSN, conn->StatSN,
2519 			      conn->sess->ExpCmdSN, conn->sess->MaxCmdSN);
2520 
2521 		if (pdu->cmd_sn != conn->sess->ExpCmdSN) {
2522 			SPDK_DEBUGLOG(iscsi, "CmdSN(%u) might have dropped\n", pdu->cmd_sn);
2523 			/* ignore error */
2524 		}
2525 	} else {
2526 		SPDK_DEBUGLOG(iscsi, "CmdSN=%u, ExpStatSN=%u, StatSN=%u\n",
2527 			      pdu->cmd_sn, ExpStatSN, conn->StatSN);
2528 	}
2529 
2530 	if (ExpStatSN != conn->StatSN) {
2531 		SPDK_DEBUGLOG(iscsi, "StatSN(%u/%u) might have dropped\n",
2532 			      ExpStatSN, conn->StatSN);
2533 		/* ignore error */
2534 	}
2535 
2536 	if (conn->cid == cid) {
2537 		/* connection or session closed successfully */
2538 		response = 0;
2539 		iscsi_conn_logout(conn);
2540 	} else {
2541 		response = 1;
2542 	}
2543 
2544 	/* response PDU */
2545 	rsp_pdu = iscsi_get_pdu(conn);
2546 	if (rsp_pdu == NULL) {
2547 		return SPDK_ISCSI_CONNECTION_FATAL;
2548 	}
2549 	rsph = (struct iscsi_bhs_logout_resp *)&rsp_pdu->bhs;
2550 	rsp_pdu->data = NULL;
2551 	rsph->opcode = ISCSI_OP_LOGOUT_RSP;
2552 	rsph->flags |= 0x80; /* bit 0 must be 1 */
2553 	rsph->response = response;
2554 	DSET24(rsph->data_segment_len, 0);
2555 	to_be32(&rsph->itt, task_tag);
2556 
2557 	if (conn->sess != NULL) {
2558 		to_be32(&rsph->stat_sn, conn->StatSN);
2559 		conn->StatSN++;
2560 
2561 		if (conn->sess->connections == 1) {
2562 			conn->sess->MaxCmdSN++;
2563 		}
2564 
2565 		to_be32(&rsph->exp_cmd_sn, conn->sess->ExpCmdSN);
2566 		to_be32(&rsph->max_cmd_sn, conn->sess->MaxCmdSN);
2567 	} else {
2568 		to_be32(&rsph->stat_sn, conn->StatSN);
2569 		conn->StatSN++;
2570 		to_be32(&rsph->exp_cmd_sn, pdu->cmd_sn);
2571 		to_be32(&rsph->max_cmd_sn, pdu->cmd_sn);
2572 	}
2573 
2574 	rsph->time_2_wait = 0;
2575 	rsph->time_2_retain = 0;
2576 
2577 	iscsi_conn_write_pdu(conn, rsp_pdu, iscsi_conn_logout_pdu_complete, conn);
2578 
2579 	return 0;
2580 }
2581 
2582 static int
2583 iscsi_send_r2t(struct spdk_iscsi_conn *conn,
2584 	       struct spdk_iscsi_task *task, int offset,
2585 	       int len, uint32_t transfer_tag, uint32_t *R2TSN)
2586 {
2587 	struct spdk_iscsi_pdu *rsp_pdu;
2588 	struct iscsi_bhs_r2t *rsph;
2589 	uint64_t fmt_lun;
2590 
2591 	/* R2T PDU */
2592 	rsp_pdu = iscsi_get_pdu(conn);
2593 	if (rsp_pdu == NULL) {
2594 		return SPDK_ISCSI_CONNECTION_FATAL;
2595 	}
2596 	rsph = (struct iscsi_bhs_r2t *)&rsp_pdu->bhs;
2597 	rsp_pdu->data = NULL;
2598 	rsph->opcode = ISCSI_OP_R2T;
2599 	rsph->flags |= 0x80; /* bit 0 is default to 1 */
2600 	fmt_lun = spdk_scsi_lun_id_int_to_fmt(task->lun_id);
2601 	to_be64(&rsph->lun, fmt_lun);
2602 	to_be32(&rsph->itt, task->tag);
2603 	to_be32(&rsph->ttt, transfer_tag);
2604 
2605 	to_be32(&rsph->stat_sn, conn->StatSN);
2606 	to_be32(&rsph->exp_cmd_sn, conn->sess->ExpCmdSN);
2607 	to_be32(&rsph->max_cmd_sn, conn->sess->MaxCmdSN);
2608 
2609 	to_be32(&rsph->r2t_sn, *R2TSN);
2610 	*R2TSN += 1;
2611 
2612 	task->r2t_datasn = 0; /* next expected datasn to ack */
2613 
2614 	to_be32(&rsph->buffer_offset, (uint32_t)offset);
2615 	to_be32(&rsph->desired_xfer_len, (uint32_t)len);
2616 	task->desired_data_transfer_length = (size_t)len;
2617 
2618 	/* we need to hold onto this task/cmd because until the PDU has been
2619 	 * written out */
2620 	rsp_pdu->task = task;
2621 	task->scsi.ref++;
2622 
2623 	iscsi_conn_write_pdu(conn, rsp_pdu, iscsi_conn_pdu_generic_complete, NULL);
2624 
2625 	return 0;
2626 }
2627 
2628 /* This function is used to remove the r2t pdu from snack_pdu_list by < task, r2t_sn> info */
2629 static struct spdk_iscsi_pdu *
2630 iscsi_remove_r2t_pdu_from_snack_list(struct spdk_iscsi_conn *conn,
2631 				     struct spdk_iscsi_task *task,
2632 				     uint32_t r2t_sn)
2633 {
2634 	struct spdk_iscsi_pdu *pdu;
2635 	struct iscsi_bhs_r2t *r2t_header;
2636 
2637 	TAILQ_FOREACH(pdu, &conn->snack_pdu_list, tailq) {
2638 		if (pdu->bhs.opcode == ISCSI_OP_R2T) {
2639 			r2t_header = (struct iscsi_bhs_r2t *)&pdu->bhs;
2640 			if (pdu->task == task &&
2641 			    from_be32(&r2t_header->r2t_sn) == r2t_sn) {
2642 				TAILQ_REMOVE(&conn->snack_pdu_list, pdu, tailq);
2643 				return pdu;
2644 			}
2645 		}
2646 	}
2647 
2648 	return NULL;
2649 }
2650 
2651 /* This function is used re-send the r2t packet */
2652 static int
2653 iscsi_send_r2t_recovery(struct spdk_iscsi_conn *conn,
2654 			struct spdk_iscsi_task *task, uint32_t r2t_sn,
2655 			bool send_new_r2tsn)
2656 {
2657 	struct spdk_iscsi_pdu *pdu;
2658 	struct iscsi_bhs_r2t *rsph;
2659 	uint32_t transfer_len;
2660 	uint32_t len;
2661 	int rc;
2662 
2663 	/* remove the r2t pdu from the snack_list */
2664 	pdu = iscsi_remove_r2t_pdu_from_snack_list(conn, task, r2t_sn);
2665 	if (!pdu) {
2666 		SPDK_DEBUGLOG(iscsi, "No pdu is found\n");
2667 		return -1;
2668 	}
2669 
2670 	/* flag
2671 	 * false: only need to re-send the old r2t with changing statsn
2672 	 * true: we send a r2t with new r2tsn
2673 	 */
2674 	if (!send_new_r2tsn) {
2675 		to_be32(&pdu->bhs.stat_sn, conn->StatSN);
2676 		iscsi_conn_write_pdu(conn, pdu, iscsi_conn_pdu_generic_complete, NULL);
2677 	} else {
2678 		rsph = (struct iscsi_bhs_r2t *)&pdu->bhs;
2679 		transfer_len = from_be32(&rsph->desired_xfer_len);
2680 
2681 		/* still need to increase the acked r2tsn */
2682 		task->acked_r2tsn++;
2683 		len = spdk_min(conn->sess->MaxBurstLength,
2684 			       (transfer_len - task->next_expected_r2t_offset));
2685 
2686 		/* remove the old_r2t_pdu */
2687 		iscsi_conn_free_pdu(conn, pdu);
2688 
2689 		/* re-send a new r2t pdu */
2690 		rc = iscsi_send_r2t(conn, task, task->next_expected_r2t_offset,
2691 				    len, task->ttt, &task->R2TSN);
2692 		if (rc < 0) {
2693 			return SPDK_ISCSI_CONNECTION_FATAL;
2694 		}
2695 	}
2696 
2697 	return 0;
2698 }
2699 
2700 static int
2701 add_transfer_task(struct spdk_iscsi_conn *conn, struct spdk_iscsi_task *task)
2702 {
2703 	uint32_t transfer_len;
2704 	size_t max_burst_len;
2705 	size_t segment_len;
2706 	size_t data_len;
2707 	int len;
2708 	int rc;
2709 	int data_out_req;
2710 
2711 	transfer_len = task->scsi.transfer_len;
2712 	data_len = iscsi_task_get_pdu(task)->data_segment_len;
2713 	max_burst_len = conn->sess->MaxBurstLength;
2714 	segment_len = SPDK_ISCSI_MAX_RECV_DATA_SEGMENT_LENGTH;
2715 	data_out_req = 1 + (transfer_len - data_len - 1) / segment_len;
2716 	task->data_out_cnt = data_out_req;
2717 
2718 	/*
2719 	 * If we already have too many tasks using R2T, then queue this task
2720 	 *  and start sending R2T for it after some of the tasks using R2T/data
2721 	 *  out buffers complete.
2722 	 */
2723 	if (conn->pending_r2t >= g_iscsi.MaxR2TPerConnection) {
2724 		TAILQ_INSERT_TAIL(&conn->queued_r2t_tasks, task, link);
2725 		return 0;
2726 	}
2727 
2728 	conn->data_out_cnt += data_out_req;
2729 	conn->pending_r2t++;
2730 
2731 	task->next_expected_r2t_offset = data_len;
2732 	task->current_data_offset = data_len;
2733 	task->current_r2t_length = 0;
2734 	task->R2TSN = 0;
2735 	/* According to RFC3720 10.8.5, 0xffffffff is
2736 	 * reserved for TTT in R2T.
2737 	 */
2738 	if (++conn->ttt == 0xffffffffu) {
2739 		conn->ttt = 0;
2740 	}
2741 	task->ttt = conn->ttt;
2742 
2743 	while (data_len != transfer_len) {
2744 		len = spdk_min(max_burst_len, (transfer_len - data_len));
2745 		rc = iscsi_send_r2t(conn, task, data_len, len,
2746 				    task->ttt, &task->R2TSN);
2747 		if (rc < 0) {
2748 			SPDK_ERRLOG("iscsi_send_r2t() failed\n");
2749 			return rc;
2750 		}
2751 		data_len += len;
2752 		task->next_r2t_offset = data_len;
2753 		task->outstanding_r2t++;
2754 		if (conn->sess->MaxOutstandingR2T == task->outstanding_r2t) {
2755 			break;
2756 		}
2757 	}
2758 
2759 	TAILQ_INSERT_TAIL(&conn->active_r2t_tasks, task, link);
2760 	task->is_r2t_active = true;
2761 	return 0;
2762 }
2763 
2764 /* If there are additional large writes queued for R2Ts, start them now.
2765  *  This is called when a large write is just completed or when multiple LUNs
2766  *  are attached and large write tasks for the specific LUN are cleared.
2767  */
2768 static void
2769 start_queued_transfer_tasks(struct spdk_iscsi_conn *conn)
2770 {
2771 	struct spdk_iscsi_task *task, *tmp;
2772 
2773 	TAILQ_FOREACH_SAFE(task, &conn->queued_r2t_tasks, link, tmp) {
2774 		if (conn->pending_r2t < g_iscsi.MaxR2TPerConnection) {
2775 			TAILQ_REMOVE(&conn->queued_r2t_tasks, task, link);
2776 			add_transfer_task(conn, task);
2777 		} else {
2778 			break;
2779 		}
2780 	}
2781 }
2782 
2783 bool
2784 iscsi_del_transfer_task(struct spdk_iscsi_conn *conn, uint32_t task_tag)
2785 {
2786 	struct spdk_iscsi_task *task, *tmp;
2787 
2788 	TAILQ_FOREACH_SAFE(task, &conn->active_r2t_tasks, link, tmp) {
2789 		if (task->tag == task_tag) {
2790 			assert(conn->data_out_cnt >= task->data_out_cnt);
2791 			conn->data_out_cnt -= task->data_out_cnt;
2792 
2793 			assert(conn->pending_r2t > 0);
2794 			conn->pending_r2t--;
2795 
2796 			assert(task->is_r2t_active == true);
2797 			TAILQ_REMOVE(&conn->active_r2t_tasks, task, link);
2798 			task->is_r2t_active = false;
2799 			iscsi_task_put(task);
2800 
2801 			start_queued_transfer_tasks(conn);
2802 			return true;
2803 		}
2804 	}
2805 	return false;
2806 }
2807 
2808 void iscsi_clear_all_transfer_task(struct spdk_iscsi_conn *conn,
2809 				   struct spdk_scsi_lun *lun,
2810 				   struct spdk_iscsi_pdu *pdu)
2811 {
2812 	struct spdk_iscsi_task *task, *task_tmp;
2813 	struct spdk_iscsi_pdu *pdu_tmp;
2814 
2815 	TAILQ_FOREACH_SAFE(task, &conn->active_r2t_tasks, link, task_tmp) {
2816 		pdu_tmp = iscsi_task_get_pdu(task);
2817 		if ((lun == NULL || lun == task->scsi.lun) &&
2818 		    (pdu == NULL || spdk_sn32_lt(pdu_tmp->cmd_sn, pdu->cmd_sn))) {
2819 			task->outstanding_r2t = 0;
2820 			task->next_r2t_offset = 0;
2821 			task->next_expected_r2t_offset = 0;
2822 			task->current_data_offset = 0;
2823 			assert(conn->data_out_cnt >= task->data_out_cnt);
2824 			conn->data_out_cnt -= task->data_out_cnt;
2825 			assert(conn->pending_r2t > 0);
2826 			conn->pending_r2t--;
2827 
2828 			TAILQ_REMOVE(&conn->active_r2t_tasks, task, link);
2829 			task->is_r2t_active = false;
2830 			if (lun != NULL && spdk_scsi_lun_is_removing(lun)) {
2831 				spdk_scsi_task_process_null_lun(&task->scsi);
2832 				iscsi_task_response(conn, task);
2833 			}
2834 			iscsi_task_put(task);
2835 		}
2836 	}
2837 
2838 	TAILQ_FOREACH_SAFE(task, &conn->queued_r2t_tasks, link, task_tmp) {
2839 		pdu_tmp = iscsi_task_get_pdu(task);
2840 		if ((lun == NULL || lun == task->scsi.lun) &&
2841 		    (pdu == NULL || spdk_sn32_lt(pdu_tmp->cmd_sn, pdu->cmd_sn))) {
2842 			TAILQ_REMOVE(&conn->queued_r2t_tasks, task, link);
2843 			task->is_r2t_active = false;
2844 			if (lun != NULL && spdk_scsi_lun_is_removing(lun)) {
2845 				spdk_scsi_task_process_null_lun(&task->scsi);
2846 				iscsi_task_response(conn, task);
2847 			}
2848 			iscsi_task_put(task);
2849 		}
2850 	}
2851 
2852 	start_queued_transfer_tasks(conn);
2853 }
2854 
2855 static struct spdk_iscsi_task *
2856 get_transfer_task(struct spdk_iscsi_conn *conn, uint32_t transfer_tag)
2857 {
2858 	struct spdk_iscsi_task *task;
2859 
2860 	TAILQ_FOREACH(task, &conn->active_r2t_tasks, link) {
2861 		if (task->ttt == transfer_tag) {
2862 			return task;
2863 		}
2864 	}
2865 
2866 	return NULL;
2867 }
2868 
2869 static void
2870 iscsi_conn_datain_pdu_complete(void *arg)
2871 {
2872 	struct spdk_iscsi_conn *conn = arg;
2873 
2874 	iscsi_conn_handle_queued_datain_tasks(conn);
2875 }
2876 
2877 static int
2878 iscsi_send_datain(struct spdk_iscsi_conn *conn,
2879 		  struct spdk_iscsi_task *task, int datain_flag,
2880 		  int residual_len, int offset, int DataSN, int len)
2881 {
2882 	struct spdk_iscsi_pdu *rsp_pdu;
2883 	struct iscsi_bhs_data_in *rsph;
2884 	uint32_t task_tag;
2885 	uint32_t transfer_tag;
2886 	int F_bit, U_bit, O_bit, S_bit;
2887 	struct spdk_iscsi_task *primary;
2888 	struct spdk_scsi_lun *lun_dev;
2889 
2890 	primary = iscsi_task_get_primary(task);
2891 
2892 	/* DATA PDU */
2893 	rsp_pdu = iscsi_get_pdu(conn);
2894 	rsph = (struct iscsi_bhs_data_in *)&rsp_pdu->bhs;
2895 	rsp_pdu->data = task->scsi.iovs[0].iov_base + offset;
2896 	rsp_pdu->data_buf_len = task->scsi.iovs[0].iov_len - offset;
2897 	rsp_pdu->data_valid_bytes = len;
2898 	rsp_pdu->data_from_mempool = true;
2899 
2900 	task_tag = task->tag;
2901 	transfer_tag = 0xffffffffU;
2902 
2903 	F_bit = datain_flag & ISCSI_FLAG_FINAL;
2904 	O_bit = datain_flag & ISCSI_DATAIN_OVERFLOW;
2905 	U_bit = datain_flag & ISCSI_DATAIN_UNDERFLOW;
2906 	S_bit = datain_flag & ISCSI_DATAIN_STATUS;
2907 
2908 	/*
2909 	 * we need to hold onto this task/cmd because until the
2910 	 * PDU has been written out
2911 	 */
2912 	rsp_pdu->task = task;
2913 	task->scsi.ref++;
2914 
2915 	rsph->opcode = ISCSI_OP_SCSI_DATAIN;
2916 
2917 	if (F_bit) {
2918 		rsph->flags |= ISCSI_FLAG_FINAL;
2919 	}
2920 
2921 	/* we leave the A_bit clear */
2922 
2923 	if (F_bit && S_bit)  {
2924 		if (O_bit) {
2925 			rsph->flags |= ISCSI_DATAIN_OVERFLOW;
2926 		}
2927 
2928 		if (U_bit) {
2929 			rsph->flags |= ISCSI_DATAIN_UNDERFLOW;
2930 		}
2931 	}
2932 
2933 	if (S_bit) {
2934 		rsph->flags |= ISCSI_DATAIN_STATUS;
2935 		rsph->status = task->scsi.status;
2936 	}
2937 
2938 	DSET24(rsph->data_segment_len, len);
2939 
2940 	to_be32(&rsph->itt, task_tag);
2941 	to_be32(&rsph->ttt, transfer_tag);
2942 
2943 	if (S_bit) {
2944 		to_be32(&rsph->stat_sn, conn->StatSN);
2945 		conn->StatSN++;
2946 	}
2947 
2948 	if (F_bit && S_bit && !iscsi_task_is_immediate(primary)) {
2949 		conn->sess->MaxCmdSN++;
2950 	}
2951 
2952 	to_be32(&rsph->exp_cmd_sn, conn->sess->ExpCmdSN);
2953 	to_be32(&rsph->max_cmd_sn, conn->sess->MaxCmdSN);
2954 
2955 	to_be32(&rsph->data_sn, DataSN);
2956 
2957 	if (conn->sess->ErrorRecoveryLevel >= 1) {
2958 		primary->datain_datasn = DataSN;
2959 	}
2960 	DataSN++;
2961 
2962 	offset += task->scsi.offset;
2963 	to_be32(&rsph->buffer_offset, (uint32_t)offset);
2964 
2965 	if (F_bit && S_bit) {
2966 		to_be32(&rsph->res_cnt, residual_len);
2967 	}
2968 
2969 	lun_dev = spdk_scsi_dev_get_lun(conn->dev, task->lun_id);
2970 	if (spdk_likely(lun_dev != NULL)) {
2971 		if (spdk_unlikely(spdk_scsi_lun_get_dif_ctx(lun_dev, &task->scsi,
2972 				  &rsp_pdu->dif_ctx))) {
2973 			rsp_pdu->dif_insert_or_strip = true;
2974 		}
2975 	}
2976 
2977 	iscsi_conn_write_pdu(conn, rsp_pdu, iscsi_conn_datain_pdu_complete, conn);
2978 
2979 	return DataSN;
2980 }
2981 
2982 static int
2983 iscsi_transfer_in(struct spdk_iscsi_conn *conn, struct spdk_iscsi_task *task)
2984 {
2985 	uint32_t DataSN;
2986 	uint32_t transfer_len;
2987 	uint32_t data_len;
2988 	uint32_t segment_len;
2989 	uint32_t offset;
2990 	uint32_t residual_len = 0;
2991 	int sent_status;
2992 	uint32_t len;
2993 	int datain_flag = 0;
2994 	int datain_seq_cnt;
2995 	int i;
2996 	uint32_t sequence_end;
2997 	struct spdk_iscsi_task *primary;
2998 
2999 	primary = iscsi_task_get_primary(task);
3000 	segment_len = conn->MaxRecvDataSegmentLength;
3001 	data_len = task->scsi.data_transferred;
3002 	transfer_len = task->scsi.length;
3003 
3004 	if (task->scsi.status != SPDK_SCSI_STATUS_GOOD) {
3005 		return 0;
3006 	}
3007 
3008 	if (data_len < transfer_len) {
3009 		/* underflow */
3010 		SPDK_DEBUGLOG(iscsi, "Underflow %u/%u\n", data_len, transfer_len);
3011 		residual_len = transfer_len - data_len;
3012 		transfer_len = data_len;
3013 		datain_flag |= ISCSI_DATAIN_UNDERFLOW;
3014 	} else if (data_len > transfer_len) {
3015 		/* overflow */
3016 		SPDK_DEBUGLOG(iscsi, "Overflow %u/%u\n", data_len, transfer_len);
3017 		residual_len = data_len - transfer_len;
3018 		datain_flag |= ISCSI_DATAIN_OVERFLOW;
3019 	} else {
3020 		SPDK_DEBUGLOG(iscsi, "Transfer %u\n", transfer_len);
3021 		residual_len = 0;
3022 	}
3023 
3024 	DataSN = primary->datain_datasn;
3025 	sent_status = 0;
3026 
3027 	/* calculate the number of sequences for all data-in pdus */
3028 	datain_seq_cnt = 1 + ((transfer_len - 1) / (int)conn->sess->MaxBurstLength);
3029 	for (i = 0; i < datain_seq_cnt; i++) {
3030 		offset = i * conn->sess->MaxBurstLength;
3031 		sequence_end = spdk_min(((i + 1) * conn->sess->MaxBurstLength),
3032 					transfer_len);
3033 
3034 		/* send data splitted by segment_len */
3035 		for (; offset < sequence_end; offset += segment_len) {
3036 			len = spdk_min(segment_len, (sequence_end - offset));
3037 
3038 			datain_flag &= ~(ISCSI_FLAG_FINAL | ISCSI_DATAIN_STATUS);
3039 
3040 			if (offset + len == sequence_end) {
3041 				/* last PDU in a sequence */
3042 				datain_flag |= ISCSI_FLAG_FINAL;
3043 				if (task->scsi.sense_data_len == 0) {
3044 					/* The last pdu in all data-in pdus */
3045 					if ((offset + len) == transfer_len &&
3046 					    (primary->bytes_completed == primary->scsi.transfer_len)) {
3047 						datain_flag |= ISCSI_DATAIN_STATUS;
3048 						sent_status = 1;
3049 					}
3050 				}
3051 			}
3052 
3053 			SPDK_DEBUGLOG(iscsi, "Transfer=%d, Offset=%d, Len=%d\n",
3054 				      sequence_end, offset, len);
3055 			SPDK_DEBUGLOG(iscsi, "StatSN=%u, DataSN=%u, Offset=%u, Len=%d\n",
3056 				      conn->StatSN, DataSN, offset, len);
3057 
3058 			DataSN = iscsi_send_datain(conn, task, datain_flag, residual_len,
3059 						   offset, DataSN, len);
3060 		}
3061 	}
3062 
3063 	if (task != primary) {
3064 		primary->scsi.data_transferred += task->scsi.data_transferred;
3065 	}
3066 	primary->datain_datasn = DataSN;
3067 
3068 	return sent_status;
3069 }
3070 
3071 void iscsi_task_response(struct spdk_iscsi_conn *conn,
3072 			 struct spdk_iscsi_task *task)
3073 {
3074 	struct spdk_iscsi_pdu *rsp_pdu;
3075 	struct iscsi_bhs_scsi_resp *rsph;
3076 	uint32_t task_tag;
3077 	uint32_t transfer_len;
3078 	size_t residual_len;
3079 	size_t data_len;
3080 	int O_bit, U_bit;
3081 	int rc;
3082 	struct spdk_iscsi_task *primary;
3083 
3084 	primary = iscsi_task_get_primary(task);
3085 
3086 	transfer_len = primary->scsi.transfer_len;
3087 	task_tag = task->tag;
3088 
3089 	/* transfer data from logical unit */
3090 	/* (direction is view of initiator side) */
3091 	if (iscsi_task_is_read(primary)) {
3092 		rc = iscsi_transfer_in(conn, task);
3093 		if (rc > 0) {
3094 			/* sent status by last DATAIN PDU */
3095 			return;
3096 		}
3097 
3098 		if (primary->bytes_completed != primary->scsi.transfer_len) {
3099 			return;
3100 		}
3101 	}
3102 
3103 	O_bit = U_bit = 0;
3104 	residual_len = 0;
3105 	data_len = primary->scsi.data_transferred;
3106 
3107 	if ((transfer_len != 0) &&
3108 	    (task->scsi.status == SPDK_SCSI_STATUS_GOOD)) {
3109 		if (data_len < transfer_len) {
3110 			/* underflow */
3111 			SPDK_DEBUGLOG(iscsi, "Underflow %zu/%u\n", data_len, transfer_len);
3112 			residual_len = transfer_len - data_len;
3113 			U_bit = 1;
3114 		} else if (data_len > transfer_len) {
3115 			/* overflow */
3116 			SPDK_DEBUGLOG(iscsi, "Overflow %zu/%u\n", data_len, transfer_len);
3117 			residual_len = data_len - transfer_len;
3118 			O_bit = 1;
3119 		} else {
3120 			SPDK_DEBUGLOG(iscsi, "Transfer %u\n", transfer_len);
3121 		}
3122 	}
3123 
3124 	/* response PDU */
3125 	rsp_pdu = iscsi_get_pdu(conn);
3126 	assert(rsp_pdu != NULL);
3127 	rsph = (struct iscsi_bhs_scsi_resp *)&rsp_pdu->bhs;
3128 	assert(task->scsi.sense_data_len <= sizeof(rsp_pdu->sense.data));
3129 	memcpy(rsp_pdu->sense.data, task->scsi.sense_data, task->scsi.sense_data_len);
3130 	to_be16(&rsp_pdu->sense.length, task->scsi.sense_data_len);
3131 	rsp_pdu->data = (uint8_t *)&rsp_pdu->sense;
3132 	rsp_pdu->data_from_mempool = true;
3133 
3134 	/*
3135 	 * we need to hold onto this task/cmd because until the
3136 	 * PDU has been written out
3137 	 */
3138 	rsp_pdu->task = task;
3139 	task->scsi.ref++;
3140 
3141 	rsph->opcode = ISCSI_OP_SCSI_RSP;
3142 	rsph->flags |= 0x80; /* bit 0 is default to 1 */
3143 
3144 	if (O_bit) {
3145 		rsph->flags |= ISCSI_SCSI_OVERFLOW;
3146 	}
3147 
3148 	if (U_bit) {
3149 		rsph->flags |= ISCSI_SCSI_UNDERFLOW;
3150 	}
3151 
3152 	rsph->status = task->scsi.status;
3153 	if (task->scsi.sense_data_len) {
3154 		/* SenseLength (2 bytes) + SenseData  */
3155 		DSET24(rsph->data_segment_len, 2 + task->scsi.sense_data_len);
3156 	}
3157 	to_be32(&rsph->itt, task_tag);
3158 
3159 	to_be32(&rsph->stat_sn, conn->StatSN);
3160 	conn->StatSN++;
3161 
3162 	if (!iscsi_task_is_immediate(primary)) {
3163 		conn->sess->MaxCmdSN++;
3164 	}
3165 
3166 	to_be32(&rsph->exp_cmd_sn, conn->sess->ExpCmdSN);
3167 	to_be32(&rsph->max_cmd_sn, conn->sess->MaxCmdSN);
3168 
3169 	to_be32(&rsph->bi_read_res_cnt, 0);
3170 	to_be32(&rsph->res_cnt, residual_len);
3171 
3172 	iscsi_conn_write_pdu(conn, rsp_pdu, iscsi_conn_pdu_generic_complete, NULL);
3173 }
3174 
3175 /*
3176  *  This function compare the input pdu's bhs with the pdu's bhs associated by
3177  *  active_r2t_tasks and queued_r2t_tasks in a connection
3178  */
3179 static bool
3180 iscsi_compare_pdu_bhs_within_existed_r2t_tasks(struct spdk_iscsi_conn *conn,
3181 		struct spdk_iscsi_pdu *pdu)
3182 {
3183 	struct spdk_iscsi_task	*task;
3184 
3185 	TAILQ_FOREACH(task, &conn->active_r2t_tasks, link) {
3186 		if (!memcmp(&pdu->bhs, iscsi_task_get_bhs(task), ISCSI_BHS_LEN)) {
3187 			return true;
3188 		}
3189 	}
3190 
3191 	TAILQ_FOREACH(task, &conn->queued_r2t_tasks, link) {
3192 		if (!memcmp(&pdu->bhs, iscsi_task_get_bhs(task), ISCSI_BHS_LEN)) {
3193 			return true;
3194 		}
3195 	}
3196 
3197 	return false;
3198 }
3199 
3200 void
3201 iscsi_queue_task(struct spdk_iscsi_conn *conn, struct spdk_iscsi_task *task)
3202 {
3203 	spdk_trace_record(TRACE_ISCSI_TASK_QUEUE, conn->id, task->scsi.length,
3204 			  (uintptr_t)task, (uintptr_t)task->pdu);
3205 	task->is_queued = true;
3206 	spdk_scsi_dev_queue_task(conn->dev, &task->scsi);
3207 }
3208 
3209 static int
3210 iscsi_pdu_payload_op_scsi_read(struct spdk_iscsi_conn *conn, struct spdk_iscsi_task *task)
3211 {
3212 	if (task->scsi.transfer_len <= SPDK_BDEV_LARGE_BUF_MAX_SIZE) {
3213 		task->parent = NULL;
3214 		task->scsi.offset = 0;
3215 		task->scsi.length = task->scsi.transfer_len;
3216 		spdk_scsi_task_set_data(&task->scsi, NULL, 0);
3217 
3218 		iscsi_queue_task(conn, task);
3219 		return 0;
3220 	} else {
3221 		TAILQ_INIT(&task->subtask_list);
3222 		task->current_data_offset = 0;
3223 		TAILQ_INSERT_TAIL(&conn->queued_datain_tasks, task, link);
3224 
3225 		return iscsi_conn_handle_queued_datain_tasks(conn);
3226 	}
3227 }
3228 
3229 static int
3230 iscsi_pdu_payload_op_scsi_write(struct spdk_iscsi_conn *conn, struct spdk_iscsi_task *task)
3231 {
3232 	struct spdk_iscsi_pdu *pdu;
3233 	struct iscsi_bhs_scsi_req *reqh;
3234 	uint32_t transfer_len;
3235 	uint32_t scsi_data_len;
3236 	struct spdk_iscsi_task *subtask;
3237 	int rc;
3238 
3239 	pdu = iscsi_task_get_pdu(task);
3240 	reqh = (struct iscsi_bhs_scsi_req *)&pdu->bhs;
3241 
3242 	transfer_len = task->scsi.transfer_len;
3243 
3244 	if (spdk_likely(!pdu->dif_insert_or_strip)) {
3245 		scsi_data_len = pdu->data_segment_len;
3246 	} else {
3247 		scsi_data_len = pdu->data_buf_len;
3248 	}
3249 
3250 	if (reqh->final_bit &&
3251 	    pdu->data_segment_len < transfer_len) {
3252 		/* needs R2T */
3253 		rc = add_transfer_task(conn, task);
3254 		if (rc < 0) {
3255 			SPDK_ERRLOG("add_transfer_task() failed\n");
3256 			iscsi_task_put(task);
3257 			return SPDK_ISCSI_CONNECTION_FATAL;
3258 		}
3259 
3260 		/* Non-immediate writes */
3261 		if (pdu->data_segment_len != 0) {
3262 			/* we are doing the first partial write task */
3263 			subtask = iscsi_task_get(conn, task, iscsi_task_cpl);
3264 			assert(subtask != NULL);
3265 
3266 			spdk_scsi_task_set_data(&subtask->scsi, pdu->data, scsi_data_len);
3267 			subtask->scsi.length = pdu->data_segment_len;
3268 			iscsi_task_associate_pdu(subtask, pdu);
3269 
3270 			iscsi_queue_task(conn, subtask);
3271 		}
3272 		return 0;
3273 	}
3274 
3275 	if (pdu->data_segment_len == transfer_len) {
3276 		/* we are doing small writes with no R2T */
3277 		spdk_scsi_task_set_data(&task->scsi, pdu->data, scsi_data_len);
3278 		task->scsi.length = transfer_len;
3279 	}
3280 
3281 	iscsi_queue_task(conn, task);
3282 	return 0;
3283 }
3284 
3285 static int
3286 iscsi_pdu_hdr_op_scsi(struct spdk_iscsi_conn *conn, struct spdk_iscsi_pdu *pdu)
3287 {
3288 	struct spdk_iscsi_task	*task;
3289 	struct spdk_scsi_dev	*dev;
3290 	uint8_t *cdb;
3291 	uint64_t lun;
3292 	uint32_t task_tag;
3293 	uint32_t transfer_len;
3294 	int R_bit, W_bit;
3295 	int lun_i;
3296 	struct iscsi_bhs_scsi_req *reqh;
3297 
3298 	if (conn->sess->session_type != SESSION_TYPE_NORMAL) {
3299 		SPDK_ERRLOG("ISCSI_OP_SCSI not allowed in discovery and invalid session\n");
3300 		return SPDK_ISCSI_CONNECTION_FATAL;
3301 	}
3302 
3303 	reqh = (struct iscsi_bhs_scsi_req *)&pdu->bhs;
3304 
3305 	R_bit = reqh->read_bit;
3306 	W_bit = reqh->write_bit;
3307 	lun = from_be64(&reqh->lun);
3308 	task_tag = from_be32(&reqh->itt);
3309 	transfer_len = from_be32(&reqh->expected_data_xfer_len);
3310 	cdb = reqh->cdb;
3311 
3312 	SPDK_LOGDUMP(iscsi, "CDB", cdb, 16);
3313 
3314 	task = iscsi_task_get(conn, NULL, iscsi_task_cpl);
3315 	if (!task) {
3316 		SPDK_ERRLOG("Unable to acquire task\n");
3317 		return SPDK_ISCSI_CONNECTION_FATAL;
3318 	}
3319 
3320 	iscsi_task_associate_pdu(task, pdu);
3321 	lun_i = spdk_scsi_lun_id_fmt_to_int(lun);
3322 	task->lun_id = lun_i;
3323 	dev = conn->dev;
3324 	task->scsi.lun = spdk_scsi_dev_get_lun(dev, lun_i);
3325 
3326 	if ((R_bit != 0) && (W_bit != 0)) {
3327 		SPDK_ERRLOG("Bidirectional CDB is not supported\n");
3328 		iscsi_task_put(task);
3329 		return SPDK_ISCSI_CONNECTION_FATAL;
3330 	}
3331 
3332 	task->scsi.cdb = cdb;
3333 	task->tag = task_tag;
3334 	task->scsi.transfer_len = transfer_len;
3335 	task->scsi.target_port = conn->target_port;
3336 	task->scsi.initiator_port = conn->initiator_port;
3337 	task->parent = NULL;
3338 	task->scsi.status = SPDK_SCSI_STATUS_GOOD;
3339 
3340 	if (task->scsi.lun == NULL) {
3341 		spdk_scsi_task_process_null_lun(&task->scsi);
3342 		iscsi_task_cpl(&task->scsi);
3343 		return 0;
3344 	}
3345 
3346 	/* no bi-directional support */
3347 	if (R_bit) {
3348 		task->scsi.dxfer_dir = SPDK_SCSI_DIR_FROM_DEV;
3349 	} else if (W_bit) {
3350 		task->scsi.dxfer_dir = SPDK_SCSI_DIR_TO_DEV;
3351 
3352 		if ((conn->sess->ErrorRecoveryLevel >= 1) &&
3353 		    (iscsi_compare_pdu_bhs_within_existed_r2t_tasks(conn, pdu))) {
3354 			iscsi_task_response(conn, task);
3355 			iscsi_task_put(task);
3356 			return 0;
3357 		}
3358 
3359 		if (pdu->data_segment_len > iscsi_get_max_immediate_data_size()) {
3360 			SPDK_ERRLOG("data segment len(=%zu) > immediate data len(=%"PRIu32")\n",
3361 				    pdu->data_segment_len, iscsi_get_max_immediate_data_size());
3362 			iscsi_task_put(task);
3363 			return iscsi_reject(conn, pdu, ISCSI_REASON_PROTOCOL_ERROR);
3364 		}
3365 
3366 		if (pdu->data_segment_len > transfer_len) {
3367 			SPDK_ERRLOG("data segment len(=%zu) > task transfer len(=%d)\n",
3368 				    pdu->data_segment_len, transfer_len);
3369 			iscsi_task_put(task);
3370 			return iscsi_reject(conn, pdu, ISCSI_REASON_PROTOCOL_ERROR);
3371 		}
3372 
3373 		/* check the ImmediateData and also pdu->data_segment_len */
3374 		if ((!conn->sess->ImmediateData && (pdu->data_segment_len > 0)) ||
3375 		    (pdu->data_segment_len > conn->sess->FirstBurstLength)) {
3376 			iscsi_task_put(task);
3377 			return iscsi_reject(conn, pdu, ISCSI_REASON_PROTOCOL_ERROR);
3378 		}
3379 
3380 		if (spdk_unlikely(spdk_scsi_lun_get_dif_ctx(task->scsi.lun, &task->scsi, &pdu->dif_ctx))) {
3381 			pdu->dif_insert_or_strip = true;
3382 		}
3383 	} else {
3384 		/* neither R nor W bit set */
3385 		task->scsi.dxfer_dir = SPDK_SCSI_DIR_NONE;
3386 		if (transfer_len > 0) {
3387 			iscsi_task_put(task);
3388 			SPDK_ERRLOG("Reject scsi cmd with EDTL > 0 but (R | W) == 0\n");
3389 			return iscsi_reject(conn, pdu, ISCSI_REASON_INVALID_PDU_FIELD);
3390 		}
3391 	}
3392 
3393 	pdu->task = task;
3394 	return 0;
3395 }
3396 
3397 static int
3398 iscsi_pdu_payload_op_scsi(struct spdk_iscsi_conn *conn, struct spdk_iscsi_pdu *pdu)
3399 {
3400 	struct spdk_iscsi_task *task;
3401 
3402 	if (pdu->task == NULL) {
3403 		return 0;
3404 	}
3405 
3406 	task = pdu->task;
3407 
3408 	if (spdk_scsi_dev_get_lun(conn->dev, task->lun_id) == NULL) {
3409 		spdk_scsi_task_process_null_lun(&task->scsi);
3410 		iscsi_task_cpl(&task->scsi);
3411 		return 0;
3412 	}
3413 
3414 	switch (task->scsi.dxfer_dir) {
3415 	case SPDK_SCSI_DIR_FROM_DEV:
3416 		return iscsi_pdu_payload_op_scsi_read(conn, task);
3417 	case SPDK_SCSI_DIR_TO_DEV:
3418 		return iscsi_pdu_payload_op_scsi_write(conn, task);
3419 	case SPDK_SCSI_DIR_NONE:
3420 		iscsi_queue_task(conn, task);
3421 		return 0;
3422 	default:
3423 		assert(false);
3424 		iscsi_task_put(task);
3425 		break;
3426 	}
3427 
3428 	return SPDK_ISCSI_CONNECTION_FATAL;
3429 }
3430 
3431 void
3432 iscsi_task_mgmt_response(struct spdk_iscsi_conn *conn,
3433 			 struct spdk_iscsi_task *task)
3434 {
3435 	struct spdk_iscsi_pdu *rsp_pdu;
3436 	struct iscsi_bhs_task_req *reqh;
3437 	struct iscsi_bhs_task_resp *rsph;
3438 
3439 	if (task->pdu == NULL) {
3440 		/*
3441 		 * This was an internally generated task management command,
3442 		 *  usually from LUN cleanup when a connection closes.
3443 		 */
3444 		return;
3445 	}
3446 
3447 	reqh = (struct iscsi_bhs_task_req *)&task->pdu->bhs;
3448 	/* response PDU */
3449 	rsp_pdu = iscsi_get_pdu(conn);
3450 	rsph = (struct iscsi_bhs_task_resp *)&rsp_pdu->bhs;
3451 	rsph->opcode = ISCSI_OP_TASK_RSP;
3452 	rsph->flags |= 0x80; /* bit 0 default to 1 */
3453 	switch (task->scsi.response) {
3454 	case SPDK_SCSI_TASK_MGMT_RESP_COMPLETE:
3455 		rsph->response = ISCSI_TASK_FUNC_RESP_COMPLETE;
3456 		break;
3457 	case SPDK_SCSI_TASK_MGMT_RESP_SUCCESS:
3458 		rsph->response = ISCSI_TASK_FUNC_RESP_COMPLETE;
3459 		break;
3460 	case SPDK_SCSI_TASK_MGMT_RESP_REJECT:
3461 		rsph->response = ISCSI_TASK_FUNC_REJECTED;
3462 		break;
3463 	case SPDK_SCSI_TASK_MGMT_RESP_INVALID_LUN:
3464 		rsph->response = ISCSI_TASK_FUNC_RESP_LUN_NOT_EXIST;
3465 		break;
3466 	case SPDK_SCSI_TASK_MGMT_RESP_TARGET_FAILURE:
3467 		rsph->response = ISCSI_TASK_FUNC_REJECTED;
3468 		break;
3469 	case SPDK_SCSI_TASK_MGMT_RESP_REJECT_FUNC_NOT_SUPPORTED:
3470 		rsph->response = ISCSI_TASK_FUNC_RESP_FUNC_NOT_SUPPORTED;
3471 		break;
3472 	}
3473 	rsph->itt = reqh->itt;
3474 
3475 	to_be32(&rsph->stat_sn, conn->StatSN);
3476 	conn->StatSN++;
3477 
3478 	if (reqh->immediate == 0) {
3479 		conn->sess->MaxCmdSN++;
3480 	}
3481 
3482 	to_be32(&rsph->exp_cmd_sn, conn->sess->ExpCmdSN);
3483 	to_be32(&rsph->max_cmd_sn, conn->sess->MaxCmdSN);
3484 
3485 	iscsi_conn_write_pdu(conn, rsp_pdu, iscsi_conn_pdu_generic_complete, NULL);
3486 }
3487 
3488 static void
3489 iscsi_queue_mgmt_task(struct spdk_iscsi_conn *conn, struct spdk_iscsi_task *task)
3490 {
3491 	struct spdk_scsi_lun *lun;
3492 
3493 	lun = spdk_scsi_dev_get_lun(conn->dev, task->lun_id);
3494 	if (lun == NULL) {
3495 		task->scsi.response = SPDK_SCSI_TASK_MGMT_RESP_INVALID_LUN;
3496 		iscsi_task_mgmt_response(conn, task);
3497 		iscsi_task_put(task);
3498 		return;
3499 	}
3500 
3501 	spdk_scsi_dev_queue_mgmt_task(conn->dev, &task->scsi);
3502 }
3503 
3504 static int
3505 _iscsi_op_abort_task(void *arg)
3506 {
3507 	struct spdk_iscsi_task *task = arg;
3508 	int rc;
3509 
3510 	rc = iscsi_conn_abort_queued_datain_task(task->conn, task->scsi.abort_id);
3511 	if (rc != 0) {
3512 		return SPDK_POLLER_BUSY;
3513 	}
3514 
3515 	spdk_poller_unregister(&task->mgmt_poller);
3516 	iscsi_queue_mgmt_task(task->conn, task);
3517 	return SPDK_POLLER_BUSY;
3518 }
3519 
3520 static void
3521 iscsi_op_abort_task(struct spdk_iscsi_task *task, uint32_t ref_task_tag)
3522 {
3523 	task->scsi.abort_id = ref_task_tag;
3524 	task->scsi.function = SPDK_SCSI_TASK_FUNC_ABORT_TASK;
3525 	task->mgmt_poller = SPDK_POLLER_REGISTER(_iscsi_op_abort_task, task, 10);
3526 }
3527 
3528 static int
3529 _iscsi_op_abort_task_set(void *arg)
3530 {
3531 	struct spdk_iscsi_task *task = arg;
3532 	int rc;
3533 
3534 	rc = iscsi_conn_abort_queued_datain_tasks(task->conn, task->scsi.lun,
3535 			task->pdu);
3536 	if (rc != 0) {
3537 		return SPDK_POLLER_BUSY;
3538 	}
3539 
3540 	spdk_poller_unregister(&task->mgmt_poller);
3541 	iscsi_queue_mgmt_task(task->conn, task);
3542 	return SPDK_POLLER_BUSY;
3543 }
3544 
3545 void
3546 iscsi_op_abort_task_set(struct spdk_iscsi_task *task, uint8_t function)
3547 {
3548 	task->scsi.function = function;
3549 	task->mgmt_poller = SPDK_POLLER_REGISTER(_iscsi_op_abort_task_set, task, 10);
3550 }
3551 
3552 static int
3553 iscsi_pdu_hdr_op_task(struct spdk_iscsi_conn *conn, struct spdk_iscsi_pdu *pdu)
3554 {
3555 	struct iscsi_bhs_task_req *reqh;
3556 	uint64_t lun;
3557 	uint32_t task_tag;
3558 	uint32_t ref_task_tag;
3559 	uint8_t function;
3560 	int lun_i;
3561 	struct spdk_iscsi_task *task;
3562 	struct spdk_scsi_dev *dev;
3563 
3564 	if (conn->sess->session_type != SESSION_TYPE_NORMAL) {
3565 		SPDK_ERRLOG("ISCSI_OP_TASK not allowed in discovery and invalid session\n");
3566 		return SPDK_ISCSI_CONNECTION_FATAL;
3567 	}
3568 
3569 	reqh = (struct iscsi_bhs_task_req *)&pdu->bhs;
3570 	function = reqh->flags & ISCSI_TASK_FUNCTION_MASK;
3571 	lun = from_be64(&reqh->lun);
3572 	task_tag = from_be32(&reqh->itt);
3573 	ref_task_tag = from_be32(&reqh->ref_task_tag);
3574 
3575 	SPDK_DEBUGLOG(iscsi, "I=%d, func=%d, ITT=%x, ref TT=%x, LUN=0x%16.16"PRIx64"\n",
3576 		      reqh->immediate, function, task_tag, ref_task_tag, lun);
3577 
3578 	SPDK_DEBUGLOG(iscsi, "StatSN=%u, ExpCmdSN=%u, MaxCmdSN=%u\n",
3579 		      conn->StatSN, conn->sess->ExpCmdSN, conn->sess->MaxCmdSN);
3580 
3581 	lun_i = spdk_scsi_lun_id_fmt_to_int(lun);
3582 	dev = conn->dev;
3583 
3584 	task = iscsi_task_get(conn, NULL, iscsi_task_mgmt_cpl);
3585 	if (!task) {
3586 		SPDK_ERRLOG("Unable to acquire task\n");
3587 		return SPDK_ISCSI_CONNECTION_FATAL;
3588 	}
3589 
3590 	iscsi_task_associate_pdu(task, pdu);
3591 	task->scsi.target_port = conn->target_port;
3592 	task->scsi.initiator_port = conn->initiator_port;
3593 	task->tag = task_tag;
3594 	task->scsi.lun = spdk_scsi_dev_get_lun(dev, lun_i);
3595 	task->lun_id = lun_i;
3596 
3597 	if (task->scsi.lun == NULL) {
3598 		task->scsi.response = SPDK_SCSI_TASK_MGMT_RESP_INVALID_LUN;
3599 		iscsi_task_mgmt_response(conn, task);
3600 		iscsi_task_put(task);
3601 		return 0;
3602 	}
3603 
3604 	switch (function) {
3605 	/* abort task identified by Referenced Task Tag field */
3606 	case ISCSI_TASK_FUNC_ABORT_TASK:
3607 		SPDK_NOTICELOG("ABORT_TASK\n");
3608 
3609 		iscsi_del_transfer_task(conn, ref_task_tag);
3610 		iscsi_op_abort_task(task, ref_task_tag);
3611 		return 0;
3612 
3613 	/* abort all tasks issued via this session on the LUN */
3614 	case ISCSI_TASK_FUNC_ABORT_TASK_SET:
3615 		SPDK_NOTICELOG("ABORT_TASK_SET\n");
3616 
3617 		iscsi_clear_all_transfer_task(conn, task->scsi.lun, pdu);
3618 		iscsi_op_abort_task_set(task, SPDK_SCSI_TASK_FUNC_ABORT_TASK_SET);
3619 		return 0;
3620 
3621 	case ISCSI_TASK_FUNC_CLEAR_TASK_SET:
3622 		task->scsi.response = SPDK_SCSI_TASK_MGMT_RESP_REJECT_FUNC_NOT_SUPPORTED;
3623 		SPDK_NOTICELOG("CLEAR_TASK_SET (Unsupported)\n");
3624 		break;
3625 
3626 	case ISCSI_TASK_FUNC_CLEAR_ACA:
3627 		task->scsi.response = SPDK_SCSI_TASK_MGMT_RESP_REJECT_FUNC_NOT_SUPPORTED;
3628 		SPDK_NOTICELOG("CLEAR_ACA (Unsupported)\n");
3629 		break;
3630 
3631 	case ISCSI_TASK_FUNC_LOGICAL_UNIT_RESET:
3632 		SPDK_NOTICELOG("LOGICAL_UNIT_RESET\n");
3633 
3634 		iscsi_clear_all_transfer_task(conn, task->scsi.lun, pdu);
3635 		iscsi_op_abort_task_set(task, SPDK_SCSI_TASK_FUNC_LUN_RESET);
3636 		return 0;
3637 
3638 	case ISCSI_TASK_FUNC_TARGET_WARM_RESET:
3639 		SPDK_NOTICELOG("TARGET_WARM_RESET (Unsupported)\n");
3640 		task->scsi.response = SPDK_SCSI_TASK_MGMT_RESP_REJECT_FUNC_NOT_SUPPORTED;
3641 		break;
3642 
3643 	case ISCSI_TASK_FUNC_TARGET_COLD_RESET:
3644 		SPDK_NOTICELOG("TARGET_COLD_RESET (Unsupported)\n");
3645 		task->scsi.response = SPDK_SCSI_TASK_MGMT_RESP_REJECT_FUNC_NOT_SUPPORTED;
3646 		break;
3647 
3648 	case ISCSI_TASK_FUNC_TASK_REASSIGN:
3649 		SPDK_NOTICELOG("TASK_REASSIGN (Unsupported)\n");
3650 		task->scsi.response = SPDK_SCSI_TASK_MGMT_RESP_REJECT_FUNC_NOT_SUPPORTED;
3651 		break;
3652 
3653 	default:
3654 		SPDK_ERRLOG("unsupported function %d\n", function);
3655 		task->scsi.response = SPDK_SCSI_TASK_MGMT_RESP_REJECT;
3656 		break;
3657 	}
3658 
3659 	iscsi_task_mgmt_response(conn, task);
3660 	iscsi_task_put(task);
3661 	return 0;
3662 }
3663 
3664 static int
3665 iscsi_pdu_hdr_op_nopout(struct spdk_iscsi_conn *conn, struct spdk_iscsi_pdu *pdu)
3666 {
3667 	struct iscsi_bhs_nop_out *reqh;
3668 	uint32_t task_tag;
3669 	uint32_t transfer_tag;
3670 	int I_bit;
3671 
3672 	if (conn->sess->session_type == SESSION_TYPE_DISCOVERY) {
3673 		SPDK_ERRLOG("ISCSI_OP_NOPOUT not allowed in discovery session\n");
3674 		return SPDK_ISCSI_CONNECTION_FATAL;
3675 	}
3676 
3677 	reqh = (struct iscsi_bhs_nop_out *)&pdu->bhs;
3678 	I_bit = reqh->immediate;
3679 
3680 	if (pdu->data_segment_len > SPDK_ISCSI_MAX_RECV_DATA_SEGMENT_LENGTH) {
3681 		return iscsi_reject(conn, pdu, ISCSI_REASON_PROTOCOL_ERROR);
3682 	}
3683 
3684 	task_tag = from_be32(&reqh->itt);
3685 	transfer_tag = from_be32(&reqh->ttt);
3686 
3687 	SPDK_DEBUGLOG(iscsi, "I=%d, ITT=%x, TTT=%x\n",
3688 		      I_bit, task_tag, transfer_tag);
3689 
3690 	SPDK_DEBUGLOG(iscsi, "CmdSN=%u, StatSN=%u, ExpCmdSN=%u, MaxCmdSN=%u\n",
3691 		      pdu->cmd_sn, conn->StatSN, conn->sess->ExpCmdSN,
3692 		      conn->sess->MaxCmdSN);
3693 
3694 	if (transfer_tag != 0xFFFFFFFF && transfer_tag != (uint32_t)conn->id) {
3695 		SPDK_ERRLOG("invalid transfer tag 0x%x\n", transfer_tag);
3696 		/*
3697 		 * Technically we should probably fail the connection here, but for now
3698 		 *  just print the error message and continue.
3699 		 */
3700 	}
3701 
3702 	if (task_tag == 0xffffffffU && I_bit == 0) {
3703 		SPDK_ERRLOG("got NOPOUT ITT=0xffffffff, I=0\n");
3704 		return SPDK_ISCSI_CONNECTION_FATAL;
3705 	}
3706 
3707 	return 0;
3708 }
3709 
3710 static int
3711 iscsi_pdu_payload_op_nopout(struct spdk_iscsi_conn *conn, struct spdk_iscsi_pdu *pdu)
3712 {
3713 	struct spdk_iscsi_pdu *rsp_pdu;
3714 	struct iscsi_bhs_nop_out *reqh;
3715 	struct iscsi_bhs_nop_in *rsph;
3716 	uint8_t *data;
3717 	uint64_t lun;
3718 	uint32_t task_tag;
3719 	int I_bit;
3720 	int data_len;
3721 
3722 	reqh = (struct iscsi_bhs_nop_out *)&pdu->bhs;
3723 	I_bit = reqh->immediate;
3724 
3725 	data_len = pdu->data_segment_len;
3726 	if (data_len > conn->MaxRecvDataSegmentLength) {
3727 		data_len = conn->MaxRecvDataSegmentLength;
3728 	}
3729 
3730 	lun = from_be64(&reqh->lun);
3731 	task_tag = from_be32(&reqh->itt);
3732 
3733 	/*
3734 	 * We don't actually check to see if this is a response to the NOP-In
3735 	 * that we sent.  Our goal is to just verify that the initiator is
3736 	 * alive and responding to commands, not to verify that it tags
3737 	 * NOP-Outs correctly
3738 	 */
3739 	conn->nop_outstanding = false;
3740 
3741 	if (task_tag == 0xffffffffU) {
3742 		assert(I_bit == 1);
3743 		SPDK_DEBUGLOG(iscsi, "got NOPOUT ITT=0xffffffff\n");
3744 		return 0;
3745 	}
3746 
3747 	data = calloc(1, data_len);
3748 	if (!data) {
3749 		SPDK_ERRLOG("calloc() failed for ping data\n");
3750 		return SPDK_ISCSI_CONNECTION_FATAL;
3751 	}
3752 
3753 	/* response of NOPOUT */
3754 	if (data_len > 0) {
3755 		/* copy ping data */
3756 		memcpy(data, pdu->data, data_len);
3757 	}
3758 
3759 	/* response PDU */
3760 	rsp_pdu = iscsi_get_pdu(conn);
3761 	assert(rsp_pdu != NULL);
3762 
3763 	rsph = (struct iscsi_bhs_nop_in *)&rsp_pdu->bhs;
3764 	rsp_pdu->data = data;
3765 	rsph->opcode = ISCSI_OP_NOPIN;
3766 	rsph->flags |= 0x80; /* bit 0 default to 1 */
3767 	DSET24(rsph->data_segment_len, data_len);
3768 	to_be64(&rsph->lun, lun);
3769 	to_be32(&rsph->itt, task_tag);
3770 	to_be32(&rsph->ttt, 0xffffffffU);
3771 
3772 	to_be32(&rsph->stat_sn, conn->StatSN);
3773 	conn->StatSN++;
3774 
3775 	if (I_bit == 0) {
3776 		conn->sess->MaxCmdSN++;
3777 	}
3778 
3779 	to_be32(&rsph->exp_cmd_sn, conn->sess->ExpCmdSN);
3780 	to_be32(&rsph->max_cmd_sn, conn->sess->MaxCmdSN);
3781 
3782 	iscsi_conn_write_pdu(conn, rsp_pdu, iscsi_conn_pdu_generic_complete, NULL);
3783 	conn->last_nopin = spdk_get_ticks();
3784 
3785 	return 0;
3786 }
3787 
3788 /* This function returns the spdk_scsi_task by searching the snack list via
3789  * task transfertag and the pdu's opcode
3790  */
3791 static struct spdk_iscsi_task *
3792 get_scsi_task_from_ttt(struct spdk_iscsi_conn *conn, uint32_t transfer_tag)
3793 {
3794 	struct spdk_iscsi_pdu *pdu;
3795 	struct iscsi_bhs_data_in *datain_bhs;
3796 
3797 	TAILQ_FOREACH(pdu, &conn->snack_pdu_list, tailq) {
3798 		if (pdu->bhs.opcode == ISCSI_OP_SCSI_DATAIN) {
3799 			datain_bhs = (struct iscsi_bhs_data_in *)&pdu->bhs;
3800 			if (from_be32(&datain_bhs->ttt) == transfer_tag) {
3801 				return pdu->task;
3802 			}
3803 		}
3804 	}
3805 
3806 	return NULL;
3807 }
3808 
3809 /* This function returns the spdk_scsi_task by searching the snack list via
3810  * initiator task tag and the pdu's opcode
3811  */
3812 static struct spdk_iscsi_task *
3813 get_scsi_task_from_itt(struct spdk_iscsi_conn *conn,
3814 		       uint32_t task_tag, enum iscsi_op opcode)
3815 {
3816 	struct spdk_iscsi_pdu *pdu;
3817 
3818 	TAILQ_FOREACH(pdu, &conn->snack_pdu_list, tailq) {
3819 		if (pdu->bhs.opcode == opcode &&
3820 		    pdu->task != NULL &&
3821 		    pdu->task->tag == task_tag) {
3822 			return pdu->task;
3823 		}
3824 	}
3825 
3826 	return NULL;
3827 }
3828 
3829 /* This function is used to handle the r2t snack */
3830 static int
3831 iscsi_handle_r2t_snack(struct spdk_iscsi_conn *conn,
3832 		       struct spdk_iscsi_task *task,
3833 		       struct spdk_iscsi_pdu *pdu, uint32_t beg_run,
3834 		       uint32_t run_length, int32_t task_tag)
3835 {
3836 	int32_t last_r2tsn;
3837 	int i;
3838 
3839 	if (beg_run < task->acked_r2tsn) {
3840 		SPDK_ERRLOG("ITT: 0x%08x, R2T SNACK requests retransmission of"
3841 			    "R2TSN: from 0x%08x to 0x%08x. But it has already"
3842 			    "ack to R2TSN:0x%08x, protocol error.\n",
3843 			    task_tag, beg_run, (beg_run + run_length),
3844 			    (task->acked_r2tsn - 1));
3845 		return iscsi_reject(conn, pdu, ISCSI_REASON_PROTOCOL_ERROR);
3846 	}
3847 
3848 	if (run_length) {
3849 		if ((beg_run + run_length) > task->R2TSN) {
3850 			SPDK_ERRLOG("ITT: 0x%08x, received R2T SNACK with"
3851 				    "BegRun: 0x%08x, RunLength: 0x%08x, exceeds"
3852 				    "current R2TSN: 0x%08x, protocol error.\n",
3853 				    task_tag, beg_run, run_length,
3854 				    task->R2TSN);
3855 
3856 			return iscsi_reject(conn, pdu, ISCSI_REASON_INVALID_PDU_FIELD);
3857 		}
3858 		last_r2tsn = (beg_run + run_length);
3859 	} else {
3860 		last_r2tsn = task->R2TSN;
3861 	}
3862 
3863 	for (i = beg_run; i < last_r2tsn; i++) {
3864 		if (iscsi_send_r2t_recovery(conn, task, i, false) < 0) {
3865 			SPDK_ERRLOG("The r2t_sn=%d of r2t_task=%p is not sent\n", i, task);
3866 		}
3867 	}
3868 	return 0;
3869 }
3870 
3871 /* This function is used to recover the data in packet */
3872 static int
3873 iscsi_handle_recovery_datain(struct spdk_iscsi_conn *conn,
3874 			     struct spdk_iscsi_task *task,
3875 			     struct spdk_iscsi_pdu *pdu, uint32_t beg_run,
3876 			     uint32_t run_length, uint32_t task_tag)
3877 {
3878 	struct spdk_iscsi_pdu *old_pdu, *pdu_temp;
3879 	uint32_t i;
3880 	struct iscsi_bhs_data_in *datain_header;
3881 	uint32_t last_statsn;
3882 
3883 	task = iscsi_task_get_primary(task);
3884 
3885 	SPDK_DEBUGLOG(iscsi, "iscsi_handle_recovery_datain\n");
3886 
3887 	if (beg_run < task->acked_data_sn) {
3888 		SPDK_ERRLOG("ITT: 0x%08x, DATA IN SNACK requests retransmission of"
3889 			    "DATASN: from 0x%08x to 0x%08x but already acked to "
3890 			    "DATASN: 0x%08x protocol error\n",
3891 			    task_tag, beg_run,
3892 			    (beg_run + run_length), (task->acked_data_sn - 1));
3893 
3894 		return iscsi_reject(conn, pdu, ISCSI_REASON_PROTOCOL_ERROR);
3895 	}
3896 
3897 	if (run_length == 0) {
3898 		/* as the DataSN begins at 0 */
3899 		run_length = task->datain_datasn + 1;
3900 	}
3901 
3902 	if ((beg_run + run_length - 1) > task->datain_datasn) {
3903 		SPDK_ERRLOG("Initiator requests BegRun: 0x%08x, RunLength:"
3904 			    "0x%08x greater than maximum DataSN: 0x%08x.\n",
3905 			    beg_run, run_length, task->datain_datasn);
3906 
3907 		return -1;
3908 	} else {
3909 		last_statsn = beg_run + run_length - 1;
3910 	}
3911 
3912 	for (i = beg_run; i <= last_statsn; i++) {
3913 		TAILQ_FOREACH_SAFE(old_pdu, &conn->snack_pdu_list, tailq, pdu_temp) {
3914 			if (old_pdu->bhs.opcode == ISCSI_OP_SCSI_DATAIN) {
3915 				datain_header = (struct iscsi_bhs_data_in *)&old_pdu->bhs;
3916 				if (from_be32(&datain_header->itt) == task_tag &&
3917 				    from_be32(&datain_header->data_sn) == i) {
3918 					TAILQ_REMOVE(&conn->snack_pdu_list, old_pdu, tailq);
3919 					iscsi_conn_write_pdu(conn, old_pdu, old_pdu->cb_fn, old_pdu->cb_arg);
3920 					break;
3921 				}
3922 			}
3923 		}
3924 	}
3925 	return 0;
3926 }
3927 
3928 /* This function is used to handle the status snack */
3929 static int
3930 iscsi_handle_status_snack(struct spdk_iscsi_conn *conn, struct spdk_iscsi_pdu *pdu)
3931 {
3932 	uint32_t beg_run;
3933 	uint32_t run_length;
3934 	struct iscsi_bhs_snack_req *reqh;
3935 	uint32_t i;
3936 	uint32_t last_statsn;
3937 	bool found_pdu;
3938 	struct spdk_iscsi_pdu *old_pdu;
3939 
3940 	reqh = (struct iscsi_bhs_snack_req *)&pdu->bhs;
3941 	beg_run = from_be32(&reqh->beg_run);
3942 	run_length = from_be32(&reqh->run_len);
3943 
3944 	SPDK_DEBUGLOG(iscsi, "beg_run=%d, run_length=%d, conn->StatSN="
3945 		      "%d, conn->exp_statsn=%d\n", beg_run, run_length,
3946 		      conn->StatSN, conn->exp_statsn);
3947 
3948 	if (!beg_run) {
3949 		beg_run = conn->exp_statsn;
3950 	} else if (beg_run < conn->exp_statsn) {
3951 		SPDK_ERRLOG("Got Status SNACK Begrun: 0x%08x, RunLength: 0x%08x "
3952 			    "but already got ExpStatSN: 0x%08x on CID:%hu.\n",
3953 			    beg_run, run_length, conn->StatSN, conn->cid);
3954 
3955 		return iscsi_reject(conn, pdu, ISCSI_REASON_INVALID_PDU_FIELD);
3956 	}
3957 
3958 	last_statsn = (!run_length) ? conn->StatSN : (beg_run + run_length);
3959 
3960 	for (i = beg_run; i < last_statsn; i++) {
3961 		found_pdu = false;
3962 		TAILQ_FOREACH(old_pdu, &conn->snack_pdu_list, tailq) {
3963 			if (from_be32(&old_pdu->bhs.stat_sn) == i) {
3964 				found_pdu = true;
3965 				break;
3966 			}
3967 		}
3968 
3969 		if (!found_pdu) {
3970 			SPDK_ERRLOG("Unable to find StatSN: 0x%08x. For a Status"
3971 				    "SNACK, assuming this is a proactive SNACK "
3972 				    "for an untransmitted StatSN, ignoring.\n",
3973 				    beg_run);
3974 		} else {
3975 			TAILQ_REMOVE(&conn->snack_pdu_list, old_pdu, tailq);
3976 			iscsi_conn_write_pdu(conn, old_pdu, old_pdu->cb_fn, old_pdu->cb_arg);
3977 		}
3978 	}
3979 
3980 	return 0;
3981 }
3982 
3983 /* This function is used to handle the data ack snack */
3984 static int
3985 iscsi_handle_data_ack(struct spdk_iscsi_conn *conn, struct spdk_iscsi_pdu *pdu)
3986 {
3987 	uint32_t transfer_tag;
3988 	uint32_t beg_run;
3989 	uint32_t run_length;
3990 	struct spdk_iscsi_pdu *old_pdu;
3991 	uint32_t old_datasn;
3992 	struct iscsi_bhs_snack_req *reqh;
3993 	struct spdk_iscsi_task *task;
3994 	struct iscsi_bhs_data_in *datain_header;
3995 	struct spdk_iscsi_task *primary;
3996 
3997 	reqh = (struct iscsi_bhs_snack_req *)&pdu->bhs;
3998 	transfer_tag = from_be32(&reqh->ttt);
3999 	beg_run = from_be32(&reqh->beg_run);
4000 	run_length = from_be32(&reqh->run_len);
4001 	task = NULL;
4002 	datain_header = NULL;
4003 
4004 	SPDK_DEBUGLOG(iscsi, "beg_run=%d,transfer_tag=%d,run_len=%d\n",
4005 		      beg_run, transfer_tag, run_length);
4006 
4007 	task = get_scsi_task_from_ttt(conn, transfer_tag);
4008 	if (!task) {
4009 		SPDK_ERRLOG("Data ACK SNACK for TTT: 0x%08x is invalid.\n",
4010 			    transfer_tag);
4011 		goto reject_return;
4012 	}
4013 
4014 	primary = iscsi_task_get_primary(task);
4015 	if ((run_length != 0) || (beg_run < primary->acked_data_sn)) {
4016 		SPDK_ERRLOG("TTT: 0x%08x Data ACK SNACK BegRUN: %d is less than "
4017 			    "the next expected acked DataSN: %d\n",
4018 			    transfer_tag, beg_run, primary->acked_data_sn);
4019 		goto reject_return;
4020 	}
4021 
4022 	primary->acked_data_sn = beg_run;
4023 
4024 	/* To free the pdu */
4025 	TAILQ_FOREACH(old_pdu, &conn->snack_pdu_list, tailq) {
4026 		if (old_pdu->bhs.opcode == ISCSI_OP_SCSI_DATAIN) {
4027 			datain_header = (struct iscsi_bhs_data_in *) &old_pdu->bhs;
4028 			old_datasn = from_be32(&datain_header->data_sn);
4029 			if ((from_be32(&datain_header->ttt) == transfer_tag) &&
4030 			    (old_datasn == beg_run - 1)) {
4031 				TAILQ_REMOVE(&conn->snack_pdu_list, old_pdu, tailq);
4032 				iscsi_conn_free_pdu(conn, old_pdu);
4033 				break;
4034 			}
4035 		}
4036 	}
4037 
4038 	SPDK_DEBUGLOG(iscsi, "Received Data ACK SNACK for TTT: 0x%08x,"
4039 		      " updated acked DataSN to 0x%08x.\n", transfer_tag,
4040 		      (task->acked_data_sn - 1));
4041 
4042 	return 0;
4043 
4044 reject_return:
4045 	return iscsi_reject(conn, pdu, ISCSI_REASON_INVALID_SNACK);
4046 }
4047 
4048 /* This function is used to handle the snack request from the initiator */
4049 static int
4050 iscsi_pdu_hdr_op_snack(struct spdk_iscsi_conn *conn, struct spdk_iscsi_pdu *pdu)
4051 {
4052 	struct iscsi_bhs_snack_req *reqh;
4053 	struct spdk_iscsi_task *task;
4054 	int type;
4055 	uint32_t task_tag;
4056 	uint32_t beg_run;
4057 	uint32_t run_length;
4058 	int rc;
4059 
4060 	if (conn->sess->session_type == SESSION_TYPE_DISCOVERY) {
4061 		SPDK_ERRLOG("ISCSI_OP_SNACK not allowed in  discovery session\n");
4062 		return SPDK_ISCSI_CONNECTION_FATAL;
4063 	}
4064 
4065 	reqh = (struct iscsi_bhs_snack_req *)&pdu->bhs;
4066 	if (!conn->sess->ErrorRecoveryLevel) {
4067 		SPDK_ERRLOG("Got a SNACK request in ErrorRecoveryLevel=0\n");
4068 		return iscsi_reject(conn, pdu, ISCSI_REASON_PROTOCOL_ERROR);
4069 	}
4070 
4071 	type = reqh->flags & ISCSI_FLAG_SNACK_TYPE_MASK;
4072 	SPDK_DEBUGLOG(iscsi, "The value of type is %d\n", type);
4073 
4074 	switch (type) {
4075 	case 0:
4076 		reqh = (struct iscsi_bhs_snack_req *)&pdu->bhs;
4077 		task_tag = from_be32(&reqh->itt);
4078 		beg_run = from_be32(&reqh->beg_run);
4079 		run_length = from_be32(&reqh->run_len);
4080 
4081 		SPDK_DEBUGLOG(iscsi, "beg_run=%d, run_length=%d, "
4082 			      "task_tag=%x, transfer_tag=%u\n", beg_run,
4083 			      run_length, task_tag, from_be32(&reqh->ttt));
4084 
4085 		task = get_scsi_task_from_itt(conn, task_tag,
4086 					      ISCSI_OP_SCSI_DATAIN);
4087 		if (task) {
4088 			return iscsi_handle_recovery_datain(conn, task, pdu,
4089 							    beg_run, run_length, task_tag);
4090 		}
4091 		task = get_scsi_task_from_itt(conn, task_tag, ISCSI_OP_R2T);
4092 		if (task) {
4093 			return iscsi_handle_r2t_snack(conn, task, pdu, beg_run,
4094 						      run_length, task_tag);
4095 		}
4096 		SPDK_ERRLOG("It is Neither datain nor r2t recovery request\n");
4097 		rc = -1;
4098 		break;
4099 	case ISCSI_FLAG_SNACK_TYPE_STATUS:
4100 		rc = iscsi_handle_status_snack(conn, pdu);
4101 		break;
4102 	case ISCSI_FLAG_SNACK_TYPE_DATA_ACK:
4103 		rc = iscsi_handle_data_ack(conn, pdu);
4104 		break;
4105 	case ISCSI_FLAG_SNACK_TYPE_RDATA:
4106 		SPDK_ERRLOG("R-Data SNACK is Not Supported int spdk\n");
4107 		rc = iscsi_reject(conn, pdu, ISCSI_REASON_PROTOCOL_ERROR);
4108 		break;
4109 	default:
4110 		SPDK_ERRLOG("Unknown SNACK type %d, protocol error\n", type);
4111 		rc = iscsi_reject(conn, pdu, ISCSI_REASON_PROTOCOL_ERROR);
4112 		break;
4113 	}
4114 
4115 	return rc;
4116 }
4117 
4118 static int
4119 iscsi_pdu_hdr_op_data(struct spdk_iscsi_conn *conn, struct spdk_iscsi_pdu *pdu)
4120 {
4121 	struct spdk_iscsi_task	*task;
4122 	struct iscsi_bhs_data_out *reqh;
4123 	struct spdk_scsi_lun	*lun_dev;
4124 	struct spdk_mobj	*mobj;
4125 	uint32_t transfer_tag;
4126 	uint32_t task_tag;
4127 	uint32_t transfer_len;
4128 	uint32_t DataSN;
4129 	uint32_t buffer_offset;
4130 	uint32_t len;
4131 	int F_bit;
4132 	int rc;
4133 
4134 	if (conn->sess->session_type == SESSION_TYPE_DISCOVERY) {
4135 		SPDK_ERRLOG("ISCSI_OP_SCSI_DATAOUT not allowed in discovery session\n");
4136 		return SPDK_ISCSI_CONNECTION_FATAL;
4137 	}
4138 
4139 	reqh = (struct iscsi_bhs_data_out *)&pdu->bhs;
4140 	F_bit = !!(reqh->flags & ISCSI_FLAG_FINAL);
4141 	transfer_tag = from_be32(&reqh->ttt);
4142 	task_tag = from_be32(&reqh->itt);
4143 	DataSN = from_be32(&reqh->data_sn);
4144 	buffer_offset = from_be32(&reqh->buffer_offset);
4145 
4146 	if (pdu->data_segment_len > SPDK_ISCSI_MAX_RECV_DATA_SEGMENT_LENGTH) {
4147 		return iscsi_reject(conn, pdu, ISCSI_REASON_PROTOCOL_ERROR);
4148 	}
4149 
4150 	task = get_transfer_task(conn, transfer_tag);
4151 	if (task == NULL) {
4152 		SPDK_ERRLOG("Not found task for transfer_tag=%x\n", transfer_tag);
4153 		return iscsi_reject(conn, pdu, ISCSI_REASON_INVALID_PDU_FIELD);
4154 	}
4155 
4156 	lun_dev = spdk_scsi_dev_get_lun(conn->dev, task->lun_id);
4157 
4158 	if (pdu->data_segment_len > task->desired_data_transfer_length) {
4159 		SPDK_ERRLOG("the dataout pdu data length is larger than the value sent by R2T PDU\n");
4160 		return SPDK_ISCSI_CONNECTION_FATAL;
4161 	}
4162 
4163 	if (task->tag != task_tag) {
4164 		SPDK_ERRLOG("The r2t task tag is %u, and the dataout task tag is %u\n",
4165 			    task->tag, task_tag);
4166 		return iscsi_reject(conn, pdu, ISCSI_REASON_INVALID_PDU_FIELD);
4167 	}
4168 
4169 	if (DataSN != task->r2t_datasn) {
4170 		SPDK_ERRLOG("DataSN(%u) exp=%d error\n", DataSN, task->r2t_datasn);
4171 		if (conn->sess->ErrorRecoveryLevel >= 1) {
4172 			rc = iscsi_send_r2t_recovery(conn, task, task->acked_r2tsn, true);
4173 			if (rc == 0) {
4174 				return 0;
4175 			}
4176 		}
4177 		return iscsi_reject(conn, pdu, ISCSI_REASON_PROTOCOL_ERROR);
4178 	}
4179 
4180 	if (buffer_offset != task->next_expected_r2t_offset) {
4181 		SPDK_ERRLOG("offset(%u) error\n", buffer_offset);
4182 		return SPDK_ISCSI_CONNECTION_FATAL;
4183 	}
4184 
4185 	transfer_len = task->scsi.transfer_len;
4186 	task->current_r2t_length += pdu->data_segment_len;
4187 	task->next_expected_r2t_offset += pdu->data_segment_len;
4188 	task->r2t_datasn++;
4189 
4190 	if (task->current_r2t_length > conn->sess->MaxBurstLength) {
4191 		SPDK_ERRLOG("R2T burst(%u) > MaxBurstLength(%u)\n",
4192 			    task->current_r2t_length,
4193 			    conn->sess->MaxBurstLength);
4194 		return SPDK_ISCSI_CONNECTION_FATAL;
4195 	}
4196 
4197 	if (F_bit) {
4198 		/*
4199 		 * This R2T burst is done. Clear the length before we
4200 		 *  receive a PDU for the next R2t burst.
4201 		 */
4202 		task->current_r2t_length = 0;
4203 	}
4204 
4205 	if (task->next_expected_r2t_offset == transfer_len) {
4206 		task->acked_r2tsn++;
4207 	} else if (F_bit && (task->next_r2t_offset < transfer_len)) {
4208 		task->acked_r2tsn++;
4209 		len = spdk_min(conn->sess->MaxBurstLength,
4210 			       (transfer_len - task->next_r2t_offset));
4211 		rc = iscsi_send_r2t(conn, task, task->next_r2t_offset, len,
4212 				    task->ttt, &task->R2TSN);
4213 		if (rc < 0) {
4214 			SPDK_ERRLOG("iscsi_send_r2t() failed\n");
4215 		}
4216 		task->next_r2t_offset += len;
4217 	}
4218 
4219 	if (lun_dev == NULL) {
4220 		SPDK_DEBUGLOG(iscsi, "LUN %d is removed, reject this PDU.\n",
4221 			      task->lun_id);
4222 		return iscsi_reject(conn, pdu, ISCSI_REASON_PROTOCOL_ERROR);
4223 	} else if (spdk_unlikely(spdk_scsi_lun_get_dif_ctx(lun_dev, &task->scsi, &pdu->dif_ctx))) {
4224 		pdu->dif_insert_or_strip = true;
4225 	}
4226 
4227 	mobj = iscsi_task_get_mobj(task);
4228 	if (mobj == NULL) {
4229 		if (!F_bit && !pdu->dif_insert_or_strip) {
4230 			/* More Data-OUT PDUs will follow in this sequence. Increase the buffer
4231 			 * size up to SPDK_ISCSI_MAX_RECV_DATA_SEGMENT_LENGTH to merge them
4232 			 * into a single subtask.
4233 			 */
4234 			pdu->data_buf_len = spdk_min(task->desired_data_transfer_length,
4235 						     SPDK_ISCSI_MAX_RECV_DATA_SEGMENT_LENGTH);
4236 		}
4237 	} else {
4238 		/* Set up the data buffer from the one saved by the primary task. */
4239 		pdu->mobj[0] = mobj;
4240 		pdu->data = (void *)((uint64_t)mobj->buf + mobj->data_len);
4241 		pdu->data_from_mempool = true;
4242 		pdu->data_buf_len = SPDK_BDEV_BUF_SIZE_WITH_MD(SPDK_ISCSI_MAX_RECV_DATA_SEGMENT_LENGTH);
4243 
4244 		iscsi_task_set_mobj(task, NULL);
4245 	}
4246 
4247 	return 0;
4248 }
4249 
4250 static int
4251 iscsi_submit_write_subtask(struct spdk_iscsi_conn *conn, struct spdk_iscsi_task *task,
4252 			   struct spdk_iscsi_pdu *pdu, struct spdk_mobj *mobj)
4253 {
4254 	struct spdk_iscsi_task *subtask;
4255 
4256 	subtask = iscsi_task_get(conn, task, iscsi_task_cpl);
4257 	if (subtask == NULL) {
4258 		SPDK_ERRLOG("Unable to acquire subtask\n");
4259 		return SPDK_ISCSI_CONNECTION_FATAL;
4260 	}
4261 	subtask->scsi.offset = task->current_data_offset;
4262 	subtask->scsi.length = mobj->data_len;
4263 	iscsi_task_associate_pdu(subtask, pdu);
4264 
4265 	task->current_data_offset += mobj->data_len;
4266 
4267 	if (spdk_likely(!pdu->dif_insert_or_strip)) {
4268 		spdk_scsi_task_set_data(&subtask->scsi, mobj->buf, mobj->data_len);
4269 	} else {
4270 		spdk_scsi_task_set_data(&subtask->scsi, mobj->buf, pdu->data_buf_len);
4271 	}
4272 
4273 	iscsi_queue_task(conn, subtask);
4274 	return 0;
4275 }
4276 
4277 static int
4278 iscsi_pdu_payload_op_data(struct spdk_iscsi_conn *conn, struct spdk_iscsi_pdu *pdu)
4279 {
4280 	struct spdk_iscsi_task *task;
4281 	struct iscsi_bhs_data_out *reqh;
4282 	struct spdk_mobj *mobj;
4283 	uint32_t transfer_tag;
4284 	int F_bit;
4285 	int rc;
4286 
4287 	reqh = (struct iscsi_bhs_data_out *)&pdu->bhs;
4288 	F_bit = !!(reqh->flags & ISCSI_FLAG_FINAL);
4289 	transfer_tag = from_be32(&reqh->ttt);
4290 
4291 	task = get_transfer_task(conn, transfer_tag);
4292 	if (spdk_unlikely(task == NULL)) {
4293 		SPDK_ERRLOG("Not found for transfer_tag=%x\n", transfer_tag);
4294 		return iscsi_reject(conn, pdu, ISCSI_REASON_INVALID_PDU_FIELD);
4295 	}
4296 
4297 	if (spdk_scsi_dev_get_lun(conn->dev, task->lun_id) == NULL) {
4298 		SPDK_DEBUGLOG(iscsi, "LUN %d is removed, reject this PDU.\n",
4299 			      task->lun_id);
4300 		return iscsi_reject(conn, pdu, ISCSI_REASON_PROTOCOL_ERROR);
4301 	}
4302 
4303 	/* If current PDU is final in a sequence, submit all received data,
4304 	 * otherwise, continue aggregation until the first data buffer is full.
4305 	 * We do not use SGL and instead create a subtask per data buffer. Hence further
4306 	 * aggregation does not improve any performance.
4307 	 */
4308 	mobj = pdu->mobj[0];
4309 	assert(mobj != NULL);
4310 
4311 	if (F_bit || mobj->data_len >= SPDK_ISCSI_MAX_RECV_DATA_SEGMENT_LENGTH ||
4312 	    pdu->dif_insert_or_strip) {
4313 		rc = iscsi_submit_write_subtask(conn, task, pdu, mobj);
4314 		if (rc != 0) {
4315 			return rc;
4316 		}
4317 	} else {
4318 		assert(pdu->mobj[1] == NULL);
4319 		iscsi_task_set_mobj(task, mobj);
4320 		pdu->mobj[0] = NULL;
4321 		return 0;
4322 	}
4323 
4324 	mobj = pdu->mobj[1];
4325 	if (mobj == NULL) {
4326 		return 0;
4327 	}
4328 
4329 	assert(pdu->dif_insert_or_strip == false);
4330 	assert(mobj->data_len < SPDK_ISCSI_MAX_RECV_DATA_SEGMENT_LENGTH);
4331 
4332 	if (F_bit) {
4333 		return iscsi_submit_write_subtask(conn, task, pdu, mobj);
4334 	} else {
4335 		iscsi_task_set_mobj(task, mobj);
4336 		pdu->mobj[1] = NULL;
4337 		return 0;
4338 	}
4339 }
4340 
4341 static void
4342 init_login_reject_response(struct spdk_iscsi_pdu *pdu, struct spdk_iscsi_pdu *rsp_pdu)
4343 {
4344 	struct iscsi_bhs_login_rsp *rsph;
4345 
4346 	memset(rsp_pdu, 0, sizeof(struct spdk_iscsi_pdu));
4347 	rsph = (struct iscsi_bhs_login_rsp *)&rsp_pdu->bhs;
4348 	rsph->version_max = ISCSI_VERSION;
4349 	rsph->version_act = ISCSI_VERSION;
4350 	rsph->opcode = ISCSI_OP_LOGIN_RSP;
4351 	rsph->status_class = ISCSI_CLASS_INITIATOR_ERROR;
4352 	rsph->status_detail = ISCSI_LOGIN_INVALID_LOGIN_REQUEST;
4353 	rsph->itt = pdu->bhs.itt;
4354 }
4355 
4356 static void
4357 iscsi_pdu_dump(struct spdk_iscsi_pdu *pdu)
4358 {
4359 	spdk_log_dump(stderr, "PDU", (uint8_t *)&pdu->bhs, ISCSI_BHS_LEN);
4360 }
4361 
4362 /* This function is used to refree the pdu when it is acknowledged */
4363 static void
4364 remove_acked_pdu(struct spdk_iscsi_conn *conn, uint32_t ExpStatSN)
4365 {
4366 	struct spdk_iscsi_pdu *pdu, *pdu_temp;
4367 	uint32_t stat_sn;
4368 
4369 	conn->exp_statsn = spdk_min(ExpStatSN, conn->StatSN);
4370 	TAILQ_FOREACH_SAFE(pdu, &conn->snack_pdu_list, tailq, pdu_temp) {
4371 		stat_sn = from_be32(&pdu->bhs.stat_sn);
4372 		if (spdk_sn32_lt(stat_sn, conn->exp_statsn)) {
4373 			TAILQ_REMOVE(&conn->snack_pdu_list, pdu, tailq);
4374 			iscsi_conn_free_pdu(conn, pdu);
4375 		}
4376 	}
4377 }
4378 
4379 static int
4380 iscsi_update_cmdsn(struct spdk_iscsi_conn *conn, struct spdk_iscsi_pdu *pdu)
4381 {
4382 	int opcode;
4383 	uint32_t ExpStatSN;
4384 	int I_bit;
4385 	struct spdk_iscsi_sess *sess;
4386 	struct iscsi_bhs_scsi_req *reqh;
4387 
4388 	sess = conn->sess;
4389 	if (!sess) {
4390 		SPDK_ERRLOG("Connection has no associated session!\n");
4391 		return SPDK_ISCSI_CONNECTION_FATAL;
4392 	}
4393 
4394 	opcode = pdu->bhs.opcode;
4395 	reqh = (struct iscsi_bhs_scsi_req *)&pdu->bhs;
4396 
4397 	pdu->cmd_sn = from_be32(&reqh->cmd_sn);
4398 
4399 	I_bit = reqh->immediate;
4400 	if (I_bit == 0) {
4401 		if (spdk_sn32_lt(pdu->cmd_sn, sess->ExpCmdSN) ||
4402 		    spdk_sn32_gt(pdu->cmd_sn, sess->MaxCmdSN)) {
4403 			if (sess->session_type == SESSION_TYPE_NORMAL &&
4404 			    opcode != ISCSI_OP_SCSI_DATAOUT) {
4405 				SPDK_ERRLOG("CmdSN(%u) ignore (ExpCmdSN=%u, MaxCmdSN=%u)\n",
4406 					    pdu->cmd_sn, sess->ExpCmdSN, sess->MaxCmdSN);
4407 
4408 				if (sess->ErrorRecoveryLevel >= 1) {
4409 					SPDK_DEBUGLOG(iscsi, "Skip the error in ERL 1 and 2\n");
4410 				} else {
4411 					return SPDK_PDU_FATAL;
4412 				}
4413 			}
4414 		}
4415 	} else if (pdu->cmd_sn != sess->ExpCmdSN) {
4416 		SPDK_ERRLOG("CmdSN(%u) error ExpCmdSN=%u\n", pdu->cmd_sn, sess->ExpCmdSN);
4417 
4418 		if (sess->ErrorRecoveryLevel >= 1) {
4419 			SPDK_DEBUGLOG(iscsi, "Skip the error in ERL 1 and 2\n");
4420 		} else if (opcode != ISCSI_OP_NOPOUT) {
4421 			/*
4422 			 * The Linux initiator does not send valid CmdSNs for
4423 			 *  nopout under heavy load, so do not close the
4424 			 *  connection in that case.
4425 			 */
4426 			return SPDK_ISCSI_CONNECTION_FATAL;
4427 		}
4428 	}
4429 
4430 	ExpStatSN = from_be32(&reqh->exp_stat_sn);
4431 	if (spdk_sn32_gt(ExpStatSN, conn->StatSN)) {
4432 		SPDK_DEBUGLOG(iscsi, "StatSN(%u) advanced\n", ExpStatSN);
4433 		ExpStatSN = conn->StatSN;
4434 	}
4435 
4436 	if (sess->ErrorRecoveryLevel >= 1) {
4437 		remove_acked_pdu(conn, ExpStatSN);
4438 	}
4439 
4440 	if (!I_bit && opcode != ISCSI_OP_SCSI_DATAOUT) {
4441 		sess->ExpCmdSN++;
4442 	}
4443 
4444 	return 0;
4445 }
4446 
4447 static int
4448 iscsi_pdu_hdr_handle(struct spdk_iscsi_conn *conn, struct spdk_iscsi_pdu *pdu)
4449 {
4450 	int opcode;
4451 	int rc;
4452 	struct spdk_iscsi_pdu *rsp_pdu = NULL;
4453 
4454 	if (pdu == NULL) {
4455 		return -1;
4456 	}
4457 
4458 	opcode = pdu->bhs.opcode;
4459 
4460 	SPDK_DEBUGLOG(iscsi, "opcode %x\n", opcode);
4461 
4462 	if (opcode == ISCSI_OP_LOGIN) {
4463 		return iscsi_pdu_hdr_op_login(conn, pdu);
4464 	}
4465 
4466 	/* connection in login phase but receive non-login opcode
4467 	 * return response code 0x020b to initiator.
4468 	 * */
4469 	if (!conn->full_feature && conn->state == ISCSI_CONN_STATE_RUNNING) {
4470 		rsp_pdu = iscsi_get_pdu(conn);
4471 		if (rsp_pdu == NULL) {
4472 			return SPDK_ISCSI_CONNECTION_FATAL;
4473 		}
4474 		init_login_reject_response(pdu, rsp_pdu);
4475 		iscsi_conn_write_pdu(conn, rsp_pdu, iscsi_conn_pdu_generic_complete, NULL);
4476 		SPDK_ERRLOG("Received opcode %d in login phase\n", opcode);
4477 		return SPDK_ISCSI_LOGIN_ERROR_RESPONSE;
4478 	} else if (conn->state == ISCSI_CONN_STATE_INVALID) {
4479 		SPDK_ERRLOG("before Full Feature\n");
4480 		iscsi_pdu_dump(pdu);
4481 		return SPDK_ISCSI_CONNECTION_FATAL;
4482 	}
4483 
4484 	rc = iscsi_update_cmdsn(conn, pdu);
4485 	if (rc != 0) {
4486 		return rc;
4487 	}
4488 
4489 	switch (opcode) {
4490 	case ISCSI_OP_NOPOUT:
4491 		rc = iscsi_pdu_hdr_op_nopout(conn, pdu);
4492 		break;
4493 
4494 	case ISCSI_OP_SCSI:
4495 		rc = iscsi_pdu_hdr_op_scsi(conn, pdu);
4496 		break;
4497 	case ISCSI_OP_TASK:
4498 		rc = iscsi_pdu_hdr_op_task(conn, pdu);
4499 		break;
4500 
4501 	case ISCSI_OP_TEXT:
4502 		rc = iscsi_pdu_hdr_op_text(conn, pdu);
4503 		break;
4504 
4505 	case ISCSI_OP_LOGOUT:
4506 		rc = iscsi_pdu_hdr_op_logout(conn, pdu);
4507 		break;
4508 
4509 	case ISCSI_OP_SCSI_DATAOUT:
4510 		rc = iscsi_pdu_hdr_op_data(conn, pdu);
4511 		break;
4512 
4513 	case ISCSI_OP_SNACK:
4514 		rc = iscsi_pdu_hdr_op_snack(conn, pdu);
4515 		break;
4516 
4517 	default:
4518 		SPDK_ERRLOG("unsupported opcode %x\n", opcode);
4519 		return iscsi_reject(conn, pdu, ISCSI_REASON_PROTOCOL_ERROR);
4520 	}
4521 
4522 	if (rc < 0) {
4523 		SPDK_ERRLOG("processing PDU header (opcode=%x) failed on %s(%s)\n",
4524 			    opcode,
4525 			    conn->target_port != NULL ? spdk_scsi_port_get_name(conn->target_port) : "NULL",
4526 			    conn->initiator_port != NULL ? spdk_scsi_port_get_name(conn->initiator_port) : "NULL");
4527 	}
4528 
4529 	return rc;
4530 }
4531 
4532 static int
4533 iscsi_pdu_payload_handle(struct spdk_iscsi_conn *conn, struct spdk_iscsi_pdu *pdu)
4534 {
4535 	int opcode;
4536 	int rc = 0;
4537 
4538 	opcode = pdu->bhs.opcode;
4539 
4540 	SPDK_DEBUGLOG(iscsi, "opcode %x\n", opcode);
4541 
4542 	switch (opcode) {
4543 	case ISCSI_OP_LOGIN:
4544 		rc = iscsi_pdu_payload_op_login(conn, pdu);
4545 		break;
4546 	case ISCSI_OP_NOPOUT:
4547 		rc = iscsi_pdu_payload_op_nopout(conn, pdu);
4548 		break;
4549 	case ISCSI_OP_SCSI:
4550 		rc = iscsi_pdu_payload_op_scsi(conn, pdu);
4551 		break;
4552 	case ISCSI_OP_TASK:
4553 		break;
4554 	case ISCSI_OP_TEXT:
4555 		rc = iscsi_pdu_payload_op_text(conn, pdu);
4556 		break;
4557 	case ISCSI_OP_LOGOUT:
4558 		break;
4559 	case ISCSI_OP_SCSI_DATAOUT:
4560 		rc = iscsi_pdu_payload_op_data(conn, pdu);
4561 		break;
4562 	case ISCSI_OP_SNACK:
4563 		break;
4564 	default:
4565 		SPDK_ERRLOG("unsupported opcode %x\n", opcode);
4566 		return iscsi_reject(conn, pdu, ISCSI_REASON_PROTOCOL_ERROR);
4567 	}
4568 
4569 	if (rc < 0) {
4570 		SPDK_ERRLOG("processing PDU payload (opcode=%x) failed on %s(%s)\n",
4571 			    opcode,
4572 			    conn->target_port != NULL ? spdk_scsi_port_get_name(conn->target_port) : "NULL",
4573 			    conn->initiator_port != NULL ? spdk_scsi_port_get_name(conn->initiator_port) : "NULL");
4574 	}
4575 
4576 	return rc;
4577 }
4578 
4579 /* Return zero if completed to read payload, positive number if still in progress,
4580  * or negative number if any error.
4581  */
4582 static int
4583 iscsi_pdu_payload_read(struct spdk_iscsi_conn *conn, struct spdk_iscsi_pdu *pdu)
4584 {
4585 	struct spdk_mempool *pool;
4586 	struct spdk_mobj *mobj;
4587 	uint32_t data_len;
4588 	uint32_t read_len;
4589 	uint32_t crc32c;
4590 	int rc;
4591 
4592 	data_len = pdu->data_segment_len;
4593 
4594 	mobj = pdu->mobj[0];
4595 	if (mobj == NULL) {
4596 		if (pdu->data_buf_len <= iscsi_get_max_immediate_data_size()) {
4597 			pool = g_iscsi.pdu_immediate_data_pool;
4598 			pdu->data_buf_len = SPDK_BDEV_BUF_SIZE_WITH_MD(iscsi_get_max_immediate_data_size());
4599 		} else if (pdu->data_buf_len <= SPDK_ISCSI_MAX_RECV_DATA_SEGMENT_LENGTH) {
4600 			pool = g_iscsi.pdu_data_out_pool;
4601 			pdu->data_buf_len = SPDK_BDEV_BUF_SIZE_WITH_MD(SPDK_ISCSI_MAX_RECV_DATA_SEGMENT_LENGTH);
4602 		} else {
4603 			SPDK_ERRLOG("Data(%d) > MaxSegment(%d)\n",
4604 				    data_len, SPDK_ISCSI_MAX_RECV_DATA_SEGMENT_LENGTH);
4605 			return -1;
4606 		}
4607 		mobj = iscsi_datapool_get(pool);
4608 		if (mobj == NULL) {
4609 			return 1;
4610 		}
4611 		pdu->mobj[0] = mobj;
4612 		pdu->data = mobj->buf;
4613 		pdu->data_from_mempool = true;
4614 	} else if (mobj->data_len == SPDK_ISCSI_MAX_RECV_DATA_SEGMENT_LENGTH) {
4615 		/* The first data buffer ran out. Allocate the second data buffer and
4616 		 * continue reading the data segment.
4617 		 */
4618 		assert(pdu->mobj[1] == NULL);
4619 		assert(pdu->data_from_mempool == true);
4620 		assert(!pdu->dif_insert_or_strip);
4621 
4622 		if (conn->data_digest) {
4623 			_iscsi_pdu_calc_data_digest(pdu);
4624 		}
4625 		mobj = iscsi_datapool_get(g_iscsi.pdu_data_out_pool);
4626 		if (mobj == NULL) {
4627 			return 1;
4628 		}
4629 		pdu->mobj[1] = mobj;
4630 		pdu->data = mobj->buf;
4631 		pdu->data_offset = pdu->data_valid_bytes;
4632 		pdu->data_buf_len = SPDK_BDEV_BUF_SIZE_WITH_MD(SPDK_ISCSI_MAX_RECV_DATA_SEGMENT_LENGTH);
4633 	}
4634 
4635 	/* copy the actual data into local buffer */
4636 	read_len = spdk_min(data_len - pdu->data_valid_bytes,
4637 			    SPDK_ISCSI_MAX_RECV_DATA_SEGMENT_LENGTH - mobj->data_len);
4638 	if (read_len > 0) {
4639 		rc = iscsi_conn_read_data_segment(conn,
4640 						  pdu,
4641 						  pdu->data_valid_bytes - pdu->data_offset,
4642 						  read_len);
4643 		if (rc < 0) {
4644 			return rc;
4645 		}
4646 
4647 		mobj->data_len += rc;
4648 		pdu->data_valid_bytes += rc;
4649 		if (pdu->data_valid_bytes < data_len) {
4650 			return 1;
4651 		}
4652 	}
4653 
4654 	/* copy out the data digest */
4655 	if (conn->data_digest &&
4656 	    pdu->ddigest_valid_bytes < ISCSI_DIGEST_LEN) {
4657 		rc = iscsi_conn_read_data(conn,
4658 					  ISCSI_DIGEST_LEN - pdu->ddigest_valid_bytes,
4659 					  pdu->data_digest + pdu->ddigest_valid_bytes);
4660 		if (rc < 0) {
4661 			return rc;
4662 		}
4663 
4664 		pdu->ddigest_valid_bytes += rc;
4665 		if (pdu->ddigest_valid_bytes < ISCSI_DIGEST_LEN) {
4666 			return 1;
4667 		}
4668 	}
4669 
4670 	/* check data digest */
4671 	if (conn->data_digest) {
4672 		_iscsi_pdu_calc_data_digest(pdu);
4673 		crc32c = _iscsi_pdu_finalize_data_digest(pdu);
4674 		rc = MATCH_DIGEST_WORD(pdu->data_digest, crc32c);
4675 		if (rc == 0) {
4676 			SPDK_ERRLOG("data digest error (%s)\n", conn->initiator_name);
4677 			return -1;
4678 		}
4679 	}
4680 
4681 	return 0;
4682 }
4683 
4684 static int
4685 iscsi_read_pdu(struct spdk_iscsi_conn *conn)
4686 {
4687 	enum iscsi_pdu_recv_state prev_state;
4688 	struct spdk_iscsi_pdu *pdu;
4689 	uint32_t crc32c;
4690 	int ahs_len;
4691 	int rc;
4692 
4693 	do {
4694 		prev_state = conn->pdu_recv_state;
4695 		pdu = conn->pdu_in_progress;
4696 
4697 		switch (conn->pdu_recv_state) {
4698 		case ISCSI_PDU_RECV_STATE_AWAIT_PDU_READY:
4699 			assert(conn->pdu_in_progress == NULL);
4700 
4701 			conn->pdu_in_progress = iscsi_get_pdu(conn);
4702 			if (conn->pdu_in_progress == NULL) {
4703 				return SPDK_ISCSI_CONNECTION_FATAL;
4704 			}
4705 			conn->pdu_recv_state = ISCSI_PDU_RECV_STATE_AWAIT_PDU_HDR;
4706 			break;
4707 		case ISCSI_PDU_RECV_STATE_AWAIT_PDU_HDR:
4708 			if (pdu->bhs_valid_bytes < ISCSI_BHS_LEN) {
4709 				rc = iscsi_conn_read_data(conn,
4710 							  ISCSI_BHS_LEN - pdu->bhs_valid_bytes,
4711 							  (uint8_t *)&pdu->bhs + pdu->bhs_valid_bytes);
4712 				if (rc < 0) {
4713 					conn->pdu_recv_state = ISCSI_PDU_RECV_STATE_ERROR;
4714 					break;
4715 				}
4716 				pdu->bhs_valid_bytes += rc;
4717 				if (pdu->bhs_valid_bytes < ISCSI_BHS_LEN) {
4718 					return 0;
4719 				}
4720 			}
4721 
4722 			/* conn->is_logged_out must be checked after completing to process
4723 			 * logout request, i.e., before processing PDU header in this state
4724 			 * machine, otherwise logout response may not be sent to initiator
4725 			 * and initiator may get logout timeout.
4726 			 */
4727 			if (spdk_unlikely(conn->is_logged_out)) {
4728 				SPDK_DEBUGLOG(iscsi, "pdu received after logout\n");
4729 				conn->pdu_recv_state = ISCSI_PDU_RECV_STATE_ERROR;
4730 				break;
4731 			}
4732 
4733 			pdu->data_segment_len = ISCSI_ALIGN(DGET24(pdu->bhs.data_segment_len));
4734 			pdu->data_buf_len = pdu->data_segment_len;
4735 
4736 			/* AHS */
4737 			ahs_len = pdu->bhs.total_ahs_len * 4;
4738 			if (ahs_len > ISCSI_AHS_LEN) {
4739 				SPDK_DEBUGLOG(iscsi, "pdu ahs length %d is invalid\n", ahs_len);
4740 				conn->pdu_recv_state = ISCSI_PDU_RECV_STATE_ERROR;
4741 				break;
4742 			}
4743 
4744 			if (pdu->ahs_valid_bytes < ahs_len) {
4745 				rc = iscsi_conn_read_data(conn,
4746 							  ahs_len - pdu->ahs_valid_bytes,
4747 							  pdu->ahs + pdu->ahs_valid_bytes);
4748 				if (rc < 0) {
4749 					conn->pdu_recv_state = ISCSI_PDU_RECV_STATE_ERROR;
4750 					break;
4751 				}
4752 
4753 				pdu->ahs_valid_bytes += rc;
4754 				if (pdu->ahs_valid_bytes < ahs_len) {
4755 					return 0;
4756 				}
4757 			}
4758 
4759 			/* Header Digest */
4760 			if (conn->header_digest &&
4761 			    pdu->hdigest_valid_bytes < ISCSI_DIGEST_LEN) {
4762 				rc = iscsi_conn_read_data(conn,
4763 							  ISCSI_DIGEST_LEN - pdu->hdigest_valid_bytes,
4764 							  pdu->header_digest + pdu->hdigest_valid_bytes);
4765 				if (rc < 0) {
4766 					conn->pdu_recv_state = ISCSI_PDU_RECV_STATE_ERROR;
4767 					break;
4768 				}
4769 
4770 				pdu->hdigest_valid_bytes += rc;
4771 				if (pdu->hdigest_valid_bytes < ISCSI_DIGEST_LEN) {
4772 					return 0;
4773 				}
4774 			}
4775 
4776 			if (conn->header_digest) {
4777 				crc32c = iscsi_pdu_calc_header_digest(pdu);
4778 				rc = MATCH_DIGEST_WORD(pdu->header_digest, crc32c);
4779 				if (rc == 0) {
4780 					SPDK_ERRLOG("header digest error (%s)\n", conn->initiator_name);
4781 					conn->pdu_recv_state = ISCSI_PDU_RECV_STATE_ERROR;
4782 					break;
4783 				}
4784 			}
4785 
4786 			rc = iscsi_pdu_hdr_handle(conn, pdu);
4787 			if (rc < 0) {
4788 				SPDK_ERRLOG("Critical error is detected. Close the connection\n");
4789 				conn->pdu_recv_state = ISCSI_PDU_RECV_STATE_ERROR;
4790 				break;
4791 			}
4792 
4793 			conn->pdu_recv_state = ISCSI_PDU_RECV_STATE_AWAIT_PDU_PAYLOAD;
4794 			break;
4795 		case ISCSI_PDU_RECV_STATE_AWAIT_PDU_PAYLOAD:
4796 			if (pdu->data_segment_len != 0) {
4797 				rc = iscsi_pdu_payload_read(conn, pdu);
4798 				if (rc > 0) {
4799 					return 0;
4800 				} else if (rc < 0) {
4801 					conn->pdu_recv_state = ISCSI_PDU_RECV_STATE_ERROR;
4802 					break;
4803 				}
4804 			}
4805 
4806 			/* All data for this PDU has now been read from the socket. */
4807 			spdk_trace_record(TRACE_ISCSI_READ_PDU, conn->id, pdu->data_valid_bytes,
4808 					  (uintptr_t)pdu, pdu->bhs.opcode);
4809 
4810 			if (!pdu->is_rejected) {
4811 				rc = iscsi_pdu_payload_handle(conn, pdu);
4812 			} else {
4813 				rc = 0;
4814 			}
4815 			if (rc == 0) {
4816 				spdk_trace_record(TRACE_ISCSI_TASK_EXECUTED, 0, 0, (uintptr_t)pdu, 0);
4817 				iscsi_put_pdu(pdu);
4818 				conn->pdu_in_progress = NULL;
4819 				conn->pdu_recv_state = ISCSI_PDU_RECV_STATE_AWAIT_PDU_READY;
4820 				return 1;
4821 			} else {
4822 				conn->pdu_recv_state = ISCSI_PDU_RECV_STATE_ERROR;
4823 			}
4824 			break;
4825 		case ISCSI_PDU_RECV_STATE_ERROR:
4826 			return SPDK_ISCSI_CONNECTION_FATAL;
4827 		default:
4828 			assert(false);
4829 			SPDK_ERRLOG("code should not come here\n");
4830 			break;
4831 		}
4832 	} while (prev_state != conn->pdu_recv_state);
4833 
4834 	return 0;
4835 }
4836 
4837 #define GET_PDU_LOOP_COUNT	16
4838 
4839 int
4840 iscsi_handle_incoming_pdus(struct spdk_iscsi_conn *conn)
4841 {
4842 	int i, rc;
4843 
4844 	/* Read new PDUs from network */
4845 	for (i = 0; i < GET_PDU_LOOP_COUNT; i++) {
4846 		rc = iscsi_read_pdu(conn);
4847 		if (rc == 0) {
4848 			break;
4849 		} else if (rc < 0) {
4850 			return rc;
4851 		}
4852 
4853 		if (conn->is_stopped) {
4854 			break;
4855 		}
4856 	}
4857 
4858 	return i;
4859 }
4860