요약·해설과 원문, 전문 번역을 서로 분리했습니다. API 이름, symbol, source path는 원문 표기를 사용합니다.
1. 요약·해설
원문의 핵심 논리와 kernel programming 관점의 보충 설명입니다. 아래의 전문 번역과는 별도로 작성했습니다.
2. 영어 원문 전체
번역 기준이 된 Linux v6.18.37 원문입니다. 줄 번호는 이 버전의 파일 좌표입니다.
원문 전체 펼치기
=======
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 inode *, const struct qstr *,
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 *, enum d_real_type type);
bool (*d_unalias_trylock)(const struct dentry *);
void (*d_unalias_unlock)(const struct dentry *);
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
d_unalias_trylock yes no no no
d_unalias_unlock yes no no no
================== =========== ======== ============== ========
inode_operations
================
prototypes::
int (*create) (struct mnt_idmap *, 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 mnt_idmap *, struct inode *,struct dentry *,const char *);
struct dentry *(*mkdir) (struct mnt_idmap *, struct inode *,struct dentry *,umode_t);
int (*rmdir) (struct inode *,struct dentry *);
int (*mknod) (struct mnt_idmap *, struct inode *,struct dentry *,umode_t,dev_t);
int (*rename) (struct mnt_idmap *, 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 mnt_idmap *, struct inode *, int, unsigned int);
struct posix_acl * (*get_inode_acl)(struct inode *, int, bool);
int (*setattr) (struct mnt_idmap *, struct dentry *, struct iattr *);
int (*getattr) (struct mnt_idmap *, 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 mnt_idmap *, struct inode *,
struct file *, umode_t);
int (*fileattr_set)(struct mnt_idmap *idmap,
struct dentry *dentry, struct file_kattr *fa);
int (*fileattr_get)(struct dentry *dentry, struct file_kattr *fa);
struct posix_acl * (*get_acl)(struct mnt_idmap *, struct dentry *, int);
struct offset_ctx *(*get_offset_ctx)(struct inode *inode);
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 (both parents, some children) (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
get_offset_ctx no
============== ==================================================
Additionally, ->rmdir(), ->unlink() and ->rename() have ->i_rwsem
exclusive on victim.
cross-directory ->rename() has (per-superblock) ->s_vfs_rename_sem.
->unlink() and ->rename() have ->i_rwsem exclusive on all non-directories
involved.
->rename() has ->i_rwsem exclusive on any subdirectory that changes parent.
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 mnt_idmap *idmap,
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 (*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)(const struct kiocb *, struct address_space *mapping,
loff_t pos, unsigned len,
struct folio **foliop, void **fsdata);
int (*write_end)(const struct kiocb *, struct address_space *mapping,
loff_t pos, unsigned len, unsigned copied,
struct folio *folio, 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_folio)(struct address_space *, struct folio *);
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
====================== ======================== ========= ===============
read_folio: yes, unlocks shared
writepages:
dirty_folio: maybe
readahead: yes, unlocks shared
write_begin: locks the folio 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_folio: 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().
->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 in
mapping->i_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 MM wants to make a change to the
folio that would invalidate the filesystem's private data. For example,
it may be about to be removed from the address_space or split. The folio
is locked and not under writeback. It may be dirty. The gfp parameter
is not usually used for allocation, but rather to indicate what the
filesystem may do to attempt to free the private data. The filesystem may
return false to indicate that the folio's private data cannot be freed.
If it returns true, it should have already removed the private data from
the folio. If a filesystem does not provide a ->release_folio method,
the pagecache will assume that private data is buffer_heads and call
try_to_free_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 gendisk *, 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_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 *);
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_shared() is called with i_rwsem held for reading, and with the
file f_pos_lock held exclusively
->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_fault *);
vm_fault_t (*huge_fault)(struct vm_fault *, unsigned int order);
vm_fault_t (*map_pages)(struct vm_fault *, pgoff_t start, pgoff_t end);
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: write
close: read/write
fault: read can return with page locked
huge_fault: maybe-read
map_pages: maybe-read
page_mkwrite: read can return with page locked
pfn_mkwrite: read
access: read
============= ========== ===========================
->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.
->huge_fault() is called when there is no PUD or PMD entry present. This
gives the filesystem the opportunity to install a PUD or PMD sized page.
Filesystems can also use the ->fault method to return a PMD sized page,
so implementing this function may not be necessary. In particular,
filesystems should not call filemap_fault() from ->huge_fault().
The mmap_lock may not be held when this method is called.
->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 the RCU lock held and must
not block. If it's not possible to reach a page without blocking,
filesystem should skip it. Filesystem should use set_pte_range() 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)
3. 한국어 전문 번역
영어 원문의 문단 순서와 의미를 유지한 전체 번역입니다. 코드, 함수명, symbol과 URL은 원문 표기를 유지합니다.
문서 범위와 dentry_operations
1-59이 문서는 VFS 관련 method의 locking rule을 설명하며 현재 상태를 반영한다고 여겨집니다. Prototype이나 locking protocol을 바꾸면 이 문서와 tree 안의 관련 구현도 함께 갱신해야 하며, 파일시스템·장치 관리자에게 수정을 떠넘겨서는 안 됩니다. 적어도 의심스러운 사례 목록은 문서 끝에 기록해야 합니다. Out-of-tree 코드 관리자가 `diff(1)`을 사용할 수 있어야 하므로 변경 로그처럼 만들지 말아야 합니다. 현재 빠진 항목은 socket operation입니다.
`dentry_operations` 표는 `rename_lock`, `->d_lock`, block 가능 여부, RCU walk 호출 가능성을 함께 표시합니다. `d_revalidate`는 두 lock 없이 ref-walk에서 block할 수 있고 RCU walk에서도 호출될 수 있습니다. `d_weak_revalidate`는 lock 없이 block할 수 있으나 RCU walk에서는 호출되지 않습니다.
`d_hash`는 두 lock 없이 block하지 않으며 RCU walk 가능성이 있습니다. `d_compare`는 `rename_lock`을 보유하고 block하지 않으며 RCU walk일 수 있습니다. `d_delete`와 표에 포함된 `d_prune`은 `->d_lock`을 보유하고 block하지 않습니다.
`d_init`, `d_release`, `d_iput`, `d_automount`, `d_real`은 표의 lock을 보유하지 않으며 앞의 네 항목은 block할 수 있고 `d_real`도 block할 수 있습니다. `d_dname`은 lock 없이 block하지 않습니다. `d_manage`는 ref-walk에서 block할 수 있고 RCU walk일 수 있습니다.
`d_unalias_trylock`과 `d_unalias_unlock`은 `rename_lock`을 보유하고 `->d_lock`은 보유하지 않으며 block하지도 RCU walk에서 호출되지도 않습니다. 원문 prototype의 `d_dname` 괄호 모양을 포함한 표기와 모든 함수 signature는 아래 원문 블록에 그대로 보존됩니다.
lock 보유와 RCU walk·blocking 가능성을 압축한 표입니다.
=======
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 inode *, const struct qstr *,
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 *, enum d_real_type type);
bool (*d_unalias_trylock)(const struct dentry *);
void (*d_unalias_unlock)(const struct dentry *);
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
d_unalias_trylock yes no no no
d_unalias_unlock yes no no no
================== =========== ======== ============== ========
inode_operations
inode_operations와 directory locking
60-138`inode_operations`의 모든 callback은 block할 수 있습니다. 표의 `i_rwsem(inode)`은 호출 시 inode에 어떤 모드로 lock이 잡혀 있는지를 나타냅니다.
`lookup`은 shared, `create`, `mknod`, `symlink`, `mkdir`, `setattr`, `fileattr_set`은 exclusive입니다. `link`는 두 inode 모두 exclusive이고 `unlink`와 `rmdir`도 두 대상에 exclusive lock이 적용됩니다. `rename`은 두 parent와 일부 child에 exclusive lock을 갖습니다.
`readlink`, `get_link`, `get_inode_acl`, `get_acl`, `getattr`, `listxattr`, `fiemap`, `update_time`, `tmpfile`, `get_offset_ctx`에는 이 표 기준의 `i_rwsem`이 없습니다. `permission`도 없지만 RCU walk mode에서 호출되면 block하면 안 됩니다.
`atomic_open`은 기본적으로 shared이고 open flag에 `O_CREAT`이 있으면 exclusive입니다. `fileattr_get`은 lock이 없거나 exclusive일 수 있습니다.
추가로 `->rmdir()`, `->unlink()`, `->rename()`은 victim의 `->i_rwsem`을 exclusive로 잡습니다. Cross-directory `->rename()`은 superblock별 `->s_vfs_rename_sem`도 보유합니다. `->unlink()`와 `->rename()`은 관련된 모든 non-directory의 `->i_rwsem`을 exclusive로 잡으며, `->rename()`은 parent가 바뀌는 subdirectory에도 exclusive lock을 갖습니다. Directory operation locking의 자세한 설명은 `Documentation/filesystems/directory-locking.rst`를 참고합니다.
대표 callback을 shared, exclusive, 없음으로 분류합니다.
================
prototypes::
int (*create) (struct mnt_idmap *, 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 mnt_idmap *, struct inode *,struct dentry *,const char *);
struct dentry *(*mkdir) (struct mnt_idmap *, struct inode *,struct dentry *,umode_t);
int (*rmdir) (struct inode *,struct dentry *);
int (*mknod) (struct mnt_idmap *, struct inode *,struct dentry *,umode_t,dev_t);
int (*rename) (struct mnt_idmap *, 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 mnt_idmap *, struct inode *, int, unsigned int);
struct posix_acl * (*get_inode_acl)(struct inode *, int, bool);
int (*setattr) (struct mnt_idmap *, struct dentry *, struct iattr *);
int (*getattr) (struct mnt_idmap *, 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 mnt_idmap *, struct inode *,
struct file *, umode_t);
int (*fileattr_set)(struct mnt_idmap *idmap,
struct dentry *dentry, struct file_kattr *fa);
int (*fileattr_get)(struct dentry *dentry, struct file_kattr *fa);
struct posix_acl * (*get_acl)(struct mnt_idmap *, struct dentry *, int);
struct offset_ctx *(*get_offset_ctx)(struct inode *inode);
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 (both parents, some children) (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
get_offset_ctx no
============== ==================================================
Additionally, ->rmdir(), ->unlink() and ->rename() have ->i_rwsem
exclusive on victim.
cross-directory ->rename() has (per-superblock) ->s_vfs_rename_sem.
->unlink() and ->rename() have ->i_rwsem exclusive on all non-directories
involved.
->rename() has ->i_rwsem exclusive on any subdirectory that changes parent.
See Documentation/filesystems/directory-locking.rst for more detailed discussion
of the locking scheme for directory operations.
xattr_handler operations
xattr_handler operations
139-163`xattr_handler`의 `list`, `get`, `set` callback은 모두 block할 수 있습니다. `list`와 `get`은 호출 시 inode의 `i_rwsem`을 보유하지 않으며, `set`은 exclusive `i_rwsem(inode)`을 보유합니다.
Prototype에서 `set`은 `struct mnt_idmap *idmap`, dentry, inode, name, buffer, size, flags를 받습니다. Locking contract는 확장 속성의 읽기와 쓰기를 명확히 구분하므로 handler 구현은 `set` 경로에서 이미 잡힌 inode write lock을 다시 획득하지 않도록 해야 합니다.
모든 연산은 sleep할 수 있지만 inode lock 상태가 다릅니다.
========================
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 mnt_idmap *idmap,
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
super_operations와 s_umount
164-224`super_operations` 표는 각 callback의 `s_umount` 상태와 예외 주석을 기록합니다. 대부분 block할 수 있지만 `free_inode`는 RCU callback에서 호출되고 `drop_inode`는 `inode->i_lock`을 보유한다는 중요한 예외가 있습니다.
`put_super`, `freeze_fs`, `unfreeze_fs`, `remount_fs`는 `s_umount` write lock 아래에서 호출됩니다. `sync_fs`는 read lock입니다. `statfs`는 경우에 따라 read lock이고, `umount_begin`, `show_options`, `quota_read`, `quota_write`는 `s_umount`을 보유하지 않습니다. `show_options`에는 `namespace_sem` 주석이 붙습니다.
`->statfs()`가 native 또는 compat `ustat(2)`에서 호출될 때 shared `s_umount`을 갖는 것은 좋지 않은 API에서 생긴 우연입니다. Userspace가 superblock 식별자로 `dev_t`만 주기 때문에 superblock을 고정하려고 이 lock을 사용합니다. `statfs()`, `fstatfs()` 등 다른 경로는 syscall에 전달된 path를 해석하면서 superblock을 고정하므로 `->statfs()` 호출 시 이 lock을 잡지 않습니다.
Quota code는 `dqio_sem`으로 `->quota_read()`와 `->quota_write()`가 quota 파일에서 동작하는 유일한 함수임을 보장합니다. 단, 관리자가 quota가 켜진 상태에서 quota 파일에 직접 쓰는 잘못된 경우는 예외입니다. 추가 locking 정보는 이 문서의 `dquot_operations` 절을 참고합니다.
mount 수명주기 callback의 read/write lock 상태입니다.
================
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
file_system_type mount와 kill_sb
225-248`file_system_type`의 `mount`와 `kill_sb`는 둘 다 block할 수 있습니다. `->mount()`는 `ERR_PTR` 또는 root dentry를 반환하며, 반환 시 그 superblock은 lock된 상태여야 합니다.
`->kill_sb()`는 write-locked superblock을 전달받아 모든 shutdown 작업을 수행한 뒤 lock을 풀고 reference를 내려놓습니다. 따라서 구현은 shutdown 과정과 superblock unlock·put의 소유권을 함께 책임집니다.
`file_system_type` callback이 넘겨받고 반환해야 하는 상태입니다.
================
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
address_space_operations와 folio 수명주기
249-371`address_space_operations`에서는 `dirty_folio`와 `free_folio`를 제외한 callback이 block할 수 있습니다. 표는 folio lock, `i_rwsem`, `invalidate_lock` 상태를 함께 보여줍니다.
`read_folio`와 `readahead`는 folio가 lock된 상태이고 shared `invalidate_lock` 아래에서 호출되며, 시도한 folio를 직접 unlock합니다. `write_begin`은 folio를 lock하고 exclusive `i_rwsem` 아래에서 실행되며, `write_end`는 lock된 folio를 받아 unlock하고 역시 exclusive `i_rwsem` 아래에 있습니다.
`dirty_folio`는 folio lock이 있을 수도 없을 수도 있습니다. `invalidate_folio`는 folio lock과 exclusive `invalidate_lock`을 보유합니다. `release_folio`, `free_folio`, `launder_folio`, `is_partially_uptodate`, `error_remove_folio`는 folio가 lock된 상태이고 `migrate_folio`는 source와 destination 둘 다 lock됩니다. `swap_rw`도 lock된 folio를 받아 unlock합니다.
`->write_begin()`, `->write_end()`, `->read_folio()`는 `/dev/loop` request handler에서 호출될 수 있습니다. `->read_folio()`는 동기적으로 또는 I/O completion에서 folio를 unlock하고 `->readahead()`도 I/O를 시도한 folio를 같은 방식으로 unlock합니다.
`->writepages()`는 주기적 writeback과 syscall이 시작한 sync에 사용됩니다. Address space는 적어도 `*nr_to_write` page에 I/O를 시작하고 쓴 page마다 값을 줄여야 합니다. 요청보다 더 많거나 적게 쓸 수 있지만 가능한 한 가까워야 하며 `nr_to_write`가 NULL이면 모든 dirty page를 써야 합니다. `writepages`는 `mapping->i_pages`에 존재하는 page만 써야 합니다.
`->dirty_folio()`는 대상 folio가 writeback 필요 상태로 표시될 때 여러 커널 경로에서 호출됩니다. 호출자가 folio lock을 잡았거나 truncation을 막는 page table lock 아래에서 folio를 찾았으므로 이때 folio는 truncate될 수 없습니다.
`->bmap()`은 일부 파일시스템의 legacy ioctl `FIBMAP`과 swapper가 사용하며, swapper 사용은 결국 없어질 예정입니다. 새 호출자를 추가해서는 안 됩니다.
`->invalidate_folio()`는 truncate 중 page의 buffer 일부 또는 전부를 버리려 할 때 호출됩니다. 파일시스템은 truncate 또는 hole punch 경로에서 page cache를 무효화하기 전에 `invalidate_lock`을 exclusive로 획득하여 fault·read 같은 cache 채우기 함수와의 race를 막아야 합니다.
MM은 folio를 address space에서 제거하거나 split하는 등 파일시스템 private data를 무효화할 변경 전에 `->release_folio()`를 호출합니다. Folio는 lock되어 있고 writeback 중이 아니지만 dirty일 수 있습니다. `gfp`는 보통 할당보다 private data를 해제하기 위해 파일시스템이 무엇을 할 수 있는지 나타냅니다. 해제할 수 없으면 false를 반환하고, true라면 이미 private data를 제거해야 합니다. Method가 없으면 page cache는 private data를 buffer head로 가정해 `try_to_free_buffers()`를 호출합니다.
`->free_folio()`는 커널이 page cache에서 folio를 제거한 뒤 호출됩니다. Dirty folio를 해제하기 전 `->launder_folio()`가 호출될 수 있으며 정리에 성공하면 0, 실패하면 error를 반환합니다. 다시 mapping되고 redirty되는 것을 막으려면 전체 연산 동안 folio lock을 유지해야 합니다.
`->swap_activate()`는 swap 파일을 검증·준비하고 쓰기 중 메모리 할당을 최소화해야 합니다. `add_swap_extent()` 또는 `iomap_swapfile_activate()`를 호출하고 추가한 extent 수를 반환합니다. I/O를 `->swap_rw()`로 제출하려면 `SWP_FS_OPS`를 설정하며, 그렇지 않으면 `sis->bdev` block device로 직접 제출됩니다. 성공한 activation 뒤 `sys_swapoff()` 경로에서 `->swap_deactivate()`가 호출되고, `SWP_FS_OPS`가 설정되었으면 swap I/O에 `->swap_rw`가 호출됩니다.
callback이 받는 folio와 반환 시 unlock 책임을 요약합니다.
activation 결과가 이후 I/O 제출 경로를 결정합니다.
========================
prototypes::
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)(const struct kiocb *, struct address_space *mapping,
loff_t pos, unsigned len,
struct folio **foliop, void **fsdata);
int (*write_end)(const struct kiocb *, struct address_space *mapping,
loff_t pos, unsigned len, unsigned copied,
struct folio *folio, 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_folio)(struct address_space *, struct folio *);
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
====================== ======================== ========= ===============
read_folio: yes, unlocks shared
writepages:
dirty_folio: maybe
readahead: yes, unlocks shared
write_begin: locks the folio 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_folio: 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().
->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 in
mapping->i_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 MM wants to make a change to the
folio that would invalidate the filesystem's private data. For example,
it may be about to be removed from the address_space or split. The folio
is locked and not under writeback. It may be dirty. The gfp parameter
is not usually used for allocation, but rather to indicate what the
filesystem may do to attempt to free the private data. The filesystem may
return false to indicate that the folio's private data cannot be freed.
If it returns true, it should have already removed the private data from
the folio. If a filesystem does not provide a ->release_folio method,
the pagecache will assume that private data is buffer_heads and call
try_to_free_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
file_lock_operations
372-394`fl_copy_lock`은 `inode->i_lock`을 보유한 상태에서 호출되며 block하면 안 됩니다. `fl_release_private`는 이 lock을 보유할 수도 있고 block할 수도 있지만 lock 종류에 따라 예외가 있습니다.
Flock 또는 POSIX lock의 `->fl_release_private`는 현재 block이 허용됩니다. 그러나 lease는 `i_lock`을 보유한 채 해제될 수 있으므로 lease에 대해 호출된 `fl_release_private`는 block하면 안 됩니다.
lease와 일반 lock의 blocking 차이를 구분합니다.
====================
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
lock_manager_operations
395-421`lock_manager_operations` 표는 `flc_lock`, `blocked_lock_lock`, block 가능성을 나타냅니다. `lm_notify`는 `blocked_lock_lock`을 보유하고 block하지 않습니다. `lm_grant`는 두 lock 모두 없이 nonblocking입니다.
`lm_break`, `lm_change`, `lm_breaker_owns_lease`, `lm_lock_expirable`은 `flc_lock`을 보유하고 `blocked_lock_lock`은 없으며 block하지 않습니다. `lm_expire_lock`만 두 lock 없이 block할 수 있습니다.
내부 lock 보유와 sleep 가능성을 구분합니다.
=======================
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
buffer_head I/O completion
422-435`buffer_head`의 `b_end_io(struct buffer_head *bh, int uptodate)`는 interrupt context에서 호출되므로 극도로 조심해야 합니다. `bh`가 lock되어 있다는 것 외에는 보장되는 조건이 없습니다.
현재 이 callback을 제공하는 곳은 RAID1, highmem, `fs/buffer.c`, `fs/ntfs/aops.c`입니다. Block device가 I/O completion 시 이 method를 호출합니다. 구현은 sleep 가능한 경로 또는 추가 lock 보유를 가정해서는 안 됩니다.
완료 handler가 의존할 수 있는 조건은 매우 제한적입니다.
===========
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
block_device_operations
436-468`block_device_operations`에서 `open`과 `release`는 `open_mutex`를 보유한 상태로 호출됩니다. `ioctl`, `compat_ioctl`, `direct_access`, `unlock_native_capacity`, `getgeo`, `swap_slot_free_notify`에는 이 mutex가 없습니다.
`swap_slot_free_notify`는 `swap_lock`을 보유한 채 호출되며 때로는 page lock도 함께 보유합니다. 따라서 `open_mutex`가 없다는 사실만 보고 자유롭게 block하거나 다른 lock을 획득해서는 안 되고 swap locking order를 지켜야 합니다.
`open_mutex`와 swap 경로의 별도 lock을 표시합니다.
=======================
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 gendisk *, 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
file_operations와 page cache 직렬화
469-560여기에 나열된 `file_operations` callback은 모두 block할 수 있습니다. `->llseek()` locking은 공통 llseek에서 개별 구현으로 이동했습니다. 파일시스템이 `generic_file_llseek`을 쓰지 않으면 자체 `->llseek()`에서 적절한 lock을 획득·해제해야 합니다. 많은 파일시스템에서는 inode mutex를 잡거나 `i_size_read()`를 사용하는 것으로 충분할 수 있습니다.
이 잠금은 `file->f_pos`의 동시 변경을 보호하지 않습니다. 그 동기화는 userspace가 책임져야 합니다. `->iterate_shared()`는 `i_rwsem` read lock과 file의 exclusive `f_pos_lock`을 보유한 채 호출됩니다.
`->fasync()`는 `filp->f_flags`의 `FASYNC` 비트를 유지해야 합니다. 대부분 `fasync_helper()`가 이를 처리하므로 별도 관리가 필요하지 않습니다. 양수 반환값은 VFS layer에서 0으로 mapping됩니다.
Directory의 `->readdir()`와 `->ioctl()` 인터페이스는 변경되어야 합니다. 이상적으로는 `->readdir()`를 `inode_operations`로 옮기고 directory `->ioctl()`을 별도 method로 만들거나 없애야 합니다. Union mount와 유사한 구성에서는 모든 component에 `struct file`이 존재하지 않는 문제 등 현재 인터페이스에는 여러 결함이 있습니다.
Directory의 `->read`도 없어져야 하며 `sys_read()` 계열에서 `-EISDIR`을 강제하는 편이 맞습니다. `->setlease` 구현은 개별 파일시스템에서 lease를 설정하기 전이나 후에 `generic_setlease()`를 호출하여 연산 결과를 기록해야 합니다.
`->fallocate`는 hole punch나 page cache 내용을 무효화하는 연산에서 cache 일관성을 세심하게 유지해야 합니다. 일반적으로 `truncate_inode_pages_range()`로 관련 page cache 범위를 무효화합니다. 동시에 파일 offset에서 disk block으로의 내부·on-disk mapping도 갱신해야 합니다.
Mapping 갱신이 끝날 때까지 page fault와 read가 디스크에서 이제 stale한 cache 내용을 다시 불러오지 못하게 해야 합니다. VFS는 `filemap_fault()`, `filemap_read()`, readahead가 디스크에서 page를 읽을 때 `mapping->invalidate_lock`을 shared로 잡으므로 fallocate 구현은 재로딩을 막기 위해 이 lock을 exclusive로 획득해야 합니다.
`->copy_file_range`와 `->remap_file_range`는 실행 중 file data 변경과 직렬화되어야 합니다. `write(2)` 같은 변경은 `inode->i_rwsem`으로 막을 수 있습니다. Memory mapping을 통한 내용 변경은 `->page_mkwrite`와 조정하도록 `mapping->invalidate_lock`을 획득해야 합니다.
연산별로 필요한 lock 또는 helper를 정리합니다.
===============
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_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 *);
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_shared() is called with i_rwsem held for reading, and with the
file f_pos_lock held exclusively
->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
dquot_operations와 quota 재귀
561-591`dquot_operations`는 파일시스템 관점의 올바른 locking을 보장한 뒤 generic quota operation을 호출하는 wrapper 성격의 함수입니다.
`write_dquot`, `acquire_dquot`, `release_dquot`는 filesystem recursion이 가능하며 호출 시 `dqonoff_sem` 또는 `dqptr_sem`을 보유합니다. `mark_dirty`는 recursion이 없고 보유 lock도 없습니다. `write_info`는 recursion이 가능하며 `dqonoff_sem`을 보유합니다.
여기서 FS recursion은 superblock operation의 `->quota_read()`와 `->quota_write()`를 호출하는 것을 뜻합니다. Quota locking의 자세한 내용은 `fs/dquot.c`에서 확인할 수 있습니다.
파일시스템 재진입과 이미 보유한 semaphore를 함께 봅니다.
================
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
vm_operations_struct와 fault 직렬화
592-669`vm_operations_struct` 표에서 `open`은 write `mmap_lock`, `close`는 read 또는 write lock 아래에서 호출됩니다. `fault`, `page_mkwrite`, `pfn_mkwrite`, `access`는 read lock이고 `huge_fault`와 `map_pages`는 read lock이 있을 수도 있습니다. `fault`와 `page_mkwrite`는 page를 lock한 상태로 반환할 수 있습니다.
`->fault()`는 존재하지 않던 PTE를 fault-in하려 할 때 호출됩니다. 파일시스템은 `vm_fault`의 `pgoff`에 해당하는 page를 찾아 반환해야 합니다. Page가 truncate 또는 invalidate될 수 있다면 `invalidate_lock`을 잡고 이미 truncate되지 않았는지 확인한 뒤 `VM_FAULT_LOCKED`와 locked page를 반환합니다. 이후 VM이 page를 unlock합니다.
`->huge_fault()`는 PUD 또는 PMD entry가 없을 때 호출되어 파일시스템이 PUD·PMD 크기 page를 설치할 기회를 줍니다. `->fault`에서도 PMD 크기 page를 반환할 수 있으므로 구현이 불필요할 수 있습니다. 특히 `->huge_fault()`에서 `filemap_fault()`를 호출하면 안 됩니다. 이 method 호출 시 `mmap_lock`이 없을 수 있습니다.
`->map_pages()`는 VM이 쉽게 접근 가능한 page를 미리 mapping하려 할 때 호출됩니다. 파일시스템은 `start_pgoff`부터 `end_pgoff`까지의 page를 찾아 mapping해야 합니다. RCU lock을 보유한 상태로 호출되므로 block하면 안 되며, block 없이 page에 닿을 수 없으면 건너뜁니다. PTE 설정에는 `set_pte_range()`를 사용하고 `vm_fault`의 `pte`를 기준으로 다른 offset의 entry pointer를 계산합니다.
`->page_mkwrite()`는 read-only PTE가 writeable로 바뀌기 직전에 호출됩니다. Truncate·invalidate race와 `->remap_file_range`, `->copy_file_range` 같은 연산과의 race를 막고 locked page를 반환해야 하며 보통 `mapping->invalidate_lock`이 적합합니다. Page가 이미 truncate되었다면 `->fault()`처럼 새 page를 찾지 말고 `VM_FAULT_NOPAGE`를 반환하여 VM이 fault를 재시도하게 합니다.
`->pfn_mkwrite()`는 page 없는 `VM_PFNMAP` 또는 `VM_MIXEDMAP` PTE에 대한 page_mkwrite와 같습니다. 예상 반환값은 `VM_FAULT_NOPAGE` 또는 `VM_FAULT_ERROR` 유형입니다. Error를 반환하지 않으면 호출 뒤 기본 동작은 PTE를 read-write로 바꾸는 것입니다.
`->access()`는 `access_process_vm()`에서 `get_user_pages()`가 실패할 때 호출되며 보통 `/proc/pid/mem`이나 ptrace를 통한 process debugging에 사용됩니다. `VM_IO | VM_PFNMAP` VMA에만 필요합니다.
문서 끝의 `Dubious stuff` 절은 누군가 무언가를 깨뜨렸거나 이미 깨진 상태를 발견했지만 직접 고치지 못했다면 최소한 여기에 기록하라고 요청합니다. 현재 별도 사례는 기재되어 있지 않습니다.
`mmap_lock` 상태와 page lock 반환 가능성을 요약합니다.
쓰기 허용 전에 page와 file mapping의 일관성을 확인합니다.
====================
prototypes::
void (*open)(struct vm_area_struct *);
void (*close)(struct vm_area_struct *);
vm_fault_t (*fault)(struct vm_fault *);
vm_fault_t (*huge_fault)(struct vm_fault *, unsigned int order);
vm_fault_t (*map_pages)(struct vm_fault *, pgoff_t start, pgoff_t end);
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: write
close: read/write
fault: read can return with page locked
huge_fault: maybe-read
map_pages: maybe-read
page_mkwrite: read can return with page locked
pfn_mkwrite: read
access: read
============= ========== ===========================
->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.
->huge_fault() is called when there is no PUD or PMD entry present. This
gives the filesystem the opportunity to install a PUD or PMD sized page.
Filesystems can also use the ->fault method to return a PMD sized page,
so implementing this function may not be necessary. In particular,
filesystems should not call filemap_fault() from ->huge_fault().
The mmap_lock may not be held when this method is called.
->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 the RCU lock held and must
not block. If it's not possible to reach a page without blocking,
filesystem should skip it. Filesystem should use set_pte_range() 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)
요약·해설
locking.rst:1-669이 문서는 VFS callback을 구현할 때 호출자가 이미 보유한 lock, callback의 sleep 가능 여부, 반환 전에 unlock해야 하는 객체를 한곳에 모은 계약표입니다. 같은 이름의 callback이라도 RCU walk, interrupt, writeback, fault처럼 호출 문맥에 따라 허용 동작이 달라집니다.
구현 검토에서는 먼저 표의 기존 lock을 확인하고, 추가 lock 획득 순서와 block 가능성을 검증해야 합니다. Folio·page cache 변경은 `invalidate_lock`, directory 변경은 `i_rwsem`과 rename lock, mmap write는 `page_mkwrite`와의 직렬화가 핵심입니다.
각 callback 구현 전에 확인할 공통 질문입니다.