Skip to contentSkip to conversation

proc: move procfs to what kernfs does

PATCH RESEND In review Christian Brauner 14 participants 351 messages Nov 4 – Nov 16 Page 1 of 3

Subsystems (78)
lore
Share & tools
lore

Christian Brauner

author maintainer
#0 lore raw

v2 cover proc: move procfs to what kernfs does

This series aims to get rid of copying to and from userspace while pinning procfs entries allowing userspace to delay removal as long as it wants.

In essence, it aligns procfs with what kernfs is already doing. That gets rid of a big attack surface and a whole bug class in one go. The bounce buffer will come with some costs but luckily some codepaths (like readdir) have been so criminally slow and buggy that massaging them ends up speeding things up or at least leaving them on par with mainline even with a bounce buffer in the mix.

There was a hackish and very narrow AI solution to a small part of this bug class which was sent off-list. In essence, it used a second buffering mechanism on top of seqfiles which was really nasty. It also didn't address any of the non-seqfile users.

If we want to get rid of the this whole bug class we need a bigger hammer. That means reworking how procfs handles data. So I tried to work through all of that. The series is now in a decent shape (I'm not saying "glorious" as there's so so many warts. If they were ironed out it could be a lot nicer but that's for another day.).

I understand it's big but I think it is nicer to be able to look at the end result since we have some transitory states that are gone at the end of the series.

I have polished this a bit more and have sorted out a few more bugs and tried to clean up some codepaths given the current constraints. Again, I think we could go a lot further there if we wanted to but I think that blows this out of proportion and at some point it becomes difficult to grasp the scope.

So, remove_proc_entry() waits until every call into the procfs entry has returned. Most of those calls copy to or from userspace with the entry pinned.

A reader or writer can induce a page fault in that copy take as long as it wants. For example, with userfaultfd or by punching holes into a memfd over and over. Plus, the callers of remove_proc_entry() like to hold locks while they wait. For example, addrconf holds RTNL when it removes /proc/net/dev_snmp6/<dev> and xt_hashlimit holds a mutex that all network namespaces share.

So every network device with IPv6 gets a /proc/net/dev_snmp6/<dev> that everyone can read, and addrconf_ifdown() removes it with RTNL held. So any local user can keep RTNL for as long as their read stays stalled. Until then no device can be registered, removed or renamed and no network namespace can be created or torn down.

If the caller lacks privileges for userfaultfd a FUSE mount in a user namespace whose daemon never answers is enough to stall the copy. Killing the reader ends it, but until then whoever removes the file sits in D state.

xt_hashlimit removes the proc file of a table with hashlimit_mutex held. Every rule insert in every network namespace takes that mutex and so does network namespace cleanup. cleanup_net() runs on a single workqueue with pernet_ops_rwsem held, so a stalled reader also stops every later network namespace teardown and every module load that registers pernet operations. xt_recent does the same with recent_mutex.

And of course, it's not specific to networking. remove_proc_entry(), proc_remove() and remove_proc_subtree() have over 200 callers and plenty of them hold locks. For example, a stalled reader of /proc/fs/ext4/<dev>/options holds up the unmount of that filesystem with s_umount held, and every sync(2) with it. The same goes for PCI hot-removal, for freeing IRQ descriptors, which CPU bring-up waits on, and for unplugging a USB sound card.

And btw, syzbot has hit removal under locks before (cf. [1]), and the xt_recent deadlock fixed in (1) below is another one.

Stalling the kernel in a copy to or from userspace is a well-known exploitation primitive. It's why unprivileged userfaultfd can't do it by default anymore since v5.11 (d0d4730ac2e4), and FUSE has been used the same way.

This series touches just about every ->proc_read(), ->proc_write() and ->proc_ioctl() in the tree, so I've split it up into seven series. They go out as replies to this mail:

Part 1/7: proc: fix a few old bugs in /proc handlers (51 patches)

Bugs in the handlers and in procfs itself that are a lot older than the conversion and that reviewing it turned up. Most of them are for stable. They come first so they can go there on their own and the conversion doesn't have to bother with that crap.

Part 2/7: proc: let procfs own the data path (23 patches)

The procfs side. procfs owns the seq_file of an entry, copies in writes, copies out reads and copies ioctl arguments in and out, and only calls into an entry with it pinned. The open files procfs has to know and the wait queue a pollable entry is polled on live in an open node that only those entries get, the entry is pinned around the vm_operations of its mappings, and lockdep checks the pin. proc_create_seq() and friends and the plain seq_file users are switched over here too.

Part 3/7: proc: convert the arch and platform entries (23 patches) Part 4/7: proc: convert the driver entries (26 patches)
Part 5/7: proc: convert the fs, kernel and mm entries (30 patches) Part 6/7: proc: convert the net entries and the kfifo samples (13 patches)

Part 7/7: proc: drop the __user methods (6 patches)

Drops the old methods. kcore, kmsg and the kpage files, which are never removed and keep reading straight into userspace, get file_operations of their own, so nothing in struct proc_ops takes a __user pointer anymore, and the new methods get the names kernfs uses, ->proc_read(), ->proc_write() and ->proc_ioctl(). The last patch takes the poll_table away from ->proc_poll(). This needs all four conversion series.

Parts 1 and 2 are the base. Parts 3 to 6 go on top of part 2 in any order and don't depend on each other. Part 7 needs all four.

The series should all indicate cleanly what dependencies they have so b4 should be able to pull it for review.

With all of it on a KASAN and lockdep kernel the removal selftests of every part pass, the proc, pktgen and allocinfo selftests behave like without it and the bugs from (1) that reproduce in a VM are gone. Every patch builds on its own on x86_64 and i386, and with W=1 on the architectures it touches.

[1]: https://lore.kernel.org/r/[email protected]
[2]: https://lore.kernel.org/r/[email protected]

---
Link to v1: https://patch.msgid.link/20261102-defizit-jobaussicht-kurios-7016c6e67442@brauner

Signature · 1 line
Christian Brauner <[email protected]>
author maintainer
#1 lore raw

v2 cover proc: fix a few old bugs in /proc handlers (Part 1/7)

Part 1/7 of "proc: move procfs to what kernfs does", the base of the other six parts:

https://patch.msgid.link/20261104-work-procfs-v2-0-b45cd5789ac5@brauner

Moving procfs to what kernfs does touches just about every ->proc_read(), ->proc_write() and ->proc_ioctl() in the tree. Reviewing that turned up bugs that have nothing to do with the conversion and are a lot older. They go first so they can go to stable on their own. Four selftests come with them.

In procfs itself:

- readdir resumed a listing at a counted position, so an entry that came or went in between repeated or skipped one, and it ended a listing early when the entry it was emitting went away. It resumes after the last name now, like kernfs. /proc/sys had the same bug.
- /proc/sys readdir ended a listing early at an entry that was being unregistered, so getdents64() reported EOF with entries left.
- /proc/sys copied to and from userspace with the table held, so a read, write or getdents64() that faults for as long as userspace wants kept unregister_sysctl_table() waiting, which addrconf calls under RTNL.
- proc_sys_make_inode() read the table after it had dropped sysctl_lock.
- a symlink's entry stayed pinned while readlink() copied it out, so a faulting readlink() held up remove_proc_entry(). ALSA removes its card links with snd_card_mutex held.
- name resolution walked through regular files, and pktgen lets userspace pick names, so an unprivileged user could hang an entry below another file and get it freed. pktgen refuses a '/' now.
- proc_register() WARNed on a duplicate name, which pktgen's names can provoke.
- proc_remove() removed by name, so removing an entry that was already gone could take out a different one.
- the parent of entries a dying network namespace left in /proc/net was freed silently. procfs warns now.
- on NOMMU every /proc file could be mapped privately, which reads it with nommu_region_sem held, and /proc/maps takes that lock. Any user could hang the machine.
- sunrpc queued the pollers of its channel files on a wait queue in the per-namespace cache_detail, which is freed with the namespace. Back to one static queue here, the conversion makes procfs own the queues.
- vmcore_cleanup() could run twice at once.

In the handlers:

- PCI/proc and isapnp truncated the position to an int, so a pwrite() or pread() at a huge offset went negative and accessed config space far outside the file.
- dasd looked in front of its buffer on an empty write.
- toshiba_acpi's brightness and fan write checks could never fail.
- simdisk read the file name without the lock that protects it, so a reader could copy out memory a concurrent detach had freed.
- rtas_flash read past its validate message, and rtasd handed out what vmalloc() left in its log buffer.
- ALSA's info layer let a write past the end of a data entry through unclamped.
- BusLogic, ips and libipw returned 0 from writes, so stdio writers retry forever.
- the scsi host files and um's /proc/exitcode parsed writes without NUL-terminating them.
- ntfs3 tripped the page allocator's warning on a huge label write.
- esas2r took the lengths of its HBA, SMP and firmware ioctls from userspace unchecked, through a file everyone can open.
- powerpc's copy_oldmem_page() didn't check ioremap_cache() and only recovered from a machine check for read(), the pseries ofdt parser read past its input, and lparcfg reported a failed hcall as a huge write.
- alloc_tag removed /proc/allocinfo with the codetag module lock held when a module's tags couldn't be reserved, and a reader of the file takes that lock with the entry pinned, so the module load and the reader waited for each other for good.
- esas2r copied the kernel addresses of the adapter, its pci_dev and its Scsi_Host out through the 0444 ATTONode.
- cs46xx stored the chip in the private data of its region files and read it back as the region.
- isapnp went on talking to whatever device the card had selected, and unlocked a mutex it never took, when isapnp_cfg_begin() refused a logical device number.
- simdisk freed the gendisk before it removed the entry, so a write in between set the capacity of a freed disk.
- the pseries ofdt commands leaked a node reference per property command, and lockd handed out the NUL behind "Y\n".
- lparcfg and psi overwrote the last byte of a write to terminate it, so a write without a trailing newline lost a character.
- the sparc LED and rtas progress files consumed only the start of a write, so a looping writer sent the rest as a second command.
- profiling reported success when /proc/profile couldn't be created, and zorro sized its files like a zorro_dev instead of the ConfigDev they serve.

The xt_recent deadlock v1 fixed here goes in through netfilter instead.

The procfs, sysctl, readlink, pktgen, sunrpc, PCI and duplicate name bugs reproduce on a KASAN and lockdep kernel in a VM and are gone with the series. The rest is build tested.

---
Changes in v2:
- thirteen more fixes that the review of v1 turned up: alloc_tag,
esas2r, cs46xx, isapnp, simdisk, pseries ofdt, lockd, lparcfg, psi,
the sparc LED, rtas progress, profiling and zorro
- the NOMMU, crash_dump and lparcfg patches say more about the bug
- new patch: sysctl readdir ended a listing early when an entry was
being unregistered, pre-existing
- the xt_recent patch is dropped, Cen Zhang's fix for the same lock is
on its way through netfilter
- the readdir churn selftests skip instead of failing without
/dev/net/tun, the sysctl removal selftest seeks past the dots first so
its fault lands in an entry, the selftests' Makefile, .gitignore and
config lines sit in the series that adds each test
- struct sysctl_dirent loses its unused mode
- Reviewed-by and Acked-by from Rafael, Takashi and Chuck
- rebased onto v7.4-rc1
- Link to v1: https://patch.msgid.link/[email protected]

---
Christian Brauner (51):
alloc_tag: don't remove /proc/allocinfo under the codetag module lock
scsi: esas2r: don't copy kernel pointers out in EXPRESS_IOCTL_GET_MOD_INFO
ALSA: cs46xx: hand the region to the region proc files
PNP: isapnp: don't go on when isapnp_cfg_begin() fails
xtensa: simdisk: remove the proc entry before the disk powerpc/pseries: put the node that the ofdt property commands look up
lockd: don't hand out the terminator of nlm_end_grace powerpc/pseries/lparcfg: don't drop the last byte of a write
profiling: report it when /proc/profile can't be created
zorro: size the proc files like what they serve
sparc: led: consume the whole write
powerpc/rtas: consume the whole write to /proc/powerpc/rtas/progress sched/psi: don't drop the last byte of a trigger write
proc: sysctl: don't stop readdir at an entry that is being unregistered PCI/proc: don't truncate the position of config space accesses
PNP: isapnp: don't read past the end of the buffer on a large pread() s390/dasd: don't look in front of the buffer on an empty write platform/x86: toshiba_acpi: reject malformed brightness and fan writes
xtensa: simdisk: don't read the file name without the lock powerpc/rtas_flash: don't read past the validate message powerpc/rtasd: zero the error log buffer
ALSA: info: don't write past the end of a data entry
scsi: BusLogic: don't return 0 from writes to the proc file
scsi: ips: don't return 0 from writes to the proc file
wifi: libipw: don't return 0 from writes to debug_level
scsi: core: NUL-terminate what is written to the host proc files
um: NUL-terminate what is written to /proc/exitcode
ntfs3: don't warn when a huge label is written
proc: don't walk through a non-directory when resolving a name
net: pktgen: reject device names with a '/'
proc: don't WARN about a name that is already registered
proc: resume readdir after the last name it returned selftests/proc: check a /proc listing while entries come and go
proc: let proc_remove() remove the entry it was given
proc: warn about entries left in /proc/net of a dying namespace
proc: don't let NOMMU map procfs files
proc/vmcore: don't let vmcore_cleanup() run twice at once powerpc/crash_dump: check ioremap_cache() in copy_oldmem_page() powerpc/crash_dump: recover from a machine check in copy_oldmem_page()
sunrpc: make queue_wait a global wait queue again
scsi: esas2r: bound the lengths of the HBA, SMP and firmware ioctls powerpc/pseries: bound the lengths in the ofdt property parser powerpc/pseries/lparcfg: return h_get_ppp()'s status as a long
proc: sysctl: resume readdir after the last name it returned selftests/proc: check a sysctl listing while entries come and go
proc: sysctl: copy to and from userspace without holding the table
proc: sysctl: look at the table under sysctl_lock when creating an inode
proc: sysctl: don't hold the tables while readdir copies to userspace selftests/proc: check that faulting sysctl accesses don't hold up removal
proc: don't pin a symlink's entry while readlink() copies it out selftests/proc: check that a faulting readlink() doesn't hold up removal

 arch/powerpc/kernel/crash_dump.c                   |   6 +-
 arch/powerpc/kernel/rtas-proc.c                    |   3 +-
 arch/powerpc/kernel/rtas_flash.c                   |   2 +-
 arch/powerpc/kernel/rtasd.c                        |   2 +-
 arch/powerpc/platforms/pseries/lparcfg.c           |   7 +-
 arch/powerpc/platforms/pseries/reconfig.c          |  24 +-
 arch/sparc/kernel/led.c                            |   3 +-
 arch/um/kernel/exitcode.c                          |   3 +-
 arch/xtensa/platforms/iss/simdisk.c                |  28 +-
 drivers/net/wireless/intel/ipw2x00/libipw_module.c |   2 +-
 drivers/pci/proc.c                                 |  15 +-
 drivers/platform/x86/toshiba_acpi.c                |   8 +-
 drivers/pnp/isapnp/core.c                          |  16 +-
 drivers/pnp/isapnp/proc.c                          |  11 +-
 drivers/s390/block/dasd.c                          |   2 +-
 drivers/scsi/BusLogic.c                            |   2 +-
 drivers/scsi/esas2r/esas2r.h                       |   2 +-
 drivers/scsi/esas2r/esas2r_ioctl.c                 |  48 ++-
 drivers/scsi/esas2r/esas2r_main.c                  |   3 +-
 drivers/scsi/ips.c                                 |   2 +-
 drivers/scsi/scsi_proc.c                           |   1 +
 drivers/zorro/proc.c                               |   2 +-
 fs/lockd/procfs.c                                  |   2 +-
 fs/ntfs3/super.c                                   |  11 +-
 fs/proc/generic.c                                  | 174 ++++++---
 fs/proc/inode.c                                    |  38 +-
 fs/proc/internal.h                                 |   1 +
 fs/proc/proc_net.c                                 |   7 +
 fs/proc/proc_sysctl.c                              | 388 ++++++++++++++-------
 fs/proc/root.c                                     |   1 +
 fs/proc/vmcore.c                                   |   5 +
 include/linux/sunrpc/cache.h                       |   1 -
 kernel/profile.c                                   |   8 +-
 kernel/sched/psi.c                                 |   4 +-
 mm/alloc_tag.c                                     |  27 +-
 net/core/pktgen.c                                  |   4 +
 net/sunrpc/cache.c                                 |  12 +-
 sound/core/info.c                                  |   2 +
 sound/isa/es18xx.c                                 |   6 +-
 sound/pci/cs46xx/cs46xx_lib.c                      |   2 +-
 tools/testing/selftests/proc/.gitignore            |   4 +
 tools/testing/selftests/proc/Makefile              |   4 +
 tools/testing/selftests/proc/config                |   9 +
 tools/testing/selftests/proc/proc-readdir-churn.c  | 240 +++++++++++++
 .../selftests/proc/proc-remove-slow-readlink.c     | 191 ++++++++++
 .../selftests/proc/proc-remove-slow-sysctl.c       | 215 ++++++++++++
 .../selftests/proc/proc-sysctl-readdir-churn.c     | 152 ++++++++
 47 files changed, 1420 insertions(+), 280 deletions(-)

---
base-commit: 6628e7d4c6b25c8d18f1345e3a20d21829aae7e4
change-id: 20261101-work-procfs-bugfixes-054d00028491

author maintainer
#2 lore raw

PATCH RESEND v2 1/51 alloc_tag: don't remove /proc/allocinfo under the codetag module lock

codetag_alloc_module_section() takes the codetag type's mod_lock for writing and calls reserve_module_tags() with it held. When that can't reserve the tags, because the section's alignment doesn't fit, because there are too many tags for the page flag bits or because the memory for them can't be allocated, it shuts memory allocation profiling down and removes /proc/allocinfo, still with mod_lock held.

remove_proc_entry() waits until every reader of the entry has let go of it, and a reader of /proc/allocinfo takes mod_lock for reading in allocinfo_start() while it holds the entry. So a module load that hits one of those paths while /proc/allocinfo is being read waits for the reader and the reader waits for the module load, for good.

Let a work item remove the entry in that case. The profiling is shut down right away like before, the file just goes a moment later.

Fixes 4835f747d3ed ("alloc_tag: support for page allocation tag compression")
---
 mm/alloc_tag.c | 27 ++++++++++++++++++++++++---
 1 file changed, 24 insertions(+), 3 deletions(-)
mm/alloc_tag.c +24 -3
index 82e2c3448dcf..7d7ad6704953 100644
@@ -15,6 +15,7 @@
 #include <linux/seq_file.h>
 #include <linux/string_choices.h>
 #include <linux/vmalloc.h>
+#include <linux/workqueue.h>
 #include <linux/kmemleak.h>
 #include <uapi/linux/alloc_tag.h>
 
@@ -604,6 +605,26 @@ static void shutdown_mem_profiling(bool remove_file)
 	mem_profiling_support = false;
 }
 
+static void remove_allocinfo_file(struct work_struct *work)
+{
+	remove_proc_entry(ALLOCINFO_FILE_NAME, NULL);
+}
+static DECLARE_WORK(remove_allocinfo_work, remove_allocinfo_file);
+
+/*
+ * A module's tags are reserved with the codetag module lock held for
+ * writing, and a reader of /proc/allocinfo takes that lock with the entry
+ * pinned. Removing the entry there would wait for that reader for good, so
+ * let a work item do it.
+ */
+static void shutdown_mem_profiling_async(void)
+{
+	if (!mem_profiling_support)
+		return;
+	shutdown_mem_profiling(false);
+	schedule_work(&remove_allocinfo_work);
+}
+
 void __init alloc_tag_sec_init(void)
 {
 	struct alloc_tag *last_codetag;
@@ -855,7 +876,7 @@ static void *reserve_module_tags(struct module *mod, unsigned long size,
 		align = 1;
 
 	if (!ensure_alignment(align, &prepend)) {
-		shutdown_mem_profiling(true);
+		shutdown_mem_profiling_async();
 		pr_err("%s: alignment %lu is incompatible with allocation tag indexing. Memory allocation profiling is disabled!\n",
 			mod->name, align);
 		return ERR_PTR(-EINVAL);
@@ -905,14 +926,14 @@ unlock:
 
 		module_tags.size = offset + size;
 		if (mem_alloc_profiling_enabled() && !tags_addressable()) {
-			shutdown_mem_profiling(true);
+			shutdown_mem_profiling_async();
 			pr_warn("With module %s there are too many tags to fit in %d page flag bits. Memory allocation profiling is disabled!\n",
 				mod->name, NR_UNUSED_PAGEFLAG_BITS);
 		}
 
 		grow_res = vm_module_tags_populate();
 		if (grow_res) {
-			shutdown_mem_profiling(true);
+			shutdown_mem_profiling_async();
 			pr_err("Failed to allocate memory for allocation tags in the module %s. Memory allocation profiling is disabled!\n",
 			       mod->name);
 			return ERR_PTR(grow_res);
Signature · 1 line
2.53.0
reviewer
#3 lore raw

Re: [PATCH RESEND v2 01/51] alloc_tag: don't remove /proc/allocinfo under the codetag module lock

Cc Suren

Hi Christian

Quoted 13 lines · Christian Brauner

codetag_alloc_module_section() takes the codetag type's mod_lock for writing and calls reserve_module_tags() with it held. When that can't reserve the tags, because the section's alignment doesn't fit, because there are too many tags for the page flag bits or because the memory for them can't be allocated, it shuts memory allocation profiling down and removes /proc/allocinfo, still with mod_lock held.

remove_proc_entry() waits until every reader of the entry has let go of it, and a reader of /proc/allocinfo takes mod_lock for reading in allocinfo_start() while it holds the entry. So a module load that hits one of those paths while /proc/allocinfo is being read waits for the reader and the reader waits for the module load, for good.

Quoted 6 lines

Let a work item remove the entry in that case. The profiling is shut down right away like before, the file just goes a moment later.

Fixes 4835f747d3ed ("alloc_tag: support for page allocation tag compression")

Thanks.

is this a problem you have hit in practice?
Sashiko discovered this issue earlier and reported it as follows:

mm/alloc_tag.c static void *reserve_module_tags(struct module *mod, unsigned long size, · line 954

Quoted 11 lines
mm/alloc_tag.c +1 -1
index 2070e682fe106..112a014d4b890 100644
@@ -950,10 +950,12 @@ static void *reserve_module_tags(struct module *mod, unsigned long size,
 		int grow_res;
 
 		module_tags.size = offset + size;
-		if (mem_alloc_profiling_enabled() && !tags_addressable()) {
+		if (!tags_addressable()) {
 			shutdown_mem_profiling(true);

This is a pre-existing issue, but does this shutdown_mem_profiling(true) call introduce an AB-BA deadlock between /proc/allocinfo file readers (pde->in_use) and module loading (cttype->mod_lock)?
A user reading /proc/allocinfo acquires the procfs in_use reference in use_pde(), then blocks on down_read(&alloc_tag_cttype->mod_lock) in allocinfo_start().
Concurrently, if a module loads and tags_addressable() fails, codetag_alloc_module_section() holds down_write(&cttype->mod_lock) and calls shutdown_mem_profiling(true), which removes the proc entry. This removal waits indefinitely for the in_use reference to drop to zero, hanging both procfs reads and module loading.

mm/alloc_tag.c static void *reserve_module_tags(struct module *mod, unsigned long size, · line 961

Quoted 9 lines
mm/alloc_tag.c +4 -2
-			pr_warn("With module %s there are too many tags to fit in %d page flag bits. Memory allocation profiling is disabled!\n",
-				mod->name, NR_UNUSED_PAGEFLAG_BITS);
+			pr_warn_once("With module %s there are too many tags to fit in %d page flag bits. Memory allocation profiling is disabled!\n",
+				     mod->name, NR_UNUSED_PAGEFLAG_BITS);
+			release_module_tags(mod, false);
+			return ERR_PTR(-EAGAIN);
 		}
 
 		grow_res = vm_module_tags_populate();

I previously sent a patch with a comparable idea, though Sashiko remained unconvinced.

[patch]: https://lore.kernel.org/all/[email protected]/

[Sashiko's objections]: https://sashiko.dev/#/patchset/[email protected]

Could this patch perhaps wait for mine? No worries if this is inconvenient.

Best regards
Hao

Quoted 70 lines
---
 mm/alloc_tag.c | 27 ++++++++++++++++++++++++---
 1 file changed, 24 insertions(+), 3 deletions(-)
mm/alloc_tag.c +24 -3
index 82e2c3448dcf..7d7ad6704953 100644
@@ -15,6 +15,7 @@
 #include <linux/seq_file.h>
 #include <linux/string_choices.h>
 #include <linux/vmalloc.h>
+#include <linux/workqueue.h>
 #include <linux/kmemleak.h>
 #include <uapi/linux/alloc_tag.h>
 
@@ -604,6 +605,26 @@ static void shutdown_mem_profiling(bool remove_file)
 	mem_profiling_support = false;
 }
 
+static void remove_allocinfo_file(struct work_struct *work)
+{
+	remove_proc_entry(ALLOCINFO_FILE_NAME, NULL);
+}
+static DECLARE_WORK(remove_allocinfo_work, remove_allocinfo_file);
+
+/*
+ * A module's tags are reserved with the codetag module lock held for
+ * writing, and a reader of /proc/allocinfo takes that lock with the entry
+ * pinned. Removing the entry there would wait for that reader for good, so
+ * let a work item do it.
+ */
+static void shutdown_mem_profiling_async(void)
+{
+	if (!mem_profiling_support)
+		return;
+	shutdown_mem_profiling(false);
+	schedule_work(&remove_allocinfo_work);
+}
+
 void __init alloc_tag_sec_init(void)
 {
 	struct alloc_tag *last_codetag;
@@ -855,7 +876,7 @@ static void *reserve_module_tags(struct module *mod, unsigned long size,
 		align = 1;
 
 	if (!ensure_alignment(align, &prepend)) {
-		shutdown_mem_profiling(true);
+		shutdown_mem_profiling_async();
 		pr_err("%s: alignment %lu is incompatible with allocation tag indexing. Memory allocation profiling is disabled!\n",
 			mod->name, align);
 		return ERR_PTR(-EINVAL);
@@ -905,14 +926,14 @@ unlock:
 
 		module_tags.size = offset + size;
 		if (mem_alloc_profiling_enabled() && !tags_addressable()) {
-			shutdown_mem_profiling(true);
+			shutdown_mem_profiling_async();
 			pr_warn("With module %s there are too many tags to fit in %d page flag bits. Memory allocation profiling is disabled!\n",
 				mod->name, NR_UNUSED_PAGEFLAG_BITS);
 		}
 
 		grow_res = vm_module_tags_populate();
 		if (grow_res) {
-			shutdown_mem_profiling(true);
+			shutdown_mem_profiling_async();
 			pr_err("Failed to allocate memory for allocation tags in the module %s. Memory allocation profiling is disabled!\n",
 			       mod->name);
 			return ERR_PTR(grow_res);
author maintainer
#4 lore raw

Re: [PATCH RESEND v2 01/51] alloc_tag: don't remove /proc/allocinfo under the codetag module lock

Quoted 1 line · Hao Ge

is this a problem you have hit in practice?

No? For alloc tagging it might be reasonable somehow but 90% of these problems I haven't hid in practice. But they're all reproed.

Quoted 5 lines

I previously sent a patch with a comparable idea, though Sashiko remained unconvinced.

[patch]: https://lore.kernel.org/all/[email protected]/

Could this patch perhaps wait for mine? No worries if this is inconvenient.

I don't care. We just need to keep straight what was fixed.

#5 lore raw

Re: [PATCH RESEND v2 01/51] alloc_tag: don't remove /proc/allocinfo under the codetag module lock

In reply to Christian Brauner
kernel test robot noticed the following build warnings:

Hi Christian,

kernel test robot noticed the following build warnings:

[auto build test WARNING on 6628e7d4c6b25c8d18f1345e3a20d21829aae7e4]

url:    https://github.com/intel-lab-lkp/linux/commits/Christian-Brauner/alloc_tag-don-t-remove-proc-allocinfo-under-the-codetag-module-lock/20261104-200606
base:   6628e7d4c6b25c8d18f1345e3a20d21829aae7e4
patch link:    https://lore.kernel.org/r/20261104-work-procfs-bugfixes-v2-1-021c84d852e0%40kernel.org
patch subject: [PATCH RESEND v2 01/51] alloc_tag: don't remove /proc/allocinfo under the codetag module lock
config: sh-randconfig-1001-20261105 (https://download.01.org/0day-ci/archive/20261105/[email protected]/config)
compiler: sh4-linux-gcc (GCC) 16.2.0
reproduce (this is a W=1 build): (https://download.01.org/0day-ci/archive/20261105/[email protected]/reproduce)

If you fix the issue in a separate patch/commit (i.e. not just a new version of the same patch/commit), kindly add following tags
| Reported-by: kernel test robot <[email protected]>
| Closes: https://lore.kernel.org/oe-kbuild-all/[email protected]/

All warnings (new ones prefixed by >>):

>> mm/alloc_tag.c:620:13: warning: 'shutdown_mem_profiling_async' defined but not used [-Wunused-function]

620 | static void shutdown_mem_profiling_async(void)
| ^~~~~~~~~~~~~~~~~~~~~~~~~~~~

vim +/shutdown_mem_profiling_async +620 mm/alloc_tag.c

613
614 /*
615 * A module's tags are reserved with the codetag module lock held for
616 * writing, and a reader of /proc/allocinfo takes that lock with the entry
617 * pinned. Removing the entry there would wait for that reader for good, so
618 * let a work item do it.
619 */

 > 620	static void shutdown_mem_profiling_async(void)

621 {
622 if (!mem_profiling_support)
623 return;
624 shutdown_mem_profiling(false);
625 schedule_work(&remove_allocinfo_work);
626 }
627

--
0-DAY CI Kernel Test Service
https://github.com/intel/lkp-tests/wiki

#6 lore raw

Re: [PATCH RESEND v2 01/51] alloc_tag: don't remove /proc/allocinfo under the codetag module lock

In reply to Christian Brauner
Thank you for your contribution! Sashiko AI review found 1 potential issue(s) to consider: - [Low] alloc_tag: unused function shutdown_mem_profiling_async() when !CONFIG_MODULES --

Thank you for your contribution! Sashiko AI review found 1 potential issue(s) to consider:
- [Low] alloc_tag: unused function shutdown_mem_profiling_async() when !CONFIG_MODULES --

commit ec0095b3ecdd2d01651f48bc80cc81d976e06106
Author: Christian Brauner <[email protected]>

alloc_tag: don't remove /proc/allocinfo under the codetag module lock

This commit defers removing /proc/allocinfo to a work item when reserve_module_tags() fails, avoiding a deadlock between remove_proc_entry() waiting on active procfs readers and allocinfo_start() waiting on the codetag module lock.

Quoted 4 lines
mm/alloc_tag.c +0 -0
index 82e2c3448dcf2..7d7ad67049537 100644

[ ... ]

Quoted 13 lines
mm/alloc_tag.c +9 -0
@@ -604,6 +605,26 @@ static void shutdown_mem_profiling(bool remove_file)
 	mem_profiling_support = false;
 }
 
+static void remove_allocinfo_file(struct work_struct *work)
+{
+	remove_proc_entry(ALLOCINFO_FILE_NAME, NULL);
+}
+static DECLARE_WORK(remove_allocinfo_work, remove_allocinfo_file);
+
+/*
+ * A module's tags are reserved with the codetag module lock held for
+ * writing, and a reader of /proc/allocinfo takes that lock with the entry

mm/alloc_tag.c static void shutdown_mem_profiling(bool remove_file) · line 626

Quoted 10 lines
mm/alloc_tag.c +10 -0
+ * pinned. Removing the entry there would wait for that reader for good, so
+ * let a work item do it.
+ */
+static void shutdown_mem_profiling_async(void)
+{
+	if (!mem_profiling_support)
+		return;
+	shutdown_mem_profiling(false);
+	schedule_work(&remove_allocinfo_work);
+}

[Severity: Low]
All callers of shutdown_mem_profiling_async() are in reserve_module_tags(), which is inside the #ifdef CONFIG_MODULES block further down in mm/alloc_tag.c.

When building with CONFIG_MEM_ALLOC_PROFILING=y and CONFIG_MODULES=n, will defining remove_allocinfo_file(), remove_allocinfo_work, and shutdown_mem_profiling_async() outside #ifdef CONFIG_MODULES trigger an unused-function compiler warning?

Signature · 1 line
Sashiko AI review · https://sashiko.dev/#/patchset/[email protected]?part=1
author maintainer
#7 lore raw

PATCH RESEND v2 2/51 scsi: esas2r: don't copy kernel pointers out in EXPRESS_IOCTL_GET_MOD_INFO

In reply to Christian Brauner

EXPRESS_IOCTL_GET_MOD_INFO fills in the addresses of the adapter, its pci_dev and its Scsi_Host and copies the whole struct back to userspace. Nothing in userspace can do anything with those addresses, and the ioctl is reachable through /proc/scsi/esas2r/ATTONode, which is created with mode 0444. Only pass the host number.

Fixes 26780d9e12ed ("[SCSI] esas2r: ATTO Technology ExpressSAS 6G SAS/SATA RAID Adapter Driver")
---
 drivers/scsi/esas2r/esas2r_ioctl.c | 7 ++++---
 1 file changed, 4 insertions(+), 3 deletions(-)
drivers/scsi/esas2r/esas2r_ioctl.c +4 -3
index 3f7c1d131ec3..c93d9265e100 100644
@@ -1468,9 +1468,10 @@ int esas2r_ioctl_handler(void *hostdata, unsigned int cmd, void __user *arg)
 
 	case EXPRESS_IOCTL_GET_MOD_INFO:
 
-		ioctl->data.modinfo.adapter = a;
-		ioctl->data.modinfo.pci_dev = a->pcid;
-		ioctl->data.modinfo.scsi_host = a->host;
+		/* these are kernel pointers, userspace has no use for them */
+		ioctl->data.modinfo.adapter = NULL;
+		ioctl->data.modinfo.pci_dev = NULL;
+		ioctl->data.modinfo.scsi_host = NULL;
 		ioctl->data.modinfo.host_no = a->host->host_no;
 
 		break;
Signature · 1 line
2.53.0
#8 lore raw

Re: [PATCH RESEND v2 02/51] scsi: esas2r: don't copy kernel pointers out in EXPRESS_IOCTL_GET_MOD_INFO

Sashiko has reviewed this patch and found no issues.
Quoted 9 lines

EXPRESS_IOCTL_GET_MOD_INFO fills in the addresses of the adapter, its pci_dev and its Scsi_Host and copies the whole struct back to userspace. Nothing in userspace can do anything with those addresses, and the ioctl is reachable through /proc/scsi/esas2r/ATTONode, which is created with mode 0444. Only pass the host number.

Fixes 26780d9e12ed ("[SCSI] esas2r: ATTO Technology ExpressSAS 6G SAS/SATA RAID Adapter Driver")

Sashiko has reviewed this patch and found no issues.

Signature · 1 line
Sashiko AI review · https://sashiko.dev/#/patchset/[email protected]?part=2
author maintainer
#9 lore raw

PATCH RESEND v2 3/51 ALSA: cs46xx: hand the region to the region proc files

In reply to Christian Brauner

snd_cs46xx_proc_init() stores the chip in the private data of the five region entries, but snd_cs46xx_io_read() reads that back as the region, so a read of /proc/asound/cardN/CS46xx_BA0 and friends copies from whatever sits at the region's offset in struct snd_cs46xx instead of the mapped registers. Store the region.

Fixes 1da177e4c3f4 ("Linux-2.6.12-rc2")
---
 sound/pci/cs46xx/cs46xx_lib.c | 2 +-
 1 file changed, 1 insertion(+), 1 deletion(-)
sound/pci/cs46xx/cs46xx_lib.c +1 -1
index 797a5f09cade..efc7df444cb5 100644
@@ -2764,7 +2764,7 @@ static int snd_cs46xx_proc_init(struct snd_card *card, struct snd_cs46xx *chip)
 		struct snd_cs46xx_region *region = &chip->region.idx[idx];
 		if (! snd_card_proc_new(card, region->name, &entry)) {
 			entry->content = SNDRV_INFO_CONTENT_DATA;
-			entry->private_data = chip;
+			entry->private_data = region;
 			entry->c.ops = &snd_cs46xx_proc_io_ops;
 			entry->size = region->size;
 			entry->mode = S_IFREG | 0400;
Signature · 1 line
2.53.0
#10 lore raw

Re: [PATCH RESEND v2 03/51] ALSA: cs46xx: hand the region to the region proc files

Sashiko has reviewed this patch and found no issues.
Quoted 9 lines

snd_cs46xx_proc_init() stores the chip in the private data of the five region entries, but snd_cs46xx_io_read() reads that back as the region, so a read of /proc/asound/cardN/CS46xx_BA0 and friends copies from whatever sits at the region's offset in struct snd_cs46xx instead of the mapped registers. Store the region.

Fixes 1da177e4c3f4 ("Linux-2.6.12-rc2")

Sashiko has reviewed this patch and found no issues.

Signature · 1 line
Sashiko AI review · https://sashiko.dev/#/patchset/[email protected]?part=3
Reviewed-by on v2 3/51
#11 lore raw

Re: [PATCH RESEND v2 03/51] ALSA: cs46xx: hand the region to the region proc files

In reply to Christian Brauner
Quoted 10 lines · Christian Brauner

snd_cs46xx_proc_init() stores the chip in the private data of the five region entries, but snd_cs46xx_io_read() reads that back as the region, so a read of /proc/asound/cardN/CS46xx_BA0 and friends copies from whatever sits at the region's offset in struct snd_cs46xx instead of the mapped registers. Store the region.

Fixes 1da177e4c3f4 ("Linux-2.6.12-rc2")

thanks,

Takashi

author maintainer
#12 lore raw

PATCH RESEND v2 4/51 PNP: isapnp: don't go on when isapnp_cfg_begin() fails

In reply to Christian Brauner

isapnp_cfg_begin() refuses a logical device number above 10 and a bad card number with -EINVAL before it takes isapnp_cfg_mutex. The callers that read and write the device's configuration, the proc file included, don't look at that: they go on talking to whatever device the card currently has selected and then unlock a mutex they never took in isapnp_cfg_end(). isapnp_create_device() hands out logical device numbers without a bound, so a card with twelve or more logical devices gets there. Return the error instead.

Fixes 1da177e4c3f4 ("Linux-2.6.12-rc2")
---
 drivers/pnp/isapnp/core.c | 16 ++++++++++++----
 drivers/pnp/isapnp/proc.c |  5 ++++-
 sound/isa/es18xx.c        |  6 +++++-
 3 files changed, 21 insertions(+), 6 deletions(-)
drivers/pnp/isapnp/core.c +12 -4
index 219f96f2aaaf..3591a2791c1a 100644
@@ -853,7 +853,9 @@ static int isapnp_get_resources(struct pnp_dev *dev)
 
 	pnp_dbg(&dev->dev, "get resources\n");
 	pnp_init_resources(dev);
-	isapnp_cfg_begin(dev->card->number, dev->number);
+	ret = isapnp_cfg_begin(dev->card->number, dev->number);
+	if (ret)
+		return ret;
 	dev->active = isapnp_read_byte(ISAPNP_CFG_ACTIVATE);
 	if (!dev->active)
 		goto __end;
@@ -887,10 +889,12 @@ __end:
 static int isapnp_set_resources(struct pnp_dev *dev)
 {
 	struct resource *res;
-	int tmp;
+	int tmp, ret;
 
 	pnp_dbg(&dev->dev, "set resources\n");
-	isapnp_cfg_begin(dev->card->number, dev->number);
+	ret = isapnp_cfg_begin(dev->card->number, dev->number);
+	if (ret)
+		return ret;
 	dev->active = 1;
 	for (tmp = 0; tmp < ISAPNP_MAX_PORT; tmp++) {
 		res = pnp_get_resource(dev, IORESOURCE_IO, tmp);
@@ -936,9 +940,13 @@ static int isapnp_set_resources(struct pnp_dev *dev)
 
 static int isapnp_disable_resources(struct pnp_dev *dev)
 {
+	int ret;
+
 	if (!dev->active)
 		return -EINVAL;
-	isapnp_cfg_begin(dev->card->number, dev->number);
+	ret = isapnp_cfg_begin(dev->card->number, dev->number);
+	if (ret)
+		return ret;
 	isapnp_deactivate(dev->number);
 	dev->active = 0;
 	isapnp_cfg_end();
drivers/pnp/isapnp/proc.c +4 -1
index c1f6e6bd0eb2..b3abab24050b 100644
@@ -25,6 +25,7 @@ static ssize_t isapnp_proc_bus_read(struct file *file, char __user * buf,
 	struct pnp_dev *dev = pde_data(file_inode(file));
 	int pos = *ppos;
 	int cnt, size = 256;
+	int ret;
 
 	if (pos >= size)
 		return 0;
@@ -37,7 +38,9 @@ static ssize_t isapnp_proc_bus_read(struct file *file, char __user * buf,
 	if (!access_ok(buf, cnt))
 		return -EINVAL;
 
-	isapnp_cfg_begin(dev->card->number, dev->number);
+	ret = isapnp_cfg_begin(dev->card->number, dev->number);
+	if (ret)
+		return ret;
 	for (; pos < 256 && cnt > 0; pos++, buf++, cnt--) {
 		unsigned char val;
 		val = isapnp_read_byte(pos);
sound/isa/es18xx.c +5 -1
index 3cadbf7cf238..de1eda5a0656 100644
@@ -1950,7 +1950,11 @@ static int snd_audiodrive_pnp_init_main(int dev, struct pnp_dev *pdev)
 	/* ok. hack using Vendor-Defined Card-Level registers */
 	/* skip csn and logdev initialization - already done in isapnp_configure */
 	if (pnp_device_is_isapnp(pdev)) {
-		isapnp_cfg_begin(isapnp_card_number(pdev), isapnp_csn_number(pdev));
+		int ret = isapnp_cfg_begin(isapnp_card_number(pdev),
+					   isapnp_csn_number(pdev));
+
+		if (ret)
+			return ret;
 		isapnp_write_byte(0x27, pnp_irq(pdev, 0));	/* Hardware Volume IRQ Number */
 		if (mpu_port[dev] != SNDRV_AUTO_PORT)
 			isapnp_write_byte(0x28, pnp_irq(pdev, 0)); /* MPU-401 IRQ Number */
Signature · 1 line
2.53.0
#13 lore raw

Re: [PATCH RESEND v2 04/51] PNP: isapnp: don't go on when isapnp_cfg_begin() fails

Sashiko has reviewed this patch and found no issues.
Quoted 9 lines

isapnp_cfg_begin() refuses a logical device number above 10 and a bad card number with -EINVAL before it takes isapnp_cfg_mutex. The callers that read and write the device's configuration, the proc file included, don't look at that: they go on talking to whatever device the card currently has selected and then unlock a mutex they never took in isapnp_cfg_end(). isapnp_create_device() hands out logical device numbers without a bound, so a card with twelve or more logical devices gets there. Return the error instead.

Quoted 3 lines
Fixes 1da177e4c3f4 ("Linux-2.6.12-rc2")

Sashiko has reviewed this patch and found no issues.

Signature · 1 line
Sashiko AI review · https://sashiko.dev/#/patchset/[email protected]?part=4
author maintainer
#14 lore raw

PATCH RESEND v2 5/51 xtensa: simdisk: remove the proc entry before the disk

In reply to Christian Brauner

simdisk_teardown() frees the gendisk and only then removes /proc/simdisk/<n>. A write to that entry in between attaches the file that was written to the disk, and simdisk_attach() sets the capacity of the gendisk that is gone. Remove the entry first, remove_proc_entry() waits for a writer that is in the middle of that.

Fixes b6c7e873daf7 ("xtensa: ISS: add host file-based simulated disk")
---
 arch/xtensa/platforms/iss/simdisk.c | 3 ++-
 1 file changed, 2 insertions(+), 1 deletion(-)
arch/xtensa/platforms/iss/simdisk.c +2 -1
index a2ddb49c269d..e51edb8cf872 100644
@@ -379,12 +379,13 @@ static void simdisk_teardown(struct simdisk *dev, int which,
 {
 	char tmp[2] = { '0' + which, 0 };
 
+	/* a write to the entry attaches a file to the disk, so it goes first */
+	remove_proc_entry(tmp, procdir);
 	simdisk_detach(dev);
 	if (dev->gd) {
 		del_gendisk(dev->gd);
 		put_disk(dev->gd);
 	}
-	remove_proc_entry(tmp, procdir);
 }
 
 static void __exit simdisk_exit(void)
Signature · 1 line
2.53.0
#15 lore raw

Re: [PATCH RESEND v2 05/51] xtensa: simdisk: remove the proc entry before the disk

Sashiko has reviewed this patch and found no issues.
Quoted 9 lines

simdisk_teardown() frees the gendisk and only then removes /proc/simdisk/<n>. A write to that entry in between attaches the file that was written to the disk, and simdisk_attach() sets the capacity of the gendisk that is gone. Remove the entry first, remove_proc_entry() waits for a writer that is in the middle of that.

Fixes b6c7e873daf7 ("xtensa: ISS: add host file-based simulated disk")

Sashiko has reviewed this patch and found no issues.

Signature · 1 line
Sashiko AI review · https://sashiko.dev/#/patchset/[email protected]?part=5
author maintainer
#16 lore raw

PATCH RESEND v2 6/51 powerpc/pseries: put the node that the ofdt property commands look up

In reply to Christian Brauner

parse_node() looks the node up with of_find_node_by_phandle(), which returns it with a reference, and do_add_property(), do_remove_property() and do_update_property() never put that reference. Every property command written to /proc/powerpc/ofdt leaks one. Put it when the command is done.

Fixes 610d91511f99 ("[PATCH] powerpc: Add support for changing properties from userspace")
---
 arch/powerpc/platforms/pseries/reconfig.c | 6 +++---
 1 file changed, 3 insertions(+), 3 deletions(-)
arch/powerpc/platforms/pseries/reconfig.c +3 -3
index 18e3f1a036e3..5a0c9c0b6253 100644
@@ -271,8 +271,8 @@ static char *parse_node(char *buf, size_t bufsize, struct device_node **npp)
 
 static int do_add_property(char *buf, size_t bufsize)
 {
+	struct device_node *np __free(device_node) = NULL;
 	struct property *prop = NULL;
-	struct device_node *np;
 	unsigned char *value;
 	char *name, *end;
 	int length;
@@ -296,7 +296,7 @@ static int do_add_property(char *buf, size_t bufsize)
 
 static int do_remove_property(char *buf, size_t bufsize)
 {
-	struct device_node *np;
+	struct device_node *np __free(device_node) = NULL;
 	char *tmp;
 	buf = parse_node(buf, bufsize, &np);
 
@@ -315,7 +315,7 @@ static int do_remove_property(char *buf, size_t bufsize)
 
 static int do_update_property(char *buf, size_t bufsize)
 {
-	struct device_node *np;
+	struct device_node *np __free(device_node) = NULL;
 	unsigned char *value;
 	char *name, *end, *next_prop;
 	int length;
Signature · 1 line
2.53.0
#17 lore raw

Re: [PATCH RESEND v2 06/51] powerpc/pseries: put the node that the ofdt property commands look up

Thank you for your contribution! Sashiko AI review found 1 potential issue(s) to consider: - [Low] powerpc/pseries: __free(device_node) declared = NULL at top of functions --

Thank you for your contribution! Sashiko AI review found 1 potential issue(s) to consider:
- [Low] powerpc/pseries: __free(device_node) declared = NULL at top of functions --

commit 3c337546ce05e068449f95031255af375235286d
Author: Christian Brauner <[email protected]>

powerpc/pseries: put the node that the ofdt property commands look up

This commit uses __free(device_node) in do_add_property(), do_remove_property(), and do_update_property() to release the device_node reference obtained by parse_node() via of_find_node_by_phandle().

Quoted 24 lines
arch/powerpc/platforms/pseries/reconfig.c +2 -2
index 18e3f1a036e35..5a0c9c0b6253f 100644
@@ -271,8 +271,8 @@ static char *parse_node(char *buf, size_t bufsize, struct device_node **npp)
 
 static int do_add_property(char *buf, size_t bufsize)
 {
+	struct device_node *np __free(device_node) = NULL;
 	struct property *prop = NULL;
-	struct device_node *np;
 	unsigned char *value;
 	char *name, *end;
 	int length;
@@ -296,7 +296,7 @@ static int do_add_property(char *buf, size_t bufsize)
 
 static int do_remove_property(char *buf, size_t bufsize)
 {
-	struct device_node *np;
+	struct device_node *np __free(device_node) = NULL;
 	char *tmp;
 	buf = parse_node(buf, bufsize, &np);
 

arch/powerpc/platforms/pseries/reconfig.c static int do_remove_property(char *buf, size_t bufsize) · line 318

Quoted 5 lines
arch/powerpc/platforms/pseries/reconfig.c +1 -1
@@ -315,7 +315,7 @@ static int do_remove_property(char *buf, size_t bufsize)
 
 static int do_update_property(char *buf, size_t bufsize)
 {
-	struct device_node *np;
+	struct device_node *np __free(device_node) = NULL;

[Severity: Low]
This isn't a bug, but in do_add_property(), do_remove_property(), and do_update_property() in arch/powerpc/platforms/pseries/reconfig.c, np is declared with __free(device_node) = NULL at the top of each function and assigned later via parse_node(buf, bufsize, &np), whereas cleanup.h conventions require defining and initializing __free() variables in a single statement.

Since parse_node() is a static helper only called by these three functions:

static char *parse_node(char *buf, size_t bufsize, struct device_node **npp)

{
	char *handle_str;
	phandle handle;
	*npp = NULL;
	...
	*npp = of_find_node_by_phandle(handle);
	return buf;
}

could parse_node() return struct device_node * directly (and advance char **buf) so that struct device_node *np __free(device_node) can be defined and initialized in one statement in each caller?

Signature · 1 line
Sashiko AI review · https://sashiko.dev/#/patchset/[email protected]?part=6
author maintainer
#18 lore raw

PATCH RESEND v2 7/51 lockd: don't hand out the terminator of nlm_end_grace

In reply to Christian Brauner

nlm_end_grace_read() answers with "Y\n" or "N\n" from a three byte buffer and hands out all three bytes, the terminating NUL included. Leave the NUL out.

Fixes d68e3c4aa416 ("lockd: add a /proc/fs/lockd/nlm_end_grace file")
---
 fs/lockd/procfs.c | 2 +-
 1 file changed, 1 insertion(+), 1 deletion(-)
fs/lockd/procfs.c +1 -1
index a01f08c8c2f3..74f7ab77535a 100644
@@ -57,7 +57,7 @@ nlm_end_grace_read(struct file *file, char __user *buf, size_t size,
 	resp[1] = '\n';
 	resp[2] = '\0';
 
-	return simple_read_from_buffer(buf, size, pos, resp, sizeof(resp));
+	return simple_read_from_buffer(buf, size, pos, resp, sizeof(resp) - 1);
 }
 
 static const struct proc_ops lockd_end_grace_proc_ops = {
Signature · 1 line
2.53.0
#19 lore raw

Re: [PATCH RESEND v2 07/51] lockd: don't hand out the terminator of nlm_end_grace

Sashiko has reviewed this patch and found no issues.
Quoted 6 lines

nlm_end_grace_read() answers with "Y\n" or "N\n" from a three byte buffer and hands out all three bytes, the terminating NUL included. Leave the NUL out.

Fixes d68e3c4aa416 ("lockd: add a /proc/fs/lockd/nlm_end_grace file")

Sashiko has reviewed this patch and found no issues.

Signature · 1 line
Sashiko AI review · https://sashiko.dev/#/patchset/[email protected]?part=7
author maintainer
#20 lore raw

PATCH RESEND v2 8/51 powerpc/pseries/lparcfg: don't drop the last byte of a write

In reply to Christian Brauner

lparcfg_write() terminates its copy of the write by overwriting the last byte, so a write without a trailing newline loses its last
character: "partition_entitled_capacity=5" is parsed as an empty value and fails with -EINVAL. Terminate behind the copy instead, and refuse a write that fills the whole buffer, which can't be terminated.

Fixes 1da177e4c3f4 ("Linux-2.6.12-rc2")
---
 arch/powerpc/platforms/pseries/lparcfg.c | 5 ++---
 1 file changed, 2 insertions(+), 3 deletions(-)
arch/powerpc/platforms/pseries/lparcfg.c +2 -3
index 3280b7968cab..9882f98c0efb 100644
@@ -699,13 +699,12 @@ static ssize_t lparcfg_write(struct file *file, const char __user * buf,
 	if (!firmware_has_feature(FW_FEATURE_SPLPAR))
 		return -EINVAL;
 
-	if (count == 0 || count > sizeof(kbuf))
+	if (count == 0 || count >= sizeof(kbuf))
 		return -EINVAL;
 
 	if (copy_from_user(kbuf, buf, count))
 		return -EFAULT;
-
-	kbuf[count - 1] = '\0';
+	kbuf[count] = '\0';
 	tmp = strchr(kbuf, '=');
 	if (!tmp)
 		return -EINVAL;
Signature · 1 line
2.53.0
#21 lore raw

Re: [PATCH RESEND v2 08/51] powerpc/pseries/lparcfg: don't drop the last byte of a write

Sashiko has reviewed this patch and found no issues.
Quoted 9 lines

lparcfg_write() terminates its copy of the write by overwriting the last byte, so a write without a trailing newline loses its last
character: "partition_entitled_capacity=5" is parsed as an empty value and fails with -EINVAL. Terminate behind the copy instead, and refuse a write that fills the whole buffer, which can't be terminated.

Fixes 1da177e4c3f4 ("Linux-2.6.12-rc2")

Sashiko has reviewed this patch and found no issues.

Signature · 1 line
Sashiko AI review · https://sashiko.dev/#/patchset/[email protected]?part=8
author maintainer
#22 lore raw

PATCH RESEND v2 9/51 profiling: report it when /proc/profile can't be created

In reply to Christian Brauner

create_proc_profile() returns 0 whether proc_create() worked or not, so a write to /sys/kernel/profiling that turned profiling on but didn't get the file reports success and there is no file to read the profile from. Return -ENOMEM like the other failures of that write do.

Fixes 22b8ce94708f ("profiling: dynamically enable readprofile at runtime")
---
 kernel/profile.c | 8 ++++----
 1 file changed, 4 insertions(+), 4 deletions(-)
kernel/profile.c +4 -4
index e7defa90a34c..820d5ec909d4 100644
@@ -216,15 +216,15 @@ static const struct proc_ops profile_proc_ops = {
 int __ref create_proc_profile(void)
 {
 	struct proc_dir_entry *entry;
-	int err = 0;
 
 	if (!prof_on)
 		return 0;
 	entry = proc_create("profile", S_IWUSR | S_IRUGO,
 			    NULL, &profile_proc_ops);
-	if (entry)
-		proc_set_size(entry, (1 + prof_len) * sizeof(atomic_t));
-	return err;
+	if (!entry)
+		return -ENOMEM;
+	proc_set_size(entry, (1 + prof_len) * sizeof(atomic_t));
+	return 0;
 }
 subsys_initcall(create_proc_profile);
 #endif /* CONFIG_PROC_FS */
Signature · 1 line
2.53.0
#23 lore raw

Re: [PATCH RESEND v2 09/51] profiling: report it when /proc/profile can't be created

Sashiko has reviewed this patch and found no issues.
Quoted 7 lines

create_proc_profile() returns 0 whether proc_create() worked or not, so a write to /sys/kernel/profiling that turned profiling on but didn't get the file reports success and there is no file to read the profile from. Return -ENOMEM like the other failures of that write do.

Fixes 22b8ce94708f ("profiling: dynamically enable readprofile at runtime")

Sashiko has reviewed this patch and found no issues.

Signature · 1 line
Sashiko AI review · https://sashiko.dev/#/patchset/[email protected]?part=9
author maintainer
#24 lore raw

PATCH RESEND v2 10/51 zorro: size the proc files like what they serve

In reply to Christian Brauner

The files under /proc/bus/zorro hand out a struct ConfigDev and seek within that, but their size says sizeof(struct zorro_dev). Say sizeof(struct ConfigDev).

Fixes 1da177e4c3f4 ("Linux-2.6.12-rc2")
---
 drivers/zorro/proc.c | 2 +-
 1 file changed, 1 insertion(+), 1 deletion(-)
drivers/zorro/proc.c +1 -1
index f916bf60b312..4c6f8f1c4d71 100644
@@ -108,7 +108,7 @@ static int __init zorro_proc_attach_device(unsigned int slot)
 				 &zorro_autocon[slot]);
 	if (!entry)
 		return -ENOMEM;
-	proc_set_size(entry, sizeof(struct zorro_dev));
+	proc_set_size(entry, sizeof(struct ConfigDev));
 	return 0;
 }
 
Signature · 1 line
2.53.0
maintainer Reviewed-by Acked-by on v2 10/51
#25 lore raw

Re: [PATCH RESEND v2 10/51] zorro: size the proc files like what they serve

Quoted 6 lines · Christian Brauner

The files under /proc/bus/zorro hand out a struct ConfigDev and seek within that, but their size says sizeof(struct zorro_dev). Say sizeof(struct ConfigDev).

Fixes 1da177e4c3f4 ("Linux-2.6.12-rc2")

Gr{oetje,eeting}s,

Geert

Signature · 5 lines
Geert Uytterhoeven -- There's lots of Linux beyond ia32 -- [email protected]

In personal conversations with technical people, I call myself a hacker. But
when I'm talking to journalists I just say "programmer" or something like that.
                                -- Linus Torvalds
#26 lore raw

Re: [PATCH RESEND v2 10/51] zorro: size the proc files like what they serve

In reply to Christian Brauner
Sashiko has reviewed this patch and found no issues.
Quoted 6 lines

The files under /proc/bus/zorro hand out a struct ConfigDev and seek within that, but their size says sizeof(struct zorro_dev). Say sizeof(struct ConfigDev).

Fixes 1da177e4c3f4 ("Linux-2.6.12-rc2")

Sashiko has reviewed this patch and found no issues.

Signature · 1 line
Sashiko AI review · https://sashiko.dev/#/patchset/[email protected]?part=10
author maintainer
#27 lore raw

PATCH RESEND v2 11/51 sparc: led: consume the whole write

In reply to Christian Brauner

led_proc_write() looks at the first eight bytes of a write and returns that many, so a writer that loops until everything is written, stdio does, sends the rest as a second command. That one is unknown and switches the LED off. Return the whole count, the rest is ignored.

Fixes ee1858d3122d ("[SPARC]: Add sun4m LED driver.")
---
 arch/sparc/kernel/led.c | 3 ++-
 1 file changed, 2 insertions(+), 1 deletion(-)
arch/sparc/kernel/led.c +2 -1
index 9b53ac1fe533..a1478de9fe5d 100644
@@ -68,6 +68,7 @@ static int led_proc_open(struct inode *inode, struct file *file)
 static ssize_t led_proc_write(struct file *file, const char __user *buffer,
 			      size_t count, loff_t *ppos)
 {
+	size_t len = count;
 	char *buf = NULL;
 
 	if (count > LED_MAX_LENGTH)
@@ -102,7 +103,7 @@ static ssize_t led_proc_write(struct file *file, const char __user *buffer,
 
 	kfree(buf);
 
-	return count;
+	return len;
 }
 
 static const struct proc_ops led_proc_ops = {
Signature · 1 line
2.53.0
#28 lore raw

Re: [PATCH RESEND v2 11/51] sparc: led: consume the whole write

Sashiko has reviewed this patch and found no issues.
Quoted 7 lines

led_proc_write() looks at the first eight bytes of a write and returns that many, so a writer that loops until everything is written, stdio does, sends the rest as a second command. That one is unknown and switches the LED off. Return the whole count, the rest is ignored.

Fixes ee1858d3122d ("[SPARC]: Add sun4m LED driver.")

Sashiko has reviewed this patch and found no issues.

Signature · 1 line
Sashiko AI review · https://sashiko.dev/#/patchset/[email protected]?part=11
author maintainer
#29 lore raw

PATCH RESEND v2 12/51 powerpc/rtas: consume the whole write to /proc/powerpc/rtas/progress

In reply to Christian Brauner

ppc_rtas_progress_write() shows the first 255 bytes of a write and returns that many, so a writer that loops until everything is written shows the rest as a second message. Return the whole count, the rest is ignored.

Fixes 1da177e4c3f4 ("Linux-2.6.12-rc2")
---
 arch/powerpc/kernel/rtas-proc.c | 3 ++-
 1 file changed, 2 insertions(+), 1 deletion(-)
arch/powerpc/kernel/rtas-proc.c +2 -1
index f38df72e64b8..89b165986851 100644
@@ -311,6 +311,7 @@ static int ppc_rtas_poweron_show(struct seq_file *m, void *v)
 static ssize_t ppc_rtas_progress_write(struct file *file,
 		const char __user *buf, size_t count, loff_t *ppos)
 {
+	size_t len = count;
 	unsigned long hex;
 
 	if (count >= MAX_LINELENGTH)
@@ -324,7 +325,7 @@ static ssize_t ppc_rtas_progress_write(struct file *file,
 	hex = simple_strtoul(progress_led, NULL, 10);
 
 	rtas_progress ((char *)progress_led, hex);
-	return count;
+	return len;
 
 	/* clear the line */
 	/* rtas_progress("                   ", 0xffff);*/
Signature · 1 line
2.53.0
#30 lore raw

Re: [PATCH RESEND v2 12/51] powerpc/rtas: consume the whole write to /proc/powerpc/rtas/progress

Sashiko has reviewed this patch and found no issues.
Quoted 7 lines

ppc_rtas_progress_write() shows the first 255 bytes of a write and returns that many, so a writer that loops until everything is written shows the rest as a second message. Return the whole count, the rest is ignored.

Fixes 1da177e4c3f4 ("Linux-2.6.12-rc2")

Sashiko has reviewed this patch and found no issues.

Signature · 1 line
Sashiko AI review · https://sashiko.dev/#/patchset/[email protected]?part=12
author maintainer
#31 lore raw

PATCH RESEND v2 13/51 sched/psi: don't drop the last byte of a trigger write

In reply to Christian Brauner

psi_write() copies at most 32 bytes of the write into its buffer and terminates the buffer by overwriting its last byte. For a write shorter than 32 bytes that is the last byte the writer sent. A trigger written without a trailing newline loses its last digit then, "some 150000 1000000" turns into "some 150000 100000", and a shorter one like "some 150 10000" fails with -EINVAL because the window doesn't fit anymore. Only writes that end in a newline parse as intended.

Copy at most 31 bytes and terminate behind them.

Fixes 0e94682b73bf ("psi: introduce psi monitor")
---
 kernel/sched/psi.c | 4 ++--
 1 file changed, 2 insertions(+), 2 deletions(-)
kernel/sched/psi.c +2 -2
index 7c5381423334..8b59635e95d4 100644
@@ -1566,11 +1566,11 @@ static ssize_t psi_write(struct file *file, const char __user *user_buf,
 	if (!nbytes)
 		return -EINVAL;
 
-	buf_size = min(nbytes, sizeof(buf));
+	buf_size = min(nbytes, sizeof(buf) - 1);
 	if (copy_from_user(buf, user_buf, buf_size))
 		return -EFAULT;
 
-	buf[buf_size - 1] = '\0';
+	buf[buf_size] = '\0';
 
 	seq = file->private_data;
 
Signature · 1 line
2.53.0
#32 lore raw

Re: [PATCH RESEND v2 13/51] sched/psi: don't drop the last byte of a trigger write

Sashiko has reviewed this patch and found no issues.
Quoted 8 lines

psi_write() copies at most 32 bytes of the write into its buffer and terminates the buffer by overwriting its last byte. For a write shorter than 32 bytes that is the last byte the writer sent. A trigger written without a trailing newline loses its last digit then, "some 150000 1000000" turns into "some 150000 100000", and a shorter one like "some 150 10000" fails with -EINVAL because the window doesn't fit anymore. Only writes that end in a newline parse as intended.

Quoted 5 lines

Copy at most 31 bytes and terminate behind them.

Fixes 0e94682b73bf ("psi: introduce psi monitor")

Sashiko has reviewed this patch and found no issues.

Signature · 1 line
Sashiko AI review · https://sashiko.dev/#/patchset/[email protected]?part=13
author maintainer
#33 lore raw

PATCH RESEND v2 14/51 proc: sysctl: don't stop readdir at an entry that is being unregistered

In reply to Christian Brauner

proc_sys_fill_cache() creates the inode of an entry that has no dentry yet. Since ace0c791e6c3 ("proc/sysctl: Don't grab i_lock under sysctl_lock.") proc_sys_make_inode() refuses to do that once the table is being unregistered and fails with -ENOENT. readdir takes every table it lists into use and unregister_sysctl_table() marks the table as being unregistered before it waits for readdir to let go of it. So an entry that is unregistered right then makes proc_sys_fill_cache() fail, proc_sys_readdir() stops there and returns 0. If that getdents64() call hadn't emitted anything before that entry userspace sees the end of the directory and never gets the entries behind it. A listing of /proc/sys/net/ipv6/conf can end early that way while a device goes away.

So skip an entry whose table is being unregistered, like readdir already skips a link it can't follow. Lookup treats such an entry as gone too since ea5751ccd665 ("proc/sysctl: don't return ENOMEM on lookup when a table is unregistering").

Fixes ace0c791e6c3 ("proc/sysctl: Don't grab i_lock under sysctl_lock.")
---
 fs/proc/proc_sysctl.c | 3 +++
 1 file changed, 3 insertions(+)
fs/proc/proc_sysctl.c +3 -0
index 6c0859c66563..b4a309d49698 100644
@@ -704,6 +704,9 @@ static bool proc_sys_fill_cache(struct file *file,
 			if (unlikely(res)) {
 				dput(child);
 
+				/* skip an entry whose table is being unregistered */
+				if (res == ERR_PTR(-ENOENT))
+					return true;
 				if (IS_ERR(res))
 					return false;
 
Signature · 1 line
2.53.0
#34 lore raw

Re: [PATCH RESEND v2 14/51] proc: sysctl: don't stop readdir at an entry that is being unregistered

Sashiko has reviewed this patch and found no issues.
Quoted 13 lines

proc_sys_fill_cache() creates the inode of an entry that has no dentry yet. Since ace0c791e6c3 ("proc/sysctl: Don't grab i_lock under sysctl_lock.") proc_sys_make_inode() refuses to do that once the table is being unregistered and fails with -ENOENT. readdir takes every table it lists into use and unregister_sysctl_table() marks the table as being unregistered before it waits for readdir to let go of it. So an entry that is unregistered right then makes proc_sys_fill_cache() fail, proc_sys_readdir() stops there and returns 0. If that getdents64() call hadn't emitted anything before that entry userspace sees the end of the directory and never gets the entries behind it. A listing of /proc/sys/net/ipv6/conf can end early that way while a device goes away.

Quoted 8 lines

So skip an entry whose table is being unregistered, like readdir already skips a link it can't follow. Lookup treats such an entry as gone too since ea5751ccd665 ("proc/sysctl: don't return ENOMEM on lookup when a table is unregistering").

Fixes ace0c791e6c3 ("proc/sysctl: Don't grab i_lock under sysctl_lock.")

Sashiko has reviewed this patch and found no issues.

Signature · 1 line
Sashiko AI review · https://sashiko.dev/#/patchset/[email protected]?part=14
author maintainer
#35 lore raw

PATCH RESEND v2 15/51 PCI/proc: don't truncate the position of config space accesses

In reply to Christian Brauner

proc_bus_pci_write() truncates the file position to an int. A pwrite() at an offset like 0xfffff000 turns it negative, the check against the size of the config space passes and the count it clamps to ends up larger than what was written. The loop then reads past the end of the caller's buffer and writes all of it into config space at negative offsets, which pci_user_write_config_*() pass on to the config accessors unchecked. The write also returns more than it was asked to write.

An offset above 4G that truncates to a small positive value writes to the start of config space instead. proc_bus_pci_read() keeps the position in an unsigned int, so a read at such an offset returns the start of config space instead of hitting EOF.

Check the position against the size of the config space before narrowing it.

Fixes 1da177e4c3f4 ("Linux-2.6.12-rc2")
---
 drivers/pci/proc.c | 15 ++++++++-------
 1 file changed, 8 insertions(+), 7 deletions(-)
drivers/pci/proc.c +8 -7
index 3d7a9ed5fc22..e0dc70123f82 100644
@@ -32,8 +32,7 @@ static ssize_t proc_bus_pci_read(struct file *file, char __user *buf,
 				 size_t nbytes, loff_t *ppos)
 {
 	struct pci_dev *dev = pde_data(file_inode(file));
-	unsigned int pos = *ppos;
-	unsigned int cnt, size;
+	unsigned int pos, cnt, size;
 
 	/*
 	 * Normal users can read only the standardized portion of the
@@ -51,8 +50,9 @@ static ssize_t proc_bus_pci_read(struct file *file, char __user *buf,
 	if (!nbytes)
 		return 0;
 
-	if (pos >= size)
+	if (*ppos >= size)
 		return 0;
+	pos = *ppos;
 	if (nbytes >= size)
 		nbytes = size;
 	if (pos + nbytes > size)
@@ -119,9 +119,8 @@ static ssize_t proc_bus_pci_write(struct file *file, const char __user *buf,
 {
 	struct inode *ino = file_inode(file);
 	struct pci_dev *dev = pde_data(ino);
-	int pos = *ppos;
 	int size = dev->cfg_size;
-	int cnt, ret;
+	int pos, cnt, ret;
 
 	ret = security_locked_down(LOCKDOWN_PCI_ACCESS);
 	if (ret)
@@ -130,14 +129,16 @@ static ssize_t proc_bus_pci_write(struct file *file, const char __user *buf,
 	if (!nbytes)
 		return 0;
 
+	if (*ppos >= size)
+		return 0;
+	pos = *ppos;
+
 	if (resource_is_exclusive(&dev->driver_exclusive_resource, pos, nbytes)) {
 		pci_warn_once(dev, "%s: Unexpected write to kernel-exclusive config offset %x",
 			      current->comm, pos);
 		add_taint(TAINT_USER, LOCKDEP_STILL_OK);
 	}
 
-	if (pos >= size)
-		return 0;
 	if (nbytes >= size)
 		nbytes = size;
 	if (pos + nbytes > size)
Signature · 1 line
2.53.0
#36 lore raw

Re: [PATCH RESEND v2 15/51] PCI/proc: don't truncate the position of config space accesses

Sashiko has reviewed this patch and found no issues.
Quoted 14 lines

proc_bus_pci_write() truncates the file position to an int. A pwrite() at an offset like 0xfffff000 turns it negative, the check against the size of the config space passes and the count it clamps to ends up larger than what was written. The loop then reads past the end of the caller's buffer and writes all of it into config space at negative offsets, which pci_user_write_config_*() pass on to the config accessors unchecked. The write also returns more than it was asked to write.

An offset above 4G that truncates to a small positive value writes to the start of config space instead. proc_bus_pci_read() keeps the position in an unsigned int, so a read at such an offset returns the start of config space instead of hitting EOF.

Quoted 6 lines

Check the position against the size of the config space before narrowing it.

Fixes 1da177e4c3f4 ("Linux-2.6.12-rc2")

Sashiko has reviewed this patch and found no issues.

Signature · 1 line
Sashiko AI review · https://sashiko.dev/#/patchset/[email protected]?part=15
author maintainer
#37 lore raw

PATCH RESEND v2 16/51 PNP: isapnp: don't read past the end of the buffer on a large pread()

In reply to Christian Brauner

isapnp_proc_bus_read() truncates the position to an int. A pread() at an offset like 0xfffffc00 turns it negative, the check against the size of the configuration space passes, and the loop then puts everything from that position up to byte 256 into the reader's buffer, no matter how few bytes were asked for.

Keep the position as a loff_t and clamp the count against what is left of the configuration space.

---
 drivers/pnp/isapnp/proc.c | 6 ++----
 1 file changed, 2 insertions(+), 4 deletions(-)
drivers/pnp/isapnp/proc.c +2 -4
index b3abab24050b..1829c20d5446 100644
@@ -23,15 +23,13 @@ static ssize_t isapnp_proc_bus_read(struct file *file, char __user * buf,
 				    size_t nbytes, loff_t * ppos)
 {
 	struct pnp_dev *dev = pde_data(file_inode(file));
-	int pos = *ppos;
+	loff_t pos = *ppos;
 	int cnt, size = 256;
 	int ret;
 
 	if (pos >= size)
 		return 0;
-	if (nbytes >= size)
-		nbytes = size;
-	if (pos + nbytes > size)
+	if (nbytes > size - pos)
 		nbytes = size - pos;
 	cnt = nbytes;
 
Signature · 1 line
2.53.0
#38 lore raw

Re: [PATCH RESEND v2 16/51] PNP: isapnp: don't read past the end of the buffer on a large pread()

Sashiko has reviewed this patch and found no issues.
Quoted 6 lines

isapnp_proc_bus_read() truncates the position to an int. A pread() at an offset like 0xfffffc00 turns it negative, the check against the size of the configuration space passes, and the loop then puts everything from that position up to byte 256 into the reader's buffer, no matter how few bytes were asked for.

Quoted 7 lines

Keep the position as a loff_t and clamp the count against what is left of the configuration space.

Sashiko has reviewed this patch and found no issues.

Signature · 1 line
Sashiko AI review · https://sashiko.dev/#/patchset/[email protected]?part=16
author maintainer
#39 lore raw

PATCH RESEND v2 17/51 s390/dasd: don't look in front of the buffer on an empty write

In reply to Christian Brauner

dasd_get_user_string() strips a trailing newline by looking at the last byte that was written. For an empty write that's the byte in front of the buffer it just allocated. Only look if something was written.

Fixes 1da177e4c3f4 ("Linux-2.6.12-rc2")
---
 drivers/s390/block/dasd.c | 2 +-
 1 file changed, 1 insertion(+), 1 deletion(-)
drivers/s390/block/dasd.c +1 -1
index 2ffe404b890f..e97891e58957 100644
@@ -933,7 +933,7 @@ char *dasd_get_user_string(const char __user *user_buf, size_t user_len)
 		return ERR_PTR(-EFAULT);
 	}
 	/* got the string, now strip linefeed. */
-	if (buffer[user_len - 1] == '\n')
+	if (user_len && buffer[user_len - 1] == '\n')
 		buffer[user_len - 1] = 0;
 	else
 		buffer[user_len] = 0;
Signature · 1 line
2.53.0
#40 lore raw

Re: [PATCH RESEND v2 17/51] s390/dasd: don't look in front of the buffer on an empty write

Sashiko has reviewed this patch and found no issues.
Quoted 7 lines

dasd_get_user_string() strips a trailing newline by looking at the last byte that was written. For an empty write that's the byte in front of the buffer it just allocated. Only look if something was written.

Fixes 1da177e4c3f4 ("Linux-2.6.12-rc2")

Sashiko has reviewed this patch and found no issues.

Signature · 1 line
Sashiko AI review · https://sashiko.dev/#/patchset/[email protected]?part=17
author maintainer
#41 lore raw

PATCH RESEND v2 18/51 platform/x86: toshiba_acpi: reject malformed brightness and fan writes

In reply to Christian Brauner

When lcd_proc_write() and fan_proc_write() were refactored their checks were inverted but the && stayed. They only fail if sscanf() didn't parse anything and the value is out of range at the same time, and for the brightness value < 0 && value > levels can't be true at all. So an out of range brightness or fan setting is passed on to the hardware, and so is the uninitialized value if nothing could be parsed.

Restore the checks as they were before the refactoring.

Fixes e1a949c1b988 ("toshiba_acpi: Refactor *{get, set} functions return value")
Fixes 3e07e5baa2af ("toshiba_acpi: Add set_fan_status function")
---
 drivers/platform/x86/toshiba_acpi.c | 8 ++++----
 1 file changed, 4 insertions(+), 4 deletions(-)
drivers/platform/x86/toshiba_acpi.c +4 -4
index a0b8060836d0..9eb8f1e5aeda 100644
@@ -1498,8 +1498,8 @@ static ssize_t lcd_proc_write(struct file *file, const char __user *buf,
 	cmd[len] = '\0';
 
 	levels = dev->backlight_dev->props.max_brightness + 1;
-	if (sscanf(cmd, " brightness : %i", &value) != 1 &&
-	    value < 0 && value > levels)
+	if (sscanf(cmd, " brightness : %i", &value) != 1 ||
+	    value < 0 || value >= levels)
 		return -EINVAL;
 
 	if (set_lcd_brightness(dev, value))
@@ -1678,8 +1678,8 @@ static ssize_t fan_proc_write(struct file *file, const char __user *buf,
 		return -EFAULT;
 	cmd[len] = '\0';
 
-	if (sscanf(cmd, " force_on : %i", &value) != 1 &&
-	    value != 0 && value != 1)
+	if (sscanf(cmd, " force_on : %i", &value) != 1 ||
+	    value < 0 || value > 1)
 		return -EINVAL;
 
 	if (set_fan_status(dev, value))
Signature · 1 line
2.53.0
#42 lore raw

Re: [PATCH RESEND v2 18/51] platform/x86: toshiba_acpi: reject malformed brightness and fan writes

Sashiko has reviewed this patch and found no issues.
Quoted 7 lines

When lcd_proc_write() and fan_proc_write() were refactored their checks were inverted but the && stayed. They only fail if sscanf() didn't parse anything and the value is out of range at the same time, and for the brightness value < 0 && value > levels can't be true at all. So an out of range brightness or fan setting is passed on to the hardware, and so is the uninitialized value if nothing could be parsed.

Quoted 6 lines

Restore the checks as they were before the refactoring.

Fixes e1a949c1b988 ("toshiba_acpi: Refactor *{get, set} functions return value")
Fixes 3e07e5baa2af ("toshiba_acpi: Add set_fan_status function")

Sashiko has reviewed this patch and found no issues.

Signature · 1 line
Sashiko AI review · https://sashiko.dev/#/patchset/[email protected]?part=18
author maintainer
#43 lore raw

PATCH RESEND v2 19/51 xtensa: simdisk: don't read the file name without the lock

In reply to Christian Brauner

proc_read_simdisk() looks at dev->filename without holding dev->lock. A write to the same file detaches the disk and frees the name under the lock, so a concurrent reader can copy out freed memory. Copy the name with the lock held.

Fixes b6c7e873daf7 ("xtensa: ISS: add host file-based simulated disk")
---
 arch/xtensa/platforms/iss/simdisk.c | 25 ++++++++++++-------------
 1 file changed, 12 insertions(+), 13 deletions(-)
arch/xtensa/platforms/iss/simdisk.c +12 -13
index e51edb8cf872..1248d960e5d3 100644
@@ -238,22 +238,21 @@ static ssize_t proc_read_simdisk(struct file *file, char __user *buf,
 			size_t size, loff_t *ppos)
 {
 	struct simdisk *dev = pde_data(file_inode(file));
-	const char *s = dev->filename;
-	if (s) {
-		ssize_t len = strlen(s);
-		char *temp = kmalloc(len + 2, GFP_KERNEL);
+	ssize_t len;
+	char *temp;
 
-		if (!temp)
-			return -ENOMEM;
+	/* a write sets at most a page, see proc_write_simdisk() */
+	temp = kmalloc(PAGE_SIZE + 2, GFP_KERNEL);
+	if (!temp)
+		return -ENOMEM;
 
-		len = scnprintf(temp, len + 2, "%s\n", s);
-		len = simple_read_from_buffer(buf, size, ppos,
-					      temp, len);
+	spin_lock(&dev->lock);
+	len = scnprintf(temp, PAGE_SIZE + 2, "%s\n", dev->filename ?: "");
+	spin_unlock(&dev->lock);
 
-		kfree(temp);
-		return len;
-	}
-	return simple_read_from_buffer(buf, size, ppos, "\n", 1);
+	len = simple_read_from_buffer(buf, size, ppos, temp, len);
+	kfree(temp);
+	return len;
 }
 
 static ssize_t proc_write_simdisk(struct file *file, const char __user *buf,
Signature · 1 line
2.53.0
#44 lore raw

Re: [PATCH RESEND v2 19/51] xtensa: simdisk: don't read the file name without the lock

Sashiko has reviewed this patch and found no issues.
Quoted 8 lines

proc_read_simdisk() looks at dev->filename without holding dev->lock. A write to the same file detaches the disk and frees the name under the lock, so a concurrent reader can copy out freed memory. Copy the name with the lock held.

Fixes b6c7e873daf7 ("xtensa: ISS: add host file-based simulated disk")

Sashiko has reviewed this patch and found no issues.

Signature · 1 line
Sashiko AI review · https://sashiko.dev/#/patchset/[email protected]?part=19
author maintainer
#45 lore raw

PATCH RESEND v2 20/51 powerpc/rtas_flash: don't read past the validate message

In reply to Christian Brauner

get_validate_flash_msg() adds up what snprintf() returns, which is the length of the whole string and not what fit into msg. If the update results the firmware hands back don't fit into what is left of the 256 bytes, the length ends up larger than msg and validate_flash_read() copies whatever follows it on the stack to userspace. Use scnprintf().

Fixes a94a14720eaf ("powerpc/rtas_flash: Fix validate_flash buffer overflow issue")
---
 arch/powerpc/kernel/rtas_flash.c | 2 +-
 1 file changed, 1 insertion(+), 1 deletion(-)
arch/powerpc/kernel/rtas_flash.c +1 -1
index 722dbfb6fbf8..f1cd105f7426 100644
@@ -448,7 +448,7 @@ static int get_validate_flash_msg(struct rtas_validate_flash_t *args_buf,
 		n = sprintf(msg, "%d\n", args_buf->update_results);
 		if ((args_buf->update_results >= VALIDATE_CUR_UNKNOWN) ||
 		    (args_buf->update_results == VALIDATE_TMP_UPDATE))
-			n += snprintf(msg + n, msglen - n, "%s\n",
+			n += scnprintf(msg + n, msglen - n, "%s\n",
 					args_buf->buf);
 	} else {
 		n = sprintf(msg, "%d\n", args_buf->status);
Signature · 1 line
2.53.0
#46 lore raw

Re: [PATCH RESEND v2 20/51] powerpc/rtas_flash: don't read past the validate message

Sashiko has reviewed this patch and found no issues.
Quoted 9 lines

get_validate_flash_msg() adds up what snprintf() returns, which is the length of the whole string and not what fit into msg. If the update results the firmware hands back don't fit into what is left of the 256 bytes, the length ends up larger than msg and validate_flash_read() copies whatever follows it on the stack to userspace. Use scnprintf().

Fixes a94a14720eaf ("powerpc/rtas_flash: Fix validate_flash buffer overflow issue")

Sashiko has reviewed this patch and found no issues.

Signature · 1 line
Sashiko AI review · https://sashiko.dev/#/patchset/[email protected]?part=20
author maintainer
#47 lore raw

PATCH RESEND v2 21/51 powerpc/rtasd: zero the error log buffer

In reply to Christian Brauner

rtas_log_read() hands out a whole slot of the error log but pSeries_log_error() only fills in the sequence number and the event, which is usually a lot shorter. The rest of the slot is whatever vmalloc() left there. Use vzalloc().

Fixes 1da177e4c3f4 ("Linux-2.6.12-rc2")
---
 arch/powerpc/kernel/rtasd.c | 2 +-
 1 file changed, 1 insertion(+), 1 deletion(-)
arch/powerpc/kernel/rtasd.c +1 -1
index fd40864bdb70..dd0df5e164a3 100644
@@ -523,7 +523,7 @@ static int __init rtas_event_scan_init(void)
 	rtas_error_log_max = rtas_get_error_log_max();
 	rtas_error_log_buffer_max = rtas_error_log_max + sizeof(int);
 
-	rtas_log_buf = vmalloc(array_size(LOG_NUMBER,
+	rtas_log_buf = vzalloc(array_size(LOG_NUMBER,
 					  rtas_error_log_buffer_max));
 	if (!rtas_log_buf) {
 		printk(KERN_ERR "rtasd: no memory\n");
Signature · 1 line
2.53.0
#48 lore raw

Re: [PATCH RESEND v2 21/51] powerpc/rtasd: zero the error log buffer

Sashiko has reviewed this patch and found no issues.
Quoted 8 lines

rtas_log_read() hands out a whole slot of the error log but pSeries_log_error() only fills in the sequence number and the event, which is usually a lot shorter. The rest of the slot is whatever vmalloc() left there. Use vzalloc().

Fixes 1da177e4c3f4 ("Linux-2.6.12-rc2")

Sashiko has reviewed this patch and found no issues.

Signature · 1 line
Sashiko AI review · https://sashiko.dev/#/patchset/[email protected]?part=21
author maintainer
#49 lore raw

PATCH RESEND v2 22/51 ALSA: info: don't write past the end of a data entry

In reply to Christian Brauner

snd_info_entry_write() clamps the count to what is left of the entry by computing entry->size - pos as a size_t. For a position past the end that wraps and the write goes to the driver unclamped, for opl4 into sample memory outside of what the entry covers. At the end of the entry the driver gets a count of 0 and vmalloc(0) warns. Before the clamp moved into the common code the driver ignored such writes. Fail them with -ENOSPC instead, like a block device does at the end of the device. Returning 0 would make writers that use stdio retry forever.

Fixes d97e1b78239c ("ALSA: info - Check file position validity in common layer")
---
 sound/core/info.c | 2 ++
 1 file changed, 2 insertions(+)
sound/core/info.c +2 -0
index 023b4736aa6d..f608d335b6c9 100644
@@ -171,6 +171,8 @@ static ssize_t snd_info_entry_write(struct file *file, const char __user *buffer
 	pos = *offset;
 	if (!valid_pos(pos, count))
 		return -EIO;
+	if (pos >= entry->size)
+		return count ? -ENOSPC : 0;
 	if (count > 0) {
 		size_t maxsize = entry->size - pos;
 		count = min(count, maxsize);
Signature · 1 line
2.53.0
#50 lore raw

Re: [PATCH RESEND v2 22/51] ALSA: info: don't write past the end of a data entry

Sashiko has reviewed this patch and found no issues.
Quoted 9 lines

snd_info_entry_write() clamps the count to what is left of the entry by computing entry->size - pos as a size_t. For a position past the end that wraps and the write goes to the driver unclamped, for opl4 into sample memory outside of what the entry covers. At the end of the entry the driver gets a count of 0 and vmalloc(0) warns. Before the clamp moved into the common code the driver ignored such writes. Fail them with -ENOSPC instead, like a block device does at the end of the device. Returning 0 would make writers that use stdio retry forever.

Quoted 4 lines
Fixes d97e1b78239c ("ALSA: info - Check file position validity in common layer")

Sashiko has reviewed this patch and found no issues.

Signature · 1 line
Sashiko AI review · https://sashiko.dev/#/patchset/[email protected]?part=22
author maintainer
#51 lore raw

PATCH RESEND v2 23/51 scsi: BusLogic: don't return 0 from writes to the proc file

In reply to Christian Brauner

A write to /proc/scsi/BusLogic/<n> resets the statistics and returns 0. Writers that use stdio, echo for example, take that as no progress and retry forever. Return the number of bytes that were written.

Fixes 1da177e4c3f4 ("Linux-2.6.12-rc2")
---
 drivers/scsi/BusLogic.c | 2 +-
 1 file changed, 1 insertion(+), 1 deletion(-)
drivers/scsi/BusLogic.c +1 -1
index 27b446c0c5d0..7ad814f549ae 100644
@@ -3328,7 +3328,7 @@ static int blogic_write_info(struct Scsi_Host *shost, char *procbuf,
 	adapter->ext_resets = 0;
 	adapter->adapter_intern_errors = 0;
 	memset(tgt_stats, 0, BLOGIC_MAXDEV * sizeof(struct blogic_tgt_stats));
-	return 0;
+	return bytes_avail;
 }
 
 static int blogic_show_info(struct seq_file *m, struct Scsi_Host *shost)
Signature · 1 line
2.53.0
#52 lore raw

Re: [PATCH RESEND v2 23/51] scsi: BusLogic: don't return 0 from writes to the proc file

Sashiko has reviewed this patch and found no issues.
Quoted 6 lines

A write to /proc/scsi/BusLogic/<n> resets the statistics and returns 0. Writers that use stdio, echo for example, take that as no progress and retry forever. Return the number of bytes that were written.

Fixes 1da177e4c3f4 ("Linux-2.6.12-rc2")

Sashiko has reviewed this patch and found no issues.

Signature · 1 line
Sashiko AI review · https://sashiko.dev/#/patchset/[email protected]?part=23
author maintainer
#53 lore raw

PATCH RESEND v2 24/51 scsi: ips: don't return 0 from writes to the proc file

In reply to Christian Brauner

ips_write_info() ignores what is written to /proc/scsi/ips/<n> and returns 0. Writers that use stdio, echo for example, take that as no progress and retry forever. Return the number of bytes that were written.

Fixes 1da177e4c3f4 ("Linux-2.6.12-rc2")
---
 drivers/scsi/ips.c | 2 +-
 1 file changed, 1 insertion(+), 1 deletion(-)
drivers/scsi/ips.c +1 -1
index c7d6c5aae340..85c4fb164743 100644
@@ -1428,7 +1428,7 @@ ips_write_info(struct Scsi_Host *host, char *buffer, int length)
 	if (!ha)
 		return (-EINVAL);
 
-	return 0;
+	return length;
 }
 
 static int
Signature · 1 line
2.53.0
#54 lore raw

Re: [PATCH RESEND v2 24/51] scsi: ips: don't return 0 from writes to the proc file

Sashiko has reviewed this patch and found no issues.
Quoted 7 lines

ips_write_info() ignores what is written to /proc/scsi/ips/<n> and returns 0. Writers that use stdio, echo for example, take that as no progress and retry forever. Return the number of bytes that were written.

Fixes 1da177e4c3f4 ("Linux-2.6.12-rc2")

Sashiko has reviewed this patch and found no issues.

Signature · 1 line
Sashiko AI review · https://sashiko.dev/#/patchset/[email protected]?part=24
author maintainer
#55 lore raw

PATCH RESEND v2 25/51 wifi: libipw: don't return 0 from writes to debug_level

In reply to Christian Brauner

debug_level_proc_write() returns the length of the string it parsed. A write that starts with a NUL byte thus returns 0 and writers that use stdio retry it forever. Return the number of bytes that were written instead, which also stops writes longer than the 11 bytes it looks at from coming up short.

Fixes b453872c35cf ("[NET] ieee80211 subsystem")
---
 drivers/net/wireless/intel/ipw2x00/libipw_module.c | 2 +-
 1 file changed, 1 insertion(+), 1 deletion(-)
drivers/net/wireless/intel/ipw2x00/libipw_module.c +1 -1
index 22358b2c2ecd..552c8ff3928b 100644
@@ -236,7 +236,7 @@ static ssize_t debug_level_proc_write(struct file *file,
 	else
 		libipw_debug_level = val;
 
-	return strnlen(buf, len);
+	return count;
 }
 
 static const struct proc_ops debug_level_proc_ops = {
Signature · 1 line
2.53.0
#56 lore raw

Re: [PATCH RESEND v2 25/51] wifi: libipw: don't return 0 from writes to debug_level

Sashiko has reviewed this patch and found no issues.
Quoted 8 lines

debug_level_proc_write() returns the length of the string it parsed. A write that starts with a NUL byte thus returns 0 and writers that use stdio retry it forever. Return the number of bytes that were written instead, which also stops writes longer than the 11 bytes it looks at from coming up short.

Fixes b453872c35cf ("[NET] ieee80211 subsystem")

Sashiko has reviewed this patch and found no issues.

Signature · 1 line
Sashiko AI review · https://sashiko.dev/#/patchset/[email protected]?part=25
author maintainer
#57 lore raw

PATCH RESEND v2 26/51 scsi: core: NUL-terminate what is written to the host proc files

In reply to Christian Brauner

proc_scsi_host_write() copies what is written into a page and hands it to ->write_info() without terminating it. ppa and imm parse it with strncmp() and simple_strtoul(), which read on past what was written into whatever the page held before. Terminate the copy. A write is at most PROC_BLOCK_SIZE bytes, so the page always has room for that.

Fixes 1da177e4c3f4 ("Linux-2.6.12-rc2")
---
 drivers/scsi/scsi_proc.c | 1 +
 1 file changed, 1 insertion(+)
drivers/scsi/scsi_proc.c +1 -0
index fdc355d783da..dbd03360b5a4 100644
@@ -80,6 +80,7 @@ static ssize_t proc_scsi_host_write(struct file *file, const char __user *buf,
 		ret = -EFAULT;
 		if (copy_from_user(page, buf, count))
 			goto out;
+		page[count] = '\0';
 		ret = shost->hostt->write_info(shost, page, count);
 	}
 out:
Signature · 1 line
2.53.0
#58 lore raw

Re: [PATCH RESEND v2 26/51] scsi: core: NUL-terminate what is written to the host proc files

Sashiko has reviewed this patch and found no issues.
Quoted 9 lines

proc_scsi_host_write() copies what is written into a page and hands it to ->write_info() without terminating it. ppa and imm parse it with strncmp() and simple_strtoul(), which read on past what was written into whatever the page held before. Terminate the copy. A write is at most PROC_BLOCK_SIZE bytes, so the page always has room for that.

Fixes 1da177e4c3f4 ("Linux-2.6.12-rc2")

Sashiko has reviewed this patch and found no issues.

Signature · 1 line
Sashiko AI review · https://sashiko.dev/#/patchset/[email protected]?part=26
author maintainer
#59 lore raw

PATCH RESEND v2 27/51 um: NUL-terminate what is written to /proc/exitcode

In reply to Christian Brauner

exitcode_proc_write() copies up to sizeof(buf) bytes of the write into buf and hands it to simple_strtol() without terminating it. So "echo -n 5" parses whatever the stack held after the '5', and a write of seven bytes or more reads past the end of buf. Terminate the copy.

Fixes 1da177e4c3f4 ("Linux-2.6.12-rc2")
---
 arch/um/kernel/exitcode.c | 3 ++-
 1 file changed, 2 insertions(+), 1 deletion(-)
arch/um/kernel/exitcode.c +2 -1
index 43edc2aa57e4..0230354f4812 100644
@@ -43,9 +43,10 @@ static ssize_t exitcode_proc_write(struct file *file,
 	size_t size;
 	int tmp;
 
-	size = min(count, sizeof(buf));
+	size = min(count, sizeof(buf) - 1);
 	if (copy_from_user(buf, buffer, size))
 		return -EFAULT;
+	buf[size] = '\0';
 
 	tmp = simple_strtol(buf, &end, 0);
 	if ((*end != '\0') && !isspace(*end))
Signature · 1 line
2.53.0
#60 lore raw

Re: [PATCH RESEND v2 27/51] um: NUL-terminate what is written to /proc/exitcode

Sashiko has reviewed this patch and found no issues.
Quoted 8 lines

exitcode_proc_write() copies up to sizeof(buf) bytes of the write into buf and hands it to simple_strtol() without terminating it. So "echo -n 5" parses whatever the stack held after the '5', and a write of seven bytes or more reads past the end of buf. Terminate the copy.

Fixes 1da177e4c3f4 ("Linux-2.6.12-rc2")

Sashiko has reviewed this patch and found no issues.

Signature · 1 line
Sashiko AI review · https://sashiko.dev/#/patchset/[email protected]?part=27
author maintainer
#61 lore raw

PATCH RESEND v2 28/51 ntfs3: don't warn when a huge label is written

In reply to Christian Brauner

ntfs3_label_write() allocates as many bytes as are written with plain kmalloc(). A write that is larger than what kmalloc() can hand out then trips the page allocator's warning, which panics a panic_on_warn kernel. Use memdup_user(), which fails such an allocation quietly with -ENOMEM like before.

Fixes 7832e123490a ("fs/ntfs3: Add support /proc/fs/ntfs3/<dev>/volinfo and /proc/fs/ntfs3/<dev>/label")
---
 fs/ntfs3/super.c | 11 +++--------
 1 file changed, 3 insertions(+), 8 deletions(-)
fs/ntfs3/super.c +3 -8
index 29aabdc8a801..37e27b73b7a5 100644
@@ -576,15 +576,10 @@ static ssize_t ntfs3_label_write(struct file *file, const char __user *buffer,
 	if (sb_rdonly(sb))
 		return -EROFS;
 
-	label = kmalloc(count, GFP_NOFS);
+	label = memdup_user(buffer, count);
+	if (IS_ERR(label))
+		return PTR_ERR(label);
 
-	if (!label)
-		return -ENOMEM;
-
-	if (copy_from_user(label, buffer, ret)) {
-		ret = -EFAULT;
-		goto out;
-	}
 	while (ret > 0 && label[ret - 1] == '\n')
 		ret -= 1;
 
Signature · 1 line
2.53.0
#62 lore raw

Re: [PATCH RESEND v2 28/51] ntfs3: don't warn when a huge label is written

Sashiko has reviewed this patch and found no issues.
Quoted 9 lines

ntfs3_label_write() allocates as many bytes as are written with plain kmalloc(). A write that is larger than what kmalloc() can hand out then trips the page allocator's warning, which panics a panic_on_warn kernel. Use memdup_user(), which fails such an allocation quietly with -ENOMEM like before.

Fixes 7832e123490a ("fs/ntfs3: Add support /proc/fs/ntfs3/<dev>/volinfo and /proc/fs/ntfs3/<dev>/label")

Sashiko has reviewed this patch and found no issues.

Signature · 1 line
Sashiko AI review · https://sashiko.dev/#/patchset/[email protected]?part=28
author maintainer
#63 lore raw

PATCH RESEND v2 29/51 proc: don't walk through a non-directory when resolving a name

In reply to Christian Brauner

__xlate_proc_name() walks the components of a name like "a/b/c" and takes whatever it finds for "a" and "b" as the directory to go on in. It never checks that they actually are directories. So proc_create("file/x") hangs x into the subdir tree of the regular file "file". Nobody can look x up there, but remove_proc_subtree() on the file removes and frees x along with it, behind the back of whoever registered x.

pktgen passes the name the writer of "add_device" picks to proc_create_data(), and only the part in front of the '@' has to name a network device:

echo "add_device lo@" > /proc/net/pktgen/kpktgend_0
echo "add_device lo@/x" > /proc/net/pktgen/kpktgend_1
echo "rem_device_all" > /proc/net/pktgen/kpktgend_0
echo "rem_device_all" > /proc/net/pktgen/kpktgend_1

The third write frees both entries and the fourth one makes kpktgend_1 call proc_remove() on the freed second one:

  BUG: KASAN: slab-use-after-free in proc_remove+0x8f/0xa0
  Read of size 8 at addr ff110001134c8e70 by task kpktgend_1/243
  Call Trace:
   proc_remove+0x8f/0xa0
   pktgen_remove_device.isra.0+0x118/0x500
   pktgen_rem_all_ifs+0xeb/0x1a0
   pktgen_thread_worker+0x1b42/0x7280

The files of a network namespace belong to the root of its user namespace and these writes don't require a capability. So once pktgen is loaded an unprivileged user can do this in namespaces of its own.

Treat a component that isn't a directory like one that doesn't exist. All names with a '/' that the tree passes in as literals only walk through directories. pktgen is fixed separately to not pass such names in the first place.

Fixes 1da177e4c3f4 ("Linux-2.6.12-rc2")
---
 fs/proc/generic.c | 2 +-
 1 file changed, 1 insertion(+), 1 deletion(-)
fs/proc/generic.c +1 -1
index 4c3fcaf68ef4..6ac9c4c13897 100644
@@ -170,7 +170,7 @@ static int __xlate_proc_name(const char *name, struct proc_dir_entry **ret,
 	de = *ret ?: &proc_root;
 	while ((next = strchr(cp, '/')) != NULL) {
 		de = pde_subdir_find(de, cp, next - cp);
-		if (!de) {
+		if (!de || !S_ISDIR(de->mode)) {
 			WARN(1, "name '%s'\n", name);
 			return -ENOENT;
 		}
Signature · 1 line
2.53.0
#64 lore raw

Re: [PATCH RESEND v2 29/51] proc: don't walk through a non-directory when resolving a name

Sashiko has reviewed this patch and found no issues.
Quoted 17 lines

__xlate_proc_name() walks the components of a name like "a/b/c" and takes whatever it finds for "a" and "b" as the directory to go on in. It never checks that they actually are directories. So proc_create("file/x") hangs x into the subdir tree of the regular file "file". Nobody can look x up there, but remove_proc_subtree() on the file removes and frees x along with it, behind the back of whoever registered x.

pktgen passes the name the writer of "add_device" picks to proc_create_data(), and only the part in front of the '@' has to name a network device:

echo "add_device lo@" > /proc/net/pktgen/kpktgend_0
echo "add_device lo@/x" > /proc/net/pktgen/kpktgend_1
echo "rem_device_all" > /proc/net/pktgen/kpktgend_0
[ ... ]

Quoted 4 lines
Fixes 1da177e4c3f4 ("Linux-2.6.12-rc2")

Sashiko has reviewed this patch and found no issues.

Signature · 1 line
Sashiko AI review · https://sashiko.dev/#/patchset/[email protected]?part=29
author maintainer
#65 lore raw

PATCH RESEND v2 30/51 net: pktgen: reject device names with a '/'

In reply to Christian Brauner

"add_device" takes a name like eth0@1. Only the part in front of the '@' has to name a network device. The rest is free text and all of it becomes the name of a file in /proc/net/pktgen, where procfs takes a '/' as a directory separator. So "add_device lo@a/b" makes procfs look for a directory "lo@a" that doesn't exist and warn about it. Any user can do that in a network namespace of its own:

name 'lo@a/b'

  WARNING: fs/proc/generic.c:174 at __xlate_proc_name+0xb1/0xf0, CPU#3: bash/241
  Call Trace:
   __proc_create+0xd0/0x9b0
   proc_create_reg+0x45/0xf0
   proc_create_data+0x77/0xf0
   pktgen_thread_write+0xd8d/0x1750

With panic_on_warn that takes the machine down. And if "lo@a" exists because somebody added a device of that name, procfs used to register the new entry below that regular file, and removing "lo@a" freed both.

Reject names with a '/'.

Fixes e6fce5b916cd ("pktgen: multiqueue etc.")
---
 net/core/pktgen.c | 4 ++++
 1 file changed, 4 insertions(+)
net/core/pktgen.c +4 -0
index d63eeadddfcc..02af70d360bc 100644
@@ -3831,6 +3831,10 @@ static int pktgen_add_device(struct pktgen_thread *t, const char *ifname)
 	int err;
 	int node = cpu_to_node(t->cpu);
 
+	/* The name becomes the name of a file in /proc/net/pktgen. */
+	if (strchr(ifname, '/'))
+		return -EINVAL;
+
 	/* We don't allow a device to be on several threads */
 
 	if (__pktgen_NN_threads(t->net, ifname, FIND)) {
Signature · 1 line
2.53.0
#66 lore raw

Re: [PATCH RESEND v2 30/51] net: pktgen: reject device names with a '/'

Sashiko has reviewed this patch and found no issues.
Quoted 19 lines

"add_device" takes a name like eth0@1. Only the part in front of the '@' has to name a network device. The rest is free text and all of it becomes the name of a file in /proc/net/pktgen, where procfs takes a '/' as a directory separator. So "add_device lo@a/b" makes procfs look for a directory "lo@a" that doesn't exist and warn about it. Any user can do that in a network namespace of its own:

name 'lo@a/b'

  WARNING: fs/proc/generic.c:174 at __xlate_proc_name+0xb1/0xf0, CPU#3: bash/241
  Call Trace:
   __proc_create+0xd0/0x9b0
   proc_create_reg+0x45/0xf0
   proc_create_data+0x77/0xf0
   pktgen_thread_write+0xd8d/0x1750

With panic_on_warn that takes the machine down. And if "lo@a" exists because somebody added a device of that name, procfs used to register the new entry below that regular file, and removing "lo@a" freed both.

Quoted 6 lines

Reject names with a '/'.

Fixes e6fce5b916cd ("pktgen: multiqueue etc.")

Sashiko has reviewed this patch and found no issues.

Signature · 1 line
Sashiko AI review · https://sashiko.dev/#/patchset/[email protected]?part=30
author maintainer
#67 lore raw

PATCH RESEND v2 31/51 proc: don't WARN about a name that is already registered

In reply to Christian Brauner

proc_register() WARNs when the directory already has an entry of the same name and fails the registration. Callers that pick their names themselves should never get there but some take names from userspace. pktgen creates a file for each device a writer of "add_device" adds, named after the device. A device can have any name, including "pgctrl" or "kpktgend_0", the names of pktgen's own files:

ip link set lo name pgctrl
ip link set pgctrl up
echo "add_device pgctrl" > /proc/net/pktgen/kpktgend_0

proc_dir_entry 'pktgen/pgctrl' already registered

  WARNING: fs/proc/generic.c:404 at proc_register+0x555/0x8b0, CPU#0: bash/241
  Call Trace:
   proc_create_data+0x9f/0xf0
   pktgen_thread_write+0xd9b/0x1780
   proc_reg_write+0x1c2/0x3c0
   vfs_write+0x1cd/0xfa0

The files of a network namespace belong to the root of its user namespace and none of this requires a capability. So once pktgen is loaded an unprivileged user can taint the kernel, or crash it with panic_on_warn, from namespaces of its own. pktgen itself copes with the failed registration just fine.

So go back to what proc_register() did before commit 6c2f91e077f1 ("proc: use WARN() rather than printk+backtrace") and what sysfs_warn_dup() does for sysfs: report the name with pr_warn() and dump the stack. While at it, do that after dropping proc_subdir_lock instead of printing a backtrace while holding the lock that every lookup and readdir in procfs needs.

Fixes 6c2f91e077f1 ("proc: use WARN() rather than printk+backtrace")
---
 fs/proc/generic.c | 5 +++--
 1 file changed, 3 insertions(+), 2 deletions(-)
fs/proc/generic.c +3 -2
index 6ac9c4c13897..9e59796349e1 100644
@@ -402,9 +402,10 @@ struct proc_dir_entry *proc_register(struct proc_dir_entry *dir,
 	write_lock(&proc_subdir_lock);
 	dp->parent = dir;
 	if (pde_subdir_insert(dir, dp) == false) {
-		WARN(1, "proc_dir_entry '%s/%s' already registered\n",
-		     dir->name, dp->name);
 		write_unlock(&proc_subdir_lock);
+		pr_warn("proc_dir_entry '%s/%s' already registered\n",
+			dir->name, dp->name);
+		dump_stack();
 		goto out_free_inum;
 	}
 	write_unlock(&proc_subdir_lock);
Signature · 1 line
2.53.0
#68 lore raw

Re: [PATCH RESEND v2 31/51] proc: don't WARN about a name that is already registered

Sashiko has reviewed this patch and found no issues.
Quoted 15 lines

proc_register() WARNs when the directory already has an entry of the same name and fails the registration. Callers that pick their names themselves should never get there but some take names from userspace. pktgen creates a file for each device a writer of "add_device" adds, named after the device. A device can have any name, including "pgctrl" or "kpktgend_0", the names of pktgen's own files:

ip link set lo name pgctrl
ip link set pgctrl up
echo "add_device pgctrl" > /proc/net/pktgen/kpktgend_0

proc_dir_entry 'pktgen/pgctrl' already registered

  WARNING: fs/proc/generic.c:404 at proc_register+0x555/0x8b0, CPU#0: bash/241
  Call Trace:
   proc_create_data+0x9f/0xf0
Quoted 6 lines

[ ... ]

Fixes 6c2f91e077f1 ("proc: use WARN() rather than printk+backtrace")

Sashiko has reviewed this patch and found no issues.

Signature · 1 line
Sashiko AI review · https://sashiko.dev/#/patchset/[email protected]?part=31
author maintainer
#69 lore raw

PATCH RESEND v2 32/51 proc: resume readdir after the last name it returned

In reply to Christian Brauner

proc_readdir_de() counts the entries of a directory and resumes a listing at the number getdents64() stopped at. The entries are sorted by name, so one that is added or removed in between shifts everything behind it by one. Listing /proc/net/dev_snmp6 with a buffer that holds ".", ".." and "lo" and adding a device whose name sorts before "lo" makes the next call return "lo" a second time. Removing one that sorted before the position makes the next call skip an entry instead.

Since commit 895b4c0c79b0 ("fs/proc: fix uaf in proc_readdir_de()") an entry that is removed while it is being emitted also ends the listing right there. pde_subdir_next() finds nothing after an erased entry, so proc_readdir_de() reports the end of the directory and the next call resumes by number, skipping another entry. For /proc itself proc_root_readdir() takes that as the end of the static entries and moves on to the pids, so the rest of the static entries is missing. And if the position is behind the last entry when a call starts proc_readdir_de() returns 0, so /proc then lists no pids at all.

So remember the name of the last entry a call emitted in the file and resume at the first entry after it, like kernfs resumes after the node it stopped at. An entry that was removed while it was emitted is continued after by its name as well. If the position was moved by a seek in between the listing counts from the start like before.

Fixes 1da177e4c3f4 ("Linux-2.6.12-rc2")
Fixes 895b4c0c79b0 ("fs/proc: fix uaf in proc_readdir_de()")
---
 fs/proc/generic.c  | 89 ++++++++++++++++++++++++++++++++++++++++++++++--------
 fs/proc/internal.h |  1 +
 fs/proc/proc_net.c |  1 +
 fs/proc/root.c     |  1 +
 4 files changed, 80 insertions(+), 12 deletions(-)
fs/proc/generic.c +77 -12
index 9e59796349e1..588999058e66 100644
@@ -87,6 +87,28 @@ static struct proc_dir_entry *pde_subdir_find(struct proc_dir_entry *dir,
 	return NULL;
 }
 
+/* The first entry of @dir that sorts after @name. */
+static struct proc_dir_entry *pde_subdir_after(struct proc_dir_entry *dir,
+					       const char *name,
+					       unsigned int len)
+{
+	struct rb_node *node = dir->subdir.rb_node, *after = NULL;
+
+	while (node) {
+		struct proc_dir_entry *de = rb_entry(node,
+						     struct proc_dir_entry,
+						     subdir_node);
+
+		if (proc_match(name, de, len) < 0) {
+			after = node;
+			node = node->rb_left;
+		} else {
+			node = node->rb_right;
+		}
+	}
+	return rb_entry_safe(after, struct proc_dir_entry, subdir_node);
+}
+
 static bool pde_subdir_insert(struct proc_dir_entry *dir,
 			      struct proc_dir_entry *de)
 {
@@ -278,6 +300,40 @@ struct dentry *proc_lookup(struct inode *dir, struct dentry *dentry,
 	return proc_lookup_de(dir, dentry, PDE(dir));
 }
 
+/*
+ * Where the next readdir resumes. The entries are counted, so one that is
+ * added or removed in front of the position would shift what the next call
+ * returns. The name of the last entry emitted doesn't move.
+ */
+struct proc_dir_cursor {
+	loff_t pos;			/* the position behind the entry */
+	unsigned int len;
+	char name[NAME_MAX + 1];
+};
+
+/* If this can't remember the entry the next call counts from the start. */
+static void proc_dir_cursor_set(struct file *file, struct proc_dir_entry *de,
+				loff_t pos)
+{
+	struct proc_dir_cursor *cursor = file->private_data;
+
+	if (!cursor) {
+		cursor = kmalloc(sizeof(*cursor), GFP_KERNEL);
+		if (!cursor)
+			return;
+		file->private_data = cursor;
+	}
+	cursor->pos = pos;
+	cursor->len = de->namelen;
+	memcpy(cursor->name, de->name, de->namelen);
+}
+
+int proc_dir_release(struct inode *inode, struct file *file)
+{
+	kfree(file->private_data);
+	return 0;
+}
+
 /*
  * This returns non-zero if at EOF, so that the /proc
  * root directory can use this and check if it should
@@ -290,23 +346,26 @@ struct dentry *proc_lookup(struct inode *dir, struct dentry *dentry,
 int proc_readdir_de(struct file *file, struct dir_context *ctx,
 		    struct proc_dir_entry *de)
 {
+	struct proc_dir_cursor *cursor = file->private_data;
+	struct proc_dir_entry *dir = de;
 	int i;
 
 	if (!dir_emit_dots(file, ctx))
 		return 0;
 
-	i = ctx->pos - 2;
 	read_lock(&proc_subdir_lock);
-	de = pde_subdir_first(de);
-	for (;;) {
-		if (!de) {
-			read_unlock(&proc_subdir_lock);
-			return 0;
-		}
-		if (!i)
-			break;
-		de = pde_subdir_next(de);
-		i--;
+	if (cursor && cursor->pos == ctx->pos) {
+		/* Resume after the last entry emitted, wherever it is now. */
+		de = pde_subdir_after(dir, cursor->name, cursor->len);
+	} else {
+		/* Moved by a seek, count from the start like always. */
+		de = pde_subdir_first(dir);
+		for (i = ctx->pos - 2; de && i; i--)
+			de = pde_subdir_next(de);
+	}
+	if (!de) {
+		read_unlock(&proc_subdir_lock);
+		return 1;
 	}
 
 	do {
@@ -319,8 +378,13 @@ int proc_readdir_de(struct file *file, struct dir_context *ctx,
 			return 0;
 		}
 		ctx->pos++;
+		proc_dir_cursor_set(file, de, ctx->pos);
 		read_lock(&proc_subdir_lock);
-		next = pde_subdir_next(de);
+		/* Removed in the meantime, go on after its name. */
+		if (RB_EMPTY_NODE(&de->subdir_node))
+			next = pde_subdir_after(dir, de->name, de->namelen);
+		else
+			next = pde_subdir_next(de);
 		pde_put(de);
 		de = next;
 	} while (de);
@@ -348,6 +412,7 @@ static const struct file_operations proc_dir_operations = {
 	.llseek			= generic_file_llseek,
 	.read			= generic_read_dir,
 	.iterate_shared		= proc_readdir,
+	.release		= proc_dir_release,
 };
 
 static int proc_net_d_revalidate(struct inode *dir, const struct qstr *name,
fs/proc/internal.h +1 -0
index df873df9afc5..04f7ce2b24ed 100644
@@ -287,6 +287,7 @@ extern struct dentry *proc_lookup(struct inode *, struct dentry *, unsigned int)
 struct dentry *proc_lookup_de(struct inode *, struct dentry *, struct proc_dir_entry *);
 extern int proc_readdir(struct file *, struct dir_context *);
 int proc_readdir_de(struct file *, struct dir_context *, struct proc_dir_entry *);
+int proc_dir_release(struct inode *, struct file *);
 
 static inline void pde_get(struct proc_dir_entry *pde)
 {
fs/proc/proc_net.c +1 -0
index b1f5eafb069a..dbcf87a257e1 100644
@@ -351,6 +351,7 @@ const struct file_operations proc_net_operations = {
 	.llseek		= generic_file_llseek,
 	.read		= generic_read_dir,
 	.iterate_shared	= proc_tgid_net_readdir,
+	.release	= proc_dir_release,
 };
 
 static __net_init int proc_net_ns_init(struct net *net)
fs/proc/root.c +1 -0
index 7fbbe92bf73a..dfee1caa26f7 100644
@@ -441,6 +441,7 @@ static const struct file_operations proc_root_operations = {
 	.read		 = generic_read_dir,
 	.iterate_shared	 = proc_root_readdir,
 	.llseek		= generic_file_llseek,
+	.release	= proc_dir_release,
 };
 
 /*
Signature · 1 line
2.53.0
#70 lore raw

Re: [PATCH RESEND v2 32/51] proc: resume readdir after the last name it returned

Thank you for your contribution! Sashiko AI review found 1 potential issue(s) to consider: - [High] proc: proc_readdir_de() returns 1 at EOF, breaking old_readdir() --

Thank you for your contribution! Sashiko AI review found 1 potential issue(s) to consider:
- [High] proc: proc_readdir_de() returns 1 at EOF, breaking old_readdir() --

commit 6510b1c4f87c45306294a13ba8447b50990db356
Author: Christian Brauner <[email protected]>

proc: resume readdir after the last name it returned

This commit records the name of the last emitted directory entry in a cursor stored in file->private_data so that subsequent readdir calls can resume after that entry by name rather than by numeric index. It also continues after an entry's name if the entry is removed while being emitted, and returns 1 when no entries remain at the start of proc_readdir_de().

Quoted 4 lines
fs/proc/generic.c +0 -0
index 9e59796349e15..588999058e66d 100644

[ ... ]

Quoted 26 lines
fs/proc/generic.c +5 -11
@@ -290,23 +346,26 @@ struct dentry *proc_lookup(struct inode *dir, struct dentry *dentry,
 int proc_readdir_de(struct file *file, struct dir_context *ctx,
 		    struct proc_dir_entry *de)
 {
+	struct proc_dir_cursor *cursor = file->private_data;
+	struct proc_dir_entry *dir = de;
 	int i;
 
 	if (!dir_emit_dots(file, ctx))
 		return 0;
 
-	i = ctx->pos - 2;
 	read_lock(&proc_subdir_lock);
-	de = pde_subdir_first(de);
-	for (;;) {
-		if (!de) {
-			read_unlock(&proc_subdir_lock);
-			return 0;
-		}
-		if (!i)
-			break;
-		de = pde_subdir_next(de);
-		i--;
+	if (cursor && cursor->pos == ctx->pos) {
+		/* Resume after the last entry emitted, wherever it is now. */
+		de = pde_subdir_after(dir, cursor->name, cursor->len);

fs/proc/generic.c struct dentry *proc_lookup(struct inode *dir, struct dentry *dentry, · line 369

Quoted 10 lines
fs/proc/generic.c +9 -0
+	} else {
+		/* Moved by a seek, count from the start like always. */
+		de = pde_subdir_first(dir);
+		for (i = ctx->pos - 2; de && i; i--)
+			de = pde_subdir_next(de);
+	}
+	if (!de) {
+		read_unlock(&proc_subdir_lock);
+		return 1;
 	}

[Severity: High]
Does returning 1 here when !de cause old_readdir() and compat_old_readdir() to return 1 instead of 0 at end-of-directory on non-root /proc directories?

While proc_root_readdir() checks for a positive return value from proc_readdir_de() to advance to the PID entries, proc_readdir() (for proc_dir_operations) and proc_tgid_net_readdir() (for proc_net_operations) return the result of proc_readdir_de() directly as their .iterate_shared return value:

fs/proc/generic.c:proc_readdir() {
	...
	return proc_readdir_de(file, ctx, PDE(inode));
}
fs/proc/proc_net.c:proc_tgid_net_readdir() {
	...
	ret = proc_readdir_de(file, ctx, net->proc_net);
	put_net(net);
	return ret;
}

Previously, proc_readdir_de() only returned 1 after completing the do-while loop (where dir_emit() had succeeded at least once and set buf.result = 1 in fillonedir()), and returned 0 when !de at the start of the call.

In fs/readdir.c, old_readdir() and compat_old_readdir() do:

	error = iterate_dir(fd_file(f), &buf.ctx);
	if (buf.result)
		error = buf.result;

	return error;

When old_readdir() or compat_old_readdir() is called at EOF (ctx->pos >= 2 and !de), dir_emit_dots() returns true without invoking ctx->actor, so buf.result remains 0 and iterate_dir() returns 1 from proc_readdir_de(). Wouldn't old_readdir() and compat_old_readdir() then return 1 to userspace without writing to the dirent buffer or advancing file->f_pos, causing callers to read uninitialized or stale dirent memory in an infinite loop?

Signature · 1 line
Sashiko AI review · https://sashiko.dev/#/patchset/[email protected]?part=32
author maintainer
#71 lore raw

PATCH RESEND v2 33/51 selftests/proc: check a /proc listing while entries come and go

In reply to Christian Brauner

List /proc/net/dev_snmp6 of a new network namespace while a tun device comes and goes:

- with a buffer that holds the dots and "lo", add a device whose name sorts first, finish the listing: "lo" is listed once

- with that device added and a buffer that holds the dots and it, remove it, finish the listing: "lo" is still listed

- with that device added, stall getdents64() on a userfaultfd page while it writes the device's entry, remove the device, finish the
listing: "lo" is still listed

All three fail without the fix, the first lists "lo" twice, the other two not at all.

---
 tools/testing/selftests/proc/.gitignore           |   1 +
 tools/testing/selftests/proc/Makefile             |   1 +
 tools/testing/selftests/proc/config               |   4 +
 tools/testing/selftests/proc/proc-readdir-churn.c | 240 ++++++++++++++++++++++
 4 files changed, 246 insertions(+)
tools/testing/selftests/proc/.gitignore +1 -0
index 9c9735570abf..8520c7878ea2 100644
@@ -8,6 +8,7 @@
 /proc-maps-race
 /proc-multiple-procfs
 /proc-net-dev-lseek
+/proc-readdir-churn
 /proc-empty-vm
 /proc-pid-vm
 /proc-self-map-files-001
tools/testing/selftests/proc/Makefile +1 -0
index a7de2bb6d8be..e0c0d313f4d0 100644
@@ -11,6 +11,7 @@ TEST_GEN_PROGS += proc-2-is-kthread
 TEST_GEN_PROGS += proc-loadavg-001
 TEST_GEN_PROGS += proc-maps-race
 TEST_GEN_PROGS += proc-net-dev-lseek
+TEST_GEN_PROGS += proc-readdir-churn
 TEST_GEN_PROGS += proc-empty-vm
 TEST_GEN_PROGS += proc-pid-vm
 TEST_GEN_PROGS += proc-self-map-files-001
tools/testing/selftests/proc/config +4 -0
index 68fbd2b35884..052e365af5a9 100644
@@ -1 +1,5 @@
 CONFIG_PROC_FS=y
+CONFIG_NET_NS=y
+CONFIG_IPV6=y
+CONFIG_TUN=y
+CONFIG_USERFAULTFD=y
tools/testing/selftests/proc/proc-readdir-churn.c new file +240 -0

240 lines not on this page · raw message

Signature · 1 line
2.53.0
#72 lore raw

Re: [PATCH RESEND v2 33/51] selftests/proc: check a /proc listing while entries come and go

Sashiko has reviewed this patch and found no issues.
Quoted 9 lines

List /proc/net/dev_snmp6 of a new network namespace while a tun device comes and goes:

- with a buffer that holds the dots and "lo", add a device whose name sorts first, finish the listing: "lo" is listed once

- with that device added and a buffer that holds the dots and it, remove it, finish the listing: "lo" is still listed

Quoted 8 lines

- with that device added, stall getdents64() on a userfaultfd page while it writes the device's entry, remove the device, finish the
listing: "lo" is still listed

All three fail without the fix, the first lists "lo" twice, the other two not at all.

Sashiko has reviewed this patch and found no issues.

Signature · 1 line
Sashiko AI review · https://sashiko.dev/#/patchset/[email protected]?part=33
author maintainer
#73 lore raw

PATCH RESEND v2 34/51 proc: let proc_remove() remove the entry it was given

In reply to Christian Brauner

proc_remove() looks the entry up by its name in its parent and removes whatever it finds there:

  remove_proc_subtree(de->name, de->parent);

If the entry was removed already, say along with its parent, that is either nothing or a different entry that got the same name in the meantime, and de->parent may well be gone. Two removals of the same entry are a bug in the caller, but going by the name turns it into removing an entry that belongs to somebody else.

Since commit 895b4c0c79b0 ("fs/proc: fix uaf in proc_readdir_de()") an entry that was unlinked has an empty rb node. So check for that under proc_subdir_lock and otherwise remove the entry itself, with the loop of remove_proc_subtree() moved into a helper both of them use. Nothing can help a caller that passes an entry that has been freed already.

Fixes a8ca16ea7b0a ("proc: Supply a function to remove a proc entry by PDE")
---
 fs/proc/generic.c | 78 ++++++++++++++++++++++++++++++++++++-------------------
 1 file changed, 51 insertions(+), 27 deletions(-)
fs/proc/generic.c +51 -27
index 588999058e66..9a0a2fcac7c7 100644
@@ -818,33 +818,14 @@ void remove_proc_entry(const char *name, struct proc_dir_entry *parent)
 }
 EXPORT_SYMBOL(remove_proc_entry);
 
-int remove_proc_subtree(const char *name, struct proc_dir_entry *parent)
+/*
+ * Remove @root, already erased from its parent, and everything below it.
+ * Called with proc_subdir_lock held for writing, returns with it dropped.
+ */
+static int __remove_proc_subtree(struct proc_dir_entry *root)
 {
-	struct proc_dir_entry *root = NULL, *de, *next;
-	const char *fn = name;
-	unsigned int len;
-
-	write_lock(&proc_subdir_lock);
-	if (__xlate_proc_name(name, &parent, &fn) != 0) {
-		write_unlock(&proc_subdir_lock);
-		return -ENOENT;
-	}
-	len = strlen(fn);
+	struct proc_dir_entry *de = root, *next;
 
-	root = pde_subdir_find(parent, fn, len);
-	if (!root) {
-		write_unlock(&proc_subdir_lock);
-		return -ENOENT;
-	}
-	if (unlikely(pde_is_permanent(root))) {
-		write_unlock(&proc_subdir_lock);
-		WARN(1, "removing permanent /proc entry '%s/%s'",
-			root->parent->name, root->name);
-		return -EINVAL;
-	}
-	pde_erase(root, parent);
-
-	de = root;
 	while (1) {
 		next = pde_subdir_first(de);
 		if (next) {
@@ -872,6 +853,34 @@ int remove_proc_subtree(const char *name, struct proc_dir_entry *parent)
 	pde_put(root);
 	return 0;
 }
+
+int remove_proc_subtree(const char *name, struct proc_dir_entry *parent)
+{
+	struct proc_dir_entry *root = NULL;
+	const char *fn = name;
+	unsigned int len;
+
+	write_lock(&proc_subdir_lock);
+	if (__xlate_proc_name(name, &parent, &fn) != 0) {
+		write_unlock(&proc_subdir_lock);
+		return -ENOENT;
+	}
+	len = strlen(fn);
+
+	root = pde_subdir_find(parent, fn, len);
+	if (!root) {
+		write_unlock(&proc_subdir_lock);
+		return -ENOENT;
+	}
+	if (unlikely(pde_is_permanent(root))) {
+		write_unlock(&proc_subdir_lock);
+		WARN(1, "removing permanent /proc entry '%s/%s'",
+			root->parent->name, root->name);
+		return -EINVAL;
+	}
+	pde_erase(root, parent);
+	return __remove_proc_subtree(root);
+}
 EXPORT_SYMBOL(remove_proc_subtree);
 
 void *proc_get_parent_data(const struct inode *inode)
@@ -883,8 +892,23 @@ EXPORT_SYMBOL_GPL(proc_get_parent_data);
 
 void proc_remove(struct proc_dir_entry *de)
 {
-	if (de)
-		remove_proc_subtree(de->name, de->parent);
+	if (!de)
+		return;
+
+	write_lock(&proc_subdir_lock);
+	/* Removed already, maybe along with its parent. */
+	if (RB_EMPTY_NODE(&de->subdir_node)) {
+		write_unlock(&proc_subdir_lock);
+		return;
+	}
+	if (unlikely(pde_is_permanent(de))) {
+		write_unlock(&proc_subdir_lock);
+		WARN(1, "removing permanent /proc entry '%s/%s'",
+		     de->parent->name, de->name);
+		return;
+	}
+	pde_erase(de, de->parent);
+	__remove_proc_subtree(de);
 }
 EXPORT_SYMBOL(proc_remove);
 
Signature · 1 line
2.53.0
#74 lore raw

Re: [PATCH RESEND v2 34/51] proc: let proc_remove() remove the entry it was given

Sashiko has reviewed this patch and found no issues.
Quoted 18 lines

proc_remove() looks the entry up by its name in its parent and removes whatever it finds there:

  remove_proc_subtree(de->name, de->parent);

If the entry was removed already, say along with its parent, that is either nothing or a different entry that got the same name in the meantime, and de->parent may well be gone. Two removals of the same entry are a bug in the caller, but going by the name turns it into removing an entry that belongs to somebody else.

Since commit 895b4c0c79b0 ("fs/proc: fix uaf in proc_readdir_de()") an entry that was unlinked has an empty rb node. So check for that under proc_subdir_lock and otherwise remove the entry itself, with the loop of remove_proc_subtree() moved into a helper both of them use. Nothing can help a caller that passes an entry that has been freed already.

Quoted 3 lines
Fixes a8ca16ea7b0a ("proc: Supply a function to remove a proc entry by PDE")

Sashiko has reviewed this patch and found no issues.

Signature · 1 line
Sashiko AI review · https://sashiko.dev/#/patchset/[email protected]?part=34
author maintainer
#75 lore raw

PATCH RESEND v2 35/51 proc: warn about entries left in /proc/net of a dying namespace

In reply to Christian Brauner

proc_net_ns_exit() runs after all the other pernet exits and frees net->proc_net right after removing "stat" from it. An entry that some pernet exit forgot to remove is left with a freed ->parent, and so PDE_NET() hands seq_open_net() and single_open_net() a freed struct net when the entry is opened through a file descriptor that someone kept.

There is no such entry in the tree that we know of, but nothing would tell us about one either. So warn about it like remove_proc_entry() does for a directory that isn't empty.

Fixes e9720acd728a ("[NET]: Make /proc/net a symlink on /proc/self/net (v3)")
---
 fs/proc/proc_net.c | 6 ++++++
 1 file changed, 6 insertions(+)
fs/proc/proc_net.c +6 -0
index dbcf87a257e1..df5484813d5d 100644
@@ -410,7 +410,13 @@ out:
 
 static __net_exit void proc_net_ns_exit(struct net *net)
 {
+	struct proc_dir_entry *left;
+
 	remove_proc_entry("stat", net->proc_net);
+	/* Whatever is left still points at net->proc_net and so at net. */
+	left = rb_entry_safe(rb_first(&net->proc_net->subdir),
+			     struct proc_dir_entry, subdir_node);
+	WARN(left, "/proc/net: leaking at least '%s'\n", left->name);
 	pde_free(net->proc_net);
 }
 
Signature · 1 line
2.53.0
#76 lore raw

Re: [PATCH RESEND v2 35/51] proc: warn about entries left in /proc/net of a dying namespace

Sashiko has reviewed this patch and found no issues.
Quoted 6 lines

proc_net_ns_exit() runs after all the other pernet exits and frees net->proc_net right after removing "stat" from it. An entry that some pernet exit forgot to remove is left with a freed ->parent, and so PDE_NET() hands seq_open_net() and single_open_net() a freed struct net when the entry is opened through a file descriptor that someone kept.

Quoted 7 lines

There is no such entry in the tree that we know of, but nothing would tell us about one either. So warn about it like remove_proc_entry() does for a directory that isn't empty.

Fixes e9720acd728a ("[NET]: Make /proc/net a symlink on /proc/self/net (v3)")

Sashiko has reviewed this patch and found no issues.

Signature · 1 line
Sashiko AI review · https://sashiko.dev/#/patchset/[email protected]?part=35
author maintainer
#77 lore raw

PATCH RESEND v2 36/51 proc: don't let NOMMU map procfs files

In reply to Christian Brauner

Every procfs file has a ->mmap since commit 786d7e1612f0 ("Fix rmmod/read/write races in /proc entries"), whether the entry has a ->proc_mmap or not. On NOMMU validate_mmap_request() takes that to mean the file can be mapped. procfs has no ->mmap_capabilities so a regular file gets NOMMU_MAP_COPY, and a private mapping never calls ->mmap at all. Instead do_mmap() takes nommu_region_sem for writing and do_mmap_private() reads the file into the copy with kernel_read().

Reading /proc/maps takes nommu_region_sem as well:

mmap(NULL, 4096, PROT_READ, MAP_PRIVATE, open("/proc/maps", O_RDONLY), 0)

do_mmap() // down_write(&nommu_region_sem)
-> do_mmap_private()

     -> kernel_read()
        -> seq_read_iter()
           -> nommu_region_list_start()   // down_read()

The task hangs for good, holding nommu_region_sem and its own mmap_lock, and every mmap(), munmap() and exit after that hangs behind it. /proc/maps is 0444 so any user can do that.

Give the procfs files a ->mmap_capabilities on NOMMU that allows nothing. That covers every entry and not just /proc/maps, procfs can't know which entry's read takes nommu_region_sem. Mapping a procfs file then fails with -ENODEV, like mapping a file without ->mmap did before 786d7e1612f0. NOMMU never called ->proc_mmap() for a regular file anyway, procfs never offered NOMMU_MAP_DIRECT.

Fixes 786d7e1612f0 ("Fix rmmod/read/write races in /proc entries")
---
 fs/proc/inode.c | 24 ++++++++++++++++++++++++
 1 file changed, 24 insertions(+)
fs/proc/inode.c +24 -0
index b7634f975d98..9933f03ab9fb 100644
@@ -466,6 +466,18 @@ proc_reg_get_unmapped_area(struct file *file, unsigned long orig_addr,
 	return rv;
 }
 
+#ifndef CONFIG_MMU
+/*
+ * NOMMU never calls ->proc_mmap() for a regular file. It reads the file into
+ * a private copy instead, with nommu_region_sem held for writing, which
+ * reading /proc/maps takes as well. Don't map procfs files at all.
+ */
+static unsigned int proc_reg_mmap_capabilities(struct file *file)
+{
+	return 0;
+}
+#endif
+
 static int proc_reg_open(struct inode *inode, struct file *file)
 {
 	struct proc_dir_entry *pde = PDE(inode);
@@ -559,6 +571,9 @@ static const struct file_operations proc_reg_file_ops = {
 	.unlocked_ioctl	= proc_reg_unlocked_ioctl,
 	.mmap		= proc_reg_mmap,
 	.get_unmapped_area = proc_reg_get_unmapped_area,
+#ifndef CONFIG_MMU
+	.mmap_capabilities = proc_reg_mmap_capabilities,
+#endif
 	.open		= proc_reg_open,
 	.release	= proc_reg_release,
 };
@@ -572,6 +587,9 @@ static const struct file_operations proc_iter_file_ops = {
 	.unlocked_ioctl	= proc_reg_unlocked_ioctl,
 	.mmap		= proc_reg_mmap,
 	.get_unmapped_area = proc_reg_get_unmapped_area,
+#ifndef CONFIG_MMU
+	.mmap_capabilities = proc_reg_mmap_capabilities,
+#endif
 	.open		= proc_reg_open,
 	.release	= proc_reg_release,
 };
@@ -586,6 +604,9 @@ static const struct file_operations proc_reg_file_ops_compat = {
 	.compat_ioctl	= proc_reg_compat_ioctl,
 	.mmap		= proc_reg_mmap,
 	.get_unmapped_area = proc_reg_get_unmapped_area,
+#ifndef CONFIG_MMU
+	.mmap_capabilities = proc_reg_mmap_capabilities,
+#endif
 	.open		= proc_reg_open,
 	.release	= proc_reg_release,
 };
@@ -600,6 +621,9 @@ static const struct file_operations proc_iter_file_ops_compat = {
 	.compat_ioctl	= proc_reg_compat_ioctl,
 	.mmap		= proc_reg_mmap,
 	.get_unmapped_area = proc_reg_get_unmapped_area,
+#ifndef CONFIG_MMU
+	.mmap_capabilities = proc_reg_mmap_capabilities,
+#endif
 	.open		= proc_reg_open,
 	.release	= proc_reg_release,
 };
Signature · 1 line
2.53.0
#78 lore raw

Re: [PATCH RESEND v2 36/51] proc: don't let NOMMU map procfs files

Sashiko has reviewed this patch and found no issues.
Quoted 14 lines

Every procfs file has a ->mmap since commit 786d7e1612f0 ("Fix rmmod/read/write races in /proc entries"), whether the entry has a ->proc_mmap or not. On NOMMU validate_mmap_request() takes that to mean the file can be mapped. procfs has no ->mmap_capabilities so a regular file gets NOMMU_MAP_COPY, and a private mapping never calls ->mmap at all. Instead do_mmap() takes nommu_region_sem for writing and do_mmap_private() reads the file into the copy with kernel_read().

Reading /proc/maps takes nommu_region_sem as well:

mmap(NULL, 4096, PROT_READ, MAP_PRIVATE, open("/proc/maps", O_RDONLY), 0)

do_mmap() // down_write(&nommu_region_sem)
-> do_mmap_private()

Quoted 7 lines
     -> kernel_read()

[ ... ]

Fixes 786d7e1612f0 ("Fix rmmod/read/write races in /proc entries")

Sashiko has reviewed this patch and found no issues.

Signature · 1 line
Sashiko AI review · https://sashiko.dev/#/patchset/[email protected]?part=36
author maintainer
#79 lore raw

PATCH RESEND v2 37/51 proc/vmcore: don't let vmcore_cleanup() run twice at once

In reply to Christian Brauner

vmcore_cleanup() has a single caller, fadump's release_mem_store() on powerpc. That checks fw_dump.dump_active without a lock and calls vmcore_cleanup() without one, and kernfs only serializes the writers of one open file. So two tasks that write to /sys/kernel/fadump/release_mem through different files run vmcore_cleanup() at the same time.

The first one removes /proc/vmcore and waits for its readers in proc_remove(). The second one finds the entry already unlinked, returns from proc_remove() right away and frees vmcore_list, the ELF headers and the device dumps while those readers still walk them. Or both of them free the same lists at once.

Serialize vmcore_cleanup() with a mutex of its own. It can't be vmcore_mutex, removing /proc/vmcore calls release_vmcore() which takes it. The second caller then finds nothing left to free.

Fixes b500afff11f6 ("fadump: Invalidate registration and release reserved memory for general use.")
---
 fs/proc/vmcore.c | 5 +++++
 1 file changed, 5 insertions(+)
fs/proc/vmcore.c +5 -0
index 1fe70c4ecc54..ccb795b85509 100644
@@ -1764,6 +1764,11 @@ fs_initcall(vmcore_init);
 /* Cleanup function for vmcore module. */
 void vmcore_cleanup(void)
 {
+	/* Not vmcore_mutex, removing /proc/vmcore calls release_vmcore(). */
+	static DEFINE_MUTEX(vmcore_cleanup_mutex);
+
+	/* Two writers of fadump's release_mem can get here at once. */
+	guard(mutex)(&vmcore_cleanup_mutex);
 	if (proc_vmcore) {
 		proc_remove(proc_vmcore);
 		proc_vmcore = NULL;
Signature · 1 line
2.53.0
#80 lore raw

Re: [PATCH RESEND v2 37/51] proc/vmcore: don't let vmcore_cleanup() run twice at once

Sashiko has reviewed this patch and found no issues.
Quoted 13 lines

vmcore_cleanup() has a single caller, fadump's release_mem_store() on powerpc. That checks fw_dump.dump_active without a lock and calls vmcore_cleanup() without one, and kernfs only serializes the writers of one open file. So two tasks that write to /sys/kernel/fadump/release_mem through different files run vmcore_cleanup() at the same time.

The first one removes /proc/vmcore and waits for its readers in proc_remove(). The second one finds the entry already unlinked, returns from proc_remove() right away and frees vmcore_list, the ELF headers and the device dumps while those readers still walk them. Or both of them free the same lists at once.

Quoted 8 lines

Serialize vmcore_cleanup() with a mutex of its own. It can't be vmcore_mutex, removing /proc/vmcore calls release_vmcore() which takes it. The second caller then finds nothing left to free.

Fixes b500afff11f6 ("fadump: Invalidate registration and release reserved memory for general use.")

Sashiko has reviewed this patch and found no issues.

Signature · 1 line
Sashiko AI review · https://sashiko.dev/#/patchset/[email protected]?part=37
author maintainer
#81 lore raw

PATCH RESEND v2 38/51 powerpc/crash_dump: check ioremap_cache() in copy_oldmem_page()

In reply to Christian Brauner

copy_oldmem_page() maps a page of the old kernel that isn't in the linear mapping with ioremap_cache() and copies from it without checking whether the mapping worked. If it didn't, the copy reads from an offset into the NULL page. That oopses unless the copy happens to be a user copy, whose exception table entries turn the fault into a short copy.

Return -ENOMEM like the other architectures do. read_from_oldmem() turns that into -EFAULT like any other short copy.

Fixes 54c32021eb6f ("[PATCH] powerpc: Add arch-dependent copy_oldmem_page")
---
 arch/powerpc/kernel/crash_dump.c | 2 ++
 1 file changed, 2 insertions(+)
arch/powerpc/kernel/crash_dump.c +2 -0
index 103b6605dd68..1543917bd3e1 100644
@@ -86,6 +86,8 @@ ssize_t copy_oldmem_page(struct iov_iter *iter, unsigned long pfn,
 		csize = copy_to_iter(vaddr + offset, csize, iter);
 	} else {
 		vaddr = ioremap_cache(paddr, PAGE_SIZE);
+		if (!vaddr)
+			return -ENOMEM;
 		csize = copy_to_iter(vaddr + offset, csize, iter);
 		iounmap(vaddr);
 	}
Signature · 1 line
2.53.0
#82 lore raw

Re: [PATCH RESEND v2 38/51] powerpc/crash_dump: check ioremap_cache() in copy_oldmem_page()

Sashiko has reviewed this patch and found no issues.
Quoted 6 lines

copy_oldmem_page() maps a page of the old kernel that isn't in the linear mapping with ioremap_cache() and copies from it without checking whether the mapping worked. If it didn't, the copy reads from an offset into the NULL page. That oopses unless the copy happens to be a user copy, whose exception table entries turn the fault into a short copy.

Quoted 7 lines

Return -ENOMEM like the other architectures do. read_from_oldmem() turns that into -EFAULT like any other short copy.

Fixes 54c32021eb6f ("[PATCH] powerpc: Add arch-dependent copy_oldmem_page")

Sashiko has reviewed this patch and found no issues.

Signature · 1 line
Sashiko AI review · https://sashiko.dev/#/patchset/[email protected]?part=38
author maintainer
#83 lore raw

PATCH RESEND v2 39/51 powerpc/crash_dump: recover from a machine check in copy_oldmem_page()

In reply to Christian Brauner

A capture kernel reads the memory of the crashed kernel, and that memory may well have uncorrectable errors. On powerpc a machine check in the kernel is only recovered from if the instruction that took it has an exception table entry (cf. mce_common_process_ue()). copy_oldmem_page() copies with copy_to_iter(). For a read() of /proc/vmcore that is a user copy, all of whose loads have exception table entries, so the machine check turns into a short copy and read_from_oldmem() returns -EFAULT.

But since commit 4a22fd20379c ("vmcore: convert __read_vmcore to use an iov_iter") /proc/vmcore can be spliced too, and splice(), sendfile() and copy_file_range() copy into kernel pages with memcpy(), which has no exception table entries. A machine check there panics the capture kernel. The same goes for the reads of the ELF headers and notes that vmcore does itself, and those have been memcpy() for as long as copy_oldmem_page() has had its kernel buffer branch, since commit 54c32021eb6f ("[PATCH] powerpc: Add arch-dependent copy_oldmem_page").

Copy with _copy_mc_to_iter() instead. PPC64 selects ARCH_HAS_COPY_MC and there it uses copy_mc_generic() for kernel and user destinations alike, which has the exception table entries. Everywhere else it is _copy_to_iter().

Fixes 54c32021eb6f ("[PATCH] powerpc: Add arch-dependent copy_oldmem_page")
Fixes 4a22fd20379c ("vmcore: convert __read_vmcore to use an iov_iter")
---
 arch/powerpc/kernel/crash_dump.c | 4 ++--
 1 file changed, 2 insertions(+), 2 deletions(-)
arch/powerpc/kernel/crash_dump.c +2 -2
index 1543917bd3e1..ca7e019ae3e9 100644
@@ -83,12 +83,12 @@ ssize_t copy_oldmem_page(struct iov_iter *iter, unsigned long pfn,
 
 	if (memblock_is_region_memory(paddr, csize)) {
 		vaddr = __va(paddr);
-		csize = copy_to_iter(vaddr + offset, csize, iter);
+		csize = _copy_mc_to_iter(vaddr + offset, csize, iter);
 	} else {
 		vaddr = ioremap_cache(paddr, PAGE_SIZE);
 		if (!vaddr)
 			return -ENOMEM;
-		csize = copy_to_iter(vaddr + offset, csize, iter);
+		csize = _copy_mc_to_iter(vaddr + offset, csize, iter);
 		iounmap(vaddr);
 	}
 
Signature · 1 line
2.53.0
#84 lore raw

Re: [PATCH RESEND v2 39/51] powerpc/crash_dump: recover from a machine check in copy_oldmem_page()

Sashiko has reviewed this patch and found no issues.
Quoted 22 lines

A capture kernel reads the memory of the crashed kernel, and that memory may well have uncorrectable errors. On powerpc a machine check in the kernel is only recovered from if the instruction that took it has an exception table entry (cf. mce_common_process_ue()). copy_oldmem_page() copies with copy_to_iter(). For a read() of /proc/vmcore that is a user copy, all of whose loads have exception table entries, so the machine check turns into a short copy and read_from_oldmem() returns -EFAULT.

But since commit 4a22fd20379c ("vmcore: convert __read_vmcore to use an iov_iter") /proc/vmcore can be spliced too, and splice(), sendfile() and copy_file_range() copy into kernel pages with memcpy(), which has no exception table entries. A machine check there panics the capture kernel. The same goes for the reads of the ELF headers and notes that vmcore does itself, and those have been memcpy() for as long as copy_oldmem_page() has had its kernel buffer branch, since commit 54c32021eb6f ("[PATCH] powerpc: Add arch-dependent copy_oldmem_page").

Copy with _copy_mc_to_iter() instead. PPC64 selects ARCH_HAS_COPY_MC and there it uses copy_mc_generic() for kernel and user destinations alike, which has the exception table entries. Everywhere else it is _copy_to_iter().

Quoted 5 lines
Fixes 54c32021eb6f ("[PATCH] powerpc: Add arch-dependent copy_oldmem_page")
Fixes 4a22fd20379c ("vmcore: convert __read_vmcore to use an iov_iter")

Sashiko has reviewed this patch and found no issues.

Signature · 1 line
Sashiko AI review · https://sashiko.dev/#/patchset/[email protected]?part=39
Reviewed-by on v2 39/51
#85 lore raw

Re: [PATCH RESEND v2 39/51] powerpc/crash_dump: recover from a machine check in copy_oldmem_page()

In reply to Christian Brauner
Quoted 22 lines · Christian Brauner

A capture kernel reads the memory of the crashed kernel, and that memory may well have uncorrectable errors. On powerpc a machine check in the kernel is only recovered from if the instruction that took it has an exception table entry (cf. mce_common_process_ue()). copy_oldmem_page() copies with copy_to_iter(). For a read() of /proc/vmcore that is a user copy, all of whose loads have exception table entries, so the machine check turns into a short copy and read_from_oldmem() returns -EFAULT.

But since commit 4a22fd20379c ("vmcore: convert __read_vmcore to use an iov_iter") /proc/vmcore can be spliced too, and splice(), sendfile() and copy_file_range() copy into kernel pages with memcpy(), which has no exception table entries. A machine check there panics the capture kernel. The same goes for the reads of the ELF headers and notes that vmcore does itself, and those have been memcpy() for as long as copy_oldmem_page() has had its kernel buffer branch, since commit 54c32021eb6f ("[PATCH] powerpc: Add arch-dependent copy_oldmem_page").

Copy with _copy_mc_to_iter() instead. PPC64 selects ARCH_HAS_COPY_MC and there it uses copy_mc_generic() for kernel and user destinations alike, which has the exception table entries. Everywhere else it is _copy_to_iter().

Quoted 5 lines
Fixes 54c32021eb6f ("[PATCH] powerpc: Add arch-dependent copy_oldmem_page")
Fixes 4a22fd20379c ("vmcore: convert __read_vmcore to use an iov_iter")

The change is the right direction, and x86_64 has the same gap.

arch/x86/kernel/crash_dump_64.c:__copy_oldmem_page() copies with copy_to_iter(), the same as the powerpc code this patch changes. x86_64 selects ARCH_HAS_COPY_MC, and _copy_mc_to_iter() is already available, with the _copy_to_iter() fallback in include/linux/uio.h for arches without it. The plain and encrypted paths share __copy_oldmem_page(), so one conversion there covers both.

PS: I found this because I am looking at x856 production fleet kdump success rate , where first kernel died of an MCE very often produce no usable vmcore at all, and makedumpfile never finishes due to this type of problem.

author maintainer
#86 lore raw

PATCH RESEND v2 40/51 sunrpc: make queue_wait a global wait queue again

In reply to Christian Brauner

Since commit 552d0e17ea04 ("sunrpc: convert queue_wait from global to per-cache-detail waitqueue") poll() and epoll queue their waiters for a channel file on the queue_wait head in struct cache_detail. But the cache_detail can be freed while its channel file is still open and waited on.

The procfs channel files of a network namespace are removed when the namespace goes away. Removing a procfs file waits for the callers that are in one of its methods right now and then calls ->release on every file that is still open (cf. close_pdeo()). The waiters that poll() and epoll left on the head stay queued until their file is really closed. So:

sunrpc_exit_net()
-> ip_map_cache_destroy()

     -> cache_unregister_net()
        -> remove_cache_proc_entries()
           -> proc_remove()      // ->release, the waiters stay queued
     -> cache_destroy_net()      // kfree(cd)

and when poll() returns remove_wait_queue() writes to the freed cache_detail:

  BUG: KASAN: slab-use-after-free in _raw_spin_lock_irqsave+0x4b/0xa0
  Read of size 1 at addr ff110001131bb570 by task sunrpc-poll-uaf/242
  Call Trace:
   remove_wait_queue+0x22/0x1c0
   poll_freewait+0xc2/0x230
   do_sys_poll+0x9ba/0xd50
   __x64_sys_poll+0x165/0x470
  Freed by task 12:
   kfree+0x267/0x620
   sunrpc_exit_net+0x34/0x80
   ops_undo_list+0x271/0x8d0
   cleanup_net+0x3f3/0x860

Closing an epoll instance that watches the file gets there through ep_unregister_pollwait() instead.

The channel files of a network namespace belong to the root of its user namespace and cache_open() doesn't check for a capability. So an unprivileged user can open the channel file of a namespace of its own from the outside, poll it and let the namespace die.

Go back to a single static wait queue that never goes away. A wakeup for one cache wakes the waiters of all caches again but cache_poll() reports per cache_detail so that's just a spurious wakeup. procfs should really own the wait queue of its files like kernfs does but that's nothing for stable.

Fixes 552d0e17ea04 ("sunrpc: convert queue_wait from global to per-cache-detail waitqueue")
---
 include/linux/sunrpc/cache.h |  1 -
 net/sunrpc/cache.c           | 12 +++++++++---
 2 files changed, 9 insertions(+), 4 deletions(-)
include/linux/sunrpc/cache.h +0 -1
index 2735c332ddb7..bf4fc543e1e5 100644
@@ -119,7 +119,6 @@ struct cache_detail {
 	struct list_head	requests;
 	struct list_head	readers;
 	spinlock_t		queue_lock;
-	wait_queue_head_t	queue_wait;
 	u64			next_seqno;
 
 	atomic_t		writers;		/* how many time is /channel open */
net/sunrpc/cache.c +9 -3
index 1bc04109d213..1ceaea7e01b9 100644
@@ -404,7 +404,6 @@ void sunrpc_init_cache_detail(struct cache_detail *cd)
 	INIT_LIST_HEAD(&cd->requests);
 	INIT_LIST_HEAD(&cd->readers);
 	spin_lock_init(&cd->queue_lock);
-	init_waitqueue_head(&cd->queue_wait);
 	cd->next_seqno = 1;
 	spin_lock(&cache_list_lock);
 	cd->nextcheck = 0;
@@ -965,13 +964,20 @@ out:
 	return ret;
 }
 
+/*
+ * Not in struct cache_detail: poll and epoll waiters stay queued until
+ * their file is closed, but a channel file in procfs can stay open after
+ * the cache_detail of its dying network namespace has been freed.
+ */
+static DECLARE_WAIT_QUEUE_HEAD(queue_wait);
+
 static __poll_t cache_poll(struct file *filp, poll_table *wait,
 			       struct cache_detail *cd)
 {
 	__poll_t mask;
 	struct cache_reader *rp = filp->private_data;
 
-	poll_wait(filp, &cd->queue_wait, wait);
+	poll_wait(filp, &queue_wait, wait);
 
 	/* alway allow write */
 	mask = EPOLLOUT | EPOLLWRNORM;
@@ -1236,7 +1242,7 @@ static int cache_do_upcall(struct cache_detail *detail, struct cache_head *h)
 	spin_unlock(&detail->queue_lock);
 	if (ret != -EAGAIN && detail->cache_notify)
 		detail->cache_notify(detail, h);
-	wake_up(&detail->queue_wait);
+	wake_up(&queue_wait);
 	if (ret == -EAGAIN) {
 		kfree(buf);
 		kfree(crq);
Signature · 1 line
2.53.0
#87 lore raw

Re: [PATCH RESEND v2 40/51] sunrpc: make queue_wait a global wait queue again

Sashiko has reviewed this patch and found no issues.
Quoted 13 lines

Since commit 552d0e17ea04 ("sunrpc: convert queue_wait from global to per-cache-detail waitqueue") poll() and epoll queue their waiters for a channel file on the queue_wait head in struct cache_detail. But the cache_detail can be freed while its channel file is still open and waited on.

The procfs channel files of a network namespace are removed when the namespace goes away. Removing a procfs file waits for the callers that are in one of its methods right now and then calls ->release on every file that is still open (cf. close_pdeo()). The waiters that poll() and epoll left on the head stay queued until their file is really closed. So:

Quoted 8 lines

sunrpc_exit_net()
-> ip_map_cache_destroy()

[ ... ]
Fixes 552d0e17ea04 ("sunrpc: convert queue_wait from global to per-cache-detail waitqueue")

Sashiko has reviewed this patch and found no issues.

Signature · 1 line
Sashiko AI review · https://sashiko.dev/#/patchset/[email protected]?part=40
author maintainer
#88 lore raw

PATCH RESEND v2 41/51 scsi: esas2r: bound the lengths of the HBA, SMP and firmware ioctls

In reply to Christian Brauner

esas2r_ioctl_handler() copies in a struct atto_express_ioctl, a bit over 512k, and hands the union member for the command to the handlers. For EXPRESS_IOCTL_HBA and EXPRESS_IOCTL_SMP the length of the buffered ioctl is the size of the member plus lengths that come straight from userspace:

  bi.length = sizeof(struct atto_ioctl) + ioctl_hba->data_length;

bi.length = sizeof(struct atto_ioctl_smp)
+ le32_to_cpu(si->req_length)
+ le32_to_cpu(si->rsp_length);

handle_buffered_ioctl() copies bi.length bytes from the member into a DMA buffer and, once the adapter is done, copies the DMA buffer back over the member. Nothing checks that the lengths fit into the struct that was copied in. So a large data_length makes it read past the struct and then write the DMA buffer back over the memory behind it.

The firmware commands pass sizeof(struct atto_express_ioctl) to esas2r_{read,write}_{fw,fs}() as the length of data.fwrw.image, which starts 28 bytes into the struct. So they can read and write 28 bytes past it as well.

The handler is reachable through /proc/scsi/esas2r/ATTONode. It is created with mode 0, which procfs turns into 0444, and esas2r doesn't check for a capability anywhere. So any local user can do this on a machine with such an adapter.

Bound all of these by the room from the member to the end of the struct. read_hw() passes handle_hba_ioctl() a single struct atto_ioctl and only ever returns that, so there the data length has to be zero.

Fixes 26780d9e12ed ("[SCSI] esas2r: ATTO Technology ExpressSAS 6G SAS/SATA RAID Adapter Driver")
---
 drivers/scsi/esas2r/esas2r.h       |  2 +-
 drivers/scsi/esas2r/esas2r_ioctl.c | 41 ++++++++++++++++++++++++--------------
 drivers/scsi/esas2r/esas2r_main.c  |  3 ++-
 3 files changed, 29 insertions(+), 17 deletions(-)
drivers/scsi/esas2r/esas2r.h +1 -1
index a763edd05fe4..10101f50b282 100644
@@ -967,7 +967,7 @@ int esas2r_write_params(struct esas2r_adapter *a, struct esas2r_request *rq,
 int esas2r_ioctl_handler(void *hostdata, unsigned int cmd, void __user *arg);
 int esas2r_ioctl(struct scsi_device *dev, unsigned int cmd, void __user *arg);
 u8 handle_hba_ioctl(struct esas2r_adapter *a,
-		    struct atto_ioctl *ioctl_hba);
+		    struct atto_ioctl *ioctl_hba, size_t room);
 enum scsi_qc_status esas2r_queuecommand(struct Scsi_Host *host,
 					struct scsi_cmnd *cmd);
 int esas2r_show_info(struct seq_file *m, struct Scsi_Host *sh);
drivers/scsi/esas2r/esas2r_ioctl.c +26 -15

94 lines not on this page · raw message

drivers/scsi/esas2r/esas2r_main.c +2 -1
index ada278c24c51..75a70ae9441b 100644
@@ -178,7 +178,8 @@ static ssize_t read_hw(struct file *file, struct kobject *kobj,
 	if (!a->local_atto_ioctl)
 		return -ENOMEM;
 
-	if (handle_hba_ioctl(a, a->local_atto_ioctl) != IOCTL_SUCCESS)
+	if (handle_hba_ioctl(a, a->local_atto_ioctl,
+			     sizeof(struct atto_ioctl)) != IOCTL_SUCCESS)
 		return -ENOMEM;
 
 	memcpy(buf, a->local_atto_ioctl, length);
Signature · 1 line
2.53.0
#89 lore raw

Re: [PATCH RESEND v2 41/51] scsi: esas2r: bound the lengths of the HBA, SMP and firmware ioctls

Thank you for your contribution! Sashiko AI review found 1 potential issue(s) to consider: - [High] scsi: esas2r: double fetch of data_length in handle_hba_ioctl() --

Thank you for your contribution! Sashiko AI review found 1 potential issue(s) to consider:
- [High] scsi: esas2r: double fetch of data_length in handle_hba_ioctl()
--

commit a2397b86d116881b0f288e71fe8885d678578a5f
Author: Christian Brauner <[email protected]>

scsi: esas2r: bound the lengths of the HBA, SMP and firmware ioctls

This commit bounds the lengths of the HBA, SMP, and firmware ioctls in esas2r against the remaining room in struct atto_express_ioctl (or sizeof(struct atto_ioctl) for read_hw()) to prevent out-of-bounds DMA buffer reads and writes.

Quoted 4 lines
drivers/scsi/esas2r/esas2r_ioctl.c +0 -0
index c93d9265e1008..80ae5b9d45db1 100644

[ ... ]

Quoted 18 lines
drivers/scsi/esas2r/esas2r_ioctl.c +6 -1
@@ -1221,11 +1231,16 @@ static void hba_ioctl_done_callback(struct esas2r_adapter *a,
 	}
 }
 
+/* @room is the size of the buffer that starts with @ioctl_hba. */
 u8 handle_hba_ioctl(struct esas2r_adapter *a,
-		    struct atto_ioctl *ioctl_hba)
+		    struct atto_ioctl *ioctl_hba, size_t room)
 {
 	struct esas2r_buffered_ioctl bi;
 
+	/* The data follows @ioctl_hba in the same buffer. */
+	if (ioctl_hba->data_length > room - sizeof(struct atto_ioctl))
+		return IOCTL_INVALID_PARAM;
+
 	memset(&bi, 0, sizeof(bi));
 
 	bi.a = a;

drivers/scsi/esas2r/esas2r_ioctl.c

Quoted 2 lines
drivers/scsi/esas2r/esas2r_ioctl.c +0 -0
 	bi.ioctl = ioctl_hba;
 	bi.length = sizeof(struct atto_ioctl) + ioctl_hba->data_length;

[Severity: High]
As reported by Sashiko on RFC [1], in drivers/scsi/esas2r/esas2r_main.c, read_hw() and write_hw() access the shared a->local_atto_ioctl buffer (allocated as sizeof(struct atto_ioctl)) without any driver lock:

drivers/scsi/esas2r/esas2r_main.c:read_hw() {
	...
	if (handle_hba_ioctl(a, a->local_atto_ioctl,
			     sizeof(struct atto_ioctl)) != IOCTL_SUCCESS)
		return -ENOMEM;
	...
}
drivers/scsi/esas2r/esas2r_main.c:write_hw() {
	...
	memset(a->local_atto_ioctl, 0, sizeof(struct atto_ioctl));
	memcpy(a->local_atto_ioctl, buf, length);
	...
}

Because kernfs only serializes sysfs bin_attribute operations per open file description, concurrent read_hw() and write_hw() calls on two separate open file descriptors for the sysfs hw attribute can race on a->local_atto_ioctl.

In handle_hba_ioctl(), ioctl_hba->data_length is read once for the bounds check against room - sizeof(struct atto_ioctl) and read a second time when computing bi.length. If a concurrent write_hw() overwrites a->local_atto_ioctl->data_length from 0 to a non-zero value between those two reads, wouldn't handle_buffered_ioctl() still read and write bi.length bytes past the end of a->local_atto_ioctl?

[1] https://lore.kernel.org/r/[email protected]

Signature · 1 line
Sashiko AI review · https://sashiko.dev/#/patchset/[email protected]?part=41
author maintainer
#90 lore raw

PATCH RESEND v2 42/51 powerpc/pseries: bound the lengths in the ofdt property parser

In reply to Christian Brauner

The commands for /proc/powerpc/ofdt that carry properties, "add_node", "add_property" and "update_property", can make the parser read past the buffer they were copied into:

(1) do_update_property() computes the end of the buffer after parse_node() moved buf past the phandle. So the end is off by the length of the phandle string, which can be padded with zeroes, and parse_next_property() accepts a value that reaches that far past the command. new_property() then copies those bytes into the property, which everyone can read in /proc/device-tree.

(2) parse_next_property() parses the length with simple_strtoul() into an int and only rejects -1. A length above INT_MAX turns negative, tmp += *length moves backwards and passes the check against the end, so *tmp is read up to 2G in front of the buffer.

(3) Updating "slb-size" or "ibm,slb-size" reads an int from the value whatever its length.

Compute the end before parsing the phandle, reject lengths that don't fit into an int or into what is left of the buffer, and only take the slb size from a value that holds one. The file is root-only and refused under lockdown but the parser still shouldn't read past its input.

Fixes 1da177e4c3f4 ("Linux-2.6.12-rc2")
Fixes 610d91511f99 ("[PATCH] powerpc: Add support for changing properties from userspace")
Fixes 46db2f86a3b2 ("powerpc/pseries: Fix to handle slb resize across migration")
---
 arch/powerpc/platforms/pseries/reconfig.c | 18 ++++++++++--------
 1 file changed, 10 insertions(+), 8 deletions(-)
arch/powerpc/platforms/pseries/reconfig.c +10 -8
index 5a0c9c0b6253..b543afbc1efb 100644
@@ -114,6 +114,7 @@ static void release_prop_list(const struct property *prop)
 static char * parse_next_property(char *buf, char *end, char **name, int *length,
 				  unsigned char **value)
 {
+	unsigned long len;
 	char *tmp;
 
 	*name = buf;
@@ -133,13 +134,13 @@ static char * parse_next_property(char *buf, char *end, char **name, int *length
 	}
 
 	/* now we're on the length */
-	*length = -1;
-	*length = simple_strtoul(tmp, &tmp, 10);
-	if (*length == -1) {
+	len = simple_strtoul(tmp, &tmp, 10);
+	if (len > INT_MAX) {
 		printk(KERN_ERR "property parse failed in %s at line %d\n",
 		       __func__, __LINE__);
 		return NULL;
 	}
+	*length = len;
 	if (*tmp != ' ' || ++tmp >= end) {
 		printk(KERN_ERR "property parse failed in %s at line %d\n",
 		       __func__, __LINE__);
@@ -148,13 +149,13 @@ static char * parse_next_property(char *buf, char *end, char **name, int *length
 
 	/* now we're on the value */
 	*value = tmp;
-	tmp += *length;
-	if (tmp > end) {
+	if (len > end - tmp) {
 		printk(KERN_ERR "property parse failed in %s at line %d\n",
 		       __func__, __LINE__);
 		return NULL;
 	}
-	else if (tmp < end && *tmp != ' ' && *tmp != '\0') {
+	tmp += len;
+	if (tmp < end && *tmp != ' ' && *tmp != '\0') {
 		printk(KERN_ERR "property parse failed in %s at line %d\n",
 		       __func__, __LINE__);
 		return NULL;
@@ -320,8 +321,8 @@ static int do_update_property(char *buf, size_t bufsize)
 	char *name, *end, *next_prop;
 	int length;
 	struct property *newprop;
-	buf = parse_node(buf, bufsize, &np);
 	end = buf + bufsize;
+	buf = parse_node(buf, bufsize, &np);
 
 	if (!np)
 		return -ENODEV;
@@ -337,7 +338,8 @@ static int do_update_property(char *buf, size_t bufsize)
 	if (!newprop)
 		return -ENOMEM;
 
-	if (!strcmp(name, "slb-size") || !strcmp(name, "ibm,slb-size"))
+	if ((!strcmp(name, "slb-size") || !strcmp(name, "ibm,slb-size")) &&
+	    length >= (int)sizeof(int))
 		slb_set_size(*(int *)value);
 
 	return of_update_property(np, newprop);
Signature · 1 line
2.53.0
#91 lore raw

Re: [PATCH RESEND v2 42/51] powerpc/pseries: bound the lengths in the ofdt property parser

Sashiko has reviewed this patch and found no issues.
Quoted 15 lines

The commands for /proc/powerpc/ofdt that carry properties, "add_node", "add_property" and "update_property", can make the parser read past the buffer they were copied into:

(1) do_update_property() computes the end of the buffer after parse_node() moved buf past the phandle. So the end is off by the length of the phandle string, which can be padded with zeroes, and parse_next_property() accepts a value that reaches that far past the command. new_property() then copies those bytes into the property, which everyone can read in /proc/device-tree.

(2) parse_next_property() parses the length with simple_strtoul() into an int and only rejects -1. A length above INT_MAX turns negative, tmp += *length moves backwards and passes the check against the end, so *tmp is read up to 2G in front of the buffer.

Quoted 6 lines
[ ... ]
Fixes 1da177e4c3f4 ("Linux-2.6.12-rc2")
Fixes 610d91511f99 ("[PATCH] powerpc: Add support for changing properties from userspace")
Fixes 46db2f86a3b2 ("powerpc/pseries: Fix to handle slb resize across migration")

Sashiko has reviewed this patch and found no issues.

Signature · 1 line
Sashiko AI review · https://sashiko.dev/#/patchset/[email protected]?part=42
author maintainer
#92 lore raw

PATCH RESEND v2 43/51 powerpc/pseries/lparcfg: return h_get_ppp()'s status as a long

In reply to Christian Brauner

h_get_ppp() returns the status of the H_GET_PPP hcall as an unsigned int. update_ppp() hands it on as its ssize_t result, and lparcfg_write() turns the hcall statuses it knows into an errno and returns anything else as it is. So when H_GET_PPP fails, say with H_PARAMETER (-4), the status comes back as 4294967292 and a write to /proc/powerpc/lparcfg reports that many bytes written.

Return the status as the long it is. lparcfg_write() then treats it like the status of H_SET_PPP: an unknown error status is at least negative, and one of the positive long-busy statuses comes back as a byte count, as it does for H_SET_PPP already. Before commit 11529396ea31 ("powerpc/pseries: Split processor entitlement retrieval and gathering to helper routines") a failed H_GET_PPP turned into -EIO.

Fixes 11529396ea31 ("powerpc/pseries: Split processor entitlement retrieval and gathering to helper routines")
---
 arch/powerpc/platforms/pseries/lparcfg.c | 2 +-
 1 file changed, 1 insertion(+), 1 deletion(-)
arch/powerpc/platforms/pseries/lparcfg.c +1 -1
index 9882f98c0efb..4f6b2975c6e9 100644
@@ -113,7 +113,7 @@ struct hvcall_ppp_data {
  *	          XXXXXX - Entitled procs capacity % available to the
  *			   partitions pool.
  */
-static unsigned int h_get_ppp(struct hvcall_ppp_data *ppp_data)
+static long h_get_ppp(struct hvcall_ppp_data *ppp_data)
 {
 	unsigned long retbuf[PLPAR_HCALL9_BUFSIZE] = {0};
 	long rc;
Signature · 1 line
2.53.0
#93 lore raw

Re: [PATCH RESEND v2 43/51] powerpc/pseries/lparcfg: return h_get_ppp()'s status as a long

Sashiko has reviewed this patch and found no issues.
Quoted 14 lines

h_get_ppp() returns the status of the H_GET_PPP hcall as an unsigned int. update_ppp() hands it on as its ssize_t result, and lparcfg_write() turns the hcall statuses it knows into an errno and returns anything else as it is. So when H_GET_PPP fails, say with H_PARAMETER (-4), the status comes back as 4294967292 and a write to /proc/powerpc/lparcfg reports that many bytes written.

Return the status as the long it is. lparcfg_write() then treats it like the status of H_SET_PPP: an unknown error status is at least negative, and one of the positive long-busy statuses comes back as a byte count, as it does for H_SET_PPP already. Before commit 11529396ea31 ("powerpc/pseries: Split processor entitlement retrieval and gathering to helper routines") a failed H_GET_PPP turned into -EIO.

Quoted 4 lines
Fixes 11529396ea31 ("powerpc/pseries: Split processor entitlement retrieval and gathering to helper routines")

Sashiko has reviewed this patch and found no issues.

Signature · 1 line
Sashiko AI review · https://sashiko.dev/#/patchset/[email protected]?part=43
author maintainer
#94 lore raw

PATCH RESEND v2 44/51 proc: sysctl: resume readdir after the last name it returned

In reply to Christian Brauner

proc_sys_readdir() counts the entries of a directory and resumes a listing at the number getdents64() stopped at. The entries are sorted by name, so one that is registered or unregistered in between shifts everything behind it by one. Listing /proc/sys/net/ipv4/conf with a buffer that holds ".", ".." and "all" and registering a device whose name sorts before "all" makes the next call return "all" a second time. Unregistering one that sorted before the position makes it skip an entry instead. So a listing that takes more than one call shows a name twice, or not at all. Even the 64k buffer of ls needs a second call to find the end of the directory, so a device that comes up right then repeats the last entry.

So remember the name of the last entry a call emitted in the file and resume at the first usable entry after it, like kernfs resumes after the node it stopped at. The entry itself can't be pinned across calls, unregistering waits for that. If the position was moved by a seek in between the listing counts from the start like before, seeking to an arbitrary position has never been better than that.

That also takes one walk down the tree to resume instead of a walk over every entry in front of the position with a round trip through sysctl_lock for each of them.

Fixes 77b14db502cb ("[PATCH] sysctl: reimplement the sysctl proc support")
---
 fs/proc/proc_sysctl.c | 106 ++++++++++++++++++++++++++++++++++++++++++++++++--
 1 file changed, 103 insertions(+), 3 deletions(-)
fs/proc/proc_sysctl.c +103 -3
index b4a309d49698..ba52f13eb8f3 100644
@@ -417,6 +417,54 @@ static void next_entry(struct ctl_table_header **phead, const struct ctl_table *
 	*pentry = entry;
 }
 
+/*
+ * The first usable entry of @dir after @name, or the first one at all for a
+ * NULL @name. The entries are sorted by name, so that is where a listing
+ * resumes when entries in front of it came or went in between. -ENOENT if
+ * the directory is being unregistered.
+ */
+static int entry_after(struct ctl_dir *dir, const char *name, int namelen,
+		       struct ctl_table_header **phead,
+		       const struct ctl_table **pentry)
+{
+	struct ctl_table_header *head = NULL;
+	const struct ctl_table *entry = NULL;
+	struct rb_node *node, *after = NULL;
+	struct ctl_node *ctl_node;
+
+	spin_lock(&sysctl_lock);
+	if (unlikely(dir->header.unregistering)) {
+		spin_unlock(&sysctl_lock);
+		return -ENOENT;
+	}
+	if (!name) {
+		after = rb_first(&dir->root);
+	} else for (node = dir->root.rb_node; node;) {
+		const struct ctl_table *table;
+		struct ctl_table_header *h;
+
+		ctl_node = rb_entry(node, struct ctl_node, node);
+		h = ctl_node->header;
+		table = &h->ctl_table[ctl_node - h->node];
+		if (namecmp(table->procname, strlen(table->procname),
+			    name, namelen) > 0) {
+			after = node;
+			node = node->rb_left;
+		} else {
+			node = node->rb_right;
+		}
+	}
+	ctl_node = first_usable_entry(after);
+	spin_unlock(&sysctl_lock);
+	if (ctl_node) {
+		head = ctl_node->header;
+		entry = &head->ctl_table[ctl_node - head->node];
+	}
+	*phead = head;
+	*pentry = entry;
+	return 0;
+}
+
 /*
  * sysctl_perm does NOT grant the superuser all rights automatically, because
  * some sysctl variables are readonly even to root.
@@ -675,6 +723,36 @@ out:
 	return ret;
 }
 
+/*
+ * Where the next readdir resumes. The entries are counted, so one that is
+ * registered or unregistered in front of the position would shift what
+ * the next call returns. The name of the last entry emitted doesn't move.
+ */
+struct sysctl_cursor {
+	loff_t pos;			/* the position behind the entry */
+	int len;
+	char name[NAME_MAX + 1];
+};
+
+/* If this can't remember the entry the next call counts from the start. */
+static void sysctl_cursor_set(struct file *file, const char *name, int len,
+			      loff_t pos)
+{
+	struct sysctl_cursor *cursor = file->private_data;
+
+	if (len > NAME_MAX)
+		return;
+	if (!cursor) {
+		cursor = kmalloc(sizeof(*cursor), GFP_KERNEL);
+		if (!cursor)
+			return;
+		file->private_data = cursor;
+	}
+	cursor->pos = pos;
+	cursor->len = len;
+	memcpy(cursor->name, name, len);
+}
+
 static bool proc_sys_fill_cache(struct file *file,
 				struct dir_context *ctx,
 				struct ctl_table_header *head,
@@ -756,8 +834,11 @@ static int scan(struct ctl_table_header *head, const struct ctl_table *table,
 	else
 		res = proc_sys_fill_cache(file, ctx, head, table);
 
-	if (res)
+	if (res) {
 		ctx->pos = *pos;
+		sysctl_cursor_set(file, table->procname, strlen(table->procname),
+				  ctx->pos);
+	}
 
 	return res;
 }
@@ -765,6 +846,7 @@ static int scan(struct ctl_table_header *head, const struct ctl_table *table,
 static int proc_sys_readdir(struct file *file, struct dir_context *ctx)
 {
 	struct ctl_table_header *head = grab_header(file_inode(file));
+	struct sysctl_cursor *cursor = file->private_data;
 	struct ctl_table_header *h = NULL;
 	const struct ctl_table *entry;
 	struct ctl_dir *ctl_dir;
@@ -778,9 +860,20 @@ static int proc_sys_readdir(struct file *file, struct dir_context *ctx)
 	if (!dir_emit_dots(file, ctx))
 		goto out;
 
-	pos = 2;
+	/*
+	 * Resume after the last entry the previous call emitted. Only a seek
+	 * that moved the position away from it counts from the start, like
+	 * seeking to an arbitrary position always did.
+	 */
+	if (cursor && cursor->pos == ctx->pos) {
+		entry_after(ctl_dir, cursor->name, cursor->len, &h, &entry);
+		pos = ctx->pos;
+	} else {
+		first_entry(ctl_dir, &h, &entry);
+		pos = 2;
+	}
 
-	for (first_entry(ctl_dir, &h, &entry); h; next_entry(&h, &entry)) {
+	for (; h; next_entry(&h, &entry)) {
 		if (!scan(h, entry, &pos, file, ctx)) {
 			sysctl_head_finish(h);
 			break;
@@ -791,6 +884,12 @@ out:
 	return 0;
 }
 
+static int proc_sys_dir_release(struct inode *inode, struct file *file)
+{
+	kfree(file->private_data);
+	return 0;
+}
+
 static int proc_sys_permission(const struct mnt_idmap *idmap,
 			       struct inode *inode, int mask)
 {
@@ -870,6 +969,7 @@ static const struct file_operations proc_sys_dir_file_operations = {
 	.read		= generic_read_dir,
 	.iterate_shared	= proc_sys_readdir,
 	.llseek		= generic_file_llseek,
+	.release	= proc_sys_dir_release,
 };
 
 static const struct inode_operations proc_sys_inode_operations = {
Signature · 1 line
2.53.0
#95 lore raw

Re: [PATCH RESEND v2 44/51] proc: sysctl: resume readdir after the last name it returned

Quoted 27 lines · Christian Brauner

proc_sys_readdir() counts the entries of a directory and resumes a listing at the number getdents64() stopped at. The entries are sorted by name, so one that is registered or unregistered in between shifts everything behind it by one. Listing /proc/sys/net/ipv4/conf with a buffer that holds ".", ".." and "all" and registering a device whose name sorts before "all" makes the next call return "all" a second time. Unregistering one that sorted before the position makes it skip an entry instead. So a listing that takes more than one call shows a name twice, or not at all. Even the 64k buffer of ls needs a second call to find the end of the directory, so a device that comes up right then repeats the last entry.

So remember the name of the last entry a call emitted in the file and resume at the first usable entry after it, like kernfs resumes after the node it stopped at. The entry itself can't be pinned across calls, unregistering waits for that. If the position was moved by a seek in between the listing counts from the start like before, seeking to an arbitrary position has never been better than that.

That also takes one walk down the tree to resume instead of a walk over every entry in front of the position with a round trip through sysctl_lock for each of them.

Fixes 77b14db502cb ("[PATCH] sysctl: reimplement the sysctl proc support")

---

[...]

fs/proc/proc_sysctl.c static int scan(struct ctl_table_header *head, const struct ctl_table *table, · line 840

Quoted 9 lines
fs/proc/proc_sysctl.c +3 -1
@@ -756,8 +834,11 @@ static int scan(struct ctl_table_header *head, const struct ctl_table *table,
        else
                res = proc_sys_fill_cache(file, ctx, head, table);
 
-       if (res)
+       if (res) {
                ctx->pos = *pos;
+               sysctl_cursor_set(file, table->procname, strlen(table->procname),
+                                 ctx->pos);

sysctl_cursor_set() is called here, when the output buffer is too small; but not if the proc_sys_readdir() loop ends because the end of the table was reached and "h" is NULL?

Doesn't that mean that another getdents() after reaching end of the file would observe the last entries again?

author maintainer
#96 lore raw

Re: [PATCH RESEND v2 44/51] proc: sysctl: resume readdir after the last name it returned

Quoted 3 lines · Jann Horn

sysctl_cursor_set() is called here, when the output buffer is too small; but not if the proc_sys_readdir() loop ends because the end of the table was reached and "h" is NULL?

It's the other way around. res is true when the entry went into the buffer. The cursor moves with every entry that was emitted. That includes the last entry of the table.

When the buffer is full, res is false, we stop, and the cursor leads us to the last entry that we sent.

Quoted 2 lines

Doesn't that mean that another getdents() after reaching end of the file would observe the last entries again?

No. After the last entry, cursor->pos == ctx->pos. So the next getdents does entry_after(last_name). That doens't find anything. So h is NULL, the loop doesn't run and it returns zero.

If an entry registered behind the name it would show up.

Reviewed-by on v2 44/51
#97 lore raw

Re: [PATCH RESEND v2 44/51] proc: sysctl: resume readdir after the last name it returned

In reply to Christian Brauner
Quoted 19 lines · Christian Brauner

proc_sys_readdir() counts the entries of a directory and resumes a listing at the number getdents64() stopped at. The entries are sorted by name, so one that is registered or unregistered in between shifts everything behind it by one. Listing /proc/sys/net/ipv4/conf with a buffer that holds ".", ".." and "all" and registering a device whose name sorts before "all" makes the next call return "all" a second time. Unregistering one that sorted before the position makes it skip an entry instead. So a listing that takes more than one call shows a name twice, or not at all. Even the 64k buffer of ls needs a second call to find the end of the directory, so a device that comes up right then repeats the last entry.

So remember the name of the last entry a call emitted in the file and resume at the first usable entry after it, like kernfs resumes after the node it stopped at. The entry itself can't be pinned across calls, unregistering waits for that. If the position was moved by a seek in between the listing counts from the start like before, seeking to an arbitrary position has never been better than that.

Quoted 7 lines

That also takes one walk down the tree to resume instead of a walk over every entry in front of the position with a round trip through sysctl_lock for each of them.

Fixes 77b14db502cb ("[PATCH] sysctl: reimplement the sysctl proc support")
#98 lore raw

Re: [PATCH RESEND v2 44/51] proc: sysctl: resume readdir after the last name it returned

In reply to Christian Brauner
Sashiko has reviewed this patch and found no issues.
Quoted 19 lines

proc_sys_readdir() counts the entries of a directory and resumes a listing at the number getdents64() stopped at. The entries are sorted by name, so one that is registered or unregistered in between shifts everything behind it by one. Listing /proc/sys/net/ipv4/conf with a buffer that holds ".", ".." and "all" and registering a device whose name sorts before "all" makes the next call return "all" a second time. Unregistering one that sorted before the position makes it skip an entry instead. So a listing that takes more than one call shows a name twice, or not at all. Even the 64k buffer of ls needs a second call to find the end of the directory, so a device that comes up right then repeats the last entry.

So remember the name of the last entry a call emitted in the file and resume at the first usable entry after it, like kernfs resumes after the node it stopped at. The entry itself can't be pinned across calls, unregistering waits for that. If the position was moved by a seek in between the listing counts from the start like before, seeking to an arbitrary position has never been better than that.

Quoted 7 lines

That also takes one walk down the tree to resume instead of a walk over every entry in front of the position with a round trip through sysctl_lock for each of them.

Fixes 77b14db502cb ("[PATCH] sysctl: reimplement the sysctl proc support")

Sashiko has reviewed this patch and found no issues.

Signature · 1 line
Sashiko AI review · https://sashiko.dev/#/patchset/[email protected]?part=44
author maintainer
#99 lore raw

PATCH RESEND v2 45/51 selftests/proc: check a sysctl listing while entries come and go

In reply to Christian Brauner

List /proc/sys/net/ipv4/conf of a new network namespace in two pieces:

- with a buffer that holds the dots and "all", register a tun device whose name sorts first, finish the listing: "all" is listed once

- with that device registered and a buffer that holds the dots and it, unregister it, finish the listing: "all" is still listed

Both fail without the fix, the first lists "all" twice, the second not at all.

---
 tools/testing/selftests/proc/.gitignore            |   1 +
 tools/testing/selftests/proc/Makefile              |   1 +
 .../selftests/proc/proc-sysctl-readdir-churn.c     | 152 +++++++++++++++++++++
 3 files changed, 154 insertions(+)
tools/testing/selftests/proc/.gitignore +1 -0
index 8520c7878ea2..5b5e24e39cbd 100644
@@ -25,4 +25,5 @@
 /self
 /setns-dcache
 /setns-sysvipc
+/proc-sysctl-readdir-churn
 /thread-self
tools/testing/selftests/proc/Makefile +1 -0
index e0c0d313f4d0..dae09f333455 100644
@@ -30,6 +30,7 @@ TEST_GEN_PROGS += setns-sysvipc
 TEST_GEN_PROGS += thread-self
 TEST_GEN_PROGS += proc-multiple-procfs
 TEST_GEN_PROGS += proc-fsconfig-hidepid
+TEST_GEN_PROGS += proc-sysctl-readdir-churn
 TEST_GEN_PROGS += proc-pidns
 
 include ../lib.mk
tools/testing/selftests/proc/proc-sysctl-readdir-churn.c new file +152 -0

152 lines not on this page · raw message

Signature · 1 line
2.53.0
#100 lore raw

Re: [PATCH RESEND v2 45/51] selftests/proc: check a sysctl listing while entries come and go

Thank you for your contribution! Sashiko AI review found 1 potential issue(s) to consider: - [Low] selftests/proc: duplicate readdir churn test in proc-sysctl-readdir-churn.c --

Thank you for your contribution! Sashiko AI review found 1 potential issue(s) to consider:
- [Low] selftests/proc: duplicate readdir churn test in proc-sysctl-readdir-churn.c --

commit 89d111e3f559a343f6b04af3c2c0857d3d1f5a29
Author: Christian Brauner <[email protected]>

selftests/proc: check a sysctl listing while entries come and go

This commit adds a selftest in proc-sysctl-readdir-churn.c to verify that a multi-call getdents64() listing of /proc/sys/net/ipv4/conf does not repeat or skip entries when a network device is registered or unregistered in between calls.

Quoted 6 lines
tools/testing/selftests/proc/proc-sysctl-readdir-churn.c new file +0 -0
new file mode 100644
index 0000000000000..b2ad097b464aa
@@ -0,0 +1,152 @@

[ ... ]

Quoted 118 lines
tools/testing/selftests/proc/proc-sysctl-readdir-churn.c new file +118 -0
+#define CONF_DIR	"/proc/sys/net/ipv4/conf"
+#define TUN_NAME	"a0"		/* sorts before "all" */
+#define TUN_PATH	CONF_DIR "/" TUN_NAME
+#define SMALL_BUF	80		/* ".", ".." and one short name */
+#define NAMES		64
+
+static int tun_open(const char *name)
+{
+	struct ifreq ifr = {};
+	int fd;
+
+	fd = open("/dev/net/tun", O_RDWR | O_CLOEXEC);
+	if (fd < 0)
+		return -1;
+	strncpy(ifr.ifr_name, name, IFNAMSIZ - 1);
+	ifr.ifr_flags = IFF_TUN | IFF_NO_PI;
+	if (ioctl(fd, TUNSETIFF, &ifr)) {
+		close(fd);
+		return -1;
+	}
+	return fd;
+}
+
+/* one getdents64() into @buf, the names appended to @names */
+static int list(int fd, char *buf, size_t size, char names[][NAME_MAX + 1],
+		int *n)
+{
+	long ret, off;
+	int got = 0;
+
+	ret = syscall(__NR_getdents64, fd, buf, size);
+	if (ret < 0)
+		return -errno;
+	for (off = 0; off < ret;) {
+		struct dirent64 *d = (void *)(buf + off);
+
+		if (*n < NAMES)
+			strcpy(names[(*n)++], d->d_name);
+		got++;
+		off += d->d_reclen;
+	}
+	return got;
+}
+
+static int count(char names[][NAME_MAX + 1], int n, const char *name)
+{
+	int i, c = 0;
+
+	for (i = 0; i < n; i++)
+		if (!strcmp(names[i], name))
+			c++;
+	return c;
+}
+
+FIXTURE(sysctl_readdir) {
+	int dir;
+	int n;
+	char names[NAMES][NAME_MAX + 1];
+	char buf[65536];
+};
+
+FIXTURE_SETUP(sysctl_readdir)
+{
+	int tun;
+
+	if (unshare(CLONE_NEWNET))
+		SKIP(return, "unshare(CLONE_NEWNET): %s", strerror(errno));
+	tun = open("/dev/net/tun", O_RDWR | O_CLOEXEC);
+	if (tun < 0)
+		SKIP(return, "/dev/net/tun: %s", strerror(errno));
+	close(tun);
+	self->dir = open(CONF_DIR, O_RDONLY | O_DIRECTORY | O_CLOEXEC);
+	if (self->dir < 0)
+		SKIP(return, CONF_DIR ": %s", strerror(errno));
+	self->n = 0;
+}
+
+FIXTURE_TEARDOWN(sysctl_readdir)
+{
+	close(self->dir);
+}
+
+/* a device registered in front of the position doesn't repeat an entry */
+TEST_F(sysctl_readdir, register_in_front)
+{
+	int tun;
+
+	/* ".", ".." and "all", "default" doesn't fit */
+	ASSERT_EQ(list(self->dir, self->buf, SMALL_BUF, self->names, &self->n), 3);
+	ASSERT_EQ(count(self->names, self->n, "all"), 1);
+
+	tun = tun_open(TUN_NAME);
+	ASSERT_GE(tun, 0);
+	ASSERT_EQ(access(TUN_PATH, F_OK), 0);
+
+	while (list(self->dir, self->buf, sizeof(self->buf), self->names,
+		    &self->n) > 0)
+		;
+	EXPECT_EQ(count(self->names, self->n, "all"), 1);
+	EXPECT_EQ(count(self->names, self->n, "default"), 1);
+	EXPECT_EQ(count(self->names, self->n, "lo"), 1);
+	close(tun);
+}
+
+/* a device unregistered in front of the position doesn't skip an entry */
+TEST_F(sysctl_readdir, unregister_in_front)
+{
+	int tun;
+
+	tun = tun_open(TUN_NAME);
+	ASSERT_GE(tun, 0);
+	ASSERT_EQ(access(TUN_PATH, F_OK), 0);
+
+	/* ".", ".." and the device, "all" doesn't fit */
+	ASSERT_EQ(list(self->dir, self->buf, SMALL_BUF, self->names, &self->n), 3);
+	ASSERT_EQ(count(self->names, self->n, TUN_NAME), 1);
+
+	/* closing the device unregisters its sysctls under RTNL */

tools/testing/selftests/proc/proc-sysctl-readdir-churn.c line 150

Quoted 10 lines
tools/testing/selftests/proc/proc-sysctl-readdir-churn.c new file +10 -0
+	close(tun);
+	ASSERT_EQ(access(TUN_PATH, F_OK), -1);
+
+	while (list(self->dir, self->buf, sizeof(self->buf), self->names,
+		    &self->n) > 0)
+		;
+	EXPECT_EQ(count(self->names, self->n, "all"), 1);
+	EXPECT_EQ(count(self->names, self->n, "default"), 1);
+	EXPECT_EQ(count(self->names, self->n, "lo"), 1);
+}

[Severity: Low]
As reported by Sashiko on RFC [1], this isn't a bug, but tun_open(), list(), count(), the fixture state in FIXTURE(sysctl_readdir), FIXTURE_SETUP(sysctl_readdir), FIXTURE_TEARDOWN(sysctl_readdir), and the register_in_front and unregister_in_front test cases in tools/testing/selftests/proc/proc-sysctl-readdir-churn.c duplicate the helpers, FIXTURE(proc_readdir), and the add_in_front and remove_in_front test cases in tools/testing/selftests/proc/proc-readdir-churn.c, differing only in the target directory (/proc/sys/net/ipv4/conf vs /proc/net/dev_snmp6) and expected entries.

Should these sysctl cases be added to tools/testing/selftests/proc/proc-readdir-churn.c (for example using FIXTURE_VARIANT() and FIXTURE_VARIANT_ADD()) rather than introducing a separate standalone test file?

[1] https://lore.kernel.org/r/[email protected]

Signature · 1 line
Sashiko AI review · https://sashiko.dev/#/patchset/[email protected]?part=45
author maintainer
#101 lore raw

PATCH RESEND v2 46/51 proc: sysctl: copy to and from userspace without holding the table

In reply to Christian Brauner

proc_sys_call_handler() grabs the table, copies in what is written, calls the handler and copies what it produced out to userspace before it lets go of the table again. Unregistering a table waits until nobody uses it anymore. So a reader or writer whose copy faults for as long as it wants, with userfaultfd or a stalled FUSE mapping, keeps unregister_sysctl_table() waiting, and its callers like to hold locks while they do that. addrconf unregisters the ipv6 sysctls of a device with RTNL held, so a stalled read of /proc/sys/net/ipv6/conf/<dev>/mtu holds up every RTNL user until the reader gives up.

Copy in before grabbing the table and copy out after letting go of it, like procfs and kernfs do for their files. The buffer is ours, nothing needs the table for the copies.

That moves the allocation and the copy in before the permission check. A write that can't be copied in, or a request that is too large, now fails with -EFAULT or -ENOMEM where it used to fail with -EPERM.

Fixes 330d57fb98a9 ("[PATCH] Fix sysctl unregistration oops (CVE-2005-2709)")
---
 fs/proc/proc_sysctl.c | 50 ++++++++++++++++++++++++++++----------------------
 1 file changed, 28 insertions(+), 22 deletions(-)
fs/proc/proc_sysctl.c +28 -22
index ba52f13eb8f3..f5c9f04e8509 100644
@@ -602,14 +602,36 @@ static ssize_t proc_sys_call_handler(struct kiocb *iocb, struct iov_iter *iter,
 		int write)
 {
 	struct inode *inode = file_inode(iocb->ki_filp);
-	struct ctl_table_header *head = grab_header(inode);
 	const struct ctl_table *table = PROC_I(inode)->sysctl_entry;
+	struct ctl_table_header *head;
 	size_t count = iov_iter_count(iter);
 	char *kbuf;
 	ssize_t error;
 
-	if (IS_ERR(head))
-		return PTR_ERR(head);
+	/* don't even try if the size is too large */
+	if (count >= KMALLOC_MAX_SIZE)
+		return -ENOMEM;
+	kbuf = kvzalloc(count + 1, GFP_KERNEL);
+	if (!kbuf)
+		return -ENOMEM;
+
+	/*
+	 * Copy in before grabbing the table and copy out after letting go of
+	 * it. Unregistering the table waits for us and a copy that faults can
+	 * take as long as userspace wants.
+	 */
+	if (write) {
+		error = -EFAULT;
+		if (!copy_from_iter_full(kbuf, count, iter))
+			goto out_free_buf;
+		kbuf[count] = '\0';
+	}
+
+	head = grab_header(inode);
+	if (IS_ERR(head)) {
+		error = PTR_ERR(head);
+		goto out_free_buf;
+	}
 
 	/*
 	 * At this point we know that the sysctl was not unregistered
@@ -624,28 +646,15 @@ static ssize_t proc_sys_call_handler(struct kiocb *iocb, struct iov_iter *iter,
 	if (!table->proc_handler)
 		goto out;
 
-	/* don't even try if the size is too large */
-	error = -ENOMEM;
-	if (count >= KMALLOC_MAX_SIZE)
-		goto out;
-	kbuf = kvzalloc(count + 1, GFP_KERNEL);
-	if (!kbuf)
-		goto out;
-
-	if (write) {
-		error = -EFAULT;
-		if (!copy_from_iter_full(kbuf, count, iter))
-			goto out_free_buf;
-		kbuf[count] = '\0';
-	}
-
 	error = BPF_CGROUP_RUN_PROG_SYSCTL(head, table, write, &kbuf, &count,
 					   &iocb->ki_pos);
 	if (error)
-		goto out_free_buf;
+		goto out;
 
 	/* careful: calling conventions are nasty here */
 	error = table->proc_handler(table, write, kbuf, &count, &iocb->ki_pos);
+out:
+	sysctl_head_finish(head);
 	if (error)
 		goto out_free_buf;
 
@@ -658,9 +667,6 @@ static ssize_t proc_sys_call_handler(struct kiocb *iocb, struct iov_iter *iter,
 	error = count;
 out_free_buf:
 	kvfree(kbuf);
-out:
-	sysctl_head_finish(head);
-
 	return error;
 }
 
Signature · 1 line
2.53.0
#102 lore raw

Re: [PATCH RESEND v2 46/51] proc: sysctl: copy to and from userspace without holding the table

Sashiko has reviewed this patch and found no issues.
Quoted 14 lines

proc_sys_call_handler() grabs the table, copies in what is written, calls the handler and copies what it produced out to userspace before it lets go of the table again. Unregistering a table waits until nobody uses it anymore. So a reader or writer whose copy faults for as long as it wants, with userfaultfd or a stalled FUSE mapping, keeps unregister_sysctl_table() waiting, and its callers like to hold locks while they do that. addrconf unregisters the ipv6 sysctls of a device with RTNL held, so a stalled read of /proc/sys/net/ipv6/conf/<dev>/mtu holds up every RTNL user until the reader gives up.

Copy in before grabbing the table and copy out after letting go of it, like procfs and kernfs do for their files. The buffer is ours, nothing needs the table for the copies.

Quoted 7 lines

That moves the allocation and the copy in before the permission check. A write that can't be copied in, or a request that is too large, now fails with -EFAULT or -ENOMEM where it used to fail with -EPERM.

Fixes 330d57fb98a9 ("[PATCH] Fix sysctl unregistration oops (CVE-2005-2709)")

Sashiko has reviewed this patch and found no issues.

Signature · 1 line
Sashiko AI review · https://sashiko.dev/#/patchset/[email protected]?part=46
author maintainer
#103 lore raw

PATCH RESEND v2 47/51 proc: sysctl: look at the table under sysctl_lock when creating an inode

In reply to Christian Brauner

proc_sys_make_inode() checks under sysctl_lock that @head isn't being unregistered, lets go of the lock, and then reads the mode of @table and calls ->set_ownership() with @head. That's fine as long as the caller holds @head in use, which keeps unregistering from getting past that check. The next patch has a caller that only pins the memory of @head. For that one the table, and whatever the owner of the header keeps behind it, is only there for as long as nobody unregisters the header, which happens under sysctl_lock. So read the mode and set the ownership before letting go of the lock. The ->set_ownership() callbacks only look up ids in a user namespace.

No functional changes.

---
 fs/proc/proc_sysctl.c | 20 +++++++++++++-------
 1 file changed, 13 insertions(+), 7 deletions(-)
fs/proc/proc_sysctl.c +13 -7
index f5c9f04e8509..82024f1ea756 100644
@@ -500,6 +500,7 @@ static struct inode *proc_sys_make_inode(struct super_block *sb,
 	struct ctl_table_root *root = head->root;
 	struct inode *inode;
 	struct proc_inode *ei;
+	umode_t mode;
 
 	inode = new_inode(sb);
 	if (!inode)
@@ -509,12 +510,22 @@ static struct inode *proc_sys_make_inode(struct super_block *sb,
 
 	ei = PROC_I(inode);
 
+	inode->i_uid = GLOBAL_ROOT_UID;
+	inode->i_gid = GLOBAL_ROOT_GID;
 	spin_lock(&sysctl_lock);
 	if (unlikely(head->unregistering)) {
 		spin_unlock(&sysctl_lock);
 		iput(inode);
 		return ERR_PTR(-ENOENT);
 	}
+	/*
+	 * The table, and whatever the owner of the header keeps behind it,
+	 * is only there for as long as nobody unregisters the header, which
+	 * happens under sysctl_lock. So look at them before letting go of it.
+	 */
+	mode = table->mode;
+	if (root->set_ownership)
+		root->set_ownership(head, &inode->i_uid, &inode->i_gid);
 	ei->sysctl = head;
 	ei->sysctl_entry = table;
 	hlist_add_head_rcu(&ei->sibling_inodes, &head->inodes);
@@ -522,8 +533,8 @@ static struct inode *proc_sys_make_inode(struct super_block *sb,
 	spin_unlock(&sysctl_lock);
 
 	simple_inode_init_ts(inode);
-	inode->i_mode = table->mode;
-	if (!S_ISDIR(table->mode)) {
+	inode->i_mode = mode;
+	if (!S_ISDIR(mode)) {
 		inode->i_mode |= S_IFREG;
 		inode->i_op = &proc_sys_inode_operations;
 		inode->i_fop = &proc_sys_file_operations;
@@ -535,11 +546,6 @@ static struct inode *proc_sys_make_inode(struct super_block *sb,
 			make_empty_dir_inode(inode);
 	}
 
-	inode->i_uid = GLOBAL_ROOT_UID;
-	inode->i_gid = GLOBAL_ROOT_GID;
-	if (root->set_ownership)
-		root->set_ownership(head, &inode->i_uid, &inode->i_gid);
-
 	return inode;
 }
 
Signature · 1 line
2.53.0
#104 lore raw

Re: [PATCH RESEND v2 47/51] proc: sysctl: look at the table under sysctl_lock when creating an inode

Sashiko has reviewed this patch and found no issues.
Quoted 11 lines

proc_sys_make_inode() checks under sysctl_lock that @head isn't being unregistered, lets go of the lock, and then reads the mode of @table and calls ->set_ownership() with @head. That's fine as long as the caller holds @head in use, which keeps unregistering from getting past that check. The next patch has a caller that only pins the memory of @head. For that one the table, and whatever the owner of the header keeps behind it, is only there for as long as nobody unregisters the header, which happens under sysctl_lock. So read the mode and set the ownership before letting go of the lock. The ->set_ownership() callbacks only look up ids in a user namespace.

Quoted 3 lines

No functional changes.

Sashiko has reviewed this patch and found no issues.

Signature · 1 line
Sashiko AI review · https://sashiko.dev/#/patchset/[email protected]?part=47
author maintainer
#105 lore raw

PATCH RESEND v2 48/51 proc: sysctl: don't hold the tables while readdir copies to userspace

In reply to Christian Brauner

proc_sys_readdir() holds the directory's table for the whole readdir and the table of each entry while dir_emit() copies its name to userspace. Unregistering a table waits until nobody uses it anymore. So a getdents64() whose buffer faults for as long as it wants keeps unregister_sysctl_table() waiting, just like a stalled read() does. Listing /proc/sys/net/ipv6/conf/<dev>/ that way holds up the removal of the device under RTNL.

So don't take any table into use for a listing. A header counts what refers to its memory, the inodes made for it, and unregistering doesn't wait for those. readdir takes one of those references on the entry it is at instead, which keeps the header around and nothing else. Under sysctl_lock, where unregistering erases an entry, it finds the entry, copies its name, follows a link to the entry it stands for and pins that. Then it looks the dentry up, creates the inode if there is none, which checks for itself under sysctl_lock that the table is still registered, and emits the entry with nothing held at all. An entry whose table is being unregistered by then is still skipped. The next entry is the first live one after that name, which is where a listing resumes between calls since "proc: sysctl: resume readdir after the last name it returned" anyway. kernfs_fop_readdir() and proc_readdir_de() work the same way, a reference on the entry and the lock only to find the next one.

While the entry is still registered its node is still in the tree and the next one is right behind it, like kernfs_dir_next_pos() continues from the node it holds. Only once it went away, and to resume, is the next entry found by name. That's one trip through sysctl_lock per entry like before, and the link entries of /proc/sys/net no longer take two more. The directory isn't taken into use either, an entry keeps its directory registered while it is used and readdir looks at the directory under the lock. So the dots don't wait for anything, a directory that went away lists them and then fails with -ENOENT. A seek to an arbitrary position counts the entries from the start like before, one trip per entry.

While at it, return errors instead of ending the listing as if the directory was done.

Fixes 77b14db502cb ("[PATCH] sysctl: reimplement the sysctl proc support")
---
 fs/proc/proc_sysctl.c | 311 +++++++++++++++++++++++++++-----------------------
 1 file changed, 166 insertions(+), 145 deletions(-)
fs/proc/proc_sysctl.c +166 -145
index 82024f1ea756..6a92c33db9b5 100644
@@ -91,6 +91,8 @@ static void drop_sysctl_table(struct ctl_table_header *header);
 static int sysctl_follow_link(struct ctl_table_header **phead,
 	const struct ctl_table **pentry);
 static int insert_links(struct ctl_table_header *head);
+static struct ctl_table_set *lookup_header_set(struct ctl_table_root *root);
+static struct ctl_dir *xlate_dir(struct ctl_table_set *set, struct ctl_dir *dir);
 static void put_links(struct ctl_table_header *header);
 
 static void sysctl_print_dir(struct ctl_dir *dir)
@@ -367,86 +369,96 @@ static const struct ctl_table *lookup_entry(struct ctl_table_header **phead,
 	return entry;
 }
 
-static struct ctl_node *first_usable_entry(struct rb_node *node)
-{
-	struct ctl_node *ctl_node;
+/*
+ * What readdir takes along for an entry between the trips through
+ * sysctl_lock: the header pinned, which keeps its memory and nothing else,
+ * the entry and its name. For a link the header and entry are the
+ * ones it stands for in the caller's set.
+ */
+struct sysctl_dirent {
+	struct ctl_table_header *head;
+	const struct ctl_table *table;
+	struct ctl_node *node;		/* the entry's node in the directory, NULL for a link */
+	ino_t ino;
+	unsigned int type;
+	bool skip;
+	int len;
+	char name[NAME_MAX + 1];
+};
 
-	for (;node; node = rb_next(node)) {
-		ctl_node = rb_entry(node, struct ctl_node, node);
-		if (use_table(ctl_node->header))
-			return ctl_node;
-	}
-	return NULL;
+/* A reference on the memory of @head, like an inode made for it holds. */
+static void sysctl_pin(struct ctl_table_header *head)
+{
+	lockdep_assert_held(&sysctl_lock);
+	head->count++;
 }
 
-static void first_entry(struct ctl_dir *dir,
-	struct ctl_table_header **phead, const struct ctl_table **pentry)
+static void sysctl_unpin(struct ctl_table_header *head)
 {
-	struct ctl_table_header *head = NULL;
-	const struct ctl_table *entry = NULL;
-	struct ctl_node *ctl_node;
-
-	spin_lock(&sysctl_lock);
-	ctl_node = first_usable_entry(rb_first(&dir->root));
-	spin_unlock(&sysctl_lock);
-	if (ctl_node) {
-		head = ctl_node->header;
-		entry = &head->ctl_table[ctl_node - head->node];
-	}
-	*phead = head;
-	*pentry = entry;
+	lockdep_assert_held(&sysctl_lock);
+	if (!--head->count)
+		kfree_rcu(head, rcu);
 }
 
-static void next_entry(struct ctl_table_header **phead, const struct ctl_table **pentry)
+/* the first entry from @node on whose table isn't being unregistered */
+static struct ctl_node *first_live_entry(struct rb_node *node)
 {
-	struct ctl_table_header *head = *phead;
-	const struct ctl_table *entry = *pentry;
-	struct ctl_node *ctl_node = &head->node[entry - head->ctl_table];
-
-	spin_lock(&sysctl_lock);
-	unuse_table(head);
+	struct ctl_node *ctl_node;
 
-	ctl_node = first_usable_entry(rb_next(&ctl_node->node));
-	spin_unlock(&sysctl_lock);
-	head = NULL;
-	if (ctl_node) {
-		head = ctl_node->header;
-		entry = &head->ctl_table[ctl_node - head->node];
+	lockdep_assert_held(&sysctl_lock);
+	for (; node; node = rb_next(node)) {
+		ctl_node = rb_entry(node, struct ctl_node, node);
+		if (!ctl_node->header->unregistering)
+			return ctl_node;
 	}
-	*phead = head;
-	*pentry = entry;
+	return NULL;
 }
 
 /*
- * The first usable entry of @dir after @name, or the first one at all for a
- * NULL @name. The entries are sorted by name, so that is where a listing
- * resumes when entries in front of it came or went in between. -ENOENT if
- * the directory is being unregistered.
+ * Fill @d with the entry of @dir behind the one it holds, letting go of that
+ * one, or with the first live entry after @name, or the first one at all for
+ * a NULL @name. While the entry @d holds is still registered its node is
+ * still in the tree and the next one is right behind it. Once it is gone the
+ * entries are found by name, they are sorted by it, so that is also where a
+ * listing resumes when entries in front of it came or went in between.
+ * 1 with the next entry pinned in @d, 0 at the end of the directory and
+ * -ENOENT once @dir itself is being unregistered.
+ *
+ * Everything that reads the tables happens under sysctl_lock, where an entry
+ * is erased when it is unregistered, since nothing holds the tables in use.
  */
-static int entry_after(struct ctl_dir *dir, const char *name, int namelen,
-		       struct ctl_table_header **phead,
-		       const struct ctl_table **pentry)
+static int sysctl_dir_next(struct ctl_dir *dir, struct sysctl_dirent *d,
+			   const char *name, int namelen)
 {
-	struct ctl_table_header *head = NULL;
-	const struct ctl_table *entry = NULL;
 	struct rb_node *node, *after = NULL;
+	struct ctl_table_header *head;
+	const struct ctl_table *entry;
 	struct ctl_node *ctl_node;
+	bool by_name = true;
+	int ret = 0;
 
 	spin_lock(&sysctl_lock);
+	if (d->head) {
+		if (d->node && !d->head->unregistering) {
+			after = rb_next(&d->node->node);
+			by_name = false;
+		}
+		sysctl_unpin(d->head);
+		d->head = NULL;
+	}
 	if (unlikely(dir->header.unregistering)) {
-		spin_unlock(&sysctl_lock);
-		return -ENOENT;
+		ret = -ENOENT;
+		goto out;
 	}
-	if (!name) {
+	if (!by_name) {
+		/* behind the entry @d held */
+	} else if (!name) {
 		after = rb_first(&dir->root);
 	} else for (node = dir->root.rb_node; node;) {
-		const struct ctl_table *table;
-		struct ctl_table_header *h;
-
 		ctl_node = rb_entry(node, struct ctl_node, node);
-		h = ctl_node->header;
-		table = &h->ctl_table[ctl_node - h->node];
-		if (namecmp(table->procname, strlen(table->procname),
+		head = ctl_node->header;
+		entry = &head->ctl_table[ctl_node - head->node];
+		if (namecmp(entry->procname, strlen(entry->procname),
 			    name, namelen) > 0) {
 			after = node;
 			node = node->rb_left;
@@ -454,15 +466,55 @@ static int entry_after(struct ctl_dir *dir, const char *name, int namelen,
 			node = node->rb_right;
 		}
 	}
-	ctl_node = first_usable_entry(after);
-	spin_unlock(&sysctl_lock);
-	if (ctl_node) {
-		head = ctl_node->header;
-		entry = &head->ctl_table[ctl_node - head->node];
+	ctl_node = first_live_entry(after);
+	if (!ctl_node)
+		goto out;
+	head = ctl_node->header;
+	entry = &head->ctl_table[ctl_node - head->node];
+
+	d->len = strlen(entry->procname);
+	if (d->len > NAME_MAX) {
+		ret = -ENAMETOOLONG;
+		goto out;
 	}
-	*phead = head;
-	*pentry = entry;
-	return 0;
+	memcpy(d->name, entry->procname, d->len);
+	d->skip = false;
+	d->node = ctl_node;
+	if (unlikely(S_ISLNK(entry->mode))) {
+		/* the entry it stands for in the caller's set, or nothing */
+		struct ctl_table_root *root = entry->data;
+		struct ctl_table_set *set = lookup_header_set(root);
+		struct ctl_dir *xdir = xlate_dir(set, head->parent);
+		struct ctl_table_header *xhead = NULL;
+		const struct ctl_table *xentry = NULL;
+
+		if (!IS_ERR(xdir))
+			xentry = find_entry(&xhead, xdir, d->name, d->len);
+		if (!xentry || xhead->unregistering) {
+			d->skip = true;
+		} else {
+			head = xhead;
+			entry = xentry;
+		}
+		d->node = NULL;
+	}
+	sysctl_pin(head);
+	d->head = head;
+	d->table = entry;
+	ret = 1;
+out:
+	spin_unlock(&sysctl_lock);
+	return ret;
+}
+
+static void sysctl_dir_done(struct sysctl_dirent *d)
+{
+	if (!d->head)
+		return;
+	spin_lock(&sysctl_lock);
+	sysctl_unpin(d->head);
+	spin_unlock(&sysctl_lock);
+	d->head = NULL;
 }
 
 /*
@@ -765,112 +817,71 @@ static void sysctl_cursor_set(struct file *file, const char *name, int len,
 	memcpy(cursor->name, name, len);
 }
 
-static bool proc_sys_fill_cache(struct file *file,
-				struct dir_context *ctx,
-				struct ctl_table_header *head,
-				const struct ctl_table *table)
+/*
+ * The inode number and type of the entry @d holds, instantiating its dentry
+ * if there is none. Needs the header pinned, proc_sys_make_inode() checks
+ * for itself that the table is still registered.
+ */
+static int proc_sys_fill_dirent(struct file *file, struct sysctl_dirent *d)
 {
 	struct dentry *child, *dir = file->f_path.dentry;
 	struct inode *inode;
 	struct qstr qname;
-	ino_t ino = 0;
-	unsigned type = DT_UNKNOWN;
 
-	qname.name = table->procname;
-	qname.len  = strlen(table->procname);
+	qname.name = d->name;
+	qname.len  = d->len;
 	qname.hash = full_name_hash(dir, qname.name, qname.len);
 
 	child = d_lookup(dir, &qname);
 	if (!child) {
 		child = d_alloc_parallel(dir, &qname);
 		if (IS_ERR(child))
-			return false;
+			return PTR_ERR(child);
 		if (d_in_lookup(child)) {
 			struct dentry *res;
-			inode = proc_sys_make_inode(dir->d_sb, head, table);
+			inode = proc_sys_make_inode(dir->d_sb, d->head, d->table);
 			res = d_splice_alias_ops(inode, child,
 						 &proc_sys_dentry_operations);
 			d_lookup_done(child);
 			if (unlikely(res)) {
 				dput(child);
 
-				/* skip an entry whose table is being unregistered */
-				if (res == ERR_PTR(-ENOENT))
-					return true;
 				if (IS_ERR(res))
-					return false;
+					return PTR_ERR(res);
 
 				child = res;
 			}
 		}
 	}
 	inode = d_inode(child);
-	ino  = inode->i_ino;
-	type = inode->i_mode >> 12;
+	d->ino = inode->i_ino;
+	d->type = inode->i_mode >> 12;
 	dput(child);
-	return dir_emit(ctx, qname.name, qname.len, ino, type);
-}
-
-static bool proc_sys_link_fill_cache(struct file *file,
-				    struct dir_context *ctx,
-				    struct ctl_table_header *head,
-				    const struct ctl_table *table)
-{
-	bool ret = true;
-
-	head = sysctl_head_grab(head);
-	if (IS_ERR(head))
-		return false;
-
-	/* It is not an error if we can not follow the link ignore it */
-	if (sysctl_follow_link(&head, &table))
-		goto out;
-
-	ret = proc_sys_fill_cache(file, ctx, head, table);
-out:
-	sysctl_head_finish(head);
-	return ret;
-}
-
-static int scan(struct ctl_table_header *head, const struct ctl_table *table,
-		unsigned long *pos, struct file *file,
-		struct dir_context *ctx)
-{
-	bool res;
-
-	if ((*pos)++ < ctx->pos)
-		return true;
-
-	if (unlikely(S_ISLNK(table->mode)))
-		res = proc_sys_link_fill_cache(file, ctx, head, table);
-	else
-		res = proc_sys_fill_cache(file, ctx, head, table);
-
-	if (res) {
-		ctx->pos = *pos;
-		sysctl_cursor_set(file, table->procname, strlen(table->procname),
-				  ctx->pos);
-	}
-
-	return res;
+	return 0;
 }
 
+/*
+ * Unregistering a table waits until nobody uses it anymore and a copy to
+ * userspace can take as long as userspace wants. So a listing doesn't take
+ * any table into use. It pins the memory of the entry it is at, finds the
+ * next one under sysctl_lock and emits with nothing held, like
+ * kernfs_fop_readdir() and proc_readdir_de() do. Between calls a listing
+ * resumes after the name of the last entry it emitted.
+ */
 static int proc_sys_readdir(struct file *file, struct dir_context *ctx)
 {
-	struct ctl_table_header *head = grab_header(file_inode(file));
+	struct ctl_table_header *head = PROC_I(file_inode(file))->sysctl;
 	struct sysctl_cursor *cursor = file->private_data;
-	struct ctl_table_header *h = NULL;
-	const struct ctl_table *entry;
+	struct sysctl_dirent d = {};
 	struct ctl_dir *ctl_dir;
-	unsigned long pos;
-
-	if (IS_ERR(head))
-		return PTR_ERR(head);
+	int err;
 
+	if (!head)
+		head = &sysctl_table_root.default_set.dir.header;
 	ctl_dir = container_of(head, struct ctl_dir, header);
 
 	if (!dir_emit_dots(file, ctx))
-		goto out;
+		return 0;
 
 	/*
 	 * Resume after the last entry the previous call emitted. Only a seek
@@ -878,22 +889,32 @@ static int proc_sys_readdir(struct file *file, struct dir_context *ctx)
 	 * seeking to an arbitrary position always did.
 	 */
 	if (cursor && cursor->pos == ctx->pos) {
-		entry_after(ctl_dir, cursor->name, cursor->len, &h, &entry);
-		pos = ctx->pos;
+		err = sysctl_dir_next(ctl_dir, &d, cursor->name, cursor->len);
 	} else {
-		first_entry(ctl_dir, &h, &entry);
-		pos = 2;
+		loff_t pos = 2;
+
+		err = sysctl_dir_next(ctl_dir, &d, NULL, 0);
+		while (err > 0 && pos++ < ctx->pos)
+			err = sysctl_dir_next(ctl_dir, &d, d.name, d.len);
 	}
+	if (err < 0)
+		return err;
 
-	for (; h; next_entry(&h, &entry)) {
-		if (!scan(h, entry, &pos, file, ctx)) {
-			sysctl_head_finish(h);
-			break;
+	while (err > 0) {
+		if (!d.skip) {
+			err = proc_sys_fill_dirent(file, &d);
+			/* skip an entry whose table is being unregistered */
+			if (err && err != -ENOENT)
+				break;
+			if (!err && !dir_emit(ctx, d.name, d.len, d.ino, d.type))
+				break;
 		}
+		ctx->pos++;
+		sysctl_cursor_set(file, d.name, d.len, ctx->pos);
+		err = sysctl_dir_next(ctl_dir, &d, d.name, d.len);
 	}
-out:
-	sysctl_head_finish(head);
-	return 0;
+	sysctl_dir_done(&d);
+	return err;
 }
 
 static int proc_sys_dir_release(struct inode *inode, struct file *file)
Signature · 1 line
2.53.0
#106 lore raw

Re: [PATCH RESEND v2 48/51] proc: sysctl: don't hold the tables while readdir copies to userspace

Sashiko has reviewed this patch and found no issues.
Quoted 18 lines

proc_sys_readdir() holds the directory's table for the whole readdir and the table of each entry while dir_emit() copies its name to userspace. Unregistering a table waits until nobody uses it anymore. So a getdents64() whose buffer faults for as long as it wants keeps unregister_sysctl_table() waiting, just like a stalled read() does. Listing /proc/sys/net/ipv6/conf/<dev>/ that way holds up the removal of the device under RTNL.

So don't take any table into use for a listing. A header counts what refers to its memory, the inodes made for it, and unregistering doesn't wait for those. readdir takes one of those references on the entry it is at instead, which keeps the header around and nothing else. Under sysctl_lock, where unregistering erases an entry, it finds the entry, copies its name, follows a link to the entry it stands for and pins that. Then it looks the dentry up, creates the inode if there is none, [ ... ]
directory was done.

Quoted 3 lines
Fixes 77b14db502cb ("[PATCH] sysctl: reimplement the sysctl proc support")

Sashiko has reviewed this patch and found no issues.

Signature · 1 line
Sashiko AI review · https://sashiko.dev/#/patchset/[email protected]?part=48
author maintainer
#107 lore raw

PATCH RESEND v2 49/51 selftests/proc: check that faulting sysctl accesses don't hold up removal

In reply to Christian Brauner

Read, write and list /proc/sys/net/ipv6/conf/<dev>/ of a tun device with a buffer whose first page is backed by userfaultfd and remove the device while the task sleeps in its copy from or to userspace:

- unregistering the table doesn't wait for a faulting read(), write() or getdents64()

- the read still gets the value that was produced before the removal and the next read fails with -ENOENT

- the write is copied in after the removal and fails with -ENOENT

- getdents64() still lists what it looked up before the removal and fails with -ENOENT afterwards

The tables are unregistered under RTNL, so a regression stalls each test for five seconds before it fails.

---
 tools/testing/selftests/proc/.gitignore            |   1 +
 tools/testing/selftests/proc/Makefile              |   1 +
 .../selftests/proc/proc-remove-slow-sysctl.c       | 215 +++++++++++++++++++++
 3 files changed, 217 insertions(+)
tools/testing/selftests/proc/.gitignore +1 -0
index 5b5e24e39cbd..7b8133492782 100644
@@ -21,6 +21,7 @@
 /proc-uptime-001
 /proc-uptime-002
 /proc-pidns
+/proc-remove-slow-sysctl
 /read
 /self
 /setns-dcache
tools/testing/selftests/proc/Makefile +1 -0
index dae09f333455..bce6beca7274 100644
@@ -32,5 +32,6 @@ TEST_GEN_PROGS += proc-multiple-procfs
 TEST_GEN_PROGS += proc-fsconfig-hidepid
 TEST_GEN_PROGS += proc-sysctl-readdir-churn
 TEST_GEN_PROGS += proc-pidns
+TEST_GEN_PROGS += proc-remove-slow-sysctl
 
 include ../lib.mk
tools/testing/selftests/proc/proc-remove-slow-sysctl.c new file +215 -0

215 lines not on this page · raw message

Signature · 1 line
2.53.0
#108 lore raw

Re: [PATCH RESEND v2 49/51] selftests/proc: check that faulting sysctl accesses don't hold up removal

Sashiko has reviewed this patch and found no issues.
Quoted 12 lines

Read, write and list /proc/sys/net/ipv6/conf/<dev>/ of a tun device with a buffer whose first page is backed by userfaultfd and remove the device while the task sleeps in its copy from or to userspace:

- unregistering the table doesn't wait for a faulting read(), write() or getdents64()

- the read still gets the value that was produced before the removal and the next read fails with -ENOENT

- the write is copied in after the removal and fails with -ENOENT

Quoted 7 lines

- getdents64() still lists what it looked up before the removal and fails with -ENOENT afterwards

The tables are unregistered under RTNL, so a regression stalls each test for five seconds before it fails.

Sashiko has reviewed this patch and found no issues.

Signature · 1 line
Sashiko AI review · https://sashiko.dev/#/patchset/[email protected]?part=49
author maintainer
#109 lore raw

PATCH RESEND v2 50/51 proc: don't pin a symlink's entry while readlink() copies it out

In reply to Christian Brauner

proc_get_link() pins the entry with use_pde() and the delayed call unpins it. vfs_readlink() copies the link to userspace in between. So a page fault in that copy holds up remove_proc_entry() just like the copies of reads and writes do, and the callers hold locks while they wait. /proc/asound/<id> is removed with snd_card_mutex and info_mutex held when a card changes its id.

The pin doesn't keep anything alive. proc_symlink() copies the target and pde_free() frees it with the entry, and the inode holds a reference to the entry. What the pin does is keep a removed symlink from being followed. So check ->in_use instead and drop the delayed call. That also takes an atomic pair off every traversal of /proc/net and /proc/mounts.

Fixes 7e0e953bb0cf ("procfs: fix race between symlink removals and traversals")
---
 fs/proc/inode.c | 14 +++++++-------
 1 file changed, 7 insertions(+), 7 deletions(-)
fs/proc/inode.c +7 -7
index 9933f03ab9fb..2d65f3c8ec03 100644
@@ -629,19 +629,19 @@ static const struct file_operations proc_iter_file_ops_compat = {
 };
 #endif
 
-static void proc_put_link(void *p)
-{
-	unuse_pde(p);
-}
-
 static const char *proc_get_link(struct dentry *dentry,
 				 struct inode *inode,
 				 struct delayed_call *done)
 {
 	struct proc_dir_entry *pde = PDE(inode);
-	if (!use_pde(pde))
+
+	/*
+	 * No pin. The link lives with the entry, which the inode holds, and a
+	 * reader could fault while vfs_readlink() copies it out. Just don't
+	 * follow a removed one.
+	 */
+	if (unlikely(atomic_read(&pde->in_use) < 0))
 		return ERR_PTR(-EINVAL);
-	set_delayed_call(done, proc_put_link, pde);
 	return pde->data;
 }
 
Signature · 1 line
2.53.0
#110 lore raw

Re: [PATCH RESEND v2 50/51] proc: don't pin a symlink's entry while readlink() copies it out

Sashiko has reviewed this patch and found no issues.
Quoted 14 lines

proc_get_link() pins the entry with use_pde() and the delayed call unpins it. vfs_readlink() copies the link to userspace in between. So a page fault in that copy holds up remove_proc_entry() just like the copies of reads and writes do, and the callers hold locks while they wait. /proc/asound/<id> is removed with snd_card_mutex and info_mutex held when a card changes its id.

The pin doesn't keep anything alive. proc_symlink() copies the target and pde_free() frees it with the entry, and the inode holds a reference to the entry. What the pin does is keep a removed symlink from being followed. So check ->in_use instead and drop the delayed call. That also takes an atomic pair off every traversal of /proc/net and /proc/mounts.

Quoted 3 lines
Fixes 7e0e953bb0cf ("procfs: fix race between symlink removals and traversals")

Sashiko has reviewed this patch and found no issues.

Signature · 1 line
Sashiko AI review · https://sashiko.dev/#/patchset/[email protected]?part=50
author maintainer
#111 lore raw

PATCH RESEND v2 51/51 selftests/proc: check that a faulting readlink() doesn't hold up removal

In reply to Christian Brauner

Add the symlink case:

- readlink() /proc/asound/<id> of a dummy card into a buffer backed by userfaultfd

- change the card's id through sysfs while the reader faults, which removes the symlink with snd_card_mutex and info_mutex held

- expect that to finish without waiting for the reader

Skipped without snd-dummy.

---
 tools/testing/selftests/proc/.gitignore            |   1 +
 tools/testing/selftests/proc/Makefile              |   1 +
 tools/testing/selftests/proc/config                |   5 +
 .../selftests/proc/proc-remove-slow-readlink.c     | 191 +++++++++++++++++++++
 4 files changed, 198 insertions(+)
tools/testing/selftests/proc/.gitignore +1 -0
index 7b8133492782..3fa89f46b9c7 100644
@@ -22,6 +22,7 @@
 /proc-uptime-002
 /proc-pidns
 /proc-remove-slow-sysctl
+/proc-remove-slow-readlink
 /read
 /self
 /setns-dcache
tools/testing/selftests/proc/Makefile +1 -0
index bce6beca7274..df02699a3587 100644
@@ -33,5 +33,6 @@ TEST_GEN_PROGS += proc-fsconfig-hidepid
 TEST_GEN_PROGS += proc-sysctl-readdir-churn
 TEST_GEN_PROGS += proc-pidns
 TEST_GEN_PROGS += proc-remove-slow-sysctl
+TEST_GEN_PROGS += proc-remove-slow-readlink
 
 include ../lib.mk
tools/testing/selftests/proc/config +5 -0
index 052e365af5a9..1504a761b39b 100644
@@ -3,3 +3,8 @@ CONFIG_NET_NS=y
 CONFIG_IPV6=y
 CONFIG_TUN=y
 CONFIG_USERFAULTFD=y
+CONFIG_SOUND=y
+CONFIG_SND=y
+CONFIG_SND_DUMMY=m
+CONFIG_MODULES=y
+CONFIG_MODULE_UNLOAD=y
tools/testing/selftests/proc/proc-remove-slow-readlink.c new file +191 -0

191 lines not on this page · raw message

Signature · 1 line
2.53.0
#112 lore raw

Re: [PATCH RESEND v2 51/51] selftests/proc: check that a faulting readlink() doesn't hold up removal

Sashiko has reviewed this patch and found no issues.
Quoted 5 lines

Add the symlink case:

- readlink() /proc/asound/<id> of a dummy card into a buffer backed by userfaultfd

Quoted 8 lines

- change the card's id through sysfs while the reader faults, which removes the symlink with snd_card_mutex and info_mutex held

- expect that to finish without waiting for the reader

Skipped without snd-dummy.

Sashiko has reviewed this patch and found no issues.

Signature · 1 line
Sashiko AI review · https://sashiko.dev/#/patchset/[email protected]?part=51
author maintainer
#113 lore raw

v2 cover proc: let procfs own the data path (Part 2/7)

In reply to Christian Brauner

Part 2/7 of "proc: move procfs to what kernfs does", on top of part 1:

https://patch.msgid.link/20261104-work-procfs-v2-0-b45cd5789ac5@brauner

remove_proc_entry() waits until every call into the entry has returned. A seq_file entry wait across seq_read_iter() including the copy to userspace. Non-seq_file entries wait across ->proc_read(), ->proc_write() and ->proc_ioctl(), which copy to and from userspace as well.

A reader or writer can abuse a page fault to make copy take as long as it wants. For example, by using userfaultfd or by punching holes into a memfd over and over. And callers of remove_proc_entry() like to hold locks while they wait. For instance, addrconf holds RTNL when it removes /proc/net/dev_snmp6/<dev> and xt_hashlimit holds hashlimit_mutex which is shared by all network namespaces.

There was a hackish and very narrow AI solution to a small part of this bug class which was sent off-list. In essence, it used a second buffering mechanism on top of seqfiles which was really nasty. It also didn't address any of the non-seqfile users.

If we want to get rid of the this whole bug class we need a bigger hammer. That means reworking how procfs handles data. So I tried to work through all of that.

This changes procfs so the entry's code only ever runs with the entry pinned and never touches userspace memory. This is the core procfs change required for this. The entries themselves are converted in four series on top of it. The are independent of each other. The last series drops all __user methods.

* seq_file reads

procfs owns the seq_file and only calls into the entry with it pinned. An entry declares its seq_operations, or just a show function, and the size of its private state in struct proc_ops. procfs opens and frees the seq_file and reads and seeks through seq_file directly.

->proc_open() and ->proc_release() only deal with whatever the entry needs on top of that. proc_create_seq() and friends already keep the seq_operations in the entry so they're switched over in one go here. That covers most of /proc/net.

The open coded single_open() and seq_open() users that don't do anything else are converted with a coccinelle script. A nice side effect is that opening one of these entries no longer allocates a pde_opener as they have no ->proc_release() of their own anymore.

* Writes

procfs copies in what is written before it pins the entry and hands the entry a NUL-terminated kernel copy through ->proc_write_buf().

The copy is capped at PAGE_SIZE - 1 bytes unless the entry asks for more in ->proc_write_size.

Entries that take binary data in pieces (the PCI config space, ALSA's data entries, cio_ignore and the rtas flash files) ask for PROC_ENTRY_SHORT_WRITES and their writes come up short.

Since procfs copies in the whole write first, a write that is too large or whose buffer can't be read fails before the entry's own checks now.

* Reads that don't go through seq_file

An entry fills a kernel buffer in ->proc_read_buf(), procfs copies that to userspace after unpinning the entry and only moves the position if that copy worked, like kernfs_file_read_iter().

The buffer is a page unless the entry asks for more in ->proc_read_size, and like with kernfs a larger read comes up short.

Entries whose readers want all of a large file in one read, /proc/vmcore, /proc/config.gz and ALSA's data entries, ask for PROC_ENTRY_FULL_READS and procfs fills their reads in pieces. These entries are read through ->read_iter() now, so sendfile() and splice() work for them.

* ioctls

The command number doesn't reliably say what an ioctl copies. The PCI ioctls aren't encoded at all, i8k's encode the wrong sizes and esas2r uses a range of plain numbers.

So an entry lists its commands in ->proc_ioctl_args with what goes in and what comes back out. That works like DRM's ioctl tables.

procfs copies the argument in before it pins the entry, calls ->proc_ioctl_buf() with that copy and copies it back out after unpinning the entry.

A command that isn't in the table fails with -ENOTTY. 32-bit tasks go through the same table, so the compat hooks go away.

* permanent entries

Entries that are never removed, kcore, kmsg and the kpage files, keep reading straight into userspace. The last series gives them file_operations of their own and takes the __user methods out of struct proc_ops altogether.

* mmap()

procfs pins the entry around ->proc_mmap() and then wraps the vm_operations of the mapping the way kernfs does. So the entry's ->fault(), ->page_mkwrite(), ->access() and ->open() run pinned as well.

Removing the entry unmaps the mappings in its own address space, like kernfs does, and a fault into one of them is SIGBUS from then on.

A file that maps through another address space, /proc/bus/pci through the one of /dev/mem, keeps its mappings like a sysfs resource file does. The entry's vm_operations live in its open node. vmcore's mappings of the old memory no longer outlive fadump releasing it.

* Poll

An entry with a ->proc_poll() used to sleep its pollers on a wait queue of its own and procfs only pinned the entry around the call.

The poller stays on that queue after the call, so after
remove_proc_entry() ran ->proc_release() on the still open file and the owner freed the queue with the rest.

sunrpc kept the queue of its channel files in the per-namespace cache_detail, so a poll() across the end of the namespace was a use-after-free. md works around the same thing at unload by waking its pollers in a loop until nobody is left.

Make procfs own the wait queue. It lives in the open node, proc_reg_poll() does the poll_wait() on it before it calls the method. The owner wakes the pollers with proc_poll_notify(), and a poll of a removed entry reports EPOLLERR | EPOLLPRI.

The seven pollable entries in the tree move over in the conversion series.

The last series takes the poll_table away from ->proc_poll() once nothing needs it anymore.

* Lockdep

The pin is a read lock to lockdep and a removal takes the write side around waiting for the last user, the way kernfs annotates its active reference.

A method that takes a lock while pinned and a removal under that lock is the deadlock xt_recent had, and lockdep reports it now instead of a reviewer having to find it.

The class is per kind of entry, keyed on the seq_operations or proc_ops the entries of a kind share, and per registration site for the entries that only share a show function, like sysfs keys per attribute.

On a KASAN and lockdep kernel the reader selftest fails without the series and passes with it, and the mapped-entry selftest, run against a virtio-rng device in a VM, fails without the mmap patch and passes with it. The other proc selftests behave the same with and without the series and so do the entries converted here that I could get at in a VM.

---
Changes in v2:
- the open files of an entry live in an open node that only entries with
a release or mmap hook get, a removal waits with wait_var_event(), the readdir cursor is shared with sysctl
- procfs pins the entry around the vm_operations of its mappings and
unmaps a removed entry's own address space like kernfs does, with a selftest; a file that maps through another address space,
/proc/bus/pci through the one of /dev/mem, keeps its mappings like a
sysfs resource file; vmcore's mappings of the old memory no longer
outlive fadump releasing it
- lockdep checks the pin
- procfs owns the wait queue of an entry with a ->proc_poll(), the
conversions are in the area series
- the seq_file runs the entry's own ->next() and ->show() with procfs's ->start() and ->stop() around them instead of a wrapper per record,
which cost up to 24% on /proc/vmstat, and the ERR_PTR(-EIO) sentinel
is gone
- ioctls that only pass a value no longer copy to a NULL pointer
(-EFAULT on csky), and registration also refuses a
->proc_compat_ioctl() next to ->proc_ioctl_buf()
- rebased onto v7.4-rc1
- Link to v1: https://patch.msgid.link/[email protected]

---
Christian Brauner (23):
proc: drop the compat file operations
proc: add pde_pin() and pde_unpin()
proc: share the readdir cursor with sysctl
proc: wait for the last user of an entry with wait_var_event()
proc: keep the open files of an entry in an open node
proc: make room for more entry flags
proc: let procfs own the seq_file of seq_file entries
proc: let procfs own the seq_file of proc_create_seq() and friends
proc: let procfs own the seq_file of DEFINE_PROC_SHOW_ATTRIBUTE() files
treewide: let procfs own the seq_file of simple proc entries selftests/proc: check that a faulting reader doesn't hold up removal
seq_file: add seq_preallocate()
proc: let procfs own the seq_file of /proc/stat
proc: let procfs copy in writes before pinning the entry
proc: copy in writes to the network namespace entries before pinning
proc: let procfs copy out reads that don't go through seq_file fs/proc/vmcore: let procfs copy out reads
proc: let procfs copy ioctl arguments in and out
proc: pin the entry around the vm_operations of its mappings selftests/proc: check that a mapped entry can be removed
proc: let lockdep check the pin
proc: own the wait queue of an entry with a ->proc_poll()
Documentation: seq_file: describe how a /proc file uses seq_file

 Documentation/filesystems/seq_file.rst             |  42 +-
 arch/alpha/kernel/srm_env.c                        |  10 +-
 arch/arm/mm/alignment.c                            |  10 +-
 arch/powerpc/kernel/rtas-proc.c                    |  50 +-
 arch/powerpc/platforms/pseries/lpar.c              |  20 +-
 arch/powerpc/platforms/pseries/lparcfg.c           |  10 +-
 arch/sh/mm/alignment.c                             |  10 +-
 arch/sparc/kernel/led.c                            |  10 +-
 arch/um/kernel/exitcode.c                          |  10 +-
 drivers/acpi/proc.c                                |  12 +-
 drivers/hwmon/dell-smm-hwmon.c                     |  10 +-
 drivers/input/input.c                              |  24 +-
 drivers/macintosh/via-pmu.c                        |  10 +-
 drivers/net/wireless/intel/ipw2x00/libipw_module.c |  10 +-
 drivers/platform/x86/lenovo/thinkpad_acpi.c        |  10 +-
 drivers/platform/x86/toshiba_acpi.c                |  40 +-
 drivers/pnp/pnpbios/proc.c                         |  10 +-
 drivers/s390/block/dasd_proc.c                     |  10 +-
 drivers/s390/cio/blacklist.c                       |  13 +-
 drivers/scsi/scsi_devinfo.c                        |  10 +-
 drivers/scsi/scsi_proc.c                           |  21 +-
 drivers/usb/gadget/function/rndis.c                |  10 +-
 drivers/video/fbdev/via/viafbdev.c                 |  70 +--
 fs/jfs/jfs_debug.c                                 |  10 +-
 fs/ntfs3/super.c                                   |  20 +-
 fs/proc/cpuinfo.c                                  |  10 +-
 fs/proc/generic.c                                  | 261 ++++++---
 fs/proc/inode.c                                    | 652 ++++++++++++++++-----
 fs/proc/internal.h                                 | 146 ++++-
 fs/proc/proc_net.c                                 |  72 +--
 fs/proc/proc_sysctl.c                              |  45 +-
 fs/proc/stat.c                                     |   6 +-
 fs/proc/vmcore.c                                   |  14 +-
 fs/seq_file.c                                      |  36 +-
 fs/smb/client/cifs_debug.c                         |  79 +--
 fs/smb/client/dfs_cache.c                          |  10 +-
 include/linux/proc_fs.h                            | 159 ++++-
 include/linux/seq_file.h                           |  11 +-
 kernel/irq/proc.c                                  |  30 +-
 kernel/latencytop.c                                |  10 +-
 lib/dynamic_debug.c                                |   6 +-
 mm/slab_common.c                                   |  10 +-
 net/core/pktgen.c                                  |  30 +-
 net/sunrpc/stats.c                                 |  10 +-
 tools/testing/selftests/proc/.gitignore            |   2 +
 tools/testing/selftests/proc/Makefile              |   2 +
 tools/testing/selftests/proc/proc-remove-mapped.c  | 160 +++++
 .../selftests/proc/proc-remove-slow-reader.c       | 133 +++++
 48 files changed, 1440 insertions(+), 916 deletions(-)

---
base-commit: 6628e7d4c6b25c8d18f1345e3a20d21829aae7e4
change-id: 20261101-work-procfs-core-8fa4a4f412cf
prerequisite-change-id: 20261101-work-procfs-bugfixes-054d00028491:v2
prerequisite-patch-id: a81e8b894107e48d607f8257d2c9f56e0dd6f400
prerequisite-patch-id: 7edf7ca7ecd32c9e09085e4b65922af10097beaa
prerequisite-patch-id: 81f6893f79b4236637675553298a6f2892b603f3
prerequisite-patch-id: 598c2b1a389f47adcac88ebcf1c9f74e2511fbab
prerequisite-patch-id: 6f5a2172dacc5ff2491fa9832c48ccd0e1ce1eda
prerequisite-patch-id: 8947af6490288e4e2a3b2bf8844a974bedb1d975
prerequisite-patch-id: 8cbe756286fd95967d31b0c46cacfeb05f0a2c6b
prerequisite-patch-id: 3fa159f2b6ccd0ac51a2662e4eec5587ec18de89
prerequisite-patch-id: bfb4e4ffe9631cb58015fefe6bd3698cd53e2244
prerequisite-patch-id: 56ff6667a57a962264c07c0227c61aa2f1f4c22c
prerequisite-patch-id: bc506323e29944ec0c29eae84950c706a8592042
prerequisite-patch-id: 326c0ebb5accf0f40cbee1323fb4c3378f5be154
prerequisite-patch-id: d6eaf7690a54a0dfda7500936a048b769fa265dd
prerequisite-patch-id: 7c7b2535642b4d388e13eab518cbe0f9550eb1e6
prerequisite-patch-id: 0474af12959624910718795bf86684383664c685
prerequisite-patch-id: f6d4191e23c22e2d2cc90cc5d04781f913e98a8e
prerequisite-patch-id: b0031a7c4855b7ec38259c59f30f65101a8fc4b5
prerequisite-patch-id: 0b7f226abf2b9ff41873a1aa55cf97747647d56b
prerequisite-patch-id: f63e345f897619af54813958046617c655fb7daf
prerequisite-patch-id: c0e21e762a2960e3324c5ab04634a7035e515fa6
prerequisite-patch-id: fd59c71eadd8f39c58b3baea93567bc093bc9b0e
prerequisite-patch-id: 5d52cc8a5c73e4c5ba16b8e24f51408c17583bf9
prerequisite-patch-id: 1f9179284e2f3314d4b46ac5e989089a21c7576c
prerequisite-patch-id: 10397bbf696bee16dc71eb79fff6c5e73842bcbc
prerequisite-patch-id: 9b44279dcf08912238d2f6438a3328a778a79a0c
prerequisite-patch-id: 16854b621a3a71dfc365aaf7abaa7f65adfe9f7e
prerequisite-patch-id: ca42eea21fae1fd1cd3518ab057c74b61ffd68fe
prerequisite-patch-id: 23255dc2be76b0479c083dbd4c897bfbb533aed5
prerequisite-patch-id: 82129c687ebf0a41b369893b92f2c038420ab801
prerequisite-patch-id: 56ad57a99a5bda075a9f4e844368974296744934
prerequisite-patch-id: 288b3cbaa11e01a778cc3d7beb6c0549aacf59f2
prerequisite-patch-id: a163b1549608652bfa5bd9ff93efa55b541010c4
prerequisite-patch-id: 43b92dfc1a98fbf0d14597a3e3ae99972844773b
prerequisite-patch-id: 19c12bc6e3fbed35acc1f657196b1a997f48cdfe
prerequisite-patch-id: 5800c3076694bad719954b2ad4d7448c6e013bfd
prerequisite-patch-id: 2a2f63d8843b159594b9eee6ddea028ce76a6270
prerequisite-patch-id: 40a1951d57906c4a1b98a4bd96a814b80339b9c5
prerequisite-patch-id: e2141077e69f20a2b27fab69c8d61d0686682f53
prerequisite-patch-id: c4d6018c26c40dc549d88330d23ce48f872c2b7f
prerequisite-patch-id: 6de8ec17746031bc6d1d9ac262c5be0f905fcd79
prerequisite-patch-id: b87bcb167884605bff1fd0f2ed8a88942d07efd5
prerequisite-patch-id: cfa9a8b4c67e20cfd22d77035bfd21ee96ab3298
prerequisite-patch-id: abf3482ed2399b7b2e1ee72e937af05bb9200667
prerequisite-patch-id: 02c175b2dee565a85b3308ecf2ec8e3c9a029e0f
prerequisite-patch-id: d58c239fba616b366a725de6acba3f88734156d0
prerequisite-patch-id: dbe02fe3f784776fda5e7ae99f077bef0cd4b48d
prerequisite-patch-id: 53edc9a95afff57c4acba40095a8054924261ea2
prerequisite-patch-id: 5348d8957eb7eae7430ca8b101aa84ce77d3aa4f
prerequisite-patch-id: 36c96d781e2dd80b20932667bbe6e7fd14976069
prerequisite-patch-id: efeb2d6f7df71d5dede2c1d12fe999a28e38aab9
prerequisite-patch-id: 17f95c7fdf0bdc7c8aaaf7883bff1dcc19a0f529

author maintainer
#114 lore raw

PATCH RESEND v2 1/23 proc: drop the compat file operations

procfs has both sets of file operations twice, with and without ->compat_ioctl(), and picks the one with it for entries that have ->proc_compat_ioctl(). That's from commit 778f3dd5a13c ("Fix procfs compat_ioctl regression") when a file without ->compat_ioctl() went through the translation tables in fs/compat_ioctl.c and one with it didn't. Those tables are gone since commit 77b9040195de ("compat_ioctl:
simplify the implementation"). compat_sys_ioctl() answers -ENOTTY for a file without ->compat_ioctl() now, which is what proc_reg_compat_ioctl() answers for an entry without ->proc_compat_ioctl().

So always set ->compat_ioctl() and drop the second set of file operations and the flag that picked it.

No functional changes.

---
 fs/proc/generic.c       |  4 ----
 fs/proc/inode.c         | 45 +++------------------------------------------
 fs/proc/internal.h      |  9 ---------
 include/linux/proc_fs.h |  1 -
 4 files changed, 3 insertions(+), 56 deletions(-)
fs/proc/generic.c +0 -4
index 9a0a2fcac7c7..e7264f0cf5ab 100644
@@ -446,10 +446,6 @@ static void pde_set_flags(struct proc_dir_entry *pde)
 		pde->flags |= PROC_ENTRY_PERMANENT;
 	if (proc_ops->proc_read_iter)
 		pde->flags |= PROC_ENTRY_proc_read_iter;
-#ifdef CONFIG_COMPAT
-	if (proc_ops->proc_compat_ioctl)
-		pde->flags |= PROC_ENTRY_proc_compat_ioctl;
-#endif
 	if (proc_ops->proc_lseek)
 		pde->flags |= PROC_ENTRY_proc_lseek;
 }
fs/proc/inode.c +3 -42

75 lines not on this page · raw message

fs/proc/internal.h +0 -9
index 04f7ce2b24ed..268a0523be12 100644
@@ -92,15 +92,6 @@ static inline bool pde_has_proc_read_iter(const struct proc_dir_entry *pde)
 	return pde->flags & PROC_ENTRY_proc_read_iter;
 }
 
-static inline bool pde_has_proc_compat_ioctl(const struct proc_dir_entry *pde)
-{
-#ifdef CONFIG_COMPAT
-	return pde->flags & PROC_ENTRY_proc_compat_ioctl;
-#else
-	return false;
-#endif
-}
-
 static inline bool pde_has_proc_lseek(const struct proc_dir_entry *pde)
 {
 	return pde->flags & PROC_ENTRY_proc_lseek;
include/linux/proc_fs.h +0 -1
index 47d7deaeed8f..6ad5150020bf 100644
@@ -26,7 +26,6 @@ enum {
 #endif
 
 	PROC_ENTRY_proc_read_iter	= 1U << 1,
-	PROC_ENTRY_proc_compat_ioctl	= 1U << 2,
 	PROC_ENTRY_proc_lseek		= 1U << 3,
 
 	PROC_ENTRY_FORCE_LOOKUP		= 1U << 7,
Signature · 1 line
2.53.0
#115 lore raw

Re: [PATCH RESEND v2 01/23] proc: drop the compat file operations

Sashiko has reviewed this patch and found no issues.
Quoted 11 lines

procfs has both sets of file operations twice, with and without ->compat_ioctl(), and picks the one with it for entries that have ->proc_compat_ioctl(). That's from commit 778f3dd5a13c ("Fix procfs compat_ioctl regression") when a file without ->compat_ioctl() went through the translation tables in fs/compat_ioctl.c and one with it didn't. Those tables are gone since commit 77b9040195de ("compat_ioctl:
simplify the implementation"). compat_sys_ioctl() answers -ENOTTY for a file without ->compat_ioctl() now, which is what proc_reg_compat_ioctl() answers for an entry without ->proc_compat_ioctl().

Quoted 6 lines

So always set ->compat_ioctl() and drop the second set of file operations and the flag that picked it.

No functional changes.

Sashiko has reviewed this patch and found no issues.

Signature · 1 line
Sashiko AI review · https://sashiko.dev/#/patchset/[email protected]?part=1
author maintainer
#116 lore raw

PATCH RESEND v2 2/23 proc: add pde_pin() and pde_unpin()

In reply to Christian Brauner

Every call into an entry that can go away is wrapped in use_pde() and unuse_pde(), and a permanent entry is called straight away. The read, write, poll, ioctl, mmap and lseek methods all spell that out as the same if-else. The next patches add a few more callers. So put it into pde_pin() and pde_unpin() and use them everywhere.

No functional changes.

---
 fs/proc/inode.c | 116 +++++++++++++++++++++++++++-----------------------------
 1 file changed, 55 insertions(+), 61 deletions(-)
fs/proc/inode.c +55 -61
index 18f6490bfe77..66a3688757dd 100644
@@ -206,6 +206,18 @@ static void unuse_pde(struct proc_dir_entry *pde)
 		complete(pde->pde_unload_completion);
 }
 
+/* Pin an entry that can go away around a call into it, see use_pde(). */
+static bool pde_pin(struct proc_dir_entry *pde)
+{
+	return pde_is_permanent(pde) || use_pde(pde);
+}
+
+static void pde_unpin(struct proc_dir_entry *pde)
+{
+	if (!pde_is_permanent(pde))
+		unuse_pde(pde);
+}
+
 /*
  * At most 2 contexts can enter this function: the one doing the last
  * close on the descriptor and whoever is deleting PDE itself.
@@ -275,14 +287,12 @@ void proc_entry_rundown(struct proc_dir_entry *de)
 static loff_t proc_reg_llseek(struct file *file, loff_t offset, int whence)
 {
 	struct proc_dir_entry *pde = PDE(file_inode(file));
-	loff_t rv = -EINVAL;
+	loff_t rv;
 
-	if (pde_is_permanent(pde)) {
-		return pde->proc_ops->proc_lseek(file, offset, whence);
-	} else if (use_pde(pde)) {
-		rv = pde->proc_ops->proc_lseek(file, offset, whence);
-		unuse_pde(pde);
-	}
+	if (!pde_pin(pde))
+		return -EINVAL;
+	rv = pde->proc_ops->proc_lseek(file, offset, whence);
+	pde_unpin(pde);
 	return rv;
 }
 
@@ -291,13 +301,10 @@ static ssize_t proc_reg_read_iter(struct kiocb *iocb, struct iov_iter *iter)
 	struct proc_dir_entry *pde = PDE(file_inode(iocb->ki_filp));
 	ssize_t ret;
 
-	if (pde_is_permanent(pde))
-		return pde->proc_ops->proc_read_iter(iocb, iter);
-
-	if (!use_pde(pde))
+	if (!pde_pin(pde))
 		return -EIO;
 	ret = pde->proc_ops->proc_read_iter(iocb, iter);
-	unuse_pde(pde);
+	pde_unpin(pde);
 	return ret;
 }
 
@@ -312,14 +319,12 @@ static ssize_t pde_read(struct proc_dir_entry *pde, struct file *file, char __us
 static ssize_t proc_reg_read(struct file *file, char __user *buf, size_t count, loff_t *ppos)
 {
 	struct proc_dir_entry *pde = PDE(file_inode(file));
-	ssize_t rv = -EIO;
+	ssize_t rv;
 
-	if (pde_is_permanent(pde)) {
-		return pde_read(pde, file, buf, count, ppos);
-	} else if (use_pde(pde)) {
-		rv = pde_read(pde, file, buf, count, ppos);
-		unuse_pde(pde);
-	}
+	if (!pde_pin(pde))
+		return -EIO;
+	rv = pde_read(pde, file, buf, count, ppos);
+	pde_unpin(pde);
 	return rv;
 }
 
@@ -334,14 +339,12 @@ static ssize_t pde_write(struct proc_dir_entry *pde, struct file *file, const ch
 static ssize_t proc_reg_write(struct file *file, const char __user *buf, size_t count, loff_t *ppos)
 {
 	struct proc_dir_entry *pde = PDE(file_inode(file));
-	ssize_t rv = -EIO;
+	ssize_t rv;
 
-	if (pde_is_permanent(pde)) {
-		return pde_write(pde, file, buf, count, ppos);
-	} else if (use_pde(pde)) {
-		rv = pde_write(pde, file, buf, count, ppos);
-		unuse_pde(pde);
-	}
+	if (!pde_pin(pde))
+		return -EIO;
+	rv = pde_write(pde, file, buf, count, ppos);
+	pde_unpin(pde);
 	return rv;
 }
 
@@ -356,14 +359,12 @@ static __poll_t pde_poll(struct proc_dir_entry *pde, struct file *file, struct p
 static __poll_t proc_reg_poll(struct file *file, struct poll_table_struct *pts)
 {
 	struct proc_dir_entry *pde = PDE(file_inode(file));
-	__poll_t rv = DEFAULT_POLLMASK;
+	__poll_t rv;
 
-	if (pde_is_permanent(pde)) {
-		return pde_poll(pde, file, pts);
-	} else if (use_pde(pde)) {
-		rv = pde_poll(pde, file, pts);
-		unuse_pde(pde);
-	}
+	if (!pde_pin(pde))
+		return DEFAULT_POLLMASK;
+	rv = pde_poll(pde, file, pts);
+	pde_unpin(pde);
 	return rv;
 }
 
@@ -378,14 +379,12 @@ static long pde_ioctl(struct proc_dir_entry *pde, struct file *file, unsigned in
 static long proc_reg_unlocked_ioctl(struct file *file, unsigned int cmd, unsigned long arg)
 {
 	struct proc_dir_entry *pde = PDE(file_inode(file));
-	long rv = -ENOTTY;
+	long rv;
 
-	if (pde_is_permanent(pde)) {
-		return pde_ioctl(pde, file, cmd, arg);
-	} else if (use_pde(pde)) {
-		rv = pde_ioctl(pde, file, cmd, arg);
-		unuse_pde(pde);
-	}
+	if (!pde_pin(pde))
+		return -ENOTTY;
+	rv = pde_ioctl(pde, file, cmd, arg);
+	pde_unpin(pde);
 	return rv;
 }
 
@@ -401,13 +400,12 @@ static long pde_compat_ioctl(struct proc_dir_entry *pde, struct file *file, unsi
 static long proc_reg_compat_ioctl(struct file *file, unsigned int cmd, unsigned long arg)
 {
 	struct proc_dir_entry *pde = PDE(file_inode(file));
-	long rv = -ENOTTY;
-	if (pde_is_permanent(pde)) {
-		return pde_compat_ioctl(pde, file, cmd, arg);
-	} else if (use_pde(pde)) {
-		rv = pde_compat_ioctl(pde, file, cmd, arg);
-		unuse_pde(pde);
-	}
+	long rv;
+
+	if (!pde_pin(pde))
+		return -ENOTTY;
+	rv = pde_compat_ioctl(pde, file, cmd, arg);
+	pde_unpin(pde);
 	return rv;
 }
 #else
@@ -425,14 +423,12 @@ static int pde_mmap(struct proc_dir_entry *pde, struct file *file, struct vm_are
 static int proc_reg_mmap(struct file *file, struct vm_area_struct *vma)
 {
 	struct proc_dir_entry *pde = PDE(file_inode(file));
-	int rv = -EIO;
+	int rv;
 
-	if (pde_is_permanent(pde)) {
-		return pde_mmap(pde, file, vma);
-	} else if (use_pde(pde)) {
-		rv = pde_mmap(pde, file, vma);
-		unuse_pde(pde);
-	}
+	if (!pde_pin(pde))
+		return -EIO;
+	rv = pde_mmap(pde, file, vma);
+	pde_unpin(pde);
 	return rv;
 }
 
@@ -457,14 +453,12 @@ proc_reg_get_unmapped_area(struct file *file, unsigned long orig_addr,
 			   unsigned long flags)
 {
 	struct proc_dir_entry *pde = PDE(file_inode(file));
-	unsigned long rv = -EIO;
+	unsigned long rv;
 
-	if (pde_is_permanent(pde)) {
-		return pde_get_unmapped_area(pde, file, orig_addr, len, pgoff, flags);
-	} else if (use_pde(pde)) {
-		rv = pde_get_unmapped_area(pde, file, orig_addr, len, pgoff, flags);
-		unuse_pde(pde);
-	}
+	if (!pde_pin(pde))
+		return -EIO;
+	rv = pde_get_unmapped_area(pde, file, orig_addr, len, pgoff, flags);
+	pde_unpin(pde);
 	return rv;
 }
 
Signature · 1 line
2.53.0
#117 lore raw

Re: [PATCH RESEND v2 02/23] proc: add pde_pin() and pde_unpin()

Sashiko has reviewed this patch and found no issues.
Quoted 9 lines

Every call into an entry that can go away is wrapped in use_pde() and unuse_pde(), and a permanent entry is called straight away. The read, write, poll, ioctl, mmap and lseek methods all spell that out as the same if-else. The next patches add a few more callers. So put it into pde_pin() and pde_unpin() and use them everywhere.

No functional changes.

Sashiko has reviewed this patch and found no issues.

Signature · 1 line
Sashiko AI review · https://sashiko.dev/#/patchset/[email protected]?part=2
author maintainer
#118 lore raw

PATCH RESEND v2 3/23 proc: share the readdir cursor with sysctl

In reply to Christian Brauner

proc_readdir_de() and proc_sys_readdir() both resume a listing after the last entry it emitted and each remembers that entry in the open file with a cursor of its own: the same struct, the same way of setting it, the same release. Keep one in generic.c and let sysctl use it.

No functional changes.

---
 fs/proc/generic.c     | 29 ++++++++++++-----------------
 fs/proc/internal.h    | 25 +++++++++++++++++++++++++
 fs/proc/proc_sysctl.c | 45 +++++----------------------------------------
 3 files changed, 42 insertions(+), 57 deletions(-)
fs/proc/generic.c +12 -17
index e7264f0cf5ab..f6d620a5c3d2 100644
@@ -301,22 +301,16 @@ struct dentry *proc_lookup(struct inode *dir, struct dentry *dentry,
 }
 
 /*
- * Where the next readdir resumes. The entries are counted, so one that is
- * added or removed in front of the position would shift what the next call
- * returns. The name of the last entry emitted doesn't move.
+ * Remember @name as the entry the listing is behind at @pos. If this can't
+ * the next call counts from the start.
  */
-struct proc_dir_cursor {
-	loff_t pos;			/* the position behind the entry */
-	unsigned int len;
-	char name[NAME_MAX + 1];
-};
-
-/* If this can't remember the entry the next call counts from the start. */
-static void proc_dir_cursor_set(struct file *file, struct proc_dir_entry *de,
-				loff_t pos)
+void proc_dir_cursor_set(struct file *file, const char *name, unsigned int len,
+			 loff_t pos)
 {
 	struct proc_dir_cursor *cursor = file->private_data;
 
+	if (len > NAME_MAX)
+		return;
 	if (!cursor) {
 		cursor = kmalloc(sizeof(*cursor), GFP_KERNEL);
 		if (!cursor)
@@ -324,8 +318,8 @@ static void proc_dir_cursor_set(struct file *file, struct proc_dir_entry *de,
 		file->private_data = cursor;
 	}
 	cursor->pos = pos;
-	cursor->len = de->namelen;
-	memcpy(cursor->name, de->name, de->namelen);
+	cursor->len = len;
+	memcpy(cursor->name, name, len);
 }
 
 int proc_dir_release(struct inode *inode, struct file *file)
@@ -346,7 +340,7 @@ int proc_dir_release(struct inode *inode, struct file *file)
 int proc_readdir_de(struct file *file, struct dir_context *ctx,
 		    struct proc_dir_entry *de)
 {
-	struct proc_dir_cursor *cursor = file->private_data;
+	const struct proc_dir_cursor *cursor;
 	struct proc_dir_entry *dir = de;
 	int i;
 
@@ -354,7 +348,8 @@ int proc_readdir_de(struct file *file, struct dir_context *ctx,
 		return 0;
 
 	read_lock(&proc_subdir_lock);
-	if (cursor && cursor->pos == ctx->pos) {
+	cursor = proc_dir_cursor_at(file, ctx->pos);
+	if (cursor) {
 		/* Resume after the last entry emitted, wherever it is now. */
 		de = pde_subdir_after(dir, cursor->name, cursor->len);
 	} else {
@@ -378,7 +373,7 @@ int proc_readdir_de(struct file *file, struct dir_context *ctx,
 			return 0;
 		}
 		ctx->pos++;
-		proc_dir_cursor_set(file, de, ctx->pos);
+		proc_dir_cursor_set(file, de->name, de->namelen, ctx->pos);
 		read_lock(&proc_subdir_lock);
 		/* Removed in the meantime, go on after its name. */
 		if (RB_EMPTY_NODE(&de->subdir_node))
fs/proc/internal.h +25 -0
index 268a0523be12..6b61d09ac5e5 100644
@@ -278,6 +278,31 @@ extern struct dentry *proc_lookup(struct inode *, struct dentry *, unsigned int)
 struct dentry *proc_lookup_de(struct inode *, struct dentry *, struct proc_dir_entry *);
 extern int proc_readdir(struct file *, struct dir_context *);
 int proc_readdir_de(struct file *, struct dir_context *, struct proc_dir_entry *);
+
+/*
+ * Where the next readdir resumes. The entries are counted, so one that is
+ * added or removed in front of the position would shift what the next call
+ * returns. The name of the last entry emitted doesn't move. The directory's
+ * file keeps it, see proc_dir_release().
+ */
+struct proc_dir_cursor {
+	loff_t pos;			/* the position behind the entry */
+	unsigned int len;
+	char name[NAME_MAX + 1];
+};
+
+/* The entry to resume after, if the position is still the one behind it. */
+static inline const struct proc_dir_cursor *
+proc_dir_cursor_at(struct file *file, loff_t pos)
+{
+	const struct proc_dir_cursor *cursor = file->private_data;
+
+	if (cursor && cursor->pos == pos)
+		return cursor;
+	return NULL;
+}
+void proc_dir_cursor_set(struct file *file, const char *name, unsigned int len,
+			 loff_t pos);
 int proc_dir_release(struct inode *, struct file *);
 
 static inline void pde_get(struct proc_dir_entry *pde)
fs/proc/proc_sysctl.c +5 -40

81 lines not on this page · raw message

Signature · 1 line
2.53.0
#119 lore raw

Re: [PATCH RESEND v2 03/23] proc: share the readdir cursor with sysctl

Sashiko has reviewed this patch and found no issues.
Quoted 9 lines

proc_readdir_de() and proc_sys_readdir() both resume a listing after the last entry it emitted and each remembers that entry in the open file with a cursor of its own: the same struct, the same way of setting it, the same release. Keep one in generic.c and let sysctl use it.

No functional changes.

Sashiko has reviewed this patch and found no issues.

Signature · 1 line
Sashiko AI review · https://sashiko.dev/#/patchset/[email protected]?part=3
author maintainer
#120 lore raw

PATCH RESEND v2 4/23 proc: wait for the last user of an entry with wait_var_event()

In reply to Christian Brauner

proc_entry_rundown() waits for the last user of an entry with a completion on its stack that it points the entry at while it waits. That's a pointer in every struct proc_dir_entry for something that happens once in the life of an entry, if at all.

Wait on the count itself with wait_var_event() instead and let unuse_pde() wake the waiter with wake_up_var() when the count hits the bias. The waiters sleep on the hashed wait queues behind that, so procfs doesn't need a wait queue of its own for this, neither in the entry nor a global one. kernfs keeps one per root for the same thing, deactivate_waitq. Note that atomic_dec_return() is fully ordered, so the count is visible before wake_up_var() looks for waiters.

No functional changes.

---
 fs/proc/inode.c    | 7 +++----
 fs/proc/internal.h | 1 -
 2 files changed, 3 insertions(+), 5 deletions(-)
fs/proc/inode.c +3 -4
index 66a3688757dd..8795add1898d 100644
@@ -25,6 +25,7 @@
 #include <linux/slab.h>
 #include <linux/mount.h>
 #include <linux/bug.h>
+#include <linux/wait_bit.h>
 
 #include "internal.h"
 
@@ -203,7 +204,7 @@ static inline int use_pde(struct proc_dir_entry *pde)
 static void unuse_pde(struct proc_dir_entry *pde)
 {
 	if (unlikely(atomic_dec_return(&pde->in_use) == BIAS))
-		complete(pde->pde_unload_completion);
+		wake_up_var(&pde->in_use);
 }
 
 /* Pin an entry that can go away around a call into it, see use_pde(). */
@@ -266,11 +267,9 @@ static void close_pdeo(struct proc_dir_entry *pde, struct pde_opener *pdeo)
 
 void proc_entry_rundown(struct proc_dir_entry *de)
 {
-	DECLARE_COMPLETION_ONSTACK(c);
 	/* Wait until all existing callers into module are done. */
-	de->pde_unload_completion = &c;
 	if (atomic_add_return(BIAS, &de->in_use) != BIAS)
-		wait_for_completion(&c);
+		wait_var_event(&de->in_use, atomic_read(&de->in_use) == BIAS);
 
 	/* ->pde_openers list can't grow from now on. */
 
fs/proc/internal.h +0 -1
index 6b61d09ac5e5..ab4d7bd1fb75 100644
@@ -38,7 +38,6 @@ struct proc_dir_entry {
 	struct list_head pde_openers;	/* who did ->open, but not ->release */
 	/* protects ->pde_openers and all struct pde_opener instances */
 	spinlock_t pde_unload_lock;
-	struct completion *pde_unload_completion;
 	const struct inode_operations *proc_iops;
 	union {
 		const struct proc_ops *proc_ops;
Signature · 1 line
2.53.0
#121 lore raw

Re: [PATCH RESEND v2 04/23] proc: wait for the last user of an entry with wait_var_event()

Thank you for your contribution! Sashiko AI review found 1 potential issue(s) to consider: - [Medium] proc: missing acquire ordering in proc_entry_rundown() wait_var_event() --

Thank you for your contribution! Sashiko AI review found 1 potential issue(s) to consider:
- [Medium] proc: missing acquire ordering in proc_entry_rundown() wait_var_event() --

commit 983e734e20cf0803ce3936df6614c8375020b212
Author: Christian Brauner <[email protected]>

proc: wait for the last user of an entry with wait_var_event()

This commit replaces the per-entry pde_unload_completion pointer in struct proc_dir_entry with wait_var_event() and wake_up_var() on pde->in_use during proc_entry_rundown().

Quoted 4 lines
fs/proc/inode.c +0 -0
index 66a3688757dd7..8795add1898dc 100644

[ ... ]

fs/proc/inode.c static void close_pdeo(struct proc_dir_entry *pde, struct pde_opener *pdeo) · line 272

Quoted 10 lines
fs/proc/inode.c +1 -3
@@ -266,11 +267,9 @@ static void close_pdeo(struct proc_dir_entry *pde, struct pde_opener *pdeo)
 
 void proc_entry_rundown(struct proc_dir_entry *de)
 {
-	DECLARE_COMPLETION_ONSTACK(c);
 	/* Wait until all existing callers into module are done. */
-	de->pde_unload_completion = &c;
 	if (atomic_add_return(BIAS, &de->in_use) != BIAS)
-		wait_for_completion(&c);
+		wait_var_event(&de->in_use, atomic_read(&de->in_use) == BIAS);

[Severity: Medium]
Should the condition in wait_var_event() use atomic_read_acquire(&de->in_use) instead of atomic_read(&de->in_use)?

When remove_proc_entry(), remove_proc_subtree(), or proc_remove() calls proc_entry_rundown(de) while another CPU is executing an in-flight proc callback, atomic_add_return(BIAS, &de->in_use) returns a value not equal to BIAS. If that callback finishes and executes atomic_dec_return(&pde->in_use) in unuse_pde() before proc_entry_rundown() evaluates the wait condition, wait_var_event() takes its initial fast path:

include/linux/wait_bit.h:
#define wait_var_event(var, condition) \

do {									\
	might_sleep();							\
	if (condition)							\
		break;							\
	__wait_var_event(var, condition);				\
} while (0)

Because atomic_read() is relaxed, breaking out on the initial check neither takes the waitqueue lock nor issues an acquire barrier. On weakly-ordered architectures, memory accesses performed after proc_entry_rundown() (such as freeing or reading private data after remove_proc_entry() returns, especially once the subsequent patch in this series skips pde_unload_lock when !de->open) could be reordered before memory accesses made by the proc callback prior to unuse_pde().

Previously, complete() and wait_for_completion() unconditionally provided release-acquire ordering via the completion waitqueue lock, and the documentation for wait_var_event() notes that the condition should use smp_load_acquire() or a similarly ordered access so memory changes made before the condition became true are visible after the wait completes.

Signature · 1 line
Sashiko AI review · https://sashiko.dev/#/patchset/[email protected]?part=4
author maintainer
#122 lore raw

PATCH RESEND v2 5/23 proc: keep the open files of an entry in an open node

In reply to Christian Brauner

procfs remembers the open files of an entry that has a ->proc_release(), so that it can call the release hook when the entry is removed while files are still open. The list head for that and the lock that protects it sit in every struct proc_dir_entry, for the few entries that need them, and the next patches want to keep more there, the vm_operations of an entry's mappings for a start.

Move the list into a struct pde_open_node that only those entries get. It is allocated when the entry is registered, whether an entry needs one follows from its proc_ops, and freed with the entry. So ->open is constant for the life of an entry, nothing has to look it up or pin it, and the removal path stays what it is. kernfs allocates its kernfs_open_node on the first open instead, but there every attribute can be polled and so every one of them would need one. In procfs the entries that need the node are the exception. Permanent entries don't get one, they are never removed, so their release hook only ever runs when a file is closed.

The spinlock stays in the entry and now protects what hangs off ->open. Moving it behind the gid fills a hole, so struct proc_dir_entry shrinks from 160 to 144 bytes on x86_64 here, and it ends up at 160 bytes at the end of this series instead of the 184 it would have grown to with the read and write limits and the vm_operations of its mappings in it. That keeps 32 bytes of inline name instead of 8. 34 of the 68 /proc/net names a network namespace gets are longer than 7 characters.

No functional changes.

---
 fs/proc/generic.c  | 20 +++++++++++++++++++-
 fs/proc/inode.c    | 23 +++++++++++++----------
 fs/proc/internal.h | 16 +++++++++++++---
 3 files changed, 45 insertions(+), 14 deletions(-)
fs/proc/generic.c +19 -1
index f6d620a5c3d2..84f064a651e4 100644
@@ -40,6 +40,7 @@ void pde_free(struct proc_dir_entry *pde)
 		kfree(pde->data);
 	if (pde->name != pde->inline_name)
 		kfree(pde->name);
+	kfree(pde->open);
 	kmem_cache_free(proc_dir_entry_cache, pde);
 }
 
@@ -445,6 +446,18 @@ static void pde_set_flags(struct proc_dir_entry *pde)
 		pde->flags |= PROC_ENTRY_proc_lseek;
 }
 
+/*
+ * procfs has to know the open files of an entry whose ->proc_release() it
+ * calls at removal. A permanent entry is never removed and skips all that,
+ * see proc_reg_open().
+ */
+static bool pde_needs_open_node(const struct proc_dir_entry *pde)
+{
+	if (!S_ISREG(pde->mode) || pde_is_permanent(pde))
+		return false;
+	return pde->proc_ops->proc_release;
+}
+
 /* returns the registered entry, or frees dp and returns NULL on failure */
 struct proc_dir_entry *proc_register(struct proc_dir_entry *dir,
 		struct proc_dir_entry *dp)
@@ -454,6 +467,12 @@ struct proc_dir_entry *proc_register(struct proc_dir_entry *dir,
 
 	if (!S_ISDIR(dp->mode))
 		pde_set_flags(dp);
+	if (pde_needs_open_node(dp)) {
+		dp->open = kzalloc(sizeof(*dp->open), GFP_KERNEL);
+		if (!dp->open)
+			goto out_free_inum;
+		INIT_LIST_HEAD(&dp->open->files);
+	}
 
 	write_lock(&proc_subdir_lock);
 	dp->parent = dir;
@@ -533,7 +552,6 @@ static struct proc_dir_entry *__proc_create(struct proc_dir_entry **parent,
 	ent->subdir = RB_ROOT;
 	refcount_set(&ent->refcnt, 1);
 	spin_lock_init(&ent->pde_unload_lock);
-	INIT_LIST_HEAD(&ent->pde_openers);
 	proc_set_user(ent, (*parent)->uid, (*parent)->gid);
 
 	/* Revalidate everything under /proc/${pid}/net */
fs/proc/inode.c +13 -10
index 8795add1898d..56eab69e1dcc 100644
@@ -271,12 +271,13 @@ void proc_entry_rundown(struct proc_dir_entry *de)
 	if (atomic_add_return(BIAS, &de->in_use) != BIAS)
 		wait_var_event(&de->in_use, atomic_read(&de->in_use) == BIAS);
 
-	/* ->pde_openers list can't grow from now on. */
-
+	/* ->open->files can't grow from now on. */
+	if (!de->open)
+		return;
 	spin_lock(&de->pde_unload_lock);
-	while (!list_empty(&de->pde_openers)) {
+	while (!list_empty(&de->open->files)) {
 		struct pde_opener *pdeo;
-		pdeo = list_first_entry(&de->pde_openers, struct pde_opener, lh);
+		pdeo = list_first_entry(&de->open->files, struct pde_opener, lh);
 		close_pdeo(de, pdeo);
 		spin_lock(&de->pde_unload_lock);
 	}
@@ -499,13 +500,13 @@ static int proc_reg_open(struct inode *inode, struct file *file)
 	 * 2) rmmod isn't blocked by opening file in /proc and sitting on
 	 *    the descriptor (including "rmmod foo </proc/foo" scenario).
 	 *
-	 * Save every "struct file" with custom ->release hook.
+	 * Save every "struct file" with custom ->release hook. Those entries
+	 * have an open node, see proc_register().
 	 */
 	if (!use_pde(pde))
 		return -ENOENT;
 
-	const auto release = pde->proc_ops->proc_release;
-	if (release) {
+	if (pde->open) {
 		pdeo = kmem_cache_alloc(pde_opener_cache, GFP_KERNEL);
 		if (!pdeo) {
 			rv = -ENOMEM;
@@ -517,14 +518,14 @@ static int proc_reg_open(struct inode *inode, struct file *file)
 	if (open)
 		rv = open(inode, file);
 
-	if (release) {
+	if (pde->open) {
 		if (rv == 0) {
 			/* To know what to release. */
 			pdeo->file = file;
 			pdeo->closing = false;
 			pdeo->c = NULL;
 			spin_lock(&pde->pde_unload_lock);
-			list_add(&pdeo->lh, &pde->pde_openers);
+			list_add(&pdeo->lh, &pde->open->files);
 			spin_unlock(&pde->pde_unload_lock);
 		} else
 			kmem_cache_free(pde_opener_cache, pdeo);
@@ -547,8 +548,10 @@ static int proc_reg_release(struct inode *inode, struct file *file)
 		return 0;
 	}
 
+	if (!pde->open)
+		return 0;
 	spin_lock(&pde->pde_unload_lock);
-	list_for_each_entry(pdeo, &pde->pde_openers, lh) {
+	list_for_each_entry(pdeo, &pde->open->files, lh) {
 		if (pdeo->file == file) {
 			close_pdeo(pde, pdeo);
 			return 0;
fs/proc/internal.h +13 -3
index ab4d7bd1fb75..33776bc00ff0 100644
@@ -35,9 +35,6 @@ struct proc_dir_entry {
 	 */
 	atomic_t in_use;
 	refcount_t refcnt;
-	struct list_head pde_openers;	/* who did ->open, but not ->release */
-	/* protects ->pde_openers and all struct pde_opener instances */
-	spinlock_t pde_unload_lock;
 	const struct inode_operations *proc_iops;
 	union {
 		const struct proc_ops *proc_ops;
@@ -47,6 +44,8 @@ struct proc_dir_entry {
 		const struct seq_operations *seq_ops;
 		int (*single_show)(struct seq_file *, void *);
 	};
+	/* the open files procfs has to know, see struct pde_open_node */
+	struct pde_open_node *open;
 	proc_write_t write;
 	void *data;
 	unsigned int state_size;
@@ -54,6 +53,8 @@ struct proc_dir_entry {
 	nlink_t nlink;
 	kuid_t uid;
 	kgid_t gid;
+	/* protects ->open->files and all struct pde_opener instances */
+	spinlock_t pde_unload_lock;
 	loff_t size;
 	struct proc_dir_entry *parent;
 	struct rb_root subdir;
@@ -325,6 +326,15 @@ struct pde_opener {
 	bool closing;
 	struct completion *c;
 } __randomize_layout;
+
+/*
+ * The open files of an entry whose ->proc_release() procfs has to call when
+ * the entry is removed while they are still open. Allocated with the entry,
+ * see proc_register().
+ */
+struct pde_open_node {
+	struct list_head files;		/* who did ->open, but not ->release */
+};
 extern const struct inode_operations proc_link_inode_operations;
 extern const struct inode_operations proc_pid_link_inode_operations;
 extern const struct super_operations proc_sops;
Signature · 1 line
2.53.0
#123 lore raw

Re: [PATCH RESEND v2 05/23] proc: keep the open files of an entry in an open node

Sashiko has reviewed this patch and found no issues.
Quoted 26 lines

procfs remembers the open files of an entry that has a ->proc_release(), so that it can call the release hook when the entry is removed while files are still open. The list head for that and the lock that protects it sit in every struct proc_dir_entry, for the few entries that need them, and the next patches want to keep more there, the vm_operations of an entry's mappings for a start.

Move the list into a struct pde_open_node that only those entries get. It is allocated when the entry is registered, whether an entry needs one follows from its proc_ops, and freed with the entry. So ->open is constant for the life of an entry, nothing has to look it up or pin it, and the removal path stays what it is. kernfs allocates its kernfs_open_node on the first open instead, but there every attribute can be polled and so every one of them would need one. In procfs the entries that need the node are the exception. Permanent entries don't get one, they are never removed, so their release hook only ever runs when a file is closed.

The spinlock stays in the entry and now protects what hangs off ->open. Moving it behind the gid fills a hole, so struct proc_dir_entry shrinks from 160 to 144 bytes on x86_64 here, and it ends up at 160 bytes at the end of this series instead of the 184 it would have grown to with the read and write limits and the vm_operations of its mappings in it. That keeps 32 bytes of inline name instead of 8. 34 of the 68 /proc/net names a network namespace gets are longer than 7 characters.

Quoted 3 lines

No functional changes.

Sashiko has reviewed this patch and found no issues.

Signature · 1 line
Sashiko AI review · https://sashiko.dev/#/patchset/[email protected]?part=5
author maintainer
#124 lore raw

PATCH RESEND v2 6/23 proc: make room for more entry flags

In reply to Christian Brauner

->flags of struct proc_dir_entry is a u8 and the next patches need more flags than it has room for, so make it a u16. Bit 6 stays free, vfs-7.5.mount takes it for PROC_ENTRY_CANT_MOUNT.

No functional changes.

---
 fs/proc/internal.h | 2 +-
 1 file changed, 1 insertion(+), 1 deletion(-)
fs/proc/internal.h +1 -1
index 33776bc00ff0..7dea0237f08b 100644
@@ -61,7 +61,7 @@ struct proc_dir_entry {
 	struct rb_node subdir_node;
 	char *name;
 	umode_t mode;
-	u8 flags;
+	u16 flags;
 	u8 namelen;
 	char inline_name[];
 } __randomize_layout;
Signature · 1 line
2.53.0
#125 lore raw

Re: [PATCH RESEND v2 06/23] proc: make room for more entry flags

Sashiko has reviewed this patch and found no issues.
Quoted 7 lines

->flags of struct proc_dir_entry is a u8 and the next patches need more flags than it has room for, so make it a u16. Bit 6 stays free, vfs-7.5.mount takes it for PROC_ENTRY_CANT_MOUNT.

No functional changes.

Sashiko has reviewed this patch and found no issues.

Signature · 1 line
Sashiko AI review · https://sashiko.dev/#/patchset/[email protected]?part=6
author maintainer
#126 lore raw

PATCH RESEND v2 7/23 proc: let procfs own the seq_file of seq_file entries

In reply to Christian Brauner

remove_proc_entry() waits until every call into the entry has returned. For a seq_file entry that's all of seq_read_iter(), including the copy to userspace. A page fault in that copy can be made to take as long as the reader wants, e.g. with userfaultfd or by punching holes into a memfd over and over. And callers of remove_proc_entry() like to hold locks while they wait. xt_hashlimit holds hashlimit_mutex, which all network namespaces share, and addrconf holds RTNL.

But the entry's code only runs between ->start() and ->stop() and the copies to userspace happen outside of that. So let procfs own the seq_file the way kernfs does. An entry declares its seq_operations, or just a show function, and the size of its private state in struct proc_ops. procfs then opens the seq_file with seq_operations it builds for the entry when it is registered: the entry's own ->next() and ->show() with a ->start() and ->stop() of procfs around them that pin the entry and unpin it again. Nothing of procfs runs between the records that way. procfs reads and seeks through seq_file directly. The copies to userspace happen with the entry unpinned.

That changes who owns the seq_file. remove_proc_entry() can now finish while a reader is still copying out of the buffer, so the seq_file can't go away with the entry. procfs frees it once the file is released. ->proc_open() finds the seq_file in ->private_data and sets up whatever the entry needs and ->proc_release() releases just that. It still runs when the entry is removed, or when the file is closed before that.

Since procfs reads these entries through seq_read_iter() itself they all have ->splice_read() now, so sendfile(), splice(), aio, the RWF flags and kernel_read() work on them, and readv() is one read instead of one per segment. Note that a removed entry still hands out what it had already formatted and then answers -EIO to reads, and to seeks that have to walk the records. Seeking it failed with -EINVAL right away before.

For an entry that only has a show function the seq_operations do what single_open() does, like kernfs_seq_start(). If the entry can't be pinned ->start() fails with -EIO and switches the seq_file to seq_operations whose ->stop() doesn't unpin, so the entry's own ->start() and ->next() can return any error they like. An entry that declares a seq_file and also a read or seek method of its own, or one that releases the seq_file with seq_release() itself, doesn't make sense, procfs reads, seeks and releases the seq_file itself, so registering it fails.

No users yet.

---
 fs/proc/generic.c       |  65 ++++++++++++++++++---
 fs/proc/inode.c         | 146 +++++++++++++++++++++++++++++++++++++++++++-----
 fs/proc/internal.h      |  21 +++++++
 include/linux/proc_fs.h |  22 +++++++-
 4 files changed, 231 insertions(+), 23 deletions(-)
fs/proc/generic.c +58 -7
index 84f064a651e4..59b89e251ba3 100644
@@ -41,6 +41,7 @@ void pde_free(struct proc_dir_entry *pde)
 	if (pde->name != pde->inline_name)
 		kfree(pde->name);
 	kfree(pde->open);
+	kfree(pde->seq_direct);
 	kmem_cache_free(proc_dir_entry_cache, pde);
 }
 
@@ -431,19 +432,41 @@ static const struct inode_operations proc_dir_inode_operations = {
 	.setattr	= proc_setattr,
 };
 
-static void pde_set_flags(struct proc_dir_entry *pde)
+static int pde_set_flags(struct proc_dir_entry *pde)
 {
 	const struct proc_ops *proc_ops = pde->proc_ops;
 
 	if (!proc_ops)
-		return;
+		return 0;
 
 	if (proc_ops->proc_flags & PROC_ENTRY_PERMANENT)
 		pde->flags |= PROC_ENTRY_PERMANENT;
-	if (proc_ops->proc_read_iter)
-		pde->flags |= PROC_ENTRY_proc_read_iter;
-	if (proc_ops->proc_lseek)
+	if (proc_ops->proc_seq_ops) {
+		pde->seq_ops = proc_ops->proc_seq_ops;
+		pde->state_size = proc_ops->proc_state_size;
+		pde->flags |= PROC_ENTRY_proc_seq_ops;
+	} else if (proc_ops->proc_show) {
+		pde->single_show = proc_ops->proc_show;
+		pde->flags |= PROC_ENTRY_proc_show;
+	}
+	if (pde_is_seq_file(pde)) {
+		/* procfs reads and seeks through the seq_file itself */
+		if (WARN_ON_ONCE(proc_ops->proc_read || proc_ops->proc_read_iter ||
+				 proc_ops->proc_lseek))
+			return -EINVAL;
+		/* and frees it, see pde_seq_release() */
+		if (WARN_ON_ONCE(proc_ops->proc_release == seq_release ||
+				 proc_ops->proc_release == seq_release_private ||
+				 proc_ops->proc_release == single_release))
+			return -EINVAL;
 		pde->flags |= PROC_ENTRY_proc_lseek;
+	} else {
+		if (proc_ops->proc_read_iter)
+			pde->flags |= PROC_ENTRY_proc_read_iter;
+		if (proc_ops->proc_lseek)
+			pde->flags |= PROC_ENTRY_proc_lseek;
+	}
+	return 0;
 }
 
 /*
@@ -458,6 +481,32 @@ static bool pde_needs_open_node(const struct proc_dir_entry *pde)
 	return pde->proc_ops->proc_release;
 }
 
+/*
+ * The seq_operations of a seq_file entry: procfs's start and stop around the
+ * entry's own next and show, see pde_seq_start().
+ */
+static int pde_init_seq_direct(struct proc_dir_entry *pde)
+{
+	struct seq_operations *ops;
+
+	if (!pde_is_seq_file(pde))
+		return 0;
+	ops = kmalloc(sizeof(*ops), GFP_KERNEL);
+	if (!ops)
+		return -ENOMEM;
+	ops->start = pde_seq_start;
+	ops->stop = pde_seq_stop;
+	if (pde_has_proc_seq_ops(pde)) {
+		ops->next = pde->seq_ops->next;
+		ops->show = pde->seq_ops->show;
+	} else {
+		ops->next = pde_single_next;
+		ops->show = pde->single_show;
+	}
+	pde->seq_direct = ops;
+	return 0;
+}
+
 /* returns the registered entry, or frees dp and returns NULL on failure */
 struct proc_dir_entry *proc_register(struct proc_dir_entry *dir,
 		struct proc_dir_entry *dp)
@@ -465,14 +514,16 @@ struct proc_dir_entry *proc_register(struct proc_dir_entry *dir,
 	if (proc_alloc_inum(&dp->low_ino))
 		goto out_free_entry;
 
-	if (!S_ISDIR(dp->mode))
-		pde_set_flags(dp);
+	if (!S_ISDIR(dp->mode) && pde_set_flags(dp))
+		goto out_free_inum;
 	if (pde_needs_open_node(dp)) {
 		dp->open = kzalloc(sizeof(*dp->open), GFP_KERNEL);
 		if (!dp->open)
 			goto out_free_inum;
 		INIT_LIST_HEAD(&dp->open->files);
 	}
+	if (pde_init_seq_direct(dp))
+		goto out_free_inum;
 
 	write_lock(&proc_subdir_lock);
 	dp->parent = dir;
fs/proc/inode.c +131 -15

198 lines not on this page · raw message

fs/proc/internal.h +21 -0
index 7dea0237f08b..674e6b4ed21e 100644
@@ -46,6 +46,8 @@ struct proc_dir_entry {
 	};
 	/* the open files procfs has to know, see struct pde_open_node */
 	struct pde_open_node *open;
+	/* the seq_operations of the seq_file, see pde_init_seq_direct() */
+	struct seq_operations *seq_direct;
 	proc_write_t write;
 	void *data;
 	unsigned int state_size;
@@ -97,6 +99,22 @@ static inline bool pde_has_proc_lseek(const struct proc_dir_entry *pde)
 	return pde->flags & PROC_ENTRY_proc_lseek;
 }
 
+static inline bool pde_has_proc_seq_ops(const struct proc_dir_entry *pde)
+{
+	return pde->flags & PROC_ENTRY_proc_seq_ops;
+}
+
+static inline bool pde_has_proc_show(const struct proc_dir_entry *pde)
+{
+	return pde->flags & PROC_ENTRY_proc_show;
+}
+
+/* procfs owns the seq_file, see pde_seq_start() */
+static inline bool pde_is_seq_file(const struct proc_dir_entry *pde)
+{
+	return pde_has_proc_seq_ops(pde) || pde_has_proc_show(pde);
+}
+
 extern struct kmem_cache *proc_dir_entry_cache;
 void pde_free(struct proc_dir_entry *pde);
 
@@ -343,6 +361,9 @@ void proc_init_kmemcache(void);
 void proc_invalidate_siblings_dcache(struct hlist_head *inodes, spinlock_t *lock);
 void set_proc_pid_nlink(void);
 extern struct inode *proc_get_inode(struct super_block *, struct proc_dir_entry *);
+void *pde_seq_start(struct seq_file *m, loff_t *pos);
+void pde_seq_stop(struct seq_file *m, void *v);
+void *pde_single_next(struct seq_file *m, void *v, loff_t *pos);
 extern void proc_entry_rundown(struct proc_dir_entry *);
 
 /*
include/linux/proc_fs.h +21 -1
index 6ad5150020bf..ea55ed85a2d6 100644
@@ -27,6 +27,8 @@ enum {
 
 	PROC_ENTRY_proc_read_iter	= 1U << 1,
 	PROC_ENTRY_proc_lseek		= 1U << 3,
+	PROC_ENTRY_proc_seq_ops		= 1U << 4,
+	PROC_ENTRY_proc_show		= 1U << 5,
 
 	PROC_ENTRY_FORCE_LOOKUP		= 1U << 7,
 };
@@ -37,7 +39,10 @@ struct proc_ops {
 	ssize_t	(*proc_read)(struct file *, char __user *, size_t, loff_t *);
 	ssize_t (*proc_read_iter)(struct kiocb *, struct iov_iter *);
 	ssize_t	(*proc_write)(struct file *, const char __user *, size_t, loff_t *);
-	/* mandatory unless nonseekable_open() or equivalent is used */
+	/*
+	 * mandatory unless nonseekable_open() or equivalent is used, procfs
+	 * seeks seq_file entries itself
+	 */
 	loff_t	(*proc_lseek)(struct file *, loff_t, int);
 	int	(*proc_release)(struct inode *, struct file *);
 	__poll_t (*proc_poll)(struct file *, struct poll_table_struct *);
@@ -47,6 +52,21 @@ struct proc_ops {
 #endif
 	int	(*proc_mmap)(struct file *, struct vm_area_struct *);
 	unsigned long (*proc_get_unmapped_area)(struct file *, unsigned long, unsigned long, unsigned long, unsigned long);
+	/*
+	 * For seq_file entries procfs opens the seq_file, reads and seeks
+	 * through it and frees it once the file is released. ->proc_open()
+	 * finds the seq_file in ->private_data and ->proc_release() only
+	 * releases what ->proc_open() set up. It can run while a reader still
+	 * copies out of the seq_file, so it must leave that alone. procfs
+	 * allocates ->proc_state_size bytes of ->private state for
+	 * ->proc_seq_ops and points ->private at the entry's data for
+	 * ->proc_show(). Nothing that runs with the entry pinned may wait for
+	 * something a copy to or from userspace can hold, like the seq_file's
+	 * lock.
+	 */
+	const struct seq_operations *proc_seq_ops;
+	int	(*proc_show)(struct seq_file *, void *);
+	unsigned int proc_state_size;
 } __randomize_layout;
 
 /* definitions for hide_pid field */
Signature · 1 line
2.53.0
#127 lore raw

Re: [PATCH RESEND v2 07/23] proc: let procfs own the seq_file of seq_file entries

Sashiko has reviewed this patch and found no issues.
Quoted 17 lines

remove_proc_entry() waits until every call into the entry has returned. For a seq_file entry that's all of seq_read_iter(), including the copy to userspace. A page fault in that copy can be made to take as long as the reader wants, e.g. with userfaultfd or by punching holes into a memfd over and over. And callers of remove_proc_entry() like to hold locks while they wait. xt_hashlimit holds hashlimit_mutex, which all network namespaces share, and addrconf holds RTNL.

But the entry's code only runs between ->start() and ->stop() and the copies to userspace happen outside of that. So let procfs own the seq_file the way kernfs does. An entry declares its seq_operations, or just a show function, and the size of its private state in struct proc_ops. procfs then opens the seq_file with seq_operations it builds for the entry when it is registered: the entry's own ->next() and ->show() with a ->start() and ->stop() of procfs around them that pin [ ... ]

Quoted 4 lines

No users yet.

Sashiko has reviewed this patch and found no issues.

Signature · 1 line
Sashiko AI review · https://sashiko.dev/#/patchset/[email protected]?part=7
maintainer
#128 lore raw

Re: [PATCH RESEND v2 07/23] proc: let procfs own the seq_file of seq_file entries

In reply to Christian Brauner

fs/proc/generic.c static bool pde_needs_open_node(const struct proc_dir_entry *pde) · line 494

Quoted 8 lines · Christian Brauner

[...]

fs/proc/generic.c +7 -0
+static int pde_init_seq_direct(struct proc_dir_entry *pde)
+{
+	struct seq_operations *ops;
+
+	if (!pde_is_seq_file(pde))
+		return 0;
+	ops = kmalloc(sizeof(*ops), GFP_KERNEL);

Please use the new style typed allocation calls for objects:

ops = kmalloc_obj(*ops);

(This happened to jump out at me, but please check the other patches for this pattern.)

Quoted 1 line
		dp->open = kzalloc(sizeof(*dp->open), GFP_KERNEL);

Same, etc.

Signature · 1 line
Kees Cook
author maintainer
#129 lore raw

Re: [PATCH RESEND v2 07/23] proc: let procfs own the seq_file of seq_file entries

Quoted 5 lines · Kees Cook

Please use the new style typed allocation calls for objects:

ops = kmalloc_obj(*ops);

(This happened to jump out at me, but please check the other patches for this pattern.)

Done, there are 5 of them in total:

proc: resume readdir after the last name it returned
- cursor = kmalloc(sizeof(*cursor), GFP_KERNEL_ACCOUNT);
+ cursor = kmalloc_obj(*cursor, GFP_KERNEL_ACCOUNT);

proc: sysctl: resume readdir after the last name it returned
- cursor = kmalloc(sizeof(*cursor), GFP_KERNEL_ACCOUNT);
+ cursor = kmalloc_obj(*cursor, GFP_KERNEL_ACCOUNT);

proc: keep the open files of an entry in an open node
- dp->open = kzalloc(sizeof(*dp->open), GFP_KERNEL);
+ dp->open = kzalloc_obj(*dp->open);

proc: own the wait queue of an entry with a ->proc_poll()
- on = kzalloc(sizeof(*on), GFP_KERNEL);
+ on = kzalloc_obj(*on);

proc: let procfs own the seq_file of seq_file entries
- ops = kmalloc(sizeof(*ops), GFP_KERNEL);
+ ops = kmalloc_obj(*ops);

author maintainer
#130 lore raw

PATCH RESEND v2 8/23 proc: let procfs own the seq_file of proc_create_seq() and friends

In reply to Christian Brauner

proc_create_seq_private(), proc_create_single_data() and their network namespace variants keep the seq_operations or the show function in the entry already. Let procfs own the seq_file for all of them. For the network namespace variants ->proc_open() and ->proc_release() keep taking and dropping the reference to the network namespace.

That's most of /proc/net, among them the files of xt_hashlimit and /proc/net/dev_snmp6/<dev>. A reader that faults on its buffer no longer holds up their removal.

Fixes 786d7e1612f0 ("Fix rmmod/read/write races in /proc entries")
---
 fs/proc/generic.c  | 42 ++++--------------------------------------
 fs/proc/proc_net.c | 40 +++++++++++++---------------------------
 2 files changed, 17 insertions(+), 65 deletions(-)
fs/proc/generic.c +4 -38
index 59b89e251ba3..959bf9e33245 100644
@@ -737,30 +737,9 @@ struct proc_dir_entry *proc_create(const char *name, umode_t mode,
 }
 EXPORT_SYMBOL(proc_create);
 
-static int proc_seq_open(struct inode *inode, struct file *file)
-{
-	struct proc_dir_entry *de = PDE(inode);
-
-	if (de->state_size)
-		return seq_open_private(file, de->seq_ops, de->state_size);
-	return seq_open(file, de->seq_ops);
-}
-
-static int proc_seq_release(struct inode *inode, struct file *file)
-{
-	struct proc_dir_entry *de = PDE(inode);
-
-	if (de->state_size)
-		return seq_release_private(inode, file);
-	return seq_release(inode, file);
-}
-
+/* procfs owns the seq_file of these, see pde_seq_start() */
 static const struct proc_ops proc_seq_ops = {
 	/* not permanent -- can call into arbitrary seq_operations */
-	.proc_open	= proc_seq_open,
-	.proc_read_iter	= seq_read_iter,
-	.proc_lseek	= seq_lseek,
-	.proc_release	= proc_seq_release,
 };
 
 struct proc_dir_entry *proc_create_seq_private(const char *name, umode_t mode,
@@ -775,25 +754,11 @@ struct proc_dir_entry *proc_create_seq_private(const char *name, umode_t mode,
 	p->proc_ops = &proc_seq_ops;
 	p->seq_ops = ops;
 	p->state_size = state_size;
+	p->flags |= PROC_ENTRY_proc_seq_ops;
 	return proc_register(parent, p);
 }
 EXPORT_SYMBOL(proc_create_seq_private);
 
-static int proc_single_open(struct inode *inode, struct file *file)
-{
-	struct proc_dir_entry *de = PDE(inode);
-
-	return single_open(file, de->single_show, de->data);
-}
-
-static const struct proc_ops proc_single_ops = {
-	/* not permanent -- can call into arbitrary ->single_show */
-	.proc_open	= proc_single_open,
-	.proc_read_iter = seq_read_iter,
-	.proc_lseek	= seq_lseek,
-	.proc_release	= single_release,
-};
-
 struct proc_dir_entry *proc_create_single_data(const char *name, umode_t mode,
 		struct proc_dir_entry *parent,
 		int (*show)(struct seq_file *, void *), void *data)
@@ -803,8 +768,9 @@ struct proc_dir_entry *proc_create_single_data(const char *name, umode_t mode,
 	p = proc_create_reg(name, mode, &parent, data);
 	if (!p)
 		return NULL;
-	p->proc_ops = &proc_single_ops;
+	p->proc_ops = &proc_seq_ops;
 	p->single_show = show;
+	p->flags |= PROC_ENTRY_proc_show;
 	return proc_register(parent, p);
 }
 EXPORT_SYMBOL(proc_create_single_data);
fs/proc/proc_net.c +13 -27
index df5484813d5d..9973f846c467 100644
@@ -37,13 +37,13 @@ static struct net *get_proc_net(const struct inode *inode)
 	return maybe_get_net(PDE_NET(PDE(inode)));
 }
 
+/* procfs opened the seq_file and allocated its state, see pde_seq_start() */
 static int seq_open_net(struct inode *inode, struct file *file)
 {
-	unsigned int state_size = PDE(inode)->state_size;
-	struct seq_net_private *p;
+	struct seq_net_private *p = ((struct seq_file *)file->private_data)->private;
 	struct net *net;
 
-	WARN_ON_ONCE(state_size < sizeof(*p));
+	WARN_ON_ONCE(PDE(inode)->state_size < sizeof(*p));
 
 	if (file->f_mode & FMODE_WRITE && !PDE(inode)->write)
 		return -EACCES;
@@ -51,12 +51,6 @@ static int seq_open_net(struct inode *inode, struct file *file)
 	net = get_proc_net(inode);
 	if (!net)
 		return -ENXIO;
-
-	p = __seq_open_private(file, PDE(inode)->seq_ops, state_size);
-	if (!p) {
-		put_net(net);
-		return -ENOMEM;
-	}
 #ifdef CONFIG_NET_NS
 	p->net = net;
 	netns_tracker_alloc(net, &p->ns_tracker, GFP_KERNEL);
@@ -77,18 +71,13 @@ static void seq_file_net_put_net(struct seq_file *seq)
 
 static int seq_release_net(struct inode *ino, struct file *f)
 {
-	struct seq_file *seq = f->private_data;
-
-	seq_file_net_put_net(seq);
-	seq_release_private(ino, f);
+	seq_file_net_put_net(f->private_data);
 	return 0;
 }
 
 static const struct proc_ops proc_net_seq_ops = {
 	.proc_open	= seq_open_net,
-	.proc_read	= seq_read,
 	.proc_write	= proc_simple_write,
-	.proc_lseek	= seq_lseek,
 	.proc_release	= seq_release_net,
 };
 
@@ -125,6 +114,7 @@ struct proc_dir_entry *proc_create_net_data(const char *name, umode_t mode,
 	p->proc_ops = &proc_net_seq_ops;
 	p->seq_ops = ops;
 	p->state_size = state_size;
+	p->flags |= PROC_ENTRY_proc_seq_ops;
 	return proc_register(parent, p);
 }
 EXPORT_SYMBOL_GPL(proc_create_net_data);
@@ -170,6 +160,7 @@ struct proc_dir_entry *proc_create_net_data_write(const char *name, umode_t mode
 	p->proc_ops = &proc_net_seq_ops;
 	p->seq_ops = ops;
 	p->state_size = state_size;
+	p->flags |= PROC_ENTRY_proc_seq_ops;
 	p->write = write;
 	return proc_register(parent, p);
 }
@@ -177,32 +168,25 @@ EXPORT_SYMBOL_GPL(proc_create_net_data_write);
 
 static int single_open_net(struct inode *inode, struct file *file)
 {
-	struct proc_dir_entry *de = PDE(inode);
-	struct net *net;
-	int err;
+	struct net *net = get_proc_net(inode);
 
-	net = get_proc_net(inode);
 	if (!net)
 		return -ENXIO;
-
-	err = single_open(file, de->single_show, net);
-	if (err)
-		put_net(net);
-	return err;
+	((struct seq_file *)file->private_data)->private = net;
+	return 0;
 }
 
 static int single_release_net(struct inode *ino, struct file *f)
 {
 	struct seq_file *seq = f->private_data;
+
 	put_net(seq->private);
-	return single_release(ino, f);
+	return 0;
 }
 
 static const struct proc_ops proc_net_single_ops = {
 	.proc_open	= single_open_net,
-	.proc_read	= seq_read,
 	.proc_write	= proc_simple_write,
-	.proc_lseek	= seq_lseek,
 	.proc_release	= single_release_net,
 };
 
@@ -218,6 +202,7 @@ struct proc_dir_entry *proc_create_net_single(const char *name, umode_t mode,
 	pde_force_lookup(p);
 	p->proc_ops = &proc_net_single_ops;
 	p->single_show = show;
+	p->flags |= PROC_ENTRY_proc_show;
 	return proc_register(parent, p);
 }
 EXPORT_SYMBOL_GPL(proc_create_net_single);
@@ -261,6 +246,7 @@ struct proc_dir_entry *proc_create_net_single_write(const char *name, umode_t mo
 	pde_force_lookup(p);
 	p->proc_ops = &proc_net_single_ops;
 	p->single_show = show;
+	p->flags |= PROC_ENTRY_proc_show;
 	p->write = write;
 	return proc_register(parent, p);
 }
Signature · 1 line
2.53.0
#131 lore raw

Re: [PATCH RESEND v2 08/23] proc: let procfs own the seq_file of proc_create_seq() and friends

Thank you for your contribution! Sashiko AI review found 1 potential issue(s) to consider: - [Low] proc: unused-but-set variable p in seq_open_net() when CONFIG_NET_NS=n --

Thank you for your contribution! Sashiko AI review found 1 potential issue(s) to consider:
- [Low] proc: unused-but-set variable p in seq_open_net() when CONFIG_NET_NS=n --

commit 4dea51dab83a49a4131e34ad5f96bc9822052389
Author: Christian Brauner <[email protected]>

proc: let procfs own the seq_file of proc_create_seq() and friends

This commit updates proc_create_seq_private(), proc_create_single_data(), and their network namespace variants so that procfs owns the seq_file directly via PROC_ENTRY_proc_seq_ops and PROC_ENTRY_proc_show. For the network namespace variants, ->proc_open() and ->proc_release() are simplified to only manage the network namespace reference.

Quoted 24 lines
fs/proc/proc_net.c +3 -3
index df5484813d5dd..9973f846c4674 100644
@@ -37,13 +37,13 @@ static struct net *get_proc_net(const struct inode *inode)
 	return maybe_get_net(PDE_NET(PDE(inode)));
 }
 
+/* procfs opened the seq_file and allocated its state, see pde_seq_start() */
 static int seq_open_net(struct inode *inode, struct file *file)
 {
-	unsigned int state_size = PDE(inode)->state_size;
-	struct seq_net_private *p;
+	struct seq_net_private *p = ((struct seq_file *)file->private_data)->private;
 	struct net *net;
 
-	WARN_ON_ONCE(state_size < sizeof(*p));
+	WARN_ON_ONCE(PDE(inode)->state_size < sizeof(*p));
 
 	if (file->f_mode & FMODE_WRITE && !PDE(inode)->write)
 		return -EACCES;
@@ -51,12 +51,6 @@ static int seq_open_net(struct inode *inode, struct file *file)
 	net = get_proc_net(inode);
 	if (!net)

fs/proc/proc_net.c static int seq_open_net(struct inode *inode, struct file *file) · line 56

Quoted 10 lines
fs/proc/proc_net.c +0 -6
 		return -ENXIO;
-
-	p = __seq_open_private(file, PDE(inode)->seq_ops, state_size);
-	if (!p) {
-		put_net(net);
-		return -ENOMEM;
-	}
 #ifdef CONFIG_NET_NS
 	p->net = net;
 	netns_tracker_alloc(net, &p->ns_tracker, GFP_KERNEL);

[Severity: Low]
When CONFIG_NET_NS is disabled, does initializing p unconditionally in seq_open_net() trigger a -Wunused-but-set-variable warning?

Previously, p was assigned via __seq_open_private() and checked with if (!p) outside the #ifdef CONFIG_NET_NS block. With that check removed, the only remaining reference outside #ifdef CONFIG_NET_NS is sizeof(*p) in WARN_ON_ONCE(), which is an unevaluated context and does not read the value of p.

Signature · 1 line
Sashiko AI review · https://sashiko.dev/#/patchset/[email protected]?part=8
author maintainer
#132 lore raw

PATCH RESEND v2 9/23 proc: let procfs own the seq_file of DEFINE_PROC_SHOW_ATTRIBUTE() files

In reply to Christian Brauner

Declare the show function and let procfs open the seq_file.

---
 include/linux/seq_file.h | 10 +---------
 1 file changed, 1 insertion(+), 9 deletions(-)
include/linux/seq_file.h +1 -9
index dc0e8c62d9e0..b813b7e63d89 100644
@@ -233,16 +233,8 @@ static const struct file_operations __name ## _fops = {			\
 }
 
 #define DEFINE_PROC_SHOW_ATTRIBUTE(__name)				\
-static int __name ## _open(struct inode *inode, struct file *file)	\
-{									\
-	return single_open(file, __name ## _show, pde_data(inode));	\
-}									\
-									\
 static const struct proc_ops __name ## _proc_ops = {			\
-	.proc_open	= __name ## _open,				\
-	.proc_read	= seq_read,					\
-	.proc_lseek	= seq_lseek,					\
-	.proc_release	= single_release,				\
+	.proc_show	= __name ## _show,				\
 }
 
 static inline struct user_namespace *seq_user_ns(struct seq_file *seq)
Signature · 1 line
2.53.0
#133 lore raw

Re: [PATCH RESEND v2 09/23] proc: let procfs own the seq_file of DEFINE_PROC_SHOW_ATTRIBUTE() files

Sashiko has reviewed this patch and found no issues.
Quoted 3 lines

Declare the show function and let procfs open the seq_file.

Sashiko has reviewed this patch and found no issues.

Signature · 1 line
Sashiko AI review · https://sashiko.dev/#/patchset/[email protected]?part=9
author maintainer
#134 lore raw

PATCH RESEND v2 10/23 treewide: let procfs own the seq_file of simple proc entries

In reply to Christian Brauner

Most proc entries that bring their own struct proc_ops only call single_open(), seq_open() or seq_open_private() in ->proc_open() and free the seq_file with the matching helper. Declare the show function or the seq_operations instead and let procfs open and free the seq_file. Reading these files then no longer holds up their removal.

Done with the following semantic patch. The new initializers were aligned like their neighbours afterwards:

// SPDX-License-Identifier: GPL-2.0-only
/// Let procfs open the seq_file of proc entries whose ->proc_open() only /// calls single_open(), seq_open() or seq_open_private().
//
// Confidence: High
// Options: --no-includes --include-headers

virtual patch

  @single depends on patch@
  identifier open_fn, show_fn, i, f;
  @@
  static int open_fn(struct inode *i, struct file *f)
  {
  	return single_open(f, show_fn, \(NULL\|pde_data(i)\));
  }

@single_ops depends on single@
identifier single.open_fn, single.show_fn, ops;
symbol single_release;
@@
const struct proc_ops ops = {
- .proc_open = open_fn,
+ .proc_show = show_fn,
...,
- .proc_release = single_release,
...
};

  @seq depends on patch@
  identifier open_fn, sops, i, f;
  @@
  static int open_fn(struct inode *i, struct file *f)
  {
  	return seq_open(f, &sops);
  }

@seq_ops depends on seq@
identifier seq.open_fn, seq.sops, ops;
symbol seq_release;
@@
const struct proc_ops ops = {
- .proc_open = open_fn,
+ .proc_seq_ops = &sops,
...,
- .proc_release = seq_release,
...
};

  @priv depends on patch@
  identifier open_fn, sops, i, f;
  expression size;
  @@
  static int open_fn(struct inode *i, struct file *f)
  {
  	return seq_open_private(f, &sops, size);
  }

@priv_ops depends on priv@
identifier priv.open_fn, priv.sops, ops;
expression priv.size;
symbol seq_release_private;
@@
const struct proc_ops ops = {
- .proc_open = open_fn,
+ .proc_seq_ops = &sops,
+ .proc_state_size = size,
...,
- .proc_release = seq_release_private,
...
};

  // procfs reads and seeks through the seq_file itself
  @depends on single_ops || seq_ops || priv_ops@
  identifier ops = {single_ops.ops, seq_ops.ops, priv_ops.ops};
  symbol seq_read_iter;
  @@
  const struct proc_ops ops = {
  	...,
  -	.proc_read_iter = seq_read_iter,
  	...
  };

  @depends on single_ops || seq_ops || priv_ops@
  identifier ops = {single_ops.ops, seq_ops.ops, priv_ops.ops};
  symbol seq_read;
  @@
  const struct proc_ops ops = {
  	...,
  -	.proc_read = seq_read,
  	...
  };

  @depends on single_ops || seq_ops || priv_ops@
  identifier ops = {single_ops.ops, seq_ops.ops, priv_ops.ops};
  symbol seq_lseek;
  @@
  const struct proc_ops ops = {
  	...,
  -	.proc_lseek = seq_lseek,
  	...
  };

// drop the open function unless something else still uses it @open_used@
identifier open_fn = {single.open_fn, seq.open_fn, priv.open_fn}; @@
open_fn

  @depends on !open_used && (single_ops || seq_ops || priv_ops)@
  identifier open_fn = {single.open_fn, seq.open_fn, priv.open_fn};
  @@
  - static int open_fn(...) { ... }
---
 arch/alpha/kernel/srm_env.c                        | 10 +--
 arch/arm/mm/alignment.c                            | 10 +--
 arch/powerpc/kernel/rtas-proc.c                    | 50 ++------------
 arch/powerpc/platforms/pseries/lpar.c              | 20 +-----
 arch/powerpc/platforms/pseries/lparcfg.c           | 10 +--
 arch/sh/mm/alignment.c                             | 10 +--
 arch/sparc/kernel/led.c                            | 10 +--
 arch/um/kernel/exitcode.c                          | 10 +--
 drivers/acpi/proc.c                                | 12 +---
 drivers/hwmon/dell-smm-hwmon.c                     | 10 +--
 drivers/input/input.c                              | 24 ++-----
 drivers/macintosh/via-pmu.c                        | 10 +--
 drivers/net/wireless/intel/ipw2x00/libipw_module.c | 10 +--
 drivers/platform/x86/lenovo/thinkpad_acpi.c        | 10 +--
 drivers/platform/x86/toshiba_acpi.c                | 40 ++---------
 drivers/pnp/pnpbios/proc.c                         | 10 +--
 drivers/s390/block/dasd_proc.c                     | 10 +--
 drivers/s390/cio/blacklist.c                       | 13 +---
 drivers/scsi/scsi_devinfo.c                        | 10 +--
 drivers/scsi/scsi_proc.c                           | 21 +-----
 drivers/usb/gadget/function/rndis.c                | 10 +--
 drivers/video/fbdev/via/viafbdev.c                 | 70 ++-----------------
 fs/jfs/jfs_debug.c                                 | 10 +--
 fs/ntfs3/super.c                                   | 20 +-----
 fs/proc/cpuinfo.c                                  | 10 +--
 fs/smb/client/cifs_debug.c                         | 79 +++-------------------
 fs/smb/client/dfs_cache.c                          | 10 +--
 kernel/irq/proc.c                                  | 30 +-------
 kernel/latencytop.c                                | 10 +--
 lib/dynamic_debug.c                                |  6 +-
 mm/slab_common.c                                   | 10 +--
 net/core/pktgen.c                                  | 30 +-------
 net/sunrpc/stats.c                                 | 10 +--
 33 files changed, 64 insertions(+), 551 deletions(-)
arch/alpha/kernel/srm_env.c +1 -9
index 217b4dca51dd..faafc2df7886 100644
@@ -81,11 +81,6 @@ static int srm_env_proc_show(struct seq_file *m, void *v)
 	return ret;
 }
 
-static int srm_env_proc_open(struct inode *inode, struct file *file)
-{
-	return single_open(file, srm_env_proc_show, pde_data(inode));
-}
-
 static ssize_t srm_env_proc_write(struct file *file, const char __user *buffer,
 				  size_t count, loff_t *pos)
 {
@@ -120,10 +115,7 @@ static ssize_t srm_env_proc_write(struct file *file, const char __user *buffer,
 }
 
 static const struct proc_ops srm_env_proc_ops = {
-	.proc_open	= srm_env_proc_open,
-	.proc_read	= seq_read,
-	.proc_lseek	= seq_lseek,
-	.proc_release	= single_release,
+	.proc_show	= srm_env_proc_show,
 	.proc_write	= srm_env_proc_write,
 };
 
arch/arm/mm/alignment.c +1 -9
index f6c1e6b61179..3e5e30968634 100644
@@ -144,11 +144,6 @@ static int alignment_proc_show(struct seq_file *m, void *v)
 	return 0;
 }
 
-static int alignment_proc_open(struct inode *inode, struct file *file)
-{
-	return single_open(file, alignment_proc_show, NULL);
-}
-
 static ssize_t alignment_proc_write(struct file *file, const char __user *buffer,
 				    size_t count, loff_t *pos)
 {
@@ -164,10 +159,7 @@ static ssize_t alignment_proc_write(struct file *file, const char __user *buffer
 }
 
 static const struct proc_ops alignment_proc_ops = {
-	.proc_open	= alignment_proc_open,
-	.proc_read	= seq_read,
-	.proc_lseek	= seq_lseek,
-	.proc_release	= single_release,
+	.proc_show	= alignment_proc_show,
 	.proc_write	= alignment_proc_write,
 };
 #endif /* CONFIG_PROC_FS */
arch/powerpc/kernel/rtas-proc.c +5 -45

74 lines not on this page · raw message

arch/powerpc/platforms/pseries/lpar.c +2 -18
index 6a415febc53b..48fe0be71a89 100644
@@ -584,17 +584,9 @@ static int vcpudispatch_stats_display(struct seq_file *p, void *v)
 	return 0;
 }
 
-static int vcpudispatch_stats_open(struct inode *inode, struct file *file)
-{
-	return single_open(file, vcpudispatch_stats_display, NULL);
-}
-
 static const struct proc_ops vcpudispatch_stats_proc_ops = {
-	.proc_open	= vcpudispatch_stats_open,
-	.proc_read	= seq_read,
+	.proc_show	= vcpudispatch_stats_display,
 	.proc_write	= vcpudispatch_stats_write,
-	.proc_lseek	= seq_lseek,
-	.proc_release	= single_release,
 };
 
 static ssize_t vcpudispatch_stats_freq_write(struct file *file,
@@ -628,17 +620,9 @@ static int vcpudispatch_stats_freq_display(struct seq_file *p, void *v)
 	return 0;
 }
 
-static int vcpudispatch_stats_freq_open(struct inode *inode, struct file *file)
-{
-	return single_open(file, vcpudispatch_stats_freq_display, NULL);
-}
-
 static const struct proc_ops vcpudispatch_stats_freq_proc_ops = {
-	.proc_open	= vcpudispatch_stats_freq_open,
-	.proc_read	= seq_read,
+	.proc_show	= vcpudispatch_stats_freq_display,
 	.proc_write	= vcpudispatch_stats_freq_write,
-	.proc_lseek	= seq_lseek,
-	.proc_release	= single_release,
 };
 
 static int __init vcpudispatch_stats_procfs_init(void)
arch/powerpc/platforms/pseries/lparcfg.c +1 -9
index 4f6b2975c6e9..cb3d96efb225 100644
@@ -797,17 +797,9 @@ static int lparcfg_data(struct seq_file *m, void *v)
 	return pseries_lparcfg_data(m, v);
 }
 
-static int lparcfg_open(struct inode *inode, struct file *file)
-{
-	return single_open(file, lparcfg_data, NULL);
-}
-
 static const struct proc_ops lparcfg_proc_ops = {
-	.proc_read	= seq_read,
 	.proc_write	= lparcfg_write,
-	.proc_open	= lparcfg_open,
-	.proc_release	= single_release,
-	.proc_lseek	= seq_lseek,
+	.proc_show	= lparcfg_data,
 };
 
 static int __init lparcfg_init(void)
arch/sh/mm/alignment.c +1 -9
index 3a76a766f423..2198c6f2ea63 100644
@@ -132,11 +132,6 @@ static int alignment_proc_show(struct seq_file *m, void *v)
 	return 0;
 }
 
-static int alignment_proc_open(struct inode *inode, struct file *file)
-{
-	return single_open(file, alignment_proc_show, NULL);
-}
-
 static ssize_t alignment_proc_write(struct file *file,
 		const char __user *buffer, size_t count, loff_t *pos)
 {
@@ -153,10 +148,7 @@ static ssize_t alignment_proc_write(struct file *file,
 }
 
 static const struct proc_ops alignment_proc_ops = {
-	.proc_open	= alignment_proc_open,
-	.proc_read	= seq_read,
-	.proc_lseek	= seq_lseek,
-	.proc_release	= single_release,
+	.proc_show	= alignment_proc_show,
 	.proc_write	= alignment_proc_write,
 };
 
arch/sparc/kernel/led.c +1 -9
index a1478de9fe5d..0f7376b51a04 100644
@@ -60,11 +60,6 @@ static int led_proc_show(struct seq_file *m, void *v)
 	return 0;
 }
 
-static int led_proc_open(struct inode *inode, struct file *file)
-{
-	return single_open(file, led_proc_show, NULL);
-}
-
 static ssize_t led_proc_write(struct file *file, const char __user *buffer,
 			      size_t count, loff_t *ppos)
 {
@@ -107,10 +102,7 @@ static ssize_t led_proc_write(struct file *file, const char __user *buffer,
 }
 
 static const struct proc_ops led_proc_ops = {
-	.proc_open	= led_proc_open,
-	.proc_read	= seq_read,
-	.proc_lseek	= seq_lseek,
-	.proc_release	= single_release,
+	.proc_show	= led_proc_show,
 	.proc_write	= led_proc_write,
 };
 #endif
arch/um/kernel/exitcode.c +1 -9
index 0230354f4812..c71657df38f5 100644
@@ -31,11 +31,6 @@ static int exitcode_proc_show(struct seq_file *m, void *v)
 	return 0;
 }
 
-static int exitcode_proc_open(struct inode *inode, struct file *file)
-{
-	return single_open(file, exitcode_proc_show, NULL);
-}
-
 static ssize_t exitcode_proc_write(struct file *file,
 		const char __user *buffer, size_t count, loff_t *pos)
 {
@@ -57,10 +52,7 @@ static ssize_t exitcode_proc_write(struct file *file,
 }
 
 static const struct proc_ops exitcode_proc_ops = {
-	.proc_open	= exitcode_proc_open,
-	.proc_read	= seq_read,
-	.proc_lseek	= seq_lseek,
-	.proc_release	= single_release,
+	.proc_show	= exitcode_proc_show,
 	.proc_write	= exitcode_proc_write,
 };
 
drivers/acpi/proc.c +1 -11
index c08ead07252b..b8a0bd4580e0 100644
@@ -121,19 +121,9 @@ acpi_system_write_wakeup_device(struct file *file,
 	return count;
 }
 
-static int
-acpi_system_wakeup_device_open_fs(struct inode *inode, struct file *file)
-{
-	return single_open(file, acpi_system_wakeup_device_seq_show,
-			   pde_data(inode));
-}
-
 static const struct proc_ops acpi_system_wakeup_device_proc_ops = {
-	.proc_open	= acpi_system_wakeup_device_open_fs,
-	.proc_read	= seq_read,
+	.proc_show	= acpi_system_wakeup_device_seq_show,
 	.proc_write	= acpi_system_write_wakeup_device,
-	.proc_lseek	= seq_lseek,
-	.proc_release	= single_release,
 };
 
 void __init acpi_sleep_proc_init(void)
drivers/hwmon/dell-smm-hwmon.c +1 -9
index 88837f028405..492b2b6c6d7e 100644
@@ -694,16 +694,8 @@ static int i8k_proc_show(struct seq_file *seq, void *offset)
 	return 0;
 }
 
-static int i8k_open_fs(struct inode *inode, struct file *file)
-{
-	return single_open(file, i8k_proc_show, pde_data(inode));
-}
-
 static const struct proc_ops i8k_proc_ops = {
-	.proc_open	= i8k_open_fs,
-	.proc_read	= seq_read,
-	.proc_lseek	= seq_lseek,
-	.proc_release	= single_release,
+	.proc_show	= i8k_proc_show,
 	.proc_ioctl	= i8k_ioctl,
 };
 
drivers/input/input.c +4 -20
index 0859b60ca924..d27eecbf4a03 100644
@@ -1218,18 +1218,10 @@ static const struct seq_operations input_devices_seq_ops = {
 	.show	= input_devices_seq_show,
 };
 
-static int input_proc_devices_open(struct inode *inode, struct file *file)
-{
-	return seq_open_private(file, &input_devices_seq_ops,
-				sizeof(struct input_seq_state));
-}
-
 static const struct proc_ops input_devices_proc_ops = {
-	.proc_open	= input_proc_devices_open,
+	.proc_seq_ops	= &input_devices_seq_ops,
+	.proc_state_size = sizeof(struct input_seq_state),
 	.proc_poll	= input_proc_devices_poll,
-	.proc_read	= seq_read,
-	.proc_lseek	= seq_lseek,
-	.proc_release	= seq_release_private,
 };
 
 static void *input_handlers_seq_start(struct seq_file *seq, loff_t *pos)
@@ -1279,17 +1271,9 @@ static const struct seq_operations input_handlers_seq_ops = {
 	.show	= input_handlers_seq_show,
 };
 
-static int input_proc_handlers_open(struct inode *inode, struct file *file)
-{
-	return seq_open_private(file, &input_handlers_seq_ops,
-				sizeof(struct input_seq_state));
-}
-
 static const struct proc_ops input_handlers_proc_ops = {
-	.proc_open	= input_proc_handlers_open,
-	.proc_read	= seq_read,
-	.proc_lseek	= seq_lseek,
-	.proc_release	= seq_release_private,
+	.proc_seq_ops = &input_handlers_seq_ops,
+	.proc_state_size = sizeof(struct input_seq_state),
 };
 
 static int __init input_proc_init(void)
drivers/macintosh/via-pmu.c +1 -9
index 8c652c15018c..49f929ae10e4 100644
@@ -912,11 +912,6 @@ static int pmu_options_proc_show(struct seq_file *m, void *v)
 	return 0;
 }
 
-static int pmu_options_proc_open(struct inode *inode, struct file *file)
-{
-	return single_open(file, pmu_options_proc_show, NULL);
-}
-
 static ssize_t pmu_options_proc_write(struct file *file,
 		const char __user *buffer, size_t count, loff_t *pos)
 {
@@ -962,10 +957,7 @@ static ssize_t pmu_options_proc_write(struct file *file,
 }
 
 static const struct proc_ops pmu_options_proc_ops = {
-	.proc_open	= pmu_options_proc_open,
-	.proc_read	= seq_read,
-	.proc_lseek	= seq_lseek,
-	.proc_release	= single_release,
+	.proc_show	= pmu_options_proc_show,
 	.proc_write	= pmu_options_proc_write,
 };
 #endif
drivers/net/wireless/intel/ipw2x00/libipw_module.c +1 -9
index 552c8ff3928b..15d9a5efb581 100644
@@ -215,11 +215,6 @@ static int debug_level_proc_show(struct seq_file *m, void *v)
 	return 0;
 }
 
-static int debug_level_proc_open(struct inode *inode, struct file *file)
-{
-	return single_open(file, debug_level_proc_show, NULL);
-}
-
 static ssize_t debug_level_proc_write(struct file *file,
 		const char __user *buffer, size_t count, loff_t *pos)
 {
@@ -240,10 +235,7 @@ static ssize_t debug_level_proc_write(struct file *file,
 }
 
 static const struct proc_ops debug_level_proc_ops = {
-	.proc_open	= debug_level_proc_open,
-	.proc_read	= seq_read,
-	.proc_lseek	= seq_lseek,
-	.proc_release	= single_release,
+	.proc_show	= debug_level_proc_show,
 	.proc_write	= debug_level_proc_write,
 };
 #endif				/* CONFIG_LIBIPW_DEBUG */
drivers/platform/x86/lenovo/thinkpad_acpi.c +1 -9
index 4f81855ad721..2ee208c82801 100644
@@ -881,11 +881,6 @@ static int dispatch_proc_show(struct seq_file *m, void *v)
 	return ibm->read(m);
 }
 
-static int dispatch_proc_open(struct inode *inode, struct file *file)
-{
-	return single_open(file, dispatch_proc_show, pde_data(inode));
-}
-
 static ssize_t dispatch_proc_write(struct file *file,
 			const char __user *userbuf,
 			size_t count, loff_t *pos)
@@ -910,10 +905,7 @@ static ssize_t dispatch_proc_write(struct file *file,
 }
 
 static const struct proc_ops dispatch_proc_ops = {
-	.proc_open	= dispatch_proc_open,
-	.proc_read	= seq_read,
-	.proc_lseek	= seq_lseek,
-	.proc_release	= single_release,
+	.proc_show	= dispatch_proc_show,
 	.proc_write	= dispatch_proc_write,
 };
 
drivers/platform/x86/toshiba_acpi.c +4 -36
index 9eb8f1e5aeda..560e62da05a9 100644
@@ -1448,11 +1448,6 @@ static int lcd_proc_show(struct seq_file *m, void *v)
 	return 0;
 }
 
-static int lcd_proc_open(struct inode *inode, struct file *file)
-{
-	return single_open(file, lcd_proc_show, pde_data(inode));
-}
-
 static int set_lcd_brightness(struct toshiba_acpi_dev *dev, int value)
 {
 	u32 result;
@@ -1509,10 +1504,7 @@ static ssize_t lcd_proc_write(struct file *file, const char __user *buf,
 }
 
 static const struct proc_ops lcd_proc_ops = {
-	.proc_open	= lcd_proc_open,
-	.proc_read	= seq_read,
-	.proc_lseek	= seq_lseek,
-	.proc_release	= single_release,
+	.proc_show	= lcd_proc_show,
 	.proc_write	= lcd_proc_write,
 };
 
@@ -1549,11 +1541,6 @@ static int video_proc_show(struct seq_file *m, void *v)
 	return 0;
 }
 
-static int video_proc_open(struct inode *inode, struct file *file)
-{
-	return single_open(file, video_proc_show, pde_data(inode));
-}
-
 static ssize_t video_proc_write(struct file *file, const char __user *buf,
 				size_t count, loff_t *pos)
 {
@@ -1614,10 +1601,7 @@ static ssize_t video_proc_write(struct file *file, const char __user *buf,
 }
 
 static const struct proc_ops video_proc_ops = {
-	.proc_open	= video_proc_open,
-	.proc_read	= seq_read,
-	.proc_lseek	= seq_lseek,
-	.proc_release	= single_release,
+	.proc_show	= video_proc_show,
 	.proc_write	= video_proc_write,
 };
 
@@ -1660,11 +1644,6 @@ static int fan_proc_show(struct seq_file *m, void *v)
 	return 0;
 }
 
-static int fan_proc_open(struct inode *inode, struct file *file)
-{
-	return single_open(file, fan_proc_show, pde_data(inode));
-}
-
 static ssize_t fan_proc_write(struct file *file, const char __user *buf,
 			      size_t count, loff_t *pos)
 {
@@ -1691,10 +1670,7 @@ static ssize_t fan_proc_write(struct file *file, const char __user *buf,
 }
 
 static const struct proc_ops fan_proc_ops = {
-	.proc_open	= fan_proc_open,
-	.proc_read	= seq_read,
-	.proc_lseek	= seq_lseek,
-	.proc_release	= single_release,
+	.proc_show	= fan_proc_show,
 	.proc_write	= fan_proc_write,
 };
 
@@ -1731,11 +1707,6 @@ static int keys_proc_show(struct seq_file *m, void *v)
 	return 0;
 }
 
-static int keys_proc_open(struct inode *inode, struct file *file)
-{
-	return single_open(file, keys_proc_show, pde_data(inode));
-}
-
 static ssize_t keys_proc_write(struct file *file, const char __user *buf,
 			       size_t count, loff_t *pos)
 {
@@ -1758,10 +1729,7 @@ static ssize_t keys_proc_write(struct file *file, const char __user *buf,
 }
 
 static const struct proc_ops keys_proc_ops = {
-	.proc_open	= keys_proc_open,
-	.proc_read	= seq_read,
-	.proc_lseek	= seq_lseek,
-	.proc_release	= single_release,
+	.proc_show	= keys_proc_show,
 	.proc_write	= keys_proc_write,
 };
 
drivers/pnp/pnpbios/proc.c +1 -9
index 0f0d819b157f..14632a8d0da0 100644
@@ -171,11 +171,6 @@ static int pnpbios_proc_show(struct seq_file *m, void *v)
 	return 0;
 }
 
-static int pnpbios_proc_open(struct inode *inode, struct file *file)
-{
-	return single_open(file, pnpbios_proc_show, pde_data(inode));
-}
-
 static ssize_t pnpbios_proc_write(struct file *file, const char __user *buf,
 				  size_t count, loff_t *pos)
 {
@@ -211,10 +206,7 @@ out:
 }
 
 static const struct proc_ops pnpbios_proc_ops = {
-	.proc_open	= pnpbios_proc_open,
-	.proc_read	= seq_read,
-	.proc_lseek	= seq_lseek,
-	.proc_release	= single_release,
+	.proc_show	= pnpbios_proc_show,
 	.proc_write	= pnpbios_proc_write,
 };
 
drivers/s390/block/dasd_proc.c +1 -9
index 48e12e81df00..86399427f01d 100644
@@ -246,11 +246,6 @@ static int dasd_stats_proc_show(struct seq_file *m, void *v)
 	return 0;
 }
 
-static int dasd_stats_proc_open(struct inode *inode, struct file *file)
-{
-	return single_open(file, dasd_stats_proc_show, NULL);
-}
-
 static ssize_t dasd_stats_proc_write(struct file *file,
 		const char __user *user_buf, size_t user_len, loff_t *pos)
 {
@@ -316,10 +311,7 @@ out_error:
 }
 
 static const struct proc_ops dasd_stats_proc_ops = {
-	.proc_open	= dasd_stats_proc_open,
-	.proc_read	= seq_read,
-	.proc_lseek	= seq_lseek,
-	.proc_release	= single_release,
+	.proc_show	= dasd_stats_proc_show,
 	.proc_write	= dasd_stats_proc_write,
 };
 
drivers/s390/cio/blacklist.c +2 -11
index 020d210bde9f..4e02f78f6102 100644
@@ -397,18 +397,9 @@ static const struct seq_operations cio_ignore_proc_seq_ops = {
 	.show  = cio_ignore_proc_seq_show,
 };
 
-static int
-cio_ignore_proc_open(struct inode *inode, struct file *file)
-{
-	return seq_open_private(file, &cio_ignore_proc_seq_ops,
-				sizeof(struct ccwdev_iter));
-}
-
 static const struct proc_ops cio_ignore_proc_ops = {
-	.proc_open	= cio_ignore_proc_open,
-	.proc_read	= seq_read,
-	.proc_lseek	= seq_lseek,
-	.proc_release	= seq_release_private,
+	.proc_seq_ops	= &cio_ignore_proc_seq_ops,
+	.proc_state_size = sizeof(struct ccwdev_iter),
 	.proc_write	= cio_ignore_write,
 };
 
drivers/scsi/scsi_devinfo.c +1 -9
index cfc259fd0141..0b8f5ff40543 100644
@@ -670,11 +670,6 @@ static const struct seq_operations scsi_devinfo_seq_ops = {
 	.show	= devinfo_seq_show,
 };
 
-static int proc_scsi_devinfo_open(struct inode *inode, struct file *file)
-{
-	return seq_open(file, &scsi_devinfo_seq_ops);
-}
-
 /*
  * proc_scsi_dev_info_write - allow additions to scsi_dev_info_list via /proc.
  *
@@ -714,11 +709,8 @@ out:
 }
 
 static const struct proc_ops scsi_devinfo_proc_ops = {
-	.proc_open	= proc_scsi_devinfo_open,
-	.proc_read	= seq_read,
+	.proc_seq_ops	= &scsi_devinfo_seq_ops,
 	.proc_write	= proc_scsi_devinfo_write,
-	.proc_lseek	= seq_lseek,
-	.proc_release	= seq_release,
 };
 #endif /* CONFIG_SCSI_PROC_FS */
 
drivers/scsi/scsi_proc.c +1 -20
index dbd03360b5a4..3e49c4c8704f 100644
@@ -521,28 +521,9 @@ static const struct seq_operations scsi_seq_ops = {
 	.show	= scsi_seq_show
 };
 
-/**
- * proc_scsi_open - glue function
- * @inode: not used
- * @file: passed to single_open()
- *
- * Associates proc_scsi_show with this file
- */
-static int proc_scsi_open(struct inode *inode, struct file *file)
-{
-	/*
-	 * We don't really need this for the write case but it doesn't
-	 * harm either.
-	 */
-	return seq_open(file, &scsi_seq_ops);
-}
-
 static const struct proc_ops scsi_scsi_proc_ops = {
-	.proc_open	= proc_scsi_open,
-	.proc_read	= seq_read,
+	.proc_seq_ops	= &scsi_seq_ops,
 	.proc_write	= proc_scsi_write,
-	.proc_lseek	= seq_lseek,
-	.proc_release	= seq_release,
 };
 
 /**
drivers/usb/gadget/function/rndis.c +1 -9
index a2fd239b7ad3..3c7bd30b8a3a 100644
@@ -1183,16 +1183,8 @@ static ssize_t rndis_proc_write(struct file *file, const char __user *buffer,
 	return count;
 }
 
-static int rndis_proc_open(struct inode *inode, struct file *file)
-{
-	return single_open(file, rndis_proc_show, pde_data(inode));
-}
-
 static const struct proc_ops rndis_proc_ops = {
-	.proc_open	= rndis_proc_open,
-	.proc_read	= seq_read,
-	.proc_lseek	= seq_lseek,
-	.proc_release	= single_release,
+	.proc_show	= rndis_proc_show,
 	.proc_write	= rndis_proc_write,
 };
 
drivers/video/fbdev/via/viafbdev.c +7 -63

154 lines not on this page · raw message

fs/jfs/jfs_debug.c +1 -9
index 44b62b3c322e..5eb35b0d420f 100644
@@ -23,11 +23,6 @@ static int jfs_loglevel_proc_show(struct seq_file *m, void *v)
 	return 0;
 }
 
-static int jfs_loglevel_proc_open(struct inode *inode, struct file *file)
-{
-	return single_open(file, jfs_loglevel_proc_show, NULL);
-}
-
 static ssize_t jfs_loglevel_proc_write(struct file *file,
 		const char __user *buffer, size_t count, loff_t *ppos)
 {
@@ -44,10 +39,7 @@ static ssize_t jfs_loglevel_proc_write(struct file *file,
 }
 
 static const struct proc_ops jfs_loglevel_proc_ops = {
-	.proc_open	= jfs_loglevel_proc_open,
-	.proc_read	= seq_read,
-	.proc_lseek	= seq_lseek,
-	.proc_release	= single_release,
+	.proc_show	= jfs_loglevel_proc_show,
 	.proc_write	= jfs_loglevel_proc_write,
 };
 #endif
fs/ntfs3/super.c +2 -18
index 37e27b73b7a5..cd47839872b0 100644
@@ -548,11 +548,6 @@ static int ntfs3_volinfo(struct seq_file *m, void *o)
 	return 0;
 }
 
-static int ntfs3_volinfo_open(struct inode *inode, struct file *file)
-{
-	return single_open(file, ntfs3_volinfo, pde_data(inode));
-}
-
 /* read /proc/fs/ntfs3/<dev>/label */
 static int ntfs3_label_show(struct seq_file *m, void *o)
 {
@@ -598,23 +593,12 @@ out:
 	return ret;
 }
 
-static int ntfs3_label_open(struct inode *inode, struct file *file)
-{
-	return single_open(file, ntfs3_label_show, pde_data(inode));
-}
-
 static const struct proc_ops ntfs3_volinfo_fops = {
-	.proc_read = seq_read,
-	.proc_lseek = seq_lseek,
-	.proc_release = single_release,
-	.proc_open = ntfs3_volinfo_open,
+	.proc_show = ntfs3_volinfo,
 };
 
 static const struct proc_ops ntfs3_label_fops = {
-	.proc_read = seq_read,
-	.proc_lseek = seq_lseek,
-	.proc_release = single_release,
-	.proc_open = ntfs3_label_open,
+	.proc_show = ntfs3_label_show,
 	.proc_write = ntfs3_label_write,
 };
 
fs/proc/cpuinfo.c +1 -9
index f38bda5b83ec..d8cd718c6030 100644
@@ -7,17 +7,9 @@
 
 extern const struct seq_operations cpuinfo_op;
 
-static int cpuinfo_open(struct inode *inode, struct file *file)
-{
-	return seq_open(file, &cpuinfo_op);
-}
-
 static const struct proc_ops cpuinfo_proc_ops = {
 	.proc_flags	= PROC_ENTRY_PERMANENT,
-	.proc_open	= cpuinfo_open,
-	.proc_read_iter	= seq_read_iter,
-	.proc_lseek	= seq_lseek,
-	.proc_release	= seq_release,
+	.proc_seq_ops	= &cpuinfo_op,
 };
 
 static int __init proc_cpuinfo_init(void)
fs/smb/client/cifs_debug.c +8 -71

165 lines not on this page · raw message

fs/smb/client/dfs_cache.c +1 -9
index 26956e33037e..58f16cf83d36 100644
@@ -213,16 +213,8 @@ static ssize_t dfscache_proc_write(struct file *file, const char __user *buffer,
 	return count;
 }
 
-static int dfscache_proc_open(struct inode *inode, struct file *file)
-{
-	return single_open(file, dfscache_proc_show, NULL);
-}
-
 const struct proc_ops dfscache_proc_ops = {
-	.proc_open	= dfscache_proc_open,
-	.proc_read	= seq_read,
-	.proc_lseek	= seq_lseek,
-	.proc_release	= single_release,
+	.proc_show	= dfscache_proc_show,
 	.proc_write	= dfscache_proc_write,
 };
 
kernel/irq/proc.c +3 -27
index 0c0df16de581..aa3d5544cfc1 100644
@@ -188,29 +188,13 @@ static ssize_t irq_affinity_list_proc_write(struct file *file,
 	return write_irq_affinity(1, file, buffer, count, pos);
 }
 
-static int irq_affinity_proc_open(struct inode *inode, struct file *file)
-{
-	return single_open(file, irq_affinity_proc_show, pde_data(inode));
-}
-
-static int irq_affinity_list_proc_open(struct inode *inode, struct file *file)
-{
-	return single_open(file, irq_affinity_list_proc_show, pde_data(inode));
-}
-
 static const struct proc_ops irq_affinity_proc_ops = {
-	.proc_open	= irq_affinity_proc_open,
-	.proc_read	= seq_read,
-	.proc_lseek	= seq_lseek,
-	.proc_release	= single_release,
+	.proc_show	= irq_affinity_proc_show,
 	.proc_write	= irq_affinity_proc_write,
 };
 
 static const struct proc_ops irq_affinity_list_proc_ops = {
-	.proc_open	= irq_affinity_list_proc_open,
-	.proc_read	= seq_read,
-	.proc_lseek	= seq_lseek,
-	.proc_release	= single_release,
+	.proc_show	= irq_affinity_list_proc_show,
 	.proc_write	= irq_affinity_list_proc_write,
 };
 
@@ -263,16 +247,8 @@ out:
 	return err;
 }
 
-static int default_affinity_open(struct inode *inode, struct file *file)
-{
-	return single_open(file, default_affinity_show, pde_data(inode));
-}
-
 static const struct proc_ops default_affinity_proc_ops = {
-	.proc_open	= default_affinity_open,
-	.proc_read	= seq_read,
-	.proc_lseek	= seq_lseek,
-	.proc_release	= single_release,
+	.proc_show	= default_affinity_show,
 	.proc_write	= default_affinity_write,
 };
 
kernel/latencytop.c +1 -9
index d4281d1e13a6..b764f47606d3 100644
@@ -275,17 +275,9 @@ lstats_write(struct file *file, const char __user *buf, size_t count,
 	return count;
 }
 
-static int lstats_open(struct inode *inode, struct file *filp)
-{
-	return single_open(filp, lstats_show, NULL);
-}
-
 static const struct proc_ops lstats_proc_ops = {
-	.proc_open	= lstats_open,
-	.proc_read	= seq_read,
+	.proc_show	= lstats_show,
 	.proc_write	= lstats_write,
-	.proc_lseek	= seq_lseek,
-	.proc_release	= single_release,
 };
 
 static int __init init_lstats_procfs(void)
lib/dynamic_debug.c +2 -4
index 18a71a9108d3..64a211290872 100644
@@ -1194,10 +1194,8 @@ static const struct file_operations ddebug_proc_fops = {
 };
 
 static const struct proc_ops proc_fops = {
-	.proc_open = ddebug_proc_open,
-	.proc_read = seq_read,
-	.proc_lseek = seq_lseek,
-	.proc_release = seq_release_private,
+	.proc_seq_ops = &ddebug_proc_seqops,
+	.proc_state_size = sizeof(struct ddebug_iter),
 	.proc_write = ddebug_proc_write
 };
 
mm/slab_common.c +1 -9
index 01c64ef661e7..fbf303b45858 100644
@@ -1233,17 +1233,9 @@ static const struct seq_operations slabinfo_op = {
 	.show = slab_show,
 };
 
-static int slabinfo_open(struct inode *inode, struct file *file)
-{
-	return seq_open(file, &slabinfo_op);
-}
-
 static const struct proc_ops slabinfo_proc_ops = {
 	.proc_flags	= PROC_ENTRY_PERMANENT,
-	.proc_open	= slabinfo_open,
-	.proc_read	= seq_read,
-	.proc_lseek	= seq_lseek,
-	.proc_release	= seq_release,
+	.proc_seq_ops	= &slabinfo_op,
 };
 
 static int __init slab_proc_init(void)
net/core/pktgen.c +3 -27
index 02af70d360bc..12363a373fb8 100644
@@ -550,17 +550,9 @@ static ssize_t pgctrl_write(struct file *file, const char __user *buf,
 	return count;
 }
 
-static int pgctrl_open(struct inode *inode, struct file *file)
-{
-	return single_open(file, pgctrl_show, pde_data(inode));
-}
-
 static const struct proc_ops pktgen_proc_ops = {
-	.proc_open	= pgctrl_open,
-	.proc_read	= seq_read,
-	.proc_lseek	= seq_lseek,
+	.proc_show	= pgctrl_show,
 	.proc_write	= pgctrl_write,
-	.proc_release	= single_release,
 };
 
 static int pktgen_if_show(struct seq_file *seq, void *v)
@@ -1870,17 +1862,9 @@ static ssize_t pktgen_if_write(struct file *file,
 	return -EINVAL;
 }
 
-static int pktgen_if_open(struct inode *inode, struct file *file)
-{
-	return single_open(file, pktgen_if_show, pde_data(inode));
-}
-
 static const struct proc_ops pktgen_if_proc_ops = {
-	.proc_open	= pktgen_if_open,
-	.proc_read	= seq_read,
-	.proc_lseek	= seq_lseek,
+	.proc_show	= pktgen_if_show,
 	.proc_write	= pktgen_if_write,
-	.proc_release	= single_release,
 };
 
 static int pktgen_thread_show(struct seq_file *seq, void *v)
@@ -2010,17 +1994,9 @@ out:
 	return ret;
 }
 
-static int pktgen_thread_open(struct inode *inode, struct file *file)
-{
-	return single_open(file, pktgen_thread_show, pde_data(inode));
-}
-
 static const struct proc_ops pktgen_thread_proc_ops = {
-	.proc_open	= pktgen_thread_open,
-	.proc_read	= seq_read,
-	.proc_lseek	= seq_lseek,
+	.proc_show	= pktgen_thread_show,
 	.proc_write	= pktgen_thread_write,
-	.proc_release	= single_release,
 };
 
 /* Think find or remove for NN */
net/sunrpc/stats.c +1 -9
index d08711bee18e..f5ee18a0eb37 100644
@@ -64,16 +64,8 @@ static int rpc_proc_show(struct seq_file *seq, void *v) {
 	return 0;
 }
 
-static int rpc_proc_open(struct inode *inode, struct file *file)
-{
-	return single_open(file, rpc_proc_show, pde_data(inode));
-}
-
 static const struct proc_ops rpc_proc_ops = {
-	.proc_open	= rpc_proc_open,
-	.proc_read	= seq_read,
-	.proc_lseek	= seq_lseek,
-	.proc_release	= single_release,
+	.proc_show = rpc_proc_show,
 };
 
 /*
Signature · 1 line
2.53.0
#135 lore raw

Re: [PATCH RESEND v2 10/23] treewide: let procfs own the seq_file of simple proc entries

Sashiko has reviewed this patch and found no issues.
Quoted 20 lines

Most proc entries that bring their own struct proc_ops only call single_open(), seq_open() or seq_open_private() in ->proc_open() and free the seq_file with the matching helper. Declare the show function or the seq_operations instead and let procfs open and free the seq_file. Reading these files then no longer holds up their removal.

Done with the following semantic patch. The new initializers were aligned like their neighbours afterwards:

// SPDX-License-Identifier: GPL-2.0-only
/// Let procfs open the seq_file of proc entries whose ->proc_open() only /// calls single_open(), seq_open() or seq_open_private().
//
// Confidence: High
// Options: --no-includes --include-headers
[ ... ]
identifier open_fn = {single.open_fn, seq.open_fn, priv.open_fn}; @@
- static int open_fn(...) { ... }

Quoted 1 line

Sashiko has reviewed this patch and found no issues.

Signature · 1 line
Sashiko AI review · https://sashiko.dev/#/patchset/[email protected]?part=10
author maintainer
#136 lore raw

PATCH RESEND v2 11/23 selftests/proc: check that a faulting reader doesn't hold up removal

In reply to Christian Brauner

Read /proc/net/dev_snmp6/<dev> of a tun device into a buffer whose first page is backed by userfaultfd and remove the device while the reader sleeps in its copy to userspace:

- removing the entry doesn't wait for the reader

- the reader still gets what was printed before the removal

- and the next read fails with -EIO

The entry is removed under RTNL, so a regression stalls the test for five seconds before it fails.

---
 tools/testing/selftests/proc/.gitignore            |   1 +
 tools/testing/selftests/proc/Makefile              |   1 +
 .../selftests/proc/proc-remove-slow-reader.c       | 133 +++++++++++++++++++++
 3 files changed, 135 insertions(+)
tools/testing/selftests/proc/.gitignore +1 -0
index 3fa89f46b9c7..e2566cc0ae07 100644
@@ -22,6 +22,7 @@
 /proc-uptime-002
 /proc-pidns
 /proc-remove-slow-sysctl
+/proc-remove-slow-reader
 /proc-remove-slow-readlink
 /read
 /self
tools/testing/selftests/proc/Makefile +1 -0
index df02699a3587..6a9bdc999f54 100644
@@ -33,6 +33,7 @@ TEST_GEN_PROGS += proc-fsconfig-hidepid
 TEST_GEN_PROGS += proc-sysctl-readdir-churn
 TEST_GEN_PROGS += proc-pidns
 TEST_GEN_PROGS += proc-remove-slow-sysctl
+TEST_GEN_PROGS += proc-remove-slow-reader
 TEST_GEN_PROGS += proc-remove-slow-readlink
 
 include ../lib.mk
tools/testing/selftests/proc/proc-remove-slow-reader.c new file +133 -0

133 lines not on this page · raw message

Signature · 1 line
2.53.0
#137 lore raw

Re: [PATCH RESEND v2 11/23] selftests/proc: check that a faulting reader doesn't hold up removal

Sashiko has reviewed this patch and found no issues.
Quoted 6 lines

Read /proc/net/dev_snmp6/<dev> of a tun device into a buffer whose first page is backed by userfaultfd and remove the device while the reader sleeps in its copy to userspace:

- removing the entry doesn't wait for the reader

Quoted 8 lines

- the reader still gets what was printed before the removal

- and the next read fails with -EIO

The entry is removed under RTNL, so a regression stalls the test for five seconds before it fails.

Sashiko has reviewed this patch and found no issues.

Signature · 1 line
Sashiko AI review · https://sashiko.dev/#/patchset/[email protected]?part=11
author maintainer
#138 lore raw

PATCH RESEND v2 12/23 seq_file: add seq_preallocate()

In reply to Christian Brauner

single_open_size() allocates the buffer itself because it does the single_open() too. A file whose seq_file is opened by somebody else, like procfs does now, needs to do that after the fact. Add seq_preallocate() for that and use it in single_open_size().

No functional changes.

---
 fs/seq_file.c            | 36 ++++++++++++++++++++++++++++--------
 include/linux/seq_file.h |  1 +
 2 files changed, 29 insertions(+), 8 deletions(-)
fs/seq_file.c +28 -8
index 456c78719fd0..a4644cdda7e6 100644
@@ -590,21 +590,41 @@ int single_open(struct file *file, int (*show)(struct seq_file *, void *),
 }
 EXPORT_SYMBOL(single_open);
 
-int single_open_size(struct file *file, int (*show)(struct seq_file *, void *),
-		void *data, size_t size)
+/**
+ *	seq_preallocate -	start out with a buffer of @size
+ *	@m: the seq_file, before it is first read
+ *	@size: the size of the buffer
+ *
+ *	For files whose records don't fit into a page, so that the first read
+ *	doesn't have to work its way up to the right buffer size.
+ */
+int seq_preallocate(struct seq_file *m, size_t size)
 {
 	char *buf = seq_buf_alloc(size);
-	int ret;
+
 	if (!buf)
 		return -ENOMEM;
+	kvfree(m->buf);
+	m->buf = buf;
+	m->size = size;
+	return 0;
+}
+EXPORT_SYMBOL(seq_preallocate);
+
+int single_open_size(struct file *file, int (*show)(struct seq_file *, void *),
+		void *data, size_t size)
+{
+	int ret;
+
 	ret = single_open(file, show, data);
-	if (ret) {
-		kvfree(buf);
+	if (ret)
 		return ret;
+	ret = seq_preallocate(file->private_data, size);
+	if (ret) {
+		single_release(file_inode(file), file);
+		file->private_data = NULL;
 	}
-	((struct seq_file *)file->private_data)->buf = buf;
-	((struct seq_file *)file->private_data)->size = size;
-	return 0;
+	return ret;
 }
 EXPORT_SYMBOL(single_open_size);
 
include/linux/seq_file.h +1 -0
index b813b7e63d89..834daff48b7d 100644
@@ -175,6 +175,7 @@ int seq_path_root(struct seq_file *m, const struct path *path,
 void *single_start(struct seq_file *, loff_t *);
 int single_open(struct file *, int (*)(struct seq_file *, void *), void *);
 int single_open_size(struct file *, int (*)(struct seq_file *, void *), void *, size_t);
+int seq_preallocate(struct seq_file *m, size_t size);
 int single_release(struct inode *, struct file *);
 void *__seq_open_private(struct file *, const struct seq_operations *, int);
 int seq_open_private(struct file *, const struct seq_operations *, int);
Signature · 1 line
2.53.0
#139 lore raw

Re: [PATCH RESEND v2 12/23] seq_file: add seq_preallocate()

Sashiko has reviewed this patch and found no issues.
Quoted 8 lines

single_open_size() allocates the buffer itself because it does the single_open() too. A file whose seq_file is opened by somebody else, like procfs does now, needs to do that after the fact. Add seq_preallocate() for that and use it in single_open_size().

No functional changes.

Sashiko has reviewed this patch and found no issues.

Signature · 1 line
Sashiko AI review · https://sashiko.dev/#/patchset/[email protected]?part=12
author maintainer
#140 lore raw

PATCH RESEND v2 13/23 proc: let procfs own the seq_file of /proc/stat

In reply to Christian Brauner

Declare the show function and let procfs open and free the seq_file. ->proc_open() only preallocates the buffer now.

---
 fs/proc/stat.c | 6 ++----
 1 file changed, 2 insertions(+), 4 deletions(-)
fs/proc/stat.c +2 -4
index 79b42f2bfd00..3bfb79edc0f6 100644
@@ -161,15 +161,13 @@ static int stat_open(struct inode *inode, struct file *file)
 
 	/* minimum size to display an interrupt count : 2 bytes */
 	size += 2 * irq_get_nr_irqs();
-	return single_open_size(file, show_stat, NULL, size);
+	return seq_preallocate(file->private_data, size);
 }
 
 static const struct proc_ops stat_proc_ops = {
 	.proc_flags	= PROC_ENTRY_PERMANENT,
+	.proc_show	= show_stat,
 	.proc_open	= stat_open,
-	.proc_read_iter	= seq_read_iter,
-	.proc_lseek	= seq_lseek,
-	.proc_release	= single_release,
 };
 
 static int __init proc_stat_init(void)
Signature · 1 line
2.53.0
#141 lore raw

Re: [PATCH RESEND v2 13/23] proc: let procfs own the seq_file of /proc/stat

Sashiko has reviewed this patch and found no issues.
Quoted 4 lines

Declare the show function and let procfs open and free the seq_file. ->proc_open() only preallocates the buffer now.

Sashiko has reviewed this patch and found no issues.

Signature · 1 line
Sashiko AI review · https://sashiko.dev/#/patchset/[email protected]?part=13
author maintainer
#142 lore raw

PATCH RESEND v2 14/23 proc: let procfs copy in writes before pinning the entry

In reply to Christian Brauner

proc_reg_write() pins the entry and calls ->proc_write() which copies from userspace itself. A page fault in that copy can take as long as the writer wants, just like the copy to userspace of a read, and remove_proc_entry() waits for it.

So do what kernfs does for writes as well. An entry that implements ->proc_write_buf() gets a NUL-terminated kernel copy of what was written. procfs makes that copy before it pins the entry. The copy is capped at ->proc_write_size bytes, or at PAGE_SIZE - 1 like proc_simple_write() if the entry doesn't care. Larger writes fail with -EINVAL. The proc_ops go away with the entry, so procfs remembers the limit in the entry when it is registered, like the size of the seq_file state, instead of pinning the entry just to look up a number.

Entries that take binary data in pieces, like the PCI config space, ALSA's data entries or a firmware image, can ask for PROC_ENTRY_SHORT_WRITES instead. procfs then copies in the first ->proc_write_size bytes and the write comes up short.

->proc_write_buf() gets the position like ->proc_write() so entries that write at an offset keep working.

Note that procfs copies in the whole write before the entry looks at any of it. So a write that is too large or whose buffer can't be read fails before the entry's own checks run, permission checks included, even where the entry only ever looked at the first few bytes.

An entry that implements ->proc_write_buf() and still has a ->proc_write() fails to register.

No users yet.

---
 fs/proc/generic.c       |  8 ++++++++
 fs/proc/inode.c         | 33 +++++++++++++++++++++++++++++++++
 fs/proc/internal.h      | 11 +++++++++++
 include/linux/proc_fs.h | 17 +++++++++++++++++
 4 files changed, 69 insertions(+)
fs/proc/generic.c +8 -0
index 959bf9e33245..4f1f83e9f288 100644
@@ -466,6 +466,14 @@ static int pde_set_flags(struct proc_dir_entry *pde)
 		if (proc_ops->proc_lseek)
 			pde->flags |= PROC_ENTRY_proc_lseek;
 	}
+	if (proc_ops->proc_write_buf) {
+		if (WARN_ON_ONCE(proc_ops->proc_write))
+			return -EINVAL;
+		pde->flags |= PROC_ENTRY_proc_write_buf;
+		pde->write_size = proc_ops->proc_write_size ?: PAGE_SIZE - 1;
+		if (proc_ops->proc_flags & PROC_ENTRY_SHORT_WRITES)
+			pde->flags |= PROC_ENTRY_SHORT_WRITES;
+	}
 	return 0;
 }
 
fs/proc/inode.c +33 -0
index d51ab7548b11..df1caa0f238d 100644
@@ -417,11 +417,44 @@ static ssize_t pde_write(struct proc_dir_entry *pde, struct file *file, const ch
 	return -EIO;
 }
 
+/*
+ * procfs copies in what is written before it pins the entry. A writer that
+ * faults on its buffer then doesn't hold up remove_proc_entry().
+ */
+static ssize_t pde_write_buf(struct proc_dir_entry *pde, struct file *file,
+			     const char __user *ubuf, size_t count, loff_t *ppos)
+{
+	char *buf __free(kvfree) = NULL;
+	size_t size;
+	ssize_t rv;
+
+	size = pde->write_size;
+	if (count > size) {
+		if (!pde_has_short_writes(pde))
+			return -EINVAL;
+		count = size;
+	}
+	buf = kvmalloc(count + 1, GFP_KERNEL);
+	if (!buf)
+		return -ENOMEM;
+	if (copy_from_user(buf, ubuf, count))
+		return -EFAULT;
+	buf[count] = '\0';
+
+	if (!pde_pin(pde))
+		return -EIO;
+	rv = pde->proc_ops->proc_write_buf(file, buf, count, ppos);
+	pde_unpin(pde);
+	return rv;
+}
+
 static ssize_t proc_reg_write(struct file *file, const char __user *buf, size_t count, loff_t *ppos)
 {
 	struct proc_dir_entry *pde = PDE(file_inode(file));
 	ssize_t rv;
 
+	if (pde_has_proc_write_buf(pde))
+		return pde_write_buf(pde, file, buf, count, ppos);
 	if (!pde_pin(pde))
 		return -EIO;
 	rv = pde_write(pde, file, buf, count, ppos);
fs/proc/internal.h +11 -0
index 674e6b4ed21e..da246c5ed4bf 100644
@@ -51,6 +51,7 @@ struct proc_dir_entry {
 	proc_write_t write;
 	void *data;
 	unsigned int state_size;
+	unsigned int write_size;
 	unsigned int low_ino;
 	nlink_t nlink;
 	kuid_t uid;
@@ -109,6 +110,16 @@ static inline bool pde_has_proc_show(const struct proc_dir_entry *pde)
 	return pde->flags & PROC_ENTRY_proc_show;
 }
 
+static inline bool pde_has_proc_write_buf(const struct proc_dir_entry *pde)
+{
+	return pde->flags & PROC_ENTRY_proc_write_buf;
+}
+
+static inline bool pde_has_short_writes(const struct proc_dir_entry *pde)
+{
+	return pde->flags & PROC_ENTRY_SHORT_WRITES;
+}
+
 /* procfs owns the seq_file, see pde_seq_start() */
 static inline bool pde_is_seq_file(const struct proc_dir_entry *pde)
 {
include/linux/proc_fs.h +17 -0
index ea55ed85a2d6..c81c93325044 100644
@@ -31,6 +31,13 @@ enum {
 	PROC_ENTRY_proc_show		= 1U << 5,
 
 	PROC_ENTRY_FORCE_LOOKUP		= 1U << 7,
+	PROC_ENTRY_proc_write_buf	= 1U << 8,
+
+	/*
+	 * Writes larger than ->proc_write_size come up short instead of
+	 * failing with -EINVAL.
+	 */
+	PROC_ENTRY_SHORT_WRITES		= 1U << 9,
 };
 
 struct proc_ops {
@@ -67,6 +74,16 @@ struct proc_ops {
 	const struct seq_operations *proc_seq_ops;
 	int	(*proc_show)(struct seq_file *, void *);
 	unsigned int proc_state_size;
+	/*
+	 * procfs copies what is written into a kernel buffer and calls
+	 * ->proc_write_buf() with it. The buffer is NUL-terminated and holds
+	 * at most ->proc_write_size bytes, PAGE_SIZE - 1 if that's 0. Larger
+	 * writes fail with -EINVAL unless the entry asks for
+	 * PROC_ENTRY_SHORT_WRITES. The position is NULL for a stream, like
+	 * for ->write().
+	 */
+	ssize_t	(*proc_write_buf)(struct file *, char *, size_t, loff_t *);
+	unsigned int proc_write_size;
 } __randomize_layout;
 
 /* definitions for hide_pid field */
Signature · 1 line
2.53.0
#143 lore raw

Re: [PATCH RESEND v2 14/23] proc: let procfs copy in writes before pinning the entry

Hi Christian,

Quoted 27 lines · Christian Brauner

proc_reg_write() pins the entry and calls ->proc_write() which copies from userspace itself. A page fault in that copy can take as long as the writer wants, just like the copy to userspace of a read, and remove_proc_entry() waits for it.

So do what kernfs does for writes as well. An entry that implements ->proc_write_buf() gets a NUL-terminated kernel copy of what was written. procfs makes that copy before it pins the entry. The copy is capped at ->proc_write_size bytes, or at PAGE_SIZE - 1 like proc_simple_write() if the entry doesn't care. Larger writes fail with -EINVAL. The proc_ops go away with the entry, so procfs remembers the limit in the entry when it is registered, like the size of the seq_file state, instead of pinning the entry just to look up a number.

Entries that take binary data in pieces, like the PCI config space, ALSA's data entries or a firmware image, can ask for PROC_ENTRY_SHORT_WRITES instead. procfs then copies in the first ->proc_write_size bytes and the write comes up short.

->proc_write_buf() gets the position like ->proc_write() so entries that write at an offset keep working.

Note that procfs copies in the whole write before the entry looks at any of it. So a write that is too large or whose buffer can't be read fails before the entry's own checks run, permission checks included, even where the entry only ever looked at the first few bytes.

Quoted 6 lines

An entry that implements ->proc_write_buf() and still has a ->proc_write() fails to register.

No users yet.

Thanks for your patch!

Quoted 5 lines
include/linux/proc_fs.h +0 -0
@@ -67,6 +74,16 @@ struct proc_ops {
        const struct seq_operations *proc_seq_ops;
        int     (*proc_show)(struct seq_file *, void *);

include/linux/proc_fs.h struct proc_ops { · line 85

Quoted 10 lines
include/linux/proc_fs.h +9 -0
        unsigned int proc_state_size;
+       /*
+        * procfs copies what is written into a kernel buffer and calls
+        * ->proc_write_buf() with it. The buffer is NUL-terminated and holds
+        * at most ->proc_write_size bytes, PAGE_SIZE - 1 if that's 0. Larger
+        * writes fail with -EINVAL unless the entry asks for
+        * PROC_ENTRY_SHORT_WRITES. The position is NULL for a stream, like
+        * for ->write().
+        */
+       ssize_t (*proc_write_buf)(struct file *, char *, size_t, loff_t *);

"const char *"?

Seems like you have to drop several const attributes during the conversion from "const char __user *buf" to "char *buf".

While at it, I think it would be good to use this conversion as an opportunity to replace "char *" by "void *", which will probably let you drop several casts from users.

include/linux/proc_fs.h struct proc_ops { · line 89

Quoted 5 lines
include/linux/proc_fs.h +1 -0
+       unsigned int proc_write_size;
 } __randomize_layout;
 
 /* definitions for hide_pid field */

Gr{oetje,eeting}s,

Geert

--
Geert Uytterhoeven -- There's lots of Linux beyond ia32 -- [email protected]

In personal conversations with technical people, I call myself a hacker. But when I'm talking to journalists I just say "programmer" or something like that.
-- Linus Torvalds

author maintainer
#144 lore raw

Re: [PATCH RESEND v2 14/23] proc: let procfs copy in writes before pinning the entry

Quoted 3 lines · Geert Uytterhoeven
Quoted 1 line

+ ssize_t (*proc_write_buf)(struct file *, char *, size_t, loff_t *);

"const char *"?

I prototyped this to have a detailed reply. It's not worth it.

* The buffer is the entry's private copy.
procfs creates the copy for this specific call and frees it afterwards.

A bunch of handlers modify the buffer in place and it's documented as allowed:

- afs_proc_cells_write()
- afs_proc_sysname_write
- a chunk of the sunrpc cache channel ->cache_parse() implementations
- thinkpad_acpi's ->write() methods
- SCSI devinfo file
- dyndbg
- cio_ignore
- the pseries ofdt parsers
- two more hand the buffer to a char * interface:
- the SCSI host ->write_info()
- simple_strtoul() in proc_scsi_write()
- four strip a trailing newline in place

All ways to make that work suck.

(1) Copy in the handler. That means eight kmemdup_nul()s and a kvmemdup() for every nfs downcall.
IOW the copy this series just removed comes back as a copy of a copy which is not acceptable.

(2) Make the parsers work on spans which also sucks and doesn't solve all of them.

(3) Leave the buffer writable. Costs nothing, nobody else can see it.

So (3) I think char * stays.

Quoted 3 lines

While at it, I think it would be good to use this conversion as an opportunity to replace "char *" by "void *", which will probably let you drop several casts from users.

So I tried that too. The thing is it drops exactly one u8 * cast in ntfs3's label write. And to get this done we need to introduce a whole range of local char *foo = arg assignments. So I decided against this. It just doesn't add value.

Thanks for taking a look!

#145 lore raw

Re: [PATCH RESEND v2 14/23] proc: let procfs copy in writes before pinning the entry

Quoted 6 lines · On Sat, 7 Nov 2026 10:48:35 +0100 Christian Brauner <[email protected]> wrote:
Quoted 3 lines

While at it, I think it would be good to use this conversion as an opportunity to replace "char *" by "void *", which will probably let you drop several casts from users.

So I tried that too. The thing is it drops exactly one u8 * cast in ntfs3's label write.

Since char is now unsigned that one isn't even needed...

David

#146 lore raw

Re: [PATCH RESEND v2 14/23] proc: let procfs copy in writes before pinning the entry

Quoted 8 lines · David Laight
Quoted 6 lines
Quoted 3 lines

While at it, I think it would be good to use this conversion as an opportunity to replace "char *" by "void *", which will probably let you drop several casts from users.

So I tried that too. The thing is it drops exactly one u8 * cast in ntfs3's label write.

Since char is now unsigned that one isn't even needed...

Please excuse me missing the context, but what circumstances does your
claim refer to?

Maciej

#147 lore raw

Re: [PATCH RESEND v2 14/23] proc: let procfs copy in writes before pinning the entry

Quoted 6 lines · On Mon, 9 Nov 2026 05:05:57 +0000 (GMT) "Maciej W. Rozycki"…
Quoted 4 lines · David Laight
Quoted 4 lines
Quoted 3 lines

While at it, I think it would be good to use this conversion as an opportunity to replace "char *" by "void *", which will probably let you drop several casts from users.

Quoted 7 lines
Quoted 4 lines
Quoted 2 lines

So I tried that too. The thing is it drops exactly one u8 * cast in ntfs3's label write.

Since char is now unsigned that one isn't even needed...

Please excuse me missing the context, but what circumstances does your
claim refer to?

Just that the cast would have to be:

	u8 *foo = (u8 *)bar;

where 'bar' is 'char *', and I don't think you need a cast there when char is unsigned.

David

Quoted 3 lines

Maciej

#148 lore raw

Re: [PATCH RESEND v2 14/23] proc: let procfs copy in writes before pinning the entry

Quoted 5 lines · David Laight

Just that the cast would have to be:

        u8 *foo = (u8 *)bar;

where 'bar' is 'char *', and I don't think you need a cast there when char is unsigned.

.. and just to clarify: 'char' is always unsigned in the kernel on all architectures since commit 3bc753c06dd0 ("kbuild: treat char as always unsigned") back four years ago...

Linus

#149 lore raw

Re: [PATCH RESEND v2 14/23] proc: let procfs copy in writes before pinning the entry

Quoted 8 lines · Linus Torvalds
Quoted 4 lines

Just that the cast would have to be:

        u8 *foo = (u8 *)bar;

where 'bar' is 'char *', and I don't think you need a cast there when char is unsigned.

.. and just to clarify: 'char' is always unsigned in the kernel on all architectures since commit 3bc753c06dd0 ("kbuild: treat char as always unsigned") back four years ago...

Thanks, yes, that's the piece of the context I was missing. I've since
actually come across this commit while investigating which Linux ports have plain `char' signed in the psABI (MIPS for sure).

Maciej

#150 lore raw

Re: [PATCH RESEND v2 14/23] proc: let procfs copy in writes before pinning the entry

In reply to Christian Brauner
Thank you for your contribution! Sashiko AI review found 1 potential issue(s) to consider: - [Low] proc: split __free(kvfree) declaration and initialization in pde_write_buf() --

Thank you for your contribution! Sashiko AI review found 1 potential issue(s) to consider:
- [Low] proc: split __free(kvfree) declaration and initialization in pde_write_buf() --

commit e52627c4b4d80d32822781f143a8c1245bd64a2c
Author: Christian Brauner <[email protected]>

proc: let procfs copy in writes before pinning the entry

This commit introduces a ->proc_write_buf() callback in struct proc_ops so that procfs can copy write data from userspace into a NUL-terminated kernel buffer before pinning the proc_dir_entry. This prevents userspace page faults during write copies from blocking remove_proc_entry().

Quoted 16 lines
fs/proc/inode.c +8 -0
index d51ab7548b117..df1caa0f238df 100644
@@ -417,11 +417,44 @@ static ssize_t pde_write(struct proc_dir_entry *pde, struct file *file, const ch
 	return -EIO;
 }
 
+/*
+ * procfs copies in what is written before it pins the entry. A writer that
+ * faults on its buffer then doesn't hold up remove_proc_entry().
+ */
+static ssize_t pde_write_buf(struct proc_dir_entry *pde, struct file *file,
+			     const char __user *ubuf, size_t count, loff_t *ppos)
+{
+	char *buf __free(kvfree) = NULL;

fs/proc/inode.c static ssize_t pde_write(struct proc_dir_entry *pde, struct file *file, const ch · line 437

Quoted 10 lines
fs/proc/inode.c +10 -0
+	size_t size;
+	ssize_t rv;
+
+	size = pde->write_size;
+	if (count > size) {
+		if (!pde_has_short_writes(pde))
+			return -EINVAL;
+		count = size;
+	}
+	buf = kvmalloc(count + 1, GFP_KERNEL);

[Severity: Low]
As reported by Sashiko on RFC [1], this isn't a bug, but in pde_write_buf() (called from proc_reg_write()), buf is declared with __free(kvfree) = NULL at the top of the function and assigned later with kvmalloc() after the count > size check.

Per the Cleanup API conventions in include/linux/cleanup.h, should buf be defined and initialized in a single statement at the allocation site:

	char *buf __free(kvfree) = kvmalloc(count + 1, GFP_KERNEL);

after validating count?

[1] https://lore.kernel.org/r/[email protected]

Signature · 1 line
Sashiko AI review · https://sashiko.dev/#/patchset/[email protected]?part=14
author maintainer
#151 lore raw

PATCH RESEND v2 15/23 proc: copy in writes to the network namespace entries before pinning

In reply to Christian Brauner

proc_simple_write() already hands ->write() a kernel copy of what was written but makes that copy with the entry pinned. Let procfs make it before it pins the entry instead. That covers everything created with proc_create_net_data_write() and proc_create_net_single_write(), the afs files and the rxrpc stats.

So a write to a proc_create_net_single() file without ->write() can fail with -EINVAL or -EFAULT now before proc_simple_write() gets to refuse it with -EACCES.

---
 fs/proc/generic.c  | 15 ++++-----------
 fs/proc/internal.h |  2 +-
 fs/proc/proc_net.c |  4 ++--
 3 files changed, 7 insertions(+), 14 deletions(-)
fs/proc/generic.c +4 -11
index 4f1f83e9f288..5e2ed5a04ec9 100644
@@ -947,26 +947,19 @@ void proc_remove(struct proc_dir_entry *de)
 EXPORT_SYMBOL(proc_remove);
 
 /*
- * Pull a user buffer into memory and pass it to the file's write handler if
- * one is supplied.  The ->write() method is permitted to modify the
- * kernel-side buffer.
+ * Pass what was written to the file's write handler if one is supplied. The
+ * ->write() method is permitted to modify the buffer.
  */
-ssize_t proc_simple_write(struct file *f, const char __user *ubuf, size_t size,
-			  loff_t *_pos)
+ssize_t proc_simple_write(struct file *f, char *buf, size_t size, loff_t *_pos)
 {
 	struct proc_dir_entry *pde = PDE(file_inode(f));
-	char *buf;
 	int ret;
 
 	if (!pde->write)
 		return -EACCES;
-	if (size == 0 || size > PAGE_SIZE - 1)
+	if (size == 0)
 		return -EINVAL;
-	buf = memdup_user_nul(ubuf, size);
-	if (IS_ERR(buf))
-		return PTR_ERR(buf);
 	ret = pde->write(f, buf, size);
-	kfree(buf);
 	return ret == 0 ? size : ret;
 }
 
fs/proc/internal.h +1 -1
index da246c5ed4bf..1d36fe4b1af5 100644
@@ -344,7 +344,7 @@ static inline bool is_empty_pde(const struct proc_dir_entry *pde)
 {
 	return S_ISDIR(pde->mode) && !pde->proc_iops;
 }
-extern ssize_t proc_simple_write(struct file *, const char __user *, size_t, loff_t *);
+extern ssize_t proc_simple_write(struct file *, char *, size_t, loff_t *);
 
 /*
  * inode.c
fs/proc/proc_net.c +2 -2
index 9973f846c467..b78d627b024f 100644
@@ -77,7 +77,7 @@ static int seq_release_net(struct inode *ino, struct file *f)
 
 static const struct proc_ops proc_net_seq_ops = {
 	.proc_open	= seq_open_net,
-	.proc_write	= proc_simple_write,
+	.proc_write_buf	= proc_simple_write,
 	.proc_release	= seq_release_net,
 };
 
@@ -186,7 +186,7 @@ static int single_release_net(struct inode *ino, struct file *f)
 
 static const struct proc_ops proc_net_single_ops = {
 	.proc_open	= single_open_net,
-	.proc_write	= proc_simple_write,
+	.proc_write_buf	= proc_simple_write,
 	.proc_release	= single_release_net,
 };
 
Signature · 1 line
2.53.0
#152 lore raw

Re: [PATCH RESEND v2 15/23] proc: copy in writes to the network namespace entries before pinning

Sashiko has reviewed this patch and found no issues.
Quoted 11 lines

proc_simple_write() already hands ->write() a kernel copy of what was written but makes that copy with the entry pinned. Let procfs make it before it pins the entry instead. That covers everything created with proc_create_net_data_write() and proc_create_net_single_write(), the afs files and the rxrpc stats.

So a write to a proc_create_net_single() file without ->write() can fail with -EINVAL or -EFAULT now before proc_simple_write() gets to refuse it with -EACCES.

Sashiko has reviewed this patch and found no issues.

Signature · 1 line
Sashiko AI review · https://sashiko.dev/#/patchset/[email protected]?part=15
author maintainer
#153 lore raw

PATCH RESEND v2 16/23 proc: let procfs copy out reads that don't go through seq_file

In reply to Christian Brauner

proc_reg_read() and proc_reg_read_iter() pin the entry and call ->proc_read() or ->proc_read_iter() which copy to userspace themselves. Like for seq_file reads and for writes, a reader can make a page fault in that copy take as long as it wants and remove_proc_entry() waits for it.

So do what kernfs does for these reads as well. An entry that implements ->proc_read_buf() fills a kernel buffer of at most ->proc_read_size bytes, a page if the entry doesn't care, and procfs copies it to userspace after unpinning the entry. The entry moves the position like it did for ->proc_read() but that only sticks if the copy to userspace worked, like in kernfs_file_read_iter(). If the copy fails halfway the read fails with -EFAULT and the position stays, where simple_read_from_buffer() returned what it had copied until then. procfs remembers ->proc_read_size in the entry like ->proc_write_size.

Larger reads come up short, like with kernfs. An entry whose readers want all of a large file in one read asks for PROC_ENTRY_FULL_READS and procfs fills the read in pieces of ->proc_read_size, unpinning the entry in between. A piece whose copy fails ends the read with what the pieces before it returned. kexec-tools treats any short read of /proc/vmcore as fatal for example (cf. [1]).

These entries are read through ->read_iter() so readv(), splice(), aio, the RWF flags, kernel_read() and io_uring work for them like for the ->proc_read_iter() ones. io_uring's nonblocking attempt gets -EAGAIN though, like loop_rw_iter() gave it for ->proc_read() entries. Neither the allocation nor the entry can honor IOCB_NOWAIT, and io_uring would take a short read of a record file for an unfinished one and glue the next record to it. So it retries from a worker like before.

An entry that implements ->proc_read_buf() and also declares a seq_file or one of the other read methods fails to register.

No users yet.

[1]: https://git.kernel.org/pub/scm/utils/kernel/kexec/kexec-tools.git/tree/util_lib/elf_info.c

---
 fs/proc/generic.c       |  9 ++++++++
 fs/proc/inode.c         | 60 ++++++++++++++++++++++++++++++++++++++++++++++++-
 fs/proc/internal.h      | 11 +++++++++
 include/linux/proc_fs.h | 16 +++++++++++++
 4 files changed, 95 insertions(+), 1 deletion(-)
fs/proc/generic.c +9 -0
index 5e2ed5a04ec9..2d503250de75 100644
@@ -474,6 +474,15 @@ static int pde_set_flags(struct proc_dir_entry *pde)
 		if (proc_ops->proc_flags & PROC_ENTRY_SHORT_WRITES)
 			pde->flags |= PROC_ENTRY_SHORT_WRITES;
 	}
+	if (proc_ops->proc_read_buf) {
+		if (WARN_ON_ONCE(pde_is_seq_file(pde) || proc_ops->proc_read ||
+				 proc_ops->proc_read_iter))
+			return -EINVAL;
+		pde->flags |= PROC_ENTRY_proc_read_buf;
+		pde->read_size = proc_ops->proc_read_size ?: PAGE_SIZE;
+		if (proc_ops->proc_flags & PROC_ENTRY_FULL_READS)
+			pde->flags |= PROC_ENTRY_FULL_READS;
+	}
 	return 0;
 }
 
fs/proc/inode.c +59 -1

83 lines not on this page · raw message

fs/proc/internal.h +11 -0
index 1d36fe4b1af5..b5c78f4f392c 100644
@@ -52,6 +52,7 @@ struct proc_dir_entry {
 	void *data;
 	unsigned int state_size;
 	unsigned int write_size;
+	unsigned int read_size;
 	unsigned int low_ino;
 	nlink_t nlink;
 	kuid_t uid;
@@ -120,6 +121,16 @@ static inline bool pde_has_short_writes(const struct proc_dir_entry *pde)
 	return pde->flags & PROC_ENTRY_SHORT_WRITES;
 }
 
+static inline bool pde_has_proc_read_buf(const struct proc_dir_entry *pde)
+{
+	return pde->flags & PROC_ENTRY_proc_read_buf;
+}
+
+static inline bool pde_has_full_reads(const struct proc_dir_entry *pde)
+{
+	return pde->flags & PROC_ENTRY_FULL_READS;
+}
+
 /* procfs owns the seq_file, see pde_seq_start() */
 static inline bool pde_is_seq_file(const struct proc_dir_entry *pde)
 {
include/linux/proc_fs.h +16 -0
index c81c93325044..0f0997898ba3 100644
@@ -38,6 +38,13 @@ enum {
 	 * failing with -EINVAL.
 	 */
 	PROC_ENTRY_SHORT_WRITES		= 1U << 9,
+	PROC_ENTRY_proc_read_buf	= 1U << 10,
+
+	/*
+	 * Reads larger than ->proc_read_size are filled in pieces instead of
+	 * coming up short.
+	 */
+	PROC_ENTRY_FULL_READS		= 1U << 11,
 };
 
 struct proc_ops {
@@ -84,6 +91,15 @@ struct proc_ops {
 	 */
 	ssize_t	(*proc_write_buf)(struct file *, char *, size_t, loff_t *);
 	unsigned int proc_write_size;
+	/*
+	 * procfs calls ->proc_read_buf() to fill a kernel buffer of at most
+	 * ->proc_read_size bytes, PAGE_SIZE if that's 0, and copies it to
+	 * userspace afterwards. Larger reads come up short unless the entry
+	 * asks for PROC_ENTRY_FULL_READS. The position the entry moves to only
+	 * sticks if the copy works.
+	 */
+	ssize_t	(*proc_read_buf)(struct file *, char *, size_t, loff_t *);
+	unsigned int proc_read_size;
 } __randomize_layout;
 
 /* definitions for hide_pid field */
Signature · 1 line
2.53.0
#154 lore raw

Re: [PATCH RESEND v2 16/23] proc: let procfs copy out reads that don't go through seq_file

Hi Christian,

Quoted 31 lines · Christian Brauner

proc_reg_read() and proc_reg_read_iter() pin the entry and call ->proc_read() or ->proc_read_iter() which copy to userspace themselves. Like for seq_file reads and for writes, a reader can make a page fault in that copy take as long as it wants and remove_proc_entry() waits for it.

So do what kernfs does for these reads as well. An entry that implements ->proc_read_buf() fills a kernel buffer of at most ->proc_read_size bytes, a page if the entry doesn't care, and procfs copies it to userspace after unpinning the entry. The entry moves the position like it did for ->proc_read() but that only sticks if the copy to userspace worked, like in kernfs_file_read_iter(). If the copy fails halfway the read fails with -EFAULT and the position stays, where simple_read_from_buffer() returned what it had copied until then. procfs remembers ->proc_read_size in the entry like ->proc_write_size.

Larger reads come up short, like with kernfs. An entry whose readers want all of a large file in one read asks for PROC_ENTRY_FULL_READS and procfs fills the read in pieces of ->proc_read_size, unpinning the entry in between. A piece whose copy fails ends the read with what the pieces before it returned. kexec-tools treats any short read of /proc/vmcore as fatal for example (cf. [1]).

These entries are read through ->read_iter() so readv(), splice(), aio, the RWF flags, kernel_read() and io_uring work for them like for the ->proc_read_iter() ones. io_uring's nonblocking attempt gets -EAGAIN though, like loop_rw_iter() gave it for ->proc_read() entries. Neither the allocation nor the entry can honor IOCB_NOWAIT, and io_uring would take a short read of a record file for an unfinished one and glue the next record to it. So it retries from a worker like before.

Quoted 8 lines

An entry that implements ->proc_read_buf() and also declares a seq_file or one of the other read methods fails to register.

No users yet.

[1]: https://git.kernel.org/pub/scm/utils/kernel/kexec/kexec-tools.git/tree/util_lib/elf_info.c

Thanks for your patch!

Quoted 5 lines
include/linux/proc_fs.h +0 -0
@@ -84,6 +91,15 @@ struct proc_ops {
         */

include/linux/proc_fs.h struct proc_ops { · line 101

Quoted 10 lines
include/linux/proc_fs.h +8 -0
        ssize_t (*proc_write_buf)(struct file *, char *, size_t, loff_t *);
        unsigned int proc_write_size;
+       /*
+        * procfs calls ->proc_read_buf() to fill a kernel buffer of at most
+        * ->proc_read_size bytes, PAGE_SIZE if that's 0, and copies it to
+        * userspace afterwards. Larger reads come up short unless the entry
+        * asks for PROC_ENTRY_FULL_READS. The position the entry moves to only
+        * sticks if the copy works.
+        */
+       ssize_t (*proc_read_buf)(struct file *, char *, size_t, loff_t *);

As for proc_write_buf, I think it would be good to use this conversion as an opportunity to replace "char *" by "void *", which will probably let you drop several casts from users.

include/linux/proc_fs.h struct proc_ops { · line 105

Quoted 5 lines
include/linux/proc_fs.h +1 -0
+       unsigned int proc_read_size;
 } __randomize_layout;
 
 /* definitions for hide_pid field */

Gr{oetje,eeting}s,

Geert

--
Geert Uytterhoeven -- There's lots of Linux beyond ia32 -- [email protected]

In personal conversations with technical people, I call myself a hacker. But when I'm talking to journalists I just say "programmer" or something like that.
-- Linus Torvalds

#155 lore raw

Re: [PATCH RESEND v2 16/23] proc: let procfs copy out reads that don't go through seq_file

In reply to Christian Brauner
Thank you for your contribution! Sashiko AI review found 1 potential issue(s) to consider: - [Low] proc: define and initialize __free(kvfree) variable buf in pde_read_buf() --

Thank you for your contribution! Sashiko AI review found 1 potential issue(s) to consider:
- [Low] proc: define and initialize __free(kvfree) variable buf in pde_read_buf() --

commit 19cf278eb9fee57b90ee19764f6b076d9cab553d
Author: Christian Brauner <[email protected]>

proc: let procfs copy out reads that don't go through seq_file

This commit adds ->proc_read_buf() and PROC_ENTRY_FULL_READS to proc_ops so that non-seq_file procfs entries can fill a kernel buffer while pinned and let procfs copy it to userspace after unpinning the entry.

Quoted 4 lines
fs/proc/inode.c +0 -0
index df1caa0f238df..caa47933c233d 100644

[ ... ]

Quoted 15 lines
fs/proc/inode.c +11 -0
@@ -377,11 +379,67 @@ static loff_t proc_reg_llseek(struct file *file, loff_t offset, int whence)
 	return rv;
 }
 
+/*
+ * The entry fills a kernel buffer and procfs copies that to userspace after
+ * unpinning the entry. A reader that faults on its buffer then doesn't hold
+ * up remove_proc_entry().
+ */
+static ssize_t pde_read_buf(struct proc_dir_entry *pde, struct kiocb *iocb,
+			    struct iov_iter *iter)
+{
+	struct file *file = iocb->ki_filp;
+	char *buf __free(kvfree) = NULL;
+	ssize_t rv, done = 0;

fs/proc/inode.c static loff_t proc_reg_llseek(struct file *file, loff_t offset, int whence) · line 402

Quoted 10 lines
fs/proc/inode.c +10 -0
+	size_t len, count;
+	loff_t pos;
+
+	if (!iov_iter_count(iter))
+		return 0;
+	/* neither the allocation nor the entry can honor IOCB_NOWAIT */
+	if ((iocb->ki_flags & IOCB_NOWAIT) && !(file->f_flags & O_NONBLOCK))
+		return -EAGAIN;
+	len = min_t(size_t, iov_iter_count(iter), pde->read_size);
+	buf = kvmalloc(len, GFP_KERNEL);

[Severity: Low]
As reported by Sashiko on RFC [1], this isn't a bug, but in pde_read_buf() in fs/proc/inode.c, buf is declared with __free(kvfree) = NULL at the top of the function before the early returns and then assigned later at the kvmalloc() call. Could buf be defined and initialized in a single statement at the allocation site:

	char *buf __free(kvfree) = kvmalloc(len, GFP_KERNEL);

to follow the cleanup.h conventions?

[1] https://lore.kernel.org/r/[email protected]

Signature · 1 line
Sashiko AI review · https://sashiko.dev/#/patchset/[email protected]?part=16
author maintainer
#156 lore raw

PATCH RESEND v2 17/23 fs/proc/vmcore: let procfs copy out reads

In reply to Christian Brauner

Implement ->proc_read_buf() so procfs copies what is read to userspace after it unpinned the entry. __read_vmcore() fills procfs' buffer through a kvec iov_iter. So a read goes through that buffer now instead of straight from the old memory into the reader's, which is what splice() did already. mmap() isn't affected. On ppc64 a machine check while reading the old memory used to be recovered through the exception table of copy_to_user(), by accident. copy_oldmem_page() copies with _copy_mc_to_iter() now, so a read through procfs' buffer recovers from it as well.

The buffer is 128k, which keeps the entry pinned for one such piece at a time, and /proc/vmcore asks for PROC_ENTRY_FULL_READS so that a larger read is filled in pieces. kexec-tools treats a short read of it as fatal. A read that faults on its buffer in a later piece returns the pieces before it now instead of failing with -EFAULT. fadump removes /proc/vmcore when its memory is released and that no longer waits for a reader that faults on its buffer.

---
 fs/proc/vmcore.c | 14 +++++++++++---
 1 file changed, 11 insertions(+), 3 deletions(-)
fs/proc/vmcore.c +11 -3
index ccb795b85509..1c1e71231f4e 100644
@@ -27,6 +27,7 @@
 #include <linux/mutex.h>
 #include <linux/vmalloc.h>
 #include <linux/pagemap.h>
+#include <linux/sizes.h>
 #include <linux/uio.h>
 #include <linux/cc_platform.h>
 #include <asm/io.h>
@@ -427,9 +428,14 @@ static ssize_t __read_vmcore(struct iov_iter *iter, loff_t *fpos)
 	return acc;
 }
 
-static ssize_t read_vmcore(struct kiocb *iocb, struct iov_iter *iter)
+static ssize_t read_vmcore(struct file *file, char *buf, size_t count,
+			   loff_t *ppos)
 {
-	return __read_vmcore(iter, &iocb->ki_pos);
+	struct kvec kvec = { .iov_base = buf, .iov_len = count };
+	struct iov_iter iter;
+
+	iov_iter_kvec(&iter, ITER_DEST, &kvec, 1, count);
+	return __read_vmcore(&iter, ppos);
 }
 
 /**
@@ -709,9 +715,11 @@ static int mmap_vmcore(struct file *file, struct vm_area_struct *vma)
 #endif
 
 static const struct proc_ops vmcore_proc_ops = {
+	.proc_flags	= PROC_ENTRY_FULL_READS,
 	.proc_open	= open_vmcore,
 	.proc_release	= release_vmcore,
-	.proc_read_iter	= read_vmcore,
+	.proc_read_buf	= read_vmcore,
+	.proc_read_size	= SZ_128K,
 	.proc_lseek	= default_llseek,
 	.proc_mmap	= mmap_vmcore,
 };
Signature · 1 line
2.53.0
#157 lore raw

Re: [PATCH RESEND v2 17/23] fs/proc/vmcore: let procfs copy out reads

Sashiko has reviewed this patch and found no issues.
Quoted 18 lines

Implement ->proc_read_buf() so procfs copies what is read to userspace after it unpinned the entry. __read_vmcore() fills procfs' buffer through a kvec iov_iter. So a read goes through that buffer now instead of straight from the old memory into the reader's, which is what splice() did already. mmap() isn't affected. On ppc64 a machine check while reading the old memory used to be recovered through the exception table of copy_to_user(), by accident. copy_oldmem_page() copies with _copy_mc_to_iter() now, so a read through procfs' buffer recovers from it as well.

The buffer is 128k, which keeps the entry pinned for one such piece at a time, and /proc/vmcore asks for PROC_ENTRY_FULL_READS so that a larger read is filled in pieces. kexec-tools treats a short read of it as fatal. A read that faults on its buffer in a later piece returns the pieces before it now instead of failing with -EFAULT. fadump removes /proc/vmcore when its memory is released and that no longer waits for a reader that faults on its buffer.

Quoted 1 line

Sashiko has reviewed this patch and found no issues.

Signature · 1 line
Sashiko AI review · https://sashiko.dev/#/patchset/[email protected]?part=17
author maintainer
#158 lore raw

PATCH RESEND v2 18/23 proc: let procfs copy ioctl arguments in and out

In reply to Christian Brauner

proc_reg_unlocked_ioctl() pins the entry and calls ->proc_ioctl() which copies its argument from and to userspace itself. Like for reads and writes, an ioctl can make a page fault in those copies take as long as it wants and remove_proc_entry() waits for it.

The command number doesn't reliably say what an ioctl copies. Some of the procfs ones aren't encoded at all, like the PCI ones or esas2r's, and i8k's encode the wrong sizes. So keep a table of the commands, like DRM keeps one of its ioctls, and let it say what each command copies. An entry that implements ->proc_ioctl_buf() lists its commands in ->proc_ioctl_args with the number of bytes that go in and that come back out. procfs copies the argument in before it pins the entry, calls ->proc_ioctl_buf() with that kernel copy and copies it back out after unpinning the entry if the ioctl succeeded. A command that copies neither gets its argument as is, a command that isn't in the table fails with -ENOTTY. PROC_IOCTL_IOC() fills in an entry from a command that encodes its argument.

Note that, like for writes, procfs copies the argument in before the entry's own checks run, permission checks included. So a bad pointer fails with -EFAULT where the entry used to say -EPERM first.

The table lives with the proc_ops, which go away with the entry, so procfs pins the entry to look the command up and lets go of it again before it copies anything. 32-bit tasks go through the same table with their pointer converted by compat_ptr(). An entry that implements ->proc_ioctl_buf() and still has a ->proc_ioctl() or a ->proc_compat_ioctl() fails to register, and so does one that lists commands without implementing it or implements it without listing any.

No users yet.

---
 fs/proc/generic.c       | 17 +++++++++++++++
 fs/proc/inode.c         | 58 +++++++++++++++++++++++++++++++++++++++++++++++++
 fs/proc/internal.h      |  5 +++++
 include/linux/proc_fs.h | 35 +++++++++++++++++++++++++++++
 4 files changed, 115 insertions(+)
fs/proc/generic.c +17 -0
index 2d503250de75..1bad3b068d53 100644
@@ -483,6 +483,23 @@ static int pde_set_flags(struct proc_dir_entry *pde)
 		if (proc_ops->proc_flags & PROC_ENTRY_FULL_READS)
 			pde->flags |= PROC_ENTRY_FULL_READS;
 	}
+	if (proc_ops->proc_ioctl_buf) {
+		if (WARN_ON_ONCE(proc_ops->proc_ioctl))
+			return -EINVAL;
+#ifdef CONFIG_COMPAT
+		/* 32-bit tasks go through the table as well */
+		if (WARN_ON_ONCE(proc_ops->proc_compat_ioctl))
+			return -EINVAL;
+#endif
+		/* the table says what procfs copies, see pde_ioctl_arg() */
+		if (WARN_ON_ONCE(!proc_ops->proc_ioctl_args ||
+				 !proc_ops->proc_nr_ioctl_args))
+			return -EINVAL;
+		pde->flags |= PROC_ENTRY_proc_ioctl_buf;
+	} else if (WARN_ON_ONCE(proc_ops->proc_ioctl_args ||
+				proc_ops->proc_nr_ioctl_args)) {
+		return -EINVAL;
+	}
 	return 0;
 }
 
fs/proc/inode.c +58 -0

81 lines not on this page · raw message

fs/proc/internal.h +5 -0
index b5c78f4f392c..ae0f9779cf1b 100644
@@ -131,6 +131,11 @@ static inline bool pde_has_full_reads(const struct proc_dir_entry *pde)
 	return pde->flags & PROC_ENTRY_FULL_READS;
 }
 
+static inline bool pde_has_proc_ioctl_buf(const struct proc_dir_entry *pde)
+{
+	return pde->flags & PROC_ENTRY_proc_ioctl_buf;
+}
+
 /* procfs owns the seq_file, see pde_seq_start() */
 static inline bool pde_is_seq_file(const struct proc_dir_entry *pde)
 {
include/linux/proc_fs.h +35 -0
index 0f0997898ba3..2ba4e4a39e13 100644
@@ -8,6 +8,7 @@
 #include <linux/compiler.h>
 #include <linux/types.h>
 #include <linux/fs.h>
+#include <linux/ioctl.h>
 
 struct proc_dir_entry;
 struct seq_file;
@@ -45,8 +46,29 @@ enum {
 	 * coming up short.
 	 */
 	PROC_ENTRY_FULL_READS		= 1U << 11,
+	PROC_ENTRY_proc_ioctl_buf	= 1U << 12,
 };
 
+/*
+ * How many bytes of the argument of @cmd procfs copies in before calling
+ * ->proc_ioctl_buf() and copies back out after it. A command that copies
+ * neither gets its argument as is.
+ */
+struct proc_ioctl_arg {
+	unsigned int cmd;
+	unsigned int in;
+	unsigned int out;
+};
+
+#define PROC_IOCTL_ARG(_cmd, _in, _out) \
+	{ .cmd = (_cmd), .in = (_in), .out = (_out) }
+
+/* A command that encodes the size and direction of its argument. */
+#define PROC_IOCTL_IOC(_cmd)						\
+	PROC_IOCTL_ARG(_cmd,						\
+		       (_IOC_DIR(_cmd) & _IOC_WRITE) ? _IOC_SIZE(_cmd) : 0, \
+		       (_IOC_DIR(_cmd) & _IOC_READ) ? _IOC_SIZE(_cmd) : 0)
+
 struct proc_ops {
 	unsigned int proc_flags;
 	int	(*proc_open)(struct inode *, struct file *);
@@ -100,6 +122,19 @@ struct proc_ops {
 	 */
 	ssize_t	(*proc_read_buf)(struct file *, char *, size_t, loff_t *);
 	unsigned int proc_read_size;
+	/*
+	 * procfs looks the command up in ->proc_ioctl_args, copies in what it
+	 * passes before pinning the entry, calls ->proc_ioctl_buf() with that
+	 * copy and copies out what it returns after unpinning the entry.
+	 * Commands that aren't in the table fail with -ENOTTY. 32-bit tasks
+	 * go through the same table. The copy is zeroed and as large as the
+	 * larger of the two sizes, it only goes back out if the ioctl
+	 * succeeded, and a command that copies neither gets its argument as
+	 * is.
+	 */
+	long	(*proc_ioctl_buf)(struct file *, unsigned int, void *);
+	const struct proc_ioctl_arg *proc_ioctl_args;
+	unsigned int proc_nr_ioctl_args;
 } __randomize_layout;
 
 /* definitions for hide_pid field */
Signature · 1 line
2.53.0
#159 lore raw

Re: [PATCH RESEND v2 18/23] proc: let procfs copy ioctl arguments in and out

Thank you for your contribution! Sashiko AI review found 1 potential issue(s) to consider: - [Low] proc: __free() variable buf declared at top of pde_ioctl_buf() --

Thank you for your contribution! Sashiko AI review found 1 potential issue(s) to consider:
- [Low] proc: __free() variable buf declared at top of pde_ioctl_buf()
--

commit 56830294f9ddc9f5679014810e7198455a39f42c
Author: Christian Brauner <[email protected]>

proc: let procfs copy ioctl arguments in and out

This commit adds support for ->proc_ioctl_buf() and ->proc_ioctl_args in struct proc_ops so that procfs can copy ioctl arguments from and to userspace without holding the proc_dir_entry pinned across user copies.

Quoted 4 lines
fs/proc/inode.c +0 -0
index caa47933c233d..717cbaad65df2 100644

[ ... ]

Quoted 4 lines
fs/proc/inode.c +0 -0
@@ -548,11 +549,66 @@ static long pde_ioctl(struct proc_dir_entry *pde, struct file *file, unsigned in
 	return -ENOTTY;
 }
 

[ ... ]

fs/proc/inode.c static long pde_ioctl(struct proc_dir_entry *pde, struct file *file, unsigned in · line 589

Quoted 13 lines
fs/proc/inode.c +13 -0
+static long pde_ioctl_buf(struct proc_dir_entry *pde, struct file *file,
+			  unsigned int cmd, void __user *uarg, unsigned long arg)
+{
+	void *buf __free(kvfree) = NULL;
+	struct proc_ioctl_arg a;
+	size_t size;
+	long rv;
+
+	if (!pde_ioctl_arg(pde, cmd, &a))
+		return -ENOTTY;
+	size = max(a.in, a.out);
+	if (size) {
+		buf = kvzalloc(size, GFP_KERNEL);

[Severity: Low]
As reported by Sashiko on RFC [1], this isn't a bug, but in pde_ioctl_buf() in fs/proc/inode.c, buf is declared with __free(kvfree) = NULL at the top of the function and assigned later when size is non-zero.

Since the cleanup API convention prefers defining and initializing __free() variables in a single statement rather than initializing them to NULL at the top of the function and assigning them later, could buf be defined and initialized once size is known (for example via size ? kvzalloc(size, GFP_KERNEL) : NULL)?

[1] https://lore.kernel.org/r/[email protected]

Signature · 1 line
Sashiko AI review · https://sashiko.dev/#/patchset/[email protected]?part=18
author maintainer
#160 lore raw

PATCH RESEND v2 19/23 proc: pin the entry around the vm_operations of its mappings

In reply to Christian Brauner

proc_reg_mmap() pins the entry around ->proc_mmap() and that's it. What the entry hands out lives on without the pin: the vm_operations it put on the mapping run on every fault, on every write to a read-only page and on every ptrace access with the entry unpinned, and the mapping itself survives remove_proc_entry(). For /proc/vmcore that means the fault handler runs after vmcore_cleanup() freed what it looks at, and a mapping of the old memory keeps pointing at it after fadump gave that memory back to the page allocator. /proc/bus/pci has the same problem when a device goes away.

So do what kernfs does for the mappings of sysfs files. procfs puts vm_operations of its own on the mapping. They pin the entry around its ->open(), ->fault(), ->page_mkwrite() and ->access() and fail with SIGBUS, or do nothing, once the entry is gone. The entry's vm_operations are kept in its open node, so every mapping of an entry has to use the same ones, like kernfs asks that of every mapping of an open file. ->close() can't be wrapped, it runs when the mapping goes away and that can be after the entry is gone, so a mapping that has one is refused.

When the entry is removed procfs unmaps the mappings of every open file of an entry that has been mapped before it calls ->proc_release(), so a fault into one of them finds the entry gone. That unmaps the entry's own address space, the way kernfs_drain_open_files() does it. /proc/bus/pci maps through the iomem address space that /dev/mem and the sysfs resource files share, see iomem_get_mapping(), and unmapping that would take every /dev/mem and BAR mapping on the system with it. So those mappings are left alone, like the sysfs resource files leave theirs, and keep pointing at the BAR of a device that is gone. To know the files an entry that can be mapped gets an open node like an entry with a ->proc_release() has one. The mapping is linked into the file's address space only after ->mmap() returned, so a removal that runs in between doesn't find it. kernfs has the same window.

Entries that are never removed aren't wrapped, procfs never pins them.

---
 fs/proc/generic.c       |   6 +--
 fs/proc/inode.c         | 126 ++++++++++++++++++++++++++++++++++++++++++++----
 fs/proc/internal.h      |   9 ++--
 include/linux/proc_fs.h |  15 ++++++
 4 files changed, 140 insertions(+), 16 deletions(-)
fs/proc/generic.c +3 -3
index 1bad3b068d53..81a6cb560c75 100644
@@ -505,14 +505,14 @@ static int pde_set_flags(struct proc_dir_entry *pde)
 
 /*
  * procfs has to know the open files of an entry whose ->proc_release() it
- * calls at removal. A permanent entry is never removed and skips all that,
- * see proc_reg_open().
+ * calls at removal and whose mappings it undoes then. A permanent entry is
+ * never removed and skips all that, see proc_reg_open().
  */
 static bool pde_needs_open_node(const struct proc_dir_entry *pde)
 {
 	if (!S_ISREG(pde->mode) || pde_is_permanent(pde))
 		return false;
-	return pde->proc_ops->proc_release;
+	return pde->proc_ops->proc_release || pde->proc_ops->proc_mmap;
 }
 
 /*
fs/proc/inode.c +116 -10

164 lines not on this page · raw message

fs/proc/internal.h +6 -3
index ae0f9779cf1b..0b1c0585d6a6 100644
@@ -373,12 +373,15 @@ struct pde_opener {
 } __randomize_layout;
 
 /*
- * The open files of an entry whose ->proc_release() procfs has to call when
- * the entry is removed while they are still open. Allocated with the entry,
- * see proc_register().
+ * The open files of an entry whose ->proc_release() procfs has to call and
+ * whose mappings it has to undo when the entry is removed while they are
+ * still open, that is of an entry with a ->proc_release() or a
+ * ->proc_mmap(). Allocated with the entry, see proc_register().
  */
 struct pde_open_node {
 	struct list_head files;		/* who did ->open, but not ->release */
+	/* of its mappings, the same for all of them, see pde_mmap() */
+	const struct vm_operations_struct *vm_ops;
 };
 extern const struct inode_operations proc_link_inode_operations;
 extern const struct inode_operations proc_pid_link_inode_operations;
include/linux/proc_fs.h +15 -0
index 2ba4e4a39e13..5bf039d20990 100644
@@ -86,6 +86,21 @@ struct proc_ops {
 #ifdef CONFIG_COMPAT
 	long	(*proc_compat_ioctl)(struct file *, unsigned int, unsigned long);
 #endif
+	/*
+	 * procfs pins the entry around ->proc_mmap() and wraps the
+	 * vm_operations of the mapping so that ->open(), ->fault(),
+	 * ->page_mkwrite() and ->access() run with the entry pinned as well.
+	 * Nothing else of them is called, like for a kernfs file. Every
+	 * mapping of an entry has to use the same vm_operations. A ->close()
+	 * can't be wrapped, it runs when the mapping goes away and that can
+	 * be after the entry is gone, so a mapping that has one is refused.
+	 * Removing the entry unmaps the mappings in its own address space,
+	 * like kernfs does, and a fault into one of them is SIGBUS from then
+	 * on. A file that maps through another address space, /proc/bus/pci
+	 * through the one of /dev/mem, keeps its mappings like a sysfs
+	 * resource file does. The mappings of a permanent entry are left
+	 * alone.
+	 */
 	int	(*proc_mmap)(struct file *, struct vm_area_struct *);
 	unsigned long (*proc_get_unmapped_area)(struct file *, unsigned long, unsigned long, unsigned long, unsigned long);
 	/*
Signature · 1 line
2.53.0
#161 lore raw

Re: [PATCH RESEND v2 19/23] proc: pin the entry around the vm_operations of its mappings

Sashiko has reviewed this patch and found no issues.
Quoted 18 lines

proc_reg_mmap() pins the entry around ->proc_mmap() and that's it. What the entry hands out lives on without the pin: the vm_operations it put on the mapping run on every fault, on every write to a read-only page and on every ptrace access with the entry unpinned, and the mapping itself survives remove_proc_entry(). For /proc/vmcore that means the fault handler runs after vmcore_cleanup() freed what it looks at, and a mapping of the old memory keeps pointing at it after fadump gave that memory back to the page allocator. /proc/bus/pci has the same problem when a device goes away.

So do what kernfs does for the mappings of sysfs files. procfs puts vm_operations of its own on the mapping. They pin the entry around its ->open(), ->fault(), ->page_mkwrite() and ->access() and fail with SIGBUS, or do nothing, once the entry is gone. The entry's vm_operations are kept in its open node, so every mapping of an entry [ ... ]
window.

Quoted 3 lines

Entries that are never removed aren't wrapped, procfs never pins them.

Sashiko has reviewed this patch and found no issues.

Signature · 1 line
Sashiko AI review · https://sashiko.dev/#/patchset/[email protected]?part=19
author maintainer
#162 lore raw

PATCH RESEND v2 20/23 selftests/proc: check that a mapped entry can be removed

In reply to Christian Brauner

Map a memory BAR of a PCI device through /proc/bus/pci and remove the device through sysfs:

- the removal doesn't wait for the mapped file

- the entry is gone

- and reading the file fails with -EIO

The mapping itself survives. /proc/bus/pci maps through the iomem address space of /dev/mem and procfs leaves that alone, like the sysfs resource files leave theirs, so the test doesn't touch the mapping after the removal. What the BAR of a removed device reads like is between the reader and the hardware.

Nothing in the test can know which device is safe to remove, so it takes the device from PROC_PCI_DEV, skips without it and rescans the bus afterwards. It also skips where PCI files can't be mapped or that isn't allowed.

---
 tools/testing/selftests/proc/.gitignore           |   1 +
 tools/testing/selftests/proc/Makefile             |   1 +
 tools/testing/selftests/proc/proc-remove-mapped.c | 160 ++++++++++++++++++++++
 3 files changed, 162 insertions(+)
tools/testing/selftests/proc/.gitignore +1 -0
index e2566cc0ae07..cafd8c263c9a 100644
@@ -23,6 +23,7 @@
 /proc-pidns
 /proc-remove-slow-sysctl
 /proc-remove-slow-reader
+/proc-remove-mapped
 /proc-remove-slow-readlink
 /read
 /self
tools/testing/selftests/proc/Makefile +1 -0
index 6a9bdc999f54..c38297afc244 100644
@@ -34,6 +34,7 @@ TEST_GEN_PROGS += proc-sysctl-readdir-churn
 TEST_GEN_PROGS += proc-pidns
 TEST_GEN_PROGS += proc-remove-slow-sysctl
 TEST_GEN_PROGS += proc-remove-slow-reader
+TEST_GEN_PROGS += proc-remove-mapped
 TEST_GEN_PROGS += proc-remove-slow-readlink
 
 include ../lib.mk
tools/testing/selftests/proc/proc-remove-mapped.c new file +160 -0

160 lines not on this page · raw message

Signature · 1 line
2.53.0
#163 lore raw

Re: [PATCH RESEND v2 20/23] selftests/proc: check that a mapped entry can be removed

Thank you for your contribution! Sashiko AI review found 2 potential issue(s) to consider: - [Medium] selftests/proc: 32-bit off_t truncation in proc-remove-mapped mmap() - [Low] selftests/proc…

Thank you for your contribution! Sashiko AI review found 2 potential issue(s) to consider:
- [Medium] selftests/proc: 32-bit off_t truncation in proc-remove-mapped mmap()
- [Low] selftests/proc: unused len parameter in mem_bar() in proc-remove-mapped --

commit df303f424b9a370ffbd0eec6c07ff2a99d0ee4ea
Author: Christian Brauner <[email protected]>

selftests/proc: check that a mapped entry can be removed

This commit adds a procfs selftest that maps a PCI device memory BAR via /proc/bus/pci and removes the PCI device through sysfs to verify that removing a mapped procfs entry does not block and leaves the file returning -EIO on subsequent reads.

Quoted 5 lines
tools/testing/selftests/proc/proc-remove-mapped.c new file +0 -0
new file mode 100644
index 0000000000000..92860fb2a8f40

[ ... ]

Quoted 24 lines
tools/testing/selftests/proc/proc-remove-mapped.c new file +24 -0
+/* the first memory BAR of @dev */
+static int mem_bar(const char *dev, unsigned long long *start,
+		   unsigned long long *len)
+{
+	unsigned long long s, e, flags;
+	char path[PATH_MAX];
+	int ret = -ENODEV;
+	FILE *f;
+
+	snprintf(path, sizeof(path), SYSFS_DEVICES "%s/resource", dev);
+	f = fopen(path, "r");
+	if (!f)
+		return -errno;
+	while (fscanf(f, "%llx %llx %llx", &s, &e, &flags) == 3) {
+		if ((flags & IORESOURCE_MEM) && e >= s) {
+			*start = s;
+			*len = e - s + 1;
+			ret = 0;
+			break;
+		}
+	}
+	fclose(f);
+	return ret;
+}

[ ... ]

tools/testing/selftests/proc/proc-remove-mapped.c line 114

Quoted 11 lines
tools/testing/selftests/proc/proc-remove-mapped.c new file +11 -0
+TEST_F(pci, remove_while_mapped)
+{
+	long psz = sysconf(_SC_PAGESIZE);
+	unsigned long long start = 0, len = 0;
+	char path[PATH_MAX];
+	volatile unsigned int *p;
+	unsigned int v;
+	int fd;
+
+	if (mem_bar(self->dev, &start, &len))
+		SKIP(return, "%s has no memory BAR", self->dev);

[Severity: Low]
This isn't a bug, but is the len parameter in mem_bar() needed? mem_bar() writes *len = e - s + 1 and remove_while_mapped() passes &len, but len is never read afterward because mmap() maps a single page of size psz.

Quoted 6 lines
tools/testing/selftests/proc/proc-remove-mapped.c new file +6 -0
+
+	fd = open(self->path, O_RDONLY | O_CLOEXEC);
+	ASSERT_GE(fd, 0);
+	if (ioctl(fd, PCIIOC_MMAP_IS_MEM)) {
+		/* no PCI mmap on this architecture, or locked down */
+		if (errno == EINVAL || errno == EPERM) {

tools/testing/selftests/proc/proc-remove-mapped.c line 130

Quoted 10 lines
tools/testing/selftests/proc/proc-remove-mapped.c new file +10 -0
+			close(fd);
+			SKIP(return, "PCIIOC_MMAP_IS_MEM: %s", strerror(errno));
+		}
+		ASSERT_TRUE(false) {
+			TH_LOG("PCIIOC_MMAP_IS_MEM: %s", strerror(errno));
+		}
+	}
+	p = mmap(NULL, psz, PROT_READ, MAP_SHARED, fd, start);
+	if (p == MAP_FAILED)
+		SKIP(return, "mmap: %s", strerror(errno));

[Severity: Medium]
On 32-bit architectures, will passing start to mmap() in remove_while_mapped() truncate or sign-extend PCI BAR addresses at or above 0x80000000?

Neither proc-remove-mapped.c nor tools/testing/selftests/proc/Makefile defines _FILE_OFFSET_BITS to 64, so off_t is a 32-bit signed integer on 32-bit builds. When mem_bar() parses a BAR physical address >= 0x80000000 into unsigned long long start, converting start to a 32-bit signed off_t in mmap() either truncates bits above 32 or produces a negative offset (which fails with EINVAL in musl, or sign-extends the page offset passed to mmap2 in glibc so pci_mmap_fits() in proc_bus_pci_mmap() fails with ENODEV and causes the test to skip).

Should proc-remove-mapped.c define _FILE_OFFSET_BITS 64 before including the system headers?

Signature · 1 line
Sashiko AI review · https://sashiko.dev/#/patchset/[email protected]?part=20
author maintainer
#164 lore raw

PATCH RESEND v2 21/23 proc: let lockdep check the pin

In reply to Christian Brauner

remove_proc_entry() waits until every call into the entry has returned, and its callers like to hold locks while they wait. A method of the entry that takes one of those locks deadlocks with them. xt_recent removed its entries with a spinlock held that its seq_file took, and ALSA has to remove an entry before it takes info_mutex because its open takes it. Both of those were found by reading the code.

kernfs lets lockdep find them. kernfs_get_active() is a read lock to lockdep and kernfs_drain() takes the write side around its wait. So a method that takes a lock L while active records class -> L, a removal under L records L -> class, and lockdep reports the cycle.

Do the same for the pin. use_pde() records a read lock on the entry's lockdep map, unuse_pde() releases it and proc_entry_rundown() takes the write side around waiting for the last user. The key of the class is what the entries of a kind already share, their seq_operations or their proc_ops, static objects that lockdep takes as a key. The entries that only share a show function, those of proc_create_single() and friends, get a key per registration site instead, like every sysfs attribute has one: a show function lives in text and lockdep doesn't take that as a key. So all /proc/net/dev entries are one class, which is right. The same code runs pinned in every network namespace and a removal under a lock that its reader takes is a deadlock in any of them.

Nothing in the tree removes an entry of its own kind from one of its methods, so there's no need for an escape hatch like kernfs_break_active_protection() yet.

The map only exists on lockdep kernels.

---
 fs/proc/generic.c       | 46 ++++++++++++++++++++++++++++++++++++----------
 fs/proc/inode.c         | 29 ++++++++++++++++++++++++++---
 fs/proc/internal.h      | 17 ++++++++++++++++-
 fs/proc/proc_net.c      | 28 +++++++++++++++-------------
 include/linux/proc_fs.h | 42 +++++++++++++++++++++++++++++++++---------
 5 files changed, 126 insertions(+), 36 deletions(-)
fs/proc/generic.c +36 -10
index 81a6cb560c75..ca4025ee7aa8 100644
@@ -541,9 +541,33 @@ static int pde_init_seq_direct(struct proc_dir_entry *pde)
 	return 0;
 }
 
+static void pde_lockdep_init(struct proc_dir_entry *pde,
+			     struct lock_class_key *key)
+{
+#ifdef CONFIG_DEBUG_LOCK_ALLOC
+	const void *k = key;
+
+	if (!pde_lockdep(pde))
+		return;
+	/*
+	 * To lockdep the pin is a read lock that proc_entry_rundown() takes
+	 * the write side of, see use_pde(). The entries that share
+	 * seq_operations or proc_ops run the same code pinned, so they share
+	 * a class, and those are static objects that lockdep takes as its
+	 * key. The entries that only share a show function get a key per
+	 * registration site instead, see proc_create_single_data().
+	 */
+	if (!k)
+		k = pde_has_proc_seq_ops(pde) ? (const void *)pde->seq_ops :
+						pde->proc_ops;
+	lockdep_init_map(&pde->dep_map, "pde->in_use",
+			 (struct lock_class_key *)k, 0);
+#endif
+}
+
 /* returns the registered entry, or frees dp and returns NULL on failure */
 struct proc_dir_entry *proc_register(struct proc_dir_entry *dir,
-		struct proc_dir_entry *dp)
+		struct proc_dir_entry *dp, struct lock_class_key *key)
 {
 	if (proc_alloc_inum(&dp->low_ino))
 		goto out_free_entry;
@@ -558,6 +582,7 @@ struct proc_dir_entry *proc_register(struct proc_dir_entry *dir,
 	}
 	if (pde_init_seq_direct(dp))
 		goto out_free_inum;
+	pde_lockdep_init(dp, key);
 
 	write_lock(&proc_subdir_lock);
 	dp->parent = dir;
@@ -660,7 +685,7 @@ struct proc_dir_entry *proc_symlink(const char *name,
 		ent->data = kmemdup(dest, ent->size + 1, GFP_KERNEL);
 		if (ent->data) {
 			ent->proc_iops = &proc_link_inode_operations;
-			ent = proc_register(parent, ent);
+			ent = proc_register(parent, ent, NULL);
 		} else {
 			pde_free(ent);
 			ent = NULL;
@@ -686,7 +711,7 @@ struct proc_dir_entry *_proc_mkdir(const char *name, umode_t mode,
 		if (force_lookup) {
 			pde_force_lookup(ent);
 		}
-		ent = proc_register(parent, ent);
+		ent = proc_register(parent, ent, NULL);
 	}
 	return ent;
 }
@@ -723,7 +748,7 @@ struct proc_dir_entry *proc_create_mount_point(const char *name)
 		ent->data = NULL;
 		ent->proc_dir_ops = NULL;
 		ent->proc_iops = NULL;
-		ent = proc_register(parent, ent);
+		ent = proc_register(parent, ent, NULL);
 	}
 	return ent;
 }
@@ -759,7 +784,7 @@ struct proc_dir_entry *proc_create_data(const char *name, umode_t mode,
 	if (!p)
 		return NULL;
 	p->proc_ops = proc_ops;
-	return proc_register(parent, p);
+	return proc_register(parent, p, NULL);
 }
 EXPORT_SYMBOL(proc_create_data);
  
@@ -789,13 +814,14 @@ struct proc_dir_entry *proc_create_seq_private(const char *name, umode_t mode,
 	p->seq_ops = ops;
 	p->state_size = state_size;
 	p->flags |= PROC_ENTRY_proc_seq_ops;
-	return proc_register(parent, p);
+	return proc_register(parent, p, NULL);
 }
 EXPORT_SYMBOL(proc_create_seq_private);
 
-struct proc_dir_entry *proc_create_single_data(const char *name, umode_t mode,
+struct proc_dir_entry *__proc_create_single_data(const char *name, umode_t mode,
 		struct proc_dir_entry *parent,
-		int (*show)(struct seq_file *, void *), void *data)
+		int (*show)(struct seq_file *, void *), void *data,
+		struct lock_class_key *key)
 {
 	struct proc_dir_entry *p;
 
@@ -805,9 +831,9 @@ struct proc_dir_entry *proc_create_single_data(const char *name, umode_t mode,
 	p->proc_ops = &proc_seq_ops;
 	p->single_show = show;
 	p->flags |= PROC_ENTRY_proc_show;
-	return proc_register(parent, p);
+	return proc_register(parent, p, key);
 }
-EXPORT_SYMBOL(proc_create_single_data);
+EXPORT_SYMBOL(__proc_create_single_data);
 
 void proc_set_size(struct proc_dir_entry *de, loff_t size)
 {
fs/proc/inode.c +26 -3
index 5e423bcad278..59de4681d845 100644
@@ -199,13 +199,24 @@ const struct super_operations proc_sops = {
 
 enum {BIAS = -1U<<31};
 
+/*
+ * To lockdep the pin is a read lock and proc_entry_rundown() takes the write
+ * side, see pde_lockdep_init(). So a method that takes a lock while pinned
+ * and a removal under that lock are the deadlock lockdep knows how to report.
+ */
 static inline int use_pde(struct proc_dir_entry *pde)
 {
-	return likely(atomic_inc_unless_negative(&pde->in_use));
+	if (unlikely(!atomic_inc_unless_negative(&pde->in_use)))
+		return 0;
+	if (pde_lockdep(pde))
+		rwsem_acquire_read(&pde->dep_map, 0, 1, _RET_IP_);
+	return 1;
 }
 
 static void unuse_pde(struct proc_dir_entry *pde)
 {
+	if (pde_lockdep(pde))
+		rwsem_release(&pde->dep_map, _RET_IP_);
 	if (unlikely(atomic_dec_return(&pde->in_use) == BIAS))
 		wake_up_var(&pde->in_use);
 }
@@ -362,9 +373,21 @@ static void close_pdeo(struct proc_dir_entry *pde, struct pde_opener *pdeo,
 
 void proc_entry_rundown(struct proc_dir_entry *de)
 {
-	/* Wait until all existing callers into module are done. */
-	if (atomic_add_return(BIAS, &de->in_use) != BIAS)
+	/*
+	 * Wait until all existing callers into module are done. That's the
+	 * write side of the pin to lockdep, see use_pde().
+	 */
+	if (pde_lockdep(de))
+		rwsem_acquire(&de->dep_map, 0, 0, _RET_IP_);
+	if (atomic_add_return(BIAS, &de->in_use) != BIAS) {
+		if (pde_lockdep(de))
+			lock_contended(&de->dep_map, _RET_IP_);
 		wait_var_event(&de->in_use, atomic_read(&de->in_use) == BIAS);
+	}
+	if (pde_lockdep(de)) {
+		lock_acquired(&de->dep_map, _RET_IP_);
+		rwsem_release(&de->dep_map, _RET_IP_);
+	}
 
 	/* ->open->files can't grow from now on. */
 	if (!de->open)
fs/proc/internal.h +16 -1
index 0b1c0585d6a6..7a197e2920f8 100644
@@ -9,6 +9,7 @@
 #include <linux/proc_ns.h>
 #include <linux/refcount.h>
 #include <linux/spinlock.h>
+#include <linux/lockdep.h>
 #include <linux/atomic.h>
 #include <linux/binfmts.h>
 #include <linux/sched/coredump.h>
@@ -67,6 +68,9 @@ struct proc_dir_entry {
 	umode_t mode;
 	u16 flags;
 	u8 namelen;
+#ifdef CONFIG_DEBUG_LOCK_ALLOC
+	struct lockdep_map dep_map;	/* the pin as a lock, see use_pde() */
+#endif
 	char inline_name[];
 } __randomize_layout;
 
@@ -142,6 +146,16 @@ static inline bool pde_is_seq_file(const struct proc_dir_entry *pde)
 	return pde_has_proc_seq_ops(pde) || pde_has_proc_show(pde);
 }
 
+/* Only regular files are pinned, and only their map is initialized. */
+static inline bool pde_lockdep(const struct proc_dir_entry *pde)
+{
+#ifdef CONFIG_DEBUG_LOCK_ALLOC
+	return S_ISREG(pde->mode);
+#else
+	return false;
+#endif
+}
+
 extern struct kmem_cache *proc_dir_entry_cache;
 void pde_free(struct proc_dir_entry *pde);
 
@@ -318,7 +332,8 @@ bool proc_fill_cache(struct file *, struct dir_context *, const char *, unsigned
 struct proc_dir_entry *proc_create_reg(const char *name, umode_t mode,
 		struct proc_dir_entry **parent, void *data);
 struct proc_dir_entry *proc_register(struct proc_dir_entry *dir,
-		struct proc_dir_entry *dp);
+		struct proc_dir_entry *dp,
+		struct lock_class_key *key);
 extern struct dentry *proc_lookup(struct inode *, struct dentry *, unsigned int);
 struct dentry *proc_lookup_de(struct inode *, struct dentry *, struct proc_dir_entry *);
 extern int proc_readdir(struct file *, struct dir_context *);
fs/proc/proc_net.c +15 -13
index b78d627b024f..9ddd7c323dfc 100644
@@ -115,7 +115,7 @@ struct proc_dir_entry *proc_create_net_data(const char *name, umode_t mode,
 	p->seq_ops = ops;
 	p->state_size = state_size;
 	p->flags |= PROC_ENTRY_proc_seq_ops;
-	return proc_register(parent, p);
+	return proc_register(parent, p, NULL);
 }
 EXPORT_SYMBOL_GPL(proc_create_net_data);
 
@@ -162,7 +162,7 @@ struct proc_dir_entry *proc_create_net_data_write(const char *name, umode_t mode
 	p->state_size = state_size;
 	p->flags |= PROC_ENTRY_proc_seq_ops;
 	p->write = write;
-	return proc_register(parent, p);
+	return proc_register(parent, p, NULL);
 }
 EXPORT_SYMBOL_GPL(proc_create_net_data_write);
 
@@ -190,9 +190,10 @@ static const struct proc_ops proc_net_single_ops = {
 	.proc_release	= single_release_net,
 };
 
-struct proc_dir_entry *proc_create_net_single(const char *name, umode_t mode,
+struct proc_dir_entry *__proc_create_net_single(const char *name, umode_t mode,
 		struct proc_dir_entry *parent,
-		int (*show)(struct seq_file *, void *), void *data)
+		int (*show)(struct seq_file *, void *), void *data,
+		struct lock_class_key *key)
 {
 	struct proc_dir_entry *p;
 
@@ -203,9 +204,9 @@ struct proc_dir_entry *proc_create_net_single(const char *name, umode_t mode,
 	p->proc_ops = &proc_net_single_ops;
 	p->single_show = show;
 	p->flags |= PROC_ENTRY_proc_show;
-	return proc_register(parent, p);
+	return proc_register(parent, p, key);
 }
-EXPORT_SYMBOL_GPL(proc_create_net_single);
+EXPORT_SYMBOL_GPL(__proc_create_net_single);
 
 /**
  * proc_create_net_single_write - Create a writable net_ns-specific proc file
@@ -232,11 +233,12 @@ EXPORT_SYMBOL_GPL(proc_create_net_single);
  * pde_data() on the file inode.  The network namespace must be accessed by
  * calling seq_file_single_net() on the seq_file struct.
  */
-struct proc_dir_entry *proc_create_net_single_write(const char *name, umode_t mode,
-						    struct proc_dir_entry *parent,
-						    int (*show)(struct seq_file *, void *),
-						    proc_write_t write,
-						    void *data)
+struct proc_dir_entry *__proc_create_net_single_write(const char *name, umode_t mode,
+						      struct proc_dir_entry *parent,
+						      int (*show)(struct seq_file *, void *),
+						      proc_write_t write,
+						      void *data,
+						      struct lock_class_key *key)
 {
 	struct proc_dir_entry *p;
 
@@ -248,9 +250,9 @@ struct proc_dir_entry *proc_create_net_single_write(const char *name, umode_t mo
 	p->single_show = show;
 	p->flags |= PROC_ENTRY_proc_show;
 	p->write = write;
-	return proc_register(parent, p);
+	return proc_register(parent, p, key);
 }
-EXPORT_SYMBOL_GPL(proc_create_net_single_write);
+EXPORT_SYMBOL_GPL(__proc_create_net_single_write);
 
 static struct net *get_proc_task_net(struct inode *dir)
 {
include/linux/proc_fs.h +33 -9

61 lines not on this page · raw message

Signature · 1 line
2.53.0
#165 lore raw

Re: [PATCH RESEND v2 21/23] proc: let lockdep check the pin

Thank you for your contribution! Sashiko AI review found 1 potential issue(s) to consider: - [Low] proc: kernel-doc mismatch on __proc_create_net_single_write() --

Thank you for your contribution! Sashiko AI review found 1 potential issue(s) to consider:
- [Low] proc: kernel-doc mismatch on __proc_create_net_single_write()
--

commit 095fce4c95ecbe25e644f1a3fe90061f695e9271
Author: Christian Brauner <[email protected]>

proc: let lockdep check the pin

This commit adds lockdep tracking to proc_dir_entry pinning so lockdep can detect deadlocks between proc entry methods and removal under held locks. Entries created via proc_create_single() and related helpers receive a per-registration-site lock_class_key via wrapper macros.

Quoted 4 lines
fs/proc/proc_net.c +0 -0
index b78d627b024f8..9ddd7c323dfcd 100644

[ ... ]

Quoted 5 lines
fs/proc/proc_net.c +0 -1
@@ -232,11 +233,12 @@ EXPORT_SYMBOL_GPL(proc_create_net_single);
  * pde_data() on the file inode.  The network namespace must be accessed by
  * calling seq_file_single_net() on the seq_file struct.
  */
-struct proc_dir_entry *proc_create_net_single_write(const char *name, umode_t mode,

fs/proc/proc_net.c EXPORT_SYMBOL_GPL(proc_create_net_single); · line 241

Quoted 10 lines
fs/proc/proc_net.c +6 -4
-						    struct proc_dir_entry *parent,
-						    int (*show)(struct seq_file *, void *),
-						    proc_write_t write,
-						    void *data)
+struct proc_dir_entry *__proc_create_net_single_write(const char *name, umode_t mode,
+						      struct proc_dir_entry *parent,
+						      int (*show)(struct seq_file *, void *),
+						      proc_write_t write,
+						      void *data,
+						      struct lock_class_key *key)

[Severity: Low]
When proc_create_net_single_write() in fs/proc/proc_net.c is renamed to __proc_create_net_single_write() and given the new key parameter, the preceding kernel-doc block still documents the old name and omits @key:

/**
* proc_create_net_single_write - Create a writable net_ns-specific proc file
* @name: The name of the file.
* @mode: The file's access mode.
* @parent: The parent directory in which to create.
* @show: The seqfile show method with which to read the file.
* @write: The write method with which to 'modify' the file.
* @data: Data for retrieval by pde_data().

Should this kernel-doc comment be updated to match __proc_create_net_single_write() and document @key (or moved to the proc_create_net_single_write() macro in include/linux/proc_fs.h) to avoid scripts/kernel-doc warnings when building with W=1?

Signature · 1 line
Sashiko AI review · https://sashiko.dev/#/patchset/[email protected]?part=21
author maintainer
#166 lore raw

PATCH RESEND v2 22/23 proc: own the wait queue of an entry with a ->proc_poll()

In reply to Christian Brauner

An entry with a ->proc_poll() calls poll_wait() on a wait queue of its own and procfs pins the entry around that. The pin covers the call, not what it leaves behind: the poller stays queued on the entry's queue after the call, and so after remove_proc_entry() ran ->proc_release() on the still open file and the entry's owner freed the queue with the rest. sunrpc had the queue of its channel files in the per-namespace cache_detail, which is freed when the namespace goes, so a poll() or epoll on such a file across the end of the namespace was a use-after-free, fixed for stable by going back to one static queue. md works around the same problem at module unload by waking its pollers in a loop until none is left.

So do what kernfs does with kernfs_open_node: procfs owns the wait queue. Every entry with a ->proc_poll() gets an open node, which lives as long as the entry does, and the entry's inode holds the entry, so the queue outlives every open file and every poll or epoll entry on it. proc_reg_poll() does the poll_wait() on it before it calls the method, the owner wakes the pollers with proc_poll_notify(), and procfs wakes them when the entry is removed, after which a poll of it reports EPOLLERR | EPOLLPRI, like kernfs_fop_poll() does. The open node tracks the open files only for the entries whose release hook procfs has to call at removal, as before. Which methods an entry has procfs keeps in the entry's flags, and whether its files are tracked comes from there
too: the last close of a file can come after the entry was removed and its proc_ops freed with their module.

The method still gets the poll_table for now and the entries keep sleeping on their own queues until they are converted. The last series takes the poll_table away, so that an entry can't hand procfs a queue that dies before its files do.

---
 fs/proc/generic.c       | 38 ++++++++++++++++++++--------------
 fs/proc/inode.c         | 55 ++++++++++++++++++++++++++++++++++++-------------
 fs/proc/internal.h      | 35 ++++++++++++++++++++++++++-----
 include/linux/proc_fs.h | 11 ++++++++++
 4 files changed, 105 insertions(+), 34 deletions(-)
fs/proc/generic.c +23 -15
index ca4025ee7aa8..9c073cb867e5 100644
@@ -466,6 +466,12 @@ static int pde_set_flags(struct proc_dir_entry *pde)
 		if (proc_ops->proc_lseek)
 			pde->flags |= PROC_ENTRY_proc_lseek;
 	}
+	if (proc_ops->proc_poll)
+		pde->flags |= PROC_ENTRY_proc_poll;
+	if (proc_ops->proc_release)
+		pde->flags |= PROC_ENTRY_proc_release;
+	if (proc_ops->proc_mmap)
+		pde->flags |= PROC_ENTRY_proc_mmap;
 	if (proc_ops->proc_write_buf) {
 		if (WARN_ON_ONCE(proc_ops->proc_write))
 			return -EINVAL;
@@ -503,16 +509,22 @@ static int pde_set_flags(struct proc_dir_entry *pde)
 	return 0;
 }
 
-/*
- * procfs has to know the open files of an entry whose ->proc_release() it
- * calls at removal and whose mappings it undoes then. A permanent entry is
- * never removed and skips all that, see proc_reg_open().
- */
-static bool pde_needs_open_node(const struct proc_dir_entry *pde)
+/* The open node, see struct pde_open_node. */
+static int pde_init_open_node(struct proc_dir_entry *pde)
 {
-	if (!S_ISREG(pde->mode) || pde_is_permanent(pde))
-		return false;
-	return pde->proc_ops->proc_release || pde->proc_ops->proc_mmap;
+	struct pde_open_node *on;
+
+	if (!S_ISREG(pde->mode))
+		return 0;
+	if (!pde_has_proc_poll(pde) && !pde_tracks_files(pde))
+		return 0;
+	on = kzalloc(sizeof(*on), GFP_KERNEL);
+	if (!on)
+		return -ENOMEM;
+	INIT_LIST_HEAD(&on->files);
+	init_waitqueue_head(&on->poll);
+	pde->open = on;
+	return 0;
 }
 
 /*
@@ -574,12 +586,8 @@ struct proc_dir_entry *proc_register(struct proc_dir_entry *dir,
 
 	if (!S_ISDIR(dp->mode) && pde_set_flags(dp))
 		goto out_free_inum;
-	if (pde_needs_open_node(dp)) {
-		dp->open = kzalloc(sizeof(*dp->open), GFP_KERNEL);
-		if (!dp->open)
-			goto out_free_inum;
-		INIT_LIST_HEAD(&dp->open->files);
-	}
+	if (pde_init_open_node(dp))
+		goto out_free_inum;
 	if (pde_init_seq_direct(dp))
 		goto out_free_inum;
 	pde_lockdep_init(dp, key);
fs/proc/inode.c +41 -14

97 lines not on this page · raw message

fs/proc/internal.h +30 -5
index 7a197e2920f8..d2d731706788 100644
@@ -15,6 +15,7 @@
 #include <linux/sched/coredump.h>
 #include <linux/sched/task.h>
 #include <linux/mm.h>
+#include <linux/wait.h>
 
 struct ctl_table_header;
 struct mempolicy;
@@ -140,6 +141,26 @@ static inline bool pde_has_proc_ioctl_buf(const struct proc_dir_entry *pde)
 	return pde->flags & PROC_ENTRY_proc_ioctl_buf;
 }
 
+static inline bool pde_has_proc_poll(const struct proc_dir_entry *pde)
+{
+	return pde->flags & PROC_ENTRY_proc_poll;
+}
+
+/*
+ * procfs has to know the open files of an entry whose ->proc_release() it
+ * calls at removal and whose mappings it undoes then. A permanent entry is
+ * never removed and skips all that, see proc_reg_open(). This looks at the
+ * flags and not at the proc_ops: the last close of a file can come after
+ * the entry was removed and the proc_ops freed with their module, see
+ * proc_reg_release().
+ */
+static inline bool pde_tracks_files(const struct proc_dir_entry *pde)
+{
+	if (pde_is_permanent(pde))
+		return false;
+	return pde->flags & (PROC_ENTRY_proc_release | PROC_ENTRY_proc_mmap);
+}
+
 /* procfs owns the seq_file, see pde_seq_start() */
 static inline bool pde_is_seq_file(const struct proc_dir_entry *pde)
 {
@@ -388,15 +409,19 @@ struct pde_opener {
 } __randomize_layout;
 
 /*
- * The open files of an entry whose ->proc_release() procfs has to call and
- * whose mappings it has to undo when the entry is removed while they are
- * still open, that is of an entry with a ->proc_release() or a
- * ->proc_mmap(). Allocated with the entry, see proc_register().
+ * What procfs keeps for the open files of an entry: the files themselves if
+ * it has to call their ->proc_release() and undo their mappings when the
+ * entry is removed, that is for an entry with a ->proc_release() or a
+ * ->proc_mmap(), and the wait queue their pollers sleep on for an entry with
+ * a ->proc_poll(). Allocated with the entry, see proc_register().
  */
 struct pde_open_node {
-	struct list_head files;		/* who did ->open, but not ->release */
+	/* who did ->open, but not ->release, see pde_tracks_files() */
+	struct list_head files;
 	/* of its mappings, the same for all of them, see pde_mmap() */
 	const struct vm_operations_struct *vm_ops;
+	/* what poll() and epoll wait on, see proc_poll_notify() */
+	wait_queue_head_t poll;
 };
 extern const struct inode_operations proc_link_inode_operations;
 extern const struct inode_operations proc_pid_link_inode_operations;
include/linux/proc_fs.h +11 -0
index feb3228cb5af..8520b18ce1f7 100644
@@ -47,6 +47,9 @@ enum {
 	 */
 	PROC_ENTRY_FULL_READS		= 1U << 11,
 	PROC_ENTRY_proc_ioctl_buf	= 1U << 12,
+	PROC_ENTRY_proc_poll		= 1U << 13,
+	PROC_ENTRY_proc_release		= 1U << 14,
+	PROC_ENTRY_proc_mmap		= 1U << 15,
 };
 
 /*
@@ -81,6 +84,12 @@ struct proc_ops {
 	 */
 	loff_t	(*proc_lseek)(struct file *, loff_t, int);
 	int	(*proc_release)(struct inode *, struct file *);
+	/*
+	 * procfs owns a wait queue for an entry with a ->proc_poll() and
+	 * does the poll_wait() on it before it calls the method. The owner
+	 * wakes the pollers with proc_poll_notify(). A poll on a removed
+	 * entry reports EPOLLERR | EPOLLPRI.
+	 */
 	__poll_t (*proc_poll)(struct file *, struct poll_table_struct *);
 	long	(*proc_ioctl)(struct file *, unsigned int, unsigned long);
 #ifdef CONFIG_COMPAT
@@ -243,6 +252,7 @@ extern void *proc_get_parent_data(const struct inode *);
 extern void proc_remove(struct proc_dir_entry *);
 extern void remove_proc_entry(const char *, struct proc_dir_entry *);
 extern int remove_proc_subtree(const char *, struct proc_dir_entry *);
+void proc_poll_notify(struct proc_dir_entry *pde);
 
 struct proc_dir_entry *proc_create_net_data(const char *name, umode_t mode,
 		struct proc_dir_entry *parent, const struct seq_operations *ops,
@@ -341,6 +351,7 @@ static inline void *proc_get_parent_data(const struct inode *inode) { BUG(); ret
 static inline void proc_remove(struct proc_dir_entry *de) {}
 #define remove_proc_entry(name, parent) do {} while (0)
 static inline int remove_proc_subtree(const char *name, struct proc_dir_entry *parent) { return 0; }
+static inline void proc_poll_notify(struct proc_dir_entry *pde) {}
 
 #define proc_create_net_data(name, mode, parent, ops, state_size, data) ({NULL;})
 #define proc_create_net_data_write(name, mode, parent, ops, write, state_size, data) ({NULL;})
Signature · 1 line
2.53.0
#167 lore raw

Re: [PATCH RESEND v2 22/23] proc: own the wait queue of an entry with a ->proc_poll()

Thank you for your contribution! Sashiko AI review found 1 potential issue(s) to consider: - [Medium] proc: dual poll_wait() calls in proc_reg_poll() break AIO poll --

Thank you for your contribution! Sashiko AI review found 1 potential issue(s) to consider:
- [Medium] proc: dual poll_wait() calls in proc_reg_poll() break AIO poll --

commit 443c1e3f3b75bcf766632cccb5651e0034423048
Author: Christian Brauner <[email protected]>

proc: own the wait queue of an entry with a ->proc_poll()

This commit gives procfs entries that implement ->proc_poll() a procfs-owned wait queue in struct pde_open_node and adds proc_poll_notify() to wake pollers on that queue. proc_reg_poll() calls poll_wait() on the procfs wait queue before invoking the entry's ->proc_poll() callback with the same poll_table.

Quoted 4 lines
fs/proc/inode.c +0 -0
index 59de4681d8452..ab30a58879d51 100644

[ ... ]

Quoted 22 lines
fs/proc/inode.c +7 -8
@@ -555,26 +561,46 @@ static ssize_t proc_reg_write(struct file *file, const char __user *buf, size_t
 	return rv;
 }
 
-static __poll_t pde_poll(struct proc_dir_entry *pde, struct file *file, struct poll_table_struct *pts)
-{
-	const auto poll = pde->proc_ops->proc_poll;
-	if (poll)
-		return poll(file, pts);
-	return DEFAULT_POLLMASK;
-}
-
+/*
+ * The pollers of an entry sleep on a wait queue procfs owns, which is there
+ * for as long as the entry's inode is, however the entry's owner goes away.
+ * The owner wakes them through proc_poll_notify(), and procfs does when the
+ * entry is removed: a poll of a removed entry reports EPOLLERR | EPOLLPRI,
+ * like kernfs_fop_poll().
+ */
 static __poll_t proc_reg_poll(struct file *file, struct poll_table_struct *pts)
 {
 	struct proc_dir_entry *pde = PDE(file_inode(file));

fs/proc/inode.c static ssize_t proc_reg_write(struct file *file, const char __user *buf, size_t · line 581

Quoted 10 lines
fs/proc/inode.c +5 -2
 	__poll_t rv;
 
-	if (!pde_pin(pde))
+	if (!pde_has_proc_poll(pde))
 		return DEFAULT_POLLMASK;
-	rv = pde_poll(pde, file, pts);
+	poll_wait(file, &pde->open->poll, pts);
+	if (!pde_pin(pde))
+		return DEFAULT_POLLMASK | EPOLLERR | EPOLLPRI;
+	rv = pde->proc_ops->proc_poll(file, pts);

[Severity: Medium]
Does calling poll_wait() on pde->open->poll in proc_reg_poll() before passing pts to pde->proc_ops->proc_poll() break Linux AIO polling (IOCB_CMD_POLL via io_submit()) for unconverted procfs entries?

While ->proc_poll() implementations still receive pts and call poll_wait() on their own wait queues, vfs_poll() -> proc_reg_poll() ends up calling poll_wait() twice on the same poll_table_struct: first on &pde->open->poll and then on the subsystem's wait queue inside ->proc_poll().

When userspace submits an IOCB_CMD_POLL request via io_submit() on a pollable procfs file (such as /proc/pressure/*, /proc/mdstat, /proc/swaps, or /proc/kmsg), aio_poll() sets apt.pt._qproc = aio_poll_queue_proc. The first poll_wait() queues the request on &pde->open->poll and sets pt->queued = true, and the second poll_wait() inside ->proc_poll() hits the single-waitqueue check in fs/aio.c:aio_poll_queue_proc():

	/* multiple wait queues per file are not supported */
	if (unlikely(pt->queued)) {
		pt->error = -EINVAL;
		return;
	}

If the polled event is not immediately ready, aio_poll() sees apt.error == -EINVAL, removes the wait entry from &pde->open->poll, and fails the io_submit() request with -EINVAL.

Signature · 1 line
Sashiko AI review · https://sashiko.dev/#/patchset/[email protected]?part=22
author maintainer
#168 lore raw

PATCH RESEND v2 23/23 Documentation: seq_file: describe how a /proc file uses seq_file

In reply to Christian Brauner

The example in seq_file.rst hands proc_create() file operations built from an open method that calls seq_open() and from seq_read(), seq_lseek() and seq_release(). procfs doesn't work that way anymore. It opens and releases the seq_file itself when the entry declares its seq_operations or its show function in struct proc_ops. Say so, and point the extra-simple version at ->proc_show() for /proc files.

---
 Documentation/filesystems/seq_file.rst | 42 ++++++++++++++++++++++++++--------
 1 file changed, 33 insertions(+), 9 deletions(-)
Documentation/filesystems/seq_file.rst +33 -9
index d753d8177bcb..3e6ff1c1226d 100644
@@ -68,7 +68,7 @@ kernel 3.10. Current versions require the following update::
     -	entry = create_proc_entry("sequence", 0, NULL);
     -	if (entry)
     -		entry->proc_fops = &ct_file_ops;
-    +	entry = proc_create("sequence", 0, NULL, &ct_file_ops);
+    +	entry = proc_create("sequence", 0, NULL, &ct_proc_ops);
 
 The iterator interface
 ======================
@@ -277,9 +277,10 @@ seq_file system, but we have not yet turned them into a file that a user
 can see. Creating a file within the kernel requires, of course, the
 creation of a set of file_operations which implement the operations on that
 file. The seq_file interface provides a set of canned operations which do
-most of the work. The virtual file author still must implement the open()
-method, however, to hook everything up. The open function is often a single
-line, as in the example module::
+most of the work. A file in /proc is special, procfs hooks the seq_file up
+itself, see below. Everywhere else the virtual file author still must
+implement the open() method to do that. The open function is often a
+single line::
 
 	static int ct_open(struct inode *inode, struct file *file)
 	{
@@ -343,19 +344,38 @@ file_operations structure will look like::
 There is also a seq_release_private() which passes the contents of the
 seq_file private field to kfree() before releasing the structure.
 
-The final step is the creation of the /proc file itself. In the example
-code, that is done in the initialization code in the usual way::
+The final step is the creation of the file itself. A file in /proc is
+special here: procfs opens and releases the seq_file itself, so there is
+no open method and no file_operations for it. The entry declares its
+seq_operations in struct proc_ops instead, and the size of a private
+block in proc_state_size if it wants procfs to allocate one like
+seq_open_private() would::
+
+	static const struct proc_ops ct_proc_ops = {
+	        .proc_seq_ops = &ct_seq_ops,
+	};
 
 	static int ct_init(void)
 	{
-	        struct proc_dir_entry *entry;
-
-	        proc_create("sequence", 0, NULL, &ct_file_ops);
+	        proc_create("sequence", 0, NULL, &ct_proc_ops);
 	        return 0;
 	}
 
 	module_init(ct_init);
 
+A ->proc_open() method of such an entry finds the seq_file in
+file->private_data and may set up more state; ->proc_release() releases
+only that. It runs when the entry is removed, which can be while a reader
+is still copying out of the seq_file, so it must leave the seq_file
+alone. procfs only calls into the entry with the entry pinned, between
+start() and stop() like in its other methods, so nothing that runs there
+may wait for something a reader can hold while it copies to userspace,
+like the seq_file's lock.
+An entry that wants to start out with a larger buffer, like
+single_open_size() gives, calls seq_preallocate() from ->proc_open().
+The file_operations above are what a file elsewhere, in debugfs for
+example, uses.
+
 And that is pretty much it.
 
 
@@ -394,3 +414,7 @@ value given to single_open() can be found in the private field of the
 seq_file structure. When using single_open(), the programmer should use
 single_release() instead of seq_release() in the file_operations structure
 to avoid a memory leak.
+
+A file in /proc puts the show() function into the proc_show field of its
+struct proc_ops instead and procfs does the rest, with the entry's data in
+the private field of the seq_file structure.
Signature · 1 line
2.53.0
#169 lore raw

Re: [PATCH RESEND v2 23/23] Documentation: seq_file: describe how a /proc file uses seq_file

Sashiko has reviewed this patch and found no issues.
Quoted 8 lines

The example in seq_file.rst hands proc_create() file operations built from an open method that calls seq_open() and from seq_read(), seq_lseek() and seq_release(). procfs doesn't work that way anymore. It opens and releases the seq_file itself when the entry declares its seq_operations or its show function in struct proc_ops. Say so, and point the extra-simple version at ->proc_show() for /proc files.

Sashiko has reviewed this patch and found no issues.

Signature · 1 line
Sashiko AI review · https://sashiko.dev/#/patchset/[email protected]?part=23
author maintainer
#170 lore raw

v2 cover proc: convert the arch and platform entries (Part 3/7)

In reply to Christian Brauner

Part 3/7 of "proc: move procfs to what kernfs does", on top of part 2 and independent of parts 4 to 6:

https://patch.msgid.link/20261104-work-procfs-v2-0-b45cd5789ac5@brauner

This converts the proc entries under arch/ and the ones of ACPI, the platform drivers, via-pmu and PNP to what "proc: let procfs own the data path" set up. Afterwards the entries' code only runs with the entry pinned and never touches userspace memory. One patch per subsystem and method.

- procfs copies in the writes of alpha's srm_env, the ARM and sh alignment files, the rtas, pseries, mconsole and exitcode files, sparc's led, /proc/mtrr, simdisk, /proc/acpi/wakeup, via-pmu's options, thinkpad_acpi, toshiba_acpi and pnpbios. Most of them just stop copying in themselves or switch from kstrto*_from_user() to kstrto*(). Where a write larger than anything the entry parses now fails with -EINVAL from procfs the commit says so.
- procfs copies out the reads of /proc/atags, /proc/bootinfo, the rtas error log and flash files, /proc/powerpc/systemcfg, simdisk and /proc/bus/isapnp, mostly simple_read_from_buffer() turned into memory_read_from_buffer().
- procfs owns the seq_file of /proc/mtrr and copies its ioctl arguments in and out. The ioctls are table driven now, the native and the 32-bit commands share one table.
- the rtas flash files take their image in 4k pieces and keep doing that with PROC_ENTRY_SHORT_WRITES.
- the rtas error log is a stream, it hands out a record before procfs copies it out, so a reader that passes a bad buffer loses it. Its pollers sleep on the wait queue procfs owns for the entry now and rtasd wakes them with proc_poll_notify().

Build tested per commit on x86_64 and with W=1 on the touched objects on alpha, arm, m68k, powerpc, sh, sparc, um, x86 and xtensa. The entries I could get at in an x86 VM behave the same with and without the series.

---
Changes in v2:
- rtasd lets procfs own the wait queue of the rtas error log
- rebased onto v7.4-rc1, the thinkpad_acpi write merged with its
cleanup.h restyle upstream
- Link to v1: https://patch.msgid.link/[email protected]

---
Christian Brauner (23):
alpha: srm_env: let procfs copy in writes
ARM: alignment: let procfs copy in writes
ARM: atags: let procfs copy out reads of /proc/atags m68k/bootinfo: let procfs copy out reads of /proc/bootinfo powerpc/rtas: let procfs copy in writes
powerpc/rtas: let procfs copy out reads
powerpc/rtasd: let procfs own the wait queue of the rtas error log powerpc/pseries: let procfs copy in writes powerpc/procfs: let procfs copy out reads of /proc/powerpc/systemcfg
sh: alignment: let procfs copy in writes
sparc: led: let procfs copy in writes
um: let procfs copy in writes
x86/mtrr: let procfs own the seq_file of /proc/mtrr x86/mtrr: let procfs copy in writes to /proc/mtrr x86/mtrr: let procfs copy the ioctl arguments of /proc/mtrr
xtensa: simdisk: let procfs copy in writes
xtensa: simdisk: let procfs copy out reads
ACPI: proc: let procfs copy in writes to /proc/acpi/wakeup macintosh/via-pmu: let procfs copy in writes to the options file platform/x86: thinkpad_acpi: let procfs copy in writes platform/x86: toshiba_acpi: let procfs copy in writes
PNP: pnpbios: let procfs copy in writes
PNP: isapnp: let procfs copy out reads

 arch/alpha/kernel/srm_env.c                 | 12 +---
 arch/arm/kernel/atags_proc.c                |  6 +-
 arch/arm/mm/alignment.c                     |  7 +--
 arch/m68k/kernel/bootinfo_proc.c            |  6 +-
 arch/powerpc/kernel/proc_powerpc.c          |  6 +-
 arch/powerpc/kernel/rtas-proc.c             | 40 ++++++------
 arch/powerpc/kernel/rtas_flash.c            | 62 +++++++++----------
 arch/powerpc/kernel/rtasd.c                 | 30 +++------
 arch/powerpc/platforms/pseries/lpar.c       | 14 ++---
 arch/powerpc/platforms/pseries/lparcfg.c    |  7 +--
 arch/powerpc/platforms/pseries/reconfig.c   | 22 +++----
 arch/sh/mm/alignment.c                      |  7 +--
 arch/sparc/kernel/led.c                     | 12 +---
 arch/um/drivers/mconsole_kern.c             | 11 +---
 arch/um/kernel/exitcode.c                   | 14 ++---
 arch/x86/kernel/cpu/mtrr/if.c               | 95 ++++++++++++++++-------------
 arch/xtensa/platforms/iss/simdisk.c         | 32 ++++------
 drivers/acpi/proc.c                         |  7 +--
 drivers/macintosh/via-pmu.c                 |  7 +--
 drivers/platform/x86/lenovo/thinkpad_acpi.c | 12 +---
 drivers/platform/x86/toshiba_acpi.c         | 36 ++++-------
 drivers/pnp/isapnp/proc.c                   | 20 +++---
 drivers/pnp/pnpbios/proc.c                  |  9 +--
 23 files changed, 198 insertions(+), 276 deletions(-)

---
base-commit: 6628e7d4c6b25c8d18f1345e3a20d21829aae7e4
change-id: 20261101-work-procfs-arch-8d4ade48be31
prerequisite-change-id: 20261101-work-procfs-core-8fa4a4f412cf:v2
prerequisite-patch-id: a81e8b894107e48d607f8257d2c9f56e0dd6f400
prerequisite-patch-id: 7edf7ca7ecd32c9e09085e4b65922af10097beaa
prerequisite-patch-id: 81f6893f79b4236637675553298a6f2892b603f3
prerequisite-patch-id: 598c2b1a389f47adcac88ebcf1c9f74e2511fbab
prerequisite-patch-id: 6f5a2172dacc5ff2491fa9832c48ccd0e1ce1eda
prerequisite-patch-id: 8947af6490288e4e2a3b2bf8844a974bedb1d975
prerequisite-patch-id: 8cbe756286fd95967d31b0c46cacfeb05f0a2c6b
prerequisite-patch-id: 3fa159f2b6ccd0ac51a2662e4eec5587ec18de89
prerequisite-patch-id: bfb4e4ffe9631cb58015fefe6bd3698cd53e2244
prerequisite-patch-id: 56ff6667a57a962264c07c0227c61aa2f1f4c22c
prerequisite-patch-id: bc506323e29944ec0c29eae84950c706a8592042
prerequisite-patch-id: 326c0ebb5accf0f40cbee1323fb4c3378f5be154
prerequisite-patch-id: d6eaf7690a54a0dfda7500936a048b769fa265dd
prerequisite-patch-id: 7c7b2535642b4d388e13eab518cbe0f9550eb1e6
prerequisite-patch-id: 0474af12959624910718795bf86684383664c685
prerequisite-patch-id: f6d4191e23c22e2d2cc90cc5d04781f913e98a8e
prerequisite-patch-id: b0031a7c4855b7ec38259c59f30f65101a8fc4b5
prerequisite-patch-id: 0b7f226abf2b9ff41873a1aa55cf97747647d56b
prerequisite-patch-id: f63e345f897619af54813958046617c655fb7daf
prerequisite-patch-id: c0e21e762a2960e3324c5ab04634a7035e515fa6
prerequisite-patch-id: fd59c71eadd8f39c58b3baea93567bc093bc9b0e
prerequisite-patch-id: 5d52cc8a5c73e4c5ba16b8e24f51408c17583bf9
prerequisite-patch-id: 1f9179284e2f3314d4b46ac5e989089a21c7576c
prerequisite-patch-id: 10397bbf696bee16dc71eb79fff6c5e73842bcbc
prerequisite-patch-id: 9b44279dcf08912238d2f6438a3328a778a79a0c
prerequisite-patch-id: 16854b621a3a71dfc365aaf7abaa7f65adfe9f7e
prerequisite-patch-id: ca42eea21fae1fd1cd3518ab057c74b61ffd68fe
prerequisite-patch-id: 23255dc2be76b0479c083dbd4c897bfbb533aed5
prerequisite-patch-id: 82129c687ebf0a41b369893b92f2c038420ab801
prerequisite-patch-id: 56ad57a99a5bda075a9f4e844368974296744934
prerequisite-patch-id: 288b3cbaa11e01a778cc3d7beb6c0549aacf59f2
prerequisite-patch-id: a163b1549608652bfa5bd9ff93efa55b541010c4
prerequisite-patch-id: 43b92dfc1a98fbf0d14597a3e3ae99972844773b
prerequisite-patch-id: 19c12bc6e3fbed35acc1f657196b1a997f48cdfe
prerequisite-patch-id: 5800c3076694bad719954b2ad4d7448c6e013bfd
prerequisite-patch-id: 2a2f63d8843b159594b9eee6ddea028ce76a6270
prerequisite-patch-id: 40a1951d57906c4a1b98a4bd96a814b80339b9c5
prerequisite-patch-id: e2141077e69f20a2b27fab69c8d61d0686682f53
prerequisite-patch-id: c4d6018c26c40dc549d88330d23ce48f872c2b7f
prerequisite-patch-id: 6de8ec17746031bc6d1d9ac262c5be0f905fcd79
prerequisite-patch-id: b87bcb167884605bff1fd0f2ed8a88942d07efd5
prerequisite-patch-id: cfa9a8b4c67e20cfd22d77035bfd21ee96ab3298
prerequisite-patch-id: abf3482ed2399b7b2e1ee72e937af05bb9200667
prerequisite-patch-id: 02c175b2dee565a85b3308ecf2ec8e3c9a029e0f
prerequisite-patch-id: d58c239fba616b366a725de6acba3f88734156d0
prerequisite-patch-id: dbe02fe3f784776fda5e7ae99f077bef0cd4b48d
prerequisite-patch-id: 53edc9a95afff57c4acba40095a8054924261ea2
prerequisite-patch-id: 5348d8957eb7eae7430ca8b101aa84ce77d3aa4f
prerequisite-patch-id: 36c96d781e2dd80b20932667bbe6e7fd14976069
prerequisite-patch-id: efeb2d6f7df71d5dede2c1d12fe999a28e38aab9
prerequisite-patch-id: 17f95c7fdf0bdc7c8aaaf7883bff1dcc19a0f529
prerequisite-patch-id: 117db27dcdef433de7c6be5e95973cac1e373927
prerequisite-patch-id: a0844aa26ffb65ccb362b88ef6c2f4758e15edbf
prerequisite-patch-id: 9c64355dfde62e399f2717d9208c4607834d4650
prerequisite-patch-id: 9644739854ddfe2876f17fda8727fd5119255957
prerequisite-patch-id: c61bba24c035f79a2a32a80ace0924ab58e97f46
prerequisite-patch-id: 143fb91bddf33068b6ee11e205818c4c2815e23d
prerequisite-patch-id: 9ce9be2ff05250f92d945c0084f4bb31d3d0b27d
prerequisite-patch-id: aee0961341523547095a43ae298cb8b551302f10
prerequisite-patch-id: 2f0fdb970ddd760d85ff5d2caad0b96348270182
prerequisite-patch-id: f2aa468ff5cbb1cabab3f70e1b8eeee0286cfb4a
prerequisite-patch-id: 5555895bcbca4d7c9888ecc9e82c0e4d76da8f40
prerequisite-patch-id: 487141c49e2548310bfb6c2a0964a78f08b285a9
prerequisite-patch-id: c3d3008819fa5629a18142ec9ba6d7024ade7fdb
prerequisite-patch-id: ca587c976690ac16e3d759fccab2116fef0508e8
prerequisite-patch-id: 9423f410b99853693db06c29f12f1c08278b050d
prerequisite-patch-id: e269815617a6324615a38916b8886f99d98c641e
prerequisite-patch-id: 3d24be1897a624d519ef144801f76d152c7528a9
prerequisite-patch-id: 1ea3fc8319d9012faaf3a182ac61d5da89aafdb7
prerequisite-patch-id: 7547b4e2c1b3588acf6caf90cc01fe7884fdb6bd
prerequisite-patch-id: 695d325349ebeb89bf0ea24bcf0c4f1c4edacab5
prerequisite-patch-id: e33502a202979aba0d6fdaf196e8471d906992a1
prerequisite-patch-id: 47bfe4f07677ad75fe8d9accc8923a1cbdf3afa6
prerequisite-patch-id: 9fc0739226572203fcb36f2c271be7b27f405ef2

author maintainer
#171 lore raw

PATCH RESEND v2 1/23 alpha: srm_env: let procfs copy in writes

Implement ->proc_write_buf() so procfs copies in what is written to /proc/srm_environment/* before it pins the entry, and hand that copy to the console callback through the page it used before.

---
 arch/alpha/kernel/srm_env.c | 12 +++---------
 1 file changed, 3 insertions(+), 9 deletions(-)
arch/alpha/kernel/srm_env.c +3 -9
index faafc2df7886..6a1742b09a82 100644
@@ -81,7 +81,7 @@ static int srm_env_proc_show(struct seq_file *m, void *v)
 	return ret;
 }
 
-static ssize_t srm_env_proc_write(struct file *file, const char __user *buffer,
+static ssize_t srm_env_proc_write(struct file *file, char *buffer,
 				  size_t count, loff_t *pos)
 {
 	int res;
@@ -92,13 +92,8 @@ static ssize_t srm_env_proc_write(struct file *file, const char __user *buffer,
 	if (!buf)
 		return -ENOMEM;
 
-	res = -EINVAL;
-	if (count >= PAGE_SIZE)
-		goto out;
-
 	res = -EFAULT;
-	if (copy_from_user(buf, buffer, count))
-		goto out;
+	memcpy(buf, buffer, count);
 	buf[count] = '\0';
 
 	ret1 = callback_setenv(id, buf, count);
@@ -109,14 +104,13 @@ static ssize_t srm_env_proc_write(struct file *file, const char __user *buffer,
 		res = (int) ret1;
 	}
 
- out:
 	free_page((unsigned long)buf);
 	return res;
 }
 
 static const struct proc_ops srm_env_proc_ops = {
 	.proc_show	= srm_env_proc_show,
-	.proc_write	= srm_env_proc_write,
+	.proc_write_buf	= srm_env_proc_write,
 };
 
 static int __init
Signature · 1 line
2.53.0
author maintainer
#172 lore raw

PATCH RESEND v2 2/23 ARM: alignment: let procfs copy in writes

In reply to Christian Brauner

Implement ->proc_write_buf() so procfs copies in what is written to /proc/cpu/alignment before it pins the entry, and take the mode from that copy. Writes larger than PAGE_SIZE - 1 bytes fail with -EINVAL now.

---
 arch/arm/mm/alignment.c | 7 +++----
 1 file changed, 3 insertions(+), 4 deletions(-)
arch/arm/mm/alignment.c +3 -4
index 3e5e30968634..11ceefdfa388 100644
@@ -144,14 +144,13 @@ static int alignment_proc_show(struct seq_file *m, void *v)
 	return 0;
 }
 
-static ssize_t alignment_proc_write(struct file *file, const char __user *buffer,
+static ssize_t alignment_proc_write(struct file *file, char *buffer,
 				    size_t count, loff_t *pos)
 {
 	char mode;
 
 	if (count > 0) {
-		if (get_user(mode, buffer))
-			return -EFAULT;
+		mode = buffer[0];
 		if (mode >= '0' && mode <= '5')
 			ai_usermode = safe_usermode(mode - '0', true);
 	}
@@ -160,7 +159,7 @@ static ssize_t alignment_proc_write(struct file *file, const char __user *buffer
 
 static const struct proc_ops alignment_proc_ops = {
 	.proc_show	= alignment_proc_show,
-	.proc_write	= alignment_proc_write,
+	.proc_write_buf	= alignment_proc_write,
 };
 #endif /* CONFIG_PROC_FS */
 
Signature · 1 line
2.53.0
author maintainer
#173 lore raw

PATCH RESEND v2 3/23 ARM: atags: let procfs copy out reads of /proc/atags

In reply to Christian Brauner

Implement ->proc_read_buf() so procfs copies what is read to userspace after it unpinned the entry.

---
 arch/arm/kernel/atags_proc.c | 6 +++---
 1 file changed, 3 insertions(+), 3 deletions(-)
arch/arm/kernel/atags_proc.c +3 -3
index 8411fbfbcb8b..ff28bf24dd30 100644
@@ -10,15 +10,15 @@ struct buffer {
 	char data[] __counted_by(size);
 };
 
-static ssize_t atags_read(struct file *file, char __user *buf,
+static ssize_t atags_read(struct file *file, char *buf,
 			  size_t count, loff_t *ppos)
 {
 	struct buffer *b = pde_data(file_inode(file));
-	return simple_read_from_buffer(buf, count, ppos, b->data, b->size);
+	return memory_read_from_buffer(buf, count, ppos, b->data, b->size);
 }
 
 static const struct proc_ops atags_proc_ops = {
-	.proc_read	= atags_read,
+	.proc_read_buf	= atags_read,
 	.proc_lseek	= default_llseek,
 };
 
Signature · 1 line
2.53.0
author maintainer
#174 lore raw

PATCH RESEND v2 4/23 m68k/bootinfo: let procfs copy out reads of /proc/bootinfo

In reply to Christian Brauner

Implement ->proc_read_buf() so procfs copies what is read to userspace after it unpinned the entry.

---
 arch/m68k/kernel/bootinfo_proc.c | 6 +++---
 1 file changed, 3 insertions(+), 3 deletions(-)
arch/m68k/kernel/bootinfo_proc.c +3 -3
index 857fa2aaa748..4936cf44e86a 100644
@@ -19,15 +19,15 @@ static char bootinfo_tmp[1536] __initdata;
 static void *bootinfo_copy;
 static size_t bootinfo_size;
 
-static ssize_t bootinfo_read(struct file *file, char __user *buf,
+static ssize_t bootinfo_read(struct file *file, char *buf,
 			  size_t count, loff_t *ppos)
 {
-	return simple_read_from_buffer(buf, count, ppos, bootinfo_copy,
+	return memory_read_from_buffer(buf, count, ppos, bootinfo_copy,
 				       bootinfo_size);
 }
 
 static const struct proc_ops bootinfo_proc_ops = {
-	.proc_read	= bootinfo_read,
+	.proc_read_buf	= bootinfo_read,
 	.proc_lseek	= default_llseek,
 };
 
Signature · 1 line
2.53.0
maintainer Reviewed-by Acked-by on v2 4/23
#175 lore raw

Re: [PATCH RESEND v2 04/23] m68k/bootinfo: let procfs copy out reads of /proc/bootinfo

Quoted 4 lines · Christian Brauner

Implement ->proc_read_buf() so procfs copies what is read to userspace after it unpinned the entry.

Gr{oetje,eeting}s,

Geert

Signature · 5 lines
Geert Uytterhoeven -- There's lots of Linux beyond ia32 -- [email protected]

In personal conversations with technical people, I call myself a hacker. But
when I'm talking to journalists I just say "programmer" or something like that.
                                -- Linus Torvalds
author maintainer
#176 lore raw

PATCH RESEND v2 5/23 powerpc/rtas: let procfs copy in writes

In reply to Christian Brauner

Implement ->proc_write_buf() for the files in /proc/powerpc/rtas and /proc/ppc64/rtas so procfs copies in what is written before it pins the entry, and parse what was written from that copy.

firmware_flash, firmware_update and validate_flash take an image in 4k pieces and relied on writes coming up short. They keep doing that with PROC_ENTRY_SHORT_WRITES. Writes to the other files that are larger than PAGE_SIZE - 1 bytes fail with -EINVAL now.

validate_flash only keeps the first 4k of the image and used to swallow whatever was written beyond that in one go. It takes at most 4k per write now, like for the part it keeps, so a writer has to loop there like it has to for the image itself.

---
 arch/powerpc/kernel/rtas-proc.c  | 40 ++++++++++++++++++----------------------
 arch/powerpc/kernel/rtas_flash.c | 38 +++++++++++++++++---------------------
 2 files changed, 35 insertions(+), 43 deletions(-)
arch/powerpc/kernel/rtas-proc.c +18 -22
index 808023f9d1f6..75d64a410209 100644
@@ -138,45 +138,45 @@ static unsigned long rtas_tone_volume = 0;
 static int ppc_rtas_sensors_show(struct seq_file *m, void *v);
 static int ppc_rtas_clock_show(struct seq_file *m, void *v);
 static ssize_t ppc_rtas_clock_write(struct file *file,
-		const char __user *buf, size_t count, loff_t *ppos);
+		char *buf, size_t count, loff_t *ppos);
 static int ppc_rtas_progress_show(struct seq_file *m, void *v);
 static ssize_t ppc_rtas_progress_write(struct file *file,
-		const char __user *buf, size_t count, loff_t *ppos);
+		char *buf, size_t count, loff_t *ppos);
 static int ppc_rtas_poweron_show(struct seq_file *m, void *v);
 static ssize_t ppc_rtas_poweron_write(struct file *file,
-		const char __user *buf, size_t count, loff_t *ppos);
+		char *buf, size_t count, loff_t *ppos);
 
 static ssize_t ppc_rtas_tone_freq_write(struct file *file,
-		const char __user *buf, size_t count, loff_t *ppos);
+		char *buf, size_t count, loff_t *ppos);
 static int ppc_rtas_tone_freq_show(struct seq_file *m, void *v);
 static ssize_t ppc_rtas_tone_volume_write(struct file *file,
-		const char __user *buf, size_t count, loff_t *ppos);
+		char *buf, size_t count, loff_t *ppos);
 static int ppc_rtas_tone_volume_show(struct seq_file *m, void *v);
 static int ppc_rtas_rmo_buf_show(struct seq_file *m, void *v);
 
 static const struct proc_ops ppc_rtas_poweron_proc_ops = {
 	.proc_show	= ppc_rtas_poweron_show,
-	.proc_write	= ppc_rtas_poweron_write,
+	.proc_write_buf	= ppc_rtas_poweron_write,
 };
 
 static const struct proc_ops ppc_rtas_progress_proc_ops = {
 	.proc_show	= ppc_rtas_progress_show,
-	.proc_write	= ppc_rtas_progress_write,
+	.proc_write_buf	= ppc_rtas_progress_write,
 };
 
 static const struct proc_ops ppc_rtas_clock_proc_ops = {
 	.proc_show	= ppc_rtas_clock_show,
-	.proc_write	= ppc_rtas_clock_write,
+	.proc_write_buf	= ppc_rtas_clock_write,
 };
 
 static const struct proc_ops ppc_rtas_tone_freq_proc_ops = {
 	.proc_show	= ppc_rtas_tone_freq_show,
-	.proc_write	= ppc_rtas_tone_freq_write,
+	.proc_write_buf	= ppc_rtas_tone_freq_write,
 };
 
 static const struct proc_ops ppc_rtas_tone_volume_proc_ops = {
 	.proc_show	= ppc_rtas_tone_volume_show,
-	.proc_write	= ppc_rtas_tone_volume_write,
+	.proc_write_buf	= ppc_rtas_tone_volume_write,
 };
 
 static int ppc_rtas_find_all_sensors(void);
@@ -216,16 +216,14 @@ static int __init proc_rtas_init(void)
 
 __initcall(proc_rtas_init);
 
-static int parse_number(const char __user *p, size_t count, u64 *val)
+static int parse_number(const char *p, size_t count, u64 *val)
 {
 	char buf[40];
 
 	if (count > 39)
 		return -EINVAL;
 
-	if (copy_from_user(buf, p, count))
-		return -EFAULT;
-
+	memcpy(buf, p, count);
 	buf[count] = 0;
 
 	return kstrtoull(buf, 10, val);
@@ -235,7 +233,7 @@ static int parse_number(const char __user *p, size_t count, u64 *val)
 /* POWER-ON-TIME                                                      */
 /* ****************************************************************** */
 static ssize_t ppc_rtas_poweron_write(struct file *file,
-		const char __user *buf, size_t count, loff_t *ppos)
+		char *buf, size_t count, loff_t *ppos)
 {
 	struct rtc_time tm;
 	time64_t nowtime;
@@ -269,16 +267,14 @@ static int ppc_rtas_poweron_show(struct seq_file *m, void *v)
 /* PROGRESS                                                           */
 /* ****************************************************************** */
 static ssize_t ppc_rtas_progress_write(struct file *file,
-		const char __user *buf, size_t count, loff_t *ppos)
+		char *buf, size_t count, loff_t *ppos)
 {
 	size_t len = count;
 	unsigned long hex;
 
 	if (count >= MAX_LINELENGTH)
 		count = MAX_LINELENGTH -1;
-	if (copy_from_user(progress_led, buf, count)) { /* save the string */
-		return -EFAULT;
-	}
+	memcpy(progress_led, buf, count); /* save the string */
 	progress_led[count] = 0;
 
 	/* Lets see if the user passed hexdigits */
@@ -302,7 +298,7 @@ static int ppc_rtas_progress_show(struct seq_file *m, void *v)
 /* CLOCK                                                              */
 /* ****************************************************************** */
 static ssize_t ppc_rtas_clock_write(struct file *file,
-		const char __user *buf, size_t count, loff_t *ppos)
+		char *buf, size_t count, loff_t *ppos)
 {
 	struct rtc_time tm;
 	time64_t nowtime;
@@ -661,7 +657,7 @@ static void get_location_code(struct seq_file *m, struct individual_sensor *s,
 /* INDICATORS - Tone Frequency                                        */
 /* ****************************************************************** */
 static ssize_t ppc_rtas_tone_freq_write(struct file *file,
-		const char __user *buf, size_t count, loff_t *ppos)
+		char *buf, size_t count, loff_t *ppos)
 {
 	u64 freq;
 	int error = parse_number(buf, count, &freq);
@@ -686,7 +682,7 @@ static int ppc_rtas_tone_freq_show(struct seq_file *m, void *v)
 /* INDICATORS - Tone Volume                                           */
 /* ****************************************************************** */
 static ssize_t ppc_rtas_tone_volume_write(struct file *file,
-		const char __user *buf, size_t count, loff_t *ppos)
+		char *buf, size_t count, loff_t *ppos)
 {
 	u64 volume;
 	int error = parse_number(buf, count, &volume);
arch/powerpc/kernel/rtas_flash.c +17 -21
index f1cd105f7426..77a4627f2507 100644
@@ -307,7 +307,7 @@ static ssize_t rtas_flash_read_num(struct file *file, char __user *buf,
  * count is.  If the system is low on memory it will be just as well
  * that we fail....
  */
-static ssize_t rtas_flash_write(struct file *file, const char __user *buffer,
+static ssize_t rtas_flash_write(struct file *file, char *buffer,
 				size_t count, loff_t *off)
 {
 	struct rtas_update_flash_t *const uf = &rtas_update_flash_data;
@@ -343,16 +343,11 @@ static ssize_t rtas_flash_write(struct file *file, const char __user *buffer,
 		next_free = 0;
 	}
 
-	if (count > RTAS_BLK_SIZE)
-		count = RTAS_BLK_SIZE;
 	p = kmem_cache_zalloc(flash_block_cache, GFP_KERNEL);
 	if (!p)
 		return -ENOMEM;
 	
-	if(copy_from_user(p, buffer, count)) {
-		kmem_cache_free(flash_block_cache, p);
-		return -EFAULT;
-	}
+	memcpy(p, buffer, count);
 	fl->blocks[next_free].data = p;
 	fl->blocks[next_free].length = count;
 	fl->num_blocks++;
@@ -390,7 +385,7 @@ static ssize_t manage_flash_read(struct file *file, char __user *buf,
 	return simple_read_from_buffer(buf, count, ppos, msg, msglen);
 }
 
-static ssize_t manage_flash_write(struct file *file, const char __user *buf,
+static ssize_t manage_flash_write(struct file *file, char *buf,
 				size_t count, loff_t *off)
 {
 	struct rtas_manage_flash_t *const args_buf = &rtas_manage_flash_data;
@@ -401,9 +396,8 @@ static ssize_t manage_flash_write(struct file *file, const char __user *buf,
 
 	if ((args_buf->status == MANAGE_AUTH) || (count == 0))
 		return count;
-		
-	if (get_user(cmd, buf))
-		return -EFAULT;
+
+	cmd = buf[0];
 
 	if (cmd == '0')
 		op = RTAS_REJECT_TMP_IMG;
@@ -471,7 +465,7 @@ static ssize_t validate_flash_read(struct file *file, char __user *buf,
 	return simple_read_from_buffer(buf, count, ppos, msg, msglen);
 }
 
-static ssize_t validate_flash_write(struct file *file, const char __user *buf,
+static ssize_t validate_flash_write(struct file *file, char *buf,
 				    size_t count, loff_t *off)
 {
 	struct rtas_validate_flash_t *const args_buf =
@@ -494,11 +488,7 @@ static ssize_t validate_flash_write(struct file *file, const char __user *buf,
 		args_buf->status = VALIDATE_INCOMPLETE;
 	}
 
-	if (!access_ok(buf, count))
-		return -EFAULT;
-
-	if (copy_from_user(args_buf->buf + *off, buf, count))
-		return -EFAULT;
+	memcpy(args_buf->buf + *off, buf, count);
 
 	*off += count;
 	return count;
@@ -632,8 +622,10 @@ static const struct rtas_flash_file rtas_flash_files[] = {
 		.filename	= "powerpc/rtas/" FIRMWARE_FLASH_NAME,
 		.handle		= RTAS_FN_IBM_UPDATE_FLASH_64_AND_REBOOT,
 		.status		= &rtas_update_flash_data.status,
+		.ops.proc_flags	= PROC_ENTRY_SHORT_WRITES,
 		.ops.proc_read	= rtas_flash_read_msg,
-		.ops.proc_write	= rtas_flash_write,
+		.ops.proc_write_buf = rtas_flash_write,
+		.ops.proc_write_size = RTAS_BLK_SIZE,
 		.ops.proc_release = rtas_flash_release,
 		.ops.proc_lseek	= default_llseek,
 	},
@@ -641,8 +633,10 @@ static const struct rtas_flash_file rtas_flash_files[] = {
 		.filename	= "powerpc/rtas/" FIRMWARE_UPDATE_NAME,
 		.handle		= RTAS_FN_IBM_UPDATE_FLASH_64_AND_REBOOT,
 		.status		= &rtas_update_flash_data.status,
+		.ops.proc_flags	= PROC_ENTRY_SHORT_WRITES,
 		.ops.proc_read	= rtas_flash_read_num,
-		.ops.proc_write	= rtas_flash_write,
+		.ops.proc_write_buf = rtas_flash_write,
+		.ops.proc_write_size = RTAS_BLK_SIZE,
 		.ops.proc_release = rtas_flash_release,
 		.ops.proc_lseek	= default_llseek,
 	},
@@ -650,8 +644,10 @@ static const struct rtas_flash_file rtas_flash_files[] = {
 		.filename	= "powerpc/rtas/" VALIDATE_FLASH_NAME,
 		.handle		= RTAS_FN_IBM_VALIDATE_FLASH_IMAGE,
 		.status		= &rtas_validate_flash_data.status,
+		.ops.proc_flags	= PROC_ENTRY_SHORT_WRITES,
 		.ops.proc_read	= validate_flash_read,
-		.ops.proc_write	= validate_flash_write,
+		.ops.proc_write_buf = validate_flash_write,
+		.ops.proc_write_size = VALIDATE_BUF_SIZE,
 		.ops.proc_release = validate_flash_release,
 		.ops.proc_lseek	= default_llseek,
 	},
@@ -660,7 +656,7 @@ static const struct rtas_flash_file rtas_flash_files[] = {
 		.handle		= RTAS_FN_IBM_MANAGE_FLASH_IMAGE,
 		.status		= &rtas_manage_flash_data.status,
 		.ops.proc_read	= manage_flash_read,
-		.ops.proc_write	= manage_flash_write,
+		.ops.proc_write_buf = manage_flash_write,
 		.ops.proc_lseek	= default_llseek,
 	}
 };
Signature · 1 line
2.53.0