shmem.c 106 KB

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