Re: [PATCH v1] usb: core: add sysfs entry for usb device state

From: Alan Stern
Date: Thu Jun 01 2023 - 19:21:41 EST


On Thu, Jun 01, 2023 at 11:04:56PM +0000, Roy Luo wrote:
> Expose usb device state to userland as the information is useful in
> detecting non-compliant setups and diagnosing enumeration failures.
> For example:
> - End-to-end signal integrity issues: the device would fail port reset
> repeatedly and thus be stuck in POWERED state.
> - Charge-only cables (missing D+/D- lines): the device would never enter
> POWERED state as the HC would not see any pullup.
>
> What's the status quo?
> We do have error logs such as "Cannot enable. Maybe the USB cable is bad?"
> to flag potential setup issues, but there's no good way to expose them to
> userspace.
>
> Why add a sysfs entry in struct usb_port instead of struct usb_device?
> The struct usb_device is not device_add() to the system until it's in
> ADDRESS state hence we would miss the first two states. The struct
> usb_port is a better place to keep the information because its life
> cycle is longer than the struct usb_device that is attached to the port.
>
> Reviewed-by: Alan Stern <stern@xxxxxxxxxxxxxxxxxxx>
> Signed-off-by: Roy Luo <royluo@xxxxxxxxxx>
> ---

> diff --git a/drivers/usb/core/hub.c b/drivers/usb/core/hub.c
> index 97a0f8faea6e..35d94288726b 100644
> --- a/drivers/usb/core/hub.c
> +++ b/drivers/usb/core/hub.c
> @@ -2018,6 +2018,23 @@ bool usb_device_is_owned(struct usb_device *udev)
> return !!hub->ports[udev->portnum - 1]->port_owner;
> }
>
> +static void update_port_device_state(struct usb_device *udev)
> +{
> + struct usb_port *port_dev = NULL;
> + struct usb_hub *hub = NULL;
> + struct kernfs_node *state_node = NULL;
> +
> + if (udev->parent) {
> + hub = usb_hub_to_struct_hub(udev->parent);
> + port_dev = hub->ports[udev->portnum - 1];
> + WRITE_ONCE(port_dev->state, udev->state);
> + state_node = sysfs_get_dirent(port_dev->dev.kobj.sd, "state");
> + if (state_node) {
> + sysfs_notify_dirent(state_node);
> + }
> + }
> +}

I didn't notice the "= NULL" initializers before. You might want to
remove them, since they are completely unnecessary.

Alan Stern