7

To remount a mounted filesystem to read-only, I can use following command:

mount -o remount,ro /foo

This is used for example in the shutdown sequence, where root filesystem (/) is remounted read-only, right before halt/reboot is called.

What does actually remounting to read-only do? Does it change some "flag" in the kernel, so that writes are denied?

How difficult would it be to write own program which does nothing else but remount a given filesystem to read-only ?

11

Mounting or remounting a filesystem is done using the mount(2) syscall. When remounting, this takes the target location (the mountpoint), the flags to be used in the mount operation, and any extra data used for the specific filesystem involved. When remounting read-only, the flags used are MS_RDONLY and MS_REMOUNT; you're also supposed to provide any other flags which were used when the filesystem was first mounted.

Remounting a filesystem read-only does indeed set a flag in the kernel's filesystem data structures, after performing some clean-up (basically finishing any outstanding writes). You can see how it's handled in the ext4 source code: if an ext4 filesystem is mounted read-write and then remounted read-only, the filesystem is synced, quotas are suspended, and s_flags in the superblock structure is updated to indicate the filesystem is read-only. This is then used throughout the kernel to deny writes; see for example sb_permission which prevents write access on a read-only filesystem.

If you want to do this yourself, you can try just calling mount() with the appropriate options as per the manpage linked above. For a complete solution I believe you'd need to determine the current mount flags and update them, but you could hard-code a simple program to match what your filesystems currently are mounted as...

  • do I have to do the syncing of the filesystem, suspending quota, and setting s_flags in the superblock structure myself in my simple program, or does the kernel do it for me once I call the mount() syscall ? – Martin Vegter Apr 11 '15 at 13:38
  • 1
    The kernel does it all for you, all you need to do is call mount(). – Stephen Kitt Apr 11 '15 at 13:50

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.