xref: /linux/arch/powerpc/platforms/pseries/iommu.c (revision 3a2c4d55e32ad65efebdb6de44eef3bfa08bb49d)
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/vmalloc.h>
25 #include <linux/of.h>
26 #include <linux/of_address.h>
27 #include <linux/iommu.h>
28 #include <linux/rculist.h>
29 #include <asm/io.h>
30 #include <asm/prom.h>
31 #include <asm/rtas.h>
32 #include <asm/iommu.h>
33 #include <asm/pci-bridge.h>
34 #include <asm/machdep.h>
35 #include <asm/firmware.h>
36 #include <asm/tce.h>
37 #include <asm/ppc-pci.h>
38 #include <asm/udbg.h>
39 #include <asm/mmzone.h>
40 #include <asm/plpar_wrappers.h>
41 
42 #include "pseries.h"
43 
44 enum {
45 	DDW_QUERY_PE_DMA_WIN  = 0,
46 	DDW_CREATE_PE_DMA_WIN = 1,
47 	DDW_REMOVE_PE_DMA_WIN = 2,
48 
49 	DDW_APPLICABLE_SIZE
50 };
51 
52 enum {
53 	DDW_EXT_SIZE = 0,
54 	DDW_EXT_RESET_DMA_WIN = 1,
55 	DDW_EXT_QUERY_OUT_SIZE = 2,
56 	DDW_EXT_LIMITED_ADDR_MODE = 3
57 };
58 
59 static struct iommu_table *iommu_pseries_alloc_table(int node)
60 {
61 	struct iommu_table *tbl;
62 
63 	tbl = kzalloc_node(sizeof(struct iommu_table), GFP_KERNEL, node);
64 	if (!tbl)
65 		return NULL;
66 
67 	INIT_LIST_HEAD_RCU(&tbl->it_group_list);
68 	kref_init(&tbl->it_kref);
69 	return tbl;
70 }
71 
72 #ifdef CONFIG_IOMMU_API
73 static struct iommu_table_group_ops spapr_tce_table_group_ops;
74 #endif
75 
76 static struct iommu_table_group *iommu_pseries_alloc_group(int node)
77 {
78 	struct iommu_table_group *table_group;
79 
80 	table_group = kzalloc_node(sizeof(*table_group), GFP_KERNEL, node);
81 	if (!table_group)
82 		return NULL;
83 
84 #ifdef CONFIG_IOMMU_API
85 	table_group->ops = &spapr_tce_table_group_ops;
86 	table_group->pgsizes = SZ_4K;
87 #endif
88 
89 	table_group->tables[0] = iommu_pseries_alloc_table(node);
90 	if (table_group->tables[0])
91 		return table_group;
92 
93 	kfree(table_group);
94 	return NULL;
95 }
96 
97 static void iommu_pseries_free_group(struct iommu_table_group *table_group,
98 		const char *node_name)
99 {
100 	if (!table_group)
101 		return;
102 
103 #ifdef CONFIG_IOMMU_API
104 	if (table_group->group) {
105 		iommu_group_put(table_group->group);
106 		BUG_ON(table_group->group);
107 	}
108 #endif
109 
110 	/* Default DMA window table is at index 0, while DDW at 1. SR-IOV
111 	 * adapters only have table on index 0(if not direct mapped).
112 	 */
113 	if (table_group->tables[0])
114 		iommu_tce_table_put(table_group->tables[0]);
115 
116 	if (table_group->tables[1])
117 		iommu_tce_table_put(table_group->tables[1]);
118 
119 	kfree(table_group);
120 }
121 
122 static int tce_build_pSeries(struct iommu_table *tbl, long index,
123 			      long npages, unsigned long uaddr,
124 			      enum dma_data_direction direction,
125 			      unsigned long attrs)
126 {
127 	u64 proto_tce;
128 	__be64 *tcep;
129 	u64 rpn;
130 	const unsigned long tceshift = tbl->it_page_shift;
131 	const unsigned long pagesize = IOMMU_PAGE_SIZE(tbl);
132 
133 	proto_tce = TCE_PCI_READ; // Read allowed
134 
135 	if (direction != DMA_TO_DEVICE)
136 		proto_tce |= TCE_PCI_WRITE;
137 
138 	tcep = ((__be64 *)tbl->it_base) + index;
139 
140 	while (npages--) {
141 		/* can't move this out since we might cross MEMBLOCK boundary */
142 		rpn = __pa(uaddr) >> tceshift;
143 		*tcep = cpu_to_be64(proto_tce | rpn << tceshift);
144 
145 		uaddr += pagesize;
146 		tcep++;
147 	}
148 	return 0;
149 }
150 
151 
152 static void tce_clear_pSeries(struct iommu_table *tbl, long index, long npages)
153 {
154 	__be64 *tcep;
155 
156 	tcep = ((__be64 *)tbl->it_base) + index;
157 
158 	while (npages--)
159 		*(tcep++) = 0;
160 }
161 
162 static unsigned long tce_get_pseries(struct iommu_table *tbl, long index)
163 {
164 	__be64 *tcep;
165 
166 	tcep = ((__be64 *)tbl->it_base) + index;
167 
168 	return be64_to_cpu(*tcep);
169 }
170 
171 #ifdef CONFIG_IOMMU_API
172 static long pseries_tce_iommu_userspace_view_alloc(struct iommu_table *tbl)
173 {
174 	unsigned long cb = ALIGN(sizeof(tbl->it_userspace[0]) * tbl->it_size, PAGE_SIZE);
175 	unsigned long *uas;
176 
177 	if (tbl->it_indirect_levels) /* Impossible */
178 		return -EPERM;
179 
180 	WARN_ON(tbl->it_userspace);
181 
182 	uas = vzalloc(cb);
183 	if (!uas)
184 		return -ENOMEM;
185 
186 	tbl->it_userspace = (__be64 *) uas;
187 
188 	return 0;
189 }
190 #endif
191 
192 static void tce_iommu_userspace_view_free(struct iommu_table *tbl)
193 {
194 	vfree(tbl->it_userspace);
195 	tbl->it_userspace = NULL;
196 }
197 
198 static void tce_free_pSeries(struct iommu_table *tbl)
199 {
200 	if (tbl->it_userspace)
201 		tce_iommu_userspace_view_free(tbl);
202 }
203 
204 static void tce_free_pSeriesLP(unsigned long liobn, long, long, long);
205 static void tce_freemulti_pSeriesLP(struct iommu_table*, long, long);
206 
207 static int tce_build_pSeriesLP(unsigned long liobn, long tcenum, long tceshift,
208 				long npages, unsigned long uaddr,
209 				enum dma_data_direction direction,
210 				unsigned long attrs)
211 {
212 	u64 rc = 0;
213 	u64 proto_tce, tce;
214 	u64 rpn;
215 	int ret = 0;
216 	long tcenum_start = tcenum, npages_start = npages;
217 
218 	rpn = __pa(uaddr) >> tceshift;
219 	proto_tce = TCE_PCI_READ;
220 	if (direction != DMA_TO_DEVICE)
221 		proto_tce |= TCE_PCI_WRITE;
222 
223 	while (npages--) {
224 		tce = proto_tce | rpn << tceshift;
225 		rc = plpar_tce_put((u64)liobn, (u64)tcenum << tceshift, tce);
226 
227 		if (unlikely(rc == H_NOT_ENOUGH_RESOURCES)) {
228 			ret = (int)rc;
229 			tce_free_pSeriesLP(liobn, tcenum_start, tceshift,
230 			                   (npages_start - (npages + 1)));
231 			break;
232 		}
233 
234 		if (rc && printk_ratelimit()) {
235 			printk("tce_build_pSeriesLP: plpar_tce_put failed. rc=%lld\n", rc);
236 			printk("\tindex   = 0x%llx\n", (u64)liobn);
237 			printk("\ttcenum  = 0x%llx\n", (u64)tcenum);
238 			printk("\ttce val = 0x%llx\n", tce );
239 			dump_stack();
240 		}
241 
242 		tcenum++;
243 		rpn++;
244 	}
245 	return ret;
246 }
247 
248 static DEFINE_PER_CPU(__be64 *, tce_page);
249 
250 static int tce_buildmulti_pSeriesLP(struct iommu_table *tbl, long tcenum,
251 				     long npages, unsigned long uaddr,
252 				     enum dma_data_direction direction,
253 				     unsigned long attrs)
254 {
255 	u64 rc = 0;
256 	u64 proto_tce;
257 	__be64 *tcep;
258 	u64 rpn;
259 	long l, limit;
260 	long tcenum_start = tcenum, npages_start = npages;
261 	int ret = 0;
262 	unsigned long flags;
263 	const unsigned long tceshift = tbl->it_page_shift;
264 
265 	if ((npages == 1) || !firmware_has_feature(FW_FEATURE_PUT_TCE_IND)) {
266 		return tce_build_pSeriesLP(tbl->it_index, tcenum,
267 					   tceshift, npages, uaddr,
268 		                           direction, attrs);
269 	}
270 
271 	local_irq_save(flags);	/* to protect tcep and the page behind it */
272 
273 	tcep = __this_cpu_read(tce_page);
274 
275 	/* This is safe to do since interrupts are off when we're called
276 	 * from iommu_alloc{,_sg}()
277 	 */
278 	if (!tcep) {
279 		tcep = (__be64 *)__get_free_page(GFP_ATOMIC);
280 		/* If allocation fails, fall back to the loop implementation */
281 		if (!tcep) {
282 			local_irq_restore(flags);
283 			return tce_build_pSeriesLP(tbl->it_index, tcenum,
284 					tceshift,
285 					npages, uaddr, direction, attrs);
286 		}
287 		__this_cpu_write(tce_page, tcep);
288 	}
289 
290 	rpn = __pa(uaddr) >> tceshift;
291 	proto_tce = TCE_PCI_READ;
292 	if (direction != DMA_TO_DEVICE)
293 		proto_tce |= TCE_PCI_WRITE;
294 
295 	/* We can map max one pageful of TCEs at a time */
296 	do {
297 		/*
298 		 * Set up the page with TCE data, looping through and setting
299 		 * the values.
300 		 */
301 		limit = min_t(long, npages, 4096 / TCE_ENTRY_SIZE);
302 
303 		for (l = 0; l < limit; l++) {
304 			tcep[l] = cpu_to_be64(proto_tce | rpn << tceshift);
305 			rpn++;
306 		}
307 
308 		rc = plpar_tce_put_indirect((u64)tbl->it_index,
309 					    (u64)tcenum << tceshift,
310 					    (u64)__pa(tcep),
311 					    limit);
312 
313 		npages -= limit;
314 		tcenum += limit;
315 	} while (npages > 0 && !rc);
316 
317 	local_irq_restore(flags);
318 
319 	if (unlikely(rc == H_NOT_ENOUGH_RESOURCES)) {
320 		ret = (int)rc;
321 		tce_freemulti_pSeriesLP(tbl, tcenum_start,
322 		                        (npages_start - (npages + limit)));
323 		return ret;
324 	}
325 
326 	if (rc && printk_ratelimit()) {
327 		printk("tce_buildmulti_pSeriesLP: plpar_tce_put failed. rc=%lld\n", rc);
328 		printk("\tindex   = 0x%llx\n", (u64)tbl->it_index);
329 		printk("\tnpages  = 0x%llx\n", (u64)npages);
330 		printk("\ttce[0] val = 0x%llx\n", tcep[0]);
331 		dump_stack();
332 	}
333 	return ret;
334 }
335 
336 static void tce_free_pSeriesLP(unsigned long liobn, long tcenum, long tceshift,
337 			       long npages)
338 {
339 	u64 rc;
340 
341 	while (npages--) {
342 		rc = plpar_tce_put((u64)liobn, (u64)tcenum << tceshift, 0);
343 
344 		if (rc && printk_ratelimit()) {
345 			printk("tce_free_pSeriesLP: plpar_tce_put failed. rc=%lld\n", rc);
346 			printk("\tindex   = 0x%llx\n", (u64)liobn);
347 			printk("\ttcenum  = 0x%llx\n", (u64)tcenum);
348 			dump_stack();
349 		}
350 
351 		tcenum++;
352 	}
353 }
354 
355 
356 static void tce_freemulti_pSeriesLP(struct iommu_table *tbl, long tcenum, long npages)
357 {
358 	u64 rc;
359 	long rpages = npages;
360 	unsigned long limit;
361 
362 	if (!firmware_has_feature(FW_FEATURE_STUFF_TCE))
363 		return tce_free_pSeriesLP(tbl->it_index, tcenum,
364 					  tbl->it_page_shift, npages);
365 
366 	do {
367 		limit = min_t(unsigned long, rpages, 512);
368 
369 		rc = plpar_tce_stuff((u64)tbl->it_index,
370 				     (u64)tcenum << tbl->it_page_shift, 0, limit);
371 
372 		rpages -= limit;
373 		tcenum += limit;
374 	} while (rpages > 0 && !rc);
375 
376 	if (rc && printk_ratelimit()) {
377 		printk("tce_freemulti_pSeriesLP: plpar_tce_stuff failed\n");
378 		printk("\trc      = %lld\n", rc);
379 		printk("\tindex   = 0x%llx\n", (u64)tbl->it_index);
380 		printk("\tnpages  = 0x%llx\n", (u64)npages);
381 		dump_stack();
382 	}
383 }
384 
385 static unsigned long tce_get_pSeriesLP(struct iommu_table *tbl, long tcenum)
386 {
387 	u64 rc;
388 	unsigned long tce_ret;
389 
390 	rc = plpar_tce_get((u64)tbl->it_index,
391 			   (u64)tcenum << tbl->it_page_shift, &tce_ret);
392 
393 	if (rc && printk_ratelimit()) {
394 		printk("tce_get_pSeriesLP: plpar_tce_get failed. rc=%lld\n", rc);
395 		printk("\tindex   = 0x%llx\n", (u64)tbl->it_index);
396 		printk("\ttcenum  = 0x%llx\n", (u64)tcenum);
397 		dump_stack();
398 	}
399 
400 	return tce_ret;
401 }
402 
403 /* this is compatible with cells for the device tree property */
404 struct dynamic_dma_window_prop {
405 	__be32	liobn;		/* tce table number */
406 	__be64	dma_base;	/* address hi,lo */
407 	__be32	tce_shift;	/* ilog2(tce_page_size) */
408 	__be32	window_shift;	/* ilog2(tce_window_size) */
409 };
410 
411 struct dma_win {
412 	struct device_node *device;
413 	const struct dynamic_dma_window_prop *prop;
414 	bool    direct;
415 	struct list_head list;
416 };
417 
418 /* Dynamic DMA Window support */
419 struct ddw_query_response {
420 	u32 windows_available;
421 	u64 largest_available_block;
422 	u32 page_size;
423 	u32 migration_capable;
424 };
425 
426 struct ddw_create_response {
427 	u32 liobn;
428 	u32 addr_hi;
429 	u32 addr_lo;
430 };
431 
432 static LIST_HEAD(dma_win_list);
433 /* prevents races between memory on/offline and window creation */
434 static DEFINE_SPINLOCK(dma_win_list_lock);
435 /* protects initializing window twice for same device */
436 static DEFINE_MUTEX(dma_win_init_mutex);
437 
438 static int tce_clearrange_multi_pSeriesLP(unsigned long start_pfn,
439 					unsigned long num_pfn, const void *arg)
440 {
441 	const struct dynamic_dma_window_prop *maprange = arg;
442 	int rc;
443 	u64 tce_size, num_tce, dma_offset, next;
444 	u32 tce_shift;
445 	long limit;
446 
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 	do {
461 		/*
462 		 * Set up the page with TCE data, looping through and setting
463 		 * the values.
464 		 */
465 		limit = min_t(long, num_tce, 512);
466 		dma_offset = next + be64_to_cpu(maprange->dma_base);
467 
468 		rc = plpar_tce_stuff((u64)be32_to_cpu(maprange->liobn),
469 					     dma_offset,
470 					     0, limit);
471 		next += limit * tce_size;
472 		num_tce -= limit;
473 	} while (num_tce > 0 && !rc);
474 
475 	return rc;
476 }
477 
478 static int tce_setrange_multi_pSeriesLP(unsigned long start_pfn,
479 					unsigned long num_pfn, const void *arg)
480 {
481 	const struct dynamic_dma_window_prop *maprange = arg;
482 	u64 tce_size, num_tce, dma_offset, next, proto_tce, liobn;
483 	__be64 *tcep;
484 	u32 tce_shift;
485 	u64 rc = 0;
486 	long l, limit;
487 
488 	if (!firmware_has_feature(FW_FEATURE_PUT_TCE_IND)) {
489 		unsigned long tceshift = be32_to_cpu(maprange->tce_shift);
490 		unsigned long dmastart = (start_pfn << PAGE_SHIFT) +
491 				be64_to_cpu(maprange->dma_base);
492 		unsigned long tcenum = dmastart >> tceshift;
493 		unsigned long npages = num_pfn << PAGE_SHIFT >> tceshift;
494 		void *uaddr = __va(start_pfn << PAGE_SHIFT);
495 
496 		return tce_build_pSeriesLP(be32_to_cpu(maprange->liobn),
497 				tcenum, tceshift, npages, (unsigned long) uaddr,
498 				DMA_BIDIRECTIONAL, 0);
499 	}
500 
501 	local_irq_disable();	/* to protect tcep and the page behind it */
502 	tcep = __this_cpu_read(tce_page);
503 
504 	if (!tcep) {
505 		tcep = (__be64 *)__get_free_page(GFP_ATOMIC);
506 		if (!tcep) {
507 			local_irq_enable();
508 			return -ENOMEM;
509 		}
510 		__this_cpu_write(tce_page, tcep);
511 	}
512 
513 	proto_tce = TCE_PCI_READ | TCE_PCI_WRITE;
514 
515 	liobn = (u64)be32_to_cpu(maprange->liobn);
516 	tce_shift = be32_to_cpu(maprange->tce_shift);
517 	tce_size = 1ULL << tce_shift;
518 	next = start_pfn << PAGE_SHIFT;
519 	num_tce = num_pfn << PAGE_SHIFT;
520 
521 	/* round back to the beginning of the tce page size */
522 	num_tce += next & (tce_size - 1);
523 	next &= ~(tce_size - 1);
524 
525 	/* covert to number of tces */
526 	num_tce |= tce_size - 1;
527 	num_tce >>= tce_shift;
528 
529 	/* We can map max one pageful of TCEs at a time */
530 	do {
531 		/*
532 		 * Set up the page with TCE data, looping through and setting
533 		 * the values.
534 		 */
535 		limit = min_t(long, num_tce, 4096 / TCE_ENTRY_SIZE);
536 		dma_offset = next + be64_to_cpu(maprange->dma_base);
537 
538 		for (l = 0; l < limit; l++) {
539 			tcep[l] = cpu_to_be64(proto_tce | next);
540 			next += tce_size;
541 		}
542 
543 		rc = plpar_tce_put_indirect(liobn,
544 					    dma_offset,
545 					    (u64)__pa(tcep),
546 					    limit);
547 
548 		num_tce -= limit;
549 	} while (num_tce > 0 && !rc);
550 
551 	/* error cleanup: caller will clear whole range */
552 
553 	local_irq_enable();
554 	return rc;
555 }
556 
557 static int tce_setrange_multi_pSeriesLP_walk(unsigned long start_pfn,
558 		unsigned long num_pfn, void *arg)
559 {
560 	return tce_setrange_multi_pSeriesLP(start_pfn, num_pfn, arg);
561 }
562 
563 static void iommu_table_setparms_common(struct iommu_table *tbl, unsigned long busno,
564 					unsigned long liobn, unsigned long win_addr,
565 					unsigned long window_size, unsigned long page_shift,
566 					void *base, struct iommu_table_ops *table_ops)
567 {
568 	tbl->it_busno = busno;
569 	tbl->it_index = liobn;
570 	tbl->it_offset = win_addr >> page_shift;
571 	tbl->it_size = window_size >> page_shift;
572 	tbl->it_page_shift = page_shift;
573 	tbl->it_base = (unsigned long)base;
574 	tbl->it_blocksize = 16;
575 	tbl->it_type = TCE_PCI;
576 	tbl->it_ops = table_ops;
577 }
578 
579 struct iommu_table_ops iommu_table_pseries_ops;
580 
581 static void iommu_table_setparms(struct pci_controller *phb,
582 				 struct device_node *dn,
583 				 struct iommu_table *tbl)
584 {
585 	struct device_node *node;
586 	const unsigned long *basep;
587 	const u32 *sizep;
588 
589 	/* Test if we are going over 2GB of DMA space */
590 	if (phb->dma_window_base_cur + phb->dma_window_size > SZ_2G) {
591 		udbg_printf("PCI_DMA: Unexpected number of IOAs under this PHB.\n");
592 		panic("PCI_DMA: Unexpected number of IOAs under this PHB.\n");
593 	}
594 
595 	node = phb->dn;
596 	basep = of_get_property(node, "linux,tce-base", NULL);
597 	sizep = of_get_property(node, "linux,tce-size", NULL);
598 	if (basep == NULL || sizep == NULL) {
599 		printk(KERN_ERR "PCI_DMA: iommu_table_setparms: %pOF has "
600 				"missing tce entries !\n", dn);
601 		return;
602 	}
603 
604 	iommu_table_setparms_common(tbl, phb->bus->number, 0, phb->dma_window_base_cur,
605 				    phb->dma_window_size, IOMMU_PAGE_SHIFT_4K,
606 				    __va(*basep), &iommu_table_pseries_ops);
607 
608 	if (!is_kdump_kernel())
609 		memset((void *)tbl->it_base, 0, *sizep);
610 
611 	phb->dma_window_base_cur += phb->dma_window_size;
612 }
613 
614 struct iommu_table_ops iommu_table_lpar_multi_ops;
615 
616 struct iommu_table_ops iommu_table_pseries_ops = {
617 	.set = tce_build_pSeries,
618 	.clear = tce_clear_pSeries,
619 	.get = tce_get_pseries
620 };
621 
622 static void pci_dma_bus_setup_pSeries(struct pci_bus *bus)
623 {
624 	struct device_node *dn;
625 	struct iommu_table *tbl;
626 	struct device_node *isa_dn, *isa_dn_orig;
627 	struct device_node *tmp;
628 	struct pci_dn *pci;
629 	int children;
630 
631 	dn = pci_bus_to_OF_node(bus);
632 
633 	pr_debug("pci_dma_bus_setup_pSeries: setting up bus %pOF\n", dn);
634 
635 	if (bus->self) {
636 		/* This is not a root bus, any setup will be done for the
637 		 * device-side of the bridge in iommu_dev_setup_pSeries().
638 		 */
639 		return;
640 	}
641 	pci = PCI_DN(dn);
642 
643 	/* Check if the ISA bus on the system is under
644 	 * this PHB.
645 	 */
646 	isa_dn = isa_dn_orig = of_find_node_by_type(NULL, "isa");
647 
648 	while (isa_dn && isa_dn != dn)
649 		isa_dn = isa_dn->parent;
650 
651 	of_node_put(isa_dn_orig);
652 
653 	/* Count number of direct PCI children of the PHB. */
654 	for (children = 0, tmp = dn->child; tmp; tmp = tmp->sibling)
655 		children++;
656 
657 	pr_debug("Children: %d\n", children);
658 
659 	/* Calculate amount of DMA window per slot. Each window must be
660 	 * a power of two (due to pci_alloc_consistent requirements).
661 	 *
662 	 * Keep 256MB aside for PHBs with ISA.
663 	 */
664 
665 	if (!isa_dn) {
666 		/* No ISA/IDE - just set window size and return */
667 		pci->phb->dma_window_size = 0x80000000ul; /* To be divided */
668 
669 		while (pci->phb->dma_window_size * children > 0x80000000ul)
670 			pci->phb->dma_window_size >>= 1;
671 		pr_debug("No ISA/IDE, window size is 0x%llx\n",
672 			 pci->phb->dma_window_size);
673 		pci->phb->dma_window_base_cur = 0;
674 
675 		return;
676 	}
677 
678 	/* If we have ISA, then we probably have an IDE
679 	 * controller too. Allocate a 128MB table but
680 	 * skip the first 128MB to avoid stepping on ISA
681 	 * space.
682 	 */
683 	pci->phb->dma_window_size = 0x8000000ul;
684 	pci->phb->dma_window_base_cur = 0x8000000ul;
685 
686 	pci->table_group = iommu_pseries_alloc_group(pci->phb->node);
687 	tbl = pci->table_group->tables[0];
688 
689 	iommu_table_setparms(pci->phb, dn, tbl);
690 
691 	if (!iommu_init_table(tbl, pci->phb->node, 0, 0))
692 		panic("Failed to initialize iommu table");
693 
694 	/* Divide the rest (1.75GB) among the children */
695 	pci->phb->dma_window_size = 0x80000000ul;
696 	while (pci->phb->dma_window_size * children > 0x70000000ul)
697 		pci->phb->dma_window_size >>= 1;
698 
699 	pr_debug("ISA/IDE, window size is 0x%llx\n", pci->phb->dma_window_size);
700 }
701 
702 #ifdef CONFIG_IOMMU_API
703 static int tce_exchange_pseries(struct iommu_table *tbl, long index, unsigned
704 				long *tce, enum dma_data_direction *direction)
705 {
706 	long rc;
707 	unsigned long ioba = (unsigned long) index << tbl->it_page_shift;
708 	unsigned long flags, oldtce = 0;
709 	u64 proto_tce = iommu_direction_to_tce_perm(*direction);
710 	unsigned long newtce = *tce | proto_tce;
711 
712 	spin_lock_irqsave(&tbl->large_pool.lock, flags);
713 
714 	rc = plpar_tce_get((u64)tbl->it_index, ioba, &oldtce);
715 	if (!rc)
716 		rc = plpar_tce_put((u64)tbl->it_index, ioba, newtce);
717 
718 	if (!rc) {
719 		*direction = iommu_tce_direction(oldtce);
720 		*tce = oldtce & ~(TCE_PCI_READ | TCE_PCI_WRITE);
721 	}
722 
723 	spin_unlock_irqrestore(&tbl->large_pool.lock, flags);
724 
725 	return rc;
726 }
727 
728 static __be64 *tce_useraddr_pSeriesLP(struct iommu_table *tbl, long index,
729 				      bool __always_unused alloc)
730 {
731 	return tbl->it_userspace ? &tbl->it_userspace[index - tbl->it_offset] : NULL;
732 }
733 #endif
734 
735 struct iommu_table_ops iommu_table_lpar_multi_ops = {
736 	.set = tce_buildmulti_pSeriesLP,
737 #ifdef CONFIG_IOMMU_API
738 	.xchg_no_kill = tce_exchange_pseries,
739 	.useraddrptr = tce_useraddr_pSeriesLP,
740 #endif
741 	.clear = tce_freemulti_pSeriesLP,
742 	.get = tce_get_pSeriesLP,
743 	.free = tce_free_pSeries
744 };
745 
746 #ifdef CONFIG_IOMMU_API
747 /*
748  * When the DMA window properties might have been removed,
749  * the parent node has the table_group setup on it.
750  */
751 static struct device_node *pci_dma_find_parent_node(struct pci_dev *dev,
752 					       struct iommu_table_group *table_group)
753 {
754 	struct device_node *dn = pci_device_to_OF_node(dev);
755 	struct pci_dn *rpdn;
756 
757 	for (; dn && PCI_DN(dn); dn = dn->parent) {
758 		rpdn = PCI_DN(dn);
759 
760 		if (table_group == rpdn->table_group)
761 			return dn;
762 	}
763 
764 	return NULL;
765 }
766 #endif
767 
768 /*
769  * Find nearest ibm,dma-window (default DMA window) or direct DMA window or
770  * dynamic 64bit DMA window, walking up the device tree.
771  */
772 static struct device_node *pci_dma_find(struct device_node *dn,
773 					struct dynamic_dma_window_prop *prop)
774 {
775 	const __be32 *default_prop = NULL;
776 	const __be32 *ddw_prop = NULL;
777 	struct device_node *rdn = NULL;
778 	bool default_win = false, ddw_win = false;
779 
780 	for ( ; dn && PCI_DN(dn); dn = dn->parent) {
781 		default_prop = of_get_property(dn, "ibm,dma-window", NULL);
782 		if (default_prop) {
783 			rdn = dn;
784 			default_win = true;
785 		}
786 		ddw_prop = of_get_property(dn, DIRECT64_PROPNAME, NULL);
787 		if (ddw_prop) {
788 			rdn = dn;
789 			ddw_win = true;
790 			break;
791 		}
792 		ddw_prop = of_get_property(dn, DMA64_PROPNAME, NULL);
793 		if (ddw_prop) {
794 			rdn = dn;
795 			ddw_win = true;
796 			break;
797 		}
798 
799 		/* At least found default window, which is the case for normal boot */
800 		if (default_win)
801 			break;
802 	}
803 
804 	/* For PCI devices there will always be a DMA window, either on the device
805 	 * or parent bus
806 	 */
807 	WARN_ON(!(default_win | ddw_win));
808 
809 	/* caller doesn't want to get DMA window property */
810 	if (!prop)
811 		return rdn;
812 
813 	/* parse DMA window property. During normal system boot, only default
814 	 * DMA window is passed in OF. But, for kdump, a dedicated adapter might
815 	 * have both default and DDW in FDT. In this scenario, default window
816 	 * takes precedence over DDW. For a dedicated adapter, default window will
817 	 * potentially have more unused TCEs.
818 	 */
819 	if (default_win) {
820 		unsigned long offset, size, liobn;
821 
822 		of_parse_dma_window(rdn, default_prop, &liobn, &offset, &size);
823 
824 		prop->liobn = cpu_to_be32((u32)liobn);
825 		prop->dma_base = cpu_to_be64(offset);
826 		prop->tce_shift = cpu_to_be32(IOMMU_PAGE_SHIFT_4K);
827 		prop->window_shift = cpu_to_be32(order_base_2(size));
828 	} else {
829 		struct dynamic_dma_window_prop *p;
830 
831 		p = (struct dynamic_dma_window_prop *)ddw_prop;
832 		prop->liobn = p->liobn;
833 		prop->dma_base = p->dma_base;
834 		prop->tce_shift = p->tce_shift;
835 		prop->window_shift = p->window_shift;
836 	}
837 
838 	return rdn;
839 }
840 
841 static void pci_dma_bus_setup_pSeriesLP(struct pci_bus *bus)
842 {
843 	struct iommu_table *tbl;
844 	struct device_node *dn, *pdn;
845 	struct pci_dn *ppci;
846 	struct dynamic_dma_window_prop prop;
847 
848 	dn = pci_bus_to_OF_node(bus);
849 
850 	pr_debug("pci_dma_bus_setup_pSeriesLP: setting up bus %pOF\n",
851 		 dn);
852 
853 	pdn = pci_dma_find(dn, &prop);
854 
855 	/* In PPC architecture, there will always be DMA window on bus or one of the
856 	 * parent bus. During reboot, there will be ibm,dma-window property to
857 	 * define DMA window. For kdump, there will at least be default window or DDW
858 	 * or both.
859 	 * There is an exception to the above. In case the PE goes into frozen
860 	 * state, firmware may not provide ibm,dma-window property at the time
861 	 * of LPAR boot up.
862 	 */
863 
864 	if (!pdn) {
865 		pr_debug("  no ibm,dma-window property !\n");
866 		return;
867 	}
868 
869 	ppci = PCI_DN(pdn);
870 
871 	pr_debug("  parent is %pOF, iommu_table: 0x%p\n",
872 		 pdn, ppci->table_group);
873 
874 	if (!ppci->table_group) {
875 		ppci->table_group = iommu_pseries_alloc_group(ppci->phb->node);
876 		tbl = ppci->table_group->tables[0];
877 
878 		iommu_table_setparms_common(tbl, ppci->phb->bus->number,
879 				be32_to_cpu(prop.liobn),
880 				be64_to_cpu(prop.dma_base),
881 				1ULL << be32_to_cpu(prop.window_shift),
882 				be32_to_cpu(prop.tce_shift), NULL,
883 				&iommu_table_lpar_multi_ops);
884 
885 		if (!iommu_init_table(tbl, ppci->phb->node, 0, 0))
886 			panic("Failed to initialize iommu table");
887 
888 		iommu_register_group(ppci->table_group,
889 				pci_domain_nr(bus), 0);
890 		pr_debug("  created table: %p\n", ppci->table_group);
891 	}
892 }
893 
894 
895 static void pci_dma_dev_setup_pSeries(struct pci_dev *dev)
896 {
897 	struct device_node *dn;
898 	struct iommu_table *tbl;
899 
900 	pr_debug("pci_dma_dev_setup_pSeries: %s\n", pci_name(dev));
901 
902 	dn = dev->dev.of_node;
903 
904 	/* If we're the direct child of a root bus, then we need to allocate
905 	 * an iommu table ourselves. The bus setup code should have setup
906 	 * the window sizes already.
907 	 */
908 	if (!dev->bus->self) {
909 		struct pci_controller *phb = PCI_DN(dn)->phb;
910 
911 		pr_debug(" --> first child, no bridge. Allocating iommu table.\n");
912 		PCI_DN(dn)->table_group = iommu_pseries_alloc_group(phb->node);
913 		tbl = PCI_DN(dn)->table_group->tables[0];
914 		iommu_table_setparms(phb, dn, tbl);
915 
916 		if (!iommu_init_table(tbl, phb->node, 0, 0))
917 			panic("Failed to initialize iommu table");
918 
919 		set_iommu_table_base(&dev->dev, tbl);
920 		return;
921 	}
922 
923 	/* If this device is further down the bus tree, search upwards until
924 	 * an already allocated iommu table is found and use that.
925 	 */
926 
927 	while (dn && PCI_DN(dn) && PCI_DN(dn)->table_group == NULL)
928 		dn = dn->parent;
929 
930 	if (dn && PCI_DN(dn))
931 		set_iommu_table_base(&dev->dev,
932 				PCI_DN(dn)->table_group->tables[0]);
933 	else
934 		printk(KERN_WARNING "iommu: Device %s has no iommu table\n",
935 		       pci_name(dev));
936 }
937 
938 static int __read_mostly disable_ddw;
939 
940 static int __init disable_ddw_setup(char *str)
941 {
942 	disable_ddw = 1;
943 	printk(KERN_INFO "ppc iommu: disabling ddw.\n");
944 
945 	return 0;
946 }
947 
948 early_param("disable_ddw", disable_ddw_setup);
949 
950 static void clean_dma_window(struct device_node *np, struct dynamic_dma_window_prop *dwp)
951 {
952 	int ret;
953 
954 	ret = tce_clearrange_multi_pSeriesLP(0,
955 		1ULL << (be32_to_cpu(dwp->window_shift) - PAGE_SHIFT), dwp);
956 	if (ret)
957 		pr_warn("%pOF failed to clear tces in window.\n",
958 			np);
959 	else
960 		pr_debug("%pOF successfully cleared tces in window.\n",
961 			 np);
962 }
963 
964 /*
965  * Call only if DMA window is clean.
966  */
967 static void __remove_dma_window(struct device_node *np, u32 *ddw_avail, u64 liobn)
968 {
969 	int ret;
970 
971 	ret = rtas_call(ddw_avail[DDW_REMOVE_PE_DMA_WIN], 1, 1, NULL, liobn);
972 	if (ret)
973 		pr_warn("%pOF: failed to remove DMA window: rtas returned "
974 			"%d to ibm,remove-pe-dma-window(%x) %llx\n",
975 			np, ret, ddw_avail[DDW_REMOVE_PE_DMA_WIN], liobn);
976 	else
977 		pr_debug("%pOF: successfully removed DMA window: rtas returned "
978 			"%d to ibm,remove-pe-dma-window(%x) %llx\n",
979 			np, ret, ddw_avail[DDW_REMOVE_PE_DMA_WIN], liobn);
980 }
981 
982 static void remove_dma_window(struct device_node *np, u32 *ddw_avail,
983 			      struct property *win, bool cleanup)
984 {
985 	struct dynamic_dma_window_prop *dwp;
986 	u64 liobn;
987 
988 	dwp = win->value;
989 	liobn = (u64)be32_to_cpu(dwp->liobn);
990 
991 	if (cleanup)
992 		clean_dma_window(np, dwp);
993 	__remove_dma_window(np, ddw_avail, liobn);
994 }
995 
996 static void copy_property(struct device_node *pdn, const char *from, const char *to)
997 {
998 	struct property *src, *dst;
999 
1000 	src = of_find_property(pdn, from, NULL);
1001 	if (!src)
1002 		return;
1003 
1004 	dst = kzalloc_obj(*dst);
1005 	if (!dst)
1006 		return;
1007 
1008 	dst->name = kstrdup(to, GFP_KERNEL);
1009 	dst->value = kmemdup(src->value, src->length, GFP_KERNEL);
1010 	dst->length = src->length;
1011 	if (!dst->name || !dst->value)
1012 		return;
1013 
1014 	if (of_add_property(pdn, dst)) {
1015 		pr_err("Unable to add DMA window property for %pOF", pdn);
1016 		goto free_prop;
1017 	}
1018 
1019 	return;
1020 
1021 free_prop:
1022 	kfree(dst->name);
1023 	kfree(dst->value);
1024 	kfree(dst);
1025 }
1026 
1027 static int remove_dma_window_named(struct device_node *np, bool remove_prop, const char *win_name,
1028 				   bool cleanup)
1029 {
1030 	struct property *win;
1031 	u32 ddw_avail[DDW_APPLICABLE_SIZE];
1032 	int ret = 0;
1033 
1034 	win = of_find_property(np, win_name, NULL);
1035 	if (!win)
1036 		return -EINVAL;
1037 
1038 	ret = of_property_read_u32_array(np, "ibm,ddw-applicable",
1039 					 &ddw_avail[0], DDW_APPLICABLE_SIZE);
1040 	if (ret)
1041 		return 0;
1042 
1043 	if (win->length >= sizeof(struct dynamic_dma_window_prop))
1044 		remove_dma_window(np, ddw_avail, win, cleanup);
1045 
1046 	if (!remove_prop)
1047 		return 0;
1048 
1049 	/* Default window property if removed is lost as reset-pe doesn't restore it.
1050 	 * Though FDT has a copy of it, the DLPAR hotplugged devices will not have a
1051 	 * node on FDT until next reboot. So, back it up.
1052 	 */
1053 	if ((strcmp(win_name, "ibm,dma-window") == 0) &&
1054 	    !of_find_property(np, "ibm,dma-window-saved", NULL))
1055 		copy_property(np, win_name, "ibm,dma-window-saved");
1056 
1057 	ret = of_remove_property(np, win);
1058 	if (ret)
1059 		pr_warn("%pOF: failed to remove DMA window property: %d\n",
1060 			np, ret);
1061 	return 0;
1062 }
1063 
1064 static bool find_existing_ddw(struct device_node *pdn, u64 *dma_addr, int *window_shift,
1065 			      bool *direct_mapping)
1066 {
1067 	struct dma_win *window;
1068 	const struct dynamic_dma_window_prop *dma64;
1069 	bool found = false;
1070 
1071 	spin_lock(&dma_win_list_lock);
1072 	/* check if we already created a window and dupe that config if so */
1073 	list_for_each_entry(window, &dma_win_list, list) {
1074 		if (window->device == pdn) {
1075 			dma64 = window->prop;
1076 			*dma_addr = be64_to_cpu(dma64->dma_base);
1077 			*window_shift = be32_to_cpu(dma64->window_shift);
1078 			*direct_mapping = window->direct;
1079 			found = true;
1080 			break;
1081 		}
1082 	}
1083 	spin_unlock(&dma_win_list_lock);
1084 
1085 	return found;
1086 }
1087 
1088 static struct dma_win *ddw_list_new_entry(struct device_node *pdn,
1089 					  const struct dynamic_dma_window_prop *dma64)
1090 {
1091 	struct dma_win *window;
1092 
1093 	window = kzalloc_obj(*window);
1094 	if (!window)
1095 		return NULL;
1096 
1097 	window->device = pdn;
1098 	window->prop = dma64;
1099 	window->direct = false;
1100 
1101 	return window;
1102 }
1103 
1104 static void find_existing_ddw_windows_named(const char *name)
1105 {
1106 	int len;
1107 	struct device_node *pdn;
1108 	struct dma_win *window;
1109 	const struct dynamic_dma_window_prop *dma64;
1110 
1111 	for_each_node_with_property(pdn, name) {
1112 		dma64 = of_get_property(pdn, name, &len);
1113 		if (!dma64 || len < sizeof(*dma64)) {
1114 			remove_dma_window_named(pdn, true, name, true);
1115 			continue;
1116 		}
1117 
1118 		/* If at the time of system initialization, there are DDWs in OF,
1119 		 * it means this is during kexec. DDW could be direct or dynamic.
1120 		 * We will just mark DDWs as "dynamic" since this is kdump path,
1121 		 * no need to worry about perforance. ddw_list_new_entry() will
1122 		 * set window->direct = false.
1123 		 */
1124 		window = ddw_list_new_entry(pdn, dma64);
1125 		if (!window) {
1126 			of_node_put(pdn);
1127 			break;
1128 		}
1129 
1130 		spin_lock(&dma_win_list_lock);
1131 		list_add(&window->list, &dma_win_list);
1132 		spin_unlock(&dma_win_list_lock);
1133 	}
1134 }
1135 
1136 static int find_existing_ddw_windows(void)
1137 {
1138 	if (!firmware_has_feature(FW_FEATURE_LPAR))
1139 		return 0;
1140 
1141 	find_existing_ddw_windows_named(DIRECT64_PROPNAME);
1142 	find_existing_ddw_windows_named(DMA64_PROPNAME);
1143 
1144 	return 0;
1145 }
1146 machine_arch_initcall(pseries, find_existing_ddw_windows);
1147 
1148 /**
1149  * ddw_read_ext - Get the value of an DDW extension
1150  * @np:		device node from which the extension value is to be read.
1151  * @extnum:	index number of the extension.
1152  * @value:	pointer to return value, modified when extension is available.
1153  *
1154  * Checks if "ibm,ddw-extensions" exists for this node, and get the value
1155  * on index 'extnum'.
1156  * It can be used only to check if a property exists, passing value == NULL.
1157  *
1158  * Returns:
1159  *	0 if extension successfully read
1160  *	-EINVAL if the "ibm,ddw-extensions" does not exist,
1161  *	-ENODATA if "ibm,ddw-extensions" does not have a value, and
1162  *	-EOVERFLOW if "ibm,ddw-extensions" does not contain this extension.
1163  */
1164 static inline int ddw_read_ext(const struct device_node *np, int extnum,
1165 			       u32 *value)
1166 {
1167 	static const char propname[] = "ibm,ddw-extensions";
1168 	u32 count;
1169 	int ret;
1170 
1171 	ret = of_property_read_u32_index(np, propname, DDW_EXT_SIZE, &count);
1172 	if (ret)
1173 		return ret;
1174 
1175 	if (count < extnum)
1176 		return -EOVERFLOW;
1177 
1178 	if (!value)
1179 		value = &count;
1180 
1181 	return of_property_read_u32_index(np, propname, extnum, value);
1182 }
1183 
1184 static int query_ddw(struct pci_dev *dev, const u32 *ddw_avail,
1185 		     struct ddw_query_response *query,
1186 		     struct device_node *parent)
1187 {
1188 	struct device_node *dn;
1189 	struct pci_dn *pdn;
1190 	u32 cfg_addr, ext_query, query_out[5];
1191 	u64 buid;
1192 	int ret, out_sz;
1193 
1194 	/*
1195 	 * From LoPAR level 2.8, "ibm,ddw-extensions" index 3 can rule how many
1196 	 * output parameters ibm,query-pe-dma-windows will have, ranging from
1197 	 * 5 to 6.
1198 	 */
1199 	ret = ddw_read_ext(parent, DDW_EXT_QUERY_OUT_SIZE, &ext_query);
1200 	if (!ret && ext_query == 1)
1201 		out_sz = 6;
1202 	else
1203 		out_sz = 5;
1204 
1205 	/*
1206 	 * Get the config address and phb buid of the PE window.
1207 	 * Rely on eeh to retrieve this for us.
1208 	 * Retrieve them from the pci device, not the node with the
1209 	 * dma-window property
1210 	 */
1211 	dn = pci_device_to_OF_node(dev);
1212 	pdn = PCI_DN(dn);
1213 	buid = pdn->phb->buid;
1214 	cfg_addr = ((pdn->busno << 16) | (pdn->devfn << 8));
1215 
1216 	ret = rtas_call(ddw_avail[DDW_QUERY_PE_DMA_WIN], 3, out_sz, query_out,
1217 			cfg_addr, BUID_HI(buid), BUID_LO(buid));
1218 
1219 	switch (out_sz) {
1220 	case 5:
1221 		query->windows_available = query_out[0];
1222 		query->largest_available_block = query_out[1];
1223 		query->page_size = query_out[2];
1224 		query->migration_capable = query_out[3];
1225 		break;
1226 	case 6:
1227 		query->windows_available = query_out[0];
1228 		query->largest_available_block = ((u64)query_out[1] << 32) |
1229 						 query_out[2];
1230 		query->page_size = query_out[3];
1231 		query->migration_capable = query_out[4];
1232 		break;
1233 	}
1234 
1235 	dev_info(&dev->dev, "ibm,query-pe-dma-windows(%x) %x %x %x returned %d, lb=%llx ps=%x wn=%d\n",
1236 		 ddw_avail[DDW_QUERY_PE_DMA_WIN], cfg_addr, BUID_HI(buid),
1237 		 BUID_LO(buid), ret, query->largest_available_block,
1238 		 query->page_size, query->windows_available);
1239 
1240 	return ret;
1241 }
1242 
1243 static int create_ddw(struct pci_dev *dev, const u32 *ddw_avail,
1244 			struct ddw_create_response *create, int page_shift,
1245 			int window_shift)
1246 {
1247 	struct device_node *dn;
1248 	struct pci_dn *pdn;
1249 	u32 cfg_addr;
1250 	u64 buid;
1251 	int ret;
1252 
1253 	/*
1254 	 * Get the config address and phb buid of the PE window.
1255 	 * Rely on eeh to retrieve this for us.
1256 	 * Retrieve them from the pci device, not the node with the
1257 	 * dma-window property
1258 	 */
1259 	dn = pci_device_to_OF_node(dev);
1260 	pdn = PCI_DN(dn);
1261 	buid = pdn->phb->buid;
1262 	cfg_addr = ((pdn->busno << 16) | (pdn->devfn << 8));
1263 
1264 	do {
1265 		/* extra outputs are LIOBN and dma-addr (hi, lo) */
1266 		ret = rtas_call(ddw_avail[DDW_CREATE_PE_DMA_WIN], 5, 4,
1267 				(u32 *)create, cfg_addr, BUID_HI(buid),
1268 				BUID_LO(buid), page_shift, window_shift);
1269 	} while (rtas_busy_delay(ret));
1270 	dev_info(&dev->dev,
1271 		"ibm,create-pe-dma-window(%x) %x %x %x %x %x returned %d "
1272 		"(liobn = 0x%x starting addr = %x %x)\n",
1273 		 ddw_avail[DDW_CREATE_PE_DMA_WIN], cfg_addr, BUID_HI(buid),
1274 		 BUID_LO(buid), page_shift, window_shift, ret, create->liobn,
1275 		 create->addr_hi, create->addr_lo);
1276 
1277 	return ret;
1278 }
1279 
1280 struct failed_ddw_pdn {
1281 	struct device_node *pdn;
1282 	struct list_head list;
1283 };
1284 
1285 static LIST_HEAD(failed_ddw_pdn_list);
1286 
1287 static phys_addr_t ddw_memory_hotplug_max(void)
1288 {
1289 	resource_size_t max_addr;
1290 
1291 #if defined(CONFIG_NUMA) && defined(CONFIG_MEMORY_HOTPLUG)
1292 	max_addr = hot_add_drconf_memory_max();
1293 #else
1294 	max_addr = memblock_end_of_DRAM();
1295 #endif
1296 
1297 	return max_addr;
1298 }
1299 
1300 /*
1301  * Platforms supporting the DDW option starting with LoPAR level 2.7 implement
1302  * ibm,ddw-extensions, which carries the rtas token for
1303  * ibm,reset-pe-dma-windows.
1304  * That rtas-call can be used to restore the default DMA window for the device.
1305  */
1306 static void reset_dma_window(struct pci_dev *dev, struct device_node *par_dn)
1307 {
1308 	int ret;
1309 	u32 cfg_addr, reset_dma_win;
1310 	u64 buid;
1311 	struct device_node *dn;
1312 	struct pci_dn *pdn;
1313 
1314 	ret = ddw_read_ext(par_dn, DDW_EXT_RESET_DMA_WIN, &reset_dma_win);
1315 	if (ret)
1316 		return;
1317 
1318 	dn = pci_device_to_OF_node(dev);
1319 	pdn = PCI_DN(dn);
1320 	buid = pdn->phb->buid;
1321 	cfg_addr = (pdn->busno << 16) | (pdn->devfn << 8);
1322 
1323 	ret = rtas_call(reset_dma_win, 3, 1, NULL, cfg_addr, BUID_HI(buid),
1324 			BUID_LO(buid));
1325 	if (ret)
1326 		dev_info(&dev->dev,
1327 			 "ibm,reset-pe-dma-windows(%x) %x %x %x returned %d ",
1328 			 reset_dma_win, cfg_addr, BUID_HI(buid), BUID_LO(buid),
1329 			 ret);
1330 }
1331 
1332 /*
1333  * Platforms support placing PHB in limited address mode starting with LoPAR
1334  * level 2.13 implement. In this mode, the DMA address returned by DDW is over
1335  * 4GB but, less than 64-bits. This benefits IO adapters that don't support
1336  * 64-bits for DMA addresses.
1337  */
1338 static int limited_dma_window(struct pci_dev *dev, struct device_node *par_dn)
1339 {
1340 	int ret;
1341 	u32 cfg_addr, reset_dma_win, las_supported;
1342 	u64 buid;
1343 	struct device_node *dn;
1344 	struct pci_dn *pdn;
1345 
1346 	ret = ddw_read_ext(par_dn, DDW_EXT_RESET_DMA_WIN, &reset_dma_win);
1347 	if (ret)
1348 		goto out;
1349 
1350 	ret = ddw_read_ext(par_dn, DDW_EXT_LIMITED_ADDR_MODE, &las_supported);
1351 
1352 	/* Limited Address Space extension available on the platform but DDW in
1353 	 * limited addressing mode not supported
1354 	 */
1355 	if (!ret && !las_supported)
1356 		ret = -EPROTO;
1357 
1358 	if (ret) {
1359 		dev_info(&dev->dev, "Limited Address Space for DDW not Supported, err: %d", ret);
1360 		goto out;
1361 	}
1362 
1363 	dn = pci_device_to_OF_node(dev);
1364 	pdn = PCI_DN(dn);
1365 	buid = pdn->phb->buid;
1366 	cfg_addr = (pdn->busno << 16) | (pdn->devfn << 8);
1367 
1368 	ret = rtas_call(reset_dma_win, 4, 1, NULL, cfg_addr, BUID_HI(buid),
1369 			BUID_LO(buid), 1);
1370 	if (ret)
1371 		dev_info(&dev->dev,
1372 			 "ibm,reset-pe-dma-windows(%x) for Limited Addr Support: %x %x %x returned %d ",
1373 			 reset_dma_win, cfg_addr, BUID_HI(buid), BUID_LO(buid),
1374 			 ret);
1375 
1376 out:
1377 	return ret;
1378 }
1379 
1380 /* Return largest page shift based on "IO Page Sizes" output of ibm,query-pe-dma-window. */
1381 static int iommu_get_page_shift(u32 query_page_size)
1382 {
1383 	/* Supported IO page-sizes according to LoPAR, note that 2M is out of order */
1384 	const int shift[] = {
1385 		__builtin_ctzll(SZ_4K),   __builtin_ctzll(SZ_64K), __builtin_ctzll(SZ_16M),
1386 		__builtin_ctzll(SZ_32M),  __builtin_ctzll(SZ_64M), __builtin_ctzll(SZ_128M),
1387 		__builtin_ctzll(SZ_256M), __builtin_ctzll(SZ_16G), __builtin_ctzll(SZ_2M)
1388 	};
1389 
1390 	int i = ARRAY_SIZE(shift) - 1;
1391 	int ret = 0;
1392 
1393 	/*
1394 	 * On LoPAR, ibm,query-pe-dma-window outputs "IO Page Sizes" using a bit field:
1395 	 * - bit 31 means 4k pages are supported,
1396 	 * - bit 30 means 64k pages are supported, and so on.
1397 	 * Larger pagesizes map more memory with the same amount of TCEs, so start probing them.
1398 	 */
1399 	for (; i >= 0 ; i--) {
1400 		if (query_page_size & (1 << i))
1401 			ret = max(ret, shift[i]);
1402 	}
1403 
1404 	return ret;
1405 }
1406 
1407 static struct property *ddw_property_create(const char *propname, u32 liobn, u64 dma_addr,
1408 					    u32 page_shift, u32 window_shift)
1409 {
1410 	struct dynamic_dma_window_prop *ddwprop;
1411 	struct property *win64;
1412 
1413 	win64 = kzalloc_obj(*win64);
1414 	if (!win64)
1415 		return NULL;
1416 
1417 	win64->name = kstrdup(propname, GFP_KERNEL);
1418 	ddwprop = kzalloc_obj(*ddwprop);
1419 	win64->value = ddwprop;
1420 	win64->length = sizeof(*ddwprop);
1421 	if (!win64->name || !win64->value) {
1422 		kfree(win64->name);
1423 		kfree(win64->value);
1424 		kfree(win64);
1425 		return NULL;
1426 	}
1427 
1428 	ddwprop->liobn = cpu_to_be32(liobn);
1429 	ddwprop->dma_base = cpu_to_be64(dma_addr);
1430 	ddwprop->tce_shift = cpu_to_be32(page_shift);
1431 	ddwprop->window_shift = cpu_to_be32(window_shift);
1432 
1433 	return win64;
1434 }
1435 
1436 /*
1437  * If the PE supports dynamic dma windows, and there is space for a table
1438  * that can map all pages in a linear offset, then setup such a table,
1439  * and record the dma-offset in the struct device.
1440  *
1441  * dev: the pci device we are checking
1442  * pdn: the parent pe node with the ibm,dma_window property
1443  * Future: also check if we can remap the base window for our base page size
1444  *
1445  * returns true if can map all pages (direct mapping), false otherwise..
1446  */
1447 static bool enable_ddw(struct pci_dev *dev, struct device_node *pdn, u64 dma_mask)
1448 {
1449 	int len = 0, ret;
1450 	int max_ram_len = order_base_2(ddw_memory_hotplug_max());
1451 	struct ddw_query_response query;
1452 	struct ddw_create_response create;
1453 	int page_shift;
1454 	u64 win_addr, dynamic_offset = 0;
1455 	const char *win_name;
1456 	struct device_node *dn;
1457 	u32 ddw_avail[DDW_APPLICABLE_SIZE];
1458 	struct dma_win *window;
1459 	struct property *win64;
1460 	struct failed_ddw_pdn *fpdn;
1461 	bool default_win_removed = false, direct_mapping = false;
1462 	bool dynamic_mapping = false;
1463 	bool pmem_present;
1464 	struct pci_dn *pci = PCI_DN(pdn);
1465 	struct property *default_win = NULL;
1466 	bool limited_addr_req = false, limited_addr_enabled = false;
1467 	int dev_max_ddw;
1468 	int ddw_sz;
1469 
1470 	dn = of_find_node_by_type(NULL, "ibm,pmemory");
1471 	pmem_present = dn != NULL;
1472 	of_node_put(dn);
1473 
1474 	mutex_lock(&dma_win_init_mutex);
1475 
1476 	if (find_existing_ddw(pdn, &dev->dev.archdata.dma_offset, &len, &direct_mapping))
1477 		goto out_unlock;
1478 
1479 	/*
1480 	 * If we already went through this for a previous function of
1481 	 * the same device and failed, we don't want to muck with the
1482 	 * DMA window again, as it will race with in-flight operations
1483 	 * and can lead to EEHs. The above mutex protects access to the
1484 	 * list.
1485 	 */
1486 	list_for_each_entry(fpdn, &failed_ddw_pdn_list, list) {
1487 		if (fpdn->pdn == pdn)
1488 			goto out_unlock;
1489 	}
1490 
1491 	/*
1492 	 * the ibm,ddw-applicable property holds the tokens for:
1493 	 * ibm,query-pe-dma-window
1494 	 * ibm,create-pe-dma-window
1495 	 * for the given node in that order.
1496 	 * the property is actually in the parent, not the PE
1497 	 */
1498 	ret = of_property_read_u32_array(pdn, "ibm,ddw-applicable",
1499 					 &ddw_avail[0], DDW_APPLICABLE_SIZE);
1500 	if (ret)
1501 		goto out_failed;
1502 
1503        /*
1504 	 * Query if there is a second window of size to map the
1505 	 * whole partition.  Query returns number of windows, largest
1506 	 * block assigned to PE (partition endpoint), and two bitmasks
1507 	 * of page sizes: supported and supported for migrate-dma.
1508 	 */
1509 	dn = pci_device_to_OF_node(dev);
1510 	ret = query_ddw(dev, ddw_avail, &query, pdn);
1511 	if (ret != 0)
1512 		goto out_failed;
1513 
1514 	/* DMA Limited Addressing required? This is when the driver has
1515 	 * requested to create DDW but supports mask which is less than 64-bits
1516 	 */
1517 	limited_addr_req = (dma_mask != DMA_BIT_MASK(64));
1518 
1519 	/* place the PHB in Limited Addressing mode */
1520 	if (limited_addr_req) {
1521 		if (limited_dma_window(dev, pdn))
1522 			goto out_failed;
1523 
1524 		/* PHB is in Limited address mode */
1525 		limited_addr_enabled = true;
1526 	}
1527 
1528 	/*
1529 	 * If there is no window available, remove the default DMA window,
1530 	 * if it's present. This will make all the resources available to the
1531 	 * new DDW window.
1532 	 * If anything fails after this, we need to restore it, so also check
1533 	 * for extensions presence.
1534 	 */
1535 	if (query.windows_available == 0) {
1536 		int reset_win_ext;
1537 
1538 		/* DDW + IOMMU on single window may fail if there is any allocation */
1539 		if (iommu_table_in_use(pci->table_group->tables[0])) {
1540 			dev_warn(&dev->dev, "current IOMMU table in use, can't be replaced.\n");
1541 			goto out_failed;
1542 		}
1543 
1544 		default_win = of_find_property(pdn, "ibm,dma-window", NULL);
1545 		if (!default_win)
1546 			goto out_failed;
1547 
1548 		reset_win_ext = ddw_read_ext(pdn, DDW_EXT_RESET_DMA_WIN, NULL);
1549 		if (reset_win_ext)
1550 			goto out_failed;
1551 
1552 		remove_dma_window(pdn, ddw_avail, default_win, true);
1553 		default_win_removed = true;
1554 
1555 		/* Query again, to check if the window is available */
1556 		ret = query_ddw(dev, ddw_avail, &query, pdn);
1557 		if (ret != 0)
1558 			goto out_failed;
1559 
1560 		if (query.windows_available == 0) {
1561 			/* no windows are available for this device. */
1562 			dev_dbg(&dev->dev, "no free dynamic windows");
1563 			goto out_failed;
1564 		}
1565 	}
1566 
1567 	page_shift = iommu_get_page_shift(query.page_size);
1568 	if (!page_shift) {
1569 		dev_dbg(&dev->dev, "no supported page size in mask %x",
1570 			query.page_size);
1571 		goto out_failed;
1572 	}
1573 
1574 	/* Maximum DMA window size that the device can address (in log2) */
1575 	dev_max_ddw = fls64(dma_mask);
1576 
1577 	/* If the device DMA mask is less than 64-bits, make sure the DMA window
1578 	 * size is not bigger than what the device can access
1579 	 */
1580 	ddw_sz = min(order_base_2(query.largest_available_block << page_shift),
1581 			dev_max_ddw);
1582 
1583 	/*
1584 	 * The "ibm,pmemory" can appear anywhere in the address space.
1585 	 * Assuming it is still backed by page structs, try MAX_PHYSMEM_BITS
1586 	 * for the upper limit and fallback to max RAM otherwise but this
1587 	 * disables device::dma_ops_bypass.
1588 	 */
1589 	len = max_ram_len;
1590 	if (pmem_present) {
1591 		if (ddw_sz >= MAX_PHYSMEM_BITS)
1592 			len = MAX_PHYSMEM_BITS;
1593 		else
1594 			dev_info(&dev->dev, "Skipping ibm,pmemory");
1595 	}
1596 
1597 	/* check if the available block * number of ptes will map everything */
1598 	if (ddw_sz < len) {
1599 		dev_dbg(&dev->dev,
1600 			"can't map partition max 0x%llx with %llu %llu-sized pages\n",
1601 			1ULL << len,
1602 			query.largest_available_block,
1603 			1ULL << page_shift);
1604 
1605 		len = ddw_sz;
1606 		dynamic_mapping = true;
1607 	} else {
1608 		direct_mapping = !default_win_removed ||
1609 			(len == MAX_PHYSMEM_BITS) ||
1610 			(!pmem_present && (len == max_ram_len));
1611 
1612 		/* DDW is big enough to direct map RAM. If there is vPMEM, check
1613 		 * if enough space is left in DDW where we can dynamically
1614 		 * allocate TCEs for vPMEM. For now, this Hybrid sharing of DDW
1615 		 * is only for SR-IOV devices.
1616 		 */
1617 		if (default_win_removed && pmem_present && !direct_mapping) {
1618 			/* DDW is big enough to be split */
1619 			if ((1ULL << ddw_sz) >=
1620 			    MIN_DDW_VPMEM_DMA_WINDOW + (1ULL << max_ram_len)) {
1621 
1622 				direct_mapping = true;
1623 
1624 				/* offset of the Dynamic part of DDW */
1625 				dynamic_offset = 1ULL << max_ram_len;
1626 			}
1627 
1628 			/* DDW will at least have dynamic allocation */
1629 			dynamic_mapping = true;
1630 
1631 			/* create max size DDW possible */
1632 			len = ddw_sz;
1633 		}
1634 	}
1635 
1636 	/* Even if the DDW is split into both direct mapped RAM and dynamically
1637 	 * mapped vPMEM, the DDW property in OF will be marked as Direct.
1638 	 */
1639 	win_name = direct_mapping ? DIRECT64_PROPNAME : DMA64_PROPNAME;
1640 
1641 	ret = create_ddw(dev, ddw_avail, &create, page_shift, len);
1642 	if (ret != 0)
1643 		goto out_failed;
1644 
1645 	dev_dbg(&dev->dev, "created tce table LIOBN 0x%x for %pOF\n",
1646 		  create.liobn, dn);
1647 
1648 	win_addr = ((u64)create.addr_hi << 32) | create.addr_lo;
1649 	win64 = ddw_property_create(win_name, create.liobn, win_addr, page_shift, len);
1650 
1651 	if (!win64) {
1652 		dev_info(&dev->dev,
1653 			 "couldn't allocate property, property name, or value\n");
1654 		goto out_remove_win;
1655 	}
1656 
1657 	ret = of_add_property(pdn, win64);
1658 	if (ret) {
1659 		dev_err(&dev->dev, "unable to add DMA window property for %pOF: %d",
1660 			pdn, ret);
1661 		goto out_free_prop;
1662 	}
1663 
1664 	window = ddw_list_new_entry(pdn, win64->value);
1665 	if (!window)
1666 		goto out_del_prop;
1667 
1668 	window->direct = direct_mapping;
1669 
1670 	if (direct_mapping) {
1671 		/* DDW maps the whole partition, so enable direct DMA mapping */
1672 		ret = walk_system_ram_range(0, ddw_memory_hotplug_max() >> PAGE_SHIFT,
1673 					    win64->value, tce_setrange_multi_pSeriesLP_walk);
1674 		if (ret) {
1675 			dev_info(&dev->dev, "failed to map DMA window for %pOF: %d\n",
1676 				 dn, ret);
1677 
1678 			/* Make sure to clean DDW if any TCE was set*/
1679 			clean_dma_window(pdn, win64->value);
1680 			goto out_del_list;
1681 		}
1682 		if (default_win_removed) {
1683 			iommu_tce_table_put(pci->table_group->tables[0]);
1684 			pci->table_group->tables[0] = NULL;
1685 			set_iommu_table_base(&dev->dev, NULL);
1686 		}
1687 	}
1688 
1689 	if (dynamic_mapping) {
1690 		struct iommu_table *newtbl;
1691 		int i;
1692 		unsigned long start = 0, end = 0;
1693 		u64 dynamic_addr, dynamic_len;
1694 
1695 		for (i = 0; i < ARRAY_SIZE(pci->phb->mem_resources); i++) {
1696 			const unsigned long mask = IORESOURCE_MEM_64 | IORESOURCE_MEM;
1697 
1698 			/* Look for MMIO32 */
1699 			if ((pci->phb->mem_resources[i].flags & mask) == IORESOURCE_MEM) {
1700 				start = pci->phb->mem_resources[i].start;
1701 				end = pci->phb->mem_resources[i].end;
1702 				break;
1703 			}
1704 		}
1705 
1706 		/* New table for using DDW instead of the default DMA window */
1707 		newtbl = iommu_pseries_alloc_table(pci->phb->node);
1708 		if (!newtbl) {
1709 			dev_dbg(&dev->dev, "couldn't create new IOMMU table\n");
1710 			goto out_del_list;
1711 		}
1712 
1713 		/* If the DDW is split between directly mapped RAM and Dynamic
1714 		 * mapped for TCES, offset into the DDW where the dynamic part
1715 		 * begins.
1716 		 */
1717 		dynamic_addr = win_addr + dynamic_offset;
1718 		dynamic_len = (1UL << len) - dynamic_offset;
1719 		iommu_table_setparms_common(newtbl, pci->phb->bus->number, create.liobn,
1720 					    dynamic_addr, dynamic_len, page_shift, NULL,
1721 					    &iommu_table_lpar_multi_ops);
1722 		iommu_init_table(newtbl, pci->phb->node,
1723 				 start >> page_shift, end >> page_shift);
1724 
1725 		pci->table_group->tables[default_win_removed ? 0 : 1] = newtbl;
1726 
1727 		set_iommu_table_base(&dev->dev, newtbl);
1728 	}
1729 
1730 	if (default_win_removed) {
1731 		/* default_win is valid here because default_win_removed == true */
1732 		if (!of_find_property(pdn, "ibm,dma-window-saved", NULL))
1733 			copy_property(pdn, "ibm,dma-window", "ibm,dma-window-saved");
1734 		of_remove_property(pdn, default_win);
1735 		dev_info(&dev->dev, "Removed default DMA window for %pOF\n", pdn);
1736 	}
1737 
1738 	spin_lock(&dma_win_list_lock);
1739 	list_add(&window->list, &dma_win_list);
1740 	spin_unlock(&dma_win_list_lock);
1741 
1742 	dev->dev.archdata.dma_offset = win_addr;
1743 	goto out_unlock;
1744 
1745 out_del_list:
1746 	kfree(window);
1747 
1748 out_del_prop:
1749 	of_remove_property(pdn, win64);
1750 
1751 out_free_prop:
1752 	kfree(win64->name);
1753 	kfree(win64->value);
1754 	kfree(win64);
1755 
1756 out_remove_win:
1757 	/* DDW is clean, so it's ok to call this directly. */
1758 	__remove_dma_window(pdn, ddw_avail, create.liobn);
1759 
1760 out_failed:
1761 	if (default_win_removed || limited_addr_enabled)
1762 		reset_dma_window(dev, pdn);
1763 
1764 	fpdn = kzalloc_obj(*fpdn);
1765 	if (!fpdn)
1766 		goto out_unlock;
1767 	fpdn->pdn = pdn;
1768 	list_add(&fpdn->list, &failed_ddw_pdn_list);
1769 
1770 out_unlock:
1771 	mutex_unlock(&dma_win_init_mutex);
1772 
1773 	/* For pre-mapped memory, set bus_dma_limit to the max RAM */
1774 	if (direct_mapping)
1775 		dev->dev.bus_dma_limit = dev->dev.archdata.dma_offset +
1776 						(1ULL << max_ram_len);
1777 
1778 	dev_info(&dev->dev, "lsa_required: %x, lsa_enabled: %x, direct mapping: %x\n",
1779 			limited_addr_req, limited_addr_enabled, direct_mapping);
1780 
1781 	return direct_mapping;
1782 }
1783 
1784 static __u64 query_page_size_to_mask(u32 query_page_size)
1785 {
1786 	const long shift[] = {
1787 		(SZ_4K),   (SZ_64K), (SZ_16M),
1788 		(SZ_32M),  (SZ_64M), (SZ_128M),
1789 		(SZ_256M), (SZ_16G), (SZ_2M)
1790 	};
1791 	int i, ret = 0;
1792 
1793 	for (i = 0; i < ARRAY_SIZE(shift); i++) {
1794 		if (query_page_size & (1 << i))
1795 			ret |= shift[i];
1796 	}
1797 
1798 	return ret;
1799 }
1800 
1801 static void spapr_tce_init_table_group(struct pci_dev *pdev,
1802 				       struct device_node *pdn,
1803 				       struct dynamic_dma_window_prop prop)
1804 {
1805 	struct iommu_table_group  *table_group = PCI_DN(pdn)->table_group;
1806 	u32 ddw_avail[DDW_APPLICABLE_SIZE];
1807 
1808 	struct ddw_query_response query;
1809 	int ret;
1810 
1811 	/* Only for normal boot with default window. Doesn't matter during
1812 	 * kdump, since these will not be used during kdump.
1813 	 */
1814 	if (is_kdump_kernel())
1815 		return;
1816 
1817 	if (table_group->max_dynamic_windows_supported != 0)
1818 		return; /* already initialized */
1819 
1820 	table_group->tce32_start = be64_to_cpu(prop.dma_base);
1821 	table_group->tce32_size = 1 << be32_to_cpu(prop.window_shift);
1822 
1823 	if (!of_find_property(pdn, "ibm,dma-window", NULL))
1824 		dev_err(&pdev->dev, "default dma window missing!\n");
1825 
1826 	ret = of_property_read_u32_array(pdn, "ibm,ddw-applicable",
1827 			&ddw_avail[0], DDW_APPLICABLE_SIZE);
1828 	if (ret) {
1829 		table_group->max_dynamic_windows_supported = -1;
1830 		return;
1831 	}
1832 
1833 	ret = query_ddw(pdev, ddw_avail, &query, pdn);
1834 	if (ret) {
1835 		dev_err(&pdev->dev, "%s: query_ddw failed\n", __func__);
1836 		table_group->max_dynamic_windows_supported = -1;
1837 		return;
1838 	}
1839 
1840 	if (query.windows_available == 0)
1841 		table_group->max_dynamic_windows_supported = 1;
1842 	else
1843 		table_group->max_dynamic_windows_supported = IOMMU_TABLE_GROUP_MAX_TABLES;
1844 
1845 	table_group->max_levels = 1;
1846 	table_group->pgsizes |= query_page_size_to_mask(query.page_size);
1847 }
1848 
1849 static void pci_dma_dev_setup_pSeriesLP(struct pci_dev *dev)
1850 {
1851 	struct device_node *pdn, *dn;
1852 	struct iommu_table *tbl;
1853 	struct pci_dn *pci;
1854 	struct dynamic_dma_window_prop prop;
1855 
1856 	pr_debug("pci_dma_dev_setup_pSeriesLP: %s\n", pci_name(dev));
1857 
1858 	/* dev setup for LPAR is a little tricky, since the device tree might
1859 	 * contain the dma-window properties per-device and not necessarily
1860 	 * for the bus. So we need to search upwards in the tree until we
1861 	 * either hit a dma-window property, OR find a parent with a table
1862 	 * already allocated.
1863 	 */
1864 	dn = pci_device_to_OF_node(dev);
1865 	pr_debug("  node is %pOF\n", dn);
1866 
1867 	pdn = pci_dma_find(dn, &prop);
1868 	if (!pdn || !PCI_DN(pdn)) {
1869 		printk(KERN_WARNING "pci_dma_dev_setup_pSeriesLP: "
1870 		       "no DMA window found for pci dev=%s dn=%pOF\n",
1871 				 pci_name(dev), dn);
1872 		return;
1873 	}
1874 	pr_debug("  parent is %pOF\n", pdn);
1875 
1876 	pci = PCI_DN(pdn);
1877 	if (!pci->table_group) {
1878 		pci->table_group = iommu_pseries_alloc_group(pci->phb->node);
1879 		tbl = pci->table_group->tables[0];
1880 
1881 		iommu_table_setparms_common(tbl, pci->phb->bus->number,
1882 				be32_to_cpu(prop.liobn),
1883 				be64_to_cpu(prop.dma_base),
1884 				1ULL << be32_to_cpu(prop.window_shift),
1885 				be32_to_cpu(prop.tce_shift), NULL,
1886 				&iommu_table_lpar_multi_ops);
1887 
1888 		iommu_init_table(tbl, pci->phb->node, 0, 0);
1889 		iommu_register_group(pci->table_group,
1890 				pci_domain_nr(pci->phb->bus), 0);
1891 		pr_debug("  created table: %p\n", pci->table_group);
1892 	} else {
1893 		pr_debug("  found DMA window, table: %p\n", pci->table_group);
1894 	}
1895 
1896 	spapr_tce_init_table_group(dev, pdn, prop);
1897 
1898 	set_iommu_table_base(&dev->dev, pci->table_group->tables[0]);
1899 	iommu_add_device(pci->table_group, &dev->dev);
1900 }
1901 
1902 static bool iommu_bypass_supported_pSeriesLP(struct pci_dev *pdev, u64 dma_mask)
1903 {
1904 	struct device_node *dn = pci_device_to_OF_node(pdev), *pdn;
1905 
1906 	/* For DDW, DMA mask should be more than 32-bits. For mask more then
1907 	 * 32-bits but less then 64-bits, DMA addressing is supported in
1908 	 * Limited Addressing mode.
1909 	 */
1910 	if (dma_mask <= DMA_BIT_MASK(32))
1911 		return false;
1912 
1913 	dev_dbg(&pdev->dev, "node is %pOF\n", dn);
1914 
1915 	/*
1916 	 * the device tree might contain the dma-window properties
1917 	 * per-device and not necessarily for the bus. So we need to
1918 	 * search upwards in the tree until we either hit a dma-window
1919 	 * property, OR find a parent with a table already allocated.
1920 	 */
1921 	pdn = pci_dma_find(dn, NULL);
1922 	if (pdn && PCI_DN(pdn))
1923 		return enable_ddw(pdev, pdn, dma_mask);
1924 
1925 	return false;
1926 }
1927 
1928 #ifdef CONFIG_IOMMU_API
1929 /*
1930  * A simple iommu_table_group_ops which only allows reusing the existing
1931  * iommu_table. This handles VFIO for POWER7 or the nested KVM.
1932  * The ops does not allow creating windows and only allows reusing the existing
1933  * one if it matches table_group->tce32_start/tce32_size/page_shift.
1934  */
1935 static unsigned long spapr_tce_get_table_size(__u32 page_shift,
1936 					      __u64 window_size, __u32 levels)
1937 {
1938 	unsigned long size;
1939 
1940 	if (levels > 1)
1941 		return ~0U;
1942 	size = window_size >> (page_shift - 3);
1943 	return size;
1944 }
1945 
1946 static struct pci_dev *iommu_group_get_first_pci_dev(struct iommu_group *group)
1947 {
1948 	struct pci_dev *pdev = NULL;
1949 	int ret;
1950 
1951 	/* No IOMMU group ? */
1952 	if (!group)
1953 		return NULL;
1954 
1955 	ret = iommu_group_for_each_dev(group, &pdev, dev_has_iommu_table);
1956 	if (!ret || !pdev)
1957 		return NULL;
1958 	return pdev;
1959 }
1960 
1961 static void restore_default_dma_window(struct pci_dev *pdev, struct device_node *pdn)
1962 {
1963 	reset_dma_window(pdev, pdn);
1964 	copy_property(pdn, "ibm,dma-window-saved", "ibm,dma-window");
1965 }
1966 
1967 static long remove_dynamic_dma_windows(struct pci_dev *pdev, struct device_node *pdn)
1968 {
1969 	struct pci_dn *pci = PCI_DN(pdn);
1970 	struct dma_win *window;
1971 	bool direct_mapping;
1972 	int len;
1973 
1974 	if (find_existing_ddw(pdn, &pdev->dev.archdata.dma_offset, &len, &direct_mapping)) {
1975 		remove_dma_window_named(pdn, true, direct_mapping ?
1976 						   DIRECT64_PROPNAME : DMA64_PROPNAME, true);
1977 		if (!direct_mapping) {
1978 			WARN_ON(!pci->table_group->tables[0] && !pci->table_group->tables[1]);
1979 
1980 			if (pci->table_group->tables[1]) {
1981 				iommu_tce_table_put(pci->table_group->tables[1]);
1982 				pci->table_group->tables[1] = NULL;
1983 			} else if (pci->table_group->tables[0]) {
1984 				/* Default window was removed and only the DDW exists */
1985 				iommu_tce_table_put(pci->table_group->tables[0]);
1986 				pci->table_group->tables[0] = NULL;
1987 			}
1988 		}
1989 		spin_lock(&dma_win_list_lock);
1990 		list_for_each_entry(window, &dma_win_list, list) {
1991 			if (window->device == pdn) {
1992 				list_del(&window->list);
1993 				kfree(window);
1994 				break;
1995 			}
1996 		}
1997 		spin_unlock(&dma_win_list_lock);
1998 	}
1999 
2000 	return 0;
2001 }
2002 
2003 static long pseries_setup_default_iommu_config(struct iommu_table_group *table_group,
2004 					       struct device *dev)
2005 {
2006 	struct pci_dev *pdev = to_pci_dev(dev);
2007 	const __be32 *default_prop;
2008 	long liobn, offset, size;
2009 	struct device_node *pdn;
2010 	struct iommu_table *tbl;
2011 	struct pci_dn *pci;
2012 
2013 	pdn = pci_dma_find_parent_node(pdev, table_group);
2014 	if (!pdn || !PCI_DN(pdn)) {
2015 		dev_warn(&pdev->dev, "No table_group configured for the node %pOF\n", pdn);
2016 		return -1;
2017 	}
2018 	pci = PCI_DN(pdn);
2019 
2020 	/* The default window is restored if not present already on removal of DDW.
2021 	 * However, if used by VFIO SPAPR sub driver, the user's order of removal of
2022 	 * windows might have been different to not leading to auto restoration,
2023 	 * suppose the DDW was removed first followed by the default one.
2024 	 * So, restore the default window with reset-pe-dma call explicitly.
2025 	 */
2026 	restore_default_dma_window(pdev, pdn);
2027 
2028 	default_prop = of_get_property(pdn, "ibm,dma-window", NULL);
2029 	of_parse_dma_window(pdn, default_prop, &liobn, &offset, &size);
2030 	tbl = iommu_pseries_alloc_table(pci->phb->node);
2031 	if (!tbl) {
2032 		dev_err(&pdev->dev, "couldn't create new IOMMU table\n");
2033 		return -1;
2034 	}
2035 
2036 	iommu_table_setparms_common(tbl, pci->phb->bus->number, liobn, offset,
2037 				    size, IOMMU_PAGE_SHIFT_4K, NULL,
2038 				    &iommu_table_lpar_multi_ops);
2039 	iommu_init_table(tbl, pci->phb->node, 0, 0);
2040 
2041 	pci->table_group->tables[0] = tbl;
2042 	set_iommu_table_base(&pdev->dev, tbl);
2043 
2044 	return 0;
2045 }
2046 
2047 static bool is_default_window_request(struct iommu_table_group *table_group, __u32 page_shift,
2048 				      __u64 window_size)
2049 {
2050 	if ((window_size <= table_group->tce32_size) &&
2051 	    (page_shift == IOMMU_PAGE_SHIFT_4K))
2052 		return true;
2053 
2054 	return false;
2055 }
2056 
2057 static long spapr_tce_create_table(struct iommu_table_group *table_group, int num,
2058 				   __u32 page_shift, __u64 window_size, __u32 levels,
2059 				   struct iommu_table **ptbl)
2060 {
2061 	struct pci_dev *pdev = iommu_group_get_first_pci_dev(table_group->group);
2062 	u32 ddw_avail[DDW_APPLICABLE_SIZE];
2063 	struct ddw_create_response create;
2064 	unsigned long liobn, offset, size;
2065 	unsigned long start = 0, end = 0;
2066 	struct ddw_query_response query;
2067 	const __be32 *default_prop;
2068 	struct failed_ddw_pdn *fpdn;
2069 	unsigned int window_shift;
2070 	struct device_node *pdn;
2071 	struct iommu_table *tbl;
2072 	struct dma_win *window;
2073 	struct property *win64;
2074 	struct pci_dn *pci;
2075 	u64 win_addr;
2076 	int len, i;
2077 	long ret;
2078 
2079 	if (!is_power_of_2(window_size) || levels > 1)
2080 		return -EINVAL;
2081 
2082 	window_shift = order_base_2(window_size);
2083 
2084 	mutex_lock(&dma_win_init_mutex);
2085 
2086 	ret = -ENODEV;
2087 
2088 	pdn = pci_dma_find_parent_node(pdev, table_group);
2089 	if (!pdn || !PCI_DN(pdn)) { /* Niether of 32s|64-bit exist! */
2090 		dev_warn(&pdev->dev, "No dma-windows exist for the node %pOF\n", pdn);
2091 		goto out_failed;
2092 	}
2093 	pci = PCI_DN(pdn);
2094 
2095 	/* If the enable DDW failed for the pdn, dont retry! */
2096 	list_for_each_entry(fpdn, &failed_ddw_pdn_list, list) {
2097 		if (fpdn->pdn == pdn) {
2098 			dev_info(&pdev->dev, "%pOF in failed DDW device list\n", pdn);
2099 			goto out_unlock;
2100 		}
2101 	}
2102 
2103 	tbl = iommu_pseries_alloc_table(pci->phb->node);
2104 	if (!tbl) {
2105 		dev_dbg(&pdev->dev, "couldn't create new IOMMU table\n");
2106 		goto out_unlock;
2107 	}
2108 
2109 	if (num == 0) {
2110 		bool direct_mapping;
2111 		/* The request is not for default window? Ensure there is no DDW window already */
2112 		if (!is_default_window_request(table_group, page_shift, window_size)) {
2113 			if (find_existing_ddw(pdn, &pdev->dev.archdata.dma_offset, &len,
2114 					      &direct_mapping)) {
2115 				dev_warn(&pdev->dev, "%pOF: 64-bit window already present.", pdn);
2116 				ret = -EPERM;
2117 				goto out_unlock;
2118 			}
2119 		} else {
2120 			/* Request is for Default window, ensure there is no DDW if there is a
2121 			 * need to reset. reset-pe otherwise removes the DDW also
2122 			 */
2123 			default_prop = of_get_property(pdn, "ibm,dma-window", NULL);
2124 			if (!default_prop) {
2125 				if (find_existing_ddw(pdn, &pdev->dev.archdata.dma_offset, &len,
2126 						      &direct_mapping)) {
2127 					dev_warn(&pdev->dev, "%pOF: Attempt to create window#0 when 64-bit window is present. Preventing the attempt as that would destroy the 64-bit window",
2128 						 pdn);
2129 					ret = -EPERM;
2130 					goto out_unlock;
2131 				}
2132 
2133 				restore_default_dma_window(pdev, pdn);
2134 
2135 				default_prop = of_get_property(pdn, "ibm,dma-window", NULL);
2136 				of_parse_dma_window(pdn, default_prop, &liobn, &offset, &size);
2137 				/* Limit the default window size to window_size */
2138 				iommu_table_setparms_common(tbl, pci->phb->bus->number, liobn,
2139 							    offset, 1UL << window_shift,
2140 							    IOMMU_PAGE_SHIFT_4K, NULL,
2141 							    &iommu_table_lpar_multi_ops);
2142 				iommu_init_table(tbl, pci->phb->node,
2143 						 start >> IOMMU_PAGE_SHIFT_4K,
2144 						 end >> IOMMU_PAGE_SHIFT_4K);
2145 
2146 				table_group->tables[0] = tbl;
2147 
2148 				mutex_unlock(&dma_win_init_mutex);
2149 
2150 				goto exit;
2151 			}
2152 		}
2153 	}
2154 
2155 	ret = of_property_read_u32_array(pdn, "ibm,ddw-applicable",
2156 				&ddw_avail[0], DDW_APPLICABLE_SIZE);
2157 	if (ret) {
2158 		dev_info(&pdev->dev, "ibm,ddw-applicable not found\n");
2159 		goto out_failed;
2160 	}
2161 	ret = -ENODEV;
2162 
2163 	pr_err("%s: Calling query %pOF\n", __func__, pdn);
2164 	ret = query_ddw(pdev, ddw_avail, &query, pdn);
2165 	if (ret)
2166 		goto out_failed;
2167 	ret = -ENODEV;
2168 
2169 	len = window_shift;
2170 	if (query.largest_available_block < (1ULL << (len - page_shift))) {
2171 		dev_dbg(&pdev->dev, "can't map window 0x%llx with %llu %llu-sized pages\n",
2172 				1ULL << len, query.largest_available_block,
2173 				1ULL << page_shift);
2174 		ret = -EINVAL; /* Retry with smaller window size */
2175 		goto out_unlock;
2176 	}
2177 
2178 	if (create_ddw(pdev, ddw_avail, &create, page_shift, len)) {
2179 		pr_err("%s: Create ddw failed %pOF\n", __func__, pdn);
2180 		goto out_failed;
2181 	}
2182 
2183 	win_addr = ((u64)create.addr_hi << 32) | create.addr_lo;
2184 	win64 = ddw_property_create(DMA64_PROPNAME, create.liobn, win_addr, page_shift, len);
2185 	if (!win64)
2186 		goto remove_window;
2187 
2188 	ret = of_add_property(pdn, win64);
2189 	if (ret) {
2190 		dev_err(&pdev->dev, "unable to add DMA window property for %pOF: %ld", pdn, ret);
2191 		goto free_property;
2192 	}
2193 	ret = -ENODEV;
2194 
2195 	window = ddw_list_new_entry(pdn, win64->value);
2196 	if (!window)
2197 		goto remove_property;
2198 
2199 	window->direct = false;
2200 
2201 	for (i = 0; i < ARRAY_SIZE(pci->phb->mem_resources); i++) {
2202 		const unsigned long mask = IORESOURCE_MEM_64 | IORESOURCE_MEM;
2203 
2204 		/* Look for MMIO32 */
2205 		if ((pci->phb->mem_resources[i].flags & mask) == IORESOURCE_MEM) {
2206 			start = pci->phb->mem_resources[i].start;
2207 			end = pci->phb->mem_resources[i].end;
2208 				break;
2209 		}
2210 	}
2211 
2212 	/* New table for using DDW instead of the default DMA window */
2213 	iommu_table_setparms_common(tbl, pci->phb->bus->number, create.liobn, win_addr,
2214 				    1UL << len, page_shift, NULL, &iommu_table_lpar_multi_ops);
2215 	iommu_init_table(tbl, pci->phb->node, start >> page_shift, end >> page_shift);
2216 
2217 	pci->table_group->tables[num] = tbl;
2218 	set_iommu_table_base(&pdev->dev, tbl);
2219 	pdev->dev.archdata.dma_offset = win_addr;
2220 
2221 	spin_lock(&dma_win_list_lock);
2222 	list_add(&window->list, &dma_win_list);
2223 	spin_unlock(&dma_win_list_lock);
2224 
2225 	mutex_unlock(&dma_win_init_mutex);
2226 
2227 	goto exit;
2228 
2229 remove_property:
2230 	of_remove_property(pdn, win64);
2231 free_property:
2232 	kfree(win64->name);
2233 	kfree(win64->value);
2234 	kfree(win64);
2235 remove_window:
2236 	__remove_dma_window(pdn, ddw_avail, create.liobn);
2237 
2238 out_failed:
2239 	fpdn = kzalloc_obj(*fpdn);
2240 	if (!fpdn)
2241 		goto out_unlock;
2242 	fpdn->pdn = pdn;
2243 	list_add(&fpdn->list, &failed_ddw_pdn_list);
2244 
2245 out_unlock:
2246 	mutex_unlock(&dma_win_init_mutex);
2247 
2248 	return ret;
2249 exit:
2250 	/* Allocate the userspace view */
2251 	pseries_tce_iommu_userspace_view_alloc(tbl);
2252 	tbl->it_allocated_size = spapr_tce_get_table_size(page_shift, window_size, levels);
2253 
2254 	*ptbl = iommu_tce_table_get(tbl);
2255 
2256 	return 0;
2257 }
2258 
2259 static bool is_default_window_table(struct iommu_table_group *table_group, struct iommu_table *tbl)
2260 {
2261 	if (((tbl->it_size << tbl->it_page_shift)  <= table_group->tce32_size) &&
2262 	    (tbl->it_page_shift == IOMMU_PAGE_SHIFT_4K))
2263 		return true;
2264 
2265 	return false;
2266 }
2267 
2268 static long spapr_tce_set_window(struct iommu_table_group *table_group,
2269 				 int num, struct iommu_table *tbl)
2270 {
2271 	return tbl == table_group->tables[num] ? 0 : -EPERM;
2272 }
2273 
2274 static long spapr_tce_unset_window(struct iommu_table_group *table_group, int num)
2275 {
2276 	struct pci_dev *pdev = iommu_group_get_first_pci_dev(table_group->group);
2277 	struct device_node *dn = pci_device_to_OF_node(pdev), *pdn;
2278 	struct iommu_table *tbl = table_group->tables[num];
2279 	struct failed_ddw_pdn *fpdn;
2280 	struct dma_win *window;
2281 	const char *win_name;
2282 	int ret = -ENODEV;
2283 
2284 	if (!tbl) /* The table was never created OR window was never opened */
2285 		return 0;
2286 
2287 	mutex_lock(&dma_win_init_mutex);
2288 
2289 	if ((num == 0) && is_default_window_table(table_group, tbl))
2290 		win_name = "ibm,dma-window";
2291 	else
2292 		win_name = DMA64_PROPNAME;
2293 
2294 	pdn = pci_dma_find(dn, NULL);
2295 	if (!pdn || !PCI_DN(pdn)) { /* Niether of 32s|64-bit exist! */
2296 		dev_warn(&pdev->dev, "No dma-windows exist for the node %pOF\n", pdn);
2297 		goto out_failed;
2298 	}
2299 
2300 	/* Dont clear the TCEs, User should have done it */
2301 	if (remove_dma_window_named(pdn, true, win_name, false)) {
2302 		pr_err("%s: The existing DDW removal failed for node %pOF\n", __func__, pdn);
2303 		goto out_failed; /* Could not remove it either! */
2304 	}
2305 
2306 	if (strcmp(win_name, DMA64_PROPNAME) == 0) {
2307 		spin_lock(&dma_win_list_lock);
2308 		list_for_each_entry(window, &dma_win_list, list) {
2309 			if (window->device == pdn) {
2310 				list_del(&window->list);
2311 				kfree(window);
2312 				break;
2313 			}
2314 		}
2315 		spin_unlock(&dma_win_list_lock);
2316 	}
2317 
2318 	iommu_tce_table_put(table_group->tables[num]);
2319 	table_group->tables[num] = NULL;
2320 
2321 	ret = 0;
2322 
2323 	goto out_unlock;
2324 
2325 out_failed:
2326 	fpdn = kzalloc_obj(*fpdn);
2327 	if (!fpdn)
2328 		goto out_unlock;
2329 	fpdn->pdn = pdn;
2330 	list_add(&fpdn->list, &failed_ddw_pdn_list);
2331 
2332 out_unlock:
2333 	mutex_unlock(&dma_win_init_mutex);
2334 
2335 	return ret;
2336 }
2337 
2338 static long spapr_tce_take_ownership(struct iommu_table_group *table_group, struct device *dev)
2339 {
2340 	struct iommu_table *tbl = table_group->tables[0];
2341 	struct pci_dev *pdev = to_pci_dev(dev);
2342 	struct device_node *dn = pci_device_to_OF_node(pdev);
2343 	struct device_node *pdn;
2344 
2345 	/* SRIOV VFs using direct map by the host driver OR multifunction devices
2346 	 * where the ownership was taken on the attempt by the first function
2347 	 */
2348 	if (!tbl && (table_group->max_dynamic_windows_supported != 1))
2349 		return 0;
2350 
2351 	mutex_lock(&dma_win_init_mutex);
2352 
2353 	pdn = pci_dma_find(dn, NULL);
2354 	if (!pdn || !PCI_DN(pdn)) { /* Niether of 32s|64-bit exist! */
2355 		dev_warn(&pdev->dev, "No dma-windows exist for the node %pOF\n", pdn);
2356 		mutex_unlock(&dma_win_init_mutex);
2357 		return -1;
2358 	}
2359 
2360 	/*
2361 	 * Though rtas call reset-pe removes the DDW, it doesn't clear the entries on the table
2362 	 * if there are any. In case of direct map, the entries will be left over, which
2363 	 * is fine for PEs with 2 DMA windows where the second window is created with create-pe
2364 	 * at which point the table is cleared. However, on VFs having only one DMA window, the
2365 	 * default window would end up seeing the entries left over from the direct map done
2366 	 * on the second window. So, remove the ddw explicitly so that clean_dma_window()
2367 	 * cleans up the entries if any.
2368 	 */
2369 	if (remove_dynamic_dma_windows(pdev, pdn)) {
2370 		dev_warn(&pdev->dev, "The existing DDW removal failed for node %pOF\n", pdn);
2371 		mutex_unlock(&dma_win_init_mutex);
2372 		return -1;
2373 	}
2374 
2375 	/* The table_group->tables[0] is not null now, it must be the default window
2376 	 * Remove it, let the userspace create it as it needs.
2377 	 */
2378 	if (table_group->tables[0]) {
2379 		remove_dma_window_named(pdn, true, "ibm,dma-window", true);
2380 		iommu_tce_table_put(tbl);
2381 		table_group->tables[0] = NULL;
2382 	}
2383 	set_iommu_table_base(dev, NULL);
2384 
2385 	mutex_unlock(&dma_win_init_mutex);
2386 
2387 	return 0;
2388 }
2389 
2390 static void spapr_tce_release_ownership(struct iommu_table_group *table_group, struct device *dev)
2391 {
2392 	struct iommu_table *tbl = table_group->tables[0];
2393 
2394 	if (tbl) { /* Default window already restored */
2395 		return;
2396 	}
2397 
2398 	mutex_lock(&dma_win_init_mutex);
2399 
2400 	/* Restore the default window */
2401 	pseries_setup_default_iommu_config(table_group, dev);
2402 
2403 	mutex_unlock(&dma_win_init_mutex);
2404 
2405 	return;
2406 }
2407 
2408 static struct iommu_table_group_ops spapr_tce_table_group_ops = {
2409 	.get_table_size = spapr_tce_get_table_size,
2410 	.create_table = spapr_tce_create_table,
2411 	.set_window = spapr_tce_set_window,
2412 	.unset_window = spapr_tce_unset_window,
2413 	.take_ownership = spapr_tce_take_ownership,
2414 	.release_ownership = spapr_tce_release_ownership,
2415 };
2416 #endif
2417 
2418 static int iommu_mem_notifier(struct notifier_block *nb, unsigned long action,
2419 		void *data)
2420 {
2421 	struct dma_win *window;
2422 	struct memory_notify *arg = data;
2423 	int ret = 0;
2424 
2425 	/* This notifier can get called when onlining persistent memory as well.
2426 	 * TCEs are not pre-mapped for persistent memory. Persistent memory will
2427 	 * always be above ddw_memory_hotplug_max()
2428 	 */
2429 
2430 	switch (action) {
2431 	case MEM_GOING_ONLINE:
2432 		spin_lock(&dma_win_list_lock);
2433 		list_for_each_entry(window, &dma_win_list, list) {
2434 			if (window->direct && (arg->start_pfn << PAGE_SHIFT) <
2435 				ddw_memory_hotplug_max()) {
2436 				ret |= tce_setrange_multi_pSeriesLP(arg->start_pfn,
2437 						arg->nr_pages, window->prop);
2438 			}
2439 			/* XXX log error */
2440 		}
2441 		spin_unlock(&dma_win_list_lock);
2442 		break;
2443 	case MEM_CANCEL_ONLINE:
2444 	case MEM_OFFLINE:
2445 		spin_lock(&dma_win_list_lock);
2446 		list_for_each_entry(window, &dma_win_list, list) {
2447 			if (window->direct && (arg->start_pfn << PAGE_SHIFT) <
2448 				ddw_memory_hotplug_max()) {
2449 				ret |= tce_clearrange_multi_pSeriesLP(arg->start_pfn,
2450 						arg->nr_pages, window->prop);
2451 			}
2452 			/* XXX log error */
2453 		}
2454 		spin_unlock(&dma_win_list_lock);
2455 		break;
2456 	default:
2457 		break;
2458 	}
2459 	if (ret && action != MEM_CANCEL_ONLINE)
2460 		return NOTIFY_BAD;
2461 
2462 	return NOTIFY_OK;
2463 }
2464 
2465 static struct notifier_block iommu_mem_nb = {
2466 	.notifier_call = iommu_mem_notifier,
2467 };
2468 
2469 static int iommu_reconfig_notifier(struct notifier_block *nb, unsigned long action, void *data)
2470 {
2471 	int err = NOTIFY_OK;
2472 	struct of_reconfig_data *rd = data;
2473 	struct device_node *np = rd->dn;
2474 	struct pci_dn *pci = PCI_DN(np);
2475 	struct dma_win *window;
2476 
2477 	switch (action) {
2478 	case OF_RECONFIG_DETACH_NODE:
2479 		/*
2480 		 * Removing the property will invoke the reconfig
2481 		 * notifier again, which causes dead-lock on the
2482 		 * read-write semaphore of the notifier chain. So
2483 		 * we have to remove the property when releasing
2484 		 * the device node.
2485 		 */
2486 		if (remove_dma_window_named(np, false, DIRECT64_PROPNAME, true))
2487 			remove_dma_window_named(np, false, DMA64_PROPNAME, true);
2488 
2489 		if (pci && pci->table_group)
2490 			iommu_pseries_free_group(pci->table_group,
2491 					np->full_name);
2492 
2493 		spin_lock(&dma_win_list_lock);
2494 		list_for_each_entry(window, &dma_win_list, list) {
2495 			if (window->device == np) {
2496 				list_del(&window->list);
2497 				kfree(window);
2498 				break;
2499 			}
2500 		}
2501 		spin_unlock(&dma_win_list_lock);
2502 		break;
2503 	default:
2504 		err = NOTIFY_DONE;
2505 		break;
2506 	}
2507 	return err;
2508 }
2509 
2510 static struct notifier_block iommu_reconfig_nb = {
2511 	.notifier_call = iommu_reconfig_notifier,
2512 };
2513 
2514 /* These are called very early. */
2515 void __init iommu_init_early_pSeries(void)
2516 {
2517 	if (of_chosen && of_get_property(of_chosen, "linux,iommu-off", NULL))
2518 		return;
2519 
2520 	if (firmware_has_feature(FW_FEATURE_LPAR)) {
2521 		pseries_pci_controller_ops.dma_bus_setup = pci_dma_bus_setup_pSeriesLP;
2522 		pseries_pci_controller_ops.dma_dev_setup = pci_dma_dev_setup_pSeriesLP;
2523 		if (!disable_ddw)
2524 			pseries_pci_controller_ops.iommu_bypass_supported =
2525 				iommu_bypass_supported_pSeriesLP;
2526 	} else {
2527 		pseries_pci_controller_ops.dma_bus_setup = pci_dma_bus_setup_pSeries;
2528 		pseries_pci_controller_ops.dma_dev_setup = pci_dma_dev_setup_pSeries;
2529 	}
2530 
2531 
2532 	of_reconfig_notifier_register(&iommu_reconfig_nb);
2533 	register_memory_notifier(&iommu_mem_nb);
2534 
2535 	set_pci_dma_ops(&dma_iommu_ops);
2536 }
2537 
2538 static int __init disable_multitce(char *str)
2539 {
2540 	if (strcmp(str, "off") == 0 &&
2541 	    firmware_has_feature(FW_FEATURE_LPAR) &&
2542 	    (firmware_has_feature(FW_FEATURE_PUT_TCE_IND) ||
2543 	     firmware_has_feature(FW_FEATURE_STUFF_TCE))) {
2544 		printk(KERN_INFO "Disabling MULTITCE firmware feature\n");
2545 		powerpc_firmware_features &=
2546 			~(FW_FEATURE_PUT_TCE_IND | FW_FEATURE_STUFF_TCE);
2547 	}
2548 	return 1;
2549 }
2550 
2551 __setup("multitce=", disable_multitce);
2552 
2553 #ifdef CONFIG_SPAPR_TCE_IOMMU
2554 struct iommu_group *pSeries_pci_device_group(struct pci_controller *hose,
2555 					     struct pci_dev *pdev)
2556 {
2557 	struct device_node *pdn, *dn = pdev->dev.of_node;
2558 	struct iommu_group *grp;
2559 	struct pci_dn *pci;
2560 
2561 	pdn = pci_dma_find(dn, NULL);
2562 	if (!pdn || !PCI_DN(pdn))
2563 		return ERR_PTR(-ENODEV);
2564 
2565 	pci = PCI_DN(pdn);
2566 	if (!pci->table_group)
2567 		return ERR_PTR(-ENODEV);
2568 
2569 	grp = pci->table_group->group;
2570 	if (!grp)
2571 		return ERR_PTR(-ENODEV);
2572 
2573 	return iommu_group_ref_get(grp);
2574 }
2575 #endif
2576