xref: /linux/kernel/locking/rwsem.c (revision 813b46808822db6838c43e92ba21ce013d23fcdc)
1 // SPDX-License-Identifier: GPL-2.0
2 /* kernel/rwsem.c: R/W semaphores, public implementation
3  *
4  * Written by David Howells (dhowells@redhat.com).
5  * Derived from asm-i386/semaphore.h
6  *
7  * Writer lock-stealing by Alex Shi <alex.shi@intel.com>
8  * and Michel Lespinasse <walken@google.com>
9  *
10  * Optimistic spinning by Tim Chen <tim.c.chen@intel.com>
11  * and Davidlohr Bueso <davidlohr@hp.com>. Based on mutexes.
12  *
13  * Rwsem count bit fields re-definition and rwsem rearchitecture by
14  * Waiman Long <longman@redhat.com> and
15  * Peter Zijlstra <peterz@infradead.org>.
16  */
17 
18 #include <linux/types.h>
19 #include <linux/kernel.h>
20 #include <linux/sched.h>
21 #include <linux/sched/rt.h>
22 #include <linux/sched/task.h>
23 #include <linux/sched/debug.h>
24 #include <linux/sched/wake_q.h>
25 #include <linux/sched/signal.h>
26 #include <linux/sched/clock.h>
27 #include <linux/export.h>
28 #include <linux/rwsem.h>
29 #include <linux/atomic.h>
30 #include <linux/hung_task.h>
31 #include <trace/events/lock.h>
32 
33 #ifndef CONFIG_PREEMPT_RT
34 #include "lock_events.h"
35 
36 /*
37  * The least significant 2 bits of the owner value has the following
38  * meanings when set.
39  *  - Bit 0: RWSEM_READER_OWNED - rwsem may be owned by readers (just a hint)
40  *  - Bit 1: RWSEM_NONSPINNABLE - Cannot spin on a reader-owned lock
41  *
42  * When the rwsem is reader-owned and a spinning writer has timed out,
43  * the nonspinnable bit will be set to disable optimistic spinning.
44 
45  * When a writer acquires a rwsem, it puts its task_struct pointer
46  * into the owner field. It is cleared after an unlock.
47  *
48  * When a reader acquires a rwsem, it will also puts its task_struct
49  * pointer into the owner field with the RWSEM_READER_OWNED bit set.
50  * On unlock, the owner field will largely be left untouched. So
51  * for a free or reader-owned rwsem, the owner value may contain
52  * information about the last reader that acquires the rwsem.
53  *
54  * That information may be helpful in debugging cases where the system
55  * seems to hang on a reader owned rwsem especially if only one reader
56  * is involved. Ideally we would like to track all the readers that own
57  * a rwsem, but the overhead is simply too big.
58  *
59  * A fast path reader optimistic lock stealing is supported when the rwsem
60  * is previously owned by a writer and the following conditions are met:
61  *  - rwsem is not currently writer owned
62  *  - the handoff isn't set.
63  */
64 #define RWSEM_READER_OWNED	(1UL << 0)
65 #define RWSEM_NONSPINNABLE	(1UL << 1)
66 #define RWSEM_OWNER_FLAGS_MASK	(RWSEM_READER_OWNED | RWSEM_NONSPINNABLE)
67 
68 #ifdef CONFIG_DEBUG_RWSEMS
69 # define DEBUG_RWSEMS_WARN_ON(c, sem)	do {			\
70 	if (!debug_locks_silent &&				\
71 	    WARN_ONCE(c, "DEBUG_RWSEMS_WARN_ON(%s): count = 0x%lx, magic = 0x%lx, owner = 0x%lx, curr 0x%lx, list %sempty\n",\
72 		#c, atomic_long_read(&(sem)->count),		\
73 		(unsigned long) sem->magic,			\
74 		atomic_long_read(&(sem)->owner), (long)current,	\
75 		list_empty(&(sem)->wait_list) ? "" : "not "))	\
76 			debug_locks_off();			\
77 	} while (0)
78 #else
79 # define DEBUG_RWSEMS_WARN_ON(c, sem)
80 #endif
81 
82 /*
83  * On 64-bit architectures, the bit definitions of the count are:
84  *
85  * Bit  0    - writer locked bit
86  * Bit  1    - waiters present bit
87  * Bit  2    - lock handoff bit
88  * Bits 3-7  - reserved
89  * Bits 8-62 - 55-bit reader count
90  * Bit  63   - read fail bit
91  *
92  * On 32-bit architectures, the bit definitions of the count are:
93  *
94  * Bit  0    - writer locked bit
95  * Bit  1    - waiters present bit
96  * Bit  2    - lock handoff bit
97  * Bits 3-7  - reserved
98  * Bits 8-30 - 23-bit reader count
99  * Bit  31   - read fail bit
100  *
101  * It is not likely that the most significant bit (read fail bit) will ever
102  * be set. This guard bit is still checked anyway in the down_read() fastpath
103  * just in case we need to use up more of the reader bits for other purpose
104  * in the future.
105  *
106  * atomic_long_fetch_add() is used to obtain reader lock, whereas
107  * atomic_long_cmpxchg() will be used to obtain writer lock.
108  *
109  * There are three places where the lock handoff bit may be set or cleared.
110  * 1) rwsem_mark_wake() for readers		-- set, clear
111  * 2) rwsem_try_write_lock() for writers	-- set, clear
112  * 3) rwsem_del_waiter()			-- clear
113  *
114  * For all the above cases, wait_lock will be held. A writer must also
115  * be the first one in the wait_list to be eligible for setting the handoff
116  * bit. So concurrent setting/clearing of handoff bit is not possible.
117  */
118 #define RWSEM_WRITER_LOCKED	(1UL << 0)
119 #define RWSEM_FLAG_WAITERS	(1UL << 1)
120 #define RWSEM_FLAG_HANDOFF	(1UL << 2)
121 #define RWSEM_FLAG_READFAIL	(1UL << (BITS_PER_LONG - 1))
122 
123 #define RWSEM_READER_SHIFT	8
124 #define RWSEM_READER_BIAS	(1UL << RWSEM_READER_SHIFT)
125 #define RWSEM_READER_MASK	(~(RWSEM_READER_BIAS - 1))
126 #define RWSEM_WRITER_MASK	RWSEM_WRITER_LOCKED
127 #define RWSEM_LOCK_MASK		(RWSEM_WRITER_MASK|RWSEM_READER_MASK)
128 #define RWSEM_READ_FAILED_MASK	(RWSEM_WRITER_MASK|RWSEM_FLAG_WAITERS|\
129 				 RWSEM_FLAG_HANDOFF|RWSEM_FLAG_READFAIL)
130 
131 /*
132  * All writes to owner are protected by WRITE_ONCE() to make sure that
133  * store tearing can't happen as optimistic spinners may read and use
134  * the owner value concurrently without lock. Read from owner, however,
135  * may not need READ_ONCE() as long as the pointer value is only used
136  * for comparison and isn't being dereferenced.
137  *
138  * Both rwsem_{set,clear}_owner() functions should be in the same
139  * preempt disable section as the atomic op that changes sem->count.
140  */
141 static inline void rwsem_set_owner(struct rw_semaphore *sem)
142 {
143 	lockdep_assert_preemption_disabled();
144 	atomic_long_set(&sem->owner, (long)current);
145 }
146 
147 static inline void rwsem_clear_owner(struct rw_semaphore *sem)
148 {
149 	lockdep_assert_preemption_disabled();
150 	atomic_long_set(&sem->owner, 0);
151 }
152 
153 /*
154  * Test the flags in the owner field.
155  */
156 static inline bool rwsem_test_oflags(struct rw_semaphore *sem, long flags)
157 {
158 	return atomic_long_read(&sem->owner) & flags;
159 }
160 
161 /*
162  * The task_struct pointer of the last owning reader will be left in
163  * the owner field.
164  *
165  * Note that the owner value just indicates the task has owned the rwsem
166  * previously, it may not be the real owner or one of the real owners
167  * anymore when that field is examined, so take it with a grain of salt.
168  *
169  * The reader non-spinnable bit is preserved.
170  */
171 static inline void __rwsem_set_reader_owned(struct rw_semaphore *sem,
172 					    struct task_struct *owner)
173 {
174 	unsigned long val = (unsigned long)owner | RWSEM_READER_OWNED |
175 		(atomic_long_read(&sem->owner) & RWSEM_NONSPINNABLE);
176 
177 	atomic_long_set(&sem->owner, val);
178 }
179 
180 static inline void rwsem_set_reader_owned(struct rw_semaphore *sem)
181 {
182 	__rwsem_set_reader_owned(sem, current);
183 }
184 
185 #if defined(CONFIG_DEBUG_RWSEMS) || defined(CONFIG_DETECT_HUNG_TASK_BLOCKER)
186 /*
187  * Return just the real task structure pointer of the owner
188  */
189 struct task_struct *rwsem_owner(struct rw_semaphore *sem)
190 {
191 	return (struct task_struct *)
192 		(atomic_long_read(&sem->owner) & ~RWSEM_OWNER_FLAGS_MASK);
193 }
194 
195 /*
196  * Return true if the rwsem is owned by a reader.
197  */
198 bool is_rwsem_reader_owned(struct rw_semaphore *sem)
199 {
200 	/*
201 	 * Check the count to see if it is write-locked.
202 	 */
203 	long count = atomic_long_read(&sem->count);
204 
205 	if (count & RWSEM_WRITER_MASK)
206 		return false;
207 	return rwsem_test_oflags(sem, RWSEM_READER_OWNED);
208 }
209 
210 /*
211  * With CONFIG_DEBUG_RWSEMS or CONFIG_DETECT_HUNG_TASK_BLOCKER configured,
212  * it will make sure that the owner field of a reader-owned rwsem either
213  * points to a real reader-owner(s) or gets cleared. The only exception is
214  * when the unlock is done by up_read_non_owner().
215  */
216 static inline void rwsem_clear_reader_owned(struct rw_semaphore *sem)
217 {
218 	unsigned long val = atomic_long_read(&sem->owner);
219 
220 	while ((val & ~RWSEM_OWNER_FLAGS_MASK) == (unsigned long)current) {
221 		if (atomic_long_try_cmpxchg(&sem->owner, &val,
222 					    val & RWSEM_OWNER_FLAGS_MASK))
223 			return;
224 	}
225 }
226 #else
227 static inline void rwsem_clear_reader_owned(struct rw_semaphore *sem)
228 {
229 }
230 #endif
231 
232 /*
233  * Set the RWSEM_NONSPINNABLE bits if the RWSEM_READER_OWNED flag
234  * remains set. Otherwise, the operation will be aborted.
235  */
236 static inline void rwsem_set_nonspinnable(struct rw_semaphore *sem)
237 {
238 	unsigned long owner = atomic_long_read(&sem->owner);
239 
240 	do {
241 		if (!(owner & RWSEM_READER_OWNED))
242 			break;
243 		if (owner & RWSEM_NONSPINNABLE)
244 			break;
245 	} while (!atomic_long_try_cmpxchg(&sem->owner, &owner,
246 					  owner | RWSEM_NONSPINNABLE));
247 }
248 
249 static inline bool rwsem_read_trylock(struct rw_semaphore *sem, long *cntp)
250 {
251 	*cntp = atomic_long_add_return_acquire(RWSEM_READER_BIAS, &sem->count);
252 
253 	if (WARN_ON_ONCE(*cntp < 0))
254 		rwsem_set_nonspinnable(sem);
255 
256 	if (!(*cntp & RWSEM_READ_FAILED_MASK)) {
257 		rwsem_set_reader_owned(sem);
258 		return true;
259 	}
260 
261 	return false;
262 }
263 
264 static inline bool rwsem_write_trylock(struct rw_semaphore *sem)
265 {
266 	long tmp = RWSEM_UNLOCKED_VALUE;
267 
268 	if (atomic_long_try_cmpxchg_acquire(&sem->count, &tmp, RWSEM_WRITER_LOCKED)) {
269 		rwsem_set_owner(sem);
270 		return true;
271 	}
272 
273 	return false;
274 }
275 
276 /*
277  * Return the real task structure pointer of the owner and the embedded
278  * flags in the owner. pflags must be non-NULL.
279  */
280 static inline struct task_struct *
281 rwsem_owner_flags(struct rw_semaphore *sem, unsigned long *pflags)
282 {
283 	unsigned long owner = atomic_long_read(&sem->owner);
284 
285 	*pflags = owner & RWSEM_OWNER_FLAGS_MASK;
286 	return (struct task_struct *)(owner & ~RWSEM_OWNER_FLAGS_MASK);
287 }
288 
289 /*
290  * Guide to the rw_semaphore's count field.
291  *
292  * When the RWSEM_WRITER_LOCKED bit in count is set, the lock is owned
293  * by a writer.
294  *
295  * The lock is owned by readers when
296  * (1) the RWSEM_WRITER_LOCKED isn't set in count,
297  * (2) some of the reader bits are set in count, and
298  * (3) the owner field has RWSEM_READ_OWNED bit set.
299  *
300  * Having some reader bits set is not enough to guarantee a readers owned
301  * lock as the readers may be in the process of backing out from the count
302  * and a writer has just released the lock. So another writer may steal
303  * the lock immediately after that.
304  */
305 
306 /*
307  * Initialize an rwsem:
308  */
309 void __init_rwsem(struct rw_semaphore *sem, const char *name,
310 		  struct lock_class_key *key)
311 {
312 #ifdef CONFIG_DEBUG_LOCK_ALLOC
313 	/*
314 	 * Make sure we are not reinitializing a held semaphore:
315 	 */
316 	debug_check_no_locks_freed((void *)sem, sizeof(*sem));
317 	lockdep_init_map_wait(&sem->dep_map, name, key, 0, LD_WAIT_SLEEP);
318 #endif
319 #ifdef CONFIG_DEBUG_RWSEMS
320 	sem->magic = sem;
321 #endif
322 	atomic_long_set(&sem->count, RWSEM_UNLOCKED_VALUE);
323 	raw_spin_lock_init(&sem->wait_lock);
324 	INIT_LIST_HEAD(&sem->wait_list);
325 	atomic_long_set(&sem->owner, 0L);
326 #ifdef CONFIG_RWSEM_SPIN_ON_OWNER
327 	osq_lock_init(&sem->osq);
328 #endif
329 }
330 EXPORT_SYMBOL(__init_rwsem);
331 
332 enum rwsem_waiter_type {
333 	RWSEM_WAITING_FOR_WRITE,
334 	RWSEM_WAITING_FOR_READ
335 };
336 
337 struct rwsem_waiter {
338 	struct list_head list;
339 	struct task_struct *task;
340 	enum rwsem_waiter_type type;
341 	unsigned long timeout;
342 	bool handoff_set;
343 };
344 #define rwsem_first_waiter(sem) \
345 	list_first_entry(&sem->wait_list, struct rwsem_waiter, list)
346 
347 enum rwsem_wake_type {
348 	RWSEM_WAKE_ANY,		/* Wake whatever's at head of wait list */
349 	RWSEM_WAKE_READERS,	/* Wake readers only */
350 	RWSEM_WAKE_READ_OWNED	/* Waker thread holds the read lock */
351 };
352 
353 /*
354  * The typical HZ value is either 250 or 1000. So set the minimum waiting
355  * time to at least 4ms or 1 jiffy (if it is higher than 4ms) in the wait
356  * queue before initiating the handoff protocol.
357  */
358 #define RWSEM_WAIT_TIMEOUT	DIV_ROUND_UP(HZ, 250)
359 
360 /*
361  * Magic number to batch-wakeup waiting readers, even when writers are
362  * also present in the queue. This both limits the amount of work the
363  * waking thread must do and also prevents any potential counter overflow,
364  * however unlikely.
365  */
366 #define MAX_READERS_WAKEUP	0x100
367 
368 static inline void
369 rwsem_add_waiter(struct rw_semaphore *sem, struct rwsem_waiter *waiter)
370 {
371 	lockdep_assert_held(&sem->wait_lock);
372 	list_add_tail(&waiter->list, &sem->wait_list);
373 	/* caller will set RWSEM_FLAG_WAITERS */
374 }
375 
376 /*
377  * Remove a waiter from the wait_list and clear flags.
378  *
379  * Both rwsem_mark_wake() and rwsem_try_write_lock() contain a full 'copy' of
380  * this function. Modify with care.
381  *
382  * Return: true if wait_list isn't empty and false otherwise
383  */
384 static inline bool
385 rwsem_del_waiter(struct rw_semaphore *sem, struct rwsem_waiter *waiter)
386 {
387 	lockdep_assert_held(&sem->wait_lock);
388 	list_del(&waiter->list);
389 	if (likely(!list_empty(&sem->wait_list)))
390 		return true;
391 
392 	atomic_long_andnot(RWSEM_FLAG_HANDOFF | RWSEM_FLAG_WAITERS, &sem->count);
393 	return false;
394 }
395 
396 /*
397  * handle the lock release when processes blocked on it that can now run
398  * - if we come here from up_xxxx(), then the RWSEM_FLAG_WAITERS bit must
399  *   have been set.
400  * - there must be someone on the queue
401  * - the wait_lock must be held by the caller
402  * - tasks are marked for wakeup, the caller must later invoke wake_up_q()
403  *   to actually wakeup the blocked task(s) and drop the reference count,
404  *   preferably when the wait_lock is released
405  * - woken process blocks are discarded from the list after having task zeroed
406  * - writers are only marked woken if downgrading is false
407  *
408  * Implies rwsem_del_waiter() for all woken readers.
409  */
410 static void rwsem_mark_wake(struct rw_semaphore *sem,
411 			    enum rwsem_wake_type wake_type,
412 			    struct wake_q_head *wake_q)
413 {
414 	struct rwsem_waiter *waiter, *tmp;
415 	long oldcount, woken = 0, adjustment = 0;
416 	struct list_head wlist;
417 
418 	lockdep_assert_held(&sem->wait_lock);
419 
420 	/*
421 	 * Take a peek at the queue head waiter such that we can determine
422 	 * the wakeup(s) to perform.
423 	 */
424 	waiter = rwsem_first_waiter(sem);
425 
426 	if (waiter->type == RWSEM_WAITING_FOR_WRITE) {
427 		if (wake_type == RWSEM_WAKE_ANY) {
428 			/*
429 			 * Mark writer at the front of the queue for wakeup.
430 			 * Until the task is actually later awoken later by
431 			 * the caller, other writers are able to steal it.
432 			 * Readers, on the other hand, will block as they
433 			 * will notice the queued writer.
434 			 */
435 			wake_q_add(wake_q, waiter->task);
436 			lockevent_inc(rwsem_wake_writer);
437 		}
438 
439 		return;
440 	}
441 
442 	/*
443 	 * No reader wakeup if there are too many of them already.
444 	 */
445 	if (unlikely(atomic_long_read(&sem->count) < 0))
446 		return;
447 
448 	/*
449 	 * Writers might steal the lock before we grant it to the next reader.
450 	 * We prefer to do the first reader grant before counting readers
451 	 * so we can bail out early if a writer stole the lock.
452 	 */
453 	if (wake_type != RWSEM_WAKE_READ_OWNED) {
454 		struct task_struct *owner;
455 
456 		adjustment = RWSEM_READER_BIAS;
457 		oldcount = atomic_long_fetch_add(adjustment, &sem->count);
458 		if (unlikely(oldcount & RWSEM_WRITER_MASK)) {
459 			/*
460 			 * When we've been waiting "too" long (for writers
461 			 * to give up the lock), request a HANDOFF to
462 			 * force the issue.
463 			 */
464 			if (time_after(jiffies, waiter->timeout)) {
465 				if (!(oldcount & RWSEM_FLAG_HANDOFF)) {
466 					adjustment -= RWSEM_FLAG_HANDOFF;
467 					lockevent_inc(rwsem_rlock_handoff);
468 				}
469 				waiter->handoff_set = true;
470 			}
471 
472 			atomic_long_add(-adjustment, &sem->count);
473 			return;
474 		}
475 		/*
476 		 * Set it to reader-owned to give spinners an early
477 		 * indication that readers now have the lock.
478 		 * The reader nonspinnable bit seen at slowpath entry of
479 		 * the reader is copied over.
480 		 */
481 		owner = waiter->task;
482 		__rwsem_set_reader_owned(sem, owner);
483 	}
484 
485 	/*
486 	 * Grant up to MAX_READERS_WAKEUP read locks to all the readers in the
487 	 * queue. We know that the woken will be at least 1 as we accounted
488 	 * for above. Note we increment the 'active part' of the count by the
489 	 * number of readers before waking any processes up.
490 	 *
491 	 * This is an adaptation of the phase-fair R/W locks where at the
492 	 * reader phase (first waiter is a reader), all readers are eligible
493 	 * to acquire the lock at the same time irrespective of their order
494 	 * in the queue. The writers acquire the lock according to their
495 	 * order in the queue.
496 	 *
497 	 * We have to do wakeup in 2 passes to prevent the possibility that
498 	 * the reader count may be decremented before it is incremented. It
499 	 * is because the to-be-woken waiter may not have slept yet. So it
500 	 * may see waiter->task got cleared, finish its critical section and
501 	 * do an unlock before the reader count increment.
502 	 *
503 	 * 1) Collect the read-waiters in a separate list, count them and
504 	 *    fully increment the reader count in rwsem.
505 	 * 2) For each waiters in the new list, clear waiter->task and
506 	 *    put them into wake_q to be woken up later.
507 	 */
508 	INIT_LIST_HEAD(&wlist);
509 	list_for_each_entry_safe(waiter, tmp, &sem->wait_list, list) {
510 		if (waiter->type == RWSEM_WAITING_FOR_WRITE)
511 			continue;
512 
513 		woken++;
514 		list_move_tail(&waiter->list, &wlist);
515 
516 		/*
517 		 * Limit # of readers that can be woken up per wakeup call.
518 		 */
519 		if (unlikely(woken >= MAX_READERS_WAKEUP))
520 			break;
521 	}
522 
523 	adjustment = woken * RWSEM_READER_BIAS - adjustment;
524 	lockevent_cond_inc(rwsem_wake_reader, woken);
525 
526 	oldcount = atomic_long_read(&sem->count);
527 	if (list_empty(&sem->wait_list)) {
528 		/*
529 		 * Combined with list_move_tail() above, this implies
530 		 * rwsem_del_waiter().
531 		 */
532 		adjustment -= RWSEM_FLAG_WAITERS;
533 		if (oldcount & RWSEM_FLAG_HANDOFF)
534 			adjustment -= RWSEM_FLAG_HANDOFF;
535 	} else if (woken) {
536 		/*
537 		 * When we've woken a reader, we no longer need to force
538 		 * writers to give up the lock and we can clear HANDOFF.
539 		 */
540 		if (oldcount & RWSEM_FLAG_HANDOFF)
541 			adjustment -= RWSEM_FLAG_HANDOFF;
542 	}
543 
544 	if (adjustment)
545 		atomic_long_add(adjustment, &sem->count);
546 
547 	/* 2nd pass */
548 	list_for_each_entry_safe(waiter, tmp, &wlist, list) {
549 		struct task_struct *tsk;
550 
551 		tsk = waiter->task;
552 		get_task_struct(tsk);
553 
554 		/*
555 		 * Ensure calling get_task_struct() before setting the reader
556 		 * waiter to nil such that rwsem_down_read_slowpath() cannot
557 		 * race with do_exit() by always holding a reference count
558 		 * to the task to wakeup.
559 		 */
560 		smp_store_release(&waiter->task, NULL);
561 		/*
562 		 * Ensure issuing the wakeup (either by us or someone else)
563 		 * after setting the reader waiter to nil.
564 		 */
565 		wake_q_add_safe(wake_q, tsk);
566 	}
567 }
568 
569 /*
570  * Remove a waiter and try to wake up other waiters in the wait queue
571  * This function is called from the out_nolock path of both the reader and
572  * writer slowpaths with wait_lock held. It releases the wait_lock and
573  * optionally wake up waiters before it returns.
574  */
575 static inline void
576 rwsem_del_wake_waiter(struct rw_semaphore *sem, struct rwsem_waiter *waiter,
577 		      struct wake_q_head *wake_q)
578 		      __releases(&sem->wait_lock)
579 {
580 	bool first = rwsem_first_waiter(sem) == waiter;
581 
582 	wake_q_init(wake_q);
583 
584 	/*
585 	 * If the wait_list isn't empty and the waiter to be deleted is
586 	 * the first waiter, we wake up the remaining waiters as they may
587 	 * be eligible to acquire or spin on the lock.
588 	 */
589 	if (rwsem_del_waiter(sem, waiter) && first)
590 		rwsem_mark_wake(sem, RWSEM_WAKE_ANY, wake_q);
591 	raw_spin_unlock_irq(&sem->wait_lock);
592 	if (!wake_q_empty(wake_q))
593 		wake_up_q(wake_q);
594 }
595 
596 /*
597  * This function must be called with the sem->wait_lock held to prevent
598  * race conditions between checking the rwsem wait list and setting the
599  * sem->count accordingly.
600  *
601  * Implies rwsem_del_waiter() on success.
602  */
603 static inline bool rwsem_try_write_lock(struct rw_semaphore *sem,
604 					struct rwsem_waiter *waiter)
605 {
606 	struct rwsem_waiter *first = rwsem_first_waiter(sem);
607 	long count, new;
608 
609 	lockdep_assert_held(&sem->wait_lock);
610 
611 	count = atomic_long_read(&sem->count);
612 	do {
613 		bool has_handoff = !!(count & RWSEM_FLAG_HANDOFF);
614 
615 		if (has_handoff) {
616 			/*
617 			 * Honor handoff bit and yield only when the first
618 			 * waiter is the one that set it. Otherwisee, we
619 			 * still try to acquire the rwsem.
620 			 */
621 			if (first->handoff_set && (waiter != first))
622 				return false;
623 		}
624 
625 		new = count;
626 
627 		if (count & RWSEM_LOCK_MASK) {
628 			/*
629 			 * A waiter (first or not) can set the handoff bit
630 			 * if it is an RT task or wait in the wait queue
631 			 * for too long.
632 			 */
633 			if (has_handoff || (!rt_or_dl_task(waiter->task) &&
634 					    !time_after(jiffies, waiter->timeout)))
635 				return false;
636 
637 			new |= RWSEM_FLAG_HANDOFF;
638 		} else {
639 			new |= RWSEM_WRITER_LOCKED;
640 			new &= ~RWSEM_FLAG_HANDOFF;
641 
642 			if (list_is_singular(&sem->wait_list))
643 				new &= ~RWSEM_FLAG_WAITERS;
644 		}
645 	} while (!atomic_long_try_cmpxchg_acquire(&sem->count, &count, new));
646 
647 	/*
648 	 * We have either acquired the lock with handoff bit cleared or set
649 	 * the handoff bit. Only the first waiter can have its handoff_set
650 	 * set here to enable optimistic spinning in slowpath loop.
651 	 */
652 	if (new & RWSEM_FLAG_HANDOFF) {
653 		first->handoff_set = true;
654 		lockevent_inc(rwsem_wlock_handoff);
655 		return false;
656 	}
657 
658 	/*
659 	 * Have rwsem_try_write_lock() fully imply rwsem_del_waiter() on
660 	 * success.
661 	 */
662 	list_del(&waiter->list);
663 	rwsem_set_owner(sem);
664 	return true;
665 }
666 
667 /*
668  * The rwsem_spin_on_owner() function returns the following 4 values
669  * depending on the lock owner state.
670  *   OWNER_NULL  : owner is currently NULL
671  *   OWNER_WRITER: when owner changes and is a writer
672  *   OWNER_READER: when owner changes and the new owner may be a reader.
673  *   OWNER_NONSPINNABLE:
674  *		   when optimistic spinning has to stop because either the
675  *		   owner stops running, is unknown, or its timeslice has
676  *		   been used up.
677  */
678 enum owner_state {
679 	OWNER_NULL		= 1 << 0,
680 	OWNER_WRITER		= 1 << 1,
681 	OWNER_READER		= 1 << 2,
682 	OWNER_NONSPINNABLE	= 1 << 3,
683 };
684 
685 #ifdef CONFIG_RWSEM_SPIN_ON_OWNER
686 /*
687  * Try to acquire write lock before the writer has been put on wait queue.
688  */
689 static inline bool rwsem_try_write_lock_unqueued(struct rw_semaphore *sem)
690 {
691 	long count = atomic_long_read(&sem->count);
692 
693 	while (!(count & (RWSEM_LOCK_MASK|RWSEM_FLAG_HANDOFF))) {
694 		if (atomic_long_try_cmpxchg_acquire(&sem->count, &count,
695 					count | RWSEM_WRITER_LOCKED)) {
696 			rwsem_set_owner(sem);
697 			lockevent_inc(rwsem_opt_lock);
698 			return true;
699 		}
700 	}
701 	return false;
702 }
703 
704 static inline bool rwsem_can_spin_on_owner(struct rw_semaphore *sem)
705 {
706 	struct task_struct *owner;
707 	unsigned long flags;
708 	bool ret = true;
709 
710 	if (need_resched()) {
711 		lockevent_inc(rwsem_opt_fail);
712 		return false;
713 	}
714 
715 	/*
716 	 * Disable preemption is equal to the RCU read-side crital section,
717 	 * thus the task_strcut structure won't go away.
718 	 */
719 	owner = rwsem_owner_flags(sem, &flags);
720 	/*
721 	 * Don't check the read-owner as the entry may be stale.
722 	 */
723 	if ((flags & RWSEM_NONSPINNABLE) ||
724 	    (owner && !(flags & RWSEM_READER_OWNED) && !owner_on_cpu(owner)))
725 		ret = false;
726 
727 	lockevent_cond_inc(rwsem_opt_fail, !ret);
728 	return ret;
729 }
730 
731 #define OWNER_SPINNABLE		(OWNER_NULL | OWNER_WRITER | OWNER_READER)
732 
733 static inline enum owner_state
734 rwsem_owner_state(struct task_struct *owner, unsigned long flags)
735 {
736 	if (flags & RWSEM_NONSPINNABLE)
737 		return OWNER_NONSPINNABLE;
738 
739 	if (flags & RWSEM_READER_OWNED)
740 		return OWNER_READER;
741 
742 	return owner ? OWNER_WRITER : OWNER_NULL;
743 }
744 
745 static noinline enum owner_state
746 rwsem_spin_on_owner(struct rw_semaphore *sem)
747 {
748 	struct task_struct *new, *owner;
749 	unsigned long flags, new_flags;
750 	enum owner_state state;
751 
752 	lockdep_assert_preemption_disabled();
753 
754 	owner = rwsem_owner_flags(sem, &flags);
755 	state = rwsem_owner_state(owner, flags);
756 	if (state != OWNER_WRITER)
757 		return state;
758 
759 	for (;;) {
760 		/*
761 		 * When a waiting writer set the handoff flag, it may spin
762 		 * on the owner as well. Once that writer acquires the lock,
763 		 * we can spin on it. So we don't need to quit even when the
764 		 * handoff bit is set.
765 		 */
766 		new = rwsem_owner_flags(sem, &new_flags);
767 		if ((new != owner) || (new_flags != flags)) {
768 			state = rwsem_owner_state(new, new_flags);
769 			break;
770 		}
771 
772 		/*
773 		 * Ensure we emit the owner->on_cpu, dereference _after_
774 		 * checking sem->owner still matches owner, if that fails,
775 		 * owner might point to free()d memory, if it still matches,
776 		 * our spinning context already disabled preemption which is
777 		 * equal to RCU read-side crital section ensures the memory
778 		 * stays valid.
779 		 */
780 		barrier();
781 
782 		if (need_resched() || !owner_on_cpu(owner)) {
783 			state = OWNER_NONSPINNABLE;
784 			break;
785 		}
786 
787 		cpu_relax();
788 	}
789 
790 	return state;
791 }
792 
793 /*
794  * Calculate reader-owned rwsem spinning threshold for writer
795  *
796  * The more readers own the rwsem, the longer it will take for them to
797  * wind down and free the rwsem. So the empirical formula used to
798  * determine the actual spinning time limit here is:
799  *
800  *   Spinning threshold = (10 + nr_readers/2)us
801  *
802  * The limit is capped to a maximum of 25us (30 readers). This is just
803  * a heuristic and is subjected to change in the future.
804  */
805 static inline u64 rwsem_rspin_threshold(struct rw_semaphore *sem)
806 {
807 	long count = atomic_long_read(&sem->count);
808 	int readers = count >> RWSEM_READER_SHIFT;
809 	u64 delta;
810 
811 	if (readers > 30)
812 		readers = 30;
813 	delta = (20 + readers) * NSEC_PER_USEC / 2;
814 
815 	return sched_clock() + delta;
816 }
817 
818 static bool rwsem_optimistic_spin(struct rw_semaphore *sem)
819 {
820 	bool taken = false;
821 	int prev_owner_state = OWNER_NULL;
822 	int loop = 0;
823 	u64 rspin_threshold = 0;
824 
825 	/* sem->wait_lock should not be held when doing optimistic spinning */
826 	if (!osq_lock(&sem->osq))
827 		goto done;
828 
829 	/*
830 	 * Optimistically spin on the owner field and attempt to acquire the
831 	 * lock whenever the owner changes. Spinning will be stopped when:
832 	 *  1) the owning writer isn't running; or
833 	 *  2) readers own the lock and spinning time has exceeded limit.
834 	 */
835 	for (;;) {
836 		enum owner_state owner_state;
837 
838 		owner_state = rwsem_spin_on_owner(sem);
839 		if (!(owner_state & OWNER_SPINNABLE))
840 			break;
841 
842 		/*
843 		 * Try to acquire the lock
844 		 */
845 		taken = rwsem_try_write_lock_unqueued(sem);
846 
847 		if (taken)
848 			break;
849 
850 		/*
851 		 * Time-based reader-owned rwsem optimistic spinning
852 		 */
853 		if (owner_state == OWNER_READER) {
854 			/*
855 			 * Re-initialize rspin_threshold every time when
856 			 * the owner state changes from non-reader to reader.
857 			 * This allows a writer to steal the lock in between
858 			 * 2 reader phases and have the threshold reset at
859 			 * the beginning of the 2nd reader phase.
860 			 */
861 			if (prev_owner_state != OWNER_READER) {
862 				if (rwsem_test_oflags(sem, RWSEM_NONSPINNABLE))
863 					break;
864 				rspin_threshold = rwsem_rspin_threshold(sem);
865 				loop = 0;
866 			}
867 
868 			/*
869 			 * Check time threshold once every 16 iterations to
870 			 * avoid calling sched_clock() too frequently so
871 			 * as to reduce the average latency between the times
872 			 * when the lock becomes free and when the spinner
873 			 * is ready to do a trylock.
874 			 */
875 			else if (!(++loop & 0xf) && (sched_clock() > rspin_threshold)) {
876 				rwsem_set_nonspinnable(sem);
877 				lockevent_inc(rwsem_opt_nospin);
878 				break;
879 			}
880 		}
881 
882 		/*
883 		 * An RT task cannot do optimistic spinning if it cannot
884 		 * be sure the lock holder is running or live-lock may
885 		 * happen if the current task and the lock holder happen
886 		 * to run in the same CPU. However, aborting optimistic
887 		 * spinning while a NULL owner is detected may miss some
888 		 * opportunity where spinning can continue without causing
889 		 * problem.
890 		 *
891 		 * There are 2 possible cases where an RT task may be able
892 		 * to continue spinning.
893 		 *
894 		 * 1) The lock owner is in the process of releasing the
895 		 *    lock, sem->owner is cleared but the lock has not
896 		 *    been released yet.
897 		 * 2) The lock was free and owner cleared, but another
898 		 *    task just comes in and acquire the lock before
899 		 *    we try to get it. The new owner may be a spinnable
900 		 *    writer.
901 		 *
902 		 * To take advantage of two scenarios listed above, the RT
903 		 * task is made to retry one more time to see if it can
904 		 * acquire the lock or continue spinning on the new owning
905 		 * writer. Of course, if the time lag is long enough or the
906 		 * new owner is not a writer or spinnable, the RT task will
907 		 * quit spinning.
908 		 *
909 		 * If the owner is a writer, the need_resched() check is
910 		 * done inside rwsem_spin_on_owner(). If the owner is not
911 		 * a writer, need_resched() check needs to be done here.
912 		 */
913 		if (owner_state != OWNER_WRITER) {
914 			if (need_resched())
915 				break;
916 			if (rt_or_dl_task(current) &&
917 			   (prev_owner_state != OWNER_WRITER))
918 				break;
919 		}
920 		prev_owner_state = owner_state;
921 
922 		/*
923 		 * The cpu_relax() call is a compiler barrier which forces
924 		 * everything in this loop to be re-loaded. We don't need
925 		 * memory barriers as we'll eventually observe the right
926 		 * values at the cost of a few extra spins.
927 		 */
928 		cpu_relax();
929 	}
930 	osq_unlock(&sem->osq);
931 done:
932 	lockevent_cond_inc(rwsem_opt_fail, !taken);
933 	return taken;
934 }
935 
936 /*
937  * Clear the owner's RWSEM_NONSPINNABLE bit if it is set. This should
938  * only be called when the reader count reaches 0.
939  */
940 static inline void clear_nonspinnable(struct rw_semaphore *sem)
941 {
942 	if (unlikely(rwsem_test_oflags(sem, RWSEM_NONSPINNABLE)))
943 		atomic_long_andnot(RWSEM_NONSPINNABLE, &sem->owner);
944 }
945 
946 #else
947 static inline bool rwsem_can_spin_on_owner(struct rw_semaphore *sem)
948 {
949 	return false;
950 }
951 
952 static inline bool rwsem_optimistic_spin(struct rw_semaphore *sem)
953 {
954 	return false;
955 }
956 
957 static inline void clear_nonspinnable(struct rw_semaphore *sem) { }
958 
959 static inline enum owner_state
960 rwsem_spin_on_owner(struct rw_semaphore *sem)
961 {
962 	return OWNER_NONSPINNABLE;
963 }
964 #endif
965 
966 /*
967  * Prepare to wake up waiter(s) in the wait queue by putting them into the
968  * given wake_q if the rwsem lock owner isn't a writer. If rwsem is likely
969  * reader-owned, wake up read lock waiters in queue front or wake up any
970  * front waiter otherwise.
971 
972  * This is being called from both reader and writer slow paths.
973  */
974 static inline void rwsem_cond_wake_waiter(struct rw_semaphore *sem, long count,
975 					  struct wake_q_head *wake_q)
976 {
977 	enum rwsem_wake_type wake_type;
978 
979 	if (count & RWSEM_WRITER_MASK)
980 		return;
981 
982 	if (count & RWSEM_READER_MASK) {
983 		wake_type = RWSEM_WAKE_READERS;
984 	} else {
985 		wake_type = RWSEM_WAKE_ANY;
986 		clear_nonspinnable(sem);
987 	}
988 	rwsem_mark_wake(sem, wake_type, wake_q);
989 }
990 
991 /*
992  * Wait for the read lock to be granted
993  */
994 static struct rw_semaphore __sched *
995 rwsem_down_read_slowpath(struct rw_semaphore *sem, long count, unsigned int state)
996 {
997 	long adjustment = -RWSEM_READER_BIAS;
998 	long rcnt = (count >> RWSEM_READER_SHIFT);
999 	struct rwsem_waiter waiter;
1000 	DEFINE_WAKE_Q(wake_q);
1001 
1002 	/*
1003 	 * To prevent a constant stream of readers from starving a sleeping
1004 	 * writer, don't attempt optimistic lock stealing if the lock is
1005 	 * very likely owned by readers.
1006 	 */
1007 	if ((atomic_long_read(&sem->owner) & RWSEM_READER_OWNED) &&
1008 	    (rcnt > 1) && !(count & RWSEM_WRITER_LOCKED))
1009 		goto queue;
1010 
1011 	/*
1012 	 * Reader optimistic lock stealing.
1013 	 */
1014 	if (!(count & (RWSEM_WRITER_LOCKED | RWSEM_FLAG_HANDOFF))) {
1015 		rwsem_set_reader_owned(sem);
1016 		lockevent_inc(rwsem_rlock_steal);
1017 
1018 		/*
1019 		 * Wake up other readers in the wait queue if it is
1020 		 * the first reader.
1021 		 */
1022 		if ((rcnt == 1) && (count & RWSEM_FLAG_WAITERS)) {
1023 			raw_spin_lock_irq(&sem->wait_lock);
1024 			if (!list_empty(&sem->wait_list))
1025 				rwsem_mark_wake(sem, RWSEM_WAKE_READ_OWNED,
1026 						&wake_q);
1027 			raw_spin_unlock_irq(&sem->wait_lock);
1028 			wake_up_q(&wake_q);
1029 		}
1030 		return sem;
1031 	}
1032 
1033 queue:
1034 	waiter.task = current;
1035 	waiter.type = RWSEM_WAITING_FOR_READ;
1036 	waiter.timeout = jiffies + RWSEM_WAIT_TIMEOUT;
1037 	waiter.handoff_set = false;
1038 
1039 	raw_spin_lock_irq(&sem->wait_lock);
1040 	if (list_empty(&sem->wait_list)) {
1041 		/*
1042 		 * In case the wait queue is empty and the lock isn't owned
1043 		 * by a writer, this reader can exit the slowpath and return
1044 		 * immediately as its RWSEM_READER_BIAS has already been set
1045 		 * in the count.
1046 		 */
1047 		if (!(atomic_long_read(&sem->count) & RWSEM_WRITER_MASK)) {
1048 			/* Provide lock ACQUIRE */
1049 			smp_acquire__after_ctrl_dep();
1050 			raw_spin_unlock_irq(&sem->wait_lock);
1051 			rwsem_set_reader_owned(sem);
1052 			lockevent_inc(rwsem_rlock_fast);
1053 			return sem;
1054 		}
1055 		adjustment += RWSEM_FLAG_WAITERS;
1056 	}
1057 	rwsem_add_waiter(sem, &waiter);
1058 
1059 	/* we're now waiting on the lock, but no longer actively locking */
1060 	count = atomic_long_add_return(adjustment, &sem->count);
1061 
1062 	rwsem_cond_wake_waiter(sem, count, &wake_q);
1063 	raw_spin_unlock_irq(&sem->wait_lock);
1064 
1065 	if (!wake_q_empty(&wake_q))
1066 		wake_up_q(&wake_q);
1067 
1068 	trace_contention_begin(sem, LCB_F_READ);
1069 	set_current_state(state);
1070 
1071 	if (state == TASK_UNINTERRUPTIBLE)
1072 		hung_task_set_blocker(sem, BLOCKER_TYPE_RWSEM_READER);
1073 
1074 	/* wait to be given the lock */
1075 	for (;;) {
1076 		if (!smp_load_acquire(&waiter.task)) {
1077 			/* Matches rwsem_mark_wake()'s smp_store_release(). */
1078 			break;
1079 		}
1080 		if (signal_pending_state(state, current)) {
1081 			raw_spin_lock_irq(&sem->wait_lock);
1082 			if (waiter.task)
1083 				goto out_nolock;
1084 			raw_spin_unlock_irq(&sem->wait_lock);
1085 			/* Ordered by sem->wait_lock against rwsem_mark_wake(). */
1086 			break;
1087 		}
1088 		schedule_preempt_disabled();
1089 		lockevent_inc(rwsem_sleep_reader);
1090 		set_current_state(state);
1091 	}
1092 
1093 	if (state == TASK_UNINTERRUPTIBLE)
1094 		hung_task_clear_blocker();
1095 
1096 	__set_current_state(TASK_RUNNING);
1097 	lockevent_inc(rwsem_rlock);
1098 	trace_contention_end(sem, 0);
1099 	return sem;
1100 
1101 out_nolock:
1102 	rwsem_del_wake_waiter(sem, &waiter, &wake_q);
1103 	__set_current_state(TASK_RUNNING);
1104 	lockevent_inc(rwsem_rlock_fail);
1105 	trace_contention_end(sem, -EINTR);
1106 	return ERR_PTR(-EINTR);
1107 }
1108 
1109 /*
1110  * Wait until we successfully acquire the write lock
1111  */
1112 static struct rw_semaphore __sched *
1113 rwsem_down_write_slowpath(struct rw_semaphore *sem, int state)
1114 {
1115 	struct rwsem_waiter waiter;
1116 	DEFINE_WAKE_Q(wake_q);
1117 
1118 	/* do optimistic spinning and steal lock if possible */
1119 	if (rwsem_can_spin_on_owner(sem) && rwsem_optimistic_spin(sem)) {
1120 		/* rwsem_optimistic_spin() implies ACQUIRE on success */
1121 		return sem;
1122 	}
1123 
1124 	/*
1125 	 * Optimistic spinning failed, proceed to the slowpath
1126 	 * and block until we can acquire the sem.
1127 	 */
1128 	waiter.task = current;
1129 	waiter.type = RWSEM_WAITING_FOR_WRITE;
1130 	waiter.timeout = jiffies + RWSEM_WAIT_TIMEOUT;
1131 	waiter.handoff_set = false;
1132 
1133 	raw_spin_lock_irq(&sem->wait_lock);
1134 	rwsem_add_waiter(sem, &waiter);
1135 
1136 	/* we're now waiting on the lock */
1137 	if (rwsem_first_waiter(sem) != &waiter) {
1138 		rwsem_cond_wake_waiter(sem, atomic_long_read(&sem->count),
1139 				       &wake_q);
1140 		if (!wake_q_empty(&wake_q)) {
1141 			/*
1142 			 * We want to minimize wait_lock hold time especially
1143 			 * when a large number of readers are to be woken up.
1144 			 */
1145 			raw_spin_unlock_irq(&sem->wait_lock);
1146 			wake_up_q(&wake_q);
1147 			raw_spin_lock_irq(&sem->wait_lock);
1148 		}
1149 	} else {
1150 		atomic_long_or(RWSEM_FLAG_WAITERS, &sem->count);
1151 	}
1152 
1153 	/* wait until we successfully acquire the lock */
1154 	set_current_state(state);
1155 	trace_contention_begin(sem, LCB_F_WRITE);
1156 
1157 	if (state == TASK_UNINTERRUPTIBLE)
1158 		hung_task_set_blocker(sem, BLOCKER_TYPE_RWSEM_WRITER);
1159 
1160 	for (;;) {
1161 		if (rwsem_try_write_lock(sem, &waiter)) {
1162 			/* rwsem_try_write_lock() implies ACQUIRE on success */
1163 			break;
1164 		}
1165 
1166 		raw_spin_unlock_irq(&sem->wait_lock);
1167 
1168 		if (signal_pending_state(state, current))
1169 			goto out_nolock;
1170 
1171 		/*
1172 		 * After setting the handoff bit and failing to acquire
1173 		 * the lock, attempt to spin on owner to accelerate lock
1174 		 * transfer. If the previous owner is a on-cpu writer and it
1175 		 * has just released the lock, OWNER_NULL will be returned.
1176 		 * In this case, we attempt to acquire the lock again
1177 		 * without sleeping.
1178 		 */
1179 		if (waiter.handoff_set) {
1180 			enum owner_state owner_state;
1181 
1182 			owner_state = rwsem_spin_on_owner(sem);
1183 			if (owner_state == OWNER_NULL)
1184 				goto trylock_again;
1185 		}
1186 
1187 		schedule_preempt_disabled();
1188 		lockevent_inc(rwsem_sleep_writer);
1189 		set_current_state(state);
1190 trylock_again:
1191 		raw_spin_lock_irq(&sem->wait_lock);
1192 	}
1193 
1194 	if (state == TASK_UNINTERRUPTIBLE)
1195 		hung_task_clear_blocker();
1196 
1197 	__set_current_state(TASK_RUNNING);
1198 	raw_spin_unlock_irq(&sem->wait_lock);
1199 	lockevent_inc(rwsem_wlock);
1200 	trace_contention_end(sem, 0);
1201 	return sem;
1202 
1203 out_nolock:
1204 	__set_current_state(TASK_RUNNING);
1205 	raw_spin_lock_irq(&sem->wait_lock);
1206 	rwsem_del_wake_waiter(sem, &waiter, &wake_q);
1207 	lockevent_inc(rwsem_wlock_fail);
1208 	trace_contention_end(sem, -EINTR);
1209 	return ERR_PTR(-EINTR);
1210 }
1211 
1212 /*
1213  * handle waking up a waiter on the semaphore
1214  * - up_read/up_write has decremented the active part of count if we come here
1215  */
1216 static struct rw_semaphore *rwsem_wake(struct rw_semaphore *sem)
1217 {
1218 	unsigned long flags;
1219 	DEFINE_WAKE_Q(wake_q);
1220 
1221 	raw_spin_lock_irqsave(&sem->wait_lock, flags);
1222 
1223 	if (!list_empty(&sem->wait_list))
1224 		rwsem_mark_wake(sem, RWSEM_WAKE_ANY, &wake_q);
1225 
1226 	raw_spin_unlock_irqrestore(&sem->wait_lock, flags);
1227 	wake_up_q(&wake_q);
1228 
1229 	return sem;
1230 }
1231 
1232 /*
1233  * downgrade a write lock into a read lock
1234  * - caller incremented waiting part of count and discovered it still negative
1235  * - just wake up any readers at the front of the queue
1236  */
1237 static struct rw_semaphore *rwsem_downgrade_wake(struct rw_semaphore *sem)
1238 {
1239 	unsigned long flags;
1240 	DEFINE_WAKE_Q(wake_q);
1241 
1242 	raw_spin_lock_irqsave(&sem->wait_lock, flags);
1243 
1244 	if (!list_empty(&sem->wait_list))
1245 		rwsem_mark_wake(sem, RWSEM_WAKE_READ_OWNED, &wake_q);
1246 
1247 	raw_spin_unlock_irqrestore(&sem->wait_lock, flags);
1248 	wake_up_q(&wake_q);
1249 
1250 	return sem;
1251 }
1252 
1253 /*
1254  * lock for reading
1255  */
1256 static __always_inline int __down_read_common(struct rw_semaphore *sem, int state)
1257 {
1258 	int ret = 0;
1259 	long count;
1260 
1261 	preempt_disable();
1262 	if (!rwsem_read_trylock(sem, &count)) {
1263 		if (IS_ERR(rwsem_down_read_slowpath(sem, count, state))) {
1264 			ret = -EINTR;
1265 			goto out;
1266 		}
1267 		DEBUG_RWSEMS_WARN_ON(!is_rwsem_reader_owned(sem), sem);
1268 	}
1269 out:
1270 	preempt_enable();
1271 	return ret;
1272 }
1273 
1274 static __always_inline void __down_read(struct rw_semaphore *sem)
1275 {
1276 	__down_read_common(sem, TASK_UNINTERRUPTIBLE);
1277 }
1278 
1279 static __always_inline int __down_read_interruptible(struct rw_semaphore *sem)
1280 {
1281 	return __down_read_common(sem, TASK_INTERRUPTIBLE);
1282 }
1283 
1284 static __always_inline int __down_read_killable(struct rw_semaphore *sem)
1285 {
1286 	return __down_read_common(sem, TASK_KILLABLE);
1287 }
1288 
1289 static inline int __down_read_trylock(struct rw_semaphore *sem)
1290 {
1291 	int ret = 0;
1292 	long tmp;
1293 
1294 	DEBUG_RWSEMS_WARN_ON(sem->magic != sem, sem);
1295 
1296 	preempt_disable();
1297 	tmp = atomic_long_read(&sem->count);
1298 	while (!(tmp & RWSEM_READ_FAILED_MASK)) {
1299 		if (atomic_long_try_cmpxchg_acquire(&sem->count, &tmp,
1300 						    tmp + RWSEM_READER_BIAS)) {
1301 			rwsem_set_reader_owned(sem);
1302 			ret = 1;
1303 			break;
1304 		}
1305 	}
1306 	preempt_enable();
1307 	return ret;
1308 }
1309 
1310 /*
1311  * lock for writing
1312  */
1313 static __always_inline int __down_write_common(struct rw_semaphore *sem, int state)
1314 {
1315 	int ret = 0;
1316 
1317 	preempt_disable();
1318 	if (unlikely(!rwsem_write_trylock(sem))) {
1319 		if (IS_ERR(rwsem_down_write_slowpath(sem, state)))
1320 			ret = -EINTR;
1321 	}
1322 	preempt_enable();
1323 	return ret;
1324 }
1325 
1326 static __always_inline void __down_write(struct rw_semaphore *sem)
1327 {
1328 	__down_write_common(sem, TASK_UNINTERRUPTIBLE);
1329 }
1330 
1331 static __always_inline int __down_write_killable(struct rw_semaphore *sem)
1332 {
1333 	return __down_write_common(sem, TASK_KILLABLE);
1334 }
1335 
1336 static inline int __down_write_trylock(struct rw_semaphore *sem)
1337 {
1338 	int ret;
1339 
1340 	preempt_disable();
1341 	DEBUG_RWSEMS_WARN_ON(sem->magic != sem, sem);
1342 	ret = rwsem_write_trylock(sem);
1343 	preempt_enable();
1344 
1345 	return ret;
1346 }
1347 
1348 /*
1349  * unlock after reading
1350  */
1351 static inline void __up_read(struct rw_semaphore *sem)
1352 {
1353 	long tmp;
1354 
1355 	DEBUG_RWSEMS_WARN_ON(sem->magic != sem, sem);
1356 	DEBUG_RWSEMS_WARN_ON(!is_rwsem_reader_owned(sem), sem);
1357 
1358 	preempt_disable();
1359 	rwsem_clear_reader_owned(sem);
1360 	tmp = atomic_long_add_return_release(-RWSEM_READER_BIAS, &sem->count);
1361 	DEBUG_RWSEMS_WARN_ON(tmp < 0, sem);
1362 	if (unlikely((tmp & (RWSEM_LOCK_MASK|RWSEM_FLAG_WAITERS)) ==
1363 		      RWSEM_FLAG_WAITERS)) {
1364 		clear_nonspinnable(sem);
1365 		rwsem_wake(sem);
1366 	}
1367 	preempt_enable();
1368 }
1369 
1370 /*
1371  * unlock after writing
1372  */
1373 static inline void __up_write(struct rw_semaphore *sem)
1374 {
1375 	long tmp;
1376 
1377 	DEBUG_RWSEMS_WARN_ON(sem->magic != sem, sem);
1378 	/*
1379 	 * sem->owner may differ from current if the ownership is transferred
1380 	 * to an anonymous writer by setting the RWSEM_NONSPINNABLE bits.
1381 	 */
1382 	DEBUG_RWSEMS_WARN_ON((rwsem_owner(sem) != current) &&
1383 			    !rwsem_test_oflags(sem, RWSEM_NONSPINNABLE), sem);
1384 
1385 	preempt_disable();
1386 	rwsem_clear_owner(sem);
1387 	tmp = atomic_long_fetch_add_release(-RWSEM_WRITER_LOCKED, &sem->count);
1388 	if (unlikely(tmp & RWSEM_FLAG_WAITERS))
1389 		rwsem_wake(sem);
1390 	preempt_enable();
1391 }
1392 
1393 /*
1394  * downgrade write lock to read lock
1395  */
1396 static inline void __downgrade_write(struct rw_semaphore *sem)
1397 {
1398 	long tmp;
1399 
1400 	/*
1401 	 * When downgrading from exclusive to shared ownership,
1402 	 * anything inside the write-locked region cannot leak
1403 	 * into the read side. In contrast, anything in the
1404 	 * read-locked region is ok to be re-ordered into the
1405 	 * write side. As such, rely on RELEASE semantics.
1406 	 */
1407 	DEBUG_RWSEMS_WARN_ON(rwsem_owner(sem) != current, sem);
1408 	preempt_disable();
1409 	tmp = atomic_long_fetch_add_release(
1410 		-RWSEM_WRITER_LOCKED+RWSEM_READER_BIAS, &sem->count);
1411 	rwsem_set_reader_owned(sem);
1412 	if (tmp & RWSEM_FLAG_WAITERS)
1413 		rwsem_downgrade_wake(sem);
1414 	preempt_enable();
1415 }
1416 
1417 #else /* !CONFIG_PREEMPT_RT */
1418 
1419 #define RT_MUTEX_BUILD_MUTEX
1420 #include "rtmutex.c"
1421 
1422 #define rwbase_set_and_save_current_state(state)	\
1423 	set_current_state(state)
1424 
1425 #define rwbase_restore_current_state()			\
1426 	__set_current_state(TASK_RUNNING)
1427 
1428 #define rwbase_rtmutex_lock_state(rtm, state)		\
1429 	__rt_mutex_lock(rtm, state)
1430 
1431 #define rwbase_rtmutex_slowlock_locked(rtm, state, wq)	\
1432 	__rt_mutex_slowlock_locked(rtm, NULL, state, wq)
1433 
1434 #define rwbase_rtmutex_unlock(rtm)			\
1435 	__rt_mutex_unlock(rtm)
1436 
1437 #define rwbase_rtmutex_trylock(rtm)			\
1438 	__rt_mutex_trylock(rtm)
1439 
1440 #define rwbase_signal_pending_state(state, current)	\
1441 	signal_pending_state(state, current)
1442 
1443 #define rwbase_pre_schedule()				\
1444 	rt_mutex_pre_schedule()
1445 
1446 #define rwbase_schedule()				\
1447 	rt_mutex_schedule()
1448 
1449 #define rwbase_post_schedule()				\
1450 	rt_mutex_post_schedule()
1451 
1452 #include "rwbase_rt.c"
1453 
1454 void __init_rwsem(struct rw_semaphore *sem, const char *name,
1455 		  struct lock_class_key *key)
1456 {
1457 	init_rwbase_rt(&(sem)->rwbase);
1458 
1459 #ifdef CONFIG_DEBUG_LOCK_ALLOC
1460 	debug_check_no_locks_freed((void *)sem, sizeof(*sem));
1461 	lockdep_init_map_wait(&sem->dep_map, name, key, 0, LD_WAIT_SLEEP);
1462 #endif
1463 }
1464 EXPORT_SYMBOL(__init_rwsem);
1465 
1466 static inline void __down_read(struct rw_semaphore *sem)
1467 {
1468 	rwbase_read_lock(&sem->rwbase, TASK_UNINTERRUPTIBLE);
1469 }
1470 
1471 static inline int __down_read_interruptible(struct rw_semaphore *sem)
1472 {
1473 	return rwbase_read_lock(&sem->rwbase, TASK_INTERRUPTIBLE);
1474 }
1475 
1476 static inline int __down_read_killable(struct rw_semaphore *sem)
1477 {
1478 	return rwbase_read_lock(&sem->rwbase, TASK_KILLABLE);
1479 }
1480 
1481 static inline int __down_read_trylock(struct rw_semaphore *sem)
1482 {
1483 	return rwbase_read_trylock(&sem->rwbase);
1484 }
1485 
1486 static inline void __up_read(struct rw_semaphore *sem)
1487 {
1488 	rwbase_read_unlock(&sem->rwbase, TASK_NORMAL);
1489 }
1490 
1491 static inline void __sched __down_write(struct rw_semaphore *sem)
1492 {
1493 	rwbase_write_lock(&sem->rwbase, TASK_UNINTERRUPTIBLE);
1494 }
1495 
1496 static inline int __sched __down_write_killable(struct rw_semaphore *sem)
1497 {
1498 	return rwbase_write_lock(&sem->rwbase, TASK_KILLABLE);
1499 }
1500 
1501 static inline int __down_write_trylock(struct rw_semaphore *sem)
1502 {
1503 	return rwbase_write_trylock(&sem->rwbase);
1504 }
1505 
1506 static inline void __up_write(struct rw_semaphore *sem)
1507 {
1508 	rwbase_write_unlock(&sem->rwbase);
1509 }
1510 
1511 static inline void __downgrade_write(struct rw_semaphore *sem)
1512 {
1513 	rwbase_write_downgrade(&sem->rwbase);
1514 }
1515 
1516 /* Debug stubs for the common API */
1517 #define DEBUG_RWSEMS_WARN_ON(c, sem)
1518 
1519 static inline void __rwsem_set_reader_owned(struct rw_semaphore *sem,
1520 					    struct task_struct *owner)
1521 {
1522 }
1523 
1524 static inline bool is_rwsem_reader_owned(struct rw_semaphore *sem)
1525 {
1526 	int count = atomic_read(&sem->rwbase.readers);
1527 
1528 	return count < 0 && count != READER_BIAS;
1529 }
1530 
1531 #endif /* CONFIG_PREEMPT_RT */
1532 
1533 /*
1534  * lock for reading
1535  */
1536 void __sched down_read(struct rw_semaphore *sem)
1537 {
1538 	might_sleep();
1539 	rwsem_acquire_read(&sem->dep_map, 0, 0, _RET_IP_);
1540 
1541 	LOCK_CONTENDED(sem, __down_read_trylock, __down_read);
1542 }
1543 EXPORT_SYMBOL(down_read);
1544 
1545 int __sched down_read_interruptible(struct rw_semaphore *sem)
1546 {
1547 	might_sleep();
1548 	rwsem_acquire_read(&sem->dep_map, 0, 0, _RET_IP_);
1549 
1550 	if (LOCK_CONTENDED_RETURN(sem, __down_read_trylock, __down_read_interruptible)) {
1551 		rwsem_release(&sem->dep_map, _RET_IP_);
1552 		return -EINTR;
1553 	}
1554 
1555 	return 0;
1556 }
1557 EXPORT_SYMBOL(down_read_interruptible);
1558 
1559 int __sched down_read_killable(struct rw_semaphore *sem)
1560 {
1561 	might_sleep();
1562 	rwsem_acquire_read(&sem->dep_map, 0, 0, _RET_IP_);
1563 
1564 	if (LOCK_CONTENDED_RETURN(sem, __down_read_trylock, __down_read_killable)) {
1565 		rwsem_release(&sem->dep_map, _RET_IP_);
1566 		return -EINTR;
1567 	}
1568 
1569 	return 0;
1570 }
1571 EXPORT_SYMBOL(down_read_killable);
1572 
1573 /*
1574  * trylock for reading -- returns 1 if successful, 0 if contention
1575  */
1576 int down_read_trylock(struct rw_semaphore *sem)
1577 {
1578 	int ret = __down_read_trylock(sem);
1579 
1580 	if (ret == 1)
1581 		rwsem_acquire_read(&sem->dep_map, 0, 1, _RET_IP_);
1582 	return ret;
1583 }
1584 EXPORT_SYMBOL(down_read_trylock);
1585 
1586 /*
1587  * lock for writing
1588  */
1589 void __sched down_write(struct rw_semaphore *sem)
1590 {
1591 	might_sleep();
1592 	rwsem_acquire(&sem->dep_map, 0, 0, _RET_IP_);
1593 	LOCK_CONTENDED(sem, __down_write_trylock, __down_write);
1594 }
1595 EXPORT_SYMBOL(down_write);
1596 
1597 /*
1598  * lock for writing
1599  */
1600 int __sched down_write_killable(struct rw_semaphore *sem)
1601 {
1602 	might_sleep();
1603 	rwsem_acquire(&sem->dep_map, 0, 0, _RET_IP_);
1604 
1605 	if (LOCK_CONTENDED_RETURN(sem, __down_write_trylock,
1606 				  __down_write_killable)) {
1607 		rwsem_release(&sem->dep_map, _RET_IP_);
1608 		return -EINTR;
1609 	}
1610 
1611 	return 0;
1612 }
1613 EXPORT_SYMBOL(down_write_killable);
1614 
1615 /*
1616  * trylock for writing -- returns 1 if successful, 0 if contention
1617  */
1618 int down_write_trylock(struct rw_semaphore *sem)
1619 {
1620 	int ret = __down_write_trylock(sem);
1621 
1622 	if (ret == 1)
1623 		rwsem_acquire(&sem->dep_map, 0, 1, _RET_IP_);
1624 
1625 	return ret;
1626 }
1627 EXPORT_SYMBOL(down_write_trylock);
1628 
1629 /*
1630  * release a read lock
1631  */
1632 void up_read(struct rw_semaphore *sem)
1633 {
1634 	rwsem_release(&sem->dep_map, _RET_IP_);
1635 	__up_read(sem);
1636 }
1637 EXPORT_SYMBOL(up_read);
1638 
1639 /*
1640  * release a write lock
1641  */
1642 void up_write(struct rw_semaphore *sem)
1643 {
1644 	rwsem_release(&sem->dep_map, _RET_IP_);
1645 	__up_write(sem);
1646 }
1647 EXPORT_SYMBOL(up_write);
1648 
1649 /*
1650  * downgrade write lock to read lock
1651  */
1652 void downgrade_write(struct rw_semaphore *sem)
1653 {
1654 	lock_downgrade(&sem->dep_map, _RET_IP_);
1655 	__downgrade_write(sem);
1656 }
1657 EXPORT_SYMBOL(downgrade_write);
1658 
1659 #ifdef CONFIG_DEBUG_LOCK_ALLOC
1660 
1661 void down_read_nested(struct rw_semaphore *sem, int subclass)
1662 {
1663 	might_sleep();
1664 	rwsem_acquire_read(&sem->dep_map, subclass, 0, _RET_IP_);
1665 	LOCK_CONTENDED(sem, __down_read_trylock, __down_read);
1666 }
1667 EXPORT_SYMBOL(down_read_nested);
1668 
1669 int down_read_killable_nested(struct rw_semaphore *sem, int subclass)
1670 {
1671 	might_sleep();
1672 	rwsem_acquire_read(&sem->dep_map, subclass, 0, _RET_IP_);
1673 
1674 	if (LOCK_CONTENDED_RETURN(sem, __down_read_trylock, __down_read_killable)) {
1675 		rwsem_release(&sem->dep_map, _RET_IP_);
1676 		return -EINTR;
1677 	}
1678 
1679 	return 0;
1680 }
1681 EXPORT_SYMBOL(down_read_killable_nested);
1682 
1683 void _down_write_nest_lock(struct rw_semaphore *sem, struct lockdep_map *nest)
1684 {
1685 	might_sleep();
1686 	rwsem_acquire_nest(&sem->dep_map, 0, 0, nest, _RET_IP_);
1687 	LOCK_CONTENDED(sem, __down_write_trylock, __down_write);
1688 }
1689 EXPORT_SYMBOL(_down_write_nest_lock);
1690 
1691 void down_read_non_owner(struct rw_semaphore *sem)
1692 {
1693 	might_sleep();
1694 	__down_read(sem);
1695 	/*
1696 	 * The owner value for a reader-owned lock is mostly for debugging
1697 	 * purpose only and is not critical to the correct functioning of
1698 	 * rwsem. So it is perfectly fine to set it in a preempt-enabled
1699 	 * context here.
1700 	 */
1701 	__rwsem_set_reader_owned(sem, NULL);
1702 }
1703 EXPORT_SYMBOL(down_read_non_owner);
1704 
1705 void down_write_nested(struct rw_semaphore *sem, int subclass)
1706 {
1707 	might_sleep();
1708 	rwsem_acquire(&sem->dep_map, subclass, 0, _RET_IP_);
1709 	LOCK_CONTENDED(sem, __down_write_trylock, __down_write);
1710 }
1711 EXPORT_SYMBOL(down_write_nested);
1712 
1713 int __sched down_write_killable_nested(struct rw_semaphore *sem, int subclass)
1714 {
1715 	might_sleep();
1716 	rwsem_acquire(&sem->dep_map, subclass, 0, _RET_IP_);
1717 
1718 	if (LOCK_CONTENDED_RETURN(sem, __down_write_trylock,
1719 				  __down_write_killable)) {
1720 		rwsem_release(&sem->dep_map, _RET_IP_);
1721 		return -EINTR;
1722 	}
1723 
1724 	return 0;
1725 }
1726 EXPORT_SYMBOL(down_write_killable_nested);
1727 
1728 void up_read_non_owner(struct rw_semaphore *sem)
1729 {
1730 	DEBUG_RWSEMS_WARN_ON(!is_rwsem_reader_owned(sem), sem);
1731 	__up_read(sem);
1732 }
1733 EXPORT_SYMBOL(up_read_non_owner);
1734 
1735 #endif
1736