Interesting. I've never heard of that happening before. Can you link a reference to where I can find out more about that aspect of the linux memory subsystem?
The mlock manual[0] has a "notes" section that provides a good brief summary. The GNU libc manual has more than anyone would ever want to read about memory management, including a section on memory locking[1].
On an intuitive level, think of swap as being a place the kernel can put memory the program has written. When you malloc(4096) and write some bytes into it, the kernel can't evict that page to disk unless there's some swap space to stick it in. However, executables are different because they're already on disk -- the in-memory version is just a cache (everything is cache (computers have too many caches)). The kernel is allowed to drop the copy of the program it has in memory, because it can always read it back from the original executable.
It's one of the reasons why running without swap can have even worse pathological behaviour than running with swap. With swap the kernel can prioritise keeping code in RAM over little-used data, wheras without it when RAM fills up with data eventually the currently running hot code gets swapped out and performance completely tanks, meaning the system doesn't actually hit the nice OOM error you hope it would. (hence userspace utilities like earlyoom to kick in before the kernel's absolute last resort strategy).
I believe that when a file is mmap'd a page table is created for it in the . As you perform read/write on the file a fault loads the actual entries into that page table. As pages can be mapped they so too can be unmapped under pressure, without that falling back to swap (since it is already a file backed map, you wouldn't swap a file backed map to a different file after all).
There are a few relevant bits to this. You can MAP_POPULATE the file to prepopulate the entries and you can MAP_LOCKED to MAP_POPULATE + lock the pages in (unreliably). As mentioned in the man page for mmap MAP_LOCKED has some failure modes that you don't get with mlock.