shmem.c 90 KB

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