netfilter: netns: shrink netns_ct struct
[linux-2.6-microblaze.git] / arch / powerpc / platforms / powernv / npu-dma.c
1 /*
2  * This file implements the DMA operations for NVLink devices. The NPU
3  * devices all point to the same iommu table as the parent PCI device.
4  *
5  * Copyright Alistair Popple, IBM Corporation 2015.
6  *
7  * This program is free software; you can redistribute it and/or
8  * modify it under the terms of version 2 of the GNU General Public
9  * License as published by the Free Software Foundation.
10  */
11
12 #include <linux/slab.h>
13 #include <linux/mmu_notifier.h>
14 #include <linux/mmu_context.h>
15 #include <linux/of.h>
16 #include <linux/export.h>
17 #include <linux/pci.h>
18 #include <linux/memblock.h>
19 #include <linux/iommu.h>
20 #include <linux/sizes.h>
21
22 #include <asm/debugfs.h>
23 #include <asm/tlb.h>
24 #include <asm/powernv.h>
25 #include <asm/reg.h>
26 #include <asm/opal.h>
27 #include <asm/io.h>
28 #include <asm/iommu.h>
29 #include <asm/pnv-pci.h>
30 #include <asm/msi_bitmap.h>
31 #include <asm/opal.h>
32
33 #include "powernv.h"
34 #include "pci.h"
35
36 #define npu_to_phb(x) container_of(x, struct pnv_phb, npu)
37
38 /*
39  * spinlock to protect initialisation of an npu_context for a particular
40  * mm_struct.
41  */
42 static DEFINE_SPINLOCK(npu_context_lock);
43
44 /*
45  * Other types of TCE cache invalidation are not functional in the
46  * hardware.
47  */
48 static struct pci_dev *get_pci_dev(struct device_node *dn)
49 {
50         struct pci_dn *pdn = PCI_DN(dn);
51
52         return pci_get_domain_bus_and_slot(pci_domain_nr(pdn->phb->bus),
53                                            pdn->busno, pdn->devfn);
54 }
55
56 /* Given a NPU device get the associated PCI device. */
57 struct pci_dev *pnv_pci_get_gpu_dev(struct pci_dev *npdev)
58 {
59         struct device_node *dn;
60         struct pci_dev *gpdev;
61
62         if (WARN_ON(!npdev))
63                 return NULL;
64
65         if (WARN_ON(!npdev->dev.of_node))
66                 return NULL;
67
68         /* Get assoicated PCI device */
69         dn = of_parse_phandle(npdev->dev.of_node, "ibm,gpu", 0);
70         if (!dn)
71                 return NULL;
72
73         gpdev = get_pci_dev(dn);
74         of_node_put(dn);
75
76         return gpdev;
77 }
78 EXPORT_SYMBOL(pnv_pci_get_gpu_dev);
79
80 /* Given the real PCI device get a linked NPU device. */
81 struct pci_dev *pnv_pci_get_npu_dev(struct pci_dev *gpdev, int index)
82 {
83         struct device_node *dn;
84         struct pci_dev *npdev;
85
86         if (WARN_ON(!gpdev))
87                 return NULL;
88
89         /* Not all PCI devices have device-tree nodes */
90         if (!gpdev->dev.of_node)
91                 return NULL;
92
93         /* Get assoicated PCI device */
94         dn = of_parse_phandle(gpdev->dev.of_node, "ibm,npu", index);
95         if (!dn)
96                 return NULL;
97
98         npdev = get_pci_dev(dn);
99         of_node_put(dn);
100
101         return npdev;
102 }
103 EXPORT_SYMBOL(pnv_pci_get_npu_dev);
104
105 #define NPU_DMA_OP_UNSUPPORTED()                                        \
106         dev_err_once(dev, "%s operation unsupported for NVLink devices\n", \
107                 __func__)
108
109 static void *dma_npu_alloc(struct device *dev, size_t size,
110                            dma_addr_t *dma_handle, gfp_t flag,
111                            unsigned long attrs)
112 {
113         NPU_DMA_OP_UNSUPPORTED();
114         return NULL;
115 }
116
117 static void dma_npu_free(struct device *dev, size_t size,
118                          void *vaddr, dma_addr_t dma_handle,
119                          unsigned long attrs)
120 {
121         NPU_DMA_OP_UNSUPPORTED();
122 }
123
124 static dma_addr_t dma_npu_map_page(struct device *dev, struct page *page,
125                                    unsigned long offset, size_t size,
126                                    enum dma_data_direction direction,
127                                    unsigned long attrs)
128 {
129         NPU_DMA_OP_UNSUPPORTED();
130         return 0;
131 }
132
133 static int dma_npu_map_sg(struct device *dev, struct scatterlist *sglist,
134                           int nelems, enum dma_data_direction direction,
135                           unsigned long attrs)
136 {
137         NPU_DMA_OP_UNSUPPORTED();
138         return 0;
139 }
140
141 static int dma_npu_dma_supported(struct device *dev, u64 mask)
142 {
143         NPU_DMA_OP_UNSUPPORTED();
144         return 0;
145 }
146
147 static u64 dma_npu_get_required_mask(struct device *dev)
148 {
149         NPU_DMA_OP_UNSUPPORTED();
150         return 0;
151 }
152
153 static const struct dma_map_ops dma_npu_ops = {
154         .map_page               = dma_npu_map_page,
155         .map_sg                 = dma_npu_map_sg,
156         .alloc                  = dma_npu_alloc,
157         .free                   = dma_npu_free,
158         .dma_supported          = dma_npu_dma_supported,
159         .get_required_mask      = dma_npu_get_required_mask,
160 };
161
162 /*
163  * Returns the PE assoicated with the PCI device of the given
164  * NPU. Returns the linked pci device if pci_dev != NULL.
165  */
166 static struct pnv_ioda_pe *get_gpu_pci_dev_and_pe(struct pnv_ioda_pe *npe,
167                                                   struct pci_dev **gpdev)
168 {
169         struct pnv_phb *phb;
170         struct pci_controller *hose;
171         struct pci_dev *pdev;
172         struct pnv_ioda_pe *pe;
173         struct pci_dn *pdn;
174
175         pdev = pnv_pci_get_gpu_dev(npe->pdev);
176         if (!pdev)
177                 return NULL;
178
179         pdn = pci_get_pdn(pdev);
180         if (WARN_ON(!pdn || pdn->pe_number == IODA_INVALID_PE))
181                 return NULL;
182
183         hose = pci_bus_to_host(pdev->bus);
184         phb = hose->private_data;
185         pe = &phb->ioda.pe_array[pdn->pe_number];
186
187         if (gpdev)
188                 *gpdev = pdev;
189
190         return pe;
191 }
192
193 long pnv_npu_set_window(struct pnv_ioda_pe *npe, int num,
194                 struct iommu_table *tbl)
195 {
196         struct pnv_phb *phb = npe->phb;
197         int64_t rc;
198         const unsigned long size = tbl->it_indirect_levels ?
199                 tbl->it_level_size : tbl->it_size;
200         const __u64 start_addr = tbl->it_offset << tbl->it_page_shift;
201         const __u64 win_size = tbl->it_size << tbl->it_page_shift;
202
203         pe_info(npe, "Setting up window %llx..%llx pg=%lx\n",
204                         start_addr, start_addr + win_size - 1,
205                         IOMMU_PAGE_SIZE(tbl));
206
207         rc = opal_pci_map_pe_dma_window(phb->opal_id,
208                         npe->pe_number,
209                         npe->pe_number,
210                         tbl->it_indirect_levels + 1,
211                         __pa(tbl->it_base),
212                         size << 3,
213                         IOMMU_PAGE_SIZE(tbl));
214         if (rc) {
215                 pe_err(npe, "Failed to configure TCE table, err %lld\n", rc);
216                 return rc;
217         }
218         pnv_pci_ioda2_tce_invalidate_entire(phb, false);
219
220         /* Add the table to the list so its TCE cache will get invalidated */
221         pnv_pci_link_table_and_group(phb->hose->node, num,
222                         tbl, &npe->table_group);
223
224         return 0;
225 }
226
227 long pnv_npu_unset_window(struct pnv_ioda_pe *npe, int num)
228 {
229         struct pnv_phb *phb = npe->phb;
230         int64_t rc;
231
232         pe_info(npe, "Removing DMA window\n");
233
234         rc = opal_pci_map_pe_dma_window(phb->opal_id, npe->pe_number,
235                         npe->pe_number,
236                         0/* levels */, 0/* table address */,
237                         0/* table size */, 0/* page size */);
238         if (rc) {
239                 pe_err(npe, "Unmapping failed, ret = %lld\n", rc);
240                 return rc;
241         }
242         pnv_pci_ioda2_tce_invalidate_entire(phb, false);
243
244         pnv_pci_unlink_table_and_group(npe->table_group.tables[num],
245                         &npe->table_group);
246
247         return 0;
248 }
249
250 /*
251  * Enables 32 bit DMA on NPU.
252  */
253 static void pnv_npu_dma_set_32(struct pnv_ioda_pe *npe)
254 {
255         struct pci_dev *gpdev;
256         struct pnv_ioda_pe *gpe;
257         int64_t rc;
258
259         /*
260          * Find the assoicated PCI devices and get the dma window
261          * information from there.
262          */
263         if (!npe->pdev || !(npe->flags & PNV_IODA_PE_DEV))
264                 return;
265
266         gpe = get_gpu_pci_dev_and_pe(npe, &gpdev);
267         if (!gpe)
268                 return;
269
270         rc = pnv_npu_set_window(npe, 0, gpe->table_group.tables[0]);
271
272         /*
273          * We don't initialise npu_pe->tce32_table as we always use
274          * dma_npu_ops which are nops.
275          */
276         set_dma_ops(&npe->pdev->dev, &dma_npu_ops);
277 }
278
279 /*
280  * Enables bypass mode on the NPU. The NPU only supports one
281  * window per link, so bypass needs to be explicitly enabled or
282  * disabled. Unlike for a PHB3 bypass and non-bypass modes can't be
283  * active at the same time.
284  */
285 static int pnv_npu_dma_set_bypass(struct pnv_ioda_pe *npe)
286 {
287         struct pnv_phb *phb = npe->phb;
288         int64_t rc = 0;
289         phys_addr_t top = memblock_end_of_DRAM();
290
291         if (phb->type != PNV_PHB_NPU_NVLINK || !npe->pdev)
292                 return -EINVAL;
293
294         rc = pnv_npu_unset_window(npe, 0);
295         if (rc != OPAL_SUCCESS)
296                 return rc;
297
298         /* Enable the bypass window */
299
300         top = roundup_pow_of_two(top);
301         dev_info(&npe->pdev->dev, "Enabling bypass for PE %x\n",
302                         npe->pe_number);
303         rc = opal_pci_map_pe_dma_window_real(phb->opal_id,
304                         npe->pe_number, npe->pe_number,
305                         0 /* bypass base */, top);
306
307         if (rc == OPAL_SUCCESS)
308                 pnv_pci_ioda2_tce_invalidate_entire(phb, false);
309
310         return rc;
311 }
312
313 void pnv_npu_try_dma_set_bypass(struct pci_dev *gpdev, bool bypass)
314 {
315         int i;
316         struct pnv_phb *phb;
317         struct pci_dn *pdn;
318         struct pnv_ioda_pe *npe;
319         struct pci_dev *npdev;
320
321         for (i = 0; ; ++i) {
322                 npdev = pnv_pci_get_npu_dev(gpdev, i);
323
324                 if (!npdev)
325                         break;
326
327                 pdn = pci_get_pdn(npdev);
328                 if (WARN_ON(!pdn || pdn->pe_number == IODA_INVALID_PE))
329                         return;
330
331                 phb = pci_bus_to_host(npdev->bus)->private_data;
332
333                 /* We only do bypass if it's enabled on the linked device */
334                 npe = &phb->ioda.pe_array[pdn->pe_number];
335
336                 if (bypass) {
337                         dev_info(&npdev->dev,
338                                         "Using 64-bit DMA iommu bypass\n");
339                         pnv_npu_dma_set_bypass(npe);
340                 } else {
341                         dev_info(&npdev->dev, "Using 32-bit DMA via iommu\n");
342                         pnv_npu_dma_set_32(npe);
343                 }
344         }
345 }
346
347 /* Switch ownership from platform code to external user (e.g. VFIO) */
348 void pnv_npu_take_ownership(struct pnv_ioda_pe *npe)
349 {
350         struct pnv_phb *phb = npe->phb;
351         int64_t rc;
352
353         /*
354          * Note: NPU has just a single TVE in the hardware which means that
355          * while used by the kernel, it can have either 32bit window or
356          * DMA bypass but never both. So we deconfigure 32bit window only
357          * if it was enabled at the moment of ownership change.
358          */
359         if (npe->table_group.tables[0]) {
360                 pnv_npu_unset_window(npe, 0);
361                 return;
362         }
363
364         /* Disable bypass */
365         rc = opal_pci_map_pe_dma_window_real(phb->opal_id,
366                         npe->pe_number, npe->pe_number,
367                         0 /* bypass base */, 0);
368         if (rc) {
369                 pe_err(npe, "Failed to disable bypass, err %lld\n", rc);
370                 return;
371         }
372         pnv_pci_ioda2_tce_invalidate_entire(npe->phb, false);
373 }
374
375 struct pnv_ioda_pe *pnv_pci_npu_setup_iommu(struct pnv_ioda_pe *npe)
376 {
377         struct pnv_phb *phb = npe->phb;
378         struct pci_bus *pbus = phb->hose->bus;
379         struct pci_dev *npdev, *gpdev = NULL, *gptmp;
380         struct pnv_ioda_pe *gpe = get_gpu_pci_dev_and_pe(npe, &gpdev);
381
382         if (!gpe || !gpdev)
383                 return NULL;
384
385         list_for_each_entry(npdev, &pbus->devices, bus_list) {
386                 gptmp = pnv_pci_get_gpu_dev(npdev);
387
388                 if (gptmp != gpdev)
389                         continue;
390
391                 pe_info(gpe, "Attached NPU %s\n", dev_name(&npdev->dev));
392                 iommu_group_add_device(gpe->table_group.group, &npdev->dev);
393         }
394
395         return gpe;
396 }
397
398 /* Maximum number of nvlinks per npu */
399 #define NV_MAX_LINKS 6
400
401 /* Maximum index of npu2 hosts in the system. Always < NV_MAX_NPUS */
402 static int max_npu2_index;
403
404 struct npu_context {
405         struct mm_struct *mm;
406         struct pci_dev *npdev[NV_MAX_NPUS][NV_MAX_LINKS];
407         struct mmu_notifier mn;
408         struct kref kref;
409         bool nmmu_flush;
410
411         /* Callback to stop translation requests on a given GPU */
412         void (*release_cb)(struct npu_context *context, void *priv);
413
414         /*
415          * Private pointer passed to the above callback for usage by
416          * device drivers.
417          */
418         void *priv;
419 };
420
421 struct mmio_atsd_reg {
422         struct npu *npu;
423         int reg;
424 };
425
426 /*
427  * Find a free MMIO ATSD register and mark it in use. Return -ENOSPC
428  * if none are available.
429  */
430 static int get_mmio_atsd_reg(struct npu *npu)
431 {
432         int i;
433
434         for (i = 0; i < npu->mmio_atsd_count; i++) {
435                 if (!test_bit(i, &npu->mmio_atsd_usage))
436                         if (!test_and_set_bit_lock(i, &npu->mmio_atsd_usage))
437                                 return i;
438         }
439
440         return -ENOSPC;
441 }
442
443 static void put_mmio_atsd_reg(struct npu *npu, int reg)
444 {
445         clear_bit_unlock(reg, &npu->mmio_atsd_usage);
446 }
447
448 /* MMIO ATSD register offsets */
449 #define XTS_ATSD_LAUNCH 0
450 #define XTS_ATSD_AVA    1
451 #define XTS_ATSD_STAT   2
452
453 static unsigned long get_atsd_launch_val(unsigned long pid, unsigned long psize)
454 {
455         unsigned long launch = 0;
456
457         if (psize == MMU_PAGE_COUNT) {
458                 /* IS set to invalidate entire matching PID */
459                 launch |= PPC_BIT(12);
460         } else {
461                 /* AP set to invalidate region of psize */
462                 launch |= (u64)mmu_get_ap(psize) << PPC_BITLSHIFT(17);
463         }
464
465         /* PRS set to process-scoped */
466         launch |= PPC_BIT(13);
467
468         /* PID */
469         launch |= pid << PPC_BITLSHIFT(38);
470
471         /* Leave "No flush" (bit 39) 0 so every ATSD performs a flush */
472
473         return launch;
474 }
475
476 static void mmio_atsd_regs_write(struct mmio_atsd_reg
477                         mmio_atsd_reg[NV_MAX_NPUS], unsigned long offset,
478                         unsigned long val)
479 {
480         struct npu *npu;
481         int i, reg;
482
483         for (i = 0; i <= max_npu2_index; i++) {
484                 reg = mmio_atsd_reg[i].reg;
485                 if (reg < 0)
486                         continue;
487
488                 npu = mmio_atsd_reg[i].npu;
489                 __raw_writeq_be(val, npu->mmio_atsd_regs[reg] + offset);
490         }
491 }
492
493 static void mmio_invalidate_pid(struct mmio_atsd_reg mmio_atsd_reg[NV_MAX_NPUS],
494                                 unsigned long pid)
495 {
496         unsigned long launch = get_atsd_launch_val(pid, MMU_PAGE_COUNT);
497
498         /* Invalidating the entire process doesn't use a va */
499         mmio_atsd_regs_write(mmio_atsd_reg, XTS_ATSD_LAUNCH, launch);
500 }
501
502 static void mmio_invalidate_range(struct mmio_atsd_reg
503                         mmio_atsd_reg[NV_MAX_NPUS], unsigned long pid,
504                         unsigned long start, unsigned long psize)
505 {
506         unsigned long launch = get_atsd_launch_val(pid, psize);
507
508         /* Write all VAs first */
509         mmio_atsd_regs_write(mmio_atsd_reg, XTS_ATSD_AVA, start);
510
511         /* Issue one barrier for all address writes */
512         eieio();
513
514         /* Launch */
515         mmio_atsd_regs_write(mmio_atsd_reg, XTS_ATSD_LAUNCH, launch);
516 }
517
518 #define mn_to_npu_context(x) container_of(x, struct npu_context, mn)
519
520 static void mmio_invalidate_wait(
521         struct mmio_atsd_reg mmio_atsd_reg[NV_MAX_NPUS])
522 {
523         struct npu *npu;
524         int i, reg;
525
526         /* Wait for all invalidations to complete */
527         for (i = 0; i <= max_npu2_index; i++) {
528                 if (mmio_atsd_reg[i].reg < 0)
529                         continue;
530
531                 /* Wait for completion */
532                 npu = mmio_atsd_reg[i].npu;
533                 reg = mmio_atsd_reg[i].reg;
534                 while (__raw_readq(npu->mmio_atsd_regs[reg] + XTS_ATSD_STAT))
535                         cpu_relax();
536         }
537 }
538
539 /*
540  * Acquires all the address translation shootdown (ATSD) registers required to
541  * launch an ATSD on all links this npu_context is active on.
542  */
543 static void acquire_atsd_reg(struct npu_context *npu_context,
544                         struct mmio_atsd_reg mmio_atsd_reg[NV_MAX_NPUS])
545 {
546         int i, j;
547         struct npu *npu;
548         struct pci_dev *npdev;
549         struct pnv_phb *nphb;
550
551         for (i = 0; i <= max_npu2_index; i++) {
552                 mmio_atsd_reg[i].reg = -1;
553                 for (j = 0; j < NV_MAX_LINKS; j++) {
554                         /*
555                          * There are no ordering requirements with respect to
556                          * the setup of struct npu_context, but to ensure
557                          * consistent behaviour we need to ensure npdev[][] is
558                          * only read once.
559                          */
560                         npdev = READ_ONCE(npu_context->npdev[i][j]);
561                         if (!npdev)
562                                 continue;
563
564                         nphb = pci_bus_to_host(npdev->bus)->private_data;
565                         npu = &nphb->npu;
566                         mmio_atsd_reg[i].npu = npu;
567                         mmio_atsd_reg[i].reg = get_mmio_atsd_reg(npu);
568                         while (mmio_atsd_reg[i].reg < 0) {
569                                 mmio_atsd_reg[i].reg = get_mmio_atsd_reg(npu);
570                                 cpu_relax();
571                         }
572                         break;
573                 }
574         }
575 }
576
577 /*
578  * Release previously acquired ATSD registers. To avoid deadlocks the registers
579  * must be released in the same order they were acquired above in
580  * acquire_atsd_reg.
581  */
582 static void release_atsd_reg(struct mmio_atsd_reg mmio_atsd_reg[NV_MAX_NPUS])
583 {
584         int i;
585
586         for (i = 0; i <= max_npu2_index; i++) {
587                 /*
588                  * We can't rely on npu_context->npdev[][] being the same here
589                  * as when acquire_atsd_reg() was called, hence we use the
590                  * values stored in mmio_atsd_reg during the acquire phase
591                  * rather than re-reading npdev[][].
592                  */
593                 if (mmio_atsd_reg[i].reg < 0)
594                         continue;
595
596                 put_mmio_atsd_reg(mmio_atsd_reg[i].npu, mmio_atsd_reg[i].reg);
597         }
598 }
599
600 /*
601  * Invalidate a virtual address range
602  */
603 static void mmio_invalidate(struct npu_context *npu_context,
604                         unsigned long start, unsigned long size)
605 {
606         struct mmio_atsd_reg mmio_atsd_reg[NV_MAX_NPUS];
607         unsigned long pid = npu_context->mm->context.id;
608         unsigned long atsd_start = 0;
609         unsigned long end = start + size - 1;
610         int atsd_psize = MMU_PAGE_COUNT;
611
612         /*
613          * Convert the input range into one of the supported sizes. If the range
614          * doesn't fit, use the next larger supported size. Invalidation latency
615          * is high, so over-invalidation is preferred to issuing multiple
616          * invalidates.
617          *
618          * A 4K page size isn't supported by NPU/GPU ATS, so that case is
619          * ignored.
620          */
621         if (size == SZ_64K) {
622                 atsd_start = start;
623                 atsd_psize = MMU_PAGE_64K;
624         } else if (ALIGN_DOWN(start, SZ_2M) == ALIGN_DOWN(end, SZ_2M)) {
625                 atsd_start = ALIGN_DOWN(start, SZ_2M);
626                 atsd_psize = MMU_PAGE_2M;
627         } else if (ALIGN_DOWN(start, SZ_1G) == ALIGN_DOWN(end, SZ_1G)) {
628                 atsd_start = ALIGN_DOWN(start, SZ_1G);
629                 atsd_psize = MMU_PAGE_1G;
630         }
631
632         if (npu_context->nmmu_flush)
633                 /*
634                  * Unfortunately the nest mmu does not support flushing specific
635                  * addresses so we have to flush the whole mm once before
636                  * shooting down the GPU translation.
637                  */
638                 flush_all_mm(npu_context->mm);
639
640         /*
641          * Loop over all the NPUs this process is active on and launch
642          * an invalidate.
643          */
644         acquire_atsd_reg(npu_context, mmio_atsd_reg);
645
646         if (atsd_psize == MMU_PAGE_COUNT)
647                 mmio_invalidate_pid(mmio_atsd_reg, pid);
648         else
649                 mmio_invalidate_range(mmio_atsd_reg, pid, atsd_start,
650                                         atsd_psize);
651
652         mmio_invalidate_wait(mmio_atsd_reg);
653
654         /*
655          * The GPU requires two flush ATSDs to ensure all entries have been
656          * flushed. We use PID 0 as it will never be used for a process on the
657          * GPU.
658          */
659         mmio_invalidate_pid(mmio_atsd_reg, 0);
660         mmio_invalidate_wait(mmio_atsd_reg);
661         mmio_invalidate_pid(mmio_atsd_reg, 0);
662         mmio_invalidate_wait(mmio_atsd_reg);
663
664         release_atsd_reg(mmio_atsd_reg);
665 }
666
667 static void pnv_npu2_mn_release(struct mmu_notifier *mn,
668                                 struct mm_struct *mm)
669 {
670         struct npu_context *npu_context = mn_to_npu_context(mn);
671
672         /* Call into device driver to stop requests to the NMMU */
673         if (npu_context->release_cb)
674                 npu_context->release_cb(npu_context, npu_context->priv);
675
676         /*
677          * There should be no more translation requests for this PID, but we
678          * need to ensure any entries for it are removed from the TLB.
679          */
680         mmio_invalidate(npu_context, 0, ~0UL);
681 }
682
683 static void pnv_npu2_mn_change_pte(struct mmu_notifier *mn,
684                                 struct mm_struct *mm,
685                                 unsigned long address,
686                                 pte_t pte)
687 {
688         struct npu_context *npu_context = mn_to_npu_context(mn);
689         mmio_invalidate(npu_context, address, PAGE_SIZE);
690 }
691
692 static void pnv_npu2_mn_invalidate_range(struct mmu_notifier *mn,
693                                         struct mm_struct *mm,
694                                         unsigned long start, unsigned long end)
695 {
696         struct npu_context *npu_context = mn_to_npu_context(mn);
697         mmio_invalidate(npu_context, start, end - start);
698 }
699
700 static const struct mmu_notifier_ops nv_nmmu_notifier_ops = {
701         .release = pnv_npu2_mn_release,
702         .change_pte = pnv_npu2_mn_change_pte,
703         .invalidate_range = pnv_npu2_mn_invalidate_range,
704 };
705
706 /*
707  * Call into OPAL to setup the nmmu context for the current task in
708  * the NPU. This must be called to setup the context tables before the
709  * GPU issues ATRs. pdev should be a pointed to PCIe GPU device.
710  *
711  * A release callback should be registered to allow a device driver to
712  * be notified that it should not launch any new translation requests
713  * as the final TLB invalidate is about to occur.
714  *
715  * Returns an error if there no contexts are currently available or a
716  * npu_context which should be passed to pnv_npu2_handle_fault().
717  *
718  * mmap_sem must be held in write mode and must not be called from interrupt
719  * context.
720  */
721 struct npu_context *pnv_npu2_init_context(struct pci_dev *gpdev,
722                         unsigned long flags,
723                         void (*cb)(struct npu_context *, void *),
724                         void *priv)
725 {
726         int rc;
727         u32 nvlink_index;
728         struct device_node *nvlink_dn;
729         struct mm_struct *mm = current->mm;
730         struct pnv_phb *nphb;
731         struct npu *npu;
732         struct npu_context *npu_context;
733
734         /*
735          * At present we don't support GPUs connected to multiple NPUs and I'm
736          * not sure the hardware does either.
737          */
738         struct pci_dev *npdev = pnv_pci_get_npu_dev(gpdev, 0);
739
740         if (!firmware_has_feature(FW_FEATURE_OPAL))
741                 return ERR_PTR(-ENODEV);
742
743         if (!npdev)
744                 /* No nvlink associated with this GPU device */
745                 return ERR_PTR(-ENODEV);
746
747         nvlink_dn = of_parse_phandle(npdev->dev.of_node, "ibm,nvlink", 0);
748         if (WARN_ON(of_property_read_u32(nvlink_dn, "ibm,npu-link-index",
749                                                         &nvlink_index)))
750                 return ERR_PTR(-ENODEV);
751
752         if (!mm || mm->context.id == 0) {
753                 /*
754                  * Kernel thread contexts are not supported and context id 0 is
755                  * reserved on the GPU.
756                  */
757                 return ERR_PTR(-EINVAL);
758         }
759
760         nphb = pci_bus_to_host(npdev->bus)->private_data;
761         npu = &nphb->npu;
762
763         /*
764          * Setup the NPU context table for a particular GPU. These need to be
765          * per-GPU as we need the tables to filter ATSDs when there are no
766          * active contexts on a particular GPU. It is safe for these to be
767          * called concurrently with destroy as the OPAL call takes appropriate
768          * locks and refcounts on init/destroy.
769          */
770         rc = opal_npu_init_context(nphb->opal_id, mm->context.id, flags,
771                                 PCI_DEVID(gpdev->bus->number, gpdev->devfn));
772         if (rc < 0)
773                 return ERR_PTR(-ENOSPC);
774
775         /*
776          * We store the npu pci device so we can more easily get at the
777          * associated npus.
778          */
779         spin_lock(&npu_context_lock);
780         npu_context = mm->context.npu_context;
781         if (npu_context) {
782                 if (npu_context->release_cb != cb ||
783                         npu_context->priv != priv) {
784                         spin_unlock(&npu_context_lock);
785                         opal_npu_destroy_context(nphb->opal_id, mm->context.id,
786                                                 PCI_DEVID(gpdev->bus->number,
787                                                         gpdev->devfn));
788                         return ERR_PTR(-EINVAL);
789                 }
790
791                 WARN_ON(!kref_get_unless_zero(&npu_context->kref));
792         }
793         spin_unlock(&npu_context_lock);
794
795         if (!npu_context) {
796                 /*
797                  * We can set up these fields without holding the
798                  * npu_context_lock as the npu_context hasn't been returned to
799                  * the caller meaning it can't be destroyed. Parallel allocation
800                  * is protected against by mmap_sem.
801                  */
802                 rc = -ENOMEM;
803                 npu_context = kzalloc(sizeof(struct npu_context), GFP_KERNEL);
804                 if (npu_context) {
805                         kref_init(&npu_context->kref);
806                         npu_context->mm = mm;
807                         npu_context->mn.ops = &nv_nmmu_notifier_ops;
808                         rc = __mmu_notifier_register(&npu_context->mn, mm);
809                 }
810
811                 if (rc) {
812                         kfree(npu_context);
813                         opal_npu_destroy_context(nphb->opal_id, mm->context.id,
814                                         PCI_DEVID(gpdev->bus->number,
815                                                 gpdev->devfn));
816                         return ERR_PTR(rc);
817                 }
818
819                 mm->context.npu_context = npu_context;
820         }
821
822         npu_context->release_cb = cb;
823         npu_context->priv = priv;
824
825         /*
826          * npdev is a pci_dev pointer setup by the PCI code. We assign it to
827          * npdev[][] to indicate to the mmu notifiers that an invalidation
828          * should also be sent over this nvlink. The notifiers don't use any
829          * other fields in npu_context, so we just need to ensure that when they
830          * deference npu_context->npdev[][] it is either a valid pointer or
831          * NULL.
832          */
833         WRITE_ONCE(npu_context->npdev[npu->index][nvlink_index], npdev);
834
835         if (!nphb->npu.nmmu_flush) {
836                 /*
837                  * If we're not explicitly flushing ourselves we need to mark
838                  * the thread for global flushes
839                  */
840                 npu_context->nmmu_flush = false;
841                 mm_context_add_copro(mm);
842         } else
843                 npu_context->nmmu_flush = true;
844
845         return npu_context;
846 }
847 EXPORT_SYMBOL(pnv_npu2_init_context);
848
849 static void pnv_npu2_release_context(struct kref *kref)
850 {
851         struct npu_context *npu_context =
852                 container_of(kref, struct npu_context, kref);
853
854         if (!npu_context->nmmu_flush)
855                 mm_context_remove_copro(npu_context->mm);
856
857         npu_context->mm->context.npu_context = NULL;
858 }
859
860 /*
861  * Destroy a context on the given GPU. May free the npu_context if it is no
862  * longer active on any GPUs. Must not be called from interrupt context.
863  */
864 void pnv_npu2_destroy_context(struct npu_context *npu_context,
865                         struct pci_dev *gpdev)
866 {
867         int removed;
868         struct pnv_phb *nphb;
869         struct npu *npu;
870         struct pci_dev *npdev = pnv_pci_get_npu_dev(gpdev, 0);
871         struct device_node *nvlink_dn;
872         u32 nvlink_index;
873
874         if (WARN_ON(!npdev))
875                 return;
876
877         if (!firmware_has_feature(FW_FEATURE_OPAL))
878                 return;
879
880         nphb = pci_bus_to_host(npdev->bus)->private_data;
881         npu = &nphb->npu;
882         nvlink_dn = of_parse_phandle(npdev->dev.of_node, "ibm,nvlink", 0);
883         if (WARN_ON(of_property_read_u32(nvlink_dn, "ibm,npu-link-index",
884                                                         &nvlink_index)))
885                 return;
886         WRITE_ONCE(npu_context->npdev[npu->index][nvlink_index], NULL);
887         opal_npu_destroy_context(nphb->opal_id, npu_context->mm->context.id,
888                                 PCI_DEVID(gpdev->bus->number, gpdev->devfn));
889         spin_lock(&npu_context_lock);
890         removed = kref_put(&npu_context->kref, pnv_npu2_release_context);
891         spin_unlock(&npu_context_lock);
892
893         /*
894          * We need to do this outside of pnv_npu2_release_context so that it is
895          * outside the spinlock as mmu_notifier_destroy uses SRCU.
896          */
897         if (removed) {
898                 mmu_notifier_unregister(&npu_context->mn,
899                                         npu_context->mm);
900
901                 kfree(npu_context);
902         }
903
904 }
905 EXPORT_SYMBOL(pnv_npu2_destroy_context);
906
907 /*
908  * Assumes mmap_sem is held for the contexts associated mm.
909  */
910 int pnv_npu2_handle_fault(struct npu_context *context, uintptr_t *ea,
911                         unsigned long *flags, unsigned long *status, int count)
912 {
913         u64 rc = 0, result = 0;
914         int i, is_write;
915         struct page *page[1];
916
917         /* mmap_sem should be held so the struct_mm must be present */
918         struct mm_struct *mm = context->mm;
919
920         if (!firmware_has_feature(FW_FEATURE_OPAL))
921                 return -ENODEV;
922
923         WARN_ON(!rwsem_is_locked(&mm->mmap_sem));
924
925         for (i = 0; i < count; i++) {
926                 is_write = flags[i] & NPU2_WRITE;
927                 rc = get_user_pages_remote(NULL, mm, ea[i], 1,
928                                         is_write ? FOLL_WRITE : 0,
929                                         page, NULL, NULL);
930
931                 /*
932                  * To support virtualised environments we will have to do an
933                  * access to the page to ensure it gets faulted into the
934                  * hypervisor. For the moment virtualisation is not supported in
935                  * other areas so leave the access out.
936                  */
937                 if (rc != 1) {
938                         status[i] = rc;
939                         result = -EFAULT;
940                         continue;
941                 }
942
943                 status[i] = 0;
944                 put_page(page[0]);
945         }
946
947         return result;
948 }
949 EXPORT_SYMBOL(pnv_npu2_handle_fault);
950
951 int pnv_npu2_init(struct pnv_phb *phb)
952 {
953         unsigned int i;
954         u64 mmio_atsd;
955         struct device_node *dn;
956         struct pci_dev *gpdev;
957         static int npu_index;
958         uint64_t rc = 0;
959
960         phb->npu.nmmu_flush =
961                 of_property_read_bool(phb->hose->dn, "ibm,nmmu-flush");
962         for_each_child_of_node(phb->hose->dn, dn) {
963                 gpdev = pnv_pci_get_gpu_dev(get_pci_dev(dn));
964                 if (gpdev) {
965                         rc = opal_npu_map_lpar(phb->opal_id,
966                                 PCI_DEVID(gpdev->bus->number, gpdev->devfn),
967                                 0, 0);
968                         if (rc)
969                                 dev_err(&gpdev->dev,
970                                         "Error %lld mapping device to LPAR\n",
971                                         rc);
972                 }
973         }
974
975         for (i = 0; !of_property_read_u64_index(phb->hose->dn, "ibm,mmio-atsd",
976                                                         i, &mmio_atsd); i++)
977                 phb->npu.mmio_atsd_regs[i] = ioremap(mmio_atsd, 32);
978
979         pr_info("NPU%lld: Found %d MMIO ATSD registers", phb->opal_id, i);
980         phb->npu.mmio_atsd_count = i;
981         phb->npu.mmio_atsd_usage = 0;
982         npu_index++;
983         if (WARN_ON(npu_index >= NV_MAX_NPUS))
984                 return -ENOSPC;
985         max_npu2_index = npu_index;
986         phb->npu.index = npu_index;
987
988         return 0;
989 }