Skip to contentSkip to conversation

mtdchar: kvmalloc() for large read/write buffers?

RFC PATCH In review ping.li 3 participants 13 messages Nov 19 – Dec 3 Memory technology devices (MTD)

lore
Share & tools
lore

ping.li

author
#0 lore raw

cover mtdchar: kvmalloc() for large read/write buffers?

From: Ping Li <[email protected]>

While investigating a throughput regression on one of our platforms (long uptime, fragmented memory, large read()/write() on /dev/mtdX) I noticed an inconsistency inside mtdchar:

- the ioctl paths (MEMREAD/MEMWRITE) allocate their bounce

    buffers with kvmalloc() (83208e106a8e8),

- but the read()/write() paths still use mtd_kmalloc_up_to(), which halves the buffer size until kmalloc() succeeds.

The halving behavior is not a correctness problem: the loop in mtdchar_read()/mtdchar_write() makes progress with whatever chunk size it gets. But under fragmentation a multi-megabyte transfer silently degrades into many small mtd_read()/mtd_write() calls, which is visible when the low-level driver cost scales with the number of transactions (e.g. drivers that forward each call to a remote controller over a bus).

This RFC proposes to align the read()/write() paths with the ioctl paths by using kvmalloc(), keeping the KMALLOC_MAX_SIZE cap.

The open question I would like to sort out before submitting a proper patch:

How concerned should we be about low-level drivers receiving a vmalloc'd buffer?

Looking at the tree, most drivers only memcpy() the buffer, and the controllers that DMA directly into it (brcmnand, gpmi, cadence, atmel, ...) already check is_vmalloc_addr()/ virt_addr_valid() and fall back to a bounce path. So vmalloc'd buffers are supported everywhere today -- just slower on those controllers. With mtd_kmalloc_up_to() the same controllers get a kmalloc'd (smaller) buffer instead, so either way there is a slowdown; it is mostly a question of which one userspace prefers:
few large transactions through a bounce path, or many small transactions without one.

If the direction is agreed, I will follow up with a proper patch and numbers from our platform.

Ping Li (1):
mtd: mtdchar: use kvmalloc() for large read/write buffers

 drivers/mtd/mtdchar.c | 28 ++++++++++++++++++++--------
 1 file changed, 20 insertions(+), 8 deletions(-)

base-commit: aebb7274476403040d582c61478df8f4a7bf9cd3 --
2.34.1

author
#1 lore raw

RFC PATCH 1/1 mtd: mtdchar: use kvmalloc() for large read/write buffers

mtdchar_read() and mtdchar_write() use mtd_kmalloc_up_to() for their bounce buffer. Under memory fragmentation this helper halves the requested size until kmalloc() succeeds, so a userspace read()/write() of a few megabytes may silently degrade into many small mtd_read()/ mtd_write() calls: more per-chunk overhead, and device drivers whose backend cost scales with the number of transactions pay a visible throughput penalty.

The ioctl paths (MEMREAD/MEMWRITE) already use kvmalloc() for the same purpose (83208e106a8e8 "mtdchar: use kvmalloc() for potentially large allocations"). Use kvmalloc() in the read/write paths too: it tries kmalloc() first and falls back to vmalloc() when the buddy allocator cannot serve the request contiguously, so the buffer keeps its original size instead of shrinking.

The size is still capped at KMALLOC_MAX_SIZE, as mtd_kmalloc_up_to() did.

Most low-level MTD drivers only memcpy() the buffer, so vmalloc'd buffers are fine there; controllers that DMA directly into the buffer (brcmnand, gpmi, cadence, atmel, ...) check is_vmalloc_addr()/ virt_addr_valid() and fall back to a bounce path already.

---
 drivers/mtd/mtdchar.c | 28 ++++++++++++++++++++--------
 1 file changed, 20 insertions(+), 8 deletions(-)
