Commit Graph

24 Commits

Author SHA1 Message Date
Alice Ryhl
6a2be11026 UPSTREAM: task: rust: rework how current is accessed
Introduce a new type called `CurrentTask` that lets you perform various
operations that are only safe on the `current` task.  Use the new type to
provide a way to access the current mm without incrementing its refcount.

With this change, you can write stuff such as

	let vma = current!().mm().lock_vma_under_rcu(addr);

without incrementing any refcounts.

This replaces the existing abstractions for accessing the current pid
namespace.  With the old approach, every field access to current involves
both a macro and a unsafe helper function.  The new approach simplifies
that to a single safe function on the `CurrentTask` type.  This makes it
less heavy-weight to add additional current accessors in the future.

That said, creating a `CurrentTask` type like the one in this patch
requires that we are careful to ensure that it cannot escape the current
task or otherwise access things after they are freed.  To do this, I
declared that it cannot escape the current "task context" where I defined
a "task context" as essentially the region in which `current` remains
unchanged.  So e.g., release_task() or begin_new_exec() would leave the
task context.

If a userspace thread returns to userspace and later makes another
syscall, then I consider the two syscalls to be different task contexts.
This allows values stored in that task to be modified between syscalls,
even if they're guaranteed to be immutable during a syscall.

Ensuring correctness of `CurrentTask` is slightly tricky if we also want
the ability to have a safe `kthread_use_mm()` implementation in Rust.  To
support that safely, there are two patterns we need to ensure are safe:

	// Case 1: current!() called inside the scope.
	let mm;
	kthread_use_mm(some_mm, || {
	    mm = current!().mm();
	});
	drop(some_mm);
	mm.do_something(); // UAF

and:

	// Case 2: current!() called before the scope.
	let mm;
	let task = current!();
	kthread_use_mm(some_mm, || {
	    mm = task.mm();
	});
	drop(some_mm);
	mm.do_something(); // UAF

The existing `current!()` abstraction already natively prevents the first
case: The `&CurrentTask` would be tied to the inner scope, so the
borrow-checker ensures that no reference derived from it can escape the
scope.

Fixing the second case is a bit more tricky.  The solution is to
essentially pretend that the contents of the scope execute on an different
thread, which means that only thread-safe types can cross the boundary.
Since `CurrentTask` is marked `NotThreadSafe`, attempts to move it to
another thread will fail, and this includes our fake pretend thread
boundary.

This has the disadvantage that other types that aren't thread-safe for
reasons unrelated to `current` also cannot be moved across the
`kthread_use_mm()` boundary.  I consider this an acceptable tradeoff.

Link: https://lkml.kernel.org/r/20250408-vma-v16-8-d8b446e885d9@google.com
Signed-off-by: Alice Ryhl <aliceryhl@google.com>
Acked-by: Lorenzo Stoakes <lorenzo.stoakes@oracle.com>
Acked-by: Liam R. Howlett <Liam.Howlett@Oracle.com>
Reviewed-by: Boqun Feng <boqun.feng@gmail.com>
Reviewed-by: Andreas Hindborg <a.hindborg@kernel.org>
Reviewed-by: Gary Guo <gary@garyguo.net>
Cc: Alex Gaynor <alex.gaynor@gmail.com>
Cc: Arnd Bergmann <arnd@arndb.de>
Cc: Balbir Singh <balbirs@nvidia.com>
Cc: Benno Lossin <benno.lossin@proton.me>
Cc: Björn Roy Baron <bjorn3_gh@protonmail.com>
Cc: Greg Kroah-Hartman <gregkh@linuxfoundation.org>
Cc: Jann Horn <jannh@google.com>
Cc: John Hubbard <jhubbard@nvidia.com>
Cc: Matthew Wilcox (Oracle) <willy@infradead.org>
Cc: Miguel Ojeda <ojeda@kernel.org>
Cc: Suren Baghdasaryan <surenb@google.com>
Cc: Trevor Gross <tmgross@umich.edu>
Cc: Vlastimil Babka <vbabka@suse.cz>
Signed-off-by: Andrew Morton <akpm@linux-foundation.org>

Bug: 429146594
(cherry picked from commit 6acb75ad7b9e1548ae7f7532312295f74e48c973)
Change-Id: I40422349633c5c125a5d4d8611efc5ca5c2cd484
Signed-off-by: Alice Ryhl <aliceryhl@google.com>
2025-07-02 13:08:23 +00:00
Christian Brauner
602e2300de UPSTREAM: rust: add PidNamespace
The lifetime of `PidNamespace` is bound to `Task` and `struct pid`.

The `PidNamespace` of a `Task` doesn't ever change once the `Task` is
alive. A `unshare(CLONE_NEWPID)` or `setns(fd_pidns/pidfd, CLONE_NEWPID)`
will not have an effect on the calling `Task`'s pid namespace. It will
only effect the pid namespace of children created by the calling `Task`.
This invariant guarantees that after having acquired a reference to a
`Task`'s pid namespace it will remain unchanged.

When a task has exited and been reaped `release_task()` will be called.
This will set the `PidNamespace` of the task to `NULL`. So retrieving
the `PidNamespace` of a task that is dead will return `NULL`. Note, that
neither holding the RCU lock nor holding a referencing count to the
`Task` will prevent `release_task()` being called.

In order to retrieve the `PidNamespace` of a `Task` the
`task_active_pid_ns()` function can be used. There are two cases to
consider:

(1) retrieving the `PidNamespace` of the `current` task (2) retrieving
the `PidNamespace` of a non-`current` task

From system call context retrieving the `PidNamespace` for case (1) is
always safe and requires neither RCU locking nor a reference count to be
held. Retrieving the `PidNamespace` after `release_task()` for current
will return `NULL` but no codepath like that is exposed to Rust.

Retrieving the `PidNamespace` from system call context for (2) requires
RCU protection. Accessing `PidNamespace` outside of RCU protection
requires a reference count that must've been acquired while holding the
RCU lock. Note that accessing a non-`current` task means `NULL` can be
returned as the non-`current` task could have already passed through
`release_task()`.

To retrieve (1) the `current_pid_ns!()` macro should be used which
ensure that the returned `PidNamespace` cannot outlive the calling
scope. The associated `current_pid_ns()` function should not be called
directly as it could be abused to created an unbounded lifetime for
`PidNamespace`. The `current_pid_ns!()` macro allows Rust to handle the
common case of accessing `current`'s `PidNamespace` without RCU
protection and without having to acquire a reference count.

For (2) the `task_get_pid_ns()` method must be used. This will always
acquire a reference on `PidNamespace` and will return an `Option` to
force the caller to explicitly handle the case where `PidNamespace` is
`None`, something that tends to be forgotten when doing the equivalent
operation in `C`. Missing RCU primitives make it difficult to perform
operations that are otherwise safe without holding a reference count as
long as RCU protection is guaranteed. But it is not important currently.
But we do want it in the future.

Note for (2) the required RCU protection around calling
`task_active_pid_ns()` synchronizes against putting the last reference
of the associated `struct pid` of `task->thread_pid`. The `struct pid`
stored in that field is used to retrieve the `PidNamespace` of the
caller. When `release_task()` is called `task->thread_pid` will be
`NULL`ed and `put_pid()` on said `struct pid` will be delayed in
`free_pid()` via `call_rcu()` allowing everyone with an RCU protected
access to the `struct pid` acquired from `task->thread_pid` to finish.

