A confusion about `slab allocator` 's initialization

Maxim Dounin mdounin at mdounin.ru
Fri Jul 19 13:58:26 UTC 2013


Hello!

On Wed, Jul 17, 2013 at 11:04:35PM +0800, Hungpo DU wrote:

> I find a couple of lines confusing while reading the slab allocator's code.
> 
>          96     p = (u_char *) pool + sizeof(ngx_slab_pool_t);
>          97     size = pool->end - p;
>         ...
>         110     p += n * sizeof(ngx_slab_page_t);
>         111
>         112     pages = (ngx_uint_t) (size / (ngx_pagesize +
> sizeof(ngx_slab_page_t)));
>         113
>         114     ngx_memzero(p, pages * sizeof(ngx_slab_page_t));
>         115
>         ...
>         125     pool->start = (u_char *)
>         126                   ngx_align_ptr((uintptr_t) p + pages *
> sizeof(ngx_slab_page_t),
>         127                                  ngx_pagesize);
> 
> The `size` takes space occupied by *slots* into account, that'll make
> `pages`
> a little bit larger. Then,
> 
> * because `p` is already advanced by sizeof *slots*, the following
> `ngx_memzero`
> will operates on more `ngx_slab_page_t`'s than expected.
> 
> * also `pool->start` will start at a higher postion before aligned by
> `ngx_pagesize`. One more page maybe available if `pages` is a little
> smaller?
> 
> 
> Can someone please tell me these lines's true intention? I must get it
> wrong
> somewhere.

Slab allocator uses page as a memory allocation unit, and each 
memory page must have corresponding ngx_slab_page_t structure.  
That is, if "pages" will be smaller - memory available for 
allocation will be the same, as memory page without corresponding 
ngx_slab_page_t structure can't be used.

With "size" reduced by n * sizeof(ngx_slab_page_t) the code might 
be a bit more readable though, and probably something like this 
worth committing:

--- a/src/core/ngx_slab.c	Sat Jul 13 03:24:30 2013 +0400
+++ b/src/core/ngx_slab.c	Fri Jul 19 17:53:11 2013 +0400
@@ -105,6 +105,7 @@ ngx_slab_init(ngx_slab_pool_t *pool)
     }
 
     p += n * sizeof(ngx_slab_page_t);
+    size -= n * sizeof(ngx_slab_page_t);
 
     pages = (ngx_uint_t) (size / (ngx_pagesize + sizeof(ngx_slab_page_t)));
 
Not sure though.

-- 
Maxim Dounin
http://nginx.org/en/donation.html



More information about the nginx-devel mailing list