1 /*
2  * CDDL HEADER START
3  *
4  * The contents of this file are subject to the terms of the
5  * Common Development and Distribution License (the "License").
6  * You may not use this file except in compliance with the License.
7  *
8  * You can obtain a copy of the license at usr/src/OPENSOLARIS.LICENSE
9  * or https://opensource.org/licenses/CDDL-1.0.
10  * See the License for the specific language governing permissions
11  * and limitations under the License.
12  *
13  * When distributing Covered Code, include this CDDL HEADER in each
14  * file and include the License file at usr/src/OPENSOLARIS.LICENSE.
15  * If applicable, add the following below this CDDL HEADER, with the
16  * fields enclosed by brackets "[]" replaced with your own identifying
17  * information: Portions Copyright [yyyy] [name of copyright owner]
18  *
19  * CDDL HEADER END
20  */
21 /*
22  * Copyright (c) 2005, 2010, Oracle and/or its affiliates. All rights reserved.
23  * Copyright (c) 2018, Joyent, Inc.
24  * Copyright (c) 2011, 2019 by Delphix. All rights reserved.
25  * Copyright (c) 2014 by Saso Kiselkov. All rights reserved.
26  * Copyright 2017 Nexenta Systems, Inc.  All rights reserved.
27  */
28 
29 #include <sys/spa.h>
30 #include <sys/zio.h>
31 #include <sys/spa_impl.h>
32 #include <sys/zio_compress.h>
33 #include <sys/zio_checksum.h>
34 #include <sys/zfs_context.h>
35 #include <sys/arc.h>
36 #include <sys/zfs_refcount.h>
37 #include <sys/vdev.h>
38 #include <sys/vdev_trim.h>
39 #include <sys/vdev_impl.h>
40 #include <sys/dsl_pool.h>
41 #include <sys/multilist.h>
42 #include <sys/abd.h>
43 #include <sys/zil.h>
44 #include <sys/fm/fs/zfs.h>
45 #ifdef _KERNEL
46 #include <sys/shrinker.h>
47 #include <sys/vmsystm.h>
48 #include <sys/zpl.h>
49 #include <linux/page_compat.h>
50 #include <linux/notifier.h>
51 #include <linux/memory.h>
52 #endif
53 #include <sys/callb.h>
54 #include <sys/kstat.h>
55 #include <sys/zthr.h>
56 #include <zfs_fletcher.h>
57 #include <sys/arc_impl.h>
58 #include <sys/trace_zfs.h>
59 #include <sys/aggsum.h>
60 
61 /*
62  * This is a limit on how many pages the ARC shrinker makes available for
63  * eviction in response to one page allocation attempt.  Note that in
64  * practice, the kernel's shrinker can ask us to evict up to about 4x this
65  * for one allocation attempt.
66  *
67  * The default limit of 10,000 (in practice, 160MB per allocation attempt
68  * with 4K pages) limits the amount of time spent attempting to reclaim ARC
69  * memory to less than 100ms per allocation attempt, even with a small
70  * average compressed block size of ~8KB.
71  *
72  * See also the comment in arc_shrinker_count().
73  * Set to 0 to disable limit.
74  */
75 int zfs_arc_shrinker_limit = 10000;
76 
77 #ifdef CONFIG_MEMORY_HOTPLUG
78 static struct notifier_block arc_hotplug_callback_mem_nb;
79 #endif
80 
81 /*
82  * Return a default max arc size based on the amount of physical memory.
83  */
84 uint64_t
85 arc_default_max(uint64_t min, uint64_t allmem)
86 {
87 	/* Default to 1/2 of all memory. */
88 	return (MAX(allmem / 2, min));
89 }
90 
91 #ifdef _KERNEL
92 /*
93  * Return maximum amount of memory that we could possibly use.  Reduced
94  * to half of all memory in user space which is primarily used for testing.
95  */
96 uint64_t
97 arc_all_memory(void)
98 {
99 #ifdef CONFIG_HIGHMEM
100 	return (ptob(zfs_totalram_pages - zfs_totalhigh_pages));
101 #else
102 	return (ptob(zfs_totalram_pages));
103 #endif /* CONFIG_HIGHMEM */
104 }
105 
106 /*
107  * Return the amount of memory that is considered free.  In user space
108  * which is primarily used for testing we pretend that free memory ranges
109  * from 0-20% of all memory.
110  */
111 uint64_t
112 arc_free_memory(void)
113 {
114 #ifdef CONFIG_HIGHMEM
115 	struct sysinfo si;
116 	si_meminfo(&si);
117 	return (ptob(si.freeram - si.freehigh));
118 #else
119 	return (ptob(nr_free_pages() +
120 	    nr_inactive_file_pages()));
121 #endif /* CONFIG_HIGHMEM */
122 }
123 
124 /*
125  * Return the amount of memory that can be consumed before reclaim will be
126  * needed.  Positive if there is sufficient free memory, negative indicates
127  * the amount of memory that needs to be freed up.
128  */
129 int64_t
130 arc_available_memory(void)
131 {
132 	return (arc_free_memory() - arc_sys_free);
133 }
134 
135 static uint64_t
136 arc_evictable_memory(void)
137 {
138 	int64_t asize = aggsum_value(&arc_sums.arcstat_size);
139 	uint64_t arc_clean =
140 	    zfs_refcount_count(&arc_mru->arcs_esize[ARC_BUFC_DATA]) +
141 	    zfs_refcount_count(&arc_mru->arcs_esize[ARC_BUFC_METADATA]) +
142 	    zfs_refcount_count(&arc_mfu->arcs_esize[ARC_BUFC_DATA]) +
143 	    zfs_refcount_count(&arc_mfu->arcs_esize[ARC_BUFC_METADATA]);
144 	uint64_t arc_dirty = MAX((int64_t)asize - (int64_t)arc_clean, 0);
145 
146 	/*
147 	 * Scale reported evictable memory in proportion to page cache, cap
148 	 * at specified min/max.
149 	 */
150 	uint64_t min = (ptob(nr_file_pages()) / 100) * zfs_arc_pc_percent;
151 	min = MAX(arc_c_min, MIN(arc_c_max, min));
152 
153 	if (arc_dirty >= min)
154 		return (arc_clean);
155 
156 	return (MAX((int64_t)asize - (int64_t)min, 0));
157 }
158 
159 /*
160  * The _count() function returns the number of free-able objects.
161  * The _scan() function returns the number of objects that were freed.
162  */
163 static unsigned long
164 arc_shrinker_count(struct shrinker *shrink, struct shrink_control *sc)
165 {
166 	/*
167 	 * __GFP_FS won't be set if we are called from ZFS code (see
168 	 * kmem_flags_convert(), which removes it).  To avoid a deadlock, we
169 	 * don't allow evicting in this case.  We return 0 rather than
170 	 * SHRINK_STOP so that the shrinker logic doesn't accumulate a
171 	 * deficit against us.
172 	 */
173 	if (!(sc->gfp_mask & __GFP_FS)) {
174 		return (0);
175 	}
176 
177 	/*
178 	 * This code is reached in the "direct reclaim" case, where the
179 	 * kernel (outside ZFS) is trying to allocate a page, and the system
180 	 * is low on memory.
181 	 *
182 	 * The kernel's shrinker code doesn't understand how many pages the
183 	 * ARC's callback actually frees, so it may ask the ARC to shrink a
184 	 * lot for one page allocation. This is problematic because it may
185 	 * take a long time, thus delaying the page allocation, and because
186 	 * it may force the ARC to unnecessarily shrink very small.
187 	 *
188 	 * Therefore, we limit the amount of data that we say is evictable,
189 	 * which limits the amount that the shrinker will ask us to evict for
190 	 * one page allocation attempt.
191 	 *
192 	 * In practice, we may be asked to shrink 4x the limit to satisfy one
193 	 * page allocation, before the kernel's shrinker code gives up on us.
194 	 * When that happens, we rely on the kernel code to find the pages
195 	 * that we freed before invoking the OOM killer.  This happens in
196 	 * __alloc_pages_slowpath(), which retries and finds the pages we
197 	 * freed when it calls get_page_from_freelist().
198 	 *
199 	 * See also the comment above zfs_arc_shrinker_limit.
200 	 */
201 	int64_t limit = zfs_arc_shrinker_limit != 0 ?
202 	    zfs_arc_shrinker_limit : INT64_MAX;
203 	return (MIN(limit, btop((int64_t)arc_evictable_memory())));
204 }
205 
206 static unsigned long
207 arc_shrinker_scan(struct shrinker *shrink, struct shrink_control *sc)
208 {
209 	ASSERT((sc->gfp_mask & __GFP_FS) != 0);
210 
211 	/* The arc is considered warm once reclaim has occurred */
212 	if (unlikely(arc_warm == B_FALSE))
213 		arc_warm = B_TRUE;
214 
215 	/*
216 	 * Evict the requested number of pages by reducing arc_c and waiting
217 	 * for the requested amount of data to be evicted.
218 	 */
219 	arc_reduce_target_size(ptob(sc->nr_to_scan));
220 	arc_wait_for_eviction(ptob(sc->nr_to_scan), B_FALSE);
221 	if (current->reclaim_state != NULL)
222 #ifdef	HAVE_RECLAIM_STATE_RECLAIMED
223 		current->reclaim_state->reclaimed += sc->nr_to_scan;
224 #else
225 		current->reclaim_state->reclaimed_slab += sc->nr_to_scan;
226 #endif
227 
228 	/*
229 	 * We are experiencing memory pressure which the arc_evict_zthr was
230 	 * unable to keep up with. Set arc_no_grow to briefly pause arc
231 	 * growth to avoid compounding the memory pressure.
232 	 */
233 	arc_no_grow = B_TRUE;
234 
235 	/*
236 	 * When direct reclaim is observed it usually indicates a rapid
237 	 * increase in memory pressure.  This occurs because the kswapd
238 	 * threads were unable to asynchronously keep enough free memory
239 	 * available.
240 	 */
241 	if (current_is_kswapd()) {
242 		ARCSTAT_BUMP(arcstat_memory_indirect_count);
243 	} else {
244 		ARCSTAT_BUMP(arcstat_memory_direct_count);
245 	}
246 
247 	return (sc->nr_to_scan);
248 }
249 
250 SPL_SHRINKER_DECLARE(arc_shrinker,
251     arc_shrinker_count, arc_shrinker_scan, DEFAULT_SEEKS);
252 
253 int
254 arc_memory_throttle(spa_t *spa, uint64_t reserve, uint64_t txg)
255 {
256 	uint64_t free_memory = arc_free_memory();
257 
258 	if (free_memory > arc_all_memory() * arc_lotsfree_percent / 100)
259 		return (0);
260 
261 	if (txg > spa->spa_lowmem_last_txg) {
262 		spa->spa_lowmem_last_txg = txg;
263 		spa->spa_lowmem_page_load = 0;
264 	}
265 	/*
266 	 * If we are in pageout, we know that memory is already tight,
267 	 * the arc is already going to be evicting, so we just want to
268 	 * continue to let page writes occur as quickly as possible.
269 	 */
270 	if (current_is_kswapd()) {
271 		if (spa->spa_lowmem_page_load >
272 		    MAX(arc_sys_free / 4, free_memory) / 4) {
273 			DMU_TX_STAT_BUMP(dmu_tx_memory_reclaim);
274 			return (SET_ERROR(ERESTART));
275 		}
276 		/* Note: reserve is inflated, so we deflate */
277 		atomic_add_64(&spa->spa_lowmem_page_load, reserve / 8);
278 		return (0);
279 	} else if (spa->spa_lowmem_page_load > 0 && arc_reclaim_needed()) {
280 		/* memory is low, delay before restarting */
281 		ARCSTAT_INCR(arcstat_memory_throttle_count, 1);
282 		DMU_TX_STAT_BUMP(dmu_tx_memory_reclaim);
283 		return (SET_ERROR(EAGAIN));
284 	}
285 	spa->spa_lowmem_page_load = 0;
286 	return (0);
287 }
288 
289 static void
290 arc_set_sys_free(uint64_t allmem)
291 {
292 	/*
293 	 * The ARC tries to keep at least this much memory available for the
294 	 * system.  This gives the ARC time to shrink in response to memory
295 	 * pressure, before running completely out of memory and invoking the
296 	 * direct-reclaim ARC shrinker.
297 	 *
298 	 * This should be more than twice high_wmark_pages(), so that
299 	 * arc_wait_for_eviction() will wait until at least the
300 	 * high_wmark_pages() are free (see arc_evict_state_impl()).
301 	 *
302 	 * Note: Even when the system is very low on memory, the kernel's
303 	 * shrinker code may only ask for one "batch" of pages (512KB) to be
304 	 * evicted.  If concurrent allocations consume these pages, there may
305 	 * still be insufficient free pages, and the OOM killer takes action.
306 	 *
307 	 * By setting arc_sys_free large enough, and having
308 	 * arc_wait_for_eviction() wait until there is at least arc_sys_free/2
309 	 * free memory, it is much less likely that concurrent allocations can
310 	 * consume all the memory that was evicted before checking for
311 	 * OOM.
312 	 *
313 	 * It's hard to iterate the zones from a linux kernel module, which
314 	 * makes it difficult to determine the watermark dynamically. Instead
315 	 * we compute the maximum high watermark for this system, based
316 	 * on the amount of memory, assuming default parameters on Linux kernel
317 	 * 5.3.
318 	 */
319 
320 	/*
321 	 * Base wmark_low is 4 * the square root of Kbytes of RAM.
322 	 */
323 	long wmark = 4 * int_sqrt(allmem/1024) * 1024;
324 
325 	/*
326 	 * Clamp to between 128K and 64MB.
327 	 */
328 	wmark = MAX(wmark, 128 * 1024);
329 	wmark = MIN(wmark, 64 * 1024 * 1024);
330 
331 	/*
332 	 * watermark_boost can increase the wmark by up to 150%.
333 	 */
334 	wmark += wmark * 150 / 100;
335 
336 	/*
337 	 * arc_sys_free needs to be more than 2x the watermark, because
338 	 * arc_wait_for_eviction() waits for half of arc_sys_free.  Bump this up
339 	 * to 3x to ensure we're above it.
340 	 */
341 	arc_sys_free = wmark * 3 + allmem / 32;
342 }
343 
344 void
345 arc_lowmem_init(void)
346 {
347 	uint64_t allmem = arc_all_memory();
348 
349 	/*
350 	 * Register a shrinker to support synchronous (direct) memory
351 	 * reclaim from the arc.  This is done to prevent kswapd from
352 	 * swapping out pages when it is preferable to shrink the arc.
353 	 */
354 	spl_register_shrinker(&arc_shrinker);
355 	arc_set_sys_free(allmem);
356 }
357 
358 void
359 arc_lowmem_fini(void)
360 {
361 	spl_unregister_shrinker(&arc_shrinker);
362 }
363 
364 int
365 param_set_arc_u64(const char *buf, zfs_kernel_param_t *kp)
366 {
367 	int error;
368 
369 	error = spl_param_set_u64(buf, kp);
370 	if (error < 0)
371 		return (SET_ERROR(error));
372 
373 	arc_tuning_update(B_TRUE);
374 
375 	return (0);
376 }
377 
378 int
379 param_set_arc_min(const char *buf, zfs_kernel_param_t *kp)
380 {
381 	return (param_set_arc_u64(buf, kp));
382 }
383 
384 int
385 param_set_arc_max(const char *buf, zfs_kernel_param_t *kp)
386 {
387 	return (param_set_arc_u64(buf, kp));
388 }
389 
390 int
391 param_set_arc_int(const char *buf, zfs_kernel_param_t *kp)
392 {
393 	int error;
394 
395 	error = param_set_int(buf, kp);
396 	if (error < 0)
397 		return (SET_ERROR(error));
398 
399 	arc_tuning_update(B_TRUE);
400 
401 	return (0);
402 }
403 
404 #ifdef CONFIG_MEMORY_HOTPLUG
405 static int
406 arc_hotplug_callback(struct notifier_block *self, unsigned long action,
407     void *arg)
408 {
409 	(void) self, (void) arg;
410 	uint64_t allmem = arc_all_memory();
411 	if (action != MEM_ONLINE)
412 		return (NOTIFY_OK);
413 
414 	arc_set_limits(allmem);
415 
416 #ifdef __LP64__
417 	if (zfs_dirty_data_max_max == 0)
418 		zfs_dirty_data_max_max = MIN(4ULL * 1024 * 1024 * 1024,
419 		    allmem * zfs_dirty_data_max_max_percent / 100);
420 #else
421 	if (zfs_dirty_data_max_max == 0)
422 		zfs_dirty_data_max_max = MIN(1ULL * 1024 * 1024 * 1024,
423 		    allmem * zfs_dirty_data_max_max_percent / 100);
424 #endif
425 
426 	arc_set_sys_free(allmem);
427 	return (NOTIFY_OK);
428 }
429 #endif
430 
431 void
432 arc_register_hotplug(void)
433 {
434 #ifdef CONFIG_MEMORY_HOTPLUG
435 	arc_hotplug_callback_mem_nb.notifier_call = arc_hotplug_callback;
436 	/* There is no significance to the value 100 */
437 	arc_hotplug_callback_mem_nb.priority = 100;
438 	register_memory_notifier(&arc_hotplug_callback_mem_nb);
439 #endif
440 }
441 
442 void
443 arc_unregister_hotplug(void)
444 {
445 #ifdef CONFIG_MEMORY_HOTPLUG
446 	unregister_memory_notifier(&arc_hotplug_callback_mem_nb);
447 #endif
448 }
449 #else /* _KERNEL */
450 int64_t
451 arc_available_memory(void)
452 {
453 	int64_t lowest = INT64_MAX;
454 
455 	/* Every 100 calls, free a small amount */
456 	if (random_in_range(100) == 0)
457 		lowest = -1024;
458 
459 	return (lowest);
460 }
461 
462 int
463 arc_memory_throttle(spa_t *spa, uint64_t reserve, uint64_t txg)
464 {
465 	(void) spa, (void) reserve, (void) txg;
466 	return (0);
467 }
468 
469 uint64_t
470 arc_all_memory(void)
471 {
472 	return (ptob(physmem) / 2);
473 }
474 
475 uint64_t
476 arc_free_memory(void)
477 {
478 	return (random_in_range(arc_all_memory() * 20 / 100));
479 }
480 
481 void
482 arc_register_hotplug(void)
483 {
484 }
485 
486 void
487 arc_unregister_hotplug(void)
488 {
489 }
490 #endif /* _KERNEL */
491 
492 /*
493  * Helper function for arc_prune_async() it is responsible for safely
494  * handling the execution of a registered arc_prune_func_t.
495  */
496 static void
497 arc_prune_task(void *ptr)
498 {
499 	arc_prune_t *ap = (arc_prune_t *)ptr;
500 	arc_prune_func_t *func = ap->p_pfunc;
501 
502 	if (func != NULL)
503 		func(ap->p_adjust, ap->p_private);
504 
505 	zfs_refcount_remove(&ap->p_refcnt, func);
506 }
507 
508 /*
509  * Notify registered consumers they must drop holds on a portion of the ARC
510  * buffered they reference.  This provides a mechanism to ensure the ARC can
511  * honor the metadata limit and reclaim otherwise pinned ARC buffers.  This
512  * is analogous to dnlc_reduce_cache() but more generic.
513  *
514  * This operation is performed asynchronously so it may be safely called
515  * in the context of the arc_reclaim_thread().  A reference is taken here
516  * for each registered arc_prune_t and the arc_prune_task() is responsible
517  * for releasing it once the registered arc_prune_func_t has completed.
518  */
519 void
520 arc_prune_async(uint64_t adjust)
521 {
522 	arc_prune_t *ap;
523 
524 	mutex_enter(&arc_prune_mtx);
525 	for (ap = list_head(&arc_prune_list); ap != NULL;
526 	    ap = list_next(&arc_prune_list, ap)) {
527 
528 		if (zfs_refcount_count(&ap->p_refcnt) >= 2)
529 			continue;
530 
531 		zfs_refcount_add(&ap->p_refcnt, ap->p_pfunc);
532 		ap->p_adjust = adjust;
533 		if (taskq_dispatch(arc_prune_taskq, arc_prune_task,
534 		    ap, TQ_SLEEP) == TASKQID_INVALID) {
535 			zfs_refcount_remove(&ap->p_refcnt, ap->p_pfunc);
536 			continue;
537 		}
538 		ARCSTAT_BUMP(arcstat_prune);
539 	}
540 	mutex_exit(&arc_prune_mtx);
541 }
542 
543 ZFS_MODULE_PARAM(zfs_arc, zfs_arc_, shrinker_limit, INT, ZMOD_RW,
544 	"Limit on number of pages that ARC shrinker can reclaim at once");
545