shmem.c 91 KB

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