drivers/mtd/mtdchar.c +20 -8
index bf01e6ac7293..442fac076940 100644
@@ -148,7 +148,13 @@ static ssize_t mtdchar_read(struct file *file, char __user *buf, size_t count,
 	if (!count)
 		return 0;
 
-	kbuf = mtd_kmalloc_up_to(mtd, &size);
+	/*
+	 * Cap the buffer like mtd_kmalloc_up_to() used to; kvmalloc()
+	 * then falls back to vmalloc() when the fragmented buddy
+	 * allocator cannot serve the request contiguously.
+	 */
+	size = min_t(size_t, count, KMALLOC_MAX_SIZE);
+	kbuf = kvmalloc(size, GFP_KERNEL);
 	if (!kbuf)
 		return -ENOMEM;
 
@@ -192,7 +198,7 @@ static ssize_t mtdchar_read(struct file *file, char __user *buf, size_t count,
 		if (!ret || mtd_is_bitflip_or_eccerr(ret)) {
 			*ppos += retlen;
 			if (copy_to_user(buf, kbuf, retlen)) {
-				kfree(kbuf);
+				kvfree(kbuf);
 				return -EFAULT;
 			}
 			else
@@ -204,13 +210,13 @@ static ssize_t mtdchar_read(struct file *file, char __user *buf, size_t count,
 				count = 0;
 		}
 		else {
-			kfree(kbuf);
+			kvfree(kbuf);
 			return ret;
 		}
 
 	}
 
-	kfree(kbuf);
+	kvfree(kbuf);
 	return total_retlen;
 } /* mtdchar_read */
 
@@ -237,7 +243,13 @@ static ssize_t mtdchar_write(struct file *file, const char __user *buf, size_t c
 	if (!count)
 		return 0;
 
-	kbuf = mtd_kmalloc_up_to(mtd, &size);
+	/*
+	 * Cap the buffer like mtd_kmalloc_up_to() used to; kvmalloc()
+	 * then falls back to vmalloc() when the fragmented buddy
+	 * allocator cannot serve the request contiguously.
+	 */
+	size = min_t(size_t, count, KMALLOC_MAX_SIZE);
+	kbuf = kvmalloc(size, GFP_KERNEL);
 	if (!kbuf)
 		return -ENOMEM;
 
@@ -245,7 +257,7 @@ static ssize_t mtdchar_write(struct file *file, const char __user *buf, size_t c
 		len = min_t(size_t, count, size);
 
 		if (copy_from_user(kbuf, buf, len)) {
-			kfree(kbuf);
+			kvfree(kbuf);
 			return -EFAULT;
 		}
 
@@ -292,12 +304,12 @@ static ssize_t mtdchar_write(struct file *file, const char __user *buf, size_t c
 			buf += retlen;
 		}
 		else {
-			kfree(kbuf);
+			kvfree(kbuf);
 			return ret;
 		}
 	}
 
-	kfree(kbuf);
+	kvfree(kbuf);
 	return total_retlen;
 } /* mtdchar_write */
 
Signature · 1 line
2.34.1
#2 lore raw

Re: [RFC PATCH 1/1] mtd: mtdchar: use kvmalloc() for large read/write buffers

Thank you for your contribution! Sashiko AI review found 3 potential issues to consider: - [High] mtd: mtdchar: vmalloc buffers from kvmalloc() break __pa() and DMA drivers - [Medium] mtd: mtdchar…

Thank you for your contribution! Sashiko AI review found 3 potential issues to consider:
- [High] mtd: mtdchar: vmalloc buffers from kvmalloc() break __pa() and DMA drivers
- [Medium] mtd: mtdchar: removing mtd_kmalloc_up_to() backoff breaks NOMMU and low-memory IO
- [Medium] mtd: mtdchar: premature vmalloc fallback degrades SPI-NOR and DMA controllers
--

commit bc32b04018c61d2e1915dc5e166a083d5fe4285b
Author: Ping Li <[email protected]>

mtd: mtdchar: use kvmalloc() for large read/write buffers

This commit replaces mtd_kmalloc_up_to() and kfree() in mtdchar_read() and mtdchar_write() with kvmalloc() and kvfree(), capping the buffer size at KMALLOC_MAX_SIZE.

Quoted 8 lines
drivers/mtd/mtdchar.c +0 -0
index bf01e6ac72931..442fac0769406 100644
@@ -148,7 +148,13 @@ static ssize_t mtdchar_read(struct file *file, char __user *buf, size_t count,
 	if (!count)
 		return 0;
 

drivers/mtd/mtdchar.c static ssize_t mtdchar_read(struct file *file, char __user *buf, size_t count, · line 159

Quoted 10 lines
drivers/mtd/mtdchar.c +7 -1
-	kbuf = mtd_kmalloc_up_to(mtd, &size);
+	/*
+	 * Cap the buffer like mtd_kmalloc_up_to() used to; kvmalloc()
+	 * then falls back to vmalloc() when the fragmented buddy
+	 * allocator cannot serve the request contiguously.
+	 */
+	size = min_t(size_t, count, KMALLOC_MAX_SIZE);
+	kbuf = kvmalloc(size, GFP_KERNEL);
 	if (!kbuf)
 		return -ENOMEM;

[Severity: High]
Can passing a vmalloc-backed kbuf from mtdchar_read() and mtdchar_write() corrupt memory or leak uninitialized kernel memory in MTD drivers that require physically contiguous linear-map buffers?

When count > PAGE_SIZE and a contiguous block of the full size is not immediately free, kvmalloc() falls back to vmalloc(). Unlike the MEMREAD and MEMWRITE ioctls (which require master->_read_oob and master->_write_oob), mtd_read() and mtd_write() reach drivers that only implement _read and _write, such as powernv_flash:

drivers/mtd/devices/powernv_flash.c:powernv_flash_async_op() {
	switch (op) {
	case FLASH_OP_READ:
		rc = opal_flash_read(info->id, offset, __pa(buf), len, token);
		break;
	case FLASH_OP_WRITE:
		rc = opal_flash_write(info->id, offset, __pa(buf), len, token);
		break;
}

Running __pa() on a multi-page vmalloc address passes a bogus, physically non-contiguous address to OPAL firmware, corrupting memory or leaving kbuf uninitialized before copy_to_user().

Several raw NAND paths reachable from mtdchar_read() and mtdchar_write() also call dma_map_single() directly on kbuf without bouncing vmalloc
addresses: fsmc_nand (dma_xfer()), intel-nand-controller (ebu_dma_start()) and r852 (r852_do_dma()) do not set NAND_USES_DMA or check virt_addr_valid(), and MTD_FILE_MODE_OTP_USER calls __macronix_30lfxg18ac_rw_otp() -> nand_read_page_op() / nand_prog_page_op(), bypassing nand_base.c's NAND_USES_DMA bounce check.

[Severity: Medium]
Does dropping mtd_kmalloc_up_to()'s size backoff cause large reads and writes to fail with -ENOMEM on NOMMU or low-memory systems?

mtd_kmalloc_up_to() halved the allocation size down to max(mtd->writesize, PAGE_SIZE) with __GFP_NOWARN | __GFP_NORETRY before falling back to GFP_KERNEL. On !CONFIG_MMU, kvmalloc() still calls kmalloc() for the full size (up to KMALLOC_MAX_SIZE) with no size reduction, so fragmented systems now fail with -ENOMEM instead of using a smaller buffer. On CONFIG_MMU systems where free memory or 32-bit vmalloc space cannot satisfy a multi-megabyte buffer at once, a single full-sized GFP_KERNEL allocation can trigger the OOM killer or return -ENOMEM where a smaller buffer previously succeeded.

Also, the comment block right above mtdchar_read() still states that mtdchar_read() uses mtd_kmalloc_up_to() to mitigate low-memory and fragmentation failures by reducing the buffer size.

[Severity: Medium]
Can falling back to vmalloc() on the first failed max-order kmalloc() degrade throughput on SPI-NOR and DMA controllers compared to an intermediate-sized kmalloc() buffer?

For size > PAGE_SIZE, kvmalloc() strips __GFP_DIRECT_RECLAIM from its single kmalloc() attempt; if a full-size (e.g. 4 MiB) contiguous block is not immediately free, it returns a vmalloc buffer even when 256 KiB or 512 KiB contiguous blocks are available. On SPI-NOR, a vmalloc buffer triggers spi_nor_spimem_bounce(), clamping every transfer to nor->bouncebuf_size (PAGE_SIZE) and adding a memcpy() per page. On controllers that check virt_addr_valid() without an internal bounce buffer -- including atmel_nand_data_in() / atmel_nand_data_out() (mentioned in the commit message) and am654_hbmc_dma_read() -- a vmalloc buffer disables DMA and falls back to PIO or MMIO memcpy_fromio().

Signature · 5 lines
Sashiko AI review · https://sashiko.dev/#/patchset/[email protected]?part=1

______________________________________________________
Linux MTD discussion mailing list
http://lists.infradead.org/mailman/listinfo/linux-mtd/
author
#3 lore raw

Re: [RFC PATCH 1/1] mtd: mtdchar: use kvmalloc() for large read/write buffers

From: [email protected]

Hi,

Thanks for the review. I verified the three findings in the tree and all of them check out.

1. powernv_flash registers _read/_write directly and passes __pa(buf) down to OPAL (powernv_flash.c:69, :220), so a vmalloc'd buffer would hand firmware a bogus physical address. fsmc_nand.c:505, intel-nand-controller.c:312 and r852.c:196 dma_map_single() the buffer without any virt_addr_valid() check. This also explains why the 2022 ioctl conversion (83208e106a8e8) was safe: MEMREAD and MEMWRITE require _read_oob/_write_oob, which these drivers do not implement.

2. Agreed on the low-memory regression: kvmalloc() makes a single kmalloc() attempt and then goes straight to vmalloc(), so the size backoff that used to make progress under fragmentation is gone. The stale comment above mtdchar_read() is my oversight.

3. Agreed that "shrink first, vmalloc last" is the right shape; jumping to vmalloc while intermediate contiguous sizes are still available trades a cheap shrink for an expensive bounce path.

So the answer to the cover letter's question is: quite concerned. Plain kvmalloc() in the _read/_write path is a no-go as long as drivers assume a linear-map buffer.

The options I see from here:

a) a small pre-cleanup series making the affected drivers vmalloc-safe (bounce or reject), then converting mtdchar_read()/mtdchar_write() with the size backoff kept and vmalloc only as a last resort;
b) keeping the current halving-only behavior and dropping this RFC.

I am happy to work on (a) if that direction is acceptable; otherwise I will withdraw the RFC.

Thanks,
Ping

author
#4 lore raw

Re: [RFC PATCH 1/1] mtd: mtdchar: use kvmalloc() for large read/write buffers

In reply to [email protected]

From: [email protected]

Hi,

Thanks for the review. I verified the three findings in the tree and all of them check out.

1. powernv_flash registers _read/_write directly and passes __pa(buf) down to OPAL (powernv_flash.c:69, :220), so a vmalloc'd buffer would hand firmware a bogus physical address. fsmc_nand.c:505, intel-nand-controller.c:312 and r852.c:196 dma_map_single() the buffer without any virt_addr_valid() check. This also explains why the 2022 ioctl conversion (83208e106a8e8) was safe: MEMREAD and MEMWRITE require _read_oob/_write_oob, which these drivers do not implement.

2. Agreed on the low-memory regression: kvmalloc() makes a single kmalloc() attempt and then goes straight to vmalloc(), so the size backoff that used to make progress under fragmentation is gone. The stale comment above mtdchar_read() is my oversight.

3. Agreed that "shrink first, vmalloc last" is the right shape; jumping to vmalloc while intermediate contiguous sizes are still available trades a cheap shrink for an expensive bounce path.

So the answer to the cover letter's question is: quite concerned. Plain kvmalloc() in the _read/_write path is a no-go as long as drivers assume a linear-map buffer.

The options I see from here:

a) a small pre-cleanup series making the affected drivers vmalloc-safe (bounce or reject), then converting mtdchar_read()/mtdchar_write() with the size backoff kept and vmalloc only as a last resort;
b) keeping the current halving-only behavior and dropping this RFC.

