xref: /titanic_52/usr/src/uts/common/os/mem_cage.c (revision f498645a3eecf2ddd304b4ea9c7f1b4c155ff79e)
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 http://www.opensolaris.org/os/licensing.
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 2006 Sun Microsystems, Inc.  All rights reserved.
23  * Use is subject to license terms.
24  */
25 
26 #pragma ident	"%Z%%M%	%I%	%E% SMI"
27 
28 #include <sys/types.h>
29 #include <sys/param.h>
30 #include <sys/thread.h>
31 #include <sys/proc.h>
32 #include <sys/callb.h>
33 #include <sys/vnode.h>
34 #include <sys/debug.h>
35 #include <sys/systm.h>		/* for bzero */
36 #include <sys/memlist.h>
37 #include <sys/cmn_err.h>
38 #include <sys/sysmacros.h>
39 #include <sys/vmsystm.h>	/* for NOMEMWAIT() */
40 #include <sys/atomic.h>		/* used to update kcage_freemem */
41 #include <sys/kmem.h>		/* for kmem_reap */
42 #include <sys/errno.h>
43 #include <sys/mem_cage.h>
44 #include <vm/seg_kmem.h>
45 #include <vm/page.h>
46 #include <vm/hat.h>
47 #include <vm/vm_dep.h>
48 #include <sys/mem_config.h>
49 #include <sys/lgrp.h>
50 
51 extern pri_t maxclsyspri;
52 
53 #ifdef DEBUG
54 #define	KCAGE_STATS
55 #endif
56 
57 #ifdef KCAGE_STATS
58 
59 #define	KCAGE_STATS_VERSION 9	/* can help report generators */
60 #define	KCAGE_STATS_NSCANS 256	/* depth of scan statistics buffer */
61 
62 struct kcage_stats_scan {
63 	/* managed by KCAGE_STAT_* macros */
64 	clock_t	scan_lbolt;
65 	uint_t	scan_id;
66 
67 	/* set in kcage_cageout() */
68 	uint_t	kt_passes;
69 	clock_t	kt_ticks;
70 	pgcnt_t	kt_kcage_freemem_start;
71 	pgcnt_t	kt_kcage_freemem_end;
72 	pgcnt_t kt_freemem_start;
73 	pgcnt_t kt_freemem_end;
74 	uint_t	kt_examined;
75 	uint_t	kt_cantlock;
76 	uint_t	kt_gotone;
77 	uint_t	kt_gotonefree;
78 	uint_t	kt_skiplevel;
79 	uint_t	kt_skipshared;
80 	uint_t	kt_skiprefd;
81 	uint_t	kt_destroy;
82 
83 	/* set in kcage_invalidate_page() */
84 	uint_t	kip_reloclocked;
85 	uint_t	kip_relocmod;
86 	uint_t	kip_destroy;
87 	uint_t	kip_nomem;
88 	uint_t	kip_demotefailed;
89 
90 	/* set in kcage_expand() */
91 	uint_t	ke_wanted;
92 	uint_t	ke_examined;
93 	uint_t	ke_lefthole;
94 	uint_t	ke_gotone;
95 	uint_t	ke_gotonefree;
96 };
97 
98 struct kcage_stats {
99 	/* managed by KCAGE_STAT_* macros */
100 	uint_t	version;
101 	uint_t	size;
102 
103 	/* set in kcage_cageout */
104 	uint_t	kt_wakeups;
105 	uint_t	kt_scans;
106 	uint_t	kt_cageout_break;
107 
108 	/* set in kcage_expand */
109 	uint_t	ke_calls;
110 	uint_t	ke_nopfn;
111 	uint_t	ke_nopaget;
112 	uint_t	ke_isnoreloc;
113 	uint_t	ke_deleting;
114 	uint_t	ke_lowfreemem;
115 	uint_t	ke_terminate;
116 
117 	/* set in kcage_freemem_add() */
118 	uint_t	kfa_trottlewake;
119 
120 	/* set in kcage_freemem_sub() */
121 	uint_t	kfs_cagewake;
122 
123 	/* set in kcage_create_throttle */
124 	uint_t	kct_calls;
125 	uint_t	kct_cageout;
126 	uint_t	kct_critical;
127 	uint_t	kct_exempt;
128 	uint_t	kct_cagewake;
129 	uint_t	kct_wait;
130 	uint_t	kct_progress;
131 	uint_t	kct_noprogress;
132 	uint_t	kct_timeout;
133 
134 	/* set in kcage_cageout_wakeup */
135 	uint_t	kcw_expandearly;
136 
137 	/* managed by KCAGE_STAT_* macros */
138 	uint_t	scan_array_size;
139 	uint_t	scan_index;
140 	struct kcage_stats_scan scans[KCAGE_STATS_NSCANS];
141 };
142 
143 static struct kcage_stats kcage_stats;
144 static struct kcage_stats_scan kcage_stats_scan_zero;
145 
146 /*
147  * No real need for atomics here. For the most part the incs and sets are
148  * done by the kernel cage thread. There are a few that are done by any
149  * number of other threads. Those cases are noted by comments.
150  */
151 #define	KCAGE_STAT_INCR(m)	kcage_stats.m++
152 
153 #define	KCAGE_STAT_NINCR(m, v) kcage_stats.m += (v)
154 
155 #define	KCAGE_STAT_INCR_SCAN(m)	\
156 	KCAGE_STAT_INCR(scans[kcage_stats.scan_index].m)
157 
158 #define	KCAGE_STAT_NINCR_SCAN(m, v) \
159 	KCAGE_STAT_NINCR(scans[kcage_stats.scan_index].m, v)
160 
161 #define	KCAGE_STAT_SET(m, v)	kcage_stats.m = (v)
162 
163 #define	KCAGE_STAT_SETZ(m, v)	\
164 	if (kcage_stats.m == 0) kcage_stats.m = (v)
165 
166 #define	KCAGE_STAT_SET_SCAN(m, v)	\
167 	KCAGE_STAT_SET(scans[kcage_stats.scan_index].m, v)
168 
169 #define	KCAGE_STAT_SETZ_SCAN(m, v)	\
170 	KCAGE_STAT_SETZ(scans[kcage_stats.scan_index].m, v)
171 
172 #define	KCAGE_STAT_INC_SCAN_INDEX \
173 	KCAGE_STAT_SET_SCAN(scan_lbolt, lbolt); \
174 	KCAGE_STAT_SET_SCAN(scan_id, kcage_stats.scan_index); \
175 	kcage_stats.scan_index = \
176 	(kcage_stats.scan_index + 1) % KCAGE_STATS_NSCANS; \
177 	kcage_stats.scans[kcage_stats.scan_index] = kcage_stats_scan_zero
178 
179 #define	KCAGE_STAT_INIT_SCAN_INDEX \
180 	kcage_stats.version = KCAGE_STATS_VERSION; \
181 	kcage_stats.size = sizeof (kcage_stats); \
182 	kcage_stats.scan_array_size = KCAGE_STATS_NSCANS; \
183 	kcage_stats.scan_index = 0
184 
185 #else /* KCAGE_STATS */
186 
187 #define	KCAGE_STAT_INCR(v)
188 #define	KCAGE_STAT_NINCR(m, v)
189 #define	KCAGE_STAT_INCR_SCAN(v)
190 #define	KCAGE_STAT_NINCR_SCAN(m, v)
191 #define	KCAGE_STAT_SET(m, v)
192 #define	KCAGE_STAT_SETZ(m, v)
193 #define	KCAGE_STAT_SET_SCAN(m, v)
194 #define	KCAGE_STAT_SETZ_SCAN(m, v)
195 #define	KCAGE_STAT_INC_SCAN_INDEX
196 #define	KCAGE_STAT_INIT_SCAN_INDEX
197 
198 #endif /* KCAGE_STATS */
199 
200 static kmutex_t kcage_throttle_mutex;	/* protects kcage_throttle_cv */
201 static kcondvar_t kcage_throttle_cv;
202 
203 static kmutex_t kcage_cageout_mutex;	/* protects cv and ready flag */
204 static kcondvar_t kcage_cageout_cv;	/* cageout thread naps here */
205 static int kcage_cageout_ready;		/* nonzero when cageout thread ready */
206 kthread_id_t kcage_cageout_thread;	/* to aid debugging */
207 
208 static kmutex_t kcage_range_mutex;	/* proctects kcage_glist elements */
209 
210 /*
211  * Cage expansion happens within a range.
212  */
213 struct kcage_glist {
214 	struct kcage_glist	*next;
215 	pfn_t			base;
216 	pfn_t			lim;
217 	pfn_t			curr;
218 	int			decr;
219 };
220 
221 static struct kcage_glist *kcage_glist;
222 static struct kcage_glist *kcage_current_glist;
223 
224 /*
225  * The firstfree element is provided so that kmem_alloc can be avoided
226  * until that cage has somewhere to go. This is not currently a problem
227  * as early kmem_alloc's use BOP_ALLOC instead of page_create_va.
228  */
229 static struct kcage_glist kcage_glist_firstfree;
230 static struct kcage_glist *kcage_glist_freelist = &kcage_glist_firstfree;
231 
232 /*
233  * Miscellaneous forward references
234  */
235 static struct kcage_glist *kcage_glist_alloc(void);
236 static int kcage_glist_delete(pfn_t, pfn_t, struct kcage_glist **);
237 static void kcage_cageout(void);
238 static int kcage_invalidate_page(page_t *, pgcnt_t *);
239 static int kcage_setnoreloc_pages(page_t *, se_t);
240 
241 /*
242  * Kernel Memory Cage counters and thresholds.
243  */
244 int kcage_on = 0;
245 pgcnt_t kcage_freemem;
246 pgcnt_t kcage_needfree;
247 pgcnt_t kcage_lotsfree;
248 pgcnt_t kcage_desfree;
249 pgcnt_t kcage_minfree;
250 pgcnt_t kcage_throttlefree;
251 pgcnt_t	kcage_reserve;
252 int kcage_maxwait = 10;	/* in seconds */
253 
254 /* when we use lp for kmem we start the cage at a higher initial value */
255 pgcnt_t kcage_kmemlp_mincage;
256 
257 #ifdef DEBUG
258 pgcnt_t	kcage_pagets;
259 #define	KCAGEPAGETS_INC()	kcage_pagets++
260 #else
261 #define	KCAGEPAGETS_INC()
262 #endif
263 
264 /*
265  * Startup and Dynamic Reconfiguration interfaces.
266  * kcage_range_lock()
267  * kcage_range_unlock()
268  * kcage_range_islocked()
269  * kcage_range_add()
270  * kcage_range_del()
271  * kcage_init()
272  * kcage_set_thresholds()
273  */
274 
275 int
276 kcage_range_trylock(void)
277 {
278 	return (mutex_tryenter(&kcage_range_mutex));
279 }
280 
281 void
282 kcage_range_lock(void)
283 {
284 	mutex_enter(&kcage_range_mutex);
285 }
286 
287 void
288 kcage_range_unlock(void)
289 {
290 	mutex_exit(&kcage_range_mutex);
291 }
292 
293 int
294 kcage_range_islocked(void)
295 {
296 	return (MUTEX_HELD(&kcage_range_mutex));
297 }
298 
299 /*
300  * Called from page_get_contig_pages to get the approximate kcage pfn range
301  * for exclusion from search for contiguous pages. This routine is called
302  * without kcage_range lock (kcage routines can call page_get_contig_pages
303  * through page_relocate) and with the assumption, based on kcage_range_add,
304  * that kcage_current_glist always contain a valid pointer.
305  */
306 
307 int
308 kcage_current_pfn(pfn_t *pfncur)
309 {
310 	struct kcage_glist *lp = kcage_current_glist;
311 
312 	ASSERT(kcage_on);
313 
314 	ASSERT(lp != NULL);
315 
316 	*pfncur = lp->curr;
317 
318 	return (lp->decr);
319 }
320 
321 int
322 kcage_range_init(struct memlist *ml, int decr)
323 {
324 	int ret = 0;
325 
326 	ASSERT(kcage_range_islocked());
327 
328 	if (decr) {
329 		while (ml->next != NULL)
330 			ml = ml->next;
331 	}
332 
333 	while (ml != NULL) {
334 		ret = kcage_range_add(btop(ml->address), btop(ml->size), decr);
335 		if (ret)
336 			break;
337 
338 		ml = (decr ? ml->prev : ml->next);
339 	}
340 
341 	return (ret);
342 }
343 
344 /*
345  * Third arg controls direction of growth: 0: increasing pfns,
346  * 1: decreasing.
347  * Calls to add and delete must be protected by calls to
348  * kcage_range_lock() and kcage_range_unlock().
349  */
350 int
351 kcage_range_add(pfn_t base, pgcnt_t npgs, int decr)
352 {
353 	struct kcage_glist *new, **lpp;
354 	pfn_t lim;
355 
356 	ASSERT(kcage_range_islocked());
357 
358 	ASSERT(npgs != 0);
359 	if (npgs == 0)
360 		return (EINVAL);
361 
362 	lim = base + npgs;
363 
364 	ASSERT(lim > base);
365 	if (lim <= base)
366 		return (EINVAL);
367 
368 	new = kcage_glist_alloc();
369 	if (new == NULL) {
370 		return (ENOMEM);
371 	}
372 
373 	new->base = base;
374 	new->lim = lim;
375 	new->decr = decr;
376 	if (new->decr != 0)
377 		new->curr = new->lim;
378 	else
379 		new->curr = new->base;
380 	/*
381 	 * Any overlapping existing ranges are removed by deleting
382 	 * from the new list as we search for the tail.
383 	 */
384 	lpp = &kcage_glist;
385 	while (*lpp != NULL) {
386 		int ret;
387 		ret = kcage_glist_delete((*lpp)->base, (*lpp)->lim, &new);
388 		if (ret != 0)
389 			return (ret);
390 		lpp = &(*lpp)->next;
391 	}
392 
393 	*lpp = new;
394 
395 	if (kcage_current_glist == NULL) {
396 		kcage_current_glist = kcage_glist;
397 	}
398 
399 	return (0);
400 }
401 
402 /*
403  * Calls to add and delete must be protected by calls to
404  * kcage_range_lock() and kcage_range_unlock().
405  */
406 int
407 kcage_range_delete(pfn_t base, pgcnt_t npgs)
408 {
409 	struct kcage_glist *lp;
410 	pfn_t lim;
411 
412 	ASSERT(kcage_range_islocked());
413 
414 	ASSERT(npgs != 0);
415 	if (npgs == 0)
416 		return (EINVAL);
417 
418 	lim = base + npgs;
419 
420 	ASSERT(lim > base);
421 	if (lim <= base)
422 		return (EINVAL);
423 
424 	/*
425 	 * Check if the delete is OK first as a number of elements
426 	 * might be involved and it will be difficult to go
427 	 * back and undo (can't just add the range back in).
428 	 */
429 	for (lp = kcage_glist; lp != NULL; lp = lp->next) {
430 		/*
431 		 * If there have been no pages allocated from this
432 		 * element, we don't need to check it.
433 		 */
434 		if ((lp->decr == 0 && lp->curr == lp->base) ||
435 		    (lp->decr != 0 && lp->curr == lp->lim))
436 			continue;
437 		/*
438 		 * If the element does not overlap, its OK.
439 		 */
440 		if (base >= lp->lim || lim <= lp->base)
441 			continue;
442 		/*
443 		 * Overlapping element: Does the range to be deleted
444 		 * overlap the area already used? If so fail.
445 		 */
446 		if (lp->decr == 0 && base < lp->curr && lim >= lp->base) {
447 			return (EBUSY);
448 		}
449 		if (lp->decr != 0 && base < lp->lim && lim >= lp->curr) {
450 			return (EBUSY);
451 		}
452 	}
453 	return (kcage_glist_delete(base, lim, &kcage_glist));
454 }
455 
456 /*
457  * Calls to add and delete must be protected by calls to
458  * kcage_range_lock() and kcage_range_unlock().
459  * This routine gets called after successful Solaris memory
460  * delete operation from DR post memory delete routines.
461  */
462 int
463 kcage_range_delete_post_mem_del(pfn_t base, pgcnt_t npgs)
464 {
465 	pfn_t lim;
466 
467 	ASSERT(kcage_range_islocked());
468 
469 	ASSERT(npgs != 0);
470 	if (npgs == 0)
471 		return (EINVAL);
472 
473 	lim = base + npgs;
474 
475 	ASSERT(lim > base);
476 	if (lim <= base)
477 		return (EINVAL);
478 
479 	return (kcage_glist_delete(base, lim, &kcage_glist));
480 }
481 
482 /*
483  * No locking is required here as the whole operation is covered
484  * by the kcage_range_lock().
485  */
486 static struct kcage_glist *
487 kcage_glist_alloc(void)
488 {
489 	struct kcage_glist *new;
490 
491 	if ((new = kcage_glist_freelist) != NULL) {
492 		kcage_glist_freelist = new->next;
493 		bzero(new, sizeof (*new));
494 	} else {
495 		new = kmem_zalloc(sizeof (struct kcage_glist), KM_NOSLEEP);
496 	}
497 	return (new);
498 }
499 
500 static void
501 kcage_glist_free(struct kcage_glist *lp)
502 {
503 	lp->next = kcage_glist_freelist;
504 	kcage_glist_freelist = lp;
505 }
506 
507 static int
508 kcage_glist_delete(pfn_t base, pfn_t lim, struct kcage_glist **lpp)
509 {
510 	struct kcage_glist *lp, *prev = *lpp;
511 
512 	while ((lp = *lpp) != NULL) {
513 		if (lim > lp->base && base < lp->lim) {
514 			/* The delete range overlaps this element. */
515 			if (base <= lp->base && lim >= lp->lim) {
516 				/* Delete whole element. */
517 				*lpp = lp->next;
518 				if (lp == kcage_current_glist) {
519 					/* This can never happen. */
520 					ASSERT(kcage_current_glist != prev);
521 					kcage_current_glist = prev;
522 				}
523 				kcage_glist_free(lp);
524 				continue;
525 			}
526 
527 			/* Partial delete. */
528 			if (base > lp->base && lim < lp->lim) {
529 				struct kcage_glist *new;
530 
531 				/*
532 				 * Remove a section from the middle,
533 				 * need to allocate a new element.
534 				 */
535 				new = kcage_glist_alloc();
536 				if (new == NULL) {
537 					return (ENOMEM);
538 				}
539 
540 				/*
541 				 * Tranfser unused range to new.
542 				 * Edit lp in place to preserve
543 				 * kcage_current_glist.
544 				 */
545 				new->decr = lp->decr;
546 				if (new->decr != 0) {
547 					new->base = lp->base;
548 					new->lim = base;
549 					new->curr = base;
550 
551 					lp->base = lim;
552 				} else {
553 					new->base = lim;
554 					new->lim = lp->lim;
555 					new->curr = new->base;
556 
557 					lp->lim = base;
558 				}
559 
560 				/* Insert new. */
561 				new->next = lp->next;
562 				lp->next = new;
563 				lpp = &lp->next;
564 			} else {
565 				/* Delete part of current block. */
566 				if (base > lp->base) {
567 					ASSERT(lim >= lp->lim);
568 					ASSERT(base < lp->lim);
569 					if (lp->decr != 0 &&
570 					    lp->curr == lp->lim)
571 						lp->curr = base;
572 					lp->lim = base;
573 				} else {
574 					ASSERT(base <= lp->base);
575 					ASSERT(lim > lp->base);
576 					if (lp->decr == 0 &&
577 					    lp->curr == lp->base)
578 						lp->curr = lim;
579 					lp->base = lim;
580 				}
581 			}
582 		}
583 		prev = *lpp;
584 		lpp = &(*lpp)->next;
585 	}
586 
587 	return (0);
588 }
589 
590 /*
591  * The caller of kcage_get_pfn must hold the kcage_range_lock to make
592  * sure that there are no concurrent calls. The same lock
593  * must be obtained for range add and delete by calling
594  * kcage_range_lock() and kcage_range_unlock().
595  */
596 static pfn_t
597 kcage_get_pfn(void)
598 {
599 	struct kcage_glist *lp;
600 	pfn_t pfn;
601 
602 	ASSERT(kcage_range_islocked());
603 
604 	lp = kcage_current_glist;
605 	while (lp != NULL) {
606 		if (lp->decr != 0) {
607 			if (lp->curr != lp->base) {
608 				pfn = --lp->curr;
609 				return (pfn);
610 			}
611 		} else {
612 			if (lp->curr != lp->lim) {
613 				pfn = lp->curr++;
614 				return (pfn);
615 			}
616 		}
617 
618 		lp = lp->next;
619 		if (lp)
620 			kcage_current_glist = lp;
621 	}
622 
623 	return (PFN_INVALID);
624 }
625 
626 /*
627  * Walk the physical address space of the cage.
628  * This routine does not guarantee to return PFNs in the order
629  * in which they were allocated to the cage. Instead, it walks
630  * each range as they appear on the growth list returning the PFNs
631  * range in ascending order.
632  *
633  * To begin scanning at lower edge of cage, reset should be nonzero.
634  * To step through cage, reset should be zero.
635  *
636  * PFN_INVALID will be returned when the upper end of the cage is
637  * reached -- indicating a full scan of the cage has been completed since
638  * previous reset. PFN_INVALID will continue to be returned until
639  * kcage_walk_cage is reset.
640  *
641  * It is possible to receive a PFN_INVALID result on reset if a growth
642  * list is not installed or if none of the PFNs in the installed list have
643  * been allocated to the cage. In otherwords, there is no cage.
644  *
645  * Caller need not hold kcage_range_lock while calling this function
646  * as the front part of the list is static - pages never come out of
647  * the cage.
648  *
649  * The caller is expected to only be kcage_cageout().
650  */
651 static pfn_t
652 kcage_walk_cage(int reset)
653 {
654 	static struct kcage_glist *lp = NULL;
655 	static pfn_t pfn;
656 
657 	if (reset)
658 		lp = NULL;
659 	if (lp == NULL) {
660 		lp = kcage_glist;
661 		pfn = PFN_INVALID;
662 	}
663 again:
664 	if (pfn == PFN_INVALID) {
665 		if (lp == NULL)
666 			return (PFN_INVALID);
667 
668 		if (lp->decr != 0) {
669 			/*
670 			 * In this range the cage grows from the highest
671 			 * address towards the lowest.
672 			 * Arrange to return pfns from curr to lim-1,
673 			 * inclusive, in ascending order.
674 			 */
675 
676 			pfn = lp->curr;
677 		} else {
678 			/*
679 			 * In this range the cage grows from the lowest
680 			 * address towards the highest.
681 			 * Arrange to return pfns from base to curr,
682 			 * inclusive, in ascending order.
683 			 */
684 
685 			pfn = lp->base;
686 		}
687 	}
688 
689 	if (lp->decr != 0) {		/* decrementing pfn */
690 		if (pfn == lp->lim) {
691 			/* Don't go beyond the static part of the glist. */
692 			if (lp == kcage_current_glist)
693 				lp = NULL;
694 			else
695 				lp = lp->next;
696 			pfn = PFN_INVALID;
697 			goto again;
698 		}
699 
700 		ASSERT(pfn >= lp->curr && pfn < lp->lim);
701 	} else {			/* incrementing pfn */
702 		if (pfn == lp->curr) {
703 			/* Don't go beyond the static part of the glist. */
704 			if (lp == kcage_current_glist)
705 				lp = NULL;
706 			else
707 				lp = lp->next;
708 			pfn = PFN_INVALID;
709 			goto again;
710 		}
711 
712 		ASSERT(pfn >= lp->base && pfn < lp->curr);
713 	}
714 
715 	return (pfn++);
716 }
717 
718 /*
719  * Callback functions for to recalc cage thresholds after
720  * Kphysm memory add/delete operations.
721  */
722 /*ARGSUSED*/
723 static void
724 kcage_kphysm_postadd_cb(void *arg, pgcnt_t delta_pages)
725 {
726 	kcage_recalc_thresholds();
727 }
728 
729 /*ARGSUSED*/
730 static int
731 kcage_kphysm_predel_cb(void *arg, pgcnt_t delta_pages)
732 {
733 	/* TODO: when should cage refuse memory delete requests? */
734 	return (0);
735 }
736 
737 /*ARGSUSED*/
738 static  void
739 kcage_kphysm_postdel_cb(void *arg, pgcnt_t delta_pages, int cancelled)
740 {
741 	kcage_recalc_thresholds();
742 }
743 
744 static kphysm_setup_vector_t kcage_kphysm_vectors = {
745 	KPHYSM_SETUP_VECTOR_VERSION,
746 	kcage_kphysm_postadd_cb,
747 	kcage_kphysm_predel_cb,
748 	kcage_kphysm_postdel_cb
749 };
750 
751 /*
752  * This is called before a CPR suspend and after a CPR resume.  We have to
753  * turn off kcage_cageout_ready before a suspend, and turn it back on after a
754  * restart.
755  */
756 /*ARGSUSED*/
757 static boolean_t
758 kcage_cageout_cpr(void *arg, int code)
759 {
760 	if (code == CB_CODE_CPR_CHKPT) {
761 		ASSERT(kcage_cageout_ready);
762 		kcage_cageout_ready = 0;
763 		return (B_TRUE);
764 	} else if (code == CB_CODE_CPR_RESUME) {
765 		ASSERT(kcage_cageout_ready == 0);
766 		kcage_cageout_ready = 1;
767 		return (B_TRUE);
768 	}
769 	return (B_FALSE);
770 }
771 
772 /*
773  * kcage_recalc_preferred_size() increases initial cage size to improve large
774  * page availability when lp for kmem is enabled and kpr is disabled
775  */
776 static pgcnt_t
777 kcage_recalc_preferred_size(pgcnt_t preferred_size)
778 {
779 	if (SEGKMEM_USE_LARGEPAGES && segkmem_reloc == 0) {
780 		pgcnt_t lpmincage = kcage_kmemlp_mincage;
781 		if (lpmincage == 0) {
782 			lpmincage = MIN(P2ROUNDUP(((physmem * PAGESIZE) / 8),
783 			    segkmem_heaplp_quantum), 0x40000000UL) / PAGESIZE;
784 		}
785 		kcage_kmemlp_mincage = MIN(lpmincage,
786 			    (segkmem_kmemlp_max / PAGESIZE));
787 		preferred_size = MAX(kcage_kmemlp_mincage, preferred_size);
788 	}
789 	return (preferred_size);
790 }
791 
792 /*
793  * Kcage_init() builds the cage and initializes the cage thresholds.
794  * The size of the cage is determined by the argument preferred_size.
795  * or the actual amount of memory, whichever is smaller.
796  */
797 void
798 kcage_init(pgcnt_t preferred_size)
799 {
800 	pgcnt_t wanted;
801 	pfn_t pfn;
802 	page_t *pp;
803 	extern struct vnode kvp;
804 	extern void page_list_noreloc_startup(page_t *);
805 
806 	ASSERT(!kcage_on);
807 	ASSERT(kcage_range_islocked());
808 
809 	/* increase preferred cage size for lp for kmem */
810 	preferred_size = kcage_recalc_preferred_size(preferred_size);
811 
812 	/* Debug note: initialize this now so early expansions can stat */
813 	KCAGE_STAT_INIT_SCAN_INDEX;
814 
815 	/*
816 	 * Initialize cage thresholds and install kphysm callback.
817 	 * If we can't arrange to have the thresholds track with
818 	 * available physical memory, then the cage thresholds may
819 	 * end up over time at levels that adversly effect system
820 	 * performance; so, bail out.
821 	 */
822 	kcage_recalc_thresholds();
823 	if (kphysm_setup_func_register(&kcage_kphysm_vectors, NULL)) {
824 		ASSERT(0);		/* Catch this in DEBUG kernels. */
825 		return;
826 	}
827 
828 	/*
829 	 * Limit startup cage size within the range of kcage_minfree
830 	 * and availrmem, inclusively.
831 	 */
832 	wanted = MIN(MAX(preferred_size, kcage_minfree), availrmem);
833 
834 	/*
835 	 * Construct the cage. PFNs are allocated from the glist. It
836 	 * is assumed that the list has been properly ordered for the
837 	 * platform by the platform code. Typically, this is as simple
838 	 * as calling kcage_range_init(phys_avail, decr), where decr is
839 	 * 1 if the kernel has been loaded into upper end of physical
840 	 * memory, or 0 if the kernel has been loaded at the low end.
841 	 *
842 	 * Note: it is assumed that we are in the startup flow, so there
843 	 * is no reason to grab the page lock.
844 	 */
845 	kcage_freemem = 0;
846 	pfn = PFN_INVALID;			/* prime for alignment test */
847 	while (wanted != 0) {
848 		if ((pfn = kcage_get_pfn()) == PFN_INVALID)
849 			break;
850 
851 		if ((pp = page_numtopp_nolock(pfn)) != NULL) {
852 			KCAGEPAGETS_INC();
853 			/*
854 			 * Set the noreloc state on the page.
855 			 * If the page is free and not already
856 			 * on the noreloc list then move it.
857 			 */
858 			if (PP_ISFREE(pp)) {
859 				if (PP_ISNORELOC(pp) == 0)
860 					page_list_noreloc_startup(pp);
861 			} else {
862 				ASSERT(pp->p_szc == 0);
863 				PP_SETNORELOC(pp);
864 			}
865 		}
866 		PLCNT_XFER_NORELOC(pp);
867 		wanted -= 1;
868 	}
869 
870 	/*
871 	 * Need to go through and find kernel allocated pages
872 	 * and capture them into the Cage.  These will primarily
873 	 * be pages gotten through boot_alloc().
874 	 */
875 	if (kvp.v_pages) {
876 
877 		pp = kvp.v_pages;
878 		do {
879 			ASSERT(!PP_ISFREE(pp));
880 			ASSERT(pp->p_szc == 0);
881 			PP_SETNORELOC(pp);
882 		} while ((pp = pp->p_vpnext) != kvp.v_pages);
883 
884 	}
885 
886 	kcage_on = 1;
887 
888 	/*
889 	 * CB_CL_CPR_POST_KERNEL is the class that executes from cpr_suspend()
890 	 * after the cageout thread is blocked, and executes from cpr_resume()
891 	 * before the cageout thread is restarted.  By executing in this class,
892 	 * we are assured that the kernel cage thread won't miss wakeup calls
893 	 * and also CPR's larger kmem_alloc requests will not fail after
894 	 * CPR shuts down the cageout kernel thread.
895 	 */
896 	(void) callb_add(kcage_cageout_cpr, NULL, CB_CL_CPR_POST_KERNEL,
897 	    "cageout");
898 
899 	/*
900 	 * Coalesce pages to improve large page availability. A better fix
901 	 * would to coalesce pages as they are included in the cage
902 	 */
903 	if (SEGKMEM_USE_LARGEPAGES) {
904 		extern void page_freelist_coalesce_all(int mnode);
905 		extern int max_mem_nodes;
906 		int mnode, max_mnodes = max_mem_nodes;
907 		for (mnode = 0; mnode < max_mnodes; mnode++) {
908 			page_freelist_coalesce_all(mnode);
909 		}
910 	}
911 }
912 
913 void
914 kcage_recalc_thresholds()
915 {
916 	static int first = 1;
917 	static pgcnt_t init_lotsfree;
918 	static pgcnt_t init_desfree;
919 	static pgcnt_t init_minfree;
920 	static pgcnt_t init_throttlefree;
921 	static pgcnt_t init_reserve;
922 
923 	/* TODO: any reason to take more care than this with live editing? */
924 	mutex_enter(&kcage_cageout_mutex);
925 	mutex_enter(&freemem_lock);
926 
927 	if (first) {
928 		first = 0;
929 		init_lotsfree = kcage_lotsfree;
930 		init_desfree = kcage_desfree;
931 		init_minfree = kcage_minfree;
932 		init_throttlefree = kcage_throttlefree;
933 		init_reserve = kcage_reserve;
934 	} else {
935 		kcage_lotsfree = init_lotsfree;
936 		kcage_desfree = init_desfree;
937 		kcage_minfree = init_minfree;
938 		kcage_throttlefree = init_throttlefree;
939 		kcage_reserve = init_reserve;
940 	}
941 
942 	if (kcage_lotsfree == 0)
943 		kcage_lotsfree = MAX(32, total_pages / 256);
944 
945 	if (kcage_minfree == 0)
946 		kcage_minfree = MAX(32, kcage_lotsfree / 2);
947 
948 	if (kcage_desfree == 0)
949 		kcage_desfree = MAX(32, kcage_minfree);
950 
951 	if (kcage_throttlefree == 0)
952 		kcage_throttlefree = MAX(32, kcage_minfree / 2);
953 
954 	if (kcage_reserve == 0)
955 		kcage_reserve = MIN(32, kcage_throttlefree / 2);
956 
957 	mutex_exit(&freemem_lock);
958 	mutex_exit(&kcage_cageout_mutex);
959 
960 	if (kcage_cageout_ready) {
961 		if (kcage_freemem < kcage_desfree)
962 			kcage_cageout_wakeup();
963 
964 		if (kcage_needfree) {
965 			mutex_enter(&kcage_throttle_mutex);
966 			cv_broadcast(&kcage_throttle_cv);
967 			mutex_exit(&kcage_throttle_mutex);
968 		}
969 	}
970 }
971 
972 /*
973  * Pageout interface:
974  * kcage_cageout_init()
975  */
976 void
977 kcage_cageout_init()
978 {
979 	if (kcage_on) {
980 
981 		(void) thread_create(NULL, 0, kcage_cageout,
982 		    NULL, 0, proc_pageout, TS_RUN, maxclsyspri - 1);
983 	}
984 }
985 
986 
987 /*
988  * VM Interfaces:
989  * kcage_create_throttle()
990  * kcage_freemem_add()
991  * kcage_freemem_sub()
992  */
993 
994 /*
995  * Wakeup cageout thread and throttle waiting for the number of pages
996  * requested to become available.  For non-critical requests, a
997  * timeout is added, since freemem accounting is separate from cage
998  * freemem accounting: it's possible for us to get stuck and not make
999  * forward progress even though there was sufficient freemem before
1000  * arriving here.
1001  */
1002 int
1003 kcage_create_throttle(pgcnt_t npages, int flags)
1004 {
1005 	int niter = 0;
1006 	pgcnt_t lastfree;
1007 	int enough = kcage_freemem > kcage_throttlefree + npages;
1008 
1009 	KCAGE_STAT_INCR(kct_calls);		/* unprotected incr. */
1010 
1011 	kcage_cageout_wakeup();			/* just to be sure */
1012 	KCAGE_STAT_INCR(kct_cagewake);		/* unprotected incr. */
1013 
1014 	/*
1015 	 * Obviously, we can't throttle the cageout thread since
1016 	 * we depend on it.  We also can't throttle the panic thread.
1017 	 */
1018 	if (curthread == kcage_cageout_thread || panicstr) {
1019 		KCAGE_STAT_INCR(kct_cageout);	/* unprotected incr. */
1020 		return (KCT_CRIT);
1021 	}
1022 
1023 	/*
1024 	 * Don't throttle threads which are critical for proper
1025 	 * vm management if we're above kcage_throttlefree or
1026 	 * if freemem is very low.
1027 	 */
1028 	if (NOMEMWAIT()) {
1029 		if (enough) {
1030 			KCAGE_STAT_INCR(kct_exempt);	/* unprotected incr. */
1031 			return (KCT_CRIT);
1032 		} else if (freemem < minfree) {
1033 			KCAGE_STAT_INCR(kct_critical);  /* unprotected incr. */
1034 			return (KCT_CRIT);
1035 		}
1036 	}
1037 
1038 	/*
1039 	 * Don't throttle real-time threads if kcage_freemem > kcage_reserve.
1040 	 */
1041 	if (DISP_PRIO(curthread) > maxclsyspri &&
1042 	    kcage_freemem > kcage_reserve) {
1043 		KCAGE_STAT_INCR(kct_exempt);	/* unprotected incr. */
1044 		return (KCT_CRIT);
1045 	}
1046 
1047 	/*
1048 	 * Cause all other threads (which are assumed to not be
1049 	 * critical to cageout) to wait here until their request
1050 	 * can be satisfied. Be a little paranoid and wake the
1051 	 * kernel cage on each loop through this logic.
1052 	 */
1053 	while (kcage_freemem < kcage_throttlefree + npages) {
1054 		ASSERT(kcage_on);
1055 
1056 		lastfree = kcage_freemem;
1057 
1058 		if (kcage_cageout_ready) {
1059 			mutex_enter(&kcage_throttle_mutex);
1060 
1061 			kcage_needfree += npages;
1062 			KCAGE_STAT_INCR(kct_wait);
1063 
1064 			kcage_cageout_wakeup();
1065 			KCAGE_STAT_INCR(kct_cagewake);
1066 
1067 			cv_wait(&kcage_throttle_cv, &kcage_throttle_mutex);
1068 
1069 			kcage_needfree -= npages;
1070 
1071 			mutex_exit(&kcage_throttle_mutex);
1072 		} else {
1073 			/*
1074 			 * NOTE: atomics are used just in case we enter
1075 			 * mp operation before the cageout thread is ready.
1076 			 */
1077 			atomic_add_long(&kcage_needfree, npages);
1078 
1079 			kcage_cageout_wakeup();
1080 			KCAGE_STAT_INCR(kct_cagewake);	/* unprotected incr. */
1081 
1082 			atomic_add_long(&kcage_needfree, -npages);
1083 		}
1084 
1085 		if ((flags & PG_WAIT) == 0) {
1086 			if (kcage_freemem > lastfree) {
1087 				KCAGE_STAT_INCR(kct_progress);
1088 				niter = 0;
1089 			} else {
1090 				KCAGE_STAT_INCR(kct_noprogress);
1091 				if (++niter >= kcage_maxwait) {
1092 					KCAGE_STAT_INCR(kct_timeout);
1093 					return (KCT_FAILURE);
1094 				}
1095 			}
1096 		}
1097 	}
1098 	return (KCT_NONCRIT);
1099 }
1100 
1101 void
1102 kcage_freemem_add(pgcnt_t npages)
1103 {
1104 	extern void wakeup_pcgs(void);
1105 
1106 	atomic_add_long(&kcage_freemem, npages);
1107 
1108 	wakeup_pcgs();  /* wakeup threads in pcgs() */
1109 
1110 	if (kcage_needfree != 0 &&
1111 		kcage_freemem >= (kcage_throttlefree + kcage_needfree)) {
1112 
1113 		mutex_enter(&kcage_throttle_mutex);
1114 		cv_broadcast(&kcage_throttle_cv);
1115 		KCAGE_STAT_INCR(kfa_trottlewake);
1116 		mutex_exit(&kcage_throttle_mutex);
1117 	}
1118 }
1119 
1120 void
1121 kcage_freemem_sub(pgcnt_t npages)
1122 {
1123 	atomic_add_long(&kcage_freemem, -npages);
1124 
1125 	if (kcage_freemem < kcage_desfree) {
1126 		kcage_cageout_wakeup();
1127 		KCAGE_STAT_INCR(kfs_cagewake); /* unprotected incr. */
1128 	}
1129 }
1130 
1131 /*
1132  * return 0 on failure and 1 on success.
1133  */
1134 static int
1135 kcage_setnoreloc_pages(page_t *rootpp, se_t se)
1136 {
1137 	pgcnt_t npgs, i;
1138 	page_t *pp;
1139 	pfn_t rootpfn = page_pptonum(rootpp);
1140 	uint_t szc;
1141 
1142 	ASSERT(!PP_ISFREE(rootpp));
1143 	ASSERT(PAGE_LOCKED_SE(rootpp, se));
1144 	if (!group_page_trylock(rootpp, se)) {
1145 		return (0);
1146 	}
1147 	szc = rootpp->p_szc;
1148 	if (szc == 0) {
1149 		/*
1150 		 * The szc of a locked page can only change for pages that are
1151 		 * non-swapfs (i.e. anonymous memory) file system pages.
1152 		 */
1153 		ASSERT(rootpp->p_vnode != NULL &&
1154 		    rootpp->p_vnode != &kvp &&
1155 		    !IS_SWAPFSVP(rootpp->p_vnode));
1156 		PP_SETNORELOC(rootpp);
1157 		return (1);
1158 	}
1159 	npgs = page_get_pagecnt(szc);
1160 	ASSERT(IS_P2ALIGNED(rootpfn, npgs));
1161 	pp = rootpp;
1162 	for (i = 0; i < npgs; i++, pp++) {
1163 		ASSERT(PAGE_LOCKED_SE(pp, se));
1164 		ASSERT(!PP_ISFREE(pp));
1165 		ASSERT(pp->p_szc == szc);
1166 		PP_SETNORELOC(pp);
1167 	}
1168 	group_page_unlock(rootpp);
1169 	return (1);
1170 }
1171 
1172 /*
1173  * Attempt to convert page to a caged page (set the P_NORELOC flag).
1174  * If successful and pages is free, move page to the tail of whichever
1175  * list it is on.
1176  * Returns:
1177  *   EBUSY  page already locked, assimilated but not free.
1178  *   ENOMEM page assimilated, but memory too low to relocate. Page not free.
1179  *   EAGAIN page not assimilated. Page not free.
1180  *   ERANGE page assimilated. Page not root.
1181  *   0      page assimilated. Page free.
1182  *   *nfreedp number of pages freed.
1183  * NOTE: With error codes ENOMEM, EBUSY, and 0 (zero), there is no way
1184  * to distinguish between a page that was already a NORELOC page from
1185  * those newly converted to NORELOC pages by this invocation of
1186  * kcage_assimilate_page.
1187  */
1188 static int
1189 kcage_assimilate_page(page_t *pp, pgcnt_t *nfreedp)
1190 {
1191 	if (page_trylock(pp, SE_EXCL)) {
1192 		if (PP_ISNORELOC(pp)) {
1193 check_free_and_return:
1194 			if (PP_ISFREE(pp)) {
1195 				page_unlock(pp);
1196 				*nfreedp = 0;
1197 				return (0);
1198 			} else {
1199 				page_unlock(pp);
1200 				return (EBUSY);
1201 			}
1202 			/*NOTREACHED*/
1203 		}
1204 	} else {
1205 		if (page_trylock(pp, SE_SHARED)) {
1206 			if (PP_ISNORELOC(pp))
1207 				goto check_free_and_return;
1208 		} else
1209 			return (EAGAIN);
1210 
1211 		if (!PP_ISFREE(pp)) {
1212 			page_unlock(pp);
1213 			return (EAGAIN);
1214 		}
1215 
1216 		/*
1217 		 * Need to upgrade the lock on it and set the NORELOC
1218 		 * bit. If it is free then remove it from the free
1219 		 * list so that the platform free list code can keep
1220 		 * NORELOC pages where they should be.
1221 		 */
1222 		/*
1223 		 * Before doing anything, get the exclusive lock.
1224 		 * This may fail (eg ISM pages are left shared locked).
1225 		 * If the page is free this will leave a hole in the
1226 		 * cage. There is no solution yet to this.
1227 		 */
1228 		if (!page_tryupgrade(pp)) {
1229 			page_unlock(pp);
1230 			return (EAGAIN);
1231 		}
1232 	}
1233 
1234 	ASSERT(PAGE_EXCL(pp));
1235 
1236 	if (PP_ISFREE(pp)) {
1237 		int which = PP_ISAGED(pp) ? PG_FREE_LIST : PG_CACHE_LIST;
1238 
1239 		page_list_sub(pp, which);
1240 		ASSERT(pp->p_szc == 0);
1241 		PP_SETNORELOC(pp);
1242 		PLCNT_XFER_NORELOC(pp);
1243 		page_list_add(pp, which | PG_LIST_TAIL);
1244 
1245 		page_unlock(pp);
1246 		*nfreedp = 1;
1247 		return (0);
1248 	} else {
1249 		if (pp->p_szc != 0) {
1250 			if (!kcage_setnoreloc_pages(pp, SE_EXCL)) {
1251 				page_unlock(pp);
1252 				return (EAGAIN);
1253 			}
1254 			ASSERT(PP_ISNORELOC(pp));
1255 		} else {
1256 			PP_SETNORELOC(pp);
1257 		}
1258 		PLCNT_XFER_NORELOC(pp);
1259 		return (kcage_invalidate_page(pp, nfreedp));
1260 	}
1261 	/*NOTREACHED*/
1262 }
1263 
1264 static int
1265 kcage_expand()
1266 {
1267 	int did_something = 0;
1268 
1269 	spgcnt_t wanted;
1270 	pfn_t pfn;
1271 	page_t *pp;
1272 	/* TODO: we don't really need n any more? */
1273 	pgcnt_t n;
1274 	pgcnt_t nf, nfreed;
1275 
1276 	/*
1277 	 * Expand the cage if available cage memory is really low. Calculate
1278 	 * the amount required to return kcage_freemem to the level of
1279 	 * kcage_lotsfree, or to satisfy throttled requests, whichever is
1280 	 * more.  It is rare for their sum to create an artificial threshold
1281 	 * above kcage_lotsfree, but it is possible.
1282 	 *
1283 	 * Exit early if expansion amount is equal to or less than zero.
1284 	 * (<0 is possible if kcage_freemem rises suddenly.)
1285 	 *
1286 	 * Exit early when the global page pool (apparently) does not
1287 	 * have enough free pages to page_relocate() even a single page.
1288 	 */
1289 	wanted = MAX(kcage_lotsfree, kcage_throttlefree + kcage_needfree)
1290 		- kcage_freemem;
1291 	if (wanted <= 0)
1292 		return (0);
1293 	else if (freemem < pageout_reserve + 1) {
1294 		KCAGE_STAT_INCR(ke_lowfreemem);
1295 		return (0);
1296 	}
1297 
1298 	/*
1299 	 * Try to get the range list lock. If the lock is already
1300 	 * held, then don't get stuck here waiting for it.
1301 	 */
1302 	if (!kcage_range_trylock())
1303 		return (0);
1304 
1305 	KCAGE_STAT_INCR(ke_calls);
1306 	KCAGE_STAT_SET_SCAN(ke_wanted, (uint_t)wanted);
1307 
1308 	/*
1309 	 * Assimilate more pages from the global page pool into the cage.
1310 	 */
1311 	n = 0;				/* number of pages PP_SETNORELOC'd */
1312 	nf = 0;				/* number of those actually free */
1313 	while (kcage_on && nf < wanted) {
1314 		pfn = kcage_get_pfn();
1315 		if (pfn == PFN_INVALID) {	/* eek! no where to grow */
1316 			KCAGE_STAT_INCR(ke_nopfn);
1317 			goto terminate;
1318 		}
1319 
1320 		KCAGE_STAT_INCR_SCAN(ke_examined);
1321 
1322 		if ((pp = page_numtopp_nolock(pfn)) == NULL) {
1323 			KCAGE_STAT_INCR(ke_nopaget);
1324 			continue;
1325 		}
1326 		KCAGEPAGETS_INC();
1327 		/*
1328 		 * Sanity check. Skip this pfn if it is
1329 		 * being deleted.
1330 		 */
1331 		if (pfn_is_being_deleted(pfn)) {
1332 			KCAGE_STAT_INCR(ke_deleting);
1333 			continue;
1334 		}
1335 
1336 		/*
1337 		 * NORELOC is only set at boot-time or by this routine
1338 		 * under the kcage_range_mutex lock which is currently
1339 		 * held. This means we can do a fast check here before
1340 		 * locking the page in kcage_assimilate_page.
1341 		 */
1342 		if (PP_ISNORELOC(pp)) {
1343 			KCAGE_STAT_INCR(ke_isnoreloc);
1344 			continue;
1345 		}
1346 
1347 		switch (kcage_assimilate_page(pp, &nfreed)) {
1348 			case 0:		/* assimilated, page is free */
1349 				KCAGE_STAT_NINCR_SCAN(ke_gotonefree, nfreed);
1350 				did_something = 1;
1351 				nf += nfreed;
1352 				n++;
1353 				break;
1354 
1355 			case EBUSY:	/* assimilated, page not free */
1356 			case ERANGE:	/* assimilated, page not root */
1357 				KCAGE_STAT_INCR_SCAN(ke_gotone);
1358 				did_something = 1;
1359 				n++;
1360 				break;
1361 
1362 			case ENOMEM:	/* assimilated, but no mem */
1363 				KCAGE_STAT_INCR(ke_terminate);
1364 				did_something = 1;
1365 				n++;
1366 				goto terminate;
1367 
1368 			case EAGAIN:	/* can't assimilate */
1369 				KCAGE_STAT_INCR_SCAN(ke_lefthole);
1370 				break;
1371 
1372 			default:	/* catch this with debug kernels */
1373 				ASSERT(0);
1374 				break;
1375 		}
1376 	}
1377 
1378 	/*
1379 	 * Realign cage edge with the nearest physical address
1380 	 * boundry for big pages. This is done to give us a
1381 	 * better chance of actually getting usable big pages
1382 	 * in the cage.
1383 	 */
1384 
1385 terminate:
1386 	kcage_range_unlock();
1387 
1388 	return (did_something);
1389 }
1390 
1391 /*
1392  * Relocate page opp (Original Page Pointer) from cage pool to page rpp
1393  * (Replacement Page Pointer) in the global pool. Page opp will be freed
1394  * if relocation is successful, otherwise it is only unlocked.
1395  * On entry, page opp must be exclusively locked and not free.
1396  * *nfreedp: number of pages freed.
1397  */
1398 static int
1399 kcage_relocate_page(page_t *pp, pgcnt_t *nfreedp)
1400 {
1401 	page_t *opp = pp;
1402 	page_t *rpp = NULL;
1403 	spgcnt_t npgs;
1404 	int result;
1405 
1406 	ASSERT(!PP_ISFREE(opp));
1407 	ASSERT(PAGE_EXCL(opp));
1408 
1409 	result = page_relocate(&opp, &rpp, 1, 1, &npgs, NULL);
1410 	*nfreedp = npgs;
1411 	if (result == 0) {
1412 		while (npgs-- > 0) {
1413 			page_t *tpp;
1414 
1415 			ASSERT(rpp != NULL);
1416 			tpp = rpp;
1417 			page_sub(&rpp, tpp);
1418 			page_unlock(tpp);
1419 		}
1420 
1421 		ASSERT(rpp == NULL);
1422 
1423 		return (0);		/* success */
1424 	}
1425 
1426 	page_unlock(opp);
1427 	return (result);
1428 }
1429 
1430 /*
1431  * Based on page_invalidate_pages()
1432  *
1433  * Kcage_invalidate_page() uses page_relocate() twice. Both instances
1434  * of use must be updated to match the new page_relocate() when it
1435  * becomes available.
1436  *
1437  * Return result of kcage_relocate_page or zero if page was directly freed.
1438  * *nfreedp: number of pages freed.
1439  */
1440 static int
1441 kcage_invalidate_page(page_t *pp, pgcnt_t *nfreedp)
1442 {
1443 	int result;
1444 
1445 #if defined(__sparc)
1446 	extern struct vnode prom_ppages;
1447 	ASSERT(pp->p_vnode != &prom_ppages);
1448 #endif /* __sparc */
1449 
1450 	ASSERT(!PP_ISFREE(pp));
1451 	ASSERT(PAGE_EXCL(pp));
1452 
1453 	/*
1454 	 * Is this page involved in some I/O? shared?
1455 	 * The page_struct_lock need not be acquired to
1456 	 * examine these fields since the page has an
1457 	 * "exclusive" lock.
1458 	 */
1459 	if (pp->p_lckcnt != 0 || pp->p_cowcnt != 0) {
1460 		result = kcage_relocate_page(pp, nfreedp);
1461 #ifdef KCAGE_STATS
1462 		if (result == 0)
1463 			KCAGE_STAT_INCR_SCAN(kip_reloclocked);
1464 		else if (result == ENOMEM)
1465 			KCAGE_STAT_INCR_SCAN(kip_nomem);
1466 #endif
1467 		return (result);
1468 	}
1469 
1470 	ASSERT(pp->p_vnode->v_type != VCHR);
1471 
1472 	/*
1473 	 * Unload the mappings and check if mod bit is set.
1474 	 */
1475 	(void) hat_pageunload(pp, HAT_FORCE_PGUNLOAD);
1476 
1477 	if (hat_ismod(pp)) {
1478 		result = kcage_relocate_page(pp, nfreedp);
1479 #ifdef KCAGE_STATS
1480 		if (result == 0)
1481 			KCAGE_STAT_INCR_SCAN(kip_relocmod);
1482 		else if (result == ENOMEM)
1483 			KCAGE_STAT_INCR_SCAN(kip_nomem);
1484 #endif
1485 		return (result);
1486 	}
1487 
1488 	if (!page_try_demote_pages(pp)) {
1489 		KCAGE_STAT_INCR_SCAN(kip_demotefailed);
1490 		page_unlock(pp);
1491 		return (EAGAIN);
1492 	}
1493 
1494 	page_destroy(pp, 0);
1495 	KCAGE_STAT_INCR_SCAN(kip_destroy);
1496 	*nfreedp = 1;
1497 	return (0);
1498 }
1499 
1500 static void
1501 kcage_cageout()
1502 {
1503 	pfn_t pfn;
1504 	page_t *pp;
1505 	callb_cpr_t cprinfo;
1506 	int did_something;
1507 	int scan_again;
1508 	pfn_t start_pfn;
1509 	int pass;
1510 	int last_pass;
1511 	int pages_skipped;
1512 	int shared_skipped;
1513 	uint_t shared_level = 8;
1514 	pgcnt_t nfreed;
1515 #ifdef KCAGE_STATS
1516 	clock_t scan_start;
1517 #endif
1518 
1519 	CALLB_CPR_INIT(&cprinfo, &kcage_cageout_mutex,
1520 		callb_generic_cpr, "cageout");
1521 
1522 	mutex_enter(&kcage_cageout_mutex);
1523 	kcage_cageout_thread = curthread;
1524 
1525 	pfn = PFN_INVALID;		/* force scan reset */
1526 	start_pfn = PFN_INVALID;	/* force init with 1st cage pfn */
1527 	kcage_cageout_ready = 1;	/* switch kcage_cageout_wakeup mode */
1528 
1529 loop:
1530 	/*
1531 	 * Wait here. Sooner or later, kcage_freemem_sub() will notice
1532 	 * that kcage_freemem is less than kcage_desfree. When it does
1533 	 * notice, kcage_freemem_sub() will wake us up via call to
1534 	 * kcage_cageout_wakeup().
1535 	 */
1536 	CALLB_CPR_SAFE_BEGIN(&cprinfo);
1537 	cv_wait(&kcage_cageout_cv, &kcage_cageout_mutex);
1538 	CALLB_CPR_SAFE_END(&cprinfo, &kcage_cageout_mutex);
1539 
1540 	KCAGE_STAT_INCR(kt_wakeups);
1541 	KCAGE_STAT_SET_SCAN(kt_freemem_start, freemem);
1542 	KCAGE_STAT_SET_SCAN(kt_kcage_freemem_start, kcage_freemem);
1543 	pass = 0;
1544 	last_pass = 0;
1545 
1546 #ifdef KCAGE_STATS
1547 	scan_start = lbolt;
1548 #endif
1549 
1550 again:
1551 	if (!kcage_on)
1552 		goto loop;
1553 
1554 	KCAGE_STAT_INCR(kt_scans);
1555 	KCAGE_STAT_INCR_SCAN(kt_passes);
1556 
1557 	did_something = 0;
1558 	pages_skipped = 0;
1559 	shared_skipped = 0;
1560 	while ((kcage_freemem < kcage_lotsfree || kcage_needfree) &&
1561 		(pfn = kcage_walk_cage(pfn == PFN_INVALID)) != PFN_INVALID) {
1562 
1563 		if (start_pfn == PFN_INVALID)
1564 			start_pfn = pfn;
1565 		else if (start_pfn == pfn) {
1566 			last_pass = pass;
1567 			pass += 1;
1568 			/*
1569 			 * Did a complete walk of kernel cage, but didn't free
1570 			 * any pages.  If only one cpu is online then
1571 			 * stop kernel cage walk and try expanding.
1572 			 */
1573 			if (ncpus_online == 1 && did_something == 0) {
1574 				KCAGE_STAT_INCR(kt_cageout_break);
1575 				break;
1576 			}
1577 		}
1578 
1579 		pp = page_numtopp_nolock(pfn);
1580 		if (pp == NULL) {
1581 			continue;
1582 		}
1583 
1584 		KCAGE_STAT_INCR_SCAN(kt_examined);
1585 
1586 		/*
1587 		 * Do a quick PP_ISNORELOC() and PP_ISFREE test outside
1588 		 * of the lock. If one is missed it will be seen next
1589 		 * time through.
1590 		 *
1591 		 * Skip non-caged-pages. These pages can exist in the cage
1592 		 * because, if during cage expansion, a page is
1593 		 * encountered that is long-term locked the lock prevents the
1594 		 * expansion logic from setting the P_NORELOC flag. Hence,
1595 		 * non-caged-pages surrounded by caged-pages.
1596 		 */
1597 		if (!PP_ISNORELOC(pp)) {
1598 			switch (kcage_assimilate_page(pp, &nfreed)) {
1599 				case 0:
1600 					did_something = 1;
1601 					KCAGE_STAT_NINCR_SCAN(kt_gotonefree,
1602 					    nfreed);
1603 					break;
1604 
1605 				case EBUSY:
1606 				case ERANGE:
1607 					did_something = 1;
1608 					KCAGE_STAT_INCR_SCAN(kt_gotone);
1609 					break;
1610 
1611 				case EAGAIN:
1612 				case ENOMEM:
1613 					break;
1614 
1615 				default:
1616 					/* catch this with debug kernels */
1617 					ASSERT(0);
1618 					break;
1619 			}
1620 
1621 			continue;
1622 		} else {
1623 			int prm;
1624 
1625 			if (PP_ISFREE(pp)) {
1626 				continue;
1627 			}
1628 
1629 			if ((pp->p_vnode == &kvp && pp->p_lckcnt > 0) ||
1630 			    !page_trylock(pp, SE_EXCL)) {
1631 				KCAGE_STAT_INCR_SCAN(kt_cantlock);
1632 				continue;
1633 			}
1634 
1635 			/* P_NORELOC bit should not have gone away. */
1636 			ASSERT(PP_ISNORELOC(pp));
1637 			if (PP_ISFREE(pp) || (pp->p_vnode == &kvp &&
1638 			    pp->p_lckcnt > 0)) {
1639 				page_unlock(pp);
1640 				continue;
1641 			}
1642 
1643 			KCAGE_STAT_SET_SCAN(kt_skiplevel, shared_level);
1644 			if (hat_page_getshare(pp) > shared_level) {
1645 				page_unlock(pp);
1646 				pages_skipped = 1;
1647 				shared_skipped = 1;
1648 				KCAGE_STAT_INCR_SCAN(kt_skipshared);
1649 				continue;
1650 			}
1651 
1652 			/*
1653 			 * In pass {0, 1}, skip page if ref bit is set.
1654 			 * In pass {0, 1, 2}, skip page if mod bit is set.
1655 			 */
1656 			prm = hat_pagesync(pp,
1657 				HAT_SYNC_DONTZERO | HAT_SYNC_STOPON_MOD);
1658 
1659 			/* On first pass ignore ref'd pages */
1660 			if (pass <= 1 && (prm & P_REF)) {
1661 				KCAGE_STAT_INCR_SCAN(kt_skiprefd);
1662 				pages_skipped = 1;
1663 				page_unlock(pp);
1664 				continue;
1665 			}
1666 
1667 			/* On pass 2, page_destroy if mod bit is not set */
1668 			if (pass <= 2) {
1669 				if (pp->p_szc != 0 || (prm & P_MOD) ||
1670 					pp->p_lckcnt || pp->p_cowcnt) {
1671 					pages_skipped = 1;
1672 					page_unlock(pp);
1673 				} else {
1674 
1675 					/*
1676 					 * unload the mappings before
1677 					 * checking if mod bit is set
1678 					 */
1679 					(void) hat_pageunload(pp,
1680 						HAT_FORCE_PGUNLOAD);
1681 
1682 					/*
1683 					 * skip this page if modified
1684 					 */
1685 					if (hat_ismod(pp)) {
1686 						pages_skipped = 1;
1687 						page_unlock(pp);
1688 						continue;
1689 					}
1690 
1691 					KCAGE_STAT_INCR_SCAN(kt_destroy);
1692 					page_destroy(pp, 0);
1693 					did_something = 1;
1694 				}
1695 				continue;
1696 			}
1697 
1698 			if (kcage_invalidate_page(pp, &nfreed) == 0) {
1699 				did_something = 1;
1700 				KCAGE_STAT_NINCR_SCAN(kt_gotonefree, nfreed);
1701 			}
1702 
1703 			/*
1704 			 * No need to drop the page lock here.
1705 			 * Kcage_invalidate_page has done that for us
1706 			 * either explicitly or through a page_free.
1707 			 */
1708 		}
1709 	}
1710 
1711 	/*
1712 	 * Expand the cage only if available cage memory is really low.
1713 	 * This test is done only after a complete scan of the cage.
1714 	 * The reason for not checking and expanding more often is to
1715 	 * avoid rapid expansion of the cage. Naturally, scanning the
1716 	 * cage takes time. So by scanning first, we use that work as a
1717 	 * delay loop in between expand decisions.
1718 	 */
1719 
1720 	scan_again = 0;
1721 	if (kcage_freemem < kcage_minfree || kcage_needfree) {
1722 		/*
1723 		 * Kcage_expand() will return a non-zero value if it was
1724 		 * able to expand the cage -- whether or not the new
1725 		 * pages are free and immediately usable. If non-zero,
1726 		 * we do another scan of the cage. The pages might be
1727 		 * freed during that scan or by time we get back here.
1728 		 * If not, we will attempt another expansion.
1729 		 * However, if kcage_expand() returns zero, then it was
1730 		 * unable to expand the cage. This is the case when the
1731 		 * the growth list is exausted, therefore no work was done
1732 		 * and there is no reason to scan the cage again.
1733 		 * Note: Kernel cage scan is not repeated on single-cpu
1734 		 * system to avoid kernel cage thread hogging cpu.
1735 		 */
1736 		if (pass <= 3 && pages_skipped && ncpus_online > 1)
1737 			scan_again = 1;
1738 		else
1739 			(void) kcage_expand(); /* don't scan again */
1740 	} else if (kcage_freemem < kcage_lotsfree) {
1741 		/*
1742 		 * If available cage memory is less than abundant
1743 		 * and a full scan of the cage has not yet been completed,
1744 		 * or a scan has completed and some work was performed,
1745 		 * or pages were skipped because of sharing,
1746 		 * or we simply have not yet completed two passes,
1747 		 * then do another scan.
1748 		 */
1749 		if (pass <= 2 && pages_skipped)
1750 			scan_again = 1;
1751 		if (pass == last_pass || did_something)
1752 			scan_again = 1;
1753 		else if (shared_skipped && shared_level < (8<<24)) {
1754 			shared_level <<= 1;
1755 			scan_again = 1;
1756 		}
1757 	}
1758 
1759 	if (scan_again && ncpus_online > 1)
1760 		goto again;
1761 	else {
1762 		if (shared_level > 8)
1763 			shared_level >>= 1;
1764 
1765 		KCAGE_STAT_SET_SCAN(kt_freemem_end, freemem);
1766 		KCAGE_STAT_SET_SCAN(kt_kcage_freemem_end, kcage_freemem);
1767 		KCAGE_STAT_SET_SCAN(kt_ticks, lbolt - scan_start);
1768 		KCAGE_STAT_INC_SCAN_INDEX;
1769 		goto loop;
1770 	}
1771 
1772 	/*NOTREACHED*/
1773 }
1774 
1775 void
1776 kcage_cageout_wakeup()
1777 {
1778 	if (mutex_tryenter(&kcage_cageout_mutex)) {
1779 		if (kcage_cageout_ready) {
1780 			cv_signal(&kcage_cageout_cv);
1781 		} else if (kcage_freemem < kcage_minfree || kcage_needfree) {
1782 			/*
1783 			 * Available cage memory is really low. Time to
1784 			 * start expanding the cage. However, the
1785 			 * kernel cage thread is not yet ready to
1786 			 * do the work. Use *this* thread, which is
1787 			 * most likely to be t0, to do the work.
1788 			 */
1789 			KCAGE_STAT_INCR(kcw_expandearly);
1790 			(void) kcage_expand();
1791 			KCAGE_STAT_INC_SCAN_INDEX;
1792 		}
1793 
1794 		mutex_exit(&kcage_cageout_mutex);
1795 	}
1796 	/* else, kernel cage thread is already running */
1797 }
1798 
1799 void
1800 kcage_tick()
1801 {
1802 	/*
1803 	 * Once per second we wake up all the threads throttled
1804 	 * waiting for cage memory, in case we've become stuck
1805 	 * and haven't made forward progress expanding the cage.
1806 	 */
1807 	if (kcage_on && kcage_cageout_ready)
1808 		cv_broadcast(&kcage_throttle_cv);
1809 }
1810