> > so if i free() locked data, do
> > Leander> you think the page becomes unlocked even if there is
> > Leander> locked data left in the same page?
> > Are you sure free()ing the data will automatically munlock() it? I
> > doubt
> that was an question !
> i've been talking with somebody on #kernelnewbies and he
> told me that free()'d pages do not have to be returnd to the kernel...
> anyway - i often mlock()'d more pages than my computer has RAM, so
> the libc returns the pages to the kernel and they become unlocked, at
> least it seems so.
> > then
> > you shouldn't assume it does.
> ok, but if i free()'d memory and so that memory is not assigned to my
> task anymore, why should that page stay locked ?
A memory range could very well still be mapped in the process after
it has been free()'d. There could be other allocations on the same
page, and even if there isn't it depends on the library. Malloc and
friends are implemented by a library using mmap and similar
functions. The library will not mlock or munlock any pages. But if
the library returns the memory to the OS using munmap or similar it
should get unlocked.
> > In a well-designed API (which is the case in Linux and libc), every
> > function that allocates resources has a (or several) corresponding
> > functions that deallocate them, even if it is just a no-op in the
> > current implementation.
> they told me that mlock() is not a no-op
If mlock() was a no-op it would violate the specification. It
could be unimplemented which could be signaled by not defining
_POSIX_MEMLOCK_RANGE, any code using mlock should actually check
this definition. Another option would be to always return error
on any call of mlock, but that could prevent some programs from
working at all.
> > (This could change in another
> > implementation!) As a good programming habit (esp. with C/C++), you
> > should make sure such allocation and deallocations are done in pairs,
> > ... Apply this philosophy to your mlock() and
> > munlock().
> yes, but the kernel doesn't !
> - let's say struct a and b live in the same page
> - i mlock() struct a and b
> - later i munlock() struct a
> - struct b is munlock()d too, thats bad
True, if you need to mlock a struct it should not be allocated
using malloc. Allocating the struct with mmap sounds like a
better idea to me.
> the right way would be to determine the page for each struct. that's pretty easy,
> they told me how to do it in the irc. but i don't have the log here. i think it
> was a
> simple ptr&0x0value operation.
Of course doing your own bookkeeping would be another option.
Why do you need to mlock some memory, how much memory do you
need to mlock? Would mlockall() be an option for you?