From nobody Thu Feb 12 17:27:46 2026 Received: from us-smtp-delivery-124.mimecast.com (us-smtp-delivery-124.mimecast.com [170.10.129.124]) (using TLSv1.2 with cipher ECDHE-RSA-AES256-GCM-SHA384 (256/256 bits)) (No client certificate requested) by smtp.subspace.kernel.org (Postfix) with ESMTPS id 9BB0E1DFFB for ; Mon, 10 Jun 2024 18:03:33 +0000 (UTC) Authentication-Results: smtp.subspace.kernel.org; arc=none smtp.client-ip=170.10.129.124 ARC-Seal: i=1; a=rsa-sha256; d=subspace.kernel.org; s=arc-20240116; t=1718042615; cv=none; b=GfeurbBDWvWU3uFDZsjANXFVgFBEKGqkD42R+KvL/yJTKwfYJ0mThcY1VwT3WprvnprVHbmpqHj41KvP+uoHBEVlwW00ICfHPnhZLuDcfIdgda6466heyPfAQDOcHK+etuUCFbO9w2pZslcjLo2MLWsIRDX8pFVBcHq3k/3dxM8= ARC-Message-Signature: i=1; a=rsa-sha256; d=subspace.kernel.org; s=arc-20240116; t=1718042615; c=relaxed/simple; bh=X0OsUVU4whKgMI8Hzd5DwWsl+jAnlQPOwOL7uMZTJgI=; h=From:To:Cc:Subject:Date:Message-ID:In-Reply-To:References: MIME-Version:Content-Type; b=MlLiX9MwMye13XybHM4ydAoqiBCp6dTWTSkMbUmLampQsSC+LIiMd+34p/PNEhda+xUpEA+NU8qvPZNNjpsLYLd5QPkJU3N6QwpDN0qUzXimWJrVvsailvRBqS9wEJ4mYPt7Wg2Har71Ba0WPQcGHEAVe5wiKKG4gAlFe0YTjj4= ARC-Authentication-Results: i=1; smtp.subspace.kernel.org; dmarc=pass (p=none dis=none) header.from=redhat.com; spf=pass smtp.mailfrom=redhat.com; dkim=pass (1024-bit key) header.d=redhat.com header.i=@redhat.com header.b=NBXx+zid; arc=none smtp.client-ip=170.10.129.124 Authentication-Results: smtp.subspace.kernel.org; dmarc=pass (p=none dis=none) header.from=redhat.com Authentication-Results: smtp.subspace.kernel.org; spf=pass smtp.mailfrom=redhat.com Authentication-Results: smtp.subspace.kernel.org; dkim=pass (1024-bit key) header.d=redhat.com header.i=@redhat.com header.b="NBXx+zid" DKIM-Signature: v=1; a=rsa-sha256; c=relaxed/relaxed; d=redhat.com; s=mimecast20190719; t=1718042612; h=from:from:reply-to:subject:subject:date:date:message-id:message-id: to:to:cc:cc:mime-version:mime-version:content-type:content-type: content-transfer-encoding:content-transfer-encoding: in-reply-to:in-reply-to:references:references; bh=MOH7HuTCUNOIi1ypXRDBz2Sa8rCOYzURRQsh29Kh5U0=; b=NBXx+zid5e1MxtJHSpE+8LjFuJTsB4WLUpBNcrUf3KqSnB3FWBgpizpUi5WmjcAYDtQC61 7zBb4AorH21sxO42Ozclh4Ti76AIX8z5ZjFNyeGYdDUUugADDmaZDuxmTmiqlUXk7ZL44+ e06k3jyHtUQEQRvWmGIToPwStBq/BxY= Received: from mail-lf1-f70.google.com (mail-lf1-f70.google.com [209.85.167.70]) by relay.mimecast.com with ESMTP with STARTTLS (version=TLSv1.3, cipher=TLS_AES_256_GCM_SHA384) id us-mta-389-xh2yZ0tpOa-KGVmwmFfb1A-1; Mon, 10 Jun 2024 14:03:31 -0400 X-MC-Unique: xh2yZ0tpOa-KGVmwmFfb1A-1 Received: by mail-lf1-f70.google.com with SMTP id 2adb3069b0e04-52baa7fb26dso173544e87.3 for ; Mon, 10 Jun 2024 11:03:31 -0700 (PDT) X-Google-DKIM-Signature: v=1; a=rsa-sha256; c=relaxed/relaxed; d=1e100.net; s=20230601; t=1718042610; x=1718647410; h=content-transfer-encoding:mime-version:references:in-reply-to :message-id:date:subject:cc:to:from:x-gm-message-state:from:to:cc :subject:date:message-id:reply-to; bh=MOH7HuTCUNOIi1ypXRDBz2Sa8rCOYzURRQsh29Kh5U0=; b=VPVGhrqbcaPXxWMBiuoaosTlY74yDrhSoFvslHb4WzcFigJqQLua0JDosshO9DkG1j AnrH+SDg2/TghcNGvn8UKDZNwOyk9vJvViUvodsk0ZAaG8qVzvbtij/A25hgPl2ZauPl s08MbG4g6127v1Pn4oM2DIYEKUhUb19bLJlj70y4L58xLs2QJQmV39IkOM59HnPF+LP6 68S+midCRuFH1txgf8n8quchg2d3HejVi54E8NOI1y+pqnqz5w1qvyqRbeOsGGqe3bqq 21E+hLAJ1gEVlxePER6Thz9wChlTTlP5cp7yrhCYUYlDwqm7HaU2C3HuEbq1QVxvPlfw p1mA== X-Forwarded-Encrypted: i=1; AJvYcCU/0jBMpBDr+gmAIbeRaAQ6DWWLv4A9pAsGQAtdzceY7JzhViBgaqdoj4bxFSWpfGWtz9j8Y29gRZuwOpdd7W0ZD6d2m+JYup7RW/DJ X-Gm-Message-State: AOJu0YwcEybfNAbnuS3mo40VsAlZe26TxNYeJikVxpLYAMlabgKVlgyK fFF5jR0F/JT5oUnt2SWWJ2uvn1Sh8IfsvHs08z/7n4eWYrZC1AjzUhk1mRGAqAgkd9c9w8XWpmk UkmrtKF8a8lNV3zx8fGVcPCO9KgbPa9qqoTQo+DKUj+eH7Nxdgea8PCKtMct2Lg== X-Received: by 2002:a05:6512:31cd:b0:52c:8440:1d7b with SMTP id 2adb3069b0e04-52c84401e02mr4936356e87.36.1718042609775; Mon, 10 Jun 2024 11:03:29 -0700 (PDT) X-Google-Smtp-Source: AGHT+IFcM8nXvZdQsYEWpW5FBxipSy3B12hC7zjzhSY8QswERWu5NWPzpSC0A2gHP8gwLTF9QrMgXQ== X-Received: by 2002:a05:6512:31cd:b0:52c:8440:1d7b with SMTP id 2adb3069b0e04-52c84401e02mr4936329e87.36.1718042609299; Mon, 10 Jun 2024 11:03:29 -0700 (PDT) Received: from cassiopeiae.. ([2a02:810d:4b3f:ee94:642:1aff:fe31:a19f]) by smtp.gmail.com with ESMTPSA id ffacd0b85a97d-35f24c7a9c8sm3266475f8f.78.2024.06.10.11.03.26 (version=TLS1_3 cipher=TLS_AES_256_GCM_SHA384 bits=256/256); Mon, 10 Jun 2024 11:03:27 -0700 (PDT) From: Danilo Krummrich To: gregkh@linuxfoundation.org, rafael@kernel.org, mcgrof@kernel.org, russell.h.weight@intel.com, ojeda@kernel.org, alex.gaynor@gmail.com, wedsonaf@gmail.com, boqun.feng@gmail.com, gary@garyguo.net, bjorn3_gh@protonmail.com, benno.lossin@proton.me, a.hindborg@samsung.com, aliceryhl@google.com, airlied@gmail.com, fujita.tomonori@gmail.com, pstanner@redhat.com, ajanulgu@redhat.com, lyude@redhat.com Cc: rust-for-linux@vger.kernel.org, linux-kernel@vger.kernel.org, Danilo Krummrich Subject: [PATCH v2 1/2] rust: add abstraction for struct device Date: Mon, 10 Jun 2024 20:02:27 +0200 Message-ID: <20240610180318.72152-2-dakr@redhat.com> X-Mailer: git-send-email 2.45.1 In-Reply-To: <20240610180318.72152-1-dakr@redhat.com> References: <20240610180318.72152-1-dakr@redhat.com> Precedence: bulk X-Mailing-List: linux-kernel@vger.kernel.org List-Id: List-Subscribe: List-Unsubscribe: MIME-Version: 1.0 Content-Type: text/plain; charset="utf-8" Content-Transfer-Encoding: quoted-printable Add an (always) reference-counted abstraction for a generic C `struct device`. This abstraction encapsulates existing `struct device` instances and manages its reference count. Subsystems may use this abstraction as a base to abstract subsystem specific device instances based on a generic `struct device`, such as `struct pci_dev`. Co-developed-by: Wedson Almeida Filho Signed-off-by: Wedson Almeida Filho Signed-off-by: Danilo Krummrich --- rust/helpers.c | 1 + rust/kernel/device.rs | 97 +++++++++++++++++++++++++++++++++++++++++++ rust/kernel/lib.rs | 1 + 3 files changed, 99 insertions(+) create mode 100644 rust/kernel/device.rs diff --git a/rust/helpers.c b/rust/helpers.c index 2c37a0f5d7a8..0e02b2c64c72 100644 --- a/rust/helpers.c +++ b/rust/helpers.c @@ -23,6 +23,7 @@ #include #include #include +#include #include #include #include diff --git a/rust/kernel/device.rs b/rust/kernel/device.rs new file mode 100644 index 000000000000..6e22b0b97928 --- /dev/null +++ b/rust/kernel/device.rs @@ -0,0 +1,97 @@ +// SPDX-License-Identifier: GPL-2.0 + +//! Generic devices that are part of the kernel's driver model. +//! +//! C header: [`include/linux/device.h`](srctree/include/linux/device.h) + +use crate::{ + bindings, + types::{ARef, Opaque}, +}; +use core::ptr; + +/// A reference-counted device. +/// +/// This structure represents the Rust abstraction for a C `struct device`= . This implementation +/// abstracts the usage of an already existing C `struct device` within Ru= st code that we get +/// passed from the C side. +/// +/// An instance of this abstraction can be obtained temporarily or permane= nt. +/// +/// A temporary one is bound to the lifetime of the C `struct device` poin= ter used for creation. +/// A permanent instance is always reference-counted and hence not restric= ted by any lifetime +/// boundaries. +/// +/// For subsystems it is recommended to create a permanent instance to wra= p into a subsystem +/// specifc device structure (e.g. `pci::Device`). This is useful for pass= ing it to drivers in +/// `T::probe()`, such that a driver can store the `ARef` (equival= ent to storing a +/// `struct device` pointer in a C driver) for arbitrary purposes, e.g. al= locating DMA coherent +/// memory. +/// +/// # Invariants +/// +/// The pointer stored in `Self` is non-null and valid for the lifetime of= the `ARef` instance. In +/// particular, the `ARef` instance owns an increment on the underlying ob= ject=E2=80=99s reference count. +#[repr(transparent)] +pub struct Device(Opaque); + +impl Device { + /// Creates a new reference-counted abstraction instance of an existin= g `struct device` pointer. + /// + /// # Safety + /// + /// Callers must ensure that `ptr` is valid, non-null, and has a non-z= ero reference count, + /// i.e. it must be ensured that the reference count of the C `struct = device` `ptr` points to + /// can't drop to zero, for the duration of this function call. + pub unsafe fn from_raw(ptr: *mut bindings::device) -> ARef { + // SAFETY: By the safety requirements, ptr is valid. + // Initially increase the reference count by one to compensate for= the final decrement once + // this newly created `ARef` instance is dropped. + unsafe { bindings::get_device(ptr) }; + + // CAST: `Self` is a `repr(transparent)` wrapper around `bindings:= :device`. + let ptr =3D ptr.cast::(); + + // SAFETY: By the safety requirements, ptr is valid. + unsafe { ARef::from_raw(ptr::NonNull::new_unchecked(ptr)) } + } + + /// Obtain the raw `struct device *`. + pub(crate) fn as_raw(&self) -> *mut bindings::device { + self.0.get() + } + + /// Convert a raw C `struct device` pointer to a `&'a Device`. + /// + /// # Safety + /// + /// Callers must ensure that `ptr` is valid, non-null, and has a non-z= ero reference count, + /// i.e. it must be ensured that the reference count of the C `struct = device` `ptr` points to + /// can't drop to zero, for the duration of this function call and the= entire duration when the + /// returned reference exists. + pub unsafe fn as_ref<'a>(ptr: *mut bindings::device) -> &'a Self { + // SAFETY: Guaranteed by the safety requirements of the function. + unsafe { &*ptr.cast() } + } +} + +// SAFETY: Instances of `Device` are always reference-counted. +unsafe impl crate::types::AlwaysRefCounted for Device { + fn inc_ref(&self) { + // SAFETY: The existence of a shared reference guarantees that the= refcount is non-zero. + unsafe { bindings::get_device(self.as_raw()) }; + } + + unsafe fn dec_ref(obj: ptr::NonNull) { + // SAFETY: The safety requirements guarantee that the refcount is = non-zero. + unsafe { bindings::put_device(obj.cast().as_ptr()) } + } +} + +// SAFETY: `Device` only holds a pointer to a C `struct device`, which is = safe to be used from any +// thread. +unsafe impl Send for Device {} + +// SAFETY: `Device` only holds a pointer to a C `struct device`, reference= s to which are safe to be +// used from any thread. +unsafe impl Sync for Device {} diff --git a/rust/kernel/lib.rs b/rust/kernel/lib.rs index fbd91a48ff8b..dd1207f1a873 100644 --- a/rust/kernel/lib.rs +++ b/rust/kernel/lib.rs @@ -28,6 +28,7 @@ =20 pub mod alloc; mod build_assert; +pub mod device; pub mod error; pub mod init; pub mod ioctl; --=20 2.45.1 From nobody Thu Feb 12 17:27:46 2026 Received: from us-smtp-delivery-124.mimecast.com (us-smtp-delivery-124.mimecast.com [170.10.133.124]) (using TLSv1.2 with cipher ECDHE-RSA-AES256-GCM-SHA384 (256/256 bits)) (No client certificate requested) by smtp.subspace.kernel.org (Postfix) with ESMTPS id 6375C14E2EA for ; Mon, 10 Jun 2024 18:03:37 +0000 (UTC) Authentication-Results: smtp.subspace.kernel.org; arc=none smtp.client-ip=170.10.133.124 ARC-Seal: i=1; a=rsa-sha256; d=subspace.kernel.org; s=arc-20240116; t=1718042619; cv=none; b=DR47eNNfJhjkPaG/aeOlDU7OpcICtRO/fq3PvlQDdPp/o+pa3e5TaoS7JM0CMBzpc66y3kYoC9/aj1xFwZ+XenBaj15tp6oDOyaUIZdYSqeRm7juNz6fElNRPSL54gpoXI0w8MVHZ3yJFgRSNrpjPbZGgV7wW9RyqieOxJAeShU= ARC-Message-Signature: i=1; a=rsa-sha256; d=subspace.kernel.org; s=arc-20240116; t=1718042619; c=relaxed/simple; bh=uo7uJNZ3epcfm6pUCaHZJk3wrGW8HkLdKy1yzy9H64k=; h=From:To:Cc:Subject:Date:Message-ID:In-Reply-To:References: MIME-Version; b=sI8SOWoHJmdTFEx+n87bapGI59FlQIY1Ta5d9oJ5lqqTAxOs+ME0zmGifh8qxxN1ahxiOYn8/xZ+u0jAmRoSxT/rO1psynEEmIb9vL5Va/ehwd2kIVHuPgjO+0/sj7HSLGCNJGnN533NG5m8KGkNRSVC+itJZ5GevHjGzfUkGhg= ARC-Authentication-Results: i=1; smtp.subspace.kernel.org; dmarc=pass (p=none dis=none) header.from=redhat.com; spf=pass smtp.mailfrom=redhat.com; dkim=pass (1024-bit key) header.d=redhat.com header.i=@redhat.com header.b=VoUWEp07; arc=none smtp.client-ip=170.10.133.124 Authentication-Results: smtp.subspace.kernel.org; dmarc=pass (p=none dis=none) header.from=redhat.com Authentication-Results: smtp.subspace.kernel.org; spf=pass smtp.mailfrom=redhat.com Authentication-Results: smtp.subspace.kernel.org; dkim=pass (1024-bit key) header.d=redhat.com header.i=@redhat.com header.b="VoUWEp07" DKIM-Signature: v=1; a=rsa-sha256; c=relaxed/relaxed; d=redhat.com; s=mimecast20190719; t=1718042616; h=from:from:reply-to:subject:subject:date:date:message-id:message-id: to:to:cc:cc:mime-version:mime-version: content-transfer-encoding:content-transfer-encoding: in-reply-to:in-reply-to:references:references; bh=Ko/751Ih42xdNXKctrEpP8bOTHpEg6/LHScfPoHYDW4=; b=VoUWEp07vu4CGYumVHgAySp0Ak+xaNsUsXjzvIixs2Zh+HWjdicDxY9AOye4qsoasEvVOy xppQeKihYJHlZuQGIXpkPqqhfGgJQM8Crm1L9FZ4nxCJkUzoBXU5ZvfGo2E2+HwHanG8Bw c5dVYOz8ecB1ZdH9ckWgVLJYD81T1Fk= Received: from mail-wr1-f71.google.com (mail-wr1-f71.google.com [209.85.221.71]) by relay.mimecast.com with ESMTP with STARTTLS (version=TLSv1.3, cipher=TLS_AES_256_GCM_SHA384) id us-mta-554-3_kKfLCOMSWKEvQ5CqluEQ-1; Mon, 10 Jun 2024 14:03:34 -0400 X-MC-Unique: 3_kKfLCOMSWKEvQ5CqluEQ-1 Received: by mail-wr1-f71.google.com with SMTP id ffacd0b85a97d-35f271c5b17so124683f8f.0 for ; Mon, 10 Jun 2024 11:03:34 -0700 (PDT) X-Google-DKIM-Signature: v=1; a=rsa-sha256; c=relaxed/relaxed; d=1e100.net; s=20230601; t=1718042614; x=1718647414; h=content-transfer-encoding:mime-version:references:in-reply-to :message-id:date:subject:cc:to:from:x-gm-message-state:from:to:cc :subject:date:message-id:reply-to; bh=Ko/751Ih42xdNXKctrEpP8bOTHpEg6/LHScfPoHYDW4=; b=LCIR86+TBeTZXSsd2DTZ6cZ8elxO/dP/cyMz5ZzQab3C5+0YLanjWbdwVLfagy7U84 M2ZVoT+AkcJDNnb2ZgL9liClu8qLvIpCwmCPkZZdg3Pvjx+rRjFuGw+clWI6djdttvcR Cz7nfe2vrVO9s9ezC+HNHWTJ1ChGoTMMh6imrgCEFRnELCcjr7u0AF/+vxZ/2oRXOrBE 3ldzlm2jfoJoTpXSv4DFtQrAt+4VfZ/ZS0DH1mAmjKIIIldzeD0o2oK+VipKTf+qN9Mw nWPdy1yofPernM/n+6wg5Jc33Xd5ImpiJcQ4xtNv4Wg4hUPRZwrYjQTmo4VM2SNpjqd3 +q7Q== X-Forwarded-Encrypted: i=1; AJvYcCW78V9EgHwREEQki616jhJMh/lLiOqmN2PNs1Axc3AiCSyYjXOubfUPa5WBZue3WY4IYuJVMBXbCCyu8CxPU1lLRMIqoBgewHAg/GLk X-Gm-Message-State: AOJu0Yw0BOJSoL2LWO79f5BGIMeQtHL8wZrriIJbttEGFWbIRAz506pl AVImYpP+JIjSKiRYIFbQLn8vv3xvWZTbtUf6VQJxPRjgZ1u7PszsskpY25CdGsH9cV1+E971gK/ 1DYXaT3zsYfQi+pUOVkeA+Q8vTyLS2X1cIMqIC8ZiDFU7d323WbTy8GaOVs57wA== X-Received: by 2002:a05:6000:2c2:b0:35f:1835:3a62 with SMTP id ffacd0b85a97d-35f18353c74mr5628315f8f.35.1718042613662; Mon, 10 Jun 2024 11:03:33 -0700 (PDT) X-Google-Smtp-Source: AGHT+IGRjRL00cNynGjzhv5Ncbfra3TprBtbnWt4hfvsVgE5SGzuiZzJ0gnNTax6xVQ+ug9rSsbqwA== X-Received: by 2002:a05:6000:2c2:b0:35f:1835:3a62 with SMTP id ffacd0b85a97d-35f18353c74mr5628275f8f.35.1718042613322; Mon, 10 Jun 2024 11:03:33 -0700 (PDT) Received: from cassiopeiae.. ([2a02:810d:4b3f:ee94:642:1aff:fe31:a19f]) by smtp.gmail.com with ESMTPSA id ffacd0b85a97d-35f1aed74cesm6273814f8f.112.2024.06.10.11.03.31 (version=TLS1_3 cipher=TLS_AES_256_GCM_SHA384 bits=256/256); Mon, 10 Jun 2024 11:03:32 -0700 (PDT) From: Danilo Krummrich To: gregkh@linuxfoundation.org, rafael@kernel.org, mcgrof@kernel.org, russell.h.weight@intel.com, ojeda@kernel.org, alex.gaynor@gmail.com, wedsonaf@gmail.com, boqun.feng@gmail.com, gary@garyguo.net, bjorn3_gh@protonmail.com, benno.lossin@proton.me, a.hindborg@samsung.com, aliceryhl@google.com, airlied@gmail.com, fujita.tomonori@gmail.com, pstanner@redhat.com, ajanulgu@redhat.com, lyude@redhat.com Cc: rust-for-linux@vger.kernel.org, linux-kernel@vger.kernel.org, Danilo Krummrich Subject: [PATCH v2 2/2] rust: add firmware abstractions Date: Mon, 10 Jun 2024 20:02:28 +0200 Message-ID: <20240610180318.72152-3-dakr@redhat.com> X-Mailer: git-send-email 2.45.1 In-Reply-To: <20240610180318.72152-1-dakr@redhat.com> References: <20240610180318.72152-1-dakr@redhat.com> Precedence: bulk X-Mailing-List: linux-kernel@vger.kernel.org List-Id: List-Subscribe: List-Unsubscribe: MIME-Version: 1.0 Content-Transfer-Encoding: quoted-printable Content-Type: text/plain; charset="utf-8" Add an abstraction around the kernels firmware API to request firmware images. The abstraction provides functions to access the firmware's size and backing buffer. The firmware is released once the abstraction instance is dropped. Signed-off-by: Danilo Krummrich --- rust/bindings/bindings_helper.h | 1 + rust/kernel/firmware.rs | 107 ++++++++++++++++++++++++++++++++ rust/kernel/lib.rs | 1 + 3 files changed, 109 insertions(+) create mode 100644 rust/kernel/firmware.rs diff --git a/rust/bindings/bindings_helper.h b/rust/bindings/bindings_helpe= r.h index ddb5644d4fd9..18a3f05115cb 100644 --- a/rust/bindings/bindings_helper.h +++ b/rust/bindings/bindings_helper.h @@ -9,6 +9,7 @@ #include #include #include +#include #include #include #include diff --git a/rust/kernel/firmware.rs b/rust/kernel/firmware.rs new file mode 100644 index 000000000000..7ff4c325f670 --- /dev/null +++ b/rust/kernel/firmware.rs @@ -0,0 +1,107 @@ +// SPDX-License-Identifier: GPL-2.0 + +//! Firmware abstraction +//! +//! C header: [`include/linux/firmware.h`](srctree/include/linux/firmware.= h") + +use crate::{bindings, device::Device, error::Error, error::Result, str::CS= tr}; +use core::ptr::NonNull; + +// One of the following: `bindings::request_firmware`, `bindings::firmware= _request_nowarn`, +// `firmware_request_platform`, `bindings::request_firmware_direct` +type FwFunc =3D + unsafe extern "C" fn(*mut *const bindings::firmware, *const i8, *mut b= indings::device) -> i32; + +/// Abstraction around a C `struct firmware`. +/// +/// This is a simple abstraction around the C firmware API. Just like with= the C API, firmware can +/// be requested. Once requested the abstraction provides direct access to= the firmware buffer as +/// `&[u8]`. The firmware is released once [`Firmware`] is dropped. +/// +/// # Invariants +/// +/// The pointer is valid, and has ownership over the instance of `struct f= irmware`. +/// +/// # Examples +/// +/// ``` +/// use kernel::firmware::Firmware; +/// +/// let fw =3D Firmware::request("path/to/firmware.bin", dev.as_ref())?; +/// driver_load_firmware(fw.data()); +/// ``` +pub struct Firmware(NonNull); + +impl Firmware { + fn request_internal(name: &CStr, dev: &Device, func: FwFunc) -> Result= { + let mut fw: *mut bindings::firmware =3D core::ptr::null_mut(); + let pfw: *mut *mut bindings::firmware =3D &mut fw; + + // SAFETY: `pfw` is a valid pointer to a NULL initialized `binding= s::firmware` pointer. + // `name` and `dev` are valid as by their type invariants. + let ret =3D unsafe { func(pfw as _, name.as_char_ptr(), dev.as_raw= ()) }; + if ret !=3D 0 { + return Err(Error::from_errno(ret)); + } + + // SAFETY: `func` not bailing out with a non-zero error code, guar= antees that `fw` is a + // valid pointer to `bindings::firmware`. + Ok(Firmware(unsafe { NonNull::new_unchecked(fw) })) + } + + /// Send a firmware request and wait for it. See also `bindings::reque= st_firmware`. + pub fn request(name: &CStr, dev: &Device) -> Result { + Self::request_internal(name, dev, bindings::request_firmware) + } + + /// Send a request for an optional firmware module. See also + /// `bindings::firmware_request_nowarn`. + pub fn request_nowarn(name: &CStr, dev: &Device) -> Result { + Self::request_internal(name, dev, bindings::firmware_request_nowar= n) + } + + /// Send a request for a firmware with platform-fw fallback. See also + /// `bindings::firmware_request_platform`. + pub fn request_platform(name: &CStr, dev: &Device) -> Result { + Self::request_internal(name, dev, bindings::firmware_request_platf= orm) + } + + /// Send a request for a firmware directly without usermode helper. Se= e also + /// `bindings::request_firmware_direct`. + pub fn request_direct(name: &CStr, dev: &Device) -> Result { + Self::request_internal(name, dev, bindings::request_firmware_direc= t) + } + + fn as_raw(&self) -> *mut bindings::firmware { + self.0.as_ptr() + } + + /// Returns the size of the requested firmware in bytes. + pub fn size(&self) -> usize { + // SAFETY: Safe as by the type invariant. + unsafe { (*self.as_raw()).size } + } + + /// Returns the requested firmware as `&[u8]`. + pub fn data(&self) -> &[u8] { + // SAFETY: Safe as by the type invariant. Additionally, `bindings:= :firmware` guarantees, if + // sucessfully requested, that `bindings::firmware::data` has a si= ze of + // `bindings::firmware::size` bytes. + unsafe { core::slice::from_raw_parts((*self.as_raw()).data, self.s= ize()) } + } +} + +impl Drop for Firmware { + fn drop(&mut self) { + // SAFETY: Safe as by the type invariant. + unsafe { bindings::release_firmware(self.as_raw()) }; + } +} + +// SAFETY: `Firmware` only holds a pointer to a C `struct firmware`, which= is safe to be used from +// any thread. +unsafe impl Send for Firmware {} + +// SAFETY: `Firmware` only holds a pointer to a C `struct firmware`, refer= ences to which are safe to +// be used from any thread. +unsafe impl Sync for Firmware {} diff --git a/rust/kernel/lib.rs b/rust/kernel/lib.rs index dd1207f1a873..5307aa45bb8d 100644 --- a/rust/kernel/lib.rs +++ b/rust/kernel/lib.rs @@ -30,6 +30,7 @@ mod build_assert; pub mod device; pub mod error; +pub mod firmware; pub mod init; pub mod ioctl; #[cfg(CONFIG_KUNIT)] --=20 2.45.1