shm_map questions

John Baldwin jhb at freebsd.org
Thu Apr 18 15:24:35 UTC 2013


On Thursday, April 11, 2013 10:58:14 am Laurie Jennings wrote:
> Im working on a simple project that shares a memory segment between a user 
processand a kernel module. I'm having some problems with shm_map and there 
doesn't seem to be much info on it.
> Im not sure what happened to the memory when the user process that creates 
it terminates.  I have some questions.
> 1) Does the kernel mapping keep the segment from being garbage collected 
when the use process that creates it terminated? I've experienced shm_unmap() 
panic when tryingto unmap a segment
> scenario:  
> User process Maps SegmentKernel maps it  with shm_map()User Process 
TerminatesKernel tries to shm_unmap() and it panics.

The kernel mapping bumps the refcount on the underlying vm object, so it will
not go away.  OTOH, you should be keeping your own reference count on the
associated fd so that you can call shm_unmap().  That is, the model should be
something like:

struct mydata *foo;

foo->fp = fget(fd);
shm_map(fp, &foo->p);
/* Don't call fdrop */

and then when unmapping:

struct mydata *foo;

shm_unmap(foo->fp, foo->p);
fdrop(foo->fp);

> 2) Is there a way for the kernel process to know when the user process has 
goneaway? A ref count?

You can install a process_exit EVENTHANDLER if you want to destroy this when a
process goes away.  I have used shm_map/unmap for other objects that already
had a reference count so I did my shm_unmap when that object was destroyed.

> 3) Does a SHM_ANON segment persist as long as the kernel has it mapped, or 
doesit get garbage collected when the creating user process terminates?

It goes away when the backing 'struct file' goes away.  If you follow the 
model above of keeping a reference count on the associated struct file then
it won't go away until you fdrop() after the shm_unmap.

> 4) When using a named segment, can the kernel "reuse" a mapping for a new 
userprocess?
> Example:
> User process creates shm segment with path /fooKernel Maps shm segment with 
shm_map()User process terminates.User process runs again, opening segment /foo
> Does the kernel need to re-map, or is the original mapping valid?

The mapping is not per-process, so if you have mapped a shm for /foo and
mapped it, it will stay mapped until you call shm_unmap.  Multiple processes
can shm_open /foo and mmap it and they will all share the same memory.

You could even share a SHM_ANON fd among multiple processes by passing it
across a UNIX domain socket.

Hope this helps.

-- 
John Baldwin


More information about the freebsd-net mailing list