shmem.c 114 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781278227832784278527862787278827892790279127922793279427952796279727982799280028012802280328042805280628072808280928102811281228132814281528162817281828192820282128222823282428252826282728282829283028312832283328342835283628372838283928402841284228432844284528462847284828492850285128522853285428552856285728582859286028612862286328642865286628672868286928702871287228732874287528762877287828792880288128822883288428852886288728882889289028912892289328942895289628972898289929002901290229032904290529062907290829092910291129122913291429152916291729182919292029212922292329242925292629272928292929302931293229332934293529362937293829392940294129422943294429452946294729482949295029512952295329542955295629572958295929602961296229632964296529662967296829692970297129722973297429752976297729782979298029812982298329842985298629872988298929902991299229932994299529962997299829993000300130023003300430053006300730083009301030113012301330143015301630173018301930203021302230233024302530263027302830293030303130323033303430353036303730383039304030413042304330443045304630473048304930503051305230533054305530563057305830593060306130623063306430653066306730683069307030713072307330743075307630773078307930803081308230833084308530863087308830893090309130923093309430953096309730983099310031013102310331043105310631073108310931103111311231133114311531163117311831193120312131223123312431253126312731283129313031313132313331343135313631373138313931403141314231433144314531463147314831493150315131523153315431553156315731583159316031613162316331643165316631673168316931703171317231733174317531763177317831793180318131823183318431853186318731883189319031913192319331943195319631973198319932003201320232033204320532063207320832093210321132123213321432153216321732183219322032213222322332243225322632273228322932303231323232333234323532363237323832393240324132423243324432453246324732483249325032513252325332543255325632573258325932603261326232633264326532663267326832693270327132723273327432753276327732783279328032813282328332843285328632873288328932903291329232933294329532963297329832993300330133023303330433053306330733083309331033113312331333143315331633173318331933203321332233233324332533263327332833293330333133323333333433353336333733383339334033413342334333443345334633473348334933503351335233533354335533563357335833593360336133623363336433653366336733683369337033713372337333743375337633773378337933803381338233833384338533863387338833893390339133923393339433953396339733983399340034013402340334043405340634073408340934103411341234133414341534163417341834193420342134223423342434253426342734283429343034313432343334343435343634373438343934403441344234433444344534463447344834493450345134523453345434553456345734583459346034613462346334643465346634673468346934703471347234733474347534763477347834793480348134823483348434853486348734883489349034913492349334943495349634973498349935003501350235033504350535063507350835093510351135123513351435153516351735183519352035213522352335243525352635273528352935303531353235333534353535363537353835393540354135423543354435453546354735483549355035513552355335543555355635573558355935603561356235633564356535663567356835693570357135723573357435753576357735783579358035813582358335843585358635873588358935903591359235933594359535963597359835993600360136023603360436053606360736083609361036113612361336143615361636173618361936203621362236233624362536263627362836293630363136323633363436353636363736383639364036413642364336443645364636473648364936503651365236533654365536563657365836593660366136623663366436653666366736683669367036713672367336743675367636773678367936803681368236833684368536863687368836893690369136923693369436953696369736983699370037013702370337043705370637073708370937103711371237133714371537163717371837193720372137223723372437253726372737283729373037313732373337343735373637373738373937403741374237433744374537463747374837493750375137523753375437553756375737583759376037613762376337643765376637673768376937703771377237733774377537763777377837793780378137823783378437853786378737883789379037913792379337943795379637973798379938003801380238033804380538063807380838093810381138123813381438153816381738183819382038213822382338243825382638273828382938303831383238333834383538363837383838393840384138423843384438453846384738483849385038513852385338543855385638573858385938603861386238633864386538663867386838693870387138723873387438753876387738783879388038813882388338843885388638873888388938903891389238933894389538963897389838993900390139023903390439053906390739083909391039113912391339143915391639173918391939203921392239233924392539263927392839293930393139323933393439353936393739383939394039413942394339443945394639473948394939503951395239533954395539563957395839593960396139623963396439653966396739683969397039713972397339743975397639773978397939803981398239833984398539863987398839893990399139923993399439953996399739983999400040014002400340044005400640074008400940104011401240134014401540164017401840194020402140224023402440254026402740284029403040314032403340344035403640374038403940404041404240434044404540464047404840494050405140524053405440554056405740584059406040614062406340644065406640674068406940704071407240734074407540764077407840794080408140824083408440854086408740884089409040914092409340944095409640974098409941004101410241034104410541064107410841094110411141124113411441154116411741184119412041214122412341244125412641274128412941304131413241334134413541364137413841394140414141424143414441454146414741484149415041514152415341544155415641574158415941604161416241634164416541664167416841694170417141724173417441754176417741784179418041814182418341844185418641874188418941904191419241934194419541964197419841994200420142024203420442054206420742084209421042114212421342144215421642174218421942204221422242234224422542264227422842294230423142324233423442354236423742384239424042414242424342444245424642474248424942504251425242534254425542564257425842594260426142624263426442654266426742684269427042714272427342744275427642774278427942804281428242834284428542864287428842894290429142924293429442954296429742984299430043014302430343044305430643074308430943104311431243134314431543164317431843194320432143224323432443254326432743284329433043314332433343344335433643374338433943404341434243434344434543464347434843494350435143524353435443554356435743584359436043614362436343644365436643674368436943704371437243734374437543764377437843794380438143824383438443854386438743884389439043914392439343944395439643974398439944004401440244034404440544064407
  1. /*
  2. * Resizable virtual memory filesystem for Linux.
  3. *
  4. * Copyright (C) 2000 Linus Torvalds.
  5. * 2000 Transmeta Corp.
  6. * 2000-2001 Christoph Rohland
  7. * 2000-2001 SAP AG
  8. * 2002 Red Hat Inc.
  9. * Copyright (C) 2002-2011 Hugh Dickins.
  10. * Copyright (C) 2011 Google Inc.
  11. * Copyright (C) 2002-2005 VERITAS Software Corporation.
  12. * Copyright (C) 2004 Andi Kleen, SuSE Labs
  13. *
  14. * Extended attribute support for tmpfs:
  15. * Copyright (c) 2004, Luke Kenneth Casson Leighton <[email protected]>
  16. * Copyright (c) 2004 Red Hat, Inc., James Morris <[email protected]>
  17. *
  18. * tiny-shmem:
  19. * Copyright (c) 2004, 2008 Matt Mackall <[email protected]>
  20. *
  21. * This file is released under the GPL.
  22. */
  23. #include <linux/fs.h>
  24. #include <linux/init.h>
  25. #include <linux/vfs.h>
  26. #include <linux/mount.h>
  27. #include <linux/ramfs.h>
  28. #include <linux/pagemap.h>
  29. #include <linux/file.h>
  30. #include <linux/fileattr.h>
  31. #include <linux/mm.h>
  32. #include <linux/random.h>
  33. #include <linux/sched/signal.h>
  34. #include <linux/export.h>
  35. #include <linux/swap.h>
  36. #include <linux/uio.h>
  37. #include <linux/hugetlb.h>
  38. #include <linux/fs_parser.h>
  39. #include <linux/swapfile.h>
  40. #include <linux/iversion.h>
  41. #include <linux/mm_inline.h>
  42. #include "swap.h"
  43. #undef CREATE_TRACE_POINTS
  44. #include <trace/hooks/mm.h>
  45. static struct vfsmount *shm_mnt;
  46. #ifdef CONFIG_SHMEM
  47. /*
  48. * This virtual memory filesystem is heavily based on the ramfs. It
  49. * extends ramfs by the ability to use swap and honor resource limits
  50. * which makes it a completely usable filesystem.
  51. */
  52. #include <linux/xattr.h>
  53. #include <linux/exportfs.h>
  54. #include <linux/posix_acl.h>
  55. #include <linux/posix_acl_xattr.h>
  56. #include <linux/mman.h>
  57. #include <linux/string.h>
  58. #include <linux/slab.h>
  59. #include <linux/backing-dev.h>
  60. #include <linux/shmem_fs.h>
  61. #include <linux/writeback.h>
  62. #include <linux/pagevec.h>
  63. #include <linux/percpu_counter.h>
  64. #include <linux/falloc.h>
  65. #include <linux/splice.h>
  66. #include <linux/security.h>
  67. #include <linux/swapops.h>
  68. #include <linux/mempolicy.h>
  69. #include <linux/namei.h>
  70. #include <linux/ctype.h>
  71. #include <linux/migrate.h>
  72. #include <linux/highmem.h>
  73. #include <linux/seq_file.h>
  74. #include <linux/magic.h>
  75. #include <linux/syscalls.h>
  76. #include <linux/fcntl.h>
  77. #include <uapi/linux/memfd.h>
  78. #include <linux/userfaultfd_k.h>
  79. #include <linux/rmap.h>
  80. #include <linux/uuid.h>
  81. #include <linux/android_vendor.h>
  82. #include <linux/uaccess.h>
  83. #include "internal.h"
  84. #define BLOCKS_PER_PAGE (PAGE_SIZE/512)
  85. #define VM_ACCT(size) (PAGE_ALIGN(size) >> PAGE_SHIFT)
  86. /* Pretend that each entry is of this size in directory's i_size */
  87. #define BOGO_DIRENT_SIZE 20
  88. /* Symlink up to this size is kmalloc'ed instead of using a swappable page */
  89. #define SHORT_SYMLINK_LEN 128
  90. /*
  91. * shmem_fallocate communicates with shmem_fault or shmem_writepage via
  92. * inode->i_private (with i_rwsem making sure that it has only one user at
  93. * a time): we would prefer not to enlarge the shmem inode just for that.
  94. */
  95. struct shmem_falloc {
  96. wait_queue_head_t *waitq; /* faults into hole wait for punch to end */
  97. pgoff_t start; /* start of range currently being fallocated */
  98. pgoff_t next; /* the next page offset to be fallocated */
  99. pgoff_t nr_falloced; /* how many new pages have been fallocated */
  100. pgoff_t nr_unswapped; /* how often writepage refused to swap out */
  101. };
  102. struct shmem_options {
  103. unsigned long long blocks;
  104. unsigned long long inodes;
  105. struct mempolicy *mpol;
  106. kuid_t uid;
  107. kgid_t gid;
  108. umode_t mode;
  109. bool full_inums;
  110. int huge;
  111. int seen;
  112. #define SHMEM_SEEN_BLOCKS 1
  113. #define SHMEM_SEEN_INODES 2
  114. #define SHMEM_SEEN_HUGE 4
  115. #define SHMEM_SEEN_INUMS 8
  116. };
  117. #ifdef CONFIG_TMPFS
  118. static unsigned long shmem_default_max_blocks(void)
  119. {
  120. return totalram_pages() / 2;
  121. }
  122. static unsigned long shmem_default_max_inodes(void)
  123. {
  124. unsigned long nr_pages = totalram_pages();
  125. return min(nr_pages - totalhigh_pages(), nr_pages / 2);
  126. }
  127. #endif
  128. static int shmem_swapin_folio(struct inode *inode, pgoff_t index,
  129. struct folio **foliop, enum sgp_type sgp,
  130. gfp_t gfp, struct vm_area_struct *vma,
  131. vm_fault_t *fault_type);
  132. static inline struct shmem_sb_info *SHMEM_SB(struct super_block *sb)
  133. {
  134. return sb->s_fs_info;
  135. }
  136. /*
  137. * shmem_file_setup pre-accounts the whole fixed size of a VM object,
  138. * for shared memory and for shared anonymous (/dev/zero) mappings
  139. * (unless MAP_NORESERVE and sysctl_overcommit_memory <= 1),
  140. * consistent with the pre-accounting of private mappings ...
  141. */
  142. static inline int shmem_acct_size(unsigned long flags, loff_t size)
  143. {
  144. return (flags & VM_NORESERVE) ?
  145. 0 : security_vm_enough_memory_mm(current->mm, VM_ACCT(size));
  146. }
  147. static inline void shmem_unacct_size(unsigned long flags, loff_t size)
  148. {
  149. if (!(flags & VM_NORESERVE))
  150. vm_unacct_memory(VM_ACCT(size));
  151. }
  152. static inline int shmem_reacct_size(unsigned long flags,
  153. loff_t oldsize, loff_t newsize)
  154. {
  155. if (!(flags & VM_NORESERVE)) {
  156. if (VM_ACCT(newsize) > VM_ACCT(oldsize))
  157. return security_vm_enough_memory_mm(current->mm,
  158. VM_ACCT(newsize) - VM_ACCT(oldsize));
  159. else if (VM_ACCT(newsize) < VM_ACCT(oldsize))
  160. vm_unacct_memory(VM_ACCT(oldsize) - VM_ACCT(newsize));
  161. }
  162. return 0;
  163. }
  164. /*
  165. * ... whereas tmpfs objects are accounted incrementally as
  166. * pages are allocated, in order to allow large sparse files.
  167. * shmem_get_folio reports shmem_acct_block failure as -ENOSPC not -ENOMEM,
  168. * so that a failure on a sparse tmpfs mapping will give SIGBUS not OOM.
  169. */
  170. static inline int shmem_acct_block(unsigned long flags, long pages)
  171. {
  172. if (!(flags & VM_NORESERVE))
  173. return 0;
  174. return security_vm_enough_memory_mm(current->mm,
  175. pages * VM_ACCT(PAGE_SIZE));
  176. }
  177. static inline void shmem_unacct_blocks(unsigned long flags, long pages)
  178. {
  179. if (flags & VM_NORESERVE)
  180. vm_unacct_memory(pages * VM_ACCT(PAGE_SIZE));
  181. }
  182. static inline bool shmem_inode_acct_block(struct inode *inode, long pages)
  183. {
  184. struct shmem_inode_info *info = SHMEM_I(inode);
  185. struct shmem_sb_info *sbinfo = SHMEM_SB(inode->i_sb);
  186. if (shmem_acct_block(info->flags, pages))
  187. return false;
  188. if (sbinfo->max_blocks) {
  189. if (percpu_counter_compare(&sbinfo->used_blocks,
  190. sbinfo->max_blocks - pages) > 0)
  191. goto unacct;
  192. percpu_counter_add(&sbinfo->used_blocks, pages);
  193. }
  194. return true;
  195. unacct:
  196. shmem_unacct_blocks(info->flags, pages);
  197. return false;
  198. }
  199. static inline void shmem_inode_unacct_blocks(struct inode *inode, long pages)
  200. {
  201. struct shmem_inode_info *info = SHMEM_I(inode);
  202. struct shmem_sb_info *sbinfo = SHMEM_SB(inode->i_sb);
  203. if (sbinfo->max_blocks)
  204. percpu_counter_sub(&sbinfo->used_blocks, pages);
  205. shmem_unacct_blocks(info->flags, pages);
  206. }
  207. static const struct super_operations shmem_ops;
  208. const struct address_space_operations shmem_aops;
  209. static const struct file_operations shmem_file_operations;
  210. static const struct inode_operations shmem_inode_operations;
  211. static const struct inode_operations shmem_dir_inode_operations;
  212. static const struct inode_operations shmem_special_inode_operations;
  213. static const struct vm_operations_struct shmem_vm_ops;
  214. static struct file_system_type shmem_fs_type;
  215. bool vma_is_shmem(struct vm_area_struct *vma)
  216. {
  217. return vma->vm_ops == &shmem_vm_ops;
  218. }
  219. static LIST_HEAD(shmem_swaplist);
  220. static DEFINE_MUTEX(shmem_swaplist_mutex);
  221. /*
  222. * shmem_reserve_inode() performs bookkeeping to reserve a shmem inode, and
  223. * produces a novel ino for the newly allocated inode.
  224. *
  225. * It may also be called when making a hard link to permit the space needed by
  226. * each dentry. However, in that case, no new inode number is needed since that
  227. * internally draws from another pool of inode numbers (currently global
  228. * get_next_ino()). This case is indicated by passing NULL as inop.
  229. */
  230. #define SHMEM_INO_BATCH 1024
  231. static int shmem_reserve_inode(struct super_block *sb, ino_t *inop)
  232. {
  233. struct shmem_sb_info *sbinfo = SHMEM_SB(sb);
  234. ino_t ino;
  235. if (!(sb->s_flags & SB_KERNMOUNT)) {
  236. raw_spin_lock(&sbinfo->stat_lock);
  237. if (sbinfo->max_inodes) {
  238. if (!sbinfo->free_inodes) {
  239. raw_spin_unlock(&sbinfo->stat_lock);
  240. return -ENOSPC;
  241. }
  242. sbinfo->free_inodes--;
  243. }
  244. if (inop) {
  245. ino = sbinfo->next_ino++;
  246. if (unlikely(is_zero_ino(ino)))
  247. ino = sbinfo->next_ino++;
  248. if (unlikely(!sbinfo->full_inums &&
  249. ino > UINT_MAX)) {
  250. /*
  251. * Emulate get_next_ino uint wraparound for
  252. * compatibility
  253. */
  254. if (IS_ENABLED(CONFIG_64BIT))
  255. pr_warn("%s: inode number overflow on device %d, consider using inode64 mount option\n",
  256. __func__, MINOR(sb->s_dev));
  257. sbinfo->next_ino = 1;
  258. ino = sbinfo->next_ino++;
  259. }
  260. *inop = ino;
  261. }
  262. raw_spin_unlock(&sbinfo->stat_lock);
  263. } else if (inop) {
  264. /*
  265. * __shmem_file_setup, one of our callers, is lock-free: it
  266. * doesn't hold stat_lock in shmem_reserve_inode since
  267. * max_inodes is always 0, and is called from potentially
  268. * unknown contexts. As such, use a per-cpu batched allocator
  269. * which doesn't require the per-sb stat_lock unless we are at
  270. * the batch boundary.
  271. *
  272. * We don't need to worry about inode{32,64} since SB_KERNMOUNT
  273. * shmem mounts are not exposed to userspace, so we don't need
  274. * to worry about things like glibc compatibility.
  275. */
  276. ino_t *next_ino;
  277. next_ino = per_cpu_ptr(sbinfo->ino_batch, get_cpu());
  278. ino = *next_ino;
  279. if (unlikely(ino % SHMEM_INO_BATCH == 0)) {
  280. raw_spin_lock(&sbinfo->stat_lock);
  281. ino = sbinfo->next_ino;
  282. sbinfo->next_ino += SHMEM_INO_BATCH;
  283. raw_spin_unlock(&sbinfo->stat_lock);
  284. if (unlikely(is_zero_ino(ino)))
  285. ino++;
  286. }
  287. *inop = ino;
  288. *next_ino = ++ino;
  289. put_cpu();
  290. }
  291. return 0;
  292. }
  293. static void shmem_free_inode(struct super_block *sb)
  294. {
  295. struct shmem_sb_info *sbinfo = SHMEM_SB(sb);
  296. if (sbinfo->max_inodes) {
  297. raw_spin_lock(&sbinfo->stat_lock);
  298. sbinfo->free_inodes++;
  299. raw_spin_unlock(&sbinfo->stat_lock);
  300. }
  301. }
  302. /**
  303. * shmem_recalc_inode - recalculate the block usage of an inode
  304. * @inode: inode to recalc
  305. *
  306. * We have to calculate the free blocks since the mm can drop
  307. * undirtied hole pages behind our back.
  308. *
  309. * But normally info->alloced == inode->i_mapping->nrpages + info->swapped
  310. * So mm freed is info->alloced - (inode->i_mapping->nrpages + info->swapped)
  311. *
  312. * It has to be called with the spinlock held.
  313. */
  314. static void shmem_recalc_inode(struct inode *inode)
  315. {
  316. struct shmem_inode_info *info = SHMEM_I(inode);
  317. long freed;
  318. freed = info->alloced - info->swapped - inode->i_mapping->nrpages;
  319. if (freed > 0) {
  320. info->alloced -= freed;
  321. inode->i_blocks -= freed * BLOCKS_PER_PAGE;
  322. shmem_inode_unacct_blocks(inode, freed);
  323. }
  324. }
  325. bool shmem_charge(struct inode *inode, long pages)
  326. {
  327. struct shmem_inode_info *info = SHMEM_I(inode);
  328. unsigned long flags;
  329. if (!shmem_inode_acct_block(inode, pages))
  330. return false;
  331. /* nrpages adjustment first, then shmem_recalc_inode() when balanced */
  332. inode->i_mapping->nrpages += pages;
  333. spin_lock_irqsave(&info->lock, flags);
  334. info->alloced += pages;
  335. inode->i_blocks += pages * BLOCKS_PER_PAGE;
  336. shmem_recalc_inode(inode);
  337. spin_unlock_irqrestore(&info->lock, flags);
  338. return true;
  339. }
  340. void shmem_uncharge(struct inode *inode, long pages)
  341. {
  342. struct shmem_inode_info *info = SHMEM_I(inode);
  343. unsigned long flags;
  344. /* nrpages adjustment done by __filemap_remove_folio() or caller */
  345. spin_lock_irqsave(&info->lock, flags);
  346. info->alloced -= pages;
  347. inode->i_blocks -= pages * BLOCKS_PER_PAGE;
  348. shmem_recalc_inode(inode);
  349. spin_unlock_irqrestore(&info->lock, flags);
  350. shmem_inode_unacct_blocks(inode, pages);
  351. }
  352. /*
  353. * Replace item expected in xarray by a new item, while holding xa_lock.
  354. */
  355. static int shmem_replace_entry(struct address_space *mapping,
  356. pgoff_t index, void *expected, void *replacement)
  357. {
  358. XA_STATE(xas, &mapping->i_pages, index);
  359. void *item;
  360. VM_BUG_ON(!expected);
  361. VM_BUG_ON(!replacement);
  362. item = xas_load(&xas);
  363. if (item != expected)
  364. return -ENOENT;
  365. xas_store(&xas, replacement);
  366. return 0;
  367. }
  368. /*
  369. * Sometimes, before we decide whether to proceed or to fail, we must check
  370. * that an entry was not already brought back from swap by a racing thread.
  371. *
  372. * Checking page is not enough: by the time a SwapCache page is locked, it
  373. * might be reused, and again be SwapCache, using the same swap as before.
  374. */
  375. static bool shmem_confirm_swap(struct address_space *mapping,
  376. pgoff_t index, swp_entry_t swap)
  377. {
  378. return xa_load(&mapping->i_pages, index) == swp_to_radix_entry(swap);
  379. }
  380. /*
  381. * Definitions for "huge tmpfs": tmpfs mounted with the huge= option
  382. *
  383. * SHMEM_HUGE_NEVER:
  384. * disables huge pages for the mount;
  385. * SHMEM_HUGE_ALWAYS:
  386. * enables huge pages for the mount;
  387. * SHMEM_HUGE_WITHIN_SIZE:
  388. * only allocate huge pages if the page will be fully within i_size,
  389. * also respect fadvise()/madvise() hints;
  390. * SHMEM_HUGE_ADVISE:
  391. * only allocate huge pages if requested with fadvise()/madvise();
  392. */
  393. #define SHMEM_HUGE_NEVER 0
  394. #define SHMEM_HUGE_ALWAYS 1
  395. #define SHMEM_HUGE_WITHIN_SIZE 2
  396. #define SHMEM_HUGE_ADVISE 3
  397. /*
  398. * Special values.
  399. * Only can be set via /sys/kernel/mm/transparent_hugepage/shmem_enabled:
  400. *
  401. * SHMEM_HUGE_DENY:
  402. * disables huge on shm_mnt and all mounts, for emergency use;
  403. * SHMEM_HUGE_FORCE:
  404. * enables huge on shm_mnt and all mounts, w/o needing option, for testing;
  405. *
  406. */
  407. #define SHMEM_HUGE_DENY (-1)
  408. #define SHMEM_HUGE_FORCE (-2)
  409. #ifdef CONFIG_TRANSPARENT_HUGEPAGE
  410. /* ifdef here to avoid bloating shmem.o when not necessary */
  411. static int shmem_huge __read_mostly = SHMEM_HUGE_NEVER;
  412. bool shmem_is_huge(struct vm_area_struct *vma, struct inode *inode,
  413. pgoff_t index, bool shmem_huge_force)
  414. {
  415. loff_t i_size;
  416. if (!S_ISREG(inode->i_mode))
  417. return false;
  418. if (vma && ((vma->vm_flags & VM_NOHUGEPAGE) ||
  419. test_bit(MMF_DISABLE_THP, &vma->vm_mm->flags)))
  420. return false;
  421. if (shmem_huge == SHMEM_HUGE_DENY)
  422. return false;
  423. if (shmem_huge_force || shmem_huge == SHMEM_HUGE_FORCE)
  424. return true;
  425. switch (SHMEM_SB(inode->i_sb)->huge) {
  426. case SHMEM_HUGE_ALWAYS:
  427. return true;
  428. case SHMEM_HUGE_WITHIN_SIZE:
  429. index = round_up(index + 1, HPAGE_PMD_NR);
  430. i_size = round_up(i_size_read(inode), PAGE_SIZE);
  431. if (i_size >> PAGE_SHIFT >= index)
  432. return true;
  433. fallthrough;
  434. case SHMEM_HUGE_ADVISE:
  435. if (vma && (vma->vm_flags & VM_HUGEPAGE))
  436. return true;
  437. fallthrough;
  438. default:
  439. return false;
  440. }
  441. }
  442. #if defined(CONFIG_SYSFS)
  443. static int shmem_parse_huge(const char *str)
  444. {
  445. if (!strcmp(str, "never"))
  446. return SHMEM_HUGE_NEVER;
  447. if (!strcmp(str, "always"))
  448. return SHMEM_HUGE_ALWAYS;
  449. if (!strcmp(str, "within_size"))
  450. return SHMEM_HUGE_WITHIN_SIZE;
  451. if (!strcmp(str, "advise"))
  452. return SHMEM_HUGE_ADVISE;
  453. if (!strcmp(str, "deny"))
  454. return SHMEM_HUGE_DENY;
  455. if (!strcmp(str, "force"))
  456. return SHMEM_HUGE_FORCE;
  457. return -EINVAL;
  458. }
  459. #endif
  460. #if defined(CONFIG_SYSFS) || defined(CONFIG_TMPFS)
  461. static const char *shmem_format_huge(int huge)
  462. {
  463. switch (huge) {
  464. case SHMEM_HUGE_NEVER:
  465. return "never";
  466. case SHMEM_HUGE_ALWAYS:
  467. return "always";
  468. case SHMEM_HUGE_WITHIN_SIZE:
  469. return "within_size";
  470. case SHMEM_HUGE_ADVISE:
  471. return "advise";
  472. case SHMEM_HUGE_DENY:
  473. return "deny";
  474. case SHMEM_HUGE_FORCE:
  475. return "force";
  476. default:
  477. VM_BUG_ON(1);
  478. return "bad_val";
  479. }
  480. }
  481. #endif
  482. static unsigned long shmem_unused_huge_shrink(struct shmem_sb_info *sbinfo,
  483. struct shrink_control *sc, unsigned long nr_to_split)
  484. {
  485. LIST_HEAD(list), *pos, *next;
  486. LIST_HEAD(to_remove);
  487. struct inode *inode;
  488. struct shmem_inode_info *info;
  489. struct folio *folio;
  490. unsigned long batch = sc ? sc->nr_to_scan : 128;
  491. int split = 0;
  492. if (list_empty(&sbinfo->shrinklist))
  493. return SHRINK_STOP;
  494. spin_lock(&sbinfo->shrinklist_lock);
  495. list_for_each_safe(pos, next, &sbinfo->shrinklist) {
  496. info = list_entry(pos, struct shmem_inode_info, shrinklist);
  497. /* pin the inode */
  498. inode = igrab(&info->vfs_inode);
  499. /* inode is about to be evicted */
  500. if (!inode) {
  501. list_del_init(&info->shrinklist);
  502. goto next;
  503. }
  504. /* Check if there's anything to gain */
  505. if (round_up(inode->i_size, PAGE_SIZE) ==
  506. round_up(inode->i_size, HPAGE_PMD_SIZE)) {
  507. list_move(&info->shrinklist, &to_remove);
  508. goto next;
  509. }
  510. list_move(&info->shrinklist, &list);
  511. next:
  512. sbinfo->shrinklist_len--;
  513. if (!--batch)
  514. break;
  515. }
  516. spin_unlock(&sbinfo->shrinklist_lock);
  517. list_for_each_safe(pos, next, &to_remove) {
  518. info = list_entry(pos, struct shmem_inode_info, shrinklist);
  519. inode = &info->vfs_inode;
  520. list_del_init(&info->shrinklist);
  521. iput(inode);
  522. }
  523. list_for_each_safe(pos, next, &list) {
  524. int ret;
  525. pgoff_t index;
  526. info = list_entry(pos, struct shmem_inode_info, shrinklist);
  527. inode = &info->vfs_inode;
  528. if (nr_to_split && split >= nr_to_split)
  529. goto move_back;
  530. index = (inode->i_size & HPAGE_PMD_MASK) >> PAGE_SHIFT;
  531. folio = filemap_get_folio(inode->i_mapping, index);
  532. if (!folio)
  533. goto drop;
  534. /* No huge page at the end of the file: nothing to split */
  535. if (!folio_test_large(folio)) {
  536. folio_put(folio);
  537. goto drop;
  538. }
  539. /*
  540. * Move the inode on the list back to shrinklist if we failed
  541. * to lock the page at this time.
  542. *
  543. * Waiting for the lock may lead to deadlock in the
  544. * reclaim path.
  545. */
  546. if (!folio_trylock(folio)) {
  547. folio_put(folio);
  548. goto move_back;
  549. }
  550. ret = split_folio(folio);
  551. folio_unlock(folio);
  552. folio_put(folio);
  553. /* If split failed move the inode on the list back to shrinklist */
  554. if (ret)
  555. goto move_back;
  556. split++;
  557. drop:
  558. list_del_init(&info->shrinklist);
  559. goto put;
  560. move_back:
  561. /*
  562. * Make sure the inode is either on the global list or deleted
  563. * from any local list before iput() since it could be deleted
  564. * in another thread once we put the inode (then the local list
  565. * is corrupted).
  566. */
  567. spin_lock(&sbinfo->shrinklist_lock);
  568. list_move(&info->shrinklist, &sbinfo->shrinklist);
  569. sbinfo->shrinklist_len++;
  570. spin_unlock(&sbinfo->shrinklist_lock);
  571. put:
  572. iput(inode);
  573. }
  574. return split;
  575. }
  576. static long shmem_unused_huge_scan(struct super_block *sb,
  577. struct shrink_control *sc)
  578. {
  579. struct shmem_sb_info *sbinfo = SHMEM_SB(sb);
  580. if (!READ_ONCE(sbinfo->shrinklist_len))
  581. return SHRINK_STOP;
  582. return shmem_unused_huge_shrink(sbinfo, sc, 0);
  583. }
  584. static long shmem_unused_huge_count(struct super_block *sb,
  585. struct shrink_control *sc)
  586. {
  587. struct shmem_sb_info *sbinfo = SHMEM_SB(sb);
  588. return READ_ONCE(sbinfo->shrinklist_len);
  589. }
  590. #else /* !CONFIG_TRANSPARENT_HUGEPAGE */
  591. #define shmem_huge SHMEM_HUGE_DENY
  592. bool shmem_is_huge(struct vm_area_struct *vma, struct inode *inode,
  593. pgoff_t index, bool shmem_huge_force)
  594. {
  595. return false;
  596. }
  597. static unsigned long shmem_unused_huge_shrink(struct shmem_sb_info *sbinfo,
  598. struct shrink_control *sc, unsigned long nr_to_split)
  599. {
  600. return 0;
  601. }
  602. #endif /* CONFIG_TRANSPARENT_HUGEPAGE */
  603. /*
  604. * Like filemap_add_folio, but error if expected item has gone.
  605. */
  606. static int shmem_add_to_page_cache(struct folio *folio,
  607. struct address_space *mapping,
  608. pgoff_t index, void *expected, gfp_t gfp,
  609. struct mm_struct *charge_mm)
  610. {
  611. XA_STATE_ORDER(xas, &mapping->i_pages, index, folio_order(folio));
  612. long nr = folio_nr_pages(folio);
  613. int error;
  614. VM_BUG_ON_FOLIO(index != round_down(index, nr), folio);
  615. VM_BUG_ON_FOLIO(!folio_test_locked(folio), folio);
  616. VM_BUG_ON_FOLIO(!folio_test_swapbacked(folio), folio);
  617. VM_BUG_ON(expected && folio_test_large(folio));
  618. folio_ref_add(folio, nr);
  619. folio->mapping = mapping;
  620. folio->index = index;
  621. if (!folio_test_swapcache(folio)) {
  622. error = mem_cgroup_charge(folio, charge_mm, gfp);
  623. if (error) {
  624. if (folio_test_pmd_mappable(folio)) {
  625. count_vm_event(THP_FILE_FALLBACK);
  626. count_vm_event(THP_FILE_FALLBACK_CHARGE);
  627. }
  628. goto error;
  629. }
  630. }
  631. folio_throttle_swaprate(folio, gfp);
  632. do {
  633. xas_lock_irq(&xas);
  634. if (expected != xas_find_conflict(&xas)) {
  635. xas_set_err(&xas, -EEXIST);
  636. goto unlock;
  637. }
  638. if (expected && xas_find_conflict(&xas)) {
  639. xas_set_err(&xas, -EEXIST);
  640. goto unlock;
  641. }
  642. xas_store(&xas, folio);
  643. if (xas_error(&xas))
  644. goto unlock;
  645. if (folio_test_pmd_mappable(folio)) {
  646. count_vm_event(THP_FILE_ALLOC);
  647. __lruvec_stat_mod_folio(folio, NR_SHMEM_THPS, nr);
  648. }
  649. mapping->nrpages += nr;
  650. __lruvec_stat_mod_folio(folio, NR_FILE_PAGES, nr);
  651. __lruvec_stat_mod_folio(folio, NR_SHMEM, nr);
  652. unlock:
  653. xas_unlock_irq(&xas);
  654. } while (xas_nomem(&xas, gfp));
  655. if (xas_error(&xas)) {
  656. error = xas_error(&xas);
  657. goto error;
  658. }
  659. return 0;
  660. error:
  661. folio->mapping = NULL;
  662. folio_ref_sub(folio, nr);
  663. return error;
  664. }
  665. /*
  666. * Like delete_from_page_cache, but substitutes swap for @folio.
  667. */
  668. static void shmem_delete_from_page_cache(struct folio *folio, void *radswap)
  669. {
  670. struct address_space *mapping = folio->mapping;
  671. long nr = folio_nr_pages(folio);
  672. int error;
  673. xa_lock_irq(&mapping->i_pages);
  674. error = shmem_replace_entry(mapping, folio->index, folio, radswap);
  675. folio->mapping = NULL;
  676. mapping->nrpages -= nr;
  677. __lruvec_stat_mod_folio(folio, NR_FILE_PAGES, -nr);
  678. __lruvec_stat_mod_folio(folio, NR_SHMEM, -nr);
  679. xa_unlock_irq(&mapping->i_pages);
  680. folio_put(folio);
  681. BUG_ON(error);
  682. }
  683. /*
  684. * Remove swap entry from page cache, free the swap and its page cache.
  685. */
  686. static int shmem_free_swap(struct address_space *mapping,
  687. pgoff_t index, void *radswap)
  688. {
  689. void *old;
  690. old = xa_cmpxchg_irq(&mapping->i_pages, index, radswap, NULL, 0);
  691. if (old != radswap)
  692. return -ENOENT;
  693. free_swap_and_cache(radix_to_swp_entry(radswap));
  694. return 0;
  695. }
  696. /*
  697. * Determine (in bytes) how many of the shmem object's pages mapped by the
  698. * given offsets are swapped out.
  699. *
  700. * This is safe to call without i_rwsem or the i_pages lock thanks to RCU,
  701. * as long as the inode doesn't go away and racy results are not a problem.
  702. */
  703. unsigned long shmem_partial_swap_usage(struct address_space *mapping,
  704. pgoff_t start, pgoff_t end)
  705. {
  706. XA_STATE(xas, &mapping->i_pages, start);
  707. struct page *page;
  708. unsigned long swapped = 0;
  709. unsigned long max = end - 1;
  710. rcu_read_lock();
  711. xas_for_each(&xas, page, max) {
  712. if (xas_retry(&xas, page))
  713. continue;
  714. if (xa_is_value(page))
  715. swapped++;
  716. if (xas.xa_index == max)
  717. break;
  718. if (need_resched()) {
  719. xas_pause(&xas);
  720. cond_resched_rcu();
  721. }
  722. }
  723. rcu_read_unlock();
  724. return swapped << PAGE_SHIFT;
  725. }
  726. /*
  727. * Determine (in bytes) how many of the shmem object's pages mapped by the
  728. * given vma is swapped out.
  729. *
  730. * This is safe to call without i_rwsem or the i_pages lock thanks to RCU,
  731. * as long as the inode doesn't go away and racy results are not a problem.
  732. */
  733. unsigned long shmem_swap_usage(struct vm_area_struct *vma)
  734. {
  735. struct inode *inode = file_inode(vma->vm_file);
  736. struct shmem_inode_info *info = SHMEM_I(inode);
  737. struct address_space *mapping = inode->i_mapping;
  738. unsigned long swapped;
  739. /* Be careful as we don't hold info->lock */
  740. swapped = READ_ONCE(info->swapped);
  741. /*
  742. * The easier cases are when the shmem object has nothing in swap, or
  743. * the vma maps it whole. Then we can simply use the stats that we
  744. * already track.
  745. */
  746. if (!swapped)
  747. return 0;
  748. if (!vma->vm_pgoff && vma->vm_end - vma->vm_start >= inode->i_size)
  749. return swapped << PAGE_SHIFT;
  750. /* Here comes the more involved part */
  751. return shmem_partial_swap_usage(mapping, vma->vm_pgoff,
  752. vma->vm_pgoff + vma_pages(vma));
  753. }
  754. /*
  755. * SysV IPC SHM_UNLOCK restore Unevictable pages to their evictable lists.
  756. */
  757. void shmem_unlock_mapping(struct address_space *mapping)
  758. {
  759. struct folio_batch fbatch;
  760. pgoff_t index = 0;
  761. folio_batch_init(&fbatch);
  762. /*
  763. * Minor point, but we might as well stop if someone else SHM_LOCKs it.
  764. */
  765. while (!mapping_unevictable(mapping) &&
  766. filemap_get_folios(mapping, &index, ~0UL, &fbatch)) {
  767. check_move_unevictable_folios(&fbatch);
  768. folio_batch_release(&fbatch);
  769. cond_resched();
  770. }
  771. }
  772. static struct folio *shmem_get_partial_folio(struct inode *inode, pgoff_t index)
  773. {
  774. struct folio *folio;
  775. /*
  776. * At first avoid shmem_get_folio(,,,SGP_READ): that fails
  777. * beyond i_size, and reports fallocated pages as holes.
  778. */
  779. folio = __filemap_get_folio(inode->i_mapping, index,
  780. FGP_ENTRY | FGP_LOCK, 0);
  781. if (!xa_is_value(folio))
  782. return folio;
  783. /*
  784. * But read a page back from swap if any of it is within i_size
  785. * (although in some cases this is just a waste of time).
  786. */
  787. folio = NULL;
  788. shmem_get_folio(inode, index, &folio, SGP_READ);
  789. return folio;
  790. }
  791. /*
  792. * Remove range of pages and swap entries from page cache, and free them.
  793. * If !unfalloc, truncate or punch hole; if unfalloc, undo failed fallocate.
  794. */
  795. static void shmem_undo_range(struct inode *inode, loff_t lstart, loff_t lend,
  796. bool unfalloc)
  797. {
  798. struct address_space *mapping = inode->i_mapping;
  799. struct shmem_inode_info *info = SHMEM_I(inode);
  800. pgoff_t start = (lstart + PAGE_SIZE - 1) >> PAGE_SHIFT;
  801. pgoff_t end = (lend + 1) >> PAGE_SHIFT;
  802. struct folio_batch fbatch;
  803. pgoff_t indices[PAGEVEC_SIZE];
  804. struct folio *folio;
  805. bool same_folio;
  806. long nr_swaps_freed = 0;
  807. pgoff_t index;
  808. int i;
  809. if (lend == -1)
  810. end = -1; /* unsigned, so actually very big */
  811. if (info->fallocend > start && info->fallocend <= end && !unfalloc)
  812. info->fallocend = start;
  813. folio_batch_init(&fbatch);
  814. index = start;
  815. while (index < end && find_lock_entries(mapping, index, end - 1,
  816. &fbatch, indices)) {
  817. for (i = 0; i < folio_batch_count(&fbatch); i++) {
  818. folio = fbatch.folios[i];
  819. index = indices[i];
  820. if (xa_is_value(folio)) {
  821. if (unfalloc)
  822. continue;
  823. nr_swaps_freed += !shmem_free_swap(mapping,
  824. index, folio);
  825. continue;
  826. }
  827. index += folio_nr_pages(folio) - 1;
  828. if (!unfalloc || !folio_test_uptodate(folio))
  829. truncate_inode_folio(mapping, folio);
  830. folio_unlock(folio);
  831. }
  832. folio_batch_remove_exceptionals(&fbatch);
  833. folio_batch_release(&fbatch);
  834. cond_resched();
  835. index++;
  836. }
  837. /*
  838. * When undoing a failed fallocate, we want none of the partial folio
  839. * zeroing and splitting below, but shall want to truncate the whole
  840. * folio when !uptodate indicates that it was added by this fallocate,
  841. * even when [lstart, lend] covers only a part of the folio.
  842. */
  843. if (unfalloc)
  844. goto whole_folios;
  845. same_folio = (lstart >> PAGE_SHIFT) == (lend >> PAGE_SHIFT);
  846. folio = shmem_get_partial_folio(inode, lstart >> PAGE_SHIFT);
  847. if (folio) {
  848. same_folio = lend < folio_pos(folio) + folio_size(folio);
  849. folio_mark_dirty(folio);
  850. if (!truncate_inode_partial_folio(folio, lstart, lend)) {
  851. start = folio->index + folio_nr_pages(folio);
  852. if (same_folio)
  853. end = folio->index;
  854. }
  855. folio_unlock(folio);
  856. folio_put(folio);
  857. folio = NULL;
  858. }
  859. if (!same_folio)
  860. folio = shmem_get_partial_folio(inode, lend >> PAGE_SHIFT);
  861. if (folio) {
  862. folio_mark_dirty(folio);
  863. if (!truncate_inode_partial_folio(folio, lstart, lend))
  864. end = folio->index;
  865. folio_unlock(folio);
  866. folio_put(folio);
  867. }
  868. whole_folios:
  869. index = start;
  870. while (index < end) {
  871. cond_resched();
  872. if (!find_get_entries(mapping, index, end - 1, &fbatch,
  873. indices)) {
  874. /* If all gone or hole-punch or unfalloc, we're done */
  875. if (index == start || end != -1)
  876. break;
  877. /* But if truncating, restart to make sure all gone */
  878. index = start;
  879. continue;
  880. }
  881. for (i = 0; i < folio_batch_count(&fbatch); i++) {
  882. folio = fbatch.folios[i];
  883. index = indices[i];
  884. if (xa_is_value(folio)) {
  885. if (unfalloc)
  886. continue;
  887. if (shmem_free_swap(mapping, index, folio)) {
  888. /* Swap was replaced by page: retry */
  889. index--;
  890. break;
  891. }
  892. nr_swaps_freed++;
  893. continue;
  894. }
  895. folio_lock(folio);
  896. if (!unfalloc || !folio_test_uptodate(folio)) {
  897. if (folio_mapping(folio) != mapping) {
  898. /* Page was replaced by swap: retry */
  899. folio_unlock(folio);
  900. index--;
  901. break;
  902. }
  903. VM_BUG_ON_FOLIO(folio_test_writeback(folio),
  904. folio);
  905. truncate_inode_folio(mapping, folio);
  906. }
  907. index = folio->index + folio_nr_pages(folio) - 1;
  908. folio_unlock(folio);
  909. }
  910. folio_batch_remove_exceptionals(&fbatch);
  911. folio_batch_release(&fbatch);
  912. index++;
  913. }
  914. spin_lock_irq(&info->lock);
  915. info->swapped -= nr_swaps_freed;
  916. shmem_recalc_inode(inode);
  917. spin_unlock_irq(&info->lock);
  918. }
  919. void shmem_truncate_range(struct inode *inode, loff_t lstart, loff_t lend)
  920. {
  921. shmem_undo_range(inode, lstart, lend, false);
  922. inode->i_ctime = inode->i_mtime = current_time(inode);
  923. inode_inc_iversion(inode);
  924. }
  925. EXPORT_SYMBOL_GPL(shmem_truncate_range);
  926. static int shmem_getattr(struct user_namespace *mnt_userns,
  927. const struct path *path, struct kstat *stat,
  928. u32 request_mask, unsigned int query_flags)
  929. {
  930. struct inode *inode = path->dentry->d_inode;
  931. struct shmem_inode_info *info = SHMEM_I(inode);
  932. if (info->alloced - info->swapped != inode->i_mapping->nrpages) {
  933. spin_lock_irq(&info->lock);
  934. shmem_recalc_inode(inode);
  935. spin_unlock_irq(&info->lock);
  936. }
  937. if (info->fsflags & FS_APPEND_FL)
  938. stat->attributes |= STATX_ATTR_APPEND;
  939. if (info->fsflags & FS_IMMUTABLE_FL)
  940. stat->attributes |= STATX_ATTR_IMMUTABLE;
  941. if (info->fsflags & FS_NODUMP_FL)
  942. stat->attributes |= STATX_ATTR_NODUMP;
  943. stat->attributes_mask |= (STATX_ATTR_APPEND |
  944. STATX_ATTR_IMMUTABLE |
  945. STATX_ATTR_NODUMP);
  946. generic_fillattr(&init_user_ns, inode, stat);
  947. if (shmem_is_huge(NULL, inode, 0, false))
  948. stat->blksize = HPAGE_PMD_SIZE;
  949. if (request_mask & STATX_BTIME) {
  950. stat->result_mask |= STATX_BTIME;
  951. stat->btime.tv_sec = info->i_crtime.tv_sec;
  952. stat->btime.tv_nsec = info->i_crtime.tv_nsec;
  953. }
  954. return 0;
  955. }
  956. static int shmem_setattr(struct user_namespace *mnt_userns,
  957. struct dentry *dentry, struct iattr *attr)
  958. {
  959. struct inode *inode = d_inode(dentry);
  960. struct shmem_inode_info *info = SHMEM_I(inode);
  961. int error;
  962. bool update_mtime = false;
  963. bool update_ctime = true;
  964. error = setattr_prepare(&init_user_ns, dentry, attr);
  965. if (error)
  966. return error;
  967. if (S_ISREG(inode->i_mode) && (attr->ia_valid & ATTR_SIZE)) {
  968. loff_t oldsize = inode->i_size;
  969. loff_t newsize = attr->ia_size;
  970. /* protected by i_rwsem */
  971. if ((newsize < oldsize && (info->seals & F_SEAL_SHRINK)) ||
  972. (newsize > oldsize && (info->seals & F_SEAL_GROW)))
  973. return -EPERM;
  974. if (newsize != oldsize) {
  975. error = shmem_reacct_size(SHMEM_I(inode)->flags,
  976. oldsize, newsize);
  977. if (error)
  978. return error;
  979. i_size_write(inode, newsize);
  980. update_mtime = true;
  981. } else {
  982. update_ctime = false;
  983. }
  984. if (newsize <= oldsize) {
  985. loff_t holebegin = round_up(newsize, PAGE_SIZE);
  986. if (oldsize > holebegin)
  987. unmap_mapping_range(inode->i_mapping,
  988. holebegin, 0, 1);
  989. if (info->alloced)
  990. shmem_truncate_range(inode,
  991. newsize, (loff_t)-1);
  992. /* unmap again to remove racily COWed private pages */
  993. if (oldsize > holebegin)
  994. unmap_mapping_range(inode->i_mapping,
  995. holebegin, 0, 1);
  996. }
  997. }
  998. setattr_copy(&init_user_ns, inode, attr);
  999. if (attr->ia_valid & ATTR_MODE)
  1000. error = posix_acl_chmod(&init_user_ns, inode, inode->i_mode);
  1001. if (!error && update_ctime) {
  1002. inode->i_ctime = current_time(inode);
  1003. if (update_mtime)
  1004. inode->i_mtime = inode->i_ctime;
  1005. inode_inc_iversion(inode);
  1006. }
  1007. return error;
  1008. }
  1009. static void shmem_evict_inode(struct inode *inode)
  1010. {
  1011. struct shmem_inode_info *info = SHMEM_I(inode);
  1012. struct shmem_sb_info *sbinfo = SHMEM_SB(inode->i_sb);
  1013. if (shmem_mapping(inode->i_mapping)) {
  1014. shmem_unacct_size(info->flags, inode->i_size);
  1015. inode->i_size = 0;
  1016. mapping_set_exiting(inode->i_mapping);
  1017. shmem_truncate_range(inode, 0, (loff_t)-1);
  1018. if (!list_empty(&info->shrinklist)) {
  1019. spin_lock(&sbinfo->shrinklist_lock);
  1020. if (!list_empty(&info->shrinklist)) {
  1021. list_del_init(&info->shrinklist);
  1022. sbinfo->shrinklist_len--;
  1023. }
  1024. spin_unlock(&sbinfo->shrinklist_lock);
  1025. }
  1026. while (!list_empty(&info->swaplist)) {
  1027. /* Wait while shmem_unuse() is scanning this inode... */
  1028. wait_var_event(&info->stop_eviction,
  1029. !atomic_read(&info->stop_eviction));
  1030. mutex_lock(&shmem_swaplist_mutex);
  1031. /* ...but beware of the race if we peeked too early */
  1032. if (!atomic_read(&info->stop_eviction))
  1033. list_del_init(&info->swaplist);
  1034. mutex_unlock(&shmem_swaplist_mutex);
  1035. }
  1036. }
  1037. simple_xattrs_free(&info->xattrs);
  1038. WARN_ON(inode->i_blocks);
  1039. shmem_free_inode(inode->i_sb);
  1040. clear_inode(inode);
  1041. }
  1042. static int shmem_find_swap_entries(struct address_space *mapping,
  1043. pgoff_t start, struct folio_batch *fbatch,
  1044. pgoff_t *indices, unsigned int type)
  1045. {
  1046. XA_STATE(xas, &mapping->i_pages, start);
  1047. struct folio *folio;
  1048. swp_entry_t entry;
  1049. rcu_read_lock();
  1050. xas_for_each(&xas, folio, ULONG_MAX) {
  1051. if (xas_retry(&xas, folio))
  1052. continue;
  1053. if (!xa_is_value(folio))
  1054. continue;
  1055. entry = radix_to_swp_entry(folio);
  1056. /*
  1057. * swapin error entries can be found in the mapping. But they're
  1058. * deliberately ignored here as we've done everything we can do.
  1059. */
  1060. if (swp_type(entry) != type)
  1061. continue;
  1062. indices[folio_batch_count(fbatch)] = xas.xa_index;
  1063. if (!folio_batch_add(fbatch, folio))
  1064. break;
  1065. if (need_resched()) {
  1066. xas_pause(&xas);
  1067. cond_resched_rcu();
  1068. }
  1069. }
  1070. rcu_read_unlock();
  1071. return xas.xa_index;
  1072. }
  1073. /*
  1074. * Move the swapped pages for an inode to page cache. Returns the count
  1075. * of pages swapped in, or the error in case of failure.
  1076. */
  1077. static int shmem_unuse_swap_entries(struct inode *inode,
  1078. struct folio_batch *fbatch, pgoff_t *indices)
  1079. {
  1080. int i = 0;
  1081. int ret = 0;
  1082. int error = 0;
  1083. struct address_space *mapping = inode->i_mapping;
  1084. for (i = 0; i < folio_batch_count(fbatch); i++) {
  1085. struct folio *folio = fbatch->folios[i];
  1086. if (!xa_is_value(folio))
  1087. continue;
  1088. error = shmem_swapin_folio(inode, indices[i],
  1089. &folio, SGP_CACHE,
  1090. mapping_gfp_mask(mapping),
  1091. NULL, NULL);
  1092. if (error == 0) {
  1093. folio_unlock(folio);
  1094. folio_put(folio);
  1095. ret++;
  1096. }
  1097. if (error == -ENOMEM)
  1098. break;
  1099. error = 0;
  1100. }
  1101. return error ? error : ret;
  1102. }
  1103. /*
  1104. * If swap found in inode, free it and move page from swapcache to filecache.
  1105. */
  1106. static int shmem_unuse_inode(struct inode *inode, unsigned int type)
  1107. {
  1108. struct address_space *mapping = inode->i_mapping;
  1109. pgoff_t start = 0;
  1110. struct folio_batch fbatch;
  1111. pgoff_t indices[PAGEVEC_SIZE];
  1112. int ret = 0;
  1113. do {
  1114. folio_batch_init(&fbatch);
  1115. shmem_find_swap_entries(mapping, start, &fbatch, indices, type);
  1116. if (folio_batch_count(&fbatch) == 0) {
  1117. ret = 0;
  1118. break;
  1119. }
  1120. ret = shmem_unuse_swap_entries(inode, &fbatch, indices);
  1121. if (ret < 0)
  1122. break;
  1123. start = indices[folio_batch_count(&fbatch) - 1];
  1124. } while (true);
  1125. return ret;
  1126. }
  1127. /*
  1128. * Read all the shared memory data that resides in the swap
  1129. * device 'type' back into memory, so the swap device can be
  1130. * unused.
  1131. */
  1132. int shmem_unuse(unsigned int type)
  1133. {
  1134. struct shmem_inode_info *info, *next;
  1135. int error = 0;
  1136. if (list_empty(&shmem_swaplist))
  1137. return 0;
  1138. mutex_lock(&shmem_swaplist_mutex);
  1139. list_for_each_entry_safe(info, next, &shmem_swaplist, swaplist) {
  1140. if (!info->swapped) {
  1141. list_del_init(&info->swaplist);
  1142. continue;
  1143. }
  1144. /*
  1145. * Drop the swaplist mutex while searching the inode for swap;
  1146. * but before doing so, make sure shmem_evict_inode() will not
  1147. * remove placeholder inode from swaplist, nor let it be freed
  1148. * (igrab() would protect from unlink, but not from unmount).
  1149. */
  1150. atomic_inc(&info->stop_eviction);
  1151. mutex_unlock(&shmem_swaplist_mutex);
  1152. error = shmem_unuse_inode(&info->vfs_inode, type);
  1153. cond_resched();
  1154. mutex_lock(&shmem_swaplist_mutex);
  1155. next = list_next_entry(info, swaplist);
  1156. if (!info->swapped)
  1157. list_del_init(&info->swaplist);
  1158. if (atomic_dec_and_test(&info->stop_eviction))
  1159. wake_up_var(&info->stop_eviction);
  1160. if (error)
  1161. break;
  1162. }
  1163. mutex_unlock(&shmem_swaplist_mutex);
  1164. return error;
  1165. }
  1166. /*
  1167. * Move the page from the page cache to the swap cache.
  1168. */
  1169. static int shmem_writepage(struct page *page, struct writeback_control *wbc)
  1170. {
  1171. struct folio *folio = page_folio(page);
  1172. struct shmem_inode_info *info;
  1173. struct address_space *mapping;
  1174. struct inode *inode;
  1175. swp_entry_t swap;
  1176. pgoff_t index;
  1177. /*
  1178. * If /sys/kernel/mm/transparent_hugepage/shmem_enabled is "always" or
  1179. * "force", drivers/gpu/drm/i915/gem/i915_gem_shmem.c gets huge pages,
  1180. * and its shmem_writeback() needs them to be split when swapping.
  1181. */
  1182. if (folio_test_large(folio)) {
  1183. /* Ensure the subpages are still dirty */
  1184. folio_test_set_dirty(folio);
  1185. if (split_huge_page(page) < 0)
  1186. goto redirty;
  1187. folio = page_folio(page);
  1188. folio_clear_dirty(folio);
  1189. }
  1190. BUG_ON(!folio_test_locked(folio));
  1191. mapping = folio->mapping;
  1192. index = folio->index;
  1193. inode = mapping->host;
  1194. info = SHMEM_I(inode);
  1195. if (info->flags & VM_LOCKED)
  1196. goto redirty;
  1197. if (!total_swap_pages)
  1198. goto redirty;
  1199. /*
  1200. * Our capabilities prevent regular writeback or sync from ever calling
  1201. * shmem_writepage; but a stacking filesystem might use ->writepage of
  1202. * its underlying filesystem, in which case tmpfs should write out to
  1203. * swap only in response to memory pressure, and not for the writeback
  1204. * threads or sync.
  1205. */
  1206. if (!wbc->for_reclaim) {
  1207. WARN_ON_ONCE(1); /* Still happens? Tell us about it! */
  1208. goto redirty;
  1209. }
  1210. /*
  1211. * This is somewhat ridiculous, but without plumbing a SWAP_MAP_FALLOC
  1212. * value into swapfile.c, the only way we can correctly account for a
  1213. * fallocated folio arriving here is now to initialize it and write it.
  1214. *
  1215. * That's okay for a folio already fallocated earlier, but if we have
  1216. * not yet completed the fallocation, then (a) we want to keep track
  1217. * of this folio in case we have to undo it, and (b) it may not be a
  1218. * good idea to continue anyway, once we're pushing into swap. So
  1219. * reactivate the folio, and let shmem_fallocate() quit when too many.
  1220. */
  1221. if (!folio_test_uptodate(folio)) {
  1222. if (inode->i_private) {
  1223. struct shmem_falloc *shmem_falloc;
  1224. spin_lock(&inode->i_lock);
  1225. shmem_falloc = inode->i_private;
  1226. if (shmem_falloc &&
  1227. !shmem_falloc->waitq &&
  1228. index >= shmem_falloc->start &&
  1229. index < shmem_falloc->next)
  1230. shmem_falloc->nr_unswapped++;
  1231. else
  1232. shmem_falloc = NULL;
  1233. spin_unlock(&inode->i_lock);
  1234. if (shmem_falloc)
  1235. goto redirty;
  1236. }
  1237. folio_zero_range(folio, 0, folio_size(folio));
  1238. flush_dcache_folio(folio);
  1239. folio_mark_uptodate(folio);
  1240. }
  1241. swap = folio_alloc_swap(folio);
  1242. if (!swap.val)
  1243. goto redirty;
  1244. /*
  1245. * Add inode to shmem_unuse()'s list of swapped-out inodes,
  1246. * if it's not already there. Do it now before the folio is
  1247. * moved to swap cache, when its pagelock no longer protects
  1248. * the inode from eviction. But don't unlock the mutex until
  1249. * we've incremented swapped, because shmem_unuse_inode() will
  1250. * prune a !swapped inode from the swaplist under this mutex.
  1251. */
  1252. mutex_lock(&shmem_swaplist_mutex);
  1253. if (list_empty(&info->swaplist))
  1254. list_add(&info->swaplist, &shmem_swaplist);
  1255. if (add_to_swap_cache(folio, swap,
  1256. __GFP_HIGH | __GFP_NOMEMALLOC | __GFP_NOWARN,
  1257. NULL) == 0) {
  1258. spin_lock_irq(&info->lock);
  1259. shmem_recalc_inode(inode);
  1260. info->swapped++;
  1261. spin_unlock_irq(&info->lock);
  1262. swap_shmem_alloc(swap);
  1263. shmem_delete_from_page_cache(folio, swp_to_radix_entry(swap));
  1264. mutex_unlock(&shmem_swaplist_mutex);
  1265. BUG_ON(folio_mapped(folio));
  1266. swap_writepage(&folio->page, wbc);
  1267. return 0;
  1268. }
  1269. mutex_unlock(&shmem_swaplist_mutex);
  1270. put_swap_folio(folio, swap);
  1271. redirty:
  1272. folio_mark_dirty(folio);
  1273. if (wbc->for_reclaim)
  1274. return AOP_WRITEPAGE_ACTIVATE; /* Return with folio locked */
  1275. folio_unlock(folio);
  1276. return 0;
  1277. }
  1278. #if defined(CONFIG_NUMA) && defined(CONFIG_TMPFS)
  1279. static void shmem_show_mpol(struct seq_file *seq, struct mempolicy *mpol)
  1280. {
  1281. char buffer[64];
  1282. if (!mpol || mpol->mode == MPOL_DEFAULT)
  1283. return; /* show nothing */
  1284. mpol_to_str(buffer, sizeof(buffer), mpol);
  1285. seq_printf(seq, ",mpol=%s", buffer);
  1286. }
  1287. static struct mempolicy *shmem_get_sbmpol(struct shmem_sb_info *sbinfo)
  1288. {
  1289. struct mempolicy *mpol = NULL;
  1290. if (sbinfo->mpol) {
  1291. raw_spin_lock(&sbinfo->stat_lock); /* prevent replace/use races */
  1292. mpol = sbinfo->mpol;
  1293. mpol_get(mpol);
  1294. raw_spin_unlock(&sbinfo->stat_lock);
  1295. }
  1296. return mpol;
  1297. }
  1298. #else /* !CONFIG_NUMA || !CONFIG_TMPFS */
  1299. static inline void shmem_show_mpol(struct seq_file *seq, struct mempolicy *mpol)
  1300. {
  1301. }
  1302. static inline struct mempolicy *shmem_get_sbmpol(struct shmem_sb_info *sbinfo)
  1303. {
  1304. return NULL;
  1305. }
  1306. #endif /* CONFIG_NUMA && CONFIG_TMPFS */
  1307. #ifndef CONFIG_NUMA
  1308. #define vm_policy vm_private_data
  1309. #endif
  1310. static void shmem_pseudo_vma_init(struct vm_area_struct *vma,
  1311. struct shmem_inode_info *info, pgoff_t index)
  1312. {
  1313. /* Create a pseudo vma that just contains the policy */
  1314. vma_init(vma, NULL);
  1315. /* Bias interleave by inode number to distribute better across nodes */
  1316. vma->vm_pgoff = index + info->vfs_inode.i_ino;
  1317. vma->vm_policy = mpol_shared_policy_lookup(&info->policy, index);
  1318. }
  1319. static void shmem_pseudo_vma_destroy(struct vm_area_struct *vma)
  1320. {
  1321. /* Drop reference taken by mpol_shared_policy_lookup() */
  1322. mpol_cond_put(vma->vm_policy);
  1323. }
  1324. static struct folio *shmem_swapin(swp_entry_t swap, gfp_t gfp,
  1325. struct shmem_inode_info *info, pgoff_t index)
  1326. {
  1327. struct vm_area_struct pvma;
  1328. struct page *page;
  1329. struct vm_fault vmf = {
  1330. .vma = &pvma,
  1331. };
  1332. shmem_pseudo_vma_init(&pvma, info, index);
  1333. page = swap_cluster_readahead(swap, gfp, &vmf);
  1334. shmem_pseudo_vma_destroy(&pvma);
  1335. if (!page)
  1336. return NULL;
  1337. return page_folio(page);
  1338. }
  1339. /*
  1340. * Make sure huge_gfp is always more limited than limit_gfp.
  1341. * Some of the flags set permissions, while others set limitations.
  1342. */
  1343. static gfp_t limit_gfp_mask(gfp_t huge_gfp, gfp_t limit_gfp)
  1344. {
  1345. gfp_t allowflags = __GFP_IO | __GFP_FS | __GFP_RECLAIM;
  1346. gfp_t denyflags = __GFP_NOWARN | __GFP_NORETRY;
  1347. gfp_t zoneflags = limit_gfp & GFP_ZONEMASK;
  1348. gfp_t result = huge_gfp & ~(allowflags | GFP_ZONEMASK);
  1349. /* Allow allocations only from the originally specified zones. */
  1350. result |= zoneflags;
  1351. /*
  1352. * Minimize the result gfp by taking the union with the deny flags,
  1353. * and the intersection of the allow flags.
  1354. */
  1355. result |= (limit_gfp & denyflags);
  1356. result |= (huge_gfp & limit_gfp) & allowflags;
  1357. return result;
  1358. }
  1359. static struct folio *shmem_alloc_hugefolio(gfp_t gfp,
  1360. struct shmem_inode_info *info, pgoff_t index)
  1361. {
  1362. struct vm_area_struct pvma;
  1363. struct address_space *mapping = info->vfs_inode.i_mapping;
  1364. pgoff_t hindex;
  1365. struct folio *folio;
  1366. hindex = round_down(index, HPAGE_PMD_NR);
  1367. if (xa_find(&mapping->i_pages, &hindex, hindex + HPAGE_PMD_NR - 1,
  1368. XA_PRESENT))
  1369. return NULL;
  1370. shmem_pseudo_vma_init(&pvma, info, hindex);
  1371. folio = vma_alloc_folio(gfp, HPAGE_PMD_ORDER, &pvma, 0, true);
  1372. shmem_pseudo_vma_destroy(&pvma);
  1373. if (!folio)
  1374. count_vm_event(THP_FILE_FALLBACK);
  1375. return folio;
  1376. }
  1377. static struct folio *shmem_alloc_folio(gfp_t gfp,
  1378. struct shmem_inode_info *info, pgoff_t index)
  1379. {
  1380. struct vm_area_struct pvma;
  1381. struct folio *folio = NULL;
  1382. shmem_pseudo_vma_init(&pvma, info, index);
  1383. trace_android_rvh_shmem_get_folio(info, &folio);
  1384. if (folio)
  1385. goto done;
  1386. folio = vma_alloc_folio(gfp, 0, &pvma, 0, false);
  1387. done:
  1388. shmem_pseudo_vma_destroy(&pvma);
  1389. return folio;
  1390. }
  1391. static struct folio *shmem_alloc_and_acct_folio(gfp_t gfp, struct inode *inode,
  1392. pgoff_t index, bool huge)
  1393. {
  1394. struct shmem_inode_info *info = SHMEM_I(inode);
  1395. struct folio *folio;
  1396. int nr;
  1397. int err = -ENOSPC;
  1398. if (!IS_ENABLED(CONFIG_TRANSPARENT_HUGEPAGE))
  1399. huge = false;
  1400. nr = huge ? HPAGE_PMD_NR : 1;
  1401. if (!shmem_inode_acct_block(inode, nr))
  1402. goto failed;
  1403. if (huge)
  1404. folio = shmem_alloc_hugefolio(gfp, info, index);
  1405. else
  1406. folio = shmem_alloc_folio(gfp, info, index);
  1407. if (folio) {
  1408. __folio_set_locked(folio);
  1409. __folio_set_swapbacked(folio);
  1410. return folio;
  1411. }
  1412. err = -ENOMEM;
  1413. shmem_inode_unacct_blocks(inode, nr);
  1414. failed:
  1415. return ERR_PTR(err);
  1416. }
  1417. /*
  1418. * When a page is moved from swapcache to shmem filecache (either by the
  1419. * usual swapin of shmem_get_folio_gfp(), or by the less common swapoff of
  1420. * shmem_unuse_inode()), it may have been read in earlier from swap, in
  1421. * ignorance of the mapping it belongs to. If that mapping has special
  1422. * constraints (like the gma500 GEM driver, which requires RAM below 4GB),
  1423. * we may need to copy to a suitable page before moving to filecache.
  1424. *
  1425. * In a future release, this may well be extended to respect cpuset and
  1426. * NUMA mempolicy, and applied also to anonymous pages in do_swap_page();
  1427. * but for now it is a simple matter of zone.
  1428. */
  1429. static bool shmem_should_replace_folio(struct folio *folio, gfp_t gfp)
  1430. {
  1431. return folio_zonenum(folio) > gfp_zone(gfp);
  1432. }
  1433. static int shmem_replace_folio(struct folio **foliop, gfp_t gfp,
  1434. struct shmem_inode_info *info, pgoff_t index)
  1435. {
  1436. struct folio *old, *new;
  1437. struct address_space *swap_mapping;
  1438. swp_entry_t entry;
  1439. pgoff_t swap_index;
  1440. int error;
  1441. old = *foliop;
  1442. entry = folio_swap_entry(old);
  1443. swap_index = swp_offset(entry);
  1444. swap_mapping = swap_address_space(entry);
  1445. /*
  1446. * We have arrived here because our zones are constrained, so don't
  1447. * limit chance of success by further cpuset and node constraints.
  1448. */
  1449. gfp &= ~GFP_CONSTRAINT_MASK;
  1450. VM_BUG_ON_FOLIO(folio_test_large(old), old);
  1451. new = shmem_alloc_folio(gfp, info, index);
  1452. if (!new)
  1453. return -ENOMEM;
  1454. folio_get(new);
  1455. folio_copy(new, old);
  1456. flush_dcache_folio(new);
  1457. __folio_set_locked(new);
  1458. __folio_set_swapbacked(new);
  1459. folio_mark_uptodate(new);
  1460. folio_set_swap_entry(new, entry);
  1461. folio_set_swapcache(new);
  1462. /*
  1463. * Our caller will very soon move newpage out of swapcache, but it's
  1464. * a nice clean interface for us to replace oldpage by newpage there.
  1465. */
  1466. xa_lock_irq(&swap_mapping->i_pages);
  1467. error = shmem_replace_entry(swap_mapping, swap_index, old, new);
  1468. if (!error) {
  1469. mem_cgroup_migrate(old, new);
  1470. __lruvec_stat_mod_folio(new, NR_FILE_PAGES, 1);
  1471. __lruvec_stat_mod_folio(new, NR_SHMEM, 1);
  1472. __lruvec_stat_mod_folio(old, NR_FILE_PAGES, -1);
  1473. __lruvec_stat_mod_folio(old, NR_SHMEM, -1);
  1474. }
  1475. xa_unlock_irq(&swap_mapping->i_pages);
  1476. if (unlikely(error)) {
  1477. /*
  1478. * Is this possible? I think not, now that our callers check
  1479. * both PageSwapCache and page_private after getting page lock;
  1480. * but be defensive. Reverse old to newpage for clear and free.
  1481. */
  1482. old = new;
  1483. } else {
  1484. folio_add_lru(new);
  1485. *foliop = new;
  1486. }
  1487. folio_clear_swapcache(old);
  1488. old->private = NULL;
  1489. folio_unlock(old);
  1490. folio_put_refs(old, 2);
  1491. return error;
  1492. }
  1493. static void shmem_set_folio_swapin_error(struct inode *inode, pgoff_t index,
  1494. struct folio *folio, swp_entry_t swap)
  1495. {
  1496. struct address_space *mapping = inode->i_mapping;
  1497. struct shmem_inode_info *info = SHMEM_I(inode);
  1498. swp_entry_t swapin_error;
  1499. void *old;
  1500. swapin_error = make_swapin_error_entry(&folio->page);
  1501. old = xa_cmpxchg_irq(&mapping->i_pages, index,
  1502. swp_to_radix_entry(swap),
  1503. swp_to_radix_entry(swapin_error), 0);
  1504. if (old != swp_to_radix_entry(swap))
  1505. return;
  1506. folio_wait_writeback(folio);
  1507. delete_from_swap_cache(folio);
  1508. spin_lock_irq(&info->lock);
  1509. /*
  1510. * Don't treat swapin error folio as alloced. Otherwise inode->i_blocks won't
  1511. * be 0 when inode is released and thus trigger WARN_ON(inode->i_blocks) in
  1512. * shmem_evict_inode.
  1513. */
  1514. info->alloced--;
  1515. info->swapped--;
  1516. shmem_recalc_inode(inode);
  1517. spin_unlock_irq(&info->lock);
  1518. swap_free(swap);
  1519. }
  1520. /*
  1521. * Swap in the folio pointed to by *foliop.
  1522. * Caller has to make sure that *foliop contains a valid swapped folio.
  1523. * Returns 0 and the folio in foliop if success. On failure, returns the
  1524. * error code and NULL in *foliop.
  1525. */
  1526. static int shmem_swapin_folio(struct inode *inode, pgoff_t index,
  1527. struct folio **foliop, enum sgp_type sgp,
  1528. gfp_t gfp, struct vm_area_struct *vma,
  1529. vm_fault_t *fault_type)
  1530. {
  1531. struct address_space *mapping = inode->i_mapping;
  1532. struct shmem_inode_info *info = SHMEM_I(inode);
  1533. struct mm_struct *charge_mm = vma ? vma->vm_mm : NULL;
  1534. struct folio *folio = NULL;
  1535. swp_entry_t swap;
  1536. int error;
  1537. VM_BUG_ON(!*foliop || !xa_is_value(*foliop));
  1538. swap = radix_to_swp_entry(*foliop);
  1539. *foliop = NULL;
  1540. if (is_swapin_error_entry(swap))
  1541. return -EIO;
  1542. /* Look it up and read it in.. */
  1543. folio = swap_cache_get_folio(swap, NULL, 0);
  1544. if (!folio) {
  1545. /* Or update major stats only when swapin succeeds?? */
  1546. if (fault_type) {
  1547. *fault_type |= VM_FAULT_MAJOR;
  1548. count_vm_event(PGMAJFAULT);
  1549. count_memcg_event_mm(charge_mm, PGMAJFAULT);
  1550. }
  1551. /* Here we actually start the io */
  1552. folio = shmem_swapin(swap, gfp, info, index);
  1553. if (!folio) {
  1554. error = -ENOMEM;
  1555. goto failed;
  1556. }
  1557. }
  1558. /* We have to do this with folio locked to prevent races */
  1559. folio_lock(folio);
  1560. if (!folio_test_swapcache(folio) ||
  1561. folio_swap_entry(folio).val != swap.val ||
  1562. !shmem_confirm_swap(mapping, index, swap)) {
  1563. error = -EEXIST;
  1564. goto unlock;
  1565. }
  1566. if (!folio_test_uptodate(folio)) {
  1567. error = -EIO;
  1568. goto failed;
  1569. }
  1570. folio_wait_writeback(folio);
  1571. /*
  1572. * Some architectures may have to restore extra metadata to the
  1573. * folio after reading from swap.
  1574. */
  1575. arch_swap_restore(swap, folio);
  1576. if (shmem_should_replace_folio(folio, gfp)) {
  1577. error = shmem_replace_folio(&folio, gfp, info, index);
  1578. if (error)
  1579. goto failed;
  1580. }
  1581. error = shmem_add_to_page_cache(folio, mapping, index,
  1582. swp_to_radix_entry(swap), gfp,
  1583. charge_mm);
  1584. if (error)
  1585. goto failed;
  1586. spin_lock_irq(&info->lock);
  1587. info->swapped--;
  1588. shmem_recalc_inode(inode);
  1589. spin_unlock_irq(&info->lock);
  1590. if (sgp == SGP_WRITE)
  1591. folio_mark_accessed(folio);
  1592. delete_from_swap_cache(folio);
  1593. folio_mark_dirty(folio);
  1594. swap_free(swap);
  1595. *foliop = folio;
  1596. return 0;
  1597. failed:
  1598. if (!shmem_confirm_swap(mapping, index, swap))
  1599. error = -EEXIST;
  1600. if (error == -EIO)
  1601. shmem_set_folio_swapin_error(inode, index, folio, swap);
  1602. unlock:
  1603. if (folio) {
  1604. folio_unlock(folio);
  1605. folio_put(folio);
  1606. }
  1607. return error;
  1608. }
  1609. /*
  1610. * shmem_get_folio_gfp - find page in cache, or get from swap, or allocate
  1611. *
  1612. * If we allocate a new one we do not mark it dirty. That's up to the
  1613. * vm. If we swap it in we mark it dirty since we also free the swap
  1614. * entry since a page cannot live in both the swap and page cache.
  1615. *
  1616. * vma, vmf, and fault_type are only supplied by shmem_fault:
  1617. * otherwise they are NULL.
  1618. */
  1619. static int shmem_get_folio_gfp(struct inode *inode, pgoff_t index,
  1620. struct folio **foliop, enum sgp_type sgp, gfp_t gfp,
  1621. struct vm_area_struct *vma, struct vm_fault *vmf,
  1622. vm_fault_t *fault_type)
  1623. {
  1624. struct address_space *mapping = inode->i_mapping;
  1625. struct shmem_inode_info *info = SHMEM_I(inode);
  1626. struct shmem_sb_info *sbinfo;
  1627. struct mm_struct *charge_mm;
  1628. struct folio *folio;
  1629. pgoff_t hindex = index;
  1630. gfp_t huge_gfp;
  1631. int error;
  1632. int once = 0;
  1633. int alloced = 0;
  1634. if (index > (MAX_LFS_FILESIZE >> PAGE_SHIFT))
  1635. return -EFBIG;
  1636. repeat:
  1637. if (sgp <= SGP_CACHE &&
  1638. ((loff_t)index << PAGE_SHIFT) >= i_size_read(inode)) {
  1639. return -EINVAL;
  1640. }
  1641. sbinfo = SHMEM_SB(inode->i_sb);
  1642. charge_mm = vma ? vma->vm_mm : NULL;
  1643. folio = __filemap_get_folio(mapping, index, FGP_ENTRY | FGP_LOCK, 0);
  1644. if (folio && vma && userfaultfd_minor(vma)) {
  1645. if (!xa_is_value(folio)) {
  1646. folio_unlock(folio);
  1647. folio_put(folio);
  1648. }
  1649. *fault_type = handle_userfault(vmf, VM_UFFD_MINOR);
  1650. return 0;
  1651. }
  1652. if (xa_is_value(folio)) {
  1653. error = shmem_swapin_folio(inode, index, &folio,
  1654. sgp, gfp, vma, fault_type);
  1655. if (error == -EEXIST)
  1656. goto repeat;
  1657. *foliop = folio;
  1658. return error;
  1659. }
  1660. if (folio) {
  1661. hindex = folio->index;
  1662. if (sgp == SGP_WRITE)
  1663. folio_mark_accessed(folio);
  1664. if (folio_test_uptodate(folio))
  1665. goto out;
  1666. /* fallocated folio */
  1667. if (sgp != SGP_READ)
  1668. goto clear;
  1669. folio_unlock(folio);
  1670. folio_put(folio);
  1671. }
  1672. /*
  1673. * SGP_READ: succeed on hole, with NULL folio, letting caller zero.
  1674. * SGP_NOALLOC: fail on hole, with NULL folio, letting caller fail.
  1675. */
  1676. *foliop = NULL;
  1677. if (sgp == SGP_READ)
  1678. return 0;
  1679. if (sgp == SGP_NOALLOC)
  1680. return -ENOENT;
  1681. /*
  1682. * Fast cache lookup and swap lookup did not find it: allocate.
  1683. */
  1684. if (vma && userfaultfd_missing(vma)) {
  1685. *fault_type = handle_userfault(vmf, VM_UFFD_MISSING);
  1686. return 0;
  1687. }
  1688. if (!shmem_is_huge(vma, inode, index, false))
  1689. goto alloc_nohuge;
  1690. huge_gfp = vma_thp_gfp_mask(vma);
  1691. huge_gfp = limit_gfp_mask(huge_gfp, gfp);
  1692. folio = shmem_alloc_and_acct_folio(huge_gfp, inode, index, true);
  1693. if (IS_ERR(folio)) {
  1694. alloc_nohuge:
  1695. folio = shmem_alloc_and_acct_folio(gfp, inode, index, false);
  1696. }
  1697. if (IS_ERR(folio)) {
  1698. int retry = 5;
  1699. error = PTR_ERR(folio);
  1700. folio = NULL;
  1701. if (error != -ENOSPC)
  1702. goto unlock;
  1703. /*
  1704. * Try to reclaim some space by splitting a large folio
  1705. * beyond i_size on the filesystem.
  1706. */
  1707. while (retry--) {
  1708. int ret;
  1709. ret = shmem_unused_huge_shrink(sbinfo, NULL, 1);
  1710. if (ret == SHRINK_STOP)
  1711. break;
  1712. if (ret)
  1713. goto alloc_nohuge;
  1714. }
  1715. goto unlock;
  1716. }
  1717. hindex = round_down(index, folio_nr_pages(folio));
  1718. if (sgp == SGP_WRITE)
  1719. __folio_set_referenced(folio);
  1720. error = shmem_add_to_page_cache(folio, mapping, hindex,
  1721. NULL, gfp & GFP_RECLAIM_MASK,
  1722. charge_mm);
  1723. if (error)
  1724. goto unacct;
  1725. folio_add_lru(folio);
  1726. spin_lock_irq(&info->lock);
  1727. info->alloced += folio_nr_pages(folio);
  1728. inode->i_blocks += (blkcnt_t)BLOCKS_PER_PAGE << folio_order(folio);
  1729. shmem_recalc_inode(inode);
  1730. spin_unlock_irq(&info->lock);
  1731. alloced = true;
  1732. if (folio_test_pmd_mappable(folio) &&
  1733. DIV_ROUND_UP(i_size_read(inode), PAGE_SIZE) <
  1734. folio_next_index(folio) - 1) {
  1735. /*
  1736. * Part of the large folio is beyond i_size: subject
  1737. * to shrink under memory pressure.
  1738. */
  1739. spin_lock(&sbinfo->shrinklist_lock);
  1740. /*
  1741. * _careful to defend against unlocked access to
  1742. * ->shrink_list in shmem_unused_huge_shrink()
  1743. */
  1744. if (list_empty_careful(&info->shrinklist)) {
  1745. list_add_tail(&info->shrinklist,
  1746. &sbinfo->shrinklist);
  1747. sbinfo->shrinklist_len++;
  1748. }
  1749. spin_unlock(&sbinfo->shrinklist_lock);
  1750. }
  1751. /*
  1752. * Let SGP_FALLOC use the SGP_WRITE optimization on a new folio.
  1753. */
  1754. if (sgp == SGP_FALLOC)
  1755. sgp = SGP_WRITE;
  1756. clear:
  1757. /*
  1758. * Let SGP_WRITE caller clear ends if write does not fill folio;
  1759. * but SGP_FALLOC on a folio fallocated earlier must initialize
  1760. * it now, lest undo on failure cancel our earlier guarantee.
  1761. */
  1762. if (sgp != SGP_WRITE && !folio_test_uptodate(folio)) {
  1763. long i, n = folio_nr_pages(folio);
  1764. for (i = 0; i < n; i++)
  1765. clear_highpage(folio_page(folio, i));
  1766. flush_dcache_folio(folio);
  1767. folio_mark_uptodate(folio);
  1768. }
  1769. /* Perhaps the file has been truncated since we checked */
  1770. if (sgp <= SGP_CACHE &&
  1771. ((loff_t)index << PAGE_SHIFT) >= i_size_read(inode)) {
  1772. if (alloced) {
  1773. folio_clear_dirty(folio);
  1774. filemap_remove_folio(folio);
  1775. spin_lock_irq(&info->lock);
  1776. shmem_recalc_inode(inode);
  1777. spin_unlock_irq(&info->lock);
  1778. }
  1779. error = -EINVAL;
  1780. goto unlock;
  1781. }
  1782. out:
  1783. *foliop = folio;
  1784. return 0;
  1785. /*
  1786. * Error recovery.
  1787. */
  1788. unacct:
  1789. shmem_inode_unacct_blocks(inode, folio_nr_pages(folio));
  1790. if (folio_test_large(folio)) {
  1791. folio_unlock(folio);
  1792. folio_put(folio);
  1793. goto alloc_nohuge;
  1794. }
  1795. unlock:
  1796. if (folio) {
  1797. folio_unlock(folio);
  1798. folio_put(folio);
  1799. }
  1800. if (error == -ENOSPC && !once++) {
  1801. spin_lock_irq(&info->lock);
  1802. shmem_recalc_inode(inode);
  1803. spin_unlock_irq(&info->lock);
  1804. goto repeat;
  1805. }
  1806. if (error == -EEXIST)
  1807. goto repeat;
  1808. return error;
  1809. }
  1810. int shmem_get_folio(struct inode *inode, pgoff_t index, struct folio **foliop,
  1811. enum sgp_type sgp)
  1812. {
  1813. return shmem_get_folio_gfp(inode, index, foliop, sgp,
  1814. mapping_gfp_mask(inode->i_mapping), NULL, NULL, NULL);
  1815. }
  1816. /*
  1817. * This is like autoremove_wake_function, but it removes the wait queue
  1818. * entry unconditionally - even if something else had already woken the
  1819. * target.
  1820. */
  1821. static int synchronous_wake_function(wait_queue_entry_t *wait, unsigned mode, int sync, void *key)
  1822. {
  1823. int ret = default_wake_function(wait, mode, sync, key);
  1824. list_del_init(&wait->entry);
  1825. return ret;
  1826. }
  1827. static vm_fault_t shmem_fault(struct vm_fault *vmf)
  1828. {
  1829. struct vm_area_struct *vma = vmf->vma;
  1830. struct inode *inode = file_inode(vma->vm_file);
  1831. gfp_t gfp = mapping_gfp_mask(inode->i_mapping);
  1832. struct folio *folio = NULL;
  1833. int err;
  1834. vm_fault_t ret = VM_FAULT_LOCKED;
  1835. /*
  1836. * Trinity finds that probing a hole which tmpfs is punching can
  1837. * prevent the hole-punch from ever completing: which in turn
  1838. * locks writers out with its hold on i_rwsem. So refrain from
  1839. * faulting pages into the hole while it's being punched. Although
  1840. * shmem_undo_range() does remove the additions, it may be unable to
  1841. * keep up, as each new page needs its own unmap_mapping_range() call,
  1842. * and the i_mmap tree grows ever slower to scan if new vmas are added.
  1843. *
  1844. * It does not matter if we sometimes reach this check just before the
  1845. * hole-punch begins, so that one fault then races with the punch:
  1846. * we just need to make racing faults a rare case.
  1847. *
  1848. * The implementation below would be much simpler if we just used a
  1849. * standard mutex or completion: but we cannot take i_rwsem in fault,
  1850. * and bloating every shmem inode for this unlikely case would be sad.
  1851. */
  1852. if (unlikely(inode->i_private)) {
  1853. struct shmem_falloc *shmem_falloc;
  1854. spin_lock(&inode->i_lock);
  1855. shmem_falloc = inode->i_private;
  1856. if (shmem_falloc &&
  1857. shmem_falloc->waitq &&
  1858. vmf->pgoff >= shmem_falloc->start &&
  1859. vmf->pgoff < shmem_falloc->next) {
  1860. struct file *fpin;
  1861. wait_queue_head_t *shmem_falloc_waitq;
  1862. DEFINE_WAIT_FUNC(shmem_fault_wait, synchronous_wake_function);
  1863. ret = VM_FAULT_NOPAGE;
  1864. fpin = maybe_unlock_mmap_for_io(vmf, NULL);
  1865. if (fpin)
  1866. ret = VM_FAULT_RETRY;
  1867. shmem_falloc_waitq = shmem_falloc->waitq;
  1868. prepare_to_wait(shmem_falloc_waitq, &shmem_fault_wait,
  1869. TASK_UNINTERRUPTIBLE);
  1870. spin_unlock(&inode->i_lock);
  1871. schedule();
  1872. /*
  1873. * shmem_falloc_waitq points into the shmem_fallocate()
  1874. * stack of the hole-punching task: shmem_falloc_waitq
  1875. * is usually invalid by the time we reach here, but
  1876. * finish_wait() does not dereference it in that case;
  1877. * though i_lock needed lest racing with wake_up_all().
  1878. */
  1879. spin_lock(&inode->i_lock);
  1880. finish_wait(shmem_falloc_waitq, &shmem_fault_wait);
  1881. spin_unlock(&inode->i_lock);
  1882. if (fpin)
  1883. fput(fpin);
  1884. return ret;
  1885. }
  1886. spin_unlock(&inode->i_lock);
  1887. }
  1888. err = shmem_get_folio_gfp(inode, vmf->pgoff, &folio, SGP_CACHE,
  1889. gfp, vma, vmf, &ret);
  1890. if (err)
  1891. return vmf_error(err);
  1892. if (folio)
  1893. vmf->page = folio_file_page(folio, vmf->pgoff);
  1894. return ret;
  1895. }
  1896. unsigned long shmem_get_unmapped_area(struct file *file,
  1897. unsigned long uaddr, unsigned long len,
  1898. unsigned long pgoff, unsigned long flags)
  1899. {
  1900. unsigned long (*get_area)(struct file *,
  1901. unsigned long, unsigned long, unsigned long, unsigned long);
  1902. unsigned long addr;
  1903. unsigned long offset;
  1904. unsigned long inflated_len;
  1905. unsigned long inflated_addr;
  1906. unsigned long inflated_offset;
  1907. if (len > TASK_SIZE)
  1908. return -ENOMEM;
  1909. get_area = current->mm->get_unmapped_area;
  1910. addr = get_area(file, uaddr, len, pgoff, flags);
  1911. if (!IS_ENABLED(CONFIG_TRANSPARENT_HUGEPAGE))
  1912. return addr;
  1913. if (IS_ERR_VALUE(addr))
  1914. return addr;
  1915. if (addr & ~PAGE_MASK)
  1916. return addr;
  1917. if (addr > TASK_SIZE - len)
  1918. return addr;
  1919. if (shmem_huge == SHMEM_HUGE_DENY)
  1920. return addr;
  1921. if (len < HPAGE_PMD_SIZE)
  1922. return addr;
  1923. if (flags & MAP_FIXED)
  1924. return addr;
  1925. /*
  1926. * Our priority is to support MAP_SHARED mapped hugely;
  1927. * and support MAP_PRIVATE mapped hugely too, until it is COWed.
  1928. * But if caller specified an address hint and we allocated area there
  1929. * successfully, respect that as before.
  1930. */
  1931. if (uaddr == addr)
  1932. return addr;
  1933. if (shmem_huge != SHMEM_HUGE_FORCE) {
  1934. struct super_block *sb;
  1935. if (file) {
  1936. VM_BUG_ON(file->f_op != &shmem_file_operations);
  1937. sb = file_inode(file)->i_sb;
  1938. } else {
  1939. /*
  1940. * Called directly from mm/mmap.c, or drivers/char/mem.c
  1941. * for "/dev/zero", to create a shared anonymous object.
  1942. */
  1943. if (IS_ERR(shm_mnt))
  1944. return addr;
  1945. sb = shm_mnt->mnt_sb;
  1946. }
  1947. if (SHMEM_SB(sb)->huge == SHMEM_HUGE_NEVER)
  1948. return addr;
  1949. }
  1950. offset = (pgoff << PAGE_SHIFT) & (HPAGE_PMD_SIZE-1);
  1951. if (offset && offset + len < 2 * HPAGE_PMD_SIZE)
  1952. return addr;
  1953. if ((addr & (HPAGE_PMD_SIZE-1)) == offset)
  1954. return addr;
  1955. inflated_len = len + HPAGE_PMD_SIZE - PAGE_SIZE;
  1956. if (inflated_len > TASK_SIZE)
  1957. return addr;
  1958. if (inflated_len < len)
  1959. return addr;
  1960. inflated_addr = get_area(NULL, uaddr, inflated_len, 0, flags);
  1961. if (IS_ERR_VALUE(inflated_addr))
  1962. return addr;
  1963. if (inflated_addr & ~PAGE_MASK)
  1964. return addr;
  1965. inflated_offset = inflated_addr & (HPAGE_PMD_SIZE-1);
  1966. inflated_addr += offset - inflated_offset;
  1967. if (inflated_offset > offset)
  1968. inflated_addr += HPAGE_PMD_SIZE;
  1969. if (inflated_addr > TASK_SIZE - len)
  1970. return addr;
  1971. return inflated_addr;
  1972. }
  1973. #ifdef CONFIG_NUMA
  1974. static int shmem_set_policy(struct vm_area_struct *vma, struct mempolicy *mpol)
  1975. {
  1976. struct inode *inode = file_inode(vma->vm_file);
  1977. return mpol_set_shared_policy(&SHMEM_I(inode)->policy, vma, mpol);
  1978. }
  1979. static struct mempolicy *shmem_get_policy(struct vm_area_struct *vma,
  1980. unsigned long addr)
  1981. {
  1982. struct inode *inode = file_inode(vma->vm_file);
  1983. pgoff_t index;
  1984. index = ((addr - vma->vm_start) >> PAGE_SHIFT) + vma->vm_pgoff;
  1985. return mpol_shared_policy_lookup(&SHMEM_I(inode)->policy, index);
  1986. }
  1987. #endif
  1988. int shmem_lock(struct file *file, int lock, struct ucounts *ucounts)
  1989. {
  1990. struct inode *inode = file_inode(file);
  1991. struct shmem_inode_info *info = SHMEM_I(inode);
  1992. int retval = -ENOMEM;
  1993. /*
  1994. * What serializes the accesses to info->flags?
  1995. * ipc_lock_object() when called from shmctl_do_lock(),
  1996. * no serialization needed when called from shm_destroy().
  1997. */
  1998. if (lock && !(info->flags & VM_LOCKED)) {
  1999. if (!user_shm_lock(inode->i_size, ucounts))
  2000. goto out_nomem;
  2001. info->flags |= VM_LOCKED;
  2002. mapping_set_unevictable(file->f_mapping);
  2003. }
  2004. if (!lock && (info->flags & VM_LOCKED) && ucounts) {
  2005. user_shm_unlock(inode->i_size, ucounts);
  2006. info->flags &= ~VM_LOCKED;
  2007. mapping_clear_unevictable(file->f_mapping);
  2008. }
  2009. retval = 0;
  2010. out_nomem:
  2011. return retval;
  2012. }
  2013. static int shmem_mmap(struct file *file, struct vm_area_struct *vma)
  2014. {
  2015. struct shmem_inode_info *info = SHMEM_I(file_inode(file));
  2016. int ret;
  2017. ret = seal_check_future_write(info->seals, vma);
  2018. if (ret)
  2019. return ret;
  2020. /* arm64 - allow memory tagging on RAM-based files */
  2021. vm_flags_set(vma, VM_MTE_ALLOWED);
  2022. file_accessed(file);
  2023. vma->vm_ops = &shmem_vm_ops;
  2024. return 0;
  2025. }
  2026. #ifdef CONFIG_TMPFS_XATTR
  2027. static int shmem_initxattrs(struct inode *, const struct xattr *, void *);
  2028. /*
  2029. * chattr's fsflags are unrelated to extended attributes,
  2030. * but tmpfs has chosen to enable them under the same config option.
  2031. */
  2032. static void shmem_set_inode_flags(struct inode *inode, unsigned int fsflags)
  2033. {
  2034. unsigned int i_flags = 0;
  2035. if (fsflags & FS_NOATIME_FL)
  2036. i_flags |= S_NOATIME;
  2037. if (fsflags & FS_APPEND_FL)
  2038. i_flags |= S_APPEND;
  2039. if (fsflags & FS_IMMUTABLE_FL)
  2040. i_flags |= S_IMMUTABLE;
  2041. /*
  2042. * But FS_NODUMP_FL does not require any action in i_flags.
  2043. */
  2044. inode_set_flags(inode, i_flags, S_NOATIME | S_APPEND | S_IMMUTABLE);
  2045. }
  2046. #else
  2047. static void shmem_set_inode_flags(struct inode *inode, unsigned int fsflags)
  2048. {
  2049. }
  2050. #define shmem_initxattrs NULL
  2051. #endif
  2052. static struct inode *shmem_get_inode(struct super_block *sb, struct inode *dir,
  2053. umode_t mode, dev_t dev, unsigned long flags)
  2054. {
  2055. struct inode *inode;
  2056. struct shmem_inode_info *info;
  2057. struct shmem_sb_info *sbinfo = SHMEM_SB(sb);
  2058. ino_t ino;
  2059. if (shmem_reserve_inode(sb, &ino))
  2060. return NULL;
  2061. inode = new_inode(sb);
  2062. if (inode) {
  2063. inode->i_ino = ino;
  2064. inode_init_owner(&init_user_ns, inode, dir, mode);
  2065. inode->i_blocks = 0;
  2066. inode->i_atime = inode->i_mtime = inode->i_ctime = current_time(inode);
  2067. inode->i_generation = get_random_u32();
  2068. info = SHMEM_I(inode);
  2069. memset(info, 0, (char *)inode - (char *)info);
  2070. android_init_vendor_data(info, 1);
  2071. spin_lock_init(&info->lock);
  2072. atomic_set(&info->stop_eviction, 0);
  2073. info->seals = F_SEAL_SEAL;
  2074. info->flags = flags & VM_NORESERVE;
  2075. info->i_crtime = inode->i_mtime;
  2076. info->fsflags = (dir == NULL) ? 0 :
  2077. SHMEM_I(dir)->fsflags & SHMEM_FL_INHERITED;
  2078. if (info->fsflags)
  2079. shmem_set_inode_flags(inode, info->fsflags);
  2080. INIT_LIST_HEAD(&info->shrinklist);
  2081. INIT_LIST_HEAD(&info->swaplist);
  2082. simple_xattrs_init(&info->xattrs);
  2083. cache_no_acl(inode);
  2084. mapping_set_large_folios(inode->i_mapping);
  2085. switch (mode & S_IFMT) {
  2086. default:
  2087. inode->i_op = &shmem_special_inode_operations;
  2088. init_special_inode(inode, mode, dev);
  2089. break;
  2090. case S_IFREG:
  2091. inode->i_mapping->a_ops = &shmem_aops;
  2092. inode->i_op = &shmem_inode_operations;
  2093. inode->i_fop = &shmem_file_operations;
  2094. mpol_shared_policy_init(&info->policy,
  2095. shmem_get_sbmpol(sbinfo));
  2096. break;
  2097. case S_IFDIR:
  2098. inc_nlink(inode);
  2099. /* Some things misbehave if size == 0 on a directory */
  2100. inode->i_size = 2 * BOGO_DIRENT_SIZE;
  2101. inode->i_op = &shmem_dir_inode_operations;
  2102. inode->i_fop = &simple_dir_operations;
  2103. break;
  2104. case S_IFLNK:
  2105. /*
  2106. * Must not load anything in the rbtree,
  2107. * mpol_free_shared_policy will not be called.
  2108. */
  2109. mpol_shared_policy_init(&info->policy, NULL);
  2110. break;
  2111. }
  2112. lockdep_annotate_inode_mutex_key(inode);
  2113. } else
  2114. shmem_free_inode(sb);
  2115. return inode;
  2116. }
  2117. #ifdef CONFIG_USERFAULTFD
  2118. int shmem_mfill_atomic_pte(struct mm_struct *dst_mm,
  2119. pmd_t *dst_pmd,
  2120. struct vm_area_struct *dst_vma,
  2121. unsigned long dst_addr,
  2122. unsigned long src_addr,
  2123. bool zeropage, bool wp_copy,
  2124. struct page **pagep)
  2125. {
  2126. struct inode *inode = file_inode(dst_vma->vm_file);
  2127. struct shmem_inode_info *info = SHMEM_I(inode);
  2128. struct address_space *mapping = inode->i_mapping;
  2129. gfp_t gfp = mapping_gfp_mask(mapping);
  2130. pgoff_t pgoff = linear_page_index(dst_vma, dst_addr);
  2131. void *page_kaddr;
  2132. struct folio *folio;
  2133. int ret;
  2134. pgoff_t max_off;
  2135. if (!shmem_inode_acct_block(inode, 1)) {
  2136. /*
  2137. * We may have got a page, returned -ENOENT triggering a retry,
  2138. * and now we find ourselves with -ENOMEM. Release the page, to
  2139. * avoid a BUG_ON in our caller.
  2140. */
  2141. if (unlikely(*pagep)) {
  2142. put_page(*pagep);
  2143. *pagep = NULL;
  2144. }
  2145. return -ENOMEM;
  2146. }
  2147. if (!*pagep) {
  2148. ret = -ENOMEM;
  2149. folio = shmem_alloc_folio(gfp, info, pgoff);
  2150. if (!folio)
  2151. goto out_unacct_blocks;
  2152. if (!zeropage) { /* COPY */
  2153. page_kaddr = kmap_local_folio(folio, 0);
  2154. /*
  2155. * The read mmap_lock is held here. Despite the
  2156. * mmap_lock being read recursive a deadlock is still
  2157. * possible if a writer has taken a lock. For example:
  2158. *
  2159. * process A thread 1 takes read lock on own mmap_lock
  2160. * process A thread 2 calls mmap, blocks taking write lock
  2161. * process B thread 1 takes page fault, read lock on own mmap lock
  2162. * process B thread 2 calls mmap, blocks taking write lock
  2163. * process A thread 1 blocks taking read lock on process B
  2164. * process B thread 1 blocks taking read lock on process A
  2165. *
  2166. * Disable page faults to prevent potential deadlock
  2167. * and retry the copy outside the mmap_lock.
  2168. */
  2169. pagefault_disable();
  2170. ret = copy_from_user(page_kaddr,
  2171. (const void __user *)src_addr,
  2172. PAGE_SIZE);
  2173. pagefault_enable();
  2174. kunmap_local(page_kaddr);
  2175. /* fallback to copy_from_user outside mmap_lock */
  2176. if (unlikely(ret)) {
  2177. *pagep = &folio->page;
  2178. ret = -ENOENT;
  2179. /* don't free the page */
  2180. goto out_unacct_blocks;
  2181. }
  2182. flush_dcache_folio(folio);
  2183. } else { /* ZEROPAGE */
  2184. clear_user_highpage(&folio->page, dst_addr);
  2185. }
  2186. } else {
  2187. folio = page_folio(*pagep);
  2188. VM_BUG_ON_FOLIO(folio_test_large(folio), folio);
  2189. *pagep = NULL;
  2190. }
  2191. VM_BUG_ON(folio_test_locked(folio));
  2192. VM_BUG_ON(folio_test_swapbacked(folio));
  2193. __folio_set_locked(folio);
  2194. __folio_set_swapbacked(folio);
  2195. __folio_mark_uptodate(folio);
  2196. ret = -EFAULT;
  2197. max_off = DIV_ROUND_UP(i_size_read(inode), PAGE_SIZE);
  2198. if (unlikely(pgoff >= max_off))
  2199. goto out_release;
  2200. ret = shmem_add_to_page_cache(folio, mapping, pgoff, NULL,
  2201. gfp & GFP_RECLAIM_MASK, dst_mm);
  2202. if (ret)
  2203. goto out_release;
  2204. ret = mfill_atomic_install_pte(dst_mm, dst_pmd, dst_vma, dst_addr,
  2205. &folio->page, true, wp_copy);
  2206. if (ret)
  2207. goto out_delete_from_cache;
  2208. spin_lock_irq(&info->lock);
  2209. info->alloced++;
  2210. inode->i_blocks += BLOCKS_PER_PAGE;
  2211. shmem_recalc_inode(inode);
  2212. spin_unlock_irq(&info->lock);
  2213. folio_unlock(folio);
  2214. return 0;
  2215. out_delete_from_cache:
  2216. filemap_remove_folio(folio);
  2217. out_release:
  2218. folio_unlock(folio);
  2219. folio_put(folio);
  2220. out_unacct_blocks:
  2221. shmem_inode_unacct_blocks(inode, 1);
  2222. return ret;
  2223. }
  2224. #endif /* CONFIG_USERFAULTFD */
  2225. #ifdef CONFIG_TMPFS
  2226. static const struct inode_operations shmem_symlink_inode_operations;
  2227. static const struct inode_operations shmem_short_symlink_operations;
  2228. static int
  2229. shmem_write_begin(struct file *file, struct address_space *mapping,
  2230. loff_t pos, unsigned len,
  2231. struct page **pagep, void **fsdata)
  2232. {
  2233. struct inode *inode = mapping->host;
  2234. struct shmem_inode_info *info = SHMEM_I(inode);
  2235. pgoff_t index = pos >> PAGE_SHIFT;
  2236. struct folio *folio;
  2237. int ret = 0;
  2238. /* i_rwsem is held by caller */
  2239. if (unlikely(info->seals & (F_SEAL_GROW |
  2240. F_SEAL_WRITE | F_SEAL_FUTURE_WRITE))) {
  2241. if (info->seals & (F_SEAL_WRITE | F_SEAL_FUTURE_WRITE))
  2242. return -EPERM;
  2243. if ((info->seals & F_SEAL_GROW) && pos + len > inode->i_size)
  2244. return -EPERM;
  2245. }
  2246. ret = shmem_get_folio(inode, index, &folio, SGP_WRITE);
  2247. if (ret)
  2248. return ret;
  2249. *pagep = folio_file_page(folio, index);
  2250. if (PageHWPoison(*pagep)) {
  2251. folio_unlock(folio);
  2252. folio_put(folio);
  2253. *pagep = NULL;
  2254. return -EIO;
  2255. }
  2256. return 0;
  2257. }
  2258. static int
  2259. shmem_write_end(struct file *file, struct address_space *mapping,
  2260. loff_t pos, unsigned len, unsigned copied,
  2261. struct page *page, void *fsdata)
  2262. {
  2263. struct inode *inode = mapping->host;
  2264. if (pos + copied > inode->i_size)
  2265. i_size_write(inode, pos + copied);
  2266. if (!PageUptodate(page)) {
  2267. struct page *head = compound_head(page);
  2268. if (PageTransCompound(page)) {
  2269. int i;
  2270. for (i = 0; i < HPAGE_PMD_NR; i++) {
  2271. if (head + i == page)
  2272. continue;
  2273. clear_highpage(head + i);
  2274. flush_dcache_page(head + i);
  2275. }
  2276. }
  2277. if (copied < PAGE_SIZE) {
  2278. unsigned from = pos & (PAGE_SIZE - 1);
  2279. zero_user_segments(page, 0, from,
  2280. from + copied, PAGE_SIZE);
  2281. }
  2282. SetPageUptodate(head);
  2283. }
  2284. set_page_dirty(page);
  2285. unlock_page(page);
  2286. put_page(page);
  2287. return copied;
  2288. }
  2289. static ssize_t shmem_file_read_iter(struct kiocb *iocb, struct iov_iter *to)
  2290. {
  2291. struct file *file = iocb->ki_filp;
  2292. struct inode *inode = file_inode(file);
  2293. struct address_space *mapping = inode->i_mapping;
  2294. pgoff_t index;
  2295. unsigned long offset;
  2296. int error = 0;
  2297. ssize_t retval = 0;
  2298. loff_t *ppos = &iocb->ki_pos;
  2299. index = *ppos >> PAGE_SHIFT;
  2300. offset = *ppos & ~PAGE_MASK;
  2301. for (;;) {
  2302. struct folio *folio = NULL;
  2303. struct page *page = NULL;
  2304. pgoff_t end_index;
  2305. unsigned long nr, ret;
  2306. loff_t i_size = i_size_read(inode);
  2307. end_index = i_size >> PAGE_SHIFT;
  2308. if (index > end_index)
  2309. break;
  2310. if (index == end_index) {
  2311. nr = i_size & ~PAGE_MASK;
  2312. if (nr <= offset)
  2313. break;
  2314. }
  2315. error = shmem_get_folio(inode, index, &folio, SGP_READ);
  2316. if (error) {
  2317. if (error == -EINVAL)
  2318. error = 0;
  2319. break;
  2320. }
  2321. if (folio) {
  2322. folio_unlock(folio);
  2323. page = folio_file_page(folio, index);
  2324. if (PageHWPoison(page)) {
  2325. folio_put(folio);
  2326. error = -EIO;
  2327. break;
  2328. }
  2329. }
  2330. /*
  2331. * We must evaluate after, since reads (unlike writes)
  2332. * are called without i_rwsem protection against truncate
  2333. */
  2334. nr = PAGE_SIZE;
  2335. i_size = i_size_read(inode);
  2336. end_index = i_size >> PAGE_SHIFT;
  2337. if (index == end_index) {
  2338. nr = i_size & ~PAGE_MASK;
  2339. if (nr <= offset) {
  2340. if (folio)
  2341. folio_put(folio);
  2342. break;
  2343. }
  2344. }
  2345. nr -= offset;
  2346. if (folio) {
  2347. /*
  2348. * If users can be writing to this page using arbitrary
  2349. * virtual addresses, take care about potential aliasing
  2350. * before reading the page on the kernel side.
  2351. */
  2352. if (mapping_writably_mapped(mapping))
  2353. flush_dcache_page(page);
  2354. /*
  2355. * Mark the page accessed if we read the beginning.
  2356. */
  2357. if (!offset)
  2358. folio_mark_accessed(folio);
  2359. /*
  2360. * Ok, we have the page, and it's up-to-date, so
  2361. * now we can copy it to user space...
  2362. */
  2363. ret = copy_page_to_iter(page, offset, nr, to);
  2364. folio_put(folio);
  2365. } else if (user_backed_iter(to)) {
  2366. /*
  2367. * Copy to user tends to be so well optimized, but
  2368. * clear_user() not so much, that it is noticeably
  2369. * faster to copy the zero page instead of clearing.
  2370. */
  2371. ret = copy_page_to_iter(ZERO_PAGE(0), offset, nr, to);
  2372. } else {
  2373. /*
  2374. * But submitting the same page twice in a row to
  2375. * splice() - or others? - can result in confusion:
  2376. * so don't attempt that optimization on pipes etc.
  2377. */
  2378. ret = iov_iter_zero(nr, to);
  2379. }
  2380. retval += ret;
  2381. offset += ret;
  2382. index += offset >> PAGE_SHIFT;
  2383. offset &= ~PAGE_MASK;
  2384. if (!iov_iter_count(to))
  2385. break;
  2386. if (ret < nr) {
  2387. error = -EFAULT;
  2388. break;
  2389. }
  2390. cond_resched();
  2391. }
  2392. *ppos = ((loff_t) index << PAGE_SHIFT) + offset;
  2393. file_accessed(file);
  2394. return retval ? retval : error;
  2395. }
  2396. static loff_t shmem_file_llseek(struct file *file, loff_t offset, int whence)
  2397. {
  2398. struct address_space *mapping = file->f_mapping;
  2399. struct inode *inode = mapping->host;
  2400. if (whence != SEEK_DATA && whence != SEEK_HOLE)
  2401. return generic_file_llseek_size(file, offset, whence,
  2402. MAX_LFS_FILESIZE, i_size_read(inode));
  2403. if (offset < 0)
  2404. return -ENXIO;
  2405. inode_lock(inode);
  2406. /* We're holding i_rwsem so we can access i_size directly */
  2407. offset = mapping_seek_hole_data(mapping, offset, inode->i_size, whence);
  2408. if (offset >= 0)
  2409. offset = vfs_setpos(file, offset, MAX_LFS_FILESIZE);
  2410. inode_unlock(inode);
  2411. return offset;
  2412. }
  2413. static long shmem_fallocate(struct file *file, int mode, loff_t offset,
  2414. loff_t len)
  2415. {
  2416. struct inode *inode = file_inode(file);
  2417. struct shmem_sb_info *sbinfo = SHMEM_SB(inode->i_sb);
  2418. struct shmem_inode_info *info = SHMEM_I(inode);
  2419. struct shmem_falloc shmem_falloc;
  2420. pgoff_t start, index, end, undo_fallocend;
  2421. int error;
  2422. if (mode & ~(FALLOC_FL_KEEP_SIZE | FALLOC_FL_PUNCH_HOLE))
  2423. return -EOPNOTSUPP;
  2424. inode_lock(inode);
  2425. if (mode & FALLOC_FL_PUNCH_HOLE) {
  2426. struct address_space *mapping = file->f_mapping;
  2427. loff_t unmap_start = round_up(offset, PAGE_SIZE);
  2428. loff_t unmap_end = round_down(offset + len, PAGE_SIZE) - 1;
  2429. DECLARE_WAIT_QUEUE_HEAD_ONSTACK(shmem_falloc_waitq);
  2430. /* protected by i_rwsem */
  2431. if (info->seals & (F_SEAL_WRITE | F_SEAL_FUTURE_WRITE)) {
  2432. error = -EPERM;
  2433. goto out;
  2434. }
  2435. shmem_falloc.waitq = &shmem_falloc_waitq;
  2436. shmem_falloc.start = (u64)unmap_start >> PAGE_SHIFT;
  2437. shmem_falloc.next = (unmap_end + 1) >> PAGE_SHIFT;
  2438. spin_lock(&inode->i_lock);
  2439. inode->i_private = &shmem_falloc;
  2440. spin_unlock(&inode->i_lock);
  2441. if ((u64)unmap_end > (u64)unmap_start)
  2442. unmap_mapping_range(mapping, unmap_start,
  2443. 1 + unmap_end - unmap_start, 0);
  2444. shmem_truncate_range(inode, offset, offset + len - 1);
  2445. /* No need to unmap again: hole-punching leaves COWed pages */
  2446. spin_lock(&inode->i_lock);
  2447. inode->i_private = NULL;
  2448. wake_up_all(&shmem_falloc_waitq);
  2449. WARN_ON_ONCE(!list_empty(&shmem_falloc_waitq.head));
  2450. spin_unlock(&inode->i_lock);
  2451. error = 0;
  2452. goto out;
  2453. }
  2454. /* We need to check rlimit even when FALLOC_FL_KEEP_SIZE */
  2455. error = inode_newsize_ok(inode, offset + len);
  2456. if (error)
  2457. goto out;
  2458. if ((info->seals & F_SEAL_GROW) && offset + len > inode->i_size) {
  2459. error = -EPERM;
  2460. goto out;
  2461. }
  2462. start = offset >> PAGE_SHIFT;
  2463. end = (offset + len + PAGE_SIZE - 1) >> PAGE_SHIFT;
  2464. /* Try to avoid a swapstorm if len is impossible to satisfy */
  2465. if (sbinfo->max_blocks && end - start > sbinfo->max_blocks) {
  2466. error = -ENOSPC;
  2467. goto out;
  2468. }
  2469. shmem_falloc.waitq = NULL;
  2470. shmem_falloc.start = start;
  2471. shmem_falloc.next = start;
  2472. shmem_falloc.nr_falloced = 0;
  2473. shmem_falloc.nr_unswapped = 0;
  2474. spin_lock(&inode->i_lock);
  2475. inode->i_private = &shmem_falloc;
  2476. spin_unlock(&inode->i_lock);
  2477. /*
  2478. * info->fallocend is only relevant when huge pages might be
  2479. * involved: to prevent split_huge_page() freeing fallocated
  2480. * pages when FALLOC_FL_KEEP_SIZE committed beyond i_size.
  2481. */
  2482. undo_fallocend = info->fallocend;
  2483. if (info->fallocend < end)
  2484. info->fallocend = end;
  2485. for (index = start; index < end; ) {
  2486. struct folio *folio;
  2487. /*
  2488. * Good, the fallocate(2) manpage permits EINTR: we may have
  2489. * been interrupted because we are using up too much memory.
  2490. */
  2491. if (signal_pending(current))
  2492. error = -EINTR;
  2493. else if (shmem_falloc.nr_unswapped > shmem_falloc.nr_falloced)
  2494. error = -ENOMEM;
  2495. else
  2496. error = shmem_get_folio(inode, index, &folio,
  2497. SGP_FALLOC);
  2498. if (error) {
  2499. info->fallocend = undo_fallocend;
  2500. /* Remove the !uptodate folios we added */
  2501. if (index > start) {
  2502. shmem_undo_range(inode,
  2503. (loff_t)start << PAGE_SHIFT,
  2504. ((loff_t)index << PAGE_SHIFT) - 1, true);
  2505. }
  2506. goto undone;
  2507. }
  2508. /*
  2509. * Here is a more important optimization than it appears:
  2510. * a second SGP_FALLOC on the same large folio will clear it,
  2511. * making it uptodate and un-undoable if we fail later.
  2512. */
  2513. index = folio_next_index(folio);
  2514. /* Beware 32-bit wraparound */
  2515. if (!index)
  2516. index--;
  2517. /*
  2518. * Inform shmem_writepage() how far we have reached.
  2519. * No need for lock or barrier: we have the page lock.
  2520. */
  2521. if (!folio_test_uptodate(folio))
  2522. shmem_falloc.nr_falloced += index - shmem_falloc.next;
  2523. shmem_falloc.next = index;
  2524. /*
  2525. * If !uptodate, leave it that way so that freeable folios
  2526. * can be recognized if we need to rollback on error later.
  2527. * But mark it dirty so that memory pressure will swap rather
  2528. * than free the folios we are allocating (and SGP_CACHE folios
  2529. * might still be clean: we now need to mark those dirty too).
  2530. */
  2531. folio_mark_dirty(folio);
  2532. folio_unlock(folio);
  2533. folio_put(folio);
  2534. cond_resched();
  2535. }
  2536. if (!(mode & FALLOC_FL_KEEP_SIZE) && offset + len > inode->i_size)
  2537. i_size_write(inode, offset + len);
  2538. undone:
  2539. spin_lock(&inode->i_lock);
  2540. inode->i_private = NULL;
  2541. spin_unlock(&inode->i_lock);
  2542. out:
  2543. if (!error)
  2544. file_modified(file);
  2545. inode_unlock(inode);
  2546. return error;
  2547. }
  2548. static int shmem_statfs(struct dentry *dentry, struct kstatfs *buf)
  2549. {
  2550. struct shmem_sb_info *sbinfo = SHMEM_SB(dentry->d_sb);
  2551. buf->f_type = TMPFS_MAGIC;
  2552. buf->f_bsize = PAGE_SIZE;
  2553. buf->f_namelen = NAME_MAX;
  2554. if (sbinfo->max_blocks) {
  2555. buf->f_blocks = sbinfo->max_blocks;
  2556. buf->f_bavail =
  2557. buf->f_bfree = sbinfo->max_blocks -
  2558. percpu_counter_sum(&sbinfo->used_blocks);
  2559. }
  2560. if (sbinfo->max_inodes) {
  2561. buf->f_files = sbinfo->max_inodes;
  2562. buf->f_ffree = sbinfo->free_inodes;
  2563. }
  2564. /* else leave those fields 0 like simple_statfs */
  2565. buf->f_fsid = uuid_to_fsid(dentry->d_sb->s_uuid.b);
  2566. return 0;
  2567. }
  2568. /*
  2569. * File creation. Allocate an inode, and we're done..
  2570. */
  2571. static int
  2572. shmem_mknod(struct user_namespace *mnt_userns, struct inode *dir,
  2573. struct dentry *dentry, umode_t mode, dev_t dev)
  2574. {
  2575. struct inode *inode;
  2576. int error = -ENOSPC;
  2577. inode = shmem_get_inode(dir->i_sb, dir, mode, dev, VM_NORESERVE);
  2578. if (inode) {
  2579. error = simple_acl_create(dir, inode);
  2580. if (error)
  2581. goto out_iput;
  2582. error = security_inode_init_security(inode, dir,
  2583. &dentry->d_name,
  2584. shmem_initxattrs, NULL);
  2585. if (error && error != -EOPNOTSUPP)
  2586. goto out_iput;
  2587. error = 0;
  2588. dir->i_size += BOGO_DIRENT_SIZE;
  2589. dir->i_ctime = dir->i_mtime = current_time(dir);
  2590. inode_inc_iversion(dir);
  2591. d_instantiate(dentry, inode);
  2592. dget(dentry); /* Extra count - pin the dentry in core */
  2593. }
  2594. return error;
  2595. out_iput:
  2596. iput(inode);
  2597. return error;
  2598. }
  2599. static int
  2600. shmem_tmpfile(struct user_namespace *mnt_userns, struct inode *dir,
  2601. struct file *file, umode_t mode)
  2602. {
  2603. struct inode *inode;
  2604. int error = -ENOSPC;
  2605. inode = shmem_get_inode(dir->i_sb, dir, mode, 0, VM_NORESERVE);
  2606. if (inode) {
  2607. error = security_inode_init_security(inode, dir,
  2608. NULL,
  2609. shmem_initxattrs, NULL);
  2610. if (error && error != -EOPNOTSUPP)
  2611. goto out_iput;
  2612. error = simple_acl_create(dir, inode);
  2613. if (error)
  2614. goto out_iput;
  2615. d_tmpfile(file, inode);
  2616. }
  2617. return finish_open_simple(file, error);
  2618. out_iput:
  2619. iput(inode);
  2620. return error;
  2621. }
  2622. static int shmem_mkdir(struct user_namespace *mnt_userns, struct inode *dir,
  2623. struct dentry *dentry, umode_t mode)
  2624. {
  2625. int error;
  2626. if ((error = shmem_mknod(&init_user_ns, dir, dentry,
  2627. mode | S_IFDIR, 0)))
  2628. return error;
  2629. inc_nlink(dir);
  2630. return 0;
  2631. }
  2632. static int shmem_create(struct user_namespace *mnt_userns, struct inode *dir,
  2633. struct dentry *dentry, umode_t mode, bool excl)
  2634. {
  2635. return shmem_mknod(&init_user_ns, dir, dentry, mode | S_IFREG, 0);
  2636. }
  2637. /*
  2638. * Link a file..
  2639. */
  2640. static int shmem_link(struct dentry *old_dentry, struct inode *dir, struct dentry *dentry)
  2641. {
  2642. struct inode *inode = d_inode(old_dentry);
  2643. int ret = 0;
  2644. /*
  2645. * No ordinary (disk based) filesystem counts links as inodes;
  2646. * but each new link needs a new dentry, pinning lowmem, and
  2647. * tmpfs dentries cannot be pruned until they are unlinked.
  2648. * But if an O_TMPFILE file is linked into the tmpfs, the
  2649. * first link must skip that, to get the accounting right.
  2650. */
  2651. if (inode->i_nlink) {
  2652. ret = shmem_reserve_inode(inode->i_sb, NULL);
  2653. if (ret)
  2654. goto out;
  2655. }
  2656. dir->i_size += BOGO_DIRENT_SIZE;
  2657. inode->i_ctime = dir->i_ctime = dir->i_mtime = current_time(inode);
  2658. inode_inc_iversion(dir);
  2659. inc_nlink(inode);
  2660. ihold(inode); /* New dentry reference */
  2661. dget(dentry); /* Extra pinning count for the created dentry */
  2662. d_instantiate(dentry, inode);
  2663. out:
  2664. return ret;
  2665. }
  2666. static int shmem_unlink(struct inode *dir, struct dentry *dentry)
  2667. {
  2668. struct inode *inode = d_inode(dentry);
  2669. if (inode->i_nlink > 1 && !S_ISDIR(inode->i_mode))
  2670. shmem_free_inode(inode->i_sb);
  2671. dir->i_size -= BOGO_DIRENT_SIZE;
  2672. inode->i_ctime = dir->i_ctime = dir->i_mtime = current_time(inode);
  2673. inode_inc_iversion(dir);
  2674. drop_nlink(inode);
  2675. dput(dentry); /* Undo the count from "create" - this does all the work */
  2676. return 0;
  2677. }
  2678. static int shmem_rmdir(struct inode *dir, struct dentry *dentry)
  2679. {
  2680. if (!simple_empty(dentry))
  2681. return -ENOTEMPTY;
  2682. drop_nlink(d_inode(dentry));
  2683. drop_nlink(dir);
  2684. return shmem_unlink(dir, dentry);
  2685. }
  2686. static int shmem_whiteout(struct user_namespace *mnt_userns,
  2687. struct inode *old_dir, struct dentry *old_dentry)
  2688. {
  2689. struct dentry *whiteout;
  2690. int error;
  2691. whiteout = d_alloc(old_dentry->d_parent, &old_dentry->d_name);
  2692. if (!whiteout)
  2693. return -ENOMEM;
  2694. error = shmem_mknod(&init_user_ns, old_dir, whiteout,
  2695. S_IFCHR | WHITEOUT_MODE, WHITEOUT_DEV);
  2696. dput(whiteout);
  2697. if (error)
  2698. return error;
  2699. /*
  2700. * Cheat and hash the whiteout while the old dentry is still in
  2701. * place, instead of playing games with FS_RENAME_DOES_D_MOVE.
  2702. *
  2703. * d_lookup() will consistently find one of them at this point,
  2704. * not sure which one, but that isn't even important.
  2705. */
  2706. d_rehash(whiteout);
  2707. return 0;
  2708. }
  2709. /*
  2710. * The VFS layer already does all the dentry stuff for rename,
  2711. * we just have to decrement the usage count for the target if
  2712. * it exists so that the VFS layer correctly free's it when it
  2713. * gets overwritten.
  2714. */
  2715. static int shmem_rename2(struct user_namespace *mnt_userns,
  2716. struct inode *old_dir, struct dentry *old_dentry,
  2717. struct inode *new_dir, struct dentry *new_dentry,
  2718. unsigned int flags)
  2719. {
  2720. struct inode *inode = d_inode(old_dentry);
  2721. int they_are_dirs = S_ISDIR(inode->i_mode);
  2722. if (flags & ~(RENAME_NOREPLACE | RENAME_EXCHANGE | RENAME_WHITEOUT))
  2723. return -EINVAL;
  2724. if (flags & RENAME_EXCHANGE)
  2725. return simple_rename_exchange(old_dir, old_dentry, new_dir, new_dentry);
  2726. if (!simple_empty(new_dentry))
  2727. return -ENOTEMPTY;
  2728. if (flags & RENAME_WHITEOUT) {
  2729. int error;
  2730. error = shmem_whiteout(&init_user_ns, old_dir, old_dentry);
  2731. if (error)
  2732. return error;
  2733. }
  2734. if (d_really_is_positive(new_dentry)) {
  2735. (void) shmem_unlink(new_dir, new_dentry);
  2736. if (they_are_dirs) {
  2737. drop_nlink(d_inode(new_dentry));
  2738. drop_nlink(old_dir);
  2739. }
  2740. } else if (they_are_dirs) {
  2741. drop_nlink(old_dir);
  2742. inc_nlink(new_dir);
  2743. }
  2744. old_dir->i_size -= BOGO_DIRENT_SIZE;
  2745. new_dir->i_size += BOGO_DIRENT_SIZE;
  2746. old_dir->i_ctime = old_dir->i_mtime =
  2747. new_dir->i_ctime = new_dir->i_mtime =
  2748. inode->i_ctime = current_time(old_dir);
  2749. inode_inc_iversion(old_dir);
  2750. inode_inc_iversion(new_dir);
  2751. return 0;
  2752. }
  2753. static int shmem_symlink(struct user_namespace *mnt_userns, struct inode *dir,
  2754. struct dentry *dentry, const char *symname)
  2755. {
  2756. int error;
  2757. int len;
  2758. struct inode *inode;
  2759. struct folio *folio;
  2760. len = strlen(symname) + 1;
  2761. if (len > PAGE_SIZE)
  2762. return -ENAMETOOLONG;
  2763. inode = shmem_get_inode(dir->i_sb, dir, S_IFLNK | 0777, 0,
  2764. VM_NORESERVE);
  2765. if (!inode)
  2766. return -ENOSPC;
  2767. error = security_inode_init_security(inode, dir, &dentry->d_name,
  2768. shmem_initxattrs, NULL);
  2769. if (error && error != -EOPNOTSUPP) {
  2770. iput(inode);
  2771. return error;
  2772. }
  2773. inode->i_size = len-1;
  2774. if (len <= SHORT_SYMLINK_LEN) {
  2775. inode->i_link = kmemdup(symname, len, GFP_KERNEL);
  2776. if (!inode->i_link) {
  2777. iput(inode);
  2778. return -ENOMEM;
  2779. }
  2780. inode->i_op = &shmem_short_symlink_operations;
  2781. } else {
  2782. inode_nohighmem(inode);
  2783. error = shmem_get_folio(inode, 0, &folio, SGP_WRITE);
  2784. if (error) {
  2785. iput(inode);
  2786. return error;
  2787. }
  2788. inode->i_mapping->a_ops = &shmem_aops;
  2789. inode->i_op = &shmem_symlink_inode_operations;
  2790. memcpy(folio_address(folio), symname, len);
  2791. folio_mark_uptodate(folio);
  2792. folio_mark_dirty(folio);
  2793. folio_unlock(folio);
  2794. folio_put(folio);
  2795. }
  2796. dir->i_size += BOGO_DIRENT_SIZE;
  2797. dir->i_ctime = dir->i_mtime = current_time(dir);
  2798. inode_inc_iversion(dir);
  2799. d_instantiate(dentry, inode);
  2800. dget(dentry);
  2801. return 0;
  2802. }
  2803. static void shmem_put_link(void *arg)
  2804. {
  2805. folio_mark_accessed(arg);
  2806. folio_put(arg);
  2807. }
  2808. static const char *shmem_get_link(struct dentry *dentry,
  2809. struct inode *inode,
  2810. struct delayed_call *done)
  2811. {
  2812. struct folio *folio = NULL;
  2813. int error;
  2814. if (!dentry) {
  2815. folio = filemap_get_folio(inode->i_mapping, 0);
  2816. if (!folio)
  2817. return ERR_PTR(-ECHILD);
  2818. if (PageHWPoison(folio_page(folio, 0)) ||
  2819. !folio_test_uptodate(folio)) {
  2820. folio_put(folio);
  2821. return ERR_PTR(-ECHILD);
  2822. }
  2823. } else {
  2824. error = shmem_get_folio(inode, 0, &folio, SGP_READ);
  2825. if (error)
  2826. return ERR_PTR(error);
  2827. if (!folio)
  2828. return ERR_PTR(-ECHILD);
  2829. if (PageHWPoison(folio_page(folio, 0))) {
  2830. folio_unlock(folio);
  2831. folio_put(folio);
  2832. return ERR_PTR(-ECHILD);
  2833. }
  2834. folio_unlock(folio);
  2835. }
  2836. set_delayed_call(done, shmem_put_link, folio);
  2837. return folio_address(folio);
  2838. }
  2839. #ifdef CONFIG_TMPFS_XATTR
  2840. static int shmem_fileattr_get(struct dentry *dentry, struct fileattr *fa)
  2841. {
  2842. struct shmem_inode_info *info = SHMEM_I(d_inode(dentry));
  2843. fileattr_fill_flags(fa, info->fsflags & SHMEM_FL_USER_VISIBLE);
  2844. return 0;
  2845. }
  2846. static int shmem_fileattr_set(struct user_namespace *mnt_userns,
  2847. struct dentry *dentry, struct fileattr *fa)
  2848. {
  2849. struct inode *inode = d_inode(dentry);
  2850. struct shmem_inode_info *info = SHMEM_I(inode);
  2851. if (fileattr_has_fsx(fa))
  2852. return -EOPNOTSUPP;
  2853. if (fa->flags & ~SHMEM_FL_USER_MODIFIABLE)
  2854. return -EOPNOTSUPP;
  2855. info->fsflags = (info->fsflags & ~SHMEM_FL_USER_MODIFIABLE) |
  2856. (fa->flags & SHMEM_FL_USER_MODIFIABLE);
  2857. shmem_set_inode_flags(inode, info->fsflags);
  2858. inode->i_ctime = current_time(inode);
  2859. inode_inc_iversion(inode);
  2860. return 0;
  2861. }
  2862. /*
  2863. * Superblocks without xattr inode operations may get some security.* xattr
  2864. * support from the LSM "for free". As soon as we have any other xattrs
  2865. * like ACLs, we also need to implement the security.* handlers at
  2866. * filesystem level, though.
  2867. */
  2868. /*
  2869. * Callback for security_inode_init_security() for acquiring xattrs.
  2870. */
  2871. static int shmem_initxattrs(struct inode *inode,
  2872. const struct xattr *xattr_array,
  2873. void *fs_info)
  2874. {
  2875. struct shmem_inode_info *info = SHMEM_I(inode);
  2876. const struct xattr *xattr;
  2877. struct simple_xattr *new_xattr;
  2878. size_t len;
  2879. for (xattr = xattr_array; xattr->name != NULL; xattr++) {
  2880. new_xattr = simple_xattr_alloc(xattr->value, xattr->value_len);
  2881. if (!new_xattr)
  2882. return -ENOMEM;
  2883. len = strlen(xattr->name) + 1;
  2884. new_xattr->name = kmalloc(XATTR_SECURITY_PREFIX_LEN + len,
  2885. GFP_KERNEL);
  2886. if (!new_xattr->name) {
  2887. kvfree(new_xattr);
  2888. return -ENOMEM;
  2889. }
  2890. memcpy(new_xattr->name, XATTR_SECURITY_PREFIX,
  2891. XATTR_SECURITY_PREFIX_LEN);
  2892. memcpy(new_xattr->name + XATTR_SECURITY_PREFIX_LEN,
  2893. xattr->name, len);
  2894. simple_xattr_list_add(&info->xattrs, new_xattr);
  2895. }
  2896. return 0;
  2897. }
  2898. static int shmem_xattr_handler_get(const struct xattr_handler *handler,
  2899. struct dentry *unused, struct inode *inode,
  2900. const char *name, void *buffer, size_t size)
  2901. {
  2902. struct shmem_inode_info *info = SHMEM_I(inode);
  2903. name = xattr_full_name(handler, name);
  2904. return simple_xattr_get(&info->xattrs, name, buffer, size);
  2905. }
  2906. static int shmem_xattr_handler_set(const struct xattr_handler *handler,
  2907. struct user_namespace *mnt_userns,
  2908. struct dentry *unused, struct inode *inode,
  2909. const char *name, const void *value,
  2910. size_t size, int flags)
  2911. {
  2912. struct shmem_inode_info *info = SHMEM_I(inode);
  2913. int err;
  2914. name = xattr_full_name(handler, name);
  2915. err = simple_xattr_set(&info->xattrs, name, value, size, flags, NULL);
  2916. if (!err) {
  2917. inode->i_ctime = current_time(inode);
  2918. inode_inc_iversion(inode);
  2919. }
  2920. return err;
  2921. }
  2922. static const struct xattr_handler shmem_security_xattr_handler = {
  2923. .prefix = XATTR_SECURITY_PREFIX,
  2924. .get = shmem_xattr_handler_get,
  2925. .set = shmem_xattr_handler_set,
  2926. };
  2927. static const struct xattr_handler shmem_trusted_xattr_handler = {
  2928. .prefix = XATTR_TRUSTED_PREFIX,
  2929. .get = shmem_xattr_handler_get,
  2930. .set = shmem_xattr_handler_set,
  2931. };
  2932. static const struct xattr_handler *shmem_xattr_handlers[] = {
  2933. #ifdef CONFIG_TMPFS_POSIX_ACL
  2934. &posix_acl_access_xattr_handler,
  2935. &posix_acl_default_xattr_handler,
  2936. #endif
  2937. &shmem_security_xattr_handler,
  2938. &shmem_trusted_xattr_handler,
  2939. NULL
  2940. };
  2941. static ssize_t shmem_listxattr(struct dentry *dentry, char *buffer, size_t size)
  2942. {
  2943. struct shmem_inode_info *info = SHMEM_I(d_inode(dentry));
  2944. return simple_xattr_list(d_inode(dentry), &info->xattrs, buffer, size);
  2945. }
  2946. #endif /* CONFIG_TMPFS_XATTR */
  2947. static const struct inode_operations shmem_short_symlink_operations = {
  2948. .getattr = shmem_getattr,
  2949. .get_link = simple_get_link,
  2950. #ifdef CONFIG_TMPFS_XATTR
  2951. .listxattr = shmem_listxattr,
  2952. #endif
  2953. };
  2954. static const struct inode_operations shmem_symlink_inode_operations = {
  2955. .getattr = shmem_getattr,
  2956. .get_link = shmem_get_link,
  2957. #ifdef CONFIG_TMPFS_XATTR
  2958. .listxattr = shmem_listxattr,
  2959. #endif
  2960. };
  2961. static struct dentry *shmem_get_parent(struct dentry *child)
  2962. {
  2963. return ERR_PTR(-ESTALE);
  2964. }
  2965. static int shmem_match(struct inode *ino, void *vfh)
  2966. {
  2967. __u32 *fh = vfh;
  2968. __u64 inum = fh[2];
  2969. inum = (inum << 32) | fh[1];
  2970. return ino->i_ino == inum && fh[0] == ino->i_generation;
  2971. }
  2972. /* Find any alias of inode, but prefer a hashed alias */
  2973. static struct dentry *shmem_find_alias(struct inode *inode)
  2974. {
  2975. struct dentry *alias = d_find_alias(inode);
  2976. return alias ?: d_find_any_alias(inode);
  2977. }
  2978. static struct dentry *shmem_fh_to_dentry(struct super_block *sb,
  2979. struct fid *fid, int fh_len, int fh_type)
  2980. {
  2981. struct inode *inode;
  2982. struct dentry *dentry = NULL;
  2983. u64 inum;
  2984. if (fh_len < 3)
  2985. return NULL;
  2986. inum = fid->raw[2];
  2987. inum = (inum << 32) | fid->raw[1];
  2988. inode = ilookup5(sb, (unsigned long)(inum + fid->raw[0]),
  2989. shmem_match, fid->raw);
  2990. if (inode) {
  2991. dentry = shmem_find_alias(inode);
  2992. iput(inode);
  2993. }
  2994. return dentry;
  2995. }
  2996. static int shmem_encode_fh(struct inode *inode, __u32 *fh, int *len,
  2997. struct inode *parent)
  2998. {
  2999. if (*len < 3) {
  3000. *len = 3;
  3001. return FILEID_INVALID;
  3002. }
  3003. if (inode_unhashed(inode)) {
  3004. /* Unfortunately insert_inode_hash is not idempotent,
  3005. * so as we hash inodes here rather than at creation
  3006. * time, we need a lock to ensure we only try
  3007. * to do it once
  3008. */
  3009. static DEFINE_SPINLOCK(lock);
  3010. spin_lock(&lock);
  3011. if (inode_unhashed(inode))
  3012. __insert_inode_hash(inode,
  3013. inode->i_ino + inode->i_generation);
  3014. spin_unlock(&lock);
  3015. }
  3016. fh[0] = inode->i_generation;
  3017. fh[1] = inode->i_ino;
  3018. fh[2] = ((__u64)inode->i_ino) >> 32;
  3019. *len = 3;
  3020. return 1;
  3021. }
  3022. static const struct export_operations shmem_export_ops = {
  3023. .get_parent = shmem_get_parent,
  3024. .encode_fh = shmem_encode_fh,
  3025. .fh_to_dentry = shmem_fh_to_dentry,
  3026. };
  3027. enum shmem_param {
  3028. Opt_gid,
  3029. Opt_huge,
  3030. Opt_mode,
  3031. Opt_mpol,
  3032. Opt_nr_blocks,
  3033. Opt_nr_inodes,
  3034. Opt_size,
  3035. Opt_uid,
  3036. Opt_inode32,
  3037. Opt_inode64,
  3038. };
  3039. static const struct constant_table shmem_param_enums_huge[] = {
  3040. {"never", SHMEM_HUGE_NEVER },
  3041. {"always", SHMEM_HUGE_ALWAYS },
  3042. {"within_size", SHMEM_HUGE_WITHIN_SIZE },
  3043. {"advise", SHMEM_HUGE_ADVISE },
  3044. {}
  3045. };
  3046. const struct fs_parameter_spec shmem_fs_parameters[] = {
  3047. fsparam_u32 ("gid", Opt_gid),
  3048. fsparam_enum ("huge", Opt_huge, shmem_param_enums_huge),
  3049. fsparam_u32oct("mode", Opt_mode),
  3050. fsparam_string("mpol", Opt_mpol),
  3051. fsparam_string("nr_blocks", Opt_nr_blocks),
  3052. fsparam_string("nr_inodes", Opt_nr_inodes),
  3053. fsparam_string("size", Opt_size),
  3054. fsparam_u32 ("uid", Opt_uid),
  3055. fsparam_flag ("inode32", Opt_inode32),
  3056. fsparam_flag ("inode64", Opt_inode64),
  3057. {}
  3058. };
  3059. static int shmem_parse_one(struct fs_context *fc, struct fs_parameter *param)
  3060. {
  3061. struct shmem_options *ctx = fc->fs_private;
  3062. struct fs_parse_result result;
  3063. unsigned long long size;
  3064. char *rest;
  3065. int opt;
  3066. kuid_t kuid;
  3067. kgid_t kgid;
  3068. opt = fs_parse(fc, shmem_fs_parameters, param, &result);
  3069. if (opt < 0)
  3070. return opt;
  3071. switch (opt) {
  3072. case Opt_size:
  3073. size = memparse(param->string, &rest);
  3074. if (*rest == '%') {
  3075. size <<= PAGE_SHIFT;
  3076. size *= totalram_pages();
  3077. do_div(size, 100);
  3078. rest++;
  3079. }
  3080. if (*rest)
  3081. goto bad_value;
  3082. ctx->blocks = DIV_ROUND_UP(size, PAGE_SIZE);
  3083. ctx->seen |= SHMEM_SEEN_BLOCKS;
  3084. break;
  3085. case Opt_nr_blocks:
  3086. ctx->blocks = memparse(param->string, &rest);
  3087. if (*rest || ctx->blocks > S64_MAX)
  3088. goto bad_value;
  3089. ctx->seen |= SHMEM_SEEN_BLOCKS;
  3090. break;
  3091. case Opt_nr_inodes:
  3092. ctx->inodes = memparse(param->string, &rest);
  3093. if (*rest)
  3094. goto bad_value;
  3095. ctx->seen |= SHMEM_SEEN_INODES;
  3096. break;
  3097. case Opt_mode:
  3098. ctx->mode = result.uint_32 & 07777;
  3099. break;
  3100. case Opt_uid:
  3101. kuid = make_kuid(current_user_ns(), result.uint_32);
  3102. if (!uid_valid(kuid))
  3103. goto bad_value;
  3104. /*
  3105. * The requested uid must be representable in the
  3106. * filesystem's idmapping.
  3107. */
  3108. if (!kuid_has_mapping(fc->user_ns, kuid))
  3109. goto bad_value;
  3110. ctx->uid = kuid;
  3111. break;
  3112. case Opt_gid:
  3113. kgid = make_kgid(current_user_ns(), result.uint_32);
  3114. if (!gid_valid(kgid))
  3115. goto bad_value;
  3116. /*
  3117. * The requested gid must be representable in the
  3118. * filesystem's idmapping.
  3119. */
  3120. if (!kgid_has_mapping(fc->user_ns, kgid))
  3121. goto bad_value;
  3122. ctx->gid = kgid;
  3123. break;
  3124. case Opt_huge:
  3125. ctx->huge = result.uint_32;
  3126. if (ctx->huge != SHMEM_HUGE_NEVER &&
  3127. !(IS_ENABLED(CONFIG_TRANSPARENT_HUGEPAGE) &&
  3128. has_transparent_hugepage()))
  3129. goto unsupported_parameter;
  3130. ctx->seen |= SHMEM_SEEN_HUGE;
  3131. break;
  3132. case Opt_mpol:
  3133. if (IS_ENABLED(CONFIG_NUMA)) {
  3134. mpol_put(ctx->mpol);
  3135. ctx->mpol = NULL;
  3136. if (mpol_parse_str(param->string, &ctx->mpol))
  3137. goto bad_value;
  3138. break;
  3139. }
  3140. goto unsupported_parameter;
  3141. case Opt_inode32:
  3142. ctx->full_inums = false;
  3143. ctx->seen |= SHMEM_SEEN_INUMS;
  3144. break;
  3145. case Opt_inode64:
  3146. if (sizeof(ino_t) < 8) {
  3147. return invalfc(fc,
  3148. "Cannot use inode64 with <64bit inums in kernel\n");
  3149. }
  3150. ctx->full_inums = true;
  3151. ctx->seen |= SHMEM_SEEN_INUMS;
  3152. break;
  3153. }
  3154. return 0;
  3155. unsupported_parameter:
  3156. return invalfc(fc, "Unsupported parameter '%s'", param->key);
  3157. bad_value:
  3158. return invalfc(fc, "Bad value for '%s'", param->key);
  3159. }
  3160. static int shmem_parse_options(struct fs_context *fc, void *data)
  3161. {
  3162. char *options = data;
  3163. if (options) {
  3164. int err = security_sb_eat_lsm_opts(options, &fc->security);
  3165. if (err)
  3166. return err;
  3167. }
  3168. while (options != NULL) {
  3169. char *this_char = options;
  3170. for (;;) {
  3171. /*
  3172. * NUL-terminate this option: unfortunately,
  3173. * mount options form a comma-separated list,
  3174. * but mpol's nodelist may also contain commas.
  3175. */
  3176. options = strchr(options, ',');
  3177. if (options == NULL)
  3178. break;
  3179. options++;
  3180. if (!isdigit(*options)) {
  3181. options[-1] = '\0';
  3182. break;
  3183. }
  3184. }
  3185. if (*this_char) {
  3186. char *value = strchr(this_char, '=');
  3187. size_t len = 0;
  3188. int err;
  3189. if (value) {
  3190. *value++ = '\0';
  3191. len = strlen(value);
  3192. }
  3193. err = vfs_parse_fs_string(fc, this_char, value, len);
  3194. if (err < 0)
  3195. return err;
  3196. }
  3197. }
  3198. return 0;
  3199. }
  3200. /*
  3201. * Reconfigure a shmem filesystem.
  3202. *
  3203. * Note that we disallow change from limited->unlimited blocks/inodes while any
  3204. * are in use; but we must separately disallow unlimited->limited, because in
  3205. * that case we have no record of how much is already in use.
  3206. */
  3207. static int shmem_reconfigure(struct fs_context *fc)
  3208. {
  3209. struct shmem_options *ctx = fc->fs_private;
  3210. struct shmem_sb_info *sbinfo = SHMEM_SB(fc->root->d_sb);
  3211. unsigned long inodes;
  3212. struct mempolicy *mpol = NULL;
  3213. const char *err;
  3214. raw_spin_lock(&sbinfo->stat_lock);
  3215. inodes = sbinfo->max_inodes - sbinfo->free_inodes;
  3216. if ((ctx->seen & SHMEM_SEEN_BLOCKS) && ctx->blocks) {
  3217. if (!sbinfo->max_blocks) {
  3218. err = "Cannot retroactively limit size";
  3219. goto out;
  3220. }
  3221. if (percpu_counter_compare(&sbinfo->used_blocks,
  3222. ctx->blocks) > 0) {
  3223. err = "Too small a size for current use";
  3224. goto out;
  3225. }
  3226. }
  3227. if ((ctx->seen & SHMEM_SEEN_INODES) && ctx->inodes) {
  3228. if (!sbinfo->max_inodes) {
  3229. err = "Cannot retroactively limit inodes";
  3230. goto out;
  3231. }
  3232. if (ctx->inodes < inodes) {
  3233. err = "Too few inodes for current use";
  3234. goto out;
  3235. }
  3236. }
  3237. if ((ctx->seen & SHMEM_SEEN_INUMS) && !ctx->full_inums &&
  3238. sbinfo->next_ino > UINT_MAX) {
  3239. err = "Current inum too high to switch to 32-bit inums";
  3240. goto out;
  3241. }
  3242. if (ctx->seen & SHMEM_SEEN_HUGE)
  3243. sbinfo->huge = ctx->huge;
  3244. if (ctx->seen & SHMEM_SEEN_INUMS)
  3245. sbinfo->full_inums = ctx->full_inums;
  3246. if (ctx->seen & SHMEM_SEEN_BLOCKS)
  3247. sbinfo->max_blocks = ctx->blocks;
  3248. if (ctx->seen & SHMEM_SEEN_INODES) {
  3249. sbinfo->max_inodes = ctx->inodes;
  3250. sbinfo->free_inodes = ctx->inodes - inodes;
  3251. }
  3252. /*
  3253. * Preserve previous mempolicy unless mpol remount option was specified.
  3254. */
  3255. if (ctx->mpol) {
  3256. mpol = sbinfo->mpol;
  3257. sbinfo->mpol = ctx->mpol; /* transfers initial ref */
  3258. ctx->mpol = NULL;
  3259. }
  3260. raw_spin_unlock(&sbinfo->stat_lock);
  3261. mpol_put(mpol);
  3262. return 0;
  3263. out:
  3264. raw_spin_unlock(&sbinfo->stat_lock);
  3265. return invalfc(fc, "%s", err);
  3266. }
  3267. static int shmem_show_options(struct seq_file *seq, struct dentry *root)
  3268. {
  3269. struct shmem_sb_info *sbinfo = SHMEM_SB(root->d_sb);
  3270. if (sbinfo->max_blocks != shmem_default_max_blocks())
  3271. seq_printf(seq, ",size=%luk",
  3272. sbinfo->max_blocks << (PAGE_SHIFT - 10));
  3273. if (sbinfo->max_inodes != shmem_default_max_inodes())
  3274. seq_printf(seq, ",nr_inodes=%lu", sbinfo->max_inodes);
  3275. if (sbinfo->mode != (0777 | S_ISVTX))
  3276. seq_printf(seq, ",mode=%03ho", sbinfo->mode);
  3277. if (!uid_eq(sbinfo->uid, GLOBAL_ROOT_UID))
  3278. seq_printf(seq, ",uid=%u",
  3279. from_kuid_munged(&init_user_ns, sbinfo->uid));
  3280. if (!gid_eq(sbinfo->gid, GLOBAL_ROOT_GID))
  3281. seq_printf(seq, ",gid=%u",
  3282. from_kgid_munged(&init_user_ns, sbinfo->gid));
  3283. /*
  3284. * Showing inode{64,32} might be useful even if it's the system default,
  3285. * since then people don't have to resort to checking both here and
  3286. * /proc/config.gz to confirm 64-bit inums were successfully applied
  3287. * (which may not even exist if IKCONFIG_PROC isn't enabled).
  3288. *
  3289. * We hide it when inode64 isn't the default and we are using 32-bit
  3290. * inodes, since that probably just means the feature isn't even under
  3291. * consideration.
  3292. *
  3293. * As such:
  3294. *
  3295. * +-----------------+-----------------+
  3296. * | TMPFS_INODE64=y | TMPFS_INODE64=n |
  3297. * +------------------+-----------------+-----------------+
  3298. * | full_inums=true | show | show |
  3299. * | full_inums=false | show | hide |
  3300. * +------------------+-----------------+-----------------+
  3301. *
  3302. */
  3303. if (IS_ENABLED(CONFIG_TMPFS_INODE64) || sbinfo->full_inums)
  3304. seq_printf(seq, ",inode%d", (sbinfo->full_inums ? 64 : 32));
  3305. #ifdef CONFIG_TRANSPARENT_HUGEPAGE
  3306. /* Rightly or wrongly, show huge mount option unmasked by shmem_huge */
  3307. if (sbinfo->huge)
  3308. seq_printf(seq, ",huge=%s", shmem_format_huge(sbinfo->huge));
  3309. #endif
  3310. shmem_show_mpol(seq, sbinfo->mpol);
  3311. return 0;
  3312. }
  3313. #endif /* CONFIG_TMPFS */
  3314. static void shmem_put_super(struct super_block *sb)
  3315. {
  3316. struct shmem_sb_info *sbinfo = SHMEM_SB(sb);
  3317. free_percpu(sbinfo->ino_batch);
  3318. percpu_counter_destroy(&sbinfo->used_blocks);
  3319. mpol_put(sbinfo->mpol);
  3320. kfree(sbinfo);
  3321. sb->s_fs_info = NULL;
  3322. }
  3323. static int shmem_fill_super(struct super_block *sb, struct fs_context *fc)
  3324. {
  3325. struct shmem_options *ctx = fc->fs_private;
  3326. struct inode *inode;
  3327. struct shmem_sb_info *sbinfo;
  3328. /* Round up to L1_CACHE_BYTES to resist false sharing */
  3329. sbinfo = kzalloc(max((int)sizeof(struct shmem_sb_info),
  3330. L1_CACHE_BYTES), GFP_KERNEL);
  3331. if (!sbinfo)
  3332. return -ENOMEM;
  3333. sb->s_fs_info = sbinfo;
  3334. #ifdef CONFIG_TMPFS
  3335. /*
  3336. * Per default we only allow half of the physical ram per
  3337. * tmpfs instance, limiting inodes to one per page of lowmem;
  3338. * but the internal instance is left unlimited.
  3339. */
  3340. if (!(sb->s_flags & SB_KERNMOUNT)) {
  3341. if (!(ctx->seen & SHMEM_SEEN_BLOCKS))
  3342. ctx->blocks = shmem_default_max_blocks();
  3343. if (!(ctx->seen & SHMEM_SEEN_INODES))
  3344. ctx->inodes = shmem_default_max_inodes();
  3345. if (!(ctx->seen & SHMEM_SEEN_INUMS))
  3346. ctx->full_inums = IS_ENABLED(CONFIG_TMPFS_INODE64);
  3347. } else {
  3348. sb->s_flags |= SB_NOUSER;
  3349. }
  3350. sb->s_export_op = &shmem_export_ops;
  3351. sb->s_flags |= SB_NOSEC | SB_I_VERSION;
  3352. #else
  3353. sb->s_flags |= SB_NOUSER;
  3354. #endif
  3355. sbinfo->max_blocks = ctx->blocks;
  3356. sbinfo->free_inodes = sbinfo->max_inodes = ctx->inodes;
  3357. if (sb->s_flags & SB_KERNMOUNT) {
  3358. sbinfo->ino_batch = alloc_percpu(ino_t);
  3359. if (!sbinfo->ino_batch)
  3360. goto failed;
  3361. }
  3362. sbinfo->uid = ctx->uid;
  3363. sbinfo->gid = ctx->gid;
  3364. sbinfo->full_inums = ctx->full_inums;
  3365. sbinfo->mode = ctx->mode;
  3366. sbinfo->huge = ctx->huge;
  3367. sbinfo->mpol = ctx->mpol;
  3368. ctx->mpol = NULL;
  3369. raw_spin_lock_init(&sbinfo->stat_lock);
  3370. if (percpu_counter_init(&sbinfo->used_blocks, 0, GFP_KERNEL))
  3371. goto failed;
  3372. spin_lock_init(&sbinfo->shrinklist_lock);
  3373. INIT_LIST_HEAD(&sbinfo->shrinklist);
  3374. sb->s_maxbytes = MAX_LFS_FILESIZE;
  3375. sb->s_blocksize = PAGE_SIZE;
  3376. sb->s_blocksize_bits = PAGE_SHIFT;
  3377. sb->s_magic = TMPFS_MAGIC;
  3378. sb->s_op = &shmem_ops;
  3379. sb->s_time_gran = 1;
  3380. #ifdef CONFIG_TMPFS_XATTR
  3381. sb->s_xattr = shmem_xattr_handlers;
  3382. #endif
  3383. #ifdef CONFIG_TMPFS_POSIX_ACL
  3384. sb->s_flags |= SB_POSIXACL;
  3385. #endif
  3386. uuid_gen(&sb->s_uuid);
  3387. inode = shmem_get_inode(sb, NULL, S_IFDIR | sbinfo->mode, 0, VM_NORESERVE);
  3388. if (!inode)
  3389. goto failed;
  3390. inode->i_uid = sbinfo->uid;
  3391. inode->i_gid = sbinfo->gid;
  3392. sb->s_root = d_make_root(inode);
  3393. if (!sb->s_root)
  3394. goto failed;
  3395. return 0;
  3396. failed:
  3397. shmem_put_super(sb);
  3398. return -ENOMEM;
  3399. }
  3400. static int shmem_get_tree(struct fs_context *fc)
  3401. {
  3402. return get_tree_nodev(fc, shmem_fill_super);
  3403. }
  3404. static void shmem_free_fc(struct fs_context *fc)
  3405. {
  3406. struct shmem_options *ctx = fc->fs_private;
  3407. if (ctx) {
  3408. mpol_put(ctx->mpol);
  3409. kfree(ctx);
  3410. }
  3411. }
  3412. static const struct fs_context_operations shmem_fs_context_ops = {
  3413. .free = shmem_free_fc,
  3414. .get_tree = shmem_get_tree,
  3415. #ifdef CONFIG_TMPFS
  3416. .parse_monolithic = shmem_parse_options,
  3417. .parse_param = shmem_parse_one,
  3418. .reconfigure = shmem_reconfigure,
  3419. #endif
  3420. };
  3421. static struct kmem_cache *shmem_inode_cachep;
  3422. static struct inode *shmem_alloc_inode(struct super_block *sb)
  3423. {
  3424. struct shmem_inode_info *info;
  3425. info = alloc_inode_sb(sb, shmem_inode_cachep, GFP_KERNEL);
  3426. if (!info)
  3427. return NULL;
  3428. return &info->vfs_inode;
  3429. }
  3430. static void shmem_free_in_core_inode(struct inode *inode)
  3431. {
  3432. if (S_ISLNK(inode->i_mode))
  3433. kfree(inode->i_link);
  3434. kmem_cache_free(shmem_inode_cachep, SHMEM_I(inode));
  3435. }
  3436. static void shmem_destroy_inode(struct inode *inode)
  3437. {
  3438. if (S_ISREG(inode->i_mode))
  3439. mpol_free_shared_policy(&SHMEM_I(inode)->policy);
  3440. }
  3441. static void shmem_init_inode(void *foo)
  3442. {
  3443. struct shmem_inode_info *info = foo;
  3444. inode_init_once(&info->vfs_inode);
  3445. }
  3446. static void shmem_init_inodecache(void)
  3447. {
  3448. shmem_inode_cachep = kmem_cache_create("shmem_inode_cache",
  3449. sizeof(struct shmem_inode_info),
  3450. 0, SLAB_PANIC|SLAB_ACCOUNT, shmem_init_inode);
  3451. }
  3452. static void shmem_destroy_inodecache(void)
  3453. {
  3454. kmem_cache_destroy(shmem_inode_cachep);
  3455. }
  3456. /* Keep the page in page cache instead of truncating it */
  3457. static int shmem_error_remove_page(struct address_space *mapping,
  3458. struct page *page)
  3459. {
  3460. return 0;
  3461. }
  3462. const struct address_space_operations shmem_aops = {
  3463. .writepage = shmem_writepage,
  3464. .dirty_folio = noop_dirty_folio,
  3465. #ifdef CONFIG_TMPFS
  3466. .write_begin = shmem_write_begin,
  3467. .write_end = shmem_write_end,
  3468. #endif
  3469. #ifdef CONFIG_MIGRATION
  3470. .migrate_folio = migrate_folio,
  3471. #endif
  3472. .error_remove_page = shmem_error_remove_page,
  3473. };
  3474. EXPORT_SYMBOL(shmem_aops);
  3475. static const struct file_operations shmem_file_operations = {
  3476. .mmap = shmem_mmap,
  3477. .get_unmapped_area = shmem_get_unmapped_area,
  3478. #ifdef CONFIG_TMPFS
  3479. .llseek = shmem_file_llseek,
  3480. .read_iter = shmem_file_read_iter,
  3481. .write_iter = generic_file_write_iter,
  3482. .fsync = noop_fsync,
  3483. .splice_read = generic_file_splice_read,
  3484. .splice_write = iter_file_splice_write,
  3485. .fallocate = shmem_fallocate,
  3486. #endif
  3487. };
  3488. static const struct inode_operations shmem_inode_operations = {
  3489. .getattr = shmem_getattr,
  3490. .setattr = shmem_setattr,
  3491. #ifdef CONFIG_TMPFS_XATTR
  3492. .listxattr = shmem_listxattr,
  3493. .set_acl = simple_set_acl,
  3494. .fileattr_get = shmem_fileattr_get,
  3495. .fileattr_set = shmem_fileattr_set,
  3496. #endif
  3497. };
  3498. static const struct inode_operations shmem_dir_inode_operations = {
  3499. #ifdef CONFIG_TMPFS
  3500. .getattr = shmem_getattr,
  3501. .create = shmem_create,
  3502. .lookup = simple_lookup,
  3503. .link = shmem_link,
  3504. .unlink = shmem_unlink,
  3505. .symlink = shmem_symlink,
  3506. .mkdir = shmem_mkdir,
  3507. .rmdir = shmem_rmdir,
  3508. .mknod = shmem_mknod,
  3509. .rename = shmem_rename2,
  3510. .tmpfile = shmem_tmpfile,
  3511. #endif
  3512. #ifdef CONFIG_TMPFS_XATTR
  3513. .listxattr = shmem_listxattr,
  3514. .fileattr_get = shmem_fileattr_get,
  3515. .fileattr_set = shmem_fileattr_set,
  3516. #endif
  3517. #ifdef CONFIG_TMPFS_POSIX_ACL
  3518. .setattr = shmem_setattr,
  3519. .set_acl = simple_set_acl,
  3520. #endif
  3521. };
  3522. static const struct inode_operations shmem_special_inode_operations = {
  3523. .getattr = shmem_getattr,
  3524. #ifdef CONFIG_TMPFS_XATTR
  3525. .listxattr = shmem_listxattr,
  3526. #endif
  3527. #ifdef CONFIG_TMPFS_POSIX_ACL
  3528. .setattr = shmem_setattr,
  3529. .set_acl = simple_set_acl,
  3530. #endif
  3531. };
  3532. static const struct super_operations shmem_ops = {
  3533. .alloc_inode = shmem_alloc_inode,
  3534. .free_inode = shmem_free_in_core_inode,
  3535. .destroy_inode = shmem_destroy_inode,
  3536. #ifdef CONFIG_TMPFS
  3537. .statfs = shmem_statfs,
  3538. .show_options = shmem_show_options,
  3539. #endif
  3540. .evict_inode = shmem_evict_inode,
  3541. .drop_inode = generic_delete_inode,
  3542. .put_super = shmem_put_super,
  3543. #ifdef CONFIG_TRANSPARENT_HUGEPAGE
  3544. .nr_cached_objects = shmem_unused_huge_count,
  3545. .free_cached_objects = shmem_unused_huge_scan,
  3546. #endif
  3547. };
  3548. static const struct vm_operations_struct shmem_vm_ops = {
  3549. .fault = shmem_fault,
  3550. .map_pages = filemap_map_pages,
  3551. #ifdef CONFIG_NUMA
  3552. .set_policy = shmem_set_policy,
  3553. .get_policy = shmem_get_policy,
  3554. #endif
  3555. };
  3556. int shmem_init_fs_context(struct fs_context *fc)
  3557. {
  3558. struct shmem_options *ctx;
  3559. ctx = kzalloc(sizeof(struct shmem_options), GFP_KERNEL);
  3560. if (!ctx)
  3561. return -ENOMEM;
  3562. ctx->mode = 0777 | S_ISVTX;
  3563. ctx->uid = current_fsuid();
  3564. ctx->gid = current_fsgid();
  3565. fc->fs_private = ctx;
  3566. fc->ops = &shmem_fs_context_ops;
  3567. return 0;
  3568. }
  3569. static struct file_system_type shmem_fs_type = {
  3570. .owner = THIS_MODULE,
  3571. .name = "tmpfs",
  3572. .init_fs_context = shmem_init_fs_context,
  3573. #ifdef CONFIG_TMPFS
  3574. .parameters = shmem_fs_parameters,
  3575. #endif
  3576. .kill_sb = kill_litter_super,
  3577. .fs_flags = FS_USERNS_MOUNT,
  3578. };
  3579. void __init shmem_init(void)
  3580. {
  3581. int error;
  3582. shmem_init_inodecache();
  3583. error = register_filesystem(&shmem_fs_type);
  3584. if (error) {
  3585. pr_err("Could not register tmpfs\n");
  3586. goto out2;
  3587. }
  3588. shm_mnt = kern_mount(&shmem_fs_type);
  3589. if (IS_ERR(shm_mnt)) {
  3590. error = PTR_ERR(shm_mnt);
  3591. pr_err("Could not kern_mount tmpfs\n");
  3592. goto out1;
  3593. }
  3594. #ifdef CONFIG_TRANSPARENT_HUGEPAGE
  3595. if (has_transparent_hugepage() && shmem_huge > SHMEM_HUGE_DENY)
  3596. SHMEM_SB(shm_mnt->mnt_sb)->huge = shmem_huge;
  3597. else
  3598. shmem_huge = SHMEM_HUGE_NEVER; /* just in case it was patched */
  3599. #endif
  3600. return;
  3601. out1:
  3602. unregister_filesystem(&shmem_fs_type);
  3603. out2:
  3604. shmem_destroy_inodecache();
  3605. shm_mnt = ERR_PTR(error);
  3606. }
  3607. #if defined(CONFIG_TRANSPARENT_HUGEPAGE) && defined(CONFIG_SYSFS)
  3608. static ssize_t shmem_enabled_show(struct kobject *kobj,
  3609. struct kobj_attribute *attr, char *buf)
  3610. {
  3611. static const int values[] = {
  3612. SHMEM_HUGE_ALWAYS,
  3613. SHMEM_HUGE_WITHIN_SIZE,
  3614. SHMEM_HUGE_ADVISE,
  3615. SHMEM_HUGE_NEVER,
  3616. SHMEM_HUGE_DENY,
  3617. SHMEM_HUGE_FORCE,
  3618. };
  3619. int len = 0;
  3620. int i;
  3621. for (i = 0; i < ARRAY_SIZE(values); i++) {
  3622. len += sysfs_emit_at(buf, len,
  3623. shmem_huge == values[i] ? "%s[%s]" : "%s%s",
  3624. i ? " " : "",
  3625. shmem_format_huge(values[i]));
  3626. }
  3627. len += sysfs_emit_at(buf, len, "\n");
  3628. return len;
  3629. }
  3630. static ssize_t shmem_enabled_store(struct kobject *kobj,
  3631. struct kobj_attribute *attr, const char *buf, size_t count)
  3632. {
  3633. char tmp[16];
  3634. int huge;
  3635. if (count + 1 > sizeof(tmp))
  3636. return -EINVAL;
  3637. memcpy(tmp, buf, count);
  3638. tmp[count] = '\0';
  3639. if (count && tmp[count - 1] == '\n')
  3640. tmp[count - 1] = '\0';
  3641. huge = shmem_parse_huge(tmp);
  3642. if (huge == -EINVAL)
  3643. return -EINVAL;
  3644. if (!has_transparent_hugepage() &&
  3645. huge != SHMEM_HUGE_NEVER && huge != SHMEM_HUGE_DENY)
  3646. return -EINVAL;
  3647. shmem_huge = huge;
  3648. if (shmem_huge > SHMEM_HUGE_DENY)
  3649. SHMEM_SB(shm_mnt->mnt_sb)->huge = shmem_huge;
  3650. return count;
  3651. }
  3652. struct kobj_attribute shmem_enabled_attr = __ATTR_RW(shmem_enabled);
  3653. #endif /* CONFIG_TRANSPARENT_HUGEPAGE && CONFIG_SYSFS */
  3654. #else /* !CONFIG_SHMEM */
  3655. /*
  3656. * tiny-shmem: simple shmemfs and tmpfs using ramfs code
  3657. *
  3658. * This is intended for small system where the benefits of the full
  3659. * shmem code (swap-backed and resource-limited) are outweighed by
  3660. * their complexity. On systems without swap this code should be
  3661. * effectively equivalent, but much lighter weight.
  3662. */
  3663. static struct file_system_type shmem_fs_type = {
  3664. .name = "tmpfs",
  3665. .init_fs_context = ramfs_init_fs_context,
  3666. .parameters = ramfs_fs_parameters,
  3667. .kill_sb = ramfs_kill_sb,
  3668. .fs_flags = FS_USERNS_MOUNT,
  3669. };
  3670. void __init shmem_init(void)
  3671. {
  3672. BUG_ON(register_filesystem(&shmem_fs_type) != 0);
  3673. shm_mnt = kern_mount(&shmem_fs_type);
  3674. BUG_ON(IS_ERR(shm_mnt));
  3675. }
  3676. int shmem_unuse(unsigned int type)
  3677. {
  3678. return 0;
  3679. }
  3680. int shmem_lock(struct file *file, int lock, struct ucounts *ucounts)
  3681. {
  3682. return 0;
  3683. }
  3684. void shmem_unlock_mapping(struct address_space *mapping)
  3685. {
  3686. }
  3687. #ifdef CONFIG_MMU
  3688. unsigned long shmem_get_unmapped_area(struct file *file,
  3689. unsigned long addr, unsigned long len,
  3690. unsigned long pgoff, unsigned long flags)
  3691. {
  3692. return current->mm->get_unmapped_area(file, addr, len, pgoff, flags);
  3693. }
  3694. #endif
  3695. void shmem_truncate_range(struct inode *inode, loff_t lstart, loff_t lend)
  3696. {
  3697. truncate_inode_pages_range(inode->i_mapping, lstart, lend);
  3698. }
  3699. EXPORT_SYMBOL_GPL(shmem_truncate_range);
  3700. #define shmem_vm_ops generic_file_vm_ops
  3701. #define shmem_file_operations ramfs_file_operations
  3702. #define shmem_get_inode(sb, dir, mode, dev, flags) ramfs_get_inode(sb, dir, mode, dev)
  3703. #define shmem_acct_size(flags, size) 0
  3704. #define shmem_unacct_size(flags, size) do {} while (0)
  3705. #endif /* CONFIG_SHMEM */
  3706. /* common code */
  3707. static struct file *__shmem_file_setup(struct vfsmount *mnt, const char *name, loff_t size,
  3708. unsigned long flags, unsigned int i_flags)
  3709. {
  3710. struct inode *inode;
  3711. struct file *res;
  3712. if (IS_ERR(mnt))
  3713. return ERR_CAST(mnt);
  3714. if (size < 0 || size > MAX_LFS_FILESIZE)
  3715. return ERR_PTR(-EINVAL);
  3716. if (shmem_acct_size(flags, size))
  3717. return ERR_PTR(-ENOMEM);
  3718. inode = shmem_get_inode(mnt->mnt_sb, NULL, S_IFREG | S_IRWXUGO, 0,
  3719. flags);
  3720. if (unlikely(!inode)) {
  3721. shmem_unacct_size(flags, size);
  3722. return ERR_PTR(-ENOSPC);
  3723. }
  3724. inode->i_flags |= i_flags;
  3725. inode->i_size = size;
  3726. clear_nlink(inode); /* It is unlinked */
  3727. res = ERR_PTR(ramfs_nommu_expand_for_mapping(inode, size));
  3728. if (!IS_ERR(res))
  3729. res = alloc_file_pseudo(inode, mnt, name, O_RDWR,
  3730. &shmem_file_operations);
  3731. if (IS_ERR(res))
  3732. iput(inode);
  3733. return res;
  3734. }
  3735. /**
  3736. * shmem_kernel_file_setup - get an unlinked file living in tmpfs which must be
  3737. * kernel internal. There will be NO LSM permission checks against the
  3738. * underlying inode. So users of this interface must do LSM checks at a
  3739. * higher layer. The users are the big_key and shm implementations. LSM
  3740. * checks are provided at the key or shm level rather than the inode.
  3741. * @name: name for dentry (to be seen in /proc/<pid>/maps
  3742. * @size: size to be set for the file
  3743. * @flags: VM_NORESERVE suppresses pre-accounting of the entire object size
  3744. */
  3745. struct file *shmem_kernel_file_setup(const char *name, loff_t size, unsigned long flags)
  3746. {
  3747. return __shmem_file_setup(shm_mnt, name, size, flags, S_PRIVATE);
  3748. }
  3749. /**
  3750. * shmem_file_setup - get an unlinked file living in tmpfs
  3751. * @name: name for dentry (to be seen in /proc/<pid>/maps
  3752. * @size: size to be set for the file
  3753. * @flags: VM_NORESERVE suppresses pre-accounting of the entire object size
  3754. */
  3755. struct file *shmem_file_setup(const char *name, loff_t size, unsigned long flags)
  3756. {
  3757. return __shmem_file_setup(shm_mnt, name, size, flags, 0);
  3758. }
  3759. EXPORT_SYMBOL_GPL(shmem_file_setup);
  3760. /**
  3761. * shmem_file_setup_with_mnt - get an unlinked file living in tmpfs
  3762. * @mnt: the tmpfs mount where the file will be created
  3763. * @name: name for dentry (to be seen in /proc/<pid>/maps
  3764. * @size: size to be set for the file
  3765. * @flags: VM_NORESERVE suppresses pre-accounting of the entire object size
  3766. */
  3767. struct file *shmem_file_setup_with_mnt(struct vfsmount *mnt, const char *name,
  3768. loff_t size, unsigned long flags)
  3769. {
  3770. return __shmem_file_setup(mnt, name, size, flags, 0);
  3771. }
  3772. EXPORT_SYMBOL_GPL(shmem_file_setup_with_mnt);
  3773. /**
  3774. * shmem_zero_setup - setup a shared anonymous mapping
  3775. * @vma: the vma to be mmapped is prepared by do_mmap
  3776. */
  3777. int shmem_zero_setup(struct vm_area_struct *vma)
  3778. {
  3779. struct file *file;
  3780. loff_t size = vma->vm_end - vma->vm_start;
  3781. /*
  3782. * Cloning a new file under mmap_lock leads to a lock ordering conflict
  3783. * between XFS directory reading and selinux: since this file is only
  3784. * accessible to the user through its mapping, use S_PRIVATE flag to
  3785. * bypass file security, in the same way as shmem_kernel_file_setup().
  3786. */
  3787. file = shmem_kernel_file_setup("dev/zero", size, vma->vm_flags);
  3788. if (IS_ERR(file))
  3789. return PTR_ERR(file);
  3790. if (vma->vm_file)
  3791. fput(vma->vm_file);
  3792. vma->vm_file = file;
  3793. vma->vm_ops = &shmem_vm_ops;
  3794. return 0;
  3795. }
  3796. /**
  3797. * shmem_read_mapping_page_gfp - read into page cache, using specified page allocation flags.
  3798. * @mapping: the page's address_space
  3799. * @index: the page index
  3800. * @gfp: the page allocator flags to use if allocating
  3801. *
  3802. * This behaves as a tmpfs "read_cache_page_gfp(mapping, index, gfp)",
  3803. * with any new page allocations done using the specified allocation flags.
  3804. * But read_cache_page_gfp() uses the ->read_folio() method: which does not
  3805. * suit tmpfs, since it may have pages in swapcache, and needs to find those
  3806. * for itself; although drivers/gpu/drm i915 and ttm rely upon this support.
  3807. *
  3808. * i915_gem_object_get_pages_gtt() mixes __GFP_NORETRY | __GFP_NOWARN in
  3809. * with the mapping_gfp_mask(), to avoid OOMing the machine unnecessarily.
  3810. */
  3811. struct page *shmem_read_mapping_page_gfp(struct address_space *mapping,
  3812. pgoff_t index, gfp_t gfp)
  3813. {
  3814. #ifdef CONFIG_SHMEM
  3815. struct inode *inode = mapping->host;
  3816. struct folio *folio;
  3817. struct page *page;
  3818. int error;
  3819. BUG_ON(!shmem_mapping(mapping));
  3820. error = shmem_get_folio_gfp(inode, index, &folio, SGP_CACHE,
  3821. gfp, NULL, NULL, NULL);
  3822. if (error)
  3823. return ERR_PTR(error);
  3824. folio_unlock(folio);
  3825. page = folio_file_page(folio, index);
  3826. if (PageHWPoison(page)) {
  3827. folio_put(folio);
  3828. return ERR_PTR(-EIO);
  3829. }
  3830. return page;
  3831. #else
  3832. /*
  3833. * The tiny !SHMEM case uses ramfs without swap
  3834. */
  3835. return read_cache_page_gfp(mapping, index, gfp);
  3836. #endif
  3837. }
  3838. EXPORT_SYMBOL_GPL(shmem_read_mapping_page_gfp);
  3839. int reclaim_shmem_address_space(struct address_space *mapping)
  3840. {
  3841. #ifdef CONFIG_SHMEM
  3842. pgoff_t start = 0;
  3843. struct page *page;
  3844. LIST_HEAD(page_list);
  3845. XA_STATE(xas, &mapping->i_pages, start);
  3846. if (!shmem_mapping(mapping))
  3847. return -EINVAL;
  3848. lru_add_drain();
  3849. rcu_read_lock();
  3850. xas_for_each(&xas, page, ULONG_MAX) {
  3851. if (xas_retry(&xas, page))
  3852. continue;
  3853. if (xa_is_value(page))
  3854. continue;
  3855. if (isolate_lru_page(page))
  3856. continue;
  3857. list_add(&page->lru, &page_list);
  3858. if (need_resched()) {
  3859. xas_pause(&xas);
  3860. cond_resched_rcu();
  3861. }
  3862. }
  3863. rcu_read_unlock();
  3864. return reclaim_pages(&page_list);
  3865. #else
  3866. return 0;
  3867. #endif
  3868. }
  3869. EXPORT_SYMBOL_GPL(reclaim_shmem_address_space);