xref: /linux/drivers/pci/p2pdma.c (revision 6282ca8585010bfb4ab658243a1665428bcfa9de)
1 // SPDX-License-Identifier: GPL-2.0
2 /*
3  * PCI Peer 2 Peer DMA support.
4  *
5  * Copyright (c) 2016-2018, Logan Gunthorpe
6  * Copyright (c) 2016-2017, Microsemi Corporation
7  * Copyright (c) 2017, Christoph Hellwig
8  * Copyright (c) 2018, Eideticom Inc.
9  */
10 
11 #define pr_fmt(fmt) "pci-p2pdma: " fmt
12 #include <linux/ctype.h>
13 #include <linux/dma-map-ops.h>
14 #include <linux/pci-p2pdma.h>
15 #include <linux/module.h>
16 #include <linux/slab.h>
17 #include <linux/genalloc.h>
18 #include <linux/memremap.h>
19 #include <linux/percpu-refcount.h>
20 #include <linux/random.h>
21 #include <linux/seq_buf.h>
22 #include <linux/xarray.h>
23 
24 struct pci_p2pdma {
25 	struct gen_pool *pool;
26 	bool p2pmem_published;
27 	struct xarray map_types;
28 	struct p2pdma_provider mem[PCI_STD_NUM_BARS];
29 };
30 
31 struct pci_p2pdma_pagemap {
32 	struct dev_pagemap pgmap;
33 	struct p2pdma_provider *mem;
34 };
35 
36 static struct pci_p2pdma_pagemap *to_p2p_pgmap(struct dev_pagemap *pgmap)
37 {
38 	return container_of(pgmap, struct pci_p2pdma_pagemap, pgmap);
39 }
40 
41 static ssize_t size_show(struct device *dev, struct device_attribute *attr,
42 			 char *buf)
43 {
44 	struct pci_dev *pdev = to_pci_dev(dev);
45 	struct pci_p2pdma *p2pdma;
46 	size_t size = 0;
47 
48 	rcu_read_lock();
49 	p2pdma = rcu_dereference(pdev->p2pdma);
50 	if (p2pdma && p2pdma->pool)
51 		size = gen_pool_size(p2pdma->pool);
52 	rcu_read_unlock();
53 
54 	return sysfs_emit(buf, "%zd\n", size);
55 }
56 static DEVICE_ATTR_RO(size);
57 
58 static ssize_t available_show(struct device *dev, struct device_attribute *attr,
59 			      char *buf)
60 {
61 	struct pci_dev *pdev = to_pci_dev(dev);
62 	struct pci_p2pdma *p2pdma;
63 	size_t avail = 0;
64 
65 	rcu_read_lock();
66 	p2pdma = rcu_dereference(pdev->p2pdma);
67 	if (p2pdma && p2pdma->pool)
68 		avail = gen_pool_avail(p2pdma->pool);
69 	rcu_read_unlock();
70 
71 	return sysfs_emit(buf, "%zd\n", avail);
72 }
73 static DEVICE_ATTR_RO(available);
74 
75 static ssize_t published_show(struct device *dev, struct device_attribute *attr,
76 			      char *buf)
77 {
78 	struct pci_dev *pdev = to_pci_dev(dev);
79 	struct pci_p2pdma *p2pdma;
80 	bool published = false;
81 
82 	rcu_read_lock();
83 	p2pdma = rcu_dereference(pdev->p2pdma);
84 	if (p2pdma)
85 		published = p2pdma->p2pmem_published;
86 	rcu_read_unlock();
87 
88 	return sysfs_emit(buf, "%d\n", published);
89 }
90 static DEVICE_ATTR_RO(published);
91 
92 static int p2pmem_alloc_mmap(struct file *filp, struct kobject *kobj,
93 		const struct bin_attribute *attr, struct vm_area_struct *vma)
94 {
95 	struct pci_dev *pdev = to_pci_dev(kobj_to_dev(kobj));
96 	size_t len = vma->vm_end - vma->vm_start;
97 	struct pci_p2pdma *p2pdma;
98 	struct percpu_ref *ref;
99 	unsigned long vaddr;
100 	void *kaddr;
101 	int ret;
102 
103 	/* prevent private mappings from being established */
104 	if ((vma->vm_flags & VM_MAYSHARE) != VM_MAYSHARE) {
105 		pci_info_ratelimited(pdev,
106 				     "%s: fail, attempted private mapping\n",
107 				     current->comm);
108 		return -EINVAL;
109 	}
110 
111 	if (vma->vm_pgoff) {
112 		pci_info_ratelimited(pdev,
113 				     "%s: fail, attempted mapping with non-zero offset\n",
114 				     current->comm);
115 		return -EINVAL;
116 	}
117 
118 	rcu_read_lock();
119 	p2pdma = rcu_dereference(pdev->p2pdma);
120 	if (!p2pdma) {
121 		ret = -ENODEV;
122 		goto out;
123 	}
124 
125 	kaddr = (void *)gen_pool_alloc_owner(p2pdma->pool, len, (void **)&ref);
126 	if (!kaddr) {
127 		ret = -ENOMEM;
128 		goto out;
129 	}
130 
131 	/*
132 	 * vm_insert_page() can sleep, so a reference is taken to mapping
133 	 * such that rcu_read_unlock() can be done before inserting the
134 	 * pages
135 	 */
136 	if (unlikely(!percpu_ref_tryget_live_rcu(ref))) {
137 		ret = -ENODEV;
138 		goto out_free_mem;
139 	}
140 	rcu_read_unlock();
141 
142 	for (vaddr = vma->vm_start; vaddr < vma->vm_end; vaddr += PAGE_SIZE) {
143 		struct page *page = virt_to_page(kaddr);
144 
145 		/*
146 		 * Initialise the refcount for the freshly allocated page. As
147 		 * we have just allocated the page no one else should be
148 		 * using it.
149 		 */
150 		VM_WARN_ON_ONCE_PAGE(!page_ref_count(page), page);
151 		set_page_count(page, 1);
152 		ret = vm_insert_page(vma, vaddr, page);
153 		if (ret) {
154 			gen_pool_free(p2pdma->pool, (uintptr_t)kaddr, len);
155 			return ret;
156 		}
157 		percpu_ref_get(ref);
158 		put_page(page);
159 		kaddr += PAGE_SIZE;
160 		len -= PAGE_SIZE;
161 	}
162 
163 	percpu_ref_put(ref);
164 
165 	return 0;
166 out_free_mem:
167 	gen_pool_free(p2pdma->pool, (uintptr_t)kaddr, len);
168 out:
169 	rcu_read_unlock();
170 	return ret;
171 }
172 
173 static const struct bin_attribute p2pmem_alloc_attr = {
174 	.attr = { .name = "allocate", .mode = 0660 },
175 	.mmap = p2pmem_alloc_mmap,
176 	/*
177 	 * Some places where we want to call mmap (ie. python) will check
178 	 * that the file size is greater than the mmap size before allowing
179 	 * the mmap to continue. To work around this, just set the size
180 	 * to be very large.
181 	 */
182 	.size = SZ_1T,
183 };
184 
185 static struct attribute *p2pmem_attrs[] = {
186 	&dev_attr_size.attr,
187 	&dev_attr_available.attr,
188 	&dev_attr_published.attr,
189 	NULL,
190 };
191 
192 static const struct bin_attribute *const p2pmem_bin_attrs[] = {
193 	&p2pmem_alloc_attr,
194 	NULL,
195 };
196 
197 static const struct attribute_group p2pmem_group = {
198 	.attrs = p2pmem_attrs,
199 	.bin_attrs = p2pmem_bin_attrs,
200 	.name = "p2pmem",
201 };
202 
203 static void p2pdma_page_free(struct page *page)
204 {
205 	struct pci_p2pdma_pagemap *pgmap = to_p2p_pgmap(page_pgmap(page));
206 	/* safe to dereference while a reference is held to the percpu ref */
207 	struct pci_p2pdma *p2pdma = rcu_dereference_protected(
208 		to_pci_dev(pgmap->mem->owner)->p2pdma, 1);
209 	struct percpu_ref *ref;
210 
211 	gen_pool_free_owner(p2pdma->pool, (uintptr_t)page_to_virt(page),
212 			    PAGE_SIZE, (void **)&ref);
213 	percpu_ref_put(ref);
214 }
215 
216 static const struct dev_pagemap_ops p2pdma_pgmap_ops = {
217 	.page_free = p2pdma_page_free,
218 };
219 
220 static void pci_p2pdma_release(void *data)
221 {
222 	struct pci_dev *pdev = data;
223 	struct pci_p2pdma *p2pdma;
224 
225 	p2pdma = rcu_dereference_protected(pdev->p2pdma, 1);
226 	if (!p2pdma)
227 		return;
228 
229 	/* Flush and disable pci_alloc_p2p_mem() */
230 	pdev->p2pdma = NULL;
231 	if (p2pdma->pool)
232 		synchronize_rcu();
233 	xa_destroy(&p2pdma->map_types);
234 
235 	if (!p2pdma->pool)
236 		return;
237 
238 	gen_pool_destroy(p2pdma->pool);
239 	sysfs_remove_group(&pdev->dev.kobj, &p2pmem_group);
240 }
241 
242 /**
243  * pcim_p2pdma_init - Initialise peer-to-peer DMA providers
244  * @pdev: The PCI device to enable P2PDMA for
245  *
246  * This function initializes the peer-to-peer DMA infrastructure
247  * for a PCI device. It allocates and sets up the necessary data
248  * structures to support P2PDMA operations, including mapping type
249  * tracking.
250  */
251 int pcim_p2pdma_init(struct pci_dev *pdev)
252 {
253 	struct pci_p2pdma *p2p;
254 	int i, ret;
255 
256 	p2p = rcu_dereference_protected(pdev->p2pdma, 1);
257 	if (p2p)
258 		return 0;
259 
260 	p2p = devm_kzalloc(&pdev->dev, sizeof(*p2p), GFP_KERNEL);
261 	if (!p2p)
262 		return -ENOMEM;
263 
264 	xa_init(&p2p->map_types);
265 	/*
266 	 * Iterate over all standard PCI BARs and record only those that
267 	 * correspond to MMIO regions. Skip non-memory resources (e.g. I/O
268 	 * port BARs) since they cannot be used for peer-to-peer (P2P)
269 	 * transactions.
270 	 */
271 	for (i = 0; i < PCI_STD_NUM_BARS; i++) {
272 		if (!(pci_resource_flags(pdev, i) & IORESOURCE_MEM))
273 			continue;
274 
275 		p2p->mem[i].owner = &pdev->dev;
276 		p2p->mem[i].bus_offset =
277 			pci_bus_address(pdev, i) - pci_resource_start(pdev, i);
278 	}
279 
280 	ret = devm_add_action_or_reset(&pdev->dev, pci_p2pdma_release, pdev);
281 	if (ret)
282 		goto out_p2p;
283 
284 	rcu_assign_pointer(pdev->p2pdma, p2p);
285 	return 0;
286 
287 out_p2p:
288 	devm_kfree(&pdev->dev, p2p);
289 	return ret;
290 }
291 EXPORT_SYMBOL_GPL(pcim_p2pdma_init);
292 
293 /**
294  * pcim_p2pdma_provider - Get peer-to-peer DMA provider
295  * @pdev: The PCI device to enable P2PDMA for
296  * @bar: BAR index to get provider
297  *
298  * This function gets peer-to-peer DMA provider for a PCI device. The lifetime
299  * of the provider (and of course the MMIO) is bound to the lifetime of the
300  * driver. A driver calling this function must ensure that all references to the
301  * provider, and any DMA mappings created for any MMIO, are all cleaned up
302  * before the driver remove() completes.
303  *
304  * Since P2P is almost always shared with a second driver this means some system
305  * to notify, invalidate and revoke the MMIO's DMA must be in place to use this
306  * function. For example a revoke can be built using DMABUF.
307  */
308 struct p2pdma_provider *pcim_p2pdma_provider(struct pci_dev *pdev, int bar)
309 {
310 	struct pci_p2pdma *p2p;
311 
312 	if (!(pci_resource_flags(pdev, bar) & IORESOURCE_MEM))
313 		return NULL;
314 
315 	p2p = rcu_dereference_protected(pdev->p2pdma, 1);
316 	if (WARN_ON(!p2p))
317 		/* Someone forgot to call to pcim_p2pdma_init() before */
318 		return NULL;
319 
320 	return &p2p->mem[bar];
321 }
322 EXPORT_SYMBOL_GPL(pcim_p2pdma_provider);
323 
324 static int pci_p2pdma_setup_pool(struct pci_dev *pdev)
325 {
326 	struct pci_p2pdma *p2pdma;
327 	int ret;
328 
329 	p2pdma = rcu_dereference_protected(pdev->p2pdma, 1);
330 	if (p2pdma->pool)
331 		/* We already setup pools, do nothing, */
332 		return 0;
333 
334 	p2pdma->pool = gen_pool_create(PAGE_SHIFT, dev_to_node(&pdev->dev));
335 	if (!p2pdma->pool)
336 		return -ENOMEM;
337 
338 	ret = sysfs_create_group(&pdev->dev.kobj, &p2pmem_group);
339 	if (ret)
340 		goto out_pool_destroy;
341 
342 	return 0;
343 
344 out_pool_destroy:
345 	gen_pool_destroy(p2pdma->pool);
346 	p2pdma->pool = NULL;
347 	return ret;
348 }
349 
350 static void pci_p2pdma_unmap_mappings(void *data)
351 {
352 	struct pci_p2pdma_pagemap *p2p_pgmap = data;
353 
354 	/*
355 	 * Removing the alloc attribute from sysfs will call
356 	 * unmap_mapping_range() on the inode, teardown any existing userspace
357 	 * mappings and prevent new ones from being created.
358 	 */
359 	sysfs_remove_file_from_group(&p2p_pgmap->mem->owner->kobj,
360 				     &p2pmem_alloc_attr.attr,
361 				     p2pmem_group.name);
362 }
363 
364 /**
365  * pci_p2pdma_add_resource - add memory for use as p2p memory
366  * @pdev: the device to add the memory to
367  * @bar: PCI BAR to add
368  * @size: size of the memory to add, may be zero to use the whole BAR
369  * @offset: offset into the PCI BAR
370  *
371  * The memory will be given ZONE_DEVICE struct pages so that it may
372  * be used with any DMA request.
373  */
374 int pci_p2pdma_add_resource(struct pci_dev *pdev, int bar, size_t size,
375 			    u64 offset)
376 {
377 	struct pci_p2pdma_pagemap *p2p_pgmap;
378 	struct p2pdma_provider *mem;
379 	struct dev_pagemap *pgmap;
380 	struct pci_p2pdma *p2pdma;
381 	void *addr;
382 	int error;
383 
384 	if (!(pci_resource_flags(pdev, bar) & IORESOURCE_MEM))
385 		return -EINVAL;
386 
387 	if (offset >= pci_resource_len(pdev, bar))
388 		return -EINVAL;
389 
390 	if (!size)
391 		size = pci_resource_len(pdev, bar) - offset;
392 
393 	if (size + offset > pci_resource_len(pdev, bar))
394 		return -EINVAL;
395 
396 	error = pcim_p2pdma_init(pdev);
397 	if (error)
398 		return error;
399 
400 	error = pci_p2pdma_setup_pool(pdev);
401 	if (error)
402 		return error;
403 
404 	mem = pcim_p2pdma_provider(pdev, bar);
405 	/*
406 	 * We checked validity of BAR prior to call
407 	 * to pcim_p2pdma_provider. It should never return NULL.
408 	 */
409 	if (WARN_ON(!mem))
410 		return -EINVAL;
411 
412 	p2p_pgmap = devm_kzalloc(&pdev->dev, sizeof(*p2p_pgmap), GFP_KERNEL);
413 	if (!p2p_pgmap)
414 		return -ENOMEM;
415 
416 	pgmap = &p2p_pgmap->pgmap;
417 	pgmap->range.start = pci_resource_start(pdev, bar) + offset;
418 	pgmap->range.end = pgmap->range.start + size - 1;
419 	pgmap->nr_range = 1;
420 	pgmap->type = MEMORY_DEVICE_PCI_P2PDMA;
421 	pgmap->ops = &p2pdma_pgmap_ops;
422 	p2p_pgmap->mem = mem;
423 
424 	addr = devm_memremap_pages(&pdev->dev, pgmap);
425 	if (IS_ERR(addr)) {
426 		error = PTR_ERR(addr);
427 		goto pgmap_free;
428 	}
429 
430 	error = devm_add_action_or_reset(&pdev->dev, pci_p2pdma_unmap_mappings,
431 					 p2p_pgmap);
432 	if (error)
433 		goto pages_free;
434 
435 	p2pdma = rcu_dereference_protected(pdev->p2pdma, 1);
436 	error = gen_pool_add_owner(p2pdma->pool, (unsigned long)addr,
437 			pci_bus_address(pdev, bar) + offset,
438 			range_len(&pgmap->range), dev_to_node(&pdev->dev),
439 			&pgmap->ref);
440 	if (error)
441 		goto pages_free;
442 
443 	pci_info(pdev, "added peer-to-peer DMA memory %#llx-%#llx\n",
444 		 pgmap->range.start, pgmap->range.end);
445 
446 	return 0;
447 
448 pages_free:
449 	devm_memunmap_pages(&pdev->dev, pgmap);
450 pgmap_free:
451 	devm_kfree(&pdev->dev, p2p_pgmap);
452 	return error;
453 }
454 EXPORT_SYMBOL_GPL(pci_p2pdma_add_resource);
455 
456 /*
457  * Note this function returns the parent PCI device with a
458  * reference taken. It is the caller's responsibility to drop
459  * the reference.
460  */
461 static struct pci_dev *find_parent_pci_dev(struct device *dev)
462 {
463 	struct device *parent;
464 
465 	dev = get_device(dev);
466 
467 	while (dev) {
468 		if (dev_is_pci(dev))
469 			return to_pci_dev(dev);
470 
471 		parent = get_device(dev->parent);
472 		put_device(dev);
473 		dev = parent;
474 	}
475 
476 	return NULL;
477 }
478 
479 /*
480  * Check if a PCI bridge has its ACS redirection bits set to redirect P2P
481  * TLPs upstream via ACS. Returns 1 if the packets will be redirected
482  * upstream, 0 otherwise.
483  */
484 static int pci_bridge_has_acs_redir(struct pci_dev *pdev)
485 {
486 	int pos;
487 	u16 ctrl;
488 
489 	pos = pdev->acs_cap;
490 	if (!pos)
491 		return 0;
492 
493 	pci_read_config_word(pdev, pos + PCI_ACS_CTRL, &ctrl);
494 
495 	if (ctrl & (PCI_ACS_RR | PCI_ACS_CR | PCI_ACS_EC))
496 		return 1;
497 
498 	return 0;
499 }
500 
501 static void seq_buf_print_bus_devfn(struct seq_buf *buf, struct pci_dev *pdev)
502 {
503 	if (!buf)
504 		return;
505 
506 	seq_buf_printf(buf, "%s;", pci_name(pdev));
507 }
508 
509 static bool cpu_supports_p2pdma(void)
510 {
511 #ifdef CONFIG_X86
512 	struct cpuinfo_x86 *c = &cpu_data(0);
513 
514 	/* Any AMD CPU whose family ID is Zen or newer supports p2pdma */
515 	if (c->x86_vendor == X86_VENDOR_AMD && c->x86 >= 0x17)
516 		return true;
517 #endif
518 
519 	return false;
520 }
521 
522 static const struct pci_p2pdma_whitelist_entry {
523 	unsigned short vendor;
524 	unsigned short device;
525 	enum {
526 		REQ_SAME_HOST_BRIDGE	= 1 << 0,
527 	} flags;
528 } pci_p2pdma_whitelist[] = {
529 	/* Intel Xeon E5/Core i7 */
530 	{PCI_VENDOR_ID_INTEL,	0x3c00, REQ_SAME_HOST_BRIDGE},
531 	{PCI_VENDOR_ID_INTEL,	0x3c01, REQ_SAME_HOST_BRIDGE},
532 	/* Intel Xeon E7 v3/Xeon E5 v3/Core i7 */
533 	{PCI_VENDOR_ID_INTEL,	0x2f00, REQ_SAME_HOST_BRIDGE},
534 	{PCI_VENDOR_ID_INTEL,	0x2f01, REQ_SAME_HOST_BRIDGE},
535 	/* Intel Skylake-E */
536 	{PCI_VENDOR_ID_INTEL,	0x2030, 0},
537 	{PCI_VENDOR_ID_INTEL,	0x2031, 0},
538 	{PCI_VENDOR_ID_INTEL,	0x2032, 0},
539 	{PCI_VENDOR_ID_INTEL,	0x2033, 0},
540 	{PCI_VENDOR_ID_INTEL,	0x2020, 0},
541 	{PCI_VENDOR_ID_INTEL,	0x09a2, 0},
542 	{}
543 };
544 
545 /*
546  * If the first device on host's root bus is either devfn 00.0 or a PCIe
547  * Root Port, return it.  Otherwise return NULL.
548  *
549  * We often use a devfn 00.0 "host bridge" in the pci_p2pdma_whitelist[]
550  * (though there is no PCI/PCIe requirement for such a device).  On some
551  * platforms, e.g., Intel Skylake, there is no such host bridge device, and
552  * pci_p2pdma_whitelist[] may contain a Root Port at any devfn.
553  *
554  * This function is similar to pci_get_slot(host->bus, 0), but it does
555  * not take the pci_bus_sem lock since __host_bridge_whitelist() must not
556  * sleep.
557  *
558  * For this to be safe, the caller should hold a reference to a device on the
559  * bridge, which should ensure the host_bridge device will not be freed
560  * or removed from the head of the devices list.
561  */
562 static struct pci_dev *pci_host_bridge_dev(struct pci_host_bridge *host)
563 {
564 	struct pci_dev *root;
565 
566 	root = list_first_entry_or_null(&host->bus->devices,
567 					struct pci_dev, bus_list);
568 
569 	if (!root)
570 		return NULL;
571 
572 	if (root->devfn == PCI_DEVFN(0, 0))
573 		return root;
574 
575 	if (pci_pcie_type(root) == PCI_EXP_TYPE_ROOT_PORT)
576 		return root;
577 
578 	return NULL;
579 }
580 
581 static bool __host_bridge_whitelist(struct pci_host_bridge *host,
582 				    bool same_host_bridge, bool warn)
583 {
584 	struct pci_dev *root = pci_host_bridge_dev(host);
585 	const struct pci_p2pdma_whitelist_entry *entry;
586 	unsigned short vendor, device;
587 
588 	if (!root)
589 		return false;
590 
591 	vendor = root->vendor;
592 	device = root->device;
593 
594 	for (entry = pci_p2pdma_whitelist; entry->vendor; entry++) {
595 		if (vendor != entry->vendor || device != entry->device)
596 			continue;
597 		if (entry->flags & REQ_SAME_HOST_BRIDGE && !same_host_bridge)
598 			return false;
599 
600 		return true;
601 	}
602 
603 	if (warn)
604 		pci_warn(root, "Host bridge not in P2PDMA whitelist: %04x:%04x\n",
605 			 vendor, device);
606 
607 	return false;
608 }
609 
610 /*
611  * If we can't find a common upstream bridge take a look at the root
612  * complex and compare it to a whitelist of known good hardware.
613  */
614 static bool host_bridge_whitelist(struct pci_dev *a, struct pci_dev *b,
615 				  bool warn)
616 {
617 	struct pci_host_bridge *host_a = pci_find_host_bridge(a->bus);
618 	struct pci_host_bridge *host_b = pci_find_host_bridge(b->bus);
619 
620 	if (host_a == host_b)
621 		return __host_bridge_whitelist(host_a, true, warn);
622 
623 	if (__host_bridge_whitelist(host_a, false, warn) &&
624 	    __host_bridge_whitelist(host_b, false, warn))
625 		return true;
626 
627 	return false;
628 }
629 
630 static unsigned long map_types_idx(struct pci_dev *client)
631 {
632 	return (pci_domain_nr(client->bus) << 16) | pci_dev_id(client);
633 }
634 
635 /*
636  * Calculate the P2PDMA mapping type and distance between two PCI devices.
637  *
638  * If the two devices are the same PCI function, return
639  * PCI_P2PDMA_MAP_BUS_ADDR and a distance of 0.
640  *
641  * If they are two functions of the same device, return
642  * PCI_P2PDMA_MAP_BUS_ADDR and a distance of 2 (one hop up to the bridge,
643  * then one hop back down to another function of the same device).
644  *
645  * In the case where two devices are connected to the same PCIe switch,
646  * return a distance of 4. This corresponds to the following PCI tree:
647  *
648  *     -+  Root Port
649  *      \+ Switch Upstream Port
650  *       +-+ Switch Downstream Port 0
651  *       + \- Device A
652  *       \-+ Switch Downstream Port 1
653  *         \- Device B
654  *
655  * The distance is 4 because we traverse from Device A to Downstream Port 0
656  * to the common Switch Upstream Port, back down to Downstream Port 1 and
657  * then to Device B. The mapping type returned depends on the ACS
658  * redirection setting of the ports along the path.
659  *
660  * If ACS redirect is set on any port in the path, traffic between the
661  * devices will go through the host bridge, so return
662  * PCI_P2PDMA_MAP_THRU_HOST_BRIDGE; otherwise return
663  * PCI_P2PDMA_MAP_BUS_ADDR.
664  *
665  * Any two devices that have a data path that goes through the host bridge
666  * will consult a whitelist. If the host bridge is in the whitelist, return
667  * PCI_P2PDMA_MAP_THRU_HOST_BRIDGE with the distance set to the number of
668  * ports per above. If the device is not in the whitelist, return
669  * PCI_P2PDMA_MAP_NOT_SUPPORTED.
670  */
671 static enum pci_p2pdma_map_type
672 calc_map_type_and_dist(struct pci_dev *provider, struct pci_dev *client,
673 		int *dist, bool verbose)
674 {
675 	enum pci_p2pdma_map_type map_type = PCI_P2PDMA_MAP_THRU_HOST_BRIDGE;
676 	struct pci_dev *a = provider, *b = client, *bb;
677 	bool acs_redirects = false;
678 	struct pci_p2pdma *p2pdma;
679 	struct seq_buf acs_list;
680 	int acs_cnt = 0;
681 	int dist_a = 0;
682 	int dist_b = 0;
683 	char buf[128];
684 
685 	seq_buf_init(&acs_list, buf, sizeof(buf));
686 
687 	/*
688 	 * Note, we don't need to take references to devices returned by
689 	 * pci_upstream_bridge() seeing we hold a reference to a child
690 	 * device which will already hold a reference to the upstream bridge.
691 	 */
692 	while (a) {
693 		dist_b = 0;
694 
695 		if (pci_bridge_has_acs_redir(a)) {
696 			seq_buf_print_bus_devfn(&acs_list, a);
697 			acs_cnt++;
698 		}
699 
700 		bb = b;
701 
702 		while (bb) {
703 			if (a == bb)
704 				goto check_b_path_acs;
705 
706 			bb = pci_upstream_bridge(bb);
707 			dist_b++;
708 		}
709 
710 		a = pci_upstream_bridge(a);
711 		dist_a++;
712 	}
713 
714 	*dist = dist_a + dist_b;
715 	goto map_through_host_bridge;
716 
717 check_b_path_acs:
718 	bb = b;
719 
720 	while (bb) {
721 		if (a == bb)
722 			break;
723 
724 		if (pci_bridge_has_acs_redir(bb)) {
725 			seq_buf_print_bus_devfn(&acs_list, bb);
726 			acs_cnt++;
727 		}
728 
729 		bb = pci_upstream_bridge(bb);
730 	}
731 
732 	*dist = dist_a + dist_b;
733 
734 	if (!acs_cnt) {
735 		map_type = PCI_P2PDMA_MAP_BUS_ADDR;
736 		goto done;
737 	}
738 
739 	if (verbose) {
740 		acs_list.buffer[acs_list.len-1] = 0; /* drop final semicolon */
741 		pci_warn(client, "ACS redirect is set between the client and provider (%s)\n",
742 			 pci_name(provider));
743 		pci_warn(client, "to disable ACS redirect for this path, add the kernel parameter: pci=disable_acs_redir=%s\n",
744 			 acs_list.buffer);
745 	}
746 	acs_redirects = true;
747 
748 map_through_host_bridge:
749 	if (!cpu_supports_p2pdma() &&
750 	    !host_bridge_whitelist(provider, client, acs_redirects)) {
751 		if (verbose)
752 			pci_warn(client, "cannot be used for peer-to-peer DMA as the client and provider (%s) do not share an upstream bridge or whitelisted host bridge\n",
753 				 pci_name(provider));
754 		map_type = PCI_P2PDMA_MAP_NOT_SUPPORTED;
755 	}
756 done:
757 	rcu_read_lock();
758 	p2pdma = rcu_dereference(provider->p2pdma);
759 	if (p2pdma)
760 		xa_store(&p2pdma->map_types, map_types_idx(client),
761 			 xa_mk_value(map_type), GFP_ATOMIC);
762 	rcu_read_unlock();
763 	return map_type;
764 }
765 
766 /**
767  * pci_p2pdma_distance_many - Determine the cumulative distance between
768  *	a p2pdma provider and the clients in use.
769  * @provider: p2pdma provider to check against the client list
770  * @clients: array of devices to check (NULL-terminated)
771  * @num_clients: number of clients in the array
772  * @verbose: if true, print warnings for devices when we return -1
773  *
774  * Returns -1 if any of the clients are not compatible, otherwise returns a
775  * positive number where a lower number is the preferable choice. (If there's
776  * one client that's the same as the provider it will return 0, which is best
777  * choice).
778  *
779  * "compatible" means the provider and the clients are either all behind
780  * the same PCI root port or the host bridges connected to each of the devices
781  * are listed in the 'pci_p2pdma_whitelist'.
782  */
783 int pci_p2pdma_distance_many(struct pci_dev *provider, struct device **clients,
784 			     int num_clients, bool verbose)
785 {
786 	enum pci_p2pdma_map_type map;
787 	bool not_supported = false;
788 	struct pci_dev *pci_client;
789 	int total_dist = 0;
790 	int i, distance;
791 
792 	if (num_clients == 0)
793 		return -1;
794 
795 	for (i = 0; i < num_clients; i++) {
796 		pci_client = find_parent_pci_dev(clients[i]);
797 		if (!pci_client) {
798 			if (verbose)
799 				dev_warn(clients[i],
800 					 "cannot be used for peer-to-peer DMA as it is not a PCI device\n");
801 			return -1;
802 		}
803 
804 		map = calc_map_type_and_dist(provider, pci_client, &distance,
805 					     verbose);
806 
807 		pci_dev_put(pci_client);
808 
809 		if (map == PCI_P2PDMA_MAP_NOT_SUPPORTED)
810 			not_supported = true;
811 
812 		if (not_supported && !verbose)
813 			break;
814 
815 		total_dist += distance;
816 	}
817 
818 	if (not_supported)
819 		return -1;
820 
821 	return total_dist;
822 }
823 EXPORT_SYMBOL_GPL(pci_p2pdma_distance_many);
824 
825 /**
826  * pci_has_p2pmem - check if a given PCI device has published any p2pmem
827  * @pdev: PCI device to check
828  */
829 static bool pci_has_p2pmem(struct pci_dev *pdev)
830 {
831 	struct pci_p2pdma *p2pdma;
832 	bool res;
833 
834 	rcu_read_lock();
835 	p2pdma = rcu_dereference(pdev->p2pdma);
836 	res = p2pdma && p2pdma->p2pmem_published;
837 	rcu_read_unlock();
838 
839 	return res;
840 }
841 
842 /**
843  * pci_p2pmem_find_many - find a peer-to-peer DMA memory device compatible with
844  *	the specified list of clients and shortest distance
845  * @clients: array of devices to check (NULL-terminated)
846  * @num_clients: number of client devices in the list
847  *
848  * If multiple devices are behind the same switch, the one "closest" to the
849  * client devices in use will be chosen first. (So if one of the providers is
850  * the same as one of the clients, that provider will be used ahead of any
851  * other providers that are unrelated). If multiple providers are an equal
852  * distance away, one will be chosen at random.
853  *
854  * Returns a pointer to the PCI device with a reference taken (use pci_dev_put
855  * to return the reference) or NULL if no compatible device is found. The
856  * found provider will also be assigned to the client list.
857  */
858 struct pci_dev *pci_p2pmem_find_many(struct device **clients, int num_clients)
859 {
860 	struct pci_dev *pdev = NULL;
861 	int distance;
862 	int closest_distance = INT_MAX;
863 	struct pci_dev **closest_pdevs;
864 	int dev_cnt = 0;
865 	const int max_devs = PAGE_SIZE / sizeof(*closest_pdevs);
866 	int i;
867 
868 	closest_pdevs = kmalloc(PAGE_SIZE, GFP_KERNEL);
869 	if (!closest_pdevs)
870 		return NULL;
871 
872 	for_each_pci_dev(pdev) {
873 		if (!pci_has_p2pmem(pdev))
874 			continue;
875 
876 		distance = pci_p2pdma_distance_many(pdev, clients,
877 						    num_clients, false);
878 		if (distance < 0 || distance > closest_distance)
879 			continue;
880 
881 		if (distance == closest_distance && dev_cnt >= max_devs)
882 			continue;
883 
884 		if (distance < closest_distance) {
885 			for (i = 0; i < dev_cnt; i++)
886 				pci_dev_put(closest_pdevs[i]);
887 
888 			dev_cnt = 0;
889 			closest_distance = distance;
890 		}
891 
892 		closest_pdevs[dev_cnt++] = pci_dev_get(pdev);
893 	}
894 
895 	if (dev_cnt)
896 		pdev = pci_dev_get(closest_pdevs[get_random_u32_below(dev_cnt)]);
897 
898 	for (i = 0; i < dev_cnt; i++)
899 		pci_dev_put(closest_pdevs[i]);
900 
901 	kfree(closest_pdevs);
902 	return pdev;
903 }
904 EXPORT_SYMBOL_GPL(pci_p2pmem_find_many);
905 
906 /**
907  * pci_alloc_p2pmem - allocate peer-to-peer DMA memory
908  * @pdev: the device to allocate memory from
909  * @size: number of bytes to allocate
910  *
911  * Returns the allocated memory or NULL on error.
912  */
913 void *pci_alloc_p2pmem(struct pci_dev *pdev, size_t size)
914 {
915 	void *ret = NULL;
916 	struct percpu_ref *ref;
917 	struct pci_p2pdma *p2pdma;
918 
919 	/*
920 	 * Pairs with synchronize_rcu() in pci_p2pdma_release() to
921 	 * ensure pdev->p2pdma is non-NULL for the duration of the
922 	 * read-lock.
923 	 */
924 	rcu_read_lock();
925 	p2pdma = rcu_dereference(pdev->p2pdma);
926 	if (unlikely(!p2pdma))
927 		goto out;
928 
929 	ret = (void *)gen_pool_alloc_owner(p2pdma->pool, size, (void **) &ref);
930 	if (!ret)
931 		goto out;
932 
933 	if (unlikely(!percpu_ref_tryget_live_rcu(ref))) {
934 		gen_pool_free(p2pdma->pool, (unsigned long) ret, size);
935 		ret = NULL;
936 	}
937 out:
938 	rcu_read_unlock();
939 	return ret;
940 }
941 EXPORT_SYMBOL_GPL(pci_alloc_p2pmem);
942 
943 /**
944  * pci_free_p2pmem - free peer-to-peer DMA memory
945  * @pdev: the device the memory was allocated from
946  * @addr: address of the memory that was allocated
947  * @size: number of bytes that were allocated
948  */
949 void pci_free_p2pmem(struct pci_dev *pdev, void *addr, size_t size)
950 {
951 	struct percpu_ref *ref;
952 	struct pci_p2pdma *p2pdma = rcu_dereference_protected(pdev->p2pdma, 1);
953 
954 	gen_pool_free_owner(p2pdma->pool, (uintptr_t)addr, size,
955 			(void **) &ref);
956 	percpu_ref_put(ref);
957 }
958 EXPORT_SYMBOL_GPL(pci_free_p2pmem);
959 
960 /**
961  * pci_p2pmem_virt_to_bus - return the PCI bus address for a given virtual
962  *	address obtained with pci_alloc_p2pmem()
963  * @pdev: the device the memory was allocated from
964  * @addr: address of the memory that was allocated
965  */
966 pci_bus_addr_t pci_p2pmem_virt_to_bus(struct pci_dev *pdev, void *addr)
967 {
968 	struct pci_p2pdma *p2pdma;
969 
970 	if (!addr)
971 		return 0;
972 
973 	p2pdma = rcu_dereference_protected(pdev->p2pdma, 1);
974 	if (!p2pdma)
975 		return 0;
976 
977 	/*
978 	 * Note: when we added the memory to the pool we used the PCI
979 	 * bus address as the physical address. So gen_pool_virt_to_phys()
980 	 * actually returns the bus address despite the misleading name.
981 	 */
982 	return gen_pool_virt_to_phys(p2pdma->pool, (unsigned long)addr);
983 }
984 EXPORT_SYMBOL_GPL(pci_p2pmem_virt_to_bus);
985 
986 /**
987  * pci_p2pmem_alloc_sgl - allocate peer-to-peer DMA memory in a scatterlist
988  * @pdev: the device to allocate memory from
989  * @nents: the number of SG entries in the list
990  * @length: number of bytes to allocate
991  *
992  * Return: %NULL on error or &struct scatterlist pointer and @nents on success
993  */
994 struct scatterlist *pci_p2pmem_alloc_sgl(struct pci_dev *pdev,
995 					 unsigned int *nents, u32 length)
996 {
997 	struct scatterlist *sg;
998 	void *addr;
999 
1000 	sg = kmalloc(sizeof(*sg), GFP_KERNEL);
1001 	if (!sg)
1002 		return NULL;
1003 
1004 	sg_init_table(sg, 1);
1005 
1006 	addr = pci_alloc_p2pmem(pdev, length);
1007 	if (!addr)
1008 		goto out_free_sg;
1009 
1010 	sg_set_buf(sg, addr, length);
1011 	*nents = 1;
1012 	return sg;
1013 
1014 out_free_sg:
1015 	kfree(sg);
1016 	return NULL;
1017 }
1018 EXPORT_SYMBOL_GPL(pci_p2pmem_alloc_sgl);
1019 
1020 /**
1021  * pci_p2pmem_free_sgl - free a scatterlist allocated by pci_p2pmem_alloc_sgl()
1022  * @pdev: the device to allocate memory from
1023  * @sgl: the allocated scatterlist
1024  */
1025 void pci_p2pmem_free_sgl(struct pci_dev *pdev, struct scatterlist *sgl)
1026 {
1027 	struct scatterlist *sg;
1028 	int count;
1029 
1030 	for_each_sg(sgl, sg, INT_MAX, count) {
1031 		if (!sg)
1032 			break;
1033 
1034 		pci_free_p2pmem(pdev, sg_virt(sg), sg->length);
1035 	}
1036 	kfree(sgl);
1037 }
1038 EXPORT_SYMBOL_GPL(pci_p2pmem_free_sgl);
1039 
1040 /**
1041  * pci_p2pmem_publish - publish the peer-to-peer DMA memory for use by
1042  *	other devices with pci_p2pmem_find()
1043  * @pdev: the device with peer-to-peer DMA memory to publish
1044  * @publish: set to true to publish the memory, false to unpublish it
1045  *
1046  * Published memory can be used by other PCI device drivers for
1047  * peer-2-peer DMA operations. Non-published memory is reserved for
1048  * exclusive use of the device driver that registers the peer-to-peer
1049  * memory.
1050  */
1051 void pci_p2pmem_publish(struct pci_dev *pdev, bool publish)
1052 {
1053 	struct pci_p2pdma *p2pdma;
1054 
1055 	rcu_read_lock();
1056 	p2pdma = rcu_dereference(pdev->p2pdma);
1057 	if (p2pdma)
1058 		p2pdma->p2pmem_published = publish;
1059 	rcu_read_unlock();
1060 }
1061 EXPORT_SYMBOL_GPL(pci_p2pmem_publish);
1062 
1063 /**
1064  * pci_p2pdma_map_type - Determine the mapping type for P2PDMA transfers
1065  * @provider: P2PDMA provider structure
1066  * @dev: Target device for the transfer
1067  *
1068  * Determines how peer-to-peer DMA transfers should be mapped between
1069  * the provider and the target device. The mapping type indicates whether
1070  * the transfer can be done directly through PCI switches or must go
1071  * through the host bridge.
1072  */
1073 enum pci_p2pdma_map_type pci_p2pdma_map_type(struct p2pdma_provider *provider,
1074 					     struct device *dev)
1075 {
1076 	enum pci_p2pdma_map_type type = PCI_P2PDMA_MAP_NOT_SUPPORTED;
1077 	struct pci_dev *pdev = to_pci_dev(provider->owner);
1078 	struct pci_dev *client;
1079 	struct pci_p2pdma *p2pdma;
1080 	int dist;
1081 
1082 	if (!pdev->p2pdma)
1083 		return PCI_P2PDMA_MAP_NOT_SUPPORTED;
1084 
1085 	if (!dev_is_pci(dev))
1086 		return PCI_P2PDMA_MAP_NOT_SUPPORTED;
1087 
1088 	client = to_pci_dev(dev);
1089 
1090 	rcu_read_lock();
1091 	p2pdma = rcu_dereference(pdev->p2pdma);
1092 
1093 	if (p2pdma)
1094 		type = xa_to_value(xa_load(&p2pdma->map_types,
1095 					   map_types_idx(client)));
1096 	rcu_read_unlock();
1097 
1098 	if (type == PCI_P2PDMA_MAP_UNKNOWN)
1099 		return calc_map_type_and_dist(pdev, client, &dist, true);
1100 
1101 	return type;
1102 }
1103 
1104 void __pci_p2pdma_update_state(struct pci_p2pdma_map_state *state,
1105 		struct device *dev, struct page *page)
1106 {
1107 	struct pci_p2pdma_pagemap *p2p_pgmap = to_p2p_pgmap(page_pgmap(page));
1108 
1109 	if (state->mem == p2p_pgmap->mem)
1110 		return;
1111 
1112 	state->mem = p2p_pgmap->mem;
1113 	state->map = pci_p2pdma_map_type(p2p_pgmap->mem, dev);
1114 }
1115 
1116 /**
1117  * pci_p2pdma_enable_store - parse a configfs/sysfs attribute store
1118  *		to enable p2pdma
1119  * @page: contents of the value to be stored
1120  * @p2p_dev: returns the PCI device that was selected to be used
1121  *		(if one was specified in the stored value)
1122  * @use_p2pdma: returns whether to enable p2pdma or not
1123  *
1124  * Parses an attribute value to decide whether to enable p2pdma.
1125  * The value can select a PCI device (using its full BDF device
1126  * name) or a boolean (in any format kstrtobool() accepts). A false
1127  * value disables p2pdma, a true value expects the caller
1128  * to automatically find a compatible device and specifying a PCI device
1129  * expects the caller to use the specific provider.
1130  *
1131  * pci_p2pdma_enable_show() should be used as the show operation for
1132  * the attribute.
1133  *
1134  * Returns 0 on success
1135  */
1136 int pci_p2pdma_enable_store(const char *page, struct pci_dev **p2p_dev,
1137 			    bool *use_p2pdma)
1138 {
1139 	struct device *dev;
1140 
1141 	dev = bus_find_device_by_name(&pci_bus_type, NULL, page);
1142 	if (dev) {
1143 		*use_p2pdma = true;
1144 		*p2p_dev = to_pci_dev(dev);
1145 
1146 		if (!pci_has_p2pmem(*p2p_dev)) {
1147 			pci_err(*p2p_dev,
1148 				"PCI device has no peer-to-peer memory: %s\n",
1149 				page);
1150 			pci_dev_put(*p2p_dev);
1151 			return -ENODEV;
1152 		}
1153 
1154 		return 0;
1155 	} else if ((page[0] == '0' || page[0] == '1') && !iscntrl(page[1])) {
1156 		/*
1157 		 * If the user enters a PCI device that  doesn't exist
1158 		 * like "0000:01:00.1", we don't want kstrtobool to think
1159 		 * it's a '0' when it's clearly not what the user wanted.
1160 		 * So we require 0's and 1's to be exactly one character.
1161 		 */
1162 	} else if (!kstrtobool(page, use_p2pdma)) {
1163 		return 0;
1164 	}
1165 
1166 	pr_err("No such PCI device: %.*s\n", (int)strcspn(page, "\n"), page);
1167 	return -ENODEV;
1168 }
1169 EXPORT_SYMBOL_GPL(pci_p2pdma_enable_store);
1170 
1171 /**
1172  * pci_p2pdma_enable_show - show a configfs/sysfs attribute indicating
1173  *		whether p2pdma is enabled
1174  * @page: contents of the stored value
1175  * @p2p_dev: the selected p2p device (NULL if no device is selected)
1176  * @use_p2pdma: whether p2pdma has been enabled
1177  *
1178  * Attributes that use pci_p2pdma_enable_store() should use this function
1179  * to show the value of the attribute.
1180  *
1181  * Returns 0 on success
1182  */
1183 ssize_t pci_p2pdma_enable_show(char *page, struct pci_dev *p2p_dev,
1184 			       bool use_p2pdma)
1185 {
1186 	if (!use_p2pdma)
1187 		return sprintf(page, "0\n");
1188 
1189 	if (!p2p_dev)
1190 		return sprintf(page, "1\n");
1191 
1192 	return sprintf(page, "%s\n", pci_name(p2p_dev));
1193 }
1194 EXPORT_SYMBOL_GPL(pci_p2pdma_enable_show);
1195