Swoole 源碼分析——內存模塊以內存池

前言

Swoole 中爲了更好的進行內存管理,減小頻繁分配釋放內存空間形成的損耗和內存碎片,程序設計並實現了三種不一樣功能的內存池:FixedPoolRingBufferMemoryGlobalreact

其中 MemoryGlobal 用於全局變量 SwooleG.memory_poolRingBuffer 用於 reactor 線程的緩衝區,FixedPool 用於 swoole_table 共享內存表。數組

swMemoryPool 內存池數據結構

不管是哪一種內存池,它的基礎數據結構都是 swMemoryPool:安全

typedef struct _swMemoryPool
{
    void *object;
    void* (*alloc)(struct _swMemoryPool *pool, uint32_t size);
    void (*free)(struct _swMemoryPool *pool, void *ptr);
    void (*destroy)(struct _swMemoryPool *pool);
} swMemoryPool;

能夠看出來, swMemoryPool 更加相似於接口,規定了內存池須要定義的函數。swoole

MemoryGlobal 內存池實現

MemoryGlobal 數據結構

首先看一下 MemoryGlobal 的數據結構:數據結構

typedef struct _swMemoryGlobal_page
{
    struct _swMemoryGlobal_page *next;
    char memory[0];
} swMemoryGlobal_page;

typedef struct _swMemoryGlobal
{
    uint8_t shared;
    uint32_t pagesize;
    swLock lock;
    swMemoryGlobal_page *root_page;
    swMemoryGlobal_page *current_page;
    uint32_t current_offset;
} swMemoryGlobal;

能夠很明顯的看出,MemoryGlobal 實際上就是一個單鏈表,root_page 是鏈表的頭,current_page 就是鏈表的尾,current_offset 指的是最後一個鏈表元素的偏移量。函數

比較特殊的是 MemoryGlobal 單鏈表內存池的內存只能增長不會減小。fetch

MemoryGlobal 的建立

#define SW_MIN_PAGE_SIZE  4096

swMemoryPool* swMemoryGlobal_new(uint32_t pagesize, uint8_t shared)
{
    swMemoryGlobal gm, *gm_ptr;
    assert(pagesize >= SW_MIN_PAGE_SIZE);
    bzero(&gm, sizeof(swMemoryGlobal));

    gm.shared = shared;
    gm.pagesize = pagesize;

    swMemoryGlobal_page *page = swMemoryGlobal_new_page(&gm);
    if (page == NULL)
    {
        return NULL;
    }
    if (swMutex_create(&gm.lock, shared) < 0)
    {
        return NULL;
    }

    gm.root_page = page;

    gm_ptr = (swMemoryGlobal *) page->memory;
    gm.current_offset += sizeof(swMemoryGlobal);

    swMemoryPool *allocator = (swMemoryPool *) (page->memory + gm.current_offset);
    gm.current_offset += sizeof(swMemoryPool);

    allocator->object = gm_ptr;
    allocator->alloc = swMemoryGlobal_alloc;
    allocator->destroy = swMemoryGlobal_destroy;
    allocator->free = swMemoryGlobal_free;

    memcpy(gm_ptr, &gm, sizeof(gm));
    return allocator;
}
  • 能夠看到,每次申請建立 MemoryGlobal 內存不得小於 2k
  • 建立的 MemoryGlobalcurrent_offset 被初始化爲 swMemoryGlobalswMemoryPool 的大小之和
  • 返回的 allocator 類型是 swMemoryPool,其內存結構爲:ui

    swMemoryGlobal swMemoryPool memory
static swMemoryGlobal_page* swMemoryGlobal_new_page(swMemoryGlobal *gm)
{
    swMemoryGlobal_page *page = (gm->shared == 1) ? sw_shm_malloc(gm->pagesize) : sw_malloc(gm->pagesize);
    if (page == NULL)
    {
        return NULL;
    }
    bzero(page, gm->pagesize);
    page->next = NULL;

    if (gm->current_page != NULL)
    {
        gm->current_page->next = page;
    }

    gm->current_page = page;
    gm->current_offset = 0;

    return page;
}

鏈表元素的建立比較簡單,就是申請內存,初始化單鏈表的各個變量。this

MemoryGlobal 內存的申請

