diff --git a/drivers/input/touchscreen/sur40.c b/drivers/input/touchscreen/sur40.c index 09d8c5f8d..39166161d 100644 --- a/drivers/input/touchscreen/sur40.c +++ b/drivers/input/touchscreen/sur40.c @@ -647,6 +647,25 @@ static int sur40_input_setup_events(struct input_dev *input_dev) return 0; } +/* + * Release the sur40 state once the last reference to the video device is + * gone. The video_device is embedded in sur40, so sur40 must not be freed + * while an open file descriptor can still reach it (e.g. from the v4l2 core + * release path). sur40_disconnect() only drops the reference taken by + * v4l2_device_register(), which frees sur40 right away if nothing is open + * or defers it to this callback until the last user closes the device. + */ +static void sur40_release(struct v4l2_device *v4l2_dev) +{ + struct sur40_state *sur40 = + container_of(v4l2_dev, struct sur40_state, v4l2); + + v4l2_ctrl_handler_free(&sur40->hdl); + v4l2_device_unregister(&sur40->v4l2); + kfree(sur40->bulk_in_buffer); + kfree(sur40); +} + /* Check candidate USB interface. */ static int sur40_probe(struct usb_interface *interface, const struct usb_device_id *id) @@ -726,6 +745,7 @@ static int sur40_probe(struct usb_interface *interface, } /* register the video master device */ + sur40->v4l2.release = sur40_release; snprintf(sur40->v4l2.name, sizeof(sur40->v4l2.name), "%s", DRIVER_LONG); error = v4l2_device_register(sur40->dev, &sur40->v4l2); if (error) { @@ -827,14 +847,18 @@ static void sur40_disconnect(struct usb_interface *interface) input_unregister_device(sur40->input); - v4l2_ctrl_handler_free(&sur40->hdl); + v4l2_device_disconnect(&sur40->v4l2); video_unregister_device(&sur40->vdev); - v4l2_device_unregister(&sur40->v4l2); - - kfree(sur40->bulk_in_buffer); - kfree(sur40); usb_set_intfdata(interface, NULL); + + /* + * Drop the reference taken by v4l2_device_register(). The state is + * only freed from sur40_release() once the last video device user is + * gone, so an open device node cannot use the freed memory. + */ + v4l2_device_put(&sur40->v4l2); + dev_dbg(&interface->dev, "%s is now disconnected\n", DRIVER_DESC); }