shmem.c 89 KB

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