net/socket.c: use straight fdget/fdput (resend)
Subsystems (4)
Al Viro
maintainerPATCH 1/1 net/socket.c: use straight fdget/fdput (resend)
[sigh... turns out that my .muttrc had no netdev alias ;-/]
Checking the theory that the important part in sockfd_lookup_light() is avoiding needless file refcount operations, not the marginal reduction of the register pressure from not keeping a struct file pointer in the caller.
If that's true, we should get the same benefits from straight fdget()/fdput(). And AFAICS with sane use of CLASS(fd) we can get a better code generation...
Would be nice if somebody tested it on networking test suites (including benchmarks)...
---
include/linux/file.h +6 -6
@@ -29,12 +29,6 @@ extern struct file *alloc_file_pseudo_noaccount(struct inode *, struct vfsmountextern struct file *alloc_file_clone (struct file *,int flags,const struct file_operations *); -static inline void fput_light (struct file *file,int fput_needed) -{ -if (fput_needed) -fput (file); -} -struct fd {struct file *file;unsigned int flags;
@@ -76,6 +70,12 @@ static inline struct fd fdget_pos(int fd)return __to_fd (__fdget_pos (fd)); } +static inline bool fd_empty (struct fd f) +{ +// better code with gcc that way +return unlikely (!(f.flags | (unsigned long )f.file)); +} +static inline void fdput_pos (struct fd f) {if (f.flags &FDPUT_POS_UNLOCK )
net/socket.c +151 -184
553 lines not on this page · raw message
----- End forwarded message -----
Quoted 5 lines · Al Viro
Checking the theory that the important part in
sockfd_lookup_light()is avoiding needless file refcount operations, not the marginal reduction of the register pressure from not keeping a struct file pointer in the caller.
Yeah, the register pressure thing is not likely an issue. That said, I think we can fix it.
Quoted 1 line
If that's true, we should get the same benefits from straight fdget()/fdput().
Agreed.
That said, your patch is just horrendous.
Review
Quoted 5 lines
(quoted diff) +5
-0+static inline bool fd_empty(struct fd f) +{ + // better code with gcc that way + return unlikely(!(f.flags | (unsigned long)f.file)); +}
Ok, this is disgusting. I went all "WTF?"
And then looked at why you would say that testing two different fields in a 'struct fd' would possibly be better than just checking one.
And I see why that's the case - it basically short-circuits the (inlined) __to_fd() logic, and the compiler can undo it and look at the original single-word value.
But it's still disgusting. If there is anything else in between, the compiler wouldn't then notice any more.
What we *really* should do is have 'struct fd' just *be* that single-word value, never expand it to two words at all, and instead of doing "fd.file" we'd do "fd_file(fd)" and "fd_flags(fd)".
Maybe it's not too late to do that?
This is *particularly* true for the socket code that doesn't even want the 'struct file *' at all outside of that "check that it's a socket, then turn it into a socket pointer". So _particularly_ in that context, having a "fd_file()" helper to do the (trivial) unpacking would work very well.
But even without changing 'struct fd', maybe we could just have "__fdget()" and friends not return a "unsigned long", but a "struct rawfd".
Which would is a struct with an unsigned long.
There's actually a possible future standard C++ extension for what we want to do ("C++ tagged pointers") and while it might make it into C eventually, we'd have to do it manully with ugly inline helpers (LLVM does it manually in C++ with a PointerIntPair class).
IOW, we could do something like the attached. I think it's actually almost a cleanup, and now your socket things can use "struct rawfd" and that fd_empty() becomes
static inline bool rawfd_empty(struct rawfd raw) { return !raw.word; }
instead. Still somewhat disgusting, but now it's a "C doesn't have tagged pointers, so we do this by hand" _understandable_ disgusting.
Hmm? The attached patch compiles. It looks "ObviouslyCorrect(tm)". But it might be "TotallyBroken(tm)". You get the idea.
Linus
fs/file.c | 22 +++++++++++----------- include/linux/file.h | 22 +++++++++++++++++----- 2 files changed, 28 insertions(+), 16 deletions(-)
fs/file.c +11 -11
@@ -1128,7 +1128,7 @@ EXPORT_SYMBOL(task_lookup_next_fdget_rcu);* The fput_needed flag returned by fget_light should be passed to the * corresponding fput_light. */ -static unsigned long __fget_light (unsigned int fd,fmode_t mask) +static struct rawfd __fget_light (unsigned int fd,fmode_t mask) {struct files_struct *files = current->files;struct file *file;
@@ -1145,22 +1145,22 @@ static unsigned long __fget_light(unsigned int fd, fmode_t mask)if (likely (atomic_read_acquire (&files->count) ==1 )) { file =files_lookup_fd_raw (files, fd);if (!file ||unlikely (file->f_mode & mask)) -return 0 ; -return (unsigned long )file; +return EMPTY_RAWFD ; +return (struct rawfd ) { (unsigned long )file }; }else { file =__fget_files (files, fd, mask);if (!file) -return 0 ; -return FDPUT_FPUT | (unsigned long )file; +return EMPTY_RAWFD ; +return (struct rawfd ) {FDPUT_FPUT | (unsigned long )file }; } } -unsigned long __fdget (unsigned int fd) +struct rawfd __fdget (unsigned int fd) {return __fget_light (fd,FMODE_PATH ); }EXPORT_SYMBOL (__fdget); -unsigned long __fdget_raw (unsigned int fd) +struct rawfd __fdget_raw (unsigned int fd) {return __fget_light (fd,0 ); }
@@ -1181,13 +1181,13 @@ static inline bool file_needs_f_pos_lock(struct file *file) (file_count (file) >1 || file->f_op->iterate_shared); } -unsigned long __fdget_pos (unsigned int fd) +struct rawfd __fdget_pos (unsigned int fd) { -unsigned long v =__fdget (fd); -struct file *file = (struct file *)(v & ~3 ); +struct rawfd v =__fdget (fd); +struct file *file =fdfile (v);if (file &&file_needs_f_pos_lock (file)) { - v |=FDPUT_POS_UNLOCK ; + v.word |=FDPUT_POS_UNLOCK ;mutex_lock (&file->f_pos_lock); }return v;
include/linux/file.h +17 -5
@@ -42,6 +42,18 @@ struct fd {#define FDPUT_FPUT 1#define FDPUT_POS_UNLOCK 2 +/* "Tagged file pointer" */ +struct rawfd { +unsigned long word; +}; +#define EMPTY_RAWFD (struct rawfd) { 0 } + +static inline struct file *fdfile (struct rawfd raw) +{return (struct file *) (raw.word & ~3 ); } + +static inline unsigned int fdflags (struct rawfd raw) +{return raw.word &3 ; } +static inline void fdput (struct fd fd) {if (fd.flags &FDPUT_FPUT )
@@ -51,14 +63,14 @@ static inline void fdput(struct fd fd)extern struct file *fget (unsigned int fd);extern struct file *fget_raw (unsigned int fd);extern struct file *fget_task (struct task_struct *task,unsigned int fd); -extern unsigned long __fdget (unsigned int fd); -extern unsigned long __fdget_raw (unsigned int fd); -extern unsigned long __fdget_pos (unsigned int fd); +extern struct rawfd __fdget (unsigned int fd); +extern struct rawfd __fdget_raw (unsigned int fd); +extern struct rawfd __fdget_pos (unsigned int fd);extern void __f_unlock_pos (struct file *); -static inline struct fd __to_fd (unsigned long v) +static inline struct fd __to_fd (struct rawfd raw) { -return (struct fd ){(struct file *)(v & ~3 ),v &3 }; +return (struct fd ){fdfile (raw),fdflags (raw)}; }static inline struct fd fdget (unsigned int fd)
Quoted 3 lines · Linus Torvalds
IOW, we could do something like the attached. I think it's actually almost a cleanup [..]
The reason I say that is this part of the patch:
-static inline struct fd __to_fd(unsigned long v) +static inline struct fd __to_fd(struct rawfd raw)
{
- return (struct fd){(struct file *)(v & ~3),v & 3};
+ return (struct fd){fdfile(raw),fdflags(raw)};
}
which I think actually improves on our current situation.
No, my fdfile/fdflags functions aren't pretty, but they have more type safety than the bare "unsigned long", and in that "__to_fd()" case I think it actually makes that unpacking operation much more obvious.
It might be good to have the reverse "packing" helper inline function too, so that __fdget() wouldn't do this:
return (struct rawfd) { FDPUT_FPUT | (unsigned long)file };but instead have some kind of "mkrawfd()" helper that does the above, and we'd have
return mkrawfd(file, FDPUT_FPUT);
instead. That would obviate my EMPTY_RAWFD macro, and we'd just use "mkrawfd(NULL, 0)"?
Maybe this is bikeshedding. But I'd rather have this kind of explicit one-word interface with a wrapped tagged pointer than have something as subtle as your fd_empty() that magically generates better code in certain very specific circumstances.
Linus
Al Viro
maintainerQuoted 24 lines · Linus Torvalds
Quoted 5 lines · Al Viro
Checking the theory that the important part in
sockfd_lookup_light()is avoiding needless file refcount operations, not the marginal reduction of the register pressure from not keeping a struct file pointer in the caller.Yeah, the register pressure thing is not likely an issue. That said, I think we can fix it.
Quoted 1 line
If that's true, we should get the same benefits from straight fdget()/fdput().
Agreed.
That said, your patch is just horrendous.
Review
Quoted 5 lines
(quoted diff) +5
-0+static inline bool fd_empty(struct fd f) +{ + // better code with gcc that way + return unlikely(!(f.flags | (unsigned long)f.file)); +}Ok, this is disgusting. I went all "WTF?"
Quoted 6 lines
And then looked at why you would say that testing two different fields in a 'struct fd' would possibly be better than just checking one.
And I see why that's the case - it basically short-circuits the (inlined)
__to_fd()logic, and the compiler can undo it and look at the original single-word value.
Not really. The real reason is different - there is a constraint on possible values of struct fd. No valid instance can ever have NULL file and non-zero flags.
The usual pattern is this:
fd = something; if (!fd.file) return -EBADF; // we know that fd.file != NULL .... fdput(fd); return something_else;
Switch to __cleanup would expand into something like
fd = something;
if (!fd.file) {
fdput(fd);
return -EBADF;
}
// we know that fd.file != NULL
...
fdput(fd);
return something_else;Look at the early exit there in more details:
if (!fd.file) {
if (fd.flags & FDPUT_FPUT)
fput(fd.file); // would oops
return -EBADF;
}It *is* correct, but only because NULL fd.file can only happen with zero fd.flags, so this fput() call is a dead code.
Boths your and mine variants are equivalent to this:
if (!fd.file && !fd.flags) {
fpdut(fd); // compiler will eliminate it
return -EBADF;
}
// we assume that fd.file is non-NULL now
...
fdput(fd);
return something_else;
and IMO both attack the problem at the wrong place. If we
keep the check as it is (NULL fd.file) and turn fdput() into
if ((fd.flags & FDPUT_FPUT) && fd.file)
fput(fd.file);we will get obviously correct behaviour with good code generation - pretty much all current users of fdput() are downstream of the check that fd.file is non-NULL and gcc will be able to optimize the second part of condition away.
IOW, we don't disturb the existing explicit callers and the only implicit ones (from __cleanup()) that might get an extra check are the ones on failure exits between getting fd and checking it to be empty. Not a lot of those...
How about the following?
commit b3692a6e34e9dcfb1d9705782bc928bd04d5640d
Author: Al Viro <[email protected]> Date: Sat May 25 23:32:20 2024 -0400
[experimental] net/socket.c: use straight fdget/fdput
Checking the theory that the important part in sockfd_lookup_light() is avoiding needless file refcount operations, not the marginal reduction of the register pressure from not keeping a struct file pointer in the caller.
If that's true, we should get the same benefits from straight fdget()/fdput(). And AFAICS with sane use of CLASS(fd) we can get a better code generation...
Would be nice if somebody tested it on networking test suites (including benchmarks)...
include/linux/file.h +6 -7
@@ -29,12 +29,6 @@ extern struct file *alloc_file_pseudo_noaccount(struct inode *, struct vfsmountextern struct file *alloc_file_clone (struct file *,int flags,const struct file_operations *); -static inline void fput_light (struct file *file,int fput_needed) -{ -if (fput_needed) -fput (file); -} -struct fd {struct file *file;unsigned int flags;
@@ -44,7 +38,7 @@ struct fd {static inline void fdput (struct fd fd) { -if (fd.flags &FDPUT_FPUT ) +if ((fd.flags &FDPUT_FPUT ) && fd.file)fput (fd.file); }
@@ -76,6 +70,11 @@ static inline struct fd fdget_pos(int fd)return __to_fd (__fdget_pos (fd)); } +static inline bool fd_empty (struct fd f) +{ +return unlikely (!f.file); +} +static inline void fdput_pos (struct fd f) {if (f.flags &FDPUT_POS_UNLOCK )
net/socket.c +151 -184
553 lines not on this page · raw message
Quoted 6 lines · Al Viro
Not really. The real reason is different - there is a constraint on possible values of struct fd. No valid instance can ever have NULL file and non-zero flags.
The usual pattern is this:
[ snip snip ]
Ugh. I still hate it, including your new version. I suspect it will easily generate the extra test at fd_empty() time, and your new version would instead just move that extra test at fdput() time instead.
Hopefully in most cases the compiler sees the previous test for fd.file, realizes the new test is unnecessary and optimizes it away.
Except we most definitely pass around 'struct fd *' in some places (at least ovlfs), so I doubt that will be the case everywhere.
What would make more sense is if you make the "fd_empty()" test be about the _flags_, and then both the fp_empty() test and the test inside fdput() would be testing the same things.
Sadly, we'd need another bit in the flags. One option is easy enough - we'd just have to make 'struct file' always be 8-byte aligned, which it effectively always is.
Or we'd need to make the rule be that FDPUT_POS_UNLOCK only gets set if FDPUT_FPUT is set.
Because I think we could have even a two-bit tag value have that "no fd" case:
00 - no fd
01 - fd but no need for fput
10 - fd needs fput
11 - fd needs pos unlock and fput
but as it is, that's not what we have. Right now we have
00 - no fd or fd with no need for fput ("look at fd.file to decide") 01 - fd needs fput
10 - fd pos unlock but no fput
11 - fd pos unlock and fput
but that 10 case looks odd to me. Why would we ever need a pos unlock but no fput? The reason we don't need an fput is that we're the only thread that has access to the file pointer, but that also implies that we shouldn't need to lock the position.
So now I've just confused myself. Why *do* we have that 10 pattern?
Adding a separate bit would certainly avoid any complexity, and then you'd have "flags==0 means no file pointer" and the "fd_empty()" test would then make the fdput) test obviously unnecessary in the usual pattern.
Linus
Al Viro
maintainerQuoted 2 lines · Linus Torvalds
Hopefully in most cases the compiler sees the previous test for fd.file, realizes the new test is unnecessary and optimizes it away.
It does.
Quoted 2 lines
Except we most definitely pass around 'struct fd *' in some places (at least ovlfs), so I doubt that will be the case everywhere.
... and those places need care, really. I've done that review quite recently. I don't think you'd been on Cc in related thread... <checks> nope.
|| Another is overlayfs ovl_real_fdget() and ovl_real_fdget_meta(). || Those two are arguably too clever for their readers' good. || It's still "borrow or clone, and remember which one had it been", || but that's mixed with returning errors: || err = ovl_read_fdget(file, &fd); || may construct and store a junk value in fd if err is non-zero. || Not a bug, but only because all callers remember to ignore that || value in such case.
Junk value as in e.g. <ERR_PTR(-EIO), FDPUT_FPUT>; it's trivial to avoid (
file = ovl_open_realfile(file, &realpath);
if (IS_ERR(file))
return ERR_PTR(file);
real->flags = FDPUT_FPUT;
real->file = file;
return 0;
instead of
real->flags = FDPUT_FPUT;
real->file = ovl_open_realfile(file, &realpath);
return PTR_ERR_OR_ZERO(real->file);we have there right now and similar for <ERR_PTR(-EPERM), 0> pairs), but note that anything like your switch to struct-wrapped unsigned long would need similar massage there anyway.
Quoted 3 lines
What would make more sense is if you make the "
fd_empty()" test be about the _flags_, and then both thefp_empty()test and the test insidefdput()would be testing the same things.
Umm... What encoding would you use?
Quoted 6 lines
Sadly, we'd need another bit in the flags. One option is easy enough - we'd just have to make 'struct file' always be 8-byte aligned, which it effectively always is.
Or we'd need to make the rule be that
FDPUT_POS_UNLOCKonly gets set ifFDPUT_FPUTis set.
Huh? That makes no sense - open a file, fork, and there you go; same file reference in unshared descriptor tables in child and parent. You definitely don't want to bump refcount on fdget_pos() in either and you don't want to lose read/write/lseek serialization.
FDPUT_FPUT is *not* a property of file; it's about the original reference to file not being guaranteed to stay pinned for the lifetime of struct fd in question...
Quoted 4 lines · Al Viro
FDPUT_FPUTis *not* a property of file; it's about the original reference to file not being guaranteed to stay pinned for the lifetime of struct fd in question...
Yup. I forgot the rules and thought we set FDPUT_PUT for cases where we had exclusive access to 'struct file *', but it's for cases where we have exclusive access to the 'int fd'.
Linus
Al Viro
maintainerQuoted 5 lines · Al Viro
Quoted 3 lines
What would make more sense is if you make the "
fd_empty()" test be about the _flags_, and then both thefp_empty()test and the test insidefdput()would be testing the same things.Umm... What encoding would you use?
FWIW, _if_ we go for replacement of struct fd with struct-wrapped unsigned long and actually steal another bit from pointer, we could actually use that to encode errors as well...
If bit 0 is clear for file reference and set for an error, we could use bit 1 to represent borrowed vs. cloned and bit 2 for need to unlock...
overlayfs would be happier that way - we could have those functions return struct fd directly, and pass the error value that way. fdget() would report EBADF explicitly on empty slot - not a big deal. Hmm...
Let me play with that a bit and see if I can come up with something tolerable.
We could add that in parallel to existing struct fd; we'd need a name for replacement, though - anything like "rawfd" is asking for confusion around fdget_raw(), and we'd need replacements for fdget() et.al. that would yield those.
Alternatively, with a sane set of helpers we could actually _replace_ struct fd definition without a huge flagday commit - start with adding #define fd_file(fd) ((fd).file)
#define fd_valid(fd) (fd_file(fd) != NULL)
convert the current users, one by one (fairly mechanical patches), then change the definition of struct fd. The last step would affect
* definitions of helpers
* adding fd-constructing macros (ERR_FD, etc.)
* converting the few places that really construct those
suckers (fdget() et.al., overlayfs, a couple of explicit initializers to {NULL, 0}).
It's not a huge amount of work and the flagday step would be fairly small, but we'd probably need to split that over a couple of cycles - helpers in one, along with renaming fd.file to e.g. fd.__file_use_the_damn_helpers, then in the next cycle do the switchover.
Hell knows; let me play with that a bit and let's see what falls out...
Quoted 3 lines · Al Viro
Alternatively, with a sane set of helpers we could actually _replace_ struct fd definition without a huge flagday commit
It wouldn't even be all that huge. We've got less than 200 of those 'struct fd' users, and some of them hardly even look at the result, but just pass it off to other helpers (ie the kernel/bpf/syscalls.c pattern).
With just a couple of helpers it would be mostly a cleanup.
Linus
Quoted 2 lines · Linus Torvalds
With just a couple of helpers it would be mostly a cleanup.
Looking around, I think we could even take four bits. Without any debugging, 'struct file' is 160 bytes on 32-bit, it would not hurt at all to just force a 16-byte alignment.
In fact, in practice it is aligned more than that - we already use SLAB_HWCACHE_ALIGN, which in most cases means that it's 64-byte aligned.
But to be safe, we should specify the 16 bytes in the kmem_cache_create() call, and we should just make this all very explicit:
--- a/fs/file_table.c +++ b/fs/file_table.c @@ -512,7 +512,7 @@ EXPORT_SYMBOL(__fput_sync);
void __init files_init(void)
{
- filp_cachep = kmem_cache_create("filp", sizeof(struct file), 0,
+ filp_cachep = kmem_cache_create("filp", sizeof(struct file), 16,
SLAB_TYPESAFE_BY_RCU | SLAB_HWCACHE_ALIGN |
SLAB_PANIC | SLAB_ACCOUNT, NULL);
percpu_counter_init(&nr_files, 0, GFP_KERNEL); --- a/include/linux/fs.h
+++ b/include/linux/fs.h
@@ -1025,7 +1025,7 @@ struct file {
errseq_t f_wb_err;
errseq_t f_sb_err; /* for syncfs */
} __randomize_layout
- __attribute__((aligned(4))); /* lest something weird
decides that 2 is OK */
+ __attribute__((aligned(16))); /* Up to four tag bits */
struct file_handle {
__u32 handle_bytes;and while four tag bits isn't something to waste, it looks pretty reasonable here.
Linus
Al Viro
maintainerQuoted 1 line · Al Viro
Hell knows; let me play with that a bit and let's see what falls out...
gcc optimizer is... interesting:
if (v & 1)
if (!(v & 3))
foo();is *NOT* collapsed into a no-op. Not even
if (v & 1)
if (!(v & 1) && !(v & 2))
foo();is good enough for it.
if (v & 1)
if (!(v & 1))
if (!(v & 2))
foo();is recognized, thankfully, but... WTF? As far as I can tell,
if (!(v & 1) && !(v & 2))
gets turned into if (!(v & 3)), and then gcc gets stuck on that.
if (!(v & 1)) if (!(v & 2))is turned into the same, but apparently only after it actually looks at both parts in context of what it knows about the earlier checks.
clang handles all forms just fine, but gcc does not ;-/