xref: /openbmc/linux/arch/powerpc/kernel/iommu.c (revision 2a954832)
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 |= (s->offset & ~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 
909 	size = PAGE_ALIGN(size);
910 	order = get_order(size);
911 
912  	/*
913 	 * Client asked for way too much space.  This is checked later
914 	 * anyway.  It is easier to debug here for the drivers than in
915 	 * the tce tables.
916 	 */
917 	if (order >= IOMAP_MAX_ORDER) {
918 		dev_info(dev, "iommu_alloc_consistent size too large: 0x%lx\n",
919 			 size);
920 		return NULL;
921 	}
922 
923 	if (!tbl)
924 		return NULL;
925 
926 	/* Alloc enough pages (and possibly more) */
927 	page = alloc_pages_node(node, flag, order);
928 	if (!page)
929 		return NULL;
930 	ret = page_address(page);
931 	memset(ret, 0, size);
932 
933 	/* Set up tces to cover the allocated range */
934 	nio_pages = size >> tbl->it_page_shift;
935 	io_order = get_iommu_order(size, tbl);
936 	mapping = iommu_alloc(dev, tbl, ret, nio_pages, DMA_BIDIRECTIONAL,
937 			      mask >> tbl->it_page_shift, io_order, 0);
938 	if (mapping == DMA_MAPPING_ERROR) {
939 		free_pages((unsigned long)ret, order);
940 		return NULL;
941 	}
942 	*dma_handle = mapping;
943 	return ret;
944 }
945 
946 void iommu_free_coherent(struct iommu_table *tbl, size_t size,
947 			 void *vaddr, dma_addr_t dma_handle)
948 {
949 	if (tbl) {
950 		unsigned int nio_pages;
951 
952 		size = PAGE_ALIGN(size);
953 		nio_pages = size >> tbl->it_page_shift;
954 		iommu_free(tbl, dma_handle, nio_pages);
955 		size = PAGE_ALIGN(size);
956 		free_pages((unsigned long)vaddr, get_order(size));
957 	}
958 }
959 
960 unsigned long iommu_direction_to_tce_perm(enum dma_data_direction dir)
961 {
962 	switch (dir) {
963 	case DMA_BIDIRECTIONAL:
964 		return TCE_PCI_READ | TCE_PCI_WRITE;
965 	case DMA_FROM_DEVICE:
966 		return TCE_PCI_WRITE;
967 	case DMA_TO_DEVICE:
968 		return TCE_PCI_READ;
969 	default:
970 		return 0;
971 	}
972 }
973 EXPORT_SYMBOL_GPL(iommu_direction_to_tce_perm);
974 
975 #ifdef CONFIG_IOMMU_API
976 /*
977  * SPAPR TCE API
978  */
979 static void group_release(void *iommu_data)
980 {
981 	struct iommu_table_group *table_group = iommu_data;
982 
983 	table_group->group = NULL;
984 }
985 
986 void iommu_register_group(struct iommu_table_group *table_group,
987 		int pci_domain_number, unsigned long pe_num)
988 {
989 	struct iommu_group *grp;
990 	char *name;
991 
992 	grp = iommu_group_alloc();
993 	if (IS_ERR(grp)) {
994 		pr_warn("powerpc iommu api: cannot create new group, err=%ld\n",
995 				PTR_ERR(grp));
996 		return;
997 	}
998 	table_group->group = grp;
999 	iommu_group_set_iommudata(grp, table_group, group_release);
1000 	name = kasprintf(GFP_KERNEL, "domain%d-pe%lx",
1001 			pci_domain_number, pe_num);
1002 	if (!name)
1003 		return;
1004 	iommu_group_set_name(grp, name);
1005 	kfree(name);
1006 }
1007 
1008 enum dma_data_direction iommu_tce_direction(unsigned long tce)
1009 {
1010 	if ((tce & TCE_PCI_READ) && (tce & TCE_PCI_WRITE))
1011 		return DMA_BIDIRECTIONAL;
1012 	else if (tce & TCE_PCI_READ)
1013 		return DMA_TO_DEVICE;
1014 	else if (tce & TCE_PCI_WRITE)
1015 		return DMA_FROM_DEVICE;
1016 	else
1017 		return DMA_NONE;
1018 }
1019 EXPORT_SYMBOL_GPL(iommu_tce_direction);
1020 
1021 void iommu_flush_tce(struct iommu_table *tbl)
1022 {
1023 	/* Flush/invalidate TLB caches if necessary */
1024 	if (tbl->it_ops->flush)
1025 		tbl->it_ops->flush(tbl);
1026 
1027 	/* Make sure updates are seen by hardware */
1028 	mb();
1029 }
1030 EXPORT_SYMBOL_GPL(iommu_flush_tce);
1031 
1032 int iommu_tce_check_ioba(unsigned long page_shift,
1033 		unsigned long offset, unsigned long size,
1034 		unsigned long ioba, unsigned long npages)
1035 {
1036 	unsigned long mask = (1UL << page_shift) - 1;
1037 
1038 	if (ioba & mask)
1039 		return -EINVAL;
1040 
1041 	ioba >>= page_shift;
1042 	if (ioba < offset)
1043 		return -EINVAL;
1044 
1045 	if ((ioba + 1) > (offset + size))
1046 		return -EINVAL;
1047 
1048 	return 0;
1049 }
1050 EXPORT_SYMBOL_GPL(iommu_tce_check_ioba);
1051 
1052 int iommu_tce_check_gpa(unsigned long page_shift, unsigned long gpa)
1053 {
1054 	unsigned long mask = (1UL << page_shift) - 1;
1055 
1056 	if (gpa & mask)
1057 		return -EINVAL;
1058 
1059 	return 0;
1060 }
1061 EXPORT_SYMBOL_GPL(iommu_tce_check_gpa);
1062 
1063 extern long iommu_tce_xchg_no_kill(struct mm_struct *mm,
1064 		struct iommu_table *tbl,
1065 		unsigned long entry, unsigned long *hpa,
1066 		enum dma_data_direction *direction)
1067 {
1068 	long ret;
1069 	unsigned long size = 0;
1070 
1071 	ret = tbl->it_ops->xchg_no_kill(tbl, entry, hpa, direction);
1072 	if (!ret && ((*direction == DMA_FROM_DEVICE) ||
1073 			(*direction == DMA_BIDIRECTIONAL)) &&
1074 			!mm_iommu_is_devmem(mm, *hpa, tbl->it_page_shift,
1075 					&size))
1076 		SetPageDirty(pfn_to_page(*hpa >> PAGE_SHIFT));
1077 
1078 	return ret;
1079 }
1080 EXPORT_SYMBOL_GPL(iommu_tce_xchg_no_kill);
1081 
1082 void iommu_tce_kill(struct iommu_table *tbl,
1083 		unsigned long entry, unsigned long pages)
1084 {
1085 	if (tbl->it_ops->tce_kill)
1086 		tbl->it_ops->tce_kill(tbl, entry, pages);
1087 }
1088 EXPORT_SYMBOL_GPL(iommu_tce_kill);
1089 
1090 static int iommu_take_ownership(struct iommu_table *tbl)
1091 {
1092 	unsigned long flags, i, sz = (tbl->it_size + 7) >> 3;
1093 	int ret = 0;
1094 
1095 	/*
1096 	 * VFIO does not control TCE entries allocation and the guest
1097 	 * can write new TCEs on top of existing ones so iommu_tce_build()
1098 	 * must be able to release old pages. This functionality
1099 	 * requires exchange() callback defined so if it is not
1100 	 * implemented, we disallow taking ownership over the table.
1101 	 */
1102 	if (!tbl->it_ops->xchg_no_kill)
1103 		return -EINVAL;
1104 
1105 	spin_lock_irqsave(&tbl->large_pool.lock, flags);
1106 	for (i = 0; i < tbl->nr_pools; i++)
1107 		spin_lock_nest_lock(&tbl->pools[i].lock, &tbl->large_pool.lock);
1108 
1109 	if (iommu_table_in_use(tbl)) {
1110 		pr_err("iommu_tce: it_map is not empty");
1111 		ret = -EBUSY;
1112 	} else {
1113 		memset(tbl->it_map, 0xff, sz);
1114 	}
1115 
1116 	for (i = 0; i < tbl->nr_pools; i++)
1117 		spin_unlock(&tbl->pools[i].lock);
1118 	spin_unlock_irqrestore(&tbl->large_pool.lock, flags);
1119 
1120 	return ret;
1121 }
1122 
1123 static void iommu_release_ownership(struct iommu_table *tbl)
1124 {
1125 	unsigned long flags, i, sz = (tbl->it_size + 7) >> 3;
1126 
1127 	spin_lock_irqsave(&tbl->large_pool.lock, flags);
1128 	for (i = 0; i < tbl->nr_pools; i++)
1129 		spin_lock_nest_lock(&tbl->pools[i].lock, &tbl->large_pool.lock);
1130 
1131 	memset(tbl->it_map, 0, sz);
1132 
1133 	iommu_table_reserve_pages(tbl, tbl->it_reserved_start,
1134 			tbl->it_reserved_end);
1135 
1136 	for (i = 0; i < tbl->nr_pools; i++)
1137 		spin_unlock(&tbl->pools[i].lock);
1138 	spin_unlock_irqrestore(&tbl->large_pool.lock, flags);
1139 }
1140 
1141 int iommu_add_device(struct iommu_table_group *table_group, struct device *dev)
1142 {
1143 	/*
1144 	 * The sysfs entries should be populated before
1145 	 * binding IOMMU group. If sysfs entries isn't
1146 	 * ready, we simply bail.
1147 	 */
1148 	if (!device_is_registered(dev))
1149 		return -ENOENT;
1150 
1151 	if (device_iommu_mapped(dev)) {
1152 		pr_debug("%s: Skipping device %s with iommu group %d\n",
1153 			 __func__, dev_name(dev),
1154 			 iommu_group_id(dev->iommu_group));
1155 		return -EBUSY;
1156 	}
1157 
1158 	pr_debug("%s: Adding %s to iommu group %d\n",
1159 		 __func__, dev_name(dev),  iommu_group_id(table_group->group));
1160 	/*
1161 	 * This is still not adding devices via the IOMMU bus notifier because
1162 	 * of pcibios_init() from arch/powerpc/kernel/pci_64.c which calls
1163 	 * pcibios_scan_phb() first (and this guy adds devices and triggers
1164 	 * the notifier) and only then it calls pci_bus_add_devices() which
1165 	 * configures DMA for buses which also creates PEs and IOMMU groups.
1166 	 */
1167 	return iommu_probe_device(dev);
1168 }
1169 EXPORT_SYMBOL_GPL(iommu_add_device);
1170 
1171 void iommu_del_device(struct device *dev)
1172 {
1173 	/*
1174 	 * Some devices might not have IOMMU table and group
1175 	 * and we needn't detach them from the associated
1176 	 * IOMMU groups
1177 	 */
1178 	if (!device_iommu_mapped(dev)) {
1179 		pr_debug("iommu_tce: skipping device %s with no tbl\n",
1180 			 dev_name(dev));
1181 		return;
1182 	}
1183 
1184 	iommu_group_remove_device(dev);
1185 }
1186 EXPORT_SYMBOL_GPL(iommu_del_device);
1187 
1188 /*
1189  * A simple iommu_table_group_ops which only allows reusing the existing
1190  * iommu_table. This handles VFIO for POWER7 or the nested KVM.
1191  * The ops does not allow creating windows and only allows reusing the existing
1192  * one if it matches table_group->tce32_start/tce32_size/page_shift.
1193  */
1194 static unsigned long spapr_tce_get_table_size(__u32 page_shift,
1195 					      __u64 window_size, __u32 levels)
1196 {
1197 	unsigned long size;
1198 
1199 	if (levels > 1)
1200 		return ~0U;
1201 	size = window_size >> (page_shift - 3);
1202 	return size;
1203 }
1204 
1205 static long spapr_tce_create_table(struct iommu_table_group *table_group, int num,
1206 				   __u32 page_shift, __u64 window_size, __u32 levels,
1207 				   struct iommu_table **ptbl)
1208 {
1209 	struct iommu_table *tbl = table_group->tables[0];
1210 
1211 	if (num > 0)
1212 		return -EPERM;
1213 
1214 	if (tbl->it_page_shift != page_shift ||
1215 	    tbl->it_size != (window_size >> page_shift) ||
1216 	    tbl->it_indirect_levels != levels - 1)
1217 		return -EINVAL;
1218 
1219 	*ptbl = iommu_tce_table_get(tbl);
1220 	return 0;
1221 }
1222 
1223 static long spapr_tce_set_window(struct iommu_table_group *table_group,
1224 				 int num, struct iommu_table *tbl)
1225 {
1226 	return tbl == table_group->tables[num] ? 0 : -EPERM;
1227 }
1228 
1229 static long spapr_tce_unset_window(struct iommu_table_group *table_group, int num)
1230 {
1231 	return 0;
1232 }
1233 
1234 static long spapr_tce_take_ownership(struct iommu_table_group *table_group)
1235 {
1236 	int i, j, rc = 0;
1237 
1238 	for (i = 0; i < IOMMU_TABLE_GROUP_MAX_TABLES; ++i) {
1239 		struct iommu_table *tbl = table_group->tables[i];
1240 
1241 		if (!tbl || !tbl->it_map)
1242 			continue;
1243 
1244 		rc = iommu_take_ownership(tbl);
1245 		if (!rc)
1246 			continue;
1247 
1248 		for (j = 0; j < i; ++j)
1249 			iommu_release_ownership(table_group->tables[j]);
1250 		return rc;
1251 	}
1252 	return 0;
1253 }
1254 
1255 static void spapr_tce_release_ownership(struct iommu_table_group *table_group)
1256 {
1257 	int i;
1258 
1259 	for (i = 0; i < IOMMU_TABLE_GROUP_MAX_TABLES; ++i) {
1260 		struct iommu_table *tbl = table_group->tables[i];
1261 
1262 		if (!tbl)
1263 			continue;
1264 
1265 		iommu_table_clear(tbl);
1266 		if (tbl->it_map)
1267 			iommu_release_ownership(tbl);
1268 	}
1269 }
1270 
1271 struct iommu_table_group_ops spapr_tce_table_group_ops = {
1272 	.get_table_size = spapr_tce_get_table_size,
1273 	.create_table = spapr_tce_create_table,
1274 	.set_window = spapr_tce_set_window,
1275 	.unset_window = spapr_tce_unset_window,
1276 	.take_ownership = spapr_tce_take_ownership,
1277 	.release_ownership = spapr_tce_release_ownership,
1278 };
1279 
1280 /*
1281  * A simple iommu_ops to allow less cruft in generic VFIO code.
1282  */
1283 static int spapr_tce_blocking_iommu_attach_dev(struct iommu_domain *dom,
1284 					       struct device *dev)
1285 {
1286 	struct iommu_group *grp = iommu_group_get(dev);
1287 	struct iommu_table_group *table_group;
1288 	int ret = -EINVAL;
1289 
1290 	if (!grp)
1291 		return -ENODEV;
1292 
1293 	table_group = iommu_group_get_iommudata(grp);
1294 	ret = table_group->ops->take_ownership(table_group);
1295 	iommu_group_put(grp);
1296 
1297 	return ret;
1298 }
1299 
1300 static void spapr_tce_blocking_iommu_set_platform_dma(struct device *dev)
1301 {
1302 	struct iommu_group *grp = iommu_group_get(dev);
1303 	struct iommu_table_group *table_group;
1304 
1305 	table_group = iommu_group_get_iommudata(grp);
1306 	table_group->ops->release_ownership(table_group);
1307 }
1308 
1309 static const struct iommu_domain_ops spapr_tce_blocking_domain_ops = {
1310 	.attach_dev = spapr_tce_blocking_iommu_attach_dev,
1311 };
1312 
1313 static bool spapr_tce_iommu_capable(struct device *dev, enum iommu_cap cap)
1314 {
1315 	switch (cap) {
1316 	case IOMMU_CAP_CACHE_COHERENCY:
1317 		return true;
1318 	default:
1319 		break;
1320 	}
1321 
1322 	return false;
1323 }
1324 
1325 static struct iommu_domain *spapr_tce_iommu_domain_alloc(unsigned int type)
1326 {
1327 	struct iommu_domain *dom;
1328 
1329 	if (type != IOMMU_DOMAIN_BLOCKED)
1330 		return NULL;
1331 
1332 	dom = kzalloc(sizeof(*dom), GFP_KERNEL);
1333 	if (!dom)
1334 		return NULL;
1335 
1336 	dom->ops = &spapr_tce_blocking_domain_ops;
1337 
1338 	return dom;
1339 }
1340 
1341 static struct iommu_device *spapr_tce_iommu_probe_device(struct device *dev)
1342 {
1343 	struct pci_dev *pdev;
1344 	struct pci_controller *hose;
1345 
1346 	if (!dev_is_pci(dev))
1347 		return ERR_PTR(-EPERM);
1348 
1349 	pdev = to_pci_dev(dev);
1350 	hose = pdev->bus->sysdata;
1351 
1352 	return &hose->iommu;
1353 }
1354 
1355 static void spapr_tce_iommu_release_device(struct device *dev)
1356 {
1357 }
1358 
1359 static struct iommu_group *spapr_tce_iommu_device_group(struct device *dev)
1360 {
1361 	struct pci_controller *hose;
1362 	struct pci_dev *pdev;
1363 
1364 	pdev = to_pci_dev(dev);
1365 	hose = pdev->bus->sysdata;
1366 
1367 	if (!hose->controller_ops.device_group)
1368 		return ERR_PTR(-ENOENT);
1369 
1370 	return hose->controller_ops.device_group(hose, pdev);
1371 }
1372 
1373 static const struct iommu_ops spapr_tce_iommu_ops = {
1374 	.capable = spapr_tce_iommu_capable,
1375 	.domain_alloc = spapr_tce_iommu_domain_alloc,
1376 	.probe_device = spapr_tce_iommu_probe_device,
1377 	.release_device = spapr_tce_iommu_release_device,
1378 	.device_group = spapr_tce_iommu_device_group,
1379 	.set_platform_dma_ops = spapr_tce_blocking_iommu_set_platform_dma,
1380 };
1381 
1382 static struct attribute *spapr_tce_iommu_attrs[] = {
1383 	NULL,
1384 };
1385 
1386 static struct attribute_group spapr_tce_iommu_group = {
1387 	.name = "spapr-tce-iommu",
1388 	.attrs = spapr_tce_iommu_attrs,
1389 };
1390 
1391 static const struct attribute_group *spapr_tce_iommu_groups[] = {
1392 	&spapr_tce_iommu_group,
1393 	NULL,
1394 };
1395 
1396 /*
1397  * This registers IOMMU devices of PHBs. This needs to happen
1398  * after core_initcall(iommu_init) + postcore_initcall(pci_driver_init) and
1399  * before subsys_initcall(iommu_subsys_init).
1400  */
1401 static int __init spapr_tce_setup_phb_iommus_initcall(void)
1402 {
1403 	struct pci_controller *hose;
1404 
1405 	list_for_each_entry(hose, &hose_list, list_node) {
1406 		iommu_device_sysfs_add(&hose->iommu, hose->parent,
1407 				       spapr_tce_iommu_groups, "iommu-phb%04x",
1408 				       hose->global_number);
1409 		iommu_device_register(&hose->iommu, &spapr_tce_iommu_ops,
1410 				      hose->parent);
1411 	}
1412 	return 0;
1413 }
1414 postcore_initcall_sync(spapr_tce_setup_phb_iommus_initcall);
1415 
1416 #endif /* CONFIG_IOMMU_API */
1417