xref: /openbmc/linux/arch/powerpc/kernel/iommu.c (revision 2208f39c)
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 <asm/io.h>
29 #include <asm/prom.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 
39 #define DBG(...)
40 
41 static int novmerge;
42 
43 static void __iommu_free(struct iommu_table *, dma_addr_t, unsigned int);
44 
45 static int __init setup_iommu(char *str)
46 {
47 	if (!strcmp(str, "novmerge"))
48 		novmerge = 1;
49 	else if (!strcmp(str, "vmerge"))
50 		novmerge = 0;
51 	return 1;
52 }
53 
54 __setup("iommu=", setup_iommu);
55 
56 static DEFINE_PER_CPU(unsigned int, iommu_pool_hash);
57 
58 /*
59  * We precalculate the hash to avoid doing it on every allocation.
60  *
61  * The hash is important to spread CPUs across all the pools. For example,
62  * on a POWER7 with 4 way SMT we want interrupts on the primary threads and
63  * with 4 pools all primary threads would map to the same pool.
64  */
65 static int __init setup_iommu_pool_hash(void)
66 {
67 	unsigned int i;
68 
69 	for_each_possible_cpu(i)
70 		per_cpu(iommu_pool_hash, i) = hash_32(i, IOMMU_POOL_HASHBITS);
71 
72 	return 0;
73 }
74 subsys_initcall(setup_iommu_pool_hash);
75 
76 #ifdef CONFIG_FAIL_IOMMU
77 
78 static DECLARE_FAULT_ATTR(fail_iommu);
79 
80 static int __init setup_fail_iommu(char *str)
81 {
82 	return setup_fault_attr(&fail_iommu, str);
83 }
84 __setup("fail_iommu=", setup_fail_iommu);
85 
86 static bool should_fail_iommu(struct device *dev)
87 {
88 	return dev->archdata.fail_iommu && should_fail(&fail_iommu, 1);
89 }
90 
91 static int __init fail_iommu_debugfs(void)
92 {
93 	struct dentry *dir = fault_create_debugfs_attr("fail_iommu",
94 						       NULL, &fail_iommu);
95 
96 	return PTR_ERR_OR_ZERO(dir);
97 }
98 late_initcall(fail_iommu_debugfs);
99 
100 static ssize_t fail_iommu_show(struct device *dev,
101 			       struct device_attribute *attr, char *buf)
102 {
103 	return sprintf(buf, "%d\n", dev->archdata.fail_iommu);
104 }
105 
106 static ssize_t fail_iommu_store(struct device *dev,
107 				struct device_attribute *attr, const char *buf,
108 				size_t count)
109 {
110 	int i;
111 
112 	if (count > 0 && sscanf(buf, "%d", &i) > 0)
113 		dev->archdata.fail_iommu = (i == 0) ? 0 : 1;
114 
115 	return count;
116 }
117 
118 static DEVICE_ATTR_RW(fail_iommu);
119 
120 static int fail_iommu_bus_notify(struct notifier_block *nb,
121 				 unsigned long action, void *data)
122 {
123 	struct device *dev = data;
124 
125 	if (action == BUS_NOTIFY_ADD_DEVICE) {
126 		if (device_create_file(dev, &dev_attr_fail_iommu))
127 			pr_warn("Unable to create IOMMU fault injection sysfs "
128 				"entries\n");
129 	} else if (action == BUS_NOTIFY_DEL_DEVICE) {
130 		device_remove_file(dev, &dev_attr_fail_iommu);
131 	}
132 
133 	return 0;
134 }
135 
136 static struct notifier_block fail_iommu_bus_notifier = {
137 	.notifier_call = fail_iommu_bus_notify
138 };
139 
140 static int __init fail_iommu_setup(void)
141 {
142 #ifdef CONFIG_PCI
143 	bus_register_notifier(&pci_bus_type, &fail_iommu_bus_notifier);
144 #endif
145 #ifdef CONFIG_IBMVIO
146 	bus_register_notifier(&vio_bus_type, &fail_iommu_bus_notifier);
147 #endif
148 
149 	return 0;
150 }
151 /*
152  * Must execute after PCI and VIO subsystem have initialised but before
153  * devices are probed.
154  */
155 arch_initcall(fail_iommu_setup);
156 #else
157 static inline bool should_fail_iommu(struct device *dev)
158 {
159 	return false;
160 }
161 #endif
162 
163 static unsigned long iommu_range_alloc(struct device *dev,
164 				       struct iommu_table *tbl,
165                                        unsigned long npages,
166                                        unsigned long *handle,
167                                        unsigned long mask,
168                                        unsigned int align_order)
169 {
170 	unsigned long n, end, start;
171 	unsigned long limit;
172 	int largealloc = npages > 15;
173 	int pass = 0;
174 	unsigned long align_mask;
175 	unsigned long flags;
176 	unsigned int pool_nr;
177 	struct iommu_pool *pool;
178 
179 	align_mask = (1ull << align_order) - 1;
180 
181 	/* This allocator was derived from x86_64's bit string search */
182 
183 	/* Sanity check */
184 	if (unlikely(npages == 0)) {
185 		if (printk_ratelimit())
186 			WARN_ON(1);
187 		return DMA_MAPPING_ERROR;
188 	}
189 
190 	if (should_fail_iommu(dev))
191 		return DMA_MAPPING_ERROR;
192 
193 	/*
194 	 * We don't need to disable preemption here because any CPU can
195 	 * safely use any IOMMU pool.
196 	 */
197 	pool_nr = raw_cpu_read(iommu_pool_hash) & (tbl->nr_pools - 1);
198 
199 	if (largealloc)
200 		pool = &(tbl->large_pool);
201 	else
202 		pool = &(tbl->pools[pool_nr]);
203 
204 	spin_lock_irqsave(&(pool->lock), flags);
205 
206 again:
207 	if ((pass == 0) && handle && *handle &&
208 	    (*handle >= pool->start) && (*handle < pool->end))
209 		start = *handle;
210 	else
211 		start = pool->hint;
212 
213 	limit = pool->end;
214 
215 	/* The case below can happen if we have a small segment appended
216 	 * to a large, or when the previous alloc was at the very end of
217 	 * the available space. If so, go back to the initial start.
218 	 */
219 	if (start >= limit)
220 		start = pool->start;
221 
222 	if (limit + tbl->it_offset > mask) {
223 		limit = mask - tbl->it_offset + 1;
224 		/* If we're constrained on address range, first try
225 		 * at the masked hint to avoid O(n) search complexity,
226 		 * but on second pass, start at 0 in pool 0.
227 		 */
228 		if ((start & mask) >= limit || pass > 0) {
229 			spin_unlock(&(pool->lock));
230 			pool = &(tbl->pools[0]);
231 			spin_lock(&(pool->lock));
232 			start = pool->start;
233 		} else {
234 			start &= mask;
235 		}
236 	}
237 
238 	n = iommu_area_alloc(tbl->it_map, limit, start, npages, tbl->it_offset,
239 			dma_get_seg_boundary_nr_pages(dev, tbl->it_page_shift),
240 			align_mask);
241 	if (n == -1) {
242 		if (likely(pass == 0)) {
243 			/* First try the pool from the start */
244 			pool->hint = pool->start;
245 			pass++;
246 			goto again;
247 
248 		} else if (pass <= tbl->nr_pools) {
249 			/* Now try scanning all the other pools */
250 			spin_unlock(&(pool->lock));
251 			pool_nr = (pool_nr + 1) & (tbl->nr_pools - 1);
252 			pool = &tbl->pools[pool_nr];
253 			spin_lock(&(pool->lock));
254 			pool->hint = pool->start;
255 			pass++;
256 			goto again;
257 
258 		} else {
259 			/* Give up */
260 			spin_unlock_irqrestore(&(pool->lock), flags);
261 			return DMA_MAPPING_ERROR;
262 		}
263 	}
264 
265 	end = n + npages;
266 
267 	/* Bump the hint to a new block for small allocs. */
268 	if (largealloc) {
269 		/* Don't bump to new block to avoid fragmentation */
270 		pool->hint = end;
271 	} else {
272 		/* Overflow will be taken care of at the next allocation */
273 		pool->hint = (end + tbl->it_blocksize - 1) &
274 		                ~(tbl->it_blocksize - 1);
275 	}
276 
277 	/* Update handle for SG allocations */
278 	if (handle)
279 		*handle = end;
280 
281 	spin_unlock_irqrestore(&(pool->lock), flags);
282 
283 	return n;
284 }
285 
286 static dma_addr_t iommu_alloc(struct device *dev, struct iommu_table *tbl,
287 			      void *page, unsigned int npages,
288 			      enum dma_data_direction direction,
289 			      unsigned long mask, unsigned int align_order,
290 			      unsigned long attrs)
291 {
292 	unsigned long entry;
293 	dma_addr_t ret = DMA_MAPPING_ERROR;
294 	int build_fail;
295 
296 	entry = iommu_range_alloc(dev, tbl, npages, NULL, mask, align_order);
297 
298 	if (unlikely(entry == DMA_MAPPING_ERROR))
299 		return DMA_MAPPING_ERROR;
300 
301 	entry += tbl->it_offset;	/* Offset into real TCE table */
302 	ret = entry << tbl->it_page_shift;	/* Set the return dma address */
303 
304 	/* Put the TCEs in the HW table */
305 	build_fail = tbl->it_ops->set(tbl, entry, npages,
306 				      (unsigned long)page &
307 				      IOMMU_PAGE_MASK(tbl), direction, attrs);
308 
309 	/* tbl->it_ops->set() only returns non-zero for transient errors.
310 	 * Clean up the table bitmap in this case and return
311 	 * DMA_MAPPING_ERROR. For all other errors the functionality is
312 	 * not altered.
313 	 */
314 	if (unlikely(build_fail)) {
315 		__iommu_free(tbl, ret, npages);
316 		return DMA_MAPPING_ERROR;
317 	}
318 
319 	/* Flush/invalidate TLB caches if necessary */
320 	if (tbl->it_ops->flush)
321 		tbl->it_ops->flush(tbl);
322 
323 	/* Make sure updates are seen by hardware */
324 	mb();
325 
326 	return ret;
327 }
328 
329 static bool iommu_free_check(struct iommu_table *tbl, dma_addr_t dma_addr,
330 			     unsigned int npages)
331 {
332 	unsigned long entry, free_entry;
333 
334 	entry = dma_addr >> tbl->it_page_shift;
335 	free_entry = entry - tbl->it_offset;
336 
337 	if (((free_entry + npages) > tbl->it_size) ||
338 	    (entry < tbl->it_offset)) {
339 		if (printk_ratelimit()) {
340 			printk(KERN_INFO "iommu_free: invalid entry\n");
341 			printk(KERN_INFO "\tentry     = 0x%lx\n", entry);
342 			printk(KERN_INFO "\tdma_addr  = 0x%llx\n", (u64)dma_addr);
343 			printk(KERN_INFO "\tTable     = 0x%llx\n", (u64)tbl);
344 			printk(KERN_INFO "\tbus#      = 0x%llx\n", (u64)tbl->it_busno);
345 			printk(KERN_INFO "\tsize      = 0x%llx\n", (u64)tbl->it_size);
346 			printk(KERN_INFO "\tstartOff  = 0x%llx\n", (u64)tbl->it_offset);
347 			printk(KERN_INFO "\tindex     = 0x%llx\n", (u64)tbl->it_index);
348 			WARN_ON(1);
349 		}
350 
351 		return false;
352 	}
353 
354 	return true;
355 }
356 
357 static struct iommu_pool *get_pool(struct iommu_table *tbl,
358 				   unsigned long entry)
359 {
360 	struct iommu_pool *p;
361 	unsigned long largepool_start = tbl->large_pool.start;
362 
363 	/* The large pool is the last pool at the top of the table */
364 	if (entry >= largepool_start) {
365 		p = &tbl->large_pool;
366 	} else {
367 		unsigned int pool_nr = entry / tbl->poolsize;
368 
369 		BUG_ON(pool_nr > tbl->nr_pools);
370 		p = &tbl->pools[pool_nr];
371 	}
372 
373 	return p;
374 }
375 
376 static void __iommu_free(struct iommu_table *tbl, dma_addr_t dma_addr,
377 			 unsigned int npages)
378 {
379 	unsigned long entry, free_entry;
380 	unsigned long flags;
381 	struct iommu_pool *pool;
382 
383 	entry = dma_addr >> tbl->it_page_shift;
384 	free_entry = entry - tbl->it_offset;
385 
386 	pool = get_pool(tbl, free_entry);
387 
388 	if (!iommu_free_check(tbl, dma_addr, npages))
389 		return;
390 
391 	tbl->it_ops->clear(tbl, entry, npages);
392 
393 	spin_lock_irqsave(&(pool->lock), flags);
394 	bitmap_clear(tbl->it_map, free_entry, npages);
395 	spin_unlock_irqrestore(&(pool->lock), flags);
396 }
397 
398 static void iommu_free(struct iommu_table *tbl, dma_addr_t dma_addr,
399 		unsigned int npages)
400 {
401 	__iommu_free(tbl, dma_addr, npages);
402 
403 	/* Make sure TLB cache is flushed if the HW needs it. We do
404 	 * not do an mb() here on purpose, it is not needed on any of
405 	 * the current platforms.
406 	 */
407 	if (tbl->it_ops->flush)
408 		tbl->it_ops->flush(tbl);
409 }
410 
411 int ppc_iommu_map_sg(struct device *dev, struct iommu_table *tbl,
412 		     struct scatterlist *sglist, int nelems,
413 		     unsigned long mask, enum dma_data_direction direction,
414 		     unsigned long attrs)
415 {
416 	dma_addr_t dma_next = 0, dma_addr;
417 	struct scatterlist *s, *outs, *segstart;
418 	int outcount, incount, i, build_fail = 0;
419 	unsigned int align;
420 	unsigned long handle;
421 	unsigned int max_seg_size;
422 
423 	BUG_ON(direction == DMA_NONE);
424 
425 	if ((nelems == 0) || !tbl)
426 		return 0;
427 
428 	outs = s = segstart = &sglist[0];
429 	outcount = 1;
430 	incount = nelems;
431 	handle = 0;
432 
433 	/* Init first segment length for backout at failure */
434 	outs->dma_length = 0;
435 
436 	DBG("sg mapping %d elements:\n", nelems);
437 
438 	max_seg_size = dma_get_max_seg_size(dev);
439 	for_each_sg(sglist, s, nelems, i) {
440 		unsigned long vaddr, npages, entry, slen;
441 
442 		slen = s->length;
443 		/* Sanity check */
444 		if (slen == 0) {
445 			dma_next = 0;
446 			continue;
447 		}
448 		/* Allocate iommu entries for that segment */
449 		vaddr = (unsigned long) sg_virt(s);
450 		npages = iommu_num_pages(vaddr, slen, IOMMU_PAGE_SIZE(tbl));
451 		align = 0;
452 		if (tbl->it_page_shift < PAGE_SHIFT && slen >= PAGE_SIZE &&
453 		    (vaddr & ~PAGE_MASK) == 0)
454 			align = PAGE_SHIFT - tbl->it_page_shift;
455 		entry = iommu_range_alloc(dev, tbl, npages, &handle,
456 					  mask >> tbl->it_page_shift, align);
457 
458 		DBG("  - vaddr: %lx, size: %lx\n", vaddr, slen);
459 
460 		/* Handle failure */
461 		if (unlikely(entry == DMA_MAPPING_ERROR)) {
462 			if (!(attrs & DMA_ATTR_NO_WARN) &&
463 			    printk_ratelimit())
464 				dev_info(dev, "iommu_alloc failed, tbl %p "
465 					 "vaddr %lx npages %lu\n", tbl, vaddr,
466 					 npages);
467 			goto failure;
468 		}
469 
470 		/* Convert entry to a dma_addr_t */
471 		entry += tbl->it_offset;
472 		dma_addr = entry << tbl->it_page_shift;
473 		dma_addr |= (s->offset & ~IOMMU_PAGE_MASK(tbl));
474 
475 		DBG("  - %lu pages, entry: %lx, dma_addr: %lx\n",
476 			    npages, entry, dma_addr);
477 
478 		/* Insert into HW table */
479 		build_fail = tbl->it_ops->set(tbl, entry, npages,
480 					      vaddr & IOMMU_PAGE_MASK(tbl),
481 					      direction, attrs);
482 		if(unlikely(build_fail))
483 			goto failure;
484 
485 		/* If we are in an open segment, try merging */
486 		if (segstart != s) {
487 			DBG("  - trying merge...\n");
488 			/* We cannot merge if:
489 			 * - allocated dma_addr isn't contiguous to previous allocation
490 			 */
491 			if (novmerge || (dma_addr != dma_next) ||
492 			    (outs->dma_length + s->length > max_seg_size)) {
493 				/* Can't merge: create a new segment */
494 				segstart = s;
495 				outcount++;
496 				outs = sg_next(outs);
497 				DBG("    can't merge, new segment.\n");
498 			} else {
499 				outs->dma_length += s->length;
500 				DBG("    merged, new len: %ux\n", outs->dma_length);
501 			}
502 		}
503 
504 		if (segstart == s) {
505 			/* This is a new segment, fill entries */
506 			DBG("  - filling new segment.\n");
507 			outs->dma_address = dma_addr;
508 			outs->dma_length = slen;
509 		}
510 
511 		/* Calculate next page pointer for contiguous check */
512 		dma_next = dma_addr + slen;
513 
514 		DBG("  - dma next is: %lx\n", dma_next);
515 	}
516 
517 	/* Flush/invalidate TLB caches if necessary */
518 	if (tbl->it_ops->flush)
519 		tbl->it_ops->flush(tbl);
520 
521 	DBG("mapped %d elements:\n", outcount);
522 
523 	/* For the sake of ppc_iommu_unmap_sg, we clear out the length in the
524 	 * next entry of the sglist if we didn't fill the list completely
525 	 */
526 	if (outcount < incount) {
527 		outs = sg_next(outs);
528 		outs->dma_address = DMA_MAPPING_ERROR;
529 		outs->dma_length = 0;
530 	}
531 
532 	/* Make sure updates are seen by hardware */
533 	mb();
534 
535 	return outcount;
536 
537  failure:
538 	for_each_sg(sglist, s, nelems, i) {
539 		if (s->dma_length != 0) {
540 			unsigned long vaddr, npages;
541 
542 			vaddr = s->dma_address & IOMMU_PAGE_MASK(tbl);
543 			npages = iommu_num_pages(s->dma_address, s->dma_length,
544 						 IOMMU_PAGE_SIZE(tbl));
545 			__iommu_free(tbl, vaddr, npages);
546 			s->dma_address = DMA_MAPPING_ERROR;
547 			s->dma_length = 0;
548 		}
549 		if (s == outs)
550 			break;
551 	}
552 	return 0;
553 }
554 
555 
556 void ppc_iommu_unmap_sg(struct iommu_table *tbl, struct scatterlist *sglist,
557 			int nelems, enum dma_data_direction direction,
558 			unsigned long attrs)
559 {
560 	struct scatterlist *sg;
561 
562 	BUG_ON(direction == DMA_NONE);
563 
564 	if (!tbl)
565 		return;
566 
567 	sg = sglist;
568 	while (nelems--) {
569 		unsigned int npages;
570 		dma_addr_t dma_handle = sg->dma_address;
571 
572 		if (sg->dma_length == 0)
573 			break;
574 		npages = iommu_num_pages(dma_handle, sg->dma_length,
575 					 IOMMU_PAGE_SIZE(tbl));
576 		__iommu_free(tbl, dma_handle, npages);
577 		sg = sg_next(sg);
578 	}
579 
580 	/* Flush/invalidate TLBs if necessary. As for iommu_free(), we
581 	 * do not do an mb() here, the affected platforms do not need it
582 	 * when freeing.
583 	 */
584 	if (tbl->it_ops->flush)
585 		tbl->it_ops->flush(tbl);
586 }
587 
588 static void iommu_table_clear(struct iommu_table *tbl)
589 {
590 	/*
591 	 * In case of firmware assisted dump system goes through clean
592 	 * reboot process at the time of system crash. Hence it's safe to
593 	 * clear the TCE entries if firmware assisted dump is active.
594 	 */
595 	if (!is_kdump_kernel() || is_fadump_active()) {
596 		/* Clear the table in case firmware left allocations in it */
597 		tbl->it_ops->clear(tbl, tbl->it_offset, tbl->it_size);
598 		return;
599 	}
600 
601 #ifdef CONFIG_CRASH_DUMP
602 	if (tbl->it_ops->get) {
603 		unsigned long index, tceval, tcecount = 0;
604 
605 		/* Reserve the existing mappings left by the first kernel. */
606 		for (index = 0; index < tbl->it_size; index++) {
607 			tceval = tbl->it_ops->get(tbl, index + tbl->it_offset);
608 			/*
609 			 * Freed TCE entry contains 0x7fffffffffffffff on JS20
610 			 */
611 			if (tceval && (tceval != 0x7fffffffffffffffUL)) {
612 				__set_bit(index, tbl->it_map);
613 				tcecount++;
614 			}
615 		}
616 
617 		if ((tbl->it_size - tcecount) < KDUMP_MIN_TCE_ENTRIES) {
618 			printk(KERN_WARNING "TCE table is full; freeing ");
619 			printk(KERN_WARNING "%d entries for the kdump boot\n",
620 				KDUMP_MIN_TCE_ENTRIES);
621 			for (index = tbl->it_size - KDUMP_MIN_TCE_ENTRIES;
622 				index < tbl->it_size; index++)
623 				__clear_bit(index, tbl->it_map);
624 		}
625 	}
626 #endif
627 }
628 
629 static void iommu_table_reserve_pages(struct iommu_table *tbl,
630 		unsigned long res_start, unsigned long res_end)
631 {
632 	int i;
633 
634 	WARN_ON_ONCE(res_end < res_start);
635 	/*
636 	 * Reserve page 0 so it will not be used for any mappings.
637 	 * This avoids buggy drivers that consider page 0 to be invalid
638 	 * to crash the machine or even lose data.
639 	 */
640 	if (tbl->it_offset == 0)
641 		set_bit(0, tbl->it_map);
642 
643 	tbl->it_reserved_start = res_start;
644 	tbl->it_reserved_end = res_end;
645 
646 	/* Check if res_start..res_end isn't empty and overlaps the table */
647 	if (res_start && res_end &&
648 			(tbl->it_offset + tbl->it_size < res_start ||
649 			 res_end < tbl->it_offset))
650 		return;
651 
652 	for (i = tbl->it_reserved_start; i < tbl->it_reserved_end; ++i)
653 		set_bit(i - tbl->it_offset, tbl->it_map);
654 }
655 
656 static void iommu_table_release_pages(struct iommu_table *tbl)
657 {
658 	int i;
659 
660 	/*
661 	 * In case we have reserved the first bit, we should not emit
662 	 * the warning below.
663 	 */
664 	if (tbl->it_offset == 0)
665 		clear_bit(0, tbl->it_map);
666 
667 	for (i = tbl->it_reserved_start; i < tbl->it_reserved_end; ++i)
668 		clear_bit(i - tbl->it_offset, tbl->it_map);
669 }
670 
671 /*
672  * Build a iommu_table structure.  This contains a bit map which
673  * is used to manage allocation of the tce space.
674  */
675 struct iommu_table *iommu_init_table(struct iommu_table *tbl, int nid,
676 		unsigned long res_start, unsigned long res_end)
677 {
678 	unsigned long sz;
679 	static int welcomed = 0;
680 	struct page *page;
681 	unsigned int i;
682 	struct iommu_pool *p;
683 
684 	BUG_ON(!tbl->it_ops);
685 
686 	/* number of bytes needed for the bitmap */
687 	sz = BITS_TO_LONGS(tbl->it_size) * sizeof(unsigned long);
688 
689 	page = alloc_pages_node(nid, GFP_KERNEL, get_order(sz));
690 	if (!page)
691 		panic("iommu_init_table: Can't allocate %ld bytes\n", sz);
692 	tbl->it_map = page_address(page);
693 	memset(tbl->it_map, 0, sz);
694 
695 	iommu_table_reserve_pages(tbl, res_start, res_end);
696 
697 	/* We only split the IOMMU table if we have 1GB or more of space */
698 	if ((tbl->it_size << tbl->it_page_shift) >= (1UL * 1024 * 1024 * 1024))
699 		tbl->nr_pools = IOMMU_NR_POOLS;
700 	else
701 		tbl->nr_pools = 1;
702 
703 	/* We reserve the top 1/4 of the table for large allocations */
704 	tbl->poolsize = (tbl->it_size * 3 / 4) / tbl->nr_pools;
705 
706 	for (i = 0; i < tbl->nr_pools; i++) {
707 		p = &tbl->pools[i];
708 		spin_lock_init(&(p->lock));
709 		p->start = tbl->poolsize * i;
710 		p->hint = p->start;
711 		p->end = p->start + tbl->poolsize;
712 	}
713 
714 	p = &tbl->large_pool;
715 	spin_lock_init(&(p->lock));
716 	p->start = tbl->poolsize * i;
717 	p->hint = p->start;
718 	p->end = tbl->it_size;
719 
720 	iommu_table_clear(tbl);
721 
722 	if (!welcomed) {
723 		printk(KERN_INFO "IOMMU table initialized, virtual merging %s\n",
724 		       novmerge ? "disabled" : "enabled");
725 		welcomed = 1;
726 	}
727 
728 	return tbl;
729 }
730 
731 static void iommu_table_free(struct kref *kref)
732 {
733 	unsigned long bitmap_sz;
734 	unsigned int order;
735 	struct iommu_table *tbl;
736 
737 	tbl = container_of(kref, struct iommu_table, it_kref);
738 
739 	if (tbl->it_ops->free)
740 		tbl->it_ops->free(tbl);
741 
742 	if (!tbl->it_map) {
743 		kfree(tbl);
744 		return;
745 	}
746 
747 	iommu_table_release_pages(tbl);
748 
749 	/* verify that table contains no entries */
750 	if (!bitmap_empty(tbl->it_map, tbl->it_size))
751 		pr_warn("%s: Unexpected TCEs\n", __func__);
752 
753 	/* calculate bitmap size in bytes */
754 	bitmap_sz = BITS_TO_LONGS(tbl->it_size) * sizeof(unsigned long);
755 
756 	/* free bitmap */
757 	order = get_order(bitmap_sz);
758 	free_pages((unsigned long) tbl->it_map, order);
759 
760 	/* free table */
761 	kfree(tbl);
762 }
763 
764 struct iommu_table *iommu_tce_table_get(struct iommu_table *tbl)
765 {
766 	if (kref_get_unless_zero(&tbl->it_kref))
767 		return tbl;
768 
769 	return NULL;
770 }
771 EXPORT_SYMBOL_GPL(iommu_tce_table_get);
772 
773 int iommu_tce_table_put(struct iommu_table *tbl)
774 {
775 	if (WARN_ON(!tbl))
776 		return 0;
777 
778 	return kref_put(&tbl->it_kref, iommu_table_free);
779 }
780 EXPORT_SYMBOL_GPL(iommu_tce_table_put);
781 
782 /* Creates TCEs for a user provided buffer.  The user buffer must be
783  * contiguous real kernel storage (not vmalloc).  The address passed here
784  * comprises a page address and offset into that page. The dma_addr_t
785  * returned will point to the same byte within the page as was passed in.
786  */
787 dma_addr_t iommu_map_page(struct device *dev, struct iommu_table *tbl,
788 			  struct page *page, unsigned long offset, size_t size,
789 			  unsigned long mask, enum dma_data_direction direction,
790 			  unsigned long attrs)
791 {
792 	dma_addr_t dma_handle = DMA_MAPPING_ERROR;
793 	void *vaddr;
794 	unsigned long uaddr;
795 	unsigned int npages, align;
796 
797 	BUG_ON(direction == DMA_NONE);
798 
799 	vaddr = page_address(page) + offset;
800 	uaddr = (unsigned long)vaddr;
801 
802 	if (tbl) {
803 		npages = iommu_num_pages(uaddr, size, IOMMU_PAGE_SIZE(tbl));
804 		align = 0;
805 		if (tbl->it_page_shift < PAGE_SHIFT && size >= PAGE_SIZE &&
806 		    ((unsigned long)vaddr & ~PAGE_MASK) == 0)
807 			align = PAGE_SHIFT - tbl->it_page_shift;
808 
809 		dma_handle = iommu_alloc(dev, tbl, vaddr, npages, direction,
810 					 mask >> tbl->it_page_shift, align,
811 					 attrs);
812 		if (dma_handle == DMA_MAPPING_ERROR) {
813 			if (!(attrs & DMA_ATTR_NO_WARN) &&
814 			    printk_ratelimit())  {
815 				dev_info(dev, "iommu_alloc failed, tbl %p "
816 					 "vaddr %p npages %d\n", tbl, vaddr,
817 					 npages);
818 			}
819 		} else
820 			dma_handle |= (uaddr & ~IOMMU_PAGE_MASK(tbl));
821 	}
822 
823 	return dma_handle;
824 }
825 
826 void iommu_unmap_page(struct iommu_table *tbl, dma_addr_t dma_handle,
827 		      size_t size, enum dma_data_direction direction,
828 		      unsigned long attrs)
829 {
830 	unsigned int npages;
831 
832 	BUG_ON(direction == DMA_NONE);
833 
834 	if (tbl) {
835 		npages = iommu_num_pages(dma_handle, size,
836 					 IOMMU_PAGE_SIZE(tbl));
837 		iommu_free(tbl, dma_handle, npages);
838 	}
839 }
840 
841 /* Allocates a contiguous real buffer and creates mappings over it.
842  * Returns the virtual address of the buffer and sets dma_handle
843  * to the dma address (mapping) of the first page.
844  */
845 void *iommu_alloc_coherent(struct device *dev, struct iommu_table *tbl,
846 			   size_t size,	dma_addr_t *dma_handle,
847 			   unsigned long mask, gfp_t flag, int node)
848 {
849 	void *ret = NULL;
850 	dma_addr_t mapping;
851 	unsigned int order;
852 	unsigned int nio_pages, io_order;
853 	struct page *page;
854 
855 	size = PAGE_ALIGN(size);
856 	order = get_order(size);
857 
858  	/*
859 	 * Client asked for way too much space.  This is checked later
860 	 * anyway.  It is easier to debug here for the drivers than in
861 	 * the tce tables.
862 	 */
863 	if (order >= IOMAP_MAX_ORDER) {
864 		dev_info(dev, "iommu_alloc_consistent size too large: 0x%lx\n",
865 			 size);
866 		return NULL;
867 	}
868 
869 	if (!tbl)
870 		return NULL;
871 
872 	/* Alloc enough pages (and possibly more) */
873 	page = alloc_pages_node(node, flag, order);
874 	if (!page)
875 		return NULL;
876 	ret = page_address(page);
877 	memset(ret, 0, size);
878 
879 	/* Set up tces to cover the allocated range */
880 	nio_pages = size >> tbl->it_page_shift;
881 	io_order = get_iommu_order(size, tbl);
882 	mapping = iommu_alloc(dev, tbl, ret, nio_pages, DMA_BIDIRECTIONAL,
883 			      mask >> tbl->it_page_shift, io_order, 0);
884 	if (mapping == DMA_MAPPING_ERROR) {
885 		free_pages((unsigned long)ret, order);
886 		return NULL;
887 	}
888 	*dma_handle = mapping;
889 	return ret;
890 }
891 
892 void iommu_free_coherent(struct iommu_table *tbl, size_t size,
893 			 void *vaddr, dma_addr_t dma_handle)
894 {
895 	if (tbl) {
896 		unsigned int nio_pages;
897 
898 		size = PAGE_ALIGN(size);
899 		nio_pages = size >> tbl->it_page_shift;
900 		iommu_free(tbl, dma_handle, nio_pages);
901 		size = PAGE_ALIGN(size);
902 		free_pages((unsigned long)vaddr, get_order(size));
903 	}
904 }
905 
906 unsigned long iommu_direction_to_tce_perm(enum dma_data_direction dir)
907 {
908 	switch (dir) {
909 	case DMA_BIDIRECTIONAL:
910 		return TCE_PCI_READ | TCE_PCI_WRITE;
911 	case DMA_FROM_DEVICE:
912 		return TCE_PCI_WRITE;
913 	case DMA_TO_DEVICE:
914 		return TCE_PCI_READ;
915 	default:
916 		return 0;
917 	}
918 }
919 EXPORT_SYMBOL_GPL(iommu_direction_to_tce_perm);
920 
921 #ifdef CONFIG_IOMMU_API
922 /*
923  * SPAPR TCE API
924  */
925 static void group_release(void *iommu_data)
926 {
927 	struct iommu_table_group *table_group = iommu_data;
928 
929 	table_group->group = NULL;
930 }
931 
932 void iommu_register_group(struct iommu_table_group *table_group,
933 		int pci_domain_number, unsigned long pe_num)
934 {
935 	struct iommu_group *grp;
936 	char *name;
937 
938 	grp = iommu_group_alloc();
939 	if (IS_ERR(grp)) {
940 		pr_warn("powerpc iommu api: cannot create new group, err=%ld\n",
941 				PTR_ERR(grp));
942 		return;
943 	}
944 	table_group->group = grp;
945 	iommu_group_set_iommudata(grp, table_group, group_release);
946 	name = kasprintf(GFP_KERNEL, "domain%d-pe%lx",
947 			pci_domain_number, pe_num);
948 	if (!name)
949 		return;
950 	iommu_group_set_name(grp, name);
951 	kfree(name);
952 }
953 
954 enum dma_data_direction iommu_tce_direction(unsigned long tce)
955 {
956 	if ((tce & TCE_PCI_READ) && (tce & TCE_PCI_WRITE))
957 		return DMA_BIDIRECTIONAL;
958 	else if (tce & TCE_PCI_READ)
959 		return DMA_TO_DEVICE;
960 	else if (tce & TCE_PCI_WRITE)
961 		return DMA_FROM_DEVICE;
962 	else
963 		return DMA_NONE;
964 }
965 EXPORT_SYMBOL_GPL(iommu_tce_direction);
966 
967 void iommu_flush_tce(struct iommu_table *tbl)
968 {
969 	/* Flush/invalidate TLB caches if necessary */
970 	if (tbl->it_ops->flush)
971 		tbl->it_ops->flush(tbl);
972 
973 	/* Make sure updates are seen by hardware */
974 	mb();
975 }
976 EXPORT_SYMBOL_GPL(iommu_flush_tce);
977 
978 int iommu_tce_check_ioba(unsigned long page_shift,
979 		unsigned long offset, unsigned long size,
980 		unsigned long ioba, unsigned long npages)
981 {
982 	unsigned long mask = (1UL << page_shift) - 1;
983 
984 	if (ioba & mask)
985 		return -EINVAL;
986 
987 	ioba >>= page_shift;
988 	if (ioba < offset)
989 		return -EINVAL;
990 
991 	if ((ioba + 1) > (offset + size))
992 		return -EINVAL;
993 
994 	return 0;
995 }
996 EXPORT_SYMBOL_GPL(iommu_tce_check_ioba);
997 
998 int iommu_tce_check_gpa(unsigned long page_shift, unsigned long gpa)
999 {
1000 	unsigned long mask = (1UL << page_shift) - 1;
1001 
1002 	if (gpa & mask)
1003 		return -EINVAL;
1004 
1005 	return 0;
1006 }
1007 EXPORT_SYMBOL_GPL(iommu_tce_check_gpa);
1008 
1009 extern long iommu_tce_xchg_no_kill(struct mm_struct *mm,
1010 		struct iommu_table *tbl,
1011 		unsigned long entry, unsigned long *hpa,
1012 		enum dma_data_direction *direction)
1013 {
1014 	long ret;
1015 	unsigned long size = 0;
1016 
1017 	ret = tbl->it_ops->xchg_no_kill(tbl, entry, hpa, direction, false);
1018 	if (!ret && ((*direction == DMA_FROM_DEVICE) ||
1019 			(*direction == DMA_BIDIRECTIONAL)) &&
1020 			!mm_iommu_is_devmem(mm, *hpa, tbl->it_page_shift,
1021 					&size))
1022 		SetPageDirty(pfn_to_page(*hpa >> PAGE_SHIFT));
1023 
1024 	return ret;
1025 }
1026 EXPORT_SYMBOL_GPL(iommu_tce_xchg_no_kill);
1027 
1028 void iommu_tce_kill(struct iommu_table *tbl,
1029 		unsigned long entry, unsigned long pages)
1030 {
1031 	if (tbl->it_ops->tce_kill)
1032 		tbl->it_ops->tce_kill(tbl, entry, pages, false);
1033 }
1034 EXPORT_SYMBOL_GPL(iommu_tce_kill);
1035 
1036 int iommu_take_ownership(struct iommu_table *tbl)
1037 {
1038 	unsigned long flags, i, sz = (tbl->it_size + 7) >> 3;
1039 	int ret = 0;
1040 
1041 	/*
1042 	 * VFIO does not control TCE entries allocation and the guest
1043 	 * can write new TCEs on top of existing ones so iommu_tce_build()
1044 	 * must be able to release old pages. This functionality
1045 	 * requires exchange() callback defined so if it is not
1046 	 * implemented, we disallow taking ownership over the table.
1047 	 */
1048 	if (!tbl->it_ops->xchg_no_kill)
1049 		return -EINVAL;
1050 
1051 	spin_lock_irqsave(&tbl->large_pool.lock, flags);
1052 	for (i = 0; i < tbl->nr_pools; i++)
1053 		spin_lock(&tbl->pools[i].lock);
1054 
1055 	iommu_table_release_pages(tbl);
1056 
1057 	if (!bitmap_empty(tbl->it_map, tbl->it_size)) {
1058 		pr_err("iommu_tce: it_map is not empty");
1059 		ret = -EBUSY;
1060 		/* Undo iommu_table_release_pages, i.e. restore bit#0, etc */
1061 		iommu_table_reserve_pages(tbl, tbl->it_reserved_start,
1062 				tbl->it_reserved_end);
1063 	} else {
1064 		memset(tbl->it_map, 0xff, sz);
1065 	}
1066 
1067 	for (i = 0; i < tbl->nr_pools; i++)
1068 		spin_unlock(&tbl->pools[i].lock);
1069 	spin_unlock_irqrestore(&tbl->large_pool.lock, flags);
1070 
1071 	return ret;
1072 }
1073 EXPORT_SYMBOL_GPL(iommu_take_ownership);
1074 
1075 void iommu_release_ownership(struct iommu_table *tbl)
1076 {
1077 	unsigned long flags, i, sz = (tbl->it_size + 7) >> 3;
1078 
1079 	spin_lock_irqsave(&tbl->large_pool.lock, flags);
1080 	for (i = 0; i < tbl->nr_pools; i++)
1081 		spin_lock(&tbl->pools[i].lock);
1082 
1083 	memset(tbl->it_map, 0, sz);
1084 
1085 	iommu_table_reserve_pages(tbl, tbl->it_reserved_start,
1086 			tbl->it_reserved_end);
1087 
1088 	for (i = 0; i < tbl->nr_pools; i++)
1089 		spin_unlock(&tbl->pools[i].lock);
1090 	spin_unlock_irqrestore(&tbl->large_pool.lock, flags);
1091 }
1092 EXPORT_SYMBOL_GPL(iommu_release_ownership);
1093 
1094 int iommu_add_device(struct iommu_table_group *table_group, struct device *dev)
1095 {
1096 	/*
1097 	 * The sysfs entries should be populated before
1098 	 * binding IOMMU group. If sysfs entries isn't
1099 	 * ready, we simply bail.
1100 	 */
1101 	if (!device_is_registered(dev))
1102 		return -ENOENT;
1103 
1104 	if (device_iommu_mapped(dev)) {
1105 		pr_debug("%s: Skipping device %s with iommu group %d\n",
1106 			 __func__, dev_name(dev),
1107 			 iommu_group_id(dev->iommu_group));
1108 		return -EBUSY;
1109 	}
1110 
1111 	pr_debug("%s: Adding %s to iommu group %d\n",
1112 		 __func__, dev_name(dev),  iommu_group_id(table_group->group));
1113 
1114 	return iommu_group_add_device(table_group->group, dev);
1115 }
1116 EXPORT_SYMBOL_GPL(iommu_add_device);
1117 
1118 void iommu_del_device(struct device *dev)
1119 {
1120 	/*
1121 	 * Some devices might not have IOMMU table and group
1122 	 * and we needn't detach them from the associated
1123 	 * IOMMU groups
1124 	 */
1125 	if (!device_iommu_mapped(dev)) {
1126 		pr_debug("iommu_tce: skipping device %s with no tbl\n",
1127 			 dev_name(dev));
1128 		return;
1129 	}
1130 
1131 	iommu_group_remove_device(dev);
1132 }
1133 EXPORT_SYMBOL_GPL(iommu_del_device);
1134 #endif /* CONFIG_IOMMU_API */
1135