xref: /linux/drivers/nvme/target/pci-epf.c (revision 5d5fbfbbacd1efb13a9bf91317d4fde859ede4b9)
1 // SPDX-License-Identifier: GPL-2.0
2 /*
3  * NVMe PCI Endpoint Function target driver.
4  *
5  * Copyright (c) 2024, Western Digital Corporation or its affiliates.
6  * Copyright (c) 2024, Rick Wertenbroek <rick.wertenbroek@gmail.com>
7  *                     REDS Institute, HEIG-VD, HES-SO, Switzerland
8  */
9 #define pr_fmt(fmt) KBUILD_MODNAME ": " fmt
10 
11 #include <linux/delay.h>
12 #include <linux/dmaengine.h>
13 #include <linux/io.h>
14 #include <linux/mempool.h>
15 #include <linux/module.h>
16 #include <linux/mutex.h>
17 #include <linux/nvme.h>
18 #include <linux/pci_ids.h>
19 #include <linux/pci-epc.h>
20 #include <linux/pci-epf.h>
21 #include <linux/pci_regs.h>
22 #include <linux/slab.h>
23 
24 #include "nvmet.h"
25 
26 static LIST_HEAD(nvmet_pci_epf_ports);
27 static DEFINE_MUTEX(nvmet_pci_epf_ports_mutex);
28 
29 /*
30  * Default and maximum allowed data transfer size. For the default,
31  * allow up to 128 page-sized segments. For the maximum allowed,
32  * use 4 times the default (which is completely arbitrary).
33  */
34 #define NVMET_PCI_EPF_MAX_SEGS		128
35 #define NVMET_PCI_EPF_MDTS_KB		\
36 	(NVMET_PCI_EPF_MAX_SEGS << (PAGE_SHIFT - 10))
37 #define NVMET_PCI_EPF_MAX_MDTS_KB	(NVMET_PCI_EPF_MDTS_KB * 4)
38 
39 /*
40  * IRQ vector coalescing threshold: by default, post 8 CQEs before raising an
41  * interrupt vector to the host. This default 8 is completely arbitrary and can
42  * be changed by the host with a nvme_set_features command.
43  */
44 #define NVMET_PCI_EPF_IV_THRESHOLD	8
45 
46 /*
47  * BAR CC register and SQ polling intervals.
48  */
49 #define NVMET_PCI_EPF_CC_POLL_INTERVAL	msecs_to_jiffies(10)
50 #define NVMET_PCI_EPF_SQ_POLL_INTERVAL	msecs_to_jiffies(5)
51 #define NVMET_PCI_EPF_SQ_POLL_IDLE	msecs_to_jiffies(5000)
52 
53 /*
54  * SQ arbitration burst default: fetch at most 8 commands at a time from an SQ.
55  */
56 #define NVMET_PCI_EPF_SQ_AB		8
57 
58 /*
59  * Handling of CQs is normally immediate, unless we fail to map a CQ or the CQ
60  * is full, in which case we retry the CQ processing after this interval.
61  */
62 #define NVMET_PCI_EPF_CQ_RETRY_INTERVAL	msecs_to_jiffies(1)
63 
64 enum nvmet_pci_epf_queue_flags {
65 	NVMET_PCI_EPF_Q_LIVE = 0,	/* The queue is live */
66 	NVMET_PCI_EPF_Q_IRQ_ENABLED,	/* IRQ is enabled for this queue */
67 };
68 
69 /*
70  * IRQ vector descriptor.
71  */
72 struct nvmet_pci_epf_irq_vector {
73 	unsigned int	vector;
74 	unsigned int	ref;
75 	bool		cd;
76 	int		nr_irqs;
77 };
78 
79 struct nvmet_pci_epf_queue {
80 	union {
81 		struct nvmet_sq		nvme_sq;
82 		struct nvmet_cq		nvme_cq;
83 	};
84 	struct nvmet_pci_epf_ctrl	*ctrl;
85 	unsigned long			flags;
86 
87 	u64				pci_addr;
88 	size_t				pci_size;
89 	struct pci_epc_map		pci_map;
90 
91 	u16				qid;
92 	u16				depth;
93 	u16				vector;
94 	u16				head;
95 	u16				tail;
96 	u16				phase;
97 	u32				db;
98 
99 	size_t				qes;
100 
101 	struct nvmet_pci_epf_irq_vector	*iv;
102 	struct workqueue_struct		*iod_wq;
103 	struct delayed_work		work;
104 	spinlock_t			lock;
105 	struct list_head		list;
106 };
107 
108 /*
109  * PCI Root Complex (RC) address data segment for mapping an admin or
110  * I/O command buffer @buf of @length bytes to the PCI address @pci_addr.
111  */
112 struct nvmet_pci_epf_segment {
113 	void				*buf;
114 	u64				pci_addr;
115 	u32				length;
116 };
117 
118 /*
119  * Command descriptors.
120  */
121 struct nvmet_pci_epf_iod {
122 	struct list_head		link;
123 
124 	struct nvmet_req		req;
125 	struct nvme_command		cmd;
126 	struct nvme_completion		cqe;
127 	unsigned int			status;
128 
129 	struct nvmet_pci_epf_ctrl	*ctrl;
130 
131 	struct nvmet_pci_epf_queue	*sq;
132 	struct nvmet_pci_epf_queue	*cq;
133 
134 	/* Data transfer size and direction for the command. */
135 	size_t				data_len;
136 	enum dma_data_direction		dma_dir;
137 
138 	/*
139 	 * PCI Root Complex (RC) address data segments: if nr_data_segs is 1, we
140 	 * use only @data_seg. Otherwise, the array of segments @data_segs is
141 	 * allocated to manage multiple PCI address data segments. @data_sgl and
142 	 * @data_sgt are used to setup the command request for execution by the
143 	 * target core.
144 	 */
145 	unsigned int			nr_data_segs;
146 	struct nvmet_pci_epf_segment	data_seg;
147 	struct nvmet_pci_epf_segment	*data_segs;
148 	struct scatterlist		data_sgl;
149 	struct sg_table			data_sgt;
150 
151 	struct work_struct		work;
152 	struct completion		done;
153 };
154 
155 /*
156  * PCI target controller private data.
157  */
158 struct nvmet_pci_epf_ctrl {
159 	struct nvmet_pci_epf		*nvme_epf;
160 	struct nvmet_port		*port;
161 	struct nvmet_ctrl		*tctrl;
162 	struct device			*dev;
163 
164 	unsigned int			nr_queues;
165 	struct nvmet_pci_epf_queue	*sq;
166 	struct nvmet_pci_epf_queue	*cq;
167 	unsigned int			sq_ab;
168 
169 	mempool_t			iod_pool;
170 	void				*bar;
171 	u64				cap;
172 	u32				cc;
173 	u32				csts;
174 
175 	size_t				io_sqes;
176 	size_t				io_cqes;
177 
178 	size_t				mps_shift;
179 	size_t				mps;
180 	size_t				mps_mask;
181 
182 	unsigned int			mdts;
183 
184 	struct delayed_work		poll_cc;
185 	struct delayed_work		poll_sqs;
186 
187 	struct mutex			irq_lock;
188 	struct nvmet_pci_epf_irq_vector	*irq_vectors;
189 	unsigned int			irq_vector_threshold;
190 
191 	bool				link_up;
192 	bool				enabled;
193 };
194 
195 /*
196  * PCI EPF driver private data.
197  */
198 struct nvmet_pci_epf {
199 	struct pci_epf			*epf;
200 
201 	const struct pci_epc_features	*epc_features;
202 
203 	void				*reg_bar;
204 	size_t				msix_table_offset;
205 
206 	unsigned int			irq_type;
207 	unsigned int			nr_vectors;
208 
209 	struct nvmet_pci_epf_ctrl	ctrl;
210 
211 	bool				dma_enabled;
212 	struct dma_chan			*dma_tx_chan;
213 	struct dma_chan			*dma_rx_chan;
214 
215 	struct mutex			mmio_lock;
216 
217 	/* PCI endpoint function configfs attributes. */
218 	struct config_group		group;
219 	__le16				portid;
220 	char				subsysnqn[NVMF_NQN_SIZE];
221 	unsigned int			mdts_kb;
222 };
223 
224 static inline u32 nvmet_pci_epf_bar_read32(struct nvmet_pci_epf_ctrl *ctrl,
225 					   u32 off)
226 {
227 	__le32 *bar_reg = ctrl->bar + off;
228 
229 	return le32_to_cpu(READ_ONCE(*bar_reg));
230 }
231 
232 static inline void nvmet_pci_epf_bar_write32(struct nvmet_pci_epf_ctrl *ctrl,
233 					     u32 off, u32 val)
234 {
235 	__le32 *bar_reg = ctrl->bar + off;
236 
237 	WRITE_ONCE(*bar_reg, cpu_to_le32(val));
238 }
239 
240 static inline u64 nvmet_pci_epf_bar_read64(struct nvmet_pci_epf_ctrl *ctrl,
241 					   u32 off)
242 {
243 	return (u64)nvmet_pci_epf_bar_read32(ctrl, off) |
244 		((u64)nvmet_pci_epf_bar_read32(ctrl, off + 4) << 32);
245 }
246 
247 static inline void nvmet_pci_epf_bar_write64(struct nvmet_pci_epf_ctrl *ctrl,
248 					     u32 off, u64 val)
249 {
250 	nvmet_pci_epf_bar_write32(ctrl, off, val & 0xFFFFFFFF);
251 	nvmet_pci_epf_bar_write32(ctrl, off + 4, (val >> 32) & 0xFFFFFFFF);
252 }
253 
254 static inline int nvmet_pci_epf_mem_map(struct nvmet_pci_epf *nvme_epf,
255 		u64 pci_addr, size_t size, struct pci_epc_map *map)
256 {
257 	struct pci_epf *epf = nvme_epf->epf;
258 
259 	return pci_epc_mem_map(epf->epc, epf->func_no, epf->vfunc_no,
260 			       pci_addr, size, map);
261 }
262 
263 static inline void nvmet_pci_epf_mem_unmap(struct nvmet_pci_epf *nvme_epf,
264 					   struct pci_epc_map *map)
265 {
266 	struct pci_epf *epf = nvme_epf->epf;
267 
268 	pci_epc_mem_unmap(epf->epc, epf->func_no, epf->vfunc_no, map);
269 }
270 
271 struct nvmet_pci_epf_dma_filter {
272 	struct device *dev;
273 	u32 dma_mask;
274 };
275 
276 static bool nvmet_pci_epf_dma_filter(struct dma_chan *chan, void *arg)
277 {
278 	struct nvmet_pci_epf_dma_filter *filter = arg;
279 	struct dma_slave_caps caps;
280 
281 	memset(&caps, 0, sizeof(caps));
282 	dma_get_slave_caps(chan, &caps);
283 
284 	return chan->device->dev == filter->dev &&
285 		(filter->dma_mask & caps.directions);
286 }
287 
288 static void nvmet_pci_epf_init_dma(struct nvmet_pci_epf *nvme_epf)
289 {
290 	struct pci_epf *epf = nvme_epf->epf;
291 	struct device *dev = &epf->dev;
292 	struct nvmet_pci_epf_dma_filter filter;
293 	struct dma_chan *chan;
294 	dma_cap_mask_t mask;
295 
296 	dma_cap_zero(mask);
297 	dma_cap_set(DMA_SLAVE, mask);
298 
299 	filter.dev = epf->epc->dev.parent;
300 	filter.dma_mask = BIT(DMA_DEV_TO_MEM);
301 
302 	chan = dma_request_channel(mask, nvmet_pci_epf_dma_filter, &filter);
303 	if (!chan)
304 		goto out_dma_no_rx;
305 
306 	nvme_epf->dma_rx_chan = chan;
307 
308 	filter.dma_mask = BIT(DMA_MEM_TO_DEV);
309 	chan = dma_request_channel(mask, nvmet_pci_epf_dma_filter, &filter);
310 	if (!chan)
311 		goto out_dma_no_tx;
312 
313 	nvme_epf->dma_tx_chan = chan;
314 
315 	nvme_epf->dma_enabled = true;
316 
317 	dev_dbg(dev, "Using DMA RX channel %s, maximum segment size %u B\n",
318 		dma_chan_name(nvme_epf->dma_rx_chan),
319 		dma_get_max_seg_size(dmaengine_get_dma_device(nvme_epf->
320 							      dma_rx_chan)));
321 
322 	dev_dbg(dev, "Using DMA TX channel %s, maximum segment size %u B\n",
323 		dma_chan_name(nvme_epf->dma_tx_chan),
324 		dma_get_max_seg_size(dmaengine_get_dma_device(nvme_epf->
325 							      dma_tx_chan)));
326 
327 	return;
328 
329 out_dma_no_tx:
330 	dma_release_channel(nvme_epf->dma_rx_chan);
331 	nvme_epf->dma_rx_chan = NULL;
332 
333 out_dma_no_rx:
334 	nvme_epf->dma_enabled = false;
335 
336 	dev_info(&epf->dev, "DMA not supported, falling back to MMIO\n");
337 }
338 
339 static void nvmet_pci_epf_deinit_dma(struct nvmet_pci_epf *nvme_epf)
340 {
341 	if (!nvme_epf->dma_enabled)
342 		return;
343 
344 	dma_release_channel(nvme_epf->dma_tx_chan);
345 	nvme_epf->dma_tx_chan = NULL;
346 	dma_release_channel(nvme_epf->dma_rx_chan);
347 	nvme_epf->dma_rx_chan = NULL;
348 	nvme_epf->dma_enabled = false;
349 }
350 
351 static int nvmet_pci_epf_dma_transfer(struct nvmet_pci_epf *nvme_epf,
352 		struct nvmet_pci_epf_segment *seg, enum dma_data_direction dir)
353 {
354 	struct pci_epf *epf = nvme_epf->epf;
355 	struct dma_async_tx_descriptor *desc;
356 	struct dma_slave_config sconf = {};
357 	struct device *dev = &epf->dev;
358 	struct device *dma_dev;
359 	struct dma_chan *chan;
360 	dma_cookie_t cookie;
361 	dma_addr_t dma_addr;
362 	int ret;
363 
364 	switch (dir) {
365 	case DMA_FROM_DEVICE:
366 		chan = nvme_epf->dma_rx_chan;
367 		sconf.direction = DMA_DEV_TO_MEM;
368 		sconf.src_addr = seg->pci_addr;
369 		break;
370 	case DMA_TO_DEVICE:
371 		chan = nvme_epf->dma_tx_chan;
372 		sconf.direction = DMA_MEM_TO_DEV;
373 		sconf.dst_addr = seg->pci_addr;
374 		break;
375 	default:
376 		return -EINVAL;
377 	}
378 
379 	dma_dev = dmaengine_get_dma_device(chan);
380 	dma_addr = dma_map_single(dma_dev, seg->buf, seg->length, dir);
381 	ret = dma_mapping_error(dma_dev, dma_addr);
382 	if (ret)
383 		return ret;
384 
385 	desc = dmaengine_prep_config_single_safe(chan, dma_addr, seg->length,
386 						 sconf.direction,
387 						 DMA_CTRL_ACK, &sconf);
388 	if (!desc) {
389 		dev_err(dev, "Failed to prepare DMA\n");
390 		ret = -EIO;
391 		goto unmap;
392 	}
393 
394 	cookie = dmaengine_submit(desc);
395 	ret = dma_submit_error(cookie);
396 	if (ret) {
397 		dev_err(dev, "Failed to do DMA submit (err=%d)\n", ret);
398 		goto unmap;
399 	}
400 
401 	if (dma_sync_wait(chan, cookie) != DMA_COMPLETE) {
402 		dev_err(dev, "DMA transfer failed\n");
403 		ret = -EIO;
404 		dmaengine_terminate_sync(chan);
405 	}
406 
407 unmap:
408 	dma_unmap_single(dma_dev, dma_addr, seg->length, dir);
409 
410 	return ret;
411 }
412 
413 static int nvmet_pci_epf_mmio_transfer(struct nvmet_pci_epf *nvme_epf,
414 		struct nvmet_pci_epf_segment *seg, enum dma_data_direction dir)
415 {
416 	u64 pci_addr = seg->pci_addr;
417 	u32 length = seg->length;
418 	void *buf = seg->buf;
419 	struct pci_epc_map map;
420 	int ret = -EINVAL;
421 
422 	/*
423 	 * Note: MMIO transfers do not need serialization but this is a
424 	 * simple way to avoid using too many mapping windows.
425 	 */
426 	mutex_lock(&nvme_epf->mmio_lock);
427 
428 	while (length) {
429 		ret = nvmet_pci_epf_mem_map(nvme_epf, pci_addr, length, &map);
430 		if (ret)
431 			break;
432 
433 		switch (dir) {
434 		case DMA_FROM_DEVICE:
435 			memcpy_fromio(buf, map.virt_addr, map.pci_size);
436 			break;
437 		case DMA_TO_DEVICE:
438 			memcpy_toio(map.virt_addr, buf, map.pci_size);
439 			break;
440 		default:
441 			ret = -EINVAL;
442 			goto unlock;
443 		}
444 
445 		pci_addr += map.pci_size;
446 		buf += map.pci_size;
447 		length -= map.pci_size;
448 
449 		nvmet_pci_epf_mem_unmap(nvme_epf, &map);
450 	}
451 
452 unlock:
453 	mutex_unlock(&nvme_epf->mmio_lock);
454 
455 	return ret;
456 }
457 
458 static inline int nvmet_pci_epf_transfer_seg(struct nvmet_pci_epf *nvme_epf,
459 		struct nvmet_pci_epf_segment *seg, enum dma_data_direction dir)
460 {
461 	if (nvme_epf->dma_enabled)
462 		return nvmet_pci_epf_dma_transfer(nvme_epf, seg, dir);
463 
464 	return nvmet_pci_epf_mmio_transfer(nvme_epf, seg, dir);
465 }
466 
467 static inline int nvmet_pci_epf_transfer(struct nvmet_pci_epf_ctrl *ctrl,
468 					 void *buf, u64 pci_addr, u32 length,
469 					 enum dma_data_direction dir)
470 {
471 	struct nvmet_pci_epf_segment seg = {
472 		.buf = buf,
473 		.pci_addr = pci_addr,
474 		.length = length,
475 	};
476 
477 	return nvmet_pci_epf_transfer_seg(ctrl->nvme_epf, &seg, dir);
478 }
479 
480 static int nvmet_pci_epf_alloc_irq_vectors(struct nvmet_pci_epf_ctrl *ctrl)
481 {
482 	ctrl->irq_vectors = kzalloc_objs(struct nvmet_pci_epf_irq_vector,
483 					 ctrl->nr_queues);
484 	if (!ctrl->irq_vectors)
485 		return -ENOMEM;
486 
487 	mutex_init(&ctrl->irq_lock);
488 
489 	return 0;
490 }
491 
492 static void nvmet_pci_epf_free_irq_vectors(struct nvmet_pci_epf_ctrl *ctrl)
493 {
494 	if (ctrl->irq_vectors) {
495 		mutex_destroy(&ctrl->irq_lock);
496 		kfree(ctrl->irq_vectors);
497 		ctrl->irq_vectors = NULL;
498 	}
499 }
500 
501 static struct nvmet_pci_epf_irq_vector *
502 nvmet_pci_epf_find_irq_vector(struct nvmet_pci_epf_ctrl *ctrl, u16 vector)
503 {
504 	struct nvmet_pci_epf_irq_vector *iv;
505 	int i;
506 
507 	lockdep_assert_held(&ctrl->irq_lock);
508 
509 	for (i = 0; i < ctrl->nr_queues; i++) {
510 		iv = &ctrl->irq_vectors[i];
511 		if (iv->ref && iv->vector == vector)
512 			return iv;
513 	}
514 
515 	return NULL;
516 }
517 
518 static struct nvmet_pci_epf_irq_vector *
519 nvmet_pci_epf_add_irq_vector(struct nvmet_pci_epf_ctrl *ctrl, u16 vector)
520 {
521 	struct nvmet_pci_epf_irq_vector *iv;
522 	int i;
523 
524 	mutex_lock(&ctrl->irq_lock);
525 
526 	iv = nvmet_pci_epf_find_irq_vector(ctrl, vector);
527 	if (iv) {
528 		iv->ref++;
529 		goto unlock;
530 	}
531 
532 	for (i = 0; i < ctrl->nr_queues; i++) {
533 		iv = &ctrl->irq_vectors[i];
534 		if (!iv->ref)
535 			break;
536 	}
537 
538 	if (WARN_ON_ONCE(!iv))
539 		goto unlock;
540 
541 	iv->ref = 1;
542 	iv->vector = vector;
543 	iv->nr_irqs = 0;
544 
545 unlock:
546 	mutex_unlock(&ctrl->irq_lock);
547 
548 	return iv;
549 }
550 
551 static void nvmet_pci_epf_remove_irq_vector(struct nvmet_pci_epf_ctrl *ctrl,
552 					    u16 vector)
553 {
554 	struct nvmet_pci_epf_irq_vector *iv;
555 
556 	mutex_lock(&ctrl->irq_lock);
557 
558 	iv = nvmet_pci_epf_find_irq_vector(ctrl, vector);
559 	if (iv) {
560 		iv->ref--;
561 		if (!iv->ref) {
562 			iv->vector = 0;
563 			iv->nr_irqs = 0;
564 		}
565 	}
566 
567 	mutex_unlock(&ctrl->irq_lock);
568 }
569 
570 static bool nvmet_pci_epf_should_raise_irq(struct nvmet_pci_epf_ctrl *ctrl,
571 		struct nvmet_pci_epf_queue *cq, bool force)
572 {
573 	struct nvmet_pci_epf_irq_vector *iv = cq->iv;
574 	bool ret;
575 
576 	/* IRQ coalescing for the admin queue is not allowed. */
577 	if (!cq->qid)
578 		return true;
579 
580 	if (iv->cd)
581 		return true;
582 
583 	if (force) {
584 		ret = iv->nr_irqs > 0;
585 	} else {
586 		iv->nr_irqs++;
587 		ret = iv->nr_irqs >= ctrl->irq_vector_threshold;
588 	}
589 	if (ret)
590 		iv->nr_irqs = 0;
591 
592 	return ret;
593 }
594 
595 static void nvmet_pci_epf_raise_irq(struct nvmet_pci_epf_ctrl *ctrl,
596 		struct nvmet_pci_epf_queue *cq, bool force)
597 {
598 	struct nvmet_pci_epf *nvme_epf = ctrl->nvme_epf;
599 	struct pci_epf *epf = nvme_epf->epf;
600 	int ret = 0;
601 
602 	if (!test_bit(NVMET_PCI_EPF_Q_LIVE, &cq->flags) ||
603 	    !test_bit(NVMET_PCI_EPF_Q_IRQ_ENABLED, &cq->flags))
604 		return;
605 
606 	mutex_lock(&ctrl->irq_lock);
607 
608 	if (!nvmet_pci_epf_should_raise_irq(ctrl, cq, force))
609 		goto unlock;
610 
611 	switch (nvme_epf->irq_type) {
612 	case PCI_IRQ_MSIX:
613 	case PCI_IRQ_MSI:
614 		/*
615 		 * If we fail to raise an MSI or MSI-X interrupt, it is likely
616 		 * because the host is using legacy INTX IRQs (e.g. BIOS,
617 		 * grub), but we can fallback to the INTX type only if the
618 		 * endpoint controller supports this type.
619 		 */
620 		ret = pci_epc_raise_irq(epf->epc, epf->func_no, epf->vfunc_no,
621 					nvme_epf->irq_type, cq->vector + 1);
622 		if (!ret || !nvme_epf->epc_features->intx_capable)
623 			break;
624 		fallthrough;
625 	case PCI_IRQ_INTX:
626 		ret = pci_epc_raise_irq(epf->epc, epf->func_no, epf->vfunc_no,
627 					PCI_IRQ_INTX, 0);
628 		break;
629 	default:
630 		WARN_ON_ONCE(1);
631 		ret = -EINVAL;
632 		break;
633 	}
634 
635 	if (ret)
636 		dev_err_ratelimited(ctrl->dev,
637 				    "CQ[%u]: Failed to raise IRQ (err=%d)\n",
638 				    cq->qid, ret);
639 
640 unlock:
641 	mutex_unlock(&ctrl->irq_lock);
642 }
643 
644 static inline const char *nvmet_pci_epf_iod_name(struct nvmet_pci_epf_iod *iod)
645 {
646 	return nvme_opcode_str(iod->sq->qid, iod->cmd.common.opcode);
647 }
648 
649 static void nvmet_pci_epf_exec_iod_work(struct work_struct *work);
650 
651 static struct nvmet_pci_epf_iod *
652 nvmet_pci_epf_alloc_iod(struct nvmet_pci_epf_queue *sq)
653 {
654 	struct nvmet_pci_epf_ctrl *ctrl = sq->ctrl;
655 	struct nvmet_pci_epf_iod *iod;
656 
657 	iod = mempool_alloc(&ctrl->iod_pool, GFP_KERNEL);
658 	if (unlikely(!iod))
659 		return NULL;
660 
661 	memset(iod, 0, sizeof(*iod));
662 	iod->req.cmd = &iod->cmd;
663 	iod->req.cqe = &iod->cqe;
664 	iod->req.port = ctrl->port;
665 	iod->ctrl = ctrl;
666 	iod->sq = sq;
667 	iod->cq = &ctrl->cq[sq->qid];
668 	INIT_LIST_HEAD(&iod->link);
669 	iod->dma_dir = DMA_NONE;
670 	INIT_WORK(&iod->work, nvmet_pci_epf_exec_iod_work);
671 	init_completion(&iod->done);
672 
673 	return iod;
674 }
675 
676 /*
677  * Allocate or grow a command table of PCI segments.
678  */
679 static int nvmet_pci_epf_alloc_iod_data_segs(struct nvmet_pci_epf_iod *iod,
680 					     int nsegs)
681 {
682 	struct nvmet_pci_epf_segment *segs;
683 	int nr_segs = iod->nr_data_segs + nsegs;
684 
685 	segs = krealloc(iod->data_segs,
686 			nr_segs * sizeof(struct nvmet_pci_epf_segment),
687 			GFP_KERNEL | __GFP_ZERO);
688 	if (!segs)
689 		return -ENOMEM;
690 
691 	iod->nr_data_segs = nr_segs;
692 	iod->data_segs = segs;
693 
694 	return 0;
695 }
696 
697 static void nvmet_pci_epf_free_iod(struct nvmet_pci_epf_iod *iod)
698 {
699 	int i;
700 
701 	if (iod->data_segs) {
702 		for (i = 0; i < iod->nr_data_segs; i++)
703 			kfree(iod->data_segs[i].buf);
704 		if (iod->data_segs != &iod->data_seg)
705 			kfree(iod->data_segs);
706 	}
707 	if (iod->data_sgt.nents > 1)
708 		sg_free_table(&iod->data_sgt);
709 	mempool_free(iod, &iod->ctrl->iod_pool);
710 }
711 
712 static int nvmet_pci_epf_transfer_iod_data(struct nvmet_pci_epf_iod *iod)
713 {
714 	struct nvmet_pci_epf *nvme_epf = iod->ctrl->nvme_epf;
715 	struct nvmet_pci_epf_segment *seg = &iod->data_segs[0];
716 	int i, ret;
717 
718 	/* Split the data transfer according to the PCI segments. */
719 	for (i = 0; i < iod->nr_data_segs; i++, seg++) {
720 		ret = nvmet_pci_epf_transfer_seg(nvme_epf, seg, iod->dma_dir);
721 		if (ret) {
722 			iod->status = NVME_SC_DATA_XFER_ERROR | NVME_STATUS_DNR;
723 			return ret;
724 		}
725 	}
726 
727 	return 0;
728 }
729 
730 static inline u32 nvmet_pci_epf_prp_ofst(struct nvmet_pci_epf_ctrl *ctrl,
731 					 u64 prp)
732 {
733 	return prp & ctrl->mps_mask;
734 }
735 
736 static inline size_t nvmet_pci_epf_prp_size(struct nvmet_pci_epf_ctrl *ctrl,
737 					    u64 prp)
738 {
739 	return ctrl->mps - nvmet_pci_epf_prp_ofst(ctrl, prp);
740 }
741 
742 /*
743  * Transfer a PRP list from the host and return the number of prps.
744  */
745 static int nvmet_pci_epf_get_prp_list(struct nvmet_pci_epf_ctrl *ctrl, u64 prp,
746 				      size_t xfer_len, __le64 *prps)
747 {
748 	size_t nr_prps = (xfer_len + ctrl->mps_mask) >> ctrl->mps_shift;
749 	u32 length;
750 	int ret;
751 
752 	/*
753 	 * Compute the number of PRPs required for the number of bytes to
754 	 * transfer (xfer_len). If this number overflows the memory page size
755 	 * with the PRP list pointer specified, only return the space available
756 	 * in the memory page, the last PRP in there will be a PRP list pointer
757 	 * to the remaining PRPs.
758 	 */
759 	length = min(nvmet_pci_epf_prp_size(ctrl, prp), nr_prps << 3);
760 	ret = nvmet_pci_epf_transfer(ctrl, prps, prp, length, DMA_FROM_DEVICE);
761 	if (ret)
762 		return ret;
763 
764 	return length >> 3;
765 }
766 
767 static int nvmet_pci_epf_iod_parse_prp_list(struct nvmet_pci_epf_ctrl *ctrl,
768 					    struct nvmet_pci_epf_iod *iod)
769 {
770 	struct nvme_command *cmd = &iod->cmd;
771 	struct nvmet_pci_epf_segment *seg;
772 	size_t size = 0, ofst, prp_size, xfer_len;
773 	size_t transfer_len = iod->data_len;
774 	int nr_segs, nr_prps = 0;
775 	u64 pci_addr, prp;
776 	int i = 0, ret;
777 	__le64 *prps;
778 
779 	prps = kzalloc(ctrl->mps, GFP_KERNEL);
780 	if (!prps)
781 		goto err_internal;
782 
783 	/*
784 	 * Allocate PCI segments for the command: this considers the worst case
785 	 * scenario where all prps are discontiguous, so get as many segments
786 	 * as we can have prps. In practice, most of the time, we will have
787 	 * far less PCI segments than prps.
788 	 */
789 	prp = le64_to_cpu(cmd->common.dptr.prp1);
790 	if (!prp)
791 		goto err_invalid_field;
792 
793 	ofst = nvmet_pci_epf_prp_ofst(ctrl, prp);
794 	nr_segs = (transfer_len + ofst + ctrl->mps - 1) >> ctrl->mps_shift;
795 
796 	ret = nvmet_pci_epf_alloc_iod_data_segs(iod, nr_segs);
797 	if (ret)
798 		goto err_internal;
799 
800 	/* Set the first segment using prp1. */
801 	seg = &iod->data_segs[0];
802 	seg->pci_addr = prp;
803 	seg->length = nvmet_pci_epf_prp_size(ctrl, prp);
804 
805 	size = seg->length;
806 	pci_addr = prp + size;
807 	nr_segs = 1;
808 
809 	/*
810 	 * Now build the PCI address segments using the PRP lists, starting
811 	 * from prp2.
812 	 */
813 	prp = le64_to_cpu(cmd->common.dptr.prp2);
814 	if (!prp)
815 		goto err_invalid_field;
816 
817 	while (size < transfer_len) {
818 		xfer_len = transfer_len - size;
819 
820 		if (!nr_prps) {
821 			nr_prps = nvmet_pci_epf_get_prp_list(ctrl, prp,
822 							     xfer_len, prps);
823 			if (nr_prps < 0)
824 				goto err_internal;
825 
826 			i = 0;
827 			ofst = 0;
828 		}
829 
830 		/* Current entry */
831 		prp = le64_to_cpu(prps[i]);
832 		if (!prp)
833 			goto err_invalid_field;
834 
835 		/* Did we reach the last PRP entry of the list? */
836 		if (xfer_len > ctrl->mps && i == nr_prps - 1) {
837 			/* We need more PRPs: PRP is a list pointer. */
838 			nr_prps = 0;
839 			continue;
840 		}
841 
842 		/* Only the first PRP is allowed to have an offset. */
843 		if (nvmet_pci_epf_prp_ofst(ctrl, prp))
844 			goto err_invalid_offset;
845 
846 		if (prp != pci_addr) {
847 			/* Discontiguous prp: new segment. */
848 			nr_segs++;
849 			if (WARN_ON_ONCE(nr_segs > iod->nr_data_segs))
850 				goto err_internal;
851 
852 			seg++;
853 			seg->pci_addr = prp;
854 			seg->length = 0;
855 			pci_addr = prp;
856 		}
857 
858 		prp_size = min_t(size_t, ctrl->mps, xfer_len);
859 		seg->length += prp_size;
860 		pci_addr += prp_size;
861 		size += prp_size;
862 
863 		i++;
864 	}
865 
866 	iod->nr_data_segs = nr_segs;
867 	ret = 0;
868 
869 	if (size != transfer_len) {
870 		dev_err(ctrl->dev,
871 			"PRPs transfer length mismatch: got %zu B, need %zu B\n",
872 			size, transfer_len);
873 		goto err_internal;
874 	}
875 
876 	kfree(prps);
877 
878 	return 0;
879 
880 err_invalid_offset:
881 	dev_err(ctrl->dev, "PRPs list invalid offset\n");
882 	iod->status = NVME_SC_PRP_INVALID_OFFSET | NVME_STATUS_DNR;
883 	goto err;
884 
885 err_invalid_field:
886 	dev_err(ctrl->dev, "PRPs list invalid field\n");
887 	iod->status = NVME_SC_INVALID_FIELD | NVME_STATUS_DNR;
888 	goto err;
889 
890 err_internal:
891 	dev_err(ctrl->dev, "PRPs list internal error\n");
892 	iod->status = NVME_SC_INTERNAL | NVME_STATUS_DNR;
893 
894 err:
895 	kfree(prps);
896 	return -EINVAL;
897 }
898 
899 static int nvmet_pci_epf_iod_parse_prp_simple(struct nvmet_pci_epf_ctrl *ctrl,
900 					      struct nvmet_pci_epf_iod *iod)
901 {
902 	struct nvme_command *cmd = &iod->cmd;
903 	size_t transfer_len = iod->data_len;
904 	int ret, nr_segs = 1;
905 	u64 prp1, prp2 = 0;
906 	size_t prp1_size;
907 
908 	prp1 = le64_to_cpu(cmd->common.dptr.prp1);
909 	prp1_size = nvmet_pci_epf_prp_size(ctrl, prp1);
910 
911 	/* For commands crossing a page boundary, we should have prp2. */
912 	if (transfer_len > prp1_size) {
913 		prp2 = le64_to_cpu(cmd->common.dptr.prp2);
914 		if (!prp2) {
915 			iod->status = NVME_SC_INVALID_FIELD | NVME_STATUS_DNR;
916 			return -EINVAL;
917 		}
918 		if (nvmet_pci_epf_prp_ofst(ctrl, prp2)) {
919 			iod->status =
920 				NVME_SC_PRP_INVALID_OFFSET | NVME_STATUS_DNR;
921 			return -EINVAL;
922 		}
923 		if (prp2 != prp1 + prp1_size)
924 			nr_segs = 2;
925 	}
926 
927 	if (nr_segs == 1) {
928 		iod->nr_data_segs = 1;
929 		iod->data_segs = &iod->data_seg;
930 		iod->data_segs[0].pci_addr = prp1;
931 		iod->data_segs[0].length = transfer_len;
932 		return 0;
933 	}
934 
935 	ret = nvmet_pci_epf_alloc_iod_data_segs(iod, nr_segs);
936 	if (ret) {
937 		iod->status = NVME_SC_INTERNAL | NVME_STATUS_DNR;
938 		return ret;
939 	}
940 
941 	iod->data_segs[0].pci_addr = prp1;
942 	iod->data_segs[0].length = prp1_size;
943 	iod->data_segs[1].pci_addr = prp2;
944 	iod->data_segs[1].length = transfer_len - prp1_size;
945 
946 	return 0;
947 }
948 
949 static int nvmet_pci_epf_iod_parse_prps(struct nvmet_pci_epf_iod *iod)
950 {
951 	struct nvmet_pci_epf_ctrl *ctrl = iod->ctrl;
952 	u64 prp1 = le64_to_cpu(iod->cmd.common.dptr.prp1);
953 	size_t ofst;
954 
955 	/* Get the PCI address segments for the command using its PRPs. */
956 	ofst = nvmet_pci_epf_prp_ofst(ctrl, prp1);
957 	if (ofst & 0x3) {
958 		iod->status = NVME_SC_PRP_INVALID_OFFSET | NVME_STATUS_DNR;
959 		return -EINVAL;
960 	}
961 
962 	if (iod->data_len + ofst <= ctrl->mps * 2)
963 		return nvmet_pci_epf_iod_parse_prp_simple(ctrl, iod);
964 
965 	return nvmet_pci_epf_iod_parse_prp_list(ctrl, iod);
966 }
967 
968 /*
969  * Transfer an SGL segment from the host and return the number of data
970  * descriptors and the next segment descriptor, if any.
971  */
972 static struct nvme_sgl_desc *
973 nvmet_pci_epf_get_sgl_segment(struct nvmet_pci_epf_ctrl *ctrl,
974 			      struct nvme_sgl_desc *desc, unsigned int *nr_sgls)
975 {
976 	struct nvme_sgl_desc *sgls;
977 	u32 length = le32_to_cpu(desc->length);
978 	int nr_descs, ret;
979 	void *buf;
980 
981 	if (length < sizeof(struct nvme_sgl_desc))
982 		return NULL;
983 
984 	buf = kmalloc(length, GFP_KERNEL);
985 	if (!buf)
986 		return NULL;
987 
988 	ret = nvmet_pci_epf_transfer(ctrl, buf, le64_to_cpu(desc->addr), length,
989 				     DMA_FROM_DEVICE);
990 	if (ret) {
991 		kfree(buf);
992 		return NULL;
993 	}
994 
995 	sgls = buf;
996 	nr_descs = length / sizeof(struct nvme_sgl_desc);
997 	if (sgls[nr_descs - 1].type == (NVME_SGL_FMT_SEG_DESC << 4) ||
998 	    sgls[nr_descs - 1].type == (NVME_SGL_FMT_LAST_SEG_DESC << 4)) {
999 		/*
1000 		 * We have another SGL segment following this one: do not count
1001 		 * it as a regular data SGL descriptor and return it to the
1002 		 * caller.
1003 		 */
1004 		*desc = sgls[nr_descs - 1];
1005 		nr_descs--;
1006 	} else {
1007 		/* We do not have another SGL segment after this one. */
1008 		desc->length = 0;
1009 	}
1010 
1011 	*nr_sgls = nr_descs;
1012 
1013 	return sgls;
1014 }
1015 
1016 static int nvmet_pci_epf_iod_parse_sgl_segments(struct nvmet_pci_epf_ctrl *ctrl,
1017 						struct nvmet_pci_epf_iod *iod)
1018 {
1019 	struct nvme_command *cmd = &iod->cmd;
1020 	struct nvme_sgl_desc seg = cmd->common.dptr.sgl;
1021 	struct nvme_sgl_desc *sgls = NULL;
1022 	int n = 0, i, nr_sgls;
1023 	int ret;
1024 
1025 	/*
1026 	 * We do not support inline data nor keyed SGLs, so we should be seeing
1027 	 * only segment descriptors.
1028 	 */
1029 	if (seg.type != (NVME_SGL_FMT_SEG_DESC << 4) &&
1030 	    seg.type != (NVME_SGL_FMT_LAST_SEG_DESC << 4)) {
1031 		iod->status = NVME_SC_SGL_INVALID_TYPE | NVME_STATUS_DNR;
1032 		return -EIO;
1033 	}
1034 
1035 	while (seg.length) {
1036 		sgls = nvmet_pci_epf_get_sgl_segment(ctrl, &seg, &nr_sgls);
1037 		if (!sgls) {
1038 			iod->status = NVME_SC_INTERNAL | NVME_STATUS_DNR;
1039 			return -EIO;
1040 		}
1041 
1042 		/* Grow the PCI segment table as needed. */
1043 		ret = nvmet_pci_epf_alloc_iod_data_segs(iod, nr_sgls);
1044 		if (ret) {
1045 			iod->status = NVME_SC_INTERNAL | NVME_STATUS_DNR;
1046 			goto out;
1047 		}
1048 
1049 		/*
1050 		 * Parse the SGL descriptors to build the PCI segment table,
1051 		 * checking the descriptor type as we go.
1052 		 */
1053 		for (i = 0; i < nr_sgls; i++) {
1054 			if (sgls[i].type != (NVME_SGL_FMT_DATA_DESC << 4)) {
1055 				iod->status = NVME_SC_SGL_INVALID_TYPE |
1056 					NVME_STATUS_DNR;
1057 				goto out;
1058 			}
1059 			iod->data_segs[n].pci_addr = le64_to_cpu(sgls[i].addr);
1060 			iod->data_segs[n].length = le32_to_cpu(sgls[i].length);
1061 			n++;
1062 		}
1063 
1064 		kfree(sgls);
1065 	}
1066 
1067  out:
1068 	if (iod->status != NVME_SC_SUCCESS) {
1069 		kfree(sgls);
1070 		return -EIO;
1071 	}
1072 
1073 	return 0;
1074 }
1075 
1076 static int nvmet_pci_epf_iod_parse_sgls(struct nvmet_pci_epf_iod *iod)
1077 {
1078 	struct nvmet_pci_epf_ctrl *ctrl = iod->ctrl;
1079 	struct nvme_sgl_desc *sgl = &iod->cmd.common.dptr.sgl;
1080 
1081 	if (sgl->type == (NVME_SGL_FMT_DATA_DESC << 4)) {
1082 		/* Single data descriptor case. */
1083 		iod->nr_data_segs = 1;
1084 		iod->data_segs = &iod->data_seg;
1085 		iod->data_seg.pci_addr = le64_to_cpu(sgl->addr);
1086 		iod->data_seg.length = le32_to_cpu(sgl->length);
1087 		return 0;
1088 	}
1089 
1090 	return nvmet_pci_epf_iod_parse_sgl_segments(ctrl, iod);
1091 }
1092 
1093 static int nvmet_pci_epf_alloc_iod_data_buf(struct nvmet_pci_epf_iod *iod)
1094 {
1095 	struct nvmet_pci_epf_ctrl *ctrl = iod->ctrl;
1096 	struct nvmet_req *req = &iod->req;
1097 	struct nvmet_pci_epf_segment *seg;
1098 	struct scatterlist *sg;
1099 	int ret, i;
1100 
1101 	if (iod->data_len > ctrl->mdts) {
1102 		iod->status = NVME_SC_INVALID_FIELD | NVME_STATUS_DNR;
1103 		return -EINVAL;
1104 	}
1105 
1106 	/*
1107 	 * Get the PCI address segments for the command data buffer using either
1108 	 * its SGLs or PRPs.
1109 	 */
1110 	if (iod->cmd.common.flags & NVME_CMD_SGL_ALL)
1111 		ret = nvmet_pci_epf_iod_parse_sgls(iod);
1112 	else
1113 		ret = nvmet_pci_epf_iod_parse_prps(iod);
1114 	if (ret)
1115 		return ret;
1116 
1117 	/* Get a command buffer using SGLs matching the PCI segments. */
1118 	if (iod->nr_data_segs == 1) {
1119 		sg_init_table(&iod->data_sgl, 1);
1120 		iod->data_sgt.sgl = &iod->data_sgl;
1121 		iod->data_sgt.nents = 1;
1122 		iod->data_sgt.orig_nents = 1;
1123 	} else {
1124 		ret = sg_alloc_table(&iod->data_sgt, iod->nr_data_segs,
1125 				     GFP_KERNEL);
1126 		if (ret)
1127 			goto err_nomem;
1128 	}
1129 
1130 	for_each_sgtable_sg(&iod->data_sgt, sg, i) {
1131 		seg = &iod->data_segs[i];
1132 		seg->buf = kmalloc(seg->length, GFP_KERNEL);
1133 		if (!seg->buf)
1134 			goto err_nomem;
1135 		sg_set_buf(sg, seg->buf, seg->length);
1136 	}
1137 
1138 	req->transfer_len = iod->data_len;
1139 	req->sg = iod->data_sgt.sgl;
1140 	req->sg_cnt = iod->data_sgt.nents;
1141 
1142 	return 0;
1143 
1144 err_nomem:
1145 	iod->status = NVME_SC_INTERNAL | NVME_STATUS_DNR;
1146 	return -ENOMEM;
1147 }
1148 
1149 static void nvmet_pci_epf_complete_iod(struct nvmet_pci_epf_iod *iod)
1150 {
1151 	struct nvmet_pci_epf_queue *cq = iod->cq;
1152 	unsigned long flags;
1153 
1154 	/* Print an error message for failed commands, except AENs. */
1155 	iod->status = le16_to_cpu(iod->cqe.status) >> 1;
1156 	if (iod->status && iod->cmd.common.opcode != nvme_admin_async_event)
1157 		dev_err(iod->ctrl->dev,
1158 			"CQ[%d]: Command %s (0x%x) status 0x%0x\n",
1159 			iod->sq->qid, nvmet_pci_epf_iod_name(iod),
1160 			iod->cmd.common.opcode, iod->status);
1161 
1162 	/*
1163 	 * Add the command to the list of completed commands and schedule the
1164 	 * CQ work.
1165 	 */
1166 	spin_lock_irqsave(&cq->lock, flags);
1167 	list_add_tail(&iod->link, &cq->list);
1168 	queue_delayed_work(system_highpri_wq, &cq->work, 0);
1169 	spin_unlock_irqrestore(&cq->lock, flags);
1170 }
1171 
1172 static void nvmet_pci_epf_drain_queue(struct nvmet_pci_epf_queue *queue)
1173 {
1174 	struct nvmet_pci_epf_iod *iod;
1175 	unsigned long flags;
1176 
1177 	spin_lock_irqsave(&queue->lock, flags);
1178 	while (!list_empty(&queue->list)) {
1179 		iod = list_first_entry(&queue->list, struct nvmet_pci_epf_iod,
1180 				       link);
1181 		list_del_init(&iod->link);
1182 		nvmet_pci_epf_free_iod(iod);
1183 	}
1184 	spin_unlock_irqrestore(&queue->lock, flags);
1185 }
1186 
1187 static int nvmet_pci_epf_add_port(struct nvmet_port *port)
1188 {
1189 	mutex_lock(&nvmet_pci_epf_ports_mutex);
1190 	list_add_tail(&port->entry, &nvmet_pci_epf_ports);
1191 	mutex_unlock(&nvmet_pci_epf_ports_mutex);
1192 	return 0;
1193 }
1194 
1195 static void nvmet_pci_epf_remove_port(struct nvmet_port *port)
1196 {
1197 	mutex_lock(&nvmet_pci_epf_ports_mutex);
1198 	list_del_init(&port->entry);
1199 	mutex_unlock(&nvmet_pci_epf_ports_mutex);
1200 }
1201 
1202 static struct nvmet_port *
1203 nvmet_pci_epf_find_port(struct nvmet_pci_epf_ctrl *ctrl, __le16 portid)
1204 {
1205 	struct nvmet_port *p, *port = NULL;
1206 
1207 	mutex_lock(&nvmet_pci_epf_ports_mutex);
1208 	list_for_each_entry(p, &nvmet_pci_epf_ports, entry) {
1209 		if (p->disc_addr.portid == portid) {
1210 			port = p;
1211 			break;
1212 		}
1213 	}
1214 	mutex_unlock(&nvmet_pci_epf_ports_mutex);
1215 
1216 	return port;
1217 }
1218 
1219 static void nvmet_pci_epf_queue_response(struct nvmet_req *req)
1220 {
1221 	struct nvmet_pci_epf_iod *iod =
1222 		container_of(req, struct nvmet_pci_epf_iod, req);
1223 
1224 	iod->status = le16_to_cpu(req->cqe->status) >> 1;
1225 
1226 	/*
1227 	 * If the command failed or we have no data to transfer, complete the
1228 	 * command immediately.
1229 	 */
1230 	if (iod->status || !iod->data_len || iod->dma_dir != DMA_TO_DEVICE) {
1231 		nvmet_pci_epf_complete_iod(iod);
1232 		return;
1233 	}
1234 
1235 	complete(&iod->done);
1236 }
1237 
1238 static u8 nvmet_pci_epf_get_mdts(const struct nvmet_ctrl *tctrl)
1239 {
1240 	struct nvmet_pci_epf_ctrl *ctrl = tctrl->drvdata;
1241 	int page_shift = NVME_CAP_MPSMIN(tctrl->cap) + 12;
1242 
1243 	return ilog2(ctrl->mdts) - page_shift;
1244 }
1245 
1246 static u16 nvmet_pci_epf_create_cq(struct nvmet_ctrl *tctrl,
1247 		u16 cqid, u16 flags, u16 qsize, u64 pci_addr, u16 vector)
1248 {
1249 	struct nvmet_pci_epf_ctrl *ctrl = tctrl->drvdata;
1250 	struct nvmet_pci_epf_queue *cq = &ctrl->cq[cqid];
1251 	u16 status;
1252 	int ret;
1253 
1254 	if (test_bit(NVMET_PCI_EPF_Q_LIVE, &cq->flags))
1255 		return NVME_SC_QID_INVALID | NVME_STATUS_DNR;
1256 
1257 	if (!(flags & NVME_QUEUE_PHYS_CONTIG))
1258 		return NVME_SC_INVALID_QUEUE | NVME_STATUS_DNR;
1259 
1260 	cq->pci_addr = pci_addr;
1261 	cq->qid = cqid;
1262 	cq->depth = qsize + 1;
1263 	cq->vector = vector;
1264 	cq->head = 0;
1265 	cq->tail = 0;
1266 	cq->phase = 1;
1267 	cq->db = NVME_REG_DBS + (((cqid * 2) + 1) * sizeof(u32));
1268 	nvmet_pci_epf_bar_write32(ctrl, cq->db, 0);
1269 
1270 	if (!cqid)
1271 		cq->qes = sizeof(struct nvme_completion);
1272 	else
1273 		cq->qes = ctrl->io_cqes;
1274 	cq->pci_size = cq->qes * cq->depth;
1275 
1276 	if (flags & NVME_CQ_IRQ_ENABLED) {
1277 		cq->iv = nvmet_pci_epf_add_irq_vector(ctrl, vector);
1278 		if (!cq->iv)
1279 			return NVME_SC_INTERNAL | NVME_STATUS_DNR;
1280 		set_bit(NVMET_PCI_EPF_Q_IRQ_ENABLED, &cq->flags);
1281 	}
1282 
1283 	status = nvmet_cq_create(tctrl, &cq->nvme_cq, cqid, cq->depth);
1284 	if (status != NVME_SC_SUCCESS)
1285 		goto err;
1286 
1287 	/*
1288 	 * Map the CQ PCI address space and since PCI endpoint controllers may
1289 	 * return a partial mapping, check that the mapping is large enough.
1290 	 */
1291 	ret = nvmet_pci_epf_mem_map(ctrl->nvme_epf, cq->pci_addr, cq->pci_size,
1292 				    &cq->pci_map);
1293 	if (ret) {
1294 		dev_err(ctrl->dev, "Failed to map CQ %u (err=%d)\n",
1295 			cq->qid, ret);
1296 		goto err_internal;
1297 	}
1298 
1299 	if (cq->pci_map.pci_size < cq->pci_size) {
1300 		dev_err(ctrl->dev, "Invalid partial mapping of queue %u\n",
1301 			cq->qid);
1302 		goto err_unmap_queue;
1303 	}
1304 
1305 	set_bit(NVMET_PCI_EPF_Q_LIVE, &cq->flags);
1306 
1307 	if (test_bit(NVMET_PCI_EPF_Q_IRQ_ENABLED, &cq->flags))
1308 		dev_dbg(ctrl->dev,
1309 			"CQ[%u]: %u entries of %zu B, IRQ vector %u\n",
1310 			cqid, qsize, cq->qes, cq->vector);
1311 	else
1312 		dev_dbg(ctrl->dev,
1313 			"CQ[%u]: %u entries of %zu B, IRQ disabled\n",
1314 			cqid, qsize, cq->qes);
1315 
1316 	return NVME_SC_SUCCESS;
1317 
1318 err_unmap_queue:
1319 	nvmet_pci_epf_mem_unmap(ctrl->nvme_epf, &cq->pci_map);
1320 err_internal:
1321 	status = NVME_SC_INTERNAL | NVME_STATUS_DNR;
1322 	nvmet_cq_put(&cq->nvme_cq);
1323 err:
1324 	if (test_and_clear_bit(NVMET_PCI_EPF_Q_IRQ_ENABLED, &cq->flags))
1325 		nvmet_pci_epf_remove_irq_vector(ctrl, cq->vector);
1326 	return status;
1327 }
1328 
1329 static u16 nvmet_pci_epf_delete_cq(struct nvmet_ctrl *tctrl, u16 cqid)
1330 {
1331 	struct nvmet_pci_epf_ctrl *ctrl = tctrl->drvdata;
1332 	struct nvmet_pci_epf_queue *cq = &ctrl->cq[cqid];
1333 
1334 	if (!test_and_clear_bit(NVMET_PCI_EPF_Q_LIVE, &cq->flags))
1335 		return NVME_SC_QID_INVALID | NVME_STATUS_DNR;
1336 
1337 	cancel_delayed_work_sync(&cq->work);
1338 	nvmet_pci_epf_drain_queue(cq);
1339 	if (test_and_clear_bit(NVMET_PCI_EPF_Q_IRQ_ENABLED, &cq->flags))
1340 		nvmet_pci_epf_remove_irq_vector(ctrl, cq->vector);
1341 	nvmet_pci_epf_mem_unmap(ctrl->nvme_epf, &cq->pci_map);
1342 	nvmet_cq_put(&cq->nvme_cq);
1343 
1344 	return NVME_SC_SUCCESS;
1345 }
1346 
1347 static u16 nvmet_pci_epf_create_sq(struct nvmet_ctrl *tctrl,
1348 		u16 sqid, u16 cqid, u16 flags, u16 qsize, u64 pci_addr)
1349 {
1350 	struct nvmet_pci_epf_ctrl *ctrl = tctrl->drvdata;
1351 	struct nvmet_pci_epf_queue *sq = &ctrl->sq[sqid];
1352 	struct nvmet_pci_epf_queue *cq = &ctrl->cq[cqid];
1353 	u16 status;
1354 
1355 	if (test_bit(NVMET_PCI_EPF_Q_LIVE, &sq->flags))
1356 		return NVME_SC_QID_INVALID | NVME_STATUS_DNR;
1357 
1358 	if (!(flags & NVME_QUEUE_PHYS_CONTIG))
1359 		return NVME_SC_INVALID_QUEUE | NVME_STATUS_DNR;
1360 
1361 	sq->pci_addr = pci_addr;
1362 	sq->qid = sqid;
1363 	sq->depth = qsize + 1;
1364 	sq->head = 0;
1365 	sq->tail = 0;
1366 	sq->phase = 0;
1367 	sq->db = NVME_REG_DBS + (sqid * 2 * sizeof(u32));
1368 	nvmet_pci_epf_bar_write32(ctrl, sq->db, 0);
1369 	if (!sqid)
1370 		sq->qes = 1UL << NVME_ADM_SQES;
1371 	else
1372 		sq->qes = ctrl->io_sqes;
1373 	sq->pci_size = sq->qes * sq->depth;
1374 
1375 	status = nvmet_sq_create(tctrl, &sq->nvme_sq, &cq->nvme_cq, sqid,
1376 			sq->depth);
1377 	if (status != NVME_SC_SUCCESS)
1378 		return status;
1379 
1380 	sq->iod_wq = alloc_workqueue("sq%d_wq", WQ_UNBOUND,
1381 				min_t(int, sq->depth, WQ_MAX_ACTIVE), sqid);
1382 	if (!sq->iod_wq) {
1383 		dev_err(ctrl->dev, "Failed to create SQ %d work queue\n", sqid);
1384 		status = NVME_SC_INTERNAL | NVME_STATUS_DNR;
1385 		goto out_destroy_sq;
1386 	}
1387 
1388 	set_bit(NVMET_PCI_EPF_Q_LIVE, &sq->flags);
1389 
1390 	dev_dbg(ctrl->dev, "SQ[%u]: %u entries of %zu B\n",
1391 		sqid, qsize, sq->qes);
1392 
1393 	return NVME_SC_SUCCESS;
1394 
1395 out_destroy_sq:
1396 	nvmet_sq_destroy(&sq->nvme_sq);
1397 	return status;
1398 }
1399 
1400 static u16 nvmet_pci_epf_delete_sq(struct nvmet_ctrl *tctrl, u16 sqid)
1401 {
1402 	struct nvmet_pci_epf_ctrl *ctrl = tctrl->drvdata;
1403 	struct nvmet_pci_epf_queue *sq = &ctrl->sq[sqid];
1404 
1405 	if (!test_and_clear_bit(NVMET_PCI_EPF_Q_LIVE, &sq->flags))
1406 		return NVME_SC_QID_INVALID | NVME_STATUS_DNR;
1407 
1408 	destroy_workqueue(sq->iod_wq);
1409 	sq->iod_wq = NULL;
1410 
1411 	nvmet_pci_epf_drain_queue(sq);
1412 
1413 	if (sq->nvme_sq.ctrl)
1414 		nvmet_sq_destroy(&sq->nvme_sq);
1415 
1416 	return NVME_SC_SUCCESS;
1417 }
1418 
1419 static u16 nvmet_pci_epf_get_feat(const struct nvmet_ctrl *tctrl,
1420 				  u8 feat, void *data)
1421 {
1422 	struct nvmet_pci_epf_ctrl *ctrl = tctrl->drvdata;
1423 	struct nvmet_feat_arbitration *arb;
1424 	struct nvmet_feat_irq_coalesce *irqc;
1425 	struct nvmet_feat_irq_config *irqcfg;
1426 	struct nvmet_pci_epf_irq_vector *iv;
1427 	u16 status;
1428 
1429 	switch (feat) {
1430 	case NVME_FEAT_ARBITRATION:
1431 		arb = data;
1432 		if (!ctrl->sq_ab)
1433 			arb->ab = 0x7;
1434 		else
1435 			arb->ab = ilog2(ctrl->sq_ab);
1436 		return NVME_SC_SUCCESS;
1437 
1438 	case NVME_FEAT_IRQ_COALESCE:
1439 		irqc = data;
1440 		irqc->thr = ctrl->irq_vector_threshold;
1441 		irqc->time = 0;
1442 		return NVME_SC_SUCCESS;
1443 
1444 	case NVME_FEAT_IRQ_CONFIG:
1445 		irqcfg = data;
1446 		mutex_lock(&ctrl->irq_lock);
1447 		iv = nvmet_pci_epf_find_irq_vector(ctrl, irqcfg->iv);
1448 		if (iv) {
1449 			irqcfg->cd = iv->cd;
1450 			status = NVME_SC_SUCCESS;
1451 		} else {
1452 			status = NVME_SC_INVALID_FIELD | NVME_STATUS_DNR;
1453 		}
1454 		mutex_unlock(&ctrl->irq_lock);
1455 		return status;
1456 
1457 	default:
1458 		return NVME_SC_INVALID_FIELD | NVME_STATUS_DNR;
1459 	}
1460 }
1461 
1462 static u16 nvmet_pci_epf_set_feat(const struct nvmet_ctrl *tctrl,
1463 				  u8 feat, void *data)
1464 {
1465 	struct nvmet_pci_epf_ctrl *ctrl = tctrl->drvdata;
1466 	struct nvmet_feat_arbitration *arb;
1467 	struct nvmet_feat_irq_coalesce *irqc;
1468 	struct nvmet_feat_irq_config *irqcfg;
1469 	struct nvmet_pci_epf_irq_vector *iv;
1470 	u16 status;
1471 
1472 	switch (feat) {
1473 	case NVME_FEAT_ARBITRATION:
1474 		arb = data;
1475 		if (arb->ab == 0x7)
1476 			ctrl->sq_ab = 0;
1477 		else
1478 			ctrl->sq_ab = 1 << arb->ab;
1479 		return NVME_SC_SUCCESS;
1480 
1481 	case NVME_FEAT_IRQ_COALESCE:
1482 		/*
1483 		 * Since we do not implement precise IRQ coalescing timing,
1484 		 * ignore the time field.
1485 		 */
1486 		irqc = data;
1487 		ctrl->irq_vector_threshold = irqc->thr + 1;
1488 		return NVME_SC_SUCCESS;
1489 
1490 	case NVME_FEAT_IRQ_CONFIG:
1491 		irqcfg = data;
1492 		mutex_lock(&ctrl->irq_lock);
1493 		iv = nvmet_pci_epf_find_irq_vector(ctrl, irqcfg->iv);
1494 		if (iv) {
1495 			iv->cd = irqcfg->cd;
1496 			status = NVME_SC_SUCCESS;
1497 		} else {
1498 			status = NVME_SC_INVALID_FIELD | NVME_STATUS_DNR;
1499 		}
1500 		mutex_unlock(&ctrl->irq_lock);
1501 		return status;
1502 
1503 	default:
1504 		return NVME_SC_INVALID_FIELD | NVME_STATUS_DNR;
1505 	}
1506 }
1507 
1508 static const struct nvmet_fabrics_ops nvmet_pci_epf_fabrics_ops = {
1509 	.owner		= THIS_MODULE,
1510 	.type		= NVMF_TRTYPE_PCI,
1511 	.add_port	= nvmet_pci_epf_add_port,
1512 	.remove_port	= nvmet_pci_epf_remove_port,
1513 	.queue_response = nvmet_pci_epf_queue_response,
1514 	.get_mdts	= nvmet_pci_epf_get_mdts,
1515 	.create_cq	= nvmet_pci_epf_create_cq,
1516 	.delete_cq	= nvmet_pci_epf_delete_cq,
1517 	.create_sq	= nvmet_pci_epf_create_sq,
1518 	.delete_sq	= nvmet_pci_epf_delete_sq,
1519 	.get_feature	= nvmet_pci_epf_get_feat,
1520 	.set_feature	= nvmet_pci_epf_set_feat,
1521 };
1522 
1523 static void nvmet_pci_epf_cq_work(struct work_struct *work);
1524 
1525 static void nvmet_pci_epf_init_queue(struct nvmet_pci_epf_ctrl *ctrl,
1526 				     unsigned int qid, bool sq)
1527 {
1528 	struct nvmet_pci_epf_queue *queue;
1529 
1530 	if (sq) {
1531 		queue = &ctrl->sq[qid];
1532 	} else {
1533 		queue = &ctrl->cq[qid];
1534 		INIT_DELAYED_WORK(&queue->work, nvmet_pci_epf_cq_work);
1535 	}
1536 	queue->ctrl = ctrl;
1537 	queue->qid = qid;
1538 	spin_lock_init(&queue->lock);
1539 	INIT_LIST_HEAD(&queue->list);
1540 }
1541 
1542 static int nvmet_pci_epf_alloc_queues(struct nvmet_pci_epf_ctrl *ctrl)
1543 {
1544 	unsigned int qid;
1545 
1546 	ctrl->sq = kzalloc_objs(struct nvmet_pci_epf_queue, ctrl->nr_queues);
1547 	if (!ctrl->sq)
1548 		return -ENOMEM;
1549 
1550 	ctrl->cq = kzalloc_objs(struct nvmet_pci_epf_queue, ctrl->nr_queues);
1551 	if (!ctrl->cq) {
1552 		kfree(ctrl->sq);
1553 		ctrl->sq = NULL;
1554 		return -ENOMEM;
1555 	}
1556 
1557 	for (qid = 0; qid < ctrl->nr_queues; qid++) {
1558 		nvmet_pci_epf_init_queue(ctrl, qid, true);
1559 		nvmet_pci_epf_init_queue(ctrl, qid, false);
1560 	}
1561 
1562 	return 0;
1563 }
1564 
1565 static void nvmet_pci_epf_free_queues(struct nvmet_pci_epf_ctrl *ctrl)
1566 {
1567 	kfree(ctrl->sq);
1568 	ctrl->sq = NULL;
1569 	kfree(ctrl->cq);
1570 	ctrl->cq = NULL;
1571 }
1572 
1573 static void nvmet_pci_epf_exec_iod_work(struct work_struct *work)
1574 {
1575 	struct nvmet_pci_epf_iod *iod =
1576 		container_of(work, struct nvmet_pci_epf_iod, work);
1577 	struct nvmet_req *req = &iod->req;
1578 	bool no_wait;
1579 	int ret;
1580 
1581 	if (!iod->ctrl->link_up) {
1582 		nvmet_pci_epf_free_iod(iod);
1583 		return;
1584 	}
1585 
1586 	if (!test_bit(NVMET_PCI_EPF_Q_LIVE, &iod->sq->flags)) {
1587 		iod->status = NVME_SC_QID_INVALID | NVME_STATUS_DNR;
1588 		goto complete;
1589 	}
1590 
1591 	/*
1592 	 * If nvmet_req_init() fails (e.g., unsupported opcode) it will call
1593 	 * __nvmet_req_complete() internally which will call
1594 	 * nvmet_pci_epf_queue_response() and will complete the command directly.
1595 	 */
1596 	if (!nvmet_req_init(req, &iod->sq->nvme_sq, &nvmet_pci_epf_fabrics_ops))
1597 		return;
1598 
1599 	iod->data_len = nvmet_req_transfer_len(req);
1600 	if (iod->data_len) {
1601 		/*
1602 		 * Get the data DMA transfer direction. Here "device" means the
1603 		 * PCI root-complex host.
1604 		 */
1605 		if (nvme_is_write(&iod->cmd))
1606 			iod->dma_dir = DMA_FROM_DEVICE;
1607 		else
1608 			iod->dma_dir = DMA_TO_DEVICE;
1609 
1610 		/*
1611 		 * Setup the command data buffer and get the command data from
1612 		 * the host if needed.
1613 		 */
1614 		ret = nvmet_pci_epf_alloc_iod_data_buf(iod);
1615 		if (!ret && iod->dma_dir == DMA_FROM_DEVICE)
1616 			ret = nvmet_pci_epf_transfer_iod_data(iod);
1617 		if (ret) {
1618 			nvmet_req_uninit(req);
1619 			goto complete;
1620 		}
1621 	}
1622 
1623 	/*
1624 	 * If we do not have data to transfer after the command execution
1625 	 * finishes, nvmet_pci_epf_queue_response() will complete the command
1626 	 * directly. No need to wait for the completion in this case.
1627 	 */
1628 	no_wait = !iod->data_len || iod->dma_dir != DMA_TO_DEVICE;
1629 
1630 	req->execute(req);
1631 
1632 	if (no_wait)
1633 		return;
1634 
1635 	wait_for_completion(&iod->done);
1636 
1637 	if (iod->status != NVME_SC_SUCCESS)
1638 		return;
1639 
1640 	WARN_ON_ONCE(!iod->data_len || iod->dma_dir != DMA_TO_DEVICE);
1641 	nvmet_pci_epf_transfer_iod_data(iod);
1642 
1643 complete:
1644 	nvmet_pci_epf_complete_iod(iod);
1645 }
1646 
1647 static int nvmet_pci_epf_process_sq(struct nvmet_pci_epf_ctrl *ctrl,
1648 				    struct nvmet_pci_epf_queue *sq)
1649 {
1650 	struct nvmet_pci_epf_iod *iod;
1651 	int ret, n = 0;
1652 	u16 head = sq->head;
1653 
1654 	sq->tail = nvmet_pci_epf_bar_read32(ctrl, sq->db);
1655 	while (head != sq->tail && (!ctrl->sq_ab || n < ctrl->sq_ab)) {
1656 		iod = nvmet_pci_epf_alloc_iod(sq);
1657 		if (!iod)
1658 			break;
1659 
1660 		/* Get the NVMe command submitted by the host. */
1661 		ret = nvmet_pci_epf_transfer(ctrl, &iod->cmd,
1662 					     sq->pci_addr + head * sq->qes,
1663 					     sq->qes, DMA_FROM_DEVICE);
1664 		if (ret) {
1665 			/* Not much we can do... */
1666 			nvmet_pci_epf_free_iod(iod);
1667 			break;
1668 		}
1669 
1670 		dev_dbg(ctrl->dev, "SQ[%u]: head %u, tail %u, command %s\n",
1671 			sq->qid, head, sq->tail,
1672 			nvmet_pci_epf_iod_name(iod));
1673 
1674 		head++;
1675 		if (head == sq->depth)
1676 			head = 0;
1677 		WRITE_ONCE(sq->head, head);
1678 		n++;
1679 
1680 		queue_work_on(WORK_CPU_UNBOUND, sq->iod_wq, &iod->work);
1681 
1682 		sq->tail = nvmet_pci_epf_bar_read32(ctrl, sq->db);
1683 	}
1684 
1685 	return n;
1686 }
1687 
1688 static void nvmet_pci_epf_poll_sqs_work(struct work_struct *work)
1689 {
1690 	struct nvmet_pci_epf_ctrl *ctrl =
1691 		container_of(work, struct nvmet_pci_epf_ctrl, poll_sqs.work);
1692 	struct nvmet_pci_epf_queue *sq;
1693 	unsigned long limit = jiffies;
1694 	unsigned long last = 0;
1695 	int i, nr_sqs;
1696 
1697 	while (ctrl->link_up && ctrl->enabled) {
1698 		nr_sqs = 0;
1699 		/* Do round-robin arbitration. */
1700 		for (i = 0; i < ctrl->nr_queues; i++) {
1701 			sq = &ctrl->sq[i];
1702 			if (!test_bit(NVMET_PCI_EPF_Q_LIVE, &sq->flags))
1703 				continue;
1704 			if (nvmet_pci_epf_process_sq(ctrl, sq))
1705 				nr_sqs++;
1706 		}
1707 
1708 		/*
1709 		 * If we have been running for a while, reschedule to let other
1710 		 * tasks run and to avoid RCU stalls.
1711 		 */
1712 		if (time_is_before_jiffies(limit + secs_to_jiffies(1))) {
1713 			cond_resched();
1714 			limit = jiffies;
1715 			continue;
1716 		}
1717 
1718 		if (nr_sqs) {
1719 			last = jiffies;
1720 			continue;
1721 		}
1722 
1723 		/*
1724 		 * If we have not received any command on any queue for more
1725 		 * than NVMET_PCI_EPF_SQ_POLL_IDLE, assume we are idle and
1726 		 * reschedule. This avoids "burning" a CPU when the controller
1727 		 * is idle for a long time.
1728 		 */
1729 		if (time_is_before_jiffies(last + NVMET_PCI_EPF_SQ_POLL_IDLE))
1730 			break;
1731 
1732 		cpu_relax();
1733 	}
1734 
1735 	schedule_delayed_work(&ctrl->poll_sqs, NVMET_PCI_EPF_SQ_POLL_INTERVAL);
1736 }
1737 
1738 static void nvmet_pci_epf_cq_work(struct work_struct *work)
1739 {
1740 	struct nvmet_pci_epf_queue *cq =
1741 		container_of(work, struct nvmet_pci_epf_queue, work.work);
1742 	struct nvmet_pci_epf_ctrl *ctrl = cq->ctrl;
1743 	struct nvme_completion *cqe;
1744 	struct nvmet_pci_epf_iod *iod;
1745 	unsigned long flags;
1746 	int ret = 0, n = 0;
1747 
1748 	while (test_bit(NVMET_PCI_EPF_Q_LIVE, &cq->flags) && ctrl->link_up) {
1749 
1750 		/* Check that the CQ is not full. */
1751 		cq->head = nvmet_pci_epf_bar_read32(ctrl, cq->db);
1752 		if (cq->head == cq->tail + 1) {
1753 			ret = -EAGAIN;
1754 			break;
1755 		}
1756 
1757 		spin_lock_irqsave(&cq->lock, flags);
1758 		iod = list_first_entry_or_null(&cq->list,
1759 					       struct nvmet_pci_epf_iod, link);
1760 		if (iod)
1761 			list_del_init(&iod->link);
1762 		spin_unlock_irqrestore(&cq->lock, flags);
1763 
1764 		if (!iod)
1765 			break;
1766 
1767 		/*
1768 		 * Post the IOD completion entry. If the IOD request was
1769 		 * executed (req->execute() called), the CQE is already
1770 		 * initialized. However, the IOD may have been failed before
1771 		 * that, leaving the CQE not properly initialized. So always
1772 		 * initialize it here.
1773 		 */
1774 		cqe = &iod->cqe;
1775 		cqe->sq_head = cpu_to_le16(READ_ONCE(iod->sq->head));
1776 		cqe->sq_id = cpu_to_le16(iod->sq->qid);
1777 		cqe->command_id = iod->cmd.common.command_id;
1778 		cqe->status = cpu_to_le16((iod->status << 1) | cq->phase);
1779 
1780 		dev_dbg(ctrl->dev,
1781 			"CQ[%u]: %s status 0x%x, result 0x%llx, head %u, tail %u, phase %u\n",
1782 			cq->qid, nvmet_pci_epf_iod_name(iod), iod->status,
1783 			le64_to_cpu(cqe->result.u64), cq->head, cq->tail,
1784 			cq->phase);
1785 
1786 		memcpy_toio(cq->pci_map.virt_addr + cq->tail * cq->qes,
1787 			    cqe, cq->qes);
1788 
1789 		cq->tail++;
1790 		if (cq->tail >= cq->depth) {
1791 			cq->tail = 0;
1792 			cq->phase ^= 1;
1793 		}
1794 
1795 		nvmet_pci_epf_free_iod(iod);
1796 
1797 		/* Signal the host. */
1798 		nvmet_pci_epf_raise_irq(ctrl, cq, false);
1799 		n++;
1800 	}
1801 
1802 	/*
1803 	 * We do not support precise IRQ coalescing time (100ns units as per
1804 	 * NVMe specifications). So if we have posted completion entries without
1805 	 * reaching the interrupt coalescing threshold, raise an interrupt.
1806 	 */
1807 	if (n)
1808 		nvmet_pci_epf_raise_irq(ctrl, cq, true);
1809 
1810 	if (ret < 0)
1811 		queue_delayed_work(system_highpri_wq, &cq->work,
1812 				   NVMET_PCI_EPF_CQ_RETRY_INTERVAL);
1813 }
1814 
1815 static void nvmet_pci_epf_clear_ctrl_config(struct nvmet_pci_epf_ctrl *ctrl)
1816 {
1817 	struct nvmet_ctrl *tctrl = ctrl->tctrl;
1818 
1819 	/* Initialize controller status. */
1820 	tctrl->csts = 0;
1821 	ctrl->csts = 0;
1822 	nvmet_pci_epf_bar_write32(ctrl, NVME_REG_CSTS, ctrl->csts);
1823 
1824 	/* Initialize controller configuration and start polling. */
1825 	tctrl->cc = 0;
1826 	ctrl->cc = 0;
1827 	nvmet_pci_epf_bar_write32(ctrl, NVME_REG_CC, ctrl->cc);
1828 }
1829 
1830 static int nvmet_pci_epf_enable_ctrl(struct nvmet_pci_epf_ctrl *ctrl)
1831 {
1832 	u64 pci_addr, asq, acq;
1833 	u32 aqa;
1834 	u16 status, qsize;
1835 
1836 	if (ctrl->enabled)
1837 		return 0;
1838 
1839 	dev_info(ctrl->dev, "Enabling controller\n");
1840 
1841 	ctrl->mps_shift = nvmet_cc_mps(ctrl->cc) + 12;
1842 	ctrl->mps = 1UL << ctrl->mps_shift;
1843 	ctrl->mps_mask = ctrl->mps - 1;
1844 
1845 	ctrl->io_sqes = 1UL << nvmet_cc_iosqes(ctrl->cc);
1846 	if (ctrl->io_sqes < sizeof(struct nvme_command)) {
1847 		dev_err(ctrl->dev, "Unsupported I/O SQES %zu (need %zu)\n",
1848 			ctrl->io_sqes, sizeof(struct nvme_command));
1849 		goto err;
1850 	}
1851 
1852 	ctrl->io_cqes = 1UL << nvmet_cc_iocqes(ctrl->cc);
1853 	if (ctrl->io_cqes < sizeof(struct nvme_completion)) {
1854 		dev_err(ctrl->dev, "Unsupported I/O CQES %zu (need %zu)\n",
1855 			ctrl->io_cqes, sizeof(struct nvme_completion));
1856 		goto err;
1857 	}
1858 
1859 	/* Create the admin queue. */
1860 	aqa = nvmet_pci_epf_bar_read32(ctrl, NVME_REG_AQA);
1861 	asq = nvmet_pci_epf_bar_read64(ctrl, NVME_REG_ASQ);
1862 	acq = nvmet_pci_epf_bar_read64(ctrl, NVME_REG_ACQ);
1863 
1864 	qsize = (aqa & 0x0fff0000) >> 16;
1865 	pci_addr = acq & GENMASK_ULL(63, 12);
1866 	status = nvmet_pci_epf_create_cq(ctrl->tctrl, 0,
1867 				NVME_CQ_IRQ_ENABLED | NVME_QUEUE_PHYS_CONTIG,
1868 				qsize, pci_addr, 0);
1869 	if (status != NVME_SC_SUCCESS) {
1870 		dev_err(ctrl->dev, "Failed to create admin completion queue\n");
1871 		goto err;
1872 	}
1873 
1874 	qsize = aqa & 0x00000fff;
1875 	pci_addr = asq & GENMASK_ULL(63, 12);
1876 	status = nvmet_pci_epf_create_sq(ctrl->tctrl, 0, 0,
1877 			NVME_QUEUE_PHYS_CONTIG, qsize, pci_addr);
1878 	if (status != NVME_SC_SUCCESS) {
1879 		dev_err(ctrl->dev, "Failed to create admin submission queue\n");
1880 		nvmet_pci_epf_delete_cq(ctrl->tctrl, 0);
1881 		goto err;
1882 	}
1883 
1884 	ctrl->sq_ab = NVMET_PCI_EPF_SQ_AB;
1885 	ctrl->irq_vector_threshold = NVMET_PCI_EPF_IV_THRESHOLD;
1886 	ctrl->enabled = true;
1887 	ctrl->csts = NVME_CSTS_RDY;
1888 
1889 	/* Start polling the controller SQs. */
1890 	schedule_delayed_work(&ctrl->poll_sqs, 0);
1891 
1892 	return 0;
1893 
1894 err:
1895 	nvmet_pci_epf_clear_ctrl_config(ctrl);
1896 	return -EINVAL;
1897 }
1898 
1899 static void nvmet_pci_epf_disable_ctrl(struct nvmet_pci_epf_ctrl *ctrl,
1900 				       bool shutdown)
1901 {
1902 	int qid;
1903 
1904 	if (!ctrl->enabled)
1905 		return;
1906 
1907 	dev_info(ctrl->dev, "%s controller\n",
1908 		 shutdown ? "Shutting down" : "Disabling");
1909 
1910 	ctrl->enabled = false;
1911 	cancel_delayed_work_sync(&ctrl->poll_sqs);
1912 
1913 	/* Delete all I/O queues first. */
1914 	for (qid = 1; qid < ctrl->nr_queues; qid++)
1915 		nvmet_pci_epf_delete_sq(ctrl->tctrl, qid);
1916 
1917 	for (qid = 1; qid < ctrl->nr_queues; qid++)
1918 		nvmet_pci_epf_delete_cq(ctrl->tctrl, qid);
1919 
1920 	/* Delete the admin queue last. */
1921 	nvmet_pci_epf_delete_sq(ctrl->tctrl, 0);
1922 	nvmet_pci_epf_delete_cq(ctrl->tctrl, 0);
1923 
1924 	ctrl->csts &= ~NVME_CSTS_RDY;
1925 	if (shutdown) {
1926 		ctrl->csts |= NVME_CSTS_SHST_CMPLT;
1927 		ctrl->cc &= ~NVME_CC_ENABLE;
1928 		nvmet_pci_epf_bar_write32(ctrl, NVME_REG_CC, ctrl->cc);
1929 	}
1930 }
1931 
1932 static void nvmet_pci_epf_poll_cc_work(struct work_struct *work)
1933 {
1934 	struct nvmet_pci_epf_ctrl *ctrl =
1935 		container_of(work, struct nvmet_pci_epf_ctrl, poll_cc.work);
1936 	u32 old_cc, new_cc;
1937 	int ret;
1938 
1939 	if (!ctrl->tctrl)
1940 		return;
1941 
1942 	old_cc = ctrl->cc;
1943 	new_cc = nvmet_pci_epf_bar_read32(ctrl, NVME_REG_CC);
1944 	if (new_cc == old_cc)
1945 		goto reschedule_work;
1946 
1947 	ctrl->cc = new_cc;
1948 
1949 	if (nvmet_cc_en(new_cc) && !nvmet_cc_en(old_cc)) {
1950 		ret = nvmet_pci_epf_enable_ctrl(ctrl);
1951 		if (ret)
1952 			goto reschedule_work;
1953 	}
1954 
1955 	if (!nvmet_cc_en(new_cc) && nvmet_cc_en(old_cc))
1956 		nvmet_pci_epf_disable_ctrl(ctrl, false);
1957 
1958 	if (nvmet_cc_shn(new_cc) && !nvmet_cc_shn(old_cc))
1959 		nvmet_pci_epf_disable_ctrl(ctrl, true);
1960 
1961 	if (!nvmet_cc_shn(new_cc) && nvmet_cc_shn(old_cc))
1962 		ctrl->csts &= ~NVME_CSTS_SHST_CMPLT;
1963 
1964 	nvmet_update_cc(ctrl->tctrl, ctrl->cc);
1965 	nvmet_pci_epf_bar_write32(ctrl, NVME_REG_CSTS, ctrl->csts);
1966 
1967 reschedule_work:
1968 	schedule_delayed_work(&ctrl->poll_cc, NVMET_PCI_EPF_CC_POLL_INTERVAL);
1969 }
1970 
1971 static void nvmet_pci_epf_init_bar(struct nvmet_pci_epf_ctrl *ctrl)
1972 {
1973 	struct nvmet_ctrl *tctrl = ctrl->tctrl;
1974 
1975 	ctrl->bar = ctrl->nvme_epf->reg_bar;
1976 
1977 	/* Copy the target controller capabilities as a base. */
1978 	ctrl->cap = tctrl->cap;
1979 
1980 	/* Contiguous Queues Required (CQR). */
1981 	ctrl->cap |= 0x1ULL << 16;
1982 
1983 	/* Set Doorbell stride to 4B (DSTRB). */
1984 	ctrl->cap &= ~GENMASK_ULL(35, 32);
1985 
1986 	/* Clear NVM Subsystem Reset Supported (NSSRS). */
1987 	ctrl->cap &= ~(0x1ULL << 36);
1988 
1989 	/* Clear Boot Partition Support (BPS). */
1990 	ctrl->cap &= ~(0x1ULL << 45);
1991 
1992 	/* Clear Persistent Memory Region Supported (PMRS). */
1993 	ctrl->cap &= ~(0x1ULL << 56);
1994 
1995 	/* Clear Controller Memory Buffer Supported (CMBS). */
1996 	ctrl->cap &= ~(0x1ULL << 57);
1997 
1998 	nvmet_pci_epf_bar_write64(ctrl, NVME_REG_CAP, ctrl->cap);
1999 	nvmet_pci_epf_bar_write32(ctrl, NVME_REG_VS, tctrl->subsys->ver);
2000 
2001 	nvmet_pci_epf_clear_ctrl_config(ctrl);
2002 }
2003 
2004 static int nvmet_pci_epf_create_ctrl(struct nvmet_pci_epf *nvme_epf,
2005 				     unsigned int max_nr_queues)
2006 {
2007 	struct nvmet_pci_epf_ctrl *ctrl = &nvme_epf->ctrl;
2008 	struct nvmet_alloc_ctrl_args args = {};
2009 	char hostnqn[NVMF_NQN_SIZE];
2010 	uuid_t id;
2011 	int ret;
2012 
2013 	memset(ctrl, 0, sizeof(*ctrl));
2014 	ctrl->dev = &nvme_epf->epf->dev;
2015 	mutex_init(&ctrl->irq_lock);
2016 	ctrl->nvme_epf = nvme_epf;
2017 	ctrl->mdts = nvme_epf->mdts_kb * SZ_1K;
2018 	INIT_DELAYED_WORK(&ctrl->poll_cc, nvmet_pci_epf_poll_cc_work);
2019 	INIT_DELAYED_WORK(&ctrl->poll_sqs, nvmet_pci_epf_poll_sqs_work);
2020 
2021 	ret = mempool_init_kmalloc_pool(&ctrl->iod_pool,
2022 					max_nr_queues * NVMET_MAX_QUEUE_SIZE,
2023 					sizeof(struct nvmet_pci_epf_iod));
2024 	if (ret) {
2025 		dev_err(ctrl->dev, "Failed to initialize IOD mempool\n");
2026 		return ret;
2027 	}
2028 
2029 	ctrl->port = nvmet_pci_epf_find_port(ctrl, nvme_epf->portid);
2030 	if (!ctrl->port) {
2031 		dev_err(ctrl->dev, "Port not found\n");
2032 		ret = -EINVAL;
2033 		goto out_mempool_exit;
2034 	}
2035 
2036 	/* Create the target controller. */
2037 	uuid_gen(&id);
2038 	snprintf(hostnqn, NVMF_NQN_SIZE,
2039 		 "nqn.2014-08.org.nvmexpress:uuid:%pUb", &id);
2040 	args.port = ctrl->port;
2041 	args.subsysnqn = nvme_epf->subsysnqn;
2042 	memset(&id, 0, sizeof(uuid_t));
2043 	args.hostid = &id;
2044 	args.hostnqn = hostnqn;
2045 	args.ops = &nvmet_pci_epf_fabrics_ops;
2046 
2047 	ctrl->tctrl = nvmet_alloc_ctrl(&args);
2048 	if (!ctrl->tctrl) {
2049 		dev_err(ctrl->dev, "Failed to create target controller\n");
2050 		ret = -ENOMEM;
2051 		goto out_mempool_exit;
2052 	}
2053 	ctrl->tctrl->drvdata = ctrl;
2054 
2055 	/* We do not support protection information for now. */
2056 	if (ctrl->tctrl->pi_support) {
2057 		dev_err(ctrl->dev,
2058 			"Protection information (PI) is not supported\n");
2059 		ret = -ENOTSUPP;
2060 		goto out_put_ctrl;
2061 	}
2062 
2063 	/* Allocate our queues, up to the maximum number. */
2064 	ctrl->nr_queues = min(ctrl->tctrl->max_qid + 1, max_nr_queues);
2065 	ret = nvmet_pci_epf_alloc_queues(ctrl);
2066 	if (ret)
2067 		goto out_put_ctrl;
2068 
2069 	/*
2070 	 * Allocate the IRQ vectors descriptors. We cannot have more than the
2071 	 * maximum number of queues.
2072 	 */
2073 	ret = nvmet_pci_epf_alloc_irq_vectors(ctrl);
2074 	if (ret)
2075 		goto out_free_queues;
2076 
2077 	dev_info(ctrl->dev,
2078 		 "New PCI ctrl \"%s\", %u I/O queues, mdts %u B\n",
2079 		 ctrl->tctrl->subsys->subsysnqn, ctrl->nr_queues - 1,
2080 		 ctrl->mdts);
2081 
2082 	/* Initialize BAR 0 using the target controller CAP. */
2083 	nvmet_pci_epf_init_bar(ctrl);
2084 
2085 	return 0;
2086 
2087 out_free_queues:
2088 	nvmet_pci_epf_free_queues(ctrl);
2089 out_put_ctrl:
2090 	nvmet_ctrl_put(ctrl->tctrl);
2091 	ctrl->tctrl = NULL;
2092 out_mempool_exit:
2093 	mempool_exit(&ctrl->iod_pool);
2094 	return ret;
2095 }
2096 
2097 static void nvmet_pci_epf_start_ctrl(struct nvmet_pci_epf_ctrl *ctrl)
2098 {
2099 
2100 	dev_info(ctrl->dev, "PCI link up\n");
2101 	ctrl->link_up = true;
2102 
2103 	schedule_delayed_work(&ctrl->poll_cc, NVMET_PCI_EPF_CC_POLL_INTERVAL);
2104 }
2105 
2106 static void nvmet_pci_epf_stop_ctrl(struct nvmet_pci_epf_ctrl *ctrl)
2107 {
2108 	dev_info(ctrl->dev, "PCI link down\n");
2109 	ctrl->link_up = false;
2110 
2111 	cancel_delayed_work_sync(&ctrl->poll_cc);
2112 
2113 	nvmet_pci_epf_disable_ctrl(ctrl, false);
2114 	nvmet_pci_epf_clear_ctrl_config(ctrl);
2115 }
2116 
2117 static void nvmet_pci_epf_destroy_ctrl(struct nvmet_pci_epf_ctrl *ctrl)
2118 {
2119 	if (!ctrl->tctrl)
2120 		return;
2121 
2122 	dev_info(ctrl->dev, "Destroying PCI ctrl \"%s\"\n",
2123 		 ctrl->tctrl->subsys->subsysnqn);
2124 
2125 	nvmet_pci_epf_stop_ctrl(ctrl);
2126 
2127 	nvmet_pci_epf_free_queues(ctrl);
2128 	nvmet_pci_epf_free_irq_vectors(ctrl);
2129 
2130 	nvmet_ctrl_put(ctrl->tctrl);
2131 	ctrl->tctrl = NULL;
2132 
2133 	mempool_exit(&ctrl->iod_pool);
2134 }
2135 
2136 static int nvmet_pci_epf_configure_bar(struct nvmet_pci_epf *nvme_epf)
2137 {
2138 	struct pci_epf *epf = nvme_epf->epf;
2139 	const struct pci_epc_features *epc_features = nvme_epf->epc_features;
2140 	size_t reg_size, reg_bar_size;
2141 	size_t msix_table_size = 0;
2142 
2143 	/*
2144 	 * The first free BAR will be our register BAR and per NVMe
2145 	 * specifications, it must be BAR 0.
2146 	 */
2147 	if (pci_epc_get_first_free_bar(epc_features) != BAR_0) {
2148 		dev_err(&epf->dev, "BAR 0 is not free\n");
2149 		return -ENODEV;
2150 	}
2151 
2152 	/*
2153 	 * While NVMe PCIe Transport Specification 1.1, section 2.1.10, claims
2154 	 * that the BAR0 type is Implementation Specific, in NVMe 1.1, the type
2155 	 * is required to be 64-bit. Thus, for interoperability, always set the
2156 	 * type to 64-bit. In the rare case that the PCI EPC does not support
2157 	 * configuring BAR0 as 64-bit, the call to pci_epc_set_bar() will fail,
2158 	 * and we will return failure back to the user.
2159 	 */
2160 	epf->bar[BAR_0].flags |= PCI_BASE_ADDRESS_MEM_TYPE_64;
2161 
2162 	/*
2163 	 * Calculate the size of the register bar: NVMe registers first with
2164 	 * enough space for the doorbells, followed by the MSI-X table
2165 	 * if supported.
2166 	 */
2167 	reg_size = NVME_REG_DBS + (NVMET_NR_QUEUES * 2 * sizeof(u32));
2168 	reg_size = ALIGN(reg_size, 8);
2169 
2170 	if (epc_features->msix_capable) {
2171 		size_t pba_size;
2172 
2173 		msix_table_size = PCI_MSIX_ENTRY_SIZE * epf->msix_interrupts;
2174 		nvme_epf->msix_table_offset = reg_size;
2175 		pba_size = ALIGN(DIV_ROUND_UP(epf->msix_interrupts, 8), 8);
2176 
2177 		reg_size += msix_table_size + pba_size;
2178 	}
2179 
2180 	if (epc_features->bar[BAR_0].type == BAR_FIXED) {
2181 		if (reg_size > epc_features->bar[BAR_0].fixed_size) {
2182 			dev_err(&epf->dev,
2183 				"BAR 0 size %llu B too small, need %zu B\n",
2184 				epc_features->bar[BAR_0].fixed_size,
2185 				reg_size);
2186 			return -ENOMEM;
2187 		}
2188 		reg_bar_size = epc_features->bar[BAR_0].fixed_size;
2189 	} else {
2190 		reg_bar_size = ALIGN(reg_size, max(epc_features->align, 4096));
2191 	}
2192 
2193 	nvme_epf->reg_bar = pci_epf_alloc_space(epf, reg_bar_size, BAR_0,
2194 						epc_features, PRIMARY_INTERFACE);
2195 	if (!nvme_epf->reg_bar) {
2196 		dev_err(&epf->dev, "Failed to allocate BAR 0\n");
2197 		return -ENOMEM;
2198 	}
2199 	memset(nvme_epf->reg_bar, 0, reg_bar_size);
2200 
2201 	return 0;
2202 }
2203 
2204 static void nvmet_pci_epf_free_bar(struct nvmet_pci_epf *nvme_epf)
2205 {
2206 	struct pci_epf *epf = nvme_epf->epf;
2207 
2208 	if (!nvme_epf->reg_bar)
2209 		return;
2210 
2211 	pci_epf_free_space(epf, nvme_epf->reg_bar, BAR_0, PRIMARY_INTERFACE);
2212 	nvme_epf->reg_bar = NULL;
2213 }
2214 
2215 static void nvmet_pci_epf_clear_bar(struct nvmet_pci_epf *nvme_epf)
2216 {
2217 	struct pci_epf *epf = nvme_epf->epf;
2218 
2219 	pci_epc_clear_bar(epf->epc, epf->func_no, epf->vfunc_no,
2220 			  &epf->bar[BAR_0]);
2221 }
2222 
2223 static int nvmet_pci_epf_init_irq(struct nvmet_pci_epf *nvme_epf)
2224 {
2225 	const struct pci_epc_features *epc_features = nvme_epf->epc_features;
2226 	struct pci_epf *epf = nvme_epf->epf;
2227 	int ret;
2228 
2229 	/* Enable MSI-X if supported, otherwise, use MSI. */
2230 	if (epc_features->msix_capable && epf->msix_interrupts) {
2231 		ret = pci_epc_set_msix(epf->epc, epf->func_no, epf->vfunc_no,
2232 				       epf->msix_interrupts, BAR_0,
2233 				       nvme_epf->msix_table_offset);
2234 		if (ret) {
2235 			dev_err(&epf->dev, "Failed to configure MSI-X\n");
2236 			return ret;
2237 		}
2238 
2239 		nvme_epf->nr_vectors = epf->msix_interrupts;
2240 		nvme_epf->irq_type = PCI_IRQ_MSIX;
2241 
2242 		return 0;
2243 	}
2244 
2245 	if (epc_features->msi_capable && epf->msi_interrupts) {
2246 		ret = pci_epc_set_msi(epf->epc, epf->func_no, epf->vfunc_no,
2247 				      epf->msi_interrupts);
2248 		if (ret) {
2249 			dev_err(&epf->dev, "Failed to configure MSI\n");
2250 			return ret;
2251 		}
2252 
2253 		nvme_epf->nr_vectors = epf->msi_interrupts;
2254 		nvme_epf->irq_type = PCI_IRQ_MSI;
2255 
2256 		return 0;
2257 	}
2258 
2259 	/* MSI and MSI-X are not supported: fall back to INTx. */
2260 	nvme_epf->nr_vectors = 1;
2261 	nvme_epf->irq_type = PCI_IRQ_INTX;
2262 
2263 	return 0;
2264 }
2265 
2266 static int nvmet_pci_epf_epc_init(struct pci_epf *epf)
2267 {
2268 	struct nvmet_pci_epf *nvme_epf = epf_get_drvdata(epf);
2269 	const struct pci_epc_features *epc_features = nvme_epf->epc_features;
2270 	struct nvmet_pci_epf_ctrl *ctrl = &nvme_epf->ctrl;
2271 	unsigned int max_nr_queues = NVMET_NR_QUEUES;
2272 	int ret;
2273 
2274 	/* For now, do not support virtual functions. */
2275 	if (epf->vfunc_no > 0) {
2276 		dev_err(&epf->dev, "Virtual functions are not supported\n");
2277 		return -EINVAL;
2278 	}
2279 
2280 	/*
2281 	 * Cap the maximum number of queues we can support on the controller
2282 	 * with the number of IRQs we can use.
2283 	 */
2284 	if (epc_features->msix_capable && epf->msix_interrupts) {
2285 		dev_info(&epf->dev,
2286 			 "PCI endpoint controller supports MSI-X, %u vectors\n",
2287 			 epf->msix_interrupts);
2288 		max_nr_queues = min(max_nr_queues, epf->msix_interrupts);
2289 	} else if (epc_features->msi_capable && epf->msi_interrupts) {
2290 		dev_info(&epf->dev,
2291 			 "PCI endpoint controller supports MSI, %u vectors\n",
2292 			 epf->msi_interrupts);
2293 		max_nr_queues = min(max_nr_queues, epf->msi_interrupts);
2294 	}
2295 
2296 	if (max_nr_queues < 2) {
2297 		dev_err(&epf->dev, "Invalid maximum number of queues %u\n",
2298 			max_nr_queues);
2299 		return -EINVAL;
2300 	}
2301 
2302 	/* Create the target controller. */
2303 	ret = nvmet_pci_epf_create_ctrl(nvme_epf, max_nr_queues);
2304 	if (ret) {
2305 		dev_err(&epf->dev,
2306 			"Failed to create NVMe PCI target controller (err=%d)\n",
2307 			ret);
2308 		return ret;
2309 	}
2310 
2311 	nvmet_pci_epf_init_dma(nvme_epf);
2312 
2313 	/* Set device ID, class, etc. */
2314 	epf->header->vendorid = ctrl->tctrl->subsys->vendor_id;
2315 	epf->header->subsys_vendor_id = ctrl->tctrl->subsys->subsys_vendor_id;
2316 	ret = pci_epc_write_header(epf->epc, epf->func_no, epf->vfunc_no,
2317 				   epf->header);
2318 	if (ret) {
2319 		dev_err(&epf->dev,
2320 			"Failed to write configuration header (err=%d)\n", ret);
2321 		goto out_destroy_ctrl;
2322 	}
2323 
2324 	ret = pci_epc_set_bar(epf->epc, epf->func_no, epf->vfunc_no,
2325 			      &epf->bar[BAR_0]);
2326 	if (ret) {
2327 		dev_err(&epf->dev, "Failed to set BAR 0 (err=%d)\n", ret);
2328 		goto out_destroy_ctrl;
2329 	}
2330 
2331 	/*
2332 	 * Enable interrupts and start polling the controller BAR if we do not
2333 	 * have a link up notifier.
2334 	 */
2335 	ret = nvmet_pci_epf_init_irq(nvme_epf);
2336 	if (ret)
2337 		goto out_clear_bar;
2338 
2339 	if (!epc_features->linkup_notifier)
2340 		nvmet_pci_epf_start_ctrl(&nvme_epf->ctrl);
2341 
2342 	return 0;
2343 
2344 out_clear_bar:
2345 	nvmet_pci_epf_clear_bar(nvme_epf);
2346 out_destroy_ctrl:
2347 	nvmet_pci_epf_destroy_ctrl(&nvme_epf->ctrl);
2348 	return ret;
2349 }
2350 
2351 static void nvmet_pci_epf_epc_deinit(struct pci_epf *epf)
2352 {
2353 	struct nvmet_pci_epf *nvme_epf = epf_get_drvdata(epf);
2354 	struct nvmet_pci_epf_ctrl *ctrl = &nvme_epf->ctrl;
2355 
2356 	nvmet_pci_epf_destroy_ctrl(ctrl);
2357 
2358 	nvmet_pci_epf_deinit_dma(nvme_epf);
2359 	nvmet_pci_epf_clear_bar(nvme_epf);
2360 }
2361 
2362 static int nvmet_pci_epf_link_up(struct pci_epf *epf)
2363 {
2364 	struct nvmet_pci_epf *nvme_epf = epf_get_drvdata(epf);
2365 	struct nvmet_pci_epf_ctrl *ctrl = &nvme_epf->ctrl;
2366 
2367 	nvmet_pci_epf_start_ctrl(ctrl);
2368 
2369 	return 0;
2370 }
2371 
2372 static int nvmet_pci_epf_link_down(struct pci_epf *epf)
2373 {
2374 	struct nvmet_pci_epf *nvme_epf = epf_get_drvdata(epf);
2375 	struct nvmet_pci_epf_ctrl *ctrl = &nvme_epf->ctrl;
2376 
2377 	nvmet_pci_epf_stop_ctrl(ctrl);
2378 
2379 	return 0;
2380 }
2381 
2382 static const struct pci_epc_event_ops nvmet_pci_epf_event_ops = {
2383 	.epc_init = nvmet_pci_epf_epc_init,
2384 	.epc_deinit = nvmet_pci_epf_epc_deinit,
2385 	.link_up = nvmet_pci_epf_link_up,
2386 	.link_down = nvmet_pci_epf_link_down,
2387 };
2388 
2389 static int nvmet_pci_epf_bind(struct pci_epf *epf)
2390 {
2391 	struct nvmet_pci_epf *nvme_epf = epf_get_drvdata(epf);
2392 	const struct pci_epc_features *epc_features;
2393 	struct pci_epc *epc = epf->epc;
2394 	int ret;
2395 
2396 	if (WARN_ON_ONCE(!epc))
2397 		return -EINVAL;
2398 
2399 	epc_features = pci_epc_get_features(epc, epf->func_no, epf->vfunc_no);
2400 	if (!epc_features) {
2401 		dev_err(&epf->dev, "epc_features not implemented\n");
2402 		return -EOPNOTSUPP;
2403 	}
2404 	nvme_epf->epc_features = epc_features;
2405 
2406 	ret = nvmet_pci_epf_configure_bar(nvme_epf);
2407 	if (ret)
2408 		return ret;
2409 
2410 	return 0;
2411 }
2412 
2413 static void nvmet_pci_epf_unbind(struct pci_epf *epf)
2414 {
2415 	struct nvmet_pci_epf *nvme_epf = epf_get_drvdata(epf);
2416 	struct pci_epc *epc = epf->epc;
2417 
2418 	nvmet_pci_epf_destroy_ctrl(&nvme_epf->ctrl);
2419 
2420 	if (epc->init_complete) {
2421 		nvmet_pci_epf_deinit_dma(nvme_epf);
2422 		nvmet_pci_epf_clear_bar(nvme_epf);
2423 	}
2424 
2425 	nvmet_pci_epf_free_bar(nvme_epf);
2426 }
2427 
2428 static struct pci_epf_header nvme_epf_pci_header = {
2429 	.vendorid	= PCI_ANY_ID,
2430 	.deviceid	= PCI_ANY_ID,
2431 	.progif_code	= 0x02, /* NVM Express */
2432 	.baseclass_code = PCI_BASE_CLASS_STORAGE,
2433 	.subclass_code	= 0x08, /* Non-Volatile Memory controller */
2434 	.interrupt_pin	= PCI_INTERRUPT_INTA,
2435 };
2436 
2437 static int nvmet_pci_epf_probe(struct pci_epf *epf,
2438 			       const struct pci_epf_device_id *id)
2439 {
2440 	struct nvmet_pci_epf *nvme_epf;
2441 	int ret;
2442 
2443 	nvme_epf = devm_kzalloc(&epf->dev, sizeof(*nvme_epf), GFP_KERNEL);
2444 	if (!nvme_epf)
2445 		return -ENOMEM;
2446 
2447 	ret = devm_mutex_init(&epf->dev, &nvme_epf->mmio_lock);
2448 	if (ret)
2449 		return ret;
2450 
2451 	nvme_epf->epf = epf;
2452 	nvme_epf->mdts_kb = NVMET_PCI_EPF_MDTS_KB;
2453 
2454 	epf->event_ops = &nvmet_pci_epf_event_ops;
2455 	epf->header = &nvme_epf_pci_header;
2456 	epf_set_drvdata(epf, nvme_epf);
2457 
2458 	return 0;
2459 }
2460 
2461 #define to_nvme_epf(epf_group)	\
2462 	container_of(epf_group, struct nvmet_pci_epf, group)
2463 
2464 static ssize_t nvmet_pci_epf_portid_show(struct config_item *item, char *page)
2465 {
2466 	struct config_group *group = to_config_group(item);
2467 	struct nvmet_pci_epf *nvme_epf = to_nvme_epf(group);
2468 
2469 	return sysfs_emit(page, "%u\n", le16_to_cpu(nvme_epf->portid));
2470 }
2471 
2472 static ssize_t nvmet_pci_epf_portid_store(struct config_item *item,
2473 					  const char *page, size_t len)
2474 {
2475 	struct config_group *group = to_config_group(item);
2476 	struct nvmet_pci_epf *nvme_epf = to_nvme_epf(group);
2477 	u16 portid;
2478 
2479 	/* Do not allow setting this when the function is already started. */
2480 	if (nvme_epf->ctrl.tctrl)
2481 		return -EBUSY;
2482 
2483 	if (!len)
2484 		return -EINVAL;
2485 
2486 	if (kstrtou16(page, 0, &portid))
2487 		return -EINVAL;
2488 
2489 	nvme_epf->portid = cpu_to_le16(portid);
2490 
2491 	return len;
2492 }
2493 
2494 CONFIGFS_ATTR(nvmet_pci_epf_, portid);
2495 
2496 static ssize_t nvmet_pci_epf_subsysnqn_show(struct config_item *item,
2497 					    char *page)
2498 {
2499 	struct config_group *group = to_config_group(item);
2500 	struct nvmet_pci_epf *nvme_epf = to_nvme_epf(group);
2501 
2502 	return sysfs_emit(page, "%s\n", nvme_epf->subsysnqn);
2503 }
2504 
2505 static ssize_t nvmet_pci_epf_subsysnqn_store(struct config_item *item,
2506 					     const char *page, size_t len)
2507 {
2508 	struct config_group *group = to_config_group(item);
2509 	struct nvmet_pci_epf *nvme_epf = to_nvme_epf(group);
2510 
2511 	/* Do not allow setting this when the function is already started. */
2512 	if (nvme_epf->ctrl.tctrl)
2513 		return -EBUSY;
2514 
2515 	if (!len)
2516 		return -EINVAL;
2517 
2518 	strscpy(nvme_epf->subsysnqn, page, len);
2519 
2520 	return len;
2521 }
2522 
2523 CONFIGFS_ATTR(nvmet_pci_epf_, subsysnqn);
2524 
2525 static ssize_t nvmet_pci_epf_mdts_kb_show(struct config_item *item, char *page)
2526 {
2527 	struct config_group *group = to_config_group(item);
2528 	struct nvmet_pci_epf *nvme_epf = to_nvme_epf(group);
2529 
2530 	return sysfs_emit(page, "%u\n", nvme_epf->mdts_kb);
2531 }
2532 
2533 static ssize_t nvmet_pci_epf_mdts_kb_store(struct config_item *item,
2534 					   const char *page, size_t len)
2535 {
2536 	struct config_group *group = to_config_group(item);
2537 	struct nvmet_pci_epf *nvme_epf = to_nvme_epf(group);
2538 	unsigned long mdts_kb;
2539 	int ret;
2540 
2541 	if (nvme_epf->ctrl.tctrl)
2542 		return -EBUSY;
2543 
2544 	ret = kstrtoul(page, 0, &mdts_kb);
2545 	if (ret)
2546 		return ret;
2547 	if (!mdts_kb)
2548 		mdts_kb = NVMET_PCI_EPF_MDTS_KB;
2549 	else if (mdts_kb > NVMET_PCI_EPF_MAX_MDTS_KB)
2550 		mdts_kb = NVMET_PCI_EPF_MAX_MDTS_KB;
2551 
2552 	if (!is_power_of_2(mdts_kb))
2553 		return -EINVAL;
2554 
2555 	nvme_epf->mdts_kb = mdts_kb;
2556 
2557 	return len;
2558 }
2559 
2560 CONFIGFS_ATTR(nvmet_pci_epf_, mdts_kb);
2561 
2562 static struct configfs_attribute *nvmet_pci_epf_attrs[] = {
2563 	&nvmet_pci_epf_attr_portid,
2564 	&nvmet_pci_epf_attr_subsysnqn,
2565 	&nvmet_pci_epf_attr_mdts_kb,
2566 	NULL,
2567 };
2568 
2569 static const struct config_item_type nvmet_pci_epf_group_type = {
2570 	.ct_attrs	= nvmet_pci_epf_attrs,
2571 	.ct_owner	= THIS_MODULE,
2572 };
2573 
2574 static struct config_group *nvmet_pci_epf_add_cfs(struct pci_epf *epf,
2575 						  struct config_group *group)
2576 {
2577 	struct nvmet_pci_epf *nvme_epf = epf_get_drvdata(epf);
2578 
2579 	config_group_init_type_name(&nvme_epf->group, "nvme",
2580 				    &nvmet_pci_epf_group_type);
2581 
2582 	return &nvme_epf->group;
2583 }
2584 
2585 static const struct pci_epf_device_id nvmet_pci_epf_ids[] = {
2586 	{ .name = "nvmet_pci_epf" },
2587 	{},
2588 };
2589 
2590 static struct pci_epf_ops nvmet_pci_epf_ops = {
2591 	.bind	= nvmet_pci_epf_bind,
2592 	.unbind	= nvmet_pci_epf_unbind,
2593 	.add_cfs = nvmet_pci_epf_add_cfs,
2594 };
2595 
2596 static struct pci_epf_driver nvmet_pci_epf_driver = {
2597 	.driver.name	= "nvmet_pci_epf",
2598 	.probe		= nvmet_pci_epf_probe,
2599 	.id_table	= nvmet_pci_epf_ids,
2600 	.ops		= &nvmet_pci_epf_ops,
2601 	.owner		= THIS_MODULE,
2602 };
2603 
2604 static int __init nvmet_pci_epf_init_module(void)
2605 {
2606 	int ret;
2607 
2608 	ret = pci_epf_register_driver(&nvmet_pci_epf_driver);
2609 	if (ret)
2610 		return ret;
2611 
2612 	ret = nvmet_register_transport(&nvmet_pci_epf_fabrics_ops);
2613 	if (ret) {
2614 		pci_epf_unregister_driver(&nvmet_pci_epf_driver);
2615 		return ret;
2616 	}
2617 
2618 	return 0;
2619 }
2620 
2621 static void __exit nvmet_pci_epf_cleanup_module(void)
2622 {
2623 	nvmet_unregister_transport(&nvmet_pci_epf_fabrics_ops);
2624 	pci_epf_unregister_driver(&nvmet_pci_epf_driver);
2625 }
2626 
2627 module_init(nvmet_pci_epf_init_module);
2628 module_exit(nvmet_pci_epf_cleanup_module);
2629 
2630 MODULE_DESCRIPTION("NVMe PCI Endpoint Function target driver");
2631 MODULE_AUTHOR("Damien Le Moal <dlemoal@kernel.org>");
2632 MODULE_LICENSE("GPL");
2633