code:
.. SPDX-License-Identifier: GPL-2.0

Idmappings
==========

Most filesystem developers will have encountered idmappings. They are used when
reading from or writing ownership to disk, reporting ownership to userspace, or
for permission checking. This document is aimed at filesystem developers that
want to know how idmappings work.

Formal notes
------------

An idmapping is essentially a translation of a range of ids into another or the
same range of ids. The notational convention for idmappings that is widely used
in userspace is::

 u:k:r

``u`` indicates the first element in the upper idmapset ``U`` and ``k``
indicates the first element in the lower idmapset ``K``. The ``r`` parameter
indicates the range of the idmapping, i.e. how many ids are mapped. From now
on, we will always prefix ids with ``u`` or ``k`` to make it clear whether
we're talking about an id in the upper or lower idmapset.

To see what this looks like in practice, let's take the following idmapping::

 u22:k10000:r3

and write down the mappings it will generate::

 u22 -> k10000
 u23 -> k10001
 u24 -> k10002

From a mathematical viewpoint ``U`` and ``K`` are well-ordered sets and an
idmapping is an order isomorphism from ``U`` into ``K``. So ``U`` and ``K`` are
order isomorphic. In fact, ``U`` and ``K`` are always well-ordered subsets of
the set of all possible ids useable on a given system.

Looking at this mathematically briefly will help us highlight some properties
that make it easier to understand how we can translate between idmappings. For
example, we know that the inverse idmapping is an order isomorphism as well::

 k10000 -> u22
 k10001 -> u23
 k10002 -> u24

Given that we are dealing with order isomorphisms plus the fact that we're
dealing with subsets we can embedd idmappings into each other, i.e. we can
sensibly translate between different idmappings. For example, assume we've been
given the three idmappings::

 1. u0:k10000:r10000
 2. u0:k20000:r10000
 3. u0:k30000:r10000

and id ``k11000`` which has been generated by the first idmapping by mapping
``u1000`` from the upper idmapset down to ``k11000`` in the lower idmapset.

Because we're dealing with order isomorphic subsets it is meaningful to ask
what id ``k11000`` corresponds to in the second or third idmapping. The
straightfoward algorithm to use is to apply the inverse of the first idmapping,
mapping ``k11000`` up to ``u1000``. Afterwards, we can map ``u1000`` down using
either the second idmapping mapping or third idmapping mapping. The second
idmapping would map ``u1000`` down to ``21000``. The third idmapping would map
``u1000`` down to ``u31000``.

If we were given the same task for the following three idmappings::

 1. u0:k10000:r10000
 2. u0:k20000:r200
 3. u0:k30000:r300

we would fail to translate as the sets aren't order isomorphic over the full
range of the first idmapping anymore (However they are order isomorphic over
the full range of the second idmapping.). Neither the second or third idmapping
contain ``u1000`` in the upper idmapset ``U``. This is equivalent to not having
an id mapped. We can simply say that ``u1000`` is unmapped in the second and
third idmapping. The kernel will report unmapped ids as the overflowuid
``(uid_t)-1`` or overflowgid ``(gid_t)-1`` to userspace.

The algorithm to calculate what a given id maps to is pretty simple. First, we
need to verify that the range can contain our target id. We will skip this step
for simplicity. After that if we want to know what ``id`` maps to we can do
simple calculations:

- If we want to map from left to right::

   u:k:r
   id - u + k = n

- If we want to map from right to left::

   u:k:r
   id - k + u = n

Instead of "left to right" we can also say "down" and instead of "right to
left" we can also say "up". Obviously mapping down and up invert each other.

To see whether the simple formulas above work, consider the following two
idmappings::

 1. u0:k20000:r10000
 2. u500:k30000:r10000

Assume we are given ``k21000`` in the lower idmapset of the first idmapping. We
want to know what id this was mapped from in the upper idmapset of the first
idmapping. So we're mapping up in the first idmapping::

 id     - k      + u  = n
 k21000 - k20000 + u0 = u1000

Now assume we are given the id ``u1100`` in the upper idmapset of the second
idmapping and we want to know what this id maps down to in the lower idmapset
of the second idmapping. This means we're mapping down in the second
idmapping::

 id    - u    + k      = n
 u1100 - u500 + k30000 = k30600

General notes
-------------

In the context of the kernel an idmapping can be interpreted as mapping a range
of userspace ids into a range of kernel ids::

 userspace-id:kernel-id:range

A userspace id is always an element in the upper idmapset of an idmapping of
type ``uid_t`` or ``gid_t`` and a kernel id is always an element in the lower
idmapset of an idmapping of type ``kuid_t`` or ``kgid_t``. From now on
"userspace id" will be used to refer to the well known ``uid_t`` and ``gid_t``
types and "kernel id" will be used to refer to ``kuid_t`` and ``kgid_t``.

The kernel is mostly concerned with kernel ids. They are used when performing
permission checks and are stored in an inode's ``i_uid`` and ``i_gid`` field.
A userspace id on the other hand is an id that is reported to userspace by the
kernel, or is passed by userspace to the kernel, or a raw device id that is
written or read from disk.

Note that we are only concerned with idmappings as the kernel stores them not
how userspace would specify them.

For the rest of this document we will prefix all userspace ids with ``u`` and
all kernel ids with ``k``. Ranges of idmappings will be prefixed with ``r``. So
an idmapping will be written as ``u0:k10000:r10000``.

For example, the id ``u1000`` is an id in the upper idmapset or "userspace
idmapset" starting with ``u1000``. And it is mapped to ``k11000`` which is a
kernel id in the lower idmapset or "kernel idmapset" starting with ``k10000``.

A kernel id is always created by an idmapping. Such idmappings are associated
with user namespaces. Since we mainly care about how idmappings work we're not
going to be concerned with how idmappings are created nor how they are used
outside of the filesystem context. This is best left to an explanation of user
namespaces.

The initial user namespace is special. It always has an idmapping of the
following form::

 u0:k0:r4294967295

which is an identity idmapping over the full range of ids available on this
system.

Other user namespaces usually have non-identity idmappings such as::

 u0:k10000:r10000

When a process creates or wants to change ownership of a file, or when the
ownership of a file is read from disk by a filesystem, the userspace id is
immediately translated into a kernel id according to the idmapping associated
with the relevant user namespace.

For instance, consider a file that is stored on disk by a filesystem as being
owned by ``u1000``:

- If a filesystem were to be mounted in the initial user namespaces (as most
  filesystems are) then the initial idmapping will be used. As we saw this is
  simply the identity idmapping. This would mean id ``u1000`` read from disk
  would be mapped to id ``k1000``. So an inode's ``i_uid`` and ``i_gid`` field
  would contain ``k1000``.

- If a filesystem were to be mounted with an idmapping of ``u0:k10000:r10000``
  then ``u1000`` read from disk would be mapped to ``k11000``. So an inode's
  ``i_uid`` and ``i_gid`` would contain ``k11000``.

Translation algorithms
----------------------

We've already seen briefly that it is possible to translate between different
idmappings. We'll now take a closer look how that works.

Crossmapping
~~~~~~~~~~~~

This translation algorithm is used by the kernel in quite a few places. For
example, it is used when reporting back the ownership of a file to userspace
via the ``stat()`` system call family.

If we've been given ``k11000`` from one idmapping we can map that id up in
another idmapping. In order for this to work both idmappings need to contain
the same kernel id in their kernel idmapsets. For example, consider the
following idmappings::

 1. u0:k10000:r10000
 2. u20000:k10000:r10000

and we are mapping ``u1000`` down to ``k11000`` in the first idmapping . We can
then translate ``k11000`` into a userspace id in the second idmapping using the
kernel idmapset of the second idmapping::

 /* Map the kernel id up into a userspace id in the second idmapping. */
 from_kuid(u20000:k10000:r10000, k11000) = u21000

Note, how we can get back to the kernel id in the first idmapping by inverting
the algorithm::

 /* Map the userspace id down into a kernel id in the second idmapping. */
 make_kuid(u20000:k10000:r10000, u21000) = k11000

 /* Map the kernel id up into a userspace id in the first idmapping. */
 from_kuid(u0:k10000:r10000, k11000) = u1000

This algorithm allows us to answer the question what userspace id a given
kernel id corresponds to in a given idmapping. In order to be able to answer
this question both idmappings need to contain the same kernel id in their
respective kernel idmapsets.

For example, when the kernel reads a raw userspace id from disk it maps it down
into a kernel id according to the idmapping associated with the filesystem.
Let's assume the filesystem was mounted with an idmapping of
``u0:k20000:r10000`` and it reads a file owned by ``u1000`` from disk. This
means ``u1000`` will be mapped to ``k21000`` which is what will be stored in
the inode's ``i_uid`` and ``i_gid`` field.

When someone in userspace calls ``stat()`` or a related function to get
ownership information about the file the kernel can't simply map the id back up
according to the filesystem's idmapping as this would give the wrong owner if
the caller is using an idmapping.

So the kernel will map the id back up in the idmapping of the caller. Let's
assume the caller has the slighly unconventional idmapping
``u3000:k20000:r10000`` then ``k21000`` would map back up to ``u4000``.
Consequently the user would see that this file is owned by ``u4000``.

Remapping
~~~~~~~~~

It is possible to translate a kernel id from one idmapping to another one via
the userspace idmapset of the two idmappings. This is equivalent to remapping
a kernel id.

Let's look at an example. We are given the following two idmappings::

 1. u0:k10000:r10000
 2. u0:k20000:r10000

and we are given ``k11000`` in the first idmapping. In order to translate this
kernel id in the first idmapping into a kernel id in the second idmapping we
need to perform two steps:

1. Map the kernel id up into a userspace id in the first idmapping::

    /* Map the kernel id up into a userspace id in the first idmapping. */
    from_kuid(u0:k10000:r10000, k11000) = u1000

2. Map the userspace id down into a kernel id in the second idmapping::

    /* Map the userspace id down into a kernel id in the second idmapping. */
    make_kuid(u0:k20000:r10000, u1000) = k21000

