shmem.c 107 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555255625572558255925602561256225632564256525662567256825692570257125722573257425752576257725782579258025812582258325842585258625872588258925902591259225932594259525962597259825992600260126022603260426052606260726082609261026112612261326142615261626172618261926202621262226232624262526262627262826292630263126322633263426352636263726382639264026412642264326442645264626472648264926502651265226532654265526562657265826592660266126622663266426652666266726682669267026712672267326742675267626772678267926802681268226832684268526862687268826892690269126922693269426952696269726982699270027012702270327042705270627072708270927102711271227132714271527162717271827192720272127222723272427252726272727282729273027312732273327342735273627372738273927402741274227432744274527462747274827492750275127522753275427552756275727582759276027612762276327642765276627672768276927702771277227732774277527762777277827792780278127822783278427852786278727882789279027912792279327942795279627972798279928002801280228032804280528062807280828092810281128122813281428152816281728182819282028212822282328242825282628272828282928302831283228332834283528362837283828392840284128422843284428452846284728482849285028512852285328542855285628572858285928602861286228632864286528662867286828692870287128722873287428752876287728782879288028812882288328842885288628872888288928902891289228932894289528962897289828992900290129022903290429052906290729082909291029112912291329142915291629172918291929202921292229232924292529262927292829292930293129322933293429352936293729382939294029412942294329442945294629472948294929502951295229532954295529562957295829592960296129622963296429652966296729682969297029712972297329742975297629772978297929802981298229832984298529862987298829892990299129922993299429952996299729982999300030013002300330043005300630073008300930103011301230133014301530163017301830193020302130223023302430253026302730283029303030313032303330343035303630373038303930403041304230433044304530463047304830493050305130523053305430553056305730583059306030613062306330643065306630673068306930703071307230733074307530763077307830793080308130823083308430853086308730883089309030913092309330943095309630973098309931003101310231033104310531063107310831093110311131123113311431153116311731183119312031213122312331243125312631273128312931303131313231333134313531363137313831393140314131423143314431453146314731483149315031513152315331543155315631573158315931603161316231633164316531663167316831693170317131723173317431753176317731783179318031813182318331843185318631873188318931903191319231933194319531963197319831993200320132023203320432053206320732083209321032113212321332143215321632173218321932203221322232233224322532263227322832293230323132323233323432353236323732383239324032413242324332443245324632473248324932503251325232533254325532563257325832593260326132623263326432653266326732683269327032713272327332743275327632773278327932803281328232833284328532863287328832893290329132923293329432953296329732983299330033013302330333043305330633073308330933103311331233133314331533163317331833193320332133223323332433253326332733283329333033313332333333343335333633373338333933403341334233433344334533463347334833493350335133523353335433553356335733583359336033613362336333643365336633673368336933703371337233733374337533763377337833793380338133823383338433853386338733883389339033913392339333943395339633973398339934003401340234033404340534063407340834093410341134123413341434153416341734183419342034213422342334243425342634273428342934303431343234333434343534363437343834393440344134423443344434453446344734483449345034513452345334543455345634573458345934603461346234633464346534663467346834693470347134723473347434753476347734783479348034813482348334843485348634873488348934903491349234933494349534963497349834993500350135023503350435053506350735083509351035113512351335143515351635173518351935203521352235233524352535263527352835293530353135323533353435353536353735383539354035413542354335443545354635473548354935503551355235533554355535563557355835593560356135623563356435653566356735683569357035713572357335743575357635773578357935803581358235833584358535863587358835893590359135923593359435953596359735983599360036013602360336043605360636073608360936103611361236133614361536163617361836193620362136223623362436253626362736283629363036313632363336343635363636373638363936403641364236433644364536463647364836493650365136523653365436553656365736583659366036613662366336643665366636673668366936703671367236733674367536763677367836793680368136823683368436853686368736883689369036913692369336943695369636973698369937003701370237033704370537063707370837093710371137123713371437153716371737183719372037213722372337243725372637273728372937303731373237333734373537363737373837393740374137423743374437453746374737483749375037513752375337543755375637573758375937603761376237633764376537663767376837693770377137723773377437753776377737783779378037813782378337843785378637873788378937903791379237933794379537963797379837993800380138023803380438053806380738083809381038113812381338143815381638173818381938203821382238233824382538263827382838293830383138323833383438353836383738383839384038413842384338443845384638473848384938503851385238533854385538563857385838593860386138623863386438653866386738683869387038713872387338743875387638773878387938803881388238833884388538863887388838893890389138923893389438953896389738983899390039013902390339043905390639073908390939103911391239133914391539163917391839193920392139223923392439253926392739283929393039313932393339343935393639373938393939403941394239433944394539463947394839493950395139523953395439553956395739583959396039613962396339643965396639673968396939703971397239733974397539763977397839793980398139823983398439853986398739883989399039913992399339943995399639973998399940004001400240034004400540064007400840094010401140124013401440154016401740184019402040214022402340244025402640274028402940304031403240334034403540364037403840394040404140424043404440454046404740484049405040514052405340544055405640574058405940604061406240634064406540664067406840694070407140724073407440754076407740784079408040814082408340844085408640874088408940904091409240934094409540964097409840994100410141024103410441054106410741084109411041114112411341144115411641174118411941204121412241234124412541264127412841294130413141324133413441354136413741384139414041414142414341444145414641474148414941504151
  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 <asm/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. void **pslot;
  270. void *item;
  271. VM_BUG_ON(!expected);
  272. VM_BUG_ON(!replacement);
  273. pslot = radix_tree_lookup_slot(&mapping->page_tree, index);
  274. if (!pslot)
  275. return -ENOENT;
  276. item = radix_tree_deref_slot_protected(pslot, &mapping->tree_lock);
  277. if (item != expected)
  278. return -ENOENT;
  279. radix_tree_replace_slot(pslot, replacement);
  280. return 0;
  281. }
  282. /*
  283. * Sometimes, before we decide whether to proceed or to fail, we must check
  284. * that an entry was not already brought back from swap by a racing thread.
  285. *
  286. * Checking page is not enough: by the time a SwapCache page is locked, it
  287. * might be reused, and again be SwapCache, using the same swap as before.
  288. */
  289. static bool shmem_confirm_swap(struct address_space *mapping,
  290. pgoff_t index, swp_entry_t swap)
  291. {
  292. void *item;
  293. rcu_read_lock();
  294. item = radix_tree_lookup(&mapping->page_tree, index);
  295. rcu_read_unlock();
  296. return item == swp_to_radix_entry(swap);
  297. }
  298. /*
  299. * Definitions for "huge tmpfs": tmpfs mounted with the huge= option
  300. *
  301. * SHMEM_HUGE_NEVER:
  302. * disables huge pages for the mount;
  303. * SHMEM_HUGE_ALWAYS:
  304. * enables huge pages for the mount;
  305. * SHMEM_HUGE_WITHIN_SIZE:
  306. * only allocate huge pages if the page will be fully within i_size,
  307. * also respect fadvise()/madvise() hints;
  308. * SHMEM_HUGE_ADVISE:
  309. * only allocate huge pages if requested with fadvise()/madvise();
  310. */
  311. #define SHMEM_HUGE_NEVER 0
  312. #define SHMEM_HUGE_ALWAYS 1
  313. #define SHMEM_HUGE_WITHIN_SIZE 2
  314. #define SHMEM_HUGE_ADVISE 3
  315. /*
  316. * Special values.
  317. * Only can be set via /sys/kernel/mm/transparent_hugepage/shmem_enabled:
  318. *
  319. * SHMEM_HUGE_DENY:
  320. * disables huge on shm_mnt and all mounts, for emergency use;
  321. * SHMEM_HUGE_FORCE:
  322. * enables huge on shm_mnt and all mounts, w/o needing option, for testing;
  323. *
  324. */
  325. #define SHMEM_HUGE_DENY (-1)
  326. #define SHMEM_HUGE_FORCE (-2)
  327. #ifdef CONFIG_TRANSPARENT_HUGE_PAGECACHE
  328. /* ifdef here to avoid bloating shmem.o when not necessary */
  329. int shmem_huge __read_mostly;
  330. #if defined(CONFIG_SYSFS) || defined(CONFIG_TMPFS)
  331. static int shmem_parse_huge(const char *str)
  332. {
  333. if (!strcmp(str, "never"))
  334. return SHMEM_HUGE_NEVER;
  335. if (!strcmp(str, "always"))
  336. return SHMEM_HUGE_ALWAYS;
  337. if (!strcmp(str, "within_size"))
  338. return SHMEM_HUGE_WITHIN_SIZE;
  339. if (!strcmp(str, "advise"))
  340. return SHMEM_HUGE_ADVISE;
  341. if (!strcmp(str, "deny"))
  342. return SHMEM_HUGE_DENY;
  343. if (!strcmp(str, "force"))
  344. return SHMEM_HUGE_FORCE;
  345. return -EINVAL;
  346. }
  347. static const char *shmem_format_huge(int huge)
  348. {
  349. switch (huge) {
  350. case SHMEM_HUGE_NEVER:
  351. return "never";
  352. case SHMEM_HUGE_ALWAYS:
  353. return "always";
  354. case SHMEM_HUGE_WITHIN_SIZE:
  355. return "within_size";
  356. case SHMEM_HUGE_ADVISE:
  357. return "advise";
  358. case SHMEM_HUGE_DENY:
  359. return "deny";
  360. case SHMEM_HUGE_FORCE:
  361. return "force";
  362. default:
  363. VM_BUG_ON(1);
  364. return "bad_val";
  365. }
  366. }
  367. #endif
  368. static unsigned long shmem_unused_huge_shrink(struct shmem_sb_info *sbinfo,
  369. struct shrink_control *sc, unsigned long nr_to_split)
  370. {
  371. LIST_HEAD(list), *pos, *next;
  372. LIST_HEAD(to_remove);
  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_move(&info->shrinklist, &to_remove);
  395. removed++;
  396. goto next;
  397. }
  398. list_move(&info->shrinklist, &list);
  399. next:
  400. if (!--batch)
  401. break;
  402. }
  403. spin_unlock(&sbinfo->shrinklist_lock);
  404. list_for_each_safe(pos, next, &to_remove) {
  405. info = list_entry(pos, struct shmem_inode_info, shrinklist);
  406. inode = &info->vfs_inode;
  407. list_del_init(&info->shrinklist);
  408. iput(inode);
  409. }
  410. list_for_each_safe(pos, next, &list) {
  411. int ret;
  412. info = list_entry(pos, struct shmem_inode_info, shrinklist);
  413. inode = &info->vfs_inode;
  414. if (nr_to_split && split >= nr_to_split)
  415. goto leave;
  416. page = find_get_page(inode->i_mapping,
  417. (inode->i_size & HPAGE_PMD_MASK) >> PAGE_SHIFT);
  418. if (!page)
  419. goto drop;
  420. /* No huge page at the end of the file: nothing to split */
  421. if (!PageTransHuge(page)) {
  422. put_page(page);
  423. goto drop;
  424. }
  425. /*
  426. * Leave the inode on the list if we failed to lock
  427. * the page at this time.
  428. *
  429. * Waiting for the lock may lead to deadlock in the
  430. * reclaim path.
  431. */
  432. if (!trylock_page(page)) {
  433. put_page(page);
  434. goto leave;
  435. }
  436. ret = split_huge_page(page);
  437. unlock_page(page);
  438. put_page(page);
  439. /* If split failed leave the inode on the list */
  440. if (ret)
  441. goto leave;
  442. split++;
  443. drop:
  444. list_del_init(&info->shrinklist);
  445. removed++;
  446. leave:
  447. iput(inode);
  448. }
  449. spin_lock(&sbinfo->shrinklist_lock);
  450. list_splice_tail(&list, &sbinfo->shrinklist);
  451. sbinfo->shrinklist_len -= removed;
  452. spin_unlock(&sbinfo->shrinklist_lock);
  453. return split;
  454. }
  455. static long shmem_unused_huge_scan(struct super_block *sb,
  456. struct shrink_control *sc)
  457. {
  458. struct shmem_sb_info *sbinfo = SHMEM_SB(sb);
  459. if (!READ_ONCE(sbinfo->shrinklist_len))
  460. return SHRINK_STOP;
  461. return shmem_unused_huge_shrink(sbinfo, sc, 0);
  462. }
  463. static long shmem_unused_huge_count(struct super_block *sb,
  464. struct shrink_control *sc)
  465. {
  466. struct shmem_sb_info *sbinfo = SHMEM_SB(sb);
  467. return READ_ONCE(sbinfo->shrinklist_len);
  468. }
  469. #else /* !CONFIG_TRANSPARENT_HUGE_PAGECACHE */
  470. #define shmem_huge SHMEM_HUGE_DENY
  471. static unsigned long shmem_unused_huge_shrink(struct shmem_sb_info *sbinfo,
  472. struct shrink_control *sc, unsigned long nr_to_split)
  473. {
  474. return 0;
  475. }
  476. #endif /* CONFIG_TRANSPARENT_HUGE_PAGECACHE */
  477. /*
  478. * Like add_to_page_cache_locked, but error if expected item has gone.
  479. */
  480. static int shmem_add_to_page_cache(struct page *page,
  481. struct address_space *mapping,
  482. pgoff_t index, void *expected)
  483. {
  484. int error, nr = hpage_nr_pages(page);
  485. VM_BUG_ON_PAGE(PageTail(page), page);
  486. VM_BUG_ON_PAGE(index != round_down(index, nr), page);
  487. VM_BUG_ON_PAGE(!PageLocked(page), page);
  488. VM_BUG_ON_PAGE(!PageSwapBacked(page), page);
  489. VM_BUG_ON(expected && PageTransHuge(page));
  490. page_ref_add(page, nr);
  491. page->mapping = mapping;
  492. page->index = index;
  493. spin_lock_irq(&mapping->tree_lock);
  494. if (PageTransHuge(page)) {
  495. void __rcu **results;
  496. pgoff_t idx;
  497. int i;
  498. error = 0;
  499. if (radix_tree_gang_lookup_slot(&mapping->page_tree,
  500. &results, &idx, index, 1) &&
  501. idx < index + HPAGE_PMD_NR) {
  502. error = -EEXIST;
  503. }
  504. if (!error) {
  505. for (i = 0; i < HPAGE_PMD_NR; i++) {
  506. error = radix_tree_insert(&mapping->page_tree,
  507. index + i, page + i);
  508. VM_BUG_ON(error);
  509. }
  510. count_vm_event(THP_FILE_ALLOC);
  511. }
  512. } else if (!expected) {
  513. error = radix_tree_insert(&mapping->page_tree, index, page);
  514. } else {
  515. error = shmem_radix_tree_replace(mapping, index, expected,
  516. page);
  517. }
  518. if (!error) {
  519. mapping->nrpages += nr;
  520. if (PageTransHuge(page))
  521. __inc_node_page_state(page, NR_SHMEM_THPS);
  522. __mod_node_page_state(page_pgdat(page), NR_FILE_PAGES, nr);
  523. __mod_node_page_state(page_pgdat(page), NR_SHMEM, nr);
  524. spin_unlock_irq(&mapping->tree_lock);
  525. } else {
  526. page->mapping = NULL;
  527. spin_unlock_irq(&mapping->tree_lock);
  528. page_ref_sub(page, nr);
  529. }
  530. return error;
  531. }
  532. /*
  533. * Like delete_from_page_cache, but substitutes swap for page.
  534. */
  535. static void shmem_delete_from_page_cache(struct page *page, void *radswap)
  536. {
  537. struct address_space *mapping = page->mapping;
  538. int error;
  539. VM_BUG_ON_PAGE(PageCompound(page), page);
  540. spin_lock_irq(&mapping->tree_lock);
  541. error = shmem_radix_tree_replace(mapping, page->index, page, radswap);
  542. page->mapping = NULL;
  543. mapping->nrpages--;
  544. __dec_node_page_state(page, NR_FILE_PAGES);
  545. __dec_node_page_state(page, NR_SHMEM);
  546. spin_unlock_irq(&mapping->tree_lock);
  547. put_page(page);
  548. BUG_ON(error);
  549. }
  550. /*
  551. * Remove swap entry from radix tree, free the swap and its page cache.
  552. */
  553. static int shmem_free_swap(struct address_space *mapping,
  554. pgoff_t index, void *radswap)
  555. {
  556. void *old;
  557. spin_lock_irq(&mapping->tree_lock);
  558. old = radix_tree_delete_item(&mapping->page_tree, index, radswap);
  559. spin_unlock_irq(&mapping->tree_lock);
  560. if (old != radswap)
  561. return -ENOENT;
  562. free_swap_and_cache(radix_to_swp_entry(radswap));
  563. return 0;
  564. }
  565. /*
  566. * Determine (in bytes) how many of the shmem object's pages mapped by the
  567. * given offsets are swapped out.
  568. *
  569. * This is safe to call without i_mutex or mapping->tree_lock thanks to RCU,
  570. * as long as the inode doesn't go away and racy results are not a problem.
  571. */
  572. unsigned long shmem_partial_swap_usage(struct address_space *mapping,
  573. pgoff_t start, pgoff_t end)
  574. {
  575. struct radix_tree_iter iter;
  576. void **slot;
  577. struct page *page;
  578. unsigned long swapped = 0;
  579. rcu_read_lock();
  580. radix_tree_for_each_slot(slot, &mapping->page_tree, &iter, start) {
  581. if (iter.index >= end)
  582. break;
  583. page = radix_tree_deref_slot(slot);
  584. if (radix_tree_deref_retry(page)) {
  585. slot = radix_tree_iter_retry(&iter);
  586. continue;
  587. }
  588. if (radix_tree_exceptional_entry(page))
  589. swapped++;
  590. if (need_resched()) {
  591. cond_resched_rcu();
  592. slot = radix_tree_iter_next(&iter);
  593. }
  594. }
  595. rcu_read_unlock();
  596. return swapped << PAGE_SHIFT;
  597. }
  598. /*
  599. * Determine (in bytes) how many of the shmem object's pages mapped by the
  600. * given vma is swapped out.
  601. *
  602. * This is safe to call without i_mutex or mapping->tree_lock thanks to RCU,
  603. * as long as the inode doesn't go away and racy results are not a problem.
  604. */
  605. unsigned long shmem_swap_usage(struct vm_area_struct *vma)
  606. {
  607. struct inode *inode = file_inode(vma->vm_file);
  608. struct shmem_inode_info *info = SHMEM_I(inode);
  609. struct address_space *mapping = inode->i_mapping;
  610. unsigned long swapped;
  611. /* Be careful as we don't hold info->lock */
  612. swapped = READ_ONCE(info->swapped);
  613. /*
  614. * The easier cases are when the shmem object has nothing in swap, or
  615. * the vma maps it whole. Then we can simply use the stats that we
  616. * already track.
  617. */
  618. if (!swapped)
  619. return 0;
  620. if (!vma->vm_pgoff && vma->vm_end - vma->vm_start >= inode->i_size)
  621. return swapped << PAGE_SHIFT;
  622. /* Here comes the more involved part */
  623. return shmem_partial_swap_usage(mapping,
  624. linear_page_index(vma, vma->vm_start),
  625. linear_page_index(vma, vma->vm_end));
  626. }
  627. /*
  628. * SysV IPC SHM_UNLOCK restore Unevictable pages to their evictable lists.
  629. */
  630. void shmem_unlock_mapping(struct address_space *mapping)
  631. {
  632. struct pagevec pvec;
  633. pgoff_t indices[PAGEVEC_SIZE];
  634. pgoff_t index = 0;
  635. pagevec_init(&pvec, 0);
  636. /*
  637. * Minor point, but we might as well stop if someone else SHM_LOCKs it.
  638. */
  639. while (!mapping_unevictable(mapping)) {
  640. /*
  641. * Avoid pagevec_lookup(): find_get_pages() returns 0 as if it
  642. * has finished, if it hits a row of PAGEVEC_SIZE swap entries.
  643. */
  644. pvec.nr = find_get_entries(mapping, index,
  645. PAGEVEC_SIZE, pvec.pages, indices);
  646. if (!pvec.nr)
  647. break;
  648. index = indices[pvec.nr - 1] + 1;
  649. pagevec_remove_exceptionals(&pvec);
  650. check_move_unevictable_pages(pvec.pages, pvec.nr);
  651. pagevec_release(&pvec);
  652. cond_resched();
  653. }
  654. }
  655. /*
  656. * Remove range of pages and swap entries from radix tree, and free them.
  657. * If !unfalloc, truncate or punch hole; if unfalloc, undo failed fallocate.
  658. */
  659. static void shmem_undo_range(struct inode *inode, loff_t lstart, loff_t lend,
  660. bool unfalloc)
  661. {
  662. struct address_space *mapping = inode->i_mapping;
  663. struct shmem_inode_info *info = SHMEM_I(inode);
  664. pgoff_t start = (lstart + PAGE_SIZE - 1) >> PAGE_SHIFT;
  665. pgoff_t end = (lend + 1) >> PAGE_SHIFT;
  666. unsigned int partial_start = lstart & (PAGE_SIZE - 1);
  667. unsigned int partial_end = (lend + 1) & (PAGE_SIZE - 1);
  668. struct pagevec pvec;
  669. pgoff_t indices[PAGEVEC_SIZE];
  670. long nr_swaps_freed = 0;
  671. pgoff_t index;
  672. int i;
  673. if (lend == -1)
  674. end = -1; /* unsigned, so actually very big */
  675. pagevec_init(&pvec, 0);
  676. index = start;
  677. while (index < end) {
  678. pvec.nr = find_get_entries(mapping, index,
  679. min(end - index, (pgoff_t)PAGEVEC_SIZE),
  680. pvec.pages, indices);
  681. if (!pvec.nr)
  682. break;
  683. for (i = 0; i < pagevec_count(&pvec); i++) {
  684. struct page *page = pvec.pages[i];
  685. index = indices[i];
  686. if (index >= end)
  687. break;
  688. if (radix_tree_exceptional_entry(page)) {
  689. if (unfalloc)
  690. continue;
  691. nr_swaps_freed += !shmem_free_swap(mapping,
  692. index, page);
  693. continue;
  694. }
  695. VM_BUG_ON_PAGE(page_to_pgoff(page) != index, page);
  696. if (!trylock_page(page))
  697. continue;
  698. if (PageTransTail(page)) {
  699. /* Middle of THP: zero out the page */
  700. clear_highpage(page);
  701. unlock_page(page);
  702. continue;
  703. } else if (PageTransHuge(page)) {
  704. if (index == round_down(end, HPAGE_PMD_NR)) {
  705. /*
  706. * Range ends in the middle of THP:
  707. * zero out the page
  708. */
  709. clear_highpage(page);
  710. unlock_page(page);
  711. continue;
  712. }
  713. index += HPAGE_PMD_NR - 1;
  714. i += HPAGE_PMD_NR - 1;
  715. }
  716. if (!unfalloc || !PageUptodate(page)) {
  717. VM_BUG_ON_PAGE(PageTail(page), page);
  718. if (page_mapping(page) == mapping) {
  719. VM_BUG_ON_PAGE(PageWriteback(page), page);
  720. truncate_inode_page(mapping, page);
  721. }
  722. }
  723. unlock_page(page);
  724. }
  725. pagevec_remove_exceptionals(&pvec);
  726. pagevec_release(&pvec);
  727. cond_resched();
  728. index++;
  729. }
  730. if (partial_start) {
  731. struct page *page = NULL;
  732. shmem_getpage(inode, start - 1, &page, SGP_READ);
  733. if (page) {
  734. unsigned int top = PAGE_SIZE;
  735. if (start > end) {
  736. top = partial_end;
  737. partial_end = 0;
  738. }
  739. zero_user_segment(page, partial_start, top);
  740. set_page_dirty(page);
  741. unlock_page(page);
  742. put_page(page);
  743. }
  744. }
  745. if (partial_end) {
  746. struct page *page = NULL;
  747. shmem_getpage(inode, end, &page, SGP_READ);
  748. if (page) {
  749. zero_user_segment(page, 0, partial_end);
  750. set_page_dirty(page);
  751. unlock_page(page);
  752. put_page(page);
  753. }
  754. }
  755. if (start >= end)
  756. return;
  757. index = start;
  758. while (index < end) {
  759. cond_resched();
  760. pvec.nr = find_get_entries(mapping, index,
  761. min(end - index, (pgoff_t)PAGEVEC_SIZE),
  762. pvec.pages, indices);
  763. if (!pvec.nr) {
  764. /* If all gone or hole-punch or unfalloc, we're done */
  765. if (index == start || end != -1)
  766. break;
  767. /* But if truncating, restart to make sure all gone */
  768. index = start;
  769. continue;
  770. }
  771. for (i = 0; i < pagevec_count(&pvec); i++) {
  772. struct page *page = pvec.pages[i];
  773. index = indices[i];
  774. if (index >= end)
  775. break;
  776. if (radix_tree_exceptional_entry(page)) {
  777. if (unfalloc)
  778. continue;
  779. if (shmem_free_swap(mapping, index, page)) {
  780. /* Swap was replaced by page: retry */
  781. index--;
  782. break;
  783. }
  784. nr_swaps_freed++;
  785. continue;
  786. }
  787. lock_page(page);
  788. if (PageTransTail(page)) {
  789. /* Middle of THP: zero out the page */
  790. clear_highpage(page);
  791. unlock_page(page);
  792. /*
  793. * Partial thp truncate due 'start' in middle
  794. * of THP: don't need to look on these pages
  795. * again on !pvec.nr restart.
  796. */
  797. if (index != round_down(end, HPAGE_PMD_NR))
  798. start++;
  799. continue;
  800. } else if (PageTransHuge(page)) {
  801. if (index == round_down(end, HPAGE_PMD_NR)) {
  802. /*
  803. * Range ends in the middle of THP:
  804. * zero out the page
  805. */
  806. clear_highpage(page);
  807. unlock_page(page);
  808. continue;
  809. }
  810. index += HPAGE_PMD_NR - 1;
  811. i += HPAGE_PMD_NR - 1;
  812. }
  813. if (!unfalloc || !PageUptodate(page)) {
  814. VM_BUG_ON_PAGE(PageTail(page), page);
  815. if (page_mapping(page) == mapping) {
  816. VM_BUG_ON_PAGE(PageWriteback(page), page);
  817. truncate_inode_page(mapping, page);
  818. } else {
  819. /* Page was replaced by swap: retry */
  820. unlock_page(page);
  821. index--;
  822. break;
  823. }
  824. }
  825. unlock_page(page);
  826. }
  827. pagevec_remove_exceptionals(&pvec);
  828. pagevec_release(&pvec);
  829. index++;
  830. }
  831. spin_lock_irq(&info->lock);
  832. info->swapped -= nr_swaps_freed;
  833. shmem_recalc_inode(inode);
  834. spin_unlock_irq(&info->lock);
  835. }
  836. void shmem_truncate_range(struct inode *inode, loff_t lstart, loff_t lend)
  837. {
  838. shmem_undo_range(inode, lstart, lend, false);
  839. inode->i_ctime = inode->i_mtime = current_time(inode);
  840. }
  841. EXPORT_SYMBOL_GPL(shmem_truncate_range);
  842. static int shmem_getattr(struct vfsmount *mnt, struct dentry *dentry,
  843. struct kstat *stat)
  844. {
  845. struct inode *inode = dentry->d_inode;
  846. struct shmem_inode_info *info = SHMEM_I(inode);
  847. if (info->alloced - info->swapped != inode->i_mapping->nrpages) {
  848. spin_lock_irq(&info->lock);
  849. shmem_recalc_inode(inode);
  850. spin_unlock_irq(&info->lock);
  851. }
  852. generic_fillattr(inode, stat);
  853. return 0;
  854. }
  855. static int shmem_setattr(struct dentry *dentry, struct iattr *attr)
  856. {
  857. struct inode *inode = d_inode(dentry);
  858. struct shmem_inode_info *info = SHMEM_I(inode);
  859. struct shmem_sb_info *sbinfo = SHMEM_SB(inode->i_sb);
  860. int error;
  861. error = setattr_prepare(dentry, attr);
  862. if (error)
  863. return error;
  864. if (S_ISREG(inode->i_mode) && (attr->ia_valid & ATTR_SIZE)) {
  865. loff_t oldsize = inode->i_size;
  866. loff_t newsize = attr->ia_size;
  867. /* protected by i_mutex */
  868. if ((newsize < oldsize && (info->seals & F_SEAL_SHRINK)) ||
  869. (newsize > oldsize && (info->seals & F_SEAL_GROW)))
  870. return -EPERM;
  871. if (newsize != oldsize) {
  872. error = shmem_reacct_size(SHMEM_I(inode)->flags,
  873. oldsize, newsize);
  874. if (error)
  875. return error;
  876. i_size_write(inode, newsize);
  877. inode->i_ctime = inode->i_mtime = current_time(inode);
  878. }
  879. if (newsize <= oldsize) {
  880. loff_t holebegin = round_up(newsize, PAGE_SIZE);
  881. if (oldsize > holebegin)
  882. unmap_mapping_range(inode->i_mapping,
  883. holebegin, 0, 1);
  884. if (info->alloced)
  885. shmem_truncate_range(inode,
  886. newsize, (loff_t)-1);
  887. /* unmap again to remove racily COWed private pages */
  888. if (oldsize > holebegin)
  889. unmap_mapping_range(inode->i_mapping,
  890. holebegin, 0, 1);
  891. /*
  892. * Part of the huge page can be beyond i_size: subject
  893. * to shrink under memory pressure.
  894. */
  895. if (IS_ENABLED(CONFIG_TRANSPARENT_HUGE_PAGECACHE)) {
  896. spin_lock(&sbinfo->shrinklist_lock);
  897. /*
  898. * _careful to defend against unlocked access to
  899. * ->shrink_list in shmem_unused_huge_shrink()
  900. */
  901. if (list_empty_careful(&info->shrinklist)) {
  902. list_add_tail(&info->shrinklist,
  903. &sbinfo->shrinklist);
  904. sbinfo->shrinklist_len++;
  905. }
  906. spin_unlock(&sbinfo->shrinklist_lock);
  907. }
  908. }
  909. }
  910. setattr_copy(inode, attr);
  911. if (attr->ia_valid & ATTR_MODE)
  912. error = posix_acl_chmod(inode, inode->i_mode);
  913. return error;
  914. }
  915. static void shmem_evict_inode(struct inode *inode)
  916. {
  917. struct shmem_inode_info *info = SHMEM_I(inode);
  918. struct shmem_sb_info *sbinfo = SHMEM_SB(inode->i_sb);
  919. if (inode->i_mapping->a_ops == &shmem_aops) {
  920. shmem_unacct_size(info->flags, inode->i_size);
  921. inode->i_size = 0;
  922. shmem_truncate_range(inode, 0, (loff_t)-1);
  923. if (!list_empty(&info->shrinklist)) {
  924. spin_lock(&sbinfo->shrinklist_lock);
  925. if (!list_empty(&info->shrinklist)) {
  926. list_del_init(&info->shrinklist);
  927. sbinfo->shrinklist_len--;
  928. }
  929. spin_unlock(&sbinfo->shrinklist_lock);
  930. }
  931. if (!list_empty(&info->swaplist)) {
  932. mutex_lock(&shmem_swaplist_mutex);
  933. list_del_init(&info->swaplist);
  934. mutex_unlock(&shmem_swaplist_mutex);
  935. }
  936. }
  937. simple_xattrs_free(&info->xattrs);
  938. WARN_ON(inode->i_blocks);
  939. shmem_free_inode(inode->i_sb);
  940. clear_inode(inode);
  941. }
  942. /*
  943. * If swap found in inode, free it and move page from swapcache to filecache.
  944. */
  945. static int shmem_unuse_inode(struct shmem_inode_info *info,
  946. swp_entry_t swap, struct page **pagep)
  947. {
  948. struct address_space *mapping = info->vfs_inode.i_mapping;
  949. void *radswap;
  950. pgoff_t index;
  951. gfp_t gfp;
  952. int error = 0;
  953. radswap = swp_to_radix_entry(swap);
  954. index = radix_tree_locate_item(&mapping->page_tree, radswap);
  955. if (index == -1)
  956. return -EAGAIN; /* tell shmem_unuse we found nothing */
  957. /*
  958. * Move _head_ to start search for next from here.
  959. * But be careful: shmem_evict_inode checks list_empty without taking
  960. * mutex, and there's an instant in list_move_tail when info->swaplist
  961. * would appear empty, if it were the only one on shmem_swaplist.
  962. */
  963. if (shmem_swaplist.next != &info->swaplist)
  964. list_move_tail(&shmem_swaplist, &info->swaplist);
  965. gfp = mapping_gfp_mask(mapping);
  966. if (shmem_should_replace_page(*pagep, gfp)) {
  967. mutex_unlock(&shmem_swaplist_mutex);
  968. error = shmem_replace_page(pagep, gfp, info, index);
  969. mutex_lock(&shmem_swaplist_mutex);
  970. /*
  971. * We needed to drop mutex to make that restrictive page
  972. * allocation, but the inode might have been freed while we
  973. * dropped it: although a racing shmem_evict_inode() cannot
  974. * complete without emptying the radix_tree, our page lock
  975. * on this swapcache page is not enough to prevent that -
  976. * free_swap_and_cache() of our swap entry will only
  977. * trylock_page(), removing swap from radix_tree whatever.
  978. *
  979. * We must not proceed to shmem_add_to_page_cache() if the
  980. * inode has been freed, but of course we cannot rely on
  981. * inode or mapping or info to check that. However, we can
  982. * safely check if our swap entry is still in use (and here
  983. * it can't have got reused for another page): if it's still
  984. * in use, then the inode cannot have been freed yet, and we
  985. * can safely proceed (if it's no longer in use, that tells
  986. * nothing about the inode, but we don't need to unuse swap).
  987. */
  988. if (!page_swapcount(*pagep))
  989. error = -ENOENT;
  990. }
  991. /*
  992. * We rely on shmem_swaplist_mutex, not only to protect the swaplist,
  993. * but also to hold up shmem_evict_inode(): so inode cannot be freed
  994. * beneath us (pagelock doesn't help until the page is in pagecache).
  995. */
  996. if (!error)
  997. error = shmem_add_to_page_cache(*pagep, mapping, index,
  998. radswap);
  999. if (error != -ENOMEM) {
  1000. /*
  1001. * Truncation and eviction use free_swap_and_cache(), which
  1002. * only does trylock page: if we raced, best clean up here.
  1003. */
  1004. delete_from_swap_cache(*pagep);
  1005. set_page_dirty(*pagep);
  1006. if (!error) {
  1007. spin_lock_irq(&info->lock);
  1008. info->swapped--;
  1009. spin_unlock_irq(&info->lock);
  1010. swap_free(swap);
  1011. }
  1012. }
  1013. return error;
  1014. }
  1015. /*
  1016. * Search through swapped inodes to find and replace swap by page.
  1017. */
  1018. int shmem_unuse(swp_entry_t swap, struct page *page)
  1019. {
  1020. struct list_head *this, *next;
  1021. struct shmem_inode_info *info;
  1022. struct mem_cgroup *memcg;
  1023. int error = 0;
  1024. /*
  1025. * There's a faint possibility that swap page was replaced before
  1026. * caller locked it: caller will come back later with the right page.
  1027. */
  1028. if (unlikely(!PageSwapCache(page) || page_private(page) != swap.val))
  1029. goto out;
  1030. /*
  1031. * Charge page using GFP_KERNEL while we can wait, before taking
  1032. * the shmem_swaplist_mutex which might hold up shmem_writepage().
  1033. * Charged back to the user (not to caller) when swap account is used.
  1034. */
  1035. error = mem_cgroup_try_charge(page, current->mm, GFP_KERNEL, &memcg,
  1036. false);
  1037. if (error)
  1038. goto out;
  1039. /* No radix_tree_preload: swap entry keeps a place for page in tree */
  1040. error = -EAGAIN;
  1041. mutex_lock(&shmem_swaplist_mutex);
  1042. list_for_each_safe(this, next, &shmem_swaplist) {
  1043. info = list_entry(this, struct shmem_inode_info, swaplist);
  1044. if (info->swapped)
  1045. error = shmem_unuse_inode(info, swap, &page);
  1046. else
  1047. list_del_init(&info->swaplist);
  1048. cond_resched();
  1049. if (error != -EAGAIN)
  1050. break;
  1051. /* found nothing in this: move on to search the next */
  1052. }
  1053. mutex_unlock(&shmem_swaplist_mutex);
  1054. if (error) {
  1055. if (error != -ENOMEM)
  1056. error = 0;
  1057. mem_cgroup_cancel_charge(page, memcg, false);
  1058. } else
  1059. mem_cgroup_commit_charge(page, memcg, true, false);
  1060. out:
  1061. unlock_page(page);
  1062. put_page(page);
  1063. return error;
  1064. }
  1065. /*
  1066. * Move the page from the page cache to the swap cache.
  1067. */
  1068. static int shmem_writepage(struct page *page, struct writeback_control *wbc)
  1069. {
  1070. struct shmem_inode_info *info;
  1071. struct address_space *mapping;
  1072. struct inode *inode;
  1073. swp_entry_t swap;
  1074. pgoff_t index;
  1075. VM_BUG_ON_PAGE(PageCompound(page), page);
  1076. BUG_ON(!PageLocked(page));
  1077. mapping = page->mapping;
  1078. index = page->index;
  1079. inode = mapping->host;
  1080. info = SHMEM_I(inode);
  1081. if (info->flags & VM_LOCKED)
  1082. goto redirty;
  1083. if (!total_swap_pages)
  1084. goto redirty;
  1085. /*
  1086. * Our capabilities prevent regular writeback or sync from ever calling
  1087. * shmem_writepage; but a stacking filesystem might use ->writepage of
  1088. * its underlying filesystem, in which case tmpfs should write out to
  1089. * swap only in response to memory pressure, and not for the writeback
  1090. * threads or sync.
  1091. */
  1092. if (!wbc->for_reclaim) {
  1093. WARN_ON_ONCE(1); /* Still happens? Tell us about it! */
  1094. goto redirty;
  1095. }
  1096. /*
  1097. * This is somewhat ridiculous, but without plumbing a SWAP_MAP_FALLOC
  1098. * value into swapfile.c, the only way we can correctly account for a
  1099. * fallocated page arriving here is now to initialize it and write it.
  1100. *
  1101. * That's okay for a page already fallocated earlier, but if we have
  1102. * not yet completed the fallocation, then (a) we want to keep track
  1103. * of this page in case we have to undo it, and (b) it may not be a
  1104. * good idea to continue anyway, once we're pushing into swap. So
  1105. * reactivate the page, and let shmem_fallocate() quit when too many.
  1106. */
  1107. if (!PageUptodate(page)) {
  1108. if (inode->i_private) {
  1109. struct shmem_falloc *shmem_falloc;
  1110. spin_lock(&inode->i_lock);
  1111. shmem_falloc = inode->i_private;
  1112. if (shmem_falloc &&
  1113. !shmem_falloc->waitq &&
  1114. index >= shmem_falloc->start &&
  1115. index < shmem_falloc->next)
  1116. shmem_falloc->nr_unswapped++;
  1117. else
  1118. shmem_falloc = NULL;
  1119. spin_unlock(&inode->i_lock);
  1120. if (shmem_falloc)
  1121. goto redirty;
  1122. }
  1123. clear_highpage(page);
  1124. flush_dcache_page(page);
  1125. SetPageUptodate(page);
  1126. }
  1127. swap = get_swap_page();
  1128. if (!swap.val)
  1129. goto redirty;
  1130. if (mem_cgroup_try_charge_swap(page, swap))
  1131. goto free_swap;
  1132. /*
  1133. * Add inode to shmem_unuse()'s list of swapped-out inodes,
  1134. * if it's not already there. Do it now before the page is
  1135. * moved to swap cache, when its pagelock no longer protects
  1136. * the inode from eviction. But don't unlock the mutex until
  1137. * we've incremented swapped, because shmem_unuse_inode() will
  1138. * prune a !swapped inode from the swaplist under this mutex.
  1139. */
  1140. mutex_lock(&shmem_swaplist_mutex);
  1141. if (list_empty(&info->swaplist))
  1142. list_add_tail(&info->swaplist, &shmem_swaplist);
  1143. if (add_to_swap_cache(page, swap, GFP_ATOMIC) == 0) {
  1144. spin_lock_irq(&info->lock);
  1145. shmem_recalc_inode(inode);
  1146. info->swapped++;
  1147. spin_unlock_irq(&info->lock);
  1148. swap_shmem_alloc(swap);
  1149. shmem_delete_from_page_cache(page, swp_to_radix_entry(swap));
  1150. mutex_unlock(&shmem_swaplist_mutex);
  1151. BUG_ON(page_mapped(page));
  1152. swap_writepage(page, wbc);
  1153. return 0;
  1154. }
  1155. mutex_unlock(&shmem_swaplist_mutex);
  1156. free_swap:
  1157. swapcache_free(swap);
  1158. redirty:
  1159. set_page_dirty(page);
  1160. if (wbc->for_reclaim)
  1161. return AOP_WRITEPAGE_ACTIVATE; /* Return with page locked */
  1162. unlock_page(page);
  1163. return 0;
  1164. }
  1165. #if defined(CONFIG_NUMA) && defined(CONFIG_TMPFS)
  1166. static void shmem_show_mpol(struct seq_file *seq, struct mempolicy *mpol)
  1167. {
  1168. char buffer[64];
  1169. if (!mpol || mpol->mode == MPOL_DEFAULT)
  1170. return; /* show nothing */
  1171. mpol_to_str(buffer, sizeof(buffer), mpol);
  1172. seq_printf(seq, ",mpol=%s", buffer);
  1173. }
  1174. static struct mempolicy *shmem_get_sbmpol(struct shmem_sb_info *sbinfo)
  1175. {
  1176. struct mempolicy *mpol = NULL;
  1177. if (sbinfo->mpol) {
  1178. spin_lock(&sbinfo->stat_lock); /* prevent replace/use races */
  1179. mpol = sbinfo->mpol;
  1180. mpol_get(mpol);
  1181. spin_unlock(&sbinfo->stat_lock);
  1182. }
  1183. return mpol;
  1184. }
  1185. #else /* !CONFIG_NUMA || !CONFIG_TMPFS */
  1186. static inline void shmem_show_mpol(struct seq_file *seq, struct mempolicy *mpol)
  1187. {
  1188. }
  1189. static inline struct mempolicy *shmem_get_sbmpol(struct shmem_sb_info *sbinfo)
  1190. {
  1191. return NULL;
  1192. }
  1193. #endif /* CONFIG_NUMA && CONFIG_TMPFS */
  1194. #ifndef CONFIG_NUMA
  1195. #define vm_policy vm_private_data
  1196. #endif
  1197. static void shmem_pseudo_vma_init(struct vm_area_struct *vma,
  1198. struct shmem_inode_info *info, pgoff_t index)
  1199. {
  1200. /* Create a pseudo vma that just contains the policy */
  1201. vma->vm_start = 0;
  1202. /* Bias interleave by inode number to distribute better across nodes */
  1203. vma->vm_pgoff = index + info->vfs_inode.i_ino;
  1204. vma->vm_ops = NULL;
  1205. vma->vm_policy = mpol_shared_policy_lookup(&info->policy, index);
  1206. }
  1207. static void shmem_pseudo_vma_destroy(struct vm_area_struct *vma)
  1208. {
  1209. /* Drop reference taken by mpol_shared_policy_lookup() */
  1210. mpol_cond_put(vma->vm_policy);
  1211. }
  1212. static struct page *shmem_swapin(swp_entry_t swap, gfp_t gfp,
  1213. struct shmem_inode_info *info, pgoff_t index)
  1214. {
  1215. struct vm_area_struct pvma;
  1216. struct page *page;
  1217. shmem_pseudo_vma_init(&pvma, info, index);
  1218. page = swapin_readahead(swap, gfp, &pvma, 0);
  1219. shmem_pseudo_vma_destroy(&pvma);
  1220. return page;
  1221. }
  1222. static struct page *shmem_alloc_hugepage(gfp_t gfp,
  1223. struct shmem_inode_info *info, pgoff_t index)
  1224. {
  1225. struct vm_area_struct pvma;
  1226. struct inode *inode = &info->vfs_inode;
  1227. struct address_space *mapping = inode->i_mapping;
  1228. pgoff_t idx, hindex;
  1229. void __rcu **results;
  1230. struct page *page;
  1231. if (!IS_ENABLED(CONFIG_TRANSPARENT_HUGE_PAGECACHE))
  1232. return NULL;
  1233. hindex = round_down(index, HPAGE_PMD_NR);
  1234. rcu_read_lock();
  1235. if (radix_tree_gang_lookup_slot(&mapping->page_tree, &results, &idx,
  1236. hindex, 1) && idx < hindex + HPAGE_PMD_NR) {
  1237. rcu_read_unlock();
  1238. return NULL;
  1239. }
  1240. rcu_read_unlock();
  1241. shmem_pseudo_vma_init(&pvma, info, hindex);
  1242. page = alloc_pages_vma(gfp | __GFP_COMP | __GFP_NORETRY | __GFP_NOWARN,
  1243. HPAGE_PMD_ORDER, &pvma, 0, numa_node_id(), true);
  1244. shmem_pseudo_vma_destroy(&pvma);
  1245. if (page)
  1246. prep_transhuge_page(page);
  1247. return page;
  1248. }
  1249. static struct page *shmem_alloc_page(gfp_t gfp,
  1250. struct shmem_inode_info *info, pgoff_t index)
  1251. {
  1252. struct vm_area_struct pvma;
  1253. struct page *page;
  1254. shmem_pseudo_vma_init(&pvma, info, index);
  1255. page = alloc_page_vma(gfp, &pvma, 0);
  1256. shmem_pseudo_vma_destroy(&pvma);
  1257. return page;
  1258. }
  1259. static struct page *shmem_alloc_and_acct_page(gfp_t gfp,
  1260. struct shmem_inode_info *info, struct shmem_sb_info *sbinfo,
  1261. pgoff_t index, bool huge)
  1262. {
  1263. struct page *page;
  1264. int nr;
  1265. int err = -ENOSPC;
  1266. if (!IS_ENABLED(CONFIG_TRANSPARENT_HUGE_PAGECACHE))
  1267. huge = false;
  1268. nr = huge ? HPAGE_PMD_NR : 1;
  1269. if (shmem_acct_block(info->flags, nr))
  1270. goto failed;
  1271. if (sbinfo->max_blocks) {
  1272. if (percpu_counter_compare(&sbinfo->used_blocks,
  1273. sbinfo->max_blocks - nr) > 0)
  1274. goto unacct;
  1275. percpu_counter_add(&sbinfo->used_blocks, nr);
  1276. }
  1277. if (huge)
  1278. page = shmem_alloc_hugepage(gfp, info, index);
  1279. else
  1280. page = shmem_alloc_page(gfp, info, index);
  1281. if (page) {
  1282. __SetPageLocked(page);
  1283. __SetPageSwapBacked(page);
  1284. return page;
  1285. }
  1286. err = -ENOMEM;
  1287. if (sbinfo->max_blocks)
  1288. percpu_counter_add(&sbinfo->used_blocks, -nr);
  1289. unacct:
  1290. shmem_unacct_blocks(info->flags, nr);
  1291. failed:
  1292. return ERR_PTR(err);
  1293. }
  1294. /*
  1295. * When a page is moved from swapcache to shmem filecache (either by the
  1296. * usual swapin of shmem_getpage_gfp(), or by the less common swapoff of
  1297. * shmem_unuse_inode()), it may have been read in earlier from swap, in
  1298. * ignorance of the mapping it belongs to. If that mapping has special
  1299. * constraints (like the gma500 GEM driver, which requires RAM below 4GB),
  1300. * we may need to copy to a suitable page before moving to filecache.
  1301. *
  1302. * In a future release, this may well be extended to respect cpuset and
  1303. * NUMA mempolicy, and applied also to anonymous pages in do_swap_page();
  1304. * but for now it is a simple matter of zone.
  1305. */
  1306. static bool shmem_should_replace_page(struct page *page, gfp_t gfp)
  1307. {
  1308. return page_zonenum(page) > gfp_zone(gfp);
  1309. }
  1310. static int shmem_replace_page(struct page **pagep, gfp_t gfp,
  1311. struct shmem_inode_info *info, pgoff_t index)
  1312. {
  1313. struct page *oldpage, *newpage;
  1314. struct address_space *swap_mapping;
  1315. pgoff_t swap_index;
  1316. int error;
  1317. oldpage = *pagep;
  1318. swap_index = page_private(oldpage);
  1319. swap_mapping = page_mapping(oldpage);
  1320. /*
  1321. * We have arrived here because our zones are constrained, so don't
  1322. * limit chance of success by further cpuset and node constraints.
  1323. */
  1324. gfp &= ~GFP_CONSTRAINT_MASK;
  1325. newpage = shmem_alloc_page(gfp, info, index);
  1326. if (!newpage)
  1327. return -ENOMEM;
  1328. get_page(newpage);
  1329. copy_highpage(newpage, oldpage);
  1330. flush_dcache_page(newpage);
  1331. __SetPageLocked(newpage);
  1332. __SetPageSwapBacked(newpage);
  1333. SetPageUptodate(newpage);
  1334. set_page_private(newpage, swap_index);
  1335. SetPageSwapCache(newpage);
  1336. /*
  1337. * Our caller will very soon move newpage out of swapcache, but it's
  1338. * a nice clean interface for us to replace oldpage by newpage there.
  1339. */
  1340. spin_lock_irq(&swap_mapping->tree_lock);
  1341. error = shmem_radix_tree_replace(swap_mapping, swap_index, oldpage,
  1342. newpage);
  1343. if (!error) {
  1344. __inc_node_page_state(newpage, NR_FILE_PAGES);
  1345. __dec_node_page_state(oldpage, NR_FILE_PAGES);
  1346. }
  1347. spin_unlock_irq(&swap_mapping->tree_lock);
  1348. if (unlikely(error)) {
  1349. /*
  1350. * Is this possible? I think not, now that our callers check
  1351. * both PageSwapCache and page_private after getting page lock;
  1352. * but be defensive. Reverse old to newpage for clear and free.
  1353. */
  1354. oldpage = newpage;
  1355. } else {
  1356. mem_cgroup_migrate(oldpage, newpage);
  1357. lru_cache_add_anon(newpage);
  1358. *pagep = newpage;
  1359. }
  1360. ClearPageSwapCache(oldpage);
  1361. set_page_private(oldpage, 0);
  1362. unlock_page(oldpage);
  1363. put_page(oldpage);
  1364. put_page(oldpage);
  1365. return error;
  1366. }
  1367. /*
  1368. * shmem_getpage_gfp - find page in cache, or get from swap, or allocate
  1369. *
  1370. * If we allocate a new one we do not mark it dirty. That's up to the
  1371. * vm. If we swap it in we mark it dirty since we also free the swap
  1372. * entry since a page cannot live in both the swap and page cache.
  1373. *
  1374. * fault_mm and fault_type are only supplied by shmem_fault:
  1375. * otherwise they are NULL.
  1376. */
  1377. static int shmem_getpage_gfp(struct inode *inode, pgoff_t index,
  1378. struct page **pagep, enum sgp_type sgp, gfp_t gfp,
  1379. struct mm_struct *fault_mm, int *fault_type)
  1380. {
  1381. struct address_space *mapping = inode->i_mapping;
  1382. struct shmem_inode_info *info = SHMEM_I(inode);
  1383. struct shmem_sb_info *sbinfo;
  1384. struct mm_struct *charge_mm;
  1385. struct mem_cgroup *memcg;
  1386. struct page *page;
  1387. swp_entry_t swap;
  1388. enum sgp_type sgp_huge = sgp;
  1389. pgoff_t hindex = index;
  1390. int error;
  1391. int once = 0;
  1392. int alloced = 0;
  1393. if (index > (MAX_LFS_FILESIZE >> PAGE_SHIFT))
  1394. return -EFBIG;
  1395. if (sgp == SGP_NOHUGE || sgp == SGP_HUGE)
  1396. sgp = SGP_CACHE;
  1397. repeat:
  1398. swap.val = 0;
  1399. page = find_lock_entry(mapping, index);
  1400. if (radix_tree_exceptional_entry(page)) {
  1401. swap = radix_to_swp_entry(page);
  1402. page = NULL;
  1403. }
  1404. if (sgp <= SGP_CACHE &&
  1405. ((loff_t)index << PAGE_SHIFT) >= i_size_read(inode)) {
  1406. error = -EINVAL;
  1407. goto unlock;
  1408. }
  1409. if (page && sgp == SGP_WRITE)
  1410. mark_page_accessed(page);
  1411. /* fallocated page? */
  1412. if (page && !PageUptodate(page)) {
  1413. if (sgp != SGP_READ)
  1414. goto clear;
  1415. unlock_page(page);
  1416. put_page(page);
  1417. page = NULL;
  1418. }
  1419. if (page || (sgp == SGP_READ && !swap.val)) {
  1420. *pagep = page;
  1421. return 0;
  1422. }
  1423. /*
  1424. * Fast cache lookup did not find it:
  1425. * bring it back from swap or allocate.
  1426. */
  1427. sbinfo = SHMEM_SB(inode->i_sb);
  1428. charge_mm = fault_mm ? : current->mm;
  1429. if (swap.val) {
  1430. /* Look it up and read it in.. */
  1431. page = lookup_swap_cache(swap);
  1432. if (!page) {
  1433. /* Or update major stats only when swapin succeeds?? */
  1434. if (fault_type) {
  1435. *fault_type |= VM_FAULT_MAJOR;
  1436. count_vm_event(PGMAJFAULT);
  1437. mem_cgroup_count_vm_event(fault_mm, PGMAJFAULT);
  1438. }
  1439. /* Here we actually start the io */
  1440. page = shmem_swapin(swap, gfp, info, index);
  1441. if (!page) {
  1442. error = -ENOMEM;
  1443. goto failed;
  1444. }
  1445. }
  1446. /* We have to do this with page locked to prevent races */
  1447. lock_page(page);
  1448. if (!PageSwapCache(page) || page_private(page) != swap.val ||
  1449. !shmem_confirm_swap(mapping, index, swap)) {
  1450. error = -EEXIST; /* try again */
  1451. goto unlock;
  1452. }
  1453. if (!PageUptodate(page)) {
  1454. error = -EIO;
  1455. goto failed;
  1456. }
  1457. wait_on_page_writeback(page);
  1458. if (shmem_should_replace_page(page, gfp)) {
  1459. error = shmem_replace_page(&page, gfp, info, index);
  1460. if (error)
  1461. goto failed;
  1462. }
  1463. error = mem_cgroup_try_charge(page, charge_mm, gfp, &memcg,
  1464. false);
  1465. if (!error) {
  1466. error = shmem_add_to_page_cache(page, mapping, index,
  1467. swp_to_radix_entry(swap));
  1468. /*
  1469. * We already confirmed swap under page lock, and make
  1470. * no memory allocation here, so usually no possibility
  1471. * of error; but free_swap_and_cache() only trylocks a
  1472. * page, so it is just possible that the entry has been
  1473. * truncated or holepunched since swap was confirmed.
  1474. * shmem_undo_range() will have done some of the
  1475. * unaccounting, now delete_from_swap_cache() will do
  1476. * the rest.
  1477. * Reset swap.val? No, leave it so "failed" goes back to
  1478. * "repeat": reading a hole and writing should succeed.
  1479. */
  1480. if (error) {
  1481. mem_cgroup_cancel_charge(page, memcg, false);
  1482. delete_from_swap_cache(page);
  1483. }
  1484. }
  1485. if (error)
  1486. goto failed;
  1487. mem_cgroup_commit_charge(page, memcg, true, false);
  1488. spin_lock_irq(&info->lock);
  1489. info->swapped--;
  1490. shmem_recalc_inode(inode);
  1491. spin_unlock_irq(&info->lock);
  1492. if (sgp == SGP_WRITE)
  1493. mark_page_accessed(page);
  1494. delete_from_swap_cache(page);
  1495. set_page_dirty(page);
  1496. swap_free(swap);
  1497. } else {
  1498. /* shmem_symlink() */
  1499. if (mapping->a_ops != &shmem_aops)
  1500. goto alloc_nohuge;
  1501. if (shmem_huge == SHMEM_HUGE_DENY || sgp_huge == SGP_NOHUGE)
  1502. goto alloc_nohuge;
  1503. if (shmem_huge == SHMEM_HUGE_FORCE)
  1504. goto alloc_huge;
  1505. switch (sbinfo->huge) {
  1506. loff_t i_size;
  1507. pgoff_t off;
  1508. case SHMEM_HUGE_NEVER:
  1509. goto alloc_nohuge;
  1510. case SHMEM_HUGE_WITHIN_SIZE:
  1511. off = round_up(index, HPAGE_PMD_NR);
  1512. i_size = round_up(i_size_read(inode), PAGE_SIZE);
  1513. if (i_size >= HPAGE_PMD_SIZE &&
  1514. i_size >> PAGE_SHIFT >= off)
  1515. goto alloc_huge;
  1516. /* fallthrough */
  1517. case SHMEM_HUGE_ADVISE:
  1518. if (sgp_huge == SGP_HUGE)
  1519. goto alloc_huge;
  1520. /* TODO: implement fadvise() hints */
  1521. goto alloc_nohuge;
  1522. }
  1523. alloc_huge:
  1524. page = shmem_alloc_and_acct_page(gfp, info, sbinfo,
  1525. index, true);
  1526. if (IS_ERR(page)) {
  1527. alloc_nohuge: page = shmem_alloc_and_acct_page(gfp, info, sbinfo,
  1528. index, false);
  1529. }
  1530. if (IS_ERR(page)) {
  1531. int retry = 5;
  1532. error = PTR_ERR(page);
  1533. page = NULL;
  1534. if (error != -ENOSPC)
  1535. goto failed;
  1536. /*
  1537. * Try to reclaim some spece by splitting a huge page
  1538. * beyond i_size on the filesystem.
  1539. */
  1540. while (retry--) {
  1541. int ret;
  1542. ret = shmem_unused_huge_shrink(sbinfo, NULL, 1);
  1543. if (ret == SHRINK_STOP)
  1544. break;
  1545. if (ret)
  1546. goto alloc_nohuge;
  1547. }
  1548. goto failed;
  1549. }
  1550. if (PageTransHuge(page))
  1551. hindex = round_down(index, HPAGE_PMD_NR);
  1552. else
  1553. hindex = index;
  1554. if (sgp == SGP_WRITE)
  1555. __SetPageReferenced(page);
  1556. error = mem_cgroup_try_charge(page, charge_mm, gfp, &memcg,
  1557. PageTransHuge(page));
  1558. if (error)
  1559. goto unacct;
  1560. error = radix_tree_maybe_preload_order(gfp & GFP_RECLAIM_MASK,
  1561. compound_order(page));
  1562. if (!error) {
  1563. error = shmem_add_to_page_cache(page, mapping, hindex,
  1564. NULL);
  1565. radix_tree_preload_end();
  1566. }
  1567. if (error) {
  1568. mem_cgroup_cancel_charge(page, memcg,
  1569. PageTransHuge(page));
  1570. goto unacct;
  1571. }
  1572. mem_cgroup_commit_charge(page, memcg, false,
  1573. PageTransHuge(page));
  1574. lru_cache_add_anon(page);
  1575. spin_lock_irq(&info->lock);
  1576. info->alloced += 1 << compound_order(page);
  1577. inode->i_blocks += BLOCKS_PER_PAGE << compound_order(page);
  1578. shmem_recalc_inode(inode);
  1579. spin_unlock_irq(&info->lock);
  1580. alloced = true;
  1581. if (PageTransHuge(page) &&
  1582. DIV_ROUND_UP(i_size_read(inode), PAGE_SIZE) <
  1583. hindex + HPAGE_PMD_NR - 1) {
  1584. /*
  1585. * Part of the huge page is beyond i_size: subject
  1586. * to shrink under memory pressure.
  1587. */
  1588. spin_lock(&sbinfo->shrinklist_lock);
  1589. /*
  1590. * _careful to defend against unlocked access to
  1591. * ->shrink_list in shmem_unused_huge_shrink()
  1592. */
  1593. if (list_empty_careful(&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. cond_resched_rcu();
  2201. slot = radix_tree_iter_next(&iter);
  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. cond_resched_rcu();
  2261. slot = radix_tree_iter_next(&iter);
  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. .readlink = generic_readlink,
  2842. .get_link = simple_get_link,
  2843. #ifdef CONFIG_TMPFS_XATTR
  2844. .listxattr = shmem_listxattr,
  2845. #endif
  2846. };
  2847. static const struct inode_operations shmem_symlink_inode_operations = {
  2848. .readlink = generic_readlink,
  2849. .get_link = shmem_get_link,
  2850. #ifdef CONFIG_TMPFS_XATTR
  2851. .listxattr = shmem_listxattr,
  2852. #endif
  2853. };
  2854. static struct dentry *shmem_get_parent(struct dentry *child)
  2855. {
  2856. return ERR_PTR(-ESTALE);
  2857. }
  2858. static int shmem_match(struct inode *ino, void *vfh)
  2859. {
  2860. __u32 *fh = vfh;
  2861. __u64 inum = fh[2];
  2862. inum = (inum << 32) | fh[1];
  2863. return ino->i_ino == inum && fh[0] == ino->i_generation;
  2864. }
  2865. static struct dentry *shmem_fh_to_dentry(struct super_block *sb,
  2866. struct fid *fid, int fh_len, int fh_type)
  2867. {
  2868. struct inode *inode;
  2869. struct dentry *dentry = NULL;
  2870. u64 inum;
  2871. if (fh_len < 3)
  2872. return NULL;
  2873. inum = fid->raw[2];
  2874. inum = (inum << 32) | fid->raw[1];
  2875. inode = ilookup5(sb, (unsigned long)(inum + fid->raw[0]),
  2876. shmem_match, fid->raw);
  2877. if (inode) {
  2878. dentry = d_find_alias(inode);
  2879. iput(inode);
  2880. }
  2881. return dentry;
  2882. }
  2883. static int shmem_encode_fh(struct inode *inode, __u32 *fh, int *len,
  2884. struct inode *parent)
  2885. {
  2886. if (*len < 3) {
  2887. *len = 3;
  2888. return FILEID_INVALID;
  2889. }
  2890. if (inode_unhashed(inode)) {
  2891. /* Unfortunately insert_inode_hash is not idempotent,
  2892. * so as we hash inodes here rather than at creation
  2893. * time, we need a lock to ensure we only try
  2894. * to do it once
  2895. */
  2896. static DEFINE_SPINLOCK(lock);
  2897. spin_lock(&lock);
  2898. if (inode_unhashed(inode))
  2899. __insert_inode_hash(inode,
  2900. inode->i_ino + inode->i_generation);
  2901. spin_unlock(&lock);
  2902. }
  2903. fh[0] = inode->i_generation;
  2904. fh[1] = inode->i_ino;
  2905. fh[2] = ((__u64)inode->i_ino) >> 32;
  2906. *len = 3;
  2907. return 1;
  2908. }
  2909. static const struct export_operations shmem_export_ops = {
  2910. .get_parent = shmem_get_parent,
  2911. .encode_fh = shmem_encode_fh,
  2912. .fh_to_dentry = shmem_fh_to_dentry,
  2913. };
  2914. static int shmem_parse_options(char *options, struct shmem_sb_info *sbinfo,
  2915. bool remount)
  2916. {
  2917. char *this_char, *value, *rest;
  2918. struct mempolicy *mpol = NULL;
  2919. uid_t uid;
  2920. gid_t gid;
  2921. while (options != NULL) {
  2922. this_char = options;
  2923. for (;;) {
  2924. /*
  2925. * NUL-terminate this option: unfortunately,
  2926. * mount options form a comma-separated list,
  2927. * but mpol's nodelist may also contain commas.
  2928. */
  2929. options = strchr(options, ',');
  2930. if (options == NULL)
  2931. break;
  2932. options++;
  2933. if (!isdigit(*options)) {
  2934. options[-1] = '\0';
  2935. break;
  2936. }
  2937. }
  2938. if (!*this_char)
  2939. continue;
  2940. if ((value = strchr(this_char,'=')) != NULL) {
  2941. *value++ = 0;
  2942. } else {
  2943. pr_err("tmpfs: No value for mount option '%s'\n",
  2944. this_char);
  2945. goto error;
  2946. }
  2947. if (!strcmp(this_char,"size")) {
  2948. unsigned long long size;
  2949. size = memparse(value,&rest);
  2950. if (*rest == '%') {
  2951. size <<= PAGE_SHIFT;
  2952. size *= totalram_pages;
  2953. do_div(size, 100);
  2954. rest++;
  2955. }
  2956. if (*rest)
  2957. goto bad_val;
  2958. sbinfo->max_blocks =
  2959. DIV_ROUND_UP(size, PAGE_SIZE);
  2960. } else if (!strcmp(this_char,"nr_blocks")) {
  2961. sbinfo->max_blocks = memparse(value, &rest);
  2962. if (*rest)
  2963. goto bad_val;
  2964. } else if (!strcmp(this_char,"nr_inodes")) {
  2965. sbinfo->max_inodes = memparse(value, &rest);
  2966. if (*rest)
  2967. goto bad_val;
  2968. } else if (!strcmp(this_char,"mode")) {
  2969. if (remount)
  2970. continue;
  2971. sbinfo->mode = simple_strtoul(value, &rest, 8) & 07777;
  2972. if (*rest)
  2973. goto bad_val;
  2974. } else if (!strcmp(this_char,"uid")) {
  2975. if (remount)
  2976. continue;
  2977. uid = simple_strtoul(value, &rest, 0);
  2978. if (*rest)
  2979. goto bad_val;
  2980. sbinfo->uid = make_kuid(current_user_ns(), uid);
  2981. if (!uid_valid(sbinfo->uid))
  2982. goto bad_val;
  2983. } else if (!strcmp(this_char,"gid")) {
  2984. if (remount)
  2985. continue;
  2986. gid = simple_strtoul(value, &rest, 0);
  2987. if (*rest)
  2988. goto bad_val;
  2989. sbinfo->gid = make_kgid(current_user_ns(), gid);
  2990. if (!gid_valid(sbinfo->gid))
  2991. goto bad_val;
  2992. #ifdef CONFIG_TRANSPARENT_HUGE_PAGECACHE
  2993. } else if (!strcmp(this_char, "huge")) {
  2994. int huge;
  2995. huge = shmem_parse_huge(value);
  2996. if (huge < 0)
  2997. goto bad_val;
  2998. if (!has_transparent_hugepage() &&
  2999. huge != SHMEM_HUGE_NEVER)
  3000. goto bad_val;
  3001. sbinfo->huge = huge;
  3002. #endif
  3003. #ifdef CONFIG_NUMA
  3004. } else if (!strcmp(this_char,"mpol")) {
  3005. mpol_put(mpol);
  3006. mpol = NULL;
  3007. if (mpol_parse_str(value, &mpol))
  3008. goto bad_val;
  3009. #endif
  3010. } else {
  3011. pr_err("tmpfs: Bad mount option %s\n", this_char);
  3012. goto error;
  3013. }
  3014. }
  3015. sbinfo->mpol = mpol;
  3016. return 0;
  3017. bad_val:
  3018. pr_err("tmpfs: Bad value '%s' for mount option '%s'\n",
  3019. value, this_char);
  3020. error:
  3021. mpol_put(mpol);
  3022. return 1;
  3023. }
  3024. static int shmem_remount_fs(struct super_block *sb, int *flags, char *data)
  3025. {
  3026. struct shmem_sb_info *sbinfo = SHMEM_SB(sb);
  3027. struct shmem_sb_info config = *sbinfo;
  3028. unsigned long inodes;
  3029. int error = -EINVAL;
  3030. config.mpol = NULL;
  3031. if (shmem_parse_options(data, &config, true))
  3032. return error;
  3033. spin_lock(&sbinfo->stat_lock);
  3034. inodes = sbinfo->max_inodes - sbinfo->free_inodes;
  3035. if (percpu_counter_compare(&sbinfo->used_blocks, config.max_blocks) > 0)
  3036. goto out;
  3037. if (config.max_inodes < inodes)
  3038. goto out;
  3039. /*
  3040. * Those tests disallow limited->unlimited while any are in use;
  3041. * but we must separately disallow unlimited->limited, because
  3042. * in that case we have no record of how much is already in use.
  3043. */
  3044. if (config.max_blocks && !sbinfo->max_blocks)
  3045. goto out;
  3046. if (config.max_inodes && !sbinfo->max_inodes)
  3047. goto out;
  3048. error = 0;
  3049. sbinfo->huge = config.huge;
  3050. sbinfo->max_blocks = config.max_blocks;
  3051. sbinfo->max_inodes = config.max_inodes;
  3052. sbinfo->free_inodes = config.max_inodes - inodes;
  3053. /*
  3054. * Preserve previous mempolicy unless mpol remount option was specified.
  3055. */
  3056. if (config.mpol) {
  3057. mpol_put(sbinfo->mpol);
  3058. sbinfo->mpol = config.mpol; /* transfers initial ref */
  3059. }
  3060. out:
  3061. spin_unlock(&sbinfo->stat_lock);
  3062. return error;
  3063. }
  3064. static int shmem_show_options(struct seq_file *seq, struct dentry *root)
  3065. {
  3066. struct shmem_sb_info *sbinfo = SHMEM_SB(root->d_sb);
  3067. if (sbinfo->max_blocks != shmem_default_max_blocks())
  3068. seq_printf(seq, ",size=%luk",
  3069. sbinfo->max_blocks << (PAGE_SHIFT - 10));
  3070. if (sbinfo->max_inodes != shmem_default_max_inodes())
  3071. seq_printf(seq, ",nr_inodes=%lu", sbinfo->max_inodes);
  3072. if (sbinfo->mode != (S_IRWXUGO | S_ISVTX))
  3073. seq_printf(seq, ",mode=%03ho", sbinfo->mode);
  3074. if (!uid_eq(sbinfo->uid, GLOBAL_ROOT_UID))
  3075. seq_printf(seq, ",uid=%u",
  3076. from_kuid_munged(&init_user_ns, sbinfo->uid));
  3077. if (!gid_eq(sbinfo->gid, GLOBAL_ROOT_GID))
  3078. seq_printf(seq, ",gid=%u",
  3079. from_kgid_munged(&init_user_ns, sbinfo->gid));
  3080. #ifdef CONFIG_TRANSPARENT_HUGE_PAGECACHE
  3081. /* Rightly or wrongly, show huge mount option unmasked by shmem_huge */
  3082. if (sbinfo->huge)
  3083. seq_printf(seq, ",huge=%s", shmem_format_huge(sbinfo->huge));
  3084. #endif
  3085. shmem_show_mpol(seq, sbinfo->mpol);
  3086. return 0;
  3087. }
  3088. #define MFD_NAME_PREFIX "memfd:"
  3089. #define MFD_NAME_PREFIX_LEN (sizeof(MFD_NAME_PREFIX) - 1)
  3090. #define MFD_NAME_MAX_LEN (NAME_MAX - MFD_NAME_PREFIX_LEN)
  3091. #define MFD_ALL_FLAGS (MFD_CLOEXEC | MFD_ALLOW_SEALING)
  3092. SYSCALL_DEFINE2(memfd_create,
  3093. const char __user *, uname,
  3094. unsigned int, flags)
  3095. {
  3096. struct shmem_inode_info *info;
  3097. struct file *file;
  3098. int fd, error;
  3099. char *name;
  3100. long len;
  3101. if (flags & ~(unsigned int)MFD_ALL_FLAGS)
  3102. return -EINVAL;
  3103. /* length includes terminating zero */
  3104. len = strnlen_user(uname, MFD_NAME_MAX_LEN + 1);
  3105. if (len <= 0)
  3106. return -EFAULT;
  3107. if (len > MFD_NAME_MAX_LEN + 1)
  3108. return -EINVAL;
  3109. name = kmalloc(len + MFD_NAME_PREFIX_LEN, GFP_TEMPORARY);
  3110. if (!name)
  3111. return -ENOMEM;
  3112. strcpy(name, MFD_NAME_PREFIX);
  3113. if (copy_from_user(&name[MFD_NAME_PREFIX_LEN], uname, len)) {
  3114. error = -EFAULT;
  3115. goto err_name;
  3116. }
  3117. /* terminating-zero may have changed after strnlen_user() returned */
  3118. if (name[len + MFD_NAME_PREFIX_LEN - 1]) {
  3119. error = -EFAULT;
  3120. goto err_name;
  3121. }
  3122. fd = get_unused_fd_flags((flags & MFD_CLOEXEC) ? O_CLOEXEC : 0);
  3123. if (fd < 0) {
  3124. error = fd;
  3125. goto err_name;
  3126. }
  3127. file = shmem_file_setup(name, 0, VM_NORESERVE);
  3128. if (IS_ERR(file)) {
  3129. error = PTR_ERR(file);
  3130. goto err_fd;
  3131. }
  3132. info = SHMEM_I(file_inode(file));
  3133. file->f_mode |= FMODE_LSEEK | FMODE_PREAD | FMODE_PWRITE;
  3134. file->f_flags |= O_RDWR | O_LARGEFILE;
  3135. if (flags & MFD_ALLOW_SEALING)
  3136. info->seals &= ~F_SEAL_SEAL;
  3137. fd_install(fd, file);
  3138. kfree(name);
  3139. return fd;
  3140. err_fd:
  3141. put_unused_fd(fd);
  3142. err_name:
  3143. kfree(name);
  3144. return error;
  3145. }
  3146. #endif /* CONFIG_TMPFS */
  3147. static void shmem_put_super(struct super_block *sb)
  3148. {
  3149. struct shmem_sb_info *sbinfo = SHMEM_SB(sb);
  3150. percpu_counter_destroy(&sbinfo->used_blocks);
  3151. mpol_put(sbinfo->mpol);
  3152. kfree(sbinfo);
  3153. sb->s_fs_info = NULL;
  3154. }
  3155. int shmem_fill_super(struct super_block *sb, void *data, int silent)
  3156. {
  3157. struct inode *inode;
  3158. struct shmem_sb_info *sbinfo;
  3159. int err = -ENOMEM;
  3160. /* Round up to L1_CACHE_BYTES to resist false sharing */
  3161. sbinfo = kzalloc(max((int)sizeof(struct shmem_sb_info),
  3162. L1_CACHE_BYTES), GFP_KERNEL);
  3163. if (!sbinfo)
  3164. return -ENOMEM;
  3165. sbinfo->mode = S_IRWXUGO | S_ISVTX;
  3166. sbinfo->uid = current_fsuid();
  3167. sbinfo->gid = current_fsgid();
  3168. sb->s_fs_info = sbinfo;
  3169. #ifdef CONFIG_TMPFS
  3170. /*
  3171. * Per default we only allow half of the physical ram per
  3172. * tmpfs instance, limiting inodes to one per page of lowmem;
  3173. * but the internal instance is left unlimited.
  3174. */
  3175. if (!(sb->s_flags & MS_KERNMOUNT)) {
  3176. sbinfo->max_blocks = shmem_default_max_blocks();
  3177. sbinfo->max_inodes = shmem_default_max_inodes();
  3178. if (shmem_parse_options(data, sbinfo, false)) {
  3179. err = -EINVAL;
  3180. goto failed;
  3181. }
  3182. } else {
  3183. sb->s_flags |= MS_NOUSER;
  3184. }
  3185. sb->s_export_op = &shmem_export_ops;
  3186. sb->s_flags |= MS_NOSEC;
  3187. #else
  3188. sb->s_flags |= MS_NOUSER;
  3189. #endif
  3190. spin_lock_init(&sbinfo->stat_lock);
  3191. if (percpu_counter_init(&sbinfo->used_blocks, 0, GFP_KERNEL))
  3192. goto failed;
  3193. sbinfo->free_inodes = sbinfo->max_inodes;
  3194. spin_lock_init(&sbinfo->shrinklist_lock);
  3195. INIT_LIST_HEAD(&sbinfo->shrinklist);
  3196. sb->s_maxbytes = MAX_LFS_FILESIZE;
  3197. sb->s_blocksize = PAGE_SIZE;
  3198. sb->s_blocksize_bits = PAGE_SHIFT;
  3199. sb->s_magic = TMPFS_MAGIC;
  3200. sb->s_op = &shmem_ops;
  3201. sb->s_time_gran = 1;
  3202. #ifdef CONFIG_TMPFS_XATTR
  3203. sb->s_xattr = shmem_xattr_handlers;
  3204. #endif
  3205. #ifdef CONFIG_TMPFS_POSIX_ACL
  3206. sb->s_flags |= MS_POSIXACL;
  3207. #endif
  3208. inode = shmem_get_inode(sb, NULL, S_IFDIR | sbinfo->mode, 0, VM_NORESERVE);
  3209. if (!inode)
  3210. goto failed;
  3211. inode->i_uid = sbinfo->uid;
  3212. inode->i_gid = sbinfo->gid;
  3213. sb->s_root = d_make_root(inode);
  3214. if (!sb->s_root)
  3215. goto failed;
  3216. return 0;
  3217. failed:
  3218. shmem_put_super(sb);
  3219. return err;
  3220. }
  3221. static struct kmem_cache *shmem_inode_cachep;
  3222. static struct inode *shmem_alloc_inode(struct super_block *sb)
  3223. {
  3224. struct shmem_inode_info *info;
  3225. info = kmem_cache_alloc(shmem_inode_cachep, GFP_KERNEL);
  3226. if (!info)
  3227. return NULL;
  3228. return &info->vfs_inode;
  3229. }
  3230. static void shmem_destroy_callback(struct rcu_head *head)
  3231. {
  3232. struct inode *inode = container_of(head, struct inode, i_rcu);
  3233. if (S_ISLNK(inode->i_mode))
  3234. kfree(inode->i_link);
  3235. kmem_cache_free(shmem_inode_cachep, SHMEM_I(inode));
  3236. }
  3237. static void shmem_destroy_inode(struct inode *inode)
  3238. {
  3239. if (S_ISREG(inode->i_mode))
  3240. mpol_free_shared_policy(&SHMEM_I(inode)->policy);
  3241. call_rcu(&inode->i_rcu, shmem_destroy_callback);
  3242. }
  3243. static void shmem_init_inode(void *foo)
  3244. {
  3245. struct shmem_inode_info *info = foo;
  3246. inode_init_once(&info->vfs_inode);
  3247. }
  3248. static int shmem_init_inodecache(void)
  3249. {
  3250. shmem_inode_cachep = kmem_cache_create("shmem_inode_cache",
  3251. sizeof(struct shmem_inode_info),
  3252. 0, SLAB_PANIC|SLAB_ACCOUNT, shmem_init_inode);
  3253. return 0;
  3254. }
  3255. static void shmem_destroy_inodecache(void)
  3256. {
  3257. kmem_cache_destroy(shmem_inode_cachep);
  3258. }
  3259. static const struct address_space_operations shmem_aops = {
  3260. .writepage = shmem_writepage,
  3261. .set_page_dirty = __set_page_dirty_no_writeback,
  3262. #ifdef CONFIG_TMPFS
  3263. .write_begin = shmem_write_begin,
  3264. .write_end = shmem_write_end,
  3265. #endif
  3266. #ifdef CONFIG_MIGRATION
  3267. .migratepage = migrate_page,
  3268. #endif
  3269. .error_remove_page = generic_error_remove_page,
  3270. };
  3271. static const struct file_operations shmem_file_operations = {
  3272. .mmap = shmem_mmap,
  3273. .get_unmapped_area = shmem_get_unmapped_area,
  3274. #ifdef CONFIG_TMPFS
  3275. .llseek = shmem_file_llseek,
  3276. .read_iter = shmem_file_read_iter,
  3277. .write_iter = generic_file_write_iter,
  3278. .fsync = noop_fsync,
  3279. .splice_read = generic_file_splice_read,
  3280. .splice_write = iter_file_splice_write,
  3281. .fallocate = shmem_fallocate,
  3282. #endif
  3283. };
  3284. static const struct inode_operations shmem_inode_operations = {
  3285. .getattr = shmem_getattr,
  3286. .setattr = shmem_setattr,
  3287. #ifdef CONFIG_TMPFS_XATTR
  3288. .listxattr = shmem_listxattr,
  3289. .set_acl = simple_set_acl,
  3290. #endif
  3291. };
  3292. static const struct inode_operations shmem_dir_inode_operations = {
  3293. #ifdef CONFIG_TMPFS
  3294. .create = shmem_create,
  3295. .lookup = simple_lookup,
  3296. .link = shmem_link,
  3297. .unlink = shmem_unlink,
  3298. .symlink = shmem_symlink,
  3299. .mkdir = shmem_mkdir,
  3300. .rmdir = shmem_rmdir,
  3301. .mknod = shmem_mknod,
  3302. .rename = shmem_rename2,
  3303. .tmpfile = shmem_tmpfile,
  3304. #endif
  3305. #ifdef CONFIG_TMPFS_XATTR
  3306. .listxattr = shmem_listxattr,
  3307. #endif
  3308. #ifdef CONFIG_TMPFS_POSIX_ACL
  3309. .setattr = shmem_setattr,
  3310. .set_acl = simple_set_acl,
  3311. #endif
  3312. };
  3313. static const struct inode_operations shmem_special_inode_operations = {
  3314. #ifdef CONFIG_TMPFS_XATTR
  3315. .listxattr = shmem_listxattr,
  3316. #endif
  3317. #ifdef CONFIG_TMPFS_POSIX_ACL
  3318. .setattr = shmem_setattr,
  3319. .set_acl = simple_set_acl,
  3320. #endif
  3321. };
  3322. static const struct super_operations shmem_ops = {
  3323. .alloc_inode = shmem_alloc_inode,
  3324. .destroy_inode = shmem_destroy_inode,
  3325. #ifdef CONFIG_TMPFS
  3326. .statfs = shmem_statfs,
  3327. .remount_fs = shmem_remount_fs,
  3328. .show_options = shmem_show_options,
  3329. #endif
  3330. .evict_inode = shmem_evict_inode,
  3331. .drop_inode = generic_delete_inode,
  3332. .put_super = shmem_put_super,
  3333. #ifdef CONFIG_TRANSPARENT_HUGE_PAGECACHE
  3334. .nr_cached_objects = shmem_unused_huge_count,
  3335. .free_cached_objects = shmem_unused_huge_scan,
  3336. #endif
  3337. };
  3338. static const struct vm_operations_struct shmem_vm_ops = {
  3339. .fault = shmem_fault,
  3340. .map_pages = filemap_map_pages,
  3341. #ifdef CONFIG_NUMA
  3342. .set_policy = shmem_set_policy,
  3343. .get_policy = shmem_get_policy,
  3344. #endif
  3345. };
  3346. static struct dentry *shmem_mount(struct file_system_type *fs_type,
  3347. int flags, const char *dev_name, void *data)
  3348. {
  3349. return mount_nodev(fs_type, flags, data, shmem_fill_super);
  3350. }
  3351. static struct file_system_type shmem_fs_type = {
  3352. .owner = THIS_MODULE,
  3353. .name = "tmpfs",
  3354. .mount = shmem_mount,
  3355. .kill_sb = kill_litter_super,
  3356. .fs_flags = FS_USERNS_MOUNT,
  3357. };
  3358. int __init shmem_init(void)
  3359. {
  3360. int error;
  3361. /* If rootfs called this, don't re-init */
  3362. if (shmem_inode_cachep)
  3363. return 0;
  3364. error = shmem_init_inodecache();
  3365. if (error)
  3366. goto out3;
  3367. error = register_filesystem(&shmem_fs_type);
  3368. if (error) {
  3369. pr_err("Could not register tmpfs\n");
  3370. goto out2;
  3371. }
  3372. shm_mnt = kern_mount(&shmem_fs_type);
  3373. if (IS_ERR(shm_mnt)) {
  3374. error = PTR_ERR(shm_mnt);
  3375. pr_err("Could not kern_mount tmpfs\n");
  3376. goto out1;
  3377. }
  3378. #ifdef CONFIG_TRANSPARENT_HUGE_PAGECACHE
  3379. if (has_transparent_hugepage() && shmem_huge > SHMEM_HUGE_DENY)
  3380. SHMEM_SB(shm_mnt->mnt_sb)->huge = shmem_huge;
  3381. else
  3382. shmem_huge = 0; /* just in case it was patched */
  3383. #endif
  3384. return 0;
  3385. out1:
  3386. unregister_filesystem(&shmem_fs_type);
  3387. out2:
  3388. shmem_destroy_inodecache();
  3389. out3:
  3390. shm_mnt = ERR_PTR(error);
  3391. return error;
  3392. }
  3393. #if defined(CONFIG_TRANSPARENT_HUGE_PAGECACHE) && defined(CONFIG_SYSFS)
  3394. static ssize_t shmem_enabled_show(struct kobject *kobj,
  3395. struct kobj_attribute *attr, char *buf)
  3396. {
  3397. int values[] = {
  3398. SHMEM_HUGE_ALWAYS,
  3399. SHMEM_HUGE_WITHIN_SIZE,
  3400. SHMEM_HUGE_ADVISE,
  3401. SHMEM_HUGE_NEVER,
  3402. SHMEM_HUGE_DENY,
  3403. SHMEM_HUGE_FORCE,
  3404. };
  3405. int i, count;
  3406. for (i = 0, count = 0; i < ARRAY_SIZE(values); i++) {
  3407. const char *fmt = shmem_huge == values[i] ? "[%s] " : "%s ";
  3408. count += sprintf(buf + count, fmt,
  3409. shmem_format_huge(values[i]));
  3410. }
  3411. buf[count - 1] = '\n';
  3412. return count;
  3413. }
  3414. static ssize_t shmem_enabled_store(struct kobject *kobj,
  3415. struct kobj_attribute *attr, const char *buf, size_t count)
  3416. {
  3417. char tmp[16];
  3418. int huge;
  3419. if (count + 1 > sizeof(tmp))
  3420. return -EINVAL;
  3421. memcpy(tmp, buf, count);
  3422. tmp[count] = '\0';
  3423. if (count && tmp[count - 1] == '\n')
  3424. tmp[count - 1] = '\0';
  3425. huge = shmem_parse_huge(tmp);
  3426. if (huge == -EINVAL)
  3427. return -EINVAL;
  3428. if (!has_transparent_hugepage() &&
  3429. huge != SHMEM_HUGE_NEVER && huge != SHMEM_HUGE_DENY)
  3430. return -EINVAL;
  3431. shmem_huge = huge;
  3432. if (shmem_huge > SHMEM_HUGE_DENY)
  3433. SHMEM_SB(shm_mnt->mnt_sb)->huge = shmem_huge;
  3434. return count;
  3435. }
  3436. struct kobj_attribute shmem_enabled_attr =
  3437. __ATTR(shmem_enabled, 0644, shmem_enabled_show, shmem_enabled_store);
  3438. #endif /* CONFIG_TRANSPARENT_HUGE_PAGECACHE && CONFIG_SYSFS */
  3439. #ifdef CONFIG_TRANSPARENT_HUGE_PAGECACHE
  3440. bool shmem_huge_enabled(struct vm_area_struct *vma)
  3441. {
  3442. struct inode *inode = file_inode(vma->vm_file);
  3443. struct shmem_sb_info *sbinfo = SHMEM_SB(inode->i_sb);
  3444. loff_t i_size;
  3445. pgoff_t off;
  3446. if (shmem_huge == SHMEM_HUGE_FORCE)
  3447. return true;
  3448. if (shmem_huge == SHMEM_HUGE_DENY)
  3449. return false;
  3450. switch (sbinfo->huge) {
  3451. case SHMEM_HUGE_NEVER:
  3452. return false;
  3453. case SHMEM_HUGE_ALWAYS:
  3454. return true;
  3455. case SHMEM_HUGE_WITHIN_SIZE:
  3456. off = round_up(vma->vm_pgoff, HPAGE_PMD_NR);
  3457. i_size = round_up(i_size_read(inode), PAGE_SIZE);
  3458. if (i_size >= HPAGE_PMD_SIZE &&
  3459. i_size >> PAGE_SHIFT >= off)
  3460. return true;
  3461. case SHMEM_HUGE_ADVISE:
  3462. /* TODO: implement fadvise() hints */
  3463. return (vma->vm_flags & VM_HUGEPAGE);
  3464. default:
  3465. VM_BUG_ON(1);
  3466. return false;
  3467. }
  3468. }
  3469. #endif /* CONFIG_TRANSPARENT_HUGE_PAGECACHE */
  3470. #else /* !CONFIG_SHMEM */
  3471. /*
  3472. * tiny-shmem: simple shmemfs and tmpfs using ramfs code
  3473. *
  3474. * This is intended for small system where the benefits of the full
  3475. * shmem code (swap-backed and resource-limited) are outweighed by
  3476. * their complexity. On systems without swap this code should be
  3477. * effectively equivalent, but much lighter weight.
  3478. */
  3479. static struct file_system_type shmem_fs_type = {
  3480. .name = "tmpfs",
  3481. .mount = ramfs_mount,
  3482. .kill_sb = kill_litter_super,
  3483. .fs_flags = FS_USERNS_MOUNT,
  3484. };
  3485. int __init shmem_init(void)
  3486. {
  3487. BUG_ON(register_filesystem(&shmem_fs_type) != 0);
  3488. shm_mnt = kern_mount(&shmem_fs_type);
  3489. BUG_ON(IS_ERR(shm_mnt));
  3490. return 0;
  3491. }
  3492. int shmem_unuse(swp_entry_t swap, struct page *page)
  3493. {
  3494. return 0;
  3495. }
  3496. int shmem_lock(struct file *file, int lock, struct user_struct *user)
  3497. {
  3498. return 0;
  3499. }
  3500. void shmem_unlock_mapping(struct address_space *mapping)
  3501. {
  3502. }
  3503. #ifdef CONFIG_MMU
  3504. unsigned long shmem_get_unmapped_area(struct file *file,
  3505. unsigned long addr, unsigned long len,
  3506. unsigned long pgoff, unsigned long flags)
  3507. {
  3508. return current->mm->get_unmapped_area(file, addr, len, pgoff, flags);
  3509. }
  3510. #endif
  3511. void shmem_truncate_range(struct inode *inode, loff_t lstart, loff_t lend)
  3512. {
  3513. truncate_inode_pages_range(inode->i_mapping, lstart, lend);
  3514. }
  3515. EXPORT_SYMBOL_GPL(shmem_truncate_range);
  3516. #define shmem_vm_ops generic_file_vm_ops
  3517. #define shmem_file_operations ramfs_file_operations
  3518. #define shmem_get_inode(sb, dir, mode, dev, flags) ramfs_get_inode(sb, dir, mode, dev)
  3519. #define shmem_acct_size(flags, size) 0
  3520. #define shmem_unacct_size(flags, size) do {} while (0)
  3521. #endif /* CONFIG_SHMEM */
  3522. /* common code */
  3523. static const struct dentry_operations anon_ops = {
  3524. .d_dname = simple_dname
  3525. };
  3526. static struct file *__shmem_file_setup(const char *name, loff_t size,
  3527. unsigned long flags, unsigned int i_flags)
  3528. {
  3529. struct file *res;
  3530. struct inode *inode;
  3531. struct path path;
  3532. struct super_block *sb;
  3533. struct qstr this;
  3534. if (IS_ERR(shm_mnt))
  3535. return ERR_CAST(shm_mnt);
  3536. if (size < 0 || size > MAX_LFS_FILESIZE)
  3537. return ERR_PTR(-EINVAL);
  3538. if (shmem_acct_size(flags, size))
  3539. return ERR_PTR(-ENOMEM);
  3540. res = ERR_PTR(-ENOMEM);
  3541. this.name = name;
  3542. this.len = strlen(name);
  3543. this.hash = 0; /* will go */
  3544. sb = shm_mnt->mnt_sb;
  3545. path.mnt = mntget(shm_mnt);
  3546. path.dentry = d_alloc_pseudo(sb, &this);
  3547. if (!path.dentry)
  3548. goto put_memory;
  3549. d_set_d_op(path.dentry, &anon_ops);
  3550. res = ERR_PTR(-ENOSPC);
  3551. inode = shmem_get_inode(sb, NULL, S_IFREG | S_IRWXUGO, 0, flags);
  3552. if (!inode)
  3553. goto put_memory;
  3554. inode->i_flags |= i_flags;
  3555. d_instantiate(path.dentry, inode);
  3556. inode->i_size = size;
  3557. clear_nlink(inode); /* It is unlinked */
  3558. res = ERR_PTR(ramfs_nommu_expand_for_mapping(inode, size));
  3559. if (IS_ERR(res))
  3560. goto put_path;
  3561. res = alloc_file(&path, FMODE_WRITE | FMODE_READ,
  3562. &shmem_file_operations);
  3563. if (IS_ERR(res))
  3564. goto put_path;
  3565. return res;
  3566. put_memory:
  3567. shmem_unacct_size(flags, size);
  3568. put_path:
  3569. path_put(&path);
  3570. return res;
  3571. }
  3572. /**
  3573. * shmem_kernel_file_setup - get an unlinked file living in tmpfs which must be
  3574. * kernel internal. There will be NO LSM permission checks against the
  3575. * underlying inode. So users of this interface must do LSM checks at a
  3576. * higher layer. The users are the big_key and shm implementations. LSM
  3577. * checks are provided at the key or shm level rather than the inode.
  3578. * @name: name for dentry (to be seen in /proc/<pid>/maps
  3579. * @size: size to be set for the file
  3580. * @flags: VM_NORESERVE suppresses pre-accounting of the entire object size
  3581. */
  3582. struct file *shmem_kernel_file_setup(const char *name, loff_t size, unsigned long flags)
  3583. {
  3584. return __shmem_file_setup(name, size, flags, S_PRIVATE);
  3585. }
  3586. /**
  3587. * shmem_file_setup - get an unlinked file living in tmpfs
  3588. * @name: name for dentry (to be seen in /proc/<pid>/maps
  3589. * @size: size to be set for the file
  3590. * @flags: VM_NORESERVE suppresses pre-accounting of the entire object size
  3591. */
  3592. struct file *shmem_file_setup(const char *name, loff_t size, unsigned long flags)
  3593. {
  3594. return __shmem_file_setup(name, size, flags, 0);
  3595. }
  3596. EXPORT_SYMBOL_GPL(shmem_file_setup);
  3597. /**
  3598. * shmem_zero_setup - setup a shared anonymous mapping
  3599. * @vma: the vma to be mmapped is prepared by do_mmap_pgoff
  3600. */
  3601. int shmem_zero_setup(struct vm_area_struct *vma)
  3602. {
  3603. struct file *file;
  3604. loff_t size = vma->vm_end - vma->vm_start;
  3605. /*
  3606. * Cloning a new file under mmap_sem leads to a lock ordering conflict
  3607. * between XFS directory reading and selinux: since this file is only
  3608. * accessible to the user through its mapping, use S_PRIVATE flag to
  3609. * bypass file security, in the same way as shmem_kernel_file_setup().
  3610. */
  3611. file = __shmem_file_setup("dev/zero", size, vma->vm_flags, S_PRIVATE);
  3612. if (IS_ERR(file))
  3613. return PTR_ERR(file);
  3614. if (vma->vm_file)
  3615. fput(vma->vm_file);
  3616. vma->vm_file = file;
  3617. vma->vm_ops = &shmem_vm_ops;
  3618. if (IS_ENABLED(CONFIG_TRANSPARENT_HUGE_PAGECACHE) &&
  3619. ((vma->vm_start + ~HPAGE_PMD_MASK) & HPAGE_PMD_MASK) <
  3620. (vma->vm_end & HPAGE_PMD_MASK)) {
  3621. khugepaged_enter(vma, vma->vm_flags);
  3622. }
  3623. return 0;
  3624. }
  3625. /**
  3626. * shmem_read_mapping_page_gfp - read into page cache, using specified page allocation flags.
  3627. * @mapping: the page's address_space
  3628. * @index: the page index
  3629. * @gfp: the page allocator flags to use if allocating
  3630. *
  3631. * This behaves as a tmpfs "read_cache_page_gfp(mapping, index, gfp)",
  3632. * with any new page allocations done using the specified allocation flags.
  3633. * But read_cache_page_gfp() uses the ->readpage() method: which does not
  3634. * suit tmpfs, since it may have pages in swapcache, and needs to find those
  3635. * for itself; although drivers/gpu/drm i915 and ttm rely upon this support.
  3636. *
  3637. * i915_gem_object_get_pages_gtt() mixes __GFP_NORETRY | __GFP_NOWARN in
  3638. * with the mapping_gfp_mask(), to avoid OOMing the machine unnecessarily.
  3639. */
  3640. struct page *shmem_read_mapping_page_gfp(struct address_space *mapping,
  3641. pgoff_t index, gfp_t gfp)
  3642. {
  3643. #ifdef CONFIG_SHMEM
  3644. struct inode *inode = mapping->host;
  3645. struct page *page;
  3646. int error;
  3647. BUG_ON(mapping->a_ops != &shmem_aops);
  3648. error = shmem_getpage_gfp(inode, index, &page, SGP_CACHE,
  3649. gfp, NULL, NULL);
  3650. if (error)
  3651. page = ERR_PTR(error);
  3652. else
  3653. unlock_page(page);
  3654. return page;
  3655. #else
  3656. /*
  3657. * The tiny !SHMEM case uses ramfs without swap
  3658. */
  3659. return read_cache_page_gfp(mapping, index, gfp);
  3660. #endif
  3661. }
  3662. EXPORT_SYMBOL_GPL(shmem_read_mapping_page_gfp);