Android12 简单的共享内存驱动实现 参考Ashmem

2024-04-01 19:20

本文主要是介绍Android12 简单的共享内存驱动实现 参考Ashmem,希望对大家解决编程问题提供一定的参考价值,需要的开发者们随着小编来一起学习吧!

Android12 共享内存驱动实现

SOC:RK3568

system:Android12

概述:

1. 概述
Ashmem(Anonymous Shared Memory,Android 匿名共享内存),它基于 mmap 系统调用,可以让不同进程将同一段物理内存映射到各自的虚拟地址中,从而实现内存共享。

它以驱动程序的形式在内核空间中实现,并通过文件描述符来传递共享内存的句柄。

工作上要使用Ashmem,但是对于C++来讲使用不方便,因为涉及到fd文件描述符传递 。于是想参考google 的Ashmem,设计一个简单的进程只通过操作文件即可获取共享的驱动

逻辑原理如下:

主要代码:

 //结构体MyAshmem_area 用来描述一块匿名共享内存struct MyAshmem_area {char name[MYASHMEM_FULL_NAME_LEN];//匿名struct list_head unpinned_list;//暂时无用//每一块匿名共享内存都会在临时文件系统tmpfs中对应一个文件,也就是filestruct file *file;size_t size;//文件的大小 sizeunsigned long prot_mask;//    prot_mask是访问保护位
};struct MyAshmem_area *asma;

开机启动Myshmem驱动:

static int __init MyAshmem_init(void)
{int ret = -ENOMEM;//创建一个使用slap缓存 用于分配 MyAshmem_area 的分配器MyAshmem_area_cachep = kmem_cache_create("ashmem_area_cache",sizeof(struct MyAshmem_area),0, 0, NULL);if (!MyAshmem_area_cachep) {pr_err("failed to create slab cache\n");goto out;}//注册匿名共享内存设备ret = misc_register(&MyAshmem_misc);if (ret) {pr_err("failed to register misc device!\n");goto out_free1;}pr_info("initialized\n");return 0;out_free1:kmem_cache_destroy(MyAshmem_area_cachep);
out:return ret;
}
注册时调用
device_initcall(MyAshmem_init);

 匿名内存设备是一个misc设备类型,所以它使用一个miscdevice类型的结构体结构体MyAshmem_misc进行注册,定义如下:

static struct miscdevice MyAshmem_misc = {.minor = MISC_DYNAMIC_MINOR,.name = "MyAshmem",.fops = &MyAshmem_fops,
};

文件操作/dev/MyAshmem,MyAshmem_fops 表示其操作方法列表。:

static const struct file_operations MyAshmem_fops = {.owner = THIS_MODULE,.open = MyAshmem_open,//当应用open时调用.release = MyAshmem_release,.mmap = MyAshmem_mmap,当应用mmap 时调用
};

open具体实现方法 :

static int MyAshmem_open(struct inode *inode, struct file *file)
{int ret;//当open计数器大于1时返回if(op > 0){printk("already MyAshmem_open");return 0;}printk("MyAshmem_open");asma = kmem_cache_zalloc(MyAshmem_area_cachep, GFP_KERNEL);if (!asma)return -ENOMEM;//初始化链表 ,暂时没完善INIT_LIST_HEAD(&asma->unpinned_list);memcpy(asma->name, MYASHMEM_NAME_PREFIX, MYASHMEM_NAME_PREFIX_LEN);//设置默认匿名strcpy(asma->name + MYASHMEM_NAME_PREFIX_LEN, "MyAshmemDrive");//设置默认长度asma->size = 4096;//设置默认保护位置asma->prot_mask = PROT_MASK;//open计数器加一op++;return 0;
}

mmap实现:

static int MyAshmem_mmap(struct file *file, struct vm_area_struct *vma)
{static struct file_operations vmfile_fops;int ret = 0;mutex_lock(&MyAshmem_mutex);printk("MyAshmem_mmap");/* user needs to SET_SIZE before mapping */if (!asma->size) {ret = -EINVAL;goto out;}/* requested mapping size larger than object size *///比较size 设置大小,否则直接失败if (vma->vm_end - vma->vm_start > PAGE_ALIGN(asma->size)) {ret = -EINVAL;goto out;}/* requested protection bits must match our allowed protection mask *///检测需要映射的虚拟内存vma的保护权限是否超过了匿名共享内存的保护权限//比如vma除了允许读之外还允许写,但是asma只允许读,这就算超过了,会mmap失败,直接返回。if ((vma->vm_flags & ~calc_vm_prot_bits(asma->prot_mask, 0)) &calc_vm_prot_bits(PROT_MASK, 0)) {ret = -EPERM;goto out;}vma->vm_flags &= ~calc_vm_may_flags(~asma->prot_mask);//第一次mmap会创造一个临时文件用来映射共享内存,//第二次打开直接从这个映射文件上mmapif (!asma->file) {char *name = MYASHMEM_NAME_DEF;struct file *vmfile;struct inode *inode;if (asma->name[MYASHMEM_NAME_PREFIX_LEN] != '\0')name = asma->name;/* ... and allocate the backing shmem file *///在tmpfs中创建一个临时文件。vmfile = shmem_file_setup(name, asma->size, vma->vm_flags);if (IS_ERR(vmfile)) {ret = PTR_ERR(vmfile);goto out;}vmfile->f_mode |= FMODE_LSEEK;inode = file_inode(vmfile);lockdep_set_class(&inode->i_rwsem, &backing_shmem_inode_class);//记录临时文件asma->file = vmfile;/** override mmap operation of the vmfile so that it can't be* remapped which would lead to creation of a new vma with no* asma permission checks. Have to override get_unmapped_area* as well to prevent VM_BUG_ON check for f_ops modification.*/if (!vmfile_fops.mmap) {vmfile_fops = *vmfile->f_op;vmfile_fops.mmap = MyAshmem_vmfile_mmap;vmfile_fops.get_unmapped_area =MyAshmem_vmfile_get_unmapped_area;}vmfile->f_op = &vmfile_fops;}get_file(asma->file);/** XXX - Reworked to use shmem_zero_setup() instead of* shmem_set_file while we're in staging. -jstultz*///判断映射虚拟内存vma是否需要在不同进程间共享,if (vma->vm_flags & VM_SHARED) {ret = shmem_zero_setup(vma);if (ret) {fput(asma->file);goto out;}} else {vma_set_anonymous(vma);}if (vma->vm_file)fput(vma->vm_file);vma->vm_file = asma->file;out:mutex_unlock(&MyAshmem_mutex);//返回地址return ret;
}

全部代码drivers\staging\android\MyAshmem.c:

#include <linux/init.h>
#include <linux/export.h>
#include <linux/file.h>
#include <linux/fs.h>
#include <linux/falloc.h>
#include <linux/miscdevice.h>
#include <linux/security.h>
#include <linux/mm.h>
#include <linux/mman.h>
#include <linux/uaccess.h>
#include <linux/personality.h>
#include <linux/bitops.h>
#include <linux/mutex.h>
#include <linux/shmem_fs.h>#define PROT_MASK		(PROT_EXEC | PROT_READ | PROT_WRITE)#define MYASHMEM_NAME_LEN		256
#define MYASHMEM_NAME_PREFIX "dev/MyAshmem/"
#define MYASHMEM_NAME_PREFIX_LEN (sizeof(MYASHMEM_NAME_PREFIX) - 1)
#define MYASHMEM_FULL_NAME_LEN (MYASHMEM_NAME_LEN + MYASHMEM_NAME_PREFIX_LEN)
#define MYASHMEM_NAME_DEF "/dev/MyAshmem"
static int op = 0;
struct MyAshmem_area {char name[MYASHMEM_FULL_NAME_LEN];struct list_head unpinned_list;struct file *file;size_t size;unsigned long prot_mask;
};
struct MyAshmem_area *asma;static DEFINE_MUTEX(MyAshmem_mutex);
static struct kmem_cache *MyAshmem_area_cachep __read_mostly;static int MyAshmem_open(struct inode *inode, struct file *file)
{int ret;//当open计数器大于1时返回if(op > 0){printk("already MyAshmem_open");return 0;}printk("MyAshmem_open");asma = kmem_cache_zalloc(MyAshmem_area_cachep, GFP_KERNEL);if (!asma)return -ENOMEM;//初始化链表 ,暂时没完善INIT_LIST_HEAD(&asma->unpinned_list);memcpy(asma->name, MYASHMEM_NAME_PREFIX, MYASHMEM_NAME_PREFIX_LEN);//设置默认匿名strcpy(asma->name + MYASHMEM_NAME_PREFIX_LEN, "MyAshmemDrive");//设置默认长度asma->size = 4096;//设置默认保护位置asma->prot_mask = PROT_MASK;//open计数器加一op++;return 0;
}static int MyAshmem_release(struct inode *ignored, struct file *file)
{if (asma->file)fput(asma->file);kmem_cache_free(MyAshmem_area_cachep, asma);op--;return 0;
}
static int MyAshmem_vmfile_mmap(struct file *file, struct vm_area_struct *vma)
{/* do not allow to mmap ashmem backing shmem file directly */return -EPERM;
}static unsigned long
MyAshmem_vmfile_get_unmapped_area(struct file *file, unsigned long addr,unsigned long len, unsigned long pgoff,unsigned long flags)
{return current->mm->get_unmapped_area(file, addr, len, pgoff, flags);
}static inline vm_flags_t calc_vm_may_flags(unsigned long prot)
{return _calc_vm_trans(prot, PROT_READ,  VM_MAYREAD) |_calc_vm_trans(prot, PROT_WRITE, VM_MAYWRITE) |_calc_vm_trans(prot, PROT_EXEC,  VM_MAYEXEC);
}static struct lock_class_key backing_shmem_inode_class;
static int MyAshmem_mmap(struct file *file, struct vm_area_struct *vma)
{static struct file_operations vmfile_fops;int ret = 0;mutex_lock(&MyAshmem_mutex);printk("MyAshmem_mmap");/* user needs to SET_SIZE before mapping */if (!asma->size) {ret = -EINVAL;goto out;}/* requested mapping size larger than object size *///比较size 设置大小,否则直接失败if (vma->vm_end - vma->vm_start > PAGE_ALIGN(asma->size)) {ret = -EINVAL;goto out;}/* requested protection bits must match our allowed protection mask *///检测需要映射的虚拟内存vma的保护权限是否超过了匿名共享内存的保护权限//比如vma除了允许读之外还允许写,但是asma只允许读,这就算超过了,会mmap失败,直接返回。if ((vma->vm_flags & ~calc_vm_prot_bits(asma->prot_mask, 0)) &calc_vm_prot_bits(PROT_MASK, 0)) {ret = -EPERM;goto out;}vma->vm_flags &= ~calc_vm_may_flags(~asma->prot_mask);//第一次mmap会创造一个临时文件用来映射共享内存,//第二次打开直接从这个映射文件上mmapif (!asma->file) {char *name = MYASHMEM_NAME_DEF;struct file *vmfile;struct inode *inode;if (asma->name[MYASHMEM_NAME_PREFIX_LEN] != '\0')name = asma->name;/* ... and allocate the backing shmem file *///在tmpfs中创建一个临时文件。vmfile = shmem_file_setup(name, asma->size, vma->vm_flags);if (IS_ERR(vmfile)) {ret = PTR_ERR(vmfile);goto out;}vmfile->f_mode |= FMODE_LSEEK;inode = file_inode(vmfile);lockdep_set_class(&inode->i_rwsem, &backing_shmem_inode_class);//记录临时文件asma->file = vmfile;/** override mmap operation of the vmfile so that it can't be* remapped which would lead to creation of a new vma with no* asma permission checks. Have to override get_unmapped_area* as well to prevent VM_BUG_ON check for f_ops modification.*/if (!vmfile_fops.mmap) {vmfile_fops = *vmfile->f_op;vmfile_fops.mmap = MyAshmem_vmfile_mmap;vmfile_fops.get_unmapped_area =MyAshmem_vmfile_get_unmapped_area;}vmfile->f_op = &vmfile_fops;}get_file(asma->file);/** XXX - Reworked to use shmem_zero_setup() instead of* shmem_set_file while we're in staging. -jstultz*///判断映射虚拟内存vma是否需要在不同进程间共享,if (vma->vm_flags & VM_SHARED) {ret = shmem_zero_setup(vma);if (ret) {fput(asma->file);goto out;}} else {vma_set_anonymous(vma);}if (vma->vm_file)fput(vma->vm_file);vma->vm_file = asma->file;out:mutex_unlock(&MyAshmem_mutex);//返回地址return ret;
}static const struct file_operations MyAshmem_fops = {.owner = THIS_MODULE,.open = MyAshmem_open,.release = MyAshmem_release,.mmap = MyAshmem_mmap,
};static struct miscdevice MyAshmem_misc = {.minor = MISC_DYNAMIC_MINOR,.name = "MyAshmem",.fops = &MyAshmem_fops,
};static int __init MyAshmem_init(void)
{int ret = -ENOMEM;//创建一个使用slap缓存 用于分配 MyAshmem_area 的分配器MyAshmem_area_cachep = kmem_cache_create("ashmem_area_cache",sizeof(struct MyAshmem_area),0, 0, NULL);if (!MyAshmem_area_cachep) {pr_err("failed to create slab cache\n");goto out;}//注册匿名共享内存设备ret = misc_register(&MyAshmem_misc);if (ret) {pr_err("failed to register misc device!\n");goto out_free1;}pr_info("initialized\n");return 0;out_free1:kmem_cache_destroy(MyAshmem_area_cachep);
out:return ret;
}
device_initcall(MyAshmem_init);