As you can see we used the userspace idmapset in both idmappings to translate
the kernel id in one idmapping to a kernel id in another idmapping.

This allows us to answer the question what kernel id we would need to use to
get the same userspace id in another idmapping. In order to be able to answer
this question both idmappings need to contain the same userspace id in their
respective userspace idmapsets.

Note, how we can easily get back to the kernel id in the first idmapping by
inverting the algorithm:

1. Map the kernel id up into a userspace id in the second idmapping::

    /* Map the kernel id up into a userspace id in the second idmapping. */
    from_kuid(u0:k20000:r10000, k21000) = u1000

2. Map the userspace id down into a kernel id in the first idmapping::

    /* Map the userspace id down into a kernel id in the first idmapping. */
    make_kuid(u0:k10000:r10000, u1000) = k11000

Another way to look at this translation is to treat it as inverting one
idmapping and applying another idmapping if both idmappings have the relevant
userspace id mapped. This will come in handy when working with idmapped mounts.

Invalid translations
~~~~~~~~~~~~~~~~~~~~

It is never valid to use an id in the kernel idmapset of one idmapping as the
id in the userspace idmapset of another or the same idmapping. While the kernel
idmapset always indicates an idmapset in the kernel id space the userspace
idmapset indicates a userspace id. So the following translations are forbidden::

 /* Map the userspace id down into a kernel id in the first idmapping. */
 make_kuid(u0:k10000:r10000, u1000) = k11000

 /* INVALID: Map the kernel id down into a kernel id in the second idmapping. */
 make_kuid(u10000:k20000:r10000, k110000) = k21000
                                 ~~~~~~~

and equally wrong::

 /* Map the kernel id up into a userspace id in the first idmapping. */
 from_kuid(u0:k10000:r10000, k11000) = u1000

 /* INVALID: Map the userspace id up into a userspace id in the second idmapping. */
 from_kuid(u20000:k0:r10000, u1000) = k21000
                             ~~~~~

Idmappings when creating filesystem objects
-------------------------------------------

The concepts of mapping an id down or mapping an id up are expressed in the two
kernel functions filesystem developers are rather familiar with and which we've
already used in this document::

 /* Map the userspace id down into a kernel id. */
 make_kuid(idmapping, uid)

 /* Map the kernel id up into a userspace id. */
 from_kuid(idmapping, kuid)

We will take an abbreviated look into how idmappings figure into creating
filesystem objects. For simplicity we will only look at what happens when the
VFS has already completed path lookup right before it calls into the filesystem
itself. So we're concerned with what happens when e.g. ``vfs_mkdir()`` is
called. We will also assume that the directory we're creating filesystem
objects in is readable and writable for everyone.

When creating a filesystem object the caller will look at the caller's
filesystem ids. These are just regular ``uid_t`` and ``gid_t`` userspace ids
but they are exclusively used when determining file ownership which is why they
are called "filesystem ids". They are usually identical to the uid and gid of
the caller but can differ. We will just assume they are always identical to not
get lost in too many details.

When the caller enters the kernel two things happen:

1. Map the caller's userspace ids down into kernel ids in the caller's
   idmapping.
   (To be precise, the kernel will simply look at the kernel ids stashed in the
   credentials of the current task but for our education we'll pretend this
   translation happens just in time.)
2. Verify that the caller's kernel ids can be mapped up to userspace ids in the
   filesystem's idmapping.

The second step is important as regular filesystem will ultimately need to map
the kernel id back up into a userspace id when writing to disk.
So with the second step the kernel guarantees that a valid userspace id can be
written to disk. If it can't the kernel will refuse the creation request to not
even remotely risk filesystem corruption.

The astute reader will have realized that this is simply a varation of the
crossmapping algorithm we mentioned above in a previous section. First, the
kernel maps the caller's userspace id down into a kernel id according to the
caller's idmapping and then maps that kernel id up according to the
filesystem's idmapping.

Let's see some examples with caller/filesystem idmapping but without mount
idmappings. This will exhibit some problems we can hit. After that we will
revisit/reconsider these examples, this time using mount idmappings, to see how
they can solve the problems we observed before.

Example 1
~~~~~~~~~

::

 caller id:            u1000
 caller idmapping:     u0:k0:r4294967295
 filesystem idmapping: u0:k0:r4294967295

Both the caller and the filesystem use the identity idmapping:

1. Map the caller's userspace ids into kernel ids in the caller's idmapping::

    make_kuid(u0:k0:r4294967295, u1000) = k1000

2. Verify that the caller's kernel ids can be mapped to userspace ids in the
   filesystem's idmapping.

   For this second step the kernel will call the function
   ``fsuidgid_has_mapping()`` which ultimately boils down to calling
   ``from_kuid()``::

    from_kuid(u0:k0:r4294967295, k1000) = u1000

In this example both idmappings are the same so there's nothing exciting going
on. Ultimately the userspace id that lands on disk will be ``u1000``.

Example 2
~~~~~~~~~

::

 caller id:            u1000
 caller idmapping:     u0:k10000:r10000
 filesystem idmapping: u0:k20000:r10000

1. Map the caller's userspace ids down into kernel ids in the caller's
   idmapping::

    make_kuid(u0:k10000:r10000, u1000) = k11000

2. Verify that the caller's kernel ids can be mapped up to userspace ids in the
   filesystem's idmapping::

    from_kuid(u0:k20000:r10000, k11000) = u-1

It's immediately clear that while the caller's userspace id could be
successfully mapped down into kernel ids in the caller's idmapping the kernel
ids could not be mapped up according to the filesystem's idmapping. So the
kernel will deny this creation request.

Note that while this example is less common, because most filesystem can't be
mounted with non-initial idmappings this is a general problem as we can see in
the next examples.

Example 3
~~~~~~~~~

::

 caller id:            u1000
 caller idmapping:     u0:k10000:r10000
 filesystem idmapping: u0:k0:r4294967295

1. Map the caller's userspace ids down into kernel ids in the caller's
   idmapping::

    make_kuid(u0:k10000:r10000, u1000) = k11000

2. Verify that the caller's kernel ids can be mapped up to userspace ids in the
   filesystem's idmapping::

    from_kuid(u0:k0:r4294967295, k11000) = u11000

We can see that the translation always succeeds. The userspace id that the
filesystem will ultimately put to disk will always be identical to the value of
the kernel id that was created in the caller's idmapping. This has mainly two
consequences.

First, that we can't allow a caller to ultimately write to disk with another
userspace id. We could only do this if we were to mount the whole fileystem
with the caller's or another idmapping. But that solution is limited to a few
filesystems and not very flexible. But this is a use-case that is pretty
important in containerized workloads.

Second, the caller will usually not be able to create any files or access
directories that have stricter permissions because none of the filesystem's
kernel ids map up into valid userspace ids in the caller's idmapping

1. Map raw userspace ids down to kernel ids in the filesystem's idmapping::

    make_kuid(u0:k0:r4294967295, u1000) = k1000

2. Map kernel ids up to userspace ids in the caller's idmapping::

    from_kuid(u0:k10000:r10000, k1000) = u-1

Example 4
~~~~~~~~~

::

 file id:              u1000
 caller idmapping:     u0:k10000:r10000
 filesystem idmapping: u0:k0:r4294967295

In order to report ownership to userspace the kernel uses the crossmapping
algorithm introduced in a previous section:

1. Map the userspace id on disk down into a kernel id in the filesystem's
   idmapping::

    make_kuid(u0:k0:r4294967295, u1000) = k1000

2. Map the kernel id up into a userspace id in the caller's idmapping::

    from_kuid(u0:k10000:r10000, k1000) = u-1

The crossmapping algorithm fails in this case because the kernel id in the
filesystem idmapping cannot be mapped up to a userspace id in the caller's
idmapping. Thus, the kernel will report the ownership of this file as the
overflowid.

Example 5
~~~~~~~~~

::

 file id:              u1000
 caller idmapping:     u0:k10000:r10000
 filesystem idmapping: u0:k20000:r10000

In order to report ownership to userspace the kernel uses the crossmapping
algorithm introduced in a previous section:

1. Map the userspace id on disk down into a kernel id in the filesystem's
   idmapping::

    make_kuid(u0:k20000:r10000, u1000) = k21000

2. Map the kernel id up into a userspace id in the caller's idmapping::

    from_kuid(u0:k10000:r10000, k21000) = u-1

Again, the crossmapping algorithm fails in this case because the kernel id in
the filesystem idmapping cannot be mapped to a userspace id in the caller's
idmapping. Thus, the kernel will report the ownership of this file as the
overflowid.

Note how in the last two examples things would be simple if the caller would be
using the initial idmapping. For a filesystem mounted with the initial
idmapping it would be trivial. So we only consider a filesystem with an
idmapping of ``u0:k20000:r10000``:

1. Map the userspace id on disk down into a kernel id in the filesystem's
   idmapping::

    make_kuid(u0:k20000:r10000, u1000) = k21000

2. Map the kernel id up into a userspace id in the caller's idmapping::

    from_kuid(u0:k0:r4294967295, k21000) = u21000

Idmappings on idmapped mounts
-----------------------------

The examples we've seen in the previous section where the caller's idmapping
and the filesystem's idmapping are incompatible causes various issues for
workloads. For a more complex but common example, consider two containers
started on the host. To completely prevent the two containers from affecting
each other, an administrator may often use different non-overlapping idmappings
for the two containers::

 container1 idmapping:  u0:k10000:r10000
 container2 idmapping:  u0:k20000:r10000
 filesystem idmapping:  u0:k30000:r10000

An administrator wanting to provide easy read-write access to the following set
of files::

 dir id:       u0
 dir/file1 id: u1000
 dir/file2 id: u2000

to both containers currently can't.

Of course the administrator has the option to recursively change ownership via
``chown()``. For example, they could change ownership so that ``dir`` and all
files below it can be crossmapped from the filesystem's into the container's
idmapping. Let's assume they change ownership so it is compatible with the
first container's idmapping::

 dir id:       u10000
 dir/file1 id: u11000
 dir/file2 id: u12000

