5

In xv6 mmu.h file, there are these 2 lines of code

    #define PGROUNDUP(sz)  (((sz)+PGSIZE-1) & ~(PGSIZE-1))
    #define PGROUNDDOWN(a) (((a)) & ~(PGSIZE-1))

What do they do?

K.Wu
  • 3,553
  • 6
  • 31
  • 55
  • 1
    "round up" and "round down" might be inferred from the names. And given "mmu", PG probably means "page". – Oliver Charlesworth Apr 08 '17 at 00:52
  • the important thing to know is that `~` is the bitwise NOT operator – bruceg Apr 08 '17 at 00:56
  • 1
    Thanks @OliverCharlesworth, my understanding is that, if I replace "sz" in PGROUNDUP with the size of the current running process, it will return the size of all pages allocated to the process, and divide that by the size of a single page, then we get the number of pages allocated to that process. Do you think that is correct? – K.Wu Apr 08 '17 at 01:12
  • Thanks @bruceg, do you think my understanding up there is correct? – K.Wu Apr 08 '17 at 01:13
  • 1
    @K.Wu I'm not too sure about that. It looks like PGROUNDUP is rounding up a size to the next multiple of PGSIZE, while PGROUNDDOWN is rounding down to the previous multiple of PGSIZE. If your PGSIZE is 1024, then PGROUNDUP(1099) would be 2048, while PGROUNDDOWN(1099) would be 1024. So, if the size of your current running process is 1099, there would be two pages allocated. Is that what you're thinking? – bruceg Apr 09 '17 at 04:52

2 Answers2

12

PGROUNDUP and PGROUNDDOWN are macros to round the address sent to a multiple of the PGSIZE. These are generally used to obtained page aligned address. PGROUNDUP will round the address to the higher multiple of PGSIZE while PGROUNDDOWN will round it to the lower multiple of PGSIZE.

Let us take an example if PGROUNDUP is called on a system with PGSIZE 1KB with the address 620:

  • PGROUNDUP(620) ==> ((620 + (1024 -1)) & ~(1023)) ==> 1024
  • The address 620 was rounded up to 1024.

Similarly for PGROUNDDOWN consider:

  • PGROUNDDOWN(2400) ==> (2400 & ~(1023)) ==> 2048
  • The address 2400 was rounded down to 2048.
Jet Blue
  • 5,109
  • 7
  • 36
  • 48
Rhythm Patwa
  • 219
  • 3
  • 6
0

First you should know (PGSIZE-1)) is the max remainder (addr/page_size)

  • round down

Essentially we only need to abandon the remainder part,and & ~(PGSIZE-1)) makes the thing

  • round up
God_J
  • 1
  • 1