xref: /titanic_51/usr/src/uts/common/vm/page_retire.c (revision fe0e7ec4d916b05b52d8c7cc8a3e6a1b28e77b6f)
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, Version 1.0 only
6  * (the "License").  You may not use this file except in compliance
7  * with the License.
8  *
9  * You can obtain a copy of the license at usr/src/OPENSOLARIS.LICENSE
10  * or http://www.opensolaris.org/os/licensing.
11  * See the License for the specific language governing permissions
12  * and limitations under the License.
13  *
14  * When distributing Covered Code, include this CDDL HEADER in each
15  * file and include the License file at usr/src/OPENSOLARIS.LICENSE.
16  * If applicable, add the following below this CDDL HEADER, with the
17  * fields enclosed by brackets "[]" replaced with your own identifying
18  * information: Portions Copyright [yyyy] [name of copyright owner]
19  *
20  * CDDL HEADER END
21  */
22 /*
23  * Copyright 2005 Sun Microsystems, Inc.  All rights reserved.
24  * Use is subject to license terms.
25  */
26 
27 #pragma ident	"%Z%%M%	%I%	%E% SMI"
28 
29 /*
30  * Page Retire - Big Theory Statement.
31  *
32  * This file handles removing sections of faulty memory from use when the
33  * user land FMA Diagnosis Engine requests that a page be removed or when
34  * a CE or UE is detected by the hardware.
35  *
36  * In the bad old days, the kernel side of Page Retire did a lot of the work
37  * on its own. Now, with the DE keeping track of errors, the kernel side is
38  * rather simple minded on most platforms.
39  *
40  * Errors are all reflected to the DE, and after digesting the error and
41  * looking at all previously reported errors, the DE decides what should
42  * be done about the current error. If the DE wants a particular page to
43  * be retired, then the kernel page retire code is invoked via an ioctl.
44  * On non-FMA platforms, the ue_drain and ce_drain paths ends up calling
45  * page retire to handle the error. Since page retire is just a simple
46  * mechanism it doesn't need to differentiate between the different callers.
47  *
48  * The p_toxic field in the page_t is used to indicate which errors have
49  * occurred and what action has been taken on a given page. Because errors are
50  * reported without regard to the locked state of a page, no locks are used
51  * to SET the error bits in p_toxic. However, in order to clear the error
52  * bits, the page_t must be held exclusively locked.
53  *
54  * When page_retire() is called, it must be able to acquire locks, sleep, etc.
55  * It must not be called from high-level interrupt context.
56  *
57  * Depending on how the requested page is being used at the time of the retire
58  * request (and on the availability of sufficient system resources), the page
59  * may be retired immediately, or just marked for retirement later. For
60  * example, locked pages are marked, while free pages are retired. Multiple
61  * requests may be made to retire the same page, although there is no need
62  * to: once the p_toxic flags are set, the page will be retired as soon as it
63  * can be exclusively locked.
64  *
65  * The retire mechanism is driven centrally out of page_unlock(). To expedite
66  * the retirement of pages, further requests for SE_SHARED locks are denied
67  * as long as a page retirement is pending. In addition, as long as pages are
68  * pending retirement a background thread runs periodically trying to retire
69  * those pages. Pages which could not be retired while the system is running
70  * are scrubbed prior to rebooting to avoid latent errors on the next boot.
71  *
72  * Single CE pages and UE pages without persistent errors are scrubbed and
73  * returned to service. Recidivist pages, as well as FMA-directed requests
74  * for retirement, result in the page being taken out of service. Once the
75  * decision is made to take a page out of service, the page is cleared, hashed
76  * onto the retired_pages vnode, marked as retired, and it is unlocked.  No
77  * other requesters (except for unretire) are allowed to lock retired pages.
78  *
79  * The public routines return (sadly) 0 if they worked and a non-zero error
80  * value if something went wrong. This is done for the ioctl side of the
81  * world to allow errors to be reflected all the way out to user land. The
82  * non-zero values are explained in comments atop each function.
83  */
84 
85 /*
86  * Things to fix:
87  *
88  * 	1. Cleanup SE_EWANTED.  Since we're aggressive about trying to retire
89  *	pages, we can use page_retire_pp() to replace SE_EWANTED and all
90  *	the special delete_memory_thread() code just goes away.
91  *
92  * 	2. Trying to retire non-relocatable kvp pages may result in a
93  *      quagmire. This is because seg_kmem() no longer keeps its pages locked,
94  *      and calls page_lookup() in the free path; since kvp pages are modified
95  *      and don't have a usable backing store, page_retire() can't do anything
96  *      with them, and we'll keep denying the lock to seg_kmem_free() in a
97  *      vicious cycle. To prevent that, we don't deny locks to kvp pages, and
98  *      hence only call page_retire_pp() from page_unlock() in the free path.
99  *      Since most kernel pages are indefinitely held anyway, and don't
100  *      participate in I/O, this is of little consequence.
101  *
102  *      3. Low memory situations will be interesting. If we don't have
103  *      enough memory for page_relocate() to succeed, we won't be able to
104  *      retire dirty pages; nobody will be able to push them out to disk
105  *      either, since we aggressively deny the page lock. We could change
106  *      fsflush so it can recognize this situation, grab the lock, and push
107  *      the page out, where we'll catch it in the free path and retire it.
108  *
109  *	4. Beware of places that have code like this in them:
110  *
111  *		if (! page_tryupgrade(pp)) {
112  *			page_unlock(pp);
113  *			while (! page_lock(pp, SE_EXCL, NULL, P_RECLAIM)) {
114  *				/ *NOTHING* /
115  *			}
116  *		}
117  *		page_free(pp);
118  *
119  *	The problem is that pp can change identity right after the
120  *	page_unlock() call.  In particular, page_retire() can step in
121  *	there, change pp's identity, and hash pp onto the retired_vnode.
122  *
123  *	Of course, other functions besides page_retire() can have the
124  *	same effect. A kmem reader can waltz by, set up a mapping to the
125  *	page, and then unlock the page. Page_free() will then go castors
126  *	up. So if anybody is doing this, it's already a bug.
127  *
128  *      5. mdboot()'s call into page_retire_hunt() should probably be
129  *      moved lower. Where the call is made now, we can get into trouble
130  *      by scrubbing a kernel page that is then accessed later.
131  */
132 
133 #include <sys/types.h>
134 #include <sys/param.h>
135 #include <sys/systm.h>
136 #include <sys/mman.h>
137 #include <sys/vnode.h>
138 #include <sys/cmn_err.h>
139 #include <sys/ksynch.h>
140 #include <sys/thread.h>
141 #include <sys/disp.h>
142 #include <sys/ontrap.h>
143 #include <sys/vmsystm.h>
144 #include <sys/mem_config.h>
145 #include <sys/atomic.h>
146 #include <sys/callb.h>
147 #include <vm/page.h>
148 #include <vm/vm_dep.h>
149 #include <vm/as.h>
150 #include <vm/hat.h>
151 
152 /*
153  * vnode for all pages which are retired from the VM system;
154  */
155 vnode_t *retired_pages;
156 
157 /*
158  * Background thread that wakes up periodically to try to retire pending
159  * pages. This prevents threads from becoming blocked indefinitely in
160  * page_lookup() or some other routine should the page(s) they are waiting
161  * on become eligible for social security.
162  */
163 static void page_retire_thread(void);
164 static kthread_t *pr_thread_id;
165 static kcondvar_t pr_cv;
166 static kmutex_t pr_thread_mutex;
167 static clock_t pr_thread_shortwait;
168 static clock_t pr_thread_longwait;
169 
170 /*
171  * Make a list of all of the pages that have been marked for retirement
172  * but are not yet retired.  At system shutdown, we will scrub all of the
173  * pages in the list in case there are outstanding UEs.  Then, we
174  * cross-check this list against the number of pages that are yet to be
175  * retired, and if we find inconsistencies, we scan every page_t in the
176  * whole system looking for any pages that need to be scrubbed for UEs.
177  * The background thread also uses this queue to determine which pages
178  * it should keep trying to retire.
179  */
180 #ifdef	DEBUG
181 #define	PR_PENDING_QMAX	32
182 #else	/* DEBUG */
183 #define	PR_PENDING_QMAX	256
184 #endif	/* DEBUG */
185 page_t		*pr_pending_q[PR_PENDING_QMAX];
186 kmutex_t	pr_q_mutex;
187 
188 /*
189  * Page retire global kstats
190  */
191 struct page_retire_kstat {
192 	kstat_named_t	pr_retired;
193 	kstat_named_t	pr_requested;
194 	kstat_named_t	pr_requested_free;
195 	kstat_named_t	pr_enqueue_fail;
196 	kstat_named_t	pr_dequeue_fail;
197 	kstat_named_t	pr_pending;
198 	kstat_named_t	pr_failed;
199 	kstat_named_t	pr_failed_kernel;
200 	kstat_named_t	pr_limit;
201 	kstat_named_t	pr_limit_exceeded;
202 	kstat_named_t	pr_fma;
203 	kstat_named_t	pr_mce;
204 	kstat_named_t	pr_ue;
205 	kstat_named_t	pr_ue_cleared_retire;
206 	kstat_named_t	pr_ue_cleared_free;
207 	kstat_named_t	pr_ue_persistent;
208 	kstat_named_t	pr_unretired;
209 };
210 
211 static struct page_retire_kstat page_retire_kstat = {
212 	{ "pages_retired",		KSTAT_DATA_UINT64},
213 	{ "pages_retire_request",	KSTAT_DATA_UINT64},
214 	{ "pages_retire_request_free",	KSTAT_DATA_UINT64},
215 	{ "pages_notenqueued", 		KSTAT_DATA_UINT64},
216 	{ "pages_notdequeued", 		KSTAT_DATA_UINT64},
217 	{ "pages_pending", 		KSTAT_DATA_UINT64},
218 	{ "pages_deferred",		KSTAT_DATA_UINT64},
219 	{ "pages_deferred_kernel",	KSTAT_DATA_UINT64},
220 	{ "pages_limit",		KSTAT_DATA_UINT64},
221 	{ "pages_limit_exceeded",	KSTAT_DATA_UINT64},
222 	{ "pages_fma",			KSTAT_DATA_UINT64},
223 	{ "pages_multiple_ce",		KSTAT_DATA_UINT64},
224 	{ "pages_ue",			KSTAT_DATA_UINT64},
225 	{ "pages_ue_cleared_retired",	KSTAT_DATA_UINT64},
226 	{ "pages_ue_cleared_freed",	KSTAT_DATA_UINT64},
227 	{ "pages_ue_persistent",	KSTAT_DATA_UINT64},
228 	{ "pages_unretired",		KSTAT_DATA_UINT64},
229 };
230 
231 static kstat_t  *page_retire_ksp = NULL;
232 
233 #define	PR_INCR_KSTAT(stat)	\
234 	atomic_add_64(&(page_retire_kstat.stat.value.ui64), 1)
235 #define	PR_DECR_KSTAT(stat)	\
236 	atomic_add_64(&(page_retire_kstat.stat.value.ui64), -1)
237 
238 #define	PR_KSTAT_RETIRED_CE	(page_retire_kstat.pr_mce.value.ui64)
239 #define	PR_KSTAT_RETIRED_FMA	(page_retire_kstat.pr_fma.value.ui64)
240 #define	PR_KSTAT_RETIRED_NOTUE	(PR_KSTAT_RETIRED_CE + PR_KSTAT_RETIRED_FMA)
241 #define	PR_KSTAT_PENDING	(page_retire_kstat.pr_pending.value.ui64)
242 #define	PR_KSTAT_EQFAIL		(page_retire_kstat.pr_enqueue_fail.value.ui64)
243 #define	PR_KSTAT_DQFAIL		(page_retire_kstat.pr_dequeue_fail.value.ui64)
244 
245 /*
246  * Limit the number of multiple CE page retires.
247  * The default is 0.1% of physmem, or 1 in 1000 pages. This is set in
248  * basis points, where 100 basis points equals one percent.
249  */
250 #define	MCE_BPT	10
251 uint64_t	max_pages_retired_bps = MCE_BPT;
252 #define	PAGE_RETIRE_LIMIT	((physmem * max_pages_retired_bps) / 10000)
253 
254 /*
255  * Control over the verbosity of page retirement.
256  *
257  * When set to zero (the default), no messages will be printed.
258  * When set to one, summary messages will be printed.
259  * When set > one, all messages will be printed.
260  *
261  * A value of one will trigger detailed messages for retirement operations,
262  * and is intended as a platform tunable for processors where FMA's DE does
263  * not run (e.g., spitfire). Values > one are intended for debugging only.
264  */
265 int page_retire_messages = 0;
266 
267 /*
268  * Control whether or not we return scrubbed UE pages to service.
269  * By default we do not since FMA wants to run its diagnostics first
270  * and then ask us to unretire the page if it passes. Non-FMA platforms
271  * may set this to zero so we will only retire recidivist pages. It should
272  * not be changed by the user.
273  */
274 int page_retire_first_ue = 1;
275 
276 /*
277  * Master enable for page retire. This prevents a CE or UE early in boot
278  * from trying to retire a page before page_retire_init() has finished
279  * setting things up. This is internal only and is not a tunable!
280  */
281 static int pr_enable = 0;
282 
283 extern struct vnode kvp;
284 
285 #ifdef	DEBUG
286 struct page_retire_debug {
287 	int prd_dup;
288 	int prd_noaction;
289 	int prd_queued;
290 	int prd_notqueued;
291 	int prd_dequeue;
292 	int prd_top;
293 	int prd_locked;
294 	int prd_reloc;
295 	int prd_relocfail;
296 	int prd_mod;
297 	int prd_mod_late;
298 	int prd_kern;
299 	int prd_free;
300 	int prd_noreclaim;
301 	int prd_hashout;
302 	int prd_fma;
303 	int prd_uescrubbed;
304 	int prd_uenotscrubbed;
305 	int prd_mce;
306 	int prd_prlocked;
307 	int prd_prnotlocked;
308 	int prd_prretired;
309 	int prd_ulocked;
310 	int prd_unotretired;
311 	int prd_udestroy;
312 	int prd_uhashout;
313 	int prd_uunretired;
314 	int prd_unotlocked;
315 	int prd_checkhit;
316 	int prd_checkmiss;
317 	int prd_tctop;
318 	int prd_tclocked;
319 	int prd_hunt;
320 	int prd_dohunt;
321 	int prd_earlyhunt;
322 	int prd_latehunt;
323 	int prd_nofreedemote;
324 	int prd_nodemote;
325 	int prd_demoted;
326 } pr_debug;
327 
328 #define	PR_DEBUG(foo)	((pr_debug.foo)++)
329 
330 /*
331  * A type histogram. We record the incidence of the various toxic
332  * flag combinations along with the interesting page attributes. The
333  * goal is to get as many combinations as we can while driving all
334  * pr_debug values nonzero (indicating we've exercised all possible
335  * code paths across all possible page types). Not all combinations
336  * will make sense -- e.g. PRT_MOD|PRT_KERNEL.
337  *
338  * pr_type offset bit encoding (when examining with a debugger):
339  *
340  *    PRT_NAMED  - 0x4
341  *    PRT_KERNEL - 0x8
342  *    PRT_FREE   - 0x10
343  *    PRT_MOD    - 0x20
344  *    PRT_FMA    - 0x0
345  *    PRT_MCE    - 0x40
346  *    PRT_UE     - 0x80
347  */
348 
349 #define	PRT_NAMED	0x01
350 #define	PRT_KERNEL	0x02
351 #define	PRT_FREE	0x04
352 #define	PRT_MOD		0x08
353 #define	PRT_FMA		0x00	/* yes, this is not a mistake */
354 #define	PRT_MCE		0x10
355 #define	PRT_UE		0x20
356 #define	PRT_ALL		0x3F
357 
358 int pr_types[PRT_ALL+1];
359 
360 #define	PR_TYPES(pp)	{			\
361 	int whichtype = 0;			\
362 	if (pp->p_vnode)			\
363 		whichtype |= PRT_NAMED;		\
364 	if (PP_ISKVP(pp))			\
365 		whichtype |= PRT_KERNEL;	\
366 	if (PP_ISFREE(pp))			\
367 		whichtype |= PRT_FREE;		\
368 	if (hat_ismod(pp))			\
369 		whichtype |= PRT_MOD;		\
370 	if (pp->p_toxic & PR_UE)		\
371 		whichtype |= PRT_UE;		\
372 	if (pp->p_toxic & PR_MCE)		\
373 		whichtype |= PRT_MCE;		\
374 	pr_types[whichtype]++;			\
375 }
376 
377 int recl_calls;
378 int recl_mtbf = 3;
379 int reloc_calls;
380 int reloc_mtbf = 7;
381 int pr_calls;
382 int pr_mtbf = 15;
383 
384 #define	MTBF(v, f)	(((++(v)) & (f)) != (f))
385 
386 #else	/* DEBUG */
387 
388 #define	PR_DEBUG(foo)	/* nothing */
389 #define	PR_TYPES(foo)	/* nothing */
390 #define	MTBF(v, f)	(1)
391 
392 #endif	/* DEBUG */
393 
394 /*
395  * page_retire_done() - completion processing
396  *
397  * Used by the page_retire code for common completion processing.
398  * It keeps track of how many times a given result has happened,
399  * and writes out an occasional message.
400  *
401  * May be called with a NULL pp (PRD_INVALID_PA case).
402  */
403 #define	PRD_INVALID_KEY		-1
404 #define	PRD_SUCCESS		0
405 #define	PRD_PENDING		1
406 #define	PRD_FAILED		2
407 #define	PRD_DUPLICATE		3
408 #define	PRD_INVALID_PA		4
409 #define	PRD_LIMIT		5
410 #define	PRD_UE_SCRUBBED		6
411 #define	PRD_UNR_SUCCESS		7
412 #define	PRD_UNR_CANTLOCK	8
413 #define	PRD_UNR_NOT		9
414 
415 typedef struct page_retire_op {
416 	int	pr_key;		/* one of the PRD_* defines from above */
417 	int	pr_count;	/* How many times this has happened */
418 	int	pr_retval;	/* return value */
419 	int	pr_msglvl;	/* message level - when to print */
420 	char	*pr_message;	/* Cryptic message for field service */
421 } page_retire_op_t;
422 
423 static page_retire_op_t page_retire_ops[] = {
424 	/* key			count	retval	msglvl	message */
425 	{PRD_SUCCESS,		0,	0,	1,
426 		"Page 0x%08x.%08x removed from service"},
427 	{PRD_PENDING,		0,	EAGAIN,	2,
428 		"Page 0x%08x.%08x will be retired on free"},
429 	{PRD_FAILED,		0,	EAGAIN,	0, NULL},
430 	{PRD_DUPLICATE,		0,	EBUSY,	2,
431 		"Page 0x%08x.%08x already retired"},
432 	{PRD_INVALID_PA,	0,	EINVAL, 2,
433 		"PA 0x%08x.%08x is not a relocatable page"},
434 	{PRD_LIMIT,		0,	0,	1,
435 		"Page 0x%08x.%08x not retired due to limit exceeded"},
436 	{PRD_UE_SCRUBBED,	0,	0,	1,
437 		"Previously reported error on page 0x%08x.%08x cleared"},
438 	{PRD_UNR_SUCCESS,	0,	0,	1,
439 		"Page 0x%08x.%08x returned to service"},
440 	{PRD_UNR_CANTLOCK,	0,	EAGAIN,	2,
441 		"Page 0x%08x.%08x could not be unretired"},
442 	{PRD_UNR_NOT,		0,	EBADF,	2,
443 		"Page 0x%08x.%08x is not retired"},
444 	{PRD_INVALID_KEY,	0,	0,	0, NULL} /* MUST BE LAST! */
445 };
446 
447 /*
448  * print a message if page_retire_messages is true.
449  */
450 #define	PR_MESSAGE(debuglvl, msglvl, msg, pa)				\
451 {									\
452 	uint64_t p = (uint64_t)pa;					\
453 	if (page_retire_messages >= msglvl && msg != NULL) {		\
454 		cmn_err(debuglvl, msg,					\
455 		    (uint32_t)(p >> 32), (uint32_t)p);			\
456 	}								\
457 }
458 
459 /*
460  * Note that multiple bits may be set in a single settoxic operation.
461  * May be called without the page locked.
462  */
463 void
464 page_settoxic(page_t *pp, uchar_t bits)
465 {
466 	atomic_or_8(&pp->p_toxic, bits);
467 }
468 
469 /*
470  * Note that multiple bits may cleared in a single clrtoxic operation.
471  * Must be called with the page exclusively locked.
472  */
473 void
474 page_clrtoxic(page_t *pp, uchar_t bits)
475 {
476 	ASSERT(PAGE_EXCL(pp));
477 	atomic_and_8(&pp->p_toxic, ~bits);
478 }
479 
480 /*
481  * Prints any page retire messages to the user, and decides what
482  * error code is appropriate for the condition reported.
483  */
484 static int
485 page_retire_done(page_t *pp, int code)
486 {
487 	page_retire_op_t *prop;
488 	uint64_t	pa = 0;
489 	int		i;
490 
491 	if (pp != NULL) {
492 		pa = mmu_ptob(pp->p_pagenum);
493 	}
494 
495 	prop = NULL;
496 	for (i = 0; page_retire_ops[i].pr_key != PRD_INVALID_KEY; i++) {
497 		if (page_retire_ops[i].pr_key == code) {
498 			prop = &page_retire_ops[i];
499 			break;
500 		}
501 	}
502 
503 #ifdef	DEBUG
504 	if (page_retire_ops[i].pr_key == PRD_INVALID_KEY) {
505 		cmn_err(CE_PANIC, "page_retire_done: Invalid opcode %d", code);
506 	}
507 #endif
508 
509 	ASSERT(prop->pr_key == code);
510 
511 	prop->pr_count++;
512 
513 	PR_MESSAGE(CE_NOTE, prop->pr_msglvl, prop->pr_message, pa);
514 	if (pp != NULL) {
515 		page_settoxic(pp, PR_MSG);
516 	}
517 
518 	return (prop->pr_retval);
519 }
520 
521 /*
522  * On a reboot, our friend mdboot() wants to clear up any PP_PR_REQ() pages
523  * that we were not able to retire. On large machines, walking the complete
524  * page_t array and looking at every page_t takes too long. So, as a page is
525  * marked toxic, we track it using a list that can be processed at reboot
526  * time.  page_retire_enqueue() will do its best to try to avoid duplicate
527  * entries, but if we get too many errors at once the queue can overflow,
528  * in which case we will end up walking every page_t as a last resort.
529  * The background thread also makes use of this queue to find which pages
530  * are pending retirement.
531  */
532 static void
533 page_retire_enqueue(page_t *pp)
534 {
535 	int	nslot = -1;
536 	int	i;
537 
538 	mutex_enter(&pr_q_mutex);
539 
540 	/*
541 	 * Check to make sure retire hasn't already dequeued it.
542 	 * In the meantime if the page was cleaned up, no need
543 	 * to enqueue it.
544 	 */
545 	if (PP_RETIRED(pp) || pp->p_toxic == 0) {
546 		mutex_exit(&pr_q_mutex);
547 		PR_DEBUG(prd_noaction);
548 		return;
549 	}
550 
551 	for (i = 0; i < PR_PENDING_QMAX; i++) {
552 		if (pr_pending_q[i] == pp) {
553 			mutex_exit(&pr_q_mutex);
554 			PR_DEBUG(prd_dup);
555 			return;
556 		} else if (nslot == -1 && pr_pending_q[i] == NULL) {
557 			nslot = i;
558 		}
559 	}
560 
561 	PR_INCR_KSTAT(pr_pending);
562 
563 	if (nslot != -1) {
564 		pr_pending_q[nslot] = pp;
565 		PR_DEBUG(prd_queued);
566 	} else {
567 		PR_INCR_KSTAT(pr_enqueue_fail);
568 		PR_DEBUG(prd_notqueued);
569 	}
570 	mutex_exit(&pr_q_mutex);
571 }
572 
573 static void
574 page_retire_dequeue(page_t *pp)
575 {
576 	int i;
577 
578 	mutex_enter(&pr_q_mutex);
579 
580 	for (i = 0; i < PR_PENDING_QMAX; i++) {
581 		if (pr_pending_q[i] == pp) {
582 			pr_pending_q[i] = NULL;
583 			break;
584 		}
585 	}
586 
587 	if (i == PR_PENDING_QMAX) {
588 		PR_INCR_KSTAT(pr_dequeue_fail);
589 	}
590 
591 	PR_DECR_KSTAT(pr_pending);
592 	PR_DEBUG(prd_dequeue);
593 
594 	mutex_exit(&pr_q_mutex);
595 }
596 
597 /*
598  * Act like page_destroy(), but instead of freeing the page, hash it onto
599  * the retired_pages vnode, and mark it retired.
600  *
601  * For fun, we try to scrub the page until it's squeaky clean.
602  * availrmem is adjusted here.
603  */
604 static void
605 page_retire_destroy(page_t *pp)
606 {
607 	u_offset_t off = (u_offset_t)((uintptr_t)pp);
608 
609 	ASSERT(PAGE_EXCL(pp));
610 	ASSERT(!PP_ISFREE(pp));
611 	ASSERT(pp->p_szc == 0);
612 	ASSERT(!hat_page_is_mapped(pp));
613 	ASSERT(!pp->p_vnode);
614 
615 	page_clr_all_props(pp);
616 	pagescrub(pp, 0, MMU_PAGESIZE);
617 
618 	pp->p_next = NULL;
619 	pp->p_prev = NULL;
620 	if (page_hashin(pp, retired_pages, off, NULL) == 0) {
621 		cmn_err(CE_PANIC, "retired page %p hashin failed", (void *)pp);
622 	}
623 
624 	page_settoxic(pp, PR_RETIRED);
625 	page_clrtoxic(pp, PR_BUSY);
626 	page_retire_dequeue(pp);
627 	PR_INCR_KSTAT(pr_retired);
628 
629 	if (pp->p_toxic & PR_FMA) {
630 		PR_INCR_KSTAT(pr_fma);
631 	} else if (pp->p_toxic & PR_UE) {
632 		PR_INCR_KSTAT(pr_ue);
633 	} else {
634 		PR_INCR_KSTAT(pr_mce);
635 	}
636 
637 	mutex_enter(&freemem_lock);
638 	availrmem--;
639 	mutex_exit(&freemem_lock);
640 
641 	page_unlock(pp);
642 }
643 
644 /*
645  * Check whether the number of pages which have been retired already exceeds
646  * the maximum allowable percentage of memory which may be retired.
647  *
648  * Returns 1 if the limit has been exceeded.
649  */
650 static int
651 page_retire_limit(void)
652 {
653 	if (PR_KSTAT_RETIRED_NOTUE >= (uint64_t)PAGE_RETIRE_LIMIT) {
654 		PR_INCR_KSTAT(pr_limit_exceeded);
655 		return (1);
656 	}
657 
658 	return (0);
659 }
660 
661 #define	MSG_DM	"Data Mismatch occurred at PA 0x%08x.%08x"		\
662 	"[ 0x%x != 0x%x ] while attempting to clear previously "	\
663 	"reported error; page removed from service"
664 
665 #define	MSG_UE	"Uncorrectable Error occurred at PA 0x%08x.%08x while "	\
666 	"attempting to clear previously reported error; page removed "	\
667 	"from service"
668 
669 /*
670  * Attempt to clear a UE from a page.
671  * Returns 1 if the error has been successfully cleared.
672  */
673 static int
674 page_clear_transient_ue(page_t *pp)
675 {
676 	caddr_t		kaddr;
677 	uint8_t		rb, wb;
678 	uint64_t	pa;
679 	uint32_t	pa_hi, pa_lo;
680 	on_trap_data_t	otd;
681 	int		errors = 0;
682 	int		i;
683 
684 	ASSERT(PAGE_EXCL(pp));
685 	ASSERT(PP_PR_REQ(pp));
686 	ASSERT(pp->p_szc == 0);
687 	ASSERT(!hat_page_is_mapped(pp));
688 
689 	/*
690 	 * Clear the page and attempt to clear the UE.  If we trap
691 	 * on the next access to the page, we know the UE has recurred.
692 	 */
693 	pagescrub(pp, 0, PAGESIZE);
694 
695 	/*
696 	 * Map the page and write a bunch of bit patterns to compare
697 	 * what we wrote with what we read back.  This isn't a perfect
698 	 * test but it should be good enough to catch most of the
699 	 * recurring UEs. If this fails to catch a recurrent UE, we'll
700 	 * retire the page the next time we see a UE on the page.
701 	 */
702 	kaddr = ppmapin(pp, PROT_READ|PROT_WRITE, (caddr_t)-1);
703 
704 	pa = ptob((uint64_t)page_pptonum(pp));
705 	pa_hi = (uint32_t)(pa >> 32);
706 	pa_lo = (uint32_t)pa;
707 
708 	/*
709 	 * Fill the page with each (0x00 - 0xFF] bit pattern, flushing
710 	 * the cache in between reading and writing.  We do this under
711 	 * on_trap() protection to avoid recursion.
712 	 */
713 	if (on_trap(&otd, OT_DATA_EC)) {
714 		PR_MESSAGE(CE_WARN, 1, MSG_UE, pa);
715 		errors = 1;
716 	} else {
717 		for (wb = 0xff; wb > 0; wb--) {
718 			for (i = 0; i < PAGESIZE; i++) {
719 				kaddr[i] = wb;
720 			}
721 
722 			sync_data_memory(kaddr, PAGESIZE);
723 
724 			for (i = 0; i < PAGESIZE; i++) {
725 				rb = kaddr[i];
726 				if (rb != wb) {
727 					/*
728 					 * We had a mismatch without a trap.
729 					 * Uh-oh. Something is really wrong
730 					 * with this system.
731 					 */
732 					if (page_retire_messages) {
733 						cmn_err(CE_WARN, MSG_DM,
734 						    pa_hi, pa_lo, rb, wb);
735 					}
736 					errors = 1;
737 					goto out;	/* double break */
738 				}
739 			}
740 		}
741 	}
742 out:
743 	no_trap();
744 	ppmapout(kaddr);
745 
746 	return (errors ? 0 : 1);
747 }
748 
749 /*
750  * Try to clear a page_t with a single UE. If the UE was transient, it is
751  * returned to service, and we return 1. Otherwise we return 0 meaning
752  * that further processing is required to retire the page.
753  */
754 static int
755 page_retire_transient_ue(page_t *pp)
756 {
757 	ASSERT(PAGE_EXCL(pp));
758 	ASSERT(!hat_page_is_mapped(pp));
759 
760 	/*
761 	 * If this page is a repeat offender, retire him under the
762 	 * "two strikes and you're out" rule. The caller is responsible
763 	 * for scrubbing the page to try to clear the error.
764 	 */
765 	if (pp->p_toxic & PR_UE_SCRUBBED) {
766 		PR_INCR_KSTAT(pr_ue_persistent);
767 		return (0);
768 	}
769 
770 	if (page_clear_transient_ue(pp)) {
771 		/*
772 		 * We set the PR_SCRUBBED_UE bit; if we ever see this
773 		 * page again, we will retire it, no questions asked.
774 		 */
775 		page_settoxic(pp, PR_UE_SCRUBBED);
776 
777 		if (page_retire_first_ue) {
778 			PR_INCR_KSTAT(pr_ue_cleared_retire);
779 			return (0);
780 		} else {
781 			PR_INCR_KSTAT(pr_ue_cleared_free);
782 
783 			page_clrtoxic(pp, PR_UE | PR_MCE | PR_MSG | PR_BUSY);
784 			page_retire_dequeue(pp);
785 
786 			/* LINTED: CONSTCOND */
787 			VN_DISPOSE(pp, B_FREE, 1, kcred);
788 			return (1);
789 		}
790 	}
791 
792 	PR_INCR_KSTAT(pr_ue_persistent);
793 	return (0);
794 }
795 
796 /*
797  * Update the statistics dynamically when our kstat is read.
798  */
799 static int
800 page_retire_kstat_update(kstat_t *ksp, int rw)
801 {
802 	struct page_retire_kstat *pr;
803 
804 	if (ksp == NULL)
805 	    return (EINVAL);
806 
807 	switch (rw) {
808 
809 	case KSTAT_READ:
810 		pr = (struct page_retire_kstat *)ksp->ks_data;
811 		ASSERT(pr == &page_retire_kstat);
812 		pr->pr_limit.value.ui64 = PAGE_RETIRE_LIMIT;
813 		return (0);
814 
815 	case KSTAT_WRITE:
816 		return (EACCES);
817 
818 	default:
819 		return (EINVAL);
820 	}
821 	/*NOTREACHED*/
822 }
823 
824 /*
825  * Initialize the page retire mechanism:
826  *
827  *   - Establish the correctable error retire limit.
828  *   - Initialize locks.
829  *   - Build the retired_pages vnode.
830  *   - Set up the kstats.
831  *   - Fire off the background thread.
832  *   - Tell page_tryretire() it's OK to start retiring pages.
833  */
834 void
835 page_retire_init(void)
836 {
837 	const fs_operation_def_t retired_vnodeops_template[] = {NULL, NULL};
838 	struct vnodeops *vops;
839 
840 	const uint_t page_retire_ndata =
841 	    sizeof (page_retire_kstat) / sizeof (kstat_named_t);
842 
843 	ASSERT(page_retire_ksp == NULL);
844 
845 	if (max_pages_retired_bps <= 0) {
846 		max_pages_retired_bps = MCE_BPT;
847 	}
848 
849 	mutex_init(&pr_q_mutex, NULL, MUTEX_DEFAULT, NULL);
850 
851 	retired_pages = vn_alloc(KM_SLEEP);
852 	if (vn_make_ops("retired_pages", retired_vnodeops_template, &vops)) {
853 		cmn_err(CE_PANIC,
854 		    "page_retired_init: can't make retired vnodeops");
855 	}
856 	vn_setops(retired_pages, vops);
857 
858 	if ((page_retire_ksp = kstat_create("unix", 0, "page_retire",
859 	    "misc", KSTAT_TYPE_NAMED, page_retire_ndata,
860 	    KSTAT_FLAG_VIRTUAL)) == NULL) {
861 		cmn_err(CE_WARN, "kstat_create for page_retire failed");
862 	} else {
863 		page_retire_ksp->ks_data = (void *)&page_retire_kstat;
864 		page_retire_ksp->ks_update = page_retire_kstat_update;
865 		kstat_install(page_retire_ksp);
866 	}
867 
868 	pr_thread_shortwait = 23 * hz;
869 	pr_thread_longwait = 1201 * hz;
870 	mutex_init(&pr_thread_mutex, NULL, MUTEX_DEFAULT, NULL);
871 	cv_init(&pr_cv, NULL, CV_DEFAULT, NULL);
872 	pr_thread_id = thread_create(NULL, 0, page_retire_thread, NULL, 0, &p0,
873 	    TS_RUN, minclsyspri);
874 
875 	pr_enable = 1;
876 }
877 
878 /*
879  * page_retire_hunt() callback for the retire thread.
880  */
881 static void
882 page_retire_thread_cb(page_t *pp)
883 {
884 	PR_DEBUG(prd_tctop);
885 	if (!PP_ISKVP(pp) && page_trylock(pp, SE_EXCL)) {
886 		PR_DEBUG(prd_tclocked);
887 		page_unlock(pp);
888 	}
889 }
890 
891 /*
892  * page_retire_hunt() callback for mdboot().
893  *
894  * It is necessary to scrub any failing pages prior to reboot in order to
895  * prevent a latent error trap from occurring on the next boot.
896  */
897 void
898 page_retire_mdboot_cb(page_t *pp)
899 {
900 	/*
901 	 * Don't scrub the kernel, since we might still need it, unless
902 	 * we have UEs on the page, in which case we have nothing to lose.
903 	 */
904 	if (!PP_ISKVP(pp) || PP_TOXIC(pp)) {
905 		pp->p_selock = -1;	/* pacify ASSERTs */
906 		PP_CLRFREE(pp);
907 		pagescrub(pp, 0, PAGESIZE);
908 		pp->p_selock = 0;
909 	}
910 	pp->p_toxic = 0;
911 }
912 
913 /*
914  * Hunt down any pages in the system that have not yet been retired, invoking
915  * the provided callback function on each of them.
916  */
917 void
918 page_retire_hunt(void (*callback)(page_t *))
919 {
920 	page_t *pp;
921 	page_t *first;
922 	uint64_t tbr, found;
923 	int i;
924 
925 	PR_DEBUG(prd_hunt);
926 
927 	if (PR_KSTAT_PENDING == 0) {
928 		return;
929 	}
930 
931 	PR_DEBUG(prd_dohunt);
932 
933 	found = 0;
934 	mutex_enter(&pr_q_mutex);
935 
936 	tbr = PR_KSTAT_PENDING;
937 
938 	for (i = 0; i < PR_PENDING_QMAX; i++) {
939 		if ((pp = pr_pending_q[i]) != NULL) {
940 			mutex_exit(&pr_q_mutex);
941 			callback(pp);
942 			mutex_enter(&pr_q_mutex);
943 			found++;
944 		}
945 	}
946 
947 	if (PR_KSTAT_EQFAIL == PR_KSTAT_DQFAIL && found == tbr) {
948 		mutex_exit(&pr_q_mutex);
949 		PR_DEBUG(prd_earlyhunt);
950 		return;
951 	}
952 	mutex_exit(&pr_q_mutex);
953 
954 	PR_DEBUG(prd_latehunt);
955 
956 	/*
957 	 * We've lost track of a page somewhere. Hunt it down.
958 	 */
959 	memsegs_lock(0);
960 	pp = first = page_first();
961 	do {
962 		if (PP_PR_REQ(pp)) {
963 			callback(pp);
964 			if (++found == tbr) {
965 				break;	/* got 'em all */
966 			}
967 		}
968 	} while ((pp = page_next(pp)) != first);
969 	memsegs_unlock(0);
970 }
971 
972 /*
973  * The page_retire_thread loops forever, looking to see if there are
974  * pages still waiting to be retired.
975  */
976 static void
977 page_retire_thread(void)
978 {
979 	callb_cpr_t c;
980 
981 	CALLB_CPR_INIT(&c, &pr_thread_mutex, callb_generic_cpr, "page_retire");
982 
983 	mutex_enter(&pr_thread_mutex);
984 	for (;;) {
985 		if (pr_enable && PR_KSTAT_PENDING) {
986 			kmem_reap();
987 			seg_preap();
988 			page_retire_hunt(page_retire_thread_cb);
989 			CALLB_CPR_SAFE_BEGIN(&c);
990 			(void) cv_timedwait(&pr_cv, &pr_thread_mutex,
991 			    lbolt + pr_thread_shortwait);
992 			CALLB_CPR_SAFE_END(&c, &pr_thread_mutex);
993 		} else {
994 			CALLB_CPR_SAFE_BEGIN(&c);
995 			(void) cv_timedwait(&pr_cv, &pr_thread_mutex,
996 			    lbolt + pr_thread_longwait);
997 			CALLB_CPR_SAFE_END(&c, &pr_thread_mutex);
998 		}
999 	}
1000 	/*NOTREACHED*/
1001 }
1002 
1003 /*
1004  * page_retire_pp() decides what to do with a failing page.
1005  *
1006  * When we get a free page (e.g. the scrubber or in the free path) life is
1007  * nice because the page is clean and marked free -- those always retire
1008  * nicely. From there we go by order of difficulty. If the page has data,
1009  * we attempt to relocate its contents to a suitable replacement page. If
1010  * that does not succeed, we look to see if it is clean. If after all of
1011  * this we have a clean, unmapped page (which we usually do!), we retire it.
1012  * If the page is not clean, we still process it regardless on a UE; for
1013  * CEs or FMA requests, we fail leaving the page in service. The page will
1014  * eventually be tried again later. We always return with the page unlocked
1015  * since we are called from page_unlock().
1016  *
1017  * We don't call panic or do anything fancy down in here. Our boss the DE
1018  * gets paid handsomely to do his job of figuring out what to do when errors
1019  * occur. We just do what he tells us to do.
1020  */
1021 static int
1022 page_retire_pp(page_t *pp)
1023 {
1024 	int		toxic;
1025 
1026 	ASSERT(PAGE_EXCL(pp));
1027 	ASSERT(pp->p_iolock_state == 0);
1028 	ASSERT(pp->p_szc == 0);
1029 
1030 	PR_DEBUG(prd_top);
1031 	PR_TYPES(pp);
1032 
1033 	toxic = pp->p_toxic;
1034 	ASSERT(toxic & PR_REASONS);
1035 
1036 	if ((toxic & (PR_FMA | PR_MCE)) && !(toxic & PR_UE) &&
1037 	    page_retire_limit()) {
1038 		page_clrtoxic(pp, PR_FMA | PR_MCE | PR_MSG | PR_BUSY);
1039 		page_retire_dequeue(pp);
1040 		page_unlock(pp);
1041 		return (page_retire_done(pp, PRD_LIMIT));
1042 	}
1043 
1044 	if (PP_ISFREE(pp)) {
1045 		PR_DEBUG(prd_free);
1046 		if (!MTBF(recl_calls, recl_mtbf) || !page_reclaim(pp, NULL)) {
1047 			PR_DEBUG(prd_noreclaim);
1048 			PR_INCR_KSTAT(pr_failed);
1049 			page_unlock(pp);
1050 			return (page_retire_done(pp, PRD_FAILED));
1051 		}
1052 	}
1053 
1054 	if ((toxic & PR_UE) == 0 && pp->p_vnode && !PP_ISFREE(pp) &&
1055 	    !PP_ISNORELOCKERNEL(pp) && MTBF(reloc_calls, reloc_mtbf)) {
1056 		page_t *newpp;
1057 		spgcnt_t count;
1058 
1059 		/*
1060 		 * If we can relocate the page, great! newpp will go
1061 		 * on without us, and everything is fine.  Regardless
1062 		 * of whether the relocation succeeds, we are still
1063 		 * going to take `pp' around back and shoot it.
1064 		 */
1065 		newpp = NULL;
1066 		if (page_relocate(&pp, &newpp, 0, 0, &count, NULL) == 0) {
1067 			PR_DEBUG(prd_reloc);
1068 			page_unlock(newpp);
1069 			ASSERT(hat_page_getattr(pp, P_MOD) == 0);
1070 		} else {
1071 			PR_DEBUG(prd_relocfail);
1072 		}
1073 	}
1074 
1075 	if (hat_ismod(pp)) {
1076 		PR_DEBUG(prd_mod);
1077 		PR_INCR_KSTAT(pr_failed);
1078 		page_unlock(pp);
1079 		return (page_retire_done(pp, PRD_FAILED));
1080 	}
1081 
1082 	if (PP_ISKVP(pp)) {
1083 		PR_DEBUG(prd_kern);
1084 		PR_INCR_KSTAT(pr_failed_kernel);
1085 		page_unlock(pp);
1086 		return (page_retire_done(pp, PRD_FAILED));
1087 	}
1088 
1089 	if (pp->p_lckcnt || pp->p_cowcnt) {
1090 		PR_DEBUG(prd_locked);
1091 		PR_INCR_KSTAT(pr_failed);
1092 		page_unlock(pp);
1093 		return (page_retire_done(pp, PRD_FAILED));
1094 	}
1095 
1096 	(void) hat_pageunload(pp, HAT_FORCE_PGUNLOAD);
1097 	ASSERT(!PP_ISFREE(pp));
1098 	ASSERT(!hat_page_is_mapped(pp));
1099 
1100 	/*
1101 	 * If the page is modified, and was not relocated; we can't
1102 	 * retire it without dropping data on the floor. We have to
1103 	 * recheck after unloading since the dirty bit could have been
1104 	 * set since we last checked.
1105 	 */
1106 	if (hat_ismod(pp)) {
1107 		PR_DEBUG(prd_mod_late);
1108 		PR_INCR_KSTAT(pr_failed);
1109 		page_unlock(pp);
1110 		return (page_retire_done(pp, PRD_FAILED));
1111 	}
1112 
1113 	if (pp->p_vnode) {
1114 		PR_DEBUG(prd_hashout);
1115 		page_hashout(pp, NULL);
1116 	}
1117 	ASSERT(!pp->p_vnode);
1118 
1119 	/*
1120 	 * The problem page is locked, demoted, unmapped, not free,
1121 	 * hashed out, and not COW or mlocked (whew!).
1122 	 *
1123 	 * Now we select our ammunition, take it around back, and shoot it.
1124 	 */
1125 	if (toxic & PR_UE) {
1126 		if (page_retire_transient_ue(pp)) {
1127 			PR_DEBUG(prd_uescrubbed);
1128 			return (page_retire_done(pp, PRD_UE_SCRUBBED));
1129 		} else {
1130 			PR_DEBUG(prd_uenotscrubbed);
1131 			page_retire_destroy(pp);
1132 			return (page_retire_done(pp, PRD_SUCCESS));
1133 		}
1134 	} else if (toxic & PR_FMA) {
1135 		PR_DEBUG(prd_fma);
1136 		page_retire_destroy(pp);
1137 		return (page_retire_done(pp, PRD_SUCCESS));
1138 	} else if (toxic & PR_MCE) {
1139 		PR_DEBUG(prd_mce);
1140 		page_retire_destroy(pp);
1141 		return (page_retire_done(pp, PRD_SUCCESS));
1142 	}
1143 	panic("page_retire_pp: bad toxic flags %d", toxic);
1144 	/*NOTREACHED*/
1145 }
1146 
1147 /*
1148  * Try to retire a page when we stumble onto it in the page lock routines.
1149  */
1150 void
1151 page_tryretire(page_t *pp)
1152 {
1153 	ASSERT(PAGE_EXCL(pp));
1154 
1155 	if (!pr_enable) {
1156 		page_unlock(pp);
1157 		return;
1158 	}
1159 
1160 	/*
1161 	 * If the page is a big page, try to break it up.
1162 	 *
1163 	 * If there are other bad pages besides `pp', they will be
1164 	 * recursively retired for us thanks to a bit of magic.
1165 	 * If the page is a small page with errors, try to retire it.
1166 	 */
1167 	if (pp->p_szc > 0) {
1168 		if (PP_ISFREE(pp) && !page_try_demote_free_pages(pp)) {
1169 			page_unlock(pp);
1170 			PR_DEBUG(prd_nofreedemote);
1171 			return;
1172 		} else if (!page_try_demote_pages(pp)) {
1173 			page_unlock(pp);
1174 			PR_DEBUG(prd_nodemote);
1175 			return;
1176 		}
1177 		PR_DEBUG(prd_demoted);
1178 		page_unlock(pp);
1179 	} else {
1180 		(void) page_retire_pp(pp);
1181 	}
1182 }
1183 
1184 /*
1185  * page_retire() - the front door in to retire a page.
1186  *
1187  * Ideally, page_retire() would instantly retire the requested page.
1188  * Unfortunately, some pages are locked or otherwise tied up and cannot be
1189  * retired right away. To deal with that, bits are set in p_toxic of the
1190  * page_t. An attempt is made to lock the page; if the attempt is successful,
1191  * we instantly unlock the page counting on page_unlock() to notice p_toxic
1192  * is nonzero and to call back into page_retire_pp(). Success is determined
1193  * by looking to see whether the page has been retired once it has been
1194  * unlocked.
1195  *
1196  * Returns:
1197  *
1198  *   - 0 on success,
1199  *   - EINVAL when the PA is whacko,
1200  *   - EBUSY if the page is already retired, or
1201  *   - EAGAIN if the page could not be _immediately_ retired.
1202  */
1203 int
1204 page_retire(uint64_t pa, uchar_t reason)
1205 {
1206 	page_t	*pp;
1207 
1208 	ASSERT(reason & PR_REASONS);		/* there must be a reason */
1209 	ASSERT(!(reason & ~PR_REASONS));	/* but no other bits */
1210 
1211 	pp = page_numtopp_nolock(mmu_btop(pa));
1212 	if (pp == NULL) {
1213 		PR_MESSAGE(CE_WARN, 1, "Cannot schedule clearing of error on"
1214 		    " page 0x%08x.%08x; page is not relocatable memory", pa);
1215 		return (page_retire_done(pp, PRD_INVALID_PA));
1216 	}
1217 	if (PP_RETIRED(pp)) {
1218 		return (page_retire_done(pp, PRD_DUPLICATE));
1219 	}
1220 
1221 	if (reason & PR_UE) {
1222 		PR_MESSAGE(CE_NOTE, 1, "Scheduling clearing of error on"
1223 		    " page 0x%08x.%08x", pa);
1224 	} else {
1225 		PR_MESSAGE(CE_NOTE, 1, "Scheduling removal of"
1226 		    " page 0x%08x.%08x", pa);
1227 	}
1228 	page_settoxic(pp, reason);
1229 	page_retire_enqueue(pp);
1230 
1231 	/*
1232 	 * And now for some magic.
1233 	 *
1234 	 * We marked this page toxic up above.  All there is left to do is
1235 	 * to try to lock the page and then unlock it.  The page lock routines
1236 	 * will intercept the page and retire it if they can.  If the page
1237 	 * cannot be locked, 's okay -- page_unlock() will eventually get it,
1238 	 * or the background thread, until then the lock routines will deny
1239 	 * further locks on it.
1240 	 */
1241 	if (MTBF(pr_calls, pr_mtbf) && page_trylock(pp, SE_EXCL)) {
1242 		PR_DEBUG(prd_prlocked);
1243 		page_unlock(pp);
1244 	} else {
1245 		PR_DEBUG(prd_prnotlocked);
1246 	}
1247 
1248 	if (PP_RETIRED(pp)) {
1249 		PR_DEBUG(prd_prretired);
1250 		return (0);
1251 	} else {
1252 		cv_signal(&pr_cv);
1253 		PR_INCR_KSTAT(pr_failed);
1254 
1255 		if (pp->p_toxic & PR_MSG) {
1256 			return (page_retire_done(pp, PRD_FAILED));
1257 		} else {
1258 			return (page_retire_done(pp, PRD_PENDING));
1259 		}
1260 	}
1261 }
1262 
1263 /*
1264  * Take a retired page off the retired-pages vnode and clear the toxic flags.
1265  * If "free" is nonzero, lock it and put it back on the freelist. If "free"
1266  * is zero, the caller already holds SE_EXCL lock so we simply unretire it
1267  * and don't do anything else with it.
1268  *
1269  * Any unretire messages are printed from this routine.
1270  *
1271  * Returns 0 if page pp was unretired; else an error code.
1272  */
1273 int
1274 page_unretire_pp(page_t *pp, int free)
1275 {
1276 	/*
1277 	 * To be retired, a page has to be hashed onto the retired_pages vnode
1278 	 * and have PR_RETIRED set in p_toxic.
1279 	 */
1280 	if (free == 0 || page_try_reclaim_lock(pp, SE_EXCL, SE_RETIRED)) {
1281 		ASSERT(PAGE_EXCL(pp));
1282 		PR_DEBUG(prd_ulocked);
1283 		if (!PP_RETIRED(pp)) {
1284 			PR_DEBUG(prd_unotretired);
1285 			page_unlock(pp);
1286 			return (page_retire_done(pp, PRD_UNR_NOT));
1287 		}
1288 
1289 		PR_MESSAGE(CE_NOTE, 1, "unretiring retired"
1290 		    " page 0x%08x.%08x", mmu_ptob(pp->p_pagenum));
1291 		if (pp->p_toxic & PR_FMA) {
1292 			PR_DECR_KSTAT(pr_fma);
1293 		} else if (pp->p_toxic & PR_UE) {
1294 			PR_DECR_KSTAT(pr_ue);
1295 		} else {
1296 			PR_DECR_KSTAT(pr_mce);
1297 		}
1298 		page_clrtoxic(pp, PR_ALLFLAGS);
1299 
1300 		if (free) {
1301 			PR_DEBUG(prd_udestroy);
1302 			page_destroy(pp, 0);
1303 		} else {
1304 			PR_DEBUG(prd_uhashout);
1305 			page_hashout(pp, NULL);
1306 		}
1307 
1308 		mutex_enter(&freemem_lock);
1309 		availrmem++;
1310 		mutex_exit(&freemem_lock);
1311 
1312 		PR_DEBUG(prd_uunretired);
1313 		PR_DECR_KSTAT(pr_retired);
1314 		PR_INCR_KSTAT(pr_unretired);
1315 		return (page_retire_done(pp, PRD_UNR_SUCCESS));
1316 	}
1317 	PR_DEBUG(prd_unotlocked);
1318 	return (page_retire_done(pp, PRD_UNR_CANTLOCK));
1319 }
1320 
1321 /*
1322  * Return a page to service by moving it from the retired_pages vnode
1323  * onto the freelist.
1324  *
1325  * Called from mmioctl_page_retire() on behalf of the FMA DE.
1326  *
1327  * Returns:
1328  *
1329  *   - 0 if the page is unretired,
1330  *   - EAGAIN if the pp can not be locked,
1331  *   - EINVAL if the PA is whacko, and
1332  *   - EBADF if the pp is not retired.
1333  */
1334 int
1335 page_unretire(uint64_t pa)
1336 {
1337 	page_t	*pp;
1338 
1339 	pp = page_numtopp_nolock(mmu_btop(pa));
1340 	if (pp == NULL) {
1341 		return (page_retire_done(pp, PRD_INVALID_PA));
1342 	}
1343 
1344 	return (page_unretire_pp(pp, 1));
1345 }
1346 
1347 /*
1348  * Test a page to see if it is retired. If errors is non-NULL, the toxic
1349  * bits of the page are returned. Returns 0 on success, error code on failure.
1350  */
1351 int
1352 page_retire_check_pp(page_t *pp, uint64_t *errors)
1353 {
1354 	int rc;
1355 
1356 	if (PP_RETIRED(pp)) {
1357 		PR_DEBUG(prd_checkhit);
1358 		rc = 0;
1359 	} else {
1360 		PR_DEBUG(prd_checkmiss);
1361 		rc = EAGAIN;
1362 	}
1363 
1364 	/*
1365 	 * We have magically arranged the bit values returned to fmd(1M)
1366 	 * to line up with the FMA, MCE, and UE bits of the page_t.
1367 	 */
1368 	if (errors) {
1369 		uint64_t toxic = (uint64_t)(pp->p_toxic & PR_ERRMASK);
1370 		if (toxic & PR_UE_SCRUBBED) {
1371 			toxic &= ~PR_UE_SCRUBBED;
1372 			toxic |= PR_UE;
1373 		}
1374 		*errors = toxic;
1375 	}
1376 
1377 	return (rc);
1378 }
1379 
1380 /*
1381  * Test to see if the page_t for a given PA is retired, and return the
1382  * hardware errors we have seen on the page if requested.
1383  *
1384  * Called from mmioctl_page_retire on behalf of the FMA DE.
1385  *
1386  * Returns:
1387  *
1388  *   - 0 if the page is retired,
1389  *   - EAGAIN if it is not, and
1390  *   - EINVAL if the PA is whacko.
1391  */
1392 int
1393 page_retire_check(uint64_t pa, uint64_t *errors)
1394 {
1395 	page_t	*pp;
1396 
1397 	if (errors) {
1398 		*errors = 0;
1399 	}
1400 
1401 	pp = page_numtopp_nolock(mmu_btop(pa));
1402 	if (pp == NULL) {
1403 		return (page_retire_done(pp, PRD_INVALID_PA));
1404 	}
1405 
1406 	return (page_retire_check_pp(pp, errors));
1407 }
1408 
1409 /*
1410  * Page retire self-test. For now, it always returns 0.
1411  */
1412 int
1413 page_retire_test(void)
1414 {
1415 	page_t *first, *pp, *cpp, *cpp2, *lpp;
1416 
1417 	/*
1418 	 * Tests the corner case where a large page can't be retired
1419 	 * because one of the constituent pages is locked. We mark
1420 	 * one page to be retired and try to retire it, and mark the
1421 	 * other page to be retired but don't try to retire it, so
1422 	 * that page_unlock() in the failure path will recurse and try
1423 	 * to retire THAT page. This is the worst possible situation
1424 	 * we can get ourselves into.
1425 	 */
1426 	memsegs_lock(0);
1427 	pp = first = page_first();
1428 	do {
1429 		if (pp->p_szc && PP_PAGEROOT(pp) == pp) {
1430 			cpp = pp + 1;
1431 			lpp = PP_ISFREE(pp)? pp : pp + 2;
1432 			cpp2 = pp + 3;
1433 			if (!page_trylock(lpp, pp == lpp? SE_EXCL : SE_SHARED))
1434 				continue;
1435 			if (!page_trylock(cpp, SE_EXCL)) {
1436 				page_unlock(lpp);
1437 				continue;
1438 			}
1439 			page_settoxic(cpp, PR_FMA | PR_BUSY);
1440 			page_settoxic(cpp2, PR_FMA);
1441 			page_tryretire(cpp);	/* will fail */
1442 			page_unlock(lpp);
1443 			(void) page_retire(cpp->p_pagenum, PR_FMA);
1444 			(void) page_retire(cpp2->p_pagenum, PR_FMA);
1445 		}
1446 	} while ((pp = page_next(pp)) != first);
1447 	memsegs_unlock(0);
1448 
1449 	return (0);
1450 }
1451