从内核线程为用户空间分配内存 [英] Allocating memory for user space from kernel thread

查看:187
本文介绍了从内核线程为用户空间分配内存的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我的问题是关于将数据从内核传递到用户空间程序.我想实现一个系统调用"get_data(size,char * buff,char ** meta_buf)".在此调用中,buff由用户空间程序分配,并且其长度在size参数中传递.但是,meta_buf是可变长度的缓冲区,已分配(在用户空间程序的vm页面中)并由内核填充.用户空间程序将释放该区域.

My question is about passing data from kernel to a user space program. I want to implement a system call "get_data(size, char *buff, char **meta_buf)". In this call, buff is allocated by user space program and its length is passed in the size argument. However, meta_buf is a variable length buffer that is allocated (in the user space program's vm pages) and filled by kernel. User space program will free this region.

(我无法在用户空间中分配数据,因为用户空间程序不知道meta_buff的大小.而且,用户空间程序无法分配固定数量的内存,并且一次又一次调用系统调用以读取整个元数据. meta_data必须在一个系统调用中返回)

(I cant allocate data in user space as user space program does not know size of the meta_buff. Also, user space program cannot allocate a fixed amount of memory and call the system call again and again to read the entire meta data. meta_data has to be returned in one single system call)

  1. 如何从内核线程为用户空间程序分配内存? (如果您能指出执行类似操作的任何其他系统调用(在内核中分配并在用户空间中释放),我将不胜感激
  2. 此界面正确还是有更好的方法呢?
  1. How do I allocate memory for a user space program from kernel thread? (I would even appreciate if you can point me to any other system call that does a similar operation - allocating in kernel and freeing in user space)
  2. Is this interface right or is there a better way to do it?

推荐答案

不要尝试从内核为用户空间分配内存-这严重违反了内核的抽象层.相反,请考虑其他一些选择:

Don't attempt to allocate memory for userspace from the kernel - this is a huge violation of the kernel's abstraction layering. Instead, consider a few other options:

  • 让用户空间询问它需要多少空间.用户空间进行分配,然后从内核中获取内存.
  • 将驱动程序拥有的用户空间mmap页面直接放入其地址空间.
  • 设置所需数据量的上限.分配那么多.

在不知道为什么必须是原子的的情况下很难说更多.实际上,分配内存无论如何都必须是可中断的(否则您不太可能成功),因此从内核中移出和移回内核的可能性不大.实际上,对用户空间内存的任何写入 必须是可中断的,因为存在可能需要IO的页面错误.

It's hard to say more without knowing why this has to be atomic. Actually allocating memory's going to need to be interruptible anyway (or you're unlikely to succeed), so it's unlikely that going out of and back into the kernel is going to hurt much. In fact, any write to userspace memory must be interruptible, as there's the potential for page faults requiring IO.

这篇关于从内核线程为用户空间分配内存的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