mmap creates a memory mapping between a region of virtual memory and a file or device. the kernel needs to determine how to locate the corresponding region in the underlying storage and manage its lifecycle.
when you mmap a file or device, you provide file descriptor and other parameters to the kernel. the kernel uses this information to locate the file or device in the underlying storage system. the kernel maintains data structures such as the file system's inode table or device-specific data structures to track the location and attributes of the file or device.
the mapping itself is established by associating a range of virtual memory addresses in the process's address space with the corresponding data in the file or device. the kernel keeps track of this mapping, allowing the process to access the data through the assigned virtual memory addresses.
by default, modifications to mapped regions are not persisted to long-term storage. the kernel maintains a concept called dirty pages to track the modified pages within mapped regions. these pages contain data that has been modified in memory but not yet saved back to the file or device.
to ensure data persistence, the kernel provides mechanisms such as:
-
a. synchronization: the kernel employs various techniques, such as copy-on-write (COW), to manage modifications within mapped regions. when a page within a mapped region is modified, the kernel marks it as dirty. the data may reside in the process's memory or the kernel's page cache. the kernel tracks the modifications and ensures that the changes are eventually saved back to the file or device.
-
b. msync(): you can explicitly use the msync() system call to synchronize the mapped region with the underlying storage. this call allows you to specify specific ranges of memory to sync or sync the entire mapping. it ensures that any modifications made to the mapped region are saved to the file or device.
-
c. remapping and reestablishing the mapping: if necessary, you can manually reestablish the mapping after a reboot or system restart. this involves reopening the file or device, seeking to the appropriate position, and invoking mmap again with the required parameters. this way, the mapped region is re-associated with the corresponding data in the file or device