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