你知道Linux的共享内存与tmpfs文件系统是什么样?

前言
共享内存主要用于进程间通信,linux有两种共享内存(shared memory)机制:
(1)** system v shared memory(shmget/shmat/shmdt) **
original shared memory mechanism, still widely usedsharing between unrelated processes.
(2)**posix shared memory(shm_open/shm_unlink) **
sharing between unrelated processes, without overhead of filesystem i/ointended to be simpler and better than older apis.
另外,在linux中不得不提一下内存映射(也可用于进程间通信):
** shared mappings – mmap(2) **
lshared anonymous mappings:sharing between related processes only (related via fork())
lshared file mappings:sharing between unrelated processes, backed by file in filesystem
system v共享内存历史悠久,使用也很广范,很多类unix系统都支持。一般来说,我们在写程序时也通常使用第一种。这里不再讨论如何使用它们,关于posix共享内存的详细介绍可以参考这里1,这里2。
**讲到那么多,那么问题来了,共享内存与tmpfs有什么关系?**
the posix shared memory object implementation on linux 2.4 makes use of a dedicated filesystem, which is normally mounted under /dev/shm.
从这里可以看到,posix共享内存是基于tmpfs来实现的。实际上,更进一步,不仅psm(posix shared memory),而且ssm(system v shared memory)在内核也是基于tmpfs实现的。
tmpfs介绍
下面是内核文档中关于tmpfs的介绍:
tmpfs has the following uses:
1) there is always a kernel internal mount which you will not see at all. this is used for shared anonymous mappings and sysv shared memory.
this mount does not depend on config_tmpfs. if config_tmpfs is not set, the user visible part of tmpfs is not build. but the internal mechanisms are always present.
2) glibc 2.2 and above expects tmpfs to be mounted at /dev/shm for posix shared memory (shm_open, shm_unlink). adding the following line to /etc/fstab should take care of this:
tmpfs /dev/shm tmpfs defaults 0 0
remember to create the directory that you intend to mount tmpfs on if necessary.
this mount isnotneeded for sysv shared memory. the internal mount is used for that. (in the 2.3 kernel versions it was necessary to mount the predecessor of tmpfs (shm fs) to use sysv shared memory)
从这里可以看到tmpfs主要有两个作用:
(1)用于sysv共享内存,还有匿名内存映射;这部分由内核管理,用户不可见;
(2)用于posix共享内存,由用户负责mount,而且一般mount到/dev/shm;依赖于config_tmpfs;
到这里,我们可以了解,ssm与psm之间的区别,也明白了/dev/shm的作用。
下面我们来做一些测试:
测试
我们将/dev/shm的tmpfs设置为64m:
# mount -size=64m -o remount /dev/shm# df -lh
filesystem size used avail use% mounted on
tmpfs 64m 0 64m 0% /dev/shm
sysv共享内存的最大大小为32m:
# cat /proc/sys/kernel/shmmax
33554432
(1)创建65m的system v共享内存失败:
# ipcmk -m 68157440
ipcmk: create share memory failed: invalid argument
这是正常的。
(2)将shmmax调整为65m
# echo 68157440 > /proc/sys/kernel/shmmax# cat /proc/sys/kernel/shmmax
68157440# ipcmk -m 68157440
shared memory id: 0# ipcs -m
------ shared memory segments --------
key shmid owner perms bytes nattch status
0xef46b249 0 root 644 68157440 0
可以看到system v共享内存的大小并不受/dev/shm的影响。
(3)创建posix共享内存
点击(此处)折叠或打开
/*gcc-o shmopen shmopen.c-lrt*/#include
#include
#include
#include
#include
#include
#include
#define map_size 68157440
int main(intargc,char*argv[])
{
intfd;
void*result;
fd=shm_open(/shm1,o_rdwr|o_creat,0644);
if(fd<0){
printf(shm_open failed\n);
exit(1);
}
return 0;
}
# ./shmopen# ls -lh /dev/shm/shm1
-rw-r--r-- 1 root root 65m mar 3 06:19 /dev/shm/shm1
仅管/dev/shm只有64m,但创建65m的posix sm也可以成功。
(4)向posix sm写数据
点击(此处)折叠或打开
/*gcc-o shmwrite shmwrite.c-lrt*/#include
#include
#include
#include
#include
#include
#include
#define map_size 68157440
int main(intargc,char*argv[])
{
intfd;
void*result;
fd=shm_open(/shm1,o_rdwr|o_creat,0644);
if(fd<0){
printf(shm_open failed\n);
exit(1);
}
if(ftruncate(fd,map_size)size。
# stat /dev/shm/shm2
file:/dev/shm/shm2
size: 68157440 blocks: 0 io block: 4096 普通文件
device: 10h/16d inode: 217177 links: 1
access:(0644/-rw-r--r--)uid:(0/ root)gid:(0/ root)
access: 2015-03-03 15:24:28.025985167 +0800
modify: 2015-03-03 15:24:28.025985167 +0800
change: 2015-03-03 15:24:28.025985167 +0800
(5)向sys v共享内存写数据
将system v共享内存的最大值调整为65m(/dev/shm仍然为64m)。
# cat /proc/sys/kernel/shmmax
68157440
点击(此处)折叠或打开
/*gcc-o shmv shmv.c*/#include
#include
#include
#include
#define map_size 68157440
int main(intargc,char**argv){
intshm_id,i;
key_t key;
char temp;
char*p_map;
char*name=/dev/shm/shm3;
key=ftok(name,0);
if(key==-1)
perror(ftok error);
shm_id=shmget(key,map_size,ipc_creat);
if(shm_id==-1)
{
perror(shmget error);
return;
}
p_map=(char*)shmat(shm_id,null,0);
memset(p_map,0,map_size);
if(shmdt(p_map)==-1)
perror( detach error );
}
#./shmv
却可以正常执行。
(7)结论
虽然system v与posix共享内存都是通过tmpfs实现,但是受的限制却不相同。也就是说/proc/sys/kernel/shmmax只会影响sys v共享内存,/dev/shm只会影响posix共享内存。实际上,system v与posix共享内存本来就是使用的两个不同的tmpfs实例(instance)。
内核分析
内核在初始化时,会自动mount一个tmpfs文件系统,挂载为shm_mnt:
点击(此处)折叠或打开
//mm/shmem.cstatic struct file_system_type
shmem_fs_type={
.owner=this_module,
.name=tmpfs,
.get_sb=shmem_get_sb,
.kill_sb=kill_litter_super,
};
int__init shmem_init(void){
...
error=register_filesystem(&shmem_fs_type);
if(error)
{
printk(kern_errcould not register tmpfs\n);
goto out2;
}
///挂载tmpfs(用于sys v)
shm_mnt=vfs_kern_mount(&shmem_fs_type,ms_nouser,shmem_fs_type.name,null);
/dev/shm的mount与普通文件mount的流程类似,不再讨论。但是,值得注意的是,/dev/shm默认的大小为当前物理内存的1/2:
shmem_get_sb –> shmem_fill_super
点击(此处)折叠或打开
//mem/shmem.c
intshmem_fill_super(struct super_block*sb,void*data,intsilent)
{
...
#ifdef config_tmpfs
/*
*per default we only allow half of the physical ram per
*tmpfs instance,limiting inodestoone per page of lowmem;
*but the internal instanceisleftunlimited.
*/
if(!(sb->s_flags&ms_nouser)){///内核会设置ms_nouser
sbinfo->max_blocks=shmem_default_max_blocks();
sbinfo->max_inodes=shmem_default_max_inodes();
if(shmem_parse_options(data,sbinfo,false)){
err=-einval;
goto failed;
}
}
sb->s_export_op=&shmem_export_ops;
#else
...
#ifdef config_tmpfs
static unsigned long shmem_default_max_blocks(void){
return totalram_pages/2;
}
可以看到:由于内核在mount tmpfs时,指定了ms_nouser,所以该tmpfs没有大小限制,因此,sys v共享内存能够使用的内存空间只受/proc/sys/kernel/shmmax限制;而用户通过挂载的/dev/shm,默认为物理内存的1/2。
注意config_tmpfs.
另外,在/dev/shm创建文件走vfs接口,而sys v与匿名映射却是通过shmem_file_setup实现:
sigbus
当应用访问共享内存对应的地址空间,如果对应的物理page还没有分配,就会调用fault方法,分配失败,就会返回oom或者bigbus错误:
点击(此处)折叠或打开
staticconststruct vm_operations_struct shmem_vm_ops={
.fault=shmem_fault,
#ifdef config_numa
.set_policy=shmem_set_policy,
.get_policy=shmem_get_policy,
#endif
};
staticintshmem_fault(struct vm_area_struct*vma,struct vm_fault*vmf)
{
struct inode*inode=vma->vm_file->f_path.dentry->d_inode;
interror;
intret=vm_fault_locked;
error=shmem_getpage(inode,vmf->pgoff,&vmf->page,sgp_cache,&ret);
if(error)
return((error==-enomem)?vm_fault_oom:vm_fault_sigbus);
return ret;
}
shmem_getpage –>shmem_getpage_gfp:
/*
*shmem_getpage_gfp-find pageincache,orgetfrom swap,orallocate
*
*ifwe allocate a new one wedonotmark it dirty.that's uptothe
*vm.ifwe swap itinwe mark it dirty since we also free the swap
*entry since a page cannot liveinboth the swapandpage cache
*/
staticintshmem_getpage_gfp(struct inode*inode,pgoff_t index,
struct page**pagep,enum sgp_type sgp,gfp_t gfp,int*fault_type)
{
...
if(sbinfo->max_blocks){///dev/shm会有该值
if(percpu_counter_compare(&sbinfo->used_blocks,sbinfo->max_blocks)>=0){
error=-enospc;
goto unacct;
}
percpu_counter_inc(&sbinfo->used_blocks);
}
//分配一个物理page
page=shmem_alloc_page(gfp,info,index);
if(!page){
error=-enomem;
goto decused;
}
setpageswapbacked(page);
__set_page_locked(page);
error=mem_cgroup_cache_charge(page,current->mm,gfp&gfp_reclaim_mask);///mem_cgroup检查
if(!error)
error=shmem_add_to_page_cache(page,mapping,index,gfp,null);
共享内存与cgroup
目前,共享内存的空间计算在第一个访问共享内存的group,参考:
lhttp://lwn.net/articles/516541/
lhttps://www.kernel.org/doc/documentation/cgroups/memory.txt
posix共享内存与docker
目前docker将/dev/shm限制为64m,却没有提供参数,这种做法比较糟糕。如果应用使用大内存的posix共享内存,必然会导致问题。 参考:
lhttps://github.com/docker/docker/issues/2606
lhttps://github.com/docker/docker/pull/4981
总结
(1)posix共享内存与sys v共享内存在内核都是通过tmpfs实现,但对应两个不同的tmpfs实例,相互独立。
(2)通过/proc/sys/kernel/shmmax可以限制sys v共享内存(单个)的最大值,通过/dev/shm可以限制posix共享内存的最大值(所有之和)。

5G正在撬开一个新世界
挑选液晶拼接屏的几大要点
TriQuint最新高效率多频多模功率放大器为全球下一代3G/4G智能手机扩展连接时间
还在抱怨荣耀8手机续航不给力? 只要你关闭这个功能就能解决!
英特尔总裁与行业大咖深析解读IoT+AI,旨在推动IoT+AI等技术落地
你知道Linux的共享内存与tmpfs文件系统是什么样?
一文知道AC-DC电源模块电路设计的步骤
基于PWM技术的太阳能控制器的制作
Unity的层级细节使用流程
变频器频率为何调不上去?如何解决?
电源模块可靠性测试及设计要点
AR技术最常见的7中表现方式
什么因素带动了加密货币成为了投资的品种
苹果再刷新历史新高,市值高达9428亿美元距万亿美元大关近在咫尺
苹果延长MacBook Pro背光质保时间
少儿编程越来越火,这种现象到底是好是坏
多土层土壤参数监测仪的功能特点
人工智能需要的人才是每个人
几种汽车安全技术:ABS、TCS、VDC
智能变电站和传统变电站的区别