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