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

From: David Rientjes
Date: Tue Aug 24 2010 - 08:47:59 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, 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 | 18 ++++++++++++++++++
2 files changed, 19 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,24 @@ 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_ONCE(1, "Out of memory, no fallback implemented "
+ "(flags=0x%x)\n",
+ flags);
+ }
+}
+
/**
* 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/