static void *swMemoryGlobal_alloc(swMemoryPool *pool, uint32_t size)
{
    swMemoryGlobal *gm = pool->object;
    gm->lock.lock(&gm->lock);
    if (size > gm->pagesize - sizeof(swMemoryGlobal_page))
    {
        swWarn("failed to alloc %d bytes, exceed the maximum size[%d].", size, gm->pagesize - (int) sizeof(swMemoryGlobal_page));
        gm->lock.unlock(&gm->lock);
        return NULL;
    }
    if (gm->current_offset + size > gm->pagesize - sizeof(swMemoryGlobal_page))
    {
        swMemoryGlobal_page *page = swMemoryGlobal_new_page(gm);
        if (page == NULL)
        {
            swWarn("swMemoryGlobal_alloc alloc memory error.");
            gm->lock.unlock(&gm->lock);
            return NULL;
        }
        gm->current_page = page;
    }
    void *mem = gm->current_page->memory + gm->current_offset;
    gm->current_offset += size;
    gm->lock.unlock(&gm->lock);
    return mem;
}
  • 申請內存以前須要先將互斥鎖加鎖以防多個線程或多個進程同時申請內存,致使數據混亂。
  • 若是申請的內存大於單個鏈表元素的 pagesize,直接返回錯誤。
  • 若是當前鏈表元素剩餘的內存不足,那麼就會從新申請一個新的鏈表元素
  • 設置 current_offset,解鎖互斥鎖,返回內存地址。

MemoryGlobal 內存的釋放與銷燬

static void swMemoryGlobal_free(swMemoryPool *pool, void *ptr)
{
    swWarn("swMemoryGlobal Allocator don't need to release.");
}

static void swMemoryGlobal_destroy(swMemoryPool *poll)
{
    swMemoryGlobal *gm = poll->object;
    swMemoryGlobal_page *page = gm->root_page;
    swMemoryGlobal_page *next;

    do
    {
        next = page->next;
        sw_shm_free(page);
        page = next;
    } while (page);
}
  • MemoryGlobal 不須要進行內存的釋放
  • MemoryGlobal 的銷燬就是循環單鏈表,而後釋放內存

RingBuffer 內存池實現

RingBuffer 的數據結構

RingBuffer 相似於一個循環數組,每一次申請的一塊內存在該數組中佔據一個位置,這些內存塊是能夠不等長的,所以每一個內存塊須要有一個記錄其長度的變量。atom

typedef struct
{
    uint16_t lock;
    uint16_t index;
    uint32_t length;
    char data[0];
} swRingBuffer_item;

typedef struct
{
    uint8_t shared;
    uint8_t status;
    uint32_t size;
    uint32_t alloc_offset;
    uint32_t collect_offset;
    uint32_t alloc_count;
    sw_atomic_t free_count;
    void *memory;
} swRingBuffer;
  • swRingBuffer 中很是重要的成員變量是 alloc_offsetcollect_offsetalloc_offset 是當前循環數組中的起始地址,collect_offset 表明當前循環數組中能夠被回收的內存地址。
  • free_count 是當前循環數組中能夠被回收的個數。
  • status 爲 0 表明循環數組當前佔用的內存空間並無越過數組的結尾,也就是其地址是連續的,爲 1 表明循環數組當前佔用的內存空間一部分在循環數組的尾部,一部分在數組的頭部。

RingBuffer 的建立

RingBuffer 的建立相似於 MemoryGlobal

RingBuffer swMemoryPool memory
swMemoryPool *swRingBuffer_new(uint32_t size, uint8_t shared)
{
    void *mem = (shared == 1) ? sw_shm_malloc(size) : sw_malloc(size);
    if (mem == NULL)
    {
        swWarn("malloc(%d) failed.", size);
        return NULL;
    }

    swRingBuffer *object = mem;
    mem += sizeof(swRingBuffer);
    bzero(object, sizeof(swRingBuffer));

    object->size = (size - sizeof(swRingBuffer) - sizeof(swMemoryPool));
    object->shared = shared;

    swMemoryPool *pool = mem;
    mem += sizeof(swMemoryPool);

    pool->object = object;
    pool->destroy = swRingBuffer_destory;
    pool->free = swRingBuffer_free;
    pool->alloc = swRingBuffer_alloc;

    object->memory = mem;

    swDebug("memory: ptr=%p", mem);

    return pool;
}

RingBuffer 內存的申請

  • free_count 大於 0,說明此時數組中有待回收的內存,須要進行內存回收
  • 若當前佔用的內存不是連續的,那麼當前內存池剩餘的容量就是 collect_offset - alloc_offset
  • 若當前佔用的內存是連續的,

    • 並且數組當前 collect_offset 距離尾部的內存大於申請的內存數,那麼剩餘的容量就是 size - alloc_offset
    • 數組當前內存位置距離尾部容量不足,那麼就將當前內存到數組尾部打包成爲一個 swRingBuffer_item 數組元素,並標誌爲待回收元素,設置 status 爲 1,設置 alloc_offset 爲數組首地址,此時剩餘的容量就是 collect_offset 的地址
