xref: /openbmc/linux/drivers/iommu/iova.c (revision 9dbbc3b9)
1 // SPDX-License-Identifier: GPL-2.0-only
2 /*
3  * Copyright © 2006-2009, Intel Corporation.
4  *
5  * Author: Anil S Keshavamurthy <anil.s.keshavamurthy@intel.com>
6  */
7 
8 #include <linux/iova.h>
9 #include <linux/module.h>
10 #include <linux/slab.h>
11 #include <linux/smp.h>
12 #include <linux/bitops.h>
13 #include <linux/cpu.h>
14 
15 /* The anchor node sits above the top of the usable address space */
16 #define IOVA_ANCHOR	~0UL
17 
18 static bool iova_rcache_insert(struct iova_domain *iovad,
19 			       unsigned long pfn,
20 			       unsigned long size);
21 static unsigned long iova_rcache_get(struct iova_domain *iovad,
22 				     unsigned long size,
23 				     unsigned long limit_pfn);
24 static void init_iova_rcaches(struct iova_domain *iovad);
25 static void free_cpu_cached_iovas(unsigned int cpu, struct iova_domain *iovad);
26 static void free_iova_rcaches(struct iova_domain *iovad);
27 static void fq_destroy_all_entries(struct iova_domain *iovad);
28 static void fq_flush_timeout(struct timer_list *t);
29 
30 static int iova_cpuhp_dead(unsigned int cpu, struct hlist_node *node)
31 {
32 	struct iova_domain *iovad;
33 
34 	iovad = hlist_entry_safe(node, struct iova_domain, cpuhp_dead);
35 
36 	free_cpu_cached_iovas(cpu, iovad);
37 	return 0;
38 }
39 
40 static void free_global_cached_iovas(struct iova_domain *iovad);
41 
42 static struct iova *to_iova(struct rb_node *node)
43 {
44 	return rb_entry(node, struct iova, node);
45 }
46 
47 void
48 init_iova_domain(struct iova_domain *iovad, unsigned long granule,
49 	unsigned long start_pfn)
50 {
51 	/*
52 	 * IOVA granularity will normally be equal to the smallest
53 	 * supported IOMMU page size; both *must* be capable of
54 	 * representing individual CPU pages exactly.
55 	 */
56 	BUG_ON((granule > PAGE_SIZE) || !is_power_of_2(granule));
57 
58 	spin_lock_init(&iovad->iova_rbtree_lock);
59 	iovad->rbroot = RB_ROOT;
60 	iovad->cached_node = &iovad->anchor.node;
61 	iovad->cached32_node = &iovad->anchor.node;
62 	iovad->granule = granule;
63 	iovad->start_pfn = start_pfn;
64 	iovad->dma_32bit_pfn = 1UL << (32 - iova_shift(iovad));
65 	iovad->max32_alloc_size = iovad->dma_32bit_pfn;
66 	iovad->flush_cb = NULL;
67 	iovad->fq = NULL;
68 	iovad->anchor.pfn_lo = iovad->anchor.pfn_hi = IOVA_ANCHOR;
69 	rb_link_node(&iovad->anchor.node, NULL, &iovad->rbroot.rb_node);
70 	rb_insert_color(&iovad->anchor.node, &iovad->rbroot);
71 	cpuhp_state_add_instance_nocalls(CPUHP_IOMMU_IOVA_DEAD, &iovad->cpuhp_dead);
72 	init_iova_rcaches(iovad);
73 }
74 EXPORT_SYMBOL_GPL(init_iova_domain);
75 
76 static bool has_iova_flush_queue(struct iova_domain *iovad)
77 {
78 	return !!iovad->fq;
79 }
80 
81 static void free_iova_flush_queue(struct iova_domain *iovad)
82 {
83 	if (!has_iova_flush_queue(iovad))
84 		return;
85 
86 	if (timer_pending(&iovad->fq_timer))
87 		del_timer(&iovad->fq_timer);
88 
89 	fq_destroy_all_entries(iovad);
90 
91 	free_percpu(iovad->fq);
92 
93 	iovad->fq         = NULL;
94 	iovad->flush_cb   = NULL;
95 	iovad->entry_dtor = NULL;
96 }
97 
98 int init_iova_flush_queue(struct iova_domain *iovad,
99 			  iova_flush_cb flush_cb, iova_entry_dtor entry_dtor)
100 {
101 	struct iova_fq __percpu *queue;
102 	int cpu;
103 
104 	atomic64_set(&iovad->fq_flush_start_cnt,  0);
105 	atomic64_set(&iovad->fq_flush_finish_cnt, 0);
106 
107 	queue = alloc_percpu(struct iova_fq);
108 	if (!queue)
109 		return -ENOMEM;
110 
111 	iovad->flush_cb   = flush_cb;
112 	iovad->entry_dtor = entry_dtor;
113 
114 	for_each_possible_cpu(cpu) {
115 		struct iova_fq *fq;
116 
117 		fq = per_cpu_ptr(queue, cpu);
118 		fq->head = 0;
119 		fq->tail = 0;
120 
121 		spin_lock_init(&fq->lock);
122 	}
123 
124 	smp_wmb();
125 
126 	iovad->fq = queue;
127 
128 	timer_setup(&iovad->fq_timer, fq_flush_timeout, 0);
129 	atomic_set(&iovad->fq_timer_on, 0);
130 
131 	return 0;
132 }
133 
134 static struct rb_node *
135 __get_cached_rbnode(struct iova_domain *iovad, unsigned long limit_pfn)
136 {
137 	if (limit_pfn <= iovad->dma_32bit_pfn)
138 		return iovad->cached32_node;
139 
140 	return iovad->cached_node;
141 }
142 
143 static void
144 __cached_rbnode_insert_update(struct iova_domain *iovad, struct iova *new)
145 {
146 	if (new->pfn_hi < iovad->dma_32bit_pfn)
147 		iovad->cached32_node = &new->node;
148 	else
149 		iovad->cached_node = &new->node;
150 }
151 
152 static void
153 __cached_rbnode_delete_update(struct iova_domain *iovad, struct iova *free)
154 {
155 	struct iova *cached_iova;
156 
157 	cached_iova = to_iova(iovad->cached32_node);
158 	if (free == cached_iova ||
159 	    (free->pfn_hi < iovad->dma_32bit_pfn &&
160 	     free->pfn_lo >= cached_iova->pfn_lo)) {
161 		iovad->cached32_node = rb_next(&free->node);
162 		iovad->max32_alloc_size = iovad->dma_32bit_pfn;
163 	}
164 
165 	cached_iova = to_iova(iovad->cached_node);
166 	if (free->pfn_lo >= cached_iova->pfn_lo)
167 		iovad->cached_node = rb_next(&free->node);
168 }
169 
170 static struct rb_node *iova_find_limit(struct iova_domain *iovad, unsigned long limit_pfn)
171 {
172 	struct rb_node *node, *next;
173 	/*
174 	 * Ideally what we'd like to judge here is whether limit_pfn is close
175 	 * enough to the highest-allocated IOVA that starting the allocation
176 	 * walk from the anchor node will be quicker than this initial work to
177 	 * find an exact starting point (especially if that ends up being the
178 	 * anchor node anyway). This is an incredibly crude approximation which
179 	 * only really helps the most likely case, but is at least trivially easy.
180 	 */
181 	if (limit_pfn > iovad->dma_32bit_pfn)
182 		return &iovad->anchor.node;
183 
184 	node = iovad->rbroot.rb_node;
185 	while (to_iova(node)->pfn_hi < limit_pfn)
186 		node = node->rb_right;
187 
188 search_left:
189 	while (node->rb_left && to_iova(node->rb_left)->pfn_lo >= limit_pfn)
190 		node = node->rb_left;
191 
192 	if (!node->rb_left)
193 		return node;
194 
195 	next = node->rb_left;
196 	while (next->rb_right) {
197 		next = next->rb_right;
198 		if (to_iova(next)->pfn_lo >= limit_pfn) {
199 			node = next;
200 			goto search_left;
201 		}
202 	}
203 
204 	return node;
205 }
206 
207 /* Insert the iova into domain rbtree by holding writer lock */
208 static void
209 iova_insert_rbtree(struct rb_root *root, struct iova *iova,
210 		   struct rb_node *start)
211 {
212 	struct rb_node **new, *parent = NULL;
213 
214 	new = (start) ? &start : &(root->rb_node);
215 	/* Figure out where to put new node */
216 	while (*new) {
217 		struct iova *this = to_iova(*new);
218 
219 		parent = *new;
220 
221 		if (iova->pfn_lo < this->pfn_lo)
222 			new = &((*new)->rb_left);
223 		else if (iova->pfn_lo > this->pfn_lo)
224 			new = &((*new)->rb_right);
225 		else {
226 			WARN_ON(1); /* this should not happen */
227 			return;
228 		}
229 	}
230 	/* Add new node and rebalance tree. */
231 	rb_link_node(&iova->node, parent, new);
232 	rb_insert_color(&iova->node, root);
233 }
234 
235 static int __alloc_and_insert_iova_range(struct iova_domain *iovad,
236 		unsigned long size, unsigned long limit_pfn,
237 			struct iova *new, bool size_aligned)
238 {
239 	struct rb_node *curr, *prev;
240 	struct iova *curr_iova;
241 	unsigned long flags;
242 	unsigned long new_pfn, retry_pfn;
243 	unsigned long align_mask = ~0UL;
244 	unsigned long high_pfn = limit_pfn, low_pfn = iovad->start_pfn;
245 
246 	if (size_aligned)
247 		align_mask <<= fls_long(size - 1);
248 
249 	/* Walk the tree backwards */
250 	spin_lock_irqsave(&iovad->iova_rbtree_lock, flags);
251 	if (limit_pfn <= iovad->dma_32bit_pfn &&
252 			size >= iovad->max32_alloc_size)
253 		goto iova32_full;
254 
255 	curr = __get_cached_rbnode(iovad, limit_pfn);
256 	curr_iova = to_iova(curr);
257 	retry_pfn = curr_iova->pfn_hi + 1;
258 
259 retry:
260 	do {
261 		high_pfn = min(high_pfn, curr_iova->pfn_lo);
262 		new_pfn = (high_pfn - size) & align_mask;
263 		prev = curr;
264 		curr = rb_prev(curr);
265 		curr_iova = to_iova(curr);
266 	} while (curr && new_pfn <= curr_iova->pfn_hi && new_pfn >= low_pfn);
267 
268 	if (high_pfn < size || new_pfn < low_pfn) {
269 		if (low_pfn == iovad->start_pfn && retry_pfn < limit_pfn) {
270 			high_pfn = limit_pfn;
271 			low_pfn = retry_pfn;
272 			curr = iova_find_limit(iovad, limit_pfn);
273 			curr_iova = to_iova(curr);
274 			goto retry;
275 		}
276 		iovad->max32_alloc_size = size;
277 		goto iova32_full;
278 	}
279 
280 	/* pfn_lo will point to size aligned address if size_aligned is set */
281 	new->pfn_lo = new_pfn;
282 	new->pfn_hi = new->pfn_lo + size - 1;
283 
284 	/* If we have 'prev', it's a valid place to start the insertion. */
285 	iova_insert_rbtree(&iovad->rbroot, new, prev);
286 	__cached_rbnode_insert_update(iovad, new);
287 
288 	spin_unlock_irqrestore(&iovad->iova_rbtree_lock, flags);
289 	return 0;
290 
291 iova32_full:
292 	spin_unlock_irqrestore(&iovad->iova_rbtree_lock, flags);
293 	return -ENOMEM;
294 }
295 
296 static struct kmem_cache *iova_cache;
297 static unsigned int iova_cache_users;
298 static DEFINE_MUTEX(iova_cache_mutex);
299 
300 static struct iova *alloc_iova_mem(void)
301 {
302 	return kmem_cache_zalloc(iova_cache, GFP_ATOMIC | __GFP_NOWARN);
303 }
304 
305 static void free_iova_mem(struct iova *iova)
306 {
307 	if (iova->pfn_lo != IOVA_ANCHOR)
308 		kmem_cache_free(iova_cache, iova);
309 }
310 
311 int iova_cache_get(void)
312 {
313 	mutex_lock(&iova_cache_mutex);
314 	if (!iova_cache_users) {
315 		int ret;
316 
317 		ret = cpuhp_setup_state_multi(CPUHP_IOMMU_IOVA_DEAD, "iommu/iova:dead", NULL,
318 					iova_cpuhp_dead);
319 		if (ret) {
320 			mutex_unlock(&iova_cache_mutex);
321 			pr_err("Couldn't register cpuhp handler\n");
322 			return ret;
323 		}
324 
325 		iova_cache = kmem_cache_create(
326 			"iommu_iova", sizeof(struct iova), 0,
327 			SLAB_HWCACHE_ALIGN, NULL);
328 		if (!iova_cache) {
329 			cpuhp_remove_multi_state(CPUHP_IOMMU_IOVA_DEAD);
330 			mutex_unlock(&iova_cache_mutex);
331 			pr_err("Couldn't create iova cache\n");
332 			return -ENOMEM;
333 		}
334 	}
335 
336 	iova_cache_users++;
337 	mutex_unlock(&iova_cache_mutex);
338 
339 	return 0;
340 }
341 EXPORT_SYMBOL_GPL(iova_cache_get);
342 
343 void iova_cache_put(void)
344 {
345 	mutex_lock(&iova_cache_mutex);
346 	if (WARN_ON(!iova_cache_users)) {
347 		mutex_unlock(&iova_cache_mutex);
348 		return;
349 	}
350 	iova_cache_users--;
351 	if (!iova_cache_users) {
352 		cpuhp_remove_multi_state(CPUHP_IOMMU_IOVA_DEAD);
353 		kmem_cache_destroy(iova_cache);
354 	}
355 	mutex_unlock(&iova_cache_mutex);
356 }
357 EXPORT_SYMBOL_GPL(iova_cache_put);
358 
359 /**
360  * alloc_iova - allocates an iova
361  * @iovad: - iova domain in question
362  * @size: - size of page frames to allocate
363  * @limit_pfn: - max limit address
364  * @size_aligned: - set if size_aligned address range is required
365  * This function allocates an iova in the range iovad->start_pfn to limit_pfn,
366  * searching top-down from limit_pfn to iovad->start_pfn. If the size_aligned
367  * flag is set then the allocated address iova->pfn_lo will be naturally
368  * aligned on roundup_power_of_two(size).
369  */
370 struct iova *
371 alloc_iova(struct iova_domain *iovad, unsigned long size,
372 	unsigned long limit_pfn,
373 	bool size_aligned)
374 {
375 	struct iova *new_iova;
376 	int ret;
377 
378 	new_iova = alloc_iova_mem();
379 	if (!new_iova)
380 		return NULL;
381 
382 	ret = __alloc_and_insert_iova_range(iovad, size, limit_pfn + 1,
383 			new_iova, size_aligned);
384 
385 	if (ret) {
386 		free_iova_mem(new_iova);
387 		return NULL;
388 	}
389 
390 	return new_iova;
391 }
392 EXPORT_SYMBOL_GPL(alloc_iova);
393 
394 static struct iova *
395 private_find_iova(struct iova_domain *iovad, unsigned long pfn)
396 {
397 	struct rb_node *node = iovad->rbroot.rb_node;
398 
399 	assert_spin_locked(&iovad->iova_rbtree_lock);
400 
401 	while (node) {
402 		struct iova *iova = to_iova(node);
403 
404 		if (pfn < iova->pfn_lo)
405 			node = node->rb_left;
406 		else if (pfn > iova->pfn_hi)
407 			node = node->rb_right;
408 		else
409 			return iova;	/* pfn falls within iova's range */
410 	}
411 
412 	return NULL;
413 }
414 
415 static void remove_iova(struct iova_domain *iovad, struct iova *iova)
416 {
417 	assert_spin_locked(&iovad->iova_rbtree_lock);
418 	__cached_rbnode_delete_update(iovad, iova);
419 	rb_erase(&iova->node, &iovad->rbroot);
420 }
421 
422 /**
423  * find_iova - finds an iova for a given pfn
424  * @iovad: - iova domain in question.
425  * @pfn: - page frame number
426  * This function finds and returns an iova belonging to the
427  * given domain which matches the given pfn.
428  */
429 struct iova *find_iova(struct iova_domain *iovad, unsigned long pfn)
430 {
431 	unsigned long flags;
432 	struct iova *iova;
433 
434 	/* Take the lock so that no other thread is manipulating the rbtree */
435 	spin_lock_irqsave(&iovad->iova_rbtree_lock, flags);
436 	iova = private_find_iova(iovad, pfn);
437 	spin_unlock_irqrestore(&iovad->iova_rbtree_lock, flags);
438 	return iova;
439 }
440 EXPORT_SYMBOL_GPL(find_iova);
441 
442 /**
443  * __free_iova - frees the given iova
444  * @iovad: iova domain in question.
445  * @iova: iova in question.
446  * Frees the given iova belonging to the giving domain
447  */
448 void
449 __free_iova(struct iova_domain *iovad, struct iova *iova)
450 {
451 	unsigned long flags;
452 
453 	spin_lock_irqsave(&iovad->iova_rbtree_lock, flags);
454 	remove_iova(iovad, iova);
455 	spin_unlock_irqrestore(&iovad->iova_rbtree_lock, flags);
456 	free_iova_mem(iova);
457 }
458 EXPORT_SYMBOL_GPL(__free_iova);
459 
460 /**
461  * free_iova - finds and frees the iova for a given pfn
462  * @iovad: - iova domain in question.
463  * @pfn: - pfn that is allocated previously
464  * This functions finds an iova for a given pfn and then
465  * frees the iova from that domain.
466  */
467 void
468 free_iova(struct iova_domain *iovad, unsigned long pfn)
469 {
470 	unsigned long flags;
471 	struct iova *iova;
472 
473 	spin_lock_irqsave(&iovad->iova_rbtree_lock, flags);
474 	iova = private_find_iova(iovad, pfn);
475 	if (!iova) {
476 		spin_unlock_irqrestore(&iovad->iova_rbtree_lock, flags);
477 		return;
478 	}
479 	remove_iova(iovad, iova);
480 	spin_unlock_irqrestore(&iovad->iova_rbtree_lock, flags);
481 	free_iova_mem(iova);
482 }
483 EXPORT_SYMBOL_GPL(free_iova);
484 
485 /**
486  * alloc_iova_fast - allocates an iova from rcache
487  * @iovad: - iova domain in question
488  * @size: - size of page frames to allocate
489  * @limit_pfn: - max limit address
490  * @flush_rcache: - set to flush rcache on regular allocation failure
491  * This function tries to satisfy an iova allocation from the rcache,
492  * and falls back to regular allocation on failure. If regular allocation
493  * fails too and the flush_rcache flag is set then the rcache will be flushed.
494 */
495 unsigned long
496 alloc_iova_fast(struct iova_domain *iovad, unsigned long size,
497 		unsigned long limit_pfn, bool flush_rcache)
498 {
499 	unsigned long iova_pfn;
500 	struct iova *new_iova;
501 
502 	iova_pfn = iova_rcache_get(iovad, size, limit_pfn + 1);
503 	if (iova_pfn)
504 		return iova_pfn;
505 
506 retry:
507 	new_iova = alloc_iova(iovad, size, limit_pfn, true);
508 	if (!new_iova) {
509 		unsigned int cpu;
510 
511 		if (!flush_rcache)
512 			return 0;
513 
514 		/* Try replenishing IOVAs by flushing rcache. */
515 		flush_rcache = false;
516 		for_each_online_cpu(cpu)
517 			free_cpu_cached_iovas(cpu, iovad);
518 		free_global_cached_iovas(iovad);
519 		goto retry;
520 	}
521 
522 	return new_iova->pfn_lo;
523 }
524 
525 /**
526  * free_iova_fast - free iova pfn range into rcache
527  * @iovad: - iova domain in question.
528  * @pfn: - pfn that is allocated previously
529  * @size: - # of pages in range
530  * This functions frees an iova range by trying to put it into the rcache,
531  * falling back to regular iova deallocation via free_iova() if this fails.
532  */
533 void
534 free_iova_fast(struct iova_domain *iovad, unsigned long pfn, unsigned long size)
535 {
536 	if (iova_rcache_insert(iovad, pfn, size))
537 		return;
538 
539 	free_iova(iovad, pfn);
540 }
541 
542 #define fq_ring_for_each(i, fq) \
543 	for ((i) = (fq)->head; (i) != (fq)->tail; (i) = ((i) + 1) % IOVA_FQ_SIZE)
544 
545 static inline bool fq_full(struct iova_fq *fq)
546 {
547 	assert_spin_locked(&fq->lock);
548 	return (((fq->tail + 1) % IOVA_FQ_SIZE) == fq->head);
549 }
550 
551 static inline unsigned fq_ring_add(struct iova_fq *fq)
552 {
553 	unsigned idx = fq->tail;
554 
555 	assert_spin_locked(&fq->lock);
556 
557 	fq->tail = (idx + 1) % IOVA_FQ_SIZE;
558 
559 	return idx;
560 }
561 
562 static void fq_ring_free(struct iova_domain *iovad, struct iova_fq *fq)
563 {
564 	u64 counter = atomic64_read(&iovad->fq_flush_finish_cnt);
565 	unsigned idx;
566 
567 	assert_spin_locked(&fq->lock);
568 
569 	fq_ring_for_each(idx, fq) {
570 
571 		if (fq->entries[idx].counter >= counter)
572 			break;
573 
574 		if (iovad->entry_dtor)
575 			iovad->entry_dtor(fq->entries[idx].data);
576 
577 		free_iova_fast(iovad,
578 			       fq->entries[idx].iova_pfn,
579 			       fq->entries[idx].pages);
580 
581 		fq->head = (fq->head + 1) % IOVA_FQ_SIZE;
582 	}
583 }
584 
585 static void iova_domain_flush(struct iova_domain *iovad)
586 {
587 	atomic64_inc(&iovad->fq_flush_start_cnt);
588 	iovad->flush_cb(iovad);
589 	atomic64_inc(&iovad->fq_flush_finish_cnt);
590 }
591 
592 static void fq_destroy_all_entries(struct iova_domain *iovad)
593 {
594 	int cpu;
595 
596 	/*
597 	 * This code runs when the iova_domain is being detroyed, so don't
598 	 * bother to free iovas, just call the entry_dtor on all remaining
599 	 * entries.
600 	 */
601 	if (!iovad->entry_dtor)
602 		return;
603 
604 	for_each_possible_cpu(cpu) {
605 		struct iova_fq *fq = per_cpu_ptr(iovad->fq, cpu);
606 		int idx;
607 
608 		fq_ring_for_each(idx, fq)
609 			iovad->entry_dtor(fq->entries[idx].data);
610 	}
611 }
612 
613 static void fq_flush_timeout(struct timer_list *t)
614 {
615 	struct iova_domain *iovad = from_timer(iovad, t, fq_timer);
616 	int cpu;
617 
618 	atomic_set(&iovad->fq_timer_on, 0);
619 	iova_domain_flush(iovad);
620 
621 	for_each_possible_cpu(cpu) {
622 		unsigned long flags;
623 		struct iova_fq *fq;
624 
625 		fq = per_cpu_ptr(iovad->fq, cpu);
626 		spin_lock_irqsave(&fq->lock, flags);
627 		fq_ring_free(iovad, fq);
628 		spin_unlock_irqrestore(&fq->lock, flags);
629 	}
630 }
631 
632 void queue_iova(struct iova_domain *iovad,
633 		unsigned long pfn, unsigned long pages,
634 		unsigned long data)
635 {
636 	struct iova_fq *fq = raw_cpu_ptr(iovad->fq);
637 	unsigned long flags;
638 	unsigned idx;
639 
640 	spin_lock_irqsave(&fq->lock, flags);
641 
642 	/*
643 	 * First remove all entries from the flush queue that have already been
644 	 * flushed out on another CPU. This makes the fq_full() check below less
645 	 * likely to be true.
646 	 */
647 	fq_ring_free(iovad, fq);
648 
649 	if (fq_full(fq)) {
650 		iova_domain_flush(iovad);
651 		fq_ring_free(iovad, fq);
652 	}
653 
654 	idx = fq_ring_add(fq);
655 
656 	fq->entries[idx].iova_pfn = pfn;
657 	fq->entries[idx].pages    = pages;
658 	fq->entries[idx].data     = data;
659 	fq->entries[idx].counter  = atomic64_read(&iovad->fq_flush_start_cnt);
660 
661 	spin_unlock_irqrestore(&fq->lock, flags);
662 
663 	/* Avoid false sharing as much as possible. */
664 	if (!atomic_read(&iovad->fq_timer_on) &&
665 	    !atomic_xchg(&iovad->fq_timer_on, 1))
666 		mod_timer(&iovad->fq_timer,
667 			  jiffies + msecs_to_jiffies(IOVA_FQ_TIMEOUT));
668 }
669 
670 /**
671  * put_iova_domain - destroys the iova domain
672  * @iovad: - iova domain in question.
673  * All the iova's in that domain are destroyed.
674  */
675 void put_iova_domain(struct iova_domain *iovad)
676 {
677 	struct iova *iova, *tmp;
678 
679 	cpuhp_state_remove_instance_nocalls(CPUHP_IOMMU_IOVA_DEAD,
680 					    &iovad->cpuhp_dead);
681 
682 	free_iova_flush_queue(iovad);
683 	free_iova_rcaches(iovad);
684 	rbtree_postorder_for_each_entry_safe(iova, tmp, &iovad->rbroot, node)
685 		free_iova_mem(iova);
686 }
687 EXPORT_SYMBOL_GPL(put_iova_domain);
688 
689 static int
690 __is_range_overlap(struct rb_node *node,
691 	unsigned long pfn_lo, unsigned long pfn_hi)
692 {
693 	struct iova *iova = to_iova(node);
694 
695 	if ((pfn_lo <= iova->pfn_hi) && (pfn_hi >= iova->pfn_lo))
696 		return 1;
697 	return 0;
698 }
699 
700 static inline struct iova *
701 alloc_and_init_iova(unsigned long pfn_lo, unsigned long pfn_hi)
702 {
703 	struct iova *iova;
704 
705 	iova = alloc_iova_mem();
706 	if (iova) {
707 		iova->pfn_lo = pfn_lo;
708 		iova->pfn_hi = pfn_hi;
709 	}
710 
711 	return iova;
712 }
713 
714 static struct iova *
715 __insert_new_range(struct iova_domain *iovad,
716 	unsigned long pfn_lo, unsigned long pfn_hi)
717 {
718 	struct iova *iova;
719 
720 	iova = alloc_and_init_iova(pfn_lo, pfn_hi);
721 	if (iova)
722 		iova_insert_rbtree(&iovad->rbroot, iova, NULL);
723 
724 	return iova;
725 }
726 
727 static void
728 __adjust_overlap_range(struct iova *iova,
729 	unsigned long *pfn_lo, unsigned long *pfn_hi)
730 {
731 	if (*pfn_lo < iova->pfn_lo)
732 		iova->pfn_lo = *pfn_lo;
733 	if (*pfn_hi > iova->pfn_hi)
734 		*pfn_lo = iova->pfn_hi + 1;
735 }
736 
737 /**
738  * reserve_iova - reserves an iova in the given range
739  * @iovad: - iova domain pointer
740  * @pfn_lo: - lower page frame address
741  * @pfn_hi:- higher pfn adderss
742  * This function allocates reserves the address range from pfn_lo to pfn_hi so
743  * that this address is not dished out as part of alloc_iova.
744  */
745 struct iova *
746 reserve_iova(struct iova_domain *iovad,
747 	unsigned long pfn_lo, unsigned long pfn_hi)
748 {
749 	struct rb_node *node;
750 	unsigned long flags;
751 	struct iova *iova;
752 	unsigned int overlap = 0;
753 
754 	/* Don't allow nonsensical pfns */
755 	if (WARN_ON((pfn_hi | pfn_lo) > (ULLONG_MAX >> iova_shift(iovad))))
756 		return NULL;
757 
758 	spin_lock_irqsave(&iovad->iova_rbtree_lock, flags);
759 	for (node = rb_first(&iovad->rbroot); node; node = rb_next(node)) {
760 		if (__is_range_overlap(node, pfn_lo, pfn_hi)) {
761 			iova = to_iova(node);
762 			__adjust_overlap_range(iova, &pfn_lo, &pfn_hi);
763 			if ((pfn_lo >= iova->pfn_lo) &&
764 				(pfn_hi <= iova->pfn_hi))
765 				goto finish;
766 			overlap = 1;
767 
768 		} else if (overlap)
769 				break;
770 	}
771 
772 	/* We are here either because this is the first reserver node
773 	 * or need to insert remaining non overlap addr range
774 	 */
775 	iova = __insert_new_range(iovad, pfn_lo, pfn_hi);
776 finish:
777 
778 	spin_unlock_irqrestore(&iovad->iova_rbtree_lock, flags);
779 	return iova;
780 }
781 EXPORT_SYMBOL_GPL(reserve_iova);
782 
783 /*
784  * Magazine caches for IOVA ranges.  For an introduction to magazines,
785  * see the USENIX 2001 paper "Magazines and Vmem: Extending the Slab
786  * Allocator to Many CPUs and Arbitrary Resources" by Bonwick and Adams.
787  * For simplicity, we use a static magazine size and don't implement the
788  * dynamic size tuning described in the paper.
789  */
790 
791 #define IOVA_MAG_SIZE 128
792 
793 struct iova_magazine {
794 	unsigned long size;
795 	unsigned long pfns[IOVA_MAG_SIZE];
796 };
797 
798 struct iova_cpu_rcache {
799 	spinlock_t lock;
800 	struct iova_magazine *loaded;
801 	struct iova_magazine *prev;
802 };
803 
804 static struct iova_magazine *iova_magazine_alloc(gfp_t flags)
805 {
806 	return kzalloc(sizeof(struct iova_magazine), flags);
807 }
808 
809 static void iova_magazine_free(struct iova_magazine *mag)
810 {
811 	kfree(mag);
812 }
813 
814 static void
815 iova_magazine_free_pfns(struct iova_magazine *mag, struct iova_domain *iovad)
816 {
817 	unsigned long flags;
818 	int i;
819 
820 	if (!mag)
821 		return;
822 
823 	spin_lock_irqsave(&iovad->iova_rbtree_lock, flags);
824 
825 	for (i = 0 ; i < mag->size; ++i) {
826 		struct iova *iova = private_find_iova(iovad, mag->pfns[i]);
827 
828 		if (WARN_ON(!iova))
829 			continue;
830 
831 		remove_iova(iovad, iova);
832 		free_iova_mem(iova);
833 	}
834 
835 	spin_unlock_irqrestore(&iovad->iova_rbtree_lock, flags);
836 
837 	mag->size = 0;
838 }
839 
840 static bool iova_magazine_full(struct iova_magazine *mag)
841 {
842 	return (mag && mag->size == IOVA_MAG_SIZE);
843 }
844 
845 static bool iova_magazine_empty(struct iova_magazine *mag)
846 {
847 	return (!mag || mag->size == 0);
848 }
849 
850 static unsigned long iova_magazine_pop(struct iova_magazine *mag,
851 				       unsigned long limit_pfn)
852 {
853 	int i;
854 	unsigned long pfn;
855 
856 	BUG_ON(iova_magazine_empty(mag));
857 
858 	/* Only fall back to the rbtree if we have no suitable pfns at all */
859 	for (i = mag->size - 1; mag->pfns[i] > limit_pfn; i--)
860 		if (i == 0)
861 			return 0;
862 
863 	/* Swap it to pop it */
864 	pfn = mag->pfns[i];
865 	mag->pfns[i] = mag->pfns[--mag->size];
866 
867 	return pfn;
868 }
869 
870 static void iova_magazine_push(struct iova_magazine *mag, unsigned long pfn)
871 {
872 	BUG_ON(iova_magazine_full(mag));
873 
874 	mag->pfns[mag->size++] = pfn;
875 }
876 
877 static void init_iova_rcaches(struct iova_domain *iovad)
878 {
879 	struct iova_cpu_rcache *cpu_rcache;
880 	struct iova_rcache *rcache;
881 	unsigned int cpu;
882 	int i;
883 
884 	for (i = 0; i < IOVA_RANGE_CACHE_MAX_SIZE; ++i) {
885 		rcache = &iovad->rcaches[i];
886 		spin_lock_init(&rcache->lock);
887 		rcache->depot_size = 0;
888 		rcache->cpu_rcaches = __alloc_percpu(sizeof(*cpu_rcache), cache_line_size());
889 		if (WARN_ON(!rcache->cpu_rcaches))
890 			continue;
891 		for_each_possible_cpu(cpu) {
892 			cpu_rcache = per_cpu_ptr(rcache->cpu_rcaches, cpu);
893 			spin_lock_init(&cpu_rcache->lock);
894 			cpu_rcache->loaded = iova_magazine_alloc(GFP_KERNEL);
895 			cpu_rcache->prev = iova_magazine_alloc(GFP_KERNEL);
896 		}
897 	}
898 }
899 
900 /*
901  * Try inserting IOVA range starting with 'iova_pfn' into 'rcache', and
902  * return true on success.  Can fail if rcache is full and we can't free
903  * space, and free_iova() (our only caller) will then return the IOVA
904  * range to the rbtree instead.
905  */
906 static bool __iova_rcache_insert(struct iova_domain *iovad,
907 				 struct iova_rcache *rcache,
908 				 unsigned long iova_pfn)
909 {
910 	struct iova_magazine *mag_to_free = NULL;
911 	struct iova_cpu_rcache *cpu_rcache;
912 	bool can_insert = false;
913 	unsigned long flags;
914 
915 	cpu_rcache = raw_cpu_ptr(rcache->cpu_rcaches);
916 	spin_lock_irqsave(&cpu_rcache->lock, flags);
917 
918 	if (!iova_magazine_full(cpu_rcache->loaded)) {
919 		can_insert = true;
920 	} else if (!iova_magazine_full(cpu_rcache->prev)) {
921 		swap(cpu_rcache->prev, cpu_rcache->loaded);
922 		can_insert = true;
923 	} else {
924 		struct iova_magazine *new_mag = iova_magazine_alloc(GFP_ATOMIC);
925 
926 		if (new_mag) {
927 			spin_lock(&rcache->lock);
928 			if (rcache->depot_size < MAX_GLOBAL_MAGS) {
929 				rcache->depot[rcache->depot_size++] =
930 						cpu_rcache->loaded;
931 			} else {
932 				mag_to_free = cpu_rcache->loaded;
933 			}
934 			spin_unlock(&rcache->lock);
935 
936 			cpu_rcache->loaded = new_mag;
937 			can_insert = true;
938 		}
939 	}
940 
941 	if (can_insert)
942 		iova_magazine_push(cpu_rcache->loaded, iova_pfn);
943 
944 	spin_unlock_irqrestore(&cpu_rcache->lock, flags);
945 
946 	if (mag_to_free) {
947 		iova_magazine_free_pfns(mag_to_free, iovad);
948 		iova_magazine_free(mag_to_free);
949 	}
950 
951 	return can_insert;
952 }
953 
954 static bool iova_rcache_insert(struct iova_domain *iovad, unsigned long pfn,
955 			       unsigned long size)
956 {
957 	unsigned int log_size = order_base_2(size);
958 
959 	if (log_size >= IOVA_RANGE_CACHE_MAX_SIZE)
960 		return false;
961 
962 	return __iova_rcache_insert(iovad, &iovad->rcaches[log_size], pfn);
963 }
964 
965 /*
966  * Caller wants to allocate a new IOVA range from 'rcache'.  If we can
967  * satisfy the request, return a matching non-NULL range and remove
968  * it from the 'rcache'.
969  */
970 static unsigned long __iova_rcache_get(struct iova_rcache *rcache,
971 				       unsigned long limit_pfn)
972 {
973 	struct iova_cpu_rcache *cpu_rcache;
974 	unsigned long iova_pfn = 0;
975 	bool has_pfn = false;
976 	unsigned long flags;
977 
978 	cpu_rcache = raw_cpu_ptr(rcache->cpu_rcaches);
979 	spin_lock_irqsave(&cpu_rcache->lock, flags);
980 
981 	if (!iova_magazine_empty(cpu_rcache->loaded)) {
982 		has_pfn = true;
983 	} else if (!iova_magazine_empty(cpu_rcache->prev)) {
984 		swap(cpu_rcache->prev, cpu_rcache->loaded);
985 		has_pfn = true;
986 	} else {
987 		spin_lock(&rcache->lock);
988 		if (rcache->depot_size > 0) {
989 			iova_magazine_free(cpu_rcache->loaded);
990 			cpu_rcache->loaded = rcache->depot[--rcache->depot_size];
991 			has_pfn = true;
992 		}
993 		spin_unlock(&rcache->lock);
994 	}
995 
996 	if (has_pfn)
997 		iova_pfn = iova_magazine_pop(cpu_rcache->loaded, limit_pfn);
998 
999 	spin_unlock_irqrestore(&cpu_rcache->lock, flags);
1000 
1001 	return iova_pfn;
1002 }
1003 
1004 /*
1005  * Try to satisfy IOVA allocation range from rcache.  Fail if requested
1006  * size is too big or the DMA limit we are given isn't satisfied by the
1007  * top element in the magazine.
1008  */
1009 static unsigned long iova_rcache_get(struct iova_domain *iovad,
1010 				     unsigned long size,
1011 				     unsigned long limit_pfn)
1012 {
1013 	unsigned int log_size = order_base_2(size);
1014 
1015 	if (log_size >= IOVA_RANGE_CACHE_MAX_SIZE)
1016 		return 0;
1017 
1018 	return __iova_rcache_get(&iovad->rcaches[log_size], limit_pfn - size);
1019 }
1020 
1021 /*
1022  * free rcache data structures.
1023  */
1024 static void free_iova_rcaches(struct iova_domain *iovad)
1025 {
1026 	struct iova_rcache *rcache;
1027 	struct iova_cpu_rcache *cpu_rcache;
1028 	unsigned int cpu;
1029 	int i, j;
1030 
1031 	for (i = 0; i < IOVA_RANGE_CACHE_MAX_SIZE; ++i) {
1032 		rcache = &iovad->rcaches[i];
1033 		for_each_possible_cpu(cpu) {
1034 			cpu_rcache = per_cpu_ptr(rcache->cpu_rcaches, cpu);
1035 			iova_magazine_free(cpu_rcache->loaded);
1036 			iova_magazine_free(cpu_rcache->prev);
1037 		}
1038 		free_percpu(rcache->cpu_rcaches);
1039 		for (j = 0; j < rcache->depot_size; ++j)
1040 			iova_magazine_free(rcache->depot[j]);
1041 	}
1042 }
1043 
1044 /*
1045  * free all the IOVA ranges cached by a cpu (used when cpu is unplugged)
1046  */
1047 static void free_cpu_cached_iovas(unsigned int cpu, struct iova_domain *iovad)
1048 {
1049 	struct iova_cpu_rcache *cpu_rcache;
1050 	struct iova_rcache *rcache;
1051 	unsigned long flags;
1052 	int i;
1053 
1054 	for (i = 0; i < IOVA_RANGE_CACHE_MAX_SIZE; ++i) {
1055 		rcache = &iovad->rcaches[i];
1056 		cpu_rcache = per_cpu_ptr(rcache->cpu_rcaches, cpu);
1057 		spin_lock_irqsave(&cpu_rcache->lock, flags);
1058 		iova_magazine_free_pfns(cpu_rcache->loaded, iovad);
1059 		iova_magazine_free_pfns(cpu_rcache->prev, iovad);
1060 		spin_unlock_irqrestore(&cpu_rcache->lock, flags);
1061 	}
1062 }
1063 
1064 /*
1065  * free all the IOVA ranges of global cache
1066  */
1067 static void free_global_cached_iovas(struct iova_domain *iovad)
1068 {
1069 	struct iova_rcache *rcache;
1070 	unsigned long flags;
1071 	int i, j;
1072 
1073 	for (i = 0; i < IOVA_RANGE_CACHE_MAX_SIZE; ++i) {
1074 		rcache = &iovad->rcaches[i];
1075 		spin_lock_irqsave(&rcache->lock, flags);
1076 		for (j = 0; j < rcache->depot_size; ++j) {
1077 			iova_magazine_free_pfns(rcache->depot[j], iovad);
1078 			iova_magazine_free(rcache->depot[j]);
1079 		}
1080 		rcache->depot_size = 0;
1081 		spin_unlock_irqrestore(&rcache->lock, flags);
1082 	}
1083 }
1084 MODULE_AUTHOR("Anil S Keshavamurthy <anil.s.keshavamurthy@intel.com>");
1085 MODULE_LICENSE("GPL");
1086