Redis源碼系列(一)

Redis源碼系列——內存管理

函數原型 src/zmalloc.h

函數指針與void*指針的使用,提供了一個泛型的機制redis

/*stringfication*/
#define __xstr(s) __str(s)
#define __str(s) #s
/*prototypes*/
void *zmalloc(size_t size);
void *zcalloc(size_t size);
void *zrealloc(void *ptr, size_t size);
void zfree(void *ptr);
char *zstrdup(const char *s);
size_t zmalloc_used_memory(void);
void zmalloc_enable_thread_safeness(void);
void zmalloc_set_oom_handler(void (*oom_handler)(size_t));
float zmalloc_get_fragmentation_ratio(size_t rss);
size_t zmalloc_get_rss(void);
#ifndef HAVE_MALLOC_SIZE
size_t zmalloc_size(void *ptr);
#endif

函數實現src/zmalloc.c

幾個全局靜態量安全

/*已經使用的內存*/
static size_t used_memory = 0;
/*線程安全標誌 全局靜態變量*/
static int zmalloc_thread_safe = 0;
/*鎖*/
pthread_mutex_t used_memory_mutex = PTHREAD_MUTEX_INITIALIZER;

1.zlic_free

提供原始的libc內存free函數,在包含zmalloc.h以前定義.多線程

/* This function provide us access to the original libc free(). This is useful
 * for instance to free results obtained by backtrace_symbols(). We need
 * to define this function before including zmalloc.h that may shadow the
 * free implementation if we use jemalloc or another non standard allocator. */
void zlibc_free(void *ptr) {
    free(ptr);
}

2.PREFIX_SIZE

根據機器的不一樣,定義爲一個字長大小app

#if defined(__sun) || defined(__sparc) || defined(__sparc__)
#define PREFIX_SIZE (sizeof(long long))
#else
#define PREFIX_SIZE (sizeof(size_t))

3.zmalloc

redis的內存申請函數,內部用malloc函數實現.ide

/*
 * zmalloc , zcalloc ,zrealloc
 * 都申請了多一個PREFIX_SZIE 的內存大小,並與字長對齊
 */
void *zmalloc(size_t size) {
    /*size 爲實際須要的大小
     * PREFIX_SIZE 爲預編譯宏:根據機器而定,用於存儲size的值*/
    void *ptr = malloc(size+PREFIX_SIZE);
    /*錯誤處理:調用函數default_oom*/
    if (!ptr) zmalloc_oom_handler(size);
#ifdef HAVE_MALLOC_SIZE
    update_zmalloc_stat_alloc(zmalloc_size(ptr));
    return ptr;
#else
    /*分配內存的第一個字長放上 size的值*/
    *((size_t*)ptr) = size;
    /*更新已經使用的內存大小全局量*/
    update_zmalloc_stat_alloc(size+PREFIX_SIZE);
    /*向右偏移PREFIX_SIZE 此時指針指向的空間的大小就是size*/
    //     +--------------+-----------------+
    //     | PREFIX_SIZE  | size            |
    //     +--------------+-----------------+
    //     ^              ^
    //     |              |
    //    ptr            (char*)ptr+PREFIX_SIZE
    // 也是返回的指針指向的地址
    return (char*)ptr+PREFIX_SIZE;
#endif
}

關於錯誤處理的函數,zmalloc_oom_handler實際爲一函數指針函數

/*錯誤處理,並退出*/
static void zmalloc_default_oom(size_t size) {
    fprintf(stderr, "zmalloc: Out of memory trying to allocate %zu bytes\n",
        size);
    fflush(stderr);
    abort();
}
/*函數指針*/
static void (*zmalloc_oom_handler)(size_t) = zmalloc_default_oom;

其值,指向默認的oom(out of memory)處理函數.fetch

至於維護內存大小全局變量的update_zmalloc_stat_alloc則爲一個宏函數,其實現以下:this

/*使得變量used_memory精確的維護實際分配的內存*/
#define update_zmalloc_stat_alloc(__n) do { \
    /*轉爲size_t*/
    size_t _n = (__n); \
    /* 
     * 判斷是否與字長對齊,對於64位機器,內存是否與8對齊
     * 不對齊就加上必定的偏移量使之對齊
     */
    if (_n&(sizeof(long)-1)) _n += sizeof(long)-(_n&(sizeof(long)-1)); \
    /*是否須要保證線程安全*/
    if (zmalloc_thread_safe) { \
        update_zmalloc_stat_add(_n); \
    } else { \
        used_memory += _n; \
    } \
} while(0)

