gup.c 101 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555255625572558255925602561256225632564256525662567256825692570257125722573257425752576257725782579258025812582258325842585258625872588258925902591259225932594259525962597259825992600260126022603260426052606260726082609261026112612261326142615261626172618261926202621262226232624262526262627262826292630263126322633263426352636263726382639264026412642264326442645264626472648264926502651265226532654265526562657265826592660266126622663266426652666266726682669267026712672267326742675267626772678267926802681268226832684268526862687268826892690269126922693269426952696269726982699270027012702270327042705270627072708270927102711271227132714271527162717271827192720272127222723272427252726272727282729273027312732273327342735273627372738273927402741274227432744274527462747274827492750275127522753275427552756275727582759276027612762276327642765276627672768276927702771277227732774277527762777277827792780278127822783278427852786278727882789279027912792279327942795279627972798279928002801280228032804280528062807280828092810281128122813281428152816281728182819282028212822282328242825282628272828282928302831283228332834283528362837283828392840284128422843284428452846284728482849285028512852285328542855285628572858285928602861286228632864286528662867286828692870287128722873287428752876287728782879288028812882288328842885288628872888288928902891289228932894289528962897289828992900290129022903290429052906290729082909291029112912291329142915291629172918291929202921292229232924292529262927292829292930293129322933293429352936293729382939294029412942294329442945294629472948294929502951295229532954295529562957295829592960296129622963296429652966296729682969297029712972297329742975297629772978297929802981298229832984298529862987298829892990299129922993299429952996299729982999300030013002300330043005300630073008300930103011301230133014301530163017301830193020302130223023302430253026302730283029303030313032303330343035303630373038303930403041304230433044304530463047304830493050305130523053305430553056305730583059306030613062306330643065306630673068306930703071307230733074307530763077307830793080308130823083308430853086308730883089309030913092309330943095309630973098309931003101310231033104310531063107310831093110311131123113311431153116311731183119312031213122312331243125312631273128312931303131313231333134313531363137313831393140314131423143314431453146314731483149315031513152315331543155315631573158315931603161316231633164316531663167316831693170317131723173317431753176317731783179318031813182318331843185318631873188318931903191319231933194319531963197319831993200320132023203320432053206320732083209321032113212321332143215321632173218321932203221322232233224322532263227322832293230323132323233323432353236323732383239324032413242324332443245324632473248324932503251325232533254325532563257325832593260326132623263326432653266326732683269327032713272327332743275327632773278327932803281328232833284328532863287328832893290329132923293329432953296329732983299330033013302330333043305330633073308330933103311331233133314331533163317331833193320332133223323332433253326332733283329333033313332333333343335333633373338333933403341334233433344334533463347334833493350335133523353335433553356335733583359336033613362336333643365336633673368336933703371337233733374337533763377337833793380338133823383338433853386338733883389339033913392339333943395339633973398339934003401340234033404340534063407340834093410341134123413341434153416341734183419342034213422342334243425342634273428342934303431343234333434343534363437343834393440344134423443344434453446344734483449345034513452345334543455345634573458345934603461346234633464346534663467346834693470347134723473347434753476347734783479348034813482348334843485348634873488348934903491349234933494349534963497349834993500350135023503350435053506350735083509351035113512351335143515351635173518351935203521352235233524352535263527352835293530353135323533353435353536353735383539354035413542354335443545354635473548354935503551355235533554355535563557
  1. // SPDX-License-Identifier: GPL-2.0-only
  2. #include <linux/kernel.h>
  3. #include <linux/errno.h>
  4. #include <linux/err.h>
  5. #include <linux/spinlock.h>
  6. #include <linux/mm.h>
  7. #include <linux/memfd.h>
  8. #include <linux/memremap.h>
  9. #include <linux/pagemap.h>
  10. #include <linux/rmap.h>
  11. #include <linux/swap.h>
  12. #include <linux/swapops.h>
  13. #include <linux/secretmem.h>
  14. #include <linux/sched/signal.h>
  15. #include <linux/rwsem.h>
  16. #include <linux/hugetlb.h>
  17. #include <linux/migrate.h>
  18. #include <linux/mm_inline.h>
  19. #include <linux/pagevec.h>
  20. #include <linux/sched/mm.h>
  21. #include <linux/shmem_fs.h>
  22. #include <asm/mmu_context.h>
  23. #include <asm/tlbflush.h>
  24. #include "internal.h"
  25. #include "swap.h"
  26. static inline void sanity_check_pinned_pages(struct page **pages,
  27. unsigned long npages)
  28. {
  29. if (!IS_ENABLED(CONFIG_DEBUG_VM))
  30. return;
  31. /*
  32. * We only pin anonymous pages if they are exclusive. Once pinned, we
  33. * can no longer turn them possibly shared and PageAnonExclusive() will
  34. * stick around until the page is freed.
  35. *
  36. * We'd like to verify that our pinned anonymous pages are still mapped
  37. * exclusively. The issue with anon THP is that we don't know how
  38. * they are/were mapped when pinning them. However, for anon
  39. * THP we can assume that either the given page (PTE-mapped THP) or
  40. * the head page (PMD-mapped THP) should be PageAnonExclusive(). If
  41. * neither is the case, there is certainly something wrong.
  42. */
  43. for (; npages; npages--, pages++) {
  44. struct page *page = *pages;
  45. struct folio *folio;
  46. if (!page)
  47. continue;
  48. folio = page_folio(page);
  49. if (is_zero_page(page) ||
  50. !folio_test_anon(folio))
  51. continue;
  52. if (!folio_test_large(folio) || folio_test_hugetlb(folio))
  53. VM_WARN_ON_ONCE_FOLIO(!PageAnonExclusive(&folio->page), folio);
  54. else
  55. /* Either a PTE-mapped or a PMD-mapped THP. */
  56. VM_WARN_ON_ONCE_PAGE(!PageAnonExclusive(&folio->page) &&
  57. !PageAnonExclusive(page), page);
  58. }
  59. }
  60. /*
  61. * Return the folio with ref appropriately incremented,
  62. * or NULL if that failed.
  63. */
  64. static inline struct folio *try_get_folio(struct page *page, int refs)
  65. {
  66. struct folio *folio;
  67. retry:
  68. folio = page_folio(page);
  69. if (WARN_ON_ONCE(folio_ref_count(folio) < 0))
  70. return NULL;
  71. if (unlikely(!folio_ref_try_add(folio, refs)))
  72. return NULL;
  73. /*
  74. * At this point we have a stable reference to the folio; but it
  75. * could be that between calling page_folio() and the refcount
  76. * increment, the folio was split, in which case we'd end up
  77. * holding a reference on a folio that has nothing to do with the page
  78. * we were given anymore.
  79. * So now that the folio is stable, recheck that the page still
  80. * belongs to this folio.
  81. */
  82. if (unlikely(page_folio(page) != folio)) {
  83. folio_put_refs(folio, refs);
  84. goto retry;
  85. }
  86. return folio;
  87. }
  88. static void gup_put_folio(struct folio *folio, int refs, unsigned int flags)
  89. {
  90. if (flags & FOLL_PIN) {
  91. if (is_zero_folio(folio))
  92. return;
  93. node_stat_mod_folio(folio, NR_FOLL_PIN_RELEASED, refs);
  94. if (folio_has_pincount(folio))
  95. atomic_sub(refs, &folio->_pincount);
  96. else
  97. refs *= GUP_PIN_COUNTING_BIAS;
  98. }
  99. folio_put_refs(folio, refs);
  100. }
  101. /**
  102. * try_grab_folio() - add a folio's refcount by a flag-dependent amount
  103. * @folio: pointer to folio to be grabbed
  104. * @refs: the value to (effectively) add to the folio's refcount
  105. * @flags: gup flags: these are the FOLL_* flag values
  106. *
  107. * This might not do anything at all, depending on the flags argument.
  108. *
  109. * "grab" names in this file mean, "look at flags to decide whether to use
  110. * FOLL_PIN or FOLL_GET behavior, when incrementing the folio's refcount.
  111. *
  112. * Either FOLL_PIN or FOLL_GET (or neither) may be set, but not both at the same
  113. * time.
  114. *
  115. * Return: 0 for success, or if no action was required (if neither FOLL_PIN
  116. * nor FOLL_GET was set, nothing is done). A negative error code for failure:
  117. *
  118. * -ENOMEM FOLL_GET or FOLL_PIN was set, but the folio could not
  119. * be grabbed.
  120. *
  121. * It is called when we have a stable reference for the folio, typically in
  122. * GUP slow path.
  123. */
  124. int __must_check try_grab_folio(struct folio *folio, int refs,
  125. unsigned int flags)
  126. {
  127. if (WARN_ON_ONCE(folio_ref_count(folio) <= 0))
  128. return -ENOMEM;
  129. if (unlikely(!(flags & FOLL_PCI_P2PDMA) && folio_is_pci_p2pdma(folio)))
  130. return -EREMOTEIO;
  131. if (flags & FOLL_GET)
  132. folio_ref_add(folio, refs);
  133. else if (flags & FOLL_PIN) {
  134. /*
  135. * Don't take a pin on the zero page - it's not going anywhere
  136. * and it is used in a *lot* of places.
  137. */
  138. if (is_zero_folio(folio))
  139. return 0;
  140. /*
  141. * Increment the normal page refcount field at least once,
  142. * so that the page really is pinned.
  143. */
  144. if (folio_has_pincount(folio)) {
  145. folio_ref_add(folio, refs);
  146. atomic_add(refs, &folio->_pincount);
  147. } else {
  148. folio_ref_add(folio, refs * GUP_PIN_COUNTING_BIAS);
  149. }
  150. node_stat_mod_folio(folio, NR_FOLL_PIN_ACQUIRED, refs);
  151. }
  152. return 0;
  153. }
  154. /**
  155. * unpin_user_page() - release a dma-pinned page
  156. * @page: pointer to page to be released
  157. *
  158. * Pages that were pinned via pin_user_pages*() must be released via either
  159. * unpin_user_page(), or one of the unpin_user_pages*() routines. This is so
  160. * that such pages can be separately tracked and uniquely handled. In
  161. * particular, interactions with RDMA and filesystems need special handling.
  162. */
  163. void unpin_user_page(struct page *page)
  164. {
  165. sanity_check_pinned_pages(&page, 1);
  166. gup_put_folio(page_folio(page), 1, FOLL_PIN);
  167. }
  168. EXPORT_SYMBOL(unpin_user_page);
  169. /**
  170. * unpin_folio() - release a dma-pinned folio
  171. * @folio: pointer to folio to be released
  172. *
  173. * Folios that were pinned via memfd_pin_folios() or other similar routines
  174. * must be released either using unpin_folio() or unpin_folios().
  175. */
  176. void unpin_folio(struct folio *folio)
  177. {
  178. gup_put_folio(folio, 1, FOLL_PIN);
  179. }
  180. EXPORT_SYMBOL_GPL(unpin_folio);
  181. /**
  182. * folio_add_pin - Try to get an additional pin on a pinned folio
  183. * @folio: The folio to be pinned
  184. *
  185. * Get an additional pin on a folio we already have a pin on. Makes no change
  186. * if the folio is a zero_page.
  187. */
  188. void folio_add_pin(struct folio *folio)
  189. {
  190. if (is_zero_folio(folio))
  191. return;
  192. /*
  193. * Similar to try_grab_folio(): be sure to *also* increment the normal
  194. * page refcount field at least once, so that the page really is
  195. * pinned.
  196. */
  197. if (folio_has_pincount(folio)) {
  198. WARN_ON_ONCE(atomic_read(&folio->_pincount) < 1);
  199. folio_ref_inc(folio);
  200. atomic_inc(&folio->_pincount);
  201. } else {
  202. WARN_ON_ONCE(folio_ref_count(folio) < GUP_PIN_COUNTING_BIAS);
  203. folio_ref_add(folio, GUP_PIN_COUNTING_BIAS);
  204. }
  205. }
  206. static inline struct folio *gup_folio_range_next(struct page *start,
  207. unsigned long npages, unsigned long i, unsigned int *ntails)
  208. {
  209. struct page *next = start + i;
  210. struct folio *folio = page_folio(next);
  211. unsigned int nr = 1;
  212. if (folio_test_large(folio))
  213. nr = min_t(unsigned int, npages - i,
  214. folio_nr_pages(folio) - folio_page_idx(folio, next));
  215. *ntails = nr;
  216. return folio;
  217. }
  218. static inline struct folio *gup_folio_next(struct page **list,
  219. unsigned long npages, unsigned long i, unsigned int *ntails)
  220. {
  221. struct folio *folio = page_folio(list[i]);
  222. unsigned int nr;
  223. for (nr = i + 1; nr < npages; nr++) {
  224. if (page_folio(list[nr]) != folio)
  225. break;
  226. }
  227. *ntails = nr - i;
  228. return folio;
  229. }
  230. /**
  231. * unpin_user_pages_dirty_lock() - release and optionally dirty gup-pinned pages
  232. * @pages: array of pages to be maybe marked dirty, and definitely released.
  233. * @npages: number of pages in the @pages array.
  234. * @make_dirty: whether to mark the pages dirty
  235. *
  236. * "gup-pinned page" refers to a page that has had one of the get_user_pages()
  237. * variants called on that page.
  238. *
  239. * For each page in the @pages array, make that page (or its head page, if a
  240. * compound page) dirty, if @make_dirty is true, and if the page was previously
  241. * listed as clean. In any case, releases all pages using unpin_user_page(),
  242. * possibly via unpin_user_pages(), for the non-dirty case.
  243. *
  244. * Please see the unpin_user_page() documentation for details.
  245. *
  246. * set_page_dirty_lock() is used internally. If instead, set_page_dirty() is
  247. * required, then the caller should a) verify that this is really correct,
  248. * because _lock() is usually required, and b) hand code it:
  249. * set_page_dirty_lock(), unpin_user_page().
  250. *
  251. */
  252. void unpin_user_pages_dirty_lock(struct page **pages, unsigned long npages,
  253. bool make_dirty)
  254. {
  255. unsigned long i;
  256. struct folio *folio;
  257. unsigned int nr;
  258. if (!make_dirty) {
  259. unpin_user_pages(pages, npages);
  260. return;
  261. }
  262. sanity_check_pinned_pages(pages, npages);
  263. for (i = 0; i < npages; i += nr) {
  264. folio = gup_folio_next(pages, npages, i, &nr);
  265. /*
  266. * Checking PageDirty at this point may race with
  267. * clear_page_dirty_for_io(), but that's OK. Two key
  268. * cases:
  269. *
  270. * 1) This code sees the page as already dirty, so it
  271. * skips the call to set_page_dirty(). That could happen
  272. * because clear_page_dirty_for_io() called
  273. * folio_mkclean(), followed by set_page_dirty().
  274. * However, now the page is going to get written back,
  275. * which meets the original intention of setting it
  276. * dirty, so all is well: clear_page_dirty_for_io() goes
  277. * on to call TestClearPageDirty(), and write the page
  278. * back.
  279. *
  280. * 2) This code sees the page as clean, so it calls
  281. * set_page_dirty(). The page stays dirty, despite being
  282. * written back, so it gets written back again in the
  283. * next writeback cycle. This is harmless.
  284. */
  285. if (!folio_test_dirty(folio)) {
  286. folio_lock(folio);
  287. folio_mark_dirty(folio);
  288. folio_unlock(folio);
  289. }
  290. gup_put_folio(folio, nr, FOLL_PIN);
  291. }
  292. }
  293. EXPORT_SYMBOL(unpin_user_pages_dirty_lock);
  294. /**
  295. * unpin_user_page_range_dirty_lock() - release and optionally dirty
  296. * gup-pinned page range
  297. *
  298. * @page: the starting page of a range maybe marked dirty, and definitely released.
  299. * @npages: number of consecutive pages to release.
  300. * @make_dirty: whether to mark the pages dirty
  301. *
  302. * "gup-pinned page range" refers to a range of pages that has had one of the
  303. * pin_user_pages() variants called on that page.
  304. *
  305. * The page range must be truly physically contiguous: the page range
  306. * corresponds to a contiguous PFN range and all pages can be iterated
  307. * naturally.
  308. *
  309. * For the page ranges defined by [page .. page+npages], make that range (or
  310. * its head pages, if a compound page) dirty, if @make_dirty is true, and if the
  311. * page range was previously listed as clean.
  312. *
  313. * set_page_dirty_lock() is used internally. If instead, set_page_dirty() is
  314. * required, then the caller should a) verify that this is really correct,
  315. * because _lock() is usually required, and b) hand code it:
  316. * set_page_dirty_lock(), unpin_user_page().
  317. *
  318. */
  319. void unpin_user_page_range_dirty_lock(struct page *page, unsigned long npages,
  320. bool make_dirty)
  321. {
  322. unsigned long i;
  323. struct folio *folio;
  324. unsigned int nr;
  325. VM_WARN_ON_ONCE(!page_range_contiguous(page, npages));
  326. for (i = 0; i < npages; i += nr) {
  327. folio = gup_folio_range_next(page, npages, i, &nr);
  328. if (make_dirty && !folio_test_dirty(folio)) {
  329. folio_lock(folio);
  330. folio_mark_dirty(folio);
  331. folio_unlock(folio);
  332. }
  333. gup_put_folio(folio, nr, FOLL_PIN);
  334. }
  335. }
  336. EXPORT_SYMBOL(unpin_user_page_range_dirty_lock);
  337. static void gup_fast_unpin_user_pages(struct page **pages, unsigned long npages)
  338. {
  339. unsigned long i;
  340. struct folio *folio;
  341. unsigned int nr;
  342. /*
  343. * Don't perform any sanity checks because we might have raced with
  344. * fork() and some anonymous pages might now actually be shared --
  345. * which is why we're unpinning after all.
  346. */
  347. for (i = 0; i < npages; i += nr) {
  348. folio = gup_folio_next(pages, npages, i, &nr);
  349. gup_put_folio(folio, nr, FOLL_PIN);
  350. }
  351. }
  352. /**
  353. * unpin_user_pages() - release an array of gup-pinned pages.
  354. * @pages: array of pages to be marked dirty and released.
  355. * @npages: number of pages in the @pages array.
  356. *
  357. * For each page in the @pages array, release the page using unpin_user_page().
  358. *
  359. * Please see the unpin_user_page() documentation for details.
  360. */
  361. void unpin_user_pages(struct page **pages, unsigned long npages)
  362. {
  363. unsigned long i;
  364. struct folio *folio;
  365. unsigned int nr;
  366. /*
  367. * If this WARN_ON() fires, then the system *might* be leaking pages (by
  368. * leaving them pinned), but probably not. More likely, gup/pup returned
  369. * a hard -ERRNO error to the caller, who erroneously passed it here.
  370. */
  371. if (WARN_ON(IS_ERR_VALUE(npages)))
  372. return;
  373. sanity_check_pinned_pages(pages, npages);
  374. for (i = 0; i < npages; i += nr) {
  375. if (!pages[i]) {
  376. nr = 1;
  377. continue;
  378. }
  379. folio = gup_folio_next(pages, npages, i, &nr);
  380. gup_put_folio(folio, nr, FOLL_PIN);
  381. }
  382. }
  383. EXPORT_SYMBOL(unpin_user_pages);
  384. /**
  385. * unpin_user_folio() - release pages of a folio
  386. * @folio: pointer to folio to be released
  387. * @npages: number of pages of same folio
  388. *
  389. * Release npages of the folio
  390. */
  391. void unpin_user_folio(struct folio *folio, unsigned long npages)
  392. {
  393. gup_put_folio(folio, npages, FOLL_PIN);
  394. }
  395. EXPORT_SYMBOL(unpin_user_folio);
  396. /**
  397. * unpin_folios() - release an array of gup-pinned folios.
  398. * @folios: array of folios to be marked dirty and released.
  399. * @nfolios: number of folios in the @folios array.
  400. *
  401. * For each folio in the @folios array, release the folio using gup_put_folio.
  402. *
  403. * Please see the unpin_folio() documentation for details.
  404. */
  405. void unpin_folios(struct folio **folios, unsigned long nfolios)
  406. {
  407. unsigned long i = 0, j;
  408. /*
  409. * If this WARN_ON() fires, then the system *might* be leaking folios
  410. * (by leaving them pinned), but probably not. More likely, gup/pup
  411. * returned a hard -ERRNO error to the caller, who erroneously passed
  412. * it here.
  413. */
  414. if (WARN_ON(IS_ERR_VALUE(nfolios)))
  415. return;
  416. while (i < nfolios) {
  417. for (j = i + 1; j < nfolios; j++)
  418. if (folios[i] != folios[j])
  419. break;
  420. if (folios[i])
  421. gup_put_folio(folios[i], j - i, FOLL_PIN);
  422. i = j;
  423. }
  424. }
  425. EXPORT_SYMBOL_GPL(unpin_folios);
  426. /*
  427. * Set the MMF_HAS_PINNED if not set yet; after set it'll be there for the mm's
  428. * lifecycle. Avoid setting the bit unless necessary, or it might cause write
  429. * cache bouncing on large SMP machines for concurrent pinned gups.
  430. */
  431. static inline void mm_set_has_pinned_flag(struct mm_struct *mm)
  432. {
  433. if (!mm_flags_test(MMF_HAS_PINNED, mm))
  434. mm_flags_set(MMF_HAS_PINNED, mm);
  435. }
  436. #ifdef CONFIG_MMU
  437. #ifdef CONFIG_HAVE_GUP_FAST
  438. /**
  439. * try_grab_folio_fast() - Attempt to get or pin a folio in fast path.
  440. * @page: pointer to page to be grabbed
  441. * @refs: the value to (effectively) add to the folio's refcount
  442. * @flags: gup flags: these are the FOLL_* flag values.
  443. *
  444. * "grab" names in this file mean, "look at flags to decide whether to use
  445. * FOLL_PIN or FOLL_GET behavior, when incrementing the folio's refcount.
  446. *
  447. * Either FOLL_PIN or FOLL_GET (or neither) must be set, but not both at the
  448. * same time. (That's true throughout the get_user_pages*() and
  449. * pin_user_pages*() APIs.) Cases:
  450. *
  451. * FOLL_GET: folio's refcount will be incremented by @refs.
  452. *
  453. * FOLL_PIN on large folios: folio's refcount will be incremented by
  454. * @refs, and its pincount will be incremented by @refs.
  455. *
  456. * FOLL_PIN on single-page folios: folio's refcount will be incremented by
  457. * @refs * GUP_PIN_COUNTING_BIAS.
  458. *
  459. * Return: The folio containing @page (with refcount appropriately
  460. * incremented) for success, or NULL upon failure. If neither FOLL_GET
  461. * nor FOLL_PIN was set, that's considered failure, and furthermore,
  462. * a likely bug in the caller, so a warning is also emitted.
  463. *
  464. * It uses add ref unless zero to elevate the folio refcount and must be called
  465. * in fast path only.
  466. */
  467. static struct folio *try_grab_folio_fast(struct page *page, int refs,
  468. unsigned int flags)
  469. {
  470. struct folio *folio;
  471. /* Raise warn if it is not called in fast GUP */
  472. VM_WARN_ON_ONCE(!irqs_disabled());
  473. if (WARN_ON_ONCE((flags & (FOLL_GET | FOLL_PIN)) == 0))
  474. return NULL;
  475. if (unlikely(!(flags & FOLL_PCI_P2PDMA) && is_pci_p2pdma_page(page)))
  476. return NULL;
  477. if (flags & FOLL_GET)
  478. return try_get_folio(page, refs);
  479. /* FOLL_PIN is set */
  480. /*
  481. * Don't take a pin on the zero page - it's not going anywhere
  482. * and it is used in a *lot* of places.
  483. */
  484. if (is_zero_page(page))
  485. return page_folio(page);
  486. folio = try_get_folio(page, refs);
  487. if (!folio)
  488. return NULL;
  489. /*
  490. * Can't do FOLL_LONGTERM + FOLL_PIN gup fast path if not in a
  491. * right zone, so fail and let the caller fall back to the slow
  492. * path.
  493. */
  494. if (unlikely((flags & FOLL_LONGTERM) &&
  495. !folio_is_longterm_pinnable(folio))) {
  496. folio_put_refs(folio, refs);
  497. return NULL;
  498. }
  499. /*
  500. * When pinning a large folio, use an exact count to track it.
  501. *
  502. * However, be sure to *also* increment the normal folio
  503. * refcount field at least once, so that the folio really
  504. * is pinned. That's why the refcount from the earlier
  505. * try_get_folio() is left intact.
  506. */
  507. if (folio_has_pincount(folio))
  508. atomic_add(refs, &folio->_pincount);
  509. else
  510. folio_ref_add(folio,
  511. refs * (GUP_PIN_COUNTING_BIAS - 1));
  512. /*
  513. * Adjust the pincount before re-checking the PTE for changes.
  514. * This is essentially a smp_mb() and is paired with a memory
  515. * barrier in folio_try_share_anon_rmap_*().
  516. */
  517. smp_mb__after_atomic();
  518. node_stat_mod_folio(folio, NR_FOLL_PIN_ACQUIRED, refs);
  519. return folio;
  520. }
  521. #endif /* CONFIG_HAVE_GUP_FAST */
  522. /* Common code for can_follow_write_* */
  523. static inline bool can_follow_write_common(struct page *page,
  524. struct vm_area_struct *vma, unsigned int flags)
  525. {
  526. /* Maybe FOLL_FORCE is set to override it? */
  527. if (!(flags & FOLL_FORCE))
  528. return false;
  529. /* But FOLL_FORCE has no effect on shared mappings */
  530. if (vma->vm_flags & (VM_MAYSHARE | VM_SHARED))
  531. return false;
  532. /* ... or read-only private ones */
  533. if (!(vma->vm_flags & VM_MAYWRITE))
  534. return false;
  535. /* ... or already writable ones that just need to take a write fault */
  536. if (vma->vm_flags & VM_WRITE)
  537. return false;
  538. /*
  539. * See can_change_pte_writable(): we broke COW and could map the page
  540. * writable if we have an exclusive anonymous page ...
  541. */
  542. return page && PageAnon(page) && PageAnonExclusive(page);
  543. }
  544. static struct page *no_page_table(struct vm_area_struct *vma,
  545. unsigned int flags, unsigned long address)
  546. {
  547. if (!(flags & FOLL_DUMP))
  548. return NULL;
  549. /*
  550. * When core dumping, we don't want to allocate unnecessary pages or
  551. * page tables. Return error instead of NULL to skip handle_mm_fault,
  552. * then get_dump_page() will return NULL to leave a hole in the dump.
  553. * But we can only make this optimization where a hole would surely
  554. * be zero-filled if handle_mm_fault() actually did handle it.
  555. */
  556. if (is_vm_hugetlb_page(vma)) {
  557. struct hstate *h = hstate_vma(vma);
  558. if (!hugetlbfs_pagecache_present(h, vma, address))
  559. return ERR_PTR(-EFAULT);
  560. } else if ((vma_is_anonymous(vma) || !vma->vm_ops->fault)) {
  561. return ERR_PTR(-EFAULT);
  562. }
  563. return NULL;
  564. }
  565. #ifdef CONFIG_PGTABLE_HAS_HUGE_LEAVES
  566. /* FOLL_FORCE can write to even unwritable PUDs in COW mappings. */
  567. static inline bool can_follow_write_pud(pud_t pud, struct page *page,
  568. struct vm_area_struct *vma,
  569. unsigned int flags)
  570. {
  571. /* If the pud is writable, we can write to the page. */
  572. if (pud_write(pud))
  573. return true;
  574. return can_follow_write_common(page, vma, flags);
  575. }
  576. static struct page *follow_huge_pud(struct vm_area_struct *vma,
  577. unsigned long addr, pud_t *pudp,
  578. int flags, unsigned long *page_mask)
  579. {
  580. struct mm_struct *mm = vma->vm_mm;
  581. struct page *page;
  582. pud_t pud = *pudp;
  583. unsigned long pfn = pud_pfn(pud);
  584. int ret;
  585. assert_spin_locked(pud_lockptr(mm, pudp));
  586. if (!pud_present(pud))
  587. return NULL;
  588. if ((flags & FOLL_WRITE) &&
  589. !can_follow_write_pud(pud, pfn_to_page(pfn), vma, flags))
  590. return NULL;
  591. pfn += (addr & ~PUD_MASK) >> PAGE_SHIFT;
  592. page = pfn_to_page(pfn);
  593. if (!pud_write(pud) && gup_must_unshare(vma, flags, page))
  594. return ERR_PTR(-EMLINK);
  595. ret = try_grab_folio(page_folio(page), 1, flags);
  596. if (ret)
  597. page = ERR_PTR(ret);
  598. else
  599. *page_mask = HPAGE_PUD_NR - 1;
  600. return page;
  601. }
  602. /* FOLL_FORCE can write to even unwritable PMDs in COW mappings. */
  603. static inline bool can_follow_write_pmd(pmd_t pmd, struct page *page,
  604. struct vm_area_struct *vma,
  605. unsigned int flags)
  606. {
  607. /* If the pmd is writable, we can write to the page. */
  608. if (pmd_write(pmd))
  609. return true;
  610. if (!can_follow_write_common(page, vma, flags))
  611. return false;
  612. /* ... and a write-fault isn't required for other reasons. */
  613. if (pmd_needs_soft_dirty_wp(vma, pmd))
  614. return false;
  615. return !userfaultfd_huge_pmd_wp(vma, pmd);
  616. }
  617. static struct page *follow_huge_pmd(struct vm_area_struct *vma,
  618. unsigned long addr, pmd_t *pmd,
  619. unsigned int flags,
  620. unsigned long *page_mask)
  621. {
  622. struct mm_struct *mm = vma->vm_mm;
  623. pmd_t pmdval = *pmd;
  624. struct page *page;
  625. int ret;
  626. assert_spin_locked(pmd_lockptr(mm, pmd));
  627. page = pmd_page(pmdval);
  628. if ((flags & FOLL_WRITE) &&
  629. !can_follow_write_pmd(pmdval, page, vma, flags))
  630. return NULL;
  631. /* Avoid dumping huge zero page */
  632. if ((flags & FOLL_DUMP) && is_huge_zero_pmd(pmdval))
  633. return ERR_PTR(-EFAULT);
  634. if (pmd_protnone(*pmd) && !gup_can_follow_protnone(vma, flags))
  635. return NULL;
  636. if (!pmd_write(pmdval) && gup_must_unshare(vma, flags, page))
  637. return ERR_PTR(-EMLINK);
  638. VM_WARN_ON_ONCE_PAGE((flags & FOLL_PIN) && PageAnon(page) &&
  639. !PageAnonExclusive(page), page);
  640. ret = try_grab_folio(page_folio(page), 1, flags);
  641. if (ret)
  642. return ERR_PTR(ret);
  643. #ifdef CONFIG_TRANSPARENT_HUGEPAGE
  644. if (pmd_trans_huge(pmdval) && (flags & FOLL_TOUCH))
  645. touch_pmd(vma, addr, pmd, flags & FOLL_WRITE);
  646. #endif /* CONFIG_TRANSPARENT_HUGEPAGE */
  647. page += (addr & ~HPAGE_PMD_MASK) >> PAGE_SHIFT;
  648. *page_mask = HPAGE_PMD_NR - 1;
  649. return page;
  650. }
  651. #else /* CONFIG_PGTABLE_HAS_HUGE_LEAVES */
  652. static struct page *follow_huge_pud(struct vm_area_struct *vma,
  653. unsigned long addr, pud_t *pudp,
  654. int flags, unsigned long *page_mask)
  655. {
  656. return NULL;
  657. }
  658. static struct page *follow_huge_pmd(struct vm_area_struct *vma,
  659. unsigned long addr, pmd_t *pmd,
  660. unsigned int flags,
  661. unsigned long *page_mask)
  662. {
  663. return NULL;
  664. }
  665. #endif /* CONFIG_PGTABLE_HAS_HUGE_LEAVES */
  666. static int follow_pfn_pte(struct vm_area_struct *vma, unsigned long address,
  667. pte_t *pte, unsigned int flags)
  668. {
  669. if (flags & FOLL_TOUCH) {
  670. pte_t orig_entry = ptep_get(pte);
  671. pte_t entry = orig_entry;
  672. if (flags & FOLL_WRITE)
  673. entry = pte_mkdirty(entry);
  674. entry = pte_mkyoung(entry);
  675. if (!pte_same(orig_entry, entry)) {
  676. set_pte_at(vma->vm_mm, address, pte, entry);
  677. update_mmu_cache(vma, address, pte);
  678. }
  679. }
  680. /* Proper page table entry exists, but no corresponding struct page */
  681. return -EEXIST;
  682. }
  683. /* FOLL_FORCE can write to even unwritable PTEs in COW mappings. */
  684. static inline bool can_follow_write_pte(pte_t pte, struct page *page,
  685. struct vm_area_struct *vma,
  686. unsigned int flags)
  687. {
  688. /* If the pte is writable, we can write to the page. */
  689. if (pte_write(pte))
  690. return true;
  691. if (!can_follow_write_common(page, vma, flags))
  692. return false;
  693. /* ... and a write-fault isn't required for other reasons. */
  694. if (pte_needs_soft_dirty_wp(vma, pte))
  695. return false;
  696. return !userfaultfd_pte_wp(vma, pte);
  697. }
  698. static struct page *follow_page_pte(struct vm_area_struct *vma,
  699. unsigned long address, pmd_t *pmd, unsigned int flags)
  700. {
  701. struct mm_struct *mm = vma->vm_mm;
  702. struct folio *folio;
  703. struct page *page;
  704. spinlock_t *ptl;
  705. pte_t *ptep, pte;
  706. int ret;
  707. ptep = pte_offset_map_lock(mm, pmd, address, &ptl);
  708. if (!ptep)
  709. return no_page_table(vma, flags, address);
  710. pte = ptep_get(ptep);
  711. if (!pte_present(pte))
  712. goto no_page;
  713. if (pte_protnone(pte) && !gup_can_follow_protnone(vma, flags))
  714. goto no_page;
  715. page = vm_normal_page(vma, address, pte);
  716. /*
  717. * We only care about anon pages in can_follow_write_pte().
  718. */
  719. if ((flags & FOLL_WRITE) &&
  720. !can_follow_write_pte(pte, page, vma, flags)) {
  721. page = NULL;
  722. goto out;
  723. }
  724. if (unlikely(!page)) {
  725. if (flags & FOLL_DUMP) {
  726. /* Avoid special (like zero) pages in core dumps */
  727. page = ERR_PTR(-EFAULT);
  728. goto out;
  729. }
  730. if (is_zero_pfn(pte_pfn(pte))) {
  731. page = pte_page(pte);
  732. } else {
  733. ret = follow_pfn_pte(vma, address, ptep, flags);
  734. page = ERR_PTR(ret);
  735. goto out;
  736. }
  737. }
  738. folio = page_folio(page);
  739. if (!pte_write(pte) && gup_must_unshare(vma, flags, page)) {
  740. page = ERR_PTR(-EMLINK);
  741. goto out;
  742. }
  743. VM_WARN_ON_ONCE_PAGE((flags & FOLL_PIN) && PageAnon(page) &&
  744. !PageAnonExclusive(page), page);
  745. /* try_grab_folio() does nothing unless FOLL_GET or FOLL_PIN is set. */
  746. ret = try_grab_folio(folio, 1, flags);
  747. if (unlikely(ret)) {
  748. page = ERR_PTR(ret);
  749. goto out;
  750. }
  751. /*
  752. * We need to make the page accessible if and only if we are going
  753. * to access its content (the FOLL_PIN case). Please see
  754. * Documentation/core-api/pin_user_pages.rst for details.
  755. */
  756. if (flags & FOLL_PIN) {
  757. ret = arch_make_folio_accessible(folio);
  758. if (ret) {
  759. unpin_user_page(page);
  760. page = ERR_PTR(ret);
  761. goto out;
  762. }
  763. }
  764. if (flags & FOLL_TOUCH) {
  765. if ((flags & FOLL_WRITE) &&
  766. !pte_dirty(pte) && !folio_test_dirty(folio))
  767. folio_mark_dirty(folio);
  768. /*
  769. * pte_mkyoung() would be more correct here, but atomic care
  770. * is needed to avoid losing the dirty bit: it is easier to use
  771. * folio_mark_accessed().
  772. */
  773. folio_mark_accessed(folio);
  774. }
  775. out:
  776. pte_unmap_unlock(ptep, ptl);
  777. return page;
  778. no_page:
  779. pte_unmap_unlock(ptep, ptl);
  780. if (!pte_none(pte))
  781. return NULL;
  782. return no_page_table(vma, flags, address);
  783. }
  784. static struct page *follow_pmd_mask(struct vm_area_struct *vma,
  785. unsigned long address, pud_t *pudp,
  786. unsigned int flags,
  787. unsigned long *page_mask)
  788. {
  789. pmd_t *pmd, pmdval;
  790. spinlock_t *ptl;
  791. struct page *page;
  792. struct mm_struct *mm = vma->vm_mm;
  793. pmd = pmd_offset(pudp, address);
  794. pmdval = pmdp_get_lockless(pmd);
  795. if (pmd_none(pmdval))
  796. return no_page_table(vma, flags, address);
  797. if (!pmd_present(pmdval))
  798. return no_page_table(vma, flags, address);
  799. if (likely(!pmd_leaf(pmdval)))
  800. return follow_page_pte(vma, address, pmd, flags);
  801. if (pmd_protnone(pmdval) && !gup_can_follow_protnone(vma, flags))
  802. return no_page_table(vma, flags, address);
  803. ptl = pmd_lock(mm, pmd);
  804. pmdval = *pmd;
  805. if (unlikely(!pmd_present(pmdval))) {
  806. spin_unlock(ptl);
  807. return no_page_table(vma, flags, address);
  808. }
  809. if (unlikely(!pmd_leaf(pmdval))) {
  810. spin_unlock(ptl);
  811. return follow_page_pte(vma, address, pmd, flags);
  812. }
  813. if (pmd_trans_huge(pmdval) && (flags & FOLL_SPLIT_PMD)) {
  814. spin_unlock(ptl);
  815. split_huge_pmd(vma, pmd, address);
  816. /* If pmd was left empty, stuff a page table in there quickly */
  817. return pte_alloc(mm, pmd) ? ERR_PTR(-ENOMEM) :
  818. follow_page_pte(vma, address, pmd, flags);
  819. }
  820. page = follow_huge_pmd(vma, address, pmd, flags, page_mask);
  821. spin_unlock(ptl);
  822. return page;
  823. }
  824. static struct page *follow_pud_mask(struct vm_area_struct *vma,
  825. unsigned long address, p4d_t *p4dp,
  826. unsigned int flags,
  827. unsigned long *page_mask)
  828. {
  829. pud_t *pudp, pud;
  830. spinlock_t *ptl;
  831. struct page *page;
  832. struct mm_struct *mm = vma->vm_mm;
  833. pudp = pud_offset(p4dp, address);
  834. pud = pudp_get(pudp);
  835. if (!pud_present(pud))
  836. return no_page_table(vma, flags, address);
  837. if (pud_leaf(pud)) {
  838. ptl = pud_lock(mm, pudp);
  839. page = follow_huge_pud(vma, address, pudp, flags, page_mask);
  840. spin_unlock(ptl);
  841. if (page)
  842. return page;
  843. return no_page_table(vma, flags, address);
  844. }
  845. if (unlikely(pud_bad(pud)))
  846. return no_page_table(vma, flags, address);
  847. return follow_pmd_mask(vma, address, pudp, flags, page_mask);
  848. }
  849. static struct page *follow_p4d_mask(struct vm_area_struct *vma,
  850. unsigned long address, pgd_t *pgdp,
  851. unsigned int flags,
  852. unsigned long *page_mask)
  853. {
  854. p4d_t *p4dp, p4d;
  855. p4dp = p4d_offset(pgdp, address);
  856. p4d = p4dp_get(p4dp);
  857. BUILD_BUG_ON(p4d_leaf(p4d));
  858. if (!p4d_present(p4d) || p4d_bad(p4d))
  859. return no_page_table(vma, flags, address);
  860. return follow_pud_mask(vma, address, p4dp, flags, page_mask);
  861. }
  862. /**
  863. * follow_page_mask - look up a page descriptor from a user-virtual address
  864. * @vma: vm_area_struct mapping @address
  865. * @address: virtual address to look up
  866. * @flags: flags modifying lookup behaviour
  867. * @page_mask: a pointer to output page_mask
  868. *
  869. * @flags can have FOLL_ flags set, defined in <linux/mm.h>
  870. *
  871. * When getting an anonymous page and the caller has to trigger unsharing
  872. * of a shared anonymous page first, -EMLINK is returned. The caller should
  873. * trigger a fault with FAULT_FLAG_UNSHARE set. Note that unsharing is only
  874. * relevant with FOLL_PIN and !FOLL_WRITE.
  875. *
  876. * On output, @page_mask is set according to the size of the page.
  877. *
  878. * Return: the mapped (struct page *), %NULL if no mapping exists, or
  879. * an error pointer if there is a mapping to something not represented
  880. * by a page descriptor (see also vm_normal_page()).
  881. */
  882. static struct page *follow_page_mask(struct vm_area_struct *vma,
  883. unsigned long address, unsigned int flags,
  884. unsigned long *page_mask)
  885. {
  886. pgd_t *pgd;
  887. struct mm_struct *mm = vma->vm_mm;
  888. struct page *page;
  889. vma_pgtable_walk_begin(vma);
  890. *page_mask = 0;
  891. pgd = pgd_offset(mm, address);
  892. if (pgd_none(*pgd) || unlikely(pgd_bad(*pgd)))
  893. page = no_page_table(vma, flags, address);
  894. else
  895. page = follow_p4d_mask(vma, address, pgd, flags, page_mask);
  896. vma_pgtable_walk_end(vma);
  897. return page;
  898. }
  899. static int get_gate_page(struct mm_struct *mm, unsigned long address,
  900. unsigned int gup_flags, struct vm_area_struct **vma,
  901. struct page **page)
  902. {
  903. pgd_t *pgd;
  904. p4d_t *p4d;
  905. pud_t *pud;
  906. pmd_t *pmd;
  907. pte_t *pte;
  908. pte_t entry;
  909. int ret = -EFAULT;
  910. /* user gate pages are read-only */
  911. if (gup_flags & FOLL_WRITE)
  912. return -EFAULT;
  913. pgd = pgd_offset(mm, address);
  914. if (pgd_none(*pgd))
  915. return -EFAULT;
  916. p4d = p4d_offset(pgd, address);
  917. if (p4d_none(*p4d))
  918. return -EFAULT;
  919. pud = pud_offset(p4d, address);
  920. if (pud_none(*pud))
  921. return -EFAULT;
  922. pmd = pmd_offset(pud, address);
  923. if (!pmd_present(*pmd))
  924. return -EFAULT;
  925. pte = pte_offset_map(pmd, address);
  926. if (!pte)
  927. return -EFAULT;
  928. entry = ptep_get(pte);
  929. if (pte_none(entry))
  930. goto unmap;
  931. *vma = get_gate_vma(mm);
  932. if (!page)
  933. goto out;
  934. *page = vm_normal_page(*vma, address, entry);
  935. if (!*page) {
  936. if ((gup_flags & FOLL_DUMP) || !is_zero_pfn(pte_pfn(entry)))
  937. goto unmap;
  938. *page = pte_page(entry);
  939. }
  940. ret = try_grab_folio(page_folio(*page), 1, gup_flags);
  941. if (unlikely(ret))
  942. goto unmap;
  943. out:
  944. ret = 0;
  945. unmap:
  946. pte_unmap(pte);
  947. return ret;
  948. }
  949. /*
  950. * mmap_lock must be held on entry. If @flags has FOLL_UNLOCKABLE but not
  951. * FOLL_NOWAIT, the mmap_lock may be released. If it is, *@locked will be set
  952. * to 0 and -EBUSY returned.
  953. */
  954. static int faultin_page(struct vm_area_struct *vma,
  955. unsigned long address, unsigned int flags, bool unshare,
  956. int *locked)
  957. {
  958. unsigned int fault_flags = 0;
  959. vm_fault_t ret;
  960. if (flags & FOLL_NOFAULT)
  961. return -EFAULT;
  962. if (flags & FOLL_WRITE)
  963. fault_flags |= FAULT_FLAG_WRITE;
  964. if (flags & FOLL_REMOTE)
  965. fault_flags |= FAULT_FLAG_REMOTE;
  966. if (flags & FOLL_UNLOCKABLE) {
  967. fault_flags |= FAULT_FLAG_ALLOW_RETRY | FAULT_FLAG_KILLABLE;
  968. /*
  969. * FAULT_FLAG_INTERRUPTIBLE is opt-in. GUP callers must set
  970. * FOLL_INTERRUPTIBLE to enable FAULT_FLAG_INTERRUPTIBLE.
  971. * That's because some callers may not be prepared to
  972. * handle early exits caused by non-fatal signals.
  973. */
  974. if (flags & FOLL_INTERRUPTIBLE)
  975. fault_flags |= FAULT_FLAG_INTERRUPTIBLE;
  976. }
  977. if (flags & FOLL_NOWAIT)
  978. fault_flags |= FAULT_FLAG_ALLOW_RETRY | FAULT_FLAG_RETRY_NOWAIT;
  979. if (flags & FOLL_TRIED) {
  980. /*
  981. * Note: FAULT_FLAG_ALLOW_RETRY and FAULT_FLAG_TRIED
  982. * can co-exist
  983. */
  984. fault_flags |= FAULT_FLAG_TRIED;
  985. }
  986. if (unshare) {
  987. fault_flags |= FAULT_FLAG_UNSHARE;
  988. /* FAULT_FLAG_WRITE and FAULT_FLAG_UNSHARE are incompatible */
  989. VM_WARN_ON_ONCE(fault_flags & FAULT_FLAG_WRITE);
  990. }
  991. ret = handle_mm_fault(vma, address, fault_flags, NULL);
  992. if (ret & VM_FAULT_COMPLETED) {
  993. /*
  994. * With FAULT_FLAG_RETRY_NOWAIT we'll never release the
  995. * mmap lock in the page fault handler. Sanity check this.
  996. */
  997. WARN_ON_ONCE(fault_flags & FAULT_FLAG_RETRY_NOWAIT);
  998. *locked = 0;
  999. /*
  1000. * We should do the same as VM_FAULT_RETRY, but let's not
  1001. * return -EBUSY since that's not reflecting the reality of
  1002. * what has happened - we've just fully completed a page
  1003. * fault, with the mmap lock released. Use -EAGAIN to show
  1004. * that we want to take the mmap lock _again_.
  1005. */
  1006. return -EAGAIN;
  1007. }
  1008. if (ret & VM_FAULT_ERROR) {
  1009. int err = vm_fault_to_errno(ret, flags);
  1010. if (err)
  1011. return err;
  1012. BUG();
  1013. }
  1014. if (ret & VM_FAULT_RETRY) {
  1015. if (!(fault_flags & FAULT_FLAG_RETRY_NOWAIT))
  1016. *locked = 0;
  1017. return -EBUSY;
  1018. }
  1019. return 0;
  1020. }
  1021. /*
  1022. * Writing to file-backed mappings which require folio dirty tracking using GUP
  1023. * is a fundamentally broken operation, as kernel write access to GUP mappings
  1024. * do not adhere to the semantics expected by a file system.
  1025. *
  1026. * Consider the following scenario:-
  1027. *
  1028. * 1. A folio is written to via GUP which write-faults the memory, notifying
  1029. * the file system and dirtying the folio.
  1030. * 2. Later, writeback is triggered, resulting in the folio being cleaned and
  1031. * the PTE being marked read-only.
  1032. * 3. The GUP caller writes to the folio, as it is mapped read/write via the
  1033. * direct mapping.
  1034. * 4. The GUP caller, now done with the page, unpins it and sets it dirty
  1035. * (though it does not have to).
  1036. *
  1037. * This results in both data being written to a folio without writenotify, and
  1038. * the folio being dirtied unexpectedly (if the caller decides to do so).
  1039. */
  1040. static bool writable_file_mapping_allowed(struct vm_area_struct *vma,
  1041. unsigned long gup_flags)
  1042. {
  1043. /*
  1044. * If we aren't pinning then no problematic write can occur. A long term
  1045. * pin is the most egregious case so this is the case we disallow.
  1046. */
  1047. if ((gup_flags & (FOLL_PIN | FOLL_LONGTERM)) !=
  1048. (FOLL_PIN | FOLL_LONGTERM))
  1049. return true;
  1050. /*
  1051. * If the VMA does not require dirty tracking then no problematic write
  1052. * can occur either.
  1053. */
  1054. return !vma_needs_dirty_tracking(vma);
  1055. }
  1056. static int check_vma_flags(struct vm_area_struct *vma, unsigned long gup_flags)
  1057. {
  1058. vm_flags_t vm_flags = vma->vm_flags;
  1059. int write = (gup_flags & FOLL_WRITE);
  1060. int foreign = (gup_flags & FOLL_REMOTE);
  1061. bool vma_anon = vma_is_anonymous(vma);
  1062. if (vm_flags & (VM_IO | VM_PFNMAP))
  1063. return -EFAULT;
  1064. if ((gup_flags & FOLL_ANON) && !vma_anon)
  1065. return -EFAULT;
  1066. if ((gup_flags & FOLL_LONGTERM) && vma_is_fsdax(vma))
  1067. return -EOPNOTSUPP;
  1068. if ((gup_flags & FOLL_SPLIT_PMD) && is_vm_hugetlb_page(vma))
  1069. return -EOPNOTSUPP;
  1070. if (vma_is_secretmem(vma))
  1071. return -EFAULT;
  1072. if (write) {
  1073. if (!vma_anon &&
  1074. !writable_file_mapping_allowed(vma, gup_flags))
  1075. return -EFAULT;
  1076. if (!(vm_flags & VM_WRITE) || (vm_flags & VM_SHADOW_STACK)) {
  1077. if (!(gup_flags & FOLL_FORCE))
  1078. return -EFAULT;
  1079. /*
  1080. * We used to let the write,force case do COW in a
  1081. * VM_MAYWRITE VM_SHARED !VM_WRITE vma, so ptrace could
  1082. * set a breakpoint in a read-only mapping of an
  1083. * executable, without corrupting the file (yet only
  1084. * when that file had been opened for writing!).
  1085. * Anon pages in shared mappings are surprising: now
  1086. * just reject it.
  1087. */
  1088. if (!is_cow_mapping(vm_flags))
  1089. return -EFAULT;
  1090. }
  1091. } else if (!(vm_flags & VM_READ)) {
  1092. if (!(gup_flags & FOLL_FORCE))
  1093. return -EFAULT;
  1094. /*
  1095. * Is there actually any vma we can reach here which does not
  1096. * have VM_MAYREAD set?
  1097. */
  1098. if (!(vm_flags & VM_MAYREAD))
  1099. return -EFAULT;
  1100. }
  1101. /*
  1102. * gups are always data accesses, not instruction
  1103. * fetches, so execute=false here
  1104. */
  1105. if (!arch_vma_access_permitted(vma, write, false, foreign))
  1106. return -EFAULT;
  1107. return 0;
  1108. }
  1109. /*
  1110. * This is "vma_lookup()", but with a warning if we would have
  1111. * historically expanded the stack in the GUP code.
  1112. */
  1113. static struct vm_area_struct *gup_vma_lookup(struct mm_struct *mm,
  1114. unsigned long addr)
  1115. {
  1116. #ifdef CONFIG_STACK_GROWSUP
  1117. return vma_lookup(mm, addr);
  1118. #else
  1119. static volatile unsigned long next_warn;
  1120. struct vm_area_struct *vma;
  1121. unsigned long now, next;
  1122. vma = find_vma(mm, addr);
  1123. if (!vma || (addr >= vma->vm_start))
  1124. return vma;
  1125. /* Only warn for half-way relevant accesses */
  1126. if (!(vma->vm_flags & VM_GROWSDOWN))
  1127. return NULL;
  1128. if (vma->vm_start - addr > 65536)
  1129. return NULL;
  1130. /* Let's not warn more than once an hour.. */
  1131. now = jiffies; next = next_warn;
  1132. if (next && time_before(now, next))
  1133. return NULL;
  1134. next_warn = now + 60*60*HZ;
  1135. /* Let people know things may have changed. */
  1136. pr_warn("GUP no longer grows the stack in %s (%d): %lx-%lx (%lx)\n",
  1137. current->comm, task_pid_nr(current),
  1138. vma->vm_start, vma->vm_end, addr);
  1139. dump_stack();
  1140. return NULL;
  1141. #endif
  1142. }
  1143. /**
  1144. * __get_user_pages() - pin user pages in memory
  1145. * @mm: mm_struct of target mm
  1146. * @start: starting user address
  1147. * @nr_pages: number of pages from start to pin
  1148. * @gup_flags: flags modifying pin behaviour
  1149. * @pages: array that receives pointers to the pages pinned.
  1150. * Should be at least nr_pages long. Or NULL, if caller
  1151. * only intends to ensure the pages are faulted in.
  1152. * @locked: whether we're still with the mmap_lock held
  1153. *
  1154. * Returns either number of pages pinned (which may be less than the
  1155. * number requested), or an error. Details about the return value:
  1156. *
  1157. * -- If nr_pages is 0, returns 0.
  1158. * -- If nr_pages is >0, but no pages were pinned, returns -errno.
  1159. * -- If nr_pages is >0, and some pages were pinned, returns the number of
  1160. * pages pinned. Again, this may be less than nr_pages.
  1161. * -- 0 return value is possible when the fault would need to be retried.
  1162. *
  1163. * The caller is responsible for releasing returned @pages, via put_page().
  1164. *
  1165. * Must be called with mmap_lock held. It may be released. See below.
  1166. *
  1167. * __get_user_pages walks a process's page tables and takes a reference to
  1168. * each struct page that each user address corresponds to at a given
  1169. * instant. That is, it takes the page that would be accessed if a user
  1170. * thread accesses the given user virtual address at that instant.
  1171. *
  1172. * This does not guarantee that the page exists in the user mappings when
  1173. * __get_user_pages returns, and there may even be a completely different
  1174. * page there in some cases (eg. if mmapped pagecache has been invalidated
  1175. * and subsequently re-faulted). However it does guarantee that the page
  1176. * won't be freed completely. And mostly callers simply care that the page
  1177. * contains data that was valid *at some point in time*. Typically, an IO
  1178. * or similar operation cannot guarantee anything stronger anyway because
  1179. * locks can't be held over the syscall boundary.
  1180. *
  1181. * If @gup_flags & FOLL_WRITE == 0, the page must not be written to. If
  1182. * the page is written to, set_page_dirty (or set_page_dirty_lock, as
  1183. * appropriate) must be called after the page is finished with, and
  1184. * before put_page is called.
  1185. *
  1186. * If FOLL_UNLOCKABLE is set without FOLL_NOWAIT then the mmap_lock may
  1187. * be released. If this happens *@locked will be set to 0 on return.
  1188. *
  1189. * A caller using such a combination of @gup_flags must therefore hold the
  1190. * mmap_lock for reading only, and recognize when it's been released. Otherwise,
  1191. * it must be held for either reading or writing and will not be released.
  1192. *
  1193. * In most cases, get_user_pages or get_user_pages_fast should be used
  1194. * instead of __get_user_pages. __get_user_pages should be used only if
  1195. * you need some special @gup_flags.
  1196. */
  1197. static long __get_user_pages(struct mm_struct *mm,
  1198. unsigned long start, unsigned long nr_pages,
  1199. unsigned int gup_flags, struct page **pages,
  1200. int *locked)
  1201. {
  1202. long ret = 0, i = 0;
  1203. struct vm_area_struct *vma = NULL;
  1204. unsigned long page_mask = 0;
  1205. if (!nr_pages)
  1206. return 0;
  1207. start = untagged_addr_remote(mm, start);
  1208. VM_WARN_ON_ONCE(!!pages != !!(gup_flags & (FOLL_GET | FOLL_PIN)));
  1209. /* FOLL_GET and FOLL_PIN are mutually exclusive. */
  1210. VM_WARN_ON_ONCE((gup_flags & (FOLL_PIN | FOLL_GET)) ==
  1211. (FOLL_PIN | FOLL_GET));
  1212. do {
  1213. struct page *page;
  1214. unsigned int page_increm;
  1215. /* first iteration or cross vma bound */
  1216. if (!vma || start >= vma->vm_end) {
  1217. /*
  1218. * MADV_POPULATE_(READ|WRITE) wants to handle VMA
  1219. * lookups+error reporting differently.
  1220. */
  1221. if (gup_flags & FOLL_MADV_POPULATE) {
  1222. vma = vma_lookup(mm, start);
  1223. if (!vma) {
  1224. ret = -ENOMEM;
  1225. goto out;
  1226. }
  1227. if (check_vma_flags(vma, gup_flags)) {
  1228. ret = -EINVAL;
  1229. goto out;
  1230. }
  1231. goto retry;
  1232. }
  1233. vma = gup_vma_lookup(mm, start);
  1234. if (!vma && in_gate_area(mm, start)) {
  1235. ret = get_gate_page(mm, start & PAGE_MASK,
  1236. gup_flags, &vma,
  1237. pages ? &page : NULL);
  1238. if (ret)
  1239. goto out;
  1240. page_mask = 0;
  1241. goto next_page;
  1242. }
  1243. if (!vma) {
  1244. ret = -EFAULT;
  1245. goto out;
  1246. }
  1247. ret = check_vma_flags(vma, gup_flags);
  1248. if (ret)
  1249. goto out;
  1250. }
  1251. retry:
  1252. /*
  1253. * If we have a pending SIGKILL, don't keep faulting pages and
  1254. * potentially allocating memory.
  1255. */
  1256. if (fatal_signal_pending(current)) {
  1257. ret = -EINTR;
  1258. goto out;
  1259. }
  1260. cond_resched();
  1261. page = follow_page_mask(vma, start, gup_flags, &page_mask);
  1262. if (!page || PTR_ERR(page) == -EMLINK) {
  1263. ret = faultin_page(vma, start, gup_flags,
  1264. PTR_ERR(page) == -EMLINK, locked);
  1265. switch (ret) {
  1266. case 0:
  1267. goto retry;
  1268. case -EBUSY:
  1269. case -EAGAIN:
  1270. ret = 0;
  1271. fallthrough;
  1272. case -EFAULT:
  1273. case -ENOMEM:
  1274. case -EHWPOISON:
  1275. goto out;
  1276. }
  1277. BUG();
  1278. } else if (PTR_ERR(page) == -EEXIST) {
  1279. /*
  1280. * Proper page table entry exists, but no corresponding
  1281. * struct page. If the caller expects **pages to be
  1282. * filled in, bail out now, because that can't be done
  1283. * for this page.
  1284. */
  1285. if (pages) {
  1286. ret = PTR_ERR(page);
  1287. goto out;
  1288. }
  1289. } else if (IS_ERR(page)) {
  1290. ret = PTR_ERR(page);
  1291. goto out;
  1292. }
  1293. next_page:
  1294. page_increm = 1 + (~(start >> PAGE_SHIFT) & page_mask);
  1295. if (page_increm > nr_pages)
  1296. page_increm = nr_pages;
  1297. if (pages) {
  1298. struct page *subpage;
  1299. unsigned int j;
  1300. /*
  1301. * This must be a large folio (and doesn't need to
  1302. * be the whole folio; it can be part of it), do
  1303. * the refcount work for all the subpages too.
  1304. *
  1305. * NOTE: here the page may not be the head page
  1306. * e.g. when start addr is not thp-size aligned.
  1307. * try_grab_folio() should have taken care of tail
  1308. * pages.
  1309. */
  1310. if (page_increm > 1) {
  1311. struct folio *folio = page_folio(page);
  1312. /*
  1313. * Since we already hold refcount on the
  1314. * large folio, this should never fail.
  1315. */
  1316. if (try_grab_folio(folio, page_increm - 1,
  1317. gup_flags)) {
  1318. /*
  1319. * Release the 1st page ref if the
  1320. * folio is problematic, fail hard.
  1321. */
  1322. gup_put_folio(folio, 1, gup_flags);
  1323. ret = -EFAULT;
  1324. goto out;
  1325. }
  1326. }
  1327. for (j = 0; j < page_increm; j++) {
  1328. subpage = page + j;
  1329. pages[i + j] = subpage;
  1330. flush_anon_page(vma, subpage, start + j * PAGE_SIZE);
  1331. flush_dcache_page(subpage);
  1332. }
  1333. }
  1334. i += page_increm;
  1335. start += page_increm * PAGE_SIZE;
  1336. nr_pages -= page_increm;
  1337. } while (nr_pages);
  1338. out:
  1339. return i ? i : ret;
  1340. }
  1341. static bool vma_permits_fault(struct vm_area_struct *vma,
  1342. unsigned int fault_flags)
  1343. {
  1344. bool write = !!(fault_flags & FAULT_FLAG_WRITE);
  1345. bool foreign = !!(fault_flags & FAULT_FLAG_REMOTE);
  1346. vm_flags_t vm_flags = write ? VM_WRITE : VM_READ;
  1347. if (!(vm_flags & vma->vm_flags))
  1348. return false;
  1349. /*
  1350. * The architecture might have a hardware protection
  1351. * mechanism other than read/write that can deny access.
  1352. *
  1353. * gup always represents data access, not instruction
  1354. * fetches, so execute=false here:
  1355. */
  1356. if (!arch_vma_access_permitted(vma, write, false, foreign))
  1357. return false;
  1358. return true;
  1359. }
  1360. /**
  1361. * fixup_user_fault() - manually resolve a user page fault
  1362. * @mm: mm_struct of target mm
  1363. * @address: user address
  1364. * @fault_flags:flags to pass down to handle_mm_fault()
  1365. * @unlocked: did we unlock the mmap_lock while retrying, maybe NULL if caller
  1366. * does not allow retry. If NULL, the caller must guarantee
  1367. * that fault_flags does not contain FAULT_FLAG_ALLOW_RETRY.
  1368. *
  1369. * This is meant to be called in the specific scenario where for locking reasons
  1370. * we try to access user memory in atomic context (within a pagefault_disable()
  1371. * section), this returns -EFAULT, and we want to resolve the user fault before
  1372. * trying again.
  1373. *
  1374. * Typically this is meant to be used by the futex code.
  1375. *
  1376. * The main difference with get_user_pages() is that this function will
  1377. * unconditionally call handle_mm_fault() which will in turn perform all the
  1378. * necessary SW fixup of the dirty and young bits in the PTE, while
  1379. * get_user_pages() only guarantees to update these in the struct page.
  1380. *
  1381. * This is important for some architectures where those bits also gate the
  1382. * access permission to the page because they are maintained in software. On
  1383. * such architectures, gup() will not be enough to make a subsequent access
  1384. * succeed.
  1385. *
  1386. * This function will not return with an unlocked mmap_lock. So it has not the
  1387. * same semantics wrt the @mm->mmap_lock as does filemap_fault().
  1388. */
  1389. int fixup_user_fault(struct mm_struct *mm,
  1390. unsigned long address, unsigned int fault_flags,
  1391. bool *unlocked)
  1392. {
  1393. struct vm_area_struct *vma;
  1394. vm_fault_t ret;
  1395. address = untagged_addr_remote(mm, address);
  1396. if (unlocked)
  1397. fault_flags |= FAULT_FLAG_ALLOW_RETRY | FAULT_FLAG_KILLABLE;
  1398. retry:
  1399. vma = gup_vma_lookup(mm, address);
  1400. if (!vma)
  1401. return -EFAULT;
  1402. if (!vma_permits_fault(vma, fault_flags))
  1403. return -EFAULT;
  1404. if ((fault_flags & FAULT_FLAG_KILLABLE) &&
  1405. fatal_signal_pending(current))
  1406. return -EINTR;
  1407. ret = handle_mm_fault(vma, address, fault_flags, NULL);
  1408. if (ret & VM_FAULT_COMPLETED) {
  1409. /*
  1410. * NOTE: it's a pity that we need to retake the lock here
  1411. * to pair with the unlock() in the callers. Ideally we
  1412. * could tell the callers so they do not need to unlock.
  1413. */
  1414. mmap_read_lock(mm);
  1415. *unlocked = true;
  1416. return 0;
  1417. }
  1418. if (ret & VM_FAULT_ERROR) {
  1419. int err = vm_fault_to_errno(ret, 0);
  1420. if (err)
  1421. return err;
  1422. BUG();
  1423. }
  1424. if (ret & VM_FAULT_RETRY) {
  1425. mmap_read_lock(mm);
  1426. *unlocked = true;
  1427. fault_flags |= FAULT_FLAG_TRIED;
  1428. goto retry;
  1429. }
  1430. return 0;
  1431. }
  1432. EXPORT_SYMBOL_GPL(fixup_user_fault);
  1433. /*
  1434. * GUP always responds to fatal signals. When FOLL_INTERRUPTIBLE is
  1435. * specified, it'll also respond to generic signals. The caller of GUP
  1436. * that has FOLL_INTERRUPTIBLE should take care of the GUP interruption.
  1437. */
  1438. static bool gup_signal_pending(unsigned int flags)
  1439. {
  1440. if (fatal_signal_pending(current))
  1441. return true;
  1442. if (!(flags & FOLL_INTERRUPTIBLE))
  1443. return false;
  1444. return signal_pending(current);
  1445. }
  1446. /*
  1447. * Locking: (*locked == 1) means that the mmap_lock has already been acquired by
  1448. * the caller. This function may drop the mmap_lock. If it does so, then it will
  1449. * set (*locked = 0).
  1450. *
  1451. * (*locked == 0) means that the caller expects this function to acquire and
  1452. * drop the mmap_lock. Therefore, the value of *locked will still be zero when
  1453. * the function returns, even though it may have changed temporarily during
  1454. * function execution.
  1455. *
  1456. * Please note that this function, unlike __get_user_pages(), will not return 0
  1457. * for nr_pages > 0, unless FOLL_NOWAIT is used.
  1458. */
  1459. static __always_inline long __get_user_pages_locked(struct mm_struct *mm,
  1460. unsigned long start,
  1461. unsigned long nr_pages,
  1462. struct page **pages,
  1463. int *locked,
  1464. unsigned int flags)
  1465. {
  1466. long ret, pages_done;
  1467. bool must_unlock = false;
  1468. if (!nr_pages)
  1469. return 0;
  1470. /*
  1471. * The internal caller expects GUP to manage the lock internally and the
  1472. * lock must be released when this returns.
  1473. */
  1474. if (!*locked) {
  1475. if (mmap_read_lock_killable(mm))
  1476. return -EAGAIN;
  1477. must_unlock = true;
  1478. *locked = 1;
  1479. }
  1480. else
  1481. mmap_assert_locked(mm);
  1482. if (flags & FOLL_PIN)
  1483. mm_set_has_pinned_flag(mm);
  1484. /*
  1485. * FOLL_PIN and FOLL_GET are mutually exclusive. Traditional behavior
  1486. * is to set FOLL_GET if the caller wants pages[] filled in (but has
  1487. * carelessly failed to specify FOLL_GET), so keep doing that, but only
  1488. * for FOLL_GET, not for the newer FOLL_PIN.
  1489. *
  1490. * FOLL_PIN always expects pages to be non-null, but no need to assert
  1491. * that here, as any failures will be obvious enough.
  1492. */
  1493. if (pages && !(flags & FOLL_PIN))
  1494. flags |= FOLL_GET;
  1495. pages_done = 0;
  1496. for (;;) {
  1497. ret = __get_user_pages(mm, start, nr_pages, flags, pages,
  1498. locked);
  1499. if (!(flags & FOLL_UNLOCKABLE)) {
  1500. /* VM_FAULT_RETRY couldn't trigger, bypass */
  1501. pages_done = ret;
  1502. break;
  1503. }
  1504. /* VM_FAULT_RETRY or VM_FAULT_COMPLETED cannot return errors */
  1505. VM_WARN_ON_ONCE(!*locked && (ret < 0 || ret >= nr_pages));
  1506. if (ret > 0) {
  1507. nr_pages -= ret;
  1508. pages_done += ret;
  1509. if (!nr_pages)
  1510. break;
  1511. }
  1512. if (*locked) {
  1513. /*
  1514. * VM_FAULT_RETRY didn't trigger or it was a
  1515. * FOLL_NOWAIT.
  1516. */
  1517. if (!pages_done)
  1518. pages_done = ret;
  1519. break;
  1520. }
  1521. /*
  1522. * VM_FAULT_RETRY triggered, so seek to the faulting offset.
  1523. * For the prefault case (!pages) we only update counts.
  1524. */
  1525. if (likely(pages))
  1526. pages += ret;
  1527. start += ret << PAGE_SHIFT;
  1528. /* The lock was temporarily dropped, so we must unlock later */
  1529. must_unlock = true;
  1530. retry:
  1531. /*
  1532. * Repeat on the address that fired VM_FAULT_RETRY
  1533. * with both FAULT_FLAG_ALLOW_RETRY and
  1534. * FAULT_FLAG_TRIED. Note that GUP can be interrupted
  1535. * by fatal signals of even common signals, depending on
  1536. * the caller's request. So we need to check it before we
  1537. * start trying again otherwise it can loop forever.
  1538. */
  1539. if (gup_signal_pending(flags)) {
  1540. if (!pages_done)
  1541. pages_done = -EINTR;
  1542. break;
  1543. }
  1544. ret = mmap_read_lock_killable(mm);
  1545. if (ret) {
  1546. if (!pages_done)
  1547. pages_done = ret;
  1548. break;
  1549. }
  1550. *locked = 1;
  1551. ret = __get_user_pages(mm, start, 1, flags | FOLL_TRIED,
  1552. pages, locked);
  1553. if (!*locked) {
  1554. /* Continue to retry until we succeeded */
  1555. VM_WARN_ON_ONCE(ret != 0);
  1556. goto retry;
  1557. }
  1558. if (ret != 1) {
  1559. VM_WARN_ON_ONCE(ret > 1);
  1560. if (!pages_done)
  1561. pages_done = ret;
  1562. break;
  1563. }
  1564. nr_pages--;
  1565. pages_done++;
  1566. if (!nr_pages)
  1567. break;
  1568. if (likely(pages))
  1569. pages++;
  1570. start += PAGE_SIZE;
  1571. }
  1572. if (must_unlock && *locked) {
  1573. /*
  1574. * We either temporarily dropped the lock, or the caller
  1575. * requested that we both acquire and drop the lock. Either way,
  1576. * we must now unlock, and notify the caller of that state.
  1577. */
  1578. mmap_read_unlock(mm);
  1579. *locked = 0;
  1580. }
  1581. /*
  1582. * Failing to pin anything implies something has gone wrong (except when
  1583. * FOLL_NOWAIT is specified).
  1584. */
  1585. if (WARN_ON_ONCE(pages_done == 0 && !(flags & FOLL_NOWAIT)))
  1586. return -EFAULT;
  1587. return pages_done;
  1588. }
  1589. /**
  1590. * populate_vma_page_range() - populate a range of pages in the vma.
  1591. * @vma: target vma
  1592. * @start: start address
  1593. * @end: end address
  1594. * @locked: whether the mmap_lock is still held
  1595. *
  1596. * This takes care of mlocking the pages too if VM_LOCKED is set.
  1597. *
  1598. * Return either number of pages pinned in the vma, or a negative error
  1599. * code on error.
  1600. *
  1601. * vma->vm_mm->mmap_lock must be held.
  1602. *
  1603. * If @locked is NULL, it may be held for read or write and will
  1604. * be unperturbed.
  1605. *
  1606. * If @locked is non-NULL, it must held for read only and may be
  1607. * released. If it's released, *@locked will be set to 0.
  1608. */
  1609. long populate_vma_page_range(struct vm_area_struct *vma,
  1610. unsigned long start, unsigned long end, int *locked)
  1611. {
  1612. struct mm_struct *mm = vma->vm_mm;
  1613. unsigned long nr_pages = (end - start) / PAGE_SIZE;
  1614. int local_locked = 1;
  1615. int gup_flags;
  1616. long ret;
  1617. VM_WARN_ON_ONCE(!PAGE_ALIGNED(start));
  1618. VM_WARN_ON_ONCE(!PAGE_ALIGNED(end));
  1619. VM_WARN_ON_ONCE_VMA(start < vma->vm_start, vma);
  1620. VM_WARN_ON_ONCE_VMA(end > vma->vm_end, vma);
  1621. mmap_assert_locked(mm);
  1622. /*
  1623. * Rightly or wrongly, the VM_LOCKONFAULT case has never used
  1624. * faultin_page() to break COW, so it has no work to do here.
  1625. */
  1626. if (vma->vm_flags & VM_LOCKONFAULT)
  1627. return nr_pages;
  1628. /* ... similarly, we've never faulted in PROT_NONE pages */
  1629. if (!vma_is_accessible(vma))
  1630. return -EFAULT;
  1631. gup_flags = FOLL_TOUCH;
  1632. /*
  1633. * We want to touch writable mappings with a write fault in order
  1634. * to break COW, except for shared mappings because these don't COW
  1635. * and we would not want to dirty them for nothing.
  1636. *
  1637. * Otherwise, do a read fault, and use FOLL_FORCE in case it's not
  1638. * readable (ie write-only or executable).
  1639. */
  1640. if ((vma->vm_flags & (VM_WRITE | VM_SHARED)) == VM_WRITE)
  1641. gup_flags |= FOLL_WRITE;
  1642. else
  1643. gup_flags |= FOLL_FORCE;
  1644. if (locked)
  1645. gup_flags |= FOLL_UNLOCKABLE;
  1646. /*
  1647. * We made sure addr is within a VMA, so the following will
  1648. * not result in a stack expansion that recurses back here.
  1649. */
  1650. ret = __get_user_pages(mm, start, nr_pages, gup_flags,
  1651. NULL, locked ? locked : &local_locked);
  1652. lru_add_drain();
  1653. return ret;
  1654. }
  1655. /*
  1656. * faultin_page_range() - populate (prefault) page tables inside the
  1657. * given range readable/writable
  1658. *
  1659. * This takes care of mlocking the pages, too, if VM_LOCKED is set.
  1660. *
  1661. * @mm: the mm to populate page tables in
  1662. * @start: start address
  1663. * @end: end address
  1664. * @write: whether to prefault readable or writable
  1665. * @locked: whether the mmap_lock is still held
  1666. *
  1667. * Returns either number of processed pages in the MM, or a negative error
  1668. * code on error (see __get_user_pages()). Note that this function reports
  1669. * errors related to VMAs, such as incompatible mappings, as expected by
  1670. * MADV_POPULATE_(READ|WRITE).
  1671. *
  1672. * The range must be page-aligned.
  1673. *
  1674. * mm->mmap_lock must be held. If it's released, *@locked will be set to 0.
  1675. */
  1676. long faultin_page_range(struct mm_struct *mm, unsigned long start,
  1677. unsigned long end, bool write, int *locked)
  1678. {
  1679. unsigned long nr_pages = (end - start) / PAGE_SIZE;
  1680. int gup_flags;
  1681. long ret;
  1682. VM_WARN_ON_ONCE(!PAGE_ALIGNED(start));
  1683. VM_WARN_ON_ONCE(!PAGE_ALIGNED(end));
  1684. mmap_assert_locked(mm);
  1685. /*
  1686. * FOLL_TOUCH: Mark page accessed and thereby young; will also mark
  1687. * the page dirty with FOLL_WRITE -- which doesn't make a
  1688. * difference with !FOLL_FORCE, because the page is writable
  1689. * in the page table.
  1690. * FOLL_HWPOISON: Return -EHWPOISON instead of -EFAULT when we hit
  1691. * a poisoned page.
  1692. * !FOLL_FORCE: Require proper access permissions.
  1693. */
  1694. gup_flags = FOLL_TOUCH | FOLL_HWPOISON | FOLL_UNLOCKABLE |
  1695. FOLL_MADV_POPULATE;
  1696. if (write)
  1697. gup_flags |= FOLL_WRITE;
  1698. ret = __get_user_pages_locked(mm, start, nr_pages, NULL, locked,
  1699. gup_flags);
  1700. lru_add_drain();
  1701. return ret;
  1702. }
  1703. /*
  1704. * __mm_populate - populate and/or mlock pages within a range of address space.
  1705. *
  1706. * This is used to implement mlock() and the MAP_POPULATE / MAP_LOCKED mmap
  1707. * flags. VMAs must be already marked with the desired vm_flags, and
  1708. * mmap_lock must not be held.
  1709. */
  1710. int __mm_populate(unsigned long start, unsigned long len, int ignore_errors)
  1711. {
  1712. struct mm_struct *mm = current->mm;
  1713. unsigned long end, nstart, nend;
  1714. struct vm_area_struct *vma = NULL;
  1715. int locked = 0;
  1716. long ret = 0;
  1717. end = start + len;
  1718. for (nstart = start; nstart < end; nstart = nend) {
  1719. /*
  1720. * We want to fault in pages for [nstart; end) address range.
  1721. * Find first corresponding VMA.
  1722. */
  1723. if (!locked) {
  1724. locked = 1;
  1725. mmap_read_lock(mm);
  1726. vma = find_vma_intersection(mm, nstart, end);
  1727. } else if (nstart >= vma->vm_end)
  1728. vma = find_vma_intersection(mm, vma->vm_end, end);
  1729. if (!vma)
  1730. break;
  1731. /*
  1732. * Set [nstart; nend) to intersection of desired address
  1733. * range with the first VMA. Also, skip undesirable VMA types.
  1734. */
  1735. nend = min(end, vma->vm_end);
  1736. if (vma->vm_flags & (VM_IO | VM_PFNMAP))
  1737. continue;
  1738. if (nstart < vma->vm_start)
  1739. nstart = vma->vm_start;
  1740. /*
  1741. * Now fault in a range of pages. populate_vma_page_range()
  1742. * double checks the vma flags, so that it won't mlock pages
  1743. * if the vma was already munlocked.
  1744. */
  1745. ret = populate_vma_page_range(vma, nstart, nend, &locked);
  1746. if (ret < 0) {
  1747. if (ignore_errors) {
  1748. ret = 0;
  1749. continue; /* continue at next VMA */
  1750. }
  1751. break;
  1752. }
  1753. nend = nstart + ret * PAGE_SIZE;
  1754. ret = 0;
  1755. }
  1756. if (locked)
  1757. mmap_read_unlock(mm);
  1758. return ret; /* 0 or negative error code */
  1759. }
  1760. #else /* CONFIG_MMU */
  1761. static long __get_user_pages_locked(struct mm_struct *mm, unsigned long start,
  1762. unsigned long nr_pages, struct page **pages,
  1763. int *locked, unsigned int foll_flags)
  1764. {
  1765. struct vm_area_struct *vma;
  1766. bool must_unlock = false;
  1767. vm_flags_t vm_flags;
  1768. long i;
  1769. if (!nr_pages)
  1770. return 0;
  1771. /*
  1772. * The internal caller expects GUP to manage the lock internally and the
  1773. * lock must be released when this returns.
  1774. */
  1775. if (!*locked) {
  1776. if (mmap_read_lock_killable(mm))
  1777. return -EAGAIN;
  1778. must_unlock = true;
  1779. *locked = 1;
  1780. }
  1781. /* calculate required read or write permissions.
  1782. * If FOLL_FORCE is set, we only require the "MAY" flags.
  1783. */
  1784. vm_flags = (foll_flags & FOLL_WRITE) ?
  1785. (VM_WRITE | VM_MAYWRITE) : (VM_READ | VM_MAYREAD);
  1786. vm_flags &= (foll_flags & FOLL_FORCE) ?
  1787. (VM_MAYREAD | VM_MAYWRITE) : (VM_READ | VM_WRITE);
  1788. for (i = 0; i < nr_pages; i++) {
  1789. vma = find_vma(mm, start);
  1790. if (!vma)
  1791. break;
  1792. /* protect what we can, including chardevs */
  1793. if ((vma->vm_flags & (VM_IO | VM_PFNMAP)) ||
  1794. !(vm_flags & vma->vm_flags))
  1795. break;
  1796. if (pages) {
  1797. pages[i] = virt_to_page((void *)start);
  1798. if (pages[i])
  1799. get_page(pages[i]);
  1800. }
  1801. start = (start + PAGE_SIZE) & PAGE_MASK;
  1802. }
  1803. if (must_unlock && *locked) {
  1804. mmap_read_unlock(mm);
  1805. *locked = 0;
  1806. }
  1807. return i ? : -EFAULT;
  1808. }
  1809. #endif /* !CONFIG_MMU */
  1810. /**
  1811. * fault_in_writeable - fault in userspace address range for writing
  1812. * @uaddr: start of address range
  1813. * @size: size of address range
  1814. *
  1815. * Returns the number of bytes not faulted in (like copy_to_user() and
  1816. * copy_from_user()).
  1817. */
  1818. size_t fault_in_writeable(char __user *uaddr, size_t size)
  1819. {
  1820. const unsigned long start = (unsigned long)uaddr;
  1821. const unsigned long end = start + size;
  1822. unsigned long cur;
  1823. if (unlikely(size == 0))
  1824. return 0;
  1825. if (!user_write_access_begin(uaddr, size))
  1826. return size;
  1827. /* Stop once we overflow to 0. */
  1828. for (cur = start; cur && cur < end; cur = PAGE_ALIGN_DOWN(cur + PAGE_SIZE))
  1829. unsafe_put_user(0, (char __user *)cur, out);
  1830. out:
  1831. user_write_access_end();
  1832. if (size > cur - start)
  1833. return size - (cur - start);
  1834. return 0;
  1835. }
  1836. EXPORT_SYMBOL(fault_in_writeable);
  1837. /**
  1838. * fault_in_subpage_writeable - fault in an address range for writing
  1839. * @uaddr: start of address range
  1840. * @size: size of address range
  1841. *
  1842. * Fault in a user address range for writing while checking for permissions at
  1843. * sub-page granularity (e.g. arm64 MTE). This function should be used when
  1844. * the caller cannot guarantee forward progress of a copy_to_user() loop.
  1845. *
  1846. * Returns the number of bytes not faulted in (like copy_to_user() and
  1847. * copy_from_user()).
  1848. */
  1849. size_t fault_in_subpage_writeable(char __user *uaddr, size_t size)
  1850. {
  1851. size_t faulted_in;
  1852. /*
  1853. * Attempt faulting in at page granularity first for page table
  1854. * permission checking. The arch-specific probe_subpage_writeable()
  1855. * functions may not check for this.
  1856. */
  1857. faulted_in = size - fault_in_writeable(uaddr, size);
  1858. if (faulted_in)
  1859. faulted_in -= probe_subpage_writeable(uaddr, faulted_in);
  1860. return size - faulted_in;
  1861. }
  1862. EXPORT_SYMBOL(fault_in_subpage_writeable);
  1863. /*
  1864. * fault_in_safe_writeable - fault in an address range for writing
  1865. * @uaddr: start of address range
  1866. * @size: length of address range
  1867. *
  1868. * Faults in an address range for writing. This is primarily useful when we
  1869. * already know that some or all of the pages in the address range aren't in
  1870. * memory.
  1871. *
  1872. * Unlike fault_in_writeable(), this function is non-destructive.
  1873. *
  1874. * Note that we don't pin or otherwise hold the pages referenced that we fault
  1875. * in. There's no guarantee that they'll stay in memory for any duration of
  1876. * time.
  1877. *
  1878. * Returns the number of bytes not faulted in, like copy_to_user() and
  1879. * copy_from_user().
  1880. */
  1881. size_t fault_in_safe_writeable(const char __user *uaddr, size_t size)
  1882. {
  1883. const unsigned long start = (unsigned long)uaddr;
  1884. const unsigned long end = start + size;
  1885. unsigned long cur;
  1886. struct mm_struct *mm = current->mm;
  1887. bool unlocked = false;
  1888. if (unlikely(size == 0))
  1889. return 0;
  1890. mmap_read_lock(mm);
  1891. /* Stop once we overflow to 0. */
  1892. for (cur = start; cur && cur < end; cur = PAGE_ALIGN_DOWN(cur + PAGE_SIZE))
  1893. if (fixup_user_fault(mm, cur, FAULT_FLAG_WRITE, &unlocked))
  1894. break;
  1895. mmap_read_unlock(mm);
  1896. if (size > cur - start)
  1897. return size - (cur - start);
  1898. return 0;
  1899. }
  1900. EXPORT_SYMBOL(fault_in_safe_writeable);
  1901. /**
  1902. * fault_in_readable - fault in userspace address range for reading
  1903. * @uaddr: start of user address range
  1904. * @size: size of user address range
  1905. *
  1906. * Returns the number of bytes not faulted in (like copy_to_user() and
  1907. * copy_from_user()).
  1908. */
  1909. size_t fault_in_readable(const char __user *uaddr, size_t size)
  1910. {
  1911. const unsigned long start = (unsigned long)uaddr;
  1912. const unsigned long end = start + size;
  1913. unsigned long cur;
  1914. volatile char c;
  1915. if (unlikely(size == 0))
  1916. return 0;
  1917. if (!user_read_access_begin(uaddr, size))
  1918. return size;
  1919. /* Stop once we overflow to 0. */
  1920. for (cur = start; cur && cur < end; cur = PAGE_ALIGN_DOWN(cur + PAGE_SIZE))
  1921. unsafe_get_user(c, (const char __user *)cur, out);
  1922. out:
  1923. user_read_access_end();
  1924. (void)c;
  1925. if (size > cur - start)
  1926. return size - (cur - start);
  1927. return 0;
  1928. }
  1929. EXPORT_SYMBOL(fault_in_readable);
  1930. /**
  1931. * get_dump_page() - pin user page in memory while writing it to core dump
  1932. * @addr: user address
  1933. * @locked: a pointer to an int denoting whether the mmap sem is held
  1934. *
  1935. * Returns struct page pointer of user page pinned for dump,
  1936. * to be freed afterwards by put_page().
  1937. *
  1938. * Returns NULL on any kind of failure - a hole must then be inserted into
  1939. * the corefile, to preserve alignment with its headers; and also returns
  1940. * NULL wherever the ZERO_PAGE, or an anonymous pte_none, has been found -
  1941. * allowing a hole to be left in the corefile to save disk space.
  1942. *
  1943. * Called without mmap_lock (takes and releases the mmap_lock by itself).
  1944. */
  1945. #ifdef CONFIG_ELF_CORE
  1946. struct page *get_dump_page(unsigned long addr, int *locked)
  1947. {
  1948. struct page *page;
  1949. int ret;
  1950. ret = __get_user_pages_locked(current->mm, addr, 1, &page, locked,
  1951. FOLL_FORCE | FOLL_DUMP | FOLL_GET);
  1952. return (ret == 1) ? page : NULL;
  1953. }
  1954. #endif /* CONFIG_ELF_CORE */
  1955. #ifdef CONFIG_MIGRATION
  1956. /*
  1957. * An array of either pages or folios ("pofs"). Although it may seem tempting to
  1958. * avoid this complication, by simply interpreting a list of folios as a list of
  1959. * pages, that approach won't work in the longer term, because eventually the
  1960. * layouts of struct page and struct folio will become completely different.
  1961. * Furthermore, this pof approach avoids excessive page_folio() calls.
  1962. */
  1963. struct pages_or_folios {
  1964. union {
  1965. struct page **pages;
  1966. struct folio **folios;
  1967. void **entries;
  1968. };
  1969. bool has_folios;
  1970. long nr_entries;
  1971. };
  1972. static struct folio *pofs_get_folio(struct pages_or_folios *pofs, long i)
  1973. {
  1974. if (pofs->has_folios)
  1975. return pofs->folios[i];
  1976. return page_folio(pofs->pages[i]);
  1977. }
  1978. static void pofs_clear_entry(struct pages_or_folios *pofs, long i)
  1979. {
  1980. pofs->entries[i] = NULL;
  1981. }
  1982. static void pofs_unpin(struct pages_or_folios *pofs)
  1983. {
  1984. if (pofs->has_folios)
  1985. unpin_folios(pofs->folios, pofs->nr_entries);
  1986. else
  1987. unpin_user_pages(pofs->pages, pofs->nr_entries);
  1988. }
  1989. static struct folio *pofs_next_folio(struct folio *folio,
  1990. struct pages_or_folios *pofs, long *index_ptr)
  1991. {
  1992. long i = *index_ptr + 1;
  1993. if (!pofs->has_folios && folio_test_large(folio)) {
  1994. const unsigned long start_pfn = folio_pfn(folio);
  1995. const unsigned long end_pfn = start_pfn + folio_nr_pages(folio);
  1996. for (; i < pofs->nr_entries; i++) {
  1997. unsigned long pfn = page_to_pfn(pofs->pages[i]);
  1998. /* Is this page part of this folio? */
  1999. if (pfn < start_pfn || pfn >= end_pfn)
  2000. break;
  2001. }
  2002. }
  2003. if (unlikely(i == pofs->nr_entries))
  2004. return NULL;
  2005. *index_ptr = i;
  2006. return pofs_get_folio(pofs, i);
  2007. }
  2008. /*
  2009. * Returns the number of collected folios. Return value is always >= 0.
  2010. */
  2011. static unsigned long collect_longterm_unpinnable_folios(
  2012. struct list_head *movable_folio_list,
  2013. struct pages_or_folios *pofs)
  2014. {
  2015. unsigned long collected = 0;
  2016. struct folio *folio;
  2017. int drained = 0;
  2018. long i = 0;
  2019. for (folio = pofs_get_folio(pofs, i); folio;
  2020. folio = pofs_next_folio(folio, pofs, &i)) {
  2021. if (folio_is_longterm_pinnable(folio))
  2022. continue;
  2023. collected++;
  2024. if (folio_is_device_coherent(folio))
  2025. continue;
  2026. if (folio_test_hugetlb(folio)) {
  2027. folio_isolate_hugetlb(folio, movable_folio_list);
  2028. continue;
  2029. }
  2030. if (drained == 0 && folio_may_be_lru_cached(folio) &&
  2031. folio_ref_count(folio) !=
  2032. folio_expected_ref_count(folio) + 1) {
  2033. lru_add_drain();
  2034. drained = 1;
  2035. }
  2036. if (drained == 1 && folio_may_be_lru_cached(folio) &&
  2037. folio_ref_count(folio) !=
  2038. folio_expected_ref_count(folio) + 1) {
  2039. lru_add_drain_all();
  2040. drained = 2;
  2041. }
  2042. if (!folio_isolate_lru(folio))
  2043. continue;
  2044. list_add_tail(&folio->lru, movable_folio_list);
  2045. node_stat_mod_folio(folio,
  2046. NR_ISOLATED_ANON + folio_is_file_lru(folio),
  2047. folio_nr_pages(folio));
  2048. }
  2049. return collected;
  2050. }
  2051. /*
  2052. * Unpins all folios and migrates device coherent folios and movable_folio_list.
  2053. * Returns -EAGAIN if all folios were successfully migrated or -errno for
  2054. * failure (or partial success).
  2055. */
  2056. static int
  2057. migrate_longterm_unpinnable_folios(struct list_head *movable_folio_list,
  2058. struct pages_or_folios *pofs)
  2059. {
  2060. int ret;
  2061. unsigned long i;
  2062. for (i = 0; i < pofs->nr_entries; i++) {
  2063. struct folio *folio = pofs_get_folio(pofs, i);
  2064. if (folio_is_device_coherent(folio)) {
  2065. /*
  2066. * Migration will fail if the folio is pinned, so
  2067. * convert the pin on the source folio to a normal
  2068. * reference.
  2069. */
  2070. pofs_clear_entry(pofs, i);
  2071. folio_get(folio);
  2072. gup_put_folio(folio, 1, FOLL_PIN);
  2073. if (migrate_device_coherent_folio(folio)) {
  2074. ret = -EBUSY;
  2075. goto err;
  2076. }
  2077. continue;
  2078. }
  2079. /*
  2080. * We can't migrate folios with unexpected references, so drop
  2081. * the reference obtained by __get_user_pages_locked().
  2082. * Migrating folios have been added to movable_folio_list after
  2083. * calling folio_isolate_lru() which takes a reference so the
  2084. * folio won't be freed if it's migrating.
  2085. */
  2086. unpin_folio(folio);
  2087. pofs_clear_entry(pofs, i);
  2088. }
  2089. if (!list_empty(movable_folio_list)) {
  2090. struct migration_target_control mtc = {
  2091. .nid = NUMA_NO_NODE,
  2092. .gfp_mask = GFP_USER | __GFP_NOWARN,
  2093. .reason = MR_LONGTERM_PIN,
  2094. };
  2095. if (migrate_pages(movable_folio_list, alloc_migration_target,
  2096. NULL, (unsigned long)&mtc, MIGRATE_SYNC,
  2097. MR_LONGTERM_PIN, NULL)) {
  2098. ret = -ENOMEM;
  2099. goto err;
  2100. }
  2101. }
  2102. putback_movable_pages(movable_folio_list);
  2103. return -EAGAIN;
  2104. err:
  2105. pofs_unpin(pofs);
  2106. putback_movable_pages(movable_folio_list);
  2107. return ret;
  2108. }
  2109. static long
  2110. check_and_migrate_movable_pages_or_folios(struct pages_or_folios *pofs)
  2111. {
  2112. LIST_HEAD(movable_folio_list);
  2113. unsigned long collected;
  2114. collected = collect_longterm_unpinnable_folios(&movable_folio_list,
  2115. pofs);
  2116. if (!collected)
  2117. return 0;
  2118. return migrate_longterm_unpinnable_folios(&movable_folio_list, pofs);
  2119. }
  2120. /*
  2121. * Check whether all folios are *allowed* to be pinned indefinitely (long term).
  2122. * Rather confusingly, all folios in the range are required to be pinned via
  2123. * FOLL_PIN, before calling this routine.
  2124. *
  2125. * Return values:
  2126. *
  2127. * 0: if everything is OK and all folios in the range are allowed to be pinned,
  2128. * then this routine leaves all folios pinned and returns zero for success.
  2129. *
  2130. * -EAGAIN: if any folios in the range are not allowed to be pinned, then this
  2131. * routine will migrate those folios away, unpin all the folios in the range. If
  2132. * migration of the entire set of folios succeeds, then -EAGAIN is returned. The
  2133. * caller should re-pin the entire range with FOLL_PIN and then call this
  2134. * routine again.
  2135. *
  2136. * -ENOMEM, or any other -errno: if an error *other* than -EAGAIN occurs, this
  2137. * indicates a migration failure. The caller should give up, and propagate the
  2138. * error back up the call stack. The caller does not need to unpin any folios in
  2139. * that case, because this routine will do the unpinning.
  2140. */
  2141. static long check_and_migrate_movable_folios(unsigned long nr_folios,
  2142. struct folio **folios)
  2143. {
  2144. struct pages_or_folios pofs = {
  2145. .folios = folios,
  2146. .has_folios = true,
  2147. .nr_entries = nr_folios,
  2148. };
  2149. return check_and_migrate_movable_pages_or_folios(&pofs);
  2150. }
  2151. /*
  2152. * Return values and behavior are the same as those for
  2153. * check_and_migrate_movable_folios().
  2154. */
  2155. static long check_and_migrate_movable_pages(unsigned long nr_pages,
  2156. struct page **pages)
  2157. {
  2158. struct pages_or_folios pofs = {
  2159. .pages = pages,
  2160. .has_folios = false,
  2161. .nr_entries = nr_pages,
  2162. };
  2163. return check_and_migrate_movable_pages_or_folios(&pofs);
  2164. }
  2165. #else
  2166. static long check_and_migrate_movable_pages(unsigned long nr_pages,
  2167. struct page **pages)
  2168. {
  2169. return 0;
  2170. }
  2171. static long check_and_migrate_movable_folios(unsigned long nr_folios,
  2172. struct folio **folios)
  2173. {
  2174. return 0;
  2175. }
  2176. #endif /* CONFIG_MIGRATION */
  2177. /*
  2178. * __gup_longterm_locked() is a wrapper for __get_user_pages_locked which
  2179. * allows us to process the FOLL_LONGTERM flag.
  2180. */
  2181. static long __gup_longterm_locked(struct mm_struct *mm,
  2182. unsigned long start,
  2183. unsigned long nr_pages,
  2184. struct page **pages,
  2185. int *locked,
  2186. unsigned int gup_flags)
  2187. {
  2188. unsigned int flags;
  2189. long rc, nr_pinned_pages;
  2190. if (!(gup_flags & FOLL_LONGTERM))
  2191. return __get_user_pages_locked(mm, start, nr_pages, pages,
  2192. locked, gup_flags);
  2193. flags = memalloc_pin_save();
  2194. do {
  2195. nr_pinned_pages = __get_user_pages_locked(mm, start, nr_pages,
  2196. pages, locked,
  2197. gup_flags);
  2198. if (nr_pinned_pages <= 0) {
  2199. rc = nr_pinned_pages;
  2200. break;
  2201. }
  2202. /* FOLL_LONGTERM implies FOLL_PIN */
  2203. rc = check_and_migrate_movable_pages(nr_pinned_pages, pages);
  2204. } while (rc == -EAGAIN);
  2205. memalloc_pin_restore(flags);
  2206. return rc ? rc : nr_pinned_pages;
  2207. }
  2208. /*
  2209. * Check that the given flags are valid for the exported gup/pup interface, and
  2210. * update them with the required flags that the caller must have set.
  2211. */
  2212. static bool is_valid_gup_args(struct page **pages, int *locked,
  2213. unsigned int *gup_flags_p, unsigned int to_set)
  2214. {
  2215. unsigned int gup_flags = *gup_flags_p;
  2216. /*
  2217. * These flags not allowed to be specified externally to the gup
  2218. * interfaces:
  2219. * - FOLL_TOUCH/FOLL_PIN/FOLL_TRIED/FOLL_FAST_ONLY are internal only
  2220. * - FOLL_REMOTE is internal only, set in (get|pin)_user_pages_remote()
  2221. * - FOLL_UNLOCKABLE is internal only and used if locked is !NULL
  2222. */
  2223. if (WARN_ON_ONCE(gup_flags & INTERNAL_GUP_FLAGS))
  2224. return false;
  2225. gup_flags |= to_set;
  2226. if (locked) {
  2227. /* At the external interface locked must be set */
  2228. if (WARN_ON_ONCE(*locked != 1))
  2229. return false;
  2230. gup_flags |= FOLL_UNLOCKABLE;
  2231. }
  2232. /* FOLL_GET and FOLL_PIN are mutually exclusive. */
  2233. if (WARN_ON_ONCE((gup_flags & (FOLL_PIN | FOLL_GET)) ==
  2234. (FOLL_PIN | FOLL_GET)))
  2235. return false;
  2236. /* LONGTERM can only be specified when pinning */
  2237. if (WARN_ON_ONCE(!(gup_flags & FOLL_PIN) && (gup_flags & FOLL_LONGTERM)))
  2238. return false;
  2239. /* Pages input must be given if using GET/PIN */
  2240. if (WARN_ON_ONCE((gup_flags & (FOLL_GET | FOLL_PIN)) && !pages))
  2241. return false;
  2242. /* We want to allow the pgmap to be hot-unplugged at all times */
  2243. if (WARN_ON_ONCE((gup_flags & FOLL_LONGTERM) &&
  2244. (gup_flags & FOLL_PCI_P2PDMA)))
  2245. return false;
  2246. *gup_flags_p = gup_flags;
  2247. return true;
  2248. }
  2249. #ifdef CONFIG_MMU
  2250. /**
  2251. * get_user_pages_remote() - pin user pages in memory
  2252. * @mm: mm_struct of target mm
  2253. * @start: starting user address
  2254. * @nr_pages: number of pages from start to pin
  2255. * @gup_flags: flags modifying lookup behaviour
  2256. * @pages: array that receives pointers to the pages pinned.
  2257. * Should be at least nr_pages long. Or NULL, if caller
  2258. * only intends to ensure the pages are faulted in.
  2259. * @locked: pointer to lock flag indicating whether lock is held and
  2260. * subsequently whether VM_FAULT_RETRY functionality can be
  2261. * utilised. Lock must initially be held.
  2262. *
  2263. * Returns either number of pages pinned (which may be less than the
  2264. * number requested), or an error. Details about the return value:
  2265. *
  2266. * -- If nr_pages is 0, returns 0.
  2267. * -- If nr_pages is >0, but no pages were pinned, returns -errno.
  2268. * -- If nr_pages is >0, and some pages were pinned, returns the number of
  2269. * pages pinned. Again, this may be less than nr_pages.
  2270. *
  2271. * The caller is responsible for releasing returned @pages, via put_page().
  2272. *
  2273. * Must be called with mmap_lock held for read or write.
  2274. *
  2275. * get_user_pages_remote walks a process's page tables and takes a reference
  2276. * to each struct page that each user address corresponds to at a given
  2277. * instant. That is, it takes the page that would be accessed if a user
  2278. * thread accesses the given user virtual address at that instant.
  2279. *
  2280. * This does not guarantee that the page exists in the user mappings when
  2281. * get_user_pages_remote returns, and there may even be a completely different
  2282. * page there in some cases (eg. if mmapped pagecache has been invalidated
  2283. * and subsequently re-faulted). However it does guarantee that the page
  2284. * won't be freed completely. And mostly callers simply care that the page
  2285. * contains data that was valid *at some point in time*. Typically, an IO
  2286. * or similar operation cannot guarantee anything stronger anyway because
  2287. * locks can't be held over the syscall boundary.
  2288. *
  2289. * If gup_flags & FOLL_WRITE == 0, the page must not be written to. If the page
  2290. * is written to, set_page_dirty (or set_page_dirty_lock, as appropriate) must
  2291. * be called after the page is finished with, and before put_page is called.
  2292. *
  2293. * get_user_pages_remote is typically used for fewer-copy IO operations,
  2294. * to get a handle on the memory by some means other than accesses
  2295. * via the user virtual addresses. The pages may be submitted for
  2296. * DMA to devices or accessed via their kernel linear mapping (via the
  2297. * kmap APIs). Care should be taken to use the correct cache flushing APIs.
  2298. *
  2299. * See also get_user_pages_fast, for performance critical applications.
  2300. *
  2301. * get_user_pages_remote should be phased out in favor of
  2302. * get_user_pages_locked|unlocked or get_user_pages_fast. Nothing
  2303. * should use get_user_pages_remote because it cannot pass
  2304. * FAULT_FLAG_ALLOW_RETRY to handle_mm_fault.
  2305. */
  2306. long get_user_pages_remote(struct mm_struct *mm,
  2307. unsigned long start, unsigned long nr_pages,
  2308. unsigned int gup_flags, struct page **pages,
  2309. int *locked)
  2310. {
  2311. int local_locked = 1;
  2312. if (!is_valid_gup_args(pages, locked, &gup_flags,
  2313. FOLL_TOUCH | FOLL_REMOTE))
  2314. return -EINVAL;
  2315. return __get_user_pages_locked(mm, start, nr_pages, pages,
  2316. locked ? locked : &local_locked,
  2317. gup_flags);
  2318. }
  2319. EXPORT_SYMBOL(get_user_pages_remote);
  2320. #else /* CONFIG_MMU */
  2321. long get_user_pages_remote(struct mm_struct *mm,
  2322. unsigned long start, unsigned long nr_pages,
  2323. unsigned int gup_flags, struct page **pages,
  2324. int *locked)
  2325. {
  2326. return 0;
  2327. }
  2328. #endif /* !CONFIG_MMU */
  2329. /**
  2330. * get_user_pages() - pin user pages in memory
  2331. * @start: starting user address
  2332. * @nr_pages: number of pages from start to pin
  2333. * @gup_flags: flags modifying lookup behaviour
  2334. * @pages: array that receives pointers to the pages pinned.
  2335. * Should be at least nr_pages long. Or NULL, if caller
  2336. * only intends to ensure the pages are faulted in.
  2337. *
  2338. * This is the same as get_user_pages_remote(), just with a less-flexible
  2339. * calling convention where we assume that the mm being operated on belongs to
  2340. * the current task, and doesn't allow passing of a locked parameter. We also
  2341. * obviously don't pass FOLL_REMOTE in here.
  2342. */
  2343. long get_user_pages(unsigned long start, unsigned long nr_pages,
  2344. unsigned int gup_flags, struct page **pages)
  2345. {
  2346. int locked = 1;
  2347. if (!is_valid_gup_args(pages, NULL, &gup_flags, FOLL_TOUCH))
  2348. return -EINVAL;
  2349. return __get_user_pages_locked(current->mm, start, nr_pages, pages,
  2350. &locked, gup_flags);
  2351. }
  2352. EXPORT_SYMBOL(get_user_pages);
  2353. /*
  2354. * get_user_pages_unlocked() is suitable to replace the form:
  2355. *
  2356. * mmap_read_lock(mm);
  2357. * get_user_pages(mm, ..., pages, NULL);
  2358. * mmap_read_unlock(mm);
  2359. *
  2360. * with:
  2361. *
  2362. * get_user_pages_unlocked(mm, ..., pages);
  2363. *
  2364. * It is functionally equivalent to get_user_pages_fast so
  2365. * get_user_pages_fast should be used instead if specific gup_flags
  2366. * (e.g. FOLL_FORCE) are not required.
  2367. */
  2368. long get_user_pages_unlocked(unsigned long start, unsigned long nr_pages,
  2369. struct page **pages, unsigned int gup_flags)
  2370. {
  2371. int locked = 0;
  2372. if (!is_valid_gup_args(pages, NULL, &gup_flags,
  2373. FOLL_TOUCH | FOLL_UNLOCKABLE))
  2374. return -EINVAL;
  2375. return __get_user_pages_locked(current->mm, start, nr_pages, pages,
  2376. &locked, gup_flags);
  2377. }
  2378. EXPORT_SYMBOL(get_user_pages_unlocked);
  2379. /*
  2380. * GUP-fast
  2381. *
  2382. * get_user_pages_fast attempts to pin user pages by walking the page
  2383. * tables directly and avoids taking locks. Thus the walker needs to be
  2384. * protected from page table pages being freed from under it, and should
  2385. * block any THP splits.
  2386. *
  2387. * One way to achieve this is to have the walker disable interrupts, and
  2388. * rely on IPIs from the TLB flushing code blocking before the page table
  2389. * pages are freed. This is unsuitable for architectures that do not need
  2390. * to broadcast an IPI when invalidating TLBs.
  2391. *
  2392. * Another way to achieve this is to batch up page table containing pages
  2393. * belonging to more than one mm_user, then rcu_sched a callback to free those
  2394. * pages. Disabling interrupts will allow the gup_fast() walker to both block
  2395. * the rcu_sched callback, and an IPI that we broadcast for splitting THPs
  2396. * (which is a relatively rare event). The code below adopts this strategy.
  2397. *
  2398. * Before activating this code, please be aware that the following assumptions
  2399. * are currently made:
  2400. *
  2401. * *) Either MMU_GATHER_RCU_TABLE_FREE is enabled, and tlb_remove_table() is used to
  2402. * free pages containing page tables or TLB flushing requires IPI broadcast.
  2403. *
  2404. * *) ptes can be read atomically by the architecture.
  2405. *
  2406. * *) valid user addresses are below TASK_MAX_SIZE
  2407. *
  2408. * The last two assumptions can be relaxed by the addition of helper functions.
  2409. *
  2410. * This code is based heavily on the PowerPC implementation by Nick Piggin.
  2411. */
  2412. #ifdef CONFIG_HAVE_GUP_FAST
  2413. /*
  2414. * Used in the GUP-fast path to determine whether GUP is permitted to work on
  2415. * a specific folio.
  2416. *
  2417. * This call assumes the caller has pinned the folio, that the lowest page table
  2418. * level still points to this folio, and that interrupts have been disabled.
  2419. *
  2420. * GUP-fast must reject all secretmem folios.
  2421. *
  2422. * Writing to pinned file-backed dirty tracked folios is inherently problematic
  2423. * (see comment describing the writable_file_mapping_allowed() function). We
  2424. * therefore try to avoid the most egregious case of a long-term mapping doing
  2425. * so.
  2426. *
  2427. * This function cannot be as thorough as that one as the VMA is not available
  2428. * in the fast path, so instead we whitelist known good cases and if in doubt,
  2429. * fall back to the slow path.
  2430. */
  2431. static bool gup_fast_folio_allowed(struct folio *folio, unsigned int flags)
  2432. {
  2433. bool reject_file_backed = false;
  2434. struct address_space *mapping;
  2435. bool check_secretmem = false;
  2436. unsigned long mapping_flags;
  2437. /*
  2438. * If we aren't pinning then no problematic write can occur. A long term
  2439. * pin is the most egregious case so this is the one we disallow.
  2440. */
  2441. if ((flags & (FOLL_PIN | FOLL_LONGTERM | FOLL_WRITE)) ==
  2442. (FOLL_PIN | FOLL_LONGTERM | FOLL_WRITE))
  2443. reject_file_backed = true;
  2444. /* We hold a folio reference, so we can safely access folio fields. */
  2445. /* secretmem folios are always order-0 folios. */
  2446. if (IS_ENABLED(CONFIG_SECRETMEM) && !folio_test_large(folio))
  2447. check_secretmem = true;
  2448. if (!reject_file_backed && !check_secretmem)
  2449. return true;
  2450. if (WARN_ON_ONCE(folio_test_slab(folio)))
  2451. return false;
  2452. /* hugetlb neither requires dirty-tracking nor can be secretmem. */
  2453. if (folio_test_hugetlb(folio))
  2454. return true;
  2455. /*
  2456. * GUP-fast disables IRQs. When IRQS are disabled, RCU grace periods
  2457. * cannot proceed, which means no actions performed under RCU can
  2458. * proceed either.
  2459. *
  2460. * inodes and thus their mappings are freed under RCU, which means the
  2461. * mapping cannot be freed beneath us and thus we can safely dereference
  2462. * it.
  2463. */
  2464. lockdep_assert_irqs_disabled();
  2465. /*
  2466. * However, there may be operations which _alter_ the mapping, so ensure
  2467. * we read it once and only once.
  2468. */
  2469. mapping = READ_ONCE(folio->mapping);
  2470. /*
  2471. * The mapping may have been truncated, in any case we cannot determine
  2472. * if this mapping is safe - fall back to slow path to determine how to
  2473. * proceed.
  2474. */
  2475. if (!mapping)
  2476. return false;
  2477. /* Anonymous folios pose no problem. */
  2478. mapping_flags = (unsigned long)mapping & FOLIO_MAPPING_FLAGS;
  2479. if (mapping_flags)
  2480. return mapping_flags & FOLIO_MAPPING_ANON;
  2481. /*
  2482. * At this point, we know the mapping is non-null and points to an
  2483. * address_space object.
  2484. */
  2485. if (check_secretmem && secretmem_mapping(mapping))
  2486. return false;
  2487. /* The only remaining allowed file system is shmem. */
  2488. return !reject_file_backed || shmem_mapping(mapping);
  2489. }
  2490. #ifdef CONFIG_ARCH_HAS_PTE_SPECIAL
  2491. /*
  2492. * GUP-fast relies on pte change detection to avoid concurrent pgtable
  2493. * operations.
  2494. *
  2495. * To pin the page, GUP-fast needs to do below in order:
  2496. * (1) pin the page (by prefetching pte), then (2) check pte not changed.
  2497. *
  2498. * For the rest of pgtable operations where pgtable updates can be racy
  2499. * with GUP-fast, we need to do (1) clear pte, then (2) check whether page
  2500. * is pinned.
  2501. *
  2502. * Above will work for all pte-level operations, including THP split.
  2503. *
  2504. * For THP collapse, it's a bit more complicated because GUP-fast may be
  2505. * walking a pgtable page that is being freed (pte is still valid but pmd
  2506. * can be cleared already). To avoid race in such condition, we need to
  2507. * also check pmd here to make sure pmd doesn't change (corresponds to
  2508. * pmdp_collapse_flush() in the THP collapse code path).
  2509. */
  2510. static int gup_fast_pte_range(pmd_t pmd, pmd_t *pmdp, unsigned long addr,
  2511. unsigned long end, unsigned int flags, struct page **pages,
  2512. int *nr)
  2513. {
  2514. int ret = 0;
  2515. pte_t *ptep, *ptem;
  2516. ptem = ptep = pte_offset_map(&pmd, addr);
  2517. if (!ptep)
  2518. return 0;
  2519. do {
  2520. pte_t pte = ptep_get_lockless(ptep);
  2521. struct page *page;
  2522. struct folio *folio;
  2523. /*
  2524. * Always fallback to ordinary GUP on PROT_NONE-mapped pages:
  2525. * pte_access_permitted() better should reject these pages
  2526. * either way: otherwise, GUP-fast might succeed in
  2527. * cases where ordinary GUP would fail due to VMA access
  2528. * permissions.
  2529. */
  2530. if (pte_protnone(pte))
  2531. goto pte_unmap;
  2532. if (!pte_access_permitted(pte, flags & FOLL_WRITE))
  2533. goto pte_unmap;
  2534. if (pte_special(pte))
  2535. goto pte_unmap;
  2536. /* If it's not marked as special it must have a valid memmap. */
  2537. VM_WARN_ON_ONCE(!pfn_valid(pte_pfn(pte)));
  2538. page = pte_page(pte);
  2539. folio = try_grab_folio_fast(page, 1, flags);
  2540. if (!folio)
  2541. goto pte_unmap;
  2542. if (unlikely(pmd_val(pmd) != pmd_val(*pmdp)) ||
  2543. unlikely(pte_val(pte) != pte_val(ptep_get(ptep)))) {
  2544. gup_put_folio(folio, 1, flags);
  2545. goto pte_unmap;
  2546. }
  2547. if (!gup_fast_folio_allowed(folio, flags)) {
  2548. gup_put_folio(folio, 1, flags);
  2549. goto pte_unmap;
  2550. }
  2551. if (!pte_write(pte) && gup_must_unshare(NULL, flags, page)) {
  2552. gup_put_folio(folio, 1, flags);
  2553. goto pte_unmap;
  2554. }
  2555. /*
  2556. * We need to make the page accessible if and only if we are
  2557. * going to access its content (the FOLL_PIN case). Please
  2558. * see Documentation/core-api/pin_user_pages.rst for
  2559. * details.
  2560. */
  2561. if ((flags & FOLL_PIN) && arch_make_folio_accessible(folio)) {
  2562. gup_put_folio(folio, 1, flags);
  2563. goto pte_unmap;
  2564. }
  2565. folio_set_referenced(folio);
  2566. pages[*nr] = page;
  2567. (*nr)++;
  2568. } while (ptep++, addr += PAGE_SIZE, addr != end);
  2569. ret = 1;
  2570. pte_unmap:
  2571. pte_unmap(ptem);
  2572. return ret;
  2573. }
  2574. #else
  2575. /*
  2576. * If we can't determine whether or not a pte is special, then fail immediately
  2577. * for ptes. Note, we can still pin HugeTLB and THP as these are guaranteed not
  2578. * to be special.
  2579. *
  2580. * For a futex to be placed on a THP tail page, get_futex_key requires a
  2581. * get_user_pages_fast_only implementation that can pin pages. Thus it's still
  2582. * useful to have gup_fast_pmd_leaf even if we can't operate on ptes.
  2583. */
  2584. static int gup_fast_pte_range(pmd_t pmd, pmd_t *pmdp, unsigned long addr,
  2585. unsigned long end, unsigned int flags, struct page **pages,
  2586. int *nr)
  2587. {
  2588. return 0;
  2589. }
  2590. #endif /* CONFIG_ARCH_HAS_PTE_SPECIAL */
  2591. static int gup_fast_pmd_leaf(pmd_t orig, pmd_t *pmdp, unsigned long addr,
  2592. unsigned long end, unsigned int flags, struct page **pages,
  2593. int *nr)
  2594. {
  2595. struct page *page;
  2596. struct folio *folio;
  2597. int refs;
  2598. if (!pmd_access_permitted(orig, flags & FOLL_WRITE))
  2599. return 0;
  2600. if (pmd_special(orig))
  2601. return 0;
  2602. refs = (end - addr) >> PAGE_SHIFT;
  2603. page = pmd_page(orig) + ((addr & ~PMD_MASK) >> PAGE_SHIFT);
  2604. folio = try_grab_folio_fast(page, refs, flags);
  2605. if (!folio)
  2606. return 0;
  2607. if (unlikely(pmd_val(orig) != pmd_val(*pmdp))) {
  2608. gup_put_folio(folio, refs, flags);
  2609. return 0;
  2610. }
  2611. if (!gup_fast_folio_allowed(folio, flags)) {
  2612. gup_put_folio(folio, refs, flags);
  2613. return 0;
  2614. }
  2615. if (!pmd_write(orig) && gup_must_unshare(NULL, flags, &folio->page)) {
  2616. gup_put_folio(folio, refs, flags);
  2617. return 0;
  2618. }
  2619. pages += *nr;
  2620. *nr += refs;
  2621. for (; refs; refs--)
  2622. *(pages++) = page++;
  2623. folio_set_referenced(folio);
  2624. return 1;
  2625. }
  2626. static int gup_fast_pud_leaf(pud_t orig, pud_t *pudp, unsigned long addr,
  2627. unsigned long end, unsigned int flags, struct page **pages,
  2628. int *nr)
  2629. {
  2630. struct page *page;
  2631. struct folio *folio;
  2632. int refs;
  2633. if (!pud_access_permitted(orig, flags & FOLL_WRITE))
  2634. return 0;
  2635. if (pud_special(orig))
  2636. return 0;
  2637. refs = (end - addr) >> PAGE_SHIFT;
  2638. page = pud_page(orig) + ((addr & ~PUD_MASK) >> PAGE_SHIFT);
  2639. folio = try_grab_folio_fast(page, refs, flags);
  2640. if (!folio)
  2641. return 0;
  2642. if (unlikely(pud_val(orig) != pud_val(*pudp))) {
  2643. gup_put_folio(folio, refs, flags);
  2644. return 0;
  2645. }
  2646. if (!gup_fast_folio_allowed(folio, flags)) {
  2647. gup_put_folio(folio, refs, flags);
  2648. return 0;
  2649. }
  2650. if (!pud_write(orig) && gup_must_unshare(NULL, flags, &folio->page)) {
  2651. gup_put_folio(folio, refs, flags);
  2652. return 0;
  2653. }
  2654. pages += *nr;
  2655. *nr += refs;
  2656. for (; refs; refs--)
  2657. *(pages++) = page++;
  2658. folio_set_referenced(folio);
  2659. return 1;
  2660. }
  2661. static int gup_fast_pmd_range(pud_t *pudp, pud_t pud, unsigned long addr,
  2662. unsigned long end, unsigned int flags, struct page **pages,
  2663. int *nr)
  2664. {
  2665. unsigned long next;
  2666. pmd_t *pmdp;
  2667. pmdp = pmd_offset_lockless(pudp, pud, addr);
  2668. do {
  2669. pmd_t pmd = pmdp_get_lockless(pmdp);
  2670. next = pmd_addr_end(addr, end);
  2671. if (!pmd_present(pmd))
  2672. return 0;
  2673. if (unlikely(pmd_leaf(pmd))) {
  2674. /* See gup_fast_pte_range() */
  2675. if (pmd_protnone(pmd))
  2676. return 0;
  2677. if (!gup_fast_pmd_leaf(pmd, pmdp, addr, next, flags,
  2678. pages, nr))
  2679. return 0;
  2680. } else if (!gup_fast_pte_range(pmd, pmdp, addr, next, flags,
  2681. pages, nr))
  2682. return 0;
  2683. } while (pmdp++, addr = next, addr != end);
  2684. return 1;
  2685. }
  2686. static int gup_fast_pud_range(p4d_t *p4dp, p4d_t p4d, unsigned long addr,
  2687. unsigned long end, unsigned int flags, struct page **pages,
  2688. int *nr)
  2689. {
  2690. unsigned long next;
  2691. pud_t *pudp;
  2692. pudp = pud_offset_lockless(p4dp, p4d, addr);
  2693. do {
  2694. pud_t pud = pudp_get(pudp);
  2695. next = pud_addr_end(addr, end);
  2696. if (unlikely(!pud_present(pud)))
  2697. return 0;
  2698. if (unlikely(pud_leaf(pud))) {
  2699. if (!gup_fast_pud_leaf(pud, pudp, addr, next, flags,
  2700. pages, nr))
  2701. return 0;
  2702. } else if (!gup_fast_pmd_range(pudp, pud, addr, next, flags,
  2703. pages, nr))
  2704. return 0;
  2705. } while (pudp++, addr = next, addr != end);
  2706. return 1;
  2707. }
  2708. static int gup_fast_p4d_range(pgd_t *pgdp, pgd_t pgd, unsigned long addr,
  2709. unsigned long end, unsigned int flags, struct page **pages,
  2710. int *nr)
  2711. {
  2712. unsigned long next;
  2713. p4d_t *p4dp;
  2714. p4dp = p4d_offset_lockless(pgdp, pgd, addr);
  2715. do {
  2716. p4d_t p4d = p4dp_get(p4dp);
  2717. next = p4d_addr_end(addr, end);
  2718. if (!p4d_present(p4d))
  2719. return 0;
  2720. BUILD_BUG_ON(p4d_leaf(p4d));
  2721. if (!gup_fast_pud_range(p4dp, p4d, addr, next, flags,
  2722. pages, nr))
  2723. return 0;
  2724. } while (p4dp++, addr = next, addr != end);
  2725. return 1;
  2726. }
  2727. static void gup_fast_pgd_range(unsigned long addr, unsigned long end,
  2728. unsigned int flags, struct page **pages, int *nr)
  2729. {
  2730. unsigned long next;
  2731. pgd_t *pgdp;
  2732. pgdp = pgd_offset(current->mm, addr);
  2733. do {
  2734. pgd_t pgd = pgdp_get(pgdp);
  2735. next = pgd_addr_end(addr, end);
  2736. if (pgd_none(pgd))
  2737. return;
  2738. BUILD_BUG_ON(pgd_leaf(pgd));
  2739. if (!gup_fast_p4d_range(pgdp, pgd, addr, next, flags,
  2740. pages, nr))
  2741. return;
  2742. } while (pgdp++, addr = next, addr != end);
  2743. }
  2744. #else
  2745. static inline void gup_fast_pgd_range(unsigned long addr, unsigned long end,
  2746. unsigned int flags, struct page **pages, int *nr)
  2747. {
  2748. }
  2749. #endif /* CONFIG_HAVE_GUP_FAST */
  2750. #ifndef gup_fast_permitted
  2751. /*
  2752. * Check if it's allowed to use get_user_pages_fast_only() for the range, or
  2753. * we need to fall back to the slow version:
  2754. */
  2755. static bool gup_fast_permitted(unsigned long start, unsigned long end)
  2756. {
  2757. return true;
  2758. }
  2759. #endif
  2760. static unsigned long gup_fast(unsigned long start, unsigned long end,
  2761. unsigned int gup_flags, struct page **pages)
  2762. {
  2763. unsigned long flags;
  2764. int nr_pinned = 0;
  2765. unsigned seq;
  2766. if (!IS_ENABLED(CONFIG_HAVE_GUP_FAST) ||
  2767. !gup_fast_permitted(start, end))
  2768. return 0;
  2769. if (gup_flags & FOLL_PIN) {
  2770. if (!raw_seqcount_try_begin(&current->mm->write_protect_seq, seq))
  2771. return 0;
  2772. }
  2773. /*
  2774. * Disable interrupts. The nested form is used, in order to allow full,
  2775. * general purpose use of this routine.
  2776. *
  2777. * With interrupts disabled, we block page table pages from being freed
  2778. * from under us. See struct mmu_table_batch comments in
  2779. * include/asm-generic/tlb.h for more details.
  2780. *
  2781. * We do not adopt an rcu_read_lock() here as we also want to block IPIs
  2782. * that come from callers of tlb_remove_table_sync_one().
  2783. */
  2784. local_irq_save(flags);
  2785. gup_fast_pgd_range(start, end, gup_flags, pages, &nr_pinned);
  2786. local_irq_restore(flags);
  2787. /*
  2788. * When pinning pages for DMA there could be a concurrent write protect
  2789. * from fork() via copy_page_range(), in this case always fail GUP-fast.
  2790. */
  2791. if (gup_flags & FOLL_PIN) {
  2792. if (read_seqcount_retry(&current->mm->write_protect_seq, seq)) {
  2793. gup_fast_unpin_user_pages(pages, nr_pinned);
  2794. return 0;
  2795. } else {
  2796. sanity_check_pinned_pages(pages, nr_pinned);
  2797. }
  2798. }
  2799. return nr_pinned;
  2800. }
  2801. static int gup_fast_fallback(unsigned long start, unsigned long nr_pages,
  2802. unsigned int gup_flags, struct page **pages)
  2803. {
  2804. unsigned long len, end;
  2805. unsigned long nr_pinned;
  2806. int locked = 0;
  2807. int ret;
  2808. if (WARN_ON_ONCE(gup_flags & ~(FOLL_WRITE | FOLL_LONGTERM |
  2809. FOLL_FORCE | FOLL_PIN | FOLL_GET |
  2810. FOLL_FAST_ONLY | FOLL_NOFAULT |
  2811. FOLL_PCI_P2PDMA | FOLL_HONOR_NUMA_FAULT)))
  2812. return -EINVAL;
  2813. if (gup_flags & FOLL_PIN)
  2814. mm_set_has_pinned_flag(current->mm);
  2815. if (!(gup_flags & FOLL_FAST_ONLY))
  2816. might_lock_read(&current->mm->mmap_lock);
  2817. start = untagged_addr(start) & PAGE_MASK;
  2818. len = nr_pages << PAGE_SHIFT;
  2819. if (check_add_overflow(start, len, &end))
  2820. return -EOVERFLOW;
  2821. if (end > TASK_SIZE_MAX)
  2822. return -EFAULT;
  2823. nr_pinned = gup_fast(start, end, gup_flags, pages);
  2824. if (nr_pinned == nr_pages || gup_flags & FOLL_FAST_ONLY)
  2825. return nr_pinned;
  2826. /* Slow path: try to get the remaining pages with get_user_pages */
  2827. start += nr_pinned << PAGE_SHIFT;
  2828. pages += nr_pinned;
  2829. ret = __gup_longterm_locked(current->mm, start, nr_pages - nr_pinned,
  2830. pages, &locked,
  2831. gup_flags | FOLL_TOUCH | FOLL_UNLOCKABLE);
  2832. if (ret < 0) {
  2833. /*
  2834. * The caller has to unpin the pages we already pinned so
  2835. * returning -errno is not an option
  2836. */
  2837. if (nr_pinned)
  2838. return nr_pinned;
  2839. return ret;
  2840. }
  2841. return ret + nr_pinned;
  2842. }
  2843. /**
  2844. * get_user_pages_fast_only() - pin user pages in memory
  2845. * @start: starting user address
  2846. * @nr_pages: number of pages from start to pin
  2847. * @gup_flags: flags modifying pin behaviour
  2848. * @pages: array that receives pointers to the pages pinned.
  2849. * Should be at least nr_pages long.
  2850. *
  2851. * Like get_user_pages_fast() except it's IRQ-safe in that it won't fall back to
  2852. * the regular GUP.
  2853. *
  2854. * If the architecture does not support this function, simply return with no
  2855. * pages pinned.
  2856. *
  2857. * Careful, careful! COW breaking can go either way, so a non-write
  2858. * access can get ambiguous page results. If you call this function without
  2859. * 'write' set, you'd better be sure that you're ok with that ambiguity.
  2860. */
  2861. int get_user_pages_fast_only(unsigned long start, int nr_pages,
  2862. unsigned int gup_flags, struct page **pages)
  2863. {
  2864. /*
  2865. * Internally (within mm/gup.c), gup fast variants must set FOLL_GET,
  2866. * because gup fast is always a "pin with a +1 page refcount" request.
  2867. *
  2868. * FOLL_FAST_ONLY is required in order to match the API description of
  2869. * this routine: no fall back to regular ("slow") GUP.
  2870. */
  2871. if (!is_valid_gup_args(pages, NULL, &gup_flags,
  2872. FOLL_GET | FOLL_FAST_ONLY))
  2873. return -EINVAL;
  2874. return gup_fast_fallback(start, nr_pages, gup_flags, pages);
  2875. }
  2876. EXPORT_SYMBOL_GPL(get_user_pages_fast_only);
  2877. /**
  2878. * get_user_pages_fast() - pin user pages in memory
  2879. * @start: starting user address
  2880. * @nr_pages: number of pages from start to pin
  2881. * @gup_flags: flags modifying pin behaviour
  2882. * @pages: array that receives pointers to the pages pinned.
  2883. * Should be at least nr_pages long.
  2884. *
  2885. * Attempt to pin user pages in memory without taking mm->mmap_lock.
  2886. * If not successful, it will fall back to taking the lock and
  2887. * calling get_user_pages().
  2888. *
  2889. * Returns number of pages pinned. This may be fewer than the number requested.
  2890. * If nr_pages is 0 or negative, returns 0. If no pages were pinned, returns
  2891. * -errno.
  2892. */
  2893. int get_user_pages_fast(unsigned long start, int nr_pages,
  2894. unsigned int gup_flags, struct page **pages)
  2895. {
  2896. /*
  2897. * The caller may or may not have explicitly set FOLL_GET; either way is
  2898. * OK. However, internally (within mm/gup.c), gup fast variants must set
  2899. * FOLL_GET, because gup fast is always a "pin with a +1 page refcount"
  2900. * request.
  2901. */
  2902. if (!is_valid_gup_args(pages, NULL, &gup_flags, FOLL_GET))
  2903. return -EINVAL;
  2904. return gup_fast_fallback(start, nr_pages, gup_flags, pages);
  2905. }
  2906. EXPORT_SYMBOL_GPL(get_user_pages_fast);
  2907. /**
  2908. * pin_user_pages_fast() - pin user pages in memory without taking locks
  2909. *
  2910. * @start: starting user address
  2911. * @nr_pages: number of pages from start to pin
  2912. * @gup_flags: flags modifying pin behaviour
  2913. * @pages: array that receives pointers to the pages pinned.
  2914. * Should be at least nr_pages long.
  2915. *
  2916. * Nearly the same as get_user_pages_fast(), except that FOLL_PIN is set. See
  2917. * get_user_pages_fast() for documentation on the function arguments, because
  2918. * the arguments here are identical.
  2919. *
  2920. * FOLL_PIN means that the pages must be released via unpin_user_page(). Please
  2921. * see Documentation/core-api/pin_user_pages.rst for further details.
  2922. *
  2923. * Note that if a zero_page is amongst the returned pages, it will not have
  2924. * pins in it and unpin_user_page() will not remove pins from it.
  2925. */
  2926. int pin_user_pages_fast(unsigned long start, int nr_pages,
  2927. unsigned int gup_flags, struct page **pages)
  2928. {
  2929. if (!is_valid_gup_args(pages, NULL, &gup_flags, FOLL_PIN))
  2930. return -EINVAL;
  2931. return gup_fast_fallback(start, nr_pages, gup_flags, pages);
  2932. }
  2933. EXPORT_SYMBOL_GPL(pin_user_pages_fast);
  2934. /**
  2935. * pin_user_pages_remote() - pin pages of a remote process
  2936. *
  2937. * @mm: mm_struct of target mm
  2938. * @start: starting user address
  2939. * @nr_pages: number of pages from start to pin
  2940. * @gup_flags: flags modifying lookup behaviour
  2941. * @pages: array that receives pointers to the pages pinned.
  2942. * Should be at least nr_pages long.
  2943. * @locked: pointer to lock flag indicating whether lock is held and
  2944. * subsequently whether VM_FAULT_RETRY functionality can be
  2945. * utilised. Lock must initially be held.
  2946. *
  2947. * Nearly the same as get_user_pages_remote(), except that FOLL_PIN is set. See
  2948. * get_user_pages_remote() for documentation on the function arguments, because
  2949. * the arguments here are identical.
  2950. *
  2951. * FOLL_PIN means that the pages must be released via unpin_user_page(). Please
  2952. * see Documentation/core-api/pin_user_pages.rst for details.
  2953. *
  2954. * Note that if a zero_page is amongst the returned pages, it will not have
  2955. * pins in it and unpin_user_page*() will not remove pins from it.
  2956. */
  2957. long pin_user_pages_remote(struct mm_struct *mm,
  2958. unsigned long start, unsigned long nr_pages,
  2959. unsigned int gup_flags, struct page **pages,
  2960. int *locked)
  2961. {
  2962. int local_locked = 1;
  2963. if (!is_valid_gup_args(pages, locked, &gup_flags,
  2964. FOLL_PIN | FOLL_TOUCH | FOLL_REMOTE))
  2965. return 0;
  2966. return __gup_longterm_locked(mm, start, nr_pages, pages,
  2967. locked ? locked : &local_locked,
  2968. gup_flags);
  2969. }
  2970. EXPORT_SYMBOL(pin_user_pages_remote);
  2971. /**
  2972. * pin_user_pages() - pin user pages in memory for use by other devices
  2973. *
  2974. * @start: starting user address
  2975. * @nr_pages: number of pages from start to pin
  2976. * @gup_flags: flags modifying lookup behaviour
  2977. * @pages: array that receives pointers to the pages pinned.
  2978. * Should be at least nr_pages long.
  2979. *
  2980. * Nearly the same as get_user_pages(), except that FOLL_TOUCH is not set, and
  2981. * FOLL_PIN is set.
  2982. *
  2983. * FOLL_PIN means that the pages must be released via unpin_user_page(). Please
  2984. * see Documentation/core-api/pin_user_pages.rst for details.
  2985. *
  2986. * Note that if a zero_page is amongst the returned pages, it will not have
  2987. * pins in it and unpin_user_page*() will not remove pins from it.
  2988. */
  2989. long pin_user_pages(unsigned long start, unsigned long nr_pages,
  2990. unsigned int gup_flags, struct page **pages)
  2991. {
  2992. int locked = 1;
  2993. if (!is_valid_gup_args(pages, NULL, &gup_flags, FOLL_PIN))
  2994. return 0;
  2995. return __gup_longterm_locked(current->mm, start, nr_pages,
  2996. pages, &locked, gup_flags);
  2997. }
  2998. EXPORT_SYMBOL(pin_user_pages);
  2999. /*
  3000. * pin_user_pages_unlocked() is the FOLL_PIN variant of
  3001. * get_user_pages_unlocked(). Behavior is the same, except that this one sets
  3002. * FOLL_PIN and rejects FOLL_GET.
  3003. *
  3004. * Note that if a zero_page is amongst the returned pages, it will not have
  3005. * pins in it and unpin_user_page*() will not remove pins from it.
  3006. */
  3007. long pin_user_pages_unlocked(unsigned long start, unsigned long nr_pages,
  3008. struct page **pages, unsigned int gup_flags)
  3009. {
  3010. int locked = 0;
  3011. if (!is_valid_gup_args(pages, NULL, &gup_flags,
  3012. FOLL_PIN | FOLL_TOUCH | FOLL_UNLOCKABLE))
  3013. return 0;
  3014. return __gup_longterm_locked(current->mm, start, nr_pages, pages,
  3015. &locked, gup_flags);
  3016. }
  3017. EXPORT_SYMBOL(pin_user_pages_unlocked);
  3018. /**
  3019. * memfd_pin_folios() - pin folios associated with a memfd
  3020. * @memfd: the memfd whose folios are to be pinned
  3021. * @start: the first memfd offset
  3022. * @end: the last memfd offset (inclusive)
  3023. * @folios: array that receives pointers to the folios pinned
  3024. * @max_folios: maximum number of entries in @folios
  3025. * @offset: the offset into the first folio
  3026. *
  3027. * Attempt to pin folios associated with a memfd in the contiguous range
  3028. * [start, end]. Given that a memfd is either backed by shmem or hugetlb,
  3029. * the folios can either be found in the page cache or need to be allocated
  3030. * if necessary. Once the folios are located, they are all pinned via
  3031. * FOLL_PIN and @offset is populatedwith the offset into the first folio.
  3032. * And, eventually, these pinned folios must be released either using
  3033. * unpin_folios() or unpin_folio().
  3034. *
  3035. * It must be noted that the folios may be pinned for an indefinite amount
  3036. * of time. And, in most cases, the duration of time they may stay pinned
  3037. * would be controlled by the userspace. This behavior is effectively the
  3038. * same as using FOLL_LONGTERM with other GUP APIs.
  3039. *
  3040. * Returns number of folios pinned, which could be less than @max_folios
  3041. * as it depends on the folio sizes that cover the range [start, end].
  3042. * If no folios were pinned, it returns -errno.
  3043. */
  3044. long memfd_pin_folios(struct file *memfd, loff_t start, loff_t end,
  3045. struct folio **folios, unsigned int max_folios,
  3046. pgoff_t *offset)
  3047. {
  3048. unsigned int flags, nr_folios, nr_found;
  3049. unsigned int i, pgshift = PAGE_SHIFT;
  3050. pgoff_t start_idx, end_idx;
  3051. struct folio *folio = NULL;
  3052. struct folio_batch fbatch;
  3053. struct hstate *h;
  3054. long ret = -EINVAL;
  3055. if (start < 0 || start > end || !max_folios)
  3056. return -EINVAL;
  3057. if (!memfd)
  3058. return -EINVAL;
  3059. if (!shmem_file(memfd) && !is_file_hugepages(memfd))
  3060. return -EINVAL;
  3061. if (end >= i_size_read(file_inode(memfd)))
  3062. return -EINVAL;
  3063. if (is_file_hugepages(memfd)) {
  3064. h = hstate_file(memfd);
  3065. pgshift = huge_page_shift(h);
  3066. }
  3067. flags = memalloc_pin_save();
  3068. do {
  3069. nr_folios = 0;
  3070. start_idx = start >> pgshift;
  3071. end_idx = end >> pgshift;
  3072. if (is_file_hugepages(memfd)) {
  3073. start_idx <<= huge_page_order(h);
  3074. end_idx <<= huge_page_order(h);
  3075. }
  3076. folio_batch_init(&fbatch);
  3077. while (start_idx <= end_idx && nr_folios < max_folios) {
  3078. /*
  3079. * In most cases, we should be able to find the folios
  3080. * in the page cache. If we cannot find them for some
  3081. * reason, we try to allocate them and add them to the
  3082. * page cache.
  3083. */
  3084. nr_found = filemap_get_folios_contig(memfd->f_mapping,
  3085. &start_idx,
  3086. end_idx,
  3087. &fbatch);
  3088. if (folio) {
  3089. folio_put(folio);
  3090. folio = NULL;
  3091. }
  3092. for (i = 0; i < nr_found; i++) {
  3093. folio = fbatch.folios[i];
  3094. if (try_grab_folio(folio, 1, FOLL_PIN)) {
  3095. folio_batch_release(&fbatch);
  3096. ret = -EINVAL;
  3097. goto err;
  3098. }
  3099. if (nr_folios == 0)
  3100. *offset = offset_in_folio(folio, start);
  3101. folios[nr_folios] = folio;
  3102. if (++nr_folios == max_folios)
  3103. break;
  3104. }
  3105. folio = NULL;
  3106. folio_batch_release(&fbatch);
  3107. if (!nr_found) {
  3108. folio = memfd_alloc_folio(memfd, start_idx);
  3109. if (IS_ERR(folio)) {
  3110. ret = PTR_ERR(folio);
  3111. if (ret != -EEXIST)
  3112. goto err;
  3113. folio = NULL;
  3114. }
  3115. }
  3116. }
  3117. ret = check_and_migrate_movable_folios(nr_folios, folios);
  3118. } while (ret == -EAGAIN);
  3119. memalloc_pin_restore(flags);
  3120. return ret ? ret : nr_folios;
  3121. err:
  3122. memalloc_pin_restore(flags);
  3123. unpin_folios(folios, nr_folios);
  3124. return ret;
  3125. }
  3126. EXPORT_SYMBOL_GPL(memfd_pin_folios);
  3127. /**
  3128. * folio_add_pins() - add pins to an already-pinned folio
  3129. * @folio: the folio to add more pins to
  3130. * @pins: number of pins to add
  3131. *
  3132. * Try to add more pins to an already-pinned folio. The semantics
  3133. * of the pin (e.g., FOLL_WRITE) follow any existing pin and cannot
  3134. * be changed.
  3135. *
  3136. * This function is helpful when having obtained a pin on a large folio
  3137. * using memfd_pin_folios(), but wanting to logically unpin parts
  3138. * (e.g., individual pages) of the folio later, for example, using
  3139. * unpin_user_page_range_dirty_lock().
  3140. *
  3141. * This is not the right interface to initially pin a folio.
  3142. */
  3143. int folio_add_pins(struct folio *folio, unsigned int pins)
  3144. {
  3145. VM_WARN_ON_ONCE(!folio_maybe_dma_pinned(folio));
  3146. return try_grab_folio(folio, pins, FOLL_PIN);
  3147. }
  3148. EXPORT_SYMBOL_GPL(folio_add_pins);