static void* swRingBuffer_alloc(swMemoryPool *pool, uint32_t size)
{
    assert(size > 0);

    swRingBuffer *object = pool->object;
    swRingBuffer_item *item;
    uint32_t capacity;

    uint32_t alloc_size = size + sizeof(swRingBuffer_item);

    if (object->free_count > 0)
    {
        swRingBuffer_collect(object);
    }

    if (object->status == 0)
    {
        if (object->alloc_offset + alloc_size >= (object->size - sizeof(swRingBuffer_item)))
        {
            uint32_t skip_n = object->size - object->alloc_offset;
            if (skip_n >= sizeof(swRingBuffer_item))
            {
                item = object->memory + object->alloc_offset;
                item->lock = 0;
                item->length = skip_n - sizeof(swRingBuffer_item);
                sw_atomic_t *free_count = &object->free_count;
                sw_atomic_fetch_add(free_count, 1);
            }
            object->alloc_offset = 0;
            object->status = 1;
            capacity = object->collect_offset - object->alloc_offset;
        }
        else
        {
            capacity = object->size - object->alloc_offset;
        }
    }
    else
    {
        capacity = object->collect_offset - object->alloc_offset;
    }

    if (capacity < alloc_size)
    {
        return NULL;
    }

    item = object->memory + object->alloc_offset;
    item->lock = 1;
    item->length = size;
    item->index = object->alloc_count;

    object->alloc_offset += alloc_size;
    object->alloc_count ++;

    swDebug("alloc: ptr=%p", (void * )((void * )item->data - object->memory));

    return item->data;
}

RingBuffer 內存的回收

  • RingBufferfree_count 大於 0 的時候,就說明當前內存池存在須要回收的元素,每次在申請新的內存時,都會調用這個函數來回收內存。
  • 回收內存時,本函數只會回收連續的多個空餘的內存元素,若多個待回收的內存元素之間相互隔離,那麼這些內存元素不會被回收。
static void swRingBuffer_collect(swRingBuffer *object)
{
    swRingBuffer_item *item;
    sw_atomic_t *free_count = &object->free_count;

    int count = object->free_count;
    int i;
    uint32_t n_size;

    for (i = 0; i < count; i++)
    {
        item = object->memory + object->collect_offset;
        if (item->lock == 0)
        {
            n_size = item->length + sizeof(swRingBuffer_item);

            object->collect_offset += n_size;

            if (object->collect_offset + sizeof(swRingBuffer_item) >object->size || object->collect_offset >= object->size)
            {
                object->collect_offset = 0;
                object->status = 0;
            }
            sw_atomic_fetch_sub(free_count, 1);
        }
        else
        {
            break;
        }
    }
}

RingBuffer 內存的釋放

內存的釋放很簡單,只須要設置 lock 爲 0,而且增長 free_count 的數量便可:

static void swRingBuffer_free(swMemoryPool *pool, void *ptr)
{
    swRingBuffer *object = pool->object;
    swRingBuffer_item *item = ptr - sizeof(swRingBuffer_item);

    assert(ptr >= object->memory);
    assert(ptr <= object->memory + object->size);
    assert(item->lock == 1);

    if (item->lock != 1)
    {
        swDebug("invalid free: index=%d, ptr=%p", item->index,  (void * )((void * )item->data - object->memory));
    }
    else
    {
        item->lock = 0;
    }

    swDebug("free: ptr=%p", (void * )((void * )item->data - object->memory));

    sw_atomic_t *free_count = &object->free_count;
    sw_atomic_fetch_add(free_count, 1);
}

RingBuffer 內存的銷燬

static void swRingBuffer_destory(swMemoryPool *pool)
{
    swRingBuffer *object = pool->object;
    if (object->shared)
    {
        sw_shm_free(object);
    }
    else
    {
        sw_free(object);
    }
}
  • 值得注意的是,RingBuffer 除了原子鎖以外就沒有任何鎖了,在申請與釋放過程的代碼中也沒有看出來是線程安全的無鎖數據結構,我的認爲 RingBuffer 並不是是線程安全/進程安全的數據結構,所以利用這個內存池申請共享內存時,須要本身進行加鎖。

FixedPool 內存池實現

FixedPool 數據結構

FixedPool 是隨機分配內存池,將一整塊內存空間切分紅等大小的一個個小塊,每次分配其中的一個小塊做爲要使用的內存,這些小塊以雙向鏈表的形式存儲。

typedef struct _swFixedPool_slice
{
    uint8_t lock;
    struct _swFixedPool_slice *next;
    struct _swFixedPool_slice *pre;
    char data[0];

} swFixedPool_slice;

typedef struct _swFixedPool
{
    void *memory;
    size_t size;

    swFixedPool_slice *head;
    swFixedPool_slice *tail;

    /**
     * total memory size
     */
    uint32_t slice_num;

    /**
     * memory usage
     */
    uint32_t slice_use;

    /**
     * Fixed slice size, not include the memory used by swFixedPool_slice
     */
    uint32_t slice_size;

    /**
     * use shared memory
     */
    uint8_t shared;

} swFixedPool;

