shmem.c 107 KB

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