开发者

Please explain what this piece of C code does

Can someone explain what is this piece of code do?

p开发者_运维技巧a_offset = offset & ~(sysconf(_SC_PAGE_SIZE) - 1);

/* offset for mmap() must be page aligned */

I understand that here sysconf returns the page size, which lets assume that it is 4096, but after that I am not able to understand the logic. Thanks in advance.


If sysconf returns the page size, which is a power of two or 00..00100..00 in binary, - 1 makes a mask of that number (that is, it makes a number of the form 00..0011..11, then ~ computes the reverse of this mask (11..1100..00). Lastly, the bitwise and & operation between the newly created mask and offset rounds offset down to the nearest multiple of the page size.


assuming page size is a power of 2, the expression will return offset % _SC_PAGE_SIZE; so if offset is 5000 and page size is 4096 it will return 4.

update: i was wrong, see comments below. also the context as requested by OP is of virtual address to physical address translation in an operating system. the expression above gives the virtual page address, which is translated into a physical page address. after translation the byte being addressed is found at page_address + (offset % _SC_PAGE_SIZE).


4096 is 212, so sysconf(_SC_PAGE_SIZE) - 1 is 12 1's in binary. The complement (~) is a series of leading 1's followed by 12 0's. offset & 1111...0000 0000 0000 will therefore extract the bits used to represent the page number.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