Link: https://lore.kernel.org/r/20241002-brauner-rust-pid_namespace-v5-1-a90e70d44fde@kernel.org
Reviewed-by: Alice Ryhl <aliceryhl@google.com>
Signed-off-by: Christian Brauner <brauner@kernel.org>

Bug: 429146594
(cherry picked from commit e0020ba6cbcbfbaaa50c3d4b610c7caa36459624)
Change-Id: Ib7d3b257fe9b6f11f8171924e2a146abb52b9bb7
Signed-off-by: Alice Ryhl <aliceryhl@google.com>
2025-07-02 13:08:23 +00:00
Alice Ryhl
b7f54dd23b Revert "BACKPORT: FROMLIST: task: rust: rework how current is accessed"
This reverts commit 98c8011159.

Bug: 429146594
Change-Id: Ib6968a1a63aafb9fea3e485c39d451b70cf320b4
Signed-off-by: Alice Ryhl <aliceryhl@google.com>
2025-07-02 13:07:45 +00:00
Greg Kroah-Hartman
b3fb80bdc6 Merge 6.12.19 into android16-6.12
GKI (arm64) relevant 48 out of 271 changes, affecting 92 files +576/-223
  5b414ed3bb Revert "of: reserved-memory: Fix using wrong number of cells to get property 'alignment'" [1 file, +2/-2]
  48a934fc47 Revert "mm/page_alloc.c: don't show protection in zone's ->lowmem_reserve[] for empty zone" [1 file, +1/-2]
  88310caff6 Bluetooth: Add check for mgmt_alloc_skb() in mgmt_remote_name() [1 file, +2/-0]
  7841180342 Bluetooth: Add check for mgmt_alloc_skb() in mgmt_device_connected() [1 file, +3/-0]
  2d448dbd47 userfaultfd: do not block on locking a large folio with raised refcount [1 file, +16/-1]
  f57e89c1cb block: fix conversion of GPT partition name to 7-bit [1 file, +1/-1]
  9426f38372 mm/page_alloc: fix uninitialized variable [1 file, +1/-0]
  79636d2981 mm: abort vma_modify() on merge out of memory failure [1 file, +8/-4]
  605f53f13b mm: don't skip arch_sync_kernel_mappings() in error paths [2 files, +6/-4]
  9ed33c7bac mm: fix finish_fault() handling for large folios [1 file, +10/-5]
  576a2f4c43 hwpoison, memory_hotplug: lock folio before unmap hwpoisoned folio [1 file, +4/-1]
  2e66d69941 mm: memory-hotplug: check folio ref count first in do_migrate_range [1 file, +7/-13]
  3c63fb6ef7 nvme-pci: use sgls for all user requests if possible [2 files, +13/-4]
  9dedafd86e nvme-ioctl: fix leaked requests on mapping error [1 file, +8/-4]
  084819b0d8 net: gso: fix ownership in __udp_gso_segment [1 file, +6/-2]
  1688acf477 perf/core: Fix pmus_lock vs. pmus_srcu ordering [1 file, +2/-2]
  a899adf706 HID: hid-steam: Fix use-after-free when detaching device [1 file, +1/-1]
  8aa8a40c76 ppp: Fix KMSAN uninit-value warning with bpf [1 file, +19/-9]
  b71cd95764 ethtool: linkstate: migrate linkstate functions to support multi-PHY setups [1 file, +15/-8]
  9c1d09cdbc net: ethtool: plumb PHY stats to PHY drivers [7 files, +167/-2]
  639c703529 net: ethtool: netlink: Allow NULL nlattrs when getting a phy_device [9 files, +19/-18]
  30e8aee778 vlan: enforce underlying device type [1 file, +2/-1]
  5d609f0d2f exfat: fix just enough dentries but allocate a new cluster to dir [1 file, +1/-1]
  c897b8ec46 exfat: fix soft lockup in exfat_clear_bitmap [3 files, +16/-7]
  611015122d exfat: short-circuit zero-byte writes in exfat_file_write_iter [1 file, +1/-1]
  2b484789e9 net-timestamp: support TCP GSO case for a few missing flags [1 file, +7/-4]
  b08e290324 ublk: set_params: properly check if parameters can be applied [1 file, +5/-2]
  b5741e4b9e sched/fair: Fix potential memory corruption in child_cfs_rq_on_list [1 file, +4/-2]
  39c2b2767e xhci: Restrict USB4 tunnel detection for USB3 devices to Intel hosts [1 file, +8/-0]
  4ea3319f3e usb: hub: lack of clearing xHC resources [1 file, +33/-0]
  0cab185c73 usb: quirks: Add DELAY_INIT and NO_LPM for Prolific Mass Storage Card Reader [1 file, +4/-0]
  079a3e52f3 usb: typec: ucsi: Fix NULL pointer access [1 file, +7/-6]
  840afbea3f usb: gadget: u_ether: Set is_suspend flag if remote wakeup fails [1 file, +2/-2]
  ced69d88eb usb: dwc3: Set SUSPENDENABLE soon after phy init [3 files, +45/-30]
  35db1f1829 usb: dwc3: gadget: Prevent irq storm when TH re-executes [2 files, +13/-13]
  b387312527 usb: typec: ucsi: increase timeout for PPM reset operations [1 file, +1/-1]
  4bf6c57a89 usb: gadget: Set self-powered based on MaxPower and bmAttributes [1 file, +11/-5]
  dcd7ffdefb usb: gadget: Fix setting self-powered state on suspend [1 file, +2/-1]
  395011ee82 usb: gadget: Check bmAttributes only if configuration is valid [1 file, +1/-1]
  012b98cdb5 acpi: typec: ucsi: Introduce a ->poll_cci method [7 files, +25/-12]
  d7015bb3c5 xhci: pci: Fix indentation in the PCI device ID definitions [1 file, +4/-4]
  ea39f99864 usb: xhci: Enable the TRB overfetch quirk on VIA VL805 [3 files, +10/-5]
  4e8df56636 char: misc: deallocate static minor in error path [1 file, +1/-1]
  b50e18791f drivers: core: fix device leak in __fw_devlink_relax_cycles() [1 file, +1/-0]
  a684bad77e mm: hugetlb: Add huge page size param to huge_ptep_get_and_clear() [16 files, +46/-28]
  6ad9643aa5 fs/netfs/read_pgpriv2: skip folio queues without `marks3` [1 file, +3/-2]
  5bc6e5b10f fs/netfs/read_collect: fix crash due to uninitialized `prev` variable [1 file, +11/-10]
  86b7ebddab uprobes: Fix race in uprobe_free_utask [1 file, +1/-1]

