Re: KSM For All Via LD_PRELOAD?

Paolo Bonzini
2010-06-09T08:56:42Z

On 06/09/2010 10:33 AM, Dor Laor wrote:
>> What I'm thinking about is somehow intercepting malloc() and wrapping it
>> so that all malloc()-ed memory gets madvise()-d as well.

You can also operate at a lower level and intercept mmap and brk, not
malloc. (But see below).

>> Or is this too crazy an idea?
>
> It should work. Note that the the malloced memory should be aligned in
> order to get better sharing.

Within glibc malloc large blocks are mmaped, so they are automatically
aligned. Effective sharing of small blocks would take too much luck or
too much wasted memory, so probably madvising brk memory is not too useful.

Of course there are exceptions. Bitmaps are very much sharable, but not
big. And some programs have their own allocator, using mmap in all
likelihood and slicing the resulting block. Typically these will be
virtual machines for garbage collected languages (but also GCC for
example does this). They will store a lot of pointers in there too, so
in this case KSM would likely work a lot for little benefit.

So if you really want to apply it to _all_ processes, it comes to mind
to wrap both mmap and malloc so that you can set a flag only for
mmap-within-malloc... It will take some experimentation and heuristics
to actually not degrade performance (and of course it will depend on the
workload), but it should work.

Paolo