[PATCH] clean overflow checks in count_mounts() a bit

From: Al Viro
Date: Sun Feb 13 2022 - 22:42:25 EST


On Mon, Feb 14, 2022 at 03:04:27AM +0000, Al Viro wrote:

> I don't believe it's worth the trouble. Sure, you run that loop
> only once, instead of once per copy. And if that's more than noise,
> compared to allocating the same mounts we'd been counting, connecting
> them into tree, hashing, etc., I would be *very* surprised.
>
> NAKed-by: Al Viro <viro@xxxxxxxxxxxxxxxxxx>

BTW, speaking of count_mounts(), the wraparound checks there are somewhat
confused: x + y wraparound will lead to both x + y < x and x + y < y - no
need to check both (the value of x + y is either their sum as natural
numbers, in which case there's no wraparound and both checks are false,
or the sum minus 2^32, in which case both checks are true since both x and
y are below 2^32).

IMO more straightforward code would be better here.

Signed-off-by: Al Viro <viro@xxxxxxxxxxxxxxxxxx>
---
diff --git a/fs/namespace.c b/fs/namespace.c
index 13d025a9ecf5d..42d4fc21263b2 100644
--- a/fs/namespace.c
+++ b/fs/namespace.c
@@ -2069,22 +2069,23 @@ static int invent_group_ids(struct mount *mnt, bool recurse)
int count_mounts(struct mnt_namespace *ns, struct mount *mnt)
{
unsigned int max = READ_ONCE(sysctl_mount_max);
- unsigned int mounts = 0, old, pending, sum;
+ unsigned int mounts = 0;
struct mount *p;

+ if (ns->mounts >= max)
+ return -ENOSPC;
+ max -= ns->mounts;
+ if (ns->pending_mounts >= max)
+ return -ENOSPC;
+ max -= ns->pending_mounts;
+
for (p = mnt; p; p = next_mnt(p, mnt))
mounts++;

- old = ns->mounts;
- pending = ns->pending_mounts;
- sum = old + pending;
- if ((old > sum) ||
- (pending > sum) ||
- (max < sum) ||
- (mounts > (max - sum)))
+ if (mounts > max)
return -ENOSPC;

- ns->pending_mounts = pending + mounts;
+ ns->pending_mounts += mounts;
return 0;
}