This would still leave ``dir`` rather useless to the second container. In fact,
``dir`` and all files below it would continue to appear owned by the overflowid
for the second container.

Or consider another increasingly popular example. Some service managers such as
systemd implement a concept called "portable home directories". A user may want
to use their home directories on different machines where they are assigned
different login userspace ids. Most users will have ``u1000`` as the login id
on their machine at home and all files in their home directory will usually be
owned by ``u1000``. At uni or at work they may have another login id such as
``u1125``. This makes it rather difficult to interact with their home directory
on their work machine.

In both cases changing ownership recursively has grave implications. The most
obvious one is that ownership is changed globally and permanently. In the home
directory case this change in ownership would even need to happen everytime the
user switches from their home to their work machine. For really large sets of
files this becomes increasingly costly.

If the user is lucky, they are dealing with a filesystem that is mountable
inside user namespaces. But this would also change ownership globally and the
change in ownership is tied to the lifetime of the filesystem mount, i.e. the
superblock. The only way to change ownership is to completely unmount the
filesystem and mount it again in another user namespace. This is usually
impossible because it would mean that all users currently accessing the
filesystem can't anymore. And it means that ``dir`` still can't be shared
between two containers with different idmappings.
But usually the user doesn't even have this option since most filesystems
aren't mountable inside containers. And not having them mountable might be
desirable as it doesn't require the filesystem to deal with malicious
filesystem images.

But the usecases mentioned above and more can be handled by idmapped mounts.
They allow to expose the same set of dentries with different ownership at
different mounts. This is achieved by marking the mounts with a user namespace
through the ``mount_setattr()`` system call. The idmapping associated with it
is then used to translate from the caller's idmapping to the filesystem's
idmapping and vica versa using the remapping algorithm we introduced above.

Idmapped mounts make it possible to change ownership in a temporary and
localized way. The ownership changes are restricted to a specific mount and the
ownership changes are tied to the lifetime of the mount. All other users and
locations where the filesystem is exposed are unaffected.

Filesystems that support idmapped mounts don't have any real reason to support
being mountable inside user namespaces. A filesystem could be exposed
completely under an idmapped mount to get the same effect. This has the
advantage that filesystems can leave the creation of the superblock to
privileged users in the initial user namespace.

However, it is perfectly possible to combine idmapped mounts with filesystems
mountable inside user namespaces. We will touch on this further below.

Remapping helpers
~~~~~~~~~~~~~~~~~

Idmapping functions were added that translate between idmappings. They make use
of the remapping algorithm we've introduced earlier. We're going to look at
two:

- ``i_uid_into_mnt()`` and ``i_gid_into_mnt()``

  The ``i_*id_into_mnt()`` functions translate filesystem's kernel ids into
  kernel ids in the mount's idmapping::

   /* Map the filesystem's kernel id up into a userspace id in the filesystem's idmapping. */
   from_kuid(filesystem, kid) = uid

   /* Map the filesystem's userspace id down ito a kernel id in the mount's idmapping. */
   make_kuid(mount, uid) = kuid

- ``mapped_fsuid()`` and ``mapped_fsgid()``

  The ``mapped_fs*id()`` functions translate the caller's kernel ids into
  kernel ids in the filesystem's idmapping. This translation is achieved by
  remapping the caller's kernel ids using the mount's idmapping::

   /* Map the caller's kernel id up into a userspace id in the mount's idmapping. */
   from_kuid(mount, kid) = uid

   /* Map the mount's userspace id down into a kernel id in the filesystem's idmapping. */
   make_kuid(filesystem, uid) = kuid

Note that these two functions invert each other. Consider the following
idmappings::

 caller idmapping:     u0:k10000:r10000
 filesystem idmapping: u0:k20000:r10000
 mount idmapping:      u0:k10000:r10000

Assume a file owned by ``u1000`` is read from disk. The filesystem maps this id
to ``k21000`` according to its idmapping. This is what is stored in the
inode's ``i_uid`` and ``i_gid`` fields.

When the caller queries the ownership of this file via ``stat()`` the kernel
would usually simply use the crossmapping algorithm and map the filesystem's
kernel id up to a userspace id in the caller's idmapping.

But when the caller is accessing the file on an idmapped mount the kernel will
first call ``i_uid_into_mnt()`` thereby translating the filesystem's kernel id
into a kernel id in the mount's idmapping::

 i_uid_into_mnt(k21000):
   /* Map the filesystem's kernel id up into a userspace id. */
   from_kuid(u0:k20000:r10000, k21000) = u1000

   /* Map the filesystem's userspace id down ito a kernel id in the mount's idmapping. */
   make_kuid(u0:k10000:r10000, u1000) = k11000

Finally, when the kernel reports the owner to the caller it will turn the
kernel id in the mount's idmapping into a userspace id in the caller's
idmapping::

  from_kuid(u0:k10000:r10000, k11000) = u1000

We can test whether this algorithm really works by verifying what happens when
we create a new file. Let's say the user is creating a file with ``u1000``.

The kernel maps this to ``k11000`` in the caller's idmapping. Usually the
kernel would now apply the crossmapping, verifying that ``k11000`` can be
mapped to a userspace id in the filesystem's idmapping. Since ``k11000`` can't
be mapped up in the filesystem's idmapping directly this creation request
fails.

But when the caller is accessing the file on an idmapped mount the kernel will
first call ``mapped_fs*id()`` thereby translating the caller's kernel id into
a kernel id according to the mount's idmapping::

 mapped_fsuid(k11000):
    /* Map the caller's kernel id up into a userspace id in the mount's idmapping. */
    from_kuid(u0:k10000:r10000, k11000) = u1000

    /* Map the mount's userspace id down into a kernel id in the filesystem's idmapping. */
    make_kuid(u0:k20000:r10000, u1000) = k21000

When finally writing to disk the kernel will then map ``k21000`` up into a
userspace id in the filesystem's idmapping::

   from_kuid(u0:k20000:r10000, k21000) = u1000

As we can see, we end up with an invertible and therefore information
preserving algorithm. A file created from ``u1000`` on an idmapped mount will
also be reported as being owned by ``u1000`` and vica versa.

Let's now briefly reconsider the failing examples from earlier in the context
of idmapped mounts.

Example 2 reconsidered
~~~~~~~~~~~~~~~~~~~~~~

::

 caller id:            u1000
 caller idmapping:     u0:k10000:r10000
 filesystem idmapping: u0:k20000:r10000
 mount idmapping:      u0:k10000:r10000

When the caller is using a non-initial idmapping the common case is to attach
the same idmapping to the mount. We now perform three steps:

1. Map the caller's userspace ids into kernel ids in the caller's idmapping::

    make_kuid(u0:k10000:r10000, u1000) = k11000

2. Translate the caller's kernel id into a kernel id in the filesystem's
   idmapping::

    mapped_fsuid(k11000):
      /* Map the kernel id up into a userspace id in the mount's idmapping. */
      from_kuid(u0:k10000:r10000, k11000) = u1000

      /* Map the userspace id down into a kernel id in the filesystem's idmapping. */
      make_kuid(u0:k20000:r10000, u1000) = k21000

2. Verify that the caller's kernel ids can be mapped to userspace ids in the
   filesystem's idmapping::

    from_kuid(u0:k20000:r10000, k21000) = u1000

So the ownership that lands on disk will be ``u1000``.

Example 3 reconsidered
~~~~~~~~~~~~~~~~~~~~~~

::

 caller id:            u1000
 caller idmapping:     u0:k10000:r10000
 filesystem idmapping: u0:k0:r4294967295
 mount idmapping:      u0:k10000:r10000

The same translation algorithm works with the third example.

1. Map the caller's userspace ids into kernel ids in the caller's idmapping::

    make_kuid(u0:k10000:r10000, u1000) = k11000

2. Translate the caller's kernel id into a kernel id in the filesystem's
   idmapping::

    mapped_fsuid(k11000):
       /* Map the kernel id up into a userspace id in the mount's idmapping. */
       from_kuid(u0:k10000:r10000, k11000) = u1000

       /* Map the userspace id down into a kernel id in the filesystem's idmapping. */
       make_kuid(u0:k0:r4294967295, u1000) = k1000

2. Verify that the caller's kernel ids can be mapped to userspace ids in the
   filesystem's idmapping::

    from_kuid(u0:k0:r4294967295, k21000) = u1000

So the ownership that lands on disk will be ``u1000``.

Example 4 reconsidered
~~~~~~~~~~~~~~~~~~~~~~

::

 file id:              u1000
 caller idmapping:     u0:k10000:r10000
 filesystem idmapping: u0:k0:r4294967295
 mount idmapping:      u0:k10000:r10000

In order to report ownership to userspace the kernel now does three steps using
the translation algorithm we introduced earlier:

1. Map the userspace id on disk down into a kernel id in the filesystem's
   idmapping::

    make_kuid(u0:k0:r4294967295, u1000) = k1000

2. Translate the kernel id into a kernel id in the mount's idmapping::

    i_uid_into_mnt(k1000):
      /* Map the kernel id up into a userspace id in the filesystem's idmapping. */
      from_kuid(u0:k0:r4294967295, k1000) = u1000

      /* Map the userspace id down into a kernel id in the mounts's idmapping. */
      make_kuid(u0:k10000:r10000, u1000) = k11000

3. Map the kernel id up into a userspace id in the caller's idmapping::

    from_kuid(u0:k10000:r10000, k11000) = u1000

Earlier, the caller's kernel id couldn't be crossmapped in the filesystems's
idmapping. With the idmapped mount in place it now can be crossmapped into the
filesystem's idmapping via the mount's idmapping. The file will now be created
with ``u1000`` according to the mount's idmapping.

Example 5 reconsidered
~~~~~~~~~~~~~~~~~~~~~~

::

 file id:              u1000
 caller idmapping:     u0:k10000:r10000
 filesystem idmapping: u0:k20000:r10000
 mount idmapping:      u0:k10000:r10000

