futex.c 110 KB

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