I am happy to work on (a) if that direction is acceptable; otherwise I will withdraw the RFC.

Thanks,
Ping

author
#5 lore raw

Re: [RFC PATCH 1/1] mtd: mtdchar: use kvmalloc() for large read/write buffers

From: [email protected]

Apologies for the duplicate -- that was a resend glitch on my side; the two messages are identical, please disregard one of them.

maintainer
#6 lore raw
In reply to ping.li

Hi Ping Li,

Quoted 39 lines · ping.li

From: Ping Li <[email protected]>

While investigating a throughput regression on one of our platforms (long uptime, fragmented memory, large read()/write() on /dev/mtdX) I noticed an inconsistency inside mtdchar:

- the ioctl paths (MEMREAD/MEMWRITE) allocate their bounce

    buffers with kvmalloc() (83208e106a8e8),

- but the read()/write() paths still use mtd_kmalloc_up_to(), which halves the buffer size until kmalloc() succeeds.

The halving behavior is not a correctness problem: the loop in mtdchar_read()/mtdchar_write() makes progress with whatever chunk size it gets. But under fragmentation a multi-megabyte transfer silently degrades into many small mtd_read()/mtd_write() calls, which is visible when the low-level driver cost scales with the number of transactions (e.g. drivers that forward each call to a remote controller over a bus).

