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