xref: /linux/drivers/nvme/target/tcp.c (revision db1ecca22edf27c5a3dd66af406c88b5b5ac7cc1)
1 // SPDX-License-Identifier: GPL-2.0
2 /*
3  * NVMe over Fabrics TCP target.
4  * Copyright (c) 2018 Lightbits Labs. All rights reserved.
5  */
6 #define pr_fmt(fmt) KBUILD_MODNAME ": " fmt
7 #include <linux/module.h>
8 #include <linux/init.h>
9 #include <linux/slab.h>
10 #include <linux/err.h>
11 #include <linux/key.h>
12 #include <linux/nvme-tcp.h>
13 #include <linux/nvme-keyring.h>
14 #include <net/sock.h>
15 #include <net/tcp.h>
16 #include <net/tls.h>
17 #include <net/tls_prot.h>
18 #include <net/handshake.h>
19 #include <linux/inet.h>
20 #include <linux/llist.h>
21 #include <crypto/hash.h>
22 #include <trace/events/sock.h>
23 
24 #include "nvmet.h"
25 
26 #define NVMET_TCP_DEF_INLINE_DATA_SIZE	(4 * PAGE_SIZE)
27 
28 static int param_store_val(const char *str, int *val, int min, int max)
29 {
30 	int ret, new_val;
31 
32 	ret = kstrtoint(str, 10, &new_val);
33 	if (ret)
34 		return -EINVAL;
35 
36 	if (new_val < min || new_val > max)
37 		return -EINVAL;
38 
39 	*val = new_val;
40 	return 0;
41 }
42 
43 static int set_params(const char *str, const struct kernel_param *kp)
44 {
45 	return param_store_val(str, kp->arg, 0, INT_MAX);
46 }
47 
48 static const struct kernel_param_ops set_param_ops = {
49 	.set	= set_params,
50 	.get	= param_get_int,
51 };
52 
53 /* Define the socket priority to use for connections were it is desirable
54  * that the NIC consider performing optimized packet processing or filtering.
55  * A non-zero value being sufficient to indicate general consideration of any
56  * possible optimization.  Making it a module param allows for alternative
57  * values that may be unique for some NIC implementations.
58  */
59 static int so_priority;
60 device_param_cb(so_priority, &set_param_ops, &so_priority, 0644);
61 MODULE_PARM_DESC(so_priority, "nvmet tcp socket optimize priority: Default 0");
62 
63 /* Define a time period (in usecs) that io_work() shall sample an activated
64  * queue before determining it to be idle.  This optional module behavior
65  * can enable NIC solutions that support socket optimized packet processing
66  * using advanced interrupt moderation techniques.
67  */
68 static int idle_poll_period_usecs;
69 device_param_cb(idle_poll_period_usecs, &set_param_ops,
70 		&idle_poll_period_usecs, 0644);
71 MODULE_PARM_DESC(idle_poll_period_usecs,
72 		"nvmet tcp io_work poll till idle time period in usecs: Default 0");
73 
74 #ifdef CONFIG_NVME_TARGET_TCP_TLS
75 /*
76  * TLS handshake timeout
77  */
78 static int tls_handshake_timeout = 10;
79 module_param(tls_handshake_timeout, int, 0644);
80 MODULE_PARM_DESC(tls_handshake_timeout,
81 		 "nvme TLS handshake timeout in seconds (default 10)");
82 #endif
83 
84 #define NVMET_TCP_RECV_BUDGET		8
85 #define NVMET_TCP_SEND_BUDGET		8
86 #define NVMET_TCP_IO_WORK_BUDGET	64
87 
88 enum nvmet_tcp_send_state {
89 	NVMET_TCP_SEND_DATA_PDU,
90 	NVMET_TCP_SEND_DATA,
91 	NVMET_TCP_SEND_R2T,
92 	NVMET_TCP_SEND_DDGST,
93 	NVMET_TCP_SEND_RESPONSE
94 };
95 
96 enum nvmet_tcp_recv_state {
97 	NVMET_TCP_RECV_PDU,
98 	NVMET_TCP_RECV_DATA,
99 	NVMET_TCP_RECV_DDGST,
100 	NVMET_TCP_RECV_ERR,
101 };
102 
103 enum {
104 	NVMET_TCP_F_INIT_FAILED = (1 << 0),
105 };
106 
107 struct nvmet_tcp_cmd {
108 	struct nvmet_tcp_queue		*queue;
109 	struct nvmet_req		req;
110 
111 	struct nvme_tcp_cmd_pdu		*cmd_pdu;
112 	struct nvme_tcp_rsp_pdu		*rsp_pdu;
113 	struct nvme_tcp_data_pdu	*data_pdu;
114 	struct nvme_tcp_r2t_pdu		*r2t_pdu;
115 
116 	u32				rbytes_done;
117 	u32				wbytes_done;
118 
119 	u32				pdu_len;
120 	u32				pdu_recv;
121 	int				sg_idx;
122 	char				recv_cbuf[CMSG_LEN(sizeof(char))];
123 	struct msghdr			recv_msg;
124 	struct bio_vec			*iov;
125 	u32				flags;
126 
127 	struct list_head		entry;
128 	struct llist_node		lentry;
129 
130 	/* send state */
131 	u32				offset;
132 	struct scatterlist		*cur_sg;
133 	enum nvmet_tcp_send_state	state;
134 
135 	__le32				exp_ddgst;
136 	__le32				recv_ddgst;
137 };
138 
139 enum nvmet_tcp_queue_state {
140 	NVMET_TCP_Q_CONNECTING,
141 	NVMET_TCP_Q_TLS_HANDSHAKE,
142 	NVMET_TCP_Q_LIVE,
143 	NVMET_TCP_Q_DISCONNECTING,
144 	NVMET_TCP_Q_FAILED,
145 };
146 
147 struct nvmet_tcp_queue {
148 	struct socket		*sock;
149 	struct nvmet_tcp_port	*port;
150 	struct work_struct	io_work;
151 	struct nvmet_cq		nvme_cq;
152 	struct nvmet_sq		nvme_sq;
153 	struct kref		kref;
154 
155 	/* send state */
156 	struct nvmet_tcp_cmd	*cmds;
157 	unsigned int		nr_cmds;
158 	struct list_head	free_list;
159 	struct llist_head	resp_list;
160 	struct list_head	resp_send_list;
161 	int			send_list_len;
162 	struct nvmet_tcp_cmd	*snd_cmd;
163 
164 	/* recv state */
165 	int			offset;
166 	int			left;
167 	enum nvmet_tcp_recv_state rcv_state;
168 	struct nvmet_tcp_cmd	*cmd;
169 	union nvme_tcp_pdu	pdu;
170 
171 	/* digest state */
172 	bool			hdr_digest;
173 	bool			data_digest;
174 	struct ahash_request	*snd_hash;
175 	struct ahash_request	*rcv_hash;
176 
177 	/* TLS state */
178 	key_serial_t		tls_pskid;
179 	struct delayed_work	tls_handshake_tmo_work;
180 
181 	unsigned long           poll_end;
182 
183 	spinlock_t		state_lock;
184 	enum nvmet_tcp_queue_state state;
185 
186 	struct sockaddr_storage	sockaddr;
187 	struct sockaddr_storage	sockaddr_peer;
188 	struct work_struct	release_work;
189 
190 	int			idx;
191 	struct list_head	queue_list;
192 
193 	struct nvmet_tcp_cmd	connect;
194 
195 	struct page_frag_cache	pf_cache;
196 
197 	void (*data_ready)(struct sock *);
198 	void (*state_change)(struct sock *);
199 	void (*write_space)(struct sock *);
200 };
201 
202 struct nvmet_tcp_port {
203 	struct socket		*sock;
204 	struct work_struct	accept_work;
205 	struct nvmet_port	*nport;
206 	struct sockaddr_storage addr;
207 	void (*data_ready)(struct sock *);
208 };
209 
210 static DEFINE_IDA(nvmet_tcp_queue_ida);
211 static LIST_HEAD(nvmet_tcp_queue_list);
212 static DEFINE_MUTEX(nvmet_tcp_queue_mutex);
213 
214 static struct workqueue_struct *nvmet_tcp_wq;
215 static const struct nvmet_fabrics_ops nvmet_tcp_ops;
216 static void nvmet_tcp_free_cmd(struct nvmet_tcp_cmd *c);
217 static void nvmet_tcp_free_cmd_buffers(struct nvmet_tcp_cmd *cmd);
218 
219 static inline u16 nvmet_tcp_cmd_tag(struct nvmet_tcp_queue *queue,
220 		struct nvmet_tcp_cmd *cmd)
221 {
222 	if (unlikely(!queue->nr_cmds)) {
223 		/* We didn't allocate cmds yet, send 0xffff */
224 		return USHRT_MAX;
225 	}
226 
227 	return cmd - queue->cmds;
228 }
229 
230 static inline bool nvmet_tcp_has_data_in(struct nvmet_tcp_cmd *cmd)
231 {
232 	return nvme_is_write(cmd->req.cmd) &&
233 		cmd->rbytes_done < cmd->req.transfer_len;
234 }
235 
236 static inline bool nvmet_tcp_need_data_in(struct nvmet_tcp_cmd *cmd)
237 {
238 	return nvmet_tcp_has_data_in(cmd) && !cmd->req.cqe->status;
239 }
240 
241 static inline bool nvmet_tcp_need_data_out(struct nvmet_tcp_cmd *cmd)
242 {
243 	return !nvme_is_write(cmd->req.cmd) &&
244 		cmd->req.transfer_len > 0 &&
245 		!cmd->req.cqe->status;
246 }
247 
248 static inline bool nvmet_tcp_has_inline_data(struct nvmet_tcp_cmd *cmd)
249 {
250 	return nvme_is_write(cmd->req.cmd) && cmd->pdu_len &&
251 		!cmd->rbytes_done;
252 }
253 
254 static inline struct nvmet_tcp_cmd *
255 nvmet_tcp_get_cmd(struct nvmet_tcp_queue *queue)
256 {
257 	struct nvmet_tcp_cmd *cmd;
258 
259 	cmd = list_first_entry_or_null(&queue->free_list,
260 				struct nvmet_tcp_cmd, entry);
261 	if (!cmd)
262 		return NULL;
263 	list_del_init(&cmd->entry);
264 
265 	cmd->rbytes_done = cmd->wbytes_done = 0;
266 	cmd->pdu_len = 0;
267 	cmd->pdu_recv = 0;
268 	cmd->iov = NULL;
269 	cmd->flags = 0;
270 	return cmd;
271 }
272 
273 static inline void nvmet_tcp_put_cmd(struct nvmet_tcp_cmd *cmd)
274 {
275 	if (unlikely(cmd == &cmd->queue->connect))
276 		return;
277 
278 	list_add_tail(&cmd->entry, &cmd->queue->free_list);
279 }
280 
281 static inline int queue_cpu(struct nvmet_tcp_queue *queue)
282 {
283 	return queue->sock->sk->sk_incoming_cpu;
284 }
285 
286 static inline u8 nvmet_tcp_hdgst_len(struct nvmet_tcp_queue *queue)
287 {
288 	return queue->hdr_digest ? NVME_TCP_DIGEST_LENGTH : 0;
289 }
290 
291 static inline u8 nvmet_tcp_ddgst_len(struct nvmet_tcp_queue *queue)
292 {
293 	return queue->data_digest ? NVME_TCP_DIGEST_LENGTH : 0;
294 }
295 
296 static inline void nvmet_tcp_hdgst(struct ahash_request *hash,
297 		void *pdu, size_t len)
298 {
299 	struct scatterlist sg;
300 
301 	sg_init_one(&sg, pdu, len);
302 	ahash_request_set_crypt(hash, &sg, pdu + len, len);
303 	crypto_ahash_digest(hash);
304 }
305 
306 static int nvmet_tcp_verify_hdgst(struct nvmet_tcp_queue *queue,
307 	void *pdu, size_t len)
308 {
309 	struct nvme_tcp_hdr *hdr = pdu;
310 	__le32 recv_digest;
311 	__le32 exp_digest;
312 
313 	if (unlikely(!(hdr->flags & NVME_TCP_F_HDGST))) {
314 		pr_err("queue %d: header digest enabled but no header digest\n",
315 			queue->idx);
316 		return -EPROTO;
317 	}
318 
319 	recv_digest = *(__le32 *)(pdu + hdr->hlen);
320 	nvmet_tcp_hdgst(queue->rcv_hash, pdu, len);
321 	exp_digest = *(__le32 *)(pdu + hdr->hlen);
322 	if (recv_digest != exp_digest) {
323 		pr_err("queue %d: header digest error: recv %#x expected %#x\n",
324 			queue->idx, le32_to_cpu(recv_digest),
325 			le32_to_cpu(exp_digest));
326 		return -EPROTO;
327 	}
328 
329 	return 0;
330 }
331 
332 static int nvmet_tcp_check_ddgst(struct nvmet_tcp_queue *queue, void *pdu)
333 {
334 	struct nvme_tcp_hdr *hdr = pdu;
335 	u8 digest_len = nvmet_tcp_hdgst_len(queue);
336 	u32 len;
337 
338 	len = le32_to_cpu(hdr->plen) - hdr->hlen -
339 		(hdr->flags & NVME_TCP_F_HDGST ? digest_len : 0);
340 
341 	if (unlikely(len && !(hdr->flags & NVME_TCP_F_DDGST))) {
342 		pr_err("queue %d: data digest flag is cleared\n", queue->idx);
343 		return -EPROTO;
344 	}
345 
346 	return 0;
347 }
348 
349 static void nvmet_tcp_free_cmd_buffers(struct nvmet_tcp_cmd *cmd)
350 {
351 	kfree(cmd->iov);
352 	sgl_free(cmd->req.sg);
353 	cmd->iov = NULL;
354 	cmd->req.sg = NULL;
355 }
356 
357 static void nvmet_tcp_build_pdu_iovec(struct nvmet_tcp_cmd *cmd)
358 {
359 	struct bio_vec *iov = cmd->iov;
360 	struct scatterlist *sg;
361 	u32 length, offset, sg_offset;
362 	int nr_pages;
363 
364 	length = cmd->pdu_len;
365 	nr_pages = DIV_ROUND_UP(length, PAGE_SIZE);
366 	offset = cmd->rbytes_done;
367 	cmd->sg_idx = offset / PAGE_SIZE;
368 	sg_offset = offset % PAGE_SIZE;
369 	sg = &cmd->req.sg[cmd->sg_idx];
370 
371 	while (length) {
372 		u32 iov_len = min_t(u32, length, sg->length - sg_offset);
373 
374 		bvec_set_page(iov, sg_page(sg), iov_len,
375 				sg->offset + sg_offset);
376 
377 		length -= iov_len;
378 		sg = sg_next(sg);
379 		iov++;
380 		sg_offset = 0;
381 	}
382 
383 	iov_iter_bvec(&cmd->recv_msg.msg_iter, ITER_DEST, cmd->iov,
384 		      nr_pages, cmd->pdu_len);
385 }
386 
387 static void nvmet_tcp_fatal_error(struct nvmet_tcp_queue *queue)
388 {
389 	queue->rcv_state = NVMET_TCP_RECV_ERR;
390 	if (queue->nvme_sq.ctrl)
391 		nvmet_ctrl_fatal_error(queue->nvme_sq.ctrl);
392 	else
393 		kernel_sock_shutdown(queue->sock, SHUT_RDWR);
394 }
395 
396 static void nvmet_tcp_socket_error(struct nvmet_tcp_queue *queue, int status)
397 {
398 	queue->rcv_state = NVMET_TCP_RECV_ERR;
399 	if (status == -EPIPE || status == -ECONNRESET)
400 		kernel_sock_shutdown(queue->sock, SHUT_RDWR);
401 	else
402 		nvmet_tcp_fatal_error(queue);
403 }
404 
405 static int nvmet_tcp_map_data(struct nvmet_tcp_cmd *cmd)
406 {
407 	struct nvme_sgl_desc *sgl = &cmd->req.cmd->common.dptr.sgl;
408 	u32 len = le32_to_cpu(sgl->length);
409 
410 	if (!len)
411 		return 0;
412 
413 	if (sgl->type == ((NVME_SGL_FMT_DATA_DESC << 4) |
414 			  NVME_SGL_FMT_OFFSET)) {
415 		if (!nvme_is_write(cmd->req.cmd))
416 			return NVME_SC_INVALID_FIELD | NVME_SC_DNR;
417 
418 		if (len > cmd->req.port->inline_data_size)
419 			return NVME_SC_SGL_INVALID_OFFSET | NVME_SC_DNR;
420 		cmd->pdu_len = len;
421 	}
422 	cmd->req.transfer_len += len;
423 
424 	cmd->req.sg = sgl_alloc(len, GFP_KERNEL, &cmd->req.sg_cnt);
425 	if (!cmd->req.sg)
426 		return NVME_SC_INTERNAL;
427 	cmd->cur_sg = cmd->req.sg;
428 
429 	if (nvmet_tcp_has_data_in(cmd)) {
430 		cmd->iov = kmalloc_array(cmd->req.sg_cnt,
431 				sizeof(*cmd->iov), GFP_KERNEL);
432 		if (!cmd->iov)
433 			goto err;
434 	}
435 
436 	return 0;
437 err:
438 	nvmet_tcp_free_cmd_buffers(cmd);
439 	return NVME_SC_INTERNAL;
440 }
441 
442 static void nvmet_tcp_calc_ddgst(struct ahash_request *hash,
443 		struct nvmet_tcp_cmd *cmd)
444 {
445 	ahash_request_set_crypt(hash, cmd->req.sg,
446 		(void *)&cmd->exp_ddgst, cmd->req.transfer_len);
447 	crypto_ahash_digest(hash);
448 }
449 
450 static void nvmet_setup_c2h_data_pdu(struct nvmet_tcp_cmd *cmd)
451 {
452 	struct nvme_tcp_data_pdu *pdu = cmd->data_pdu;
453 	struct nvmet_tcp_queue *queue = cmd->queue;
454 	u8 hdgst = nvmet_tcp_hdgst_len(cmd->queue);
455 	u8 ddgst = nvmet_tcp_ddgst_len(cmd->queue);
456 
457 	cmd->offset = 0;
458 	cmd->state = NVMET_TCP_SEND_DATA_PDU;
459 
460 	pdu->hdr.type = nvme_tcp_c2h_data;
461 	pdu->hdr.flags = NVME_TCP_F_DATA_LAST | (queue->nvme_sq.sqhd_disabled ?
462 						NVME_TCP_F_DATA_SUCCESS : 0);
463 	pdu->hdr.hlen = sizeof(*pdu);
464 	pdu->hdr.pdo = pdu->hdr.hlen + hdgst;
465 	pdu->hdr.plen =
466 		cpu_to_le32(pdu->hdr.hlen + hdgst +
467 				cmd->req.transfer_len + ddgst);
468 	pdu->command_id = cmd->req.cqe->command_id;
469 	pdu->data_length = cpu_to_le32(cmd->req.transfer_len);
470 	pdu->data_offset = cpu_to_le32(cmd->wbytes_done);
471 
472 	if (queue->data_digest) {
473 		pdu->hdr.flags |= NVME_TCP_F_DDGST;
474 		nvmet_tcp_calc_ddgst(queue->snd_hash, cmd);
475 	}
476 
477 	if (cmd->queue->hdr_digest) {
478 		pdu->hdr.flags |= NVME_TCP_F_HDGST;
479 		nvmet_tcp_hdgst(queue->snd_hash, pdu, sizeof(*pdu));
480 	}
481 }
482 
483 static void nvmet_setup_r2t_pdu(struct nvmet_tcp_cmd *cmd)
484 {
485 	struct nvme_tcp_r2t_pdu *pdu = cmd->r2t_pdu;
486 	struct nvmet_tcp_queue *queue = cmd->queue;
487 	u8 hdgst = nvmet_tcp_hdgst_len(cmd->queue);
488 
489 	cmd->offset = 0;
490 	cmd->state = NVMET_TCP_SEND_R2T;
491 
492 	pdu->hdr.type = nvme_tcp_r2t;
493 	pdu->hdr.flags = 0;
494 	pdu->hdr.hlen = sizeof(*pdu);
495 	pdu->hdr.pdo = 0;
496 	pdu->hdr.plen = cpu_to_le32(pdu->hdr.hlen + hdgst);
497 
498 	pdu->command_id = cmd->req.cmd->common.command_id;
499 	pdu->ttag = nvmet_tcp_cmd_tag(cmd->queue, cmd);
500 	pdu->r2t_length = cpu_to_le32(cmd->req.transfer_len - cmd->rbytes_done);
501 	pdu->r2t_offset = cpu_to_le32(cmd->rbytes_done);
502 	if (cmd->queue->hdr_digest) {
503 		pdu->hdr.flags |= NVME_TCP_F_HDGST;
504 		nvmet_tcp_hdgst(queue->snd_hash, pdu, sizeof(*pdu));
505 	}
506 }
507 
508 static void nvmet_setup_response_pdu(struct nvmet_tcp_cmd *cmd)
509 {
510 	struct nvme_tcp_rsp_pdu *pdu = cmd->rsp_pdu;
511 	struct nvmet_tcp_queue *queue = cmd->queue;
512 	u8 hdgst = nvmet_tcp_hdgst_len(cmd->queue);
513 
514 	cmd->offset = 0;
515 	cmd->state = NVMET_TCP_SEND_RESPONSE;
516 
517 	pdu->hdr.type = nvme_tcp_rsp;
518 	pdu->hdr.flags = 0;
519 	pdu->hdr.hlen = sizeof(*pdu);
520 	pdu->hdr.pdo = 0;
521 	pdu->hdr.plen = cpu_to_le32(pdu->hdr.hlen + hdgst);
522 	if (cmd->queue->hdr_digest) {
523 		pdu->hdr.flags |= NVME_TCP_F_HDGST;
524 		nvmet_tcp_hdgst(queue->snd_hash, pdu, sizeof(*pdu));
525 	}
526 }
527 
528 static void nvmet_tcp_process_resp_list(struct nvmet_tcp_queue *queue)
529 {
530 	struct llist_node *node;
531 	struct nvmet_tcp_cmd *cmd;
532 
533 	for (node = llist_del_all(&queue->resp_list); node; node = node->next) {
534 		cmd = llist_entry(node, struct nvmet_tcp_cmd, lentry);
535 		list_add(&cmd->entry, &queue->resp_send_list);
536 		queue->send_list_len++;
537 	}
538 }
539 
540 static struct nvmet_tcp_cmd *nvmet_tcp_fetch_cmd(struct nvmet_tcp_queue *queue)
541 {
542 	queue->snd_cmd = list_first_entry_or_null(&queue->resp_send_list,
543 				struct nvmet_tcp_cmd, entry);
544 	if (!queue->snd_cmd) {
545 		nvmet_tcp_process_resp_list(queue);
546 		queue->snd_cmd =
547 			list_first_entry_or_null(&queue->resp_send_list,
548 					struct nvmet_tcp_cmd, entry);
549 		if (unlikely(!queue->snd_cmd))
550 			return NULL;
551 	}
552 
553 	list_del_init(&queue->snd_cmd->entry);
554 	queue->send_list_len--;
555 
556 	if (nvmet_tcp_need_data_out(queue->snd_cmd))
557 		nvmet_setup_c2h_data_pdu(queue->snd_cmd);
558 	else if (nvmet_tcp_need_data_in(queue->snd_cmd))
559 		nvmet_setup_r2t_pdu(queue->snd_cmd);
560 	else
561 		nvmet_setup_response_pdu(queue->snd_cmd);
562 
563 	return queue->snd_cmd;
564 }
565 
566 static void nvmet_tcp_queue_response(struct nvmet_req *req)
567 {
568 	struct nvmet_tcp_cmd *cmd =
569 		container_of(req, struct nvmet_tcp_cmd, req);
570 	struct nvmet_tcp_queue	*queue = cmd->queue;
571 	struct nvme_sgl_desc *sgl;
572 	u32 len;
573 
574 	if (unlikely(cmd == queue->cmd)) {
575 		sgl = &cmd->req.cmd->common.dptr.sgl;
576 		len = le32_to_cpu(sgl->length);
577 
578 		/*
579 		 * Wait for inline data before processing the response.
580 		 * Avoid using helpers, this might happen before
581 		 * nvmet_req_init is completed.
582 		 */
583 		if (queue->rcv_state == NVMET_TCP_RECV_PDU &&
584 		    len && len <= cmd->req.port->inline_data_size &&
585 		    nvme_is_write(cmd->req.cmd))
586 			return;
587 	}
588 
589 	llist_add(&cmd->lentry, &queue->resp_list);
590 	queue_work_on(queue_cpu(queue), nvmet_tcp_wq, &cmd->queue->io_work);
591 }
592 
593 static void nvmet_tcp_execute_request(struct nvmet_tcp_cmd *cmd)
594 {
595 	if (unlikely(cmd->flags & NVMET_TCP_F_INIT_FAILED))
596 		nvmet_tcp_queue_response(&cmd->req);
597 	else
598 		cmd->req.execute(&cmd->req);
599 }
600 
601 static int nvmet_try_send_data_pdu(struct nvmet_tcp_cmd *cmd)
602 {
603 	struct msghdr msg = {
604 		.msg_flags = MSG_DONTWAIT | MSG_MORE | MSG_SPLICE_PAGES,
605 	};
606 	struct bio_vec bvec;
607 	u8 hdgst = nvmet_tcp_hdgst_len(cmd->queue);
608 	int left = sizeof(*cmd->data_pdu) - cmd->offset + hdgst;
609 	int ret;
610 
611 	bvec_set_virt(&bvec, (void *)cmd->data_pdu + cmd->offset, left);
612 	iov_iter_bvec(&msg.msg_iter, ITER_SOURCE, &bvec, 1, left);
613 	ret = sock_sendmsg(cmd->queue->sock, &msg);
614 	if (ret <= 0)
615 		return ret;
616 
617 	cmd->offset += ret;
618 	left -= ret;
619 
620 	if (left)
621 		return -EAGAIN;
622 
623 	cmd->state = NVMET_TCP_SEND_DATA;
624 	cmd->offset  = 0;
625 	return 1;
626 }
627 
628 static int nvmet_try_send_data(struct nvmet_tcp_cmd *cmd, bool last_in_batch)
629 {
630 	struct nvmet_tcp_queue *queue = cmd->queue;
631 	int ret;
632 
633 	while (cmd->cur_sg) {
634 		struct msghdr msg = {
635 			.msg_flags = MSG_DONTWAIT | MSG_SPLICE_PAGES,
636 		};
637 		struct page *page = sg_page(cmd->cur_sg);
638 		struct bio_vec bvec;
639 		u32 left = cmd->cur_sg->length - cmd->offset;
640 
641 		if ((!last_in_batch && cmd->queue->send_list_len) ||
642 		    cmd->wbytes_done + left < cmd->req.transfer_len ||
643 		    queue->data_digest || !queue->nvme_sq.sqhd_disabled)
644 			msg.msg_flags |= MSG_MORE;
645 
646 		bvec_set_page(&bvec, page, left, cmd->offset);
647 		iov_iter_bvec(&msg.msg_iter, ITER_SOURCE, &bvec, 1, left);
648 		ret = sock_sendmsg(cmd->queue->sock, &msg);
649 		if (ret <= 0)
650 			return ret;
651 
652 		cmd->offset += ret;
653 		cmd->wbytes_done += ret;
654 
655 		/* Done with sg?*/
656 		if (cmd->offset == cmd->cur_sg->length) {
657 			cmd->cur_sg = sg_next(cmd->cur_sg);
658 			cmd->offset = 0;
659 		}
660 	}
661 
662 	if (queue->data_digest) {
663 		cmd->state = NVMET_TCP_SEND_DDGST;
664 		cmd->offset = 0;
665 	} else {
666 		if (queue->nvme_sq.sqhd_disabled) {
667 			cmd->queue->snd_cmd = NULL;
668 			nvmet_tcp_put_cmd(cmd);
669 		} else {
670 			nvmet_setup_response_pdu(cmd);
671 		}
672 	}
673 
674 	if (queue->nvme_sq.sqhd_disabled)
675 		nvmet_tcp_free_cmd_buffers(cmd);
676 
677 	return 1;
678 
679 }
680 
681 static int nvmet_try_send_response(struct nvmet_tcp_cmd *cmd,
682 		bool last_in_batch)
683 {
684 	struct msghdr msg = { .msg_flags = MSG_DONTWAIT | MSG_SPLICE_PAGES, };
685 	struct bio_vec bvec;
686 	u8 hdgst = nvmet_tcp_hdgst_len(cmd->queue);
687 	int left = sizeof(*cmd->rsp_pdu) - cmd->offset + hdgst;
688 	int ret;
689 
690 	if (!last_in_batch && cmd->queue->send_list_len)
691 		msg.msg_flags |= MSG_MORE;
692 	else
693 		msg.msg_flags |= MSG_EOR;
694 
695 	bvec_set_virt(&bvec, (void *)cmd->rsp_pdu + cmd->offset, left);
696 	iov_iter_bvec(&msg.msg_iter, ITER_SOURCE, &bvec, 1, left);
697 	ret = sock_sendmsg(cmd->queue->sock, &msg);
698 	if (ret <= 0)
699 		return ret;
700 	cmd->offset += ret;
701 	left -= ret;
702 
703 	if (left)
704 		return -EAGAIN;
705 
706 	nvmet_tcp_free_cmd_buffers(cmd);
707 	cmd->queue->snd_cmd = NULL;
708 	nvmet_tcp_put_cmd(cmd);
709 	return 1;
710 }
711 
712 static int nvmet_try_send_r2t(struct nvmet_tcp_cmd *cmd, bool last_in_batch)
713 {
714 	struct msghdr msg = { .msg_flags = MSG_DONTWAIT | MSG_SPLICE_PAGES, };
715 	struct bio_vec bvec;
716 	u8 hdgst = nvmet_tcp_hdgst_len(cmd->queue);
717 	int left = sizeof(*cmd->r2t_pdu) - cmd->offset + hdgst;
718 	int ret;
719 
720 	if (!last_in_batch && cmd->queue->send_list_len)
721 		msg.msg_flags |= MSG_MORE;
722 	else
723 		msg.msg_flags |= MSG_EOR;
724 
725 	bvec_set_virt(&bvec, (void *)cmd->r2t_pdu + cmd->offset, left);
726 	iov_iter_bvec(&msg.msg_iter, ITER_SOURCE, &bvec, 1, left);
727 	ret = sock_sendmsg(cmd->queue->sock, &msg);
728 	if (ret <= 0)
729 		return ret;
730 	cmd->offset += ret;
731 	left -= ret;
732 
733 	if (left)
734 		return -EAGAIN;
735 
736 	cmd->queue->snd_cmd = NULL;
737 	return 1;
738 }
739 
740 static int nvmet_try_send_ddgst(struct nvmet_tcp_cmd *cmd, bool last_in_batch)
741 {
742 	struct nvmet_tcp_queue *queue = cmd->queue;
743 	int left = NVME_TCP_DIGEST_LENGTH - cmd->offset;
744 	struct msghdr msg = { .msg_flags = MSG_DONTWAIT };
745 	struct kvec iov = {
746 		.iov_base = (u8 *)&cmd->exp_ddgst + cmd->offset,
747 		.iov_len = left
748 	};
749 	int ret;
750 
751 	if (!last_in_batch && cmd->queue->send_list_len)
752 		msg.msg_flags |= MSG_MORE;
753 	else
754 		msg.msg_flags |= MSG_EOR;
755 
756 	ret = kernel_sendmsg(queue->sock, &msg, &iov, 1, iov.iov_len);
757 	if (unlikely(ret <= 0))
758 		return ret;
759 
760 	cmd->offset += ret;
761 	left -= ret;
762 
763 	if (left)
764 		return -EAGAIN;
765 
766 	if (queue->nvme_sq.sqhd_disabled) {
767 		cmd->queue->snd_cmd = NULL;
768 		nvmet_tcp_put_cmd(cmd);
769 	} else {
770 		nvmet_setup_response_pdu(cmd);
771 	}
772 	return 1;
773 }
774 
775 static int nvmet_tcp_try_send_one(struct nvmet_tcp_queue *queue,
776 		bool last_in_batch)
777 {
778 	struct nvmet_tcp_cmd *cmd = queue->snd_cmd;
779 	int ret = 0;
780 
781 	if (!cmd || queue->state == NVMET_TCP_Q_DISCONNECTING) {
782 		cmd = nvmet_tcp_fetch_cmd(queue);
783 		if (unlikely(!cmd))
784 			return 0;
785 	}
786 
787 	if (cmd->state == NVMET_TCP_SEND_DATA_PDU) {
788 		ret = nvmet_try_send_data_pdu(cmd);
789 		if (ret <= 0)
790 			goto done_send;
791 	}
792 
793 	if (cmd->state == NVMET_TCP_SEND_DATA) {
794 		ret = nvmet_try_send_data(cmd, last_in_batch);
795 		if (ret <= 0)
796 			goto done_send;
797 	}
798 
799 	if (cmd->state == NVMET_TCP_SEND_DDGST) {
800 		ret = nvmet_try_send_ddgst(cmd, last_in_batch);
801 		if (ret <= 0)
802 			goto done_send;
803 	}
804 
805 	if (cmd->state == NVMET_TCP_SEND_R2T) {
806 		ret = nvmet_try_send_r2t(cmd, last_in_batch);
807 		if (ret <= 0)
808 			goto done_send;
809 	}
810 
811 	if (cmd->state == NVMET_TCP_SEND_RESPONSE)
812 		ret = nvmet_try_send_response(cmd, last_in_batch);
813 
814 done_send:
815 	if (ret < 0) {
816 		if (ret == -EAGAIN)
817 			return 0;
818 		return ret;
819 	}
820 
821 	return 1;
822 }
823 
824 static int nvmet_tcp_try_send(struct nvmet_tcp_queue *queue,
825 		int budget, int *sends)
826 {
827 	int i, ret = 0;
828 
829 	for (i = 0; i < budget; i++) {
830 		ret = nvmet_tcp_try_send_one(queue, i == budget - 1);
831 		if (unlikely(ret < 0)) {
832 			nvmet_tcp_socket_error(queue, ret);
833 			goto done;
834 		} else if (ret == 0) {
835 			break;
836 		}
837 		(*sends)++;
838 	}
839 done:
840 	return ret;
841 }
842 
843 static void nvmet_prepare_receive_pdu(struct nvmet_tcp_queue *queue)
844 {
845 	queue->offset = 0;
846 	queue->left = sizeof(struct nvme_tcp_hdr);
847 	queue->cmd = NULL;
848 	queue->rcv_state = NVMET_TCP_RECV_PDU;
849 }
850 
851 static void nvmet_tcp_free_crypto(struct nvmet_tcp_queue *queue)
852 {
853 	struct crypto_ahash *tfm = crypto_ahash_reqtfm(queue->rcv_hash);
854 
855 	ahash_request_free(queue->rcv_hash);
856 	ahash_request_free(queue->snd_hash);
857 	crypto_free_ahash(tfm);
858 }
859 
860 static int nvmet_tcp_alloc_crypto(struct nvmet_tcp_queue *queue)
861 {
862 	struct crypto_ahash *tfm;
863 
864 	tfm = crypto_alloc_ahash("crc32c", 0, CRYPTO_ALG_ASYNC);
865 	if (IS_ERR(tfm))
866 		return PTR_ERR(tfm);
867 
868 	queue->snd_hash = ahash_request_alloc(tfm, GFP_KERNEL);
869 	if (!queue->snd_hash)
870 		goto free_tfm;
871 	ahash_request_set_callback(queue->snd_hash, 0, NULL, NULL);
872 
873 	queue->rcv_hash = ahash_request_alloc(tfm, GFP_KERNEL);
874 	if (!queue->rcv_hash)
875 		goto free_snd_hash;
876 	ahash_request_set_callback(queue->rcv_hash, 0, NULL, NULL);
877 
878 	return 0;
879 free_snd_hash:
880 	ahash_request_free(queue->snd_hash);
881 free_tfm:
882 	crypto_free_ahash(tfm);
883 	return -ENOMEM;
884 }
885 
886 
887 static int nvmet_tcp_handle_icreq(struct nvmet_tcp_queue *queue)
888 {
889 	struct nvme_tcp_icreq_pdu *icreq = &queue->pdu.icreq;
890 	struct nvme_tcp_icresp_pdu *icresp = &queue->pdu.icresp;
891 	struct msghdr msg = {};
892 	struct kvec iov;
893 	int ret;
894 
895 	if (le32_to_cpu(icreq->hdr.plen) != sizeof(struct nvme_tcp_icreq_pdu)) {
896 		pr_err("bad nvme-tcp pdu length (%d)\n",
897 			le32_to_cpu(icreq->hdr.plen));
898 		nvmet_tcp_fatal_error(queue);
899 	}
900 
901 	if (icreq->pfv != NVME_TCP_PFV_1_0) {
902 		pr_err("queue %d: bad pfv %d\n", queue->idx, icreq->pfv);
903 		return -EPROTO;
904 	}
905 
906 	if (icreq->hpda != 0) {
907 		pr_err("queue %d: unsupported hpda %d\n", queue->idx,
908 			icreq->hpda);
909 		return -EPROTO;
910 	}
911 
912 	queue->hdr_digest = !!(icreq->digest & NVME_TCP_HDR_DIGEST_ENABLE);
913 	queue->data_digest = !!(icreq->digest & NVME_TCP_DATA_DIGEST_ENABLE);
914 	if (queue->hdr_digest || queue->data_digest) {
915 		ret = nvmet_tcp_alloc_crypto(queue);
916 		if (ret)
917 			return ret;
918 	}
919 
920 	memset(icresp, 0, sizeof(*icresp));
921 	icresp->hdr.type = nvme_tcp_icresp;
922 	icresp->hdr.hlen = sizeof(*icresp);
923 	icresp->hdr.pdo = 0;
924 	icresp->hdr.plen = cpu_to_le32(icresp->hdr.hlen);
925 	icresp->pfv = cpu_to_le16(NVME_TCP_PFV_1_0);
926 	icresp->maxdata = cpu_to_le32(0x400000); /* 16M arbitrary limit */
927 	icresp->cpda = 0;
928 	if (queue->hdr_digest)
929 		icresp->digest |= NVME_TCP_HDR_DIGEST_ENABLE;
930 	if (queue->data_digest)
931 		icresp->digest |= NVME_TCP_DATA_DIGEST_ENABLE;
932 
933 	iov.iov_base = icresp;
934 	iov.iov_len = sizeof(*icresp);
935 	ret = kernel_sendmsg(queue->sock, &msg, &iov, 1, iov.iov_len);
936 	if (ret < 0) {
937 		queue->state = NVMET_TCP_Q_FAILED;
938 		return ret; /* queue removal will cleanup */
939 	}
940 
941 	queue->state = NVMET_TCP_Q_LIVE;
942 	nvmet_prepare_receive_pdu(queue);
943 	return 0;
944 }
945 
946 static void nvmet_tcp_handle_req_failure(struct nvmet_tcp_queue *queue,
947 		struct nvmet_tcp_cmd *cmd, struct nvmet_req *req)
948 {
949 	size_t data_len = le32_to_cpu(req->cmd->common.dptr.sgl.length);
950 	int ret;
951 
952 	/*
953 	 * This command has not been processed yet, hence we are trying to
954 	 * figure out if there is still pending data left to receive. If
955 	 * we don't, we can simply prepare for the next pdu and bail out,
956 	 * otherwise we will need to prepare a buffer and receive the
957 	 * stale data before continuing forward.
958 	 */
959 	if (!nvme_is_write(cmd->req.cmd) || !data_len ||
960 	    data_len > cmd->req.port->inline_data_size) {
961 		nvmet_prepare_receive_pdu(queue);
962 		return;
963 	}
964 
965 	ret = nvmet_tcp_map_data(cmd);
966 	if (unlikely(ret)) {
967 		pr_err("queue %d: failed to map data\n", queue->idx);
968 		nvmet_tcp_fatal_error(queue);
969 		return;
970 	}
971 
972 	queue->rcv_state = NVMET_TCP_RECV_DATA;
973 	nvmet_tcp_build_pdu_iovec(cmd);
974 	cmd->flags |= NVMET_TCP_F_INIT_FAILED;
975 }
976 
977 static int nvmet_tcp_handle_h2c_data_pdu(struct nvmet_tcp_queue *queue)
978 {
979 	struct nvme_tcp_data_pdu *data = &queue->pdu.data;
980 	struct nvmet_tcp_cmd *cmd;
981 
982 	if (likely(queue->nr_cmds)) {
983 		if (unlikely(data->ttag >= queue->nr_cmds)) {
984 			pr_err("queue %d: received out of bound ttag %u, nr_cmds %u\n",
985 				queue->idx, data->ttag, queue->nr_cmds);
986 			nvmet_tcp_fatal_error(queue);
987 			return -EPROTO;
988 		}
989 		cmd = &queue->cmds[data->ttag];
990 	} else {
991 		cmd = &queue->connect;
992 	}
993 
994 	if (le32_to_cpu(data->data_offset) != cmd->rbytes_done) {
995 		pr_err("ttag %u unexpected data offset %u (expected %u)\n",
996 			data->ttag, le32_to_cpu(data->data_offset),
997 			cmd->rbytes_done);
998 		/* FIXME: use path and transport errors */
999 		nvmet_req_complete(&cmd->req,
1000 			NVME_SC_INVALID_FIELD | NVME_SC_DNR);
1001 		return -EPROTO;
1002 	}
1003 
1004 	cmd->pdu_len = le32_to_cpu(data->data_length);
1005 	cmd->pdu_recv = 0;
1006 	nvmet_tcp_build_pdu_iovec(cmd);
1007 	queue->cmd = cmd;
1008 	queue->rcv_state = NVMET_TCP_RECV_DATA;
1009 
1010 	return 0;
1011 }
1012 
1013 static int nvmet_tcp_done_recv_pdu(struct nvmet_tcp_queue *queue)
1014 {
1015 	struct nvme_tcp_hdr *hdr = &queue->pdu.cmd.hdr;
1016 	struct nvme_command *nvme_cmd = &queue->pdu.cmd.cmd;
1017 	struct nvmet_req *req;
1018 	int ret;
1019 
1020 	if (unlikely(queue->state == NVMET_TCP_Q_CONNECTING)) {
1021 		if (hdr->type != nvme_tcp_icreq) {
1022 			pr_err("unexpected pdu type (%d) before icreq\n",
1023 				hdr->type);
1024 			nvmet_tcp_fatal_error(queue);
1025 			return -EPROTO;
1026 		}
1027 		return nvmet_tcp_handle_icreq(queue);
1028 	}
1029 
1030 	if (unlikely(hdr->type == nvme_tcp_icreq)) {
1031 		pr_err("queue %d: received icreq pdu in state %d\n",
1032 			queue->idx, queue->state);
1033 		nvmet_tcp_fatal_error(queue);
1034 		return -EPROTO;
1035 	}
1036 
1037 	if (hdr->type == nvme_tcp_h2c_data) {
1038 		ret = nvmet_tcp_handle_h2c_data_pdu(queue);
1039 		if (unlikely(ret))
1040 			return ret;
1041 		return 0;
1042 	}
1043 
1044 	queue->cmd = nvmet_tcp_get_cmd(queue);
1045 	if (unlikely(!queue->cmd)) {
1046 		/* This should never happen */
1047 		pr_err("queue %d: out of commands (%d) send_list_len: %d, opcode: %d",
1048 			queue->idx, queue->nr_cmds, queue->send_list_len,
1049 			nvme_cmd->common.opcode);
1050 		nvmet_tcp_fatal_error(queue);
1051 		return -ENOMEM;
1052 	}
1053 
1054 	req = &queue->cmd->req;
1055 	memcpy(req->cmd, nvme_cmd, sizeof(*nvme_cmd));
1056 
1057 	if (unlikely(!nvmet_req_init(req, &queue->nvme_cq,
1058 			&queue->nvme_sq, &nvmet_tcp_ops))) {
1059 		pr_err("failed cmd %p id %d opcode %d, data_len: %d\n",
1060 			req->cmd, req->cmd->common.command_id,
1061 			req->cmd->common.opcode,
1062 			le32_to_cpu(req->cmd->common.dptr.sgl.length));
1063 
1064 		nvmet_tcp_handle_req_failure(queue, queue->cmd, req);
1065 		return 0;
1066 	}
1067 
1068 	ret = nvmet_tcp_map_data(queue->cmd);
1069 	if (unlikely(ret)) {
1070 		pr_err("queue %d: failed to map data\n", queue->idx);
1071 		if (nvmet_tcp_has_inline_data(queue->cmd))
1072 			nvmet_tcp_fatal_error(queue);
1073 		else
1074 			nvmet_req_complete(req, ret);
1075 		ret = -EAGAIN;
1076 		goto out;
1077 	}
1078 
1079 	if (nvmet_tcp_need_data_in(queue->cmd)) {
1080 		if (nvmet_tcp_has_inline_data(queue->cmd)) {
1081 			queue->rcv_state = NVMET_TCP_RECV_DATA;
1082 			nvmet_tcp_build_pdu_iovec(queue->cmd);
1083 			return 0;
1084 		}
1085 		/* send back R2T */
1086 		nvmet_tcp_queue_response(&queue->cmd->req);
1087 		goto out;
1088 	}
1089 
1090 	queue->cmd->req.execute(&queue->cmd->req);
1091 out:
1092 	nvmet_prepare_receive_pdu(queue);
1093 	return ret;
1094 }
1095 
1096 static const u8 nvme_tcp_pdu_sizes[] = {
1097 	[nvme_tcp_icreq]	= sizeof(struct nvme_tcp_icreq_pdu),
1098 	[nvme_tcp_cmd]		= sizeof(struct nvme_tcp_cmd_pdu),
1099 	[nvme_tcp_h2c_data]	= sizeof(struct nvme_tcp_data_pdu),
1100 };
1101 
1102 static inline u8 nvmet_tcp_pdu_size(u8 type)
1103 {
1104 	size_t idx = type;
1105 
1106 	return (idx < ARRAY_SIZE(nvme_tcp_pdu_sizes) &&
1107 		nvme_tcp_pdu_sizes[idx]) ?
1108 			nvme_tcp_pdu_sizes[idx] : 0;
1109 }
1110 
1111 static inline bool nvmet_tcp_pdu_valid(u8 type)
1112 {
1113 	switch (type) {
1114 	case nvme_tcp_icreq:
1115 	case nvme_tcp_cmd:
1116 	case nvme_tcp_h2c_data:
1117 		/* fallthru */
1118 		return true;
1119 	}
1120 
1121 	return false;
1122 }
1123 
1124 static int nvmet_tcp_tls_record_ok(struct nvmet_tcp_queue *queue,
1125 		struct msghdr *msg, char *cbuf)
1126 {
1127 	struct cmsghdr *cmsg = (struct cmsghdr *)cbuf;
1128 	u8 ctype, level, description;
1129 	int ret = 0;
1130 
1131 	ctype = tls_get_record_type(queue->sock->sk, cmsg);
1132 	switch (ctype) {
1133 	case 0:
1134 		break;
1135 	case TLS_RECORD_TYPE_DATA:
1136 		break;
1137 	case TLS_RECORD_TYPE_ALERT:
1138 		tls_alert_recv(queue->sock->sk, msg, &level, &description);
1139 		if (level == TLS_ALERT_LEVEL_FATAL) {
1140 			pr_err("queue %d: TLS Alert desc %u\n",
1141 			       queue->idx, description);
1142 			ret = -ENOTCONN;
1143 		} else {
1144 			pr_warn("queue %d: TLS Alert desc %u\n",
1145 			       queue->idx, description);
1146 			ret = -EAGAIN;
1147 		}
1148 		break;
1149 	default:
1150 		/* discard this record type */
1151 		pr_err("queue %d: TLS record %d unhandled\n",
1152 		       queue->idx, ctype);
1153 		ret = -EAGAIN;
1154 		break;
1155 	}
1156 	return ret;
1157 }
1158 
1159 static int nvmet_tcp_try_recv_pdu(struct nvmet_tcp_queue *queue)
1160 {
1161 	struct nvme_tcp_hdr *hdr = &queue->pdu.cmd.hdr;
1162 	int len, ret;
1163 	struct kvec iov;
1164 	char cbuf[CMSG_LEN(sizeof(char))] = {};
1165 	struct msghdr msg = { .msg_flags = MSG_DONTWAIT };
1166 
1167 recv:
1168 	iov.iov_base = (void *)&queue->pdu + queue->offset;
1169 	iov.iov_len = queue->left;
1170 	if (queue->tls_pskid) {
1171 		msg.msg_control = cbuf;
1172 		msg.msg_controllen = sizeof(cbuf);
1173 	}
1174 	len = kernel_recvmsg(queue->sock, &msg, &iov, 1,
1175 			iov.iov_len, msg.msg_flags);
1176 	if (unlikely(len < 0))
1177 		return len;
1178 	if (queue->tls_pskid) {
1179 		ret = nvmet_tcp_tls_record_ok(queue, &msg, cbuf);
1180 		if (ret < 0)
1181 			return ret;
1182 	}
1183 
1184 	queue->offset += len;
1185 	queue->left -= len;
1186 	if (queue->left)
1187 		return -EAGAIN;
1188 
1189 	if (queue->offset == sizeof(struct nvme_tcp_hdr)) {
1190 		u8 hdgst = nvmet_tcp_hdgst_len(queue);
1191 
1192 		if (unlikely(!nvmet_tcp_pdu_valid(hdr->type))) {
1193 			pr_err("unexpected pdu type %d\n", hdr->type);
1194 			nvmet_tcp_fatal_error(queue);
1195 			return -EIO;
1196 		}
1197 
1198 		if (unlikely(hdr->hlen != nvmet_tcp_pdu_size(hdr->type))) {
1199 			pr_err("pdu %d bad hlen %d\n", hdr->type, hdr->hlen);
1200 			return -EIO;
1201 		}
1202 
1203 		queue->left = hdr->hlen - queue->offset + hdgst;
1204 		goto recv;
1205 	}
1206 
1207 	if (queue->hdr_digest &&
1208 	    nvmet_tcp_verify_hdgst(queue, &queue->pdu, hdr->hlen)) {
1209 		nvmet_tcp_fatal_error(queue); /* fatal */
1210 		return -EPROTO;
1211 	}
1212 
1213 	if (queue->data_digest &&
1214 	    nvmet_tcp_check_ddgst(queue, &queue->pdu)) {
1215 		nvmet_tcp_fatal_error(queue); /* fatal */
1216 		return -EPROTO;
1217 	}
1218 
1219 	return nvmet_tcp_done_recv_pdu(queue);
1220 }
1221 
1222 static void nvmet_tcp_prep_recv_ddgst(struct nvmet_tcp_cmd *cmd)
1223 {
1224 	struct nvmet_tcp_queue *queue = cmd->queue;
1225 
1226 	nvmet_tcp_calc_ddgst(queue->rcv_hash, cmd);
1227 	queue->offset = 0;
1228 	queue->left = NVME_TCP_DIGEST_LENGTH;
1229 	queue->rcv_state = NVMET_TCP_RECV_DDGST;
1230 }
1231 
1232 static int nvmet_tcp_try_recv_data(struct nvmet_tcp_queue *queue)
1233 {
1234 	struct nvmet_tcp_cmd  *cmd = queue->cmd;
1235 	int len, ret;
1236 
1237 	while (msg_data_left(&cmd->recv_msg)) {
1238 		len = sock_recvmsg(cmd->queue->sock, &cmd->recv_msg,
1239 			cmd->recv_msg.msg_flags);
1240 		if (len <= 0)
1241 			return len;
1242 		if (queue->tls_pskid) {
1243 			ret = nvmet_tcp_tls_record_ok(cmd->queue,
1244 					&cmd->recv_msg, cmd->recv_cbuf);
1245 			if (ret < 0)
1246 				return ret;
1247 		}
1248 
1249 		cmd->pdu_recv += len;
1250 		cmd->rbytes_done += len;
1251 	}
1252 
1253 	if (queue->data_digest) {
1254 		nvmet_tcp_prep_recv_ddgst(cmd);
1255 		return 0;
1256 	}
1257 
1258 	if (cmd->rbytes_done == cmd->req.transfer_len)
1259 		nvmet_tcp_execute_request(cmd);
1260 
1261 	nvmet_prepare_receive_pdu(queue);
1262 	return 0;
1263 }
1264 
1265 static int nvmet_tcp_try_recv_ddgst(struct nvmet_tcp_queue *queue)
1266 {
1267 	struct nvmet_tcp_cmd *cmd = queue->cmd;
1268 	int ret, len;
1269 	char cbuf[CMSG_LEN(sizeof(char))] = {};
1270 	struct msghdr msg = { .msg_flags = MSG_DONTWAIT };
1271 	struct kvec iov = {
1272 		.iov_base = (void *)&cmd->recv_ddgst + queue->offset,
1273 		.iov_len = queue->left
1274 	};
1275 
1276 	if (queue->tls_pskid) {
1277 		msg.msg_control = cbuf;
1278 		msg.msg_controllen = sizeof(cbuf);
1279 	}
1280 	len = kernel_recvmsg(queue->sock, &msg, &iov, 1,
1281 			iov.iov_len, msg.msg_flags);
1282 	if (unlikely(len < 0))
1283 		return len;
1284 	if (queue->tls_pskid) {
1285 		ret = nvmet_tcp_tls_record_ok(queue, &msg, cbuf);
1286 		if (ret < 0)
1287 			return ret;
1288 	}
1289 
1290 	queue->offset += len;
1291 	queue->left -= len;
1292 	if (queue->left)
1293 		return -EAGAIN;
1294 
1295 	if (queue->data_digest && cmd->exp_ddgst != cmd->recv_ddgst) {
1296 		pr_err("queue %d: cmd %d pdu (%d) data digest error: recv %#x expected %#x\n",
1297 			queue->idx, cmd->req.cmd->common.command_id,
1298 			queue->pdu.cmd.hdr.type, le32_to_cpu(cmd->recv_ddgst),
1299 			le32_to_cpu(cmd->exp_ddgst));
1300 		nvmet_req_uninit(&cmd->req);
1301 		nvmet_tcp_free_cmd_buffers(cmd);
1302 		nvmet_tcp_fatal_error(queue);
1303 		ret = -EPROTO;
1304 		goto out;
1305 	}
1306 
1307 	if (cmd->rbytes_done == cmd->req.transfer_len)
1308 		nvmet_tcp_execute_request(cmd);
1309 
1310 	ret = 0;
1311 out:
1312 	nvmet_prepare_receive_pdu(queue);
1313 	return ret;
1314 }
1315 
1316 static int nvmet_tcp_try_recv_one(struct nvmet_tcp_queue *queue)
1317 {
1318 	int result = 0;
1319 
1320 	if (unlikely(queue->rcv_state == NVMET_TCP_RECV_ERR))
1321 		return 0;
1322 
1323 	if (queue->rcv_state == NVMET_TCP_RECV_PDU) {
1324 		result = nvmet_tcp_try_recv_pdu(queue);
1325 		if (result != 0)
1326 			goto done_recv;
1327 	}
1328 
1329 	if (queue->rcv_state == NVMET_TCP_RECV_DATA) {
1330 		result = nvmet_tcp_try_recv_data(queue);
1331 		if (result != 0)
1332 			goto done_recv;
1333 	}
1334 
1335 	if (queue->rcv_state == NVMET_TCP_RECV_DDGST) {
1336 		result = nvmet_tcp_try_recv_ddgst(queue);
1337 		if (result != 0)
1338 			goto done_recv;
1339 	}
1340 
1341 done_recv:
1342 	if (result < 0) {
1343 		if (result == -EAGAIN)
1344 			return 0;
1345 		return result;
1346 	}
1347 	return 1;
1348 }
1349 
1350 static int nvmet_tcp_try_recv(struct nvmet_tcp_queue *queue,
1351 		int budget, int *recvs)
1352 {
1353 	int i, ret = 0;
1354 
1355 	for (i = 0; i < budget; i++) {
1356 		ret = nvmet_tcp_try_recv_one(queue);
1357 		if (unlikely(ret < 0)) {
1358 			nvmet_tcp_socket_error(queue, ret);
1359 			goto done;
1360 		} else if (ret == 0) {
1361 			break;
1362 		}
1363 		(*recvs)++;
1364 	}
1365 done:
1366 	return ret;
1367 }
1368 
1369 static void nvmet_tcp_release_queue(struct kref *kref)
1370 {
1371 	struct nvmet_tcp_queue *queue =
1372 		container_of(kref, struct nvmet_tcp_queue, kref);
1373 
1374 	WARN_ON(queue->state != NVMET_TCP_Q_DISCONNECTING);
1375 	queue_work(nvmet_wq, &queue->release_work);
1376 }
1377 
1378 static void nvmet_tcp_schedule_release_queue(struct nvmet_tcp_queue *queue)
1379 {
1380 	spin_lock_bh(&queue->state_lock);
1381 	if (queue->state == NVMET_TCP_Q_TLS_HANDSHAKE) {
1382 		/* Socket closed during handshake */
1383 		tls_handshake_cancel(queue->sock->sk);
1384 	}
1385 	if (queue->state != NVMET_TCP_Q_DISCONNECTING) {
1386 		queue->state = NVMET_TCP_Q_DISCONNECTING;
1387 		kref_put(&queue->kref, nvmet_tcp_release_queue);
1388 	}
1389 	spin_unlock_bh(&queue->state_lock);
1390 }
1391 
1392 static inline void nvmet_tcp_arm_queue_deadline(struct nvmet_tcp_queue *queue)
1393 {
1394 	queue->poll_end = jiffies + usecs_to_jiffies(idle_poll_period_usecs);
1395 }
1396 
1397 static bool nvmet_tcp_check_queue_deadline(struct nvmet_tcp_queue *queue,
1398 		int ops)
1399 {
1400 	if (!idle_poll_period_usecs)
1401 		return false;
1402 
1403 	if (ops)
1404 		nvmet_tcp_arm_queue_deadline(queue);
1405 
1406 	return !time_after(jiffies, queue->poll_end);
1407 }
1408 
1409 static void nvmet_tcp_io_work(struct work_struct *w)
1410 {
1411 	struct nvmet_tcp_queue *queue =
1412 		container_of(w, struct nvmet_tcp_queue, io_work);
1413 	bool pending;
1414 	int ret, ops = 0;
1415 
1416 	do {
1417 		pending = false;
1418 
1419 		ret = nvmet_tcp_try_recv(queue, NVMET_TCP_RECV_BUDGET, &ops);
1420 		if (ret > 0)
1421 			pending = true;
1422 		else if (ret < 0)
1423 			return;
1424 
1425 		ret = nvmet_tcp_try_send(queue, NVMET_TCP_SEND_BUDGET, &ops);
1426 		if (ret > 0)
1427 			pending = true;
1428 		else if (ret < 0)
1429 			return;
1430 
1431 	} while (pending && ops < NVMET_TCP_IO_WORK_BUDGET);
1432 
1433 	/*
1434 	 * Requeue the worker if idle deadline period is in progress or any
1435 	 * ops activity was recorded during the do-while loop above.
1436 	 */
1437 	if (nvmet_tcp_check_queue_deadline(queue, ops) || pending)
1438 		queue_work_on(queue_cpu(queue), nvmet_tcp_wq, &queue->io_work);
1439 }
1440 
1441 static int nvmet_tcp_alloc_cmd(struct nvmet_tcp_queue *queue,
1442 		struct nvmet_tcp_cmd *c)
1443 {
1444 	u8 hdgst = nvmet_tcp_hdgst_len(queue);
1445 
1446 	c->queue = queue;
1447 	c->req.port = queue->port->nport;
1448 
1449 	c->cmd_pdu = page_frag_alloc(&queue->pf_cache,
1450 			sizeof(*c->cmd_pdu) + hdgst, GFP_KERNEL | __GFP_ZERO);
1451 	if (!c->cmd_pdu)
1452 		return -ENOMEM;
1453 	c->req.cmd = &c->cmd_pdu->cmd;
1454 
1455 	c->rsp_pdu = page_frag_alloc(&queue->pf_cache,
1456 			sizeof(*c->rsp_pdu) + hdgst, GFP_KERNEL | __GFP_ZERO);
1457 	if (!c->rsp_pdu)
1458 		goto out_free_cmd;
1459 	c->req.cqe = &c->rsp_pdu->cqe;
1460 
1461 	c->data_pdu = page_frag_alloc(&queue->pf_cache,
1462 			sizeof(*c->data_pdu) + hdgst, GFP_KERNEL | __GFP_ZERO);
1463 	if (!c->data_pdu)
1464 		goto out_free_rsp;
1465 
1466 	c->r2t_pdu = page_frag_alloc(&queue->pf_cache,
1467 			sizeof(*c->r2t_pdu) + hdgst, GFP_KERNEL | __GFP_ZERO);
1468 	if (!c->r2t_pdu)
1469 		goto out_free_data;
1470 
1471 	if (queue->state == NVMET_TCP_Q_TLS_HANDSHAKE) {
1472 		c->recv_msg.msg_control = c->recv_cbuf;
1473 		c->recv_msg.msg_controllen = sizeof(c->recv_cbuf);
1474 	}
1475 	c->recv_msg.msg_flags = MSG_DONTWAIT | MSG_NOSIGNAL;
1476 
1477 	list_add_tail(&c->entry, &queue->free_list);
1478 
1479 	return 0;
1480 out_free_data:
1481 	page_frag_free(c->data_pdu);
1482 out_free_rsp:
1483 	page_frag_free(c->rsp_pdu);
1484 out_free_cmd:
1485 	page_frag_free(c->cmd_pdu);
1486 	return -ENOMEM;
1487 }
1488 
1489 static void nvmet_tcp_free_cmd(struct nvmet_tcp_cmd *c)
1490 {
1491 	page_frag_free(c->r2t_pdu);
1492 	page_frag_free(c->data_pdu);
1493 	page_frag_free(c->rsp_pdu);
1494 	page_frag_free(c->cmd_pdu);
1495 }
1496 
1497 static int nvmet_tcp_alloc_cmds(struct nvmet_tcp_queue *queue)
1498 {
1499 	struct nvmet_tcp_cmd *cmds;
1500 	int i, ret = -EINVAL, nr_cmds = queue->nr_cmds;
1501 
1502 	cmds = kcalloc(nr_cmds, sizeof(struct nvmet_tcp_cmd), GFP_KERNEL);
1503 	if (!cmds)
1504 		goto out;
1505 
1506 	for (i = 0; i < nr_cmds; i++) {
1507 		ret = nvmet_tcp_alloc_cmd(queue, cmds + i);
1508 		if (ret)
1509 			goto out_free;
1510 	}
1511 
1512 	queue->cmds = cmds;
1513 
1514 	return 0;
1515 out_free:
1516 	while (--i >= 0)
1517 		nvmet_tcp_free_cmd(cmds + i);
1518 	kfree(cmds);
1519 out:
1520 	return ret;
1521 }
1522 
1523 static void nvmet_tcp_free_cmds(struct nvmet_tcp_queue *queue)
1524 {
1525 	struct nvmet_tcp_cmd *cmds = queue->cmds;
1526 	int i;
1527 
1528 	for (i = 0; i < queue->nr_cmds; i++)
1529 		nvmet_tcp_free_cmd(cmds + i);
1530 
1531 	nvmet_tcp_free_cmd(&queue->connect);
1532 	kfree(cmds);
1533 }
1534 
1535 static void nvmet_tcp_restore_socket_callbacks(struct nvmet_tcp_queue *queue)
1536 {
1537 	struct socket *sock = queue->sock;
1538 
1539 	write_lock_bh(&sock->sk->sk_callback_lock);
1540 	sock->sk->sk_data_ready =  queue->data_ready;
1541 	sock->sk->sk_state_change = queue->state_change;
1542 	sock->sk->sk_write_space = queue->write_space;
1543 	sock->sk->sk_user_data = NULL;
1544 	write_unlock_bh(&sock->sk->sk_callback_lock);
1545 }
1546 
1547 static void nvmet_tcp_uninit_data_in_cmds(struct nvmet_tcp_queue *queue)
1548 {
1549 	struct nvmet_tcp_cmd *cmd = queue->cmds;
1550 	int i;
1551 
1552 	for (i = 0; i < queue->nr_cmds; i++, cmd++) {
1553 		if (nvmet_tcp_need_data_in(cmd))
1554 			nvmet_req_uninit(&cmd->req);
1555 	}
1556 
1557 	if (!queue->nr_cmds && nvmet_tcp_need_data_in(&queue->connect)) {
1558 		/* failed in connect */
1559 		nvmet_req_uninit(&queue->connect.req);
1560 	}
1561 }
1562 
1563 static void nvmet_tcp_free_cmd_data_in_buffers(struct nvmet_tcp_queue *queue)
1564 {
1565 	struct nvmet_tcp_cmd *cmd = queue->cmds;
1566 	int i;
1567 
1568 	for (i = 0; i < queue->nr_cmds; i++, cmd++) {
1569 		if (nvmet_tcp_need_data_in(cmd))
1570 			nvmet_tcp_free_cmd_buffers(cmd);
1571 	}
1572 
1573 	if (!queue->nr_cmds && nvmet_tcp_need_data_in(&queue->connect))
1574 		nvmet_tcp_free_cmd_buffers(&queue->connect);
1575 }
1576 
1577 static void nvmet_tcp_release_queue_work(struct work_struct *w)
1578 {
1579 	struct page *page;
1580 	struct nvmet_tcp_queue *queue =
1581 		container_of(w, struct nvmet_tcp_queue, release_work);
1582 
1583 	mutex_lock(&nvmet_tcp_queue_mutex);
1584 	list_del_init(&queue->queue_list);
1585 	mutex_unlock(&nvmet_tcp_queue_mutex);
1586 
1587 	nvmet_tcp_restore_socket_callbacks(queue);
1588 	cancel_delayed_work_sync(&queue->tls_handshake_tmo_work);
1589 	cancel_work_sync(&queue->io_work);
1590 	/* stop accepting incoming data */
1591 	queue->rcv_state = NVMET_TCP_RECV_ERR;
1592 
1593 	nvmet_tcp_uninit_data_in_cmds(queue);
1594 	nvmet_sq_destroy(&queue->nvme_sq);
1595 	cancel_work_sync(&queue->io_work);
1596 	nvmet_tcp_free_cmd_data_in_buffers(queue);
1597 	/* ->sock will be released by fput() */
1598 	fput(queue->sock->file);
1599 	nvmet_tcp_free_cmds(queue);
1600 	if (queue->hdr_digest || queue->data_digest)
1601 		nvmet_tcp_free_crypto(queue);
1602 	ida_free(&nvmet_tcp_queue_ida, queue->idx);
1603 	page = virt_to_head_page(queue->pf_cache.va);
1604 	__page_frag_cache_drain(page, queue->pf_cache.pagecnt_bias);
1605 	kfree(queue);
1606 }
1607 
1608 static void nvmet_tcp_data_ready(struct sock *sk)
1609 {
1610 	struct nvmet_tcp_queue *queue;
1611 
1612 	trace_sk_data_ready(sk);
1613 
1614 	read_lock_bh(&sk->sk_callback_lock);
1615 	queue = sk->sk_user_data;
1616 	if (likely(queue)) {
1617 		if (queue->data_ready)
1618 			queue->data_ready(sk);
1619 		if (queue->state != NVMET_TCP_Q_TLS_HANDSHAKE)
1620 			queue_work_on(queue_cpu(queue), nvmet_tcp_wq,
1621 				      &queue->io_work);
1622 	}
1623 	read_unlock_bh(&sk->sk_callback_lock);
1624 }
1625 
1626 static void nvmet_tcp_write_space(struct sock *sk)
1627 {
1628 	struct nvmet_tcp_queue *queue;
1629 
1630 	read_lock_bh(&sk->sk_callback_lock);
1631 	queue = sk->sk_user_data;
1632 	if (unlikely(!queue))
1633 		goto out;
1634 
1635 	if (unlikely(queue->state == NVMET_TCP_Q_CONNECTING)) {
1636 		queue->write_space(sk);
1637 		goto out;
1638 	}
1639 
1640 	if (sk_stream_is_writeable(sk)) {
1641 		clear_bit(SOCK_NOSPACE, &sk->sk_socket->flags);
1642 		queue_work_on(queue_cpu(queue), nvmet_tcp_wq, &queue->io_work);
1643 	}
1644 out:
1645 	read_unlock_bh(&sk->sk_callback_lock);
1646 }
1647 
1648 static void nvmet_tcp_state_change(struct sock *sk)
1649 {
1650 	struct nvmet_tcp_queue *queue;
1651 
1652 	read_lock_bh(&sk->sk_callback_lock);
1653 	queue = sk->sk_user_data;
1654 	if (!queue)
1655 		goto done;
1656 
1657 	switch (sk->sk_state) {
1658 	case TCP_FIN_WAIT2:
1659 	case TCP_LAST_ACK:
1660 		break;
1661 	case TCP_FIN_WAIT1:
1662 	case TCP_CLOSE_WAIT:
1663 	case TCP_CLOSE:
1664 		/* FALLTHRU */
1665 		nvmet_tcp_schedule_release_queue(queue);
1666 		break;
1667 	default:
1668 		pr_warn("queue %d unhandled state %d\n",
1669 			queue->idx, sk->sk_state);
1670 	}
1671 done:
1672 	read_unlock_bh(&sk->sk_callback_lock);
1673 }
1674 
1675 static int nvmet_tcp_set_queue_sock(struct nvmet_tcp_queue *queue)
1676 {
1677 	struct socket *sock = queue->sock;
1678 	struct inet_sock *inet = inet_sk(sock->sk);
1679 	int ret;
1680 
1681 	ret = kernel_getsockname(sock,
1682 		(struct sockaddr *)&queue->sockaddr);
1683 	if (ret < 0)
1684 		return ret;
1685 
1686 	ret = kernel_getpeername(sock,
1687 		(struct sockaddr *)&queue->sockaddr_peer);
1688 	if (ret < 0)
1689 		return ret;
1690 
1691 	/*
1692 	 * Cleanup whatever is sitting in the TCP transmit queue on socket
1693 	 * close. This is done to prevent stale data from being sent should
1694 	 * the network connection be restored before TCP times out.
1695 	 */
1696 	sock_no_linger(sock->sk);
1697 
1698 	if (so_priority > 0)
1699 		sock_set_priority(sock->sk, so_priority);
1700 
1701 	/* Set socket type of service */
1702 	if (inet->rcv_tos > 0)
1703 		ip_sock_set_tos(sock->sk, inet->rcv_tos);
1704 
1705 	ret = 0;
1706 	write_lock_bh(&sock->sk->sk_callback_lock);
1707 	if (sock->sk->sk_state != TCP_ESTABLISHED) {
1708 		/*
1709 		 * If the socket is already closing, don't even start
1710 		 * consuming it
1711 		 */
1712 		ret = -ENOTCONN;
1713 	} else {
1714 		sock->sk->sk_user_data = queue;
1715 		queue->data_ready = sock->sk->sk_data_ready;
1716 		sock->sk->sk_data_ready = nvmet_tcp_data_ready;
1717 		queue->state_change = sock->sk->sk_state_change;
1718 		sock->sk->sk_state_change = nvmet_tcp_state_change;
1719 		queue->write_space = sock->sk->sk_write_space;
1720 		sock->sk->sk_write_space = nvmet_tcp_write_space;
1721 		if (idle_poll_period_usecs)
1722 			nvmet_tcp_arm_queue_deadline(queue);
1723 		queue_work_on(queue_cpu(queue), nvmet_tcp_wq, &queue->io_work);
1724 	}
1725 	write_unlock_bh(&sock->sk->sk_callback_lock);
1726 
1727 	return ret;
1728 }
1729 
1730 #ifdef CONFIG_NVME_TARGET_TCP_TLS
1731 static int nvmet_tcp_try_peek_pdu(struct nvmet_tcp_queue *queue)
1732 {
1733 	struct nvme_tcp_hdr *hdr = &queue->pdu.cmd.hdr;
1734 	int len, ret;
1735 	struct kvec iov = {
1736 		.iov_base = (u8 *)&queue->pdu + queue->offset,
1737 		.iov_len = sizeof(struct nvme_tcp_hdr),
1738 	};
1739 	char cbuf[CMSG_LEN(sizeof(char))] = {};
1740 	struct msghdr msg = {
1741 		.msg_control = cbuf,
1742 		.msg_controllen = sizeof(cbuf),
1743 		.msg_flags = MSG_PEEK,
1744 	};
1745 
1746 	if (nvmet_port_secure_channel_required(queue->port->nport))
1747 		return 0;
1748 
1749 	len = kernel_recvmsg(queue->sock, &msg, &iov, 1,
1750 			iov.iov_len, msg.msg_flags);
1751 	if (unlikely(len < 0)) {
1752 		pr_debug("queue %d: peek error %d\n",
1753 			 queue->idx, len);
1754 		return len;
1755 	}
1756 
1757 	ret = nvmet_tcp_tls_record_ok(queue, &msg, cbuf);
1758 	if (ret < 0)
1759 		return ret;
1760 
1761 	if (len < sizeof(struct nvme_tcp_hdr)) {
1762 		pr_debug("queue %d: short read, %d bytes missing\n",
1763 			 queue->idx, (int)iov.iov_len - len);
1764 		return -EAGAIN;
1765 	}
1766 	pr_debug("queue %d: hdr type %d hlen %d plen %d size %d\n",
1767 		 queue->idx, hdr->type, hdr->hlen, hdr->plen,
1768 		 (int)sizeof(struct nvme_tcp_icreq_pdu));
1769 	if (hdr->type == nvme_tcp_icreq &&
1770 	    hdr->hlen == sizeof(struct nvme_tcp_icreq_pdu) &&
1771 	    hdr->plen == (__le32)sizeof(struct nvme_tcp_icreq_pdu)) {
1772 		pr_debug("queue %d: icreq detected\n",
1773 			 queue->idx);
1774 		return len;
1775 	}
1776 	return 0;
1777 }
1778 
1779 static void nvmet_tcp_tls_handshake_done(void *data, int status,
1780 					 key_serial_t peerid)
1781 {
1782 	struct nvmet_tcp_queue *queue = data;
1783 
1784 	pr_debug("queue %d: TLS handshake done, key %x, status %d\n",
1785 		 queue->idx, peerid, status);
1786 	spin_lock_bh(&queue->state_lock);
1787 	if (WARN_ON(queue->state != NVMET_TCP_Q_TLS_HANDSHAKE)) {
1788 		spin_unlock_bh(&queue->state_lock);
1789 		return;
1790 	}
1791 	if (!status) {
1792 		queue->tls_pskid = peerid;
1793 		queue->state = NVMET_TCP_Q_CONNECTING;
1794 	} else
1795 		queue->state = NVMET_TCP_Q_FAILED;
1796 	spin_unlock_bh(&queue->state_lock);
1797 
1798 	cancel_delayed_work_sync(&queue->tls_handshake_tmo_work);
1799 	if (status)
1800 		nvmet_tcp_schedule_release_queue(queue);
1801 	else
1802 		nvmet_tcp_set_queue_sock(queue);
1803 	kref_put(&queue->kref, nvmet_tcp_release_queue);
1804 }
1805 
1806 static void nvmet_tcp_tls_handshake_timeout(struct work_struct *w)
1807 {
1808 	struct nvmet_tcp_queue *queue = container_of(to_delayed_work(w),
1809 			struct nvmet_tcp_queue, tls_handshake_tmo_work);
1810 
1811 	pr_warn("queue %d: TLS handshake timeout\n", queue->idx);
1812 	/*
1813 	 * If tls_handshake_cancel() fails we've lost the race with
1814 	 * nvmet_tcp_tls_handshake_done() */
1815 	if (!tls_handshake_cancel(queue->sock->sk))
1816 		return;
1817 	spin_lock_bh(&queue->state_lock);
1818 	if (WARN_ON(queue->state != NVMET_TCP_Q_TLS_HANDSHAKE)) {
1819 		spin_unlock_bh(&queue->state_lock);
1820 		return;
1821 	}
1822 	queue->state = NVMET_TCP_Q_FAILED;
1823 	spin_unlock_bh(&queue->state_lock);
1824 	nvmet_tcp_schedule_release_queue(queue);
1825 	kref_put(&queue->kref, nvmet_tcp_release_queue);
1826 }
1827 
1828 static int nvmet_tcp_tls_handshake(struct nvmet_tcp_queue *queue)
1829 {
1830 	int ret = -EOPNOTSUPP;
1831 	struct tls_handshake_args args;
1832 
1833 	if (queue->state != NVMET_TCP_Q_TLS_HANDSHAKE) {
1834 		pr_warn("cannot start TLS in state %d\n", queue->state);
1835 		return -EINVAL;
1836 	}
1837 
1838 	kref_get(&queue->kref);
1839 	pr_debug("queue %d: TLS ServerHello\n", queue->idx);
1840 	memset(&args, 0, sizeof(args));
1841 	args.ta_sock = queue->sock;
1842 	args.ta_done = nvmet_tcp_tls_handshake_done;
1843 	args.ta_data = queue;
1844 	args.ta_keyring = key_serial(queue->port->nport->keyring);
1845 	args.ta_timeout_ms = tls_handshake_timeout * 1000;
1846 
1847 	ret = tls_server_hello_psk(&args, GFP_KERNEL);
1848 	if (ret) {
1849 		kref_put(&queue->kref, nvmet_tcp_release_queue);
1850 		pr_err("failed to start TLS, err=%d\n", ret);
1851 	} else {
1852 		queue_delayed_work(nvmet_wq, &queue->tls_handshake_tmo_work,
1853 				   tls_handshake_timeout * HZ);
1854 	}
1855 	return ret;
1856 }
1857 #else
1858 static void nvmet_tcp_tls_handshake_timeout(struct work_struct *w) {}
1859 #endif
1860 
1861 static void nvmet_tcp_alloc_queue(struct nvmet_tcp_port *port,
1862 		struct socket *newsock)
1863 {
1864 	struct nvmet_tcp_queue *queue;
1865 	struct file *sock_file = NULL;
1866 	int ret;
1867 
1868 	queue = kzalloc(sizeof(*queue), GFP_KERNEL);
1869 	if (!queue) {
1870 		ret = -ENOMEM;
1871 		goto out_release;
1872 	}
1873 
1874 	INIT_WORK(&queue->release_work, nvmet_tcp_release_queue_work);
1875 	INIT_WORK(&queue->io_work, nvmet_tcp_io_work);
1876 	kref_init(&queue->kref);
1877 	queue->sock = newsock;
1878 	queue->port = port;
1879 	queue->nr_cmds = 0;
1880 	spin_lock_init(&queue->state_lock);
1881 	if (queue->port->nport->disc_addr.tsas.tcp.sectype ==
1882 	    NVMF_TCP_SECTYPE_TLS13)
1883 		queue->state = NVMET_TCP_Q_TLS_HANDSHAKE;
1884 	else
1885 		queue->state = NVMET_TCP_Q_CONNECTING;
1886 	INIT_LIST_HEAD(&queue->free_list);
1887 	init_llist_head(&queue->resp_list);
1888 	INIT_LIST_HEAD(&queue->resp_send_list);
1889 
1890 	sock_file = sock_alloc_file(queue->sock, O_CLOEXEC, NULL);
1891 	if (IS_ERR(sock_file)) {
1892 		ret = PTR_ERR(sock_file);
1893 		goto out_free_queue;
1894 	}
1895 
1896 	queue->idx = ida_alloc(&nvmet_tcp_queue_ida, GFP_KERNEL);
1897 	if (queue->idx < 0) {
1898 		ret = queue->idx;
1899 		goto out_sock;
1900 	}
1901 
1902 	ret = nvmet_tcp_alloc_cmd(queue, &queue->connect);
1903 	if (ret)
1904 		goto out_ida_remove;
1905 
1906 	ret = nvmet_sq_init(&queue->nvme_sq);
1907 	if (ret)
1908 		goto out_free_connect;
1909 
1910 	nvmet_prepare_receive_pdu(queue);
1911 
1912 	mutex_lock(&nvmet_tcp_queue_mutex);
1913 	list_add_tail(&queue->queue_list, &nvmet_tcp_queue_list);
1914 	mutex_unlock(&nvmet_tcp_queue_mutex);
1915 
1916 	INIT_DELAYED_WORK(&queue->tls_handshake_tmo_work,
1917 			  nvmet_tcp_tls_handshake_timeout);
1918 #ifdef CONFIG_NVME_TARGET_TCP_TLS
1919 	if (queue->state == NVMET_TCP_Q_TLS_HANDSHAKE) {
1920 		struct sock *sk = queue->sock->sk;
1921 
1922 		/* Restore the default callbacks before starting upcall */
1923 		read_lock_bh(&sk->sk_callback_lock);
1924 		sk->sk_user_data = NULL;
1925 		sk->sk_data_ready = port->data_ready;
1926 		read_unlock_bh(&sk->sk_callback_lock);
1927 		if (!nvmet_tcp_try_peek_pdu(queue)) {
1928 			if (!nvmet_tcp_tls_handshake(queue))
1929 				return;
1930 			/* TLS handshake failed, terminate the connection */
1931 			goto out_destroy_sq;
1932 		}
1933 		/* Not a TLS connection, continue with normal processing */
1934 		queue->state = NVMET_TCP_Q_CONNECTING;
1935 	}
1936 #endif
1937 
1938 	ret = nvmet_tcp_set_queue_sock(queue);
1939 	if (ret)
1940 		goto out_destroy_sq;
1941 
1942 	return;
1943 out_destroy_sq:
1944 	mutex_lock(&nvmet_tcp_queue_mutex);
1945 	list_del_init(&queue->queue_list);
1946 	mutex_unlock(&nvmet_tcp_queue_mutex);
1947 	nvmet_sq_destroy(&queue->nvme_sq);
1948 out_free_connect:
1949 	nvmet_tcp_free_cmd(&queue->connect);
1950 out_ida_remove:
1951 	ida_free(&nvmet_tcp_queue_ida, queue->idx);
1952 out_sock:
1953 	fput(queue->sock->file);
1954 out_free_queue:
1955 	kfree(queue);
1956 out_release:
1957 	pr_err("failed to allocate queue, error %d\n", ret);
1958 	if (!sock_file)
1959 		sock_release(newsock);
1960 }
1961 
1962 static void nvmet_tcp_accept_work(struct work_struct *w)
1963 {
1964 	struct nvmet_tcp_port *port =
1965 		container_of(w, struct nvmet_tcp_port, accept_work);
1966 	struct socket *newsock;
1967 	int ret;
1968 
1969 	while (true) {
1970 		ret = kernel_accept(port->sock, &newsock, O_NONBLOCK);
1971 		if (ret < 0) {
1972 			if (ret != -EAGAIN)
1973 				pr_warn("failed to accept err=%d\n", ret);
1974 			return;
1975 		}
1976 		nvmet_tcp_alloc_queue(port, newsock);
1977 	}
1978 }
1979 
1980 static void nvmet_tcp_listen_data_ready(struct sock *sk)
1981 {
1982 	struct nvmet_tcp_port *port;
1983 
1984 	trace_sk_data_ready(sk);
1985 
1986 	read_lock_bh(&sk->sk_callback_lock);
1987 	port = sk->sk_user_data;
1988 	if (!port)
1989 		goto out;
1990 
1991 	if (sk->sk_state == TCP_LISTEN)
1992 		queue_work(nvmet_wq, &port->accept_work);
1993 out:
1994 	read_unlock_bh(&sk->sk_callback_lock);
1995 }
1996 
1997 static int nvmet_tcp_add_port(struct nvmet_port *nport)
1998 {
1999 	struct nvmet_tcp_port *port;
2000 	__kernel_sa_family_t af;
2001 	int ret;
2002 
2003 	port = kzalloc(sizeof(*port), GFP_KERNEL);
2004 	if (!port)
2005 		return -ENOMEM;
2006 
2007 	switch (nport->disc_addr.adrfam) {
2008 	case NVMF_ADDR_FAMILY_IP4:
2009 		af = AF_INET;
2010 		break;
2011 	case NVMF_ADDR_FAMILY_IP6:
2012 		af = AF_INET6;
2013 		break;
2014 	default:
2015 		pr_err("address family %d not supported\n",
2016 				nport->disc_addr.adrfam);
2017 		ret = -EINVAL;
2018 		goto err_port;
2019 	}
2020 
2021 	ret = inet_pton_with_scope(&init_net, af, nport->disc_addr.traddr,
2022 			nport->disc_addr.trsvcid, &port->addr);
2023 	if (ret) {
2024 		pr_err("malformed ip/port passed: %s:%s\n",
2025 			nport->disc_addr.traddr, nport->disc_addr.trsvcid);
2026 		goto err_port;
2027 	}
2028 
2029 	port->nport = nport;
2030 	INIT_WORK(&port->accept_work, nvmet_tcp_accept_work);
2031 	if (port->nport->inline_data_size < 0)
2032 		port->nport->inline_data_size = NVMET_TCP_DEF_INLINE_DATA_SIZE;
2033 
2034 	ret = sock_create(port->addr.ss_family, SOCK_STREAM,
2035 				IPPROTO_TCP, &port->sock);
2036 	if (ret) {
2037 		pr_err("failed to create a socket\n");
2038 		goto err_port;
2039 	}
2040 
2041 	port->sock->sk->sk_user_data = port;
2042 	port->data_ready = port->sock->sk->sk_data_ready;
2043 	port->sock->sk->sk_data_ready = nvmet_tcp_listen_data_ready;
2044 	sock_set_reuseaddr(port->sock->sk);
2045 	tcp_sock_set_nodelay(port->sock->sk);
2046 	if (so_priority > 0)
2047 		sock_set_priority(port->sock->sk, so_priority);
2048 
2049 	ret = kernel_bind(port->sock, (struct sockaddr *)&port->addr,
2050 			sizeof(port->addr));
2051 	if (ret) {
2052 		pr_err("failed to bind port socket %d\n", ret);
2053 		goto err_sock;
2054 	}
2055 
2056 	ret = kernel_listen(port->sock, 128);
2057 	if (ret) {
2058 		pr_err("failed to listen %d on port sock\n", ret);
2059 		goto err_sock;
2060 	}
2061 
2062 	nport->priv = port;
2063 	pr_info("enabling port %d (%pISpc)\n",
2064 		le16_to_cpu(nport->disc_addr.portid), &port->addr);
2065 
2066 	return 0;
2067 
2068 err_sock:
2069 	sock_release(port->sock);
2070 err_port:
2071 	kfree(port);
2072 	return ret;
2073 }
2074 
2075 static void nvmet_tcp_destroy_port_queues(struct nvmet_tcp_port *port)
2076 {
2077 	struct nvmet_tcp_queue *queue;
2078 
2079 	mutex_lock(&nvmet_tcp_queue_mutex);
2080 	list_for_each_entry(queue, &nvmet_tcp_queue_list, queue_list)
2081 		if (queue->port == port)
2082 			kernel_sock_shutdown(queue->sock, SHUT_RDWR);
2083 	mutex_unlock(&nvmet_tcp_queue_mutex);
2084 }
2085 
2086 static void nvmet_tcp_remove_port(struct nvmet_port *nport)
2087 {
2088 	struct nvmet_tcp_port *port = nport->priv;
2089 
2090 	write_lock_bh(&port->sock->sk->sk_callback_lock);
2091 	port->sock->sk->sk_data_ready = port->data_ready;
2092 	port->sock->sk->sk_user_data = NULL;
2093 	write_unlock_bh(&port->sock->sk->sk_callback_lock);
2094 	cancel_work_sync(&port->accept_work);
2095 	/*
2096 	 * Destroy the remaining queues, which are not belong to any
2097 	 * controller yet.
2098 	 */
2099 	nvmet_tcp_destroy_port_queues(port);
2100 
2101 	sock_release(port->sock);
2102 	kfree(port);
2103 }
2104 
2105 static void nvmet_tcp_delete_ctrl(struct nvmet_ctrl *ctrl)
2106 {
2107 	struct nvmet_tcp_queue *queue;
2108 
2109 	mutex_lock(&nvmet_tcp_queue_mutex);
2110 	list_for_each_entry(queue, &nvmet_tcp_queue_list, queue_list)
2111 		if (queue->nvme_sq.ctrl == ctrl)
2112 			kernel_sock_shutdown(queue->sock, SHUT_RDWR);
2113 	mutex_unlock(&nvmet_tcp_queue_mutex);
2114 }
2115 
2116 static u16 nvmet_tcp_install_queue(struct nvmet_sq *sq)
2117 {
2118 	struct nvmet_tcp_queue *queue =
2119 		container_of(sq, struct nvmet_tcp_queue, nvme_sq);
2120 
2121 	if (sq->qid == 0) {
2122 		/* Let inflight controller teardown complete */
2123 		flush_workqueue(nvmet_wq);
2124 	}
2125 
2126 	queue->nr_cmds = sq->size * 2;
2127 	if (nvmet_tcp_alloc_cmds(queue))
2128 		return NVME_SC_INTERNAL;
2129 	return 0;
2130 }
2131 
2132 static void nvmet_tcp_disc_port_addr(struct nvmet_req *req,
2133 		struct nvmet_port *nport, char *traddr)
2134 {
2135 	struct nvmet_tcp_port *port = nport->priv;
2136 
2137 	if (inet_addr_is_any((struct sockaddr *)&port->addr)) {
2138 		struct nvmet_tcp_cmd *cmd =
2139 			container_of(req, struct nvmet_tcp_cmd, req);
2140 		struct nvmet_tcp_queue *queue = cmd->queue;
2141 
2142 		sprintf(traddr, "%pISc", (struct sockaddr *)&queue->sockaddr);
2143 	} else {
2144 		memcpy(traddr, nport->disc_addr.traddr, NVMF_TRADDR_SIZE);
2145 	}
2146 }
2147 
2148 static const struct nvmet_fabrics_ops nvmet_tcp_ops = {
2149 	.owner			= THIS_MODULE,
2150 	.type			= NVMF_TRTYPE_TCP,
2151 	.msdbd			= 1,
2152 	.add_port		= nvmet_tcp_add_port,
2153 	.remove_port		= nvmet_tcp_remove_port,
2154 	.queue_response		= nvmet_tcp_queue_response,
2155 	.delete_ctrl		= nvmet_tcp_delete_ctrl,
2156 	.install_queue		= nvmet_tcp_install_queue,
2157 	.disc_traddr		= nvmet_tcp_disc_port_addr,
2158 };
2159 
2160 static int __init nvmet_tcp_init(void)
2161 {
2162 	int ret;
2163 
2164 	nvmet_tcp_wq = alloc_workqueue("nvmet_tcp_wq",
2165 				WQ_MEM_RECLAIM | WQ_HIGHPRI, 0);
2166 	if (!nvmet_tcp_wq)
2167 		return -ENOMEM;
2168 
2169 	ret = nvmet_register_transport(&nvmet_tcp_ops);
2170 	if (ret)
2171 		goto err;
2172 
2173 	return 0;
2174 err:
2175 	destroy_workqueue(nvmet_tcp_wq);
2176 	return ret;
2177 }
2178 
2179 static void __exit nvmet_tcp_exit(void)
2180 {
2181 	struct nvmet_tcp_queue *queue;
2182 
2183 	nvmet_unregister_transport(&nvmet_tcp_ops);
2184 
2185 	flush_workqueue(nvmet_wq);
2186 	mutex_lock(&nvmet_tcp_queue_mutex);
2187 	list_for_each_entry(queue, &nvmet_tcp_queue_list, queue_list)
2188 		kernel_sock_shutdown(queue->sock, SHUT_RDWR);
2189 	mutex_unlock(&nvmet_tcp_queue_mutex);
2190 	flush_workqueue(nvmet_wq);
2191 
2192 	destroy_workqueue(nvmet_tcp_wq);
2193 }
2194 
2195 module_init(nvmet_tcp_init);
2196 module_exit(nvmet_tcp_exit);
2197 
2198 MODULE_LICENSE("GPL v2");
2199 MODULE_ALIAS("nvmet-transport-3"); /* 3 == NVMF_TRTYPE_TCP */
2200