shmem.c 89 KB

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