FixedPool 內存池的建立

FixedPool 內存池的建立有兩個函數 swFixedPool_newswFixedPool_new2,其中 swFixedPool_new2 是利用已有的內存基礎上來構建內存池,這個也是 table 共享內存表建立的方法。

swMemoryPool* swFixedPool_new2(uint32_t slice_size, void *memory, size_t size)
{
    swFixedPool *object = memory;
    memory += sizeof(swFixedPool);
    bzero(object, sizeof(swFixedPool));

    object->slice_size = slice_size;
    object->size = size - sizeof(swMemoryPool) - sizeof(swFixedPool);
    object->slice_num = object->size / (slice_size + sizeof(swFixedPool_slice));

    swMemoryPool *pool = memory;
    memory += sizeof(swMemoryPool);
    bzero(pool, sizeof(swMemoryPool));

    pool->object = object;
    pool->alloc = swFixedPool_alloc;
    pool->free = swFixedPool_free;
    pool->destroy = swFixedPool_destroy;

    object->memory = memory;

    /**
     * init linked list
     */
    swFixedPool_init(object);

    return pool;
}

內存池的建立和前兩個大同小異,只是此次多了 swFixedPool_init 這個構建雙向鏈表的過程:

static void swFixedPool_init(swFixedPool *object)
{
    swFixedPool_slice *slice;
    void *cur = object->memory;
    void *max = object->memory + object->size;
    do
    {
        slice = (swFixedPool_slice *) cur;
        bzero(slice, sizeof(swFixedPool_slice));

        if (object->head != NULL)
        {
            object->head->pre = slice;
            slice->next = object->head;
        }
        else
        {
            object->tail = slice;
        }

        object->head = slice;
        cur += (sizeof(swFixedPool_slice) + object->slice_size);

        if (cur < max)
        {
            slice->pre = (swFixedPool_slice *) cur;
        }
        else
        {
            slice->pre = NULL;
            break;
        }

    } while (1);
}

能夠看出來,程序從內存空間的首部開始,每次初始化一個 slice 大小的空間,並插入到鏈表的頭部,所以整個鏈表的內存地址和 memory 的地址是相反的。

FixedPool 內存池的申請

static void* swFixedPool_alloc(swMemoryPool *pool, uint32_t size)
{
    swFixedPool *object = pool->object;
    swFixedPool_slice *slice;

    slice = object->head;

    if (slice->lock == 0)
    {
        slice->lock = 1;
        object->slice_use ++;
        /**
         * move next slice to head (idle list)
         */
        object->head = slice->next;
        
        slice->next->pre = NULL;

        /*
         * move this slice to tail (busy list)
         */
        object->tail->next = slice;
        slice->next = NULL;
        slice->pre = object->tail;
        object->tail = slice;

        return slice->data;
    }
    else
    {
        return NULL;
    }
}
  • 首先獲取內存池鏈表首部的節點,並判斷該節點是否被佔用,若是被佔用,說明內存池已滿,返回null(由於全部被佔用的節點都會被放到尾部);若是未被佔用,則將該節點的下一個節點移到首部,並將該節點移動到尾部,標記該節點爲佔用狀態,返回該節點的數據域。

FixedPool 內存池的釋放

static void swFixedPool_free(swMemoryPool *pool, void *ptr)
{
    swFixedPool *object = pool->object;
    swFixedPool_slice *slice;

    assert(ptr > object->memory && ptr < object->memory + object->size);

    slice = ptr - sizeof(swFixedPool_slice);

    if (slice->lock)
    {
        object->slice_use--;
    }

    slice->lock = 0;

    //list head, AB
    if (slice->pre == NULL)
    {
        return;
    }
    //list tail, DE
    if (slice->next == NULL)
    {
        slice->pre->next = NULL;
        object->tail = slice->pre;
    }
    //middle BCD
    else
    {
        slice->pre->next = slice->next;
        slice->next->pre = slice->pre;
    }

    slice->pre = NULL;
    slice->next = object->head;
    object->head->pre = slice;
    object->head = slice;
}
  • 首先經過移動 ptr 指針得到 slice 對象,並將佔用標記 lock 置爲 0。若是該節點爲頭節點,則直接返回。若是不是頭節點,則將該節點移動到鏈表頭部。

FixedPool 內存池的銷燬

static void swFixedPool_destroy(swMemoryPool *pool)
{
    swFixedPool *object = pool->object;
    if (object->shared)
    {
        sw_shm_free(object);
    }
    else
    {
        sw_free(object);
    }
}
相關文章
相關標籤/搜索