This RFC proposes to align the read()/write() paths with the ioctl paths by using kvmalloc(), keeping the KMALLOC_MAX_SIZE cap.

The open question I would like to sort out before submitting a proper patch:

How concerned should we be about low-level drivers receiving a vmalloc'd buffer?

Looking at the tree, most drivers only memcpy() the buffer, and the controllers that DMA directly into it (brcmnand, gpmi, cadence, atmel, ...) already check is_vmalloc_addr()/ virt_addr_valid() and fall back to a bounce path. So vmalloc'd buffers are supported everywhere today -- just slower on those controllers. With mtd_kmalloc_up_to() the same controllers get a kmalloc'd (smaller) buffer instead, so either way there is a slowdown; it is mostly a question of which one userspace prefers:
few large transactions through a bounce path, or many small transactions without one.

Quoted 2 lines

If the direction is agreed, I will follow up with a proper patch and numbers from our platform.

I would be curious to know how this gets faster and why? Because the preferred path is obviously via DMA to avoid keeping the CPU busy for such transfers, in which case you have no other choice than kmalloc'ing your buffer for the low-level driver.

I am not generally opposed to the idea. I actually think it's best to have a unified allocation method if that is possible (without strong preference myself, but perhaps Richard will share a more educated opinion?). The main problem is how to handle the legacy cases. Typically Sashiko raised that some devices use __pa() over the buffer virtual address, which is absolutely horrible in 2027. Those will have to be fixed in your serie (as prerequisites). So be aware that the series is gonna be larger than what you expect.

Ideally, I believe the low-level drivers should tell the MTD layer whether they expect continuous buffers > PAGE_SIZE or not. We could therefore have our own devm_mtd_kvmalloc(mtd, ...) which attaches the buffer to the MTD device, tries kzalloc() if requested by the mtd device (some kind of mtd->expects_dma_bufs boolean set during probe, typically based on the availability of DMA callbacks), fallbacks to vmalloc() otherwise.

Thanks,
Miquèl

author
#7 lore raw

From: [email protected]

Hi Miquel,

