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