zswap.c 50 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802
  1. // SPDX-License-Identifier: GPL-2.0-or-later
  2. /*
  3. * zswap.c - zswap driver file
  4. *
  5. * zswap is a cache that takes pages that are in the process
  6. * of being swapped out and attempts to compress and store them in a
  7. * RAM-based memory pool. This can result in a significant I/O reduction on
  8. * the swap device and, in the case where decompressing from RAM is faster
  9. * than reading from the swap device, can also improve workload performance.
  10. *
  11. * Copyright (C) 2012 Seth Jennings <sjenning@linux.vnet.ibm.com>
  12. */
  13. #define pr_fmt(fmt) KBUILD_MODNAME ": " fmt
  14. #include <linux/module.h>
  15. #include <linux/cpu.h>
  16. #include <linux/highmem.h>
  17. #include <linux/slab.h>
  18. #include <linux/spinlock.h>
  19. #include <linux/types.h>
  20. #include <linux/atomic.h>
  21. #include <linux/swap.h>
  22. #include <linux/crypto.h>
  23. #include <linux/scatterlist.h>
  24. #include <linux/mempolicy.h>
  25. #include <linux/mempool.h>
  26. #include <linux/zpool.h>
  27. #include <crypto/acompress.h>
  28. #include <linux/zswap.h>
  29. #include <linux/mm_types.h>
  30. #include <linux/page-flags.h>
  31. #include <linux/swapops.h>
  32. #include <linux/writeback.h>
  33. #include <linux/pagemap.h>
  34. #include <linux/workqueue.h>
  35. #include <linux/list_lru.h>
  36. #include "swap.h"
  37. #include "internal.h"
  38. /*********************************
  39. * statistics
  40. **********************************/
  41. /* The number of compressed pages currently stored in zswap */
  42. atomic_t zswap_stored_pages = ATOMIC_INIT(0);
  43. /*
  44. * The statistics below are not protected from concurrent access for
  45. * performance reasons so they may not be a 100% accurate. However,
  46. * they do provide useful information on roughly how many times a
  47. * certain event is occurring.
  48. */
  49. /* Pool limit was hit (see zswap_max_pool_percent) */
  50. static u64 zswap_pool_limit_hit;
  51. /* Pages written back when pool limit was reached */
  52. static u64 zswap_written_back_pages;
  53. /* Store failed due to a reclaim failure after pool limit was reached */
  54. static u64 zswap_reject_reclaim_fail;
  55. /* Store failed due to compression algorithm failure */
  56. static u64 zswap_reject_compress_fail;
  57. /* Compressed page was too big for the allocator to (optimally) store */
  58. static u64 zswap_reject_compress_poor;
  59. /* Store failed because underlying allocator could not get memory */
  60. static u64 zswap_reject_alloc_fail;
  61. /* Store failed because the entry metadata could not be allocated (rare) */
  62. static u64 zswap_reject_kmemcache_fail;
  63. /* Shrinker work queue */
  64. static struct workqueue_struct *shrink_wq;
  65. /* Pool limit was hit, we need to calm down */
  66. static bool zswap_pool_reached_full;
  67. /*********************************
  68. * tunables
  69. **********************************/
  70. #define ZSWAP_PARAM_UNSET ""
  71. static int zswap_setup(void);
  72. /* Enable/disable zswap */
  73. static DEFINE_STATIC_KEY_MAYBE(CONFIG_ZSWAP_DEFAULT_ON, zswap_ever_enabled);
  74. static bool zswap_enabled = IS_ENABLED(CONFIG_ZSWAP_DEFAULT_ON);
  75. static int zswap_enabled_param_set(const char *,
  76. const struct kernel_param *);
  77. static const struct kernel_param_ops zswap_enabled_param_ops = {
  78. .set = zswap_enabled_param_set,
  79. .get = param_get_bool,
  80. };
  81. module_param_cb(enabled, &zswap_enabled_param_ops, &zswap_enabled, 0644);
  82. /* Crypto compressor to use */
  83. static char *zswap_compressor = CONFIG_ZSWAP_COMPRESSOR_DEFAULT;
  84. static int zswap_compressor_param_set(const char *,
  85. const struct kernel_param *);
  86. static const struct kernel_param_ops zswap_compressor_param_ops = {
  87. .set = zswap_compressor_param_set,
  88. .get = param_get_charp,
  89. .free = param_free_charp,
  90. };
  91. module_param_cb(compressor, &zswap_compressor_param_ops,
  92. &zswap_compressor, 0644);
  93. /* Compressed storage zpool to use */
  94. static char *zswap_zpool_type = CONFIG_ZSWAP_ZPOOL_DEFAULT;
  95. static int zswap_zpool_param_set(const char *, const struct kernel_param *);
  96. static const struct kernel_param_ops zswap_zpool_param_ops = {
  97. .set = zswap_zpool_param_set,
  98. .get = param_get_charp,
  99. .free = param_free_charp,
  100. };
  101. module_param_cb(zpool, &zswap_zpool_param_ops, &zswap_zpool_type, 0644);
  102. /* The maximum percentage of memory that the compressed pool can occupy */
  103. static unsigned int zswap_max_pool_percent = 20;
  104. module_param_named(max_pool_percent, zswap_max_pool_percent, uint, 0644);
  105. /* The threshold for accepting new pages after the max_pool_percent was hit */
  106. static unsigned int zswap_accept_thr_percent = 90; /* of max pool size */
  107. module_param_named(accept_threshold_percent, zswap_accept_thr_percent,
  108. uint, 0644);
  109. /* Enable/disable memory pressure-based shrinker. */
  110. static bool zswap_shrinker_enabled = IS_ENABLED(
  111. CONFIG_ZSWAP_SHRINKER_DEFAULT_ON);
  112. module_param_named(shrinker_enabled, zswap_shrinker_enabled, bool, 0644);
  113. bool zswap_is_enabled(void)
  114. {
  115. return zswap_enabled;
  116. }
  117. bool zswap_never_enabled(void)
  118. {
  119. return !static_branch_maybe(CONFIG_ZSWAP_DEFAULT_ON, &zswap_ever_enabled);
  120. }
  121. /*********************************
  122. * data structures
  123. **********************************/
  124. struct crypto_acomp_ctx {
  125. struct crypto_acomp *acomp;
  126. struct acomp_req *req;
  127. struct crypto_wait wait;
  128. u8 *buffer;
  129. struct mutex mutex;
  130. bool is_sleepable;
  131. };
  132. /*
  133. * The lock ordering is zswap_tree.lock -> zswap_pool.lru_lock.
  134. * The only case where lru_lock is not acquired while holding tree.lock is
  135. * when a zswap_entry is taken off the lru for writeback, in that case it
  136. * needs to be verified that it's still valid in the tree.
  137. */
  138. struct zswap_pool {
  139. struct zpool *zpool;
  140. struct crypto_acomp_ctx __percpu *acomp_ctx;
  141. struct percpu_ref ref;
  142. struct list_head list;
  143. struct work_struct release_work;
  144. struct hlist_node node;
  145. char tfm_name[CRYPTO_MAX_ALG_NAME];
  146. };
  147. /* Global LRU lists shared by all zswap pools. */
  148. static struct list_lru zswap_list_lru;
  149. /* The lock protects zswap_next_shrink updates. */
  150. static DEFINE_SPINLOCK(zswap_shrink_lock);
  151. static struct mem_cgroup *zswap_next_shrink;
  152. static struct work_struct zswap_shrink_work;
  153. static struct shrinker *zswap_shrinker;
  154. /*
  155. * struct zswap_entry
  156. *
  157. * This structure contains the metadata for tracking a single compressed
  158. * page within zswap.
  159. *
  160. * swpentry - associated swap entry, the offset indexes into the red-black tree
  161. * length - the length in bytes of the compressed page data. Needed during
  162. * decompression.
  163. * referenced - true if the entry recently entered the zswap pool. Unset by the
  164. * writeback logic. The entry is only reclaimed by the writeback
  165. * logic if referenced is unset. See comments in the shrinker
  166. * section for context.
  167. * pool - the zswap_pool the entry's data is in
  168. * handle - zpool allocation handle that stores the compressed page data
  169. * objcg - the obj_cgroup that the compressed memory is charged to
  170. * lru - handle to the pool's lru used to evict pages.
  171. */
  172. struct zswap_entry {
  173. swp_entry_t swpentry;
  174. unsigned int length;
  175. bool referenced;
  176. struct zswap_pool *pool;
  177. unsigned long handle;
  178. struct obj_cgroup *objcg;
  179. struct list_head lru;
  180. };
  181. static struct xarray *zswap_trees[MAX_SWAPFILES];
  182. static unsigned int nr_zswap_trees[MAX_SWAPFILES];
  183. /* RCU-protected iteration */
  184. static LIST_HEAD(zswap_pools);
  185. /* protects zswap_pools list modification */
  186. static DEFINE_SPINLOCK(zswap_pools_lock);
  187. /* pool counter to provide unique names to zpool */
  188. static atomic_t zswap_pools_count = ATOMIC_INIT(0);
  189. enum zswap_init_type {
  190. ZSWAP_UNINIT,
  191. ZSWAP_INIT_SUCCEED,
  192. ZSWAP_INIT_FAILED
  193. };
  194. static enum zswap_init_type zswap_init_state;
  195. /* used to ensure the integrity of initialization */
  196. static DEFINE_MUTEX(zswap_init_lock);
  197. /* init completed, but couldn't create the initial pool */
  198. static bool zswap_has_pool;
  199. /*********************************
  200. * helpers and fwd declarations
  201. **********************************/
  202. static inline struct xarray *swap_zswap_tree(swp_entry_t swp)
  203. {
  204. return &zswap_trees[swp_type(swp)][swp_offset(swp)
  205. >> SWAP_ADDRESS_SPACE_SHIFT];
  206. }
  207. #define zswap_pool_debug(msg, p) \
  208. pr_debug("%s pool %s/%s\n", msg, (p)->tfm_name, \
  209. zpool_get_type((p)->zpool))
  210. /*********************************
  211. * pool functions
  212. **********************************/
  213. static void __zswap_pool_empty(struct percpu_ref *ref);
  214. static struct zswap_pool *zswap_pool_create(char *type, char *compressor)
  215. {
  216. struct zswap_pool *pool;
  217. char name[38]; /* 'zswap' + 32 char (max) num + \0 */
  218. gfp_t gfp = __GFP_NORETRY | __GFP_NOWARN | __GFP_KSWAPD_RECLAIM;
  219. int ret, cpu;
  220. if (!zswap_has_pool) {
  221. /* if either are unset, pool initialization failed, and we
  222. * need both params to be set correctly before trying to
  223. * create a pool.
  224. */
  225. if (!strcmp(type, ZSWAP_PARAM_UNSET))
  226. return NULL;
  227. if (!strcmp(compressor, ZSWAP_PARAM_UNSET))
  228. return NULL;
  229. }
  230. pool = kzalloc(sizeof(*pool), GFP_KERNEL);
  231. if (!pool)
  232. return NULL;
  233. /* unique name for each pool specifically required by zsmalloc */
  234. snprintf(name, 38, "zswap%x", atomic_inc_return(&zswap_pools_count));
  235. pool->zpool = zpool_create_pool(type, name, gfp);
  236. if (!pool->zpool) {
  237. pr_err("%s zpool not available\n", type);
  238. goto error;
  239. }
  240. pr_debug("using %s zpool\n", zpool_get_type(pool->zpool));
  241. strscpy(pool->tfm_name, compressor, sizeof(pool->tfm_name));
  242. pool->acomp_ctx = alloc_percpu(*pool->acomp_ctx);
  243. if (!pool->acomp_ctx) {
  244. pr_err("percpu alloc failed\n");
  245. goto error;
  246. }
  247. for_each_possible_cpu(cpu)
  248. mutex_init(&per_cpu_ptr(pool->acomp_ctx, cpu)->mutex);
  249. ret = cpuhp_state_add_instance(CPUHP_MM_ZSWP_POOL_PREPARE,
  250. &pool->node);
  251. if (ret)
  252. goto error;
  253. /* being the current pool takes 1 ref; this func expects the
  254. * caller to always add the new pool as the current pool
  255. */
  256. ret = percpu_ref_init(&pool->ref, __zswap_pool_empty,
  257. PERCPU_REF_ALLOW_REINIT, GFP_KERNEL);
  258. if (ret)
  259. goto ref_fail;
  260. INIT_LIST_HEAD(&pool->list);
  261. zswap_pool_debug("created", pool);
  262. return pool;
  263. ref_fail:
  264. cpuhp_state_remove_instance(CPUHP_MM_ZSWP_POOL_PREPARE, &pool->node);
  265. error:
  266. if (pool->acomp_ctx)
  267. free_percpu(pool->acomp_ctx);
  268. if (pool->zpool)
  269. zpool_destroy_pool(pool->zpool);
  270. kfree(pool);
  271. return NULL;
  272. }
  273. static struct zswap_pool *__zswap_pool_create_fallback(void)
  274. {
  275. bool has_comp, has_zpool;
  276. has_comp = crypto_has_acomp(zswap_compressor, 0, 0);
  277. if (!has_comp && strcmp(zswap_compressor,
  278. CONFIG_ZSWAP_COMPRESSOR_DEFAULT)) {
  279. pr_err("compressor %s not available, using default %s\n",
  280. zswap_compressor, CONFIG_ZSWAP_COMPRESSOR_DEFAULT);
  281. param_free_charp(&zswap_compressor);
  282. zswap_compressor = CONFIG_ZSWAP_COMPRESSOR_DEFAULT;
  283. has_comp = crypto_has_acomp(zswap_compressor, 0, 0);
  284. }
  285. if (!has_comp) {
  286. pr_err("default compressor %s not available\n",
  287. zswap_compressor);
  288. param_free_charp(&zswap_compressor);
  289. zswap_compressor = ZSWAP_PARAM_UNSET;
  290. }
  291. has_zpool = zpool_has_pool(zswap_zpool_type);
  292. if (!has_zpool && strcmp(zswap_zpool_type,
  293. CONFIG_ZSWAP_ZPOOL_DEFAULT)) {
  294. pr_err("zpool %s not available, using default %s\n",
  295. zswap_zpool_type, CONFIG_ZSWAP_ZPOOL_DEFAULT);
  296. param_free_charp(&zswap_zpool_type);
  297. zswap_zpool_type = CONFIG_ZSWAP_ZPOOL_DEFAULT;
  298. has_zpool = zpool_has_pool(zswap_zpool_type);
  299. }
  300. if (!has_zpool) {
  301. pr_err("default zpool %s not available\n",
  302. zswap_zpool_type);
  303. param_free_charp(&zswap_zpool_type);
  304. zswap_zpool_type = ZSWAP_PARAM_UNSET;
  305. }
  306. if (!has_comp || !has_zpool)
  307. return NULL;
  308. return zswap_pool_create(zswap_zpool_type, zswap_compressor);
  309. }
  310. static void zswap_pool_destroy(struct zswap_pool *pool)
  311. {
  312. zswap_pool_debug("destroying", pool);
  313. cpuhp_state_remove_instance(CPUHP_MM_ZSWP_POOL_PREPARE, &pool->node);
  314. free_percpu(pool->acomp_ctx);
  315. zpool_destroy_pool(pool->zpool);
  316. kfree(pool);
  317. }
  318. static void __zswap_pool_release(struct work_struct *work)
  319. {
  320. struct zswap_pool *pool = container_of(work, typeof(*pool),
  321. release_work);
  322. synchronize_rcu();
  323. /* nobody should have been able to get a ref... */
  324. WARN_ON(!percpu_ref_is_zero(&pool->ref));
  325. percpu_ref_exit(&pool->ref);
  326. /* pool is now off zswap_pools list and has no references. */
  327. zswap_pool_destroy(pool);
  328. }
  329. static struct zswap_pool *zswap_pool_current(void);
  330. static void __zswap_pool_empty(struct percpu_ref *ref)
  331. {
  332. struct zswap_pool *pool;
  333. pool = container_of(ref, typeof(*pool), ref);
  334. spin_lock_bh(&zswap_pools_lock);
  335. WARN_ON(pool == zswap_pool_current());
  336. list_del_rcu(&pool->list);
  337. INIT_WORK(&pool->release_work, __zswap_pool_release);
  338. schedule_work(&pool->release_work);
  339. spin_unlock_bh(&zswap_pools_lock);
  340. }
  341. static int __must_check zswap_pool_get(struct zswap_pool *pool)
  342. {
  343. if (!pool)
  344. return 0;
  345. return percpu_ref_tryget(&pool->ref);
  346. }
  347. static void zswap_pool_put(struct zswap_pool *pool)
  348. {
  349. percpu_ref_put(&pool->ref);
  350. }
  351. static struct zswap_pool *__zswap_pool_current(void)
  352. {
  353. struct zswap_pool *pool;
  354. pool = list_first_or_null_rcu(&zswap_pools, typeof(*pool), list);
  355. WARN_ONCE(!pool && zswap_has_pool,
  356. "%s: no page storage pool!\n", __func__);
  357. return pool;
  358. }
  359. static struct zswap_pool *zswap_pool_current(void)
  360. {
  361. assert_spin_locked(&zswap_pools_lock);
  362. return __zswap_pool_current();
  363. }
  364. static struct zswap_pool *zswap_pool_current_get(void)
  365. {
  366. struct zswap_pool *pool;
  367. rcu_read_lock();
  368. pool = __zswap_pool_current();
  369. if (!zswap_pool_get(pool))
  370. pool = NULL;
  371. rcu_read_unlock();
  372. return pool;
  373. }
  374. /* type and compressor must be null-terminated */
  375. static struct zswap_pool *zswap_pool_find_get(char *type, char *compressor)
  376. {
  377. struct zswap_pool *pool;
  378. assert_spin_locked(&zswap_pools_lock);
  379. list_for_each_entry_rcu(pool, &zswap_pools, list) {
  380. if (strcmp(pool->tfm_name, compressor))
  381. continue;
  382. if (strcmp(zpool_get_type(pool->zpool), type))
  383. continue;
  384. /* if we can't get it, it's about to be destroyed */
  385. if (!zswap_pool_get(pool))
  386. continue;
  387. return pool;
  388. }
  389. return NULL;
  390. }
  391. static unsigned long zswap_max_pages(void)
  392. {
  393. return totalram_pages() * zswap_max_pool_percent / 100;
  394. }
  395. static unsigned long zswap_accept_thr_pages(void)
  396. {
  397. return zswap_max_pages() * zswap_accept_thr_percent / 100;
  398. }
  399. unsigned long zswap_total_pages(void)
  400. {
  401. struct zswap_pool *pool;
  402. unsigned long total = 0;
  403. rcu_read_lock();
  404. list_for_each_entry_rcu(pool, &zswap_pools, list)
  405. total += zpool_get_total_pages(pool->zpool);
  406. rcu_read_unlock();
  407. return total;
  408. }
  409. static bool zswap_check_limits(void)
  410. {
  411. unsigned long cur_pages = zswap_total_pages();
  412. unsigned long max_pages = zswap_max_pages();
  413. if (cur_pages >= max_pages) {
  414. zswap_pool_limit_hit++;
  415. zswap_pool_reached_full = true;
  416. } else if (zswap_pool_reached_full &&
  417. cur_pages <= zswap_accept_thr_pages()) {
  418. zswap_pool_reached_full = false;
  419. }
  420. return zswap_pool_reached_full;
  421. }
  422. /*********************************
  423. * param callbacks
  424. **********************************/
  425. static bool zswap_pool_changed(const char *s, const struct kernel_param *kp)
  426. {
  427. /* no change required */
  428. if (!strcmp(s, *(char **)kp->arg) && zswap_has_pool)
  429. return false;
  430. return true;
  431. }
  432. /* val must be a null-terminated string */
  433. static int __zswap_param_set(const char *val, const struct kernel_param *kp,
  434. char *type, char *compressor)
  435. {
  436. struct zswap_pool *pool, *put_pool = NULL;
  437. char *s = strstrip((char *)val);
  438. int ret = 0;
  439. bool new_pool = false;
  440. mutex_lock(&zswap_init_lock);
  441. switch (zswap_init_state) {
  442. case ZSWAP_UNINIT:
  443. /* if this is load-time (pre-init) param setting,
  444. * don't create a pool; that's done during init.
  445. */
  446. ret = param_set_charp(s, kp);
  447. break;
  448. case ZSWAP_INIT_SUCCEED:
  449. new_pool = zswap_pool_changed(s, kp);
  450. break;
  451. case ZSWAP_INIT_FAILED:
  452. pr_err("can't set param, initialization failed\n");
  453. ret = -ENODEV;
  454. }
  455. mutex_unlock(&zswap_init_lock);
  456. /* no need to create a new pool, return directly */
  457. if (!new_pool)
  458. return ret;
  459. if (!type) {
  460. if (!zpool_has_pool(s)) {
  461. pr_err("zpool %s not available\n", s);
  462. return -ENOENT;
  463. }
  464. type = s;
  465. } else if (!compressor) {
  466. if (!crypto_has_acomp(s, 0, 0)) {
  467. pr_err("compressor %s not available\n", s);
  468. return -ENOENT;
  469. }
  470. compressor = s;
  471. } else {
  472. WARN_ON(1);
  473. return -EINVAL;
  474. }
  475. spin_lock_bh(&zswap_pools_lock);
  476. pool = zswap_pool_find_get(type, compressor);
  477. if (pool) {
  478. zswap_pool_debug("using existing", pool);
  479. WARN_ON(pool == zswap_pool_current());
  480. list_del_rcu(&pool->list);
  481. }
  482. spin_unlock_bh(&zswap_pools_lock);
  483. if (!pool)
  484. pool = zswap_pool_create(type, compressor);
  485. else {
  486. /*
  487. * Restore the initial ref dropped by percpu_ref_kill()
  488. * when the pool was decommissioned and switch it again
  489. * to percpu mode.
  490. */
  491. percpu_ref_resurrect(&pool->ref);
  492. /* Drop the ref from zswap_pool_find_get(). */
  493. zswap_pool_put(pool);
  494. }
  495. if (pool)
  496. ret = param_set_charp(s, kp);
  497. else
  498. ret = -EINVAL;
  499. spin_lock_bh(&zswap_pools_lock);
  500. if (!ret) {
  501. put_pool = zswap_pool_current();
  502. list_add_rcu(&pool->list, &zswap_pools);
  503. zswap_has_pool = true;
  504. } else if (pool) {
  505. /* add the possibly pre-existing pool to the end of the pools
  506. * list; if it's new (and empty) then it'll be removed and
  507. * destroyed by the put after we drop the lock
  508. */
  509. list_add_tail_rcu(&pool->list, &zswap_pools);
  510. put_pool = pool;
  511. }
  512. spin_unlock_bh(&zswap_pools_lock);
  513. if (!zswap_has_pool && !pool) {
  514. /* if initial pool creation failed, and this pool creation also
  515. * failed, maybe both compressor and zpool params were bad.
  516. * Allow changing this param, so pool creation will succeed
  517. * when the other param is changed. We already verified this
  518. * param is ok in the zpool_has_pool() or crypto_has_acomp()
  519. * checks above.
  520. */
  521. ret = param_set_charp(s, kp);
  522. }
  523. /* drop the ref from either the old current pool,
  524. * or the new pool we failed to add
  525. */
  526. if (put_pool)
  527. percpu_ref_kill(&put_pool->ref);
  528. return ret;
  529. }
  530. static int zswap_compressor_param_set(const char *val,
  531. const struct kernel_param *kp)
  532. {
  533. return __zswap_param_set(val, kp, zswap_zpool_type, NULL);
  534. }
  535. static int zswap_zpool_param_set(const char *val,
  536. const struct kernel_param *kp)
  537. {
  538. return __zswap_param_set(val, kp, NULL, zswap_compressor);
  539. }
  540. static int zswap_enabled_param_set(const char *val,
  541. const struct kernel_param *kp)
  542. {
  543. int ret = -ENODEV;
  544. /* if this is load-time (pre-init) param setting, only set param. */
  545. if (system_state != SYSTEM_RUNNING)
  546. return param_set_bool(val, kp);
  547. mutex_lock(&zswap_init_lock);
  548. switch (zswap_init_state) {
  549. case ZSWAP_UNINIT:
  550. if (zswap_setup())
  551. break;
  552. fallthrough;
  553. case ZSWAP_INIT_SUCCEED:
  554. if (!zswap_has_pool)
  555. pr_err("can't enable, no pool configured\n");
  556. else
  557. ret = param_set_bool(val, kp);
  558. break;
  559. case ZSWAP_INIT_FAILED:
  560. pr_err("can't enable, initialization failed\n");
  561. }
  562. mutex_unlock(&zswap_init_lock);
  563. return ret;
  564. }
  565. /*********************************
  566. * lru functions
  567. **********************************/
  568. /* should be called under RCU */
  569. #ifdef CONFIG_MEMCG
  570. static inline struct mem_cgroup *mem_cgroup_from_entry(struct zswap_entry *entry)
  571. {
  572. return entry->objcg ? obj_cgroup_memcg(entry->objcg) : NULL;
  573. }
  574. #else
  575. static inline struct mem_cgroup *mem_cgroup_from_entry(struct zswap_entry *entry)
  576. {
  577. return NULL;
  578. }
  579. #endif
  580. static inline int entry_to_nid(struct zswap_entry *entry)
  581. {
  582. return page_to_nid(virt_to_page(entry));
  583. }
  584. static void zswap_lru_add(struct list_lru *list_lru, struct zswap_entry *entry)
  585. {
  586. int nid = entry_to_nid(entry);
  587. struct mem_cgroup *memcg;
  588. /*
  589. * Note that it is safe to use rcu_read_lock() here, even in the face of
  590. * concurrent memcg offlining. Thanks to the memcg->kmemcg_id indirection
  591. * used in list_lru lookup, only two scenarios are possible:
  592. *
  593. * 1. list_lru_add() is called before memcg->kmemcg_id is updated. The
  594. * new entry will be reparented to memcg's parent's list_lru.
  595. * 2. list_lru_add() is called after memcg->kmemcg_id is updated. The
  596. * new entry will be added directly to memcg's parent's list_lru.
  597. *
  598. * Similar reasoning holds for list_lru_del().
  599. */
  600. rcu_read_lock();
  601. memcg = mem_cgroup_from_entry(entry);
  602. /* will always succeed */
  603. list_lru_add(list_lru, &entry->lru, nid, memcg);
  604. rcu_read_unlock();
  605. }
  606. static void zswap_lru_del(struct list_lru *list_lru, struct zswap_entry *entry)
  607. {
  608. int nid = entry_to_nid(entry);
  609. struct mem_cgroup *memcg;
  610. rcu_read_lock();
  611. memcg = mem_cgroup_from_entry(entry);
  612. /* will always succeed */
  613. list_lru_del(list_lru, &entry->lru, nid, memcg);
  614. rcu_read_unlock();
  615. }
  616. void zswap_lruvec_state_init(struct lruvec *lruvec)
  617. {
  618. atomic_long_set(&lruvec->zswap_lruvec_state.nr_disk_swapins, 0);
  619. }
  620. void zswap_folio_swapin(struct folio *folio)
  621. {
  622. struct lruvec *lruvec;
  623. if (folio) {
  624. lruvec = folio_lruvec(folio);
  625. atomic_long_inc(&lruvec->zswap_lruvec_state.nr_disk_swapins);
  626. }
  627. }
  628. /*
  629. * This function should be called when a memcg is being offlined.
  630. *
  631. * Since the global shrinker shrink_worker() may hold a reference
  632. * of the memcg, we must check and release the reference in
  633. * zswap_next_shrink.
  634. *
  635. * shrink_worker() must handle the case where this function releases
  636. * the reference of memcg being shrunk.
  637. */
  638. void zswap_memcg_offline_cleanup(struct mem_cgroup *memcg)
  639. {
  640. /* lock out zswap shrinker walking memcg tree */
  641. spin_lock(&zswap_shrink_lock);
  642. if (zswap_next_shrink == memcg) {
  643. do {
  644. zswap_next_shrink = mem_cgroup_iter(NULL, zswap_next_shrink, NULL);
  645. } while (zswap_next_shrink && !mem_cgroup_online(zswap_next_shrink));
  646. }
  647. spin_unlock(&zswap_shrink_lock);
  648. }
  649. /*********************************
  650. * zswap entry functions
  651. **********************************/
  652. static struct kmem_cache *zswap_entry_cache;
  653. static struct zswap_entry *zswap_entry_cache_alloc(gfp_t gfp, int nid)
  654. {
  655. struct zswap_entry *entry;
  656. entry = kmem_cache_alloc_node(zswap_entry_cache, gfp, nid);
  657. if (!entry)
  658. return NULL;
  659. return entry;
  660. }
  661. static void zswap_entry_cache_free(struct zswap_entry *entry)
  662. {
  663. kmem_cache_free(zswap_entry_cache, entry);
  664. }
  665. /*
  666. * Carries out the common pattern of freeing and entry's zpool allocation,
  667. * freeing the entry itself, and decrementing the number of stored pages.
  668. */
  669. static void zswap_entry_free(struct zswap_entry *entry)
  670. {
  671. zswap_lru_del(&zswap_list_lru, entry);
  672. zpool_free(entry->pool->zpool, entry->handle);
  673. zswap_pool_put(entry->pool);
  674. if (entry->objcg) {
  675. obj_cgroup_uncharge_zswap(entry->objcg, entry->length);
  676. obj_cgroup_put(entry->objcg);
  677. }
  678. zswap_entry_cache_free(entry);
  679. atomic_dec(&zswap_stored_pages);
  680. }
  681. /*********************************
  682. * compressed storage functions
  683. **********************************/
  684. static int zswap_cpu_comp_prepare(unsigned int cpu, struct hlist_node *node)
  685. {
  686. struct zswap_pool *pool = hlist_entry(node, struct zswap_pool, node);
  687. struct crypto_acomp_ctx *acomp_ctx = per_cpu_ptr(pool->acomp_ctx, cpu);
  688. struct crypto_acomp *acomp = NULL;
  689. struct acomp_req *req = NULL;
  690. u8 *buffer = NULL;
  691. int ret;
  692. buffer = kmalloc_node(PAGE_SIZE * 2, GFP_KERNEL, cpu_to_node(cpu));
  693. if (!buffer) {
  694. ret = -ENOMEM;
  695. goto fail;
  696. }
  697. acomp = crypto_alloc_acomp_node(pool->tfm_name, 0, 0, cpu_to_node(cpu));
  698. if (IS_ERR(acomp)) {
  699. pr_err("could not alloc crypto acomp %s : %ld\n",
  700. pool->tfm_name, PTR_ERR(acomp));
  701. ret = PTR_ERR(acomp);
  702. goto fail;
  703. }
  704. req = acomp_request_alloc(acomp);
  705. if (!req) {
  706. pr_err("could not alloc crypto acomp_request %s\n",
  707. pool->tfm_name);
  708. ret = -ENOMEM;
  709. goto fail;
  710. }
  711. /*
  712. * Only hold the mutex after completing allocations, otherwise we may
  713. * recurse into zswap through reclaim and attempt to hold the mutex
  714. * again resulting in a deadlock.
  715. */
  716. mutex_lock(&acomp_ctx->mutex);
  717. crypto_init_wait(&acomp_ctx->wait);
  718. /*
  719. * if the backend of acomp is async zip, crypto_req_done() will wakeup
  720. * crypto_wait_req(); if the backend of acomp is scomp, the callback
  721. * won't be called, crypto_wait_req() will return without blocking.
  722. */
  723. acomp_request_set_callback(req, CRYPTO_TFM_REQ_MAY_BACKLOG,
  724. crypto_req_done, &acomp_ctx->wait);
  725. acomp_ctx->buffer = buffer;
  726. acomp_ctx->acomp = acomp;
  727. acomp_ctx->is_sleepable = acomp_is_async(acomp);
  728. acomp_ctx->req = req;
  729. mutex_unlock(&acomp_ctx->mutex);
  730. return 0;
  731. fail:
  732. if (acomp)
  733. crypto_free_acomp(acomp);
  734. kfree(buffer);
  735. return ret;
  736. }
  737. static int zswap_cpu_comp_dead(unsigned int cpu, struct hlist_node *node)
  738. {
  739. struct zswap_pool *pool = hlist_entry(node, struct zswap_pool, node);
  740. struct crypto_acomp_ctx *acomp_ctx = per_cpu_ptr(pool->acomp_ctx, cpu);
  741. mutex_lock(&acomp_ctx->mutex);
  742. if (!IS_ERR_OR_NULL(acomp_ctx)) {
  743. if (!IS_ERR_OR_NULL(acomp_ctx->req))
  744. acomp_request_free(acomp_ctx->req);
  745. acomp_ctx->req = NULL;
  746. if (!IS_ERR_OR_NULL(acomp_ctx->acomp))
  747. crypto_free_acomp(acomp_ctx->acomp);
  748. kfree(acomp_ctx->buffer);
  749. }
  750. mutex_unlock(&acomp_ctx->mutex);
  751. return 0;
  752. }
  753. static struct crypto_acomp_ctx *acomp_ctx_get_cpu_lock(struct zswap_pool *pool)
  754. {
  755. struct crypto_acomp_ctx *acomp_ctx;
  756. for (;;) {
  757. acomp_ctx = raw_cpu_ptr(pool->acomp_ctx);
  758. mutex_lock(&acomp_ctx->mutex);
  759. if (likely(acomp_ctx->req))
  760. return acomp_ctx;
  761. /*
  762. * It is possible that we were migrated to a different CPU after
  763. * getting the per-CPU ctx but before the mutex was acquired. If
  764. * the old CPU got offlined, zswap_cpu_comp_dead() could have
  765. * already freed ctx->req (among other things) and set it to
  766. * NULL. Just try again on the new CPU that we ended up on.
  767. */
  768. mutex_unlock(&acomp_ctx->mutex);
  769. }
  770. }
  771. static void acomp_ctx_put_unlock(struct crypto_acomp_ctx *acomp_ctx)
  772. {
  773. mutex_unlock(&acomp_ctx->mutex);
  774. }
  775. static bool zswap_compress(struct folio *folio, struct zswap_entry *entry)
  776. {
  777. struct crypto_acomp_ctx *acomp_ctx;
  778. struct scatterlist input, output;
  779. int comp_ret = 0, alloc_ret = 0;
  780. unsigned int dlen = PAGE_SIZE;
  781. unsigned long handle;
  782. struct zpool *zpool;
  783. char *buf;
  784. gfp_t gfp;
  785. u8 *dst;
  786. acomp_ctx = acomp_ctx_get_cpu_lock(entry->pool);
  787. dst = acomp_ctx->buffer;
  788. sg_init_table(&input, 1);
  789. sg_set_folio(&input, folio, PAGE_SIZE, 0);
  790. /*
  791. * We need PAGE_SIZE * 2 here since there maybe over-compression case,
  792. * and hardware-accelerators may won't check the dst buffer size, so
  793. * giving the dst buffer with enough length to avoid buffer overflow.
  794. */
  795. sg_init_one(&output, dst, PAGE_SIZE * 2);
  796. acomp_request_set_params(acomp_ctx->req, &input, &output, PAGE_SIZE, dlen);
  797. /*
  798. * it maybe looks a little bit silly that we send an asynchronous request,
  799. * then wait for its completion synchronously. This makes the process look
  800. * synchronous in fact.
  801. * Theoretically, acomp supports users send multiple acomp requests in one
  802. * acomp instance, then get those requests done simultaneously. but in this
  803. * case, zswap actually does store and load page by page, there is no
  804. * existing method to send the second page before the first page is done
  805. * in one thread doing zwap.
  806. * but in different threads running on different cpu, we have different
  807. * acomp instance, so multiple threads can do (de)compression in parallel.
  808. */
  809. comp_ret = crypto_wait_req(crypto_acomp_compress(acomp_ctx->req), &acomp_ctx->wait);
  810. dlen = acomp_ctx->req->dlen;
  811. if (comp_ret)
  812. goto unlock;
  813. zpool = entry->pool->zpool;
  814. gfp = __GFP_NORETRY | __GFP_NOWARN | __GFP_KSWAPD_RECLAIM;
  815. if (zpool_malloc_support_movable(zpool))
  816. gfp |= __GFP_HIGHMEM | __GFP_MOVABLE;
  817. alloc_ret = zpool_malloc(zpool, dlen, gfp, &handle);
  818. if (alloc_ret)
  819. goto unlock;
  820. buf = zpool_map_handle(zpool, handle, ZPOOL_MM_WO);
  821. memcpy(buf, dst, dlen);
  822. zpool_unmap_handle(zpool, handle);
  823. entry->handle = handle;
  824. entry->length = dlen;
  825. unlock:
  826. if (comp_ret == -ENOSPC || alloc_ret == -ENOSPC)
  827. zswap_reject_compress_poor++;
  828. else if (comp_ret)
  829. zswap_reject_compress_fail++;
  830. else if (alloc_ret)
  831. zswap_reject_alloc_fail++;
  832. acomp_ctx_put_unlock(acomp_ctx);
  833. return comp_ret == 0 && alloc_ret == 0;
  834. }
  835. static void zswap_decompress(struct zswap_entry *entry, struct folio *folio)
  836. {
  837. struct zpool *zpool = entry->pool->zpool;
  838. struct scatterlist input, output;
  839. struct crypto_acomp_ctx *acomp_ctx;
  840. u8 *src;
  841. acomp_ctx = acomp_ctx_get_cpu_lock(entry->pool);
  842. src = zpool_map_handle(zpool, entry->handle, ZPOOL_MM_RO);
  843. /*
  844. * If zpool_map_handle is atomic, we cannot reliably utilize its mapped buffer
  845. * to do crypto_acomp_decompress() which might sleep. In such cases, we must
  846. * resort to copying the buffer to a temporary one.
  847. * Meanwhile, zpool_map_handle() might return a non-linearly mapped buffer,
  848. * such as a kmap address of high memory or even ever a vmap address.
  849. * However, sg_init_one is only equipped to handle linearly mapped low memory.
  850. * In such cases, we also must copy the buffer to a temporary and lowmem one.
  851. */
  852. if ((acomp_ctx->is_sleepable && !zpool_can_sleep_mapped(zpool)) ||
  853. !virt_addr_valid(src)) {
  854. memcpy(acomp_ctx->buffer, src, entry->length);
  855. src = acomp_ctx->buffer;
  856. zpool_unmap_handle(zpool, entry->handle);
  857. }
  858. sg_init_one(&input, src, entry->length);
  859. sg_init_table(&output, 1);
  860. sg_set_folio(&output, folio, PAGE_SIZE, 0);
  861. acomp_request_set_params(acomp_ctx->req, &input, &output, entry->length, PAGE_SIZE);
  862. BUG_ON(crypto_wait_req(crypto_acomp_decompress(acomp_ctx->req), &acomp_ctx->wait));
  863. BUG_ON(acomp_ctx->req->dlen != PAGE_SIZE);
  864. if (src != acomp_ctx->buffer)
  865. zpool_unmap_handle(zpool, entry->handle);
  866. acomp_ctx_put_unlock(acomp_ctx);
  867. }
  868. /*********************************
  869. * writeback code
  870. **********************************/
  871. /*
  872. * Attempts to free an entry by adding a folio to the swap cache,
  873. * decompressing the entry data into the folio, and issuing a
  874. * bio write to write the folio back to the swap device.
  875. *
  876. * This can be thought of as a "resumed writeback" of the folio
  877. * to the swap device. We are basically resuming the same swap
  878. * writeback path that was intercepted with the zswap_store()
  879. * in the first place. After the folio has been decompressed into
  880. * the swap cache, the compressed version stored by zswap can be
  881. * freed.
  882. */
  883. static int zswap_writeback_entry(struct zswap_entry *entry,
  884. swp_entry_t swpentry)
  885. {
  886. struct xarray *tree;
  887. pgoff_t offset = swp_offset(swpentry);
  888. struct folio *folio;
  889. struct mempolicy *mpol;
  890. bool folio_was_allocated;
  891. struct writeback_control wbc = {
  892. .sync_mode = WB_SYNC_NONE,
  893. };
  894. /* try to allocate swap cache folio */
  895. mpol = get_task_policy(current);
  896. folio = __read_swap_cache_async(swpentry, GFP_KERNEL, mpol,
  897. NO_INTERLEAVE_INDEX, &folio_was_allocated, true);
  898. if (!folio)
  899. return -ENOMEM;
  900. /*
  901. * Found an existing folio, we raced with swapin or concurrent
  902. * shrinker. We generally writeback cold folios from zswap, and
  903. * swapin means the folio just became hot, so skip this folio.
  904. * For unlikely concurrent shrinker case, it will be unlinked
  905. * and freed when invalidated by the concurrent shrinker anyway.
  906. */
  907. if (!folio_was_allocated) {
  908. folio_put(folio);
  909. return -EEXIST;
  910. }
  911. /*
  912. * folio is locked, and the swapcache is now secured against
  913. * concurrent swapping to and from the slot, and concurrent
  914. * swapoff so we can safely dereference the zswap tree here.
  915. * Verify that the swap entry hasn't been invalidated and recycled
  916. * behind our backs, to avoid overwriting a new swap folio with
  917. * old compressed data. Only when this is successful can the entry
  918. * be dereferenced.
  919. */
  920. tree = swap_zswap_tree(swpentry);
  921. if (entry != xa_cmpxchg(tree, offset, entry, NULL, GFP_KERNEL)) {
  922. delete_from_swap_cache(folio);
  923. folio_unlock(folio);
  924. folio_put(folio);
  925. return -ENOMEM;
  926. }
  927. zswap_decompress(entry, folio);
  928. count_vm_event(ZSWPWB);
  929. if (entry->objcg)
  930. count_objcg_events(entry->objcg, ZSWPWB, 1);
  931. zswap_entry_free(entry);
  932. /* folio is up to date */
  933. folio_mark_uptodate(folio);
  934. /* move it to the tail of the inactive list after end_writeback */
  935. folio_set_reclaim(folio);
  936. /* start writeback */
  937. __swap_writepage(folio, &wbc);
  938. folio_put(folio);
  939. return 0;
  940. }
  941. /*********************************
  942. * shrinker functions
  943. **********************************/
  944. /*
  945. * The dynamic shrinker is modulated by the following factors:
  946. *
  947. * 1. Each zswap entry has a referenced bit, which the shrinker unsets (giving
  948. * the entry a second chance) before rotating it in the LRU list. If the
  949. * entry is considered again by the shrinker, with its referenced bit unset,
  950. * it is written back. The writeback rate as a result is dynamically
  951. * adjusted by the pool activities - if the pool is dominated by new entries
  952. * (i.e lots of recent zswapouts), these entries will be protected and
  953. * the writeback rate will slow down. On the other hand, if the pool has a
  954. * lot of stagnant entries, these entries will be reclaimed immediately,
  955. * effectively increasing the writeback rate.
  956. *
  957. * 2. Swapins counter: If we observe swapins, it is a sign that we are
  958. * overshrinking and should slow down. We maintain a swapins counter, which
  959. * is consumed and subtract from the number of eligible objects on the LRU
  960. * in zswap_shrinker_count().
  961. *
  962. * 3. Compression ratio. The better the workload compresses, the less gains we
  963. * can expect from writeback. We scale down the number of objects available
  964. * for reclaim by this ratio.
  965. */
  966. static enum lru_status shrink_memcg_cb(struct list_head *item, struct list_lru_one *l,
  967. spinlock_t *lock, void *arg)
  968. {
  969. struct zswap_entry *entry = container_of(item, struct zswap_entry, lru);
  970. bool *encountered_page_in_swapcache = (bool *)arg;
  971. swp_entry_t swpentry;
  972. enum lru_status ret = LRU_REMOVED_RETRY;
  973. int writeback_result;
  974. /*
  975. * Second chance algorithm: if the entry has its referenced bit set, give it
  976. * a second chance. Only clear the referenced bit and rotate it in the
  977. * zswap's LRU list.
  978. */
  979. if (entry->referenced) {
  980. entry->referenced = false;
  981. return LRU_ROTATE;
  982. }
  983. /*
  984. * As soon as we drop the LRU lock, the entry can be freed by
  985. * a concurrent invalidation. This means the following:
  986. *
  987. * 1. We extract the swp_entry_t to the stack, allowing
  988. * zswap_writeback_entry() to pin the swap entry and
  989. * then validate the zwap entry against that swap entry's
  990. * tree using pointer value comparison. Only when that
  991. * is successful can the entry be dereferenced.
  992. *
  993. * 2. Usually, objects are taken off the LRU for reclaim. In
  994. * this case this isn't possible, because if reclaim fails
  995. * for whatever reason, we have no means of knowing if the
  996. * entry is alive to put it back on the LRU.
  997. *
  998. * So rotate it before dropping the lock. If the entry is
  999. * written back or invalidated, the free path will unlink
  1000. * it. For failures, rotation is the right thing as well.
  1001. *
  1002. * Temporary failures, where the same entry should be tried
  1003. * again immediately, almost never happen for this shrinker.
  1004. * We don't do any trylocking; -ENOMEM comes closest,
  1005. * but that's extremely rare and doesn't happen spuriously
  1006. * either. Don't bother distinguishing this case.
  1007. */
  1008. list_move_tail(item, &l->list);
  1009. /*
  1010. * Once the lru lock is dropped, the entry might get freed. The
  1011. * swpentry is copied to the stack, and entry isn't deref'd again
  1012. * until the entry is verified to still be alive in the tree.
  1013. */
  1014. swpentry = entry->swpentry;
  1015. /*
  1016. * It's safe to drop the lock here because we return either
  1017. * LRU_REMOVED_RETRY or LRU_RETRY.
  1018. */
  1019. spin_unlock(lock);
  1020. writeback_result = zswap_writeback_entry(entry, swpentry);
  1021. if (writeback_result) {
  1022. zswap_reject_reclaim_fail++;
  1023. ret = LRU_RETRY;
  1024. /*
  1025. * Encountering a page already in swap cache is a sign that we are shrinking
  1026. * into the warmer region. We should terminate shrinking (if we're in the dynamic
  1027. * shrinker context).
  1028. */
  1029. if (writeback_result == -EEXIST && encountered_page_in_swapcache) {
  1030. ret = LRU_STOP;
  1031. *encountered_page_in_swapcache = true;
  1032. }
  1033. } else {
  1034. zswap_written_back_pages++;
  1035. }
  1036. spin_lock(lock);
  1037. return ret;
  1038. }
  1039. static unsigned long zswap_shrinker_scan(struct shrinker *shrinker,
  1040. struct shrink_control *sc)
  1041. {
  1042. unsigned long shrink_ret;
  1043. bool encountered_page_in_swapcache = false;
  1044. if (!zswap_shrinker_enabled ||
  1045. !mem_cgroup_zswap_writeback_enabled(sc->memcg)) {
  1046. sc->nr_scanned = 0;
  1047. return SHRINK_STOP;
  1048. }
  1049. shrink_ret = list_lru_shrink_walk(&zswap_list_lru, sc, &shrink_memcg_cb,
  1050. &encountered_page_in_swapcache);
  1051. if (encountered_page_in_swapcache)
  1052. return SHRINK_STOP;
  1053. return shrink_ret ? shrink_ret : SHRINK_STOP;
  1054. }
  1055. static unsigned long zswap_shrinker_count(struct shrinker *shrinker,
  1056. struct shrink_control *sc)
  1057. {
  1058. struct mem_cgroup *memcg = sc->memcg;
  1059. struct lruvec *lruvec = mem_cgroup_lruvec(memcg, NODE_DATA(sc->nid));
  1060. atomic_long_t *nr_disk_swapins =
  1061. &lruvec->zswap_lruvec_state.nr_disk_swapins;
  1062. unsigned long nr_backing, nr_stored, nr_freeable, nr_disk_swapins_cur,
  1063. nr_remain;
  1064. if (!zswap_shrinker_enabled || !mem_cgroup_zswap_writeback_enabled(memcg))
  1065. return 0;
  1066. /*
  1067. * The shrinker resumes swap writeback, which will enter block
  1068. * and may enter fs. XXX: Harmonize with vmscan.c __GFP_FS
  1069. * rules (may_enter_fs()), which apply on a per-folio basis.
  1070. */
  1071. if (!gfp_has_io_fs(sc->gfp_mask))
  1072. return 0;
  1073. /*
  1074. * For memcg, use the cgroup-wide ZSWAP stats since we don't
  1075. * have them per-node and thus per-lruvec. Careful if memcg is
  1076. * runtime-disabled: we can get sc->memcg == NULL, which is ok
  1077. * for the lruvec, but not for memcg_page_state().
  1078. *
  1079. * Without memcg, use the zswap pool-wide metrics.
  1080. */
  1081. if (!mem_cgroup_disabled()) {
  1082. mem_cgroup_flush_stats(memcg);
  1083. nr_backing = memcg_page_state(memcg, MEMCG_ZSWAP_B) >> PAGE_SHIFT;
  1084. nr_stored = memcg_page_state(memcg, MEMCG_ZSWAPPED);
  1085. } else {
  1086. nr_backing = zswap_total_pages();
  1087. nr_stored = atomic_read(&zswap_stored_pages);
  1088. }
  1089. if (!nr_stored)
  1090. return 0;
  1091. nr_freeable = list_lru_shrink_count(&zswap_list_lru, sc);
  1092. if (!nr_freeable)
  1093. return 0;
  1094. /*
  1095. * Subtract from the lru size the number of pages that are recently swapped
  1096. * in from disk. The idea is that had we protect the zswap's LRU by this
  1097. * amount of pages, these disk swapins would not have happened.
  1098. */
  1099. nr_disk_swapins_cur = atomic_long_read(nr_disk_swapins);
  1100. do {
  1101. if (nr_freeable >= nr_disk_swapins_cur)
  1102. nr_remain = 0;
  1103. else
  1104. nr_remain = nr_disk_swapins_cur - nr_freeable;
  1105. } while (!atomic_long_try_cmpxchg(
  1106. nr_disk_swapins, &nr_disk_swapins_cur, nr_remain));
  1107. nr_freeable -= nr_disk_swapins_cur - nr_remain;
  1108. if (!nr_freeable)
  1109. return 0;
  1110. /*
  1111. * Scale the number of freeable pages by the memory saving factor.
  1112. * This ensures that the better zswap compresses memory, the fewer
  1113. * pages we will evict to swap (as it will otherwise incur IO for
  1114. * relatively small memory saving).
  1115. */
  1116. return mult_frac(nr_freeable, nr_backing, nr_stored);
  1117. }
  1118. static struct shrinker *zswap_alloc_shrinker(void)
  1119. {
  1120. struct shrinker *shrinker;
  1121. shrinker =
  1122. shrinker_alloc(SHRINKER_NUMA_AWARE | SHRINKER_MEMCG_AWARE, "mm-zswap");
  1123. if (!shrinker)
  1124. return NULL;
  1125. shrinker->scan_objects = zswap_shrinker_scan;
  1126. shrinker->count_objects = zswap_shrinker_count;
  1127. shrinker->batch = 0;
  1128. shrinker->seeks = DEFAULT_SEEKS;
  1129. return shrinker;
  1130. }
  1131. static int shrink_memcg(struct mem_cgroup *memcg)
  1132. {
  1133. int nid, shrunk = 0, scanned = 0;
  1134. if (!mem_cgroup_zswap_writeback_enabled(memcg))
  1135. return -ENOENT;
  1136. /*
  1137. * Skip zombies because their LRUs are reparented and we would be
  1138. * reclaiming from the parent instead of the dead memcg.
  1139. */
  1140. if (memcg && !mem_cgroup_online(memcg))
  1141. return -ENOENT;
  1142. for_each_node_state(nid, N_NORMAL_MEMORY) {
  1143. unsigned long nr_to_walk = 1;
  1144. shrunk += list_lru_walk_one(&zswap_list_lru, nid, memcg,
  1145. &shrink_memcg_cb, NULL, &nr_to_walk);
  1146. scanned += 1 - nr_to_walk;
  1147. }
  1148. if (!scanned)
  1149. return -ENOENT;
  1150. return shrunk ? 0 : -EAGAIN;
  1151. }
  1152. static void shrink_worker(struct work_struct *w)
  1153. {
  1154. struct mem_cgroup *memcg;
  1155. int ret, failures = 0, attempts = 0;
  1156. unsigned long thr;
  1157. /* Reclaim down to the accept threshold */
  1158. thr = zswap_accept_thr_pages();
  1159. /*
  1160. * Global reclaim will select cgroup in a round-robin fashion from all
  1161. * online memcgs, but memcgs that have no pages in zswap and
  1162. * writeback-disabled memcgs (memory.zswap.writeback=0) are not
  1163. * candidates for shrinking.
  1164. *
  1165. * Shrinking will be aborted if we encounter the following
  1166. * MAX_RECLAIM_RETRIES times:
  1167. * - No writeback-candidate memcgs found in a memcg tree walk.
  1168. * - Shrinking a writeback-candidate memcg failed.
  1169. *
  1170. * We save iteration cursor memcg into zswap_next_shrink,
  1171. * which can be modified by the offline memcg cleaner
  1172. * zswap_memcg_offline_cleanup().
  1173. *
  1174. * Since the offline cleaner is called only once, we cannot leave an
  1175. * offline memcg reference in zswap_next_shrink.
  1176. * We can rely on the cleaner only if we get online memcg under lock.
  1177. *
  1178. * If we get an offline memcg, we cannot determine if the cleaner has
  1179. * already been called or will be called later. We must put back the
  1180. * reference before returning from this function. Otherwise, the
  1181. * offline memcg left in zswap_next_shrink will hold the reference
  1182. * until the next run of shrink_worker().
  1183. */
  1184. do {
  1185. /*
  1186. * Start shrinking from the next memcg after zswap_next_shrink.
  1187. * When the offline cleaner has already advanced the cursor,
  1188. * advancing the cursor here overlooks one memcg, but this
  1189. * should be negligibly rare.
  1190. *
  1191. * If we get an online memcg, keep the extra reference in case
  1192. * the original one obtained by mem_cgroup_iter() is dropped by
  1193. * zswap_memcg_offline_cleanup() while we are shrinking the
  1194. * memcg.
  1195. */
  1196. spin_lock(&zswap_shrink_lock);
  1197. do {
  1198. memcg = mem_cgroup_iter(NULL, zswap_next_shrink, NULL);
  1199. zswap_next_shrink = memcg;
  1200. } while (memcg && !mem_cgroup_tryget_online(memcg));
  1201. spin_unlock(&zswap_shrink_lock);
  1202. if (!memcg) {
  1203. /*
  1204. * Continue shrinking without incrementing failures if
  1205. * we found candidate memcgs in the last tree walk.
  1206. */
  1207. if (!attempts && ++failures == MAX_RECLAIM_RETRIES)
  1208. break;
  1209. attempts = 0;
  1210. goto resched;
  1211. }
  1212. ret = shrink_memcg(memcg);
  1213. /* drop the extra reference */
  1214. mem_cgroup_put(memcg);
  1215. /*
  1216. * There are no writeback-candidate pages in the memcg.
  1217. * This is not an issue as long as we can find another memcg
  1218. * with pages in zswap. Skip this without incrementing attempts
  1219. * and failures.
  1220. */
  1221. if (ret == -ENOENT)
  1222. continue;
  1223. ++attempts;
  1224. if (ret && ++failures == MAX_RECLAIM_RETRIES)
  1225. break;
  1226. resched:
  1227. cond_resched();
  1228. } while (zswap_total_pages() > thr);
  1229. }
  1230. /*********************************
  1231. * main API
  1232. **********************************/
  1233. bool zswap_store(struct folio *folio)
  1234. {
  1235. swp_entry_t swp = folio->swap;
  1236. pgoff_t offset = swp_offset(swp);
  1237. struct xarray *tree = swap_zswap_tree(swp);
  1238. struct zswap_entry *entry, *old;
  1239. struct obj_cgroup *objcg = NULL;
  1240. struct mem_cgroup *memcg = NULL;
  1241. VM_WARN_ON_ONCE(!folio_test_locked(folio));
  1242. VM_WARN_ON_ONCE(!folio_test_swapcache(folio));
  1243. /* Large folios aren't supported */
  1244. if (folio_test_large(folio))
  1245. return false;
  1246. if (!zswap_enabled)
  1247. goto check_old;
  1248. /* Check cgroup limits */
  1249. objcg = get_obj_cgroup_from_folio(folio);
  1250. if (objcg && !obj_cgroup_may_zswap(objcg)) {
  1251. memcg = get_mem_cgroup_from_objcg(objcg);
  1252. if (shrink_memcg(memcg)) {
  1253. mem_cgroup_put(memcg);
  1254. goto reject;
  1255. }
  1256. mem_cgroup_put(memcg);
  1257. }
  1258. if (zswap_check_limits())
  1259. goto reject;
  1260. /* allocate entry */
  1261. entry = zswap_entry_cache_alloc(GFP_KERNEL, folio_nid(folio));
  1262. if (!entry) {
  1263. zswap_reject_kmemcache_fail++;
  1264. goto reject;
  1265. }
  1266. /* if entry is successfully added, it keeps the reference */
  1267. entry->pool = zswap_pool_current_get();
  1268. if (!entry->pool)
  1269. goto freepage;
  1270. if (objcg) {
  1271. memcg = get_mem_cgroup_from_objcg(objcg);
  1272. if (memcg_list_lru_alloc(memcg, &zswap_list_lru, GFP_KERNEL)) {
  1273. mem_cgroup_put(memcg);
  1274. goto put_pool;
  1275. }
  1276. mem_cgroup_put(memcg);
  1277. }
  1278. if (!zswap_compress(folio, entry))
  1279. goto put_pool;
  1280. entry->swpentry = swp;
  1281. entry->objcg = objcg;
  1282. entry->referenced = true;
  1283. old = xa_store(tree, offset, entry, GFP_KERNEL);
  1284. if (xa_is_err(old)) {
  1285. int err = xa_err(old);
  1286. WARN_ONCE(err != -ENOMEM, "unexpected xarray error: %d\n", err);
  1287. zswap_reject_alloc_fail++;
  1288. goto store_failed;
  1289. }
  1290. /*
  1291. * We may have had an existing entry that became stale when
  1292. * the folio was redirtied and now the new version is being
  1293. * swapped out. Get rid of the old.
  1294. */
  1295. if (old)
  1296. zswap_entry_free(old);
  1297. if (objcg) {
  1298. obj_cgroup_charge_zswap(objcg, entry->length);
  1299. count_objcg_events(objcg, ZSWPOUT, 1);
  1300. }
  1301. /*
  1302. * We finish initializing the entry while it's already in xarray.
  1303. * This is safe because:
  1304. *
  1305. * 1. Concurrent stores and invalidations are excluded by folio lock.
  1306. *
  1307. * 2. Writeback is excluded by the entry not being on the LRU yet.
  1308. * The publishing order matters to prevent writeback from seeing
  1309. * an incoherent entry.
  1310. */
  1311. if (entry->length) {
  1312. INIT_LIST_HEAD(&entry->lru);
  1313. zswap_lru_add(&zswap_list_lru, entry);
  1314. }
  1315. /* update stats */
  1316. atomic_inc(&zswap_stored_pages);
  1317. count_vm_event(ZSWPOUT);
  1318. return true;
  1319. store_failed:
  1320. zpool_free(entry->pool->zpool, entry->handle);
  1321. put_pool:
  1322. zswap_pool_put(entry->pool);
  1323. freepage:
  1324. zswap_entry_cache_free(entry);
  1325. reject:
  1326. obj_cgroup_put(objcg);
  1327. if (zswap_pool_reached_full)
  1328. queue_work(shrink_wq, &zswap_shrink_work);
  1329. check_old:
  1330. /*
  1331. * If the zswap store fails or zswap is disabled, we must invalidate the
  1332. * possibly stale entry which was previously stored at this offset.
  1333. * Otherwise, writeback could overwrite the new data in the swapfile.
  1334. */
  1335. entry = xa_erase(tree, offset);
  1336. if (entry)
  1337. zswap_entry_free(entry);
  1338. return false;
  1339. }
  1340. bool zswap_load(struct folio *folio)
  1341. {
  1342. swp_entry_t swp = folio->swap;
  1343. pgoff_t offset = swp_offset(swp);
  1344. bool swapcache = folio_test_swapcache(folio);
  1345. struct xarray *tree = swap_zswap_tree(swp);
  1346. struct zswap_entry *entry;
  1347. VM_WARN_ON_ONCE(!folio_test_locked(folio));
  1348. if (zswap_never_enabled())
  1349. return false;
  1350. /*
  1351. * Large folios should not be swapped in while zswap is being used, as
  1352. * they are not properly handled. Zswap does not properly load large
  1353. * folios, and a large folio may only be partially in zswap.
  1354. *
  1355. * Return true without marking the folio uptodate so that an IO error is
  1356. * emitted (e.g. do_swap_page() will sigbus).
  1357. */
  1358. if (WARN_ON_ONCE(folio_test_large(folio)))
  1359. return true;
  1360. /*
  1361. * When reading into the swapcache, invalidate our entry. The
  1362. * swapcache can be the authoritative owner of the page and
  1363. * its mappings, and the pressure that results from having two
  1364. * in-memory copies outweighs any benefits of caching the
  1365. * compression work.
  1366. *
  1367. * (Most swapins go through the swapcache. The notable
  1368. * exception is the singleton fault on SWP_SYNCHRONOUS_IO
  1369. * files, which reads into a private page and may free it if
  1370. * the fault fails. We remain the primary owner of the entry.)
  1371. */
  1372. if (swapcache)
  1373. entry = xa_erase(tree, offset);
  1374. else
  1375. entry = xa_load(tree, offset);
  1376. if (!entry)
  1377. return false;
  1378. zswap_decompress(entry, folio);
  1379. count_vm_event(ZSWPIN);
  1380. if (entry->objcg)
  1381. count_objcg_events(entry->objcg, ZSWPIN, 1);
  1382. if (swapcache) {
  1383. zswap_entry_free(entry);
  1384. folio_mark_dirty(folio);
  1385. }
  1386. folio_mark_uptodate(folio);
  1387. return true;
  1388. }
  1389. void zswap_invalidate(swp_entry_t swp)
  1390. {
  1391. pgoff_t offset = swp_offset(swp);
  1392. struct xarray *tree = swap_zswap_tree(swp);
  1393. struct zswap_entry *entry;
  1394. entry = xa_erase(tree, offset);
  1395. if (entry)
  1396. zswap_entry_free(entry);
  1397. }
  1398. int zswap_swapon(int type, unsigned long nr_pages)
  1399. {
  1400. struct xarray *trees, *tree;
  1401. unsigned int nr, i;
  1402. nr = DIV_ROUND_UP(nr_pages, SWAP_ADDRESS_SPACE_PAGES);
  1403. trees = kvcalloc(nr, sizeof(*tree), GFP_KERNEL);
  1404. if (!trees) {
  1405. pr_err("alloc failed, zswap disabled for swap type %d\n", type);
  1406. return -ENOMEM;
  1407. }
  1408. for (i = 0; i < nr; i++)
  1409. xa_init(trees + i);
  1410. nr_zswap_trees[type] = nr;
  1411. zswap_trees[type] = trees;
  1412. return 0;
  1413. }
  1414. void zswap_swapoff(int type)
  1415. {
  1416. struct xarray *trees = zswap_trees[type];
  1417. unsigned int i;
  1418. if (!trees)
  1419. return;
  1420. /* try_to_unuse() invalidated all the entries already */
  1421. for (i = 0; i < nr_zswap_trees[type]; i++)
  1422. WARN_ON_ONCE(!xa_empty(trees + i));
  1423. kvfree(trees);
  1424. nr_zswap_trees[type] = 0;
  1425. zswap_trees[type] = NULL;
  1426. }
  1427. /*********************************
  1428. * debugfs functions
  1429. **********************************/
  1430. #ifdef CONFIG_DEBUG_FS
  1431. #include <linux/debugfs.h>
  1432. static struct dentry *zswap_debugfs_root;
  1433. static int debugfs_get_total_size(void *data, u64 *val)
  1434. {
  1435. *val = zswap_total_pages() * PAGE_SIZE;
  1436. return 0;
  1437. }
  1438. DEFINE_DEBUGFS_ATTRIBUTE(total_size_fops, debugfs_get_total_size, NULL, "%llu\n");
  1439. static int zswap_debugfs_init(void)
  1440. {
  1441. if (!debugfs_initialized())
  1442. return -ENODEV;
  1443. zswap_debugfs_root = debugfs_create_dir("zswap", NULL);
  1444. debugfs_create_u64("pool_limit_hit", 0444,
  1445. zswap_debugfs_root, &zswap_pool_limit_hit);
  1446. debugfs_create_u64("reject_reclaim_fail", 0444,
  1447. zswap_debugfs_root, &zswap_reject_reclaim_fail);
  1448. debugfs_create_u64("reject_alloc_fail", 0444,
  1449. zswap_debugfs_root, &zswap_reject_alloc_fail);
  1450. debugfs_create_u64("reject_kmemcache_fail", 0444,
  1451. zswap_debugfs_root, &zswap_reject_kmemcache_fail);
  1452. debugfs_create_u64("reject_compress_fail", 0444,
  1453. zswap_debugfs_root, &zswap_reject_compress_fail);
  1454. debugfs_create_u64("reject_compress_poor", 0444,
  1455. zswap_debugfs_root, &zswap_reject_compress_poor);
  1456. debugfs_create_u64("written_back_pages", 0444,
  1457. zswap_debugfs_root, &zswap_written_back_pages);
  1458. debugfs_create_file("pool_total_size", 0444,
  1459. zswap_debugfs_root, NULL, &total_size_fops);
  1460. debugfs_create_atomic_t("stored_pages", 0444,
  1461. zswap_debugfs_root, &zswap_stored_pages);
  1462. return 0;
  1463. }
  1464. #else
  1465. static int zswap_debugfs_init(void)
  1466. {
  1467. return 0;
  1468. }
  1469. #endif
  1470. /*********************************
  1471. * module init and exit
  1472. **********************************/
  1473. static int zswap_setup(void)
  1474. {
  1475. struct zswap_pool *pool;
  1476. int ret;
  1477. zswap_entry_cache = KMEM_CACHE(zswap_entry, 0);
  1478. if (!zswap_entry_cache) {
  1479. pr_err("entry cache creation failed\n");
  1480. goto cache_fail;
  1481. }
  1482. ret = cpuhp_setup_state_multi(CPUHP_MM_ZSWP_POOL_PREPARE,
  1483. "mm/zswap_pool:prepare",
  1484. zswap_cpu_comp_prepare,
  1485. zswap_cpu_comp_dead);
  1486. if (ret)
  1487. goto hp_fail;
  1488. shrink_wq = alloc_workqueue("zswap-shrink",
  1489. WQ_UNBOUND|WQ_MEM_RECLAIM, 1);
  1490. if (!shrink_wq)
  1491. goto shrink_wq_fail;
  1492. zswap_shrinker = zswap_alloc_shrinker();
  1493. if (!zswap_shrinker)
  1494. goto shrinker_fail;
  1495. if (list_lru_init_memcg(&zswap_list_lru, zswap_shrinker))
  1496. goto lru_fail;
  1497. shrinker_register(zswap_shrinker);
  1498. INIT_WORK(&zswap_shrink_work, shrink_worker);
  1499. pool = __zswap_pool_create_fallback();
  1500. if (pool) {
  1501. pr_info("loaded using pool %s/%s\n", pool->tfm_name,
  1502. zpool_get_type(pool->zpool));
  1503. list_add(&pool->list, &zswap_pools);
  1504. zswap_has_pool = true;
  1505. static_branch_enable(&zswap_ever_enabled);
  1506. } else {
  1507. pr_err("pool creation failed\n");
  1508. zswap_enabled = false;
  1509. }
  1510. if (zswap_debugfs_init())
  1511. pr_warn("debugfs initialization failed\n");
  1512. zswap_init_state = ZSWAP_INIT_SUCCEED;
  1513. return 0;
  1514. lru_fail:
  1515. shrinker_free(zswap_shrinker);
  1516. shrinker_fail:
  1517. destroy_workqueue(shrink_wq);
  1518. shrink_wq_fail:
  1519. cpuhp_remove_multi_state(CPUHP_MM_ZSWP_POOL_PREPARE);
  1520. hp_fail:
  1521. kmem_cache_destroy(zswap_entry_cache);
  1522. cache_fail:
  1523. /* if built-in, we aren't unloaded on failure; don't allow use */
  1524. zswap_init_state = ZSWAP_INIT_FAILED;
  1525. zswap_enabled = false;
  1526. return -ENOMEM;
  1527. }
  1528. static int __init zswap_init(void)
  1529. {
  1530. if (!zswap_enabled)
  1531. return 0;
  1532. return zswap_setup();
  1533. }
  1534. /* must be late so crypto has time to come up */
  1535. late_initcall(zswap_init);
  1536. MODULE_AUTHOR("Seth Jennings <sjennings@variantweb.net>");
  1537. MODULE_DESCRIPTION("Compressed cache for swap pages");