[PATCH] kernfs: use stack-buf for small writes.

NeilBrown
2014-09-23T04:06:44Z

[-- Attachment #1: Type: text/plain, Size: 2131 bytes --]

For a write <= 128 characters, don't use kmalloc.

mdmon, part of mdadm, will sometimes need to write
to a sysfs file in order to allow writes to the array
to continue. This is important to support RAID metadata
types that the kernel doesn't know about.

It is important that this write doesn't block on
memory allocation. The safest way to ensure that is to
use an on-stack buffer.

Writes are always small, typically less than 10 characters.

Note that reads from a sysfs file are already safe due to the use for
seqfile. The first read will allocate a buffer (m->buf) which will
be used for all subsequent reads.

Signed-off-by: NeilBrown <neilb@suse.de>

---
Hi Tejun,
I wonder if you would consider this patch.
When mdmon needs to update metadata after a device failure in an array
there are two 'kmalloc' sources that can trigger deadlock if memory is tight
and needs to be written to the array (which cannot be allowed until mdmon
updates the metadata).
One is in O_DIRECT writes which I have patches for. The other is when
writing to the sysfs file to tell md that it is safe to continue.
This simple patch removes the second.

Thanks,
NeilBrown

diff --git a/fs/kernfs/file.c b/fs/kernfs/file.c
index 4429d6d9217f..75b58669ce55 100644
--- a/fs/kernfs/file.c
+++ b/fs/kernfs/file.c
@@ -269,6 +269,7 @@ static ssize_t kernfs_fop_write(struct file *file, const char __user *user_buf,
const struct kernfs_ops *ops;
size_t len;
char *buf;
+ char stackbuf[129];

if (of->atomic_write_len) {
len = count;
@@ -278,7 +279,10 @@ static ssize_t kernfs_fop_write(struct file *file, const char __user *user_buf,
len = min_t(size_t, count, PAGE_SIZE);
}

- buf = kmalloc(len + 1, GFP_KERNEL);
+ if (len < sizeof(stackbuf))
+ buf = stackbuf;
+ else
+ buf = kmalloc(len + 1, GFP_KERNEL);
if (!buf)
return -ENOMEM;

@@ -311,7 +315,8 @@ static ssize_t kernfs_fop_write(struct file *file, const char __user *user_buf,
if (len > 0)
*ppos += len;
out_free:
- kfree(buf);
+ if (buf != stackbuf)
+ kfree(buf);
return len;
}

[-- Attachment #2: signature.asc --]
[-- Type: application/pgp-signature, Size: 828 bytes --]