A swap partition doesn't contain a structured filesystem. The kernel doesn't need that because it stores memory pages on the partition marked as a swap area. Since there could be several memory pages in the swap area, how does the kernel locate each page when a process requests its page to be loaded into memory? Let's explain more: Looking at the header of the swap partition from Devuan OS:
#define SWAP_UUID_LENGTH 16
#define SWAP_LABEL_LENGTH 16
struct swap_header_v1_2 {
char bootbits[1024]; /* Space for disklabel etc. */
unsigned int version;
unsigned int last_page;
unsigned int nr_badpages;
unsigned char uuid[SWAP_UUID_LENGTH];
char volume_name[SWAP_LABEL_LENGTH];
unsigned int padding[117];
unsigned int badpages[1];
};
So when mkswap
command is executed for a partition, that's what gets placed on that partition, the swap header.
Now, let's have a scenario where "process A" has its memory page swapped, so there's one memory page in the swap area. Of course, there could be many memory pages in the swap area. "Process A" needs to access that memory page that was swapped. "Process A" tells the kernel, may I have my swapped memory page, please? The kernel says: sure, my dear friend. The kernel looks for "process A"'s memory page in the swap partition. Since the swap partition isn't a sophisticated structure (not a filesystem), how would the kernel know how to locate that specific memory page of "process A" in the swap partition?
Perhaps the kernel somewhere stores sector addresses for those swapped pages, so when a process asks for its memory page, the kernel knows where to look in the swap partition, reads the memory page from the partition and loads it into memory.
Swap is only valid during a given boot, so all the tracking information is kept in memory. Swapping pages in and out is handled entirely by the kernel, and is transparent to processes. Basically, memory is split up into pages, tracked in page tables; these are structures defined by each CPU architecture. When a page is swapped out, the kernel marks it as invalid; thus, the next time anything tries to access the page, the CPU will fault, which will cause a handler in the kernel to be invoked; its this handlers responsibility to restore the pages contents.
In Linux, theres a swap_info
structure which describes each swap device or file. Within that structure, a swap_map
maps memory pages to blocks in the swap device or file. When a page is swapped out, the kernel stores the swap_info
index and swap_map
offset in the corresponding page table entry, which allows it to find the page on disk when necessary. (All supported architectures provide enough space for this in their page tables, but there are limits e.g. the available space means that Linux can manage at most 64GiB of swap on x86.)
Youll find a much more detailed description of all this in the Swap Management chapter of Mel Gormans Understanding the Linux Virtual Memory Manager.
External links referenced by this document: