Linux: free memory for buddies

Can anyone explain this code?

page_idx = page_to_pfn(page) & ((1 << MAX_ORDER) - 1);

      

page_to_pfn () already returned page_idx, so what does '&' mean to use for? Or does page_to_pfn () return something else?

+3


source to share


2 answers


You need to know what x & ((1 << n) - 1)

is the trick that means x % ((int) pow(2, n))

. This is often faster (but it is better to leave such optimizations to the compiler).

So, in this case, it does it modulo pow(2, MAX_ORDER)

. This brings up the wrapper; if page_idx is greater than pow(2, MAX_ORDER)

, it will fall back to 0. Here's the equivalent but more readable code:



const int MAX_ORDER_N = (int) pow(2, MAX_ORDER);

page_idx = page_to_pfn(page);

/* wraparound */
while (page_idx > MAX_ORDER_N) {
    page_idx -= MAX_ORDER_N;
}

      

+2


source


This is a bit mask that ensures that page_idx does not exceed a certain value (2 ^ MAX_ORDER).

# define MAX_ORDER (8)

(1 << MAX_ORDER) /* 100000000 */
- 1 /* flip bits, same as ~(…) due to two-complement: 11111111 */

      



So, you only have eight least significant bits left

  1010010101001
& 0000011111111
= 0000010101001

      

+1


source







All Articles