drivers/staging/android/Makefile 

ccflags-y += -I$(src)                   # needed for trace eventsobj-y                                   += ion/
obj-$(CONFIG_FIQ_DEBUGGER)              += fiq_debugger/obj-$(CONFIG_ASHMEM)                    += ashmem.o
obj-$(CONFIG_ANDROID_VSOC)              += vsoc.o
+++obj-y                           += MyAshmem.o

进程write:

#include <stdio.h>
#include <stdlib.h>
#include<sys/types.h>
#include<sys/stat.h>
#include<fcntl.h>
#include<sys/mman.h>
#include<unistd.h>
#define ASHMEM_DEVICE  "/dev/MyAshmem"
int main(void){int fd = open(ASHMEM_DEVICE, O_RDWR);char *addr = (char*)mmap(NULL, 4096 , PROT_READ | PROT_WRITE, MAP_SHARED, fd, 0);int i =0;while(1){*addr = i++;printf("write:%d\n",*addr);sleep(1);}return 0;
}

进程read:

#include <stdio.h>
#include <stdlib.h>
#include<sys/types.h>
#include<sys/stat.h>
#include<fcntl.h>
#include<sys/mman.h>
#include<unistd.h>
#define ASHMEM_DEVICE  "/dev/MyAshmem"
int main(void){int fd2 = open(ASHMEM_DEVICE, O_RDWR);char *addr2 = (char*)mmap(NULL, 4096 , PROT_READ | PROT_WRITE, MAP_SHARED, fd2, 0);int i =0;while(1){printf("read:%d\n",*addr2);sleep(1);}return 0;
}

编译/mnt/h/android-ndk-r21e/android-ndk-r21e/install/bin/aarch64-linux-android-g++ write.cpp -o write.out

/mnt/h/android-ndk-r21e/android-ndk-r21e/install/bin/aarch64-linux-android-g++ read.cpp  -o read.out

结果:

BUG:1.目前只能使用一次,得重新开机才能使用

2.不支持多组,只支持一组应用使用 

下一章节改进,觉得有用喜欢的话就给个点赞+收藏

这篇关于Android12 简单的共享内存驱动实现 参考Ashmem的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!



http://www.chinasem.cn/article/867950

相关文章

hdu1043(八数码问题,广搜 + hash(实现状态压缩) )

利用康拓展开将一个排列映射成一个自然数,然后就变成了普通的广搜题。 #include<iostream>#include<algorithm>#include<string>#include<stack>#include<queue>#include<map>#include<stdio.h>#include<stdlib.h>#include<ctype.h>#inclu

csu 1446 Problem J Modified LCS (扩展欧几里得算法的简单应用)

这是一道扩展欧几里得算法的简单应用题,这题是在湖南多校训练赛中队友ac的一道题,在比赛之后请教了队友,然后自己把它a掉 这也是自己独自做扩展欧几里得算法的题目 题意:把题意转变下就变成了:求d1*x - d2*y = f2 - f1的解,很明显用exgcd来解 下面介绍一下exgcd的一些知识点:求ax + by = c的解 一、首先求ax + by = gcd(a,b)的解 这个

