shmem.c 89 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569257025712572257325742575257625772578257925802581258225832584258525862587258825892590259125922593259425952596259725982599260026012602260326042605260626072608260926102611261226132614261526162617261826192620262126222623262426252626262726282629263026312632263326342635263626372638263926402641264226432644264526462647264826492650265126522653265426552656265726582659266026612662266326642665266626672668266926702671267226732674267526762677267826792680268126822683268426852686268726882689269026912692269326942695269626972698269927002701270227032704270527062707270827092710271127122713271427152716271727182719272027212722272327242725272627272728272927302731273227332734273527362737273827392740274127422743274427452746274727482749275027512752275327542755275627572758275927602761276227632764276527662767276827692770277127722773277427752776277727782779278027812782278327842785278627872788278927902791279227932794279527962797279827992800280128022803280428052806280728082809281028112812281328142815281628172818281928202821282228232824282528262827282828292830283128322833283428352836283728382839284028412842284328442845284628472848284928502851285228532854285528562857285828592860286128622863286428652866286728682869287028712872287328742875287628772878287928802881288228832884288528862887288828892890289128922893289428952896289728982899290029012902290329042905290629072908290929102911291229132914291529162917291829192920292129222923292429252926292729282929293029312932293329342935293629372938293929402941294229432944294529462947294829492950295129522953295429552956295729582959296029612962296329642965296629672968296929702971297229732974297529762977297829792980298129822983298429852986298729882989299029912992299329942995299629972998299930003001300230033004300530063007300830093010301130123013301430153016301730183019302030213022302330243025302630273028302930303031303230333034303530363037303830393040304130423043304430453046304730483049305030513052305330543055305630573058305930603061306230633064306530663067306830693070307130723073307430753076307730783079308030813082308330843085308630873088308930903091309230933094309530963097309830993100310131023103310431053106310731083109311031113112311331143115311631173118311931203121312231233124312531263127312831293130313131323133313431353136313731383139314031413142314331443145314631473148314931503151315231533154315531563157315831593160316131623163316431653166316731683169317031713172317331743175317631773178317931803181318231833184318531863187318831893190319131923193319431953196319731983199320032013202320332043205320632073208320932103211321232133214321532163217321832193220322132223223322432253226322732283229323032313232323332343235323632373238323932403241324232433244324532463247324832493250325132523253325432553256325732583259326032613262326332643265326632673268326932703271327232733274327532763277327832793280328132823283328432853286328732883289329032913292329332943295329632973298329933003301330233033304330533063307330833093310331133123313331433153316331733183319332033213322332333243325332633273328332933303331333233333334333533363337333833393340334133423343334433453346334733483349335033513352335333543355335633573358335933603361336233633364336533663367336833693370337133723373337433753376337733783379338033813382338333843385338633873388338933903391339233933394339533963397339833993400340134023403340434053406340734083409341034113412341334143415341634173418341934203421342234233424342534263427342834293430343134323433343434353436343734383439344034413442344334443445344634473448344934503451345234533454
  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. if (!mapping->host)
  1306. return false;
  1307. return mapping->host->i_sb->s_op == &shmem_ops;
  1308. }
  1309. #ifdef CONFIG_TMPFS
  1310. static const struct inode_operations shmem_symlink_inode_operations;
  1311. static const struct inode_operations shmem_short_symlink_operations;
  1312. #ifdef CONFIG_TMPFS_XATTR
  1313. static int shmem_initxattrs(struct inode *, const struct xattr *, void *);
  1314. #else
  1315. #define shmem_initxattrs NULL
  1316. #endif
  1317. static int
  1318. shmem_write_begin(struct file *file, struct address_space *mapping,
  1319. loff_t pos, unsigned len, unsigned flags,
  1320. struct page **pagep, void **fsdata)
  1321. {
  1322. struct inode *inode = mapping->host;
  1323. struct shmem_inode_info *info = SHMEM_I(inode);
  1324. pgoff_t index = pos >> PAGE_CACHE_SHIFT;
  1325. /* i_mutex is held by caller */
  1326. if (unlikely(info->seals)) {
  1327. if (info->seals & F_SEAL_WRITE)
  1328. return -EPERM;
  1329. if ((info->seals & F_SEAL_GROW) && pos + len > inode->i_size)
  1330. return -EPERM;
  1331. }
  1332. return shmem_getpage(inode, index, pagep, SGP_WRITE, NULL);
  1333. }
  1334. static int
  1335. shmem_write_end(struct file *file, struct address_space *mapping,
  1336. loff_t pos, unsigned len, unsigned copied,
  1337. struct page *page, void *fsdata)
  1338. {
  1339. struct inode *inode = mapping->host;
  1340. if (pos + copied > inode->i_size)
  1341. i_size_write(inode, pos + copied);
  1342. if (!PageUptodate(page)) {
  1343. if (copied < PAGE_CACHE_SIZE) {
  1344. unsigned from = pos & (PAGE_CACHE_SIZE - 1);
  1345. zero_user_segments(page, 0, from,
  1346. from + copied, PAGE_CACHE_SIZE);
  1347. }
  1348. SetPageUptodate(page);
  1349. }
  1350. set_page_dirty(page);
  1351. unlock_page(page);
  1352. page_cache_release(page);
  1353. return copied;
  1354. }
  1355. static ssize_t shmem_file_read_iter(struct kiocb *iocb, struct iov_iter *to)
  1356. {
  1357. struct file *file = iocb->ki_filp;
  1358. struct inode *inode = file_inode(file);
  1359. struct address_space *mapping = inode->i_mapping;
  1360. pgoff_t index;
  1361. unsigned long offset;
  1362. enum sgp_type sgp = SGP_READ;
  1363. int error = 0;
  1364. ssize_t retval = 0;
  1365. loff_t *ppos = &iocb->ki_pos;
  1366. /*
  1367. * Might this read be for a stacking filesystem? Then when reading
  1368. * holes of a sparse file, we actually need to allocate those pages,
  1369. * and even mark them dirty, so it cannot exceed the max_blocks limit.
  1370. */
  1371. if (!iter_is_iovec(to))
  1372. sgp = SGP_DIRTY;
  1373. index = *ppos >> PAGE_CACHE_SHIFT;
  1374. offset = *ppos & ~PAGE_CACHE_MASK;
  1375. for (;;) {
  1376. struct page *page = NULL;
  1377. pgoff_t end_index;
  1378. unsigned long nr, ret;
  1379. loff_t i_size = i_size_read(inode);
  1380. end_index = i_size >> PAGE_CACHE_SHIFT;
  1381. if (index > end_index)
  1382. break;
  1383. if (index == end_index) {
  1384. nr = i_size & ~PAGE_CACHE_MASK;
  1385. if (nr <= offset)
  1386. break;
  1387. }
  1388. error = shmem_getpage(inode, index, &page, sgp, NULL);
  1389. if (error) {
  1390. if (error == -EINVAL)
  1391. error = 0;
  1392. break;
  1393. }
  1394. if (page)
  1395. unlock_page(page);
  1396. /*
  1397. * We must evaluate after, since reads (unlike writes)
  1398. * are called without i_mutex protection against truncate
  1399. */
  1400. nr = PAGE_CACHE_SIZE;
  1401. i_size = i_size_read(inode);
  1402. end_index = i_size >> PAGE_CACHE_SHIFT;
  1403. if (index == end_index) {
  1404. nr = i_size & ~PAGE_CACHE_MASK;
  1405. if (nr <= offset) {
  1406. if (page)
  1407. page_cache_release(page);
  1408. break;
  1409. }
  1410. }
  1411. nr -= offset;
  1412. if (page) {
  1413. /*
  1414. * If users can be writing to this page using arbitrary
  1415. * virtual addresses, take care about potential aliasing
  1416. * before reading the page on the kernel side.
  1417. */
  1418. if (mapping_writably_mapped(mapping))
  1419. flush_dcache_page(page);
  1420. /*
  1421. * Mark the page accessed if we read the beginning.
  1422. */
  1423. if (!offset)
  1424. mark_page_accessed(page);
  1425. } else {
  1426. page = ZERO_PAGE(0);
  1427. page_cache_get(page);
  1428. }
  1429. /*
  1430. * Ok, we have the page, and it's up-to-date, so
  1431. * now we can copy it to user space...
  1432. */
  1433. ret = copy_page_to_iter(page, offset, nr, to);
  1434. retval += ret;
  1435. offset += ret;
  1436. index += offset >> PAGE_CACHE_SHIFT;
  1437. offset &= ~PAGE_CACHE_MASK;
  1438. page_cache_release(page);
  1439. if (!iov_iter_count(to))
  1440. break;
  1441. if (ret < nr) {
  1442. error = -EFAULT;
  1443. break;
  1444. }
  1445. cond_resched();
  1446. }
  1447. *ppos = ((loff_t) index << PAGE_CACHE_SHIFT) + offset;
  1448. file_accessed(file);
  1449. return retval ? retval : error;
  1450. }
  1451. static ssize_t shmem_file_splice_read(struct file *in, loff_t *ppos,
  1452. struct pipe_inode_info *pipe, size_t len,
  1453. unsigned int flags)
  1454. {
  1455. struct address_space *mapping = in->f_mapping;
  1456. struct inode *inode = mapping->host;
  1457. unsigned int loff, nr_pages, req_pages;
  1458. struct page *pages[PIPE_DEF_BUFFERS];
  1459. struct partial_page partial[PIPE_DEF_BUFFERS];
  1460. struct page *page;
  1461. pgoff_t index, end_index;
  1462. loff_t isize, left;
  1463. int error, page_nr;
  1464. struct splice_pipe_desc spd = {
  1465. .pages = pages,
  1466. .partial = partial,
  1467. .nr_pages_max = PIPE_DEF_BUFFERS,
  1468. .flags = flags,
  1469. .ops = &page_cache_pipe_buf_ops,
  1470. .spd_release = spd_release_page,
  1471. };
  1472. isize = i_size_read(inode);
  1473. if (unlikely(*ppos >= isize))
  1474. return 0;
  1475. left = isize - *ppos;
  1476. if (unlikely(left < len))
  1477. len = left;
  1478. if (splice_grow_spd(pipe, &spd))
  1479. return -ENOMEM;
  1480. index = *ppos >> PAGE_CACHE_SHIFT;
  1481. loff = *ppos & ~PAGE_CACHE_MASK;
  1482. req_pages = (len + loff + PAGE_CACHE_SIZE - 1) >> PAGE_CACHE_SHIFT;
  1483. nr_pages = min(req_pages, spd.nr_pages_max);
  1484. spd.nr_pages = find_get_pages_contig(mapping, index,
  1485. nr_pages, spd.pages);
  1486. index += spd.nr_pages;
  1487. error = 0;
  1488. while (spd.nr_pages < nr_pages) {
  1489. error = shmem_getpage(inode, index, &page, SGP_CACHE, NULL);
  1490. if (error)
  1491. break;
  1492. unlock_page(page);
  1493. spd.pages[spd.nr_pages++] = page;
  1494. index++;
  1495. }
  1496. index = *ppos >> PAGE_CACHE_SHIFT;
  1497. nr_pages = spd.nr_pages;
  1498. spd.nr_pages = 0;
  1499. for (page_nr = 0; page_nr < nr_pages; page_nr++) {
  1500. unsigned int this_len;
  1501. if (!len)
  1502. break;
  1503. this_len = min_t(unsigned long, len, PAGE_CACHE_SIZE - loff);
  1504. page = spd.pages[page_nr];
  1505. if (!PageUptodate(page) || page->mapping != mapping) {
  1506. error = shmem_getpage(inode, index, &page,
  1507. SGP_CACHE, NULL);
  1508. if (error)
  1509. break;
  1510. unlock_page(page);
  1511. page_cache_release(spd.pages[page_nr]);
  1512. spd.pages[page_nr] = page;
  1513. }
  1514. isize = i_size_read(inode);
  1515. end_index = (isize - 1) >> PAGE_CACHE_SHIFT;
  1516. if (unlikely(!isize || index > end_index))
  1517. break;
  1518. if (end_index == index) {
  1519. unsigned int plen;
  1520. plen = ((isize - 1) & ~PAGE_CACHE_MASK) + 1;
  1521. if (plen <= loff)
  1522. break;
  1523. this_len = min(this_len, plen - loff);
  1524. len = this_len;
  1525. }
  1526. spd.partial[page_nr].offset = loff;
  1527. spd.partial[page_nr].len = this_len;
  1528. len -= this_len;
  1529. loff = 0;
  1530. spd.nr_pages++;
  1531. index++;
  1532. }
  1533. while (page_nr < nr_pages)
  1534. page_cache_release(spd.pages[page_nr++]);
  1535. if (spd.nr_pages)
  1536. error = splice_to_pipe(pipe, &spd);
  1537. splice_shrink_spd(&spd);
  1538. if (error > 0) {
  1539. *ppos += error;
  1540. file_accessed(in);
  1541. }
  1542. return error;
  1543. }
  1544. /*
  1545. * llseek SEEK_DATA or SEEK_HOLE through the radix_tree.
  1546. */
  1547. static pgoff_t shmem_seek_hole_data(struct address_space *mapping,
  1548. pgoff_t index, pgoff_t end, int whence)
  1549. {
  1550. struct page *page;
  1551. struct pagevec pvec;
  1552. pgoff_t indices[PAGEVEC_SIZE];
  1553. bool done = false;
  1554. int i;
  1555. pagevec_init(&pvec, 0);
  1556. pvec.nr = 1; /* start small: we may be there already */
  1557. while (!done) {
  1558. pvec.nr = find_get_entries(mapping, index,
  1559. pvec.nr, pvec.pages, indices);
  1560. if (!pvec.nr) {
  1561. if (whence == SEEK_DATA)
  1562. index = end;
  1563. break;
  1564. }
  1565. for (i = 0; i < pvec.nr; i++, index++) {
  1566. if (index < indices[i]) {
  1567. if (whence == SEEK_HOLE) {
  1568. done = true;
  1569. break;
  1570. }
  1571. index = indices[i];
  1572. }
  1573. page = pvec.pages[i];
  1574. if (page && !radix_tree_exceptional_entry(page)) {
  1575. if (!PageUptodate(page))
  1576. page = NULL;
  1577. }
  1578. if (index >= end ||
  1579. (page && whence == SEEK_DATA) ||
  1580. (!page && whence == SEEK_HOLE)) {
  1581. done = true;
  1582. break;
  1583. }
  1584. }
  1585. pagevec_remove_exceptionals(&pvec);
  1586. pagevec_release(&pvec);
  1587. pvec.nr = PAGEVEC_SIZE;
  1588. cond_resched();
  1589. }
  1590. return index;
  1591. }
  1592. static loff_t shmem_file_llseek(struct file *file, loff_t offset, int whence)
  1593. {
  1594. struct address_space *mapping = file->f_mapping;
  1595. struct inode *inode = mapping->host;
  1596. pgoff_t start, end;
  1597. loff_t new_offset;
  1598. if (whence != SEEK_DATA && whence != SEEK_HOLE)
  1599. return generic_file_llseek_size(file, offset, whence,
  1600. MAX_LFS_FILESIZE, i_size_read(inode));
  1601. mutex_lock(&inode->i_mutex);
  1602. /* We're holding i_mutex so we can access i_size directly */
  1603. if (offset < 0)
  1604. offset = -EINVAL;
  1605. else if (offset >= inode->i_size)
  1606. offset = -ENXIO;
  1607. else {
  1608. start = offset >> PAGE_CACHE_SHIFT;
  1609. end = (inode->i_size + PAGE_CACHE_SIZE - 1) >> PAGE_CACHE_SHIFT;
  1610. new_offset = shmem_seek_hole_data(mapping, start, end, whence);
  1611. new_offset <<= PAGE_CACHE_SHIFT;
  1612. if (new_offset > offset) {
  1613. if (new_offset < inode->i_size)
  1614. offset = new_offset;
  1615. else if (whence == SEEK_DATA)
  1616. offset = -ENXIO;
  1617. else
  1618. offset = inode->i_size;
  1619. }
  1620. }
  1621. if (offset >= 0)
  1622. offset = vfs_setpos(file, offset, MAX_LFS_FILESIZE);
  1623. mutex_unlock(&inode->i_mutex);
  1624. return offset;
  1625. }
  1626. /*
  1627. * We need a tag: a new tag would expand every radix_tree_node by 8 bytes,
  1628. * so reuse a tag which we firmly believe is never set or cleared on shmem.
  1629. */
  1630. #define SHMEM_TAG_PINNED PAGECACHE_TAG_TOWRITE
  1631. #define LAST_SCAN 4 /* about 150ms max */
  1632. static void shmem_tag_pins(struct address_space *mapping)
  1633. {
  1634. struct radix_tree_iter iter;
  1635. void **slot;
  1636. pgoff_t start;
  1637. struct page *page;
  1638. lru_add_drain();
  1639. start = 0;
  1640. rcu_read_lock();
  1641. restart:
  1642. radix_tree_for_each_slot(slot, &mapping->page_tree, &iter, start) {
  1643. page = radix_tree_deref_slot(slot);
  1644. if (!page || radix_tree_exception(page)) {
  1645. if (radix_tree_deref_retry(page))
  1646. goto restart;
  1647. } else if (page_count(page) - page_mapcount(page) > 1) {
  1648. spin_lock_irq(&mapping->tree_lock);
  1649. radix_tree_tag_set(&mapping->page_tree, iter.index,
  1650. SHMEM_TAG_PINNED);
  1651. spin_unlock_irq(&mapping->tree_lock);
  1652. }
  1653. if (need_resched()) {
  1654. cond_resched_rcu();
  1655. start = iter.index + 1;
  1656. goto restart;
  1657. }
  1658. }
  1659. rcu_read_unlock();
  1660. }
  1661. /*
  1662. * Setting SEAL_WRITE requires us to verify there's no pending writer. However,
  1663. * via get_user_pages(), drivers might have some pending I/O without any active
  1664. * user-space mappings (eg., direct-IO, AIO). Therefore, we look at all pages
  1665. * and see whether it has an elevated ref-count. If so, we tag them and wait for
  1666. * them to be dropped.
  1667. * The caller must guarantee that no new user will acquire writable references
  1668. * to those pages to avoid races.
  1669. */
  1670. static int shmem_wait_for_pins(struct address_space *mapping)
  1671. {
  1672. struct radix_tree_iter iter;
  1673. void **slot;
  1674. pgoff_t start;
  1675. struct page *page;
  1676. int error, scan;
  1677. shmem_tag_pins(mapping);
  1678. error = 0;
  1679. for (scan = 0; scan <= LAST_SCAN; scan++) {
  1680. if (!radix_tree_tagged(&mapping->page_tree, SHMEM_TAG_PINNED))
  1681. break;
  1682. if (!scan)
  1683. lru_add_drain_all();
  1684. else if (schedule_timeout_killable((HZ << scan) / 200))
  1685. scan = LAST_SCAN;
  1686. start = 0;
  1687. rcu_read_lock();
  1688. restart:
  1689. radix_tree_for_each_tagged(slot, &mapping->page_tree, &iter,
  1690. start, SHMEM_TAG_PINNED) {
  1691. page = radix_tree_deref_slot(slot);
  1692. if (radix_tree_exception(page)) {
  1693. if (radix_tree_deref_retry(page))
  1694. goto restart;
  1695. page = NULL;
  1696. }
  1697. if (page &&
  1698. page_count(page) - page_mapcount(page) != 1) {
  1699. if (scan < LAST_SCAN)
  1700. goto continue_resched;
  1701. /*
  1702. * On the last scan, we clean up all those tags
  1703. * we inserted; but make a note that we still
  1704. * found pages pinned.
  1705. */
  1706. error = -EBUSY;
  1707. }
  1708. spin_lock_irq(&mapping->tree_lock);
  1709. radix_tree_tag_clear(&mapping->page_tree,
  1710. iter.index, SHMEM_TAG_PINNED);
  1711. spin_unlock_irq(&mapping->tree_lock);
  1712. continue_resched:
  1713. if (need_resched()) {
  1714. cond_resched_rcu();
  1715. start = iter.index + 1;
  1716. goto restart;
  1717. }
  1718. }
  1719. rcu_read_unlock();
  1720. }
  1721. return error;
  1722. }
  1723. #define F_ALL_SEALS (F_SEAL_SEAL | \
  1724. F_SEAL_SHRINK | \
  1725. F_SEAL_GROW | \
  1726. F_SEAL_WRITE)
  1727. int shmem_add_seals(struct file *file, unsigned int seals)
  1728. {
  1729. struct inode *inode = file_inode(file);
  1730. struct shmem_inode_info *info = SHMEM_I(inode);
  1731. int error;
  1732. /*
  1733. * SEALING
  1734. * Sealing allows multiple parties to share a shmem-file but restrict
  1735. * access to a specific subset of file operations. Seals can only be
  1736. * added, but never removed. This way, mutually untrusted parties can
  1737. * share common memory regions with a well-defined policy. A malicious
  1738. * peer can thus never perform unwanted operations on a shared object.
  1739. *
  1740. * Seals are only supported on special shmem-files and always affect
  1741. * the whole underlying inode. Once a seal is set, it may prevent some
  1742. * kinds of access to the file. Currently, the following seals are
  1743. * defined:
  1744. * SEAL_SEAL: Prevent further seals from being set on this file
  1745. * SEAL_SHRINK: Prevent the file from shrinking
  1746. * SEAL_GROW: Prevent the file from growing
  1747. * SEAL_WRITE: Prevent write access to the file
  1748. *
  1749. * As we don't require any trust relationship between two parties, we
  1750. * must prevent seals from being removed. Therefore, sealing a file
  1751. * only adds a given set of seals to the file, it never touches
  1752. * existing seals. Furthermore, the "setting seals"-operation can be
  1753. * sealed itself, which basically prevents any further seal from being
  1754. * added.
  1755. *
  1756. * Semantics of sealing are only defined on volatile files. Only
  1757. * anonymous shmem files support sealing. More importantly, seals are
  1758. * never written to disk. Therefore, there's no plan to support it on
  1759. * other file types.
  1760. */
  1761. if (file->f_op != &shmem_file_operations)
  1762. return -EINVAL;
  1763. if (!(file->f_mode & FMODE_WRITE))
  1764. return -EPERM;
  1765. if (seals & ~(unsigned int)F_ALL_SEALS)
  1766. return -EINVAL;
  1767. mutex_lock(&inode->i_mutex);
  1768. if (info->seals & F_SEAL_SEAL) {
  1769. error = -EPERM;
  1770. goto unlock;
  1771. }
  1772. if ((seals & F_SEAL_WRITE) && !(info->seals & F_SEAL_WRITE)) {
  1773. error = mapping_deny_writable(file->f_mapping);
  1774. if (error)
  1775. goto unlock;
  1776. error = shmem_wait_for_pins(file->f_mapping);
  1777. if (error) {
  1778. mapping_allow_writable(file->f_mapping);
  1779. goto unlock;
  1780. }
  1781. }
  1782. info->seals |= seals;
  1783. error = 0;
  1784. unlock:
  1785. mutex_unlock(&inode->i_mutex);
  1786. return error;
  1787. }
  1788. EXPORT_SYMBOL_GPL(shmem_add_seals);
  1789. int shmem_get_seals(struct file *file)
  1790. {
  1791. if (file->f_op != &shmem_file_operations)
  1792. return -EINVAL;
  1793. return SHMEM_I(file_inode(file))->seals;
  1794. }
  1795. EXPORT_SYMBOL_GPL(shmem_get_seals);
  1796. long shmem_fcntl(struct file *file, unsigned int cmd, unsigned long arg)
  1797. {
  1798. long error;
  1799. switch (cmd) {
  1800. case F_ADD_SEALS:
  1801. /* disallow upper 32bit */
  1802. if (arg > UINT_MAX)
  1803. return -EINVAL;
  1804. error = shmem_add_seals(file, arg);
  1805. break;
  1806. case F_GET_SEALS:
  1807. error = shmem_get_seals(file);
  1808. break;
  1809. default:
  1810. error = -EINVAL;
  1811. break;
  1812. }
  1813. return error;
  1814. }
  1815. static long shmem_fallocate(struct file *file, int mode, loff_t offset,
  1816. loff_t len)
  1817. {
  1818. struct inode *inode = file_inode(file);
  1819. struct shmem_sb_info *sbinfo = SHMEM_SB(inode->i_sb);
  1820. struct shmem_inode_info *info = SHMEM_I(inode);
  1821. struct shmem_falloc shmem_falloc;
  1822. pgoff_t start, index, end;
  1823. int error;
  1824. if (mode & ~(FALLOC_FL_KEEP_SIZE | FALLOC_FL_PUNCH_HOLE))
  1825. return -EOPNOTSUPP;
  1826. mutex_lock(&inode->i_mutex);
  1827. if (mode & FALLOC_FL_PUNCH_HOLE) {
  1828. struct address_space *mapping = file->f_mapping;
  1829. loff_t unmap_start = round_up(offset, PAGE_SIZE);
  1830. loff_t unmap_end = round_down(offset + len, PAGE_SIZE) - 1;
  1831. DECLARE_WAIT_QUEUE_HEAD_ONSTACK(shmem_falloc_waitq);
  1832. /* protected by i_mutex */
  1833. if (info->seals & F_SEAL_WRITE) {
  1834. error = -EPERM;
  1835. goto out;
  1836. }
  1837. shmem_falloc.waitq = &shmem_falloc_waitq;
  1838. shmem_falloc.start = unmap_start >> PAGE_SHIFT;
  1839. shmem_falloc.next = (unmap_end + 1) >> PAGE_SHIFT;
  1840. spin_lock(&inode->i_lock);
  1841. inode->i_private = &shmem_falloc;
  1842. spin_unlock(&inode->i_lock);
  1843. if ((u64)unmap_end > (u64)unmap_start)
  1844. unmap_mapping_range(mapping, unmap_start,
  1845. 1 + unmap_end - unmap_start, 0);
  1846. shmem_truncate_range(inode, offset, offset + len - 1);
  1847. /* No need to unmap again: hole-punching leaves COWed pages */
  1848. spin_lock(&inode->i_lock);
  1849. inode->i_private = NULL;
  1850. wake_up_all(&shmem_falloc_waitq);
  1851. spin_unlock(&inode->i_lock);
  1852. error = 0;
  1853. goto out;
  1854. }
  1855. /* We need to check rlimit even when FALLOC_FL_KEEP_SIZE */
  1856. error = inode_newsize_ok(inode, offset + len);
  1857. if (error)
  1858. goto out;
  1859. if ((info->seals & F_SEAL_GROW) && offset + len > inode->i_size) {
  1860. error = -EPERM;
  1861. goto out;
  1862. }
  1863. start = offset >> PAGE_CACHE_SHIFT;
  1864. end = (offset + len + PAGE_CACHE_SIZE - 1) >> PAGE_CACHE_SHIFT;
  1865. /* Try to avoid a swapstorm if len is impossible to satisfy */
  1866. if (sbinfo->max_blocks && end - start > sbinfo->max_blocks) {
  1867. error = -ENOSPC;
  1868. goto out;
  1869. }
  1870. shmem_falloc.waitq = NULL;
  1871. shmem_falloc.start = start;
  1872. shmem_falloc.next = start;
  1873. shmem_falloc.nr_falloced = 0;
  1874. shmem_falloc.nr_unswapped = 0;
  1875. spin_lock(&inode->i_lock);
  1876. inode->i_private = &shmem_falloc;
  1877. spin_unlock(&inode->i_lock);
  1878. for (index = start; index < end; index++) {
  1879. struct page *page;
  1880. /*
  1881. * Good, the fallocate(2) manpage permits EINTR: we may have
  1882. * been interrupted because we are using up too much memory.
  1883. */
  1884. if (signal_pending(current))
  1885. error = -EINTR;
  1886. else if (shmem_falloc.nr_unswapped > shmem_falloc.nr_falloced)
  1887. error = -ENOMEM;
  1888. else
  1889. error = shmem_getpage(inode, index, &page, SGP_FALLOC,
  1890. NULL);
  1891. if (error) {
  1892. /* Remove the !PageUptodate pages we added */
  1893. shmem_undo_range(inode,
  1894. (loff_t)start << PAGE_CACHE_SHIFT,
  1895. (loff_t)index << PAGE_CACHE_SHIFT, true);
  1896. goto undone;
  1897. }
  1898. /*
  1899. * Inform shmem_writepage() how far we have reached.
  1900. * No need for lock or barrier: we have the page lock.
  1901. */
  1902. shmem_falloc.next++;
  1903. if (!PageUptodate(page))
  1904. shmem_falloc.nr_falloced++;
  1905. /*
  1906. * If !PageUptodate, leave it that way so that freeable pages
  1907. * can be recognized if we need to rollback on error later.
  1908. * But set_page_dirty so that memory pressure will swap rather
  1909. * than free the pages we are allocating (and SGP_CACHE pages
  1910. * might still be clean: we now need to mark those dirty too).
  1911. */
  1912. set_page_dirty(page);
  1913. unlock_page(page);
  1914. page_cache_release(page);
  1915. cond_resched();
  1916. }
  1917. if (!(mode & FALLOC_FL_KEEP_SIZE) && offset + len > inode->i_size)
  1918. i_size_write(inode, offset + len);
  1919. inode->i_ctime = CURRENT_TIME;
  1920. undone:
  1921. spin_lock(&inode->i_lock);
  1922. inode->i_private = NULL;
  1923. spin_unlock(&inode->i_lock);
  1924. out:
  1925. mutex_unlock(&inode->i_mutex);
  1926. return error;
  1927. }
  1928. static int shmem_statfs(struct dentry *dentry, struct kstatfs *buf)
  1929. {
  1930. struct shmem_sb_info *sbinfo = SHMEM_SB(dentry->d_sb);
  1931. buf->f_type = TMPFS_MAGIC;
  1932. buf->f_bsize = PAGE_CACHE_SIZE;
  1933. buf->f_namelen = NAME_MAX;
  1934. if (sbinfo->max_blocks) {
  1935. buf->f_blocks = sbinfo->max_blocks;
  1936. buf->f_bavail =
  1937. buf->f_bfree = sbinfo->max_blocks -
  1938. percpu_counter_sum(&sbinfo->used_blocks);
  1939. }
  1940. if (sbinfo->max_inodes) {
  1941. buf->f_files = sbinfo->max_inodes;
  1942. buf->f_ffree = sbinfo->free_inodes;
  1943. }
  1944. /* else leave those fields 0 like simple_statfs */
  1945. return 0;
  1946. }
  1947. /*
  1948. * File creation. Allocate an inode, and we're done..
  1949. */
  1950. static int
  1951. shmem_mknod(struct inode *dir, struct dentry *dentry, umode_t mode, dev_t dev)
  1952. {
  1953. struct inode *inode;
  1954. int error = -ENOSPC;
  1955. inode = shmem_get_inode(dir->i_sb, dir, mode, dev, VM_NORESERVE);
  1956. if (inode) {
  1957. error = simple_acl_create(dir, inode);
  1958. if (error)
  1959. goto out_iput;
  1960. error = security_inode_init_security(inode, dir,
  1961. &dentry->d_name,
  1962. shmem_initxattrs, NULL);
  1963. if (error && error != -EOPNOTSUPP)
  1964. goto out_iput;
  1965. error = 0;
  1966. dir->i_size += BOGO_DIRENT_SIZE;
  1967. dir->i_ctime = dir->i_mtime = CURRENT_TIME;
  1968. d_instantiate(dentry, inode);
  1969. dget(dentry); /* Extra count - pin the dentry in core */
  1970. }
  1971. return error;
  1972. out_iput:
  1973. iput(inode);
  1974. return error;
  1975. }
  1976. static int
  1977. shmem_tmpfile(struct inode *dir, struct dentry *dentry, umode_t mode)
  1978. {
  1979. struct inode *inode;
  1980. int error = -ENOSPC;
  1981. inode = shmem_get_inode(dir->i_sb, dir, mode, 0, VM_NORESERVE);
  1982. if (inode) {
  1983. error = security_inode_init_security(inode, dir,
  1984. NULL,
  1985. shmem_initxattrs, NULL);
  1986. if (error && error != -EOPNOTSUPP)
  1987. goto out_iput;
  1988. error = simple_acl_create(dir, inode);
  1989. if (error)
  1990. goto out_iput;
  1991. d_tmpfile(dentry, inode);
  1992. }
  1993. return error;
  1994. out_iput:
  1995. iput(inode);
  1996. return error;
  1997. }
  1998. static int shmem_mkdir(struct inode *dir, struct dentry *dentry, umode_t mode)
  1999. {
  2000. int error;
  2001. if ((error = shmem_mknod(dir, dentry, mode | S_IFDIR, 0)))
  2002. return error;
  2003. inc_nlink(dir);
  2004. return 0;
  2005. }
  2006. static int shmem_create(struct inode *dir, struct dentry *dentry, umode_t mode,
  2007. bool excl)
  2008. {
  2009. return shmem_mknod(dir, dentry, mode | S_IFREG, 0);
  2010. }
  2011. /*
  2012. * Link a file..
  2013. */
  2014. static int shmem_link(struct dentry *old_dentry, struct inode *dir, struct dentry *dentry)
  2015. {
  2016. struct inode *inode = old_dentry->d_inode;
  2017. int ret;
  2018. /*
  2019. * No ordinary (disk based) filesystem counts links as inodes;
  2020. * but each new link needs a new dentry, pinning lowmem, and
  2021. * tmpfs dentries cannot be pruned until they are unlinked.
  2022. */
  2023. ret = shmem_reserve_inode(inode->i_sb);
  2024. if (ret)
  2025. goto out;
  2026. dir->i_size += BOGO_DIRENT_SIZE;
  2027. inode->i_ctime = dir->i_ctime = dir->i_mtime = CURRENT_TIME;
  2028. inc_nlink(inode);
  2029. ihold(inode); /* New dentry reference */
  2030. dget(dentry); /* Extra pinning count for the created dentry */
  2031. d_instantiate(dentry, inode);
  2032. out:
  2033. return ret;
  2034. }
  2035. static int shmem_unlink(struct inode *dir, struct dentry *dentry)
  2036. {
  2037. struct inode *inode = dentry->d_inode;
  2038. if (inode->i_nlink > 1 && !S_ISDIR(inode->i_mode))
  2039. shmem_free_inode(inode->i_sb);
  2040. dir->i_size -= BOGO_DIRENT_SIZE;
  2041. inode->i_ctime = dir->i_ctime = dir->i_mtime = CURRENT_TIME;
  2042. drop_nlink(inode);
  2043. dput(dentry); /* Undo the count from "create" - this does all the work */
  2044. return 0;
  2045. }
  2046. static int shmem_rmdir(struct inode *dir, struct dentry *dentry)
  2047. {
  2048. if (!simple_empty(dentry))
  2049. return -ENOTEMPTY;
  2050. drop_nlink(dentry->d_inode);
  2051. drop_nlink(dir);
  2052. return shmem_unlink(dir, dentry);
  2053. }
  2054. static int shmem_exchange(struct inode *old_dir, struct dentry *old_dentry, struct inode *new_dir, struct dentry *new_dentry)
  2055. {
  2056. bool old_is_dir = d_is_dir(old_dentry);
  2057. bool new_is_dir = d_is_dir(new_dentry);
  2058. if (old_dir != new_dir && old_is_dir != new_is_dir) {
  2059. if (old_is_dir) {
  2060. drop_nlink(old_dir);
  2061. inc_nlink(new_dir);
  2062. } else {
  2063. drop_nlink(new_dir);
  2064. inc_nlink(old_dir);
  2065. }
  2066. }
  2067. old_dir->i_ctime = old_dir->i_mtime =
  2068. new_dir->i_ctime = new_dir->i_mtime =
  2069. old_dentry->d_inode->i_ctime =
  2070. new_dentry->d_inode->i_ctime = CURRENT_TIME;
  2071. return 0;
  2072. }
  2073. static int shmem_whiteout(struct inode *old_dir, struct dentry *old_dentry)
  2074. {
  2075. struct dentry *whiteout;
  2076. int error;
  2077. whiteout = d_alloc(old_dentry->d_parent, &old_dentry->d_name);
  2078. if (!whiteout)
  2079. return -ENOMEM;
  2080. error = shmem_mknod(old_dir, whiteout,
  2081. S_IFCHR | WHITEOUT_MODE, WHITEOUT_DEV);
  2082. dput(whiteout);
  2083. if (error)
  2084. return error;
  2085. /*
  2086. * Cheat and hash the whiteout while the old dentry is still in
  2087. * place, instead of playing games with FS_RENAME_DOES_D_MOVE.
  2088. *
  2089. * d_lookup() will consistently find one of them at this point,
  2090. * not sure which one, but that isn't even important.
  2091. */
  2092. d_rehash(whiteout);
  2093. return 0;
  2094. }
  2095. /*
  2096. * The VFS layer already does all the dentry stuff for rename,
  2097. * we just have to decrement the usage count for the target if
  2098. * it exists so that the VFS layer correctly free's it when it
  2099. * gets overwritten.
  2100. */
  2101. static int shmem_rename2(struct inode *old_dir, struct dentry *old_dentry, struct inode *new_dir, struct dentry *new_dentry, unsigned int flags)
  2102. {
  2103. struct inode *inode = old_dentry->d_inode;
  2104. int they_are_dirs = S_ISDIR(inode->i_mode);
  2105. if (flags & ~(RENAME_NOREPLACE | RENAME_EXCHANGE | RENAME_WHITEOUT))
  2106. return -EINVAL;
  2107. if (flags & RENAME_EXCHANGE)
  2108. return shmem_exchange(old_dir, old_dentry, new_dir, new_dentry);
  2109. if (!simple_empty(new_dentry))
  2110. return -ENOTEMPTY;
  2111. if (flags & RENAME_WHITEOUT) {
  2112. int error;
  2113. error = shmem_whiteout(old_dir, old_dentry);
  2114. if (error)
  2115. return error;
  2116. }
  2117. if (new_dentry->d_inode) {
  2118. (void) shmem_unlink(new_dir, new_dentry);
  2119. if (they_are_dirs) {
  2120. drop_nlink(new_dentry->d_inode);
  2121. drop_nlink(old_dir);
  2122. }
  2123. } else if (they_are_dirs) {
  2124. drop_nlink(old_dir);
  2125. inc_nlink(new_dir);
  2126. }
  2127. old_dir->i_size -= BOGO_DIRENT_SIZE;
  2128. new_dir->i_size += BOGO_DIRENT_SIZE;
  2129. old_dir->i_ctime = old_dir->i_mtime =
  2130. new_dir->i_ctime = new_dir->i_mtime =
  2131. inode->i_ctime = CURRENT_TIME;
  2132. return 0;
  2133. }
  2134. static int shmem_symlink(struct inode *dir, struct dentry *dentry, const char *symname)
  2135. {
  2136. int error;
  2137. int len;
  2138. struct inode *inode;
  2139. struct page *page;
  2140. char *kaddr;
  2141. struct shmem_inode_info *info;
  2142. len = strlen(symname) + 1;
  2143. if (len > PAGE_CACHE_SIZE)
  2144. return -ENAMETOOLONG;
  2145. inode = shmem_get_inode(dir->i_sb, dir, S_IFLNK|S_IRWXUGO, 0, VM_NORESERVE);
  2146. if (!inode)
  2147. return -ENOSPC;
  2148. error = security_inode_init_security(inode, dir, &dentry->d_name,
  2149. shmem_initxattrs, NULL);
  2150. if (error) {
  2151. if (error != -EOPNOTSUPP) {
  2152. iput(inode);
  2153. return error;
  2154. }
  2155. error = 0;
  2156. }
  2157. info = SHMEM_I(inode);
  2158. inode->i_size = len-1;
  2159. if (len <= SHORT_SYMLINK_LEN) {
  2160. info->symlink = kmemdup(symname, len, GFP_KERNEL);
  2161. if (!info->symlink) {
  2162. iput(inode);
  2163. return -ENOMEM;
  2164. }
  2165. inode->i_op = &shmem_short_symlink_operations;
  2166. } else {
  2167. error = shmem_getpage(inode, 0, &page, SGP_WRITE, NULL);
  2168. if (error) {
  2169. iput(inode);
  2170. return error;
  2171. }
  2172. inode->i_mapping->a_ops = &shmem_aops;
  2173. inode->i_op = &shmem_symlink_inode_operations;
  2174. kaddr = kmap_atomic(page);
  2175. memcpy(kaddr, symname, len);
  2176. kunmap_atomic(kaddr);
  2177. SetPageUptodate(page);
  2178. set_page_dirty(page);
  2179. unlock_page(page);
  2180. page_cache_release(page);
  2181. }
  2182. dir->i_size += BOGO_DIRENT_SIZE;
  2183. dir->i_ctime = dir->i_mtime = CURRENT_TIME;
  2184. d_instantiate(dentry, inode);
  2185. dget(dentry);
  2186. return 0;
  2187. }
  2188. static void *shmem_follow_short_symlink(struct dentry *dentry, struct nameidata *nd)
  2189. {
  2190. nd_set_link(nd, SHMEM_I(dentry->d_inode)->symlink);
  2191. return NULL;
  2192. }
  2193. static void *shmem_follow_link(struct dentry *dentry, struct nameidata *nd)
  2194. {
  2195. struct page *page = NULL;
  2196. int error = shmem_getpage(dentry->d_inode, 0, &page, SGP_READ, NULL);
  2197. nd_set_link(nd, error ? ERR_PTR(error) : kmap(page));
  2198. if (page)
  2199. unlock_page(page);
  2200. return page;
  2201. }
  2202. static void shmem_put_link(struct dentry *dentry, struct nameidata *nd, void *cookie)
  2203. {
  2204. if (!IS_ERR(nd_get_link(nd))) {
  2205. struct page *page = cookie;
  2206. kunmap(page);
  2207. mark_page_accessed(page);
  2208. page_cache_release(page);
  2209. }
  2210. }
  2211. #ifdef CONFIG_TMPFS_XATTR
  2212. /*
  2213. * Superblocks without xattr inode operations may get some security.* xattr
  2214. * support from the LSM "for free". As soon as we have any other xattrs
  2215. * like ACLs, we also need to implement the security.* handlers at
  2216. * filesystem level, though.
  2217. */
  2218. /*
  2219. * Callback for security_inode_init_security() for acquiring xattrs.
  2220. */
  2221. static int shmem_initxattrs(struct inode *inode,
  2222. const struct xattr *xattr_array,
  2223. void *fs_info)
  2224. {
  2225. struct shmem_inode_info *info = SHMEM_I(inode);
  2226. const struct xattr *xattr;
  2227. struct simple_xattr *new_xattr;
  2228. size_t len;
  2229. for (xattr = xattr_array; xattr->name != NULL; xattr++) {
  2230. new_xattr = simple_xattr_alloc(xattr->value, xattr->value_len);
  2231. if (!new_xattr)
  2232. return -ENOMEM;
  2233. len = strlen(xattr->name) + 1;
  2234. new_xattr->name = kmalloc(XATTR_SECURITY_PREFIX_LEN + len,
  2235. GFP_KERNEL);
  2236. if (!new_xattr->name) {
  2237. kfree(new_xattr);
  2238. return -ENOMEM;
  2239. }
  2240. memcpy(new_xattr->name, XATTR_SECURITY_PREFIX,
  2241. XATTR_SECURITY_PREFIX_LEN);
  2242. memcpy(new_xattr->name + XATTR_SECURITY_PREFIX_LEN,
  2243. xattr->name, len);
  2244. simple_xattr_list_add(&info->xattrs, new_xattr);
  2245. }
  2246. return 0;
  2247. }
  2248. static const struct xattr_handler *shmem_xattr_handlers[] = {
  2249. #ifdef CONFIG_TMPFS_POSIX_ACL
  2250. &posix_acl_access_xattr_handler,
  2251. &posix_acl_default_xattr_handler,
  2252. #endif
  2253. NULL
  2254. };
  2255. static int shmem_xattr_validate(const char *name)
  2256. {
  2257. struct { const char *prefix; size_t len; } arr[] = {
  2258. { XATTR_SECURITY_PREFIX, XATTR_SECURITY_PREFIX_LEN },
  2259. { XATTR_TRUSTED_PREFIX, XATTR_TRUSTED_PREFIX_LEN }
  2260. };
  2261. int i;
  2262. for (i = 0; i < ARRAY_SIZE(arr); i++) {
  2263. size_t preflen = arr[i].len;
  2264. if (strncmp(name, arr[i].prefix, preflen) == 0) {
  2265. if (!name[preflen])
  2266. return -EINVAL;
  2267. return 0;
  2268. }
  2269. }
  2270. return -EOPNOTSUPP;
  2271. }
  2272. static ssize_t shmem_getxattr(struct dentry *dentry, const char *name,
  2273. void *buffer, size_t size)
  2274. {
  2275. struct shmem_inode_info *info = SHMEM_I(dentry->d_inode);
  2276. int err;
  2277. /*
  2278. * If this is a request for a synthetic attribute in the system.*
  2279. * namespace use the generic infrastructure to resolve a handler
  2280. * for it via sb->s_xattr.
  2281. */
  2282. if (!strncmp(name, XATTR_SYSTEM_PREFIX, XATTR_SYSTEM_PREFIX_LEN))
  2283. return generic_getxattr(dentry, name, buffer, size);
  2284. err = shmem_xattr_validate(name);
  2285. if (err)
  2286. return err;
  2287. return simple_xattr_get(&info->xattrs, name, buffer, size);
  2288. }
  2289. static int shmem_setxattr(struct dentry *dentry, const char *name,
  2290. const void *value, size_t size, int flags)
  2291. {
  2292. struct shmem_inode_info *info = SHMEM_I(dentry->d_inode);
  2293. int err;
  2294. /*
  2295. * If this is a request for a synthetic attribute in the system.*
  2296. * namespace use the generic infrastructure to resolve a handler
  2297. * for it via sb->s_xattr.
  2298. */
  2299. if (!strncmp(name, XATTR_SYSTEM_PREFIX, XATTR_SYSTEM_PREFIX_LEN))
  2300. return generic_setxattr(dentry, name, value, size, flags);
  2301. err = shmem_xattr_validate(name);
  2302. if (err)
  2303. return err;
  2304. return simple_xattr_set(&info->xattrs, name, value, size, flags);
  2305. }
  2306. static int shmem_removexattr(struct dentry *dentry, const char *name)
  2307. {
  2308. struct shmem_inode_info *info = SHMEM_I(dentry->d_inode);
  2309. int err;
  2310. /*
  2311. * If this is a request for a synthetic attribute in the system.*
  2312. * namespace use the generic infrastructure to resolve a handler
  2313. * for it via sb->s_xattr.
  2314. */
  2315. if (!strncmp(name, XATTR_SYSTEM_PREFIX, XATTR_SYSTEM_PREFIX_LEN))
  2316. return generic_removexattr(dentry, name);
  2317. err = shmem_xattr_validate(name);
  2318. if (err)
  2319. return err;
  2320. return simple_xattr_remove(&info->xattrs, name);
  2321. }
  2322. static ssize_t shmem_listxattr(struct dentry *dentry, char *buffer, size_t size)
  2323. {
  2324. struct shmem_inode_info *info = SHMEM_I(dentry->d_inode);
  2325. return simple_xattr_list(&info->xattrs, buffer, size);
  2326. }
  2327. #endif /* CONFIG_TMPFS_XATTR */
  2328. static const struct inode_operations shmem_short_symlink_operations = {
  2329. .readlink = generic_readlink,
  2330. .follow_link = shmem_follow_short_symlink,
  2331. #ifdef CONFIG_TMPFS_XATTR
  2332. .setxattr = shmem_setxattr,
  2333. .getxattr = shmem_getxattr,
  2334. .listxattr = shmem_listxattr,
  2335. .removexattr = shmem_removexattr,
  2336. #endif
  2337. };
  2338. static const struct inode_operations shmem_symlink_inode_operations = {
  2339. .readlink = generic_readlink,
  2340. .follow_link = shmem_follow_link,
  2341. .put_link = shmem_put_link,
  2342. #ifdef CONFIG_TMPFS_XATTR
  2343. .setxattr = shmem_setxattr,
  2344. .getxattr = shmem_getxattr,
  2345. .listxattr = shmem_listxattr,
  2346. .removexattr = shmem_removexattr,
  2347. #endif
  2348. };
  2349. static struct dentry *shmem_get_parent(struct dentry *child)
  2350. {
  2351. return ERR_PTR(-ESTALE);
  2352. }
  2353. static int shmem_match(struct inode *ino, void *vfh)
  2354. {
  2355. __u32 *fh = vfh;
  2356. __u64 inum = fh[2];
  2357. inum = (inum << 32) | fh[1];
  2358. return ino->i_ino == inum && fh[0] == ino->i_generation;
  2359. }
  2360. static struct dentry *shmem_fh_to_dentry(struct super_block *sb,
  2361. struct fid *fid, int fh_len, int fh_type)
  2362. {
  2363. struct inode *inode;
  2364. struct dentry *dentry = NULL;
  2365. u64 inum;
  2366. if (fh_len < 3)
  2367. return NULL;
  2368. inum = fid->raw[2];
  2369. inum = (inum << 32) | fid->raw[1];
  2370. inode = ilookup5(sb, (unsigned long)(inum + fid->raw[0]),
  2371. shmem_match, fid->raw);
  2372. if (inode) {
  2373. dentry = d_find_alias(inode);
  2374. iput(inode);
  2375. }
  2376. return dentry;
  2377. }
  2378. static int shmem_encode_fh(struct inode *inode, __u32 *fh, int *len,
  2379. struct inode *parent)
  2380. {
  2381. if (*len < 3) {
  2382. *len = 3;
  2383. return FILEID_INVALID;
  2384. }
  2385. if (inode_unhashed(inode)) {
  2386. /* Unfortunately insert_inode_hash is not idempotent,
  2387. * so as we hash inodes here rather than at creation
  2388. * time, we need a lock to ensure we only try
  2389. * to do it once
  2390. */
  2391. static DEFINE_SPINLOCK(lock);
  2392. spin_lock(&lock);
  2393. if (inode_unhashed(inode))
  2394. __insert_inode_hash(inode,
  2395. inode->i_ino + inode->i_generation);
  2396. spin_unlock(&lock);
  2397. }
  2398. fh[0] = inode->i_generation;
  2399. fh[1] = inode->i_ino;
  2400. fh[2] = ((__u64)inode->i_ino) >> 32;
  2401. *len = 3;
  2402. return 1;
  2403. }
  2404. static const struct export_operations shmem_export_ops = {
  2405. .get_parent = shmem_get_parent,
  2406. .encode_fh = shmem_encode_fh,
  2407. .fh_to_dentry = shmem_fh_to_dentry,
  2408. };
  2409. static int shmem_parse_options(char *options, struct shmem_sb_info *sbinfo,
  2410. bool remount)
  2411. {
  2412. char *this_char, *value, *rest;
  2413. struct mempolicy *mpol = NULL;
  2414. uid_t uid;
  2415. gid_t gid;
  2416. while (options != NULL) {
  2417. this_char = options;
  2418. for (;;) {
  2419. /*
  2420. * NUL-terminate this option: unfortunately,
  2421. * mount options form a comma-separated list,
  2422. * but mpol's nodelist may also contain commas.
  2423. */
  2424. options = strchr(options, ',');
  2425. if (options == NULL)
  2426. break;
  2427. options++;
  2428. if (!isdigit(*options)) {
  2429. options[-1] = '\0';
  2430. break;
  2431. }
  2432. }
  2433. if (!*this_char)
  2434. continue;
  2435. if ((value = strchr(this_char,'=')) != NULL) {
  2436. *value++ = 0;
  2437. } else {
  2438. printk(KERN_ERR
  2439. "tmpfs: No value for mount option '%s'\n",
  2440. this_char);
  2441. goto error;
  2442. }
  2443. if (!strcmp(this_char,"size")) {
  2444. unsigned long long size;
  2445. size = memparse(value,&rest);
  2446. if (*rest == '%') {
  2447. size <<= PAGE_SHIFT;
  2448. size *= totalram_pages;
  2449. do_div(size, 100);
  2450. rest++;
  2451. }
  2452. if (*rest)
  2453. goto bad_val;
  2454. sbinfo->max_blocks =
  2455. DIV_ROUND_UP(size, PAGE_CACHE_SIZE);
  2456. } else if (!strcmp(this_char,"nr_blocks")) {
  2457. sbinfo->max_blocks = memparse(value, &rest);
  2458. if (*rest)
  2459. goto bad_val;
  2460. } else if (!strcmp(this_char,"nr_inodes")) {
  2461. sbinfo->max_inodes = memparse(value, &rest);
  2462. if (*rest)
  2463. goto bad_val;
  2464. } else if (!strcmp(this_char,"mode")) {
  2465. if (remount)
  2466. continue;
  2467. sbinfo->mode = simple_strtoul(value, &rest, 8) & 07777;
  2468. if (*rest)
  2469. goto bad_val;
  2470. } else if (!strcmp(this_char,"uid")) {
  2471. if (remount)
  2472. continue;
  2473. uid = simple_strtoul(value, &rest, 0);
  2474. if (*rest)
  2475. goto bad_val;
  2476. sbinfo->uid = make_kuid(current_user_ns(), uid);
  2477. if (!uid_valid(sbinfo->uid))
  2478. goto bad_val;
  2479. } else if (!strcmp(this_char,"gid")) {
  2480. if (remount)
  2481. continue;
  2482. gid = simple_strtoul(value, &rest, 0);
  2483. if (*rest)
  2484. goto bad_val;
  2485. sbinfo->gid = make_kgid(current_user_ns(), gid);
  2486. if (!gid_valid(sbinfo->gid))
  2487. goto bad_val;
  2488. } else if (!strcmp(this_char,"mpol")) {
  2489. mpol_put(mpol);
  2490. mpol = NULL;
  2491. if (mpol_parse_str(value, &mpol))
  2492. goto bad_val;
  2493. } else {
  2494. printk(KERN_ERR "tmpfs: Bad mount option %s\n",
  2495. this_char);
  2496. goto error;
  2497. }
  2498. }
  2499. sbinfo->mpol = mpol;
  2500. return 0;
  2501. bad_val:
  2502. printk(KERN_ERR "tmpfs: Bad value '%s' for mount option '%s'\n",
  2503. value, this_char);
  2504. error:
  2505. mpol_put(mpol);
  2506. return 1;
  2507. }
  2508. static int shmem_remount_fs(struct super_block *sb, int *flags, char *data)
  2509. {
  2510. struct shmem_sb_info *sbinfo = SHMEM_SB(sb);
  2511. struct shmem_sb_info config = *sbinfo;
  2512. unsigned long inodes;
  2513. int error = -EINVAL;
  2514. config.mpol = NULL;
  2515. if (shmem_parse_options(data, &config, true))
  2516. return error;
  2517. spin_lock(&sbinfo->stat_lock);
  2518. inodes = sbinfo->max_inodes - sbinfo->free_inodes;
  2519. if (percpu_counter_compare(&sbinfo->used_blocks, config.max_blocks) > 0)
  2520. goto out;
  2521. if (config.max_inodes < inodes)
  2522. goto out;
  2523. /*
  2524. * Those tests disallow limited->unlimited while any are in use;
  2525. * but we must separately disallow unlimited->limited, because
  2526. * in that case we have no record of how much is already in use.
  2527. */
  2528. if (config.max_blocks && !sbinfo->max_blocks)
  2529. goto out;
  2530. if (config.max_inodes && !sbinfo->max_inodes)
  2531. goto out;
  2532. error = 0;
  2533. sbinfo->max_blocks = config.max_blocks;
  2534. sbinfo->max_inodes = config.max_inodes;
  2535. sbinfo->free_inodes = config.max_inodes - inodes;
  2536. /*
  2537. * Preserve previous mempolicy unless mpol remount option was specified.
  2538. */
  2539. if (config.mpol) {
  2540. mpol_put(sbinfo->mpol);
  2541. sbinfo->mpol = config.mpol; /* transfers initial ref */
  2542. }
  2543. out:
  2544. spin_unlock(&sbinfo->stat_lock);
  2545. return error;
  2546. }
  2547. static int shmem_show_options(struct seq_file *seq, struct dentry *root)
  2548. {
  2549. struct shmem_sb_info *sbinfo = SHMEM_SB(root->d_sb);
  2550. if (sbinfo->max_blocks != shmem_default_max_blocks())
  2551. seq_printf(seq, ",size=%luk",
  2552. sbinfo->max_blocks << (PAGE_CACHE_SHIFT - 10));
  2553. if (sbinfo->max_inodes != shmem_default_max_inodes())
  2554. seq_printf(seq, ",nr_inodes=%lu", sbinfo->max_inodes);
  2555. if (sbinfo->mode != (S_IRWXUGO | S_ISVTX))
  2556. seq_printf(seq, ",mode=%03ho", sbinfo->mode);
  2557. if (!uid_eq(sbinfo->uid, GLOBAL_ROOT_UID))
  2558. seq_printf(seq, ",uid=%u",
  2559. from_kuid_munged(&init_user_ns, sbinfo->uid));
  2560. if (!gid_eq(sbinfo->gid, GLOBAL_ROOT_GID))
  2561. seq_printf(seq, ",gid=%u",
  2562. from_kgid_munged(&init_user_ns, sbinfo->gid));
  2563. shmem_show_mpol(seq, sbinfo->mpol);
  2564. return 0;
  2565. }
  2566. #define MFD_NAME_PREFIX "memfd:"
  2567. #define MFD_NAME_PREFIX_LEN (sizeof(MFD_NAME_PREFIX) - 1)
  2568. #define MFD_NAME_MAX_LEN (NAME_MAX - MFD_NAME_PREFIX_LEN)
  2569. #define MFD_ALL_FLAGS (MFD_CLOEXEC | MFD_ALLOW_SEALING)
  2570. SYSCALL_DEFINE2(memfd_create,
  2571. const char __user *, uname,
  2572. unsigned int, flags)
  2573. {
  2574. struct shmem_inode_info *info;
  2575. struct file *file;
  2576. int fd, error;
  2577. char *name;
  2578. long len;
  2579. if (flags & ~(unsigned int)MFD_ALL_FLAGS)
  2580. return -EINVAL;
  2581. /* length includes terminating zero */
  2582. len = strnlen_user(uname, MFD_NAME_MAX_LEN + 1);
  2583. if (len <= 0)
  2584. return -EFAULT;
  2585. if (len > MFD_NAME_MAX_LEN + 1)
  2586. return -EINVAL;
  2587. name = kmalloc(len + MFD_NAME_PREFIX_LEN, GFP_TEMPORARY);
  2588. if (!name)
  2589. return -ENOMEM;
  2590. strcpy(name, MFD_NAME_PREFIX);
  2591. if (copy_from_user(&name[MFD_NAME_PREFIX_LEN], uname, len)) {
  2592. error = -EFAULT;
  2593. goto err_name;
  2594. }
  2595. /* terminating-zero may have changed after strnlen_user() returned */
  2596. if (name[len + MFD_NAME_PREFIX_LEN - 1]) {
  2597. error = -EFAULT;
  2598. goto err_name;
  2599. }
  2600. fd = get_unused_fd_flags((flags & MFD_CLOEXEC) ? O_CLOEXEC : 0);
  2601. if (fd < 0) {
  2602. error = fd;
  2603. goto err_name;
  2604. }
  2605. file = shmem_file_setup(name, 0, VM_NORESERVE);
  2606. if (IS_ERR(file)) {
  2607. error = PTR_ERR(file);
  2608. goto err_fd;
  2609. }
  2610. info = SHMEM_I(file_inode(file));
  2611. file->f_mode |= FMODE_LSEEK | FMODE_PREAD | FMODE_PWRITE;
  2612. file->f_flags |= O_RDWR | O_LARGEFILE;
  2613. if (flags & MFD_ALLOW_SEALING)
  2614. info->seals &= ~F_SEAL_SEAL;
  2615. fd_install(fd, file);
  2616. kfree(name);
  2617. return fd;
  2618. err_fd:
  2619. put_unused_fd(fd);
  2620. err_name:
  2621. kfree(name);
  2622. return error;
  2623. }
  2624. #endif /* CONFIG_TMPFS */
  2625. static void shmem_put_super(struct super_block *sb)
  2626. {
  2627. struct shmem_sb_info *sbinfo = SHMEM_SB(sb);
  2628. percpu_counter_destroy(&sbinfo->used_blocks);
  2629. mpol_put(sbinfo->mpol);
  2630. kfree(sbinfo);
  2631. sb->s_fs_info = NULL;
  2632. }
  2633. int shmem_fill_super(struct super_block *sb, void *data, int silent)
  2634. {
  2635. struct inode *inode;
  2636. struct shmem_sb_info *sbinfo;
  2637. int err = -ENOMEM;
  2638. /* Round up to L1_CACHE_BYTES to resist false sharing */
  2639. sbinfo = kzalloc(max((int)sizeof(struct shmem_sb_info),
  2640. L1_CACHE_BYTES), GFP_KERNEL);
  2641. if (!sbinfo)
  2642. return -ENOMEM;
  2643. sbinfo->mode = S_IRWXUGO | S_ISVTX;
  2644. sbinfo->uid = current_fsuid();
  2645. sbinfo->gid = current_fsgid();
  2646. sb->s_fs_info = sbinfo;
  2647. #ifdef CONFIG_TMPFS
  2648. /*
  2649. * Per default we only allow half of the physical ram per
  2650. * tmpfs instance, limiting inodes to one per page of lowmem;
  2651. * but the internal instance is left unlimited.
  2652. */
  2653. if (!(sb->s_flags & MS_KERNMOUNT)) {
  2654. sbinfo->max_blocks = shmem_default_max_blocks();
  2655. sbinfo->max_inodes = shmem_default_max_inodes();
  2656. if (shmem_parse_options(data, sbinfo, false)) {
  2657. err = -EINVAL;
  2658. goto failed;
  2659. }
  2660. } else {
  2661. sb->s_flags |= MS_NOUSER;
  2662. }
  2663. sb->s_export_op = &shmem_export_ops;
  2664. sb->s_flags |= MS_NOSEC;
  2665. #else
  2666. sb->s_flags |= MS_NOUSER;
  2667. #endif
  2668. spin_lock_init(&sbinfo->stat_lock);
  2669. if (percpu_counter_init(&sbinfo->used_blocks, 0, GFP_KERNEL))
  2670. goto failed;
  2671. sbinfo->free_inodes = sbinfo->max_inodes;
  2672. sb->s_maxbytes = MAX_LFS_FILESIZE;
  2673. sb->s_blocksize = PAGE_CACHE_SIZE;
  2674. sb->s_blocksize_bits = PAGE_CACHE_SHIFT;
  2675. sb->s_magic = TMPFS_MAGIC;
  2676. sb->s_op = &shmem_ops;
  2677. sb->s_time_gran = 1;
  2678. #ifdef CONFIG_TMPFS_XATTR
  2679. sb->s_xattr = shmem_xattr_handlers;
  2680. #endif
  2681. #ifdef CONFIG_TMPFS_POSIX_ACL
  2682. sb->s_flags |= MS_POSIXACL;
  2683. #endif
  2684. inode = shmem_get_inode(sb, NULL, S_IFDIR | sbinfo->mode, 0, VM_NORESERVE);
  2685. if (!inode)
  2686. goto failed;
  2687. inode->i_uid = sbinfo->uid;
  2688. inode->i_gid = sbinfo->gid;
  2689. sb->s_root = d_make_root(inode);
  2690. if (!sb->s_root)
  2691. goto failed;
  2692. return 0;
  2693. failed:
  2694. shmem_put_super(sb);
  2695. return err;
  2696. }
  2697. static struct kmem_cache *shmem_inode_cachep;
  2698. static struct inode *shmem_alloc_inode(struct super_block *sb)
  2699. {
  2700. struct shmem_inode_info *info;
  2701. info = kmem_cache_alloc(shmem_inode_cachep, GFP_KERNEL);
  2702. if (!info)
  2703. return NULL;
  2704. return &info->vfs_inode;
  2705. }
  2706. static void shmem_destroy_callback(struct rcu_head *head)
  2707. {
  2708. struct inode *inode = container_of(head, struct inode, i_rcu);
  2709. kmem_cache_free(shmem_inode_cachep, SHMEM_I(inode));
  2710. }
  2711. static void shmem_destroy_inode(struct inode *inode)
  2712. {
  2713. if (S_ISREG(inode->i_mode))
  2714. mpol_free_shared_policy(&SHMEM_I(inode)->policy);
  2715. call_rcu(&inode->i_rcu, shmem_destroy_callback);
  2716. }
  2717. static void shmem_init_inode(void *foo)
  2718. {
  2719. struct shmem_inode_info *info = foo;
  2720. inode_init_once(&info->vfs_inode);
  2721. }
  2722. static int shmem_init_inodecache(void)
  2723. {
  2724. shmem_inode_cachep = kmem_cache_create("shmem_inode_cache",
  2725. sizeof(struct shmem_inode_info),
  2726. 0, SLAB_PANIC, shmem_init_inode);
  2727. return 0;
  2728. }
  2729. static void shmem_destroy_inodecache(void)
  2730. {
  2731. kmem_cache_destroy(shmem_inode_cachep);
  2732. }
  2733. static const struct address_space_operations shmem_aops = {
  2734. .writepage = shmem_writepage,
  2735. .set_page_dirty = __set_page_dirty_no_writeback,
  2736. #ifdef CONFIG_TMPFS
  2737. .write_begin = shmem_write_begin,
  2738. .write_end = shmem_write_end,
  2739. #endif
  2740. #ifdef CONFIG_MIGRATION
  2741. .migratepage = migrate_page,
  2742. #endif
  2743. .error_remove_page = generic_error_remove_page,
  2744. };
  2745. static const struct file_operations shmem_file_operations = {
  2746. .mmap = shmem_mmap,
  2747. #ifdef CONFIG_TMPFS
  2748. .llseek = shmem_file_llseek,
  2749. .read = new_sync_read,
  2750. .write = new_sync_write,
  2751. .read_iter = shmem_file_read_iter,
  2752. .write_iter = generic_file_write_iter,
  2753. .fsync = noop_fsync,
  2754. .splice_read = shmem_file_splice_read,
  2755. .splice_write = iter_file_splice_write,
  2756. .fallocate = shmem_fallocate,
  2757. #endif
  2758. };
  2759. static const struct inode_operations shmem_inode_operations = {
  2760. .setattr = shmem_setattr,
  2761. #ifdef CONFIG_TMPFS_XATTR
  2762. .setxattr = shmem_setxattr,
  2763. .getxattr = shmem_getxattr,
  2764. .listxattr = shmem_listxattr,
  2765. .removexattr = shmem_removexattr,
  2766. .set_acl = simple_set_acl,
  2767. #endif
  2768. };
  2769. static const struct inode_operations shmem_dir_inode_operations = {
  2770. #ifdef CONFIG_TMPFS
  2771. .create = shmem_create,
  2772. .lookup = simple_lookup,
  2773. .link = shmem_link,
  2774. .unlink = shmem_unlink,
  2775. .symlink = shmem_symlink,
  2776. .mkdir = shmem_mkdir,
  2777. .rmdir = shmem_rmdir,
  2778. .mknod = shmem_mknod,
  2779. .rename2 = shmem_rename2,
  2780. .tmpfile = shmem_tmpfile,
  2781. #endif
  2782. #ifdef CONFIG_TMPFS_XATTR
  2783. .setxattr = shmem_setxattr,
  2784. .getxattr = shmem_getxattr,
  2785. .listxattr = shmem_listxattr,
  2786. .removexattr = shmem_removexattr,
  2787. #endif
  2788. #ifdef CONFIG_TMPFS_POSIX_ACL
  2789. .setattr = shmem_setattr,
  2790. .set_acl = simple_set_acl,
  2791. #endif
  2792. };
  2793. static const struct inode_operations shmem_special_inode_operations = {
  2794. #ifdef CONFIG_TMPFS_XATTR
  2795. .setxattr = shmem_setxattr,
  2796. .getxattr = shmem_getxattr,
  2797. .listxattr = shmem_listxattr,
  2798. .removexattr = shmem_removexattr,
  2799. #endif
  2800. #ifdef CONFIG_TMPFS_POSIX_ACL
  2801. .setattr = shmem_setattr,
  2802. .set_acl = simple_set_acl,
  2803. #endif
  2804. };
  2805. static const struct super_operations shmem_ops = {
  2806. .alloc_inode = shmem_alloc_inode,
  2807. .destroy_inode = shmem_destroy_inode,
  2808. #ifdef CONFIG_TMPFS
  2809. .statfs = shmem_statfs,
  2810. .remount_fs = shmem_remount_fs,
  2811. .show_options = shmem_show_options,
  2812. #endif
  2813. .evict_inode = shmem_evict_inode,
  2814. .drop_inode = generic_delete_inode,
  2815. .put_super = shmem_put_super,
  2816. };
  2817. static const struct vm_operations_struct shmem_vm_ops = {
  2818. .fault = shmem_fault,
  2819. .map_pages = filemap_map_pages,
  2820. #ifdef CONFIG_NUMA
  2821. .set_policy = shmem_set_policy,
  2822. .get_policy = shmem_get_policy,
  2823. #endif
  2824. };
  2825. static struct dentry *shmem_mount(struct file_system_type *fs_type,
  2826. int flags, const char *dev_name, void *data)
  2827. {
  2828. return mount_nodev(fs_type, flags, data, shmem_fill_super);
  2829. }
  2830. static struct file_system_type shmem_fs_type = {
  2831. .owner = THIS_MODULE,
  2832. .name = "tmpfs",
  2833. .mount = shmem_mount,
  2834. .kill_sb = kill_litter_super,
  2835. .fs_flags = FS_USERNS_MOUNT,
  2836. };
  2837. int __init shmem_init(void)
  2838. {
  2839. int error;
  2840. /* If rootfs called this, don't re-init */
  2841. if (shmem_inode_cachep)
  2842. return 0;
  2843. error = shmem_init_inodecache();
  2844. if (error)
  2845. goto out3;
  2846. error = register_filesystem(&shmem_fs_type);
  2847. if (error) {
  2848. printk(KERN_ERR "Could not register tmpfs\n");
  2849. goto out2;
  2850. }
  2851. shm_mnt = kern_mount(&shmem_fs_type);
  2852. if (IS_ERR(shm_mnt)) {
  2853. error = PTR_ERR(shm_mnt);
  2854. printk(KERN_ERR "Could not kern_mount tmpfs\n");
  2855. goto out1;
  2856. }
  2857. return 0;
  2858. out1:
  2859. unregister_filesystem(&shmem_fs_type);
  2860. out2:
  2861. shmem_destroy_inodecache();
  2862. out3:
  2863. shm_mnt = ERR_PTR(error);
  2864. return error;
  2865. }
  2866. #else /* !CONFIG_SHMEM */
  2867. /*
  2868. * tiny-shmem: simple shmemfs and tmpfs using ramfs code
  2869. *
  2870. * This is intended for small system where the benefits of the full
  2871. * shmem code (swap-backed and resource-limited) are outweighed by
  2872. * their complexity. On systems without swap this code should be
  2873. * effectively equivalent, but much lighter weight.
  2874. */
  2875. static struct file_system_type shmem_fs_type = {
  2876. .name = "tmpfs",
  2877. .mount = ramfs_mount,
  2878. .kill_sb = kill_litter_super,
  2879. .fs_flags = FS_USERNS_MOUNT,
  2880. };
  2881. int __init shmem_init(void)
  2882. {
  2883. BUG_ON(register_filesystem(&shmem_fs_type) != 0);
  2884. shm_mnt = kern_mount(&shmem_fs_type);
  2885. BUG_ON(IS_ERR(shm_mnt));
  2886. return 0;
  2887. }
  2888. int shmem_unuse(swp_entry_t swap, struct page *page)
  2889. {
  2890. return 0;
  2891. }
  2892. int shmem_lock(struct file *file, int lock, struct user_struct *user)
  2893. {
  2894. return 0;
  2895. }
  2896. void shmem_unlock_mapping(struct address_space *mapping)
  2897. {
  2898. }
  2899. void shmem_truncate_range(struct inode *inode, loff_t lstart, loff_t lend)
  2900. {
  2901. truncate_inode_pages_range(inode->i_mapping, lstart, lend);
  2902. }
  2903. EXPORT_SYMBOL_GPL(shmem_truncate_range);
  2904. #define shmem_vm_ops generic_file_vm_ops
  2905. #define shmem_file_operations ramfs_file_operations
  2906. #define shmem_get_inode(sb, dir, mode, dev, flags) ramfs_get_inode(sb, dir, mode, dev)
  2907. #define shmem_acct_size(flags, size) 0
  2908. #define shmem_unacct_size(flags, size) do {} while (0)
  2909. #endif /* CONFIG_SHMEM */
  2910. /* common code */
  2911. static struct dentry_operations anon_ops = {
  2912. .d_dname = simple_dname
  2913. };
  2914. static struct file *__shmem_file_setup(const char *name, loff_t size,
  2915. unsigned long flags, unsigned int i_flags)
  2916. {
  2917. struct file *res;
  2918. struct inode *inode;
  2919. struct path path;
  2920. struct super_block *sb;
  2921. struct qstr this;
  2922. if (IS_ERR(shm_mnt))
  2923. return ERR_CAST(shm_mnt);
  2924. if (size < 0 || size > MAX_LFS_FILESIZE)
  2925. return ERR_PTR(-EINVAL);
  2926. if (shmem_acct_size(flags, size))
  2927. return ERR_PTR(-ENOMEM);
  2928. res = ERR_PTR(-ENOMEM);
  2929. this.name = name;
  2930. this.len = strlen(name);
  2931. this.hash = 0; /* will go */
  2932. sb = shm_mnt->mnt_sb;
  2933. path.mnt = mntget(shm_mnt);
  2934. path.dentry = d_alloc_pseudo(sb, &this);
  2935. if (!path.dentry)
  2936. goto put_memory;
  2937. d_set_d_op(path.dentry, &anon_ops);
  2938. res = ERR_PTR(-ENOSPC);
  2939. inode = shmem_get_inode(sb, NULL, S_IFREG | S_IRWXUGO, 0, flags);
  2940. if (!inode)
  2941. goto put_memory;
  2942. inode->i_flags |= i_flags;
  2943. d_instantiate(path.dentry, inode);
  2944. inode->i_size = size;
  2945. clear_nlink(inode); /* It is unlinked */
  2946. res = ERR_PTR(ramfs_nommu_expand_for_mapping(inode, size));
  2947. if (IS_ERR(res))
  2948. goto put_path;
  2949. res = alloc_file(&path, FMODE_WRITE | FMODE_READ,
  2950. &shmem_file_operations);
  2951. if (IS_ERR(res))
  2952. goto put_path;
  2953. return res;
  2954. put_memory:
  2955. shmem_unacct_size(flags, size);
  2956. put_path:
  2957. path_put(&path);
  2958. return res;
  2959. }
  2960. /**
  2961. * shmem_kernel_file_setup - get an unlinked file living in tmpfs which must be
  2962. * kernel internal. There will be NO LSM permission checks against the
  2963. * underlying inode. So users of this interface must do LSM checks at a
  2964. * higher layer. The one user is the big_key implementation. LSM checks
  2965. * are provided at the key level rather than the inode level.
  2966. * @name: name for dentry (to be seen in /proc/<pid>/maps
  2967. * @size: size to be set for the file
  2968. * @flags: VM_NORESERVE suppresses pre-accounting of the entire object size
  2969. */
  2970. struct file *shmem_kernel_file_setup(const char *name, loff_t size, unsigned long flags)
  2971. {
  2972. return __shmem_file_setup(name, size, flags, S_PRIVATE);
  2973. }
  2974. /**
  2975. * shmem_file_setup - get an unlinked file living in tmpfs
  2976. * @name: name for dentry (to be seen in /proc/<pid>/maps
  2977. * @size: size to be set for the file
  2978. * @flags: VM_NORESERVE suppresses pre-accounting of the entire object size
  2979. */
  2980. struct file *shmem_file_setup(const char *name, loff_t size, unsigned long flags)
  2981. {
  2982. return __shmem_file_setup(name, size, flags, 0);
  2983. }
  2984. EXPORT_SYMBOL_GPL(shmem_file_setup);
  2985. /**
  2986. * shmem_zero_setup - setup a shared anonymous mapping
  2987. * @vma: the vma to be mmapped is prepared by do_mmap_pgoff
  2988. */
  2989. int shmem_zero_setup(struct vm_area_struct *vma)
  2990. {
  2991. struct file *file;
  2992. loff_t size = vma->vm_end - vma->vm_start;
  2993. file = shmem_file_setup("dev/zero", size, vma->vm_flags);
  2994. if (IS_ERR(file))
  2995. return PTR_ERR(file);
  2996. if (vma->vm_file)
  2997. fput(vma->vm_file);
  2998. vma->vm_file = file;
  2999. vma->vm_ops = &shmem_vm_ops;
  3000. return 0;
  3001. }
  3002. /**
  3003. * shmem_read_mapping_page_gfp - read into page cache, using specified page allocation flags.
  3004. * @mapping: the page's address_space
  3005. * @index: the page index
  3006. * @gfp: the page allocator flags to use if allocating
  3007. *
  3008. * This behaves as a tmpfs "read_cache_page_gfp(mapping, index, gfp)",
  3009. * with any new page allocations done using the specified allocation flags.
  3010. * But read_cache_page_gfp() uses the ->readpage() method: which does not
  3011. * suit tmpfs, since it may have pages in swapcache, and needs to find those
  3012. * for itself; although drivers/gpu/drm i915 and ttm rely upon this support.
  3013. *
  3014. * i915_gem_object_get_pages_gtt() mixes __GFP_NORETRY | __GFP_NOWARN in
  3015. * with the mapping_gfp_mask(), to avoid OOMing the machine unnecessarily.
  3016. */
  3017. struct page *shmem_read_mapping_page_gfp(struct address_space *mapping,
  3018. pgoff_t index, gfp_t gfp)
  3019. {
  3020. #ifdef CONFIG_SHMEM
  3021. struct inode *inode = mapping->host;
  3022. struct page *page;
  3023. int error;
  3024. BUG_ON(mapping->a_ops != &shmem_aops);
  3025. error = shmem_getpage_gfp(inode, index, &page, SGP_CACHE, gfp, NULL);
  3026. if (error)
  3027. page = ERR_PTR(error);
  3028. else
  3029. unlock_page(page);
  3030. return page;
  3031. #else
  3032. /*
  3033. * The tiny !SHMEM case uses ramfs without swap
  3034. */
  3035. return read_cache_page_gfp(mapping, index, gfp);
  3036. #endif
  3037. }
  3038. EXPORT_SYMBOL_GPL(shmem_read_mapping_page_gfp);