shmem.c 90 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569257025712572257325742575257625772578257925802581258225832584258525862587258825892590259125922593259425952596259725982599260026012602260326042605260626072608260926102611261226132614261526162617261826192620262126222623262426252626262726282629263026312632263326342635263626372638263926402641264226432644264526462647264826492650265126522653265426552656265726582659266026612662266326642665266626672668266926702671267226732674267526762677267826792680268126822683268426852686268726882689269026912692269326942695269626972698269927002701270227032704270527062707270827092710271127122713271427152716271727182719272027212722272327242725272627272728272927302731273227332734273527362737273827392740274127422743274427452746274727482749275027512752275327542755275627572758275927602761276227632764276527662767276827692770277127722773277427752776277727782779278027812782278327842785278627872788278927902791279227932794279527962797279827992800280128022803280428052806280728082809281028112812281328142815281628172818281928202821282228232824282528262827282828292830283128322833283428352836283728382839284028412842284328442845284628472848284928502851285228532854285528562857285828592860286128622863286428652866286728682869287028712872287328742875287628772878287928802881288228832884288528862887288828892890289128922893289428952896289728982899290029012902290329042905290629072908290929102911291229132914291529162917291829192920292129222923292429252926292729282929293029312932293329342935293629372938293929402941294229432944294529462947294829492950295129522953295429552956295729582959296029612962296329642965296629672968296929702971297229732974297529762977297829792980298129822983298429852986298729882989299029912992299329942995299629972998299930003001300230033004300530063007300830093010301130123013301430153016301730183019302030213022302330243025302630273028302930303031303230333034303530363037303830393040304130423043304430453046304730483049305030513052305330543055305630573058305930603061306230633064306530663067306830693070307130723073307430753076307730783079308030813082308330843085308630873088308930903091309230933094309530963097309830993100310131023103310431053106310731083109311031113112311331143115311631173118311931203121312231233124312531263127312831293130313131323133313431353136313731383139314031413142314331443145314631473148314931503151315231533154315531563157315831593160316131623163316431653166316731683169317031713172317331743175317631773178317931803181318231833184318531863187318831893190319131923193319431953196319731983199320032013202320332043205320632073208320932103211321232133214321532163217321832193220322132223223322432253226322732283229323032313232323332343235323632373238323932403241324232433244324532463247324832493250325132523253325432553256325732583259326032613262326332643265326632673268326932703271327232733274327532763277327832793280328132823283328432853286328732883289329032913292329332943295329632973298329933003301330233033304330533063307330833093310331133123313331433153316331733183319332033213322332333243325332633273328332933303331333233333334333533363337333833393340334133423343334433453346334733483349335033513352335333543355335633573358335933603361336233633364336533663367336833693370337133723373337433753376337733783379338033813382338333843385338633873388338933903391339233933394339533963397339833993400340134023403340434053406340734083409341034113412341334143415341634173418341934203421342234233424342534263427342834293430343134323433343434353436343734383439344034413442344334443445344634473448344934503451345234533454345534563457345834593460346134623463346434653466346734683469347034713472347334743475347634773478347934803481348234833484348534863487348834893490349134923493349434953496349734983499350035013502350335043505
  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_SIZE/512)
  72. #define VM_ACCT(size) (PAGE_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_WRITE, /* may exceed i_size, may allocate !Uptodate page */
  94. SGP_FALLOC, /* like SGP_WRITE, but make existing page Uptodate */
  95. };
  96. #ifdef CONFIG_TMPFS
  97. static unsigned long shmem_default_max_blocks(void)
  98. {
  99. return totalram_pages / 2;
  100. }
  101. static unsigned long shmem_default_max_inodes(void)
  102. {
  103. return min(totalram_pages - totalhigh_pages, totalram_pages / 2);
  104. }
  105. #endif
  106. static bool shmem_should_replace_page(struct page *page, gfp_t gfp);
  107. static int shmem_replace_page(struct page **pagep, gfp_t gfp,
  108. struct shmem_inode_info *info, pgoff_t index);
  109. static int shmem_getpage_gfp(struct inode *inode, pgoff_t index,
  110. struct page **pagep, enum sgp_type sgp,
  111. gfp_t gfp, struct mm_struct *fault_mm, int *fault_type);
  112. static inline int shmem_getpage(struct inode *inode, pgoff_t index,
  113. struct page **pagep, enum sgp_type sgp)
  114. {
  115. return shmem_getpage_gfp(inode, index, pagep, sgp,
  116. mapping_gfp_mask(inode->i_mapping), NULL, NULL);
  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 large 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_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_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. get_page(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. put_page(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. put_page(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_SIZE - 1) >> PAGE_SHIFT;
  422. pgoff_t end = (lend + 1) >> PAGE_SHIFT;
  423. unsigned int partial_start = lstart & (PAGE_SIZE - 1);
  424. unsigned int partial_end = (lend + 1) & (PAGE_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);
  470. if (page) {
  471. unsigned int top = PAGE_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. put_page(page);
  480. }
  481. }
  482. if (partial_end) {
  483. struct page *page = NULL;
  484. shmem_getpage(inode, end, &page, SGP_READ);
  485. if (page) {
  486. zero_user_segment(page, 0, partial_end);
  487. set_page_dirty(page);
  488. unlock_page(page);
  489. put_page(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. put_page(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. #if defined(CONFIG_NUMA) && defined(CONFIG_TMPFS)
  849. static void shmem_show_mpol(struct seq_file *seq, struct mempolicy *mpol)
  850. {
  851. char buffer[64];
  852. if (!mpol || mpol->mode == MPOL_DEFAULT)
  853. return; /* show nothing */
  854. mpol_to_str(buffer, sizeof(buffer), mpol);
  855. seq_printf(seq, ",mpol=%s", buffer);
  856. }
  857. static struct mempolicy *shmem_get_sbmpol(struct shmem_sb_info *sbinfo)
  858. {
  859. struct mempolicy *mpol = NULL;
  860. if (sbinfo->mpol) {
  861. spin_lock(&sbinfo->stat_lock); /* prevent replace/use races */
  862. mpol = sbinfo->mpol;
  863. mpol_get(mpol);
  864. spin_unlock(&sbinfo->stat_lock);
  865. }
  866. return mpol;
  867. }
  868. #else /* !CONFIG_NUMA || !CONFIG_TMPFS */
  869. static inline void shmem_show_mpol(struct seq_file *seq, struct mempolicy *mpol)
  870. {
  871. }
  872. static inline struct mempolicy *shmem_get_sbmpol(struct shmem_sb_info *sbinfo)
  873. {
  874. return NULL;
  875. }
  876. #endif /* CONFIG_NUMA && CONFIG_TMPFS */
  877. #ifndef CONFIG_NUMA
  878. #define vm_policy vm_private_data
  879. #endif
  880. static struct page *shmem_swapin(swp_entry_t swap, gfp_t gfp,
  881. struct shmem_inode_info *info, pgoff_t index)
  882. {
  883. struct vm_area_struct pvma;
  884. struct page *page;
  885. /* Create a pseudo vma that just contains the policy */
  886. pvma.vm_start = 0;
  887. /* Bias interleave by inode number to distribute better across nodes */
  888. pvma.vm_pgoff = index + info->vfs_inode.i_ino;
  889. pvma.vm_ops = NULL;
  890. pvma.vm_policy = mpol_shared_policy_lookup(&info->policy, index);
  891. page = swapin_readahead(swap, gfp, &pvma, 0);
  892. /* Drop reference taken by mpol_shared_policy_lookup() */
  893. mpol_cond_put(pvma.vm_policy);
  894. return page;
  895. }
  896. static struct page *shmem_alloc_page(gfp_t gfp,
  897. struct shmem_inode_info *info, pgoff_t index)
  898. {
  899. struct vm_area_struct pvma;
  900. struct page *page;
  901. /* Create a pseudo vma that just contains the policy */
  902. pvma.vm_start = 0;
  903. /* Bias interleave by inode number to distribute better across nodes */
  904. pvma.vm_pgoff = index + info->vfs_inode.i_ino;
  905. pvma.vm_ops = NULL;
  906. pvma.vm_policy = mpol_shared_policy_lookup(&info->policy, index);
  907. page = alloc_pages_vma(gfp, 0, &pvma, 0, numa_node_id(), false);
  908. if (page) {
  909. __SetPageLocked(page);
  910. __SetPageSwapBacked(page);
  911. }
  912. /* Drop reference taken by mpol_shared_policy_lookup() */
  913. mpol_cond_put(pvma.vm_policy);
  914. return page;
  915. }
  916. /*
  917. * When a page is moved from swapcache to shmem filecache (either by the
  918. * usual swapin of shmem_getpage_gfp(), or by the less common swapoff of
  919. * shmem_unuse_inode()), it may have been read in earlier from swap, in
  920. * ignorance of the mapping it belongs to. If that mapping has special
  921. * constraints (like the gma500 GEM driver, which requires RAM below 4GB),
  922. * we may need to copy to a suitable page before moving to filecache.
  923. *
  924. * In a future release, this may well be extended to respect cpuset and
  925. * NUMA mempolicy, and applied also to anonymous pages in do_swap_page();
  926. * but for now it is a simple matter of zone.
  927. */
  928. static bool shmem_should_replace_page(struct page *page, gfp_t gfp)
  929. {
  930. return page_zonenum(page) > gfp_zone(gfp);
  931. }
  932. static int shmem_replace_page(struct page **pagep, gfp_t gfp,
  933. struct shmem_inode_info *info, pgoff_t index)
  934. {
  935. struct page *oldpage, *newpage;
  936. struct address_space *swap_mapping;
  937. pgoff_t swap_index;
  938. int error;
  939. oldpage = *pagep;
  940. swap_index = page_private(oldpage);
  941. swap_mapping = page_mapping(oldpage);
  942. /*
  943. * We have arrived here because our zones are constrained, so don't
  944. * limit chance of success by further cpuset and node constraints.
  945. */
  946. gfp &= ~GFP_CONSTRAINT_MASK;
  947. newpage = shmem_alloc_page(gfp, info, index);
  948. if (!newpage)
  949. return -ENOMEM;
  950. get_page(newpage);
  951. copy_highpage(newpage, oldpage);
  952. flush_dcache_page(newpage);
  953. SetPageUptodate(newpage);
  954. set_page_private(newpage, swap_index);
  955. SetPageSwapCache(newpage);
  956. /*
  957. * Our caller will very soon move newpage out of swapcache, but it's
  958. * a nice clean interface for us to replace oldpage by newpage there.
  959. */
  960. spin_lock_irq(&swap_mapping->tree_lock);
  961. error = shmem_radix_tree_replace(swap_mapping, swap_index, oldpage,
  962. newpage);
  963. if (!error) {
  964. __inc_zone_page_state(newpage, NR_FILE_PAGES);
  965. __dec_zone_page_state(oldpage, NR_FILE_PAGES);
  966. }
  967. spin_unlock_irq(&swap_mapping->tree_lock);
  968. if (unlikely(error)) {
  969. /*
  970. * Is this possible? I think not, now that our callers check
  971. * both PageSwapCache and page_private after getting page lock;
  972. * but be defensive. Reverse old to newpage for clear and free.
  973. */
  974. oldpage = newpage;
  975. } else {
  976. mem_cgroup_migrate(oldpage, newpage);
  977. lru_cache_add_anon(newpage);
  978. *pagep = newpage;
  979. }
  980. ClearPageSwapCache(oldpage);
  981. set_page_private(oldpage, 0);
  982. unlock_page(oldpage);
  983. put_page(oldpage);
  984. put_page(oldpage);
  985. return error;
  986. }
  987. /*
  988. * shmem_getpage_gfp - find page in cache, or get from swap, or allocate
  989. *
  990. * If we allocate a new one we do not mark it dirty. That's up to the
  991. * vm. If we swap it in we mark it dirty since we also free the swap
  992. * entry since a page cannot live in both the swap and page cache.
  993. *
  994. * fault_mm and fault_type are only supplied by shmem_fault:
  995. * otherwise they are NULL.
  996. */
  997. static int shmem_getpage_gfp(struct inode *inode, pgoff_t index,
  998. struct page **pagep, enum sgp_type sgp, gfp_t gfp,
  999. struct mm_struct *fault_mm, int *fault_type)
  1000. {
  1001. struct address_space *mapping = inode->i_mapping;
  1002. struct shmem_inode_info *info;
  1003. struct shmem_sb_info *sbinfo;
  1004. struct mm_struct *charge_mm;
  1005. struct mem_cgroup *memcg;
  1006. struct page *page;
  1007. swp_entry_t swap;
  1008. int error;
  1009. int once = 0;
  1010. int alloced = 0;
  1011. if (index > (MAX_LFS_FILESIZE >> PAGE_SHIFT))
  1012. return -EFBIG;
  1013. repeat:
  1014. swap.val = 0;
  1015. page = find_lock_entry(mapping, index);
  1016. if (radix_tree_exceptional_entry(page)) {
  1017. swap = radix_to_swp_entry(page);
  1018. page = NULL;
  1019. }
  1020. if (sgp <= SGP_CACHE &&
  1021. ((loff_t)index << PAGE_SHIFT) >= i_size_read(inode)) {
  1022. error = -EINVAL;
  1023. goto unlock;
  1024. }
  1025. if (page && sgp == SGP_WRITE)
  1026. mark_page_accessed(page);
  1027. /* fallocated page? */
  1028. if (page && !PageUptodate(page)) {
  1029. if (sgp != SGP_READ)
  1030. goto clear;
  1031. unlock_page(page);
  1032. put_page(page);
  1033. page = NULL;
  1034. }
  1035. if (page || (sgp == SGP_READ && !swap.val)) {
  1036. *pagep = page;
  1037. return 0;
  1038. }
  1039. /*
  1040. * Fast cache lookup did not find it:
  1041. * bring it back from swap or allocate.
  1042. */
  1043. info = SHMEM_I(inode);
  1044. sbinfo = SHMEM_SB(inode->i_sb);
  1045. charge_mm = fault_mm ? : current->mm;
  1046. if (swap.val) {
  1047. /* Look it up and read it in.. */
  1048. page = lookup_swap_cache(swap);
  1049. if (!page) {
  1050. /* Or update major stats only when swapin succeeds?? */
  1051. if (fault_type) {
  1052. *fault_type |= VM_FAULT_MAJOR;
  1053. count_vm_event(PGMAJFAULT);
  1054. mem_cgroup_count_vm_event(fault_mm, PGMAJFAULT);
  1055. }
  1056. /* Here we actually start the io */
  1057. page = shmem_swapin(swap, gfp, info, index);
  1058. if (!page) {
  1059. error = -ENOMEM;
  1060. goto failed;
  1061. }
  1062. }
  1063. /* We have to do this with page locked to prevent races */
  1064. lock_page(page);
  1065. if (!PageSwapCache(page) || page_private(page) != swap.val ||
  1066. !shmem_confirm_swap(mapping, index, swap)) {
  1067. error = -EEXIST; /* try again */
  1068. goto unlock;
  1069. }
  1070. if (!PageUptodate(page)) {
  1071. error = -EIO;
  1072. goto failed;
  1073. }
  1074. wait_on_page_writeback(page);
  1075. if (shmem_should_replace_page(page, gfp)) {
  1076. error = shmem_replace_page(&page, gfp, info, index);
  1077. if (error)
  1078. goto failed;
  1079. }
  1080. error = mem_cgroup_try_charge(page, charge_mm, gfp, &memcg,
  1081. false);
  1082. if (!error) {
  1083. error = shmem_add_to_page_cache(page, mapping, index,
  1084. swp_to_radix_entry(swap));
  1085. /*
  1086. * We already confirmed swap under page lock, and make
  1087. * no memory allocation here, so usually no possibility
  1088. * of error; but free_swap_and_cache() only trylocks a
  1089. * page, so it is just possible that the entry has been
  1090. * truncated or holepunched since swap was confirmed.
  1091. * shmem_undo_range() will have done some of the
  1092. * unaccounting, now delete_from_swap_cache() will do
  1093. * the rest.
  1094. * Reset swap.val? No, leave it so "failed" goes back to
  1095. * "repeat": reading a hole and writing should succeed.
  1096. */
  1097. if (error) {
  1098. mem_cgroup_cancel_charge(page, memcg, false);
  1099. delete_from_swap_cache(page);
  1100. }
  1101. }
  1102. if (error)
  1103. goto failed;
  1104. mem_cgroup_commit_charge(page, memcg, true, false);
  1105. spin_lock(&info->lock);
  1106. info->swapped--;
  1107. shmem_recalc_inode(inode);
  1108. spin_unlock(&info->lock);
  1109. if (sgp == SGP_WRITE)
  1110. mark_page_accessed(page);
  1111. delete_from_swap_cache(page);
  1112. set_page_dirty(page);
  1113. swap_free(swap);
  1114. } else {
  1115. if (shmem_acct_block(info->flags)) {
  1116. error = -ENOSPC;
  1117. goto failed;
  1118. }
  1119. if (sbinfo->max_blocks) {
  1120. if (percpu_counter_compare(&sbinfo->used_blocks,
  1121. sbinfo->max_blocks) >= 0) {
  1122. error = -ENOSPC;
  1123. goto unacct;
  1124. }
  1125. percpu_counter_inc(&sbinfo->used_blocks);
  1126. }
  1127. page = shmem_alloc_page(gfp, info, index);
  1128. if (!page) {
  1129. error = -ENOMEM;
  1130. goto decused;
  1131. }
  1132. if (sgp == SGP_WRITE)
  1133. __SetPageReferenced(page);
  1134. error = mem_cgroup_try_charge(page, charge_mm, gfp, &memcg,
  1135. false);
  1136. if (error)
  1137. goto decused;
  1138. error = radix_tree_maybe_preload(gfp & GFP_RECLAIM_MASK);
  1139. if (!error) {
  1140. error = shmem_add_to_page_cache(page, mapping, index,
  1141. NULL);
  1142. radix_tree_preload_end();
  1143. }
  1144. if (error) {
  1145. mem_cgroup_cancel_charge(page, memcg, false);
  1146. goto decused;
  1147. }
  1148. mem_cgroup_commit_charge(page, memcg, false, false);
  1149. lru_cache_add_anon(page);
  1150. spin_lock(&info->lock);
  1151. info->alloced++;
  1152. inode->i_blocks += BLOCKS_PER_PAGE;
  1153. shmem_recalc_inode(inode);
  1154. spin_unlock(&info->lock);
  1155. alloced = true;
  1156. /*
  1157. * Let SGP_FALLOC use the SGP_WRITE optimization on a new page.
  1158. */
  1159. if (sgp == SGP_FALLOC)
  1160. sgp = SGP_WRITE;
  1161. clear:
  1162. /*
  1163. * Let SGP_WRITE caller clear ends if write does not fill page;
  1164. * but SGP_FALLOC on a page fallocated earlier must initialize
  1165. * it now, lest undo on failure cancel our earlier guarantee.
  1166. */
  1167. if (sgp != SGP_WRITE) {
  1168. clear_highpage(page);
  1169. flush_dcache_page(page);
  1170. SetPageUptodate(page);
  1171. }
  1172. }
  1173. /* Perhaps the file has been truncated since we checked */
  1174. if (sgp <= SGP_CACHE &&
  1175. ((loff_t)index << PAGE_SHIFT) >= i_size_read(inode)) {
  1176. if (alloced) {
  1177. ClearPageDirty(page);
  1178. delete_from_page_cache(page);
  1179. spin_lock(&info->lock);
  1180. shmem_recalc_inode(inode);
  1181. spin_unlock(&info->lock);
  1182. }
  1183. error = -EINVAL;
  1184. goto unlock;
  1185. }
  1186. *pagep = page;
  1187. return 0;
  1188. /*
  1189. * Error recovery.
  1190. */
  1191. decused:
  1192. if (sbinfo->max_blocks)
  1193. percpu_counter_add(&sbinfo->used_blocks, -1);
  1194. unacct:
  1195. shmem_unacct_blocks(info->flags, 1);
  1196. failed:
  1197. if (swap.val && !shmem_confirm_swap(mapping, index, swap))
  1198. error = -EEXIST;
  1199. unlock:
  1200. if (page) {
  1201. unlock_page(page);
  1202. put_page(page);
  1203. }
  1204. if (error == -ENOSPC && !once++) {
  1205. info = SHMEM_I(inode);
  1206. spin_lock(&info->lock);
  1207. shmem_recalc_inode(inode);
  1208. spin_unlock(&info->lock);
  1209. goto repeat;
  1210. }
  1211. if (error == -EEXIST) /* from above or from radix_tree_insert */
  1212. goto repeat;
  1213. return error;
  1214. }
  1215. static int shmem_fault(struct vm_area_struct *vma, struct vm_fault *vmf)
  1216. {
  1217. struct inode *inode = file_inode(vma->vm_file);
  1218. gfp_t gfp = mapping_gfp_mask(inode->i_mapping);
  1219. int error;
  1220. int ret = VM_FAULT_LOCKED;
  1221. /*
  1222. * Trinity finds that probing a hole which tmpfs is punching can
  1223. * prevent the hole-punch from ever completing: which in turn
  1224. * locks writers out with its hold on i_mutex. So refrain from
  1225. * faulting pages into the hole while it's being punched. Although
  1226. * shmem_undo_range() does remove the additions, it may be unable to
  1227. * keep up, as each new page needs its own unmap_mapping_range() call,
  1228. * and the i_mmap tree grows ever slower to scan if new vmas are added.
  1229. *
  1230. * It does not matter if we sometimes reach this check just before the
  1231. * hole-punch begins, so that one fault then races with the punch:
  1232. * we just need to make racing faults a rare case.
  1233. *
  1234. * The implementation below would be much simpler if we just used a
  1235. * standard mutex or completion: but we cannot take i_mutex in fault,
  1236. * and bloating every shmem inode for this unlikely case would be sad.
  1237. */
  1238. if (unlikely(inode->i_private)) {
  1239. struct shmem_falloc *shmem_falloc;
  1240. spin_lock(&inode->i_lock);
  1241. shmem_falloc = inode->i_private;
  1242. if (shmem_falloc &&
  1243. shmem_falloc->waitq &&
  1244. vmf->pgoff >= shmem_falloc->start &&
  1245. vmf->pgoff < shmem_falloc->next) {
  1246. wait_queue_head_t *shmem_falloc_waitq;
  1247. DEFINE_WAIT(shmem_fault_wait);
  1248. ret = VM_FAULT_NOPAGE;
  1249. if ((vmf->flags & FAULT_FLAG_ALLOW_RETRY) &&
  1250. !(vmf->flags & FAULT_FLAG_RETRY_NOWAIT)) {
  1251. /* It's polite to up mmap_sem if we can */
  1252. up_read(&vma->vm_mm->mmap_sem);
  1253. ret = VM_FAULT_RETRY;
  1254. }
  1255. shmem_falloc_waitq = shmem_falloc->waitq;
  1256. prepare_to_wait(shmem_falloc_waitq, &shmem_fault_wait,
  1257. TASK_UNINTERRUPTIBLE);
  1258. spin_unlock(&inode->i_lock);
  1259. schedule();
  1260. /*
  1261. * shmem_falloc_waitq points into the shmem_fallocate()
  1262. * stack of the hole-punching task: shmem_falloc_waitq
  1263. * is usually invalid by the time we reach here, but
  1264. * finish_wait() does not dereference it in that case;
  1265. * though i_lock needed lest racing with wake_up_all().
  1266. */
  1267. spin_lock(&inode->i_lock);
  1268. finish_wait(shmem_falloc_waitq, &shmem_fault_wait);
  1269. spin_unlock(&inode->i_lock);
  1270. return ret;
  1271. }
  1272. spin_unlock(&inode->i_lock);
  1273. }
  1274. error = shmem_getpage_gfp(inode, vmf->pgoff, &vmf->page, SGP_CACHE,
  1275. gfp, vma->vm_mm, &ret);
  1276. if (error)
  1277. return ((error == -ENOMEM) ? VM_FAULT_OOM : VM_FAULT_SIGBUS);
  1278. return ret;
  1279. }
  1280. #ifdef CONFIG_NUMA
  1281. static int shmem_set_policy(struct vm_area_struct *vma, struct mempolicy *mpol)
  1282. {
  1283. struct inode *inode = file_inode(vma->vm_file);
  1284. return mpol_set_shared_policy(&SHMEM_I(inode)->policy, vma, mpol);
  1285. }
  1286. static struct mempolicy *shmem_get_policy(struct vm_area_struct *vma,
  1287. unsigned long addr)
  1288. {
  1289. struct inode *inode = file_inode(vma->vm_file);
  1290. pgoff_t index;
  1291. index = ((addr - vma->vm_start) >> PAGE_SHIFT) + vma->vm_pgoff;
  1292. return mpol_shared_policy_lookup(&SHMEM_I(inode)->policy, index);
  1293. }
  1294. #endif
  1295. int shmem_lock(struct file *file, int lock, struct user_struct *user)
  1296. {
  1297. struct inode *inode = file_inode(file);
  1298. struct shmem_inode_info *info = SHMEM_I(inode);
  1299. int retval = -ENOMEM;
  1300. spin_lock(&info->lock);
  1301. if (lock && !(info->flags & VM_LOCKED)) {
  1302. if (!user_shm_lock(inode->i_size, user))
  1303. goto out_nomem;
  1304. info->flags |= VM_LOCKED;
  1305. mapping_set_unevictable(file->f_mapping);
  1306. }
  1307. if (!lock && (info->flags & VM_LOCKED) && user) {
  1308. user_shm_unlock(inode->i_size, user);
  1309. info->flags &= ~VM_LOCKED;
  1310. mapping_clear_unevictable(file->f_mapping);
  1311. }
  1312. retval = 0;
  1313. out_nomem:
  1314. spin_unlock(&info->lock);
  1315. return retval;
  1316. }
  1317. static int shmem_mmap(struct file *file, struct vm_area_struct *vma)
  1318. {
  1319. file_accessed(file);
  1320. vma->vm_ops = &shmem_vm_ops;
  1321. return 0;
  1322. }
  1323. static struct inode *shmem_get_inode(struct super_block *sb, const struct inode *dir,
  1324. umode_t mode, dev_t dev, unsigned long flags)
  1325. {
  1326. struct inode *inode;
  1327. struct shmem_inode_info *info;
  1328. struct shmem_sb_info *sbinfo = SHMEM_SB(sb);
  1329. if (shmem_reserve_inode(sb))
  1330. return NULL;
  1331. inode = new_inode(sb);
  1332. if (inode) {
  1333. inode->i_ino = get_next_ino();
  1334. inode_init_owner(inode, dir, mode);
  1335. inode->i_blocks = 0;
  1336. inode->i_atime = inode->i_mtime = inode->i_ctime = CURRENT_TIME;
  1337. inode->i_generation = get_seconds();
  1338. info = SHMEM_I(inode);
  1339. memset(info, 0, (char *)inode - (char *)info);
  1340. spin_lock_init(&info->lock);
  1341. info->seals = F_SEAL_SEAL;
  1342. info->flags = flags & VM_NORESERVE;
  1343. INIT_LIST_HEAD(&info->swaplist);
  1344. simple_xattrs_init(&info->xattrs);
  1345. cache_no_acl(inode);
  1346. switch (mode & S_IFMT) {
  1347. default:
  1348. inode->i_op = &shmem_special_inode_operations;
  1349. init_special_inode(inode, mode, dev);
  1350. break;
  1351. case S_IFREG:
  1352. inode->i_mapping->a_ops = &shmem_aops;
  1353. inode->i_op = &shmem_inode_operations;
  1354. inode->i_fop = &shmem_file_operations;
  1355. mpol_shared_policy_init(&info->policy,
  1356. shmem_get_sbmpol(sbinfo));
  1357. break;
  1358. case S_IFDIR:
  1359. inc_nlink(inode);
  1360. /* Some things misbehave if size == 0 on a directory */
  1361. inode->i_size = 2 * BOGO_DIRENT_SIZE;
  1362. inode->i_op = &shmem_dir_inode_operations;
  1363. inode->i_fop = &simple_dir_operations;
  1364. break;
  1365. case S_IFLNK:
  1366. /*
  1367. * Must not load anything in the rbtree,
  1368. * mpol_free_shared_policy will not be called.
  1369. */
  1370. mpol_shared_policy_init(&info->policy, NULL);
  1371. break;
  1372. }
  1373. } else
  1374. shmem_free_inode(sb);
  1375. return inode;
  1376. }
  1377. bool shmem_mapping(struct address_space *mapping)
  1378. {
  1379. if (!mapping->host)
  1380. return false;
  1381. return mapping->host->i_sb->s_op == &shmem_ops;
  1382. }
  1383. #ifdef CONFIG_TMPFS
  1384. static const struct inode_operations shmem_symlink_inode_operations;
  1385. static const struct inode_operations shmem_short_symlink_operations;
  1386. #ifdef CONFIG_TMPFS_XATTR
  1387. static int shmem_initxattrs(struct inode *, const struct xattr *, void *);
  1388. #else
  1389. #define shmem_initxattrs NULL
  1390. #endif
  1391. static int
  1392. shmem_write_begin(struct file *file, struct address_space *mapping,
  1393. loff_t pos, unsigned len, unsigned flags,
  1394. struct page **pagep, void **fsdata)
  1395. {
  1396. struct inode *inode = mapping->host;
  1397. struct shmem_inode_info *info = SHMEM_I(inode);
  1398. pgoff_t index = pos >> PAGE_SHIFT;
  1399. /* i_mutex is held by caller */
  1400. if (unlikely(info->seals)) {
  1401. if (info->seals & F_SEAL_WRITE)
  1402. return -EPERM;
  1403. if ((info->seals & F_SEAL_GROW) && pos + len > inode->i_size)
  1404. return -EPERM;
  1405. }
  1406. return shmem_getpage(inode, index, pagep, SGP_WRITE);
  1407. }
  1408. static int
  1409. shmem_write_end(struct file *file, struct address_space *mapping,
  1410. loff_t pos, unsigned len, unsigned copied,
  1411. struct page *page, void *fsdata)
  1412. {
  1413. struct inode *inode = mapping->host;
  1414. if (pos + copied > inode->i_size)
  1415. i_size_write(inode, pos + copied);
  1416. if (!PageUptodate(page)) {
  1417. if (copied < PAGE_SIZE) {
  1418. unsigned from = pos & (PAGE_SIZE - 1);
  1419. zero_user_segments(page, 0, from,
  1420. from + copied, PAGE_SIZE);
  1421. }
  1422. SetPageUptodate(page);
  1423. }
  1424. set_page_dirty(page);
  1425. unlock_page(page);
  1426. put_page(page);
  1427. return copied;
  1428. }
  1429. static ssize_t shmem_file_read_iter(struct kiocb *iocb, struct iov_iter *to)
  1430. {
  1431. struct file *file = iocb->ki_filp;
  1432. struct inode *inode = file_inode(file);
  1433. struct address_space *mapping = inode->i_mapping;
  1434. pgoff_t index;
  1435. unsigned long offset;
  1436. enum sgp_type sgp = SGP_READ;
  1437. int error = 0;
  1438. ssize_t retval = 0;
  1439. loff_t *ppos = &iocb->ki_pos;
  1440. /*
  1441. * Might this read be for a stacking filesystem? Then when reading
  1442. * holes of a sparse file, we actually need to allocate those pages,
  1443. * and even mark them dirty, so it cannot exceed the max_blocks limit.
  1444. */
  1445. if (!iter_is_iovec(to))
  1446. sgp = SGP_CACHE;
  1447. index = *ppos >> PAGE_SHIFT;
  1448. offset = *ppos & ~PAGE_MASK;
  1449. for (;;) {
  1450. struct page *page = NULL;
  1451. pgoff_t end_index;
  1452. unsigned long nr, ret;
  1453. loff_t i_size = i_size_read(inode);
  1454. end_index = i_size >> PAGE_SHIFT;
  1455. if (index > end_index)
  1456. break;
  1457. if (index == end_index) {
  1458. nr = i_size & ~PAGE_MASK;
  1459. if (nr <= offset)
  1460. break;
  1461. }
  1462. error = shmem_getpage(inode, index, &page, sgp);
  1463. if (error) {
  1464. if (error == -EINVAL)
  1465. error = 0;
  1466. break;
  1467. }
  1468. if (page) {
  1469. if (sgp == SGP_CACHE)
  1470. set_page_dirty(page);
  1471. unlock_page(page);
  1472. }
  1473. /*
  1474. * We must evaluate after, since reads (unlike writes)
  1475. * are called without i_mutex protection against truncate
  1476. */
  1477. nr = PAGE_SIZE;
  1478. i_size = i_size_read(inode);
  1479. end_index = i_size >> PAGE_SHIFT;
  1480. if (index == end_index) {
  1481. nr = i_size & ~PAGE_MASK;
  1482. if (nr <= offset) {
  1483. if (page)
  1484. put_page(page);
  1485. break;
  1486. }
  1487. }
  1488. nr -= offset;
  1489. if (page) {
  1490. /*
  1491. * If users can be writing to this page using arbitrary
  1492. * virtual addresses, take care about potential aliasing
  1493. * before reading the page on the kernel side.
  1494. */
  1495. if (mapping_writably_mapped(mapping))
  1496. flush_dcache_page(page);
  1497. /*
  1498. * Mark the page accessed if we read the beginning.
  1499. */
  1500. if (!offset)
  1501. mark_page_accessed(page);
  1502. } else {
  1503. page = ZERO_PAGE(0);
  1504. get_page(page);
  1505. }
  1506. /*
  1507. * Ok, we have the page, and it's up-to-date, so
  1508. * now we can copy it to user space...
  1509. */
  1510. ret = copy_page_to_iter(page, offset, nr, to);
  1511. retval += ret;
  1512. offset += ret;
  1513. index += offset >> PAGE_SHIFT;
  1514. offset &= ~PAGE_MASK;
  1515. put_page(page);
  1516. if (!iov_iter_count(to))
  1517. break;
  1518. if (ret < nr) {
  1519. error = -EFAULT;
  1520. break;
  1521. }
  1522. cond_resched();
  1523. }
  1524. *ppos = ((loff_t) index << PAGE_SHIFT) + offset;
  1525. file_accessed(file);
  1526. return retval ? retval : error;
  1527. }
  1528. static ssize_t shmem_file_splice_read(struct file *in, loff_t *ppos,
  1529. struct pipe_inode_info *pipe, size_t len,
  1530. unsigned int flags)
  1531. {
  1532. struct address_space *mapping = in->f_mapping;
  1533. struct inode *inode = mapping->host;
  1534. unsigned int loff, nr_pages, req_pages;
  1535. struct page *pages[PIPE_DEF_BUFFERS];
  1536. struct partial_page partial[PIPE_DEF_BUFFERS];
  1537. struct page *page;
  1538. pgoff_t index, end_index;
  1539. loff_t isize, left;
  1540. int error, page_nr;
  1541. struct splice_pipe_desc spd = {
  1542. .pages = pages,
  1543. .partial = partial,
  1544. .nr_pages_max = PIPE_DEF_BUFFERS,
  1545. .flags = flags,
  1546. .ops = &page_cache_pipe_buf_ops,
  1547. .spd_release = spd_release_page,
  1548. };
  1549. isize = i_size_read(inode);
  1550. if (unlikely(*ppos >= isize))
  1551. return 0;
  1552. left = isize - *ppos;
  1553. if (unlikely(left < len))
  1554. len = left;
  1555. if (splice_grow_spd(pipe, &spd))
  1556. return -ENOMEM;
  1557. index = *ppos >> PAGE_SHIFT;
  1558. loff = *ppos & ~PAGE_MASK;
  1559. req_pages = (len + loff + PAGE_SIZE - 1) >> PAGE_SHIFT;
  1560. nr_pages = min(req_pages, spd.nr_pages_max);
  1561. spd.nr_pages = find_get_pages_contig(mapping, index,
  1562. nr_pages, spd.pages);
  1563. index += spd.nr_pages;
  1564. error = 0;
  1565. while (spd.nr_pages < nr_pages) {
  1566. error = shmem_getpage(inode, index, &page, SGP_CACHE);
  1567. if (error)
  1568. break;
  1569. unlock_page(page);
  1570. spd.pages[spd.nr_pages++] = page;
  1571. index++;
  1572. }
  1573. index = *ppos >> PAGE_SHIFT;
  1574. nr_pages = spd.nr_pages;
  1575. spd.nr_pages = 0;
  1576. for (page_nr = 0; page_nr < nr_pages; page_nr++) {
  1577. unsigned int this_len;
  1578. if (!len)
  1579. break;
  1580. this_len = min_t(unsigned long, len, PAGE_SIZE - loff);
  1581. page = spd.pages[page_nr];
  1582. if (!PageUptodate(page) || page->mapping != mapping) {
  1583. error = shmem_getpage(inode, index, &page, SGP_CACHE);
  1584. if (error)
  1585. break;
  1586. unlock_page(page);
  1587. put_page(spd.pages[page_nr]);
  1588. spd.pages[page_nr] = page;
  1589. }
  1590. isize = i_size_read(inode);
  1591. end_index = (isize - 1) >> PAGE_SHIFT;
  1592. if (unlikely(!isize || index > end_index))
  1593. break;
  1594. if (end_index == index) {
  1595. unsigned int plen;
  1596. plen = ((isize - 1) & ~PAGE_MASK) + 1;
  1597. if (plen <= loff)
  1598. break;
  1599. this_len = min(this_len, plen - loff);
  1600. len = this_len;
  1601. }
  1602. spd.partial[page_nr].offset = loff;
  1603. spd.partial[page_nr].len = this_len;
  1604. len -= this_len;
  1605. loff = 0;
  1606. spd.nr_pages++;
  1607. index++;
  1608. }
  1609. while (page_nr < nr_pages)
  1610. put_page(spd.pages[page_nr++]);
  1611. if (spd.nr_pages)
  1612. error = splice_to_pipe(pipe, &spd);
  1613. splice_shrink_spd(&spd);
  1614. if (error > 0) {
  1615. *ppos += error;
  1616. file_accessed(in);
  1617. }
  1618. return error;
  1619. }
  1620. /*
  1621. * llseek SEEK_DATA or SEEK_HOLE through the radix_tree.
  1622. */
  1623. static pgoff_t shmem_seek_hole_data(struct address_space *mapping,
  1624. pgoff_t index, pgoff_t end, int whence)
  1625. {
  1626. struct page *page;
  1627. struct pagevec pvec;
  1628. pgoff_t indices[PAGEVEC_SIZE];
  1629. bool done = false;
  1630. int i;
  1631. pagevec_init(&pvec, 0);
  1632. pvec.nr = 1; /* start small: we may be there already */
  1633. while (!done) {
  1634. pvec.nr = find_get_entries(mapping, index,
  1635. pvec.nr, pvec.pages, indices);
  1636. if (!pvec.nr) {
  1637. if (whence == SEEK_DATA)
  1638. index = end;
  1639. break;
  1640. }
  1641. for (i = 0; i < pvec.nr; i++, index++) {
  1642. if (index < indices[i]) {
  1643. if (whence == SEEK_HOLE) {
  1644. done = true;
  1645. break;
  1646. }
  1647. index = indices[i];
  1648. }
  1649. page = pvec.pages[i];
  1650. if (page && !radix_tree_exceptional_entry(page)) {
  1651. if (!PageUptodate(page))
  1652. page = NULL;
  1653. }
  1654. if (index >= end ||
  1655. (page && whence == SEEK_DATA) ||
  1656. (!page && whence == SEEK_HOLE)) {
  1657. done = true;
  1658. break;
  1659. }
  1660. }
  1661. pagevec_remove_exceptionals(&pvec);
  1662. pagevec_release(&pvec);
  1663. pvec.nr = PAGEVEC_SIZE;
  1664. cond_resched();
  1665. }
  1666. return index;
  1667. }
  1668. static loff_t shmem_file_llseek(struct file *file, loff_t offset, int whence)
  1669. {
  1670. struct address_space *mapping = file->f_mapping;
  1671. struct inode *inode = mapping->host;
  1672. pgoff_t start, end;
  1673. loff_t new_offset;
  1674. if (whence != SEEK_DATA && whence != SEEK_HOLE)
  1675. return generic_file_llseek_size(file, offset, whence,
  1676. MAX_LFS_FILESIZE, i_size_read(inode));
  1677. inode_lock(inode);
  1678. /* We're holding i_mutex so we can access i_size directly */
  1679. if (offset < 0)
  1680. offset = -EINVAL;
  1681. else if (offset >= inode->i_size)
  1682. offset = -ENXIO;
  1683. else {
  1684. start = offset >> PAGE_SHIFT;
  1685. end = (inode->i_size + PAGE_SIZE - 1) >> PAGE_SHIFT;
  1686. new_offset = shmem_seek_hole_data(mapping, start, end, whence);
  1687. new_offset <<= PAGE_SHIFT;
  1688. if (new_offset > offset) {
  1689. if (new_offset < inode->i_size)
  1690. offset = new_offset;
  1691. else if (whence == SEEK_DATA)
  1692. offset = -ENXIO;
  1693. else
  1694. offset = inode->i_size;
  1695. }
  1696. }
  1697. if (offset >= 0)
  1698. offset = vfs_setpos(file, offset, MAX_LFS_FILESIZE);
  1699. inode_unlock(inode);
  1700. return offset;
  1701. }
  1702. /*
  1703. * We need a tag: a new tag would expand every radix_tree_node by 8 bytes,
  1704. * so reuse a tag which we firmly believe is never set or cleared on shmem.
  1705. */
  1706. #define SHMEM_TAG_PINNED PAGECACHE_TAG_TOWRITE
  1707. #define LAST_SCAN 4 /* about 150ms max */
  1708. static void shmem_tag_pins(struct address_space *mapping)
  1709. {
  1710. struct radix_tree_iter iter;
  1711. void **slot;
  1712. pgoff_t start;
  1713. struct page *page;
  1714. lru_add_drain();
  1715. start = 0;
  1716. rcu_read_lock();
  1717. radix_tree_for_each_slot(slot, &mapping->page_tree, &iter, start) {
  1718. page = radix_tree_deref_slot(slot);
  1719. if (!page || radix_tree_exception(page)) {
  1720. if (radix_tree_deref_retry(page)) {
  1721. slot = radix_tree_iter_retry(&iter);
  1722. continue;
  1723. }
  1724. } else if (page_count(page) - page_mapcount(page) > 1) {
  1725. spin_lock_irq(&mapping->tree_lock);
  1726. radix_tree_tag_set(&mapping->page_tree, iter.index,
  1727. SHMEM_TAG_PINNED);
  1728. spin_unlock_irq(&mapping->tree_lock);
  1729. }
  1730. if (need_resched()) {
  1731. cond_resched_rcu();
  1732. slot = radix_tree_iter_next(&iter);
  1733. }
  1734. }
  1735. rcu_read_unlock();
  1736. }
  1737. /*
  1738. * Setting SEAL_WRITE requires us to verify there's no pending writer. However,
  1739. * via get_user_pages(), drivers might have some pending I/O without any active
  1740. * user-space mappings (eg., direct-IO, AIO). Therefore, we look at all pages
  1741. * and see whether it has an elevated ref-count. If so, we tag them and wait for
  1742. * them to be dropped.
  1743. * The caller must guarantee that no new user will acquire writable references
  1744. * to those pages to avoid races.
  1745. */
  1746. static int shmem_wait_for_pins(struct address_space *mapping)
  1747. {
  1748. struct radix_tree_iter iter;
  1749. void **slot;
  1750. pgoff_t start;
  1751. struct page *page;
  1752. int error, scan;
  1753. shmem_tag_pins(mapping);
  1754. error = 0;
  1755. for (scan = 0; scan <= LAST_SCAN; scan++) {
  1756. if (!radix_tree_tagged(&mapping->page_tree, SHMEM_TAG_PINNED))
  1757. break;
  1758. if (!scan)
  1759. lru_add_drain_all();
  1760. else if (schedule_timeout_killable((HZ << scan) / 200))
  1761. scan = LAST_SCAN;
  1762. start = 0;
  1763. rcu_read_lock();
  1764. radix_tree_for_each_tagged(slot, &mapping->page_tree, &iter,
  1765. start, SHMEM_TAG_PINNED) {
  1766. page = radix_tree_deref_slot(slot);
  1767. if (radix_tree_exception(page)) {
  1768. if (radix_tree_deref_retry(page)) {
  1769. slot = radix_tree_iter_retry(&iter);
  1770. continue;
  1771. }
  1772. page = NULL;
  1773. }
  1774. if (page &&
  1775. page_count(page) - page_mapcount(page) != 1) {
  1776. if (scan < LAST_SCAN)
  1777. goto continue_resched;
  1778. /*
  1779. * On the last scan, we clean up all those tags
  1780. * we inserted; but make a note that we still
  1781. * found pages pinned.
  1782. */
  1783. error = -EBUSY;
  1784. }
  1785. spin_lock_irq(&mapping->tree_lock);
  1786. radix_tree_tag_clear(&mapping->page_tree,
  1787. iter.index, SHMEM_TAG_PINNED);
  1788. spin_unlock_irq(&mapping->tree_lock);
  1789. continue_resched:
  1790. if (need_resched()) {
  1791. cond_resched_rcu();
  1792. slot = radix_tree_iter_next(&iter);
  1793. }
  1794. }
  1795. rcu_read_unlock();
  1796. }
  1797. return error;
  1798. }
  1799. #define F_ALL_SEALS (F_SEAL_SEAL | \
  1800. F_SEAL_SHRINK | \
  1801. F_SEAL_GROW | \
  1802. F_SEAL_WRITE)
  1803. int shmem_add_seals(struct file *file, unsigned int seals)
  1804. {
  1805. struct inode *inode = file_inode(file);
  1806. struct shmem_inode_info *info = SHMEM_I(inode);
  1807. int error;
  1808. /*
  1809. * SEALING
  1810. * Sealing allows multiple parties to share a shmem-file but restrict
  1811. * access to a specific subset of file operations. Seals can only be
  1812. * added, but never removed. This way, mutually untrusted parties can
  1813. * share common memory regions with a well-defined policy. A malicious
  1814. * peer can thus never perform unwanted operations on a shared object.
  1815. *
  1816. * Seals are only supported on special shmem-files and always affect
  1817. * the whole underlying inode. Once a seal is set, it may prevent some
  1818. * kinds of access to the file. Currently, the following seals are
  1819. * defined:
  1820. * SEAL_SEAL: Prevent further seals from being set on this file
  1821. * SEAL_SHRINK: Prevent the file from shrinking
  1822. * SEAL_GROW: Prevent the file from growing
  1823. * SEAL_WRITE: Prevent write access to the file
  1824. *
  1825. * As we don't require any trust relationship between two parties, we
  1826. * must prevent seals from being removed. Therefore, sealing a file
  1827. * only adds a given set of seals to the file, it never touches
  1828. * existing seals. Furthermore, the "setting seals"-operation can be
  1829. * sealed itself, which basically prevents any further seal from being
  1830. * added.
  1831. *
  1832. * Semantics of sealing are only defined on volatile files. Only
  1833. * anonymous shmem files support sealing. More importantly, seals are
  1834. * never written to disk. Therefore, there's no plan to support it on
  1835. * other file types.
  1836. */
  1837. if (file->f_op != &shmem_file_operations)
  1838. return -EINVAL;
  1839. if (!(file->f_mode & FMODE_WRITE))
  1840. return -EPERM;
  1841. if (seals & ~(unsigned int)F_ALL_SEALS)
  1842. return -EINVAL;
  1843. inode_lock(inode);
  1844. if (info->seals & F_SEAL_SEAL) {
  1845. error = -EPERM;
  1846. goto unlock;
  1847. }
  1848. if ((seals & F_SEAL_WRITE) && !(info->seals & F_SEAL_WRITE)) {
  1849. error = mapping_deny_writable(file->f_mapping);
  1850. if (error)
  1851. goto unlock;
  1852. error = shmem_wait_for_pins(file->f_mapping);
  1853. if (error) {
  1854. mapping_allow_writable(file->f_mapping);
  1855. goto unlock;
  1856. }
  1857. }
  1858. info->seals |= seals;
  1859. error = 0;
  1860. unlock:
  1861. inode_unlock(inode);
  1862. return error;
  1863. }
  1864. EXPORT_SYMBOL_GPL(shmem_add_seals);
  1865. int shmem_get_seals(struct file *file)
  1866. {
  1867. if (file->f_op != &shmem_file_operations)
  1868. return -EINVAL;
  1869. return SHMEM_I(file_inode(file))->seals;
  1870. }
  1871. EXPORT_SYMBOL_GPL(shmem_get_seals);
  1872. long shmem_fcntl(struct file *file, unsigned int cmd, unsigned long arg)
  1873. {
  1874. long error;
  1875. switch (cmd) {
  1876. case F_ADD_SEALS:
  1877. /* disallow upper 32bit */
  1878. if (arg > UINT_MAX)
  1879. return -EINVAL;
  1880. error = shmem_add_seals(file, arg);
  1881. break;
  1882. case F_GET_SEALS:
  1883. error = shmem_get_seals(file);
  1884. break;
  1885. default:
  1886. error = -EINVAL;
  1887. break;
  1888. }
  1889. return error;
  1890. }
  1891. static long shmem_fallocate(struct file *file, int mode, loff_t offset,
  1892. loff_t len)
  1893. {
  1894. struct inode *inode = file_inode(file);
  1895. struct shmem_sb_info *sbinfo = SHMEM_SB(inode->i_sb);
  1896. struct shmem_inode_info *info = SHMEM_I(inode);
  1897. struct shmem_falloc shmem_falloc;
  1898. pgoff_t start, index, end;
  1899. int error;
  1900. if (mode & ~(FALLOC_FL_KEEP_SIZE | FALLOC_FL_PUNCH_HOLE))
  1901. return -EOPNOTSUPP;
  1902. inode_lock(inode);
  1903. if (mode & FALLOC_FL_PUNCH_HOLE) {
  1904. struct address_space *mapping = file->f_mapping;
  1905. loff_t unmap_start = round_up(offset, PAGE_SIZE);
  1906. loff_t unmap_end = round_down(offset + len, PAGE_SIZE) - 1;
  1907. DECLARE_WAIT_QUEUE_HEAD_ONSTACK(shmem_falloc_waitq);
  1908. /* protected by i_mutex */
  1909. if (info->seals & F_SEAL_WRITE) {
  1910. error = -EPERM;
  1911. goto out;
  1912. }
  1913. shmem_falloc.waitq = &shmem_falloc_waitq;
  1914. shmem_falloc.start = unmap_start >> PAGE_SHIFT;
  1915. shmem_falloc.next = (unmap_end + 1) >> PAGE_SHIFT;
  1916. spin_lock(&inode->i_lock);
  1917. inode->i_private = &shmem_falloc;
  1918. spin_unlock(&inode->i_lock);
  1919. if ((u64)unmap_end > (u64)unmap_start)
  1920. unmap_mapping_range(mapping, unmap_start,
  1921. 1 + unmap_end - unmap_start, 0);
  1922. shmem_truncate_range(inode, offset, offset + len - 1);
  1923. /* No need to unmap again: hole-punching leaves COWed pages */
  1924. spin_lock(&inode->i_lock);
  1925. inode->i_private = NULL;
  1926. wake_up_all(&shmem_falloc_waitq);
  1927. spin_unlock(&inode->i_lock);
  1928. error = 0;
  1929. goto out;
  1930. }
  1931. /* We need to check rlimit even when FALLOC_FL_KEEP_SIZE */
  1932. error = inode_newsize_ok(inode, offset + len);
  1933. if (error)
  1934. goto out;
  1935. if ((info->seals & F_SEAL_GROW) && offset + len > inode->i_size) {
  1936. error = -EPERM;
  1937. goto out;
  1938. }
  1939. start = offset >> PAGE_SHIFT;
  1940. end = (offset + len + PAGE_SIZE - 1) >> PAGE_SHIFT;
  1941. /* Try to avoid a swapstorm if len is impossible to satisfy */
  1942. if (sbinfo->max_blocks && end - start > sbinfo->max_blocks) {
  1943. error = -ENOSPC;
  1944. goto out;
  1945. }
  1946. shmem_falloc.waitq = NULL;
  1947. shmem_falloc.start = start;
  1948. shmem_falloc.next = start;
  1949. shmem_falloc.nr_falloced = 0;
  1950. shmem_falloc.nr_unswapped = 0;
  1951. spin_lock(&inode->i_lock);
  1952. inode->i_private = &shmem_falloc;
  1953. spin_unlock(&inode->i_lock);
  1954. for (index = start; index < end; index++) {
  1955. struct page *page;
  1956. /*
  1957. * Good, the fallocate(2) manpage permits EINTR: we may have
  1958. * been interrupted because we are using up too much memory.
  1959. */
  1960. if (signal_pending(current))
  1961. error = -EINTR;
  1962. else if (shmem_falloc.nr_unswapped > shmem_falloc.nr_falloced)
  1963. error = -ENOMEM;
  1964. else
  1965. error = shmem_getpage(inode, index, &page, SGP_FALLOC);
  1966. if (error) {
  1967. /* Remove the !PageUptodate pages we added */
  1968. if (index > start) {
  1969. shmem_undo_range(inode,
  1970. (loff_t)start << PAGE_SHIFT,
  1971. ((loff_t)index << PAGE_SHIFT) - 1, true);
  1972. }
  1973. goto undone;
  1974. }
  1975. /*
  1976. * Inform shmem_writepage() how far we have reached.
  1977. * No need for lock or barrier: we have the page lock.
  1978. */
  1979. shmem_falloc.next++;
  1980. if (!PageUptodate(page))
  1981. shmem_falloc.nr_falloced++;
  1982. /*
  1983. * If !PageUptodate, leave it that way so that freeable pages
  1984. * can be recognized if we need to rollback on error later.
  1985. * But set_page_dirty so that memory pressure will swap rather
  1986. * than free the pages we are allocating (and SGP_CACHE pages
  1987. * might still be clean: we now need to mark those dirty too).
  1988. */
  1989. set_page_dirty(page);
  1990. unlock_page(page);
  1991. put_page(page);
  1992. cond_resched();
  1993. }
  1994. if (!(mode & FALLOC_FL_KEEP_SIZE) && offset + len > inode->i_size)
  1995. i_size_write(inode, offset + len);
  1996. inode->i_ctime = CURRENT_TIME;
  1997. undone:
  1998. spin_lock(&inode->i_lock);
  1999. inode->i_private = NULL;
  2000. spin_unlock(&inode->i_lock);
  2001. out:
  2002. inode_unlock(inode);
  2003. return error;
  2004. }
  2005. static int shmem_statfs(struct dentry *dentry, struct kstatfs *buf)
  2006. {
  2007. struct shmem_sb_info *sbinfo = SHMEM_SB(dentry->d_sb);
  2008. buf->f_type = TMPFS_MAGIC;
  2009. buf->f_bsize = PAGE_SIZE;
  2010. buf->f_namelen = NAME_MAX;
  2011. if (sbinfo->max_blocks) {
  2012. buf->f_blocks = sbinfo->max_blocks;
  2013. buf->f_bavail =
  2014. buf->f_bfree = sbinfo->max_blocks -
  2015. percpu_counter_sum(&sbinfo->used_blocks);
  2016. }
  2017. if (sbinfo->max_inodes) {
  2018. buf->f_files = sbinfo->max_inodes;
  2019. buf->f_ffree = sbinfo->free_inodes;
  2020. }
  2021. /* else leave those fields 0 like simple_statfs */
  2022. return 0;
  2023. }
  2024. /*
  2025. * File creation. Allocate an inode, and we're done..
  2026. */
  2027. static int
  2028. shmem_mknod(struct inode *dir, struct dentry *dentry, umode_t mode, dev_t dev)
  2029. {
  2030. struct inode *inode;
  2031. int error = -ENOSPC;
  2032. inode = shmem_get_inode(dir->i_sb, dir, mode, dev, VM_NORESERVE);
  2033. if (inode) {
  2034. error = simple_acl_create(dir, inode);
  2035. if (error)
  2036. goto out_iput;
  2037. error = security_inode_init_security(inode, dir,
  2038. &dentry->d_name,
  2039. shmem_initxattrs, NULL);
  2040. if (error && error != -EOPNOTSUPP)
  2041. goto out_iput;
  2042. error = 0;
  2043. dir->i_size += BOGO_DIRENT_SIZE;
  2044. dir->i_ctime = dir->i_mtime = CURRENT_TIME;
  2045. d_instantiate(dentry, inode);
  2046. dget(dentry); /* Extra count - pin the dentry in core */
  2047. }
  2048. return error;
  2049. out_iput:
  2050. iput(inode);
  2051. return error;
  2052. }
  2053. static int
  2054. shmem_tmpfile(struct inode *dir, struct dentry *dentry, umode_t mode)
  2055. {
  2056. struct inode *inode;
  2057. int error = -ENOSPC;
  2058. inode = shmem_get_inode(dir->i_sb, dir, mode, 0, VM_NORESERVE);
  2059. if (inode) {
  2060. error = security_inode_init_security(inode, dir,
  2061. NULL,
  2062. shmem_initxattrs, NULL);
  2063. if (error && error != -EOPNOTSUPP)
  2064. goto out_iput;
  2065. error = simple_acl_create(dir, inode);
  2066. if (error)
  2067. goto out_iput;
  2068. d_tmpfile(dentry, inode);
  2069. }
  2070. return error;
  2071. out_iput:
  2072. iput(inode);
  2073. return error;
  2074. }
  2075. static int shmem_mkdir(struct inode *dir, struct dentry *dentry, umode_t mode)
  2076. {
  2077. int error;
  2078. if ((error = shmem_mknod(dir, dentry, mode | S_IFDIR, 0)))
  2079. return error;
  2080. inc_nlink(dir);
  2081. return 0;
  2082. }
  2083. static int shmem_create(struct inode *dir, struct dentry *dentry, umode_t mode,
  2084. bool excl)
  2085. {
  2086. return shmem_mknod(dir, dentry, mode | S_IFREG, 0);
  2087. }
  2088. /*
  2089. * Link a file..
  2090. */
  2091. static int shmem_link(struct dentry *old_dentry, struct inode *dir, struct dentry *dentry)
  2092. {
  2093. struct inode *inode = d_inode(old_dentry);
  2094. int ret;
  2095. /*
  2096. * No ordinary (disk based) filesystem counts links as inodes;
  2097. * but each new link needs a new dentry, pinning lowmem, and
  2098. * tmpfs dentries cannot be pruned until they are unlinked.
  2099. */
  2100. ret = shmem_reserve_inode(inode->i_sb);
  2101. if (ret)
  2102. goto out;
  2103. dir->i_size += BOGO_DIRENT_SIZE;
  2104. inode->i_ctime = dir->i_ctime = dir->i_mtime = CURRENT_TIME;
  2105. inc_nlink(inode);
  2106. ihold(inode); /* New dentry reference */
  2107. dget(dentry); /* Extra pinning count for the created dentry */
  2108. d_instantiate(dentry, inode);
  2109. out:
  2110. return ret;
  2111. }
  2112. static int shmem_unlink(struct inode *dir, struct dentry *dentry)
  2113. {
  2114. struct inode *inode = d_inode(dentry);
  2115. if (inode->i_nlink > 1 && !S_ISDIR(inode->i_mode))
  2116. shmem_free_inode(inode->i_sb);
  2117. dir->i_size -= BOGO_DIRENT_SIZE;
  2118. inode->i_ctime = dir->i_ctime = dir->i_mtime = CURRENT_TIME;
  2119. drop_nlink(inode);
  2120. dput(dentry); /* Undo the count from "create" - this does all the work */
  2121. return 0;
  2122. }
  2123. static int shmem_rmdir(struct inode *dir, struct dentry *dentry)
  2124. {
  2125. if (!simple_empty(dentry))
  2126. return -ENOTEMPTY;
  2127. drop_nlink(d_inode(dentry));
  2128. drop_nlink(dir);
  2129. return shmem_unlink(dir, dentry);
  2130. }
  2131. static int shmem_exchange(struct inode *old_dir, struct dentry *old_dentry, struct inode *new_dir, struct dentry *new_dentry)
  2132. {
  2133. bool old_is_dir = d_is_dir(old_dentry);
  2134. bool new_is_dir = d_is_dir(new_dentry);
  2135. if (old_dir != new_dir && old_is_dir != new_is_dir) {
  2136. if (old_is_dir) {
  2137. drop_nlink(old_dir);
  2138. inc_nlink(new_dir);
  2139. } else {
  2140. drop_nlink(new_dir);
  2141. inc_nlink(old_dir);
  2142. }
  2143. }
  2144. old_dir->i_ctime = old_dir->i_mtime =
  2145. new_dir->i_ctime = new_dir->i_mtime =
  2146. d_inode(old_dentry)->i_ctime =
  2147. d_inode(new_dentry)->i_ctime = CURRENT_TIME;
  2148. return 0;
  2149. }
  2150. static int shmem_whiteout(struct inode *old_dir, struct dentry *old_dentry)
  2151. {
  2152. struct dentry *whiteout;
  2153. int error;
  2154. whiteout = d_alloc(old_dentry->d_parent, &old_dentry->d_name);
  2155. if (!whiteout)
  2156. return -ENOMEM;
  2157. error = shmem_mknod(old_dir, whiteout,
  2158. S_IFCHR | WHITEOUT_MODE, WHITEOUT_DEV);
  2159. dput(whiteout);
  2160. if (error)
  2161. return error;
  2162. /*
  2163. * Cheat and hash the whiteout while the old dentry is still in
  2164. * place, instead of playing games with FS_RENAME_DOES_D_MOVE.
  2165. *
  2166. * d_lookup() will consistently find one of them at this point,
  2167. * not sure which one, but that isn't even important.
  2168. */
  2169. d_rehash(whiteout);
  2170. return 0;
  2171. }
  2172. /*
  2173. * The VFS layer already does all the dentry stuff for rename,
  2174. * we just have to decrement the usage count for the target if
  2175. * it exists so that the VFS layer correctly free's it when it
  2176. * gets overwritten.
  2177. */
  2178. static int shmem_rename2(struct inode *old_dir, struct dentry *old_dentry, struct inode *new_dir, struct dentry *new_dentry, unsigned int flags)
  2179. {
  2180. struct inode *inode = d_inode(old_dentry);
  2181. int they_are_dirs = S_ISDIR(inode->i_mode);
  2182. if (flags & ~(RENAME_NOREPLACE | RENAME_EXCHANGE | RENAME_WHITEOUT))
  2183. return -EINVAL;
  2184. if (flags & RENAME_EXCHANGE)
  2185. return shmem_exchange(old_dir, old_dentry, new_dir, new_dentry);
  2186. if (!simple_empty(new_dentry))
  2187. return -ENOTEMPTY;
  2188. if (flags & RENAME_WHITEOUT) {
  2189. int error;
  2190. error = shmem_whiteout(old_dir, old_dentry);
  2191. if (error)
  2192. return error;
  2193. }
  2194. if (d_really_is_positive(new_dentry)) {
  2195. (void) shmem_unlink(new_dir, new_dentry);
  2196. if (they_are_dirs) {
  2197. drop_nlink(d_inode(new_dentry));
  2198. drop_nlink(old_dir);
  2199. }
  2200. } else if (they_are_dirs) {
  2201. drop_nlink(old_dir);
  2202. inc_nlink(new_dir);
  2203. }
  2204. old_dir->i_size -= BOGO_DIRENT_SIZE;
  2205. new_dir->i_size += BOGO_DIRENT_SIZE;
  2206. old_dir->i_ctime = old_dir->i_mtime =
  2207. new_dir->i_ctime = new_dir->i_mtime =
  2208. inode->i_ctime = CURRENT_TIME;
  2209. return 0;
  2210. }
  2211. static int shmem_symlink(struct inode *dir, struct dentry *dentry, const char *symname)
  2212. {
  2213. int error;
  2214. int len;
  2215. struct inode *inode;
  2216. struct page *page;
  2217. struct shmem_inode_info *info;
  2218. len = strlen(symname) + 1;
  2219. if (len > PAGE_SIZE)
  2220. return -ENAMETOOLONG;
  2221. inode = shmem_get_inode(dir->i_sb, dir, S_IFLNK|S_IRWXUGO, 0, VM_NORESERVE);
  2222. if (!inode)
  2223. return -ENOSPC;
  2224. error = security_inode_init_security(inode, dir, &dentry->d_name,
  2225. shmem_initxattrs, NULL);
  2226. if (error) {
  2227. if (error != -EOPNOTSUPP) {
  2228. iput(inode);
  2229. return error;
  2230. }
  2231. error = 0;
  2232. }
  2233. info = SHMEM_I(inode);
  2234. inode->i_size = len-1;
  2235. if (len <= SHORT_SYMLINK_LEN) {
  2236. inode->i_link = kmemdup(symname, len, GFP_KERNEL);
  2237. if (!inode->i_link) {
  2238. iput(inode);
  2239. return -ENOMEM;
  2240. }
  2241. inode->i_op = &shmem_short_symlink_operations;
  2242. } else {
  2243. inode_nohighmem(inode);
  2244. error = shmem_getpage(inode, 0, &page, SGP_WRITE);
  2245. if (error) {
  2246. iput(inode);
  2247. return error;
  2248. }
  2249. inode->i_mapping->a_ops = &shmem_aops;
  2250. inode->i_op = &shmem_symlink_inode_operations;
  2251. memcpy(page_address(page), symname, len);
  2252. SetPageUptodate(page);
  2253. set_page_dirty(page);
  2254. unlock_page(page);
  2255. put_page(page);
  2256. }
  2257. dir->i_size += BOGO_DIRENT_SIZE;
  2258. dir->i_ctime = dir->i_mtime = CURRENT_TIME;
  2259. d_instantiate(dentry, inode);
  2260. dget(dentry);
  2261. return 0;
  2262. }
  2263. static void shmem_put_link(void *arg)
  2264. {
  2265. mark_page_accessed(arg);
  2266. put_page(arg);
  2267. }
  2268. static const char *shmem_get_link(struct dentry *dentry,
  2269. struct inode *inode,
  2270. struct delayed_call *done)
  2271. {
  2272. struct page *page = NULL;
  2273. int error;
  2274. if (!dentry) {
  2275. page = find_get_page(inode->i_mapping, 0);
  2276. if (!page)
  2277. return ERR_PTR(-ECHILD);
  2278. if (!PageUptodate(page)) {
  2279. put_page(page);
  2280. return ERR_PTR(-ECHILD);
  2281. }
  2282. } else {
  2283. error = shmem_getpage(inode, 0, &page, SGP_READ);
  2284. if (error)
  2285. return ERR_PTR(error);
  2286. unlock_page(page);
  2287. }
  2288. set_delayed_call(done, shmem_put_link, page);
  2289. return page_address(page);
  2290. }
  2291. #ifdef CONFIG_TMPFS_XATTR
  2292. /*
  2293. * Superblocks without xattr inode operations may get some security.* xattr
  2294. * support from the LSM "for free". As soon as we have any other xattrs
  2295. * like ACLs, we also need to implement the security.* handlers at
  2296. * filesystem level, though.
  2297. */
  2298. /*
  2299. * Callback for security_inode_init_security() for acquiring xattrs.
  2300. */
  2301. static int shmem_initxattrs(struct inode *inode,
  2302. const struct xattr *xattr_array,
  2303. void *fs_info)
  2304. {
  2305. struct shmem_inode_info *info = SHMEM_I(inode);
  2306. const struct xattr *xattr;
  2307. struct simple_xattr *new_xattr;
  2308. size_t len;
  2309. for (xattr = xattr_array; xattr->name != NULL; xattr++) {
  2310. new_xattr = simple_xattr_alloc(xattr->value, xattr->value_len);
  2311. if (!new_xattr)
  2312. return -ENOMEM;
  2313. len = strlen(xattr->name) + 1;
  2314. new_xattr->name = kmalloc(XATTR_SECURITY_PREFIX_LEN + len,
  2315. GFP_KERNEL);
  2316. if (!new_xattr->name) {
  2317. kfree(new_xattr);
  2318. return -ENOMEM;
  2319. }
  2320. memcpy(new_xattr->name, XATTR_SECURITY_PREFIX,
  2321. XATTR_SECURITY_PREFIX_LEN);
  2322. memcpy(new_xattr->name + XATTR_SECURITY_PREFIX_LEN,
  2323. xattr->name, len);
  2324. simple_xattr_list_add(&info->xattrs, new_xattr);
  2325. }
  2326. return 0;
  2327. }
  2328. static int shmem_xattr_handler_get(const struct xattr_handler *handler,
  2329. struct dentry *unused, struct inode *inode,
  2330. const char *name, void *buffer, size_t size)
  2331. {
  2332. struct shmem_inode_info *info = SHMEM_I(inode);
  2333. name = xattr_full_name(handler, name);
  2334. return simple_xattr_get(&info->xattrs, name, buffer, size);
  2335. }
  2336. static int shmem_xattr_handler_set(const struct xattr_handler *handler,
  2337. struct dentry *unused, struct inode *inode,
  2338. const char *name, const void *value,
  2339. size_t size, int flags)
  2340. {
  2341. struct shmem_inode_info *info = SHMEM_I(inode);
  2342. name = xattr_full_name(handler, name);
  2343. return simple_xattr_set(&info->xattrs, name, value, size, flags);
  2344. }
  2345. static const struct xattr_handler shmem_security_xattr_handler = {
  2346. .prefix = XATTR_SECURITY_PREFIX,
  2347. .get = shmem_xattr_handler_get,
  2348. .set = shmem_xattr_handler_set,
  2349. };
  2350. static const struct xattr_handler shmem_trusted_xattr_handler = {
  2351. .prefix = XATTR_TRUSTED_PREFIX,
  2352. .get = shmem_xattr_handler_get,
  2353. .set = shmem_xattr_handler_set,
  2354. };
  2355. static const struct xattr_handler *shmem_xattr_handlers[] = {
  2356. #ifdef CONFIG_TMPFS_POSIX_ACL
  2357. &posix_acl_access_xattr_handler,
  2358. &posix_acl_default_xattr_handler,
  2359. #endif
  2360. &shmem_security_xattr_handler,
  2361. &shmem_trusted_xattr_handler,
  2362. NULL
  2363. };
  2364. static ssize_t shmem_listxattr(struct dentry *dentry, char *buffer, size_t size)
  2365. {
  2366. struct shmem_inode_info *info = SHMEM_I(d_inode(dentry));
  2367. return simple_xattr_list(d_inode(dentry), &info->xattrs, buffer, size);
  2368. }
  2369. #endif /* CONFIG_TMPFS_XATTR */
  2370. static const struct inode_operations shmem_short_symlink_operations = {
  2371. .readlink = generic_readlink,
  2372. .get_link = simple_get_link,
  2373. #ifdef CONFIG_TMPFS_XATTR
  2374. .setxattr = generic_setxattr,
  2375. .getxattr = generic_getxattr,
  2376. .listxattr = shmem_listxattr,
  2377. .removexattr = generic_removexattr,
  2378. #endif
  2379. };
  2380. static const struct inode_operations shmem_symlink_inode_operations = {
  2381. .readlink = generic_readlink,
  2382. .get_link = shmem_get_link,
  2383. #ifdef CONFIG_TMPFS_XATTR
  2384. .setxattr = generic_setxattr,
  2385. .getxattr = generic_getxattr,
  2386. .listxattr = shmem_listxattr,
  2387. .removexattr = generic_removexattr,
  2388. #endif
  2389. };
  2390. static struct dentry *shmem_get_parent(struct dentry *child)
  2391. {
  2392. return ERR_PTR(-ESTALE);
  2393. }
  2394. static int shmem_match(struct inode *ino, void *vfh)
  2395. {
  2396. __u32 *fh = vfh;
  2397. __u64 inum = fh[2];
  2398. inum = (inum << 32) | fh[1];
  2399. return ino->i_ino == inum && fh[0] == ino->i_generation;
  2400. }
  2401. static struct dentry *shmem_fh_to_dentry(struct super_block *sb,
  2402. struct fid *fid, int fh_len, int fh_type)
  2403. {
  2404. struct inode *inode;
  2405. struct dentry *dentry = NULL;
  2406. u64 inum;
  2407. if (fh_len < 3)
  2408. return NULL;
  2409. inum = fid->raw[2];
  2410. inum = (inum << 32) | fid->raw[1];
  2411. inode = ilookup5(sb, (unsigned long)(inum + fid->raw[0]),
  2412. shmem_match, fid->raw);
  2413. if (inode) {
  2414. dentry = d_find_alias(inode);
  2415. iput(inode);
  2416. }
  2417. return dentry;
  2418. }
  2419. static int shmem_encode_fh(struct inode *inode, __u32 *fh, int *len,
  2420. struct inode *parent)
  2421. {
  2422. if (*len < 3) {
  2423. *len = 3;
  2424. return FILEID_INVALID;
  2425. }
  2426. if (inode_unhashed(inode)) {
  2427. /* Unfortunately insert_inode_hash is not idempotent,
  2428. * so as we hash inodes here rather than at creation
  2429. * time, we need a lock to ensure we only try
  2430. * to do it once
  2431. */
  2432. static DEFINE_SPINLOCK(lock);
  2433. spin_lock(&lock);
  2434. if (inode_unhashed(inode))
  2435. __insert_inode_hash(inode,
  2436. inode->i_ino + inode->i_generation);
  2437. spin_unlock(&lock);
  2438. }
  2439. fh[0] = inode->i_generation;
  2440. fh[1] = inode->i_ino;
  2441. fh[2] = ((__u64)inode->i_ino) >> 32;
  2442. *len = 3;
  2443. return 1;
  2444. }
  2445. static const struct export_operations shmem_export_ops = {
  2446. .get_parent = shmem_get_parent,
  2447. .encode_fh = shmem_encode_fh,
  2448. .fh_to_dentry = shmem_fh_to_dentry,
  2449. };
  2450. static int shmem_parse_options(char *options, struct shmem_sb_info *sbinfo,
  2451. bool remount)
  2452. {
  2453. char *this_char, *value, *rest;
  2454. struct mempolicy *mpol = NULL;
  2455. uid_t uid;
  2456. gid_t gid;
  2457. while (options != NULL) {
  2458. this_char = options;
  2459. for (;;) {
  2460. /*
  2461. * NUL-terminate this option: unfortunately,
  2462. * mount options form a comma-separated list,
  2463. * but mpol's nodelist may also contain commas.
  2464. */
  2465. options = strchr(options, ',');
  2466. if (options == NULL)
  2467. break;
  2468. options++;
  2469. if (!isdigit(*options)) {
  2470. options[-1] = '\0';
  2471. break;
  2472. }
  2473. }
  2474. if (!*this_char)
  2475. continue;
  2476. if ((value = strchr(this_char,'=')) != NULL) {
  2477. *value++ = 0;
  2478. } else {
  2479. pr_err("tmpfs: No value for mount option '%s'\n",
  2480. this_char);
  2481. goto error;
  2482. }
  2483. if (!strcmp(this_char,"size")) {
  2484. unsigned long long size;
  2485. size = memparse(value,&rest);
  2486. if (*rest == '%') {
  2487. size <<= PAGE_SHIFT;
  2488. size *= totalram_pages;
  2489. do_div(size, 100);
  2490. rest++;
  2491. }
  2492. if (*rest)
  2493. goto bad_val;
  2494. sbinfo->max_blocks =
  2495. DIV_ROUND_UP(size, PAGE_SIZE);
  2496. } else if (!strcmp(this_char,"nr_blocks")) {
  2497. sbinfo->max_blocks = memparse(value, &rest);
  2498. if (*rest)
  2499. goto bad_val;
  2500. } else if (!strcmp(this_char,"nr_inodes")) {
  2501. sbinfo->max_inodes = memparse(value, &rest);
  2502. if (*rest)
  2503. goto bad_val;
  2504. } else if (!strcmp(this_char,"mode")) {
  2505. if (remount)
  2506. continue;
  2507. sbinfo->mode = simple_strtoul(value, &rest, 8) & 07777;
  2508. if (*rest)
  2509. goto bad_val;
  2510. } else if (!strcmp(this_char,"uid")) {
  2511. if (remount)
  2512. continue;
  2513. uid = simple_strtoul(value, &rest, 0);
  2514. if (*rest)
  2515. goto bad_val;
  2516. sbinfo->uid = make_kuid(current_user_ns(), uid);
  2517. if (!uid_valid(sbinfo->uid))
  2518. goto bad_val;
  2519. } else if (!strcmp(this_char,"gid")) {
  2520. if (remount)
  2521. continue;
  2522. gid = simple_strtoul(value, &rest, 0);
  2523. if (*rest)
  2524. goto bad_val;
  2525. sbinfo->gid = make_kgid(current_user_ns(), gid);
  2526. if (!gid_valid(sbinfo->gid))
  2527. goto bad_val;
  2528. } else if (!strcmp(this_char,"mpol")) {
  2529. mpol_put(mpol);
  2530. mpol = NULL;
  2531. if (mpol_parse_str(value, &mpol))
  2532. goto bad_val;
  2533. } else {
  2534. pr_err("tmpfs: Bad mount option %s\n", this_char);
  2535. goto error;
  2536. }
  2537. }
  2538. sbinfo->mpol = mpol;
  2539. return 0;
  2540. bad_val:
  2541. pr_err("tmpfs: Bad value '%s' for mount option '%s'\n",
  2542. value, this_char);
  2543. error:
  2544. mpol_put(mpol);
  2545. return 1;
  2546. }
  2547. static int shmem_remount_fs(struct super_block *sb, int *flags, char *data)
  2548. {
  2549. struct shmem_sb_info *sbinfo = SHMEM_SB(sb);
  2550. struct shmem_sb_info config = *sbinfo;
  2551. unsigned long inodes;
  2552. int error = -EINVAL;
  2553. config.mpol = NULL;
  2554. if (shmem_parse_options(data, &config, true))
  2555. return error;
  2556. spin_lock(&sbinfo->stat_lock);
  2557. inodes = sbinfo->max_inodes - sbinfo->free_inodes;
  2558. if (percpu_counter_compare(&sbinfo->used_blocks, config.max_blocks) > 0)
  2559. goto out;
  2560. if (config.max_inodes < inodes)
  2561. goto out;
  2562. /*
  2563. * Those tests disallow limited->unlimited while any are in use;
  2564. * but we must separately disallow unlimited->limited, because
  2565. * in that case we have no record of how much is already in use.
  2566. */
  2567. if (config.max_blocks && !sbinfo->max_blocks)
  2568. goto out;
  2569. if (config.max_inodes && !sbinfo->max_inodes)
  2570. goto out;
  2571. error = 0;
  2572. sbinfo->max_blocks = config.max_blocks;
  2573. sbinfo->max_inodes = config.max_inodes;
  2574. sbinfo->free_inodes = config.max_inodes - inodes;
  2575. /*
  2576. * Preserve previous mempolicy unless mpol remount option was specified.
  2577. */
  2578. if (config.mpol) {
  2579. mpol_put(sbinfo->mpol);
  2580. sbinfo->mpol = config.mpol; /* transfers initial ref */
  2581. }
  2582. out:
  2583. spin_unlock(&sbinfo->stat_lock);
  2584. return error;
  2585. }
  2586. static int shmem_show_options(struct seq_file *seq, struct dentry *root)
  2587. {
  2588. struct shmem_sb_info *sbinfo = SHMEM_SB(root->d_sb);
  2589. if (sbinfo->max_blocks != shmem_default_max_blocks())
  2590. seq_printf(seq, ",size=%luk",
  2591. sbinfo->max_blocks << (PAGE_SHIFT - 10));
  2592. if (sbinfo->max_inodes != shmem_default_max_inodes())
  2593. seq_printf(seq, ",nr_inodes=%lu", sbinfo->max_inodes);
  2594. if (sbinfo->mode != (S_IRWXUGO | S_ISVTX))
  2595. seq_printf(seq, ",mode=%03ho", sbinfo->mode);
  2596. if (!uid_eq(sbinfo->uid, GLOBAL_ROOT_UID))
  2597. seq_printf(seq, ",uid=%u",
  2598. from_kuid_munged(&init_user_ns, sbinfo->uid));
  2599. if (!gid_eq(sbinfo->gid, GLOBAL_ROOT_GID))
  2600. seq_printf(seq, ",gid=%u",
  2601. from_kgid_munged(&init_user_ns, sbinfo->gid));
  2602. shmem_show_mpol(seq, sbinfo->mpol);
  2603. return 0;
  2604. }
  2605. #define MFD_NAME_PREFIX "memfd:"
  2606. #define MFD_NAME_PREFIX_LEN (sizeof(MFD_NAME_PREFIX) - 1)
  2607. #define MFD_NAME_MAX_LEN (NAME_MAX - MFD_NAME_PREFIX_LEN)
  2608. #define MFD_ALL_FLAGS (MFD_CLOEXEC | MFD_ALLOW_SEALING)
  2609. SYSCALL_DEFINE2(memfd_create,
  2610. const char __user *, uname,
  2611. unsigned int, flags)
  2612. {
  2613. struct shmem_inode_info *info;
  2614. struct file *file;
  2615. int fd, error;
  2616. char *name;
  2617. long len;
  2618. if (flags & ~(unsigned int)MFD_ALL_FLAGS)
  2619. return -EINVAL;
  2620. /* length includes terminating zero */
  2621. len = strnlen_user(uname, MFD_NAME_MAX_LEN + 1);
  2622. if (len <= 0)
  2623. return -EFAULT;
  2624. if (len > MFD_NAME_MAX_LEN + 1)
  2625. return -EINVAL;
  2626. name = kmalloc(len + MFD_NAME_PREFIX_LEN, GFP_TEMPORARY);
  2627. if (!name)
  2628. return -ENOMEM;
  2629. strcpy(name, MFD_NAME_PREFIX);
  2630. if (copy_from_user(&name[MFD_NAME_PREFIX_LEN], uname, len)) {
  2631. error = -EFAULT;
  2632. goto err_name;
  2633. }
  2634. /* terminating-zero may have changed after strnlen_user() returned */
  2635. if (name[len + MFD_NAME_PREFIX_LEN - 1]) {
  2636. error = -EFAULT;
  2637. goto err_name;
  2638. }
  2639. fd = get_unused_fd_flags((flags & MFD_CLOEXEC) ? O_CLOEXEC : 0);
  2640. if (fd < 0) {
  2641. error = fd;
  2642. goto err_name;
  2643. }
  2644. file = shmem_file_setup(name, 0, VM_NORESERVE);
  2645. if (IS_ERR(file)) {
  2646. error = PTR_ERR(file);
  2647. goto err_fd;
  2648. }
  2649. info = SHMEM_I(file_inode(file));
  2650. file->f_mode |= FMODE_LSEEK | FMODE_PREAD | FMODE_PWRITE;
  2651. file->f_flags |= O_RDWR | O_LARGEFILE;
  2652. if (flags & MFD_ALLOW_SEALING)
  2653. info->seals &= ~F_SEAL_SEAL;
  2654. fd_install(fd, file);
  2655. kfree(name);
  2656. return fd;
  2657. err_fd:
  2658. put_unused_fd(fd);
  2659. err_name:
  2660. kfree(name);
  2661. return error;
  2662. }
  2663. #endif /* CONFIG_TMPFS */
  2664. static void shmem_put_super(struct super_block *sb)
  2665. {
  2666. struct shmem_sb_info *sbinfo = SHMEM_SB(sb);
  2667. percpu_counter_destroy(&sbinfo->used_blocks);
  2668. mpol_put(sbinfo->mpol);
  2669. kfree(sbinfo);
  2670. sb->s_fs_info = NULL;
  2671. }
  2672. int shmem_fill_super(struct super_block *sb, void *data, int silent)
  2673. {
  2674. struct inode *inode;
  2675. struct shmem_sb_info *sbinfo;
  2676. int err = -ENOMEM;
  2677. /* Round up to L1_CACHE_BYTES to resist false sharing */
  2678. sbinfo = kzalloc(max((int)sizeof(struct shmem_sb_info),
  2679. L1_CACHE_BYTES), GFP_KERNEL);
  2680. if (!sbinfo)
  2681. return -ENOMEM;
  2682. sbinfo->mode = S_IRWXUGO | S_ISVTX;
  2683. sbinfo->uid = current_fsuid();
  2684. sbinfo->gid = current_fsgid();
  2685. sb->s_fs_info = sbinfo;
  2686. #ifdef CONFIG_TMPFS
  2687. /*
  2688. * Per default we only allow half of the physical ram per
  2689. * tmpfs instance, limiting inodes to one per page of lowmem;
  2690. * but the internal instance is left unlimited.
  2691. */
  2692. if (!(sb->s_flags & MS_KERNMOUNT)) {
  2693. sbinfo->max_blocks = shmem_default_max_blocks();
  2694. sbinfo->max_inodes = shmem_default_max_inodes();
  2695. if (shmem_parse_options(data, sbinfo, false)) {
  2696. err = -EINVAL;
  2697. goto failed;
  2698. }
  2699. } else {
  2700. sb->s_flags |= MS_NOUSER;
  2701. }
  2702. sb->s_export_op = &shmem_export_ops;
  2703. sb->s_flags |= MS_NOSEC;
  2704. #else
  2705. sb->s_flags |= MS_NOUSER;
  2706. #endif
  2707. spin_lock_init(&sbinfo->stat_lock);
  2708. if (percpu_counter_init(&sbinfo->used_blocks, 0, GFP_KERNEL))
  2709. goto failed;
  2710. sbinfo->free_inodes = sbinfo->max_inodes;
  2711. sb->s_maxbytes = MAX_LFS_FILESIZE;
  2712. sb->s_blocksize = PAGE_SIZE;
  2713. sb->s_blocksize_bits = PAGE_SHIFT;
  2714. sb->s_magic = TMPFS_MAGIC;
  2715. sb->s_op = &shmem_ops;
  2716. sb->s_time_gran = 1;
  2717. #ifdef CONFIG_TMPFS_XATTR
  2718. sb->s_xattr = shmem_xattr_handlers;
  2719. #endif
  2720. #ifdef CONFIG_TMPFS_POSIX_ACL
  2721. sb->s_flags |= MS_POSIXACL;
  2722. #endif
  2723. inode = shmem_get_inode(sb, NULL, S_IFDIR | sbinfo->mode, 0, VM_NORESERVE);
  2724. if (!inode)
  2725. goto failed;
  2726. inode->i_uid = sbinfo->uid;
  2727. inode->i_gid = sbinfo->gid;
  2728. sb->s_root = d_make_root(inode);
  2729. if (!sb->s_root)
  2730. goto failed;
  2731. return 0;
  2732. failed:
  2733. shmem_put_super(sb);
  2734. return err;
  2735. }
  2736. static struct kmem_cache *shmem_inode_cachep;
  2737. static struct inode *shmem_alloc_inode(struct super_block *sb)
  2738. {
  2739. struct shmem_inode_info *info;
  2740. info = kmem_cache_alloc(shmem_inode_cachep, GFP_KERNEL);
  2741. if (!info)
  2742. return NULL;
  2743. return &info->vfs_inode;
  2744. }
  2745. static void shmem_destroy_callback(struct rcu_head *head)
  2746. {
  2747. struct inode *inode = container_of(head, struct inode, i_rcu);
  2748. if (S_ISLNK(inode->i_mode))
  2749. kfree(inode->i_link);
  2750. kmem_cache_free(shmem_inode_cachep, SHMEM_I(inode));
  2751. }
  2752. static void shmem_destroy_inode(struct inode *inode)
  2753. {
  2754. if (S_ISREG(inode->i_mode))
  2755. mpol_free_shared_policy(&SHMEM_I(inode)->policy);
  2756. call_rcu(&inode->i_rcu, shmem_destroy_callback);
  2757. }
  2758. static void shmem_init_inode(void *foo)
  2759. {
  2760. struct shmem_inode_info *info = foo;
  2761. inode_init_once(&info->vfs_inode);
  2762. }
  2763. static int shmem_init_inodecache(void)
  2764. {
  2765. shmem_inode_cachep = kmem_cache_create("shmem_inode_cache",
  2766. sizeof(struct shmem_inode_info),
  2767. 0, SLAB_PANIC|SLAB_ACCOUNT, shmem_init_inode);
  2768. return 0;
  2769. }
  2770. static void shmem_destroy_inodecache(void)
  2771. {
  2772. kmem_cache_destroy(shmem_inode_cachep);
  2773. }
  2774. static const struct address_space_operations shmem_aops = {
  2775. .writepage = shmem_writepage,
  2776. .set_page_dirty = __set_page_dirty_no_writeback,
  2777. #ifdef CONFIG_TMPFS
  2778. .write_begin = shmem_write_begin,
  2779. .write_end = shmem_write_end,
  2780. #endif
  2781. #ifdef CONFIG_MIGRATION
  2782. .migratepage = migrate_page,
  2783. #endif
  2784. .error_remove_page = generic_error_remove_page,
  2785. };
  2786. static const struct file_operations shmem_file_operations = {
  2787. .mmap = shmem_mmap,
  2788. #ifdef CONFIG_TMPFS
  2789. .llseek = shmem_file_llseek,
  2790. .read_iter = shmem_file_read_iter,
  2791. .write_iter = generic_file_write_iter,
  2792. .fsync = noop_fsync,
  2793. .splice_read = shmem_file_splice_read,
  2794. .splice_write = iter_file_splice_write,
  2795. .fallocate = shmem_fallocate,
  2796. #endif
  2797. };
  2798. static const struct inode_operations shmem_inode_operations = {
  2799. .getattr = shmem_getattr,
  2800. .setattr = shmem_setattr,
  2801. #ifdef CONFIG_TMPFS_XATTR
  2802. .setxattr = generic_setxattr,
  2803. .getxattr = generic_getxattr,
  2804. .listxattr = shmem_listxattr,
  2805. .removexattr = generic_removexattr,
  2806. .set_acl = simple_set_acl,
  2807. #endif
  2808. };
  2809. static const struct inode_operations shmem_dir_inode_operations = {
  2810. #ifdef CONFIG_TMPFS
  2811. .create = shmem_create,
  2812. .lookup = simple_lookup,
  2813. .link = shmem_link,
  2814. .unlink = shmem_unlink,
  2815. .symlink = shmem_symlink,
  2816. .mkdir = shmem_mkdir,
  2817. .rmdir = shmem_rmdir,
  2818. .mknod = shmem_mknod,
  2819. .rename2 = shmem_rename2,
  2820. .tmpfile = shmem_tmpfile,
  2821. #endif
  2822. #ifdef CONFIG_TMPFS_XATTR
  2823. .setxattr = generic_setxattr,
  2824. .getxattr = generic_getxattr,
  2825. .listxattr = shmem_listxattr,
  2826. .removexattr = generic_removexattr,
  2827. #endif
  2828. #ifdef CONFIG_TMPFS_POSIX_ACL
  2829. .setattr = shmem_setattr,
  2830. .set_acl = simple_set_acl,
  2831. #endif
  2832. };
  2833. static const struct inode_operations shmem_special_inode_operations = {
  2834. #ifdef CONFIG_TMPFS_XATTR
  2835. .setxattr = generic_setxattr,
  2836. .getxattr = generic_getxattr,
  2837. .listxattr = shmem_listxattr,
  2838. .removexattr = generic_removexattr,
  2839. #endif
  2840. #ifdef CONFIG_TMPFS_POSIX_ACL
  2841. .setattr = shmem_setattr,
  2842. .set_acl = simple_set_acl,
  2843. #endif
  2844. };
  2845. static const struct super_operations shmem_ops = {
  2846. .alloc_inode = shmem_alloc_inode,
  2847. .destroy_inode = shmem_destroy_inode,
  2848. #ifdef CONFIG_TMPFS
  2849. .statfs = shmem_statfs,
  2850. .remount_fs = shmem_remount_fs,
  2851. .show_options = shmem_show_options,
  2852. #endif
  2853. .evict_inode = shmem_evict_inode,
  2854. .drop_inode = generic_delete_inode,
  2855. .put_super = shmem_put_super,
  2856. };
  2857. static const struct vm_operations_struct shmem_vm_ops = {
  2858. .fault = shmem_fault,
  2859. .map_pages = filemap_map_pages,
  2860. #ifdef CONFIG_NUMA
  2861. .set_policy = shmem_set_policy,
  2862. .get_policy = shmem_get_policy,
  2863. #endif
  2864. };
  2865. static struct dentry *shmem_mount(struct file_system_type *fs_type,
  2866. int flags, const char *dev_name, void *data)
  2867. {
  2868. return mount_nodev(fs_type, flags, data, shmem_fill_super);
  2869. }
  2870. static struct file_system_type shmem_fs_type = {
  2871. .owner = THIS_MODULE,
  2872. .name = "tmpfs",
  2873. .mount = shmem_mount,
  2874. .kill_sb = kill_litter_super,
  2875. .fs_flags = FS_USERNS_MOUNT,
  2876. };
  2877. int __init shmem_init(void)
  2878. {
  2879. int error;
  2880. /* If rootfs called this, don't re-init */
  2881. if (shmem_inode_cachep)
  2882. return 0;
  2883. error = shmem_init_inodecache();
  2884. if (error)
  2885. goto out3;
  2886. error = register_filesystem(&shmem_fs_type);
  2887. if (error) {
  2888. pr_err("Could not register tmpfs\n");
  2889. goto out2;
  2890. }
  2891. shm_mnt = kern_mount(&shmem_fs_type);
  2892. if (IS_ERR(shm_mnt)) {
  2893. error = PTR_ERR(shm_mnt);
  2894. pr_err("Could not kern_mount tmpfs\n");
  2895. goto out1;
  2896. }
  2897. return 0;
  2898. out1:
  2899. unregister_filesystem(&shmem_fs_type);
  2900. out2:
  2901. shmem_destroy_inodecache();
  2902. out3:
  2903. shm_mnt = ERR_PTR(error);
  2904. return error;
  2905. }
  2906. #else /* !CONFIG_SHMEM */
  2907. /*
  2908. * tiny-shmem: simple shmemfs and tmpfs using ramfs code
  2909. *
  2910. * This is intended for small system where the benefits of the full
  2911. * shmem code (swap-backed and resource-limited) are outweighed by
  2912. * their complexity. On systems without swap this code should be
  2913. * effectively equivalent, but much lighter weight.
  2914. */
  2915. static struct file_system_type shmem_fs_type = {
  2916. .name = "tmpfs",
  2917. .mount = ramfs_mount,
  2918. .kill_sb = kill_litter_super,
  2919. .fs_flags = FS_USERNS_MOUNT,
  2920. };
  2921. int __init shmem_init(void)
  2922. {
  2923. BUG_ON(register_filesystem(&shmem_fs_type) != 0);
  2924. shm_mnt = kern_mount(&shmem_fs_type);
  2925. BUG_ON(IS_ERR(shm_mnt));
  2926. return 0;
  2927. }
  2928. int shmem_unuse(swp_entry_t swap, struct page *page)
  2929. {
  2930. return 0;
  2931. }
  2932. int shmem_lock(struct file *file, int lock, struct user_struct *user)
  2933. {
  2934. return 0;
  2935. }
  2936. void shmem_unlock_mapping(struct address_space *mapping)
  2937. {
  2938. }
  2939. void shmem_truncate_range(struct inode *inode, loff_t lstart, loff_t lend)
  2940. {
  2941. truncate_inode_pages_range(inode->i_mapping, lstart, lend);
  2942. }
  2943. EXPORT_SYMBOL_GPL(shmem_truncate_range);
  2944. #define shmem_vm_ops generic_file_vm_ops
  2945. #define shmem_file_operations ramfs_file_operations
  2946. #define shmem_get_inode(sb, dir, mode, dev, flags) ramfs_get_inode(sb, dir, mode, dev)
  2947. #define shmem_acct_size(flags, size) 0
  2948. #define shmem_unacct_size(flags, size) do {} while (0)
  2949. #endif /* CONFIG_SHMEM */
  2950. /* common code */
  2951. static struct dentry_operations anon_ops = {
  2952. .d_dname = simple_dname
  2953. };
  2954. static struct file *__shmem_file_setup(const char *name, loff_t size,
  2955. unsigned long flags, unsigned int i_flags)
  2956. {
  2957. struct file *res;
  2958. struct inode *inode;
  2959. struct path path;
  2960. struct super_block *sb;
  2961. struct qstr this;
  2962. if (IS_ERR(shm_mnt))
  2963. return ERR_CAST(shm_mnt);
  2964. if (size < 0 || size > MAX_LFS_FILESIZE)
  2965. return ERR_PTR(-EINVAL);
  2966. if (shmem_acct_size(flags, size))
  2967. return ERR_PTR(-ENOMEM);
  2968. res = ERR_PTR(-ENOMEM);
  2969. this.name = name;
  2970. this.len = strlen(name);
  2971. this.hash = 0; /* will go */
  2972. sb = shm_mnt->mnt_sb;
  2973. path.mnt = mntget(shm_mnt);
  2974. path.dentry = d_alloc_pseudo(sb, &this);
  2975. if (!path.dentry)
  2976. goto put_memory;
  2977. d_set_d_op(path.dentry, &anon_ops);
  2978. res = ERR_PTR(-ENOSPC);
  2979. inode = shmem_get_inode(sb, NULL, S_IFREG | S_IRWXUGO, 0, flags);
  2980. if (!inode)
  2981. goto put_memory;
  2982. inode->i_flags |= i_flags;
  2983. d_instantiate(path.dentry, inode);
  2984. inode->i_size = size;
  2985. clear_nlink(inode); /* It is unlinked */
  2986. res = ERR_PTR(ramfs_nommu_expand_for_mapping(inode, size));
  2987. if (IS_ERR(res))
  2988. goto put_path;
  2989. res = alloc_file(&path, FMODE_WRITE | FMODE_READ,
  2990. &shmem_file_operations);
  2991. if (IS_ERR(res))
  2992. goto put_path;
  2993. return res;
  2994. put_memory:
  2995. shmem_unacct_size(flags, size);
  2996. put_path:
  2997. path_put(&path);
  2998. return res;
  2999. }
  3000. /**
  3001. * shmem_kernel_file_setup - get an unlinked file living in tmpfs which must be
  3002. * kernel internal. There will be NO LSM permission checks against the
  3003. * underlying inode. So users of this interface must do LSM checks at a
  3004. * higher layer. The users are the big_key and shm implementations. LSM
  3005. * checks are provided at the key or shm level rather than the inode.
  3006. * @name: name for dentry (to be seen in /proc/<pid>/maps
  3007. * @size: size to be set for the file
  3008. * @flags: VM_NORESERVE suppresses pre-accounting of the entire object size
  3009. */
  3010. struct file *shmem_kernel_file_setup(const char *name, loff_t size, unsigned long flags)
  3011. {
  3012. return __shmem_file_setup(name, size, flags, S_PRIVATE);
  3013. }
  3014. /**
  3015. * shmem_file_setup - get an unlinked file living in tmpfs
  3016. * @name: name for dentry (to be seen in /proc/<pid>/maps
  3017. * @size: size to be set for the file
  3018. * @flags: VM_NORESERVE suppresses pre-accounting of the entire object size
  3019. */
  3020. struct file *shmem_file_setup(const char *name, loff_t size, unsigned long flags)
  3021. {
  3022. return __shmem_file_setup(name, size, flags, 0);
  3023. }
  3024. EXPORT_SYMBOL_GPL(shmem_file_setup);
  3025. /**
  3026. * shmem_zero_setup - setup a shared anonymous mapping
  3027. * @vma: the vma to be mmapped is prepared by do_mmap_pgoff
  3028. */
  3029. int shmem_zero_setup(struct vm_area_struct *vma)
  3030. {
  3031. struct file *file;
  3032. loff_t size = vma->vm_end - vma->vm_start;
  3033. /*
  3034. * Cloning a new file under mmap_sem leads to a lock ordering conflict
  3035. * between XFS directory reading and selinux: since this file is only
  3036. * accessible to the user through its mapping, use S_PRIVATE flag to
  3037. * bypass file security, in the same way as shmem_kernel_file_setup().
  3038. */
  3039. file = __shmem_file_setup("dev/zero", size, vma->vm_flags, S_PRIVATE);
  3040. if (IS_ERR(file))
  3041. return PTR_ERR(file);
  3042. if (vma->vm_file)
  3043. fput(vma->vm_file);
  3044. vma->vm_file = file;
  3045. vma->vm_ops = &shmem_vm_ops;
  3046. return 0;
  3047. }
  3048. /**
  3049. * shmem_read_mapping_page_gfp - read into page cache, using specified page allocation flags.
  3050. * @mapping: the page's address_space
  3051. * @index: the page index
  3052. * @gfp: the page allocator flags to use if allocating
  3053. *
  3054. * This behaves as a tmpfs "read_cache_page_gfp(mapping, index, gfp)",
  3055. * with any new page allocations done using the specified allocation flags.
  3056. * But read_cache_page_gfp() uses the ->readpage() method: which does not
  3057. * suit tmpfs, since it may have pages in swapcache, and needs to find those
  3058. * for itself; although drivers/gpu/drm i915 and ttm rely upon this support.
  3059. *
  3060. * i915_gem_object_get_pages_gtt() mixes __GFP_NORETRY | __GFP_NOWARN in
  3061. * with the mapping_gfp_mask(), to avoid OOMing the machine unnecessarily.
  3062. */
  3063. struct page *shmem_read_mapping_page_gfp(struct address_space *mapping,
  3064. pgoff_t index, gfp_t gfp)
  3065. {
  3066. #ifdef CONFIG_SHMEM
  3067. struct inode *inode = mapping->host;
  3068. struct page *page;
  3069. int error;
  3070. BUG_ON(mapping->a_ops != &shmem_aops);
  3071. error = shmem_getpage_gfp(inode, index, &page, SGP_CACHE,
  3072. gfp, NULL, NULL);
  3073. if (error)
  3074. page = ERR_PTR(error);
  3075. else
  3076. unlock_page(page);
  3077. return page;
  3078. #else
  3079. /*
  3080. * The tiny !SHMEM case uses ramfs without swap
  3081. */
  3082. return read_cache_page_gfp(mapping, index, gfp);
  3083. #endif
  3084. }
  3085. EXPORT_SYMBOL_GPL(shmem_read_mapping_page_gfp);