這裏有幾個地方值得注意:spa

  1. 宏中使用的do{...}while(0)技巧操作系統

  2. 判斷是否對其的位運算操做, 與取模運算一致

    \[a \%(2^n)=a\&(2^n-1) \]

  3. 是否須要線程安全的實現方式,若是須要就調用update_zmalloc_stat_add,否則就直接增長used_memory

線程安全方法中用到的宏,實現以下:

#ifdef HAVE_ATOMIC
#define update_zmalloc_stat_add(__n) __sync_add_and_fetch(&used_memory, (__n))
#else
/* 
 * 線程安全方法更新,使用互斥鎖(mutex)保證線程安全
 * 由update_zmalloc_stat_alloc調用
 * 先加鎖,而後更新最後再解鎖
 */
#define update_zmalloc_stat_add(__n) do { \
    pthread_mutex_lock(&used_memory_mutex); \
    /*線程安全*/
    used_memory += (__n); \
    pthread_mutex_unlock(&used_memory_mutex); \
} while(0)

#endif

此處用到的互斥鎖等,均源自POSIX多線程,即pthread.h

既然在allocation的時候有這樣一套機制,那麼在free的時候會有對應的宏來維護內存大小量.

#define update_zmalloc_stat_sub(__n) do { \
    pthread_mutex_lock(&used_memory_mutex); \
    used_memory -= (__n); \
    pthread_mutex_unlock(&used_memory_mutex); \
} while(0)
#define update_zmalloc_stat_free(__n) do { \
    size_t _n = (__n); \
    if (_n&(sizeof(long)-1)) _n += sizeof(long)-(_n&(sizeof(long)-1)); \
    if (zmalloc_thread_safe) { \
        update_zmalloc_stat_sub(_n); \
    } else { \
        used_memory -= _n; \
    } \
} while(0)

對應着看,應該很好理解.

4.zcalloc

內部調用calloc實現

void *zcalloc(size_t size) {
    /*
     * calloc是線程安全函數
     * 分配的內存大小爲 num*size
     * 並初始化爲0
     */
    void *ptr = calloc(1, size+PREFIX_SIZE);

    if (!ptr) zmalloc_oom_handler(size);
#ifdef HAVE_MALLOC_SIZE
    update_zmalloc_stat_alloc(zmalloc_size(ptr));
    return ptr;
#else
    *((size_t*)ptr) = size;
    update_zmalloc_stat_alloc(size+PREFIX_SIZE);
    return (char*)ptr+PREFIX_SIZE;
#endif
}

5.zrealloc

在此以前,先看看realloc函數

從新(擴大)分配內存函數,內部調用realloc函數

/*從新分配內存*/
void *zrealloc(void *ptr, size_t size) {
#ifndef HAVE_MALLOC_SIZE
    void *realptr;
#endif
    size_t oldsize;
    void *newptr;

    /*從新申請一塊內存並返回*/
    if (ptr == NULL) return zmalloc(size);
#ifdef HAVE_MALLOC_SIZE
    oldsize = zmalloc_size(ptr);
	/*calloc從新申請內存*/
    newptr = realloc(ptr,size);
    if (!newptr) zmalloc_oom_handler(size);
	/*free原來的內存*/
    update_zmalloc_stat_free(oldsize);
	/*更新全局量 used_memory*/
    update_zmalloc_stat_alloc(zmalloc_size(newptr));
    return newptr;
#else
 	/*向前PREFIX_SIZE*/
    realptr = (char*)ptr-PREFIX_SIZE;
	/*原來內存的大小*/
    oldsize = *((size_t*)realptr);
	/*從新申請內存*/
    newptr = realloc(realptr,size+PREFIX_SIZE);
    if (!newptr) zmalloc_oom_handler(size);
	/*存儲size*/
    *((size_t*)newptr) = size;
	/*free原來的空間*/
    update_zmalloc_stat_free(oldsize);
	/*更新全局量 used_memory*/
    update_zmalloc_stat_alloc(size);
    return (char*)newptr+PREFIX_SIZE;
#endif
}