Again, in order to report ownership to userspace the kernel now does three
steps using the translation algorithm we introduced earlier:

1. Map the userspace id on disk down into a kernel id in the filesystem's
   idmapping::

    make_kuid(u0:k20000:r10000, u1000) = k21000

2. Translate the kernel id into a kernel id in the mount's idmapping::

    i_uid_into_mnt(k21000):
      /* Map the kernel id up into a userspace id in the filesystem's idmapping. */
      from_kuid(u0:k20000:r10000, k21000) = u1000

      /* Map the userspace id down into a kernel id in the mounts's idmapping. */
      make_kuid(u0:k10000:r10000, u1000) = k11000

3. Map the kernel id up into a userspace id in the caller's idmapping::

    from_kuid(u0:k10000:r10000, k11000) = u1000

Earlier, the file's kernel id couldn't be crossmapped in the filesystems's
idmapping. With the idmapped mount in place it now can be crossmapped into the
filesystem's idmapping via the mount's idmapping. The file is now owned by
``u1000`` according to the mount's idmapping.

Changing ownership on a home directory
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~

We've seen above how idmapped mounts can be used to translate between
idmappings when either the caller, the filesystem or both uses a non-initial
idmapping. A wide range of usecases exist when the caller is using
a non-initial idmapping. This mostly happens in the context of containerized
workloads. The consequence is as we have seen that for both, filesystem's
mounted with the initial idmapping and filesystems mounted with non-initial
idmappings, access to the filesystem isn't working because the kernel ids can't
be crossmapped between the caller's and the filesystem's idmapping.

As we've seen above idmapped mounts provide a solution to this by remapping the
caller's or filesystem's idmapping according to the mount's idmapping.

Aside from containerized workloads, idmapped mounts have the advantage that
they also work when both the caller and the filesystem use the initial
idmapping which means users on the host can change the ownership of directories
and files on a per-mount basis.

Consider our previous example where a user has their home directory on portable
storage. At home they have id ``u1000`` and all files in their home directory
are owned by ``u1000`` whereas at uni or work they have login id ``u1125``.

Taking their home directory with them becomes problematic. They can't easily
access their files, they might not be able to write to disk without applying
lax permissions or ACLs and even if they can, they will end up with an annoying
mix of files and directories owned by ``u1000`` and ``u1125``.

Idmapped mounts allow to solve this problem. A user can create an idmapped
mount for their home directory on their work computer or their computer at home
depending on what ownership they would prefer to end up on the portable storage
itself.

Let's assume they want all files on disk to belong to ``u1000``. When the user
plugs in their portable storage at their work station they can setup a job that
creates an idmapped mount with the minimal idmapping ``u1000:k1125:r1``. So now
when they create a file the kernel performs the following steps we already know
from above:::

 caller id:            u1125
 caller idmapping:     u0:k0:r4294967295
 filesystem idmapping: u0:k0:r4294967295
 mount idmapping:      u1000:k1125:r1

1. Map the caller's userspace ids into kernel ids in the caller's idmapping::

    make_kuid(u0:k0:r4294967295, u1125) = k1125

2. Translate the caller's kernel id into a kernel id in the filesystem's
   idmapping::

    mapped_fsuid(k1125):
      /* Map the kernel id up into a userspace id in the mount's idmapping. */
      from_kuid(u1000:k1125:r1, k1125) = u1000

      /* Map the userspace id down into a kernel id in the filesystem's idmapping. */
      make_kuid(u0:k0:r4294967295, u1000) = k1000

2. Verify that the caller's kernel ids can be mapped to userspace ids in the
   filesystem's idmapping::

    from_kuid(u0:k0:r4294967295, k1000) = u1000

So ultimately the file will be created with ``u1000`` on disk.

Now let's briefly look at what ownership the caller with id ``u1125`` will see
on their work computer:

::

 file id:              u1000
 caller idmapping:     u0:k0:r4294967295
 filesystem idmapping: u0:k0:r4294967295
 mount idmapping:      u1000:k1125:r1

1. Map the userspace id on disk down into a kernel id in the filesystem's
   idmapping::

    make_kuid(u0:k0:r4294967295, u1000) = k1000

2. Translate the kernel id into a kernel id in the mount's idmapping::

    i_uid_into_mnt(k1000):
      /* Map the kernel id up into a userspace id in the filesystem's idmapping. */
      from_kuid(u0:k0:r4294967295, k1000) = u1000

      /* Map the userspace id down into a kernel id in the mounts's idmapping. */
      make_kuid(u1000:k1125:r1, u1000) = k1125

3. Map the kernel id up into a userspace id in the caller's idmapping::

    from_kuid(u0:k0:r4294967295, k1125) = u1125

So ultimately the caller will be reported that the file belongs to ``u1125``
which is the caller's userspace id on their workstation in our example.

The raw userspace id that is put on disk is ``u1000`` so when the user takes
their home directory back to their home computer where they are assigned
``u1000`` using the initial idmapping and mount the filesystem with the initial
idmapping they will see all those files owned by ``u1000``.


code:
.. _filesystems_index:

===============================
Filesystems in the Linux kernel
===============================

This under-development manual will, some glorious day, provide
comprehensive information on how the Linux virtual filesystem (VFS) layer
works, along with the filesystems that sit below it.  For now, what we have
can be found below.

Core VFS documentation
======================

See these manuals for documentation about the VFS layer itself and how its
algorithms work.

.. toctree::
   :maxdepth: 2

   vfs
   path-lookup
   api-summary
   splice
   locking
   directory-locking
   devpts
   dnotify
   fiemap
   files
   locks
   mount_api
   quota
   seq_file
   sharedsubtree
   idmappings

   automount-support

   caching/index

   porting

Filesystem support layers
=========================

Documentation for the support code within the filesystem layer for use in
filesystem implementations.

.. toctree::
   :maxdepth: 2

   journalling
   fscrypt
   fsverity
   netfs_library

Filesystems
===========

Documentation for filesystem implementations.

.. toctree::
   :maxdepth: 2

   9p
   adfs
   affs
   afs
   autofs
   autofs-mount-control
   befs
   bfs
   btrfs
   cifs/index
   ceph
   coda
   configfs
   cramfs
   dax
   debugfs
   dlmfs
   ecryptfs
   efivarfs
   erofs
   ext2
   ext3
   ext4/index
   f2fs
   gfs2
   gfs2-uevents
   gfs2-glocks
   hfs
   hfsplus
   hpfs
   fuse
   fuse-io
   inotify
   isofs
   nilfs2
   nfs/index
   ntfs
   ntfs3
   ocfs2
   ocfs2-online-filecheck
   omfs
   orangefs
   overlayfs
   proc
   qnx6
   ramfs-rootfs-initramfs
   relay
   romfs
   spufs/index
   squashfs
   sysfs
   sysv-fs
   tmpfs
   ubifs
   ubifs-authentication
   udf
   virtiofs
   vfat
   xfs-delayed-logging-design
   xfs-self-describing-metadata
   zonefs

repo_name: angery/linux


code:
.. SPDX-License-Identifier: GPL-2.0

===============================================================
Inotify - A Powerful yet Simple File Change Notification System
===============================================================

Document started 15 Mar 2005 by Robert Love <rml@novell.com>

Document updated 4 Jan 2015 by Zhang Zhen <zhenzhang.zhang@huawei.com>

	- Deleted obsoleted interface, just refer to manpages for user interface.

(i) Rationale

Q:
   What is the design decision behind not tying the watch to the open fd of
   the watched object?

A:
   Watches are associated with an open inotify device, not an open file.
   This solves the primary problem with dnotify: keeping the file open pins
   the file and thus, worse, pins the mount.  Dnotify is therefore infeasible
   for use on a desktop system with removable media as the media cannot be
   unmounted.  Watching a file should not require that it be open.

Q:
   What is the design decision behind using an-fd-per-instance as opposed to
   an fd-per-watch?

A:
   An fd-per-watch quickly consumes more file descriptors than are allowed,
   more fd's than are feasible to manage, and more fd's than are optimally
   select()-able.  Yes, root can bump the per-process fd limit and yes, users
   can use epoll, but requiring both is a silly and extraneous requirement.
   A watch consumes less memory than an open file, separating the number
   spaces is thus sensible.  The current design is what user-space developers
   want: Users initialize inotify, once, and add n watches, requiring but one
   fd and no twiddling with fd limits.  Initializing an inotify instance two
   thousand times is silly.  If we can implement user-space's preferences
   cleanly--and we can, the idr layer makes stuff like this trivial--then we
   should.

   There are other good arguments.  With a single fd, there is a single
   item to block on, which is mapped to a single queue of events.  The single
   fd returns all watch events and also any potential out-of-band data.  If
   every fd was a separate watch,

   - There would be no way to get event ordering.  Events on file foo and
     file bar would pop poll() on both fd's, but there would be no way to tell
     which happened first.  A single queue trivially gives you ordering.  Such
     ordering is crucial to existing applications such as Beagle.  Imagine
     "mv a b ; mv b a" events without ordering.

   - We'd have to maintain n fd's and n internal queues with state,
     versus just one.  It is a lot messier in the kernel.  A single, linear
     queue is the data structure that makes sense.

   - User-space developers prefer the current API.  The Beagle guys, for
     example, love it.  Trust me, I asked.  It is not a surprise: Who'd want
     to manage and block on 1000 fd's via select?

   - No way to get out of band data.

   - 1024 is still too low.  ;-)

   When you talk about designing a file change notification system that
   scales to 1000s of directories, juggling 1000s of fd's just does not seem
   the right interface.  It is too heavy.

   Additionally, it _is_ possible to  more than one instance  and
   juggle more than one queue and thus more than one associated fd.  There
   need not be a one-fd-per-process mapping; it is one-fd-per-queue and a
   process can easily want more than one queue.

Q:
   Why the system call approach?

