xref: /linux/fs/locks.c (revision 9e355113f02be17db573d579515dee63621b7c8b)
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 
72 static struct file_lock *file_lock(struct file_lock_core *flc)
73 {
74 	return container_of(flc, struct file_lock, c);
75 }
76 
77 static struct file_lease *file_lease(struct file_lock_core *flc)
78 {
79 	return container_of(flc, struct file_lease, c);
80 }
81 
82 static bool lease_breaking(struct file_lease *fl)
83 {
84 	return fl->c.flc_flags & (FL_UNLOCK_PENDING | FL_DOWNGRADE_PENDING);
85 }
86 
87 static 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 
96 static int leases_enable = 1;
97 static int lease_break_time = 45;
98 
99 #ifdef CONFIG_SYSCTL
100 static 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 
119 static int __init init_fs_locks_sysctls(void)
120 {
121 	register_sysctl_init("fs", locks_sysctls);
122 	return 0;
123 }
124 early_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  */
135 struct file_lock_list_struct {
136 	spinlock_t		lock;
137 	struct hlist_head	hlist;
138 };
139 static DEFINE_PER_CPU(struct file_lock_list_struct, file_lock_list);
140 DEFINE_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
155 static 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  */
170 static DEFINE_SPINLOCK(blocked_lock_lock);
171 
172 static struct kmem_cache *flctx_cache __ro_after_init;
173 static struct kmem_cache *filelock_cache __ro_after_init;
174 static struct kmem_cache *filelease_cache __ro_after_init;
175 
176 static struct file_lock_context *
177 locks_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 	}
213 out:
214 	trace_locks_get_lock_context(inode, type, ctx);
215 	return ctx;
216 }
217 
218 static void
219 locks_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 
229 static void
230 locks_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%lx:\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 
246 static void
247 locks_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%lx "
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 
262 void
263 locks_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 
273 static 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. */
283 struct 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 }
292 EXPORT_SYMBOL_GPL(locks_alloc_lock);
293 
294 /* Allocate an empty lock structure. */
295 struct 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 }
304 EXPORT_SYMBOL_GPL(locks_alloc_lease);
305 
306 void 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 }
330 EXPORT_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  */
341 bool 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 }
357 EXPORT_SYMBOL_GPL(locks_owner_has_blockers);
358 
359 /* Free a lock which is not in use. */
360 void locks_free_lock(struct file_lock *fl)
361 {
362 	locks_release_private(fl);
363 	kmem_cache_free(filelock_cache, fl);
364 }
365 EXPORT_SYMBOL(locks_free_lock);
366 
367 /* Free a lease which is not in use. */
368 void locks_free_lease(struct file_lease *fl)
369 {
370 	kmem_cache_free(filelease_cache, fl);
371 }
372 EXPORT_SYMBOL(locks_free_lease);
373 
374 static void
375 locks_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 
386 static void
387 lease_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 
398 void locks_init_lock(struct file_lock *fl)
399 {
400 	memset(fl, 0, sizeof(struct file_lock));
401 	locks_init_lock_heads(&fl->c);
402 }
403 EXPORT_SYMBOL(locks_init_lock);
404 
405 void locks_init_lease(struct file_lease *fl)
406 {
407 	memset(fl, 0, sizeof(*fl));
408 	locks_init_lock_heads(&fl->c);
409 }
410 EXPORT_SYMBOL(locks_init_lease);
411 
412 /*
413  * Initialize a new lock from an existing file_lock structure.
414  */
415 void 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 }
432 EXPORT_SYMBOL(locks_copy_conflock);
433 
434 void 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 }
449 EXPORT_SYMBOL(locks_copy_lock);
450 
451 static 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 
471 static 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. */
484 static 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 
496 static 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 
510 static 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  */
560 static 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 */
574 static bool
575 lease_break_callback(struct file_lease *fl)
576 {
577 	kill_fasync(&fl->fl_fasync, SIGIO, POLL_MSG);
578 	return false;
579 }
580 
581 static void
582 lease_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  */
608 static int
609 lease_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 
637 static 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  */
647 static 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 */
662 static 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  */
680 static 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  */
689 static 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! */
695 static 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! */
708 static 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 
728 static unsigned long
729 posix_owner_key(struct file_lock_core *flc)
730 {
731 	return (unsigned long) flc->flc_owner;
732 }
733 
734 static 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 
741 static 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  */
753 static 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 
759 static 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 
785 static 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  */
835 int locks_delete_block(struct file_lock *waiter)
836 {
837 	return __locks_delete_block(&waiter->c);
838 }
839 EXPORT_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  */
856 static 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));
864 new_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. */
885 static 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  */
900 static 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 
917 static void
918 locks_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 
924 static void
925 locks_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 
932 static void
933 locks_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  */
945 static 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  */
958 static 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  */
980 static 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  */
998 static 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 
1010 void
1011 posix_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 
1025 retry:
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;
1044 out:
1045 	spin_unlock(&ctx->flc_lock);
1046 	return;
1047 }
1048 EXPORT_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. */
1086 static 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! */
1101 static 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  */
1133 static 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 
1176 find_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 
1195 out:
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 
1205 static 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 
1237 retry:
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  */
1458 int 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 }
1463 EXPORT_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  */
1472 static 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 
1489 static 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 */
1501 int 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 }
1523 EXPORT_SYMBOL(lease_modify);
1524 
1525 static 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 
1533 static 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 
1538 	lockdep_assert_held(&ctx->flc_lock);
1539 
1540 	list_for_each_entry_safe(fl, tmp, &ctx->flc_lease, c.flc_list) {
1541 		trace_time_out_leases(inode, fl);
1542 		if (past_time(fl->fl_downgrade_time))
1543 			lease_modify(fl, F_RDLCK, dispose);
1544 		if (past_time(fl->fl_break_time))
1545 			lease_modify(fl, F_UNLCK, dispose);
1546 	}
1547 }
1548 
1549 static bool leases_conflict(struct file_lock_core *lc, struct file_lock_core *bc)
1550 {
1551 	bool rc;
1552 	struct file_lease *lease = file_lease(lc);
1553 	struct file_lease *breaker = file_lease(bc);
1554 
1555 	if (lease->fl_lmops->lm_breaker_owns_lease
1556 			&& lease->fl_lmops->lm_breaker_owns_lease(lease))
1557 		return false;
1558 	if ((bc->flc_flags & FL_LAYOUT) != (lc->flc_flags & FL_LAYOUT)) {
1559 		rc = false;
1560 		goto trace;
1561 	}
1562 	if ((bc->flc_flags & FL_DELEG) && (lc->flc_flags & FL_LEASE)) {
1563 		rc = false;
1564 		goto trace;
1565 	}
1566 
1567 	rc = locks_conflict(bc, lc);
1568 trace:
1569 	trace_leases_conflict(rc, lease, breaker);
1570 	return rc;
1571 }
1572 
1573 static bool
1574 any_leases_conflict(struct inode *inode, struct file_lease *breaker)
1575 {
1576 	struct file_lock_context *ctx = inode->i_flctx;
1577 	struct file_lock_core *flc;
1578 
1579 	lockdep_assert_held(&ctx->flc_lock);
1580 
1581 	list_for_each_entry(flc, &ctx->flc_lease, flc_list) {
1582 		if (leases_conflict(flc, &breaker->c))
1583 			return true;
1584 	}
1585 	return false;
1586 }
1587 
1588 /**
1589  *	__break_lease	-	revoke all outstanding leases on file
1590  *	@inode: the inode of the file to return
1591  *	@flags: LEASE_BREAK_* flags
1592  *
1593  *	break_lease (inlined for speed) has checked there already is at least
1594  *	some kind of lock (maybe a lease) on this file.  Leases are broken on
1595  *	a call to open() or truncate().  This function can block waiting for the
1596  *	lease break unless you specify LEASE_BREAK_NONBLOCK.
1597  */
1598 int __break_lease(struct inode *inode, unsigned int flags)
1599 {
1600 	struct file_lease *new_fl, *fl, *tmp;
1601 	struct file_lock_context *ctx;
1602 	unsigned long break_time;
1603 	unsigned int type;
1604 	LIST_HEAD(dispose);
1605 	bool want_write = !(flags & LEASE_BREAK_OPEN_RDONLY);
1606 	int error = 0;
1607 
1608 	if (flags & LEASE_BREAK_LEASE)
1609 		type = FL_LEASE;
1610 	else if (flags & LEASE_BREAK_DELEG)
1611 		type = FL_DELEG;
1612 	else if (flags & LEASE_BREAK_LAYOUT)
1613 		type = FL_LAYOUT;
1614 	else
1615 		return -EINVAL;
1616 
1617 	new_fl = lease_alloc(NULL, type, want_write ? F_WRLCK : F_RDLCK);
1618 	if (IS_ERR(new_fl))
1619 		return PTR_ERR(new_fl);
1620 
1621 	/* typically we will check that ctx is non-NULL before calling */
1622 	ctx = locks_inode_context(inode);
1623 	if (!ctx) {
1624 		WARN_ON_ONCE(1);
1625 		goto free_lock;
1626 	}
1627 
1628 	percpu_down_read(&file_rwsem);
1629 	spin_lock(&ctx->flc_lock);
1630 
1631 	time_out_leases(inode, &dispose);
1632 
1633 	if (!any_leases_conflict(inode, new_fl))
1634 		goto out;
1635 
1636 	break_time = 0;
1637 	if (lease_break_time > 0) {
1638 		break_time = jiffies + lease_break_time * HZ;
1639 		if (break_time == 0)
1640 			break_time++;	/* so that 0 means no break time */
1641 	}
1642 
1643 	list_for_each_entry_safe(fl, tmp, &ctx->flc_lease, c.flc_list) {
1644 		if (!leases_conflict(&fl->c, &new_fl->c))
1645 			continue;
1646 		if (want_write) {
1647 			if (fl->c.flc_flags & FL_UNLOCK_PENDING)
1648 				continue;
1649 			fl->c.flc_flags |= FL_UNLOCK_PENDING;
1650 			fl->fl_break_time = break_time;
1651 		} else {
1652 			if (lease_breaking(fl))
1653 				continue;
1654 			fl->c.flc_flags |= FL_DOWNGRADE_PENDING;
1655 			fl->fl_downgrade_time = break_time;
1656 		}
1657 		if (fl->fl_lmops->lm_break(fl))
1658 			locks_delete_lock_ctx(&fl->c, &dispose);
1659 	}
1660 
1661 	if (list_empty(&ctx->flc_lease))
1662 		goto out;
1663 
1664 	if (flags & LEASE_BREAK_NONBLOCK) {
1665 		trace_break_lease_noblock(inode, new_fl);
1666 		error = -EWOULDBLOCK;
1667 		goto out;
1668 	}
1669 
1670 restart:
1671 	fl = list_first_entry(&ctx->flc_lease, struct file_lease, c.flc_list);
1672 	break_time = fl->fl_break_time;
1673 	if (break_time != 0)
1674 		break_time -= jiffies;
1675 	if (break_time == 0)
1676 		break_time++;
1677 	locks_insert_block(&fl->c, &new_fl->c, leases_conflict);
1678 	trace_break_lease_block(inode, new_fl);
1679 	spin_unlock(&ctx->flc_lock);
1680 	percpu_up_read(&file_rwsem);
1681 
1682 	lease_dispose_list(&dispose);
1683 	error = wait_event_interruptible_timeout(new_fl->c.flc_wait,
1684 						 list_empty(&new_fl->c.flc_blocked_member),
1685 						 break_time);
1686 
1687 	percpu_down_read(&file_rwsem);
1688 	spin_lock(&ctx->flc_lock);
1689 	trace_break_lease_unblock(inode, new_fl);
1690 	__locks_delete_block(&new_fl->c);
1691 	if (error >= 0) {
1692 		/*
1693 		 * Wait for the next conflicting lease that has not been
1694 		 * broken yet
1695 		 */
1696 		if (error == 0)
1697 			time_out_leases(inode, &dispose);
1698 		if (any_leases_conflict(inode, new_fl))
1699 			goto restart;
1700 		error = 0;
1701 	}
1702 out:
1703 	spin_unlock(&ctx->flc_lock);
1704 	percpu_up_read(&file_rwsem);
1705 	lease_dispose_list(&dispose);
1706 free_lock:
1707 	locks_free_lease(new_fl);
1708 	return error;
1709 }
1710 EXPORT_SYMBOL(__break_lease);
1711 
1712 /**
1713  *	lease_get_mtime - update modified time of an inode with exclusive lease
1714  *	@inode: the inode
1715  *      @time:  pointer to a timespec which contains the last modified time
1716  *
1717  * This is to force NFS clients to flush their caches for files with
1718  * exclusive leases.  The justification is that if someone has an
1719  * exclusive lease, then they could be modifying it.
1720  */
1721 void lease_get_mtime(struct inode *inode, struct timespec64 *time)
1722 {
1723 	bool has_lease = false;
1724 	struct file_lock_context *ctx;
1725 	struct file_lock_core *flc;
1726 
1727 	ctx = locks_inode_context(inode);
1728 	if (ctx && !list_empty_careful(&ctx->flc_lease)) {
1729 		spin_lock(&ctx->flc_lock);
1730 		flc = list_first_entry_or_null(&ctx->flc_lease,
1731 					       struct file_lock_core, flc_list);
1732 		if (flc && flc->flc_type == F_WRLCK)
1733 			has_lease = true;
1734 		spin_unlock(&ctx->flc_lock);
1735 	}
1736 
1737 	if (has_lease)
1738 		*time = current_time(inode);
1739 }
1740 EXPORT_SYMBOL(lease_get_mtime);
1741 
1742 /**
1743  *	__fcntl_getlease - Enquire what lease is currently active
1744  *	@filp: the file
1745  *	@flavor: type of lease flags to check
1746  *
1747  *	The value returned by this function will be one of
1748  *	(if no lease break is pending):
1749  *
1750  *	%F_RDLCK to indicate a shared lease is held.
1751  *
1752  *	%F_WRLCK to indicate an exclusive lease is held.
1753  *
1754  *	%F_UNLCK to indicate no lease is held.
1755  *
1756  *	(if a lease break is pending):
1757  *
1758  *	%F_RDLCK to indicate an exclusive lease needs to be
1759  *		changed to a shared lease (or removed).
1760  *
1761  *	%F_UNLCK to indicate the lease needs to be removed.
1762  *
1763  *	XXX: sfr & willy disagree over whether F_INPROGRESS
1764  *	should be returned to userspace.
1765  */
1766 static int __fcntl_getlease(struct file *filp, unsigned int flavor)
1767 {
1768 	struct file_lease *fl;
1769 	struct inode *inode = file_inode(filp);
1770 	struct file_lock_context *ctx;
1771 	int type = F_UNLCK;
1772 	LIST_HEAD(dispose);
1773 
1774 	ctx = locks_inode_context(inode);
1775 	if (ctx && !list_empty_careful(&ctx->flc_lease)) {
1776 		percpu_down_read(&file_rwsem);
1777 		spin_lock(&ctx->flc_lock);
1778 		time_out_leases(inode, &dispose);
1779 		list_for_each_entry(fl, &ctx->flc_lease, c.flc_list) {
1780 			if (fl->c.flc_file != filp)
1781 				continue;
1782 			if (fl->c.flc_flags & flavor)
1783 				type = target_leasetype(fl);
1784 			break;
1785 		}
1786 		spin_unlock(&ctx->flc_lock);
1787 		percpu_up_read(&file_rwsem);
1788 
1789 		lease_dispose_list(&dispose);
1790 	}
1791 	return type;
1792 }
1793 
1794 int fcntl_getlease(struct file *filp)
1795 {
1796 	return __fcntl_getlease(filp, FL_LEASE);
1797 }
1798 
1799 int fcntl_getdeleg(struct file *filp, struct delegation *deleg)
1800 {
1801 	if (deleg->d_flags != 0 || deleg->__pad != 0)
1802 		return -EINVAL;
1803 	deleg->d_type = __fcntl_getlease(filp, FL_DELEG);
1804 	return 0;
1805 }
1806 
1807 static int
1808 generic_add_lease(struct file *filp, int arg, struct file_lease **flp, void **priv)
1809 {
1810 	struct file_lease *fl, *my_fl = NULL, *lease;
1811 	struct inode *inode = file_inode(filp);
1812 	struct file_lock_context *ctx;
1813 	bool is_deleg = (*flp)->c.flc_flags & FL_DELEG;
1814 	int error;
1815 	LIST_HEAD(dispose);
1816 
1817 	lease = *flp;
1818 	trace_generic_add_lease(inode, lease);
1819 
1820 	error = file_f_owner_allocate(filp);
1821 	if (error)
1822 		return error;
1823 
1824 	/* Note that arg is never F_UNLCK here */
1825 	ctx = locks_get_lock_context(inode, arg);
1826 	if (!ctx)
1827 		return -ENOMEM;
1828 
1829 	/*
1830 	 * In the delegation case we need mutual exclusion with
1831 	 * a number of operations that take the i_rwsem.  We trylock
1832 	 * because delegations are an optional optimization, and if
1833 	 * there's some chance of a conflict--we'd rather not
1834 	 * bother, maybe that's a sign this just isn't a good file to
1835 	 * hand out a delegation on.
1836 	 */
1837 	if (is_deleg && !inode_trylock(inode))
1838 		return -EAGAIN;
1839 
1840 	percpu_down_read(&file_rwsem);
1841 	spin_lock(&ctx->flc_lock);
1842 	time_out_leases(inode, &dispose);
1843 	error = lease->fl_lmops->lm_open_conflict(filp, arg);
1844 	if (error)
1845 		goto out;
1846 
1847 	/*
1848 	 * At this point, we know that if there is an exclusive
1849 	 * lease on this file, then we hold it on this filp
1850 	 * (otherwise our open of this file would have blocked).
1851 	 * And if we are trying to acquire an exclusive lease,
1852 	 * then the file is not open by anyone (including us)
1853 	 * except for this filp.
1854 	 */
1855 	error = -EAGAIN;
1856 	list_for_each_entry(fl, &ctx->flc_lease, c.flc_list) {
1857 		if (fl->c.flc_file == filp &&
1858 		    fl->c.flc_owner == lease->c.flc_owner) {
1859 			my_fl = fl;
1860 			continue;
1861 		}
1862 
1863 		/*
1864 		 * No exclusive leases if someone else has a lease on
1865 		 * this file:
1866 		 */
1867 		if (arg == F_WRLCK)
1868 			goto out;
1869 		/*
1870 		 * Modifying our existing lease is OK, but no getting a
1871 		 * new lease if someone else is opening for write:
1872 		 */
1873 		if (fl->c.flc_flags & FL_UNLOCK_PENDING)
1874 			goto out;
1875 	}
1876 
1877 	if (my_fl != NULL) {
1878 		lease = my_fl;
1879 		error = lease->fl_lmops->lm_change(lease, arg, &dispose);
1880 		if (error)
1881 			goto out;
1882 		goto out_setup;
1883 	}
1884 
1885 	error = -EINVAL;
1886 	if (!leases_enable)
1887 		goto out;
1888 
1889 	locks_insert_lock_ctx(&lease->c, &ctx->flc_lease);
1890 	/*
1891 	 * The check in break_lease() is lockless. It's possible for another
1892 	 * open to race in after we did the earlier check for a conflicting
1893 	 * open but before the lease was inserted. Check again for a
1894 	 * conflicting open and cancel the lease if there is one.
1895 	 *
1896 	 * We also add a barrier here to ensure that the insertion of the lock
1897 	 * precedes these checks.
1898 	 */
1899 	smp_mb();
1900 	error = lease->fl_lmops->lm_open_conflict(filp, arg);
1901 	if (error) {
1902 		locks_unlink_lock_ctx(&lease->c);
1903 		goto out;
1904 	}
1905 
1906 out_setup:
1907 	if (lease->fl_lmops->lm_setup)
1908 		lease->fl_lmops->lm_setup(lease, priv);
1909 out:
1910 	spin_unlock(&ctx->flc_lock);
1911 	percpu_up_read(&file_rwsem);
1912 	lease_dispose_list(&dispose);
1913 	if (is_deleg)
1914 		inode_unlock(inode);
1915 	if (!error && !my_fl)
1916 		*flp = NULL;
1917 	return error;
1918 }
1919 
1920 static int generic_delete_lease(struct file *filp, void *owner)
1921 {
1922 	int error = -EAGAIN;
1923 	struct file_lease *fl, *victim = NULL;
1924 	struct inode *inode = file_inode(filp);
1925 	struct file_lock_context *ctx;
1926 	LIST_HEAD(dispose);
1927 
1928 	ctx = locks_inode_context(inode);
1929 	if (!ctx) {
1930 		trace_generic_delete_lease(inode, NULL);
1931 		return error;
1932 	}
1933 
1934 	percpu_down_read(&file_rwsem);
1935 	spin_lock(&ctx->flc_lock);
1936 	list_for_each_entry(fl, &ctx->flc_lease, c.flc_list) {
1937 		if (fl->c.flc_file == filp &&
1938 		    fl->c.flc_owner == owner) {
1939 			victim = fl;
1940 			break;
1941 		}
1942 	}
1943 	trace_generic_delete_lease(inode, victim);
1944 	if (victim)
1945 		error = fl->fl_lmops->lm_change(victim, F_UNLCK, &dispose);
1946 	spin_unlock(&ctx->flc_lock);
1947 	percpu_up_read(&file_rwsem);
1948 	lease_dispose_list(&dispose);
1949 	return error;
1950 }
1951 
1952 /**
1953  *	generic_setlease	-	sets a lease on an open file
1954  *	@filp:	file pointer
1955  *	@arg:	type of lease to obtain
1956  *	@flp:	input - file_lock to use, output - file_lock inserted
1957  *	@priv:	private data for lm_setup (may be NULL if lm_setup
1958  *		doesn't require it)
1959  *
1960  *	The (input) flp->fl_lmops->lm_break function is required
1961  *	by break_lease().
1962  */
1963 int generic_setlease(struct file *filp, int arg, struct file_lease **flp,
1964 			void **priv)
1965 {
1966 	struct inode *inode = file_inode(filp);
1967 
1968 	if (!S_ISREG(inode->i_mode) && !S_ISDIR(inode->i_mode))
1969 		return -EINVAL;
1970 
1971 	switch (arg) {
1972 	case F_UNLCK:
1973 		return generic_delete_lease(filp, *priv);
1974 	case F_WRLCK:
1975 		if (S_ISDIR(inode->i_mode))
1976 			return -EINVAL;
1977 		fallthrough;
1978 	case F_RDLCK:
1979 		if (!(*flp)->fl_lmops->lm_break) {
1980 			WARN_ON_ONCE(1);
1981 			return -ENOLCK;
1982 		}
1983 
1984 		return generic_add_lease(filp, arg, flp, priv);
1985 	default:
1986 		return -EINVAL;
1987 	}
1988 }
1989 EXPORT_SYMBOL(generic_setlease);
1990 
1991 /*
1992  * Kernel subsystems can register to be notified on any attempt to set
1993  * a new lease with the lease_notifier_chain. This is used by (e.g.) nfsd
1994  * to close files that it may have cached when there is an attempt to set a
1995  * conflicting lease.
1996  */
1997 static struct srcu_notifier_head lease_notifier_chain;
1998 
1999 static inline void
2000 lease_notifier_chain_init(void)
2001 {
2002 	srcu_init_notifier_head(&lease_notifier_chain);
2003 }
2004 
2005 static inline void
2006 setlease_notifier(int arg, struct file_lease *lease)
2007 {
2008 	if (arg != F_UNLCK)
2009 		srcu_notifier_call_chain(&lease_notifier_chain, arg, lease);
2010 }
2011 
2012 int lease_register_notifier(struct notifier_block *nb)
2013 {
2014 	return srcu_notifier_chain_register(&lease_notifier_chain, nb);
2015 }
2016 EXPORT_SYMBOL_GPL(lease_register_notifier);
2017 
2018 void lease_unregister_notifier(struct notifier_block *nb)
2019 {
2020 	srcu_notifier_chain_unregister(&lease_notifier_chain, nb);
2021 }
2022 EXPORT_SYMBOL_GPL(lease_unregister_notifier);
2023 
2024 
2025 int
2026 kernel_setlease(struct file *filp, int arg, struct file_lease **lease, void **priv)
2027 {
2028 	if (lease)
2029 		setlease_notifier(arg, *lease);
2030 	if (filp->f_op->setlease)
2031 		return filp->f_op->setlease(filp, arg, lease, priv);
2032 	return -EINVAL;
2033 }
2034 EXPORT_SYMBOL_GPL(kernel_setlease);
2035 
2036 /**
2037  * vfs_setlease        -       sets a lease on an open file
2038  * @filp:	file pointer
2039  * @arg:	type of lease to obtain
2040  * @lease:	file_lock to use when adding a lease
2041  * @priv:	private info for lm_setup when adding a lease (may be
2042  *		NULL if lm_setup doesn't require it)
2043  *
2044  * Call this to establish a lease on the file. The "lease" argument is not
2045  * used for F_UNLCK requests and may be NULL. For commands that set or alter
2046  * an existing lease, the ``(*lease)->fl_lmops->lm_break`` operation must be
2047  * set; if not, this function will return -ENOLCK (and generate a scary-looking
2048  * stack trace).
2049  *
2050  * The "priv" pointer is passed directly to the lm_setup function as-is. It
2051  * may be NULL if the lm_setup operation doesn't require it.
2052  */
2053 int
2054 vfs_setlease(struct file *filp, int arg, struct file_lease **lease, void **priv)
2055 {
2056 	struct inode *inode = file_inode(filp);
2057 	vfsuid_t vfsuid = i_uid_into_vfsuid(file_mnt_idmap(filp), inode);
2058 	int error;
2059 
2060 	if ((!vfsuid_eq_kuid(vfsuid, current_fsuid())) && !capable(CAP_LEASE))
2061 		return -EACCES;
2062 	error = security_file_lock(filp, arg);
2063 	if (error)
2064 		return error;
2065 	return kernel_setlease(filp, arg, lease, priv);
2066 }
2067 EXPORT_SYMBOL_GPL(vfs_setlease);
2068 
2069 static int do_fcntl_add_lease(unsigned int fd, struct file *filp, unsigned int flavor, int arg)
2070 {
2071 	struct file_lease *fl;
2072 	struct fasync_struct *new;
2073 	int error;
2074 
2075 	fl = lease_alloc(filp, flavor, arg);
2076 	if (IS_ERR(fl))
2077 		return PTR_ERR(fl);
2078 
2079 	new = fasync_alloc();
2080 	if (!new) {
2081 		locks_free_lease(fl);
2082 		return -ENOMEM;
2083 	}
2084 	new->fa_fd = fd;
2085 
2086 	error = vfs_setlease(filp, arg, &fl, (void **)&new);
2087 	if (fl)
2088 		locks_free_lease(fl);
2089 	if (new)
2090 		fasync_free(new);
2091 	return error;
2092 }
2093 
2094 /**
2095  *	fcntl_setlease	-	sets a lease on an open file
2096  *	@fd: open file descriptor
2097  *	@filp: file pointer
2098  *	@arg: type of lease to obtain
2099  *
2100  *	Call this fcntl to establish a lease on the file.
2101  *	Note that you also need to call %F_SETSIG to
2102  *	receive a signal when the lease is broken.
2103  */
2104 int fcntl_setlease(unsigned int fd, struct file *filp, int arg)
2105 {
2106 	if (S_ISDIR(file_inode(filp)->i_mode))
2107 		return -EINVAL;
2108 
2109 	if (arg == F_UNLCK)
2110 		return vfs_setlease(filp, F_UNLCK, NULL, (void **)&filp);
2111 	return do_fcntl_add_lease(fd, filp, FL_LEASE, arg);
2112 }
2113 
2114 /**
2115  *	fcntl_setdeleg	-	sets a delegation on an open file
2116  *	@fd: open file descriptor
2117  *	@filp: file pointer
2118  *	@deleg: delegation request from userland
2119  *
2120  *	Call this fcntl to establish a delegation on the file.
2121  *	Note that you also need to call %F_SETSIG to
2122  *	receive a signal when the lease is broken.
2123  */
2124 int fcntl_setdeleg(unsigned int fd, struct file *filp, struct delegation *deleg)
2125 {
2126 	/* For now, no flags are supported */
2127 	if (deleg->d_flags != 0 || deleg->__pad != 0)
2128 		return -EINVAL;
2129 
2130 	if (deleg->d_type == F_UNLCK)
2131 		return vfs_setlease(filp, F_UNLCK, NULL, (void **)&filp);
2132 	return do_fcntl_add_lease(fd, filp, FL_DELEG, deleg->d_type);
2133 }
2134 
2135 /**
2136  * flock_lock_inode_wait - Apply a FLOCK-style lock to a file
2137  * @inode: inode of the file to apply to
2138  * @fl: The lock to be applied
2139  *
2140  * Apply a FLOCK style lock request to an inode.
2141  */
2142 static int flock_lock_inode_wait(struct inode *inode, struct file_lock *fl)
2143 {
2144 	int error;
2145 	might_sleep();
2146 	for (;;) {
2147 		error = flock_lock_inode(inode, fl);
2148 		if (error != FILE_LOCK_DEFERRED)
2149 			break;
2150 		error = wait_event_interruptible(fl->c.flc_wait,
2151 						 list_empty(&fl->c.flc_blocked_member));
2152 		if (error)
2153 			break;
2154 	}
2155 	locks_delete_block(fl);
2156 	return error;
2157 }
2158 
2159 /**
2160  * locks_lock_inode_wait - Apply a lock to an inode
2161  * @inode: inode of the file to apply to
2162  * @fl: The lock to be applied
2163  *
2164  * Apply a POSIX or FLOCK style lock request to an inode.
2165  */
2166 int locks_lock_inode_wait(struct inode *inode, struct file_lock *fl)
2167 {
2168 	int res = 0;
2169 	switch (fl->c.flc_flags & (FL_POSIX|FL_FLOCK)) {
2170 		case FL_POSIX:
2171 			res = posix_lock_inode_wait(inode, fl);
2172 			break;
2173 		case FL_FLOCK:
2174 			res = flock_lock_inode_wait(inode, fl);
2175 			break;
2176 		default:
2177 			BUG();
2178 	}
2179 	return res;
2180 }
2181 EXPORT_SYMBOL(locks_lock_inode_wait);
2182 
2183 /**
2184  *	sys_flock: - flock() system call.
2185  *	@fd: the file descriptor to lock.
2186  *	@cmd: the type of lock to apply.
2187  *
2188  *	Apply a %FL_FLOCK style lock to an open file descriptor.
2189  *	The @cmd can be one of:
2190  *
2191  *	- %LOCK_SH -- a shared lock.
2192  *	- %LOCK_EX -- an exclusive lock.
2193  *	- %LOCK_UN -- remove an existing lock.
2194  *	- %LOCK_MAND -- a 'mandatory' flock. (DEPRECATED)
2195  *
2196  *	%LOCK_MAND support has been removed from the kernel.
2197  */
2198 SYSCALL_DEFINE2(flock, unsigned int, fd, unsigned int, cmd)
2199 {
2200 	int can_sleep, error, type;
2201 	struct file_lock fl;
2202 
2203 	/*
2204 	 * LOCK_MAND locks were broken for a long time in that they never
2205 	 * conflicted with one another and didn't prevent any sort of open,
2206 	 * read or write activity.
2207 	 *
2208 	 * Just ignore these requests now, to preserve legacy behavior, but
2209 	 * throw a warning to let people know that they don't actually work.
2210 	 */
2211 	if (cmd & LOCK_MAND) {
2212 		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);
2213 		return 0;
2214 	}
2215 
2216 	type = flock_translate_cmd(cmd & ~LOCK_NB);
2217 	if (type < 0)
2218 		return type;
2219 
2220 	CLASS(fd, f)(fd);
2221 	if (fd_empty(f))
2222 		return -EBADF;
2223 
2224 	if (type != F_UNLCK && !(fd_file(f)->f_mode & (FMODE_READ | FMODE_WRITE)))
2225 		return -EBADF;
2226 
2227 	flock_make_lock(fd_file(f), &fl, type);
2228 
2229 	error = security_file_lock(fd_file(f), fl.c.flc_type);
2230 	if (error)
2231 		return error;
2232 
2233 	can_sleep = !(cmd & LOCK_NB);
2234 	if (can_sleep)
2235 		fl.c.flc_flags |= FL_SLEEP;
2236 
2237 	if (fd_file(f)->f_op->flock)
2238 		error = fd_file(f)->f_op->flock(fd_file(f),
2239 					    (can_sleep) ? F_SETLKW : F_SETLK,
2240 					    &fl);
2241 	else
2242 		error = locks_lock_file_wait(fd_file(f), &fl);
2243 
2244 	locks_release_private(&fl);
2245 	return error;
2246 }
2247 
2248 /**
2249  * vfs_test_lock - test file byte range lock
2250  * @filp: The file to test lock for
2251  * @fl: The byte-range in the file to test; also used to hold result
2252  *
2253  * On entry, @fl does not contain a lock, but identifies a range (fl_start, fl_end)
2254  * in the file (c.flc_file), and an owner (c.flc_owner) for whom existing locks
2255  * should be ignored.  c.flc_type and c.flc_flags are ignored.
2256  * Both fl_lmops and fl_ops in @fl must be NULL.
2257  * Returns -ERRNO on failure.  Indicates presence of conflicting lock by
2258  * setting fl->fl_type to something other than F_UNLCK.
2259  *
2260  * If vfs_test_lock() does find a lock and return it, the caller must
2261  * use locks_free_lock() or locks_release_private() on the returned lock.
2262  */
2263 int vfs_test_lock(struct file *filp, struct file_lock *fl)
2264 {
2265 	WARN_ON_ONCE(fl->fl_ops || fl->fl_lmops);
2266 	WARN_ON_ONCE(filp != fl->c.flc_file);
2267 	if (filp->f_op->lock)
2268 		return filp->f_op->lock(filp, F_GETLK, fl);
2269 	posix_test_lock(filp, fl);
2270 	return 0;
2271 }
2272 EXPORT_SYMBOL_GPL(vfs_test_lock);
2273 
2274 /**
2275  * locks_translate_pid - translate a file_lock's fl_pid number into a namespace
2276  * @fl: The file_lock who's fl_pid should be translated
2277  * @ns: The namespace into which the pid should be translated
2278  *
2279  * Used to translate a fl_pid into a namespace virtual pid number
2280  */
2281 static pid_t locks_translate_pid(struct file_lock_core *fl, struct pid_namespace *ns)
2282 {
2283 	pid_t vnr;
2284 	struct pid *pid;
2285 
2286 	if (fl->flc_flags & FL_OFDLCK)
2287 		return -1;
2288 
2289 	/* Remote locks report a negative pid value */
2290 	if (fl->flc_pid <= 0)
2291 		return fl->flc_pid;
2292 
2293 	/*
2294 	 * If the flock owner process is dead and its pid has been already
2295 	 * freed, the translation below won't work, but we still want to show
2296 	 * flock owner pid number in init pidns.
2297 	 */
2298 	if (ns == &init_pid_ns)
2299 		return (pid_t) fl->flc_pid;
2300 
2301 	rcu_read_lock();
2302 	pid = find_pid_ns(fl->flc_pid, &init_pid_ns);
2303 	vnr = pid_nr_ns(pid, ns);
2304 	rcu_read_unlock();
2305 	return vnr;
2306 }
2307 
2308 static int posix_lock_to_flock(struct flock *flock, struct file_lock *fl)
2309 {
2310 	flock->l_pid = locks_translate_pid(&fl->c, task_active_pid_ns(current));
2311 #if BITS_PER_LONG == 32
2312 	/*
2313 	 * Make sure we can represent the posix lock via
2314 	 * legacy 32bit flock.
2315 	 */
2316 	if (fl->fl_start > OFFT_OFFSET_MAX)
2317 		return -EOVERFLOW;
2318 	if (fl->fl_end != OFFSET_MAX && fl->fl_end > OFFT_OFFSET_MAX)
2319 		return -EOVERFLOW;
2320 #endif
2321 	flock->l_start = fl->fl_start;
2322 	flock->l_len = fl->fl_end == OFFSET_MAX ? 0 :
2323 		fl->fl_end - fl->fl_start + 1;
2324 	flock->l_whence = 0;
2325 	flock->l_type = fl->c.flc_type;
2326 	return 0;
2327 }
2328 
2329 #if BITS_PER_LONG == 32
2330 static void posix_lock_to_flock64(struct flock64 *flock, struct file_lock *fl)
2331 {
2332 	flock->l_pid = locks_translate_pid(&fl->c, task_active_pid_ns(current));
2333 	flock->l_start = fl->fl_start;
2334 	flock->l_len = fl->fl_end == OFFSET_MAX ? 0 :
2335 		fl->fl_end - fl->fl_start + 1;
2336 	flock->l_whence = 0;
2337 	flock->l_type = fl->c.flc_type;
2338 }
2339 #endif
2340 
2341 /* Report the first existing lock that would conflict with l.
2342  * This implements the F_GETLK command of fcntl().
2343  */
2344 int fcntl_getlk(struct file *filp, unsigned int cmd, struct flock *flock)
2345 {
2346 	struct file_lock *fl;
2347 	int error;
2348 
2349 	fl = locks_alloc_lock();
2350 	if (fl == NULL)
2351 		return -ENOMEM;
2352 	error = -EINVAL;
2353 	if (cmd != F_OFD_GETLK && flock->l_type != F_RDLCK
2354 			&& flock->l_type != F_WRLCK)
2355 		goto out;
2356 
2357 	error = flock_to_posix_lock(filp, fl, flock);
2358 	if (error)
2359 		goto out;
2360 
2361 	if (cmd == F_OFD_GETLK) {
2362 		error = -EINVAL;
2363 		if (flock->l_pid != 0)
2364 			goto out;
2365 
2366 		fl->c.flc_flags |= FL_OFDLCK;
2367 		fl->c.flc_owner = filp;
2368 	}
2369 
2370 	error = vfs_test_lock(filp, fl);
2371 	if (error)
2372 		goto out;
2373 
2374 	flock->l_type = fl->c.flc_type;
2375 	if (fl->c.flc_type != F_UNLCK) {
2376 		error = posix_lock_to_flock(flock, fl);
2377 		if (error)
2378 			goto out;
2379 	}
2380 out:
2381 	locks_free_lock(fl);
2382 	return error;
2383 }
2384 
2385 /**
2386  * vfs_lock_file - file byte range lock
2387  * @filp: The file to apply the lock to
2388  * @cmd: type of locking operation (F_SETLK, F_GETLK, etc.)
2389  * @fl: The lock to be applied
2390  * @conf: Place to return a copy of the conflicting lock, if found.
2391  *
2392  * A caller that doesn't care about the conflicting lock may pass NULL
2393  * as the final argument.
2394  *
2395  * If the filesystem defines a private ->lock() method, then @conf will
2396  * be left unchanged; so a caller that cares should initialize it to
2397  * some acceptable default.
2398  *
2399  * To avoid blocking kernel daemons, such as lockd, that need to acquire POSIX
2400  * locks, the ->lock() interface may return asynchronously, before the lock has
2401  * been granted or denied by the underlying filesystem, if (and only if)
2402  * lm_grant is set. Additionally FOP_ASYNC_LOCK in file_operations fop_flags
2403  * need to be set.
2404  *
2405  * Callers expecting ->lock() to return asynchronously will only use F_SETLK,
2406  * not F_SETLKW; they will set FL_SLEEP if (and only if) the request is for a
2407  * blocking lock. When ->lock() does return asynchronously, it must return
2408  * FILE_LOCK_DEFERRED, and call ->lm_grant() when the lock request completes.
2409  * If the request is for non-blocking lock the file system should return
2410  * FILE_LOCK_DEFERRED then try to get the lock and call the callback routine
2411  * with the result. If the request timed out the callback routine will return a
2412  * nonzero return code and the file system should release the lock. The file
2413  * system is also responsible to keep a corresponding posix lock when it
2414  * grants a lock so the VFS can find out which locks are locally held and do
2415  * the correct lock cleanup when required.
2416  * The underlying filesystem must not drop the kernel lock or call
2417  * ->lm_grant() before returning to the caller with a FILE_LOCK_DEFERRED
2418  * return code.
2419  */
2420 int vfs_lock_file(struct file *filp, unsigned int cmd, struct file_lock *fl, struct file_lock *conf)
2421 {
2422 	WARN_ON_ONCE(filp != fl->c.flc_file);
2423 	if (filp->f_op->lock)
2424 		return filp->f_op->lock(filp, cmd, fl);
2425 	else
2426 		return posix_lock_file(filp, fl, conf);
2427 }
2428 EXPORT_SYMBOL_GPL(vfs_lock_file);
2429 
2430 static int do_lock_file_wait(struct file *filp, unsigned int cmd,
2431 			     struct file_lock *fl)
2432 {
2433 	int error;
2434 
2435 	error = security_file_lock(filp, fl->c.flc_type);
2436 	if (error)
2437 		return error;
2438 
2439 	for (;;) {
2440 		error = vfs_lock_file(filp, cmd, fl, NULL);
2441 		if (error != FILE_LOCK_DEFERRED)
2442 			break;
2443 		error = wait_event_interruptible(fl->c.flc_wait,
2444 						 list_empty(&fl->c.flc_blocked_member));
2445 		if (error)
2446 			break;
2447 	}
2448 	locks_delete_block(fl);
2449 
2450 	return error;
2451 }
2452 
2453 /* Ensure that fl->fl_file has compatible f_mode for F_SETLK calls */
2454 static int
2455 check_fmode_for_setlk(struct file_lock *fl)
2456 {
2457 	switch (fl->c.flc_type) {
2458 	case F_RDLCK:
2459 		if (!(fl->c.flc_file->f_mode & FMODE_READ))
2460 			return -EBADF;
2461 		break;
2462 	case F_WRLCK:
2463 		if (!(fl->c.flc_file->f_mode & FMODE_WRITE))
2464 			return -EBADF;
2465 	}
2466 	return 0;
2467 }
2468 
2469 /* Apply the lock described by l to an open file descriptor.
2470  * This implements both the F_SETLK and F_SETLKW commands of fcntl().
2471  */
2472 int fcntl_setlk(unsigned int fd, struct file *filp, unsigned int cmd,
2473 		struct flock *flock)
2474 {
2475 	struct file_lock *file_lock = locks_alloc_lock();
2476 	struct inode *inode = file_inode(filp);
2477 	struct file *f;
2478 	int error;
2479 
2480 	if (file_lock == NULL)
2481 		return -ENOLCK;
2482 
2483 	error = flock_to_posix_lock(filp, file_lock, flock);
2484 	if (error)
2485 		goto out;
2486 
2487 	error = check_fmode_for_setlk(file_lock);
2488 	if (error)
2489 		goto out;
2490 
2491 	/*
2492 	 * If the cmd is requesting file-private locks, then set the
2493 	 * FL_OFDLCK flag and override the owner.
2494 	 */
2495 	switch (cmd) {
2496 	case F_OFD_SETLK:
2497 		error = -EINVAL;
2498 		if (flock->l_pid != 0)
2499 			goto out;
2500 
2501 		cmd = F_SETLK;
2502 		file_lock->c.flc_flags |= FL_OFDLCK;
2503 		file_lock->c.flc_owner = filp;
2504 		break;
2505 	case F_OFD_SETLKW:
2506 		error = -EINVAL;
2507 		if (flock->l_pid != 0)
2508 			goto out;
2509 
2510 		cmd = F_SETLKW;
2511 		file_lock->c.flc_flags |= FL_OFDLCK;
2512 		file_lock->c.flc_owner = filp;
2513 		fallthrough;
2514 	case F_SETLKW:
2515 		file_lock->c.flc_flags |= FL_SLEEP;
2516 	}
2517 
2518 	error = do_lock_file_wait(filp, cmd, file_lock);
2519 
2520 	/*
2521 	 * Detect close/fcntl races and recover by zapping all POSIX locks
2522 	 * associated with this file and our files_struct, just like on
2523 	 * filp_flush(). There is no need to do that when we're
2524 	 * unlocking though, or for OFD locks.
2525 	 */
2526 	if (!error && file_lock->c.flc_type != F_UNLCK &&
2527 	    !(file_lock->c.flc_flags & FL_OFDLCK)) {
2528 		struct files_struct *files = current->files;
2529 		/*
2530 		 * We need that spin_lock here - it prevents reordering between
2531 		 * update of i_flctx->flc_posix and check for it done in
2532 		 * close(). rcu_read_lock() wouldn't do.
2533 		 */
2534 		spin_lock(&files->file_lock);
2535 		f = files_lookup_fd_locked(files, fd);
2536 		spin_unlock(&files->file_lock);
2537 		if (f != filp) {
2538 			locks_remove_posix(filp, files);
2539 			error = -EBADF;
2540 		}
2541 	}
2542 out:
2543 	trace_fcntl_setlk(inode, file_lock, error);
2544 	locks_free_lock(file_lock);
2545 	return error;
2546 }
2547 
2548 #if BITS_PER_LONG == 32
2549 /* Report the first existing lock that would conflict with l.
2550  * This implements the F_GETLK command of fcntl().
2551  */
2552 int fcntl_getlk64(struct file *filp, unsigned int cmd, struct flock64 *flock)
2553 {
2554 	struct file_lock *fl;
2555 	int error;
2556 
2557 	fl = locks_alloc_lock();
2558 	if (fl == NULL)
2559 		return -ENOMEM;
2560 
2561 	error = -EINVAL;
2562 	if (cmd != F_OFD_GETLK && flock->l_type != F_RDLCK
2563 			&& flock->l_type != F_WRLCK)
2564 		goto out;
2565 
2566 	error = flock64_to_posix_lock(filp, fl, flock);
2567 	if (error)
2568 		goto out;
2569 
2570 	if (cmd == F_OFD_GETLK) {
2571 		error = -EINVAL;
2572 		if (flock->l_pid != 0)
2573 			goto out;
2574 
2575 		fl->c.flc_flags |= FL_OFDLCK;
2576 		fl->c.flc_owner = filp;
2577 	}
2578 
2579 	error = vfs_test_lock(filp, fl);
2580 	if (error)
2581 		goto out;
2582 
2583 	flock->l_type = fl->c.flc_type;
2584 	if (fl->c.flc_type != F_UNLCK)
2585 		posix_lock_to_flock64(flock, fl);
2586 
2587 out:
2588 	locks_free_lock(fl);
2589 	return error;
2590 }
2591 
2592 /* Apply the lock described by l to an open file descriptor.
2593  * This implements both the F_SETLK and F_SETLKW commands of fcntl().
2594  */
2595 int fcntl_setlk64(unsigned int fd, struct file *filp, unsigned int cmd,
2596 		struct flock64 *flock)
2597 {
2598 	struct file_lock *file_lock = locks_alloc_lock();
2599 	struct file *f;
2600 	int error;
2601 
2602 	if (file_lock == NULL)
2603 		return -ENOLCK;
2604 
2605 	error = flock64_to_posix_lock(filp, file_lock, flock);
2606 	if (error)
2607 		goto out;
2608 
2609 	error = check_fmode_for_setlk(file_lock);
2610 	if (error)
2611 		goto out;
2612 
2613 	/*
2614 	 * If the cmd is requesting file-private locks, then set the
2615 	 * FL_OFDLCK flag and override the owner.
2616 	 */
2617 	switch (cmd) {
2618 	case F_OFD_SETLK:
2619 		error = -EINVAL;
2620 		if (flock->l_pid != 0)
2621 			goto out;
2622 
2623 		cmd = F_SETLK64;
2624 		file_lock->c.flc_flags |= FL_OFDLCK;
2625 		file_lock->c.flc_owner = filp;
2626 		break;
2627 	case F_OFD_SETLKW:
2628 		error = -EINVAL;
2629 		if (flock->l_pid != 0)
2630 			goto out;
2631 
2632 		cmd = F_SETLKW64;
2633 		file_lock->c.flc_flags |= FL_OFDLCK;
2634 		file_lock->c.flc_owner = filp;
2635 		fallthrough;
2636 	case F_SETLKW64:
2637 		file_lock->c.flc_flags |= FL_SLEEP;
2638 	}
2639 
2640 	error = do_lock_file_wait(filp, cmd, file_lock);
2641 
2642 	/*
2643 	 * Detect close/fcntl races and recover by zapping all POSIX locks
2644 	 * associated with this file and our files_struct, just like on
2645 	 * filp_flush(). There is no need to do that when we're
2646 	 * unlocking though, or for OFD locks.
2647 	 */
2648 	if (!error && file_lock->c.flc_type != F_UNLCK &&
2649 	    !(file_lock->c.flc_flags & FL_OFDLCK)) {
2650 		struct files_struct *files = current->files;
2651 		/*
2652 		 * We need that spin_lock here - it prevents reordering between
2653 		 * update of i_flctx->flc_posix and check for it done in
2654 		 * close(). rcu_read_lock() wouldn't do.
2655 		 */
2656 		spin_lock(&files->file_lock);
2657 		f = files_lookup_fd_locked(files, fd);
2658 		spin_unlock(&files->file_lock);
2659 		if (f != filp) {
2660 			locks_remove_posix(filp, files);
2661 			error = -EBADF;
2662 		}
2663 	}
2664 out:
2665 	locks_free_lock(file_lock);
2666 	return error;
2667 }
2668 #endif /* BITS_PER_LONG == 32 */
2669 
2670 /*
2671  * This function is called when the file is being removed
2672  * from the task's fd array.  POSIX locks belonging to this task
2673  * are deleted at this time.
2674  */
2675 void locks_remove_posix(struct file *filp, fl_owner_t owner)
2676 {
2677 	int error;
2678 	struct inode *inode = file_inode(filp);
2679 	struct file_lock lock;
2680 	struct file_lock_context *ctx;
2681 
2682 	/*
2683 	 * If there are no locks held on this file, we don't need to call
2684 	 * posix_lock_file().  Another process could be setting a lock on this
2685 	 * file at the same time, but we wouldn't remove that lock anyway.
2686 	 */
2687 	ctx = locks_inode_context(inode);
2688 	if (!ctx || list_empty(&ctx->flc_posix))
2689 		return;
2690 
2691 	locks_init_lock(&lock);
2692 	lock.c.flc_type = F_UNLCK;
2693 	lock.c.flc_flags = FL_POSIX | FL_CLOSE;
2694 	lock.fl_start = 0;
2695 	lock.fl_end = OFFSET_MAX;
2696 	lock.c.flc_owner = owner;
2697 	lock.c.flc_pid = current->tgid;
2698 	lock.c.flc_file = filp;
2699 	lock.fl_ops = NULL;
2700 	lock.fl_lmops = NULL;
2701 
2702 	error = vfs_lock_file(filp, F_SETLK, &lock, NULL);
2703 
2704 	if (lock.fl_ops && lock.fl_ops->fl_release_private)
2705 		lock.fl_ops->fl_release_private(&lock);
2706 	trace_locks_remove_posix(inode, &lock, error);
2707 }
2708 EXPORT_SYMBOL(locks_remove_posix);
2709 
2710 /* The i_flctx must be valid when calling into here */
2711 static void
2712 locks_remove_flock(struct file *filp, struct file_lock_context *flctx)
2713 {
2714 	struct file_lock fl;
2715 	struct inode *inode = file_inode(filp);
2716 
2717 	if (list_empty(&flctx->flc_flock))
2718 		return;
2719 
2720 	flock_make_lock(filp, &fl, F_UNLCK);
2721 	fl.c.flc_flags |= FL_CLOSE;
2722 
2723 	if (filp->f_op->flock)
2724 		filp->f_op->flock(filp, F_SETLKW, &fl);
2725 	else
2726 		flock_lock_inode(inode, &fl);
2727 
2728 	if (fl.fl_ops && fl.fl_ops->fl_release_private)
2729 		fl.fl_ops->fl_release_private(&fl);
2730 }
2731 
2732 /* The i_flctx must be valid when calling into here */
2733 static void
2734 locks_remove_lease(struct file *filp, struct file_lock_context *ctx)
2735 {
2736 	struct file_lease *fl, *tmp;
2737 	LIST_HEAD(dispose);
2738 
2739 	if (list_empty(&ctx->flc_lease))
2740 		return;
2741 
2742 	percpu_down_read(&file_rwsem);
2743 	spin_lock(&ctx->flc_lock);
2744 	list_for_each_entry_safe(fl, tmp, &ctx->flc_lease, c.flc_list)
2745 		if (filp == fl->c.flc_file)
2746 			lease_modify(fl, F_UNLCK, &dispose);
2747 	spin_unlock(&ctx->flc_lock);
2748 	percpu_up_read(&file_rwsem);
2749 
2750 	lease_dispose_list(&dispose);
2751 }
2752 
2753 /*
2754  * This function is called on the last close of an open file.
2755  */
2756 void locks_remove_file(struct file *filp)
2757 {
2758 	struct file_lock_context *ctx;
2759 
2760 	ctx = locks_inode_context(file_inode(filp));
2761 	if (!ctx)
2762 		return;
2763 
2764 	/* remove any OFD locks */
2765 	locks_remove_posix(filp, filp);
2766 
2767 	/* remove flock locks */
2768 	locks_remove_flock(filp, ctx);
2769 
2770 	/* remove any leases */
2771 	locks_remove_lease(filp, ctx);
2772 
2773 	spin_lock(&ctx->flc_lock);
2774 	locks_check_ctx_file_list(filp, &ctx->flc_posix, "POSIX");
2775 	locks_check_ctx_file_list(filp, &ctx->flc_flock, "FLOCK");
2776 	locks_check_ctx_file_list(filp, &ctx->flc_lease, "LEASE");
2777 	spin_unlock(&ctx->flc_lock);
2778 }
2779 
2780 /**
2781  * vfs_cancel_lock - file byte range unblock lock
2782  * @filp: The file to apply the unblock to
2783  * @fl: The lock to be unblocked
2784  *
2785  * Used by lock managers to cancel blocked requests
2786  */
2787 int vfs_cancel_lock(struct file *filp, struct file_lock *fl)
2788 {
2789 	WARN_ON_ONCE(filp != fl->c.flc_file);
2790 	if (filp->f_op->lock)
2791 		return filp->f_op->lock(filp, F_CANCELLK, fl);
2792 	return 0;
2793 }
2794 EXPORT_SYMBOL_GPL(vfs_cancel_lock);
2795 
2796 /**
2797  * vfs_inode_has_locks - are any file locks held on @inode?
2798  * @inode: inode to check for locks
2799  *
2800  * Return true if there are any FL_POSIX or FL_FLOCK locks currently
2801  * set on @inode.
2802  */
2803 bool vfs_inode_has_locks(struct inode *inode)
2804 {
2805 	struct file_lock_context *ctx;
2806 	bool ret;
2807 
2808 	ctx = locks_inode_context(inode);
2809 	if (!ctx)
2810 		return false;
2811 
2812 	spin_lock(&ctx->flc_lock);
2813 	ret = !list_empty(&ctx->flc_posix) || !list_empty(&ctx->flc_flock);
2814 	spin_unlock(&ctx->flc_lock);
2815 	return ret;
2816 }
2817 EXPORT_SYMBOL_GPL(vfs_inode_has_locks);
2818 
2819 #ifdef CONFIG_PROC_FS
2820 #include <linux/proc_fs.h>
2821 #include <linux/seq_file.h>
2822 
2823 struct locks_iterator {
2824 	int	li_cpu;
2825 	loff_t	li_pos;
2826 };
2827 
2828 static void lock_get_status(struct seq_file *f, struct file_lock_core *flc,
2829 			    loff_t id, char *pfx, int repeat)
2830 {
2831 	struct inode *inode = NULL;
2832 	unsigned int pid;
2833 	struct pid_namespace *proc_pidns = proc_pid_ns(file_inode(f->file)->i_sb);
2834 	int type = flc->flc_type;
2835 	struct file_lock *fl = file_lock(flc);
2836 
2837 	pid = locks_translate_pid(flc, proc_pidns);
2838 
2839 	/*
2840 	 * If lock owner is dead (and pid is freed) or not visible in current
2841 	 * pidns, zero is shown as a pid value. Check lock info from
2842 	 * init_pid_ns to get saved lock pid value.
2843 	 */
2844 	if (flc->flc_file != NULL)
2845 		inode = file_inode(flc->flc_file);
2846 
2847 	seq_printf(f, "%lld: ", id);
2848 
2849 	if (repeat)
2850 		seq_printf(f, "%*s", repeat - 1 + (int)strlen(pfx), pfx);
2851 
2852 	if (flc->flc_flags & FL_POSIX) {
2853 		if (flc->flc_flags & FL_ACCESS)
2854 			seq_puts(f, "ACCESS");
2855 		else if (flc->flc_flags & FL_OFDLCK)
2856 			seq_puts(f, "OFDLCK");
2857 		else
2858 			seq_puts(f, "POSIX ");
2859 
2860 		seq_printf(f, " %s ",
2861 			     (inode == NULL) ? "*NOINODE*" : "ADVISORY ");
2862 	} else if (flc->flc_flags & FL_FLOCK) {
2863 		seq_puts(f, "FLOCK  ADVISORY  ");
2864 	} else if (flc->flc_flags & (FL_LEASE|FL_DELEG|FL_LAYOUT)) {
2865 		struct file_lease *lease = file_lease(flc);
2866 
2867 		type = target_leasetype(lease);
2868 
2869 		if (flc->flc_flags & FL_DELEG)
2870 			seq_puts(f, "DELEG  ");
2871 		else
2872 			seq_puts(f, "LEASE  ");
2873 
2874 		if (lease_breaking(lease))
2875 			seq_puts(f, "BREAKING  ");
2876 		else if (flc->flc_file)
2877 			seq_puts(f, "ACTIVE    ");
2878 		else
2879 			seq_puts(f, "BREAKER   ");
2880 	} else {
2881 		seq_puts(f, "UNKNOWN UNKNOWN  ");
2882 	}
2883 
2884 	seq_printf(f, "%s ", (type == F_WRLCK) ? "WRITE" :
2885 			     (type == F_RDLCK) ? "READ" : "UNLCK");
2886 	if (inode) {
2887 		/* userspace relies on this representation of dev_t */
2888 		seq_printf(f, "%d %02x:%02x:%lu ", pid,
2889 				MAJOR(inode->i_sb->s_dev),
2890 				MINOR(inode->i_sb->s_dev), inode->i_ino);
2891 	} else {
2892 		seq_printf(f, "%d <none>:0 ", pid);
2893 	}
2894 	if (flc->flc_flags & FL_POSIX) {
2895 		if (fl->fl_end == OFFSET_MAX)
2896 			seq_printf(f, "%Ld EOF\n", fl->fl_start);
2897 		else
2898 			seq_printf(f, "%Ld %Ld\n", fl->fl_start, fl->fl_end);
2899 	} else {
2900 		seq_puts(f, "0 EOF\n");
2901 	}
2902 }
2903 
2904 static struct file_lock_core *get_next_blocked_member(struct file_lock_core *node)
2905 {
2906 	struct file_lock_core *tmp;
2907 
2908 	/* NULL node or root node */
2909 	if (node == NULL || node->flc_blocker == NULL)
2910 		return NULL;
2911 
2912 	/* Next member in the linked list could be itself */
2913 	tmp = list_next_entry(node, flc_blocked_member);
2914 	if (list_entry_is_head(tmp, &node->flc_blocker->flc_blocked_requests,
2915 			       flc_blocked_member)
2916 		|| tmp == node) {
2917 		return NULL;
2918 	}
2919 
2920 	return tmp;
2921 }
2922 
2923 static int locks_show(struct seq_file *f, void *v)
2924 {
2925 	struct locks_iterator *iter = f->private;
2926 	struct file_lock_core *cur, *tmp;
2927 	struct pid_namespace *proc_pidns = proc_pid_ns(file_inode(f->file)->i_sb);
2928 	int level = 0;
2929 
2930 	cur = hlist_entry(v, struct file_lock_core, flc_link);
2931 
2932 	if (locks_translate_pid(cur, proc_pidns) == 0)
2933 		return 0;
2934 
2935 	/* View this crossed linked list as a binary tree, the first member of flc_blocked_requests
2936 	 * is the left child of current node, the next silibing in flc_blocked_member is the
2937 	 * right child, we can alse get the parent of current node from flc_blocker, so this
2938 	 * question becomes traversal of a binary tree
2939 	 */
2940 	while (cur != NULL) {
2941 		if (level)
2942 			lock_get_status(f, cur, iter->li_pos, "-> ", level);
2943 		else
2944 			lock_get_status(f, cur, iter->li_pos, "", level);
2945 
2946 		if (!list_empty(&cur->flc_blocked_requests)) {
2947 			/* Turn left */
2948 			cur = list_first_entry_or_null(&cur->flc_blocked_requests,
2949 						       struct file_lock_core,
2950 						       flc_blocked_member);
2951 			level++;
2952 		} else {
2953 			/* Turn right */
2954 			tmp = get_next_blocked_member(cur);
2955 			/* Fall back to parent node */
2956 			while (tmp == NULL && cur->flc_blocker != NULL) {
2957 				cur = cur->flc_blocker;
2958 				level--;
2959 				tmp = get_next_blocked_member(cur);
2960 			}
2961 			cur = tmp;
2962 		}
2963 	}
2964 
2965 	return 0;
2966 }
2967 
2968 static void __show_fd_locks(struct seq_file *f,
2969 			struct list_head *head, int *id,
2970 			struct file *filp, struct files_struct *files)
2971 {
2972 	struct file_lock_core *fl;
2973 
2974 	list_for_each_entry(fl, head, flc_list) {
2975 
2976 		if (filp != fl->flc_file)
2977 			continue;
2978 		if (fl->flc_owner != files && fl->flc_owner != filp)
2979 			continue;
2980 
2981 		(*id)++;
2982 		seq_puts(f, "lock:\t");
2983 		lock_get_status(f, fl, *id, "", 0);
2984 	}
2985 }
2986 
2987 void show_fd_locks(struct seq_file *f,
2988 		  struct file *filp, struct files_struct *files)
2989 {
2990 	struct inode *inode = file_inode(filp);
2991 	struct file_lock_context *ctx;
2992 	int id = 0;
2993 
2994 	ctx = locks_inode_context(inode);
2995 	if (!ctx)
2996 		return;
2997 
2998 	spin_lock(&ctx->flc_lock);
2999 	__show_fd_locks(f, &ctx->flc_flock, &id, filp, files);
3000 	__show_fd_locks(f, &ctx->flc_posix, &id, filp, files);
3001 	__show_fd_locks(f, &ctx->flc_lease, &id, filp, files);
3002 	spin_unlock(&ctx->flc_lock);
3003 }
3004 
3005 static void *locks_start(struct seq_file *f, loff_t *pos)
3006 	__acquires(&blocked_lock_lock)
3007 {
3008 	struct locks_iterator *iter = f->private;
3009 
3010 	iter->li_pos = *pos + 1;
3011 	percpu_down_write(&file_rwsem);
3012 	spin_lock(&blocked_lock_lock);
3013 	return seq_hlist_start_percpu(&file_lock_list.hlist, &iter->li_cpu, *pos);
3014 }
3015 
3016 static void *locks_next(struct seq_file *f, void *v, loff_t *pos)
3017 {
3018 	struct locks_iterator *iter = f->private;
3019 
3020 	++iter->li_pos;
3021 	return seq_hlist_next_percpu(v, &file_lock_list.hlist, &iter->li_cpu, pos);
3022 }
3023 
3024 static void locks_stop(struct seq_file *f, void *v)
3025 	__releases(&blocked_lock_lock)
3026 {
3027 	spin_unlock(&blocked_lock_lock);
3028 	percpu_up_write(&file_rwsem);
3029 }
3030 
3031 static const struct seq_operations locks_seq_operations = {
3032 	.start	= locks_start,
3033 	.next	= locks_next,
3034 	.stop	= locks_stop,
3035 	.show	= locks_show,
3036 };
3037 
3038 static int __init proc_locks_init(void)
3039 {
3040 	proc_create_seq_private("locks", 0, NULL, &locks_seq_operations,
3041 			sizeof(struct locks_iterator), NULL);
3042 	return 0;
3043 }
3044 fs_initcall(proc_locks_init);
3045 #endif
3046 
3047 static int __init filelock_init(void)
3048 {
3049 	int i;
3050 
3051 	flctx_cache = kmem_cache_create("file_lock_ctx",
3052 			sizeof(struct file_lock_context), 0, SLAB_PANIC, NULL);
3053 
3054 	filelock_cache = kmem_cache_create("file_lock_cache",
3055 			sizeof(struct file_lock), 0, SLAB_PANIC, NULL);
3056 
3057 	filelease_cache = kmem_cache_create("file_lease_cache",
3058 			sizeof(struct file_lease), 0, SLAB_PANIC, NULL);
3059 
3060 	for_each_possible_cpu(i) {
3061 		struct file_lock_list_struct *fll = per_cpu_ptr(&file_lock_list, i);
3062 
3063 		spin_lock_init(&fll->lock);
3064 		INIT_HLIST_HEAD(&fll->hlist);
3065 	}
3066 
3067 	lease_notifier_chain_init();
3068 	return 0;
3069 }
3070 core_initcall(filelock_init);
3071