Changes in 6.12.19
        x86/amd_nb: Use rdmsr_safe() in amd_get_mmconfig_range()
        rust: block: fix formatting in GenDisk doc
        drm/i915/dsi: convert to struct intel_display
        drm/i915/dsi: Use TRANS_DDI_FUNC_CTL's own port width macro
        gpio: vf610: use generic device_get_match_data()
        gpio: vf610: add locking to gpio direction functions
        cifs: Remove symlink member from cifs_open_info_data union
        smb311: failure to open files of length 1040 when mounting with SMB3.1.1 POSIX extensions
        btrfs: fix data overwriting bug during buffered write when block size < page size
        x86/microcode/AMD: Add some forgotten models to the SHA check
        loongarch: Use ASM_REACHABLE
        rust: workqueue: remove unneeded ``#[allow(clippy::new_ret_no_self)]`
        rust: sort global Rust flags
        rust: types: avoid repetition in `{As,From}Bytes` impls
        rust: enable `clippy::undocumented_unsafe_blocks` lint
        rust: enable `clippy::unnecessary_safety_comment` lint
        rust: enable `clippy::unnecessary_safety_doc` lint
        rust: enable `clippy::ignored_unit_patterns` lint
        rust: enable `rustdoc::unescaped_backticks` lint
        rust: init: remove unneeded `#[allow(clippy::disallowed_names)]`
        rust: sync: remove unneeded `#[allow(clippy::non_send_fields_in_send_ty)]`
        rust: introduce `.clippy.toml`
        rust: replace `clippy::dbg_macro` with `disallowed_macros`
        rust: provide proper code documentation titles
        rust: enable Clippy's `check-private-items`
        Documentation: rust: add coding guidelines on lints
        rust: start using the `#[expect(...)]` attribute
        Documentation: rust: discuss `#[expect(...)]` in the guidelines
        rust: error: make conversion functions public
        rust: error: optimize error type to use nonzero
        rust: alloc: add `Allocator` trait
        rust: alloc: separate `aligned_size` from `krealloc_aligned`
        rust: alloc: rename `KernelAllocator` to `Kmalloc`
        rust: alloc: implement `ReallocFunc`
        rust: alloc: make `allocator` module public
        rust: alloc: implement `Allocator` for `Kmalloc`
        rust: alloc: add module `allocator_test`
        rust: alloc: implement `Vmalloc` allocator
        rust: alloc: implement `KVmalloc` allocator
        rust: alloc: add __GFP_NOWARN to `Flags`
        rust: alloc: implement kernel `Box`
        rust: treewide: switch to our kernel `Box` type
        rust: alloc: remove extension of std's `Box`
        rust: alloc: add `Box` to prelude
        rust: alloc: introduce `ArrayLayout`
        rust: alloc: implement kernel `Vec` type
        rust: alloc: implement `IntoIterator` for `Vec`
        rust: alloc: implement `collect` for `IntoIter`
        rust: treewide: switch to the kernel `Vec` type
        rust: alloc: remove `VecExt` extension
        rust: alloc: add `Vec` to prelude
        rust: error: use `core::alloc::LayoutError`
        rust: error: check for config `test` in `Error::name`
        rust: alloc: implement `contains` for `Flags`
        rust: alloc: implement `Cmalloc` in module allocator_test
        rust: str: test: replace `alloc::format`
        rust: alloc: update module comment of alloc.rs
        kbuild: rust: remove the `alloc` crate and `GlobalAlloc`
        MAINTAINERS: add entry for the Rust `alloc` module
        drm/panic: avoid reimplementing Iterator::find
        drm/panic: remove unnecessary borrow in alignment_pattern
        drm/panic: prefer eliding lifetimes
        drm/panic: remove redundant field when assigning value
        drm/panic: correctly indent continuation of line in list item
        drm/panic: allow verbose boolean for clarity
        drm/panic: allow verbose version check
        rust: kbuild: expand rusttest target for macros
        rust: fix size_t in bindgen prototypes of C builtins
        rust: map `__kernel_size_t` and friends also to usize/isize
        rust: use custom FFI integer types
        rust: alloc: Fix `ArrayLayout` allocations
        Revert "of: reserved-memory: Fix using wrong number of cells to get property 'alignment'"
        tracing: tprobe-events: Fix a memory leak when tprobe with $retval
        tracing: tprobe-events: Reject invalid tracepoint name
        stmmac: loongson: Pass correct arg to PCI function
        LoongArch: Convert unreachable() to BUG()
        LoongArch: Use polling play_dead() when resuming from hibernation
        LoongArch: Set max_pfn with the PFN of the last page
        LoongArch: KVM: Add interrupt checking for AVEC
        LoongArch: KVM: Reload guest CSR registers after sleep
        LoongArch: KVM: Fix GPA size issue about VM
        HID: appleir: Fix potential NULL dereference at raw event handle
        ksmbd: fix type confusion via race condition when using ipc_msg_send_request
        ksmbd: fix out-of-bounds in parse_sec_desc()
        ksmbd: fix use-after-free in smb2_lock
        ksmbd: fix bug on trap in smb2_lock
        gpio: rcar: Use raw_spinlock to protect register access
        gpio: aggregator: protect driver attr handlers against module unload
        ALSA: seq: Avoid module auto-load handling at event delivery
        ALSA: hda: intel: Add Dell ALC3271 to power_save denylist
        ALSA: hda/realtek - add supported Mic Mute LED for Lenovo platform
        ALSA: hda/realtek: update ALC222 depop optimize
        btrfs: fix a leaked chunk map issue in read_one_chunk()
        hwmon: (peci/dimmtemp) Do not provide fake thresholds data
        drm/amd/display: Fix null check for pipe_ctx->plane_state in resource_build_scaling_params
        drm/amdkfd: Fix NULL Pointer Dereference in KFD queue
        drm/amd/pm: always allow ih interrupt from fw
        drm/imagination: avoid deadlock on fence release
        drm/imagination: Hold drm_gem_gpuva lock for unmap
        drm/imagination: only init job done fences once
        drm/radeon: Fix rs400_gpu_init for ATI mobility radeon Xpress 200M
        Revert "mm/page_alloc.c: don't show protection in zone's ->lowmem_reserve[] for empty zone"
        Revert "selftests/mm: remove local __NR_* definitions"
        platform/x86: thinkpad_acpi: Add battery quirk for ThinkPad X131e
        x86/boot: Sanitize boot params before parsing command line
        x86/cacheinfo: Validate CPUID leaf 0x2 EDX output
        x86/cpu: Validate CPUID leaf 0x2 EDX output
        x86/cpu: Properly parse CPUID leaf 0x2 TLB descriptor 0x63
        drm/xe: Add staging tree for VM binds
        drm/xe/hmm: Style- and include fixes
        drm/xe/hmm: Don't dereference struct page pointers without notifier lock
        drm/xe/vm: Fix a misplaced #endif
        drm/xe/vm: Validate userptr during gpu vma prefetching
        mptcp: fix 'scheduling while atomic' in mptcp_pm_nl_append_new_local_addr
        drm/xe: Fix GT "for each engine" workarounds
        drm/xe: Fix fault mode invalidation with unbind
        drm/xe/userptr: properly setup pfn_flags_mask
        drm/xe/userptr: Unmap userptrs in the mmu notifier
        Bluetooth: Add check for mgmt_alloc_skb() in mgmt_remote_name()
        Bluetooth: Add check for mgmt_alloc_skb() in mgmt_device_connected()
        wifi: cfg80211: regulatory: improve invalid hints checking
        wifi: nl80211: reject cooked mode if it is set along with other flags
        selftests/damon/damos_quota_goal: handle minimum quota that cannot be further reduced
        selftests/damon/damos_quota: make real expectation of quota exceeds
        selftests/damon/damon_nr_regions: set ops update for merge results check to 100ms
        selftests/damon/damon_nr_regions: sort collected regiosn before checking with min/max boundaries
        rapidio: add check for rio_add_net() in rio_scan_alloc_net()
        rapidio: fix an API misues when rio_add_net() fails
        dma: kmsan: export kmsan_handle_dma() for modules
        s390/traps: Fix test_monitor_call() inline assembly
        NFS: fix nfs_release_folio() to not deadlock via kcompactd writeback
        userfaultfd: do not block on locking a large folio with raised refcount
        block: fix conversion of GPT partition name to 7-bit
        mm/page_alloc: fix uninitialized variable
        mm: abort vma_modify() on merge out of memory failure
        mm: memory-failure: update ttu flag inside unmap_poisoned_folio
        mm: don't skip arch_sync_kernel_mappings() in error paths
        mm: fix finish_fault() handling for large folios
        hwpoison, memory_hotplug: lock folio before unmap hwpoisoned folio
        mm: memory-hotplug: check folio ref count first in do_migrate_range
        wifi: iwlwifi: mvm: clean up ROC on failure
        wifi: iwlwifi: mvm: don't try to talk to a dead firmware
        wifi: iwlwifi: limit printed string from FW file
        wifi: iwlwifi: Free pages allocated when failing to build A-MSDU
        wifi: iwlwifi: Fix A-MSDU TSO preparation
        HID: google: fix unused variable warning under !CONFIG_ACPI
        HID: intel-ish-hid: Fix use-after-free issue in hid_ishtp_cl_remove()
        HID: intel-ish-hid: Fix use-after-free issue in ishtp_hid_remove()
        coredump: Only sort VMAs when core_sort_vma sysctl is set
        nvme-pci: add support for sgl metadata
        nvme-pci: use sgls for all user requests if possible
        nvme-ioctl: fix leaked requests on mapping error
        wifi: mac80211: Support parsing EPCS ML element
        wifi: mac80211: fix MLE non-inheritance parsing
        wifi: mac80211: fix vendor-specific inheritance
        drm/fbdev-helper: Move color-mode lookup into 4CC format helper
        drm/fbdev: Add memory-agnostic fbdev client
        drm: Add client-agnostic setup helper
        drm/fbdev-ttm: Support struct drm_driver.fbdev_probe
        drm/nouveau: Run DRM default client setup
        drm/nouveau: select FW caching
        bluetooth: btusb: Initialize .owner field of force_poll_sync_fops
        nvme-tcp: add basic support for the C2HTermReq PDU
        nvme-tcp: fix potential memory corruption in nvme_tcp_recv_pdu()
        nvmet-tcp: Fix a possible sporadic response drops in weakly ordered arch
        ALSA: hda/realtek: Remove (revert) duplicate Ally X config
        net: gso: fix ownership in __udp_gso_segment
        caif_virtio: fix wrong pointer check in cfv_probe()
        perf/core: Fix pmus_lock vs. pmus_srcu ordering
        hwmon: (pmbus) Initialise page count in pmbus_identify()
        hwmon: (ntc_thermistor) Fix the ncpXXxh103 sensor table
        hwmon: (ad7314) Validate leading zero bits and return error
        tracing: probe-events: Remove unused MAX_ARG_BUF_LEN macro
        drm/imagination: Fix timestamps in firmware traces
        ALSA: usx2y: validate nrpacks module parameter on probe
        llc: do not use skb_get() before dev_queue_xmit()
        hwmon: fix a NULL vs IS_ERR_OR_NULL() check in xgene_hwmon_probe()
        drm/sched: Fix preprocessor guard
        be2net: fix sleeping while atomic bugs in be_ndo_bridge_getlink
        net: hns3: make sure ptp clock is unregister and freed if hclge_ptp_get_cycle returns an error
        drm/i915/color: Extract intel_color_modeset()
        drm/i915: Plumb 'dsb' all way to the plane hooks
        drm/xe: Remove double pageflip
        HID: hid-steam: Fix use-after-free when detaching device
        net: ipa: Fix v4.7 resource group names
        net: ipa: Fix QSB data for v4.7
        net: ipa: Enable checksum for IPA_ENDPOINT_AP_MODEM_{RX,TX} for v4.7
        ppp: Fix KMSAN uninit-value warning with bpf
        ethtool: linkstate: migrate linkstate functions to support multi-PHY setups
        net: ethtool: plumb PHY stats to PHY drivers
        net: ethtool: netlink: Allow NULL nlattrs when getting a phy_device
        vlan: enforce underlying device type
        x86/sgx: Fix size overflows in sgx_encl_create()
        exfat: fix just enough dentries but allocate a new cluster to dir
        exfat: fix soft lockup in exfat_clear_bitmap
        exfat: short-circuit zero-byte writes in exfat_file_write_iter
        net-timestamp: support TCP GSO case for a few missing flags
        ublk: set_params: properly check if parameters can be applied
        sched/fair: Fix potential memory corruption in child_cfs_rq_on_list
        nvme-tcp: fix signedness bug in nvme_tcp_init_connection()
        net: dsa: mt7530: Fix traffic flooding for MMIO devices
        mctp i3c: handle NULL header address
        net: ipv6: fix dst ref loop in ila lwtunnel
        net: ipv6: fix missing dst ref drop in ila lwtunnel
        gpio: rcar: Fix missing of_node_put() call
        Revert "drivers/card_reader/rtsx_usb: Restore interrupt based detection"
        usb: renesas_usbhs: Call clk_put()
        xhci: Restrict USB4 tunnel detection for USB3 devices to Intel hosts
        usb: renesas_usbhs: Use devm_usb_get_phy()
        usb: hub: lack of clearing xHC resources
        usb: quirks: Add DELAY_INIT and NO_LPM for Prolific Mass Storage Card Reader
        usb: typec: ucsi: Fix NULL pointer access
        usb: renesas_usbhs: Flush the notify_hotplug_work
        usb: gadget: u_ether: Set is_suspend flag if remote wakeup fails
        usb: atm: cxacru: fix a flaw in existing endpoint checks
        usb: dwc3: Set SUSPENDENABLE soon after phy init
        usb: dwc3: gadget: Prevent irq storm when TH re-executes
        usb: typec: ucsi: increase timeout for PPM reset operations
        usb: typec: tcpci_rt1711h: Unmask alert interrupts to fix functionality
        usb: gadget: Set self-powered based on MaxPower and bmAttributes
        usb: gadget: Fix setting self-powered state on suspend
        usb: gadget: Check bmAttributes only if configuration is valid
        kbuild: userprogs: use correct lld when linking through clang
        acpi: typec: ucsi: Introduce a ->poll_cci method
        rust: finish using custom FFI integer types
        rust: map `long` to `isize` and `char` to `u8`
        xhci: pci: Fix indentation in the PCI device ID definitions
        usb: xhci: Enable the TRB overfetch quirk on VIA VL805
        KVM: SVM: Set RFLAGS.IF=1 in C code, to get VMRUN out of the STI shadow
        KVM: SVM: Save host DR masks on CPUs with DebugSwap
        KVM: SVM: Drop DEBUGCTL[5:2] from guest's effective value
        KVM: SVM: Suppress DEBUGCTL.BTF on AMD
        KVM: x86: Snapshot the host's DEBUGCTL in common x86
        KVM: SVM: Manually context switch DEBUGCTL if LBR virtualization is disabled
        KVM: x86: Snapshot the host's DEBUGCTL after disabling IRQs
        KVM: x86: Explicitly zero EAX and EBX when PERFMON_V2 isn't supported by KVM
        cdx: Fix possible UAF error in driver_override_show()
        mei: me: add panther lake P DID
        mei: vsc: Use "wakeuphostint" when getting the host wakeup GPIO
        intel_th: pci: Add Arrow Lake support
        intel_th: pci: Add Panther Lake-H support
        intel_th: pci: Add Panther Lake-P/U support
        char: misc: deallocate static minor in error path
        drivers: core: fix device leak in __fw_devlink_relax_cycles()
        slimbus: messaging: Free transaction ID in delayed interrupt scenario
        bus: mhi: host: pci_generic: Use pci_try_reset_function() to avoid deadlock
        eeprom: digsy_mtc: Make GPIO lookup table match the device
        drivers: virt: acrn: hsm: Use kzalloc to avoid info leak in pmcmd_ioctl
        iio: filter: admv8818: Force initialization of SDO
        iio: light: apds9306: fix max_scale_nano values
        iio: dac: ad3552r: clear reset status flag
        iio: adc: ad7192: fix channel select
        iio: adc: at91-sama5d2_adc: fix sama7g5 realbits value
        mm: hugetlb: Add huge page size param to huge_ptep_get_and_clear()
        arm64: hugetlb: Fix huge_ptep_get_and_clear() for non-present ptes
        fs/netfs/read_pgpriv2: skip folio queues without `marks3`
        fs/netfs/read_collect: fix crash due to uninitialized `prev` variable
        kbuild: hdrcheck: fix cross build with clang
        ALSA: hda: realtek: fix incorrect IS_REACHABLE() usage
        nvme-tcp: Fix a C2HTermReq error message
        docs: rust: remove spurious item in `expect` list
        Revert "KVM: e500: always restore irqs"
        Revert "KVM: PPC: e500: Use __kvm_faultin_pfn() to handle page faults"
        Revert "KVM: PPC: e500: Mark "struct page" pfn accessed before dropping mmu_lock"
        Revert "KVM: PPC: e500: Mark "struct page" dirty in kvmppc_e500_shadow_map()"
        KVM: e500: always restore irqs
        uprobes: Fix race in uprobe_free_utask
        selftests/bpf: Clean up open-coded gettid syscall invocations
        x86/mm: Don't disable PCID when INVLPG has been fixed by microcode
        wifi: iwlwifi: pcie: Fix TSO preparation
        Linux 6.12.19

