swapfile.c 78 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555255625572558255925602561256225632564256525662567256825692570257125722573257425752576257725782579258025812582258325842585258625872588258925902591259225932594259525962597259825992600260126022603260426052606260726082609261026112612261326142615261626172618261926202621262226232624262526262627262826292630263126322633263426352636263726382639264026412642264326442645264626472648264926502651265226532654265526562657265826592660266126622663266426652666266726682669267026712672267326742675267626772678267926802681268226832684268526862687268826892690269126922693269426952696269726982699270027012702270327042705270627072708270927102711271227132714271527162717271827192720272127222723272427252726272727282729273027312732273327342735273627372738273927402741274227432744274527462747274827492750275127522753275427552756275727582759276027612762276327642765276627672768276927702771277227732774277527762777277827792780278127822783278427852786278727882789279027912792279327942795279627972798279928002801280228032804280528062807280828092810281128122813281428152816281728182819282028212822282328242825282628272828282928302831283228332834283528362837283828392840284128422843284428452846284728482849285028512852285328542855285628572858285928602861286228632864286528662867286828692870287128722873287428752876287728782879288028812882288328842885288628872888288928902891289228932894289528962897289828992900290129022903290429052906290729082909291029112912291329142915291629172918291929202921292229232924292529262927292829292930293129322933293429352936293729382939294029412942294329442945294629472948294929502951295229532954295529562957295829592960296129622963296429652966296729682969297029712972297329742975297629772978297929802981298229832984298529862987298829892990299129922993
  1. /*
  2. * linux/mm/swapfile.c
  3. *
  4. * Copyright (C) 1991, 1992, 1993, 1994 Linus Torvalds
  5. * Swap reorganised 29.12.95, Stephen Tweedie
  6. */
  7. #include <linux/mm.h>
  8. #include <linux/hugetlb.h>
  9. #include <linux/mman.h>
  10. #include <linux/slab.h>
  11. #include <linux/kernel_stat.h>
  12. #include <linux/swap.h>
  13. #include <linux/vmalloc.h>
  14. #include <linux/pagemap.h>
  15. #include <linux/namei.h>
  16. #include <linux/shmem_fs.h>
  17. #include <linux/blkdev.h>
  18. #include <linux/random.h>
  19. #include <linux/writeback.h>
  20. #include <linux/proc_fs.h>
  21. #include <linux/seq_file.h>
  22. #include <linux/init.h>
  23. #include <linux/ksm.h>
  24. #include <linux/rmap.h>
  25. #include <linux/security.h>
  26. #include <linux/backing-dev.h>
  27. #include <linux/mutex.h>
  28. #include <linux/capability.h>
  29. #include <linux/syscalls.h>
  30. #include <linux/memcontrol.h>
  31. #include <linux/poll.h>
  32. #include <linux/oom.h>
  33. #include <linux/frontswap.h>
  34. #include <linux/swapfile.h>
  35. #include <linux/export.h>
  36. #include <asm/pgtable.h>
  37. #include <asm/tlbflush.h>
  38. #include <linux/swapops.h>
  39. #include <linux/swap_cgroup.h>
  40. static bool swap_count_continued(struct swap_info_struct *, pgoff_t,
  41. unsigned char);
  42. static void free_swap_count_continuations(struct swap_info_struct *);
  43. static sector_t map_swap_entry(swp_entry_t, struct block_device**);
  44. DEFINE_SPINLOCK(swap_lock);
  45. static unsigned int nr_swapfiles;
  46. atomic_long_t nr_swap_pages;
  47. /*
  48. * Some modules use swappable objects and may try to swap them out under
  49. * memory pressure (via the shrinker). Before doing so, they may wish to
  50. * check to see if any swap space is available.
  51. */
  52. EXPORT_SYMBOL_GPL(nr_swap_pages);
  53. /* protected with swap_lock. reading in vm_swap_full() doesn't need lock */
  54. long total_swap_pages;
  55. static int least_priority;
  56. static const char Bad_file[] = "Bad swap file entry ";
  57. static const char Unused_file[] = "Unused swap file entry ";
  58. static const char Bad_offset[] = "Bad swap offset entry ";
  59. static const char Unused_offset[] = "Unused swap offset entry ";
  60. /*
  61. * all active swap_info_structs
  62. * protected with swap_lock, and ordered by priority.
  63. */
  64. PLIST_HEAD(swap_active_head);
  65. /*
  66. * all available (active, not full) swap_info_structs
  67. * protected with swap_avail_lock, ordered by priority.
  68. * This is used by get_swap_page() instead of swap_active_head
  69. * because swap_active_head includes all swap_info_structs,
  70. * but get_swap_page() doesn't need to look at full ones.
  71. * This uses its own lock instead of swap_lock because when a
  72. * swap_info_struct changes between not-full/full, it needs to
  73. * add/remove itself to/from this list, but the swap_info_struct->lock
  74. * is held and the locking order requires swap_lock to be taken
  75. * before any swap_info_struct->lock.
  76. */
  77. static PLIST_HEAD(swap_avail_head);
  78. static DEFINE_SPINLOCK(swap_avail_lock);
  79. struct swap_info_struct *swap_info[MAX_SWAPFILES];
  80. static DEFINE_MUTEX(swapon_mutex);
  81. static DECLARE_WAIT_QUEUE_HEAD(proc_poll_wait);
  82. /* Activity counter to indicate that a swapon or swapoff has occurred */
  83. static atomic_t proc_poll_event = ATOMIC_INIT(0);
  84. static inline unsigned char swap_count(unsigned char ent)
  85. {
  86. return ent & ~SWAP_HAS_CACHE; /* may include SWAP_HAS_CONT flag */
  87. }
  88. /* returns 1 if swap entry is freed */
  89. static int
  90. __try_to_reclaim_swap(struct swap_info_struct *si, unsigned long offset)
  91. {
  92. swp_entry_t entry = swp_entry(si->type, offset);
  93. struct page *page;
  94. int ret = 0;
  95. page = find_get_page(swap_address_space(entry), swp_offset(entry));
  96. if (!page)
  97. return 0;
  98. /*
  99. * This function is called from scan_swap_map() and it's called
  100. * by vmscan.c at reclaiming pages. So, we hold a lock on a page, here.
  101. * We have to use trylock for avoiding deadlock. This is a special
  102. * case and you should use try_to_free_swap() with explicit lock_page()
  103. * in usual operations.
  104. */
  105. if (trylock_page(page)) {
  106. ret = try_to_free_swap(page);
  107. unlock_page(page);
  108. }
  109. put_page(page);
  110. return ret;
  111. }
  112. /*
  113. * swapon tell device that all the old swap contents can be discarded,
  114. * to allow the swap device to optimize its wear-levelling.
  115. */
  116. static int discard_swap(struct swap_info_struct *si)
  117. {
  118. struct swap_extent *se;
  119. sector_t start_block;
  120. sector_t nr_blocks;
  121. int err = 0;
  122. /* Do not discard the swap header page! */
  123. se = &si->first_swap_extent;
  124. start_block = (se->start_block + 1) << (PAGE_SHIFT - 9);
  125. nr_blocks = ((sector_t)se->nr_pages - 1) << (PAGE_SHIFT - 9);
  126. if (nr_blocks) {
  127. err = blkdev_issue_discard(si->bdev, start_block,
  128. nr_blocks, GFP_KERNEL, 0);
  129. if (err)
  130. return err;
  131. cond_resched();
  132. }
  133. list_for_each_entry(se, &si->first_swap_extent.list, list) {
  134. start_block = se->start_block << (PAGE_SHIFT - 9);
  135. nr_blocks = (sector_t)se->nr_pages << (PAGE_SHIFT - 9);
  136. err = blkdev_issue_discard(si->bdev, start_block,
  137. nr_blocks, GFP_KERNEL, 0);
  138. if (err)
  139. break;
  140. cond_resched();
  141. }
  142. return err; /* That will often be -EOPNOTSUPP */
  143. }
  144. /*
  145. * swap allocation tell device that a cluster of swap can now be discarded,
  146. * to allow the swap device to optimize its wear-levelling.
  147. */
  148. static void discard_swap_cluster(struct swap_info_struct *si,
  149. pgoff_t start_page, pgoff_t nr_pages)
  150. {
  151. struct swap_extent *se = si->curr_swap_extent;
  152. int found_extent = 0;
  153. while (nr_pages) {
  154. if (se->start_page <= start_page &&
  155. start_page < se->start_page + se->nr_pages) {
  156. pgoff_t offset = start_page - se->start_page;
  157. sector_t start_block = se->start_block + offset;
  158. sector_t nr_blocks = se->nr_pages - offset;
  159. if (nr_blocks > nr_pages)
  160. nr_blocks = nr_pages;
  161. start_page += nr_blocks;
  162. nr_pages -= nr_blocks;
  163. if (!found_extent++)
  164. si->curr_swap_extent = se;
  165. start_block <<= PAGE_SHIFT - 9;
  166. nr_blocks <<= PAGE_SHIFT - 9;
  167. if (blkdev_issue_discard(si->bdev, start_block,
  168. nr_blocks, GFP_NOIO, 0))
  169. break;
  170. }
  171. se = list_next_entry(se, list);
  172. }
  173. }
  174. #define SWAPFILE_CLUSTER 256
  175. #define LATENCY_LIMIT 256
  176. static inline void cluster_set_flag(struct swap_cluster_info *info,
  177. unsigned int flag)
  178. {
  179. info->flags = flag;
  180. }
  181. static inline unsigned int cluster_count(struct swap_cluster_info *info)
  182. {
  183. return info->data;
  184. }
  185. static inline void cluster_set_count(struct swap_cluster_info *info,
  186. unsigned int c)
  187. {
  188. info->data = c;
  189. }
  190. static inline void cluster_set_count_flag(struct swap_cluster_info *info,
  191. unsigned int c, unsigned int f)
  192. {
  193. info->flags = f;
  194. info->data = c;
  195. }
  196. static inline unsigned int cluster_next(struct swap_cluster_info *info)
  197. {
  198. return info->data;
  199. }
  200. static inline void cluster_set_next(struct swap_cluster_info *info,
  201. unsigned int n)
  202. {
  203. info->data = n;
  204. }
  205. static inline void cluster_set_next_flag(struct swap_cluster_info *info,
  206. unsigned int n, unsigned int f)
  207. {
  208. info->flags = f;
  209. info->data = n;
  210. }
  211. static inline bool cluster_is_free(struct swap_cluster_info *info)
  212. {
  213. return info->flags & CLUSTER_FLAG_FREE;
  214. }
  215. static inline bool cluster_is_null(struct swap_cluster_info *info)
  216. {
  217. return info->flags & CLUSTER_FLAG_NEXT_NULL;
  218. }
  219. static inline void cluster_set_null(struct swap_cluster_info *info)
  220. {
  221. info->flags = CLUSTER_FLAG_NEXT_NULL;
  222. info->data = 0;
  223. }
  224. static inline bool cluster_list_empty(struct swap_cluster_list *list)
  225. {
  226. return cluster_is_null(&list->head);
  227. }
  228. static inline unsigned int cluster_list_first(struct swap_cluster_list *list)
  229. {
  230. return cluster_next(&list->head);
  231. }
  232. static void cluster_list_init(struct swap_cluster_list *list)
  233. {
  234. cluster_set_null(&list->head);
  235. cluster_set_null(&list->tail);
  236. }
  237. static void cluster_list_add_tail(struct swap_cluster_list *list,
  238. struct swap_cluster_info *ci,
  239. unsigned int idx)
  240. {
  241. if (cluster_list_empty(list)) {
  242. cluster_set_next_flag(&list->head, idx, 0);
  243. cluster_set_next_flag(&list->tail, idx, 0);
  244. } else {
  245. unsigned int tail = cluster_next(&list->tail);
  246. cluster_set_next(&ci[tail], idx);
  247. cluster_set_next_flag(&list->tail, idx, 0);
  248. }
  249. }
  250. static unsigned int cluster_list_del_first(struct swap_cluster_list *list,
  251. struct swap_cluster_info *ci)
  252. {
  253. unsigned int idx;
  254. idx = cluster_next(&list->head);
  255. if (cluster_next(&list->tail) == idx) {
  256. cluster_set_null(&list->head);
  257. cluster_set_null(&list->tail);
  258. } else
  259. cluster_set_next_flag(&list->head,
  260. cluster_next(&ci[idx]), 0);
  261. return idx;
  262. }
  263. /* Add a cluster to discard list and schedule it to do discard */
  264. static void swap_cluster_schedule_discard(struct swap_info_struct *si,
  265. unsigned int idx)
  266. {
  267. /*
  268. * If scan_swap_map() can't find a free cluster, it will check
  269. * si->swap_map directly. To make sure the discarding cluster isn't
  270. * taken by scan_swap_map(), mark the swap entries bad (occupied). It
  271. * will be cleared after discard
  272. */
  273. memset(si->swap_map + idx * SWAPFILE_CLUSTER,
  274. SWAP_MAP_BAD, SWAPFILE_CLUSTER);
  275. cluster_list_add_tail(&si->discard_clusters, si->cluster_info, idx);
  276. schedule_work(&si->discard_work);
  277. }
  278. /*
  279. * Doing discard actually. After a cluster discard is finished, the cluster
  280. * will be added to free cluster list. caller should hold si->lock.
  281. */
  282. static void swap_do_scheduled_discard(struct swap_info_struct *si)
  283. {
  284. struct swap_cluster_info *info;
  285. unsigned int idx;
  286. info = si->cluster_info;
  287. while (!cluster_list_empty(&si->discard_clusters)) {
  288. idx = cluster_list_del_first(&si->discard_clusters, info);
  289. spin_unlock(&si->lock);
  290. discard_swap_cluster(si, idx * SWAPFILE_CLUSTER,
  291. SWAPFILE_CLUSTER);
  292. spin_lock(&si->lock);
  293. cluster_set_flag(&info[idx], CLUSTER_FLAG_FREE);
  294. cluster_list_add_tail(&si->free_clusters, info, idx);
  295. memset(si->swap_map + idx * SWAPFILE_CLUSTER,
  296. 0, SWAPFILE_CLUSTER);
  297. }
  298. }
  299. static void swap_discard_work(struct work_struct *work)
  300. {
  301. struct swap_info_struct *si;
  302. si = container_of(work, struct swap_info_struct, discard_work);
  303. spin_lock(&si->lock);
  304. swap_do_scheduled_discard(si);
  305. spin_unlock(&si->lock);
  306. }
  307. /*
  308. * The cluster corresponding to page_nr will be used. The cluster will be
  309. * removed from free cluster list and its usage counter will be increased.
  310. */
  311. static void inc_cluster_info_page(struct swap_info_struct *p,
  312. struct swap_cluster_info *cluster_info, unsigned long page_nr)
  313. {
  314. unsigned long idx = page_nr / SWAPFILE_CLUSTER;
  315. if (!cluster_info)
  316. return;
  317. if (cluster_is_free(&cluster_info[idx])) {
  318. VM_BUG_ON(cluster_list_first(&p->free_clusters) != idx);
  319. cluster_list_del_first(&p->free_clusters, cluster_info);
  320. cluster_set_count_flag(&cluster_info[idx], 0, 0);
  321. }
  322. VM_BUG_ON(cluster_count(&cluster_info[idx]) >= SWAPFILE_CLUSTER);
  323. cluster_set_count(&cluster_info[idx],
  324. cluster_count(&cluster_info[idx]) + 1);
  325. }
  326. /*
  327. * The cluster corresponding to page_nr decreases one usage. If the usage
  328. * counter becomes 0, which means no page in the cluster is in using, we can
  329. * optionally discard the cluster and add it to free cluster list.
  330. */
  331. static void dec_cluster_info_page(struct swap_info_struct *p,
  332. struct swap_cluster_info *cluster_info, unsigned long page_nr)
  333. {
  334. unsigned long idx = page_nr / SWAPFILE_CLUSTER;
  335. if (!cluster_info)
  336. return;
  337. VM_BUG_ON(cluster_count(&cluster_info[idx]) == 0);
  338. cluster_set_count(&cluster_info[idx],
  339. cluster_count(&cluster_info[idx]) - 1);
  340. if (cluster_count(&cluster_info[idx]) == 0) {
  341. /*
  342. * If the swap is discardable, prepare discard the cluster
  343. * instead of free it immediately. The cluster will be freed
  344. * after discard.
  345. */
  346. if ((p->flags & (SWP_WRITEOK | SWP_PAGE_DISCARD)) ==
  347. (SWP_WRITEOK | SWP_PAGE_DISCARD)) {
  348. swap_cluster_schedule_discard(p, idx);
  349. return;
  350. }
  351. cluster_set_flag(&cluster_info[idx], CLUSTER_FLAG_FREE);
  352. cluster_list_add_tail(&p->free_clusters, cluster_info, idx);
  353. }
  354. }
  355. /*
  356. * It's possible scan_swap_map() uses a free cluster in the middle of free
  357. * cluster list. Avoiding such abuse to avoid list corruption.
  358. */
  359. static bool
  360. scan_swap_map_ssd_cluster_conflict(struct swap_info_struct *si,
  361. unsigned long offset)
  362. {
  363. struct percpu_cluster *percpu_cluster;
  364. bool conflict;
  365. offset /= SWAPFILE_CLUSTER;
  366. conflict = !cluster_list_empty(&si->free_clusters) &&
  367. offset != cluster_list_first(&si->free_clusters) &&
  368. cluster_is_free(&si->cluster_info[offset]);
  369. if (!conflict)
  370. return false;
  371. percpu_cluster = this_cpu_ptr(si->percpu_cluster);
  372. cluster_set_null(&percpu_cluster->index);
  373. return true;
  374. }
  375. /*
  376. * Try to get a swap entry from current cpu's swap entry pool (a cluster). This
  377. * might involve allocating a new cluster for current CPU too.
  378. */
  379. static void scan_swap_map_try_ssd_cluster(struct swap_info_struct *si,
  380. unsigned long *offset, unsigned long *scan_base)
  381. {
  382. struct percpu_cluster *cluster;
  383. bool found_free;
  384. unsigned long tmp;
  385. new_cluster:
  386. cluster = this_cpu_ptr(si->percpu_cluster);
  387. if (cluster_is_null(&cluster->index)) {
  388. if (!cluster_list_empty(&si->free_clusters)) {
  389. cluster->index = si->free_clusters.head;
  390. cluster->next = cluster_next(&cluster->index) *
  391. SWAPFILE_CLUSTER;
  392. } else if (!cluster_list_empty(&si->discard_clusters)) {
  393. /*
  394. * we don't have free cluster but have some clusters in
  395. * discarding, do discard now and reclaim them
  396. */
  397. swap_do_scheduled_discard(si);
  398. *scan_base = *offset = si->cluster_next;
  399. goto new_cluster;
  400. } else
  401. return;
  402. }
  403. found_free = false;
  404. /*
  405. * Other CPUs can use our cluster if they can't find a free cluster,
  406. * check if there is still free entry in the cluster
  407. */
  408. tmp = cluster->next;
  409. while (tmp < si->max && tmp < (cluster_next(&cluster->index) + 1) *
  410. SWAPFILE_CLUSTER) {
  411. if (!si->swap_map[tmp]) {
  412. found_free = true;
  413. break;
  414. }
  415. tmp++;
  416. }
  417. if (!found_free) {
  418. cluster_set_null(&cluster->index);
  419. goto new_cluster;
  420. }
  421. cluster->next = tmp + 1;
  422. *offset = tmp;
  423. *scan_base = tmp;
  424. }
  425. static unsigned long scan_swap_map(struct swap_info_struct *si,
  426. unsigned char usage)
  427. {
  428. unsigned long offset;
  429. unsigned long scan_base;
  430. unsigned long last_in_cluster = 0;
  431. int latency_ration = LATENCY_LIMIT;
  432. /*
  433. * We try to cluster swap pages by allocating them sequentially
  434. * in swap. Once we've allocated SWAPFILE_CLUSTER pages this
  435. * way, however, we resort to first-free allocation, starting
  436. * a new cluster. This prevents us from scattering swap pages
  437. * all over the entire swap partition, so that we reduce
  438. * overall disk seek times between swap pages. -- sct
  439. * But we do now try to find an empty cluster. -Andrea
  440. * And we let swap pages go all over an SSD partition. Hugh
  441. */
  442. si->flags += SWP_SCANNING;
  443. scan_base = offset = si->cluster_next;
  444. /* SSD algorithm */
  445. if (si->cluster_info) {
  446. scan_swap_map_try_ssd_cluster(si, &offset, &scan_base);
  447. goto checks;
  448. }
  449. if (unlikely(!si->cluster_nr--)) {
  450. if (si->pages - si->inuse_pages < SWAPFILE_CLUSTER) {
  451. si->cluster_nr = SWAPFILE_CLUSTER - 1;
  452. goto checks;
  453. }
  454. spin_unlock(&si->lock);
  455. /*
  456. * If seek is expensive, start searching for new cluster from
  457. * start of partition, to minimize the span of allocated swap.
  458. * If seek is cheap, that is the SWP_SOLIDSTATE si->cluster_info
  459. * case, just handled by scan_swap_map_try_ssd_cluster() above.
  460. */
  461. scan_base = offset = si->lowest_bit;
  462. last_in_cluster = offset + SWAPFILE_CLUSTER - 1;
  463. /* Locate the first empty (unaligned) cluster */
  464. for (; last_in_cluster <= si->highest_bit; offset++) {
  465. if (si->swap_map[offset])
  466. last_in_cluster = offset + SWAPFILE_CLUSTER;
  467. else if (offset == last_in_cluster) {
  468. spin_lock(&si->lock);
  469. offset -= SWAPFILE_CLUSTER - 1;
  470. si->cluster_next = offset;
  471. si->cluster_nr = SWAPFILE_CLUSTER - 1;
  472. goto checks;
  473. }
  474. if (unlikely(--latency_ration < 0)) {
  475. cond_resched();
  476. latency_ration = LATENCY_LIMIT;
  477. }
  478. }
  479. offset = scan_base;
  480. spin_lock(&si->lock);
  481. si->cluster_nr = SWAPFILE_CLUSTER - 1;
  482. }
  483. checks:
  484. if (si->cluster_info) {
  485. while (scan_swap_map_ssd_cluster_conflict(si, offset))
  486. scan_swap_map_try_ssd_cluster(si, &offset, &scan_base);
  487. }
  488. if (!(si->flags & SWP_WRITEOK))
  489. goto no_page;
  490. if (!si->highest_bit)
  491. goto no_page;
  492. if (offset > si->highest_bit)
  493. scan_base = offset = si->lowest_bit;
  494. /* reuse swap entry of cache-only swap if not busy. */
  495. if (vm_swap_full() && si->swap_map[offset] == SWAP_HAS_CACHE) {
  496. int swap_was_freed;
  497. spin_unlock(&si->lock);
  498. swap_was_freed = __try_to_reclaim_swap(si, offset);
  499. spin_lock(&si->lock);
  500. /* entry was freed successfully, try to use this again */
  501. if (swap_was_freed)
  502. goto checks;
  503. goto scan; /* check next one */
  504. }
  505. if (si->swap_map[offset])
  506. goto scan;
  507. if (offset == si->lowest_bit)
  508. si->lowest_bit++;
  509. if (offset == si->highest_bit)
  510. si->highest_bit--;
  511. si->inuse_pages++;
  512. if (si->inuse_pages == si->pages) {
  513. si->lowest_bit = si->max;
  514. si->highest_bit = 0;
  515. spin_lock(&swap_avail_lock);
  516. plist_del(&si->avail_list, &swap_avail_head);
  517. spin_unlock(&swap_avail_lock);
  518. }
  519. si->swap_map[offset] = usage;
  520. inc_cluster_info_page(si, si->cluster_info, offset);
  521. si->cluster_next = offset + 1;
  522. si->flags -= SWP_SCANNING;
  523. return offset;
  524. scan:
  525. spin_unlock(&si->lock);
  526. while (++offset <= si->highest_bit) {
  527. if (!si->swap_map[offset]) {
  528. spin_lock(&si->lock);
  529. goto checks;
  530. }
  531. if (vm_swap_full() && si->swap_map[offset] == SWAP_HAS_CACHE) {
  532. spin_lock(&si->lock);
  533. goto checks;
  534. }
  535. if (unlikely(--latency_ration < 0)) {
  536. cond_resched();
  537. latency_ration = LATENCY_LIMIT;
  538. }
  539. }
  540. offset = si->lowest_bit;
  541. while (offset < scan_base) {
  542. if (!si->swap_map[offset]) {
  543. spin_lock(&si->lock);
  544. goto checks;
  545. }
  546. if (vm_swap_full() && si->swap_map[offset] == SWAP_HAS_CACHE) {
  547. spin_lock(&si->lock);
  548. goto checks;
  549. }
  550. if (unlikely(--latency_ration < 0)) {
  551. cond_resched();
  552. latency_ration = LATENCY_LIMIT;
  553. }
  554. offset++;
  555. }
  556. spin_lock(&si->lock);
  557. no_page:
  558. si->flags -= SWP_SCANNING;
  559. return 0;
  560. }
  561. swp_entry_t get_swap_page(void)
  562. {
  563. struct swap_info_struct *si, *next;
  564. pgoff_t offset;
  565. if (atomic_long_read(&nr_swap_pages) <= 0)
  566. goto noswap;
  567. atomic_long_dec(&nr_swap_pages);
  568. spin_lock(&swap_avail_lock);
  569. start_over:
  570. plist_for_each_entry_safe(si, next, &swap_avail_head, avail_list) {
  571. /* requeue si to after same-priority siblings */
  572. plist_requeue(&si->avail_list, &swap_avail_head);
  573. spin_unlock(&swap_avail_lock);
  574. spin_lock(&si->lock);
  575. if (!si->highest_bit || !(si->flags & SWP_WRITEOK)) {
  576. spin_lock(&swap_avail_lock);
  577. if (plist_node_empty(&si->avail_list)) {
  578. spin_unlock(&si->lock);
  579. goto nextsi;
  580. }
  581. WARN(!si->highest_bit,
  582. "swap_info %d in list but !highest_bit\n",
  583. si->type);
  584. WARN(!(si->flags & SWP_WRITEOK),
  585. "swap_info %d in list but !SWP_WRITEOK\n",
  586. si->type);
  587. plist_del(&si->avail_list, &swap_avail_head);
  588. spin_unlock(&si->lock);
  589. goto nextsi;
  590. }
  591. /* This is called for allocating swap entry for cache */
  592. offset = scan_swap_map(si, SWAP_HAS_CACHE);
  593. spin_unlock(&si->lock);
  594. if (offset)
  595. return swp_entry(si->type, offset);
  596. pr_debug("scan_swap_map of si %d failed to find offset\n",
  597. si->type);
  598. spin_lock(&swap_avail_lock);
  599. nextsi:
  600. /*
  601. * if we got here, it's likely that si was almost full before,
  602. * and since scan_swap_map() can drop the si->lock, multiple
  603. * callers probably all tried to get a page from the same si
  604. * and it filled up before we could get one; or, the si filled
  605. * up between us dropping swap_avail_lock and taking si->lock.
  606. * Since we dropped the swap_avail_lock, the swap_avail_head
  607. * list may have been modified; so if next is still in the
  608. * swap_avail_head list then try it, otherwise start over.
  609. */
  610. if (plist_node_empty(&next->avail_list))
  611. goto start_over;
  612. }
  613. spin_unlock(&swap_avail_lock);
  614. atomic_long_inc(&nr_swap_pages);
  615. noswap:
  616. return (swp_entry_t) {0};
  617. }
  618. /* The only caller of this function is now suspend routine */
  619. swp_entry_t get_swap_page_of_type(int type)
  620. {
  621. struct swap_info_struct *si;
  622. pgoff_t offset;
  623. si = swap_info[type];
  624. spin_lock(&si->lock);
  625. if (si && (si->flags & SWP_WRITEOK)) {
  626. atomic_long_dec(&nr_swap_pages);
  627. /* This is called for allocating swap entry, not cache */
  628. offset = scan_swap_map(si, 1);
  629. if (offset) {
  630. spin_unlock(&si->lock);
  631. return swp_entry(type, offset);
  632. }
  633. atomic_long_inc(&nr_swap_pages);
  634. }
  635. spin_unlock(&si->lock);
  636. return (swp_entry_t) {0};
  637. }
  638. static struct swap_info_struct *swap_info_get(swp_entry_t entry)
  639. {
  640. struct swap_info_struct *p;
  641. unsigned long offset, type;
  642. if (!entry.val)
  643. goto out;
  644. type = swp_type(entry);
  645. if (type >= nr_swapfiles)
  646. goto bad_nofile;
  647. p = swap_info[type];
  648. if (!(p->flags & SWP_USED))
  649. goto bad_device;
  650. offset = swp_offset(entry);
  651. if (offset >= p->max)
  652. goto bad_offset;
  653. if (!p->swap_map[offset])
  654. goto bad_free;
  655. spin_lock(&p->lock);
  656. return p;
  657. bad_free:
  658. pr_err("swap_free: %s%08lx\n", Unused_offset, entry.val);
  659. goto out;
  660. bad_offset:
  661. pr_err("swap_free: %s%08lx\n", Bad_offset, entry.val);
  662. goto out;
  663. bad_device:
  664. pr_err("swap_free: %s%08lx\n", Unused_file, entry.val);
  665. goto out;
  666. bad_nofile:
  667. pr_err("swap_free: %s%08lx\n", Bad_file, entry.val);
  668. out:
  669. return NULL;
  670. }
  671. static unsigned char swap_entry_free(struct swap_info_struct *p,
  672. swp_entry_t entry, unsigned char usage)
  673. {
  674. unsigned long offset = swp_offset(entry);
  675. unsigned char count;
  676. unsigned char has_cache;
  677. count = p->swap_map[offset];
  678. has_cache = count & SWAP_HAS_CACHE;
  679. count &= ~SWAP_HAS_CACHE;
  680. if (usage == SWAP_HAS_CACHE) {
  681. VM_BUG_ON(!has_cache);
  682. has_cache = 0;
  683. } else if (count == SWAP_MAP_SHMEM) {
  684. /*
  685. * Or we could insist on shmem.c using a special
  686. * swap_shmem_free() and free_shmem_swap_and_cache()...
  687. */
  688. count = 0;
  689. } else if ((count & ~COUNT_CONTINUED) <= SWAP_MAP_MAX) {
  690. if (count == COUNT_CONTINUED) {
  691. if (swap_count_continued(p, offset, count))
  692. count = SWAP_MAP_MAX | COUNT_CONTINUED;
  693. else
  694. count = SWAP_MAP_MAX;
  695. } else
  696. count--;
  697. }
  698. usage = count | has_cache;
  699. p->swap_map[offset] = usage;
  700. /* free if no reference */
  701. if (!usage) {
  702. mem_cgroup_uncharge_swap(entry);
  703. dec_cluster_info_page(p, p->cluster_info, offset);
  704. if (offset < p->lowest_bit)
  705. p->lowest_bit = offset;
  706. if (offset > p->highest_bit) {
  707. bool was_full = !p->highest_bit;
  708. p->highest_bit = offset;
  709. if (was_full && (p->flags & SWP_WRITEOK)) {
  710. spin_lock(&swap_avail_lock);
  711. WARN_ON(!plist_node_empty(&p->avail_list));
  712. if (plist_node_empty(&p->avail_list))
  713. plist_add(&p->avail_list,
  714. &swap_avail_head);
  715. spin_unlock(&swap_avail_lock);
  716. }
  717. }
  718. atomic_long_inc(&nr_swap_pages);
  719. p->inuse_pages--;
  720. frontswap_invalidate_page(p->type, offset);
  721. if (p->flags & SWP_BLKDEV) {
  722. struct gendisk *disk = p->bdev->bd_disk;
  723. if (disk->fops->swap_slot_free_notify)
  724. disk->fops->swap_slot_free_notify(p->bdev,
  725. offset);
  726. }
  727. }
  728. return usage;
  729. }
  730. /*
  731. * Caller has made sure that the swap device corresponding to entry
  732. * is still around or has not been recycled.
  733. */
  734. void swap_free(swp_entry_t entry)
  735. {
  736. struct swap_info_struct *p;
  737. p = swap_info_get(entry);
  738. if (p) {
  739. swap_entry_free(p, entry, 1);
  740. spin_unlock(&p->lock);
  741. }
  742. }
  743. /*
  744. * Called after dropping swapcache to decrease refcnt to swap entries.
  745. */
  746. void swapcache_free(swp_entry_t entry)
  747. {
  748. struct swap_info_struct *p;
  749. p = swap_info_get(entry);
  750. if (p) {
  751. swap_entry_free(p, entry, SWAP_HAS_CACHE);
  752. spin_unlock(&p->lock);
  753. }
  754. }
  755. /*
  756. * How many references to page are currently swapped out?
  757. * This does not give an exact answer when swap count is continued,
  758. * but does include the high COUNT_CONTINUED flag to allow for that.
  759. */
  760. int page_swapcount(struct page *page)
  761. {
  762. int count = 0;
  763. struct swap_info_struct *p;
  764. swp_entry_t entry;
  765. entry.val = page_private(page);
  766. p = swap_info_get(entry);
  767. if (p) {
  768. count = swap_count(p->swap_map[swp_offset(entry)]);
  769. spin_unlock(&p->lock);
  770. }
  771. return count;
  772. }
  773. /*
  774. * How many references to @entry are currently swapped out?
  775. * This considers COUNT_CONTINUED so it returns exact answer.
  776. */
  777. int swp_swapcount(swp_entry_t entry)
  778. {
  779. int count, tmp_count, n;
  780. struct swap_info_struct *p;
  781. struct page *page;
  782. pgoff_t offset;
  783. unsigned char *map;
  784. p = swap_info_get(entry);
  785. if (!p)
  786. return 0;
  787. count = swap_count(p->swap_map[swp_offset(entry)]);
  788. if (!(count & COUNT_CONTINUED))
  789. goto out;
  790. count &= ~COUNT_CONTINUED;
  791. n = SWAP_MAP_MAX + 1;
  792. offset = swp_offset(entry);
  793. page = vmalloc_to_page(p->swap_map + offset);
  794. offset &= ~PAGE_MASK;
  795. VM_BUG_ON(page_private(page) != SWP_CONTINUED);
  796. do {
  797. page = list_next_entry(page, lru);
  798. map = kmap_atomic(page);
  799. tmp_count = map[offset];
  800. kunmap_atomic(map);
  801. count += (tmp_count & ~COUNT_CONTINUED) * n;
  802. n *= (SWAP_CONT_MAX + 1);
  803. } while (tmp_count & COUNT_CONTINUED);
  804. out:
  805. spin_unlock(&p->lock);
  806. return count;
  807. }
  808. /*
  809. * We can write to an anon page without COW if there are no other references
  810. * to it. And as a side-effect, free up its swap: because the old content
  811. * on disk will never be read, and seeking back there to write new content
  812. * later would only waste time away from clustering.
  813. *
  814. * NOTE: total_mapcount should not be relied upon by the caller if
  815. * reuse_swap_page() returns false, but it may be always overwritten
  816. * (see the other implementation for CONFIG_SWAP=n).
  817. */
  818. bool reuse_swap_page(struct page *page, int *total_mapcount)
  819. {
  820. int count;
  821. VM_BUG_ON_PAGE(!PageLocked(page), page);
  822. if (unlikely(PageKsm(page)))
  823. return false;
  824. count = page_trans_huge_mapcount(page, total_mapcount);
  825. if (count <= 1 && PageSwapCache(page)) {
  826. count += page_swapcount(page);
  827. if (count != 1)
  828. goto out;
  829. if (!PageWriteback(page)) {
  830. delete_from_swap_cache(page);
  831. SetPageDirty(page);
  832. } else {
  833. swp_entry_t entry;
  834. struct swap_info_struct *p;
  835. entry.val = page_private(page);
  836. p = swap_info_get(entry);
  837. if (p->flags & SWP_STABLE_WRITES) {
  838. spin_unlock(&p->lock);
  839. return false;
  840. }
  841. spin_unlock(&p->lock);
  842. }
  843. }
  844. out:
  845. return count <= 1;
  846. }
  847. /*
  848. * If swap is getting full, or if there are no more mappings of this page,
  849. * then try_to_free_swap is called to free its swap space.
  850. */
  851. int try_to_free_swap(struct page *page)
  852. {
  853. VM_BUG_ON_PAGE(!PageLocked(page), page);
  854. if (!PageSwapCache(page))
  855. return 0;
  856. if (PageWriteback(page))
  857. return 0;
  858. if (page_swapcount(page))
  859. return 0;
  860. /*
  861. * Once hibernation has begun to create its image of memory,
  862. * there's a danger that one of the calls to try_to_free_swap()
  863. * - most probably a call from __try_to_reclaim_swap() while
  864. * hibernation is allocating its own swap pages for the image,
  865. * but conceivably even a call from memory reclaim - will free
  866. * the swap from a page which has already been recorded in the
  867. * image as a clean swapcache page, and then reuse its swap for
  868. * another page of the image. On waking from hibernation, the
  869. * original page might be freed under memory pressure, then
  870. * later read back in from swap, now with the wrong data.
  871. *
  872. * Hibernation suspends storage while it is writing the image
  873. * to disk so check that here.
  874. */
  875. if (pm_suspended_storage())
  876. return 0;
  877. delete_from_swap_cache(page);
  878. SetPageDirty(page);
  879. return 1;
  880. }
  881. /*
  882. * Free the swap entry like above, but also try to
  883. * free the page cache entry if it is the last user.
  884. */
  885. int free_swap_and_cache(swp_entry_t entry)
  886. {
  887. struct swap_info_struct *p;
  888. struct page *page = NULL;
  889. if (non_swap_entry(entry))
  890. return 1;
  891. p = swap_info_get(entry);
  892. if (p) {
  893. if (swap_entry_free(p, entry, 1) == SWAP_HAS_CACHE) {
  894. page = find_get_page(swap_address_space(entry),
  895. swp_offset(entry));
  896. if (page && !trylock_page(page)) {
  897. put_page(page);
  898. page = NULL;
  899. }
  900. }
  901. spin_unlock(&p->lock);
  902. }
  903. if (page) {
  904. /*
  905. * Not mapped elsewhere, or swap space full? Free it!
  906. * Also recheck PageSwapCache now page is locked (above).
  907. */
  908. if (PageSwapCache(page) && !PageWriteback(page) &&
  909. (!page_mapped(page) || mem_cgroup_swap_full(page))) {
  910. delete_from_swap_cache(page);
  911. SetPageDirty(page);
  912. }
  913. unlock_page(page);
  914. put_page(page);
  915. }
  916. return p != NULL;
  917. }
  918. #ifdef CONFIG_HIBERNATION
  919. /*
  920. * Find the swap type that corresponds to given device (if any).
  921. *
  922. * @offset - number of the PAGE_SIZE-sized block of the device, starting
  923. * from 0, in which the swap header is expected to be located.
  924. *
  925. * This is needed for the suspend to disk (aka swsusp).
  926. */
  927. int swap_type_of(dev_t device, sector_t offset, struct block_device **bdev_p)
  928. {
  929. struct block_device *bdev = NULL;
  930. int type;
  931. if (device)
  932. bdev = bdget(device);
  933. spin_lock(&swap_lock);
  934. for (type = 0; type < nr_swapfiles; type++) {
  935. struct swap_info_struct *sis = swap_info[type];
  936. if (!(sis->flags & SWP_WRITEOK))
  937. continue;
  938. if (!bdev) {
  939. if (bdev_p)
  940. *bdev_p = bdgrab(sis->bdev);
  941. spin_unlock(&swap_lock);
  942. return type;
  943. }
  944. if (bdev == sis->bdev) {
  945. struct swap_extent *se = &sis->first_swap_extent;
  946. if (se->start_block == offset) {
  947. if (bdev_p)
  948. *bdev_p = bdgrab(sis->bdev);
  949. spin_unlock(&swap_lock);
  950. bdput(bdev);
  951. return type;
  952. }
  953. }
  954. }
  955. spin_unlock(&swap_lock);
  956. if (bdev)
  957. bdput(bdev);
  958. return -ENODEV;
  959. }
  960. /*
  961. * Get the (PAGE_SIZE) block corresponding to given offset on the swapdev
  962. * corresponding to given index in swap_info (swap type).
  963. */
  964. sector_t swapdev_block(int type, pgoff_t offset)
  965. {
  966. struct block_device *bdev;
  967. if ((unsigned int)type >= nr_swapfiles)
  968. return 0;
  969. if (!(swap_info[type]->flags & SWP_WRITEOK))
  970. return 0;
  971. return map_swap_entry(swp_entry(type, offset), &bdev);
  972. }
  973. /*
  974. * Return either the total number of swap pages of given type, or the number
  975. * of free pages of that type (depending on @free)
  976. *
  977. * This is needed for software suspend
  978. */
  979. unsigned int count_swap_pages(int type, int free)
  980. {
  981. unsigned int n = 0;
  982. spin_lock(&swap_lock);
  983. if ((unsigned int)type < nr_swapfiles) {
  984. struct swap_info_struct *sis = swap_info[type];
  985. spin_lock(&sis->lock);
  986. if (sis->flags & SWP_WRITEOK) {
  987. n = sis->pages;
  988. if (free)
  989. n -= sis->inuse_pages;
  990. }
  991. spin_unlock(&sis->lock);
  992. }
  993. spin_unlock(&swap_lock);
  994. return n;
  995. }
  996. #endif /* CONFIG_HIBERNATION */
  997. static inline int pte_same_as_swp(pte_t pte, pte_t swp_pte)
  998. {
  999. return pte_same(pte_swp_clear_soft_dirty(pte), swp_pte);
  1000. }
  1001. /*
  1002. * No need to decide whether this PTE shares the swap entry with others,
  1003. * just let do_wp_page work it out if a write is requested later - to
  1004. * force COW, vm_page_prot omits write permission from any private vma.
  1005. */
  1006. static int unuse_pte(struct vm_area_struct *vma, pmd_t *pmd,
  1007. unsigned long addr, swp_entry_t entry, struct page *page)
  1008. {
  1009. struct page *swapcache;
  1010. struct mem_cgroup *memcg;
  1011. spinlock_t *ptl;
  1012. pte_t *pte;
  1013. int ret = 1;
  1014. swapcache = page;
  1015. page = ksm_might_need_to_copy(page, vma, addr);
  1016. if (unlikely(!page))
  1017. return -ENOMEM;
  1018. if (mem_cgroup_try_charge(page, vma->vm_mm, GFP_KERNEL,
  1019. &memcg, false)) {
  1020. ret = -ENOMEM;
  1021. goto out_nolock;
  1022. }
  1023. pte = pte_offset_map_lock(vma->vm_mm, pmd, addr, &ptl);
  1024. if (unlikely(!pte_same_as_swp(*pte, swp_entry_to_pte(entry)))) {
  1025. mem_cgroup_cancel_charge(page, memcg, false);
  1026. ret = 0;
  1027. goto out;
  1028. }
  1029. dec_mm_counter(vma->vm_mm, MM_SWAPENTS);
  1030. inc_mm_counter(vma->vm_mm, MM_ANONPAGES);
  1031. get_page(page);
  1032. set_pte_at(vma->vm_mm, addr, pte,
  1033. pte_mkold(mk_pte(page, vma->vm_page_prot)));
  1034. if (page == swapcache) {
  1035. page_add_anon_rmap(page, vma, addr, false);
  1036. mem_cgroup_commit_charge(page, memcg, true, false);
  1037. } else { /* ksm created a completely new copy */
  1038. page_add_new_anon_rmap(page, vma, addr, false);
  1039. mem_cgroup_commit_charge(page, memcg, false, false);
  1040. lru_cache_add_active_or_unevictable(page, vma);
  1041. }
  1042. swap_free(entry);
  1043. /*
  1044. * Move the page to the active list so it is not
  1045. * immediately swapped out again after swapon.
  1046. */
  1047. activate_page(page);
  1048. out:
  1049. pte_unmap_unlock(pte, ptl);
  1050. out_nolock:
  1051. if (page != swapcache) {
  1052. unlock_page(page);
  1053. put_page(page);
  1054. }
  1055. return ret;
  1056. }
  1057. static int unuse_pte_range(struct vm_area_struct *vma, pmd_t *pmd,
  1058. unsigned long addr, unsigned long end,
  1059. swp_entry_t entry, struct page *page)
  1060. {
  1061. pte_t swp_pte = swp_entry_to_pte(entry);
  1062. pte_t *pte;
  1063. int ret = 0;
  1064. /*
  1065. * We don't actually need pte lock while scanning for swp_pte: since
  1066. * we hold page lock and mmap_sem, swp_pte cannot be inserted into the
  1067. * page table while we're scanning; though it could get zapped, and on
  1068. * some architectures (e.g. x86_32 with PAE) we might catch a glimpse
  1069. * of unmatched parts which look like swp_pte, so unuse_pte must
  1070. * recheck under pte lock. Scanning without pte lock lets it be
  1071. * preemptable whenever CONFIG_PREEMPT but not CONFIG_HIGHPTE.
  1072. */
  1073. pte = pte_offset_map(pmd, addr);
  1074. do {
  1075. /*
  1076. * swapoff spends a _lot_ of time in this loop!
  1077. * Test inline before going to call unuse_pte.
  1078. */
  1079. if (unlikely(pte_same_as_swp(*pte, swp_pte))) {
  1080. pte_unmap(pte);
  1081. ret = unuse_pte(vma, pmd, addr, entry, page);
  1082. if (ret)
  1083. goto out;
  1084. pte = pte_offset_map(pmd, addr);
  1085. }
  1086. } while (pte++, addr += PAGE_SIZE, addr != end);
  1087. pte_unmap(pte - 1);
  1088. out:
  1089. return ret;
  1090. }
  1091. static inline int unuse_pmd_range(struct vm_area_struct *vma, pud_t *pud,
  1092. unsigned long addr, unsigned long end,
  1093. swp_entry_t entry, struct page *page)
  1094. {
  1095. pmd_t *pmd;
  1096. unsigned long next;
  1097. int ret;
  1098. pmd = pmd_offset(pud, addr);
  1099. do {
  1100. next = pmd_addr_end(addr, end);
  1101. if (pmd_none_or_trans_huge_or_clear_bad(pmd))
  1102. continue;
  1103. ret = unuse_pte_range(vma, pmd, addr, next, entry, page);
  1104. if (ret)
  1105. return ret;
  1106. } while (pmd++, addr = next, addr != end);
  1107. return 0;
  1108. }
  1109. static inline int unuse_pud_range(struct vm_area_struct *vma, pgd_t *pgd,
  1110. unsigned long addr, unsigned long end,
  1111. swp_entry_t entry, struct page *page)
  1112. {
  1113. pud_t *pud;
  1114. unsigned long next;
  1115. int ret;
  1116. pud = pud_offset(pgd, addr);
  1117. do {
  1118. next = pud_addr_end(addr, end);
  1119. if (pud_none_or_clear_bad(pud))
  1120. continue;
  1121. ret = unuse_pmd_range(vma, pud, addr, next, entry, page);
  1122. if (ret)
  1123. return ret;
  1124. } while (pud++, addr = next, addr != end);
  1125. return 0;
  1126. }
  1127. static int unuse_vma(struct vm_area_struct *vma,
  1128. swp_entry_t entry, struct page *page)
  1129. {
  1130. pgd_t *pgd;
  1131. unsigned long addr, end, next;
  1132. int ret;
  1133. if (page_anon_vma(page)) {
  1134. addr = page_address_in_vma(page, vma);
  1135. if (addr == -EFAULT)
  1136. return 0;
  1137. else
  1138. end = addr + PAGE_SIZE;
  1139. } else {
  1140. addr = vma->vm_start;
  1141. end = vma->vm_end;
  1142. }
  1143. pgd = pgd_offset(vma->vm_mm, addr);
  1144. do {
  1145. next = pgd_addr_end(addr, end);
  1146. if (pgd_none_or_clear_bad(pgd))
  1147. continue;
  1148. ret = unuse_pud_range(vma, pgd, addr, next, entry, page);
  1149. if (ret)
  1150. return ret;
  1151. } while (pgd++, addr = next, addr != end);
  1152. return 0;
  1153. }
  1154. static int unuse_mm(struct mm_struct *mm,
  1155. swp_entry_t entry, struct page *page)
  1156. {
  1157. struct vm_area_struct *vma;
  1158. int ret = 0;
  1159. if (!down_read_trylock(&mm->mmap_sem)) {
  1160. /*
  1161. * Activate page so shrink_inactive_list is unlikely to unmap
  1162. * its ptes while lock is dropped, so swapoff can make progress.
  1163. */
  1164. activate_page(page);
  1165. unlock_page(page);
  1166. down_read(&mm->mmap_sem);
  1167. lock_page(page);
  1168. }
  1169. for (vma = mm->mmap; vma; vma = vma->vm_next) {
  1170. if (vma->anon_vma && (ret = unuse_vma(vma, entry, page)))
  1171. break;
  1172. }
  1173. up_read(&mm->mmap_sem);
  1174. return (ret < 0)? ret: 0;
  1175. }
  1176. /*
  1177. * Scan swap_map (or frontswap_map if frontswap parameter is true)
  1178. * from current position to next entry still in use.
  1179. * Recycle to start on reaching the end, returning 0 when empty.
  1180. */
  1181. static unsigned int find_next_to_unuse(struct swap_info_struct *si,
  1182. unsigned int prev, bool frontswap)
  1183. {
  1184. unsigned int max = si->max;
  1185. unsigned int i = prev;
  1186. unsigned char count;
  1187. /*
  1188. * No need for swap_lock here: we're just looking
  1189. * for whether an entry is in use, not modifying it; false
  1190. * hits are okay, and sys_swapoff() has already prevented new
  1191. * allocations from this area (while holding swap_lock).
  1192. */
  1193. for (;;) {
  1194. if (++i >= max) {
  1195. if (!prev) {
  1196. i = 0;
  1197. break;
  1198. }
  1199. /*
  1200. * No entries in use at top of swap_map,
  1201. * loop back to start and recheck there.
  1202. */
  1203. max = prev + 1;
  1204. prev = 0;
  1205. i = 1;
  1206. }
  1207. if (frontswap) {
  1208. if (frontswap_test(si, i))
  1209. break;
  1210. else
  1211. continue;
  1212. }
  1213. count = READ_ONCE(si->swap_map[i]);
  1214. if (count && swap_count(count) != SWAP_MAP_BAD)
  1215. break;
  1216. }
  1217. return i;
  1218. }
  1219. /*
  1220. * We completely avoid races by reading each swap page in advance,
  1221. * and then search for the process using it. All the necessary
  1222. * page table adjustments can then be made atomically.
  1223. *
  1224. * if the boolean frontswap is true, only unuse pages_to_unuse pages;
  1225. * pages_to_unuse==0 means all pages; ignored if frontswap is false
  1226. */
  1227. int try_to_unuse(unsigned int type, bool frontswap,
  1228. unsigned long pages_to_unuse)
  1229. {
  1230. struct swap_info_struct *si = swap_info[type];
  1231. struct mm_struct *start_mm;
  1232. volatile unsigned char *swap_map; /* swap_map is accessed without
  1233. * locking. Mark it as volatile
  1234. * to prevent compiler doing
  1235. * something odd.
  1236. */
  1237. unsigned char swcount;
  1238. struct page *page;
  1239. swp_entry_t entry;
  1240. unsigned int i = 0;
  1241. int retval = 0;
  1242. /*
  1243. * When searching mms for an entry, a good strategy is to
  1244. * start at the first mm we freed the previous entry from
  1245. * (though actually we don't notice whether we or coincidence
  1246. * freed the entry). Initialize this start_mm with a hold.
  1247. *
  1248. * A simpler strategy would be to start at the last mm we
  1249. * freed the previous entry from; but that would take less
  1250. * advantage of mmlist ordering, which clusters forked mms
  1251. * together, child after parent. If we race with dup_mmap(), we
  1252. * prefer to resolve parent before child, lest we miss entries
  1253. * duplicated after we scanned child: using last mm would invert
  1254. * that.
  1255. */
  1256. start_mm = &init_mm;
  1257. atomic_inc(&init_mm.mm_users);
  1258. /*
  1259. * Keep on scanning until all entries have gone. Usually,
  1260. * one pass through swap_map is enough, but not necessarily:
  1261. * there are races when an instance of an entry might be missed.
  1262. */
  1263. while ((i = find_next_to_unuse(si, i, frontswap)) != 0) {
  1264. if (signal_pending(current)) {
  1265. retval = -EINTR;
  1266. break;
  1267. }
  1268. /*
  1269. * Get a page for the entry, using the existing swap
  1270. * cache page if there is one. Otherwise, get a clean
  1271. * page and read the swap into it.
  1272. */
  1273. swap_map = &si->swap_map[i];
  1274. entry = swp_entry(type, i);
  1275. page = read_swap_cache_async(entry,
  1276. GFP_HIGHUSER_MOVABLE, NULL, 0);
  1277. if (!page) {
  1278. /*
  1279. * Either swap_duplicate() failed because entry
  1280. * has been freed independently, and will not be
  1281. * reused since sys_swapoff() already disabled
  1282. * allocation from here, or alloc_page() failed.
  1283. */
  1284. swcount = *swap_map;
  1285. /*
  1286. * We don't hold lock here, so the swap entry could be
  1287. * SWAP_MAP_BAD (when the cluster is discarding).
  1288. * Instead of fail out, We can just skip the swap
  1289. * entry because swapoff will wait for discarding
  1290. * finish anyway.
  1291. */
  1292. if (!swcount || swcount == SWAP_MAP_BAD)
  1293. continue;
  1294. retval = -ENOMEM;
  1295. break;
  1296. }
  1297. /*
  1298. * Don't hold on to start_mm if it looks like exiting.
  1299. */
  1300. if (atomic_read(&start_mm->mm_users) == 1) {
  1301. mmput(start_mm);
  1302. start_mm = &init_mm;
  1303. atomic_inc(&init_mm.mm_users);
  1304. }
  1305. /*
  1306. * Wait for and lock page. When do_swap_page races with
  1307. * try_to_unuse, do_swap_page can handle the fault much
  1308. * faster than try_to_unuse can locate the entry. This
  1309. * apparently redundant "wait_on_page_locked" lets try_to_unuse
  1310. * defer to do_swap_page in such a case - in some tests,
  1311. * do_swap_page and try_to_unuse repeatedly compete.
  1312. */
  1313. wait_on_page_locked(page);
  1314. wait_on_page_writeback(page);
  1315. lock_page(page);
  1316. wait_on_page_writeback(page);
  1317. /*
  1318. * Remove all references to entry.
  1319. */
  1320. swcount = *swap_map;
  1321. if (swap_count(swcount) == SWAP_MAP_SHMEM) {
  1322. retval = shmem_unuse(entry, page);
  1323. /* page has already been unlocked and released */
  1324. if (retval < 0)
  1325. break;
  1326. continue;
  1327. }
  1328. if (swap_count(swcount) && start_mm != &init_mm)
  1329. retval = unuse_mm(start_mm, entry, page);
  1330. if (swap_count(*swap_map)) {
  1331. int set_start_mm = (*swap_map >= swcount);
  1332. struct list_head *p = &start_mm->mmlist;
  1333. struct mm_struct *new_start_mm = start_mm;
  1334. struct mm_struct *prev_mm = start_mm;
  1335. struct mm_struct *mm;
  1336. atomic_inc(&new_start_mm->mm_users);
  1337. atomic_inc(&prev_mm->mm_users);
  1338. spin_lock(&mmlist_lock);
  1339. while (swap_count(*swap_map) && !retval &&
  1340. (p = p->next) != &start_mm->mmlist) {
  1341. mm = list_entry(p, struct mm_struct, mmlist);
  1342. if (!atomic_inc_not_zero(&mm->mm_users))
  1343. continue;
  1344. spin_unlock(&mmlist_lock);
  1345. mmput(prev_mm);
  1346. prev_mm = mm;
  1347. cond_resched();
  1348. swcount = *swap_map;
  1349. if (!swap_count(swcount)) /* any usage ? */
  1350. ;
  1351. else if (mm == &init_mm)
  1352. set_start_mm = 1;
  1353. else
  1354. retval = unuse_mm(mm, entry, page);
  1355. if (set_start_mm && *swap_map < swcount) {
  1356. mmput(new_start_mm);
  1357. atomic_inc(&mm->mm_users);
  1358. new_start_mm = mm;
  1359. set_start_mm = 0;
  1360. }
  1361. spin_lock(&mmlist_lock);
  1362. }
  1363. spin_unlock(&mmlist_lock);
  1364. mmput(prev_mm);
  1365. mmput(start_mm);
  1366. start_mm = new_start_mm;
  1367. }
  1368. if (retval) {
  1369. unlock_page(page);
  1370. put_page(page);
  1371. break;
  1372. }
  1373. /*
  1374. * If a reference remains (rare), we would like to leave
  1375. * the page in the swap cache; but try_to_unmap could
  1376. * then re-duplicate the entry once we drop page lock,
  1377. * so we might loop indefinitely; also, that page could
  1378. * not be swapped out to other storage meanwhile. So:
  1379. * delete from cache even if there's another reference,
  1380. * after ensuring that the data has been saved to disk -
  1381. * since if the reference remains (rarer), it will be
  1382. * read from disk into another page. Splitting into two
  1383. * pages would be incorrect if swap supported "shared
  1384. * private" pages, but they are handled by tmpfs files.
  1385. *
  1386. * Given how unuse_vma() targets one particular offset
  1387. * in an anon_vma, once the anon_vma has been determined,
  1388. * this splitting happens to be just what is needed to
  1389. * handle where KSM pages have been swapped out: re-reading
  1390. * is unnecessarily slow, but we can fix that later on.
  1391. */
  1392. if (swap_count(*swap_map) &&
  1393. PageDirty(page) && PageSwapCache(page)) {
  1394. struct writeback_control wbc = {
  1395. .sync_mode = WB_SYNC_NONE,
  1396. };
  1397. swap_writepage(page, &wbc);
  1398. lock_page(page);
  1399. wait_on_page_writeback(page);
  1400. }
  1401. /*
  1402. * It is conceivable that a racing task removed this page from
  1403. * swap cache just before we acquired the page lock at the top,
  1404. * or while we dropped it in unuse_mm(). The page might even
  1405. * be back in swap cache on another swap area: that we must not
  1406. * delete, since it may not have been written out to swap yet.
  1407. */
  1408. if (PageSwapCache(page) &&
  1409. likely(page_private(page) == entry.val))
  1410. delete_from_swap_cache(page);
  1411. /*
  1412. * So we could skip searching mms once swap count went
  1413. * to 1, we did not mark any present ptes as dirty: must
  1414. * mark page dirty so shrink_page_list will preserve it.
  1415. */
  1416. SetPageDirty(page);
  1417. unlock_page(page);
  1418. put_page(page);
  1419. /*
  1420. * Make sure that we aren't completely killing
  1421. * interactive performance.
  1422. */
  1423. cond_resched();
  1424. if (frontswap && pages_to_unuse > 0) {
  1425. if (!--pages_to_unuse)
  1426. break;
  1427. }
  1428. }
  1429. mmput(start_mm);
  1430. return retval;
  1431. }
  1432. /*
  1433. * After a successful try_to_unuse, if no swap is now in use, we know
  1434. * we can empty the mmlist. swap_lock must be held on entry and exit.
  1435. * Note that mmlist_lock nests inside swap_lock, and an mm must be
  1436. * added to the mmlist just after page_duplicate - before would be racy.
  1437. */
  1438. static void drain_mmlist(void)
  1439. {
  1440. struct list_head *p, *next;
  1441. unsigned int type;
  1442. for (type = 0; type < nr_swapfiles; type++)
  1443. if (swap_info[type]->inuse_pages)
  1444. return;
  1445. spin_lock(&mmlist_lock);
  1446. list_for_each_safe(p, next, &init_mm.mmlist)
  1447. list_del_init(p);
  1448. spin_unlock(&mmlist_lock);
  1449. }
  1450. /*
  1451. * Use this swapdev's extent info to locate the (PAGE_SIZE) block which
  1452. * corresponds to page offset for the specified swap entry.
  1453. * Note that the type of this function is sector_t, but it returns page offset
  1454. * into the bdev, not sector offset.
  1455. */
  1456. static sector_t map_swap_entry(swp_entry_t entry, struct block_device **bdev)
  1457. {
  1458. struct swap_info_struct *sis;
  1459. struct swap_extent *start_se;
  1460. struct swap_extent *se;
  1461. pgoff_t offset;
  1462. sis = swap_info[swp_type(entry)];
  1463. *bdev = sis->bdev;
  1464. offset = swp_offset(entry);
  1465. start_se = sis->curr_swap_extent;
  1466. se = start_se;
  1467. for ( ; ; ) {
  1468. if (se->start_page <= offset &&
  1469. offset < (se->start_page + se->nr_pages)) {
  1470. return se->start_block + (offset - se->start_page);
  1471. }
  1472. se = list_next_entry(se, list);
  1473. sis->curr_swap_extent = se;
  1474. BUG_ON(se == start_se); /* It *must* be present */
  1475. }
  1476. }
  1477. /*
  1478. * Returns the page offset into bdev for the specified page's swap entry.
  1479. */
  1480. sector_t map_swap_page(struct page *page, struct block_device **bdev)
  1481. {
  1482. swp_entry_t entry;
  1483. entry.val = page_private(page);
  1484. return map_swap_entry(entry, bdev);
  1485. }
  1486. /*
  1487. * Free all of a swapdev's extent information
  1488. */
  1489. static void destroy_swap_extents(struct swap_info_struct *sis)
  1490. {
  1491. while (!list_empty(&sis->first_swap_extent.list)) {
  1492. struct swap_extent *se;
  1493. se = list_first_entry(&sis->first_swap_extent.list,
  1494. struct swap_extent, list);
  1495. list_del(&se->list);
  1496. kfree(se);
  1497. }
  1498. if (sis->flags & SWP_FILE) {
  1499. struct file *swap_file = sis->swap_file;
  1500. struct address_space *mapping = swap_file->f_mapping;
  1501. sis->flags &= ~SWP_FILE;
  1502. mapping->a_ops->swap_deactivate(swap_file);
  1503. }
  1504. }
  1505. /*
  1506. * Add a block range (and the corresponding page range) into this swapdev's
  1507. * extent list. The extent list is kept sorted in page order.
  1508. *
  1509. * This function rather assumes that it is called in ascending page order.
  1510. */
  1511. int
  1512. add_swap_extent(struct swap_info_struct *sis, unsigned long start_page,
  1513. unsigned long nr_pages, sector_t start_block)
  1514. {
  1515. struct swap_extent *se;
  1516. struct swap_extent *new_se;
  1517. struct list_head *lh;
  1518. if (start_page == 0) {
  1519. se = &sis->first_swap_extent;
  1520. sis->curr_swap_extent = se;
  1521. se->start_page = 0;
  1522. se->nr_pages = nr_pages;
  1523. se->start_block = start_block;
  1524. return 1;
  1525. } else {
  1526. lh = sis->first_swap_extent.list.prev; /* Highest extent */
  1527. se = list_entry(lh, struct swap_extent, list);
  1528. BUG_ON(se->start_page + se->nr_pages != start_page);
  1529. if (se->start_block + se->nr_pages == start_block) {
  1530. /* Merge it */
  1531. se->nr_pages += nr_pages;
  1532. return 0;
  1533. }
  1534. }
  1535. /*
  1536. * No merge. Insert a new extent, preserving ordering.
  1537. */
  1538. new_se = kmalloc(sizeof(*se), GFP_KERNEL);
  1539. if (new_se == NULL)
  1540. return -ENOMEM;
  1541. new_se->start_page = start_page;
  1542. new_se->nr_pages = nr_pages;
  1543. new_se->start_block = start_block;
  1544. list_add_tail(&new_se->list, &sis->first_swap_extent.list);
  1545. return 1;
  1546. }
  1547. /*
  1548. * A `swap extent' is a simple thing which maps a contiguous range of pages
  1549. * onto a contiguous range of disk blocks. An ordered list of swap extents
  1550. * is built at swapon time and is then used at swap_writepage/swap_readpage
  1551. * time for locating where on disk a page belongs.
  1552. *
  1553. * If the swapfile is an S_ISBLK block device, a single extent is installed.
  1554. * This is done so that the main operating code can treat S_ISBLK and S_ISREG
  1555. * swap files identically.
  1556. *
  1557. * Whether the swapdev is an S_ISREG file or an S_ISBLK blockdev, the swap
  1558. * extent list operates in PAGE_SIZE disk blocks. Both S_ISREG and S_ISBLK
  1559. * swapfiles are handled *identically* after swapon time.
  1560. *
  1561. * For S_ISREG swapfiles, setup_swap_extents() will walk all the file's blocks
  1562. * and will parse them into an ordered extent list, in PAGE_SIZE chunks. If
  1563. * some stray blocks are found which do not fall within the PAGE_SIZE alignment
  1564. * requirements, they are simply tossed out - we will never use those blocks
  1565. * for swapping.
  1566. *
  1567. * For S_ISREG swapfiles we set S_SWAPFILE across the life of the swapon. This
  1568. * prevents root from shooting her foot off by ftruncating an in-use swapfile,
  1569. * which will scribble on the fs.
  1570. *
  1571. * The amount of disk space which a single swap extent represents varies.
  1572. * Typically it is in the 1-4 megabyte range. So we can have hundreds of
  1573. * extents in the list. To avoid much list walking, we cache the previous
  1574. * search location in `curr_swap_extent', and start new searches from there.
  1575. * This is extremely effective. The average number of iterations in
  1576. * map_swap_page() has been measured at about 0.3 per page. - akpm.
  1577. */
  1578. static int setup_swap_extents(struct swap_info_struct *sis, sector_t *span)
  1579. {
  1580. struct file *swap_file = sis->swap_file;
  1581. struct address_space *mapping = swap_file->f_mapping;
  1582. struct inode *inode = mapping->host;
  1583. int ret;
  1584. if (S_ISBLK(inode->i_mode)) {
  1585. ret = add_swap_extent(sis, 0, sis->max, 0);
  1586. *span = sis->pages;
  1587. return ret;
  1588. }
  1589. if (mapping->a_ops->swap_activate) {
  1590. ret = mapping->a_ops->swap_activate(sis, swap_file, span);
  1591. if (!ret) {
  1592. sis->flags |= SWP_FILE;
  1593. ret = add_swap_extent(sis, 0, sis->max, 0);
  1594. *span = sis->pages;
  1595. }
  1596. return ret;
  1597. }
  1598. return generic_swapfile_activate(sis, swap_file, span);
  1599. }
  1600. static void _enable_swap_info(struct swap_info_struct *p, int prio,
  1601. unsigned char *swap_map,
  1602. struct swap_cluster_info *cluster_info)
  1603. {
  1604. if (prio >= 0)
  1605. p->prio = prio;
  1606. else
  1607. p->prio = --least_priority;
  1608. /*
  1609. * the plist prio is negated because plist ordering is
  1610. * low-to-high, while swap ordering is high-to-low
  1611. */
  1612. p->list.prio = -p->prio;
  1613. p->avail_list.prio = -p->prio;
  1614. p->swap_map = swap_map;
  1615. p->cluster_info = cluster_info;
  1616. p->flags |= SWP_WRITEOK;
  1617. atomic_long_add(p->pages, &nr_swap_pages);
  1618. total_swap_pages += p->pages;
  1619. assert_spin_locked(&swap_lock);
  1620. /*
  1621. * both lists are plists, and thus priority ordered.
  1622. * swap_active_head needs to be priority ordered for swapoff(),
  1623. * which on removal of any swap_info_struct with an auto-assigned
  1624. * (i.e. negative) priority increments the auto-assigned priority
  1625. * of any lower-priority swap_info_structs.
  1626. * swap_avail_head needs to be priority ordered for get_swap_page(),
  1627. * which allocates swap pages from the highest available priority
  1628. * swap_info_struct.
  1629. */
  1630. plist_add(&p->list, &swap_active_head);
  1631. spin_lock(&swap_avail_lock);
  1632. plist_add(&p->avail_list, &swap_avail_head);
  1633. spin_unlock(&swap_avail_lock);
  1634. }
  1635. static void enable_swap_info(struct swap_info_struct *p, int prio,
  1636. unsigned char *swap_map,
  1637. struct swap_cluster_info *cluster_info,
  1638. unsigned long *frontswap_map)
  1639. {
  1640. frontswap_init(p->type, frontswap_map);
  1641. spin_lock(&swap_lock);
  1642. spin_lock(&p->lock);
  1643. _enable_swap_info(p, prio, swap_map, cluster_info);
  1644. spin_unlock(&p->lock);
  1645. spin_unlock(&swap_lock);
  1646. }
  1647. static void reinsert_swap_info(struct swap_info_struct *p)
  1648. {
  1649. spin_lock(&swap_lock);
  1650. spin_lock(&p->lock);
  1651. _enable_swap_info(p, p->prio, p->swap_map, p->cluster_info);
  1652. spin_unlock(&p->lock);
  1653. spin_unlock(&swap_lock);
  1654. }
  1655. SYSCALL_DEFINE1(swapoff, const char __user *, specialfile)
  1656. {
  1657. struct swap_info_struct *p = NULL;
  1658. unsigned char *swap_map;
  1659. struct swap_cluster_info *cluster_info;
  1660. unsigned long *frontswap_map;
  1661. struct file *swap_file, *victim;
  1662. struct address_space *mapping;
  1663. struct inode *inode;
  1664. struct filename *pathname;
  1665. int err, found = 0;
  1666. unsigned int old_block_size;
  1667. if (!capable(CAP_SYS_ADMIN))
  1668. return -EPERM;
  1669. BUG_ON(!current->mm);
  1670. pathname = getname(specialfile);
  1671. if (IS_ERR(pathname))
  1672. return PTR_ERR(pathname);
  1673. victim = file_open_name(pathname, O_RDWR|O_LARGEFILE, 0);
  1674. err = PTR_ERR(victim);
  1675. if (IS_ERR(victim))
  1676. goto out;
  1677. mapping = victim->f_mapping;
  1678. spin_lock(&swap_lock);
  1679. plist_for_each_entry(p, &swap_active_head, list) {
  1680. if (p->flags & SWP_WRITEOK) {
  1681. if (p->swap_file->f_mapping == mapping) {
  1682. found = 1;
  1683. break;
  1684. }
  1685. }
  1686. }
  1687. if (!found) {
  1688. err = -EINVAL;
  1689. spin_unlock(&swap_lock);
  1690. goto out_dput;
  1691. }
  1692. if (!security_vm_enough_memory_mm(current->mm, p->pages))
  1693. vm_unacct_memory(p->pages);
  1694. else {
  1695. err = -ENOMEM;
  1696. spin_unlock(&swap_lock);
  1697. goto out_dput;
  1698. }
  1699. spin_lock(&swap_avail_lock);
  1700. plist_del(&p->avail_list, &swap_avail_head);
  1701. spin_unlock(&swap_avail_lock);
  1702. spin_lock(&p->lock);
  1703. if (p->prio < 0) {
  1704. struct swap_info_struct *si = p;
  1705. plist_for_each_entry_continue(si, &swap_active_head, list) {
  1706. si->prio++;
  1707. si->list.prio--;
  1708. si->avail_list.prio--;
  1709. }
  1710. least_priority++;
  1711. }
  1712. plist_del(&p->list, &swap_active_head);
  1713. atomic_long_sub(p->pages, &nr_swap_pages);
  1714. total_swap_pages -= p->pages;
  1715. p->flags &= ~SWP_WRITEOK;
  1716. spin_unlock(&p->lock);
  1717. spin_unlock(&swap_lock);
  1718. set_current_oom_origin();
  1719. err = try_to_unuse(p->type, false, 0); /* force unuse all pages */
  1720. clear_current_oom_origin();
  1721. if (err) {
  1722. /* re-insert swap space back into swap_list */
  1723. reinsert_swap_info(p);
  1724. goto out_dput;
  1725. }
  1726. flush_work(&p->discard_work);
  1727. destroy_swap_extents(p);
  1728. if (p->flags & SWP_CONTINUED)
  1729. free_swap_count_continuations(p);
  1730. mutex_lock(&swapon_mutex);
  1731. spin_lock(&swap_lock);
  1732. spin_lock(&p->lock);
  1733. drain_mmlist();
  1734. /* wait for anyone still in scan_swap_map */
  1735. p->highest_bit = 0; /* cuts scans short */
  1736. while (p->flags >= SWP_SCANNING) {
  1737. spin_unlock(&p->lock);
  1738. spin_unlock(&swap_lock);
  1739. schedule_timeout_uninterruptible(1);
  1740. spin_lock(&swap_lock);
  1741. spin_lock(&p->lock);
  1742. }
  1743. swap_file = p->swap_file;
  1744. old_block_size = p->old_block_size;
  1745. p->swap_file = NULL;
  1746. p->max = 0;
  1747. swap_map = p->swap_map;
  1748. p->swap_map = NULL;
  1749. cluster_info = p->cluster_info;
  1750. p->cluster_info = NULL;
  1751. frontswap_map = frontswap_map_get(p);
  1752. spin_unlock(&p->lock);
  1753. spin_unlock(&swap_lock);
  1754. frontswap_invalidate_area(p->type);
  1755. frontswap_map_set(p, NULL);
  1756. mutex_unlock(&swapon_mutex);
  1757. free_percpu(p->percpu_cluster);
  1758. p->percpu_cluster = NULL;
  1759. vfree(swap_map);
  1760. vfree(cluster_info);
  1761. vfree(frontswap_map);
  1762. /* Destroy swap account information */
  1763. swap_cgroup_swapoff(p->type);
  1764. inode = mapping->host;
  1765. if (S_ISBLK(inode->i_mode)) {
  1766. struct block_device *bdev = I_BDEV(inode);
  1767. set_blocksize(bdev, old_block_size);
  1768. blkdev_put(bdev, FMODE_READ | FMODE_WRITE | FMODE_EXCL);
  1769. } else {
  1770. inode_lock(inode);
  1771. inode->i_flags &= ~S_SWAPFILE;
  1772. inode_unlock(inode);
  1773. }
  1774. filp_close(swap_file, NULL);
  1775. /*
  1776. * Clear the SWP_USED flag after all resources are freed so that swapon
  1777. * can reuse this swap_info in alloc_swap_info() safely. It is ok to
  1778. * not hold p->lock after we cleared its SWP_WRITEOK.
  1779. */
  1780. spin_lock(&swap_lock);
  1781. p->flags = 0;
  1782. spin_unlock(&swap_lock);
  1783. err = 0;
  1784. atomic_inc(&proc_poll_event);
  1785. wake_up_interruptible(&proc_poll_wait);
  1786. out_dput:
  1787. filp_close(victim, NULL);
  1788. out:
  1789. putname(pathname);
  1790. return err;
  1791. }
  1792. #ifdef CONFIG_PROC_FS
  1793. static unsigned swaps_poll(struct file *file, poll_table *wait)
  1794. {
  1795. struct seq_file *seq = file->private_data;
  1796. poll_wait(file, &proc_poll_wait, wait);
  1797. if (seq->poll_event != atomic_read(&proc_poll_event)) {
  1798. seq->poll_event = atomic_read(&proc_poll_event);
  1799. return POLLIN | POLLRDNORM | POLLERR | POLLPRI;
  1800. }
  1801. return POLLIN | POLLRDNORM;
  1802. }
  1803. /* iterator */
  1804. static void *swap_start(struct seq_file *swap, loff_t *pos)
  1805. {
  1806. struct swap_info_struct *si;
  1807. int type;
  1808. loff_t l = *pos;
  1809. mutex_lock(&swapon_mutex);
  1810. if (!l)
  1811. return SEQ_START_TOKEN;
  1812. for (type = 0; type < nr_swapfiles; type++) {
  1813. smp_rmb(); /* read nr_swapfiles before swap_info[type] */
  1814. si = swap_info[type];
  1815. if (!(si->flags & SWP_USED) || !si->swap_map)
  1816. continue;
  1817. if (!--l)
  1818. return si;
  1819. }
  1820. return NULL;
  1821. }
  1822. static void *swap_next(struct seq_file *swap, void *v, loff_t *pos)
  1823. {
  1824. struct swap_info_struct *si = v;
  1825. int type;
  1826. if (v == SEQ_START_TOKEN)
  1827. type = 0;
  1828. else
  1829. type = si->type + 1;
  1830. for (; type < nr_swapfiles; type++) {
  1831. smp_rmb(); /* read nr_swapfiles before swap_info[type] */
  1832. si = swap_info[type];
  1833. if (!(si->flags & SWP_USED) || !si->swap_map)
  1834. continue;
  1835. ++*pos;
  1836. return si;
  1837. }
  1838. return NULL;
  1839. }
  1840. static void swap_stop(struct seq_file *swap, void *v)
  1841. {
  1842. mutex_unlock(&swapon_mutex);
  1843. }
  1844. static int swap_show(struct seq_file *swap, void *v)
  1845. {
  1846. struct swap_info_struct *si = v;
  1847. struct file *file;
  1848. int len;
  1849. if (si == SEQ_START_TOKEN) {
  1850. seq_puts(swap,"Filename\t\t\t\tType\t\tSize\tUsed\tPriority\n");
  1851. return 0;
  1852. }
  1853. file = si->swap_file;
  1854. len = seq_file_path(swap, file, " \t\n\\");
  1855. seq_printf(swap, "%*s%s\t%u\t%u\t%d\n",
  1856. len < 40 ? 40 - len : 1, " ",
  1857. S_ISBLK(file_inode(file)->i_mode) ?
  1858. "partition" : "file\t",
  1859. si->pages << (PAGE_SHIFT - 10),
  1860. si->inuse_pages << (PAGE_SHIFT - 10),
  1861. si->prio);
  1862. return 0;
  1863. }
  1864. static const struct seq_operations swaps_op = {
  1865. .start = swap_start,
  1866. .next = swap_next,
  1867. .stop = swap_stop,
  1868. .show = swap_show
  1869. };
  1870. static int swaps_open(struct inode *inode, struct file *file)
  1871. {
  1872. struct seq_file *seq;
  1873. int ret;
  1874. ret = seq_open(file, &swaps_op);
  1875. if (ret)
  1876. return ret;
  1877. seq = file->private_data;
  1878. seq->poll_event = atomic_read(&proc_poll_event);
  1879. return 0;
  1880. }
  1881. static const struct file_operations proc_swaps_operations = {
  1882. .open = swaps_open,
  1883. .read = seq_read,
  1884. .llseek = seq_lseek,
  1885. .release = seq_release,
  1886. .poll = swaps_poll,
  1887. };
  1888. static int __init procswaps_init(void)
  1889. {
  1890. proc_create("swaps", 0, NULL, &proc_swaps_operations);
  1891. return 0;
  1892. }
  1893. __initcall(procswaps_init);
  1894. #endif /* CONFIG_PROC_FS */
  1895. #ifdef MAX_SWAPFILES_CHECK
  1896. static int __init max_swapfiles_check(void)
  1897. {
  1898. MAX_SWAPFILES_CHECK();
  1899. return 0;
  1900. }
  1901. late_initcall(max_swapfiles_check);
  1902. #endif
  1903. static struct swap_info_struct *alloc_swap_info(void)
  1904. {
  1905. struct swap_info_struct *p;
  1906. unsigned int type;
  1907. p = kzalloc(sizeof(*p), GFP_KERNEL);
  1908. if (!p)
  1909. return ERR_PTR(-ENOMEM);
  1910. spin_lock(&swap_lock);
  1911. for (type = 0; type < nr_swapfiles; type++) {
  1912. if (!(swap_info[type]->flags & SWP_USED))
  1913. break;
  1914. }
  1915. if (type >= MAX_SWAPFILES) {
  1916. spin_unlock(&swap_lock);
  1917. kfree(p);
  1918. return ERR_PTR(-EPERM);
  1919. }
  1920. if (type >= nr_swapfiles) {
  1921. p->type = type;
  1922. swap_info[type] = p;
  1923. /*
  1924. * Write swap_info[type] before nr_swapfiles, in case a
  1925. * racing procfs swap_start() or swap_next() is reading them.
  1926. * (We never shrink nr_swapfiles, we never free this entry.)
  1927. */
  1928. smp_wmb();
  1929. nr_swapfiles++;
  1930. } else {
  1931. kfree(p);
  1932. p = swap_info[type];
  1933. /*
  1934. * Do not memset this entry: a racing procfs swap_next()
  1935. * would be relying on p->type to remain valid.
  1936. */
  1937. }
  1938. INIT_LIST_HEAD(&p->first_swap_extent.list);
  1939. plist_node_init(&p->list, 0);
  1940. plist_node_init(&p->avail_list, 0);
  1941. p->flags = SWP_USED;
  1942. spin_unlock(&swap_lock);
  1943. spin_lock_init(&p->lock);
  1944. return p;
  1945. }
  1946. static int claim_swapfile(struct swap_info_struct *p, struct inode *inode)
  1947. {
  1948. int error;
  1949. if (S_ISBLK(inode->i_mode)) {
  1950. p->bdev = bdgrab(I_BDEV(inode));
  1951. error = blkdev_get(p->bdev,
  1952. FMODE_READ | FMODE_WRITE | FMODE_EXCL, p);
  1953. if (error < 0) {
  1954. p->bdev = NULL;
  1955. return error;
  1956. }
  1957. p->old_block_size = block_size(p->bdev);
  1958. error = set_blocksize(p->bdev, PAGE_SIZE);
  1959. if (error < 0)
  1960. return error;
  1961. p->flags |= SWP_BLKDEV;
  1962. } else if (S_ISREG(inode->i_mode)) {
  1963. p->bdev = inode->i_sb->s_bdev;
  1964. inode_lock(inode);
  1965. if (IS_SWAPFILE(inode))
  1966. return -EBUSY;
  1967. } else
  1968. return -EINVAL;
  1969. return 0;
  1970. }
  1971. /*
  1972. * Find out how many pages are allowed for a single swap device. There
  1973. * are two limiting factors:
  1974. * 1) the number of bits for the swap offset in the swp_entry_t type, and
  1975. * 2) the number of bits in the swap pte, as defined by the different
  1976. * architectures.
  1977. *
  1978. * In order to find the largest possible bit mask, a swap entry with
  1979. * swap type 0 and swap offset ~0UL is created, encoded to a swap pte,
  1980. * decoded to a swp_entry_t again, and finally the swap offset is
  1981. * extracted.
  1982. *
  1983. * This will mask all the bits from the initial ~0UL mask that can't
  1984. * be encoded in either the swp_entry_t or the architecture definition
  1985. * of a swap pte.
  1986. */
  1987. unsigned long generic_max_swapfile_size(void)
  1988. {
  1989. return swp_offset(pte_to_swp_entry(
  1990. swp_entry_to_pte(swp_entry(0, ~0UL)))) + 1;
  1991. }
  1992. /* Can be overridden by an architecture for additional checks. */
  1993. __weak unsigned long max_swapfile_size(void)
  1994. {
  1995. return generic_max_swapfile_size();
  1996. }
  1997. static unsigned long read_swap_header(struct swap_info_struct *p,
  1998. union swap_header *swap_header,
  1999. struct inode *inode)
  2000. {
  2001. int i;
  2002. unsigned long maxpages;
  2003. unsigned long swapfilepages;
  2004. unsigned long last_page;
  2005. if (memcmp("SWAPSPACE2", swap_header->magic.magic, 10)) {
  2006. pr_err("Unable to find swap-space signature\n");
  2007. return 0;
  2008. }
  2009. /* swap partition endianess hack... */
  2010. if (swab32(swap_header->info.version) == 1) {
  2011. swab32s(&swap_header->info.version);
  2012. swab32s(&swap_header->info.last_page);
  2013. swab32s(&swap_header->info.nr_badpages);
  2014. if (swap_header->info.nr_badpages > MAX_SWAP_BADPAGES)
  2015. return 0;
  2016. for (i = 0; i < swap_header->info.nr_badpages; i++)
  2017. swab32s(&swap_header->info.badpages[i]);
  2018. }
  2019. /* Check the swap header's sub-version */
  2020. if (swap_header->info.version != 1) {
  2021. pr_warn("Unable to handle swap header version %d\n",
  2022. swap_header->info.version);
  2023. return 0;
  2024. }
  2025. p->lowest_bit = 1;
  2026. p->cluster_next = 1;
  2027. p->cluster_nr = 0;
  2028. maxpages = max_swapfile_size();
  2029. last_page = swap_header->info.last_page;
  2030. if (!last_page) {
  2031. pr_warn("Empty swap-file\n");
  2032. return 0;
  2033. }
  2034. if (last_page > maxpages) {
  2035. pr_warn("Truncating oversized swap area, only using %luk out of %luk\n",
  2036. maxpages << (PAGE_SHIFT - 10),
  2037. last_page << (PAGE_SHIFT - 10));
  2038. }
  2039. if (maxpages > last_page) {
  2040. maxpages = last_page + 1;
  2041. /* p->max is an unsigned int: don't overflow it */
  2042. if ((unsigned int)maxpages == 0)
  2043. maxpages = UINT_MAX;
  2044. }
  2045. p->highest_bit = maxpages - 1;
  2046. if (!maxpages)
  2047. return 0;
  2048. swapfilepages = i_size_read(inode) >> PAGE_SHIFT;
  2049. if (swapfilepages && maxpages > swapfilepages) {
  2050. pr_warn("Swap area shorter than signature indicates\n");
  2051. return 0;
  2052. }
  2053. if (swap_header->info.nr_badpages && S_ISREG(inode->i_mode))
  2054. return 0;
  2055. if (swap_header->info.nr_badpages > MAX_SWAP_BADPAGES)
  2056. return 0;
  2057. return maxpages;
  2058. }
  2059. static int setup_swap_map_and_extents(struct swap_info_struct *p,
  2060. union swap_header *swap_header,
  2061. unsigned char *swap_map,
  2062. struct swap_cluster_info *cluster_info,
  2063. unsigned long maxpages,
  2064. sector_t *span)
  2065. {
  2066. int i;
  2067. unsigned int nr_good_pages;
  2068. int nr_extents;
  2069. unsigned long nr_clusters = DIV_ROUND_UP(maxpages, SWAPFILE_CLUSTER);
  2070. unsigned long idx = p->cluster_next / SWAPFILE_CLUSTER;
  2071. nr_good_pages = maxpages - 1; /* omit header page */
  2072. cluster_list_init(&p->free_clusters);
  2073. cluster_list_init(&p->discard_clusters);
  2074. for (i = 0; i < swap_header->info.nr_badpages; i++) {
  2075. unsigned int page_nr = swap_header->info.badpages[i];
  2076. if (page_nr == 0 || page_nr > swap_header->info.last_page)
  2077. return -EINVAL;
  2078. if (page_nr < maxpages) {
  2079. swap_map[page_nr] = SWAP_MAP_BAD;
  2080. nr_good_pages--;
  2081. /*
  2082. * Haven't marked the cluster free yet, no list
  2083. * operation involved
  2084. */
  2085. inc_cluster_info_page(p, cluster_info, page_nr);
  2086. }
  2087. }
  2088. /* Haven't marked the cluster free yet, no list operation involved */
  2089. for (i = maxpages; i < round_up(maxpages, SWAPFILE_CLUSTER); i++)
  2090. inc_cluster_info_page(p, cluster_info, i);
  2091. if (nr_good_pages) {
  2092. swap_map[0] = SWAP_MAP_BAD;
  2093. /*
  2094. * Not mark the cluster free yet, no list
  2095. * operation involved
  2096. */
  2097. inc_cluster_info_page(p, cluster_info, 0);
  2098. p->max = maxpages;
  2099. p->pages = nr_good_pages;
  2100. nr_extents = setup_swap_extents(p, span);
  2101. if (nr_extents < 0)
  2102. return nr_extents;
  2103. nr_good_pages = p->pages;
  2104. }
  2105. if (!nr_good_pages) {
  2106. pr_warn("Empty swap-file\n");
  2107. return -EINVAL;
  2108. }
  2109. if (!cluster_info)
  2110. return nr_extents;
  2111. for (i = 0; i < nr_clusters; i++) {
  2112. if (!cluster_count(&cluster_info[idx])) {
  2113. cluster_set_flag(&cluster_info[idx], CLUSTER_FLAG_FREE);
  2114. cluster_list_add_tail(&p->free_clusters, cluster_info,
  2115. idx);
  2116. }
  2117. idx++;
  2118. if (idx == nr_clusters)
  2119. idx = 0;
  2120. }
  2121. return nr_extents;
  2122. }
  2123. /*
  2124. * Helper to sys_swapon determining if a given swap
  2125. * backing device queue supports DISCARD operations.
  2126. */
  2127. static bool swap_discardable(struct swap_info_struct *si)
  2128. {
  2129. struct request_queue *q = bdev_get_queue(si->bdev);
  2130. if (!q || !blk_queue_discard(q))
  2131. return false;
  2132. return true;
  2133. }
  2134. SYSCALL_DEFINE2(swapon, const char __user *, specialfile, int, swap_flags)
  2135. {
  2136. struct swap_info_struct *p;
  2137. struct filename *name;
  2138. struct file *swap_file = NULL;
  2139. struct address_space *mapping;
  2140. int prio;
  2141. int error;
  2142. union swap_header *swap_header;
  2143. int nr_extents;
  2144. sector_t span;
  2145. unsigned long maxpages;
  2146. unsigned char *swap_map = NULL;
  2147. struct swap_cluster_info *cluster_info = NULL;
  2148. unsigned long *frontswap_map = NULL;
  2149. struct page *page = NULL;
  2150. struct inode *inode = NULL;
  2151. if (swap_flags & ~SWAP_FLAGS_VALID)
  2152. return -EINVAL;
  2153. if (!capable(CAP_SYS_ADMIN))
  2154. return -EPERM;
  2155. p = alloc_swap_info();
  2156. if (IS_ERR(p))
  2157. return PTR_ERR(p);
  2158. INIT_WORK(&p->discard_work, swap_discard_work);
  2159. name = getname(specialfile);
  2160. if (IS_ERR(name)) {
  2161. error = PTR_ERR(name);
  2162. name = NULL;
  2163. goto bad_swap;
  2164. }
  2165. swap_file = file_open_name(name, O_RDWR|O_LARGEFILE, 0);
  2166. if (IS_ERR(swap_file)) {
  2167. error = PTR_ERR(swap_file);
  2168. swap_file = NULL;
  2169. goto bad_swap;
  2170. }
  2171. p->swap_file = swap_file;
  2172. mapping = swap_file->f_mapping;
  2173. inode = mapping->host;
  2174. /* If S_ISREG(inode->i_mode) will do inode_lock(inode); */
  2175. error = claim_swapfile(p, inode);
  2176. if (unlikely(error))
  2177. goto bad_swap;
  2178. /*
  2179. * Read the swap header.
  2180. */
  2181. if (!mapping->a_ops->readpage) {
  2182. error = -EINVAL;
  2183. goto bad_swap;
  2184. }
  2185. page = read_mapping_page(mapping, 0, swap_file);
  2186. if (IS_ERR(page)) {
  2187. error = PTR_ERR(page);
  2188. goto bad_swap;
  2189. }
  2190. swap_header = kmap(page);
  2191. maxpages = read_swap_header(p, swap_header, inode);
  2192. if (unlikely(!maxpages)) {
  2193. error = -EINVAL;
  2194. goto bad_swap;
  2195. }
  2196. /* OK, set up the swap map and apply the bad block list */
  2197. swap_map = vzalloc(maxpages);
  2198. if (!swap_map) {
  2199. error = -ENOMEM;
  2200. goto bad_swap;
  2201. }
  2202. if (bdi_cap_stable_pages_required(inode_to_bdi(inode)))
  2203. p->flags |= SWP_STABLE_WRITES;
  2204. if (p->bdev && blk_queue_nonrot(bdev_get_queue(p->bdev))) {
  2205. int cpu;
  2206. p->flags |= SWP_SOLIDSTATE;
  2207. /*
  2208. * select a random position to start with to help wear leveling
  2209. * SSD
  2210. */
  2211. p->cluster_next = 1 + (prandom_u32() % p->highest_bit);
  2212. cluster_info = vzalloc(DIV_ROUND_UP(maxpages,
  2213. SWAPFILE_CLUSTER) * sizeof(*cluster_info));
  2214. if (!cluster_info) {
  2215. error = -ENOMEM;
  2216. goto bad_swap;
  2217. }
  2218. p->percpu_cluster = alloc_percpu(struct percpu_cluster);
  2219. if (!p->percpu_cluster) {
  2220. error = -ENOMEM;
  2221. goto bad_swap;
  2222. }
  2223. for_each_possible_cpu(cpu) {
  2224. struct percpu_cluster *cluster;
  2225. cluster = per_cpu_ptr(p->percpu_cluster, cpu);
  2226. cluster_set_null(&cluster->index);
  2227. }
  2228. }
  2229. error = swap_cgroup_swapon(p->type, maxpages);
  2230. if (error)
  2231. goto bad_swap;
  2232. nr_extents = setup_swap_map_and_extents(p, swap_header, swap_map,
  2233. cluster_info, maxpages, &span);
  2234. if (unlikely(nr_extents < 0)) {
  2235. error = nr_extents;
  2236. goto bad_swap;
  2237. }
  2238. /* frontswap enabled? set up bit-per-page map for frontswap */
  2239. if (IS_ENABLED(CONFIG_FRONTSWAP))
  2240. frontswap_map = vzalloc(BITS_TO_LONGS(maxpages) * sizeof(long));
  2241. if (p->bdev &&(swap_flags & SWAP_FLAG_DISCARD) && swap_discardable(p)) {
  2242. /*
  2243. * When discard is enabled for swap with no particular
  2244. * policy flagged, we set all swap discard flags here in
  2245. * order to sustain backward compatibility with older
  2246. * swapon(8) releases.
  2247. */
  2248. p->flags |= (SWP_DISCARDABLE | SWP_AREA_DISCARD |
  2249. SWP_PAGE_DISCARD);
  2250. /*
  2251. * By flagging sys_swapon, a sysadmin can tell us to
  2252. * either do single-time area discards only, or to just
  2253. * perform discards for released swap page-clusters.
  2254. * Now it's time to adjust the p->flags accordingly.
  2255. */
  2256. if (swap_flags & SWAP_FLAG_DISCARD_ONCE)
  2257. p->flags &= ~SWP_PAGE_DISCARD;
  2258. else if (swap_flags & SWAP_FLAG_DISCARD_PAGES)
  2259. p->flags &= ~SWP_AREA_DISCARD;
  2260. /* issue a swapon-time discard if it's still required */
  2261. if (p->flags & SWP_AREA_DISCARD) {
  2262. int err = discard_swap(p);
  2263. if (unlikely(err))
  2264. pr_err("swapon: discard_swap(%p): %d\n",
  2265. p, err);
  2266. }
  2267. }
  2268. mutex_lock(&swapon_mutex);
  2269. prio = -1;
  2270. if (swap_flags & SWAP_FLAG_PREFER)
  2271. prio =
  2272. (swap_flags & SWAP_FLAG_PRIO_MASK) >> SWAP_FLAG_PRIO_SHIFT;
  2273. enable_swap_info(p, prio, swap_map, cluster_info, frontswap_map);
  2274. pr_info("Adding %uk swap on %s. Priority:%d extents:%d across:%lluk %s%s%s%s%s\n",
  2275. p->pages<<(PAGE_SHIFT-10), name->name, p->prio,
  2276. nr_extents, (unsigned long long)span<<(PAGE_SHIFT-10),
  2277. (p->flags & SWP_SOLIDSTATE) ? "SS" : "",
  2278. (p->flags & SWP_DISCARDABLE) ? "D" : "",
  2279. (p->flags & SWP_AREA_DISCARD) ? "s" : "",
  2280. (p->flags & SWP_PAGE_DISCARD) ? "c" : "",
  2281. (frontswap_map) ? "FS" : "");
  2282. mutex_unlock(&swapon_mutex);
  2283. atomic_inc(&proc_poll_event);
  2284. wake_up_interruptible(&proc_poll_wait);
  2285. if (S_ISREG(inode->i_mode))
  2286. inode->i_flags |= S_SWAPFILE;
  2287. error = 0;
  2288. goto out;
  2289. bad_swap:
  2290. free_percpu(p->percpu_cluster);
  2291. p->percpu_cluster = NULL;
  2292. if (inode && S_ISBLK(inode->i_mode) && p->bdev) {
  2293. set_blocksize(p->bdev, p->old_block_size);
  2294. blkdev_put(p->bdev, FMODE_READ | FMODE_WRITE | FMODE_EXCL);
  2295. }
  2296. destroy_swap_extents(p);
  2297. swap_cgroup_swapoff(p->type);
  2298. spin_lock(&swap_lock);
  2299. p->swap_file = NULL;
  2300. p->flags = 0;
  2301. spin_unlock(&swap_lock);
  2302. vfree(swap_map);
  2303. vfree(cluster_info);
  2304. if (swap_file) {
  2305. if (inode && S_ISREG(inode->i_mode)) {
  2306. inode_unlock(inode);
  2307. inode = NULL;
  2308. }
  2309. filp_close(swap_file, NULL);
  2310. }
  2311. out:
  2312. if (page && !IS_ERR(page)) {
  2313. kunmap(page);
  2314. put_page(page);
  2315. }
  2316. if (name)
  2317. putname(name);
  2318. if (inode && S_ISREG(inode->i_mode))
  2319. inode_unlock(inode);
  2320. return error;
  2321. }
  2322. void si_swapinfo(struct sysinfo *val)
  2323. {
  2324. unsigned int type;
  2325. unsigned long nr_to_be_unused = 0;
  2326. spin_lock(&swap_lock);
  2327. for (type = 0; type < nr_swapfiles; type++) {
  2328. struct swap_info_struct *si = swap_info[type];
  2329. if ((si->flags & SWP_USED) && !(si->flags & SWP_WRITEOK))
  2330. nr_to_be_unused += si->inuse_pages;
  2331. }
  2332. val->freeswap = atomic_long_read(&nr_swap_pages) + nr_to_be_unused;
  2333. val->totalswap = total_swap_pages + nr_to_be_unused;
  2334. spin_unlock(&swap_lock);
  2335. }
  2336. /*
  2337. * Verify that a swap entry is valid and increment its swap map count.
  2338. *
  2339. * Returns error code in following case.
  2340. * - success -> 0
  2341. * - swp_entry is invalid -> EINVAL
  2342. * - swp_entry is migration entry -> EINVAL
  2343. * - swap-cache reference is requested but there is already one. -> EEXIST
  2344. * - swap-cache reference is requested but the entry is not used. -> ENOENT
  2345. * - swap-mapped reference requested but needs continued swap count. -> ENOMEM
  2346. */
  2347. static int __swap_duplicate(swp_entry_t entry, unsigned char usage)
  2348. {
  2349. struct swap_info_struct *p;
  2350. unsigned long offset, type;
  2351. unsigned char count;
  2352. unsigned char has_cache;
  2353. int err = -EINVAL;
  2354. if (non_swap_entry(entry))
  2355. goto out;
  2356. type = swp_type(entry);
  2357. if (type >= nr_swapfiles)
  2358. goto bad_file;
  2359. p = swap_info[type];
  2360. offset = swp_offset(entry);
  2361. spin_lock(&p->lock);
  2362. if (unlikely(offset >= p->max))
  2363. goto unlock_out;
  2364. count = p->swap_map[offset];
  2365. /*
  2366. * swapin_readahead() doesn't check if a swap entry is valid, so the
  2367. * swap entry could be SWAP_MAP_BAD. Check here with lock held.
  2368. */
  2369. if (unlikely(swap_count(count) == SWAP_MAP_BAD)) {
  2370. err = -ENOENT;
  2371. goto unlock_out;
  2372. }
  2373. has_cache = count & SWAP_HAS_CACHE;
  2374. count &= ~SWAP_HAS_CACHE;
  2375. err = 0;
  2376. if (usage == SWAP_HAS_CACHE) {
  2377. /* set SWAP_HAS_CACHE if there is no cache and entry is used */
  2378. if (!has_cache && count)
  2379. has_cache = SWAP_HAS_CACHE;
  2380. else if (has_cache) /* someone else added cache */
  2381. err = -EEXIST;
  2382. else /* no users remaining */
  2383. err = -ENOENT;
  2384. } else if (count || has_cache) {
  2385. if ((count & ~COUNT_CONTINUED) < SWAP_MAP_MAX)
  2386. count += usage;
  2387. else if ((count & ~COUNT_CONTINUED) > SWAP_MAP_MAX)
  2388. err = -EINVAL;
  2389. else if (swap_count_continued(p, offset, count))
  2390. count = COUNT_CONTINUED;
  2391. else
  2392. err = -ENOMEM;
  2393. } else
  2394. err = -ENOENT; /* unused swap entry */
  2395. p->swap_map[offset] = count | has_cache;
  2396. unlock_out:
  2397. spin_unlock(&p->lock);
  2398. out:
  2399. return err;
  2400. bad_file:
  2401. pr_err("swap_dup: %s%08lx\n", Bad_file, entry.val);
  2402. goto out;
  2403. }
  2404. /*
  2405. * Help swapoff by noting that swap entry belongs to shmem/tmpfs
  2406. * (in which case its reference count is never incremented).
  2407. */
  2408. void swap_shmem_alloc(swp_entry_t entry)
  2409. {
  2410. __swap_duplicate(entry, SWAP_MAP_SHMEM);
  2411. }
  2412. /*
  2413. * Increase reference count of swap entry by 1.
  2414. * Returns 0 for success, or -ENOMEM if a swap_count_continuation is required
  2415. * but could not be atomically allocated. Returns 0, just as if it succeeded,
  2416. * if __swap_duplicate() fails for another reason (-EINVAL or -ENOENT), which
  2417. * might occur if a page table entry has got corrupted.
  2418. */
  2419. int swap_duplicate(swp_entry_t entry)
  2420. {
  2421. int err = 0;
  2422. while (!err && __swap_duplicate(entry, 1) == -ENOMEM)
  2423. err = add_swap_count_continuation(entry, GFP_ATOMIC);
  2424. return err;
  2425. }
  2426. /*
  2427. * @entry: swap entry for which we allocate swap cache.
  2428. *
  2429. * Called when allocating swap cache for existing swap entry,
  2430. * This can return error codes. Returns 0 at success.
  2431. * -EBUSY means there is a swap cache.
  2432. * Note: return code is different from swap_duplicate().
  2433. */
  2434. int swapcache_prepare(swp_entry_t entry)
  2435. {
  2436. return __swap_duplicate(entry, SWAP_HAS_CACHE);
  2437. }
  2438. struct swap_info_struct *page_swap_info(struct page *page)
  2439. {
  2440. swp_entry_t swap = { .val = page_private(page) };
  2441. return swap_info[swp_type(swap)];
  2442. }
  2443. /*
  2444. * out-of-line __page_file_ methods to avoid include hell.
  2445. */
  2446. struct address_space *__page_file_mapping(struct page *page)
  2447. {
  2448. VM_BUG_ON_PAGE(!PageSwapCache(page), page);
  2449. return page_swap_info(page)->swap_file->f_mapping;
  2450. }
  2451. EXPORT_SYMBOL_GPL(__page_file_mapping);
  2452. pgoff_t __page_file_index(struct page *page)
  2453. {
  2454. swp_entry_t swap = { .val = page_private(page) };
  2455. VM_BUG_ON_PAGE(!PageSwapCache(page), page);
  2456. return swp_offset(swap);
  2457. }
  2458. EXPORT_SYMBOL_GPL(__page_file_index);
  2459. /*
  2460. * add_swap_count_continuation - called when a swap count is duplicated
  2461. * beyond SWAP_MAP_MAX, it allocates a new page and links that to the entry's
  2462. * page of the original vmalloc'ed swap_map, to hold the continuation count
  2463. * (for that entry and for its neighbouring PAGE_SIZE swap entries). Called
  2464. * again when count is duplicated beyond SWAP_MAP_MAX * SWAP_CONT_MAX, etc.
  2465. *
  2466. * These continuation pages are seldom referenced: the common paths all work
  2467. * on the original swap_map, only referring to a continuation page when the
  2468. * low "digit" of a count is incremented or decremented through SWAP_MAP_MAX.
  2469. *
  2470. * add_swap_count_continuation(, GFP_ATOMIC) can be called while holding
  2471. * page table locks; if it fails, add_swap_count_continuation(, GFP_KERNEL)
  2472. * can be called after dropping locks.
  2473. */
  2474. int add_swap_count_continuation(swp_entry_t entry, gfp_t gfp_mask)
  2475. {
  2476. struct swap_info_struct *si;
  2477. struct page *head;
  2478. struct page *page;
  2479. struct page *list_page;
  2480. pgoff_t offset;
  2481. unsigned char count;
  2482. /*
  2483. * When debugging, it's easier to use __GFP_ZERO here; but it's better
  2484. * for latency not to zero a page while GFP_ATOMIC and holding locks.
  2485. */
  2486. page = alloc_page(gfp_mask | __GFP_HIGHMEM);
  2487. si = swap_info_get(entry);
  2488. if (!si) {
  2489. /*
  2490. * An acceptable race has occurred since the failing
  2491. * __swap_duplicate(): the swap entry has been freed,
  2492. * perhaps even the whole swap_map cleared for swapoff.
  2493. */
  2494. goto outer;
  2495. }
  2496. offset = swp_offset(entry);
  2497. count = si->swap_map[offset] & ~SWAP_HAS_CACHE;
  2498. if ((count & ~COUNT_CONTINUED) != SWAP_MAP_MAX) {
  2499. /*
  2500. * The higher the swap count, the more likely it is that tasks
  2501. * will race to add swap count continuation: we need to avoid
  2502. * over-provisioning.
  2503. */
  2504. goto out;
  2505. }
  2506. if (!page) {
  2507. spin_unlock(&si->lock);
  2508. return -ENOMEM;
  2509. }
  2510. /*
  2511. * We are fortunate that although vmalloc_to_page uses pte_offset_map,
  2512. * no architecture is using highmem pages for kernel page tables: so it
  2513. * will not corrupt the GFP_ATOMIC caller's atomic page table kmaps.
  2514. */
  2515. head = vmalloc_to_page(si->swap_map + offset);
  2516. offset &= ~PAGE_MASK;
  2517. /*
  2518. * Page allocation does not initialize the page's lru field,
  2519. * but it does always reset its private field.
  2520. */
  2521. if (!page_private(head)) {
  2522. BUG_ON(count & COUNT_CONTINUED);
  2523. INIT_LIST_HEAD(&head->lru);
  2524. set_page_private(head, SWP_CONTINUED);
  2525. si->flags |= SWP_CONTINUED;
  2526. }
  2527. list_for_each_entry(list_page, &head->lru, lru) {
  2528. unsigned char *map;
  2529. /*
  2530. * If the previous map said no continuation, but we've found
  2531. * a continuation page, free our allocation and use this one.
  2532. */
  2533. if (!(count & COUNT_CONTINUED))
  2534. goto out;
  2535. map = kmap_atomic(list_page) + offset;
  2536. count = *map;
  2537. kunmap_atomic(map);
  2538. /*
  2539. * If this continuation count now has some space in it,
  2540. * free our allocation and use this one.
  2541. */
  2542. if ((count & ~COUNT_CONTINUED) != SWAP_CONT_MAX)
  2543. goto out;
  2544. }
  2545. list_add_tail(&page->lru, &head->lru);
  2546. page = NULL; /* now it's attached, don't free it */
  2547. out:
  2548. spin_unlock(&si->lock);
  2549. outer:
  2550. if (page)
  2551. __free_page(page);
  2552. return 0;
  2553. }
  2554. /*
  2555. * swap_count_continued - when the original swap_map count is incremented
  2556. * from SWAP_MAP_MAX, check if there is already a continuation page to carry
  2557. * into, carry if so, or else fail until a new continuation page is allocated;
  2558. * when the original swap_map count is decremented from 0 with continuation,
  2559. * borrow from the continuation and report whether it still holds more.
  2560. * Called while __swap_duplicate() or swap_entry_free() holds swap_lock.
  2561. */
  2562. static bool swap_count_continued(struct swap_info_struct *si,
  2563. pgoff_t offset, unsigned char count)
  2564. {
  2565. struct page *head;
  2566. struct page *page;
  2567. unsigned char *map;
  2568. head = vmalloc_to_page(si->swap_map + offset);
  2569. if (page_private(head) != SWP_CONTINUED) {
  2570. BUG_ON(count & COUNT_CONTINUED);
  2571. return false; /* need to add count continuation */
  2572. }
  2573. offset &= ~PAGE_MASK;
  2574. page = list_entry(head->lru.next, struct page, lru);
  2575. map = kmap_atomic(page) + offset;
  2576. if (count == SWAP_MAP_MAX) /* initial increment from swap_map */
  2577. goto init_map; /* jump over SWAP_CONT_MAX checks */
  2578. if (count == (SWAP_MAP_MAX | COUNT_CONTINUED)) { /* incrementing */
  2579. /*
  2580. * Think of how you add 1 to 999
  2581. */
  2582. while (*map == (SWAP_CONT_MAX | COUNT_CONTINUED)) {
  2583. kunmap_atomic(map);
  2584. page = list_entry(page->lru.next, struct page, lru);
  2585. BUG_ON(page == head);
  2586. map = kmap_atomic(page) + offset;
  2587. }
  2588. if (*map == SWAP_CONT_MAX) {
  2589. kunmap_atomic(map);
  2590. page = list_entry(page->lru.next, struct page, lru);
  2591. if (page == head)
  2592. return false; /* add count continuation */
  2593. map = kmap_atomic(page) + offset;
  2594. init_map: *map = 0; /* we didn't zero the page */
  2595. }
  2596. *map += 1;
  2597. kunmap_atomic(map);
  2598. page = list_entry(page->lru.prev, struct page, lru);
  2599. while (page != head) {
  2600. map = kmap_atomic(page) + offset;
  2601. *map = COUNT_CONTINUED;
  2602. kunmap_atomic(map);
  2603. page = list_entry(page->lru.prev, struct page, lru);
  2604. }
  2605. return true; /* incremented */
  2606. } else { /* decrementing */
  2607. /*
  2608. * Think of how you subtract 1 from 1000
  2609. */
  2610. BUG_ON(count != COUNT_CONTINUED);
  2611. while (*map == COUNT_CONTINUED) {
  2612. kunmap_atomic(map);
  2613. page = list_entry(page->lru.next, struct page, lru);
  2614. BUG_ON(page == head);
  2615. map = kmap_atomic(page) + offset;
  2616. }
  2617. BUG_ON(*map == 0);
  2618. *map -= 1;
  2619. if (*map == 0)
  2620. count = 0;
  2621. kunmap_atomic(map);
  2622. page = list_entry(page->lru.prev, struct page, lru);
  2623. while (page != head) {
  2624. map = kmap_atomic(page) + offset;
  2625. *map = SWAP_CONT_MAX | count;
  2626. count = COUNT_CONTINUED;
  2627. kunmap_atomic(map);
  2628. page = list_entry(page->lru.prev, struct page, lru);
  2629. }
  2630. return count == COUNT_CONTINUED;
  2631. }
  2632. }
  2633. /*
  2634. * free_swap_count_continuations - swapoff free all the continuation pages
  2635. * appended to the swap_map, after swap_map is quiesced, before vfree'ing it.
  2636. */
  2637. static void free_swap_count_continuations(struct swap_info_struct *si)
  2638. {
  2639. pgoff_t offset;
  2640. for (offset = 0; offset < si->max; offset += PAGE_SIZE) {
  2641. struct page *head;
  2642. head = vmalloc_to_page(si->swap_map + offset);
  2643. if (page_private(head)) {
  2644. struct page *page, *next;
  2645. list_for_each_entry_safe(page, next, &head->lru, lru) {
  2646. list_del(&page->lru);
  2647. __free_page(page);
  2648. }
  2649. }
  2650. }
  2651. }