futex.c 107 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569257025712572257325742575257625772578257925802581258225832584258525862587258825892590259125922593259425952596259725982599260026012602260326042605260626072608260926102611261226132614261526162617261826192620262126222623262426252626262726282629263026312632263326342635263626372638263926402641264226432644264526462647264826492650265126522653265426552656265726582659266026612662266326642665266626672668266926702671267226732674267526762677267826792680268126822683268426852686268726882689269026912692269326942695269626972698269927002701270227032704270527062707270827092710271127122713271427152716271727182719272027212722272327242725272627272728272927302731273227332734273527362737273827392740274127422743274427452746274727482749275027512752275327542755275627572758275927602761276227632764276527662767276827692770277127722773277427752776277727782779278027812782278327842785278627872788278927902791279227932794279527962797279827992800280128022803280428052806280728082809281028112812281328142815281628172818281928202821282228232824282528262827282828292830283128322833283428352836283728382839284028412842284328442845284628472848284928502851285228532854285528562857285828592860286128622863286428652866286728682869287028712872287328742875287628772878287928802881288228832884288528862887288828892890289128922893289428952896289728982899290029012902290329042905290629072908290929102911291229132914291529162917291829192920292129222923292429252926292729282929293029312932293329342935293629372938293929402941294229432944294529462947294829492950295129522953295429552956295729582959296029612962296329642965296629672968296929702971297229732974297529762977297829792980298129822983298429852986298729882989299029912992299329942995299629972998299930003001300230033004300530063007300830093010301130123013301430153016301730183019302030213022302330243025302630273028302930303031303230333034303530363037303830393040304130423043304430453046304730483049305030513052305330543055305630573058305930603061306230633064306530663067306830693070307130723073307430753076307730783079308030813082308330843085308630873088308930903091309230933094309530963097309830993100310131023103310431053106310731083109311031113112311331143115311631173118311931203121312231233124312531263127312831293130313131323133313431353136313731383139314031413142314331443145314631473148314931503151315231533154315531563157315831593160316131623163316431653166316731683169317031713172317331743175317631773178317931803181318231833184318531863187318831893190319131923193319431953196319731983199320032013202320332043205320632073208320932103211321232133214321532163217321832193220322132223223322432253226322732283229323032313232323332343235323632373238323932403241324232433244324532463247324832493250325132523253325432553256325732583259326032613262326332643265326632673268326932703271327232733274327532763277327832793280328132823283328432853286328732883289329032913292329332943295329632973298329933003301330233033304330533063307330833093310331133123313331433153316331733183319332033213322332333243325332633273328332933303331333233333334333533363337333833393340334133423343334433453346334733483349335033513352335333543355335633573358335933603361336233633364336533663367336833693370337133723373337433753376337733783379338033813382338333843385338633873388338933903391339233933394339533963397339833993400340134023403340434053406340734083409341034113412341334143415341634173418341934203421342234233424342534263427342834293430343134323433343434353436343734383439344034413442344334443445344634473448344934503451345234533454345534563457345834593460346134623463346434653466346734683469347034713472347334743475347634773478347934803481348234833484348534863487348834893490349134923493349434953496349734983499350035013502350335043505350635073508350935103511351235133514351535163517351835193520352135223523352435253526352735283529353035313532353335343535353635373538353935403541354235433544354535463547354835493550355135523553355435553556355735583559356035613562356335643565356635673568356935703571357235733574357535763577357835793580358135823583358435853586358735883589359035913592359335943595359635973598359936003601360236033604360536063607360836093610361136123613361436153616361736183619362036213622362336243625362636273628362936303631363236333634363536363637363836393640364136423643364436453646364736483649365036513652365336543655365636573658365936603661366236633664366536663667366836693670367136723673367436753676367736783679368036813682368336843685368636873688368936903691369236933694369536963697369836993700370137023703370437053706370737083709371037113712371337143715371637173718371937203721372237233724372537263727372837293730373137323733373437353736373737383739374037413742374337443745374637473748374937503751375237533754375537563757375837593760376137623763376437653766376737683769377037713772377337743775377637773778377937803781378237833784378537863787378837893790379137923793379437953796379737983799380038013802380338043805380638073808380938103811381238133814381538163817381838193820382138223823382438253826382738283829383038313832383338343835383638373838383938403841384238433844384538463847384838493850385138523853385438553856385738583859386038613862386338643865386638673868386938703871387238733874387538763877387838793880388138823883388438853886388738883889389038913892389338943895389638973898389939003901390239033904390539063907390839093910391139123913391439153916391739183919392039213922392339243925392639273928392939303931393239333934393539363937393839393940394139423943394439453946394739483949395039513952395339543955395639573958395939603961396239633964396539663967396839693970397139723973397439753976397739783979398039813982398339843985398639873988398939903991399239933994399539963997399839994000400140024003400440054006400740084009
  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/compat.h>
  48. #include <linux/slab.h>
  49. #include <linux/poll.h>
  50. #include <linux/fs.h>
  51. #include <linux/file.h>
  52. #include <linux/jhash.h>
  53. #include <linux/init.h>
  54. #include <linux/futex.h>
  55. #include <linux/mount.h>
  56. #include <linux/pagemap.h>
  57. #include <linux/syscalls.h>
  58. #include <linux/signal.h>
  59. #include <linux/export.h>
  60. #include <linux/magic.h>
  61. #include <linux/pid.h>
  62. #include <linux/nsproxy.h>
  63. #include <linux/ptrace.h>
  64. #include <linux/sched/rt.h>
  65. #include <linux/sched/wake_q.h>
  66. #include <linux/sched/mm.h>
  67. #include <linux/hugetlb.h>
  68. #include <linux/freezer.h>
  69. #include <linux/bootmem.h>
  70. #include <linux/fault-inject.h>
  71. #include <asm/futex.h>
  72. #include "locking/rtmutex_common.h"
  73. /*
  74. * READ this before attempting to hack on futexes!
  75. *
  76. * Basic futex operation and ordering guarantees
  77. * =============================================
  78. *
  79. * The waiter reads the futex value in user space and calls
  80. * futex_wait(). This function computes the hash bucket and acquires
  81. * the hash bucket lock. After that it reads the futex user space value
  82. * again and verifies that the data has not changed. If it has not changed
  83. * it enqueues itself into the hash bucket, releases the hash bucket lock
  84. * and schedules.
  85. *
  86. * The waker side modifies the user space value of the futex and calls
  87. * futex_wake(). This function computes the hash bucket and acquires the
  88. * hash bucket lock. Then it looks for waiters on that futex in the hash
  89. * bucket and wakes them.
  90. *
  91. * In futex wake up scenarios where no tasks are blocked on a futex, taking
  92. * the hb spinlock can be avoided and simply return. In order for this
  93. * optimization to work, ordering guarantees must exist so that the waiter
  94. * being added to the list is acknowledged when the list is concurrently being
  95. * checked by the waker, avoiding scenarios like the following:
  96. *
  97. * CPU 0 CPU 1
  98. * val = *futex;
  99. * sys_futex(WAIT, futex, val);
  100. * futex_wait(futex, val);
  101. * uval = *futex;
  102. * *futex = newval;
  103. * sys_futex(WAKE, futex);
  104. * futex_wake(futex);
  105. * if (queue_empty())
  106. * return;
  107. * if (uval == val)
  108. * lock(hash_bucket(futex));
  109. * queue();
  110. * unlock(hash_bucket(futex));
  111. * schedule();
  112. *
  113. * This would cause the waiter on CPU 0 to wait forever because it
  114. * missed the transition of the user space value from val to newval
  115. * and the waker did not find the waiter in the hash bucket queue.
  116. *
  117. * The correct serialization ensures that a waiter either observes
  118. * the changed user space value before blocking or is woken by a
  119. * concurrent waker:
  120. *
  121. * CPU 0 CPU 1
  122. * val = *futex;
  123. * sys_futex(WAIT, futex, val);
  124. * futex_wait(futex, val);
  125. *
  126. * waiters++; (a)
  127. * smp_mb(); (A) <-- paired with -.
  128. * |
  129. * lock(hash_bucket(futex)); |
  130. * |
  131. * uval = *futex; |
  132. * | *futex = newval;
  133. * | sys_futex(WAKE, futex);
  134. * | futex_wake(futex);
  135. * |
  136. * `--------> smp_mb(); (B)
  137. * if (uval == val)
  138. * queue();
  139. * unlock(hash_bucket(futex));
  140. * schedule(); if (waiters)
  141. * lock(hash_bucket(futex));
  142. * else wake_waiters(futex);
  143. * waiters--; (b) unlock(hash_bucket(futex));
  144. *
  145. * Where (A) orders the waiters increment and the futex value read through
  146. * atomic operations (see hb_waiters_inc) and where (B) orders the write
  147. * to futex and the waiters read -- this is done by the barriers for both
  148. * shared and private futexes in get_futex_key_refs().
  149. *
  150. * This yields the following case (where X:=waiters, Y:=futex):
  151. *
  152. * X = Y = 0
  153. *
  154. * w[X]=1 w[Y]=1
  155. * MB MB
  156. * r[Y]=y r[X]=x
  157. *
  158. * Which guarantees that x==0 && y==0 is impossible; which translates back into
  159. * the guarantee that we cannot both miss the futex variable change and the
  160. * enqueue.
  161. *
  162. * Note that a new waiter is accounted for in (a) even when it is possible that
  163. * the wait call can return error, in which case we backtrack from it in (b).
  164. * Refer to the comment in queue_lock().
  165. *
  166. * Similarly, in order to account for waiters being requeued on another
  167. * address we always increment the waiters for the destination bucket before
  168. * acquiring the lock. It then decrements them again after releasing it -
  169. * the code that actually moves the futex(es) between hash buckets (requeue_futex)
  170. * will do the additional required waiter count housekeeping. This is done for
  171. * double_lock_hb() and double_unlock_hb(), respectively.
  172. */
  173. #ifdef CONFIG_HAVE_FUTEX_CMPXCHG
  174. #define futex_cmpxchg_enabled 1
  175. #else
  176. static int __read_mostly futex_cmpxchg_enabled;
  177. #endif
  178. /*
  179. * Futex flags used to encode options to functions and preserve them across
  180. * restarts.
  181. */
  182. #ifdef CONFIG_MMU
  183. # define FLAGS_SHARED 0x01
  184. #else
  185. /*
  186. * NOMMU does not have per process address space. Let the compiler optimize
  187. * code away.
  188. */
  189. # define FLAGS_SHARED 0x00
  190. #endif
  191. #define FLAGS_CLOCKRT 0x02
  192. #define FLAGS_HAS_TIMEOUT 0x04
  193. /*
  194. * Priority Inheritance state:
  195. */
  196. struct futex_pi_state {
  197. /*
  198. * list of 'owned' pi_state instances - these have to be
  199. * cleaned up in do_exit() if the task exits prematurely:
  200. */
  201. struct list_head list;
  202. /*
  203. * The PI object:
  204. */
  205. struct rt_mutex pi_mutex;
  206. struct task_struct *owner;
  207. atomic_t refcount;
  208. union futex_key key;
  209. } __randomize_layout;
  210. /**
  211. * struct futex_q - The hashed futex queue entry, one per waiting task
  212. * @list: priority-sorted list of tasks waiting on this futex
  213. * @task: the task waiting on the futex
  214. * @lock_ptr: the hash bucket lock
  215. * @key: the key the futex is hashed on
  216. * @pi_state: optional priority inheritance state
  217. * @rt_waiter: rt_waiter storage for use with requeue_pi
  218. * @requeue_pi_key: the requeue_pi target futex key
  219. * @bitset: bitset for the optional bitmasked wakeup
  220. *
  221. * We use this hashed waitqueue, instead of a normal wait_queue_entry_t, so
  222. * we can wake only the relevant ones (hashed queues may be shared).
  223. *
  224. * A futex_q has a woken state, just like tasks have TASK_RUNNING.
  225. * It is considered woken when plist_node_empty(&q->list) || q->lock_ptr == 0.
  226. * The order of wakeup is always to make the first condition true, then
  227. * the second.
  228. *
  229. * PI futexes are typically woken before they are removed from the hash list via
  230. * the rt_mutex code. See unqueue_me_pi().
  231. */
  232. struct futex_q {
  233. struct plist_node list;
  234. struct task_struct *task;
  235. spinlock_t *lock_ptr;
  236. union futex_key key;
  237. struct futex_pi_state *pi_state;
  238. struct rt_mutex_waiter *rt_waiter;
  239. union futex_key *requeue_pi_key;
  240. u32 bitset;
  241. } __randomize_layout;
  242. static const struct futex_q futex_q_init = {
  243. /* list gets initialized in queue_me()*/
  244. .key = FUTEX_KEY_INIT,
  245. .bitset = FUTEX_BITSET_MATCH_ANY
  246. };
  247. /*
  248. * Hash buckets are shared by all the futex_keys that hash to the same
  249. * location. Each key may have multiple futex_q structures, one for each task
  250. * waiting on a futex.
  251. */
  252. struct futex_hash_bucket {
  253. atomic_t waiters;
  254. spinlock_t lock;
  255. struct plist_head chain;
  256. } ____cacheline_aligned_in_smp;
  257. /*
  258. * The base of the bucket array and its size are always used together
  259. * (after initialization only in hash_futex()), so ensure that they
  260. * reside in the same cacheline.
  261. */
  262. static struct {
  263. struct futex_hash_bucket *queues;
  264. unsigned long hashsize;
  265. } __futex_data __read_mostly __aligned(2*sizeof(long));
  266. #define futex_queues (__futex_data.queues)
  267. #define futex_hashsize (__futex_data.hashsize)
  268. /*
  269. * Fault injections for futexes.
  270. */
  271. #ifdef CONFIG_FAIL_FUTEX
  272. static struct {
  273. struct fault_attr attr;
  274. bool ignore_private;
  275. } fail_futex = {
  276. .attr = FAULT_ATTR_INITIALIZER,
  277. .ignore_private = false,
  278. };
  279. static int __init setup_fail_futex(char *str)
  280. {
  281. return setup_fault_attr(&fail_futex.attr, str);
  282. }
  283. __setup("fail_futex=", setup_fail_futex);
  284. static bool should_fail_futex(bool fshared)
  285. {
  286. if (fail_futex.ignore_private && !fshared)
  287. return false;
  288. return should_fail(&fail_futex.attr, 1);
  289. }
  290. #ifdef CONFIG_FAULT_INJECTION_DEBUG_FS
  291. static int __init fail_futex_debugfs(void)
  292. {
  293. umode_t mode = S_IFREG | S_IRUSR | S_IWUSR;
  294. struct dentry *dir;
  295. dir = fault_create_debugfs_attr("fail_futex", NULL,
  296. &fail_futex.attr);
  297. if (IS_ERR(dir))
  298. return PTR_ERR(dir);
  299. if (!debugfs_create_bool("ignore-private", mode, dir,
  300. &fail_futex.ignore_private)) {
  301. debugfs_remove_recursive(dir);
  302. return -ENOMEM;
  303. }
  304. return 0;
  305. }
  306. late_initcall(fail_futex_debugfs);
  307. #endif /* CONFIG_FAULT_INJECTION_DEBUG_FS */
  308. #else
  309. static inline bool should_fail_futex(bool fshared)
  310. {
  311. return false;
  312. }
  313. #endif /* CONFIG_FAIL_FUTEX */
  314. static inline void futex_get_mm(union futex_key *key)
  315. {
  316. mmgrab(key->private.mm);
  317. /*
  318. * Ensure futex_get_mm() implies a full barrier such that
  319. * get_futex_key() implies a full barrier. This is relied upon
  320. * as smp_mb(); (B), see the ordering comment above.
  321. */
  322. smp_mb__after_atomic();
  323. }
  324. /*
  325. * Reflects a new waiter being added to the waitqueue.
  326. */
  327. static inline void hb_waiters_inc(struct futex_hash_bucket *hb)
  328. {
  329. #ifdef CONFIG_SMP
  330. atomic_inc(&hb->waiters);
  331. /*
  332. * Full barrier (A), see the ordering comment above.
  333. */
  334. smp_mb__after_atomic();
  335. #endif
  336. }
  337. /*
  338. * Reflects a waiter being removed from the waitqueue by wakeup
  339. * paths.
  340. */
  341. static inline void hb_waiters_dec(struct futex_hash_bucket *hb)
  342. {
  343. #ifdef CONFIG_SMP
  344. atomic_dec(&hb->waiters);
  345. #endif
  346. }
  347. static inline int hb_waiters_pending(struct futex_hash_bucket *hb)
  348. {
  349. #ifdef CONFIG_SMP
  350. return atomic_read(&hb->waiters);
  351. #else
  352. return 1;
  353. #endif
  354. }
  355. /**
  356. * hash_futex - Return the hash bucket in the global hash
  357. * @key: Pointer to the futex key for which the hash is calculated
  358. *
  359. * We hash on the keys returned from get_futex_key (see below) and return the
  360. * corresponding hash bucket in the global hash.
  361. */
  362. static struct futex_hash_bucket *hash_futex(union futex_key *key)
  363. {
  364. u32 hash = jhash2((u32 *)key, offsetof(typeof(*key), both.offset) / 4,
  365. key->both.offset);
  366. return &futex_queues[hash & (futex_hashsize - 1)];
  367. }
  368. /**
  369. * match_futex - Check whether two futex keys are equal
  370. * @key1: Pointer to key1
  371. * @key2: Pointer to key2
  372. *
  373. * Return 1 if two futex_keys are equal, 0 otherwise.
  374. */
  375. static inline int match_futex(union futex_key *key1, union futex_key *key2)
  376. {
  377. return (key1 && key2
  378. && key1->both.word == key2->both.word
  379. && key1->both.ptr == key2->both.ptr
  380. && key1->both.offset == key2->both.offset);
  381. }
  382. /*
  383. * Take a reference to the resource addressed by a key.
  384. * Can be called while holding spinlocks.
  385. *
  386. */
  387. static void get_futex_key_refs(union futex_key *key)
  388. {
  389. if (!key->both.ptr)
  390. return;
  391. /*
  392. * On MMU less systems futexes are always "private" as there is no per
  393. * process address space. We need the smp wmb nevertheless - yes,
  394. * arch/blackfin has MMU less SMP ...
  395. */
  396. if (!IS_ENABLED(CONFIG_MMU)) {
  397. smp_mb(); /* explicit smp_mb(); (B) */
  398. return;
  399. }
  400. switch (key->both.offset & (FUT_OFF_INODE|FUT_OFF_MMSHARED)) {
  401. case FUT_OFF_INODE:
  402. smp_mb(); /* explicit smp_mb(); (B) */
  403. break;
  404. case FUT_OFF_MMSHARED:
  405. futex_get_mm(key); /* implies smp_mb(); (B) */
  406. break;
  407. default:
  408. /*
  409. * Private futexes do not hold reference on an inode or
  410. * mm, therefore the only purpose of calling get_futex_key_refs
  411. * is because we need the barrier for the lockless waiter check.
  412. */
  413. smp_mb(); /* explicit smp_mb(); (B) */
  414. }
  415. }
  416. /*
  417. * Drop a reference to the resource addressed by a key.
  418. * The hash bucket spinlock must not be held. This is
  419. * a no-op for private futexes, see comment in the get
  420. * counterpart.
  421. */
  422. static void drop_futex_key_refs(union futex_key *key)
  423. {
  424. if (!key->both.ptr) {
  425. /* If we're here then we tried to put a key we failed to get */
  426. WARN_ON_ONCE(1);
  427. return;
  428. }
  429. if (!IS_ENABLED(CONFIG_MMU))
  430. return;
  431. switch (key->both.offset & (FUT_OFF_INODE|FUT_OFF_MMSHARED)) {
  432. case FUT_OFF_INODE:
  433. break;
  434. case FUT_OFF_MMSHARED:
  435. mmdrop(key->private.mm);
  436. break;
  437. }
  438. }
  439. /*
  440. * Generate a machine wide unique identifier for this inode.
  441. *
  442. * This relies on u64 not wrapping in the life-time of the machine; which with
  443. * 1ns resolution means almost 585 years.
  444. *
  445. * This further relies on the fact that a well formed program will not unmap
  446. * the file while it has a (shared) futex waiting on it. This mapping will have
  447. * a file reference which pins the mount and inode.
  448. *
  449. * If for some reason an inode gets evicted and read back in again, it will get
  450. * a new sequence number and will _NOT_ match, even though it is the exact same
  451. * file.
  452. *
  453. * It is important that match_futex() will never have a false-positive, esp.
  454. * for PI futexes that can mess up the state. The above argues that false-negatives
  455. * are only possible for malformed programs.
  456. */
  457. static u64 get_inode_sequence_number(struct inode *inode)
  458. {
  459. static atomic64_t i_seq;
  460. u64 old;
  461. /* Does the inode already have a sequence number? */
  462. old = atomic64_read(&inode->i_sequence);
  463. if (likely(old))
  464. return old;
  465. for (;;) {
  466. u64 new = atomic64_add_return(1, &i_seq);
  467. if (WARN_ON_ONCE(!new))
  468. continue;
  469. old = atomic64_cmpxchg_relaxed(&inode->i_sequence, 0, new);
  470. if (old)
  471. return old;
  472. return new;
  473. }
  474. }
  475. /**
  476. * get_futex_key() - Get parameters which are the keys for a futex
  477. * @uaddr: virtual address of the futex
  478. * @fshared: 0 for a PROCESS_PRIVATE futex, 1 for PROCESS_SHARED
  479. * @key: address where result is stored.
  480. * @rw: mapping needs to be read/write (values: VERIFY_READ,
  481. * VERIFY_WRITE)
  482. *
  483. * Return: a negative error code or 0
  484. *
  485. * The key words are stored in @key on success.
  486. *
  487. * For shared mappings (when @fshared), the key is:
  488. * ( inode->i_sequence, page->index, offset_within_page )
  489. * [ also see get_inode_sequence_number() ]
  490. *
  491. * For private mappings (or when !@fshared), the key is:
  492. * ( current->mm, address, 0 )
  493. *
  494. * This allows (cross process, where applicable) identification of the futex
  495. * without keeping the page pinned for the duration of the FUTEX_WAIT.
  496. *
  497. * lock_page() might sleep, the caller should not hold a spinlock.
  498. */
  499. static int
  500. get_futex_key(u32 __user *uaddr, int fshared, union futex_key *key, int rw)
  501. {
  502. unsigned long address = (unsigned long)uaddr;
  503. struct mm_struct *mm = current->mm;
  504. struct page *page, *tail;
  505. struct address_space *mapping;
  506. int err, ro = 0;
  507. /*
  508. * The futex address must be "naturally" aligned.
  509. */
  510. key->both.offset = address % PAGE_SIZE;
  511. if (unlikely((address % sizeof(u32)) != 0))
  512. return -EINVAL;
  513. address -= key->both.offset;
  514. if (unlikely(!access_ok(rw, uaddr, sizeof(u32))))
  515. return -EFAULT;
  516. if (unlikely(should_fail_futex(fshared)))
  517. return -EFAULT;
  518. /*
  519. * PROCESS_PRIVATE futexes are fast.
  520. * As the mm cannot disappear under us and the 'key' only needs
  521. * virtual address, we dont even have to find the underlying vma.
  522. * Note : We do have to check 'uaddr' is a valid user address,
  523. * but access_ok() should be faster than find_vma()
  524. */
  525. if (!fshared) {
  526. key->private.mm = mm;
  527. key->private.address = address;
  528. get_futex_key_refs(key); /* implies smp_mb(); (B) */
  529. return 0;
  530. }
  531. again:
  532. /* Ignore any VERIFY_READ mapping (futex common case) */
  533. if (unlikely(should_fail_futex(fshared)))
  534. return -EFAULT;
  535. err = get_user_pages_fast(address, 1, 1, &page);
  536. /*
  537. * If write access is not required (eg. FUTEX_WAIT), try
  538. * and get read-only access.
  539. */
  540. if (err == -EFAULT && rw == VERIFY_READ) {
  541. err = get_user_pages_fast(address, 1, 0, &page);
  542. ro = 1;
  543. }
  544. if (err < 0)
  545. return err;
  546. else
  547. err = 0;
  548. /*
  549. * The treatment of mapping from this point on is critical. The page
  550. * lock protects many things but in this context the page lock
  551. * stabilizes mapping, prevents inode freeing in the shared
  552. * file-backed region case and guards against movement to swap cache.
  553. *
  554. * Strictly speaking the page lock is not needed in all cases being
  555. * considered here and page lock forces unnecessarily serialization
  556. * From this point on, mapping will be re-verified if necessary and
  557. * page lock will be acquired only if it is unavoidable
  558. *
  559. * Mapping checks require the head page for any compound page so the
  560. * head page and mapping is looked up now. For anonymous pages, it
  561. * does not matter if the page splits in the future as the key is
  562. * based on the address. For filesystem-backed pages, the tail is
  563. * required as the index of the page determines the key. For
  564. * base pages, there is no tail page and tail == page.
  565. */
  566. tail = page;
  567. page = compound_head(page);
  568. mapping = READ_ONCE(page->mapping);
  569. /*
  570. * If page->mapping is NULL, then it cannot be a PageAnon
  571. * page; but it might be the ZERO_PAGE or in the gate area or
  572. * in a special mapping (all cases which we are happy to fail);
  573. * or it may have been a good file page when get_user_pages_fast
  574. * found it, but truncated or holepunched or subjected to
  575. * invalidate_complete_page2 before we got the page lock (also
  576. * cases which we are happy to fail). And we hold a reference,
  577. * so refcount care in invalidate_complete_page's remove_mapping
  578. * prevents drop_caches from setting mapping to NULL beneath us.
  579. *
  580. * The case we do have to guard against is when memory pressure made
  581. * shmem_writepage move it from filecache to swapcache beneath us:
  582. * an unlikely race, but we do need to retry for page->mapping.
  583. */
  584. if (unlikely(!mapping)) {
  585. int shmem_swizzled;
  586. /*
  587. * Page lock is required to identify which special case above
  588. * applies. If this is really a shmem page then the page lock
  589. * will prevent unexpected transitions.
  590. */
  591. lock_page(page);
  592. shmem_swizzled = PageSwapCache(page) || page->mapping;
  593. unlock_page(page);
  594. put_page(page);
  595. if (shmem_swizzled)
  596. goto again;
  597. return -EFAULT;
  598. }
  599. /*
  600. * Private mappings are handled in a simple way.
  601. *
  602. * If the futex key is stored on an anonymous page, then the associated
  603. * object is the mm which is implicitly pinned by the calling process.
  604. *
  605. * NOTE: When userspace waits on a MAP_SHARED mapping, even if
  606. * it's a read-only handle, it's expected that futexes attach to
  607. * the object not the particular process.
  608. */
  609. if (PageAnon(page)) {
  610. /*
  611. * A RO anonymous page will never change and thus doesn't make
  612. * sense for futex operations.
  613. */
  614. if (unlikely(should_fail_futex(fshared)) || ro) {
  615. err = -EFAULT;
  616. goto out;
  617. }
  618. key->both.offset |= FUT_OFF_MMSHARED; /* ref taken on mm */
  619. key->private.mm = mm;
  620. key->private.address = address;
  621. } else {
  622. struct inode *inode;
  623. /*
  624. * The associated futex object in this case is the inode and
  625. * the page->mapping must be traversed. Ordinarily this should
  626. * be stabilised under page lock but it's not strictly
  627. * necessary in this case as we just want to pin the inode, not
  628. * update the radix tree or anything like that.
  629. *
  630. * The RCU read lock is taken as the inode is finally freed
  631. * under RCU. If the mapping still matches expectations then the
  632. * mapping->host can be safely accessed as being a valid inode.
  633. */
  634. rcu_read_lock();
  635. if (READ_ONCE(page->mapping) != mapping) {
  636. rcu_read_unlock();
  637. put_page(page);
  638. goto again;
  639. }
  640. inode = READ_ONCE(mapping->host);
  641. if (!inode) {
  642. rcu_read_unlock();
  643. put_page(page);
  644. goto again;
  645. }
  646. key->both.offset |= FUT_OFF_INODE; /* inode-based key */
  647. key->shared.i_seq = get_inode_sequence_number(inode);
  648. key->shared.pgoff = basepage_index(tail);
  649. rcu_read_unlock();
  650. }
  651. get_futex_key_refs(key); /* implies smp_mb(); (B) */
  652. out:
  653. put_page(page);
  654. return err;
  655. }
  656. static inline void put_futex_key(union futex_key *key)
  657. {
  658. drop_futex_key_refs(key);
  659. }
  660. /**
  661. * fault_in_user_writeable() - Fault in user address and verify RW access
  662. * @uaddr: pointer to faulting user space address
  663. *
  664. * Slow path to fixup the fault we just took in the atomic write
  665. * access to @uaddr.
  666. *
  667. * We have no generic implementation of a non-destructive write to the
  668. * user address. We know that we faulted in the atomic pagefault
  669. * disabled section so we can as well avoid the #PF overhead by
  670. * calling get_user_pages() right away.
  671. */
  672. static int fault_in_user_writeable(u32 __user *uaddr)
  673. {
  674. struct mm_struct *mm = current->mm;
  675. int ret;
  676. down_read(&mm->mmap_sem);
  677. ret = fixup_user_fault(current, mm, (unsigned long)uaddr,
  678. FAULT_FLAG_WRITE, NULL);
  679. up_read(&mm->mmap_sem);
  680. return ret < 0 ? ret : 0;
  681. }
  682. /**
  683. * futex_top_waiter() - Return the highest priority waiter on a futex
  684. * @hb: the hash bucket the futex_q's reside in
  685. * @key: the futex key (to distinguish it from other futex futex_q's)
  686. *
  687. * Must be called with the hb lock held.
  688. */
  689. static struct futex_q *futex_top_waiter(struct futex_hash_bucket *hb,
  690. union futex_key *key)
  691. {
  692. struct futex_q *this;
  693. plist_for_each_entry(this, &hb->chain, list) {
  694. if (match_futex(&this->key, key))
  695. return this;
  696. }
  697. return NULL;
  698. }
  699. static int cmpxchg_futex_value_locked(u32 *curval, u32 __user *uaddr,
  700. u32 uval, u32 newval)
  701. {
  702. int ret;
  703. pagefault_disable();
  704. ret = futex_atomic_cmpxchg_inatomic(curval, uaddr, uval, newval);
  705. pagefault_enable();
  706. return ret;
  707. }
  708. static int get_futex_value_locked(u32 *dest, u32 __user *from)
  709. {
  710. int ret;
  711. pagefault_disable();
  712. ret = __get_user(*dest, from);
  713. pagefault_enable();
  714. return ret ? -EFAULT : 0;
  715. }
  716. /*
  717. * PI code:
  718. */
  719. static int refill_pi_state_cache(void)
  720. {
  721. struct futex_pi_state *pi_state;
  722. if (likely(current->pi_state_cache))
  723. return 0;
  724. pi_state = kzalloc(sizeof(*pi_state), GFP_KERNEL);
  725. if (!pi_state)
  726. return -ENOMEM;
  727. INIT_LIST_HEAD(&pi_state->list);
  728. /* pi_mutex gets initialized later */
  729. pi_state->owner = NULL;
  730. atomic_set(&pi_state->refcount, 1);
  731. pi_state->key = FUTEX_KEY_INIT;
  732. current->pi_state_cache = pi_state;
  733. return 0;
  734. }
  735. static struct futex_pi_state *alloc_pi_state(void)
  736. {
  737. struct futex_pi_state *pi_state = current->pi_state_cache;
  738. WARN_ON(!pi_state);
  739. current->pi_state_cache = NULL;
  740. return pi_state;
  741. }
  742. static void get_pi_state(struct futex_pi_state *pi_state)
  743. {
  744. WARN_ON_ONCE(!atomic_inc_not_zero(&pi_state->refcount));
  745. }
  746. /*
  747. * Drops a reference to the pi_state object and frees or caches it
  748. * when the last reference is gone.
  749. */
  750. static void put_pi_state(struct futex_pi_state *pi_state)
  751. {
  752. if (!pi_state)
  753. return;
  754. if (!atomic_dec_and_test(&pi_state->refcount))
  755. return;
  756. /*
  757. * If pi_state->owner is NULL, the owner is most probably dying
  758. * and has cleaned up the pi_state already
  759. */
  760. if (pi_state->owner) {
  761. struct task_struct *owner;
  762. raw_spin_lock_irq(&pi_state->pi_mutex.wait_lock);
  763. owner = pi_state->owner;
  764. if (owner) {
  765. raw_spin_lock(&owner->pi_lock);
  766. list_del_init(&pi_state->list);
  767. raw_spin_unlock(&owner->pi_lock);
  768. }
  769. rt_mutex_proxy_unlock(&pi_state->pi_mutex, owner);
  770. raw_spin_unlock_irq(&pi_state->pi_mutex.wait_lock);
  771. }
  772. if (current->pi_state_cache) {
  773. kfree(pi_state);
  774. } else {
  775. /*
  776. * pi_state->list is already empty.
  777. * clear pi_state->owner.
  778. * refcount is at 0 - put it back to 1.
  779. */
  780. pi_state->owner = NULL;
  781. atomic_set(&pi_state->refcount, 1);
  782. current->pi_state_cache = pi_state;
  783. }
  784. }
  785. #ifdef CONFIG_FUTEX_PI
  786. /*
  787. * This task is holding PI mutexes at exit time => bad.
  788. * Kernel cleans up PI-state, but userspace is likely hosed.
  789. * (Robust-futex cleanup is separate and might save the day for userspace.)
  790. */
  791. void exit_pi_state_list(struct task_struct *curr)
  792. {
  793. struct list_head *next, *head = &curr->pi_state_list;
  794. struct futex_pi_state *pi_state;
  795. struct futex_hash_bucket *hb;
  796. union futex_key key = FUTEX_KEY_INIT;
  797. if (!futex_cmpxchg_enabled)
  798. return;
  799. /*
  800. * We are a ZOMBIE and nobody can enqueue itself on
  801. * pi_state_list anymore, but we have to be careful
  802. * versus waiters unqueueing themselves:
  803. */
  804. raw_spin_lock_irq(&curr->pi_lock);
  805. while (!list_empty(head)) {
  806. next = head->next;
  807. pi_state = list_entry(next, struct futex_pi_state, list);
  808. key = pi_state->key;
  809. hb = hash_futex(&key);
  810. /*
  811. * We can race against put_pi_state() removing itself from the
  812. * list (a waiter going away). put_pi_state() will first
  813. * decrement the reference count and then modify the list, so
  814. * its possible to see the list entry but fail this reference
  815. * acquire.
  816. *
  817. * In that case; drop the locks to let put_pi_state() make
  818. * progress and retry the loop.
  819. */
  820. if (!atomic_inc_not_zero(&pi_state->refcount)) {
  821. raw_spin_unlock_irq(&curr->pi_lock);
  822. cpu_relax();
  823. raw_spin_lock_irq(&curr->pi_lock);
  824. continue;
  825. }
  826. raw_spin_unlock_irq(&curr->pi_lock);
  827. spin_lock(&hb->lock);
  828. raw_spin_lock_irq(&pi_state->pi_mutex.wait_lock);
  829. raw_spin_lock(&curr->pi_lock);
  830. /*
  831. * We dropped the pi-lock, so re-check whether this
  832. * task still owns the PI-state:
  833. */
  834. if (head->next != next) {
  835. /* retain curr->pi_lock for the loop invariant */
  836. raw_spin_unlock(&pi_state->pi_mutex.wait_lock);
  837. spin_unlock(&hb->lock);
  838. put_pi_state(pi_state);
  839. continue;
  840. }
  841. WARN_ON(pi_state->owner != curr);
  842. WARN_ON(list_empty(&pi_state->list));
  843. list_del_init(&pi_state->list);
  844. pi_state->owner = NULL;
  845. raw_spin_unlock(&curr->pi_lock);
  846. raw_spin_unlock_irq(&pi_state->pi_mutex.wait_lock);
  847. spin_unlock(&hb->lock);
  848. rt_mutex_futex_unlock(&pi_state->pi_mutex);
  849. put_pi_state(pi_state);
  850. raw_spin_lock_irq(&curr->pi_lock);
  851. }
  852. raw_spin_unlock_irq(&curr->pi_lock);
  853. }
  854. #endif
  855. /*
  856. * We need to check the following states:
  857. *
  858. * Waiter | pi_state | pi->owner | uTID | uODIED | ?
  859. *
  860. * [1] NULL | --- | --- | 0 | 0/1 | Valid
  861. * [2] NULL | --- | --- | >0 | 0/1 | Valid
  862. *
  863. * [3] Found | NULL | -- | Any | 0/1 | Invalid
  864. *
  865. * [4] Found | Found | NULL | 0 | 1 | Valid
  866. * [5] Found | Found | NULL | >0 | 1 | Invalid
  867. *
  868. * [6] Found | Found | task | 0 | 1 | Valid
  869. *
  870. * [7] Found | Found | NULL | Any | 0 | Invalid
  871. *
  872. * [8] Found | Found | task | ==taskTID | 0/1 | Valid
  873. * [9] Found | Found | task | 0 | 0 | Invalid
  874. * [10] Found | Found | task | !=taskTID | 0/1 | Invalid
  875. *
  876. * [1] Indicates that the kernel can acquire the futex atomically. We
  877. * came came here due to a stale FUTEX_WAITERS/FUTEX_OWNER_DIED bit.
  878. *
  879. * [2] Valid, if TID does not belong to a kernel thread. If no matching
  880. * thread is found then it indicates that the owner TID has died.
  881. *
  882. * [3] Invalid. The waiter is queued on a non PI futex
  883. *
  884. * [4] Valid state after exit_robust_list(), which sets the user space
  885. * value to FUTEX_WAITERS | FUTEX_OWNER_DIED.
  886. *
  887. * [5] The user space value got manipulated between exit_robust_list()
  888. * and exit_pi_state_list()
  889. *
  890. * [6] Valid state after exit_pi_state_list() which sets the new owner in
  891. * the pi_state but cannot access the user space value.
  892. *
  893. * [7] pi_state->owner can only be NULL when the OWNER_DIED bit is set.
  894. *
  895. * [8] Owner and user space value match
  896. *
  897. * [9] There is no transient state which sets the user space TID to 0
  898. * except exit_robust_list(), but this is indicated by the
  899. * FUTEX_OWNER_DIED bit. See [4]
  900. *
  901. * [10] There is no transient state which leaves owner and user space
  902. * TID out of sync.
  903. *
  904. *
  905. * Serialization and lifetime rules:
  906. *
  907. * hb->lock:
  908. *
  909. * hb -> futex_q, relation
  910. * futex_q -> pi_state, relation
  911. *
  912. * (cannot be raw because hb can contain arbitrary amount
  913. * of futex_q's)
  914. *
  915. * pi_mutex->wait_lock:
  916. *
  917. * {uval, pi_state}
  918. *
  919. * (and pi_mutex 'obviously')
  920. *
  921. * p->pi_lock:
  922. *
  923. * p->pi_state_list -> pi_state->list, relation
  924. *
  925. * pi_state->refcount:
  926. *
  927. * pi_state lifetime
  928. *
  929. *
  930. * Lock order:
  931. *
  932. * hb->lock
  933. * pi_mutex->wait_lock
  934. * p->pi_lock
  935. *
  936. */
  937. /*
  938. * Validate that the existing waiter has a pi_state and sanity check
  939. * the pi_state against the user space value. If correct, attach to
  940. * it.
  941. */
  942. static int attach_to_pi_state(u32 __user *uaddr, u32 uval,
  943. struct futex_pi_state *pi_state,
  944. struct futex_pi_state **ps)
  945. {
  946. pid_t pid = uval & FUTEX_TID_MASK;
  947. u32 uval2;
  948. int ret;
  949. /*
  950. * Userspace might have messed up non-PI and PI futexes [3]
  951. */
  952. if (unlikely(!pi_state))
  953. return -EINVAL;
  954. /*
  955. * We get here with hb->lock held, and having found a
  956. * futex_top_waiter(). This means that futex_lock_pi() of said futex_q
  957. * has dropped the hb->lock in between queue_me() and unqueue_me_pi(),
  958. * which in turn means that futex_lock_pi() still has a reference on
  959. * our pi_state.
  960. *
  961. * The waiter holding a reference on @pi_state also protects against
  962. * the unlocked put_pi_state() in futex_unlock_pi(), futex_lock_pi()
  963. * and futex_wait_requeue_pi() as it cannot go to 0 and consequently
  964. * free pi_state before we can take a reference ourselves.
  965. */
  966. WARN_ON(!atomic_read(&pi_state->refcount));
  967. /*
  968. * Now that we have a pi_state, we can acquire wait_lock
  969. * and do the state validation.
  970. */
  971. raw_spin_lock_irq(&pi_state->pi_mutex.wait_lock);
  972. /*
  973. * Since {uval, pi_state} is serialized by wait_lock, and our current
  974. * uval was read without holding it, it can have changed. Verify it
  975. * still is what we expect it to be, otherwise retry the entire
  976. * operation.
  977. */
  978. if (get_futex_value_locked(&uval2, uaddr))
  979. goto out_efault;
  980. if (uval != uval2)
  981. goto out_eagain;
  982. /*
  983. * Handle the owner died case:
  984. */
  985. if (uval & FUTEX_OWNER_DIED) {
  986. /*
  987. * exit_pi_state_list sets owner to NULL and wakes the
  988. * topmost waiter. The task which acquires the
  989. * pi_state->rt_mutex will fixup owner.
  990. */
  991. if (!pi_state->owner) {
  992. /*
  993. * No pi state owner, but the user space TID
  994. * is not 0. Inconsistent state. [5]
  995. */
  996. if (pid)
  997. goto out_einval;
  998. /*
  999. * Take a ref on the state and return success. [4]
  1000. */
  1001. goto out_attach;
  1002. }
  1003. /*
  1004. * If TID is 0, then either the dying owner has not
  1005. * yet executed exit_pi_state_list() or some waiter
  1006. * acquired the rtmutex in the pi state, but did not
  1007. * yet fixup the TID in user space.
  1008. *
  1009. * Take a ref on the state and return success. [6]
  1010. */
  1011. if (!pid)
  1012. goto out_attach;
  1013. } else {
  1014. /*
  1015. * If the owner died bit is not set, then the pi_state
  1016. * must have an owner. [7]
  1017. */
  1018. if (!pi_state->owner)
  1019. goto out_einval;
  1020. }
  1021. /*
  1022. * Bail out if user space manipulated the futex value. If pi
  1023. * state exists then the owner TID must be the same as the
  1024. * user space TID. [9/10]
  1025. */
  1026. if (pid != task_pid_vnr(pi_state->owner))
  1027. goto out_einval;
  1028. out_attach:
  1029. get_pi_state(pi_state);
  1030. raw_spin_unlock_irq(&pi_state->pi_mutex.wait_lock);
  1031. *ps = pi_state;
  1032. return 0;
  1033. out_einval:
  1034. ret = -EINVAL;
  1035. goto out_error;
  1036. out_eagain:
  1037. ret = -EAGAIN;
  1038. goto out_error;
  1039. out_efault:
  1040. ret = -EFAULT;
  1041. goto out_error;
  1042. out_error:
  1043. raw_spin_unlock_irq(&pi_state->pi_mutex.wait_lock);
  1044. return ret;
  1045. }
  1046. static int handle_exit_race(u32 __user *uaddr, u32 uval,
  1047. struct task_struct *tsk)
  1048. {
  1049. u32 uval2;
  1050. /*
  1051. * If PF_EXITPIDONE is not yet set, then try again.
  1052. */
  1053. if (tsk && !(tsk->flags & PF_EXITPIDONE))
  1054. return -EAGAIN;
  1055. /*
  1056. * Reread the user space value to handle the following situation:
  1057. *
  1058. * CPU0 CPU1
  1059. *
  1060. * sys_exit() sys_futex()
  1061. * do_exit() futex_lock_pi()
  1062. * futex_lock_pi_atomic()
  1063. * exit_signals(tsk) No waiters:
  1064. * tsk->flags |= PF_EXITING; *uaddr == 0x00000PID
  1065. * mm_release(tsk) Set waiter bit
  1066. * exit_robust_list(tsk) { *uaddr = 0x80000PID;
  1067. * Set owner died attach_to_pi_owner() {
  1068. * *uaddr = 0xC0000000; tsk = get_task(PID);
  1069. * } if (!tsk->flags & PF_EXITING) {
  1070. * ... attach();
  1071. * tsk->flags |= PF_EXITPIDONE; } else {
  1072. * if (!(tsk->flags & PF_EXITPIDONE))
  1073. * return -EAGAIN;
  1074. * return -ESRCH; <--- FAIL
  1075. * }
  1076. *
  1077. * Returning ESRCH unconditionally is wrong here because the
  1078. * user space value has been changed by the exiting task.
  1079. *
  1080. * The same logic applies to the case where the exiting task is
  1081. * already gone.
  1082. */
  1083. if (get_futex_value_locked(&uval2, uaddr))
  1084. return -EFAULT;
  1085. /* If the user space value has changed, try again. */
  1086. if (uval2 != uval)
  1087. return -EAGAIN;
  1088. /*
  1089. * The exiting task did not have a robust list, the robust list was
  1090. * corrupted or the user space value in *uaddr is simply bogus.
  1091. * Give up and tell user space.
  1092. */
  1093. return -ESRCH;
  1094. }
  1095. /*
  1096. * Lookup the task for the TID provided from user space and attach to
  1097. * it after doing proper sanity checks.
  1098. */
  1099. static int attach_to_pi_owner(u32 __user *uaddr, u32 uval, union futex_key *key,
  1100. struct futex_pi_state **ps)
  1101. {
  1102. pid_t pid = uval & FUTEX_TID_MASK;
  1103. struct futex_pi_state *pi_state;
  1104. struct task_struct *p;
  1105. /*
  1106. * We are the first waiter - try to look up the real owner and attach
  1107. * the new pi_state to it, but bail out when TID = 0 [1]
  1108. *
  1109. * The !pid check is paranoid. None of the call sites should end up
  1110. * with pid == 0, but better safe than sorry. Let the caller retry
  1111. */
  1112. if (!pid)
  1113. return -EAGAIN;
  1114. p = find_get_task_by_vpid(pid);
  1115. if (!p)
  1116. return handle_exit_race(uaddr, uval, NULL);
  1117. if (unlikely(p->flags & PF_KTHREAD)) {
  1118. put_task_struct(p);
  1119. return -EPERM;
  1120. }
  1121. /*
  1122. * We need to look at the task state flags to figure out,
  1123. * whether the task is exiting. To protect against the do_exit
  1124. * change of the task flags, we do this protected by
  1125. * p->pi_lock:
  1126. */
  1127. raw_spin_lock_irq(&p->pi_lock);
  1128. if (unlikely(p->flags & PF_EXITING)) {
  1129. /*
  1130. * The task is on the way out. When PF_EXITPIDONE is
  1131. * set, we know that the task has finished the
  1132. * cleanup:
  1133. */
  1134. int ret = handle_exit_race(uaddr, uval, p);
  1135. raw_spin_unlock_irq(&p->pi_lock);
  1136. put_task_struct(p);
  1137. return ret;
  1138. }
  1139. /*
  1140. * No existing pi state. First waiter. [2]
  1141. *
  1142. * This creates pi_state, we have hb->lock held, this means nothing can
  1143. * observe this state, wait_lock is irrelevant.
  1144. */
  1145. pi_state = alloc_pi_state();
  1146. /*
  1147. * Initialize the pi_mutex in locked state and make @p
  1148. * the owner of it:
  1149. */
  1150. rt_mutex_init_proxy_locked(&pi_state->pi_mutex, p);
  1151. /* Store the key for possible exit cleanups: */
  1152. pi_state->key = *key;
  1153. WARN_ON(!list_empty(&pi_state->list));
  1154. list_add(&pi_state->list, &p->pi_state_list);
  1155. /*
  1156. * Assignment without holding pi_state->pi_mutex.wait_lock is safe
  1157. * because there is no concurrency as the object is not published yet.
  1158. */
  1159. pi_state->owner = p;
  1160. raw_spin_unlock_irq(&p->pi_lock);
  1161. put_task_struct(p);
  1162. *ps = pi_state;
  1163. return 0;
  1164. }
  1165. static int lookup_pi_state(u32 __user *uaddr, u32 uval,
  1166. struct futex_hash_bucket *hb,
  1167. union futex_key *key, struct futex_pi_state **ps)
  1168. {
  1169. struct futex_q *top_waiter = futex_top_waiter(hb, key);
  1170. /*
  1171. * If there is a waiter on that futex, validate it and
  1172. * attach to the pi_state when the validation succeeds.
  1173. */
  1174. if (top_waiter)
  1175. return attach_to_pi_state(uaddr, uval, top_waiter->pi_state, ps);
  1176. /*
  1177. * We are the first waiter - try to look up the owner based on
  1178. * @uval and attach to it.
  1179. */
  1180. return attach_to_pi_owner(uaddr, uval, key, ps);
  1181. }
  1182. static int lock_pi_update_atomic(u32 __user *uaddr, u32 uval, u32 newval)
  1183. {
  1184. int err;
  1185. u32 uninitialized_var(curval);
  1186. if (unlikely(should_fail_futex(true)))
  1187. return -EFAULT;
  1188. err = cmpxchg_futex_value_locked(&curval, uaddr, uval, newval);
  1189. if (unlikely(err))
  1190. return err;
  1191. /* If user space value changed, let the caller retry */
  1192. return curval != uval ? -EAGAIN : 0;
  1193. }
  1194. /**
  1195. * futex_lock_pi_atomic() - Atomic work required to acquire a pi aware futex
  1196. * @uaddr: the pi futex user address
  1197. * @hb: the pi futex hash bucket
  1198. * @key: the futex key associated with uaddr and hb
  1199. * @ps: the pi_state pointer where we store the result of the
  1200. * lookup
  1201. * @task: the task to perform the atomic lock work for. This will
  1202. * be "current" except in the case of requeue pi.
  1203. * @set_waiters: force setting the FUTEX_WAITERS bit (1) or not (0)
  1204. *
  1205. * Return:
  1206. * - 0 - ready to wait;
  1207. * - 1 - acquired the lock;
  1208. * - <0 - error
  1209. *
  1210. * The hb->lock and futex_key refs shall be held by the caller.
  1211. */
  1212. static int futex_lock_pi_atomic(u32 __user *uaddr, struct futex_hash_bucket *hb,
  1213. union futex_key *key,
  1214. struct futex_pi_state **ps,
  1215. struct task_struct *task, int set_waiters)
  1216. {
  1217. u32 uval, newval, vpid = task_pid_vnr(task);
  1218. struct futex_q *top_waiter;
  1219. int ret;
  1220. /*
  1221. * Read the user space value first so we can validate a few
  1222. * things before proceeding further.
  1223. */
  1224. if (get_futex_value_locked(&uval, uaddr))
  1225. return -EFAULT;
  1226. if (unlikely(should_fail_futex(true)))
  1227. return -EFAULT;
  1228. /*
  1229. * Detect deadlocks.
  1230. */
  1231. if ((unlikely((uval & FUTEX_TID_MASK) == vpid)))
  1232. return -EDEADLK;
  1233. if ((unlikely(should_fail_futex(true))))
  1234. return -EDEADLK;
  1235. /*
  1236. * Lookup existing state first. If it exists, try to attach to
  1237. * its pi_state.
  1238. */
  1239. top_waiter = futex_top_waiter(hb, key);
  1240. if (top_waiter)
  1241. return attach_to_pi_state(uaddr, uval, top_waiter->pi_state, ps);
  1242. /*
  1243. * No waiter and user TID is 0. We are here because the
  1244. * waiters or the owner died bit is set or called from
  1245. * requeue_cmp_pi or for whatever reason something took the
  1246. * syscall.
  1247. */
  1248. if (!(uval & FUTEX_TID_MASK)) {
  1249. /*
  1250. * We take over the futex. No other waiters and the user space
  1251. * TID is 0. We preserve the owner died bit.
  1252. */
  1253. newval = uval & FUTEX_OWNER_DIED;
  1254. newval |= vpid;
  1255. /* The futex requeue_pi code can enforce the waiters bit */
  1256. if (set_waiters)
  1257. newval |= FUTEX_WAITERS;
  1258. ret = lock_pi_update_atomic(uaddr, uval, newval);
  1259. /* If the take over worked, return 1 */
  1260. return ret < 0 ? ret : 1;
  1261. }
  1262. /*
  1263. * First waiter. Set the waiters bit before attaching ourself to
  1264. * the owner. If owner tries to unlock, it will be forced into
  1265. * the kernel and blocked on hb->lock.
  1266. */
  1267. newval = uval | FUTEX_WAITERS;
  1268. ret = lock_pi_update_atomic(uaddr, uval, newval);
  1269. if (ret)
  1270. return ret;
  1271. /*
  1272. * If the update of the user space value succeeded, we try to
  1273. * attach to the owner. If that fails, no harm done, we only
  1274. * set the FUTEX_WAITERS bit in the user space variable.
  1275. */
  1276. return attach_to_pi_owner(uaddr, newval, key, ps);
  1277. }
  1278. /**
  1279. * __unqueue_futex() - Remove the futex_q from its futex_hash_bucket
  1280. * @q: The futex_q to unqueue
  1281. *
  1282. * The q->lock_ptr must not be NULL and must be held by the caller.
  1283. */
  1284. static void __unqueue_futex(struct futex_q *q)
  1285. {
  1286. struct futex_hash_bucket *hb;
  1287. if (WARN_ON_SMP(!q->lock_ptr || !spin_is_locked(q->lock_ptr))
  1288. || WARN_ON(plist_node_empty(&q->list)))
  1289. return;
  1290. hb = container_of(q->lock_ptr, struct futex_hash_bucket, lock);
  1291. plist_del(&q->list, &hb->chain);
  1292. hb_waiters_dec(hb);
  1293. }
  1294. /*
  1295. * The hash bucket lock must be held when this is called.
  1296. * Afterwards, the futex_q must not be accessed. Callers
  1297. * must ensure to later call wake_up_q() for the actual
  1298. * wakeups to occur.
  1299. */
  1300. static void mark_wake_futex(struct wake_q_head *wake_q, struct futex_q *q)
  1301. {
  1302. struct task_struct *p = q->task;
  1303. if (WARN(q->pi_state || q->rt_waiter, "refusing to wake PI futex\n"))
  1304. return;
  1305. get_task_struct(p);
  1306. __unqueue_futex(q);
  1307. /*
  1308. * The waiting task can free the futex_q as soon as q->lock_ptr = NULL
  1309. * is written, without taking any locks. This is possible in the event
  1310. * of a spurious wakeup, for example. A memory barrier is required here
  1311. * to prevent the following store to lock_ptr from getting ahead of the
  1312. * plist_del in __unqueue_futex().
  1313. */
  1314. smp_store_release(&q->lock_ptr, NULL);
  1315. /*
  1316. * Queue the task for later wakeup for after we've released
  1317. * the hb->lock. wake_q_add() grabs reference to p.
  1318. */
  1319. wake_q_add(wake_q, p);
  1320. put_task_struct(p);
  1321. }
  1322. /*
  1323. * Caller must hold a reference on @pi_state.
  1324. */
  1325. static int wake_futex_pi(u32 __user *uaddr, u32 uval, struct futex_pi_state *pi_state)
  1326. {
  1327. u32 uninitialized_var(curval), newval;
  1328. struct task_struct *new_owner;
  1329. bool postunlock = false;
  1330. DEFINE_WAKE_Q(wake_q);
  1331. int ret = 0;
  1332. new_owner = rt_mutex_next_owner(&pi_state->pi_mutex);
  1333. if (WARN_ON_ONCE(!new_owner)) {
  1334. /*
  1335. * As per the comment in futex_unlock_pi() this should not happen.
  1336. *
  1337. * When this happens, give up our locks and try again, giving
  1338. * the futex_lock_pi() instance time to complete, either by
  1339. * waiting on the rtmutex or removing itself from the futex
  1340. * queue.
  1341. */
  1342. ret = -EAGAIN;
  1343. goto out_unlock;
  1344. }
  1345. /*
  1346. * We pass it to the next owner. The WAITERS bit is always kept
  1347. * enabled while there is PI state around. We cleanup the owner
  1348. * died bit, because we are the owner.
  1349. */
  1350. newval = FUTEX_WAITERS | task_pid_vnr(new_owner);
  1351. if (unlikely(should_fail_futex(true)))
  1352. ret = -EFAULT;
  1353. ret = cmpxchg_futex_value_locked(&curval, uaddr, uval, newval);
  1354. if (!ret && (curval != uval)) {
  1355. /*
  1356. * If a unconditional UNLOCK_PI operation (user space did not
  1357. * try the TID->0 transition) raced with a waiter setting the
  1358. * FUTEX_WAITERS flag between get_user() and locking the hash
  1359. * bucket lock, retry the operation.
  1360. */
  1361. if ((FUTEX_TID_MASK & curval) == uval)
  1362. ret = -EAGAIN;
  1363. else
  1364. ret = -EINVAL;
  1365. }
  1366. if (ret)
  1367. goto out_unlock;
  1368. /*
  1369. * This is a point of no return; once we modify the uval there is no
  1370. * going back and subsequent operations must not fail.
  1371. */
  1372. raw_spin_lock(&pi_state->owner->pi_lock);
  1373. WARN_ON(list_empty(&pi_state->list));
  1374. list_del_init(&pi_state->list);
  1375. raw_spin_unlock(&pi_state->owner->pi_lock);
  1376. raw_spin_lock(&new_owner->pi_lock);
  1377. WARN_ON(!list_empty(&pi_state->list));
  1378. list_add(&pi_state->list, &new_owner->pi_state_list);
  1379. pi_state->owner = new_owner;
  1380. raw_spin_unlock(&new_owner->pi_lock);
  1381. postunlock = __rt_mutex_futex_unlock(&pi_state->pi_mutex, &wake_q);
  1382. out_unlock:
  1383. raw_spin_unlock_irq(&pi_state->pi_mutex.wait_lock);
  1384. if (postunlock)
  1385. rt_mutex_postunlock(&wake_q);
  1386. return ret;
  1387. }
  1388. /*
  1389. * Express the locking dependencies for lockdep:
  1390. */
  1391. static inline void
  1392. double_lock_hb(struct futex_hash_bucket *hb1, struct futex_hash_bucket *hb2)
  1393. {
  1394. if (hb1 <= hb2) {
  1395. spin_lock(&hb1->lock);
  1396. if (hb1 < hb2)
  1397. spin_lock_nested(&hb2->lock, SINGLE_DEPTH_NESTING);
  1398. } else { /* hb1 > hb2 */
  1399. spin_lock(&hb2->lock);
  1400. spin_lock_nested(&hb1->lock, SINGLE_DEPTH_NESTING);
  1401. }
  1402. }
  1403. static inline void
  1404. double_unlock_hb(struct futex_hash_bucket *hb1, struct futex_hash_bucket *hb2)
  1405. {
  1406. spin_unlock(&hb1->lock);
  1407. if (hb1 != hb2)
  1408. spin_unlock(&hb2->lock);
  1409. }
  1410. /*
  1411. * Wake up waiters matching bitset queued on this futex (uaddr).
  1412. */
  1413. static int
  1414. futex_wake(u32 __user *uaddr, unsigned int flags, int nr_wake, u32 bitset)
  1415. {
  1416. struct futex_hash_bucket *hb;
  1417. struct futex_q *this, *next;
  1418. union futex_key key = FUTEX_KEY_INIT;
  1419. int ret;
  1420. DEFINE_WAKE_Q(wake_q);
  1421. if (!bitset)
  1422. return -EINVAL;
  1423. ret = get_futex_key(uaddr, flags & FLAGS_SHARED, &key, VERIFY_READ);
  1424. if (unlikely(ret != 0))
  1425. goto out;
  1426. hb = hash_futex(&key);
  1427. /* Make sure we really have tasks to wakeup */
  1428. if (!hb_waiters_pending(hb))
  1429. goto out_put_key;
  1430. spin_lock(&hb->lock);
  1431. plist_for_each_entry_safe(this, next, &hb->chain, list) {
  1432. if (match_futex (&this->key, &key)) {
  1433. if (this->pi_state || this->rt_waiter) {
  1434. ret = -EINVAL;
  1435. break;
  1436. }
  1437. /* Check if one of the bits is set in both bitsets */
  1438. if (!(this->bitset & bitset))
  1439. continue;
  1440. mark_wake_futex(&wake_q, this);
  1441. if (++ret >= nr_wake)
  1442. break;
  1443. }
  1444. }
  1445. spin_unlock(&hb->lock);
  1446. wake_up_q(&wake_q);
  1447. out_put_key:
  1448. put_futex_key(&key);
  1449. out:
  1450. return ret;
  1451. }
  1452. static int futex_atomic_op_inuser(unsigned int encoded_op, u32 __user *uaddr)
  1453. {
  1454. unsigned int op = (encoded_op & 0x70000000) >> 28;
  1455. unsigned int cmp = (encoded_op & 0x0f000000) >> 24;
  1456. int oparg = sign_extend32((encoded_op & 0x00fff000) >> 12, 11);
  1457. int cmparg = sign_extend32(encoded_op & 0x00000fff, 11);
  1458. int oldval, ret;
  1459. if (encoded_op & (FUTEX_OP_OPARG_SHIFT << 28)) {
  1460. if (oparg < 0 || oparg > 31) {
  1461. char comm[sizeof(current->comm)];
  1462. /*
  1463. * kill this print and return -EINVAL when userspace
  1464. * is sane again
  1465. */
  1466. pr_info_ratelimited("futex_wake_op: %s tries to shift op by %d; fix this program\n",
  1467. get_task_comm(comm, current), oparg);
  1468. oparg &= 31;
  1469. }
  1470. oparg = 1 << oparg;
  1471. }
  1472. if (!access_ok(VERIFY_WRITE, uaddr, sizeof(u32)))
  1473. return -EFAULT;
  1474. ret = arch_futex_atomic_op_inuser(op, oparg, &oldval, uaddr);
  1475. if (ret)
  1476. return ret;
  1477. switch (cmp) {
  1478. case FUTEX_OP_CMP_EQ:
  1479. return oldval == cmparg;
  1480. case FUTEX_OP_CMP_NE:
  1481. return oldval != cmparg;
  1482. case FUTEX_OP_CMP_LT:
  1483. return oldval < cmparg;
  1484. case FUTEX_OP_CMP_GE:
  1485. return oldval >= cmparg;
  1486. case FUTEX_OP_CMP_LE:
  1487. return oldval <= cmparg;
  1488. case FUTEX_OP_CMP_GT:
  1489. return oldval > cmparg;
  1490. default:
  1491. return -ENOSYS;
  1492. }
  1493. }
  1494. /*
  1495. * Wake up all waiters hashed on the physical page that is mapped
  1496. * to this virtual address:
  1497. */
  1498. static int
  1499. futex_wake_op(u32 __user *uaddr1, unsigned int flags, u32 __user *uaddr2,
  1500. int nr_wake, int nr_wake2, int op)
  1501. {
  1502. union futex_key key1 = FUTEX_KEY_INIT, key2 = FUTEX_KEY_INIT;
  1503. struct futex_hash_bucket *hb1, *hb2;
  1504. struct futex_q *this, *next;
  1505. int ret, op_ret;
  1506. DEFINE_WAKE_Q(wake_q);
  1507. retry:
  1508. ret = get_futex_key(uaddr1, flags & FLAGS_SHARED, &key1, VERIFY_READ);
  1509. if (unlikely(ret != 0))
  1510. goto out;
  1511. ret = get_futex_key(uaddr2, flags & FLAGS_SHARED, &key2, VERIFY_WRITE);
  1512. if (unlikely(ret != 0))
  1513. goto out_put_key1;
  1514. hb1 = hash_futex(&key1);
  1515. hb2 = hash_futex(&key2);
  1516. retry_private:
  1517. double_lock_hb(hb1, hb2);
  1518. op_ret = futex_atomic_op_inuser(op, uaddr2);
  1519. if (unlikely(op_ret < 0)) {
  1520. double_unlock_hb(hb1, hb2);
  1521. if (!IS_ENABLED(CONFIG_MMU) ||
  1522. unlikely(op_ret != -EFAULT && op_ret != -EAGAIN)) {
  1523. /*
  1524. * we don't get EFAULT from MMU faults if we don't have
  1525. * an MMU, but we might get them from range checking
  1526. */
  1527. ret = op_ret;
  1528. goto out_put_keys;
  1529. }
  1530. if (op_ret == -EFAULT) {
  1531. ret = fault_in_user_writeable(uaddr2);
  1532. if (ret)
  1533. goto out_put_keys;
  1534. }
  1535. if (!(flags & FLAGS_SHARED)) {
  1536. cond_resched();
  1537. goto retry_private;
  1538. }
  1539. put_futex_key(&key2);
  1540. put_futex_key(&key1);
  1541. cond_resched();
  1542. goto retry;
  1543. }
  1544. plist_for_each_entry_safe(this, next, &hb1->chain, list) {
  1545. if (match_futex (&this->key, &key1)) {
  1546. if (this->pi_state || this->rt_waiter) {
  1547. ret = -EINVAL;
  1548. goto out_unlock;
  1549. }
  1550. mark_wake_futex(&wake_q, this);
  1551. if (++ret >= nr_wake)
  1552. break;
  1553. }
  1554. }
  1555. if (op_ret > 0) {
  1556. op_ret = 0;
  1557. plist_for_each_entry_safe(this, next, &hb2->chain, list) {
  1558. if (match_futex (&this->key, &key2)) {
  1559. if (this->pi_state || this->rt_waiter) {
  1560. ret = -EINVAL;
  1561. goto out_unlock;
  1562. }
  1563. mark_wake_futex(&wake_q, this);
  1564. if (++op_ret >= nr_wake2)
  1565. break;
  1566. }
  1567. }
  1568. ret += op_ret;
  1569. }
  1570. out_unlock:
  1571. double_unlock_hb(hb1, hb2);
  1572. wake_up_q(&wake_q);
  1573. out_put_keys:
  1574. put_futex_key(&key2);
  1575. out_put_key1:
  1576. put_futex_key(&key1);
  1577. out:
  1578. return ret;
  1579. }
  1580. /**
  1581. * requeue_futex() - Requeue a futex_q from one hb to another
  1582. * @q: the futex_q to requeue
  1583. * @hb1: the source hash_bucket
  1584. * @hb2: the target hash_bucket
  1585. * @key2: the new key for the requeued futex_q
  1586. */
  1587. static inline
  1588. void requeue_futex(struct futex_q *q, struct futex_hash_bucket *hb1,
  1589. struct futex_hash_bucket *hb2, union futex_key *key2)
  1590. {
  1591. /*
  1592. * If key1 and key2 hash to the same bucket, no need to
  1593. * requeue.
  1594. */
  1595. if (likely(&hb1->chain != &hb2->chain)) {
  1596. plist_del(&q->list, &hb1->chain);
  1597. hb_waiters_dec(hb1);
  1598. hb_waiters_inc(hb2);
  1599. plist_add(&q->list, &hb2->chain);
  1600. q->lock_ptr = &hb2->lock;
  1601. }
  1602. get_futex_key_refs(key2);
  1603. q->key = *key2;
  1604. }
  1605. /**
  1606. * requeue_pi_wake_futex() - Wake a task that acquired the lock during requeue
  1607. * @q: the futex_q
  1608. * @key: the key of the requeue target futex
  1609. * @hb: the hash_bucket of the requeue target futex
  1610. *
  1611. * During futex_requeue, with requeue_pi=1, it is possible to acquire the
  1612. * target futex if it is uncontended or via a lock steal. Set the futex_q key
  1613. * to the requeue target futex so the waiter can detect the wakeup on the right
  1614. * futex, but remove it from the hb and NULL the rt_waiter so it can detect
  1615. * atomic lock acquisition. Set the q->lock_ptr to the requeue target hb->lock
  1616. * to protect access to the pi_state to fixup the owner later. Must be called
  1617. * with both q->lock_ptr and hb->lock held.
  1618. */
  1619. static inline
  1620. void requeue_pi_wake_futex(struct futex_q *q, union futex_key *key,
  1621. struct futex_hash_bucket *hb)
  1622. {
  1623. get_futex_key_refs(key);
  1624. q->key = *key;
  1625. __unqueue_futex(q);
  1626. WARN_ON(!q->rt_waiter);
  1627. q->rt_waiter = NULL;
  1628. q->lock_ptr = &hb->lock;
  1629. wake_up_state(q->task, TASK_NORMAL);
  1630. }
  1631. /**
  1632. * futex_proxy_trylock_atomic() - Attempt an atomic lock for the top waiter
  1633. * @pifutex: the user address of the to futex
  1634. * @hb1: the from futex hash bucket, must be locked by the caller
  1635. * @hb2: the to futex hash bucket, must be locked by the caller
  1636. * @key1: the from futex key
  1637. * @key2: the to futex key
  1638. * @ps: address to store the pi_state pointer
  1639. * @set_waiters: force setting the FUTEX_WAITERS bit (1) or not (0)
  1640. *
  1641. * Try and get the lock on behalf of the top waiter if we can do it atomically.
  1642. * Wake the top waiter if we succeed. If the caller specified set_waiters,
  1643. * then direct futex_lock_pi_atomic() to force setting the FUTEX_WAITERS bit.
  1644. * hb1 and hb2 must be held by the caller.
  1645. *
  1646. * Return:
  1647. * - 0 - failed to acquire the lock atomically;
  1648. * - >0 - acquired the lock, return value is vpid of the top_waiter
  1649. * - <0 - error
  1650. */
  1651. static int futex_proxy_trylock_atomic(u32 __user *pifutex,
  1652. struct futex_hash_bucket *hb1,
  1653. struct futex_hash_bucket *hb2,
  1654. union futex_key *key1, union futex_key *key2,
  1655. struct futex_pi_state **ps, int set_waiters)
  1656. {
  1657. struct futex_q *top_waiter = NULL;
  1658. u32 curval;
  1659. int ret, vpid;
  1660. if (get_futex_value_locked(&curval, pifutex))
  1661. return -EFAULT;
  1662. if (unlikely(should_fail_futex(true)))
  1663. return -EFAULT;
  1664. /*
  1665. * Find the top_waiter and determine if there are additional waiters.
  1666. * If the caller intends to requeue more than 1 waiter to pifutex,
  1667. * force futex_lock_pi_atomic() to set the FUTEX_WAITERS bit now,
  1668. * as we have means to handle the possible fault. If not, don't set
  1669. * the bit unecessarily as it will force the subsequent unlock to enter
  1670. * the kernel.
  1671. */
  1672. top_waiter = futex_top_waiter(hb1, key1);
  1673. /* There are no waiters, nothing for us to do. */
  1674. if (!top_waiter)
  1675. return 0;
  1676. /* Ensure we requeue to the expected futex. */
  1677. if (!match_futex(top_waiter->requeue_pi_key, key2))
  1678. return -EINVAL;
  1679. /*
  1680. * Try to take the lock for top_waiter. Set the FUTEX_WAITERS bit in
  1681. * the contended case or if set_waiters is 1. The pi_state is returned
  1682. * in ps in contended cases.
  1683. */
  1684. vpid = task_pid_vnr(top_waiter->task);
  1685. ret = futex_lock_pi_atomic(pifutex, hb2, key2, ps, top_waiter->task,
  1686. set_waiters);
  1687. if (ret == 1) {
  1688. requeue_pi_wake_futex(top_waiter, key2, hb2);
  1689. return vpid;
  1690. }
  1691. return ret;
  1692. }
  1693. /**
  1694. * futex_requeue() - Requeue waiters from uaddr1 to uaddr2
  1695. * @uaddr1: source futex user address
  1696. * @flags: futex flags (FLAGS_SHARED, etc.)
  1697. * @uaddr2: target futex user address
  1698. * @nr_wake: number of waiters to wake (must be 1 for requeue_pi)
  1699. * @nr_requeue: number of waiters to requeue (0-INT_MAX)
  1700. * @cmpval: @uaddr1 expected value (or %NULL)
  1701. * @requeue_pi: if we are attempting to requeue from a non-pi futex to a
  1702. * pi futex (pi to pi requeue is not supported)
  1703. *
  1704. * Requeue waiters on uaddr1 to uaddr2. In the requeue_pi case, try to acquire
  1705. * uaddr2 atomically on behalf of the top waiter.
  1706. *
  1707. * Return:
  1708. * - >=0 - on success, the number of tasks requeued or woken;
  1709. * - <0 - on error
  1710. */
  1711. static int futex_requeue(u32 __user *uaddr1, unsigned int flags,
  1712. u32 __user *uaddr2, int nr_wake, int nr_requeue,
  1713. u32 *cmpval, int requeue_pi)
  1714. {
  1715. union futex_key key1 = FUTEX_KEY_INIT, key2 = FUTEX_KEY_INIT;
  1716. int drop_count = 0, task_count = 0, ret;
  1717. struct futex_pi_state *pi_state = NULL;
  1718. struct futex_hash_bucket *hb1, *hb2;
  1719. struct futex_q *this, *next;
  1720. DEFINE_WAKE_Q(wake_q);
  1721. if (nr_wake < 0 || nr_requeue < 0)
  1722. return -EINVAL;
  1723. /*
  1724. * When PI not supported: return -ENOSYS if requeue_pi is true,
  1725. * consequently the compiler knows requeue_pi is always false past
  1726. * this point which will optimize away all the conditional code
  1727. * further down.
  1728. */
  1729. if (!IS_ENABLED(CONFIG_FUTEX_PI) && requeue_pi)
  1730. return -ENOSYS;
  1731. if (requeue_pi) {
  1732. /*
  1733. * Requeue PI only works on two distinct uaddrs. This
  1734. * check is only valid for private futexes. See below.
  1735. */
  1736. if (uaddr1 == uaddr2)
  1737. return -EINVAL;
  1738. /*
  1739. * requeue_pi requires a pi_state, try to allocate it now
  1740. * without any locks in case it fails.
  1741. */
  1742. if (refill_pi_state_cache())
  1743. return -ENOMEM;
  1744. /*
  1745. * requeue_pi must wake as many tasks as it can, up to nr_wake
  1746. * + nr_requeue, since it acquires the rt_mutex prior to
  1747. * returning to userspace, so as to not leave the rt_mutex with
  1748. * waiters and no owner. However, second and third wake-ups
  1749. * cannot be predicted as they involve race conditions with the
  1750. * first wake and a fault while looking up the pi_state. Both
  1751. * pthread_cond_signal() and pthread_cond_broadcast() should
  1752. * use nr_wake=1.
  1753. */
  1754. if (nr_wake != 1)
  1755. return -EINVAL;
  1756. }
  1757. retry:
  1758. ret = get_futex_key(uaddr1, flags & FLAGS_SHARED, &key1, VERIFY_READ);
  1759. if (unlikely(ret != 0))
  1760. goto out;
  1761. ret = get_futex_key(uaddr2, flags & FLAGS_SHARED, &key2,
  1762. requeue_pi ? VERIFY_WRITE : VERIFY_READ);
  1763. if (unlikely(ret != 0))
  1764. goto out_put_key1;
  1765. /*
  1766. * The check above which compares uaddrs is not sufficient for
  1767. * shared futexes. We need to compare the keys:
  1768. */
  1769. if (requeue_pi && match_futex(&key1, &key2)) {
  1770. ret = -EINVAL;
  1771. goto out_put_keys;
  1772. }
  1773. hb1 = hash_futex(&key1);
  1774. hb2 = hash_futex(&key2);
  1775. retry_private:
  1776. hb_waiters_inc(hb2);
  1777. double_lock_hb(hb1, hb2);
  1778. if (likely(cmpval != NULL)) {
  1779. u32 curval;
  1780. ret = get_futex_value_locked(&curval, uaddr1);
  1781. if (unlikely(ret)) {
  1782. double_unlock_hb(hb1, hb2);
  1783. hb_waiters_dec(hb2);
  1784. ret = get_user(curval, uaddr1);
  1785. if (ret)
  1786. goto out_put_keys;
  1787. if (!(flags & FLAGS_SHARED))
  1788. goto retry_private;
  1789. put_futex_key(&key2);
  1790. put_futex_key(&key1);
  1791. goto retry;
  1792. }
  1793. if (curval != *cmpval) {
  1794. ret = -EAGAIN;
  1795. goto out_unlock;
  1796. }
  1797. }
  1798. if (requeue_pi && (task_count - nr_wake < nr_requeue)) {
  1799. /*
  1800. * Attempt to acquire uaddr2 and wake the top waiter. If we
  1801. * intend to requeue waiters, force setting the FUTEX_WAITERS
  1802. * bit. We force this here where we are able to easily handle
  1803. * faults rather in the requeue loop below.
  1804. */
  1805. ret = futex_proxy_trylock_atomic(uaddr2, hb1, hb2, &key1,
  1806. &key2, &pi_state, nr_requeue);
  1807. /*
  1808. * At this point the top_waiter has either taken uaddr2 or is
  1809. * waiting on it. If the former, then the pi_state will not
  1810. * exist yet, look it up one more time to ensure we have a
  1811. * reference to it. If the lock was taken, ret contains the
  1812. * vpid of the top waiter task.
  1813. * If the lock was not taken, we have pi_state and an initial
  1814. * refcount on it. In case of an error we have nothing.
  1815. */
  1816. if (ret > 0) {
  1817. WARN_ON(pi_state);
  1818. drop_count++;
  1819. task_count++;
  1820. /*
  1821. * If we acquired the lock, then the user space value
  1822. * of uaddr2 should be vpid. It cannot be changed by
  1823. * the top waiter as it is blocked on hb2 lock if it
  1824. * tries to do so. If something fiddled with it behind
  1825. * our back the pi state lookup might unearth it. So
  1826. * we rather use the known value than rereading and
  1827. * handing potential crap to lookup_pi_state.
  1828. *
  1829. * If that call succeeds then we have pi_state and an
  1830. * initial refcount on it.
  1831. */
  1832. ret = lookup_pi_state(uaddr2, ret, hb2, &key2, &pi_state);
  1833. }
  1834. switch (ret) {
  1835. case 0:
  1836. /* We hold a reference on the pi state. */
  1837. break;
  1838. /* If the above failed, then pi_state is NULL */
  1839. case -EFAULT:
  1840. double_unlock_hb(hb1, hb2);
  1841. hb_waiters_dec(hb2);
  1842. put_futex_key(&key2);
  1843. put_futex_key(&key1);
  1844. ret = fault_in_user_writeable(uaddr2);
  1845. if (!ret)
  1846. goto retry;
  1847. goto out;
  1848. case -EAGAIN:
  1849. /*
  1850. * Two reasons for this:
  1851. * - Owner is exiting and we just wait for the
  1852. * exit to complete.
  1853. * - The user space value changed.
  1854. */
  1855. double_unlock_hb(hb1, hb2);
  1856. hb_waiters_dec(hb2);
  1857. put_futex_key(&key2);
  1858. put_futex_key(&key1);
  1859. cond_resched();
  1860. goto retry;
  1861. default:
  1862. goto out_unlock;
  1863. }
  1864. }
  1865. plist_for_each_entry_safe(this, next, &hb1->chain, list) {
  1866. if (task_count - nr_wake >= nr_requeue)
  1867. break;
  1868. if (!match_futex(&this->key, &key1))
  1869. continue;
  1870. /*
  1871. * FUTEX_WAIT_REQEUE_PI and FUTEX_CMP_REQUEUE_PI should always
  1872. * be paired with each other and no other futex ops.
  1873. *
  1874. * We should never be requeueing a futex_q with a pi_state,
  1875. * which is awaiting a futex_unlock_pi().
  1876. */
  1877. if ((requeue_pi && !this->rt_waiter) ||
  1878. (!requeue_pi && this->rt_waiter) ||
  1879. this->pi_state) {
  1880. ret = -EINVAL;
  1881. break;
  1882. }
  1883. /*
  1884. * Wake nr_wake waiters. For requeue_pi, if we acquired the
  1885. * lock, we already woke the top_waiter. If not, it will be
  1886. * woken by futex_unlock_pi().
  1887. */
  1888. if (++task_count <= nr_wake && !requeue_pi) {
  1889. mark_wake_futex(&wake_q, this);
  1890. continue;
  1891. }
  1892. /* Ensure we requeue to the expected futex for requeue_pi. */
  1893. if (requeue_pi && !match_futex(this->requeue_pi_key, &key2)) {
  1894. ret = -EINVAL;
  1895. break;
  1896. }
  1897. /*
  1898. * Requeue nr_requeue waiters and possibly one more in the case
  1899. * of requeue_pi if we couldn't acquire the lock atomically.
  1900. */
  1901. if (requeue_pi) {
  1902. /*
  1903. * Prepare the waiter to take the rt_mutex. Take a
  1904. * refcount on the pi_state and store the pointer in
  1905. * the futex_q object of the waiter.
  1906. */
  1907. get_pi_state(pi_state);
  1908. this->pi_state = pi_state;
  1909. ret = rt_mutex_start_proxy_lock(&pi_state->pi_mutex,
  1910. this->rt_waiter,
  1911. this->task);
  1912. if (ret == 1) {
  1913. /*
  1914. * We got the lock. We do neither drop the
  1915. * refcount on pi_state nor clear
  1916. * this->pi_state because the waiter needs the
  1917. * pi_state for cleaning up the user space
  1918. * value. It will drop the refcount after
  1919. * doing so.
  1920. */
  1921. requeue_pi_wake_futex(this, &key2, hb2);
  1922. drop_count++;
  1923. continue;
  1924. } else if (ret) {
  1925. /*
  1926. * rt_mutex_start_proxy_lock() detected a
  1927. * potential deadlock when we tried to queue
  1928. * that waiter. Drop the pi_state reference
  1929. * which we took above and remove the pointer
  1930. * to the state from the waiters futex_q
  1931. * object.
  1932. */
  1933. this->pi_state = NULL;
  1934. put_pi_state(pi_state);
  1935. /*
  1936. * We stop queueing more waiters and let user
  1937. * space deal with the mess.
  1938. */
  1939. break;
  1940. }
  1941. }
  1942. requeue_futex(this, hb1, hb2, &key2);
  1943. drop_count++;
  1944. }
  1945. /*
  1946. * We took an extra initial reference to the pi_state either
  1947. * in futex_proxy_trylock_atomic() or in lookup_pi_state(). We
  1948. * need to drop it here again.
  1949. */
  1950. put_pi_state(pi_state);
  1951. out_unlock:
  1952. double_unlock_hb(hb1, hb2);
  1953. wake_up_q(&wake_q);
  1954. hb_waiters_dec(hb2);
  1955. /*
  1956. * drop_futex_key_refs() must be called outside the spinlocks. During
  1957. * the requeue we moved futex_q's from the hash bucket at key1 to the
  1958. * one at key2 and updated their key pointer. We no longer need to
  1959. * hold the references to key1.
  1960. */
  1961. while (--drop_count >= 0)
  1962. drop_futex_key_refs(&key1);
  1963. out_put_keys:
  1964. put_futex_key(&key2);
  1965. out_put_key1:
  1966. put_futex_key(&key1);
  1967. out:
  1968. return ret ? ret : task_count;
  1969. }
  1970. /* The key must be already stored in q->key. */
  1971. static inline struct futex_hash_bucket *queue_lock(struct futex_q *q)
  1972. __acquires(&hb->lock)
  1973. {
  1974. struct futex_hash_bucket *hb;
  1975. hb = hash_futex(&q->key);
  1976. /*
  1977. * Increment the counter before taking the lock so that
  1978. * a potential waker won't miss a to-be-slept task that is
  1979. * waiting for the spinlock. This is safe as all queue_lock()
  1980. * users end up calling queue_me(). Similarly, for housekeeping,
  1981. * decrement the counter at queue_unlock() when some error has
  1982. * occurred and we don't end up adding the task to the list.
  1983. */
  1984. hb_waiters_inc(hb);
  1985. q->lock_ptr = &hb->lock;
  1986. spin_lock(&hb->lock); /* implies smp_mb(); (A) */
  1987. return hb;
  1988. }
  1989. static inline void
  1990. queue_unlock(struct futex_hash_bucket *hb)
  1991. __releases(&hb->lock)
  1992. {
  1993. spin_unlock(&hb->lock);
  1994. hb_waiters_dec(hb);
  1995. }
  1996. static inline void __queue_me(struct futex_q *q, struct futex_hash_bucket *hb)
  1997. {
  1998. int prio;
  1999. /*
  2000. * The priority used to register this element is
  2001. * - either the real thread-priority for the real-time threads
  2002. * (i.e. threads with a priority lower than MAX_RT_PRIO)
  2003. * - or MAX_RT_PRIO for non-RT threads.
  2004. * Thus, all RT-threads are woken first in priority order, and
  2005. * the others are woken last, in FIFO order.
  2006. */
  2007. prio = min(current->normal_prio, MAX_RT_PRIO);
  2008. plist_node_init(&q->list, prio);
  2009. plist_add(&q->list, &hb->chain);
  2010. q->task = current;
  2011. }
  2012. /**
  2013. * queue_me() - Enqueue the futex_q on the futex_hash_bucket
  2014. * @q: The futex_q to enqueue
  2015. * @hb: The destination hash bucket
  2016. *
  2017. * The hb->lock must be held by the caller, and is released here. A call to
  2018. * queue_me() is typically paired with exactly one call to unqueue_me(). The
  2019. * exceptions involve the PI related operations, which may use unqueue_me_pi()
  2020. * or nothing if the unqueue is done as part of the wake process and the unqueue
  2021. * state is implicit in the state of woken task (see futex_wait_requeue_pi() for
  2022. * an example).
  2023. */
  2024. static inline void queue_me(struct futex_q *q, struct futex_hash_bucket *hb)
  2025. __releases(&hb->lock)
  2026. {
  2027. __queue_me(q, hb);
  2028. spin_unlock(&hb->lock);
  2029. }
  2030. /**
  2031. * unqueue_me() - Remove the futex_q from its futex_hash_bucket
  2032. * @q: The futex_q to unqueue
  2033. *
  2034. * The q->lock_ptr must not be held by the caller. A call to unqueue_me() must
  2035. * be paired with exactly one earlier call to queue_me().
  2036. *
  2037. * Return:
  2038. * - 1 - if the futex_q was still queued (and we removed unqueued it);
  2039. * - 0 - if the futex_q was already removed by the waking thread
  2040. */
  2041. static int unqueue_me(struct futex_q *q)
  2042. {
  2043. spinlock_t *lock_ptr;
  2044. int ret = 0;
  2045. /* In the common case we don't take the spinlock, which is nice. */
  2046. retry:
  2047. /*
  2048. * q->lock_ptr can change between this read and the following spin_lock.
  2049. * Use READ_ONCE to forbid the compiler from reloading q->lock_ptr and
  2050. * optimizing lock_ptr out of the logic below.
  2051. */
  2052. lock_ptr = READ_ONCE(q->lock_ptr);
  2053. if (lock_ptr != NULL) {
  2054. spin_lock(lock_ptr);
  2055. /*
  2056. * q->lock_ptr can change between reading it and
  2057. * spin_lock(), causing us to take the wrong lock. This
  2058. * corrects the race condition.
  2059. *
  2060. * Reasoning goes like this: if we have the wrong lock,
  2061. * q->lock_ptr must have changed (maybe several times)
  2062. * between reading it and the spin_lock(). It can
  2063. * change again after the spin_lock() but only if it was
  2064. * already changed before the spin_lock(). It cannot,
  2065. * however, change back to the original value. Therefore
  2066. * we can detect whether we acquired the correct lock.
  2067. */
  2068. if (unlikely(lock_ptr != q->lock_ptr)) {
  2069. spin_unlock(lock_ptr);
  2070. goto retry;
  2071. }
  2072. __unqueue_futex(q);
  2073. BUG_ON(q->pi_state);
  2074. spin_unlock(lock_ptr);
  2075. ret = 1;
  2076. }
  2077. drop_futex_key_refs(&q->key);
  2078. return ret;
  2079. }
  2080. /*
  2081. * PI futexes can not be requeued and must remove themself from the
  2082. * hash bucket. The hash bucket lock (i.e. lock_ptr) is held on entry
  2083. * and dropped here.
  2084. */
  2085. static void unqueue_me_pi(struct futex_q *q)
  2086. __releases(q->lock_ptr)
  2087. {
  2088. __unqueue_futex(q);
  2089. BUG_ON(!q->pi_state);
  2090. put_pi_state(q->pi_state);
  2091. q->pi_state = NULL;
  2092. spin_unlock(q->lock_ptr);
  2093. }
  2094. static int fixup_pi_state_owner(u32 __user *uaddr, struct futex_q *q,
  2095. struct task_struct *argowner)
  2096. {
  2097. struct futex_pi_state *pi_state = q->pi_state;
  2098. u32 uval, uninitialized_var(curval), newval;
  2099. struct task_struct *oldowner, *newowner;
  2100. u32 newtid;
  2101. int ret, err = 0;
  2102. lockdep_assert_held(q->lock_ptr);
  2103. raw_spin_lock_irq(&pi_state->pi_mutex.wait_lock);
  2104. oldowner = pi_state->owner;
  2105. /*
  2106. * We are here because either:
  2107. *
  2108. * - we stole the lock and pi_state->owner needs updating to reflect
  2109. * that (@argowner == current),
  2110. *
  2111. * or:
  2112. *
  2113. * - someone stole our lock and we need to fix things to point to the
  2114. * new owner (@argowner == NULL).
  2115. *
  2116. * Either way, we have to replace the TID in the user space variable.
  2117. * This must be atomic as we have to preserve the owner died bit here.
  2118. *
  2119. * Note: We write the user space value _before_ changing the pi_state
  2120. * because we can fault here. Imagine swapped out pages or a fork
  2121. * that marked all the anonymous memory readonly for cow.
  2122. *
  2123. * Modifying pi_state _before_ the user space value would leave the
  2124. * pi_state in an inconsistent state when we fault here, because we
  2125. * need to drop the locks to handle the fault. This might be observed
  2126. * in the PID check in lookup_pi_state.
  2127. */
  2128. retry:
  2129. if (!argowner) {
  2130. if (oldowner != current) {
  2131. /*
  2132. * We raced against a concurrent self; things are
  2133. * already fixed up. Nothing to do.
  2134. */
  2135. ret = 0;
  2136. goto out_unlock;
  2137. }
  2138. if (__rt_mutex_futex_trylock(&pi_state->pi_mutex)) {
  2139. /* We got the lock after all, nothing to fix. */
  2140. ret = 0;
  2141. goto out_unlock;
  2142. }
  2143. /*
  2144. * Since we just failed the trylock; there must be an owner.
  2145. */
  2146. newowner = rt_mutex_owner(&pi_state->pi_mutex);
  2147. BUG_ON(!newowner);
  2148. } else {
  2149. WARN_ON_ONCE(argowner != current);
  2150. if (oldowner == current) {
  2151. /*
  2152. * We raced against a concurrent self; things are
  2153. * already fixed up. Nothing to do.
  2154. */
  2155. ret = 0;
  2156. goto out_unlock;
  2157. }
  2158. newowner = argowner;
  2159. }
  2160. newtid = task_pid_vnr(newowner) | FUTEX_WAITERS;
  2161. /* Owner died? */
  2162. if (!pi_state->owner)
  2163. newtid |= FUTEX_OWNER_DIED;
  2164. err = get_futex_value_locked(&uval, uaddr);
  2165. if (err)
  2166. goto handle_err;
  2167. for (;;) {
  2168. newval = (uval & FUTEX_OWNER_DIED) | newtid;
  2169. err = cmpxchg_futex_value_locked(&curval, uaddr, uval, newval);
  2170. if (err)
  2171. goto handle_err;
  2172. if (curval == uval)
  2173. break;
  2174. uval = curval;
  2175. }
  2176. /*
  2177. * We fixed up user space. Now we need to fix the pi_state
  2178. * itself.
  2179. */
  2180. if (pi_state->owner != NULL) {
  2181. raw_spin_lock(&pi_state->owner->pi_lock);
  2182. WARN_ON(list_empty(&pi_state->list));
  2183. list_del_init(&pi_state->list);
  2184. raw_spin_unlock(&pi_state->owner->pi_lock);
  2185. }
  2186. pi_state->owner = newowner;
  2187. raw_spin_lock(&newowner->pi_lock);
  2188. WARN_ON(!list_empty(&pi_state->list));
  2189. list_add(&pi_state->list, &newowner->pi_state_list);
  2190. raw_spin_unlock(&newowner->pi_lock);
  2191. raw_spin_unlock_irq(&pi_state->pi_mutex.wait_lock);
  2192. return 0;
  2193. /*
  2194. * In order to reschedule or handle a page fault, we need to drop the
  2195. * locks here. In the case of a fault, this gives the other task
  2196. * (either the highest priority waiter itself or the task which stole
  2197. * the rtmutex) the chance to try the fixup of the pi_state. So once we
  2198. * are back from handling the fault we need to check the pi_state after
  2199. * reacquiring the locks and before trying to do another fixup. When
  2200. * the fixup has been done already we simply return.
  2201. *
  2202. * Note: we hold both hb->lock and pi_mutex->wait_lock. We can safely
  2203. * drop hb->lock since the caller owns the hb -> futex_q relation.
  2204. * Dropping the pi_mutex->wait_lock requires the state revalidate.
  2205. */
  2206. handle_err:
  2207. raw_spin_unlock_irq(&pi_state->pi_mutex.wait_lock);
  2208. spin_unlock(q->lock_ptr);
  2209. switch (err) {
  2210. case -EFAULT:
  2211. ret = fault_in_user_writeable(uaddr);
  2212. break;
  2213. case -EAGAIN:
  2214. cond_resched();
  2215. ret = 0;
  2216. break;
  2217. default:
  2218. WARN_ON_ONCE(1);
  2219. ret = err;
  2220. break;
  2221. }
  2222. spin_lock(q->lock_ptr);
  2223. raw_spin_lock_irq(&pi_state->pi_mutex.wait_lock);
  2224. /*
  2225. * Check if someone else fixed it for us:
  2226. */
  2227. if (pi_state->owner != oldowner) {
  2228. ret = 0;
  2229. goto out_unlock;
  2230. }
  2231. if (ret)
  2232. goto out_unlock;
  2233. goto retry;
  2234. out_unlock:
  2235. raw_spin_unlock_irq(&pi_state->pi_mutex.wait_lock);
  2236. return ret;
  2237. }
  2238. static long futex_wait_restart(struct restart_block *restart);
  2239. /**
  2240. * fixup_owner() - Post lock pi_state and corner case management
  2241. * @uaddr: user address of the futex
  2242. * @q: futex_q (contains pi_state and access to the rt_mutex)
  2243. * @locked: if the attempt to take the rt_mutex succeeded (1) or not (0)
  2244. *
  2245. * After attempting to lock an rt_mutex, this function is called to cleanup
  2246. * the pi_state owner as well as handle race conditions that may allow us to
  2247. * acquire the lock. Must be called with the hb lock held.
  2248. *
  2249. * Return:
  2250. * - 1 - success, lock taken;
  2251. * - 0 - success, lock not taken;
  2252. * - <0 - on error (-EFAULT)
  2253. */
  2254. static int fixup_owner(u32 __user *uaddr, struct futex_q *q, int locked)
  2255. {
  2256. int ret = 0;
  2257. if (locked) {
  2258. /*
  2259. * Got the lock. We might not be the anticipated owner if we
  2260. * did a lock-steal - fix up the PI-state in that case:
  2261. *
  2262. * Speculative pi_state->owner read (we don't hold wait_lock);
  2263. * since we own the lock pi_state->owner == current is the
  2264. * stable state, anything else needs more attention.
  2265. */
  2266. if (q->pi_state->owner != current)
  2267. ret = fixup_pi_state_owner(uaddr, q, current);
  2268. goto out;
  2269. }
  2270. /*
  2271. * If we didn't get the lock; check if anybody stole it from us. In
  2272. * that case, we need to fix up the uval to point to them instead of
  2273. * us, otherwise bad things happen. [10]
  2274. *
  2275. * Another speculative read; pi_state->owner == current is unstable
  2276. * but needs our attention.
  2277. */
  2278. if (q->pi_state->owner == current) {
  2279. ret = fixup_pi_state_owner(uaddr, q, NULL);
  2280. goto out;
  2281. }
  2282. /*
  2283. * Paranoia check. If we did not take the lock, then we should not be
  2284. * the owner of the rt_mutex.
  2285. */
  2286. if (rt_mutex_owner(&q->pi_state->pi_mutex) == current) {
  2287. printk(KERN_ERR "fixup_owner: ret = %d pi-mutex: %p "
  2288. "pi-state %p\n", ret,
  2289. q->pi_state->pi_mutex.owner,
  2290. q->pi_state->owner);
  2291. }
  2292. out:
  2293. return ret ? ret : locked;
  2294. }
  2295. /**
  2296. * futex_wait_queue_me() - queue_me() and wait for wakeup, timeout, or signal
  2297. * @hb: the futex hash bucket, must be locked by the caller
  2298. * @q: the futex_q to queue up on
  2299. * @timeout: the prepared hrtimer_sleeper, or null for no timeout
  2300. */
  2301. static void futex_wait_queue_me(struct futex_hash_bucket *hb, struct futex_q *q,
  2302. struct hrtimer_sleeper *timeout)
  2303. {
  2304. /*
  2305. * The task state is guaranteed to be set before another task can
  2306. * wake it. set_current_state() is implemented using smp_store_mb() and
  2307. * queue_me() calls spin_unlock() upon completion, both serializing
  2308. * access to the hash list and forcing another memory barrier.
  2309. */
  2310. set_current_state(TASK_INTERRUPTIBLE);
  2311. queue_me(q, hb);
  2312. /* Arm the timer */
  2313. if (timeout)
  2314. hrtimer_start_expires(&timeout->timer, HRTIMER_MODE_ABS);
  2315. /*
  2316. * If we have been removed from the hash list, then another task
  2317. * has tried to wake us, and we can skip the call to schedule().
  2318. */
  2319. if (likely(!plist_node_empty(&q->list))) {
  2320. /*
  2321. * If the timer has already expired, current will already be
  2322. * flagged for rescheduling. Only call schedule if there
  2323. * is no timeout, or if it has yet to expire.
  2324. */
  2325. if (!timeout || timeout->task)
  2326. freezable_schedule();
  2327. }
  2328. __set_current_state(TASK_RUNNING);
  2329. }
  2330. /**
  2331. * futex_wait_setup() - Prepare to wait on a futex
  2332. * @uaddr: the futex userspace address
  2333. * @val: the expected value
  2334. * @flags: futex flags (FLAGS_SHARED, etc.)
  2335. * @q: the associated futex_q
  2336. * @hb: storage for hash_bucket pointer to be returned to caller
  2337. *
  2338. * Setup the futex_q and locate the hash_bucket. Get the futex value and
  2339. * compare it with the expected value. Handle atomic faults internally.
  2340. * Return with the hb lock held and a q.key reference on success, and unlocked
  2341. * with no q.key reference on failure.
  2342. *
  2343. * Return:
  2344. * - 0 - uaddr contains val and hb has been locked;
  2345. * - <1 - -EFAULT or -EWOULDBLOCK (uaddr does not contain val) and hb is unlocked
  2346. */
  2347. static int futex_wait_setup(u32 __user *uaddr, u32 val, unsigned int flags,
  2348. struct futex_q *q, struct futex_hash_bucket **hb)
  2349. {
  2350. u32 uval;
  2351. int ret;
  2352. /*
  2353. * Access the page AFTER the hash-bucket is locked.
  2354. * Order is important:
  2355. *
  2356. * Userspace waiter: val = var; if (cond(val)) futex_wait(&var, val);
  2357. * Userspace waker: if (cond(var)) { var = new; futex_wake(&var); }
  2358. *
  2359. * The basic logical guarantee of a futex is that it blocks ONLY
  2360. * if cond(var) is known to be true at the time of blocking, for
  2361. * any cond. If we locked the hash-bucket after testing *uaddr, that
  2362. * would open a race condition where we could block indefinitely with
  2363. * cond(var) false, which would violate the guarantee.
  2364. *
  2365. * On the other hand, we insert q and release the hash-bucket only
  2366. * after testing *uaddr. This guarantees that futex_wait() will NOT
  2367. * absorb a wakeup if *uaddr does not match the desired values
  2368. * while the syscall executes.
  2369. */
  2370. retry:
  2371. ret = get_futex_key(uaddr, flags & FLAGS_SHARED, &q->key, VERIFY_READ);
  2372. if (unlikely(ret != 0))
  2373. return ret;
  2374. retry_private:
  2375. *hb = queue_lock(q);
  2376. ret = get_futex_value_locked(&uval, uaddr);
  2377. if (ret) {
  2378. queue_unlock(*hb);
  2379. ret = get_user(uval, uaddr);
  2380. if (ret)
  2381. goto out;
  2382. if (!(flags & FLAGS_SHARED))
  2383. goto retry_private;
  2384. put_futex_key(&q->key);
  2385. goto retry;
  2386. }
  2387. if (uval != val) {
  2388. queue_unlock(*hb);
  2389. ret = -EWOULDBLOCK;
  2390. }
  2391. out:
  2392. if (ret)
  2393. put_futex_key(&q->key);
  2394. return ret;
  2395. }
  2396. static int futex_wait(u32 __user *uaddr, unsigned int flags, u32 val,
  2397. ktime_t *abs_time, u32 bitset)
  2398. {
  2399. struct hrtimer_sleeper timeout, *to = NULL;
  2400. struct restart_block *restart;
  2401. struct futex_hash_bucket *hb;
  2402. struct futex_q q = futex_q_init;
  2403. int ret;
  2404. if (!bitset)
  2405. return -EINVAL;
  2406. q.bitset = bitset;
  2407. if (abs_time) {
  2408. to = &timeout;
  2409. hrtimer_init_on_stack(&to->timer, (flags & FLAGS_CLOCKRT) ?
  2410. CLOCK_REALTIME : CLOCK_MONOTONIC,
  2411. HRTIMER_MODE_ABS);
  2412. hrtimer_init_sleeper(to, current);
  2413. hrtimer_set_expires_range_ns(&to->timer, *abs_time,
  2414. current->timer_slack_ns);
  2415. }
  2416. retry:
  2417. /*
  2418. * Prepare to wait on uaddr. On success, holds hb lock and increments
  2419. * q.key refs.
  2420. */
  2421. ret = futex_wait_setup(uaddr, val, flags, &q, &hb);
  2422. if (ret)
  2423. goto out;
  2424. /* queue_me and wait for wakeup, timeout, or a signal. */
  2425. futex_wait_queue_me(hb, &q, to);
  2426. /* If we were woken (and unqueued), we succeeded, whatever. */
  2427. ret = 0;
  2428. /* unqueue_me() drops q.key ref */
  2429. if (!unqueue_me(&q))
  2430. goto out;
  2431. ret = -ETIMEDOUT;
  2432. if (to && !to->task)
  2433. goto out;
  2434. /*
  2435. * We expect signal_pending(current), but we might be the
  2436. * victim of a spurious wakeup as well.
  2437. */
  2438. if (!signal_pending(current))
  2439. goto retry;
  2440. ret = -ERESTARTSYS;
  2441. if (!abs_time)
  2442. goto out;
  2443. restart = &current->restart_block;
  2444. restart->fn = futex_wait_restart;
  2445. restart->futex.uaddr = uaddr;
  2446. restart->futex.val = val;
  2447. restart->futex.time = *abs_time;
  2448. restart->futex.bitset = bitset;
  2449. restart->futex.flags = flags | FLAGS_HAS_TIMEOUT;
  2450. ret = -ERESTART_RESTARTBLOCK;
  2451. out:
  2452. if (to) {
  2453. hrtimer_cancel(&to->timer);
  2454. destroy_hrtimer_on_stack(&to->timer);
  2455. }
  2456. return ret;
  2457. }
  2458. static long futex_wait_restart(struct restart_block *restart)
  2459. {
  2460. u32 __user *uaddr = restart->futex.uaddr;
  2461. ktime_t t, *tp = NULL;
  2462. if (restart->futex.flags & FLAGS_HAS_TIMEOUT) {
  2463. t = restart->futex.time;
  2464. tp = &t;
  2465. }
  2466. restart->fn = do_no_restart_syscall;
  2467. return (long)futex_wait(uaddr, restart->futex.flags,
  2468. restart->futex.val, tp, restart->futex.bitset);
  2469. }
  2470. /*
  2471. * Userspace tried a 0 -> TID atomic transition of the futex value
  2472. * and failed. The kernel side here does the whole locking operation:
  2473. * if there are waiters then it will block as a consequence of relying
  2474. * on rt-mutexes, it does PI, etc. (Due to races the kernel might see
  2475. * a 0 value of the futex too.).
  2476. *
  2477. * Also serves as futex trylock_pi()'ing, and due semantics.
  2478. */
  2479. static int futex_lock_pi(u32 __user *uaddr, unsigned int flags,
  2480. ktime_t *time, int trylock)
  2481. {
  2482. struct hrtimer_sleeper timeout, *to = NULL;
  2483. struct futex_pi_state *pi_state = NULL;
  2484. struct rt_mutex_waiter rt_waiter;
  2485. struct futex_hash_bucket *hb;
  2486. struct futex_q q = futex_q_init;
  2487. int res, ret;
  2488. if (!IS_ENABLED(CONFIG_FUTEX_PI))
  2489. return -ENOSYS;
  2490. if (refill_pi_state_cache())
  2491. return -ENOMEM;
  2492. if (time) {
  2493. to = &timeout;
  2494. hrtimer_init_on_stack(&to->timer, CLOCK_REALTIME,
  2495. HRTIMER_MODE_ABS);
  2496. hrtimer_init_sleeper(to, current);
  2497. hrtimer_set_expires(&to->timer, *time);
  2498. }
  2499. retry:
  2500. ret = get_futex_key(uaddr, flags & FLAGS_SHARED, &q.key, VERIFY_WRITE);
  2501. if (unlikely(ret != 0))
  2502. goto out;
  2503. retry_private:
  2504. hb = queue_lock(&q);
  2505. ret = futex_lock_pi_atomic(uaddr, hb, &q.key, &q.pi_state, current, 0);
  2506. if (unlikely(ret)) {
  2507. /*
  2508. * Atomic work succeeded and we got the lock,
  2509. * or failed. Either way, we do _not_ block.
  2510. */
  2511. switch (ret) {
  2512. case 1:
  2513. /* We got the lock. */
  2514. ret = 0;
  2515. goto out_unlock_put_key;
  2516. case -EFAULT:
  2517. goto uaddr_faulted;
  2518. case -EAGAIN:
  2519. /*
  2520. * Two reasons for this:
  2521. * - Task is exiting and we just wait for the
  2522. * exit to complete.
  2523. * - The user space value changed.
  2524. */
  2525. queue_unlock(hb);
  2526. put_futex_key(&q.key);
  2527. cond_resched();
  2528. goto retry;
  2529. default:
  2530. goto out_unlock_put_key;
  2531. }
  2532. }
  2533. WARN_ON(!q.pi_state);
  2534. /*
  2535. * Only actually queue now that the atomic ops are done:
  2536. */
  2537. __queue_me(&q, hb);
  2538. if (trylock) {
  2539. ret = rt_mutex_futex_trylock(&q.pi_state->pi_mutex);
  2540. /* Fixup the trylock return value: */
  2541. ret = ret ? 0 : -EWOULDBLOCK;
  2542. goto no_block;
  2543. }
  2544. rt_mutex_init_waiter(&rt_waiter);
  2545. /*
  2546. * On PREEMPT_RT_FULL, when hb->lock becomes an rt_mutex, we must not
  2547. * hold it while doing rt_mutex_start_proxy(), because then it will
  2548. * include hb->lock in the blocking chain, even through we'll not in
  2549. * fact hold it while blocking. This will lead it to report -EDEADLK
  2550. * and BUG when futex_unlock_pi() interleaves with this.
  2551. *
  2552. * Therefore acquire wait_lock while holding hb->lock, but drop the
  2553. * latter before calling __rt_mutex_start_proxy_lock(). This
  2554. * interleaves with futex_unlock_pi() -- which does a similar lock
  2555. * handoff -- such that the latter can observe the futex_q::pi_state
  2556. * before __rt_mutex_start_proxy_lock() is done.
  2557. */
  2558. raw_spin_lock_irq(&q.pi_state->pi_mutex.wait_lock);
  2559. spin_unlock(q.lock_ptr);
  2560. /*
  2561. * __rt_mutex_start_proxy_lock() unconditionally enqueues the @rt_waiter
  2562. * such that futex_unlock_pi() is guaranteed to observe the waiter when
  2563. * it sees the futex_q::pi_state.
  2564. */
  2565. ret = __rt_mutex_start_proxy_lock(&q.pi_state->pi_mutex, &rt_waiter, current);
  2566. raw_spin_unlock_irq(&q.pi_state->pi_mutex.wait_lock);
  2567. if (ret) {
  2568. if (ret == 1)
  2569. ret = 0;
  2570. goto cleanup;
  2571. }
  2572. if (unlikely(to))
  2573. hrtimer_start_expires(&to->timer, HRTIMER_MODE_ABS);
  2574. ret = rt_mutex_wait_proxy_lock(&q.pi_state->pi_mutex, to, &rt_waiter);
  2575. cleanup:
  2576. spin_lock(q.lock_ptr);
  2577. /*
  2578. * If we failed to acquire the lock (deadlock/signal/timeout), we must
  2579. * first acquire the hb->lock before removing the lock from the
  2580. * rt_mutex waitqueue, such that we can keep the hb and rt_mutex wait
  2581. * lists consistent.
  2582. *
  2583. * In particular; it is important that futex_unlock_pi() can not
  2584. * observe this inconsistency.
  2585. */
  2586. if (ret && !rt_mutex_cleanup_proxy_lock(&q.pi_state->pi_mutex, &rt_waiter))
  2587. ret = 0;
  2588. no_block:
  2589. /*
  2590. * Fixup the pi_state owner and possibly acquire the lock if we
  2591. * haven't already.
  2592. */
  2593. res = fixup_owner(uaddr, &q, !ret);
  2594. /*
  2595. * If fixup_owner() returned an error, proprogate that. If it acquired
  2596. * the lock, clear our -ETIMEDOUT or -EINTR.
  2597. */
  2598. if (res)
  2599. ret = (res < 0) ? res : 0;
  2600. /*
  2601. * If fixup_owner() faulted and was unable to handle the fault, unlock
  2602. * it and return the fault to userspace.
  2603. */
  2604. if (ret && (rt_mutex_owner(&q.pi_state->pi_mutex) == current)) {
  2605. pi_state = q.pi_state;
  2606. get_pi_state(pi_state);
  2607. }
  2608. /* Unqueue and drop the lock */
  2609. unqueue_me_pi(&q);
  2610. if (pi_state) {
  2611. rt_mutex_futex_unlock(&pi_state->pi_mutex);
  2612. put_pi_state(pi_state);
  2613. }
  2614. goto out_put_key;
  2615. out_unlock_put_key:
  2616. queue_unlock(hb);
  2617. out_put_key:
  2618. put_futex_key(&q.key);
  2619. out:
  2620. if (to) {
  2621. hrtimer_cancel(&to->timer);
  2622. destroy_hrtimer_on_stack(&to->timer);
  2623. }
  2624. return ret != -EINTR ? ret : -ERESTARTNOINTR;
  2625. uaddr_faulted:
  2626. queue_unlock(hb);
  2627. ret = fault_in_user_writeable(uaddr);
  2628. if (ret)
  2629. goto out_put_key;
  2630. if (!(flags & FLAGS_SHARED))
  2631. goto retry_private;
  2632. put_futex_key(&q.key);
  2633. goto retry;
  2634. }
  2635. /*
  2636. * Userspace attempted a TID -> 0 atomic transition, and failed.
  2637. * This is the in-kernel slowpath: we look up the PI state (if any),
  2638. * and do the rt-mutex unlock.
  2639. */
  2640. static int futex_unlock_pi(u32 __user *uaddr, unsigned int flags)
  2641. {
  2642. u32 uninitialized_var(curval), uval, vpid = task_pid_vnr(current);
  2643. union futex_key key = FUTEX_KEY_INIT;
  2644. struct futex_hash_bucket *hb;
  2645. struct futex_q *top_waiter;
  2646. int ret;
  2647. if (!IS_ENABLED(CONFIG_FUTEX_PI))
  2648. return -ENOSYS;
  2649. retry:
  2650. if (get_user(uval, uaddr))
  2651. return -EFAULT;
  2652. /*
  2653. * We release only a lock we actually own:
  2654. */
  2655. if ((uval & FUTEX_TID_MASK) != vpid)
  2656. return -EPERM;
  2657. ret = get_futex_key(uaddr, flags & FLAGS_SHARED, &key, VERIFY_WRITE);
  2658. if (ret)
  2659. return ret;
  2660. hb = hash_futex(&key);
  2661. spin_lock(&hb->lock);
  2662. /*
  2663. * Check waiters first. We do not trust user space values at
  2664. * all and we at least want to know if user space fiddled
  2665. * with the futex value instead of blindly unlocking.
  2666. */
  2667. top_waiter = futex_top_waiter(hb, &key);
  2668. if (top_waiter) {
  2669. struct futex_pi_state *pi_state = top_waiter->pi_state;
  2670. ret = -EINVAL;
  2671. if (!pi_state)
  2672. goto out_unlock;
  2673. /*
  2674. * If current does not own the pi_state then the futex is
  2675. * inconsistent and user space fiddled with the futex value.
  2676. */
  2677. if (pi_state->owner != current)
  2678. goto out_unlock;
  2679. get_pi_state(pi_state);
  2680. /*
  2681. * By taking wait_lock while still holding hb->lock, we ensure
  2682. * there is no point where we hold neither; and therefore
  2683. * wake_futex_pi() must observe a state consistent with what we
  2684. * observed.
  2685. *
  2686. * In particular; this forces __rt_mutex_start_proxy() to
  2687. * complete such that we're guaranteed to observe the
  2688. * rt_waiter. Also see the WARN in wake_futex_pi().
  2689. */
  2690. raw_spin_lock_irq(&pi_state->pi_mutex.wait_lock);
  2691. spin_unlock(&hb->lock);
  2692. /* drops pi_state->pi_mutex.wait_lock */
  2693. ret = wake_futex_pi(uaddr, uval, pi_state);
  2694. put_pi_state(pi_state);
  2695. /*
  2696. * Success, we're done! No tricky corner cases.
  2697. */
  2698. if (!ret)
  2699. goto out_putkey;
  2700. /*
  2701. * The atomic access to the futex value generated a
  2702. * pagefault, so retry the user-access and the wakeup:
  2703. */
  2704. if (ret == -EFAULT)
  2705. goto pi_faulted;
  2706. /*
  2707. * A unconditional UNLOCK_PI op raced against a waiter
  2708. * setting the FUTEX_WAITERS bit. Try again.
  2709. */
  2710. if (ret == -EAGAIN)
  2711. goto pi_retry;
  2712. /*
  2713. * wake_futex_pi has detected invalid state. Tell user
  2714. * space.
  2715. */
  2716. goto out_putkey;
  2717. }
  2718. /*
  2719. * We have no kernel internal state, i.e. no waiters in the
  2720. * kernel. Waiters which are about to queue themselves are stuck
  2721. * on hb->lock. So we can safely ignore them. We do neither
  2722. * preserve the WAITERS bit not the OWNER_DIED one. We are the
  2723. * owner.
  2724. */
  2725. if ((ret = cmpxchg_futex_value_locked(&curval, uaddr, uval, 0))) {
  2726. spin_unlock(&hb->lock);
  2727. switch (ret) {
  2728. case -EFAULT:
  2729. goto pi_faulted;
  2730. case -EAGAIN:
  2731. goto pi_retry;
  2732. default:
  2733. WARN_ON_ONCE(1);
  2734. goto out_putkey;
  2735. }
  2736. }
  2737. /*
  2738. * If uval has changed, let user space handle it.
  2739. */
  2740. ret = (curval == uval) ? 0 : -EAGAIN;
  2741. out_unlock:
  2742. spin_unlock(&hb->lock);
  2743. out_putkey:
  2744. put_futex_key(&key);
  2745. return ret;
  2746. pi_retry:
  2747. put_futex_key(&key);
  2748. cond_resched();
  2749. goto retry;
  2750. pi_faulted:
  2751. put_futex_key(&key);
  2752. ret = fault_in_user_writeable(uaddr);
  2753. if (!ret)
  2754. goto retry;
  2755. return ret;
  2756. }
  2757. /**
  2758. * handle_early_requeue_pi_wakeup() - Detect early wakeup on the initial futex
  2759. * @hb: the hash_bucket futex_q was original enqueued on
  2760. * @q: the futex_q woken while waiting to be requeued
  2761. * @key2: the futex_key of the requeue target futex
  2762. * @timeout: the timeout associated with the wait (NULL if none)
  2763. *
  2764. * Detect if the task was woken on the initial futex as opposed to the requeue
  2765. * target futex. If so, determine if it was a timeout or a signal that caused
  2766. * the wakeup and return the appropriate error code to the caller. Must be
  2767. * called with the hb lock held.
  2768. *
  2769. * Return:
  2770. * - 0 = no early wakeup detected;
  2771. * - <0 = -ETIMEDOUT or -ERESTARTNOINTR
  2772. */
  2773. static inline
  2774. int handle_early_requeue_pi_wakeup(struct futex_hash_bucket *hb,
  2775. struct futex_q *q, union futex_key *key2,
  2776. struct hrtimer_sleeper *timeout)
  2777. {
  2778. int ret = 0;
  2779. /*
  2780. * With the hb lock held, we avoid races while we process the wakeup.
  2781. * We only need to hold hb (and not hb2) to ensure atomicity as the
  2782. * wakeup code can't change q.key from uaddr to uaddr2 if we hold hb.
  2783. * It can't be requeued from uaddr2 to something else since we don't
  2784. * support a PI aware source futex for requeue.
  2785. */
  2786. if (!match_futex(&q->key, key2)) {
  2787. WARN_ON(q->lock_ptr && (&hb->lock != q->lock_ptr));
  2788. /*
  2789. * We were woken prior to requeue by a timeout or a signal.
  2790. * Unqueue the futex_q and determine which it was.
  2791. */
  2792. plist_del(&q->list, &hb->chain);
  2793. hb_waiters_dec(hb);
  2794. /* Handle spurious wakeups gracefully */
  2795. ret = -EWOULDBLOCK;
  2796. if (timeout && !timeout->task)
  2797. ret = -ETIMEDOUT;
  2798. else if (signal_pending(current))
  2799. ret = -ERESTARTNOINTR;
  2800. }
  2801. return ret;
  2802. }
  2803. /**
  2804. * futex_wait_requeue_pi() - Wait on uaddr and take uaddr2
  2805. * @uaddr: the futex we initially wait on (non-pi)
  2806. * @flags: futex flags (FLAGS_SHARED, FLAGS_CLOCKRT, etc.), they must be
  2807. * the same type, no requeueing from private to shared, etc.
  2808. * @val: the expected value of uaddr
  2809. * @abs_time: absolute timeout
  2810. * @bitset: 32 bit wakeup bitset set by userspace, defaults to all
  2811. * @uaddr2: the pi futex we will take prior to returning to user-space
  2812. *
  2813. * The caller will wait on uaddr and will be requeued by futex_requeue() to
  2814. * uaddr2 which must be PI aware and unique from uaddr. Normal wakeup will wake
  2815. * on uaddr2 and complete the acquisition of the rt_mutex prior to returning to
  2816. * userspace. This ensures the rt_mutex maintains an owner when it has waiters;
  2817. * without one, the pi logic would not know which task to boost/deboost, if
  2818. * there was a need to.
  2819. *
  2820. * We call schedule in futex_wait_queue_me() when we enqueue and return there
  2821. * via the following--
  2822. * 1) wakeup on uaddr2 after an atomic lock acquisition by futex_requeue()
  2823. * 2) wakeup on uaddr2 after a requeue
  2824. * 3) signal
  2825. * 4) timeout
  2826. *
  2827. * If 3, cleanup and return -ERESTARTNOINTR.
  2828. *
  2829. * If 2, we may then block on trying to take the rt_mutex and return via:
  2830. * 5) successful lock
  2831. * 6) signal
  2832. * 7) timeout
  2833. * 8) other lock acquisition failure
  2834. *
  2835. * If 6, return -EWOULDBLOCK (restarting the syscall would do the same).
  2836. *
  2837. * If 4 or 7, we cleanup and return with -ETIMEDOUT.
  2838. *
  2839. * Return:
  2840. * - 0 - On success;
  2841. * - <0 - On error
  2842. */
  2843. static int futex_wait_requeue_pi(u32 __user *uaddr, unsigned int flags,
  2844. u32 val, ktime_t *abs_time, u32 bitset,
  2845. u32 __user *uaddr2)
  2846. {
  2847. struct hrtimer_sleeper timeout, *to = NULL;
  2848. struct futex_pi_state *pi_state = NULL;
  2849. struct rt_mutex_waiter rt_waiter;
  2850. struct futex_hash_bucket *hb;
  2851. union futex_key key2 = FUTEX_KEY_INIT;
  2852. struct futex_q q = futex_q_init;
  2853. int res, ret;
  2854. if (!IS_ENABLED(CONFIG_FUTEX_PI))
  2855. return -ENOSYS;
  2856. if (uaddr == uaddr2)
  2857. return -EINVAL;
  2858. if (!bitset)
  2859. return -EINVAL;
  2860. if (abs_time) {
  2861. to = &timeout;
  2862. hrtimer_init_on_stack(&to->timer, (flags & FLAGS_CLOCKRT) ?
  2863. CLOCK_REALTIME : CLOCK_MONOTONIC,
  2864. HRTIMER_MODE_ABS);
  2865. hrtimer_init_sleeper(to, current);
  2866. hrtimer_set_expires_range_ns(&to->timer, *abs_time,
  2867. current->timer_slack_ns);
  2868. }
  2869. /*
  2870. * The waiter is allocated on our stack, manipulated by the requeue
  2871. * code while we sleep on uaddr.
  2872. */
  2873. rt_mutex_init_waiter(&rt_waiter);
  2874. ret = get_futex_key(uaddr2, flags & FLAGS_SHARED, &key2, VERIFY_WRITE);
  2875. if (unlikely(ret != 0))
  2876. goto out;
  2877. q.bitset = bitset;
  2878. q.rt_waiter = &rt_waiter;
  2879. q.requeue_pi_key = &key2;
  2880. /*
  2881. * Prepare to wait on uaddr. On success, increments q.key (key1) ref
  2882. * count.
  2883. */
  2884. ret = futex_wait_setup(uaddr, val, flags, &q, &hb);
  2885. if (ret)
  2886. goto out_key2;
  2887. /*
  2888. * The check above which compares uaddrs is not sufficient for
  2889. * shared futexes. We need to compare the keys:
  2890. */
  2891. if (match_futex(&q.key, &key2)) {
  2892. queue_unlock(hb);
  2893. ret = -EINVAL;
  2894. goto out_put_keys;
  2895. }
  2896. /* Queue the futex_q, drop the hb lock, wait for wakeup. */
  2897. futex_wait_queue_me(hb, &q, to);
  2898. spin_lock(&hb->lock);
  2899. ret = handle_early_requeue_pi_wakeup(hb, &q, &key2, to);
  2900. spin_unlock(&hb->lock);
  2901. if (ret)
  2902. goto out_put_keys;
  2903. /*
  2904. * In order for us to be here, we know our q.key == key2, and since
  2905. * we took the hb->lock above, we also know that futex_requeue() has
  2906. * completed and we no longer have to concern ourselves with a wakeup
  2907. * race with the atomic proxy lock acquisition by the requeue code. The
  2908. * futex_requeue dropped our key1 reference and incremented our key2
  2909. * reference count.
  2910. */
  2911. /* Check if the requeue code acquired the second futex for us. */
  2912. if (!q.rt_waiter) {
  2913. /*
  2914. * Got the lock. We might not be the anticipated owner if we
  2915. * did a lock-steal - fix up the PI-state in that case.
  2916. */
  2917. if (q.pi_state && (q.pi_state->owner != current)) {
  2918. spin_lock(q.lock_ptr);
  2919. ret = fixup_pi_state_owner(uaddr2, &q, current);
  2920. if (ret && rt_mutex_owner(&q.pi_state->pi_mutex) == current) {
  2921. pi_state = q.pi_state;
  2922. get_pi_state(pi_state);
  2923. }
  2924. /*
  2925. * Drop the reference to the pi state which
  2926. * the requeue_pi() code acquired for us.
  2927. */
  2928. put_pi_state(q.pi_state);
  2929. spin_unlock(q.lock_ptr);
  2930. }
  2931. } else {
  2932. struct rt_mutex *pi_mutex;
  2933. /*
  2934. * We have been woken up by futex_unlock_pi(), a timeout, or a
  2935. * signal. futex_unlock_pi() will not destroy the lock_ptr nor
  2936. * the pi_state.
  2937. */
  2938. WARN_ON(!q.pi_state);
  2939. pi_mutex = &q.pi_state->pi_mutex;
  2940. ret = rt_mutex_wait_proxy_lock(pi_mutex, to, &rt_waiter);
  2941. spin_lock(q.lock_ptr);
  2942. if (ret && !rt_mutex_cleanup_proxy_lock(pi_mutex, &rt_waiter))
  2943. ret = 0;
  2944. debug_rt_mutex_free_waiter(&rt_waiter);
  2945. /*
  2946. * Fixup the pi_state owner and possibly acquire the lock if we
  2947. * haven't already.
  2948. */
  2949. res = fixup_owner(uaddr2, &q, !ret);
  2950. /*
  2951. * If fixup_owner() returned an error, proprogate that. If it
  2952. * acquired the lock, clear -ETIMEDOUT or -EINTR.
  2953. */
  2954. if (res)
  2955. ret = (res < 0) ? res : 0;
  2956. /*
  2957. * If fixup_pi_state_owner() faulted and was unable to handle
  2958. * the fault, unlock the rt_mutex and return the fault to
  2959. * userspace.
  2960. */
  2961. if (ret && rt_mutex_owner(&q.pi_state->pi_mutex) == current) {
  2962. pi_state = q.pi_state;
  2963. get_pi_state(pi_state);
  2964. }
  2965. /* Unqueue and drop the lock. */
  2966. unqueue_me_pi(&q);
  2967. }
  2968. if (pi_state) {
  2969. rt_mutex_futex_unlock(&pi_state->pi_mutex);
  2970. put_pi_state(pi_state);
  2971. }
  2972. if (ret == -EINTR) {
  2973. /*
  2974. * We've already been requeued, but cannot restart by calling
  2975. * futex_lock_pi() directly. We could restart this syscall, but
  2976. * it would detect that the user space "val" changed and return
  2977. * -EWOULDBLOCK. Save the overhead of the restart and return
  2978. * -EWOULDBLOCK directly.
  2979. */
  2980. ret = -EWOULDBLOCK;
  2981. }
  2982. out_put_keys:
  2983. put_futex_key(&q.key);
  2984. out_key2:
  2985. put_futex_key(&key2);
  2986. out:
  2987. if (to) {
  2988. hrtimer_cancel(&to->timer);
  2989. destroy_hrtimer_on_stack(&to->timer);
  2990. }
  2991. return ret;
  2992. }
  2993. /*
  2994. * Support for robust futexes: the kernel cleans up held futexes at
  2995. * thread exit time.
  2996. *
  2997. * Implementation: user-space maintains a per-thread list of locks it
  2998. * is holding. Upon do_exit(), the kernel carefully walks this list,
  2999. * and marks all locks that are owned by this thread with the
  3000. * FUTEX_OWNER_DIED bit, and wakes up a waiter (if any). The list is
  3001. * always manipulated with the lock held, so the list is private and
  3002. * per-thread. Userspace also maintains a per-thread 'list_op_pending'
  3003. * field, to allow the kernel to clean up if the thread dies after
  3004. * acquiring the lock, but just before it could have added itself to
  3005. * the list. There can only be one such pending lock.
  3006. */
  3007. /**
  3008. * sys_set_robust_list() - Set the robust-futex list head of a task
  3009. * @head: pointer to the list-head
  3010. * @len: length of the list-head, as userspace expects
  3011. */
  3012. SYSCALL_DEFINE2(set_robust_list, struct robust_list_head __user *, head,
  3013. size_t, len)
  3014. {
  3015. if (!futex_cmpxchg_enabled)
  3016. return -ENOSYS;
  3017. /*
  3018. * The kernel knows only one size for now:
  3019. */
  3020. if (unlikely(len != sizeof(*head)))
  3021. return -EINVAL;
  3022. current->robust_list = head;
  3023. return 0;
  3024. }
  3025. /**
  3026. * sys_get_robust_list() - Get the robust-futex list head of a task
  3027. * @pid: pid of the process [zero for current task]
  3028. * @head_ptr: pointer to a list-head pointer, the kernel fills it in
  3029. * @len_ptr: pointer to a length field, the kernel fills in the header size
  3030. */
  3031. SYSCALL_DEFINE3(get_robust_list, int, pid,
  3032. struct robust_list_head __user * __user *, head_ptr,
  3033. size_t __user *, len_ptr)
  3034. {
  3035. struct robust_list_head __user *head;
  3036. unsigned long ret;
  3037. struct task_struct *p;
  3038. if (!futex_cmpxchg_enabled)
  3039. return -ENOSYS;
  3040. rcu_read_lock();
  3041. ret = -ESRCH;
  3042. if (!pid)
  3043. p = current;
  3044. else {
  3045. p = find_task_by_vpid(pid);
  3046. if (!p)
  3047. goto err_unlock;
  3048. }
  3049. ret = -EPERM;
  3050. if (!ptrace_may_access(p, PTRACE_MODE_READ_REALCREDS))
  3051. goto err_unlock;
  3052. head = p->robust_list;
  3053. rcu_read_unlock();
  3054. if (put_user(sizeof(*head), len_ptr))
  3055. return -EFAULT;
  3056. return put_user(head, head_ptr);
  3057. err_unlock:
  3058. rcu_read_unlock();
  3059. return ret;
  3060. }
  3061. /* Constants for the pending_op argument of handle_futex_death */
  3062. #define HANDLE_DEATH_PENDING true
  3063. #define HANDLE_DEATH_LIST false
  3064. /*
  3065. * Process a futex-list entry, check whether it's owned by the
  3066. * dying task, and do notification if so:
  3067. */
  3068. static int handle_futex_death(u32 __user *uaddr, struct task_struct *curr,
  3069. bool pi, bool pending_op)
  3070. {
  3071. u32 uval, uninitialized_var(nval), mval;
  3072. int err;
  3073. /* Futex address must be 32bit aligned */
  3074. if ((((unsigned long)uaddr) % sizeof(*uaddr)) != 0)
  3075. return -1;
  3076. retry:
  3077. if (get_user(uval, uaddr))
  3078. return -1;
  3079. /*
  3080. * Special case for regular (non PI) futexes. The unlock path in
  3081. * user space has two race scenarios:
  3082. *
  3083. * 1. The unlock path releases the user space futex value and
  3084. * before it can execute the futex() syscall to wake up
  3085. * waiters it is killed.
  3086. *
  3087. * 2. A woken up waiter is killed before it can acquire the
  3088. * futex in user space.
  3089. *
  3090. * In both cases the TID validation below prevents a wakeup of
  3091. * potential waiters which can cause these waiters to block
  3092. * forever.
  3093. *
  3094. * In both cases the following conditions are met:
  3095. *
  3096. * 1) task->robust_list->list_op_pending != NULL
  3097. * @pending_op == true
  3098. * 2) User space futex value == 0
  3099. * 3) Regular futex: @pi == false
  3100. *
  3101. * If these conditions are met, it is safe to attempt waking up a
  3102. * potential waiter without touching the user space futex value and
  3103. * trying to set the OWNER_DIED bit. The user space futex value is
  3104. * uncontended and the rest of the user space mutex state is
  3105. * consistent, so a woken waiter will just take over the
  3106. * uncontended futex. Setting the OWNER_DIED bit would create
  3107. * inconsistent state and malfunction of the user space owner died
  3108. * handling.
  3109. */
  3110. if (pending_op && !pi && !uval) {
  3111. futex_wake(uaddr, 1, 1, FUTEX_BITSET_MATCH_ANY);
  3112. return 0;
  3113. }
  3114. if ((uval & FUTEX_TID_MASK) != task_pid_vnr(curr))
  3115. return 0;
  3116. /*
  3117. * Ok, this dying thread is truly holding a futex
  3118. * of interest. Set the OWNER_DIED bit atomically
  3119. * via cmpxchg, and if the value had FUTEX_WAITERS
  3120. * set, wake up a waiter (if any). (We have to do a
  3121. * futex_wake() even if OWNER_DIED is already set -
  3122. * to handle the rare but possible case of recursive
  3123. * thread-death.) The rest of the cleanup is done in
  3124. * userspace.
  3125. */
  3126. mval = (uval & FUTEX_WAITERS) | FUTEX_OWNER_DIED;
  3127. /*
  3128. * We are not holding a lock here, but we want to have
  3129. * the pagefault_disable/enable() protection because
  3130. * we want to handle the fault gracefully. If the
  3131. * access fails we try to fault in the futex with R/W
  3132. * verification via get_user_pages. get_user() above
  3133. * does not guarantee R/W access. If that fails we
  3134. * give up and leave the futex locked.
  3135. */
  3136. if ((err = cmpxchg_futex_value_locked(&nval, uaddr, uval, mval))) {
  3137. switch (err) {
  3138. case -EFAULT:
  3139. if (fault_in_user_writeable(uaddr))
  3140. return -1;
  3141. goto retry;
  3142. case -EAGAIN:
  3143. cond_resched();
  3144. goto retry;
  3145. default:
  3146. WARN_ON_ONCE(1);
  3147. return err;
  3148. }
  3149. }
  3150. if (nval != uval)
  3151. goto retry;
  3152. /*
  3153. * Wake robust non-PI futexes here. The wakeup of
  3154. * PI futexes happens in exit_pi_state():
  3155. */
  3156. if (!pi && (uval & FUTEX_WAITERS))
  3157. futex_wake(uaddr, 1, 1, FUTEX_BITSET_MATCH_ANY);
  3158. return 0;
  3159. }
  3160. /*
  3161. * Fetch a robust-list pointer. Bit 0 signals PI futexes:
  3162. */
  3163. static inline int fetch_robust_entry(struct robust_list __user **entry,
  3164. struct robust_list __user * __user *head,
  3165. unsigned int *pi)
  3166. {
  3167. unsigned long uentry;
  3168. if (get_user(uentry, (unsigned long __user *)head))
  3169. return -EFAULT;
  3170. *entry = (void __user *)(uentry & ~1UL);
  3171. *pi = uentry & 1;
  3172. return 0;
  3173. }
  3174. /*
  3175. * Walk curr->robust_list (very carefully, it's a userspace list!)
  3176. * and mark any locks found there dead, and notify any waiters.
  3177. *
  3178. * We silently return on any sign of list-walking problem.
  3179. */
  3180. void exit_robust_list(struct task_struct *curr)
  3181. {
  3182. struct robust_list_head __user *head = curr->robust_list;
  3183. struct robust_list __user *entry, *next_entry, *pending;
  3184. unsigned int limit = ROBUST_LIST_LIMIT, pi, pip;
  3185. unsigned int uninitialized_var(next_pi);
  3186. unsigned long futex_offset;
  3187. int rc;
  3188. if (!futex_cmpxchg_enabled)
  3189. return;
  3190. /*
  3191. * Fetch the list head (which was registered earlier, via
  3192. * sys_set_robust_list()):
  3193. */
  3194. if (fetch_robust_entry(&entry, &head->list.next, &pi))
  3195. return;
  3196. /*
  3197. * Fetch the relative futex offset:
  3198. */
  3199. if (get_user(futex_offset, &head->futex_offset))
  3200. return;
  3201. /*
  3202. * Fetch any possibly pending lock-add first, and handle it
  3203. * if it exists:
  3204. */
  3205. if (fetch_robust_entry(&pending, &head->list_op_pending, &pip))
  3206. return;
  3207. next_entry = NULL; /* avoid warning with gcc */
  3208. while (entry != &head->list) {
  3209. /*
  3210. * Fetch the next entry in the list before calling
  3211. * handle_futex_death:
  3212. */
  3213. rc = fetch_robust_entry(&next_entry, &entry->next, &next_pi);
  3214. /*
  3215. * A pending lock might already be on the list, so
  3216. * don't process it twice:
  3217. */
  3218. if (entry != pending) {
  3219. if (handle_futex_death((void __user *)entry + futex_offset,
  3220. curr, pi, HANDLE_DEATH_LIST))
  3221. return;
  3222. }
  3223. if (rc)
  3224. return;
  3225. entry = next_entry;
  3226. pi = next_pi;
  3227. /*
  3228. * Avoid excessively long or circular lists:
  3229. */
  3230. if (!--limit)
  3231. break;
  3232. cond_resched();
  3233. }
  3234. if (pending) {
  3235. handle_futex_death((void __user *)pending + futex_offset,
  3236. curr, pip, HANDLE_DEATH_PENDING);
  3237. }
  3238. }
  3239. long do_futex(u32 __user *uaddr, int op, u32 val, ktime_t *timeout,
  3240. u32 __user *uaddr2, u32 val2, u32 val3)
  3241. {
  3242. int cmd = op & FUTEX_CMD_MASK;
  3243. unsigned int flags = 0;
  3244. if (!(op & FUTEX_PRIVATE_FLAG))
  3245. flags |= FLAGS_SHARED;
  3246. if (op & FUTEX_CLOCK_REALTIME) {
  3247. flags |= FLAGS_CLOCKRT;
  3248. if (cmd != FUTEX_WAIT && cmd != FUTEX_WAIT_BITSET && \
  3249. cmd != FUTEX_WAIT_REQUEUE_PI)
  3250. return -ENOSYS;
  3251. }
  3252. switch (cmd) {
  3253. case FUTEX_LOCK_PI:
  3254. case FUTEX_UNLOCK_PI:
  3255. case FUTEX_TRYLOCK_PI:
  3256. case FUTEX_WAIT_REQUEUE_PI:
  3257. case FUTEX_CMP_REQUEUE_PI:
  3258. if (!futex_cmpxchg_enabled)
  3259. return -ENOSYS;
  3260. }
  3261. switch (cmd) {
  3262. case FUTEX_WAIT:
  3263. val3 = FUTEX_BITSET_MATCH_ANY;
  3264. /* fall through */
  3265. case FUTEX_WAIT_BITSET:
  3266. return futex_wait(uaddr, flags, val, timeout, val3);
  3267. case FUTEX_WAKE:
  3268. val3 = FUTEX_BITSET_MATCH_ANY;
  3269. /* fall through */
  3270. case FUTEX_WAKE_BITSET:
  3271. return futex_wake(uaddr, flags, val, val3);
  3272. case FUTEX_REQUEUE:
  3273. return futex_requeue(uaddr, flags, uaddr2, val, val2, NULL, 0);
  3274. case FUTEX_CMP_REQUEUE:
  3275. return futex_requeue(uaddr, flags, uaddr2, val, val2, &val3, 0);
  3276. case FUTEX_WAKE_OP:
  3277. return futex_wake_op(uaddr, flags, uaddr2, val, val2, val3);
  3278. case FUTEX_LOCK_PI:
  3279. return futex_lock_pi(uaddr, flags, timeout, 0);
  3280. case FUTEX_UNLOCK_PI:
  3281. return futex_unlock_pi(uaddr, flags);
  3282. case FUTEX_TRYLOCK_PI:
  3283. return futex_lock_pi(uaddr, flags, NULL, 1);
  3284. case FUTEX_WAIT_REQUEUE_PI:
  3285. val3 = FUTEX_BITSET_MATCH_ANY;
  3286. return futex_wait_requeue_pi(uaddr, flags, val, timeout, val3,
  3287. uaddr2);
  3288. case FUTEX_CMP_REQUEUE_PI:
  3289. return futex_requeue(uaddr, flags, uaddr2, val, val2, &val3, 1);
  3290. }
  3291. return -ENOSYS;
  3292. }
  3293. SYSCALL_DEFINE6(futex, u32 __user *, uaddr, int, op, u32, val,
  3294. struct timespec __user *, utime, u32 __user *, uaddr2,
  3295. u32, val3)
  3296. {
  3297. struct timespec ts;
  3298. ktime_t t, *tp = NULL;
  3299. u32 val2 = 0;
  3300. int cmd = op & FUTEX_CMD_MASK;
  3301. if (utime && (cmd == FUTEX_WAIT || cmd == FUTEX_LOCK_PI ||
  3302. cmd == FUTEX_WAIT_BITSET ||
  3303. cmd == FUTEX_WAIT_REQUEUE_PI)) {
  3304. if (unlikely(should_fail_futex(!(op & FUTEX_PRIVATE_FLAG))))
  3305. return -EFAULT;
  3306. if (copy_from_user(&ts, utime, sizeof(ts)) != 0)
  3307. return -EFAULT;
  3308. if (!timespec_valid(&ts))
  3309. return -EINVAL;
  3310. t = timespec_to_ktime(ts);
  3311. if (cmd == FUTEX_WAIT)
  3312. t = ktime_add_safe(ktime_get(), t);
  3313. tp = &t;
  3314. }
  3315. /*
  3316. * requeue parameter in 'utime' if cmd == FUTEX_*_REQUEUE_*.
  3317. * number of waiters to wake in 'utime' if cmd == FUTEX_WAKE_OP.
  3318. */
  3319. if (cmd == FUTEX_REQUEUE || cmd == FUTEX_CMP_REQUEUE ||
  3320. cmd == FUTEX_CMP_REQUEUE_PI || cmd == FUTEX_WAKE_OP)
  3321. val2 = (u32) (unsigned long) utime;
  3322. return do_futex(uaddr, op, val, tp, uaddr2, val2, val3);
  3323. }
  3324. #ifdef CONFIG_COMPAT
  3325. /*
  3326. * Fetch a robust-list pointer. Bit 0 signals PI futexes:
  3327. */
  3328. static inline int
  3329. compat_fetch_robust_entry(compat_uptr_t *uentry, struct robust_list __user **entry,
  3330. compat_uptr_t __user *head, unsigned int *pi)
  3331. {
  3332. if (get_user(*uentry, head))
  3333. return -EFAULT;
  3334. *entry = compat_ptr((*uentry) & ~1);
  3335. *pi = (unsigned int)(*uentry) & 1;
  3336. return 0;
  3337. }
  3338. static void __user *futex_uaddr(struct robust_list __user *entry,
  3339. compat_long_t futex_offset)
  3340. {
  3341. compat_uptr_t base = ptr_to_compat(entry);
  3342. void __user *uaddr = compat_ptr(base + futex_offset);
  3343. return uaddr;
  3344. }
  3345. /*
  3346. * Walk curr->robust_list (very carefully, it's a userspace list!)
  3347. * and mark any locks found there dead, and notify any waiters.
  3348. *
  3349. * We silently return on any sign of list-walking problem.
  3350. */
  3351. void compat_exit_robust_list(struct task_struct *curr)
  3352. {
  3353. struct compat_robust_list_head __user *head = curr->compat_robust_list;
  3354. struct robust_list __user *entry, *next_entry, *pending;
  3355. unsigned int limit = ROBUST_LIST_LIMIT, pi, pip;
  3356. unsigned int uninitialized_var(next_pi);
  3357. compat_uptr_t uentry, next_uentry, upending;
  3358. compat_long_t futex_offset;
  3359. int rc;
  3360. if (!futex_cmpxchg_enabled)
  3361. return;
  3362. /*
  3363. * Fetch the list head (which was registered earlier, via
  3364. * sys_set_robust_list()):
  3365. */
  3366. if (compat_fetch_robust_entry(&uentry, &entry, &head->list.next, &pi))
  3367. return;
  3368. /*
  3369. * Fetch the relative futex offset:
  3370. */
  3371. if (get_user(futex_offset, &head->futex_offset))
  3372. return;
  3373. /*
  3374. * Fetch any possibly pending lock-add first, and handle it
  3375. * if it exists:
  3376. */
  3377. if (compat_fetch_robust_entry(&upending, &pending,
  3378. &head->list_op_pending, &pip))
  3379. return;
  3380. next_entry = NULL; /* avoid warning with gcc */
  3381. while (entry != (struct robust_list __user *) &head->list) {
  3382. /*
  3383. * Fetch the next entry in the list before calling
  3384. * handle_futex_death:
  3385. */
  3386. rc = compat_fetch_robust_entry(&next_uentry, &next_entry,
  3387. (compat_uptr_t __user *)&entry->next, &next_pi);
  3388. /*
  3389. * A pending lock might already be on the list, so
  3390. * dont process it twice:
  3391. */
  3392. if (entry != pending) {
  3393. void __user *uaddr = futex_uaddr(entry, futex_offset);
  3394. if (handle_futex_death(uaddr, curr, pi,
  3395. HANDLE_DEATH_LIST))
  3396. return;
  3397. }
  3398. if (rc)
  3399. return;
  3400. uentry = next_uentry;
  3401. entry = next_entry;
  3402. pi = next_pi;
  3403. /*
  3404. * Avoid excessively long or circular lists:
  3405. */
  3406. if (!--limit)
  3407. break;
  3408. cond_resched();
  3409. }
  3410. if (pending) {
  3411. void __user *uaddr = futex_uaddr(pending, futex_offset);
  3412. handle_futex_death(uaddr, curr, pip, HANDLE_DEATH_PENDING);
  3413. }
  3414. }
  3415. COMPAT_SYSCALL_DEFINE2(set_robust_list,
  3416. struct compat_robust_list_head __user *, head,
  3417. compat_size_t, len)
  3418. {
  3419. if (!futex_cmpxchg_enabled)
  3420. return -ENOSYS;
  3421. if (unlikely(len != sizeof(*head)))
  3422. return -EINVAL;
  3423. current->compat_robust_list = head;
  3424. return 0;
  3425. }
  3426. COMPAT_SYSCALL_DEFINE3(get_robust_list, int, pid,
  3427. compat_uptr_t __user *, head_ptr,
  3428. compat_size_t __user *, len_ptr)
  3429. {
  3430. struct compat_robust_list_head __user *head;
  3431. unsigned long ret;
  3432. struct task_struct *p;
  3433. if (!futex_cmpxchg_enabled)
  3434. return -ENOSYS;
  3435. rcu_read_lock();
  3436. ret = -ESRCH;
  3437. if (!pid)
  3438. p = current;
  3439. else {
  3440. p = find_task_by_vpid(pid);
  3441. if (!p)
  3442. goto err_unlock;
  3443. }
  3444. ret = -EPERM;
  3445. if (!ptrace_may_access(p, PTRACE_MODE_READ_REALCREDS))
  3446. goto err_unlock;
  3447. head = p->compat_robust_list;
  3448. rcu_read_unlock();
  3449. if (put_user(sizeof(*head), len_ptr))
  3450. return -EFAULT;
  3451. return put_user(ptr_to_compat(head), head_ptr);
  3452. err_unlock:
  3453. rcu_read_unlock();
  3454. return ret;
  3455. }
  3456. COMPAT_SYSCALL_DEFINE6(futex, u32 __user *, uaddr, int, op, u32, val,
  3457. struct old_timespec32 __user *, utime, u32 __user *, uaddr2,
  3458. u32, val3)
  3459. {
  3460. struct timespec ts;
  3461. ktime_t t, *tp = NULL;
  3462. int val2 = 0;
  3463. int cmd = op & FUTEX_CMD_MASK;
  3464. if (utime && (cmd == FUTEX_WAIT || cmd == FUTEX_LOCK_PI ||
  3465. cmd == FUTEX_WAIT_BITSET ||
  3466. cmd == FUTEX_WAIT_REQUEUE_PI)) {
  3467. if (compat_get_timespec(&ts, utime))
  3468. return -EFAULT;
  3469. if (!timespec_valid(&ts))
  3470. return -EINVAL;
  3471. t = timespec_to_ktime(ts);
  3472. if (cmd == FUTEX_WAIT)
  3473. t = ktime_add_safe(ktime_get(), t);
  3474. tp = &t;
  3475. }
  3476. if (cmd == FUTEX_REQUEUE || cmd == FUTEX_CMP_REQUEUE ||
  3477. cmd == FUTEX_CMP_REQUEUE_PI || cmd == FUTEX_WAKE_OP)
  3478. val2 = (int) (unsigned long) utime;
  3479. return do_futex(uaddr, op, val, tp, uaddr2, val2, val3);
  3480. }
  3481. #endif /* CONFIG_COMPAT */
  3482. static void __init futex_detect_cmpxchg(void)
  3483. {
  3484. #ifndef CONFIG_HAVE_FUTEX_CMPXCHG
  3485. u32 curval;
  3486. /*
  3487. * This will fail and we want it. Some arch implementations do
  3488. * runtime detection of the futex_atomic_cmpxchg_inatomic()
  3489. * functionality. We want to know that before we call in any
  3490. * of the complex code paths. Also we want to prevent
  3491. * registration of robust lists in that case. NULL is
  3492. * guaranteed to fault and we get -EFAULT on functional
  3493. * implementation, the non-functional ones will return
  3494. * -ENOSYS.
  3495. */
  3496. if (cmpxchg_futex_value_locked(&curval, NULL, 0, 0) == -EFAULT)
  3497. futex_cmpxchg_enabled = 1;
  3498. #endif
  3499. }
  3500. static int __init futex_init(void)
  3501. {
  3502. unsigned int futex_shift;
  3503. unsigned long i;
  3504. #if CONFIG_BASE_SMALL
  3505. futex_hashsize = 16;
  3506. #else
  3507. futex_hashsize = roundup_pow_of_two(256 * num_possible_cpus());
  3508. #endif
  3509. futex_queues = alloc_large_system_hash("futex", sizeof(*futex_queues),
  3510. futex_hashsize, 0,
  3511. futex_hashsize < 256 ? HASH_SMALL : 0,
  3512. &futex_shift, NULL,
  3513. futex_hashsize, futex_hashsize);
  3514. futex_hashsize = 1UL << futex_shift;
  3515. futex_detect_cmpxchg();
  3516. for (i = 0; i < futex_hashsize; i++) {
  3517. atomic_set(&futex_queues[i].waiters, 0);
  3518. plist_head_init(&futex_queues[i].chain);
  3519. spin_lock_init(&futex_queues[i].lock);
  3520. }
  3521. return 0;
  3522. }
  3523. core_initcall(futex_init);