Change-Id: Ia0c2b2c6a95b53a66e21505ed6ba756c6b0a2388
Signed-off-by: Greg Kroah-Hartman <gregkh@google.com>
2025-04-17 03:02:04 -07:00
Panagiotis Foliadis
a362c02577 UPSTREAM: rust: task: fix SAFETY comment in Task::wake_up
The `SAFETY` comment inside the `wake_up` method references
erroneously the `signal_pending` C function instead of the
`wake_up_process` which is actually called.

Fix the comment to reference the correct C function.

Bug: 254441685
Fixes: fe95f58320e6 ("rust: task: adjust safety comments in Task methods")
Signed-off-by: Panagiotis Foliadis <pfoliadis@posteo.net>
Reviewed-by: Charalampos Mitrodimas <charmitro@posteo.net>
Reviewed-by: Alice Ryhl <aliceryhl@google.com>
Link: https://lore.kernel.org/r/20250308-comment-fix-v1-1-4bba709fd36d@posteo.net
[ Slightly reworded. - Miguel ]
Signed-off-by: Miguel Ojeda <ojeda@kernel.org>
(cherry picked from commit 6fbafe1cbed10e53b3cf236a8a1987425206dd8e)
Signed-off-by: Lee Jones <joneslee@google.com>
Change-Id: I9e855cd18e212c82871e597683401da064bcae22
2025-04-15 10:28:36 +01:00
Gary Guo
641ecd0d0a rust: use custom FFI integer types
commit d072acda4862f095ec9056979b654cc06a22cc68 upstream.

