/*

libualloc - microlib for memory allocation with various strategies

Copyright (c) 2020 Tibor 'Igor2' Palinkas
All rights reserved.

Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions
are met:
1. Redistributions of source code must retain the above copyright
   notice, this list of conditions and the following disclaimer.
2. Redistributions in binary form must reproduce the above copyright
   notice, this list of conditions and the following disclaimer in the
   documentation and/or other materials provided with the distribution.
3. Neither the name of the Author nor the names of contributors
   may be used to endorse or promote products derived from this software
   without specific prior written permission.

THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
ARE DISCLAIMED.  IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
SUCH DAMAGE.

Source code: svn://svn.repo.hu/libualloc/trunk
Contact the author: http://igor2.repo.hu/contact.html

*/

#include <stdlib.h>
#include <stddef.h>
#include <assert.h>
#include <libualloc/libualloc.h>

struct uall_slabap_s {
	uall_slabap_t *next;       /* ... in free_slabs */
	char data[1];            /* real size is slab_size */
};

struct uall_slabap_page_s {
	uall_slabap_page_t *next;  /* ... in list of slab blocks */
	uall_slabap_page_t *prev;  /* ... in list of slab blocks */
	long used;               /* number of slabs in use */
	char data[1];            /* real size is sys->page_size */
};


#define UALL_SLABAP_PTR2SLAB(ptr)    ((uall_slabap_t *)((char *)(ptr) - offsetof(uall_slabap_t, data)))
#define UALL_SLABAP_T_SIZE           offsetof(uall_slabap_t, data)
#define UALL_SLABAP_PAGE_T_SIZE      offsetof(uall_slabap_page_t, data)
#define UALL_SLABAP_REAL_SIZE(ctx)   (UALL_ALIGN((ctx)->slab_size + UALL_SLABAP_T_SIZE))
#define UALL_SLABAPS_PER_PAGE(ctx)   (((ctx)->sys->page_size - UALL_SLABAP_PAGE_T_SIZE) / UALL_SLABAP_REAL_SIZE(ctx))

UALL_INLINE uall_slabap_page_t *uall_slabap2page(uall_slabaps_t *ctx, uall_slabap_t *slab)
{
	size_t ptr = (size_t)slab;
	if (ctx->page_mask != 0)
		return (uall_slabap_page_t *)(ptr & ctx->page_mask);
	return (uall_slabap_page_t *)(ptr / ctx->sys->page_size * ctx->sys->page_size);

	{
/* if the size of size_t doesn't match pointer size, one of these will
   result in zero or negative array size triggering a compilation error */
		char dummy1[sizeof(size_t) - sizeof(void *) + 1], dummy2[sizeof(void *) - sizeof(size_t) + 1];
		(void)dummy1; (void)dummy2;
	}
}

UALL_INLINE void *uall_slabap_alloc(uall_slabaps_t *ctx)
{
	uall_slabap_page_t *page;
	long step;
	char *s, *end;
	void *res;

	if (UALL_OVERRIDE())
		return malloc(ctx->slab_size);

	/* first try to serve from cache (fast)... */
	if (ctx->free_slabs == NULL) {
		if (ctx->pages == 0) { /* first page allocation: determine page mask */
			if ((ctx->sys->page_size & (ctx->sys->page_size - 1)) == 0)
				ctx->page_mask = ~(ctx->sys->page_size - 1); /* round: ctx->sys->page_size = 2^n */
			else
				ctx->page_mask = 0;
		}
		/* ...no free slab means a new page is needed */
		page = ctx->sys->alloc(ctx->sys, ctx->sys->page_size);
		if (page == NULL)
			return NULL;
		page->used = 0;
		page->next = ctx->pages;
		page->prev = NULL;
		if (ctx->pages != NULL)
			ctx->pages->prev = page;
		ctx->pages = page;

		/* set up all slabs and add them to the cache */
		step = UALL_ALIGN(ctx->slab_size + UALL_SLABAP_T_SIZE);
		end = (char *)page + ctx->sys->page_size - step;
		for(s = page->data; s < end; s += step) {
			uall_slabap_t *slab = (uall_slabap_t *)s;
			slab->next = ctx->free_slabs;
			ctx->free_slabs = slab;
		}
		/* page is pointing to the page of the first free slab in cache */
	}
	else
		page = uall_slabap2page(ctx, ctx->free_slabs);

	/* return the first slab from cache */
	res = &ctx->free_slabs->data;
	ctx->free_slabs = ctx->free_slabs->next;
	page->used++;
	return res;
}

UALL_INLINE void uall_slabap_free(uall_slabaps_t *ctx, void *ptr)
{
	uall_slabap_t *slab, *prev;
	uall_slabap_page_t *page;

	if (UALL_OVERRIDE()) {
		free(ptr);
		return;
	}

	slab = UALL_SLABAP_PTR2SLAB(ptr);
	slab->next = ctx->free_slabs;
	ctx->free_slabs = slab;

	page = uall_slabap2page(ctx, slab);
	assert(page->used > 0);
	page->used--;

	if (page->used == 0) { /* free empty page */

		/* first unlink any cache item pointing to this page */
		for(prev = NULL, slab = ctx->free_slabs; slab != NULL; slab = slab->next) {
			if (uall_slabap2page(ctx, slab) == page) {
				if (prev == NULL)
					ctx->free_slabs = slab->next;
				else
					prev->next = slab->next;
			}
			else
				prev = slab;
		}

		/* unlink the page */
		if (page->prev == NULL)
			ctx->pages = page->next;
		else
			page->prev->next = page->next;

		if (page->next != NULL)
			page->next->prev = page->prev;


		/* discard page */
		ctx->sys->free(ctx->sys, page);
	}
}

UALL_INLINE void uall_slabap_clean(uall_slabaps_t *ctx)
{
	uall_slabap_page_t *page, *next;
	for(page = ctx->pages; page != NULL; page = next) {
		next = page->next;
		ctx->sys->free(ctx->sys, page);
	}
	ctx->pages = NULL;
}
