xref: /linux/drivers/nvme/target/pci-epf.c (revision 66498c75b4f8017f62d720d9b59675bdf3abce91)
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 
nvmet_pci_epf_bar_read32(struct nvmet_pci_epf_ctrl * ctrl,u32 off)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 
nvmet_pci_epf_bar_write32(struct nvmet_pci_epf_ctrl * ctrl,u32 off,u32 val)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 
nvmet_pci_epf_bar_read64(struct nvmet_pci_epf_ctrl * ctrl,u32 off)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 
nvmet_pci_epf_bar_write64(struct nvmet_pci_epf_ctrl * ctrl,u32 off,u64 val)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 
nvmet_pci_epf_mem_map(struct nvmet_pci_epf * nvme_epf,u64 pci_addr,size_t size,struct pci_epc_map * map)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 
nvmet_pci_epf_mem_unmap(struct nvmet_pci_epf * nvme_epf,struct pci_epc_map * map)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 
nvmet_pci_epf_dma_filter(struct dma_chan * chan,void * arg)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 
nvmet_pci_epf_init_dma(struct nvmet_pci_epf * nvme_epf)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 
nvmet_pci_epf_deinit_dma(struct nvmet_pci_epf * nvme_epf)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 
nvmet_pci_epf_dma_transfer(struct nvmet_pci_epf * nvme_epf,struct nvmet_pci_epf_segment * seg,enum dma_data_direction dir)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 
nvmet_pci_epf_mmio_transfer(struct nvmet_pci_epf * nvme_epf,struct nvmet_pci_epf_segment * seg,enum dma_data_direction dir)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 
nvmet_pci_epf_transfer_seg(struct nvmet_pci_epf * nvme_epf,struct nvmet_pci_epf_segment * seg,enum dma_data_direction dir)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 
nvmet_pci_epf_transfer(struct nvmet_pci_epf_ctrl * ctrl,void * buf,u64 pci_addr,u32 length,enum dma_data_direction dir)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 
nvmet_pci_epf_alloc_irq_vectors(struct nvmet_pci_epf_ctrl * ctrl)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 
nvmet_pci_epf_free_irq_vectors(struct nvmet_pci_epf_ctrl * ctrl)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 *
nvmet_pci_epf_find_irq_vector(struct nvmet_pci_epf_ctrl * ctrl,u16 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 *
nvmet_pci_epf_add_irq_vector(struct nvmet_pci_epf_ctrl * ctrl,u16 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 
nvmet_pci_epf_remove_irq_vector(struct nvmet_pci_epf_ctrl * ctrl,u16 vector)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 
nvmet_pci_epf_should_raise_irq(struct nvmet_pci_epf_ctrl * ctrl,struct nvmet_pci_epf_queue * cq,bool force)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 
nvmet_pci_epf_raise_irq(struct nvmet_pci_epf_ctrl * ctrl,struct nvmet_pci_epf_queue * cq,bool force)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 
nvmet_pci_epf_iod_name(struct nvmet_pci_epf_iod * iod)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 *
nvmet_pci_epf_alloc_iod(struct nvmet_pci_epf_queue * sq)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  */
nvmet_pci_epf_alloc_iod_data_segs(struct nvmet_pci_epf_iod * iod,int nsegs)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 
nvmet_pci_epf_free_iod(struct nvmet_pci_epf_iod * iod)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 
nvmet_pci_epf_transfer_iod_data(struct nvmet_pci_epf_iod * iod)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 
nvmet_pci_epf_prp_ofst(struct nvmet_pci_epf_ctrl * ctrl,u64 prp)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 
nvmet_pci_epf_prp_size(struct nvmet_pci_epf_ctrl * ctrl,u64 prp)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  */
nvmet_pci_epf_get_prp_list(struct nvmet_pci_epf_ctrl * ctrl,u64 prp,size_t xfer_len,__le64 * prps)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 
nvmet_pci_epf_iod_parse_prp_list(struct nvmet_pci_epf_ctrl * ctrl,struct nvmet_pci_epf_iod * iod)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 
nvmet_pci_epf_iod_parse_prp_simple(struct nvmet_pci_epf_ctrl * ctrl,struct nvmet_pci_epf_iod * iod)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 
nvmet_pci_epf_iod_parse_prps(struct nvmet_pci_epf_iod * iod)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 *
nvmet_pci_epf_get_sgl_segment(struct nvmet_pci_epf_ctrl * ctrl,struct nvme_sgl_desc * desc,unsigned int * nr_sgls)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 	buf = kmalloc(length, GFP_KERNEL);
982 	if (!buf)
983 		return NULL;
984 
985 	ret = nvmet_pci_epf_transfer(ctrl, buf, le64_to_cpu(desc->addr), length,
986 				     DMA_FROM_DEVICE);
987 	if (ret) {
988 		kfree(buf);
989 		return NULL;
990 	}
991 
992 	sgls = buf;
993 	nr_descs = length / sizeof(struct nvme_sgl_desc);
994 	if (sgls[nr_descs - 1].type == (NVME_SGL_FMT_SEG_DESC << 4) ||
995 	    sgls[nr_descs - 1].type == (NVME_SGL_FMT_LAST_SEG_DESC << 4)) {
996 		/*
997 		 * We have another SGL segment following this one: do not count
998 		 * it as a regular data SGL descriptor and return it to the
999 		 * caller.
1000 		 */
1001 		*desc = sgls[nr_descs - 1];
1002 		nr_descs--;
1003 	} else {
1004 		/* We do not have another SGL segment after this one. */
1005 		desc->length = 0;
1006 	}
1007 
1008 	*nr_sgls = nr_descs;
1009 
1010 	return sgls;
1011 }
1012 
nvmet_pci_epf_iod_parse_sgl_segments(struct nvmet_pci_epf_ctrl * ctrl,struct nvmet_pci_epf_iod * iod)1013 static int nvmet_pci_epf_iod_parse_sgl_segments(struct nvmet_pci_epf_ctrl *ctrl,
1014 						struct nvmet_pci_epf_iod *iod)
1015 {
1016 	struct nvme_command *cmd = &iod->cmd;
1017 	struct nvme_sgl_desc seg = cmd->common.dptr.sgl;
1018 	struct nvme_sgl_desc *sgls = NULL;
1019 	int n = 0, i, nr_sgls;
1020 	int ret;
1021 
1022 	/*
1023 	 * We do not support inline data nor keyed SGLs, so we should be seeing
1024 	 * only segment descriptors.
1025 	 */
1026 	if (seg.type != (NVME_SGL_FMT_SEG_DESC << 4) &&
1027 	    seg.type != (NVME_SGL_FMT_LAST_SEG_DESC << 4)) {
1028 		iod->status = NVME_SC_SGL_INVALID_TYPE | NVME_STATUS_DNR;
1029 		return -EIO;
1030 	}
1031 
1032 	while (seg.length) {
1033 		sgls = nvmet_pci_epf_get_sgl_segment(ctrl, &seg, &nr_sgls);
1034 		if (!sgls) {
1035 			iod->status = NVME_SC_INTERNAL | NVME_STATUS_DNR;
1036 			return -EIO;
1037 		}
1038 
1039 		/* Grow the PCI segment table as needed. */
1040 		ret = nvmet_pci_epf_alloc_iod_data_segs(iod, nr_sgls);
1041 		if (ret) {
1042 			iod->status = NVME_SC_INTERNAL | NVME_STATUS_DNR;
1043 			goto out;
1044 		}
1045 
1046 		/*
1047 		 * Parse the SGL descriptors to build the PCI segment table,
1048 		 * checking the descriptor type as we go.
1049 		 */
1050 		for (i = 0; i < nr_sgls; i++) {
1051 			if (sgls[i].type != (NVME_SGL_FMT_DATA_DESC << 4)) {
1052 				iod->status = NVME_SC_SGL_INVALID_TYPE |
1053 					NVME_STATUS_DNR;
1054 				goto out;
1055 			}
1056 			iod->data_segs[n].pci_addr = le64_to_cpu(sgls[i].addr);
1057 			iod->data_segs[n].length = le32_to_cpu(sgls[i].length);
1058 			n++;
1059 		}
1060 
1061 		kfree(sgls);
1062 	}
1063 
1064  out:
1065 	if (iod->status != NVME_SC_SUCCESS) {
1066 		kfree(sgls);
1067 		return -EIO;
1068 	}
1069 
1070 	return 0;
1071 }
1072 
nvmet_pci_epf_iod_parse_sgls(struct nvmet_pci_epf_iod * iod)1073 static int nvmet_pci_epf_iod_parse_sgls(struct nvmet_pci_epf_iod *iod)
1074 {
1075 	struct nvmet_pci_epf_ctrl *ctrl = iod->ctrl;
1076 	struct nvme_sgl_desc *sgl = &iod->cmd.common.dptr.sgl;
1077 
1078 	if (sgl->type == (NVME_SGL_FMT_DATA_DESC << 4)) {
1079 		/* Single data descriptor case. */
1080 		iod->nr_data_segs = 1;
1081 		iod->data_segs = &iod->data_seg;
1082 		iod->data_seg.pci_addr = le64_to_cpu(sgl->addr);
1083 		iod->data_seg.length = le32_to_cpu(sgl->length);
1084 		return 0;
1085 	}
1086 
1087 	return nvmet_pci_epf_iod_parse_sgl_segments(ctrl, iod);
1088 }
1089 
nvmet_pci_epf_alloc_iod_data_buf(struct nvmet_pci_epf_iod * iod)1090 static int nvmet_pci_epf_alloc_iod_data_buf(struct nvmet_pci_epf_iod *iod)
1091 {
1092 	struct nvmet_pci_epf_ctrl *ctrl = iod->ctrl;
1093 	struct nvmet_req *req = &iod->req;
1094 	struct nvmet_pci_epf_segment *seg;
1095 	struct scatterlist *sg;
1096 	int ret, i;
1097 
1098 	if (iod->data_len > ctrl->mdts) {
1099 		iod->status = NVME_SC_INVALID_FIELD | NVME_STATUS_DNR;
1100 		return -EINVAL;
1101 	}
1102 
1103 	/*
1104 	 * Get the PCI address segments for the command data buffer using either
1105 	 * its SGLs or PRPs.
1106 	 */
1107 	if (iod->cmd.common.flags & NVME_CMD_SGL_ALL)
1108 		ret = nvmet_pci_epf_iod_parse_sgls(iod);
1109 	else
1110 		ret = nvmet_pci_epf_iod_parse_prps(iod);
1111 	if (ret)
1112 		return ret;
1113 
1114 	/* Get a command buffer using SGLs matching the PCI segments. */
1115 	if (iod->nr_data_segs == 1) {
1116 		sg_init_table(&iod->data_sgl, 1);
1117 		iod->data_sgt.sgl = &iod->data_sgl;
1118 		iod->data_sgt.nents = 1;
1119 		iod->data_sgt.orig_nents = 1;
1120 	} else {
1121 		ret = sg_alloc_table(&iod->data_sgt, iod->nr_data_segs,
1122 				     GFP_KERNEL);
1123 		if (ret)
1124 			goto err_nomem;
1125 	}
1126 
1127 	for_each_sgtable_sg(&iod->data_sgt, sg, i) {
1128 		seg = &iod->data_segs[i];
1129 		seg->buf = kmalloc(seg->length, GFP_KERNEL);
1130 		if (!seg->buf)
1131 			goto err_nomem;
1132 		sg_set_buf(sg, seg->buf, seg->length);
1133 	}
1134 
1135 	req->transfer_len = iod->data_len;
1136 	req->sg = iod->data_sgt.sgl;
1137 	req->sg_cnt = iod->data_sgt.nents;
1138 
1139 	return 0;
1140 
1141 err_nomem:
1142 	iod->status = NVME_SC_INTERNAL | NVME_STATUS_DNR;
1143 	return -ENOMEM;
1144 }
1145 
nvmet_pci_epf_complete_iod(struct nvmet_pci_epf_iod * iod)1146 static void nvmet_pci_epf_complete_iod(struct nvmet_pci_epf_iod *iod)
1147 {
1148 	struct nvmet_pci_epf_queue *cq = iod->cq;
1149 	unsigned long flags;
1150 
1151 	/* Print an error message for failed commands, except AENs. */
1152 	iod->status = le16_to_cpu(iod->cqe.status) >> 1;
1153 	if (iod->status && iod->cmd.common.opcode != nvme_admin_async_event)
1154 		dev_err(iod->ctrl->dev,
1155 			"CQ[%d]: Command %s (0x%x) status 0x%0x\n",
1156 			iod->sq->qid, nvmet_pci_epf_iod_name(iod),
1157 			iod->cmd.common.opcode, iod->status);
1158 
1159 	/*
1160 	 * Add the command to the list of completed commands and schedule the
1161 	 * CQ work.
1162 	 */
1163 	spin_lock_irqsave(&cq->lock, flags);
1164 	list_add_tail(&iod->link, &cq->list);
1165 	queue_delayed_work(system_highpri_wq, &cq->work, 0);
1166 	spin_unlock_irqrestore(&cq->lock, flags);
1167 }
1168 
nvmet_pci_epf_drain_queue(struct nvmet_pci_epf_queue * queue)1169 static void nvmet_pci_epf_drain_queue(struct nvmet_pci_epf_queue *queue)
1170 {
1171 	struct nvmet_pci_epf_iod *iod;
1172 	unsigned long flags;
1173 
1174 	spin_lock_irqsave(&queue->lock, flags);
1175 	while (!list_empty(&queue->list)) {
1176 		iod = list_first_entry(&queue->list, struct nvmet_pci_epf_iod,
1177 				       link);
1178 		list_del_init(&iod->link);
1179 		nvmet_pci_epf_free_iod(iod);
1180 	}
1181 	spin_unlock_irqrestore(&queue->lock, flags);
1182 }
1183 
nvmet_pci_epf_add_port(struct nvmet_port * port)1184 static int nvmet_pci_epf_add_port(struct nvmet_port *port)
1185 {
1186 	mutex_lock(&nvmet_pci_epf_ports_mutex);
1187 	list_add_tail(&port->entry, &nvmet_pci_epf_ports);
1188 	mutex_unlock(&nvmet_pci_epf_ports_mutex);
1189 	return 0;
1190 }
1191 
nvmet_pci_epf_remove_port(struct nvmet_port * port)1192 static void nvmet_pci_epf_remove_port(struct nvmet_port *port)
1193 {
1194 	mutex_lock(&nvmet_pci_epf_ports_mutex);
1195 	list_del_init(&port->entry);
1196 	mutex_unlock(&nvmet_pci_epf_ports_mutex);
1197 }
1198 
1199 static struct nvmet_port *
nvmet_pci_epf_find_port(struct nvmet_pci_epf_ctrl * ctrl,__le16 portid)1200 nvmet_pci_epf_find_port(struct nvmet_pci_epf_ctrl *ctrl, __le16 portid)
1201 {
1202 	struct nvmet_port *p, *port = NULL;
1203 
1204 	mutex_lock(&nvmet_pci_epf_ports_mutex);
1205 	list_for_each_entry(p, &nvmet_pci_epf_ports, entry) {
1206 		if (p->disc_addr.portid == portid) {
1207 			port = p;
1208 			break;
1209 		}
1210 	}
1211 	mutex_unlock(&nvmet_pci_epf_ports_mutex);
1212 
1213 	return port;
1214 }
1215 
nvmet_pci_epf_queue_response(struct nvmet_req * req)1216 static void nvmet_pci_epf_queue_response(struct nvmet_req *req)
1217 {
1218 	struct nvmet_pci_epf_iod *iod =
1219 		container_of(req, struct nvmet_pci_epf_iod, req);
1220 
1221 	iod->status = le16_to_cpu(req->cqe->status) >> 1;
1222 
1223 	/*
1224 	 * If the command failed or we have no data to transfer, complete the
1225 	 * command immediately.
1226 	 */
1227 	if (iod->status || !iod->data_len || iod->dma_dir != DMA_TO_DEVICE) {
1228 		nvmet_pci_epf_complete_iod(iod);
1229 		return;
1230 	}
1231 
1232 	complete(&iod->done);
1233 }
1234 
nvmet_pci_epf_get_mdts(const struct nvmet_ctrl * tctrl)1235 static u8 nvmet_pci_epf_get_mdts(const struct nvmet_ctrl *tctrl)
1236 {
1237 	struct nvmet_pci_epf_ctrl *ctrl = tctrl->drvdata;
1238 	int page_shift = NVME_CAP_MPSMIN(tctrl->cap) + 12;
1239 
1240 	return ilog2(ctrl->mdts) - page_shift;
1241 }
1242 
nvmet_pci_epf_create_cq(struct nvmet_ctrl * tctrl,u16 cqid,u16 flags,u16 qsize,u64 pci_addr,u16 vector)1243 static u16 nvmet_pci_epf_create_cq(struct nvmet_ctrl *tctrl,
1244 		u16 cqid, u16 flags, u16 qsize, u64 pci_addr, u16 vector)
1245 {
1246 	struct nvmet_pci_epf_ctrl *ctrl = tctrl->drvdata;
1247 	struct nvmet_pci_epf_queue *cq = &ctrl->cq[cqid];
1248 	u16 status;
1249 	int ret;
1250 
1251 	if (test_bit(NVMET_PCI_EPF_Q_LIVE, &cq->flags))
1252 		return NVME_SC_QID_INVALID | NVME_STATUS_DNR;
1253 
1254 	if (!(flags & NVME_QUEUE_PHYS_CONTIG))
1255 		return NVME_SC_INVALID_QUEUE | NVME_STATUS_DNR;
1256 
1257 	cq->pci_addr = pci_addr;
1258 	cq->qid = cqid;
1259 	cq->depth = qsize + 1;
1260 	cq->vector = vector;
1261 	cq->head = 0;
1262 	cq->tail = 0;
1263 	cq->phase = 1;
1264 	cq->db = NVME_REG_DBS + (((cqid * 2) + 1) * sizeof(u32));
1265 	nvmet_pci_epf_bar_write32(ctrl, cq->db, 0);
1266 
1267 	if (!cqid)
1268 		cq->qes = sizeof(struct nvme_completion);
1269 	else
1270 		cq->qes = ctrl->io_cqes;
1271 	cq->pci_size = cq->qes * cq->depth;
1272 
1273 	if (flags & NVME_CQ_IRQ_ENABLED) {
1274 		cq->iv = nvmet_pci_epf_add_irq_vector(ctrl, vector);
1275 		if (!cq->iv)
1276 			return NVME_SC_INTERNAL | NVME_STATUS_DNR;
1277 		set_bit(NVMET_PCI_EPF_Q_IRQ_ENABLED, &cq->flags);
1278 	}
1279 
1280 	status = nvmet_cq_create(tctrl, &cq->nvme_cq, cqid, cq->depth);
1281 	if (status != NVME_SC_SUCCESS)
1282 		goto err;
1283 
1284 	/*
1285 	 * Map the CQ PCI address space and since PCI endpoint controllers may
1286 	 * return a partial mapping, check that the mapping is large enough.
1287 	 */
1288 	ret = nvmet_pci_epf_mem_map(ctrl->nvme_epf, cq->pci_addr, cq->pci_size,
1289 				    &cq->pci_map);
1290 	if (ret) {
1291 		dev_err(ctrl->dev, "Failed to map CQ %u (err=%d)\n",
1292 			cq->qid, ret);
1293 		goto err_internal;
1294 	}
1295 
1296 	if (cq->pci_map.pci_size < cq->pci_size) {
1297 		dev_err(ctrl->dev, "Invalid partial mapping of queue %u\n",
1298 			cq->qid);
1299 		goto err_unmap_queue;
1300 	}
1301 
1302 	set_bit(NVMET_PCI_EPF_Q_LIVE, &cq->flags);
1303 
1304 	if (test_bit(NVMET_PCI_EPF_Q_IRQ_ENABLED, &cq->flags))
1305 		dev_dbg(ctrl->dev,
1306 			"CQ[%u]: %u entries of %zu B, IRQ vector %u\n",
1307 			cqid, qsize, cq->qes, cq->vector);
1308 	else
1309 		dev_dbg(ctrl->dev,
1310 			"CQ[%u]: %u entries of %zu B, IRQ disabled\n",
1311 			cqid, qsize, cq->qes);
1312 
1313 	return NVME_SC_SUCCESS;
1314 
1315 err_unmap_queue:
1316 	nvmet_pci_epf_mem_unmap(ctrl->nvme_epf, &cq->pci_map);
1317 err_internal:
1318 	status = NVME_SC_INTERNAL | NVME_STATUS_DNR;
1319 	nvmet_cq_put(&cq->nvme_cq);
1320 err:
1321 	if (test_and_clear_bit(NVMET_PCI_EPF_Q_IRQ_ENABLED, &cq->flags))
1322 		nvmet_pci_epf_remove_irq_vector(ctrl, cq->vector);
1323 	return status;
1324 }
1325 
nvmet_pci_epf_delete_cq(struct nvmet_ctrl * tctrl,u16 cqid)1326 static u16 nvmet_pci_epf_delete_cq(struct nvmet_ctrl *tctrl, u16 cqid)
1327 {
1328 	struct nvmet_pci_epf_ctrl *ctrl = tctrl->drvdata;
1329 	struct nvmet_pci_epf_queue *cq = &ctrl->cq[cqid];
1330 
1331 	if (!test_and_clear_bit(NVMET_PCI_EPF_Q_LIVE, &cq->flags))
1332 		return NVME_SC_QID_INVALID | NVME_STATUS_DNR;
1333 
1334 	cancel_delayed_work_sync(&cq->work);
1335 	nvmet_pci_epf_drain_queue(cq);
1336 	if (test_and_clear_bit(NVMET_PCI_EPF_Q_IRQ_ENABLED, &cq->flags))
1337 		nvmet_pci_epf_remove_irq_vector(ctrl, cq->vector);
1338 	nvmet_pci_epf_mem_unmap(ctrl->nvme_epf, &cq->pci_map);
1339 	nvmet_cq_put(&cq->nvme_cq);
1340 
1341 	return NVME_SC_SUCCESS;
1342 }
1343 
nvmet_pci_epf_create_sq(struct nvmet_ctrl * tctrl,u16 sqid,u16 cqid,u16 flags,u16 qsize,u64 pci_addr)1344 static u16 nvmet_pci_epf_create_sq(struct nvmet_ctrl *tctrl,
1345 		u16 sqid, u16 cqid, u16 flags, u16 qsize, u64 pci_addr)
1346 {
1347 	struct nvmet_pci_epf_ctrl *ctrl = tctrl->drvdata;
1348 	struct nvmet_pci_epf_queue *sq = &ctrl->sq[sqid];
1349 	struct nvmet_pci_epf_queue *cq = &ctrl->cq[cqid];
1350 	u16 status;
1351 
1352 	if (test_bit(NVMET_PCI_EPF_Q_LIVE, &sq->flags))
1353 		return NVME_SC_QID_INVALID | NVME_STATUS_DNR;
1354 
1355 	if (!(flags & NVME_QUEUE_PHYS_CONTIG))
1356 		return NVME_SC_INVALID_QUEUE | NVME_STATUS_DNR;
1357 
1358 	sq->pci_addr = pci_addr;
1359 	sq->qid = sqid;
1360 	sq->depth = qsize + 1;
1361 	sq->head = 0;
1362 	sq->tail = 0;
1363 	sq->phase = 0;
1364 	sq->db = NVME_REG_DBS + (sqid * 2 * sizeof(u32));
1365 	nvmet_pci_epf_bar_write32(ctrl, sq->db, 0);
1366 	if (!sqid)
1367 		sq->qes = 1UL << NVME_ADM_SQES;
1368 	else
1369 		sq->qes = ctrl->io_sqes;
1370 	sq->pci_size = sq->qes * sq->depth;
1371 
1372 	status = nvmet_sq_create(tctrl, &sq->nvme_sq, &cq->nvme_cq, sqid,
1373 			sq->depth);
1374 	if (status != NVME_SC_SUCCESS)
1375 		return status;
1376 
1377 	sq->iod_wq = alloc_workqueue("sq%d_wq", WQ_UNBOUND,
1378 				min_t(int, sq->depth, WQ_MAX_ACTIVE), sqid);
1379 	if (!sq->iod_wq) {
1380 		dev_err(ctrl->dev, "Failed to create SQ %d work queue\n", sqid);
1381 		status = NVME_SC_INTERNAL | NVME_STATUS_DNR;
1382 		goto out_destroy_sq;
1383 	}
1384 
1385 	set_bit(NVMET_PCI_EPF_Q_LIVE, &sq->flags);
1386 
1387 	dev_dbg(ctrl->dev, "SQ[%u]: %u entries of %zu B\n",
1388 		sqid, qsize, sq->qes);
1389 
1390 	return NVME_SC_SUCCESS;
1391 
1392 out_destroy_sq:
1393 	nvmet_sq_destroy(&sq->nvme_sq);
1394 	return status;
1395 }
1396 
nvmet_pci_epf_delete_sq(struct nvmet_ctrl * tctrl,u16 sqid)1397 static u16 nvmet_pci_epf_delete_sq(struct nvmet_ctrl *tctrl, u16 sqid)
1398 {
1399 	struct nvmet_pci_epf_ctrl *ctrl = tctrl->drvdata;
1400 	struct nvmet_pci_epf_queue *sq = &ctrl->sq[sqid];
1401 
1402 	if (!test_and_clear_bit(NVMET_PCI_EPF_Q_LIVE, &sq->flags))
1403 		return NVME_SC_QID_INVALID | NVME_STATUS_DNR;
1404 
1405 	destroy_workqueue(sq->iod_wq);
1406 	sq->iod_wq = NULL;
1407 
1408 	nvmet_pci_epf_drain_queue(sq);
1409 
1410 	if (sq->nvme_sq.ctrl)
1411 		nvmet_sq_destroy(&sq->nvme_sq);
1412 
1413 	return NVME_SC_SUCCESS;
1414 }
1415 
nvmet_pci_epf_get_feat(const struct nvmet_ctrl * tctrl,u8 feat,void * data)1416 static u16 nvmet_pci_epf_get_feat(const struct nvmet_ctrl *tctrl,
1417 				  u8 feat, void *data)
1418 {
1419 	struct nvmet_pci_epf_ctrl *ctrl = tctrl->drvdata;
1420 	struct nvmet_feat_arbitration *arb;
1421 	struct nvmet_feat_irq_coalesce *irqc;
1422 	struct nvmet_feat_irq_config *irqcfg;
1423 	struct nvmet_pci_epf_irq_vector *iv;
1424 	u16 status;
1425 
1426 	switch (feat) {
1427 	case NVME_FEAT_ARBITRATION:
1428 		arb = data;
1429 		if (!ctrl->sq_ab)
1430 			arb->ab = 0x7;
1431 		else
1432 			arb->ab = ilog2(ctrl->sq_ab);
1433 		return NVME_SC_SUCCESS;
1434 
1435 	case NVME_FEAT_IRQ_COALESCE:
1436 		irqc = data;
1437 		irqc->thr = ctrl->irq_vector_threshold;
1438 		irqc->time = 0;
1439 		return NVME_SC_SUCCESS;
1440 
1441 	case NVME_FEAT_IRQ_CONFIG:
1442 		irqcfg = data;
1443 		mutex_lock(&ctrl->irq_lock);
1444 		iv = nvmet_pci_epf_find_irq_vector(ctrl, irqcfg->iv);
1445 		if (iv) {
1446 			irqcfg->cd = iv->cd;
1447 			status = NVME_SC_SUCCESS;
1448 		} else {
1449 			status = NVME_SC_INVALID_FIELD | NVME_STATUS_DNR;
1450 		}
1451 		mutex_unlock(&ctrl->irq_lock);
1452 		return status;
1453 
1454 	default:
1455 		return NVME_SC_INVALID_FIELD | NVME_STATUS_DNR;
1456 	}
1457 }
1458 
nvmet_pci_epf_set_feat(const struct nvmet_ctrl * tctrl,u8 feat,void * data)1459 static u16 nvmet_pci_epf_set_feat(const struct nvmet_ctrl *tctrl,
1460 				  u8 feat, void *data)
1461 {
1462 	struct nvmet_pci_epf_ctrl *ctrl = tctrl->drvdata;
1463 	struct nvmet_feat_arbitration *arb;
1464 	struct nvmet_feat_irq_coalesce *irqc;
1465 	struct nvmet_feat_irq_config *irqcfg;
1466 	struct nvmet_pci_epf_irq_vector *iv;
1467 	u16 status;
1468 
1469 	switch (feat) {
1470 	case NVME_FEAT_ARBITRATION:
1471 		arb = data;
1472 		if (arb->ab == 0x7)
1473 			ctrl->sq_ab = 0;
1474 		else
1475 			ctrl->sq_ab = 1 << arb->ab;
1476 		return NVME_SC_SUCCESS;
1477 
1478 	case NVME_FEAT_IRQ_COALESCE:
1479 		/*
1480 		 * Since we do not implement precise IRQ coalescing timing,
1481 		 * ignore the time field.
1482 		 */
1483 		irqc = data;
1484 		ctrl->irq_vector_threshold = irqc->thr + 1;
1485 		return NVME_SC_SUCCESS;
1486 
1487 	case NVME_FEAT_IRQ_CONFIG:
1488 		irqcfg = data;
1489 		mutex_lock(&ctrl->irq_lock);
1490 		iv = nvmet_pci_epf_find_irq_vector(ctrl, irqcfg->iv);
1491 		if (iv) {
1492 			iv->cd = irqcfg->cd;
1493 			status = NVME_SC_SUCCESS;
1494 		} else {
1495 			status = NVME_SC_INVALID_FIELD | NVME_STATUS_DNR;
1496 		}
1497 		mutex_unlock(&ctrl->irq_lock);
1498 		return status;
1499 
1500 	default:
1501 		return NVME_SC_INVALID_FIELD | NVME_STATUS_DNR;
1502 	}
1503 }
1504 
1505 static const struct nvmet_fabrics_ops nvmet_pci_epf_fabrics_ops = {
1506 	.owner		= THIS_MODULE,
1507 	.type		= NVMF_TRTYPE_PCI,
1508 	.add_port	= nvmet_pci_epf_add_port,
1509 	.remove_port	= nvmet_pci_epf_remove_port,
1510 	.queue_response = nvmet_pci_epf_queue_response,
1511 	.get_mdts	= nvmet_pci_epf_get_mdts,
1512 	.create_cq	= nvmet_pci_epf_create_cq,
1513 	.delete_cq	= nvmet_pci_epf_delete_cq,
1514 	.create_sq	= nvmet_pci_epf_create_sq,
1515 	.delete_sq	= nvmet_pci_epf_delete_sq,
1516 	.get_feature	= nvmet_pci_epf_get_feat,
1517 	.set_feature	= nvmet_pci_epf_set_feat,
1518 };
1519 
1520 static void nvmet_pci_epf_cq_work(struct work_struct *work);
1521 
nvmet_pci_epf_init_queue(struct nvmet_pci_epf_ctrl * ctrl,unsigned int qid,bool sq)1522 static void nvmet_pci_epf_init_queue(struct nvmet_pci_epf_ctrl *ctrl,
1523 				     unsigned int qid, bool sq)
1524 {
1525 	struct nvmet_pci_epf_queue *queue;
1526 
1527 	if (sq) {
1528 		queue = &ctrl->sq[qid];
1529 	} else {
1530 		queue = &ctrl->cq[qid];
1531 		INIT_DELAYED_WORK(&queue->work, nvmet_pci_epf_cq_work);
1532 	}
1533 	queue->ctrl = ctrl;
1534 	queue->qid = qid;
1535 	spin_lock_init(&queue->lock);
1536 	INIT_LIST_HEAD(&queue->list);
1537 }
1538 
nvmet_pci_epf_alloc_queues(struct nvmet_pci_epf_ctrl * ctrl)1539 static int nvmet_pci_epf_alloc_queues(struct nvmet_pci_epf_ctrl *ctrl)
1540 {
1541 	unsigned int qid;
1542 
1543 	ctrl->sq = kzalloc_objs(struct nvmet_pci_epf_queue, ctrl->nr_queues);
1544 	if (!ctrl->sq)
1545 		return -ENOMEM;
1546 
1547 	ctrl->cq = kzalloc_objs(struct nvmet_pci_epf_queue, ctrl->nr_queues);
1548 	if (!ctrl->cq) {
1549 		kfree(ctrl->sq);
1550 		ctrl->sq = NULL;
1551 		return -ENOMEM;
1552 	}
1553 
1554 	for (qid = 0; qid < ctrl->nr_queues; qid++) {
1555 		nvmet_pci_epf_init_queue(ctrl, qid, true);
1556 		nvmet_pci_epf_init_queue(ctrl, qid, false);
1557 	}
1558 
1559 	return 0;
1560 }
1561 
nvmet_pci_epf_free_queues(struct nvmet_pci_epf_ctrl * ctrl)1562 static void nvmet_pci_epf_free_queues(struct nvmet_pci_epf_ctrl *ctrl)
1563 {
1564 	kfree(ctrl->sq);
1565 	ctrl->sq = NULL;
1566 	kfree(ctrl->cq);
1567 	ctrl->cq = NULL;
1568 }
1569 
nvmet_pci_epf_exec_iod_work(struct work_struct * work)1570 static void nvmet_pci_epf_exec_iod_work(struct work_struct *work)
1571 {
1572 	struct nvmet_pci_epf_iod *iod =
1573 		container_of(work, struct nvmet_pci_epf_iod, work);
1574 	struct nvmet_req *req = &iod->req;
1575 	bool no_wait;
1576 	int ret;
1577 
1578 	if (!iod->ctrl->link_up) {
1579 		nvmet_pci_epf_free_iod(iod);
1580 		return;
1581 	}
1582 
1583 	if (!test_bit(NVMET_PCI_EPF_Q_LIVE, &iod->sq->flags)) {
1584 		iod->status = NVME_SC_QID_INVALID | NVME_STATUS_DNR;
1585 		goto complete;
1586 	}
1587 
1588 	/*
1589 	 * If nvmet_req_init() fails (e.g., unsupported opcode) it will call
1590 	 * __nvmet_req_complete() internally which will call
1591 	 * nvmet_pci_epf_queue_response() and will complete the command directly.
1592 	 */
1593 	if (!nvmet_req_init(req, &iod->sq->nvme_sq, &nvmet_pci_epf_fabrics_ops))
1594 		return;
1595 
1596 	iod->data_len = nvmet_req_transfer_len(req);
1597 	if (iod->data_len) {
1598 		/*
1599 		 * Get the data DMA transfer direction. Here "device" means the
1600 		 * PCI root-complex host.
1601 		 */
1602 		if (nvme_is_write(&iod->cmd))
1603 			iod->dma_dir = DMA_FROM_DEVICE;
1604 		else
1605 			iod->dma_dir = DMA_TO_DEVICE;
1606 
1607 		/*
1608 		 * Setup the command data buffer and get the command data from
1609 		 * the host if needed.
1610 		 */
1611 		ret = nvmet_pci_epf_alloc_iod_data_buf(iod);
1612 		if (!ret && iod->dma_dir == DMA_FROM_DEVICE)
1613 			ret = nvmet_pci_epf_transfer_iod_data(iod);
1614 		if (ret) {
1615 			nvmet_req_uninit(req);
1616 			goto complete;
1617 		}
1618 	}
1619 
1620 	/*
1621 	 * If we do not have data to transfer after the command execution
1622 	 * finishes, nvmet_pci_epf_queue_response() will complete the command
1623 	 * directly. No need to wait for the completion in this case.
1624 	 */
1625 	no_wait = !iod->data_len || iod->dma_dir != DMA_TO_DEVICE;
1626 
1627 	req->execute(req);
1628 
1629 	if (no_wait)
1630 		return;
1631 
1632 	wait_for_completion(&iod->done);
1633 
1634 	if (iod->status != NVME_SC_SUCCESS)
1635 		return;
1636 
1637 	WARN_ON_ONCE(!iod->data_len || iod->dma_dir != DMA_TO_DEVICE);
1638 	nvmet_pci_epf_transfer_iod_data(iod);
1639 
1640 complete:
1641 	nvmet_pci_epf_complete_iod(iod);
1642 }
1643 
nvmet_pci_epf_process_sq(struct nvmet_pci_epf_ctrl * ctrl,struct nvmet_pci_epf_queue * sq)1644 static int nvmet_pci_epf_process_sq(struct nvmet_pci_epf_ctrl *ctrl,
1645 				    struct nvmet_pci_epf_queue *sq)
1646 {
1647 	struct nvmet_pci_epf_iod *iod;
1648 	int ret, n = 0;
1649 	u16 head = sq->head;
1650 
1651 	sq->tail = nvmet_pci_epf_bar_read32(ctrl, sq->db);
1652 	while (head != sq->tail && (!ctrl->sq_ab || n < ctrl->sq_ab)) {
1653 		iod = nvmet_pci_epf_alloc_iod(sq);
1654 		if (!iod)
1655 			break;
1656 
1657 		/* Get the NVMe command submitted by the host. */
1658 		ret = nvmet_pci_epf_transfer(ctrl, &iod->cmd,
1659 					     sq->pci_addr + head * sq->qes,
1660 					     sq->qes, DMA_FROM_DEVICE);
1661 		if (ret) {
1662 			/* Not much we can do... */
1663 			nvmet_pci_epf_free_iod(iod);
1664 			break;
1665 		}
1666 
1667 		dev_dbg(ctrl->dev, "SQ[%u]: head %u, tail %u, command %s\n",
1668 			sq->qid, head, sq->tail,
1669 			nvmet_pci_epf_iod_name(iod));
1670 
1671 		head++;
1672 		if (head == sq->depth)
1673 			head = 0;
1674 		WRITE_ONCE(sq->head, head);
1675 		n++;
1676 
1677 		queue_work_on(WORK_CPU_UNBOUND, sq->iod_wq, &iod->work);
1678 
1679 		sq->tail = nvmet_pci_epf_bar_read32(ctrl, sq->db);
1680 	}
1681 
1682 	return n;
1683 }
1684 
nvmet_pci_epf_poll_sqs_work(struct work_struct * work)1685 static void nvmet_pci_epf_poll_sqs_work(struct work_struct *work)
1686 {
1687 	struct nvmet_pci_epf_ctrl *ctrl =
1688 		container_of(work, struct nvmet_pci_epf_ctrl, poll_sqs.work);
1689 	struct nvmet_pci_epf_queue *sq;
1690 	unsigned long limit = jiffies;
1691 	unsigned long last = 0;
1692 	int i, nr_sqs;
1693 
1694 	while (ctrl->link_up && ctrl->enabled) {
1695 		nr_sqs = 0;
1696 		/* Do round-robin arbitration. */
1697 		for (i = 0; i < ctrl->nr_queues; i++) {
1698 			sq = &ctrl->sq[i];
1699 			if (!test_bit(NVMET_PCI_EPF_Q_LIVE, &sq->flags))
1700 				continue;
1701 			if (nvmet_pci_epf_process_sq(ctrl, sq))
1702 				nr_sqs++;
1703 		}
1704 
1705 		/*
1706 		 * If we have been running for a while, reschedule to let other
1707 		 * tasks run and to avoid RCU stalls.
1708 		 */
1709 		if (time_is_before_jiffies(limit + secs_to_jiffies(1))) {
1710 			cond_resched();
1711 			limit = jiffies;
1712 			continue;
1713 		}
1714 
1715 		if (nr_sqs) {
1716 			last = jiffies;
1717 			continue;
1718 		}
1719 
1720 		/*
1721 		 * If we have not received any command on any queue for more
1722 		 * than NVMET_PCI_EPF_SQ_POLL_IDLE, assume we are idle and
1723 		 * reschedule. This avoids "burning" a CPU when the controller
1724 		 * is idle for a long time.
1725 		 */
1726 		if (time_is_before_jiffies(last + NVMET_PCI_EPF_SQ_POLL_IDLE))
1727 			break;
1728 
1729 		cpu_relax();
1730 	}
1731 
1732 	schedule_delayed_work(&ctrl->poll_sqs, NVMET_PCI_EPF_SQ_POLL_INTERVAL);
1733 }
1734 
nvmet_pci_epf_cq_work(struct work_struct * work)1735 static void nvmet_pci_epf_cq_work(struct work_struct *work)
1736 {
1737 	struct nvmet_pci_epf_queue *cq =
1738 		container_of(work, struct nvmet_pci_epf_queue, work.work);
1739 	struct nvmet_pci_epf_ctrl *ctrl = cq->ctrl;
1740 	struct nvme_completion *cqe;
1741 	struct nvmet_pci_epf_iod *iod;
1742 	unsigned long flags;
1743 	int ret = 0, n = 0;
1744 
1745 	while (test_bit(NVMET_PCI_EPF_Q_LIVE, &cq->flags) && ctrl->link_up) {
1746 
1747 		/* Check that the CQ is not full. */
1748 		cq->head = nvmet_pci_epf_bar_read32(ctrl, cq->db);
1749 		if (cq->head == cq->tail + 1) {
1750 			ret = -EAGAIN;
1751 			break;
1752 		}
1753 
1754 		spin_lock_irqsave(&cq->lock, flags);
1755 		iod = list_first_entry_or_null(&cq->list,
1756 					       struct nvmet_pci_epf_iod, link);
1757 		if (iod)
1758 			list_del_init(&iod->link);
1759 		spin_unlock_irqrestore(&cq->lock, flags);
1760 
1761 		if (!iod)
1762 			break;
1763 
1764 		/*
1765 		 * Post the IOD completion entry. If the IOD request was
1766 		 * executed (req->execute() called), the CQE is already
1767 		 * initialized. However, the IOD may have been failed before
1768 		 * that, leaving the CQE not properly initialized. So always
1769 		 * initialize it here.
1770 		 */
1771 		cqe = &iod->cqe;
1772 		cqe->sq_head = cpu_to_le16(READ_ONCE(iod->sq->head));
1773 		cqe->sq_id = cpu_to_le16(iod->sq->qid);
1774 		cqe->command_id = iod->cmd.common.command_id;
1775 		cqe->status = cpu_to_le16((iod->status << 1) | cq->phase);
1776 
1777 		dev_dbg(ctrl->dev,
1778 			"CQ[%u]: %s status 0x%x, result 0x%llx, head %u, tail %u, phase %u\n",
1779 			cq->qid, nvmet_pci_epf_iod_name(iod), iod->status,
1780 			le64_to_cpu(cqe->result.u64), cq->head, cq->tail,
1781 			cq->phase);
1782 
1783 		memcpy_toio(cq->pci_map.virt_addr + cq->tail * cq->qes,
1784 			    cqe, cq->qes);
1785 
1786 		cq->tail++;
1787 		if (cq->tail >= cq->depth) {
1788 			cq->tail = 0;
1789 			cq->phase ^= 1;
1790 		}
1791 
1792 		nvmet_pci_epf_free_iod(iod);
1793 
1794 		/* Signal the host. */
1795 		nvmet_pci_epf_raise_irq(ctrl, cq, false);
1796 		n++;
1797 	}
1798 
1799 	/*
1800 	 * We do not support precise IRQ coalescing time (100ns units as per
1801 	 * NVMe specifications). So if we have posted completion entries without
1802 	 * reaching the interrupt coalescing threshold, raise an interrupt.
1803 	 */
1804 	if (n)
1805 		nvmet_pci_epf_raise_irq(ctrl, cq, true);
1806 
1807 	if (ret < 0)
1808 		queue_delayed_work(system_highpri_wq, &cq->work,
1809 				   NVMET_PCI_EPF_CQ_RETRY_INTERVAL);
1810 }
1811 
nvmet_pci_epf_clear_ctrl_config(struct nvmet_pci_epf_ctrl * ctrl)1812 static void nvmet_pci_epf_clear_ctrl_config(struct nvmet_pci_epf_ctrl *ctrl)
1813 {
1814 	struct nvmet_ctrl *tctrl = ctrl->tctrl;
1815 
1816 	/* Initialize controller status. */
1817 	tctrl->csts = 0;
1818 	ctrl->csts = 0;
1819 	nvmet_pci_epf_bar_write32(ctrl, NVME_REG_CSTS, ctrl->csts);
1820 
1821 	/* Initialize controller configuration and start polling. */
1822 	tctrl->cc = 0;
1823 	ctrl->cc = 0;
1824 	nvmet_pci_epf_bar_write32(ctrl, NVME_REG_CC, ctrl->cc);
1825 }
1826 
nvmet_pci_epf_enable_ctrl(struct nvmet_pci_epf_ctrl * ctrl)1827 static int nvmet_pci_epf_enable_ctrl(struct nvmet_pci_epf_ctrl *ctrl)
1828 {
1829 	u64 pci_addr, asq, acq;
1830 	u32 aqa;
1831 	u16 status, qsize;
1832 
1833 	if (ctrl->enabled)
1834 		return 0;
1835 
1836 	dev_info(ctrl->dev, "Enabling controller\n");
1837 
1838 	ctrl->mps_shift = nvmet_cc_mps(ctrl->cc) + 12;
1839 	ctrl->mps = 1UL << ctrl->mps_shift;
1840 	ctrl->mps_mask = ctrl->mps - 1;
1841 
1842 	ctrl->io_sqes = 1UL << nvmet_cc_iosqes(ctrl->cc);
1843 	if (ctrl->io_sqes < sizeof(struct nvme_command)) {
1844 		dev_err(ctrl->dev, "Unsupported I/O SQES %zu (need %zu)\n",
1845 			ctrl->io_sqes, sizeof(struct nvme_command));
1846 		goto err;
1847 	}
1848 
1849 	ctrl->io_cqes = 1UL << nvmet_cc_iocqes(ctrl->cc);
1850 	if (ctrl->io_cqes < sizeof(struct nvme_completion)) {
1851 		dev_err(ctrl->dev, "Unsupported I/O CQES %zu (need %zu)\n",
1852 			ctrl->io_cqes, sizeof(struct nvme_completion));
1853 		goto err;
1854 	}
1855 
1856 	/* Create the admin queue. */
1857 	aqa = nvmet_pci_epf_bar_read32(ctrl, NVME_REG_AQA);
1858 	asq = nvmet_pci_epf_bar_read64(ctrl, NVME_REG_ASQ);
1859 	acq = nvmet_pci_epf_bar_read64(ctrl, NVME_REG_ACQ);
1860 
1861 	qsize = (aqa & 0x0fff0000) >> 16;
1862 	pci_addr = acq & GENMASK_ULL(63, 12);
1863 	status = nvmet_pci_epf_create_cq(ctrl->tctrl, 0,
1864 				NVME_CQ_IRQ_ENABLED | NVME_QUEUE_PHYS_CONTIG,
1865 				qsize, pci_addr, 0);
1866 	if (status != NVME_SC_SUCCESS) {
1867 		dev_err(ctrl->dev, "Failed to create admin completion queue\n");
1868 		goto err;
1869 	}
1870 
1871 	qsize = aqa & 0x00000fff;
1872 	pci_addr = asq & GENMASK_ULL(63, 12);
1873 	status = nvmet_pci_epf_create_sq(ctrl->tctrl, 0, 0,
1874 			NVME_QUEUE_PHYS_CONTIG, qsize, pci_addr);
1875 	if (status != NVME_SC_SUCCESS) {
1876 		dev_err(ctrl->dev, "Failed to create admin submission queue\n");
1877 		nvmet_pci_epf_delete_cq(ctrl->tctrl, 0);
1878 		goto err;
1879 	}
1880 
1881 	ctrl->sq_ab = NVMET_PCI_EPF_SQ_AB;
1882 	ctrl->irq_vector_threshold = NVMET_PCI_EPF_IV_THRESHOLD;
1883 	ctrl->enabled = true;
1884 	ctrl->csts = NVME_CSTS_RDY;
1885 
1886 	/* Start polling the controller SQs. */
1887 	schedule_delayed_work(&ctrl->poll_sqs, 0);
1888 
1889 	return 0;
1890 
1891 err:
1892 	nvmet_pci_epf_clear_ctrl_config(ctrl);
1893 	return -EINVAL;
1894 }
1895 
nvmet_pci_epf_disable_ctrl(struct nvmet_pci_epf_ctrl * ctrl,bool shutdown)1896 static void nvmet_pci_epf_disable_ctrl(struct nvmet_pci_epf_ctrl *ctrl,
1897 				       bool shutdown)
1898 {
1899 	int qid;
1900 
1901 	if (!ctrl->enabled)
1902 		return;
1903 
1904 	dev_info(ctrl->dev, "%s controller\n",
1905 		 shutdown ? "Shutting down" : "Disabling");
1906 
1907 	ctrl->enabled = false;
1908 	cancel_delayed_work_sync(&ctrl->poll_sqs);
1909 
1910 	/* Delete all I/O queues first. */
1911 	for (qid = 1; qid < ctrl->nr_queues; qid++)
1912 		nvmet_pci_epf_delete_sq(ctrl->tctrl, qid);
1913 
1914 	for (qid = 1; qid < ctrl->nr_queues; qid++)
1915 		nvmet_pci_epf_delete_cq(ctrl->tctrl, qid);
1916 
1917 	/* Delete the admin queue last. */
1918 	nvmet_pci_epf_delete_sq(ctrl->tctrl, 0);
1919 	nvmet_pci_epf_delete_cq(ctrl->tctrl, 0);
1920 
1921 	ctrl->csts &= ~NVME_CSTS_RDY;
1922 	if (shutdown) {
1923 		ctrl->csts |= NVME_CSTS_SHST_CMPLT;
1924 		ctrl->cc &= ~NVME_CC_ENABLE;
1925 		nvmet_pci_epf_bar_write32(ctrl, NVME_REG_CC, ctrl->cc);
1926 	}
1927 }
1928 
nvmet_pci_epf_poll_cc_work(struct work_struct * work)1929 static void nvmet_pci_epf_poll_cc_work(struct work_struct *work)
1930 {
1931 	struct nvmet_pci_epf_ctrl *ctrl =
1932 		container_of(work, struct nvmet_pci_epf_ctrl, poll_cc.work);
1933 	u32 old_cc, new_cc;
1934 	int ret;
1935 
1936 	if (!ctrl->tctrl)
1937 		return;
1938 
1939 	old_cc = ctrl->cc;
1940 	new_cc = nvmet_pci_epf_bar_read32(ctrl, NVME_REG_CC);
1941 	if (new_cc == old_cc)
1942 		goto reschedule_work;
1943 
1944 	ctrl->cc = new_cc;
1945 
1946 	if (nvmet_cc_en(new_cc) && !nvmet_cc_en(old_cc)) {
1947 		ret = nvmet_pci_epf_enable_ctrl(ctrl);
1948 		if (ret)
1949 			goto reschedule_work;
1950 	}
1951 
1952 	if (!nvmet_cc_en(new_cc) && nvmet_cc_en(old_cc))
1953 		nvmet_pci_epf_disable_ctrl(ctrl, false);
1954 
1955 	if (nvmet_cc_shn(new_cc) && !nvmet_cc_shn(old_cc))
1956 		nvmet_pci_epf_disable_ctrl(ctrl, true);
1957 
1958 	if (!nvmet_cc_shn(new_cc) && nvmet_cc_shn(old_cc))
1959 		ctrl->csts &= ~NVME_CSTS_SHST_CMPLT;
1960 
1961 	nvmet_update_cc(ctrl->tctrl, ctrl->cc);
1962 	nvmet_pci_epf_bar_write32(ctrl, NVME_REG_CSTS, ctrl->csts);
1963 
1964 reschedule_work:
1965 	schedule_delayed_work(&ctrl->poll_cc, NVMET_PCI_EPF_CC_POLL_INTERVAL);
1966 }
1967 
nvmet_pci_epf_init_bar(struct nvmet_pci_epf_ctrl * ctrl)1968 static void nvmet_pci_epf_init_bar(struct nvmet_pci_epf_ctrl *ctrl)
1969 {
1970 	struct nvmet_ctrl *tctrl = ctrl->tctrl;
1971 
1972 	ctrl->bar = ctrl->nvme_epf->reg_bar;
1973 
1974 	/* Copy the target controller capabilities as a base. */
1975 	ctrl->cap = tctrl->cap;
1976 
1977 	/* Contiguous Queues Required (CQR). */
1978 	ctrl->cap |= 0x1ULL << 16;
1979 
1980 	/* Set Doorbell stride to 4B (DSTRB). */
1981 	ctrl->cap &= ~GENMASK_ULL(35, 32);
1982 
1983 	/* Clear NVM Subsystem Reset Supported (NSSRS). */
1984 	ctrl->cap &= ~(0x1ULL << 36);
1985 
1986 	/* Clear Boot Partition Support (BPS). */
1987 	ctrl->cap &= ~(0x1ULL << 45);
1988 
1989 	/* Clear Persistent Memory Region Supported (PMRS). */
1990 	ctrl->cap &= ~(0x1ULL << 56);
1991 
1992 	/* Clear Controller Memory Buffer Supported (CMBS). */
1993 	ctrl->cap &= ~(0x1ULL << 57);
1994 
1995 	nvmet_pci_epf_bar_write64(ctrl, NVME_REG_CAP, ctrl->cap);
1996 	nvmet_pci_epf_bar_write32(ctrl, NVME_REG_VS, tctrl->subsys->ver);
1997 
1998 	nvmet_pci_epf_clear_ctrl_config(ctrl);
1999 }
2000 
nvmet_pci_epf_create_ctrl(struct nvmet_pci_epf * nvme_epf,unsigned int max_nr_queues)2001 static int nvmet_pci_epf_create_ctrl(struct nvmet_pci_epf *nvme_epf,
2002 				     unsigned int max_nr_queues)
2003 {
2004 	struct nvmet_pci_epf_ctrl *ctrl = &nvme_epf->ctrl;
2005 	struct nvmet_alloc_ctrl_args args = {};
2006 	char hostnqn[NVMF_NQN_SIZE];
2007 	uuid_t id;
2008 	int ret;
2009 
2010 	memset(ctrl, 0, sizeof(*ctrl));
2011 	ctrl->dev = &nvme_epf->epf->dev;
2012 	mutex_init(&ctrl->irq_lock);
2013 	ctrl->nvme_epf = nvme_epf;
2014 	ctrl->mdts = nvme_epf->mdts_kb * SZ_1K;
2015 	INIT_DELAYED_WORK(&ctrl->poll_cc, nvmet_pci_epf_poll_cc_work);
2016 	INIT_DELAYED_WORK(&ctrl->poll_sqs, nvmet_pci_epf_poll_sqs_work);
2017 
2018 	ret = mempool_init_kmalloc_pool(&ctrl->iod_pool,
2019 					max_nr_queues * NVMET_MAX_QUEUE_SIZE,
2020 					sizeof(struct nvmet_pci_epf_iod));
2021 	if (ret) {
2022 		dev_err(ctrl->dev, "Failed to initialize IOD mempool\n");
2023 		return ret;
2024 	}
2025 
2026 	ctrl->port = nvmet_pci_epf_find_port(ctrl, nvme_epf->portid);
2027 	if (!ctrl->port) {
2028 		dev_err(ctrl->dev, "Port not found\n");
2029 		ret = -EINVAL;
2030 		goto out_mempool_exit;
2031 	}
2032 
2033 	/* Create the target controller. */
2034 	uuid_gen(&id);
2035 	snprintf(hostnqn, NVMF_NQN_SIZE,
2036 		 "nqn.2014-08.org.nvmexpress:uuid:%pUb", &id);
2037 	args.port = ctrl->port;
2038 	args.subsysnqn = nvme_epf->subsysnqn;
2039 	memset(&id, 0, sizeof(uuid_t));
2040 	args.hostid = &id;
2041 	args.hostnqn = hostnqn;
2042 	args.ops = &nvmet_pci_epf_fabrics_ops;
2043 
2044 	ctrl->tctrl = nvmet_alloc_ctrl(&args);
2045 	if (!ctrl->tctrl) {
2046 		dev_err(ctrl->dev, "Failed to create target controller\n");
2047 		ret = -ENOMEM;
2048 		goto out_mempool_exit;
2049 	}
2050 	ctrl->tctrl->drvdata = ctrl;
2051 
2052 	/* We do not support protection information for now. */
2053 	if (ctrl->tctrl->pi_support) {
2054 		dev_err(ctrl->dev,
2055 			"Protection information (PI) is not supported\n");
2056 		ret = -ENOTSUPP;
2057 		goto out_put_ctrl;
2058 	}
2059 
2060 	/* Allocate our queues, up to the maximum number. */
2061 	ctrl->nr_queues = min(ctrl->tctrl->max_qid + 1, max_nr_queues);
2062 	ret = nvmet_pci_epf_alloc_queues(ctrl);
2063 	if (ret)
2064 		goto out_put_ctrl;
2065 
2066 	/*
2067 	 * Allocate the IRQ vectors descriptors. We cannot have more than the
2068 	 * maximum number of queues.
2069 	 */
2070 	ret = nvmet_pci_epf_alloc_irq_vectors(ctrl);
2071 	if (ret)
2072 		goto out_free_queues;
2073 
2074 	dev_info(ctrl->dev,
2075 		 "New PCI ctrl \"%s\", %u I/O queues, mdts %u B\n",
2076 		 ctrl->tctrl->subsys->subsysnqn, ctrl->nr_queues - 1,
2077 		 ctrl->mdts);
2078 
2079 	/* Initialize BAR 0 using the target controller CAP. */
2080 	nvmet_pci_epf_init_bar(ctrl);
2081 
2082 	return 0;
2083 
2084 out_free_queues:
2085 	nvmet_pci_epf_free_queues(ctrl);
2086 out_put_ctrl:
2087 	nvmet_ctrl_put(ctrl->tctrl);
2088 	ctrl->tctrl = NULL;
2089 out_mempool_exit:
2090 	mempool_exit(&ctrl->iod_pool);
2091 	return ret;
2092 }
2093 
nvmet_pci_epf_start_ctrl(struct nvmet_pci_epf_ctrl * ctrl)2094 static void nvmet_pci_epf_start_ctrl(struct nvmet_pci_epf_ctrl *ctrl)
2095 {
2096 
2097 	dev_info(ctrl->dev, "PCI link up\n");
2098 	ctrl->link_up = true;
2099 
2100 	schedule_delayed_work(&ctrl->poll_cc, NVMET_PCI_EPF_CC_POLL_INTERVAL);
2101 }
2102 
nvmet_pci_epf_stop_ctrl(struct nvmet_pci_epf_ctrl * ctrl)2103 static void nvmet_pci_epf_stop_ctrl(struct nvmet_pci_epf_ctrl *ctrl)
2104 {
2105 	dev_info(ctrl->dev, "PCI link down\n");
2106 	ctrl->link_up = false;
2107 
2108 	cancel_delayed_work_sync(&ctrl->poll_cc);
2109 
2110 	nvmet_pci_epf_disable_ctrl(ctrl, false);
2111 	nvmet_pci_epf_clear_ctrl_config(ctrl);
2112 }
2113 
nvmet_pci_epf_destroy_ctrl(struct nvmet_pci_epf_ctrl * ctrl)2114 static void nvmet_pci_epf_destroy_ctrl(struct nvmet_pci_epf_ctrl *ctrl)
2115 {
2116 	if (!ctrl->tctrl)
2117 		return;
2118 
2119 	dev_info(ctrl->dev, "Destroying PCI ctrl \"%s\"\n",
2120 		 ctrl->tctrl->subsys->subsysnqn);
2121 
2122 	nvmet_pci_epf_stop_ctrl(ctrl);
2123 
2124 	nvmet_pci_epf_free_queues(ctrl);
2125 	nvmet_pci_epf_free_irq_vectors(ctrl);
2126 
2127 	nvmet_ctrl_put(ctrl->tctrl);
2128 	ctrl->tctrl = NULL;
2129 
2130 	mempool_exit(&ctrl->iod_pool);
2131 }
2132 
nvmet_pci_epf_configure_bar(struct nvmet_pci_epf * nvme_epf)2133 static int nvmet_pci_epf_configure_bar(struct nvmet_pci_epf *nvme_epf)
2134 {
2135 	struct pci_epf *epf = nvme_epf->epf;
2136 	const struct pci_epc_features *epc_features = nvme_epf->epc_features;
2137 	size_t reg_size, reg_bar_size;
2138 	size_t msix_table_size = 0;
2139 
2140 	/*
2141 	 * The first free BAR will be our register BAR and per NVMe
2142 	 * specifications, it must be BAR 0.
2143 	 */
2144 	if (pci_epc_get_first_free_bar(epc_features) != BAR_0) {
2145 		dev_err(&epf->dev, "BAR 0 is not free\n");
2146 		return -ENODEV;
2147 	}
2148 
2149 	/*
2150 	 * While NVMe PCIe Transport Specification 1.1, section 2.1.10, claims
2151 	 * that the BAR0 type is Implementation Specific, in NVMe 1.1, the type
2152 	 * is required to be 64-bit. Thus, for interoperability, always set the
2153 	 * type to 64-bit. In the rare case that the PCI EPC does not support
2154 	 * configuring BAR0 as 64-bit, the call to pci_epc_set_bar() will fail,
2155 	 * and we will return failure back to the user.
2156 	 */
2157 	epf->bar[BAR_0].flags |= PCI_BASE_ADDRESS_MEM_TYPE_64;
2158 
2159 	/*
2160 	 * Calculate the size of the register bar: NVMe registers first with
2161 	 * enough space for the doorbells, followed by the MSI-X table
2162 	 * if supported.
2163 	 */
2164 	reg_size = NVME_REG_DBS + (NVMET_NR_QUEUES * 2 * sizeof(u32));
2165 	reg_size = ALIGN(reg_size, 8);
2166 
2167 	if (epc_features->msix_capable) {
2168 		size_t pba_size;
2169 
2170 		msix_table_size = PCI_MSIX_ENTRY_SIZE * epf->msix_interrupts;
2171 		nvme_epf->msix_table_offset = reg_size;
2172 		pba_size = ALIGN(DIV_ROUND_UP(epf->msix_interrupts, 8), 8);
2173 
2174 		reg_size += msix_table_size + pba_size;
2175 	}
2176 
2177 	if (epc_features->bar[BAR_0].type == BAR_FIXED) {
2178 		if (reg_size > epc_features->bar[BAR_0].fixed_size) {
2179 			dev_err(&epf->dev,
2180 				"BAR 0 size %llu B too small, need %zu B\n",
2181 				epc_features->bar[BAR_0].fixed_size,
2182 				reg_size);
2183 			return -ENOMEM;
2184 		}
2185 		reg_bar_size = epc_features->bar[BAR_0].fixed_size;
2186 	} else {
2187 		reg_bar_size = ALIGN(reg_size, max(epc_features->align, 4096));
2188 	}
2189 
2190 	nvme_epf->reg_bar = pci_epf_alloc_space(epf, reg_bar_size, BAR_0,
2191 						epc_features, PRIMARY_INTERFACE);
2192 	if (!nvme_epf->reg_bar) {
2193 		dev_err(&epf->dev, "Failed to allocate BAR 0\n");
2194 		return -ENOMEM;
2195 	}
2196 	memset(nvme_epf->reg_bar, 0, reg_bar_size);
2197 
2198 	return 0;
2199 }
2200 
nvmet_pci_epf_free_bar(struct nvmet_pci_epf * nvme_epf)2201 static void nvmet_pci_epf_free_bar(struct nvmet_pci_epf *nvme_epf)
2202 {
2203 	struct pci_epf *epf = nvme_epf->epf;
2204 
2205 	if (!nvme_epf->reg_bar)
2206 		return;
2207 
2208 	pci_epf_free_space(epf, nvme_epf->reg_bar, BAR_0, PRIMARY_INTERFACE);
2209 	nvme_epf->reg_bar = NULL;
2210 }
2211 
nvmet_pci_epf_clear_bar(struct nvmet_pci_epf * nvme_epf)2212 static void nvmet_pci_epf_clear_bar(struct nvmet_pci_epf *nvme_epf)
2213 {
2214 	struct pci_epf *epf = nvme_epf->epf;
2215 
2216 	pci_epc_clear_bar(epf->epc, epf->func_no, epf->vfunc_no,
2217 			  &epf->bar[BAR_0]);
2218 }
2219 
nvmet_pci_epf_init_irq(struct nvmet_pci_epf * nvme_epf)2220 static int nvmet_pci_epf_init_irq(struct nvmet_pci_epf *nvme_epf)
2221 {
2222 	const struct pci_epc_features *epc_features = nvme_epf->epc_features;
2223 	struct pci_epf *epf = nvme_epf->epf;
2224 	int ret;
2225 
2226 	/* Enable MSI-X if supported, otherwise, use MSI. */
2227 	if (epc_features->msix_capable && epf->msix_interrupts) {
2228 		ret = pci_epc_set_msix(epf->epc, epf->func_no, epf->vfunc_no,
2229 				       epf->msix_interrupts, BAR_0,
2230 				       nvme_epf->msix_table_offset);
2231 		if (ret) {
2232 			dev_err(&epf->dev, "Failed to configure MSI-X\n");
2233 			return ret;
2234 		}
2235 
2236 		nvme_epf->nr_vectors = epf->msix_interrupts;
2237 		nvme_epf->irq_type = PCI_IRQ_MSIX;
2238 
2239 		return 0;
2240 	}
2241 
2242 	if (epc_features->msi_capable && epf->msi_interrupts) {
2243 		ret = pci_epc_set_msi(epf->epc, epf->func_no, epf->vfunc_no,
2244 				      epf->msi_interrupts);
2245 		if (ret) {
2246 			dev_err(&epf->dev, "Failed to configure MSI\n");
2247 			return ret;
2248 		}
2249 
2250 		nvme_epf->nr_vectors = epf->msi_interrupts;
2251 		nvme_epf->irq_type = PCI_IRQ_MSI;
2252 
2253 		return 0;
2254 	}
2255 
2256 	/* MSI and MSI-X are not supported: fall back to INTx. */
2257 	nvme_epf->nr_vectors = 1;
2258 	nvme_epf->irq_type = PCI_IRQ_INTX;
2259 
2260 	return 0;
2261 }
2262 
nvmet_pci_epf_epc_init(struct pci_epf * epf)2263 static int nvmet_pci_epf_epc_init(struct pci_epf *epf)
2264 {
2265 	struct nvmet_pci_epf *nvme_epf = epf_get_drvdata(epf);
2266 	const struct pci_epc_features *epc_features = nvme_epf->epc_features;
2267 	struct nvmet_pci_epf_ctrl *ctrl = &nvme_epf->ctrl;
2268 	unsigned int max_nr_queues = NVMET_NR_QUEUES;
2269 	int ret;
2270 
2271 	/* For now, do not support virtual functions. */
2272 	if (epf->vfunc_no > 0) {
2273 		dev_err(&epf->dev, "Virtual functions are not supported\n");
2274 		return -EINVAL;
2275 	}
2276 
2277 	/*
2278 	 * Cap the maximum number of queues we can support on the controller
2279 	 * with the number of IRQs we can use.
2280 	 */
2281 	if (epc_features->msix_capable && epf->msix_interrupts) {
2282 		dev_info(&epf->dev,
2283 			 "PCI endpoint controller supports MSI-X, %u vectors\n",
2284 			 epf->msix_interrupts);
2285 		max_nr_queues = min(max_nr_queues, epf->msix_interrupts);
2286 	} else if (epc_features->msi_capable && epf->msi_interrupts) {
2287 		dev_info(&epf->dev,
2288 			 "PCI endpoint controller supports MSI, %u vectors\n",
2289 			 epf->msi_interrupts);
2290 		max_nr_queues = min(max_nr_queues, epf->msi_interrupts);
2291 	}
2292 
2293 	if (max_nr_queues < 2) {
2294 		dev_err(&epf->dev, "Invalid maximum number of queues %u\n",
2295 			max_nr_queues);
2296 		return -EINVAL;
2297 	}
2298 
2299 	/* Create the target controller. */
2300 	ret = nvmet_pci_epf_create_ctrl(nvme_epf, max_nr_queues);
2301 	if (ret) {
2302 		dev_err(&epf->dev,
2303 			"Failed to create NVMe PCI target controller (err=%d)\n",
2304 			ret);
2305 		return ret;
2306 	}
2307 
2308 	nvmet_pci_epf_init_dma(nvme_epf);
2309 
2310 	/* Set device ID, class, etc. */
2311 	epf->header->vendorid = ctrl->tctrl->subsys->vendor_id;
2312 	epf->header->subsys_vendor_id = ctrl->tctrl->subsys->subsys_vendor_id;
2313 	ret = pci_epc_write_header(epf->epc, epf->func_no, epf->vfunc_no,
2314 				   epf->header);
2315 	if (ret) {
2316 		dev_err(&epf->dev,
2317 			"Failed to write configuration header (err=%d)\n", ret);
2318 		goto out_destroy_ctrl;
2319 	}
2320 
2321 	ret = pci_epc_set_bar(epf->epc, epf->func_no, epf->vfunc_no,
2322 			      &epf->bar[BAR_0]);
2323 	if (ret) {
2324 		dev_err(&epf->dev, "Failed to set BAR 0 (err=%d)\n", ret);
2325 		goto out_destroy_ctrl;
2326 	}
2327 
2328 	/*
2329 	 * Enable interrupts and start polling the controller BAR if we do not
2330 	 * have a link up notifier.
2331 	 */
2332 	ret = nvmet_pci_epf_init_irq(nvme_epf);
2333 	if (ret)
2334 		goto out_clear_bar;
2335 
2336 	if (!epc_features->linkup_notifier)
2337 		nvmet_pci_epf_start_ctrl(&nvme_epf->ctrl);
2338 
2339 	return 0;
2340 
2341 out_clear_bar:
2342 	nvmet_pci_epf_clear_bar(nvme_epf);
2343 out_destroy_ctrl:
2344 	nvmet_pci_epf_destroy_ctrl(&nvme_epf->ctrl);
2345 	return ret;
2346 }
2347 
nvmet_pci_epf_epc_deinit(struct pci_epf * epf)2348 static void nvmet_pci_epf_epc_deinit(struct pci_epf *epf)
2349 {
2350 	struct nvmet_pci_epf *nvme_epf = epf_get_drvdata(epf);
2351 	struct nvmet_pci_epf_ctrl *ctrl = &nvme_epf->ctrl;
2352 
2353 	nvmet_pci_epf_destroy_ctrl(ctrl);
2354 
2355 	nvmet_pci_epf_deinit_dma(nvme_epf);
2356 	nvmet_pci_epf_clear_bar(nvme_epf);
2357 }
2358 
nvmet_pci_epf_link_up(struct pci_epf * epf)2359 static int nvmet_pci_epf_link_up(struct pci_epf *epf)
2360 {
2361 	struct nvmet_pci_epf *nvme_epf = epf_get_drvdata(epf);
2362 	struct nvmet_pci_epf_ctrl *ctrl = &nvme_epf->ctrl;
2363 
2364 	nvmet_pci_epf_start_ctrl(ctrl);
2365 
2366 	return 0;
2367 }
2368 
nvmet_pci_epf_link_down(struct pci_epf * epf)2369 static int nvmet_pci_epf_link_down(struct pci_epf *epf)
2370 {
2371 	struct nvmet_pci_epf *nvme_epf = epf_get_drvdata(epf);
2372 	struct nvmet_pci_epf_ctrl *ctrl = &nvme_epf->ctrl;
2373 
2374 	nvmet_pci_epf_stop_ctrl(ctrl);
2375 
2376 	return 0;
2377 }
2378 
2379 static const struct pci_epc_event_ops nvmet_pci_epf_event_ops = {
2380 	.epc_init = nvmet_pci_epf_epc_init,
2381 	.epc_deinit = nvmet_pci_epf_epc_deinit,
2382 	.link_up = nvmet_pci_epf_link_up,
2383 	.link_down = nvmet_pci_epf_link_down,
2384 };
2385 
nvmet_pci_epf_bind(struct pci_epf * epf)2386 static int nvmet_pci_epf_bind(struct pci_epf *epf)
2387 {
2388 	struct nvmet_pci_epf *nvme_epf = epf_get_drvdata(epf);
2389 	const struct pci_epc_features *epc_features;
2390 	struct pci_epc *epc = epf->epc;
2391 	int ret;
2392 
2393 	if (WARN_ON_ONCE(!epc))
2394 		return -EINVAL;
2395 
2396 	epc_features = pci_epc_get_features(epc, epf->func_no, epf->vfunc_no);
2397 	if (!epc_features) {
2398 		dev_err(&epf->dev, "epc_features not implemented\n");
2399 		return -EOPNOTSUPP;
2400 	}
2401 	nvme_epf->epc_features = epc_features;
2402 
2403 	ret = nvmet_pci_epf_configure_bar(nvme_epf);
2404 	if (ret)
2405 		return ret;
2406 
2407 	return 0;
2408 }
2409 
nvmet_pci_epf_unbind(struct pci_epf * epf)2410 static void nvmet_pci_epf_unbind(struct pci_epf *epf)
2411 {
2412 	struct nvmet_pci_epf *nvme_epf = epf_get_drvdata(epf);
2413 	struct pci_epc *epc = epf->epc;
2414 
2415 	nvmet_pci_epf_destroy_ctrl(&nvme_epf->ctrl);
2416 
2417 	if (epc->init_complete) {
2418 		nvmet_pci_epf_deinit_dma(nvme_epf);
2419 		nvmet_pci_epf_clear_bar(nvme_epf);
2420 	}
2421 
2422 	nvmet_pci_epf_free_bar(nvme_epf);
2423 }
2424 
2425 static struct pci_epf_header nvme_epf_pci_header = {
2426 	.vendorid	= PCI_ANY_ID,
2427 	.deviceid	= PCI_ANY_ID,
2428 	.progif_code	= 0x02, /* NVM Express */
2429 	.baseclass_code = PCI_BASE_CLASS_STORAGE,
2430 	.subclass_code	= 0x08, /* Non-Volatile Memory controller */
2431 	.interrupt_pin	= PCI_INTERRUPT_INTA,
2432 };
2433 
nvmet_pci_epf_probe(struct pci_epf * epf,const struct pci_epf_device_id * id)2434 static int nvmet_pci_epf_probe(struct pci_epf *epf,
2435 			       const struct pci_epf_device_id *id)
2436 {
2437 	struct nvmet_pci_epf *nvme_epf;
2438 	int ret;
2439 
2440 	nvme_epf = devm_kzalloc(&epf->dev, sizeof(*nvme_epf), GFP_KERNEL);
2441 	if (!nvme_epf)
2442 		return -ENOMEM;
2443 
2444 	ret = devm_mutex_init(&epf->dev, &nvme_epf->mmio_lock);
2445 	if (ret)
2446 		return ret;
2447 
2448 	nvme_epf->epf = epf;
2449 	nvme_epf->mdts_kb = NVMET_PCI_EPF_MDTS_KB;
2450 
2451 	epf->event_ops = &nvmet_pci_epf_event_ops;
2452 	epf->header = &nvme_epf_pci_header;
2453 	epf_set_drvdata(epf, nvme_epf);
2454 
2455 	return 0;
2456 }
2457 
2458 #define to_nvme_epf(epf_group)	\
2459 	container_of(epf_group, struct nvmet_pci_epf, group)
2460 
nvmet_pci_epf_portid_show(struct config_item * item,char * page)2461 static ssize_t nvmet_pci_epf_portid_show(struct config_item *item, char *page)
2462 {
2463 	struct config_group *group = to_config_group(item);
2464 	struct nvmet_pci_epf *nvme_epf = to_nvme_epf(group);
2465 
2466 	return sysfs_emit(page, "%u\n", le16_to_cpu(nvme_epf->portid));
2467 }
2468 
nvmet_pci_epf_portid_store(struct config_item * item,const char * page,size_t len)2469 static ssize_t nvmet_pci_epf_portid_store(struct config_item *item,
2470 					  const char *page, size_t len)
2471 {
2472 	struct config_group *group = to_config_group(item);
2473 	struct nvmet_pci_epf *nvme_epf = to_nvme_epf(group);
2474 	u16 portid;
2475 
2476 	/* Do not allow setting this when the function is already started. */
2477 	if (nvme_epf->ctrl.tctrl)
2478 		return -EBUSY;
2479 
2480 	if (!len)
2481 		return -EINVAL;
2482 
2483 	if (kstrtou16(page, 0, &portid))
2484 		return -EINVAL;
2485 
2486 	nvme_epf->portid = cpu_to_le16(portid);
2487 
2488 	return len;
2489 }
2490 
2491 CONFIGFS_ATTR(nvmet_pci_epf_, portid);
2492 
nvmet_pci_epf_subsysnqn_show(struct config_item * item,char * page)2493 static ssize_t nvmet_pci_epf_subsysnqn_show(struct config_item *item,
2494 					    char *page)
2495 {
2496 	struct config_group *group = to_config_group(item);
2497 	struct nvmet_pci_epf *nvme_epf = to_nvme_epf(group);
2498 
2499 	return sysfs_emit(page, "%s\n", nvme_epf->subsysnqn);
2500 }
2501 
nvmet_pci_epf_subsysnqn_store(struct config_item * item,const char * page,size_t len)2502 static ssize_t nvmet_pci_epf_subsysnqn_store(struct config_item *item,
2503 					     const char *page, size_t len)
2504 {
2505 	struct config_group *group = to_config_group(item);
2506 	struct nvmet_pci_epf *nvme_epf = to_nvme_epf(group);
2507 
2508 	/* Do not allow setting this when the function is already started. */
2509 	if (nvme_epf->ctrl.tctrl)
2510 		return -EBUSY;
2511 
2512 	if (!len)
2513 		return -EINVAL;
2514 
2515 	strscpy(nvme_epf->subsysnqn, page, len);
2516 
2517 	return len;
2518 }
2519 
2520 CONFIGFS_ATTR(nvmet_pci_epf_, subsysnqn);
2521 
nvmet_pci_epf_mdts_kb_show(struct config_item * item,char * page)2522 static ssize_t nvmet_pci_epf_mdts_kb_show(struct config_item *item, char *page)
2523 {
2524 	struct config_group *group = to_config_group(item);
2525 	struct nvmet_pci_epf *nvme_epf = to_nvme_epf(group);
2526 
2527 	return sysfs_emit(page, "%u\n", nvme_epf->mdts_kb);
2528 }
2529 
nvmet_pci_epf_mdts_kb_store(struct config_item * item,const char * page,size_t len)2530 static ssize_t nvmet_pci_epf_mdts_kb_store(struct config_item *item,
2531 					   const char *page, size_t len)
2532 {
2533 	struct config_group *group = to_config_group(item);
2534 	struct nvmet_pci_epf *nvme_epf = to_nvme_epf(group);
2535 	unsigned long mdts_kb;
2536 	int ret;
2537 
2538 	if (nvme_epf->ctrl.tctrl)
2539 		return -EBUSY;
2540 
2541 	ret = kstrtoul(page, 0, &mdts_kb);
2542 	if (ret)
2543 		return ret;
2544 	if (!mdts_kb)
2545 		mdts_kb = NVMET_PCI_EPF_MDTS_KB;
2546 	else if (mdts_kb > NVMET_PCI_EPF_MAX_MDTS_KB)
2547 		mdts_kb = NVMET_PCI_EPF_MAX_MDTS_KB;
2548 
2549 	if (!is_power_of_2(mdts_kb))
2550 		return -EINVAL;
2551 
2552 	nvme_epf->mdts_kb = mdts_kb;
2553 
2554 	return len;
2555 }
2556 
2557 CONFIGFS_ATTR(nvmet_pci_epf_, mdts_kb);
2558 
2559 static struct configfs_attribute *nvmet_pci_epf_attrs[] = {
2560 	&nvmet_pci_epf_attr_portid,
2561 	&nvmet_pci_epf_attr_subsysnqn,
2562 	&nvmet_pci_epf_attr_mdts_kb,
2563 	NULL,
2564 };
2565 
2566 static const struct config_item_type nvmet_pci_epf_group_type = {
2567 	.ct_attrs	= nvmet_pci_epf_attrs,
2568 	.ct_owner	= THIS_MODULE,
2569 };
2570 
nvmet_pci_epf_add_cfs(struct pci_epf * epf,struct config_group * group)2571 static struct config_group *nvmet_pci_epf_add_cfs(struct pci_epf *epf,
2572 						  struct config_group *group)
2573 {
2574 	struct nvmet_pci_epf *nvme_epf = epf_get_drvdata(epf);
2575 
2576 	config_group_init_type_name(&nvme_epf->group, "nvme",
2577 				    &nvmet_pci_epf_group_type);
2578 
2579 	return &nvme_epf->group;
2580 }
2581 
2582 static const struct pci_epf_device_id nvmet_pci_epf_ids[] = {
2583 	{ .name = "nvmet_pci_epf" },
2584 	{},
2585 };
2586 
2587 static struct pci_epf_ops nvmet_pci_epf_ops = {
2588 	.bind	= nvmet_pci_epf_bind,
2589 	.unbind	= nvmet_pci_epf_unbind,
2590 	.add_cfs = nvmet_pci_epf_add_cfs,
2591 };
2592 
2593 static struct pci_epf_driver nvmet_pci_epf_driver = {
2594 	.driver.name	= "nvmet_pci_epf",
2595 	.probe		= nvmet_pci_epf_probe,
2596 	.id_table	= nvmet_pci_epf_ids,
2597 	.ops		= &nvmet_pci_epf_ops,
2598 	.owner		= THIS_MODULE,
2599 };
2600 
nvmet_pci_epf_init_module(void)2601 static int __init nvmet_pci_epf_init_module(void)
2602 {
2603 	int ret;
2604 
2605 	ret = pci_epf_register_driver(&nvmet_pci_epf_driver);
2606 	if (ret)
2607 		return ret;
2608 
2609 	ret = nvmet_register_transport(&nvmet_pci_epf_fabrics_ops);
2610 	if (ret) {
2611 		pci_epf_unregister_driver(&nvmet_pci_epf_driver);
2612 		return ret;
2613 	}
2614 
2615 	return 0;
2616 }
2617 
nvmet_pci_epf_cleanup_module(void)2618 static void __exit nvmet_pci_epf_cleanup_module(void)
2619 {
2620 	nvmet_unregister_transport(&nvmet_pci_epf_fabrics_ops);
2621 	pci_epf_unregister_driver(&nvmet_pci_epf_driver);
2622 }
2623 
2624 module_init(nvmet_pci_epf_init_module);
2625 module_exit(nvmet_pci_epf_cleanup_module);
2626 
2627 MODULE_DESCRIPTION("NVMe PCI Endpoint Function target driver");
2628 MODULE_AUTHOR("Damien Le Moal <dlemoal@kernel.org>");
2629 MODULE_LICENSE("GPL");
2630