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