Bind mounting source to itself

bind-mountfilesystemsmount

What does mount --bind /dir1 /dir1 do? I've read https://www.kernel.org/doc/Documentation/filesystems/sharedsubtree.txt however it doesn't give a clear explanation. Looks like it is valid not only for directories, but also for files.

Best Answer

This works exactly the same as the general case mount --bind /dir1 /dir2. All you need to know about the special case is that it is well defined and does not recurse infinitely.

(For example, files can be self-bind mounted because files can be bind-mounted).

The special case is less pointless than it first sounds, for two reasons.

1. You can set bind mount options, e.g. to limit possible operations

After this call the same contents are accessible in two places. One can also remount a single file (on a single file). It's also possible to use the bind mount to create a mountpoint from a regular directory, for example:

      mount --bind foo foo

The bind mount call attaches only (part of) a single filesystem, not possible submounts. The entire file hierarchy including submounts is attached a second place by using:

      mount --rbind olddir newdir

Note that the filesystem mount options will remain the same as those on the original mount point.

mount(8) since v2.27 allows to change the mount options by passing the relevant options along with --bind. For example:

      mount -o bind,ro foo foo

This feature is not supported by the Linux kernel; it is implemented in userspace by an additional mount(2) remounting system call. This solution is not atomic.

The alternative (classic) way to create a read-only bind mount is to use the remount operation, for example:

      mount --bind olddir newdir
      mount -o remount,bind,ro olddir newdir

Note that a read-only bind will create a read-only mountpoint (VFS entry), but the original filesystem superblock will still be writable, meaning that the olddir will be writable, but the newdir will be read-only.

It's also possible to change nosuid, nodev, noexec, noatime, nodiratime and relatime VFS entry flags by "remount,bind" operation. It's impossible to change mount options recursively (for example with -o rbind,ro).

Another use of mount options is to set the "propagation flags". These are specifically what sharedsubtree.txt explains. They can definitely be confusing. They're also outlined in man mount.

I only have one tip to offer: The doc claims shared subtrees were needed in order to propagate mounts of removable devices into a "slave" mount namespace. However a more critical motivation is to be able to unmount your removable device, after you've started a sandboxed process in a "slave" mount namespace.

2. It creates a boundary that files cannot be moved or linked across

Apparently this is desired partly in order to avoid bypassing the limitations imposed above, and partly because hardlinks can be really horrible for security and it could be useful to restrict them a bit.