Linux kernel mirror (for testing) git.kernel.org/pub/scm/linux/kernel/git/torvalds/linux.git
kernel os linux
1
fork

Configure Feed

Select the types of activity you want to include in your feed.

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>

authored by

Bence Csókás and committed by
Greg Kroah-Hartman
1f50332c 0b9570c4

+11 -9
+11 -9
drivers/usb/core/message.c
··· 1063 1063 } 1064 1064 EXPORT_SYMBOL_GPL(usb_string); 1065 1065 1066 - /* one UTF-8-encoded 16-bit character has at most three bytes */ 1066 + /* one 16-bit character, when UTF-8-encoded, has at most three bytes */ 1067 1067 #define MAX_USB_STRING_SIZE (127 * 3 + 1) 1068 1068 1069 1069 /** ··· 1084 1084 return NULL; 1085 1085 1086 1086 buf = kmalloc(MAX_USB_STRING_SIZE, GFP_NOIO); 1087 - if (buf) { 1088 - len = usb_string(udev, index, buf, MAX_USB_STRING_SIZE); 1089 - if (len > 0) { 1090 - smallbuf = kmalloc(++len, GFP_NOIO); 1091 - if (!smallbuf) 1092 - return buf; 1093 - memcpy(smallbuf, buf, len); 1094 - } 1087 + if (!buf) 1088 + return NULL; 1089 + 1090 + len = usb_string(udev, index, buf, MAX_USB_STRING_SIZE); 1091 + if (len <= 0) { 1095 1092 kfree(buf); 1093 + return NULL; 1096 1094 } 1095 + 1096 + smallbuf = krealloc(buf, len + 1, GFP_NOIO); 1097 + if (unlikely(!smallbuf)) 1098 + return buf; 1097 1099 return smallbuf; 1098 1100 } 1099 1101 EXPORT_SYMBOL_GPL(usb_cache_string);