Thanks for the review!

Quoted 2 lines

I would be curious to know how this gets faster and why? Because the preferred path is obviously via DMA ...

The motivation on our platform is not per-byte CPU cost but per-transaction cost: the low-level driver forwards the whole transfer to a controller over a bus, so the latency of each mtd_read()/mtd_write() call dominates. With the current halving, a fragmented 2 MiB read silently turns into dozens of small transactions, each paying a full round trip.

You are right that this argument does not hold for DMA-bound
drivers: for those a smaller kmalloc'd buffer given to the DMA engine beats a vmalloc'd one bouncing through the CPU. That is exactly why I like your suggestion: a per-device policy avoids both failure modes -- DMA devices keep contiguous buffers and their graceful halving degradation, transaction-bound devices keep a large buffer regardless of fragmentation.

While auditing I noticed that the fsmc/intel/r852 exposure predates this RFC: since the MEMREAD/MEMWRITE conversion (83208e106a8e8), a vmalloc'd ioctl buffer can already reach their dma_map_single() under fragmentation, because none of them declares NAND_USES_DMA, which is what activates nand_base's virt_addr_valid() bounce. I would like to send these three one-line fixes as an independent series right away, as they fix a pre-existing issue regardless of the direction taken here. Only powernv_flash (which implements plain _read/_write and is unreachable from the ioctls) is newly exposed by the proposed conversion, so it would come as a prerequisite of the series.

The plan I would then follow:

1. Audit all mtd->_read/_write implementations for direct __pa()/dma_map_single() use of the data buffer.
2. Introduce mtd->expects_dma_bufs and the allocation helper, with powernv_flash declaring it.
3. Convert mtdchar_read()/mtdchar_write() to the helper.
4. Provide numbers from our platform, including the DMA-bound counter-example.

Three questions before I start:

- Shall I wait for Richard's opinion first, or does this plan already look reasonable enough to draft a series?
- For expects_dma_bufs=false devices, is plain kvmalloc() acceptable (single kmalloc attempt, then vmalloc), or should the halving stay for those too? Sashiko's NOMMU/low-memory point suggests keeping it as a last-resort fallback.
- One more question on the flag polarity. With a false default (DMA drivers declare true), a forgetful DMA driver would silently receive vmalloc'd buffers -- the exact fsmc class of bug at the MTD layer. A true default (vmalloc-safe drivers declare false) keeps the failure mode benign at the cost of having no in-tree "false" users initially. I slightly lean toward the safe default, but I can see the dead-code concern. Which polarity would you prefer?

Thanks,
Ping

maintainer
#8 lore raw
Quoted 40 lines · Ping Li

From: [email protected]

Hi Miquel,

Thanks for the review!

Quoted 2 lines

I would be curious to know how this gets faster and why? Because the preferred path is obviously via DMA ...

The motivation on our platform is not per-byte CPU cost but per-transaction cost: the low-level driver forwards the whole transfer to a controller over a bus, so the latency of each mtd_read()/mtd_write() call dominates. With the current halving, a fragmented 2 MiB read silently turns into dozens of small transactions, each paying a full round trip.

You are right that this argument does not hold for DMA-bound
drivers: for those a smaller kmalloc'd buffer given to the DMA engine beats a vmalloc'd one bouncing through the CPU. That is exactly why I like your suggestion: a per-device policy avoids both failure modes -- DMA devices keep contiguous buffers and their graceful halving degradation, transaction-bound devices keep a large buffer regardless of fragmentation.

While auditing I noticed that the fsmc/intel/r852 exposure predates this RFC: since the MEMREAD/MEMWRITE conversion (83208e106a8e8), a vmalloc'd ioctl buffer can already reach their dma_map_single() under fragmentation, because none of them declares NAND_USES_DMA, which is what activates nand_base's virt_addr_valid() bounce. I would like to send these three one-line fixes as an independent series right away, as they fix a pre-existing issue regardless of the direction taken here. Only powernv_flash (which implements plain _read/_write and is unreachable from the ioctls) is newly exposed by the proposed conversion, so it would come as a prerequisite of the series.

The plan I would then follow:

Quoted 7 lines

1. Audit all mtd->_read/_write implementations for direct __pa()/dma_map_single() use of the data buffer.
2. Introduce mtd->expects_dma_bufs and the allocation helper, with powernv_flash declaring it.
3. Convert mtdchar_read()/mtdchar_write() to the helper.
4. Provide numbers from our platform, including the DMA-bound counter-example.

Fine.

Quoted 4 lines

Three questions before I start:

- Shall I wait for Richard's opinion first, or does this plan already look reasonable enough to draft a series?

I guess you can proceed, but Richard's opinion is indeed very welcome.

Quoted 5 lines

- For expects_dma_bufs=false devices, is plain kvmalloc() acceptable (single kmalloc attempt, then vmalloc), or should the halving stay for those too? Sashiko's NOMMU/low-memory point suggests keeping it as a last-resort fallback.

