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