What are the exact conditions based on which Linux swaps process(s) memory from RAM to a swap file?

My server has 8Gigs of RAM and 8Gigs configured for swap file. I have memory intensive apps running. These apps have peak loads during which we find swap usage increase. Approximately 1 GIG of swap is used.

I have another server with 4Gigs of RAM and 8 Gigs of swap and similar memory intensive apps running on it. But here swap usage is very negligible. Around 100 MB.

I was wondering what are the exact conditions or a rough formula based on which Linux will do a swapout of a process memory in RAM to the swap file. I know its based on swapiness factor. What else is it based on? Swap file size? Any pointers to Linux kernal internal documentation/source code explaining this will be great.


Solution 1:

The VM subsystem of a Linux kernel is a very complicated beast, the kernel uses heuristics and algorithms to determine which pages to swap in/out and when to do that. I don't think there is a simple formula which is able to describe how and when pages are being put to disk. Maybe this LWN article is of use to you:

http://lwn.net/Articles/83588/

Solution 2:

As you probably know, the linux kernel uses as much memory as possible to cache things. That's why the output of free looks like I'm almost out of memory, according to the top line:

 $ free -m
              total       used       free     shared    buffers     cached
 Mem:          3168       2963        205          0        155       1263
 -/+ buffers/cache:       1543       1624
 Swap:          494         86        407

but the important part is the amount of RAM that buffers and cache aren't using

 -/+ buffers/cache:       1543       1624

Still, all but 205 MB of memory are used in that example, even if it is by cache. As it was explained to me (or at least, as I understood it), if a program suddenly requests > 205 MB of memory, that chunk comes out of swap, so that the process can have the memory chunk, then it comes out of swap once it gets a chance to free memory being used by cache.

As pfo mentioned, the underlying mechanisms are complex, and far beyond my understanding. I asked Ted Ts'o nearly this identical question at a class he was teaching at LISA, and I've given you essentially the same answer he gave me, or at least as I understood it.

Incidentally, I suspect that the memory "used" in swap isn't actually used by anything at this point, but that it just hasn't been freed yet.