We should keep today's default, if there is one. I don't like kvmalloc in this case because it may hide bugs.

Quoted 9 lines

- One more question on the flag polarity. With a false default (DMA drivers declare true), a forgetful DMA driver would silently receive vmalloc'd buffers -- the exact fsmc class of bug at the MTD layer. A true default (vmalloc-safe drivers declare false) keeps the failure mode benign at the cost of having no in-tree "false" users initially. I slightly lean toward the safe default, but I can see the dead-code concern. Which polarity would you prefer?

We would not have 0 users, because there are plenty drivers already doing bounce buffering which would therefore need to be converted to expects_dma_bufs = true.

I think the default today is that the drivers may expect DMA-able buffers and the subsystems enforce this by bouncing the data, no?

Miquèl

author
#9 lore raw

v2 cover mtdchar: per-device bounce buffer policy

In reply to ping.li

This is the second revision of the RFC I sent earlier [1], following the discussion with Miquel [2][3]. It implements the agreed
direction: low-level drivers decide whether they may receive non-linear-map buffers, and a helper applies the allocation policy accordingly.

Patch 1 introduces mtd->allows_vmalloc_bufs (defaults to false, partitions inherit it from their master) and mtd_alloc_buf()/ mtd_free_buf(). By default buffers come from mtd_kmalloc_up_to(), which gracefully shrinks the size under fragmentation, so a driver never unexpectedly receives a buffer which is not DMA-able. Drivers that only memcpy() the buffer, or which bounce it internally, may set the flag to get kvmalloc()'s vmalloc fallback and keep the requested size, so a large read()/write() no longer silently degrades into many small mtd_read()/mtd_write() calls. The size reduction is intentionally not kept as a last resort for those devices: an allocation failure is reported to userspace rather than silently shrinking the buffer.

Patch 2 converts mtdchar_read()/mtdchar_write() to the helper and updates the stale comment above mtdchar_read().

Compared to v1, the flag is an explicit opt-in with a conservative default rather than core-set, the halving fallback after kvmalloc() is dropped, and the powernv_flash declaration patch is no longer needed since the conservative default already covers it.

Converting the drivers which already bounce internally (brcmnand, gpmi, atmel, am654-hbmc, ...) to the new flag is planned as a follow-up series.

Numbers from our platform (an IPC-backed NOR flash device where each mtd_read()/mtd_write() is forwarded to a remote controller):

- one transaction costs t ~= 20ms + 0.3ms/KB, i.e. ~620ms for the

    2M+2K transfer this platform uses for OTA updates;

- with the opt-in, every 2M+2K read() issued during the tests (~80 runs across clean, fragmented and severely fragmented memory states) produced exactly one transaction, in every single run;

- without the opt-in, the same command was observed to produce both single full-size and halved (len=1049600, two transactions) transfers within the same session, depending on transient allocator state. The split is not reproducible on demand;

- wall-clock throughput is not the benefit: a halved transfer pays only one extra fixed cost (~3%). The benefit is determinism:
the opt-in makes the transaction count and buffer size independent of memory state, which is what transaction-bound backends need.

[1] https://lore.kernel.org/linux-mtd/[email protected]/
[2] https://lore.kernel.org/linux-mtd/[email protected]/
[3] https://lore.kernel.org/linux-mtd/[email protected]/

Ping Li (2):
mtd: core: add per-device bounce buffer allocation helper
mtd: mtdchar: use mtd_alloc_buf() for the read/write bounce buffers

 drivers/mtd/mtdchar.c   | 24 +++++++++++-----------
 drivers/mtd/mtdcore.c   | 44 +++++++++++++++++++++++++++++++++++++++++
 drivers/mtd/mtdpart.c   |  1 +
 include/linux/mtd/mtd.h | 16 +++++++++++++++
 4 files changed, 74 insertions(+), 11 deletions(-)

base-commit: aebb7274476403040d582c61478df8f4a7bf9cd3

Signature · 1 line
2.34.1
author
#10 lore raw

RFC PATCH v2 1/2 mtd: core: add per-device bounce buffer allocation helper

Introduce mtd->allows_vmalloc_bufs and two helpers for the callers:

- mtd_alloc_buf(): by default buffers come from mtd_kmalloc_up_to(), which gracefully reduces the size under fragmentation so that drivers never receive a buffer which is not DMA-able. Drivers that only memcpy() the buffer, or which bounce it internally, may set the flag in their probe to get kvmalloc()'s vmalloc fallback instead, so the requested size is kept even when the buddy allocator is too fragmented to serve a contiguous block; this avoids degrading large transfers into many small ones. The size reduction is intentionally not kept as a last resort for those devices: an allocation failure is reported to userspace rather than silently shrinking the buffer, so that the declared contract cannot be quietly broken.
- mtd_free_buf(): the matching release, kvfree() based.

