shmem.c 90 KB

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