shmem.c 107 KB

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