core.c 32 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175
  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. struct task_struct *task)
  484. {
  485. int prio;
  486. /*
  487. * The priority used to register this element is
  488. * - either the real thread-priority for the real-time threads
  489. * (i.e. threads with a priority lower than MAX_RT_PRIO)
  490. * - or MAX_RT_PRIO for non-RT threads.
  491. * Thus, all RT-threads are woken first in priority order, and
  492. * the others are woken last, in FIFO order.
  493. */
  494. prio = min(current->normal_prio, MAX_RT_PRIO);
  495. plist_node_init(&q->list, prio);
  496. plist_add(&q->list, &hb->chain);
  497. q->task = task;
  498. }
  499. /**
  500. * futex_unqueue() - Remove the futex_q from its futex_hash_bucket
  501. * @q: The futex_q to unqueue
  502. *
  503. * The q->lock_ptr must not be held by the caller. A call to futex_unqueue() must
  504. * be paired with exactly one earlier call to futex_queue().
  505. *
  506. * Return:
  507. * - 1 - if the futex_q was still queued (and we removed unqueued it);
  508. * - 0 - if the futex_q was already removed by the waking thread
  509. */
  510. int futex_unqueue(struct futex_q *q)
  511. {
  512. spinlock_t *lock_ptr;
  513. int ret = 0;
  514. /* In the common case we don't take the spinlock, which is nice. */
  515. retry:
  516. /*
  517. * q->lock_ptr can change between this read and the following spin_lock.
  518. * Use READ_ONCE to forbid the compiler from reloading q->lock_ptr and
  519. * optimizing lock_ptr out of the logic below.
  520. */
  521. lock_ptr = READ_ONCE(q->lock_ptr);
  522. if (lock_ptr != NULL) {
  523. spin_lock(lock_ptr);
  524. /*
  525. * q->lock_ptr can change between reading it and
  526. * spin_lock(), causing us to take the wrong lock. This
  527. * corrects the race condition.
  528. *
  529. * Reasoning goes like this: if we have the wrong lock,
  530. * q->lock_ptr must have changed (maybe several times)
  531. * between reading it and the spin_lock(). It can
  532. * change again after the spin_lock() but only if it was
  533. * already changed before the spin_lock(). It cannot,
  534. * however, change back to the original value. Therefore
  535. * we can detect whether we acquired the correct lock.
  536. */
  537. if (unlikely(lock_ptr != q->lock_ptr)) {
  538. spin_unlock(lock_ptr);
  539. goto retry;
  540. }
  541. __futex_unqueue(q);
  542. BUG_ON(q->pi_state);
  543. spin_unlock(lock_ptr);
  544. ret = 1;
  545. }
  546. return ret;
  547. }
  548. /*
  549. * PI futexes can not be requeued and must remove themselves from the hash
  550. * bucket. The hash bucket lock (i.e. lock_ptr) is held.
  551. */
  552. void futex_unqueue_pi(struct futex_q *q)
  553. {
  554. /*
  555. * If the lock was not acquired (due to timeout or signal) then the
  556. * rt_waiter is removed before futex_q is. If this is observed by
  557. * an unlocker after dropping the rtmutex wait lock and before
  558. * acquiring the hash bucket lock, then the unlocker dequeues the
  559. * futex_q from the hash bucket list to guarantee consistent state
  560. * vs. userspace. Therefore the dequeue here must be conditional.
  561. */
  562. if (!plist_node_empty(&q->list))
  563. __futex_unqueue(q);
  564. BUG_ON(!q->pi_state);
  565. put_pi_state(q->pi_state);
  566. q->pi_state = NULL;
  567. }
  568. /* Constants for the pending_op argument of handle_futex_death */
  569. #define HANDLE_DEATH_PENDING true
  570. #define HANDLE_DEATH_LIST false
  571. /*
  572. * Process a futex-list entry, check whether it's owned by the
  573. * dying task, and do notification if so:
  574. */
  575. static int handle_futex_death(u32 __user *uaddr, struct task_struct *curr,
  576. bool pi, bool pending_op)
  577. {
  578. u32 uval, nval, mval;
  579. pid_t owner;
  580. int err;
  581. /* Futex address must be 32bit aligned */
  582. if ((((unsigned long)uaddr) % sizeof(*uaddr)) != 0)
  583. return -1;
  584. retry:
  585. if (get_user(uval, uaddr))
  586. return -1;
  587. /*
  588. * Special case for regular (non PI) futexes. The unlock path in
  589. * user space has two race scenarios:
  590. *
  591. * 1. The unlock path releases the user space futex value and
  592. * before it can execute the futex() syscall to wake up
  593. * waiters it is killed.
  594. *
  595. * 2. A woken up waiter is killed before it can acquire the
  596. * futex in user space.
  597. *
  598. * In the second case, the wake up notification could be generated
  599. * by the unlock path in user space after setting the futex value
  600. * to zero or by the kernel after setting the OWNER_DIED bit below.
  601. *
  602. * In both cases the TID validation below prevents a wakeup of
  603. * potential waiters which can cause these waiters to block
  604. * forever.
  605. *
  606. * In both cases the following conditions are met:
  607. *
  608. * 1) task->robust_list->list_op_pending != NULL
  609. * @pending_op == true
  610. * 2) The owner part of user space futex value == 0
  611. * 3) Regular futex: @pi == false
  612. *
  613. * If these conditions are met, it is safe to attempt waking up a
  614. * potential waiter without touching the user space futex value and
  615. * trying to set the OWNER_DIED bit. If the futex value is zero,
  616. * the rest of the user space mutex state is consistent, so a woken
  617. * waiter will just take over the uncontended futex. Setting the
  618. * OWNER_DIED bit would create inconsistent state and malfunction
  619. * of the user space owner died handling. Otherwise, the OWNER_DIED
  620. * bit is already set, and the woken waiter is expected to deal with
  621. * this.
  622. */
  623. owner = uval & FUTEX_TID_MASK;
  624. if (pending_op && !pi && !owner) {
  625. futex_wake(uaddr, FLAGS_SIZE_32 | FLAGS_SHARED, 1,
  626. FUTEX_BITSET_MATCH_ANY);
  627. return 0;
  628. }
  629. if (owner != task_pid_vnr(curr))
  630. return 0;
  631. /*
  632. * Ok, this dying thread is truly holding a futex
  633. * of interest. Set the OWNER_DIED bit atomically
  634. * via cmpxchg, and if the value had FUTEX_WAITERS
  635. * set, wake up a waiter (if any). (We have to do a
  636. * futex_wake() even if OWNER_DIED is already set -
  637. * to handle the rare but possible case of recursive
  638. * thread-death.) The rest of the cleanup is done in
  639. * userspace.
  640. */
  641. mval = (uval & FUTEX_WAITERS) | FUTEX_OWNER_DIED;
  642. /*
  643. * We are not holding a lock here, but we want to have
  644. * the pagefault_disable/enable() protection because
  645. * we want to handle the fault gracefully. If the
  646. * access fails we try to fault in the futex with R/W
  647. * verification via get_user_pages. get_user() above
  648. * does not guarantee R/W access. If that fails we
  649. * give up and leave the futex locked.
  650. */
  651. if ((err = futex_cmpxchg_value_locked(&nval, uaddr, uval, mval))) {
  652. switch (err) {
  653. case -EFAULT:
  654. if (fault_in_user_writeable(uaddr))
  655. return -1;
  656. goto retry;
  657. case -EAGAIN:
  658. cond_resched();
  659. goto retry;
  660. default:
  661. WARN_ON_ONCE(1);
  662. return err;
  663. }
  664. }
  665. if (nval != uval)
  666. goto retry;
  667. /*
  668. * Wake robust non-PI futexes here. The wakeup of
  669. * PI futexes happens in exit_pi_state():
  670. */
  671. if (!pi && (uval & FUTEX_WAITERS)) {
  672. futex_wake(uaddr, FLAGS_SIZE_32 | FLAGS_SHARED, 1,
  673. FUTEX_BITSET_MATCH_ANY);
  674. }
  675. return 0;
  676. }
  677. /*
  678. * Fetch a robust-list pointer. Bit 0 signals PI futexes:
  679. */
  680. static inline int fetch_robust_entry(struct robust_list __user **entry,
  681. struct robust_list __user * __user *head,
  682. unsigned int *pi)
  683. {
  684. unsigned long uentry;
  685. if (get_user(uentry, (unsigned long __user *)head))
  686. return -EFAULT;
  687. *entry = (void __user *)(uentry & ~1UL);
  688. *pi = uentry & 1;
  689. return 0;
  690. }
  691. /*
  692. * Walk curr->robust_list (very carefully, it's a userspace list!)
  693. * and mark any locks found there dead, and notify any waiters.
  694. *
  695. * We silently return on any sign of list-walking problem.
  696. */
  697. static void exit_robust_list(struct task_struct *curr)
  698. {
  699. struct robust_list_head __user *head = curr->robust_list;
  700. struct robust_list __user *entry, *next_entry, *pending;
  701. unsigned int limit = ROBUST_LIST_LIMIT, pi, pip;
  702. unsigned int next_pi;
  703. unsigned long futex_offset;
  704. int rc;
  705. /*
  706. * Fetch the list head (which was registered earlier, via
  707. * sys_set_robust_list()):
  708. */
  709. if (fetch_robust_entry(&entry, &head->list.next, &pi))
  710. return;
  711. /*
  712. * Fetch the relative futex offset:
  713. */
  714. if (get_user(futex_offset, &head->futex_offset))
  715. return;
  716. /*
  717. * Fetch any possibly pending lock-add first, and handle it
  718. * if it exists:
  719. */
  720. if (fetch_robust_entry(&pending, &head->list_op_pending, &pip))
  721. return;
  722. next_entry = NULL; /* avoid warning with gcc */
  723. while (entry != &head->list) {
  724. /*
  725. * Fetch the next entry in the list before calling
  726. * handle_futex_death:
  727. */
  728. rc = fetch_robust_entry(&next_entry, &entry->next, &next_pi);
  729. /*
  730. * A pending lock might already be on the list, so
  731. * don't process it twice:
  732. */
  733. if (entry != pending) {
  734. if (handle_futex_death((void __user *)entry + futex_offset,
  735. curr, pi, HANDLE_DEATH_LIST))
  736. return;
  737. }
  738. if (rc)
  739. return;
  740. entry = next_entry;
  741. pi = next_pi;
  742. /*
  743. * Avoid excessively long or circular lists:
  744. */
  745. if (!--limit)
  746. break;
  747. cond_resched();
  748. }
  749. if (pending) {
  750. handle_futex_death((void __user *)pending + futex_offset,
  751. curr, pip, HANDLE_DEATH_PENDING);
  752. }
  753. }
  754. #ifdef CONFIG_COMPAT
  755. static void __user *futex_uaddr(struct robust_list __user *entry,
  756. compat_long_t futex_offset)
  757. {
  758. compat_uptr_t base = ptr_to_compat(entry);
  759. void __user *uaddr = compat_ptr(base + futex_offset);
  760. return uaddr;
  761. }
  762. /*
  763. * Fetch a robust-list pointer. Bit 0 signals PI futexes:
  764. */
  765. static inline int
  766. compat_fetch_robust_entry(compat_uptr_t *uentry, struct robust_list __user **entry,
  767. compat_uptr_t __user *head, unsigned int *pi)
  768. {
  769. if (get_user(*uentry, head))
  770. return -EFAULT;
  771. *entry = compat_ptr((*uentry) & ~1);
  772. *pi = (unsigned int)(*uentry) & 1;
  773. return 0;
  774. }
  775. /*
  776. * Walk curr->robust_list (very carefully, it's a userspace list!)
  777. * and mark any locks found there dead, and notify any waiters.
  778. *
  779. * We silently return on any sign of list-walking problem.
  780. */
  781. static void compat_exit_robust_list(struct task_struct *curr)
  782. {
  783. struct compat_robust_list_head __user *head = curr->compat_robust_list;
  784. struct robust_list __user *entry, *next_entry, *pending;
  785. unsigned int limit = ROBUST_LIST_LIMIT, pi, pip;
  786. unsigned int next_pi;
  787. compat_uptr_t uentry, next_uentry, upending;
  788. compat_long_t futex_offset;
  789. int rc;
  790. /*
  791. * Fetch the list head (which was registered earlier, via
  792. * sys_set_robust_list()):
  793. */
  794. if (compat_fetch_robust_entry(&uentry, &entry, &head->list.next, &pi))
  795. return;
  796. /*
  797. * Fetch the relative futex offset:
  798. */
  799. if (get_user(futex_offset, &head->futex_offset))
  800. return;
  801. /*
  802. * Fetch any possibly pending lock-add first, and handle it
  803. * if it exists:
  804. */
  805. if (compat_fetch_robust_entry(&upending, &pending,
  806. &head->list_op_pending, &pip))
  807. return;
  808. next_entry = NULL; /* avoid warning with gcc */
  809. while (entry != (struct robust_list __user *) &head->list) {
  810. /*
  811. * Fetch the next entry in the list before calling
  812. * handle_futex_death:
  813. */
  814. rc = compat_fetch_robust_entry(&next_uentry, &next_entry,
  815. (compat_uptr_t __user *)&entry->next, &next_pi);
  816. /*
  817. * A pending lock might already be on the list, so
  818. * dont process it twice:
  819. */
  820. if (entry != pending) {
  821. void __user *uaddr = futex_uaddr(entry, futex_offset);
  822. if (handle_futex_death(uaddr, curr, pi,
  823. HANDLE_DEATH_LIST))
  824. return;
  825. }
  826. if (rc)
  827. return;
  828. uentry = next_uentry;
  829. entry = next_entry;
  830. pi = next_pi;
  831. /*
  832. * Avoid excessively long or circular lists:
  833. */
  834. if (!--limit)
  835. break;
  836. cond_resched();
  837. }
  838. if (pending) {
  839. void __user *uaddr = futex_uaddr(pending, futex_offset);
  840. handle_futex_death(uaddr, curr, pip, HANDLE_DEATH_PENDING);
  841. }
  842. }
  843. #endif
  844. #ifdef CONFIG_FUTEX_PI
  845. /*
  846. * This task is holding PI mutexes at exit time => bad.
  847. * Kernel cleans up PI-state, but userspace is likely hosed.
  848. * (Robust-futex cleanup is separate and might save the day for userspace.)
  849. */
  850. static void exit_pi_state_list(struct task_struct *curr)
  851. {
  852. struct list_head *next, *head = &curr->pi_state_list;
  853. struct futex_pi_state *pi_state;
  854. struct futex_hash_bucket *hb;
  855. union futex_key key = FUTEX_KEY_INIT;
  856. /*
  857. * We are a ZOMBIE and nobody can enqueue itself on
  858. * pi_state_list anymore, but we have to be careful
  859. * versus waiters unqueueing themselves:
  860. */
  861. raw_spin_lock_irq(&curr->pi_lock);
  862. while (!list_empty(head)) {
  863. next = head->next;
  864. pi_state = list_entry(next, struct futex_pi_state, list);
  865. key = pi_state->key;
  866. hb = futex_hash(&key);
  867. /*
  868. * We can race against put_pi_state() removing itself from the
  869. * list (a waiter going away). put_pi_state() will first
  870. * decrement the reference count and then modify the list, so
  871. * its possible to see the list entry but fail this reference
  872. * acquire.
  873. *
  874. * In that case; drop the locks to let put_pi_state() make
  875. * progress and retry the loop.
  876. */
  877. if (!refcount_inc_not_zero(&pi_state->refcount)) {
  878. raw_spin_unlock_irq(&curr->pi_lock);
  879. cpu_relax();
  880. raw_spin_lock_irq(&curr->pi_lock);
  881. continue;
  882. }
  883. raw_spin_unlock_irq(&curr->pi_lock);
  884. spin_lock(&hb->lock);
  885. raw_spin_lock_irq(&pi_state->pi_mutex.wait_lock);
  886. raw_spin_lock(&curr->pi_lock);
  887. /*
  888. * We dropped the pi-lock, so re-check whether this
  889. * task still owns the PI-state:
  890. */
  891. if (head->next != next) {
  892. /* retain curr->pi_lock for the loop invariant */
  893. raw_spin_unlock(&pi_state->pi_mutex.wait_lock);
  894. spin_unlock(&hb->lock);
  895. put_pi_state(pi_state);
  896. continue;
  897. }
  898. WARN_ON(pi_state->owner != curr);
  899. WARN_ON(list_empty(&pi_state->list));
  900. list_del_init(&pi_state->list);
  901. pi_state->owner = NULL;
  902. raw_spin_unlock(&curr->pi_lock);
  903. raw_spin_unlock_irq(&pi_state->pi_mutex.wait_lock);
  904. spin_unlock(&hb->lock);
  905. rt_mutex_futex_unlock(&pi_state->pi_mutex);
  906. put_pi_state(pi_state);
  907. raw_spin_lock_irq(&curr->pi_lock);
  908. }
  909. raw_spin_unlock_irq(&curr->pi_lock);
  910. }
  911. #else
  912. static inline void exit_pi_state_list(struct task_struct *curr) { }
  913. #endif
  914. static void futex_cleanup(struct task_struct *tsk)
  915. {
  916. if (unlikely(tsk->robust_list)) {
  917. exit_robust_list(tsk);
  918. tsk->robust_list = NULL;
  919. }
  920. #ifdef CONFIG_COMPAT
  921. if (unlikely(tsk->compat_robust_list)) {
  922. compat_exit_robust_list(tsk);
  923. tsk->compat_robust_list = NULL;
  924. }
  925. #endif
  926. if (unlikely(!list_empty(&tsk->pi_state_list)))
  927. exit_pi_state_list(tsk);
  928. }
  929. /**
  930. * futex_exit_recursive - Set the tasks futex state to FUTEX_STATE_DEAD
  931. * @tsk: task to set the state on
  932. *
  933. * Set the futex exit state of the task lockless. The futex waiter code
  934. * observes that state when a task is exiting and loops until the task has
  935. * actually finished the futex cleanup. The worst case for this is that the
  936. * waiter runs through the wait loop until the state becomes visible.
  937. *
  938. * This is called from the recursive fault handling path in make_task_dead().
  939. *
  940. * This is best effort. Either the futex exit code has run already or
  941. * not. If the OWNER_DIED bit has been set on the futex then the waiter can
  942. * take it over. If not, the problem is pushed back to user space. If the
  943. * futex exit code did not run yet, then an already queued waiter might
  944. * block forever, but there is nothing which can be done about that.
  945. */
  946. void futex_exit_recursive(struct task_struct *tsk)
  947. {
  948. /* If the state is FUTEX_STATE_EXITING then futex_exit_mutex is held */
  949. if (tsk->futex_state == FUTEX_STATE_EXITING)
  950. mutex_unlock(&tsk->futex_exit_mutex);
  951. tsk->futex_state = FUTEX_STATE_DEAD;
  952. }
  953. static void futex_cleanup_begin(struct task_struct *tsk)
  954. {
  955. /*
  956. * Prevent various race issues against a concurrent incoming waiter
  957. * including live locks by forcing the waiter to block on
  958. * tsk->futex_exit_mutex when it observes FUTEX_STATE_EXITING in
  959. * attach_to_pi_owner().
  960. */
  961. mutex_lock(&tsk->futex_exit_mutex);
  962. /*
  963. * Switch the state to FUTEX_STATE_EXITING under tsk->pi_lock.
  964. *
  965. * This ensures that all subsequent checks of tsk->futex_state in
  966. * attach_to_pi_owner() must observe FUTEX_STATE_EXITING with
  967. * tsk->pi_lock held.
  968. *
  969. * It guarantees also that a pi_state which was queued right before
  970. * the state change under tsk->pi_lock by a concurrent waiter must
  971. * be observed in exit_pi_state_list().
  972. */
  973. raw_spin_lock_irq(&tsk->pi_lock);
  974. tsk->futex_state = FUTEX_STATE_EXITING;
  975. raw_spin_unlock_irq(&tsk->pi_lock);
  976. }
  977. static void futex_cleanup_end(struct task_struct *tsk, int state)
  978. {
  979. /*
  980. * Lockless store. The only side effect is that an observer might
  981. * take another loop until it becomes visible.
  982. */
  983. tsk->futex_state = state;
  984. /*
  985. * Drop the exit protection. This unblocks waiters which observed
  986. * FUTEX_STATE_EXITING to reevaluate the state.
  987. */
  988. mutex_unlock(&tsk->futex_exit_mutex);
  989. }
  990. void futex_exec_release(struct task_struct *tsk)
  991. {
  992. /*
  993. * The state handling is done for consistency, but in the case of
  994. * exec() there is no way to prevent further damage as the PID stays
  995. * the same. But for the unlikely and arguably buggy case that a
  996. * futex is held on exec(), this provides at least as much state
  997. * consistency protection which is possible.
  998. */
  999. futex_cleanup_begin(tsk);
  1000. futex_cleanup(tsk);
  1001. /*
  1002. * Reset the state to FUTEX_STATE_OK. The task is alive and about
  1003. * exec a new binary.
  1004. */
  1005. futex_cleanup_end(tsk, FUTEX_STATE_OK);
  1006. }
  1007. void futex_exit_release(struct task_struct *tsk)
  1008. {
  1009. futex_cleanup_begin(tsk);
  1010. futex_cleanup(tsk);
  1011. futex_cleanup_end(tsk, FUTEX_STATE_DEAD);
  1012. }
  1013. static int __init futex_init(void)
  1014. {
  1015. unsigned int futex_shift;
  1016. unsigned long i;
  1017. #ifdef CONFIG_BASE_SMALL
  1018. futex_hashsize = 16;
  1019. #else
  1020. futex_hashsize = roundup_pow_of_two(256 * num_possible_cpus());
  1021. #endif
  1022. futex_queues = alloc_large_system_hash("futex", sizeof(*futex_queues),
  1023. futex_hashsize, 0, 0,
  1024. &futex_shift, NULL,
  1025. futex_hashsize, futex_hashsize);
  1026. futex_hashsize = 1UL << futex_shift;
  1027. for (i = 0; i < futex_hashsize; i++) {
  1028. atomic_set(&futex_queues[i].waiters, 0);
  1029. plist_head_init(&futex_queues[i].chain);
  1030. spin_lock_init(&futex_queues[i].lock);
  1031. }
  1032. return 0;
  1033. }
  1034. core_initcall(futex_init);