shmem.c 107 KB

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