p2pdma.c 31 KB

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