A:
   The poor user-space interface is the second biggest problem with dnotify.
   Signals are a terrible, terrible interface for file notification.  Or for
   anything, for that matter.  The ideal solution, from all perspectives, is a
   file descriptor-based one that allows basic file I/O and poll/select.
   Obtaining the fd and managing the watches could have been done either via a
   device file or a family of new system calls.  We decided to implement a
   family of system calls because that is the preferred approach for new kernel
   interfaces.  The only real difference was whether we wanted to use open(2)
   and ioctl(2) or a couple of new system calls.  System calls beat ioctls.


code:
.. SPDX-License-Identifier: GPL-2.0

==================
ISO9660 Filesystem
==================

Mount options that are the same as for msdos and vfat partitions.

  =========	========================================================
  gid=nnn	All files in the partition will be in group nnn.
  uid=nnn	All files in the partition will be owned by user id nnn.
  umask=nnn	The permission mask (see umask(1)) for the partition.
  =========	========================================================

Mount options that are the same as vfat partitions. These are only useful
when using discs encoded using Microsoft's Joliet extensions.

 ==============	=============================================================
 iocharset=name Character set to use for converting from Unicode to
		ASCII.  Joliet filenames are stored in Unicode format, but
		Unix for the most part doesn't know how to deal with Unicode.
		There is also an option of doing UTF-8 translations with the
		utf8 option.
  utf8          Encode Unicode names in UTF-8 format. Default is no.
 ==============	=============================================================

Mount options unique to the isofs filesystem.

 ================= ============================================================
  block=512        Set the block size for the disk to 512 bytes
  block=1024       Set the block size for the disk to 1024 bytes
  block=2048       Set the block size for the disk to 2048 bytes
  check=relaxed    Matches filenames with different cases
  check=strict     Matches only filenames with the exact same case
  cruft            Try to handle badly formatted CDs.
  map=off          Do not map non-Rock Ridge filenames to lower case
  map=normal       Map non-Rock Ridge filenames to lower case
  map=acorn        As map=normal but also apply Acorn extensions if present
  mode=xxx         Sets the permissions on files to xxx unless Rock Ridge
		   extensions set the permissions otherwise
  dmode=xxx        Sets the permissions on directories to xxx unless Rock Ridge
		   extensions set the permissions otherwise
  overriderockperm Set permissions on files and directories according to
		   'mode' and 'dmode' even though Rock Ridge extensions are
		   present.
  nojoliet         Ignore Joliet extensions if they are present.
  norock           Ignore Rock Ridge extensions if they are present.
  hide		   Completely strip hidden files from the file system.
  showassoc	   Show files marked with the 'associated' bit
  unhide	   Deprecated; showing hidden files is now default;
		   If given, it is a synonym for 'showassoc' which will
		   recreate previous unhide behavior
  session=x        Select number of session on multisession CD
  sbsector=xxx     Session begins from sector xxx
 ================= ============================================================

Recommended documents about ISO 9660 standard are located at:

- http://www.y-adagio.com/
- ftp://ftp.ecma.ch/ecma-st/Ecma-119.pdf

Quoting from the PDF "This 2nd Edition of Standard ECMA-119 is technically
identical with ISO 9660.", so it is a valid and gratis substitute of the
official ISO specification.


code:
The Linux Journalling API
=========================

Overview
--------

Details
~~~~~~~

The journalling layer is easy to use. You need to first of all create a
journal_t data structure. There are two calls to do this dependent on
how you decide to allocate the physical media on which the journal
resides. The jbd2_journal_init_inode() call is for journals stored in
filesystem inodes, or the jbd2_journal_init_dev() call can be used
for journal stored on a raw device (in a continuous range of blocks). A
journal_t is a typedef for a struct pointer, so when you are finally
finished make sure you call jbd2_journal_destroy() on it to free up
any used kernel memory.

Once you have got your journal_t object you need to 'mount' or load the
journal file. The journalling layer expects the space for the journal
was already allocated and initialized properly by the userspace tools.
When loading the journal you must call jbd2_journal_load() to process
journal contents. If the client file system detects the journal contents
does not need to be processed (or even need not have valid contents), it
may call jbd2_journal_wipe() to clear the journal contents before
calling jbd2_journal_load().

Note that jbd2_journal_wipe(..,0) calls
jbd2_journal_skip_recovery() for you if it detects any outstanding
transactions in the journal and similarly jbd2_journal_load() will
call jbd2_journal_recover() if necessary. I would advise reading
ext4_load_journal() in fs/ext4/super.c for examples on this stage.

Now you can go ahead and start modifying the underlying filesystem.
Almost.

You still need to actually journal your filesystem changes, this is done
by wrapping them into transactions. Additionally you also need to wrap
the modification of each of the buffers with calls to the journal layer,
so it knows what the modifications you are actually making are. To do
this use jbd2_journal_start() which returns a transaction handle.

jbd2_journal_start() and its counterpart jbd2_journal_stop(),
which indicates the end of a transaction are nestable calls, so you can
reenter a transaction if necessary, but remember you must call
jbd2_journal_stop() the same number of times as
jbd2_journal_start() before the transaction is completed (or more
accurately leaves the update phase). Ext4/VFS makes use of this feature to
simplify handling of inode dirtying, quota support, etc.

Inside each transaction you need to wrap the modifications to the
individual buffers (blocks). Before you start to modify a buffer you
need to call jbd2_journal_get_create_access() /
jbd2_journal_get_write_access() /
jbd2_journal_get_undo_access() as appropriate, this allows the
journalling layer to copy the unmodified
data if it needs to. After all the buffer may be part of a previously
uncommitted transaction. At this point you are at last ready to modify a
buffer, and once you are have done so you need to call
jbd2_journal_dirty_metadata(). Or if you've asked for access to a
buffer you now know is now longer required to be pushed back on the
device you can call jbd2_journal_forget() in much the same way as you
might have used bforget() in the past.

A jbd2_journal_flush() may be called at any time to commit and
checkpoint all your transactions.

Then at umount time , in your put_super() you can then call
jbd2_journal_destroy() to clean up your in-core journal object.

Unfortunately there a couple of ways the journal layer can cause a
deadlock. The first thing to note is that each task can only have a
single outstanding transaction at any one time, remember nothing commits
until the outermost jbd2_journal_stop(). This means you must complete
the transaction at the end of each file/inode/address etc. operation you
perform, so that the journalling system isn't re-entered on another
journal. Since transactions can't be nested/batched across differing
journals, and another filesystem other than yours (say ext4) may be
modified in a later syscall.

The second case to bear in mind is that jbd2_journal_start() can block
if there isn't enough space in the journal for your transaction (based
on the passed nblocks param) - when it blocks it merely(!) needs to wait
for transactions to complete and be committed from other tasks, so
essentially we are waiting for jbd2_journal_stop(). So to avoid
deadlocks you must treat jbd2_journal_start() /
jbd2_journal_stop() as if they were semaphores and include them in
your semaphore ordering rules to prevent
deadlocks. Note that jbd2_journal_extend() has similar blocking
behaviour to jbd2_journal_start() so you can deadlock here just as
easily as on jbd2_journal_start().

Try to reserve the right number of blocks the first time. ;-). This will
be the maximum number of blocks you are going to touch in this
transaction. I advise having a look at at least ext4_jbd.h to see the
basis on which ext4 uses to make these decisions.

Another wriggle to watch out for is your on-disk block allocation
strategy. Why? Because, if you do a delete, you need to ensure you
haven't reused any of the freed blocks until the transaction freeing
these blocks commits. If you reused these blocks and crash happens,
there is no way to restore the contents of the reallocated blocks at the
end of the last fully committed transaction. One simple way of doing
this is to mark blocks as free in internal in-memory block allocation
structures only after the transaction freeing them commits. Ext4 uses
journal commit callback for this purpose.

With journal commit callbacks you can ask the journalling layer to call
a callback function when the transaction is finally committed to disk,
so that you can do some of your own management. You ask the journalling
layer for calling the callback by simply setting
``journal->j_commit_callback`` function pointer and that function is
called after each transaction commit. You can also use
``transaction->t_private_list`` for attaching entries to a transaction
that need processing when the transaction commits.

JBD2 also provides a way to block all transaction updates via
jbd2_journal_lock_updates() /
jbd2_journal_unlock_updates(). Ext4 uses this when it wants a
window with a clean and stable fs for a moment. E.g.

::

        jbd2_journal_lock_updates() //stop new stuff happening..
        jbd2_journal_flush()        // checkpoint everything.
        ..do stuff on stable fs
        jbd2_journal_unlock_updates() // carry on with filesystem use.

The opportunities for abuse and DOS attacks with this should be obvious,
if you allow unprivileged userspace to trigger codepaths containing
these calls.

Fast commits
~~~~~~~~~~~~

JBD2 to also allows you to perform file-system specific delta commits known as
fast commits. In order to use fast commits, you will need to set following
callbacks that perform correspodning work:

`journal->j_fc_cleanup_cb`: Cleanup function called after every full commit and
fast commit.

`journal->j_fc_replay_cb`: Replay function called for replay of fast commit
blocks.

File system is free to perform fast commits as and when it wants as long as it
gets permission from JBD2 to do so by calling the function
:c:func:`jbd2_fc_begin_commit()`. Once a fast commit is done, the client
file  system should tell JBD2 about it by calling
:c:func:`jbd2_fc_end_commit()`. If file system wants JBD2 to perform a full
commit immediately after stopping the fast commit it can do so by calling
:c:func:`jbd2_fc_end_commit_fallback()`. This is useful if fast commit operation
fails for some reason and the only way to guarantee consistency is for JBD2 to
perform the full traditional commit.

JBD2 helper functions to manage fast commit buffers. File system can use
:c:func:`jbd2_fc_get_buf()` and :c:func:`jbd2_fc_wait_bufs()` to allocate
and wait on IO completion of fast commit buffers.

Currently, only Ext4 implements fast commits. For details of its implementation
of fast commits, please refer to the top level comments in
fs/ext4/fast_commit.c.

