shmem.c 112 KB

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