Re: [PATCH] secretmem: Prevent secretmem_users from wrapping to zero

From: Matthew Wilcox
Date: Mon Oct 25 2021 - 21:35:55 EST


On Mon, Oct 25, 2021 at 04:37:01PM -0700, Linus Torvalds wrote:
> For example, traditionally, on x86, with atomic counting there are
> three special situations: negative, 0 and positive. So if you use the
> traditional x86 counting atomics (just add/sub/inc/dec, no xadd) then
> there are situations where you can get more information about the
> result in %eflags if you don't use zero as the initial value, but -1.
>
> Because then you can do "inc", and if ZF is set, you know you were the
> _first_ person to increment it. And when you use "dec", and SF is set
> afterwards, you know you are the _last_ person to decrement it.
>
> That was useful when things like "xadd" weren't available, and cmpxchg
> loops are expensive. So we used to have counters where -1 was that
> "zero point". Very similar to your "1 is the zero point".
>
> But was it _logical_? No. It was an implementation trick. I think
> we've removed all those cases because it was so subtle and confusing
> (but maybe we still have it somewhere - I did not check).

We still do it for page->_mapcount; it's biased to -1 so that both
"the page has exactly one mapping" and "the page has no mapping" are
cheaply checkable conditions.

But, as you say, that's invisible to the users. page_mapcount() is
return atomic_read(&page->_mapcount) + 1;