The flag defaults to false (zero-initialized) and partitions inherit it from their master, so a driver which does not opt in -- on the master or any partition -- keeps today's behaviour and can never unexpectedly receive a non-DMA-able buffer.

No functional change yet; mtdchar is converted in the following patch.

---
 drivers/mtd/mtdcore.c   | 44 +++++++++++++++++++++++++++++++++++++++++
 drivers/mtd/mtdpart.c   |  1 +
 include/linux/mtd/mtd.h | 16 +++++++++++++++
 3 files changed, 61 insertions(+)
drivers/mtd/mtdcore.c +44 -0
index b170c3144ca8f..83365c0fbf063 100644
@@ -2566,6 +2566,50 @@ void *mtd_kmalloc_up_to(const struct mtd_info *mtd, size_t *size)
 }
 EXPORT_SYMBOL_GPL(mtd_kmalloc_up_to);
 
+/**
+ * mtd_alloc_buf - allocate a bounce buffer for an MTD device
+ * @mtd: the MTD device the buffer will be used for
+ * @size: requested size, updated to the size actually allocated
+ *
+ * By default (see mtd->allows_vmalloc_bufs) buffers come from
+ * mtd_kmalloc_up_to(), which gracefully reduces the size under
+ * fragmentation so that drivers never receive a buffer which is not
+ * DMA-able.
+ *
+ * Drivers that declared themselves vmalloc-safe (they only memcpy()
+ * the buffer or bounce it internally) get kvmalloc()'s fallback
+ * instead, so the requested size is kept even when the buddy
+ * allocator is too fragmented to serve a contiguous block; this
+ * avoids degrading large transfers into many small ones.  The size
+ * reduction is intentionally NOT kept as a last resort for those
+ * devices: an allocation failure is reported to userspace rather
+ * than silently shrinking the buffer, so that the declared contract
+ * cannot be quietly broken.
+ *
+ * Buffers must be released with mtd_free_buf().
+ *
+ * Returns a pointer to the allocated buffer on success; otherwise, NULL.
+ */
+void *mtd_alloc_buf(const struct mtd_info *mtd, size_t *size)
+{
+	if (!mtd->allows_vmalloc_bufs)
+		return mtd_kmalloc_up_to(mtd, size);
+
+	*size = min_t(size_t, *size, KMALLOC_MAX_SIZE);
+	return kvmalloc(*size, GFP_KERNEL);
+}
+EXPORT_SYMBOL_GPL(mtd_alloc_buf);
+
+/**
+ * mtd_free_buf - release a buffer allocated with mtd_alloc_buf()
+ * @buf: buffer returned by mtd_alloc_buf()
+ */
+void mtd_free_buf(void *buf)
+{
+	kvfree(buf);
+}
+EXPORT_SYMBOL_GPL(mtd_free_buf);
+
 #ifdef CONFIG_PROC_FS
 
 /*====================================================================*/
