xref: /openbmc/linux/drivers/nvme/host/tcp.c (revision 1f0d40d8)
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/slab.h>
10 #include <linux/err.h>
11 #include <linux/nvme-tcp.h>
12 #include <net/sock.h>
13 #include <net/tcp.h>
14 #include <linux/blk-mq.h>
15 #include <crypto/hash.h>
16 #include <net/busy_poll.h>
17 #include <trace/events/sock.h>
18 
19 #include "nvme.h"
20 #include "fabrics.h"
21 
22 struct nvme_tcp_queue;
23 
24 /* Define the socket priority to use for connections were it is desirable
25  * that the NIC consider performing optimized packet processing or filtering.
26  * A non-zero value being sufficient to indicate general consideration of any
27  * possible optimization.  Making it a module param allows for alternative
28  * values that may be unique for some NIC implementations.
29  */
30 static int so_priority;
31 module_param(so_priority, int, 0644);
32 MODULE_PARM_DESC(so_priority, "nvme tcp socket optimize priority");
33 
34 #ifdef CONFIG_DEBUG_LOCK_ALLOC
35 /* lockdep can detect a circular dependency of the form
36  *   sk_lock -> mmap_lock (page fault) -> fs locks -> sk_lock
37  * because dependencies are tracked for both nvme-tcp and user contexts. Using
38  * a separate class prevents lockdep from conflating nvme-tcp socket use with
39  * user-space socket API use.
40  */
41 static struct lock_class_key nvme_tcp_sk_key[2];
42 static struct lock_class_key nvme_tcp_slock_key[2];
43 
44 static void nvme_tcp_reclassify_socket(struct socket *sock)
45 {
46 	struct sock *sk = sock->sk;
47 
48 	if (WARN_ON_ONCE(!sock_allow_reclassification(sk)))
49 		return;
50 
51 	switch (sk->sk_family) {
52 	case AF_INET:
53 		sock_lock_init_class_and_name(sk, "slock-AF_INET-NVME",
54 					      &nvme_tcp_slock_key[0],
55 					      "sk_lock-AF_INET-NVME",
56 					      &nvme_tcp_sk_key[0]);
57 		break;
58 	case AF_INET6:
59 		sock_lock_init_class_and_name(sk, "slock-AF_INET6-NVME",
60 					      &nvme_tcp_slock_key[1],
61 					      "sk_lock-AF_INET6-NVME",
62 					      &nvme_tcp_sk_key[1]);
63 		break;
64 	default:
65 		WARN_ON_ONCE(1);
66 	}
67 }
68 #else
69 static void nvme_tcp_reclassify_socket(struct socket *sock) { }
70 #endif
71 
72 enum nvme_tcp_send_state {
73 	NVME_TCP_SEND_CMD_PDU = 0,
74 	NVME_TCP_SEND_H2C_PDU,
75 	NVME_TCP_SEND_DATA,
76 	NVME_TCP_SEND_DDGST,
77 };
78 
79 struct nvme_tcp_request {
80 	struct nvme_request	req;
81 	void			*pdu;
82 	struct nvme_tcp_queue	*queue;
83 	u32			data_len;
84 	u32			pdu_len;
85 	u32			pdu_sent;
86 	u32			h2cdata_left;
87 	u32			h2cdata_offset;
88 	u16			ttag;
89 	__le16			status;
90 	struct list_head	entry;
91 	struct llist_node	lentry;
92 	__le32			ddgst;
93 
94 	struct bio		*curr_bio;
95 	struct iov_iter		iter;
96 
97 	/* send state */
98 	size_t			offset;
99 	size_t			data_sent;
100 	enum nvme_tcp_send_state state;
101 };
102 
103 enum nvme_tcp_queue_flags {
104 	NVME_TCP_Q_ALLOCATED	= 0,
105 	NVME_TCP_Q_LIVE		= 1,
106 	NVME_TCP_Q_POLLING	= 2,
107 };
108 
109 enum nvme_tcp_recv_state {
110 	NVME_TCP_RECV_PDU = 0,
111 	NVME_TCP_RECV_DATA,
112 	NVME_TCP_RECV_DDGST,
113 };
114 
115 struct nvme_tcp_ctrl;
116 struct nvme_tcp_queue {
117 	struct socket		*sock;
118 	struct work_struct	io_work;
119 	int			io_cpu;
120 
121 	struct mutex		queue_lock;
122 	struct mutex		send_mutex;
123 	struct llist_head	req_list;
124 	struct list_head	send_list;
125 
126 	/* recv state */
127 	void			*pdu;
128 	int			pdu_remaining;
129 	int			pdu_offset;
130 	size_t			data_remaining;
131 	size_t			ddgst_remaining;
132 	unsigned int		nr_cqe;
133 
134 	/* send state */
135 	struct nvme_tcp_request *request;
136 
137 	u32			maxh2cdata;
138 	size_t			cmnd_capsule_len;
139 	struct nvme_tcp_ctrl	*ctrl;
140 	unsigned long		flags;
141 	bool			rd_enabled;
142 
143 	bool			hdr_digest;
144 	bool			data_digest;
145 	struct ahash_request	*rcv_hash;
146 	struct ahash_request	*snd_hash;
147 	__le32			exp_ddgst;
148 	__le32			recv_ddgst;
149 
150 	struct page_frag_cache	pf_cache;
151 
152 	void (*state_change)(struct sock *);
153 	void (*data_ready)(struct sock *);
154 	void (*write_space)(struct sock *);
155 };
156 
157 struct nvme_tcp_ctrl {
158 	/* read only in the hot path */
159 	struct nvme_tcp_queue	*queues;
160 	struct blk_mq_tag_set	tag_set;
161 
162 	/* other member variables */
163 	struct list_head	list;
164 	struct blk_mq_tag_set	admin_tag_set;
165 	struct sockaddr_storage addr;
166 	struct sockaddr_storage src_addr;
167 	struct nvme_ctrl	ctrl;
168 
169 	struct work_struct	err_work;
170 	struct delayed_work	connect_work;
171 	struct nvme_tcp_request async_req;
172 	u32			io_queues[HCTX_MAX_TYPES];
173 };
174 
175 static LIST_HEAD(nvme_tcp_ctrl_list);
176 static DEFINE_MUTEX(nvme_tcp_ctrl_mutex);
177 static struct workqueue_struct *nvme_tcp_wq;
178 static const struct blk_mq_ops nvme_tcp_mq_ops;
179 static const struct blk_mq_ops nvme_tcp_admin_mq_ops;
180 static int nvme_tcp_try_send(struct nvme_tcp_queue *queue);
181 
182 static inline struct nvme_tcp_ctrl *to_tcp_ctrl(struct nvme_ctrl *ctrl)
183 {
184 	return container_of(ctrl, struct nvme_tcp_ctrl, ctrl);
185 }
186 
187 static inline int nvme_tcp_queue_id(struct nvme_tcp_queue *queue)
188 {
189 	return queue - queue->ctrl->queues;
190 }
191 
192 static inline struct blk_mq_tags *nvme_tcp_tagset(struct nvme_tcp_queue *queue)
193 {
194 	u32 queue_idx = nvme_tcp_queue_id(queue);
195 
196 	if (queue_idx == 0)
197 		return queue->ctrl->admin_tag_set.tags[queue_idx];
198 	return queue->ctrl->tag_set.tags[queue_idx - 1];
199 }
200 
201 static inline u8 nvme_tcp_hdgst_len(struct nvme_tcp_queue *queue)
202 {
203 	return queue->hdr_digest ? NVME_TCP_DIGEST_LENGTH : 0;
204 }
205 
206 static inline u8 nvme_tcp_ddgst_len(struct nvme_tcp_queue *queue)
207 {
208 	return queue->data_digest ? NVME_TCP_DIGEST_LENGTH : 0;
209 }
210 
211 static inline void *nvme_tcp_req_cmd_pdu(struct nvme_tcp_request *req)
212 {
213 	return req->pdu;
214 }
215 
216 static inline void *nvme_tcp_req_data_pdu(struct nvme_tcp_request *req)
217 {
218 	/* use the pdu space in the back for the data pdu */
219 	return req->pdu + sizeof(struct nvme_tcp_cmd_pdu) -
220 		sizeof(struct nvme_tcp_data_pdu);
221 }
222 
223 static inline size_t nvme_tcp_inline_data_size(struct nvme_tcp_request *req)
224 {
225 	if (nvme_is_fabrics(req->req.cmd))
226 		return NVME_TCP_ADMIN_CCSZ;
227 	return req->queue->cmnd_capsule_len - sizeof(struct nvme_command);
228 }
229 
230 static inline bool nvme_tcp_async_req(struct nvme_tcp_request *req)
231 {
232 	return req == &req->queue->ctrl->async_req;
233 }
234 
235 static inline bool nvme_tcp_has_inline_data(struct nvme_tcp_request *req)
236 {
237 	struct request *rq;
238 
239 	if (unlikely(nvme_tcp_async_req(req)))
240 		return false; /* async events don't have a request */
241 
242 	rq = blk_mq_rq_from_pdu(req);
243 
244 	return rq_data_dir(rq) == WRITE && req->data_len &&
245 		req->data_len <= nvme_tcp_inline_data_size(req);
246 }
247 
248 static inline struct page *nvme_tcp_req_cur_page(struct nvme_tcp_request *req)
249 {
250 	return req->iter.bvec->bv_page;
251 }
252 
253 static inline size_t nvme_tcp_req_cur_offset(struct nvme_tcp_request *req)
254 {
255 	return req->iter.bvec->bv_offset + req->iter.iov_offset;
256 }
257 
258 static inline size_t nvme_tcp_req_cur_length(struct nvme_tcp_request *req)
259 {
260 	return min_t(size_t, iov_iter_single_seg_count(&req->iter),
261 			req->pdu_len - req->pdu_sent);
262 }
263 
264 static inline size_t nvme_tcp_pdu_data_left(struct nvme_tcp_request *req)
265 {
266 	return rq_data_dir(blk_mq_rq_from_pdu(req)) == WRITE ?
267 			req->pdu_len - req->pdu_sent : 0;
268 }
269 
270 static inline size_t nvme_tcp_pdu_last_send(struct nvme_tcp_request *req,
271 		int len)
272 {
273 	return nvme_tcp_pdu_data_left(req) <= len;
274 }
275 
276 static void nvme_tcp_init_iter(struct nvme_tcp_request *req,
277 		unsigned int dir)
278 {
279 	struct request *rq = blk_mq_rq_from_pdu(req);
280 	struct bio_vec *vec;
281 	unsigned int size;
282 	int nr_bvec;
283 	size_t offset;
284 
285 	if (rq->rq_flags & RQF_SPECIAL_PAYLOAD) {
286 		vec = &rq->special_vec;
287 		nr_bvec = 1;
288 		size = blk_rq_payload_bytes(rq);
289 		offset = 0;
290 	} else {
291 		struct bio *bio = req->curr_bio;
292 		struct bvec_iter bi;
293 		struct bio_vec bv;
294 
295 		vec = __bvec_iter_bvec(bio->bi_io_vec, bio->bi_iter);
296 		nr_bvec = 0;
297 		bio_for_each_bvec(bv, bio, bi) {
298 			nr_bvec++;
299 		}
300 		size = bio->bi_iter.bi_size;
301 		offset = bio->bi_iter.bi_bvec_done;
302 	}
303 
304 	iov_iter_bvec(&req->iter, dir, vec, nr_bvec, size);
305 	req->iter.iov_offset = offset;
306 }
307 
308 static inline void nvme_tcp_advance_req(struct nvme_tcp_request *req,
309 		int len)
310 {
311 	req->data_sent += len;
312 	req->pdu_sent += len;
313 	iov_iter_advance(&req->iter, len);
314 	if (!iov_iter_count(&req->iter) &&
315 	    req->data_sent < req->data_len) {
316 		req->curr_bio = req->curr_bio->bi_next;
317 		nvme_tcp_init_iter(req, ITER_SOURCE);
318 	}
319 }
320 
321 static inline void nvme_tcp_send_all(struct nvme_tcp_queue *queue)
322 {
323 	int ret;
324 
325 	/* drain the send queue as much as we can... */
326 	do {
327 		ret = nvme_tcp_try_send(queue);
328 	} while (ret > 0);
329 }
330 
331 static inline bool nvme_tcp_queue_more(struct nvme_tcp_queue *queue)
332 {
333 	return !list_empty(&queue->send_list) ||
334 		!llist_empty(&queue->req_list);
335 }
336 
337 static inline void nvme_tcp_queue_request(struct nvme_tcp_request *req,
338 		bool sync, bool last)
339 {
340 	struct nvme_tcp_queue *queue = req->queue;
341 	bool empty;
342 
343 	empty = llist_add(&req->lentry, &queue->req_list) &&
344 		list_empty(&queue->send_list) && !queue->request;
345 
346 	/*
347 	 * if we're the first on the send_list and we can try to send
348 	 * directly, otherwise queue io_work. Also, only do that if we
349 	 * are on the same cpu, so we don't introduce contention.
350 	 */
351 	if (queue->io_cpu == raw_smp_processor_id() &&
352 	    sync && empty && mutex_trylock(&queue->send_mutex)) {
353 		nvme_tcp_send_all(queue);
354 		mutex_unlock(&queue->send_mutex);
355 	}
356 
357 	if (last && nvme_tcp_queue_more(queue))
358 		queue_work_on(queue->io_cpu, nvme_tcp_wq, &queue->io_work);
359 }
360 
361 static void nvme_tcp_process_req_list(struct nvme_tcp_queue *queue)
362 {
363 	struct nvme_tcp_request *req;
364 	struct llist_node *node;
365 
366 	for (node = llist_del_all(&queue->req_list); node; node = node->next) {
367 		req = llist_entry(node, struct nvme_tcp_request, lentry);
368 		list_add(&req->entry, &queue->send_list);
369 	}
370 }
371 
372 static inline struct nvme_tcp_request *
373 nvme_tcp_fetch_request(struct nvme_tcp_queue *queue)
374 {
375 	struct nvme_tcp_request *req;
376 
377 	req = list_first_entry_or_null(&queue->send_list,
378 			struct nvme_tcp_request, entry);
379 	if (!req) {
380 		nvme_tcp_process_req_list(queue);
381 		req = list_first_entry_or_null(&queue->send_list,
382 				struct nvme_tcp_request, entry);
383 		if (unlikely(!req))
384 			return NULL;
385 	}
386 
387 	list_del(&req->entry);
388 	return req;
389 }
390 
391 static inline void nvme_tcp_ddgst_final(struct ahash_request *hash,
392 		__le32 *dgst)
393 {
394 	ahash_request_set_crypt(hash, NULL, (u8 *)dgst, 0);
395 	crypto_ahash_final(hash);
396 }
397 
398 static inline void nvme_tcp_ddgst_update(struct ahash_request *hash,
399 		struct page *page, off_t off, size_t len)
400 {
401 	struct scatterlist sg;
402 
403 	sg_init_table(&sg, 1);
404 	sg_set_page(&sg, page, len, off);
405 	ahash_request_set_crypt(hash, &sg, NULL, len);
406 	crypto_ahash_update(hash);
407 }
408 
409 static inline void nvme_tcp_hdgst(struct ahash_request *hash,
410 		void *pdu, size_t len)
411 {
412 	struct scatterlist sg;
413 
414 	sg_init_one(&sg, pdu, len);
415 	ahash_request_set_crypt(hash, &sg, pdu + len, len);
416 	crypto_ahash_digest(hash);
417 }
418 
419 static int nvme_tcp_verify_hdgst(struct nvme_tcp_queue *queue,
420 		void *pdu, size_t pdu_len)
421 {
422 	struct nvme_tcp_hdr *hdr = pdu;
423 	__le32 recv_digest;
424 	__le32 exp_digest;
425 
426 	if (unlikely(!(hdr->flags & NVME_TCP_F_HDGST))) {
427 		dev_err(queue->ctrl->ctrl.device,
428 			"queue %d: header digest flag is cleared\n",
429 			nvme_tcp_queue_id(queue));
430 		return -EPROTO;
431 	}
432 
433 	recv_digest = *(__le32 *)(pdu + hdr->hlen);
434 	nvme_tcp_hdgst(queue->rcv_hash, pdu, pdu_len);
435 	exp_digest = *(__le32 *)(pdu + hdr->hlen);
436 	if (recv_digest != exp_digest) {
437 		dev_err(queue->ctrl->ctrl.device,
438 			"header digest error: recv %#x expected %#x\n",
439 			le32_to_cpu(recv_digest), le32_to_cpu(exp_digest));
440 		return -EIO;
441 	}
442 
443 	return 0;
444 }
445 
446 static int nvme_tcp_check_ddgst(struct nvme_tcp_queue *queue, void *pdu)
447 {
448 	struct nvme_tcp_hdr *hdr = pdu;
449 	u8 digest_len = nvme_tcp_hdgst_len(queue);
450 	u32 len;
451 
452 	len = le32_to_cpu(hdr->plen) - hdr->hlen -
453 		((hdr->flags & NVME_TCP_F_HDGST) ? digest_len : 0);
454 
455 	if (unlikely(len && !(hdr->flags & NVME_TCP_F_DDGST))) {
456 		dev_err(queue->ctrl->ctrl.device,
457 			"queue %d: data digest flag is cleared\n",
458 		nvme_tcp_queue_id(queue));
459 		return -EPROTO;
460 	}
461 	crypto_ahash_init(queue->rcv_hash);
462 
463 	return 0;
464 }
465 
466 static void nvme_tcp_exit_request(struct blk_mq_tag_set *set,
467 		struct request *rq, unsigned int hctx_idx)
468 {
469 	struct nvme_tcp_request *req = blk_mq_rq_to_pdu(rq);
470 
471 	page_frag_free(req->pdu);
472 }
473 
474 static int nvme_tcp_init_request(struct blk_mq_tag_set *set,
475 		struct request *rq, unsigned int hctx_idx,
476 		unsigned int numa_node)
477 {
478 	struct nvme_tcp_ctrl *ctrl = to_tcp_ctrl(set->driver_data);
479 	struct nvme_tcp_request *req = blk_mq_rq_to_pdu(rq);
480 	struct nvme_tcp_cmd_pdu *pdu;
481 	int queue_idx = (set == &ctrl->tag_set) ? hctx_idx + 1 : 0;
482 	struct nvme_tcp_queue *queue = &ctrl->queues[queue_idx];
483 	u8 hdgst = nvme_tcp_hdgst_len(queue);
484 
485 	req->pdu = page_frag_alloc(&queue->pf_cache,
486 		sizeof(struct nvme_tcp_cmd_pdu) + hdgst,
487 		GFP_KERNEL | __GFP_ZERO);
488 	if (!req->pdu)
489 		return -ENOMEM;
490 
491 	pdu = req->pdu;
492 	req->queue = queue;
493 	nvme_req(rq)->ctrl = &ctrl->ctrl;
494 	nvme_req(rq)->cmd = &pdu->cmd;
495 
496 	return 0;
497 }
498 
499 static int nvme_tcp_init_hctx(struct blk_mq_hw_ctx *hctx, void *data,
500 		unsigned int hctx_idx)
501 {
502 	struct nvme_tcp_ctrl *ctrl = to_tcp_ctrl(data);
503 	struct nvme_tcp_queue *queue = &ctrl->queues[hctx_idx + 1];
504 
505 	hctx->driver_data = queue;
506 	return 0;
507 }
508 
509 static int nvme_tcp_init_admin_hctx(struct blk_mq_hw_ctx *hctx, void *data,
510 		unsigned int hctx_idx)
511 {
512 	struct nvme_tcp_ctrl *ctrl = to_tcp_ctrl(data);
513 	struct nvme_tcp_queue *queue = &ctrl->queues[0];
514 
515 	hctx->driver_data = queue;
516 	return 0;
517 }
518 
519 static enum nvme_tcp_recv_state
520 nvme_tcp_recv_state(struct nvme_tcp_queue *queue)
521 {
522 	return  (queue->pdu_remaining) ? NVME_TCP_RECV_PDU :
523 		(queue->ddgst_remaining) ? NVME_TCP_RECV_DDGST :
524 		NVME_TCP_RECV_DATA;
525 }
526 
527 static void nvme_tcp_init_recv_ctx(struct nvme_tcp_queue *queue)
528 {
529 	queue->pdu_remaining = sizeof(struct nvme_tcp_rsp_pdu) +
530 				nvme_tcp_hdgst_len(queue);
531 	queue->pdu_offset = 0;
532 	queue->data_remaining = -1;
533 	queue->ddgst_remaining = 0;
534 }
535 
536 static void nvme_tcp_error_recovery(struct nvme_ctrl *ctrl)
537 {
538 	if (!nvme_change_ctrl_state(ctrl, NVME_CTRL_RESETTING))
539 		return;
540 
541 	dev_warn(ctrl->device, "starting error recovery\n");
542 	queue_work(nvme_reset_wq, &to_tcp_ctrl(ctrl)->err_work);
543 }
544 
545 static int nvme_tcp_process_nvme_cqe(struct nvme_tcp_queue *queue,
546 		struct nvme_completion *cqe)
547 {
548 	struct nvme_tcp_request *req;
549 	struct request *rq;
550 
551 	rq = nvme_find_rq(nvme_tcp_tagset(queue), cqe->command_id);
552 	if (!rq) {
553 		dev_err(queue->ctrl->ctrl.device,
554 			"got bad cqe.command_id %#x on queue %d\n",
555 			cqe->command_id, nvme_tcp_queue_id(queue));
556 		nvme_tcp_error_recovery(&queue->ctrl->ctrl);
557 		return -EINVAL;
558 	}
559 
560 	req = blk_mq_rq_to_pdu(rq);
561 	if (req->status == cpu_to_le16(NVME_SC_SUCCESS))
562 		req->status = cqe->status;
563 
564 	if (!nvme_try_complete_req(rq, req->status, cqe->result))
565 		nvme_complete_rq(rq);
566 	queue->nr_cqe++;
567 
568 	return 0;
569 }
570 
571 static int nvme_tcp_handle_c2h_data(struct nvme_tcp_queue *queue,
572 		struct nvme_tcp_data_pdu *pdu)
573 {
574 	struct request *rq;
575 
576 	rq = nvme_find_rq(nvme_tcp_tagset(queue), pdu->command_id);
577 	if (!rq) {
578 		dev_err(queue->ctrl->ctrl.device,
579 			"got bad c2hdata.command_id %#x on queue %d\n",
580 			pdu->command_id, nvme_tcp_queue_id(queue));
581 		return -ENOENT;
582 	}
583 
584 	if (!blk_rq_payload_bytes(rq)) {
585 		dev_err(queue->ctrl->ctrl.device,
586 			"queue %d tag %#x unexpected data\n",
587 			nvme_tcp_queue_id(queue), rq->tag);
588 		return -EIO;
589 	}
590 
591 	queue->data_remaining = le32_to_cpu(pdu->data_length);
592 
593 	if (pdu->hdr.flags & NVME_TCP_F_DATA_SUCCESS &&
594 	    unlikely(!(pdu->hdr.flags & NVME_TCP_F_DATA_LAST))) {
595 		dev_err(queue->ctrl->ctrl.device,
596 			"queue %d tag %#x SUCCESS set but not last PDU\n",
597 			nvme_tcp_queue_id(queue), rq->tag);
598 		nvme_tcp_error_recovery(&queue->ctrl->ctrl);
599 		return -EPROTO;
600 	}
601 
602 	return 0;
603 }
604 
605 static int nvme_tcp_handle_comp(struct nvme_tcp_queue *queue,
606 		struct nvme_tcp_rsp_pdu *pdu)
607 {
608 	struct nvme_completion *cqe = &pdu->cqe;
609 	int ret = 0;
610 
611 	/*
612 	 * AEN requests are special as they don't time out and can
613 	 * survive any kind of queue freeze and often don't respond to
614 	 * aborts.  We don't even bother to allocate a struct request
615 	 * for them but rather special case them here.
616 	 */
617 	if (unlikely(nvme_is_aen_req(nvme_tcp_queue_id(queue),
618 				     cqe->command_id)))
619 		nvme_complete_async_event(&queue->ctrl->ctrl, cqe->status,
620 				&cqe->result);
621 	else
622 		ret = nvme_tcp_process_nvme_cqe(queue, cqe);
623 
624 	return ret;
625 }
626 
627 static void nvme_tcp_setup_h2c_data_pdu(struct nvme_tcp_request *req)
628 {
629 	struct nvme_tcp_data_pdu *data = nvme_tcp_req_data_pdu(req);
630 	struct nvme_tcp_queue *queue = req->queue;
631 	struct request *rq = blk_mq_rq_from_pdu(req);
632 	u32 h2cdata_sent = req->pdu_len;
633 	u8 hdgst = nvme_tcp_hdgst_len(queue);
634 	u8 ddgst = nvme_tcp_ddgst_len(queue);
635 
636 	req->state = NVME_TCP_SEND_H2C_PDU;
637 	req->offset = 0;
638 	req->pdu_len = min(req->h2cdata_left, queue->maxh2cdata);
639 	req->pdu_sent = 0;
640 	req->h2cdata_left -= req->pdu_len;
641 	req->h2cdata_offset += h2cdata_sent;
642 
643 	memset(data, 0, sizeof(*data));
644 	data->hdr.type = nvme_tcp_h2c_data;
645 	if (!req->h2cdata_left)
646 		data->hdr.flags = NVME_TCP_F_DATA_LAST;
647 	if (queue->hdr_digest)
648 		data->hdr.flags |= NVME_TCP_F_HDGST;
649 	if (queue->data_digest)
650 		data->hdr.flags |= NVME_TCP_F_DDGST;
651 	data->hdr.hlen = sizeof(*data);
652 	data->hdr.pdo = data->hdr.hlen + hdgst;
653 	data->hdr.plen =
654 		cpu_to_le32(data->hdr.hlen + hdgst + req->pdu_len + ddgst);
655 	data->ttag = req->ttag;
656 	data->command_id = nvme_cid(rq);
657 	data->data_offset = cpu_to_le32(req->h2cdata_offset);
658 	data->data_length = cpu_to_le32(req->pdu_len);
659 }
660 
661 static int nvme_tcp_handle_r2t(struct nvme_tcp_queue *queue,
662 		struct nvme_tcp_r2t_pdu *pdu)
663 {
664 	struct nvme_tcp_request *req;
665 	struct request *rq;
666 	u32 r2t_length = le32_to_cpu(pdu->r2t_length);
667 	u32 r2t_offset = le32_to_cpu(pdu->r2t_offset);
668 
669 	rq = nvme_find_rq(nvme_tcp_tagset(queue), pdu->command_id);
670 	if (!rq) {
671 		dev_err(queue->ctrl->ctrl.device,
672 			"got bad r2t.command_id %#x on queue %d\n",
673 			pdu->command_id, nvme_tcp_queue_id(queue));
674 		return -ENOENT;
675 	}
676 	req = blk_mq_rq_to_pdu(rq);
677 
678 	if (unlikely(!r2t_length)) {
679 		dev_err(queue->ctrl->ctrl.device,
680 			"req %d r2t len is %u, probably a bug...\n",
681 			rq->tag, r2t_length);
682 		return -EPROTO;
683 	}
684 
685 	if (unlikely(req->data_sent + r2t_length > req->data_len)) {
686 		dev_err(queue->ctrl->ctrl.device,
687 			"req %d r2t len %u exceeded data len %u (%zu sent)\n",
688 			rq->tag, r2t_length, req->data_len, req->data_sent);
689 		return -EPROTO;
690 	}
691 
692 	if (unlikely(r2t_offset < req->data_sent)) {
693 		dev_err(queue->ctrl->ctrl.device,
694 			"req %d unexpected r2t offset %u (expected %zu)\n",
695 			rq->tag, r2t_offset, req->data_sent);
696 		return -EPROTO;
697 	}
698 
699 	req->pdu_len = 0;
700 	req->h2cdata_left = r2t_length;
701 	req->h2cdata_offset = r2t_offset;
702 	req->ttag = pdu->ttag;
703 
704 	nvme_tcp_setup_h2c_data_pdu(req);
705 	nvme_tcp_queue_request(req, false, true);
706 
707 	return 0;
708 }
709 
710 static int nvme_tcp_recv_pdu(struct nvme_tcp_queue *queue, struct sk_buff *skb,
711 		unsigned int *offset, size_t *len)
712 {
713 	struct nvme_tcp_hdr *hdr;
714 	char *pdu = queue->pdu;
715 	size_t rcv_len = min_t(size_t, *len, queue->pdu_remaining);
716 	int ret;
717 
718 	ret = skb_copy_bits(skb, *offset,
719 		&pdu[queue->pdu_offset], rcv_len);
720 	if (unlikely(ret))
721 		return ret;
722 
723 	queue->pdu_remaining -= rcv_len;
724 	queue->pdu_offset += rcv_len;
725 	*offset += rcv_len;
726 	*len -= rcv_len;
727 	if (queue->pdu_remaining)
728 		return 0;
729 
730 	hdr = queue->pdu;
731 	if (queue->hdr_digest) {
732 		ret = nvme_tcp_verify_hdgst(queue, queue->pdu, hdr->hlen);
733 		if (unlikely(ret))
734 			return ret;
735 	}
736 
737 
738 	if (queue->data_digest) {
739 		ret = nvme_tcp_check_ddgst(queue, queue->pdu);
740 		if (unlikely(ret))
741 			return ret;
742 	}
743 
744 	switch (hdr->type) {
745 	case nvme_tcp_c2h_data:
746 		return nvme_tcp_handle_c2h_data(queue, (void *)queue->pdu);
747 	case nvme_tcp_rsp:
748 		nvme_tcp_init_recv_ctx(queue);
749 		return nvme_tcp_handle_comp(queue, (void *)queue->pdu);
750 	case nvme_tcp_r2t:
751 		nvme_tcp_init_recv_ctx(queue);
752 		return nvme_tcp_handle_r2t(queue, (void *)queue->pdu);
753 	default:
754 		dev_err(queue->ctrl->ctrl.device,
755 			"unsupported pdu type (%d)\n", hdr->type);
756 		return -EINVAL;
757 	}
758 }
759 
760 static inline void nvme_tcp_end_request(struct request *rq, u16 status)
761 {
762 	union nvme_result res = {};
763 
764 	if (!nvme_try_complete_req(rq, cpu_to_le16(status << 1), res))
765 		nvme_complete_rq(rq);
766 }
767 
768 static int nvme_tcp_recv_data(struct nvme_tcp_queue *queue, struct sk_buff *skb,
769 			      unsigned int *offset, size_t *len)
770 {
771 	struct nvme_tcp_data_pdu *pdu = (void *)queue->pdu;
772 	struct request *rq =
773 		nvme_cid_to_rq(nvme_tcp_tagset(queue), pdu->command_id);
774 	struct nvme_tcp_request *req = blk_mq_rq_to_pdu(rq);
775 
776 	while (true) {
777 		int recv_len, ret;
778 
779 		recv_len = min_t(size_t, *len, queue->data_remaining);
780 		if (!recv_len)
781 			break;
782 
783 		if (!iov_iter_count(&req->iter)) {
784 			req->curr_bio = req->curr_bio->bi_next;
785 
786 			/*
787 			 * If we don`t have any bios it means that controller
788 			 * sent more data than we requested, hence error
789 			 */
790 			if (!req->curr_bio) {
791 				dev_err(queue->ctrl->ctrl.device,
792 					"queue %d no space in request %#x",
793 					nvme_tcp_queue_id(queue), rq->tag);
794 				nvme_tcp_init_recv_ctx(queue);
795 				return -EIO;
796 			}
797 			nvme_tcp_init_iter(req, ITER_DEST);
798 		}
799 
800 		/* we can read only from what is left in this bio */
801 		recv_len = min_t(size_t, recv_len,
802 				iov_iter_count(&req->iter));
803 
804 		if (queue->data_digest)
805 			ret = skb_copy_and_hash_datagram_iter(skb, *offset,
806 				&req->iter, recv_len, queue->rcv_hash);
807 		else
808 			ret = skb_copy_datagram_iter(skb, *offset,
809 					&req->iter, recv_len);
810 		if (ret) {
811 			dev_err(queue->ctrl->ctrl.device,
812 				"queue %d failed to copy request %#x data",
813 				nvme_tcp_queue_id(queue), rq->tag);
814 			return ret;
815 		}
816 
817 		*len -= recv_len;
818 		*offset += recv_len;
819 		queue->data_remaining -= recv_len;
820 	}
821 
822 	if (!queue->data_remaining) {
823 		if (queue->data_digest) {
824 			nvme_tcp_ddgst_final(queue->rcv_hash, &queue->exp_ddgst);
825 			queue->ddgst_remaining = NVME_TCP_DIGEST_LENGTH;
826 		} else {
827 			if (pdu->hdr.flags & NVME_TCP_F_DATA_SUCCESS) {
828 				nvme_tcp_end_request(rq,
829 						le16_to_cpu(req->status));
830 				queue->nr_cqe++;
831 			}
832 			nvme_tcp_init_recv_ctx(queue);
833 		}
834 	}
835 
836 	return 0;
837 }
838 
839 static int nvme_tcp_recv_ddgst(struct nvme_tcp_queue *queue,
840 		struct sk_buff *skb, unsigned int *offset, size_t *len)
841 {
842 	struct nvme_tcp_data_pdu *pdu = (void *)queue->pdu;
843 	char *ddgst = (char *)&queue->recv_ddgst;
844 	size_t recv_len = min_t(size_t, *len, queue->ddgst_remaining);
845 	off_t off = NVME_TCP_DIGEST_LENGTH - queue->ddgst_remaining;
846 	int ret;
847 
848 	ret = skb_copy_bits(skb, *offset, &ddgst[off], recv_len);
849 	if (unlikely(ret))
850 		return ret;
851 
852 	queue->ddgst_remaining -= recv_len;
853 	*offset += recv_len;
854 	*len -= recv_len;
855 	if (queue->ddgst_remaining)
856 		return 0;
857 
858 	if (queue->recv_ddgst != queue->exp_ddgst) {
859 		struct request *rq = nvme_cid_to_rq(nvme_tcp_tagset(queue),
860 					pdu->command_id);
861 		struct nvme_tcp_request *req = blk_mq_rq_to_pdu(rq);
862 
863 		req->status = cpu_to_le16(NVME_SC_DATA_XFER_ERROR);
864 
865 		dev_err(queue->ctrl->ctrl.device,
866 			"data digest error: recv %#x expected %#x\n",
867 			le32_to_cpu(queue->recv_ddgst),
868 			le32_to_cpu(queue->exp_ddgst));
869 	}
870 
871 	if (pdu->hdr.flags & NVME_TCP_F_DATA_SUCCESS) {
872 		struct request *rq = nvme_cid_to_rq(nvme_tcp_tagset(queue),
873 					pdu->command_id);
874 		struct nvme_tcp_request *req = blk_mq_rq_to_pdu(rq);
875 
876 		nvme_tcp_end_request(rq, le16_to_cpu(req->status));
877 		queue->nr_cqe++;
878 	}
879 
880 	nvme_tcp_init_recv_ctx(queue);
881 	return 0;
882 }
883 
884 static int nvme_tcp_recv_skb(read_descriptor_t *desc, struct sk_buff *skb,
885 			     unsigned int offset, size_t len)
886 {
887 	struct nvme_tcp_queue *queue = desc->arg.data;
888 	size_t consumed = len;
889 	int result;
890 
891 	while (len) {
892 		switch (nvme_tcp_recv_state(queue)) {
893 		case NVME_TCP_RECV_PDU:
894 			result = nvme_tcp_recv_pdu(queue, skb, &offset, &len);
895 			break;
896 		case NVME_TCP_RECV_DATA:
897 			result = nvme_tcp_recv_data(queue, skb, &offset, &len);
898 			break;
899 		case NVME_TCP_RECV_DDGST:
900 			result = nvme_tcp_recv_ddgst(queue, skb, &offset, &len);
901 			break;
902 		default:
903 			result = -EFAULT;
904 		}
905 		if (result) {
906 			dev_err(queue->ctrl->ctrl.device,
907 				"receive failed:  %d\n", result);
908 			queue->rd_enabled = false;
909 			nvme_tcp_error_recovery(&queue->ctrl->ctrl);
910 			return result;
911 		}
912 	}
913 
914 	return consumed;
915 }
916 
917 static void nvme_tcp_data_ready(struct sock *sk)
918 {
919 	struct nvme_tcp_queue *queue;
920 
921 	trace_sk_data_ready(sk);
922 
923 	read_lock_bh(&sk->sk_callback_lock);
924 	queue = sk->sk_user_data;
925 	if (likely(queue && queue->rd_enabled) &&
926 	    !test_bit(NVME_TCP_Q_POLLING, &queue->flags))
927 		queue_work_on(queue->io_cpu, nvme_tcp_wq, &queue->io_work);
928 	read_unlock_bh(&sk->sk_callback_lock);
929 }
930 
931 static void nvme_tcp_write_space(struct sock *sk)
932 {
933 	struct nvme_tcp_queue *queue;
934 
935 	read_lock_bh(&sk->sk_callback_lock);
936 	queue = sk->sk_user_data;
937 	if (likely(queue && sk_stream_is_writeable(sk))) {
938 		clear_bit(SOCK_NOSPACE, &sk->sk_socket->flags);
939 		queue_work_on(queue->io_cpu, nvme_tcp_wq, &queue->io_work);
940 	}
941 	read_unlock_bh(&sk->sk_callback_lock);
942 }
943 
944 static void nvme_tcp_state_change(struct sock *sk)
945 {
946 	struct nvme_tcp_queue *queue;
947 
948 	read_lock_bh(&sk->sk_callback_lock);
949 	queue = sk->sk_user_data;
950 	if (!queue)
951 		goto done;
952 
953 	switch (sk->sk_state) {
954 	case TCP_CLOSE:
955 	case TCP_CLOSE_WAIT:
956 	case TCP_LAST_ACK:
957 	case TCP_FIN_WAIT1:
958 	case TCP_FIN_WAIT2:
959 		nvme_tcp_error_recovery(&queue->ctrl->ctrl);
960 		break;
961 	default:
962 		dev_info(queue->ctrl->ctrl.device,
963 			"queue %d socket state %d\n",
964 			nvme_tcp_queue_id(queue), sk->sk_state);
965 	}
966 
967 	queue->state_change(sk);
968 done:
969 	read_unlock_bh(&sk->sk_callback_lock);
970 }
971 
972 static inline void nvme_tcp_done_send_req(struct nvme_tcp_queue *queue)
973 {
974 	queue->request = NULL;
975 }
976 
977 static void nvme_tcp_fail_request(struct nvme_tcp_request *req)
978 {
979 	if (nvme_tcp_async_req(req)) {
980 		union nvme_result res = {};
981 
982 		nvme_complete_async_event(&req->queue->ctrl->ctrl,
983 				cpu_to_le16(NVME_SC_HOST_PATH_ERROR), &res);
984 	} else {
985 		nvme_tcp_end_request(blk_mq_rq_from_pdu(req),
986 				NVME_SC_HOST_PATH_ERROR);
987 	}
988 }
989 
990 static int nvme_tcp_try_send_data(struct nvme_tcp_request *req)
991 {
992 	struct nvme_tcp_queue *queue = req->queue;
993 	int req_data_len = req->data_len;
994 	u32 h2cdata_left = req->h2cdata_left;
995 
996 	while (true) {
997 		struct page *page = nvme_tcp_req_cur_page(req);
998 		size_t offset = nvme_tcp_req_cur_offset(req);
999 		size_t len = nvme_tcp_req_cur_length(req);
1000 		bool last = nvme_tcp_pdu_last_send(req, len);
1001 		int req_data_sent = req->data_sent;
1002 		int ret, flags = MSG_DONTWAIT;
1003 
1004 		if (last && !queue->data_digest && !nvme_tcp_queue_more(queue))
1005 			flags |= MSG_EOR;
1006 		else
1007 			flags |= MSG_MORE | MSG_SENDPAGE_NOTLAST;
1008 
1009 		if (sendpage_ok(page)) {
1010 			ret = kernel_sendpage(queue->sock, page, offset, len,
1011 					flags);
1012 		} else {
1013 			ret = sock_no_sendpage(queue->sock, page, offset, len,
1014 					flags);
1015 		}
1016 		if (ret <= 0)
1017 			return ret;
1018 
1019 		if (queue->data_digest)
1020 			nvme_tcp_ddgst_update(queue->snd_hash, page,
1021 					offset, ret);
1022 
1023 		/*
1024 		 * update the request iterator except for the last payload send
1025 		 * in the request where we don't want to modify it as we may
1026 		 * compete with the RX path completing the request.
1027 		 */
1028 		if (req_data_sent + ret < req_data_len)
1029 			nvme_tcp_advance_req(req, ret);
1030 
1031 		/* fully successful last send in current PDU */
1032 		if (last && ret == len) {
1033 			if (queue->data_digest) {
1034 				nvme_tcp_ddgst_final(queue->snd_hash,
1035 					&req->ddgst);
1036 				req->state = NVME_TCP_SEND_DDGST;
1037 				req->offset = 0;
1038 			} else {
1039 				if (h2cdata_left)
1040 					nvme_tcp_setup_h2c_data_pdu(req);
1041 				else
1042 					nvme_tcp_done_send_req(queue);
1043 			}
1044 			return 1;
1045 		}
1046 	}
1047 	return -EAGAIN;
1048 }
1049 
1050 static int nvme_tcp_try_send_cmd_pdu(struct nvme_tcp_request *req)
1051 {
1052 	struct nvme_tcp_queue *queue = req->queue;
1053 	struct nvme_tcp_cmd_pdu *pdu = nvme_tcp_req_cmd_pdu(req);
1054 	bool inline_data = nvme_tcp_has_inline_data(req);
1055 	u8 hdgst = nvme_tcp_hdgst_len(queue);
1056 	int len = sizeof(*pdu) + hdgst - req->offset;
1057 	int flags = MSG_DONTWAIT;
1058 	int ret;
1059 
1060 	if (inline_data || nvme_tcp_queue_more(queue))
1061 		flags |= MSG_MORE | MSG_SENDPAGE_NOTLAST;
1062 	else
1063 		flags |= MSG_EOR;
1064 
1065 	if (queue->hdr_digest && !req->offset)
1066 		nvme_tcp_hdgst(queue->snd_hash, pdu, sizeof(*pdu));
1067 
1068 	ret = kernel_sendpage(queue->sock, virt_to_page(pdu),
1069 			offset_in_page(pdu) + req->offset, len,  flags);
1070 	if (unlikely(ret <= 0))
1071 		return ret;
1072 
1073 	len -= ret;
1074 	if (!len) {
1075 		if (inline_data) {
1076 			req->state = NVME_TCP_SEND_DATA;
1077 			if (queue->data_digest)
1078 				crypto_ahash_init(queue->snd_hash);
1079 		} else {
1080 			nvme_tcp_done_send_req(queue);
1081 		}
1082 		return 1;
1083 	}
1084 	req->offset += ret;
1085 
1086 	return -EAGAIN;
1087 }
1088 
1089 static int nvme_tcp_try_send_data_pdu(struct nvme_tcp_request *req)
1090 {
1091 	struct nvme_tcp_queue *queue = req->queue;
1092 	struct nvme_tcp_data_pdu *pdu = nvme_tcp_req_data_pdu(req);
1093 	u8 hdgst = nvme_tcp_hdgst_len(queue);
1094 	int len = sizeof(*pdu) - req->offset + hdgst;
1095 	int ret;
1096 
1097 	if (queue->hdr_digest && !req->offset)
1098 		nvme_tcp_hdgst(queue->snd_hash, pdu, sizeof(*pdu));
1099 
1100 	if (!req->h2cdata_left)
1101 		ret = kernel_sendpage(queue->sock, virt_to_page(pdu),
1102 				offset_in_page(pdu) + req->offset, len,
1103 				MSG_DONTWAIT | MSG_MORE | MSG_SENDPAGE_NOTLAST);
1104 	else
1105 		ret = sock_no_sendpage(queue->sock, virt_to_page(pdu),
1106 				offset_in_page(pdu) + req->offset, len,
1107 				MSG_DONTWAIT | MSG_MORE);
1108 	if (unlikely(ret <= 0))
1109 		return ret;
1110 
1111 	len -= ret;
1112 	if (!len) {
1113 		req->state = NVME_TCP_SEND_DATA;
1114 		if (queue->data_digest)
1115 			crypto_ahash_init(queue->snd_hash);
1116 		return 1;
1117 	}
1118 	req->offset += ret;
1119 
1120 	return -EAGAIN;
1121 }
1122 
1123 static int nvme_tcp_try_send_ddgst(struct nvme_tcp_request *req)
1124 {
1125 	struct nvme_tcp_queue *queue = req->queue;
1126 	size_t offset = req->offset;
1127 	u32 h2cdata_left = req->h2cdata_left;
1128 	int ret;
1129 	struct msghdr msg = { .msg_flags = MSG_DONTWAIT };
1130 	struct kvec iov = {
1131 		.iov_base = (u8 *)&req->ddgst + req->offset,
1132 		.iov_len = NVME_TCP_DIGEST_LENGTH - req->offset
1133 	};
1134 
1135 	if (nvme_tcp_queue_more(queue))
1136 		msg.msg_flags |= MSG_MORE;
1137 	else
1138 		msg.msg_flags |= MSG_EOR;
1139 
1140 	ret = kernel_sendmsg(queue->sock, &msg, &iov, 1, iov.iov_len);
1141 	if (unlikely(ret <= 0))
1142 		return ret;
1143 
1144 	if (offset + ret == NVME_TCP_DIGEST_LENGTH) {
1145 		if (h2cdata_left)
1146 			nvme_tcp_setup_h2c_data_pdu(req);
1147 		else
1148 			nvme_tcp_done_send_req(queue);
1149 		return 1;
1150 	}
1151 
1152 	req->offset += ret;
1153 	return -EAGAIN;
1154 }
1155 
1156 static int nvme_tcp_try_send(struct nvme_tcp_queue *queue)
1157 {
1158 	struct nvme_tcp_request *req;
1159 	unsigned int noreclaim_flag;
1160 	int ret = 1;
1161 
1162 	if (!queue->request) {
1163 		queue->request = nvme_tcp_fetch_request(queue);
1164 		if (!queue->request)
1165 			return 0;
1166 	}
1167 	req = queue->request;
1168 
1169 	noreclaim_flag = memalloc_noreclaim_save();
1170 	if (req->state == NVME_TCP_SEND_CMD_PDU) {
1171 		ret = nvme_tcp_try_send_cmd_pdu(req);
1172 		if (ret <= 0)
1173 			goto done;
1174 		if (!nvme_tcp_has_inline_data(req))
1175 			goto out;
1176 	}
1177 
1178 	if (req->state == NVME_TCP_SEND_H2C_PDU) {
1179 		ret = nvme_tcp_try_send_data_pdu(req);
1180 		if (ret <= 0)
1181 			goto done;
1182 	}
1183 
1184 	if (req->state == NVME_TCP_SEND_DATA) {
1185 		ret = nvme_tcp_try_send_data(req);
1186 		if (ret <= 0)
1187 			goto done;
1188 	}
1189 
1190 	if (req->state == NVME_TCP_SEND_DDGST)
1191 		ret = nvme_tcp_try_send_ddgst(req);
1192 done:
1193 	if (ret == -EAGAIN) {
1194 		ret = 0;
1195 	} else if (ret < 0) {
1196 		dev_err(queue->ctrl->ctrl.device,
1197 			"failed to send request %d\n", ret);
1198 		nvme_tcp_fail_request(queue->request);
1199 		nvme_tcp_done_send_req(queue);
1200 	}
1201 out:
1202 	memalloc_noreclaim_restore(noreclaim_flag);
1203 	return ret;
1204 }
1205 
1206 static int nvme_tcp_try_recv(struct nvme_tcp_queue *queue)
1207 {
1208 	struct socket *sock = queue->sock;
1209 	struct sock *sk = sock->sk;
1210 	read_descriptor_t rd_desc;
1211 	int consumed;
1212 
1213 	rd_desc.arg.data = queue;
1214 	rd_desc.count = 1;
1215 	lock_sock(sk);
1216 	queue->nr_cqe = 0;
1217 	consumed = sock->ops->read_sock(sk, &rd_desc, nvme_tcp_recv_skb);
1218 	release_sock(sk);
1219 	return consumed;
1220 }
1221 
1222 static void nvme_tcp_io_work(struct work_struct *w)
1223 {
1224 	struct nvme_tcp_queue *queue =
1225 		container_of(w, struct nvme_tcp_queue, io_work);
1226 	unsigned long deadline = jiffies + msecs_to_jiffies(1);
1227 
1228 	do {
1229 		bool pending = false;
1230 		int result;
1231 
1232 		if (mutex_trylock(&queue->send_mutex)) {
1233 			result = nvme_tcp_try_send(queue);
1234 			mutex_unlock(&queue->send_mutex);
1235 			if (result > 0)
1236 				pending = true;
1237 			else if (unlikely(result < 0))
1238 				break;
1239 		}
1240 
1241 		result = nvme_tcp_try_recv(queue);
1242 		if (result > 0)
1243 			pending = true;
1244 		else if (unlikely(result < 0))
1245 			return;
1246 
1247 		if (!pending || !queue->rd_enabled)
1248 			return;
1249 
1250 	} while (!time_after(jiffies, deadline)); /* quota is exhausted */
1251 
1252 	queue_work_on(queue->io_cpu, nvme_tcp_wq, &queue->io_work);
1253 }
1254 
1255 static void nvme_tcp_free_crypto(struct nvme_tcp_queue *queue)
1256 {
1257 	struct crypto_ahash *tfm = crypto_ahash_reqtfm(queue->rcv_hash);
1258 
1259 	ahash_request_free(queue->rcv_hash);
1260 	ahash_request_free(queue->snd_hash);
1261 	crypto_free_ahash(tfm);
1262 }
1263 
1264 static int nvme_tcp_alloc_crypto(struct nvme_tcp_queue *queue)
1265 {
1266 	struct crypto_ahash *tfm;
1267 
1268 	tfm = crypto_alloc_ahash("crc32c", 0, CRYPTO_ALG_ASYNC);
1269 	if (IS_ERR(tfm))
1270 		return PTR_ERR(tfm);
1271 
1272 	queue->snd_hash = ahash_request_alloc(tfm, GFP_KERNEL);
1273 	if (!queue->snd_hash)
1274 		goto free_tfm;
1275 	ahash_request_set_callback(queue->snd_hash, 0, NULL, NULL);
1276 
1277 	queue->rcv_hash = ahash_request_alloc(tfm, GFP_KERNEL);
1278 	if (!queue->rcv_hash)
1279 		goto free_snd_hash;
1280 	ahash_request_set_callback(queue->rcv_hash, 0, NULL, NULL);
1281 
1282 	return 0;
1283 free_snd_hash:
1284 	ahash_request_free(queue->snd_hash);
1285 free_tfm:
1286 	crypto_free_ahash(tfm);
1287 	return -ENOMEM;
1288 }
1289 
1290 static void nvme_tcp_free_async_req(struct nvme_tcp_ctrl *ctrl)
1291 {
1292 	struct nvme_tcp_request *async = &ctrl->async_req;
1293 
1294 	page_frag_free(async->pdu);
1295 }
1296 
1297 static int nvme_tcp_alloc_async_req(struct nvme_tcp_ctrl *ctrl)
1298 {
1299 	struct nvme_tcp_queue *queue = &ctrl->queues[0];
1300 	struct nvme_tcp_request *async = &ctrl->async_req;
1301 	u8 hdgst = nvme_tcp_hdgst_len(queue);
1302 
1303 	async->pdu = page_frag_alloc(&queue->pf_cache,
1304 		sizeof(struct nvme_tcp_cmd_pdu) + hdgst,
1305 		GFP_KERNEL | __GFP_ZERO);
1306 	if (!async->pdu)
1307 		return -ENOMEM;
1308 
1309 	async->queue = &ctrl->queues[0];
1310 	return 0;
1311 }
1312 
1313 static void nvme_tcp_free_queue(struct nvme_ctrl *nctrl, int qid)
1314 {
1315 	struct page *page;
1316 	struct nvme_tcp_ctrl *ctrl = to_tcp_ctrl(nctrl);
1317 	struct nvme_tcp_queue *queue = &ctrl->queues[qid];
1318 	unsigned int noreclaim_flag;
1319 
1320 	if (!test_and_clear_bit(NVME_TCP_Q_ALLOCATED, &queue->flags))
1321 		return;
1322 
1323 	if (queue->hdr_digest || queue->data_digest)
1324 		nvme_tcp_free_crypto(queue);
1325 
1326 	if (queue->pf_cache.va) {
1327 		page = virt_to_head_page(queue->pf_cache.va);
1328 		__page_frag_cache_drain(page, queue->pf_cache.pagecnt_bias);
1329 		queue->pf_cache.va = NULL;
1330 	}
1331 
1332 	noreclaim_flag = memalloc_noreclaim_save();
1333 	sock_release(queue->sock);
1334 	memalloc_noreclaim_restore(noreclaim_flag);
1335 
1336 	kfree(queue->pdu);
1337 	mutex_destroy(&queue->send_mutex);
1338 	mutex_destroy(&queue->queue_lock);
1339 }
1340 
1341 static int nvme_tcp_init_connection(struct nvme_tcp_queue *queue)
1342 {
1343 	struct nvme_tcp_icreq_pdu *icreq;
1344 	struct nvme_tcp_icresp_pdu *icresp;
1345 	struct msghdr msg = {};
1346 	struct kvec iov;
1347 	bool ctrl_hdgst, ctrl_ddgst;
1348 	u32 maxh2cdata;
1349 	int ret;
1350 
1351 	icreq = kzalloc(sizeof(*icreq), GFP_KERNEL);
1352 	if (!icreq)
1353 		return -ENOMEM;
1354 
1355 	icresp = kzalloc(sizeof(*icresp), GFP_KERNEL);
1356 	if (!icresp) {
1357 		ret = -ENOMEM;
1358 		goto free_icreq;
1359 	}
1360 
1361 	icreq->hdr.type = nvme_tcp_icreq;
1362 	icreq->hdr.hlen = sizeof(*icreq);
1363 	icreq->hdr.pdo = 0;
1364 	icreq->hdr.plen = cpu_to_le32(icreq->hdr.hlen);
1365 	icreq->pfv = cpu_to_le16(NVME_TCP_PFV_1_0);
1366 	icreq->maxr2t = 0; /* single inflight r2t supported */
1367 	icreq->hpda = 0; /* no alignment constraint */
1368 	if (queue->hdr_digest)
1369 		icreq->digest |= NVME_TCP_HDR_DIGEST_ENABLE;
1370 	if (queue->data_digest)
1371 		icreq->digest |= NVME_TCP_DATA_DIGEST_ENABLE;
1372 
1373 	iov.iov_base = icreq;
1374 	iov.iov_len = sizeof(*icreq);
1375 	ret = kernel_sendmsg(queue->sock, &msg, &iov, 1, iov.iov_len);
1376 	if (ret < 0)
1377 		goto free_icresp;
1378 
1379 	memset(&msg, 0, sizeof(msg));
1380 	iov.iov_base = icresp;
1381 	iov.iov_len = sizeof(*icresp);
1382 	ret = kernel_recvmsg(queue->sock, &msg, &iov, 1,
1383 			iov.iov_len, msg.msg_flags);
1384 	if (ret < 0)
1385 		goto free_icresp;
1386 
1387 	ret = -EINVAL;
1388 	if (icresp->hdr.type != nvme_tcp_icresp) {
1389 		pr_err("queue %d: bad type returned %d\n",
1390 			nvme_tcp_queue_id(queue), icresp->hdr.type);
1391 		goto free_icresp;
1392 	}
1393 
1394 	if (le32_to_cpu(icresp->hdr.plen) != sizeof(*icresp)) {
1395 		pr_err("queue %d: bad pdu length returned %d\n",
1396 			nvme_tcp_queue_id(queue), icresp->hdr.plen);
1397 		goto free_icresp;
1398 	}
1399 
1400 	if (icresp->pfv != NVME_TCP_PFV_1_0) {
1401 		pr_err("queue %d: bad pfv returned %d\n",
1402 			nvme_tcp_queue_id(queue), icresp->pfv);
1403 		goto free_icresp;
1404 	}
1405 
1406 	ctrl_ddgst = !!(icresp->digest & NVME_TCP_DATA_DIGEST_ENABLE);
1407 	if ((queue->data_digest && !ctrl_ddgst) ||
1408 	    (!queue->data_digest && ctrl_ddgst)) {
1409 		pr_err("queue %d: data digest mismatch host: %s ctrl: %s\n",
1410 			nvme_tcp_queue_id(queue),
1411 			queue->data_digest ? "enabled" : "disabled",
1412 			ctrl_ddgst ? "enabled" : "disabled");
1413 		goto free_icresp;
1414 	}
1415 
1416 	ctrl_hdgst = !!(icresp->digest & NVME_TCP_HDR_DIGEST_ENABLE);
1417 	if ((queue->hdr_digest && !ctrl_hdgst) ||
1418 	    (!queue->hdr_digest && ctrl_hdgst)) {
1419 		pr_err("queue %d: header digest mismatch host: %s ctrl: %s\n",
1420 			nvme_tcp_queue_id(queue),
1421 			queue->hdr_digest ? "enabled" : "disabled",
1422 			ctrl_hdgst ? "enabled" : "disabled");
1423 		goto free_icresp;
1424 	}
1425 
1426 	if (icresp->cpda != 0) {
1427 		pr_err("queue %d: unsupported cpda returned %d\n",
1428 			nvme_tcp_queue_id(queue), icresp->cpda);
1429 		goto free_icresp;
1430 	}
1431 
1432 	maxh2cdata = le32_to_cpu(icresp->maxdata);
1433 	if ((maxh2cdata % 4) || (maxh2cdata < NVME_TCP_MIN_MAXH2CDATA)) {
1434 		pr_err("queue %d: invalid maxh2cdata returned %u\n",
1435 		       nvme_tcp_queue_id(queue), maxh2cdata);
1436 		goto free_icresp;
1437 	}
1438 	queue->maxh2cdata = maxh2cdata;
1439 
1440 	ret = 0;
1441 free_icresp:
1442 	kfree(icresp);
1443 free_icreq:
1444 	kfree(icreq);
1445 	return ret;
1446 }
1447 
1448 static bool nvme_tcp_admin_queue(struct nvme_tcp_queue *queue)
1449 {
1450 	return nvme_tcp_queue_id(queue) == 0;
1451 }
1452 
1453 static bool nvme_tcp_default_queue(struct nvme_tcp_queue *queue)
1454 {
1455 	struct nvme_tcp_ctrl *ctrl = queue->ctrl;
1456 	int qid = nvme_tcp_queue_id(queue);
1457 
1458 	return !nvme_tcp_admin_queue(queue) &&
1459 		qid < 1 + ctrl->io_queues[HCTX_TYPE_DEFAULT];
1460 }
1461 
1462 static bool nvme_tcp_read_queue(struct nvme_tcp_queue *queue)
1463 {
1464 	struct nvme_tcp_ctrl *ctrl = queue->ctrl;
1465 	int qid = nvme_tcp_queue_id(queue);
1466 
1467 	return !nvme_tcp_admin_queue(queue) &&
1468 		!nvme_tcp_default_queue(queue) &&
1469 		qid < 1 + ctrl->io_queues[HCTX_TYPE_DEFAULT] +
1470 			  ctrl->io_queues[HCTX_TYPE_READ];
1471 }
1472 
1473 static bool nvme_tcp_poll_queue(struct nvme_tcp_queue *queue)
1474 {
1475 	struct nvme_tcp_ctrl *ctrl = queue->ctrl;
1476 	int qid = nvme_tcp_queue_id(queue);
1477 
1478 	return !nvme_tcp_admin_queue(queue) &&
1479 		!nvme_tcp_default_queue(queue) &&
1480 		!nvme_tcp_read_queue(queue) &&
1481 		qid < 1 + ctrl->io_queues[HCTX_TYPE_DEFAULT] +
1482 			  ctrl->io_queues[HCTX_TYPE_READ] +
1483 			  ctrl->io_queues[HCTX_TYPE_POLL];
1484 }
1485 
1486 static void nvme_tcp_set_queue_io_cpu(struct nvme_tcp_queue *queue)
1487 {
1488 	struct nvme_tcp_ctrl *ctrl = queue->ctrl;
1489 	int qid = nvme_tcp_queue_id(queue);
1490 	int n = 0;
1491 
1492 	if (nvme_tcp_default_queue(queue))
1493 		n = qid - 1;
1494 	else if (nvme_tcp_read_queue(queue))
1495 		n = qid - ctrl->io_queues[HCTX_TYPE_DEFAULT] - 1;
1496 	else if (nvme_tcp_poll_queue(queue))
1497 		n = qid - ctrl->io_queues[HCTX_TYPE_DEFAULT] -
1498 				ctrl->io_queues[HCTX_TYPE_READ] - 1;
1499 	queue->io_cpu = cpumask_next_wrap(n - 1, cpu_online_mask, -1, false);
1500 }
1501 
1502 static int nvme_tcp_alloc_queue(struct nvme_ctrl *nctrl, int qid)
1503 {
1504 	struct nvme_tcp_ctrl *ctrl = to_tcp_ctrl(nctrl);
1505 	struct nvme_tcp_queue *queue = &ctrl->queues[qid];
1506 	int ret, rcv_pdu_size;
1507 
1508 	mutex_init(&queue->queue_lock);
1509 	queue->ctrl = ctrl;
1510 	init_llist_head(&queue->req_list);
1511 	INIT_LIST_HEAD(&queue->send_list);
1512 	mutex_init(&queue->send_mutex);
1513 	INIT_WORK(&queue->io_work, nvme_tcp_io_work);
1514 
1515 	if (qid > 0)
1516 		queue->cmnd_capsule_len = nctrl->ioccsz * 16;
1517 	else
1518 		queue->cmnd_capsule_len = sizeof(struct nvme_command) +
1519 						NVME_TCP_ADMIN_CCSZ;
1520 
1521 	ret = sock_create(ctrl->addr.ss_family, SOCK_STREAM,
1522 			IPPROTO_TCP, &queue->sock);
1523 	if (ret) {
1524 		dev_err(nctrl->device,
1525 			"failed to create socket: %d\n", ret);
1526 		goto err_destroy_mutex;
1527 	}
1528 
1529 	nvme_tcp_reclassify_socket(queue->sock);
1530 
1531 	/* Single syn retry */
1532 	tcp_sock_set_syncnt(queue->sock->sk, 1);
1533 
1534 	/* Set TCP no delay */
1535 	tcp_sock_set_nodelay(queue->sock->sk);
1536 
1537 	/*
1538 	 * Cleanup whatever is sitting in the TCP transmit queue on socket
1539 	 * close. This is done to prevent stale data from being sent should
1540 	 * the network connection be restored before TCP times out.
1541 	 */
1542 	sock_no_linger(queue->sock->sk);
1543 
1544 	if (so_priority > 0)
1545 		sock_set_priority(queue->sock->sk, so_priority);
1546 
1547 	/* Set socket type of service */
1548 	if (nctrl->opts->tos >= 0)
1549 		ip_sock_set_tos(queue->sock->sk, nctrl->opts->tos);
1550 
1551 	/* Set 10 seconds timeout for icresp recvmsg */
1552 	queue->sock->sk->sk_rcvtimeo = 10 * HZ;
1553 
1554 	queue->sock->sk->sk_allocation = GFP_ATOMIC;
1555 	queue->sock->sk->sk_use_task_frag = false;
1556 	nvme_tcp_set_queue_io_cpu(queue);
1557 	queue->request = NULL;
1558 	queue->data_remaining = 0;
1559 	queue->ddgst_remaining = 0;
1560 	queue->pdu_remaining = 0;
1561 	queue->pdu_offset = 0;
1562 	sk_set_memalloc(queue->sock->sk);
1563 
1564 	if (nctrl->opts->mask & NVMF_OPT_HOST_TRADDR) {
1565 		ret = kernel_bind(queue->sock, (struct sockaddr *)&ctrl->src_addr,
1566 			sizeof(ctrl->src_addr));
1567 		if (ret) {
1568 			dev_err(nctrl->device,
1569 				"failed to bind queue %d socket %d\n",
1570 				qid, ret);
1571 			goto err_sock;
1572 		}
1573 	}
1574 
1575 	if (nctrl->opts->mask & NVMF_OPT_HOST_IFACE) {
1576 		char *iface = nctrl->opts->host_iface;
1577 		sockptr_t optval = KERNEL_SOCKPTR(iface);
1578 
1579 		ret = sock_setsockopt(queue->sock, SOL_SOCKET, SO_BINDTODEVICE,
1580 				      optval, strlen(iface));
1581 		if (ret) {
1582 			dev_err(nctrl->device,
1583 			  "failed to bind to interface %s queue %d err %d\n",
1584 			  iface, qid, ret);
1585 			goto err_sock;
1586 		}
1587 	}
1588 
1589 	queue->hdr_digest = nctrl->opts->hdr_digest;
1590 	queue->data_digest = nctrl->opts->data_digest;
1591 	if (queue->hdr_digest || queue->data_digest) {
1592 		ret = nvme_tcp_alloc_crypto(queue);
1593 		if (ret) {
1594 			dev_err(nctrl->device,
1595 				"failed to allocate queue %d crypto\n", qid);
1596 			goto err_sock;
1597 		}
1598 	}
1599 
1600 	rcv_pdu_size = sizeof(struct nvme_tcp_rsp_pdu) +
1601 			nvme_tcp_hdgst_len(queue);
1602 	queue->pdu = kmalloc(rcv_pdu_size, GFP_KERNEL);
1603 	if (!queue->pdu) {
1604 		ret = -ENOMEM;
1605 		goto err_crypto;
1606 	}
1607 
1608 	dev_dbg(nctrl->device, "connecting queue %d\n",
1609 			nvme_tcp_queue_id(queue));
1610 
1611 	ret = kernel_connect(queue->sock, (struct sockaddr *)&ctrl->addr,
1612 		sizeof(ctrl->addr), 0);
1613 	if (ret) {
1614 		dev_err(nctrl->device,
1615 			"failed to connect socket: %d\n", ret);
1616 		goto err_rcv_pdu;
1617 	}
1618 
1619 	ret = nvme_tcp_init_connection(queue);
1620 	if (ret)
1621 		goto err_init_connect;
1622 
1623 	queue->rd_enabled = true;
1624 	set_bit(NVME_TCP_Q_ALLOCATED, &queue->flags);
1625 	nvme_tcp_init_recv_ctx(queue);
1626 
1627 	write_lock_bh(&queue->sock->sk->sk_callback_lock);
1628 	queue->sock->sk->sk_user_data = queue;
1629 	queue->state_change = queue->sock->sk->sk_state_change;
1630 	queue->data_ready = queue->sock->sk->sk_data_ready;
1631 	queue->write_space = queue->sock->sk->sk_write_space;
1632 	queue->sock->sk->sk_data_ready = nvme_tcp_data_ready;
1633 	queue->sock->sk->sk_state_change = nvme_tcp_state_change;
1634 	queue->sock->sk->sk_write_space = nvme_tcp_write_space;
1635 #ifdef CONFIG_NET_RX_BUSY_POLL
1636 	queue->sock->sk->sk_ll_usec = 1;
1637 #endif
1638 	write_unlock_bh(&queue->sock->sk->sk_callback_lock);
1639 
1640 	return 0;
1641 
1642 err_init_connect:
1643 	kernel_sock_shutdown(queue->sock, SHUT_RDWR);
1644 err_rcv_pdu:
1645 	kfree(queue->pdu);
1646 err_crypto:
1647 	if (queue->hdr_digest || queue->data_digest)
1648 		nvme_tcp_free_crypto(queue);
1649 err_sock:
1650 	sock_release(queue->sock);
1651 	queue->sock = NULL;
1652 err_destroy_mutex:
1653 	mutex_destroy(&queue->send_mutex);
1654 	mutex_destroy(&queue->queue_lock);
1655 	return ret;
1656 }
1657 
1658 static void nvme_tcp_restore_sock_calls(struct nvme_tcp_queue *queue)
1659 {
1660 	struct socket *sock = queue->sock;
1661 
1662 	write_lock_bh(&sock->sk->sk_callback_lock);
1663 	sock->sk->sk_user_data  = NULL;
1664 	sock->sk->sk_data_ready = queue->data_ready;
1665 	sock->sk->sk_state_change = queue->state_change;
1666 	sock->sk->sk_write_space  = queue->write_space;
1667 	write_unlock_bh(&sock->sk->sk_callback_lock);
1668 }
1669 
1670 static void __nvme_tcp_stop_queue(struct nvme_tcp_queue *queue)
1671 {
1672 	kernel_sock_shutdown(queue->sock, SHUT_RDWR);
1673 	nvme_tcp_restore_sock_calls(queue);
1674 	cancel_work_sync(&queue->io_work);
1675 }
1676 
1677 static void nvme_tcp_stop_queue(struct nvme_ctrl *nctrl, int qid)
1678 {
1679 	struct nvme_tcp_ctrl *ctrl = to_tcp_ctrl(nctrl);
1680 	struct nvme_tcp_queue *queue = &ctrl->queues[qid];
1681 
1682 	if (!test_bit(NVME_TCP_Q_ALLOCATED, &queue->flags))
1683 		return;
1684 
1685 	mutex_lock(&queue->queue_lock);
1686 	if (test_and_clear_bit(NVME_TCP_Q_LIVE, &queue->flags))
1687 		__nvme_tcp_stop_queue(queue);
1688 	mutex_unlock(&queue->queue_lock);
1689 }
1690 
1691 static int nvme_tcp_start_queue(struct nvme_ctrl *nctrl, int idx)
1692 {
1693 	struct nvme_tcp_ctrl *ctrl = to_tcp_ctrl(nctrl);
1694 	int ret;
1695 
1696 	if (idx)
1697 		ret = nvmf_connect_io_queue(nctrl, idx);
1698 	else
1699 		ret = nvmf_connect_admin_queue(nctrl);
1700 
1701 	if (!ret) {
1702 		set_bit(NVME_TCP_Q_LIVE, &ctrl->queues[idx].flags);
1703 	} else {
1704 		if (test_bit(NVME_TCP_Q_ALLOCATED, &ctrl->queues[idx].flags))
1705 			__nvme_tcp_stop_queue(&ctrl->queues[idx]);
1706 		dev_err(nctrl->device,
1707 			"failed to connect queue: %d ret=%d\n", idx, ret);
1708 	}
1709 	return ret;
1710 }
1711 
1712 static void nvme_tcp_free_admin_queue(struct nvme_ctrl *ctrl)
1713 {
1714 	if (to_tcp_ctrl(ctrl)->async_req.pdu) {
1715 		cancel_work_sync(&ctrl->async_event_work);
1716 		nvme_tcp_free_async_req(to_tcp_ctrl(ctrl));
1717 		to_tcp_ctrl(ctrl)->async_req.pdu = NULL;
1718 	}
1719 
1720 	nvme_tcp_free_queue(ctrl, 0);
1721 }
1722 
1723 static void nvme_tcp_free_io_queues(struct nvme_ctrl *ctrl)
1724 {
1725 	int i;
1726 
1727 	for (i = 1; i < ctrl->queue_count; i++)
1728 		nvme_tcp_free_queue(ctrl, i);
1729 }
1730 
1731 static void nvme_tcp_stop_io_queues(struct nvme_ctrl *ctrl)
1732 {
1733 	int i;
1734 
1735 	for (i = 1; i < ctrl->queue_count; i++)
1736 		nvme_tcp_stop_queue(ctrl, i);
1737 }
1738 
1739 static int nvme_tcp_start_io_queues(struct nvme_ctrl *ctrl,
1740 				    int first, int last)
1741 {
1742 	int i, ret;
1743 
1744 	for (i = first; i < last; i++) {
1745 		ret = nvme_tcp_start_queue(ctrl, i);
1746 		if (ret)
1747 			goto out_stop_queues;
1748 	}
1749 
1750 	return 0;
1751 
1752 out_stop_queues:
1753 	for (i--; i >= first; i--)
1754 		nvme_tcp_stop_queue(ctrl, i);
1755 	return ret;
1756 }
1757 
1758 static int nvme_tcp_alloc_admin_queue(struct nvme_ctrl *ctrl)
1759 {
1760 	int ret;
1761 
1762 	ret = nvme_tcp_alloc_queue(ctrl, 0);
1763 	if (ret)
1764 		return ret;
1765 
1766 	ret = nvme_tcp_alloc_async_req(to_tcp_ctrl(ctrl));
1767 	if (ret)
1768 		goto out_free_queue;
1769 
1770 	return 0;
1771 
1772 out_free_queue:
1773 	nvme_tcp_free_queue(ctrl, 0);
1774 	return ret;
1775 }
1776 
1777 static int __nvme_tcp_alloc_io_queues(struct nvme_ctrl *ctrl)
1778 {
1779 	int i, ret;
1780 
1781 	for (i = 1; i < ctrl->queue_count; i++) {
1782 		ret = nvme_tcp_alloc_queue(ctrl, i);
1783 		if (ret)
1784 			goto out_free_queues;
1785 	}
1786 
1787 	return 0;
1788 
1789 out_free_queues:
1790 	for (i--; i >= 1; i--)
1791 		nvme_tcp_free_queue(ctrl, i);
1792 
1793 	return ret;
1794 }
1795 
1796 static unsigned int nvme_tcp_nr_io_queues(struct nvme_ctrl *ctrl)
1797 {
1798 	unsigned int nr_io_queues;
1799 
1800 	nr_io_queues = min(ctrl->opts->nr_io_queues, num_online_cpus());
1801 	nr_io_queues += min(ctrl->opts->nr_write_queues, num_online_cpus());
1802 	nr_io_queues += min(ctrl->opts->nr_poll_queues, num_online_cpus());
1803 
1804 	return nr_io_queues;
1805 }
1806 
1807 static void nvme_tcp_set_io_queues(struct nvme_ctrl *nctrl,
1808 		unsigned int nr_io_queues)
1809 {
1810 	struct nvme_tcp_ctrl *ctrl = to_tcp_ctrl(nctrl);
1811 	struct nvmf_ctrl_options *opts = nctrl->opts;
1812 
1813 	if (opts->nr_write_queues && opts->nr_io_queues < nr_io_queues) {
1814 		/*
1815 		 * separate read/write queues
1816 		 * hand out dedicated default queues only after we have
1817 		 * sufficient read queues.
1818 		 */
1819 		ctrl->io_queues[HCTX_TYPE_READ] = opts->nr_io_queues;
1820 		nr_io_queues -= ctrl->io_queues[HCTX_TYPE_READ];
1821 		ctrl->io_queues[HCTX_TYPE_DEFAULT] =
1822 			min(opts->nr_write_queues, nr_io_queues);
1823 		nr_io_queues -= ctrl->io_queues[HCTX_TYPE_DEFAULT];
1824 	} else {
1825 		/*
1826 		 * shared read/write queues
1827 		 * either no write queues were requested, or we don't have
1828 		 * sufficient queue count to have dedicated default queues.
1829 		 */
1830 		ctrl->io_queues[HCTX_TYPE_DEFAULT] =
1831 			min(opts->nr_io_queues, nr_io_queues);
1832 		nr_io_queues -= ctrl->io_queues[HCTX_TYPE_DEFAULT];
1833 	}
1834 
1835 	if (opts->nr_poll_queues && nr_io_queues) {
1836 		/* map dedicated poll queues only if we have queues left */
1837 		ctrl->io_queues[HCTX_TYPE_POLL] =
1838 			min(opts->nr_poll_queues, nr_io_queues);
1839 	}
1840 }
1841 
1842 static int nvme_tcp_alloc_io_queues(struct nvme_ctrl *ctrl)
1843 {
1844 	unsigned int nr_io_queues;
1845 	int ret;
1846 
1847 	nr_io_queues = nvme_tcp_nr_io_queues(ctrl);
1848 	ret = nvme_set_queue_count(ctrl, &nr_io_queues);
1849 	if (ret)
1850 		return ret;
1851 
1852 	if (nr_io_queues == 0) {
1853 		dev_err(ctrl->device,
1854 			"unable to set any I/O queues\n");
1855 		return -ENOMEM;
1856 	}
1857 
1858 	ctrl->queue_count = nr_io_queues + 1;
1859 	dev_info(ctrl->device,
1860 		"creating %d I/O queues.\n", nr_io_queues);
1861 
1862 	nvme_tcp_set_io_queues(ctrl, nr_io_queues);
1863 
1864 	return __nvme_tcp_alloc_io_queues(ctrl);
1865 }
1866 
1867 static void nvme_tcp_destroy_io_queues(struct nvme_ctrl *ctrl, bool remove)
1868 {
1869 	nvme_tcp_stop_io_queues(ctrl);
1870 	if (remove)
1871 		nvme_remove_io_tag_set(ctrl);
1872 	nvme_tcp_free_io_queues(ctrl);
1873 }
1874 
1875 static int nvme_tcp_configure_io_queues(struct nvme_ctrl *ctrl, bool new)
1876 {
1877 	int ret, nr_queues;
1878 
1879 	ret = nvme_tcp_alloc_io_queues(ctrl);
1880 	if (ret)
1881 		return ret;
1882 
1883 	if (new) {
1884 		ret = nvme_alloc_io_tag_set(ctrl, &to_tcp_ctrl(ctrl)->tag_set,
1885 				&nvme_tcp_mq_ops,
1886 				ctrl->opts->nr_poll_queues ? HCTX_MAX_TYPES : 2,
1887 				sizeof(struct nvme_tcp_request));
1888 		if (ret)
1889 			goto out_free_io_queues;
1890 	}
1891 
1892 	/*
1893 	 * Only start IO queues for which we have allocated the tagset
1894 	 * and limitted it to the available queues. On reconnects, the
1895 	 * queue number might have changed.
1896 	 */
1897 	nr_queues = min(ctrl->tagset->nr_hw_queues + 1, ctrl->queue_count);
1898 	ret = nvme_tcp_start_io_queues(ctrl, 1, nr_queues);
1899 	if (ret)
1900 		goto out_cleanup_connect_q;
1901 
1902 	if (!new) {
1903 		nvme_unquiesce_io_queues(ctrl);
1904 		if (!nvme_wait_freeze_timeout(ctrl, NVME_IO_TIMEOUT)) {
1905 			/*
1906 			 * If we timed out waiting for freeze we are likely to
1907 			 * be stuck.  Fail the controller initialization just
1908 			 * to be safe.
1909 			 */
1910 			ret = -ENODEV;
1911 			goto out_wait_freeze_timed_out;
1912 		}
1913 		blk_mq_update_nr_hw_queues(ctrl->tagset,
1914 			ctrl->queue_count - 1);
1915 		nvme_unfreeze(ctrl);
1916 	}
1917 
1918 	/*
1919 	 * If the number of queues has increased (reconnect case)
1920 	 * start all new queues now.
1921 	 */
1922 	ret = nvme_tcp_start_io_queues(ctrl, nr_queues,
1923 				       ctrl->tagset->nr_hw_queues + 1);
1924 	if (ret)
1925 		goto out_wait_freeze_timed_out;
1926 
1927 	return 0;
1928 
1929 out_wait_freeze_timed_out:
1930 	nvme_quiesce_io_queues(ctrl);
1931 	nvme_sync_io_queues(ctrl);
1932 	nvme_tcp_stop_io_queues(ctrl);
1933 out_cleanup_connect_q:
1934 	nvme_cancel_tagset(ctrl);
1935 	if (new)
1936 		nvme_remove_io_tag_set(ctrl);
1937 out_free_io_queues:
1938 	nvme_tcp_free_io_queues(ctrl);
1939 	return ret;
1940 }
1941 
1942 static void nvme_tcp_destroy_admin_queue(struct nvme_ctrl *ctrl, bool remove)
1943 {
1944 	nvme_tcp_stop_queue(ctrl, 0);
1945 	if (remove)
1946 		nvme_remove_admin_tag_set(ctrl);
1947 	nvme_tcp_free_admin_queue(ctrl);
1948 }
1949 
1950 static int nvme_tcp_configure_admin_queue(struct nvme_ctrl *ctrl, bool new)
1951 {
1952 	int error;
1953 
1954 	error = nvme_tcp_alloc_admin_queue(ctrl);
1955 	if (error)
1956 		return error;
1957 
1958 	if (new) {
1959 		error = nvme_alloc_admin_tag_set(ctrl,
1960 				&to_tcp_ctrl(ctrl)->admin_tag_set,
1961 				&nvme_tcp_admin_mq_ops,
1962 				sizeof(struct nvme_tcp_request));
1963 		if (error)
1964 			goto out_free_queue;
1965 	}
1966 
1967 	error = nvme_tcp_start_queue(ctrl, 0);
1968 	if (error)
1969 		goto out_cleanup_tagset;
1970 
1971 	error = nvme_enable_ctrl(ctrl);
1972 	if (error)
1973 		goto out_stop_queue;
1974 
1975 	nvme_unquiesce_admin_queue(ctrl);
1976 
1977 	error = nvme_init_ctrl_finish(ctrl, false);
1978 	if (error)
1979 		goto out_quiesce_queue;
1980 
1981 	return 0;
1982 
1983 out_quiesce_queue:
1984 	nvme_quiesce_admin_queue(ctrl);
1985 	blk_sync_queue(ctrl->admin_q);
1986 out_stop_queue:
1987 	nvme_tcp_stop_queue(ctrl, 0);
1988 	nvme_cancel_admin_tagset(ctrl);
1989 out_cleanup_tagset:
1990 	if (new)
1991 		nvme_remove_admin_tag_set(ctrl);
1992 out_free_queue:
1993 	nvme_tcp_free_admin_queue(ctrl);
1994 	return error;
1995 }
1996 
1997 static void nvme_tcp_teardown_admin_queue(struct nvme_ctrl *ctrl,
1998 		bool remove)
1999 {
2000 	nvme_quiesce_admin_queue(ctrl);
2001 	blk_sync_queue(ctrl->admin_q);
2002 	nvme_tcp_stop_queue(ctrl, 0);
2003 	nvme_cancel_admin_tagset(ctrl);
2004 	if (remove)
2005 		nvme_unquiesce_admin_queue(ctrl);
2006 	nvme_tcp_destroy_admin_queue(ctrl, remove);
2007 }
2008 
2009 static void nvme_tcp_teardown_io_queues(struct nvme_ctrl *ctrl,
2010 		bool remove)
2011 {
2012 	if (ctrl->queue_count <= 1)
2013 		return;
2014 	nvme_quiesce_admin_queue(ctrl);
2015 	nvme_start_freeze(ctrl);
2016 	nvme_quiesce_io_queues(ctrl);
2017 	nvme_sync_io_queues(ctrl);
2018 	nvme_tcp_stop_io_queues(ctrl);
2019 	nvme_cancel_tagset(ctrl);
2020 	if (remove)
2021 		nvme_unquiesce_io_queues(ctrl);
2022 	nvme_tcp_destroy_io_queues(ctrl, remove);
2023 }
2024 
2025 static void nvme_tcp_reconnect_or_remove(struct nvme_ctrl *ctrl)
2026 {
2027 	/* If we are resetting/deleting then do nothing */
2028 	if (ctrl->state != NVME_CTRL_CONNECTING) {
2029 		WARN_ON_ONCE(ctrl->state == NVME_CTRL_NEW ||
2030 			ctrl->state == NVME_CTRL_LIVE);
2031 		return;
2032 	}
2033 
2034 	if (nvmf_should_reconnect(ctrl)) {
2035 		dev_info(ctrl->device, "Reconnecting in %d seconds...\n",
2036 			ctrl->opts->reconnect_delay);
2037 		queue_delayed_work(nvme_wq, &to_tcp_ctrl(ctrl)->connect_work,
2038 				ctrl->opts->reconnect_delay * HZ);
2039 	} else {
2040 		dev_info(ctrl->device, "Removing controller...\n");
2041 		nvme_delete_ctrl(ctrl);
2042 	}
2043 }
2044 
2045 static int nvme_tcp_setup_ctrl(struct nvme_ctrl *ctrl, bool new)
2046 {
2047 	struct nvmf_ctrl_options *opts = ctrl->opts;
2048 	int ret;
2049 
2050 	ret = nvme_tcp_configure_admin_queue(ctrl, new);
2051 	if (ret)
2052 		return ret;
2053 
2054 	if (ctrl->icdoff) {
2055 		ret = -EOPNOTSUPP;
2056 		dev_err(ctrl->device, "icdoff is not supported!\n");
2057 		goto destroy_admin;
2058 	}
2059 
2060 	if (!nvme_ctrl_sgl_supported(ctrl)) {
2061 		ret = -EOPNOTSUPP;
2062 		dev_err(ctrl->device, "Mandatory sgls are not supported!\n");
2063 		goto destroy_admin;
2064 	}
2065 
2066 	if (opts->queue_size > ctrl->sqsize + 1)
2067 		dev_warn(ctrl->device,
2068 			"queue_size %zu > ctrl sqsize %u, clamping down\n",
2069 			opts->queue_size, ctrl->sqsize + 1);
2070 
2071 	if (ctrl->sqsize + 1 > ctrl->maxcmd) {
2072 		dev_warn(ctrl->device,
2073 			"sqsize %u > ctrl maxcmd %u, clamping down\n",
2074 			ctrl->sqsize + 1, ctrl->maxcmd);
2075 		ctrl->sqsize = ctrl->maxcmd - 1;
2076 	}
2077 
2078 	if (ctrl->queue_count > 1) {
2079 		ret = nvme_tcp_configure_io_queues(ctrl, new);
2080 		if (ret)
2081 			goto destroy_admin;
2082 	}
2083 
2084 	if (!nvme_change_ctrl_state(ctrl, NVME_CTRL_LIVE)) {
2085 		/*
2086 		 * state change failure is ok if we started ctrl delete,
2087 		 * unless we're during creation of a new controller to
2088 		 * avoid races with teardown flow.
2089 		 */
2090 		WARN_ON_ONCE(ctrl->state != NVME_CTRL_DELETING &&
2091 			     ctrl->state != NVME_CTRL_DELETING_NOIO);
2092 		WARN_ON_ONCE(new);
2093 		ret = -EINVAL;
2094 		goto destroy_io;
2095 	}
2096 
2097 	nvme_start_ctrl(ctrl);
2098 	return 0;
2099 
2100 destroy_io:
2101 	if (ctrl->queue_count > 1) {
2102 		nvme_quiesce_io_queues(ctrl);
2103 		nvme_sync_io_queues(ctrl);
2104 		nvme_tcp_stop_io_queues(ctrl);
2105 		nvme_cancel_tagset(ctrl);
2106 		nvme_tcp_destroy_io_queues(ctrl, new);
2107 	}
2108 destroy_admin:
2109 	nvme_quiesce_admin_queue(ctrl);
2110 	blk_sync_queue(ctrl->admin_q);
2111 	nvme_tcp_stop_queue(ctrl, 0);
2112 	nvme_cancel_admin_tagset(ctrl);
2113 	nvme_tcp_destroy_admin_queue(ctrl, new);
2114 	return ret;
2115 }
2116 
2117 static void nvme_tcp_reconnect_ctrl_work(struct work_struct *work)
2118 {
2119 	struct nvme_tcp_ctrl *tcp_ctrl = container_of(to_delayed_work(work),
2120 			struct nvme_tcp_ctrl, connect_work);
2121 	struct nvme_ctrl *ctrl = &tcp_ctrl->ctrl;
2122 
2123 	++ctrl->nr_reconnects;
2124 
2125 	if (nvme_tcp_setup_ctrl(ctrl, false))
2126 		goto requeue;
2127 
2128 	dev_info(ctrl->device, "Successfully reconnected (%d attempt)\n",
2129 			ctrl->nr_reconnects);
2130 
2131 	ctrl->nr_reconnects = 0;
2132 
2133 	return;
2134 
2135 requeue:
2136 	dev_info(ctrl->device, "Failed reconnect attempt %d\n",
2137 			ctrl->nr_reconnects);
2138 	nvme_tcp_reconnect_or_remove(ctrl);
2139 }
2140 
2141 static void nvme_tcp_error_recovery_work(struct work_struct *work)
2142 {
2143 	struct nvme_tcp_ctrl *tcp_ctrl = container_of(work,
2144 				struct nvme_tcp_ctrl, err_work);
2145 	struct nvme_ctrl *ctrl = &tcp_ctrl->ctrl;
2146 
2147 	nvme_stop_keep_alive(ctrl);
2148 	flush_work(&ctrl->async_event_work);
2149 	nvme_tcp_teardown_io_queues(ctrl, false);
2150 	/* unquiesce to fail fast pending requests */
2151 	nvme_unquiesce_io_queues(ctrl);
2152 	nvme_tcp_teardown_admin_queue(ctrl, false);
2153 	nvme_unquiesce_admin_queue(ctrl);
2154 	nvme_auth_stop(ctrl);
2155 
2156 	if (!nvme_change_ctrl_state(ctrl, NVME_CTRL_CONNECTING)) {
2157 		/* state change failure is ok if we started ctrl delete */
2158 		WARN_ON_ONCE(ctrl->state != NVME_CTRL_DELETING &&
2159 			     ctrl->state != NVME_CTRL_DELETING_NOIO);
2160 		return;
2161 	}
2162 
2163 	nvme_tcp_reconnect_or_remove(ctrl);
2164 }
2165 
2166 static void nvme_tcp_teardown_ctrl(struct nvme_ctrl *ctrl, bool shutdown)
2167 {
2168 	nvme_tcp_teardown_io_queues(ctrl, shutdown);
2169 	nvme_quiesce_admin_queue(ctrl);
2170 	nvme_disable_ctrl(ctrl, shutdown);
2171 	nvme_tcp_teardown_admin_queue(ctrl, shutdown);
2172 }
2173 
2174 static void nvme_tcp_delete_ctrl(struct nvme_ctrl *ctrl)
2175 {
2176 	nvme_tcp_teardown_ctrl(ctrl, true);
2177 }
2178 
2179 static void nvme_reset_ctrl_work(struct work_struct *work)
2180 {
2181 	struct nvme_ctrl *ctrl =
2182 		container_of(work, struct nvme_ctrl, reset_work);
2183 
2184 	nvme_stop_ctrl(ctrl);
2185 	nvme_tcp_teardown_ctrl(ctrl, false);
2186 
2187 	if (!nvme_change_ctrl_state(ctrl, NVME_CTRL_CONNECTING)) {
2188 		/* state change failure is ok if we started ctrl delete */
2189 		WARN_ON_ONCE(ctrl->state != NVME_CTRL_DELETING &&
2190 			     ctrl->state != NVME_CTRL_DELETING_NOIO);
2191 		return;
2192 	}
2193 
2194 	if (nvme_tcp_setup_ctrl(ctrl, false))
2195 		goto out_fail;
2196 
2197 	return;
2198 
2199 out_fail:
2200 	++ctrl->nr_reconnects;
2201 	nvme_tcp_reconnect_or_remove(ctrl);
2202 }
2203 
2204 static void nvme_tcp_stop_ctrl(struct nvme_ctrl *ctrl)
2205 {
2206 	flush_work(&to_tcp_ctrl(ctrl)->err_work);
2207 	cancel_delayed_work_sync(&to_tcp_ctrl(ctrl)->connect_work);
2208 }
2209 
2210 static void nvme_tcp_free_ctrl(struct nvme_ctrl *nctrl)
2211 {
2212 	struct nvme_tcp_ctrl *ctrl = to_tcp_ctrl(nctrl);
2213 
2214 	if (list_empty(&ctrl->list))
2215 		goto free_ctrl;
2216 
2217 	mutex_lock(&nvme_tcp_ctrl_mutex);
2218 	list_del(&ctrl->list);
2219 	mutex_unlock(&nvme_tcp_ctrl_mutex);
2220 
2221 	nvmf_free_options(nctrl->opts);
2222 free_ctrl:
2223 	kfree(ctrl->queues);
2224 	kfree(ctrl);
2225 }
2226 
2227 static void nvme_tcp_set_sg_null(struct nvme_command *c)
2228 {
2229 	struct nvme_sgl_desc *sg = &c->common.dptr.sgl;
2230 
2231 	sg->addr = 0;
2232 	sg->length = 0;
2233 	sg->type = (NVME_TRANSPORT_SGL_DATA_DESC << 4) |
2234 			NVME_SGL_FMT_TRANSPORT_A;
2235 }
2236 
2237 static void nvme_tcp_set_sg_inline(struct nvme_tcp_queue *queue,
2238 		struct nvme_command *c, u32 data_len)
2239 {
2240 	struct nvme_sgl_desc *sg = &c->common.dptr.sgl;
2241 
2242 	sg->addr = cpu_to_le64(queue->ctrl->ctrl.icdoff);
2243 	sg->length = cpu_to_le32(data_len);
2244 	sg->type = (NVME_SGL_FMT_DATA_DESC << 4) | NVME_SGL_FMT_OFFSET;
2245 }
2246 
2247 static void nvme_tcp_set_sg_host_data(struct nvme_command *c,
2248 		u32 data_len)
2249 {
2250 	struct nvme_sgl_desc *sg = &c->common.dptr.sgl;
2251 
2252 	sg->addr = 0;
2253 	sg->length = cpu_to_le32(data_len);
2254 	sg->type = (NVME_TRANSPORT_SGL_DATA_DESC << 4) |
2255 			NVME_SGL_FMT_TRANSPORT_A;
2256 }
2257 
2258 static void nvme_tcp_submit_async_event(struct nvme_ctrl *arg)
2259 {
2260 	struct nvme_tcp_ctrl *ctrl = to_tcp_ctrl(arg);
2261 	struct nvme_tcp_queue *queue = &ctrl->queues[0];
2262 	struct nvme_tcp_cmd_pdu *pdu = ctrl->async_req.pdu;
2263 	struct nvme_command *cmd = &pdu->cmd;
2264 	u8 hdgst = nvme_tcp_hdgst_len(queue);
2265 
2266 	memset(pdu, 0, sizeof(*pdu));
2267 	pdu->hdr.type = nvme_tcp_cmd;
2268 	if (queue->hdr_digest)
2269 		pdu->hdr.flags |= NVME_TCP_F_HDGST;
2270 	pdu->hdr.hlen = sizeof(*pdu);
2271 	pdu->hdr.plen = cpu_to_le32(pdu->hdr.hlen + hdgst);
2272 
2273 	cmd->common.opcode = nvme_admin_async_event;
2274 	cmd->common.command_id = NVME_AQ_BLK_MQ_DEPTH;
2275 	cmd->common.flags |= NVME_CMD_SGL_METABUF;
2276 	nvme_tcp_set_sg_null(cmd);
2277 
2278 	ctrl->async_req.state = NVME_TCP_SEND_CMD_PDU;
2279 	ctrl->async_req.offset = 0;
2280 	ctrl->async_req.curr_bio = NULL;
2281 	ctrl->async_req.data_len = 0;
2282 
2283 	nvme_tcp_queue_request(&ctrl->async_req, true, true);
2284 }
2285 
2286 static void nvme_tcp_complete_timed_out(struct request *rq)
2287 {
2288 	struct nvme_tcp_request *req = blk_mq_rq_to_pdu(rq);
2289 	struct nvme_ctrl *ctrl = &req->queue->ctrl->ctrl;
2290 
2291 	nvme_tcp_stop_queue(ctrl, nvme_tcp_queue_id(req->queue));
2292 	nvmf_complete_timed_out_request(rq);
2293 }
2294 
2295 static enum blk_eh_timer_return nvme_tcp_timeout(struct request *rq)
2296 {
2297 	struct nvme_tcp_request *req = blk_mq_rq_to_pdu(rq);
2298 	struct nvme_ctrl *ctrl = &req->queue->ctrl->ctrl;
2299 	struct nvme_tcp_cmd_pdu *pdu = nvme_tcp_req_cmd_pdu(req);
2300 	u8 opc = pdu->cmd.common.opcode, fctype = pdu->cmd.fabrics.fctype;
2301 	int qid = nvme_tcp_queue_id(req->queue);
2302 
2303 	dev_warn(ctrl->device,
2304 		"queue %d: timeout cid %#x type %d opcode %#x (%s)\n",
2305 		nvme_tcp_queue_id(req->queue), nvme_cid(rq), pdu->hdr.type,
2306 		opc, nvme_opcode_str(qid, opc, fctype));
2307 
2308 	if (ctrl->state != NVME_CTRL_LIVE) {
2309 		/*
2310 		 * If we are resetting, connecting or deleting we should
2311 		 * complete immediately because we may block controller
2312 		 * teardown or setup sequence
2313 		 * - ctrl disable/shutdown fabrics requests
2314 		 * - connect requests
2315 		 * - initialization admin requests
2316 		 * - I/O requests that entered after unquiescing and
2317 		 *   the controller stopped responding
2318 		 *
2319 		 * All other requests should be cancelled by the error
2320 		 * recovery work, so it's fine that we fail it here.
2321 		 */
2322 		nvme_tcp_complete_timed_out(rq);
2323 		return BLK_EH_DONE;
2324 	}
2325 
2326 	/*
2327 	 * LIVE state should trigger the normal error recovery which will
2328 	 * handle completing this request.
2329 	 */
2330 	nvme_tcp_error_recovery(ctrl);
2331 	return BLK_EH_RESET_TIMER;
2332 }
2333 
2334 static blk_status_t nvme_tcp_map_data(struct nvme_tcp_queue *queue,
2335 			struct request *rq)
2336 {
2337 	struct nvme_tcp_request *req = blk_mq_rq_to_pdu(rq);
2338 	struct nvme_tcp_cmd_pdu *pdu = nvme_tcp_req_cmd_pdu(req);
2339 	struct nvme_command *c = &pdu->cmd;
2340 
2341 	c->common.flags |= NVME_CMD_SGL_METABUF;
2342 
2343 	if (!blk_rq_nr_phys_segments(rq))
2344 		nvme_tcp_set_sg_null(c);
2345 	else if (rq_data_dir(rq) == WRITE &&
2346 	    req->data_len <= nvme_tcp_inline_data_size(req))
2347 		nvme_tcp_set_sg_inline(queue, c, req->data_len);
2348 	else
2349 		nvme_tcp_set_sg_host_data(c, req->data_len);
2350 
2351 	return 0;
2352 }
2353 
2354 static blk_status_t nvme_tcp_setup_cmd_pdu(struct nvme_ns *ns,
2355 		struct request *rq)
2356 {
2357 	struct nvme_tcp_request *req = blk_mq_rq_to_pdu(rq);
2358 	struct nvme_tcp_cmd_pdu *pdu = nvme_tcp_req_cmd_pdu(req);
2359 	struct nvme_tcp_queue *queue = req->queue;
2360 	u8 hdgst = nvme_tcp_hdgst_len(queue), ddgst = 0;
2361 	blk_status_t ret;
2362 
2363 	ret = nvme_setup_cmd(ns, rq);
2364 	if (ret)
2365 		return ret;
2366 
2367 	req->state = NVME_TCP_SEND_CMD_PDU;
2368 	req->status = cpu_to_le16(NVME_SC_SUCCESS);
2369 	req->offset = 0;
2370 	req->data_sent = 0;
2371 	req->pdu_len = 0;
2372 	req->pdu_sent = 0;
2373 	req->h2cdata_left = 0;
2374 	req->data_len = blk_rq_nr_phys_segments(rq) ?
2375 				blk_rq_payload_bytes(rq) : 0;
2376 	req->curr_bio = rq->bio;
2377 	if (req->curr_bio && req->data_len)
2378 		nvme_tcp_init_iter(req, rq_data_dir(rq));
2379 
2380 	if (rq_data_dir(rq) == WRITE &&
2381 	    req->data_len <= nvme_tcp_inline_data_size(req))
2382 		req->pdu_len = req->data_len;
2383 
2384 	pdu->hdr.type = nvme_tcp_cmd;
2385 	pdu->hdr.flags = 0;
2386 	if (queue->hdr_digest)
2387 		pdu->hdr.flags |= NVME_TCP_F_HDGST;
2388 	if (queue->data_digest && req->pdu_len) {
2389 		pdu->hdr.flags |= NVME_TCP_F_DDGST;
2390 		ddgst = nvme_tcp_ddgst_len(queue);
2391 	}
2392 	pdu->hdr.hlen = sizeof(*pdu);
2393 	pdu->hdr.pdo = req->pdu_len ? pdu->hdr.hlen + hdgst : 0;
2394 	pdu->hdr.plen =
2395 		cpu_to_le32(pdu->hdr.hlen + hdgst + req->pdu_len + ddgst);
2396 
2397 	ret = nvme_tcp_map_data(queue, rq);
2398 	if (unlikely(ret)) {
2399 		nvme_cleanup_cmd(rq);
2400 		dev_err(queue->ctrl->ctrl.device,
2401 			"Failed to map data (%d)\n", ret);
2402 		return ret;
2403 	}
2404 
2405 	return 0;
2406 }
2407 
2408 static void nvme_tcp_commit_rqs(struct blk_mq_hw_ctx *hctx)
2409 {
2410 	struct nvme_tcp_queue *queue = hctx->driver_data;
2411 
2412 	if (!llist_empty(&queue->req_list))
2413 		queue_work_on(queue->io_cpu, nvme_tcp_wq, &queue->io_work);
2414 }
2415 
2416 static blk_status_t nvme_tcp_queue_rq(struct blk_mq_hw_ctx *hctx,
2417 		const struct blk_mq_queue_data *bd)
2418 {
2419 	struct nvme_ns *ns = hctx->queue->queuedata;
2420 	struct nvme_tcp_queue *queue = hctx->driver_data;
2421 	struct request *rq = bd->rq;
2422 	struct nvme_tcp_request *req = blk_mq_rq_to_pdu(rq);
2423 	bool queue_ready = test_bit(NVME_TCP_Q_LIVE, &queue->flags);
2424 	blk_status_t ret;
2425 
2426 	if (!nvme_check_ready(&queue->ctrl->ctrl, rq, queue_ready))
2427 		return nvme_fail_nonready_command(&queue->ctrl->ctrl, rq);
2428 
2429 	ret = nvme_tcp_setup_cmd_pdu(ns, rq);
2430 	if (unlikely(ret))
2431 		return ret;
2432 
2433 	nvme_start_request(rq);
2434 
2435 	nvme_tcp_queue_request(req, true, bd->last);
2436 
2437 	return BLK_STS_OK;
2438 }
2439 
2440 static void nvme_tcp_map_queues(struct blk_mq_tag_set *set)
2441 {
2442 	struct nvme_tcp_ctrl *ctrl = to_tcp_ctrl(set->driver_data);
2443 	struct nvmf_ctrl_options *opts = ctrl->ctrl.opts;
2444 
2445 	if (opts->nr_write_queues && ctrl->io_queues[HCTX_TYPE_READ]) {
2446 		/* separate read/write queues */
2447 		set->map[HCTX_TYPE_DEFAULT].nr_queues =
2448 			ctrl->io_queues[HCTX_TYPE_DEFAULT];
2449 		set->map[HCTX_TYPE_DEFAULT].queue_offset = 0;
2450 		set->map[HCTX_TYPE_READ].nr_queues =
2451 			ctrl->io_queues[HCTX_TYPE_READ];
2452 		set->map[HCTX_TYPE_READ].queue_offset =
2453 			ctrl->io_queues[HCTX_TYPE_DEFAULT];
2454 	} else {
2455 		/* shared read/write queues */
2456 		set->map[HCTX_TYPE_DEFAULT].nr_queues =
2457 			ctrl->io_queues[HCTX_TYPE_DEFAULT];
2458 		set->map[HCTX_TYPE_DEFAULT].queue_offset = 0;
2459 		set->map[HCTX_TYPE_READ].nr_queues =
2460 			ctrl->io_queues[HCTX_TYPE_DEFAULT];
2461 		set->map[HCTX_TYPE_READ].queue_offset = 0;
2462 	}
2463 	blk_mq_map_queues(&set->map[HCTX_TYPE_DEFAULT]);
2464 	blk_mq_map_queues(&set->map[HCTX_TYPE_READ]);
2465 
2466 	if (opts->nr_poll_queues && ctrl->io_queues[HCTX_TYPE_POLL]) {
2467 		/* map dedicated poll queues only if we have queues left */
2468 		set->map[HCTX_TYPE_POLL].nr_queues =
2469 				ctrl->io_queues[HCTX_TYPE_POLL];
2470 		set->map[HCTX_TYPE_POLL].queue_offset =
2471 			ctrl->io_queues[HCTX_TYPE_DEFAULT] +
2472 			ctrl->io_queues[HCTX_TYPE_READ];
2473 		blk_mq_map_queues(&set->map[HCTX_TYPE_POLL]);
2474 	}
2475 
2476 	dev_info(ctrl->ctrl.device,
2477 		"mapped %d/%d/%d default/read/poll queues.\n",
2478 		ctrl->io_queues[HCTX_TYPE_DEFAULT],
2479 		ctrl->io_queues[HCTX_TYPE_READ],
2480 		ctrl->io_queues[HCTX_TYPE_POLL]);
2481 }
2482 
2483 static int nvme_tcp_poll(struct blk_mq_hw_ctx *hctx, struct io_comp_batch *iob)
2484 {
2485 	struct nvme_tcp_queue *queue = hctx->driver_data;
2486 	struct sock *sk = queue->sock->sk;
2487 
2488 	if (!test_bit(NVME_TCP_Q_LIVE, &queue->flags))
2489 		return 0;
2490 
2491 	set_bit(NVME_TCP_Q_POLLING, &queue->flags);
2492 	if (sk_can_busy_loop(sk) && skb_queue_empty_lockless(&sk->sk_receive_queue))
2493 		sk_busy_loop(sk, true);
2494 	nvme_tcp_try_recv(queue);
2495 	clear_bit(NVME_TCP_Q_POLLING, &queue->flags);
2496 	return queue->nr_cqe;
2497 }
2498 
2499 static int nvme_tcp_get_address(struct nvme_ctrl *ctrl, char *buf, int size)
2500 {
2501 	struct nvme_tcp_queue *queue = &to_tcp_ctrl(ctrl)->queues[0];
2502 	struct sockaddr_storage src_addr;
2503 	int ret, len;
2504 
2505 	len = nvmf_get_address(ctrl, buf, size);
2506 
2507 	mutex_lock(&queue->queue_lock);
2508 
2509 	if (!test_bit(NVME_TCP_Q_LIVE, &queue->flags))
2510 		goto done;
2511 	ret = kernel_getsockname(queue->sock, (struct sockaddr *)&src_addr);
2512 	if (ret > 0) {
2513 		if (len > 0)
2514 			len--; /* strip trailing newline */
2515 		len += scnprintf(buf + len, size - len, "%ssrc_addr=%pISc\n",
2516 				(len) ? "," : "", &src_addr);
2517 	}
2518 done:
2519 	mutex_unlock(&queue->queue_lock);
2520 
2521 	return len;
2522 }
2523 
2524 static const struct blk_mq_ops nvme_tcp_mq_ops = {
2525 	.queue_rq	= nvme_tcp_queue_rq,
2526 	.commit_rqs	= nvme_tcp_commit_rqs,
2527 	.complete	= nvme_complete_rq,
2528 	.init_request	= nvme_tcp_init_request,
2529 	.exit_request	= nvme_tcp_exit_request,
2530 	.init_hctx	= nvme_tcp_init_hctx,
2531 	.timeout	= nvme_tcp_timeout,
2532 	.map_queues	= nvme_tcp_map_queues,
2533 	.poll		= nvme_tcp_poll,
2534 };
2535 
2536 static const struct blk_mq_ops nvme_tcp_admin_mq_ops = {
2537 	.queue_rq	= nvme_tcp_queue_rq,
2538 	.complete	= nvme_complete_rq,
2539 	.init_request	= nvme_tcp_init_request,
2540 	.exit_request	= nvme_tcp_exit_request,
2541 	.init_hctx	= nvme_tcp_init_admin_hctx,
2542 	.timeout	= nvme_tcp_timeout,
2543 };
2544 
2545 static const struct nvme_ctrl_ops nvme_tcp_ctrl_ops = {
2546 	.name			= "tcp",
2547 	.module			= THIS_MODULE,
2548 	.flags			= NVME_F_FABRICS | NVME_F_BLOCKING,
2549 	.reg_read32		= nvmf_reg_read32,
2550 	.reg_read64		= nvmf_reg_read64,
2551 	.reg_write32		= nvmf_reg_write32,
2552 	.free_ctrl		= nvme_tcp_free_ctrl,
2553 	.submit_async_event	= nvme_tcp_submit_async_event,
2554 	.delete_ctrl		= nvme_tcp_delete_ctrl,
2555 	.get_address		= nvme_tcp_get_address,
2556 	.stop_ctrl		= nvme_tcp_stop_ctrl,
2557 };
2558 
2559 static bool
2560 nvme_tcp_existing_controller(struct nvmf_ctrl_options *opts)
2561 {
2562 	struct nvme_tcp_ctrl *ctrl;
2563 	bool found = false;
2564 
2565 	mutex_lock(&nvme_tcp_ctrl_mutex);
2566 	list_for_each_entry(ctrl, &nvme_tcp_ctrl_list, list) {
2567 		found = nvmf_ip_options_match(&ctrl->ctrl, opts);
2568 		if (found)
2569 			break;
2570 	}
2571 	mutex_unlock(&nvme_tcp_ctrl_mutex);
2572 
2573 	return found;
2574 }
2575 
2576 static struct nvme_ctrl *nvme_tcp_create_ctrl(struct device *dev,
2577 		struct nvmf_ctrl_options *opts)
2578 {
2579 	struct nvme_tcp_ctrl *ctrl;
2580 	int ret;
2581 
2582 	ctrl = kzalloc(sizeof(*ctrl), GFP_KERNEL);
2583 	if (!ctrl)
2584 		return ERR_PTR(-ENOMEM);
2585 
2586 	INIT_LIST_HEAD(&ctrl->list);
2587 	ctrl->ctrl.opts = opts;
2588 	ctrl->ctrl.queue_count = opts->nr_io_queues + opts->nr_write_queues +
2589 				opts->nr_poll_queues + 1;
2590 	ctrl->ctrl.sqsize = opts->queue_size - 1;
2591 	ctrl->ctrl.kato = opts->kato;
2592 
2593 	INIT_DELAYED_WORK(&ctrl->connect_work,
2594 			nvme_tcp_reconnect_ctrl_work);
2595 	INIT_WORK(&ctrl->err_work, nvme_tcp_error_recovery_work);
2596 	INIT_WORK(&ctrl->ctrl.reset_work, nvme_reset_ctrl_work);
2597 
2598 	if (!(opts->mask & NVMF_OPT_TRSVCID)) {
2599 		opts->trsvcid =
2600 			kstrdup(__stringify(NVME_TCP_DISC_PORT), GFP_KERNEL);
2601 		if (!opts->trsvcid) {
2602 			ret = -ENOMEM;
2603 			goto out_free_ctrl;
2604 		}
2605 		opts->mask |= NVMF_OPT_TRSVCID;
2606 	}
2607 
2608 	ret = inet_pton_with_scope(&init_net, AF_UNSPEC,
2609 			opts->traddr, opts->trsvcid, &ctrl->addr);
2610 	if (ret) {
2611 		pr_err("malformed address passed: %s:%s\n",
2612 			opts->traddr, opts->trsvcid);
2613 		goto out_free_ctrl;
2614 	}
2615 
2616 	if (opts->mask & NVMF_OPT_HOST_TRADDR) {
2617 		ret = inet_pton_with_scope(&init_net, AF_UNSPEC,
2618 			opts->host_traddr, NULL, &ctrl->src_addr);
2619 		if (ret) {
2620 			pr_err("malformed src address passed: %s\n",
2621 			       opts->host_traddr);
2622 			goto out_free_ctrl;
2623 		}
2624 	}
2625 
2626 	if (opts->mask & NVMF_OPT_HOST_IFACE) {
2627 		if (!__dev_get_by_name(&init_net, opts->host_iface)) {
2628 			pr_err("invalid interface passed: %s\n",
2629 			       opts->host_iface);
2630 			ret = -ENODEV;
2631 			goto out_free_ctrl;
2632 		}
2633 	}
2634 
2635 	if (!opts->duplicate_connect && nvme_tcp_existing_controller(opts)) {
2636 		ret = -EALREADY;
2637 		goto out_free_ctrl;
2638 	}
2639 
2640 	ctrl->queues = kcalloc(ctrl->ctrl.queue_count, sizeof(*ctrl->queues),
2641 				GFP_KERNEL);
2642 	if (!ctrl->queues) {
2643 		ret = -ENOMEM;
2644 		goto out_free_ctrl;
2645 	}
2646 
2647 	ret = nvme_init_ctrl(&ctrl->ctrl, dev, &nvme_tcp_ctrl_ops, 0);
2648 	if (ret)
2649 		goto out_kfree_queues;
2650 
2651 	if (!nvme_change_ctrl_state(&ctrl->ctrl, NVME_CTRL_CONNECTING)) {
2652 		WARN_ON_ONCE(1);
2653 		ret = -EINTR;
2654 		goto out_uninit_ctrl;
2655 	}
2656 
2657 	ret = nvme_tcp_setup_ctrl(&ctrl->ctrl, true);
2658 	if (ret)
2659 		goto out_uninit_ctrl;
2660 
2661 	dev_info(ctrl->ctrl.device, "new ctrl: NQN \"%s\", addr %pISp\n",
2662 		nvmf_ctrl_subsysnqn(&ctrl->ctrl), &ctrl->addr);
2663 
2664 	mutex_lock(&nvme_tcp_ctrl_mutex);
2665 	list_add_tail(&ctrl->list, &nvme_tcp_ctrl_list);
2666 	mutex_unlock(&nvme_tcp_ctrl_mutex);
2667 
2668 	return &ctrl->ctrl;
2669 
2670 out_uninit_ctrl:
2671 	nvme_uninit_ctrl(&ctrl->ctrl);
2672 	nvme_put_ctrl(&ctrl->ctrl);
2673 	if (ret > 0)
2674 		ret = -EIO;
2675 	return ERR_PTR(ret);
2676 out_kfree_queues:
2677 	kfree(ctrl->queues);
2678 out_free_ctrl:
2679 	kfree(ctrl);
2680 	return ERR_PTR(ret);
2681 }
2682 
2683 static struct nvmf_transport_ops nvme_tcp_transport = {
2684 	.name		= "tcp",
2685 	.module		= THIS_MODULE,
2686 	.required_opts	= NVMF_OPT_TRADDR,
2687 	.allowed_opts	= NVMF_OPT_TRSVCID | NVMF_OPT_RECONNECT_DELAY |
2688 			  NVMF_OPT_HOST_TRADDR | NVMF_OPT_CTRL_LOSS_TMO |
2689 			  NVMF_OPT_HDR_DIGEST | NVMF_OPT_DATA_DIGEST |
2690 			  NVMF_OPT_NR_WRITE_QUEUES | NVMF_OPT_NR_POLL_QUEUES |
2691 			  NVMF_OPT_TOS | NVMF_OPT_HOST_IFACE,
2692 	.create_ctrl	= nvme_tcp_create_ctrl,
2693 };
2694 
2695 static int __init nvme_tcp_init_module(void)
2696 {
2697 	BUILD_BUG_ON(sizeof(struct nvme_tcp_hdr) != 8);
2698 	BUILD_BUG_ON(sizeof(struct nvme_tcp_cmd_pdu) != 72);
2699 	BUILD_BUG_ON(sizeof(struct nvme_tcp_data_pdu) != 24);
2700 	BUILD_BUG_ON(sizeof(struct nvme_tcp_rsp_pdu) != 24);
2701 	BUILD_BUG_ON(sizeof(struct nvme_tcp_r2t_pdu) != 24);
2702 	BUILD_BUG_ON(sizeof(struct nvme_tcp_icreq_pdu) != 128);
2703 	BUILD_BUG_ON(sizeof(struct nvme_tcp_icresp_pdu) != 128);
2704 	BUILD_BUG_ON(sizeof(struct nvme_tcp_term_pdu) != 24);
2705 
2706 	nvme_tcp_wq = alloc_workqueue("nvme_tcp_wq",
2707 			WQ_MEM_RECLAIM | WQ_HIGHPRI, 0);
2708 	if (!nvme_tcp_wq)
2709 		return -ENOMEM;
2710 
2711 	nvmf_register_transport(&nvme_tcp_transport);
2712 	return 0;
2713 }
2714 
2715 static void __exit nvme_tcp_cleanup_module(void)
2716 {
2717 	struct nvme_tcp_ctrl *ctrl;
2718 
2719 	nvmf_unregister_transport(&nvme_tcp_transport);
2720 
2721 	mutex_lock(&nvme_tcp_ctrl_mutex);
2722 	list_for_each_entry(ctrl, &nvme_tcp_ctrl_list, list)
2723 		nvme_delete_ctrl(&ctrl->ctrl);
2724 	mutex_unlock(&nvme_tcp_ctrl_mutex);
2725 	flush_workqueue(nvme_delete_wq);
2726 
2727 	destroy_workqueue(nvme_tcp_wq);
2728 }
2729 
2730 module_init(nvme_tcp_init_module);
2731 module_exit(nvme_tcp_cleanup_module);
2732 
2733 MODULE_LICENSE("GPL v2");
2734