Those calculations assume that the page size is a power of 2 (which is the case for
all systems that I know of), for example
PageSize = 4096 = 2^12 = 1000000000000 (binary)
Then (written as binary numbers)
PageSize-1 = 00...00111111111111
~(PageSize-1) = 11...11000000000000
which means that
(VirtualAddr & ~(PageSize-1))
is VirtualAddr
with the lower 12 bits set to zero or, in other words,
VirtualAddr
rounded down to the next multiple of 2^12 = PageSize
.
Now you can (hopefully) see that in
len = ((PageSize-1)&len) ? ((len+PageSize) & ~(PageSize-1)):len;
the first expression
((PageSize-1)&len)
is zero exactly if len
is a multiple of PageSize
. In that case, len
is left
unchanged. Otherwise (len + PageSize)
is rounded down to the next multiple of
PageSize
.
So in any case, len
is rounded up to the next multiple of PageSize
.
if (len<=PageSize)
then it'slen
, otherwise it's len rounded up to the next page boundary. That's quite different than what you described. – Forebode((VirtualAddr+PageSize-1) & ~(PageSize-1))
instead. – Forebodelang-py >>> hex(0x00053000 & ~(4095)) '0x53000' >>> hex(0x00053FFF & ~(4095)) '0x53000' >>> hex(0x00052FFF & ~(4095)) '0x52000'
– Footsie