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