Currently FFI integer types are defined in libcore. This commit creates
the `ffi` crate and asks bindgen to use that crate for FFI integer types
instead of `core::ffi`.

This commit is preparatory and no type changes are made in this commit
yet.

Signed-off-by: Gary Guo <gary@garyguo.net>
Link: https://lore.kernel.org/r/20240913213041.395655-4-gary@garyguo.net
[ Added `rustdoc`, `rusttest` and KUnit tests support. Rebased on top of
  `rust-next` (e.g. migrated more `core::ffi` cases). Reworded crate
  docs slightly and formatted. - Miguel ]
Signed-off-by: Miguel Ojeda <ojeda@kernel.org>
Signed-off-by: Greg Kroah-Hartman <gregkh@linuxfoundation.org>
2025-03-13 13:01:49 +01:00
Alice Ryhl
c0d8982f50 ANDROID: rust: add Task methods for priority inheritance
This CL adds methods for manipulating the priority of a task that I have
not upstreamed due to Binder priority inheritance being OOT.

Bug: 388786466
Change-Id: Ife8cd03f12b5dde674e5da4576341555ea6b0179
Signed-off-by: Alice Ryhl <aliceryhl@google.com>
2025-02-14 05:29:44 -08:00
Alice Ryhl
fb05a54492 FROMLIST: rust: task: make Pid type alias public
The Pid type alias represents the integer type used for pids in the
kernel. It's the Rust equivalent to pid_t, and there are various methods
on Task that use Pid as the return type.

Binder needs to use Pid as the type for function arguments and struct
fields in many places. Thus, make the type public so that Binder can
access it.

Reviewed-by: Fiona Behrens <me@kloenk.dev>
Signed-off-by: Alice Ryhl <aliceryhl@google.com>

Bug: 388786466
Link: https://lore.kernel.org/r/20250130-task-pid-pub-v1-1-508808bcfcdc@google.com
Change-Id: Id9d721ef99d5612e2fe55f03fe4562761200479e
Signed-off-by: Alice Ryhl <aliceryhl@google.com>
2025-02-14 05:29:44 -08:00
Alice Ryhl
a3803debda FROMGIT: rust: sync: condvar: Add wait_interruptible_freezable()
To support waiting for a `CondVar` as a freezable process, add a
wait_interruptible_freezable() function.

Binder needs this function in the appropriate places to freeze a process
where some of its threads are blocked on the Binder driver.

[Boqun: Capitalize the title and reword the commit log]

Signed-off-by: Alice Ryhl <aliceryhl@google.com>
Signed-off-by: Boqun Feng <boqun.feng@gmail.com>
Link: https://lore.kernel.org/r/20250204-condvar-freeze-v2-1-804483096260@google.com