Summary
~~~~~~~

Using the journal is a matter of wrapping the different context changes,
being each mount, each modification (transaction) and each changed
buffer to tell the journalling layer about them.

Data Types
----------

The journalling layer uses typedefs to 'hide' the concrete definitions
of the structures used. As a client of the JBD2 layer you can just rely
on the using the pointer as a magic cookie of some sort. Obviously the
hiding is not enforced as this is 'C'.

Structures
~~~~~~~~~~

.. kernel-doc:: include/linux/jbd2.h
   :internal:

Functions
---------

The functions here are split into two groups those that affect a journal
as a whole, and those which are used to manage transactions

Journal Level
~~~~~~~~~~~~~

.. kernel-doc:: fs/jbd2/journal.c
   :export:

.. kernel-doc:: fs/jbd2/recovery.c
   :internal:

Transasction Level
~~~~~~~~~~~~~~~~~~

.. kernel-doc:: fs/jbd2/transaction.c

See also
--------

`Journaling the Linux ext2fs Filesystem, LinuxExpo 98, Stephen
Tweedie <http://kernel.org/pub/linux/kernel/people/sct/ext3/journal-design.ps.gz>`__

`Ext3 Journalling FileSystem, OLS 2000, Dr. Stephen
Tweedie <http://olstrans.sourceforge.net/release/OLS2000-ext3/OLS2000-ext3.html>`__


code:
=======
Locking
=======

The text below describes the locking rules for VFS-related methods.
It is (believed to be) up-to-date. *Please*, if you change anything in
prototypes or locking protocols - update this file. And update the relevant
instances in the tree, don't leave that to maintainers of filesystems/devices/
etc. At the very least, put the list of dubious cases in the end of this file.
Don't turn it into log - maintainers of out-of-the-tree code are supposed to
be able to use diff(1).

Thing currently missing here: socket operations. Alexey?

dentry_operations
=================

