futex.c 80 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569257025712572257325742575257625772578257925802581258225832584258525862587258825892590259125922593259425952596259725982599260026012602260326042605260626072608260926102611261226132614261526162617261826192620262126222623262426252626262726282629263026312632263326342635263626372638263926402641264226432644264526462647264826492650265126522653265426552656265726582659266026612662266326642665266626672668266926702671267226732674267526762677267826792680268126822683268426852686268726882689269026912692269326942695269626972698269927002701270227032704270527062707270827092710271127122713271427152716271727182719272027212722272327242725272627272728272927302731273227332734273527362737273827392740274127422743274427452746274727482749275027512752275327542755275627572758275927602761276227632764276527662767276827692770277127722773277427752776277727782779278027812782278327842785278627872788278927902791279227932794279527962797279827992800280128022803280428052806280728082809281028112812281328142815281628172818281928202821282228232824282528262827282828292830283128322833283428352836283728382839284028412842284328442845284628472848284928502851285228532854285528562857285828592860286128622863286428652866286728682869287028712872287328742875287628772878287928802881288228832884288528862887288828892890289128922893289428952896289728982899290029012902290329042905290629072908290929102911291229132914291529162917291829192920292129222923292429252926292729282929293029312932293329342935293629372938293929402941294229432944294529462947294829492950295129522953295429552956295729582959296029612962296329642965296629672968296929702971297229732974297529762977297829792980298129822983298429852986298729882989299029912992299329942995299629972998299930003001300230033004300530063007300830093010301130123013301430153016301730183019302030213022302330243025302630273028302930303031303230333034303530363037303830393040
  1. /*
  2. * Fast Userspace Mutexes (which I call "Futexes!").
  3. * (C) Rusty Russell, IBM 2002
  4. *
  5. * Generalized futexes, futex requeueing, misc fixes by Ingo Molnar
  6. * (C) Copyright 2003 Red Hat Inc, All Rights Reserved
  7. *
  8. * Removed page pinning, fix privately mapped COW pages and other cleanups
  9. * (C) Copyright 2003, 2004 Jamie Lokier
  10. *
  11. * Robust futex support started by Ingo Molnar
  12. * (C) Copyright 2006 Red Hat Inc, All Rights Reserved
  13. * Thanks to Thomas Gleixner for suggestions, analysis and fixes.
  14. *
  15. * PI-futex support started by Ingo Molnar and Thomas Gleixner
  16. * Copyright (C) 2006 Red Hat, Inc., Ingo Molnar <mingo@redhat.com>
  17. * Copyright (C) 2006 Timesys Corp., Thomas Gleixner <tglx@timesys.com>
  18. *
  19. * PRIVATE futexes by Eric Dumazet
  20. * Copyright (C) 2007 Eric Dumazet <dada1@cosmosbay.com>
  21. *
  22. * Requeue-PI support by Darren Hart <dvhltc@us.ibm.com>
  23. * Copyright (C) IBM Corporation, 2009
  24. * Thanks to Thomas Gleixner for conceptual design and careful reviews.
  25. *
  26. * Thanks to Ben LaHaise for yelling "hashed waitqueues" loudly
  27. * enough at me, Linus for the original (flawed) idea, Matthew
  28. * Kirkwood for proof-of-concept implementation.
  29. *
  30. * "The futexes are also cursed."
  31. * "But they come in a choice of three flavours!"
  32. *
  33. * This program is free software; you can redistribute it and/or modify
  34. * it under the terms of the GNU General Public License as published by
  35. * the Free Software Foundation; either version 2 of the License, or
  36. * (at your option) any later version.
  37. *
  38. * This program is distributed in the hope that it will be useful,
  39. * but WITHOUT ANY WARRANTY; without even the implied warranty of
  40. * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  41. * GNU General Public License for more details.
  42. *
  43. * You should have received a copy of the GNU General Public License
  44. * along with this program; if not, write to the Free Software
  45. * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
  46. */
  47. #include <linux/slab.h>
  48. #include <linux/poll.h>
  49. #include <linux/fs.h>
  50. #include <linux/file.h>
  51. #include <linux/jhash.h>
  52. #include <linux/init.h>
  53. #include <linux/futex.h>
  54. #include <linux/mount.h>
  55. #include <linux/pagemap.h>
  56. #include <linux/syscalls.h>
  57. #include <linux/signal.h>
  58. #include <linux/export.h>
  59. #include <linux/magic.h>
  60. #include <linux/pid.h>
  61. #include <linux/nsproxy.h>
  62. #include <linux/ptrace.h>
  63. #include <linux/hugetlb.h>
  64. #include <linux/freezer.h>
  65. #include <linux/bootmem.h>
  66. #include <asm/futex.h>
  67. #include "rtmutex_common.h"
  68. int __read_mostly futex_cmpxchg_enabled;
  69. /*
  70. * Futex flags used to encode options to functions and preserve them across
  71. * restarts.
  72. */
  73. #define FLAGS_SHARED 0x01
  74. #define FLAGS_CLOCKRT 0x02
  75. #define FLAGS_HAS_TIMEOUT 0x04
  76. /*
  77. * Priority Inheritance state:
  78. */
  79. struct futex_pi_state {
  80. /*
  81. * list of 'owned' pi_state instances - these have to be
  82. * cleaned up in do_exit() if the task exits prematurely:
  83. */
  84. struct list_head list;
  85. /*
  86. * The PI object:
  87. */
  88. struct rt_mutex pi_mutex;
  89. struct task_struct *owner;
  90. atomic_t refcount;
  91. union futex_key key;
  92. };
  93. /**
  94. * struct futex_q - The hashed futex queue entry, one per waiting task
  95. * @list: priority-sorted list of tasks waiting on this futex
  96. * @task: the task waiting on the futex
  97. * @lock_ptr: the hash bucket lock
  98. * @key: the key the futex is hashed on
  99. * @pi_state: optional priority inheritance state
  100. * @rt_waiter: rt_waiter storage for use with requeue_pi
  101. * @requeue_pi_key: the requeue_pi target futex key
  102. * @bitset: bitset for the optional bitmasked wakeup
  103. *
  104. * We use this hashed waitqueue, instead of a normal wait_queue_t, so
  105. * we can wake only the relevant ones (hashed queues may be shared).
  106. *
  107. * A futex_q has a woken state, just like tasks have TASK_RUNNING.
  108. * It is considered woken when plist_node_empty(&q->list) || q->lock_ptr == 0.
  109. * The order of wakeup is always to make the first condition true, then
  110. * the second.
  111. *
  112. * PI futexes are typically woken before they are removed from the hash list via
  113. * the rt_mutex code. See unqueue_me_pi().
  114. */
  115. struct futex_q {
  116. struct plist_node list;
  117. struct task_struct *task;
  118. spinlock_t *lock_ptr;
  119. union futex_key key;
  120. struct futex_pi_state *pi_state;
  121. struct rt_mutex_waiter *rt_waiter;
  122. union futex_key *requeue_pi_key;
  123. u32 bitset;
  124. };
  125. static const struct futex_q futex_q_init = {
  126. /* list gets initialized in queue_me()*/
  127. .key = FUTEX_KEY_INIT,
  128. .bitset = FUTEX_BITSET_MATCH_ANY
  129. };
  130. /*
  131. * Hash buckets are shared by all the futex_keys that hash to the same
  132. * location. Each key may have multiple futex_q structures, one for each task
  133. * waiting on a futex.
  134. */
  135. struct futex_hash_bucket {
  136. spinlock_t lock;
  137. struct plist_head chain;
  138. } ____cacheline_aligned_in_smp;
  139. static unsigned long __read_mostly futex_hashsize;
  140. static struct futex_hash_bucket *futex_queues;
  141. /*
  142. * We hash on the keys returned from get_futex_key (see below).
  143. */
  144. static struct futex_hash_bucket *hash_futex(union futex_key *key)
  145. {
  146. u32 hash = jhash2((u32*)&key->both.word,
  147. (sizeof(key->both.word)+sizeof(key->both.ptr))/4,
  148. key->both.offset);
  149. return &futex_queues[hash & (futex_hashsize - 1)];
  150. }
  151. /*
  152. * Return 1 if two futex_keys are equal, 0 otherwise.
  153. */
  154. static inline int match_futex(union futex_key *key1, union futex_key *key2)
  155. {
  156. return (key1 && key2
  157. && key1->both.word == key2->both.word
  158. && key1->both.ptr == key2->both.ptr
  159. && key1->both.offset == key2->both.offset);
  160. }
  161. /*
  162. * Take a reference to the resource addressed by a key.
  163. * Can be called while holding spinlocks.
  164. *
  165. */
  166. static void get_futex_key_refs(union futex_key *key)
  167. {
  168. if (!key->both.ptr)
  169. return;
  170. switch (key->both.offset & (FUT_OFF_INODE|FUT_OFF_MMSHARED)) {
  171. case FUT_OFF_INODE:
  172. ihold(key->shared.inode);
  173. break;
  174. case FUT_OFF_MMSHARED:
  175. atomic_inc(&key->private.mm->mm_count);
  176. break;
  177. }
  178. }
  179. /*
  180. * Drop a reference to the resource addressed by a key.
  181. * The hash bucket spinlock must not be held.
  182. */
  183. static void drop_futex_key_refs(union futex_key *key)
  184. {
  185. if (!key->both.ptr) {
  186. /* If we're here then we tried to put a key we failed to get */
  187. WARN_ON_ONCE(1);
  188. return;
  189. }
  190. switch (key->both.offset & (FUT_OFF_INODE|FUT_OFF_MMSHARED)) {
  191. case FUT_OFF_INODE:
  192. iput(key->shared.inode);
  193. break;
  194. case FUT_OFF_MMSHARED:
  195. mmdrop(key->private.mm);
  196. break;
  197. default:
  198. smp_mb(); /* explicit MB (B) */
  199. }
  200. }
  201. /**
  202. * get_futex_key() - Get parameters which are the keys for a futex
  203. * @uaddr: virtual address of the futex
  204. * @fshared: 0 for a PROCESS_PRIVATE futex, 1 for PROCESS_SHARED
  205. * @key: address where result is stored.
  206. * @rw: mapping needs to be read/write (values: VERIFY_READ,
  207. * VERIFY_WRITE)
  208. *
  209. * Returns a negative error code or 0
  210. * The key words are stored in *key on success.
  211. *
  212. * For shared mappings, it's (page->index, vma->vm_file->f_path.dentry->d_inode,
  213. * offset_within_page). For private mappings, it's (uaddr, current->mm).
  214. * We can usually work out the index without swapping in the page.
  215. *
  216. * lock_page() might sleep, the caller should not hold a spinlock.
  217. */
  218. static int
  219. get_futex_key(u32 __user *uaddr, int fshared, union futex_key *key, int rw)
  220. {
  221. unsigned long address = (unsigned long)uaddr;
  222. struct mm_struct *mm = current->mm;
  223. struct page *page, *page_head;
  224. struct address_space *mapping;
  225. int err, ro = 0;
  226. /*
  227. * The futex address must be "naturally" aligned.
  228. */
  229. key->both.offset = address % PAGE_SIZE;
  230. if (unlikely((address % sizeof(u32)) != 0))
  231. return -EINVAL;
  232. address -= key->both.offset;
  233. /*
  234. * PROCESS_PRIVATE futexes are fast.
  235. * As the mm cannot disappear under us and the 'key' only needs
  236. * virtual address, we dont even have to find the underlying vma.
  237. * Note : We do have to check 'uaddr' is a valid user address,
  238. * but access_ok() should be faster than find_vma()
  239. */
  240. if (!fshared) {
  241. if (unlikely(!access_ok(VERIFY_WRITE, uaddr, sizeof(u32))))
  242. return -EFAULT;
  243. key->private.mm = mm;
  244. key->private.address = address;
  245. get_futex_key_refs(key);
  246. return 0;
  247. }
  248. again:
  249. err = get_user_pages_fast(address, 1, 1, &page);
  250. /*
  251. * If write access is not required (eg. FUTEX_WAIT), try
  252. * and get read-only access.
  253. */
  254. if (err == -EFAULT && rw == VERIFY_READ) {
  255. err = get_user_pages_fast(address, 1, 0, &page);
  256. ro = 1;
  257. }
  258. if (err < 0)
  259. return err;
  260. else
  261. err = 0;
  262. #ifdef CONFIG_TRANSPARENT_HUGEPAGE
  263. page_head = page;
  264. if (unlikely(PageTail(page))) {
  265. put_page(page);
  266. /* serialize against __split_huge_page_splitting() */
  267. local_irq_disable();
  268. if (likely(__get_user_pages_fast(address, 1, !ro, &page) == 1)) {
  269. page_head = compound_head(page);
  270. /*
  271. * page_head is valid pointer but we must pin
  272. * it before taking the PG_lock and/or
  273. * PG_compound_lock. The moment we re-enable
  274. * irqs __split_huge_page_splitting() can
  275. * return and the head page can be freed from
  276. * under us. We can't take the PG_lock and/or
  277. * PG_compound_lock on a page that could be
  278. * freed from under us.
  279. */
  280. if (page != page_head) {
  281. get_page(page_head);
  282. put_page(page);
  283. }
  284. local_irq_enable();
  285. } else {
  286. local_irq_enable();
  287. goto again;
  288. }
  289. }
  290. #else
  291. page_head = compound_head(page);
  292. if (page != page_head) {
  293. get_page(page_head);
  294. put_page(page);
  295. }
  296. #endif
  297. /*
  298. * The treatment of mapping from this point on is critical. The page
  299. * lock protects many things but in this context the page lock
  300. * stabilizes mapping, prevents inode freeing in the shared
  301. * file-backed region case and guards against movement to swap cache.
  302. *
  303. * Strictly speaking the page lock is not needed in all cases being
  304. * considered here and page lock forces unnecessarily serialization
  305. * From this point on, mapping will be re-verified if necessary and
  306. * page lock will be acquired only if it is unavoidable
  307. */
  308. mapping = READ_ONCE(page_head->mapping);
  309. /*
  310. * If page_head->mapping is NULL, then it cannot be a PageAnon
  311. * page; but it might be the ZERO_PAGE or in the gate area or
  312. * in a special mapping (all cases which we are happy to fail);
  313. * or it may have been a good file page when get_user_pages_fast
  314. * found it, but truncated or holepunched or subjected to
  315. * invalidate_complete_page2 before we got the page lock (also
  316. * cases which we are happy to fail). And we hold a reference,
  317. * so refcount care in invalidate_complete_page's remove_mapping
  318. * prevents drop_caches from setting mapping to NULL beneath us.
  319. *
  320. * The case we do have to guard against is when memory pressure made
  321. * shmem_writepage move it from filecache to swapcache beneath us:
  322. * an unlikely race, but we do need to retry for page_head->mapping.
  323. */
  324. if (unlikely(!mapping)) {
  325. int shmem_swizzled;
  326. /*
  327. * Page lock is required to identify which special case above
  328. * applies. If this is really a shmem page then the page lock
  329. * will prevent unexpected transitions.
  330. */
  331. lock_page(page);
  332. shmem_swizzled = PageSwapCache(page) || page->mapping;
  333. unlock_page(page_head);
  334. put_page(page_head);
  335. if (shmem_swizzled)
  336. goto again;
  337. return -EFAULT;
  338. }
  339. /*
  340. * Private mappings are handled in a simple way.
  341. *
  342. * If the futex key is stored on an anonymous page, then the associated
  343. * object is the mm which is implicitly pinned by the calling process.
  344. *
  345. * NOTE: When userspace waits on a MAP_SHARED mapping, even if
  346. * it's a read-only handle, it's expected that futexes attach to
  347. * the object not the particular process.
  348. */
  349. if (PageAnon(page_head)) {
  350. /*
  351. * A RO anonymous page will never change and thus doesn't make
  352. * sense for futex operations.
  353. */
  354. if (ro) {
  355. err = -EFAULT;
  356. goto out;
  357. }
  358. key->both.offset |= FUT_OFF_MMSHARED; /* ref taken on mm */
  359. key->private.mm = mm;
  360. key->private.address = address;
  361. get_futex_key_refs(key); /* implies smp_mb(); (B) */
  362. } else {
  363. struct inode *inode;
  364. /*
  365. * The associated futex object in this case is the inode and
  366. * the page->mapping must be traversed. Ordinarily this should
  367. * be stabilised under page lock but it's not strictly
  368. * necessary in this case as we just want to pin the inode, not
  369. * update the radix tree or anything like that.
  370. *
  371. * The RCU read lock is taken as the inode is finally freed
  372. * under RCU. If the mapping still matches expectations then the
  373. * mapping->host can be safely accessed as being a valid inode.
  374. */
  375. rcu_read_lock();
  376. if (READ_ONCE(page_head->mapping) != mapping) {
  377. rcu_read_unlock();
  378. put_page(page_head);
  379. goto again;
  380. }
  381. inode = READ_ONCE(mapping->host);
  382. if (!inode) {
  383. rcu_read_unlock();
  384. put_page(page_head);
  385. goto again;
  386. }
  387. /*
  388. * Take a reference unless it is about to be freed. Previously
  389. * this reference was taken by ihold under the page lock
  390. * pinning the inode in place so i_lock was unnecessary. The
  391. * only way for this check to fail is if the inode was
  392. * truncated in parallel so warn for now if this happens.
  393. *
  394. * We are not calling into get_futex_key_refs() in file-backed
  395. * cases, therefore a successful atomic_inc return below will
  396. * guarantee that get_futex_key() will still imply smp_mb(); (B).
  397. */
  398. if (WARN_ON_ONCE(!atomic_inc_not_zero(&inode->i_count))) {
  399. rcu_read_unlock();
  400. put_page(page_head);
  401. goto again;
  402. }
  403. /* Should be impossible but lets be paranoid for now */
  404. if (WARN_ON_ONCE(inode->i_mapping != mapping)) {
  405. err = -EFAULT;
  406. rcu_read_unlock();
  407. iput(inode);
  408. goto out;
  409. }
  410. key->both.offset |= FUT_OFF_INODE; /* inode-based key */
  411. key->shared.inode = inode;
  412. key->shared.pgoff = page_head->index;
  413. rcu_read_unlock();
  414. }
  415. out:
  416. put_page(page_head);
  417. return err;
  418. }
  419. static inline void put_futex_key(union futex_key *key)
  420. {
  421. drop_futex_key_refs(key);
  422. }
  423. /**
  424. * fault_in_user_writeable() - Fault in user address and verify RW access
  425. * @uaddr: pointer to faulting user space address
  426. *
  427. * Slow path to fixup the fault we just took in the atomic write
  428. * access to @uaddr.
  429. *
  430. * We have no generic implementation of a non-destructive write to the
  431. * user address. We know that we faulted in the atomic pagefault
  432. * disabled section so we can as well avoid the #PF overhead by
  433. * calling get_user_pages() right away.
  434. */
  435. static int fault_in_user_writeable(u32 __user *uaddr)
  436. {
  437. struct mm_struct *mm = current->mm;
  438. int ret;
  439. down_read(&mm->mmap_sem);
  440. ret = fixup_user_fault(current, mm, (unsigned long)uaddr,
  441. FAULT_FLAG_WRITE);
  442. up_read(&mm->mmap_sem);
  443. return ret < 0 ? ret : 0;
  444. }
  445. /**
  446. * futex_top_waiter() - Return the highest priority waiter on a futex
  447. * @hb: the hash bucket the futex_q's reside in
  448. * @key: the futex key (to distinguish it from other futex futex_q's)
  449. *
  450. * Must be called with the hb lock held.
  451. */
  452. static struct futex_q *futex_top_waiter(struct futex_hash_bucket *hb,
  453. union futex_key *key)
  454. {
  455. struct futex_q *this;
  456. plist_for_each_entry(this, &hb->chain, list) {
  457. if (match_futex(&this->key, key))
  458. return this;
  459. }
  460. return NULL;
  461. }
  462. static int cmpxchg_futex_value_locked(u32 *curval, u32 __user *uaddr,
  463. u32 uval, u32 newval)
  464. {
  465. int ret;
  466. pagefault_disable();
  467. ret = futex_atomic_cmpxchg_inatomic(curval, uaddr, uval, newval);
  468. pagefault_enable();
  469. return ret;
  470. }
  471. static int get_futex_value_locked(u32 *dest, u32 __user *from)
  472. {
  473. int ret;
  474. pagefault_disable();
  475. ret = __copy_from_user_inatomic(dest, from, sizeof(u32));
  476. pagefault_enable();
  477. return ret ? -EFAULT : 0;
  478. }
  479. /*
  480. * PI code:
  481. */
  482. static int refill_pi_state_cache(void)
  483. {
  484. struct futex_pi_state *pi_state;
  485. if (likely(current->pi_state_cache))
  486. return 0;
  487. pi_state = kzalloc(sizeof(*pi_state), GFP_KERNEL);
  488. if (!pi_state)
  489. return -ENOMEM;
  490. INIT_LIST_HEAD(&pi_state->list);
  491. /* pi_mutex gets initialized later */
  492. pi_state->owner = NULL;
  493. atomic_set(&pi_state->refcount, 1);
  494. pi_state->key = FUTEX_KEY_INIT;
  495. current->pi_state_cache = pi_state;
  496. return 0;
  497. }
  498. static struct futex_pi_state * alloc_pi_state(void)
  499. {
  500. struct futex_pi_state *pi_state = current->pi_state_cache;
  501. WARN_ON(!pi_state);
  502. current->pi_state_cache = NULL;
  503. return pi_state;
  504. }
  505. /*
  506. * Must be called with the hb lock held.
  507. */
  508. static void free_pi_state(struct futex_pi_state *pi_state)
  509. {
  510. if (!pi_state)
  511. return;
  512. if (!atomic_dec_and_test(&pi_state->refcount))
  513. return;
  514. /*
  515. * If pi_state->owner is NULL, the owner is most probably dying
  516. * and has cleaned up the pi_state already
  517. */
  518. if (pi_state->owner) {
  519. raw_spin_lock_irq(&pi_state->owner->pi_lock);
  520. list_del_init(&pi_state->list);
  521. raw_spin_unlock_irq(&pi_state->owner->pi_lock);
  522. rt_mutex_proxy_unlock(&pi_state->pi_mutex, pi_state->owner);
  523. }
  524. if (current->pi_state_cache)
  525. kfree(pi_state);
  526. else {
  527. /*
  528. * pi_state->list is already empty.
  529. * clear pi_state->owner.
  530. * refcount is at 0 - put it back to 1.
  531. */
  532. pi_state->owner = NULL;
  533. atomic_set(&pi_state->refcount, 1);
  534. current->pi_state_cache = pi_state;
  535. }
  536. }
  537. /*
  538. * Look up the task based on what TID userspace gave us.
  539. * We dont trust it.
  540. */
  541. static struct task_struct * futex_find_get_task(pid_t pid)
  542. {
  543. struct task_struct *p;
  544. rcu_read_lock();
  545. p = find_task_by_vpid(pid);
  546. if (p)
  547. get_task_struct(p);
  548. rcu_read_unlock();
  549. return p;
  550. }
  551. /*
  552. * This task is holding PI mutexes at exit time => bad.
  553. * Kernel cleans up PI-state, but userspace is likely hosed.
  554. * (Robust-futex cleanup is separate and might save the day for userspace.)
  555. */
  556. void exit_pi_state_list(struct task_struct *curr)
  557. {
  558. struct list_head *next, *head = &curr->pi_state_list;
  559. struct futex_pi_state *pi_state;
  560. struct futex_hash_bucket *hb;
  561. union futex_key key = FUTEX_KEY_INIT;
  562. if (!futex_cmpxchg_enabled)
  563. return;
  564. /*
  565. * We are a ZOMBIE and nobody can enqueue itself on
  566. * pi_state_list anymore, but we have to be careful
  567. * versus waiters unqueueing themselves:
  568. */
  569. raw_spin_lock_irq(&curr->pi_lock);
  570. while (!list_empty(head)) {
  571. next = head->next;
  572. pi_state = list_entry(next, struct futex_pi_state, list);
  573. key = pi_state->key;
  574. hb = hash_futex(&key);
  575. raw_spin_unlock_irq(&curr->pi_lock);
  576. spin_lock(&hb->lock);
  577. raw_spin_lock_irq(&curr->pi_lock);
  578. /*
  579. * We dropped the pi-lock, so re-check whether this
  580. * task still owns the PI-state:
  581. */
  582. if (head->next != next) {
  583. spin_unlock(&hb->lock);
  584. continue;
  585. }
  586. WARN_ON(pi_state->owner != curr);
  587. WARN_ON(list_empty(&pi_state->list));
  588. list_del_init(&pi_state->list);
  589. pi_state->owner = NULL;
  590. raw_spin_unlock_irq(&curr->pi_lock);
  591. rt_mutex_unlock(&pi_state->pi_mutex);
  592. spin_unlock(&hb->lock);
  593. raw_spin_lock_irq(&curr->pi_lock);
  594. }
  595. raw_spin_unlock_irq(&curr->pi_lock);
  596. }
  597. /*
  598. * We need to check the following states:
  599. *
  600. * Waiter | pi_state | pi->owner | uTID | uODIED | ?
  601. *
  602. * [1] NULL | --- | --- | 0 | 0/1 | Valid
  603. * [2] NULL | --- | --- | >0 | 0/1 | Valid
  604. *
  605. * [3] Found | NULL | -- | Any | 0/1 | Invalid
  606. *
  607. * [4] Found | Found | NULL | 0 | 1 | Valid
  608. * [5] Found | Found | NULL | >0 | 1 | Invalid
  609. *
  610. * [6] Found | Found | task | 0 | 1 | Valid
  611. *
  612. * [7] Found | Found | NULL | Any | 0 | Invalid
  613. *
  614. * [8] Found | Found | task | ==taskTID | 0/1 | Valid
  615. * [9] Found | Found | task | 0 | 0 | Invalid
  616. * [10] Found | Found | task | !=taskTID | 0/1 | Invalid
  617. *
  618. * [1] Indicates that the kernel can acquire the futex atomically. We
  619. * came came here due to a stale FUTEX_WAITERS/FUTEX_OWNER_DIED bit.
  620. *
  621. * [2] Valid, if TID does not belong to a kernel thread. If no matching
  622. * thread is found then it indicates that the owner TID has died.
  623. *
  624. * [3] Invalid. The waiter is queued on a non PI futex
  625. *
  626. * [4] Valid state after exit_robust_list(), which sets the user space
  627. * value to FUTEX_WAITERS | FUTEX_OWNER_DIED.
  628. *
  629. * [5] The user space value got manipulated between exit_robust_list()
  630. * and exit_pi_state_list()
  631. *
  632. * [6] Valid state after exit_pi_state_list() which sets the new owner in
  633. * the pi_state but cannot access the user space value.
  634. *
  635. * [7] pi_state->owner can only be NULL when the OWNER_DIED bit is set.
  636. *
  637. * [8] Owner and user space value match
  638. *
  639. * [9] There is no transient state which sets the user space TID to 0
  640. * except exit_robust_list(), but this is indicated by the
  641. * FUTEX_OWNER_DIED bit. See [4]
  642. *
  643. * [10] There is no transient state which leaves owner and user space
  644. * TID out of sync.
  645. */
  646. static int
  647. lookup_pi_state(u32 uval, struct futex_hash_bucket *hb,
  648. union futex_key *key, struct futex_pi_state **ps)
  649. {
  650. struct futex_pi_state *pi_state = NULL;
  651. struct futex_q *this, *next;
  652. struct plist_head *head;
  653. struct task_struct *p;
  654. pid_t pid = uval & FUTEX_TID_MASK;
  655. head = &hb->chain;
  656. plist_for_each_entry_safe(this, next, head, list) {
  657. if (match_futex(&this->key, key)) {
  658. /*
  659. * Sanity check the waiter before increasing
  660. * the refcount and attaching to it.
  661. */
  662. pi_state = this->pi_state;
  663. /*
  664. * Userspace might have messed up non-PI and
  665. * PI futexes [3]
  666. */
  667. if (unlikely(!pi_state))
  668. return -EINVAL;
  669. WARN_ON(!atomic_read(&pi_state->refcount));
  670. /*
  671. * Handle the owner died case:
  672. */
  673. if (uval & FUTEX_OWNER_DIED) {
  674. /*
  675. * exit_pi_state_list sets owner to NULL and
  676. * wakes the topmost waiter. The task which
  677. * acquires the pi_state->rt_mutex will fixup
  678. * owner.
  679. */
  680. if (!pi_state->owner) {
  681. /*
  682. * No pi state owner, but the user
  683. * space TID is not 0. Inconsistent
  684. * state. [5]
  685. */
  686. if (pid)
  687. return -EINVAL;
  688. /*
  689. * Take a ref on the state and
  690. * return. [4]
  691. */
  692. goto out_state;
  693. }
  694. /*
  695. * If TID is 0, then either the dying owner
  696. * has not yet executed exit_pi_state_list()
  697. * or some waiter acquired the rtmutex in the
  698. * pi state, but did not yet fixup the TID in
  699. * user space.
  700. *
  701. * Take a ref on the state and return. [6]
  702. */
  703. if (!pid)
  704. goto out_state;
  705. } else {
  706. /*
  707. * If the owner died bit is not set,
  708. * then the pi_state must have an
  709. * owner. [7]
  710. */
  711. if (!pi_state->owner)
  712. return -EINVAL;
  713. }
  714. /*
  715. * Bail out if user space manipulated the
  716. * futex value. If pi state exists then the
  717. * owner TID must be the same as the user
  718. * space TID. [9/10]
  719. */
  720. if (pid != task_pid_vnr(pi_state->owner))
  721. return -EINVAL;
  722. out_state:
  723. atomic_inc(&pi_state->refcount);
  724. *ps = pi_state;
  725. return 0;
  726. }
  727. }
  728. /*
  729. * We are the first waiter - try to look up the real owner and attach
  730. * the new pi_state to it, but bail out when TID = 0 [1]
  731. */
  732. if (!pid)
  733. return -ESRCH;
  734. p = futex_find_get_task(pid);
  735. if (!p)
  736. return -ESRCH;
  737. if (!p->mm) {
  738. put_task_struct(p);
  739. return -EPERM;
  740. }
  741. /*
  742. * We need to look at the task state flags to figure out,
  743. * whether the task is exiting. To protect against the do_exit
  744. * change of the task flags, we do this protected by
  745. * p->pi_lock:
  746. */
  747. raw_spin_lock_irq(&p->pi_lock);
  748. if (unlikely(p->flags & PF_EXITING)) {
  749. /*
  750. * The task is on the way out. When PF_EXITPIDONE is
  751. * set, we know that the task has finished the
  752. * cleanup:
  753. */
  754. int ret = (p->flags & PF_EXITPIDONE) ? -ESRCH : -EAGAIN;
  755. raw_spin_unlock_irq(&p->pi_lock);
  756. put_task_struct(p);
  757. return ret;
  758. }
  759. /*
  760. * No existing pi state. First waiter. [2]
  761. */
  762. pi_state = alloc_pi_state();
  763. /*
  764. * Initialize the pi_mutex in locked state and make 'p'
  765. * the owner of it:
  766. */
  767. rt_mutex_init_proxy_locked(&pi_state->pi_mutex, p);
  768. /* Store the key for possible exit cleanups: */
  769. pi_state->key = *key;
  770. WARN_ON(!list_empty(&pi_state->list));
  771. list_add(&pi_state->list, &p->pi_state_list);
  772. pi_state->owner = p;
  773. raw_spin_unlock_irq(&p->pi_lock);
  774. put_task_struct(p);
  775. *ps = pi_state;
  776. return 0;
  777. }
  778. /**
  779. * futex_lock_pi_atomic() - Atomic work required to acquire a pi aware futex
  780. * @uaddr: the pi futex user address
  781. * @hb: the pi futex hash bucket
  782. * @key: the futex key associated with uaddr and hb
  783. * @ps: the pi_state pointer where we store the result of the
  784. * lookup
  785. * @task: the task to perform the atomic lock work for. This will
  786. * be "current" except in the case of requeue pi.
  787. * @set_waiters: force setting the FUTEX_WAITERS bit (1) or not (0)
  788. *
  789. * Returns:
  790. * 0 - ready to wait
  791. * 1 - acquired the lock
  792. * <0 - error
  793. *
  794. * The hb->lock and futex_key refs shall be held by the caller.
  795. */
  796. static int futex_lock_pi_atomic(u32 __user *uaddr, struct futex_hash_bucket *hb,
  797. union futex_key *key,
  798. struct futex_pi_state **ps,
  799. struct task_struct *task, int set_waiters)
  800. {
  801. int lock_taken, ret, force_take = 0;
  802. u32 uval, newval, curval, vpid = task_pid_vnr(task);
  803. retry:
  804. ret = lock_taken = 0;
  805. /*
  806. * To avoid races, we attempt to take the lock here again
  807. * (by doing a 0 -> TID atomic cmpxchg), while holding all
  808. * the locks. It will most likely not succeed.
  809. */
  810. newval = vpid;
  811. if (set_waiters)
  812. newval |= FUTEX_WAITERS;
  813. if (unlikely(cmpxchg_futex_value_locked(&curval, uaddr, 0, newval)))
  814. return -EFAULT;
  815. /*
  816. * Detect deadlocks.
  817. */
  818. if ((unlikely((curval & FUTEX_TID_MASK) == vpid)))
  819. return -EDEADLK;
  820. /*
  821. * Surprise - we got the lock, but we do not trust user space at all.
  822. */
  823. if (unlikely(!curval)) {
  824. /*
  825. * We verify whether there is kernel state for this
  826. * futex. If not, we can safely assume, that the 0 ->
  827. * TID transition is correct. If state exists, we do
  828. * not bother to fixup the user space state as it was
  829. * corrupted already.
  830. */
  831. return futex_top_waiter(hb, key) ? -EINVAL : 1;
  832. }
  833. uval = curval;
  834. /*
  835. * Set the FUTEX_WAITERS flag, so the owner will know it has someone
  836. * to wake at the next unlock.
  837. */
  838. newval = curval | FUTEX_WAITERS;
  839. /*
  840. * Should we force take the futex? See below.
  841. */
  842. if (unlikely(force_take)) {
  843. /*
  844. * Keep the OWNER_DIED and the WAITERS bit and set the
  845. * new TID value.
  846. */
  847. newval = (curval & ~FUTEX_TID_MASK) | vpid;
  848. force_take = 0;
  849. lock_taken = 1;
  850. }
  851. if (unlikely(cmpxchg_futex_value_locked(&curval, uaddr, uval, newval)))
  852. return -EFAULT;
  853. if (unlikely(curval != uval))
  854. goto retry;
  855. /*
  856. * We took the lock due to forced take over.
  857. */
  858. if (unlikely(lock_taken))
  859. return 1;
  860. /*
  861. * We dont have the lock. Look up the PI state (or create it if
  862. * we are the first waiter):
  863. */
  864. ret = lookup_pi_state(uval, hb, key, ps);
  865. if (unlikely(ret)) {
  866. switch (ret) {
  867. case -ESRCH:
  868. /*
  869. * We failed to find an owner for this
  870. * futex. So we have no pi_state to block
  871. * on. This can happen in two cases:
  872. *
  873. * 1) The owner died
  874. * 2) A stale FUTEX_WAITERS bit
  875. *
  876. * Re-read the futex value.
  877. */
  878. if (get_futex_value_locked(&curval, uaddr))
  879. return -EFAULT;
  880. /*
  881. * If the owner died or we have a stale
  882. * WAITERS bit the owner TID in the user space
  883. * futex is 0.
  884. */
  885. if (!(curval & FUTEX_TID_MASK)) {
  886. force_take = 1;
  887. goto retry;
  888. }
  889. default:
  890. break;
  891. }
  892. }
  893. return ret;
  894. }
  895. /**
  896. * __unqueue_futex() - Remove the futex_q from its futex_hash_bucket
  897. * @q: The futex_q to unqueue
  898. *
  899. * The q->lock_ptr must not be NULL and must be held by the caller.
  900. */
  901. static void __unqueue_futex(struct futex_q *q)
  902. {
  903. struct futex_hash_bucket *hb;
  904. if (WARN_ON_SMP(!q->lock_ptr || !spin_is_locked(q->lock_ptr))
  905. || WARN_ON(plist_node_empty(&q->list)))
  906. return;
  907. hb = container_of(q->lock_ptr, struct futex_hash_bucket, lock);
  908. plist_del(&q->list, &hb->chain);
  909. }
  910. /*
  911. * The hash bucket lock must be held when this is called.
  912. * Afterwards, the futex_q must not be accessed.
  913. */
  914. static void wake_futex(struct futex_q *q)
  915. {
  916. struct task_struct *p = q->task;
  917. if (WARN(q->pi_state || q->rt_waiter, "refusing to wake PI futex\n"))
  918. return;
  919. /*
  920. * We set q->lock_ptr = NULL _before_ we wake up the task. If
  921. * a non-futex wake up happens on another CPU then the task
  922. * might exit and p would dereference a non-existing task
  923. * struct. Prevent this by holding a reference on p across the
  924. * wake up.
  925. */
  926. get_task_struct(p);
  927. __unqueue_futex(q);
  928. /*
  929. * The waiting task can free the futex_q as soon as
  930. * q->lock_ptr = NULL is written, without taking any locks. A
  931. * memory barrier is required here to prevent the following
  932. * store to lock_ptr from getting ahead of the plist_del.
  933. */
  934. smp_wmb();
  935. q->lock_ptr = NULL;
  936. wake_up_state(p, TASK_NORMAL);
  937. put_task_struct(p);
  938. }
  939. static int wake_futex_pi(u32 __user *uaddr, u32 uval, struct futex_q *this)
  940. {
  941. struct task_struct *new_owner;
  942. struct futex_pi_state *pi_state = this->pi_state;
  943. u32 uninitialized_var(curval), newval;
  944. int ret = 0;
  945. if (!pi_state)
  946. return -EINVAL;
  947. /*
  948. * If current does not own the pi_state then the futex is
  949. * inconsistent and user space fiddled with the futex value.
  950. */
  951. if (pi_state->owner != current)
  952. return -EINVAL;
  953. raw_spin_lock(&pi_state->pi_mutex.wait_lock);
  954. new_owner = rt_mutex_next_owner(&pi_state->pi_mutex);
  955. /*
  956. * It is possible that the next waiter (the one that brought
  957. * this owner to the kernel) timed out and is no longer
  958. * waiting on the lock.
  959. */
  960. if (!new_owner)
  961. new_owner = this->task;
  962. /*
  963. * We pass it to the next owner. The WAITERS bit is always
  964. * kept enabled while there is PI state around. We cleanup the
  965. * owner died bit, because we are the owner.
  966. */
  967. newval = FUTEX_WAITERS | task_pid_vnr(new_owner);
  968. if (cmpxchg_futex_value_locked(&curval, uaddr, uval, newval))
  969. ret = -EFAULT;
  970. else if (curval != uval)
  971. ret = -EINVAL;
  972. if (ret) {
  973. raw_spin_unlock(&pi_state->pi_mutex.wait_lock);
  974. return ret;
  975. }
  976. raw_spin_lock_irq(&pi_state->owner->pi_lock);
  977. WARN_ON(list_empty(&pi_state->list));
  978. list_del_init(&pi_state->list);
  979. raw_spin_unlock_irq(&pi_state->owner->pi_lock);
  980. raw_spin_lock_irq(&new_owner->pi_lock);
  981. WARN_ON(!list_empty(&pi_state->list));
  982. list_add(&pi_state->list, &new_owner->pi_state_list);
  983. pi_state->owner = new_owner;
  984. raw_spin_unlock_irq(&new_owner->pi_lock);
  985. raw_spin_unlock(&pi_state->pi_mutex.wait_lock);
  986. rt_mutex_unlock(&pi_state->pi_mutex);
  987. return 0;
  988. }
  989. static int unlock_futex_pi(u32 __user *uaddr, u32 uval)
  990. {
  991. u32 uninitialized_var(oldval);
  992. /*
  993. * There is no waiter, so we unlock the futex. The owner died
  994. * bit has not to be preserved here. We are the owner:
  995. */
  996. if (cmpxchg_futex_value_locked(&oldval, uaddr, uval, 0))
  997. return -EFAULT;
  998. if (oldval != uval)
  999. return -EAGAIN;
  1000. return 0;
  1001. }
  1002. /*
  1003. * Express the locking dependencies for lockdep:
  1004. */
  1005. static inline void
  1006. double_lock_hb(struct futex_hash_bucket *hb1, struct futex_hash_bucket *hb2)
  1007. {
  1008. if (hb1 <= hb2) {
  1009. spin_lock(&hb1->lock);
  1010. if (hb1 < hb2)
  1011. spin_lock_nested(&hb2->lock, SINGLE_DEPTH_NESTING);
  1012. } else { /* hb1 > hb2 */
  1013. spin_lock(&hb2->lock);
  1014. spin_lock_nested(&hb1->lock, SINGLE_DEPTH_NESTING);
  1015. }
  1016. }
  1017. static inline void
  1018. double_unlock_hb(struct futex_hash_bucket *hb1, struct futex_hash_bucket *hb2)
  1019. {
  1020. spin_unlock(&hb1->lock);
  1021. if (hb1 != hb2)
  1022. spin_unlock(&hb2->lock);
  1023. }
  1024. /*
  1025. * Wake up waiters matching bitset queued on this futex (uaddr).
  1026. */
  1027. static int
  1028. futex_wake(u32 __user *uaddr, unsigned int flags, int nr_wake, u32 bitset)
  1029. {
  1030. struct futex_hash_bucket *hb;
  1031. struct futex_q *this, *next;
  1032. struct plist_head *head;
  1033. union futex_key key = FUTEX_KEY_INIT;
  1034. int ret;
  1035. if (!bitset)
  1036. return -EINVAL;
  1037. ret = get_futex_key(uaddr, flags & FLAGS_SHARED, &key, VERIFY_READ);
  1038. if (unlikely(ret != 0))
  1039. goto out;
  1040. hb = hash_futex(&key);
  1041. spin_lock(&hb->lock);
  1042. head = &hb->chain;
  1043. plist_for_each_entry_safe(this, next, head, list) {
  1044. if (match_futex (&this->key, &key)) {
  1045. if (this->pi_state || this->rt_waiter) {
  1046. ret = -EINVAL;
  1047. break;
  1048. }
  1049. /* Check if one of the bits is set in both bitsets */
  1050. if (!(this->bitset & bitset))
  1051. continue;
  1052. wake_futex(this);
  1053. if (++ret >= nr_wake)
  1054. break;
  1055. }
  1056. }
  1057. spin_unlock(&hb->lock);
  1058. put_futex_key(&key);
  1059. out:
  1060. return ret;
  1061. }
  1062. /*
  1063. * Wake up all waiters hashed on the physical page that is mapped
  1064. * to this virtual address:
  1065. */
  1066. static int
  1067. futex_wake_op(u32 __user *uaddr1, unsigned int flags, u32 __user *uaddr2,
  1068. int nr_wake, int nr_wake2, int op)
  1069. {
  1070. union futex_key key1 = FUTEX_KEY_INIT, key2 = FUTEX_KEY_INIT;
  1071. struct futex_hash_bucket *hb1, *hb2;
  1072. struct plist_head *head;
  1073. struct futex_q *this, *next;
  1074. int ret, op_ret;
  1075. retry:
  1076. ret = get_futex_key(uaddr1, flags & FLAGS_SHARED, &key1, VERIFY_READ);
  1077. if (unlikely(ret != 0))
  1078. goto out;
  1079. ret = get_futex_key(uaddr2, flags & FLAGS_SHARED, &key2, VERIFY_WRITE);
  1080. if (unlikely(ret != 0))
  1081. goto out_put_key1;
  1082. hb1 = hash_futex(&key1);
  1083. hb2 = hash_futex(&key2);
  1084. retry_private:
  1085. double_lock_hb(hb1, hb2);
  1086. op_ret = futex_atomic_op_inuser(op, uaddr2);
  1087. if (unlikely(op_ret < 0)) {
  1088. double_unlock_hb(hb1, hb2);
  1089. #ifndef CONFIG_MMU
  1090. /*
  1091. * we don't get EFAULT from MMU faults if we don't have an MMU,
  1092. * but we might get them from range checking
  1093. */
  1094. ret = op_ret;
  1095. goto out_put_keys;
  1096. #endif
  1097. if (unlikely(op_ret != -EFAULT)) {
  1098. ret = op_ret;
  1099. goto out_put_keys;
  1100. }
  1101. ret = fault_in_user_writeable(uaddr2);
  1102. if (ret)
  1103. goto out_put_keys;
  1104. if (!(flags & FLAGS_SHARED))
  1105. goto retry_private;
  1106. put_futex_key(&key2);
  1107. put_futex_key(&key1);
  1108. goto retry;
  1109. }
  1110. head = &hb1->chain;
  1111. plist_for_each_entry_safe(this, next, head, list) {
  1112. if (match_futex (&this->key, &key1)) {
  1113. if (this->pi_state || this->rt_waiter) {
  1114. ret = -EINVAL;
  1115. goto out_unlock;
  1116. }
  1117. wake_futex(this);
  1118. if (++ret >= nr_wake)
  1119. break;
  1120. }
  1121. }
  1122. if (op_ret > 0) {
  1123. head = &hb2->chain;
  1124. op_ret = 0;
  1125. plist_for_each_entry_safe(this, next, head, list) {
  1126. if (match_futex (&this->key, &key2)) {
  1127. if (this->pi_state || this->rt_waiter) {
  1128. ret = -EINVAL;
  1129. goto out_unlock;
  1130. }
  1131. wake_futex(this);
  1132. if (++op_ret >= nr_wake2)
  1133. break;
  1134. }
  1135. }
  1136. ret += op_ret;
  1137. }
  1138. out_unlock:
  1139. double_unlock_hb(hb1, hb2);
  1140. out_put_keys:
  1141. put_futex_key(&key2);
  1142. out_put_key1:
  1143. put_futex_key(&key1);
  1144. out:
  1145. return ret;
  1146. }
  1147. /**
  1148. * requeue_futex() - Requeue a futex_q from one hb to another
  1149. * @q: the futex_q to requeue
  1150. * @hb1: the source hash_bucket
  1151. * @hb2: the target hash_bucket
  1152. * @key2: the new key for the requeued futex_q
  1153. */
  1154. static inline
  1155. void requeue_futex(struct futex_q *q, struct futex_hash_bucket *hb1,
  1156. struct futex_hash_bucket *hb2, union futex_key *key2)
  1157. {
  1158. /*
  1159. * If key1 and key2 hash to the same bucket, no need to
  1160. * requeue.
  1161. */
  1162. if (likely(&hb1->chain != &hb2->chain)) {
  1163. plist_del(&q->list, &hb1->chain);
  1164. plist_add(&q->list, &hb2->chain);
  1165. q->lock_ptr = &hb2->lock;
  1166. }
  1167. get_futex_key_refs(key2);
  1168. q->key = *key2;
  1169. }
  1170. /**
  1171. * requeue_pi_wake_futex() - Wake a task that acquired the lock during requeue
  1172. * @q: the futex_q
  1173. * @key: the key of the requeue target futex
  1174. * @hb: the hash_bucket of the requeue target futex
  1175. *
  1176. * During futex_requeue, with requeue_pi=1, it is possible to acquire the
  1177. * target futex if it is uncontended or via a lock steal. Set the futex_q key
  1178. * to the requeue target futex so the waiter can detect the wakeup on the right
  1179. * futex, but remove it from the hb and NULL the rt_waiter so it can detect
  1180. * atomic lock acquisition. Set the q->lock_ptr to the requeue target hb->lock
  1181. * to protect access to the pi_state to fixup the owner later. Must be called
  1182. * with both q->lock_ptr and hb->lock held.
  1183. */
  1184. static inline
  1185. void requeue_pi_wake_futex(struct futex_q *q, union futex_key *key,
  1186. struct futex_hash_bucket *hb)
  1187. {
  1188. get_futex_key_refs(key);
  1189. q->key = *key;
  1190. __unqueue_futex(q);
  1191. WARN_ON(!q->rt_waiter);
  1192. q->rt_waiter = NULL;
  1193. q->lock_ptr = &hb->lock;
  1194. wake_up_state(q->task, TASK_NORMAL);
  1195. }
  1196. /**
  1197. * futex_proxy_trylock_atomic() - Attempt an atomic lock for the top waiter
  1198. * @pifutex: the user address of the to futex
  1199. * @hb1: the from futex hash bucket, must be locked by the caller
  1200. * @hb2: the to futex hash bucket, must be locked by the caller
  1201. * @key1: the from futex key
  1202. * @key2: the to futex key
  1203. * @ps: address to store the pi_state pointer
  1204. * @set_waiters: force setting the FUTEX_WAITERS bit (1) or not (0)
  1205. *
  1206. * Try and get the lock on behalf of the top waiter if we can do it atomically.
  1207. * Wake the top waiter if we succeed. If the caller specified set_waiters,
  1208. * then direct futex_lock_pi_atomic() to force setting the FUTEX_WAITERS bit.
  1209. * hb1 and hb2 must be held by the caller.
  1210. *
  1211. * Returns:
  1212. * 0 - failed to acquire the lock atomicly
  1213. * >0 - acquired the lock, return value is vpid of the top_waiter
  1214. * <0 - error
  1215. */
  1216. static int futex_proxy_trylock_atomic(u32 __user *pifutex,
  1217. struct futex_hash_bucket *hb1,
  1218. struct futex_hash_bucket *hb2,
  1219. union futex_key *key1, union futex_key *key2,
  1220. struct futex_pi_state **ps, int set_waiters)
  1221. {
  1222. struct futex_q *top_waiter = NULL;
  1223. u32 curval;
  1224. int ret, vpid;
  1225. if (get_futex_value_locked(&curval, pifutex))
  1226. return -EFAULT;
  1227. /*
  1228. * Find the top_waiter and determine if there are additional waiters.
  1229. * If the caller intends to requeue more than 1 waiter to pifutex,
  1230. * force futex_lock_pi_atomic() to set the FUTEX_WAITERS bit now,
  1231. * as we have means to handle the possible fault. If not, don't set
  1232. * the bit unecessarily as it will force the subsequent unlock to enter
  1233. * the kernel.
  1234. */
  1235. top_waiter = futex_top_waiter(hb1, key1);
  1236. /* There are no waiters, nothing for us to do. */
  1237. if (!top_waiter)
  1238. return 0;
  1239. /* Ensure we requeue to the expected futex. */
  1240. if (!match_futex(top_waiter->requeue_pi_key, key2))
  1241. return -EINVAL;
  1242. /*
  1243. * Try to take the lock for top_waiter. Set the FUTEX_WAITERS bit in
  1244. * the contended case or if set_waiters is 1. The pi_state is returned
  1245. * in ps in contended cases.
  1246. */
  1247. vpid = task_pid_vnr(top_waiter->task);
  1248. ret = futex_lock_pi_atomic(pifutex, hb2, key2, ps, top_waiter->task,
  1249. set_waiters);
  1250. if (ret == 1) {
  1251. requeue_pi_wake_futex(top_waiter, key2, hb2);
  1252. return vpid;
  1253. }
  1254. return ret;
  1255. }
  1256. /**
  1257. * futex_requeue() - Requeue waiters from uaddr1 to uaddr2
  1258. * @uaddr1: source futex user address
  1259. * @flags: futex flags (FLAGS_SHARED, etc.)
  1260. * @uaddr2: target futex user address
  1261. * @nr_wake: number of waiters to wake (must be 1 for requeue_pi)
  1262. * @nr_requeue: number of waiters to requeue (0-INT_MAX)
  1263. * @cmpval: @uaddr1 expected value (or %NULL)
  1264. * @requeue_pi: if we are attempting to requeue from a non-pi futex to a
  1265. * pi futex (pi to pi requeue is not supported)
  1266. *
  1267. * Requeue waiters on uaddr1 to uaddr2. In the requeue_pi case, try to acquire
  1268. * uaddr2 atomically on behalf of the top waiter.
  1269. *
  1270. * Returns:
  1271. * >=0 - on success, the number of tasks requeued or woken
  1272. * <0 - on error
  1273. */
  1274. static int futex_requeue(u32 __user *uaddr1, unsigned int flags,
  1275. u32 __user *uaddr2, int nr_wake, int nr_requeue,
  1276. u32 *cmpval, int requeue_pi)
  1277. {
  1278. union futex_key key1 = FUTEX_KEY_INIT, key2 = FUTEX_KEY_INIT;
  1279. int drop_count = 0, task_count = 0, ret;
  1280. struct futex_pi_state *pi_state = NULL;
  1281. struct futex_hash_bucket *hb1, *hb2;
  1282. struct plist_head *head1;
  1283. struct futex_q *this, *next;
  1284. if (nr_wake < 0 || nr_requeue < 0)
  1285. return -EINVAL;
  1286. if (requeue_pi) {
  1287. /*
  1288. * Requeue PI only works on two distinct uaddrs. This
  1289. * check is only valid for private futexes. See below.
  1290. */
  1291. if (uaddr1 == uaddr2)
  1292. return -EINVAL;
  1293. /*
  1294. * requeue_pi requires a pi_state, try to allocate it now
  1295. * without any locks in case it fails.
  1296. */
  1297. if (refill_pi_state_cache())
  1298. return -ENOMEM;
  1299. /*
  1300. * requeue_pi must wake as many tasks as it can, up to nr_wake
  1301. * + nr_requeue, since it acquires the rt_mutex prior to
  1302. * returning to userspace, so as to not leave the rt_mutex with
  1303. * waiters and no owner. However, second and third wake-ups
  1304. * cannot be predicted as they involve race conditions with the
  1305. * first wake and a fault while looking up the pi_state. Both
  1306. * pthread_cond_signal() and pthread_cond_broadcast() should
  1307. * use nr_wake=1.
  1308. */
  1309. if (nr_wake != 1)
  1310. return -EINVAL;
  1311. }
  1312. retry:
  1313. ret = get_futex_key(uaddr1, flags & FLAGS_SHARED, &key1, VERIFY_READ);
  1314. if (unlikely(ret != 0))
  1315. goto out;
  1316. ret = get_futex_key(uaddr2, flags & FLAGS_SHARED, &key2,
  1317. requeue_pi ? VERIFY_WRITE : VERIFY_READ);
  1318. if (unlikely(ret != 0))
  1319. goto out_put_key1;
  1320. /*
  1321. * The check above which compares uaddrs is not sufficient for
  1322. * shared futexes. We need to compare the keys:
  1323. */
  1324. if (requeue_pi && match_futex(&key1, &key2)) {
  1325. ret = -EINVAL;
  1326. goto out_put_keys;
  1327. }
  1328. hb1 = hash_futex(&key1);
  1329. hb2 = hash_futex(&key2);
  1330. retry_private:
  1331. double_lock_hb(hb1, hb2);
  1332. if (likely(cmpval != NULL)) {
  1333. u32 curval;
  1334. ret = get_futex_value_locked(&curval, uaddr1);
  1335. if (unlikely(ret)) {
  1336. double_unlock_hb(hb1, hb2);
  1337. ret = get_user(curval, uaddr1);
  1338. if (ret)
  1339. goto out_put_keys;
  1340. if (!(flags & FLAGS_SHARED))
  1341. goto retry_private;
  1342. put_futex_key(&key2);
  1343. put_futex_key(&key1);
  1344. goto retry;
  1345. }
  1346. if (curval != *cmpval) {
  1347. ret = -EAGAIN;
  1348. goto out_unlock;
  1349. }
  1350. }
  1351. if (requeue_pi && (task_count - nr_wake < nr_requeue)) {
  1352. /*
  1353. * Attempt to acquire uaddr2 and wake the top waiter. If we
  1354. * intend to requeue waiters, force setting the FUTEX_WAITERS
  1355. * bit. We force this here where we are able to easily handle
  1356. * faults rather in the requeue loop below.
  1357. */
  1358. ret = futex_proxy_trylock_atomic(uaddr2, hb1, hb2, &key1,
  1359. &key2, &pi_state, nr_requeue);
  1360. /*
  1361. * At this point the top_waiter has either taken uaddr2 or is
  1362. * waiting on it. If the former, then the pi_state will not
  1363. * exist yet, look it up one more time to ensure we have a
  1364. * reference to it. If the lock was taken, ret contains the
  1365. * vpid of the top waiter task.
  1366. */
  1367. if (ret > 0) {
  1368. WARN_ON(pi_state);
  1369. drop_count++;
  1370. task_count++;
  1371. /*
  1372. * If we acquired the lock, then the user
  1373. * space value of uaddr2 should be vpid. It
  1374. * cannot be changed by the top waiter as it
  1375. * is blocked on hb2 lock if it tries to do
  1376. * so. If something fiddled with it behind our
  1377. * back the pi state lookup might unearth
  1378. * it. So we rather use the known value than
  1379. * rereading and handing potential crap to
  1380. * lookup_pi_state.
  1381. */
  1382. ret = lookup_pi_state(ret, hb2, &key2, &pi_state);
  1383. }
  1384. switch (ret) {
  1385. case 0:
  1386. break;
  1387. case -EFAULT:
  1388. free_pi_state(pi_state);
  1389. pi_state = NULL;
  1390. double_unlock_hb(hb1, hb2);
  1391. put_futex_key(&key2);
  1392. put_futex_key(&key1);
  1393. ret = fault_in_user_writeable(uaddr2);
  1394. if (!ret)
  1395. goto retry;
  1396. goto out;
  1397. case -EAGAIN:
  1398. /* The owner was exiting, try again. */
  1399. free_pi_state(pi_state);
  1400. pi_state = NULL;
  1401. double_unlock_hb(hb1, hb2);
  1402. put_futex_key(&key2);
  1403. put_futex_key(&key1);
  1404. cond_resched();
  1405. goto retry;
  1406. default:
  1407. goto out_unlock;
  1408. }
  1409. }
  1410. head1 = &hb1->chain;
  1411. plist_for_each_entry_safe(this, next, head1, list) {
  1412. if (task_count - nr_wake >= nr_requeue)
  1413. break;
  1414. if (!match_futex(&this->key, &key1))
  1415. continue;
  1416. /*
  1417. * FUTEX_WAIT_REQEUE_PI and FUTEX_CMP_REQUEUE_PI should always
  1418. * be paired with each other and no other futex ops.
  1419. *
  1420. * We should never be requeueing a futex_q with a pi_state,
  1421. * which is awaiting a futex_unlock_pi().
  1422. */
  1423. if ((requeue_pi && !this->rt_waiter) ||
  1424. (!requeue_pi && this->rt_waiter) ||
  1425. this->pi_state) {
  1426. ret = -EINVAL;
  1427. break;
  1428. }
  1429. /*
  1430. * Wake nr_wake waiters. For requeue_pi, if we acquired the
  1431. * lock, we already woke the top_waiter. If not, it will be
  1432. * woken by futex_unlock_pi().
  1433. */
  1434. if (++task_count <= nr_wake && !requeue_pi) {
  1435. wake_futex(this);
  1436. continue;
  1437. }
  1438. /* Ensure we requeue to the expected futex for requeue_pi. */
  1439. if (requeue_pi && !match_futex(this->requeue_pi_key, &key2)) {
  1440. ret = -EINVAL;
  1441. break;
  1442. }
  1443. /*
  1444. * Requeue nr_requeue waiters and possibly one more in the case
  1445. * of requeue_pi if we couldn't acquire the lock atomically.
  1446. */
  1447. if (requeue_pi) {
  1448. /* Prepare the waiter to take the rt_mutex. */
  1449. atomic_inc(&pi_state->refcount);
  1450. this->pi_state = pi_state;
  1451. ret = rt_mutex_start_proxy_lock(&pi_state->pi_mutex,
  1452. this->rt_waiter,
  1453. this->task);
  1454. if (ret == 1) {
  1455. /* We got the lock. */
  1456. requeue_pi_wake_futex(this, &key2, hb2);
  1457. drop_count++;
  1458. continue;
  1459. } else if (ret) {
  1460. /* -EDEADLK */
  1461. this->pi_state = NULL;
  1462. free_pi_state(pi_state);
  1463. goto out_unlock;
  1464. }
  1465. }
  1466. requeue_futex(this, hb1, hb2, &key2);
  1467. drop_count++;
  1468. }
  1469. out_unlock:
  1470. free_pi_state(pi_state);
  1471. double_unlock_hb(hb1, hb2);
  1472. /*
  1473. * drop_futex_key_refs() must be called outside the spinlocks. During
  1474. * the requeue we moved futex_q's from the hash bucket at key1 to the
  1475. * one at key2 and updated their key pointer. We no longer need to
  1476. * hold the references to key1.
  1477. */
  1478. while (--drop_count >= 0)
  1479. drop_futex_key_refs(&key1);
  1480. out_put_keys:
  1481. put_futex_key(&key2);
  1482. out_put_key1:
  1483. put_futex_key(&key1);
  1484. out:
  1485. return ret ? ret : task_count;
  1486. }
  1487. /* The key must be already stored in q->key. */
  1488. static inline struct futex_hash_bucket *queue_lock(struct futex_q *q)
  1489. __acquires(&hb->lock)
  1490. {
  1491. struct futex_hash_bucket *hb;
  1492. hb = hash_futex(&q->key);
  1493. q->lock_ptr = &hb->lock;
  1494. spin_lock(&hb->lock);
  1495. return hb;
  1496. }
  1497. static inline void
  1498. queue_unlock(struct futex_q *q, struct futex_hash_bucket *hb)
  1499. __releases(&hb->lock)
  1500. {
  1501. spin_unlock(&hb->lock);
  1502. }
  1503. /**
  1504. * queue_me() - Enqueue the futex_q on the futex_hash_bucket
  1505. * @q: The futex_q to enqueue
  1506. * @hb: The destination hash bucket
  1507. *
  1508. * The hb->lock must be held by the caller, and is released here. A call to
  1509. * queue_me() is typically paired with exactly one call to unqueue_me(). The
  1510. * exceptions involve the PI related operations, which may use unqueue_me_pi()
  1511. * or nothing if the unqueue is done as part of the wake process and the unqueue
  1512. * state is implicit in the state of woken task (see futex_wait_requeue_pi() for
  1513. * an example).
  1514. */
  1515. static inline void queue_me(struct futex_q *q, struct futex_hash_bucket *hb)
  1516. __releases(&hb->lock)
  1517. {
  1518. int prio;
  1519. /*
  1520. * The priority used to register this element is
  1521. * - either the real thread-priority for the real-time threads
  1522. * (i.e. threads with a priority lower than MAX_RT_PRIO)
  1523. * - or MAX_RT_PRIO for non-RT threads.
  1524. * Thus, all RT-threads are woken first in priority order, and
  1525. * the others are woken last, in FIFO order.
  1526. */
  1527. prio = min(current->normal_prio, MAX_RT_PRIO);
  1528. plist_node_init(&q->list, prio);
  1529. plist_add(&q->list, &hb->chain);
  1530. q->task = current;
  1531. spin_unlock(&hb->lock);
  1532. }
  1533. /**
  1534. * unqueue_me() - Remove the futex_q from its futex_hash_bucket
  1535. * @q: The futex_q to unqueue
  1536. *
  1537. * The q->lock_ptr must not be held by the caller. A call to unqueue_me() must
  1538. * be paired with exactly one earlier call to queue_me().
  1539. *
  1540. * Returns:
  1541. * 1 - if the futex_q was still queued (and we removed unqueued it)
  1542. * 0 - if the futex_q was already removed by the waking thread
  1543. */
  1544. static int unqueue_me(struct futex_q *q)
  1545. {
  1546. spinlock_t *lock_ptr;
  1547. int ret = 0;
  1548. /* In the common case we don't take the spinlock, which is nice. */
  1549. retry:
  1550. lock_ptr = q->lock_ptr;
  1551. barrier();
  1552. if (lock_ptr != NULL) {
  1553. spin_lock(lock_ptr);
  1554. /*
  1555. * q->lock_ptr can change between reading it and
  1556. * spin_lock(), causing us to take the wrong lock. This
  1557. * corrects the race condition.
  1558. *
  1559. * Reasoning goes like this: if we have the wrong lock,
  1560. * q->lock_ptr must have changed (maybe several times)
  1561. * between reading it and the spin_lock(). It can
  1562. * change again after the spin_lock() but only if it was
  1563. * already changed before the spin_lock(). It cannot,
  1564. * however, change back to the original value. Therefore
  1565. * we can detect whether we acquired the correct lock.
  1566. */
  1567. if (unlikely(lock_ptr != q->lock_ptr)) {
  1568. spin_unlock(lock_ptr);
  1569. goto retry;
  1570. }
  1571. __unqueue_futex(q);
  1572. BUG_ON(q->pi_state);
  1573. spin_unlock(lock_ptr);
  1574. ret = 1;
  1575. }
  1576. drop_futex_key_refs(&q->key);
  1577. return ret;
  1578. }
  1579. /*
  1580. * PI futexes can not be requeued and must remove themself from the
  1581. * hash bucket. The hash bucket lock (i.e. lock_ptr) is held on entry
  1582. * and dropped here.
  1583. */
  1584. static void unqueue_me_pi(struct futex_q *q)
  1585. __releases(q->lock_ptr)
  1586. {
  1587. __unqueue_futex(q);
  1588. BUG_ON(!q->pi_state);
  1589. free_pi_state(q->pi_state);
  1590. q->pi_state = NULL;
  1591. spin_unlock(q->lock_ptr);
  1592. }
  1593. /*
  1594. * Fixup the pi_state owner with the new owner.
  1595. *
  1596. * Must be called with hash bucket lock held and mm->sem held for non
  1597. * private futexes.
  1598. */
  1599. static int fixup_pi_state_owner(u32 __user *uaddr, struct futex_q *q,
  1600. struct task_struct *newowner)
  1601. {
  1602. u32 newtid = task_pid_vnr(newowner) | FUTEX_WAITERS;
  1603. struct futex_pi_state *pi_state = q->pi_state;
  1604. struct task_struct *oldowner = pi_state->owner;
  1605. u32 uval, uninitialized_var(curval), newval;
  1606. int ret;
  1607. /* Owner died? */
  1608. if (!pi_state->owner)
  1609. newtid |= FUTEX_OWNER_DIED;
  1610. /*
  1611. * We are here either because we stole the rtmutex from the
  1612. * previous highest priority waiter or we are the highest priority
  1613. * waiter but failed to get the rtmutex the first time.
  1614. * We have to replace the newowner TID in the user space variable.
  1615. * This must be atomic as we have to preserve the owner died bit here.
  1616. *
  1617. * Note: We write the user space value _before_ changing the pi_state
  1618. * because we can fault here. Imagine swapped out pages or a fork
  1619. * that marked all the anonymous memory readonly for cow.
  1620. *
  1621. * Modifying pi_state _before_ the user space value would
  1622. * leave the pi_state in an inconsistent state when we fault
  1623. * here, because we need to drop the hash bucket lock to
  1624. * handle the fault. This might be observed in the PID check
  1625. * in lookup_pi_state.
  1626. */
  1627. retry:
  1628. if (get_futex_value_locked(&uval, uaddr))
  1629. goto handle_fault;
  1630. while (1) {
  1631. newval = (uval & FUTEX_OWNER_DIED) | newtid;
  1632. if (cmpxchg_futex_value_locked(&curval, uaddr, uval, newval))
  1633. goto handle_fault;
  1634. if (curval == uval)
  1635. break;
  1636. uval = curval;
  1637. }
  1638. /*
  1639. * We fixed up user space. Now we need to fix the pi_state
  1640. * itself.
  1641. */
  1642. if (pi_state->owner != NULL) {
  1643. raw_spin_lock_irq(&pi_state->owner->pi_lock);
  1644. WARN_ON(list_empty(&pi_state->list));
  1645. list_del_init(&pi_state->list);
  1646. raw_spin_unlock_irq(&pi_state->owner->pi_lock);
  1647. }
  1648. pi_state->owner = newowner;
  1649. raw_spin_lock_irq(&newowner->pi_lock);
  1650. WARN_ON(!list_empty(&pi_state->list));
  1651. list_add(&pi_state->list, &newowner->pi_state_list);
  1652. raw_spin_unlock_irq(&newowner->pi_lock);
  1653. return 0;
  1654. /*
  1655. * To handle the page fault we need to drop the hash bucket
  1656. * lock here. That gives the other task (either the highest priority
  1657. * waiter itself or the task which stole the rtmutex) the
  1658. * chance to try the fixup of the pi_state. So once we are
  1659. * back from handling the fault we need to check the pi_state
  1660. * after reacquiring the hash bucket lock and before trying to
  1661. * do another fixup. When the fixup has been done already we
  1662. * simply return.
  1663. */
  1664. handle_fault:
  1665. spin_unlock(q->lock_ptr);
  1666. ret = fault_in_user_writeable(uaddr);
  1667. spin_lock(q->lock_ptr);
  1668. /*
  1669. * Check if someone else fixed it for us:
  1670. */
  1671. if (pi_state->owner != oldowner)
  1672. return 0;
  1673. if (ret)
  1674. return ret;
  1675. goto retry;
  1676. }
  1677. static long futex_wait_restart(struct restart_block *restart);
  1678. /**
  1679. * fixup_owner() - Post lock pi_state and corner case management
  1680. * @uaddr: user address of the futex
  1681. * @q: futex_q (contains pi_state and access to the rt_mutex)
  1682. * @locked: if the attempt to take the rt_mutex succeeded (1) or not (0)
  1683. *
  1684. * After attempting to lock an rt_mutex, this function is called to cleanup
  1685. * the pi_state owner as well as handle race conditions that may allow us to
  1686. * acquire the lock. Must be called with the hb lock held.
  1687. *
  1688. * Returns:
  1689. * 1 - success, lock taken
  1690. * 0 - success, lock not taken
  1691. * <0 - on error (-EFAULT)
  1692. */
  1693. static int fixup_owner(u32 __user *uaddr, struct futex_q *q, int locked)
  1694. {
  1695. struct task_struct *owner;
  1696. int ret = 0;
  1697. if (locked) {
  1698. /*
  1699. * Got the lock. We might not be the anticipated owner if we
  1700. * did a lock-steal - fix up the PI-state in that case:
  1701. */
  1702. if (q->pi_state->owner != current)
  1703. ret = fixup_pi_state_owner(uaddr, q, current);
  1704. goto out;
  1705. }
  1706. /*
  1707. * Catch the rare case, where the lock was released when we were on the
  1708. * way back before we locked the hash bucket.
  1709. */
  1710. if (q->pi_state->owner == current) {
  1711. /*
  1712. * Try to get the rt_mutex now. This might fail as some other
  1713. * task acquired the rt_mutex after we removed ourself from the
  1714. * rt_mutex waiters list.
  1715. */
  1716. if (rt_mutex_trylock(&q->pi_state->pi_mutex)) {
  1717. locked = 1;
  1718. goto out;
  1719. }
  1720. /*
  1721. * pi_state is incorrect, some other task did a lock steal and
  1722. * we returned due to timeout or signal without taking the
  1723. * rt_mutex. Too late.
  1724. */
  1725. raw_spin_lock(&q->pi_state->pi_mutex.wait_lock);
  1726. owner = rt_mutex_owner(&q->pi_state->pi_mutex);
  1727. if (!owner)
  1728. owner = rt_mutex_next_owner(&q->pi_state->pi_mutex);
  1729. raw_spin_unlock(&q->pi_state->pi_mutex.wait_lock);
  1730. ret = fixup_pi_state_owner(uaddr, q, owner);
  1731. goto out;
  1732. }
  1733. /*
  1734. * Paranoia check. If we did not take the lock, then we should not be
  1735. * the owner of the rt_mutex.
  1736. */
  1737. if (rt_mutex_owner(&q->pi_state->pi_mutex) == current)
  1738. printk(KERN_ERR "fixup_owner: ret = %d pi-mutex: %p "
  1739. "pi-state %p\n", ret,
  1740. q->pi_state->pi_mutex.owner,
  1741. q->pi_state->owner);
  1742. out:
  1743. return ret ? ret : locked;
  1744. }
  1745. /**
  1746. * futex_wait_queue_me() - queue_me() and wait for wakeup, timeout, or signal
  1747. * @hb: the futex hash bucket, must be locked by the caller
  1748. * @q: the futex_q to queue up on
  1749. * @timeout: the prepared hrtimer_sleeper, or null for no timeout
  1750. */
  1751. static void futex_wait_queue_me(struct futex_hash_bucket *hb, struct futex_q *q,
  1752. struct hrtimer_sleeper *timeout)
  1753. {
  1754. /*
  1755. * The task state is guaranteed to be set before another task can
  1756. * wake it. set_current_state() is implemented using set_mb() and
  1757. * queue_me() calls spin_unlock() upon completion, both serializing
  1758. * access to the hash list and forcing another memory barrier.
  1759. */
  1760. set_current_state(TASK_INTERRUPTIBLE);
  1761. queue_me(q, hb);
  1762. /* Arm the timer */
  1763. if (timeout) {
  1764. hrtimer_start_expires(&timeout->timer, HRTIMER_MODE_ABS);
  1765. if (!hrtimer_active(&timeout->timer))
  1766. timeout->task = NULL;
  1767. }
  1768. /*
  1769. * If we have been removed from the hash list, then another task
  1770. * has tried to wake us, and we can skip the call to schedule().
  1771. */
  1772. if (likely(!plist_node_empty(&q->list))) {
  1773. /*
  1774. * If the timer has already expired, current will already be
  1775. * flagged for rescheduling. Only call schedule if there
  1776. * is no timeout, or if it has yet to expire.
  1777. */
  1778. if (!timeout || timeout->task)
  1779. freezable_schedule();
  1780. }
  1781. __set_current_state(TASK_RUNNING);
  1782. }
  1783. /**
  1784. * futex_wait_setup() - Prepare to wait on a futex
  1785. * @uaddr: the futex userspace address
  1786. * @val: the expected value
  1787. * @flags: futex flags (FLAGS_SHARED, etc.)
  1788. * @q: the associated futex_q
  1789. * @hb: storage for hash_bucket pointer to be returned to caller
  1790. *
  1791. * Setup the futex_q and locate the hash_bucket. Get the futex value and
  1792. * compare it with the expected value. Handle atomic faults internally.
  1793. * Return with the hb lock held and a q.key reference on success, and unlocked
  1794. * with no q.key reference on failure.
  1795. *
  1796. * Returns:
  1797. * 0 - uaddr contains val and hb has been locked
  1798. * <1 - -EFAULT or -EWOULDBLOCK (uaddr does not contain val) and hb is unlocked
  1799. */
  1800. static int futex_wait_setup(u32 __user *uaddr, u32 val, unsigned int flags,
  1801. struct futex_q *q, struct futex_hash_bucket **hb)
  1802. {
  1803. u32 uval;
  1804. int ret;
  1805. /*
  1806. * Access the page AFTER the hash-bucket is locked.
  1807. * Order is important:
  1808. *
  1809. * Userspace waiter: val = var; if (cond(val)) futex_wait(&var, val);
  1810. * Userspace waker: if (cond(var)) { var = new; futex_wake(&var); }
  1811. *
  1812. * The basic logical guarantee of a futex is that it blocks ONLY
  1813. * if cond(var) is known to be true at the time of blocking, for
  1814. * any cond. If we locked the hash-bucket after testing *uaddr, that
  1815. * would open a race condition where we could block indefinitely with
  1816. * cond(var) false, which would violate the guarantee.
  1817. *
  1818. * On the other hand, we insert q and release the hash-bucket only
  1819. * after testing *uaddr. This guarantees that futex_wait() will NOT
  1820. * absorb a wakeup if *uaddr does not match the desired values
  1821. * while the syscall executes.
  1822. */
  1823. retry:
  1824. ret = get_futex_key(uaddr, flags & FLAGS_SHARED, &q->key, VERIFY_READ);
  1825. if (unlikely(ret != 0))
  1826. return ret;
  1827. retry_private:
  1828. *hb = queue_lock(q);
  1829. ret = get_futex_value_locked(&uval, uaddr);
  1830. if (ret) {
  1831. queue_unlock(q, *hb);
  1832. ret = get_user(uval, uaddr);
  1833. if (ret)
  1834. goto out;
  1835. if (!(flags & FLAGS_SHARED))
  1836. goto retry_private;
  1837. put_futex_key(&q->key);
  1838. goto retry;
  1839. }
  1840. if (uval != val) {
  1841. queue_unlock(q, *hb);
  1842. ret = -EWOULDBLOCK;
  1843. }
  1844. out:
  1845. if (ret)
  1846. put_futex_key(&q->key);
  1847. return ret;
  1848. }
  1849. static int futex_wait(u32 __user *uaddr, unsigned int flags, u32 val,
  1850. ktime_t *abs_time, u32 bitset)
  1851. {
  1852. struct hrtimer_sleeper timeout, *to = NULL;
  1853. struct restart_block *restart;
  1854. struct futex_hash_bucket *hb;
  1855. struct futex_q q = futex_q_init;
  1856. int ret;
  1857. if (!bitset)
  1858. return -EINVAL;
  1859. q.bitset = bitset;
  1860. if (abs_time) {
  1861. to = &timeout;
  1862. hrtimer_init_on_stack(&to->timer, (flags & FLAGS_CLOCKRT) ?
  1863. CLOCK_REALTIME : CLOCK_MONOTONIC,
  1864. HRTIMER_MODE_ABS);
  1865. hrtimer_init_sleeper(to, current);
  1866. hrtimer_set_expires_range_ns(&to->timer, *abs_time,
  1867. current->timer_slack_ns);
  1868. }
  1869. retry:
  1870. /*
  1871. * Prepare to wait on uaddr. On success, holds hb lock and increments
  1872. * q.key refs.
  1873. */
  1874. ret = futex_wait_setup(uaddr, val, flags, &q, &hb);
  1875. if (ret)
  1876. goto out;
  1877. /* queue_me and wait for wakeup, timeout, or a signal. */
  1878. futex_wait_queue_me(hb, &q, to);
  1879. /* If we were woken (and unqueued), we succeeded, whatever. */
  1880. ret = 0;
  1881. /* unqueue_me() drops q.key ref */
  1882. if (!unqueue_me(&q))
  1883. goto out;
  1884. ret = -ETIMEDOUT;
  1885. if (to && !to->task)
  1886. goto out;
  1887. /*
  1888. * We expect signal_pending(current), but we might be the
  1889. * victim of a spurious wakeup as well.
  1890. */
  1891. if (!signal_pending(current))
  1892. goto retry;
  1893. ret = -ERESTARTSYS;
  1894. if (!abs_time)
  1895. goto out;
  1896. restart = &current_thread_info()->restart_block;
  1897. restart->fn = futex_wait_restart;
  1898. restart->futex.uaddr = uaddr;
  1899. restart->futex.val = val;
  1900. restart->futex.time = abs_time->tv64;
  1901. restart->futex.bitset = bitset;
  1902. restart->futex.flags = flags | FLAGS_HAS_TIMEOUT;
  1903. ret = -ERESTART_RESTARTBLOCK;
  1904. out:
  1905. if (to) {
  1906. hrtimer_cancel(&to->timer);
  1907. destroy_hrtimer_on_stack(&to->timer);
  1908. }
  1909. return ret;
  1910. }
  1911. static long futex_wait_restart(struct restart_block *restart)
  1912. {
  1913. u32 __user *uaddr = restart->futex.uaddr;
  1914. ktime_t t, *tp = NULL;
  1915. if (restart->futex.flags & FLAGS_HAS_TIMEOUT) {
  1916. t.tv64 = restart->futex.time;
  1917. tp = &t;
  1918. }
  1919. restart->fn = do_no_restart_syscall;
  1920. return (long)futex_wait(uaddr, restart->futex.flags,
  1921. restart->futex.val, tp, restart->futex.bitset);
  1922. }
  1923. /*
  1924. * Userspace tried a 0 -> TID atomic transition of the futex value
  1925. * and failed. The kernel side here does the whole locking operation:
  1926. * if there are waiters then it will block, it does PI, etc. (Due to
  1927. * races the kernel might see a 0 value of the futex too.)
  1928. */
  1929. static int futex_lock_pi(u32 __user *uaddr, unsigned int flags, int detect,
  1930. ktime_t *time, int trylock)
  1931. {
  1932. struct hrtimer_sleeper timeout, *to = NULL;
  1933. struct futex_hash_bucket *hb;
  1934. struct futex_q q = futex_q_init;
  1935. int res, ret;
  1936. if (refill_pi_state_cache())
  1937. return -ENOMEM;
  1938. if (time) {
  1939. to = &timeout;
  1940. hrtimer_init_on_stack(&to->timer, CLOCK_REALTIME,
  1941. HRTIMER_MODE_ABS);
  1942. hrtimer_init_sleeper(to, current);
  1943. hrtimer_set_expires(&to->timer, *time);
  1944. }
  1945. retry:
  1946. ret = get_futex_key(uaddr, flags & FLAGS_SHARED, &q.key, VERIFY_WRITE);
  1947. if (unlikely(ret != 0))
  1948. goto out;
  1949. retry_private:
  1950. hb = queue_lock(&q);
  1951. ret = futex_lock_pi_atomic(uaddr, hb, &q.key, &q.pi_state, current, 0);
  1952. if (unlikely(ret)) {
  1953. switch (ret) {
  1954. case 1:
  1955. /* We got the lock. */
  1956. ret = 0;
  1957. goto out_unlock_put_key;
  1958. case -EFAULT:
  1959. goto uaddr_faulted;
  1960. case -EAGAIN:
  1961. /*
  1962. * Task is exiting and we just wait for the
  1963. * exit to complete.
  1964. */
  1965. queue_unlock(&q, hb);
  1966. put_futex_key(&q.key);
  1967. cond_resched();
  1968. goto retry;
  1969. default:
  1970. goto out_unlock_put_key;
  1971. }
  1972. }
  1973. /*
  1974. * Only actually queue now that the atomic ops are done:
  1975. */
  1976. queue_me(&q, hb);
  1977. WARN_ON(!q.pi_state);
  1978. /*
  1979. * Block on the PI mutex:
  1980. */
  1981. if (!trylock) {
  1982. ret = rt_mutex_timed_futex_lock(&q.pi_state->pi_mutex, to);
  1983. } else {
  1984. ret = rt_mutex_trylock(&q.pi_state->pi_mutex);
  1985. /* Fixup the trylock return value: */
  1986. ret = ret ? 0 : -EWOULDBLOCK;
  1987. }
  1988. spin_lock(q.lock_ptr);
  1989. /*
  1990. * Fixup the pi_state owner and possibly acquire the lock if we
  1991. * haven't already.
  1992. */
  1993. res = fixup_owner(uaddr, &q, !ret);
  1994. /*
  1995. * If fixup_owner() returned an error, proprogate that. If it acquired
  1996. * the lock, clear our -ETIMEDOUT or -EINTR.
  1997. */
  1998. if (res)
  1999. ret = (res < 0) ? res : 0;
  2000. /*
  2001. * If fixup_owner() faulted and was unable to handle the fault, unlock
  2002. * it and return the fault to userspace.
  2003. */
  2004. if (ret && (rt_mutex_owner(&q.pi_state->pi_mutex) == current))
  2005. rt_mutex_unlock(&q.pi_state->pi_mutex);
  2006. /* Unqueue and drop the lock */
  2007. unqueue_me_pi(&q);
  2008. goto out_put_key;
  2009. out_unlock_put_key:
  2010. queue_unlock(&q, hb);
  2011. out_put_key:
  2012. put_futex_key(&q.key);
  2013. out:
  2014. if (to)
  2015. destroy_hrtimer_on_stack(&to->timer);
  2016. return ret != -EINTR ? ret : -ERESTARTNOINTR;
  2017. uaddr_faulted:
  2018. queue_unlock(&q, hb);
  2019. ret = fault_in_user_writeable(uaddr);
  2020. if (ret)
  2021. goto out_put_key;
  2022. if (!(flags & FLAGS_SHARED))
  2023. goto retry_private;
  2024. put_futex_key(&q.key);
  2025. goto retry;
  2026. }
  2027. /*
  2028. * Userspace attempted a TID -> 0 atomic transition, and failed.
  2029. * This is the in-kernel slowpath: we look up the PI state (if any),
  2030. * and do the rt-mutex unlock.
  2031. */
  2032. static int futex_unlock_pi(u32 __user *uaddr, unsigned int flags)
  2033. {
  2034. struct futex_hash_bucket *hb;
  2035. struct futex_q *this, *next;
  2036. struct plist_head *head;
  2037. union futex_key key = FUTEX_KEY_INIT;
  2038. u32 uval, vpid = task_pid_vnr(current);
  2039. int ret;
  2040. retry:
  2041. if (get_user(uval, uaddr))
  2042. return -EFAULT;
  2043. /*
  2044. * We release only a lock we actually own:
  2045. */
  2046. if ((uval & FUTEX_TID_MASK) != vpid)
  2047. return -EPERM;
  2048. ret = get_futex_key(uaddr, flags & FLAGS_SHARED, &key, VERIFY_WRITE);
  2049. if (unlikely(ret != 0))
  2050. goto out;
  2051. hb = hash_futex(&key);
  2052. spin_lock(&hb->lock);
  2053. /*
  2054. * To avoid races, try to do the TID -> 0 atomic transition
  2055. * again. If it succeeds then we can return without waking
  2056. * anyone else up. We only try this if neither the waiters nor
  2057. * the owner died bit are set.
  2058. */
  2059. if (!(uval & ~FUTEX_TID_MASK) &&
  2060. cmpxchg_futex_value_locked(&uval, uaddr, vpid, 0))
  2061. goto pi_faulted;
  2062. /*
  2063. * Rare case: we managed to release the lock atomically,
  2064. * no need to wake anyone else up:
  2065. */
  2066. if (unlikely(uval == vpid))
  2067. goto out_unlock;
  2068. /*
  2069. * Ok, other tasks may need to be woken up - check waiters
  2070. * and do the wakeup if necessary:
  2071. */
  2072. head = &hb->chain;
  2073. plist_for_each_entry_safe(this, next, head, list) {
  2074. if (!match_futex (&this->key, &key))
  2075. continue;
  2076. ret = wake_futex_pi(uaddr, uval, this);
  2077. /*
  2078. * The atomic access to the futex value
  2079. * generated a pagefault, so retry the
  2080. * user-access and the wakeup:
  2081. */
  2082. if (ret == -EFAULT)
  2083. goto pi_faulted;
  2084. goto out_unlock;
  2085. }
  2086. /*
  2087. * No waiters - kernel unlocks the futex:
  2088. */
  2089. ret = unlock_futex_pi(uaddr, uval);
  2090. if (ret == -EFAULT)
  2091. goto pi_faulted;
  2092. out_unlock:
  2093. spin_unlock(&hb->lock);
  2094. put_futex_key(&key);
  2095. out:
  2096. return ret;
  2097. pi_faulted:
  2098. spin_unlock(&hb->lock);
  2099. put_futex_key(&key);
  2100. ret = fault_in_user_writeable(uaddr);
  2101. if (!ret)
  2102. goto retry;
  2103. return ret;
  2104. }
  2105. /**
  2106. * handle_early_requeue_pi_wakeup() - Detect early wakeup on the initial futex
  2107. * @hb: the hash_bucket futex_q was original enqueued on
  2108. * @q: the futex_q woken while waiting to be requeued
  2109. * @key2: the futex_key of the requeue target futex
  2110. * @timeout: the timeout associated with the wait (NULL if none)
  2111. *
  2112. * Detect if the task was woken on the initial futex as opposed to the requeue
  2113. * target futex. If so, determine if it was a timeout or a signal that caused
  2114. * the wakeup and return the appropriate error code to the caller. Must be
  2115. * called with the hb lock held.
  2116. *
  2117. * Returns
  2118. * 0 - no early wakeup detected
  2119. * <0 - -ETIMEDOUT or -ERESTARTNOINTR
  2120. */
  2121. static inline
  2122. int handle_early_requeue_pi_wakeup(struct futex_hash_bucket *hb,
  2123. struct futex_q *q, union futex_key *key2,
  2124. struct hrtimer_sleeper *timeout)
  2125. {
  2126. int ret = 0;
  2127. /*
  2128. * With the hb lock held, we avoid races while we process the wakeup.
  2129. * We only need to hold hb (and not hb2) to ensure atomicity as the
  2130. * wakeup code can't change q.key from uaddr to uaddr2 if we hold hb.
  2131. * It can't be requeued from uaddr2 to something else since we don't
  2132. * support a PI aware source futex for requeue.
  2133. */
  2134. if (!match_futex(&q->key, key2)) {
  2135. WARN_ON(q->lock_ptr && (&hb->lock != q->lock_ptr));
  2136. /*
  2137. * We were woken prior to requeue by a timeout or a signal.
  2138. * Unqueue the futex_q and determine which it was.
  2139. */
  2140. plist_del(&q->list, &hb->chain);
  2141. /* Handle spurious wakeups gracefully */
  2142. ret = -EWOULDBLOCK;
  2143. if (timeout && !timeout->task)
  2144. ret = -ETIMEDOUT;
  2145. else if (signal_pending(current))
  2146. ret = -ERESTARTNOINTR;
  2147. }
  2148. return ret;
  2149. }
  2150. /**
  2151. * futex_wait_requeue_pi() - Wait on uaddr and take uaddr2
  2152. * @uaddr: the futex we initially wait on (non-pi)
  2153. * @flags: futex flags (FLAGS_SHARED, FLAGS_CLOCKRT, etc.), they must be
  2154. * the same type, no requeueing from private to shared, etc.
  2155. * @val: the expected value of uaddr
  2156. * @abs_time: absolute timeout
  2157. * @bitset: 32 bit wakeup bitset set by userspace, defaults to all
  2158. * @clockrt: whether to use CLOCK_REALTIME (1) or CLOCK_MONOTONIC (0)
  2159. * @uaddr2: the pi futex we will take prior to returning to user-space
  2160. *
  2161. * The caller will wait on uaddr and will be requeued by futex_requeue() to
  2162. * uaddr2 which must be PI aware and unique from uaddr. Normal wakeup will wake
  2163. * on uaddr2 and complete the acquisition of the rt_mutex prior to returning to
  2164. * userspace. This ensures the rt_mutex maintains an owner when it has waiters;
  2165. * without one, the pi logic would not know which task to boost/deboost, if
  2166. * there was a need to.
  2167. *
  2168. * We call schedule in futex_wait_queue_me() when we enqueue and return there
  2169. * via the following:
  2170. * 1) wakeup on uaddr2 after an atomic lock acquisition by futex_requeue()
  2171. * 2) wakeup on uaddr2 after a requeue
  2172. * 3) signal
  2173. * 4) timeout
  2174. *
  2175. * If 3, cleanup and return -ERESTARTNOINTR.
  2176. *
  2177. * If 2, we may then block on trying to take the rt_mutex and return via:
  2178. * 5) successful lock
  2179. * 6) signal
  2180. * 7) timeout
  2181. * 8) other lock acquisition failure
  2182. *
  2183. * If 6, return -EWOULDBLOCK (restarting the syscall would do the same).
  2184. *
  2185. * If 4 or 7, we cleanup and return with -ETIMEDOUT.
  2186. *
  2187. * Returns:
  2188. * 0 - On success
  2189. * <0 - On error
  2190. */
  2191. static int futex_wait_requeue_pi(u32 __user *uaddr, unsigned int flags,
  2192. u32 val, ktime_t *abs_time, u32 bitset,
  2193. u32 __user *uaddr2)
  2194. {
  2195. struct hrtimer_sleeper timeout, *to = NULL;
  2196. struct rt_mutex_waiter rt_waiter;
  2197. struct rt_mutex *pi_mutex = NULL;
  2198. struct futex_hash_bucket *hb;
  2199. union futex_key key2 = FUTEX_KEY_INIT;
  2200. struct futex_q q = futex_q_init;
  2201. int res, ret;
  2202. if (uaddr == uaddr2)
  2203. return -EINVAL;
  2204. if (!bitset)
  2205. return -EINVAL;
  2206. if (abs_time) {
  2207. to = &timeout;
  2208. hrtimer_init_on_stack(&to->timer, (flags & FLAGS_CLOCKRT) ?
  2209. CLOCK_REALTIME : CLOCK_MONOTONIC,
  2210. HRTIMER_MODE_ABS);
  2211. hrtimer_init_sleeper(to, current);
  2212. hrtimer_set_expires_range_ns(&to->timer, *abs_time,
  2213. current->timer_slack_ns);
  2214. }
  2215. /*
  2216. * The waiter is allocated on our stack, manipulated by the requeue
  2217. * code while we sleep on uaddr.
  2218. */
  2219. debug_rt_mutex_init_waiter(&rt_waiter);
  2220. RB_CLEAR_NODE(&rt_waiter.pi_tree_entry);
  2221. RB_CLEAR_NODE(&rt_waiter.tree_entry);
  2222. rt_waiter.task = NULL;
  2223. ret = get_futex_key(uaddr2, flags & FLAGS_SHARED, &key2, VERIFY_WRITE);
  2224. if (unlikely(ret != 0))
  2225. goto out;
  2226. q.bitset = bitset;
  2227. q.rt_waiter = &rt_waiter;
  2228. q.requeue_pi_key = &key2;
  2229. /*
  2230. * Prepare to wait on uaddr. On success, increments q.key (key1) ref
  2231. * count.
  2232. */
  2233. ret = futex_wait_setup(uaddr, val, flags, &q, &hb);
  2234. if (ret)
  2235. goto out_key2;
  2236. /*
  2237. * The check above which compares uaddrs is not sufficient for
  2238. * shared futexes. We need to compare the keys:
  2239. */
  2240. if (match_futex(&q.key, &key2)) {
  2241. queue_unlock(&q, hb);
  2242. ret = -EINVAL;
  2243. goto out_put_keys;
  2244. }
  2245. /* Queue the futex_q, drop the hb lock, wait for wakeup. */
  2246. futex_wait_queue_me(hb, &q, to);
  2247. spin_lock(&hb->lock);
  2248. ret = handle_early_requeue_pi_wakeup(hb, &q, &key2, to);
  2249. spin_unlock(&hb->lock);
  2250. if (ret)
  2251. goto out_put_keys;
  2252. /*
  2253. * In order for us to be here, we know our q.key == key2, and since
  2254. * we took the hb->lock above, we also know that futex_requeue() has
  2255. * completed and we no longer have to concern ourselves with a wakeup
  2256. * race with the atomic proxy lock acquisition by the requeue code. The
  2257. * futex_requeue dropped our key1 reference and incremented our key2
  2258. * reference count.
  2259. */
  2260. /* Check if the requeue code acquired the second futex for us. */
  2261. if (!q.rt_waiter) {
  2262. /*
  2263. * Got the lock. We might not be the anticipated owner if we
  2264. * did a lock-steal - fix up the PI-state in that case.
  2265. */
  2266. if (q.pi_state && (q.pi_state->owner != current)) {
  2267. spin_lock(q.lock_ptr);
  2268. ret = fixup_pi_state_owner(uaddr2, &q, current);
  2269. spin_unlock(q.lock_ptr);
  2270. }
  2271. } else {
  2272. /*
  2273. * We have been woken up by futex_unlock_pi(), a timeout, or a
  2274. * signal. futex_unlock_pi() will not destroy the lock_ptr nor
  2275. * the pi_state.
  2276. */
  2277. WARN_ON(!q.pi_state);
  2278. pi_mutex = &q.pi_state->pi_mutex;
  2279. ret = rt_mutex_finish_proxy_lock(pi_mutex, to, &rt_waiter);
  2280. debug_rt_mutex_free_waiter(&rt_waiter);
  2281. spin_lock(q.lock_ptr);
  2282. /*
  2283. * Fixup the pi_state owner and possibly acquire the lock if we
  2284. * haven't already.
  2285. */
  2286. res = fixup_owner(uaddr2, &q, !ret);
  2287. /*
  2288. * If fixup_owner() returned an error, proprogate that. If it
  2289. * acquired the lock, clear -ETIMEDOUT or -EINTR.
  2290. */
  2291. if (res)
  2292. ret = (res < 0) ? res : 0;
  2293. /* Unqueue and drop the lock. */
  2294. unqueue_me_pi(&q);
  2295. }
  2296. /*
  2297. * If fixup_pi_state_owner() faulted and was unable to handle the
  2298. * fault, unlock the rt_mutex and return the fault to userspace.
  2299. */
  2300. if (ret == -EFAULT) {
  2301. if (pi_mutex && rt_mutex_owner(pi_mutex) == current)
  2302. rt_mutex_unlock(pi_mutex);
  2303. } else if (ret == -EINTR) {
  2304. /*
  2305. * We've already been requeued, but cannot restart by calling
  2306. * futex_lock_pi() directly. We could restart this syscall, but
  2307. * it would detect that the user space "val" changed and return
  2308. * -EWOULDBLOCK. Save the overhead of the restart and return
  2309. * -EWOULDBLOCK directly.
  2310. */
  2311. ret = -EWOULDBLOCK;
  2312. }
  2313. out_put_keys:
  2314. put_futex_key(&q.key);
  2315. out_key2:
  2316. put_futex_key(&key2);
  2317. out:
  2318. if (to) {
  2319. hrtimer_cancel(&to->timer);
  2320. destroy_hrtimer_on_stack(&to->timer);
  2321. }
  2322. return ret;
  2323. }
  2324. /*
  2325. * Support for robust futexes: the kernel cleans up held futexes at
  2326. * thread exit time.
  2327. *
  2328. * Implementation: user-space maintains a per-thread list of locks it
  2329. * is holding. Upon do_exit(), the kernel carefully walks this list,
  2330. * and marks all locks that are owned by this thread with the
  2331. * FUTEX_OWNER_DIED bit, and wakes up a waiter (if any). The list is
  2332. * always manipulated with the lock held, so the list is private and
  2333. * per-thread. Userspace also maintains a per-thread 'list_op_pending'
  2334. * field, to allow the kernel to clean up if the thread dies after
  2335. * acquiring the lock, but just before it could have added itself to
  2336. * the list. There can only be one such pending lock.
  2337. */
  2338. /**
  2339. * sys_set_robust_list() - Set the robust-futex list head of a task
  2340. * @head: pointer to the list-head
  2341. * @len: length of the list-head, as userspace expects
  2342. */
  2343. SYSCALL_DEFINE2(set_robust_list, struct robust_list_head __user *, head,
  2344. size_t, len)
  2345. {
  2346. if (!futex_cmpxchg_enabled)
  2347. return -ENOSYS;
  2348. /*
  2349. * The kernel knows only one size for now:
  2350. */
  2351. if (unlikely(len != sizeof(*head)))
  2352. return -EINVAL;
  2353. current->robust_list = head;
  2354. return 0;
  2355. }
  2356. /**
  2357. * sys_get_robust_list() - Get the robust-futex list head of a task
  2358. * @pid: pid of the process [zero for current task]
  2359. * @head_ptr: pointer to a list-head pointer, the kernel fills it in
  2360. * @len_ptr: pointer to a length field, the kernel fills in the header size
  2361. */
  2362. SYSCALL_DEFINE3(get_robust_list, int, pid,
  2363. struct robust_list_head __user * __user *, head_ptr,
  2364. size_t __user *, len_ptr)
  2365. {
  2366. struct robust_list_head __user *head;
  2367. unsigned long ret;
  2368. struct task_struct *p;
  2369. if (!futex_cmpxchg_enabled)
  2370. return -ENOSYS;
  2371. rcu_read_lock();
  2372. ret = -ESRCH;
  2373. if (!pid)
  2374. p = current;
  2375. else {
  2376. p = find_task_by_vpid(pid);
  2377. if (!p)
  2378. goto err_unlock;
  2379. }
  2380. ret = -EPERM;
  2381. if (!ptrace_may_access(p, PTRACE_MODE_READ))
  2382. goto err_unlock;
  2383. head = p->robust_list;
  2384. rcu_read_unlock();
  2385. if (put_user(sizeof(*head), len_ptr))
  2386. return -EFAULT;
  2387. return put_user(head, head_ptr);
  2388. err_unlock:
  2389. rcu_read_unlock();
  2390. return ret;
  2391. }
  2392. /*
  2393. * Process a futex-list entry, check whether it's owned by the
  2394. * dying task, and do notification if so:
  2395. */
  2396. int handle_futex_death(u32 __user *uaddr, struct task_struct *curr,
  2397. bool pi, bool pending_op)
  2398. {
  2399. u32 uval, uninitialized_var(nval), mval;
  2400. /* Futex address must be 32bit aligned */
  2401. if ((((unsigned long)uaddr) % sizeof(*uaddr)) != 0)
  2402. return -1;
  2403. retry:
  2404. if (get_user(uval, uaddr))
  2405. return -1;
  2406. /*
  2407. * Special case for regular (non PI) futexes. The unlock path in
  2408. * user space has two race scenarios:
  2409. *
  2410. * 1. The unlock path releases the user space futex value and
  2411. * before it can execute the futex() syscall to wake up
  2412. * waiters it is killed.
  2413. *
  2414. * 2. A woken up waiter is killed before it can acquire the
  2415. * futex in user space.
  2416. *
  2417. * In both cases the TID validation below prevents a wakeup of
  2418. * potential waiters which can cause these waiters to block
  2419. * forever.
  2420. *
  2421. * In both cases the following conditions are met:
  2422. *
  2423. * 1) task->robust_list->list_op_pending != NULL
  2424. * @pending_op == true
  2425. * 2) User space futex value == 0
  2426. * 3) Regular futex: @pi == false
  2427. *
  2428. * If these conditions are met, it is safe to attempt waking up a
  2429. * potential waiter without touching the user space futex value and
  2430. * trying to set the OWNER_DIED bit. The user space futex value is
  2431. * uncontended and the rest of the user space mutex state is
  2432. * consistent, so a woken waiter will just take over the
  2433. * uncontended futex. Setting the OWNER_DIED bit would create
  2434. * inconsistent state and malfunction of the user space owner died
  2435. * handling.
  2436. */
  2437. if (pending_op && !pi && !uval) {
  2438. futex_wake(uaddr, 1, 1, FUTEX_BITSET_MATCH_ANY);
  2439. return 0;
  2440. }
  2441. if ((uval & FUTEX_TID_MASK) == task_pid_vnr(curr)) {
  2442. /*
  2443. * Ok, this dying thread is truly holding a futex
  2444. * of interest. Set the OWNER_DIED bit atomically
  2445. * via cmpxchg, and if the value had FUTEX_WAITERS
  2446. * set, wake up a waiter (if any). (We have to do a
  2447. * futex_wake() even if OWNER_DIED is already set -
  2448. * to handle the rare but possible case of recursive
  2449. * thread-death.) The rest of the cleanup is done in
  2450. * userspace.
  2451. */
  2452. mval = (uval & FUTEX_WAITERS) | FUTEX_OWNER_DIED;
  2453. /*
  2454. * We are not holding a lock here, but we want to have
  2455. * the pagefault_disable/enable() protection because
  2456. * we want to handle the fault gracefully. If the
  2457. * access fails we try to fault in the futex with R/W
  2458. * verification via get_user_pages. get_user() above
  2459. * does not guarantee R/W access. If that fails we
  2460. * give up and leave the futex locked.
  2461. */
  2462. if (cmpxchg_futex_value_locked(&nval, uaddr, uval, mval)) {
  2463. if (fault_in_user_writeable(uaddr))
  2464. return -1;
  2465. goto retry;
  2466. }
  2467. if (nval != uval)
  2468. goto retry;
  2469. /*
  2470. * Wake robust non-PI futexes here. The wakeup of
  2471. * PI futexes happens in exit_pi_state():
  2472. */
  2473. if (!pi && (uval & FUTEX_WAITERS))
  2474. futex_wake(uaddr, 1, 1, FUTEX_BITSET_MATCH_ANY);
  2475. }
  2476. return 0;
  2477. }
  2478. /*
  2479. * Fetch a robust-list pointer. Bit 0 signals PI futexes:
  2480. */
  2481. static inline int fetch_robust_entry(struct robust_list __user **entry,
  2482. struct robust_list __user * __user *head,
  2483. unsigned int *pi)
  2484. {
  2485. unsigned long uentry;
  2486. if (get_user(uentry, (unsigned long __user *)head))
  2487. return -EFAULT;
  2488. *entry = (void __user *)(uentry & ~1UL);
  2489. *pi = uentry & 1;
  2490. return 0;
  2491. }
  2492. /*
  2493. * Walk curr->robust_list (very carefully, it's a userspace list!)
  2494. * and mark any locks found there dead, and notify any waiters.
  2495. *
  2496. * We silently return on any sign of list-walking problem.
  2497. */
  2498. void exit_robust_list(struct task_struct *curr)
  2499. {
  2500. struct robust_list_head __user *head = curr->robust_list;
  2501. struct robust_list __user *entry, *next_entry, *pending;
  2502. unsigned int limit = ROBUST_LIST_LIMIT, pi, pip;
  2503. unsigned int uninitialized_var(next_pi);
  2504. unsigned long futex_offset;
  2505. int rc;
  2506. if (!futex_cmpxchg_enabled)
  2507. return;
  2508. /*
  2509. * Fetch the list head (which was registered earlier, via
  2510. * sys_set_robust_list()):
  2511. */
  2512. if (fetch_robust_entry(&entry, &head->list.next, &pi))
  2513. return;
  2514. /*
  2515. * Fetch the relative futex offset:
  2516. */
  2517. if (get_user(futex_offset, &head->futex_offset))
  2518. return;
  2519. /*
  2520. * Fetch any possibly pending lock-add first, and handle it
  2521. * if it exists:
  2522. */
  2523. if (fetch_robust_entry(&pending, &head->list_op_pending, &pip))
  2524. return;
  2525. next_entry = NULL; /* avoid warning with gcc */
  2526. while (entry != &head->list) {
  2527. /*
  2528. * Fetch the next entry in the list before calling
  2529. * handle_futex_death:
  2530. */
  2531. rc = fetch_robust_entry(&next_entry, &entry->next, &next_pi);
  2532. /*
  2533. * A pending lock might already be on the list, so
  2534. * don't process it twice:
  2535. */
  2536. if (entry != pending) {
  2537. if (handle_futex_death((void __user *)entry + futex_offset,
  2538. curr, pi, HANDLE_DEATH_LIST))
  2539. return;
  2540. }
  2541. if (rc)
  2542. return;
  2543. entry = next_entry;
  2544. pi = next_pi;
  2545. /*
  2546. * Avoid excessively long or circular lists:
  2547. */
  2548. if (!--limit)
  2549. break;
  2550. cond_resched();
  2551. }
  2552. if (pending) {
  2553. handle_futex_death((void __user *)pending + futex_offset,
  2554. curr, pip, HANDLE_DEATH_PENDING);
  2555. }
  2556. }
  2557. long do_futex(u32 __user *uaddr, int op, u32 val, ktime_t *timeout,
  2558. u32 __user *uaddr2, u32 val2, u32 val3)
  2559. {
  2560. int cmd = op & FUTEX_CMD_MASK;
  2561. unsigned int flags = 0;
  2562. if (!(op & FUTEX_PRIVATE_FLAG))
  2563. flags |= FLAGS_SHARED;
  2564. if (op & FUTEX_CLOCK_REALTIME) {
  2565. flags |= FLAGS_CLOCKRT;
  2566. if (cmd != FUTEX_WAIT_BITSET && cmd != FUTEX_WAIT_REQUEUE_PI)
  2567. return -ENOSYS;
  2568. }
  2569. switch (cmd) {
  2570. case FUTEX_LOCK_PI:
  2571. case FUTEX_UNLOCK_PI:
  2572. case FUTEX_TRYLOCK_PI:
  2573. case FUTEX_WAIT_REQUEUE_PI:
  2574. case FUTEX_CMP_REQUEUE_PI:
  2575. if (!futex_cmpxchg_enabled)
  2576. return -ENOSYS;
  2577. }
  2578. switch (cmd) {
  2579. case FUTEX_WAIT:
  2580. val3 = FUTEX_BITSET_MATCH_ANY;
  2581. case FUTEX_WAIT_BITSET:
  2582. return futex_wait(uaddr, flags, val, timeout, val3);
  2583. case FUTEX_WAKE:
  2584. val3 = FUTEX_BITSET_MATCH_ANY;
  2585. case FUTEX_WAKE_BITSET:
  2586. return futex_wake(uaddr, flags, val, val3);
  2587. case FUTEX_REQUEUE:
  2588. return futex_requeue(uaddr, flags, uaddr2, val, val2, NULL, 0);
  2589. case FUTEX_CMP_REQUEUE:
  2590. return futex_requeue(uaddr, flags, uaddr2, val, val2, &val3, 0);
  2591. case FUTEX_WAKE_OP:
  2592. return futex_wake_op(uaddr, flags, uaddr2, val, val2, val3);
  2593. case FUTEX_LOCK_PI:
  2594. return futex_lock_pi(uaddr, flags, val, timeout, 0);
  2595. case FUTEX_UNLOCK_PI:
  2596. return futex_unlock_pi(uaddr, flags);
  2597. case FUTEX_TRYLOCK_PI:
  2598. return futex_lock_pi(uaddr, flags, 0, timeout, 1);
  2599. case FUTEX_WAIT_REQUEUE_PI:
  2600. val3 = FUTEX_BITSET_MATCH_ANY;
  2601. return futex_wait_requeue_pi(uaddr, flags, val, timeout, val3,
  2602. uaddr2);
  2603. case FUTEX_CMP_REQUEUE_PI:
  2604. return futex_requeue(uaddr, flags, uaddr2, val, val2, &val3, 1);
  2605. }
  2606. return -ENOSYS;
  2607. }
  2608. SYSCALL_DEFINE6(futex, u32 __user *, uaddr, int, op, u32, val,
  2609. struct timespec __user *, utime, u32 __user *, uaddr2,
  2610. u32, val3)
  2611. {
  2612. struct timespec ts;
  2613. ktime_t t, *tp = NULL;
  2614. u32 val2 = 0;
  2615. int cmd = op & FUTEX_CMD_MASK;
  2616. if (utime && (cmd == FUTEX_WAIT || cmd == FUTEX_LOCK_PI ||
  2617. cmd == FUTEX_WAIT_BITSET ||
  2618. cmd == FUTEX_WAIT_REQUEUE_PI)) {
  2619. if (copy_from_user(&ts, utime, sizeof(ts)) != 0)
  2620. return -EFAULT;
  2621. if (!timespec_valid(&ts))
  2622. return -EINVAL;
  2623. t = timespec_to_ktime(ts);
  2624. if (cmd == FUTEX_WAIT)
  2625. t = ktime_add_safe(ktime_get(), t);
  2626. tp = &t;
  2627. }
  2628. /*
  2629. * requeue parameter in 'utime' if cmd == FUTEX_*_REQUEUE_*.
  2630. * number of waiters to wake in 'utime' if cmd == FUTEX_WAKE_OP.
  2631. */
  2632. if (cmd == FUTEX_REQUEUE || cmd == FUTEX_CMP_REQUEUE ||
  2633. cmd == FUTEX_CMP_REQUEUE_PI || cmd == FUTEX_WAKE_OP)
  2634. val2 = (u32) (unsigned long) utime;
  2635. return do_futex(uaddr, op, val, tp, uaddr2, val2, val3);
  2636. }
  2637. static int __init futex_init(void)
  2638. {
  2639. u32 curval;
  2640. unsigned int futex_shift;
  2641. unsigned long i;
  2642. #if CONFIG_BASE_SMALL
  2643. futex_hashsize = 16;
  2644. #else
  2645. futex_hashsize = roundup_pow_of_two(256 * num_possible_cpus());
  2646. #endif
  2647. futex_queues = alloc_large_system_hash("futex", sizeof(*futex_queues),
  2648. futex_hashsize, 0,
  2649. futex_hashsize < 256 ? HASH_SMALL : 0,
  2650. &futex_shift, NULL,
  2651. futex_hashsize, futex_hashsize);
  2652. futex_hashsize = 1UL << futex_shift;
  2653. /*
  2654. * This will fail and we want it. Some arch implementations do
  2655. * runtime detection of the futex_atomic_cmpxchg_inatomic()
  2656. * functionality. We want to know that before we call in any
  2657. * of the complex code paths. Also we want to prevent
  2658. * registration of robust lists in that case. NULL is
  2659. * guaranteed to fault and we get -EFAULT on functional
  2660. * implementation, the non-functional ones will return
  2661. * -ENOSYS.
  2662. */
  2663. if (cmpxchg_futex_value_locked(&curval, NULL, 0, 0) == -EFAULT)
  2664. futex_cmpxchg_enabled = 1;
  2665. for (i = 0; i < futex_hashsize; i++) {
  2666. plist_head_init(&futex_queues[i].chain);
  2667. spin_lock_init(&futex_queues[i].lock);
  2668. }
  2669. return 0;
  2670. }
  2671. __initcall(futex_init);