Skip to content

Commit 32f4f8d

Browse files
sslupskymmahadevan108
authored andcommitted
drivers: usb: usb_dc_sam0: fix memory leak
The usb_dc_sam0 driver is leaking memory when the usb device is detached using usb_disable(). When a device is detached, the driver does not reliably deallocate the descriptor bank memory. Therefore, upon the next attach and configure, another block of memory is allocated. After several connect / disconnect sequences, the usb interface becomes unresponsive. This commit adds a static function to release all memory allocated to the ep descriptors when usb_dc_detach() is called. Since detach is called from usb_disable(), this releases the memory when the interface is disabled. Avoid calling k_free() if buffer pointer is already set to NULL. Fixes #49177 Signed-off-by: Steven Slupsky <[email protected]>
1 parent 7c231e3 commit 32f4f8d

File tree

1 file changed

+27
-0
lines changed

1 file changed

+27
-0
lines changed

drivers/usb/device/usb_dc_sam0.c

Lines changed: 27 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -288,6 +288,31 @@ int usb_dc_attach(void)
288288
return 0;
289289
}
290290

291+
static void usb_dc_release_buffers(void)
292+
{
293+
struct usb_sam0_data *data = usb_sam0_get_data();
294+
UsbDeviceDescBank *bank;
295+
void *buf;
296+
297+
/* release the buffers */
298+
for (int i = 0; i < ARRAY_SIZE(data->descriptors); i++) {
299+
for (int j = 0; j < ARRAY_SIZE(data->descriptors[0].DeviceDescBank); j++) {
300+
bank = &data->descriptors[i].DeviceDescBank[j];
301+
buf = (void *)bank->ADDR.reg;
302+
/*
303+
* We free the ep descriptor memory that was
304+
* allocated in usb_dc_ep_configure().
305+
* Therefore a disabled ep must be reconfigured
306+
* before it can be enabled again.
307+
*/
308+
if (buf != NULL) {
309+
k_free(buf);
310+
bank->ADDR.reg = (uintptr_t) NULL;
311+
}
312+
}
313+
}
314+
}
315+
291316
/* Detach from the bus */
292317
int usb_dc_detach(void)
293318
{
@@ -296,6 +321,8 @@ int usb_dc_detach(void)
296321
regs->CTRLB.bit.DETACH = 1;
297322
usb_sam0_wait_syncbusy();
298323

324+
usb_dc_release_buffers();
325+
299326
return 0;
300327
}
301328

0 commit comments

Comments
 (0)