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