xref: /linux/arch/powerpc/kernel/iommu.c (revision ff40b5769a50fab654a70575ff0f49853b799b0e)
1 // SPDX-License-Identifier: GPL-2.0-or-later
2 /*
3  * Copyright (C) 2001 Mike Corrigan & Dave Engebretsen, IBM Corporation
4  *
5  * Rewrite, cleanup, new allocation schemes, virtual merging:
6  * Copyright (C) 2004 Olof Johansson, IBM Corporation
7  *               and  Ben. Herrenschmidt, IBM Corporation
8  *
9  * Dynamic DMA mapping support, bus-independent parts.
10  */
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/spinlock.h>
18 #include <linux/string.h>
19 #include <linux/dma-mapping.h>
20 #include <linux/bitmap.h>
21 #include <linux/iommu-helper.h>
22 #include <linux/crash_dump.h>
23 #include <linux/hash.h>
24 #include <linux/fault-inject.h>
25 #include <linux/pci.h>
26 #include <linux/iommu.h>
27 #include <linux/sched.h>
28 #include <linux/debugfs.h>
29 #include <asm/io.h>
30 #include <asm/iommu.h>
31 #include <asm/pci-bridge.h>
32 #include <asm/machdep.h>
33 #include <asm/kdump.h>
34 #include <asm/fadump.h>
35 #include <asm/vio.h>
36 #include <asm/tce.h>
37 #include <asm/mmu_context.h>
38 #include <asm/ppc-pci.h>
39 
40 #define DBG(...)
41 
42 #ifdef CONFIG_IOMMU_DEBUGFS
43 static int iommu_debugfs_weight_get(void *data, u64 *val)
44 {
45 	struct iommu_table *tbl = data;
46 	*val = bitmap_weight(tbl->it_map, tbl->it_size);
47 	return 0;
48 }
49 DEFINE_DEBUGFS_ATTRIBUTE(iommu_debugfs_fops_weight, iommu_debugfs_weight_get, NULL, "%llu\n");
50 
51 static void iommu_debugfs_add(struct iommu_table *tbl)
52 {
53 	char name[10];
54 	struct dentry *liobn_entry;
55 
56 	sprintf(name, "%08lx", tbl->it_index);
57 	liobn_entry = debugfs_create_dir(name, iommu_debugfs_dir);
58 
59 	debugfs_create_file_unsafe("weight", 0400, liobn_entry, tbl, &iommu_debugfs_fops_weight);
60 	debugfs_create_ulong("it_size", 0400, liobn_entry, &tbl->it_size);
61 	debugfs_create_ulong("it_page_shift", 0400, liobn_entry, &tbl->it_page_shift);
62 	debugfs_create_ulong("it_reserved_start", 0400, liobn_entry, &tbl->it_reserved_start);
63 	debugfs_create_ulong("it_reserved_end", 0400, liobn_entry, &tbl->it_reserved_end);
64 	debugfs_create_ulong("it_indirect_levels", 0400, liobn_entry, &tbl->it_indirect_levels);
65 	debugfs_create_ulong("it_level_size", 0400, liobn_entry, &tbl->it_level_size);
66 }
67 
68 static void iommu_debugfs_del(struct iommu_table *tbl)
69 {
70 	char name[10];
71 
72 	sprintf(name, "%08lx", tbl->it_index);
73 	debugfs_lookup_and_remove(name, iommu_debugfs_dir);
74 }
75 #else
76 static void iommu_debugfs_add(struct iommu_table *tbl){}
77 static void iommu_debugfs_del(struct iommu_table *tbl){}
78 #endif
79 
80 static int novmerge;
81 
82 static void __iommu_free(struct iommu_table *, dma_addr_t, unsigned int);
83 
84 static int __init setup_iommu(char *str)
85 {
86 	if (!strcmp(str, "novmerge"))
87 		novmerge = 1;
88 	else if (!strcmp(str, "vmerge"))
89 		novmerge = 0;
90 	return 1;
91 }
92 
93 __setup("iommu=", setup_iommu);
94 
95 static DEFINE_PER_CPU(unsigned int, iommu_pool_hash);
96 
97 /*
98  * We precalculate the hash to avoid doing it on every allocation.
99  *
100  * The hash is important to spread CPUs across all the pools. For example,
101  * on a POWER7 with 4 way SMT we want interrupts on the primary threads and
102  * with 4 pools all primary threads would map to the same pool.
103  */
104 static int __init setup_iommu_pool_hash(void)
105 {
106 	unsigned int i;
107 
108 	for_each_possible_cpu(i)
109 		per_cpu(iommu_pool_hash, i) = hash_32(i, IOMMU_POOL_HASHBITS);
110 
111 	return 0;
112 }
113 subsys_initcall(setup_iommu_pool_hash);
114 
115 #ifdef CONFIG_FAIL_IOMMU
116 
117 static DECLARE_FAULT_ATTR(fail_iommu);
118 
119 static int __init setup_fail_iommu(char *str)
120 {
121 	return setup_fault_attr(&fail_iommu, str);
122 }
123 __setup("fail_iommu=", setup_fail_iommu);
124 
125 static bool should_fail_iommu(struct device *dev)
126 {
127 	return dev->archdata.fail_iommu && should_fail(&fail_iommu, 1);
128 }
129 
130 static int __init fail_iommu_debugfs(void)
131 {
132 	struct dentry *dir = fault_create_debugfs_attr("fail_iommu",
133 						       NULL, &fail_iommu);
134 
135 	return PTR_ERR_OR_ZERO(dir);
136 }
137 late_initcall(fail_iommu_debugfs);
138 
139 static ssize_t fail_iommu_show(struct device *dev,
140 			       struct device_attribute *attr, char *buf)
141 {
142 	return sprintf(buf, "%d\n", dev->archdata.fail_iommu);
143 }
144 
145 static ssize_t fail_iommu_store(struct device *dev,
146 				struct device_attribute *attr, const char *buf,
147 				size_t count)
148 {
149 	int i;
150 
151 	if (count > 0 && sscanf(buf, "%d", &i) > 0)
152 		dev->archdata.fail_iommu = (i == 0) ? 0 : 1;
153 
154 	return count;
155 }
156 
157 static DEVICE_ATTR_RW(fail_iommu);
158 
159 static int fail_iommu_bus_notify(struct notifier_block *nb,
160 				 unsigned long action, void *data)
161 {
162 	struct device *dev = data;
163 
164 	if (action == BUS_NOTIFY_ADD_DEVICE) {
165 		if (device_create_file(dev, &dev_attr_fail_iommu))
166 			pr_warn("Unable to create IOMMU fault injection sysfs "
167 				"entries\n");
168 	} else if (action == BUS_NOTIFY_DEL_DEVICE) {
169 		device_remove_file(dev, &dev_attr_fail_iommu);
170 	}
171 
172 	return 0;
173 }
174 
175 static struct notifier_block fail_iommu_bus_notifier = {
176 	.notifier_call = fail_iommu_bus_notify
177 };
178 
179 static int __init fail_iommu_setup(void)
180 {
181 #ifdef CONFIG_PCI
182 	bus_register_notifier(&pci_bus_type, &fail_iommu_bus_notifier);
183 #endif
184 #ifdef CONFIG_IBMVIO
185 	bus_register_notifier(&vio_bus_type, &fail_iommu_bus_notifier);
186 #endif
187 
188 	return 0;
189 }
190 /*
191  * Must execute after PCI and VIO subsystem have initialised but before
192  * devices are probed.
193  */
194 arch_initcall(fail_iommu_setup);
195 #else
196 static inline bool should_fail_iommu(struct device *dev)
197 {
198 	return false;
199 }
200 #endif
201 
202 static unsigned long iommu_range_alloc(struct device *dev,
203 				       struct iommu_table *tbl,
204                                        unsigned long npages,
205                                        unsigned long *handle,
206                                        unsigned long mask,
207                                        unsigned int align_order)
208 {
209 	unsigned long n, end, start;
210 	unsigned long limit;
211 	int largealloc = npages > 15;
212 	int pass = 0;
213 	unsigned long align_mask;
214 	unsigned long flags;
215 	unsigned int pool_nr;
216 	struct iommu_pool *pool;
217 
218 	align_mask = (1ull << align_order) - 1;
219 
220 	/* This allocator was derived from x86_64's bit string search */
221 
222 	/* Sanity check */
223 	if (unlikely(npages == 0)) {
224 		if (printk_ratelimit())
225 			WARN_ON(1);
226 		return DMA_MAPPING_ERROR;
227 	}
228 
229 	if (should_fail_iommu(dev))
230 		return DMA_MAPPING_ERROR;
231 
232 	/*
233 	 * We don't need to disable preemption here because any CPU can
234 	 * safely use any IOMMU pool.
235 	 */
236 	pool_nr = raw_cpu_read(iommu_pool_hash) & (tbl->nr_pools - 1);
237 
238 	if (largealloc)
239 		pool = &(tbl->large_pool);
240 	else
241 		pool = &(tbl->pools[pool_nr]);
242 
243 	spin_lock_irqsave(&(pool->lock), flags);
244 
245 again:
246 	if ((pass == 0) && handle && *handle &&
247 	    (*handle >= pool->start) && (*handle < pool->end))
248 		start = *handle;
249 	else
250 		start = pool->hint;
251 
252 	limit = pool->end;
253 
254 	/* The case below can happen if we have a small segment appended
255 	 * to a large, or when the previous alloc was at the very end of
256 	 * the available space. If so, go back to the initial start.
257 	 */
258 	if (start >= limit)
259 		start = pool->start;
260 
261 	if (limit + tbl->it_offset > mask) {
262 		limit = mask - tbl->it_offset + 1;
263 		/* If we're constrained on address range, first try
264 		 * at the masked hint to avoid O(n) search complexity,
265 		 * but on second pass, start at 0 in pool 0.
266 		 */
267 		if ((start & mask) >= limit || pass > 0) {
268 			spin_unlock(&(pool->lock));
269 			pool = &(tbl->pools[0]);
270 			spin_lock(&(pool->lock));
271 			start = pool->start;
272 		} else {
273 			start &= mask;
274 		}
275 	}
276 
277 	n = iommu_area_alloc(tbl->it_map, limit, start, npages, tbl->it_offset,
278 			dma_get_seg_boundary_nr_pages(dev, tbl->it_page_shift),
279 			align_mask);
280 	if (n == -1) {
281 		if (likely(pass == 0)) {
282 			/* First try the pool from the start */
283 			pool->hint = pool->start;
284 			pass++;
285 			goto again;
286 
287 		} else if (pass <= tbl->nr_pools) {
288 			/* Now try scanning all the other pools */
289 			spin_unlock(&(pool->lock));
290 			pool_nr = (pool_nr + 1) & (tbl->nr_pools - 1);
291 			pool = &tbl->pools[pool_nr];
292 			spin_lock(&(pool->lock));
293 			pool->hint = pool->start;
294 			pass++;
295 			goto again;
296 
297 		} else if (pass == tbl->nr_pools + 1) {
298 			/* Last resort: try largepool */
299 			spin_unlock(&pool->lock);
300 			pool = &tbl->large_pool;
301 			spin_lock(&pool->lock);
302 			pool->hint = pool->start;
303 			pass++;
304 			goto again;
305 
306 		} else {
307 			/* Give up */
308 			spin_unlock_irqrestore(&(pool->lock), flags);
309 			return DMA_MAPPING_ERROR;
310 		}
311 	}
312 
313 	end = n + npages;
314 
315 	/* Bump the hint to a new block for small allocs. */
316 	if (largealloc) {
317 		/* Don't bump to new block to avoid fragmentation */
318 		pool->hint = end;
319 	} else {
320 		/* Overflow will be taken care of at the next allocation */
321 		pool->hint = (end + tbl->it_blocksize - 1) &
322 		                ~(tbl->it_blocksize - 1);
323 	}
324 
325 	/* Update handle for SG allocations */
326 	if (handle)
327 		*handle = end;
328 
329 	spin_unlock_irqrestore(&(pool->lock), flags);
330 
331 	return n;
332 }
333 
334 static dma_addr_t iommu_alloc(struct device *dev, struct iommu_table *tbl,
335 			      void *page, unsigned int npages,
336 			      enum dma_data_direction direction,
337 			      unsigned long mask, unsigned int align_order,
338 			      unsigned long attrs)
339 {
340 	unsigned long entry;
341 	dma_addr_t ret = DMA_MAPPING_ERROR;
342 	int build_fail;
343 
344 	entry = iommu_range_alloc(dev, tbl, npages, NULL, mask, align_order);
345 
346 	if (unlikely(entry == DMA_MAPPING_ERROR))
347 		return DMA_MAPPING_ERROR;
348 
349 	entry += tbl->it_offset;	/* Offset into real TCE table */
350 	ret = entry << tbl->it_page_shift;	/* Set the return dma address */
351 
352 	/* Put the TCEs in the HW table */
353 	build_fail = tbl->it_ops->set(tbl, entry, npages,
354 				      (unsigned long)page &
355 				      IOMMU_PAGE_MASK(tbl), direction, attrs);
356 
357 	/* tbl->it_ops->set() only returns non-zero for transient errors.
358 	 * Clean up the table bitmap in this case and return
359 	 * DMA_MAPPING_ERROR. For all other errors the functionality is
360 	 * not altered.
361 	 */
362 	if (unlikely(build_fail)) {
363 		__iommu_free(tbl, ret, npages);
364 		return DMA_MAPPING_ERROR;
365 	}
366 
367 	/* Flush/invalidate TLB caches if necessary */
368 	if (tbl->it_ops->flush)
369 		tbl->it_ops->flush(tbl);
370 
371 	/* Make sure updates are seen by hardware */
372 	mb();
373 
374 	return ret;
375 }
376 
377 static bool iommu_free_check(struct iommu_table *tbl, dma_addr_t dma_addr,
378 			     unsigned int npages)
379 {
380 	unsigned long entry, free_entry;
381 
382 	entry = dma_addr >> tbl->it_page_shift;
383 	free_entry = entry - tbl->it_offset;
384 
385 	if (((free_entry + npages) > tbl->it_size) ||
386 	    (entry < tbl->it_offset)) {
387 		if (printk_ratelimit()) {
388 			printk(KERN_INFO "iommu_free: invalid entry\n");
389 			printk(KERN_INFO "\tentry     = 0x%lx\n", entry);
390 			printk(KERN_INFO "\tdma_addr  = 0x%llx\n", (u64)dma_addr);
391 			printk(KERN_INFO "\tTable     = 0x%llx\n", (u64)tbl);
392 			printk(KERN_INFO "\tbus#      = 0x%llx\n", (u64)tbl->it_busno);
393 			printk(KERN_INFO "\tsize      = 0x%llx\n", (u64)tbl->it_size);
394 			printk(KERN_INFO "\tstartOff  = 0x%llx\n", (u64)tbl->it_offset);
395 			printk(KERN_INFO "\tindex     = 0x%llx\n", (u64)tbl->it_index);
396 			WARN_ON(1);
397 		}
398 
399 		return false;
400 	}
401 
402 	return true;
403 }
404 
405 static struct iommu_pool *get_pool(struct iommu_table *tbl,
406 				   unsigned long entry)
407 {
408 	struct iommu_pool *p;
409 	unsigned long largepool_start = tbl->large_pool.start;
410 
411 	/* The large pool is the last pool at the top of the table */
412 	if (entry >= largepool_start) {
413 		p = &tbl->large_pool;
414 	} else {
415 		unsigned int pool_nr = entry / tbl->poolsize;
416 
417 		BUG_ON(pool_nr > tbl->nr_pools);
418 		p = &tbl->pools[pool_nr];
419 	}
420 
421 	return p;
422 }
423 
424 static void __iommu_free(struct iommu_table *tbl, dma_addr_t dma_addr,
425 			 unsigned int npages)
426 {
427 	unsigned long entry, free_entry;
428 	unsigned long flags;
429 	struct iommu_pool *pool;
430 
431 	entry = dma_addr >> tbl->it_page_shift;
432 	free_entry = entry - tbl->it_offset;
433 
434 	pool = get_pool(tbl, free_entry);
435 
436 	if (!iommu_free_check(tbl, dma_addr, npages))
437 		return;
438 
439 	tbl->it_ops->clear(tbl, entry, npages);
440 
441 	spin_lock_irqsave(&(pool->lock), flags);
442 	bitmap_clear(tbl->it_map, free_entry, npages);
443 	spin_unlock_irqrestore(&(pool->lock), flags);
444 }
445 
446 static void iommu_free(struct iommu_table *tbl, dma_addr_t dma_addr,
447 		unsigned int npages)
448 {
449 	__iommu_free(tbl, dma_addr, npages);
450 
451 	/* Make sure TLB cache is flushed if the HW needs it. We do
452 	 * not do an mb() here on purpose, it is not needed on any of
453 	 * the current platforms.
454 	 */
455 	if (tbl->it_ops->flush)
456 		tbl->it_ops->flush(tbl);
457 }
458 
459 int ppc_iommu_map_sg(struct device *dev, struct iommu_table *tbl,
460 		     struct scatterlist *sglist, int nelems,
461 		     unsigned long mask, enum dma_data_direction direction,
462 		     unsigned long attrs)
463 {
464 	dma_addr_t dma_next = 0, dma_addr;
465 	struct scatterlist *s, *outs, *segstart;
466 	int outcount, incount, i, build_fail = 0;
467 	unsigned int align;
468 	unsigned long handle;
469 	unsigned int max_seg_size;
470 
471 	BUG_ON(direction == DMA_NONE);
472 
473 	if ((nelems == 0) || !tbl)
474 		return -EINVAL;
475 
476 	outs = s = segstart = &sglist[0];
477 	outcount = 1;
478 	incount = nelems;
479 	handle = 0;
480 
481 	/* Init first segment length for backout at failure */
482 	outs->dma_length = 0;
483 
484 	DBG("sg mapping %d elements:\n", nelems);
485 
486 	max_seg_size = dma_get_max_seg_size(dev);
487 	for_each_sg(sglist, s, nelems, i) {
488 		unsigned long vaddr, npages, entry, slen;
489 
490 		slen = s->length;
491 		/* Sanity check */
492 		if (slen == 0) {
493 			dma_next = 0;
494 			continue;
495 		}
496 		/* Allocate iommu entries for that segment */
497 		vaddr = (unsigned long) sg_virt(s);
498 		npages = iommu_num_pages(vaddr, slen, IOMMU_PAGE_SIZE(tbl));
499 		align = 0;
500 		if (tbl->it_page_shift < PAGE_SHIFT && slen >= PAGE_SIZE &&
501 		    (vaddr & ~PAGE_MASK) == 0)
502 			align = PAGE_SHIFT - tbl->it_page_shift;
503 		entry = iommu_range_alloc(dev, tbl, npages, &handle,
504 					  mask >> tbl->it_page_shift, align);
505 
506 		DBG("  - vaddr: %lx, size: %lx\n", vaddr, slen);
507 
508 		/* Handle failure */
509 		if (unlikely(entry == DMA_MAPPING_ERROR)) {
510 			if (!(attrs & DMA_ATTR_NO_WARN) &&
511 			    printk_ratelimit())
512 				dev_info(dev, "iommu_alloc failed, tbl %p "
513 					 "vaddr %lx npages %lu\n", tbl, vaddr,
514 					 npages);
515 			goto failure;
516 		}
517 
518 		/* Convert entry to a dma_addr_t */
519 		entry += tbl->it_offset;
520 		dma_addr = entry << tbl->it_page_shift;
521 		dma_addr |= (vaddr & ~IOMMU_PAGE_MASK(tbl));
522 
523 		DBG("  - %lu pages, entry: %lx, dma_addr: %lx\n",
524 			    npages, entry, dma_addr);
525 
526 		/* Insert into HW table */
527 		build_fail = tbl->it_ops->set(tbl, entry, npages,
528 					      vaddr & IOMMU_PAGE_MASK(tbl),
529 					      direction, attrs);
530 		if(unlikely(build_fail))
531 			goto failure;
532 
533 		/* If we are in an open segment, try merging */
534 		if (segstart != s) {
535 			DBG("  - trying merge...\n");
536 			/* We cannot merge if:
537 			 * - allocated dma_addr isn't contiguous to previous allocation
538 			 */
539 			if (novmerge || (dma_addr != dma_next) ||
540 			    (outs->dma_length + s->length > max_seg_size)) {
541 				/* Can't merge: create a new segment */
542 				segstart = s;
543 				outcount++;
544 				outs = sg_next(outs);
545 				DBG("    can't merge, new segment.\n");
546 			} else {
547 				outs->dma_length += s->length;
548 				DBG("    merged, new len: %ux\n", outs->dma_length);
549 			}
550 		}
551 
552 		if (segstart == s) {
553 			/* This is a new segment, fill entries */
554 			DBG("  - filling new segment.\n");
555 			outs->dma_address = dma_addr;
556 			outs->dma_length = slen;
557 		}
558 
559 		/* Calculate next page pointer for contiguous check */
560 		dma_next = dma_addr + slen;
561 
562 		DBG("  - dma next is: %lx\n", dma_next);
563 	}
564 
565 	/* Flush/invalidate TLB caches if necessary */
566 	if (tbl->it_ops->flush)
567 		tbl->it_ops->flush(tbl);
568 
569 	DBG("mapped %d elements:\n", outcount);
570 
571 	/* For the sake of ppc_iommu_unmap_sg, we clear out the length in the
572 	 * next entry of the sglist if we didn't fill the list completely
573 	 */
574 	if (outcount < incount) {
575 		outs = sg_next(outs);
576 		outs->dma_length = 0;
577 	}
578 
579 	/* Make sure updates are seen by hardware */
580 	mb();
581 
582 	return outcount;
583 
584  failure:
585 	for_each_sg(sglist, s, nelems, i) {
586 		if (s->dma_length != 0) {
587 			unsigned long vaddr, npages;
588 
589 			vaddr = s->dma_address & IOMMU_PAGE_MASK(tbl);
590 			npages = iommu_num_pages(s->dma_address, s->dma_length,
591 						 IOMMU_PAGE_SIZE(tbl));
592 			__iommu_free(tbl, vaddr, npages);
593 			s->dma_length = 0;
594 		}
595 		if (s == outs)
596 			break;
597 	}
598 	return -EIO;
599 }
600 
601 
602 void ppc_iommu_unmap_sg(struct iommu_table *tbl, struct scatterlist *sglist,
603 			int nelems, enum dma_data_direction direction,
604 			unsigned long attrs)
605 {
606 	struct scatterlist *sg;
607 
608 	BUG_ON(direction == DMA_NONE);
609 
610 	if (!tbl)
611 		return;
612 
613 	sg = sglist;
614 	while (nelems--) {
615 		unsigned int npages;
616 		dma_addr_t dma_handle = sg->dma_address;
617 
618 		if (sg->dma_length == 0)
619 			break;
620 		npages = iommu_num_pages(dma_handle, sg->dma_length,
621 					 IOMMU_PAGE_SIZE(tbl));
622 		__iommu_free(tbl, dma_handle, npages);
623 		sg = sg_next(sg);
624 	}
625 
626 	/* Flush/invalidate TLBs if necessary. As for iommu_free(), we
627 	 * do not do an mb() here, the affected platforms do not need it
628 	 * when freeing.
629 	 */
630 	if (tbl->it_ops->flush)
631 		tbl->it_ops->flush(tbl);
632 }
633 
634 static void iommu_table_clear(struct iommu_table *tbl)
635 {
636 	/*
637 	 * In case of firmware assisted dump system goes through clean
638 	 * reboot process at the time of system crash. Hence it's safe to
639 	 * clear the TCE entries if firmware assisted dump is active.
640 	 */
641 	if (!is_kdump_kernel() || is_fadump_active()) {
642 		/* Clear the table in case firmware left allocations in it */
643 		tbl->it_ops->clear(tbl, tbl->it_offset, tbl->it_size);
644 		return;
645 	}
646 
647 #ifdef CONFIG_CRASH_DUMP
648 	if (tbl->it_ops->get) {
649 		unsigned long index, tceval, tcecount = 0;
650 
651 		/* Reserve the existing mappings left by the first kernel. */
652 		for (index = 0; index < tbl->it_size; index++) {
653 			tceval = tbl->it_ops->get(tbl, index + tbl->it_offset);
654 			/*
655 			 * Freed TCE entry contains 0x7fffffffffffffff on JS20
656 			 */
657 			if (tceval && (tceval != 0x7fffffffffffffffUL)) {
658 				__set_bit(index, tbl->it_map);
659 				tcecount++;
660 			}
661 		}
662 
663 		if ((tbl->it_size - tcecount) < KDUMP_MIN_TCE_ENTRIES) {
664 			printk(KERN_WARNING "TCE table is full; freeing ");
665 			printk(KERN_WARNING "%d entries for the kdump boot\n",
666 				KDUMP_MIN_TCE_ENTRIES);
667 			for (index = tbl->it_size - KDUMP_MIN_TCE_ENTRIES;
668 				index < tbl->it_size; index++)
669 				__clear_bit(index, tbl->it_map);
670 		}
671 	}
672 #endif
673 }
674 
675 static void iommu_table_reserve_pages(struct iommu_table *tbl,
676 		unsigned long res_start, unsigned long res_end)
677 {
678 	int i;
679 
680 	WARN_ON_ONCE(res_end < res_start);
681 	/*
682 	 * Reserve page 0 so it will not be used for any mappings.
683 	 * This avoids buggy drivers that consider page 0 to be invalid
684 	 * to crash the machine or even lose data.
685 	 */
686 	if (tbl->it_offset == 0)
687 		set_bit(0, tbl->it_map);
688 
689 	if (res_start < tbl->it_offset)
690 		res_start = tbl->it_offset;
691 
692 	if (res_end > (tbl->it_offset + tbl->it_size))
693 		res_end = tbl->it_offset + tbl->it_size;
694 
695 	/* Check if res_start..res_end is a valid range in the table */
696 	if (res_start >= res_end) {
697 		tbl->it_reserved_start = tbl->it_offset;
698 		tbl->it_reserved_end = tbl->it_offset;
699 		return;
700 	}
701 
702 	tbl->it_reserved_start = res_start;
703 	tbl->it_reserved_end = res_end;
704 
705 	for (i = tbl->it_reserved_start; i < tbl->it_reserved_end; ++i)
706 		set_bit(i - tbl->it_offset, tbl->it_map);
707 }
708 
709 /*
710  * Build a iommu_table structure.  This contains a bit map which
711  * is used to manage allocation of the tce space.
712  */
713 struct iommu_table *iommu_init_table(struct iommu_table *tbl, int nid,
714 		unsigned long res_start, unsigned long res_end)
715 {
716 	unsigned long sz;
717 	static int welcomed = 0;
718 	unsigned int i;
719 	struct iommu_pool *p;
720 
721 	BUG_ON(!tbl->it_ops);
722 
723 	/* number of bytes needed for the bitmap */
724 	sz = BITS_TO_LONGS(tbl->it_size) * sizeof(unsigned long);
725 
726 	tbl->it_map = vzalloc_node(sz, nid);
727 	if (!tbl->it_map) {
728 		pr_err("%s: Can't allocate %ld bytes\n", __func__, sz);
729 		return NULL;
730 	}
731 
732 	iommu_table_reserve_pages(tbl, res_start, res_end);
733 
734 	/* We only split the IOMMU table if we have 1GB or more of space */
735 	if ((tbl->it_size << tbl->it_page_shift) >= (1UL * 1024 * 1024 * 1024))
736 		tbl->nr_pools = IOMMU_NR_POOLS;
737 	else
738 		tbl->nr_pools = 1;
739 
740 	/* We reserve the top 1/4 of the table for large allocations */
741 	tbl->poolsize = (tbl->it_size * 3 / 4) / tbl->nr_pools;
742 
743 	for (i = 0; i < tbl->nr_pools; i++) {
744 		p = &tbl->pools[i];
745 		spin_lock_init(&(p->lock));
746 		p->start = tbl->poolsize * i;
747 		p->hint = p->start;
748 		p->end = p->start + tbl->poolsize;
749 	}
750 
751 	p = &tbl->large_pool;
752 	spin_lock_init(&(p->lock));
753 	p->start = tbl->poolsize * i;
754 	p->hint = p->start;
755 	p->end = tbl->it_size;
756 
757 	iommu_table_clear(tbl);
758 
759 	if (!welcomed) {
760 		printk(KERN_INFO "IOMMU table initialized, virtual merging %s\n",
761 		       novmerge ? "disabled" : "enabled");
762 		welcomed = 1;
763 	}
764 
765 	iommu_debugfs_add(tbl);
766 
767 	return tbl;
768 }
769 
770 bool iommu_table_in_use(struct iommu_table *tbl)
771 {
772 	unsigned long start = 0, end;
773 
774 	/* ignore reserved bit0 */
775 	if (tbl->it_offset == 0)
776 		start = 1;
777 
778 	/* Simple case with no reserved MMIO32 region */
779 	if (!tbl->it_reserved_start && !tbl->it_reserved_end)
780 		return find_next_bit(tbl->it_map, tbl->it_size, start) != tbl->it_size;
781 
782 	end = tbl->it_reserved_start - tbl->it_offset;
783 	if (find_next_bit(tbl->it_map, end, start) != end)
784 		return true;
785 
786 	start = tbl->it_reserved_end - tbl->it_offset;
787 	end = tbl->it_size;
788 	return find_next_bit(tbl->it_map, end, start) != end;
789 }
790 
791 static void iommu_table_free(struct kref *kref)
792 {
793 	struct iommu_table *tbl;
794 
795 	tbl = container_of(kref, struct iommu_table, it_kref);
796 
797 	if (tbl->it_ops->free)
798 		tbl->it_ops->free(tbl);
799 
800 	if (!tbl->it_map) {
801 		kfree(tbl);
802 		return;
803 	}
804 
805 	iommu_debugfs_del(tbl);
806 
807 	/* verify that table contains no entries */
808 	if (iommu_table_in_use(tbl))
809 		pr_warn("%s: Unexpected TCEs\n", __func__);
810 
811 	/* free bitmap */
812 	vfree(tbl->it_map);
813 
814 	/* free table */
815 	kfree(tbl);
816 }
817 
818 struct iommu_table *iommu_tce_table_get(struct iommu_table *tbl)
819 {
820 	if (kref_get_unless_zero(&tbl->it_kref))
821 		return tbl;
822 
823 	return NULL;
824 }
825 EXPORT_SYMBOL_GPL(iommu_tce_table_get);
826 
827 int iommu_tce_table_put(struct iommu_table *tbl)
828 {
829 	if (WARN_ON(!tbl))
830 		return 0;
831 
832 	return kref_put(&tbl->it_kref, iommu_table_free);
833 }
834 EXPORT_SYMBOL_GPL(iommu_tce_table_put);
835 
836 /* Creates TCEs for a user provided buffer.  The user buffer must be
837  * contiguous real kernel storage (not vmalloc).  The address passed here
838  * comprises a page address and offset into that page. The dma_addr_t
839  * returned will point to the same byte within the page as was passed in.
840  */
841 dma_addr_t iommu_map_page(struct device *dev, struct iommu_table *tbl,
842 			  struct page *page, unsigned long offset, size_t size,
843 			  unsigned long mask, enum dma_data_direction direction,
844 			  unsigned long attrs)
845 {
846 	dma_addr_t dma_handle = DMA_MAPPING_ERROR;
847 	void *vaddr;
848 	unsigned long uaddr;
849 	unsigned int npages, align;
850 
851 	BUG_ON(direction == DMA_NONE);
852 
853 	vaddr = page_address(page) + offset;
854 	uaddr = (unsigned long)vaddr;
855 
856 	if (tbl) {
857 		npages = iommu_num_pages(uaddr, size, IOMMU_PAGE_SIZE(tbl));
858 		align = 0;
859 		if (tbl->it_page_shift < PAGE_SHIFT && size >= PAGE_SIZE &&
860 		    ((unsigned long)vaddr & ~PAGE_MASK) == 0)
861 			align = PAGE_SHIFT - tbl->it_page_shift;
862 
863 		dma_handle = iommu_alloc(dev, tbl, vaddr, npages, direction,
864 					 mask >> tbl->it_page_shift, align,
865 					 attrs);
866 		if (dma_handle == DMA_MAPPING_ERROR) {
867 			if (!(attrs & DMA_ATTR_NO_WARN) &&
868 			    printk_ratelimit())  {
869 				dev_info(dev, "iommu_alloc failed, tbl %p "
870 					 "vaddr %p npages %d\n", tbl, vaddr,
871 					 npages);
872 			}
873 		} else
874 			dma_handle |= (uaddr & ~IOMMU_PAGE_MASK(tbl));
875 	}
876 
877 	return dma_handle;
878 }
879 
880 void iommu_unmap_page(struct iommu_table *tbl, dma_addr_t dma_handle,
881 		      size_t size, enum dma_data_direction direction,
882 		      unsigned long attrs)
883 {
884 	unsigned int npages;
885 
886 	BUG_ON(direction == DMA_NONE);
887 
888 	if (tbl) {
889 		npages = iommu_num_pages(dma_handle, size,
890 					 IOMMU_PAGE_SIZE(tbl));
891 		iommu_free(tbl, dma_handle, npages);
892 	}
893 }
894 
895 /* Allocates a contiguous real buffer and creates mappings over it.
896  * Returns the virtual address of the buffer and sets dma_handle
897  * to the dma address (mapping) of the first page.
898  */
899 void *iommu_alloc_coherent(struct device *dev, struct iommu_table *tbl,
900 			   size_t size,	dma_addr_t *dma_handle,
901 			   unsigned long mask, gfp_t flag, int node)
902 {
903 	void *ret = NULL;
904 	dma_addr_t mapping;
905 	unsigned int order;
906 	unsigned int nio_pages, io_order;
907 	struct page *page;
908 	int tcesize = (1 << tbl->it_page_shift);
909 
910 	size = PAGE_ALIGN(size);
911 	order = get_order(size);
912 
913  	/*
914 	 * Client asked for way too much space.  This is checked later
915 	 * anyway.  It is easier to debug here for the drivers than in
916 	 * the tce tables.
917 	 */
918 	if (order >= IOMAP_MAX_ORDER) {
919 		dev_info(dev, "iommu_alloc_consistent size too large: 0x%lx\n",
920 			 size);
921 		return NULL;
922 	}
923 
924 	if (!tbl)
925 		return NULL;
926 
927 	/* Alloc enough pages (and possibly more) */
928 	page = alloc_pages_node(node, flag, order);
929 	if (!page)
930 		return NULL;
931 	ret = page_address(page);
932 	memset(ret, 0, size);
933 
934 	/* Set up tces to cover the allocated range */
935 	nio_pages = IOMMU_PAGE_ALIGN(size, tbl) >> tbl->it_page_shift;
936 
937 	io_order = get_iommu_order(size, tbl);
938 	mapping = iommu_alloc(dev, tbl, ret, nio_pages, DMA_BIDIRECTIONAL,
939 			      mask >> tbl->it_page_shift, io_order, 0);
940 	if (mapping == DMA_MAPPING_ERROR) {
941 		free_pages((unsigned long)ret, order);
942 		return NULL;
943 	}
944 
945 	*dma_handle = mapping | ((u64)ret & (tcesize - 1));
946 	return ret;
947 }
948 
949 void iommu_free_coherent(struct iommu_table *tbl, size_t size,
950 			 void *vaddr, dma_addr_t dma_handle)
951 {
952 	if (tbl) {
953 		unsigned int nio_pages;
954 
955 		size = PAGE_ALIGN(size);
956 		nio_pages = IOMMU_PAGE_ALIGN(size, tbl) >> tbl->it_page_shift;
957 		iommu_free(tbl, dma_handle, nio_pages);
958 		size = PAGE_ALIGN(size);
959 		free_pages((unsigned long)vaddr, get_order(size));
960 	}
961 }
962 
963 unsigned long iommu_direction_to_tce_perm(enum dma_data_direction dir)
964 {
965 	switch (dir) {
966 	case DMA_BIDIRECTIONAL:
967 		return TCE_PCI_READ | TCE_PCI_WRITE;
968 	case DMA_FROM_DEVICE:
969 		return TCE_PCI_WRITE;
970 	case DMA_TO_DEVICE:
971 		return TCE_PCI_READ;
972 	default:
973 		return 0;
974 	}
975 }
976 EXPORT_SYMBOL_GPL(iommu_direction_to_tce_perm);
977 
978 #ifdef CONFIG_IOMMU_API
979 /*
980  * SPAPR TCE API
981  */
982 static void group_release(void *iommu_data)
983 {
984 	struct iommu_table_group *table_group = iommu_data;
985 
986 	table_group->group = NULL;
987 }
988 
989 void iommu_register_group(struct iommu_table_group *table_group,
990 		int pci_domain_number, unsigned long pe_num)
991 {
992 	struct iommu_group *grp;
993 	char *name;
994 
995 	grp = iommu_group_alloc();
996 	if (IS_ERR(grp)) {
997 		pr_warn("powerpc iommu api: cannot create new group, err=%ld\n",
998 				PTR_ERR(grp));
999 		return;
1000 	}
1001 	table_group->group = grp;
1002 	iommu_group_set_iommudata(grp, table_group, group_release);
1003 	name = kasprintf(GFP_KERNEL, "domain%d-pe%lx",
1004 			pci_domain_number, pe_num);
1005 	if (!name)
1006 		return;
1007 	iommu_group_set_name(grp, name);
1008 	kfree(name);
1009 }
1010 
1011 enum dma_data_direction iommu_tce_direction(unsigned long tce)
1012 {
1013 	if ((tce & TCE_PCI_READ) && (tce & TCE_PCI_WRITE))
1014 		return DMA_BIDIRECTIONAL;
1015 	else if (tce & TCE_PCI_READ)
1016 		return DMA_TO_DEVICE;
1017 	else if (tce & TCE_PCI_WRITE)
1018 		return DMA_FROM_DEVICE;
1019 	else
1020 		return DMA_NONE;
1021 }
1022 EXPORT_SYMBOL_GPL(iommu_tce_direction);
1023 
1024 void iommu_flush_tce(struct iommu_table *tbl)
1025 {
1026 	/* Flush/invalidate TLB caches if necessary */
1027 	if (tbl->it_ops->flush)
1028 		tbl->it_ops->flush(tbl);
1029 
1030 	/* Make sure updates are seen by hardware */
1031 	mb();
1032 }
1033 EXPORT_SYMBOL_GPL(iommu_flush_tce);
1034 
1035 int iommu_tce_check_ioba(unsigned long page_shift,
1036 		unsigned long offset, unsigned long size,
1037 		unsigned long ioba, unsigned long npages)
1038 {
1039 	unsigned long mask = (1UL << page_shift) - 1;
1040 
1041 	if (ioba & mask)
1042 		return -EINVAL;
1043 
1044 	ioba >>= page_shift;
1045 	if (ioba < offset)
1046 		return -EINVAL;
1047 
1048 	if ((ioba + 1) > (offset + size))
1049 		return -EINVAL;
1050 
1051 	return 0;
1052 }
1053 EXPORT_SYMBOL_GPL(iommu_tce_check_ioba);
1054 
1055 int iommu_tce_check_gpa(unsigned long page_shift, unsigned long gpa)
1056 {
1057 	unsigned long mask = (1UL << page_shift) - 1;
1058 
1059 	if (gpa & mask)
1060 		return -EINVAL;
1061 
1062 	return 0;
1063 }
1064 EXPORT_SYMBOL_GPL(iommu_tce_check_gpa);
1065 
1066 extern long iommu_tce_xchg_no_kill(struct mm_struct *mm,
1067 		struct iommu_table *tbl,
1068 		unsigned long entry, unsigned long *hpa,
1069 		enum dma_data_direction *direction)
1070 {
1071 	long ret;
1072 	unsigned long size = 0;
1073 
1074 	ret = tbl->it_ops->xchg_no_kill(tbl, entry, hpa, direction);
1075 	if (!ret && ((*direction == DMA_FROM_DEVICE) ||
1076 			(*direction == DMA_BIDIRECTIONAL)) &&
1077 			!mm_iommu_is_devmem(mm, *hpa, tbl->it_page_shift,
1078 					&size))
1079 		SetPageDirty(pfn_to_page(*hpa >> PAGE_SHIFT));
1080 
1081 	return ret;
1082 }
1083 EXPORT_SYMBOL_GPL(iommu_tce_xchg_no_kill);
1084 
1085 void iommu_tce_kill(struct iommu_table *tbl,
1086 		unsigned long entry, unsigned long pages)
1087 {
1088 	if (tbl->it_ops->tce_kill)
1089 		tbl->it_ops->tce_kill(tbl, entry, pages);
1090 }
1091 EXPORT_SYMBOL_GPL(iommu_tce_kill);
1092 
1093 static int iommu_take_ownership(struct iommu_table *tbl)
1094 {
1095 	unsigned long flags, i, sz = (tbl->it_size + 7) >> 3;
1096 	int ret = 0;
1097 
1098 	/*
1099 	 * VFIO does not control TCE entries allocation and the guest
1100 	 * can write new TCEs on top of existing ones so iommu_tce_build()
1101 	 * must be able to release old pages. This functionality
1102 	 * requires exchange() callback defined so if it is not
1103 	 * implemented, we disallow taking ownership over the table.
1104 	 */
1105 	if (!tbl->it_ops->xchg_no_kill)
1106 		return -EINVAL;
1107 
1108 	spin_lock_irqsave(&tbl->large_pool.lock, flags);
1109 	for (i = 0; i < tbl->nr_pools; i++)
1110 		spin_lock_nest_lock(&tbl->pools[i].lock, &tbl->large_pool.lock);
1111 
1112 	if (iommu_table_in_use(tbl)) {
1113 		pr_err("iommu_tce: it_map is not empty");
1114 		ret = -EBUSY;
1115 	} else {
1116 		memset(tbl->it_map, 0xff, sz);
1117 	}
1118 
1119 	for (i = 0; i < tbl->nr_pools; i++)
1120 		spin_unlock(&tbl->pools[i].lock);
1121 	spin_unlock_irqrestore(&tbl->large_pool.lock, flags);
1122 
1123 	return ret;
1124 }
1125 
1126 static void iommu_release_ownership(struct iommu_table *tbl)
1127 {
1128 	unsigned long flags, i, sz = (tbl->it_size + 7) >> 3;
1129 
1130 	spin_lock_irqsave(&tbl->large_pool.lock, flags);
1131 	for (i = 0; i < tbl->nr_pools; i++)
1132 		spin_lock_nest_lock(&tbl->pools[i].lock, &tbl->large_pool.lock);
1133 
1134 	memset(tbl->it_map, 0, sz);
1135 
1136 	iommu_table_reserve_pages(tbl, tbl->it_reserved_start,
1137 			tbl->it_reserved_end);
1138 
1139 	for (i = 0; i < tbl->nr_pools; i++)
1140 		spin_unlock(&tbl->pools[i].lock);
1141 	spin_unlock_irqrestore(&tbl->large_pool.lock, flags);
1142 }
1143 
1144 int iommu_add_device(struct iommu_table_group *table_group, struct device *dev)
1145 {
1146 	/*
1147 	 * The sysfs entries should be populated before
1148 	 * binding IOMMU group. If sysfs entries isn't
1149 	 * ready, we simply bail.
1150 	 */
1151 	if (!device_is_registered(dev))
1152 		return -ENOENT;
1153 
1154 	if (device_iommu_mapped(dev)) {
1155 		pr_debug("%s: Skipping device %s with iommu group %d\n",
1156 			 __func__, dev_name(dev),
1157 			 iommu_group_id(dev->iommu_group));
1158 		return -EBUSY;
1159 	}
1160 
1161 	pr_debug("%s: Adding %s to iommu group %d\n",
1162 		 __func__, dev_name(dev),  iommu_group_id(table_group->group));
1163 	/*
1164 	 * This is still not adding devices via the IOMMU bus notifier because
1165 	 * of pcibios_init() from arch/powerpc/kernel/pci_64.c which calls
1166 	 * pcibios_scan_phb() first (and this guy adds devices and triggers
1167 	 * the notifier) and only then it calls pci_bus_add_devices() which
1168 	 * configures DMA for buses which also creates PEs and IOMMU groups.
1169 	 */
1170 	return iommu_probe_device(dev);
1171 }
1172 EXPORT_SYMBOL_GPL(iommu_add_device);
1173 
1174 /*
1175  * A simple iommu_table_group_ops which only allows reusing the existing
1176  * iommu_table. This handles VFIO for POWER7 or the nested KVM.
1177  * The ops does not allow creating windows and only allows reusing the existing
1178  * one if it matches table_group->tce32_start/tce32_size/page_shift.
1179  */
1180 static unsigned long spapr_tce_get_table_size(__u32 page_shift,
1181 					      __u64 window_size, __u32 levels)
1182 {
1183 	unsigned long size;
1184 
1185 	if (levels > 1)
1186 		return ~0U;
1187 	size = window_size >> (page_shift - 3);
1188 	return size;
1189 }
1190 
1191 static long spapr_tce_create_table(struct iommu_table_group *table_group, int num,
1192 				   __u32 page_shift, __u64 window_size, __u32 levels,
1193 				   struct iommu_table **ptbl)
1194 {
1195 	struct iommu_table *tbl = table_group->tables[0];
1196 
1197 	if (num > 0)
1198 		return -EPERM;
1199 
1200 	if (tbl->it_page_shift != page_shift ||
1201 	    tbl->it_size != (window_size >> page_shift) ||
1202 	    tbl->it_indirect_levels != levels - 1)
1203 		return -EINVAL;
1204 
1205 	*ptbl = iommu_tce_table_get(tbl);
1206 	return 0;
1207 }
1208 
1209 static long spapr_tce_set_window(struct iommu_table_group *table_group,
1210 				 int num, struct iommu_table *tbl)
1211 {
1212 	return tbl == table_group->tables[num] ? 0 : -EPERM;
1213 }
1214 
1215 static long spapr_tce_unset_window(struct iommu_table_group *table_group, int num)
1216 {
1217 	return 0;
1218 }
1219 
1220 static long spapr_tce_take_ownership(struct iommu_table_group *table_group)
1221 {
1222 	int i, j, rc = 0;
1223 
1224 	for (i = 0; i < IOMMU_TABLE_GROUP_MAX_TABLES; ++i) {
1225 		struct iommu_table *tbl = table_group->tables[i];
1226 
1227 		if (!tbl || !tbl->it_map)
1228 			continue;
1229 
1230 		rc = iommu_take_ownership(tbl);
1231 		if (!rc)
1232 			continue;
1233 
1234 		for (j = 0; j < i; ++j)
1235 			iommu_release_ownership(table_group->tables[j]);
1236 		return rc;
1237 	}
1238 	return 0;
1239 }
1240 
1241 static void spapr_tce_release_ownership(struct iommu_table_group *table_group)
1242 {
1243 	int i;
1244 
1245 	for (i = 0; i < IOMMU_TABLE_GROUP_MAX_TABLES; ++i) {
1246 		struct iommu_table *tbl = table_group->tables[i];
1247 
1248 		if (!tbl)
1249 			continue;
1250 
1251 		iommu_table_clear(tbl);
1252 		if (tbl->it_map)
1253 			iommu_release_ownership(tbl);
1254 	}
1255 }
1256 
1257 struct iommu_table_group_ops spapr_tce_table_group_ops = {
1258 	.get_table_size = spapr_tce_get_table_size,
1259 	.create_table = spapr_tce_create_table,
1260 	.set_window = spapr_tce_set_window,
1261 	.unset_window = spapr_tce_unset_window,
1262 	.take_ownership = spapr_tce_take_ownership,
1263 	.release_ownership = spapr_tce_release_ownership,
1264 };
1265 
1266 /*
1267  * A simple iommu_ops to allow less cruft in generic VFIO code.
1268  */
1269 static int spapr_tce_blocking_iommu_attach_dev(struct iommu_domain *dom,
1270 					       struct device *dev)
1271 {
1272 	struct iommu_group *grp = iommu_group_get(dev);
1273 	struct iommu_table_group *table_group;
1274 	int ret = -EINVAL;
1275 
1276 	if (!grp)
1277 		return -ENODEV;
1278 
1279 	table_group = iommu_group_get_iommudata(grp);
1280 	ret = table_group->ops->take_ownership(table_group);
1281 	iommu_group_put(grp);
1282 
1283 	return ret;
1284 }
1285 
1286 static void spapr_tce_blocking_iommu_set_platform_dma(struct device *dev)
1287 {
1288 	struct iommu_group *grp = iommu_group_get(dev);
1289 	struct iommu_table_group *table_group;
1290 
1291 	table_group = iommu_group_get_iommudata(grp);
1292 	table_group->ops->release_ownership(table_group);
1293 }
1294 
1295 static const struct iommu_domain_ops spapr_tce_blocking_domain_ops = {
1296 	.attach_dev = spapr_tce_blocking_iommu_attach_dev,
1297 };
1298 
1299 static bool spapr_tce_iommu_capable(struct device *dev, enum iommu_cap cap)
1300 {
1301 	switch (cap) {
1302 	case IOMMU_CAP_CACHE_COHERENCY:
1303 		return true;
1304 	default:
1305 		break;
1306 	}
1307 
1308 	return false;
1309 }
1310 
1311 static struct iommu_domain *spapr_tce_iommu_domain_alloc(unsigned int type)
1312 {
1313 	struct iommu_domain *dom;
1314 
1315 	if (type != IOMMU_DOMAIN_BLOCKED)
1316 		return NULL;
1317 
1318 	dom = kzalloc(sizeof(*dom), GFP_KERNEL);
1319 	if (!dom)
1320 		return NULL;
1321 
1322 	dom->ops = &spapr_tce_blocking_domain_ops;
1323 
1324 	return dom;
1325 }
1326 
1327 static struct iommu_device *spapr_tce_iommu_probe_device(struct device *dev)
1328 {
1329 	struct pci_dev *pdev;
1330 	struct pci_controller *hose;
1331 
1332 	if (!dev_is_pci(dev))
1333 		return ERR_PTR(-EPERM);
1334 
1335 	pdev = to_pci_dev(dev);
1336 	hose = pdev->bus->sysdata;
1337 
1338 	return &hose->iommu;
1339 }
1340 
1341 static void spapr_tce_iommu_release_device(struct device *dev)
1342 {
1343 }
1344 
1345 static struct iommu_group *spapr_tce_iommu_device_group(struct device *dev)
1346 {
1347 	struct pci_controller *hose;
1348 	struct pci_dev *pdev;
1349 
1350 	pdev = to_pci_dev(dev);
1351 	hose = pdev->bus->sysdata;
1352 
1353 	if (!hose->controller_ops.device_group)
1354 		return ERR_PTR(-ENOENT);
1355 
1356 	return hose->controller_ops.device_group(hose, pdev);
1357 }
1358 
1359 static const struct iommu_ops spapr_tce_iommu_ops = {
1360 	.capable = spapr_tce_iommu_capable,
1361 	.domain_alloc = spapr_tce_iommu_domain_alloc,
1362 	.probe_device = spapr_tce_iommu_probe_device,
1363 	.release_device = spapr_tce_iommu_release_device,
1364 	.device_group = spapr_tce_iommu_device_group,
1365 	.set_platform_dma_ops = spapr_tce_blocking_iommu_set_platform_dma,
1366 };
1367 
1368 static struct attribute *spapr_tce_iommu_attrs[] = {
1369 	NULL,
1370 };
1371 
1372 static struct attribute_group spapr_tce_iommu_group = {
1373 	.name = "spapr-tce-iommu",
1374 	.attrs = spapr_tce_iommu_attrs,
1375 };
1376 
1377 static const struct attribute_group *spapr_tce_iommu_groups[] = {
1378 	&spapr_tce_iommu_group,
1379 	NULL,
1380 };
1381 
1382 /*
1383  * This registers IOMMU devices of PHBs. This needs to happen
1384  * after core_initcall(iommu_init) + postcore_initcall(pci_driver_init) and
1385  * before subsys_initcall(iommu_subsys_init).
1386  */
1387 static int __init spapr_tce_setup_phb_iommus_initcall(void)
1388 {
1389 	struct pci_controller *hose;
1390 
1391 	list_for_each_entry(hose, &hose_list, list_node) {
1392 		iommu_device_sysfs_add(&hose->iommu, hose->parent,
1393 				       spapr_tce_iommu_groups, "iommu-phb%04x",
1394 				       hose->global_number);
1395 		iommu_device_register(&hose->iommu, &spapr_tce_iommu_ops,
1396 				      hose->parent);
1397 	}
1398 	return 0;
1399 }
1400 postcore_initcall_sync(spapr_tce_setup_phb_iommus_initcall);
1401 
1402 #endif /* CONFIG_IOMMU_API */
1403