drivers/mtd/mtdpart.c +1 -0
index ddded0dbe77e0..9c245ad421a55 100644
@@ -75,6 +75,7 @@ static struct mtd_info *allocate_partition(struct mtd_info *parent,
 	child->oobsize = parent->oobsize;
 	child->oobavail = parent->oobavail;
 	child->subpage_sft = parent->subpage_sft;
+	child->allows_vmalloc_bufs = parent->allows_vmalloc_bufs;
 
 	child->name = name;
 	child->owner = parent->owner;
include/linux/mtd/mtd.h +16 -0
index 8d10d9d2e8300..4296d255c15d8 100644
@@ -368,6 +368,20 @@ struct mtd_info {
 	 */
 	bool oops_panic_write;
 
+	/*
+	 * Low-level drivers that only memcpy() the data buffers received
+	 * from the MTD layer, or which handle non-linear-map buffers
+	 * themselves (internal bounce), may set this to receive vmalloc'd
+	 * buffers, keeping the requested size intact even under heavy
+	 * memory fragmentation.
+	 *
+	 * Defaults to false: buffers always come from
+	 * mtd_kmalloc_up_to(), which gracefully shrinks the size under
+	 * fragmentation, so drivers never unexpectedly receive a buffer
+	 * that is not DMA-able.
+	 */
+	bool allows_vmalloc_bufs;
+
 	struct notifier_block reboot_notifier;  /* default mode before reboot */
 
 	/* ECC status information */
@@ -699,6 +713,8 @@ struct mtd_notifier {
 extern void register_mtd_user (struct mtd_notifier *new);
 extern int unregister_mtd_user (struct mtd_notifier *old);
 void *mtd_kmalloc_up_to(const struct mtd_info *mtd, size_t *size);
+void *mtd_alloc_buf(const struct mtd_info *mtd, size_t *size);
+void mtd_free_buf(void *buf);
 
 static inline int mtd_is_bitflip(int err) {
 	return err == -EUCLEAN;
Signature · 1 line
2.34.1
author
#11 lore raw

RFC PATCH v2 2/2 mtd: mtdchar: use mtd_alloc_buf() for the read/write bounce buffers

In reply to Ping Li

mtdchar_read() and mtdchar_write() so far rely on mtd_kmalloc_up_to(), which halves the requested size until the allocation succeeds. Under heavy memory fragmentation a multi-megabyte read()/write() thus silently degrades into many small mtd_read()/mtd_write() calls, which is visible when the low-level driver cost scales with the number of transactions (e.g. drivers forwarding each call to a remote controller).

Use mtd_alloc_buf() instead. Devices whose driver did not opt into vmalloc'd buffers keep the current behaviour; vmalloc-safe drivers keep the requested size. Also update the comment above mtdchar_read(), which still described the old mitigation.

---
 drivers/mtd/mtdchar.c | 24 +++++++++++++-----------
 1 file changed, 13 insertions(+), 11 deletions(-)
drivers/mtd/mtdchar.c +13 -11
index bf01e6ac72931..0142cad65aee3 100644
@@ -111,10 +111,12 @@ static int mtdchar_close(struct inode *inode, struct file *file)
  *   FIXME: This _really_ needs to die. In 2.5, we should lock the
  *   userspace buffer down and use it directly with readv/writev.
  *
- * The implementation below, using mtd_kmalloc_up_to, mitigates
+ * The implementation below, using mtd_alloc_buf(), mitigates
  * allocation failures when the system is under low-memory situations
- * or if memory is highly fragmented at the cost of reducing the
- * performance of the requested transfer due to a smaller buffer size.
+ * or if memory is highly fragmented.  Devices whose driver did not
+ * opt into vmalloc'd buffers get a reduced buffer size, while
+ * vmalloc-safe drivers keep the requested size, so large transfers
+ * are not degraded into many small ones.
  *
  * A more complex but more memory-efficient implementation based on
  * get_user_pages and iovecs to cover extents of those pages is a
@@ -148,7 +150,7 @@ static ssize_t mtdchar_read(struct file *file, char __user *buf, size_t count,
 	if (!count)
 		return 0;
 
-	kbuf = mtd_kmalloc_up_to(mtd, &size);
+	kbuf = mtd_alloc_buf(mtd, &size);
 	if (!kbuf)
 		return -ENOMEM;
 
@@ -192,7 +194,7 @@ static ssize_t mtdchar_read(struct file *file, char __user *buf, size_t count,
 		if (!ret || mtd_is_bitflip_or_eccerr(ret)) {
 			*ppos += retlen;
 			if (copy_to_user(buf, kbuf, retlen)) {
-				kfree(kbuf);
+				mtd_free_buf(kbuf);
 				return -EFAULT;
 			}
 			else
@@ -204,13 +206,13 @@ static ssize_t mtdchar_read(struct file *file, char __user *buf, size_t count,
 				count = 0;
 		}
 		else {
-			kfree(kbuf);
+			mtd_free_buf(kbuf);
 			return ret;
 		}
 
 	}
 
-	kfree(kbuf);
+	mtd_free_buf(kbuf);
 	return total_retlen;
 } /* mtdchar_read */
 
@@ -237,7 +239,7 @@ static ssize_t mtdchar_write(struct file *file, const char __user *buf, size_t c
 	if (!count)
 		return 0;
 
-	kbuf = mtd_kmalloc_up_to(mtd, &size);
+	kbuf = mtd_alloc_buf(mtd, &size);
 	if (!kbuf)
 		return -ENOMEM;
 
@@ -245,7 +247,7 @@ static ssize_t mtdchar_write(struct file *file, const char __user *buf, size_t c
 		len = min_t(size_t, count, size);
 
 		if (copy_from_user(kbuf, buf, len)) {
-			kfree(kbuf);
+			mtd_free_buf(kbuf);
 			return -EFAULT;
 		}
 
@@ -292,12 +294,12 @@ static ssize_t mtdchar_write(struct file *file, const char __user *buf, size_t c
 			buf += retlen;
 		}
 		else {
-			kfree(kbuf);
+			mtd_free_buf(kbuf);
 			return ret;
 		}
 	}
 
-	kfree(kbuf);
+	mtd_free_buf(kbuf);
 	return total_retlen;
 } /* mtdchar_write */
 
Signature · 1 line
2.34.1
maintainer
#12 lore raw

Re: [RFC PATCH v2 0/2] mtdchar: per-device bounce buffer policy

In reply to Ping Li
Quoted 5 lines · Ping Li

This is the second revision of the RFC I sent earlier [1], following the discussion with Miquel [2][3]. It implements the agreed
direction: low-level drivers decide whether they may receive non-linear-map buffers, and a helper applies the allocation policy accordingly.

I'm mostly fine with the approach, could you add one or ideally several users in v3 (not RFC)?

Please also Cc all the mtd maintainers using b4 or get_maintainers.pl.

Thanks,
Miquèl