shmem.c 104 KB

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