[patch v2 2/5] mm: add nofail variant of kmem_cache_zalloc

From: David Rientjes
Date: Wed Sep 01 2010 - 21:03:22 EST


Add kmem_cache_zalloc_nofail(). This function is equivalent to
kmem_cache_zalloc(), except that it will never return NULL and instead
loop forever trying to allocate memory.

If the first allocation attempt fails because the page allocator doesn't
implicitly loop, a warning will be emitted, including a call trace.
Subsequent failures will suppress this warning.

This was added as a helper function for documentation and auditability.
No future callers should be added.

Signed-off-by: David Rientjes <rientjes@xxxxxxxxxx>
---
fs/gfs2/meta_io.c | 2 +-
include/linux/slab.h | 17 +++++++++++++++++
2 files changed, 18 insertions(+), 1 deletions(-)

diff --git a/fs/gfs2/meta_io.c b/fs/gfs2/meta_io.c
--- a/fs/gfs2/meta_io.c
+++ b/fs/gfs2/meta_io.c
@@ -289,7 +289,7 @@ void gfs2_attach_bufdata(struct gfs2_glock *gl, struct buffer_head *bh,
return;
}

- bd = kmem_cache_zalloc(gfs2_bufdata_cachep, GFP_NOFS | __GFP_NOFAIL);
+ bd = kmem_cache_zalloc_nofail(gfs2_bufdata_cachep, GFP_NOFS);
bd->bd_bh = bh;
bd->bd_gl = gl;

diff --git a/include/linux/slab.h b/include/linux/slab.h
--- a/include/linux/slab.h
+++ b/include/linux/slab.h
@@ -313,6 +313,23 @@ static inline void *kmem_cache_zalloc(struct kmem_cache *k, gfp_t flags)
return kmem_cache_alloc(k, flags | __GFP_ZERO);
}

+/*
+ * NOTE: no new callers of this function should be implemented!
+ * All memory allocations should be failable whenever possible.
+ */
+static inline void *kmem_cache_zalloc_nofail(struct kmem_cache *k, gfp_t flags)
+{
+ void *ret;
+
+ for (;;) {
+ ret = kmem_cache_zalloc(k, flags);
+ if (ret)
+ return ret;
+ WARN_ON_ONCE(get_order(kmem_cache_size(k)) >
+ PAGE_ALLOC_COSTLY_ORDER);
+ }
+}
+
/**
* kzalloc - allocate memory. The memory is set to zero.
* @size: how many bytes of memory are required.
--
To unsubscribe from this list: send the line "unsubscribe linux-kernel" in
the body of a message to majordomo@xxxxxxxxxxxxxxx
More majordomo info at http://vger.kernel.org/majordomo-info.html
Please read the FAQ at http://www.tux.org/lkml/