core.c 32 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174
  1. // SPDX-License-Identifier: GPL-2.0-or-later
  2. /*
  3. * Fast Userspace Mutexes (which I call "Futexes!").
  4. * (C) Rusty Russell, IBM 2002
  5. *
  6. * Generalized futexes, futex requeueing, misc fixes by Ingo Molnar
  7. * (C) Copyright 2003 Red Hat Inc, All Rights Reserved
  8. *
  9. * Removed page pinning, fix privately mapped COW pages and other cleanups
  10. * (C) Copyright 2003, 2004 Jamie Lokier
  11. *
  12. * Robust futex support started by Ingo Molnar
  13. * (C) Copyright 2006 Red Hat Inc, All Rights Reserved
  14. * Thanks to Thomas Gleixner for suggestions, analysis and fixes.
  15. *
  16. * PI-futex support started by Ingo Molnar and Thomas Gleixner
  17. * Copyright (C) 2006 Red Hat, Inc., Ingo Molnar <mingo@redhat.com>
  18. * Copyright (C) 2006 Timesys Corp., Thomas Gleixner <tglx@timesys.com>
  19. *
  20. * PRIVATE futexes by Eric Dumazet
  21. * Copyright (C) 2007 Eric Dumazet <dada1@cosmosbay.com>
  22. *
  23. * Requeue-PI support by Darren Hart <dvhltc@us.ibm.com>
  24. * Copyright (C) IBM Corporation, 2009
  25. * Thanks to Thomas Gleixner for conceptual design and careful reviews.
  26. *
  27. * Thanks to Ben LaHaise for yelling "hashed waitqueues" loudly
  28. * enough at me, Linus for the original (flawed) idea, Matthew
  29. * Kirkwood for proof-of-concept implementation.
  30. *
  31. * "The futexes are also cursed."
  32. * "But they come in a choice of three flavours!"
  33. */
  34. #include <linux/compat.h>
  35. #include <linux/jhash.h>
  36. #include <linux/pagemap.h>
  37. #include <linux/debugfs.h>
  38. #include <linux/plist.h>
  39. #include <linux/memblock.h>
  40. #include <linux/fault-inject.h>
  41. #include <linux/slab.h>
  42. #include "futex.h"
  43. #include "../locking/rtmutex_common.h"
  44. /*
  45. * The base of the bucket array and its size are always used together
  46. * (after initialization only in futex_hash()), so ensure that they
  47. * reside in the same cacheline.
  48. */
  49. static struct {
  50. struct futex_hash_bucket *queues;
  51. unsigned long hashsize;
  52. } __futex_data __read_mostly __aligned(2*sizeof(long));
  53. #define futex_queues (__futex_data.queues)
  54. #define futex_hashsize (__futex_data.hashsize)
  55. /*
  56. * Fault injections for futexes.
  57. */
  58. #ifdef CONFIG_FAIL_FUTEX
  59. static struct {
  60. struct fault_attr attr;
  61. bool ignore_private;
  62. } fail_futex = {
  63. .attr = FAULT_ATTR_INITIALIZER,
  64. .ignore_private = false,
  65. };
  66. static int __init setup_fail_futex(char *str)
  67. {
  68. return setup_fault_attr(&fail_futex.attr, str);
  69. }
  70. __setup("fail_futex=", setup_fail_futex);
  71. bool should_fail_futex(bool fshared)
  72. {
  73. if (fail_futex.ignore_private && !fshared)
  74. return false;
  75. return should_fail(&fail_futex.attr, 1);
  76. }
  77. #ifdef CONFIG_FAULT_INJECTION_DEBUG_FS
  78. static int __init fail_futex_debugfs(void)
  79. {
  80. umode_t mode = S_IFREG | S_IRUSR | S_IWUSR;
  81. struct dentry *dir;
  82. dir = fault_create_debugfs_attr("fail_futex", NULL,
  83. &fail_futex.attr);
  84. if (IS_ERR(dir))
  85. return PTR_ERR(dir);
  86. debugfs_create_bool("ignore-private", mode, dir,
  87. &fail_futex.ignore_private);
  88. return 0;
  89. }
  90. late_initcall(fail_futex_debugfs);
  91. #endif /* CONFIG_FAULT_INJECTION_DEBUG_FS */
  92. #endif /* CONFIG_FAIL_FUTEX */
  93. /**
  94. * futex_hash - Return the hash bucket in the global hash
  95. * @key: Pointer to the futex key for which the hash is calculated
  96. *
  97. * We hash on the keys returned from get_futex_key (see below) and return the
  98. * corresponding hash bucket in the global hash.
  99. */
  100. struct futex_hash_bucket *futex_hash(union futex_key *key)
  101. {
  102. u32 hash = jhash2((u32 *)key, offsetof(typeof(*key), both.offset) / 4,
  103. key->both.offset);
  104. return &futex_queues[hash & (futex_hashsize - 1)];
  105. }
  106. /**
  107. * futex_setup_timer - set up the sleeping hrtimer.
  108. * @time: ptr to the given timeout value
  109. * @timeout: the hrtimer_sleeper structure to be set up
  110. * @flags: futex flags
  111. * @range_ns: optional range in ns
  112. *
  113. * Return: Initialized hrtimer_sleeper structure or NULL if no timeout
  114. * value given
  115. */
  116. struct hrtimer_sleeper *
  117. futex_setup_timer(ktime_t *time, struct hrtimer_sleeper *timeout,
  118. int flags, u64 range_ns)
  119. {
  120. if (!time)
  121. return NULL;
  122. hrtimer_init_sleeper_on_stack(timeout, (flags & FLAGS_CLOCKRT) ?
  123. CLOCK_REALTIME : CLOCK_MONOTONIC,
  124. HRTIMER_MODE_ABS);
  125. /*
  126. * If range_ns is 0, calling hrtimer_set_expires_range_ns() is
  127. * effectively the same as calling hrtimer_set_expires().
  128. */
  129. hrtimer_set_expires_range_ns(&timeout->timer, *time, range_ns);
  130. return timeout;
  131. }
  132. /*
  133. * Generate a machine wide unique identifier for this inode.
  134. *
  135. * This relies on u64 not wrapping in the life-time of the machine; which with
  136. * 1ns resolution means almost 585 years.
  137. *
  138. * This further relies on the fact that a well formed program will not unmap
  139. * the file while it has a (shared) futex waiting on it. This mapping will have
  140. * a file reference which pins the mount and inode.
  141. *
  142. * If for some reason an inode gets evicted and read back in again, it will get
  143. * a new sequence number and will _NOT_ match, even though it is the exact same
  144. * file.
  145. *
  146. * It is important that futex_match() will never have a false-positive, esp.
  147. * for PI futexes that can mess up the state. The above argues that false-negatives
  148. * are only possible for malformed programs.
  149. */
  150. static u64 get_inode_sequence_number(struct inode *inode)
  151. {
  152. static atomic64_t i_seq;
  153. u64 old;
  154. /* Does the inode already have a sequence number? */
  155. old = atomic64_read(&inode->i_sequence);
  156. if (likely(old))
  157. return old;
  158. for (;;) {
  159. u64 new = atomic64_add_return(1, &i_seq);
  160. if (WARN_ON_ONCE(!new))
  161. continue;
  162. old = atomic64_cmpxchg_relaxed(&inode->i_sequence, 0, new);
  163. if (old)
  164. return old;
  165. return new;
  166. }
  167. }
  168. /**
  169. * get_futex_key() - Get parameters which are the keys for a futex
  170. * @uaddr: virtual address of the futex
  171. * @flags: FLAGS_*
  172. * @key: address where result is stored.
  173. * @rw: mapping needs to be read/write (values: FUTEX_READ,
  174. * FUTEX_WRITE)
  175. *
  176. * Return: a negative error code or 0
  177. *
  178. * The key words are stored in @key on success.
  179. *
  180. * For shared mappings (when @fshared), the key is:
  181. *
  182. * ( inode->i_sequence, page->index, offset_within_page )
  183. *
  184. * [ also see get_inode_sequence_number() ]
  185. *
  186. * For private mappings (or when !@fshared), the key is:
  187. *
  188. * ( current->mm, address, 0 )
  189. *
  190. * This allows (cross process, where applicable) identification of the futex
  191. * without keeping the page pinned for the duration of the FUTEX_WAIT.
  192. *
  193. * lock_page() might sleep, the caller should not hold a spinlock.
  194. */
  195. int get_futex_key(u32 __user *uaddr, unsigned int flags, union futex_key *key,
  196. enum futex_access rw)
  197. {
  198. unsigned long address = (unsigned long)uaddr;
  199. struct mm_struct *mm = current->mm;
  200. struct page *page;
  201. struct folio *folio;
  202. struct address_space *mapping;
  203. int err, ro = 0;
  204. bool fshared;
  205. fshared = flags & FLAGS_SHARED;
  206. /*
  207. * The futex address must be "naturally" aligned.
  208. */
  209. key->both.offset = address % PAGE_SIZE;
  210. if (unlikely((address % sizeof(u32)) != 0))
  211. return -EINVAL;
  212. address -= key->both.offset;
  213. if (unlikely(!access_ok(uaddr, sizeof(u32))))
  214. return -EFAULT;
  215. if (unlikely(should_fail_futex(fshared)))
  216. return -EFAULT;
  217. /*
  218. * PROCESS_PRIVATE futexes are fast.
  219. * As the mm cannot disappear under us and the 'key' only needs
  220. * virtual address, we dont even have to find the underlying vma.
  221. * Note : We do have to check 'uaddr' is a valid user address,
  222. * but access_ok() should be faster than find_vma()
  223. */
  224. if (!fshared) {
  225. /*
  226. * On no-MMU, shared futexes are treated as private, therefore
  227. * we must not include the current process in the key. Since
  228. * there is only one address space, the address is a unique key
  229. * on its own.
  230. */
  231. if (IS_ENABLED(CONFIG_MMU))
  232. key->private.mm = mm;
  233. else
  234. key->private.mm = NULL;
  235. key->private.address = address;
  236. return 0;
  237. }
  238. again:
  239. /* Ignore any VERIFY_READ mapping (futex common case) */
  240. if (unlikely(should_fail_futex(true)))
  241. return -EFAULT;
  242. err = get_user_pages_fast(address, 1, FOLL_WRITE, &page);
  243. /*
  244. * If write access is not required (eg. FUTEX_WAIT), try
  245. * and get read-only access.
  246. */
  247. if (err == -EFAULT && rw == FUTEX_READ) {
  248. err = get_user_pages_fast(address, 1, 0, &page);
  249. ro = 1;
  250. }
  251. if (err < 0)
  252. return err;
  253. else
  254. err = 0;
  255. /*
  256. * The treatment of mapping from this point on is critical. The folio
  257. * lock protects many things but in this context the folio lock
  258. * stabilizes mapping, prevents inode freeing in the shared
  259. * file-backed region case and guards against movement to swap cache.
  260. *
  261. * Strictly speaking the folio lock is not needed in all cases being
  262. * considered here and folio lock forces unnecessarily serialization.
  263. * From this point on, mapping will be re-verified if necessary and
  264. * folio lock will be acquired only if it is unavoidable
  265. *
  266. * Mapping checks require the folio so it is looked up now. For
  267. * anonymous pages, it does not matter if the folio is split
  268. * in the future as the key is based on the address. For
  269. * filesystem-backed pages, the precise page is required as the
  270. * index of the page determines the key.
  271. */
  272. folio = page_folio(page);
  273. mapping = READ_ONCE(folio->mapping);
  274. /*
  275. * If folio->mapping is NULL, then it cannot be an anonymous
  276. * page; but it might be the ZERO_PAGE or in the gate area or
  277. * in a special mapping (all cases which we are happy to fail);
  278. * or it may have been a good file page when get_user_pages_fast
  279. * found it, but truncated or holepunched or subjected to
  280. * invalidate_complete_page2 before we got the folio lock (also
  281. * cases which we are happy to fail). And we hold a reference,
  282. * so refcount care in invalidate_inode_page's remove_mapping
  283. * prevents drop_caches from setting mapping to NULL beneath us.
  284. *
  285. * The case we do have to guard against is when memory pressure made
  286. * shmem_writepage move it from filecache to swapcache beneath us:
  287. * an unlikely race, but we do need to retry for folio->mapping.
  288. */
  289. if (unlikely(!mapping)) {
  290. int shmem_swizzled;
  291. /*
  292. * Folio lock is required to identify which special case above
  293. * applies. If this is really a shmem page then the folio lock
  294. * will prevent unexpected transitions.
  295. */
  296. folio_lock(folio);
  297. shmem_swizzled = folio_test_swapcache(folio) || folio->mapping;
  298. folio_unlock(folio);
  299. folio_put(folio);
  300. if (shmem_swizzled)
  301. goto again;
  302. return -EFAULT;
  303. }
  304. /*
  305. * Private mappings are handled in a simple way.
  306. *
  307. * If the futex key is stored in anonymous memory, then the associated
  308. * object is the mm which is implicitly pinned by the calling process.
  309. *
  310. * NOTE: When userspace waits on a MAP_SHARED mapping, even if
  311. * it's a read-only handle, it's expected that futexes attach to
  312. * the object not the particular process.
  313. */
  314. if (folio_test_anon(folio)) {
  315. /*
  316. * A RO anonymous page will never change and thus doesn't make
  317. * sense for futex operations.
  318. */
  319. if (unlikely(should_fail_futex(true)) || ro) {
  320. err = -EFAULT;
  321. goto out;
  322. }
  323. key->both.offset |= FUT_OFF_MMSHARED; /* ref taken on mm */
  324. key->private.mm = mm;
  325. key->private.address = address;
  326. } else {
  327. struct inode *inode;
  328. /*
  329. * The associated futex object in this case is the inode and
  330. * the folio->mapping must be traversed. Ordinarily this should
  331. * be stabilised under folio lock but it's not strictly
  332. * necessary in this case as we just want to pin the inode, not
  333. * update i_pages or anything like that.
  334. *
  335. * The RCU read lock is taken as the inode is finally freed
  336. * under RCU. If the mapping still matches expectations then the
  337. * mapping->host can be safely accessed as being a valid inode.
  338. */
  339. rcu_read_lock();
  340. if (READ_ONCE(folio->mapping) != mapping) {
  341. rcu_read_unlock();
  342. folio_put(folio);
  343. goto again;
  344. }
  345. inode = READ_ONCE(mapping->host);
  346. if (!inode) {
  347. rcu_read_unlock();
  348. folio_put(folio);
  349. goto again;
  350. }
  351. key->both.offset |= FUT_OFF_INODE; /* inode-based key */
  352. key->shared.i_seq = get_inode_sequence_number(inode);
  353. key->shared.pgoff = folio->index + folio_page_idx(folio, page);
  354. rcu_read_unlock();
  355. }
  356. out:
  357. folio_put(folio);
  358. return err;
  359. }
  360. /**
  361. * fault_in_user_writeable() - Fault in user address and verify RW access
  362. * @uaddr: pointer to faulting user space address
  363. *
  364. * Slow path to fixup the fault we just took in the atomic write
  365. * access to @uaddr.
  366. *
  367. * We have no generic implementation of a non-destructive write to the
  368. * user address. We know that we faulted in the atomic pagefault
  369. * disabled section so we can as well avoid the #PF overhead by
  370. * calling get_user_pages() right away.
  371. */
  372. int fault_in_user_writeable(u32 __user *uaddr)
  373. {
  374. struct mm_struct *mm = current->mm;
  375. int ret;
  376. mmap_read_lock(mm);
  377. ret = fixup_user_fault(mm, (unsigned long)uaddr,
  378. FAULT_FLAG_WRITE, NULL);
  379. mmap_read_unlock(mm);
  380. return ret < 0 ? ret : 0;
  381. }
  382. /**
  383. * futex_top_waiter() - Return the highest priority waiter on a futex
  384. * @hb: the hash bucket the futex_q's reside in
  385. * @key: the futex key (to distinguish it from other futex futex_q's)
  386. *
  387. * Must be called with the hb lock held.
  388. */
  389. struct futex_q *futex_top_waiter(struct futex_hash_bucket *hb, union futex_key *key)
  390. {
  391. struct futex_q *this;
  392. plist_for_each_entry(this, &hb->chain, list) {
  393. if (futex_match(&this->key, key))
  394. return this;
  395. }
  396. return NULL;
  397. }
  398. int futex_cmpxchg_value_locked(u32 *curval, u32 __user *uaddr, u32 uval, u32 newval)
  399. {
  400. int ret;
  401. pagefault_disable();
  402. ret = futex_atomic_cmpxchg_inatomic(curval, uaddr, uval, newval);
  403. pagefault_enable();
  404. return ret;
  405. }
  406. int futex_get_value_locked(u32 *dest, u32 __user *from)
  407. {
  408. int ret;
  409. pagefault_disable();
  410. ret = __get_user(*dest, from);
  411. pagefault_enable();
  412. return ret ? -EFAULT : 0;
  413. }
  414. /**
  415. * wait_for_owner_exiting - Block until the owner has exited
  416. * @ret: owner's current futex lock status
  417. * @exiting: Pointer to the exiting task
  418. *
  419. * Caller must hold a refcount on @exiting.
  420. */
  421. void wait_for_owner_exiting(int ret, struct task_struct *exiting)
  422. {
  423. if (ret != -EBUSY) {
  424. WARN_ON_ONCE(exiting);
  425. return;
  426. }
  427. if (WARN_ON_ONCE(ret == -EBUSY && !exiting))
  428. return;
  429. mutex_lock(&exiting->futex_exit_mutex);
  430. /*
  431. * No point in doing state checking here. If the waiter got here
  432. * while the task was in exec()->exec_futex_release() then it can
  433. * have any FUTEX_STATE_* value when the waiter has acquired the
  434. * mutex. OK, if running, EXITING or DEAD if it reached exit()
  435. * already. Highly unlikely and not a problem. Just one more round
  436. * through the futex maze.
  437. */
  438. mutex_unlock(&exiting->futex_exit_mutex);
  439. put_task_struct(exiting);
  440. }
  441. /**
  442. * __futex_unqueue() - Remove the futex_q from its futex_hash_bucket
  443. * @q: The futex_q to unqueue
  444. *
  445. * The q->lock_ptr must not be NULL and must be held by the caller.
  446. */
  447. void __futex_unqueue(struct futex_q *q)
  448. {
  449. struct futex_hash_bucket *hb;
  450. if (WARN_ON_SMP(!q->lock_ptr) || WARN_ON(plist_node_empty(&q->list)))
  451. return;
  452. lockdep_assert_held(q->lock_ptr);
  453. hb = container_of(q->lock_ptr, struct futex_hash_bucket, lock);
  454. plist_del(&q->list, &hb->chain);
  455. futex_hb_waiters_dec(hb);
  456. }
  457. /* The key must be already stored in q->key. */
  458. struct futex_hash_bucket *futex_q_lock(struct futex_q *q)
  459. __acquires(&hb->lock)
  460. {
  461. struct futex_hash_bucket *hb;
  462. hb = futex_hash(&q->key);
  463. /*
  464. * Increment the counter before taking the lock so that
  465. * a potential waker won't miss a to-be-slept task that is
  466. * waiting for the spinlock. This is safe as all futex_q_lock()
  467. * users end up calling futex_queue(). Similarly, for housekeeping,
  468. * decrement the counter at futex_q_unlock() when some error has
  469. * occurred and we don't end up adding the task to the list.
  470. */
  471. futex_hb_waiters_inc(hb); /* implies smp_mb(); (A) */
  472. q->lock_ptr = &hb->lock;
  473. spin_lock(&hb->lock);
  474. return hb;
  475. }
  476. void futex_q_unlock(struct futex_hash_bucket *hb)
  477. __releases(&hb->lock)
  478. {
  479. spin_unlock(&hb->lock);
  480. futex_hb_waiters_dec(hb);
  481. }
  482. void __futex_queue(struct futex_q *q, struct futex_hash_bucket *hb)
  483. {
  484. int prio;
  485. /*
  486. * The priority used to register this element is
  487. * - either the real thread-priority for the real-time threads
  488. * (i.e. threads with a priority lower than MAX_RT_PRIO)
  489. * - or MAX_RT_PRIO for non-RT threads.
  490. * Thus, all RT-threads are woken first in priority order, and
  491. * the others are woken last, in FIFO order.
  492. */
  493. prio = min(current->normal_prio, MAX_RT_PRIO);
  494. plist_node_init(&q->list, prio);
  495. plist_add(&q->list, &hb->chain);
  496. q->task = current;
  497. }
  498. /**
  499. * futex_unqueue() - Remove the futex_q from its futex_hash_bucket
  500. * @q: The futex_q to unqueue
  501. *
  502. * The q->lock_ptr must not be held by the caller. A call to futex_unqueue() must
  503. * be paired with exactly one earlier call to futex_queue().
  504. *
  505. * Return:
  506. * - 1 - if the futex_q was still queued (and we removed unqueued it);
  507. * - 0 - if the futex_q was already removed by the waking thread
  508. */
  509. int futex_unqueue(struct futex_q *q)
  510. {
  511. spinlock_t *lock_ptr;
  512. int ret = 0;
  513. /* In the common case we don't take the spinlock, which is nice. */
  514. retry:
  515. /*
  516. * q->lock_ptr can change between this read and the following spin_lock.
  517. * Use READ_ONCE to forbid the compiler from reloading q->lock_ptr and
  518. * optimizing lock_ptr out of the logic below.
  519. */
  520. lock_ptr = READ_ONCE(q->lock_ptr);
  521. if (lock_ptr != NULL) {
  522. spin_lock(lock_ptr);
  523. /*
  524. * q->lock_ptr can change between reading it and
  525. * spin_lock(), causing us to take the wrong lock. This
  526. * corrects the race condition.
  527. *
  528. * Reasoning goes like this: if we have the wrong lock,
  529. * q->lock_ptr must have changed (maybe several times)
  530. * between reading it and the spin_lock(). It can
  531. * change again after the spin_lock() but only if it was
  532. * already changed before the spin_lock(). It cannot,
  533. * however, change back to the original value. Therefore
  534. * we can detect whether we acquired the correct lock.
  535. */
  536. if (unlikely(lock_ptr != q->lock_ptr)) {
  537. spin_unlock(lock_ptr);
  538. goto retry;
  539. }
  540. __futex_unqueue(q);
  541. BUG_ON(q->pi_state);
  542. spin_unlock(lock_ptr);
  543. ret = 1;
  544. }
  545. return ret;
  546. }
  547. /*
  548. * PI futexes can not be requeued and must remove themselves from the hash
  549. * bucket. The hash bucket lock (i.e. lock_ptr) is held.
  550. */
  551. void futex_unqueue_pi(struct futex_q *q)
  552. {
  553. /*
  554. * If the lock was not acquired (due to timeout or signal) then the
  555. * rt_waiter is removed before futex_q is. If this is observed by
  556. * an unlocker after dropping the rtmutex wait lock and before
  557. * acquiring the hash bucket lock, then the unlocker dequeues the
  558. * futex_q from the hash bucket list to guarantee consistent state
  559. * vs. userspace. Therefore the dequeue here must be conditional.
  560. */
  561. if (!plist_node_empty(&q->list))
  562. __futex_unqueue(q);
  563. BUG_ON(!q->pi_state);
  564. put_pi_state(q->pi_state);
  565. q->pi_state = NULL;
  566. }
  567. /* Constants for the pending_op argument of handle_futex_death */
  568. #define HANDLE_DEATH_PENDING true
  569. #define HANDLE_DEATH_LIST false
  570. /*
  571. * Process a futex-list entry, check whether it's owned by the
  572. * dying task, and do notification if so:
  573. */
  574. static int handle_futex_death(u32 __user *uaddr, struct task_struct *curr,
  575. bool pi, bool pending_op)
  576. {
  577. u32 uval, nval, mval;
  578. pid_t owner;
  579. int err;
  580. /* Futex address must be 32bit aligned */
  581. if ((((unsigned long)uaddr) % sizeof(*uaddr)) != 0)
  582. return -1;
  583. retry:
  584. if (get_user(uval, uaddr))
  585. return -1;
  586. /*
  587. * Special case for regular (non PI) futexes. The unlock path in
  588. * user space has two race scenarios:
  589. *
  590. * 1. The unlock path releases the user space futex value and
  591. * before it can execute the futex() syscall to wake up
  592. * waiters it is killed.
  593. *
  594. * 2. A woken up waiter is killed before it can acquire the
  595. * futex in user space.
  596. *
  597. * In the second case, the wake up notification could be generated
  598. * by the unlock path in user space after setting the futex value
  599. * to zero or by the kernel after setting the OWNER_DIED bit below.
  600. *
  601. * In both cases the TID validation below prevents a wakeup of
  602. * potential waiters which can cause these waiters to block
  603. * forever.
  604. *
  605. * In both cases the following conditions are met:
  606. *
  607. * 1) task->robust_list->list_op_pending != NULL
  608. * @pending_op == true
  609. * 2) The owner part of user space futex value == 0
  610. * 3) Regular futex: @pi == false
  611. *
  612. * If these conditions are met, it is safe to attempt waking up a
  613. * potential waiter without touching the user space futex value and
  614. * trying to set the OWNER_DIED bit. If the futex value is zero,
  615. * the rest of the user space mutex state is consistent, so a woken
  616. * waiter will just take over the uncontended futex. Setting the
  617. * OWNER_DIED bit would create inconsistent state and malfunction
  618. * of the user space owner died handling. Otherwise, the OWNER_DIED
  619. * bit is already set, and the woken waiter is expected to deal with
  620. * this.
  621. */
  622. owner = uval & FUTEX_TID_MASK;
  623. if (pending_op && !pi && !owner) {
  624. futex_wake(uaddr, FLAGS_SIZE_32 | FLAGS_SHARED, 1,
  625. FUTEX_BITSET_MATCH_ANY);
  626. return 0;
  627. }
  628. if (owner != task_pid_vnr(curr))
  629. return 0;
  630. /*
  631. * Ok, this dying thread is truly holding a futex
  632. * of interest. Set the OWNER_DIED bit atomically
  633. * via cmpxchg, and if the value had FUTEX_WAITERS
  634. * set, wake up a waiter (if any). (We have to do a
  635. * futex_wake() even if OWNER_DIED is already set -
  636. * to handle the rare but possible case of recursive
  637. * thread-death.) The rest of the cleanup is done in
  638. * userspace.
  639. */
  640. mval = (uval & FUTEX_WAITERS) | FUTEX_OWNER_DIED;
  641. /*
  642. * We are not holding a lock here, but we want to have
  643. * the pagefault_disable/enable() protection because
  644. * we want to handle the fault gracefully. If the
  645. * access fails we try to fault in the futex with R/W
  646. * verification via get_user_pages. get_user() above
  647. * does not guarantee R/W access. If that fails we
  648. * give up and leave the futex locked.
  649. */
  650. if ((err = futex_cmpxchg_value_locked(&nval, uaddr, uval, mval))) {
  651. switch (err) {
  652. case -EFAULT:
  653. if (fault_in_user_writeable(uaddr))
  654. return -1;
  655. goto retry;
  656. case -EAGAIN:
  657. cond_resched();
  658. goto retry;
  659. default:
  660. WARN_ON_ONCE(1);
  661. return err;
  662. }
  663. }
  664. if (nval != uval)
  665. goto retry;
  666. /*
  667. * Wake robust non-PI futexes here. The wakeup of
  668. * PI futexes happens in exit_pi_state():
  669. */
  670. if (!pi && (uval & FUTEX_WAITERS)) {
  671. futex_wake(uaddr, FLAGS_SIZE_32 | FLAGS_SHARED, 1,
  672. FUTEX_BITSET_MATCH_ANY);
  673. }
  674. return 0;
  675. }
  676. /*
  677. * Fetch a robust-list pointer. Bit 0 signals PI futexes:
  678. */
  679. static inline int fetch_robust_entry(struct robust_list __user **entry,
  680. struct robust_list __user * __user *head,
  681. unsigned int *pi)
  682. {
  683. unsigned long uentry;
  684. if (get_user(uentry, (unsigned long __user *)head))
  685. return -EFAULT;
  686. *entry = (void __user *)(uentry & ~1UL);
  687. *pi = uentry & 1;
  688. return 0;
  689. }
  690. /*
  691. * Walk curr->robust_list (very carefully, it's a userspace list!)
  692. * and mark any locks found there dead, and notify any waiters.
  693. *
  694. * We silently return on any sign of list-walking problem.
  695. */
  696. static void exit_robust_list(struct task_struct *curr)
  697. {
  698. struct robust_list_head __user *head = curr->robust_list;
  699. struct robust_list __user *entry, *next_entry, *pending;
  700. unsigned int limit = ROBUST_LIST_LIMIT, pi, pip;
  701. unsigned int next_pi;
  702. unsigned long futex_offset;
  703. int rc;
  704. /*
  705. * Fetch the list head (which was registered earlier, via
  706. * sys_set_robust_list()):
  707. */
  708. if (fetch_robust_entry(&entry, &head->list.next, &pi))
  709. return;
  710. /*
  711. * Fetch the relative futex offset:
  712. */
  713. if (get_user(futex_offset, &head->futex_offset))
  714. return;
  715. /*
  716. * Fetch any possibly pending lock-add first, and handle it
  717. * if it exists:
  718. */
  719. if (fetch_robust_entry(&pending, &head->list_op_pending, &pip))
  720. return;
  721. next_entry = NULL; /* avoid warning with gcc */
  722. while (entry != &head->list) {
  723. /*
  724. * Fetch the next entry in the list before calling
  725. * handle_futex_death:
  726. */
  727. rc = fetch_robust_entry(&next_entry, &entry->next, &next_pi);
  728. /*
  729. * A pending lock might already be on the list, so
  730. * don't process it twice:
  731. */
  732. if (entry != pending) {
  733. if (handle_futex_death((void __user *)entry + futex_offset,
  734. curr, pi, HANDLE_DEATH_LIST))
  735. return;
  736. }
  737. if (rc)
  738. return;
  739. entry = next_entry;
  740. pi = next_pi;
  741. /*
  742. * Avoid excessively long or circular lists:
  743. */
  744. if (!--limit)
  745. break;
  746. cond_resched();
  747. }
  748. if (pending) {
  749. handle_futex_death((void __user *)pending + futex_offset,
  750. curr, pip, HANDLE_DEATH_PENDING);
  751. }
  752. }
  753. #ifdef CONFIG_COMPAT
  754. static void __user *futex_uaddr(struct robust_list __user *entry,
  755. compat_long_t futex_offset)
  756. {
  757. compat_uptr_t base = ptr_to_compat(entry);
  758. void __user *uaddr = compat_ptr(base + futex_offset);
  759. return uaddr;
  760. }
  761. /*
  762. * Fetch a robust-list pointer. Bit 0 signals PI futexes:
  763. */
  764. static inline int
  765. compat_fetch_robust_entry(compat_uptr_t *uentry, struct robust_list __user **entry,
  766. compat_uptr_t __user *head, unsigned int *pi)
  767. {
  768. if (get_user(*uentry, head))
  769. return -EFAULT;
  770. *entry = compat_ptr((*uentry) & ~1);
  771. *pi = (unsigned int)(*uentry) & 1;
  772. return 0;
  773. }
  774. /*
  775. * Walk curr->robust_list (very carefully, it's a userspace list!)
  776. * and mark any locks found there dead, and notify any waiters.
  777. *
  778. * We silently return on any sign of list-walking problem.
  779. */
  780. static void compat_exit_robust_list(struct task_struct *curr)
  781. {
  782. struct compat_robust_list_head __user *head = curr->compat_robust_list;
  783. struct robust_list __user *entry, *next_entry, *pending;
  784. unsigned int limit = ROBUST_LIST_LIMIT, pi, pip;
  785. unsigned int next_pi;
  786. compat_uptr_t uentry, next_uentry, upending;
  787. compat_long_t futex_offset;
  788. int rc;
  789. /*
  790. * Fetch the list head (which was registered earlier, via
  791. * sys_set_robust_list()):
  792. */
  793. if (compat_fetch_robust_entry(&uentry, &entry, &head->list.next, &pi))
  794. return;
  795. /*
  796. * Fetch the relative futex offset:
  797. */
  798. if (get_user(futex_offset, &head->futex_offset))
  799. return;
  800. /*
  801. * Fetch any possibly pending lock-add first, and handle it
  802. * if it exists:
  803. */
  804. if (compat_fetch_robust_entry(&upending, &pending,
  805. &head->list_op_pending, &pip))
  806. return;
  807. next_entry = NULL; /* avoid warning with gcc */
  808. while (entry != (struct robust_list __user *) &head->list) {
  809. /*
  810. * Fetch the next entry in the list before calling
  811. * handle_futex_death:
  812. */
  813. rc = compat_fetch_robust_entry(&next_uentry, &next_entry,
  814. (compat_uptr_t __user *)&entry->next, &next_pi);
  815. /*
  816. * A pending lock might already be on the list, so
  817. * dont process it twice:
  818. */
  819. if (entry != pending) {
  820. void __user *uaddr = futex_uaddr(entry, futex_offset);
  821. if (handle_futex_death(uaddr, curr, pi,
  822. HANDLE_DEATH_LIST))
  823. return;
  824. }
  825. if (rc)
  826. return;
  827. uentry = next_uentry;
  828. entry = next_entry;
  829. pi = next_pi;
  830. /*
  831. * Avoid excessively long or circular lists:
  832. */
  833. if (!--limit)
  834. break;
  835. cond_resched();
  836. }
  837. if (pending) {
  838. void __user *uaddr = futex_uaddr(pending, futex_offset);
  839. handle_futex_death(uaddr, curr, pip, HANDLE_DEATH_PENDING);
  840. }
  841. }
  842. #endif
  843. #ifdef CONFIG_FUTEX_PI
  844. /*
  845. * This task is holding PI mutexes at exit time => bad.
  846. * Kernel cleans up PI-state, but userspace is likely hosed.
  847. * (Robust-futex cleanup is separate and might save the day for userspace.)
  848. */
  849. static void exit_pi_state_list(struct task_struct *curr)
  850. {
  851. struct list_head *next, *head = &curr->pi_state_list;
  852. struct futex_pi_state *pi_state;
  853. struct futex_hash_bucket *hb;
  854. union futex_key key = FUTEX_KEY_INIT;
  855. /*
  856. * We are a ZOMBIE and nobody can enqueue itself on
  857. * pi_state_list anymore, but we have to be careful
  858. * versus waiters unqueueing themselves:
  859. */
  860. raw_spin_lock_irq(&curr->pi_lock);
  861. while (!list_empty(head)) {
  862. next = head->next;
  863. pi_state = list_entry(next, struct futex_pi_state, list);
  864. key = pi_state->key;
  865. hb = futex_hash(&key);
  866. /*
  867. * We can race against put_pi_state() removing itself from the
  868. * list (a waiter going away). put_pi_state() will first
  869. * decrement the reference count and then modify the list, so
  870. * its possible to see the list entry but fail this reference
  871. * acquire.
  872. *
  873. * In that case; drop the locks to let put_pi_state() make
  874. * progress and retry the loop.
  875. */
  876. if (!refcount_inc_not_zero(&pi_state->refcount)) {
  877. raw_spin_unlock_irq(&curr->pi_lock);
  878. cpu_relax();
  879. raw_spin_lock_irq(&curr->pi_lock);
  880. continue;
  881. }
  882. raw_spin_unlock_irq(&curr->pi_lock);
  883. spin_lock(&hb->lock);
  884. raw_spin_lock_irq(&pi_state->pi_mutex.wait_lock);
  885. raw_spin_lock(&curr->pi_lock);
  886. /*
  887. * We dropped the pi-lock, so re-check whether this
  888. * task still owns the PI-state:
  889. */
  890. if (head->next != next) {
  891. /* retain curr->pi_lock for the loop invariant */
  892. raw_spin_unlock(&pi_state->pi_mutex.wait_lock);
  893. spin_unlock(&hb->lock);
  894. put_pi_state(pi_state);
  895. continue;
  896. }
  897. WARN_ON(pi_state->owner != curr);
  898. WARN_ON(list_empty(&pi_state->list));
  899. list_del_init(&pi_state->list);
  900. pi_state->owner = NULL;
  901. raw_spin_unlock(&curr->pi_lock);
  902. raw_spin_unlock_irq(&pi_state->pi_mutex.wait_lock);
  903. spin_unlock(&hb->lock);
  904. rt_mutex_futex_unlock(&pi_state->pi_mutex);
  905. put_pi_state(pi_state);
  906. raw_spin_lock_irq(&curr->pi_lock);
  907. }
  908. raw_spin_unlock_irq(&curr->pi_lock);
  909. }
  910. #else
  911. static inline void exit_pi_state_list(struct task_struct *curr) { }
  912. #endif
  913. static void futex_cleanup(struct task_struct *tsk)
  914. {
  915. if (unlikely(tsk->robust_list)) {
  916. exit_robust_list(tsk);
  917. tsk->robust_list = NULL;
  918. }
  919. #ifdef CONFIG_COMPAT
  920. if (unlikely(tsk->compat_robust_list)) {
  921. compat_exit_robust_list(tsk);
  922. tsk->compat_robust_list = NULL;
  923. }
  924. #endif
  925. if (unlikely(!list_empty(&tsk->pi_state_list)))
  926. exit_pi_state_list(tsk);
  927. }
  928. /**
  929. * futex_exit_recursive - Set the tasks futex state to FUTEX_STATE_DEAD
  930. * @tsk: task to set the state on
  931. *
  932. * Set the futex exit state of the task lockless. The futex waiter code
  933. * observes that state when a task is exiting and loops until the task has
  934. * actually finished the futex cleanup. The worst case for this is that the
  935. * waiter runs through the wait loop until the state becomes visible.
  936. *
  937. * This is called from the recursive fault handling path in make_task_dead().
  938. *
  939. * This is best effort. Either the futex exit code has run already or
  940. * not. If the OWNER_DIED bit has been set on the futex then the waiter can
  941. * take it over. If not, the problem is pushed back to user space. If the
  942. * futex exit code did not run yet, then an already queued waiter might
  943. * block forever, but there is nothing which can be done about that.
  944. */
  945. void futex_exit_recursive(struct task_struct *tsk)
  946. {
  947. /* If the state is FUTEX_STATE_EXITING then futex_exit_mutex is held */
  948. if (tsk->futex_state == FUTEX_STATE_EXITING)
  949. mutex_unlock(&tsk->futex_exit_mutex);
  950. tsk->futex_state = FUTEX_STATE_DEAD;
  951. }
  952. static void futex_cleanup_begin(struct task_struct *tsk)
  953. {
  954. /*
  955. * Prevent various race issues against a concurrent incoming waiter
  956. * including live locks by forcing the waiter to block on
  957. * tsk->futex_exit_mutex when it observes FUTEX_STATE_EXITING in
  958. * attach_to_pi_owner().
  959. */
  960. mutex_lock(&tsk->futex_exit_mutex);
  961. /*
  962. * Switch the state to FUTEX_STATE_EXITING under tsk->pi_lock.
  963. *
  964. * This ensures that all subsequent checks of tsk->futex_state in
  965. * attach_to_pi_owner() must observe FUTEX_STATE_EXITING with
  966. * tsk->pi_lock held.
  967. *
  968. * It guarantees also that a pi_state which was queued right before
  969. * the state change under tsk->pi_lock by a concurrent waiter must
  970. * be observed in exit_pi_state_list().
  971. */
  972. raw_spin_lock_irq(&tsk->pi_lock);
  973. tsk->futex_state = FUTEX_STATE_EXITING;
  974. raw_spin_unlock_irq(&tsk->pi_lock);
  975. }
  976. static void futex_cleanup_end(struct task_struct *tsk, int state)
  977. {
  978. /*
  979. * Lockless store. The only side effect is that an observer might
  980. * take another loop until it becomes visible.
  981. */
  982. tsk->futex_state = state;
  983. /*
  984. * Drop the exit protection. This unblocks waiters which observed
  985. * FUTEX_STATE_EXITING to reevaluate the state.
  986. */
  987. mutex_unlock(&tsk->futex_exit_mutex);
  988. }
  989. void futex_exec_release(struct task_struct *tsk)
  990. {
  991. /*
  992. * The state handling is done for consistency, but in the case of
  993. * exec() there is no way to prevent further damage as the PID stays
  994. * the same. But for the unlikely and arguably buggy case that a
  995. * futex is held on exec(), this provides at least as much state
  996. * consistency protection which is possible.
  997. */
  998. futex_cleanup_begin(tsk);
  999. futex_cleanup(tsk);
  1000. /*
  1001. * Reset the state to FUTEX_STATE_OK. The task is alive and about
  1002. * exec a new binary.
  1003. */
  1004. futex_cleanup_end(tsk, FUTEX_STATE_OK);
  1005. }
  1006. void futex_exit_release(struct task_struct *tsk)
  1007. {
  1008. futex_cleanup_begin(tsk);
  1009. futex_cleanup(tsk);
  1010. futex_cleanup_end(tsk, FUTEX_STATE_DEAD);
  1011. }
  1012. static int __init futex_init(void)
  1013. {
  1014. unsigned int futex_shift;
  1015. unsigned long i;
  1016. #ifdef CONFIG_BASE_SMALL
  1017. futex_hashsize = 16;
  1018. #else
  1019. futex_hashsize = roundup_pow_of_two(256 * num_possible_cpus());
  1020. #endif
  1021. futex_queues = alloc_large_system_hash("futex", sizeof(*futex_queues),
  1022. futex_hashsize, 0, 0,
  1023. &futex_shift, NULL,
  1024. futex_hashsize, futex_hashsize);
  1025. futex_hashsize = 1UL << futex_shift;
  1026. for (i = 0; i < futex_hashsize; i++) {
  1027. atomic_set(&futex_queues[i].waiters, 0);
  1028. plist_head_init(&futex_queues[i].chain);
  1029. spin_lock_init(&futex_queues[i].lock);
  1030. }
  1031. return 0;
  1032. }
  1033. core_initcall(futex_init);