projects/linux·blob master · refs

3163 lines · 83.1 KiB

1// SPDX-License-Identifier: GPL-2.0-only
2/*
3 * linux/fs/locks.c
4 *
5 * We implement four types of file locks: BSD locks, posix locks, open
6 * file description locks, and leases. For details about BSD locks,
7 * see the flock(2) man page; for details about the other three, see
8 * fcntl(2).
9 *
10 *
11 * Locking conflicts and dependencies:
12 * If multiple threads attempt to lock the same byte (or flock the same file)
13 * only one can be granted the lock, and other must wait their turn.
14 * The first lock has been "applied" or "granted", the others are "waiting"
15 * and are "blocked" by the "applied" lock..
16 *
17 * Waiting and applied locks are all kept in trees whose properties are:
18 *
19 * - the root of a tree may be an applied or waiting lock.
20 * - every other node in the tree is a waiting lock that
21 * conflicts with every ancestor of that node.
22 *
23 * Every such tree begins life as a waiting singleton which obviously
24 * satisfies the above properties.
25 *
26 * The only ways we modify trees preserve these properties:
27 *
28 * 1. We may add a new leaf node, but only after first verifying that it
29 * conflicts with all of its ancestors.
30 * 2. We may remove the root of a tree, creating a new singleton
31 * tree from the root and N new trees rooted in the immediate
32 * children.
33 * 3. If the root of a tree is not currently an applied lock, we may
34 * apply it (if possible).
35 * 4. We may upgrade the root of the tree (either extend its range,
36 * or upgrade its entire range from read to write).
37 *
38 * When an applied lock is modified in a way that reduces or downgrades any
39 * part of its range, we remove all its children (2 above). This particularly
40 * happens when a lock is unlocked.
41 *
42 * For each of those child trees we "wake up" the thread which is
43 * waiting for the lock so it can continue handling as follows: if the
44 * root of the tree applies, we do so (3). If it doesn't, it must
45 * conflict with some applied lock. We remove (wake up) all of its children
46 * (2), and add it is a new leaf to the tree rooted in the applied
47 * lock (1). We then repeat the process recursively with those
48 * children.
49 *
50 */
51#include <linux/capability.h>
52#include <linux/file.h>
53#include <linux/fdtable.h>
54#include <linux/filelock.h>
55#include <linux/fs.h>
56#include <linux/init.h>
57#include <linux/security.h>
58#include <linux/slab.h>
59#include <linux/syscalls.h>
60#include <linux/time.h>
61#include <linux/rcupdate.h>
62#include <linux/pid_namespace.h>
63#include <linux/hashtable.h>
64#include <linux/percpu.h>
65#include <linux/sysctl.h>
66
67#define CREATE_TRACE_POINTS
68#include <trace/events/filelock.h>
69
70#include <linux/uaccess.h>
71
72static struct file_lock *file_lock(struct file_lock_core *flc)
73{
74 return container_of(flc, struct file_lock, c);
75}
76
77static struct file_lease *file_lease(struct file_lock_core *flc)
78{
79 return container_of(flc, struct file_lease, c);
80}
81
82static bool lease_breaking(struct file_lease *fl)
83{
84 return fl->c.flc_flags & (FL_UNLOCK_PENDING | FL_DOWNGRADE_PENDING);
85}
86
87static int target_leasetype(struct file_lease *fl)
88{
89 if (fl->c.flc_flags & FL_UNLOCK_PENDING)
90 return F_UNLCK;
91 if (fl->c.flc_flags & FL_DOWNGRADE_PENDING)
92 return F_RDLCK;
93 return fl->c.flc_type;
94}
95
96static int leases_enable = 1;
97static int lease_break_time = 45;
98
99#ifdef CONFIG_SYSCTL
100static const struct ctl_table locks_sysctls[] = {
101 {
102 .procname = "leases-enable",
103 .data = &leases_enable,
104 .maxlen = sizeof(int),
105 .mode = 0644,
106 .proc_handler = proc_dointvec,
107 },
108#ifdef CONFIG_MMU
109 {
110 .procname = "lease-break-time",
111 .data = &lease_break_time,
112 .maxlen = sizeof(int),
113 .mode = 0644,
114 .proc_handler = proc_dointvec,
115 },
116#endif /* CONFIG_MMU */
117};
118
119static int __init init_fs_locks_sysctls(void)
120{
121 register_sysctl_init("fs", locks_sysctls);
122 return 0;
123}
124early_initcall(init_fs_locks_sysctls);
125#endif /* CONFIG_SYSCTL */
126
127/*
128 * The global file_lock_list is only used for displaying /proc/locks, so we
129 * keep a list on each CPU, with each list protected by its own spinlock.
130 * Global serialization is done using file_rwsem.
131 *
132 * Note that alterations to the list also require that the relevant flc_lock is
133 * held.
134 */
135struct file_lock_list_struct {
136 spinlock_t lock;
137 struct hlist_head hlist;
138};
139static DEFINE_PER_CPU(struct file_lock_list_struct, file_lock_list);
140DEFINE_STATIC_PERCPU_RWSEM(file_rwsem);
141
142
143/*
144 * The blocked_hash is used to find POSIX lock loops for deadlock detection.
145 * It is protected by blocked_lock_lock.
146 *
147 * We hash locks by lockowner in order to optimize searching for the lock a
148 * particular lockowner is waiting on.
149 *
150 * FIXME: make this value scale via some heuristic? We generally will want more
151 * buckets when we have more lockowners holding locks, but that's a little
152 * difficult to determine without knowing what the workload will look like.
153 */
154#define BLOCKED_HASH_BITS 7
155static DEFINE_HASHTABLE(blocked_hash, BLOCKED_HASH_BITS);
156
157/*
158 * This lock protects the blocked_hash. Generally, if you're accessing it, you
159 * want to be holding this lock.
160 *
161 * In addition, it also protects the fl->fl_blocked_requests list, and the
162 * fl->fl_blocker pointer for file_lock structures that are acting as lock
163 * requests (in contrast to those that are acting as records of acquired locks).
164 *
165 * Note that when we acquire this lock in order to change the above fields,
166 * we often hold the flc_lock as well. In certain cases, when reading the fields
167 * protected by this lock, we can skip acquiring it iff we already hold the
168 * flc_lock.
169 */
170static DEFINE_SPINLOCK(blocked_lock_lock);
171
172static struct kmem_cache *flctx_cache __ro_after_init;
173static struct kmem_cache *filelock_cache __ro_after_init;
174static struct kmem_cache *filelease_cache __ro_after_init;
175
176static struct file_lock_context *
177locks_get_lock_context(struct inode *inode, int type)
178{
179 struct file_lock_context *ctx;
180
181 ctx = locks_inode_context(inode);
182 if (likely(ctx) || type == F_UNLCK)
183 goto out;
184
185 ctx = kmem_cache_alloc(flctx_cache, GFP_KERNEL);
186 if (!ctx)
187 goto out;
188
189 spin_lock_init(&ctx->flc_lock);
190 INIT_LIST_HEAD(&ctx->flc_flock);
191 INIT_LIST_HEAD(&ctx->flc_posix);
192 INIT_LIST_HEAD(&ctx->flc_lease);
193
194 /*
195 * Assign the pointer if it's not already assigned. If it is, then
196 * free the context we just allocated.
197 */
198 spin_lock(&inode->i_lock);
199 if (!(inode->i_opflags & IOP_FLCTX)) {
200 VFS_BUG_ON_INODE(inode->i_flctx, inode);
201 WRITE_ONCE(inode->i_flctx, ctx);
202 /*
203 * Paired with locks_inode_context().
204 */
205 smp_store_release(&inode->i_opflags, inode->i_opflags | IOP_FLCTX);
206 spin_unlock(&inode->i_lock);
207 } else {
208 VFS_BUG_ON_INODE(!inode->i_flctx, inode);
209 spin_unlock(&inode->i_lock);
210 kmem_cache_free(flctx_cache, ctx);
211 ctx = locks_inode_context(inode);
212 }
213out:
214 trace_locks_get_lock_context(inode, type, ctx);
215 return ctx;
216}
217
218static void
219locks_dump_ctx_list(struct list_head *list, char *list_type)
220{
221 struct file_lock_core *flc;
222
223 list_for_each_entry(flc, list, flc_list)
224 pr_warn("%s: fl_owner=%p fl_flags=0x%x fl_type=0x%x fl_pid=%u\n",
225 list_type, flc->flc_owner, flc->flc_flags,
226 flc->flc_type, flc->flc_pid);
227}
228
229static void
230locks_check_ctx_lists(struct inode *inode)
231{
232 struct file_lock_context *ctx = inode->i_flctx;
233
234 if (unlikely(!list_empty(&ctx->flc_flock) ||
235 !list_empty(&ctx->flc_posix) ||
236 !list_empty(&ctx->flc_lease))) {
237 pr_warn("Leaked locks on dev=0x%x:0x%x ino=0x%llx:\n",
238 MAJOR(inode->i_sb->s_dev), MINOR(inode->i_sb->s_dev),
239 inode->i_ino);
240 locks_dump_ctx_list(&ctx->flc_flock, "FLOCK");
241 locks_dump_ctx_list(&ctx->flc_posix, "POSIX");
242 locks_dump_ctx_list(&ctx->flc_lease, "LEASE");
243 }
244}
245
246static void
247locks_check_ctx_file_list(struct file *filp, struct list_head *list, char *list_type)
248{
249 struct file_lock_core *flc;
250 struct inode *inode = file_inode(filp);
251
252 list_for_each_entry(flc, list, flc_list)
253 if (flc->flc_file == filp)
254 pr_warn("Leaked %s lock on dev=0x%x:0x%x ino=0x%llx "
255 " fl_owner=%p fl_flags=0x%x fl_type=0x%x fl_pid=%u\n",
256 list_type, MAJOR(inode->i_sb->s_dev),
257 MINOR(inode->i_sb->s_dev), inode->i_ino,
258 flc->flc_owner, flc->flc_flags,
259 flc->flc_type, flc->flc_pid);
260}
261
262void
263locks_free_lock_context(struct inode *inode)
264{
265 struct file_lock_context *ctx = locks_inode_context(inode);
266
267 if (unlikely(ctx)) {
268 locks_check_ctx_lists(inode);
269 kmem_cache_free(flctx_cache, ctx);
270 }
271}
272
273static void locks_init_lock_heads(struct file_lock_core *flc)
274{
275 INIT_HLIST_NODE(&flc->flc_link);
276 INIT_LIST_HEAD(&flc->flc_list);
277 INIT_LIST_HEAD(&flc->flc_blocked_requests);
278 INIT_LIST_HEAD(&flc->flc_blocked_member);
279 init_waitqueue_head(&flc->flc_wait);
280}
281
282/* Allocate an empty lock structure. */
283struct file_lock *locks_alloc_lock(void)
284{
285 struct file_lock *fl = kmem_cache_zalloc(filelock_cache, GFP_KERNEL);
286
287 if (fl)
288 locks_init_lock_heads(&fl->c);
289
290 return fl;
291}
292EXPORT_SYMBOL_GPL(locks_alloc_lock);
293
294/* Allocate an empty lock structure. */
295struct file_lease *locks_alloc_lease(void)
296{
297 struct file_lease *fl = kmem_cache_zalloc(filelease_cache, GFP_KERNEL);
298
299 if (fl)
300 locks_init_lock_heads(&fl->c);
301
302 return fl;
303}
304EXPORT_SYMBOL_GPL(locks_alloc_lease);
305
306void locks_release_private(struct file_lock *fl)
307{
308 struct file_lock_core *flc = &fl->c;
309
310 BUG_ON(waitqueue_active(&flc->flc_wait));
311 BUG_ON(!list_empty(&flc->flc_list));
312 BUG_ON(!list_empty(&flc->flc_blocked_requests));
313 BUG_ON(!list_empty(&flc->flc_blocked_member));
314 BUG_ON(!hlist_unhashed(&flc->flc_link));
315
316 if (fl->fl_ops) {
317 if (fl->fl_ops->fl_release_private)
318 fl->fl_ops->fl_release_private(fl);
319 fl->fl_ops = NULL;
320 }
321
322 if (fl->fl_lmops) {
323 if (fl->fl_lmops->lm_put_owner) {
324 fl->fl_lmops->lm_put_owner(flc->flc_owner);
325 flc->flc_owner = NULL;
326 }
327 fl->fl_lmops = NULL;
328 }
329}
330EXPORT_SYMBOL_GPL(locks_release_private);
331
332/**
333 * locks_owner_has_blockers - Check for blocking lock requests
334 * @flctx: file lock context
335 * @owner: lock owner
336 *
337 * Return values:
338 * %true: @owner has at least one blocker
339 * %false: @owner has no blockers
340 */
341bool locks_owner_has_blockers(struct file_lock_context *flctx, fl_owner_t owner)
342{
343 struct file_lock_core *flc;
344
345 spin_lock(&flctx->flc_lock);
346 list_for_each_entry(flc, &flctx->flc_posix, flc_list) {
347 if (flc->flc_owner != owner)
348 continue;
349 if (!list_empty(&flc->flc_blocked_requests)) {
350 spin_unlock(&flctx->flc_lock);
351 return true;
352 }
353 }
354 spin_unlock(&flctx->flc_lock);
355 return false;
356}
357EXPORT_SYMBOL_GPL(locks_owner_has_blockers);
358
359/* Free a lock which is not in use. */
360void locks_free_lock(struct file_lock *fl)
361{
362 locks_release_private(fl);
363 kmem_cache_free(filelock_cache, fl);
364}
365EXPORT_SYMBOL(locks_free_lock);
366
367/* Free a lease which is not in use. */
368void locks_free_lease(struct file_lease *fl)
369{
370 kmem_cache_free(filelease_cache, fl);
371}
372EXPORT_SYMBOL(locks_free_lease);
373
374static void
375locks_dispose_list(struct list_head *dispose)
376{
377 struct file_lock_core *flc;
378
379 while (!list_empty(dispose)) {
380 flc = list_first_entry(dispose, struct file_lock_core, flc_list);
381 list_del_init(&flc->flc_list);
382 locks_free_lock(file_lock(flc));
383 }
384}
385
386static void
387lease_dispose_list(struct list_head *dispose)
388{
389 struct file_lock_core *flc;
390
391 while (!list_empty(dispose)) {
392 flc = list_first_entry(dispose, struct file_lock_core, flc_list);
393 list_del_init(&flc->flc_list);
394 locks_free_lease(file_lease(flc));
395 }
396}
397
398void locks_init_lock(struct file_lock *fl)
399{
400 memset(fl, 0, sizeof(struct file_lock));
401 locks_init_lock_heads(&fl->c);
402}
403EXPORT_SYMBOL(locks_init_lock);
404
405void locks_init_lease(struct file_lease *fl)
406{
407 memset(fl, 0, sizeof(*fl));
408 locks_init_lock_heads(&fl->c);
409}
410EXPORT_SYMBOL(locks_init_lease);
411
412/*
413 * Initialize a new lock from an existing file_lock structure.
414 */
415void locks_copy_conflock(struct file_lock *new, struct file_lock *fl)
416{
417 new->c.flc_owner = fl->c.flc_owner;
418 new->c.flc_pid = fl->c.flc_pid;
419 new->c.flc_file = NULL;
420 new->c.flc_flags = fl->c.flc_flags;
421 new->c.flc_type = fl->c.flc_type;
422 new->fl_start = fl->fl_start;
423 new->fl_end = fl->fl_end;
424 new->fl_lmops = fl->fl_lmops;
425 new->fl_ops = NULL;
426
427 if (fl->fl_lmops) {
428 if (fl->fl_lmops->lm_get_owner)
429 fl->fl_lmops->lm_get_owner(fl->c.flc_owner);
430 }
431}
432EXPORT_SYMBOL(locks_copy_conflock);
433
434void locks_copy_lock(struct file_lock *new, struct file_lock *fl)
435{
436 /* "new" must be a freshly-initialized lock */
437 WARN_ON_ONCE(new->fl_ops);
438
439 locks_copy_conflock(new, fl);
440
441 new->c.flc_file = fl->c.flc_file;
442 new->fl_ops = fl->fl_ops;
443
444 if (fl->fl_ops) {
445 if (fl->fl_ops->fl_copy_lock)
446 fl->fl_ops->fl_copy_lock(new, fl);
447 }
448}
449EXPORT_SYMBOL(locks_copy_lock);
450
451static void locks_move_blocks(struct file_lock *new, struct file_lock *fl)
452{
453 struct file_lock *f;
454
455 /*
456 * As ctx->flc_lock is held, new requests cannot be added to
457 * ->flc_blocked_requests, so we don't need a lock to check if it
458 * is empty.
459 */
460 if (list_empty(&fl->c.flc_blocked_requests))
461 return;
462 spin_lock(&blocked_lock_lock);
463 list_splice_init(&fl->c.flc_blocked_requests,
464 &new->c.flc_blocked_requests);
465 list_for_each_entry(f, &new->c.flc_blocked_requests,
466 c.flc_blocked_member)
467 f->c.flc_blocker = &new->c;
468 spin_unlock(&blocked_lock_lock);
469}
470
471static inline int flock_translate_cmd(int cmd) {
472 switch (cmd) {
473 case LOCK_SH:
474 return F_RDLCK;
475 case LOCK_EX:
476 return F_WRLCK;
477 case LOCK_UN:
478 return F_UNLCK;
479 }
480 return -EINVAL;
481}
482
483/* Fill in a file_lock structure with an appropriate FLOCK lock. */
484static void flock_make_lock(struct file *filp, struct file_lock *fl, int type)
485{
486 locks_init_lock(fl);
487
488 fl->c.flc_file = filp;
489 fl->c.flc_owner = filp;
490 fl->c.flc_pid = current->tgid;
491 fl->c.flc_flags = FL_FLOCK;
492 fl->c.flc_type = type;
493 fl->fl_end = OFFSET_MAX;
494}
495
496static int assign_type(struct file_lock_core *flc, int type)
497{
498 switch (type) {
499 case F_RDLCK:
500 case F_WRLCK:
501 case F_UNLCK:
502 flc->flc_type = type;
503 break;
504 default:
505 return -EINVAL;
506 }
507 return 0;
508}
509
510static int flock64_to_posix_lock(struct file *filp, struct file_lock *fl,
511 struct flock64 *l)
512{
513 switch (l->l_whence) {
514 case SEEK_SET:
515 fl->fl_start = 0;
516 break;
517 case SEEK_CUR:
518 fl->fl_start = filp->f_pos;
519 break;
520 case SEEK_END:
521 fl->fl_start = i_size_read(file_inode(filp));
522 break;
523 default:
524 return -EINVAL;
525 }
526 if (l->l_start > OFFSET_MAX - fl->fl_start)
527 return -EOVERFLOW;
528 fl->fl_start += l->l_start;
529 if (fl->fl_start < 0)
530 return -EINVAL;
531
532 /* POSIX-1996 leaves the case l->l_len < 0 undefined;
533 POSIX-2001 defines it. */
534 if (l->l_len > 0) {
535 if (l->l_len - 1 > OFFSET_MAX - fl->fl_start)
536 return -EOVERFLOW;
537 fl->fl_end = fl->fl_start + (l->l_len - 1);
538
539 } else if (l->l_len < 0) {
540 if (fl->fl_start + l->l_len < 0)
541 return -EINVAL;
542 fl->fl_end = fl->fl_start - 1;
543 fl->fl_start += l->l_len;
544 } else
545 fl->fl_end = OFFSET_MAX;
546
547 fl->c.flc_owner = current->files;
548 fl->c.flc_pid = current->tgid;
549 fl->c.flc_file = filp;
550 fl->c.flc_flags = FL_POSIX;
551 fl->fl_ops = NULL;
552 fl->fl_lmops = NULL;
553
554 return assign_type(&fl->c, l->l_type);
555}
556
557/* Verify a "struct flock" and copy it to a "struct file_lock" as a POSIX
558 * style lock.
559 */
560static int flock_to_posix_lock(struct file *filp, struct file_lock *fl,
561 struct flock *l)
562{
563 struct flock64 ll = {
564 .l_type = l->l_type,
565 .l_whence = l->l_whence,
566 .l_start = l->l_start,
567 .l_len = l->l_len,
568 };
569
570 return flock64_to_posix_lock(filp, fl, &ll);
571}
572
573/* default lease lock manager operations */
574static bool
575lease_break_callback(struct file_lease *fl)
576{
577 kill_fasync(&fl->fl_fasync, SIGIO, POLL_MSG);
578 return false;
579}
580
581static void
582lease_setup(struct file_lease *fl, void **priv)
583{
584 struct file *filp = fl->c.flc_file;
585 struct fasync_struct *fa = *priv;
586
587 /*
588 * fasync_insert_entry() returns the old entry if any. If there was no
589 * old entry, then it used "priv" and inserted it into the fasync list.
590 * Clear the pointer to indicate that it shouldn't be freed.
591 */
592 if (!fasync_insert_entry(fa->fa_fd, filp, &fl->fl_fasync, fa))
593 *priv = NULL;
594
595 __f_setown(filp, task_pid(current), PIDTYPE_TGID, 0);
596}
597
598/**
599 * lease_open_conflict - see if the given file points to an inode that has
600 * an existing open that would conflict with the
601 * desired lease.
602 * @filp: file to check
603 * @arg: type of lease that we're trying to acquire
604 *
605 * Check to see if there's an existing open fd on this file that would
606 * conflict with the lease we're trying to set.
607 */
608static int
609lease_open_conflict(struct file *filp, const int arg)
610{
611 struct inode *inode = file_inode(filp);
612 int self_wcount = 0, self_rcount = 0;
613
614 if (arg == F_RDLCK)
615 return inode_is_open_for_write(inode) ? -EAGAIN : 0;
616 else if (arg != F_WRLCK)
617 return 0;
618
619 /*
620 * Make sure that only read/write count is from lease requestor.
621 * Note that this will result in denying write leases when i_writecount
622 * is negative, which is what we want. (We shouldn't grant write leases
623 * on files open for execution.)
624 */
625 if (filp->f_mode & FMODE_WRITE)
626 self_wcount = 1;
627 else if (filp->f_mode & FMODE_READ)
628 self_rcount = 1;
629
630 if (atomic_read(&inode->i_writecount) != self_wcount ||
631 atomic_read(&inode->i_readcount) != self_rcount)
632 return -EAGAIN;
633
634 return 0;
635}
636
637static const struct lease_manager_operations lease_manager_ops = {
638 .lm_break = lease_break_callback,
639 .lm_change = lease_modify,
640 .lm_setup = lease_setup,
641 .lm_open_conflict = lease_open_conflict,
642};
643
644/*
645 * Initialize a lease, use the default lock manager operations
646 */
647static int lease_init(struct file *filp, unsigned int flags, int type, struct file_lease *fl)
648{
649 if (assign_type(&fl->c, type) != 0)
650 return -EINVAL;
651
652 fl->c.flc_owner = filp;
653 fl->c.flc_pid = current->tgid;
654
655 fl->c.flc_file = filp;
656 fl->c.flc_flags = flags;
657 fl->fl_lmops = &lease_manager_ops;
658 return 0;
659}
660
661/* Allocate a file_lock initialised to this type of lease */
662static struct file_lease *lease_alloc(struct file *filp, unsigned int flags, int type)
663{
664 struct file_lease *fl = locks_alloc_lease();
665 int error = -ENOMEM;
666
667 if (fl == NULL)
668 return ERR_PTR(error);
669
670 error = lease_init(filp, flags, type, fl);
671 if (error) {
672 locks_free_lease(fl);
673 return ERR_PTR(error);
674 }
675 return fl;
676}
677
678/* Check if two locks overlap each other.
679 */
680static inline int locks_overlap(struct file_lock *fl1, struct file_lock *fl2)
681{
682 return ((fl1->fl_end >= fl2->fl_start) &&
683 (fl2->fl_end >= fl1->fl_start));
684}
685
686/*
687 * Check whether two locks have the same owner.
688 */
689static int posix_same_owner(struct file_lock_core *fl1, struct file_lock_core *fl2)
690{
691 return fl1->flc_owner == fl2->flc_owner;
692}
693
694/* Must be called with the flc_lock held! */
695static void locks_insert_global_locks(struct file_lock_core *flc)
696{
697 struct file_lock_list_struct *fll = this_cpu_ptr(&file_lock_list);
698
699 percpu_rwsem_assert_held(&file_rwsem);
700
701 spin_lock(&fll->lock);
702 flc->flc_link_cpu = smp_processor_id();
703 hlist_add_head(&flc->flc_link, &fll->hlist);
704 spin_unlock(&fll->lock);
705}
706
707/* Must be called with the flc_lock held! */
708static void locks_delete_global_locks(struct file_lock_core *flc)
709{
710 struct file_lock_list_struct *fll;
711
712 percpu_rwsem_assert_held(&file_rwsem);
713
714 /*
715 * Avoid taking lock if already unhashed. This is safe since this check
716 * is done while holding the flc_lock, and new insertions into the list
717 * also require that it be held.
718 */
719 if (hlist_unhashed(&flc->flc_link))
720 return;
721
722 fll = per_cpu_ptr(&file_lock_list, flc->flc_link_cpu);
723 spin_lock(&fll->lock);
724 hlist_del_init(&flc->flc_link);
725 spin_unlock(&fll->lock);
726}
727
728static unsigned long
729posix_owner_key(struct file_lock_core *flc)
730{
731 return (unsigned long) flc->flc_owner;
732}
733
734static void locks_insert_global_blocked(struct file_lock_core *waiter)
735{
736 lockdep_assert_held(&blocked_lock_lock);
737
738 hash_add(blocked_hash, &waiter->flc_link, posix_owner_key(waiter));
739}
740
741static void locks_delete_global_blocked(struct file_lock_core *waiter)
742{
743 lockdep_assert_held(&blocked_lock_lock);
744
745 hash_del(&waiter->flc_link);
746}
747
748/* Remove waiter from blocker's block list.
749 * When blocker ends up pointing to itself then the list is empty.
750 *
751 * Must be called with blocked_lock_lock held.
752 */
753static void __locks_unlink_block(struct file_lock_core *waiter)
754{
755 locks_delete_global_blocked(waiter);
756 list_del_init(&waiter->flc_blocked_member);
757}
758
759static void __locks_wake_up_blocks(struct file_lock_core *blocker)
760{
761 while (!list_empty(&blocker->flc_blocked_requests)) {
762 struct file_lock_core *waiter;
763 struct file_lock *fl;
764
765 waiter = list_first_entry(&blocker->flc_blocked_requests,
766 struct file_lock_core, flc_blocked_member);
767
768 fl = file_lock(waiter);
769 __locks_unlink_block(waiter);
770 if ((waiter->flc_flags & (FL_POSIX | FL_FLOCK)) &&
771 fl->fl_lmops && fl->fl_lmops->lm_notify)
772 fl->fl_lmops->lm_notify(fl);
773 else
774 locks_wake_up_waiter(waiter);
775
776 /*
777 * The setting of flc_blocker to NULL marks the "done"
778 * point in deleting a block. Paired with acquire at the top
779 * of locks_delete_block().
780 */
781 smp_store_release(&waiter->flc_blocker, NULL);
782 }
783}
784
785static int __locks_delete_block(struct file_lock_core *waiter)
786{
787 int status = -ENOENT;
788
789 /*
790 * If fl_blocker is NULL, it won't be set again as this thread "owns"
791 * the lock and is the only one that might try to claim the lock.
792 *
793 * We use acquire/release to manage fl_blocker so that we can
794 * optimize away taking the blocked_lock_lock in many cases.
795 *
796 * The smp_load_acquire guarantees two things:
797 *
798 * 1/ that fl_blocked_requests can be tested locklessly. If something
799 * was recently added to that list it must have been in a locked region
800 * *before* the locked region when fl_blocker was set to NULL.
801 *
802 * 2/ that no other thread is accessing 'waiter', so it is safe to free
803 * it. __locks_wake_up_blocks is careful not to touch waiter after
804 * fl_blocker is released.
805 *
806 * If a lockless check of fl_blocker shows it to be NULL, we know that
807 * no new locks can be inserted into its fl_blocked_requests list, and
808 * can avoid doing anything further if the list is empty.
809 */
810 if (!smp_load_acquire(&waiter->flc_blocker) &&
811 list_empty(&waiter->flc_blocked_requests))
812 return status;
813
814 spin_lock(&blocked_lock_lock);
815 if (waiter->flc_blocker)
816 status = 0;
817 __locks_wake_up_blocks(waiter);
818 __locks_unlink_block(waiter);
819
820 /*
821 * The setting of fl_blocker to NULL marks the "done" point in deleting
822 * a block. Paired with acquire at the top of this function.
823 */
824 smp_store_release(&waiter->flc_blocker, NULL);
825 spin_unlock(&blocked_lock_lock);
826 return status;
827}
828
829/**
830 * locks_delete_block - stop waiting for a file lock
831 * @waiter: the lock which was waiting
832 *
833 * lockd/nfsd need to disconnect the lock while working on it.
834 */
835int locks_delete_block(struct file_lock *waiter)
836{
837 return __locks_delete_block(&waiter->c);
838}
839EXPORT_SYMBOL(locks_delete_block);
840
841/* Insert waiter into blocker's block list.
842 * We use a circular list so that processes can be easily woken up in
843 * the order they blocked. The documentation doesn't require this but
844 * it seems like the reasonable thing to do.
845 *
846 * Must be called with both the flc_lock and blocked_lock_lock held. The
847 * fl_blocked_requests list itself is protected by the blocked_lock_lock,
848 * but by ensuring that the flc_lock is also held on insertions we can avoid
849 * taking the blocked_lock_lock in some cases when we see that the
850 * fl_blocked_requests list is empty.
851 *
852 * Rather than just adding to the list, we check for conflicts with any existing
853 * waiters, and add beneath any waiter that blocks the new waiter.
854 * Thus wakeups don't happen until needed.
855 */
856static void __locks_insert_block(struct file_lock_core *blocker,
857 struct file_lock_core *waiter,
858 bool conflict(struct file_lock_core *,
859 struct file_lock_core *))
860{
861 struct file_lock_core *flc;
862
863 BUG_ON(!list_empty(&waiter->flc_blocked_member));
864new_blocker:
865 list_for_each_entry(flc, &blocker->flc_blocked_requests, flc_blocked_member)
866 if (conflict(flc, waiter)) {
867 blocker = flc;
868 goto new_blocker;
869 }
870 waiter->flc_blocker = blocker;
871 list_add_tail(&waiter->flc_blocked_member,
872 &blocker->flc_blocked_requests);
873
874 if ((blocker->flc_flags & (FL_POSIX|FL_OFDLCK)) == FL_POSIX)
875 locks_insert_global_blocked(waiter);
876
877 /* The requests in waiter->flc_blocked are known to conflict with
878 * waiter, but might not conflict with blocker, or the requests
879 * and lock which block it. So they all need to be woken.
880 */
881 __locks_wake_up_blocks(waiter);
882}
883
884/* Must be called with flc_lock held. */
885static void locks_insert_block(struct file_lock_core *blocker,
886 struct file_lock_core *waiter,
887 bool conflict(struct file_lock_core *,
888 struct file_lock_core *))
889{
890 spin_lock(&blocked_lock_lock);
891 __locks_insert_block(blocker, waiter, conflict);
892 spin_unlock(&blocked_lock_lock);
893}
894
895/*
896 * Wake up processes blocked waiting for blocker.
897 *
898 * Must be called with the inode->flc_lock held!
899 */
900static void locks_wake_up_blocks(struct file_lock_core *blocker)
901{
902 /*
903 * Avoid taking global lock if list is empty. This is safe since new
904 * blocked requests are only added to the list under the flc_lock, and
905 * the flc_lock is always held here. Note that removal from the
906 * fl_blocked_requests list does not require the flc_lock, so we must
907 * recheck list_empty() after acquiring the blocked_lock_lock.
908 */
909 if (list_empty(&blocker->flc_blocked_requests))
910 return;
911
912 spin_lock(&blocked_lock_lock);
913 __locks_wake_up_blocks(blocker);
914 spin_unlock(&blocked_lock_lock);
915}
916
917static void
918locks_insert_lock_ctx(struct file_lock_core *fl, struct list_head *before)
919{
920 list_add_tail(&fl->flc_list, before);
921 locks_insert_global_locks(fl);
922}
923
924static void
925locks_unlink_lock_ctx(struct file_lock_core *fl)
926{
927 locks_delete_global_locks(fl);
928 list_del_init(&fl->flc_list);
929 locks_wake_up_blocks(fl);
930}
931
932static void
933locks_delete_lock_ctx(struct file_lock_core *fl, struct list_head *dispose)
934{
935 locks_unlink_lock_ctx(fl);
936 if (dispose)
937 list_add(&fl->flc_list, dispose);
938 else
939 locks_free_lock(file_lock(fl));
940}
941
942/* Determine if lock sys_fl blocks lock caller_fl. Common functionality
943 * checks for shared/exclusive status of overlapping locks.
944 */
945static bool locks_conflict(struct file_lock_core *caller_flc,
946 struct file_lock_core *sys_flc)
947{
948 if (sys_flc->flc_type == F_WRLCK)
949 return true;
950 if (caller_flc->flc_type == F_WRLCK)
951 return true;
952 return false;
953}
954
955/* Determine if lock sys_fl blocks lock caller_fl. POSIX specific
956 * checking before calling the locks_conflict().
957 */
958static bool posix_locks_conflict(struct file_lock_core *caller_flc,
959 struct file_lock_core *sys_flc)
960{
961 struct file_lock *caller_fl = file_lock(caller_flc);
962 struct file_lock *sys_fl = file_lock(sys_flc);
963
964 /* POSIX locks owned by the same process do not conflict with
965 * each other.
966 */
967 if (posix_same_owner(caller_flc, sys_flc))
968 return false;
969
970 /* Check whether they overlap */
971 if (!locks_overlap(caller_fl, sys_fl))
972 return false;
973
974 return locks_conflict(caller_flc, sys_flc);
975}
976
977/* Determine if lock sys_fl blocks lock caller_fl. Used on xx_GETLK
978 * path so checks for additional GETLK-specific things like F_UNLCK.
979 */
980static bool posix_test_locks_conflict(struct file_lock *caller_fl,
981 struct file_lock *sys_fl)
982{
983 struct file_lock_core *caller = &caller_fl->c;
984 struct file_lock_core *sys = &sys_fl->c;
985
986 /* F_UNLCK checks any locks on the same fd. */
987 if (lock_is_unlock(caller_fl)) {
988 if (!posix_same_owner(caller, sys))
989 return false;
990 return locks_overlap(caller_fl, sys_fl);
991 }
992 return posix_locks_conflict(caller, sys);
993}
994
995/* Determine if lock sys_fl blocks lock caller_fl. FLOCK specific
996 * checking before calling the locks_conflict().
997 */
998static bool flock_locks_conflict(struct file_lock_core *caller_flc,
999 struct file_lock_core *sys_flc)
1000{
1001 /* FLOCK locks referring to the same filp do not conflict with
1002 * each other.
1003 */
1004 if (caller_flc->flc_file == sys_flc->flc_file)
1005 return false;
1006
1007 return locks_conflict(caller_flc, sys_flc);
1008}
1009
1010void
1011posix_test_lock(struct file *filp, struct file_lock *fl)
1012{
1013 struct file_lock *cfl;
1014 struct file_lock_context *ctx;
1015 struct inode *inode = file_inode(filp);
1016 void *owner;
1017 void (*func)(void);
1018
1019 ctx = locks_inode_context(inode);
1020 if (!ctx || list_empty_careful(&ctx->flc_posix)) {
1021 fl->c.flc_type = F_UNLCK;
1022 return;
1023 }
1024
1025retry:
1026 spin_lock(&ctx->flc_lock);
1027 list_for_each_entry(cfl, &ctx->flc_posix, c.flc_list) {
1028 if (!posix_test_locks_conflict(fl, cfl))
1029 continue;
1030 if (cfl->fl_lmops && cfl->fl_lmops->lm_lock_expirable
1031 && (*cfl->fl_lmops->lm_lock_expirable)(cfl)) {
1032 owner = cfl->fl_lmops->lm_mod_owner;
1033 func = cfl->fl_lmops->lm_expire_lock;
1034 __module_get(owner);
1035 spin_unlock(&ctx->flc_lock);
1036 (*func)();
1037 module_put(owner);
1038 goto retry;
1039 }
1040 locks_copy_conflock(fl, cfl);
1041 goto out;
1042 }
1043 fl->c.flc_type = F_UNLCK;
1044out:
1045 spin_unlock(&ctx->flc_lock);
1046 return;
1047}
1048EXPORT_SYMBOL(posix_test_lock);
1049
1050/*
1051 * Deadlock detection:
1052 *
1053 * We attempt to detect deadlocks that are due purely to posix file
1054 * locks.
1055 *
1056 * We assume that a task can be waiting for at most one lock at a time.
1057 * So for any acquired lock, the process holding that lock may be
1058 * waiting on at most one other lock. That lock in turns may be held by
1059 * someone waiting for at most one other lock. Given a requested lock
1060 * caller_fl which is about to wait for a conflicting lock block_fl, we
1061 * follow this chain of waiters to ensure we are not about to create a
1062 * cycle.
1063 *
1064 * Since we do this before we ever put a process to sleep on a lock, we
1065 * are ensured that there is never a cycle; that is what guarantees that
1066 * the while() loop in posix_locks_deadlock() eventually completes.
1067 *
1068 * Note: the above assumption may not be true when handling lock
1069 * requests from a broken NFS client. It may also fail in the presence
1070 * of tasks (such as posix threads) sharing the same open file table.
1071 * To handle those cases, we just bail out after a few iterations.
1072 *
1073 * For FL_OFDLCK locks, the owner is the filp, not the files_struct.
1074 * Because the owner is not even nominally tied to a thread of
1075 * execution, the deadlock detection below can't reasonably work well. Just
1076 * skip it for those.
1077 *
1078 * In principle, we could do a more limited deadlock detection on FL_OFDLCK
1079 * locks that just checks for the case where two tasks are attempting to
1080 * upgrade from read to write locks on the same inode.
1081 */
1082
1083#define MAX_DEADLK_ITERATIONS 10
1084
1085/* Find a lock that the owner of the given @blocker is blocking on. */
1086static struct file_lock_core *what_owner_is_waiting_for(struct file_lock_core *blocker)
1087{
1088 struct file_lock_core *flc;
1089
1090 hash_for_each_possible(blocked_hash, flc, flc_link, posix_owner_key(blocker)) {
1091 if (posix_same_owner(flc, blocker)) {
1092 while (flc->flc_blocker)
1093 flc = flc->flc_blocker;
1094 return flc;
1095 }
1096 }
1097 return NULL;
1098}
1099
1100/* Must be called with the blocked_lock_lock held! */
1101static bool posix_locks_deadlock(struct file_lock *caller_fl,
1102 struct file_lock *block_fl)
1103{
1104 struct file_lock_core *caller = &caller_fl->c;
1105 struct file_lock_core *blocker = &block_fl->c;
1106 int i = 0;
1107
1108 lockdep_assert_held(&blocked_lock_lock);
1109
1110 /*
1111 * This deadlock detector can't reasonably detect deadlocks with
1112 * FL_OFDLCK locks, since they aren't owned by a process, per-se.
1113 */
1114 if (caller->flc_flags & FL_OFDLCK)
1115 return false;
1116
1117 while ((blocker = what_owner_is_waiting_for(blocker))) {
1118 if (i++ > MAX_DEADLK_ITERATIONS)
1119 return false;
1120 if (posix_same_owner(caller, blocker))
1121 return true;
1122 }
1123 return false;
1124}
1125
1126/* Try to create a FLOCK lock on filp. We always insert new FLOCK locks
1127 * after any leases, but before any posix locks.
1128 *
1129 * Note that if called with an FL_EXISTS argument, the caller may determine
1130 * whether or not a lock was successfully freed by testing the return
1131 * value for -ENOENT.
1132 */
1133static int flock_lock_inode(struct inode *inode, struct file_lock *request)
1134{
1135 struct file_lock *new_fl = NULL;
1136 struct file_lock *fl;
1137 struct file_lock_context *ctx;
1138 int error = 0;
1139 bool found = false;
1140 LIST_HEAD(dispose);
1141
1142 ctx = locks_get_lock_context(inode, request->c.flc_type);
1143 if (!ctx) {
1144 if (request->c.flc_type != F_UNLCK)
1145 return -ENOMEM;
1146 return (request->c.flc_flags & FL_EXISTS) ? -ENOENT : 0;
1147 }
1148
1149 if (!(request->c.flc_flags & FL_ACCESS) && (request->c.flc_type != F_UNLCK)) {
1150 new_fl = locks_alloc_lock();
1151 if (!new_fl)
1152 return -ENOMEM;
1153 }
1154
1155 percpu_down_read(&file_rwsem);
1156 spin_lock(&ctx->flc_lock);
1157 if (request->c.flc_flags & FL_ACCESS)
1158 goto find_conflict;
1159
1160 list_for_each_entry(fl, &ctx->flc_flock, c.flc_list) {
1161 if (request->c.flc_file != fl->c.flc_file)
1162 continue;
1163 if (request->c.flc_type == fl->c.flc_type)
1164 goto out;
1165 found = true;
1166 locks_delete_lock_ctx(&fl->c, &dispose);
1167 break;
1168 }
1169
1170 if (lock_is_unlock(request)) {
1171 if ((request->c.flc_flags & FL_EXISTS) && !found)
1172 error = -ENOENT;
1173 goto out;
1174 }
1175
1176find_conflict:
1177 list_for_each_entry(fl, &ctx->flc_flock, c.flc_list) {
1178 if (!flock_locks_conflict(&request->c, &fl->c))
1179 continue;
1180 error = -EAGAIN;
1181 if (!(request->c.flc_flags & FL_SLEEP))
1182 goto out;
1183 error = FILE_LOCK_DEFERRED;
1184 locks_insert_block(&fl->c, &request->c, flock_locks_conflict);
1185 goto out;
1186 }
1187 if (request->c.flc_flags & FL_ACCESS)
1188 goto out;
1189 locks_copy_lock(new_fl, request);
1190 locks_move_blocks(new_fl, request);
1191 locks_insert_lock_ctx(&new_fl->c, &ctx->flc_flock);
1192 new_fl = NULL;
1193 error = 0;
1194
1195out:
1196 spin_unlock(&ctx->flc_lock);
1197 percpu_up_read(&file_rwsem);
1198 if (new_fl)
1199 locks_free_lock(new_fl);
1200 locks_dispose_list(&dispose);
1201 trace_flock_lock_inode(inode, request, error);
1202 return error;
1203}
1204
1205static int posix_lock_inode(struct inode *inode, struct file_lock *request,
1206 struct file_lock *conflock)
1207{
1208 struct file_lock *fl, *tmp;
1209 struct file_lock *new_fl = NULL;
1210 struct file_lock *new_fl2 = NULL;
1211 struct file_lock *left = NULL;
1212 struct file_lock *right = NULL;
1213 struct file_lock_context *ctx;
1214 int error;
1215 bool added = false;
1216 LIST_HEAD(dispose);
1217 void *owner;
1218 void (*func)(void);
1219
1220 ctx = locks_get_lock_context(inode, request->c.flc_type);
1221 if (!ctx)
1222 return lock_is_unlock(request) ? 0 : -ENOMEM;
1223
1224 /*
1225 * We may need two file_lock structures for this operation,
1226 * so we get them in advance to avoid races.
1227 *
1228 * In some cases we can be sure, that no new locks will be needed
1229 */
1230 if (!(request->c.flc_flags & FL_ACCESS) &&
1231 (request->c.flc_type != F_UNLCK ||
1232 request->fl_start != 0 || request->fl_end != OFFSET_MAX)) {
1233 new_fl = locks_alloc_lock();
1234 new_fl2 = locks_alloc_lock();
1235 }
1236
1237retry:
1238 percpu_down_read(&file_rwsem);
1239 spin_lock(&ctx->flc_lock);
1240 /*
1241 * New lock request. Walk all POSIX locks and look for conflicts. If
1242 * there are any, either return error or put the request on the
1243 * blocker's list of waiters and the global blocked_hash.
1244 */
1245 if (request->c.flc_type != F_UNLCK) {
1246 list_for_each_entry(fl, &ctx->flc_posix, c.flc_list) {
1247 if (!posix_locks_conflict(&request->c, &fl->c))
1248 continue;
1249 if (fl->fl_lmops && fl->fl_lmops->lm_lock_expirable
1250 && (*fl->fl_lmops->lm_lock_expirable)(fl)) {
1251 owner = fl->fl_lmops->lm_mod_owner;
1252 func = fl->fl_lmops->lm_expire_lock;
1253 __module_get(owner);
1254 spin_unlock(&ctx->flc_lock);
1255 percpu_up_read(&file_rwsem);
1256 (*func)();
1257 module_put(owner);
1258 goto retry;
1259 }
1260 if (conflock)
1261 locks_copy_conflock(conflock, fl);
1262 error = -EAGAIN;
1263 if (!(request->c.flc_flags & FL_SLEEP))
1264 goto out;
1265 /*
1266 * Deadlock detection and insertion into the blocked
1267 * locks list must be done while holding the same lock!
1268 */
1269 error = -EDEADLK;
1270 spin_lock(&blocked_lock_lock);
1271 /*
1272 * Ensure that we don't find any locks blocked on this
1273 * request during deadlock detection.
1274 */
1275 __locks_wake_up_blocks(&request->c);
1276 if (likely(!posix_locks_deadlock(request, fl))) {
1277 error = FILE_LOCK_DEFERRED;
1278 __locks_insert_block(&fl->c, &request->c,
1279 posix_locks_conflict);
1280 }
1281 spin_unlock(&blocked_lock_lock);
1282 goto out;
1283 }
1284 }
1285
1286 /* If we're just looking for a conflict, we're done. */
1287 error = 0;
1288 if (request->c.flc_flags & FL_ACCESS)
1289 goto out;
1290
1291 /* Find the first old lock with the same owner as the new lock */
1292 list_for_each_entry(fl, &ctx->flc_posix, c.flc_list) {
1293 if (posix_same_owner(&request->c, &fl->c))
1294 break;
1295 }
1296
1297 /* Process locks with this owner. */
1298 list_for_each_entry_safe_from(fl, tmp, &ctx->flc_posix, c.flc_list) {
1299 if (!posix_same_owner(&request->c, &fl->c))
1300 break;
1301
1302 /* Detect adjacent or overlapping regions (if same lock type) */
1303 if (request->c.flc_type == fl->c.flc_type) {
1304 /* In all comparisons of start vs end, use
1305 * "start - 1" rather than "end + 1". If end
1306 * is OFFSET_MAX, end + 1 will become negative.
1307 */
1308 if (fl->fl_end < request->fl_start - 1)
1309 continue;
1310 /* If the next lock in the list has entirely bigger
1311 * addresses than the new one, insert the lock here.
1312 */
1313 if (fl->fl_start - 1 > request->fl_end)
1314 break;
1315
1316 /* If we come here, the new and old lock are of the
1317 * same type and adjacent or overlapping. Make one
1318 * lock yielding from the lower start address of both
1319 * locks to the higher end address.
1320 */
1321 if (fl->fl_start > request->fl_start)
1322 fl->fl_start = request->fl_start;
1323 else
1324 request->fl_start = fl->fl_start;
1325 if (fl->fl_end < request->fl_end)
1326 fl->fl_end = request->fl_end;
1327 else
1328 request->fl_end = fl->fl_end;
1329 if (added) {
1330 locks_delete_lock_ctx(&fl->c, &dispose);
1331 continue;
1332 }
1333 request = fl;
1334 added = true;
1335 } else {
1336 /* Processing for different lock types is a bit
1337 * more complex.
1338 */
1339 if (fl->fl_end < request->fl_start)
1340 continue;
1341 if (fl->fl_start > request->fl_end)
1342 break;
1343 if (lock_is_unlock(request))
1344 added = true;
1345 if (fl->fl_start < request->fl_start)
1346 left = fl;
1347 /* If the next lock in the list has a higher end
1348 * address than the new one, insert the new one here.
1349 */
1350 if (fl->fl_end > request->fl_end) {
1351 right = fl;
1352 break;
1353 }
1354 if (fl->fl_start >= request->fl_start) {
1355 /* The new lock completely replaces an old
1356 * one (This may happen several times).
1357 */
1358 if (added) {
1359 locks_delete_lock_ctx(&fl->c, &dispose);
1360 continue;
1361 }
1362 /*
1363 * Replace the old lock with new_fl, and
1364 * remove the old one. It's safe to do the
1365 * insert here since we know that we won't be
1366 * using new_fl later, and that the lock is
1367 * just replacing an existing lock.
1368 */
1369 error = -ENOLCK;
1370 if (!new_fl)
1371 goto out;
1372 locks_copy_lock(new_fl, request);
1373 locks_move_blocks(new_fl, request);
1374 request = new_fl;
1375 new_fl = NULL;
1376 locks_insert_lock_ctx(&request->c,
1377 &fl->c.flc_list);
1378 locks_delete_lock_ctx(&fl->c, &dispose);
1379 added = true;
1380 }
1381 }
1382 }
1383
1384 /*
1385 * The above code only modifies existing locks in case of merging or
1386 * replacing. If new lock(s) need to be inserted all modifications are
1387 * done below this, so it's safe yet to bail out.
1388 */
1389 error = -ENOLCK; /* "no luck" */
1390 if (right && left == right && !new_fl2)
1391 goto out;
1392
1393 error = 0;
1394 if (!added) {
1395 if (lock_is_unlock(request)) {
1396 if (request->c.flc_flags & FL_EXISTS)
1397 error = -ENOENT;
1398 goto out;
1399 }
1400
1401 if (!new_fl) {
1402 error = -ENOLCK;
1403 goto out;
1404 }
1405 locks_copy_lock(new_fl, request);
1406 locks_move_blocks(new_fl, request);
1407 locks_insert_lock_ctx(&new_fl->c, &fl->c.flc_list);
1408 fl = new_fl;
1409 new_fl = NULL;
1410 }
1411 if (right) {
1412 if (left == right) {
1413 /* The new lock breaks the old one in two pieces,
1414 * so we have to use the second new lock.
1415 */
1416 left = new_fl2;
1417 new_fl2 = NULL;
1418 locks_copy_lock(left, right);
1419 locks_insert_lock_ctx(&left->c, &fl->c.flc_list);
1420 }
1421 right->fl_start = request->fl_end + 1;
1422 locks_wake_up_blocks(&right->c);
1423 }
1424 if (left) {
1425 left->fl_end = request->fl_start - 1;
1426 locks_wake_up_blocks(&left->c);
1427 }
1428 out:
1429 trace_posix_lock_inode(inode, request, error);
1430 spin_unlock(&ctx->flc_lock);
1431 percpu_up_read(&file_rwsem);
1432 /*
1433 * Free any unused locks.
1434 */
1435 if (new_fl)
1436 locks_free_lock(new_fl);
1437 if (new_fl2)
1438 locks_free_lock(new_fl2);
1439 locks_dispose_list(&dispose);
1440
1441 return error;
1442}
1443
1444/**
1445 * posix_lock_file - Apply a POSIX-style lock to a file
1446 * @filp: The file to apply the lock to
1447 * @fl: The lock to be applied
1448 * @conflock: Place to return a copy of the conflicting lock, if found.
1449 *
1450 * Add a POSIX style lock to a file.
1451 * We merge adjacent & overlapping locks whenever possible.
1452 * POSIX locks are sorted by owner task, then by starting address
1453 *
1454 * Note that if called with an FL_EXISTS argument, the caller may determine
1455 * whether or not a lock was successfully freed by testing the return
1456 * value for -ENOENT.
1457 */
1458int posix_lock_file(struct file *filp, struct file_lock *fl,
1459 struct file_lock *conflock)
1460{
1461 return posix_lock_inode(file_inode(filp), fl, conflock);
1462}
1463EXPORT_SYMBOL(posix_lock_file);
1464
1465/**
1466 * posix_lock_inode_wait - Apply a POSIX-style lock to a file
1467 * @inode: inode of file to which lock request should be applied
1468 * @fl: The lock to be applied
1469 *
1470 * Apply a POSIX style lock request to an inode.
1471 */
1472static int posix_lock_inode_wait(struct inode *inode, struct file_lock *fl)
1473{
1474 int error;
1475 might_sleep ();
1476 for (;;) {
1477 error = posix_lock_inode(inode, fl, NULL);
1478 if (error != FILE_LOCK_DEFERRED)
1479 break;
1480 error = wait_event_interruptible(fl->c.flc_wait,
1481 list_empty(&fl->c.flc_blocked_member));
1482 if (error)
1483 break;
1484 }
1485 locks_delete_block(fl);
1486 return error;
1487}
1488
1489static void lease_clear_pending(struct file_lease *fl, int arg)
1490{
1491 switch (arg) {
1492 case F_UNLCK:
1493 fl->c.flc_flags &= ~FL_UNLOCK_PENDING;
1494 fallthrough;
1495 case F_RDLCK:
1496 fl->c.flc_flags &= ~FL_DOWNGRADE_PENDING;
1497 }
1498}
1499
1500/* We already had a lease on this file; just change its type */
1501int lease_modify(struct file_lease *fl, int arg, struct list_head *dispose)
1502{
1503 int error = assign_type(&fl->c, arg);
1504
1505 if (error)
1506 return error;
1507 lease_clear_pending(fl, arg);
1508 locks_wake_up_blocks(&fl->c);
1509 if (arg == F_UNLCK) {
1510 struct file *filp = fl->c.flc_file;
1511
1512 f_delown(filp);
1513 file_f_owner(filp)->signum = 0;
1514 fasync_helper(0, fl->c.flc_file, 0, &fl->fl_fasync);
1515 if (fl->fl_fasync != NULL) {
1516 printk(KERN_ERR "locks_delete_lock: fasync == %p\n", fl->fl_fasync);
1517 fl->fl_fasync = NULL;
1518 }
1519 locks_delete_lock_ctx(&fl->c, dispose);
1520 }
1521 return 0;
1522}
1523EXPORT_SYMBOL(lease_modify);
1524
1525static bool past_time(unsigned long then)
1526{
1527 if (!then)
1528 /* 0 is a special value meaning "this never expires": */
1529 return false;
1530 return time_after(jiffies, then);
1531}
1532
1533static void time_out_leases(struct inode *inode, struct list_head *dispose)
1534{
1535 struct file_lock_context *ctx = inode->i_flctx;
1536 struct file_lease *fl, *tmp;
1537 bool remove;
1538
1539 lockdep_assert_held(&ctx->flc_lock);
1540
1541 list_for_each_entry_safe(fl, tmp, &ctx->flc_lease, c.flc_list) {
1542 trace_time_out_leases(inode, fl);
1543 if (past_time(fl->fl_downgrade_time))
1544 lease_modify(fl, F_RDLCK, dispose);
1545
1546 remove = true;
1547 if (past_time(fl->fl_break_time)) {
1548 /*
1549 * Consult the lease manager when a lease break times
1550 * out to determine whether the lease should be disposed
1551 * of.
1552 */
1553 if (fl->fl_lmops && fl->fl_lmops->lm_breaker_timedout)
1554 remove = fl->fl_lmops->lm_breaker_timedout(fl);
1555 if (remove)
1556 lease_modify(fl, F_UNLCK, dispose);
1557 }
1558 }
1559}
1560
1561static bool leases_conflict(struct file_lock_core *lc, struct file_lock_core *bc)
1562{
1563 bool rc;
1564 struct file_lease *lease = file_lease(lc);
1565 struct file_lease *breaker = file_lease(bc);
1566
1567 if (lease->fl_lmops->lm_breaker_owns_lease
1568 && lease->fl_lmops->lm_breaker_owns_lease(lease))
1569 return false;
1570 if ((bc->flc_flags & FL_LAYOUT) != (lc->flc_flags & FL_LAYOUT)) {
1571 rc = false;
1572 goto trace;
1573 }
1574 if ((bc->flc_flags & FL_DELEG) && (lc->flc_flags & FL_LEASE)) {
1575 rc = false;
1576 goto trace;
1577 }
1578
1579 rc = locks_conflict(bc, lc);
1580trace:
1581 trace_leases_conflict(rc, lease, breaker);
1582 return rc;
1583}
1584
1585#define IGNORE_MASK (FL_IGN_DIR_CREATE | FL_IGN_DIR_DELETE | FL_IGN_DIR_RENAME)
1586
1587/**
1588 * inode_lease_ignore_mask - return union of all ignored inode events for this inode
1589 * @inode: inode of which to get ignore mask
1590 *
1591 * Walk the list of leases, and return the result of all of
1592 * their FL_IGN_DIR_* bits or'ed together.
1593 */
1594u32
1595inode_lease_ignore_mask(struct inode *inode)
1596{
1597 struct file_lock_context *ctx;
1598 struct file_lock_core *flc;
1599 u32 mask = 0;
1600
1601 ctx = locks_inode_context(inode);
1602 if (!ctx)
1603 return 0;
1604
1605 spin_lock(&ctx->flc_lock);
1606 list_for_each_entry(flc, &ctx->flc_lease, flc_list) {
1607 mask |= flc->flc_flags & IGNORE_MASK;
1608 /* If we already have everything, we can stop */
1609 if (mask == IGNORE_MASK)
1610 break;
1611 }
1612 spin_unlock(&ctx->flc_lock);
1613 return mask;
1614}
1615EXPORT_SYMBOL_GPL(inode_lease_ignore_mask);
1616
1617static bool
1618ignore_dir_deleg_break(struct file_lease *fl, unsigned int flags)
1619{
1620 if ((flags & LEASE_BREAK_DIR_CREATE) && (fl->c.flc_flags & FL_IGN_DIR_CREATE))
1621 return true;
1622 if ((flags & LEASE_BREAK_DIR_DELETE) && (fl->c.flc_flags & FL_IGN_DIR_DELETE))
1623 return true;
1624 if ((flags & LEASE_BREAK_DIR_RENAME) && (fl->c.flc_flags & FL_IGN_DIR_RENAME))
1625 return true;
1626
1627 return false;
1628}
1629
1630static unsigned int
1631break_lease_flags_to_type(unsigned int flags)
1632{
1633 if (flags & LEASE_BREAK_LEASE)
1634 return FL_LEASE;
1635 else if (flags & LEASE_BREAK_DELEG)
1636 return FL_DELEG;
1637 else if (flags & LEASE_BREAK_LAYOUT)
1638 return FL_LAYOUT;
1639 else
1640 return 0;
1641
1642}
1643
1644static struct file_lease *
1645first_visible_lease(struct inode *inode, struct file_lease *new_fl, unsigned int flags)
1646{
1647 struct file_lock_context *ctx = locks_inode_context(inode);
1648 struct file_lease *fl;
1649
1650 lockdep_assert_held(&ctx->flc_lock);
1651
1652 list_for_each_entry(fl, &ctx->flc_lease, c.flc_list) {
1653 if (!leases_conflict(&fl->c, &new_fl->c))
1654 continue;
1655 if (S_ISDIR(inode->i_mode) && ignore_dir_deleg_break(fl, flags))
1656 continue;
1657 return fl;
1658 }
1659 return NULL;
1660}
1661
1662
1663/**
1664 * __break_lease - revoke all outstanding leases on file
1665 * @inode: the inode of the file to return
1666 * @flags: LEASE_BREAK_* flags
1667 *
1668 * break_lease (inlined for speed) has checked there already is at least
1669 * some kind of lock (maybe a lease) on this file. Leases and Delegations
1670 * are broken on a call to open() or truncate(). Delegations are also
1671 * broken on any event that would change the ctime. Directory delegations
1672 * are broken whenever the directory changes (unless the delegation is set
1673 * up to ignore the event). This function can block waiting for the lease
1674 * break unless you specify LEASE_BREAK_NONBLOCK.
1675 */
1676int __break_lease(struct inode *inode, unsigned int flags)
1677{
1678 struct file_lease *new_fl, *fl, *tmp;
1679 struct file_lock_context *ctx;
1680 unsigned long break_time;
1681 unsigned int type;
1682 LIST_HEAD(dispose);
1683 bool want_write = !(flags & LEASE_BREAK_OPEN_RDONLY);
1684 int error = 0;
1685
1686 trace_break_lease(inode, flags);
1687
1688 type = break_lease_flags_to_type(flags);
1689 if (!type)
1690 return -EINVAL;
1691
1692 new_fl = lease_alloc(NULL, type, want_write ? F_WRLCK : F_RDLCK);
1693 if (IS_ERR(new_fl))
1694 return PTR_ERR(new_fl);
1695
1696 /* typically we will check that ctx is non-NULL before calling */
1697 ctx = locks_inode_context(inode);
1698 if (!ctx) {
1699 WARN_ON_ONCE(1);
1700 goto free_lock;
1701 }
1702
1703 percpu_down_read(&file_rwsem);
1704 spin_lock(&ctx->flc_lock);
1705
1706 time_out_leases(inode, &dispose);
1707
1708 if (!first_visible_lease(inode, new_fl, flags))
1709 goto out;
1710
1711 break_time = 0;
1712 if (lease_break_time > 0) {
1713 break_time = jiffies + lease_break_time * HZ;
1714 if (break_time == 0)
1715 break_time++; /* so that 0 means no break time */
1716 }
1717
1718 list_for_each_entry_safe(fl, tmp, &ctx->flc_lease, c.flc_list) {
1719 if (!leases_conflict(&fl->c, &new_fl->c))
1720 continue;
1721 if (S_ISDIR(inode->i_mode) && ignore_dir_deleg_break(fl, flags))
1722 continue;
1723 if (want_write) {
1724 if (fl->c.flc_flags & FL_UNLOCK_PENDING)
1725 continue;
1726 fl->c.flc_flags |= FL_UNLOCK_PENDING;
1727 fl->fl_break_time = break_time;
1728 } else {
1729 if (lease_breaking(fl))
1730 continue;
1731 fl->c.flc_flags |= FL_DOWNGRADE_PENDING;
1732 fl->fl_downgrade_time = break_time;
1733 }
1734 if (fl->fl_lmops->lm_break(fl))
1735 locks_delete_lock_ctx(&fl->c, &dispose);
1736 }
1737
1738 fl = first_visible_lease(inode, new_fl, flags);
1739 if (!fl)
1740 goto out;
1741
1742 if (flags & LEASE_BREAK_NONBLOCK) {
1743 trace_break_lease_noblock(inode, new_fl);
1744 error = -EWOULDBLOCK;
1745 goto out;
1746 }
1747
1748restart:
1749 break_time = fl->fl_break_time;
1750 if (break_time != 0) {
1751 if (time_after(jiffies, break_time)) {
1752 fl->fl_break_time = jiffies + lease_break_time * HZ;
1753 break_time = lease_break_time * HZ;
1754 } else
1755 break_time -= jiffies;
1756 } else
1757 break_time++;
1758 locks_insert_block(&fl->c, &new_fl->c, leases_conflict);
1759 trace_break_lease_block(inode, fl);
1760 spin_unlock(&ctx->flc_lock);
1761 percpu_up_read(&file_rwsem);
1762
1763 lease_dispose_list(&dispose);
1764 error = wait_event_interruptible_timeout(new_fl->c.flc_wait,
1765 list_empty(&new_fl->c.flc_blocked_member),
1766 break_time);
1767
1768 percpu_down_read(&file_rwsem);
1769 spin_lock(&ctx->flc_lock);
1770 trace_break_lease_unblock(inode, NULL);
1771 __locks_delete_block(&new_fl->c);
1772 if (error >= 0) {
1773 /*
1774 * Wait for the next conflicting lease that has not been
1775 * broken yet
1776 */
1777 if (error == 0)
1778 time_out_leases(inode, &dispose);
1779 fl = first_visible_lease(inode, new_fl, flags);
1780 if (fl)
1781 goto restart;
1782 error = 0;
1783 }
1784out:
1785 spin_unlock(&ctx->flc_lock);
1786 percpu_up_read(&file_rwsem);
1787 lease_dispose_list(&dispose);
1788free_lock:
1789 locks_free_lease(new_fl);
1790 return error;
1791}
1792EXPORT_SYMBOL(__break_lease);
1793
1794/**
1795 * lease_get_mtime - update modified time of an inode with exclusive lease
1796 * @inode: the inode
1797 * @time: pointer to a timespec which contains the last modified time
1798 *
1799 * This is to force NFS clients to flush their caches for files with
1800 * exclusive leases. The justification is that if someone has an
1801 * exclusive lease, then they could be modifying it.
1802 */
1803void lease_get_mtime(struct inode *inode, struct timespec64 *time)
1804{
1805 bool has_lease = false;
1806 struct file_lock_context *ctx;
1807 struct file_lock_core *flc;
1808
1809 ctx = locks_inode_context(inode);
1810 if (ctx && !list_empty_careful(&ctx->flc_lease)) {
1811 spin_lock(&ctx->flc_lock);
1812 flc = list_first_entry_or_null(&ctx->flc_lease,
1813 struct file_lock_core, flc_list);
1814 if (flc && flc->flc_type == F_WRLCK)
1815 has_lease = true;
1816 spin_unlock(&ctx->flc_lock);
1817 }
1818
1819 if (has_lease)
1820 *time = current_time(inode);
1821}
1822EXPORT_SYMBOL(lease_get_mtime);
1823
1824/**
1825 * __fcntl_getlease - Enquire what lease is currently active
1826 * @filp: the file
1827 * @flavor: type of lease flags to check
1828 *
1829 * The value returned by this function will be one of
1830 * (if no lease break is pending):
1831 *
1832 * %F_RDLCK to indicate a shared lease is held.
1833 *
1834 * %F_WRLCK to indicate an exclusive lease is held.
1835 *
1836 * %F_UNLCK to indicate no lease is held.
1837 *
1838 * (if a lease break is pending):
1839 *
1840 * %F_RDLCK to indicate an exclusive lease needs to be
1841 * changed to a shared lease (or removed).
1842 *
1843 * %F_UNLCK to indicate the lease needs to be removed.
1844 *
1845 * XXX: sfr & willy disagree over whether F_INPROGRESS
1846 * should be returned to userspace.
1847 */
1848static int __fcntl_getlease(struct file *filp, unsigned int flavor)
1849{
1850 struct file_lease *fl;
1851 struct inode *inode = file_inode(filp);
1852 struct file_lock_context *ctx;
1853 int type = F_UNLCK;
1854 LIST_HEAD(dispose);
1855
1856 ctx = locks_inode_context(inode);
1857 if (ctx && !list_empty_careful(&ctx->flc_lease)) {
1858 percpu_down_read(&file_rwsem);
1859 spin_lock(&ctx->flc_lock);
1860 time_out_leases(inode, &dispose);
1861 list_for_each_entry(fl, &ctx->flc_lease, c.flc_list) {
1862 if (fl->c.flc_file != filp)
1863 continue;
1864 if (fl->c.flc_flags & flavor)
1865 type = target_leasetype(fl);
1866 break;
1867 }
1868 spin_unlock(&ctx->flc_lock);
1869 percpu_up_read(&file_rwsem);
1870
1871 lease_dispose_list(&dispose);
1872 }
1873 return type;
1874}
1875
1876int fcntl_getlease(struct file *filp)
1877{
1878 return __fcntl_getlease(filp, FL_LEASE);
1879}
1880
1881int fcntl_getdeleg(struct file *filp, struct delegation *deleg)
1882{
1883 if (deleg->d_flags != 0 || deleg->__pad != 0)
1884 return -EINVAL;
1885 deleg->d_type = __fcntl_getlease(filp, FL_DELEG);
1886 return 0;
1887}
1888
1889static int
1890generic_add_lease(struct file *filp, int arg, struct file_lease **flp, void **priv)
1891{
1892 struct file_lease *fl, *my_fl = NULL, *lease;
1893 struct inode *inode = file_inode(filp);
1894 struct file_lock_context *ctx;
1895 bool is_deleg = (*flp)->c.flc_flags & FL_DELEG;
1896 int error;
1897 LIST_HEAD(dispose);
1898
1899 lease = *flp;
1900 trace_generic_add_lease(inode, lease);
1901
1902 error = file_f_owner_allocate(filp);
1903 if (error)
1904 return error;
1905
1906 /* Note that arg is never F_UNLCK here */
1907 ctx = locks_get_lock_context(inode, arg);
1908 if (!ctx)
1909 return -ENOMEM;
1910
1911 /*
1912 * In the delegation case we need mutual exclusion with
1913 * a number of operations that take the i_rwsem. We trylock
1914 * because delegations are an optional optimization, and if
1915 * there's some chance of a conflict--we'd rather not
1916 * bother, maybe that's a sign this just isn't a good file to
1917 * hand out a delegation on.
1918 */
1919 if (is_deleg && !inode_trylock(inode))
1920 return -EAGAIN;
1921
1922 percpu_down_read(&file_rwsem);
1923 spin_lock(&ctx->flc_lock);
1924 time_out_leases(inode, &dispose);
1925 error = lease->fl_lmops->lm_open_conflict(filp, arg);
1926 if (error)
1927 goto out;
1928
1929 /*
1930 * At this point, we know that if there is an exclusive
1931 * lease on this file, then we hold it on this filp
1932 * (otherwise our open of this file would have blocked).
1933 * And if we are trying to acquire an exclusive lease,
1934 * then the file is not open by anyone (including us)
1935 * except for this filp.
1936 */
1937 error = -EAGAIN;
1938 list_for_each_entry(fl, &ctx->flc_lease, c.flc_list) {
1939 if (fl->c.flc_file == filp &&
1940 fl->c.flc_owner == lease->c.flc_owner) {
1941 my_fl = fl;
1942 continue;
1943 }
1944
1945 /*
1946 * No exclusive leases if someone else has a lease on
1947 * this file:
1948 */
1949 if (arg == F_WRLCK)
1950 goto out;
1951 /*
1952 * Modifying our existing lease is OK, but no getting a
1953 * new lease if someone else is opening for write:
1954 */
1955 if (fl->c.flc_flags & FL_UNLOCK_PENDING)
1956 goto out;
1957 }
1958
1959 if (my_fl != NULL) {
1960 lease = my_fl;
1961 error = lease->fl_lmops->lm_change(lease, arg, &dispose);
1962 if (error)
1963 goto out;
1964 goto out_setup;
1965 }
1966
1967 error = -EINVAL;
1968 if (!leases_enable)
1969 goto out;
1970
1971 locks_insert_lock_ctx(&lease->c, &ctx->flc_lease);
1972 /*
1973 * The check in break_lease() is lockless. It's possible for another
1974 * open to race in after we did the earlier check for a conflicting
1975 * open but before the lease was inserted. Check again for a
1976 * conflicting open and cancel the lease if there is one.
1977 *
1978 * We also add a barrier here to ensure that the insertion of the lock
1979 * precedes these checks.
1980 */
1981 smp_mb();
1982 error = lease->fl_lmops->lm_open_conflict(filp, arg);
1983 if (error) {
1984 locks_unlink_lock_ctx(&lease->c);
1985 goto out;
1986 }
1987
1988out_setup:
1989 if (lease->fl_lmops->lm_setup)
1990 lease->fl_lmops->lm_setup(lease, priv);
1991out:
1992 spin_unlock(&ctx->flc_lock);
1993 percpu_up_read(&file_rwsem);
1994 lease_dispose_list(&dispose);
1995 if (is_deleg)
1996 inode_unlock(inode);
1997 if (!error && !my_fl)
1998 *flp = NULL;
1999 return error;
2000}
2001
2002static int generic_delete_lease(struct file *filp, void *owner)
2003{
2004 int error = -EAGAIN;
2005 struct file_lease *fl, *victim = NULL;
2006 struct inode *inode = file_inode(filp);
2007 struct file_lock_context *ctx;
2008 LIST_HEAD(dispose);
2009
2010 ctx = locks_inode_context(inode);
2011 if (!ctx) {
2012 trace_generic_delete_lease(inode, NULL);
2013 return error;
2014 }
2015
2016 percpu_down_read(&file_rwsem);
2017 spin_lock(&ctx->flc_lock);
2018 list_for_each_entry(fl, &ctx->flc_lease, c.flc_list) {
2019 if (fl->c.flc_file == filp &&
2020 fl->c.flc_owner == owner) {
2021 victim = fl;
2022 break;
2023 }
2024 }
2025 trace_generic_delete_lease(inode, victim);
2026 if (victim)
2027 error = fl->fl_lmops->lm_change(victim, F_UNLCK, &dispose);
2028 spin_unlock(&ctx->flc_lock);
2029 percpu_up_read(&file_rwsem);
2030 lease_dispose_list(&dispose);
2031 return error;
2032}
2033
2034/**
2035 * generic_setlease - sets a lease on an open file
2036 * @filp: file pointer
2037 * @arg: type of lease to obtain
2038 * @flp: input - file_lock to use, output - file_lock inserted
2039 * @priv: private data for lm_setup (may be NULL if lm_setup
2040 * doesn't require it)
2041 *
2042 * The (input) flp->fl_lmops->lm_break function is required
2043 * by break_lease().
2044 */
2045int generic_setlease(struct file *filp, int arg, struct file_lease **flp,
2046 void **priv)
2047{
2048 struct inode *inode = file_inode(filp);
2049
2050 if (!S_ISREG(inode->i_mode) && !S_ISDIR(inode->i_mode))
2051 return -EINVAL;
2052
2053 switch (arg) {
2054 case F_UNLCK:
2055 return generic_delete_lease(filp, *priv);
2056 case F_WRLCK:
2057 if (S_ISDIR(inode->i_mode))
2058 return -EINVAL;
2059 fallthrough;
2060 case F_RDLCK:
2061 if (!(*flp)->fl_lmops->lm_break) {
2062 WARN_ON_ONCE(1);
2063 return -ENOLCK;
2064 }
2065
2066 return generic_add_lease(filp, arg, flp, priv);
2067 default:
2068 return -EINVAL;
2069 }
2070}
2071EXPORT_SYMBOL(generic_setlease);
2072
2073/*
2074 * Kernel subsystems can register to be notified on any attempt to set
2075 * a new lease with the lease_notifier_chain. This is used by (e.g.) nfsd
2076 * to close files that it may have cached when there is an attempt to set a
2077 * conflicting lease.
2078 */
2079static struct srcu_notifier_head lease_notifier_chain;
2080
2081static inline void
2082lease_notifier_chain_init(void)
2083{
2084 srcu_init_notifier_head(&lease_notifier_chain);
2085}
2086
2087static inline void
2088setlease_notifier(int arg, struct file_lease *lease)
2089{
2090 if (arg != F_UNLCK)
2091 srcu_notifier_call_chain(&lease_notifier_chain, arg, lease);
2092}
2093
2094int lease_register_notifier(struct notifier_block *nb)
2095{
2096 return srcu_notifier_chain_register(&lease_notifier_chain, nb);
2097}
2098EXPORT_SYMBOL_GPL(lease_register_notifier);
2099
2100void lease_unregister_notifier(struct notifier_block *nb)
2101{
2102 srcu_notifier_chain_unregister(&lease_notifier_chain, nb);
2103}
2104EXPORT_SYMBOL_GPL(lease_unregister_notifier);
2105
2106
2107int
2108kernel_setlease(struct file *filp, int arg, struct file_lease **lease, void **priv)
2109{
2110 if (lease)
2111 setlease_notifier(arg, *lease);
2112 if (filp->f_op->setlease)
2113 return filp->f_op->setlease(filp, arg, lease, priv);
2114 return -EINVAL;
2115}
2116EXPORT_SYMBOL_GPL(kernel_setlease);
2117
2118/**
2119 * vfs_setlease - sets a lease on an open file
2120 * @filp: file pointer
2121 * @arg: type of lease to obtain
2122 * @lease: file_lock to use when adding a lease
2123 * @priv: private info for lm_setup when adding a lease (may be
2124 * NULL if lm_setup doesn't require it)
2125 *
2126 * Call this to establish a lease on the file. The "lease" argument is not
2127 * used for F_UNLCK requests and may be NULL. For commands that set or alter
2128 * an existing lease, the ``(*lease)->fl_lmops->lm_break`` operation must be
2129 * set; if not, this function will return -ENOLCK (and generate a scary-looking
2130 * stack trace).
2131 *
2132 * The "priv" pointer is passed directly to the lm_setup function as-is. It
2133 * may be NULL if the lm_setup operation doesn't require it.
2134 */
2135int
2136vfs_setlease(struct file *filp, int arg, struct file_lease **lease, void **priv)
2137{
2138 struct inode *inode = file_inode(filp);
2139 vfsuid_t vfsuid = i_uid_into_vfsuid(file_mnt_idmap(filp), inode);
2140 int error;
2141
2142 if ((!vfsuid_eq_kuid(vfsuid, current_fsuid())) && !capable(CAP_LEASE))
2143 return -EACCES;
2144 error = security_file_lock(filp, arg);
2145 if (error)
2146 return error;
2147 return kernel_setlease(filp, arg, lease, priv);
2148}
2149EXPORT_SYMBOL_GPL(vfs_setlease);
2150
2151static int do_fcntl_add_lease(unsigned int fd, struct file *filp, unsigned int flavor, int arg)
2152{
2153 struct file_lease *fl;
2154 struct fasync_struct *new;
2155 int error;
2156
2157 fl = lease_alloc(filp, flavor, arg);
2158 if (IS_ERR(fl))
2159 return PTR_ERR(fl);
2160
2161 new = fasync_alloc();
2162 if (!new) {
2163 locks_free_lease(fl);
2164 return -ENOMEM;
2165 }
2166 new->fa_fd = fd;
2167
2168 error = vfs_setlease(filp, arg, &fl, (void **)&new);
2169 if (fl)
2170 locks_free_lease(fl);
2171 if (new)
2172 fasync_free(new);
2173 return error;
2174}
2175
2176/**
2177 * fcntl_setlease - sets a lease on an open file
2178 * @fd: open file descriptor
2179 * @filp: file pointer
2180 * @arg: type of lease to obtain
2181 *
2182 * Call this fcntl to establish a lease on the file.
2183 * Note that you also need to call %F_SETSIG to
2184 * receive a signal when the lease is broken.
2185 */
2186int fcntl_setlease(unsigned int fd, struct file *filp, int arg)
2187{
2188 if (S_ISDIR(file_inode(filp)->i_mode))
2189 return -EINVAL;
2190
2191 if (arg == F_UNLCK)
2192 return vfs_setlease(filp, F_UNLCK, NULL, (void **)&filp);
2193 return do_fcntl_add_lease(fd, filp, FL_LEASE, arg);
2194}
2195
2196/**
2197 * fcntl_setdeleg - sets a delegation on an open file
2198 * @fd: open file descriptor
2199 * @filp: file pointer
2200 * @deleg: delegation request from userland
2201 *
2202 * Call this fcntl to establish a delegation on the file.
2203 * Note that you also need to call %F_SETSIG to
2204 * receive a signal when the lease is broken.
2205 */
2206int fcntl_setdeleg(unsigned int fd, struct file *filp, struct delegation *deleg)
2207{
2208 /* For now, no flags are supported */
2209 if (deleg->d_flags != 0 || deleg->__pad != 0)
2210 return -EINVAL;
2211
2212 if (deleg->d_type == F_UNLCK)
2213 return vfs_setlease(filp, F_UNLCK, NULL, (void **)&filp);
2214 return do_fcntl_add_lease(fd, filp, FL_DELEG, deleg->d_type);
2215}
2216
2217/**
2218 * flock_lock_inode_wait - Apply a FLOCK-style lock to a file
2219 * @inode: inode of the file to apply to
2220 * @fl: The lock to be applied
2221 *
2222 * Apply a FLOCK style lock request to an inode.
2223 */
2224static int flock_lock_inode_wait(struct inode *inode, struct file_lock *fl)
2225{
2226 int error;
2227 might_sleep();
2228 for (;;) {
2229 error = flock_lock_inode(inode, fl);
2230 if (error != FILE_LOCK_DEFERRED)
2231 break;
2232 error = wait_event_interruptible(fl->c.flc_wait,
2233 list_empty(&fl->c.flc_blocked_member));
2234 if (error)
2235 break;
2236 }
2237 locks_delete_block(fl);
2238 return error;
2239}
2240
2241/**
2242 * locks_lock_inode_wait - Apply a lock to an inode
2243 * @inode: inode of the file to apply to
2244 * @fl: The lock to be applied
2245 *
2246 * Apply a POSIX or FLOCK style lock request to an inode.
2247 */
2248int locks_lock_inode_wait(struct inode *inode, struct file_lock *fl)
2249{
2250 int res = 0;
2251 switch (fl->c.flc_flags & (FL_POSIX|FL_FLOCK)) {
2252 case FL_POSIX:
2253 res = posix_lock_inode_wait(inode, fl);
2254 break;
2255 case FL_FLOCK:
2256 res = flock_lock_inode_wait(inode, fl);
2257 break;
2258 default:
2259 BUG();
2260 }
2261 return res;
2262}
2263EXPORT_SYMBOL(locks_lock_inode_wait);
2264
2265/**
2266 * sys_flock: - flock() system call.
2267 * @fd: the file descriptor to lock.
2268 * @cmd: the type of lock to apply.
2269 *
2270 * Apply a %FL_FLOCK style lock to an open file descriptor.
2271 * The @cmd can be one of:
2272 *
2273 * - %LOCK_SH -- a shared lock.
2274 * - %LOCK_EX -- an exclusive lock.
2275 * - %LOCK_UN -- remove an existing lock.
2276 * - %LOCK_MAND -- a 'mandatory' flock. (DEPRECATED)
2277 *
2278 * %LOCK_MAND support has been removed from the kernel.
2279 */
2280SYSCALL_DEFINE2(flock, unsigned int, fd, unsigned int, cmd)
2281{
2282 int can_sleep, error, type;
2283 struct file_lock fl;
2284
2285 /*
2286 * LOCK_MAND locks were broken for a long time in that they never
2287 * conflicted with one another and didn't prevent any sort of open,
2288 * read or write activity.
2289 *
2290 * Just ignore these requests now, to preserve legacy behavior, but
2291 * throw a warning to let people know that they don't actually work.
2292 */
2293 if (cmd & LOCK_MAND) {
2294 pr_warn_once("%s(%d): Attempt to set a LOCK_MAND lock via flock(2). This support has been removed and the request ignored.\n", current->comm, current->pid);
2295 return 0;
2296 }
2297
2298 type = flock_translate_cmd(cmd & ~LOCK_NB);
2299 if (type < 0)
2300 return type;
2301
2302 CLASS(fd, f)(fd);
2303 if (fd_empty(f))
2304 return -EBADF;
2305
2306 if (type != F_UNLCK && !(fd_file(f)->f_mode & (FMODE_READ | FMODE_WRITE)))
2307 return -EBADF;
2308
2309 flock_make_lock(fd_file(f), &fl, type);
2310
2311 error = security_file_lock(fd_file(f), fl.c.flc_type);
2312 if (error)
2313 return error;
2314
2315 can_sleep = !(cmd & LOCK_NB);
2316 if (can_sleep)
2317 fl.c.flc_flags |= FL_SLEEP;
2318
2319 if (fd_file(f)->f_op->flock)
2320 error = fd_file(f)->f_op->flock(fd_file(f),
2321 (can_sleep) ? F_SETLKW : F_SETLK,
2322 &fl);
2323 else
2324 error = locks_lock_file_wait(fd_file(f), &fl);
2325
2326 locks_release_private(&fl);
2327 return error;
2328}
2329
2330/**
2331 * vfs_test_lock - test file byte range lock
2332 * @filp: The file to test lock for
2333 * @fl: The byte-range in the file to test; also used to hold result
2334 *
2335 * On entry, @fl does not contain a lock, but identifies a range (fl_start, fl_end)
2336 * in the file (c.flc_file), and an owner (c.flc_owner) for whom existing locks
2337 * should be ignored. c.flc_type and c.flc_flags are ignored.
2338 * Both fl_lmops and fl_ops in @fl must be NULL.
2339 * Returns -ERRNO on failure. Indicates presence of conflicting lock by
2340 * setting fl->fl_type to something other than F_UNLCK.
2341 *
2342 * If vfs_test_lock() does find a lock and return it, the caller must
2343 * use locks_free_lock() or locks_release_private() on the returned lock.
2344 */
2345int vfs_test_lock(struct file *filp, struct file_lock *fl)
2346{
2347 int error = 0;
2348
2349 WARN_ON_ONCE(fl->fl_ops || fl->fl_lmops);
2350 WARN_ON_ONCE(filp != fl->c.flc_file);
2351 if (filp->f_op->lock)
2352 error = filp->f_op->lock(filp, F_GETLK, fl);
2353 else
2354 posix_test_lock(filp, fl);
2355
2356 /*
2357 * We don't expect FILE_LOCK_DEFERRED and callers cannot
2358 * handle it.
2359 */
2360 if (WARN_ON_ONCE(error == FILE_LOCK_DEFERRED))
2361 error = -EIO;
2362
2363 return error;
2364}
2365EXPORT_SYMBOL_GPL(vfs_test_lock);
2366
2367/**
2368 * locks_translate_pid - translate a file_lock's fl_pid number into a namespace
2369 * @fl: The file_lock who's fl_pid should be translated
2370 * @ns: The namespace into which the pid should be translated
2371 *
2372 * Used to translate a fl_pid into a namespace virtual pid number
2373 */
2374static pid_t locks_translate_pid(struct file_lock_core *fl, struct pid_namespace *ns)
2375{
2376 pid_t vnr;
2377 struct pid *pid;
2378
2379 if (fl->flc_flags & FL_OFDLCK)
2380 return -1;
2381
2382 /* Remote locks report a negative pid value */
2383 if (fl->flc_pid <= 0)
2384 return fl->flc_pid;
2385
2386 /*
2387 * If the flock owner process is dead and its pid has been already
2388 * freed, the translation below won't work, but we still want to show
2389 * flock owner pid number in init pidns.
2390 */
2391 if (ns == &init_pid_ns)
2392 return (pid_t) fl->flc_pid;
2393
2394 rcu_read_lock();
2395 pid = find_pid_ns(fl->flc_pid, &init_pid_ns);
2396 vnr = pid_nr_ns(pid, ns);
2397 rcu_read_unlock();
2398 return vnr;
2399}
2400
2401static int posix_lock_to_flock(struct flock *flock, struct file_lock *fl)
2402{
2403 flock->l_pid = locks_translate_pid(&fl->c, task_active_pid_ns(current));
2404#if BITS_PER_LONG == 32
2405 /*
2406 * Make sure we can represent the posix lock via
2407 * legacy 32bit flock.
2408 */
2409 if (fl->fl_start > OFFT_OFFSET_MAX)
2410 return -EOVERFLOW;
2411 if (fl->fl_end != OFFSET_MAX && fl->fl_end > OFFT_OFFSET_MAX)
2412 return -EOVERFLOW;
2413#endif
2414 flock->l_start = fl->fl_start;
2415 flock->l_len = fl->fl_end == OFFSET_MAX ? 0 :
2416 fl->fl_end - fl->fl_start + 1;
2417 flock->l_whence = 0;
2418 flock->l_type = fl->c.flc_type;
2419 return 0;
2420}
2421
2422#if BITS_PER_LONG == 32
2423static void posix_lock_to_flock64(struct flock64 *flock, struct file_lock *fl)
2424{
2425 flock->l_pid = locks_translate_pid(&fl->c, task_active_pid_ns(current));
2426 flock->l_start = fl->fl_start;
2427 flock->l_len = fl->fl_end == OFFSET_MAX ? 0 :
2428 fl->fl_end - fl->fl_start + 1;
2429 flock->l_whence = 0;
2430 flock->l_type = fl->c.flc_type;
2431}
2432#endif
2433
2434/* Report the first existing lock that would conflict with l.
2435 * This implements the F_GETLK command of fcntl().
2436 */
2437int fcntl_getlk(struct file *filp, unsigned int cmd, struct flock *flock)
2438{
2439 struct file_lock *fl;
2440 int error;
2441
2442 fl = locks_alloc_lock();
2443 if (fl == NULL)
2444 return -ENOMEM;
2445 error = -EINVAL;
2446 if (cmd != F_OFD_GETLK && flock->l_type != F_RDLCK
2447 && flock->l_type != F_WRLCK)
2448 goto out;
2449
2450 error = flock_to_posix_lock(filp, fl, flock);
2451 if (error)
2452 goto out;
2453
2454 if (cmd == F_OFD_GETLK) {
2455 error = -EINVAL;
2456 if (flock->l_pid != 0)
2457 goto out;
2458
2459 fl->c.flc_flags |= FL_OFDLCK;
2460 fl->c.flc_owner = filp;
2461 }
2462
2463 error = vfs_test_lock(filp, fl);
2464 if (error)
2465 goto out;
2466
2467 flock->l_type = fl->c.flc_type;
2468 if (fl->c.flc_type != F_UNLCK) {
2469 error = posix_lock_to_flock(flock, fl);
2470 if (error)
2471 goto out;
2472 }
2473out:
2474 locks_free_lock(fl);
2475 return error;
2476}
2477
2478/**
2479 * vfs_lock_file - file byte range lock
2480 * @filp: The file to apply the lock to
2481 * @cmd: type of locking operation (F_SETLK, F_GETLK, etc.)
2482 * @fl: The lock to be applied
2483 * @conf: Place to return a copy of the conflicting lock, if found.
2484 *
2485 * A caller that doesn't care about the conflicting lock may pass NULL
2486 * as the final argument.
2487 *
2488 * If the filesystem defines a private ->lock() method, then @conf will
2489 * be left unchanged; so a caller that cares should initialize it to
2490 * some acceptable default.
2491 *
2492 * To avoid blocking kernel daemons, such as lockd, that need to acquire POSIX
2493 * locks, the ->lock() interface may return asynchronously, before the lock has
2494 * been granted or denied by the underlying filesystem, if (and only if)
2495 * lm_grant is set. Additionally FOP_ASYNC_LOCK in file_operations fop_flags
2496 * need to be set.
2497 *
2498 * Callers expecting ->lock() to return asynchronously will only use F_SETLK,
2499 * not F_SETLKW; they will set FL_SLEEP if (and only if) the request is for a
2500 * blocking lock. When ->lock() does return asynchronously, it must return
2501 * FILE_LOCK_DEFERRED, and call ->lm_grant() when the lock request completes.
2502 * If the request is for non-blocking lock the file system should return
2503 * FILE_LOCK_DEFERRED then try to get the lock and call the callback routine
2504 * with the result. If the request timed out the callback routine will return a
2505 * nonzero return code and the file system should release the lock. The file
2506 * system is also responsible to keep a corresponding posix lock when it
2507 * grants a lock so the VFS can find out which locks are locally held and do
2508 * the correct lock cleanup when required.
2509 * The underlying filesystem must not drop the kernel lock or call
2510 * ->lm_grant() before returning to the caller with a FILE_LOCK_DEFERRED
2511 * return code.
2512 */
2513int vfs_lock_file(struct file *filp, unsigned int cmd, struct file_lock *fl, struct file_lock *conf)
2514{
2515 WARN_ON_ONCE(filp != fl->c.flc_file);
2516 if (filp->f_op->lock)
2517 return filp->f_op->lock(filp, cmd, fl);
2518 else
2519 return posix_lock_file(filp, fl, conf);
2520}
2521EXPORT_SYMBOL_GPL(vfs_lock_file);
2522
2523static int do_lock_file_wait(struct file *filp, unsigned int cmd,
2524 struct file_lock *fl)
2525{
2526 int error;
2527
2528 error = security_file_lock(filp, fl->c.flc_type);
2529 if (error)
2530 return error;
2531
2532 for (;;) {
2533 error = vfs_lock_file(filp, cmd, fl, NULL);
2534 if (error != FILE_LOCK_DEFERRED)
2535 break;
2536 error = wait_event_interruptible(fl->c.flc_wait,
2537 list_empty(&fl->c.flc_blocked_member));
2538 if (error)
2539 break;
2540 }
2541 locks_delete_block(fl);
2542
2543 return error;
2544}
2545
2546/* Ensure that fl->fl_file has compatible f_mode for F_SETLK calls */
2547static int
2548check_fmode_for_setlk(struct file_lock *fl)
2549{
2550 switch (fl->c.flc_type) {
2551 case F_RDLCK:
2552 if (!(fl->c.flc_file->f_mode & FMODE_READ))
2553 return -EBADF;
2554 break;
2555 case F_WRLCK:
2556 if (!(fl->c.flc_file->f_mode & FMODE_WRITE))
2557 return -EBADF;
2558 }
2559 return 0;
2560}
2561
2562/* Apply the lock described by l to an open file descriptor.
2563 * This implements both the F_SETLK and F_SETLKW commands of fcntl().
2564 */
2565int fcntl_setlk(unsigned int fd, struct file *filp, unsigned int cmd,
2566 struct flock *flock)
2567{
2568 struct file_lock *file_lock = locks_alloc_lock();
2569 struct inode *inode = file_inode(filp);
2570 struct file *f;
2571 int error;
2572
2573 if (file_lock == NULL)
2574 return -ENOLCK;
2575
2576 error = flock_to_posix_lock(filp, file_lock, flock);
2577 if (error)
2578 goto out;
2579
2580 error = check_fmode_for_setlk(file_lock);
2581 if (error)
2582 goto out;
2583
2584 /*
2585 * If the cmd is requesting file-private locks, then set the
2586 * FL_OFDLCK flag and override the owner.
2587 */
2588 switch (cmd) {
2589 case F_OFD_SETLK:
2590 error = -EINVAL;
2591 if (flock->l_pid != 0)
2592 goto out;
2593
2594 cmd = F_SETLK;
2595 file_lock->c.flc_flags |= FL_OFDLCK;
2596 file_lock->c.flc_owner = filp;
2597 break;
2598 case F_OFD_SETLKW:
2599 error = -EINVAL;
2600 if (flock->l_pid != 0)
2601 goto out;
2602
2603 cmd = F_SETLKW;
2604 file_lock->c.flc_flags |= FL_OFDLCK;
2605 file_lock->c.flc_owner = filp;
2606 fallthrough;
2607 case F_SETLKW:
2608 file_lock->c.flc_flags |= FL_SLEEP;
2609 }
2610
2611 error = do_lock_file_wait(filp, cmd, file_lock);
2612
2613 /*
2614 * Detect close/fcntl races and recover by zapping all POSIX locks
2615 * associated with this file and our files_struct, just like on
2616 * filp_flush(). There is no need to do that when we're
2617 * unlocking though, or for OFD locks.
2618 */
2619 if (!error && file_lock->c.flc_type != F_UNLCK &&
2620 !(file_lock->c.flc_flags & FL_OFDLCK)) {
2621 struct files_struct *files = current->files;
2622 /*
2623 * We need that spin_lock here - it prevents reordering between
2624 * update of i_flctx->flc_posix and check for it done in
2625 * close(). rcu_read_lock() wouldn't do.
2626 */
2627 spin_lock(&files->file_lock);
2628 f = files_lookup_fd_locked(files, fd);
2629 spin_unlock(&files->file_lock);
2630 if (f != filp) {
2631 locks_remove_posix(filp, files);
2632 error = -EBADF;
2633 }
2634 }
2635out:
2636 trace_fcntl_setlk(inode, file_lock, error);
2637 locks_free_lock(file_lock);
2638 return error;
2639}
2640
2641#if BITS_PER_LONG == 32
2642/* Report the first existing lock that would conflict with l.
2643 * This implements the F_GETLK command of fcntl().
2644 */
2645int fcntl_getlk64(struct file *filp, unsigned int cmd, struct flock64 *flock)
2646{
2647 struct file_lock *fl;
2648 int error;
2649
2650 fl = locks_alloc_lock();
2651 if (fl == NULL)
2652 return -ENOMEM;
2653
2654 error = -EINVAL;
2655 if (cmd != F_OFD_GETLK && flock->l_type != F_RDLCK
2656 && flock->l_type != F_WRLCK)
2657 goto out;
2658
2659 error = flock64_to_posix_lock(filp, fl, flock);
2660 if (error)
2661 goto out;
2662
2663 if (cmd == F_OFD_GETLK) {
2664 error = -EINVAL;
2665 if (flock->l_pid != 0)
2666 goto out;
2667
2668 fl->c.flc_flags |= FL_OFDLCK;
2669 fl->c.flc_owner = filp;
2670 }
2671
2672 error = vfs_test_lock(filp, fl);
2673 if (error)
2674 goto out;
2675
2676 flock->l_type = fl->c.flc_type;
2677 if (fl->c.flc_type != F_UNLCK)
2678 posix_lock_to_flock64(flock, fl);
2679
2680out:
2681 locks_free_lock(fl);
2682 return error;
2683}
2684
2685/* Apply the lock described by l to an open file descriptor.
2686 * This implements both the F_SETLK and F_SETLKW commands of fcntl().
2687 */
2688int fcntl_setlk64(unsigned int fd, struct file *filp, unsigned int cmd,
2689 struct flock64 *flock)
2690{
2691 struct file_lock *file_lock = locks_alloc_lock();
2692 struct file *f;
2693 int error;
2694
2695 if (file_lock == NULL)
2696 return -ENOLCK;
2697
2698 error = flock64_to_posix_lock(filp, file_lock, flock);
2699 if (error)
2700 goto out;
2701
2702 error = check_fmode_for_setlk(file_lock);
2703 if (error)
2704 goto out;
2705
2706 /*
2707 * If the cmd is requesting file-private locks, then set the
2708 * FL_OFDLCK flag and override the owner.
2709 */
2710 switch (cmd) {
2711 case F_OFD_SETLK:
2712 error = -EINVAL;
2713 if (flock->l_pid != 0)
2714 goto out;
2715
2716 cmd = F_SETLK64;
2717 file_lock->c.flc_flags |= FL_OFDLCK;
2718 file_lock->c.flc_owner = filp;
2719 break;
2720 case F_OFD_SETLKW:
2721 error = -EINVAL;
2722 if (flock->l_pid != 0)
2723 goto out;
2724
2725 cmd = F_SETLKW64;
2726 file_lock->c.flc_flags |= FL_OFDLCK;
2727 file_lock->c.flc_owner = filp;
2728 fallthrough;
2729 case F_SETLKW64:
2730 file_lock->c.flc_flags |= FL_SLEEP;
2731 }
2732
2733 error = do_lock_file_wait(filp, cmd, file_lock);
2734
2735 /*
2736 * Detect close/fcntl races and recover by zapping all POSIX locks
2737 * associated with this file and our files_struct, just like on
2738 * filp_flush(). There is no need to do that when we're
2739 * unlocking though, or for OFD locks.
2740 */
2741 if (!error && file_lock->c.flc_type != F_UNLCK &&
2742 !(file_lock->c.flc_flags & FL_OFDLCK)) {
2743 struct files_struct *files = current->files;
2744 /*
2745 * We need that spin_lock here - it prevents reordering between
2746 * update of i_flctx->flc_posix and check for it done in
2747 * close(). rcu_read_lock() wouldn't do.
2748 */
2749 spin_lock(&files->file_lock);
2750 f = files_lookup_fd_locked(files, fd);
2751 spin_unlock(&files->file_lock);
2752 if (f != filp) {
2753 locks_remove_posix(filp, files);
2754 error = -EBADF;
2755 }
2756 }
2757out:
2758 locks_free_lock(file_lock);
2759 return error;
2760}
2761#endif /* BITS_PER_LONG == 32 */
2762
2763/*
2764 * This function is called when the file is being removed
2765 * from the task's fd array. POSIX locks belonging to this task
2766 * are deleted at this time.
2767 */
2768void locks_remove_posix(struct file *filp, fl_owner_t owner)
2769{
2770 int error;
2771 struct inode *inode = file_inode(filp);
2772 struct file_lock lock;
2773 struct file_lock_context *ctx;
2774
2775 /*
2776 * If there are no locks held on this file, we don't need to call
2777 * posix_lock_file(). Another process could be setting a lock on this
2778 * file at the same time, but we wouldn't remove that lock anyway.
2779 */
2780 ctx = locks_inode_context(inode);
2781 if (!ctx || list_empty(&ctx->flc_posix))
2782 return;
2783
2784 locks_init_lock(&lock);
2785 lock.c.flc_type = F_UNLCK;
2786 lock.c.flc_flags = FL_POSIX | FL_CLOSE;
2787 lock.fl_start = 0;
2788 lock.fl_end = OFFSET_MAX;
2789 lock.c.flc_owner = owner;
2790 lock.c.flc_pid = current->tgid;
2791 lock.c.flc_file = filp;
2792 lock.fl_ops = NULL;
2793 lock.fl_lmops = NULL;
2794
2795 error = vfs_lock_file(filp, F_SETLK, &lock, NULL);
2796
2797 if (lock.fl_ops && lock.fl_ops->fl_release_private)
2798 lock.fl_ops->fl_release_private(&lock);
2799 trace_locks_remove_posix(inode, &lock, error);
2800}
2801EXPORT_SYMBOL(locks_remove_posix);
2802
2803/* The i_flctx must be valid when calling into here */
2804static void
2805locks_remove_flock(struct file *filp, struct file_lock_context *flctx)
2806{
2807 struct file_lock fl;
2808 struct inode *inode = file_inode(filp);
2809
2810 if (list_empty(&flctx->flc_flock))
2811 return;
2812
2813 flock_make_lock(filp, &fl, F_UNLCK);
2814 fl.c.flc_flags |= FL_CLOSE;
2815
2816 if (filp->f_op->flock)
2817 filp->f_op->flock(filp, F_SETLKW, &fl);
2818 else
2819 flock_lock_inode(inode, &fl);
2820
2821 if (fl.fl_ops && fl.fl_ops->fl_release_private)
2822 fl.fl_ops->fl_release_private(&fl);
2823}
2824
2825/* The i_flctx must be valid when calling into here */
2826static void
2827locks_remove_lease(struct file *filp, struct file_lock_context *ctx)
2828{
2829 struct file_lease *fl, *tmp;
2830 LIST_HEAD(dispose);
2831
2832 if (list_empty(&ctx->flc_lease))
2833 return;
2834
2835 percpu_down_read(&file_rwsem);
2836 spin_lock(&ctx->flc_lock);
2837 list_for_each_entry_safe(fl, tmp, &ctx->flc_lease, c.flc_list)
2838 if (filp == fl->c.flc_file)
2839 lease_modify(fl, F_UNLCK, &dispose);
2840 spin_unlock(&ctx->flc_lock);
2841 percpu_up_read(&file_rwsem);
2842
2843 lease_dispose_list(&dispose);
2844}
2845
2846/*
2847 * This function is called on the last close of an open file.
2848 */
2849void locks_remove_file(struct file *filp)
2850{
2851 struct file_lock_context *ctx;
2852
2853 ctx = locks_inode_context(file_inode(filp));
2854 if (!ctx)
2855 return;
2856
2857 /* remove any OFD locks */
2858 locks_remove_posix(filp, filp);
2859
2860 /* remove flock locks */
2861 locks_remove_flock(filp, ctx);
2862
2863 /* remove any leases */
2864 locks_remove_lease(filp, ctx);
2865
2866 spin_lock(&ctx->flc_lock);
2867 locks_check_ctx_file_list(filp, &ctx->flc_posix, "POSIX");
2868 locks_check_ctx_file_list(filp, &ctx->flc_flock, "FLOCK");
2869 locks_check_ctx_file_list(filp, &ctx->flc_lease, "LEASE");
2870 spin_unlock(&ctx->flc_lock);
2871}
2872
2873/**
2874 * vfs_cancel_lock - file byte range unblock lock
2875 * @filp: The file to apply the unblock to
2876 * @fl: The lock to be unblocked
2877 *
2878 * Used by lock managers to cancel blocked requests
2879 */
2880int vfs_cancel_lock(struct file *filp, struct file_lock *fl)
2881{
2882 WARN_ON_ONCE(filp != fl->c.flc_file);
2883 if (filp->f_op->lock)
2884 return filp->f_op->lock(filp, F_CANCELLK, fl);
2885 return 0;
2886}
2887EXPORT_SYMBOL_GPL(vfs_cancel_lock);
2888
2889/**
2890 * vfs_inode_has_locks - are any file locks held on @inode?
2891 * @inode: inode to check for locks
2892 *
2893 * Return true if there are any FL_POSIX or FL_FLOCK locks currently
2894 * set on @inode.
2895 */
2896bool vfs_inode_has_locks(struct inode *inode)
2897{
2898 struct file_lock_context *ctx;
2899 bool ret;
2900
2901 ctx = locks_inode_context(inode);
2902 if (!ctx)
2903 return false;
2904
2905 spin_lock(&ctx->flc_lock);
2906 ret = !list_empty(&ctx->flc_posix) || !list_empty(&ctx->flc_flock);
2907 spin_unlock(&ctx->flc_lock);
2908 return ret;
2909}
2910EXPORT_SYMBOL_GPL(vfs_inode_has_locks);
2911
2912#ifdef CONFIG_PROC_FS
2913#include <linux/proc_fs.h>
2914#include <linux/seq_file.h>
2915
2916struct locks_iterator {
2917 int li_cpu;
2918 loff_t li_pos;
2919};
2920
2921static void lock_get_status(struct seq_file *f, struct file_lock_core *flc,
2922 loff_t id, char *pfx, int repeat)
2923{
2924 struct inode *inode = NULL;
2925 unsigned int pid;
2926 struct pid_namespace *proc_pidns = proc_pid_ns(file_inode(f->file)->i_sb);
2927 int type = flc->flc_type;
2928 struct file_lock *fl = file_lock(flc);
2929
2930 pid = locks_translate_pid(flc, proc_pidns);
2931
2932 /*
2933 * If lock owner is dead (and pid is freed) or not visible in current
2934 * pidns, zero is shown as a pid value. Check lock info from
2935 * init_pid_ns to get saved lock pid value.
2936 */
2937 if (flc->flc_file != NULL)
2938 inode = file_inode(flc->flc_file);
2939
2940 seq_printf(f, "%lld: ", id);
2941
2942 if (repeat)
2943 seq_printf(f, "%*s", repeat - 1 + (int)strlen(pfx), pfx);
2944
2945 if (flc->flc_flags & FL_POSIX) {
2946 if (flc->flc_flags & FL_ACCESS)
2947 seq_puts(f, "ACCESS");
2948 else if (flc->flc_flags & FL_OFDLCK)
2949 seq_puts(f, "OFDLCK");
2950 else
2951 seq_puts(f, "POSIX ");
2952
2953 seq_printf(f, " %s ",
2954 (inode == NULL) ? "*NOINODE*" : "ADVISORY ");
2955 } else if (flc->flc_flags & FL_FLOCK) {
2956 seq_puts(f, "FLOCK ADVISORY ");
2957 } else if (flc->flc_flags & (FL_LEASE|FL_DELEG|FL_LAYOUT)) {
2958 struct file_lease *lease = file_lease(flc);
2959
2960 type = target_leasetype(lease);
2961
2962 if (flc->flc_flags & FL_DELEG)
2963 seq_puts(f, "DELEG ");
2964 else
2965 seq_puts(f, "LEASE ");
2966
2967 if (lease_breaking(lease))
2968 seq_puts(f, "BREAKING ");
2969 else if (flc->flc_file)
2970 seq_puts(f, "ACTIVE ");
2971 else
2972 seq_puts(f, "BREAKER ");
2973 } else {
2974 seq_puts(f, "UNKNOWN UNKNOWN ");
2975 }
2976
2977 seq_printf(f, "%s ", (type == F_WRLCK) ? "WRITE" :
2978 (type == F_RDLCK) ? "READ" : "UNLCK");
2979 if (inode) {
2980 /* userspace relies on this representation of dev_t */
2981 seq_printf(f, "%d %02x:%02x:%llu ", pid,
2982 MAJOR(inode->i_sb->s_dev),
2983 MINOR(inode->i_sb->s_dev), inode->i_ino);
2984 } else {
2985 seq_printf(f, "%d <none>:0 ", pid);
2986 }
2987 if (flc->flc_flags & FL_POSIX) {
2988 if (fl->fl_end == OFFSET_MAX)
2989 seq_printf(f, "%Ld EOF\n", fl->fl_start);
2990 else
2991 seq_printf(f, "%Ld %Ld\n", fl->fl_start, fl->fl_end);
2992 } else {
2993 seq_puts(f, "0 EOF\n");
2994 }
2995}
2996
2997static struct file_lock_core *get_next_blocked_member(struct file_lock_core *node)
2998{
2999 struct file_lock_core *tmp;
3000
3001 /* NULL node or root node */
3002 if (node == NULL || node->flc_blocker == NULL)
3003 return NULL;
3004
3005 /* Next member in the linked list could be itself */
3006 tmp = list_next_entry(node, flc_blocked_member);
3007 if (list_entry_is_head(tmp, &node->flc_blocker->flc_blocked_requests,
3008 flc_blocked_member)
3009 || tmp == node) {
3010 return NULL;
3011 }
3012
3013 return tmp;
3014}
3015
3016static int locks_show(struct seq_file *f, void *v)
3017{
3018 struct locks_iterator *iter = f->private;
3019 struct file_lock_core *cur, *tmp;
3020 struct pid_namespace *proc_pidns = proc_pid_ns(file_inode(f->file)->i_sb);
3021 int level = 0;
3022
3023 cur = hlist_entry(v, struct file_lock_core, flc_link);
3024
3025 if (locks_translate_pid(cur, proc_pidns) == 0)
3026 return 0;
3027
3028 /* View this crossed linked list as a binary tree, the first member of flc_blocked_requests
3029 * is the left child of current node, the next silibing in flc_blocked_member is the
3030 * right child, we can alse get the parent of current node from flc_blocker, so this
3031 * question becomes traversal of a binary tree
3032 */
3033 while (cur != NULL) {
3034 if (level)
3035 lock_get_status(f, cur, iter->li_pos, "-> ", level);
3036 else
3037 lock_get_status(f, cur, iter->li_pos, "", level);
3038
3039 if (!list_empty(&cur->flc_blocked_requests)) {
3040 /* Turn left */
3041 cur = list_first_entry_or_null(&cur->flc_blocked_requests,
3042 struct file_lock_core,
3043 flc_blocked_member);
3044 level++;
3045 } else {
3046 /* Turn right */
3047 tmp = get_next_blocked_member(cur);
3048 /* Fall back to parent node */
3049 while (tmp == NULL && cur->flc_blocker != NULL) {
3050 cur = cur->flc_blocker;
3051 level--;
3052 tmp = get_next_blocked_member(cur);
3053 }
3054 cur = tmp;
3055 }
3056 }
3057
3058 return 0;
3059}
3060
3061static void __show_fd_locks(struct seq_file *f,
3062 struct list_head *head, int *id,
3063 struct file *filp, struct files_struct *files)
3064{
3065 struct file_lock_core *fl;
3066
3067 list_for_each_entry(fl, head, flc_list) {
3068
3069 if (filp != fl->flc_file)
3070 continue;
3071 if (fl->flc_owner != files && fl->flc_owner != filp)
3072 continue;
3073
3074 (*id)++;
3075 seq_puts(f, "lock:\t");
3076 lock_get_status(f, fl, *id, "", 0);
3077 }
3078}
3079
3080void show_fd_locks(struct seq_file *f,
3081 struct file *filp, struct files_struct *files)
3082{
3083 struct inode *inode = file_inode(filp);
3084 struct file_lock_context *ctx;
3085 int id = 0;
3086
3087 ctx = locks_inode_context(inode);
3088 if (!ctx)
3089 return;
3090
3091 spin_lock(&ctx->flc_lock);
3092 __show_fd_locks(f, &ctx->flc_flock, &id, filp, files);
3093 __show_fd_locks(f, &ctx->flc_posix, &id, filp, files);
3094 __show_fd_locks(f, &ctx->flc_lease, &id, filp, files);
3095 spin_unlock(&ctx->flc_lock);
3096}
3097
3098static void *locks_start(struct seq_file *f, loff_t *pos)
3099 __acquires(&blocked_lock_lock)
3100{
3101 struct locks_iterator *iter = f->private;
3102
3103 iter->li_pos = *pos + 1;
3104 percpu_down_write(&file_rwsem);
3105 spin_lock(&blocked_lock_lock);
3106 return seq_hlist_start_percpu(&file_lock_list.hlist, &iter->li_cpu, *pos);
3107}
3108
3109static void *locks_next(struct seq_file *f, void *v, loff_t *pos)
3110{
3111 struct locks_iterator *iter = f->private;
3112
3113 ++iter->li_pos;
3114 return seq_hlist_next_percpu(v, &file_lock_list.hlist, &iter->li_cpu, pos);
3115}
3116
3117static void locks_stop(struct seq_file *f, void *v)
3118 __releases(&blocked_lock_lock)
3119{
3120 spin_unlock(&blocked_lock_lock);
3121 percpu_up_write(&file_rwsem);
3122}
3123
3124static const struct seq_operations locks_seq_operations = {
3125 .start = locks_start,
3126 .next = locks_next,
3127 .stop = locks_stop,
3128 .show = locks_show,
3129};
3130
3131static int __init proc_locks_init(void)
3132{
3133 proc_create_seq_private("locks", 0, NULL, &locks_seq_operations,
3134 sizeof(struct locks_iterator), NULL);
3135 return 0;
3136}
3137fs_initcall(proc_locks_init);
3138#endif
3139
3140static int __init filelock_init(void)
3141{
3142 int i;
3143
3144 flctx_cache = kmem_cache_create("file_lock_ctx",
3145 sizeof(struct file_lock_context), 0, SLAB_PANIC, NULL);
3146
3147 filelock_cache = kmem_cache_create("file_lock_cache",
3148 sizeof(struct file_lock), 0, SLAB_PANIC, NULL);
3149
3150 filelease_cache = kmem_cache_create("file_lease_cache",
3151 sizeof(struct file_lease), 0, SLAB_PANIC, NULL);
3152
3153 for_each_possible_cpu(i) {
3154 struct file_lock_list_struct *fll = per_cpu_ptr(&file_lock_list, i);
3155
3156 spin_lock_init(&fll->lock);
3157 INIT_HLIST_HEAD(&fll->hlist);
3158 }
3159
3160 lease_notifier_chain_init();
3161 return 0;
3162}
3163core_initcall(filelock_init);