shmem.c 91 KB

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