prototypes::

	int (*d_revalidate)(struct dentry *, unsigned int);
	int (*d_weak_revalidate)(struct dentry *, unsigned int);
	int (*d_hash)(const struct dentry *, struct qstr *);
	int (*d_compare)(const struct dentry *,
			unsigned int, const char *, const struct qstr *);
	int (*d_delete)(struct dentry *);
	int (*d_init)(struct dentry *);
	void (*d_release)(struct dentry *);
	void (*d_iput)(struct dentry *, struct inode *);
	char *(*d_dname)((struct dentry *dentry, char *buffer, int buflen);
	struct vfsmount *(*d_automount)(struct path *path);
	int (*d_manage)(const struct path *, bool);
	struct dentry *(*d_real)(struct dentry *, const struct inode *);

locking rules:

================== ===========	========	==============	========
ops		   rename_lock	->d_lock	may block	rcu-walk
================== ===========	========	==============	========
d_revalidate:	   no		no		yes (ref-walk)	maybe
d_weak_revalidate: no		no		yes	 	no
d_hash		   no		no		no		maybe
d_compare:	   yes		no		no		maybe
d_delete:	   no		yes		no		no
d_init:		   no		no		yes		no
d_release:	   no		no		yes		no
d_prune:           no		yes		no		no
d_iput:		   no		no		yes		no
d_dname:	   no		no		no		no
d_automount:	   no		no		yes		no
d_manage:	   no		no		yes (ref-walk)	maybe
d_real		   no		no		yes 		no
================== ===========	========	==============	========

inode_operations
================

prototypes::

	int (*create) (struct inode *,struct dentry *,umode_t, bool);
	struct dentry * (*lookup) (struct inode *,struct dentry *, unsigned int);
	int (*link) (struct dentry *,struct inode *,struct dentry *);
	int (*unlink) (struct inode *,struct dentry *);
	int (*symlink) (struct inode *,struct dentry *,const char *);
	int (*mkdir) (struct inode *,struct dentry *,umode_t);
	int (*rmdir) (struct inode *,struct dentry *);
	int (*mknod) (struct inode *,struct dentry *,umode_t,dev_t);
	int (*rename) (struct inode *, struct dentry *,
			struct inode *, struct dentry *, unsigned int);
	int (*readlink) (struct dentry *, char __user *,int);
	const char *(*get_link) (struct dentry *, struct inode *, struct delayed_call *);
	void (*truncate) (struct inode *);
	int (*permission) (struct inode *, int, unsigned int);
	struct posix_acl * (*get_inode_acl)(struct inode *, int, bool);
	int (*setattr) (struct dentry *, struct iattr *);
	int (*getattr) (const struct path *, struct kstat *, u32, unsigned int);
	ssize_t (*listxattr) (struct dentry *, char *, size_t);
	int (*fiemap)(struct inode *, struct fiemap_extent_info *, u64 start, u64 len);
	void (*update_time)(struct inode *, struct timespec *, int);
	int (*atomic_open)(struct inode *, struct dentry *,
				struct file *, unsigned open_flag,
				umode_t create_mode);
	int (*tmpfile) (struct user_namespace *, struct inode *,
			struct file *, umode_t);
	int (*fileattr_set)(struct user_namespace *mnt_userns,
			    struct dentry *dentry, struct fileattr *fa);
	int (*fileattr_get)(struct dentry *dentry, struct fileattr *fa);
	struct posix_acl * (*get_acl)(struct user_namespace *, struct dentry *, int);

locking rules:
	all may block

==============	=============================================
ops		i_rwsem(inode)
==============	=============================================
lookup:		shared
create:		exclusive
link:		exclusive (both)
mknod:		exclusive
symlink:	exclusive
mkdir:		exclusive
unlink:		exclusive (both)
rmdir:		exclusive (both)(see below)
rename:		exclusive (all)	(see below)
readlink:	no
get_link:	no
setattr:	exclusive
permission:	no (may not block if called in rcu-walk mode)
get_inode_acl:	no
get_acl:	no
getattr:	no
listxattr:	no
fiemap:		no
update_time:	no
atomic_open:	shared (exclusive if O_CREAT is set in open flags)
tmpfile:	no
fileattr_get:	no or exclusive
fileattr_set:	exclusive
==============	=============================================

	Additionally, ->rmdir(), ->unlink() and ->rename() have ->i_rwsem
	exclusive on victim.
	cross-directory ->rename() has (per-superblock) ->s_vfs_rename_sem.

See Documentation/filesystems/directory-locking.rst for more detailed discussion
of the locking scheme for directory operations.

xattr_handler operations
========================

prototypes::

	bool (*list)(struct dentry *dentry);
	int (*get)(const struct xattr_handler *handler, struct dentry *dentry,
		   struct inode *inode, const char *name, void *buffer,
		   size_t size);
	int (*set)(const struct xattr_handler *handler,
                   struct user_namespace *mnt_userns,
                   struct dentry *dentry, struct inode *inode, const char *name,
                   const void *buffer, size_t size, int flags);

locking rules:
	all may block

=====		==============
ops		i_rwsem(inode)
=====		==============
list:		no
get:		no
set:		exclusive
=====		==============

super_operations
================

prototypes::

	struct inode *(*alloc_inode)(struct super_block *sb);
	void (*free_inode)(struct inode *);
	void (*destroy_inode)(struct inode *);
	void (*dirty_inode) (struct inode *, int flags);
	int (*write_inode) (struct inode *, struct writeback_control *wbc);
	int (*drop_inode) (struct inode *);
	void (*evict_inode) (struct inode *);
	void (*put_super) (struct super_block *);
	int (*sync_fs)(struct super_block *sb, int wait);
	int (*freeze_fs) (struct super_block *);
	int (*unfreeze_fs) (struct super_block *);
	int (*statfs) (struct dentry *, struct kstatfs *);
	int (*remount_fs) (struct super_block *, int *, char *);
	void (*umount_begin) (struct super_block *);
	int (*show_options)(struct seq_file *, struct dentry *);
	ssize_t (*quota_read)(struct super_block *, int, char *, size_t, loff_t);
	ssize_t (*quota_write)(struct super_block *, int, const char *, size_t, loff_t);

locking rules:
	All may block [not true, see below]

======================	============	========================
ops			s_umount	note
======================	============	========================
alloc_inode:
free_inode:				called from RCU callback
destroy_inode:
dirty_inode:
write_inode:
drop_inode:				!!!inode->i_lock!!!
evict_inode:
put_super:		write
sync_fs:		read
freeze_fs:		write
unfreeze_fs:		write
statfs:			maybe(read)	(see below)
remount_fs:		write
umount_begin:		no
show_options:		no		(namespace_sem)
quota_read:		no		(see below)
quota_write:		no		(see below)
======================	============	========================

->statfs() has s_umount (shared) when called by ustat(2) (native or
compat), but that's an accident of bad API; s_umount is used to pin
the superblock down when we only have dev_t given us by userland to
identify the superblock.  Everything else (statfs(), fstatfs(), etc.)
doesn't hold it when calling ->statfs() - superblock is pinned down
by resolving the pathname passed to syscall.

->quota_read() and ->quota_write() functions are both guaranteed to
be the only ones operating on the quota file by the quota code (via
dqio_sem) (unless an admin really wants to screw up something and
writes to quota files with quotas on). For other details about locking
see also dquot_operations section.

file_system_type
================

prototypes::

	struct dentry *(*mount) (struct file_system_type *, int,
		       const char *, void *);
	void (*kill_sb) (struct super_block *);

locking rules:

=======		=========
ops		may block
=======		=========
mount		yes
kill_sb		yes
=======		=========

->mount() returns ERR_PTR or the root dentry; its superblock should be locked
on return.

->kill_sb() takes a write-locked superblock, does all shutdown work on it,
unlocks and drops the reference.

address_space_operations
========================
prototypes::

	int (*writepage)(struct page *page, struct writeback_control *wbc);
	int (*read_folio)(struct file *, struct folio *);
	int (*writepages)(struct address_space *, struct writeback_control *);
	bool (*dirty_folio)(struct address_space *, struct folio *folio);
	void (*readahead)(struct readahead_control *);
	int (*write_begin)(struct file *, struct address_space *mapping,
				loff_t pos, unsigned len,
				struct page **pagep, void **fsdata);
	int (*write_end)(struct file *, struct address_space *mapping,
				loff_t pos, unsigned len, unsigned copied,
				struct page *page, void *fsdata);
	sector_t (*bmap)(struct address_space *, sector_t);
	void (*invalidate_folio) (struct folio *, size_t start, size_t len);
	bool (*release_folio)(struct folio *, gfp_t);
	void (*free_folio)(struct folio *);
	int (*direct_IO)(struct kiocb *, struct iov_iter *iter);
	int (*migrate_folio)(struct address_space *, struct folio *dst,
			struct folio *src, enum migrate_mode);
	int (*launder_folio)(struct folio *);
	bool (*is_partially_uptodate)(struct folio *, size_t from, size_t count);
	int (*error_remove_page)(struct address_space *, struct page *);
	int (*swap_activate)(struct swap_info_struct *sis, struct file *f, sector_t *span)
	int (*swap_deactivate)(struct file *);
	int (*swap_rw)(struct kiocb *iocb, struct iov_iter *iter);

locking rules:
	All except dirty_folio and free_folio may block

======================	======================== =========	===============
ops			folio locked		 i_rwsem	invalidate_lock
======================	======================== =========	===============
writepage:		yes, unlocks (see below)
read_folio:		yes, unlocks				shared
writepages:
dirty_folio:		maybe
readahead:		yes, unlocks				shared
write_begin:		locks the page		 exclusive
write_end:		yes, unlocks		 exclusive
bmap:
invalidate_folio:	yes					exclusive
release_folio:		yes
free_folio:		yes
direct_IO:
migrate_folio:		yes (both)
launder_folio:		yes
is_partially_uptodate:	yes
error_remove_page:	yes
swap_activate:		no
swap_deactivate:	no
swap_rw:		yes, unlocks
======================	======================== =========	===============

->write_begin(), ->write_end() and ->read_folio() may be called from
the request handler (/dev/loop).

->read_folio() unlocks the folio, either synchronously or via I/O
completion.

->readahead() unlocks the folios that I/O is attempted on like ->read_folio().

->writepage() is used for two purposes: for "memory cleansing" and for
"sync".  These are quite different operations and the behaviour may differ
depending upon the mode.

If writepage is called for sync (wbc->sync_mode != WBC_SYNC_NONE) then
it *must* start I/O against the page, even if that would involve
blocking on in-progress I/O.

If writepage is called for memory cleansing (sync_mode ==
WBC_SYNC_NONE) then its role is to get as much writeout underway as
possible.  So writepage should try to avoid blocking against
currently-in-progress I/O.

If the filesystem is not called for "sync" and it determines that it
would need to block against in-progress I/O to be able to start new I/O
against the page the filesystem should redirty the page with
redirty_page_for_writepage(), then unlock the page and return zero.
This may also be done to avoid internal deadlocks, but rarely.

If the filesystem is called for sync then it must wait on any
in-progress I/O and then start new I/O.

The filesystem should unlock the page synchronously, before returning to the
caller, unless ->writepage() returns special WRITEPAGE_ACTIVATE
value. WRITEPAGE_ACTIVATE means that page cannot really be written out
currently, and VM should stop calling ->writepage() on this page for some
time. VM does this by moving page to the head of the active list, hence the
name.

Unless the filesystem is going to redirty_page_for_writepage(), unlock the page
and return zero, writepage *must* run set_page_writeback() against the page,
followed by unlocking it.  Once set_page_writeback() has been run against the
page, write I/O can be submitted and the write I/O completion handler must run
end_page_writeback() once the I/O is complete.  If no I/O is submitted, the
filesystem must run end_page_writeback() against the page before returning from
writepage.

That is: after 2.5.12, pages which are under writeout are *not* locked.  Note,
if the filesystem needs the page to be locked during writeout, that is ok, too,
the page is allowed to be unlocked at any point in time between the calls to
set_page_writeback() and end_page_writeback().

Note, failure to run either redirty_page_for_writepage() or the combination of
set_page_writeback()/end_page_writeback() on a page submitted to writepage
will leave the page itself marked clean but it will be tagged as dirty in the
radix tree.  This incoherency can lead to all sorts of hard-to-debug problems
in the filesystem like having dirty inodes at umount and losing written data.

->writepages() is used for periodic writeback and for syscall-initiated
sync operations.  The address_space should start I/O against at least
``*nr_to_write`` pages.  ``*nr_to_write`` must be decremented for each page
which is written.  The address_space implementation may write more (or less)
pages than ``*nr_to_write`` asks for, but it should try to be reasonably close.
If nr_to_write is NULL, all dirty pages must be written.

writepages should _only_ write pages which are present on
mapping->io_pages.

->dirty_folio() is called from various places in the kernel when
the target folio is marked as needing writeback.  The folio cannot be
truncated because either the caller holds the folio lock, or the caller
has found the folio while holding the page table lock which will block
truncation.

->bmap() is currently used by legacy ioctl() (FIBMAP) provided by some
filesystems and by the swapper. The latter will eventually go away.  Please,
keep it that way and don't breed new callers.

->invalidate_folio() is called when the filesystem must attempt to drop
some or all of the buffers from the page when it is being truncated. It
returns zero on success.  The filesystem must exclusively acquire
invalidate_lock before invalidating page cache in truncate / hole punch
path (and thus calling into ->invalidate_folio) to block races between page
cache invalidation and page cache filling functions (fault, read, ...).

->release_folio() is called when the kernel is about to try to drop the
buffers from the folio in preparation for freeing it.  It returns false to
indicate that the buffers are (or may be) freeable.  If ->release_folio is
NULL, the kernel assumes that the fs has no private interest in the buffers.

->free_folio() is called when the kernel has dropped the folio
from the page cache.

->launder_folio() may be called prior to releasing a folio if
it is still found to be dirty. It returns zero if the folio was successfully
cleaned, or an error value if not. Note that in order to prevent the folio
getting mapped back in and redirtied, it needs to be kept locked
across the entire operation.

->swap_activate() will be called to prepare the given file for swap.  It
should perform any validation and preparation necessary to ensure that
writes can be performed with minimal memory allocation.  It should call
add_swap_extent(), or the helper iomap_swapfile_activate(), and return
the number of extents added.  If IO should be submitted through
->swap_rw(), it should set SWP_FS_OPS, otherwise IO will be submitted
directly to the block device ``sis->bdev``.

->swap_deactivate() will be called in the sys_swapoff()
path after ->swap_activate() returned success.

->swap_rw will be called for swap IO if SWP_FS_OPS was set by ->swap_activate().

file_lock_operations
====================

prototypes::

	void (*fl_copy_lock)(struct file_lock *, struct file_lock *);
	void (*fl_release_private)(struct file_lock *);

locking rules:

===================	=============	=========
ops			inode->i_lock	may block
===================	=============	=========
fl_copy_lock:		yes		no
fl_release_private:	maybe		maybe[1]_
===================	=============	=========

.. [1]:
   ->fl_release_private for flock or POSIX locks is currently allowed
   to block. Leases however can still be freed while the i_lock is held and
   so fl_release_private called on a lease should not block.

lock_manager_operations
=======================

prototypes::

	void (*lm_notify)(struct file_lock *);  /* unblock callback */
	int (*lm_grant)(struct file_lock *, struct file_lock *, int);
	void (*lm_break)(struct file_lock *); /* break_lease callback */
	int (*lm_change)(struct file_lock **, int);
	bool (*lm_breaker_owns_lease)(struct file_lock *);
        bool (*lm_lock_expirable)(struct file_lock *);
        void (*lm_expire_lock)(void);

locking rules:

======================	=============	=================	=========
ops			   flc_lock  	blocked_lock_lock	may block
======================	=============	=================	=========
lm_notify:		no      	yes			no
lm_grant:		no		no			no
lm_break:		yes		no			no
lm_change		yes		no			no
lm_breaker_owns_lease:	yes     	no			no
lm_lock_expirable	yes		no			no
lm_expire_lock		no		no			yes
======================	=============	=================	=========

buffer_head
===========

prototypes::

	void (*b_end_io)(struct buffer_head *bh, int uptodate);

locking rules:

called from interrupts. In other words, extreme care is needed here.
bh is locked, but that's all warranties we have here. Currently only RAID1,
highmem, fs/buffer.c, and fs/ntfs/aops.c are providing these. Block devices
call this method upon the IO completion.

block_device_operations
=======================
prototypes::

	int (*open) (struct block_device *, fmode_t);
	int (*release) (struct gendisk *, fmode_t);
	int (*ioctl) (struct block_device *, fmode_t, unsigned, unsigned long);
	int (*compat_ioctl) (struct block_device *, fmode_t, unsigned, unsigned long);
	int (*direct_access) (struct block_device *, sector_t, void **,
				unsigned long *);
	void (*unlock_native_capacity) (struct gendisk *);
	int (*getgeo)(struct block_device *, struct hd_geometry *);
	void (*swap_slot_free_notify) (struct block_device *, unsigned long);

locking rules:

======================= ===================
ops			open_mutex
======================= ===================
open:			yes
release:		yes
ioctl:			no
compat_ioctl:		no
direct_access:		no
unlock_native_capacity:	no
getgeo:			no
swap_slot_free_notify:	no	(see below)
======================= ===================

swap_slot_free_notify is called with swap_lock and sometimes the page lock
held.

file_operations
===============

prototypes::

	loff_t (*llseek) (struct file *, loff_t, int);
	ssize_t (*read) (struct file *, char __user *, size_t, loff_t *);
	ssize_t (*write) (struct file *, const char __user *, size_t, loff_t *);
	ssize_t (*read_iter) (struct kiocb *, struct iov_iter *);
	ssize_t (*write_iter) (struct kiocb *, struct iov_iter *);
	int (*iopoll) (struct kiocb *kiocb, bool spin);
	int (*iterate) (struct file *, struct dir_context *);
	int (*iterate_shared) (struct file *, struct dir_context *);
	__poll_t (*poll) (struct file *, struct poll_table_struct *);
	long (*unlocked_ioctl) (struct file *, unsigned int, unsigned long);
	long (*compat_ioctl) (struct file *, unsigned int, unsigned long);
	int (*mmap) (struct file *, struct vm_area_struct *);
	int (*open) (struct inode *, struct file *);
	int (*flush) (struct file *);
	int (*release) (struct inode *, struct file *);
	int (*fsync) (struct file *, loff_t start, loff_t end, int datasync);
	int (*fasync) (int, struct file *, int);
	int (*lock) (struct file *, int, struct file_lock *);
	ssize_t (*sendpage) (struct file *, struct page *, int, size_t,
			loff_t *, int);
	unsigned long (*get_unmapped_area)(struct file *, unsigned long,
			unsigned long, unsigned long, unsigned long);
	int (*check_flags)(int);
	int (*flock) (struct file *, int, struct file_lock *);
	ssize_t (*splice_write)(struct pipe_inode_info *, struct file *, loff_t *,
			size_t, unsigned int);
	ssize_t (*splice_read)(struct file *, loff_t *, struct pipe_inode_info *,
			size_t, unsigned int);
	int (*setlease)(struct file *, long, struct file_lock **, void **);
	long (*fallocate)(struct file *, int, loff_t, loff_t);
	void (*show_fdinfo)(struct seq_file *m, struct file *f);
	unsigned (*mmap_capabilities)(struct file *);
	ssize_t (*copy_file_range)(struct file *, loff_t, struct file *,
			loff_t, size_t, unsigned int);
	loff_t (*remap_file_range)(struct file *file_in, loff_t pos_in,
			struct file *file_out, loff_t pos_out,
			loff_t len, unsigned int remap_flags);
	int (*fadvise)(struct file *, loff_t, loff_t, int);

locking rules:
	All may block.

->llseek() locking has moved from llseek to the individual llseek
implementations.  If your fs is not using generic_file_llseek, you
need to acquire and release the appropriate locks in your ->llseek().
For many filesystems, it is probably safe to acquire the inode
mutex or just to use i_size_read() instead.
Note: this does not protect the file->f_pos against concurrent modifications
since this is something the userspace has to take care about.

->iterate() is called with i_rwsem exclusive.

->iterate_shared() is called with i_rwsem at least shared.

->fasync() is responsible for maintaining the FASYNC bit in filp->f_flags.
Most instances call fasync_helper(), which does that maintenance, so it's
not normally something one needs to worry about.  Return values > 0 will be
mapped to zero in the VFS layer.

->readdir() and ->ioctl() on directories must be changed. Ideally we would
move ->readdir() to inode_operations and use a separate method for directory
->ioctl() or kill the latter completely. One of the problems is that for
anything that resembles union-mount we won't have a struct file for all
components. And there are other reasons why the current interface is a mess...

->read on directories probably must go away - we should just enforce -EISDIR
in sys_read() and friends.

->setlease operations should call generic_setlease() before or after setting
the lease within the individual filesystem to record the result of the
operation

->fallocate implementation must be really careful to maintain page cache
consistency when punching holes or performing other operations that invalidate
page cache contents. Usually the filesystem needs to call
truncate_inode_pages_range() to invalidate relevant range of the page cache.
However the filesystem usually also needs to update its internal (and on disk)
view of file offset -> disk block mapping. Until this update is finished, the
filesystem needs to block page faults and reads from reloading now-stale page
cache contents from the disk. Since VFS acquires mapping->invalidate_lock in
shared mode when loading pages from disk (filemap_fault(), filemap_read(),
readahead paths), the fallocate implementation must take the invalidate_lock to
prevent reloading.

->copy_file_range and ->remap_file_range implementations need to serialize
against modifications of file data while the operation is running. For
blocking changes through write(2) and similar operations inode->i_rwsem can be
used. To block changes to file contents via a memory mapping during the
operation, the filesystem must take mapping->invalidate_lock to coordinate
with ->page_mkwrite.

dquot_operations
================

prototypes::

	int (*write_dquot) (struct dquot *);
	int (*acquire_dquot) (struct dquot *);
	int (*release_dquot) (struct dquot *);
	int (*mark_dirty) (struct dquot *);
	int (*write_info) (struct super_block *, int);

These operations are intended to be more or less wrapping functions that ensure
a proper locking wrt the filesystem and call the generic quota operations.

What filesystem should expect from the generic quota functions:

==============	============	=========================
ops		FS recursion	Held locks when called
==============	============	=========================
write_dquot:	yes		dqonoff_sem or dqptr_sem
acquire_dquot:	yes		dqonoff_sem or dqptr_sem
release_dquot:	yes		dqonoff_sem or dqptr_sem
mark_dirty:	no		-
write_info:	yes		dqonoff_sem
==============	============	=========================

FS recursion means calling ->quota_read() and ->quota_write() from superblock
operations.

More details about quota locking can be found in fs/dquot.c.

vm_operations_struct
====================

prototypes::

	void (*open)(struct vm_area_struct*);
	void (*close)(struct vm_area_struct*);
	vm_fault_t (*fault)(struct vm_area_struct*, struct vm_fault *);
	vm_fault_t (*page_mkwrite)(struct vm_area_struct *, struct vm_fault *);
	vm_fault_t (*pfn_mkwrite)(struct vm_area_struct *, struct vm_fault *);
	int (*access)(struct vm_area_struct *, unsigned long, void*, int, int);

locking rules:

=============	=========	===========================
ops		mmap_lock	PageLocked(page)
=============	=========	===========================
open:		yes
close:		yes
fault:		yes		can return with page locked
map_pages:	yes
page_mkwrite:	yes		can return with page locked
pfn_mkwrite:	yes
access:		yes
=============	=========	===========================

->fault() is called when a previously not present pte is about to be faulted
in. The filesystem must find and return the page associated with the passed in
"pgoff" in the vm_fault structure. If it is possible that the page may be
truncated and/or invalidated, then the filesystem must lock invalidate_lock,
then ensure the page is not already truncated (invalidate_lock will block
subsequent truncate), and then return with VM_FAULT_LOCKED, and the page
locked. The VM will unlock the page.

->map_pages() is called when VM asks to map easy accessible pages.
Filesystem should find and map pages associated with offsets from "start_pgoff"
till "end_pgoff". ->map_pages() is called with page table locked and must
not block.  If it's not possible to reach a page without blocking,
filesystem should skip it. Filesystem should use do_set_pte() to setup
page table entry. Pointer to entry associated with the page is passed in
"pte" field in vm_fault structure. Pointers to entries for other offsets
should be calculated relative to "pte".

->page_mkwrite() is called when a previously read-only pte is about to become
writeable. The filesystem again must ensure that there are no
truncate/invalidate races or races with operations such as ->remap_file_range
or ->copy_file_range, and then return with the page locked. Usually
mapping->invalidate_lock is suitable for proper serialization. If the page has
been truncated, the filesystem should not look up a new page like the ->fault()
handler, but simply return with VM_FAULT_NOPAGE, which will cause the VM to
retry the fault.

->pfn_mkwrite() is the same as page_mkwrite but when the pte is
VM_PFNMAP or VM_MIXEDMAP with a page-less entry. Expected return is
VM_FAULT_NOPAGE. Or one of the VM_FAULT_ERROR types. The default behavior
after this call is to make the pte read-write, unless pfn_mkwrite returns
an error.

->access() is called when get_user_pages() fails in
access_process_vm(), typically used to debug a process through
/proc/pid/mem or ptrace.  This function is needed only for
VM_IO | VM_PFNMAP VMAs.

--------------------------------------------------------------------------------

			Dubious stuff

(if you break something or notice that it is broken and do not fix it yourself
- at least put it here)


code:
.. SPDX-License-Identifier: GPL-2.0

==========================
File Locking Release Notes
==========================

		Andy Walker <andy@lysaker.kvaerner.no>

			    12 May 1997

1. What's New?
==============

1.1 Broken Flock Emulation
--------------------------

The old flock(2) emulation in the kernel was swapped for proper BSD
compatible flock(2) support in the 1.3.x series of kernels. With the
release of the 2.1.x kernel series, support for the old emulation has
been totally removed, so that we don't need to carry this baggage
forever.

This should not cause problems for anybody, since everybody using a
2.1.x kernel should have updated their C library to a suitable version
anyway (see the file "Documentation/process/changes.rst".)

1.2 Allow Mixed Locks Again
---------------------------

1.2.1 Typical Problems - Sendmail
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
Because sendmail was unable to use the old flock() emulation, many sendmail
installations use fcntl() instead of flock(). This is true of Slackware 3.0
for example. This gave rise to some other subtle problems if sendmail was
configured to rebuild the alias file. Sendmail tried to lock the aliases.dir
file with fcntl() at the same time as the GDBM routines tried to lock this
file with flock(). With pre 1.3.96 kernels this could result in deadlocks that,
over time, or under a very heavy mail load, would eventually cause the kernel
to lock solid with deadlocked processes.

1.2.2 The Solution
^^^^^^^^^^^^^^^^^^
The solution I have chosen, after much experimentation and discussion,
is to make flock() and fcntl() locks oblivious to each other. Both can
exists, and neither will have any effect on the other.

I wanted the two lock styles to be cooperative, but there were so many
race and deadlock conditions that the current solution was the only
practical one. It puts us in the same position as, for example, SunOS
4.1.x and several other commercial Unices. The only OS's that support
cooperative flock()/fcntl() are those that emulate flock() using
fcntl(), with all the problems that implies.

1.3 Mandatory Locking As A Mount Option
---------------------------------------

Mandatory locking was prior to this release a general configuration option
that was valid for all mounted filesystems.  This had a number of inherent
dangers, not the least of which was the ability to freeze an NFS server by
asking it to read a file for which a mandatory lock existed.

Such option was dropped in Kernel v5.14.