History

futex: Split out PI futex

Move the PI futex implementation into it's own file.

Peter Zijlstra committed 5 years ago

Commit 85dc28f1 parent 966cb754 files · +1452 −1408Browse files

Showing the changes to kernel (4 of 4 files). Show all

Unified · Split

4 files
  1. kernel/futex/Makefile +1 −1
  2. kernel/futex/core.c +101 −1407
  3. kernel/futex/futex.h +117 −0
  4. kernel/futex/pi.c +1233 −0
kernel/futex/Makefile+1−1
@@ -1,3 +1,3 @@
1# SPDX-License-Identifier: GPL-2.01# SPDX-License-Identifier: GPL-2.0
2 2
3obj-y += core.o syscalls.o3obj-y += core.o syscalls.o pi.o
kernel/futex/core.c+101−1407
@@ -147,67 +147,6 @@ int __read_mostly futex_cmpxchg_enabled; · 146 unmodified lines
147#endif147#endif
148 148
149 149
150/*
151 * Priority Inheritance state:
152 */
153struct futex_pi_state {
154 /*
155 * list of 'owned' pi_state instances - these have to be
156 * cleaned up in do_exit() if the task exits prematurely:
157 */
158 struct list_head list;
159
160 /*
161 * The PI object:
162 */
163 struct rt_mutex_base pi_mutex;
164
165 struct task_struct *owner;
166 refcount_t refcount;
167
168 union futex_key key;
169} __randomize_layout;
170
171/**
172 * struct futex_q - The hashed futex queue entry, one per waiting task
173 * @list: priority-sorted list of tasks waiting on this futex
174 * @task: the task waiting on the futex
175 * @lock_ptr: the hash bucket lock
176 * @key: the key the futex is hashed on
177 * @pi_state: optional priority inheritance state
178 * @rt_waiter: rt_waiter storage for use with requeue_pi
179 * @requeue_pi_key: the requeue_pi target futex key
180 * @bitset: bitset for the optional bitmasked wakeup
181 * @requeue_state: State field for futex_requeue_pi()
182 * @requeue_wait: RCU wait for futex_requeue_pi() (RT only)
183 *
184 * We use this hashed waitqueue, instead of a normal wait_queue_entry_t, so
185 * we can wake only the relevant ones (hashed queues may be shared).
186 *
187 * A futex_q has a woken state, just like tasks have TASK_RUNNING.
188 * It is considered woken when plist_node_empty(&q->list) || q->lock_ptr == 0.
189 * The order of wakeup is always to make the first condition true, then
190 * the second.
191 *
192 * PI futexes are typically woken before they are removed from the hash list via
193 * the rt_mutex code. See futex_unqueue_pi().
194 */
195struct futex_q {
196 struct plist_node list;
197
198 struct task_struct *task;
199 spinlock_t *lock_ptr;
200 union futex_key key;
201 struct futex_pi_state *pi_state;
202 struct rt_mutex_waiter *rt_waiter;
203 union futex_key *requeue_pi_key;
204 u32 bitset;
205 atomic_t requeue_state;
206#ifdef CONFIG_PREEMPT_RT
207 struct rcuwait requeue_wait;
208#endif
209} __randomize_layout;
210
211/*150/*
212 * On PREEMPT_RT, the hash bucket lock is a 'sleeping' spinlock with an151 * On PREEMPT_RT, the hash bucket lock is a 'sleeping' spinlock with an
213 * underlying rtmutex. The task which is about to be requeued could have152 * underlying rtmutex. The task which is about to be requeued could have
@@ -259,24 +198,13 @@ enum { · 45 unmodified lines
259 Q_REQUEUE_PI_LOCKED,198 Q_REQUEUE_PI_LOCKED,
260};199};
261 200
262static const struct futex_q futex_q_init = {201const struct futex_q futex_q_init = {
263 /* list gets initialized in futex_queue()*/202 /* list gets initialized in futex_queue()*/
264 .key = FUTEX_KEY_INIT,203 .key = FUTEX_KEY_INIT,
265 .bitset = FUTEX_BITSET_MATCH_ANY,204 .bitset = FUTEX_BITSET_MATCH_ANY,
266 .requeue_state = ATOMIC_INIT(Q_REQUEUE_PI_NONE),205 .requeue_state = ATOMIC_INIT(Q_REQUEUE_PI_NONE),
267};206};
268 207
269/*
270 * Hash buckets are shared by all the futex_keys that hash to the same
271 * location. Each key may have multiple futex_q structures, one for each task
272 * waiting on a futex.
273 */
274struct futex_hash_bucket {
275 atomic_t waiters;
276 spinlock_t lock;
277 struct plist_head chain;
278} ____cacheline_aligned_in_smp;
279
280/*208/*
281 * The base of the bucket array and its size are always used together209 * The base of the bucket array and its size are always used together
282 * (after initialization only in futex_hash()), so ensure that they210 * (after initialization only in futex_hash()), so ensure that they
@@ -386,7 +314,7 @@ static inline int hb_waiters_pending(struct futex_hash_bucket *hb) · 103 unmodified lines
386 * We hash on the keys returned from get_futex_key (see below) and return the314 * We hash on the keys returned from get_futex_key (see below) and return the
387 * corresponding hash bucket in the global hash.315 * corresponding hash bucket in the global hash.
388 */316 */
389static struct futex_hash_bucket *futex_hash(union futex_key *key)317struct futex_hash_bucket *futex_hash(union futex_key *key)
390{318{
391 u32 hash = jhash2((u32 *)key, offsetof(typeof(*key), both.offset) / 4,319 u32 hash = jhash2((u32 *)key, offsetof(typeof(*key), both.offset) / 4,
392 key->both.offset);320 key->both.offset);
@@ -410,11 +338,6 @@ static inline int match_futex(union futex_key *key1, union futex_key *key2) · 17 unmodified lines
410 && key1->both.offset == key2->both.offset);338 && key1->both.offset == key2->both.offset);
411}339}
412 340
413enum futex_access {
414 FUTEX_READ,
415 FUTEX_WRITE
416};
417
418/**341/**
419 * futex_setup_timer - set up the sleeping hrtimer.342 * futex_setup_timer - set up the sleeping hrtimer.
420 * @time: ptr to the given timeout value343 * @time: ptr to the given timeout value
@@ -425,7 +348,7 @@ enum futex_access { · 4 unmodified lines
425 * Return: Initialized hrtimer_sleeper structure or NULL if no timeout348 * Return: Initialized hrtimer_sleeper structure or NULL if no timeout
426 * value given349 * value given
427 */350 */
428static inline struct hrtimer_sleeper *351struct hrtimer_sleeper *
429futex_setup_timer(ktime_t *time, struct hrtimer_sleeper *timeout,352futex_setup_timer(ktime_t *time, struct hrtimer_sleeper *timeout,
430 int flags, u64 range_ns)353 int flags, u64 range_ns)
431{354{
@@ -511,8 +434,8 @@ static u64 get_inode_sequence_number(struct inode *inode) · 79 unmodified lines
511 *434 *
512 * lock_page() might sleep, the caller should not hold a spinlock.435 * lock_page() might sleep, the caller should not hold a spinlock.
513 */436 */
514static int get_futex_key(u32 __user *uaddr, bool fshared, union futex_key *key,437int get_futex_key(u32 __user *uaddr, bool fshared, union futex_key *key,
515 enum futex_access rw)438 enum futex_access rw)
516{439{
517 unsigned long address = (unsigned long)uaddr;440 unsigned long address = (unsigned long)uaddr;
518 struct mm_struct *mm = current->mm;441 struct mm_struct *mm = current->mm;
@@ -700,7 +623,7 @@ out: · 181 unmodified lines
700 * disabled section so we can as well avoid the #PF overhead by623 * disabled section so we can as well avoid the #PF overhead by
701 * calling get_user_pages() right away.624 * calling get_user_pages() right away.
702 */625 */
703static int fault_in_user_writeable(u32 __user *uaddr)626int fault_in_user_writeable(u32 __user *uaddr)
704{627{
705 struct mm_struct *mm = current->mm;628 struct mm_struct *mm = current->mm;
706 int ret;629 int ret;
@@ -720,8 +643,7 @@ static int fault_in_user_writeable(u32 __user *uaddr) · 13 unmodified lines
720 *643 *
721 * Must be called with the hb lock held.644 * Must be called with the hb lock held.
722 */645 */
723static struct futex_q *futex_top_waiter(struct futex_hash_bucket *hb,646struct futex_q *futex_top_waiter(struct futex_hash_bucket *hb, union futex_key *key)
724 union futex_key *key)
725{647{
726 struct futex_q *this;648 struct futex_q *this;
727 649
@@ -732,8 +654,7 @@ static struct futex_q *futex_top_waiter(struct futex_hash_bucket *hb, · 4 unmodified lines
732 return NULL;654 return NULL;
733}655}
734 656
735static int futex_cmpxchg_value_locked(u32 *curval, u32 __user *uaddr,657int futex_cmpxchg_value_locked(u32 *curval, u32 __user *uaddr, u32 uval, u32 newval)
736 u32 uval, u32 newval)
737{658{
738 int ret;659 int ret;
739 660
@@ -744,7 +665,7 @@ static int futex_cmpxchg_value_locked(u32 *curval, u32 __user *uaddr, · 4 unmodified lines
744 return ret;665 return ret;
745}666}
746 667
747static int futex_get_value_locked(u32 *dest, u32 __user *from)668int futex_get_value_locked(u32 *dest, u32 __user *from)
748{669{
749 int ret;670 int ret;
750 671
@@ -755,399 +676,6 @@ static int futex_get_value_locked(u32 *dest, u32 __user *from) · 4 unmodified lines
755 return ret ? -EFAULT : 0;676 return ret ? -EFAULT : 0;
756}677}
757 678
758
759/*
760 * PI code:
761 */
762static int refill_pi_state_cache(void)
763{
764 struct futex_pi_state *pi_state;
765
766 if (likely(current->pi_state_cache))
767 return 0;
768
769 pi_state = kzalloc(sizeof(*pi_state), GFP_KERNEL);
770
771 if (!pi_state)
772 return -ENOMEM;
773
774 INIT_LIST_HEAD(&pi_state->list);
775 /* pi_mutex gets initialized later */
776 pi_state->owner = NULL;
777 refcount_set(&pi_state->refcount, 1);
778 pi_state->key = FUTEX_KEY_INIT;
779
780 current->pi_state_cache = pi_state;
781
782 return 0;
783}
784
785static struct futex_pi_state *alloc_pi_state(void)
786{
787 struct futex_pi_state *pi_state = current->pi_state_cache;
788
789 WARN_ON(!pi_state);
790 current->pi_state_cache = NULL;
791
792 return pi_state;
793}
794
795static void pi_state_update_owner(struct futex_pi_state *pi_state,
796 struct task_struct *new_owner)
797{
798 struct task_struct *old_owner = pi_state->owner;
799
800 lockdep_assert_held(&pi_state->pi_mutex.wait_lock);
801
802 if (old_owner) {
803 raw_spin_lock(&old_owner->pi_lock);
804 WARN_ON(list_empty(&pi_state->list));
805 list_del_init(&pi_state->list);
806 raw_spin_unlock(&old_owner->pi_lock);
807 }
808
809 if (new_owner) {
810 raw_spin_lock(&new_owner->pi_lock);
811 WARN_ON(!list_empty(&pi_state->list));
812 list_add(&pi_state->list, &new_owner->pi_state_list);
813 pi_state->owner = new_owner;
814 raw_spin_unlock(&new_owner->pi_lock);
815 }
816}
817
818static void get_pi_state(struct futex_pi_state *pi_state)
819{
820 WARN_ON_ONCE(!refcount_inc_not_zero(&pi_state->refcount));
821}
822
823/*
824 * Drops a reference to the pi_state object and frees or caches it
825 * when the last reference is gone.
826 */
827static void put_pi_state(struct futex_pi_state *pi_state)
828{
829 if (!pi_state)
830 return;
831
832 if (!refcount_dec_and_test(&pi_state->refcount))
833 return;
834
835 /*
836 * If pi_state->owner is NULL, the owner is most probably dying
837 * and has cleaned up the pi_state already
838 */
839 if (pi_state->owner) {
840 unsigned long flags;
841
842 raw_spin_lock_irqsave(&pi_state->pi_mutex.wait_lock, flags);
843 pi_state_update_owner(pi_state, NULL);
844 rt_mutex_proxy_unlock(&pi_state->pi_mutex);
845 raw_spin_unlock_irqrestore(&pi_state->pi_mutex.wait_lock, flags);
846 }
847
848 if (current->pi_state_cache) {
849 kfree(pi_state);
850 } else {
851 /*
852 * pi_state->list is already empty.
853 * clear pi_state->owner.
854 * refcount is at 0 - put it back to 1.
855 */
856 pi_state->owner = NULL;
857 refcount_set(&pi_state->refcount, 1);
858 current->pi_state_cache = pi_state;
859 }
860}
861
862#ifdef CONFIG_FUTEX_PI
863
864/*
865 * This task is holding PI mutexes at exit time => bad.
866 * Kernel cleans up PI-state, but userspace is likely hosed.
867 * (Robust-futex cleanup is separate and might save the day for userspace.)
868 */
869static void exit_pi_state_list(struct task_struct *curr)
870{
871 struct list_head *next, *head = &curr->pi_state_list;
872 struct futex_pi_state *pi_state;
873 struct futex_hash_bucket *hb;
874 union futex_key key = FUTEX_KEY_INIT;
875
876 if (!futex_cmpxchg_enabled)
877 return;
878 /*
879 * We are a ZOMBIE and nobody can enqueue itself on
880 * pi_state_list anymore, but we have to be careful
881 * versus waiters unqueueing themselves:
882 */
883 raw_spin_lock_irq(&curr->pi_lock);
884 while (!list_empty(head)) {
885 next = head->next;
886 pi_state = list_entry(next, struct futex_pi_state, list);
887 key = pi_state->key;
888 hb = futex_hash(&key);
889
890 /*
891 * We can race against put_pi_state() removing itself from the
892 * list (a waiter going away). put_pi_state() will first
893 * decrement the reference count and then modify the list, so
894 * its possible to see the list entry but fail this reference
895 * acquire.
896 *
897 * In that case; drop the locks to let put_pi_state() make
898 * progress and retry the loop.
899 */
900 if (!refcount_inc_not_zero(&pi_state->refcount)) {
901 raw_spin_unlock_irq(&curr->pi_lock);
902 cpu_relax();
903 raw_spin_lock_irq(&curr->pi_lock);
904 continue;
905 }
906 raw_spin_unlock_irq(&curr->pi_lock);
907
908 spin_lock(&hb->lock);
909 raw_spin_lock_irq(&pi_state->pi_mutex.wait_lock);
910 raw_spin_lock(&curr->pi_lock);
911 /*
912 * We dropped the pi-lock, so re-check whether this
913 * task still owns the PI-state:
914 */
915 if (head->next != next) {
916 /* retain curr->pi_lock for the loop invariant */
917 raw_spin_unlock(&pi_state->pi_mutex.wait_lock);
918 spin_unlock(&hb->lock);
919 put_pi_state(pi_state);
920 continue;
921 }
922
923 WARN_ON(pi_state->owner != curr);
924 WARN_ON(list_empty(&pi_state->list));
925 list_del_init(&pi_state->list);
926 pi_state->owner = NULL;
927
928 raw_spin_unlock(&curr->pi_lock);
929 raw_spin_unlock_irq(&pi_state->pi_mutex.wait_lock);
930 spin_unlock(&hb->lock);
931
932 rt_mutex_futex_unlock(&pi_state->pi_mutex);
933 put_pi_state(pi_state);
934
935 raw_spin_lock_irq(&curr->pi_lock);
936 }
937 raw_spin_unlock_irq(&curr->pi_lock);
938}
939#else
940static inline void exit_pi_state_list(struct task_struct *curr) { }
941#endif
942
943/*
944 * We need to check the following states:
945 *
946 * Waiter | pi_state | pi->owner | uTID | uODIED | ?
947 *
948 * [1] NULL | --- | --- | 0 | 0/1 | Valid
949 * [2] NULL | --- | --- | >0 | 0/1 | Valid
950 *
951 * [3] Found | NULL | -- | Any | 0/1 | Invalid
952 *
953 * [4] Found | Found | NULL | 0 | 1 | Valid
954 * [5] Found | Found | NULL | >0 | 1 | Invalid
955 *
956 * [6] Found | Found | task | 0 | 1 | Valid
957 *
958 * [7] Found | Found | NULL | Any | 0 | Invalid
959 *
960 * [8] Found | Found | task | ==taskTID | 0/1 | Valid
961 * [9] Found | Found | task | 0 | 0 | Invalid
962 * [10] Found | Found | task | !=taskTID | 0/1 | Invalid
963 *
964 * [1] Indicates that the kernel can acquire the futex atomically. We
965 * came here due to a stale FUTEX_WAITERS/FUTEX_OWNER_DIED bit.
966 *
967 * [2] Valid, if TID does not belong to a kernel thread. If no matching
968 * thread is found then it indicates that the owner TID has died.
969 *
970 * [3] Invalid. The waiter is queued on a non PI futex
971 *
972 * [4] Valid state after exit_robust_list(), which sets the user space
973 * value to FUTEX_WAITERS | FUTEX_OWNER_DIED.
974 *
975 * [5] The user space value got manipulated between exit_robust_list()
976 * and exit_pi_state_list()
977 *
978 * [6] Valid state after exit_pi_state_list() which sets the new owner in
979 * the pi_state but cannot access the user space value.
980 *
981 * [7] pi_state->owner can only be NULL when the OWNER_DIED bit is set.
982 *
983 * [8] Owner and user space value match
984 *
985 * [9] There is no transient state which sets the user space TID to 0
986 * except exit_robust_list(), but this is indicated by the
987 * FUTEX_OWNER_DIED bit. See [4]
988 *
989 * [10] There is no transient state which leaves owner and user space
990 * TID out of sync. Except one error case where the kernel is denied
991 * write access to the user address, see fixup_pi_state_owner().
992 *
993 *
994 * Serialization and lifetime rules:
995 *
996 * hb->lock:
997 *
998 * hb -> futex_q, relation
999 * futex_q -> pi_state, relation
1000 *
1001 * (cannot be raw because hb can contain arbitrary amount
1002 * of futex_q's)
1003 *
1004 * pi_mutex->wait_lock:
1005 *
1006 * {uval, pi_state}
1007 *
1008 * (and pi_mutex 'obviously')
1009 *
1010 * p->pi_lock:
1011 *
1012 * p->pi_state_list -> pi_state->list, relation
1013 * pi_mutex->owner -> pi_state->owner, relation
1014 *
1015 * pi_state->refcount:
1016 *
1017 * pi_state lifetime
1018 *
1019 *
1020 * Lock order:
1021 *
1022 * hb->lock
1023 * pi_mutex->wait_lock
1024 * p->pi_lock
1025 *
1026 */
1027
1028/*
1029 * Validate that the existing waiter has a pi_state and sanity check
1030 * the pi_state against the user space value. If correct, attach to
1031 * it.
1032 */
1033static int attach_to_pi_state(u32 __user *uaddr, u32 uval,
1034 struct futex_pi_state *pi_state,
1035 struct futex_pi_state **ps)
1036{
1037 pid_t pid = uval & FUTEX_TID_MASK;
1038 u32 uval2;
1039 int ret;
1040
1041 /*
1042 * Userspace might have messed up non-PI and PI futexes [3]
1043 */
1044 if (unlikely(!pi_state))
1045 return -EINVAL;
1046
1047 /*
1048 * We get here with hb->lock held, and having found a
1049 * futex_top_waiter(). This means that futex_lock_pi() of said futex_q
1050 * has dropped the hb->lock in between futex_queue() and futex_unqueue_pi(),
1051 * which in turn means that futex_lock_pi() still has a reference on
1052 * our pi_state.
1053 *
1054 * The waiter holding a reference on @pi_state also protects against
1055 * the unlocked put_pi_state() in futex_unlock_pi(), futex_lock_pi()
1056 * and futex_wait_requeue_pi() as it cannot go to 0 and consequently
1057 * free pi_state before we can take a reference ourselves.
1058 */
1059 WARN_ON(!refcount_read(&pi_state->refcount));
1060
1061 /*
1062 * Now that we have a pi_state, we can acquire wait_lock
1063 * and do the state validation.
1064 */
1065 raw_spin_lock_irq(&pi_state->pi_mutex.wait_lock);
1066
1067 /*
1068 * Since {uval, pi_state} is serialized by wait_lock, and our current
1069 * uval was read without holding it, it can have changed. Verify it
1070 * still is what we expect it to be, otherwise retry the entire
1071 * operation.
1072 */
1073 if (futex_get_value_locked(&uval2, uaddr))
1074 goto out_efault;
1075
1076 if (uval != uval2)
1077 goto out_eagain;
1078
1079 /*
1080 * Handle the owner died case:
1081 */
1082 if (uval & FUTEX_OWNER_DIED) {
1083 /*
1084 * exit_pi_state_list sets owner to NULL and wakes the
1085 * topmost waiter. The task which acquires the
1086 * pi_state->rt_mutex will fixup owner.
1087 */
1088 if (!pi_state->owner) {
1089 /*
1090 * No pi state owner, but the user space TID
1091 * is not 0. Inconsistent state. [5]
1092 */
1093 if (pid)
1094 goto out_einval;
1095 /*
1096 * Take a ref on the state and return success. [4]
1097 */
1098 goto out_attach;
1099 }
1100
1101 /*
1102 * If TID is 0, then either the dying owner has not
1103 * yet executed exit_pi_state_list() or some waiter
1104 * acquired the rtmutex in the pi state, but did not
1105 * yet fixup the TID in user space.
1106 *
1107 * Take a ref on the state and return success. [6]
1108 */
1109 if (!pid)
1110 goto out_attach;
1111 } else {
1112 /*
1113 * If the owner died bit is not set, then the pi_state
1114 * must have an owner. [7]
1115 */
1116 if (!pi_state->owner)
1117 goto out_einval;
1118 }
1119
1120 /*
1121 * Bail out if user space manipulated the futex value. If pi
1122 * state exists then the owner TID must be the same as the
1123 * user space TID. [9/10]
1124 */
1125 if (pid != task_pid_vnr(pi_state->owner))
1126 goto out_einval;
1127
1128out_attach:
1129 get_pi_state(pi_state);
1130 raw_spin_unlock_irq(&pi_state->pi_mutex.wait_lock);
1131 *ps = pi_state;
1132 return 0;
1133
1134out_einval:
1135 ret = -EINVAL;
1136 goto out_error;
1137
1138out_eagain:
1139 ret = -EAGAIN;
1140 goto out_error;
1141
1142out_efault:
1143 ret = -EFAULT;
1144 goto out_error;
1145
1146out_error:
1147 raw_spin_unlock_irq(&pi_state->pi_mutex.wait_lock);
1148 return ret;
1149}
1150
1151/**679/**
1152 * wait_for_owner_exiting - Block until the owner has exited680 * wait_for_owner_exiting - Block until the owner has exited
1153 * @ret: owner's current futex lock status681 * @ret: owner's current futex lock status
@@ -1155,7 +683,7 @@ out_error: · 1 unmodified line
1155 *683 *
1156 * Caller must hold a refcount on @exiting.684 * Caller must hold a refcount on @exiting.
1157 */685 */
1158static void wait_for_owner_exiting(int ret, struct task_struct *exiting)686void wait_for_owner_exiting(int ret, struct task_struct *exiting)
1159{687{
1160 if (ret != -EBUSY) {688 if (ret != -EBUSY) {
1161 WARN_ON_ONCE(exiting);689 WARN_ON_ONCE(exiting);
@@ -1179,296 +707,6 @@ static void wait_for_owner_exiting(int ret, struct task_struct *exiting) · 17 unmodified lines
1179 put_task_struct(exiting);707 put_task_struct(exiting);
1180}708}
1181 709
1182static int handle_exit_race(u32 __user *uaddr, u32 uval,
1183 struct task_struct *tsk)
1184{
1185 u32 uval2;
1186
1187 /*
1188 * If the futex exit state is not yet FUTEX_STATE_DEAD, tell the
1189 * caller that the alleged owner is busy.
1190 */
1191 if (tsk && tsk->futex_state != FUTEX_STATE_DEAD)
1192 return -EBUSY;
1193
1194 /*
1195 * Reread the user space value to handle the following situation:
1196 *
1197 * CPU0 CPU1
1198 *
1199 * sys_exit() sys_futex()
1200 * do_exit() futex_lock_pi()
1201 * futex_lock_pi_atomic()
1202 * exit_signals(tsk) No waiters:
1203 * tsk->flags |= PF_EXITING; *uaddr == 0x00000PID
1204 * mm_release(tsk) Set waiter bit
1205 * exit_robust_list(tsk) { *uaddr = 0x80000PID;
1206 * Set owner died attach_to_pi_owner() {
1207 * *uaddr = 0xC0000000; tsk = get_task(PID);
1208 * } if (!tsk->flags & PF_EXITING) {
1209 * ... attach();
1210 * tsk->futex_state = } else {
1211 * FUTEX_STATE_DEAD; if (tsk->futex_state !=
1212 * FUTEX_STATE_DEAD)
1213 * return -EAGAIN;
1214 * return -ESRCH; <--- FAIL
1215 * }
1216 *
1217 * Returning ESRCH unconditionally is wrong here because the
1218 * user space value has been changed by the exiting task.
1219 *
1220 * The same logic applies to the case where the exiting task is
1221 * already gone.
1222 */
1223 if (futex_get_value_locked(&uval2, uaddr))
1224 return -EFAULT;
1225
1226 /* If the user space value has changed, try again. */
1227 if (uval2 != uval)
1228 return -EAGAIN;
1229
1230 /*
1231 * The exiting task did not have a robust list, the robust list was
1232 * corrupted or the user space value in *uaddr is simply bogus.
1233 * Give up and tell user space.
1234 */
1235 return -ESRCH;
1236}
1237
1238static void __attach_to_pi_owner(struct task_struct *p, union futex_key *key,
1239 struct futex_pi_state **ps)
1240{
1241 /*
1242 * No existing pi state. First waiter. [2]
1243 *
1244 * This creates pi_state, we have hb->lock held, this means nothing can
1245 * observe this state, wait_lock is irrelevant.
1246 */
1247 struct futex_pi_state *pi_state = alloc_pi_state();
1248
1249 /*
1250 * Initialize the pi_mutex in locked state and make @p
1251 * the owner of it:
1252 */
1253 rt_mutex_init_proxy_locked(&pi_state->pi_mutex, p);
1254
1255 /* Store the key for possible exit cleanups: */
1256 pi_state->key = *key;
1257
1258 WARN_ON(!list_empty(&pi_state->list));
1259 list_add(&pi_state->list, &p->pi_state_list);
1260 /*
1261 * Assignment without holding pi_state->pi_mutex.wait_lock is safe
1262 * because there is no concurrency as the object is not published yet.
1263 */
1264 pi_state->owner = p;
1265
1266 *ps = pi_state;
1267}
1268/*
1269 * Lookup the task for the TID provided from user space and attach to
1270 * it after doing proper sanity checks.
1271 */
1272static int attach_to_pi_owner(u32 __user *uaddr, u32 uval, union futex_key *key,
1273 struct futex_pi_state **ps,
1274 struct task_struct **exiting)
1275{
1276 pid_t pid = uval & FUTEX_TID_MASK;
1277 struct task_struct *p;
1278
1279 /*
1280 * We are the first waiter - try to look up the real owner and attach
1281 * the new pi_state to it, but bail out when TID = 0 [1]
1282 *
1283 * The !pid check is paranoid. None of the call sites should end up
1284 * with pid == 0, but better safe than sorry. Let the caller retry
1285 */
1286 if (!pid)
1287 return -EAGAIN;
1288 p = find_get_task_by_vpid(pid);
1289 if (!p)
1290 return handle_exit_race(uaddr, uval, NULL);
1291
1292 if (unlikely(p->flags & PF_KTHREAD)) {
1293 put_task_struct(p);
1294 return -EPERM;
1295 }
1296
1297 /*
1298 * We need to look at the task state to figure out, whether the
1299 * task is exiting. To protect against the change of the task state
1300 * in futex_exit_release(), we do this protected by p->pi_lock:
1301 */
1302 raw_spin_lock_irq(&p->pi_lock);
1303 if (unlikely(p->futex_state != FUTEX_STATE_OK)) {
1304 /*
1305 * The task is on the way out. When the futex state is
1306 * FUTEX_STATE_DEAD, we know that the task has finished
1307 * the cleanup:
1308 */
1309 int ret = handle_exit_race(uaddr, uval, p);
1310
1311 raw_spin_unlock_irq(&p->pi_lock);
1312 /*
1313 * If the owner task is between FUTEX_STATE_EXITING and
1314 * FUTEX_STATE_DEAD then store the task pointer and keep
1315 * the reference on the task struct. The calling code will
1316 * drop all locks, wait for the task to reach
1317 * FUTEX_STATE_DEAD and then drop the refcount. This is
1318 * required to prevent a live lock when the current task
1319 * preempted the exiting task between the two states.
1320 */
1321 if (ret == -EBUSY)
1322 *exiting = p;
1323 else
1324 put_task_struct(p);
1325 return ret;
1326 }
1327
1328 __attach_to_pi_owner(p, key, ps);
1329 raw_spin_unlock_irq(&p->pi_lock);
1330
1331 put_task_struct(p);
1332
1333 return 0;
1334}
1335
1336static int lock_pi_update_atomic(u32 __user *uaddr, u32 uval, u32 newval)
1337{
1338 int err;
1339 u32 curval;
1340
1341 if (unlikely(should_fail_futex(true)))
1342 return -EFAULT;
1343
1344 err = futex_cmpxchg_value_locked(&curval, uaddr, uval, newval);
1345 if (unlikely(err))
1346 return err;
1347
1348 /* If user space value changed, let the caller retry */
1349 return curval != uval ? -EAGAIN : 0;
1350}
1351
1352/**
1353 * futex_lock_pi_atomic() - Atomic work required to acquire a pi aware futex
1354 * @uaddr: the pi futex user address
1355 * @hb: the pi futex hash bucket
1356 * @key: the futex key associated with uaddr and hb
1357 * @ps: the pi_state pointer where we store the result of the
1358 * lookup
1359 * @task: the task to perform the atomic lock work for. This will
1360 * be "current" except in the case of requeue pi.
1361 * @exiting: Pointer to store the task pointer of the owner task
1362 * which is in the middle of exiting
1363 * @set_waiters: force setting the FUTEX_WAITERS bit (1) or not (0)
1364 *
1365 * Return:
1366 * - 0 - ready to wait;
1367 * - 1 - acquired the lock;
1368 * - <0 - error
1369 *
1370 * The hb->lock must be held by the caller.
1371 *
1372 * @exiting is only set when the return value is -EBUSY. If so, this holds
1373 * a refcount on the exiting task on return and the caller needs to drop it
1374 * after waiting for the exit to complete.
1375 */
1376static int futex_lock_pi_atomic(u32 __user *uaddr, struct futex_hash_bucket *hb,
1377 union futex_key *key,
1378 struct futex_pi_state **ps,
1379 struct task_struct *task,
1380 struct task_struct **exiting,
1381 int set_waiters)
1382{
1383 u32 uval, newval, vpid = task_pid_vnr(task);
1384 struct futex_q *top_waiter;
1385 int ret;
1386
1387 /*
1388 * Read the user space value first so we can validate a few
1389 * things before proceeding further.
1390 */
1391 if (futex_get_value_locked(&uval, uaddr))
1392 return -EFAULT;
1393
1394 if (unlikely(should_fail_futex(true)))
1395 return -EFAULT;
1396
1397 /*
1398 * Detect deadlocks.
1399 */
1400 if ((unlikely((uval & FUTEX_TID_MASK) == vpid)))
1401 return -EDEADLK;
1402
1403 if ((unlikely(should_fail_futex(true))))
1404 return -EDEADLK;
1405
1406 /*
1407 * Lookup existing state first. If it exists, try to attach to
1408 * its pi_state.
1409 */
1410 top_waiter = futex_top_waiter(hb, key);
1411 if (top_waiter)
1412 return attach_to_pi_state(uaddr, uval, top_waiter->pi_state, ps);
1413
1414 /*
1415 * No waiter and user TID is 0. We are here because the
1416 * waiters or the owner died bit is set or called from
1417 * requeue_cmp_pi or for whatever reason something took the
1418 * syscall.
1419 */
1420 if (!(uval & FUTEX_TID_MASK)) {
1421 /*
1422 * We take over the futex. No other waiters and the user space
1423 * TID is 0. We preserve the owner died bit.
1424 */
1425 newval = uval & FUTEX_OWNER_DIED;
1426 newval |= vpid;
1427
1428 /* The futex requeue_pi code can enforce the waiters bit */
1429 if (set_waiters)
1430 newval |= FUTEX_WAITERS;
1431
1432 ret = lock_pi_update_atomic(uaddr, uval, newval);
1433 if (ret)
1434 return ret;
1435
1436 /*
1437 * If the waiter bit was requested the caller also needs PI
1438 * state attached to the new owner of the user space futex.
1439 *
1440 * @task is guaranteed to be alive and it cannot be exiting
1441 * because it is either sleeping or waiting in
1442 * futex_requeue_pi_wakeup_sync().
1443 *
1444 * No need to do the full attach_to_pi_owner() exercise
1445 * because @task is known and valid.
1446 */
1447 if (set_waiters) {
1448 raw_spin_lock_irq(&task->pi_lock);
1449 __attach_to_pi_owner(task, key, ps);
1450 raw_spin_unlock_irq(&task->pi_lock);
1451 }
1452 return 1;
1453 }
1454
1455 /*
1456 * First waiter. Set the waiters bit before attaching ourself to
1457 * the owner. If owner tries to unlock, it will be forced into
1458 * the kernel and blocked on hb->lock.
1459 */
1460 newval = uval | FUTEX_WAITERS;
1461 ret = lock_pi_update_atomic(uaddr, uval, newval);
1462 if (ret)
1463 return ret;
1464 /*
1465 * If the update of the user space value succeeded, we try to
1466 * attach to the owner. If that fails, no harm done, we only
1467 * set the FUTEX_WAITERS bit in the user space variable.
1468 */
1469 return attach_to_pi_owner(uaddr, newval, key, ps, exiting);
1470}
1471
1472/**710/**
1473 * __futex_unqueue() - Remove the futex_q from its futex_hash_bucket711 * __futex_unqueue() - Remove the futex_q from its futex_hash_bucket
1474 * @q: The futex_q to unqueue712 * @q: The futex_q to unqueue
@@ -1519,79 +757,6 @@ static void mark_wake_futex(struct wake_q_head *wake_q, struct futex_q *q) · 44 unmodified lines
1519 wake_q_add_safe(wake_q, p);757 wake_q_add_safe(wake_q, p);
1520}758}
1521 759
1522/*
1523 * Caller must hold a reference on @pi_state.
1524 */
1525static int wake_futex_pi(u32 __user *uaddr, u32 uval, struct futex_pi_state *pi_state)
1526{
1527 struct rt_mutex_waiter *top_waiter;
1528 struct task_struct *new_owner;
1529 bool postunlock = false;
1530 DEFINE_RT_WAKE_Q(wqh);
1531 u32 curval, newval;
1532 int ret = 0;
1533
1534 top_waiter = rt_mutex_top_waiter(&pi_state->pi_mutex);
1535 if (WARN_ON_ONCE(!top_waiter)) {
1536 /*
1537 * As per the comment in futex_unlock_pi() this should not happen.
1538 *
1539 * When this happens, give up our locks and try again, giving
1540 * the futex_lock_pi() instance time to complete, either by
1541 * waiting on the rtmutex or removing itself from the futex
1542 * queue.
1543 */
1544 ret = -EAGAIN;
1545 goto out_unlock;
1546 }
1547
1548 new_owner = top_waiter->task;
1549
1550 /*
1551 * We pass it to the next owner. The WAITERS bit is always kept
1552 * enabled while there is PI state around. We cleanup the owner
1553 * died bit, because we are the owner.
1554 */
1555 newval = FUTEX_WAITERS | task_pid_vnr(new_owner);
1556
1557 if (unlikely(should_fail_futex(true))) {
1558 ret = -EFAULT;
1559 goto out_unlock;
1560 }
1561
1562 ret = futex_cmpxchg_value_locked(&curval, uaddr, uval, newval);
1563 if (!ret && (curval != uval)) {
1564 /*
1565 * If a unconditional UNLOCK_PI operation (user space did not
1566 * try the TID->0 transition) raced with a waiter setting the
1567 * FUTEX_WAITERS flag between get_user() and locking the hash
1568 * bucket lock, retry the operation.
1569 */
1570 if ((FUTEX_TID_MASK & curval) == uval)
1571 ret = -EAGAIN;
1572 else
1573 ret = -EINVAL;
1574 }
1575
1576 if (!ret) {
1577 /*
1578 * This is a point of no return; once we modified the uval
1579 * there is no going back and subsequent operations must
1580 * not fail.
1581 */
1582 pi_state_update_owner(pi_state, new_owner);
1583 postunlock = __rt_mutex_futex_unlock(&pi_state->pi_mutex, &wqh);
1584 }
1585
1586out_unlock:
1587 raw_spin_unlock_irq(&pi_state->pi_mutex.wait_lock);
1588
1589 if (postunlock)
1590 rt_mutex_postunlock(&wqh);
1591
1592 return ret;
1593}
1594
1595/*760/*
1596 * Express the locking dependencies for lockdep:761 * Express the locking dependencies for lockdep:
1597 */762 */
@@ -2410,7 +1575,7 @@ out_unlock: · 812 unmodified lines
2410}1575}
2411 1576
2412/* The key must be already stored in q->key. */1577/* The key must be already stored in q->key. */
2413static inline struct futex_hash_bucket *futex_q_lock(struct futex_q *q)1578struct futex_hash_bucket *futex_q_lock(struct futex_q *q)
2414 __acquires(&hb->lock)1579 __acquires(&hb->lock)
2415{1580{
2416 struct futex_hash_bucket *hb;1581 struct futex_hash_bucket *hb;
@@ -2433,15 +1598,14 @@ static inline struct futex_hash_bucket *futex_q_lock(struct futex_q *q) · 16 unmodified lines
2433 return hb;1598 return hb;
2434}1599}
2435 1600
2436static inline void1601void futex_q_unlock(struct futex_hash_bucket *hb)
2437futex_q_unlock(struct futex_hash_bucket *hb)
2438 __releases(&hb->lock)1602 __releases(&hb->lock)
2439{1603{
2440 spin_unlock(&hb->lock);1604 spin_unlock(&hb->lock);
2441 hb_waiters_dec(hb);1605 hb_waiters_dec(hb);
2442}1606}
2443 1607
2444static inline void __futex_queue(struct futex_q *q, struct futex_hash_bucket *hb)1608void __futex_queue(struct futex_q *q, struct futex_hash_bucket *hb)
2445{1609{
2446 int prio;1610 int prio;
2447 1611
@@ -2537,255 +1701,17 @@ retry: · 89 unmodified lines
2537 * PI futexes can not be requeued and must remove themselves from the1701 * PI futexes can not be requeued and must remove themselves from the
2538 * hash bucket. The hash bucket lock (i.e. lock_ptr) is held.1702 * hash bucket. The hash bucket lock (i.e. lock_ptr) is held.
2539 */1703 */
2540static void futex_unqueue_pi(struct futex_q *q)1704void futex_unqueue_pi(struct futex_q *q)
2541{1705{
2542 __futex_unqueue(q);1706 __futex_unqueue(q);
2543 1707
2544 BUG_ON(!q->pi_state);1708 BUG_ON(!q->pi_state);
2545 put_pi_state(q->pi_state);1709 put_pi_state(q->pi_state);
2546 q->pi_state = NULL;1710 q->pi_state = NULL;
2547}
2548
2549static int __fixup_pi_state_owner(u32 __user *uaddr, struct futex_q *q,
2550 struct task_struct *argowner)
2551{
2552 struct futex_pi_state *pi_state = q->pi_state;
2553 struct task_struct *oldowner, *newowner;
2554 u32 uval, curval, newval, newtid;
2555 int err = 0;
2556
2557 oldowner = pi_state->owner;
2558
2559 /*
2560 * We are here because either:
2561 *
2562 * - we stole the lock and pi_state->owner needs updating to reflect
2563 * that (@argowner == current),
2564 *
2565 * or:
2566 *
2567 * - someone stole our lock and we need to fix things to point to the
2568 * new owner (@argowner == NULL).
2569 *
2570 * Either way, we have to replace the TID in the user space variable.
2571 * This must be atomic as we have to preserve the owner died bit here.
2572 *
2573 * Note: We write the user space value _before_ changing the pi_state
2574 * because we can fault here. Imagine swapped out pages or a fork
2575 * that marked all the anonymous memory readonly for cow.
2576 *
2577 * Modifying pi_state _before_ the user space value would leave the
2578 * pi_state in an inconsistent state when we fault here, because we
2579 * need to drop the locks to handle the fault. This might be observed
2580 * in the PID checks when attaching to PI state .
2581 */
2582retry:
2583 if (!argowner) {
2584 if (oldowner != current) {
2585 /*
2586 * We raced against a concurrent self; things are
2587 * already fixed up. Nothing to do.
2588 */
2589 return 0;
2590 }
2591
2592 if (__rt_mutex_futex_trylock(&pi_state->pi_mutex)) {
2593 /* We got the lock. pi_state is correct. Tell caller. */
2594 return 1;
2595 }
2596
2597 /*
2598 * The trylock just failed, so either there is an owner or
2599 * there is a higher priority waiter than this one.
2600 */
2601 newowner = rt_mutex_owner(&pi_state->pi_mutex);
2602 /*
2603 * If the higher priority waiter has not yet taken over the
2604 * rtmutex then newowner is NULL. We can't return here with
2605 * that state because it's inconsistent vs. the user space
2606 * state. So drop the locks and try again. It's a valid
2607 * situation and not any different from the other retry
2608 * conditions.
2609 */
2610 if (unlikely(!newowner)) {
2611 err = -EAGAIN;
2612 goto handle_err;
2613 }
2614 } else {
2615 WARN_ON_ONCE(argowner != current);
2616 if (oldowner == current) {
2617 /*
2618 * We raced against a concurrent self; things are
2619 * already fixed up. Nothing to do.
2620 */
2621 return 1;
2622 }
2623 newowner = argowner;
2624 }
2625
2626 newtid = task_pid_vnr(newowner) | FUTEX_WAITERS;
2627 /* Owner died? */
2628 if (!pi_state->owner)
2629 newtid |= FUTEX_OWNER_DIED;
2630
2631 err = futex_get_value_locked(&uval, uaddr);
2632 if (err)
2633 goto handle_err;
2634
2635 for (;;) {
2636 newval = (uval & FUTEX_OWNER_DIED) | newtid;
2637
2638 err = futex_cmpxchg_value_locked(&curval, uaddr, uval, newval);
2639 if (err)
2640 goto handle_err;
2641
2642 if (curval == uval)
2643 break;
2644 uval = curval;
2645 }
2646
2647 /*
2648 * We fixed up user space. Now we need to fix the pi_state
2649 * itself.
2650 */
2651 pi_state_update_owner(pi_state, newowner);
2652
2653 return argowner == current;
2654
2655 /*
2656 * In order to reschedule or handle a page fault, we need to drop the
2657 * locks here. In the case of a fault, this gives the other task
2658 * (either the highest priority waiter itself or the task which stole
2659 * the rtmutex) the chance to try the fixup of the pi_state. So once we
2660 * are back from handling the fault we need to check the pi_state after
2661 * reacquiring the locks and before trying to do another fixup. When
2662 * the fixup has been done already we simply return.
2663 *
2664 * Note: we hold both hb->lock and pi_mutex->wait_lock. We can safely
2665 * drop hb->lock since the caller owns the hb -> futex_q relation.
2666 * Dropping the pi_mutex->wait_lock requires the state revalidate.
2667 */
2668handle_err:
2669 raw_spin_unlock_irq(&pi_state->pi_mutex.wait_lock);
2670 spin_unlock(q->lock_ptr);
2671
2672 switch (err) {
2673 case -EFAULT:
2674 err = fault_in_user_writeable(uaddr);
2675 break;
2676
2677 case -EAGAIN:
2678 cond_resched();
2679 err = 0;
2680 break;
2681
2682 default:
2683 WARN_ON_ONCE(1);
2684 break;
2685 }
2686
2687 spin_lock(q->lock_ptr);
2688 raw_spin_lock_irq(&pi_state->pi_mutex.wait_lock);
2689
2690 /*
2691 * Check if someone else fixed it for us:
2692 */
2693 if (pi_state->owner != oldowner)
2694 return argowner == current;
2695
2696 /* Retry if err was -EAGAIN or the fault in succeeded */
2697 if (!err)
2698 goto retry;
2699
2700 /*
2701 * fault_in_user_writeable() failed so user state is immutable. At
2702 * best we can make the kernel state consistent but user state will
2703 * be most likely hosed and any subsequent unlock operation will be
2704 * rejected due to PI futex rule [10].
2705 *
2706 * Ensure that the rtmutex owner is also the pi_state owner despite
2707 * the user space value claiming something different. There is no
2708 * point in unlocking the rtmutex if current is the owner as it
2709 * would need to wait until the next waiter has taken the rtmutex
2710 * to guarantee consistent state. Keep it simple. Userspace asked
2711 * for this wreckaged state.
2712 *
2713 * The rtmutex has an owner - either current or some other
2714 * task. See the EAGAIN loop above.
2715 */
2716 pi_state_update_owner(pi_state, rt_mutex_owner(&pi_state->pi_mutex));
2717
2718 return err;
2719}
2720
2721static int fixup_pi_state_owner(u32 __user *uaddr, struct futex_q *q,
2722 struct task_struct *argowner)
2723{
2724 struct futex_pi_state *pi_state = q->pi_state;
2725 int ret;
2726
2727 lockdep_assert_held(q->lock_ptr);
2728
2729 raw_spin_lock_irq(&pi_state->pi_mutex.wait_lock);
2730 ret = __fixup_pi_state_owner(uaddr, q, argowner);
2731 raw_spin_unlock_irq(&pi_state->pi_mutex.wait_lock);
2732 return ret;
2733}
2734
2735static long futex_wait_restart(struct restart_block *restart);
2736
2737/**
2738 * fixup_owner() - Post lock pi_state and corner case management
2739 * @uaddr: user address of the futex
2740 * @q: futex_q (contains pi_state and access to the rt_mutex)
2741 * @locked: if the attempt to take the rt_mutex succeeded (1) or not (0)
2742 *
2743 * After attempting to lock an rt_mutex, this function is called to cleanup
2744 * the pi_state owner as well as handle race conditions that may allow us to
2745 * acquire the lock. Must be called with the hb lock held.
2746 *
2747 * Return:
2748 * - 1 - success, lock taken;
2749 * - 0 - success, lock not taken;
2750 * - <0 - on error (-EFAULT)
2751 */
2752static int fixup_owner(u32 __user *uaddr, struct futex_q *q, int locked)
2753{
2754 if (locked) {
2755 /*
2756 * Got the lock. We might not be the anticipated owner if we
2757 * did a lock-steal - fix up the PI-state in that case:
2758 *
2759 * Speculative pi_state->owner read (we don't hold wait_lock);
2760 * since we own the lock pi_state->owner == current is the
2761 * stable state, anything else needs more attention.
2762 */
2763 if (q->pi_state->owner != current)
2764 return fixup_pi_state_owner(uaddr, q, current);
2765 return 1;
2766 }
2767
2768 /*
2769 * If we didn't get the lock; check if anybody stole it from us. In
2770 * that case, we need to fix up the uval to point to them instead of
2771 * us, otherwise bad things happen. [10]
2772 *
2773 * Another speculative read; pi_state->owner == current is unstable
2774 * but needs our attention.
2775 */
2776 if (q->pi_state->owner == current)
2777 return fixup_pi_state_owner(uaddr, q, NULL);
2778
2779 /*
2780 * Paranoia check. If we did not take the lock, then we should not be
2781 * the owner of the rt_mutex. Warn and establish consistent state.
2782 */
2783 if (WARN_ON_ONCE(rt_mutex_owner(&q->pi_state->pi_mutex) == current))
2784 return fixup_pi_state_owner(uaddr, q, current);
2785
2786 return 0;
2787}1711}
2788 1712
1713static long futex_wait_restart(struct restart_block *restart);
1714
2789/**1715/**
2790 * futex_wait_queue() - futex_queue() and wait for wakeup, timeout, or signal1716 * futex_wait_queue() - futex_queue() and wait for wakeup, timeout, or signal
2791 * @hb: the futex hash bucket, must be locked by the caller1717 * @hb: the futex hash bucket, must be locked by the caller
@@ -2974,319 +1900,6 @@ static long futex_wait_restart(struct restart_block *restart) · 182 unmodified lines
2974}1900}
2975 1901
2976 1902
2977/*
2978 * Userspace tried a 0 -> TID atomic transition of the futex value
2979 * and failed. The kernel side here does the whole locking operation:
2980 * if there are waiters then it will block as a consequence of relying
2981 * on rt-mutexes, it does PI, etc. (Due to races the kernel might see
2982 * a 0 value of the futex too.).
2983 *
2984 * Also serves as futex trylock_pi()'ing, and due semantics.
2985 */
2986int futex_lock_pi(u32 __user *uaddr, unsigned int flags, ktime_t *time, int trylock)
2987{
2988 struct hrtimer_sleeper timeout, *to;
2989 struct task_struct *exiting = NULL;
2990 struct rt_mutex_waiter rt_waiter;
2991 struct futex_hash_bucket *hb;
2992 struct futex_q q = futex_q_init;
2993 int res, ret;
2994
2995 if (!IS_ENABLED(CONFIG_FUTEX_PI))
2996 return -ENOSYS;
2997
2998 if (refill_pi_state_cache())
2999 return -ENOMEM;
3000
3001 to = futex_setup_timer(time, &timeout, flags, 0);
3002
3003retry:
3004 ret = get_futex_key(uaddr, flags & FLAGS_SHARED, &q.key, FUTEX_WRITE);
3005 if (unlikely(ret != 0))
3006 goto out;
3007
3008retry_private:
3009 hb = futex_q_lock(&q);
3010
3011 ret = futex_lock_pi_atomic(uaddr, hb, &q.key, &q.pi_state, current,
3012 &exiting, 0);
3013 if (unlikely(ret)) {
3014 /*
3015 * Atomic work succeeded and we got the lock,
3016 * or failed. Either way, we do _not_ block.
3017 */
3018 switch (ret) {
3019 case 1:
3020 /* We got the lock. */
3021 ret = 0;
3022 goto out_unlock_put_key;
3023 case -EFAULT:
3024 goto uaddr_faulted;
3025 case -EBUSY:
3026 case -EAGAIN:
3027 /*
3028 * Two reasons for this:
3029 * - EBUSY: Task is exiting and we just wait for the
3030 * exit to complete.
3031 * - EAGAIN: The user space value changed.
3032 */
3033 futex_q_unlock(hb);
3034 /*
3035 * Handle the case where the owner is in the middle of
3036 * exiting. Wait for the exit to complete otherwise
3037 * this task might loop forever, aka. live lock.
3038 */
3039 wait_for_owner_exiting(ret, exiting);
3040 cond_resched();
3041 goto retry;
3042 default:
3043 goto out_unlock_put_key;
3044 }
3045 }
3046
3047 WARN_ON(!q.pi_state);
3048
3049 /*
3050 * Only actually queue now that the atomic ops are done:
3051 */
3052 __futex_queue(&q, hb);
3053
3054 if (trylock) {
3055 ret = rt_mutex_futex_trylock(&q.pi_state->pi_mutex);
3056 /* Fixup the trylock return value: */
3057 ret = ret ? 0 : -EWOULDBLOCK;
3058 goto no_block;
3059 }
3060
3061 rt_mutex_init_waiter(&rt_waiter);
3062
3063 /*
3064 * On PREEMPT_RT_FULL, when hb->lock becomes an rt_mutex, we must not
3065 * hold it while doing rt_mutex_start_proxy(), because then it will
3066 * include hb->lock in the blocking chain, even through we'll not in
3067 * fact hold it while blocking. This will lead it to report -EDEADLK
3068 * and BUG when futex_unlock_pi() interleaves with this.
3069 *
3070 * Therefore acquire wait_lock while holding hb->lock, but drop the
3071 * latter before calling __rt_mutex_start_proxy_lock(). This
3072 * interleaves with futex_unlock_pi() -- which does a similar lock
3073 * handoff -- such that the latter can observe the futex_q::pi_state
3074 * before __rt_mutex_start_proxy_lock() is done.
3075 */
3076 raw_spin_lock_irq(&q.pi_state->pi_mutex.wait_lock);
3077 spin_unlock(q.lock_ptr);
3078 /*
3079 * __rt_mutex_start_proxy_lock() unconditionally enqueues the @rt_waiter
3080 * such that futex_unlock_pi() is guaranteed to observe the waiter when
3081 * it sees the futex_q::pi_state.
3082 */
3083 ret = __rt_mutex_start_proxy_lock(&q.pi_state->pi_mutex, &rt_waiter, current);
3084 raw_spin_unlock_irq(&q.pi_state->pi_mutex.wait_lock);
3085
3086 if (ret) {
3087 if (ret == 1)
3088 ret = 0;
3089 goto cleanup;
3090 }
3091
3092 if (unlikely(to))
3093 hrtimer_sleeper_start_expires(to, HRTIMER_MODE_ABS);
3094
3095 ret = rt_mutex_wait_proxy_lock(&q.pi_state->pi_mutex, to, &rt_waiter);
3096
3097cleanup:
3098 spin_lock(q.lock_ptr);
3099 /*
3100 * If we failed to acquire the lock (deadlock/signal/timeout), we must
3101 * first acquire the hb->lock before removing the lock from the
3102 * rt_mutex waitqueue, such that we can keep the hb and rt_mutex wait
3103 * lists consistent.
3104 *
3105 * In particular; it is important that futex_unlock_pi() can not
3106 * observe this inconsistency.
3107 */
3108 if (ret && !rt_mutex_cleanup_proxy_lock(&q.pi_state->pi_mutex, &rt_waiter))
3109 ret = 0;
3110
3111no_block:
3112 /*
3113 * Fixup the pi_state owner and possibly acquire the lock if we
3114 * haven't already.
3115 */
3116 res = fixup_owner(uaddr, &q, !ret);
3117 /*
3118 * If fixup_owner() returned an error, propagate that. If it acquired
3119 * the lock, clear our -ETIMEDOUT or -EINTR.
3120 */
3121 if (res)
3122 ret = (res < 0) ? res : 0;
3123
3124 futex_unqueue_pi(&q);
3125 spin_unlock(q.lock_ptr);
3126 goto out;
3127
3128out_unlock_put_key:
3129 futex_q_unlock(hb);
3130
3131out:
3132 if (to) {
3133 hrtimer_cancel(&to->timer);
3134 destroy_hrtimer_on_stack(&to->timer);
3135 }
3136 return ret != -EINTR ? ret : -ERESTARTNOINTR;
3137
3138uaddr_faulted:
3139 futex_q_unlock(hb);
3140
3141 ret = fault_in_user_writeable(uaddr);
3142 if (ret)
3143 goto out;
3144
3145 if (!(flags & FLAGS_SHARED))
3146 goto retry_private;
3147
3148 goto retry;
3149}
3150
3151/*
3152 * Userspace attempted a TID -> 0 atomic transition, and failed.
3153 * This is the in-kernel slowpath: we look up the PI state (if any),
3154 * and do the rt-mutex unlock.
3155 */
3156int futex_unlock_pi(u32 __user *uaddr, unsigned int flags)
3157{
3158 u32 curval, uval, vpid = task_pid_vnr(current);
3159 union futex_key key = FUTEX_KEY_INIT;
3160 struct futex_hash_bucket *hb;
3161 struct futex_q *top_waiter;
3162 int ret;
3163
3164 if (!IS_ENABLED(CONFIG_FUTEX_PI))
3165 return -ENOSYS;
3166
3167retry:
3168 if (get_user(uval, uaddr))
3169 return -EFAULT;
3170 /*
3171 * We release only a lock we actually own:
3172 */
3173 if ((uval & FUTEX_TID_MASK) != vpid)
3174 return -EPERM;
3175
3176 ret = get_futex_key(uaddr, flags & FLAGS_SHARED, &key, FUTEX_WRITE);
3177 if (ret)
3178 return ret;
3179
3180 hb = futex_hash(&key);
3181 spin_lock(&hb->lock);
3182
3183 /*
3184 * Check waiters first. We do not trust user space values at
3185 * all and we at least want to know if user space fiddled
3186 * with the futex value instead of blindly unlocking.
3187 */
3188 top_waiter = futex_top_waiter(hb, &key);
3189 if (top_waiter) {
3190 struct futex_pi_state *pi_state = top_waiter->pi_state;
3191
3192 ret = -EINVAL;
3193 if (!pi_state)
3194 goto out_unlock;
3195
3196 /*
3197 * If current does not own the pi_state then the futex is
3198 * inconsistent and user space fiddled with the futex value.
3199 */
3200 if (pi_state->owner != current)
3201 goto out_unlock;
3202
3203 get_pi_state(pi_state);
3204 /*
3205 * By taking wait_lock while still holding hb->lock, we ensure
3206 * there is no point where we hold neither; and therefore
3207 * wake_futex_pi() must observe a state consistent with what we
3208 * observed.
3209 *
3210 * In particular; this forces __rt_mutex_start_proxy() to
3211 * complete such that we're guaranteed to observe the
3212 * rt_waiter. Also see the WARN in wake_futex_pi().
3213 */
3214 raw_spin_lock_irq(&pi_state->pi_mutex.wait_lock);
3215 spin_unlock(&hb->lock);
3216
3217 /* drops pi_state->pi_mutex.wait_lock */
3218 ret = wake_futex_pi(uaddr, uval, pi_state);
3219
3220 put_pi_state(pi_state);
3221
3222 /*
3223 * Success, we're done! No tricky corner cases.
3224 */
3225 if (!ret)
3226 return ret;
3227 /*
3228 * The atomic access to the futex value generated a
3229 * pagefault, so retry the user-access and the wakeup:
3230 */
3231 if (ret == -EFAULT)
3232 goto pi_faulted;
3233 /*
3234 * A unconditional UNLOCK_PI op raced against a waiter
3235 * setting the FUTEX_WAITERS bit. Try again.
3236 */
3237 if (ret == -EAGAIN)
3238 goto pi_retry;
3239 /*
3240 * wake_futex_pi has detected invalid state. Tell user
3241 * space.
3242 */
3243 return ret;
3244 }
3245
3246 /*
3247 * We have no kernel internal state, i.e. no waiters in the
3248 * kernel. Waiters which are about to queue themselves are stuck
3249 * on hb->lock. So we can safely ignore them. We do neither
3250 * preserve the WAITERS bit not the OWNER_DIED one. We are the
3251 * owner.
3252 */
3253 if ((ret = futex_cmpxchg_value_locked(&curval, uaddr, uval, 0))) {
3254 spin_unlock(&hb->lock);
3255 switch (ret) {
3256 case -EFAULT:
3257 goto pi_faulted;
3258
3259 case -EAGAIN:
3260 goto pi_retry;
3261
3262 default:
3263 WARN_ON_ONCE(1);
3264 return ret;
3265 }
3266 }
3267
3268 /*
3269 * If uval has changed, let user space handle it.
3270 */
3271 ret = (curval == uval) ? 0 : -EAGAIN;
3272
3273out_unlock:
3274 spin_unlock(&hb->lock);
3275 return ret;
3276
3277pi_retry:
3278 cond_resched();
3279 goto retry;
3280
3281pi_faulted:
3282
3283 ret = fault_in_user_writeable(uaddr);
3284 if (!ret)
3285 goto retry;
3286
3287 return ret;
3288}
3289
3290/**1903/**
3291 * handle_early_requeue_pi_wakeup() - Handle early wakeup on the initial futex1904 * handle_early_requeue_pi_wakeup() - Handle early wakeup on the initial futex
3292 * @hb: the hash_bucket futex_q was original enqueued on1905 * @hb: the hash_bucket futex_q was original enqueued on
@@ -3441,7 +2054,7 @@ int futex_wait_requeue_pi(u32 __user *uaddr, unsigned int flags, · 148 unmodified lines
3441 /* The requeue acquired the lock */2054 /* The requeue acquired the lock */
3442 if (q.pi_state && (q.pi_state->owner != current)) {2055 if (q.pi_state && (q.pi_state->owner != current)) {
3443 spin_lock(q.lock_ptr);2056 spin_lock(q.lock_ptr);
3444 ret = fixup_owner(uaddr2, &q, true);2057 ret = fixup_pi_owner(uaddr2, &q, true);
3445 /*2058 /*
3446 * Drop the reference to the pi state which the2059 * Drop the reference to the pi state which the
3447 * requeue_pi() code acquired for us.2060 * requeue_pi() code acquired for us.
@@ -3471,9 +2084,9 @@ int futex_wait_requeue_pi(u32 __user *uaddr, unsigned int flags, · 23 unmodified lines
3471 * Fixup the pi_state owner and possibly acquire the lock if we2084 * Fixup the pi_state owner and possibly acquire the lock if we
3472 * haven't already.2085 * haven't already.
3473 */2086 */
3474 res = fixup_owner(uaddr2, &q, !ret);2087 res = fixup_pi_owner(uaddr2, &q, !ret);
3475 /*2088 /*
3476 * If fixup_owner() returned an error, propagate that. If it2089 * If fixup_pi_owner() returned an error, propagate that. If it
3477 * acquired the lock, clear -ETIMEDOUT or -EINTR.2090 * acquired the lock, clear -ETIMEDOUT or -EINTR.
3478 */2091 */
3479 if (res)2092 if (res)
@@ -3811,6 +2424,87 @@ static void compat_exit_robust_list(struct task_struct *curr) · 331 unmodified lines
3811}2424}
3812#endif2425#endif
3813 2426
2427#ifdef CONFIG_FUTEX_PI
2428
2429/*
2430 * This task is holding PI mutexes at exit time => bad.
2431 * Kernel cleans up PI-state, but userspace is likely hosed.
2432 * (Robust-futex cleanup is separate and might save the day for userspace.)
2433 */
2434static void exit_pi_state_list(struct task_struct *curr)
2435{
2436 struct list_head *next, *head = &curr->pi_state_list;
2437 struct futex_pi_state *pi_state;
2438 struct futex_hash_bucket *hb;
2439 union futex_key key = FUTEX_KEY_INIT;
2440
2441 if (!futex_cmpxchg_enabled)
2442 return;
2443 /*
2444 * We are a ZOMBIE and nobody can enqueue itself on
2445 * pi_state_list anymore, but we have to be careful
2446 * versus waiters unqueueing themselves:
2447 */
2448 raw_spin_lock_irq(&curr->pi_lock);
2449 while (!list_empty(head)) {
2450 next = head->next;
2451 pi_state = list_entry(next, struct futex_pi_state, list);
2452 key = pi_state->key;
2453 hb = futex_hash(&key);
2454
2455 /*
2456 * We can race against put_pi_state() removing itself from the
2457 * list (a waiter going away). put_pi_state() will first
2458 * decrement the reference count and then modify the list, so
2459 * its possible to see the list entry but fail this reference
2460 * acquire.
2461 *
2462 * In that case; drop the locks to let put_pi_state() make
2463 * progress and retry the loop.
2464 */
2465 if (!refcount_inc_not_zero(&pi_state->refcount)) {
2466 raw_spin_unlock_irq(&curr->pi_lock);
2467 cpu_relax();
2468 raw_spin_lock_irq(&curr->pi_lock);
2469 continue;
2470 }
2471 raw_spin_unlock_irq(&curr->pi_lock);
2472
2473 spin_lock(&hb->lock);
2474 raw_spin_lock_irq(&pi_state->pi_mutex.wait_lock);
2475 raw_spin_lock(&curr->pi_lock);
2476 /*
2477 * We dropped the pi-lock, so re-check whether this
2478 * task still owns the PI-state:
2479 */
2480 if (head->next != next) {
2481 /* retain curr->pi_lock for the loop invariant */
2482 raw_spin_unlock(&pi_state->pi_mutex.wait_lock);
2483 spin_unlock(&hb->lock);
2484 put_pi_state(pi_state);
2485 continue;
2486 }
2487
2488 WARN_ON(pi_state->owner != curr);
2489 WARN_ON(list_empty(&pi_state->list));
2490 list_del_init(&pi_state->list);
2491 pi_state->owner = NULL;
2492
2493 raw_spin_unlock(&curr->pi_lock);
2494 raw_spin_unlock_irq(&pi_state->pi_mutex.wait_lock);
2495 spin_unlock(&hb->lock);
2496
2497 rt_mutex_futex_unlock(&pi_state->pi_mutex);
2498 put_pi_state(pi_state);
2499
2500 raw_spin_lock_irq(&curr->pi_lock);
2501 }
2502 raw_spin_unlock_irq(&curr->pi_lock);
2503}
2504#else
2505static inline void exit_pi_state_list(struct task_struct *curr) { }
2506#endif
2507
3814static void futex_cleanup(struct task_struct *tsk)2508static void futex_cleanup(struct task_struct *tsk)
3815{2509{
3816 if (unlikely(tsk->robust_list)) {2510 if (unlikely(tsk->robust_list)) {
kernel/futex/futex.h+117−0
@@ -2,6 +2,7 @@ · 1 unmodified line
2#ifndef _FUTEX_H2#ifndef _FUTEX_H
3#define _FUTEX_H3#define _FUTEX_H
4 4
5#include <linux/futex.h>
5#include <asm/futex.h>6#include <asm/futex.h>
6 7
7/*8/*
@@ -35,6 +36,122 @@ static inline bool should_fail_futex(bool fshared) · 27 unmodified lines
35}36}
36#endif37#endif
37 38
39/*
40 * Hash buckets are shared by all the futex_keys that hash to the same
41 * location. Each key may have multiple futex_q structures, one for each task
42 * waiting on a futex.
43 */
44struct futex_hash_bucket {
45 atomic_t waiters;
46 spinlock_t lock;
47 struct plist_head chain;
48} ____cacheline_aligned_in_smp;
49
50/*
51 * Priority Inheritance state:
52 */
53struct futex_pi_state {
54 /*
55 * list of 'owned' pi_state instances - these have to be
56 * cleaned up in do_exit() if the task exits prematurely:
57 */
58 struct list_head list;
59
60 /*
61 * The PI object:
62 */
63 struct rt_mutex_base pi_mutex;
64
65 struct task_struct *owner;
66 refcount_t refcount;
67
68 union futex_key key;
69} __randomize_layout;
70
71/**
72 * struct futex_q - The hashed futex queue entry, one per waiting task
73 * @list: priority-sorted list of tasks waiting on this futex
74 * @task: the task waiting on the futex
75 * @lock_ptr: the hash bucket lock
76 * @key: the key the futex is hashed on
77 * @pi_state: optional priority inheritance state
78 * @rt_waiter: rt_waiter storage for use with requeue_pi
79 * @requeue_pi_key: the requeue_pi target futex key
80 * @bitset: bitset for the optional bitmasked wakeup
81 * @requeue_state: State field for futex_requeue_pi()
82 * @requeue_wait: RCU wait for futex_requeue_pi() (RT only)
83 *
84 * We use this hashed waitqueue, instead of a normal wait_queue_entry_t, so
85 * we can wake only the relevant ones (hashed queues may be shared).
86 *
87 * A futex_q has a woken state, just like tasks have TASK_RUNNING.
88 * It is considered woken when plist_node_empty(&q->list) || q->lock_ptr == 0.
89 * The order of wakeup is always to make the first condition true, then
90 * the second.
91 *
92 * PI futexes are typically woken before they are removed from the hash list via
93 * the rt_mutex code. See futex_unqueue_pi().
94 */
95struct futex_q {
96 struct plist_node list;
97
98 struct task_struct *task;
99 spinlock_t *lock_ptr;
100 union futex_key key;
101 struct futex_pi_state *pi_state;
102 struct rt_mutex_waiter *rt_waiter;
103 union futex_key *requeue_pi_key;
104 u32 bitset;
105 atomic_t requeue_state;
106#ifdef CONFIG_PREEMPT_RT
107 struct rcuwait requeue_wait;
108#endif
109} __randomize_layout;
110
111extern const struct futex_q futex_q_init;
112
113enum futex_access {
114 FUTEX_READ,
115 FUTEX_WRITE
116};
117
118extern int get_futex_key(u32 __user *uaddr, bool fshared, union futex_key *key,
119 enum futex_access rw);
120
121extern struct futex_hash_bucket *futex_hash(union futex_key *key);
122
123extern struct hrtimer_sleeper *
124futex_setup_timer(ktime_t *time, struct hrtimer_sleeper *timeout,
125 int flags, u64 range_ns);
126
127extern int fault_in_user_writeable(u32 __user *uaddr);
128extern int futex_cmpxchg_value_locked(u32 *curval, u32 __user *uaddr, u32 uval, u32 newval);
129extern int futex_get_value_locked(u32 *dest, u32 __user *from);
130extern struct futex_q *futex_top_waiter(struct futex_hash_bucket *hb, union futex_key *key);
131
132extern void __futex_queue(struct futex_q *q, struct futex_hash_bucket *hb);
133extern void futex_unqueue_pi(struct futex_q *q);
134
135extern void wait_for_owner_exiting(int ret, struct task_struct *exiting);
136
137extern struct futex_hash_bucket *futex_q_lock(struct futex_q *q);
138extern void futex_q_unlock(struct futex_hash_bucket *hb);
139
140
141extern int futex_lock_pi_atomic(u32 __user *uaddr, struct futex_hash_bucket *hb,
142 union futex_key *key,
143 struct futex_pi_state **ps,
144 struct task_struct *task,
145 struct task_struct **exiting,
146 int set_waiters);
147
148extern int refill_pi_state_cache(void);
149extern void get_pi_state(struct futex_pi_state *pi_state);
150extern void put_pi_state(struct futex_pi_state *pi_state);
151extern int fixup_pi_owner(u32 __user *uaddr, struct futex_q *q, int locked);
152
153/* syscalls */
154
38extern int futex_wait_requeue_pi(u32 __user *uaddr, unsigned int flags, u32155extern int futex_wait_requeue_pi(u32 __user *uaddr, unsigned int flags, u32
39 val, ktime_t *abs_time, u32 bitset, u32 __user156 val, ktime_t *abs_time, u32 bitset, u32 __user
40 *uaddr2);157 *uaddr2);
kernel/futex/pi.c+1233−0
@@ -0,0 +1,1233 @@
1// SPDX-License-Identifier: GPL-2.0-or-later
2
3#include <linux/slab.h>
4#include <linux/sched/task.h>
5
6#include "futex.h"
7#include "../locking/rtmutex_common.h"
8
9/*
10 * PI code:
11 */
12int refill_pi_state_cache(void)
13{
14 struct futex_pi_state *pi_state;
15
16 if (likely(current->pi_state_cache))
17 return 0;
18
19 pi_state = kzalloc(sizeof(*pi_state), GFP_KERNEL);
20
21 if (!pi_state)
22 return -ENOMEM;
23
24 INIT_LIST_HEAD(&pi_state->list);
25 /* pi_mutex gets initialized later */
26 pi_state->owner = NULL;
27 refcount_set(&pi_state->refcount, 1);
28 pi_state->key = FUTEX_KEY_INIT;
29
30 current->pi_state_cache = pi_state;
31
32 return 0;
33}
34
35static struct futex_pi_state *alloc_pi_state(void)
36{
37 struct futex_pi_state *pi_state = current->pi_state_cache;
38
39 WARN_ON(!pi_state);
40 current->pi_state_cache = NULL;
41
42 return pi_state;
43}
44
45static void pi_state_update_owner(struct futex_pi_state *pi_state,
46 struct task_struct *new_owner)
47{
48 struct task_struct *old_owner = pi_state->owner;
49
50 lockdep_assert_held(&pi_state->pi_mutex.wait_lock);
51
52 if (old_owner) {
53 raw_spin_lock(&old_owner->pi_lock);
54 WARN_ON(list_empty(&pi_state->list));
55 list_del_init(&pi_state->list);
56 raw_spin_unlock(&old_owner->pi_lock);
57 }
58
59 if (new_owner) {
60 raw_spin_lock(&new_owner->pi_lock);
61 WARN_ON(!list_empty(&pi_state->list));
62 list_add(&pi_state->list, &new_owner->pi_state_list);
63 pi_state->owner = new_owner;
64 raw_spin_unlock(&new_owner->pi_lock);
65 }
66}
67
68void get_pi_state(struct futex_pi_state *pi_state)
69{
70 WARN_ON_ONCE(!refcount_inc_not_zero(&pi_state->refcount));
71}
72
73/*
74 * Drops a reference to the pi_state object and frees or caches it
75 * when the last reference is gone.
76 */
77void put_pi_state(struct futex_pi_state *pi_state)
78{
79 if (!pi_state)
80 return;
81
82 if (!refcount_dec_and_test(&pi_state->refcount))
83 return;
84
85 /*
86 * If pi_state->owner is NULL, the owner is most probably dying
87 * and has cleaned up the pi_state already
88 */
89 if (pi_state->owner) {
90 unsigned long flags;
91
92 raw_spin_lock_irqsave(&pi_state->pi_mutex.wait_lock, flags);
93 pi_state_update_owner(pi_state, NULL);
94 rt_mutex_proxy_unlock(&pi_state->pi_mutex);
95 raw_spin_unlock_irqrestore(&pi_state->pi_mutex.wait_lock, flags);
96 }
97
98 if (current->pi_state_cache) {
99 kfree(pi_state);
100 } else {
101 /*
102 * pi_state->list is already empty.
103 * clear pi_state->owner.
104 * refcount is at 0 - put it back to 1.
105 */
106 pi_state->owner = NULL;
107 refcount_set(&pi_state->refcount, 1);
108 current->pi_state_cache = pi_state;
109 }
110}
111
112/*
113 * We need to check the following states:
114 *
115 * Waiter | pi_state | pi->owner | uTID | uODIED | ?
116 *
117 * [1] NULL | --- | --- | 0 | 0/1 | Valid
118 * [2] NULL | --- | --- | >0 | 0/1 | Valid
119 *
120 * [3] Found | NULL | -- | Any | 0/1 | Invalid
121 *
122 * [4] Found | Found | NULL | 0 | 1 | Valid
123 * [5] Found | Found | NULL | >0 | 1 | Invalid
124 *
125 * [6] Found | Found | task | 0 | 1 | Valid
126 *
127 * [7] Found | Found | NULL | Any | 0 | Invalid
128 *
129 * [8] Found | Found | task | ==taskTID | 0/1 | Valid
130 * [9] Found | Found | task | 0 | 0 | Invalid
131 * [10] Found | Found | task | !=taskTID | 0/1 | Invalid
132 *
133 * [1] Indicates that the kernel can acquire the futex atomically. We
134 * came here due to a stale FUTEX_WAITERS/FUTEX_OWNER_DIED bit.
135 *
136 * [2] Valid, if TID does not belong to a kernel thread. If no matching
137 * thread is found then it indicates that the owner TID has died.
138 *
139 * [3] Invalid. The waiter is queued on a non PI futex
140 *
141 * [4] Valid state after exit_robust_list(), which sets the user space
142 * value to FUTEX_WAITERS | FUTEX_OWNER_DIED.
143 *
144 * [5] The user space value got manipulated between exit_robust_list()
145 * and exit_pi_state_list()
146 *
147 * [6] Valid state after exit_pi_state_list() which sets the new owner in
148 * the pi_state but cannot access the user space value.
149 *
150 * [7] pi_state->owner can only be NULL when the OWNER_DIED bit is set.
151 *
152 * [8] Owner and user space value match
153 *
154 * [9] There is no transient state which sets the user space TID to 0
155 * except exit_robust_list(), but this is indicated by the
156 * FUTEX_OWNER_DIED bit. See [4]
157 *
158 * [10] There is no transient state which leaves owner and user space
159 * TID out of sync. Except one error case where the kernel is denied
160 * write access to the user address, see fixup_pi_state_owner().
161 *
162 *
163 * Serialization and lifetime rules:
164 *
165 * hb->lock:
166 *
167 * hb -> futex_q, relation
168 * futex_q -> pi_state, relation
169 *
170 * (cannot be raw because hb can contain arbitrary amount
171 * of futex_q's)
172 *
173 * pi_mutex->wait_lock:
174 *
175 * {uval, pi_state}
176 *
177 * (and pi_mutex 'obviously')
178 *
179 * p->pi_lock:
180 *
181 * p->pi_state_list -> pi_state->list, relation
182 * pi_mutex->owner -> pi_state->owner, relation
183 *
184 * pi_state->refcount:
185 *
186 * pi_state lifetime
187 *
188 *
189 * Lock order:
190 *
191 * hb->lock
192 * pi_mutex->wait_lock
193 * p->pi_lock
194 *
195 */
196
197/*
198 * Validate that the existing waiter has a pi_state and sanity check
199 * the pi_state against the user space value. If correct, attach to
200 * it.
201 */
202static int attach_to_pi_state(u32 __user *uaddr, u32 uval,
203 struct futex_pi_state *pi_state,
204 struct futex_pi_state **ps)
205{
206 pid_t pid = uval & FUTEX_TID_MASK;
207 u32 uval2;
208 int ret;
209
210 /*
211 * Userspace might have messed up non-PI and PI futexes [3]
212 */
213 if (unlikely(!pi_state))
214 return -EINVAL;
215
216 /*
217 * We get here with hb->lock held, and having found a
218 * futex_top_waiter(). This means that futex_lock_pi() of said futex_q
219 * has dropped the hb->lock in between futex_queue() and futex_unqueue_pi(),
220 * which in turn means that futex_lock_pi() still has a reference on
221 * our pi_state.
222 *
223 * The waiter holding a reference on @pi_state also protects against
224 * the unlocked put_pi_state() in futex_unlock_pi(), futex_lock_pi()
225 * and futex_wait_requeue_pi() as it cannot go to 0 and consequently
226 * free pi_state before we can take a reference ourselves.
227 */
228 WARN_ON(!refcount_read(&pi_state->refcount));
229
230 /*
231 * Now that we have a pi_state, we can acquire wait_lock
232 * and do the state validation.
233 */
234 raw_spin_lock_irq(&pi_state->pi_mutex.wait_lock);
235
236 /*
237 * Since {uval, pi_state} is serialized by wait_lock, and our current
238 * uval was read without holding it, it can have changed. Verify it
239 * still is what we expect it to be, otherwise retry the entire
240 * operation.
241 */
242 if (futex_get_value_locked(&uval2, uaddr))
243 goto out_efault;
244
245 if (uval != uval2)
246 goto out_eagain;
247
248 /*
249 * Handle the owner died case:
250 */
251 if (uval & FUTEX_OWNER_DIED) {
252 /*
253 * exit_pi_state_list sets owner to NULL and wakes the
254 * topmost waiter. The task which acquires the
255 * pi_state->rt_mutex will fixup owner.
256 */
257 if (!pi_state->owner) {
258 /*
259 * No pi state owner, but the user space TID
260 * is not 0. Inconsistent state. [5]
261 */
262 if (pid)
263 goto out_einval;
264 /*
265 * Take a ref on the state and return success. [4]
266 */
267 goto out_attach;
268 }
269
270 /*
271 * If TID is 0, then either the dying owner has not
272 * yet executed exit_pi_state_list() or some waiter
273 * acquired the rtmutex in the pi state, but did not
274 * yet fixup the TID in user space.
275 *
276 * Take a ref on the state and return success. [6]
277 */
278 if (!pid)
279 goto out_attach;
280 } else {
281 /*
282 * If the owner died bit is not set, then the pi_state
283 * must have an owner. [7]
284 */
285 if (!pi_state->owner)
286 goto out_einval;
287 }
288
289 /*
290 * Bail out if user space manipulated the futex value. If pi
291 * state exists then the owner TID must be the same as the
292 * user space TID. [9/10]
293 */
294 if (pid != task_pid_vnr(pi_state->owner))
295 goto out_einval;
296
297out_attach:
298 get_pi_state(pi_state);
299 raw_spin_unlock_irq(&pi_state->pi_mutex.wait_lock);
300 *ps = pi_state;
301 return 0;
302
303out_einval:
304 ret = -EINVAL;
305 goto out_error;
306
307out_eagain:
308 ret = -EAGAIN;
309 goto out_error;
310
311out_efault:
312 ret = -EFAULT;
313 goto out_error;
314
315out_error:
316 raw_spin_unlock_irq(&pi_state->pi_mutex.wait_lock);
317 return ret;
318}
319
320static int handle_exit_race(u32 __user *uaddr, u32 uval,
321 struct task_struct *tsk)
322{
323 u32 uval2;
324
325 /*
326 * If the futex exit state is not yet FUTEX_STATE_DEAD, tell the
327 * caller that the alleged owner is busy.
328 */
329 if (tsk && tsk->futex_state != FUTEX_STATE_DEAD)
330 return -EBUSY;
331
332 /*
333 * Reread the user space value to handle the following situation:
334 *
335 * CPU0 CPU1
336 *
337 * sys_exit() sys_futex()
338 * do_exit() futex_lock_pi()
339 * futex_lock_pi_atomic()
340 * exit_signals(tsk) No waiters:
341 * tsk->flags |= PF_EXITING; *uaddr == 0x00000PID
342 * mm_release(tsk) Set waiter bit
343 * exit_robust_list(tsk) { *uaddr = 0x80000PID;
344 * Set owner died attach_to_pi_owner() {
345 * *uaddr = 0xC0000000; tsk = get_task(PID);
346 * } if (!tsk->flags & PF_EXITING) {
347 * ... attach();
348 * tsk->futex_state = } else {
349 * FUTEX_STATE_DEAD; if (tsk->futex_state !=
350 * FUTEX_STATE_DEAD)
351 * return -EAGAIN;
352 * return -ESRCH; <--- FAIL
353 * }
354 *
355 * Returning ESRCH unconditionally is wrong here because the
356 * user space value has been changed by the exiting task.
357 *
358 * The same logic applies to the case where the exiting task is
359 * already gone.
360 */
361 if (futex_get_value_locked(&uval2, uaddr))
362 return -EFAULT;
363
364 /* If the user space value has changed, try again. */
365 if (uval2 != uval)
366 return -EAGAIN;
367
368 /*
369 * The exiting task did not have a robust list, the robust list was
370 * corrupted or the user space value in *uaddr is simply bogus.
371 * Give up and tell user space.
372 */
373 return -ESRCH;
374}
375
376static void __attach_to_pi_owner(struct task_struct *p, union futex_key *key,
377 struct futex_pi_state **ps)
378{
379 /*
380 * No existing pi state. First waiter. [2]
381 *
382 * This creates pi_state, we have hb->lock held, this means nothing can
383 * observe this state, wait_lock is irrelevant.
384 */
385 struct futex_pi_state *pi_state = alloc_pi_state();
386
387 /*
388 * Initialize the pi_mutex in locked state and make @p
389 * the owner of it:
390 */
391 rt_mutex_init_proxy_locked(&pi_state->pi_mutex, p);
392
393 /* Store the key for possible exit cleanups: */
394 pi_state->key = *key;
395
396 WARN_ON(!list_empty(&pi_state->list));
397 list_add(&pi_state->list, &p->pi_state_list);
398 /*
399 * Assignment without holding pi_state->pi_mutex.wait_lock is safe
400 * because there is no concurrency as the object is not published yet.
401 */
402 pi_state->owner = p;
403
404 *ps = pi_state;
405}
406/*
407 * Lookup the task for the TID provided from user space and attach to
408 * it after doing proper sanity checks.
409 */
410static int attach_to_pi_owner(u32 __user *uaddr, u32 uval, union futex_key *key,
411 struct futex_pi_state **ps,
412 struct task_struct **exiting)
413{
414 pid_t pid = uval & FUTEX_TID_MASK;
415 struct task_struct *p;
416
417 /*
418 * We are the first waiter - try to look up the real owner and attach
419 * the new pi_state to it, but bail out when TID = 0 [1]
420 *
421 * The !pid check is paranoid. None of the call sites should end up
422 * with pid == 0, but better safe than sorry. Let the caller retry
423 */
424 if (!pid)
425 return -EAGAIN;
426 p = find_get_task_by_vpid(pid);
427 if (!p)
428 return handle_exit_race(uaddr, uval, NULL);
429
430 if (unlikely(p->flags & PF_KTHREAD)) {
431 put_task_struct(p);
432 return -EPERM;
433 }
434
435 /*
436 * We need to look at the task state to figure out, whether the
437 * task is exiting. To protect against the change of the task state
438 * in futex_exit_release(), we do this protected by p->pi_lock:
439 */
440 raw_spin_lock_irq(&p->pi_lock);
441 if (unlikely(p->futex_state != FUTEX_STATE_OK)) {
442 /*
443 * The task is on the way out. When the futex state is
444 * FUTEX_STATE_DEAD, we know that the task has finished
445 * the cleanup:
446 */
447 int ret = handle_exit_race(uaddr, uval, p);
448
449 raw_spin_unlock_irq(&p->pi_lock);
450 /*
451 * If the owner task is between FUTEX_STATE_EXITING and
452 * FUTEX_STATE_DEAD then store the task pointer and keep
453 * the reference on the task struct. The calling code will
454 * drop all locks, wait for the task to reach
455 * FUTEX_STATE_DEAD and then drop the refcount. This is
456 * required to prevent a live lock when the current task
457 * preempted the exiting task between the two states.
458 */
459 if (ret == -EBUSY)
460 *exiting = p;
461 else
462 put_task_struct(p);
463 return ret;
464 }
465
466 __attach_to_pi_owner(p, key, ps);
467 raw_spin_unlock_irq(&p->pi_lock);
468
469 put_task_struct(p);
470
471 return 0;
472}
473
474static int lock_pi_update_atomic(u32 __user *uaddr, u32 uval, u32 newval)
475{
476 int err;
477 u32 curval;
478
479 if (unlikely(should_fail_futex(true)))
480 return -EFAULT;
481
482 err = futex_cmpxchg_value_locked(&curval, uaddr, uval, newval);
483 if (unlikely(err))
484 return err;
485
486 /* If user space value changed, let the caller retry */
487 return curval != uval ? -EAGAIN : 0;
488}
489
490/**
491 * futex_lock_pi_atomic() - Atomic work required to acquire a pi aware futex
492 * @uaddr: the pi futex user address
493 * @hb: the pi futex hash bucket
494 * @key: the futex key associated with uaddr and hb
495 * @ps: the pi_state pointer where we store the result of the
496 * lookup
497 * @task: the task to perform the atomic lock work for. This will
498 * be "current" except in the case of requeue pi.
499 * @exiting: Pointer to store the task pointer of the owner task
500 * which is in the middle of exiting
501 * @set_waiters: force setting the FUTEX_WAITERS bit (1) or not (0)
502 *
503 * Return:
504 * - 0 - ready to wait;
505 * - 1 - acquired the lock;
506 * - <0 - error
507 *
508 * The hb->lock must be held by the caller.
509 *
510 * @exiting is only set when the return value is -EBUSY. If so, this holds
511 * a refcount on the exiting task on return and the caller needs to drop it
512 * after waiting for the exit to complete.
513 */
514int futex_lock_pi_atomic(u32 __user *uaddr, struct futex_hash_bucket *hb,
515 union futex_key *key,
516 struct futex_pi_state **ps,
517 struct task_struct *task,
518 struct task_struct **exiting,
519 int set_waiters)
520{
521 u32 uval, newval, vpid = task_pid_vnr(task);
522 struct futex_q *top_waiter;
523 int ret;
524
525 /*
526 * Read the user space value first so we can validate a few
527 * things before proceeding further.
528 */
529 if (futex_get_value_locked(&uval, uaddr))
530 return -EFAULT;
531
532 if (unlikely(should_fail_futex(true)))
533 return -EFAULT;
534
535 /*
536 * Detect deadlocks.
537 */
538 if ((unlikely((uval & FUTEX_TID_MASK) == vpid)))
539 return -EDEADLK;
540
541 if ((unlikely(should_fail_futex(true))))
542 return -EDEADLK;
543
544 /*
545 * Lookup existing state first. If it exists, try to attach to
546 * its pi_state.
547 */
548 top_waiter = futex_top_waiter(hb, key);
549 if (top_waiter)
550 return attach_to_pi_state(uaddr, uval, top_waiter->pi_state, ps);
551
552 /*
553 * No waiter and user TID is 0. We are here because the
554 * waiters or the owner died bit is set or called from
555 * requeue_cmp_pi or for whatever reason something took the
556 * syscall.
557 */
558 if (!(uval & FUTEX_TID_MASK)) {
559 /*
560 * We take over the futex. No other waiters and the user space
561 * TID is 0. We preserve the owner died bit.
562 */
563 newval = uval & FUTEX_OWNER_DIED;
564 newval |= vpid;
565
566 /* The futex requeue_pi code can enforce the waiters bit */
567 if (set_waiters)
568 newval |= FUTEX_WAITERS;
569
570 ret = lock_pi_update_atomic(uaddr, uval, newval);
571 if (ret)
572 return ret;
573
574 /*
575 * If the waiter bit was requested the caller also needs PI
576 * state attached to the new owner of the user space futex.
577 *
578 * @task is guaranteed to be alive and it cannot be exiting
579 * because it is either sleeping or waiting in
580 * futex_requeue_pi_wakeup_sync().
581 *
582 * No need to do the full attach_to_pi_owner() exercise
583 * because @task is known and valid.
584 */
585 if (set_waiters) {
586 raw_spin_lock_irq(&task->pi_lock);
587 __attach_to_pi_owner(task, key, ps);
588 raw_spin_unlock_irq(&task->pi_lock);
589 }
590 return 1;
591 }
592
593 /*
594 * First waiter. Set the waiters bit before attaching ourself to
595 * the owner. If owner tries to unlock, it will be forced into
596 * the kernel and blocked on hb->lock.
597 */
598 newval = uval | FUTEX_WAITERS;
599 ret = lock_pi_update_atomic(uaddr, uval, newval);
600 if (ret)
601 return ret;
602 /*
603 * If the update of the user space value succeeded, we try to
604 * attach to the owner. If that fails, no harm done, we only
605 * set the FUTEX_WAITERS bit in the user space variable.
606 */
607 return attach_to_pi_owner(uaddr, newval, key, ps, exiting);
608}
609
610/*
611 * Caller must hold a reference on @pi_state.
612 */
613static int wake_futex_pi(u32 __user *uaddr, u32 uval, struct futex_pi_state *pi_state)
614{
615 struct rt_mutex_waiter *top_waiter;
616 struct task_struct *new_owner;
617 bool postunlock = false;
618 DEFINE_RT_WAKE_Q(wqh);
619 u32 curval, newval;
620 int ret = 0;
621
622 top_waiter = rt_mutex_top_waiter(&pi_state->pi_mutex);
623 if (WARN_ON_ONCE(!top_waiter)) {
624 /*
625 * As per the comment in futex_unlock_pi() this should not happen.
626 *
627 * When this happens, give up our locks and try again, giving
628 * the futex_lock_pi() instance time to complete, either by
629 * waiting on the rtmutex or removing itself from the futex
630 * queue.
631 */
632 ret = -EAGAIN;
633 goto out_unlock;
634 }
635
636 new_owner = top_waiter->task;
637
638 /*
639 * We pass it to the next owner. The WAITERS bit is always kept
640 * enabled while there is PI state around. We cleanup the owner
641 * died bit, because we are the owner.
642 */
643 newval = FUTEX_WAITERS | task_pid_vnr(new_owner);
644
645 if (unlikely(should_fail_futex(true))) {
646 ret = -EFAULT;
647 goto out_unlock;
648 }
649
650 ret = futex_cmpxchg_value_locked(&curval, uaddr, uval, newval);
651 if (!ret && (curval != uval)) {
652 /*
653 * If a unconditional UNLOCK_PI operation (user space did not
654 * try the TID->0 transition) raced with a waiter setting the
655 * FUTEX_WAITERS flag between get_user() and locking the hash
656 * bucket lock, retry the operation.
657 */
658 if ((FUTEX_TID_MASK & curval) == uval)
659 ret = -EAGAIN;
660 else
661 ret = -EINVAL;
662 }
663
664 if (!ret) {
665 /*
666 * This is a point of no return; once we modified the uval
667 * there is no going back and subsequent operations must
668 * not fail.
669 */
670 pi_state_update_owner(pi_state, new_owner);
671 postunlock = __rt_mutex_futex_unlock(&pi_state->pi_mutex, &wqh);
672 }
673
674out_unlock:
675 raw_spin_unlock_irq(&pi_state->pi_mutex.wait_lock);
676
677 if (postunlock)
678 rt_mutex_postunlock(&wqh);
679
680 return ret;
681}
682
683static int __fixup_pi_state_owner(u32 __user *uaddr, struct futex_q *q,
684 struct task_struct *argowner)
685{
686 struct futex_pi_state *pi_state = q->pi_state;
687 struct task_struct *oldowner, *newowner;
688 u32 uval, curval, newval, newtid;
689 int err = 0;
690
691 oldowner = pi_state->owner;
692
693 /*
694 * We are here because either:
695 *
696 * - we stole the lock and pi_state->owner needs updating to reflect
697 * that (@argowner == current),
698 *
699 * or:
700 *
701 * - someone stole our lock and we need to fix things to point to the
702 * new owner (@argowner == NULL).
703 *
704 * Either way, we have to replace the TID in the user space variable.
705 * This must be atomic as we have to preserve the owner died bit here.
706 *
707 * Note: We write the user space value _before_ changing the pi_state
708 * because we can fault here. Imagine swapped out pages or a fork
709 * that marked all the anonymous memory readonly for cow.
710 *
711 * Modifying pi_state _before_ the user space value would leave the
712 * pi_state in an inconsistent state when we fault here, because we
713 * need to drop the locks to handle the fault. This might be observed
714 * in the PID checks when attaching to PI state .
715 */
716retry:
717 if (!argowner) {
718 if (oldowner != current) {
719 /*
720 * We raced against a concurrent self; things are
721 * already fixed up. Nothing to do.
722 */
723 return 0;
724 }
725
726 if (__rt_mutex_futex_trylock(&pi_state->pi_mutex)) {
727 /* We got the lock. pi_state is correct. Tell caller. */
728 return 1;
729 }
730
731 /*
732 * The trylock just failed, so either there is an owner or
733 * there is a higher priority waiter than this one.
734 */
735 newowner = rt_mutex_owner(&pi_state->pi_mutex);
736 /*
737 * If the higher priority waiter has not yet taken over the
738 * rtmutex then newowner is NULL. We can't return here with
739 * that state because it's inconsistent vs. the user space
740 * state. So drop the locks and try again. It's a valid
741 * situation and not any different from the other retry
742 * conditions.
743 */
744 if (unlikely(!newowner)) {
745 err = -EAGAIN;
746 goto handle_err;
747 }
748 } else {
749 WARN_ON_ONCE(argowner != current);
750 if (oldowner == current) {
751 /*
752 * We raced against a concurrent self; things are
753 * already fixed up. Nothing to do.
754 */
755 return 1;
756 }
757 newowner = argowner;
758 }
759
760 newtid = task_pid_vnr(newowner) | FUTEX_WAITERS;
761 /* Owner died? */
762 if (!pi_state->owner)
763 newtid |= FUTEX_OWNER_DIED;
764
765 err = futex_get_value_locked(&uval, uaddr);
766 if (err)
767 goto handle_err;
768
769 for (;;) {
770 newval = (uval & FUTEX_OWNER_DIED) | newtid;
771
772 err = futex_cmpxchg_value_locked(&curval, uaddr, uval, newval);
773 if (err)
774 goto handle_err;
775
776 if (curval == uval)
777 break;
778 uval = curval;
779 }
780
781 /*
782 * We fixed up user space. Now we need to fix the pi_state
783 * itself.
784 */
785 pi_state_update_owner(pi_state, newowner);
786
787 return argowner == current;
788
789 /*
790 * In order to reschedule or handle a page fault, we need to drop the
791 * locks here. In the case of a fault, this gives the other task
792 * (either the highest priority waiter itself or the task which stole
793 * the rtmutex) the chance to try the fixup of the pi_state. So once we
794 * are back from handling the fault we need to check the pi_state after
795 * reacquiring the locks and before trying to do another fixup. When
796 * the fixup has been done already we simply return.
797 *
798 * Note: we hold both hb->lock and pi_mutex->wait_lock. We can safely
799 * drop hb->lock since the caller owns the hb -> futex_q relation.
800 * Dropping the pi_mutex->wait_lock requires the state revalidate.
801 */
802handle_err:
803 raw_spin_unlock_irq(&pi_state->pi_mutex.wait_lock);
804 spin_unlock(q->lock_ptr);
805
806 switch (err) {
807 case -EFAULT:
808 err = fault_in_user_writeable(uaddr);
809 break;
810
811 case -EAGAIN:
812 cond_resched();
813 err = 0;
814 break;
815
816 default:
817 WARN_ON_ONCE(1);
818 break;
819 }
820
821 spin_lock(q->lock_ptr);
822 raw_spin_lock_irq(&pi_state->pi_mutex.wait_lock);
823
824 /*
825 * Check if someone else fixed it for us:
826 */
827 if (pi_state->owner != oldowner)
828 return argowner == current;
829
830 /* Retry if err was -EAGAIN or the fault in succeeded */
831 if (!err)
832 goto retry;
833
834 /*
835 * fault_in_user_writeable() failed so user state is immutable. At
836 * best we can make the kernel state consistent but user state will
837 * be most likely hosed and any subsequent unlock operation will be
838 * rejected due to PI futex rule [10].
839 *
840 * Ensure that the rtmutex owner is also the pi_state owner despite
841 * the user space value claiming something different. There is no
842 * point in unlocking the rtmutex if current is the owner as it
843 * would need to wait until the next waiter has taken the rtmutex
844 * to guarantee consistent state. Keep it simple. Userspace asked
845 * for this wreckaged state.
846 *
847 * The rtmutex has an owner - either current or some other
848 * task. See the EAGAIN loop above.
849 */
850 pi_state_update_owner(pi_state, rt_mutex_owner(&pi_state->pi_mutex));
851
852 return err;
853}
854
855static int fixup_pi_state_owner(u32 __user *uaddr, struct futex_q *q,
856 struct task_struct *argowner)
857{
858 struct futex_pi_state *pi_state = q->pi_state;
859 int ret;
860
861 lockdep_assert_held(q->lock_ptr);
862
863 raw_spin_lock_irq(&pi_state->pi_mutex.wait_lock);
864 ret = __fixup_pi_state_owner(uaddr, q, argowner);
865 raw_spin_unlock_irq(&pi_state->pi_mutex.wait_lock);
866 return ret;
867}
868
869/**
870 * fixup_pi_owner() - Post lock pi_state and corner case management
871 * @uaddr: user address of the futex
872 * @q: futex_q (contains pi_state and access to the rt_mutex)
873 * @locked: if the attempt to take the rt_mutex succeeded (1) or not (0)
874 *
875 * After attempting to lock an rt_mutex, this function is called to cleanup
876 * the pi_state owner as well as handle race conditions that may allow us to
877 * acquire the lock. Must be called with the hb lock held.
878 *
879 * Return:
880 * - 1 - success, lock taken;
881 * - 0 - success, lock not taken;
882 * - <0 - on error (-EFAULT)
883 */
884int fixup_pi_owner(u32 __user *uaddr, struct futex_q *q, int locked)
885{
886 if (locked) {
887 /*
888 * Got the lock. We might not be the anticipated owner if we
889 * did a lock-steal - fix up the PI-state in that case:
890 *
891 * Speculative pi_state->owner read (we don't hold wait_lock);
892 * since we own the lock pi_state->owner == current is the
893 * stable state, anything else needs more attention.
894 */
895 if (q->pi_state->owner != current)
896 return fixup_pi_state_owner(uaddr, q, current);
897 return 1;
898 }
899
900 /*
901 * If we didn't get the lock; check if anybody stole it from us. In
902 * that case, we need to fix up the uval to point to them instead of
903 * us, otherwise bad things happen. [10]
904 *
905 * Another speculative read; pi_state->owner == current is unstable
906 * but needs our attention.
907 */
908 if (q->pi_state->owner == current)
909 return fixup_pi_state_owner(uaddr, q, NULL);
910
911 /*
912 * Paranoia check. If we did not take the lock, then we should not be
913 * the owner of the rt_mutex. Warn and establish consistent state.
914 */
915 if (WARN_ON_ONCE(rt_mutex_owner(&q->pi_state->pi_mutex) == current))
916 return fixup_pi_state_owner(uaddr, q, current);
917
918 return 0;
919}
920
921/*
922 * Userspace tried a 0 -> TID atomic transition of the futex value
923 * and failed. The kernel side here does the whole locking operation:
924 * if there are waiters then it will block as a consequence of relying
925 * on rt-mutexes, it does PI, etc. (Due to races the kernel might see
926 * a 0 value of the futex too.).
927 *
928 * Also serves as futex trylock_pi()'ing, and due semantics.
929 */
930int futex_lock_pi(u32 __user *uaddr, unsigned int flags, ktime_t *time, int trylock)
931{
932 struct hrtimer_sleeper timeout, *to;
933 struct task_struct *exiting = NULL;
934 struct rt_mutex_waiter rt_waiter;
935 struct futex_hash_bucket *hb;
936 struct futex_q q = futex_q_init;
937 int res, ret;
938
939 if (!IS_ENABLED(CONFIG_FUTEX_PI))
940 return -ENOSYS;
941
942 if (refill_pi_state_cache())
943 return -ENOMEM;
944
945 to = futex_setup_timer(time, &timeout, flags, 0);
946
947retry:
948 ret = get_futex_key(uaddr, flags & FLAGS_SHARED, &q.key, FUTEX_WRITE);
949 if (unlikely(ret != 0))
950 goto out;
951
952retry_private:
953 hb = futex_q_lock(&q);
954
955 ret = futex_lock_pi_atomic(uaddr, hb, &q.key, &q.pi_state, current,
956 &exiting, 0);
957 if (unlikely(ret)) {
958 /*
959 * Atomic work succeeded and we got the lock,
960 * or failed. Either way, we do _not_ block.
961 */
962 switch (ret) {
963 case 1:
964 /* We got the lock. */
965 ret = 0;
966 goto out_unlock_put_key;
967 case -EFAULT:
968 goto uaddr_faulted;
969 case -EBUSY:
970 case -EAGAIN:
971 /*
972 * Two reasons for this:
973 * - EBUSY: Task is exiting and we just wait for the
974 * exit to complete.
975 * - EAGAIN: The user space value changed.
976 */
977 futex_q_unlock(hb);
978 /*
979 * Handle the case where the owner is in the middle of
980 * exiting. Wait for the exit to complete otherwise
981 * this task might loop forever, aka. live lock.
982 */
983 wait_for_owner_exiting(ret, exiting);
984 cond_resched();
985 goto retry;
986 default:
987 goto out_unlock_put_key;
988 }
989 }
990
991 WARN_ON(!q.pi_state);
992
993 /*
994 * Only actually queue now that the atomic ops are done:
995 */
996 __futex_queue(&q, hb);
997
998 if (trylock) {
999 ret = rt_mutex_futex_trylock(&q.pi_state->pi_mutex);
1000 /* Fixup the trylock return value: */
1001 ret = ret ? 0 : -EWOULDBLOCK;
1002 goto no_block;
1003 }
1004
1005 rt_mutex_init_waiter(&rt_waiter);
1006
1007 /*
1008 * On PREEMPT_RT_FULL, when hb->lock becomes an rt_mutex, we must not
1009 * hold it while doing rt_mutex_start_proxy(), because then it will
1010 * include hb->lock in the blocking chain, even through we'll not in
1011 * fact hold it while blocking. This will lead it to report -EDEADLK
1012 * and BUG when futex_unlock_pi() interleaves with this.
1013 *
1014 * Therefore acquire wait_lock while holding hb->lock, but drop the
1015 * latter before calling __rt_mutex_start_proxy_lock(). This
1016 * interleaves with futex_unlock_pi() -- which does a similar lock
1017 * handoff -- such that the latter can observe the futex_q::pi_state
1018 * before __rt_mutex_start_proxy_lock() is done.
1019 */
1020 raw_spin_lock_irq(&q.pi_state->pi_mutex.wait_lock);
1021 spin_unlock(q.lock_ptr);
1022 /*
1023 * __rt_mutex_start_proxy_lock() unconditionally enqueues the @rt_waiter
1024 * such that futex_unlock_pi() is guaranteed to observe the waiter when
1025 * it sees the futex_q::pi_state.
1026 */
1027 ret = __rt_mutex_start_proxy_lock(&q.pi_state->pi_mutex, &rt_waiter, current);
1028 raw_spin_unlock_irq(&q.pi_state->pi_mutex.wait_lock);
1029
1030 if (ret) {
1031 if (ret == 1)
1032 ret = 0;
1033 goto cleanup;
1034 }
1035
1036 if (unlikely(to))
1037 hrtimer_sleeper_start_expires(to, HRTIMER_MODE_ABS);
1038
1039 ret = rt_mutex_wait_proxy_lock(&q.pi_state->pi_mutex, to, &rt_waiter);
1040
1041cleanup:
1042 spin_lock(q.lock_ptr);
1043 /*
1044 * If we failed to acquire the lock (deadlock/signal/timeout), we must
1045 * first acquire the hb->lock before removing the lock from the
1046 * rt_mutex waitqueue, such that we can keep the hb and rt_mutex wait
1047 * lists consistent.
1048 *
1049 * In particular; it is important that futex_unlock_pi() can not
1050 * observe this inconsistency.
1051 */
1052 if (ret && !rt_mutex_cleanup_proxy_lock(&q.pi_state->pi_mutex, &rt_waiter))
1053 ret = 0;
1054
1055no_block:
1056 /*
1057 * Fixup the pi_state owner and possibly acquire the lock if we
1058 * haven't already.
1059 */
1060 res = fixup_pi_owner(uaddr, &q, !ret);
1061 /*
1062 * If fixup_pi_owner() returned an error, propagate that. If it acquired
1063 * the lock, clear our -ETIMEDOUT or -EINTR.
1064 */
1065 if (res)
1066 ret = (res < 0) ? res : 0;
1067
1068 futex_unqueue_pi(&q);
1069 spin_unlock(q.lock_ptr);
1070 goto out;
1071
1072out_unlock_put_key:
1073 futex_q_unlock(hb);
1074
1075out:
1076 if (to) {
1077 hrtimer_cancel(&to->timer);
1078 destroy_hrtimer_on_stack(&to->timer);
1079 }
1080 return ret != -EINTR ? ret : -ERESTARTNOINTR;
1081
1082uaddr_faulted:
1083 futex_q_unlock(hb);
1084
1085 ret = fault_in_user_writeable(uaddr);
1086 if (ret)
1087 goto out;
1088
1089 if (!(flags & FLAGS_SHARED))
1090 goto retry_private;
1091
1092 goto retry;
1093}
1094
1095/*
1096 * Userspace attempted a TID -> 0 atomic transition, and failed.
1097 * This is the in-kernel slowpath: we look up the PI state (if any),
1098 * and do the rt-mutex unlock.
1099 */
1100int futex_unlock_pi(u32 __user *uaddr, unsigned int flags)
1101{
1102 u32 curval, uval, vpid = task_pid_vnr(current);
1103 union futex_key key = FUTEX_KEY_INIT;
1104 struct futex_hash_bucket *hb;
1105 struct futex_q *top_waiter;
1106 int ret;
1107
1108 if (!IS_ENABLED(CONFIG_FUTEX_PI))
1109 return -ENOSYS;
1110
1111retry:
1112 if (get_user(uval, uaddr))
1113 return -EFAULT;
1114 /*
1115 * We release only a lock we actually own:
1116 */
1117 if ((uval & FUTEX_TID_MASK) != vpid)
1118 return -EPERM;
1119
1120 ret = get_futex_key(uaddr, flags & FLAGS_SHARED, &key, FUTEX_WRITE);
1121 if (ret)
1122 return ret;
1123
1124 hb = futex_hash(&key);
1125 spin_lock(&hb->lock);
1126
1127 /*
1128 * Check waiters first. We do not trust user space values at
1129 * all and we at least want to know if user space fiddled
1130 * with the futex value instead of blindly unlocking.
1131 */
1132 top_waiter = futex_top_waiter(hb, &key);
1133 if (top_waiter) {
1134 struct futex_pi_state *pi_state = top_waiter->pi_state;
1135
1136 ret = -EINVAL;
1137 if (!pi_state)
1138 goto out_unlock;
1139
1140 /*
1141 * If current does not own the pi_state then the futex is
1142 * inconsistent and user space fiddled with the futex value.
1143 */
1144 if (pi_state->owner != current)
1145 goto out_unlock;
1146
1147 get_pi_state(pi_state);
1148 /*
1149 * By taking wait_lock while still holding hb->lock, we ensure
1150 * there is no point where we hold neither; and therefore
1151 * wake_futex_p() must observe a state consistent with what we
1152 * observed.
1153 *
1154 * In particular; this forces __rt_mutex_start_proxy() to
1155 * complete such that we're guaranteed to observe the
1156 * rt_waiter. Also see the WARN in wake_futex_pi().
1157 */
1158 raw_spin_lock_irq(&pi_state->pi_mutex.wait_lock);
1159 spin_unlock(&hb->lock);
1160
1161 /* drops pi_state->pi_mutex.wait_lock */
1162 ret = wake_futex_pi(uaddr, uval, pi_state);
1163
1164 put_pi_state(pi_state);
1165
1166 /*
1167 * Success, we're done! No tricky corner cases.
1168 */
1169 if (!ret)
1170 return ret;
1171 /*
1172 * The atomic access to the futex value generated a
1173 * pagefault, so retry the user-access and the wakeup:
1174 */
1175 if (ret == -EFAULT)
1176 goto pi_faulted;
1177 /*
1178 * A unconditional UNLOCK_PI op raced against a waiter
1179 * setting the FUTEX_WAITERS bit. Try again.
1180 */
1181 if (ret == -EAGAIN)
1182 goto pi_retry;
1183 /*
1184 * wake_futex_pi has detected invalid state. Tell user
1185 * space.
1186 */
1187 return ret;
1188 }
1189
1190 /*
1191 * We have no kernel internal state, i.e. no waiters in the
1192 * kernel. Waiters which are about to queue themselves are stuck
1193 * on hb->lock. So we can safely ignore them. We do neither
1194 * preserve the WAITERS bit not the OWNER_DIED one. We are the
1195 * owner.
1196 */
1197 if ((ret = futex_cmpxchg_value_locked(&curval, uaddr, uval, 0))) {
1198 spin_unlock(&hb->lock);
1199 switch (ret) {
1200 case -EFAULT:
1201 goto pi_faulted;
1202
1203 case -EAGAIN:
1204 goto pi_retry;
1205
1206 default:
1207 WARN_ON_ONCE(1);
1208 return ret;
1209 }
1210 }
1211
1212 /*
1213 * If uval has changed, let user space handle it.
1214 */
1215 ret = (curval == uval) ? 0 : -EAGAIN;
1216
1217out_unlock:
1218 spin_unlock(&hb->lock);
1219 return ret;
1220
1221pi_retry:
1222 cond_resched();
1223 goto retry;
1224
1225pi_faulted:
1226
1227 ret = fault_in_user_writeable(uaddr);
1228 if (!ret)
1229 goto retry;
1230
1231 return ret;
1232}
1233