Skip to contentSkip to conversation

driver core: Authorize device trust before driver binding

PATCH In review Leon Romanovsky 2 participants 35 messages Nov 24

Subsystems (21)
lore
Share & tools
lore
#0 lore raw

v4 cover driver core: Authorize device trust before driver binding

Device trust policies need to precede driver setup, including manual attachment, so userspace can authorize devices before they operate.

This series introduces device trust policy, authorization, and lifetime commitment. Authorization does not reconfigure ATS capabilities or replace IOMMU domains selected during discovery and further ATS and IOMMU integration will follow in a separate series.

The table below tries to summarize the possible kernel command line options and system behavior after that:

Command line                        Initial behavior
----------------------------------  ---------------------------------------
No device_trust options             General: existing driver binding.

PCI: existing ACPI/topology
restrictions.
USB: existing authorized sysfs flow.

device_trust.default=default General: use each bus's initial policy.
PCI: keep the platform classification
and its restrictions; device rules can replace it.
USB: devices and interfaces denied by
USB defaults wait for authorization before binding.

device_trust.default=blocked General: block driver binding until
authorization.
PCI: restrict every device from
discovery; authorization does not revisit domain and ATS decisions.
USB: leave devices and interfaces
unbound until authorized.

device_trust.default=adversarial General: allow adversarial binding.
PCI: restrict every device as
adversarial.
USB: allow adversarial binding,
overriding USB authorization defaults.

device_trust.default=unrestricted General: allow unrestricted binding;
freeze trust policy changes.
PCI: replace the platform
classification; removable devices lose their DMA restrictions.
USB: authorize devices and interfaces
regardless of USB defaults.

device_trust=... General: matching rules select policy;
or device_trust.driver=... unmatched devices stay blocked.
without an explicit default PCI: rules replace the platform
classification; a device rule of default resolves to unrestricted.
USB: matching rules select device or
interface policy.

---
Changes in v4:
- Documentation, commit messages e.t.c
- Don't fail BT device initialization if WiFI USB claim fails/
- Rename "adversary" to "adversarial" as was agreed at the beginning.
- Added new patch to drain usbfs during disconnect.
- Added another new patch to reject usbfs connect requests for
unregistered interfaces.
- Link to v3: https://patch.msgid.link/[email protected]

Changes in v3:
- Rewrote all commit messages
- Split USB patches to smaller chunks
- Introduced special device attach function which works only in
untrusted mode
- Remove the special PHY -EBUSY IRQ handling.
- Clarify that further ATS and IOMMU integration follows separately.
- Link to v2: https://patch.msgid.link/[email protected]

Changes in v2:
- Replace the serio and PHY attachment conversions with device_driver_attach_unrestricted(), restricted to device_trust.default=unrestricted.
- Add USB authorization on top of device trust: export device_trust_set_policy() and convert the USB authorized attributes.
- Documentation and commit messages fixes
- Small USB patches rewrote and split
- Link to v1: https://patch.msgid.link/[email protected]

---
Leon Romanovsky (33):
wifi: mac80211_hwsim: lock device for manual driver binding
Bluetooth: btusb: Fix MediaTek ISO claim locking
USB: Lock interfaces during manual driver binding
USB: serial: Register USB drivers with their owning module
USB: Reject claims of DT-disabled interfaces
USB: Reject usbfs connect requests for unregistered interfaces
USB: Release interface claims according to binding state
USB: Reject claims after interface registration failure
ALSA: usb-audio: Release interface claims when probe fails
USB: Pin modules for unregistered interface claims
USB: Add helpers to release unpublished interface claims
USB: Unwind interface claims after registration or binding failure
PNP: Attach card devices through the driver core
cdx: Propagate DMA configuration errors
driver core: Report deferred probes through sysfs drivers_probe driver core: Add a compatibility API for manual driver attachment
Input: gameport - use the compatibility driver attachment API
Input: serio - use the compatibility driver attachment API
net: phy: Use the compatibility driver attachment API
USB: Drain usbfs when a device is unregistered
driver core: Introduce a generic device trust level driver core: Expose device trust authorization interfaces driver core: Accept device trust policy on the kernel command line driver core: Accept device trust policy by driver name driver core: Expose committed device trust level driver core: Cover trust authorization and binding with KUnit driver core: Document trust admission and initrd authorization
PCI: Use device trust for platform restrictions
iommu: Use device trust for DMA restrictions
driver core: Allow driver attachment with the device lock held
USB: Retain the result of configuration requests
USB: Authorize interfaces through device trust
USB: Authorize devices through device trust

 Documentation/ABI/testing/sysfs-bus-drivers-probe  |   14 +
 Documentation/ABI/testing/sysfs-bus-usb            |   18 +
 Documentation/ABI/testing/sysfs-devices-trust      |   37 +
 Documentation/admin-guide/kernel-parameters.txt    |   37 +
 .../driver-api/driver-model/device-trust.rst       |  343 +++
 Documentation/driver-api/driver-model/index.rst    |    1 +
 Documentation/usb/authorization.rst                |   37 +
 MAINTAINERS                                        |    2 +
 drivers/base/Makefile                              |    2 +-
 drivers/base/base.h                                |   52 +
 drivers/base/bus.c                                 |    9 +-
 drivers/base/core.c                                |   52 +-
 drivers/base/dd.c                                  |  192 +-
 drivers/base/test/Makefile                         |    1 +
 drivers/base/test/device-trust-test.c              | 2487 ++++++++++++++++++++
 drivers/base/trust.c                               |  509 ++++
 drivers/bluetooth/btusb_main.c                     |   55 +-
 drivers/cdx/cdx.c                                  |    2 +-
 drivers/input/gameport/gameport.c                  |   22 +-
 drivers/input/serio/serio.c                        |   29 +-
 drivers/iommu/amd/iommu.c                          |    3 +-
 drivers/iommu/dma-iommu.c                          |   14 +-
 drivers/iommu/intel/iommu.c                        |   14 +-
 drivers/iommu/iommu.c                              |    9 +-
 drivers/net/phy/phy_device.c                       |   28 +-
 drivers/net/wireless/virtual/mac80211_hwsim_main.c |    2 +
 drivers/pci/ats.c                                  |    4 +-
 drivers/pci/pci.c                                  |    5 +-
 drivers/pci/probe.c                                |   18 +-
 drivers/pci/quirks.c                               |    7 +-
 drivers/pnp/card.c                                 |   12 +-
 drivers/usb/core/devio.c                           |   12 +-
 drivers/usb/core/driver.c                          |  118 +-
 drivers/usb/core/generic.c                         |    2 +-
 drivers/usb/core/hub.c                             |   42 +-
 drivers/usb/core/message.c                         |  104 +-
 drivers/usb/core/sysfs.c                           |    9 +-
 drivers/usb/core/trace.h                           |    2 +-
 drivers/usb/core/usb.c                             |    6 +
 drivers/usb/core/usb.h                             |    7 +-
 drivers/usb/serial/usb-serial.c                    |    4 +-
 include/linux/device.h                             |   21 +
 include/linux/device/bus.h                         |   10 +
 include/linux/device/trust.h                       |   54 +
 include/linux/pci.h                                |   18 +-
 include/linux/usb.h                                |   25 +-
 include/linux/usb/serial.h                         |    4 +-
 sound/usb/card.c                                   |    7 +
 48 files changed, 4246 insertions(+), 216 deletions(-)

---
base-commit: 6628e7d4c6b25c8d18f1345e3a20d21829aae7e4
change-id: 20260915-device-trust-core-12934e618489

Best regards,

Signature · 1 line
Leon Romanovsky <[email protected]>
#1 lore raw

PATCH v4 1/33 wifi: mac80211_hwsim: lock device for manual driver binding

From: Leon Romanovsky <[email protected]>

The documented API contract for device_bind_driver() requires the device lock. mac80211_hwsim uses it for a newly created class device with no bus, so no automatic driver-core path can bind the device concurrently and the missing lock was safe.

---
 drivers/net/wireless/virtual/mac80211_hwsim_main.c | 2 ++
 1 file changed, 2 insertions(+)
drivers/net/wireless/virtual/mac80211_hwsim_main.c +2 -0
index e53714b81ec2c..b796da3dd54b3 100644
@@ -5769,7 +5769,9 @@ static int mac80211_hwsim_new_radio(struct genl_info *info,
 		goto failed_drvdata;
 	}
 	data->dev->driver = &mac80211_hwsim_driver.driver;
+	device_lock(data->dev);
 	err = device_bind_driver(data->dev);
+	device_unlock(data->dev);
 	if (err != 0) {
 		pr_debug("mac80211_hwsim: device_bind_driver failed (%d)\n",
 		       err);
Signature · 1 line
2.56.1
#2 lore raw

PATCH v4 2/33 Bluetooth: btusb: Fix MediaTek ISO claim locking

In reply to Leon Romanovsky

From: Leon Romanovsky <[email protected]>

MediaTek ISO claims are performed from HCI setup work outside USB probe. Locking only the interface does not protect the claim against teardown of the parent device. Unconditionally waiting for the parent lock can deadlock with disconnect while it drains the setup work.

Resume the interface before acquiring the parent lock and use bounded retries to keep the interface locked while claiming it. Propagate resume and lock failures to setup, since controller setup requires the parent device. Keep a failed claim non-fatal: MT7663 and MT7668 leave interface 2 to Wi-Fi.

Fixes ceac1cb0259d ("Bluetooth: btusb: mediatek: add ISO data transmission functions")
---
 drivers/bluetooth/btusb_main.c | 53 +++++++++++++++++++++++++++++-------------
 1 file changed, 37 insertions(+), 16 deletions(-)
drivers/bluetooth/btusb_main.c +37 -16
index 92a78a7e60396..128ec6f7d31f0 100644
@@ -2993,40 +2993,54 @@ static int btusb_recv_event_realtek(struct hci_dev *hdev, struct sk_buff *skb)
 	return hci_recv_frame(hdev, skb);
 }
 
