xref: /freebsd-14-stable/sys/contrib/openzfs/module/os/linux/zfs/arc_os.c (revision 2ec8b69480708185a273254e4e254140eb2ce633)
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 #include <sys/shrinker.h>
46 #include <sys/vmsystm.h>
47 #include <sys/zpl.h>
48 #include <linux/page_compat.h>
49 #include <linux/notifier.h>
50 #include <linux/memory.h>
51 #include <sys/callb.h>
52 #include <sys/kstat.h>
53 #include <sys/zthr.h>
54 #include <zfs_fletcher.h>
55 #include <sys/arc_impl.h>
56 #include <sys/trace_zfs.h>
57 #include <sys/aggsum.h>
58 
59 /*
60  * This is a limit on how many pages the ARC shrinker makes available for
61  * eviction in response to one page allocation attempt.  Note that in
62  * practice, the kernel's shrinker can ask us to evict up to about 4x this
63  * for one allocation attempt.
64  *
65  * The default limit of 10,000 (in practice, 160MB per allocation attempt
66  * with 4K pages) limits the amount of time spent attempting to reclaim ARC
67  * memory to less than 100ms per allocation attempt, even with a small
68  * average compressed block size of ~8KB.
69  *
70  * See also the comment in arc_shrinker_count().
71  * Set to 0 to disable limit.
72  */
73 int zfs_arc_shrinker_limit = 10000;
74 
75 #ifdef CONFIG_MEMORY_HOTPLUG
76 static struct notifier_block arc_hotplug_callback_mem_nb;
77 #endif
78 
79 /*
80  * Return a default max arc size based on the amount of physical memory.
81  */
82 uint64_t
arc_default_max(uint64_t min,uint64_t allmem)83 arc_default_max(uint64_t min, uint64_t allmem)
84 {
85 	/* Default to 1/2 of all memory. */
86 	return (MAX(allmem / 2, min));
87 }
88 
89 /*
90  * Return maximum amount of memory that we could possibly use.  Reduced
91  * to half of all memory in user space which is primarily used for testing.
92  */
93 uint64_t
arc_all_memory(void)94 arc_all_memory(void)
95 {
96 #ifdef CONFIG_HIGHMEM
97 	return (ptob(zfs_totalram_pages - zfs_totalhigh_pages));
98 #else
99 	return (ptob(zfs_totalram_pages));
100 #endif /* CONFIG_HIGHMEM */
101 }
102 
103 /*
104  * Return the amount of memory that is considered free.  In user space
105  * which is primarily used for testing we pretend that free memory ranges
106  * from 0-20% of all memory.
107  */
108 uint64_t
arc_free_memory(void)109 arc_free_memory(void)
110 {
111 #ifdef CONFIG_HIGHMEM
112 	struct sysinfo si;
113 	si_meminfo(&si);
114 	return (ptob(si.freeram - si.freehigh));
115 #else
116 	return (ptob(nr_free_pages() +
117 	    nr_inactive_file_pages()));
118 #endif /* CONFIG_HIGHMEM */
119 }
120 
121 /*
122  * Return the amount of memory that can be consumed before reclaim will be
123  * needed.  Positive if there is sufficient free memory, negative indicates
124  * the amount of memory that needs to be freed up.
125  */
126 int64_t
arc_available_memory(void)127 arc_available_memory(void)
128 {
129 	return (arc_free_memory() - arc_sys_free);
130 }
131 
132 static uint64_t
arc_evictable_memory(void)133 arc_evictable_memory(void)
134 {
135 	int64_t asize = aggsum_value(&arc_sums.arcstat_size);
136 	uint64_t arc_clean =
137 	    zfs_refcount_count(&arc_mru->arcs_esize[ARC_BUFC_DATA]) +
138 	    zfs_refcount_count(&arc_mru->arcs_esize[ARC_BUFC_METADATA]) +
139 	    zfs_refcount_count(&arc_mfu->arcs_esize[ARC_BUFC_DATA]) +
140 	    zfs_refcount_count(&arc_mfu->arcs_esize[ARC_BUFC_METADATA]);
141 	uint64_t arc_dirty = MAX((int64_t)asize - (int64_t)arc_clean, 0);
142 
143 	/*
144 	 * Scale reported evictable memory in proportion to page cache, cap
145 	 * at specified min/max.
146 	 */
147 	uint64_t min = (ptob(nr_file_pages()) / 100) * zfs_arc_pc_percent;
148 	min = MAX(arc_c_min, MIN(arc_c_max, min));
149 
150 	if (arc_dirty >= min)
151 		return (arc_clean);
152 
153 	return (MAX((int64_t)asize - (int64_t)min, 0));
154 }
155 
156 /*
157  * The _count() function returns the number of free-able objects.
158  * The _scan() function returns the number of objects that were freed.
159  */
160 static unsigned long
arc_shrinker_count(struct shrinker * shrink,struct shrink_control * sc)161 arc_shrinker_count(struct shrinker *shrink, struct shrink_control *sc)
162 {
163 	/*
164 	 * __GFP_FS won't be set if we are called from ZFS code (see
165 	 * kmem_flags_convert(), which removes it).  To avoid a deadlock, we
166 	 * don't allow evicting in this case.  We return 0 rather than
167 	 * SHRINK_STOP so that the shrinker logic doesn't accumulate a
168 	 * deficit against us.
169 	 */
170 	if (!(sc->gfp_mask & __GFP_FS)) {
171 		return (0);
172 	}
173 
174 	/*
175 	 * This code is reached in the "direct reclaim" case, where the
176 	 * kernel (outside ZFS) is trying to allocate a page, and the system
177 	 * is low on memory.
178 	 *
179 	 * The kernel's shrinker code doesn't understand how many pages the
180 	 * ARC's callback actually frees, so it may ask the ARC to shrink a
181 	 * lot for one page allocation. This is problematic because it may
182 	 * take a long time, thus delaying the page allocation, and because
183 	 * it may force the ARC to unnecessarily shrink very small.
184 	 *
185 	 * Therefore, we limit the amount of data that we say is evictable,
186 	 * which limits the amount that the shrinker will ask us to evict for
187 	 * one page allocation attempt.
188 	 *
189 	 * In practice, we may be asked to shrink 4x the limit to satisfy one
190 	 * page allocation, before the kernel's shrinker code gives up on us.
191 	 * When that happens, we rely on the kernel code to find the pages
192 	 * that we freed before invoking the OOM killer.  This happens in
193 	 * __alloc_pages_slowpath(), which retries and finds the pages we
194 	 * freed when it calls get_page_from_freelist().
195 	 *
196 	 * See also the comment above zfs_arc_shrinker_limit.
197 	 */
198 	int64_t limit = zfs_arc_shrinker_limit != 0 ?
199 	    zfs_arc_shrinker_limit : INT64_MAX;
200 	return (MIN(limit, btop((int64_t)arc_evictable_memory())));
201 }
202 
203 static unsigned long
arc_shrinker_scan(struct shrinker * shrink,struct shrink_control * sc)204 arc_shrinker_scan(struct shrinker *shrink, struct shrink_control *sc)
205 {
206 	ASSERT((sc->gfp_mask & __GFP_FS) != 0);
207 
208 	/* The arc is considered warm once reclaim has occurred */
209 	if (unlikely(arc_warm == B_FALSE))
210 		arc_warm = B_TRUE;
211 
212 	/*
213 	 * Evict the requested number of pages by reducing arc_c and waiting
214 	 * for the requested amount of data to be evicted.
215 	 */
216 	arc_reduce_target_size(ptob(sc->nr_to_scan));
217 	arc_wait_for_eviction(ptob(sc->nr_to_scan), B_FALSE);
218 	if (current->reclaim_state != NULL)
219 #ifdef	HAVE_RECLAIM_STATE_RECLAIMED
220 		current->reclaim_state->reclaimed += sc->nr_to_scan;
221 #else
222 		current->reclaim_state->reclaimed_slab += sc->nr_to_scan;
223 #endif
224 
225 	/*
226 	 * We are experiencing memory pressure which the arc_evict_zthr was
227 	 * unable to keep up with. Set arc_no_grow to briefly pause arc
228 	 * growth to avoid compounding the memory pressure.
229 	 */
230 	arc_no_grow = B_TRUE;
231 
232 	/*
233 	 * When direct reclaim is observed it usually indicates a rapid
234 	 * increase in memory pressure.  This occurs because the kswapd
235 	 * threads were unable to asynchronously keep enough free memory
236 	 * available.
237 	 */
238 	if (current_is_kswapd()) {
239 		ARCSTAT_BUMP(arcstat_memory_indirect_count);
240 	} else {
241 		ARCSTAT_BUMP(arcstat_memory_direct_count);
242 	}
243 
244 	return (sc->nr_to_scan);
245 }
246 
247 static struct shrinker *arc_shrinker = NULL;
248 
249 int
arc_memory_throttle(spa_t * spa,uint64_t reserve,uint64_t txg)250 arc_memory_throttle(spa_t *spa, uint64_t reserve, uint64_t txg)
251 {
252 	uint64_t free_memory = arc_free_memory();
253 
254 	if (free_memory > arc_all_memory() * arc_lotsfree_percent / 100)
255 		return (0);
256 
257 	if (txg > spa->spa_lowmem_last_txg) {
258 		spa->spa_lowmem_last_txg = txg;
259 		spa->spa_lowmem_page_load = 0;
260 	}
261 	/*
262 	 * If we are in pageout, we know that memory is already tight,
263 	 * the arc is already going to be evicting, so we just want to
264 	 * continue to let page writes occur as quickly as possible.
265 	 */
266 	if (current_is_kswapd()) {
267 		if (spa->spa_lowmem_page_load >
268 		    MAX(arc_sys_free / 4, free_memory) / 4) {
269 			DMU_TX_STAT_BUMP(dmu_tx_memory_reclaim);
270 			return (SET_ERROR(ERESTART));
271 		}
272 		/* Note: reserve is inflated, so we deflate */
273 		atomic_add_64(&spa->spa_lowmem_page_load, reserve / 8);
274 		return (0);
275 	} else if (spa->spa_lowmem_page_load > 0 && arc_reclaim_needed()) {
276 		/* memory is low, delay before restarting */
277 		ARCSTAT_INCR(arcstat_memory_throttle_count, 1);
278 		DMU_TX_STAT_BUMP(dmu_tx_memory_reclaim);
279 		return (SET_ERROR(EAGAIN));
280 	}
281 	spa->spa_lowmem_page_load = 0;
282 	return (0);
283 }
284 
285 static void
arc_set_sys_free(uint64_t allmem)286 arc_set_sys_free(uint64_t allmem)
287 {
288 	/*
289 	 * The ARC tries to keep at least this much memory available for the
290 	 * system.  This gives the ARC time to shrink in response to memory
291 	 * pressure, before running completely out of memory and invoking the
292 	 * direct-reclaim ARC shrinker.
293 	 *
294 	 * This should be more than twice high_wmark_pages(), so that
295 	 * arc_wait_for_eviction() will wait until at least the
296 	 * high_wmark_pages() are free (see arc_evict_state_impl()).
297 	 *
298 	 * Note: Even when the system is very low on memory, the kernel's
299 	 * shrinker code may only ask for one "batch" of pages (512KB) to be
300 	 * evicted.  If concurrent allocations consume these pages, there may
301 	 * still be insufficient free pages, and the OOM killer takes action.
302 	 *
303 	 * By setting arc_sys_free large enough, and having
304 	 * arc_wait_for_eviction() wait until there is at least arc_sys_free/2
305 	 * free memory, it is much less likely that concurrent allocations can
306 	 * consume all the memory that was evicted before checking for
307 	 * OOM.
308 	 *
309 	 * It's hard to iterate the zones from a linux kernel module, which
310 	 * makes it difficult to determine the watermark dynamically. Instead
311 	 * we compute the maximum high watermark for this system, based
312 	 * on the amount of memory, assuming default parameters on Linux kernel
313 	 * 5.3.
314 	 */
315 
316 	/*
317 	 * Base wmark_low is 4 * the square root of Kbytes of RAM.
318 	 */
319 	long wmark = 4 * int_sqrt(allmem/1024) * 1024;
320 
321 	/*
322 	 * Clamp to between 128K and 64MB.
323 	 */
324 	wmark = MAX(wmark, 128 * 1024);
325 	wmark = MIN(wmark, 64 * 1024 * 1024);
326 
327 	/*
328 	 * watermark_boost can increase the wmark by up to 150%.
329 	 */
330 	wmark += wmark * 150 / 100;
331 
332 	/*
333 	 * arc_sys_free needs to be more than 2x the watermark, because
334 	 * arc_wait_for_eviction() waits for half of arc_sys_free.  Bump this up
335 	 * to 3x to ensure we're above it.
336 	 */
337 	arc_sys_free = wmark * 3 + allmem / 32;
338 }
339 
340 void
arc_lowmem_init(void)341 arc_lowmem_init(void)
342 {
343 	uint64_t allmem = arc_all_memory();
344 
345 	/*
346 	 * Register a shrinker to support synchronous (direct) memory
347 	 * reclaim from the arc.  This is done to prevent kswapd from
348 	 * swapping out pages when it is preferable to shrink the arc.
349 	 */
350 	arc_shrinker = spl_register_shrinker("zfs-arc-shrinker",
351 	    arc_shrinker_count, arc_shrinker_scan, DEFAULT_SEEKS);
352 	VERIFY(arc_shrinker);
353 
354 	arc_set_sys_free(allmem);
355 }
356 
357 void
arc_lowmem_fini(void)358 arc_lowmem_fini(void)
359 {
360 	spl_unregister_shrinker(arc_shrinker);
361 	arc_shrinker = NULL;
362 }
363 
364 int
param_set_arc_u64(const char * buf,zfs_kernel_param_t * kp)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
param_set_arc_min(const char * buf,zfs_kernel_param_t * kp)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
param_set_arc_max(const char * buf,zfs_kernel_param_t * kp)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
param_set_arc_int(const char * buf,zfs_kernel_param_t * kp)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
arc_hotplug_callback(struct notifier_block * self,unsigned long action,void * arg)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
arc_register_hotplug(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
arc_unregister_hotplug(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 
450 ZFS_MODULE_PARAM(zfs_arc, zfs_arc_, shrinker_limit, INT, ZMOD_RW,
451 	"Limit on number of pages that ARC shrinker can reclaim at once");
452