shmem.c 105 KB

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