xref: /spdk/lib/nvmf/tcp.c (revision 310fc0b5d56fa43b80af869270fcf2758df9c92d)
1 /*-
2  *   BSD LICENSE
3  *
4  *   Copyright (c) Intel Corporation.
5  *   All rights reserved.
6  *
7  *   Redistribution and use in source and binary forms, with or without
8  *   modification, are permitted provided that the following conditions
9  *   are met:
10  *
11  *     * Redistributions of source code must retain the above copyright
12  *       notice, this list of conditions and the following disclaimer.
13  *     * Redistributions in binary form must reproduce the above copyright
14  *       notice, this list of conditions and the following disclaimer in
15  *       the documentation and/or other materials provided with the
16  *       distribution.
17  *     * Neither the name of Intel Corporation nor the names of its
18  *       contributors may be used to endorse or promote products derived
19  *       from this software without specific prior written permission.
20  *
21  *   THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
22  *   "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
23  *   LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
24  *   A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
25  *   OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
26  *   SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
27  *   LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
28  *   DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
29  *   THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
30  *   (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
31  *   OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
32  */
33 
34 #include "spdk/stdinc.h"
35 #include "spdk/crc32.h"
36 #include "spdk/endian.h"
37 #include "spdk/assert.h"
38 #include "spdk/thread.h"
39 #include "spdk/nvmf.h"
40 #include "spdk/nvmf_spec.h"
41 #include "spdk/sock.h"
42 #include "spdk/string.h"
43 #include "spdk/trace.h"
44 #include "spdk/util.h"
45 
46 #include "nvmf_internal.h"
47 #include "transport.h"
48 
49 #include "spdk_internal/log.h"
50 #include "spdk_internal/nvme_tcp.h"
51 
52 #define NVMF_TCP_MAX_ACCEPT_SOCK_ONE_TIME 16
53 
54 #define NVMF_TCP_PDU_MAX_H2C_DATA_SIZE	131072
55 #define NVMF_TCP_PDU_MAX_C2H_DATA_SIZE	131072
56 #define NVMF_TCP_QPAIR_MAX_C2H_PDU_NUM  64  /* Maximal c2h_data pdu number for ecah tqpair */
57 
58 /* spdk nvmf related structure */
59 enum spdk_nvmf_tcp_req_state {
60 
61 	/* The request is not currently in use */
62 	TCP_REQUEST_STATE_FREE = 0,
63 
64 	/* Initial state when request first received */
65 	TCP_REQUEST_STATE_NEW,
66 
67 	/* The request is queued until a data buffer is available. */
68 	TCP_REQUEST_STATE_NEED_BUFFER,
69 
70 	/* The request is currently transferring data from the host to the controller. */
71 	TCP_REQUEST_STATE_TRANSFERRING_HOST_TO_CONTROLLER,
72 
73 	/* The request is ready to execute at the block device */
74 	TCP_REQUEST_STATE_READY_TO_EXECUTE,
75 
76 	/* The request is currently executing at the block device */
77 	TCP_REQUEST_STATE_EXECUTING,
78 
79 	/* The request finished executing at the block device */
80 	TCP_REQUEST_STATE_EXECUTED,
81 
82 	/* The request is ready to send a completion */
83 	TCP_REQUEST_STATE_READY_TO_COMPLETE,
84 
85 	/* The request is currently transferring final pdus from the controller to the host. */
86 	TCP_REQUEST_STATE_TRANSFERRING_CONTROLLER_TO_HOST,
87 
88 	/* The request completed and can be marked free. */
89 	TCP_REQUEST_STATE_COMPLETED,
90 
91 	/* Terminator */
92 	TCP_REQUEST_NUM_STATES,
93 };
94 
95 static const char *spdk_nvmf_tcp_term_req_fes_str[] = {
96 	"Invalid PDU Header Field",
97 	"PDU Sequence Error",
98 	"Header Digiest Error",
99 	"Data Transfer Out of Range",
100 	"R2T Limit Exceeded",
101 	"Unsupported parameter",
102 };
103 
104 #define OBJECT_NVMF_TCP_IO				0x80
105 
106 #define TRACE_GROUP_NVMF_TCP				0x5
107 #define TRACE_TCP_REQUEST_STATE_NEW					SPDK_TPOINT_ID(TRACE_GROUP_NVMF_TCP, 0x0)
108 #define TRACE_TCP_REQUEST_STATE_NEED_BUFFER				SPDK_TPOINT_ID(TRACE_GROUP_NVMF_TCP, 0x1)
109 #define TRACE_TCP_REQUEST_STATE_TRANSFERRING_HOST_TO_CONTROLLER		SPDK_TPOINT_ID(TRACE_GROUP_NVMF_TCP, 0x2)
110 #define TRACE_TCP_REQUEST_STATE_READY_TO_EXECUTE			SPDK_TPOINT_ID(TRACE_GROUP_NVMF_TCP, 0x3)
111 #define TRACE_TCP_REQUEST_STATE_EXECUTING				SPDK_TPOINT_ID(TRACE_GROUP_NVMF_TCP, 0x4)
112 #define TRACE_TCP_REQUEST_STATE_EXECUTED				SPDK_TPOINT_ID(TRACE_GROUP_NVMF_TCP, 0x5)
113 #define TRACE_TCP_REQUEST_STATE_READY_TO_COMPLETE			SPDK_TPOINT_ID(TRACE_GROUP_NVMF_TCP, 0x6)
114 #define TRACE_TCP_REQUEST_STATE_TRANSFERRING_CONTROLLER_TO_HOST		SPDK_TPOINT_ID(TRACE_GROUP_NVMF_TCP, 0x7)
115 #define TRACE_TCP_REQUEST_STATE_COMPLETED				SPDK_TPOINT_ID(TRACE_GROUP_NVMF_TCP, 0x8)
116 #define TRACE_TCP_FLUSH_WRITEBUF_START					SPDK_TPOINT_ID(TRACE_GROUP_NVMF_TCP, 0x9)
117 #define TRACE_TCP_FLUSH_WRITEBUF_DONE					SPDK_TPOINT_ID(TRACE_GROUP_NVMF_TCP, 0xA)
118 #define TRACE_TCP_READ_FROM_SOCKET_DONE					SPDK_TPOINT_ID(TRACE_GROUP_NVMF_TCP, 0xB)
119 
120 SPDK_TRACE_REGISTER_FN(nvmf_tcp_trace, "nvmf_tcp", TRACE_GROUP_NVMF_TCP)
121 {
122 	spdk_trace_register_object(OBJECT_NVMF_TCP_IO, 'r');
123 	spdk_trace_register_description("TCP_REQ_NEW",
124 					TRACE_TCP_REQUEST_STATE_NEW,
125 					OWNER_NONE, OBJECT_NVMF_TCP_IO, 1, 1, "");
126 	spdk_trace_register_description("TCP_REQ_NEED_BUFFER",
127 					TRACE_TCP_REQUEST_STATE_NEED_BUFFER,
128 					OWNER_NONE, OBJECT_NVMF_TCP_IO, 0, 1, "");
129 	spdk_trace_register_description("TCP_REQ_TX_H_TO_C",
130 					TRACE_TCP_REQUEST_STATE_TRANSFERRING_HOST_TO_CONTROLLER,
131 					OWNER_NONE, OBJECT_NVMF_TCP_IO, 0, 1, "");
132 	spdk_trace_register_description("TCP_REQ_RDY_TO_EXECUTE",
133 					TRACE_TCP_REQUEST_STATE_READY_TO_EXECUTE,
134 					OWNER_NONE, OBJECT_NVMF_TCP_IO, 0, 1, "");
135 	spdk_trace_register_description("TCP_REQ_EXECUTING",
136 					TRACE_TCP_REQUEST_STATE_EXECUTING,
137 					OWNER_NONE, OBJECT_NVMF_TCP_IO, 0, 1, "");
138 	spdk_trace_register_description("TCP_REQ_EXECUTED",
139 					TRACE_TCP_REQUEST_STATE_EXECUTED,
140 					OWNER_NONE, OBJECT_NVMF_TCP_IO, 0, 1, "");
141 	spdk_trace_register_description("TCP_REQ_RDY_TO_COMPLETE",
142 					TRACE_TCP_REQUEST_STATE_READY_TO_COMPLETE,
143 					OWNER_NONE, OBJECT_NVMF_TCP_IO, 0, 1, "");
144 	spdk_trace_register_description("TCP_REQ_TRANSFER_C2H",
145 					TRACE_TCP_REQUEST_STATE_TRANSFERRING_CONTROLLER_TO_HOST,
146 					OWNER_NONE, OBJECT_NVMF_TCP_IO, 0, 1, "");
147 	spdk_trace_register_description("TCP_REQ_COMPLETED",
148 					TRACE_TCP_REQUEST_STATE_COMPLETED,
149 					OWNER_NONE, OBJECT_NVMF_TCP_IO, 0, 1, "");
150 	spdk_trace_register_description("TCP_WRITE_START",
151 					TRACE_TCP_FLUSH_WRITEBUF_START,
152 					OWNER_NONE, OBJECT_NONE, 0, 0, "");
153 	spdk_trace_register_description("TCP_WRITE_DONE",
154 					TRACE_TCP_FLUSH_WRITEBUF_DONE,
155 					OWNER_NONE, OBJECT_NONE, 0, 0, "");
156 	spdk_trace_register_description("TCP_READ_DONE",
157 					TRACE_TCP_READ_FROM_SOCKET_DONE,
158 					OWNER_NONE, OBJECT_NONE, 0, 0, "");
159 }
160 
161 struct spdk_nvmf_tcp_req  {
162 	struct spdk_nvmf_request		req;
163 	struct spdk_nvme_cpl			rsp;
164 	struct spdk_nvme_cmd			cmd;
165 
166 	/* In-capsule data buffer */
167 	uint8_t					*buf;
168 
169 	bool					data_from_pool;
170 	void					*buffers[SPDK_NVMF_MAX_SGL_ENTRIES];
171 
172 	/* transfer_tag */
173 	uint16_t				ttag;
174 
175 	/*
176 	 * next_expected_r2t_offset is used when we receive the h2c_data PDU.
177 	 */
178 	uint32_t				next_expected_r2t_offset;
179 	uint32_t				r2tl_remain;
180 
181 	/*
182 	 * c2h_data_offset is used when we send the c2h_data PDU.
183 	 */
184 	uint32_t				c2h_data_offset;
185 	uint32_t				c2h_data_pdu_num;
186 
187 	enum spdk_nvmf_tcp_req_state		state;
188 	bool					has_incapsule_data;
189 
190 	TAILQ_ENTRY(spdk_nvmf_tcp_req)		link;
191 	TAILQ_ENTRY(spdk_nvmf_tcp_req)		state_link;
192 };
193 
194 struct spdk_nvmf_tcp_qpair {
195 	struct spdk_nvmf_qpair			qpair;
196 	struct spdk_nvmf_tcp_poll_group		*group;
197 	struct spdk_nvmf_tcp_port		*port;
198 	struct spdk_sock			*sock;
199 	struct spdk_poller			*flush_poller;
200 
201 	enum nvme_tcp_pdu_recv_state		recv_state;
202 	enum nvme_tcp_qpair_state		state;
203 
204 	struct nvme_tcp_pdu			pdu_in_progress;
205 
206 	TAILQ_HEAD(, nvme_tcp_pdu)		send_queue;
207 	TAILQ_HEAD(, nvme_tcp_pdu)		free_queue;
208 
209 	struct nvme_tcp_pdu			*pdu;
210 	struct nvme_tcp_pdu			*pdu_pool;
211 	uint16_t				free_pdu_num;
212 
213 	/* Queues to track the requests in all states */
214 	TAILQ_HEAD(, spdk_nvmf_tcp_req)		state_queue[TCP_REQUEST_NUM_STATES];
215 	/* Number of requests in each state */
216 	int32_t					state_cntr[TCP_REQUEST_NUM_STATES];
217 
218 	TAILQ_HEAD(, spdk_nvmf_tcp_req)		queued_c2h_data_tcp_req;
219 
220 	uint8_t					cpda;
221 
222 	/* Array of size "max_queue_depth * InCapsuleDataSize" containing
223 	 * buffers to be used for in capsule data.
224 	 */
225 	void					*buf;
226 	void					*bufs;
227 	struct spdk_nvmf_tcp_req		*req;
228 	struct spdk_nvmf_tcp_req		*reqs;
229 
230 	bool					host_hdgst_enable;
231 	bool					host_ddgst_enable;
232 
233 
234 	/* The maximum number of I/O outstanding on this connection at one time */
235 	uint16_t				max_queue_depth;
236 
237 
238 	/** Specifies the maximum number of PDU-Data bytes per H2C Data Transfer PDU */
239 	uint32_t				maxh2cdata;
240 
241 	uint32_t				c2h_data_pdu_cnt;
242 
243 	/* IP address */
244 	char					initiator_addr[SPDK_NVMF_TRADDR_MAX_LEN];
245 	char					target_addr[SPDK_NVMF_TRADDR_MAX_LEN];
246 
247 	/* IP port */
248 	uint16_t				initiator_port;
249 	uint16_t				target_port;
250 
251 	/* Timer used to destroy qpair after detecting transport error issue if initiator does
252 	 *  not close the connection.
253 	 */
254 	struct spdk_poller			*timeout_poller;
255 
256 	TAILQ_ENTRY(spdk_nvmf_tcp_qpair)	link;
257 };
258 
259 struct spdk_nvmf_tcp_poll_group {
260 	struct spdk_nvmf_transport_poll_group	group;
261 	struct spdk_sock_group			*sock_group;
262 
263 	/* Requests that are waiting to obtain a data buffer */
264 	TAILQ_HEAD(, spdk_nvmf_tcp_req)		pending_data_buf_queue;
265 
266 	TAILQ_HEAD(, spdk_nvmf_tcp_qpair)	qpairs;
267 };
268 
269 struct spdk_nvmf_tcp_port {
270 	struct spdk_nvme_transport_id		trid;
271 	struct spdk_sock			*listen_sock;
272 	uint32_t				ref;
273 	TAILQ_ENTRY(spdk_nvmf_tcp_port)		link;
274 };
275 
276 struct spdk_nvmf_tcp_transport {
277 	struct spdk_nvmf_transport		transport;
278 
279 	pthread_mutex_t				lock;
280 
281 	TAILQ_HEAD(, spdk_nvmf_tcp_port)	ports;
282 };
283 
284 static void spdk_nvmf_tcp_qpair_process_pending(struct spdk_nvmf_tcp_transport *ttransport,
285 		struct spdk_nvmf_tcp_qpair *tqpair);
286 static bool spdk_nvmf_tcp_req_process(struct spdk_nvmf_tcp_transport *ttransport,
287 				      struct spdk_nvmf_tcp_req *tcp_req);
288 static void spdk_nvmf_tcp_handle_pending_c2h_data_queue(struct spdk_nvmf_tcp_qpair *tqpair);
289 
290 static void
291 spdk_nvmf_tcp_req_set_state(struct spdk_nvmf_tcp_req *tcp_req,
292 			    enum spdk_nvmf_tcp_req_state state)
293 {
294 	struct spdk_nvmf_qpair *qpair;
295 	struct spdk_nvmf_tcp_qpair *tqpair;
296 
297 	qpair = tcp_req->req.qpair;
298 	tqpair = SPDK_CONTAINEROF(qpair, struct spdk_nvmf_tcp_qpair, qpair);
299 
300 	TAILQ_REMOVE(&tqpair->state_queue[tcp_req->state], tcp_req, state_link);
301 	tqpair->state_cntr[tcp_req->state]--;
302 	assert(tqpair->state_cntr[tcp_req->state] >= 0);
303 
304 	TAILQ_INSERT_TAIL(&tqpair->state_queue[state], tcp_req, state_link);
305 	tqpair->state_cntr[state]++;
306 
307 	tcp_req->state = state;
308 }
309 
310 static struct nvme_tcp_pdu *
311 spdk_nvmf_tcp_pdu_get(struct spdk_nvmf_tcp_qpair *tqpair)
312 {
313 	struct nvme_tcp_pdu *pdu;
314 
315 	pdu = TAILQ_FIRST(&tqpair->free_queue);
316 	if (!pdu) {
317 		SPDK_ERRLOG("Unable to get PDU for tqpair=%p\n", tqpair);
318 		abort();
319 		return NULL;
320 	}
321 
322 	tqpair->free_pdu_num--;
323 	TAILQ_REMOVE(&tqpair->free_queue, pdu, tailq);
324 	memset(pdu, 0, sizeof(*pdu));
325 	pdu->ref = 1;
326 
327 	return pdu;
328 }
329 
330 static void
331 spdk_nvmf_tcp_pdu_put(struct spdk_nvmf_tcp_qpair *tqpair, struct nvme_tcp_pdu *pdu)
332 {
333 	if (!pdu) {
334 		return;
335 	}
336 
337 	assert(pdu->ref > 0);
338 
339 	pdu->ref--;
340 	if (pdu->ref == 0) {
341 		tqpair->free_pdu_num++;
342 		TAILQ_INSERT_HEAD(&tqpair->free_queue, pdu, tailq);
343 	}
344 }
345 
346 static struct spdk_nvmf_tcp_req *
347 spdk_nvmf_tcp_req_get(struct spdk_nvmf_tcp_qpair *tqpair)
348 {
349 	struct spdk_nvmf_tcp_req *tcp_req;
350 
351 	tcp_req = TAILQ_FIRST(&tqpair->state_queue[TCP_REQUEST_STATE_FREE]);
352 	if (!tcp_req) {
353 		SPDK_ERRLOG("Cannot allocate tcp_req on tqpair=%p\n", tqpair);
354 		return NULL;
355 	}
356 
357 	memset(&tcp_req->cmd, 0, sizeof(tcp_req->cmd));
358 	memset(&tcp_req->rsp, 0, sizeof(tcp_req->rsp));
359 	tcp_req->next_expected_r2t_offset = 0;
360 	tcp_req->r2tl_remain = 0;
361 	tcp_req->c2h_data_offset = 0;
362 	tcp_req->has_incapsule_data = false;
363 
364 	spdk_nvmf_tcp_req_set_state(tcp_req, TCP_REQUEST_STATE_NEW);
365 	return tcp_req;
366 }
367 
368 static void
369 nvmf_tcp_request_free(struct spdk_nvmf_tcp_req *tcp_req)
370 {
371 	struct spdk_nvmf_tcp_transport *ttransport;
372 
373 	if (!tcp_req) {
374 		return;
375 	}
376 
377 	SPDK_DEBUGLOG(SPDK_LOG_NVMF_TCP, "tcp_req=%p will be freed\n", tcp_req);
378 	ttransport = SPDK_CONTAINEROF(tcp_req->req.qpair->transport,
379 				      struct spdk_nvmf_tcp_transport, transport);
380 	spdk_nvmf_tcp_req_set_state(tcp_req, TCP_REQUEST_STATE_COMPLETED);
381 	spdk_nvmf_tcp_req_process(ttransport, tcp_req);
382 }
383 
384 static int
385 spdk_nvmf_tcp_req_free(struct spdk_nvmf_request *req)
386 {
387 	struct spdk_nvmf_tcp_req *tcp_req = SPDK_CONTAINEROF(req, struct spdk_nvmf_tcp_req, req);
388 
389 	nvmf_tcp_request_free(tcp_req);
390 
391 	return 0;
392 }
393 
394 static void
395 spdk_nvmf_tcp_drain_state_queue(struct spdk_nvmf_tcp_qpair *tqpair,
396 				enum spdk_nvmf_tcp_req_state state)
397 {
398 	struct spdk_nvmf_tcp_req *tcp_req, *req_tmp;
399 
400 	TAILQ_FOREACH_SAFE(tcp_req, &tqpair->state_queue[state], state_link, req_tmp) {
401 		nvmf_tcp_request_free(tcp_req);
402 	}
403 }
404 
405 static void
406 spdk_nvmf_tcp_cleanup_all_states(struct spdk_nvmf_tcp_qpair *tqpair)
407 {
408 	struct spdk_nvmf_tcp_req *tcp_req, *req_tmp;
409 	struct nvme_tcp_pdu *pdu, *tmp_pdu;
410 
411 	/* Free the pdus in the send_queue */
412 	TAILQ_FOREACH_SAFE(pdu, &tqpair->send_queue, tailq, tmp_pdu) {
413 		TAILQ_REMOVE(&tqpair->send_queue, pdu, tailq);
414 		/* Also check the pdu type, we need to calculte the c2h_data_pdu_cnt later */
415 		if (pdu->hdr.common.pdu_type == SPDK_NVME_TCP_PDU_TYPE_C2H_DATA) {
416 			assert(tqpair->c2h_data_pdu_cnt > 0);
417 			tqpair->c2h_data_pdu_cnt--;
418 		}
419 		spdk_nvmf_tcp_pdu_put(tqpair, pdu);
420 	}
421 
422 	TAILQ_FOREACH_SAFE(tcp_req, &tqpair->queued_c2h_data_tcp_req, link, req_tmp) {
423 		TAILQ_REMOVE(&tqpair->queued_c2h_data_tcp_req, tcp_req, link);
424 	}
425 	spdk_nvmf_tcp_drain_state_queue(tqpair, TCP_REQUEST_STATE_TRANSFERRING_CONTROLLER_TO_HOST);
426 
427 	spdk_nvmf_tcp_drain_state_queue(tqpair, TCP_REQUEST_STATE_NEW);
428 
429 	/* Wipe the requests waiting for buffer from the global list */
430 	TAILQ_FOREACH_SAFE(tcp_req, &tqpair->state_queue[TCP_REQUEST_STATE_NEED_BUFFER], state_link,
431 			   req_tmp) {
432 		TAILQ_REMOVE(&tqpair->group->pending_data_buf_queue, tcp_req, link);
433 	}
434 
435 	spdk_nvmf_tcp_drain_state_queue(tqpair, TCP_REQUEST_STATE_NEED_BUFFER);
436 	spdk_nvmf_tcp_drain_state_queue(tqpair, TCP_REQUEST_STATE_EXECUTING);
437 	spdk_nvmf_tcp_drain_state_queue(tqpair, TCP_REQUEST_STATE_TRANSFERRING_HOST_TO_CONTROLLER);
438 }
439 
440 static void
441 nvmf_tcp_dump_qpair_req_contents(struct spdk_nvmf_tcp_qpair *tqpair)
442 {
443 	int i;
444 	struct spdk_nvmf_tcp_req *tcp_req;
445 
446 	SPDK_ERRLOG("Dumping contents of queue pair (QID %d)\n", tqpair->qpair.qid);
447 	for (i = 1; i < TCP_REQUEST_NUM_STATES; i++) {
448 		SPDK_ERRLOG("\tNum of requests in state[%d] = %d\n", i, tqpair->state_cntr[i]);
449 		TAILQ_FOREACH(tcp_req, &tqpair->state_queue[i], state_link) {
450 			SPDK_ERRLOG("\t\tRequest Data From Pool: %d\n", tcp_req->data_from_pool);
451 			SPDK_ERRLOG("\t\tRequest opcode: %d\n", tcp_req->req.cmd->nvmf_cmd.opcode);
452 		}
453 	}
454 }
455 
456 static void
457 spdk_nvmf_tcp_qpair_destroy(struct spdk_nvmf_tcp_qpair *tqpair)
458 {
459 	int err = 0;
460 
461 	SPDK_DEBUGLOG(SPDK_LOG_NVMF_TCP, "enter\n");
462 
463 	spdk_poller_unregister(&tqpair->flush_poller);
464 	spdk_sock_close(&tqpair->sock);
465 	spdk_nvmf_tcp_cleanup_all_states(tqpair);
466 
467 	if (tqpair->free_pdu_num != (tqpair->max_queue_depth + NVMF_TCP_QPAIR_MAX_C2H_PDU_NUM)) {
468 		SPDK_ERRLOG("tqpair(%p) free pdu pool num is %u but should be %u\n", tqpair,
469 			    tqpair->free_pdu_num,
470 			    (tqpair->max_queue_depth + NVMF_TCP_QPAIR_MAX_C2H_PDU_NUM));
471 		err++;
472 	}
473 
474 	if (tqpair->state_cntr[TCP_REQUEST_STATE_FREE] != tqpair->max_queue_depth) {
475 		SPDK_ERRLOG("tqpair(%p) free tcp request num is %u but should be %u\n", tqpair,
476 			    tqpair->state_cntr[TCP_REQUEST_STATE_FREE],
477 			    tqpair->max_queue_depth);
478 		err++;
479 	}
480 
481 	if (tqpair->c2h_data_pdu_cnt != 0) {
482 		SPDK_ERRLOG("tqpair(%p) free c2h_data_pdu cnt is %u but should be 0\n", tqpair,
483 			    tqpair->c2h_data_pdu_cnt);
484 		err++;
485 	}
486 
487 	if (err > 0) {
488 		nvmf_tcp_dump_qpair_req_contents(tqpair);
489 	}
490 	free(tqpair->pdu);
491 	free(tqpair->pdu_pool);
492 	free(tqpair->req);
493 	free(tqpair->reqs);
494 	spdk_dma_free(tqpair->buf);
495 	spdk_dma_free(tqpair->bufs);
496 	free(tqpair);
497 	SPDK_DEBUGLOG(SPDK_LOG_NVMF_TCP, "Leave\n");
498 }
499 
500 static int
501 spdk_nvmf_tcp_destroy(struct spdk_nvmf_transport *transport)
502 {
503 	struct spdk_nvmf_tcp_transport	*ttransport;
504 
505 	assert(transport != NULL);
506 	ttransport = SPDK_CONTAINEROF(transport, struct spdk_nvmf_tcp_transport, transport);
507 
508 	pthread_mutex_destroy(&ttransport->lock);
509 	free(ttransport);
510 	return 0;
511 }
512 
513 static struct spdk_nvmf_transport *
514 spdk_nvmf_tcp_create(struct spdk_nvmf_transport_opts *opts)
515 {
516 	struct spdk_nvmf_tcp_transport *ttransport;
517 	uint32_t sge_count;
518 	uint32_t min_shared_buffers;
519 
520 	ttransport = calloc(1, sizeof(*ttransport));
521 	if (!ttransport) {
522 		return NULL;
523 	}
524 
525 	TAILQ_INIT(&ttransport->ports);
526 
527 	ttransport->transport.ops = &spdk_nvmf_transport_tcp;
528 
529 	SPDK_NOTICELOG("*** TCP Transport Init ***\n");
530 
531 	SPDK_INFOLOG(SPDK_LOG_NVMF_TCP, "*** TCP Transport Init ***\n"
532 		     "  Transport opts:  max_ioq_depth=%d, max_io_size=%d,\n"
533 		     "  max_qpairs_per_ctrlr=%d, io_unit_size=%d,\n"
534 		     "  in_capsule_data_size=%d, max_aq_depth=%d\n"
535 		     "  num_shared_buffers=%d, c2h_success=%d\n",
536 		     opts->max_queue_depth,
537 		     opts->max_io_size,
538 		     opts->max_qpairs_per_ctrlr,
539 		     opts->io_unit_size,
540 		     opts->in_capsule_data_size,
541 		     opts->max_aq_depth,
542 		     opts->num_shared_buffers,
543 		     opts->c2h_success);
544 
545 	/* I/O unit size cannot be larger than max I/O size */
546 	if (opts->io_unit_size > opts->max_io_size) {
547 		opts->io_unit_size = opts->max_io_size;
548 	}
549 
550 	sge_count = opts->max_io_size / opts->io_unit_size;
551 	if (sge_count > SPDK_NVMF_MAX_SGL_ENTRIES) {
552 		SPDK_ERRLOG("Unsupported IO Unit size specified, %d bytes\n", opts->io_unit_size);
553 		free(ttransport);
554 		return NULL;
555 	}
556 
557 	min_shared_buffers = spdk_thread_get_count() * opts->buf_cache_size;
558 	if (min_shared_buffers > opts->num_shared_buffers) {
559 		SPDK_ERRLOG("There are not enough buffers to satisfy"
560 			    "per-poll group caches for each thread. (%" PRIu32 ")"
561 			    "supplied. (%" PRIu32 ") required\n", opts->num_shared_buffers, min_shared_buffers);
562 		SPDK_ERRLOG("Please specify a larger number of shared buffers\n");
563 		spdk_nvmf_tcp_destroy(&ttransport->transport);
564 		return NULL;
565 	}
566 
567 	pthread_mutex_init(&ttransport->lock, NULL);
568 
569 	return &ttransport->transport;
570 }
571 
572 static int
573 _spdk_nvmf_tcp_trsvcid_to_int(const char *trsvcid)
574 {
575 	unsigned long long ull;
576 	char *end = NULL;
577 
578 	ull = strtoull(trsvcid, &end, 10);
579 	if (end == NULL || end == trsvcid || *end != '\0') {
580 		return -1;
581 	}
582 
583 	/* Valid TCP/IP port numbers are in [0, 65535] */
584 	if (ull > 65535) {
585 		return -1;
586 	}
587 
588 	return (int)ull;
589 }
590 
591 /**
592  * Canonicalize a listen address trid.
593  */
594 static int
595 _spdk_nvmf_tcp_canon_listen_trid(struct spdk_nvme_transport_id *canon_trid,
596 				 const struct spdk_nvme_transport_id *trid)
597 {
598 	int trsvcid_int;
599 
600 	trsvcid_int = _spdk_nvmf_tcp_trsvcid_to_int(trid->trsvcid);
601 	if (trsvcid_int < 0) {
602 		return -EINVAL;
603 	}
604 
605 	memset(canon_trid, 0, sizeof(*canon_trid));
606 	canon_trid->trtype = SPDK_NVME_TRANSPORT_TCP;
607 	canon_trid->adrfam = trid->adrfam;
608 	snprintf(canon_trid->traddr, sizeof(canon_trid->traddr), "%s", trid->traddr);
609 	snprintf(canon_trid->trsvcid, sizeof(canon_trid->trsvcid), "%d", trsvcid_int);
610 
611 	return 0;
612 }
613 
614 /**
615  * Find an existing listening port.
616  *
617  * Caller must hold ttransport->lock.
618  */
619 static struct spdk_nvmf_tcp_port *
620 _spdk_nvmf_tcp_find_port(struct spdk_nvmf_tcp_transport *ttransport,
621 			 const struct spdk_nvme_transport_id *trid)
622 {
623 	struct spdk_nvme_transport_id canon_trid;
624 	struct spdk_nvmf_tcp_port *port;
625 
626 	if (_spdk_nvmf_tcp_canon_listen_trid(&canon_trid, trid) != 0) {
627 		return NULL;
628 	}
629 
630 	TAILQ_FOREACH(port, &ttransport->ports, link) {
631 		if (spdk_nvme_transport_id_compare(&canon_trid, &port->trid) == 0) {
632 			return port;
633 		}
634 	}
635 
636 	return NULL;
637 }
638 
639 static int
640 spdk_nvmf_tcp_listen(struct spdk_nvmf_transport *transport,
641 		     const struct spdk_nvme_transport_id *trid)
642 {
643 	struct spdk_nvmf_tcp_transport *ttransport;
644 	struct spdk_nvmf_tcp_port *port;
645 	int trsvcid_int;
646 	uint8_t adrfam;
647 
648 	ttransport = SPDK_CONTAINEROF(transport, struct spdk_nvmf_tcp_transport, transport);
649 
650 	trsvcid_int = _spdk_nvmf_tcp_trsvcid_to_int(trid->trsvcid);
651 	if (trsvcid_int < 0) {
652 		SPDK_ERRLOG("Invalid trsvcid '%s'\n", trid->trsvcid);
653 		return -EINVAL;
654 	}
655 
656 	pthread_mutex_lock(&ttransport->lock);
657 
658 	port = _spdk_nvmf_tcp_find_port(ttransport, trid);
659 	if (port) {
660 		SPDK_DEBUGLOG(SPDK_LOG_NVMF_TCP, "Already listening on %s port %s\n",
661 			      trid->traddr, trid->trsvcid);
662 		port->ref++;
663 		pthread_mutex_unlock(&ttransport->lock);
664 		return 0;
665 	}
666 
667 	port = calloc(1, sizeof(*port));
668 	if (!port) {
669 		SPDK_ERRLOG("Port allocation failed\n");
670 		free(port);
671 		pthread_mutex_unlock(&ttransport->lock);
672 		return -ENOMEM;
673 	}
674 
675 	port->ref = 1;
676 
677 	if (_spdk_nvmf_tcp_canon_listen_trid(&port->trid, trid) != 0) {
678 		SPDK_ERRLOG("Invalid traddr %s / trsvcid %s\n",
679 			    trid->traddr, trid->trsvcid);
680 		free(port);
681 		pthread_mutex_unlock(&ttransport->lock);
682 		return -ENOMEM;
683 	}
684 
685 	port->listen_sock = spdk_sock_listen(trid->traddr, trsvcid_int);
686 	if (port->listen_sock == NULL) {
687 		SPDK_ERRLOG("spdk_sock_listen(%s, %d) failed: %s (%d)\n",
688 			    trid->traddr, trsvcid_int,
689 			    spdk_strerror(errno), errno);
690 		free(port);
691 		pthread_mutex_unlock(&ttransport->lock);
692 		return -errno;
693 	}
694 
695 	if (spdk_sock_is_ipv4(port->listen_sock)) {
696 		adrfam = SPDK_NVMF_ADRFAM_IPV4;
697 	} else if (spdk_sock_is_ipv6(port->listen_sock)) {
698 		adrfam = SPDK_NVMF_ADRFAM_IPV6;
699 	} else {
700 		SPDK_ERRLOG("Unhandled socket type\n");
701 		adrfam = 0;
702 	}
703 
704 	if (adrfam != trid->adrfam) {
705 		SPDK_ERRLOG("Socket address family mismatch\n");
706 		spdk_sock_close(&port->listen_sock);
707 		free(port);
708 		pthread_mutex_unlock(&ttransport->lock);
709 		return -EINVAL;
710 	}
711 
712 	SPDK_NOTICELOG("*** NVMe/TCP Target Listening on %s port %d ***\n",
713 		       trid->traddr, trsvcid_int);
714 
715 	TAILQ_INSERT_TAIL(&ttransport->ports, port, link);
716 	pthread_mutex_unlock(&ttransport->lock);
717 
718 	return 0;
719 }
720 
721 static int
722 spdk_nvmf_tcp_stop_listen(struct spdk_nvmf_transport *transport,
723 			  const struct spdk_nvme_transport_id *trid)
724 {
725 	struct spdk_nvmf_tcp_transport *ttransport;
726 	struct spdk_nvmf_tcp_port *port;
727 	int rc;
728 
729 	ttransport = SPDK_CONTAINEROF(transport, struct spdk_nvmf_tcp_transport, transport);
730 
731 	SPDK_DEBUGLOG(SPDK_LOG_NVMF_TCP, "Removing listen address %s port %s\n",
732 		      trid->traddr, trid->trsvcid);
733 
734 	pthread_mutex_lock(&ttransport->lock);
735 	port = _spdk_nvmf_tcp_find_port(ttransport, trid);
736 	if (port) {
737 		assert(port->ref > 0);
738 		port->ref--;
739 		if (port->ref == 0) {
740 			TAILQ_REMOVE(&ttransport->ports, port, link);
741 			spdk_sock_close(&port->listen_sock);
742 			free(port);
743 		}
744 		rc = 0;
745 	} else {
746 		SPDK_DEBUGLOG(SPDK_LOG_NVMF_TCP, "Port not found\n");
747 		rc = -ENOENT;
748 	}
749 	pthread_mutex_unlock(&ttransport->lock);
750 
751 	return rc;
752 }
753 
754 static int
755 spdk_nvmf_tcp_qpair_flush_pdus_internal(struct spdk_nvmf_tcp_qpair *tqpair)
756 {
757 	const int array_size = 32;
758 	struct iovec	iovec_array[array_size];
759 	struct iovec	*iov = iovec_array;
760 	int iovec_cnt = 0;
761 	int bytes = 0;
762 	int total_length = 0;
763 	uint32_t mapped_length;
764 	struct nvme_tcp_pdu *pdu;
765 	int pdu_length;
766 	TAILQ_HEAD(, nvme_tcp_pdu) completed_pdus_list;
767 	struct spdk_nvmf_tcp_transport *ttransport;
768 
769 	pdu = TAILQ_FIRST(&tqpair->send_queue);
770 
771 	if (pdu == NULL) {
772 		return 0;
773 	}
774 
775 	/*
776 	 * Build up a list of iovecs for the first few PDUs in the
777 	 *  tqpair 's send_queue.
778 	 */
779 	while (pdu != NULL && ((array_size - iovec_cnt) >= 3)) {
780 		iovec_cnt += nvme_tcp_build_iovecs(&iovec_array[iovec_cnt],
781 						   array_size - iovec_cnt,
782 						   pdu,
783 						   tqpair->host_hdgst_enable,
784 						   tqpair->host_ddgst_enable,
785 						   &mapped_length);
786 		total_length += mapped_length;
787 		pdu = TAILQ_NEXT(pdu, tailq);
788 	}
789 
790 	spdk_trace_record(TRACE_TCP_FLUSH_WRITEBUF_START, 0, total_length, 0, iovec_cnt);
791 
792 	bytes = spdk_sock_writev(tqpair->sock, iov, iovec_cnt);
793 	if (bytes == -1) {
794 		if (errno == EWOULDBLOCK || errno == EAGAIN) {
795 			return 1;
796 		} else {
797 			SPDK_ERRLOG("spdk_sock_writev() failed, errno %d: %s\n",
798 				    errno, spdk_strerror(errno));
799 			return -1;
800 		}
801 	}
802 
803 	spdk_trace_record(TRACE_TCP_FLUSH_WRITEBUF_DONE, 0, bytes, 0, 0);
804 
805 	pdu = TAILQ_FIRST(&tqpair->send_queue);
806 
807 	/*
808 	 * Free any PDUs that were fully written.  If a PDU was only
809 	 *  partially written, update its writev_offset so that next
810 	 *  time only the unwritten portion will be sent to writev().
811 	 */
812 	TAILQ_INIT(&completed_pdus_list);
813 	while (bytes > 0) {
814 		pdu_length = pdu->hdr.common.plen - pdu->writev_offset;
815 		if (bytes >= pdu_length) {
816 			bytes -= pdu_length;
817 			TAILQ_REMOVE(&tqpair->send_queue, pdu, tailq);
818 			TAILQ_INSERT_TAIL(&completed_pdus_list, pdu, tailq);
819 			pdu = TAILQ_FIRST(&tqpair->send_queue);
820 
821 		} else {
822 			pdu->writev_offset += bytes;
823 			bytes = 0;
824 		}
825 	}
826 
827 	while (!TAILQ_EMPTY(&completed_pdus_list)) {
828 		pdu = TAILQ_FIRST(&completed_pdus_list);
829 		TAILQ_REMOVE(&completed_pdus_list, pdu, tailq);
830 		assert(pdu->cb_fn != NULL);
831 		pdu->cb_fn(pdu->cb_arg);
832 		spdk_nvmf_tcp_pdu_put(tqpair, pdu);
833 	}
834 
835 	ttransport = SPDK_CONTAINEROF(tqpair->qpair.transport, struct spdk_nvmf_tcp_transport, transport);
836 	spdk_nvmf_tcp_qpair_process_pending(ttransport, tqpair);
837 
838 	return TAILQ_EMPTY(&tqpair->send_queue) ? 0 : 1;
839 }
840 
841 static int
842 spdk_nvmf_tcp_qpair_flush_pdus(void *_tqpair)
843 {
844 	struct spdk_nvmf_tcp_qpair *tqpair = _tqpair;
845 	int rc;
846 
847 	if (tqpair->state == NVME_TCP_QPAIR_STATE_RUNNING) {
848 		rc = spdk_nvmf_tcp_qpair_flush_pdus_internal(tqpair);
849 		if (rc == 0 && tqpair->flush_poller != NULL) {
850 			spdk_poller_unregister(&tqpair->flush_poller);
851 		} else if (rc == 1 && tqpair->flush_poller == NULL) {
852 			tqpair->flush_poller = spdk_poller_register(spdk_nvmf_tcp_qpair_flush_pdus,
853 					       tqpair, 50);
854 		}
855 	} else {
856 		/*
857 		 * If the tqpair state is not RUNNING, then
858 		 * keep trying to flush PDUs until our list is
859 		 * empty - to make sure all data is sent before
860 		 * closing the connection.
861 		 */
862 		do {
863 			rc = spdk_nvmf_tcp_qpair_flush_pdus_internal(tqpair);
864 		} while (rc == 1);
865 	}
866 
867 	if (rc < 0 && tqpair->state < NVME_TCP_QPAIR_STATE_EXITING) {
868 		/*
869 		 * If the poller has already started destruction of the tqpair,
870 		 *  i.e. the socket read failed, then the connection state may already
871 		 *  be EXITED.  We don't want to set it back to EXITING in that case.
872 		 */
873 		tqpair->state = NVME_TCP_QPAIR_STATE_EXITING;
874 	}
875 
876 	return -1;
877 }
878 
879 static void
880 spdk_nvmf_tcp_qpair_write_pdu(struct spdk_nvmf_tcp_qpair *tqpair,
881 			      struct nvme_tcp_pdu *pdu,
882 			      nvme_tcp_qpair_xfer_complete_cb cb_fn,
883 			      void *cb_arg)
884 {
885 	int enable_digest;
886 	int hlen;
887 	uint32_t crc32c;
888 
889 	hlen = pdu->hdr.common.hlen;
890 	enable_digest = 1;
891 	if (pdu->hdr.common.pdu_type == SPDK_NVME_TCP_PDU_TYPE_IC_RESP ||
892 	    pdu->hdr.common.pdu_type == SPDK_NVME_TCP_PDU_TYPE_C2H_TERM_REQ) {
893 		/* this PDU should be sent without digest */
894 		enable_digest = 0;
895 	}
896 
897 	/* Header Digest */
898 	if (enable_digest && tqpair->host_hdgst_enable) {
899 		crc32c = nvme_tcp_pdu_calc_header_digest(pdu);
900 		MAKE_DIGEST_WORD((uint8_t *)pdu->hdr.raw + hlen, crc32c);
901 	}
902 
903 	/* Data Digest */
904 	if (pdu->data_len > 0 && enable_digest && tqpair->host_ddgst_enable) {
905 		crc32c = nvme_tcp_pdu_calc_data_digest(pdu);
906 		MAKE_DIGEST_WORD(pdu->data_digest, crc32c);
907 	}
908 
909 	pdu->cb_fn = cb_fn;
910 	pdu->cb_arg = cb_arg;
911 	TAILQ_INSERT_TAIL(&tqpair->send_queue, pdu, tailq);
912 	spdk_nvmf_tcp_qpair_flush_pdus(tqpair);
913 }
914 
915 static int
916 spdk_nvmf_tcp_qpair_init_mem_resource(struct spdk_nvmf_tcp_qpair *tqpair, uint16_t size)
917 {
918 	int i;
919 	struct spdk_nvmf_tcp_req *tcp_req;
920 	struct spdk_nvmf_transport *transport = tqpair->qpair.transport;
921 	struct spdk_nvmf_tcp_transport *ttransport;
922 	ttransport = SPDK_CONTAINEROF(transport, struct spdk_nvmf_tcp_transport, transport);
923 
924 	if (!tqpair->qpair.sq_head_max) {
925 		tqpair->req = calloc(1, sizeof(*tqpair->req));
926 		if (!tqpair->req) {
927 			SPDK_ERRLOG("Unable to allocate req on tqpair=%p.\n", tqpair);
928 			return -1;
929 		}
930 
931 		if (transport->opts.in_capsule_data_size) {
932 			tqpair->buf = spdk_dma_zmalloc(ttransport->transport.opts.in_capsule_data_size, 0x1000, NULL);
933 			if (!tqpair->buf) {
934 				SPDK_ERRLOG("Unable to allocate buf on tqpair=%p.\n", tqpair);
935 				return -1;
936 			}
937 		}
938 
939 		tcp_req = tqpair->req;
940 		tcp_req->ttag = 0;
941 		tcp_req->req.qpair = &tqpair->qpair;
942 
943 		/* Set up memory to receive commands */
944 		if (tqpair->buf) {
945 			tcp_req->buf = tqpair->buf;
946 		}
947 
948 		/* Set the cmdn and rsp */
949 		tcp_req->req.rsp = (union nvmf_c2h_msg *)&tcp_req->rsp;
950 		tcp_req->req.cmd = (union nvmf_h2c_msg *)&tcp_req->cmd;
951 
952 		/* Initialize request state to FREE */
953 		tcp_req->state = TCP_REQUEST_STATE_FREE;
954 		TAILQ_INSERT_TAIL(&tqpair->state_queue[tcp_req->state], tcp_req, state_link);
955 
956 		tqpair->pdu = calloc(NVMF_TCP_QPAIR_MAX_C2H_PDU_NUM + 1, sizeof(*tqpair->pdu));
957 		if (!tqpair->pdu) {
958 			SPDK_ERRLOG("Unable to allocate pdu on tqpair=%p.\n", tqpair);
959 			return -1;
960 		}
961 
962 		for (i = 0; i < 1 + NVMF_TCP_QPAIR_MAX_C2H_PDU_NUM; i++) {
963 			TAILQ_INSERT_TAIL(&tqpair->free_queue, &tqpair->pdu[i], tailq);
964 		}
965 
966 	} else {
967 		tqpair->reqs = calloc(size, sizeof(*tqpair->reqs));
968 		if (!tqpair->reqs) {
969 			SPDK_ERRLOG("Unable to allocate reqs on tqpair=%p\n", tqpair);
970 			return -1;
971 		}
972 
973 		if (transport->opts.in_capsule_data_size) {
974 			tqpair->bufs = spdk_dma_zmalloc(size * transport->opts.in_capsule_data_size,
975 							0x1000, NULL);
976 			if (!tqpair->bufs) {
977 				SPDK_ERRLOG("Unable to allocate bufs on tqpair=%p.\n", tqpair);
978 				return -1;
979 			}
980 		}
981 
982 		for (i = 0; i < size; i++) {
983 			struct spdk_nvmf_tcp_req *tcp_req = &tqpair->reqs[i];
984 
985 			tcp_req->ttag = i + 1;
986 			tcp_req->req.qpair = &tqpair->qpair;
987 
988 			/* Set up memory to receive commands */
989 			if (tqpair->bufs) {
990 				tcp_req->buf = (void *)((uintptr_t)tqpair->bufs + (i * transport->opts.in_capsule_data_size));
991 			}
992 
993 			/* Set the cmdn and rsp */
994 			tcp_req->req.rsp = (union nvmf_c2h_msg *)&tcp_req->rsp;
995 			tcp_req->req.cmd = (union nvmf_h2c_msg *)&tcp_req->cmd;
996 
997 			/* Initialize request state to FREE */
998 			tcp_req->state = TCP_REQUEST_STATE_FREE;
999 			TAILQ_INSERT_TAIL(&tqpair->state_queue[tcp_req->state], tcp_req, state_link);
1000 		}
1001 
1002 		tqpair->pdu_pool = calloc(size, sizeof(*tqpair->pdu_pool));
1003 		if (!tqpair->pdu_pool) {
1004 			SPDK_ERRLOG("Unable to allocate pdu pool on tqpair =%p.\n", tqpair);
1005 			return -1;
1006 		}
1007 
1008 		for (i = 0; i < size; i++) {
1009 			TAILQ_INSERT_TAIL(&tqpair->free_queue, &tqpair->pdu_pool[i], tailq);
1010 		}
1011 	}
1012 
1013 	return 0;
1014 }
1015 
1016 static int
1017 spdk_nvmf_tcp_qpair_init(struct spdk_nvmf_qpair *qpair)
1018 {
1019 	struct spdk_nvmf_tcp_qpair *tqpair;
1020 	int i;
1021 
1022 	tqpair = SPDK_CONTAINEROF(qpair, struct spdk_nvmf_tcp_qpair, qpair);
1023 
1024 	SPDK_DEBUGLOG(SPDK_LOG_NVMF_TCP, "New TCP Connection: %p\n", qpair);
1025 
1026 	TAILQ_INIT(&tqpair->send_queue);
1027 	TAILQ_INIT(&tqpair->free_queue);
1028 	TAILQ_INIT(&tqpair->queued_c2h_data_tcp_req);
1029 
1030 	/* Initialise request state queues of the qpair */
1031 	for (i = TCP_REQUEST_STATE_FREE; i < TCP_REQUEST_NUM_STATES; i++) {
1032 		TAILQ_INIT(&tqpair->state_queue[i]);
1033 	}
1034 
1035 	tqpair->host_hdgst_enable = true;
1036 	tqpair->host_ddgst_enable = true;
1037 
1038 	return 0;
1039 }
1040 
1041 static int
1042 spdk_nvmf_tcp_qpair_sock_init(struct spdk_nvmf_tcp_qpair *tqpair)
1043 {
1044 
1045 	int rc;
1046 	int buf_size;
1047 
1048 	/* set recv buffer size */
1049 	buf_size = 2 * 1024 * 1024;
1050 	rc = spdk_sock_set_recvbuf(tqpair->sock, buf_size);
1051 	if (rc != 0) {
1052 		SPDK_ERRLOG("spdk_sock_set_recvbuf failed\n");
1053 		return rc;
1054 	}
1055 
1056 	/* set send buffer size */
1057 	rc = spdk_sock_set_sendbuf(tqpair->sock, buf_size);
1058 	if (rc != 0) {
1059 		SPDK_ERRLOG("spdk_sock_set_sendbuf failed\n");
1060 		return rc;
1061 	}
1062 
1063 	/* set low water mark */
1064 	rc = spdk_sock_set_recvlowat(tqpair->sock, sizeof(struct spdk_nvme_tcp_c2h_data_hdr));
1065 	if (rc != 0) {
1066 		SPDK_ERRLOG("spdk_sock_set_recvlowat() failed\n");
1067 		return rc;
1068 	}
1069 
1070 	return 0;
1071 }
1072 
1073 static void
1074 _spdk_nvmf_tcp_handle_connect(struct spdk_nvmf_transport *transport,
1075 			      struct spdk_nvmf_tcp_port *port,
1076 			      struct spdk_sock *sock, new_qpair_fn cb_fn)
1077 {
1078 	struct spdk_nvmf_tcp_qpair *tqpair;
1079 	int rc;
1080 
1081 	SPDK_DEBUGLOG(SPDK_LOG_NVMF_TCP, "New connection accepted on %s port %s\n",
1082 		      port->trid.traddr, port->trid.trsvcid);
1083 
1084 	tqpair = calloc(1, sizeof(struct spdk_nvmf_tcp_qpair));
1085 	if (tqpair == NULL) {
1086 		SPDK_ERRLOG("Could not allocate new connection.\n");
1087 		spdk_sock_close(&sock);
1088 		return;
1089 	}
1090 
1091 	tqpair->sock = sock;
1092 	tqpair->max_queue_depth = 1;
1093 	tqpair->free_pdu_num = tqpair->max_queue_depth + NVMF_TCP_QPAIR_MAX_C2H_PDU_NUM;
1094 	tqpair->state_cntr[TCP_REQUEST_STATE_FREE] = tqpair->max_queue_depth;
1095 	tqpair->port = port;
1096 	tqpair->qpair.transport = transport;
1097 
1098 	rc = spdk_sock_getaddr(tqpair->sock, tqpair->target_addr,
1099 			       sizeof(tqpair->target_addr), &tqpair->target_port,
1100 			       tqpair->initiator_addr, sizeof(tqpair->initiator_addr),
1101 			       &tqpair->initiator_port);
1102 	if (rc < 0) {
1103 		SPDK_ERRLOG("spdk_sock_getaddr() failed of tqpair=%p\n", tqpair);
1104 		spdk_nvmf_tcp_qpair_destroy(tqpair);
1105 		return;
1106 	}
1107 
1108 	cb_fn(&tqpair->qpair);
1109 }
1110 
1111 static void
1112 spdk_nvmf_tcp_port_accept(struct spdk_nvmf_transport *transport, struct spdk_nvmf_tcp_port *port,
1113 			  new_qpair_fn cb_fn)
1114 {
1115 	struct spdk_sock *sock;
1116 	int i;
1117 
1118 	for (i = 0; i < NVMF_TCP_MAX_ACCEPT_SOCK_ONE_TIME; i++) {
1119 		sock = spdk_sock_accept(port->listen_sock);
1120 		if (sock) {
1121 			_spdk_nvmf_tcp_handle_connect(transport, port, sock, cb_fn);
1122 		}
1123 	}
1124 }
1125 
1126 static void
1127 spdk_nvmf_tcp_accept(struct spdk_nvmf_transport *transport, new_qpair_fn cb_fn)
1128 {
1129 	struct spdk_nvmf_tcp_transport *ttransport;
1130 	struct spdk_nvmf_tcp_port *port;
1131 
1132 	ttransport = SPDK_CONTAINEROF(transport, struct spdk_nvmf_tcp_transport, transport);
1133 
1134 	TAILQ_FOREACH(port, &ttransport->ports, link) {
1135 		spdk_nvmf_tcp_port_accept(transport, port, cb_fn);
1136 	}
1137 }
1138 
1139 static void
1140 spdk_nvmf_tcp_discover(struct spdk_nvmf_transport *transport,
1141 		       struct spdk_nvme_transport_id *trid,
1142 		       struct spdk_nvmf_discovery_log_page_entry *entry)
1143 {
1144 	entry->trtype = SPDK_NVMF_TRTYPE_TCP;
1145 	entry->adrfam = trid->adrfam;
1146 	entry->treq.secure_channel = SPDK_NVMF_TREQ_SECURE_CHANNEL_NOT_SPECIFIED;
1147 
1148 	spdk_strcpy_pad(entry->trsvcid, trid->trsvcid, sizeof(entry->trsvcid), ' ');
1149 	spdk_strcpy_pad(entry->traddr, trid->traddr, sizeof(entry->traddr), ' ');
1150 
1151 	entry->tsas.tcp.sectype = SPDK_NVME_TCP_SECURITY_NONE;
1152 }
1153 
1154 static struct spdk_nvmf_transport_poll_group *
1155 spdk_nvmf_tcp_poll_group_create(struct spdk_nvmf_transport *transport)
1156 {
1157 	struct spdk_nvmf_tcp_poll_group *tgroup;
1158 
1159 	tgroup = calloc(1, sizeof(*tgroup));
1160 	if (!tgroup) {
1161 		return NULL;
1162 	}
1163 
1164 	tgroup->sock_group = spdk_sock_group_create();
1165 	if (!tgroup->sock_group) {
1166 		goto cleanup;
1167 	}
1168 
1169 	TAILQ_INIT(&tgroup->qpairs);
1170 	TAILQ_INIT(&tgroup->pending_data_buf_queue);
1171 
1172 	return &tgroup->group;
1173 
1174 cleanup:
1175 	free(tgroup);
1176 	return NULL;
1177 }
1178 
1179 static void
1180 spdk_nvmf_tcp_poll_group_destroy(struct spdk_nvmf_transport_poll_group *group)
1181 {
1182 	struct spdk_nvmf_tcp_poll_group *tgroup;
1183 
1184 	tgroup = SPDK_CONTAINEROF(group, struct spdk_nvmf_tcp_poll_group, group);
1185 	spdk_sock_group_close(&tgroup->sock_group);
1186 
1187 	if (!TAILQ_EMPTY(&tgroup->pending_data_buf_queue)) {
1188 		SPDK_ERRLOG("Pending I/O list wasn't empty on poll group destruction\n");
1189 	}
1190 
1191 	free(tgroup);
1192 }
1193 
1194 static void
1195 spdk_nvmf_tcp_qpair_set_recv_state(struct spdk_nvmf_tcp_qpair *tqpair,
1196 				   enum nvme_tcp_pdu_recv_state state)
1197 {
1198 	if (tqpair->recv_state == state) {
1199 		SPDK_ERRLOG("The recv state of tqpair=%p is same with the state(%d) to be set\n",
1200 			    tqpair, state);
1201 		return;
1202 	}
1203 
1204 	SPDK_DEBUGLOG(SPDK_LOG_NVMF_TCP, "tqpair(%p) recv state=%d\n", tqpair, state);
1205 	tqpair->recv_state = state;
1206 
1207 	switch (state) {
1208 	case NVME_TCP_PDU_RECV_STATE_AWAIT_PDU_CH:
1209 	case NVME_TCP_PDU_RECV_STATE_AWAIT_PDU_PSH:
1210 	case NVME_TCP_PDU_RECV_STATE_AWAIT_PDU_PAYLOAD:
1211 		break;
1212 	case NVME_TCP_PDU_RECV_STATE_ERROR:
1213 	case NVME_TCP_PDU_RECV_STATE_AWAIT_PDU_READY:
1214 		memset(&tqpair->pdu_in_progress, 0, sizeof(tqpair->pdu_in_progress));
1215 		break;
1216 	default:
1217 		SPDK_ERRLOG("The state(%d) is invalid\n", state);
1218 		abort();
1219 		break;
1220 	}
1221 }
1222 
1223 static int
1224 spdk_nvmf_tcp_qpair_handle_timeout(void *ctx)
1225 {
1226 	struct spdk_nvmf_tcp_qpair *tqpair = ctx;
1227 
1228 	assert(tqpair->recv_state == NVME_TCP_PDU_RECV_STATE_ERROR);
1229 
1230 	SPDK_ERRLOG("No pdu coming for tqpair=%p within %d seconds\n", tqpair,
1231 		    SPDK_NVME_TCP_QPAIR_EXIT_TIMEOUT);
1232 	tqpair->state = NVME_TCP_QPAIR_STATE_EXITED;
1233 	SPDK_DEBUGLOG(SPDK_LOG_NVMF_TCP, "will disconect the tqpair=%p\n", tqpair);
1234 	spdk_poller_unregister(&tqpair->timeout_poller);
1235 	spdk_nvmf_qpair_disconnect(&tqpair->qpair, NULL, NULL);
1236 
1237 	return 0;
1238 }
1239 
1240 static void
1241 spdk_nvmf_tcp_send_c2h_term_req_complete(void *cb_arg)
1242 {
1243 	struct spdk_nvmf_tcp_qpair *tqpair = (struct spdk_nvmf_tcp_qpair *)cb_arg;
1244 
1245 	if (!tqpair->timeout_poller) {
1246 		tqpair->timeout_poller = spdk_poller_register(spdk_nvmf_tcp_qpair_handle_timeout, tqpair,
1247 					 SPDK_NVME_TCP_QPAIR_EXIT_TIMEOUT * 1000000);
1248 	}
1249 }
1250 
1251 static void
1252 spdk_nvmf_tcp_send_c2h_term_req(struct spdk_nvmf_tcp_qpair *tqpair, struct nvme_tcp_pdu *pdu,
1253 				enum spdk_nvme_tcp_term_req_fes fes, uint32_t error_offset)
1254 {
1255 	struct nvme_tcp_pdu *rsp_pdu;
1256 	struct spdk_nvme_tcp_term_req_hdr *c2h_term_req;
1257 	uint32_t c2h_term_req_hdr_len = sizeof(*c2h_term_req);
1258 	uint32_t copy_len;
1259 
1260 	rsp_pdu = spdk_nvmf_tcp_pdu_get(tqpair);
1261 	if (!rsp_pdu) {
1262 		tqpair->state = NVME_TCP_QPAIR_STATE_EXITING;
1263 		spdk_nvmf_tcp_qpair_set_recv_state(tqpair, NVME_TCP_PDU_RECV_STATE_ERROR);
1264 		return;
1265 	}
1266 
1267 	c2h_term_req = &rsp_pdu->hdr.term_req;
1268 	c2h_term_req->common.pdu_type = SPDK_NVME_TCP_PDU_TYPE_C2H_TERM_REQ;
1269 	c2h_term_req->common.hlen = c2h_term_req_hdr_len;
1270 
1271 	if ((fes == SPDK_NVME_TCP_TERM_REQ_FES_INVALID_HEADER_FIELD) ||
1272 	    (fes == SPDK_NVME_TCP_TERM_REQ_FES_INVALID_DATA_UNSUPPORTED_PARAMETER)) {
1273 		DSET32(&c2h_term_req->fei, error_offset);
1274 	}
1275 
1276 	copy_len = pdu->hdr.common.hlen;
1277 	if (copy_len > SPDK_NVME_TCP_TERM_REQ_ERROR_DATA_MAX_SIZE) {
1278 		copy_len = SPDK_NVME_TCP_TERM_REQ_ERROR_DATA_MAX_SIZE;
1279 	}
1280 
1281 	/* Copy the error info into the buffer */
1282 	memcpy((uint8_t *)rsp_pdu->hdr.raw + c2h_term_req_hdr_len, pdu->hdr.raw, copy_len);
1283 	nvme_tcp_pdu_set_data(rsp_pdu, (uint8_t *)rsp_pdu->hdr.raw + c2h_term_req_hdr_len, copy_len);
1284 
1285 	/* Contain the header of the wrong received pdu */
1286 	c2h_term_req->common.plen = c2h_term_req->common.hlen + copy_len;
1287 	spdk_nvmf_tcp_qpair_set_recv_state(tqpair, NVME_TCP_PDU_RECV_STATE_ERROR);
1288 	spdk_nvmf_tcp_qpair_write_pdu(tqpair, rsp_pdu, spdk_nvmf_tcp_send_c2h_term_req_complete, tqpair);
1289 }
1290 
1291 static void
1292 spdk_nvmf_tcp_capsule_cmd_hdr_handle(struct spdk_nvmf_tcp_transport *ttransport,
1293 				     struct spdk_nvmf_tcp_qpair *tqpair,
1294 				     struct nvme_tcp_pdu *pdu)
1295 {
1296 	struct spdk_nvmf_tcp_req *tcp_req;
1297 
1298 	tcp_req = spdk_nvmf_tcp_req_get(tqpair);
1299 	if (!tcp_req) {
1300 		SPDK_ERRLOG("Cannot allocate tcp_req\n");
1301 		tqpair->state = NVME_TCP_QPAIR_STATE_EXITING;
1302 		spdk_nvmf_tcp_qpair_set_recv_state(tqpair, NVME_TCP_PDU_RECV_STATE_ERROR);
1303 		return;
1304 	}
1305 
1306 	pdu->ctx = tcp_req;
1307 	spdk_nvmf_tcp_req_set_state(tcp_req, TCP_REQUEST_STATE_NEW);
1308 	spdk_nvmf_tcp_req_process(ttransport, tcp_req);
1309 	return;
1310 }
1311 
1312 static void
1313 spdk_nvmf_tcp_capsule_cmd_payload_handle(struct spdk_nvmf_tcp_transport *ttransport,
1314 		struct spdk_nvmf_tcp_qpair *tqpair,
1315 		struct nvme_tcp_pdu *pdu)
1316 {
1317 	struct spdk_nvmf_tcp_req *tcp_req;
1318 	struct spdk_nvme_tcp_cmd *capsule_cmd;
1319 	uint32_t error_offset = 0;
1320 	enum spdk_nvme_tcp_term_req_fes fes;
1321 
1322 	capsule_cmd = &pdu->hdr.capsule_cmd;
1323 	tcp_req = pdu->ctx;
1324 	assert(tcp_req != NULL);
1325 	if (capsule_cmd->common.pdo > SPDK_NVME_TCP_PDU_PDO_MAX_OFFSET) {
1326 		SPDK_ERRLOG("Expected ICReq capsule_cmd pdu offset <= %d, got %c\n",
1327 			    SPDK_NVME_TCP_PDU_PDO_MAX_OFFSET, capsule_cmd->common.pdo);
1328 		fes = SPDK_NVME_TCP_TERM_REQ_FES_INVALID_HEADER_FIELD;
1329 		error_offset = offsetof(struct spdk_nvme_tcp_common_pdu_hdr, pdo);
1330 		goto err;
1331 	}
1332 
1333 	spdk_nvmf_tcp_qpair_set_recv_state(tqpair, NVME_TCP_PDU_RECV_STATE_AWAIT_PDU_READY);
1334 	spdk_nvmf_tcp_req_set_state(tcp_req, TCP_REQUEST_STATE_READY_TO_EXECUTE);
1335 	spdk_nvmf_tcp_req_process(ttransport, tcp_req);
1336 
1337 	return;
1338 err:
1339 	spdk_nvmf_tcp_send_c2h_term_req(tqpair, pdu, fes, error_offset);
1340 }
1341 
1342 static void
1343 spdk_nvmf_tcp_h2c_data_hdr_handle(struct spdk_nvmf_tcp_transport *ttransport,
1344 				  struct spdk_nvmf_tcp_qpair *tqpair,
1345 				  struct nvme_tcp_pdu *pdu)
1346 {
1347 	struct spdk_nvmf_tcp_req *tcp_req;
1348 	uint32_t error_offset = 0;
1349 	enum spdk_nvme_tcp_term_req_fes fes = 0;
1350 	struct spdk_nvme_tcp_h2c_data_hdr *h2c_data;
1351 	uint32_t iov_index;
1352 	bool ttag_offset_error = false;
1353 
1354 	h2c_data = &pdu->hdr.h2c_data;
1355 
1356 	SPDK_DEBUGLOG(SPDK_LOG_NVMF_TCP, "tqpair=%p, r2t_info: datao=%u, datal=%u, cccid=%u, ttag=%u\n",
1357 		      tqpair, h2c_data->datao, h2c_data->datal, h2c_data->cccid, h2c_data->ttag);
1358 
1359 	/* According to the information in the pdu to find the req */
1360 	TAILQ_FOREACH(tcp_req, &tqpair->state_queue[TCP_REQUEST_STATE_TRANSFERRING_HOST_TO_CONTROLLER],
1361 		      state_link) {
1362 		if ((tcp_req->req.cmd->nvme_cmd.cid == h2c_data->cccid) && (tcp_req->ttag == h2c_data->ttag)) {
1363 			break;
1364 		}
1365 
1366 		if (!ttag_offset_error && (tcp_req->req.cmd->nvme_cmd.cid == h2c_data->cccid)) {
1367 			ttag_offset_error = true;
1368 		}
1369 	}
1370 
1371 	if (!tcp_req) {
1372 		SPDK_DEBUGLOG(SPDK_LOG_NVMF_TCP, "tcp_req is not found for tqpair=%p\n", tqpair);
1373 		fes = SPDK_NVME_TCP_TERM_REQ_FES_INVALID_DATA_UNSUPPORTED_PARAMETER;
1374 		if (!ttag_offset_error) {
1375 			error_offset = offsetof(struct spdk_nvme_tcp_h2c_data_hdr, cccid);
1376 		} else {
1377 			error_offset = offsetof(struct spdk_nvme_tcp_h2c_data_hdr, ttag);
1378 		}
1379 		goto err;
1380 	}
1381 
1382 	if (tcp_req->next_expected_r2t_offset != h2c_data->datao) {
1383 		SPDK_DEBUGLOG(SPDK_LOG_NVMF_TCP,
1384 			      "tcp_req(%p), tqpair=%p,  expected_r2t_offset=%u, but data offset =%u\n",
1385 			      tcp_req, tqpair, tcp_req->next_expected_r2t_offset, h2c_data->datao);
1386 		fes = SPDK_NVME_TCP_TERM_REQ_FES_DATA_TRANSFER_OUT_OF_RANGE;
1387 		goto err;
1388 	}
1389 
1390 	if (h2c_data->datal > tqpair->maxh2cdata) {
1391 		SPDK_DEBUGLOG(SPDK_LOG_NVMF_TCP, "tcp_req(%p), tqpair=%p,  datao=%u execeeds maxh2cdata size=%u\n",
1392 			      tcp_req, tqpair, h2c_data->datao, tqpair->maxh2cdata);
1393 		fes = SPDK_NVME_TCP_TERM_REQ_FES_DATA_TRANSFER_OUT_OF_RANGE;
1394 		goto err;
1395 	}
1396 
1397 	if ((h2c_data->datao + h2c_data->datal) > tcp_req->req.length) {
1398 		SPDK_DEBUGLOG(SPDK_LOG_NVMF_TCP,
1399 			      "tcp_req(%p), tqpair=%p,  (datao=%u + datal=%u) execeeds requested length=%u\n",
1400 			      tcp_req, tqpair, h2c_data->datao, h2c_data->datal, tcp_req->req.length);
1401 		fes = SPDK_NVME_TCP_TERM_REQ_FES_R2T_LIMIT_EXCEEDED;
1402 		goto err;
1403 	}
1404 
1405 	pdu->ctx = tcp_req;
1406 	iov_index = pdu->hdr.h2c_data.datao / ttransport->transport.opts.io_unit_size;
1407 	nvme_tcp_pdu_set_data(pdu, tcp_req->req.iov[iov_index].iov_base + (pdu->hdr.h2c_data.datao %
1408 			      ttransport->transport.opts.io_unit_size), h2c_data->datal);
1409 	spdk_nvmf_tcp_qpair_set_recv_state(tqpair, NVME_TCP_PDU_RECV_STATE_AWAIT_PDU_PAYLOAD);
1410 	return;
1411 
1412 err:
1413 	spdk_nvmf_tcp_send_c2h_term_req(tqpair, pdu, fes, error_offset);
1414 }
1415 
1416 static void
1417 spdk_nvmf_tcp_pdu_cmd_complete(void *cb_arg)
1418 {
1419 	struct spdk_nvmf_tcp_req *tcp_req = cb_arg;
1420 	nvmf_tcp_request_free(tcp_req);
1421 }
1422 
1423 static void
1424 spdk_nvmf_tcp_send_capsule_resp_pdu(struct spdk_nvmf_tcp_req *tcp_req,
1425 				    struct spdk_nvmf_tcp_qpair *tqpair)
1426 {
1427 	struct nvme_tcp_pdu *rsp_pdu;
1428 	struct spdk_nvme_tcp_rsp *capsule_resp;
1429 
1430 	SPDK_DEBUGLOG(SPDK_LOG_NVMF_TCP, "enter, tqpair=%p\n", tqpair);
1431 	rsp_pdu = spdk_nvmf_tcp_pdu_get(tqpair);
1432 	if (!rsp_pdu) {
1433 		spdk_nvmf_tcp_qpair_set_recv_state(tqpair, NVME_TCP_PDU_RECV_STATE_ERROR);
1434 		tqpair->state = NVME_TCP_QPAIR_STATE_EXITING;
1435 		return;
1436 	}
1437 
1438 	capsule_resp = &rsp_pdu->hdr.capsule_resp;
1439 	capsule_resp->common.pdu_type = SPDK_NVME_TCP_PDU_TYPE_CAPSULE_RESP;
1440 	capsule_resp->common.plen = capsule_resp->common.hlen = sizeof(*capsule_resp);
1441 	capsule_resp->rccqe = tcp_req->req.rsp->nvme_cpl;
1442 	if (tqpair->host_hdgst_enable) {
1443 		capsule_resp->common.flags |= SPDK_NVME_TCP_CH_FLAGS_HDGSTF;
1444 		capsule_resp->common.plen += SPDK_NVME_TCP_DIGEST_LEN;
1445 	}
1446 
1447 	spdk_nvmf_tcp_qpair_write_pdu(tqpair, rsp_pdu, spdk_nvmf_tcp_pdu_cmd_complete, tcp_req);
1448 }
1449 
1450 static void
1451 spdk_nvmf_tcp_pdu_c2h_data_complete(void *cb_arg)
1452 {
1453 	struct spdk_nvmf_tcp_req *tcp_req = cb_arg;
1454 	struct spdk_nvmf_tcp_qpair *tqpair = SPDK_CONTAINEROF(tcp_req->req.qpair,
1455 					     struct spdk_nvmf_tcp_qpair, qpair);
1456 
1457 	assert(tqpair != NULL);
1458 	assert(tcp_req->c2h_data_pdu_num > 0);
1459 	tcp_req->c2h_data_pdu_num--;
1460 	if (!tcp_req->c2h_data_pdu_num) {
1461 		if (tqpair->qpair.transport->opts.c2h_success) {
1462 			nvmf_tcp_request_free(tcp_req);
1463 		} else {
1464 			spdk_nvmf_tcp_send_capsule_resp_pdu(tcp_req, tqpair);
1465 		}
1466 	}
1467 
1468 	tqpair->c2h_data_pdu_cnt--;
1469 	spdk_nvmf_tcp_handle_pending_c2h_data_queue(tqpair);
1470 }
1471 
1472 static void
1473 spdk_nvmf_tcp_send_r2t_pdu(struct spdk_nvmf_tcp_qpair *tqpair,
1474 			   struct spdk_nvmf_tcp_req *tcp_req)
1475 {
1476 	struct nvme_tcp_pdu *rsp_pdu;
1477 	struct spdk_nvme_tcp_r2t_hdr *r2t;
1478 
1479 	rsp_pdu = spdk_nvmf_tcp_pdu_get(tqpair);
1480 	if (!rsp_pdu) {
1481 		tqpair->state = NVME_TCP_QPAIR_STATE_EXITING;
1482 		spdk_nvmf_tcp_qpair_set_recv_state(tqpair, NVME_TCP_PDU_RECV_STATE_ERROR);
1483 		return;
1484 	}
1485 
1486 	r2t = &rsp_pdu->hdr.r2t;
1487 	r2t->common.pdu_type = SPDK_NVME_TCP_PDU_TYPE_R2T;
1488 	r2t->common.plen = r2t->common.hlen = sizeof(*r2t);
1489 
1490 	if (tqpair->host_hdgst_enable) {
1491 		r2t->common.flags |= SPDK_NVME_TCP_CH_FLAGS_HDGSTF;
1492 		r2t->common.plen += SPDK_NVME_TCP_DIGEST_LEN;
1493 	}
1494 
1495 	r2t->cccid = tcp_req->req.cmd->nvme_cmd.cid;
1496 	r2t->ttag = tcp_req->ttag;
1497 	r2t->r2to = tcp_req->next_expected_r2t_offset;
1498 	r2t->r2tl = spdk_min(tcp_req->req.length - tcp_req->next_expected_r2t_offset, tqpair->maxh2cdata);
1499 	tcp_req->r2tl_remain = r2t->r2tl;
1500 
1501 	SPDK_DEBUGLOG(SPDK_LOG_NVMF_TCP,
1502 		      "tcp_req(%p) on tqpair(%p), r2t_info: cccid=%u, ttag=%u, r2to=%u, r2tl=%u\n",
1503 		      tcp_req, tqpair, r2t->cccid, r2t->ttag, r2t->r2to, r2t->r2tl);
1504 	spdk_nvmf_tcp_qpair_write_pdu(tqpair, rsp_pdu, spdk_nvmf_tcp_pdu_cmd_complete, NULL);
1505 }
1506 
1507 static void
1508 spdk_nvmf_tcp_h2c_data_payload_handle(struct spdk_nvmf_tcp_transport *ttransport,
1509 				      struct spdk_nvmf_tcp_qpair *tqpair,
1510 				      struct nvme_tcp_pdu *pdu)
1511 {
1512 	struct spdk_nvmf_tcp_req *tcp_req;
1513 
1514 	tcp_req = pdu->ctx;
1515 	assert(tcp_req != NULL);
1516 
1517 	SPDK_DEBUGLOG(SPDK_LOG_NVMF_TCP, "enter\n");
1518 
1519 	tcp_req->next_expected_r2t_offset += pdu->data_len;
1520 	tcp_req->r2tl_remain -= pdu->data_len;
1521 	spdk_nvmf_tcp_qpair_set_recv_state(tqpair, NVME_TCP_PDU_RECV_STATE_AWAIT_PDU_READY);
1522 
1523 	if (!tcp_req->r2tl_remain) {
1524 		if (tcp_req->next_expected_r2t_offset == tcp_req->req.length) {
1525 			spdk_nvmf_tcp_req_set_state(tcp_req, TCP_REQUEST_STATE_READY_TO_EXECUTE);
1526 			spdk_nvmf_tcp_req_process(ttransport, tcp_req);
1527 		} else {
1528 			SPDK_DEBUGLOG(SPDK_LOG_NVMF_TCP, "Send r2t pdu for tcp_req=%p on tqpair=%p\n", tcp_req, tqpair);
1529 			spdk_nvmf_tcp_send_r2t_pdu(tqpair, tcp_req);
1530 		}
1531 	}
1532 }
1533 
1534 static void
1535 spdk_nvmf_tcp_h2c_term_req_dump(struct spdk_nvme_tcp_term_req_hdr *h2c_term_req)
1536 {
1537 	SPDK_ERRLOG("Error info of pdu(%p): %s\n", h2c_term_req,
1538 		    spdk_nvmf_tcp_term_req_fes_str[h2c_term_req->fes]);
1539 	if ((h2c_term_req->fes == SPDK_NVME_TCP_TERM_REQ_FES_INVALID_HEADER_FIELD) ||
1540 	    (h2c_term_req->fes == SPDK_NVME_TCP_TERM_REQ_FES_INVALID_DATA_UNSUPPORTED_PARAMETER)) {
1541 		SPDK_DEBUGLOG(SPDK_LOG_NVMF_TCP, "The offset from the start of the PDU header is %u\n",
1542 			      DGET32(h2c_term_req->fei));
1543 	}
1544 }
1545 
1546 static void
1547 spdk_nvmf_tcp_h2c_term_req_hdr_handle(struct spdk_nvmf_tcp_qpair *tqpair,
1548 				      struct nvme_tcp_pdu *pdu)
1549 {
1550 	struct spdk_nvme_tcp_term_req_hdr *h2c_term_req = &pdu->hdr.term_req;
1551 	uint32_t error_offset = 0;
1552 	enum spdk_nvme_tcp_term_req_fes fes;
1553 
1554 
1555 	if (h2c_term_req->fes > SPDK_NVME_TCP_TERM_REQ_FES_INVALID_DATA_UNSUPPORTED_PARAMETER) {
1556 		SPDK_ERRLOG("Fatal Error Stauts(FES) is unknown for h2c_term_req pdu=%p\n", pdu);
1557 		fes = SPDK_NVME_TCP_TERM_REQ_FES_INVALID_HEADER_FIELD;
1558 		error_offset = offsetof(struct spdk_nvme_tcp_term_req_hdr, fes);
1559 		goto end;
1560 	}
1561 
1562 	/* set the data buffer */
1563 	nvme_tcp_pdu_set_data(pdu, (uint8_t *)pdu->hdr.raw + h2c_term_req->common.hlen,
1564 			      h2c_term_req->common.plen - h2c_term_req->common.hlen);
1565 	spdk_nvmf_tcp_qpair_set_recv_state(tqpair, NVME_TCP_PDU_RECV_STATE_AWAIT_PDU_PAYLOAD);
1566 	return;
1567 end:
1568 	spdk_nvmf_tcp_send_c2h_term_req(tqpair, pdu, fes, error_offset);
1569 	return;
1570 }
1571 
1572 static void
1573 spdk_nvmf_tcp_h2c_term_req_payload_handle(struct spdk_nvmf_tcp_qpair *tqpair,
1574 		struct nvme_tcp_pdu *pdu)
1575 {
1576 	struct spdk_nvme_tcp_term_req_hdr *h2c_term_req = &pdu->hdr.term_req;
1577 
1578 	spdk_nvmf_tcp_h2c_term_req_dump(h2c_term_req);
1579 	spdk_nvmf_tcp_qpair_set_recv_state(tqpair, NVME_TCP_PDU_RECV_STATE_ERROR);
1580 	return;
1581 }
1582 
1583 static void
1584 spdk_nvmf_tcp_pdu_payload_handle(struct spdk_nvmf_tcp_qpair *tqpair)
1585 {
1586 	int rc = 0;
1587 	struct nvme_tcp_pdu *pdu;
1588 	uint32_t crc32c, error_offset = 0;
1589 	enum spdk_nvme_tcp_term_req_fes fes;
1590 	struct spdk_nvmf_tcp_transport *ttransport;
1591 
1592 	assert(tqpair->recv_state == NVME_TCP_PDU_RECV_STATE_AWAIT_PDU_PAYLOAD);
1593 	pdu = &tqpair->pdu_in_progress;
1594 
1595 	SPDK_DEBUGLOG(SPDK_LOG_NVMF_TCP, "enter\n");
1596 	/* check data digest if need */
1597 	if (pdu->ddgst_enable) {
1598 		crc32c = nvme_tcp_pdu_calc_data_digest(pdu);
1599 		rc = MATCH_DIGEST_WORD(pdu->data_digest, crc32c);
1600 		if (rc == 0) {
1601 			SPDK_ERRLOG("Data digest error on tqpair=(%p) with pdu=%p\n", tqpair, pdu);
1602 			fes = SPDK_NVME_TCP_TERM_REQ_FES_HDGST_ERROR;
1603 			spdk_nvmf_tcp_send_c2h_term_req(tqpair, pdu, fes, error_offset);
1604 			return;
1605 
1606 		}
1607 	}
1608 
1609 	ttransport = SPDK_CONTAINEROF(tqpair->qpair.transport, struct spdk_nvmf_tcp_transport, transport);
1610 	switch (pdu->hdr.common.pdu_type) {
1611 	case SPDK_NVME_TCP_PDU_TYPE_CAPSULE_CMD:
1612 		spdk_nvmf_tcp_capsule_cmd_payload_handle(ttransport, tqpair, pdu);
1613 		break;
1614 	case SPDK_NVME_TCP_PDU_TYPE_H2C_DATA:
1615 		spdk_nvmf_tcp_h2c_data_payload_handle(ttransport, tqpair, pdu);
1616 		break;
1617 
1618 	case SPDK_NVME_TCP_PDU_TYPE_H2C_TERM_REQ:
1619 		spdk_nvmf_tcp_h2c_term_req_payload_handle(tqpair, pdu);
1620 		break;
1621 
1622 	default:
1623 		/* The code should not go to here */
1624 		SPDK_ERRLOG("The code should not go to here\n");
1625 		break;
1626 	}
1627 }
1628 
1629 static void
1630 spdk_nvmf_tcp_send_icresp_complete(void *cb_arg)
1631 {
1632 	struct spdk_nvmf_tcp_qpair *tqpair = cb_arg;
1633 
1634 	tqpair->state = NVME_TCP_QPAIR_STATE_RUNNING;
1635 }
1636 
1637 static void
1638 spdk_nvmf_tcp_icreq_handle(struct spdk_nvmf_tcp_transport *ttransport,
1639 			   struct spdk_nvmf_tcp_qpair *tqpair,
1640 			   struct nvme_tcp_pdu *pdu)
1641 {
1642 	struct spdk_nvme_tcp_ic_req *ic_req = &pdu->hdr.ic_req;
1643 	struct nvme_tcp_pdu *rsp_pdu;
1644 	struct spdk_nvme_tcp_ic_resp *ic_resp;
1645 	uint32_t error_offset = 0;
1646 	enum spdk_nvme_tcp_term_req_fes fes;
1647 
1648 	/* Only PFV 0 is defined currently */
1649 	if (ic_req->pfv != 0) {
1650 		SPDK_ERRLOG("Expected ICReq PFV %u, got %u\n", 0u, ic_req->pfv);
1651 		fes = SPDK_NVME_TCP_TERM_REQ_FES_INVALID_HEADER_FIELD;
1652 		error_offset = offsetof(struct spdk_nvme_tcp_ic_req, pfv);
1653 		goto end;
1654 	}
1655 
1656 	/* MAXR2T is 0's based */
1657 	SPDK_DEBUGLOG(SPDK_LOG_NVMF_TCP, "maxr2t =%u\n", (ic_req->maxr2t + 1u));
1658 
1659 	tqpair->host_hdgst_enable = ic_req->dgst.bits.hdgst_enable ? true : false;
1660 	tqpair->host_ddgst_enable = ic_req->dgst.bits.ddgst_enable ? true : false;
1661 
1662 	tqpair->cpda = spdk_min(ic_req->hpda, SPDK_NVME_TCP_CPDA_MAX);
1663 	SPDK_DEBUGLOG(SPDK_LOG_NVMF_TCP, "cpda of tqpair=(%p) is : %u\n", tqpair, tqpair->cpda);
1664 
1665 	rsp_pdu = spdk_nvmf_tcp_pdu_get(tqpair);
1666 	if (!rsp_pdu) {
1667 		tqpair->state = NVME_TCP_QPAIR_STATE_EXITING;
1668 		spdk_nvmf_tcp_qpair_set_recv_state(tqpair, NVME_TCP_PDU_RECV_STATE_ERROR);
1669 		return;
1670 	}
1671 
1672 	ic_resp = &rsp_pdu->hdr.ic_resp;
1673 	ic_resp->common.pdu_type = SPDK_NVME_TCP_PDU_TYPE_IC_RESP;
1674 	ic_resp->common.hlen = ic_resp->common.plen =  sizeof(*ic_resp);
1675 	ic_resp->pfv = 0;
1676 	ic_resp->cpda = tqpair->cpda;
1677 	tqpair->maxh2cdata = spdk_min(NVMF_TCP_PDU_MAX_H2C_DATA_SIZE,
1678 				      ttransport->transport.opts.io_unit_size);
1679 	ic_resp->maxh2cdata = tqpair->maxh2cdata;
1680 	ic_resp->dgst.bits.hdgst_enable = tqpair->host_hdgst_enable ? 1 : 0;
1681 	ic_resp->dgst.bits.ddgst_enable = tqpair->host_ddgst_enable ? 1 : 0;
1682 
1683 	SPDK_DEBUGLOG(SPDK_LOG_NVMF_TCP, "host_hdgst_enable: %u\n", tqpair->host_hdgst_enable);
1684 	SPDK_DEBUGLOG(SPDK_LOG_NVMF_TCP, "host_ddgst_enable: %u\n", tqpair->host_ddgst_enable);
1685 
1686 	spdk_nvmf_tcp_qpair_write_pdu(tqpair, rsp_pdu, spdk_nvmf_tcp_send_icresp_complete, tqpair);
1687 	spdk_nvmf_tcp_qpair_set_recv_state(tqpair, NVME_TCP_PDU_RECV_STATE_AWAIT_PDU_READY);
1688 	return;
1689 end:
1690 	spdk_nvmf_tcp_send_c2h_term_req(tqpair, pdu, fes, error_offset);
1691 	return;
1692 }
1693 
1694 static void
1695 spdk_nvmf_tcp_pdu_psh_handle(struct spdk_nvmf_tcp_qpair *tqpair)
1696 {
1697 	struct nvme_tcp_pdu *pdu;
1698 	int rc;
1699 	uint32_t crc32c, error_offset = 0;
1700 	enum spdk_nvme_tcp_term_req_fes fes;
1701 	struct spdk_nvmf_tcp_transport *ttransport;
1702 
1703 	assert(tqpair->recv_state == NVME_TCP_PDU_RECV_STATE_AWAIT_PDU_PSH);
1704 	pdu = &tqpair->pdu_in_progress;
1705 
1706 	SPDK_DEBUGLOG(SPDK_LOG_NVMF_TCP, "pdu type of tqpair(%p) is %d\n", tqpair,
1707 		      pdu->hdr.common.pdu_type);
1708 	/* check header digest if needed */
1709 	if (pdu->has_hdgst) {
1710 		SPDK_DEBUGLOG(SPDK_LOG_NVMF_TCP, "Compare the header of pdu=%p on tqpair=%p\n", pdu, tqpair);
1711 		crc32c = nvme_tcp_pdu_calc_header_digest(pdu);
1712 		rc = MATCH_DIGEST_WORD((uint8_t *)pdu->hdr.raw + pdu->hdr.common.hlen, crc32c);
1713 		if (rc == 0) {
1714 			SPDK_ERRLOG("Header digest error on tqpair=(%p) with pdu=%p\n", tqpair, pdu);
1715 			fes = SPDK_NVME_TCP_TERM_REQ_FES_HDGST_ERROR;
1716 			spdk_nvmf_tcp_send_c2h_term_req(tqpair, pdu, fes, error_offset);
1717 			return;
1718 
1719 		}
1720 	}
1721 
1722 	ttransport = SPDK_CONTAINEROF(tqpair->qpair.transport, struct spdk_nvmf_tcp_transport, transport);
1723 	switch (pdu->hdr.common.pdu_type) {
1724 	case SPDK_NVME_TCP_PDU_TYPE_IC_REQ:
1725 		spdk_nvmf_tcp_icreq_handle(ttransport, tqpair, pdu);
1726 		break;
1727 	case SPDK_NVME_TCP_PDU_TYPE_CAPSULE_CMD:
1728 		spdk_nvmf_tcp_capsule_cmd_hdr_handle(ttransport, tqpair, pdu);
1729 		break;
1730 	case SPDK_NVME_TCP_PDU_TYPE_H2C_DATA:
1731 		spdk_nvmf_tcp_h2c_data_hdr_handle(ttransport, tqpair, pdu);
1732 		break;
1733 
1734 	case SPDK_NVME_TCP_PDU_TYPE_H2C_TERM_REQ:
1735 		spdk_nvmf_tcp_h2c_term_req_hdr_handle(tqpair, pdu);
1736 		break;
1737 
1738 	default:
1739 		SPDK_ERRLOG("Unexpected PDU type 0x%02x\n", tqpair->pdu_in_progress.hdr.common.pdu_type);
1740 		fes = SPDK_NVME_TCP_TERM_REQ_FES_INVALID_HEADER_FIELD;
1741 		error_offset = 1;
1742 		spdk_nvmf_tcp_send_c2h_term_req(tqpair, pdu, fes, error_offset);
1743 		break;
1744 	}
1745 }
1746 
1747 static void
1748 spdk_nvmf_tcp_pdu_ch_handle(struct spdk_nvmf_tcp_qpair *tqpair)
1749 {
1750 	struct nvme_tcp_pdu *pdu;
1751 	uint32_t error_offset = 0;
1752 	enum spdk_nvme_tcp_term_req_fes fes;
1753 	uint8_t expected_hlen, pdo;
1754 	bool plen_error = false, pdo_error = false;
1755 
1756 	assert(tqpair->recv_state == NVME_TCP_PDU_RECV_STATE_AWAIT_PDU_CH);
1757 	pdu = &tqpair->pdu_in_progress;
1758 
1759 	if (pdu->hdr.common.pdu_type == SPDK_NVME_TCP_PDU_TYPE_IC_REQ) {
1760 		if (tqpair->state != NVME_TCP_QPAIR_STATE_INVALID) {
1761 			SPDK_ERRLOG("Already received ICreq PDU, and reject this pdu=%p\n", pdu);
1762 			fes = SPDK_NVME_TCP_TERM_REQ_FES_PDU_SEQUENCE_ERROR;
1763 			goto err;
1764 		}
1765 		expected_hlen = sizeof(struct spdk_nvme_tcp_ic_req);
1766 		if (pdu->hdr.common.plen != expected_hlen) {
1767 			plen_error = true;
1768 		}
1769 	} else {
1770 		if (tqpair->state != NVME_TCP_QPAIR_STATE_RUNNING) {
1771 			SPDK_ERRLOG("The TCP/IP connection is not negotitated\n");
1772 			fes = SPDK_NVME_TCP_TERM_REQ_FES_PDU_SEQUENCE_ERROR;
1773 			goto err;
1774 		}
1775 
1776 		switch (pdu->hdr.common.pdu_type) {
1777 		case SPDK_NVME_TCP_PDU_TYPE_CAPSULE_CMD:
1778 			expected_hlen = sizeof(struct spdk_nvme_tcp_cmd);
1779 			pdo = pdu->hdr.common.pdo;
1780 			if ((tqpair->cpda != 0) && (pdo != ((tqpair->cpda + 1) << 2))) {
1781 				pdo_error = true;
1782 				break;
1783 			}
1784 
1785 			if (pdu->hdr.common.plen < expected_hlen) {
1786 				plen_error = true;
1787 			}
1788 			break;
1789 		case SPDK_NVME_TCP_PDU_TYPE_H2C_DATA:
1790 			expected_hlen = sizeof(struct spdk_nvme_tcp_h2c_data_hdr);
1791 			pdo = pdu->hdr.common.pdo;
1792 			if ((tqpair->cpda != 0) && (pdo != ((tqpair->cpda + 1) << 2))) {
1793 				pdo_error = true;
1794 				break;
1795 			}
1796 			if (pdu->hdr.common.plen < expected_hlen) {
1797 				plen_error = true;
1798 			}
1799 			break;
1800 
1801 		case SPDK_NVME_TCP_PDU_TYPE_H2C_TERM_REQ:
1802 			expected_hlen = sizeof(struct spdk_nvme_tcp_term_req_hdr);
1803 			if ((pdu->hdr.common.plen <= expected_hlen) ||
1804 			    (pdu->hdr.common.plen > SPDK_NVME_TCP_TERM_REQ_PDU_MAX_SIZE)) {
1805 				plen_error = true;
1806 			}
1807 			break;
1808 
1809 		default:
1810 			SPDK_ERRLOG("Unexpected PDU type 0x%02x\n", pdu->hdr.common.pdu_type);
1811 			fes = SPDK_NVME_TCP_TERM_REQ_FES_INVALID_HEADER_FIELD;
1812 			error_offset = offsetof(struct spdk_nvme_tcp_common_pdu_hdr, pdu_type);
1813 			goto err;
1814 		}
1815 	}
1816 
1817 	if (pdu->hdr.common.hlen != expected_hlen) {
1818 		SPDK_ERRLOG("PDU type=0x%02x, Expected ICReq header length %u, got %u on tqpair=%p\n",
1819 			    pdu->hdr.common.pdu_type,
1820 			    expected_hlen, pdu->hdr.common.hlen, tqpair);
1821 		fes = SPDK_NVME_TCP_TERM_REQ_FES_INVALID_HEADER_FIELD;
1822 		error_offset = offsetof(struct spdk_nvme_tcp_common_pdu_hdr, hlen);
1823 		goto err;
1824 	} else if (pdo_error) {
1825 		fes = SPDK_NVME_TCP_TERM_REQ_FES_INVALID_HEADER_FIELD;
1826 		error_offset = offsetof(struct spdk_nvme_tcp_common_pdu_hdr, pdo);
1827 	} else if (plen_error) {
1828 		fes = SPDK_NVME_TCP_TERM_REQ_FES_INVALID_HEADER_FIELD;
1829 		error_offset = offsetof(struct spdk_nvme_tcp_common_pdu_hdr, plen);
1830 		goto err;
1831 	} else {
1832 		spdk_nvmf_tcp_qpair_set_recv_state(tqpair, NVME_TCP_PDU_RECV_STATE_AWAIT_PDU_PSH);
1833 		return;
1834 	}
1835 err:
1836 	spdk_nvmf_tcp_send_c2h_term_req(tqpair, pdu, fes, error_offset);
1837 }
1838 
1839 static int
1840 spdk_nvmf_tcp_sock_process(struct spdk_nvmf_tcp_qpair *tqpair)
1841 {
1842 	int rc = 0;
1843 	struct nvme_tcp_pdu *pdu;
1844 	enum nvme_tcp_pdu_recv_state prev_state;
1845 	uint32_t data_len;
1846 	uint8_t psh_len, pdo, hlen;
1847 	int8_t  padding_len;
1848 
1849 	/* The loop here is to allow for several back-to-back state changes. */
1850 	do {
1851 		prev_state = tqpair->recv_state;
1852 
1853 		SPDK_DEBUGLOG(SPDK_LOG_NVMF_TCP, "tqpair(%p) recv pdu entering state %d\n", tqpair, prev_state);
1854 
1855 		switch (tqpair->recv_state) {
1856 		/* Wait for the common header  */
1857 		case NVME_TCP_PDU_RECV_STATE_AWAIT_PDU_READY:
1858 		case NVME_TCP_PDU_RECV_STATE_AWAIT_PDU_CH:
1859 			pdu = &tqpair->pdu_in_progress;
1860 
1861 			rc = nvme_tcp_read_data(tqpair->sock,
1862 						sizeof(struct spdk_nvme_tcp_common_pdu_hdr) - pdu->ch_valid_bytes,
1863 						(void *)&pdu->hdr.common + pdu->ch_valid_bytes);
1864 			if (rc < 0) {
1865 				SPDK_DEBUGLOG(SPDK_LOG_NVMF_TCP, "will disconnect tqpair=%p\n", tqpair);
1866 				return NVME_TCP_PDU_FATAL;
1867 			} else if (rc > 0) {
1868 				pdu->ch_valid_bytes += rc;
1869 				spdk_trace_record(TRACE_TCP_READ_FROM_SOCKET_DONE, 0, rc, 0, 0);
1870 				if (spdk_likely(tqpair->recv_state == NVME_TCP_PDU_RECV_STATE_AWAIT_PDU_READY)) {
1871 					spdk_nvmf_tcp_qpair_set_recv_state(tqpair, NVME_TCP_PDU_RECV_STATE_AWAIT_PDU_CH);
1872 				}
1873 			}
1874 
1875 			if (pdu->ch_valid_bytes < sizeof(struct spdk_nvme_tcp_common_pdu_hdr)) {
1876 				return NVME_TCP_PDU_IN_PROGRESS;
1877 			}
1878 
1879 			/* The command header of this PDU has now been read from the socket. */
1880 			spdk_nvmf_tcp_pdu_ch_handle(tqpair);
1881 			break;
1882 		/* Wait for the pdu specific header  */
1883 		case NVME_TCP_PDU_RECV_STATE_AWAIT_PDU_PSH:
1884 			pdu = &tqpair->pdu_in_progress;
1885 			psh_len = hlen = pdu->hdr.common.hlen;
1886 			/* Only capsule_cmd and h2c_data has header digest */
1887 			if (((pdu->hdr.common.pdu_type == SPDK_NVME_TCP_PDU_TYPE_CAPSULE_CMD) ||
1888 			     (pdu->hdr.common.pdu_type == SPDK_NVME_TCP_PDU_TYPE_H2C_DATA)) &&
1889 			    tqpair->host_hdgst_enable) {
1890 				pdu->has_hdgst = true;
1891 				psh_len += SPDK_NVME_TCP_DIGEST_LEN;
1892 				if (pdu->hdr.common.plen > psh_len) {
1893 					pdo = pdu->hdr.common.pdo;
1894 					padding_len = pdo - psh_len;
1895 					SPDK_DEBUGLOG(SPDK_LOG_NVMF_TCP, "padding length is =%d for pdu=%p on tqpair=%p\n", padding_len,
1896 						      pdu, tqpair);
1897 					if (padding_len > 0) {
1898 						psh_len = pdo;
1899 					}
1900 				}
1901 			}
1902 
1903 			psh_len -= sizeof(struct spdk_nvme_tcp_common_pdu_hdr);
1904 			/* The following will read psh + hdgest (if possbile) + padding (if posssible) */
1905 			if (pdu->psh_valid_bytes < psh_len) {
1906 				rc = nvme_tcp_read_data(tqpair->sock,
1907 							psh_len - pdu->psh_valid_bytes,
1908 							(void *)&pdu->hdr.raw + sizeof(struct spdk_nvme_tcp_common_pdu_hdr) + pdu->psh_valid_bytes);
1909 				if (rc < 0) {
1910 					return NVME_TCP_PDU_FATAL;
1911 				} else if (rc > 0) {
1912 					spdk_trace_record(TRACE_TCP_READ_FROM_SOCKET_DONE,
1913 							  0, rc, 0, 0);
1914 					pdu->psh_valid_bytes += rc;
1915 				}
1916 				if (pdu->psh_valid_bytes < psh_len) {
1917 					return NVME_TCP_PDU_IN_PROGRESS;
1918 				}
1919 			}
1920 
1921 			/* All header(ch, psh, head digist) of this PDU has now been read from the socket. */
1922 			spdk_nvmf_tcp_pdu_psh_handle(tqpair);
1923 			break;
1924 		case NVME_TCP_PDU_RECV_STATE_AWAIT_PDU_PAYLOAD:
1925 			pdu = &tqpair->pdu_in_progress;
1926 
1927 			/* check whether the data is valid, if not we just return */
1928 			if (!pdu->data_len) {
1929 				return NVME_TCP_PDU_IN_PROGRESS;
1930 			}
1931 
1932 			data_len = pdu->data_len;
1933 			/* data digest */
1934 			if (spdk_unlikely((pdu->hdr.common.pdu_type != SPDK_NVME_TCP_PDU_TYPE_H2C_TERM_REQ) &&
1935 					  tqpair->host_ddgst_enable)) {
1936 				data_len += SPDK_NVME_TCP_DIGEST_LEN;
1937 				pdu->ddgst_enable = true;
1938 			}
1939 
1940 			rc = nvme_tcp_read_payload_data(tqpair->sock, pdu);
1941 			if (rc < 0) {
1942 				return NVME_TCP_PDU_IN_PROGRESS;
1943 			}
1944 
1945 			pdu->readv_offset += rc;
1946 			if (pdu->readv_offset < data_len) {
1947 				return NVME_TCP_PDU_IN_PROGRESS;
1948 			}
1949 
1950 			/* All of this PDU has now been read from the socket. */
1951 			spdk_nvmf_tcp_pdu_payload_handle(tqpair);
1952 			break;
1953 		case NVME_TCP_PDU_RECV_STATE_ERROR:
1954 			pdu = &tqpair->pdu_in_progress;
1955 			/* Check whether the connection is closed. Each time, we only read 1 byte every time */
1956 			rc = nvme_tcp_read_data(tqpair->sock, 1, (void *)&pdu->hdr.common);
1957 			if (rc < 0) {
1958 				return NVME_TCP_PDU_FATAL;
1959 			}
1960 			break;
1961 		default:
1962 			assert(0);
1963 			SPDK_ERRLOG("code should not come to here");
1964 			break;
1965 		}
1966 	} while (tqpair->recv_state != prev_state);
1967 
1968 	return rc;
1969 }
1970 
1971 static enum spdk_nvme_data_transfer
1972 spdk_nvmf_tcp_req_get_xfer(struct spdk_nvmf_tcp_req *tcp_req) {
1973 	enum spdk_nvme_data_transfer xfer;
1974 	struct spdk_nvme_cmd *cmd = &tcp_req->req.cmd->nvme_cmd;
1975 	struct spdk_nvme_sgl_descriptor *sgl = &cmd->dptr.sgl1;
1976 
1977 	/* Figure out data transfer direction */
1978 	if (cmd->opc == SPDK_NVME_OPC_FABRIC)
1979 	{
1980 		xfer = spdk_nvme_opc_get_data_transfer(tcp_req->req.cmd->nvmf_cmd.fctype);
1981 	} else
1982 	{
1983 		xfer = spdk_nvme_opc_get_data_transfer(cmd->opc);
1984 
1985 		/* Some admin commands are special cases */
1986 		if ((tcp_req->req.qpair->qid == 0) &&
1987 		    ((cmd->opc == SPDK_NVME_OPC_GET_FEATURES) ||
1988 		     (cmd->opc == SPDK_NVME_OPC_SET_FEATURES))) {
1989 			switch (cmd->cdw10 & 0xff) {
1990 			case SPDK_NVME_FEAT_LBA_RANGE_TYPE:
1991 			case SPDK_NVME_FEAT_AUTONOMOUS_POWER_STATE_TRANSITION:
1992 			case SPDK_NVME_FEAT_HOST_IDENTIFIER:
1993 				break;
1994 			default:
1995 				xfer = SPDK_NVME_DATA_NONE;
1996 			}
1997 		}
1998 	}
1999 
2000 	if (xfer == SPDK_NVME_DATA_NONE)
2001 	{
2002 		return xfer;
2003 	}
2004 
2005 	/* Even for commands that may transfer data, they could have specified 0 length.
2006 	 * We want those to show up with xfer SPDK_NVME_DATA_NONE.
2007 	 */
2008 	switch (sgl->generic.type)
2009 	{
2010 	case SPDK_NVME_SGL_TYPE_DATA_BLOCK:
2011 	case SPDK_NVME_SGL_TYPE_BIT_BUCKET:
2012 	case SPDK_NVME_SGL_TYPE_SEGMENT:
2013 	case SPDK_NVME_SGL_TYPE_LAST_SEGMENT:
2014 	case SPDK_NVME_SGL_TYPE_TRANSPORT_DATA_BLOCK:
2015 		if (sgl->unkeyed.length == 0) {
2016 			xfer = SPDK_NVME_DATA_NONE;
2017 		}
2018 		break;
2019 	case SPDK_NVME_SGL_TYPE_KEYED_DATA_BLOCK:
2020 		if (sgl->keyed.length == 0) {
2021 			xfer = SPDK_NVME_DATA_NONE;
2022 		}
2023 		break;
2024 	}
2025 
2026 	return xfer;
2027 }
2028 
2029 static void
2030 spdk_nvmf_tcp_request_free_buffers(struct spdk_nvmf_tcp_req *tcp_req,
2031 				   struct spdk_nvmf_transport_poll_group *group, struct spdk_nvmf_transport *transport)
2032 {
2033 	for (uint32_t i = 0; i < tcp_req->req.iovcnt; i++) {
2034 		assert(tcp_req->buffers[i] != NULL);
2035 		if (group->buf_cache_count < group->buf_cache_size) {
2036 			STAILQ_INSERT_HEAD(&group->buf_cache,
2037 					   (struct spdk_nvmf_transport_pg_cache_buf *)tcp_req->buffers[i], link);
2038 			group->buf_cache_count++;
2039 		} else {
2040 			spdk_mempool_put(transport->data_buf_pool, tcp_req->buffers[i]);
2041 		}
2042 		tcp_req->req.iov[i].iov_base = NULL;
2043 		tcp_req->buffers[i] = NULL;
2044 		tcp_req->req.iov[i].iov_len = 0;
2045 	}
2046 	tcp_req->data_from_pool = false;
2047 }
2048 
2049 static int
2050 spdk_nvmf_tcp_req_fill_iovs(struct spdk_nvmf_tcp_transport *ttransport,
2051 			    struct spdk_nvmf_tcp_req *tcp_req)
2052 {
2053 	void					*buf = NULL;
2054 	uint32_t				length = tcp_req->req.length;
2055 	uint32_t				i = 0;
2056 	struct spdk_nvmf_tcp_qpair		*tqpair;
2057 	struct spdk_nvmf_transport_poll_group	*group;
2058 
2059 	tqpair = SPDK_CONTAINEROF(tcp_req->req.qpair, struct spdk_nvmf_tcp_qpair, qpair);
2060 	group = &tqpair->group->group;
2061 
2062 	tcp_req->req.iovcnt = 0;
2063 	while (length) {
2064 		if (!(STAILQ_EMPTY(&group->buf_cache))) {
2065 			group->buf_cache_count--;
2066 			buf = STAILQ_FIRST(&group->buf_cache);
2067 			STAILQ_REMOVE_HEAD(&group->buf_cache, link);
2068 		} else {
2069 			buf = spdk_mempool_get(ttransport->transport.data_buf_pool);
2070 			if (!buf) {
2071 				goto nomem;
2072 			}
2073 		}
2074 
2075 		tcp_req->req.iov[i].iov_base = (void *)((uintptr_t)(buf + NVMF_DATA_BUFFER_MASK) &
2076 							~NVMF_DATA_BUFFER_MASK);
2077 		tcp_req->req.iov[i].iov_len  = spdk_min(length, ttransport->transport.opts.io_unit_size);
2078 		tcp_req->req.iovcnt++;
2079 		tcp_req->buffers[i] = buf;
2080 		length -= tcp_req->req.iov[i].iov_len;
2081 		i++;
2082 	}
2083 
2084 	assert(tcp_req->req.iovcnt <= SPDK_NVMF_MAX_SGL_ENTRIES);
2085 	tcp_req->data_from_pool = true;
2086 	return 0;
2087 
2088 nomem:
2089 	spdk_nvmf_tcp_request_free_buffers(tcp_req, group, &ttransport->transport);
2090 	tcp_req->req.iovcnt = 0;
2091 	return -ENOMEM;
2092 }
2093 
2094 static int
2095 spdk_nvmf_tcp_req_parse_sgl(struct spdk_nvmf_tcp_transport *ttransport,
2096 			    struct spdk_nvmf_tcp_req *tcp_req)
2097 {
2098 	struct spdk_nvme_cmd			*cmd;
2099 	struct spdk_nvme_cpl			*rsp;
2100 	struct spdk_nvme_sgl_descriptor		*sgl;
2101 
2102 	cmd = &tcp_req->req.cmd->nvme_cmd;
2103 	rsp = &tcp_req->req.rsp->nvme_cpl;
2104 	sgl = &cmd->dptr.sgl1;
2105 
2106 	if (sgl->generic.type == SPDK_NVME_SGL_TYPE_TRANSPORT_DATA_BLOCK &&
2107 	    sgl->unkeyed.subtype == SPDK_NVME_SGL_SUBTYPE_TRANSPORT) {
2108 		if (sgl->unkeyed.length > ttransport->transport.opts.max_io_size) {
2109 			SPDK_ERRLOG("SGL length 0x%x exceeds max io size 0x%x\n",
2110 				    sgl->unkeyed.length, ttransport->transport.opts.max_io_size);
2111 			rsp->status.sc = SPDK_NVME_SC_DATA_SGL_LENGTH_INVALID;
2112 			return -1;
2113 		}
2114 
2115 		/* fill request length and populate iovs */
2116 		tcp_req->req.length = sgl->unkeyed.length;
2117 
2118 		SPDK_DEBUGLOG(SPDK_LOG_NVMF_TCP, "Data requested length= 0x%x\n",
2119 			      sgl->unkeyed.length);
2120 
2121 		if (spdk_nvmf_tcp_req_fill_iovs(ttransport, tcp_req) < 0) {
2122 			/* No available buffers. Queue this request up. */
2123 			SPDK_DEBUGLOG(SPDK_LOG_NVMF_TCP, "No available large data buffers. Queueing request %p\n", tcp_req);
2124 			return 0;
2125 		}
2126 
2127 		/* backward compatible */
2128 		tcp_req->req.data = tcp_req->req.iov[0].iov_base;
2129 
2130 
2131 		SPDK_DEBUGLOG(SPDK_LOG_NVMF_TCP, "Request %p took %d buffer/s from central pool, and data=%p\n",
2132 			      tcp_req,
2133 			      tcp_req->req.iovcnt, tcp_req->req.data);
2134 
2135 		return 0;
2136 	} else if (sgl->generic.type == SPDK_NVME_SGL_TYPE_DATA_BLOCK &&
2137 		   sgl->unkeyed.subtype == SPDK_NVME_SGL_SUBTYPE_OFFSET) {
2138 		uint64_t offset = sgl->address;
2139 		uint32_t max_len = ttransport->transport.opts.in_capsule_data_size;
2140 
2141 		SPDK_DEBUGLOG(SPDK_LOG_NVMF_TCP, "In-capsule data: offset 0x%" PRIx64 ", length 0x%x\n",
2142 			      offset, sgl->unkeyed.length);
2143 
2144 		if (offset > max_len) {
2145 			SPDK_ERRLOG("In-capsule offset 0x%" PRIx64 " exceeds capsule length 0x%x\n",
2146 				    offset, max_len);
2147 			rsp->status.sc = SPDK_NVME_SC_INVALID_SGL_OFFSET;
2148 			return -1;
2149 		}
2150 		max_len -= (uint32_t)offset;
2151 
2152 		if (sgl->unkeyed.length > max_len) {
2153 			SPDK_ERRLOG("In-capsule data length 0x%x exceeds capsule length 0x%x\n",
2154 				    sgl->unkeyed.length, max_len);
2155 			rsp->status.sc = SPDK_NVME_SC_DATA_SGL_LENGTH_INVALID;
2156 			return -1;
2157 		}
2158 
2159 		tcp_req->req.data = tcp_req->buf + offset;
2160 		tcp_req->data_from_pool = false;
2161 		tcp_req->req.length = sgl->unkeyed.length;
2162 
2163 		tcp_req->req.iov[0].iov_base = tcp_req->req.data;
2164 		tcp_req->req.iov[0].iov_len = tcp_req->req.length;
2165 		tcp_req->req.iovcnt = 1;
2166 
2167 		return 0;
2168 	}
2169 
2170 	SPDK_ERRLOG("Invalid NVMf I/O Command SGL:  Type 0x%x, Subtype 0x%x\n",
2171 		    sgl->generic.type, sgl->generic.subtype);
2172 	rsp->status.sc = SPDK_NVME_SC_SGL_DESCRIPTOR_TYPE_INVALID;
2173 	return -1;
2174 }
2175 
2176 static void
2177 spdk_nvmf_tcp_send_c2h_data(struct spdk_nvmf_tcp_qpair *tqpair,
2178 			    struct spdk_nvmf_tcp_req *tcp_req)
2179 {
2180 	struct nvme_tcp_pdu *rsp_pdu;
2181 	struct spdk_nvme_tcp_c2h_data_hdr *c2h_data;
2182 	uint32_t plen, pdo, alignment, offset, iov_index;
2183 
2184 	SPDK_DEBUGLOG(SPDK_LOG_NVMF_TCP, "enter\n");
2185 
2186 	/* always use the first iov_len, which is correct */
2187 	iov_index = tcp_req->c2h_data_offset / tcp_req->req.iov[0].iov_len;
2188 	offset = tcp_req->c2h_data_offset % tcp_req->req.iov[0].iov_len;
2189 
2190 	rsp_pdu = spdk_nvmf_tcp_pdu_get(tqpair);
2191 	assert(rsp_pdu != NULL);
2192 
2193 	c2h_data = &rsp_pdu->hdr.c2h_data;
2194 	c2h_data->common.pdu_type = SPDK_NVME_TCP_PDU_TYPE_C2H_DATA;
2195 	plen = c2h_data->common.hlen = sizeof(*c2h_data);
2196 
2197 	if (tqpair->host_hdgst_enable) {
2198 		plen += SPDK_NVME_TCP_DIGEST_LEN;
2199 		c2h_data->common.flags |= SPDK_NVME_TCP_CH_FLAGS_HDGSTF;
2200 	}
2201 
2202 	/* set the psh */
2203 	c2h_data->cccid = tcp_req->req.cmd->nvme_cmd.cid;
2204 	c2h_data->datal = spdk_min(NVMF_TCP_PDU_MAX_C2H_DATA_SIZE,
2205 				   (tcp_req->req.iov[iov_index].iov_len - offset));
2206 	c2h_data->datao = tcp_req->c2h_data_offset;
2207 
2208 	/* set the padding */
2209 	rsp_pdu->padding_len = 0;
2210 	pdo = plen;
2211 	if (tqpair->cpda) {
2212 		alignment = (tqpair->cpda + 1) << 2;
2213 		if (alignment > plen) {
2214 			rsp_pdu->padding_len = alignment - plen;
2215 			pdo = plen = alignment;
2216 		}
2217 	}
2218 
2219 	c2h_data->common.pdo = pdo;
2220 	plen += c2h_data->datal;
2221 	if (tqpair->host_ddgst_enable) {
2222 		c2h_data->common.flags |= SPDK_NVME_TCP_CH_FLAGS_DDGSTF;
2223 		plen += SPDK_NVME_TCP_DIGEST_LEN;
2224 	}
2225 
2226 	c2h_data->common.plen = plen;
2227 
2228 	nvme_tcp_pdu_set_data(rsp_pdu, tcp_req->req.iov[iov_index].iov_base + offset, c2h_data->datal);
2229 
2230 	tcp_req->c2h_data_offset += c2h_data->datal;
2231 	if (iov_index == (tcp_req->req.iovcnt - 1) && (tcp_req->c2h_data_offset == tcp_req->req.length)) {
2232 		SPDK_DEBUGLOG(SPDK_LOG_NVMF_TCP, "Last pdu for tcp_req=%p on tqpair=%p\n", tcp_req, tqpair);
2233 		c2h_data->common.flags |= SPDK_NVME_TCP_C2H_DATA_FLAGS_LAST_PDU;
2234 		if (tqpair->qpair.transport->opts.c2h_success) {
2235 			c2h_data->common.flags |= SPDK_NVME_TCP_C2H_DATA_FLAGS_SUCCESS;
2236 		}
2237 		TAILQ_REMOVE(&tqpair->queued_c2h_data_tcp_req, tcp_req, link);
2238 	}
2239 
2240 	tqpair->c2h_data_pdu_cnt += 1;
2241 	spdk_nvmf_tcp_qpair_write_pdu(tqpair, rsp_pdu, spdk_nvmf_tcp_pdu_c2h_data_complete, tcp_req);
2242 }
2243 
2244 static int
2245 spdk_nvmf_tcp_calc_c2h_data_pdu_num(struct spdk_nvmf_tcp_req *tcp_req)
2246 {
2247 	uint32_t i, iov_cnt, pdu_num = 0;
2248 
2249 	iov_cnt = tcp_req->req.iovcnt;
2250 	for (i = 0; i < iov_cnt; i++) {
2251 		pdu_num += (tcp_req->req.iov[i].iov_len + NVMF_TCP_PDU_MAX_C2H_DATA_SIZE - 1) /
2252 			   NVMF_TCP_PDU_MAX_C2H_DATA_SIZE;
2253 	}
2254 
2255 	return pdu_num;
2256 }
2257 
2258 static void
2259 spdk_nvmf_tcp_handle_pending_c2h_data_queue(struct spdk_nvmf_tcp_qpair *tqpair)
2260 {
2261 	struct spdk_nvmf_tcp_req *tcp_req;
2262 
2263 	while (!TAILQ_EMPTY(&tqpair->queued_c2h_data_tcp_req) &&
2264 	       (tqpair->c2h_data_pdu_cnt < NVMF_TCP_QPAIR_MAX_C2H_PDU_NUM)) {
2265 		tcp_req = TAILQ_FIRST(&tqpair->queued_c2h_data_tcp_req);
2266 		spdk_nvmf_tcp_send_c2h_data(tqpair, tcp_req);
2267 	}
2268 }
2269 
2270 static void
2271 spdk_nvmf_tcp_queue_c2h_data(struct spdk_nvmf_tcp_req *tcp_req,
2272 			     struct spdk_nvmf_tcp_qpair *tqpair)
2273 {
2274 	tcp_req->c2h_data_pdu_num = spdk_nvmf_tcp_calc_c2h_data_pdu_num(tcp_req);
2275 
2276 	assert(tcp_req->c2h_data_pdu_num < NVMF_TCP_QPAIR_MAX_C2H_PDU_NUM);
2277 
2278 	TAILQ_INSERT_TAIL(&tqpair->queued_c2h_data_tcp_req, tcp_req, link);
2279 	spdk_nvmf_tcp_handle_pending_c2h_data_queue(tqpair);
2280 }
2281 
2282 static int
2283 request_transfer_out(struct spdk_nvmf_request *req)
2284 {
2285 	struct spdk_nvmf_tcp_req	*tcp_req;
2286 	struct spdk_nvmf_qpair		*qpair;
2287 	struct spdk_nvmf_tcp_qpair	*tqpair;
2288 	struct spdk_nvme_cpl		*rsp;
2289 
2290 	SPDK_DEBUGLOG(SPDK_LOG_NVMF_TCP, "enter\n");
2291 
2292 	qpair = req->qpair;
2293 	rsp = &req->rsp->nvme_cpl;
2294 	tcp_req = SPDK_CONTAINEROF(req, struct spdk_nvmf_tcp_req, req);
2295 
2296 	/* Advance our sq_head pointer */
2297 	if (qpair->sq_head == qpair->sq_head_max) {
2298 		qpair->sq_head = 0;
2299 	} else {
2300 		qpair->sq_head++;
2301 	}
2302 	rsp->sqhd = qpair->sq_head;
2303 
2304 	tqpair = SPDK_CONTAINEROF(tcp_req->req.qpair, struct spdk_nvmf_tcp_qpair, qpair);
2305 	spdk_nvmf_tcp_req_set_state(tcp_req, TCP_REQUEST_STATE_TRANSFERRING_CONTROLLER_TO_HOST);
2306 	if (rsp->status.sc == SPDK_NVME_SC_SUCCESS &&
2307 	    req->xfer == SPDK_NVME_DATA_CONTROLLER_TO_HOST) {
2308 		spdk_nvmf_tcp_queue_c2h_data(tcp_req, tqpair);
2309 	} else {
2310 		spdk_nvmf_tcp_send_capsule_resp_pdu(tcp_req, tqpair);
2311 	}
2312 
2313 	return 0;
2314 }
2315 
2316 static void
2317 spdk_nvmf_tcp_pdu_set_buf_from_req(struct spdk_nvmf_tcp_qpair *tqpair,
2318 				   struct spdk_nvmf_tcp_req *tcp_req)
2319 {
2320 	struct nvme_tcp_pdu *pdu;
2321 
2322 	if (tcp_req->data_from_pool) {
2323 		SPDK_DEBUGLOG(SPDK_LOG_NVMF_TCP, "Will send r2t for tcp_req(%p) on tqpair=%p\n", tcp_req, tqpair);
2324 		tcp_req->next_expected_r2t_offset = 0;
2325 		spdk_nvmf_tcp_req_set_state(tcp_req, TCP_REQUEST_STATE_TRANSFERRING_HOST_TO_CONTROLLER);
2326 		spdk_nvmf_tcp_send_r2t_pdu(tqpair, tcp_req);
2327 	} else {
2328 		pdu = &tqpair->pdu_in_progress;
2329 		SPDK_DEBUGLOG(SPDK_LOG_NVMF_TCP, "Not need to send r2t for tcp_req(%p) on tqpair=%p\n", tcp_req,
2330 			      tqpair);
2331 		/* No need to send r2t, contained in the capsuled data */
2332 		nvme_tcp_pdu_set_data(pdu, tcp_req->req.data, tcp_req->req.length);
2333 		spdk_nvmf_tcp_qpair_set_recv_state(tqpair, NVME_TCP_PDU_RECV_STATE_AWAIT_PDU_PAYLOAD);
2334 		spdk_nvmf_tcp_req_set_state(tcp_req, TCP_REQUEST_STATE_TRANSFERRING_HOST_TO_CONTROLLER);
2335 	}
2336 }
2337 
2338 static void
2339 spdk_nvmf_tcp_set_incapsule_data(struct spdk_nvmf_tcp_qpair *tqpair,
2340 				 struct spdk_nvmf_tcp_req *tcp_req)
2341 {
2342 	struct nvme_tcp_pdu *pdu;
2343 	uint32_t plen = 0;
2344 
2345 	pdu = &tqpair->pdu_in_progress;
2346 	plen = pdu->hdr.common.hlen;
2347 
2348 	if (tqpair->host_hdgst_enable) {
2349 		plen += SPDK_NVME_TCP_DIGEST_LEN;
2350 	}
2351 
2352 	if (pdu->hdr.common.plen != plen) {
2353 		tcp_req->has_incapsule_data = true;
2354 	}
2355 }
2356 
2357 static bool
2358 spdk_nvmf_tcp_req_process(struct spdk_nvmf_tcp_transport *ttransport,
2359 			  struct spdk_nvmf_tcp_req *tcp_req)
2360 {
2361 	struct spdk_nvmf_tcp_qpair		*tqpair;
2362 	struct spdk_nvme_cpl			*rsp = &tcp_req->req.rsp->nvme_cpl;
2363 	int					rc;
2364 	enum spdk_nvmf_tcp_req_state		prev_state;
2365 	bool					progress = false;
2366 	struct spdk_nvmf_transport_poll_group	*group;
2367 
2368 	tqpair = SPDK_CONTAINEROF(tcp_req->req.qpair, struct spdk_nvmf_tcp_qpair, qpair);
2369 	group = &tqpair->group->group;
2370 	assert(tcp_req->state != TCP_REQUEST_STATE_FREE);
2371 
2372 	/* The loop here is to allow for several back-to-back state changes. */
2373 	do {
2374 		prev_state = tcp_req->state;
2375 
2376 		SPDK_DEBUGLOG(SPDK_LOG_NVMF_TCP, "Request %p entering state %d on tqpair=%p\n", tcp_req, prev_state,
2377 			      tqpair);
2378 
2379 		switch (tcp_req->state) {
2380 		case TCP_REQUEST_STATE_FREE:
2381 			/* Some external code must kick a request into TCP_REQUEST_STATE_NEW
2382 			 * to escape this state. */
2383 			break;
2384 		case TCP_REQUEST_STATE_NEW:
2385 			spdk_trace_record(TRACE_TCP_REQUEST_STATE_NEW, 0, 0, (uintptr_t)tcp_req, 0);
2386 
2387 			/* copy the cmd from the receive pdu */
2388 			tcp_req->cmd = tqpair->pdu_in_progress.hdr.capsule_cmd.ccsqe;
2389 
2390 			/* The next state transition depends on the data transfer needs of this request. */
2391 			tcp_req->req.xfer = spdk_nvmf_tcp_req_get_xfer(tcp_req);
2392 
2393 			/* If no data to transfer, ready to execute. */
2394 			if (tcp_req->req.xfer == SPDK_NVME_DATA_NONE) {
2395 				/* Reset the tqpair receving pdu state */
2396 				spdk_nvmf_tcp_qpair_set_recv_state(tqpair, NVME_TCP_PDU_RECV_STATE_AWAIT_PDU_READY);
2397 				spdk_nvmf_tcp_req_set_state(tcp_req, TCP_REQUEST_STATE_READY_TO_EXECUTE);
2398 				break;
2399 			}
2400 
2401 			spdk_nvmf_tcp_set_incapsule_data(tqpair, tcp_req);
2402 
2403 			if (!tcp_req->has_incapsule_data) {
2404 				spdk_nvmf_tcp_qpair_set_recv_state(tqpair, NVME_TCP_PDU_RECV_STATE_AWAIT_PDU_READY);
2405 			}
2406 
2407 			spdk_nvmf_tcp_req_set_state(tcp_req, TCP_REQUEST_STATE_NEED_BUFFER);
2408 			TAILQ_INSERT_TAIL(&tqpair->group->pending_data_buf_queue, tcp_req, link);
2409 			break;
2410 		case TCP_REQUEST_STATE_NEED_BUFFER:
2411 			spdk_trace_record(TRACE_TCP_REQUEST_STATE_NEED_BUFFER, 0, 0, (uintptr_t)tcp_req, 0);
2412 
2413 			assert(tcp_req->req.xfer != SPDK_NVME_DATA_NONE);
2414 
2415 			if (!tcp_req->has_incapsule_data &&
2416 			    (tcp_req != TAILQ_FIRST(&tqpair->group->pending_data_buf_queue))) {
2417 				SPDK_DEBUGLOG(SPDK_LOG_NVMF_TCP,
2418 					      "Not the first element to wait for the buf for tcp_req(%p) on tqpair=%p\n",
2419 					      tcp_req, tqpair);
2420 				/* This request needs to wait in line to obtain a buffer */
2421 				break;
2422 			}
2423 
2424 			/* Try to get a data buffer */
2425 			rc = spdk_nvmf_tcp_req_parse_sgl(ttransport, tcp_req);
2426 			if (rc < 0) {
2427 				TAILQ_REMOVE(&tqpair->group->pending_data_buf_queue, tcp_req, link);
2428 				rsp->status.sc = SPDK_NVME_SC_INTERNAL_DEVICE_ERROR;
2429 				/* Reset the tqpair receving pdu state */
2430 				spdk_nvmf_tcp_qpair_set_recv_state(tqpair, NVME_TCP_PDU_RECV_STATE_ERROR);
2431 				spdk_nvmf_tcp_req_set_state(tcp_req, TCP_REQUEST_STATE_READY_TO_COMPLETE);
2432 				break;
2433 			}
2434 
2435 			if (!tcp_req->req.data) {
2436 				SPDK_DEBUGLOG(SPDK_LOG_NVMF_TCP, "No buffer allocated for tcp_req(%p) on tqpair(%p\n)",
2437 					      tcp_req, tqpair);
2438 				/* No buffers available. */
2439 				break;
2440 			}
2441 
2442 			TAILQ_REMOVE(&tqpair->group->pending_data_buf_queue, tcp_req, link);
2443 
2444 			/* If data is transferring from host to controller, we need to do a transfer from the host. */
2445 			if (tcp_req->req.xfer == SPDK_NVME_DATA_HOST_TO_CONTROLLER) {
2446 				spdk_nvmf_tcp_pdu_set_buf_from_req(tqpair, tcp_req);
2447 				break;
2448 			}
2449 
2450 			spdk_nvmf_tcp_req_set_state(tcp_req, TCP_REQUEST_STATE_READY_TO_EXECUTE);
2451 			break;
2452 		case TCP_REQUEST_STATE_TRANSFERRING_HOST_TO_CONTROLLER:
2453 			spdk_trace_record(TRACE_TCP_REQUEST_STATE_TRANSFERRING_HOST_TO_CONTROLLER, 0, 0,
2454 					  (uintptr_t)tcp_req, 0);
2455 			/* Some external code must kick a request into TCP_REQUEST_STATE_READY_TO_EXECUTE
2456 			 * to escape this state. */
2457 			break;
2458 		case TCP_REQUEST_STATE_READY_TO_EXECUTE:
2459 			spdk_trace_record(TRACE_TCP_REQUEST_STATE_READY_TO_EXECUTE, 0, 0, (uintptr_t)tcp_req, 0);
2460 			spdk_nvmf_tcp_req_set_state(tcp_req, TCP_REQUEST_STATE_EXECUTING);
2461 			spdk_nvmf_request_exec(&tcp_req->req);
2462 			break;
2463 		case TCP_REQUEST_STATE_EXECUTING:
2464 			spdk_trace_record(TRACE_TCP_REQUEST_STATE_EXECUTING, 0, 0, (uintptr_t)tcp_req, 0);
2465 			/* Some external code must kick a request into TCP_REQUEST_STATE_EXECUTED
2466 			 * to escape this state. */
2467 			break;
2468 		case TCP_REQUEST_STATE_EXECUTED:
2469 			spdk_trace_record(TRACE_TCP_REQUEST_STATE_EXECUTED, 0, 0, (uintptr_t)tcp_req, 0);
2470 			spdk_nvmf_tcp_req_set_state(tcp_req, TCP_REQUEST_STATE_READY_TO_COMPLETE);
2471 			break;
2472 		case TCP_REQUEST_STATE_READY_TO_COMPLETE:
2473 			spdk_trace_record(TRACE_TCP_REQUEST_STATE_READY_TO_COMPLETE, 0, 0, (uintptr_t)tcp_req, 0);
2474 			rc = request_transfer_out(&tcp_req->req);
2475 			assert(rc == 0); /* No good way to handle this currently */
2476 			break;
2477 		case TCP_REQUEST_STATE_TRANSFERRING_CONTROLLER_TO_HOST:
2478 			spdk_trace_record(TRACE_TCP_REQUEST_STATE_TRANSFERRING_CONTROLLER_TO_HOST, 0, 0,
2479 					  (uintptr_t)tcp_req,
2480 					  0);
2481 			/* Some external code must kick a request into TCP_REQUEST_STATE_COMPLETED
2482 			 * to escape this state. */
2483 			break;
2484 		case TCP_REQUEST_STATE_COMPLETED:
2485 			spdk_trace_record(TRACE_TCP_REQUEST_STATE_COMPLETED, 0, 0, (uintptr_t)tcp_req, 0);
2486 			if (tcp_req->data_from_pool) {
2487 				spdk_nvmf_tcp_request_free_buffers(tcp_req, group, &ttransport->transport);
2488 			}
2489 			tcp_req->req.length = 0;
2490 			tcp_req->req.iovcnt = 0;
2491 			tcp_req->req.data = NULL;
2492 			spdk_nvmf_tcp_req_set_state(tcp_req, TCP_REQUEST_STATE_FREE);
2493 			break;
2494 		case TCP_REQUEST_NUM_STATES:
2495 		default:
2496 			assert(0);
2497 			break;
2498 		}
2499 
2500 		if (tcp_req->state != prev_state) {
2501 			progress = true;
2502 		}
2503 	} while (tcp_req->state != prev_state);
2504 
2505 	return progress;
2506 }
2507 
2508 static void
2509 spdk_nvmf_tcp_qpair_process_pending(struct spdk_nvmf_tcp_transport *ttransport,
2510 				    struct spdk_nvmf_tcp_qpair *tqpair)
2511 {
2512 	struct spdk_nvmf_tcp_req *tcp_req, *req_tmp;
2513 
2514 	/* Tqpair is not in a good state, so return it */
2515 	if (spdk_unlikely(tqpair->recv_state == NVME_TCP_PDU_RECV_STATE_ERROR)) {
2516 		return;
2517 	}
2518 
2519 
2520 	TAILQ_FOREACH_SAFE(tcp_req, &tqpair->group->pending_data_buf_queue, link, req_tmp) {
2521 		if (spdk_nvmf_tcp_req_process(ttransport, tcp_req) == false) {
2522 			break;
2523 		}
2524 	}
2525 }
2526 
2527 static void
2528 spdk_nvmf_tcp_sock_cb(void *arg, struct spdk_sock_group *group, struct spdk_sock *sock)
2529 {
2530 	struct spdk_nvmf_tcp_qpair *tqpair = arg;
2531 	struct spdk_nvmf_tcp_transport *ttransport;
2532 	int rc;
2533 
2534 	assert(tqpair != NULL);
2535 
2536 	ttransport = SPDK_CONTAINEROF(tqpair->qpair.transport, struct spdk_nvmf_tcp_transport, transport);
2537 	spdk_nvmf_tcp_qpair_process_pending(ttransport, tqpair);
2538 	rc = spdk_nvmf_tcp_sock_process(tqpair);
2539 
2540 	/* check the following two factors:
2541 	 * rc: The socket is closed
2542 	 * State of tqpair: The tqpair is in EXITING state due to internal error
2543 	 */
2544 	if ((rc < 0) || (tqpair->state == NVME_TCP_QPAIR_STATE_EXITING)) {
2545 		tqpair->state = NVME_TCP_QPAIR_STATE_EXITED;
2546 		spdk_nvmf_tcp_qpair_flush_pdus(tqpair);
2547 		SPDK_DEBUGLOG(SPDK_LOG_NVMF_TCP, "will disconect the tqpair=%p\n", tqpair);
2548 		spdk_poller_unregister(&tqpair->timeout_poller);
2549 		spdk_nvmf_qpair_disconnect(&tqpair->qpair, NULL, NULL);
2550 	}
2551 }
2552 
2553 static int
2554 spdk_nvmf_tcp_poll_group_add(struct spdk_nvmf_transport_poll_group *group,
2555 			     struct spdk_nvmf_qpair *qpair)
2556 {
2557 	struct spdk_nvmf_tcp_poll_group	*tgroup;
2558 	struct spdk_nvmf_tcp_qpair	*tqpair;
2559 	int				rc;
2560 
2561 	tgroup = SPDK_CONTAINEROF(group, struct spdk_nvmf_tcp_poll_group, group);
2562 	tqpair = SPDK_CONTAINEROF(qpair, struct spdk_nvmf_tcp_qpair, qpair);
2563 
2564 	rc = spdk_sock_group_add_sock(tgroup->sock_group, tqpair->sock,
2565 				      spdk_nvmf_tcp_sock_cb, tqpair);
2566 	if (rc != 0) {
2567 		SPDK_ERRLOG("Could not add sock to sock_group: %s (%d)\n",
2568 			    spdk_strerror(errno), errno);
2569 		spdk_nvmf_tcp_qpair_destroy(tqpair);
2570 		return -1;
2571 	}
2572 
2573 	rc =  spdk_nvmf_tcp_qpair_sock_init(tqpair);
2574 	if (rc != 0) {
2575 		SPDK_ERRLOG("Cannot set sock opt for tqpair=%p\n", tqpair);
2576 		spdk_nvmf_tcp_qpair_destroy(tqpair);
2577 		return -1;
2578 	}
2579 
2580 	rc = spdk_nvmf_tcp_qpair_init(&tqpair->qpair);
2581 	if (rc < 0) {
2582 		SPDK_ERRLOG("Cannot init tqpair=%p\n", tqpair);
2583 		spdk_nvmf_tcp_qpair_destroy(tqpair);
2584 		return -1;
2585 	}
2586 
2587 	rc = spdk_nvmf_tcp_qpair_init_mem_resource(tqpair, 1);
2588 	if (rc < 0) {
2589 		SPDK_ERRLOG("Cannot init memory resource info for tqpair=%p\n", tqpair);
2590 		spdk_nvmf_tcp_qpair_destroy(tqpair);
2591 		return -1;
2592 	}
2593 
2594 	tqpair->group = tgroup;
2595 	tqpair->state = NVME_TCP_QPAIR_STATE_INVALID;
2596 	TAILQ_INSERT_TAIL(&tgroup->qpairs, tqpair, link);
2597 
2598 	return 0;
2599 }
2600 
2601 static int
2602 spdk_nvmf_tcp_poll_group_remove(struct spdk_nvmf_transport_poll_group *group,
2603 				struct spdk_nvmf_qpair *qpair)
2604 {
2605 	struct spdk_nvmf_tcp_poll_group	*tgroup;
2606 	struct spdk_nvmf_tcp_qpair		*tqpair;
2607 	int				rc;
2608 
2609 	tgroup = SPDK_CONTAINEROF(group, struct spdk_nvmf_tcp_poll_group, group);
2610 	tqpair = SPDK_CONTAINEROF(qpair, struct spdk_nvmf_tcp_qpair, qpair);
2611 
2612 	assert(tqpair->group == tgroup);
2613 
2614 	SPDK_DEBUGLOG(SPDK_LOG_NVMF_TCP, "remove tqpair=%p from the tgroup=%p\n", tqpair, tgroup);
2615 	TAILQ_REMOVE(&tgroup->qpairs, tqpair, link);
2616 	rc = spdk_sock_group_remove_sock(tgroup->sock_group, tqpair->sock);
2617 	if (rc != 0) {
2618 		SPDK_ERRLOG("Could not remove sock from sock_group: %s (%d)\n",
2619 			    spdk_strerror(errno), errno);
2620 	}
2621 
2622 	return rc;
2623 }
2624 
2625 static int
2626 spdk_nvmf_tcp_req_complete(struct spdk_nvmf_request *req)
2627 {
2628 	struct spdk_nvmf_tcp_transport *ttransport;
2629 	struct spdk_nvmf_tcp_req *tcp_req;
2630 
2631 	ttransport = SPDK_CONTAINEROF(req->qpair->transport, struct spdk_nvmf_tcp_transport, transport);
2632 	tcp_req = SPDK_CONTAINEROF(req, struct spdk_nvmf_tcp_req, req);
2633 
2634 	spdk_nvmf_tcp_req_set_state(tcp_req, TCP_REQUEST_STATE_EXECUTED);
2635 	spdk_nvmf_tcp_req_process(ttransport, tcp_req);
2636 
2637 	return 0;
2638 }
2639 
2640 static void
2641 spdk_nvmf_tcp_close_qpair(struct spdk_nvmf_qpair *qpair)
2642 {
2643 	SPDK_DEBUGLOG(SPDK_LOG_NVMF_TCP, "enter\n");
2644 
2645 	spdk_nvmf_tcp_qpair_destroy(SPDK_CONTAINEROF(qpair, struct spdk_nvmf_tcp_qpair, qpair));
2646 }
2647 
2648 static int
2649 spdk_nvmf_tcp_poll_group_poll(struct spdk_nvmf_transport_poll_group *group)
2650 {
2651 	struct spdk_nvmf_tcp_poll_group *tgroup;
2652 	int rc;
2653 
2654 	tgroup = SPDK_CONTAINEROF(group, struct spdk_nvmf_tcp_poll_group, group);
2655 
2656 	if (spdk_unlikely(TAILQ_EMPTY(&tgroup->qpairs))) {
2657 		return 0;
2658 	}
2659 
2660 	rc = spdk_sock_group_poll(tgroup->sock_group);
2661 	if (rc < 0) {
2662 		SPDK_ERRLOG("Failed to poll sock_group=%p\n", tgroup->sock_group);
2663 		return rc;
2664 	}
2665 
2666 	return 0;
2667 }
2668 
2669 static int
2670 spdk_nvmf_tcp_qpair_get_trid(struct spdk_nvmf_qpair *qpair,
2671 			     struct spdk_nvme_transport_id *trid, bool peer)
2672 {
2673 	struct spdk_nvmf_tcp_qpair     *tqpair;
2674 	uint16_t			port;
2675 
2676 	tqpair = SPDK_CONTAINEROF(qpair, struct spdk_nvmf_tcp_qpair, qpair);
2677 	trid->trtype = SPDK_NVME_TRANSPORT_TCP;
2678 
2679 	if (peer) {
2680 		snprintf(trid->traddr, sizeof(trid->traddr), "%s", tqpair->initiator_addr);
2681 		port = tqpair->initiator_port;
2682 	} else {
2683 		snprintf(trid->traddr, sizeof(trid->traddr), "%s", tqpair->target_addr);
2684 		port = tqpair->target_port;
2685 	}
2686 
2687 	if (spdk_sock_is_ipv4(tqpair->sock)) {
2688 		trid->adrfam = SPDK_NVMF_ADRFAM_IPV4;
2689 	} else if (spdk_sock_is_ipv4(tqpair->sock)) {
2690 		trid->adrfam = SPDK_NVMF_ADRFAM_IPV6;
2691 	} else {
2692 		return -1;
2693 	}
2694 
2695 	snprintf(trid->trsvcid, sizeof(trid->trsvcid), "%d", port);
2696 	return 0;
2697 }
2698 
2699 static int
2700 spdk_nvmf_tcp_qpair_get_local_trid(struct spdk_nvmf_qpair *qpair,
2701 				   struct spdk_nvme_transport_id *trid)
2702 {
2703 	return spdk_nvmf_tcp_qpair_get_trid(qpair, trid, 0);
2704 }
2705 
2706 static int
2707 spdk_nvmf_tcp_qpair_get_peer_trid(struct spdk_nvmf_qpair *qpair,
2708 				  struct spdk_nvme_transport_id *trid)
2709 {
2710 	return spdk_nvmf_tcp_qpair_get_trid(qpair, trid, 1);
2711 }
2712 
2713 static int
2714 spdk_nvmf_tcp_qpair_get_listen_trid(struct spdk_nvmf_qpair *qpair,
2715 				    struct spdk_nvme_transport_id *trid)
2716 {
2717 	return spdk_nvmf_tcp_qpair_get_trid(qpair, trid, 0);
2718 }
2719 
2720 static int
2721 spdk_nvmf_tcp_qpair_set_sq_size(struct spdk_nvmf_qpair *qpair)
2722 {
2723 	struct spdk_nvmf_tcp_qpair     *tqpair;
2724 	int rc;
2725 	tqpair = SPDK_CONTAINEROF(qpair, struct spdk_nvmf_tcp_qpair, qpair);
2726 
2727 	rc = spdk_nvmf_tcp_qpair_init_mem_resource(tqpair, tqpair->qpair.sq_head_max);
2728 	if (!rc) {
2729 		tqpair->max_queue_depth += tqpair->qpair.sq_head_max;
2730 		tqpair->free_pdu_num += tqpair->qpair.sq_head_max;
2731 		tqpair->state_cntr[TCP_REQUEST_STATE_FREE] += tqpair->qpair.sq_head_max;
2732 		SPDK_DEBUGLOG(SPDK_LOG_NVMF_TCP, "The queue depth=%u for tqpair=%p\n",
2733 			      tqpair->max_queue_depth, tqpair);
2734 	}
2735 
2736 	return rc;
2737 
2738 }
2739 
2740 #define SPDK_NVMF_TCP_DEFAULT_MAX_QUEUE_DEPTH 128
2741 #define SPDK_NVMF_TCP_DEFAULT_AQ_DEPTH 128
2742 #define SPDK_NVMF_TCP_DEFAULT_MAX_QPAIRS_PER_CTRLR 128
2743 #define SPDK_NVMF_TCP_DEFAULT_IN_CAPSULE_DATA_SIZE 4096
2744 #define SPDK_NVMF_TCP_DEFAULT_MAX_IO_SIZE 131072
2745 #define SPDK_NVMF_TCP_DEFAULT_IO_UNIT_SIZE 131072
2746 #define SPDK_NVMF_TCP_DEFAULT_NUM_SHARED_BUFFERS 511
2747 #define SPDK_NVMF_TCP_DEFAULT_BUFFER_CACHE_SIZE 32
2748 #define SPDK_NVMF_TCP_DEFAULT_SUCCESS_OPTIMIZATION true
2749 
2750 static void
2751 spdk_nvmf_tcp_opts_init(struct spdk_nvmf_transport_opts *opts)
2752 {
2753 	opts->max_queue_depth =		SPDK_NVMF_TCP_DEFAULT_MAX_QUEUE_DEPTH;
2754 	opts->max_qpairs_per_ctrlr =	SPDK_NVMF_TCP_DEFAULT_MAX_QPAIRS_PER_CTRLR;
2755 	opts->in_capsule_data_size =	SPDK_NVMF_TCP_DEFAULT_IN_CAPSULE_DATA_SIZE;
2756 	opts->max_io_size =		SPDK_NVMF_TCP_DEFAULT_MAX_IO_SIZE;
2757 	opts->io_unit_size =		SPDK_NVMF_TCP_DEFAULT_IO_UNIT_SIZE;
2758 	opts->max_aq_depth =		SPDK_NVMF_TCP_DEFAULT_AQ_DEPTH;
2759 	opts->num_shared_buffers =	SPDK_NVMF_TCP_DEFAULT_NUM_SHARED_BUFFERS;
2760 	opts->buf_cache_size =		SPDK_NVMF_TCP_DEFAULT_BUFFER_CACHE_SIZE;
2761 	opts->c2h_success =		SPDK_NVMF_TCP_DEFAULT_SUCCESS_OPTIMIZATION;
2762 }
2763 
2764 const struct spdk_nvmf_transport_ops spdk_nvmf_transport_tcp = {
2765 	.type = SPDK_NVME_TRANSPORT_TCP,
2766 	.opts_init = spdk_nvmf_tcp_opts_init,
2767 	.create = spdk_nvmf_tcp_create,
2768 	.destroy = spdk_nvmf_tcp_destroy,
2769 
2770 	.listen = spdk_nvmf_tcp_listen,
2771 	.stop_listen = spdk_nvmf_tcp_stop_listen,
2772 	.accept = spdk_nvmf_tcp_accept,
2773 
2774 	.listener_discover = spdk_nvmf_tcp_discover,
2775 
2776 	.poll_group_create = spdk_nvmf_tcp_poll_group_create,
2777 	.poll_group_destroy = spdk_nvmf_tcp_poll_group_destroy,
2778 	.poll_group_add = spdk_nvmf_tcp_poll_group_add,
2779 	.poll_group_remove = spdk_nvmf_tcp_poll_group_remove,
2780 	.poll_group_poll = spdk_nvmf_tcp_poll_group_poll,
2781 
2782 	.req_free = spdk_nvmf_tcp_req_free,
2783 	.req_complete = spdk_nvmf_tcp_req_complete,
2784 
2785 	.qpair_fini = spdk_nvmf_tcp_close_qpair,
2786 	.qpair_get_local_trid = spdk_nvmf_tcp_qpair_get_local_trid,
2787 	.qpair_get_peer_trid = spdk_nvmf_tcp_qpair_get_peer_trid,
2788 	.qpair_get_listen_trid = spdk_nvmf_tcp_qpair_get_listen_trid,
2789 	.qpair_set_sqsize = spdk_nvmf_tcp_qpair_set_sq_size,
2790 };
2791 
2792 SPDK_LOG_REGISTER_COMPONENT("nvmf_tcp", SPDK_LOG_NVMF_TCP)
2793