xref: /openbmc/linux/drivers/pci/p2pdma.c (revision 9b93eb47)
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/pci-p2pdma.h>
14 #include <linux/module.h>
15 #include <linux/slab.h>
16 #include <linux/genalloc.h>
17 #include <linux/memremap.h>
18 #include <linux/percpu-refcount.h>
19 #include <linux/random.h>
20 #include <linux/seq_buf.h>
21 
22 struct pci_p2pdma {
23 	struct percpu_ref devmap_ref;
24 	struct completion devmap_ref_done;
25 	struct gen_pool *pool;
26 	bool p2pmem_published;
27 };
28 
29 static ssize_t size_show(struct device *dev, struct device_attribute *attr,
30 			 char *buf)
31 {
32 	struct pci_dev *pdev = to_pci_dev(dev);
33 	size_t size = 0;
34 
35 	if (pdev->p2pdma->pool)
36 		size = gen_pool_size(pdev->p2pdma->pool);
37 
38 	return snprintf(buf, PAGE_SIZE, "%zd\n", size);
39 }
40 static DEVICE_ATTR_RO(size);
41 
42 static ssize_t available_show(struct device *dev, struct device_attribute *attr,
43 			      char *buf)
44 {
45 	struct pci_dev *pdev = to_pci_dev(dev);
46 	size_t avail = 0;
47 
48 	if (pdev->p2pdma->pool)
49 		avail = gen_pool_avail(pdev->p2pdma->pool);
50 
51 	return snprintf(buf, PAGE_SIZE, "%zd\n", avail);
52 }
53 static DEVICE_ATTR_RO(available);
54 
55 static ssize_t published_show(struct device *dev, struct device_attribute *attr,
56 			      char *buf)
57 {
58 	struct pci_dev *pdev = to_pci_dev(dev);
59 
60 	return snprintf(buf, PAGE_SIZE, "%d\n",
61 			pdev->p2pdma->p2pmem_published);
62 }
63 static DEVICE_ATTR_RO(published);
64 
65 static struct attribute *p2pmem_attrs[] = {
66 	&dev_attr_size.attr,
67 	&dev_attr_available.attr,
68 	&dev_attr_published.attr,
69 	NULL,
70 };
71 
72 static const struct attribute_group p2pmem_group = {
73 	.attrs = p2pmem_attrs,
74 	.name = "p2pmem",
75 };
76 
77 static void pci_p2pdma_percpu_release(struct percpu_ref *ref)
78 {
79 	struct pci_p2pdma *p2p =
80 		container_of(ref, struct pci_p2pdma, devmap_ref);
81 
82 	complete_all(&p2p->devmap_ref_done);
83 }
84 
85 static void pci_p2pdma_percpu_kill(struct percpu_ref *ref)
86 {
87 	/*
88 	 * pci_p2pdma_add_resource() may be called multiple times
89 	 * by a driver and may register the percpu_kill devm action multiple
90 	 * times. We only want the first action to actually kill the
91 	 * percpu_ref.
92 	 */
93 	if (percpu_ref_is_dying(ref))
94 		return;
95 
96 	percpu_ref_kill(ref);
97 }
98 
99 static void pci_p2pdma_release(void *data)
100 {
101 	struct pci_dev *pdev = data;
102 
103 	if (!pdev->p2pdma)
104 		return;
105 
106 	wait_for_completion(&pdev->p2pdma->devmap_ref_done);
107 	percpu_ref_exit(&pdev->p2pdma->devmap_ref);
108 
109 	gen_pool_destroy(pdev->p2pdma->pool);
110 	sysfs_remove_group(&pdev->dev.kobj, &p2pmem_group);
111 	pdev->p2pdma = NULL;
112 }
113 
114 static int pci_p2pdma_setup(struct pci_dev *pdev)
115 {
116 	int error = -ENOMEM;
117 	struct pci_p2pdma *p2p;
118 
119 	p2p = devm_kzalloc(&pdev->dev, sizeof(*p2p), GFP_KERNEL);
120 	if (!p2p)
121 		return -ENOMEM;
122 
123 	p2p->pool = gen_pool_create(PAGE_SHIFT, dev_to_node(&pdev->dev));
124 	if (!p2p->pool)
125 		goto out;
126 
127 	init_completion(&p2p->devmap_ref_done);
128 	error = percpu_ref_init(&p2p->devmap_ref,
129 			pci_p2pdma_percpu_release, 0, GFP_KERNEL);
130 	if (error)
131 		goto out_pool_destroy;
132 
133 	error = devm_add_action_or_reset(&pdev->dev, pci_p2pdma_release, pdev);
134 	if (error)
135 		goto out_pool_destroy;
136 
137 	pdev->p2pdma = p2p;
138 
139 	error = sysfs_create_group(&pdev->dev.kobj, &p2pmem_group);
140 	if (error)
141 		goto out_pool_destroy;
142 
143 	return 0;
144 
145 out_pool_destroy:
146 	pdev->p2pdma = NULL;
147 	gen_pool_destroy(p2p->pool);
148 out:
149 	devm_kfree(&pdev->dev, p2p);
150 	return error;
151 }
152 
153 /**
154  * pci_p2pdma_add_resource - add memory for use as p2p memory
155  * @pdev: the device to add the memory to
156  * @bar: PCI BAR to add
157  * @size: size of the memory to add, may be zero to use the whole BAR
158  * @offset: offset into the PCI BAR
159  *
160  * The memory will be given ZONE_DEVICE struct pages so that it may
161  * be used with any DMA request.
162  */
163 int pci_p2pdma_add_resource(struct pci_dev *pdev, int bar, size_t size,
164 			    u64 offset)
165 {
166 	struct dev_pagemap *pgmap;
167 	void *addr;
168 	int error;
169 
170 	if (!(pci_resource_flags(pdev, bar) & IORESOURCE_MEM))
171 		return -EINVAL;
172 
173 	if (offset >= pci_resource_len(pdev, bar))
174 		return -EINVAL;
175 
176 	if (!size)
177 		size = pci_resource_len(pdev, bar) - offset;
178 
179 	if (size + offset > pci_resource_len(pdev, bar))
180 		return -EINVAL;
181 
182 	if (!pdev->p2pdma) {
183 		error = pci_p2pdma_setup(pdev);
184 		if (error)
185 			return error;
186 	}
187 
188 	pgmap = devm_kzalloc(&pdev->dev, sizeof(*pgmap), GFP_KERNEL);
189 	if (!pgmap)
190 		return -ENOMEM;
191 
192 	pgmap->res.start = pci_resource_start(pdev, bar) + offset;
193 	pgmap->res.end = pgmap->res.start + size - 1;
194 	pgmap->res.flags = pci_resource_flags(pdev, bar);
195 	pgmap->ref = &pdev->p2pdma->devmap_ref;
196 	pgmap->type = MEMORY_DEVICE_PCI_P2PDMA;
197 	pgmap->pci_p2pdma_bus_offset = pci_bus_address(pdev, bar) -
198 		pci_resource_start(pdev, bar);
199 	pgmap->kill = pci_p2pdma_percpu_kill;
200 
201 	addr = devm_memremap_pages(&pdev->dev, pgmap);
202 	if (IS_ERR(addr)) {
203 		error = PTR_ERR(addr);
204 		goto pgmap_free;
205 	}
206 
207 	error = gen_pool_add_virt(pdev->p2pdma->pool, (unsigned long)addr,
208 			pci_bus_address(pdev, bar) + offset,
209 			resource_size(&pgmap->res), dev_to_node(&pdev->dev));
210 	if (error)
211 		goto pgmap_free;
212 
213 	pci_info(pdev, "added peer-to-peer DMA memory %pR\n",
214 		 &pgmap->res);
215 
216 	return 0;
217 
218 pgmap_free:
219 	devm_kfree(&pdev->dev, pgmap);
220 	return error;
221 }
222 EXPORT_SYMBOL_GPL(pci_p2pdma_add_resource);
223 
224 /*
225  * Note this function returns the parent PCI device with a
226  * reference taken. It is the caller's responsibily to drop
227  * the reference.
228  */
229 static struct pci_dev *find_parent_pci_dev(struct device *dev)
230 {
231 	struct device *parent;
232 
233 	dev = get_device(dev);
234 
235 	while (dev) {
236 		if (dev_is_pci(dev))
237 			return to_pci_dev(dev);
238 
239 		parent = get_device(dev->parent);
240 		put_device(dev);
241 		dev = parent;
242 	}
243 
244 	return NULL;
245 }
246 
247 /*
248  * Check if a PCI bridge has its ACS redirection bits set to redirect P2P
249  * TLPs upstream via ACS. Returns 1 if the packets will be redirected
250  * upstream, 0 otherwise.
251  */
252 static int pci_bridge_has_acs_redir(struct pci_dev *pdev)
253 {
254 	int pos;
255 	u16 ctrl;
256 
257 	pos = pci_find_ext_capability(pdev, PCI_EXT_CAP_ID_ACS);
258 	if (!pos)
259 		return 0;
260 
261 	pci_read_config_word(pdev, pos + PCI_ACS_CTRL, &ctrl);
262 
263 	if (ctrl & (PCI_ACS_RR | PCI_ACS_CR | PCI_ACS_EC))
264 		return 1;
265 
266 	return 0;
267 }
268 
269 static void seq_buf_print_bus_devfn(struct seq_buf *buf, struct pci_dev *pdev)
270 {
271 	if (!buf)
272 		return;
273 
274 	seq_buf_printf(buf, "%s;", pci_name(pdev));
275 }
276 
277 /*
278  * If we can't find a common upstream bridge take a look at the root
279  * complex and compare it to a whitelist of known good hardware.
280  */
281 static bool root_complex_whitelist(struct pci_dev *dev)
282 {
283 	struct pci_host_bridge *host = pci_find_host_bridge(dev->bus);
284 	struct pci_dev *root = pci_get_slot(host->bus, PCI_DEVFN(0, 0));
285 	unsigned short vendor, device;
286 
287 	if (!root)
288 		return false;
289 
290 	vendor = root->vendor;
291 	device = root->device;
292 	pci_dev_put(root);
293 
294 	/* AMD ZEN host bridges can do peer to peer */
295 	if (vendor == PCI_VENDOR_ID_AMD && device == 0x1450)
296 		return true;
297 
298 	return false;
299 }
300 
301 /*
302  * Find the distance through the nearest common upstream bridge between
303  * two PCI devices.
304  *
305  * If the two devices are the same device then 0 will be returned.
306  *
307  * If there are two virtual functions of the same device behind the same
308  * bridge port then 2 will be returned (one step down to the PCIe switch,
309  * then one step back to the same device).
310  *
311  * In the case where two devices are connected to the same PCIe switch, the
312  * value 4 will be returned. This corresponds to the following PCI tree:
313  *
314  *     -+  Root Port
315  *      \+ Switch Upstream Port
316  *       +-+ Switch Downstream Port
317  *       + \- Device A
318  *       \-+ Switch Downstream Port
319  *         \- Device B
320  *
321  * The distance is 4 because we traverse from Device A through the downstream
322  * port of the switch, to the common upstream port, back up to the second
323  * downstream port and then to Device B.
324  *
325  * Any two devices that don't have a common upstream bridge will return -1.
326  * In this way devices on separate PCIe root ports will be rejected, which
327  * is what we want for peer-to-peer seeing each PCIe root port defines a
328  * separate hierarchy domain and there's no way to determine whether the root
329  * complex supports forwarding between them.
330  *
331  * In the case where two devices are connected to different PCIe switches,
332  * this function will still return a positive distance as long as both
333  * switches eventually have a common upstream bridge. Note this covers
334  * the case of using multiple PCIe switches to achieve a desired level of
335  * fan-out from a root port. The exact distance will be a function of the
336  * number of switches between Device A and Device B.
337  *
338  * If a bridge which has any ACS redirection bits set is in the path
339  * then this functions will return -2. This is so we reject any
340  * cases where the TLPs are forwarded up into the root complex.
341  * In this case, a list of all infringing bridge addresses will be
342  * populated in acs_list (assuming it's non-null) for printk purposes.
343  */
344 static int upstream_bridge_distance(struct pci_dev *provider,
345 				    struct pci_dev *client,
346 				    struct seq_buf *acs_list)
347 {
348 	struct pci_dev *a = provider, *b = client, *bb;
349 	int dist_a = 0;
350 	int dist_b = 0;
351 	int acs_cnt = 0;
352 
353 	/*
354 	 * Note, we don't need to take references to devices returned by
355 	 * pci_upstream_bridge() seeing we hold a reference to a child
356 	 * device which will already hold a reference to the upstream bridge.
357 	 */
358 
359 	while (a) {
360 		dist_b = 0;
361 
362 		if (pci_bridge_has_acs_redir(a)) {
363 			seq_buf_print_bus_devfn(acs_list, a);
364 			acs_cnt++;
365 		}
366 
367 		bb = b;
368 
369 		while (bb) {
370 			if (a == bb)
371 				goto check_b_path_acs;
372 
373 			bb = pci_upstream_bridge(bb);
374 			dist_b++;
375 		}
376 
377 		a = pci_upstream_bridge(a);
378 		dist_a++;
379 	}
380 
381 	/*
382 	 * Allow the connection if both devices are on a whitelisted root
383 	 * complex, but add an arbitary large value to the distance.
384 	 */
385 	if (root_complex_whitelist(provider) &&
386 	    root_complex_whitelist(client))
387 		return 0x1000 + dist_a + dist_b;
388 
389 	return -1;
390 
391 check_b_path_acs:
392 	bb = b;
393 
394 	while (bb) {
395 		if (a == bb)
396 			break;
397 
398 		if (pci_bridge_has_acs_redir(bb)) {
399 			seq_buf_print_bus_devfn(acs_list, bb);
400 			acs_cnt++;
401 		}
402 
403 		bb = pci_upstream_bridge(bb);
404 	}
405 
406 	if (acs_cnt)
407 		return -2;
408 
409 	return dist_a + dist_b;
410 }
411 
412 static int upstream_bridge_distance_warn(struct pci_dev *provider,
413 					 struct pci_dev *client)
414 {
415 	struct seq_buf acs_list;
416 	int ret;
417 
418 	seq_buf_init(&acs_list, kmalloc(PAGE_SIZE, GFP_KERNEL), PAGE_SIZE);
419 	if (!acs_list.buffer)
420 		return -ENOMEM;
421 
422 	ret = upstream_bridge_distance(provider, client, &acs_list);
423 	if (ret == -2) {
424 		pci_warn(client, "cannot be used for peer-to-peer DMA as ACS redirect is set between the client and provider (%s)\n",
425 			 pci_name(provider));
426 		/* Drop final semicolon */
427 		acs_list.buffer[acs_list.len-1] = 0;
428 		pci_warn(client, "to disable ACS redirect for this path, add the kernel parameter: pci=disable_acs_redir=%s\n",
429 			 acs_list.buffer);
430 
431 	} else if (ret < 0) {
432 		pci_warn(client, "cannot be used for peer-to-peer DMA as the client and provider (%s) do not share an upstream bridge\n",
433 			 pci_name(provider));
434 	}
435 
436 	kfree(acs_list.buffer);
437 
438 	return ret;
439 }
440 
441 /**
442  * pci_p2pdma_distance_many - Determive the cumulative distance between
443  *	a p2pdma provider and the clients in use.
444  * @provider: p2pdma provider to check against the client list
445  * @clients: array of devices to check (NULL-terminated)
446  * @num_clients: number of clients in the array
447  * @verbose: if true, print warnings for devices when we return -1
448  *
449  * Returns -1 if any of the clients are not compatible (behind the same
450  * root port as the provider), otherwise returns a positive number where
451  * a lower number is the preferable choice. (If there's one client
452  * that's the same as the provider it will return 0, which is best choice).
453  *
454  * For now, "compatible" means the provider and the clients are all behind
455  * the same PCI root port. This cuts out cases that may work but is safest
456  * for the user. Future work can expand this to white-list root complexes that
457  * can safely forward between each ports.
458  */
459 int pci_p2pdma_distance_many(struct pci_dev *provider, struct device **clients,
460 			     int num_clients, bool verbose)
461 {
462 	bool not_supported = false;
463 	struct pci_dev *pci_client;
464 	int distance = 0;
465 	int i, ret;
466 
467 	if (num_clients == 0)
468 		return -1;
469 
470 	for (i = 0; i < num_clients; i++) {
471 		pci_client = find_parent_pci_dev(clients[i]);
472 		if (!pci_client) {
473 			if (verbose)
474 				dev_warn(clients[i],
475 					 "cannot be used for peer-to-peer DMA as it is not a PCI device\n");
476 			return -1;
477 		}
478 
479 		if (verbose)
480 			ret = upstream_bridge_distance_warn(provider,
481 							    pci_client);
482 		else
483 			ret = upstream_bridge_distance(provider, pci_client,
484 						       NULL);
485 
486 		pci_dev_put(pci_client);
487 
488 		if (ret < 0)
489 			not_supported = true;
490 
491 		if (not_supported && !verbose)
492 			break;
493 
494 		distance += ret;
495 	}
496 
497 	if (not_supported)
498 		return -1;
499 
500 	return distance;
501 }
502 EXPORT_SYMBOL_GPL(pci_p2pdma_distance_many);
503 
504 /**
505  * pci_has_p2pmem - check if a given PCI device has published any p2pmem
506  * @pdev: PCI device to check
507  */
508 bool pci_has_p2pmem(struct pci_dev *pdev)
509 {
510 	return pdev->p2pdma && pdev->p2pdma->p2pmem_published;
511 }
512 EXPORT_SYMBOL_GPL(pci_has_p2pmem);
513 
514 /**
515  * pci_p2pmem_find - find a peer-to-peer DMA memory device compatible with
516  *	the specified list of clients and shortest distance (as determined
517  *	by pci_p2pmem_dma())
518  * @clients: array of devices to check (NULL-terminated)
519  * @num_clients: number of client devices in the list
520  *
521  * If multiple devices are behind the same switch, the one "closest" to the
522  * client devices in use will be chosen first. (So if one of the providers is
523  * the same as one of the clients, that provider will be used ahead of any
524  * other providers that are unrelated). If multiple providers are an equal
525  * distance away, one will be chosen at random.
526  *
527  * Returns a pointer to the PCI device with a reference taken (use pci_dev_put
528  * to return the reference) or NULL if no compatible device is found. The
529  * found provider will also be assigned to the client list.
530  */
531 struct pci_dev *pci_p2pmem_find_many(struct device **clients, int num_clients)
532 {
533 	struct pci_dev *pdev = NULL;
534 	int distance;
535 	int closest_distance = INT_MAX;
536 	struct pci_dev **closest_pdevs;
537 	int dev_cnt = 0;
538 	const int max_devs = PAGE_SIZE / sizeof(*closest_pdevs);
539 	int i;
540 
541 	closest_pdevs = kmalloc(PAGE_SIZE, GFP_KERNEL);
542 	if (!closest_pdevs)
543 		return NULL;
544 
545 	while ((pdev = pci_get_device(PCI_ANY_ID, PCI_ANY_ID, pdev))) {
546 		if (!pci_has_p2pmem(pdev))
547 			continue;
548 
549 		distance = pci_p2pdma_distance_many(pdev, clients,
550 						    num_clients, false);
551 		if (distance < 0 || distance > closest_distance)
552 			continue;
553 
554 		if (distance == closest_distance && dev_cnt >= max_devs)
555 			continue;
556 
557 		if (distance < closest_distance) {
558 			for (i = 0; i < dev_cnt; i++)
559 				pci_dev_put(closest_pdevs[i]);
560 
561 			dev_cnt = 0;
562 			closest_distance = distance;
563 		}
564 
565 		closest_pdevs[dev_cnt++] = pci_dev_get(pdev);
566 	}
567 
568 	if (dev_cnt)
569 		pdev = pci_dev_get(closest_pdevs[prandom_u32_max(dev_cnt)]);
570 
571 	for (i = 0; i < dev_cnt; i++)
572 		pci_dev_put(closest_pdevs[i]);
573 
574 	kfree(closest_pdevs);
575 	return pdev;
576 }
577 EXPORT_SYMBOL_GPL(pci_p2pmem_find_many);
578 
579 /**
580  * pci_alloc_p2p_mem - allocate peer-to-peer DMA memory
581  * @pdev: the device to allocate memory from
582  * @size: number of bytes to allocate
583  *
584  * Returns the allocated memory or NULL on error.
585  */
586 void *pci_alloc_p2pmem(struct pci_dev *pdev, size_t size)
587 {
588 	void *ret;
589 
590 	if (unlikely(!pdev->p2pdma))
591 		return NULL;
592 
593 	if (unlikely(!percpu_ref_tryget_live(&pdev->p2pdma->devmap_ref)))
594 		return NULL;
595 
596 	ret = (void *)gen_pool_alloc(pdev->p2pdma->pool, size);
597 
598 	if (unlikely(!ret))
599 		percpu_ref_put(&pdev->p2pdma->devmap_ref);
600 
601 	return ret;
602 }
603 EXPORT_SYMBOL_GPL(pci_alloc_p2pmem);
604 
605 /**
606  * pci_free_p2pmem - free peer-to-peer DMA memory
607  * @pdev: the device the memory was allocated from
608  * @addr: address of the memory that was allocated
609  * @size: number of bytes that were allocated
610  */
611 void pci_free_p2pmem(struct pci_dev *pdev, void *addr, size_t size)
612 {
613 	gen_pool_free(pdev->p2pdma->pool, (uintptr_t)addr, size);
614 	percpu_ref_put(&pdev->p2pdma->devmap_ref);
615 }
616 EXPORT_SYMBOL_GPL(pci_free_p2pmem);
617 
618 /**
619  * pci_virt_to_bus - return the PCI bus address for a given virtual
620  *	address obtained with pci_alloc_p2pmem()
621  * @pdev: the device the memory was allocated from
622  * @addr: address of the memory that was allocated
623  */
624 pci_bus_addr_t pci_p2pmem_virt_to_bus(struct pci_dev *pdev, void *addr)
625 {
626 	if (!addr)
627 		return 0;
628 	if (!pdev->p2pdma)
629 		return 0;
630 
631 	/*
632 	 * Note: when we added the memory to the pool we used the PCI
633 	 * bus address as the physical address. So gen_pool_virt_to_phys()
634 	 * actually returns the bus address despite the misleading name.
635 	 */
636 	return gen_pool_virt_to_phys(pdev->p2pdma->pool, (unsigned long)addr);
637 }
638 EXPORT_SYMBOL_GPL(pci_p2pmem_virt_to_bus);
639 
640 /**
641  * pci_p2pmem_alloc_sgl - allocate peer-to-peer DMA memory in a scatterlist
642  * @pdev: the device to allocate memory from
643  * @nents: the number of SG entries in the list
644  * @length: number of bytes to allocate
645  *
646  * Return: %NULL on error or &struct scatterlist pointer and @nents on success
647  */
648 struct scatterlist *pci_p2pmem_alloc_sgl(struct pci_dev *pdev,
649 					 unsigned int *nents, u32 length)
650 {
651 	struct scatterlist *sg;
652 	void *addr;
653 
654 	sg = kzalloc(sizeof(*sg), GFP_KERNEL);
655 	if (!sg)
656 		return NULL;
657 
658 	sg_init_table(sg, 1);
659 
660 	addr = pci_alloc_p2pmem(pdev, length);
661 	if (!addr)
662 		goto out_free_sg;
663 
664 	sg_set_buf(sg, addr, length);
665 	*nents = 1;
666 	return sg;
667 
668 out_free_sg:
669 	kfree(sg);
670 	return NULL;
671 }
672 EXPORT_SYMBOL_GPL(pci_p2pmem_alloc_sgl);
673 
674 /**
675  * pci_p2pmem_free_sgl - free a scatterlist allocated by pci_p2pmem_alloc_sgl()
676  * @pdev: the device to allocate memory from
677  * @sgl: the allocated scatterlist
678  */
679 void pci_p2pmem_free_sgl(struct pci_dev *pdev, struct scatterlist *sgl)
680 {
681 	struct scatterlist *sg;
682 	int count;
683 
684 	for_each_sg(sgl, sg, INT_MAX, count) {
685 		if (!sg)
686 			break;
687 
688 		pci_free_p2pmem(pdev, sg_virt(sg), sg->length);
689 	}
690 	kfree(sgl);
691 }
692 EXPORT_SYMBOL_GPL(pci_p2pmem_free_sgl);
693 
694 /**
695  * pci_p2pmem_publish - publish the peer-to-peer DMA memory for use by
696  *	other devices with pci_p2pmem_find()
697  * @pdev: the device with peer-to-peer DMA memory to publish
698  * @publish: set to true to publish the memory, false to unpublish it
699  *
700  * Published memory can be used by other PCI device drivers for
701  * peer-2-peer DMA operations. Non-published memory is reserved for
702  * exclusive use of the device driver that registers the peer-to-peer
703  * memory.
704  */
705 void pci_p2pmem_publish(struct pci_dev *pdev, bool publish)
706 {
707 	if (pdev->p2pdma)
708 		pdev->p2pdma->p2pmem_published = publish;
709 }
710 EXPORT_SYMBOL_GPL(pci_p2pmem_publish);
711 
712 /**
713  * pci_p2pdma_map_sg - map a PCI peer-to-peer scatterlist for DMA
714  * @dev: device doing the DMA request
715  * @sg: scatter list to map
716  * @nents: elements in the scatterlist
717  * @dir: DMA direction
718  *
719  * Scatterlists mapped with this function should not be unmapped in any way.
720  *
721  * Returns the number of SG entries mapped or 0 on error.
722  */
723 int pci_p2pdma_map_sg(struct device *dev, struct scatterlist *sg, int nents,
724 		      enum dma_data_direction dir)
725 {
726 	struct dev_pagemap *pgmap;
727 	struct scatterlist *s;
728 	phys_addr_t paddr;
729 	int i;
730 
731 	/*
732 	 * p2pdma mappings are not compatible with devices that use
733 	 * dma_virt_ops. If the upper layers do the right thing
734 	 * this should never happen because it will be prevented
735 	 * by the check in pci_p2pdma_add_client()
736 	 */
737 	if (WARN_ON_ONCE(IS_ENABLED(CONFIG_DMA_VIRT_OPS) &&
738 			 dev->dma_ops == &dma_virt_ops))
739 		return 0;
740 
741 	for_each_sg(sg, s, nents, i) {
742 		pgmap = sg_page(s)->pgmap;
743 		paddr = sg_phys(s);
744 
745 		s->dma_address = paddr - pgmap->pci_p2pdma_bus_offset;
746 		sg_dma_len(s) = s->length;
747 	}
748 
749 	return nents;
750 }
751 EXPORT_SYMBOL_GPL(pci_p2pdma_map_sg);
752 
753 /**
754  * pci_p2pdma_enable_store - parse a configfs/sysfs attribute store
755  *		to enable p2pdma
756  * @page: contents of the value to be stored
757  * @p2p_dev: returns the PCI device that was selected to be used
758  *		(if one was specified in the stored value)
759  * @use_p2pdma: returns whether to enable p2pdma or not
760  *
761  * Parses an attribute value to decide whether to enable p2pdma.
762  * The value can select a PCI device (using its full BDF device
763  * name) or a boolean (in any format strtobool() accepts). A false
764  * value disables p2pdma, a true value expects the caller
765  * to automatically find a compatible device and specifying a PCI device
766  * expects the caller to use the specific provider.
767  *
768  * pci_p2pdma_enable_show() should be used as the show operation for
769  * the attribute.
770  *
771  * Returns 0 on success
772  */
773 int pci_p2pdma_enable_store(const char *page, struct pci_dev **p2p_dev,
774 			    bool *use_p2pdma)
775 {
776 	struct device *dev;
777 
778 	dev = bus_find_device_by_name(&pci_bus_type, NULL, page);
779 	if (dev) {
780 		*use_p2pdma = true;
781 		*p2p_dev = to_pci_dev(dev);
782 
783 		if (!pci_has_p2pmem(*p2p_dev)) {
784 			pci_err(*p2p_dev,
785 				"PCI device has no peer-to-peer memory: %s\n",
786 				page);
787 			pci_dev_put(*p2p_dev);
788 			return -ENODEV;
789 		}
790 
791 		return 0;
792 	} else if ((page[0] == '0' || page[0] == '1') && !iscntrl(page[1])) {
793 		/*
794 		 * If the user enters a PCI device that  doesn't exist
795 		 * like "0000:01:00.1", we don't want strtobool to think
796 		 * it's a '0' when it's clearly not what the user wanted.
797 		 * So we require 0's and 1's to be exactly one character.
798 		 */
799 	} else if (!strtobool(page, use_p2pdma)) {
800 		return 0;
801 	}
802 
803 	pr_err("No such PCI device: %.*s\n", (int)strcspn(page, "\n"), page);
804 	return -ENODEV;
805 }
806 EXPORT_SYMBOL_GPL(pci_p2pdma_enable_store);
807 
808 /**
809  * pci_p2pdma_enable_show - show a configfs/sysfs attribute indicating
810  *		whether p2pdma is enabled
811  * @page: contents of the stored value
812  * @p2p_dev: the selected p2p device (NULL if no device is selected)
813  * @use_p2pdma: whether p2pdma has been enabled
814  *
815  * Attributes that use pci_p2pdma_enable_store() should use this function
816  * to show the value of the attribute.
817  *
818  * Returns 0 on success
819  */
820 ssize_t pci_p2pdma_enable_show(char *page, struct pci_dev *p2p_dev,
821 			       bool use_p2pdma)
822 {
823 	if (!use_p2pdma)
824 		return sprintf(page, "0\n");
825 
826 	if (!p2p_dev)
827 		return sprintf(page, "1\n");
828 
829 	return sprintf(page, "%s\n", pci_name(p2p_dev));
830 }
831 EXPORT_SYMBOL_GPL(pci_p2pdma_enable_show);
832