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