Back to home page

LXR

 
 

    


0001 /*
0002  *  linux/mm/mempool.c
0003  *
0004  *  memory buffer pool support. Such pools are mostly used
0005  *  for guaranteed, deadlock-free memory allocations during
0006  *  extreme VM load.
0007  *
0008  *  started by Ingo Molnar, Copyright (C) 2001
0009  *  debugging by David Rientjes, Copyright (C) 2015
0010  */
0011 
0012 #include <linux/mm.h>
0013 #include <linux/slab.h>
0014 #include <linux/highmem.h>
0015 #include <linux/kasan.h>
0016 #include <linux/kmemleak.h>
0017 #include <linux/export.h>
0018 #include <linux/mempool.h>
0019 #include <linux/blkdev.h>
0020 #include <linux/writeback.h>
0021 #include "slab.h"
0022 
0023 #if defined(CONFIG_DEBUG_SLAB) || defined(CONFIG_SLUB_DEBUG_ON)
0024 static void poison_error(mempool_t *pool, void *element, size_t size,
0025              size_t byte)
0026 {
0027     const int nr = pool->curr_nr;
0028     const int start = max_t(int, byte - (BITS_PER_LONG / 8), 0);
0029     const int end = min_t(int, byte + (BITS_PER_LONG / 8), size);
0030     int i;
0031 
0032     pr_err("BUG: mempool element poison mismatch\n");
0033     pr_err("Mempool %p size %zu\n", pool, size);
0034     pr_err(" nr=%d @ %p: %s0x", nr, element, start > 0 ? "... " : "");
0035     for (i = start; i < end; i++)
0036         pr_cont("%x ", *(u8 *)(element + i));
0037     pr_cont("%s\n", end < size ? "..." : "");
0038     dump_stack();
0039 }
0040 
0041 static void __check_element(mempool_t *pool, void *element, size_t size)
0042 {
0043     u8 *obj = element;
0044     size_t i;
0045 
0046     for (i = 0; i < size; i++) {
0047         u8 exp = (i < size - 1) ? POISON_FREE : POISON_END;
0048 
0049         if (obj[i] != exp) {
0050             poison_error(pool, element, size, i);
0051             return;
0052         }
0053     }
0054     memset(obj, POISON_INUSE, size);
0055 }
0056 
0057 static void check_element(mempool_t *pool, void *element)
0058 {
0059     /* Mempools backed by slab allocator */
0060     if (pool->free == mempool_free_slab || pool->free == mempool_kfree)
0061         __check_element(pool, element, ksize(element));
0062 
0063     /* Mempools backed by page allocator */
0064     if (pool->free == mempool_free_pages) {
0065         int order = (int)(long)pool->pool_data;
0066         void *addr = kmap_atomic((struct page *)element);
0067 
0068         __check_element(pool, addr, 1UL << (PAGE_SHIFT + order));
0069         kunmap_atomic(addr);
0070     }
0071 }
0072 
0073 static void __poison_element(void *element, size_t size)
0074 {
0075     u8 *obj = element;
0076 
0077     memset(obj, POISON_FREE, size - 1);
0078     obj[size - 1] = POISON_END;
0079 }
0080 
0081 static void poison_element(mempool_t *pool, void *element)
0082 {
0083     /* Mempools backed by slab allocator */
0084     if (pool->alloc == mempool_alloc_slab || pool->alloc == mempool_kmalloc)
0085         __poison_element(element, ksize(element));
0086 
0087     /* Mempools backed by page allocator */
0088     if (pool->alloc == mempool_alloc_pages) {
0089         int order = (int)(long)pool->pool_data;
0090         void *addr = kmap_atomic((struct page *)element);
0091 
0092         __poison_element(addr, 1UL << (PAGE_SHIFT + order));
0093         kunmap_atomic(addr);
0094     }
0095 }
0096 #else /* CONFIG_DEBUG_SLAB || CONFIG_SLUB_DEBUG_ON */
0097 static inline void check_element(mempool_t *pool, void *element)
0098 {
0099 }
0100 static inline void poison_element(mempool_t *pool, void *element)
0101 {
0102 }
0103 #endif /* CONFIG_DEBUG_SLAB || CONFIG_SLUB_DEBUG_ON */
0104 
0105 static void kasan_poison_element(mempool_t *pool, void *element)
0106 {
0107     if (pool->alloc == mempool_alloc_slab || pool->alloc == mempool_kmalloc)
0108         kasan_poison_kfree(element);
0109     if (pool->alloc == mempool_alloc_pages)
0110         kasan_free_pages(element, (unsigned long)pool->pool_data);
0111 }
0112 
0113 static void kasan_unpoison_element(mempool_t *pool, void *element, gfp_t flags)
0114 {
0115     if (pool->alloc == mempool_alloc_slab || pool->alloc == mempool_kmalloc)
0116         kasan_unpoison_slab(element);
0117     if (pool->alloc == mempool_alloc_pages)
0118         kasan_alloc_pages(element, (unsigned long)pool->pool_data);
0119 }
0120 
0121 static void add_element(mempool_t *pool, void *element)
0122 {
0123     BUG_ON(pool->curr_nr >= pool->min_nr);
0124     poison_element(pool, element);
0125     kasan_poison_element(pool, element);
0126     pool->elements[pool->curr_nr++] = element;
0127 }
0128 
0129 static void *remove_element(mempool_t *pool, gfp_t flags)
0130 {
0131     void *element = pool->elements[--pool->curr_nr];
0132 
0133     BUG_ON(pool->curr_nr < 0);
0134     kasan_unpoison_element(pool, element, flags);
0135     check_element(pool, element);
0136     return element;
0137 }
0138 
0139 /**
0140  * mempool_destroy - deallocate a memory pool
0141  * @pool:      pointer to the memory pool which was allocated via
0142  *             mempool_create().
0143  *
0144  * Free all reserved elements in @pool and @pool itself.  This function
0145  * only sleeps if the free_fn() function sleeps.
0146  */
0147 void mempool_destroy(mempool_t *pool)
0148 {
0149     if (unlikely(!pool))
0150         return;
0151 
0152     while (pool->curr_nr) {
0153         void *element = remove_element(pool, GFP_KERNEL);
0154         pool->free(element, pool->pool_data);
0155     }
0156     kfree(pool->elements);
0157     kfree(pool);
0158 }
0159 EXPORT_SYMBOL(mempool_destroy);
0160 
0161 /**
0162  * mempool_create - create a memory pool
0163  * @min_nr:    the minimum number of elements guaranteed to be
0164  *             allocated for this pool.
0165  * @alloc_fn:  user-defined element-allocation function.
0166  * @free_fn:   user-defined element-freeing function.
0167  * @pool_data: optional private data available to the user-defined functions.
0168  *
0169  * this function creates and allocates a guaranteed size, preallocated
0170  * memory pool. The pool can be used from the mempool_alloc() and mempool_free()
0171  * functions. This function might sleep. Both the alloc_fn() and the free_fn()
0172  * functions might sleep - as long as the mempool_alloc() function is not called
0173  * from IRQ contexts.
0174  */
0175 mempool_t *mempool_create(int min_nr, mempool_alloc_t *alloc_fn,
0176                 mempool_free_t *free_fn, void *pool_data)
0177 {
0178     return mempool_create_node(min_nr,alloc_fn,free_fn, pool_data,
0179                    GFP_KERNEL, NUMA_NO_NODE);
0180 }
0181 EXPORT_SYMBOL(mempool_create);
0182 
0183 mempool_t *mempool_create_node(int min_nr, mempool_alloc_t *alloc_fn,
0184                    mempool_free_t *free_fn, void *pool_data,
0185                    gfp_t gfp_mask, int node_id)
0186 {
0187     mempool_t *pool;
0188     pool = kzalloc_node(sizeof(*pool), gfp_mask, node_id);
0189     if (!pool)
0190         return NULL;
0191     pool->elements = kmalloc_node(min_nr * sizeof(void *),
0192                       gfp_mask, node_id);
0193     if (!pool->elements) {
0194         kfree(pool);
0195         return NULL;
0196     }
0197     spin_lock_init(&pool->lock);
0198     pool->min_nr = min_nr;
0199     pool->pool_data = pool_data;
0200     init_waitqueue_head(&pool->wait);
0201     pool->alloc = alloc_fn;
0202     pool->free = free_fn;
0203 
0204     /*
0205      * First pre-allocate the guaranteed number of buffers.
0206      */
0207     while (pool->curr_nr < pool->min_nr) {
0208         void *element;
0209 
0210         element = pool->alloc(gfp_mask, pool->pool_data);
0211         if (unlikely(!element)) {
0212             mempool_destroy(pool);
0213             return NULL;
0214         }
0215         add_element(pool, element);
0216     }
0217     return pool;
0218 }
0219 EXPORT_SYMBOL(mempool_create_node);
0220 
0221 /**
0222  * mempool_resize - resize an existing memory pool
0223  * @pool:       pointer to the memory pool which was allocated via
0224  *              mempool_create().
0225  * @new_min_nr: the new minimum number of elements guaranteed to be
0226  *              allocated for this pool.
0227  *
0228  * This function shrinks/grows the pool. In the case of growing,
0229  * it cannot be guaranteed that the pool will be grown to the new
0230  * size immediately, but new mempool_free() calls will refill it.
0231  * This function may sleep.
0232  *
0233  * Note, the caller must guarantee that no mempool_destroy is called
0234  * while this function is running. mempool_alloc() & mempool_free()
0235  * might be called (eg. from IRQ contexts) while this function executes.
0236  */
0237 int mempool_resize(mempool_t *pool, int new_min_nr)
0238 {
0239     void *element;
0240     void **new_elements;
0241     unsigned long flags;
0242 
0243     BUG_ON(new_min_nr <= 0);
0244     might_sleep();
0245 
0246     spin_lock_irqsave(&pool->lock, flags);
0247     if (new_min_nr <= pool->min_nr) {
0248         while (new_min_nr < pool->curr_nr) {
0249             element = remove_element(pool, GFP_KERNEL);
0250             spin_unlock_irqrestore(&pool->lock, flags);
0251             pool->free(element, pool->pool_data);
0252             spin_lock_irqsave(&pool->lock, flags);
0253         }
0254         pool->min_nr = new_min_nr;
0255         goto out_unlock;
0256     }
0257     spin_unlock_irqrestore(&pool->lock, flags);
0258 
0259     /* Grow the pool */
0260     new_elements = kmalloc_array(new_min_nr, sizeof(*new_elements),
0261                      GFP_KERNEL);
0262     if (!new_elements)
0263         return -ENOMEM;
0264 
0265     spin_lock_irqsave(&pool->lock, flags);
0266     if (unlikely(new_min_nr <= pool->min_nr)) {
0267         /* Raced, other resize will do our work */
0268         spin_unlock_irqrestore(&pool->lock, flags);
0269         kfree(new_elements);
0270         goto out;
0271     }
0272     memcpy(new_elements, pool->elements,
0273             pool->curr_nr * sizeof(*new_elements));
0274     kfree(pool->elements);
0275     pool->elements = new_elements;
0276     pool->min_nr = new_min_nr;
0277 
0278     while (pool->curr_nr < pool->min_nr) {
0279         spin_unlock_irqrestore(&pool->lock, flags);
0280         element = pool->alloc(GFP_KERNEL, pool->pool_data);
0281         if (!element)
0282             goto out;
0283         spin_lock_irqsave(&pool->lock, flags);
0284         if (pool->curr_nr < pool->min_nr) {
0285             add_element(pool, element);
0286         } else {
0287             spin_unlock_irqrestore(&pool->lock, flags);
0288             pool->free(element, pool->pool_data);   /* Raced */
0289             goto out;
0290         }
0291     }
0292 out_unlock:
0293     spin_unlock_irqrestore(&pool->lock, flags);
0294 out:
0295     return 0;
0296 }
0297 EXPORT_SYMBOL(mempool_resize);
0298 
0299 /**
0300  * mempool_alloc - allocate an element from a specific memory pool
0301  * @pool:      pointer to the memory pool which was allocated via
0302  *             mempool_create().
0303  * @gfp_mask:  the usual allocation bitmask.
0304  *
0305  * this function only sleeps if the alloc_fn() function sleeps or
0306  * returns NULL. Note that due to preallocation, this function
0307  * *never* fails when called from process contexts. (it might
0308  * fail if called from an IRQ context.)
0309  * Note: using __GFP_ZERO is not supported.
0310  */
0311 void *mempool_alloc(mempool_t *pool, gfp_t gfp_mask)
0312 {
0313     void *element;
0314     unsigned long flags;
0315     wait_queue_t wait;
0316     gfp_t gfp_temp;
0317 
0318     VM_WARN_ON_ONCE(gfp_mask & __GFP_ZERO);
0319     might_sleep_if(gfp_mask & __GFP_DIRECT_RECLAIM);
0320 
0321     gfp_mask |= __GFP_NOMEMALLOC;   /* don't allocate emergency reserves */
0322     gfp_mask |= __GFP_NORETRY;  /* don't loop in __alloc_pages */
0323     gfp_mask |= __GFP_NOWARN;   /* failures are OK */
0324 
0325     gfp_temp = gfp_mask & ~(__GFP_DIRECT_RECLAIM|__GFP_IO);
0326 
0327 repeat_alloc:
0328 
0329     element = pool->alloc(gfp_temp, pool->pool_data);
0330     if (likely(element != NULL))
0331         return element;
0332 
0333     spin_lock_irqsave(&pool->lock, flags);
0334     if (likely(pool->curr_nr)) {
0335         element = remove_element(pool, gfp_temp);
0336         spin_unlock_irqrestore(&pool->lock, flags);
0337         /* paired with rmb in mempool_free(), read comment there */
0338         smp_wmb();
0339         /*
0340          * Update the allocation stack trace as this is more useful
0341          * for debugging.
0342          */
0343         kmemleak_update_trace(element);
0344         return element;
0345     }
0346 
0347     /*
0348      * We use gfp mask w/o direct reclaim or IO for the first round.  If
0349      * alloc failed with that and @pool was empty, retry immediately.
0350      */
0351     if (gfp_temp != gfp_mask) {
0352         spin_unlock_irqrestore(&pool->lock, flags);
0353         gfp_temp = gfp_mask;
0354         goto repeat_alloc;
0355     }
0356 
0357     /* We must not sleep if !__GFP_DIRECT_RECLAIM */
0358     if (!(gfp_mask & __GFP_DIRECT_RECLAIM)) {
0359         spin_unlock_irqrestore(&pool->lock, flags);
0360         return NULL;
0361     }
0362 
0363     /* Let's wait for someone else to return an element to @pool */
0364     init_wait(&wait);
0365     prepare_to_wait(&pool->wait, &wait, TASK_UNINTERRUPTIBLE);
0366 
0367     spin_unlock_irqrestore(&pool->lock, flags);
0368 
0369     /*
0370      * FIXME: this should be io_schedule().  The timeout is there as a
0371      * workaround for some DM problems in 2.6.18.
0372      */
0373     io_schedule_timeout(5*HZ);
0374 
0375     finish_wait(&pool->wait, &wait);
0376     goto repeat_alloc;
0377 }
0378 EXPORT_SYMBOL(mempool_alloc);
0379 
0380 /**
0381  * mempool_free - return an element to the pool.
0382  * @element:   pool element pointer.
0383  * @pool:      pointer to the memory pool which was allocated via
0384  *             mempool_create().
0385  *
0386  * this function only sleeps if the free_fn() function sleeps.
0387  */
0388 void mempool_free(void *element, mempool_t *pool)
0389 {
0390     unsigned long flags;
0391 
0392     if (unlikely(element == NULL))
0393         return;
0394 
0395     /*
0396      * Paired with the wmb in mempool_alloc().  The preceding read is
0397      * for @element and the following @pool->curr_nr.  This ensures
0398      * that the visible value of @pool->curr_nr is from after the
0399      * allocation of @element.  This is necessary for fringe cases
0400      * where @element was passed to this task without going through
0401      * barriers.
0402      *
0403      * For example, assume @p is %NULL at the beginning and one task
0404      * performs "p = mempool_alloc(...);" while another task is doing
0405      * "while (!p) cpu_relax(); mempool_free(p, ...);".  This function
0406      * may end up using curr_nr value which is from before allocation
0407      * of @p without the following rmb.
0408      */
0409     smp_rmb();
0410 
0411     /*
0412      * For correctness, we need a test which is guaranteed to trigger
0413      * if curr_nr + #allocated == min_nr.  Testing curr_nr < min_nr
0414      * without locking achieves that and refilling as soon as possible
0415      * is desirable.
0416      *
0417      * Because curr_nr visible here is always a value after the
0418      * allocation of @element, any task which decremented curr_nr below
0419      * min_nr is guaranteed to see curr_nr < min_nr unless curr_nr gets
0420      * incremented to min_nr afterwards.  If curr_nr gets incremented
0421      * to min_nr after the allocation of @element, the elements
0422      * allocated after that are subject to the same guarantee.
0423      *
0424      * Waiters happen iff curr_nr is 0 and the above guarantee also
0425      * ensures that there will be frees which return elements to the
0426      * pool waking up the waiters.
0427      */
0428     if (unlikely(pool->curr_nr < pool->min_nr)) {
0429         spin_lock_irqsave(&pool->lock, flags);
0430         if (likely(pool->curr_nr < pool->min_nr)) {
0431             add_element(pool, element);
0432             spin_unlock_irqrestore(&pool->lock, flags);
0433             wake_up(&pool->wait);
0434             return;
0435         }
0436         spin_unlock_irqrestore(&pool->lock, flags);
0437     }
0438     pool->free(element, pool->pool_data);
0439 }
0440 EXPORT_SYMBOL(mempool_free);
0441 
0442 /*
0443  * A commonly used alloc and free fn.
0444  */
0445 void *mempool_alloc_slab(gfp_t gfp_mask, void *pool_data)
0446 {
0447     struct kmem_cache *mem = pool_data;
0448     VM_BUG_ON(mem->ctor);
0449     return kmem_cache_alloc(mem, gfp_mask);
0450 }
0451 EXPORT_SYMBOL(mempool_alloc_slab);
0452 
0453 void mempool_free_slab(void *element, void *pool_data)
0454 {
0455     struct kmem_cache *mem = pool_data;
0456     kmem_cache_free(mem, element);
0457 }
0458 EXPORT_SYMBOL(mempool_free_slab);
0459 
0460 /*
0461  * A commonly used alloc and free fn that kmalloc/kfrees the amount of memory
0462  * specified by pool_data
0463  */
0464 void *mempool_kmalloc(gfp_t gfp_mask, void *pool_data)
0465 {
0466     size_t size = (size_t)pool_data;
0467     return kmalloc(size, gfp_mask);
0468 }
0469 EXPORT_SYMBOL(mempool_kmalloc);
0470 
0471 void mempool_kfree(void *element, void *pool_data)
0472 {
0473     kfree(element);
0474 }
0475 EXPORT_SYMBOL(mempool_kfree);
0476 
0477 /*
0478  * A simple mempool-backed page allocator that allocates pages
0479  * of the order specified by pool_data.
0480  */
0481 void *mempool_alloc_pages(gfp_t gfp_mask, void *pool_data)
0482 {
0483     int order = (int)(long)pool_data;
0484     return alloc_pages(gfp_mask, order);
0485 }
0486 EXPORT_SYMBOL(mempool_alloc_pages);
0487 
0488 void mempool_free_pages(void *element, void *pool_data)
0489 {
0490     int order = (int)(long)pool_data;
0491     __free_pages(element, order);
0492 }
0493 EXPORT_SYMBOL(mempool_free_pages);