Merge tag 'printk-for-5.15' of git://git.kernel.org/pub/scm/linux/kernel/git/printk...
[linux-2.6-microblaze.git] / arch / powerpc / platforms / pseries / iommu.c
1 // SPDX-License-Identifier: GPL-2.0-or-later
2 /*
3  * Copyright (C) 2001 Mike Corrigan & Dave Engebretsen, IBM Corporation
4  *
5  * Rewrite, cleanup:
6  *
7  * Copyright (C) 2004 Olof Johansson <olof@lixom.net>, IBM Corporation
8  * Copyright (C) 2006 Olof Johansson <olof@lixom.net>
9  *
10  * Dynamic DMA mapping support, pSeries-specific parts, both SMP and LPAR.
11  */
12
13 #include <linux/init.h>
14 #include <linux/types.h>
15 #include <linux/slab.h>
16 #include <linux/mm.h>
17 #include <linux/memblock.h>
18 #include <linux/spinlock.h>
19 #include <linux/string.h>
20 #include <linux/pci.h>
21 #include <linux/dma-mapping.h>
22 #include <linux/crash_dump.h>
23 #include <linux/memory.h>
24 #include <linux/of.h>
25 #include <linux/iommu.h>
26 #include <linux/rculist.h>
27 #include <asm/io.h>
28 #include <asm/prom.h>
29 #include <asm/rtas.h>
30 #include <asm/iommu.h>
31 #include <asm/pci-bridge.h>
32 #include <asm/machdep.h>
33 #include <asm/firmware.h>
34 #include <asm/tce.h>
35 #include <asm/ppc-pci.h>
36 #include <asm/udbg.h>
37 #include <asm/mmzone.h>
38 #include <asm/plpar_wrappers.h>
39
40 #include "pseries.h"
41
42 enum {
43         DDW_QUERY_PE_DMA_WIN  = 0,
44         DDW_CREATE_PE_DMA_WIN = 1,
45         DDW_REMOVE_PE_DMA_WIN = 2,
46
47         DDW_APPLICABLE_SIZE
48 };
49
50 enum {
51         DDW_EXT_SIZE = 0,
52         DDW_EXT_RESET_DMA_WIN = 1,
53         DDW_EXT_QUERY_OUT_SIZE = 2
54 };
55
56 static struct iommu_table_group *iommu_pseries_alloc_group(int node)
57 {
58         struct iommu_table_group *table_group;
59         struct iommu_table *tbl;
60
61         table_group = kzalloc_node(sizeof(struct iommu_table_group), GFP_KERNEL,
62                            node);
63         if (!table_group)
64                 return NULL;
65
66         tbl = kzalloc_node(sizeof(struct iommu_table), GFP_KERNEL, node);
67         if (!tbl)
68                 goto free_group;
69
70         INIT_LIST_HEAD_RCU(&tbl->it_group_list);
71         kref_init(&tbl->it_kref);
72
73         table_group->tables[0] = tbl;
74
75         return table_group;
76
77 free_group:
78         kfree(table_group);
79         return NULL;
80 }
81
82 static void iommu_pseries_free_group(struct iommu_table_group *table_group,
83                 const char *node_name)
84 {
85         struct iommu_table *tbl;
86
87         if (!table_group)
88                 return;
89
90         tbl = table_group->tables[0];
91 #ifdef CONFIG_IOMMU_API
92         if (table_group->group) {
93                 iommu_group_put(table_group->group);
94                 BUG_ON(table_group->group);
95         }
96 #endif
97         iommu_tce_table_put(tbl);
98
99         kfree(table_group);
100 }
101
102 static int tce_build_pSeries(struct iommu_table *tbl, long index,
103                               long npages, unsigned long uaddr,
104                               enum dma_data_direction direction,
105                               unsigned long attrs)
106 {
107         u64 proto_tce;
108         __be64 *tcep;
109         u64 rpn;
110
111         proto_tce = TCE_PCI_READ; // Read allowed
112
113         if (direction != DMA_TO_DEVICE)
114                 proto_tce |= TCE_PCI_WRITE;
115
116         tcep = ((__be64 *)tbl->it_base) + index;
117
118         while (npages--) {
119                 /* can't move this out since we might cross MEMBLOCK boundary */
120                 rpn = __pa(uaddr) >> TCE_SHIFT;
121                 *tcep = cpu_to_be64(proto_tce | (rpn & TCE_RPN_MASK) << TCE_RPN_SHIFT);
122
123                 uaddr += TCE_PAGE_SIZE;
124                 tcep++;
125         }
126         return 0;
127 }
128
129
130 static void tce_free_pSeries(struct iommu_table *tbl, long index, long npages)
131 {
132         __be64 *tcep;
133
134         tcep = ((__be64 *)tbl->it_base) + index;
135
136         while (npages--)
137                 *(tcep++) = 0;
138 }
139
140 static unsigned long tce_get_pseries(struct iommu_table *tbl, long index)
141 {
142         __be64 *tcep;
143
144         tcep = ((__be64 *)tbl->it_base) + index;
145
146         return be64_to_cpu(*tcep);
147 }
148
149 static void tce_free_pSeriesLP(unsigned long liobn, long, long);
150 static void tce_freemulti_pSeriesLP(struct iommu_table*, long, long);
151
152 static int tce_build_pSeriesLP(unsigned long liobn, long tcenum, long tceshift,
153                                 long npages, unsigned long uaddr,
154                                 enum dma_data_direction direction,
155                                 unsigned long attrs)
156 {
157         u64 rc = 0;
158         u64 proto_tce, tce;
159         u64 rpn;
160         int ret = 0;
161         long tcenum_start = tcenum, npages_start = npages;
162
163         rpn = __pa(uaddr) >> tceshift;
164         proto_tce = TCE_PCI_READ;
165         if (direction != DMA_TO_DEVICE)
166                 proto_tce |= TCE_PCI_WRITE;
167
168         while (npages--) {
169                 tce = proto_tce | (rpn & TCE_RPN_MASK) << tceshift;
170                 rc = plpar_tce_put((u64)liobn, (u64)tcenum << tceshift, tce);
171
172                 if (unlikely(rc == H_NOT_ENOUGH_RESOURCES)) {
173                         ret = (int)rc;
174                         tce_free_pSeriesLP(liobn, tcenum_start,
175                                            (npages_start - (npages + 1)));
176                         break;
177                 }
178
179                 if (rc && printk_ratelimit()) {
180                         printk("tce_build_pSeriesLP: plpar_tce_put failed. rc=%lld\n", rc);
181                         printk("\tindex   = 0x%llx\n", (u64)liobn);
182                         printk("\ttcenum  = 0x%llx\n", (u64)tcenum);
183                         printk("\ttce val = 0x%llx\n", tce );
184                         dump_stack();
185                 }
186
187                 tcenum++;
188                 rpn++;
189         }
190         return ret;
191 }
192
193 static DEFINE_PER_CPU(__be64 *, tce_page);
194
195 static int tce_buildmulti_pSeriesLP(struct iommu_table *tbl, long tcenum,
196                                      long npages, unsigned long uaddr,
197                                      enum dma_data_direction direction,
198                                      unsigned long attrs)
199 {
200         u64 rc = 0;
201         u64 proto_tce;
202         __be64 *tcep;
203         u64 rpn;
204         long l, limit;
205         long tcenum_start = tcenum, npages_start = npages;
206         int ret = 0;
207         unsigned long flags;
208
209         if ((npages == 1) || !firmware_has_feature(FW_FEATURE_PUT_TCE_IND)) {
210                 return tce_build_pSeriesLP(tbl->it_index, tcenum,
211                                            tbl->it_page_shift, npages, uaddr,
212                                            direction, attrs);
213         }
214
215         local_irq_save(flags);  /* to protect tcep and the page behind it */
216
217         tcep = __this_cpu_read(tce_page);
218
219         /* This is safe to do since interrupts are off when we're called
220          * from iommu_alloc{,_sg}()
221          */
222         if (!tcep) {
223                 tcep = (__be64 *)__get_free_page(GFP_ATOMIC);
224                 /* If allocation fails, fall back to the loop implementation */
225                 if (!tcep) {
226                         local_irq_restore(flags);
227                         return tce_build_pSeriesLP(tbl->it_index, tcenum,
228                                         tbl->it_page_shift,
229                                         npages, uaddr, direction, attrs);
230                 }
231                 __this_cpu_write(tce_page, tcep);
232         }
233
234         rpn = __pa(uaddr) >> TCE_SHIFT;
235         proto_tce = TCE_PCI_READ;
236         if (direction != DMA_TO_DEVICE)
237                 proto_tce |= TCE_PCI_WRITE;
238
239         /* We can map max one pageful of TCEs at a time */
240         do {
241                 /*
242                  * Set up the page with TCE data, looping through and setting
243                  * the values.
244                  */
245                 limit = min_t(long, npages, 4096/TCE_ENTRY_SIZE);
246
247                 for (l = 0; l < limit; l++) {
248                         tcep[l] = cpu_to_be64(proto_tce | (rpn & TCE_RPN_MASK) << TCE_RPN_SHIFT);
249                         rpn++;
250                 }
251
252                 rc = plpar_tce_put_indirect((u64)tbl->it_index,
253                                             (u64)tcenum << 12,
254                                             (u64)__pa(tcep),
255                                             limit);
256
257                 npages -= limit;
258                 tcenum += limit;
259         } while (npages > 0 && !rc);
260
261         local_irq_restore(flags);
262
263         if (unlikely(rc == H_NOT_ENOUGH_RESOURCES)) {
264                 ret = (int)rc;
265                 tce_freemulti_pSeriesLP(tbl, tcenum_start,
266                                         (npages_start - (npages + limit)));
267                 return ret;
268         }
269
270         if (rc && printk_ratelimit()) {
271                 printk("tce_buildmulti_pSeriesLP: plpar_tce_put failed. rc=%lld\n", rc);
272                 printk("\tindex   = 0x%llx\n", (u64)tbl->it_index);
273                 printk("\tnpages  = 0x%llx\n", (u64)npages);
274                 printk("\ttce[0] val = 0x%llx\n", tcep[0]);
275                 dump_stack();
276         }
277         return ret;
278 }
279
280 static void tce_free_pSeriesLP(unsigned long liobn, long tcenum, long npages)
281 {
282         u64 rc;
283
284         while (npages--) {
285                 rc = plpar_tce_put((u64)liobn, (u64)tcenum << 12, 0);
286
287                 if (rc && printk_ratelimit()) {
288                         printk("tce_free_pSeriesLP: plpar_tce_put failed. rc=%lld\n", rc);
289                         printk("\tindex   = 0x%llx\n", (u64)liobn);
290                         printk("\ttcenum  = 0x%llx\n", (u64)tcenum);
291                         dump_stack();
292                 }
293
294                 tcenum++;
295         }
296 }
297
298
299 static void tce_freemulti_pSeriesLP(struct iommu_table *tbl, long tcenum, long npages)
300 {
301         u64 rc;
302
303         if (!firmware_has_feature(FW_FEATURE_STUFF_TCE))
304                 return tce_free_pSeriesLP(tbl->it_index, tcenum, npages);
305
306         rc = plpar_tce_stuff((u64)tbl->it_index, (u64)tcenum << 12, 0, npages);
307
308         if (rc && printk_ratelimit()) {
309                 printk("tce_freemulti_pSeriesLP: plpar_tce_stuff failed\n");
310                 printk("\trc      = %lld\n", rc);
311                 printk("\tindex   = 0x%llx\n", (u64)tbl->it_index);
312                 printk("\tnpages  = 0x%llx\n", (u64)npages);
313                 dump_stack();
314         }
315 }
316
317 static unsigned long tce_get_pSeriesLP(struct iommu_table *tbl, long tcenum)
318 {
319         u64 rc;
320         unsigned long tce_ret;
321
322         rc = plpar_tce_get((u64)tbl->it_index, (u64)tcenum << 12, &tce_ret);
323
324         if (rc && printk_ratelimit()) {
325                 printk("tce_get_pSeriesLP: plpar_tce_get failed. rc=%lld\n", rc);
326                 printk("\tindex   = 0x%llx\n", (u64)tbl->it_index);
327                 printk("\ttcenum  = 0x%llx\n", (u64)tcenum);
328                 dump_stack();
329         }
330
331         return tce_ret;
332 }
333
334 /* this is compatible with cells for the device tree property */
335 struct dynamic_dma_window_prop {
336         __be32  liobn;          /* tce table number */
337         __be64  dma_base;       /* address hi,lo */
338         __be32  tce_shift;      /* ilog2(tce_page_size) */
339         __be32  window_shift;   /* ilog2(tce_window_size) */
340 };
341
342 struct direct_window {
343         struct device_node *device;
344         const struct dynamic_dma_window_prop *prop;
345         struct list_head list;
346 };
347
348 /* Dynamic DMA Window support */
349 struct ddw_query_response {
350         u32 windows_available;
351         u64 largest_available_block;
352         u32 page_size;
353         u32 migration_capable;
354 };
355
356 struct ddw_create_response {
357         u32 liobn;
358         u32 addr_hi;
359         u32 addr_lo;
360 };
361
362 static LIST_HEAD(direct_window_list);
363 /* prevents races between memory on/offline and window creation */
364 static DEFINE_SPINLOCK(direct_window_list_lock);
365 /* protects initializing window twice for same device */
366 static DEFINE_MUTEX(direct_window_init_mutex);
367 #define DIRECT64_PROPNAME "linux,direct64-ddr-window-info"
368
369 static int tce_clearrange_multi_pSeriesLP(unsigned long start_pfn,
370                                         unsigned long num_pfn, const void *arg)
371 {
372         const struct dynamic_dma_window_prop *maprange = arg;
373         int rc;
374         u64 tce_size, num_tce, dma_offset, next;
375         u32 tce_shift;
376         long limit;
377
378         tce_shift = be32_to_cpu(maprange->tce_shift);
379         tce_size = 1ULL << tce_shift;
380         next = start_pfn << PAGE_SHIFT;
381         num_tce = num_pfn << PAGE_SHIFT;
382
383         /* round back to the beginning of the tce page size */
384         num_tce += next & (tce_size - 1);
385         next &= ~(tce_size - 1);
386
387         /* covert to number of tces */
388         num_tce |= tce_size - 1;
389         num_tce >>= tce_shift;
390
391         do {
392                 /*
393                  * Set up the page with TCE data, looping through and setting
394                  * the values.
395                  */
396                 limit = min_t(long, num_tce, 512);
397                 dma_offset = next + be64_to_cpu(maprange->dma_base);
398
399                 rc = plpar_tce_stuff((u64)be32_to_cpu(maprange->liobn),
400                                              dma_offset,
401                                              0, limit);
402                 next += limit * tce_size;
403                 num_tce -= limit;
404         } while (num_tce > 0 && !rc);
405
406         return rc;
407 }
408
409 static int tce_setrange_multi_pSeriesLP(unsigned long start_pfn,
410                                         unsigned long num_pfn, const void *arg)
411 {
412         const struct dynamic_dma_window_prop *maprange = arg;
413         u64 tce_size, num_tce, dma_offset, next, proto_tce, liobn;
414         __be64 *tcep;
415         u32 tce_shift;
416         u64 rc = 0;
417         long l, limit;
418
419         if (!firmware_has_feature(FW_FEATURE_PUT_TCE_IND)) {
420                 unsigned long tceshift = be32_to_cpu(maprange->tce_shift);
421                 unsigned long dmastart = (start_pfn << PAGE_SHIFT) +
422                                 be64_to_cpu(maprange->dma_base);
423                 unsigned long tcenum = dmastart >> tceshift;
424                 unsigned long npages = num_pfn << PAGE_SHIFT >> tceshift;
425                 void *uaddr = __va(start_pfn << PAGE_SHIFT);
426
427                 return tce_build_pSeriesLP(be32_to_cpu(maprange->liobn),
428                                 tcenum, tceshift, npages, (unsigned long) uaddr,
429                                 DMA_BIDIRECTIONAL, 0);
430         }
431
432         local_irq_disable();    /* to protect tcep and the page behind it */
433         tcep = __this_cpu_read(tce_page);
434
435         if (!tcep) {
436                 tcep = (__be64 *)__get_free_page(GFP_ATOMIC);
437                 if (!tcep) {
438                         local_irq_enable();
439                         return -ENOMEM;
440                 }
441                 __this_cpu_write(tce_page, tcep);
442         }
443
444         proto_tce = TCE_PCI_READ | TCE_PCI_WRITE;
445
446         liobn = (u64)be32_to_cpu(maprange->liobn);
447         tce_shift = be32_to_cpu(maprange->tce_shift);
448         tce_size = 1ULL << tce_shift;
449         next = start_pfn << PAGE_SHIFT;
450         num_tce = num_pfn << PAGE_SHIFT;
451
452         /* round back to the beginning of the tce page size */
453         num_tce += next & (tce_size - 1);
454         next &= ~(tce_size - 1);
455
456         /* covert to number of tces */
457         num_tce |= tce_size - 1;
458         num_tce >>= tce_shift;
459
460         /* We can map max one pageful of TCEs at a time */
461         do {
462                 /*
463                  * Set up the page with TCE data, looping through and setting
464                  * the values.
465                  */
466                 limit = min_t(long, num_tce, 4096/TCE_ENTRY_SIZE);
467                 dma_offset = next + be64_to_cpu(maprange->dma_base);
468
469                 for (l = 0; l < limit; l++) {
470                         tcep[l] = cpu_to_be64(proto_tce | next);
471                         next += tce_size;
472                 }
473
474                 rc = plpar_tce_put_indirect(liobn,
475                                             dma_offset,
476                                             (u64)__pa(tcep),
477                                             limit);
478
479                 num_tce -= limit;
480         } while (num_tce > 0 && !rc);
481
482         /* error cleanup: caller will clear whole range */
483
484         local_irq_enable();
485         return rc;
486 }
487
488 static int tce_setrange_multi_pSeriesLP_walk(unsigned long start_pfn,
489                 unsigned long num_pfn, void *arg)
490 {
491         return tce_setrange_multi_pSeriesLP(start_pfn, num_pfn, arg);
492 }
493
494 static void iommu_table_setparms(struct pci_controller *phb,
495                                  struct device_node *dn,
496                                  struct iommu_table *tbl)
497 {
498         struct device_node *node;
499         const unsigned long *basep;
500         const u32 *sizep;
501
502         node = phb->dn;
503
504         basep = of_get_property(node, "linux,tce-base", NULL);
505         sizep = of_get_property(node, "linux,tce-size", NULL);
506         if (basep == NULL || sizep == NULL) {
507                 printk(KERN_ERR "PCI_DMA: iommu_table_setparms: %pOF has "
508                                 "missing tce entries !\n", dn);
509                 return;
510         }
511
512         tbl->it_base = (unsigned long)__va(*basep);
513
514         if (!is_kdump_kernel())
515                 memset((void *)tbl->it_base, 0, *sizep);
516
517         tbl->it_busno = phb->bus->number;
518         tbl->it_page_shift = IOMMU_PAGE_SHIFT_4K;
519
520         /* Units of tce entries */
521         tbl->it_offset = phb->dma_window_base_cur >> tbl->it_page_shift;
522
523         /* Test if we are going over 2GB of DMA space */
524         if (phb->dma_window_base_cur + phb->dma_window_size > 0x80000000ul) {
525                 udbg_printf("PCI_DMA: Unexpected number of IOAs under this PHB.\n");
526                 panic("PCI_DMA: Unexpected number of IOAs under this PHB.\n");
527         }
528
529         phb->dma_window_base_cur += phb->dma_window_size;
530
531         /* Set the tce table size - measured in entries */
532         tbl->it_size = phb->dma_window_size >> tbl->it_page_shift;
533
534         tbl->it_index = 0;
535         tbl->it_blocksize = 16;
536         tbl->it_type = TCE_PCI;
537 }
538
539 /*
540  * iommu_table_setparms_lpar
541  *
542  * Function: On pSeries LPAR systems, return TCE table info, given a pci bus.
543  */
544 static void iommu_table_setparms_lpar(struct pci_controller *phb,
545                                       struct device_node *dn,
546                                       struct iommu_table *tbl,
547                                       struct iommu_table_group *table_group,
548                                       const __be32 *dma_window)
549 {
550         unsigned long offset, size;
551
552         of_parse_dma_window(dn, dma_window, &tbl->it_index, &offset, &size);
553
554         tbl->it_busno = phb->bus->number;
555         tbl->it_page_shift = IOMMU_PAGE_SHIFT_4K;
556         tbl->it_base   = 0;
557         tbl->it_blocksize  = 16;
558         tbl->it_type = TCE_PCI;
559         tbl->it_offset = offset >> tbl->it_page_shift;
560         tbl->it_size = size >> tbl->it_page_shift;
561
562         table_group->tce32_start = offset;
563         table_group->tce32_size = size;
564 }
565
566 struct iommu_table_ops iommu_table_pseries_ops = {
567         .set = tce_build_pSeries,
568         .clear = tce_free_pSeries,
569         .get = tce_get_pseries
570 };
571
572 static void pci_dma_bus_setup_pSeries(struct pci_bus *bus)
573 {
574         struct device_node *dn;
575         struct iommu_table *tbl;
576         struct device_node *isa_dn, *isa_dn_orig;
577         struct device_node *tmp;
578         struct pci_dn *pci;
579         int children;
580
581         dn = pci_bus_to_OF_node(bus);
582
583         pr_debug("pci_dma_bus_setup_pSeries: setting up bus %pOF\n", dn);
584
585         if (bus->self) {
586                 /* This is not a root bus, any setup will be done for the
587                  * device-side of the bridge in iommu_dev_setup_pSeries().
588                  */
589                 return;
590         }
591         pci = PCI_DN(dn);
592
593         /* Check if the ISA bus on the system is under
594          * this PHB.
595          */
596         isa_dn = isa_dn_orig = of_find_node_by_type(NULL, "isa");
597
598         while (isa_dn && isa_dn != dn)
599                 isa_dn = isa_dn->parent;
600
601         of_node_put(isa_dn_orig);
602
603         /* Count number of direct PCI children of the PHB. */
604         for (children = 0, tmp = dn->child; tmp; tmp = tmp->sibling)
605                 children++;
606
607         pr_debug("Children: %d\n", children);
608
609         /* Calculate amount of DMA window per slot. Each window must be
610          * a power of two (due to pci_alloc_consistent requirements).
611          *
612          * Keep 256MB aside for PHBs with ISA.
613          */
614
615         if (!isa_dn) {
616                 /* No ISA/IDE - just set window size and return */
617                 pci->phb->dma_window_size = 0x80000000ul; /* To be divided */
618
619                 while (pci->phb->dma_window_size * children > 0x80000000ul)
620                         pci->phb->dma_window_size >>= 1;
621                 pr_debug("No ISA/IDE, window size is 0x%llx\n",
622                          pci->phb->dma_window_size);
623                 pci->phb->dma_window_base_cur = 0;
624
625                 return;
626         }
627
628         /* If we have ISA, then we probably have an IDE
629          * controller too. Allocate a 128MB table but
630          * skip the first 128MB to avoid stepping on ISA
631          * space.
632          */
633         pci->phb->dma_window_size = 0x8000000ul;
634         pci->phb->dma_window_base_cur = 0x8000000ul;
635
636         pci->table_group = iommu_pseries_alloc_group(pci->phb->node);
637         tbl = pci->table_group->tables[0];
638
639         iommu_table_setparms(pci->phb, dn, tbl);
640         tbl->it_ops = &iommu_table_pseries_ops;
641         if (!iommu_init_table(tbl, pci->phb->node, 0, 0))
642                 panic("Failed to initialize iommu table");
643
644         /* Divide the rest (1.75GB) among the children */
645         pci->phb->dma_window_size = 0x80000000ul;
646         while (pci->phb->dma_window_size * children > 0x70000000ul)
647                 pci->phb->dma_window_size >>= 1;
648
649         pr_debug("ISA/IDE, window size is 0x%llx\n", pci->phb->dma_window_size);
650 }
651
652 #ifdef CONFIG_IOMMU_API
653 static int tce_exchange_pseries(struct iommu_table *tbl, long index, unsigned
654                                 long *tce, enum dma_data_direction *direction,
655                                 bool realmode)
656 {
657         long rc;
658         unsigned long ioba = (unsigned long) index << tbl->it_page_shift;
659         unsigned long flags, oldtce = 0;
660         u64 proto_tce = iommu_direction_to_tce_perm(*direction);
661         unsigned long newtce = *tce | proto_tce;
662
663         spin_lock_irqsave(&tbl->large_pool.lock, flags);
664
665         rc = plpar_tce_get((u64)tbl->it_index, ioba, &oldtce);
666         if (!rc)
667                 rc = plpar_tce_put((u64)tbl->it_index, ioba, newtce);
668
669         if (!rc) {
670                 *direction = iommu_tce_direction(oldtce);
671                 *tce = oldtce & ~(TCE_PCI_READ | TCE_PCI_WRITE);
672         }
673
674         spin_unlock_irqrestore(&tbl->large_pool.lock, flags);
675
676         return rc;
677 }
678 #endif
679
680 struct iommu_table_ops iommu_table_lpar_multi_ops = {
681         .set = tce_buildmulti_pSeriesLP,
682 #ifdef CONFIG_IOMMU_API
683         .xchg_no_kill = tce_exchange_pseries,
684 #endif
685         .clear = tce_freemulti_pSeriesLP,
686         .get = tce_get_pSeriesLP
687 };
688
689 static void pci_dma_bus_setup_pSeriesLP(struct pci_bus *bus)
690 {
691         struct iommu_table *tbl;
692         struct device_node *dn, *pdn;
693         struct pci_dn *ppci;
694         const __be32 *dma_window = NULL;
695
696         dn = pci_bus_to_OF_node(bus);
697
698         pr_debug("pci_dma_bus_setup_pSeriesLP: setting up bus %pOF\n",
699                  dn);
700
701         /* Find nearest ibm,dma-window, walking up the device tree */
702         for (pdn = dn; pdn != NULL; pdn = pdn->parent) {
703                 dma_window = of_get_property(pdn, "ibm,dma-window", NULL);
704                 if (dma_window != NULL)
705                         break;
706         }
707
708         if (dma_window == NULL) {
709                 pr_debug("  no ibm,dma-window property !\n");
710                 return;
711         }
712
713         ppci = PCI_DN(pdn);
714
715         pr_debug("  parent is %pOF, iommu_table: 0x%p\n",
716                  pdn, ppci->table_group);
717
718         if (!ppci->table_group) {
719                 ppci->table_group = iommu_pseries_alloc_group(ppci->phb->node);
720                 tbl = ppci->table_group->tables[0];
721                 iommu_table_setparms_lpar(ppci->phb, pdn, tbl,
722                                 ppci->table_group, dma_window);
723                 tbl->it_ops = &iommu_table_lpar_multi_ops;
724                 if (!iommu_init_table(tbl, ppci->phb->node, 0, 0))
725                         panic("Failed to initialize iommu table");
726                 iommu_register_group(ppci->table_group,
727                                 pci_domain_nr(bus), 0);
728                 pr_debug("  created table: %p\n", ppci->table_group);
729         }
730 }
731
732
733 static void pci_dma_dev_setup_pSeries(struct pci_dev *dev)
734 {
735         struct device_node *dn;
736         struct iommu_table *tbl;
737
738         pr_debug("pci_dma_dev_setup_pSeries: %s\n", pci_name(dev));
739
740         dn = dev->dev.of_node;
741
742         /* If we're the direct child of a root bus, then we need to allocate
743          * an iommu table ourselves. The bus setup code should have setup
744          * the window sizes already.
745          */
746         if (!dev->bus->self) {
747                 struct pci_controller *phb = PCI_DN(dn)->phb;
748
749                 pr_debug(" --> first child, no bridge. Allocating iommu table.\n");
750                 PCI_DN(dn)->table_group = iommu_pseries_alloc_group(phb->node);
751                 tbl = PCI_DN(dn)->table_group->tables[0];
752                 iommu_table_setparms(phb, dn, tbl);
753                 tbl->it_ops = &iommu_table_pseries_ops;
754                 if (!iommu_init_table(tbl, phb->node, 0, 0))
755                         panic("Failed to initialize iommu table");
756
757                 set_iommu_table_base(&dev->dev, tbl);
758                 return;
759         }
760
761         /* If this device is further down the bus tree, search upwards until
762          * an already allocated iommu table is found and use that.
763          */
764
765         while (dn && PCI_DN(dn) && PCI_DN(dn)->table_group == NULL)
766                 dn = dn->parent;
767
768         if (dn && PCI_DN(dn))
769                 set_iommu_table_base(&dev->dev,
770                                 PCI_DN(dn)->table_group->tables[0]);
771         else
772                 printk(KERN_WARNING "iommu: Device %s has no iommu table\n",
773                        pci_name(dev));
774 }
775
776 static int __read_mostly disable_ddw;
777
778 static int __init disable_ddw_setup(char *str)
779 {
780         disable_ddw = 1;
781         printk(KERN_INFO "ppc iommu: disabling ddw.\n");
782
783         return 0;
784 }
785
786 early_param("disable_ddw", disable_ddw_setup);
787
788 static void remove_dma_window(struct device_node *np, u32 *ddw_avail,
789                               struct property *win)
790 {
791         struct dynamic_dma_window_prop *dwp;
792         u64 liobn;
793         int ret;
794
795         dwp = win->value;
796         liobn = (u64)be32_to_cpu(dwp->liobn);
797
798         /* clear the whole window, note the arg is in kernel pages */
799         ret = tce_clearrange_multi_pSeriesLP(0,
800                 1ULL << (be32_to_cpu(dwp->window_shift) - PAGE_SHIFT), dwp);
801         if (ret)
802                 pr_warn("%pOF failed to clear tces in window.\n",
803                         np);
804         else
805                 pr_debug("%pOF successfully cleared tces in window.\n",
806                          np);
807
808         ret = rtas_call(ddw_avail[DDW_REMOVE_PE_DMA_WIN], 1, 1, NULL, liobn);
809         if (ret)
810                 pr_warn("%pOF: failed to remove direct window: rtas returned "
811                         "%d to ibm,remove-pe-dma-window(%x) %llx\n",
812                         np, ret, ddw_avail[DDW_REMOVE_PE_DMA_WIN], liobn);
813         else
814                 pr_debug("%pOF: successfully removed direct window: rtas returned "
815                         "%d to ibm,remove-pe-dma-window(%x) %llx\n",
816                         np, ret, ddw_avail[DDW_REMOVE_PE_DMA_WIN], liobn);
817 }
818
819 static void remove_ddw(struct device_node *np, bool remove_prop)
820 {
821         struct property *win;
822         u32 ddw_avail[DDW_APPLICABLE_SIZE];
823         int ret = 0;
824
825         ret = of_property_read_u32_array(np, "ibm,ddw-applicable",
826                                          &ddw_avail[0], DDW_APPLICABLE_SIZE);
827         if (ret)
828                 return;
829
830         win = of_find_property(np, DIRECT64_PROPNAME, NULL);
831         if (!win)
832                 return;
833
834         if (win->length >= sizeof(struct dynamic_dma_window_prop))
835                 remove_dma_window(np, ddw_avail, win);
836
837         if (!remove_prop)
838                 return;
839
840         ret = of_remove_property(np, win);
841         if (ret)
842                 pr_warn("%pOF: failed to remove direct window property: %d\n",
843                         np, ret);
844 }
845
846 static u64 find_existing_ddw(struct device_node *pdn, int *window_shift)
847 {
848         struct direct_window *window;
849         const struct dynamic_dma_window_prop *direct64;
850         u64 dma_addr = 0;
851
852         spin_lock(&direct_window_list_lock);
853         /* check if we already created a window and dupe that config if so */
854         list_for_each_entry(window, &direct_window_list, list) {
855                 if (window->device == pdn) {
856                         direct64 = window->prop;
857                         dma_addr = be64_to_cpu(direct64->dma_base);
858                         *window_shift = be32_to_cpu(direct64->window_shift);
859                         break;
860                 }
861         }
862         spin_unlock(&direct_window_list_lock);
863
864         return dma_addr;
865 }
866
867 static int find_existing_ddw_windows(void)
868 {
869         int len;
870         struct device_node *pdn;
871         struct direct_window *window;
872         const struct dynamic_dma_window_prop *direct64;
873
874         if (!firmware_has_feature(FW_FEATURE_LPAR))
875                 return 0;
876
877         for_each_node_with_property(pdn, DIRECT64_PROPNAME) {
878                 direct64 = of_get_property(pdn, DIRECT64_PROPNAME, &len);
879                 if (!direct64)
880                         continue;
881
882                 window = kzalloc(sizeof(*window), GFP_KERNEL);
883                 if (!window || len < sizeof(struct dynamic_dma_window_prop)) {
884                         kfree(window);
885                         remove_ddw(pdn, true);
886                         continue;
887                 }
888
889                 window->device = pdn;
890                 window->prop = direct64;
891                 spin_lock(&direct_window_list_lock);
892                 list_add(&window->list, &direct_window_list);
893                 spin_unlock(&direct_window_list_lock);
894         }
895
896         return 0;
897 }
898 machine_arch_initcall(pseries, find_existing_ddw_windows);
899
900 /**
901  * ddw_read_ext - Get the value of an DDW extension
902  * @np:         device node from which the extension value is to be read.
903  * @extnum:     index number of the extension.
904  * @value:      pointer to return value, modified when extension is available.
905  *
906  * Checks if "ibm,ddw-extensions" exists for this node, and get the value
907  * on index 'extnum'.
908  * It can be used only to check if a property exists, passing value == NULL.
909  *
910  * Returns:
911  *      0 if extension successfully read
912  *      -EINVAL if the "ibm,ddw-extensions" does not exist,
913  *      -ENODATA if "ibm,ddw-extensions" does not have a value, and
914  *      -EOVERFLOW if "ibm,ddw-extensions" does not contain this extension.
915  */
916 static inline int ddw_read_ext(const struct device_node *np, int extnum,
917                                u32 *value)
918 {
919         static const char propname[] = "ibm,ddw-extensions";
920         u32 count;
921         int ret;
922
923         ret = of_property_read_u32_index(np, propname, DDW_EXT_SIZE, &count);
924         if (ret)
925                 return ret;
926
927         if (count < extnum)
928                 return -EOVERFLOW;
929
930         if (!value)
931                 value = &count;
932
933         return of_property_read_u32_index(np, propname, extnum, value);
934 }
935
936 static int query_ddw(struct pci_dev *dev, const u32 *ddw_avail,
937                      struct ddw_query_response *query,
938                      struct device_node *parent)
939 {
940         struct device_node *dn;
941         struct pci_dn *pdn;
942         u32 cfg_addr, ext_query, query_out[5];
943         u64 buid;
944         int ret, out_sz;
945
946         /*
947          * From LoPAR level 2.8, "ibm,ddw-extensions" index 3 can rule how many
948          * output parameters ibm,query-pe-dma-windows will have, ranging from
949          * 5 to 6.
950          */
951         ret = ddw_read_ext(parent, DDW_EXT_QUERY_OUT_SIZE, &ext_query);
952         if (!ret && ext_query == 1)
953                 out_sz = 6;
954         else
955                 out_sz = 5;
956
957         /*
958          * Get the config address and phb buid of the PE window.
959          * Rely on eeh to retrieve this for us.
960          * Retrieve them from the pci device, not the node with the
961          * dma-window property
962          */
963         dn = pci_device_to_OF_node(dev);
964         pdn = PCI_DN(dn);
965         buid = pdn->phb->buid;
966         cfg_addr = ((pdn->busno << 16) | (pdn->devfn << 8));
967
968         ret = rtas_call(ddw_avail[DDW_QUERY_PE_DMA_WIN], 3, out_sz, query_out,
969                         cfg_addr, BUID_HI(buid), BUID_LO(buid));
970         dev_info(&dev->dev, "ibm,query-pe-dma-windows(%x) %x %x %x returned %d\n",
971                  ddw_avail[DDW_QUERY_PE_DMA_WIN], cfg_addr, BUID_HI(buid),
972                  BUID_LO(buid), ret);
973
974         switch (out_sz) {
975         case 5:
976                 query->windows_available = query_out[0];
977                 query->largest_available_block = query_out[1];
978                 query->page_size = query_out[2];
979                 query->migration_capable = query_out[3];
980                 break;
981         case 6:
982                 query->windows_available = query_out[0];
983                 query->largest_available_block = ((u64)query_out[1] << 32) |
984                                                  query_out[2];
985                 query->page_size = query_out[3];
986                 query->migration_capable = query_out[4];
987                 break;
988         }
989
990         return ret;
991 }
992
993 static int create_ddw(struct pci_dev *dev, const u32 *ddw_avail,
994                         struct ddw_create_response *create, int page_shift,
995                         int window_shift)
996 {
997         struct device_node *dn;
998         struct pci_dn *pdn;
999         u32 cfg_addr;
1000         u64 buid;
1001         int ret;
1002
1003         /*
1004          * Get the config address and phb buid of the PE window.
1005          * Rely on eeh to retrieve this for us.
1006          * Retrieve them from the pci device, not the node with the
1007          * dma-window property
1008          */
1009         dn = pci_device_to_OF_node(dev);
1010         pdn = PCI_DN(dn);
1011         buid = pdn->phb->buid;
1012         cfg_addr = ((pdn->busno << 16) | (pdn->devfn << 8));
1013
1014         do {
1015                 /* extra outputs are LIOBN and dma-addr (hi, lo) */
1016                 ret = rtas_call(ddw_avail[DDW_CREATE_PE_DMA_WIN], 5, 4,
1017                                 (u32 *)create, cfg_addr, BUID_HI(buid),
1018                                 BUID_LO(buid), page_shift, window_shift);
1019         } while (rtas_busy_delay(ret));
1020         dev_info(&dev->dev,
1021                 "ibm,create-pe-dma-window(%x) %x %x %x %x %x returned %d "
1022                 "(liobn = 0x%x starting addr = %x %x)\n",
1023                  ddw_avail[DDW_CREATE_PE_DMA_WIN], cfg_addr, BUID_HI(buid),
1024                  BUID_LO(buid), page_shift, window_shift, ret, create->liobn,
1025                  create->addr_hi, create->addr_lo);
1026
1027         return ret;
1028 }
1029
1030 struct failed_ddw_pdn {
1031         struct device_node *pdn;
1032         struct list_head list;
1033 };
1034
1035 static LIST_HEAD(failed_ddw_pdn_list);
1036
1037 static phys_addr_t ddw_memory_hotplug_max(void)
1038 {
1039         phys_addr_t max_addr = memory_hotplug_max();
1040         struct device_node *memory;
1041
1042         /*
1043          * The "ibm,pmemory" can appear anywhere in the address space.
1044          * Assuming it is still backed by page structs, set the upper limit
1045          * for the huge DMA window as MAX_PHYSMEM_BITS.
1046          */
1047         if (of_find_node_by_type(NULL, "ibm,pmemory"))
1048                 return (sizeof(phys_addr_t) * 8 <= MAX_PHYSMEM_BITS) ?
1049                         (phys_addr_t) -1 : (1ULL << MAX_PHYSMEM_BITS);
1050
1051         for_each_node_by_type(memory, "memory") {
1052                 unsigned long start, size;
1053                 int n_mem_addr_cells, n_mem_size_cells, len;
1054                 const __be32 *memcell_buf;
1055
1056                 memcell_buf = of_get_property(memory, "reg", &len);
1057                 if (!memcell_buf || len <= 0)
1058                         continue;
1059
1060                 n_mem_addr_cells = of_n_addr_cells(memory);
1061                 n_mem_size_cells = of_n_size_cells(memory);
1062
1063                 start = of_read_number(memcell_buf, n_mem_addr_cells);
1064                 memcell_buf += n_mem_addr_cells;
1065                 size = of_read_number(memcell_buf, n_mem_size_cells);
1066                 memcell_buf += n_mem_size_cells;
1067
1068                 max_addr = max_t(phys_addr_t, max_addr, start + size);
1069         }
1070
1071         return max_addr;
1072 }
1073
1074 /*
1075  * Platforms supporting the DDW option starting with LoPAR level 2.7 implement
1076  * ibm,ddw-extensions, which carries the rtas token for
1077  * ibm,reset-pe-dma-windows.
1078  * That rtas-call can be used to restore the default DMA window for the device.
1079  */
1080 static void reset_dma_window(struct pci_dev *dev, struct device_node *par_dn)
1081 {
1082         int ret;
1083         u32 cfg_addr, reset_dma_win;
1084         u64 buid;
1085         struct device_node *dn;
1086         struct pci_dn *pdn;
1087
1088         ret = ddw_read_ext(par_dn, DDW_EXT_RESET_DMA_WIN, &reset_dma_win);
1089         if (ret)
1090                 return;
1091
1092         dn = pci_device_to_OF_node(dev);
1093         pdn = PCI_DN(dn);
1094         buid = pdn->phb->buid;
1095         cfg_addr = (pdn->busno << 16) | (pdn->devfn << 8);
1096
1097         ret = rtas_call(reset_dma_win, 3, 1, NULL, cfg_addr, BUID_HI(buid),
1098                         BUID_LO(buid));
1099         if (ret)
1100                 dev_info(&dev->dev,
1101                          "ibm,reset-pe-dma-windows(%x) %x %x %x returned %d ",
1102                          reset_dma_win, cfg_addr, BUID_HI(buid), BUID_LO(buid),
1103                          ret);
1104 }
1105
1106 /* Return largest page shift based on "IO Page Sizes" output of ibm,query-pe-dma-window. */
1107 static int iommu_get_page_shift(u32 query_page_size)
1108 {
1109         /* Supported IO page-sizes according to LoPAR */
1110         const int shift[] = {
1111                 __builtin_ctzll(SZ_4K),   __builtin_ctzll(SZ_64K), __builtin_ctzll(SZ_16M),
1112                 __builtin_ctzll(SZ_32M),  __builtin_ctzll(SZ_64M), __builtin_ctzll(SZ_128M),
1113                 __builtin_ctzll(SZ_256M), __builtin_ctzll(SZ_16G)
1114         };
1115
1116         int i = ARRAY_SIZE(shift) - 1;
1117
1118         /*
1119          * On LoPAR, ibm,query-pe-dma-window outputs "IO Page Sizes" using a bit field:
1120          * - bit 31 means 4k pages are supported,
1121          * - bit 30 means 64k pages are supported, and so on.
1122          * Larger pagesizes map more memory with the same amount of TCEs, so start probing them.
1123          */
1124         for (; i >= 0 ; i--) {
1125                 if (query_page_size & (1 << i))
1126                         return shift[i];
1127         }
1128
1129         /* No valid page size found. */
1130         return 0;
1131 }
1132
1133 /*
1134  * If the PE supports dynamic dma windows, and there is space for a table
1135  * that can map all pages in a linear offset, then setup such a table,
1136  * and record the dma-offset in the struct device.
1137  *
1138  * dev: the pci device we are checking
1139  * pdn: the parent pe node with the ibm,dma_window property
1140  * Future: also check if we can remap the base window for our base page size
1141  *
1142  * returns the dma offset for use by the direct mapped DMA code.
1143  */
1144 static u64 enable_ddw(struct pci_dev *dev, struct device_node *pdn)
1145 {
1146         int len = 0, ret;
1147         int max_ram_len = order_base_2(ddw_memory_hotplug_max());
1148         struct ddw_query_response query;
1149         struct ddw_create_response create;
1150         int page_shift;
1151         u64 dma_addr;
1152         struct device_node *dn;
1153         u32 ddw_avail[DDW_APPLICABLE_SIZE];
1154         struct direct_window *window;
1155         struct property *win64;
1156         struct dynamic_dma_window_prop *ddwprop;
1157         struct failed_ddw_pdn *fpdn;
1158         bool default_win_removed = false;
1159         bool pmem_present;
1160
1161         dn = of_find_node_by_type(NULL, "ibm,pmemory");
1162         pmem_present = dn != NULL;
1163         of_node_put(dn);
1164
1165         mutex_lock(&direct_window_init_mutex);
1166
1167         dma_addr = find_existing_ddw(pdn, &len);
1168         if (dma_addr != 0)
1169                 goto out_unlock;
1170
1171         /*
1172          * If we already went through this for a previous function of
1173          * the same device and failed, we don't want to muck with the
1174          * DMA window again, as it will race with in-flight operations
1175          * and can lead to EEHs. The above mutex protects access to the
1176          * list.
1177          */
1178         list_for_each_entry(fpdn, &failed_ddw_pdn_list, list) {
1179                 if (fpdn->pdn == pdn)
1180                         goto out_unlock;
1181         }
1182
1183         /*
1184          * the ibm,ddw-applicable property holds the tokens for:
1185          * ibm,query-pe-dma-window
1186          * ibm,create-pe-dma-window
1187          * ibm,remove-pe-dma-window
1188          * for the given node in that order.
1189          * the property is actually in the parent, not the PE
1190          */
1191         ret = of_property_read_u32_array(pdn, "ibm,ddw-applicable",
1192                                          &ddw_avail[0], DDW_APPLICABLE_SIZE);
1193         if (ret)
1194                 goto out_failed;
1195
1196        /*
1197          * Query if there is a second window of size to map the
1198          * whole partition.  Query returns number of windows, largest
1199          * block assigned to PE (partition endpoint), and two bitmasks
1200          * of page sizes: supported and supported for migrate-dma.
1201          */
1202         dn = pci_device_to_OF_node(dev);
1203         ret = query_ddw(dev, ddw_avail, &query, pdn);
1204         if (ret != 0)
1205                 goto out_failed;
1206
1207         /*
1208          * If there is no window available, remove the default DMA window,
1209          * if it's present. This will make all the resources available to the
1210          * new DDW window.
1211          * If anything fails after this, we need to restore it, so also check
1212          * for extensions presence.
1213          */
1214         if (query.windows_available == 0) {
1215                 struct property *default_win;
1216                 int reset_win_ext;
1217
1218                 default_win = of_find_property(pdn, "ibm,dma-window", NULL);
1219                 if (!default_win)
1220                         goto out_failed;
1221
1222                 reset_win_ext = ddw_read_ext(pdn, DDW_EXT_RESET_DMA_WIN, NULL);
1223                 if (reset_win_ext)
1224                         goto out_failed;
1225
1226                 remove_dma_window(pdn, ddw_avail, default_win);
1227                 default_win_removed = true;
1228
1229                 /* Query again, to check if the window is available */
1230                 ret = query_ddw(dev, ddw_avail, &query, pdn);
1231                 if (ret != 0)
1232                         goto out_failed;
1233
1234                 if (query.windows_available == 0) {
1235                         /* no windows are available for this device. */
1236                         dev_dbg(&dev->dev, "no free dynamic windows");
1237                         goto out_failed;
1238                 }
1239         }
1240
1241         page_shift = iommu_get_page_shift(query.page_size);
1242         if (!page_shift) {
1243                 dev_dbg(&dev->dev, "no supported direct page size in mask %x",
1244                           query.page_size);
1245                 goto out_failed;
1246         }
1247         /* verify the window * number of ptes will map the partition */
1248         /* check largest block * page size > max memory hotplug addr */
1249         /*
1250          * The "ibm,pmemory" can appear anywhere in the address space.
1251          * Assuming it is still backed by page structs, try MAX_PHYSMEM_BITS
1252          * for the upper limit and fallback to max RAM otherwise but this
1253          * disables device::dma_ops_bypass.
1254          */
1255         len = max_ram_len;
1256         if (pmem_present) {
1257                 if (query.largest_available_block >=
1258                     (1ULL << (MAX_PHYSMEM_BITS - page_shift)))
1259                         len = MAX_PHYSMEM_BITS;
1260                 else
1261                         dev_info(&dev->dev, "Skipping ibm,pmemory");
1262         }
1263
1264         if (query.largest_available_block < (1ULL << (len - page_shift))) {
1265                 dev_dbg(&dev->dev,
1266                         "can't map partition max 0x%llx with %llu %llu-sized pages\n",
1267                         1ULL << len,
1268                         query.largest_available_block,
1269                         1ULL << page_shift);
1270                 goto out_failed;
1271         }
1272         win64 = kzalloc(sizeof(struct property), GFP_KERNEL);
1273         if (!win64) {
1274                 dev_info(&dev->dev,
1275                         "couldn't allocate property for 64bit dma window\n");
1276                 goto out_failed;
1277         }
1278         win64->name = kstrdup(DIRECT64_PROPNAME, GFP_KERNEL);
1279         win64->value = ddwprop = kmalloc(sizeof(*ddwprop), GFP_KERNEL);
1280         win64->length = sizeof(*ddwprop);
1281         if (!win64->name || !win64->value) {
1282                 dev_info(&dev->dev,
1283                         "couldn't allocate property name and value\n");
1284                 goto out_free_prop;
1285         }
1286
1287         ret = create_ddw(dev, ddw_avail, &create, page_shift, len);
1288         if (ret != 0)
1289                 goto out_free_prop;
1290
1291         ddwprop->liobn = cpu_to_be32(create.liobn);
1292         ddwprop->dma_base = cpu_to_be64(((u64)create.addr_hi << 32) |
1293                         create.addr_lo);
1294         ddwprop->tce_shift = cpu_to_be32(page_shift);
1295         ddwprop->window_shift = cpu_to_be32(len);
1296
1297         dev_dbg(&dev->dev, "created tce table LIOBN 0x%x for %pOF\n",
1298                   create.liobn, dn);
1299
1300         window = kzalloc(sizeof(*window), GFP_KERNEL);
1301         if (!window)
1302                 goto out_clear_window;
1303
1304         ret = walk_system_ram_range(0, memblock_end_of_DRAM() >> PAGE_SHIFT,
1305                         win64->value, tce_setrange_multi_pSeriesLP_walk);
1306         if (ret) {
1307                 dev_info(&dev->dev, "failed to map direct window for %pOF: %d\n",
1308                          dn, ret);
1309                 goto out_free_window;
1310         }
1311
1312         ret = of_add_property(pdn, win64);
1313         if (ret) {
1314                 dev_err(&dev->dev, "unable to add dma window property for %pOF: %d",
1315                          pdn, ret);
1316                 goto out_free_window;
1317         }
1318
1319         window->device = pdn;
1320         window->prop = ddwprop;
1321         spin_lock(&direct_window_list_lock);
1322         list_add(&window->list, &direct_window_list);
1323         spin_unlock(&direct_window_list_lock);
1324
1325         dma_addr = be64_to_cpu(ddwprop->dma_base);
1326         goto out_unlock;
1327
1328 out_free_window:
1329         kfree(window);
1330
1331 out_clear_window:
1332         remove_ddw(pdn, true);
1333
1334 out_free_prop:
1335         kfree(win64->name);
1336         kfree(win64->value);
1337         kfree(win64);
1338
1339 out_failed:
1340         if (default_win_removed)
1341                 reset_dma_window(dev, pdn);
1342
1343         fpdn = kzalloc(sizeof(*fpdn), GFP_KERNEL);
1344         if (!fpdn)
1345                 goto out_unlock;
1346         fpdn->pdn = pdn;
1347         list_add(&fpdn->list, &failed_ddw_pdn_list);
1348
1349 out_unlock:
1350         mutex_unlock(&direct_window_init_mutex);
1351
1352         /*
1353          * If we have persistent memory and the window size is only as big
1354          * as RAM, then we failed to create a window to cover persistent
1355          * memory and need to set the DMA limit.
1356          */
1357         if (pmem_present && dma_addr && (len == max_ram_len))
1358                 dev->dev.bus_dma_limit = dma_addr + (1ULL << len);
1359
1360         return dma_addr;
1361 }
1362
1363 static void pci_dma_dev_setup_pSeriesLP(struct pci_dev *dev)
1364 {
1365         struct device_node *pdn, *dn;
1366         struct iommu_table *tbl;
1367         const __be32 *dma_window = NULL;
1368         struct pci_dn *pci;
1369
1370         pr_debug("pci_dma_dev_setup_pSeriesLP: %s\n", pci_name(dev));
1371
1372         /* dev setup for LPAR is a little tricky, since the device tree might
1373          * contain the dma-window properties per-device and not necessarily
1374          * for the bus. So we need to search upwards in the tree until we
1375          * either hit a dma-window property, OR find a parent with a table
1376          * already allocated.
1377          */
1378         dn = pci_device_to_OF_node(dev);
1379         pr_debug("  node is %pOF\n", dn);
1380
1381         for (pdn = dn; pdn && PCI_DN(pdn) && !PCI_DN(pdn)->table_group;
1382              pdn = pdn->parent) {
1383                 dma_window = of_get_property(pdn, "ibm,dma-window", NULL);
1384                 if (dma_window)
1385                         break;
1386         }
1387
1388         if (!pdn || !PCI_DN(pdn)) {
1389                 printk(KERN_WARNING "pci_dma_dev_setup_pSeriesLP: "
1390                        "no DMA window found for pci dev=%s dn=%pOF\n",
1391                                  pci_name(dev), dn);
1392                 return;
1393         }
1394         pr_debug("  parent is %pOF\n", pdn);
1395
1396         pci = PCI_DN(pdn);
1397         if (!pci->table_group) {
1398                 pci->table_group = iommu_pseries_alloc_group(pci->phb->node);
1399                 tbl = pci->table_group->tables[0];
1400                 iommu_table_setparms_lpar(pci->phb, pdn, tbl,
1401                                 pci->table_group, dma_window);
1402                 tbl->it_ops = &iommu_table_lpar_multi_ops;
1403                 iommu_init_table(tbl, pci->phb->node, 0, 0);
1404                 iommu_register_group(pci->table_group,
1405                                 pci_domain_nr(pci->phb->bus), 0);
1406                 pr_debug("  created table: %p\n", pci->table_group);
1407         } else {
1408                 pr_debug("  found DMA window, table: %p\n", pci->table_group);
1409         }
1410
1411         set_iommu_table_base(&dev->dev, pci->table_group->tables[0]);
1412         iommu_add_device(pci->table_group, &dev->dev);
1413 }
1414
1415 static bool iommu_bypass_supported_pSeriesLP(struct pci_dev *pdev, u64 dma_mask)
1416 {
1417         struct device_node *dn = pci_device_to_OF_node(pdev), *pdn;
1418         const __be32 *dma_window = NULL;
1419
1420         /* only attempt to use a new window if 64-bit DMA is requested */
1421         if (dma_mask < DMA_BIT_MASK(64))
1422                 return false;
1423
1424         dev_dbg(&pdev->dev, "node is %pOF\n", dn);
1425
1426         /*
1427          * the device tree might contain the dma-window properties
1428          * per-device and not necessarily for the bus. So we need to
1429          * search upwards in the tree until we either hit a dma-window
1430          * property, OR find a parent with a table already allocated.
1431          */
1432         for (pdn = dn; pdn && PCI_DN(pdn) && !PCI_DN(pdn)->table_group;
1433                         pdn = pdn->parent) {
1434                 dma_window = of_get_property(pdn, "ibm,dma-window", NULL);
1435                 if (dma_window)
1436                         break;
1437         }
1438
1439         if (pdn && PCI_DN(pdn)) {
1440                 pdev->dev.archdata.dma_offset = enable_ddw(pdev, pdn);
1441                 if (pdev->dev.archdata.dma_offset)
1442                         return true;
1443         }
1444
1445         return false;
1446 }
1447
1448 static int iommu_mem_notifier(struct notifier_block *nb, unsigned long action,
1449                 void *data)
1450 {
1451         struct direct_window *window;
1452         struct memory_notify *arg = data;
1453         int ret = 0;
1454
1455         switch (action) {
1456         case MEM_GOING_ONLINE:
1457                 spin_lock(&direct_window_list_lock);
1458                 list_for_each_entry(window, &direct_window_list, list) {
1459                         ret |= tce_setrange_multi_pSeriesLP(arg->start_pfn,
1460                                         arg->nr_pages, window->prop);
1461                         /* XXX log error */
1462                 }
1463                 spin_unlock(&direct_window_list_lock);
1464                 break;
1465         case MEM_CANCEL_ONLINE:
1466         case MEM_OFFLINE:
1467                 spin_lock(&direct_window_list_lock);
1468                 list_for_each_entry(window, &direct_window_list, list) {
1469                         ret |= tce_clearrange_multi_pSeriesLP(arg->start_pfn,
1470                                         arg->nr_pages, window->prop);
1471                         /* XXX log error */
1472                 }
1473                 spin_unlock(&direct_window_list_lock);
1474                 break;
1475         default:
1476                 break;
1477         }
1478         if (ret && action != MEM_CANCEL_ONLINE)
1479                 return NOTIFY_BAD;
1480
1481         return NOTIFY_OK;
1482 }
1483
1484 static struct notifier_block iommu_mem_nb = {
1485         .notifier_call = iommu_mem_notifier,
1486 };
1487
1488 static int iommu_reconfig_notifier(struct notifier_block *nb, unsigned long action, void *data)
1489 {
1490         int err = NOTIFY_OK;
1491         struct of_reconfig_data *rd = data;
1492         struct device_node *np = rd->dn;
1493         struct pci_dn *pci = PCI_DN(np);
1494         struct direct_window *window;
1495
1496         switch (action) {
1497         case OF_RECONFIG_DETACH_NODE:
1498                 /*
1499                  * Removing the property will invoke the reconfig
1500                  * notifier again, which causes dead-lock on the
1501                  * read-write semaphore of the notifier chain. So
1502                  * we have to remove the property when releasing
1503                  * the device node.
1504                  */
1505                 remove_ddw(np, false);
1506                 if (pci && pci->table_group)
1507                         iommu_pseries_free_group(pci->table_group,
1508                                         np->full_name);
1509
1510                 spin_lock(&direct_window_list_lock);
1511                 list_for_each_entry(window, &direct_window_list, list) {
1512                         if (window->device == np) {
1513                                 list_del(&window->list);
1514                                 kfree(window);
1515                                 break;
1516                         }
1517                 }
1518                 spin_unlock(&direct_window_list_lock);
1519                 break;
1520         default:
1521                 err = NOTIFY_DONE;
1522                 break;
1523         }
1524         return err;
1525 }
1526
1527 static struct notifier_block iommu_reconfig_nb = {
1528         .notifier_call = iommu_reconfig_notifier,
1529 };
1530
1531 /* These are called very early. */
1532 void iommu_init_early_pSeries(void)
1533 {
1534         if (of_chosen && of_get_property(of_chosen, "linux,iommu-off", NULL))
1535                 return;
1536
1537         if (firmware_has_feature(FW_FEATURE_LPAR)) {
1538                 pseries_pci_controller_ops.dma_bus_setup = pci_dma_bus_setup_pSeriesLP;
1539                 pseries_pci_controller_ops.dma_dev_setup = pci_dma_dev_setup_pSeriesLP;
1540                 if (!disable_ddw)
1541                         pseries_pci_controller_ops.iommu_bypass_supported =
1542                                 iommu_bypass_supported_pSeriesLP;
1543         } else {
1544                 pseries_pci_controller_ops.dma_bus_setup = pci_dma_bus_setup_pSeries;
1545                 pseries_pci_controller_ops.dma_dev_setup = pci_dma_dev_setup_pSeries;
1546         }
1547
1548
1549         of_reconfig_notifier_register(&iommu_reconfig_nb);
1550         register_memory_notifier(&iommu_mem_nb);
1551
1552         set_pci_dma_ops(&dma_iommu_ops);
1553 }
1554
1555 static int __init disable_multitce(char *str)
1556 {
1557         if (strcmp(str, "off") == 0 &&
1558             firmware_has_feature(FW_FEATURE_LPAR) &&
1559             (firmware_has_feature(FW_FEATURE_PUT_TCE_IND) ||
1560              firmware_has_feature(FW_FEATURE_STUFF_TCE))) {
1561                 printk(KERN_INFO "Disabling MULTITCE firmware feature\n");
1562                 powerpc_firmware_features &=
1563                         ~(FW_FEATURE_PUT_TCE_IND | FW_FEATURE_STUFF_TCE);
1564         }
1565         return 1;
1566 }
1567
1568 __setup("multitce=", disable_multitce);
1569
1570 static int tce_iommu_bus_notifier(struct notifier_block *nb,
1571                 unsigned long action, void *data)
1572 {
1573         struct device *dev = data;
1574
1575         switch (action) {
1576         case BUS_NOTIFY_DEL_DEVICE:
1577                 iommu_del_device(dev);
1578                 return 0;
1579         default:
1580                 return 0;
1581         }
1582 }
1583
1584 static struct notifier_block tce_iommu_bus_nb = {
1585         .notifier_call = tce_iommu_bus_notifier,
1586 };
1587
1588 static int __init tce_iommu_bus_notifier_init(void)
1589 {
1590         bus_register_notifier(&pci_bus_type, &tce_iommu_bus_nb);
1591         return 0;
1592 }
1593 machine_subsys_initcall_sync(pseries, tce_iommu_bus_notifier_init);