其他部分的實現都很好理解.

6.zmalloc_size

/* Provide zmalloc_size() for systems where this function is not provided by
 * malloc itself, given that in that case we store a header with this
 * information as the first bytes of every allocation.
 *
 */
#ifndef HAVE_MALLOC_SIZE
size_t zmalloc_size(void *ptr) {
    /* malloc的內存的大小*/
    /*向前偏移一個字長*/
    void *realptr = (char*)ptr-PREFIX_SIZE;
    /*得到大小*/
    size_t size = *((size_t*)realptr);
    /* Assume at least that all the allocations are padded at sizeof(long) by
     * the underlying allocator. */
    /*內存對齊*/
    if (size&(sizeof(long)-1)) size += sizeof(long)-(size&(sizeof(long)-1));
    return size+PREFIX_SIZE;
}
#endif

7.zstrdup

複製字符串函數

char *zstrdup(const char *s) {
    /*多出來一個*/
    size_t l = strlen(s)+1;
    char *p = zmalloc(l);
    memcpy(p,s,l);
    return p;
}

8. zmalloc_used_memory

實現了線程安全方法

/*返回used_memory 線程安全*/
size_t zmalloc_used_memory(void) {
    size_t um;

    if (zmalloc_thread_safe) {
#ifdef HAVE_ATOMIC
        um = __sync_add_and_fetch(&used_memory, 0);
#else
        /*加鎖*/
        pthread_mutex_lock(&used_memory_mutex);
        um = used_memory;
        /*解鎖*/
        pthread_mutex_unlock(&used_memory_mutex);
#endif
    }/*保證線程安全*/
    else {
        um = used_memory;
    }
    return um;
}

9. help functions

/*
 * 是否須要線程安全
 * 0表明不須要 
 */
void zmalloc_enable_thread_safeness(void) {
    zmalloc_thread_safe = 1;
}
/* oom狀態下采起的操做: out of memory
 * 默認爲 zmalloc_default_oom()
 */
void zmalloc_set_oom_handler(void (*oom_handler)(size_t)) {
    zmalloc_oom_handler = oom_handler;
}

10.zmalloc_get_rss

返回當前進程實際駐留在內存中的大小,與操做系統相關

#if defined(HAVE_PROC_STAT)
#include <unistd.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
size_t zmalloc_get_rss(void) {
    /*sysconf爲系統函數,獲取頁大小*/
    int page = sysconf(_SC_PAGESIZE);
    size_t rss;
    char buf[4096];
    char filename[256];
    int fd, count;
    char *p, *x;

	/*將當前進程所對應的stat文件的絕對路徑保存到filename*/
    snprintf(filename,256,"/proc/%d/stat",getpid());
	/*只讀打開stat文件*/
    if ((fd = open(filename,O_RDONLY)) == -1) return 0;
    if (read(fd,buf,4096) <= 0) {
        close(fd);
        return 0;
    }
    close(fd);
	/*讀完信息,存到buf*/
    p = buf;
    count = 23; /* RSS 是 /proc/<pid>/stat 的第24個字段*/
    while(p && count--) {
		/*查找空格,由空格分隔字段*/
        p = strchr(p,' ');
		/*指向下一個字段首地址*/
        if (p) p++;
    }
    if (!p) return 0;
    x = strchr(p,' ');
    if (!x) return 0;
    *x = '\0';
	/*string to long long*/
    rss = strtoll(p,NULL,10);
	/*rss獲取的是內存頁的頁數,乘以頁大小便可知*/
    rss *= page;
    return rss;
}
#else
size_t zmalloc_get_rss(void) {
    /* If we can't get the RSS in an OS-specific way for this system just
     * return the memory usage we estimated in zmalloc()..
     *
     * Fragmentation will appear to be always 1 (no fragmentation)
     * of course... 
     *
     * 若是不能經過操做系統來得到,就直接返回used_memory.
     */
    return zmalloc_used_memory();
}
#endif

/* 
 * Fragmentation = RSS / allocated-bytes 
 * 內存碎片率
 */
float zmalloc_get_fragmentation_ratio(size_t rss) {
    return (float)rss/zmalloc_used_memory();
}
相關文章
相關標籤/搜索