xref: /linux/drivers/nvme/host/tcp.c (revision f16d85cd3de9d0c761b74155b4cbe2f20d3dcf80)
1 // SPDX-License-Identifier: GPL-2.0
2 /*
3  * NVMe over Fabrics TCP host.
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/jiffies.h>
10 #include <linux/slab.h>
11 #include <linux/async.h>
12 #include <linux/err.h>
13 #include <linux/crc32.h>
14 #include <linux/nvme-tcp.h>
15 #include <linux/nvme-keyring.h>
16 #include <net/sock.h>
17 #include <net/tcp.h>
18 #include <net/tls.h>
19 #include <net/tls_prot.h>
20 #include <net/handshake.h>
21 #include <linux/blk-mq.h>
22 #include <net/busy_poll.h>
23 #include <trace/events/sock.h>
24 
25 #include "nvme.h"
26 #include "fabrics.h"
27 
28 struct nvme_tcp_queue;
29 
30 /*
31  * Define the socket priority to use for connections where it is desirable
32  * that the NIC consider performing optimized packet processing or filtering.
33  * A non-zero value being sufficient to indicate general consideration of any
34  * possible optimization.  Making it a module param allows for alternative
35  * values that may be unique for some NIC implementations.
36  */
37 static int so_priority;
38 module_param(so_priority, int, 0644);
39 MODULE_PARM_DESC(so_priority, "nvme tcp socket optimize priority");
40 
41 /*
42  * Use the unbound workqueue for nvme_tcp_wq, then we can set the cpu affinity
43  * from sysfs.
44  */
45 static bool wq_unbound;
46 module_param(wq_unbound, bool, 0644);
47 MODULE_PARM_DESC(wq_unbound, "Use unbound workqueue for nvme-tcp IO context (default false)");
48 
49 /*
50  * TLS handshake timeout
51  */
52 static unsigned int tls_handshake_timeout = 10;
53 #ifdef CONFIG_NVME_TCP_TLS
54 static int tls_handshake_timeout_set(const char *val,
55 				     const struct kernel_param *kp)
56 {
57 	return param_set_uint_minmax(val, kp, 0,
58 		min_t(unsigned long, UINT_MAX / MSEC_PER_SEC,
59 		      MAX_JIFFY_OFFSET / HZ));
60 }
61 
62 static const struct kernel_param_ops tls_handshake_timeout_ops = {
63 	.set = tls_handshake_timeout_set,
64 	.get = param_get_uint,
65 };
66 
67 module_param_cb(tls_handshake_timeout, &tls_handshake_timeout_ops,
68 		&tls_handshake_timeout, 0644);
69 __MODULE_PARM_TYPE(tls_handshake_timeout, "uint");
70 MODULE_PARM_DESC(tls_handshake_timeout,
71 		 "nvme TLS handshake timeout in seconds (default 10)");
72 #endif
73 
74 /* read a TLS control record in chunks of this size */
75 #define NVME_TCP_TLS_REC_CHUNK 256
76 
77 /* TLS records read while waiting for the ICResp, the ICResp included */
78 #define NVME_TCP_ICRESP_MAX_RECORDS 8
79 
80 static int nvme_tcp_cpu_queues[NR_CPUS];
81 static DEFINE_SPINLOCK(nvme_tcp_cpu_queues_lock);
82 
83 enum nvme_tcp_send_state {
84 	NVME_TCP_SEND_CMD_PDU = 0,
85 	NVME_TCP_SEND_H2C_PDU,
86 	NVME_TCP_SEND_DATA,
87 	NVME_TCP_SEND_DDGST,
88 };
89 
90 struct nvme_tcp_request {
91 	struct nvme_request	req;
92 	void			*pdu;
93 	struct nvme_tcp_queue	*queue;
94 	u32			data_len;
95 	u32			pdu_len;
96 	u32			pdu_sent;
97 	u32			h2cdata_left;
98 	u32			h2cdata_offset;
99 	u16			ttag;
100 	__le16			status;
101 	struct list_head	entry;
102 	struct llist_node	lentry;
103 	__le32			ddgst;
104 
105 	struct bio		*curr_bio;
106 	struct iov_iter		iter;
107 	u32			data_recvd;
108 
109 	/* send state */
110 	size_t			offset;
111 	size_t			data_sent;
112 	enum nvme_tcp_send_state state;
113 };
114 
115 enum nvme_tcp_queue_flags {
116 	NVME_TCP_Q_ALLOCATED	= 0,
117 	NVME_TCP_Q_LIVE		= 1,
118 	NVME_TCP_Q_POLLING	= 2,
119 	NVME_TCP_Q_IO_CPU_SET	= 3,
120 };
121 
122 #define NVME_TCP_OPT_NR_QUEUES(opts) ((opts)->nr_io_queues + \
123 	(opts)->nr_write_queues + (opts)->nr_poll_queues + 1)
124 
125 enum nvme_tcp_recv_state {
126 	NVME_TCP_RECV_PDU = 0,
127 	NVME_TCP_RECV_DATA,
128 	NVME_TCP_RECV_DDGST,
129 };
130 
131 struct nvme_tcp_ctrl;
132 struct nvme_tcp_queue {
133 	struct socket		*sock;
134 	struct work_struct	io_work;
135 	int			io_cpu;
136 
137 	struct mutex		queue_lock;
138 	struct mutex		send_mutex;
139 	struct mutex		pf_cache_lock;
140 	struct llist_head	req_list;
141 	struct list_head	send_list;
142 
143 	/* recv state */
144 	void			*pdu;
145 	int			pdu_remaining;
146 	int			pdu_offset;
147 	size_t			data_remaining;
148 	size_t			ddgst_remaining;
149 	unsigned int		nr_cqe;
150 
151 	/* send state */
152 	struct nvme_tcp_request *request;
153 
154 	u32			maxh2cdata;
155 	size_t			cmnd_capsule_len;
156 	struct nvme_tcp_ctrl	*ctrl;
157 	unsigned long		flags;
158 	bool			rd_enabled;
159 
160 	bool			hdr_digest;
161 	bool			data_digest;
162 	bool			tls_enabled;
163 	u32			rcv_crc;
164 	u32			snd_crc;
165 	__le32			exp_ddgst;
166 	__le32			recv_ddgst;
167 	struct completion       tls_complete;
168 	int                     tls_err;
169 	struct page_frag_cache	pf_cache;
170 
171 	void (*state_change)(struct sock *);
172 	void (*data_ready)(struct sock *);
173 	void (*write_space)(struct sock *);
174 };
175 
176 static DEFINE_MUTEX(nvme_tcp_ctrl_mutex);
177 static LIST_HEAD_GUARDED(nvme_tcp_ctrl_list, nvme_tcp_ctrl_mutex);
178 
179 struct nvme_tcp_queue_setup_ctx {
180 	struct nvme_ctrl	*ctrl;
181 	int			qid;
182 	int			*err;
183 };
184 
185 struct nvme_tcp_ctrl {
186 	/* read only in the hot path */
187 	struct nvme_tcp_queue	*queues;
188 	struct blk_mq_tag_set	tag_set;
189 
190 	/* other member variables */
191 	struct list_head	list
192 		__guarded_by(&nvme_tcp_ctrl_mutex);
193 	struct blk_mq_tag_set	admin_tag_set;
194 	struct sockaddr_storage addr;
195 	struct sockaddr_storage src_addr;
196 	struct nvme_ctrl	ctrl;
197 
198 	struct work_struct	err_work;
199 	struct delayed_work	connect_work;
200 	struct nvme_tcp_request async_req;
201 	u32			io_queues[HCTX_MAX_TYPES];
202 	unsigned int		nr_allocated_queues;
203 	struct net		*net;
204 };
205 
206 static struct workqueue_struct *nvme_tcp_wq;
207 static const struct blk_mq_ops nvme_tcp_mq_ops;
208 static const struct blk_mq_ops nvme_tcp_admin_mq_ops;
209 static int nvme_tcp_try_send(struct nvme_tcp_queue *queue);
210 
211 #ifdef CONFIG_DEBUG_LOCK_ALLOC
212 /* lockdep can detect a circular dependency of the form
213  *   sk_lock -> mmap_lock (page fault) -> fs locks -> sk_lock
214  * because dependencies are tracked for both nvme-tcp and user contexts. Using
215  * a separate class prevents lockdep from conflating nvme-tcp socket use with
216  * user-space socket API use.
217  */
218 static struct lock_class_key nvme_tcp_sk_key[2];
219 static struct lock_class_key nvme_tcp_slock_key[2];
220 
221 static void nvme_tcp_reclassify_socket(struct socket *sock)
222 {
223 	struct sock *sk = sock->sk;
224 
225 	if (WARN_ON_ONCE(!sock_allow_reclassification(sk)))
226 		return;
227 
228 	switch (sk->sk_family) {
229 	case AF_INET:
230 		sock_lock_init_class_and_name(sk, "slock-AF_INET-NVME",
231 					      &nvme_tcp_slock_key[0],
232 					      "sk_lock-AF_INET-NVME",
233 					      &nvme_tcp_sk_key[0]);
234 		break;
235 	case AF_INET6:
236 		sock_lock_init_class_and_name(sk, "slock-AF_INET6-NVME",
237 					      &nvme_tcp_slock_key[1],
238 					      "sk_lock-AF_INET6-NVME",
239 					      &nvme_tcp_sk_key[1]);
240 		break;
241 	default:
242 		WARN_ON_ONCE(1);
243 	}
244 }
245 #else
246 static void nvme_tcp_reclassify_socket(struct socket *sock) { }
247 #endif
248 
249 static inline struct nvme_tcp_ctrl *to_tcp_ctrl(struct nvme_ctrl *ctrl)
250 {
251 	return container_of(ctrl, struct nvme_tcp_ctrl, ctrl);
252 }
253 
254 static inline int nvme_tcp_queue_id(struct nvme_tcp_queue *queue)
255 {
256 	return queue - queue->ctrl->queues;
257 }
258 
259 static inline bool nvme_tcp_recv_pdu_supported(enum nvme_tcp_pdu_type type)
260 {
261 	switch (type) {
262 	case nvme_tcp_c2h_term:
263 	case nvme_tcp_c2h_data:
264 	case nvme_tcp_r2t:
265 	case nvme_tcp_rsp:
266 		return true;
267 	default:
268 		return false;
269 	}
270 }
271 
272 /*
273  * Check if the queue is TLS encrypted
274  */
275 static inline bool nvme_tcp_queue_tls(struct nvme_tcp_queue *queue)
276 {
277 	if (!IS_ENABLED(CONFIG_NVME_TCP_TLS))
278 		return 0;
279 
280 	return queue->tls_enabled;
281 }
282 
283 /*
284  * Check if TLS is configured for the controller.
285  */
286 static inline bool nvme_tcp_tls_configured(struct nvme_ctrl *ctrl)
287 {
288 	if (!IS_ENABLED(CONFIG_NVME_TCP_TLS))
289 		return 0;
290 
291 	return ctrl->opts->tls || ctrl->opts->concat;
292 }
293 
294 static inline struct blk_mq_tags *nvme_tcp_tagset(struct nvme_tcp_queue *queue)
295 {
296 	u32 queue_idx = nvme_tcp_queue_id(queue);
297 
298 	if (queue_idx == 0)
299 		return queue->ctrl->admin_tag_set.tags[queue_idx];
300 	return queue->ctrl->tag_set.tags[queue_idx - 1];
301 }
302 
303 static inline u8 nvme_tcp_hdgst_len(struct nvme_tcp_queue *queue)
304 {
305 	return queue->hdr_digest ? NVME_TCP_DIGEST_LENGTH : 0;
306 }
307 
308 static inline u8 nvme_tcp_ddgst_len(struct nvme_tcp_queue *queue)
309 {
310 	return queue->data_digest ? NVME_TCP_DIGEST_LENGTH : 0;
311 }
312 
313 static inline void *nvme_tcp_req_cmd_pdu(struct nvme_tcp_request *req)
314 {
315 	return req->pdu;
316 }
317 
318 static inline void *nvme_tcp_req_data_pdu(struct nvme_tcp_request *req)
319 {
320 	/* use the pdu space in the back for the data pdu */
321 	return req->pdu + sizeof(struct nvme_tcp_cmd_pdu) -
322 		sizeof(struct nvme_tcp_data_pdu);
323 }
324 
325 static inline size_t nvme_tcp_inline_data_size(struct nvme_tcp_request *req)
326 {
327 	if (nvme_is_fabrics(req->req.cmd))
328 		return NVME_TCP_ADMIN_CCSZ;
329 	return req->queue->cmnd_capsule_len - sizeof(struct nvme_command);
330 }
331 
332 static inline bool nvme_tcp_async_req(struct nvme_tcp_request *req)
333 {
334 	return req == &req->queue->ctrl->async_req;
335 }
336 
337 static inline bool nvme_tcp_has_inline_data(struct nvme_tcp_request *req)
338 {
339 	struct request *rq;
340 
341 	if (unlikely(nvme_tcp_async_req(req)))
342 		return false; /* async events don't have a request */
343 
344 	rq = blk_mq_rq_from_pdu(req);
345 
346 	return rq_data_dir(rq) == WRITE && req->data_len &&
347 		req->data_len <= nvme_tcp_inline_data_size(req);
348 }
349 
350 static inline struct page *nvme_tcp_req_cur_page(struct nvme_tcp_request *req)
351 {
352 	return req->iter.bvec->bv_page;
353 }
354 
355 static inline size_t nvme_tcp_req_cur_offset(struct nvme_tcp_request *req)
356 {
357 	return req->iter.bvec->bv_offset + req->iter.iov_offset;
358 }
359 
360 static inline size_t nvme_tcp_req_cur_length(struct nvme_tcp_request *req)
361 {
362 	return min_t(size_t, iov_iter_single_seg_count(&req->iter),
363 			req->pdu_len - req->pdu_sent);
364 }
365 
366 static inline size_t nvme_tcp_pdu_data_left(struct nvme_tcp_request *req)
367 {
368 	return rq_data_dir(blk_mq_rq_from_pdu(req)) == WRITE ?
369 			req->pdu_len - req->pdu_sent : 0;
370 }
371 
372 static inline size_t nvme_tcp_pdu_last_send(struct nvme_tcp_request *req,
373 		int len)
374 {
375 	return nvme_tcp_pdu_data_left(req) <= len;
376 }
377 
378 static void nvme_tcp_init_iter(struct nvme_tcp_request *req,
379 		unsigned int dir)
380 {
381 	struct request *rq = blk_mq_rq_from_pdu(req);
382 
383 	if (rq->rq_flags & RQF_SPECIAL_PAYLOAD) {
384 		iov_iter_bvec(&req->iter, dir, &rq->special_vec, 1,
385 				blk_rq_payload_bytes(rq));
386 		req->iter.iov_offset = 0;
387 	} else {
388 		struct bio *bio = req->curr_bio;
389 		struct bvec_iter bi;
390 		struct bio_vec bv;
391 		int nr_bvec = 0;
392 
393 		bio_for_each_bvec(bv, bio, bi)
394 			nr_bvec++;
395 
396 		iov_iter_bvec(&req->iter, dir,
397 			__bvec_iter_bvec(bio->bi_io_vec, bio->bi_iter), nr_bvec,
398 			bio->bi_iter.bi_size);
399 		req->iter.iov_offset = bio->bi_iter.bi_offset;
400 	}
401 }
402 
403 static inline void nvme_tcp_advance_req(struct nvme_tcp_request *req,
404 		int len)
405 {
406 	req->data_sent += len;
407 	req->pdu_sent += len;
408 	iov_iter_advance(&req->iter, len);
409 	if (!iov_iter_count(&req->iter) &&
410 	    req->data_sent < req->data_len) {
411 		req->curr_bio = req->curr_bio->bi_next;
412 		nvme_tcp_init_iter(req, ITER_SOURCE);
413 	}
414 }
415 
416 static inline void nvme_tcp_send_all(struct nvme_tcp_queue *queue)
417 {
418 	int ret;
419 
420 	/* drain the send queue as much as we can... */
421 	do {
422 		ret = nvme_tcp_try_send(queue);
423 	} while (ret > 0);
424 }
425 
426 static inline bool nvme_tcp_queue_has_pending(struct nvme_tcp_queue *queue)
427 {
428 	return !list_empty(&queue->send_list) ||
429 		!llist_empty(&queue->req_list);
430 }
431 
432 static inline bool nvme_tcp_queue_more(struct nvme_tcp_queue *queue)
433 {
434 	return !nvme_tcp_queue_tls(queue) &&
435 		nvme_tcp_queue_has_pending(queue);
436 }
437 
438 static inline void nvme_tcp_queue_request(struct nvme_tcp_request *req,
439 		bool last)
440 {
441 	struct nvme_tcp_queue *queue = req->queue;
442 	bool empty;
443 
444 	empty = llist_add(&req->lentry, &queue->req_list) &&
445 		list_empty(&queue->send_list) && !queue->request;
446 
447 	/*
448 	 * if we're the first on the send_list and we can try to send
449 	 * directly, otherwise queue io_work. Also, only do that if we
450 	 * are on the same cpu, so we don't introduce contention.
451 	 *
452 	 * TLS kTLS send takes ctx->tx_lock while blk_mq holds set->srcu.
453 	 * lockdep reports circular locking via elevator_lock.  Defer TLS
454 	 * sends to the io workqueue instead of inline from this path.
455 	 */
456 	if (queue->io_cpu == raw_smp_processor_id() &&
457 	    !nvme_tcp_queue_tls(queue) &&
458 	    empty && mutex_trylock(&queue->send_mutex)) {
459 		nvme_tcp_send_all(queue);
460 		mutex_unlock(&queue->send_mutex);
461 	}
462 
463 	if (last && nvme_tcp_queue_has_pending(queue))
464 		queue_work_on(queue->io_cpu, nvme_tcp_wq, &queue->io_work);
465 }
466 
467 static void nvme_tcp_process_req_list(struct nvme_tcp_queue *queue)
468 {
469 	struct nvme_tcp_request *req;
470 	struct llist_node *node;
471 
472 	for (node = llist_del_all(&queue->req_list); node; node = node->next) {
473 		req = llist_entry(node, struct nvme_tcp_request, lentry);
474 		list_add(&req->entry, &queue->send_list);
475 	}
476 }
477 
478 static inline struct nvme_tcp_request *
479 nvme_tcp_fetch_request(struct nvme_tcp_queue *queue)
480 {
481 	struct nvme_tcp_request *req;
482 
483 	req = list_first_entry_or_null(&queue->send_list,
484 			struct nvme_tcp_request, entry);
485 	if (!req) {
486 		nvme_tcp_process_req_list(queue);
487 		req = list_first_entry_or_null(&queue->send_list,
488 				struct nvme_tcp_request, entry);
489 		if (unlikely(!req))
490 			return NULL;
491 	}
492 
493 	list_del_init(&req->entry);
494 	init_llist_node(&req->lentry);
495 	return req;
496 }
497 
498 #define NVME_TCP_CRC_SEED (~0)
499 
500 static inline void nvme_tcp_ddgst_update(u32 *crcp,
501 		struct page *page, size_t off, size_t len)
502 {
503 	page += off / PAGE_SIZE;
504 	off %= PAGE_SIZE;
505 	while (len) {
506 		const void *vaddr = kmap_local_page(page);
507 		size_t n = min(len, (size_t)PAGE_SIZE - off);
508 
509 		*crcp = crc32c(*crcp, vaddr + off, n);
510 		kunmap_local(vaddr);
511 		page++;
512 		off = 0;
513 		len -= n;
514 	}
515 }
516 
517 static inline __le32 nvme_tcp_ddgst_final(u32 crc)
518 {
519 	return cpu_to_le32(~crc);
520 }
521 
522 static inline __le32 nvme_tcp_hdgst(const void *pdu, size_t len)
523 {
524 	return cpu_to_le32(~crc32c(NVME_TCP_CRC_SEED, pdu, len));
525 }
526 
527 static inline void nvme_tcp_set_hdgst(void *pdu, size_t len)
528 {
529 	*(__le32 *)(pdu + len) = nvme_tcp_hdgst(pdu, len);
530 }
531 
532 static int nvme_tcp_verify_hdgst(struct nvme_tcp_queue *queue,
533 		void *pdu, size_t pdu_len)
534 {
535 	struct nvme_tcp_hdr *hdr = pdu;
536 	__le32 recv_digest;
537 	__le32 exp_digest;
538 
539 	if (unlikely(!(hdr->flags & NVME_TCP_F_HDGST))) {
540 		dev_err(queue->ctrl->ctrl.device,
541 			"queue %d: header digest flag is cleared\n",
542 			nvme_tcp_queue_id(queue));
543 		return -EPROTO;
544 	}
545 
546 	recv_digest = *(__le32 *)(pdu + hdr->hlen);
547 	exp_digest = nvme_tcp_hdgst(pdu, pdu_len);
548 	if (recv_digest != exp_digest) {
549 		dev_err(queue->ctrl->ctrl.device,
550 			"header digest error: recv %#x expected %#x\n",
551 			le32_to_cpu(recv_digest), le32_to_cpu(exp_digest));
552 		return -EIO;
553 	}
554 
555 	return 0;
556 }
557 
558 static int nvme_tcp_check_ddgst(struct nvme_tcp_queue *queue, void *pdu)
559 {
560 	struct nvme_tcp_hdr *hdr = pdu;
561 	u8 digest_len = nvme_tcp_hdgst_len(queue);
562 	u32 len;
563 
564 	len = le32_to_cpu(hdr->plen) - hdr->hlen -
565 		((hdr->flags & NVME_TCP_F_HDGST) ? digest_len : 0);
566 
567 	if (unlikely(len && !(hdr->flags & NVME_TCP_F_DDGST))) {
568 		dev_err(queue->ctrl->ctrl.device,
569 			"queue %d: data digest flag is cleared\n",
570 		nvme_tcp_queue_id(queue));
571 		return -EPROTO;
572 	}
573 	queue->rcv_crc = NVME_TCP_CRC_SEED;
574 
575 	return 0;
576 }
577 
578 static void nvme_tcp_exit_request(struct blk_mq_tag_set *set,
579 		struct request *rq, unsigned int hctx_idx)
580 {
581 	struct nvme_tcp_request *req = blk_mq_rq_to_pdu(rq);
582 
583 	page_frag_free(req->pdu);
584 }
585 
586 static int nvme_tcp_init_request(struct blk_mq_tag_set *set,
587 		struct request *rq, unsigned int hctx_idx,
588 		int numa_node)
589 {
590 	struct nvme_tcp_ctrl *ctrl = to_tcp_ctrl(set->driver_data);
591 	struct nvme_tcp_request *req = blk_mq_rq_to_pdu(rq);
592 	struct nvme_tcp_cmd_pdu *pdu;
593 	int queue_idx = (set == &ctrl->tag_set) ? hctx_idx + 1 : 0;
594 	struct nvme_tcp_queue *queue = &ctrl->queues[queue_idx];
595 	u8 hdgst = nvme_tcp_hdgst_len(queue);
596 
597 	mutex_lock(&queue->pf_cache_lock);
598 	req->pdu = page_frag_alloc(&queue->pf_cache,
599 		sizeof(struct nvme_tcp_cmd_pdu) + hdgst,
600 		GFP_KERNEL | __GFP_ZERO);
601 	mutex_unlock(&queue->pf_cache_lock);
602 	if (!req->pdu)
603 		return -ENOMEM;
604 
605 	pdu = req->pdu;
606 	req->queue = queue;
607 	nvme_req(rq)->ctrl = &ctrl->ctrl;
608 	nvme_req(rq)->cmd = &pdu->cmd;
609 	init_llist_node(&req->lentry);
610 	INIT_LIST_HEAD(&req->entry);
611 
612 	return 0;
613 }
614 
615 static int nvme_tcp_init_hctx(struct blk_mq_hw_ctx *hctx, void *data,
616 		unsigned int hctx_idx)
617 {
618 	struct nvme_tcp_ctrl *ctrl = to_tcp_ctrl(data);
619 	struct nvme_tcp_queue *queue = &ctrl->queues[hctx_idx + 1];
620 
621 	hctx->driver_data = queue;
622 	return 0;
623 }
624 
625 static int nvme_tcp_init_admin_hctx(struct blk_mq_hw_ctx *hctx, void *data,
626 		unsigned int hctx_idx)
627 {
628 	struct nvme_tcp_ctrl *ctrl = to_tcp_ctrl(data);
629 	struct nvme_tcp_queue *queue = &ctrl->queues[0];
630 
631 	hctx->driver_data = queue;
632 	return 0;
633 }
634 
635 static enum nvme_tcp_recv_state
636 nvme_tcp_recv_state(struct nvme_tcp_queue *queue)
637 {
638 	return  (queue->pdu_remaining) ? NVME_TCP_RECV_PDU :
639 		(queue->ddgst_remaining) ? NVME_TCP_RECV_DDGST :
640 		NVME_TCP_RECV_DATA;
641 }
642 
643 static void nvme_tcp_init_recv_ctx(struct nvme_tcp_queue *queue)
644 {
645 	queue->pdu_remaining = sizeof(struct nvme_tcp_rsp_pdu) +
646 				nvme_tcp_hdgst_len(queue);
647 	queue->pdu_offset = 0;
648 	queue->data_remaining = -1;
649 	queue->ddgst_remaining = 0;
650 }
651 
652 static void nvme_tcp_error_recovery(struct nvme_ctrl *ctrl)
653 {
654 	if (!nvme_change_ctrl_state(ctrl, NVME_CTRL_RESETTING))
655 		return;
656 
657 	dev_warn(ctrl->device, "starting error recovery\n");
658 	queue_work(nvme_reset_wq, &to_tcp_ctrl(ctrl)->err_work);
659 }
660 
661 /*
662  * NVMe has no short read: a read that completes successfully must
663  * have transferred everything it asked for.
664  */
665 static bool nvme_tcp_data_in_short(struct nvme_tcp_queue *queue,
666 				   struct request *rq)
667 {
668 	struct nvme_tcp_request *req = blk_mq_rq_to_pdu(rq);
669 
670 	if (le16_to_cpu(req->status) >> 1)
671 		return false;
672 	if (req_op(rq) != REQ_OP_READ || !req->data_len)
673 		return false;
674 	if (likely(req->data_recvd == req->data_len))
675 		return false;
676 
677 	dev_err(queue->ctrl->ctrl.device,
678 		"queue %d tag %#x short data-in: got %u of %u\n",
679 		nvme_tcp_queue_id(queue), rq->tag,
680 		req->data_recvd, req->data_len);
681 	return true;
682 }
683 
684 static int nvme_tcp_process_nvme_cqe(struct nvme_tcp_queue *queue,
685 		struct nvme_completion *cqe)
686 {
687 	struct nvme_tcp_request *req;
688 	struct request *rq;
689 
690 	rq = nvme_find_rq(nvme_tcp_tagset(queue), cqe->command_id);
691 	if (!rq) {
692 		dev_err(queue->ctrl->ctrl.device,
693 			"got bad cqe.command_id %#x on queue %d\n",
694 			cqe->command_id, nvme_tcp_queue_id(queue));
695 		nvme_tcp_error_recovery(&queue->ctrl->ctrl);
696 		return -EINVAL;
697 	}
698 
699 	req = blk_mq_rq_to_pdu(rq);
700 	if (req->status == cpu_to_le16(NVME_SC_SUCCESS))
701 		req->status = cqe->status;
702 
703 	if (unlikely(nvme_tcp_data_in_short(queue, rq)))
704 		return -EPROTO;
705 
706 	if (!nvme_try_complete_req(rq, req->status, cqe->result))
707 		nvme_complete_rq(rq);
708 	queue->nr_cqe++;
709 
710 	return 0;
711 }
712 
713 static int nvme_tcp_handle_c2h_data(struct nvme_tcp_queue *queue,
714 		struct nvme_tcp_data_pdu *pdu)
715 {
716 	struct nvme_tcp_request *req;
717 	struct request *rq;
718 
719 	rq = nvme_find_rq(nvme_tcp_tagset(queue), pdu->command_id);
720 	if (!rq) {
721 		dev_err(queue->ctrl->ctrl.device,
722 			"got bad c2hdata.command_id %#x on queue %d\n",
723 			pdu->command_id, nvme_tcp_queue_id(queue));
724 		return -ENOENT;
725 	}
726 
727 	if (rq_data_dir(rq) != READ) {
728 		dev_err(queue->ctrl->ctrl.device,
729 			"queue %d tag %#x unexpected data for a write\n",
730 			nvme_tcp_queue_id(queue), rq->tag);
731 		return -EPROTO;
732 	}
733 
734 	req = blk_mq_rq_to_pdu(rq);
735 	if (!blk_rq_payload_bytes(rq) || !req->curr_bio || !req->data_len) {
736 		dev_err(queue->ctrl->ctrl.device,
737 			"queue %d tag %#x unexpected data\n",
738 			nvme_tcp_queue_id(queue), rq->tag);
739 		return -EIO;
740 	}
741 
742 	queue->data_remaining = le32_to_cpu(pdu->data_length);
743 
744 	if (pdu->hdr.flags & NVME_TCP_F_DATA_SUCCESS &&
745 	    unlikely(!(pdu->hdr.flags & NVME_TCP_F_DATA_LAST))) {
746 		dev_err(queue->ctrl->ctrl.device,
747 			"queue %d tag %#x SUCCESS set but not last PDU\n",
748 			nvme_tcp_queue_id(queue), rq->tag);
749 		nvme_tcp_error_recovery(&queue->ctrl->ctrl);
750 		return -EPROTO;
751 	}
752 
753 	return 0;
754 }
755 
756 static int nvme_tcp_handle_comp(struct nvme_tcp_queue *queue,
757 		struct nvme_tcp_rsp_pdu *pdu)
758 {
759 	struct nvme_completion *cqe = &pdu->cqe;
760 	int ret = 0;
761 
762 	/*
763 	 * AEN requests are special as they don't time out and can
764 	 * survive any kind of queue freeze and often don't respond to
765 	 * aborts.  We don't even bother to allocate a struct request
766 	 * for them but rather special case them here.
767 	 */
768 	if (unlikely(nvme_is_aen_req(nvme_tcp_queue_id(queue),
769 				     cqe->command_id)))
770 		nvme_complete_async_event(&queue->ctrl->ctrl, cqe->status,
771 				&cqe->result);
772 	else
773 		ret = nvme_tcp_process_nvme_cqe(queue, cqe);
774 
775 	return ret;
776 }
777 
778 static void nvme_tcp_setup_h2c_data_pdu(struct nvme_tcp_request *req)
779 {
780 	struct nvme_tcp_data_pdu *data = nvme_tcp_req_data_pdu(req);
781 	struct nvme_tcp_queue *queue = req->queue;
782 	struct request *rq = blk_mq_rq_from_pdu(req);
783 	u32 h2cdata_sent = req->pdu_len;
784 	u8 hdgst = nvme_tcp_hdgst_len(queue);
785 	u8 ddgst = nvme_tcp_ddgst_len(queue);
786 
787 	req->state = NVME_TCP_SEND_H2C_PDU;
788 	req->offset = 0;
789 	req->pdu_len = min(req->h2cdata_left, queue->maxh2cdata);
790 	req->pdu_sent = 0;
791 	req->h2cdata_left -= req->pdu_len;
792 	req->h2cdata_offset += h2cdata_sent;
793 
794 	memset(data, 0, sizeof(*data));
795 	data->hdr.type = nvme_tcp_h2c_data;
796 	if (!req->h2cdata_left)
797 		data->hdr.flags = NVME_TCP_F_DATA_LAST;
798 	if (queue->hdr_digest)
799 		data->hdr.flags |= NVME_TCP_F_HDGST;
800 	if (queue->data_digest)
801 		data->hdr.flags |= NVME_TCP_F_DDGST;
802 	data->hdr.hlen = sizeof(*data);
803 	data->hdr.pdo = data->hdr.hlen + hdgst;
804 	data->hdr.plen =
805 		cpu_to_le32(data->hdr.hlen + hdgst + req->pdu_len + ddgst);
806 	data->ttag = req->ttag;
807 	data->command_id = nvme_cid(rq);
808 	data->data_offset = cpu_to_le32(req->h2cdata_offset);
809 	data->data_length = cpu_to_le32(req->pdu_len);
810 }
811 
812 static int nvme_tcp_handle_r2t(struct nvme_tcp_queue *queue,
813 		struct nvme_tcp_r2t_pdu *pdu)
814 {
815 	struct nvme_tcp_request *req;
816 	struct request *rq;
817 	u32 r2t_length = le32_to_cpu(pdu->r2t_length);
818 	u32 r2t_offset = le32_to_cpu(pdu->r2t_offset);
819 
820 	rq = nvme_find_rq(nvme_tcp_tagset(queue), pdu->command_id);
821 	if (!rq) {
822 		dev_err(queue->ctrl->ctrl.device,
823 			"got bad r2t.command_id %#x on queue %d\n",
824 			pdu->command_id, nvme_tcp_queue_id(queue));
825 		return -ENOENT;
826 	}
827 	req = blk_mq_rq_to_pdu(rq);
828 
829 	if (unlikely(rq_data_dir(rq) != WRITE)) {
830 		dev_err(queue->ctrl->ctrl.device,
831 			"req %d unexpected r2t for a non-write command\n",
832 			rq->tag);
833 		return -EPROTO;
834 	}
835 
836 	if (unlikely(!r2t_length)) {
837 		dev_err(queue->ctrl->ctrl.device,
838 			"req %d r2t len is %u, probably a bug...\n",
839 			rq->tag, r2t_length);
840 		return -EPROTO;
841 	}
842 
843 	if (unlikely(req->data_sent + r2t_length > req->data_len)) {
844 		dev_err(queue->ctrl->ctrl.device,
845 			"req %d r2t len %u exceeded data len %u (%zu sent)\n",
846 			rq->tag, r2t_length, req->data_len, req->data_sent);
847 		return -EPROTO;
848 	}
849 
850 	if (unlikely(r2t_offset < req->data_sent)) {
851 		dev_err(queue->ctrl->ctrl.device,
852 			"req %d unexpected r2t offset %u (expected %zu)\n",
853 			rq->tag, r2t_offset, req->data_sent);
854 		return -EPROTO;
855 	}
856 
857 	if (llist_on_list(&req->lentry) ||
858 	    !list_empty(&req->entry)) {
859 		dev_err(queue->ctrl->ctrl.device,
860 			"req %d unexpected r2t while processing request\n",
861 			rq->tag);
862 		return -EPROTO;
863 	}
864 
865 	req->pdu_len = 0;
866 	req->h2cdata_left = r2t_length;
867 	req->h2cdata_offset = r2t_offset;
868 	req->ttag = pdu->ttag;
869 
870 	nvme_tcp_setup_h2c_data_pdu(req);
871 
872 	llist_add(&req->lentry, &queue->req_list);
873 	queue_work_on(queue->io_cpu, nvme_tcp_wq, &queue->io_work);
874 
875 	return 0;
876 }
877 
878 static void nvme_tcp_handle_c2h_term(struct nvme_tcp_queue *queue,
879 		struct nvme_tcp_term_pdu *pdu)
880 {
881 	u16 fes;
882 	const char *msg;
883 	u32 plen = le32_to_cpu(pdu->hdr.plen);
884 
885 	static const char * const msg_table[] = {
886 		[NVME_TCP_FES_INVALID_PDU_HDR] = "Invalid PDU Header Field",
887 		[NVME_TCP_FES_PDU_SEQ_ERR] = "PDU Sequence Error",
888 		[NVME_TCP_FES_HDR_DIGEST_ERR] = "Header Digest Error",
889 		[NVME_TCP_FES_DATA_OUT_OF_RANGE] = "Data Transfer Out Of Range",
890 		[NVME_TCP_FES_DATA_LIMIT_EXCEEDED] = "Data Transfer Limit Exceeded",
891 		[NVME_TCP_FES_UNSUPPORTED_PARAM] = "Unsupported Parameter",
892 	};
893 
894 	if (plen < NVME_TCP_MIN_C2HTERM_PLEN ||
895 	    plen > NVME_TCP_MAX_C2HTERM_PLEN) {
896 		dev_err(queue->ctrl->ctrl.device,
897 			"Received a malformed C2HTermReq PDU (plen = %u)\n",
898 			plen);
899 		return;
900 	}
901 
902 	fes = le16_to_cpu(pdu->fes);
903 	if (fes && fes < ARRAY_SIZE(msg_table))
904 		msg = msg_table[fes];
905 	else
906 		msg = "Unknown";
907 
908 	dev_err(queue->ctrl->ctrl.device,
909 		"Received C2HTermReq (FES = %s)\n", msg);
910 }
911 
912 static int nvme_tcp_recv_pdu(struct nvme_tcp_queue *queue, struct sk_buff *skb,
913 		unsigned int *offset, size_t *len)
914 {
915 	struct nvme_tcp_hdr *hdr;
916 	char *pdu = queue->pdu;
917 	size_t rcv_len = min_t(size_t, *len, queue->pdu_remaining);
918 	int ret;
919 
920 	ret = skb_copy_bits(skb, *offset,
921 		&pdu[queue->pdu_offset], rcv_len);
922 	if (unlikely(ret))
923 		return ret;
924 
925 	queue->pdu_remaining -= rcv_len;
926 	queue->pdu_offset += rcv_len;
927 	*offset += rcv_len;
928 	*len -= rcv_len;
929 	if (queue->pdu_remaining)
930 		return 0;
931 
932 	hdr = queue->pdu;
933 	if (unlikely(hdr->hlen != sizeof(struct nvme_tcp_rsp_pdu))) {
934 		if (!nvme_tcp_recv_pdu_supported(hdr->type))
935 			goto unsupported_pdu;
936 
937 		dev_err(queue->ctrl->ctrl.device,
938 			"pdu type %d has unexpected header length (%d)\n",
939 			hdr->type, hdr->hlen);
940 		return -EPROTO;
941 	}
942 
943 	if (unlikely(hdr->type == nvme_tcp_c2h_term)) {
944 		/*
945 		 * C2HTermReq never includes Header or Data digests.
946 		 * Skip the checks.
947 		 */
948 		nvme_tcp_handle_c2h_term(queue, (void *)queue->pdu);
949 		return -EINVAL;
950 	}
951 
952 	if (queue->hdr_digest) {
953 		ret = nvme_tcp_verify_hdgst(queue, queue->pdu, hdr->hlen);
954 		if (unlikely(ret))
955 			return ret;
956 	}
957 
958 
959 	if (queue->data_digest) {
960 		ret = nvme_tcp_check_ddgst(queue, queue->pdu);
961 		if (unlikely(ret))
962 			return ret;
963 	}
964 
965 	switch (hdr->type) {
966 	case nvme_tcp_c2h_data:
967 		return nvme_tcp_handle_c2h_data(queue, (void *)queue->pdu);
968 	case nvme_tcp_rsp:
969 		nvme_tcp_init_recv_ctx(queue);
970 		return nvme_tcp_handle_comp(queue, (void *)queue->pdu);
971 	case nvme_tcp_r2t:
972 		nvme_tcp_init_recv_ctx(queue);
973 		return nvme_tcp_handle_r2t(queue, (void *)queue->pdu);
974 	default:
975 		goto unsupported_pdu;
976 	}
977 
978 unsupported_pdu:
979 	dev_err(queue->ctrl->ctrl.device,
980 		"unsupported pdu type (%d)\n", hdr->type);
981 	return -EINVAL;
982 }
983 
984 static inline void nvme_tcp_end_request(struct request *rq, u16 status)
985 {
986 	union nvme_result res = {};
987 
988 	if (!nvme_try_complete_req(rq, cpu_to_le16(status << 1), res))
989 		nvme_complete_rq(rq);
990 }
991 
992 static int nvme_tcp_recv_data(struct nvme_tcp_queue *queue, struct sk_buff *skb,
993 			      unsigned int *offset, size_t *len)
994 {
995 	struct nvme_tcp_data_pdu *pdu = (void *)queue->pdu;
996 	struct request *rq =
997 		nvme_cid_to_rq(nvme_tcp_tagset(queue), pdu->command_id);
998 	struct nvme_tcp_request *req = blk_mq_rq_to_pdu(rq);
999 
1000 	while (true) {
1001 		int recv_len, ret;
1002 
1003 		recv_len = min_t(size_t, *len, queue->data_remaining);
1004 		if (!recv_len)
1005 			break;
1006 
1007 		if (!iov_iter_count(&req->iter)) {
1008 			req->curr_bio = req->curr_bio->bi_next;
1009 
1010 			/*
1011 			 * If we don't have any bios it means the controller
1012 			 * sent more data than we requested, hence error
1013 			 */
1014 			if (!req->curr_bio) {
1015 				dev_err(queue->ctrl->ctrl.device,
1016 					"queue %d no space in request %#x",
1017 					nvme_tcp_queue_id(queue), rq->tag);
1018 				nvme_tcp_init_recv_ctx(queue);
1019 				return -EIO;
1020 			}
1021 			nvme_tcp_init_iter(req, ITER_DEST);
1022 		}
1023 
1024 		/* we can read only from what is left in this bio */
1025 		recv_len = min_t(size_t, recv_len,
1026 				iov_iter_count(&req->iter));
1027 
1028 		if (queue->data_digest)
1029 			ret = skb_copy_and_crc32c_datagram_iter(skb, *offset,
1030 				&req->iter, recv_len, &queue->rcv_crc);
1031 		else
1032 			ret = skb_copy_datagram_iter(skb, *offset,
1033 					&req->iter, recv_len);
1034 		if (ret) {
1035 			dev_err(queue->ctrl->ctrl.device,
1036 				"queue %d failed to copy request %#x data",
1037 				nvme_tcp_queue_id(queue), rq->tag);
1038 			return ret;
1039 		}
1040 
1041 		*len -= recv_len;
1042 		*offset += recv_len;
1043 		queue->data_remaining -= recv_len;
1044 		req->data_recvd += recv_len;
1045 	}
1046 
1047 	if (!queue->data_remaining) {
1048 		if (queue->data_digest) {
1049 			queue->exp_ddgst = nvme_tcp_ddgst_final(queue->rcv_crc);
1050 			queue->ddgst_remaining = NVME_TCP_DIGEST_LENGTH;
1051 		} else {
1052 			if (pdu->hdr.flags & NVME_TCP_F_DATA_SUCCESS) {
1053 				if (unlikely(nvme_tcp_data_in_short(queue, rq)))
1054 					return -EPROTO;
1055 				nvme_tcp_end_request(rq,
1056 						le16_to_cpu(req->status));
1057 				queue->nr_cqe++;
1058 			}
1059 			nvme_tcp_init_recv_ctx(queue);
1060 		}
1061 	}
1062 
1063 	return 0;
1064 }
1065 
1066 static int nvme_tcp_recv_ddgst(struct nvme_tcp_queue *queue,
1067 		struct sk_buff *skb, unsigned int *offset, size_t *len)
1068 {
1069 	struct nvme_tcp_data_pdu *pdu = (void *)queue->pdu;
1070 	char *ddgst = (char *)&queue->recv_ddgst;
1071 	size_t recv_len = min_t(size_t, *len, queue->ddgst_remaining);
1072 	off_t off = NVME_TCP_DIGEST_LENGTH - queue->ddgst_remaining;
1073 	int ret;
1074 
1075 	ret = skb_copy_bits(skb, *offset, &ddgst[off], recv_len);
1076 	if (unlikely(ret))
1077 		return ret;
1078 
1079 	queue->ddgst_remaining -= recv_len;
1080 	*offset += recv_len;
1081 	*len -= recv_len;
1082 	if (queue->ddgst_remaining)
1083 		return 0;
1084 
1085 	if (queue->recv_ddgst != queue->exp_ddgst) {
1086 		struct request *rq = nvme_cid_to_rq(nvme_tcp_tagset(queue),
1087 					pdu->command_id);
1088 		struct nvme_tcp_request *req = blk_mq_rq_to_pdu(rq);
1089 
1090 		req->status = cpu_to_le16(NVME_SC_DATA_XFER_ERROR);
1091 
1092 		dev_err(queue->ctrl->ctrl.device,
1093 			"data digest error: recv %#x expected %#x\n",
1094 			le32_to_cpu(queue->recv_ddgst),
1095 			le32_to_cpu(queue->exp_ddgst));
1096 	}
1097 
1098 	if (pdu->hdr.flags & NVME_TCP_F_DATA_SUCCESS) {
1099 		struct request *rq = nvme_cid_to_rq(nvme_tcp_tagset(queue),
1100 					pdu->command_id);
1101 		struct nvme_tcp_request *req = blk_mq_rq_to_pdu(rq);
1102 
1103 		if (unlikely(nvme_tcp_data_in_short(queue, rq)))
1104 			return -EPROTO;
1105 
1106 		nvme_tcp_end_request(rq, le16_to_cpu(req->status));
1107 		queue->nr_cqe++;
1108 	}
1109 
1110 	nvme_tcp_init_recv_ctx(queue);
1111 	return 0;
1112 }
1113 
1114 static int nvme_tcp_recv_skb(read_descriptor_t *desc, struct sk_buff *skb,
1115 			     unsigned int offset, size_t len)
1116 {
1117 	struct nvme_tcp_queue *queue = desc->arg.data;
1118 	size_t consumed = len;
1119 	int result;
1120 
1121 	if (unlikely(!queue->rd_enabled))
1122 		return -EFAULT;
1123 
1124 	while (len) {
1125 		switch (nvme_tcp_recv_state(queue)) {
1126 		case NVME_TCP_RECV_PDU:
1127 			result = nvme_tcp_recv_pdu(queue, skb, &offset, &len);
1128 			break;
1129 		case NVME_TCP_RECV_DATA:
1130 			result = nvme_tcp_recv_data(queue, skb, &offset, &len);
1131 			break;
1132 		case NVME_TCP_RECV_DDGST:
1133 			result = nvme_tcp_recv_ddgst(queue, skb, &offset, &len);
1134 			break;
1135 		default:
1136 			result = -EFAULT;
1137 		}
1138 		if (result) {
1139 			dev_err(queue->ctrl->ctrl.device,
1140 				"receive failed:  %d\n", result);
1141 			queue->rd_enabled = false;
1142 			nvme_tcp_error_recovery(&queue->ctrl->ctrl);
1143 			return result;
1144 		}
1145 	}
1146 
1147 	return consumed;
1148 }
1149 
1150 static void nvme_tcp_data_ready(struct sock *sk)
1151 {
1152 	struct nvme_tcp_queue *queue;
1153 
1154 	trace_sk_data_ready(sk);
1155 
1156 	read_lock_bh(&sk->sk_callback_lock);
1157 	queue = sk->sk_user_data;
1158 	if (likely(queue && queue->rd_enabled) &&
1159 	    !test_bit(NVME_TCP_Q_POLLING, &queue->flags))
1160 		queue_work_on(queue->io_cpu, nvme_tcp_wq, &queue->io_work);
1161 	read_unlock_bh(&sk->sk_callback_lock);
1162 }
1163 
1164 static void nvme_tcp_write_space(struct sock *sk)
1165 {
1166 	struct nvme_tcp_queue *queue;
1167 
1168 	read_lock_bh(&sk->sk_callback_lock);
1169 	queue = sk->sk_user_data;
1170 	if (likely(queue && sk_stream_is_writeable(sk))) {
1171 		sk_clear_nospace(sk);
1172 		/* Ensure pending TLS partial records are retried */
1173 		if (nvme_tcp_queue_tls(queue))
1174 			queue->write_space(sk);
1175 		queue_work_on(queue->io_cpu, nvme_tcp_wq, &queue->io_work);
1176 	}
1177 	read_unlock_bh(&sk->sk_callback_lock);
1178 }
1179 
1180 static void nvme_tcp_state_change(struct sock *sk)
1181 {
1182 	struct nvme_tcp_queue *queue;
1183 
1184 	read_lock_bh(&sk->sk_callback_lock);
1185 	queue = sk->sk_user_data;
1186 	if (!queue)
1187 		goto done;
1188 
1189 	switch (sk->sk_state) {
1190 	case TCP_CLOSE:
1191 	case TCP_CLOSE_WAIT:
1192 	case TCP_LAST_ACK:
1193 	case TCP_FIN_WAIT1:
1194 	case TCP_FIN_WAIT2:
1195 		nvme_tcp_error_recovery(&queue->ctrl->ctrl);
1196 		break;
1197 	default:
1198 		dev_info(queue->ctrl->ctrl.device,
1199 			"queue %d socket state %d\n",
1200 			nvme_tcp_queue_id(queue), sk->sk_state);
1201 	}
1202 
1203 	queue->state_change(sk);
1204 done:
1205 	read_unlock_bh(&sk->sk_callback_lock);
1206 }
1207 
1208 static inline void nvme_tcp_done_send_req(struct nvme_tcp_queue *queue)
1209 {
1210 	queue->request = NULL;
1211 }
1212 
1213 static void nvme_tcp_fail_request(struct nvme_tcp_request *req)
1214 {
1215 	if (nvme_tcp_async_req(req)) {
1216 		union nvme_result res = {};
1217 
1218 		nvme_complete_async_event(&req->queue->ctrl->ctrl,
1219 				cpu_to_le16(NVME_SC_HOST_PATH_ERROR), &res);
1220 	} else {
1221 		nvme_tcp_end_request(blk_mq_rq_from_pdu(req),
1222 				NVME_SC_HOST_PATH_ERROR);
1223 	}
1224 }
1225 
1226 static int nvme_tcp_try_send_data(struct nvme_tcp_request *req)
1227 {
1228 	struct nvme_tcp_queue *queue = req->queue;
1229 	int req_data_len = req->data_len;
1230 	u32 h2cdata_left = req->h2cdata_left;
1231 
1232 	while (true) {
1233 		struct bio_vec bvec;
1234 		struct msghdr msg = {
1235 			.msg_flags = MSG_DONTWAIT | MSG_SPLICE_PAGES,
1236 		};
1237 		struct page *page = nvme_tcp_req_cur_page(req);
1238 		size_t offset = nvme_tcp_req_cur_offset(req);
1239 		size_t len = nvme_tcp_req_cur_length(req);
1240 		bool last = nvme_tcp_pdu_last_send(req, len);
1241 		int req_data_sent = req->data_sent;
1242 		int ret;
1243 
1244 		if (last && !queue->data_digest && !nvme_tcp_queue_more(queue))
1245 			msg.msg_flags |= MSG_EOR;
1246 		else
1247 			msg.msg_flags |= MSG_MORE;
1248 
1249 		if (!sendpages_ok(page, len, offset))
1250 			msg.msg_flags &= ~MSG_SPLICE_PAGES;
1251 
1252 		bvec_set_page(&bvec, page, len, offset);
1253 		iov_iter_bvec(&msg.msg_iter, ITER_SOURCE, &bvec, 1, len);
1254 		ret = sock_sendmsg(queue->sock, &msg);
1255 		if (ret <= 0)
1256 			return ret;
1257 
1258 		if (queue->data_digest)
1259 			nvme_tcp_ddgst_update(&queue->snd_crc, page,
1260 					offset, ret);
1261 
1262 		/*
1263 		 * update the request iterator except for the last payload send
1264 		 * in the request where we don't want to modify it as we may
1265 		 * compete with the RX path completing the request.
1266 		 */
1267 		if (req_data_sent + ret < req_data_len)
1268 			nvme_tcp_advance_req(req, ret);
1269 
1270 		/* fully successful last send in current PDU */
1271 		if (last && ret == len) {
1272 			if (queue->data_digest) {
1273 				req->ddgst =
1274 					nvme_tcp_ddgst_final(queue->snd_crc);
1275 				req->state = NVME_TCP_SEND_DDGST;
1276 				req->offset = 0;
1277 			} else {
1278 				if (h2cdata_left)
1279 					nvme_tcp_setup_h2c_data_pdu(req);
1280 				else
1281 					nvme_tcp_done_send_req(queue);
1282 			}
1283 			return 1;
1284 		}
1285 	}
1286 	return -EAGAIN;
1287 }
1288 
1289 static int nvme_tcp_try_send_cmd_pdu(struct nvme_tcp_request *req)
1290 {
1291 	struct nvme_tcp_queue *queue = req->queue;
1292 	struct nvme_tcp_cmd_pdu *pdu = nvme_tcp_req_cmd_pdu(req);
1293 	struct bio_vec bvec;
1294 	struct msghdr msg = { .msg_flags = MSG_DONTWAIT | MSG_SPLICE_PAGES, };
1295 	bool inline_data = nvme_tcp_has_inline_data(req);
1296 	u8 hdgst = nvme_tcp_hdgst_len(queue);
1297 	int len = sizeof(*pdu) + hdgst - req->offset;
1298 	int ret;
1299 
1300 	if (inline_data || nvme_tcp_queue_more(queue))
1301 		msg.msg_flags |= MSG_MORE;
1302 	else
1303 		msg.msg_flags |= MSG_EOR;
1304 
1305 	if (queue->hdr_digest && !req->offset)
1306 		nvme_tcp_set_hdgst(pdu, sizeof(*pdu));
1307 
1308 	bvec_set_virt(&bvec, (void *)pdu + req->offset, len);
1309 	iov_iter_bvec(&msg.msg_iter, ITER_SOURCE, &bvec, 1, len);
1310 	ret = sock_sendmsg(queue->sock, &msg);
1311 	if (unlikely(ret <= 0))
1312 		return ret;
1313 
1314 	len -= ret;
1315 	if (!len) {
1316 		if (inline_data) {
1317 			req->state = NVME_TCP_SEND_DATA;
1318 			if (queue->data_digest)
1319 				queue->snd_crc = NVME_TCP_CRC_SEED;
1320 		} else {
1321 			nvme_tcp_done_send_req(queue);
1322 		}
1323 		return 1;
1324 	}
1325 	req->offset += ret;
1326 
1327 	return -EAGAIN;
1328 }
1329 
1330 static int nvme_tcp_try_send_data_pdu(struct nvme_tcp_request *req)
1331 {
1332 	struct nvme_tcp_queue *queue = req->queue;
1333 	struct nvme_tcp_data_pdu *pdu = nvme_tcp_req_data_pdu(req);
1334 	struct bio_vec bvec;
1335 	struct msghdr msg = { .msg_flags = MSG_DONTWAIT | MSG_MORE, };
1336 	u8 hdgst = nvme_tcp_hdgst_len(queue);
1337 	int len = sizeof(*pdu) - req->offset + hdgst;
1338 	int ret;
1339 
1340 	if (queue->hdr_digest && !req->offset)
1341 		nvme_tcp_set_hdgst(pdu, sizeof(*pdu));
1342 
1343 	if (!req->h2cdata_left)
1344 		msg.msg_flags |= MSG_SPLICE_PAGES;
1345 
1346 	bvec_set_virt(&bvec, (void *)pdu + req->offset, len);
1347 	iov_iter_bvec(&msg.msg_iter, ITER_SOURCE, &bvec, 1, len);
1348 	ret = sock_sendmsg(queue->sock, &msg);
1349 	if (unlikely(ret <= 0))
1350 		return ret;
1351 
1352 	len -= ret;
1353 	if (!len) {
1354 		req->state = NVME_TCP_SEND_DATA;
1355 		if (queue->data_digest)
1356 			queue->snd_crc = NVME_TCP_CRC_SEED;
1357 		return 1;
1358 	}
1359 	req->offset += ret;
1360 
1361 	return -EAGAIN;
1362 }
1363 
1364 static int nvme_tcp_try_send_ddgst(struct nvme_tcp_request *req)
1365 {
1366 	struct nvme_tcp_queue *queue = req->queue;
1367 	size_t offset = req->offset;
1368 	u32 h2cdata_left = req->h2cdata_left;
1369 	int ret;
1370 	struct msghdr msg = { .msg_flags = MSG_DONTWAIT };
1371 	struct kvec iov = {
1372 		.iov_base = (u8 *)&req->ddgst + req->offset,
1373 		.iov_len = NVME_TCP_DIGEST_LENGTH - req->offset
1374 	};
1375 
1376 	if (nvme_tcp_queue_more(queue))
1377 		msg.msg_flags |= MSG_MORE;
1378 	else
1379 		msg.msg_flags |= MSG_EOR;
1380 
1381 	ret = kernel_sendmsg(queue->sock, &msg, &iov, 1, iov.iov_len);
1382 	if (unlikely(ret <= 0))
1383 		return ret;
1384 
1385 	if (offset + ret == NVME_TCP_DIGEST_LENGTH) {
1386 		if (h2cdata_left)
1387 			nvme_tcp_setup_h2c_data_pdu(req);
1388 		else
1389 			nvme_tcp_done_send_req(queue);
1390 		return 1;
1391 	}
1392 
1393 	req->offset += ret;
1394 	return -EAGAIN;
1395 }
1396 
1397 static int nvme_tcp_try_send(struct nvme_tcp_queue *queue)
1398 {
1399 	struct nvme_tcp_request *req;
1400 	unsigned int noreclaim_flag;
1401 	int ret = 1;
1402 
1403 	if (!queue->request) {
1404 		queue->request = nvme_tcp_fetch_request(queue);
1405 		if (!queue->request)
1406 			return 0;
1407 	}
1408 	req = queue->request;
1409 
1410 	noreclaim_flag = memalloc_noreclaim_save();
1411 	if (req->state == NVME_TCP_SEND_CMD_PDU) {
1412 		ret = nvme_tcp_try_send_cmd_pdu(req);
1413 		if (ret <= 0)
1414 			goto done;
1415 		if (!nvme_tcp_has_inline_data(req))
1416 			goto out;
1417 	}
1418 
1419 	if (req->state == NVME_TCP_SEND_H2C_PDU) {
1420 		ret = nvme_tcp_try_send_data_pdu(req);
1421 		if (ret <= 0)
1422 			goto done;
1423 	}
1424 
1425 	if (req->state == NVME_TCP_SEND_DATA) {
1426 		ret = nvme_tcp_try_send_data(req);
1427 		if (ret <= 0)
1428 			goto done;
1429 	}
1430 
1431 	if (req->state == NVME_TCP_SEND_DDGST)
1432 		ret = nvme_tcp_try_send_ddgst(req);
1433 done:
1434 	if (ret == -EAGAIN) {
1435 		ret = 0;
1436 	} else if (ret < 0) {
1437 		dev_err(queue->ctrl->ctrl.device,
1438 			"failed to send request %d\n", ret);
1439 		nvme_tcp_fail_request(queue->request);
1440 		nvme_tcp_done_send_req(queue);
1441 	}
1442 out:
1443 	memalloc_noreclaim_restore(noreclaim_flag);
1444 	return ret;
1445 }
1446 
1447 static int nvme_tcp_try_recv(struct nvme_tcp_queue *queue)
1448 {
1449 	struct socket *sock = queue->sock;
1450 	struct sock *sk = sock->sk;
1451 	read_descriptor_t rd_desc;
1452 	int consumed;
1453 
1454 	rd_desc.arg.data = queue;
1455 	rd_desc.count = 1;
1456 	lock_sock(sk);
1457 	queue->nr_cqe = 0;
1458 	consumed = sock->ops->read_sock(sk, &rd_desc, nvme_tcp_recv_skb);
1459 	/*
1460 	 * nvme_tcp_recv_skb() handles its own errors, so a queue that is
1461 	 * still enabled failed inside read_sock(). Handle it before
1462 	 * release_sock() processes the backlog.
1463 	 */
1464 	if (unlikely(consumed < 0 && consumed != -EAGAIN &&
1465 		     queue->rd_enabled)) {
1466 		dev_err(queue->ctrl->ctrl.device,
1467 			"queue %d: receive failed: %d\n",
1468 			nvme_tcp_queue_id(queue), consumed);
1469 		queue->rd_enabled = false;
1470 		nvme_tcp_error_recovery(&queue->ctrl->ctrl);
1471 	}
1472 	release_sock(sk);
1473 	return consumed == -EAGAIN ? 0 : consumed;
1474 }
1475 
1476 static void nvme_tcp_io_work(struct work_struct *w)
1477 {
1478 	struct nvme_tcp_queue *queue =
1479 		container_of(w, struct nvme_tcp_queue, io_work);
1480 	unsigned long deadline = jiffies + msecs_to_jiffies(1);
1481 
1482 	do {
1483 		bool pending = false;
1484 		bool got_send_mutex = false;
1485 		int result;
1486 
1487 		if (mutex_trylock(&queue->send_mutex)) {
1488 			got_send_mutex = true;
1489 			result = nvme_tcp_try_send(queue);
1490 			mutex_unlock(&queue->send_mutex);
1491 			if (result > 0)
1492 				pending = true;
1493 			else if (unlikely(result < 0))
1494 				break;
1495 		}
1496 
1497 		result = nvme_tcp_try_recv(queue);
1498 		if (result > 0)
1499 			pending = true;
1500 		else if (unlikely(result < 0))
1501 			return;
1502 
1503 		/*
1504 		 * did we get some space after spending time in recv?
1505 		 * Only check this if we could take send_mutex. Otherwise
1506 		 * the task holding it sends the requests and queues io_work
1507 		 * again after it releases the mutex.
1508 		 */
1509 		if (got_send_mutex && nvme_tcp_queue_has_pending(queue) &&
1510 		    sk_stream_is_writeable(queue->sock->sk))
1511 			pending = true;
1512 
1513 		if (!pending || !queue->rd_enabled)
1514 			return;
1515 
1516 	} while (!time_after(jiffies, deadline)); /* quota is exhausted */
1517 
1518 	queue_work_on(queue->io_cpu, nvme_tcp_wq, &queue->io_work);
1519 }
1520 
1521 static void nvme_tcp_free_async_req(struct nvme_tcp_ctrl *ctrl)
1522 {
1523 	struct nvme_tcp_request *async = &ctrl->async_req;
1524 
1525 	page_frag_free(async->pdu);
1526 }
1527 
1528 static int nvme_tcp_alloc_async_req(struct nvme_tcp_ctrl *ctrl)
1529 {
1530 	struct nvme_tcp_queue *queue = &ctrl->queues[0];
1531 	struct nvme_tcp_request *async = &ctrl->async_req;
1532 	u8 hdgst = nvme_tcp_hdgst_len(queue);
1533 
1534 	mutex_lock(&queue->pf_cache_lock);
1535 	async->pdu = page_frag_alloc(&queue->pf_cache,
1536 		sizeof(struct nvme_tcp_cmd_pdu) + hdgst,
1537 		GFP_KERNEL | __GFP_ZERO);
1538 	mutex_unlock(&queue->pf_cache_lock);
1539 	if (!async->pdu)
1540 		return -ENOMEM;
1541 
1542 	async->queue = &ctrl->queues[0];
1543 	return 0;
1544 }
1545 
1546 static void nvme_tcp_free_queue(struct nvme_ctrl *nctrl, int qid)
1547 {
1548 	struct nvme_tcp_ctrl *ctrl = to_tcp_ctrl(nctrl);
1549 	struct nvme_tcp_queue *queue = &ctrl->queues[qid];
1550 	unsigned int noio_flag;
1551 
1552 	if (!test_and_clear_bit(NVME_TCP_Q_ALLOCATED, &queue->flags))
1553 		return;
1554 
1555 	page_frag_cache_drain(&queue->pf_cache);
1556 
1557 	/**
1558 	 * Prevent memory reclaim from triggering block I/O during socket
1559 	 * teardown. The socket release path fput -> tcp_close ->
1560 	 * tcp_disconnect -> tcp_send_active_reset may allocate memory, and
1561 	 * allowing reclaim to issue I/O could deadlock if we're being called
1562 	 * from block device teardown (e.g., del_gendisk -> elevator cleanup)
1563 	 * which holds locks that the I/O completion path needs.
1564 	 */
1565 	noio_flag = memalloc_noio_save();
1566 
1567 	/**
1568 	 * Release the socket synchronously. During reset in
1569 	 * nvme_reset_ctrl_work(), queue teardown is immediately followed by
1570 	 * re-allocation. fput() defers socket cleanup to delayed_fput_work
1571 	 * in workqueue context, which can race with new queue setup.
1572 	 *
1573 	 * Clear queue->sock under the queue lock so that a sysfs reader in
1574 	 * nvme_tcp_get_address() either observes the NVME_TCP_Q_LIVE bit
1575 	 * cleared or a still valid socket.  The queue lock itself is owned
1576 	 * by the controller and only destroyed when the controller is
1577 	 * freed, so readers blocked on it cannot race its teardown.
1578 	 */
1579 	mutex_lock(&queue->queue_lock);
1580 	__fput_sync(queue->sock->file);
1581 	queue->sock = NULL;
1582 	mutex_unlock(&queue->queue_lock);
1583 	memalloc_noio_restore(noio_flag);
1584 
1585 	kfree(queue->pdu);
1586 }
1587 
1588 static int nvme_tcp_recv_tls_alert(struct nvme_tcp_queue *queue,
1589 				   struct msghdr *msg, int len)
1590 {
1591 	struct sock *sk = queue->sock->sk;
1592 	u8 level, description;
1593 
1594 	if (len < 2) {
1595 		dev_err(queue->ctrl->ctrl.device,
1596 			"queue %d: truncated TLS alert\n",
1597 			nvme_tcp_queue_id(queue));
1598 		return -ENOTCONN;
1599 	}
1600 
1601 	/* tls_alert_recv() reads through the iterator */
1602 	iov_iter_revert(&msg->msg_iter, len);
1603 	tls_alert_recv(sk, msg, &level, &description);
1604 
1605 	if (level == TLS_ALERT_LEVEL_FATAL) {
1606 		dev_err(queue->ctrl->ctrl.device,
1607 			"queue %d: fatal TLS alert %u\n",
1608 			nvme_tcp_queue_id(queue), description);
1609 		return -ENOTCONN;
1610 	}
1611 
1612 	/* a peer shutting down normally is not worth a warning */
1613 	if (description == TLS_ALERT_DESC_CLOSE_NOTIFY)
1614 		dev_dbg(queue->ctrl->ctrl.device,
1615 			"queue %d: TLS close_notify\n",
1616 			nvme_tcp_queue_id(queue));
1617 	else
1618 		dev_warn(queue->ctrl->ctrl.device,
1619 			 "queue %d: TLS alert %u\n",
1620 			 nvme_tcp_queue_id(queue), description);
1621 
1622 	return 0;
1623 }
1624 
1625 /*
1626  * Discard a TLS record that arrived in place of the ICResp. A peer may send
1627  * a NewSessionTicket as soon as the handshake completes.
1628  *
1629  * Returns 0 when the record was discarded and the ICResp can be read, or a
1630  * negative errno if the connection cannot continue.
1631  */
1632 static int nvme_tcp_skip_tls_record(struct nvme_tcp_queue *queue,
1633 				    struct msghdr *msg, u8 ctype, int len)
1634 {
1635 	u8 buf[NVME_TCP_TLS_REC_CHUNK];
1636 	int ret;
1637 
1638 	switch (ctype) {
1639 	case TLS_RECORD_TYPE_HANDSHAKE:
1640 		break;
1641 	case TLS_RECORD_TYPE_ALERT:
1642 		ret = nvme_tcp_recv_tls_alert(queue, msg, len);
1643 		return ret ? : -ENOTCONN;
1644 	default:
1645 		pr_err("queue %d: unhandled TLS record %u\n",
1646 		       nvme_tcp_queue_id(queue), ctype);
1647 		return -ENOTCONN;
1648 	}
1649 
1650 	/* the ICResp is in a later record, drain this one first */
1651 	while (!(msg->msg_flags & MSG_EOR)) {
1652 		struct kvec iov = {
1653 			.iov_base = buf,
1654 			.iov_len = sizeof(buf),
1655 		};
1656 		char cbuf[CMSG_LEN(sizeof(char))] = {};
1657 		/* kTLS fails a control record read without a cmsg buffer */
1658 		struct msghdr drain = {
1659 			.msg_control = cbuf,
1660 			.msg_controllen = sizeof(cbuf),
1661 		};
1662 
1663 		ret = kernel_recvmsg(queue->sock, &drain, &iov, 1, sizeof(buf),
1664 				     0);
1665 		if (ret <= 0) {
1666 			pr_warn("queue %d: failed to drain TLS record: %d\n",
1667 				nvme_tcp_queue_id(queue), ret);
1668 			return ret ? : -ECONNRESET;
1669 		}
1670 		msg->msg_flags = drain.msg_flags;
1671 	}
1672 
1673 	return 0;
1674 }
1675 
1676 /*
1677  * Receive the ICResp. Over TLS, skip the records that a peer may send
1678  * ahead of it.
1679  *
1680  * Returns the length received, or a negative errno.
1681  */
1682 static int nvme_tcp_recv_icresp(struct nvme_tcp_queue *queue,
1683 				struct nvme_tcp_icresp_pdu *icresp)
1684 {
1685 	char cbuf[CMSG_LEN(sizeof(char))];
1686 	struct msghdr msg;
1687 	struct kvec iov;
1688 	u8 ctype;
1689 	int i, ret;
1690 
1691 	for (i = 0; i < NVME_TCP_ICRESP_MAX_RECORDS; i++) {
1692 		memset(&msg, 0, sizeof(msg));
1693 		memset(cbuf, 0, sizeof(cbuf));
1694 		iov.iov_base = icresp;
1695 		iov.iov_len = sizeof(*icresp);
1696 		if (nvme_tcp_queue_tls(queue)) {
1697 			msg.msg_control = cbuf;
1698 			msg.msg_controllen = sizeof(cbuf);
1699 		}
1700 		msg.msg_flags = MSG_WAITALL;
1701 		ret = kernel_recvmsg(queue->sock, &msg, &iov, 1,
1702 				     iov.iov_len, msg.msg_flags);
1703 		if (ret <= 0 || !nvme_tcp_queue_tls(queue))
1704 			return ret;
1705 
1706 		ctype = tls_get_record_type(queue->sock->sk,
1707 					    (struct cmsghdr *)cbuf);
1708 		if (ctype == TLS_RECORD_TYPE_DATA)
1709 			return ret;
1710 
1711 		ret = nvme_tcp_skip_tls_record(queue, &msg, ctype, ret);
1712 		if (ret < 0)
1713 			return ret;
1714 	}
1715 
1716 	pr_err("queue %d: too many TLS records before the ICResp\n",
1717 	       nvme_tcp_queue_id(queue));
1718 	return -EPROTO;
1719 }
1720 
1721 static int nvme_tcp_init_connection(struct nvme_tcp_queue *queue)
1722 {
1723 	struct nvme_tcp_icreq_pdu *icreq;
1724 	struct nvme_tcp_icresp_pdu *icresp;
1725 	struct msghdr msg = {};
1726 	struct kvec iov;
1727 	bool ctrl_hdgst, ctrl_ddgst;
1728 	u32 maxh2cdata;
1729 	int ret;
1730 
1731 	icreq = kzalloc_obj(*icreq);
1732 	if (!icreq)
1733 		return -ENOMEM;
1734 
1735 	icresp = kzalloc_obj(*icresp);
1736 	if (!icresp) {
1737 		ret = -ENOMEM;
1738 		goto free_icreq;
1739 	}
1740 
1741 	icreq->hdr.type = nvme_tcp_icreq;
1742 	icreq->hdr.hlen = sizeof(*icreq);
1743 	icreq->hdr.pdo = 0;
1744 	icreq->hdr.plen = cpu_to_le32(icreq->hdr.hlen);
1745 	icreq->pfv = cpu_to_le16(NVME_TCP_PFV_1_0);
1746 	icreq->maxr2t = 0; /* single inflight r2t supported */
1747 	icreq->hpda = 0; /* no alignment constraint */
1748 	if (queue->hdr_digest)
1749 		icreq->digest |= NVME_TCP_HDR_DIGEST_ENABLE;
1750 	if (queue->data_digest)
1751 		icreq->digest |= NVME_TCP_DATA_DIGEST_ENABLE;
1752 
1753 	iov.iov_base = icreq;
1754 	iov.iov_len = sizeof(*icreq);
1755 	ret = kernel_sendmsg(queue->sock, &msg, &iov, 1, iov.iov_len);
1756 	if (ret < 0) {
1757 		pr_warn("queue %d: failed to send icreq, error %d\n",
1758 			nvme_tcp_queue_id(queue), ret);
1759 		goto free_icresp;
1760 	}
1761 
1762 	ret = nvme_tcp_recv_icresp(queue, icresp);
1763 	if (ret >= 0 && ret < sizeof(*icresp))
1764 		ret = -ECONNRESET;
1765 	if (ret < 0) {
1766 		pr_warn("queue %d: failed to receive icresp, error %d\n",
1767 			nvme_tcp_queue_id(queue), ret);
1768 		goto free_icresp;
1769 	}
1770 	ret = -EINVAL;
1771 	if (icresp->hdr.type != nvme_tcp_icresp) {
1772 		pr_err("queue %d: bad type returned %d\n",
1773 			nvme_tcp_queue_id(queue), icresp->hdr.type);
1774 		goto free_icresp;
1775 	}
1776 
1777 	if (le32_to_cpu(icresp->hdr.plen) != sizeof(*icresp)) {
1778 		pr_err("queue %d: bad pdu length returned %d\n",
1779 			nvme_tcp_queue_id(queue), icresp->hdr.plen);
1780 		goto free_icresp;
1781 	}
1782 
1783 	if (icresp->pfv != NVME_TCP_PFV_1_0) {
1784 		pr_err("queue %d: bad pfv returned %d\n",
1785 			nvme_tcp_queue_id(queue), icresp->pfv);
1786 		goto free_icresp;
1787 	}
1788 
1789 	ctrl_ddgst = !!(icresp->digest & NVME_TCP_DATA_DIGEST_ENABLE);
1790 	if ((queue->data_digest && !ctrl_ddgst) ||
1791 	    (!queue->data_digest && ctrl_ddgst)) {
1792 		pr_err("queue %d: data digest mismatch host: %s ctrl: %s\n",
1793 			nvme_tcp_queue_id(queue),
1794 			queue->data_digest ? "enabled" : "disabled",
1795 			ctrl_ddgst ? "enabled" : "disabled");
1796 		goto free_icresp;
1797 	}
1798 
1799 	ctrl_hdgst = !!(icresp->digest & NVME_TCP_HDR_DIGEST_ENABLE);
1800 	if ((queue->hdr_digest && !ctrl_hdgst) ||
1801 	    (!queue->hdr_digest && ctrl_hdgst)) {
1802 		pr_err("queue %d: header digest mismatch host: %s ctrl: %s\n",
1803 			nvme_tcp_queue_id(queue),
1804 			queue->hdr_digest ? "enabled" : "disabled",
1805 			ctrl_hdgst ? "enabled" : "disabled");
1806 		goto free_icresp;
1807 	}
1808 
1809 	if (icresp->cpda != 0) {
1810 		pr_err("queue %d: unsupported cpda returned %d\n",
1811 			nvme_tcp_queue_id(queue), icresp->cpda);
1812 		goto free_icresp;
1813 	}
1814 
1815 	maxh2cdata = le32_to_cpu(icresp->maxdata);
1816 	if ((maxh2cdata % 4) || (maxh2cdata < NVME_TCP_MIN_MAXH2CDATA)) {
1817 		pr_err("queue %d: invalid maxh2cdata returned %u\n",
1818 		       nvme_tcp_queue_id(queue), maxh2cdata);
1819 		goto free_icresp;
1820 	}
1821 	queue->maxh2cdata = maxh2cdata;
1822 
1823 	ret = 0;
1824 free_icresp:
1825 	kfree(icresp);
1826 free_icreq:
1827 	kfree(icreq);
1828 	return ret;
1829 }
1830 
1831 static bool nvme_tcp_admin_queue(struct nvme_tcp_queue *queue)
1832 {
1833 	return nvme_tcp_queue_id(queue) == 0;
1834 }
1835 
1836 static bool nvme_tcp_default_queue(struct nvme_tcp_queue *queue)
1837 {
1838 	struct nvme_tcp_ctrl *ctrl = queue->ctrl;
1839 	int qid = nvme_tcp_queue_id(queue);
1840 
1841 	return !nvme_tcp_admin_queue(queue) &&
1842 		qid < 1 + ctrl->io_queues[HCTX_TYPE_DEFAULT];
1843 }
1844 
1845 static bool nvme_tcp_read_queue(struct nvme_tcp_queue *queue)
1846 {
1847 	struct nvme_tcp_ctrl *ctrl = queue->ctrl;
1848 	int qid = nvme_tcp_queue_id(queue);
1849 
1850 	return !nvme_tcp_admin_queue(queue) &&
1851 		!nvme_tcp_default_queue(queue) &&
1852 		qid < 1 + ctrl->io_queues[HCTX_TYPE_DEFAULT] +
1853 			  ctrl->io_queues[HCTX_TYPE_READ];
1854 }
1855 
1856 static bool nvme_tcp_poll_queue(struct nvme_tcp_queue *queue)
1857 {
1858 	struct nvme_tcp_ctrl *ctrl = queue->ctrl;
1859 	int qid = nvme_tcp_queue_id(queue);
1860 
1861 	return !nvme_tcp_admin_queue(queue) &&
1862 		!nvme_tcp_default_queue(queue) &&
1863 		!nvme_tcp_read_queue(queue) &&
1864 		qid < 1 + ctrl->io_queues[HCTX_TYPE_DEFAULT] +
1865 			  ctrl->io_queues[HCTX_TYPE_READ] +
1866 			  ctrl->io_queues[HCTX_TYPE_POLL];
1867 }
1868 
1869 /*
1870  * Track the number of queues assigned to each cpu using a global per-cpu
1871  * counter and select the least used cpu from the mq_map. Our goal is to spread
1872  * different controllers I/O threads across different cpu cores.
1873  *
1874  * Note that the accounting is not 100% perfect, but we don't need to be, we're
1875  * simply putting our best effort to select the best candidate cpu core that we
1876  * find at any given point.
1877  */
1878 static void nvme_tcp_set_queue_io_cpu(struct nvme_tcp_queue *queue)
1879 {
1880 	struct nvme_tcp_ctrl *ctrl = queue->ctrl;
1881 	struct blk_mq_tag_set *set = &ctrl->tag_set;
1882 	int qid = nvme_tcp_queue_id(queue) - 1;
1883 	unsigned int *mq_map = NULL;
1884 	int cpu, min_queues = INT_MAX, io_cpu;
1885 
1886 	if (wq_unbound)
1887 		goto out;
1888 
1889 	if (nvme_tcp_default_queue(queue))
1890 		mq_map = set->map[HCTX_TYPE_DEFAULT].mq_map;
1891 	else if (nvme_tcp_read_queue(queue))
1892 		mq_map = set->map[HCTX_TYPE_READ].mq_map;
1893 	else if (nvme_tcp_poll_queue(queue))
1894 		mq_map = set->map[HCTX_TYPE_POLL].mq_map;
1895 
1896 	if (WARN_ON(!mq_map))
1897 		goto out;
1898 
1899 	/* Search for the least used cpu from the mq_map */
1900 	spin_lock(&nvme_tcp_cpu_queues_lock);
1901 	io_cpu = WORK_CPU_UNBOUND;
1902 	for_each_online_cpu(cpu) {
1903 		int num_queues = nvme_tcp_cpu_queues[cpu];
1904 
1905 		if (mq_map[cpu] != qid)
1906 			continue;
1907 		if (num_queues < min_queues) {
1908 			io_cpu = cpu;
1909 			min_queues = num_queues;
1910 		}
1911 	}
1912 	if (io_cpu != WORK_CPU_UNBOUND) {
1913 		queue->io_cpu = io_cpu;
1914 		nvme_tcp_cpu_queues[io_cpu]++;
1915 		set_bit(NVME_TCP_Q_IO_CPU_SET, &queue->flags);
1916 	}
1917 	spin_unlock(&nvme_tcp_cpu_queues_lock);
1918 out:
1919 	dev_dbg(ctrl->ctrl.device, "queue %d: using cpu %d\n",
1920 		qid, queue->io_cpu);
1921 }
1922 
1923 static void nvme_tcp_tls_done(void *data, int status, key_serial_t pskid)
1924 {
1925 	struct nvme_tcp_queue *queue = data;
1926 	struct nvme_tcp_ctrl *ctrl = queue->ctrl;
1927 	int qid = nvme_tcp_queue_id(queue);
1928 	struct key *tls_key;
1929 
1930 	dev_dbg(ctrl->ctrl.device, "queue %d: TLS handshake done, key %x, status %d\n",
1931 		qid, pskid, status);
1932 
1933 	if (status) {
1934 		queue->tls_err = status;
1935 		goto out_complete;
1936 	}
1937 
1938 	tls_key = nvme_tls_key_lookup(pskid);
1939 	if (IS_ERR(tls_key)) {
1940 		dev_warn(ctrl->ctrl.device, "queue %d: Invalid key %x\n",
1941 			 qid, pskid);
1942 		queue->tls_err = -ENOKEY;
1943 	} else {
1944 		queue->tls_enabled = true;
1945 		if (qid == 0)
1946 			ctrl->ctrl.tls_pskid = key_serial(tls_key);
1947 		key_put(tls_key);
1948 		queue->tls_err = 0;
1949 	}
1950 
1951 out_complete:
1952 	complete(&queue->tls_complete);
1953 }
1954 
1955 static int nvme_tcp_start_tls(struct nvme_ctrl *nctrl,
1956 			      struct nvme_tcp_queue *queue,
1957 			      key_serial_t pskid)
1958 {
1959 	int qid = nvme_tcp_queue_id(queue);
1960 	int ret;
1961 	long wait_ret;
1962 	struct tls_handshake_args args;
1963 	unsigned int timeout = READ_ONCE(tls_handshake_timeout);
1964 	unsigned long tmo = (unsigned long)timeout * HZ;
1965 	key_serial_t keyring = nvme_keyring_id();
1966 
1967 	dev_dbg(nctrl->device, "queue %d: start TLS with key %x\n",
1968 		qid, pskid);
1969 	memset(&args, 0, sizeof(args));
1970 	args.ta_sock = queue->sock;
1971 	args.ta_done = nvme_tcp_tls_done;
1972 	args.ta_data = queue;
1973 	args.ta_my_peerids[0] = pskid;
1974 	args.ta_num_peerids = 1;
1975 	if (nctrl->opts->keyring)
1976 		keyring = key_serial(nctrl->opts->keyring);
1977 	args.ta_keyring = keyring;
1978 	args.ta_timeout_ms = timeout * MSEC_PER_SEC;
1979 	queue->tls_err = -EOPNOTSUPP;
1980 	init_completion(&queue->tls_complete);
1981 	ret = tls_client_hello_psk(&args, GFP_KERNEL);
1982 	if (ret) {
1983 		dev_err(nctrl->device, "queue %d: failed to start TLS: %d\n",
1984 			qid, ret);
1985 		return ret;
1986 	}
1987 	wait_ret = wait_for_completion_interruptible_timeout(&queue->tls_complete,
1988 							     tmo);
1989 	if (wait_ret <= 0) {
1990 		ret = wait_ret < 0 ? -ERESTARTSYS : -ETIMEDOUT;
1991 
1992 		dev_err(nctrl->device,
1993 			"queue %d: TLS handshake failed, error %d\n",
1994 			qid, ret);
1995 		tls_handshake_cancel(queue->sock->sk);
1996 	} else {
1997 		if (queue->tls_err) {
1998 			dev_err(nctrl->device,
1999 				"queue %d: TLS handshake complete, error %d\n",
2000 				qid, queue->tls_err);
2001 		} else {
2002 			dev_dbg(nctrl->device,
2003 				"queue %d: TLS handshake complete\n", qid);
2004 		}
2005 		ret = queue->tls_err;
2006 	}
2007 	return ret;
2008 }
2009 
2010 static void nvme_tcp_init_queue(struct nvme_tcp_ctrl *ctrl, int qid)
2011 {
2012 	struct nvme_tcp_queue *queue = &ctrl->queues[qid];
2013 
2014 	queue->ctrl = ctrl;
2015 	mutex_init(&queue->queue_lock);
2016 	mutex_init(&queue->send_mutex);
2017 	mutex_init(&queue->pf_cache_lock);
2018 	INIT_WORK(&queue->io_work, nvme_tcp_io_work);
2019 	queue->hdr_digest = ctrl->ctrl.opts->hdr_digest;
2020 	queue->data_digest = ctrl->ctrl.opts->data_digest;
2021 }
2022 
2023 static void nvme_tcp_exit_queue(struct nvme_tcp_ctrl *ctrl, int qid)
2024 {
2025 	struct nvme_tcp_queue *queue = &ctrl->queues[qid];
2026 
2027 	mutex_destroy(&queue->queue_lock);
2028 	mutex_destroy(&queue->send_mutex);
2029 	mutex_destroy(&queue->pf_cache_lock);
2030 }
2031 
2032 static int nvme_tcp_alloc_queue(struct nvme_ctrl *nctrl, int qid,
2033 				key_serial_t pskid)
2034 {
2035 	struct nvme_tcp_ctrl *ctrl = to_tcp_ctrl(nctrl);
2036 	struct nvme_tcp_queue *queue = &ctrl->queues[qid];
2037 	int ret, rcv_pdu_size;
2038 	struct file *sock_file;
2039 
2040 	init_llist_head(&queue->req_list);
2041 	INIT_LIST_HEAD(&queue->send_list);
2042 
2043 	if (qid > 0)
2044 		queue->cmnd_capsule_len = nctrl->ioccsz * 16;
2045 	else
2046 		queue->cmnd_capsule_len = sizeof(struct nvme_command) +
2047 						NVME_TCP_ADMIN_CCSZ;
2048 
2049 	ret = sock_create_kern(ctrl->net,
2050 			ctrl->addr.ss_family, SOCK_STREAM,
2051 			IPPROTO_TCP, &queue->sock);
2052 	if (ret) {
2053 		dev_err(nctrl->device,
2054 			"failed to create socket: %d\n", ret);
2055 		return ret;
2056 	}
2057 
2058 	sock_file = sock_alloc_file(queue->sock, O_CLOEXEC, NULL);
2059 	if (IS_ERR(sock_file))
2060 		return PTR_ERR(sock_file);
2061 
2062 	sk_net_refcnt_upgrade(queue->sock->sk);
2063 
2064 	/* Single syn retry */
2065 	tcp_sock_set_syncnt(queue->sock->sk, 1);
2066 
2067 	/* Set TCP no delay */
2068 	tcp_sock_set_nodelay(queue->sock->sk);
2069 
2070 	/*
2071 	 * Cleanup whatever is sitting in the TCP transmit queue on socket
2072 	 * close. This is done to prevent stale data from being sent should
2073 	 * the network connection be restored before TCP times out.
2074 	 */
2075 	sock_no_linger(queue->sock->sk);
2076 
2077 	if (so_priority > 0)
2078 		sock_set_priority(queue->sock->sk, so_priority);
2079 
2080 	/* Set socket type of service */
2081 	if (nctrl->opts->tos >= 0)
2082 		ip_sock_set_tos(queue->sock->sk, nctrl->opts->tos);
2083 
2084 	/* Set 10 seconds timeout for icresp recvmsg */
2085 	queue->sock->sk->sk_rcvtimeo = 10 * HZ;
2086 
2087 	queue->sock->sk->sk_allocation = GFP_ATOMIC;
2088 	queue->sock->sk->sk_use_task_frag = false;
2089 	queue->io_cpu = WORK_CPU_UNBOUND;
2090 	queue->request = NULL;
2091 	queue->data_remaining = 0;
2092 	queue->ddgst_remaining = 0;
2093 	queue->pdu_remaining = 0;
2094 	queue->pdu_offset = 0;
2095 	sk_set_memalloc(queue->sock->sk);
2096 
2097 	if (nctrl->opts->mask & NVMF_OPT_HOST_TRADDR) {
2098 		ret = kernel_bind(queue->sock, (struct sockaddr_unsized *)&ctrl->src_addr,
2099 			sizeof(ctrl->src_addr));
2100 		if (ret) {
2101 			dev_err(nctrl->device,
2102 				"failed to bind queue %d socket %d\n",
2103 				qid, ret);
2104 			goto err_sock;
2105 		}
2106 	}
2107 
2108 	if (nctrl->opts->mask & NVMF_OPT_HOST_IFACE) {
2109 		char *iface = nctrl->opts->host_iface;
2110 		sockptr_t optval = KERNEL_SOCKPTR(iface);
2111 
2112 		ret = sock_setsockopt(queue->sock, SOL_SOCKET, SO_BINDTODEVICE,
2113 				      optval, strlen(iface));
2114 		if (ret) {
2115 			dev_err(nctrl->device,
2116 			  "failed to bind to interface %s queue %d err %d\n",
2117 			  iface, qid, ret);
2118 			goto err_sock;
2119 		}
2120 	}
2121 
2122 	rcv_pdu_size = sizeof(struct nvme_tcp_rsp_pdu) +
2123 			nvme_tcp_hdgst_len(queue);
2124 	queue->pdu = kmalloc(rcv_pdu_size, GFP_KERNEL);
2125 	if (!queue->pdu) {
2126 		ret = -ENOMEM;
2127 		goto err_sock;
2128 	}
2129 
2130 	dev_dbg(nctrl->device, "connecting queue %d\n",
2131 			nvme_tcp_queue_id(queue));
2132 
2133 	ret = kernel_connect(queue->sock, (struct sockaddr_unsized *)&ctrl->addr,
2134 		sizeof(ctrl->addr), 0);
2135 	if (ret) {
2136 		dev_err(nctrl->device,
2137 			"failed to connect socket: %d\n", ret);
2138 		goto err_rcv_pdu;
2139 	}
2140 
2141 	/* If PSKs are configured try to start TLS */
2142 	if (nvme_tcp_tls_configured(nctrl) && pskid) {
2143 		ret = nvme_tcp_start_tls(nctrl, queue, pskid);
2144 		if (ret)
2145 			goto err_init_connect;
2146 	}
2147 
2148 	nvme_tcp_reclassify_socket(queue->sock);
2149 
2150 	ret = nvme_tcp_init_connection(queue);
2151 	if (ret)
2152 		goto err_init_connect;
2153 
2154 	set_bit(NVME_TCP_Q_ALLOCATED, &queue->flags);
2155 
2156 	return 0;
2157 
2158 err_init_connect:
2159 	kernel_sock_shutdown(queue->sock, SHUT_RDWR);
2160 err_rcv_pdu:
2161 	kfree(queue->pdu);
2162 err_sock:
2163 	/* Use sync variant - see nvme_tcp_free_queue() for explanation */
2164 	__fput_sync(queue->sock->file);
2165 	queue->sock = NULL;
2166 	return ret;
2167 }
2168 
2169 static void nvme_tcp_restore_sock_ops(struct nvme_tcp_queue *queue)
2170 {
2171 	struct socket *sock = queue->sock;
2172 
2173 	write_lock_bh(&sock->sk->sk_callback_lock);
2174 	sock->sk->sk_user_data  = NULL;
2175 	sock->sk->sk_data_ready = queue->data_ready;
2176 	sock->sk->sk_state_change = queue->state_change;
2177 	sock->sk->sk_write_space  = queue->write_space;
2178 	write_unlock_bh(&sock->sk->sk_callback_lock);
2179 }
2180 
2181 static void __nvme_tcp_stop_queue(struct nvme_tcp_queue *queue)
2182 {
2183 	kernel_sock_shutdown(queue->sock, SHUT_RDWR);
2184 	nvme_tcp_restore_sock_ops(queue);
2185 	cancel_work_sync(&queue->io_work);
2186 }
2187 
2188 static void nvme_tcp_stop_queue_nowait(struct nvme_ctrl *nctrl, int qid)
2189 {
2190 	struct nvme_tcp_ctrl *ctrl = to_tcp_ctrl(nctrl);
2191 	struct nvme_tcp_queue *queue = &ctrl->queues[qid];
2192 
2193 	if (!test_bit(NVME_TCP_Q_ALLOCATED, &queue->flags))
2194 		return;
2195 
2196 	if (test_and_clear_bit(NVME_TCP_Q_IO_CPU_SET, &queue->flags)) {
2197 		spin_lock(&nvme_tcp_cpu_queues_lock);
2198 		nvme_tcp_cpu_queues[queue->io_cpu]--;
2199 		spin_unlock(&nvme_tcp_cpu_queues_lock);
2200 	}
2201 
2202 	mutex_lock(&queue->queue_lock);
2203 	if (test_and_clear_bit(NVME_TCP_Q_LIVE, &queue->flags))
2204 		__nvme_tcp_stop_queue(queue);
2205 	/* Stopping the queue will disable TLS */
2206 	queue->tls_enabled = false;
2207 	mutex_unlock(&queue->queue_lock);
2208 }
2209 
2210 static void nvme_tcp_wait_queue(struct nvme_ctrl *nctrl, int qid)
2211 {
2212 	struct nvme_tcp_ctrl *ctrl = to_tcp_ctrl(nctrl);
2213 	struct nvme_tcp_queue *queue = &ctrl->queues[qid];
2214 	int timeout = 100;
2215 
2216 	while (timeout > 0) {
2217 		if (!test_bit(NVME_TCP_Q_ALLOCATED, &queue->flags) ||
2218 		    !sk_wmem_alloc_get(queue->sock->sk))
2219 			return;
2220 		msleep(2);
2221 		timeout -= 2;
2222 	}
2223 	dev_warn(nctrl->device,
2224 		 "qid %d: timeout draining sock wmem allocation expired\n",
2225 		 qid);
2226 }
2227 
2228 static void nvme_tcp_stop_queue(struct nvme_ctrl *nctrl, int qid)
2229 {
2230 	nvme_tcp_stop_queue_nowait(nctrl, qid);
2231 	nvme_tcp_wait_queue(nctrl, qid);
2232 }
2233 
2234 
2235 static void nvme_tcp_setup_sock_ops(struct nvme_tcp_queue *queue)
2236 {
2237 	write_lock_bh(&queue->sock->sk->sk_callback_lock);
2238 	queue->sock->sk->sk_user_data = queue;
2239 	queue->state_change = queue->sock->sk->sk_state_change;
2240 	queue->data_ready = queue->sock->sk->sk_data_ready;
2241 	queue->write_space = queue->sock->sk->sk_write_space;
2242 	queue->sock->sk->sk_data_ready = nvme_tcp_data_ready;
2243 	queue->sock->sk->sk_state_change = nvme_tcp_state_change;
2244 	queue->sock->sk->sk_write_space = nvme_tcp_write_space;
2245 #ifdef CONFIG_NET_RX_BUSY_POLL
2246 	queue->sock->sk->sk_ll_usec = 1;
2247 #endif
2248 	write_unlock_bh(&queue->sock->sk->sk_callback_lock);
2249 }
2250 
2251 static int nvme_tcp_start_queue(struct nvme_ctrl *nctrl, int idx)
2252 {
2253 	struct nvme_tcp_ctrl *ctrl = to_tcp_ctrl(nctrl);
2254 	struct nvme_tcp_queue *queue = &ctrl->queues[idx];
2255 	int ret;
2256 
2257 	queue->rd_enabled = true;
2258 	nvme_tcp_init_recv_ctx(queue);
2259 	nvme_tcp_setup_sock_ops(queue);
2260 
2261 	if (idx) {
2262 		nvme_tcp_set_queue_io_cpu(queue);
2263 		ret = nvmf_connect_io_queue(nctrl, idx);
2264 	} else
2265 		ret = nvmf_connect_admin_queue(nctrl);
2266 
2267 	if (!ret) {
2268 		set_bit(NVME_TCP_Q_LIVE, &queue->flags);
2269 	} else {
2270 		if (test_bit(NVME_TCP_Q_ALLOCATED, &queue->flags))
2271 			__nvme_tcp_stop_queue(queue);
2272 		dev_err(nctrl->device,
2273 			"failed to connect queue: %d ret=%d\n", idx, ret);
2274 	}
2275 	return ret;
2276 }
2277 
2278 static void nvme_tcp_free_admin_queue(struct nvme_ctrl *ctrl)
2279 {
2280 	if (to_tcp_ctrl(ctrl)->async_req.pdu) {
2281 		cancel_work_sync(&ctrl->async_event_work);
2282 		nvme_tcp_free_async_req(to_tcp_ctrl(ctrl));
2283 		to_tcp_ctrl(ctrl)->async_req.pdu = NULL;
2284 	}
2285 
2286 	nvme_tcp_free_queue(ctrl, 0);
2287 }
2288 
2289 static void nvme_tcp_free_io_queues(struct nvme_ctrl *ctrl)
2290 {
2291 	int i;
2292 
2293 	for (i = 1; i < ctrl->queue_count; i++)
2294 		nvme_tcp_free_queue(ctrl, i);
2295 }
2296 
2297 static void nvme_tcp_stop_io_queues(struct nvme_ctrl *ctrl)
2298 {
2299 	int i;
2300 
2301 	for (i = 1; i < ctrl->queue_count; i++)
2302 		nvme_tcp_stop_queue_nowait(ctrl, i);
2303 	for (i = 1; i < ctrl->queue_count; i++)
2304 		nvme_tcp_wait_queue(ctrl, i);
2305 }
2306 
2307 static int nvme_tcp_alloc_admin_queue(struct nvme_ctrl *ctrl)
2308 {
2309 	int ret;
2310 	key_serial_t pskid = 0;
2311 
2312 	if (nvme_tcp_tls_configured(ctrl)) {
2313 		if (ctrl->opts->tls_key)
2314 			pskid = key_serial(ctrl->opts->tls_key);
2315 		else if (ctrl->opts->tls) {
2316 			pskid = nvme_tls_psk_default(ctrl->opts->keyring,
2317 						      ctrl->opts->host->nqn,
2318 						      ctrl->opts->subsysnqn);
2319 			if (!pskid) {
2320 				dev_err(ctrl->device, "no valid PSK found\n");
2321 				return -ENOKEY;
2322 			}
2323 		}
2324 	}
2325 
2326 	ret = nvme_tcp_alloc_queue(ctrl, 0, pskid);
2327 	if (ret)
2328 		return ret;
2329 
2330 	ret = nvme_tcp_alloc_async_req(to_tcp_ctrl(ctrl));
2331 	if (ret)
2332 		goto out_free_queue;
2333 
2334 	return 0;
2335 
2336 out_free_queue:
2337 	nvme_tcp_free_queue(ctrl, 0);
2338 	return ret;
2339 }
2340 
2341 static int nvme_tcp_tls_check_psk(struct nvme_ctrl *ctrl)
2342 {
2343 	if (nvme_tcp_tls_configured(ctrl)) {
2344 		if (ctrl->opts->concat) {
2345 			/*
2346 			 * The generated PSK is stored in the
2347 			 * fabric options
2348 			 */
2349 			if (!ctrl->opts->tls_key) {
2350 				dev_err(ctrl->device, "no PSK generated\n");
2351 				return -ENOKEY;
2352 			}
2353 			if (ctrl->tls_pskid &&
2354 			    ctrl->tls_pskid != key_serial(ctrl->opts->tls_key)) {
2355 				dev_err(ctrl->device, "Stale PSK id %08x\n", ctrl->tls_pskid);
2356 				ctrl->tls_pskid = 0;
2357 			}
2358 		} else if (!ctrl->tls_pskid) {
2359 			dev_err(ctrl->device, "no PSK negotiated\n");
2360 			return -ENOKEY;
2361 		}
2362 	}
2363 
2364 	return 0;
2365 }
2366 
2367 static void nvme_tcp_setup_queue_async(void *data, async_cookie_t cookie)
2368 {
2369 	struct nvme_tcp_queue_setup_ctx *ctx = data;
2370 	struct nvme_ctrl *ctrl = ctx->ctrl;
2371 	int ret;
2372 
2373 	ret = nvme_tcp_alloc_queue(ctrl, ctx->qid, ctrl->tls_pskid);
2374 	if (ret)
2375 		goto out_err;
2376 
2377 	ret = nvme_tcp_start_queue(ctrl, ctx->qid);
2378 	if (ret)
2379 		goto out_err;
2380 
2381 	return;
2382 
2383 out_err:
2384 	WRITE_ONCE(*ctx->err, ret);
2385 }
2386 
2387 static int nvme_tcp_setup_io_queues(struct nvme_ctrl *ctrl, unsigned int first,
2388 		unsigned int last)
2389 {
2390 	ASYNC_DOMAIN_EXCLUSIVE(queue_domain);
2391 	struct nvme_tcp_queue_setup_ctx *ctxs;
2392 	int nr_queues = last - first;
2393 	int err = 0, i, ret;
2394 
2395 	if (first >= last)
2396 		return 0;
2397 
2398 	ctxs = kmalloc_objs(*ctxs, nr_queues);
2399 	if (!ctxs)
2400 		return -ENOMEM;
2401 
2402 	for (i = 0; i < nr_queues; i++) {
2403 		ctxs[i].ctrl = ctrl;
2404 		ctxs[i].qid = first + i;
2405 		ctxs[i].err = &err;
2406 		async_schedule_domain(nvme_tcp_setup_queue_async, &ctxs[i],
2407 				&queue_domain);
2408 	}
2409 
2410 	async_synchronize_full_domain(&queue_domain);
2411 	kfree(ctxs);
2412 
2413 	ret = READ_ONCE(err);
2414 	if (ret)
2415 		goto out_free_queues;
2416 
2417 	return 0;
2418 
2419 out_free_queues:
2420 	for (i = first; i < last; i++) {
2421 		struct nvme_tcp_queue *queue = &to_tcp_ctrl(ctrl)->queues[i];
2422 
2423 		if (test_bit(NVME_TCP_Q_LIVE, &queue->flags))
2424 			nvme_tcp_stop_queue(ctrl, i);
2425 		if (test_bit(NVME_TCP_Q_ALLOCATED, &queue->flags))
2426 			nvme_tcp_free_queue(ctrl, i);
2427 	}
2428 
2429 	return ret;
2430 }
2431 
2432 static int nvme_tcp_set_io_queue_count(struct nvme_ctrl *ctrl)
2433 {
2434 	unsigned int nr_io_queues;
2435 	int ret;
2436 
2437 	nr_io_queues = nvmf_nr_io_queues(ctrl->opts);
2438 	ret = nvme_set_queue_count(ctrl, &nr_io_queues);
2439 	if (ret)
2440 		return ret;
2441 
2442 	if (nr_io_queues == 0) {
2443 		dev_err(ctrl->device,
2444 			"unable to set any I/O queues\n");
2445 		return -ENOMEM;
2446 	}
2447 
2448 	ctrl->queue_count = nr_io_queues + 1;
2449 	dev_info(ctrl->device,
2450 		"creating %d I/O queues.\n", nr_io_queues);
2451 
2452 	nvmf_set_io_queues(ctrl->opts, nr_io_queues,
2453 			   to_tcp_ctrl(ctrl)->io_queues);
2454 	return 0;
2455 }
2456 
2457 static int nvme_tcp_configure_io_queues(struct nvme_ctrl *ctrl, bool new)
2458 {
2459 	int ret, nr_queues;
2460 
2461 	ret = nvme_tcp_set_io_queue_count(ctrl);
2462 	if (ret)
2463 		return ret;
2464 
2465 	ret = nvme_tcp_tls_check_psk(ctrl);
2466 	if (ret)
2467 		return ret;
2468 
2469 	if (new) {
2470 		ret = nvme_alloc_io_tag_set(ctrl, &to_tcp_ctrl(ctrl)->tag_set,
2471 				&nvme_tcp_mq_ops,
2472 				ctrl->opts->nr_poll_queues ? HCTX_MAX_TYPES : 2,
2473 				sizeof(struct nvme_tcp_request));
2474 		if (ret)
2475 			goto out_free_io_queues;
2476 	}
2477 
2478 	/*
2479 	 * Only setup IO queues for which we have allocated the tagset
2480 	 * and limited it to the available queues. On reconnects, the
2481 	 * queue number might have changed.
2482 	 */
2483 	nr_queues = min(ctrl->tagset->nr_hw_queues + 1, ctrl->queue_count);
2484 	ret = nvme_tcp_setup_io_queues(ctrl, 1, nr_queues);
2485 	if (ret)
2486 		goto out_cleanup_connect_q;
2487 
2488 	if (!new) {
2489 		nvme_start_freeze(ctrl);
2490 		nvme_unquiesce_io_queues(ctrl);
2491 		if (!nvme_wait_freeze_timeout(ctrl)) {
2492 			/*
2493 			 * If we timed out waiting for freeze we are likely to
2494 			 * be stuck.  Fail the controller initialization just
2495 			 * to be safe.
2496 			 */
2497 			ret = -ENODEV;
2498 			nvme_unfreeze(ctrl);
2499 			goto out_wait_freeze_timed_out;
2500 		}
2501 		blk_mq_update_nr_hw_queues(ctrl->tagset,
2502 			ctrl->queue_count - 1);
2503 		nvme_unfreeze(ctrl);
2504 	}
2505 
2506 	/*
2507 	 * If the number of queues has increased (reconnect case)
2508 	 * setup all new queues now.
2509 	 */
2510 	ret = nvme_tcp_setup_io_queues(ctrl, nr_queues,
2511 				       ctrl->tagset->nr_hw_queues + 1);
2512 	if (ret)
2513 		goto out_wait_freeze_timed_out;
2514 
2515 	return 0;
2516 
2517 out_wait_freeze_timed_out:
2518 	nvme_quiesce_io_queues(ctrl);
2519 	nvme_sync_io_queues(ctrl);
2520 	nvme_tcp_stop_io_queues(ctrl);
2521 out_cleanup_connect_q:
2522 	nvme_cancel_tagset(ctrl);
2523 	if (new)
2524 		nvme_remove_io_tag_set(ctrl);
2525 out_free_io_queues:
2526 	nvme_tcp_free_io_queues(ctrl);
2527 	return ret;
2528 }
2529 
2530 static int nvme_tcp_configure_admin_queue(struct nvme_ctrl *ctrl, bool new)
2531 {
2532 	int error;
2533 
2534 	error = nvme_tcp_alloc_admin_queue(ctrl);
2535 	if (error)
2536 		return error;
2537 
2538 	if (new) {
2539 		error = nvme_alloc_admin_tag_set(ctrl,
2540 				&to_tcp_ctrl(ctrl)->admin_tag_set,
2541 				&nvme_tcp_admin_mq_ops,
2542 				sizeof(struct nvme_tcp_request));
2543 		if (error)
2544 			goto out_free_queue;
2545 	}
2546 
2547 	error = nvme_tcp_start_queue(ctrl, 0);
2548 	if (error)
2549 		goto out_cleanup_tagset;
2550 
2551 	if (ctrl->opts->concat && !ctrl->tls_pskid)
2552 		return 0;
2553 
2554 	error = nvme_enable_ctrl(ctrl);
2555 	if (error)
2556 		goto out_stop_queue;
2557 
2558 	nvme_unquiesce_admin_queue(ctrl);
2559 
2560 	error = nvme_init_ctrl_finish(ctrl, false);
2561 	if (error)
2562 		goto out_quiesce_queue;
2563 
2564 	return 0;
2565 
2566 out_quiesce_queue:
2567 	nvme_quiesce_admin_queue(ctrl);
2568 	blk_sync_queue(ctrl->admin_q);
2569 out_stop_queue:
2570 	nvme_tcp_stop_queue(ctrl, 0);
2571 	nvme_cancel_admin_tagset(ctrl);
2572 out_cleanup_tagset:
2573 	if (new)
2574 		nvme_remove_admin_tag_set(ctrl);
2575 out_free_queue:
2576 	nvme_tcp_free_admin_queue(ctrl);
2577 	return error;
2578 }
2579 
2580 static void nvme_tcp_teardown_admin_queue(struct nvme_ctrl *ctrl,
2581 		bool remove)
2582 {
2583 	nvme_quiesce_admin_queue(ctrl);
2584 	blk_sync_queue(ctrl->admin_q);
2585 	nvme_tcp_stop_queue(ctrl, 0);
2586 	nvme_cancel_admin_tagset(ctrl);
2587 	if (remove) {
2588 		nvme_unquiesce_admin_queue(ctrl);
2589 		nvme_remove_admin_tag_set(ctrl);
2590 	}
2591 	nvme_tcp_free_admin_queue(ctrl);
2592 	if (ctrl->tls_pskid) {
2593 		dev_dbg(ctrl->device, "Wipe negotiated TLS_PSK %08x\n",
2594 			ctrl->tls_pskid);
2595 		ctrl->tls_pskid = 0;
2596 	}
2597 }
2598 
2599 static void nvme_tcp_teardown_io_queues(struct nvme_ctrl *ctrl,
2600 		bool remove)
2601 {
2602 	if (ctrl->queue_count <= 1)
2603 		return;
2604 	nvme_quiesce_io_queues(ctrl);
2605 	nvme_sync_io_queues(ctrl);
2606 	nvme_tcp_stop_io_queues(ctrl);
2607 	nvme_cancel_tagset(ctrl);
2608 	if (remove) {
2609 		nvme_unquiesce_io_queues(ctrl);
2610 		nvme_remove_io_tag_set(ctrl);
2611 	}
2612 	nvme_tcp_free_io_queues(ctrl);
2613 }
2614 
2615 static void nvme_tcp_reconnect_or_remove(struct nvme_ctrl *ctrl,
2616 		int status)
2617 {
2618 	enum nvme_ctrl_state state = nvme_ctrl_state(ctrl);
2619 
2620 	/* If we are resetting/deleting then do nothing */
2621 	if (state != NVME_CTRL_CONNECTING) {
2622 		WARN_ON_ONCE(state == NVME_CTRL_NEW || state == NVME_CTRL_LIVE);
2623 		return;
2624 	}
2625 
2626 	if (nvmf_should_reconnect(ctrl, status)) {
2627 		dev_info(ctrl->device, "Reconnecting in %d seconds...\n",
2628 			ctrl->opts->reconnect_delay);
2629 		queue_delayed_work(nvme_wq, &to_tcp_ctrl(ctrl)->connect_work,
2630 				ctrl->opts->reconnect_delay * HZ);
2631 	} else {
2632 		dev_info(ctrl->device, "Removing controller (%d)...\n",
2633 			 status);
2634 		nvme_delete_ctrl(ctrl);
2635 	}
2636 }
2637 
2638 /*
2639  * The TLS key is set by secure concatenation after negotiation has been
2640  * completed on the admin queue. We need to revoke the key when:
2641  * - concatenation is enabled (otherwise it's a static key set by the user)
2642  * and
2643  * - the generated key is present in ctrl->tls_key (otherwise there's nothing
2644  *   to revoke)
2645  * and
2646  * - a valid PSK key ID has been set in ctrl->tls_pskid (otherwise TLS
2647  *   negotiation has not run).
2648  *
2649  * We cannot always revoke the key as nvme_tcp_alloc_admin_queue() is called
2650  * twice during secure concatenation, once on a 'normal' connection to run the
2651  * DH-HMAC-CHAP negotiation (which generates the key, so it _must not_ be set),
2652  * and once after the negotiation (which uses the key, so it _must_ be set).
2653  */
2654 static bool nvme_tcp_key_revoke_needed(struct nvme_ctrl *ctrl)
2655 {
2656 	return ctrl->opts->concat && ctrl->opts->tls_key && ctrl->tls_pskid;
2657 }
2658 
2659 static int nvme_tcp_setup_ctrl(struct nvme_ctrl *ctrl, bool new)
2660 {
2661 	struct nvmf_ctrl_options *opts = ctrl->opts;
2662 	int ret;
2663 
2664 	ret = nvme_tcp_configure_admin_queue(ctrl, new);
2665 	if (ret)
2666 		return ret;
2667 
2668 	if (ctrl->opts->concat && !ctrl->tls_pskid) {
2669 		/* See comments for nvme_tcp_key_revoke_needed() */
2670 		dev_dbg(ctrl->device, "restart admin queue for secure concatenation\n");
2671 		nvme_stop_keep_alive(ctrl);
2672 		nvme_tcp_teardown_admin_queue(ctrl, false);
2673 		ret = nvme_tcp_configure_admin_queue(ctrl, false);
2674 		if (ret)
2675 			goto destroy_admin;
2676 	}
2677 
2678 	if (ctrl->icdoff) {
2679 		ret = -EOPNOTSUPP;
2680 		dev_err(ctrl->device, "icdoff is not supported!\n");
2681 		goto destroy_admin;
2682 	}
2683 
2684 	if (!nvme_ctrl_sgl_supported(ctrl)) {
2685 		ret = -EOPNOTSUPP;
2686 		dev_err(ctrl->device, "Mandatory sgls are not supported!\n");
2687 		goto destroy_admin;
2688 	}
2689 
2690 	if (opts->queue_size > ctrl->sqsize + 1)
2691 		dev_warn(ctrl->device,
2692 			"queue_size %zu > ctrl sqsize %u, clamping down\n",
2693 			opts->queue_size, ctrl->sqsize + 1);
2694 
2695 	if (ctrl->sqsize + 1 > ctrl->maxcmd) {
2696 		dev_warn(ctrl->device,
2697 			"sqsize %u > ctrl maxcmd %u, clamping down\n",
2698 			ctrl->sqsize + 1, ctrl->maxcmd);
2699 		ctrl->sqsize = ctrl->maxcmd - 1;
2700 	}
2701 
2702 	if (ctrl->queue_count > 1) {
2703 		ret = nvme_tcp_configure_io_queues(ctrl, new);
2704 		if (ret)
2705 			goto destroy_admin;
2706 	}
2707 
2708 	if (!nvme_change_ctrl_state(ctrl, NVME_CTRL_LIVE)) {
2709 		/*
2710 		 * state change failure is ok if we started ctrl delete,
2711 		 * unless we're during creation of a new controller to
2712 		 * avoid races with teardown flow.
2713 		 */
2714 		enum nvme_ctrl_state state = nvme_ctrl_state(ctrl);
2715 
2716 		WARN_ON_ONCE(state != NVME_CTRL_DELETING &&
2717 			     state != NVME_CTRL_DELETING_NOIO);
2718 		WARN_ON_ONCE(new);
2719 		ret = -EINVAL;
2720 		goto destroy_io;
2721 	}
2722 
2723 	nvme_start_ctrl(ctrl);
2724 	return 0;
2725 
2726 destroy_io:
2727 	if (ctrl->queue_count > 1) {
2728 		nvme_quiesce_io_queues(ctrl);
2729 		nvme_sync_io_queues(ctrl);
2730 		nvme_tcp_stop_io_queues(ctrl);
2731 		nvme_cancel_tagset(ctrl);
2732 		if (new)
2733 			nvme_remove_io_tag_set(ctrl);
2734 		nvme_tcp_free_io_queues(ctrl);
2735 	}
2736 destroy_admin:
2737 	nvme_stop_keep_alive(ctrl);
2738 	nvme_tcp_teardown_admin_queue(ctrl, new);
2739 	return ret;
2740 }
2741 
2742 static void nvme_tcp_reconnect_ctrl_work(struct work_struct *work)
2743 {
2744 	struct nvme_tcp_ctrl *tcp_ctrl = container_of(to_delayed_work(work),
2745 			struct nvme_tcp_ctrl, connect_work);
2746 	struct nvme_ctrl *ctrl = &tcp_ctrl->ctrl;
2747 	int ret;
2748 
2749 	++ctrl->nr_reconnects;
2750 
2751 	ret = nvme_tcp_setup_ctrl(ctrl, false);
2752 	if (ret)
2753 		goto requeue;
2754 
2755 	dev_info(ctrl->device, "Successfully reconnected (attempt %d/%d)\n",
2756 		 ctrl->nr_reconnects, ctrl->opts->max_reconnects);
2757 
2758 	/* accumulate reconnect attempts before resetting it to zero */
2759 	atomic_long_add(ctrl->nr_reconnects, &ctrl->acc_reconnects);
2760 	ctrl->nr_reconnects = 0;
2761 
2762 	return;
2763 
2764 requeue:
2765 	dev_info(ctrl->device, "Failed reconnect attempt %d/%d\n",
2766 		 ctrl->nr_reconnects, ctrl->opts->max_reconnects);
2767 	nvme_tcp_reconnect_or_remove(ctrl, ret);
2768 }
2769 
2770 static void nvme_tcp_error_recovery_work(struct work_struct *work)
2771 {
2772 	struct nvme_tcp_ctrl *tcp_ctrl = container_of(work,
2773 				struct nvme_tcp_ctrl, err_work);
2774 	struct nvme_ctrl *ctrl = &tcp_ctrl->ctrl;
2775 
2776 	if (nvme_tcp_key_revoke_needed(ctrl))
2777 		nvme_auth_revoke_tls_key(ctrl);
2778 	nvme_stop_keep_alive(ctrl);
2779 	flush_work(&ctrl->async_event_work);
2780 	nvme_tcp_teardown_io_queues(ctrl, false);
2781 	/* unquiesce to fail fast pending requests */
2782 	nvme_unquiesce_io_queues(ctrl);
2783 	nvme_tcp_teardown_admin_queue(ctrl, false);
2784 	nvme_unquiesce_admin_queue(ctrl);
2785 	nvme_auth_stop(ctrl);
2786 
2787 	if (!nvme_change_ctrl_state(ctrl, NVME_CTRL_CONNECTING)) {
2788 		/* state change failure is ok if we started ctrl delete */
2789 		enum nvme_ctrl_state state = nvme_ctrl_state(ctrl);
2790 
2791 		WARN_ON_ONCE(state != NVME_CTRL_DELETING &&
2792 			     state != NVME_CTRL_DELETING_NOIO);
2793 		return;
2794 	}
2795 
2796 	nvme_tcp_reconnect_or_remove(ctrl, 0);
2797 }
2798 
2799 static void nvme_tcp_teardown_ctrl(struct nvme_ctrl *ctrl, bool shutdown)
2800 {
2801 	nvme_tcp_teardown_io_queues(ctrl, shutdown);
2802 	nvme_quiesce_admin_queue(ctrl);
2803 	nvme_disable_ctrl(ctrl, shutdown);
2804 	nvme_tcp_teardown_admin_queue(ctrl, shutdown);
2805 }
2806 
2807 static void nvme_tcp_delete_ctrl(struct nvme_ctrl *ctrl)
2808 {
2809 	nvme_tcp_teardown_ctrl(ctrl, true);
2810 }
2811 
2812 static void nvme_reset_ctrl_work(struct work_struct *work)
2813 {
2814 	struct nvme_ctrl *ctrl =
2815 		container_of(work, struct nvme_ctrl, reset_work);
2816 	int ret;
2817 
2818 	if (nvme_tcp_key_revoke_needed(ctrl))
2819 		nvme_auth_revoke_tls_key(ctrl);
2820 	nvme_stop_ctrl(ctrl);
2821 	nvme_tcp_teardown_ctrl(ctrl, false);
2822 
2823 	if (!nvme_change_ctrl_state(ctrl, NVME_CTRL_CONNECTING)) {
2824 		/* state change failure is ok if we started ctrl delete */
2825 		enum nvme_ctrl_state state = nvme_ctrl_state(ctrl);
2826 
2827 		WARN_ON_ONCE(state != NVME_CTRL_DELETING &&
2828 			     state != NVME_CTRL_DELETING_NOIO);
2829 		return;
2830 	}
2831 
2832 	ret = nvme_tcp_setup_ctrl(ctrl, false);
2833 	if (ret)
2834 		goto out_fail;
2835 
2836 	return;
2837 
2838 out_fail:
2839 	++ctrl->nr_reconnects;
2840 	nvme_tcp_reconnect_or_remove(ctrl, ret);
2841 }
2842 
2843 static void nvme_tcp_stop_ctrl(struct nvme_ctrl *ctrl)
2844 {
2845 	flush_work(&to_tcp_ctrl(ctrl)->err_work);
2846 	cancel_delayed_work_sync(&to_tcp_ctrl(ctrl)->connect_work);
2847 }
2848 
2849 static void nvme_tcp_free_ctrl(struct nvme_ctrl *nctrl)
2850 {
2851 	struct nvme_tcp_ctrl *ctrl = to_tcp_ctrl(nctrl);
2852 	unsigned int i;
2853 
2854 	if (list_empty_careful(&ctrl->list))
2855 		goto free_ctrl;
2856 
2857 	mutex_lock(&nvme_tcp_ctrl_mutex);
2858 	list_del(&ctrl->list);
2859 	mutex_unlock(&nvme_tcp_ctrl_mutex);
2860 
2861 	nvmf_free_options(nctrl->opts);
2862 free_ctrl:
2863 	put_net(ctrl->net);
2864 	for (i = 0; i < ctrl->nr_allocated_queues; i++)
2865 		nvme_tcp_exit_queue(ctrl, i);
2866 	kfree(ctrl->queues);
2867 	kfree(ctrl);
2868 }
2869 
2870 static void nvme_tcp_set_sg_null(struct nvme_command *c)
2871 {
2872 	struct nvme_sgl_desc *sg = &c->common.dptr.sgl;
2873 
2874 	sg->addr = 0;
2875 	sg->length = 0;
2876 	sg->type = (NVME_TRANSPORT_SGL_DATA_DESC << 4) |
2877 			NVME_SGL_FMT_TRANSPORT_A;
2878 }
2879 
2880 static void nvme_tcp_set_sg_inline(struct nvme_tcp_queue *queue,
2881 		struct nvme_command *c, u32 data_len)
2882 {
2883 	struct nvme_sgl_desc *sg = &c->common.dptr.sgl;
2884 
2885 	sg->addr = cpu_to_le64(queue->ctrl->ctrl.icdoff);
2886 	sg->length = cpu_to_le32(data_len);
2887 	sg->type = (NVME_SGL_FMT_DATA_DESC << 4) | NVME_SGL_FMT_OFFSET;
2888 }
2889 
2890 static void nvme_tcp_set_sg_host_data(struct nvme_command *c,
2891 		u32 data_len)
2892 {
2893 	struct nvme_sgl_desc *sg = &c->common.dptr.sgl;
2894 
2895 	sg->addr = 0;
2896 	sg->length = cpu_to_le32(data_len);
2897 	sg->type = (NVME_TRANSPORT_SGL_DATA_DESC << 4) |
2898 			NVME_SGL_FMT_TRANSPORT_A;
2899 }
2900 
2901 static void nvme_tcp_submit_async_event(struct nvme_ctrl *arg)
2902 {
2903 	struct nvme_tcp_ctrl *ctrl = to_tcp_ctrl(arg);
2904 	struct nvme_tcp_queue *queue = &ctrl->queues[0];
2905 	struct nvme_tcp_cmd_pdu *pdu = ctrl->async_req.pdu;
2906 	struct nvme_command *cmd = &pdu->cmd;
2907 	u8 hdgst = nvme_tcp_hdgst_len(queue);
2908 
2909 	memset(pdu, 0, sizeof(*pdu));
2910 	pdu->hdr.type = nvme_tcp_cmd;
2911 	if (queue->hdr_digest)
2912 		pdu->hdr.flags |= NVME_TCP_F_HDGST;
2913 	pdu->hdr.hlen = sizeof(*pdu);
2914 	pdu->hdr.plen = cpu_to_le32(pdu->hdr.hlen + hdgst);
2915 
2916 	cmd->common.opcode = nvme_admin_async_event;
2917 	cmd->common.command_id = NVME_AQ_BLK_MQ_DEPTH;
2918 	cmd->common.flags |= NVME_CMD_SGL_METABUF;
2919 	nvme_tcp_set_sg_null(cmd);
2920 
2921 	ctrl->async_req.state = NVME_TCP_SEND_CMD_PDU;
2922 	ctrl->async_req.offset = 0;
2923 	ctrl->async_req.curr_bio = NULL;
2924 	ctrl->async_req.data_len = 0;
2925 	init_llist_node(&ctrl->async_req.lentry);
2926 	INIT_LIST_HEAD(&ctrl->async_req.entry);
2927 
2928 	nvme_tcp_queue_request(&ctrl->async_req, true);
2929 }
2930 
2931 static void nvme_tcp_complete_timed_out(struct request *rq)
2932 {
2933 	struct nvme_tcp_request *req = blk_mq_rq_to_pdu(rq);
2934 	struct nvme_ctrl *ctrl = &req->queue->ctrl->ctrl;
2935 
2936 	nvme_tcp_stop_queue(ctrl, nvme_tcp_queue_id(req->queue));
2937 	nvmf_complete_timed_out_request(rq);
2938 }
2939 
2940 static enum blk_eh_timer_return nvme_tcp_timeout(struct request *rq)
2941 {
2942 	struct nvme_tcp_request *req = blk_mq_rq_to_pdu(rq);
2943 	struct nvme_ctrl *ctrl = &req->queue->ctrl->ctrl;
2944 	struct nvme_tcp_cmd_pdu *pdu = nvme_tcp_req_cmd_pdu(req);
2945 	struct nvme_command *cmd = &pdu->cmd;
2946 	int qid = nvme_tcp_queue_id(req->queue);
2947 
2948 	dev_warn(ctrl->device,
2949 		 "I/O tag %d (%04x) type %d opcode %#x (%s) QID %d timeout\n",
2950 		 rq->tag, nvme_cid(rq), pdu->hdr.type, cmd->common.opcode,
2951 		 nvme_fabrics_opcode_str(qid, cmd), qid);
2952 
2953 	if (nvme_ctrl_state(ctrl) != NVME_CTRL_LIVE) {
2954 		/*
2955 		 * If we are resetting, connecting or deleting we should
2956 		 * complete immediately because we may block controller
2957 		 * teardown or setup sequence
2958 		 * - ctrl disable/shutdown fabrics requests
2959 		 * - connect requests
2960 		 * - initialization admin requests
2961 		 * - I/O requests that entered after unquiescing and
2962 		 *   the controller stopped responding
2963 		 *
2964 		 * All other requests should be cancelled by the error
2965 		 * recovery work, so it's fine that we fail it here.
2966 		 */
2967 		nvme_tcp_complete_timed_out(rq);
2968 		return BLK_EH_DONE;
2969 	}
2970 
2971 	/*
2972 	 * LIVE state should trigger the normal error recovery which will
2973 	 * handle completing this request.
2974 	 */
2975 	nvme_tcp_error_recovery(ctrl);
2976 	return BLK_EH_RESET_TIMER;
2977 }
2978 
2979 static blk_status_t nvme_tcp_map_data(struct nvme_tcp_queue *queue,
2980 			struct request *rq)
2981 {
2982 	struct nvme_tcp_request *req = blk_mq_rq_to_pdu(rq);
2983 	struct nvme_tcp_cmd_pdu *pdu = nvme_tcp_req_cmd_pdu(req);
2984 	struct nvme_command *c = &pdu->cmd;
2985 
2986 	c->common.flags |= NVME_CMD_SGL_METABUF;
2987 
2988 	if (!blk_rq_nr_phys_segments(rq))
2989 		nvme_tcp_set_sg_null(c);
2990 	else if (rq_data_dir(rq) == WRITE &&
2991 	    req->data_len <= nvme_tcp_inline_data_size(req))
2992 		nvme_tcp_set_sg_inline(queue, c, req->data_len);
2993 	else
2994 		nvme_tcp_set_sg_host_data(c, req->data_len);
2995 
2996 	return 0;
2997 }
2998 
2999 static blk_status_t nvme_tcp_setup_cmd_pdu(struct nvme_ns *ns,
3000 		struct request *rq)
3001 {
3002 	struct nvme_tcp_request *req = blk_mq_rq_to_pdu(rq);
3003 	struct nvme_tcp_cmd_pdu *pdu = nvme_tcp_req_cmd_pdu(req);
3004 	struct nvme_tcp_queue *queue = req->queue;
3005 	u8 hdgst = nvme_tcp_hdgst_len(queue), ddgst = 0;
3006 	blk_status_t ret;
3007 
3008 	ret = nvme_setup_cmd(ns, rq);
3009 	if (ret)
3010 		return ret;
3011 
3012 	req->state = NVME_TCP_SEND_CMD_PDU;
3013 	req->status = cpu_to_le16(NVME_SC_SUCCESS);
3014 	req->offset = 0;
3015 	req->data_sent = 0;
3016 	req->data_recvd = 0;
3017 	req->pdu_len = 0;
3018 	req->pdu_sent = 0;
3019 	req->h2cdata_left = 0;
3020 	req->data_len = blk_rq_nr_phys_segments(rq) ?
3021 				blk_rq_payload_bytes(rq) : 0;
3022 	req->curr_bio = rq->bio;
3023 	if (req->curr_bio && req->data_len)
3024 		nvme_tcp_init_iter(req, rq_data_dir(rq));
3025 
3026 	if (rq_data_dir(rq) == WRITE &&
3027 	    req->data_len <= nvme_tcp_inline_data_size(req))
3028 		req->pdu_len = req->data_len;
3029 
3030 	pdu->hdr.type = nvme_tcp_cmd;
3031 	pdu->hdr.flags = 0;
3032 	if (queue->hdr_digest)
3033 		pdu->hdr.flags |= NVME_TCP_F_HDGST;
3034 	if (queue->data_digest && req->pdu_len) {
3035 		pdu->hdr.flags |= NVME_TCP_F_DDGST;
3036 		ddgst = nvme_tcp_ddgst_len(queue);
3037 	}
3038 	pdu->hdr.hlen = sizeof(*pdu);
3039 	pdu->hdr.pdo = req->pdu_len ? pdu->hdr.hlen + hdgst : 0;
3040 	pdu->hdr.plen =
3041 		cpu_to_le32(pdu->hdr.hlen + hdgst + req->pdu_len + ddgst);
3042 
3043 	ret = nvme_tcp_map_data(queue, rq);
3044 	if (unlikely(ret)) {
3045 		nvme_cleanup_cmd(rq);
3046 		dev_err(queue->ctrl->ctrl.device,
3047 			"Failed to map data (%d)\n", ret);
3048 		return ret;
3049 	}
3050 
3051 	return 0;
3052 }
3053 
3054 static void nvme_tcp_commit_rqs(struct blk_mq_hw_ctx *hctx)
3055 {
3056 	struct nvme_tcp_queue *queue = hctx->driver_data;
3057 
3058 	if (!llist_empty(&queue->req_list))
3059 		queue_work_on(queue->io_cpu, nvme_tcp_wq, &queue->io_work);
3060 }
3061 
3062 static blk_status_t nvme_tcp_queue_rq(struct blk_mq_hw_ctx *hctx,
3063 		const struct blk_mq_queue_data *bd)
3064 {
3065 	struct nvme_ns *ns = hctx->queue->queuedata;
3066 	struct nvme_tcp_queue *queue = hctx->driver_data;
3067 	struct request *rq = bd->rq;
3068 	struct nvme_tcp_request *req = blk_mq_rq_to_pdu(rq);
3069 	bool queue_ready = test_bit(NVME_TCP_Q_LIVE, &queue->flags);
3070 	blk_status_t ret;
3071 
3072 	if (!nvme_check_ready(&queue->ctrl->ctrl, rq, queue_ready))
3073 		return nvme_fail_nonready_command(&queue->ctrl->ctrl, rq);
3074 
3075 	ret = nvme_tcp_setup_cmd_pdu(ns, rq);
3076 	if (unlikely(ret))
3077 		return ret;
3078 
3079 	nvme_start_request(rq);
3080 
3081 	nvme_tcp_queue_request(req, bd->last);
3082 
3083 	return BLK_STS_OK;
3084 }
3085 
3086 static void nvme_tcp_map_queues(struct blk_mq_tag_set *set)
3087 {
3088 	struct nvme_tcp_ctrl *ctrl = to_tcp_ctrl(set->driver_data);
3089 
3090 	nvmf_map_queues(set, &ctrl->ctrl, ctrl->io_queues);
3091 }
3092 
3093 static int nvme_tcp_poll(struct blk_mq_hw_ctx *hctx, struct io_comp_batch *iob)
3094 {
3095 	struct nvme_tcp_queue *queue = hctx->driver_data;
3096 	struct sock *sk = queue->sock->sk;
3097 	int ret;
3098 
3099 	if (!test_bit(NVME_TCP_Q_LIVE, &queue->flags))
3100 		return 0;
3101 
3102 	set_bit(NVME_TCP_Q_POLLING, &queue->flags);
3103 	if (sk_can_busy_loop(sk) && skb_queue_empty_lockless(&sk->sk_receive_queue))
3104 		sk_busy_loop(sk, true);
3105 	ret = nvme_tcp_try_recv(queue);
3106 	clear_bit(NVME_TCP_Q_POLLING, &queue->flags);
3107 	return ret < 0 ? ret : queue->nr_cqe;
3108 }
3109 
3110 static int nvme_tcp_get_address(struct nvme_ctrl *ctrl, char *buf, int size)
3111 {
3112 	struct nvme_tcp_queue *queue = &to_tcp_ctrl(ctrl)->queues[0];
3113 	struct sockaddr_storage src_addr;
3114 	int ret, len;
3115 
3116 	len = nvmf_get_address(ctrl, buf, size);
3117 
3118 	mutex_lock(&queue->queue_lock);
3119 
3120 	if (test_bit(NVME_TCP_Q_LIVE, &queue->flags)) {
3121 		ret = kernel_getsockname(queue->sock,
3122 				(struct sockaddr *)&src_addr);
3123 		if (ret > 0) {
3124 			if (len > 0)
3125 				len--; /* strip trailing newline */
3126 			len += scnprintf(buf + len, size - len,
3127 					"%ssrc_addr=%pISc\n",
3128 					(len) ? "," : "", &src_addr);
3129 		}
3130 	}
3131 
3132 	mutex_unlock(&queue->queue_lock);
3133 
3134 	return len;
3135 }
3136 
3137 static const struct blk_mq_ops nvme_tcp_mq_ops = {
3138 	.queue_rq	= nvme_tcp_queue_rq,
3139 	.commit_rqs	= nvme_tcp_commit_rqs,
3140 	.complete	= nvme_complete_rq,
3141 	.init_request	= nvme_tcp_init_request,
3142 	.exit_request	= nvme_tcp_exit_request,
3143 	.init_hctx	= nvme_tcp_init_hctx,
3144 	.timeout	= nvme_tcp_timeout,
3145 	.map_queues	= nvme_tcp_map_queues,
3146 	.poll		= nvme_tcp_poll,
3147 };
3148 
3149 static const struct blk_mq_ops nvme_tcp_admin_mq_ops = {
3150 	.queue_rq	= nvme_tcp_queue_rq,
3151 	.complete	= nvme_complete_rq,
3152 	.init_request	= nvme_tcp_init_request,
3153 	.exit_request	= nvme_tcp_exit_request,
3154 	.init_hctx	= nvme_tcp_init_admin_hctx,
3155 	.timeout	= nvme_tcp_timeout,
3156 };
3157 
3158 static const struct nvme_ctrl_ops nvme_tcp_ctrl_ops = {
3159 	.name			= "tcp",
3160 	.module			= THIS_MODULE,
3161 	.flags			= NVME_F_FABRICS | NVME_F_BLOCKING,
3162 	.reg_read32		= nvmf_reg_read32,
3163 	.reg_read64		= nvmf_reg_read64,
3164 	.reg_write32		= nvmf_reg_write32,
3165 	.subsystem_reset	= nvmf_subsystem_reset,
3166 	.free_ctrl		= nvme_tcp_free_ctrl,
3167 	.submit_async_event	= nvme_tcp_submit_async_event,
3168 	.delete_ctrl		= nvme_tcp_delete_ctrl,
3169 	.get_address		= nvme_tcp_get_address,
3170 	.stop_ctrl		= nvme_tcp_stop_ctrl,
3171 	.get_virt_boundary	= nvmf_get_virt_boundary,
3172 };
3173 
3174 static bool
3175 nvme_tcp_existing_controller(struct nvmf_ctrl_options *opts)
3176 {
3177 	struct nvme_tcp_ctrl *ctrl;
3178 	bool found = false;
3179 
3180 	mutex_lock(&nvme_tcp_ctrl_mutex);
3181 	list_for_each_entry(ctrl, &nvme_tcp_ctrl_list, list) {
3182 		found = nvmf_ip_options_match(&ctrl->ctrl, opts);
3183 		if (found)
3184 			break;
3185 	}
3186 	mutex_unlock(&nvme_tcp_ctrl_mutex);
3187 
3188 	return found;
3189 }
3190 
3191 static struct nvme_tcp_ctrl *nvme_tcp_alloc_ctrl(struct device *dev,
3192 		struct nvmf_ctrl_options *opts)
3193 {
3194 	struct nvme_tcp_ctrl *ctrl;
3195 	int ret, i;
3196 
3197 	ctrl = kzalloc_obj(*ctrl);
3198 	if (!ctrl)
3199 		return ERR_PTR(-ENOMEM);
3200 
3201 	/*
3202 	 * Safe to init list while allocating ctrl object.
3203 	 */
3204 	context_unsafe(INIT_LIST_HEAD(&ctrl->list));
3205 	ctrl->ctrl.opts = opts;
3206 	ctrl->ctrl.queue_count = NVME_TCP_OPT_NR_QUEUES(opts);
3207 	ctrl->ctrl.sqsize = opts->queue_size - 1;
3208 	ctrl->ctrl.kato = opts->kato;
3209 
3210 	INIT_DELAYED_WORK(&ctrl->connect_work,
3211 			nvme_tcp_reconnect_ctrl_work);
3212 	INIT_WORK(&ctrl->err_work, nvme_tcp_error_recovery_work);
3213 	INIT_WORK(&ctrl->ctrl.reset_work, nvme_reset_ctrl_work);
3214 
3215 	if (!(opts->mask & NVMF_OPT_TRSVCID)) {
3216 		opts->trsvcid =
3217 			kstrdup(__stringify(NVME_TCP_DISC_PORT), GFP_KERNEL);
3218 		if (!opts->trsvcid) {
3219 			ret = -ENOMEM;
3220 			goto out_free_ctrl;
3221 		}
3222 		opts->mask |= NVMF_OPT_TRSVCID;
3223 	}
3224 
3225 	ret = inet_pton_with_scope(&init_net, AF_UNSPEC,
3226 			opts->traddr, opts->trsvcid, &ctrl->addr);
3227 	if (ret) {
3228 		pr_err("malformed address passed: %s:%s\n",
3229 			opts->traddr, opts->trsvcid);
3230 		goto out_free_ctrl;
3231 	}
3232 
3233 	if (opts->mask & NVMF_OPT_HOST_TRADDR) {
3234 		ret = inet_pton_with_scope(&init_net, AF_UNSPEC,
3235 			opts->host_traddr, NULL, &ctrl->src_addr);
3236 		if (ret) {
3237 			pr_err("malformed src address passed: %s\n",
3238 			       opts->host_traddr);
3239 			goto out_free_ctrl;
3240 		}
3241 	}
3242 
3243 	if (opts->mask & NVMF_OPT_HOST_IFACE) {
3244 		if (!__dev_get_by_name(current->nsproxy->net_ns,
3245 				       opts->host_iface)) {
3246 			pr_err("invalid interface passed: %s\n",
3247 			       opts->host_iface);
3248 			ret = -ENODEV;
3249 			goto out_free_ctrl;
3250 		}
3251 	}
3252 
3253 	if (!opts->duplicate_connect && nvme_tcp_existing_controller(opts)) {
3254 		ret = -EALREADY;
3255 		goto out_free_ctrl;
3256 	}
3257 
3258 	ctrl->nr_allocated_queues = ctrl->ctrl.queue_count;
3259 	ctrl->queues = kzalloc_objs(*ctrl->queues, ctrl->nr_allocated_queues);
3260 	if (!ctrl->queues) {
3261 		ret = -ENOMEM;
3262 		goto out_free_ctrl;
3263 	}
3264 
3265 	for (i = 0; i < ctrl->nr_allocated_queues; i++)
3266 		nvme_tcp_init_queue(ctrl, i);
3267 
3268 	ctrl->net = get_net(current->nsproxy->net_ns);
3269 	ret = nvme_init_ctrl(&ctrl->ctrl, dev, &nvme_tcp_ctrl_ops, 0);
3270 	if (ret)
3271 		goto out_kfree_queues;
3272 
3273 	return ctrl;
3274 out_kfree_queues:
3275 	put_net(ctrl->net);
3276 	kfree(ctrl->queues);
3277 out_free_ctrl:
3278 	kfree(ctrl);
3279 	return ERR_PTR(ret);
3280 }
3281 
3282 static struct nvme_ctrl *nvme_tcp_create_ctrl(struct device *dev,
3283 		struct nvmf_ctrl_options *opts)
3284 {
3285 	struct nvme_tcp_ctrl *ctrl;
3286 	int ret;
3287 
3288 	ctrl = nvme_tcp_alloc_ctrl(dev, opts);
3289 	if (IS_ERR(ctrl))
3290 		return ERR_CAST(ctrl);
3291 
3292 	ret = nvme_add_ctrl(&ctrl->ctrl);
3293 	if (ret)
3294 		goto out_put_ctrl;
3295 
3296 	if (!nvme_change_ctrl_state(&ctrl->ctrl, NVME_CTRL_CONNECTING)) {
3297 		WARN_ON_ONCE(1);
3298 		ret = -EINTR;
3299 		goto out_uninit_ctrl;
3300 	}
3301 
3302 	ret = nvme_tcp_setup_ctrl(&ctrl->ctrl, true);
3303 	if (ret)
3304 		goto out_uninit_ctrl;
3305 
3306 	dev_info(ctrl->ctrl.device, "new ctrl: NQN \"%s\", addr %pISp, hostnqn: %s\n",
3307 		nvmf_ctrl_subsysnqn(&ctrl->ctrl), &ctrl->addr, opts->host->nqn);
3308 
3309 	mutex_lock(&nvme_tcp_ctrl_mutex);
3310 	list_add_tail(&ctrl->list, &nvme_tcp_ctrl_list);
3311 	mutex_unlock(&nvme_tcp_ctrl_mutex);
3312 
3313 	return &ctrl->ctrl;
3314 
3315 out_uninit_ctrl:
3316 	nvme_uninit_ctrl(&ctrl->ctrl);
3317 out_put_ctrl:
3318 	nvme_put_ctrl(&ctrl->ctrl);
3319 	if (ret > 0)
3320 		ret = -EIO;
3321 	return ERR_PTR(ret);
3322 }
3323 
3324 static struct nvmf_transport_ops nvme_tcp_transport = {
3325 	.name		= "tcp",
3326 	.module		= THIS_MODULE,
3327 	.required_opts	= NVMF_OPT_TRADDR,
3328 	.allowed_opts	= NVMF_OPT_TRSVCID | NVMF_OPT_RECONNECT_DELAY |
3329 			  NVMF_OPT_HOST_TRADDR | NVMF_OPT_CTRL_LOSS_TMO |
3330 			  NVMF_OPT_HDR_DIGEST | NVMF_OPT_DATA_DIGEST |
3331 			  NVMF_OPT_NR_WRITE_QUEUES | NVMF_OPT_NR_POLL_QUEUES |
3332 			  NVMF_OPT_TOS | NVMF_OPT_HOST_IFACE | NVMF_OPT_TLS |
3333 			  NVMF_OPT_KEYRING | NVMF_OPT_TLS_KEY | NVMF_OPT_CONCAT,
3334 	.create_ctrl	= nvme_tcp_create_ctrl,
3335 };
3336 
3337 static int __init nvme_tcp_init_module(void)
3338 {
3339 	unsigned int wq_flags = WQ_MEM_RECLAIM | WQ_HIGHPRI | WQ_SYSFS;
3340 	int cpu;
3341 
3342 	BUILD_BUG_ON(sizeof(struct nvme_tcp_hdr) != 8);
3343 	BUILD_BUG_ON(sizeof(struct nvme_tcp_cmd_pdu) != 72);
3344 	BUILD_BUG_ON(sizeof(struct nvme_tcp_data_pdu) != 24);
3345 	BUILD_BUG_ON(sizeof(struct nvme_tcp_rsp_pdu) != 24);
3346 	BUILD_BUG_ON(sizeof(struct nvme_tcp_r2t_pdu) != 24);
3347 	BUILD_BUG_ON(sizeof(struct nvme_tcp_icreq_pdu) != 128);
3348 	BUILD_BUG_ON(sizeof(struct nvme_tcp_icresp_pdu) != 128);
3349 	BUILD_BUG_ON(sizeof(struct nvme_tcp_term_pdu) != 24);
3350 
3351 	if (wq_unbound)
3352 		wq_flags |= WQ_UNBOUND;
3353 	else
3354 		wq_flags |= WQ_PERCPU;
3355 
3356 	nvme_tcp_wq = alloc_workqueue("nvme_tcp_wq", wq_flags, 0);
3357 	if (!nvme_tcp_wq)
3358 		return -ENOMEM;
3359 
3360 	for_each_possible_cpu(cpu)
3361 		nvme_tcp_cpu_queues[cpu] = 0;
3362 
3363 	nvmf_register_transport(&nvme_tcp_transport);
3364 	return 0;
3365 }
3366 
3367 static void __exit nvme_tcp_cleanup_module(void)
3368 {
3369 	struct nvme_tcp_ctrl *ctrl;
3370 
3371 	nvmf_unregister_transport(&nvme_tcp_transport);
3372 
3373 	mutex_lock(&nvme_tcp_ctrl_mutex);
3374 	list_for_each_entry(ctrl, &nvme_tcp_ctrl_list, list)
3375 		nvme_delete_ctrl(&ctrl->ctrl);
3376 	mutex_unlock(&nvme_tcp_ctrl_mutex);
3377 	flush_workqueue(nvme_delete_wq);
3378 
3379 	destroy_workqueue(nvme_tcp_wq);
3380 }
3381 
3382 module_init(nvme_tcp_init_module);
3383 module_exit(nvme_tcp_cleanup_module);
3384 
3385 MODULE_DESCRIPTION("NVMe host TCP transport driver");
3386 MODULE_LICENSE("GPL v2");
3387 MODULE_ALIAS("nvme-tcp");
3388