[redis源码注释]-内存分配
second60 20180510
内存分配文件,主要包括两个文件: zmalloc.h zmalloc.c
zmalloc.h
#ifndef __ZMALLOC_H
#define __ZMALLOC_H
/* Double expansion needed for stringification of macro values. */
#define __xstr(s) __str(s)
#define __str(s) #s
#if defined(USE_TCMALLOC)
#define ZMALLOC_LIB ("tcmalloc-" __xstr(TC_VERSION_MAJOR) "." __xstr(TC_VERSION_MINOR))
#include <google/tcmalloc.h>
#if (TC_VERSION_MAJOR == 1 && TC_VERSION_MINOR >= 6) || (TC_VERSION_MAJOR > 1)
#define HAVE_MALLOC_SIZE 1
#define zmalloc_size(p) tc_malloc_size(p)
#else
#error "Newer version of tcmalloc required"
#endif
#elif defined(USE_JEMALLOC)
#define ZMALLOC_LIB ("jemalloc-" __xstr(JEMALLOC_VERSION_MAJOR) "." __xstr(JEMALLOC_VERSION_MINOR) "." __xstr(JEMALLOC_VERSION_BUGFIX))
#include <jemalloc/jemalloc.h>
#if (JEMALLOC_VERSION_MAJOR == 2 && JEMALLOC_VERSION_MINOR >= 1) || (JEMALLOC_VERSION_MAJOR > 2)
#define HAVE_MALLOC_SIZE 1
#define zmalloc_size(p) je_malloc_usable_size(p)
#else
#error "Newer version of jemalloc required"
#endif
#elif defined(__APPLE__)
#include <malloc/malloc.h>
#define HAVE_MALLOC_SIZE 1
#define zmalloc_size(p) malloc_size(p)
#endif
#ifndef ZMALLOC_LIB
#define ZMALLOC_LIB "libc"
#endif
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);
size_t zmalloc_get_private_dirty(void);
void zlibc_free(void *ptr);
// 这个宏对于阅读内存分配很重要
// 开启表示:类库的的内存配
// 如果没有:自定义的内存分配
// 自定义内存分配原理:
// PREFIX_SIZE + size = 实际分配的大小
// size: 为使用要分配的大小
// PREFIX_SIZE:前缀的大小,是用来存储内存size用的
// |--PREFIX_SIZE--|---use menory size----|
#ifndef HAVE_MALLOC_SIZE
size_t zmalloc_size(void *ptr);
#endif
#endif /* __ZMALLOC_H */
zmalloc.c
#include <stdio.h>
#include <stdlib.h>
void zlibc_free(void *ptr) {
free(ptr);
}
#include <string.h>
#include <pthread.h>
#include "config.h"
#include "zmalloc.h"
// 如果有MALLOC_SIZE则PREFIX_SIZE为0, 分配内存时按给定的分配
// 如果没有,PREFIX_SIZE就根据平台的定义
#ifdef HAVE_MALLOC_SIZE
#define PREFIX_SIZE (0)
#else
// 不同平台size_t的定义不同
#if defined(__sun) || defined(__sparc) || defined(__sparc__)
#define PREFIX_SIZE (sizeof(long long))
#else
#define PREFIX_SIZE (sizeof(size_t))
#endif
#endif
/* Explicitly override malloc/free etc when using tcmalloc. */
#if defined(USE_TCMALLOC)
#define malloc(size) tc_malloc(size)
#define calloc(count,size) tc_calloc(count,size)
#define realloc(ptr,size) tc_realloc(ptr,size)
#define free(ptr) tc_free(ptr)
#elif defined(USE_JEMALLOC)
#define malloc(size) je_malloc(size)
#define calloc(count,size) je_calloc(count,size)
#define realloc(ptr,size) je_realloc(ptr,size)
#define free(ptr) je_free(ptr)
#endif
//是否有原子操作
#ifdef HAVE_ATOMIC
#define update_zmalloc_stat_add(__n) __sync_add_and_fetch(&used_memory, (__n))
#define update_zmalloc_stat_sub(__n) __sync_sub_and_fetch(&used_memory, (__n))
#else
// 内存数量加原子操作(线程安全加锁)
#define update_zmalloc_stat_add(__n) do { \
pthread_mutex_lock(&used_memory_mutex); \
used_memory += (__n); \
pthread_mutex_unlock(&used_memory_mutex); \
} while(0)
// 内存数量减原子操作(线程安全加锁)
#define update_zmalloc_stat_sub(__n) do { \
pthread_mutex_lock(&used_memory_mutex); \
used_memory -= (__n); \
pthread_mutex_unlock(&used_memory_mutex); \
} while(0)
#endif
// 内存增加__n
#define update_zmalloc_stat_alloc(__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_add(_n); \
} else { \
used_memory += _n; \
} \
} while(0)
// 内存释放__n
#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)
static size_t used_memory = 0; // 已分配的内存数
static int zmalloc_thread_safe = 0; // 是否线程安全
// 内存数操作时的互斥锁
pthread_mutex_t used_memory_mutex = PTHREAD_MUTEX_INITIALIZER;
// 内存溢出中断
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;
// 分配内存
// 分配时,实际的分配在小为 size + PREFIX_SIZE
// PREFIX_SIZE 根据HAVE_MALLOC_SIZE来决定
void *zmalloc(size_t size) {
void *ptr = malloc(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个字节的值设置为size
*((size_t*)ptr) = size;
update_zmalloc_stat_alloc(size+PREFIX_SIZE);
//返回 ptr首地址+PREFIX_SIZE个字节后的地址
return (char*)ptr+PREFIX_SIZE;
#endif
}
// 分配内存块大小为size的内存
// 这里默认为1块大小为size的内存
void *zcalloc(size_t size) {
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
}
// 重新给ptr分配内存,大小为size
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);
// 重新分配
newptr = realloc(ptr,size);
if (!newptr) zmalloc_oom_handler(size);
// 减少使用内存数
update_zmalloc_stat_free(oldsize);
// 加上重新分配的内存数
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_t字节,记录size值
*((size_t*)newptr) = size;
// 减小已使用内存大小值
update_zmalloc_stat_free(oldsize);
// 增加已使用内存大小值
update_zmalloc_stat_alloc(size);
return (char*)newptr+PREFIX_SIZE;
#endif
}
/* 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
// 获得指针内存大小
// 由这里可以看也PREFIX_SIZE的作用:前size_t来存储这段内存的长度。
size_t zmalloc_size(void *ptr) {
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. */
// 假设所有分配器是按sizeof(long)来填充
if (size&(sizeof(long)-1)) size += sizeof(long)-(size&(sizeof(long)-1));
// 实际的长度= 真正用的内存size + 前缀的长度PREFIX_SIZE
return size+PREFIX_SIZE;
}
#endif
//释放内存
void zfree(void *ptr) {
#ifndef HAVE_MALLOC_SIZE
void *realptr;
size_t oldsize;
#endif
if (ptr == NULL) return;
#ifdef HAVE_MALLOC_SIZE
// 有定义MALLOC_SIZE直接释放,并减少使用内存数
update_zmalloc_stat_free(zmalloc_size(ptr));
free(ptr);
#else
// 先到真正分配内存地址
realptr = (char*)ptr-PREFIX_SIZE;
// 再取得地址大小
oldsize = *((size_t*)realptr);
// 再减小内存大小并释放内存
update_zmalloc_stat_free(oldsize+PREFIX_SIZE);
free(realptr);
#endif
}
// 字符串拷贝函数
char *zstrdup(const char *s) {
// 分配内存大小=字符串长度+1
size_t l = strlen(s)+1;
// 分配内存
char *p = zmalloc(l);
// 把字符串内存拷贝到新内存中
memcpy(p,s,l);
return p;
}
// 得到已使用的内存数
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;
}
// 是否开启了线程安全
void zmalloc_enable_thread_safeness(void) {
zmalloc_thread_safe = 1;
}
// 设置内存溢出函数
void zmalloc_set_oom_handler(void (*oom_handler)(size_t)) {
zmalloc_oom_handler = oom_handler;
}
/* Get the RSS information in an OS-specific way.
*
* WARNING: the function zmalloc_get_rss() is not designed to be fast
* and may not be called in the busy loops where Redis tries to release
* memory expiring or swapping out objects.
*
* For this kind of "fast RSS reporting" usages use instead the
* function RedisEstimateRSS() that is a much faster (and less precise)
* version of the function. */
#if defined(HAVE_PROC_STAT)
#include <unistd.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
// 获取进程的RSS(Resident Set Size,指实际使用物理内存(包含共享库占用的内存))
// 在linux系统中,可以通过读取/proc/pid/stat文件获取,pid为当前进程的进程号。
// 读取到的不是byte数,而是内存页数。通过系统调用sysconf(_SC_PAGESIZE)可以获得当前系统的内存页大小。
// Unix系统貌似可以直接通过task_info直接获取,比linux系统简单的多。
// 获得进程的RSS后,可以计算目前数据的内存碎片大小,直接用rss除以used_memory。
// rss包含进程的所有内存使用,包括代码,共享库,堆栈等。
// 但是由于通常情况下redis在内存中数据的量要远远大于这些数据所占用的内存,因此这个简单的计算还是比较准确的。
//457 (rsyslogd) S 1 457 457 0 -1 1077944576 395233 0 280458 0 11546 4088 0 0
// 20 0 3 0 573 736591872 4830 18446744073709551615 140108837892096 140108838402584
// 140721264058368 140721264057232 140108815490003 0 0 16781830 1133601 18446744073709551615
// 0 0 17 0 0 0 101 0 0 140108840501632 140108840531808 140108857647104 140721264062293
// 140721264062315 140721264062315 140721264062437 0
size_t zmalloc_get_rss(void) {
int page = sysconf(_SC_PAGESIZE);
size_t rss;
char buf[4096];
char filename[256];
int fd, count;
char *p, *x;
// 读取进程内存映射文件stat:/proc/pid/stat
snprintf(filename,256,"/proc/%d/stat",getpid());
// 打开并读取文件到buf后关闭
if ((fd = open(filename,O_RDONLY)) == -1) return 0;
if (read(fd,buf,4096) <= 0) {
close(fd);
return 0;
}
close(fd);
p = buf;
count = 23; /* RSS is the 24th field in /proc/<pid>/stat */
while(p && count--) {
// 查找第23个空字符出现的地方
p = strchr(p,' ');
if (p) p++;
}
if (!p) return 0;
// 再找到第24个空字符的首地址
x = strchr(p,' ');
if (!x) return 0;
// 加上\0即省略后面的内存
// p读出来的内容到\0结束
*x = '\0';
// 把起启地址为p到NULL结束的字符串转为十进制数
rss = strtoll(p,NULL,10)
rss *= page;
return rss;
}
#elif defined(HAVE_TASKINFO)
#include <unistd.h>
#include <stdio.h>
#include <stdlib.h>
#include <sys/types.h>
#include <sys/sysctl.h>
#include <mach/task.h>
#include <mach/mach_init.h>
// 通过task_info来获得rss
size_t zmalloc_get_rss(void){
task_t task = MACH_PORT_ULL;
struct task_basic_info t_info;
mach_msg_type_number_t t_info_count = TASK_BASIC_INFO_COUNT;
if (task_for_pid(current_task(), getpid(), &task) != KERN_SUCCESS)
return 0;
task_info(task, TASK_BASIC_INFO, (task_info_t)&t_info, &t_info_count);
return t_info.resident_size;
}
#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... */
return zmalloc_used_memory();
}
#endif
/* Fragmentation = RSS / allocated-bytes */
// 内存碎片大小= rss / used_memory
float zmalloc_get_fragmentation_ratio(size_t rss) {
return (float)rss/zmalloc_used_memory();
}
#if defined(HAVE_PROC_SMAPS)
// 获取私有的脏数据大小
// 在内存映射文件:/proc/self/smaps
// 字段为:Private_Dirty:
// Private_Dirty: 24 kB
size_t zmalloc_get_private_dirty(void) {
char line[1024];
size_t pd = 0;
FILE *fp = fopen("/proc/self/smaps","r");
if (!fp) return 0;
while(fgets(line,sizeof(line),fp) != NULL) {
if (strncmp(line,"Private_Dirty:",14) == 0) {
char *p = strchr(line,'k');
if (p) {
*p = '\0';
pd += strtol(line+14,NULL,10) * 1024;
}
}
}
fclose(fp);
return pd;
}
#else
size_t zmalloc_get_private_dirty(void) {
return 0;
}
#endif
今天就先看内存分配吧!我在代码里写了注释,具体为什么就看注释吧!