xref: /freebsd/sys/contrib/openzfs/module/os/linux/zfs/arc_os.c (revision f5541f9f473430a3e608e07f623294322853d25a)
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 #include <linux/version.h>
53 #endif
54 #include <sys/callb.h>
55 #include <sys/kstat.h>
56 #include <sys/zthr.h>
57 #include <zfs_fletcher.h>
58 #include <sys/arc_impl.h>
59 #include <sys/trace_zfs.h>
60 #include <sys/aggsum.h>
61 
62 #ifdef _KERNEL
63 /*
64  * This is a limit on how many pages the ARC shrinker makes available for
65  * eviction in response to one page allocation attempt.  Note that in
66  * practice, the kernel's shrinker can ask us to evict up to about 4x this
67  * for one allocation attempt.
68  *
69  * The default limit of 10,000 (in practice, 160MB per allocation attempt
70  * with 4K pages) limits the amount of time spent attempting to reclaim ARC
71  * memory to less than 100ms per allocation attempt, even with a small
72  * average compressed block size of ~8KB.
73  *
74  * See also the comment in arc_shrinker_count().
75  * Set to 0 to disable limit.
76  */
77 static int zfs_arc_shrinker_limit = 10000;
78 
79 /*
80  * Relative cost of ARC eviction, AKA number of seeks needed to restore evicted
81  * page.  Bigger values make ARC more precious and evictions smaller comparing
82  * to other kernel subsystems.  Value of 4 means parity with page cache,
83  * according to my reading of kernel's do_shrink_slab() and other code.
84  */
85 static int zfs_arc_shrinker_seeks = DEFAULT_SEEKS;
86 
87 #ifdef CONFIG_MEMORY_HOTPLUG
88 static struct notifier_block arc_hotplug_callback_mem_nb;
89 #endif
90 #endif
91 
92 /*
93  * Return a default max arc size based on the amount of physical memory.
94  * This may be overridden by tuning the zfs_arc_max module parameter.
95  */
96 uint64_t
97 arc_default_max(uint64_t min, uint64_t allmem)
98 {
99 	uint64_t size;
100 
101 	if (allmem >= 1 << 30)
102 		size = allmem - (1 << 30);
103 	else
104 		size = min;
105 	return (MAX(allmem * 5 / 8, size));
106 }
107 
108 #ifdef _KERNEL
109 /*
110  * Return maximum amount of memory that we could possibly use.  Reduced
111  * to half of all memory in user space which is primarily used for testing.
112  */
113 uint64_t
114 arc_all_memory(void)
115 {
116 #ifdef CONFIG_HIGHMEM
117 	return (ptob(zfs_totalram_pages - zfs_totalhigh_pages));
118 #else
119 	return (ptob(zfs_totalram_pages));
120 #endif /* CONFIG_HIGHMEM */
121 }
122 
123 /*
124  * Return the amount of memory that is considered free.  In user space
125  * which is primarily used for testing we pretend that free memory ranges
126  * from 0-20% of all memory.
127  */
128 uint64_t
129 arc_free_memory(void)
130 {
131 #ifdef CONFIG_HIGHMEM
132 	struct sysinfo si;
133 	si_meminfo(&si);
134 	return (ptob(si.freeram - si.freehigh));
135 #else
136 	return (ptob(nr_free_pages() +
137 	    nr_inactive_file_pages()));
138 #endif /* CONFIG_HIGHMEM */
139 }
140 
141 /*
142  * Return the amount of memory that can be consumed before reclaim will be
143  * needed.  Positive if there is sufficient free memory, negative indicates
144  * the amount of memory that needs to be freed up.
145  */
146 int64_t
147 arc_available_memory(void)
148 {
149 	return (arc_free_memory() - arc_sys_free);
150 }
151 
152 static uint64_t
153 arc_evictable_memory(void)
154 {
155 	int64_t asize = aggsum_value(&arc_sums.arcstat_size);
156 	uint64_t arc_clean =
157 	    zfs_refcount_count(&arc_mru->arcs_esize[ARC_BUFC_DATA]) +
158 	    zfs_refcount_count(&arc_mru->arcs_esize[ARC_BUFC_METADATA]) +
159 	    zfs_refcount_count(&arc_mfu->arcs_esize[ARC_BUFC_DATA]) +
160 	    zfs_refcount_count(&arc_mfu->arcs_esize[ARC_BUFC_METADATA]);
161 	uint64_t arc_dirty = MAX((int64_t)asize - (int64_t)arc_clean, 0);
162 
163 	/*
164 	 * Scale reported evictable memory in proportion to page cache, cap
165 	 * at specified min/max.
166 	 */
167 	uint64_t min = (ptob(nr_file_pages()) / 100) * zfs_arc_pc_percent;
168 	min = MAX(arc_c_min, MIN(arc_c_max, min));
169 
170 	if (arc_dirty >= min)
171 		return (arc_clean);
172 
173 	return (MAX((int64_t)asize - (int64_t)min, 0));
174 }
175 
176 /*
177  * The _count() function returns the number of free-able objects.
178  * The _scan() function returns the number of objects that were freed.
179  */
180 static unsigned long
181 arc_shrinker_count(struct shrinker *shrink, struct shrink_control *sc)
182 {
183 	/*
184 	 * The kernel's shrinker code may not understand how many pages the
185 	 * ARC's callback actually frees, so it may ask the ARC to shrink a
186 	 * lot for one page allocation. This is problematic because it may
187 	 * take a long time, thus delaying the page allocation, and because
188 	 * it may force the ARC to unnecessarily shrink very small.
189 	 *
190 	 * Therefore, we limit the amount of data that we say is evictable,
191 	 * which limits the amount that the shrinker will ask us to evict for
192 	 * one page allocation attempt.
193 	 *
194 	 * In practice, we may be asked to shrink 4x the limit to satisfy one
195 	 * page allocation, before the kernel's shrinker code gives up on us.
196 	 * When that happens, we rely on the kernel code to find the pages
197 	 * that we freed before invoking the OOM killer.  This happens in
198 	 * __alloc_pages_slowpath(), which retries and finds the pages we
199 	 * freed when it calls get_page_from_freelist().
200 	 *
201 	 * See also the comment above zfs_arc_shrinker_limit.
202 	 */
203 	int64_t can_free = btop(arc_evictable_memory());
204 	int64_t limit = zfs_arc_shrinker_limit != 0 ?
205 	    zfs_arc_shrinker_limit : INT64_MAX;
206 	return (MIN(can_free, limit));
207 }
208 
209 static unsigned long
210 arc_shrinker_scan(struct shrinker *shrink, struct shrink_control *sc)
211 {
212 	/* The arc is considered warm once reclaim has occurred */
213 	if (unlikely(arc_warm == B_FALSE))
214 		arc_warm = B_TRUE;
215 
216 	/*
217 	 * We are experiencing memory pressure which the arc_evict_zthr was
218 	 * unable to keep up with.  Set arc_no_grow to briefly pause ARC
219 	 * growth to avoid compounding the memory pressure.
220 	 */
221 	arc_no_grow = B_TRUE;
222 
223 	/*
224 	 * Evict the requested number of pages by reducing arc_c and waiting
225 	 * for the requested amount of data to be evicted.  To avoid deadlock
226 	 * do not wait for eviction if we may be called from ZFS itself (see
227 	 * kmem_flags_convert() removing __GFP_FS).  It may cause excessive
228 	 * eviction later if many evictions are accumulated, but just skipping
229 	 * the eviction is not good either if most of memory is used by ARC.
230 	 */
231 	uint64_t to_free = arc_reduce_target_size(ptob(sc->nr_to_scan));
232 	if (sc->gfp_mask & __GFP_FS)
233 		arc_wait_for_eviction(to_free, B_FALSE, B_FALSE);
234 	if (current->reclaim_state != NULL)
235 #ifdef	HAVE_RECLAIM_STATE_RECLAIMED
236 		current->reclaim_state->reclaimed += btop(to_free);
237 #else
238 		current->reclaim_state->reclaimed_slab += btop(to_free);
239 #endif
240 
241 	/*
242 	 * When direct reclaim is observed it usually indicates a rapid
243 	 * increase in memory pressure.  This occurs because the kswapd
244 	 * threads were unable to asynchronously keep enough free memory
245 	 * available.
246 	 */
247 	if (current_is_kswapd()) {
248 		ARCSTAT_BUMP(arcstat_memory_indirect_count);
249 	} else {
250 		ARCSTAT_BUMP(arcstat_memory_direct_count);
251 	}
252 
253 	return (btop(to_free));
254 }
255 
256 static struct shrinker *arc_shrinker = NULL;
257 
258 int
259 arc_memory_throttle(spa_t *spa, uint64_t reserve, uint64_t txg)
260 {
261 	uint64_t free_memory = arc_free_memory();
262 
263 	if (free_memory > arc_all_memory() * arc_lotsfree_percent / 100)
264 		return (0);
265 
266 	if (txg > spa->spa_lowmem_last_txg) {
267 		spa->spa_lowmem_last_txg = txg;
268 		spa->spa_lowmem_page_load = 0;
269 	}
270 	/*
271 	 * If we are in pageout, we know that memory is already tight,
272 	 * the arc is already going to be evicting, so we just want to
273 	 * continue to let page writes occur as quickly as possible.
274 	 */
275 	if (current_is_kswapd()) {
276 		if (spa->spa_lowmem_page_load >
277 		    MAX(arc_sys_free / 4, free_memory) / 4) {
278 			DMU_TX_STAT_BUMP(dmu_tx_memory_reclaim);
279 			return (SET_ERROR(ERESTART));
280 		}
281 		/* Note: reserve is inflated, so we deflate */
282 		atomic_add_64(&spa->spa_lowmem_page_load, reserve / 8);
283 		return (0);
284 	} else if (spa->spa_lowmem_page_load > 0 && arc_reclaim_needed()) {
285 		/* memory is low, delay before restarting */
286 		ARCSTAT_INCR(arcstat_memory_throttle_count, 1);
287 		DMU_TX_STAT_BUMP(dmu_tx_memory_reclaim);
288 		return (SET_ERROR(EAGAIN));
289 	}
290 	spa->spa_lowmem_page_load = 0;
291 	return (0);
292 }
293 
294 static void
295 arc_set_sys_free(uint64_t allmem)
296 {
297 	/*
298 	 * The ARC tries to keep at least this much memory available for the
299 	 * system.  This gives the ARC time to shrink in response to memory
300 	 * pressure, before running completely out of memory and invoking the
301 	 * direct-reclaim ARC shrinker.
302 	 *
303 	 * This should be more than twice high_wmark_pages(), so that
304 	 * arc_wait_for_eviction() will wait until at least the
305 	 * high_wmark_pages() are free (see arc_evict_state_impl()).
306 	 *
307 	 * Note: If concurrent allocations consume these pages, there may
308 	 * still be insufficient free pages, and the OOM killer takes action.
309 	 *
310 	 * By setting arc_sys_free large enough, and having
311 	 * arc_wait_for_eviction() wait until there is at least arc_sys_free/2
312 	 * free memory, it is much less likely that concurrent allocations can
313 	 * consume all the memory that was evicted before checking for
314 	 * OOM.
315 	 *
316 	 * It's hard to iterate the zones from a linux kernel module, which
317 	 * makes it difficult to determine the watermark dynamically. Instead
318 	 * we compute the maximum high watermark for this system, based
319 	 * on the amount of memory, using the same method as the kernel uses
320 	 * to calculate its internal `min_free_kbytes` variable.  See
321 	 * torvalds/linux@ee8eb9a5fe86 for the change in the upper clamp value
322 	 * from 64M to 256M.
323 	 */
324 
325 	/*
326 	 * Base wmark_low is 4 * the square root of Kbytes of RAM.
327 	 */
328 	long wmark = int_sqrt(allmem / 1024 * 16) * 1024;
329 
330 	/*
331 	 * Clamp to between 128K and 256/64MB.
332 	 */
333 	wmark = MAX(wmark, 128 * 1024);
334 #if LINUX_VERSION_CODE >= KERNEL_VERSION(5, 7, 0)
335 	wmark = MIN(wmark, 256 * 1024 * 1024);
336 #else
337 	wmark = MIN(wmark, 64 * 1024 * 1024);
338 #endif
339 
340 	/*
341 	 * watermark_boost can increase the wmark by up to 150%.
342 	 */
343 	wmark += wmark * 150 / 100;
344 
345 	/*
346 	 * arc_sys_free needs to be more than 2x the watermark, because
347 	 * arc_wait_for_eviction() waits for half of arc_sys_free.  Bump this up
348 	 * to 3x to ensure we're above it.
349 	 */
350 	arc_sys_free = wmark * 3 + allmem / 32;
351 }
352 
353 void
354 arc_lowmem_init(void)
355 {
356 	uint64_t allmem = arc_all_memory();
357 
358 	/*
359 	 * Register a shrinker to support synchronous (direct) memory
360 	 * reclaim from the arc.  This is done to prevent kswapd from
361 	 * swapping out pages when it is preferable to shrink the arc.
362 	 */
363 	arc_shrinker = spl_register_shrinker("zfs-arc-shrinker",
364 	    arc_shrinker_count, arc_shrinker_scan, zfs_arc_shrinker_seeks);
365 	VERIFY(arc_shrinker);
366 
367 	arc_set_sys_free(allmem);
368 }
369 
370 void
371 arc_lowmem_fini(void)
372 {
373 	spl_unregister_shrinker(arc_shrinker);
374 	arc_shrinker = NULL;
375 }
376 
377 int
378 param_set_arc_u64(const char *buf, zfs_kernel_param_t *kp)
379 {
380 	int error;
381 
382 	error = spl_param_set_u64(buf, kp);
383 	if (error < 0)
384 		return (SET_ERROR(error));
385 
386 	arc_tuning_update(B_TRUE);
387 
388 	return (0);
389 }
390 
391 int
392 param_set_arc_min(const char *buf, zfs_kernel_param_t *kp)
393 {
394 	return (param_set_arc_u64(buf, kp));
395 }
396 
397 int
398 param_set_arc_max(const char *buf, zfs_kernel_param_t *kp)
399 {
400 	return (param_set_arc_u64(buf, kp));
401 }
402 
403 int
404 param_set_arc_int(const char *buf, zfs_kernel_param_t *kp)
405 {
406 	int error;
407 
408 	error = param_set_int(buf, kp);
409 	if (error < 0)
410 		return (SET_ERROR(error));
411 
412 	arc_tuning_update(B_TRUE);
413 
414 	return (0);
415 }
416 
417 #ifdef CONFIG_MEMORY_HOTPLUG
418 static int
419 arc_hotplug_callback(struct notifier_block *self, unsigned long action,
420     void *arg)
421 {
422 	(void) self, (void) arg;
423 	uint64_t allmem = arc_all_memory();
424 	if (action != MEM_ONLINE)
425 		return (NOTIFY_OK);
426 
427 	arc_set_limits(allmem);
428 
429 #ifdef __LP64__
430 	if (zfs_dirty_data_max_max == 0)
431 		zfs_dirty_data_max_max = MIN(4ULL * 1024 * 1024 * 1024,
432 		    allmem * zfs_dirty_data_max_max_percent / 100);
433 #else
434 	if (zfs_dirty_data_max_max == 0)
435 		zfs_dirty_data_max_max = MIN(1ULL * 1024 * 1024 * 1024,
436 		    allmem * zfs_dirty_data_max_max_percent / 100);
437 #endif
438 
439 	arc_set_sys_free(allmem);
440 	return (NOTIFY_OK);
441 }
442 #endif
443 
444 void
445 arc_register_hotplug(void)
446 {
447 #ifdef CONFIG_MEMORY_HOTPLUG
448 	arc_hotplug_callback_mem_nb.notifier_call = arc_hotplug_callback;
449 	/* There is no significance to the value 100 */
450 	arc_hotplug_callback_mem_nb.priority = 100;
451 	register_memory_notifier(&arc_hotplug_callback_mem_nb);
452 #endif
453 }
454 
455 void
456 arc_unregister_hotplug(void)
457 {
458 #ifdef CONFIG_MEMORY_HOTPLUG
459 	unregister_memory_notifier(&arc_hotplug_callback_mem_nb);
460 #endif
461 }
462 #else /* _KERNEL */
463 int64_t
464 arc_available_memory(void)
465 {
466 	int64_t lowest = INT64_MAX;
467 
468 	/* Every 100 calls, free a small amount */
469 	if (random_in_range(100) == 0)
470 		lowest = -1024;
471 
472 	return (lowest);
473 }
474 
475 int
476 arc_memory_throttle(spa_t *spa, uint64_t reserve, uint64_t txg)
477 {
478 	(void) spa, (void) reserve, (void) txg;
479 	return (0);
480 }
481 
482 uint64_t
483 arc_all_memory(void)
484 {
485 	return (ptob(physmem) / 2);
486 }
487 
488 uint64_t
489 arc_free_memory(void)
490 {
491 	return (random_in_range(arc_all_memory() * 20 / 100));
492 }
493 
494 void
495 arc_register_hotplug(void)
496 {
497 }
498 
499 void
500 arc_unregister_hotplug(void)
501 {
502 }
503 #endif /* _KERNEL */
504 
505 ZFS_MODULE_PARAM(zfs_arc, zfs_arc_, shrinker_limit, INT, ZMOD_RW,
506 	"Limit on number of pages that ARC shrinker can reclaim at once");
507 ZFS_MODULE_PARAM(zfs_arc, zfs_arc_, shrinker_seeks, INT, ZMOD_RD,
508 	"Relative cost of ARC eviction vs other kernel subsystems");
509