-static void btusb_mtk_claim_iso_intf(struct btusb_data *data)
+#define BTUSB_MTK_ISO_LOCK_TRIES	5
+static int btusb_mtk_claim_iso_intf(struct btusb_data *data)
 {
 	struct btmtk_data *btmtk_data;
-	int err;
+	int err, i;
 
 	if (!data->hdev)
-		return;
+		return 0;
 
 	btmtk_data = hci_get_priv(data->hdev);
 	if (!btmtk_data)
-		return;
+		return 0;
 
 	if (!btmtk_data->isopkt_intf) {
 		bt_dev_err(data->hdev, "Can't claim NULL iso interface");
-		return;
+		return 0;
 	}
 
-	/*
-	 * The function usb_driver_claim_interface() is documented to need
-	 * locks held if it's not called from a probe routine. The code here
-	 * is called from the hci_power_on workqueue, so grab the lock.
-	 */
+	err = usb_autopm_get_interface(data->intf);
+	if (err)
+		return err;
+
+	/* Disconnect may hold the parent lock while waiting for this work. */
+	for (i = 0; i < BTUSB_MTK_ISO_LOCK_TRIES; i++) {
+		err = usb_lock_device_for_reset(data->udev, data->intf);
+		if (err != -EBUSY)
+			break;
+	}
+	if (err)
+		goto put_interface;
+
 	device_lock(&btmtk_data->isopkt_intf->dev);
 	err = usb_driver_claim_interface(&btusb_driver,
 					 btmtk_data->isopkt_intf, data);
 	device_unlock(&btmtk_data->isopkt_intf->dev);
-	if (err < 0) {
-		btmtk_data->isopkt_intf = NULL;
+	if (err) {
+		/* MT7663 and MT7668 leave interface 2 to Wi-Fi. */
 		bt_dev_err(data->hdev, "Failed to claim iso interface: %d", err);
-		return;
+		err = 0;
+	} else {
+		init_usb_anchor(&btmtk_data->isopkt_anchor);
+		set_bit(BTMTK_ISOPKT_OVER_INTR, &btmtk_data->flags);
 	}
 
-	set_bit(BTMTK_ISOPKT_OVER_INTR, &btmtk_data->flags);
-	init_usb_anchor(&btmtk_data->isopkt_anchor);
+	usb_unlock_device(data->udev);
+put_interface:
+	usb_autopm_put_interface(data->intf);
+	return err;
 }
 
 static void btusb_mtk_release_iso_intf(struct hci_dev *hdev)
@@ -3169,7 +3183,14 @@ static int btusb_mtk_setup(struct hci_dev *hdev)
 	/* Claim ISO data interface and endpoint */
 	if (!test_bit(BTMTK_ISOPKT_OVER_INTR, &btmtk_data->flags)) {
 		btmtk_data->isopkt_intf = usb_ifnum_to_if(data->udev, MTK_ISO_IFNUM);
-		btusb_mtk_claim_iso_intf(data);
+		err = btusb_mtk_claim_iso_intf(data);
+		if (!test_bit(BTMTK_ISOPKT_OVER_INTR, &btmtk_data->flags))
+			btmtk_data->isopkt_intf = NULL;
+		if (err) {
+			bt_dev_err(hdev, "Failed to resume or lock iso interface: %d",
+				   err);
+			return err;
+		}
 	}
 
 	err = btmtk_usb_setup(hdev);
Signature · 1 line
2.56.1
#3 lore raw

Re: [PATCH v4 02/33] Bluetooth: btusb: Fix MediaTek ISO claim locking

Quoted 6 lines · Leon Romanovsky

From: Leon Romanovsky <[email protected]>

MediaTek ISO claims are performed from HCI setup work outside USB probe. Locking only the interface does not protect the claim against teardown of the parent device. Unconditionally waiting for the parent lock can deadlock with disconnect while it drains the setup work.

Hi,

your patch raises a question. Can usb_claim_interface() ever be used safely outside probe() without this kind of locking?
If the answer to that is negative, should the locking be integrated into usbcore?

Regards
Oliver

#4 lore raw

PATCH v4 3/33 USB: Lock interfaces during manual driver binding

In reply to Leon Romanovsky

From: Leon Romanovsky <[email protected]>

Driver core requires the claimed interface's device lock during binding. The parent USB device lock alone does not satisfy this requirement.

---
 drivers/bluetooth/btusb_main.c |  2 --
 drivers/usb/core/driver.c      | 15 ++++++++++-----
 2 files changed, 10 insertions(+), 7 deletions(-)
drivers/bluetooth/btusb_main.c +0 -2
index 128ec6f7d31f0..37f36434c6e9a 100644
@@ -3024,10 +3024,8 @@ static int btusb_mtk_claim_iso_intf(struct btusb_data *data)
 	if (err)
 		goto put_interface;
 
-	device_lock(&btmtk_data->isopkt_intf->dev);
 	err = usb_driver_claim_interface(&btusb_driver,
 					 btmtk_data->isopkt_intf, data);
-	device_unlock(&btmtk_data->isopkt_intf->dev);
 	if (err) {
 		/* MT7663 and MT7668 leave interface 2 to Wi-Fi. */
 		bt_dev_err(data->hdev, "Failed to claim iso interface: %d", err);
drivers/usb/core/driver.c +10 -5
index d3a61ebc6afb0..e1de348cc0cac 100644
@@ -540,9 +540,8 @@ static void usb_shutdown_interface(struct device *dev)
  * No device driver should directly modify internal usb_interface or
  * usb_device structure members.
  *
- * Callers must own the device lock, so driver probe() entries don't need
- * extra locking, but other call contexts may need to explicitly claim that
- * lock.
+ * Callers must hold the parent USB device lock, but not the claimed
+ * interface's device lock.
  *
  * Return: 0 on success.
  */
@@ -559,9 +558,13 @@ int usb_driver_claim_interface(struct usb_driver *driver,
 	if (dev->driver)
 		return -EBUSY;
 
+	device_lock(dev);
+
 	/* reject claim if interface is not authorized */
-	if (!iface->authorized)
-		return -ENODEV;
+	if (!iface->authorized) {
+		retval = -ENODEV;
+		goto unlock;
+	}
 
 	dev->driver = &driver->driver;
 	usb_set_intfdata(iface, data);
@@ -602,6 +605,8 @@ int usb_driver_claim_interface(struct usb_driver *driver,
 		pm_runtime_set_suspended(dev);
 	}
 
+unlock:
+	device_unlock(dev);
 	return retval;
 }
 EXPORT_SYMBOL_GPL(usb_driver_claim_interface);
Signature · 1 line
2.56.1
#5 lore raw

PATCH v4 4/33 USB: serial: Register USB drivers with their owning module

In reply to Leon Romanovsky

From: Leon Romanovsky <[email protected]>

The USB-serial core allocates each USB driver on behalf of its serial module, which deregisters and frees it during module exit. Registering through usb_register() instead identifies the USB-serial core as its owner, so a module reference does not retain the driver's allocation.

Pass the serial module's owner and KBUILD_MODNAME to usb_register_driver(). Keep the module name separate from the USB driver name so built-in drivers also link to the correct module.

Fixes 68e24113457e ("USB: serial: rework usb_serial_register/deregister_drivers()")
---
 drivers/usb/serial/usb-serial.c | 4 +++-
 include/linux/usb/serial.h      | 4 +++-
 2 files changed, 6 insertions(+), 2 deletions(-)
drivers/usb/serial/usb-serial.c +3 -1
index 4a19621f08ba2..ccbd0875339a3 100644
@@ -1513,6 +1513,7 @@ static void usb_serial_deregister(struct usb_serial_driver *device)
  * @serial_drivers: NULL-terminated array of pointers to drivers to be registered
  * @owner: owning module
  * @name: name of the usb_driver for this set of @serial_drivers
+ * @mod_name: name of the module containing the serial drivers
  * @id_table: list of all devices this @serial_drivers set binds to
  *
  * Registers all the drivers in the @serial_drivers array, and dynamically
@@ -1520,6 +1521,7 @@ static void usb_serial_deregister(struct usb_serial_driver *device)
  */
 int __usb_serial_register_drivers(struct usb_serial_driver *const serial_drivers[],
 				  struct module *owner, const char *name,
+				  const char *mod_name,
 				  const struct usb_device_id *id_table)
 {
 	int rc;
@@ -1559,7 +1561,7 @@ int __usb_serial_register_drivers(struct usb_serial_driver *const serial_drivers
 		}
 	}
 
-	rc = usb_register(udriver);
+	rc = usb_register_driver(udriver, owner, mod_name);
 	if (rc)
 		goto err_free_driver;
 
include/linux/usb/serial.h +3 -1
index 5866f19d3c7b8..fcfd0e26e0ffb 100644
@@ -321,9 +321,11 @@ struct usb_serial_driver {
 	container_of(d, struct usb_serial_driver, driver)
 
 #define usb_serial_register_drivers(serial_drivers, name, id_table) \
-	__usb_serial_register_drivers(serial_drivers, THIS_MODULE, name, id_table)
+	__usb_serial_register_drivers(serial_drivers, THIS_MODULE, name, \
+				      KBUILD_MODNAME, id_table)
 int __usb_serial_register_drivers(struct usb_serial_driver *const serial_drivers[],
 				  struct module *owner, const char *name,
+				  const char *mod_name,
 				  const struct usb_device_id *id_table);
 void usb_serial_deregister_drivers(struct usb_serial_driver *const serial_drivers[]);
 void usb_serial_port_softint(struct usb_serial_port *port);
Signature · 1 line
2.56.1
#6 lore raw

PATCH v4 5/33 USB: Reject claims of DT-disabled interfaces

In reply to Leon Romanovsky

From: Leon Romanovsky <[email protected]>

USB core skips registration of DT-disabled interfaces but keeps their objects available to sibling drivers. A CDC-ACM control interface can therefore claim a disabled data interface: manual claims check USB authorization without checking Device Tree availability.

Fixes 01fdf179f4b0 ("usb: core: skip interfaces disabled in devicetree")
---
 drivers/usb/core/driver.c | 5 +++--
 1 file changed, 3 insertions(+), 2 deletions(-)
drivers/usb/core/driver.c +3 -2
index e1de348cc0cac..735ae3310b45d 100644
@@ -28,6 +28,7 @@
 #include <linux/device.h>
 #include <linux/slab.h>
 #include <linux/export.h>
+#include <linux/of.h>
 #include <linux/usb.h>
 #include <linux/usb/quirks.h>
 #include <linux/usb/hcd.h>
@@ -560,8 +561,8 @@ int usb_driver_claim_interface(struct usb_driver *driver,
 
 	device_lock(dev);
 
-	/* reject claim if interface is not authorized */
-	if (!iface->authorized) {
+	if (!iface->authorized ||
+	    (dev->of_node && !of_device_is_available(dev->of_node))) {
 		retval = -ENODEV;
 		goto unlock;
 	}
Signature · 1 line
2.56.1
#7 lore raw

PATCH v4 6/33 USB: Reject usbfs connect requests for unregistered interfaces

In reply to Leon Romanovsky

From: Leon Romanovsky <[email protected]>

USB core does not register DT-disabled interfaces, and an interface whose registration failed stays in the active configuration. USBDEVFS_CONNECT still asks driver core to attach a driver to such an interface:

proc_ioctl()
device_attach()

    __device_attach()

The interface has no driver-core private data, so the request dereferences a NULL pointer.

Return -ENODEV for an unregistered interface. An interface claimed by a sibling driver keeps reporting -EBUSY.

Fixes ef0ff68351be ("driver core: Probe devices asynchronously instead of the driver")
---
 drivers/usb/core/devio.c | 8 +++++---
 1 file changed, 5 insertions(+), 3 deletions(-)
drivers/usb/core/devio.c +5 -3
index 101cb94254809..1491ba015bcd8 100644
@@ -2366,10 +2366,12 @@ static int proc_ioctl(struct usb_dev_state *ps, struct usbdevfs_ioctl *ctl)
 
 	/* let kernel drivers try to (re)bind to the interface */
 	case USBDEVFS_CONNECT:
-		if (!intf->dev.driver)
-			retval = device_attach(&intf->dev);
-		else
+		if (intf->dev.driver)
 			retval = -EBUSY;
+		else if (!device_is_registered(&intf->dev))
+			retval = -ENODEV;
+		else
+			retval = device_attach(&intf->dev);
 		break;
 
 	/* talk directly to the interface's driver */
Signature · 1 line
2.56.1
#8 lore raw

PATCH v4 7/33 USB: Release interface claims according to binding state

In reply to Leon Romanovsky

From: Leon Romanovsky <[email protected]>

A driver such as CDC-ACM can claim a sibling interface before it is registered. Disabling USB bus autoprobing between the claim and registration leaves dev->driver set without adding the interface to the driver's bound-device list.

Releasing that interface through driver core then attempts to remove an unattached list node, causing a NULL pointer dereference.

Fixes b8c5cec23d5c ("Driver core: udev triggered device-<>driver binding")
---
 drivers/usb/core/driver.c | 37 ++++++++++++++++++++++---------------
 1 file changed, 22 insertions(+), 15 deletions(-)
drivers/usb/core/driver.c +22 -15
index 735ae3310b45d..d902708416d06 100644
@@ -612,6 +612,15 @@ int usb_driver_claim_interface(struct usb_driver *driver,
 }
 EXPORT_SYMBOL_GPL(usb_driver_claim_interface);
 
+static void usb_unbind_claim(struct usb_interface *iface)
+{
+	struct device *dev = &iface->dev;
+
+	usb_unbind_interface(dev);
+	dev_set_drvdata(dev, NULL);
+	dev->driver = NULL;
+}
+
 /**
  * usb_driver_release_interface - unbind a driver from an interface
  * @driver: the driver to be unbound
@@ -631,27 +640,25 @@ void usb_driver_release_interface(struct usb_driver *driver,
 {
 	struct device *dev = &iface->dev;
 
-	/* this should never happen, don't release something that's not ours */
-	if (!dev->driver || dev->driver != &driver->driver)
-		return;
-
-	/* don't release from within disconnect() */
+	/* Avoid recursive locking from disconnect(). */
 	if (iface->condition != USB_INTERFACE_BOUND)
 		return;
+
+	device_lock(dev);
+	if (!dev->driver || dev->driver != &driver->driver ||
+	    iface->condition != USB_INTERFACE_BOUND)
+		goto unlock;
 	iface->condition = USB_INTERFACE_UNBINDING;
 
-	/* Release via the driver core only if the interface
-	 * has already been registered
-	 */
-	if (device_is_registered(dev)) {
-		device_release_driver(dev);
-	} else {
-		device_lock(dev);
-		usb_unbind_interface(dev);
-		dev_set_drvdata(dev, NULL);
-		dev->driver = NULL;
+	if (device_is_bound(dev)) {
 		device_unlock(dev);
+		device_release_driver(dev);
+		return;
 	}
+
+	usb_unbind_claim(iface);
+unlock:
+	device_unlock(dev);
 }
 EXPORT_SYMBOL_GPL(usb_driver_release_interface);
 
Signature · 1 line
2.56.1
#9 lore raw

PATCH v4 8/33 USB: Reject claims after interface registration failure

In reply to Leon Romanovsky

From: Leon Romanovsky <[email protected]>

After device_add() fails, the interface remains in the active configuration, so usbfs can still claim it. Configuration removal skips unregistered interfaces and never calls the claimant's disconnect callback.

A driver can claim an interface before USB core registers it. If registration fails, reject further claims because USB core will not retry registration of that object. Changing the device configuration creates new interface objects.

Fixes 86d30741e480 ("[PATCH] USB: Usbcore: Don't try to delete unregistered interfaces")
---
 drivers/usb/core/driver.c  |  2 +-
 drivers/usb/core/message.c | 12 ++++++++++--
 2 files changed, 11 insertions(+), 3 deletions(-)
drivers/usb/core/driver.c +1 -1
index d902708416d06..a50403820285a 100644
@@ -561,7 +561,7 @@ int usb_driver_claim_interface(struct usb_driver *driver,
 
 	device_lock(dev);
 
-	if (!iface->authorized ||
+	if (!iface->authorized || iface->unregistering ||
 	    (dev->of_node && !of_device_is_available(dev->of_node))) {
 		retval = -ENODEV;
 		goto unlock;
drivers/usb/core/message.c +10 -2
index a738d03c23eac..a645858b25d96 100644
@@ -1468,8 +1468,13 @@ void usb_disable_device(struct usb_device *dev, int skip_ep0)
 		 * bandwidth_mutex, we have to mark all the interfaces
 		 * before unregistering any of them.
 		 */
-		for (i = 0; i < dev->actconfig->desc.bNumInterfaces; i++)
-			dev->actconfig->interface[i]->unregistering = 1;
+		for (i = 0; i < dev->actconfig->desc.bNumInterfaces; i++) {
+			struct usb_interface *intf = dev->actconfig->interface[i];
+
+			device_lock(&intf->dev);
+			intf->unregistering = 1;
+			device_unlock(&intf->dev);
+		}
 
 		for (i = 0; i < dev->actconfig->desc.bNumInterfaces; i++) {
 			struct usb_interface	*interface;
@@ -2279,6 +2284,9 @@ int usb_set_configuration(struct usb_device *dev, int configuration)
 		device_enable_async_suspend(&intf->dev);
 		ret = device_add(&intf->dev);
 		if (ret != 0) {
+			device_lock(&intf->dev);
+			intf->unregistering = 1;
+			device_unlock(&intf->dev);
 			dev_err(&dev->dev, "device_add(%s) --> %d\n",
 				dev_name(&intf->dev), ret);
 			continue;
Signature · 1 line
2.56.1
#10 lore raw

PATCH v4 9/33 ALSA: usb-audio: Release interface claims when probe fails

In reply to Leon Romanovsky

From: Leon Romanovsky <[email protected]>

If the first control-interface probe fails after claiming streaming or MIDI interfaces, freeing the card leaves those claims behind. Module unload can then race with registration of the claimed interfaces and leave dangling driver pointers.

Release auxiliary claims when discarding a newly created card. Preserve them when a failed secondary probe leaves an existing card in use.

Fixes 9ad3d6ccf5ee ("[PATCH] USB: Remove USB private semaphore")
---
 sound/usb/card.c | 7 +++++++
 1 file changed, 7 insertions(+)
sound/usb/card.c +7 -0
index 59979b793fe91..56ebdd61f72e7 100644
@@ -1090,6 +1090,13 @@ static int usb_audio_probe(struct usb_interface *intf,
 		atomic_dec(&chip->active);
 		if (!chip->num_interfaces) {
 			usb_audio_disconnect_components(chip);
+			for (i = 0; i < dev->actconfig->desc.bNumInterfaces; i++) {
+				struct usb_interface *iface = dev->actconfig->interface[i];
+
+				if (iface->dev.driver == &usb_audio_driver.driver &&
+				    usb_get_intfdata(iface) == USB_AUDIO_IFACE_UNUSED)
+					usb_driver_release_interface(&usb_audio_driver, iface);
+			}
 			snd_card_free(chip->card);
 		}
 	}
Signature · 1 line
2.56.1
#11 lore raw

PATCH v4 10/33 USB: Pin modules for unregistered interface claims

In reply to Leon Romanovsky

From: Leon Romanovsky <[email protected]>

A successful CDC-ACM control probe can claim its data interface before registration. If data registration fails, cleanup can race with module unload when no tty is open:

Thread A (cleanup) Thread B (unload)

usb_driver_release_refused_claim(data)
usb_unbind_interface(data)
acm_disconnect(data)
usb_driver_release_interface(control)
device_release_driver(control)
device_release_driver_internal()
__device_release_driver()
klist_remove() [last bound interface]
delete_module()
acm_exit()
usb_deregister()
driver_unregister()
bus_remove_driver()
driver_detach()
[empty list]
free_module()
[resumes in freed acm_disconnect()]
tty_port_put()

The empty list lets unload skip the USB device lock and free the module before the callback returns. Hold a module reference through registration or cleanup, preparing for the cleanup added next.

---
 drivers/usb/core/driver.c  | 17 +++++++++++++++++
 drivers/usb/core/message.c |  6 ++++++
 drivers/usb/core/usb.h     |  1 +
 include/linux/usb.h        |  2 ++
 4 files changed, 26 insertions(+)
drivers/usb/core/driver.c +17 -0
index a50403820285a..a03ea60edc501 100644
@@ -529,6 +529,13 @@ static void usb_shutdown_interface(struct device *dev)
 		driver->shutdown(intf);
 }
 
+void usb_put_claim_owner(struct usb_interface *intf)
+{
+	struct module *owner = xchg(&intf->claim_owner, NULL);
+
+	module_put(owner);
+}
+
 /**
  * usb_driver_claim_interface - bind a driver to an interface
  * @driver: the driver to be bound
@@ -567,6 +574,14 @@ int usb_driver_claim_interface(struct usb_driver *driver,
 		goto unlock;
 	}
 
+	if (!device_is_registered(dev)) {
+		if (!try_module_get(driver->driver.owner)) {
+			retval = -ENODEV;
+			goto unlock;
+		}
+		iface->claim_owner = driver->driver.owner;
+	}
+
 	dev->driver = &driver->driver;
 	usb_set_intfdata(iface, data);
 	iface->needs_binding = 0;
@@ -619,6 +634,7 @@ static void usb_unbind_claim(struct usb_interface *iface)
 	usb_unbind_interface(dev);
 	dev_set_drvdata(dev, NULL);
 	dev->driver = NULL;
+	usb_put_claim_owner(iface);
 }
 
 /**
@@ -653,6 +669,7 @@ void usb_driver_release_interface(struct usb_driver *driver,
 	if (device_is_bound(dev)) {
 		device_unlock(dev);
 		device_release_driver(dev);
+		usb_put_claim_owner(iface);
 		return;
 	}
 
drivers/usb/core/message.c +6 -0
index a645858b25d96..cfb4cbdbe76fa 100644
@@ -1845,6 +1845,7 @@ static void usb_release_interface(struct device *dev)
 	struct usb_interface_cache *intfc =
 			altsetting_to_usb_interface_cache(intf->altsetting);
 
+	usb_put_claim_owner(intf);
 	kref_put(&intfc->ref, usb_release_interface_cache);
 	usb_put_dev(interface_to_usbdev(intf));
 	of_node_put(dev->of_node);
@@ -2269,6 +2270,7 @@ int usb_set_configuration(struct usb_device *dev, int configuration)
 	 */
 	for (i = 0; i < nintf; ++i) {
 		struct usb_interface *intf = cp->interface[i];
+		struct module *claim_owner;
 
 		if (intf->dev.of_node &&
 		    !of_device_is_available(intf->dev.of_node)) {
@@ -2282,7 +2284,11 @@ int usb_set_configuration(struct usb_device *dev, int configuration)
 			dev_name(&intf->dev), configuration,
 			intf->cur_altsetting->desc.bInterfaceNumber);
 		device_enable_async_suspend(&intf->dev);
+		device_lock(&intf->dev);
+		claim_owner = xchg(&intf->claim_owner, NULL);
+		device_unlock(&intf->dev);
 		ret = device_add(&intf->dev);
+		module_put(claim_owner);
 		if (ret != 0) {
 			device_lock(&intf->dev);
 			intf->unregistering = 1;
drivers/usb/core/usb.h +1 -0
index a9b37aeb515be..dfa48f43046d4 100644
@@ -49,6 +49,7 @@ extern int usb_set_isoch_delay(struct usb_device *dev);
 extern int usb_get_bos_descriptor(struct usb_device *dev);
 extern void usb_release_bos_descriptor(struct usb_device *dev);
 extern int usb_set_configuration(struct usb_device *dev, int configuration);
+void usb_put_claim_owner(struct usb_interface *intf);
 extern int usb_choose_configuration(struct usb_device *udev);
 extern int usb_generic_driver_probe(struct usb_device *udev);
 extern void usb_generic_driver_disconnect(struct usb_device *udev);
include/linux/usb.h +2 -0
index 825f03b290670..a5e706f67f33a 100644
@@ -213,6 +213,7 @@ enum usb_wireless_status {
  * @dev: driver model's view of this device
  * @usb_dev: if an interface is bound to the USB major, this will point
  *	to the sysfs representation for that device.
+ * @claim_owner: Module reference for an unpublished claim.
  * @reset_ws: Used for scheduling resets from atomic context.
  * @resetting_device: USB core reset the device, so use alt setting 0 as
  *	current; needs bandwidth alloc after reset.
@@ -271,6 +272,7 @@ struct usb_interface {
 
 	struct device dev;		/* interface specific device info */
 	struct device *usb_dev;
+	struct module *claim_owner;
 	struct work_struct reset_ws;	/* for resets in atomic context */
 };
 
Signature · 1 line
2.56.1
#12 lore raw

PATCH v4 11/33 USB: Add helpers to release unpublished interface claims

In reply to Leon Romanovsky

From: Leon Romanovsky <[email protected]>

An early USB claim can require disconnect even though driver core never bound the interface. Binding failure may also have cleared the claimant pointer.

Add release helpers so registration rollback and configuration removal can unwind these claims through USB.

---
 drivers/usb/core/driver.c | 26 ++++++++++++++++++++++++++
 drivers/usb/core/usb.h    |  3 +++
 2 files changed, 29 insertions(+)
drivers/usb/core/driver.c +26 -0
index a03ea60edc501..9dd022c1ca151 100644
@@ -637,6 +637,14 @@ static void usb_unbind_claim(struct usb_interface *iface)
 	usb_put_claim_owner(iface);
 }
 
+void usb_release_unregistered_interface(struct usb_interface *iface)
+{
+	device_lock(&iface->dev);
+	if (iface->condition == USB_INTERFACE_BOUND)
+		usb_unbind_claim(iface);
+	device_unlock(&iface->dev);
+}
+
 /**
  * usb_driver_release_interface - unbind a driver from an interface
  * @driver: the driver to be unbound
@@ -679,6 +687,24 @@ void usb_driver_release_interface(struct usb_driver *driver,
 }
 EXPORT_SYMBOL_GPL(usb_driver_release_interface);
 
+bool usb_driver_release_refused_claim(struct usb_interface *iface,
+				      struct device_driver *claimant)
+{
+	struct device *dev = &iface->dev;
+
+	device_lock(dev);
+	if (iface->condition != USB_INTERFACE_BOUND || device_is_bound(dev)) {
+		device_unlock(dev);
+		return false;
+	}
+	dev->driver = claimant;
+	usb_unbind_interface(dev);
+	dev_set_drvdata(dev, NULL);
+	dev->driver = NULL;
+	device_unlock(dev);
+	return true;
+}
+
 /* returns 0 if no match, 1 if match */
 int usb_match_device(struct usb_device *dev, const struct usb_device_id *id)
 {
drivers/usb/core/usb.h +3 -0
index dfa48f43046d4..1b2de58fd6cef 100644
@@ -50,6 +50,9 @@ extern int usb_get_bos_descriptor(struct usb_device *dev);
 extern void usb_release_bos_descriptor(struct usb_device *dev);
 extern int usb_set_configuration(struct usb_device *dev, int configuration);
 void usb_put_claim_owner(struct usb_interface *intf);
+void usb_release_unregistered_interface(struct usb_interface *iface);
+bool usb_driver_release_refused_claim(struct usb_interface *iface,
+				      struct device_driver *claimant);
 extern int usb_choose_configuration(struct usb_device *udev);
 extern int usb_generic_driver_probe(struct usb_device *udev);
 extern void usb_generic_driver_disconnect(struct usb_device *udev);
Signature · 1 line
2.56.1
#13 lore raw

PATCH v4 12/33 USB: Unwind interface claims after registration or binding failure

In reply to Leon Romanovsky

From: Leon Romanovsky <[email protected]>

A successful USB-audio control probe can claim unregistered playback and capture interfaces. If playback registration fails, releasing its claim alone leaves the card active, its disconnect callback returns immediately.

usb_set_configuration()
device_add(control)
usb_audio_probe()
snd_usb_create_streams()
snd_usb_create_stream(playback)
usb_driver_claim_interface(playback)
snd_usb_create_stream(capture)
usb_driver_claim_interface(capture)
device_add(playback) [fails]

Configuration removal skips unregistered claims. Binding failure can clear dev->driver without disconnecting the claimant, and disabled autoprobe leaves the claim unbound.

Release every claim that driver core left unbound, remove the configuration if sibling claims remain, and disconnect unpublished claims before freeing interfaces or dropping the module reference. A bound claim is on the driver's device list, so unload waits for its disconnect.

Fixes 1da177e4c3f4 ("Linux-2.6.12-rc2")
Fixes 86d30741e480f ("[PATCH] USB: Usbcore: Don't try to delete unregistered interfaces")
Fixes c6a46696f97ff ("driver core: don't fail attaching the device if it cannot be bound")
---
 drivers/usb/core/message.c | 41 ++++++++++++++++++++++++++++++++++++++++-
 1 file changed, 40 insertions(+), 1 deletion(-)
drivers/usb/core/message.c +40 -1
index cfb4cbdbe76fa..e7a23e406f8a2 100644
@@ -1489,6 +1489,9 @@ void usb_disable_device(struct usb_device *dev, int skip_ep0)
 			device_del(&interface->dev);
 		}
 
+		for (i = 0; i < dev->actconfig->desc.bNumInterfaces; i++)
+			usb_release_unregistered_interface(dev->actconfig->interface[i]);
+
 		/* Now that the interfaces are unbound, nobody should
 		 * try to access them.
 		 */
@@ -2020,6 +2023,25 @@ int usb_set_wireless_status(struct usb_interface *iface,
 }
 EXPORT_SYMBOL_GPL(usb_set_wireless_status);
 
+static bool usb_has_claimant(struct usb_device *dev,
+			     const struct device_driver *claimant)
+{
+	struct usb_host_config *config = dev->actconfig;
+	int i;
+
+	for (i = 0; i < config->desc.bNumInterfaces; i++) {
+		struct device *intf = &config->interface[i]->dev;
+		bool claimed;
+
+		device_lock(intf);
+		claimed = intf->driver == claimant;
+		device_unlock(intf);
+		if (claimed)
+			return true;
+	}
+	return false;
+}
+
 /*
  * usb_set_configuration - Makes a particular device setting be current
  * @dev: the device whose configuration is being updated
@@ -2270,6 +2292,7 @@ int usb_set_configuration(struct usb_device *dev, int configuration)
 	 */
 	for (i = 0; i < nintf; ++i) {
 		struct usb_interface *intf = cp->interface[i];
+		struct device_driver *claimant;
 		struct module *claim_owner;
 
 		if (intf->dev.of_node &&
@@ -2285,10 +2308,26 @@ int usb_set_configuration(struct usb_device *dev, int configuration)
 			intf->cur_altsetting->desc.bInterfaceNumber);
 		device_enable_async_suspend(&intf->dev);
 		device_lock(&intf->dev);
+		claimant = intf->dev.driver;
 		claim_owner = xchg(&intf->claim_owner, NULL);
 		device_unlock(&intf->dev);
 		ret = device_add(&intf->dev);
-		module_put(claim_owner);
+		if (claimant &&
+		    usb_driver_release_refused_claim(intf, claimant)) {
+			bool unconfigure = usb_has_claimant(dev, claimant);
+
+			get_device(&intf->dev);
+			if (unconfigure)
+				usb_set_configuration(dev, -1);
+			module_put(claim_owner);
+			put_device(&intf->dev);
+			if (unconfigure) {
+				usb_autosuspend_device(dev);
+				return ret ? ret : -ENODEV;
+			}
+		} else {
+			module_put(claim_owner);
+		}
 		if (ret != 0) {
 			device_lock(&intf->dev);
 			intf->unregistering = 1;
Signature · 1 line
2.56.1
#14 lore raw

PATCH v4 13/33 PNP: Attach card devices through the driver core

In reply to Leon Romanovsky

From: Leon Romanovsky <[email protected]>

pnp_request_card_device() calls the PnP bus probe directly, bypassing the driver core's supplier checks and power management setup. If device_bind_driver() then fails to create the sysfs links, the device remains attached and may stay active, but the caller receives NULL and cannot release it.

Use device_driver_attach() for synchronous probing with the driver core's setup and error handling. Preserve the card link until binding completes, so probe cleanup and CONFIG_DEBUG_TEST_DRIVER_REMOVE cannot clear or free a link still owned by the enclosing card probe.

Fixes bfc7ee207078 ("[PATCH] PNP: handle sysfs errors")
---
 drivers/pnp/card.c | 12 ++++++------
 1 file changed, 6 insertions(+), 6 deletions(-)
drivers/pnp/card.c +6 -6
index df5e3d3cbf6c0..9aaaa03d5ffa9 100644
@@ -52,13 +52,17 @@ static const struct pnp_card_device_id *match_card(struct pnp_card_driver *drv,
 
 static void card_remove(struct pnp_dev *dev)
 {
-	dev->card_link = NULL;
+	if (device_is_bound(&dev->dev))
+		dev->card_link = NULL;
 }
 
 static void card_remove_first(struct pnp_dev *dev)
 {
 	struct pnp_card_driver *drv = to_pnp_card_driver(dev->driver);
 
+	/* The card probe still owns its link until this device is bound. */
+	if (!device_is_bound(&dev->dev))
+		return;
 	if (!dev->card || !drv)
 		return;
 	if (drv->remove)
@@ -331,16 +335,12 @@ struct pnp_dev *pnp_request_card_device(struct pnp_card_link *clink,
 
 found:
 	dev->card_link = clink;
-	dev->dev.driver = &drv->link.driver;
-	if (pnp_bus_type.probe(&dev->dev))
-		goto err_out;
-	if (device_bind_driver(&dev->dev))
+	if (device_driver_attach(&drv->link.driver, &dev->dev))
 		goto err_out;
 
 	return dev;
 
 err_out:
-	dev->dev.driver = NULL;
 	dev->card_link = NULL;
 	return NULL;
 }
Signature · 1 line
2.56.1
#15 lore raw

PATCH v4 14/33 cdx: Propagate DMA configuration errors

In reply to Leon Romanovsky

From: Leon Romanovsky <[email protected]>

CDX reports successful DMA configuration when firmware setup defers or default-domain acquisition fails. Driver probing can then proceed without the required DMA setup or IOMMU ownership.

Return the configuration result so driver core stops or defers probing instead of allowing a driver to use a rejected domain.

Fixes 2959ab247061 ("cdx: add the cdx bus driver")
---
 drivers/cdx/cdx.c | 2 +-
 1 file changed, 1 insertion(+), 1 deletion(-)
drivers/cdx/cdx.c +1 -1
index a118a89a7779d..0a030bf522690 100644
@@ -367,7 +367,7 @@ static int cdx_dma_configure(struct device *dev)
 			arch_teardown_dma_ops(dev);
 	}
 
-	return 0;
+	return ret;
 }
 
 static void cdx_dma_cleanup(struct device *dev)
Signature · 1 line
2.56.1
#16 lore raw

PATCH v4 15/33 driver core: Report deferred probes through sysfs drivers_probe

In reply to Leon Romanovsky

From: Leon Romanovsky <[email protected]>

commit b8c5cec23d5c ("Driver core: udev triggered device-<>driver binding") introduced the concept of "Systems who want to control the driver binding with udev" can use the drivers_probe sysfs to trigger a driver bind based on the kernel's match list.

If attaching the driver is deferred before its probe callback runs, userspace sees EINVAL and cannot tell it should try again, maybe after loading other drivers.

Map that deferral to EAGAIN and add missed documentation for the drivers_probe sysfs. A deferral requested by the probe callback itself is still not reported.

Fixes b8c5cec23d5c ("Driver core: udev triggered device-<>driver binding")
---
 Documentation/ABI/testing/sysfs-bus-drivers-probe | 14 ++++++++++++++
 MAINTAINERS                                       |  1 +
 drivers/base/bus.c                                |  9 +++++++--
 3 files changed, 22 insertions(+), 2 deletions(-)
Documentation/ABI/testing/sysfs-bus-drivers-probe new file +14 -0
new file mode 100644
index 0000000000000..ed8828e55d6bf
@@ -0,0 +1,14 @@
+What:		/sys/bus/.../drivers_probe
+Date:		February 2007
+Contact:	[email protected]
+Description:
+		(WO) Writing a device name requests driver attachment on this
+		bus, even when drivers_autoprobe is disabled. A successful
+		write does not guarantee that a driver bound. The driver link
+		can appear before probe completes; a bind uevent signals
+		successful binding.
+
+		EAGAIN means attachment was deferred before the driver's probe
+		callback, for example while a supplier or the device itself
+		is not ready. ENODEV means the device was not found. Other
+		attachment errors return EINVAL.
MAINTAINERS +1 -0
index 93abbb315065d..b726344362b41 100644
@@ -8149,6 +8149,7 @@ M:	Johan Hovold <[email protected]>
 L:	[email protected]
 S:	Supported
 T:	git git://git.kernel.org/pub/scm/linux/kernel/git/driver-core/driver-core.git
+F:	Documentation/ABI/testing/sysfs-bus-drivers-probe
 F:	Documentation/core-api/kobject.rst
 F:	Documentation/driver-api/driver-model/
 F:	drivers/base/
drivers/base/bus.c +7 -2
index 396097fdb3162..ecff32c3704b5 100644
@@ -310,13 +310,18 @@ static ssize_t drivers_probe_store(const struct bus_type *bus,
 				   const char *buf, size_t count)
 {
 	struct device *dev;
-	int err = -EINVAL;
+	int err;
 
 	dev = bus_find_device_by_name(bus, NULL, buf);
 	if (!dev)
 		return -ENODEV;
-	if (bus_rescan_devices_helper(dev, NULL) == 0)
+	err = bus_rescan_devices_helper(dev, NULL);
+	if (!err)
 		err = count;
+	else if (err == -EPROBE_DEFER)
+		err = -EAGAIN;
+	else
+		err = -EINVAL;
 	put_device(dev);
 	return err;
 }
Signature · 1 line
2.56.1
#17 lore raw

PATCH v4 16/33 driver core: Add a compatibility API for manual driver attachment

In reply to Leon Romanovsky

From: Leon Romanovsky <[email protected]>

Manual attachment can race normal probing and removal, releasing another probe's resources. Callers cannot always acquire the device mutex under subsystem locks.

Add device_driver_attach_unrestricted() with a binding mutex shared by attachment, removal and deletion. Trylock it to reject competing transactions. Supplier-status reads must avoid sysfs lock inversion and private-state access after registration failure.

This compatibility API must not be used in any new code: it prevents use of the device trust authorization infrastructure. New code must use device_driver_attach().

---
 drivers/base/base.h    |   3 ++
 drivers/base/core.c    |  32 +++++++++++---
 drivers/base/dd.c      | 117 +++++++++++++++++++++++++++++++++++++++++++------
 include/linux/device.h |   2 +
 4 files changed, 134 insertions(+), 20 deletions(-)
drivers/base/base.h +3 -0
index 866b2beb6baa2..61f49fc142f45 100644
@@ -105,6 +105,7 @@ struct driver_private {
  *			   dev_err_probe() for later retrieval via debugfs
  * @device: pointer back to the struct device that this structure is
  *	    associated with.
+ * @driver_lock: serializes binding and removal, including compatibility attach
  * @dead: This device is currently either in the process of or has been
  *	  removed from the system. Any asynchronous events scheduled for this
  *	  device should exit without taking any action.
@@ -121,6 +122,8 @@ struct device_private {
 	const struct device_driver *async_driver;
 	char *deferred_probe_reason;
 	struct device *device;
+	/* Taken after the device mutex, except by compatibility attach. */
+	struct mutex driver_lock;
 	u8 dead:1;
 };
 #define to_device_private_parent(obj)	\
drivers/base/core.c +25 -7
index cbe05197d4a0b..92d25bf4f8632 100644
@@ -1315,13 +1315,23 @@ static ssize_t waiting_for_supplier_show(struct device *dev,
 					 const struct device_attribute *attr,
 					 char *buf)
 {
+	struct kernfs_node *kn;
+	ssize_t ret = -ENODEV;
 	bool val;
 
+	kn = sysfs_break_active_protection(&dev->kobj, &attr->attr);
+	if (!kn)
+		return -ENODEV;
+
 	device_lock(dev);
-	scoped_guard(mutex, &fwnode_link_lock)
-		val = !!fwnode_links_check_suppliers(dev->fwnode);
+	if (dev_ready_to_probe(dev) && !dev->p->dead) {
+		scoped_guard(mutex, &fwnode_link_lock)
+			val = !!fwnode_links_check_suppliers(dev->fwnode);
+		ret = sysfs_emit(buf, "%u\n", val);
+	}
 	device_unlock(dev);
-	return sysfs_emit(buf, "%u\n", val);
+	sysfs_unbreak_active_protection(kn);
+	return ret;
 }
 static const DEVICE_ATTR_RO(waiting_for_supplier);
 
@@ -3609,6 +3619,9 @@ static int device_private_init(struct device *dev)
 	if (!dev->p)
 		return -ENOMEM;
 	dev->p->device = dev;
+	mutex_init(&dev->p->driver_lock);
+	/* Driver callbacks can bind or unbind child devices. */
+	lockdep_set_novalidate_class(&dev->p->driver_lock);
 	klist_init(&dev->p->klist_children, klist_children_get,
 		   klist_children_put);
 	INIT_LIST_HEAD(&dev->p->deferred_probe);
@@ -3889,6 +3902,8 @@ EXPORT_SYMBOL_GPL(put_device);
 
 bool kill_device(struct device *dev)
 {
+	bool killed = false;
+
 	/*
 	 * Require the device lock and set the "dead" flag to guarantee that
 	 * the update behavior is consistent with the other bitfields near
@@ -3898,10 +3913,13 @@ bool kill_device(struct device *dev)
 	 */
 	device_lock_assert(dev);
 
-	if (dev->p->dead)
-		return false;
-	dev->p->dead = true;
-	return true;
+	mutex_lock(&dev->p->driver_lock);
+	if (!dev->p->dead) {
+		dev->p->dead = true;
+		killed = true;
+	}
+	mutex_unlock(&dev->p->driver_lock);
+	return killed;
 }
 EXPORT_SYMBOL_GPL(kill_device);
 
drivers/base/dd.c +104 -13

189 lines not on this page · raw message

include/linux/device.h +2 -0
index 429e39f647cf9..5433b2609ab30 100644
@@ -1314,6 +1314,8 @@ static inline void *dev_get_platdata(const struct device *dev)
  */
 int __must_check device_driver_attach(const struct device_driver *drv,
 				      struct device *dev);
+int __must_check device_driver_attach_unrestricted(
+	const struct device_driver *drv, struct device *dev);
 int __must_check device_bind_driver(struct device *dev);
 void device_release_driver(struct device *dev);
 int  __must_check device_attach(struct device *dev);
Signature · 1 line
2.56.1
#18 lore raw

PATCH v4 17/33 Input: gameport - use the compatibility driver attachment API

In reply to Leon Romanovsky

From: Leon Romanovsky <[email protected]>

Manual gameport binding calls the driver's connect callback without the device lock, allowing it to race with generic sysfs probing. Normal probing would run CONFIG_DEBUG_TEST_DRIVER_REMOVE under gameport_mutex; a disconnect callback that unregisters a child port would then deadlock trying to acquire the same mutex.

Use device_driver_attach_unrestricted() to centralize binding and failure cleanup without the debug removal cycle. Take the device lock with device_trylock() to serialize attachment with generic probing. Return -EBUSY on contention because waiting while holding gameport_mutex could deadlock with probe cleanup that needs it.

---
 drivers/input/gameport/gameport.c | 22 +++++-----------------
 1 file changed, 5 insertions(+), 17 deletions(-)
drivers/input/gameport/gameport.c +5 -17
index 9707b155bc947..88b1a3464bf3e 100644
@@ -216,24 +216,12 @@ static int gameport_bind_driver(struct gameport *gameport, struct gameport_drive
 {
 	int error;
 
-	gameport->dev.driver = &drv->driver;
-	if (drv->connect(gameport, drv)) {
-		gameport->dev.driver = NULL;
-		return -ENODEV;
-	}
+	if (!device_trylock(&gameport->dev))
+		return -EBUSY;
 
-	error = device_bind_driver(&gameport->dev);
-	if (error) {
-		dev_warn(&gameport->dev,
-			 "device_bind_driver() failed for %s (%s) and %s, error: %d\n",
-			gameport->phys, gameport->name,
-			drv->description, error);
-		drv->disconnect(gameport);
-		gameport->dev.driver = NULL;
-		return error;
-	}
-
-	return 0;
+	error = device_driver_attach_unrestricted(&drv->driver, &gameport->dev);
+	device_unlock(&gameport->dev);
+	return error;
 }
 
 static void gameport_find_driver(struct gameport *gameport)
Signature · 1 line
2.56.1
#19 lore raw

PATCH v4 18/33 Input: serio - use the compatibility driver attachment API

In reply to Leon Romanovsky

From: Leon Romanovsky <[email protected]>

Manual serio binding holds serio_mutex, but generic sysfs probing does not take that mutex. The two paths can race while updating driver state or cleaning up a failed probe.

Use device_driver_attach_unrestricted() after the port ID check to centralize binding and cleanup. Acquire the device lock with device_trylock() to exclude generic probing, returning -EBUSY instead of waiting while holding serio_mutex. Map legacy -1 connect failures to -ENODEV in the probe callback so they are not reported as -EPERM, while preserving errors returned by the attachment helper.

---
 drivers/input/serio/serio.c | 29 ++++++++++-------------------
 1 file changed, 10 insertions(+), 19 deletions(-)
drivers/input/serio/serio.c +10 -19
index 54dd26249b027..f239217d7de45 100644
@@ -83,26 +83,15 @@ static int serio_bind_driver(struct serio *serio, struct serio_driver *drv)
 {
 	int error;
 
-	if (serio_match_port(drv->id_table, serio)) {
+	if (!serio_match_port(drv->id_table, serio))
+		return 0;
 
-		serio->dev.driver = &drv->driver;
-		if (serio_connect_driver(serio, drv)) {
-			serio->dev.driver = NULL;
-			return -ENODEV;
-		}
+	if (!device_trylock(&serio->dev))
+		return -EBUSY;
 
-		error = device_bind_driver(&serio->dev);
-		if (error) {
-			dev_warn(&serio->dev,
-				 "device_bind_driver() failed for %s (%s) and %s, error: %d\n",
-				 serio->phys, serio->name,
-				 drv->description, error);
-			serio_disconnect_driver(serio);
-			serio->dev.driver = NULL;
-			return error;
-		}
-	}
-	return 0;
+	error = device_driver_attach_unrestricted(&drv->driver, &serio->dev);
+	device_unlock(&serio->dev);
+	return error;
 }
 
 static void serio_find_driver(struct serio *serio)
@@ -744,8 +733,10 @@ static int serio_driver_probe(struct device *dev)
 {
 	struct serio *serio = to_serio_port(dev);
 	struct serio_driver *drv = to_serio_driver(dev->driver);
+	int error;
 
-	return serio_connect_driver(serio, drv);
+	error = serio_connect_driver(serio, drv);
+	return error == -1 ? -ENODEV : error;
 }
 
 static void serio_driver_remove(struct device *dev)
Signature · 1 line
2.56.1
#20 lore raw

PATCH v4 19/33 net: phy: Use the compatibility driver attachment API

In reply to Leon Romanovsky

From: Leon Romanovsky <[email protected]>

The generic PHY fallback probes directly before publishing its binding. Device trust admission needs to precede that probe without changing the caller's serialization, so use device_driver_attach_unrestricted() to serialize the generic attachment.

---
 drivers/net/phy/phy_device.c | 28 ++++++++++++++--------------
 1 file changed, 14 insertions(+), 14 deletions(-)
drivers/net/phy/phy_device.c +14 -14
index 5d4508bcfbe99..4f20b451e270d 100644
@@ -1857,7 +1857,6 @@ static void phy_detach_internal(struct phy_device *phydev, bool notify_bus)
 		/* The release below lets phy_probe() write this field. */
 		phydev->irq = phydev->mdio.bus->irq[phydev->mdio.addr];
 		device_release_driver(&phydev->mdio.dev);
-		phydev->is_genphy_driven = 0;
 	}
 
 	/* Assert the reset signal */
@@ -1912,6 +1911,8 @@ int phy_attach_direct(struct net_device *dev, struct phy_device *phydev,
 	struct device *d = &phydev->mdio.dev;
 	struct module *ndev_owner = NULL;
 	struct module *drv_owner;
+	struct device_driver *drv;
+	bool bind_genphy;
 	int irq = phydev->irq;
 	int err;
 
@@ -1939,16 +1940,16 @@ int phy_attach_direct(struct net_device *dev, struct phy_device *phydev,
 	/* Assume that if there is no driver, that it doesn't
 	 * exist, and we should use the genphy driver.
 	 */
-	if (!d->driver) {
+	drv = d->driver;
+	bind_genphy = !drv;
+	if (bind_genphy) {
 		if (phydev->is_c45)
-			d->driver = &genphy_c45_driver.mdiodrv.driver;
+			drv = &genphy_c45_driver.mdiodrv.driver;
 		else
-			d->driver = &genphy_driver.mdiodrv.driver;
-
-		phydev->is_genphy_driven = 1;
+			drv = &genphy_driver.mdiodrv.driver;
 	}
 
-	drv_owner = d->driver->owner;
+	drv_owner = drv->owner;
 	if (!try_module_get(drv_owner)) {
 		phydev_err(phydev, "failed to get the device driver module\n");
 		err = -EIO;
@@ -1956,11 +1957,8 @@ int phy_attach_direct(struct net_device *dev, struct phy_device *phydev,
 	}
 	phydev->drv_owner = drv_owner;
 
-	if (phydev->is_genphy_driven) {
-		err = d->driver->probe(d);
-		if (err >= 0)
-			err = device_bind_driver(d);
-
+	if (bind_genphy) {
+		err = device_driver_attach_unrestricted(drv, d);
 		if (err)
 			goto error_module_put;
 	}
@@ -2071,8 +2069,6 @@ int phy_attach_direct(struct net_device *dev, struct phy_device *phydev,
 	module_put(phydev->drv_owner);
 	phydev->drv_owner = NULL;
 	phydev->irq = irq;
-	phydev->is_genphy_driven = 0;
-	d->driver = NULL;
 error_put_device:
 	put_device(d);
 	if (ndev_owner != bus->owner)
@@ -3813,6 +3809,8 @@ static int phy_probe(struct device *dev)
 	int err = 0;
 
 	phydev->drv = phydrv;
+	phydev->is_genphy_driven = phydrv == &genphy_driver ||
+				 phydrv == &genphy_c45_driver;
 
 	/* Disable the interrupt if the PHY doesn't support it
 	 * but the interrupt is still a valid one
@@ -3949,6 +3947,7 @@ static int phy_probe(struct device *dev)
 out_reset:
 	/* Re-assert the reset signal on error */
 	phy_device_reset(phydev, 1);
+	phydev->is_genphy_driven = 0;
 
 	return err;
 }
@@ -3977,6 +3976,7 @@ static int phy_remove(struct device *dev)
 	phy_device_reset(phydev, 1);
 
 	phydev->drv = NULL;
+	phydev->is_genphy_driven = 0;
 
 	return 0;
 }
Signature · 1 line
2.56.1
#21 lore raw

PATCH v4 20/33 USB: Drain usbfs when a device is unregistered

In reply to Leon Romanovsky

From: Leon Romanovsky <[email protected]>

Only the generic USB device driver tells usbfs that a device is gone. A device without that driver bound, such as one unbound through sysfs, is unplugged without any notification. usbdev_open() does not check for a driver, so a process can open such a device and sleep in poll() on its idle descriptor. The unplug never wakes it or sends its disconnect signal.

Drain usbfs from usb_disconnect() before device_del(). The device is already marked as not attached, so no new user can open it. The later drain from the generic driver finds nothing left.

Fixes 782da727b0d59 ("usbcore: make usb_generic a usb_device_driver")
---
 drivers/usb/core/devio.c | 4 ++--
 drivers/usb/core/hub.c   | 3 +++
 drivers/usb/core/usb.h   | 1 +
 3 files changed, 6 insertions(+), 2 deletions(-)
drivers/usb/core/devio.c +2 -2
index 1491ba015bcd8..a881f06361bfa 100644
@@ -2862,7 +2862,7 @@ const struct file_operations usbdev_file_operations = {
 	.release =	  usbdev_release,
 };
 
-static void usbdev_remove(struct usb_device *udev)
+void usbfs_notify_remove(struct usb_device *udev)
 {
 	struct usb_dev_state *ps;
 
@@ -2889,7 +2889,7 @@ static int usbdev_notify(struct notifier_block *self,
 	case USB_DEVICE_ADD:
 		break;
 	case USB_DEVICE_REMOVE:
-		usbdev_remove(dev);
+		usbfs_notify_remove(dev);
 		break;
 	}
 	return NOTIFY_OK;
drivers/usb/core/hub.c +3 -0
index 199d3f535a891..372bd6368cc94 100644
@@ -2379,6 +2379,9 @@ void usb_disconnect(struct usb_device **pdev)
 	if (udev->usb4_link)
 		device_link_del(udev->usb4_link);
 
+	/* usbfs is otherwise notified only by a bound generic driver */
+	usbfs_notify_remove(udev);
+
 	/* Unregister the device.  The device driver is responsible
 	 * for de-configuring the device and invoking the remove-device
 	 * notifier chain (used by usbfs and possibly others).
drivers/usb/core/usb.h +1 -0
index 1b2de58fd6cef..cbee731837471 100644
@@ -195,6 +195,7 @@ extern const struct file_operations usbdev_file_operations;
 
 extern int usb_devio_init(void);
 extern void usb_devio_cleanup(void);
+void usbfs_notify_remove(struct usb_device *udev);
 
 /*
  * Firmware specific cookie identifying a port's location. '0' == no location
Signature · 1 line
2.56.1
#22 lore raw

PATCH v4 21/33 driver core: Introduce a generic device trust level

In reply to Leon Romanovsky

From: Leon Romanovsky <[email protected]>

Attestation needs to hold devices before driver probing and DMA setup. Authorization on individual buses does not provide a common policy that drivers and infrastructure can use.

Introduce a shared admission policy and operating trust level. Keep the accepted level fixed for the device's lifetime because unbind or failed setup does not necessarily undo hardware configuration. Retain active trust through teardown so cleanup uses the same assumptions as setup. Preserve existing behavior when no trust boot options are supplied.

---
 Documentation/admin-guide/kernel-parameters.txt |  14 ++
 drivers/base/Makefile                           |   2 +-
 drivers/base/base.h                             |  31 ++++
 drivers/base/core.c                             |   5 +-
 drivers/base/dd.c                               |  47 +++++-
 drivers/base/trust.c                            | 187 ++++++++++++++++++++++++
 drivers/usb/core/driver.c                       |   8 +
 drivers/usb/core/message.c                      |   5 +
 include/linux/device.h                          |   8 +
 include/linux/device/bus.h                      |  10 ++
 include/linux/device/trust.h                    |  49 +++++++
 11 files changed, 361 insertions(+), 5 deletions(-)
Documentation/admin-guide/kernel-parameters.txt +14 -0
index 0b3c140babd94..8a94482f0b19b 100644
@@ -1259,6 +1259,20 @@ Kernel parameters
 	dell_smm_hwmon.fan_max=
 			[HW] Maximum configurable fan speed.
 
+	device_trust	[KNL]
+			Enable device trust with blocked as the implicit default.
+
+	device_trust.default=
+			[KNL] Set initial trust policy for all devices, including
+			hotplugged devices.
+			Format: { default | blocked | adversarial | unrestricted }
+			No trust options selects legacy unrestricted mode, preserving
+			bus policy and existing authorization. Otherwise blocked is the
+			implicit default. An explicit value wins regardless of option
+			order. default preserves bus policy; other values replace it.
+			unrestricted disables runtime policy changes.
+			See Documentation/driver-api/driver-model/device-trust.rst.
+
 	dfltcc=		[HW,S390]
 			Format: { on | off | def_only | inf_only | always }
 			on:       s390 zlib hardware support for compression on
drivers/base/Makefile +1 -1
index 435710f643a5c..cb3bd5fa2287a 100644
@@ -3,7 +3,7 @@
 
 obj-y			:= component.o core.o bus.o dd.o syscore.o \
 			   driver.o class.o platform.o \
-			   cpu.o firmware.o init.o map.o devres.o \
+			   cpu.o firmware.o init.o map.o devres.o trust.o \
 			   attribute_container.o transport_class.o \
 			   topology.o container.o property.o cacheinfo.o \
 			   swnode.o faux.o
drivers/base/base.h +31 -0
index 61f49fc142f45..87e098790d099 100644
@@ -10,6 +10,7 @@
  * shared outside of the drivers/base/ directory.
  *
  */
+#include <linux/device/trust.h>
 #include <linux/notifier.h>
 
 /**
@@ -88,6 +89,27 @@ struct driver_private {
 };
 #define to_driver(obj) container_of(obj, struct driver_private, kobj)
 
+/**
+ * enum device_trust_state - Device trust authorization and commitment
+ * @DEVICE_TRUST_SELECTABLE: No authorization or commitment. When runtime
+ *	policy changes are enabled, any policy can be selected. Selecting
+ *	blocked enters %DEVICE_TRUST_WAITING.
+ * @DEVICE_TRUST_WAITING: Blocked policy without commitment. Runtime
+ *	authorization requires adversarial or unrestricted and enters
+ *	%DEVICE_TRUST_AUTHORIZED; selecting default is rejected.
+ * @DEVICE_TRUST_AUTHORIZED: Adversarial or unrestricted selected from
+ *	%DEVICE_TRUST_WAITING. Policy is fixed, but no operating level has
+ *	been committed.
+ * @DEVICE_TRUST_COMMITTED: Policy and operating level accepted before
+ *	driver setup. Both remain fixed through setup failure and unbind.
+ */
+enum device_trust_state {
+	DEVICE_TRUST_SELECTABLE,
+	DEVICE_TRUST_WAITING,
+	DEVICE_TRUST_AUTHORIZED,
+	DEVICE_TRUST_COMMITTED,
+};
+
 /**
  * struct device_private - structure to hold the private to the driver core
  *			   portions of the device structure.
@@ -106,6 +128,7 @@ struct driver_private {
  * @device: pointer back to the struct device that this structure is
  *	    associated with.
  * @driver_lock: serializes binding and removal, including compatibility attach
+ * @trust_state: policy admission state
  * @dead: This device is currently either in the process of or has been
  *	  removed from the system. Any asynchronous events scheduled for this
  *	  device should exit without taking any action.
@@ -124,6 +147,7 @@ struct device_private {
 	struct device *device;
 	/* Taken after the device mutex, except by compatibility attach. */
 	struct mutex driver_lock;
+	enum device_trust_state trust_state;
 	u8 dead:1;
 };
 #define to_device_private_parent(obj)	\
@@ -169,6 +193,13 @@ void bus_remove_driver(struct device_driver *drv);
 void device_release_driver_internal(struct device *dev, const struct device_driver *drv,
 				    struct device *parent);
 
+int device_private_init(struct device *dev);
+
+/* Unrestricted-only manual attachment uses the caller's subsystem serialization. */
+void device_trust_init_state(struct device *dev);
+int device_trust_prepare_unrestricted(struct device *dev,
+				      const struct device_driver *drv);
+
 void driver_detach(const struct device_driver *drv);
 void driver_deferred_probe_del(struct device *dev);
 void device_set_deferred_probe_reason(const struct device *dev, struct va_format *vaf);
drivers/base/core.c +4 -1
index 92d25bf4f8632..c0006b3aa38f7 100644
@@ -3613,7 +3613,7 @@ static void device_remove_sys_dev_entry(struct device *dev)
 	}
 }
 
-static int device_private_init(struct device *dev)
+int device_private_init(struct device *dev)
 {
 	dev->p = kzalloc_obj(*dev->p);
 	if (!dev->p)
@@ -3694,6 +3694,9 @@ int device_add(struct device *dev)
 	if (error)
 		goto name_error;
 
+	device_trust_init(dev);
+	device_trust_init_state(dev);
+
 	pr_debug("device: '%s': %s\n", dev_name(dev), __func__);
 
 	parent = get_device(dev->parent);
drivers/base/dd.c +44 -3

113 lines not on this page · raw message

drivers/base/trust.c new file +187 -0

187 lines not on this page · raw message

drivers/usb/core/driver.c +8 -0
index 9dd022c1ca151..1d488111a70fb 100644
@@ -582,6 +582,12 @@ int usb_driver_claim_interface(struct usb_driver *driver,
 		iface->claim_owner = driver->driver.owner;
 	}
 
+	retval = device_trust_prepare(dev, &driver->driver);
+	if (retval) {
+		usb_put_claim_owner(iface);
+		goto unlock;
+	}
+
 	dev->driver = &driver->driver;
 	usb_set_intfdata(iface, data);
 	iface->needs_binding = 0;
@@ -619,6 +625,7 @@ int usb_driver_claim_interface(struct usb_driver *driver,
 		if (driver->supports_autosuspend)
 			pm_runtime_disable(dev);
 		pm_runtime_set_suspended(dev);
+		device_trust_clear(dev);
 	}
 
 unlock:
@@ -634,6 +641,7 @@ static void usb_unbind_claim(struct usb_interface *iface)
 	usb_unbind_interface(dev);
 	dev_set_drvdata(dev, NULL);
 	dev->driver = NULL;
+	device_trust_clear(dev);
 	usb_put_claim_owner(iface);
 }
 
drivers/usb/core/message.c +5 -0
index e7a23e406f8a2..ca6976e266f02 100644
@@ -2237,6 +2237,8 @@ int usb_set_configuration(struct usb_device *dev, int configuration)
 		pm_runtime_no_callbacks(&intf->dev);
 		dev_set_name(&intf->dev, "%d-%s:%d.%d", dev->bus->busnum,
 				dev->devpath, configuration, ifnum);
+		/* A sibling may claim the interface before it is registered */
+		device_trust_init(&intf->dev);
 		/*
 		 * Make sure the interface does not outlive its parent (e.g.
 		 * as needed for usb_queue_reset_device() and
@@ -2319,6 +2321,9 @@ int usb_set_configuration(struct usb_device *dev, int configuration)
 			get_device(&intf->dev);
 			if (unconfigure)
 				usb_set_configuration(dev, -1);
+			device_lock(&intf->dev);
+			device_trust_clear(&intf->dev);
+			device_unlock(&intf->dev);
 			module_put(claim_owner);
 			put_device(&intf->dev);
 			if (unconfigure) {
include/linux/device.h +8 -0
index 5433b2609ab30..702eb66b81bf3 100644
@@ -30,6 +30,7 @@
 #include <linux/device/class.h>
 #include <linux/device/devres.h>
 #include <linux/device/driver.h>
+#include <linux/device/trust.h>
 #include <linux/cleanup.h>
 #include <asm/device.h>
 
@@ -695,6 +696,10 @@ enum struct_device_flags {
  * @removable:  Whether the device can be removed from the system. This
  *              should be set by the subsystem / bus driver that discovered
  *              the device.
+ * @trust_policy: Requested operating policy, resolved before driver probe.
+ * @trust_level: Active trust level through driver setup and cleanup, see
+ *		device_get_trust_level().
+ * @trust_committed_level: Operating level retained across bind transactions.
  * @flags:	DEV_FLAG_XXX flags. Use atomic bitfield operations to modify.
  *
  * At the lowest level, every device in a Linux system is represented by an
@@ -798,6 +803,9 @@ struct device {
 	struct device_physical_location *physical_location;
 
 	enum device_removable	removable;
+	enum device_trust_policy trust_policy;
+	enum device_trust_level trust_level;
+	enum device_trust_level trust_committed_level;
 
 	DECLARE_BITMAP(flags, DEV_FLAG_COUNT);
 };
include/linux/device/bus.h +10 -0
index 9ef7538a9a7f2..ba2b5743a47cd 100644
@@ -17,6 +17,7 @@
 #include <linux/kobject.h>
 #include <linux/klist.h>
 #include <linux/pm.h>
+#include <linux/device/trust.h>
 
 struct device_driver;
 struct fwnode_handle;
@@ -59,6 +60,11 @@ struct fwnode_handle;
  * @resume:	Called to bring a device on this bus out of sleep mode.
  * @num_vf:	Called to find out how many virtual functions a device on this
  *		bus supports.
+ * @trust_resolve: Resolve a requested trust policy to an active trust level
+ *		immediately before driver probe. The device lock is held and
+ *		@drv is the candidate driver, which dev->driver does not name
+ *		yet. Return 0 on success or a negative errno. This callback
+ *		must not enable the device.
  * @dma_configure:	Called to setup DMA configuration on a device on
  *			this bus.
  * @dma_cleanup:	Called to cleanup DMA configuration on a device on
@@ -102,6 +108,10 @@ struct bus_type {
 
 	int (*num_vf)(struct device *dev);
 
+	int (*trust_resolve)(struct device *dev,
+			     const struct device_driver *drv,
+			     enum device_trust_policy policy,
+			     enum device_trust_level *level);
 	int (*dma_configure)(struct device *dev);
 	void (*dma_cleanup)(struct device *dev);
 
include/linux/device/trust.h new file +49 -0

49 lines not on this page · raw message

Signature · 1 line
2.56.1
#23 lore raw

PATCH v4 22/33 driver core: Expose device trust authorization interfaces

In reply to Leon Romanovsky

From: Leon Romanovsky <[email protected]>

An initrd must be able to authorize a blocked device after attestation and distinguish that permission from a successful driver binding. Existing bus authorization interfaces also need a way to grant access without bypassing the common policy.

Expose policy and active trust through sysfs, with shared authorization rules for bus callers. Authorizing a blocked device fixes the choice for its lifetime, so a failed probe cannot reopen the decision. Require boot opt-in for the new writable interface to preserve legacy attachment assumptions.

---
 Documentation/ABI/testing/sysfs-devices-trust |  32 +++++++
 MAINTAINERS                                   |   1 +
 drivers/base/base.h                           |   2 +
 drivers/base/core.c                           |  15 ++-
 drivers/base/trust.c                          | 129 ++++++++++++++++++++++++++
 include/linux/device.h                        |   5 +
 include/linux/device/trust.h                  |   3 +
 7 files changed, 186 insertions(+), 1 deletion(-)
Documentation/ABI/testing/sysfs-devices-trust new file +32 -0
new file mode 100644
index 0000000000000..59b066c2846ba
@@ -0,0 +1,32 @@
+What:		/sys/devices/.../trust
+Date:		September 2026
+Contact:	[email protected]
+Description:
+		(RO) The active trust level for the device. The values are
+		"blocked", "adversarial", and "unrestricted". Driver core
+		resolves the level before driver setup and retains it through
+		DMA cleanup. It is "blocked" outside a binding transaction.
+
+What:		/sys/devices/.../trust_policy
+Date:		September 2026
+Contact:	[email protected]
+Description:
+		(RW) The requested trust policy for the device. The initial
+		value may be selected by the bus before the device is
+		registered; otherwise it is "default". The policy is resolved
+		to an active trust level before the device is probed.
+
+		Changes through this attribute require an explicit device
+		trust boot option. Any such option selects an implicit
+		blocked default; use device_trust.default=default to
+		enable them while preserving bus policy. Without one,
+		only writing the current policy succeeds. Existing bus
+		authorization interfaces remain available. Explicit unrestricted
+		policy disables runtime policy changes.
+
+		The values are "default", "blocked", "adversarial", and
+		"unrestricted". "default" lets the bus select the operating level.
+		"blocked" prevents driver binding. "adversarial" requests
+		classification as potentially malicious. "unrestricted" requests
+		normal operation. Adversarial protections depend on bus, DMA,
+		and driver support; classification alone adds none.
MAINTAINERS +1 -0
index b726344362b41..a145aaaca2ef3 100644
@@ -8150,6 +8150,7 @@ L:	[email protected]
 S:	Supported
 T:	git git://git.kernel.org/pub/scm/linux/kernel/git/driver-core/driver-core.git
 F:	Documentation/ABI/testing/sysfs-bus-drivers-probe
+F:	Documentation/ABI/testing/sysfs-devices-trust
 F:	Documentation/core-api/kobject.rst
 F:	Documentation/driver-api/driver-model/
 F:	drivers/base/
drivers/base/base.h +2 -0
index 87e098790d099..e51637ed37193 100644
@@ -195,6 +195,8 @@ void device_release_driver_internal(struct device *dev, const struct device_driv
 
 int device_private_init(struct device *dev);
 
+extern const struct attribute_group device_trust_attr_group;
+
 /* Unrestricted-only manual attachment uses the caller's subsystem serialization. */
 void device_trust_init_state(struct device *dev);
 int device_trust_prepare_unrestricted(struct device *dev,
drivers/base/core.c +14 -1
index c0006b3aa38f7..e72424618d622 100644
@@ -2999,10 +2999,14 @@ static int device_add_attrs(struct device *dev)
 	if (error)
 		goto err_remove_type_groups;
 
+	error = device_add_group(dev, &device_trust_attr_group);
+	if (error)
+		goto err_remove_dev_groups;
+
 	if (device_supports_offline(dev) && !dev_offline_disabled(dev)) {
 		error = device_create_file(dev, &dev_attr_online);
 		if (error)
-			goto err_remove_dev_groups;
+			goto err_remove_dev_trust_group;
 	}
 
 	if (fw_devlink_flags && !fw_devlink_is_permissive() && dev->fwnode) {
@@ -3032,6 +3036,8 @@ static int device_add_attrs(struct device *dev)
 	device_remove_file(dev, &dev_attr_waiting_for_supplier);
  err_remove_dev_online:
 	device_remove_file(dev, &dev_attr_online);
+ err_remove_dev_trust_group:
+	device_remove_group(dev, &device_trust_attr_group);
  err_remove_dev_groups:
 	device_remove_groups(dev, dev->groups);
  err_remove_type_groups:
@@ -3057,6 +3063,7 @@ static void device_remove_attrs(struct device *dev)
 	device_remove_file(dev, &dev_attr_removable);
 	device_remove_file(dev, &dev_attr_waiting_for_supplier);
 	device_remove_file(dev, &dev_attr_online);
+	device_remove_group(dev, &device_trust_attr_group);
 	device_remove_groups(dev, dev->groups);
 
 	if (type)
@@ -4809,6 +4816,12 @@ static int device_attrs_change_owner(struct device *dev, kuid_t kuid,
 	if (error)
 		return error;
 
+	/* Change the trust attributes of @dev to @kuid/@kgid. */
+	error = sysfs_group_change_owner(kobj, &device_trust_attr_group, kuid,
+					 kgid);
+	if (error)
+		return error;
+
 	if (device_supports_offline(dev) && !dev_offline_disabled(dev)) {
 		/* Change online device attributes of @dev to @kuid/@kgid. */
 		error = sysfs_file_change_owner(kobj, dev_attr_online.attr.name,
drivers/base/trust.c +129 -0

141 lines not on this page · raw message

include/linux/device.h +5 -0
index 702eb66b81bf3..2914b7191d342 100644
@@ -933,6 +933,11 @@ static inline bool device_iommu_mapped(struct device *dev)
 	return (dev->iommu_group != NULL);
 }
 
+static inline bool device_policy_is_blocked(const struct device *dev)
+{
+	return READ_ONCE(dev->trust_policy) == DEVICE_TRUST_POLICY_BLOCKED;
+}
+
 /* Get the wakeup routines, which depend on struct device */
 #include <linux/pm_wakeup.h>
 
include/linux/device/trust.h +3 -0
index ff80b7a079eb8..52fd9e7c4dd5b 100644
@@ -43,6 +43,9 @@ enum device_trust_policy {
 void device_trust_init(struct device *dev);
 int device_trust_prepare(struct device *dev, const struct device_driver *drv);
 void device_trust_clear(struct device *dev);
+int device_trust_set_policy_locked(struct device *dev,
+				   enum device_trust_policy policy);
+int device_trust_set_policy(struct device *dev, enum device_trust_policy policy);
 enum device_trust_level device_get_trust_level(const struct device *dev);
 bool device_is_adversarial(const struct device *dev);
 
Signature · 1 line
2.56.1
#24 lore raw

PATCH v4 23/33 driver core: Accept device trust policy on the kernel command line

In reply to Leon Romanovsky

From: Leon Romanovsky <[email protected]>

Blocking devices until initrd attestation also blocks the hardware needed to reach the initrd and perform that attestation. A global policy alone cannot allow those dependencies while keeping other devices blocked.

Allow boot policy exceptions for specific bus devices before probing, including devices discovered later. Keep unmatched devices blocked unless the administrator explicitly chooses another default. This makes the exceptions usable with built-in drivers and avoids depending on userspace winning a race against early probing.

---
 Documentation/ABI/testing/sysfs-devices-trust   |   2 +
 Documentation/admin-guide/kernel-parameters.txt |  14 ++-
 drivers/base/base.h                             |   8 ++
 drivers/base/trust.c                            | 116 +++++++++++++++++++++++-
 include/linux/device/trust.h                    |   1 +
 5 files changed, 134 insertions(+), 7 deletions(-)
Documentation/ABI/testing/sysfs-devices-trust +2 -0
index 59b066c2846ba..3bfc85b609a6d 100644
@@ -15,6 +15,8 @@ Description:
 		value may be selected by the bus before the device is
 		registered; otherwise it is "default". The policy is resolved
 		to an active trust level before the device is probed.
+		A matching device_trust= kernel command-line entry overrides
+		the initial requested policy before registration.
 
 		Changes through this attribute require an explicit device
 		trust boot option. Any such option selects an implicit
Documentation/admin-guide/kernel-parameters.txt +12 -2
index 8a94482f0b19b..63831dc40f796 100644
@@ -1262,9 +1262,19 @@ Kernel parameters
 	device_trust	[KNL]
 			Enable device trust with blocked as the implicit default.
 
+	device_trust=	[KNL]
+			Set initial device trust policy before probing, including
+			for devices added after boot.
+			Format: <bus>:<device>=<policy>[,...]
+			Names match exactly as in /sys/bus/<bus>/devices/<device>.
+			Policies are default, blocked, adversarial, and
+			unrestricted.
+			Entries override bus policy and device_trust.default.
+			See Documentation/driver-api/driver-model/device-trust.rst.
+
 	device_trust.default=
-			[KNL] Set initial trust policy for all devices, including
-			hotplugged devices.
+			[KNL] Set initial trust policy for devices without a
+			matching device_trust= entry, including hotplugged devices.
 			Format: { default | blocked | adversarial | unrestricted }
 			No trust options selects legacy unrestricted mode, preserving
 			bus policy and existing authorization. Otherwise blocked is the
drivers/base/base.h +8 -0
index e51637ed37193..761d52f4c9caf 100644
@@ -197,6 +197,14 @@ int device_private_init(struct device *dev);
 
 extern const struct attribute_group device_trust_attr_group;
 
+#if IS_ENABLED(CONFIG_KUNIT)
+int device_trust_parse_cmdline(const char *options, const struct device *dev,
+			       enum device_trust_policy *policy);
+void device_trust_apply_boot_policy(struct device *dev,
+				    enum device_trust_policy policy,
+				    const char *options);
+#endif
+
 /* Unrestricted-only manual attachment uses the caller's subsystem serialization. */
 void device_trust_init_state(struct device *dev);
 int device_trust_prepare_unrestricted(struct device *dev,
drivers/base/trust.c +111 -5

151 lines not on this page · raw message

include/linux/device/trust.h +1 -0
index 52fd9e7c4dd5b..a3a583eeb484c 100644
@@ -40,6 +40,7 @@ enum device_trust_policy {
 	DEVICE_TRUST_POLICY_UNRESTRICTED,
 };
 
+bool device_trust_enabled(void);
 void device_trust_init(struct device *dev);
 int device_trust_prepare(struct device *dev, const struct device_driver *drv);
 void device_trust_clear(struct device *dev);
Signature · 1 line
2.56.1
#25 lore raw

PATCH v4 24/33 driver core: Accept device trust policy by driver name

In reply to Leon Romanovsky

From: Leon Romanovsky <[email protected]>

Device names can depend on enumeration order, making device-specific boot exceptions difficult to reuse across machines. Userspace is also too late to establish policy for drivers that probe during boot.

Allow exceptions selected by bus and driver name, using the names published in sysfs so policy does not depend on module aliases. Preserve more specific device rules and prior authorization. Keep a matched rule fixed across retries so changing the candidate driver cannot replace that choice.

---
 Documentation/ABI/testing/sysfs-devices-trust   |  7 +-
 Documentation/admin-guide/kernel-parameters.txt | 15 ++++-
 drivers/base/base.h                             |  8 +++
 drivers/base/trust.c                            | 88 ++++++++++++++++++++++---
 4 files changed, 107 insertions(+), 11 deletions(-)
Documentation/ABI/testing/sysfs-devices-trust +5 -2
index 3bfc85b609a6d..3d72f0268105e 100644
@@ -15,8 +15,11 @@ Description:
 		value may be selected by the bus before the device is
 		registered; otherwise it is "default". The policy is resolved
 		to an active trust level before the device is probed.
-		A matching device_trust= kernel command-line entry overrides
-		the initial requested policy before registration.
+		A non-default device_trust.default= kernel command-line value
+		replaces the bus policy before registration. A matching
+		device_trust= entry takes precedence over both, regardless
+		of command-line order. Boot policy also applies to new devices
+		discovered after boot.
 
 		Changes through this attribute require an explicit device
 		trust boot option. Any such option selects an implicit
Documentation/admin-guide/kernel-parameters.txt +14 -1
index 63831dc40f796..8a33b7010f91a 100644
@@ -1269,12 +1269,15 @@ Kernel parameters
 			Names match exactly as in /sys/bus/<bus>/devices/<device>.
 			Policies are default, blocked, adversarial, and
 			unrestricted.
-			Entries override bus policy and device_trust.default.
+			Entries override bus policy, device_trust.default, and
+			device_trust.driver.
 			See Documentation/driver-api/driver-model/device-trust.rst.
 
 	device_trust.default=
 			[KNL] Set initial trust policy for devices without a
 			matching device_trust= entry, including hotplugged devices.
+			A matching device_trust.driver= rule can replace this
+			initial policy at the first binding attempt.
 			Format: { default | blocked | adversarial | unrestricted }
 			No trust options selects legacy unrestricted mode, preserving
 			bus policy and existing authorization. Otherwise blocked is the
@@ -1283,6 +1286,16 @@ Kernel parameters
 			unrestricted disables runtime policy changes.
 			See Documentation/driver-api/driver-model/device-trust.rst.
 
+	device_trust.driver=
+			[KNL] Set initial device trust policy by driver name,
+			including for drivers built into the kernel.
+			Format: <bus>:<driver>=<policy>[,...]
+			Names match exactly as in /sys/bus/<bus>/drivers/<driver>.
+			Quote the option value for driver names containing spaces.
+			Policies are default, blocked, adversarial, and
+			unrestricted.
+			Rules remain available for hotplug and modules.
+
 	dfltcc=		[HW,S390]
 			Format: { on | off | def_only | inf_only | always }
 			on:       s390 zlib hardware support for compression on
drivers/base/base.h +8 -0
index 761d52f4c9caf..f6f65046fa206 100644
@@ -129,6 +129,7 @@ enum device_trust_state {
  *	    associated with.
  * @driver_lock: serializes binding and removal, including compatibility attach
  * @trust_state: policy admission state
+ * @trust_policy_override: explicit policy prevents deferred driver boot policy
  * @dead: This device is currently either in the process of or has been
  *	  removed from the system. Any asynchronous events scheduled for this
  *	  device should exit without taking any action.
@@ -148,6 +149,7 @@ struct device_private {
 	/* Taken after the device mutex, except by compatibility attach. */
 	struct mutex driver_lock;
 	enum device_trust_state trust_state;
+	u8 trust_policy_override:1;
 	u8 dead:1;
 };
 #define to_device_private_parent(obj)	\
@@ -200,6 +202,12 @@ extern const struct attribute_group device_trust_attr_group;
 #if IS_ENABLED(CONFIG_KUNIT)
 int device_trust_parse_cmdline(const char *options, const struct device *dev,
 			       enum device_trust_policy *policy);
+int device_trust_parse_driver_cmdline(const char *options,
+				      const struct device_driver *drv,
+				      enum device_trust_policy *policy);
+void device_trust_apply_driver_policy(struct device *dev,
+				      const struct device_driver *drv,
+				      const char *options);
 void device_trust_apply_boot_policy(struct device *dev,
 				    enum device_trust_policy policy,
 				    const char *options);
drivers/base/trust.c +80 -8

155 lines not on this page · raw message

Signature · 1 line
2.56.1
#26 lore raw

PATCH v4 25/33 driver core: Expose committed device trust level

In reply to Leon Romanovsky

From: Leon Romanovsky <[email protected]>

After probe failure or unbind, active trust returns to blocked while the accepted operating level remains committed. IOMMU state and other infrastructure can outlive the driver, so active trust alone cannot tell them which operating level was accepted.

Expose the retained commitment separately. This lets infrastructure honor the original level after probe failure or unbind without mistaking inactive driver state for a new authorization opportunity.

---
 drivers/base/trust.c         | 13 +++++++++++++
 include/linux/device/trust.h |  1 +
 2 files changed, 14 insertions(+)
drivers/base/trust.c +13 -0
index b968bfc937346..ddd570773a070 100644
@@ -155,6 +155,19 @@ enum device_trust_level device_get_trust_level(const struct device *dev)
 }
 EXPORT_SYMBOL_GPL(device_get_trust_level);
 
+/**
+ * device_get_committed_trust_level - Return the lifetime trust commitment
+ * @dev: device to inspect
+ *
+ * Return: %DEVICE_TRUST_BLOCKED before admission, otherwise the level fixed
+ * before driver setup. The commitment survives setup failure and unbind.
+ */
+enum device_trust_level device_get_committed_trust_level(const struct device *dev)
+{
+	return READ_ONCE(dev->trust_committed_level);
+}
+EXPORT_SYMBOL_GPL(device_get_committed_trust_level);
+
 /**
  * device_is_adversarial - Test whether a device is operated as an adversary
  * @dev: device to inspect
include/linux/device/trust.h +1 -0
index a3a583eeb484c..1ac9cb5b3ceb3 100644
@@ -48,6 +48,7 @@ int device_trust_set_policy_locked(struct device *dev,
 				   enum device_trust_policy policy);
 int device_trust_set_policy(struct device *dev, enum device_trust_policy policy);
 enum device_trust_level device_get_trust_level(const struct device *dev);
+enum device_trust_level device_get_committed_trust_level(const struct device *dev);
 bool device_is_adversarial(const struct device *dev);
 
 #endif /* _DEVICE_TRUST_H_ */
Signature · 1 line
2.56.1
#27 lore raw

PATCH v4 26/33 driver core: Cover trust authorization and binding with KUnit

In reply to Leon Romanovsky

From: Leon Romanovsky <[email protected]>

Authorization, committed trust and active trust change at different points in a device's lifetime. Confusing them can reopen authorization after a failed probe or let cleanup erase another binding's state. Manual attachment also uses different locks from normal probing.

Add KUnit coverage for these boundaries and for boot policy precedence. Use controlled overlap to check binding serialization, since sequential operations cannot reveal interference between attachment and removal. Isolate policy changes from external sysfs writes so unrelated userspace activity cannot alter the expected result.

---
 drivers/base/test/Makefile            |    1 +
 drivers/base/test/device-trust-test.c | 2487 +++++++++++++++++++++++++++++++++
 drivers/base/trust.c                  |    2 +
 3 files changed, 2490 insertions(+)
drivers/base/test/Makefile +1 -0
index 9ced7bbd569fc..dfff5e1d83f7c 100644
@@ -3,6 +3,7 @@ obj-$(CONFIG_TEST_ASYNC_DRIVER_PROBE)	+= test_async_driver_probe.o
 
 obj-$(CONFIG_DM_KUNIT_TEST)	+= root-device-test.o
 obj-$(CONFIG_DM_KUNIT_TEST)	+= platform-device-test.o
+obj-$(CONFIG_DM_KUNIT_TEST)	+= device-trust-test.o
 
 obj-$(CONFIG_DRIVER_PE_KUNIT_TEST) += property-entry-test.o
 CFLAGS_property-entry-test.o += $(DISABLE_STRUCTLEAK_PLUGIN)
drivers/base/test/device-trust-test.c new file +2487 -0

2,487 lines not on this page · raw message

drivers/base/trust.c +2 -0
index ddd570773a070..4f940589eb158 100644
@@ -56,6 +56,7 @@ void device_trust_init_state(struct device *dev)
 		dev->p->trust_state = dev->trust_policy == DEVICE_TRUST_POLICY_BLOCKED ?
 			DEVICE_TRUST_WAITING : DEVICE_TRUST_SELECTABLE;
 }
+EXPORT_SYMBOL_IF_KUNIT(device_trust_init_state);
 
 static int __device_trust_prepare(struct device *dev,
 				  const struct device_driver *drv, bool unrestricted_only)
@@ -316,6 +317,7 @@ static struct attribute *device_trust_attrs[] = {
 const struct attribute_group device_trust_attr_group = {
 	.attrs = device_trust_attrs,
 };
+EXPORT_SYMBOL_IF_KUNIT(device_trust_attr_group);
 
 static const char *device_trust_cmdline __ro_after_init;
 static const char *device_trust_driver_cmdline __ro_after_init;
Signature · 1 line
2.56.1
#28 lore raw

PATCH v4 27/33 driver core: Document trust admission and initrd authorization

In reply to Leon Romanovsky

From: Leon Romanovsky <[email protected]>

Allowing a driver to bind does not establish device identity or prevent DMA initiated by the hardware. An initrd that treats those as equivalent could authorize a device before attestation or containment is ready.

Document the authorization workflow and the division of responsibility between userspace, driver core and bus infrastructure. Explain which decisions survive probe failure and unbind, and when queued probes may start, so policy agents can prepare the device before granting access.

---
 .../driver-api/driver-model/device-trust.rst       | 323 +++++++++++++++++++++
 Documentation/driver-api/driver-model/index.rst    |   1 +
 2 files changed, 324 insertions(+)
Documentation/driver-api/driver-model/device-trust.rst new file +323 -0
new file mode 100644
index 0000000000000..b93426b58852d
@@ -0,0 +1,323 @@
+.. SPDX-License-Identifier: GPL-2.0
+
+============
+Device trust
+============
+
+Device trust controls how the kernel uses a device. It does not verify the
+device's identity or firmware. Driver core tracks the requested policy,
+permission to bind, and active trust level separately.
+
+Policy and active trust
+=======================
+
+The writable ``trust_policy`` attribute accepts ``default``, ``blocked``,
+``adversarial``, or ``unrestricted``. The bus may set the initial policy;
+otherwise it starts as ``default``. Boot options can override it for all
+devices, a named driver, or an individual device. See `Boot policy`_ for
+precedence.
+
+The read-only ``trust`` attribute reports the active trust level:
+
+``DEVICE_TRUST_BLOCKED`` (``blocked``)
+  There is no active driver setup or binding. The requested policy decides
+  whether a later bind is allowed.
+
+``DEVICE_TRUST_ADVERSARIAL`` (``adversarial``)
+  The device is classified as potentially malicious. Protections depend
+  on bus, DMA, and driver support; classification alone adds none.
+
+``DEVICE_TRUST_UNRESTRICTED`` (``unrestricted``)
+  The device uses the normal privileges allowed by the bus and DMA policy.
+
+Policy resolution
+=================
+
+A bus can implement ``bus_type::trust_resolve`` to choose the active level
+from the device, candidate driver, and requested policy. For ``default``,
+it may use topology or firmware information. Other policies must resolve
+to the matching level or fail.
+
+The callback must not enable the device or grant DMA access. Those steps
+belong in setup callbacks, after resolution and before probe.
+
+Without this callback, ``default`` and ``unrestricted`` resolve to
+``DEVICE_TRUST_UNRESTRICTED``, and ``adversarial`` to
+``DEVICE_TRUST_ADVERSARIAL``. Explicit ``blocked`` blocks binding.
+Enforcement is provided separately by bus, DMA, and driver code.
+
+Admission and policy writes
+===========================
+
+Authorization is userspace's choice of adversarial or unrestricted for a blocked
+device. Commitment happens when the kernel accepts a policy and operating
+level, before starting driver setup. Both limit later policy changes.
+
+Without device trust boot options, legacy unrestricted mode preserves bus
+defaults and existing bus authorization. Buses can use
+``device_trust_enabled()`` to distinguish this mode from boot opt-in.
+Changes through ``trust_policy`` are disabled. An explicit
+``device_trust.default=default`` enables them while preserving bus
+defaults; device and driver boot rules also opt in.
+
+With ``device_trust.default=unrestricted``, runtime policy changes are
+unavailable for every device, including devices with a boot policy
+exception. Writing a different policy returns ``-EBUSY``. Writing the
+current policy succeeds without changing state or suppressing a pending
+driver boot rule. Boot device and driver rules retain their precedence.
+
+When enabled, runtime policy writes follow the internal states
+below; these are not additional sysfs values.
+``P`` is the requested policy and ``L`` is the committed operating level.
+
+.. list-table:: Admission states
+   :header-rows: 1
+   :widths: 25 40 35
+
+   * - State
+     - Meaning
+     - Policy writes
+   * - SELECTABLE
+     - The device has not been authorized or committed.
+     - Any policy is allowed. Selecting blocked enters WAITING.
+   * - WAITING
+     - Policy is blocked - no operating level is committed.
+     - Choose adversarial or unrestricted to enter AUTHORIZED(P).
+   * - AUTHORIZED(P)
+     - Userspace has chosen adversarial or unrestricted from WAITING.
+     - The policy cannot change, even before setup begins.
+   * - COMMITTED(P, L)
+     - The kernel has accepted P and L for setup.
+     - Neither the policy nor the operating level can change.
+
+Bus defaults and boot options set the initial state: blocked starts in
+WAITING; other policies start in SELECTABLE. Driver boot rules apply later,
+when a matching driver attempts to bind. They may still replace this
+initial state, including WAITING, unless a per-device boot entry or a
+successful policy write takes precedence.
+
+Userspace cannot move WAITING back to SELECTABLE by writing ``default``.
+Choosing adversarial or unrestricted from WAITING locks that policy immediately.
+
+After boot initialization, the state transitions are::
+
+  SELECTABLE ----select blocked----> WAITING
+      |                                 |
+      |                             authorize
+      |                      adversarial/unrestricted
+      |                                 |
+      |                                 v
+      |                            AUTHORIZED(P)
+      |                                 |
+      +------ permitted resolution -----+
+                       |
+                       v
+                 COMMITTED(P, L)
+
+Binding and device lifetime
+============================
+
+A manual bind that reaches WAITING returns ``-EPERM`` before driver or DMA
+setup. Automatic matching skips the rejected driver and tries the next
+candidate. Rejected attempts leave the device waiting for authorization
+through an enabled policy interface.
+
+Active trust stays at L through DMA setup, probe, operation, removal, and
+``bus_type::dma_cleanup``. It returns to blocked only after cleanup ends.
+
+The state lasts for the device object's lifetime, including the switch
+from initrd to the root filesystem. Unbinding and rebinding a registered
+device does not reset it. A removed device cannot be registered again; a
+new object starts with bus and boot policy.
+
+Bus code that operates a device before ``device_add()`` must call
+``device_trust_prepare(dev, drv)`` with the device lock held before driver
+setup. Registration preserves the admitted policy and commitment. After
+setup fails or the claimant stops using the device, call
+``device_trust_clear()`` under the same lock to clear active trust while
+retaining the commitment.
+
+Compatibility attachment
+========================
+
+This compatibility API **must not be used in any new code**. Its
+unrestricted-only restriction prevents devices from using the device trust
+authorization infrastructure. New code must use ``device_driver_attach()``.
+
+``device_driver_attach_unrestricted()`` supports manual attachment with the
+caller's existing subsystem serialization. It requires a policy that
+resolves to unrestricted and either no device trust boot options or an
+explicit ``device_trust.default=unrestricted``. Other configurations return
+``-EPERM`` before calling the driver. The legacy case preserves bus
+defaults. Buses implementing ``trust_resolve`` must use
+``device_driver_attach()``.
+
+Per-device boot exceptions still apply: blocked and adversarial reject
+attachment. If a ``device_trust.driver=`` list is configured, the device
+must also have an explicit ``device_trust=`` entry; otherwise this API
+returns ``-EPERM``. That entry prevents a concurrent driver rule from
+changing the policy.
+
+The caller provides the subsystem's existing manual-binding serialization
+and excludes bus-specific policy changes. Binding and removal are
+serialized separately; an overlapping transaction returns ``-EBUSY``.
+Holding the device lock alone does not prevent attachment. The API takes
+neither the device nor parent lock, commits unrestricted before the probe
+callback, and publishes the binding after probe succeeds. It does not
+perform normal driver-core DMA, pinctrl, or power-domain setup. A failed
+probe or binding clears active trust but retains the unrestricted
+commitment.
+
+Boot policy
+===========
+
+Built-in drivers can probe before userspace starts. Use boot options to
+set their initial policy. All three options accept default, blocked,
+adversarial, and unrestricted.
+
+Any option in the ``device_trust`` namespace selects blocked as the
+implicit default, including missing values and unrecognized options.
+The bare ``device_trust`` option enables this default without device entries.
+``device_trust.default=`` overrides this default regardless of option
+order; the last valid value wins. Explicit default preserves bus policy.
+Other values replace bus policy, including topology and removability
+defaults.
+
+``device_trust=`` sets policy for individual devices using a comma-separated
+list of ``<bus>:<device>=<policy>`` entries. Names must match
+``/sys/bus/<bus>/devices/<device>`` exactly. The first colon separates the
+bus name; later colons are part of the device name. Names cannot contain
+whitespace, control characters, commas, equals signs, or double quotes.
+Wildcards are not supported.
+
+A device entry overrides driver rules, the global setting, and bus policy,
+regardless of option order. Explicit default asks the bus or generic
+resolver to choose a level, even if the global setting is blocked. The
+last entry for a device wins. If the option is repeated, the last valid
+list replaces all earlier lists. A malformed list is ignored in full,
+with a warning.
+
+``device_trust.driver=`` sets policy by driver name using a comma-separated
+list of ``<bus>:<driver>=<policy>`` entries. Use exact names from
+``/sys/bus/<bus>/drivers/<driver>``, not module names or aliases. Driver
+names may contain spaces; quote the option when they do. Other name
+restrictions and list handling are the same as for device entries. The two
+lists are independent. Driver rules cover built-in drivers, modules, and
+hotplug.
+
+The first bind attempt with a matching driver rule applies it before
+resolution and setup. It overrides bus and global defaults, including
+global blocked. It cannot override a per-device entry or an existing
+authorization or commitment. A successful sysfs policy write also takes
+precedence, except for a no-op write with
+``device_trust.default=unrestricted``. The rule applies only once per
+device object, even if resolution or setup fails.
+
+After a blocked driver rule applies, rejected probes and driver changes
+leave the device in WAITING. Userspace can authorize it unless the global
+mode is unrestricted. A driver without a matching rule follows the device's
+current policy.
+
+An initrd can hold devices with ``device_trust.default=blocked`` and use
+boot exceptions for devices and suppliers needed to reach the initrd and
+perform attestation. These exceptions allow operation before fresh initrd
+attestation. Devices without an exception stay blocked even if their bus
+would normally choose adversarial or unrestricted.
+
+Global and per-device rules apply before device registration. Buses that
+need policy earlier call ``device_trust_init()`` after setting the bus,
+name, and initial policy. Driver rules apply later, when a candidate driver
+is known.
+
+All boot rules remain available for newly discovered devices. Initialize
+boot policy before device registration. These options are not runtime
+controls or proof of hardware identity. Blocked blocks early binding and,
+outside global unrestricted mode, allows later authorization. Adversarial and
+unrestricted permit early binding without fresh initrd attestation.
+
+DMA containment
+===============
+
+Blocked blocks driver binding, not DMA that hardware starts on its own.
+The bus and IOMMU must provide containment while a device waits for
+authorization.
+
+Adversarial policy does not require an IOMMU. Without an IOMMU group, or
+with IOMMU support compiled out, binding uses the platform's normal DMA
+configuration. Adversarial policy alone does not provide DMA isolation.
+
+Device trust admission does not change DMA handling, IOMMU domain selection,
+or ATS permission according to active trust. Those remain governed by existing
+bus and platform mechanisms. Integrating them with admission is separate
+work. A setup failure after commitment leaves the chosen mode fixed; it
+cannot fall back to unrestricted.
+
+Drivers that manage DMA themselves must provide their own containment.
+Drivers that do not use DMA need no domain.
+
+Initrd attestation sequence
+===========================
+
+Drivers with init-only probe callbacks cannot retry a binding held by
+blocked policy. They need a boot exception or a persistent probe callback.
+
+For a device that uses normal driver attachment:
+
+1. Boot with ``device_trust.default=blocked`` to hold all devices. To
+   hold selected devices, use ``device_trust.default=default`` with
+   per-device blocked rules. Add exceptions needed to reach the initrd
+   and provide DMA containment while waiting. Blocked attempts remain
+   in WAITING, including attempts by built-in drivers.
+
+2. In the initrd, control probing and attest the current device through a
+   transport that works without its functional driver. Keep policy blocked
+   during verification and preparation. Leave it blocked if verification
+   fails or is unavailable. Removal or replacement invalidates the result;
+   a reused bus address is not proof of identity. Repeat attestation if a
+   reset or preparation step invalidates the evidence.
+
+3. Once all checks and preparation are complete, write adversarial or
+   unrestricted to ``trust_policy``. This locks the choice and allows
+   binding.
+
+4. Request binding through ``drivers_probe`` or another attach path. The
+   kernel commits the operating level before setup. Retries keep the same
+   policy and level. Retry if the interface reports ``-EAGAIN``. A scan
+   can skip rejected candidates without returning an error, and a
+   successful ``drivers_probe`` write need not wait for a concurrent probe.
+
+The ``driver`` link appears before probe completes. To observe successful
+binding, start monitoring ``bind`` uevents before authorization and
+correlate them with the current device lifetime, or use a successful
+synchronous per-driver bind operation. Link visibility alone is not a
+completion signal.
+
+Queued or concurrent probes may start as soon as step 3 completes, before
+step 4. Evidence must still be valid when authorizing the device.
+Boot exceptions that permit adversarial or unrestricted allow early operation
+without fresh initrd attestation.
+
+The kernel interface provides neither an attestation transport nor a verifier.
+
+Driver use and independent properties
+=====================================
+
+Drivers read active trust with ``device_get_trust_level()`` or
+``device_is_adversarial()``. They may cache it while bound, but must not
+change requested policy or treat trust as proof of other security
+properties. Use the adversarial check for paths that bypass the DMA API.
+General DMA containment belongs in bus and IOMMU code.
+
+Code that needs the level fixed for the device's lifetime can use
+``device_get_committed_trust_level()``. It returns blocked before
+commitment and the fixed level afterwards, including after failed setup
+or unbind. It does not permit operation while unbound.
+
+Trust does not describe transport protection, encryption, verified
+identity, memory privacy, or DMA addressability. Keep these properties
+independent of the requested policy and active trust level.
+
+Policy writes cannot revoke authorization or switch an operating device
+between adversarial and unrestricted. Stopping it requires a separate
+procedure to quiesce the driver, tear down DMA, and contain the device on
+its bus.
Documentation/driver-api/driver-model/index.rst +1 -0
index abeb4b36636b6..af547cd13b2c4 100644
@@ -9,6 +9,7 @@ Driver Model
    bus
    design-patterns
    device
+   device-trust
    devres
    driver
    overview
Signature · 1 line
2.56.1
#29 lore raw

PATCH v4 28/33 PCI: Use device trust for platform restrictions

In reply to Leon Romanovsky

From: Leon Romanovsky <[email protected]>

PCI topology already identifies devices that need restricted operation. Generic trust policy must inherit that classification so authorization and PCI restrictions use the same policy.

Resolve discovery-time restrictions from the requested policy, since active trust is established only before driver setup. Retain the untrusted flag for IOMMU consumers until their conversion. The initial target is confidential computing guests without an IOMMU; synchronizing later authorization with IOMMU domains and ATS remains follow-up work.

---
 .../driver-api/driver-model/device-trust.rst          | 10 +++++-----
 drivers/pci/ats.c                                     |  4 ++--
 drivers/pci/pci.c                                     |  5 +++--
 drivers/pci/probe.c                                   | 19 +++++++++----------
 drivers/pci/quirks.c                                  |  7 ++++---
 include/linux/device.h                                |  5 +++++
 include/linux/pci.h                                   | 10 ++++++++++
 7 files changed, 38 insertions(+), 22 deletions(-)
Documentation/driver-api/driver-model/device-trust.rst +5 -5
index b93426b58852d..3c6babdba80e9 100644
@@ -246,11 +246,11 @@ Adversarial policy does not require an IOMMU. Without an IOMMU group, or
 with IOMMU support compiled out, binding uses the platform's normal DMA
 configuration. Adversarial policy alone does not provide DMA isolation.
 
-Device trust admission does not change DMA handling, IOMMU domain selection,
-or ATS permission according to active trust. Those remain governed by existing
-bus and platform mechanisms. Integrating them with admission is separate
-work. A setup failure after commitment leaves the chosen mode fixed; it
-cannot fall back to unrestricted.
+The initial target is confidential computing guests without an IOMMU.
+On systems with an IOMMU, policy changes after discovery are not yet
+synchronized with domain selection or ATS configuration. That integration
+is follow-up work. A setup failure after commitment leaves the chosen mode
+fixed; it cannot fall back to unrestricted.
 
 Drivers that manage DMA themselves must provide their own containment.
 Drivers that do not use DMA need no domain.
drivers/pci/ats.c +2 -2
index 9cb23780093dd..c8c96acc26343 100644
@@ -21,7 +21,7 @@ void pci_ats_init(struct pci_dev *dev)
 {
 	int pos;
 
-	if (pci_ats_disabled())
+	if (pci_ats_disabled() || pci_dev_default_is_restricted(dev))
 		return;
 
 	pos = pci_find_ext_capability(dev, PCI_EXT_CAP_ID_ATS);
@@ -40,7 +40,7 @@ void pci_ats_init(struct pci_dev *dev)
  */
 bool pci_ats_supported(struct pci_dev *dev)
 {
-	if (!dev->ats_cap || dev->untrusted)
+	if (!dev->ats_cap)
 		return false;
 
 	if (dev->is_virtfn)
drivers/pci/pci.c +3 -2
index 7c6f2aba81443..a60701bdece4c 100644
@@ -1016,8 +1016,9 @@ static void pci_std_enable_acs(struct pci_dev *dev, struct pci_acs *caps)
 	/* Upstream Forwarding */
 	caps->ctrl |= (dev->acs_capabilities & PCI_ACS_UF);
 
-	/* Enable Translation Blocking for external devices and noats */
-	if (pci_ats_disabled() || dev->external_facing || dev->untrusted)
+	/* Enable Translation Blocking when ATS is unavailable or restricted. */
+	if (pci_ats_disabled() || dev->external_facing ||
+	    pci_dev_default_is_restricted(dev))
 		caps->ctrl |= (dev->acs_capabilities & PCI_ACS_TB);
 }
 
drivers/pci/probe.c +9 -10
index 9a178e0e5f7f4..606ab8a3aa8ed 100644
@@ -1738,24 +1738,21 @@ static void set_pcie_cxl(struct pci_dev *dev)
 
 }
 
-static void set_pcie_untrusted(struct pci_dev *dev)
+static void pci_set_default_trust_policy(struct pci_dev *dev)
 {
 	struct pci_dev *parent = pci_upstream_bridge(dev);
 
 	if (!parent)
 		return;
-	/*
-	 * If the upstream bridge is untrusted we treat this device as
-	 * untrusted as well.
-	 */
-	if (parent->untrusted) {
-		dev->untrusted = true;
+
+	if (device_policy_is_adversarial(&parent->dev)) {
+		dev->dev.trust_policy = DEVICE_TRUST_POLICY_ADVERSARIAL;
 		return;
 	}
 
 	if (arch_pci_dev_is_removable(dev)) {
-		pci_dbg(dev, "marking as untrusted\n");
-		dev->untrusted = true;
+		pci_dbg(dev, "setting adversarial trust policy\n");
+		dev->dev.trust_policy = DEVICE_TRUST_POLICY_ADVERSARIAL;
 	}
 }
 
@@ -2082,7 +2079,9 @@ int pci_setup_device(struct pci_dev *dev)
 
 	set_pcie_cxl(dev);
 
-	set_pcie_untrusted(dev);
+	pci_set_default_trust_policy(dev);
+	dev->untrusted = device_policy_is_adversarial(&dev->dev);
+	device_trust_init(&dev->dev);
 
 	/* "Unknown power state" */
 	dev->current_state = PCI_UNKNOWN;
drivers/pci/quirks.c +4 -3
index 7f1f47ea2ee41..1afad28d1b5e0 100644
@@ -5525,8 +5525,8 @@ static void pci_quirk_enable_intel_rp_mpc_acs(struct pci_dev *dev)
  * Currently this quirk does the equivalent of
  * PCI_ACS_SV | PCI_ACS_RR | PCI_ACS_CR | PCI_ACS_UF
  *
- * TODO: This quirk also needs to do equivalent of PCI_ACS_TB,
- * if dev->external_facing || dev->untrusted
+ * TODO: This quirk also needs to do the equivalent of PCI_ACS_TB when the
+ * device is external-facing or ATS is restricted by trust policy.
  */
 static int pci_quirk_enable_intel_pch_acs(struct pci_dev *dev)
 {
@@ -5567,7 +5567,8 @@ static int pci_quirk_enable_intel_spt_pch_acs(struct pci_dev *dev)
 	ctrl |= (cap & PCI_ACS_CR);
 	ctrl |= (cap & PCI_ACS_UF);
 
-	if (pci_ats_disabled() || dev->external_facing || dev->untrusted)
+	if (pci_ats_disabled() || dev->external_facing ||
+	    pci_dev_default_is_restricted(dev))
 		ctrl |= (cap & PCI_ACS_TB);
 
 	pci_write_config_dword(dev, pos + INTEL_SPT_ACS_CTRL, ctrl);
include/linux/device.h +5 -0
index 2914b7191d342..5c86e7a19e47b 100644
@@ -933,6 +933,11 @@ static inline bool device_iommu_mapped(struct device *dev)
 	return (dev->iommu_group != NULL);
 }
 
+static inline bool device_policy_is_adversarial(const struct device *dev)
+{
+	return READ_ONCE(dev->trust_policy) == DEVICE_TRUST_POLICY_ADVERSARIAL;
+}
+
 static inline bool device_policy_is_blocked(const struct device *dev)
 {
 	return READ_ONCE(dev->trust_policy) == DEVICE_TRUST_POLICY_BLOCKED;
include/linux/pci.h +10 -0
index aa3765a20a96c..5da9f7fabf1e5 100644
@@ -616,6 +616,16 @@ static inline struct pci_dev *to_pci_dev(const struct device *dev)
 {
 	return container_of(dev, struct pci_dev, dev);
 }
+
+static inline bool
+pci_dev_default_is_restricted(const struct pci_dev *pdev)
+{
+	enum device_trust_policy policy = READ_ONCE(pdev->dev.trust_policy);
+
+	return policy == DEVICE_TRUST_POLICY_BLOCKED ||
+	       policy == DEVICE_TRUST_POLICY_ADVERSARIAL;
+}
+
 #define for_each_pci_dev(d) while ((d = pci_get_device(PCI_ANY_ID, PCI_ANY_ID, d)) != NULL)
 #define for_each_pci_dev_reverse(d) \
 	while ((d = pci_get_device_reverse(PCI_ANY_ID, PCI_ANY_ID, d)) != NULL)
Signature · 1 line
2.56.1
#30 lore raw

PATCH v4 29/33 iommu: Use device trust for DMA restrictions

In reply to Leon Romanovsky

From: Leon Romanovsky <[email protected]>

PCI-specific untrusted checks exclude devices classified as adversaries through generic policy. Their DMA protections should depend on the selected trust policy rather than the source of that classification.

Use policy for early domain selection and active trust for DMA bouncing. This removes the remaining need for PCI's duplicate untrusted flag. Changes to IOMMU domains after authorization remain separate work.

---
 .../driver-api/driver-model/device-trust.rst         | 20 ++++++++++++++++++++
 drivers/iommu/amd/iommu.c                            |  3 +--
 drivers/iommu/dma-iommu.c                            | 14 +++++---------
 drivers/iommu/intel/iommu.c                          | 14 +++++---------
 drivers/iommu/iommu.c                                |  9 +++++----
 drivers/pci/probe.c                                  |  1 -
 include/linux/pci.h                                  |  8 --------
 7 files changed, 36 insertions(+), 33 deletions(-)
Documentation/driver-api/driver-model/device-trust.rst +20 -0
index 3c6babdba80e9..2c31d887a0cb0 100644
@@ -255,6 +255,26 @@ fixed; it cannot fall back to unrestricted.
 Drivers that manage DMA themselves must provide their own containment.
 Drivers that do not use DMA need no domain.
 
+PCI classification
+==================
+
+PCI selects adversarial as the initial policy for devices that the
+platform reports as removable through external-facing ports, and for
+devices below a bridge with adversarial policy. IOMMU domain selection,
+ATS, and ACS Translation Blocking follow the policy at discovery; DMA
+bouncing follows the active level. Without device trust boot options this
+classification cannot change, so PCI devices keep the restrictions they
+had before device trust.
+
+Boot options are an explicit opt-in to replace it. A global value other
+than default and a device rule replace the classification at discovery.
+Global blocked and adversarial therefore restrict every PCI device, and
+authorization does not revisit those discovery-time decisions. PCI has no
+``trust_resolve`` callback, so a device rule of default resolves to
+unrestricted. Devices below a bridge inherit adversarial policy only while
+the bridge's policy is adversarial. A matching driver rule applies when
+the driver binds and changes only DMA bouncing.
+
 Initrd attestation sequence
 ===========================
 
drivers/iommu/amd/iommu.c +1 -2
index 960e1dc05ec69..e358bbb1f2baa 100644
@@ -3401,8 +3401,7 @@ static int amd_iommu_def_domain_type(struct device *dev)
 	if (!dev_is_pci(dev))
 		return 0;
 
-	/* Always use DMA domain for untrusted device */
-	if (to_pci_dev(dev)->untrusted)
+	if (pci_dev_default_is_restricted(to_pci_dev(dev)))
 		return IOMMU_DOMAIN_DMA;
 
 	/* Apply device specific quirks */
drivers/iommu/dma-iommu.c +5 -9
index 78742aeba932d..a48fb511bfe6f 100644
@@ -589,16 +589,11 @@ static int iova_reserve_iommu_regions(struct device *dev,
 	return ret;
 }
 
-static bool dev_is_untrusted(struct device *dev)
-{
-	return dev_is_pci(dev) && to_pci_dev(dev)->untrusted;
-}
-
 static bool dev_use_swiotlb(struct device *dev, size_t size,
 			    enum dma_data_direction dir)
 {
 	return IS_ENABLED(CONFIG_SWIOTLB) &&
-		(dev_is_untrusted(dev) ||
+		(device_is_adversarial(dev) ||
 		 dma_kmalloc_needs_bounce(dev, size, dir));
 }
 
@@ -611,7 +606,7 @@ static bool dev_use_sg_swiotlb(struct device *dev, struct scatterlist *sg,
 	if (!IS_ENABLED(CONFIG_SWIOTLB))
 		return false;
 
-	if (dev_is_untrusted(dev))
+	if (device_is_adversarial(dev))
 		return true;
 
 	/*
@@ -1189,7 +1184,8 @@ static phys_addr_t iommu_dma_map_swiotlb(struct device *dev, phys_addr_t phys,
 	 * swiotlb_tbl_map_single() has initialized the bounce buffer proper to
 	 * the contents of the original memory buffer.
 	 */
-	if (phys != (phys_addr_t)DMA_MAPPING_ERROR && dev_is_untrusted(dev)) {
+	if (phys != (phys_addr_t)DMA_MAPPING_ERROR &&
+	    device_is_adversarial(dev)) {
 		size_t start, virt = (size_t)phys_to_virt(phys);
 
 		/* Pre-padding */
@@ -1790,7 +1786,7 @@ size_t iommu_dma_max_opt_mapping_size(void)
 
 size_t iommu_dma_max_mapping_size(struct device *dev)
 {
-	if (dev_is_untrusted(dev))
+	if (device_is_adversarial(dev))
 		return swiotlb_max_mapping_size(dev);
 
 	return SIZE_MAX;
drivers/iommu/intel/iommu.c +5 -9
index 5a2e705a2f2e0..0202b491f222e 100644
@@ -2624,8 +2624,8 @@ static void __init platform_optin_force_iommu(void)
 		return;
 
 	/*
-	 * If Intel-IOMMU is disabled by default, we will apply identity
-	 * map for all devices except those marked as being untrusted.
+	 * If Intel-IOMMU is disabled by default, an external device could
+	 * otherwise receive an identity map despite its adversarial policy.
 	 */
 	if (dmar_policy_off()) {
 		pr_info("Intel-IOMMU force enabled due to platform opt in\n");
@@ -3629,16 +3629,12 @@ static bool intel_iommu_is_attach_deferred(struct device *dev)
 	return translation_pre_enabled(info->iommu) && !info->domain;
 }
 
-/*
- * Check that the device does not live on an external facing PCI port that is
- * marked as untrusted. Such devices should not be able to apply quirks and
- * thus not be able to bypass the IOMMU restrictions.
- */
+/* Bypass quirks must not prevent later adversarial operation. */
 static bool risky_device(struct pci_dev *pdev)
 {
-	if (pdev->untrusted) {
+	if (pci_dev_default_is_restricted(pdev)) {
 		pci_info(pdev,
-			 "Skipping IOMMU quirk for dev [%04X:%04X] on untrusted PCI link\n",
+			 "Skipping IOMMU quirk due to trust policy [%04X:%04X]\n",
 			 pdev->vendor, pdev->device);
 		pci_info(pdev, "Please check with your BIOS/Platform vendor about this\n");
 		return true;
drivers/iommu/iommu.c +5 -4
index b486b8bbd1fcd..891b0cd2dad02 100644
@@ -1901,10 +1901,11 @@ static int iommu_get_default_domain_type(struct iommu_group *group,
 		driver_type = iommu_get_def_domain_type(group, gdev->dev,
 							driver_type);
 
-		if (dev_is_pci(gdev->dev) && to_pci_dev(gdev->dev)->untrusted) {
+		if (dev_is_pci(gdev->dev) &&
+		    pci_dev_default_is_restricted(to_pci_dev(gdev->dev))) {
 			/*
-			 * No ARM32 using systems will set untrusted, it cannot
-			 * work.
+			 * No ARM32 using systems select a restricted trust
+			 * policy; it cannot work.
 			 */
 			if (WARN_ON(IS_ENABLED(CONFIG_ARM_DMA_USE_IOMMU)))
 				return -1;
@@ -1928,7 +1929,7 @@ static int iommu_get_default_domain_type(struct iommu_group *group,
 		if (driver_type && driver_type != IOMMU_DOMAIN_DMA) {
 			dev_err_ratelimited(
 				untrusted,
-				"Device is not trusted, but driver is overriding group %u to %s, refusing to probe.\n",
+				"Device trust policy restricts DMA, but driver is overriding group %u to %s, refusing to probe.\n",
 				group->id, iommu_domain_type_str(driver_type));
 			return -1;
 		}
drivers/pci/probe.c +0 -1
index 606ab8a3aa8ed..d890049823a6e 100644
@@ -2080,7 +2080,6 @@ int pci_setup_device(struct pci_dev *dev)
 	set_pcie_cxl(dev);
 
 	pci_set_default_trust_policy(dev);
-	dev->untrusted = device_policy_is_adversarial(&dev->dev);
 	device_trust_init(&dev->dev);
 
 	/* "Unknown power state" */
include/linux/pci.h +0 -8
index 5da9f7fabf1e5..25a54b25775d4 100644
@@ -490,14 +490,6 @@ struct pci_dev {
 	unsigned int	shpc_managed:1;		/* SHPC owned by shpchp */
 	unsigned int	is_thunderbolt:1;	/* Thunderbolt controller */
 	unsigned int	is_cxl:1;               /* Compute Express Link (CXL) */
-	/*
-	 * Devices marked being untrusted are the ones that can potentially
-	 * execute DMA attacks and similar. They are typically connected
-	 * through external ports such as Thunderbolt but not limited to
-	 * that. When an IOMMU is enabled they should be getting full
-	 * mappings to make sure they cannot access arbitrary memory.
-	 */
-	unsigned int	untrusted:1;
 	/*
 	 * Info from the platform, e.g., ACPI or device tree, may mark a
 	 * device as "external-facing".  An external-facing device is
Signature · 1 line
2.56.1
#31 lore raw

PATCH v4 30/33 driver core: Allow driver attachment with the device lock held

In reply to Leon Romanovsky

From: Leon Romanovsky <[email protected]>

USB authorization needs to keep driver attachment and its configuration result under the same device lock. Dropping the lock to call device_attach() would let another request change that result before the authorizing caller can inspect it.

Provide synchronous attachment for callers that already hold the device lock. Keep asynchronous scheduling outside the lock in the existing path.

---
 drivers/base/dd.c      | 34 ++++++++++++++++++++++++++++++----
 include/linux/device.h |  1 +
 2 files changed, 31 insertions(+), 4 deletions(-)
drivers/base/dd.c +30 -4
index 4c4723384dc66..2f45b53e5ba91 100644
@@ -1222,12 +1222,11 @@ static void __device_attach_async_helper(void *_dev, async_cookie_t cookie)
 	put_device(dev);
 }
 
-static int __device_attach(struct device *dev, bool allow_async)
+static int __device_attach_locked(struct device *dev, bool allow_async,
+				  bool *async)
 {
 	int ret = 0;
-	bool async = false;
 
-	device_lock(dev);
 	mutex_lock(&dev->p->driver_lock);
 	if (dev->p->dead) {
 		goto out_unlock;
@@ -1265,7 +1264,7 @@ static int __device_attach(struct device *dev, bool allow_async)
 			 */
 			dev_dbg(dev, "scheduling asynchronous probe\n");
 			get_device(dev);
-			async = true;
+			*async = true;
 		} else {
 			pm_request_idle(dev);
 		}
@@ -1275,6 +1274,16 @@ static int __device_attach(struct device *dev, bool allow_async)
 	}
 out_unlock:
 	mutex_unlock(&dev->p->driver_lock);
+	return ret;
+}
+
+static int __device_attach(struct device *dev, bool allow_async)
+{
+	bool async = false;
+	int ret;
+
+	device_lock(dev);
+	ret = __device_attach_locked(dev, allow_async, &async);
 	device_unlock(dev);
 	if (async && !async_schedule_dev_nocall(__device_attach_async_helper, dev)) {
 		put_device(dev);
@@ -1284,6 +1293,23 @@ static int __device_attach(struct device *dev, bool allow_async)
 	return ret;
 }
 
+/**
+ * device_attach_locked - try to attach a driver with the device locked
+ * @dev: device to attach
+ *
+ * Synchronous device_attach() with the device lock held by the caller.
+ * When called for a USB interface, the parent lock must also be held.
+ * The device lock remains held on return.
+ *
+ * Return: 1 if bound, 0 if no driver bound, or a negative error.
+ */
+int device_attach_locked(struct device *dev)
+{
+	device_lock_assert(dev);
+	return __device_attach_locked(dev, false, NULL);
+}
+EXPORT_SYMBOL_GPL(device_attach_locked);
+
 /**
  * device_attach - try to attach device to a driver.
  * @dev: device.
include/linux/device.h +1 -0
index 5c86e7a19e47b..3857545f67df3 100644
@@ -1337,6 +1337,7 @@ int __must_check device_driver_attach_unrestricted(
 int __must_check device_bind_driver(struct device *dev);
 void device_release_driver(struct device *dev);
 int  __must_check device_attach(struct device *dev);
+int __must_check device_attach_locked(struct device *dev);
 int __must_check driver_attach(const struct device_driver *drv);
 void device_initial_probe(struct device *dev);
 int __must_check device_reprobe(struct device *dev);
Signature · 1 line
2.56.1
#32 lore raw

PATCH v4 31/33 USB: Retain the result of configuration requests

In reply to Leon Romanovsky

From: Leon Romanovsky <[email protected]>

The generic USB device driver can bind successfully even when setting its configuration fails. Authorization that attaches this driver therefore cannot use the attachment result to report configuration errors or decide whether setup can be retried.

Retain the last configuration result for callers holding the device lock. Keep driver binding successful so userspace can recover by selecting another configuration.

---
 drivers/usb/core/message.c | 12 +++++++++++-
 include/linux/usb.h        |  2 ++
 2 files changed, 13 insertions(+), 1 deletion(-)
drivers/usb/core/message.c +11 -1
index ca6976e266f02..32014605b6db6 100644
@@ -2042,6 +2042,8 @@ static bool usb_has_claimant(struct usb_device *dev,
 	return false;
 }
 
+static int usb_set_configuration_internal(struct usb_device *dev, int configuration);
+
 /*
  * usb_set_configuration - Makes a particular device setting be current
  * @dev: the device whose configuration is being updated
@@ -2089,6 +2091,15 @@ static bool usb_has_claimant(struct usb_device *dev,
  * drivers currently known to the kernel.
  */
 int usb_set_configuration(struct usb_device *dev, int configuration)
+{
+	int ret = usb_set_configuration_internal(dev, configuration);
+
+	dev->config_error = ret;
+	return ret;
+}
+EXPORT_SYMBOL_GPL(usb_set_configuration);
+
+static int usb_set_configuration_internal(struct usb_device *dev, int configuration)
 {
 	int i, ret;
 	struct usb_host_config *cp = NULL;
@@ -2347,7 +2358,6 @@ int usb_set_configuration(struct usb_device *dev, int configuration)
 	usb_autosuspend_device(dev);
 	return 0;
 }
-EXPORT_SYMBOL_GPL(usb_set_configuration);
 
 static LIST_HEAD(set_config_list);
 static DEFINE_SPINLOCK(set_config_lock);
include/linux/usb.h +2 -0
index a5e706f67f33a..d372712eba34c 100644
@@ -599,6 +599,7 @@ struct usb3_lpm_parameters {
  * @descriptor: USB device descriptor
  * @bos: USB device BOS descriptor set
  * @config: all of the device's configs
+ * @config_error: Result of the last configuration request.
  * @actconfig: the active configuration
  * @ep_in: array of IN endpoints
  * @ep_out: array of OUT endpoints
@@ -686,6 +687,7 @@ struct usb_device {
 	struct usb_host_config *config;
 
 	struct usb_host_config *actconfig;
+	int config_error;
 	struct usb_host_endpoint *ep_in[16];
 	struct usb_host_endpoint *ep_out[16];
 
Signature · 1 line
2.56.1
#33 lore raw

PATCH v4 32/33 USB: Authorize interfaces through device trust

In reply to Leon Romanovsky

From: Leon Romanovsky <[email protected]>

An interface denied by USB defaults must remain blocked until its trust policy permits binding. Keeping an independent denial flag would prevent generic trust authorization from making that interface usable.

Represent the initial denial as blocked policy when trust is enabled, and let interface authorization request unrestricted operation. Preserve explicit USB deauthorization and report rejected policy changes to userspace. Interface policies remain independent of the device policy.

---
 Documentation/ABI/testing/sysfs-bus-usb |  5 +++++
 Documentation/usb/authorization.rst     | 11 +++++++++++
 drivers/usb/core/driver.c               |  2 +-
 drivers/usb/core/message.c              | 23 ++++++++++++++++++-----
 drivers/usb/core/sysfs.c                |  7 +++++--
 drivers/usb/core/usb.h                  |  2 +-
 include/linux/usb.h                     |  9 +++++++--
 7 files changed, 48 insertions(+), 11 deletions(-)
Documentation/ABI/testing/sysfs-bus-usb +5 -0
index 5213117fd957e..62e326710ef5f 100644
@@ -12,6 +12,11 @@ Description:
 
 		A deauthorized interface cannot be probed or claimed.
 
+		With device trust enabled at boot, an interface that is not
+		authorized by default starts with the "blocked" trust policy
+		(see sysfs-devices-trust). Writing 1 then requests the "unrestricted"
+		policy. Deauthorizing does not change the committed trust level.
+
 What:		/sys/bus/usb/devices/usbX/interface_authorized_default
 Date:		August 2015
 Description:
Documentation/usb/authorization.rst +11 -0
index 150a14970e951..cc419a11ffc43 100644
@@ -120,6 +120,13 @@ Deny interfaces per default::
 Per default the interface_authorized_default bit is 1.
 So all interfaces would authorized per default.
 
+With device trust enabled, an interface that is not authorized by default
+starts with the "blocked" trust policy, and writing 1 to its "authorized"
+attribute requests the "unrestricted" policy. Device and interface trust policies
+are independent: selecting "adversarial" for a USB device does not select it
+for its interfaces. Set interface policies separately before their drivers
+bind, using boot rules when necessary.
+
 Note:
   If a deauthorized interface will be authorized so the driver probing must
   be triggered manually by writing INTERFACE to /sys/bus/usb/drivers_probe
@@ -127,3 +134,7 @@ Note:
 For drivers that need multiple interfaces all needed interfaces should be
 authorized first. After that the drivers should be probed.
 This avoids side effects.
+
+Driver boot rules apply when an interface is claimed, including before
+registration. An interface deauthorized through sysfs must still be
+authorized before it can be claimed.
drivers/usb/core/driver.c +1 -1
index 1d488111a70fb..80f4d2644023b 100644
@@ -338,7 +338,7 @@ static int usb_probe_interface(struct device *dev)
 	if (udev->authorized == 0) {
 		dev_info(&intf->dev, "Device is not authorized for usage\n");
 		return error;
-	} else if (intf->authorized == 0) {
+	} else if (!usb_interface_authorized(intf)) {
 		dev_info(&intf->dev, "Interface %d is not authorized for usage\n",
 				intf->altsetting->desc.bInterfaceNumber);
 		return error;
drivers/usb/core/message.c +18 -5
index 32014605b6db6..534f8e645a856 100644
@@ -1881,16 +1881,24 @@ void usb_deauthorize_interface(struct usb_interface *intf)
  * usb_authorize_interface - authorize an USB interface
  *
  * @intf: USB interface structure
+ *
+ * Return: 0 on success, or the error of the trust policy request.
  */
-void usb_authorize_interface(struct usb_interface *intf)
+int usb_authorize_interface(struct usb_interface *intf)
 {
 	struct device *dev = &intf->dev;
+	int ret = 0;
 
-	if (!intf->authorized) {
-		device_lock(dev);
-		intf->authorized = 1; /* authorize interface */
-		device_unlock(dev);
+	device_lock(dev);
+	if (device_policy_is_blocked(dev)) {
+		ret = device_trust_set_policy_locked(dev, DEVICE_TRUST_POLICY_UNRESTRICTED);
+		if (ret)
+			goto out_unlock;
 	}
+	intf->authorized = 1;
+out_unlock:
+	device_unlock(dev);
+	return ret;
 }
 
 static int usb_if_uevent(const struct device *dev, struct kobj_uevent_env *env)
@@ -2213,6 +2221,11 @@ static int usb_set_configuration_internal(struct usb_device *dev, int configurat
 		intf->altsetting = intfc->altsetting;
 		intf->num_altsetting = intfc->num_altsetting;
 		intf->authorized = !!HCD_INTF_AUTHORIZED(hcd);
+		if (device_trust_enabled()) {
+			if (!intf->authorized)
+				intf->dev.trust_policy = DEVICE_TRUST_POLICY_BLOCKED;
+			intf->authorized = 1;
+		}
 		kref_get(&intfc->ref);
 
 		alt = usb_altnum_to_altsetting(intf, 0);
drivers/usb/core/sysfs.c +5 -2
index d22dc78457d79..b8974e9db3a22 100644
@@ -1213,7 +1213,7 @@ static ssize_t interface_authorized_show(struct device *dev,
 {
 	struct usb_interface *intf = to_usb_interface(dev);
 
-	return sysfs_emit(buf, "%u\n", intf->authorized);
+	return sysfs_emit(buf, "%u\n", usb_interface_authorized(intf));
 }
 
 /*
@@ -1225,12 +1225,15 @@ static ssize_t interface_authorized_store(struct device *dev,
 	struct usb_interface *intf = to_usb_interface(dev);
 	bool val;
 	struct kernfs_node *kn;
+	int ret;
 
 	if (kstrtobool(buf, &val) != 0)
 		return -EINVAL;
 
 	if (val) {
-		usb_authorize_interface(intf);
+		ret = usb_authorize_interface(intf);
+		if (ret)
+			return ret;
 	} else {
 		/*
 		 * Prevent deadlock if another process is concurrently
drivers/usb/core/usb.h +1 -1
index cbee731837471..6f65d6cd5d117 100644
@@ -34,7 +34,7 @@ extern void usb_disable_device(struct usb_device *dev, int skip_ep0);
 extern int usb_deauthorize_device(struct usb_device *);
 extern int usb_authorize_device(struct usb_device *);
 extern void usb_deauthorize_interface(struct usb_interface *);
-extern void usb_authorize_interface(struct usb_interface *);
+extern int usb_authorize_interface(struct usb_interface *);
 extern void usb_detect_quirks(struct usb_device *udev);
 extern void usb_detect_interface_quirks(struct usb_device *udev);
 extern void usb_release_quirk_list(void);
include/linux/usb.h +7 -2
index d372712eba34c..9399c816b367d 100644
@@ -204,8 +204,8 @@ enum usb_wireless_status {
  *	has been deferred.
  * @needs_binding: flag set when the driver should be re-probed or unbound
  *	following a reset or suspend operation it doesn't support.
- * @authorized: This allows to (de)authorize individual interfaces instead
- *	a whole device in contrast to the device authorization.
+ * @authorized: USB authorization flag; trust policy may also restrict use,
+ *	see usb_interface_authorized().
  * @wireless_status: if the USB device uses a receiver/emitter combo, whether
  *	the emitter is connected.
  * @wireless_status_work: Used for scheduling wireless status changes
@@ -278,6 +278,11 @@ struct usb_interface {
 
 #define to_usb_interface(__dev)	container_of_const(__dev, struct usb_interface, dev)
 
+static inline bool usb_interface_authorized(const struct usb_interface *intf)
+{
+	return intf->authorized && !device_policy_is_blocked(&intf->dev);
+}
+
 static inline void *usb_get_intfdata(struct usb_interface *intf)
 {
 	return dev_get_drvdata(&intf->dev);
Signature · 1 line
2.56.1
#34 lore raw

PATCH v4 33/33 USB: Authorize devices through device trust

In reply to Leon Romanovsky

From: Leon Romanovsky <[email protected]>

USB authorization can configure a device and expose its interfaces. With generic trust enabled, that must wait until the device driver has been admitted, otherwise configuration bypasses policy.

Keep authorization, attachment and the configuration result under the device lock so concurrent requests cannot report each other's failures. Allow configuration retries after failure while preserving authorization and any active configuration. Retain the existing flow on legacy boots.

---
 Documentation/ABI/testing/sysfs-bus-usb | 13 +++++++++++
 Documentation/usb/authorization.rst     | 26 ++++++++++++++++++++++
 drivers/usb/core/driver.c               | 10 +++++----
 drivers/usb/core/generic.c              |  2 +-
 drivers/usb/core/hub.c                  | 39 +++++++++++++++++++++++++++------
 drivers/usb/core/message.c              |  7 ++++--
 drivers/usb/core/sysfs.c                |  2 +-
 drivers/usb/core/trace.h                |  2 +-
 drivers/usb/core/usb.c                  |  6 +++++
 include/linux/usb.h                     | 12 +++++-----
 10 files changed, 98 insertions(+), 21 deletions(-)
Documentation/ABI/testing/sysfs-bus-usb +13 -0
index 62e326710ef5f..dbe70c481e7c8 100644
@@ -33,6 +33,19 @@ Description:
 		drivers, non-authorized one are not.  By default, wired
 		USB devices are authorized.
 
+		With device trust enabled at boot, a device that is not
+		authorized by default starts with the "blocked" trust policy
+		(see sysfs-devices-trust). Writing 1 requests the "unrestricted" policy
+		if the policy is blocked, then binds and configures the device.
+		Configuration errors leave authorization granted. If setup failed
+		and no configuration remains, write 1 again to retry, or select a
+		configuration through bConfigurationValue after driver admission.
+		Writing 1 preserves an existing configuration. Finding no suitable
+		configuration remains successful authorization without setup.
+		Writing 0 deconfigures it without changing its committed trust
+		level. Without trust boot options, the existing authorization
+		flow is unchanged.
+
 What:		/sys/bus/usb/drivers/.../new_id
 Date:		October 2011
 Contact:	[email protected]
Documentation/usb/authorization.rst +26 -0
index cc419a11ffc43..327519c803768 100644
@@ -92,6 +92,32 @@ can fake descriptors and device info. Don't trust that. You are
 welcome.
 
 
+Device trust
+------------
+
+Without device trust boot options, USB authorization is unchanged. With
+device trust enabled, authorization uses the policy described in
+Documentation/driver-api/driver-model/device-trust.rst. A device that the
+authorized_default setting does not authorize starts with the "blocked"
+trust policy and reads 0 in "authorized". Boot device rules can replace
+this initial policy.
+
+Writing 1 to "authorized" for such a device requests the "unrestricted" policy and
+binds the device, which configures it. To operate it as an adversary,
+enable trust policy writes at boot, for example with
+``device_trust.default=default``, and write "adversarial" to its
+"trust_policy" attribute before writing 1. The choice is fixed for the life
+of the device: writing 0 deconfigures it, and a later 1 configures it again
+at the same trust level.
+
+Configuration errors leave authorization granted. If setup failed and no
+configuration remains, write 1 again to retry, or use "bConfigurationValue"
+to select a configuration after the device driver has been admitted.
+Writing 1 preserves an existing configuration. As before, failure to choose
+a suitable configuration is not an authorization error; an explicit
+"bConfigurationValue" selection remains available.
+
+
 Interface authorization
 -----------------------
 
drivers/usb/core/driver.c +6 -4
index 80f4d2644023b..0eb35e64b7708 100644
@@ -335,7 +335,7 @@ static int usb_probe_interface(struct device *dev)
 	if (usb_device_is_owned(udev))
 		return error;
 
-	if (udev->authorized == 0) {
+	if (!usb_device_authorized(udev)) {
 		dev_info(&intf->dev, "Device is not authorized for usage\n");
 		return error;
 	} else if (!usb_interface_authorized(intf)) {
@@ -1350,8 +1350,7 @@ static int usb_resume_device(struct usb_device *udev, pm_message_t msg)
 	if (udev->state == USB_STATE_NOTATTACHED)
 		goto done;
 
-	/* Can't resume it if it doesn't have a driver. */
-	if (udev->dev.driver == NULL) {
+	if (!udev->dev.driver && !device_trust_enabled()) {
 		status = -ENOTCONN;
 		goto done;
 	}
@@ -1366,7 +1365,10 @@ static int usb_resume_device(struct usb_device *udev, pm_message_t msg)
 	if (udev->quirks & USB_QUIRK_RESET_RESUME)
 		udev->reset_resume = 1;
 
-	udriver = to_usb_device_driver(udev->dev.driver);
+	if (udev->dev.driver)
+		udriver = to_usb_device_driver(udev->dev.driver);
+	else
+		udriver = &usb_generic_driver;
 	if (udriver->generic_subclass)
 		status = usb_generic_driver_resume(udev, msg);
 	if (status == 0 && udriver->resume)
drivers/usb/core/generic.c +1 -1
index a48994e11ef3d..bcfc01eefd09c 100644
@@ -242,7 +242,7 @@ int usb_generic_driver_probe(struct usb_device *udev)
 	/* Choose and set the configuration.  This registers the interfaces
 	 * with the driver core and lets interface drivers bind to them.
 	 */
-	if (udev->authorized == 0)
+	if (!usb_device_authorized(udev))
 		dev_info(&udev->dev, "Device is not authorized for usage\n");
 	else {
 		c = usb_choose_configuration(udev);
drivers/usb/core/hub.c +32 -7
index 372bd6368cc94..c94539b0c697c 100644
@@ -2773,7 +2773,8 @@ int usb_new_device(struct usb_device *udev)
 int usb_deauthorize_device(struct usb_device *usb_dev)
 {
 	usb_lock_device(usb_dev);
-	if (usb_dev->authorized == 0)
+	if (!usb_dev->authorized &&
+	    (!device_trust_enabled() || !usb_dev->config_error))
 		goto out_unauthorized;
 
 	usb_dev->authorized = 0;
@@ -2787,17 +2788,41 @@ int usb_deauthorize_device(struct usb_device *usb_dev)
 
 int usb_authorize_device(struct usb_device *usb_dev)
 {
+	bool attach;
 	int result = 0, c;
 
 	usb_lock_device(usb_dev);
-	if (usb_dev->authorized == 1)
-		goto out_authorized;
+	if (device_policy_is_blocked(&usb_dev->dev)) {
+		result = device_trust_set_policy_locked(&usb_dev->dev,
+							DEVICE_TRUST_POLICY_UNRESTRICTED);
+		if (result)
+			goto out_unlock;
+	}
+
+	attach = device_trust_enabled() && !usb_dev->dev.driver;
+	if (!attach && usb_dev->authorized == 1 &&
+	    (!device_trust_enabled() || !usb_dev->config_error ||
+	     usb_dev->actconfig))
+		goto out_unlock;
 
 	result = usb_autoresume_device(usb_dev);
 	if (result < 0) {
 		dev_err(&usb_dev->dev,
 			"can't autoresume for authorization: %d\n", result);
-		goto error_autoresume;
+		goto out_unlock;
+	}
+
+	if (attach) {
+		usb_dev->authorized = 1;
+		usb_dev->config_error = 0;
+		result = device_attach_locked(&usb_dev->dev);
+		if (result <= 0) {
+			if (result >= 0)
+				result = -ENODEV;
+		} else {
+			result = usb_dev->config_error;
+		}
+		goto out_autosuspend;
 	}
 
 	usb_dev->authorized = 1;
@@ -2816,10 +2841,10 @@ int usb_authorize_device(struct usb_device *usb_dev)
 	}
 	dev_info(&usb_dev->dev, "authorized to connect\n");
 
+out_autosuspend:
 	usb_autosuspend_device(usb_dev);
-error_autoresume:
-out_authorized:
-	usb_unlock_device(usb_dev);	/* complements locktree */
+out_unlock:
+	usb_unlock_device(usb_dev);
 	return result;
 }
 
drivers/usb/core/message.c +5 -2
index 534f8e645a856..17ce694bb7dac 100644
@@ -2081,7 +2081,7 @@ static int usb_set_configuration_internal(struct usb_device *dev, int configurat
  * channels are available independently; and choosing between open
  * standard device protocols (like CDC) or proprietary ones.
  *
- * Note that a non-authorized device (dev->authorized == 0) will only
+ * Note that a non-authorized device (see usb_device_authorized()) will only
  * be put in unconfigured mode.
  *
  * Note that USB has an additional level of device configurability,
@@ -2115,7 +2115,7 @@ static int usb_set_configuration_internal(struct usb_device *dev, int configurat
 	struct usb_hcd *hcd = bus_to_hcd(dev->bus);
 	int n, nintf;
 
-	if (dev->authorized == 0 || configuration == -1)
+	if (!usb_device_authorized(dev) || configuration == -1)
 		configuration = 0;
 	else {
 		for (i = 0; i < dev->descriptor.bNumConfigurations; i++) {
@@ -2128,6 +2128,9 @@ static int usb_set_configuration_internal(struct usb_device *dev, int configurat
 	}
 	if ((!cp && configuration != 0))
 		return -EINVAL;
+	if (cp && device_trust_enabled() &&
+	    device_get_trust_level(&dev->dev) == DEVICE_TRUST_BLOCKED)
+		return -EPERM;
 
 	/* The USB spec says configuration 0 means unconfigured.
 	 * But if a device includes a configuration numbered 0,
drivers/usb/core/sysfs.c +1 -1
index b8974e9db3a22..189fb917b81ee 100644
@@ -728,7 +728,7 @@ static ssize_t authorized_show(struct device *dev,
 			       struct device_attribute *attr, char *buf)
 {
 	struct usb_device *usb_dev = to_usb_device(dev);
-	return sysfs_emit(buf, "%u\n", usb_dev->authorized);
+	return sysfs_emit(buf, "%u\n", usb_device_authorized(usb_dev));
 }
 
 /*
drivers/usb/core/trace.h +1 -1
index 903e57dc273af..42f9cfcd8b0f2 100644
@@ -27,7 +27,7 @@ DECLARE_EVENT_CLASS(usb_core_log_usb_device,
 		__entry->speed = udev->speed;
 		__entry->state = udev->state;
 		__entry->bus_mA = udev->bus_mA;
-		__entry->authorized = udev->authorized;
+		__entry->authorized = usb_device_authorized(udev);
 	),
 	TP_printk("usb %s speed %s state %s %dmA [%s]",
 		__get_str(name),
drivers/usb/core/usb.c +6 -0
index 2559a180fdeec..180f4d797b107 100644
@@ -748,6 +748,12 @@ struct usb_device *usb_alloc_dev(struct usb_device *parent,
 #endif
 
 	dev->authorized = usb_dev_authorized(dev, usb_hcd);
+	if (device_trust_enabled()) {
+		if (!dev->authorized)
+			dev->dev.trust_policy = DEVICE_TRUST_POLICY_BLOCKED;
+		dev->authorized = 1;
+	}
+	device_trust_init(&dev->dev);
 	trace_usb_alloc_dev(dev);
 	return dev;
 }
include/linux/usb.h +7 -5
index 9399c816b367d..34ee4d6f91c19 100644
@@ -617,11 +617,8 @@ struct usb3_lpm_parameters {
  * @persist_enabled:  USB_PERSIST enabled for this device
  * @reset_in_progress: the device is being reset
  * @have_langid: whether string_langid is valid
- * @authorized: policy has said we can use it;
- *	(user space) policy determines if we authorize this device to be
- *	used or not. By default, wired USB devices are authorized.
- *	WUSB devices are not, until we authorize them from user space.
- *	FIXME -- complete doc
+ * @authorized: USB authorization flag; trust policy may also restrict use,
+ *	see usb_device_authorized().
  * @authenticated: Crypto authentication passed
  * @tunnel_mode: Connection native or tunneled over USB4
  * @usb4_link: device link to the USB4 host interface
@@ -756,6 +753,11 @@ struct usb_device {
 
 #define to_usb_device(__dev)	container_of_const(__dev, struct usb_device, dev)
 
+static inline bool usb_device_authorized(const struct usb_device *udev)
+{
+	return udev->authorized && !device_policy_is_blocked(&udev->dev);
+}
+
 static inline struct usb_device *__intf_to_usbdev(struct usb_interface *intf)
 {
 	return to_usb_device(intf->dev.parent);
Signature · 1 line
2.56.1