hdu2289(简单二分)

虽说是简单二分,但是我还是wa死了  题意:已知圆台的体积,求高度 首先要知道圆台体积怎么求:设上下底的半径分别为r1,r2,高为h,V = PI*(r1*r1+r1*r2+r2*r2)*h/3 然后以h进行二分 代码如下: #include<iostream>#include<algorithm>#include<cstring>#include<stack>#includ

【C++】_list常用方法解析及模拟实现

相信自己的力量,只要对自己始终保持信心,尽自己最大努力去完成任何事,就算事情最终结果是失败了,努力了也不留遗憾。💓💓💓 目录   ✨说在前面 🍋知识点一:什么是list? •🌰1.list的定义 •🌰2.list的基本特性 •🌰3.常用接口介绍 🍋知识点二:list常用接口 •🌰1.默认成员函数 🔥构造函数(⭐) 🔥析构函数 •🌰2.list对象

【Prometheus】PromQL向量匹配实现不同标签的向量数据进行运算

✨✨ 欢迎大家来到景天科技苑✨✨ 🎈🎈 养成好习惯,先赞后看哦~🎈🎈 🏆 作者简介:景天科技苑 🏆《头衔》:大厂架构师,华为云开发者社区专家博主,阿里云开发者社区专家博主,CSDN全栈领域优质创作者,掘金优秀博主,51CTO博客专家等。 🏆《博客》:Python全栈,前后端开发,小程序开发,人工智能,js逆向,App逆向,网络系统安全,数据分析,Django,fastapi

让树莓派智能语音助手实现定时提醒功能

最初的时候是想直接在rasa 的chatbot上实现,因为rasa本身是带有remindschedule模块的。不过经过一番折腾后,忽然发现,chatbot上实现的定时,语音助手不一定会有响应。因为,我目前语音助手的代码设置了长时间无应答会结束对话,这样一来,chatbot定时提醒的触发就不会被语音助手获悉。那怎么让语音助手也具有定时提醒功能呢? 我最后选择的方法是用threading.Time

Android实现任意版本设置默认的锁屏壁纸和桌面壁纸(两张壁纸可不一致)

客户有些需求需要设置默认壁纸和锁屏壁纸  在默认情况下 这两个壁纸是相同的  如果需要默认的锁屏壁纸和桌面壁纸不一样 需要额外修改 Android13实现 替换默认桌面壁纸: 将图片文件替换frameworks/base/core/res/res/drawable-nodpi/default_wallpaper.*  (注意不能是bmp格式) 替换默认锁屏壁纸: 将图片资源放入vendo

usaco 1.3 Prime Cryptarithm(简单哈希表暴搜剪枝)

思路: 1. 用一个 hash[ ] 数组存放输入的数字,令 hash[ tmp ]=1 。 2. 一个自定义函数 check( ) ,检查各位是否为输入的数字。 3. 暴搜。第一行数从 100到999,第二行数从 10到99。 4. 剪枝。 代码: /*ID: who jayLANG: C++TASK: crypt1*/#include<stdio.h>bool h

C#实战|大乐透选号器[6]:实现实时显示已选择的红蓝球数量

哈喽,你好啊,我是雷工。 关于大乐透选号器在前面已经记录了5篇笔记,这是第6篇; 接下来实现实时显示当前选中红球数量,蓝球数量; 以下为练习笔记。 01 效果演示 当选择和取消选择红球或蓝球时,在对应的位置显示实时已选择的红球、蓝球的数量; 02 标签名称 分别设置Label标签名称为:lblRedCount、lblBlueCount

uva 10387 Billiard(简单几何)

题意是一个球从矩形的中点出发,告诉你小球与矩形两条边的碰撞次数与小球回到原点的时间,求小球出发时的角度和小球的速度。 简单的几何问题,小球每与竖边碰撞一次,向右扩展一个相同的矩形;每与横边碰撞一次,向上扩展一个相同的矩形。 可以发现,扩展矩形的路径和在当前矩形中的每一段路径相同,当小球回到出发点时,一条直线的路径刚好经过最后一个扩展矩形的中心点。 最后扩展的路径和横边竖边恰好组成一个直