Bug: 388786466
(cherry picked from commit 39dfd06783c0e256f420695ea85d95a5f471bc22
 git://git.kernel.org/pub/scm/linux/kernel/git/boqun/linux.git lockdep-for-tip)
Change-Id: I04c41d20868898a3371ebafa54e4afb76edc762e
Signed-off-by: Alice Ryhl <aliceryhl@google.com>
2025-02-14 05:29:44 -08:00
Alice Ryhl
98c8011159 BACKPORT: FROMLIST: task: rust: rework how current is accessed
Introduce a new type called `CurrentTask` that lets you perform various
operations that are only safe on the `current` task. Use the new type to
provide a way to access the current mm without incrementing its
refcount.

With this change, you can write stuff such as

	let vma = current!().mm().lock_vma_under_rcu(addr);

without incrementing any refcounts.

This replaces the existing abstractions for accessing the current pid
namespace. With the old approach, every field access to current involves
both a macro and a unsafe helper function. The new approach simplifies
that to a single safe function on the `CurrentTask` type. This makes it
less heavy-weight to add additional current accessors in the future.

That said, creating a `CurrentTask` type like the one in this patch
requires that we are careful to ensure that it cannot escape the current
task or otherwise access things after they are freed. To do this, I
declared that it cannot escape the current "task context" where I
defined a "task context" as essentially the region in which `current`
remains unchanged. So e.g., release_task() or begin_new_exec() would
leave the task context.

If a userspace thread returns to userspace and later makes another
syscall, then I consider the two syscalls to be different task contexts.
This allows values stored in that task to be modified between syscalls,
even if they're guaranteed to be immutable during a syscall.

Ensuring correctness of `CurrentTask` is slightly tricky if we also want
the ability to have a safe `kthread_use_mm()` implementation in Rust. To
support that safely, there are two patterns we need to ensure are safe:

	// Case 1: current!() called inside the scope.
	let mm;
	kthread_use_mm(some_mm, || {
	    mm = current!().mm();
	});
	drop(some_mm);
	mm.do_something(); // UAF

and:

	// Case 2: current!() called before the scope.
	let mm;
	let task = current!();
	kthread_use_mm(some_mm, || {
	    mm = task.mm();
	});
	drop(some_mm);
	mm.do_something(); // UAF

The existing `current!()` abstraction already natively prevents the
first case: The `&CurrentTask` would be tied to the inner scope, so the
borrow-checker ensures that no reference derived from it can escape the
scope.

Fixing the second case is a bit more tricky. The solution is to
essentially pretend that the contents of the scope execute on an
different thread, which means that only thread-safe types can cross the
boundary. Since `CurrentTask` is marked `NotThreadSafe`, attempts to
move it to another thread will fail, and this includes our fake pretend
thread boundary.

This has the disadvantage that other types that aren't thread-safe for
reasons unrelated to `current` also cannot be moved across the
`kthread_use_mm()` boundary. I consider this an acceptable tradeoff.

Reviewed-by: Boqun Feng <boqun.feng@gmail.com>
Change-Id: Ie49ba5697b16fa8cc3706032a27f62a17184143b
Signed-off-by: Alice Ryhl <aliceryhl@google.com>

Bug: 370906207
Link: https://lore.kernel.org/all/20250115-vma-v12-8-375099ae017a@google.com/
Change-Id: I4c3a4444863d1bf03459db58c14f6a01779c9d14
[alice: removed PidNamespace changes]
Signed-off-by: Alice Ryhl <aliceryhl@google.com>
2025-02-13 09:25:42 +00:00
Alice Ryhl
aaa1316f35 UPSTREAM: rust: task: adjust safety comments in Task methods
The `Task` struct has several safety comments that aren't so great. For
example, the reason that it's okay to read the `pid` is that the field
is immutable, so there is no data race, which is not what the safety
comment says.

Thus, improve the safety comments. Also add an `as_ptr` helper. This
makes it easier to read the various accessors on Task, as `self.0` may
be confusing syntax for new Rust users.

Signed-off-by: Alice Ryhl <aliceryhl@google.com>
Link: https://lore.kernel.org/r/20241015-task-safety-cmnts-v1-1-46ee92c82768@google.com
Signed-off-by: Christian Brauner <brauner@kernel.org>

Bug: 370906207
(cherry picked from commit fe95f58320e6c8dcea3bcb01336b9a7fdd7f684b)
Change-Id: I47b0bec2d4bc0a62ed1b69af49b1dfd83bbc2d51
Signed-off-by: Alice Ryhl <aliceryhl@google.com>
2025-01-16 03:32:01 -08:00
Alice Ryhl
a72394e6fc UPSTREAM: rust: file: add Kuid wrapper
Adds a wrapper around `kuid_t` called `Kuid`. This allows us to define
various operations on kuids such as equality and current_euid. It also
lets us provide conversions from kuid into userspace values.

Rust Binder needs these operations because it needs to compare kuids for
equality, and it needs to tell userspace about the pid and uid of
incoming transactions.

To read kuids from a `struct task_struct`, you must currently use
various #defines that perform the appropriate field access under an RCU
read lock. Currently, we do not have a Rust wrapper for rcu_read_lock,
which means that for this patch, there are two ways forward:

 1. Inline the methods into Rust code, and use __rcu_read_lock directly
    rather than the rcu_read_lock wrapper. This gives up lockdep for
    these usages of RCU.

 2. Wrap the various #defines in helpers and call the helpers from Rust.

This patch uses the second option. One possible disadvantage of the
second option is the possible introduction of speculation gadgets, but
as discussed in [1], the risk appears to be acceptable.

Of course, once a wrapper for rcu_read_lock is available, it is
preferable to use that over either of the two above approaches.

Link: https://lore.kernel.org/all/202312080947.674CD2DC7@keescook/ [1]
Reviewed-by: Benno Lossin <benno.lossin@proton.me>
Reviewed-by: Martin Rodriguez Reboredo <yakoyoku@gmail.com>
Reviewed-by: Trevor Gross <tmgross@umich.edu>
Signed-off-by: Alice Ryhl <aliceryhl@google.com>
Link: https://lore.kernel.org/r/20240915-alice-file-v10-7-88484f7a3dcf@google.com
Signed-off-by: Christian Brauner <brauner@kernel.org>

Bug: 370906207
(cherry picked from commit 8ad1a41f7e23287f07a3516c700bc32501d4f104)
Change-Id: Id6ffcc18f28edd704d1b867a955fa8dad72aaec4
Signed-off-by: Alice Ryhl <aliceryhl@google.com>
2025-01-16 03:32:01 -08:00
Alice Ryhl
14e75b602d UPSTREAM: rust: task: add Task::current_raw
Introduces a safe function for getting a raw pointer to the current
task.

When writing bindings that need to access the current task, it is often
more convenient to call a method that directly returns a raw pointer
than to use the existing `Task::current` method. However, the only way
to do that is `bindings::get_current()` which is unsafe since it calls
into C. By introducing `Task::current_raw()`, it becomes possible to
obtain a pointer to the current task without using unsafe.

Link: https://lore.kernel.org/all/CAH5fLgjT48X-zYtidv31mox3C4_Ogoo_2cBOCmX0Ang3tAgGHA@mail.gmail.com/
Reviewed-by: Benno Lossin <benno.lossin@proton.me>
Reviewed-by: Martin Rodriguez Reboredo <yakoyoku@gmail.com>
Reviewed-by: Trevor Gross <tmgross@umich.edu>
Reviewed-by: Gary Guo <gary@garyguo.net>
Signed-off-by: Alice Ryhl <aliceryhl@google.com>
Link: https://lore.kernel.org/r/20240915-alice-file-v10-2-88484f7a3dcf@google.com
Signed-off-by: Christian Brauner <brauner@kernel.org>

Bug: 370906207
(cherry picked from commit 913f8cf4f376d21082c6c33d49c8c3aa9fb7e83a)
Change-Id: I2379b16bf26b5907834140ca3b62590d542150f0
Signed-off-by: Alice Ryhl <aliceryhl@google.com>
2025-01-16 03:32:01 -08:00
Alice Ryhl
f58fd7a85d UPSTREAM: rust: types: add NotThreadSafe
This introduces a new marker type for types that shouldn't be thread
safe. By adding a field of this type to a struct, it becomes non-Send
and non-Sync, which means that it cannot be accessed in any way from
threads other than the one it was created on.

This is useful for APIs that require globals such as `current` to remain
constant while the value exists.

We update two existing users in the Kernel to use this helper:

 * `Task::current()` - moving the return type of this value to a
   different thread would not be safe as you can no longer be guaranteed
   that the `current` pointer remains valid.
 * Lock guards. Mutexes and spinlocks should be unlocked on the same
   thread as where they were locked, so we enforce this using the Send
   trait.

There are also additional users in later patches of this patchset. See
[1] and [2] for the discussion that led to the introduction of this
patch.

Link: https://lore.kernel.org/all/nFDPJFnzE9Q5cqY7FwSMByRH2OAn_BpI4H53NQfWIlN6I2qfmAqnkp2wRqn0XjMO65OyZY4h6P4K2nAGKJpAOSzksYXaiAK_FoH_8QbgBI4=@proton.me/ [1]
Link: https://lore.kernel.org/all/nFDPJFnzE9Q5cqY7FwSMByRH2OAn_BpI4H53NQfWIlN6I2qfmAqnkp2wRqn0XjMO65OyZY4h6P4K2nAGKJpAOSzksYXaiAK_FoH_8QbgBI4=@proton.me/ [2]
Suggested-by: Benno Lossin <benno.lossin@proton.me>
Reviewed-by: Benno Lossin <benno.lossin@proton.me>
Reviewed-by: Trevor Gross <tmgross@umich.edu>
Reviewed-by: Martin Rodriguez Reboredo <yakoyoku@gmail.com>
Reviewed-by: Björn Roy Baron <bjorn3_gh@protonmail.com>
Reviewed-by: Gary Guo <gary@garyguo.net>
Signed-off-by: Alice Ryhl <aliceryhl@google.com>
Link: https://lore.kernel.org/r/20240915-alice-file-v10-1-88484f7a3dcf@google.com
Signed-off-by: Christian Brauner <brauner@kernel.org>

Bug: 370906207
(cherry picked from commit e7572e5deaf3bc36818f19ba35ac8e0c454c8bac)
Change-Id: I5c0a0f9d0479bb375e5d9f35a026355b82ac5d4e
Signed-off-by: Alice Ryhl <aliceryhl@google.com>
2025-01-16 03:32:01 -08:00
Miguel Ojeda
00280272a0 rust: kernel: remove redundant imports
Rust's `unused_imports` lint covers both unused and redundant imports.
In the upcoming 1.78.0, the lint detects more cases of redundant imports
[1], e.g.:

    error: the item `bindings` is imported redundantly
      --> rust/kernel/print.rs:38:9
       |
    38 |     use crate::bindings;
       |         ^^^^^^^^^^^^^^^ the item `bindings` is already defined by prelude

Most cases are `use crate::bindings`, plus a few other items like `Box`.
Thus clean them up.

Note that, in the `bindings` case, the message "defined by prelude"
above means the extern prelude, i.e. the `--extern` flags we pass.

Link: https://github.com/rust-lang/rust/pull/117772 [1]
Reviewed-by: Alice Ryhl <aliceryhl@google.com>
Link: https://lore.kernel.org/r/20240401212303.537355-3-ojeda@kernel.org
Signed-off-by: Miguel Ojeda <ojeda@kernel.org>
2024-05-05 19:22:25 +02:00
Valentin Obst
af8b18d740 rust: kernel: mark code fragments in docs with backticks
Fix places where comments include code fragments that are not enclosed
in backticks.

Signed-off-by: Valentin Obst <kernel@valentinobst.de>
Reviewed-by: Trevor Gross <tmgross@umich.edu>
Reviewed-by: Martin Rodriguez Reboredo <yakoyoku@gmail.com>
Reviewed-by: Alice Ryhl <aliceryhl@google.com>
Link: https://lore.kernel.org/r/20240131-doc-fixes-v3-v3-8-0c8af94ed7de@valentinobst.de
Signed-off-by: Miguel Ojeda <ojeda@kernel.org>
2024-02-18 21:22:27 +01:00
Valentin Obst
ebf2b8a75a rust: kernel: unify spelling of refcount in docs
Replace instances of 'ref-count[ed]' with 'refcount[ed]' to increase
consistency within the Rust documentation. The latter form is used more
widely in the rest of the kernel:

```console
$ rg '(\*|//).*?\srefcount(|ed)[\s,.]' | wc -l
1605
$ rg '(\*|//).*?\sref-count(|ed)[\s,.]' | wc -l
43
```

(numbers are for commit 052d534373 ("Merge tag 'exfat-for-6.8-rc1'
of git://git.kernel.org/pub/scm/linux/kernel/git/linkinjeon/exfat"))

Signed-off-by: Valentin Obst <kernel@valentinobst.de>
Reviewed-by: Trevor Gross <tmgross@umich.edu>
Reviewed-by: Martin Rodriguez Reboredo <yakoyoku@gmail.com>
Reviewed-by: Alice Ryhl <aliceryhl@google.com>
Link: https://lore.kernel.org/r/20240131-doc-fixes-v3-v3-7-0c8af94ed7de@valentinobst.de
[ Reworded to use the kernel's commit description style. ]
Signed-off-by: Miguel Ojeda <ojeda@kernel.org>
2024-02-18 21:22:27 +01:00
Alice Ryhl
f090f0d0ee rust: sync: update integer types in CondVar
Reduce the chances of compilation failures due to integer type
mismatches in `CondVar`.

When an integer is defined using a #define in C, bindgen doesn't know
which integer type it is supposed to be, so it will just use `u32` by
default (if it fits in an u32). Whenever the right type is something
else, we insert a cast in Rust. However, this means that the code has a
lot of extra casts, and sometimes the code will be missing casts if u32
happens to be correct on the developer's machine, even though the type
might be something else on a different platform.

This patch updates all uses of such constants in
`rust/kernel/sync/condvar.rs` to use constants defined with the right
type. This allows us to remove various unnecessary casts, while also
future-proofing for the case where `unsigned int != u32` (even though
that is unlikely to ever happen in the kernel).

I wrote this patch at the suggestion of Benno in [1].

Link: https://lore.kernel.org/all/nAEg-6vbtX72ZY3oirDhrSEf06TBWmMiTt73EklMzEAzN4FD4mF3TPEyAOxBZgZtjzoiaBYtYr3s8sa9wp1uYH9vEWRf2M-Lf4I0BY9rAgk=@proton.me/ [1]
Suggested-by: Benno Lossin <benno.lossin@proton.me>
Reviewed-by: Tiago Lam <tiagolam@gmail.com>
Reviewed-by: Boqun Feng <boqun.feng@gmail.com>
Reviewed-by: Benno Lossin <benno.lossin@proton.me>
Reviewed-by: Martin Rodriguez Reboredo <yakoyoku@gmail.com>
Signed-off-by: Alice Ryhl <aliceryhl@google.com>
Link: https://lore.kernel.org/r/20240108-rb-new-condvar-methods-v4-4-88e0c871cc05@google.com
[ Added note on the unlikeliness of `sizeof(int)` changing. ]
Signed-off-by: Miguel Ojeda <ojeda@kernel.org>
2024-01-28 20:55:28 +01:00
Alice Ryhl
e7b9b1ff1d rust: sync: add CondVar::wait_timeout
Sleep on a condition variable with a timeout.

This is used by Rust Binder for process freezing. There, we want to
sleep until the freeze operation completes, but we want to be able to
abort the process freezing if it doesn't complete within some timeout.

Note that it is not enough to avoid jiffies by introducing a variant of
`CondVar::wait_timeout` that takes the timeout in msecs because we need
to be able to restart the sleep with the remaining sleep duration if it
is interrupted, and if the API takes msecs rather than jiffies, then
that would require a conversion roundtrip jiffies->msecs->jiffies that
is best avoided.

Reviewed-by: Martin Rodriguez Reboredo <yakoyoku@gmail.com>
Reviewed-by: Tiago Lam <tiagolam@gmail.com>
Reviewed-by: Boqun Feng <boqun.feng@gmail.com>
Signed-off-by: Alice Ryhl <aliceryhl@google.com>
Reviewed-by: Benno Lossin <benno.lossin@proton.me>
Link: https://lore.kernel.org/r/20240108-rb-new-condvar-methods-v4-3-88e0c871cc05@google.com
[ Added `CondVarTimeoutResult` re-export and fixed typo. ]
Signed-off-by: Miguel Ojeda <ojeda@kernel.org>
2024-01-28 20:54:35 +01:00
Miguel Ojeda
bc2e7d5c29 rust: support srctree-relative links
Some of our links use relative paths in order to point to files in the
source tree, e.g.:

    //! C header: [`include/linux/printk.h`](../../../../include/linux/printk.h)
    /// [`struct mutex`]: ../../../../include/linux/mutex.h

These are problematic because they are hard to maintain and do not support
`O=` builds.

Instead, provide support for `srctree`-relative links, e.g.:

    //! C header: [`include/linux/printk.h`](srctree/include/linux/printk.h)
    /// [`struct mutex`]: srctree/include/linux/mutex.h

The links are fixed after `rustdoc` generation to be based on the absolute
path to the source tree.

Essentially, this is the automatic version of Tomonori's fix [1],
suggested by Gary [2].

Suggested-by: Gary Guo <gary@garyguo.net>
Reported-by: FUJITA Tomonori <fujita.tomonori@gmail.com>
Closes: https://lore.kernel.org/r/20231026.204058.2167744626131849993.fujita.tomonori@gmail.com [1]
Fixes: 48fadf4400 ("docs: Move rustdoc output, cross-reference it")
Link: https://lore.kernel.org/rust-for-linux/20231026154525.6d14b495@eugeo/ [2]
Reviewed-by: Martin Rodriguez Reboredo <yakoyoku@gmail.com>
Reviewed-by: Benno Lossin <benno.lossin@proton.me>
Link: https://lore.kernel.org/r/20231215235428.243211-1-ojeda@kernel.org
Signed-off-by: Miguel Ojeda <ojeda@kernel.org>
2023-12-21 20:54:17 +01:00
Miguel Ojeda
c61bcc278b rust: task: remove redundant explicit link
Starting with Rust 1.73.0, `rustdoc` detects redundant explicit
links with its new lint `redundant_explicit_links` [1]:

    error: redundant explicit link target
      --> rust/kernel/task.rs:85:21
       |
    85 |     /// [`current`](crate::current) macro because it is safe.
       |          ---------  ^^^^^^^^^^^^^^ explicit target is redundant
       |          |
       |          because label contains path that resolves to same destination
       |
       = note: when a link's destination is not specified,
               the label is used to resolve intra-doc links
       = note: `-D rustdoc::redundant-explicit-links` implied by `-D warnings`
    help: remove explicit link target
       |
    85 |     /// [`current`] macro because it is safe.

In order to avoid the warning in the compiler upgrade commit,
make it an intra-doc link as the tool suggests.

Link: https://github.com/rust-lang/rust/pull/113167 [1]
Reviewed-by: Finn Behrens <me@kloenk.dev>
Reviewed-by: Alice Ryhl <aliceryhl@google.com>
Reviewed-by: Martin Rodriguez Reboredo <yakoyoku@gmail.com>
Reviewed-by: Vincenzo Palazzo <vincenzopalazzodev@gmail.com>
Link: https://lore.kernel.org/r/20231005210556.466856-2-ojeda@kernel.org
Signed-off-by: Miguel Ojeda <ojeda@kernel.org>
2023-10-15 21:25:08 +02:00
Alice Ryhl
d09a61024f rust: task: add Send marker to Task
When a type also implements `Sync`, the meaning of `Send` is just "this
type may be accessed mutably from threads other than the one it is
created on". That's ok for this type.

Signed-off-by: Alice Ryhl <aliceryhl@google.com>
Reviewed-by: Andreas Hindborg <a.hindborg@samsung.com>
Reviewed-by: Gary Guo <gary@garyguo.net>
Reviewed-by: Martin Rodriguez Reboredo <yakoyoku@gmail.com>
Reviewed-by: Benno Lossin <benno.lossin@proton.me>
Link: https://lore.kernel.org/r/20230531145939.3714886-5-aliceryhl@google.com
Signed-off-by: Miguel Ojeda <ojeda@kernel.org>
2023-05-31 18:53:10 +02:00
Wedson Almeida Filho
8da7a2b743 rust: introduce current
This allows Rust code to get a reference to the current task without
having to increment the refcount, but still guaranteeing memory safety.

Cc: Ingo Molnar <mingo@redhat.com>
Cc: Peter Zijlstra <peterz@infradead.org>
Reviewed-by: Martin Rodriguez Reboredo <yakoyoku@gmail.com>
Signed-off-by: Wedson Almeida Filho <walmeida@microsoft.com>
Link: https://lore.kernel.org/r/20230411054543.21278-10-wedsonaf@gmail.com
Signed-off-by: Miguel Ojeda <ojeda@kernel.org>
2023-04-22 00:20:00 +02:00
Wedson Almeida Filho
313c4281bc rust: add basic Task
It is an abstraction for C's `struct task_struct`. It implements
`AlwaysRefCounted`, so the refcount of the wrapped object is managed
safely on the Rust side.

Cc: Ingo Molnar <mingo@redhat.com>
Cc: Peter Zijlstra <peterz@infradead.org>
Reviewed-by: Martin Rodriguez Reboredo <yakoyoku@gmail.com>
Signed-off-by: Wedson Almeida Filho <walmeida@microsoft.com>
Link: https://lore.kernel.org/r/20230411054543.21278-9-wedsonaf@gmail.com
Signed-off-by: Miguel Ojeda <ojeda@kernel.org>
2023-04-22 00:20:00 +02:00