summaryrefslogtreecommitdiff
path: root/drivers/usb/core
diff options
context:
space:
mode:
authorBence Csókás <bence98@sch.bme.hu>2026-03-15 12:24:44 +0100
committerGreg Kroah-Hartman <gregkh@linuxfoundation.org>2026-03-18 16:03:52 +0100
commit1f50332c60c2f63118b6c8b41a61d0e43d707743 (patch)
tree58f6480f40122208fe0e6458666959dadefb3850 /drivers/usb/core
parent0b9570c4ba5cbd2c0f9a282f649e4bcfce0d52af (diff)
downloadlinux-next-1f50332c60c2f63118b6c8b41a61d0e43d707743.tar.gz
linux-next-1f50332c60c2f63118b6c8b41a61d0e43d707743.zip
USB: core: Use krealloc() in usb_cache_string()
Instead of "shrinking" the allocation by kmalloc()ing a new, smaller buffer, utilize krealloc() to shrink the existing allocation. This saves a memcpy(), as well as eliminates the temporary `smallbuf` allocation, which guards against allocation failure under extreme memory pressure. Signed-off-by: Bence Csókás <bence98@sch.bme.hu> Link: https://patch.msgid.link/20260315-usb-krealloc-v2-1-32f83e090409@sch.bme.hu Signed-off-by: Greg Kroah-Hartman <gregkh@linuxfoundation.org>
Diffstat (limited to 'drivers/usb/core')
-rw-r--r--drivers/usb/core/message.c20
1 files changed, 11 insertions, 9 deletions
diff --git a/drivers/usb/core/message.c b/drivers/usb/core/message.c
index 2ab120ce2fa8..75e2bfd744a9 100644
--- a/drivers/usb/core/message.c
+++ b/drivers/usb/core/message.c
@@ -1063,7 +1063,7 @@ int usb_string(struct usb_device *dev, int index, char *buf, size_t size)
}
EXPORT_SYMBOL_GPL(usb_string);
-/* one UTF-8-encoded 16-bit character has at most three bytes */
+/* one 16-bit character, when UTF-8-encoded, has at most three bytes */
#define MAX_USB_STRING_SIZE (127 * 3 + 1)
/**
@@ -1084,16 +1084,18 @@ char *usb_cache_string(struct usb_device *udev, int index)
return NULL;
buf = kmalloc(MAX_USB_STRING_SIZE, GFP_NOIO);
- if (buf) {
- len = usb_string(udev, index, buf, MAX_USB_STRING_SIZE);
- if (len > 0) {
- smallbuf = kmalloc(++len, GFP_NOIO);
- if (!smallbuf)
- return buf;
- memcpy(smallbuf, buf, len);
- }
+ if (!buf)
+ return NULL;
+
+ len = usb_string(udev, index, buf, MAX_USB_STRING_SIZE);
+ if (len <= 0) {
kfree(buf);
+ return NULL;
}
+
+ smallbuf = krealloc(buf, len + 1, GFP_NOIO);
+ if (unlikely(!smallbuf))
+ return buf;
return smallbuf;
}
EXPORT_SYMBOL_GPL(usb_cache_string);