xref: /titanic_52/usr/src/uts/common/vm/page_retire.c (revision d58fda4376e4bf67072ce2e69f6f47036f9dbb68)
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 retire dirty UE pages. By default we do
269  * since we assume the data is corrupt and the process(es) using it will
270  * be killed. This is platform tunable only, and should probably not be
271  * changed, ever.
272  */
273 int page_retire_modified = 1;
274 
275 /*
276  * Control whether or not we return scrubbed UE pages to service.
277  * By default we do not since FMA wants to run its diagnostics first
278  * and then ask us to unretire the page if it passes. Non-FMA platforms
279  * may set this to zero so we will only retire recidivist pages. It should
280  * not be changed by the user.
281  */
282 int page_retire_first_ue = 1;
283 
284 /*
285  * Master enable for page retire. This prevents a CE or UE early in boot
286  * from trying to retire a page before page_retire_init() has finished
287  * setting things up. This is internal only and is not a tunable!
288  */
289 static int pr_enable = 0;
290 
291 extern struct vnode kvp;
292 
293 #ifdef	DEBUG
294 struct page_retire_debug {
295 	int prd_dup;
296 	int prd_noaction;
297 	int prd_queued;
298 	int prd_notqueued;
299 	int prd_dequeue;
300 	int prd_top;
301 	int prd_locked;
302 	int prd_reloc;
303 	int prd_modce;
304 	int prd_modue_fail;
305 	int prd_modue_retire;
306 	int prd_kern;
307 	int prd_free;
308 	int prd_noreclaim;
309 	int prd_hashout;
310 	int prd_fma;
311 	int prd_uescrubbed;
312 	int prd_uenotscrubbed;
313 	int prd_mce;
314 	int prd_prlocked;
315 	int prd_prnotlocked;
316 	int prd_prretired;
317 	int prd_ulocked;
318 	int prd_unotretired;
319 	int prd_udestroy;
320 	int prd_uhashout;
321 	int prd_uunretired;
322 	int prd_unotlocked;
323 	int prd_checkhit;
324 	int prd_checkmiss;
325 	int prd_tctop;
326 	int prd_tclocked;
327 	int prd_hunt;
328 	int prd_dohunt;
329 	int prd_earlyhunt;
330 	int prd_latehunt;
331 	int prd_nofreedemote;
332 	int prd_nodemote;
333 	int prd_demoted;
334 } pr_debug;
335 
336 #define	PR_DEBUG(foo)	((pr_debug.foo)++)
337 
338 /*
339  * A type histogram. We record the incidence of the various toxic
340  * flag combinations along with the interesting page attributes. The
341  * goal is to get as many combinations as we can while driving all
342  * pr_debug values nonzero (indicating we've exercised all possible
343  * code paths across all possible page types). Not all combinations
344  * will make sense -- e.g. PRT_MOD|PRT_KERNEL.
345  *
346  * pr_type offset bit encoding (when examining with a debugger):
347  *
348  *    PRT_NAMED  - 0x4
349  *    PRT_KERNEL - 0x8
350  *    PRT_FREE   - 0x10
351  *    PRT_MOD    - 0x20
352  *    PRT_FMA    - 0x0
353  *    PRT_MCE    - 0x40
354  *    PRT_UE     - 0x80
355  */
356 
357 #define	PRT_NAMED	0x01
358 #define	PRT_KERNEL	0x02
359 #define	PRT_FREE	0x04
360 #define	PRT_MOD		0x08
361 #define	PRT_FMA		0x00	/* yes, this is not a mistake */
362 #define	PRT_MCE		0x10
363 #define	PRT_UE		0x20
364 #define	PRT_ALL		0x3F
365 
366 int pr_types[PRT_ALL+1];
367 
368 #define	PR_TYPES(pp)	{			\
369 	int whichtype = 0;			\
370 	if (pp->p_vnode)			\
371 		whichtype |= PRT_NAMED;		\
372 	if (pp->p_vnode == &kvp)		\
373 		whichtype |= PRT_KERNEL;	\
374 	if (PP_ISFREE(pp))			\
375 		whichtype |= PRT_FREE;		\
376 	if (hat_ismod(pp))			\
377 		whichtype |= PRT_MOD;		\
378 	if (pp->p_toxic & PR_UE)		\
379 		whichtype |= PRT_UE;		\
380 	if (pp->p_toxic & PR_MCE)		\
381 		whichtype |= PRT_MCE;		\
382 	pr_types[whichtype]++;			\
383 }
384 
385 int recl_calls;
386 int recl_mtbf = 3;
387 int reloc_calls;
388 int reloc_mtbf = 7;
389 int pr_calls;
390 int pr_mtbf = 15;
391 
392 #define	MTBF(v, f)	(((++(v)) & (f)) != (f))
393 
394 #else	/* DEBUG */
395 
396 #define	PR_DEBUG(foo)	/* nothing */
397 #define	PR_TYPES(foo)	/* nothing */
398 #define	MTBF(v, f)	(1)
399 
400 #endif	/* DEBUG */
401 
402 /*
403  * page_retire_done() - completion processing
404  *
405  * Used by the page_retire code for common completion processing.
406  * It keeps track of how many times a given result has happened,
407  * and writes out an occasional message.
408  *
409  * May be called with a NULL pp (PRD_INVALID_PA case).
410  */
411 #define	PRD_INVALID_KEY		-1
412 #define	PRD_SUCCESS		0
413 #define	PRD_PENDING		1
414 #define	PRD_FAILED		2
415 #define	PRD_DUPLICATE		3
416 #define	PRD_INVALID_PA		4
417 #define	PRD_LIMIT		5
418 #define	PRD_UE_SCRUBBED		6
419 #define	PRD_UNR_SUCCESS		7
420 #define	PRD_UNR_CANTLOCK	8
421 #define	PRD_UNR_NOT		9
422 
423 typedef struct page_retire_op {
424 	int	pr_key;		/* one of the PRD_* defines from above */
425 	int	pr_count;	/* How many times this has happened */
426 	int	pr_retval;	/* return value */
427 	int	pr_msglvl;	/* message level - when to print */
428 	char	*pr_message;	/* Cryptic message for field service */
429 } page_retire_op_t;
430 
431 static page_retire_op_t page_retire_ops[] = {
432 	/* key			count	retval	msglvl	message */
433 	{PRD_SUCCESS,		0,	0,	1,
434 		"Page 0x%08x.%08x removed from service"},
435 	{PRD_PENDING,		0,	EAGAIN,	2,
436 		"Page 0x%08x.%08x will be retired on free"},
437 	{PRD_FAILED,		0,	EAGAIN,	0, NULL},
438 	{PRD_DUPLICATE,		0,	EBUSY,	2,
439 		"Page 0x%08x.%08x already retired"},
440 	{PRD_INVALID_PA,	0,	EINVAL, 2,
441 		"PA 0x%08x.%08x is not a relocatable page"},
442 	{PRD_LIMIT,		0,	0,	1,
443 		"Page 0x%08x.%08x not retired due to limit exceeded"},
444 	{PRD_UE_SCRUBBED,	0,	0,	1,
445 		"Previously reported error on page 0x%08x.%08x cleared"},
446 	{PRD_UNR_SUCCESS,	0,	0,	1,
447 		"Page 0x%08x.%08x returned to service"},
448 	{PRD_UNR_CANTLOCK,	0,	EAGAIN,	2,
449 		"Page 0x%08x.%08x could not be unretired"},
450 	{PRD_UNR_NOT,		0,	EBADF,	2,
451 		"Page 0x%08x.%08x is not retired"},
452 	{PRD_INVALID_KEY,	0,	0,	0, NULL} /* MUST BE LAST! */
453 };
454 
455 /*
456  * print a message if page_retire_messages is true.
457  */
458 #define	PR_MESSAGE(debuglvl, msglvl, msg, pa)				\
459 {									\
460 	uint64_t p = (uint64_t)pa;					\
461 	if (page_retire_messages >= msglvl && msg != NULL) {		\
462 		cmn_err(debuglvl, msg,					\
463 		    (uint32_t)(p >> 32), (uint32_t)p);			\
464 	}								\
465 }
466 
467 /*
468  * Note that multiple bits may be set in a single settoxic operation.
469  * May be called without the page locked.
470  */
471 void
472 page_settoxic(page_t *pp, uchar_t bits)
473 {
474 	atomic_or_8(&pp->p_toxic, bits);
475 }
476 
477 /*
478  * Note that multiple bits may cleared in a single clrtoxic operation.
479  * Must be called with the page exclusively locked.
480  */
481 void
482 page_clrtoxic(page_t *pp, uchar_t bits)
483 {
484 	ASSERT(PAGE_EXCL(pp));
485 	atomic_and_8(&pp->p_toxic, ~bits);
486 }
487 
488 /*
489  * Prints any page retire messages to the user, and decides what
490  * error code is appropriate for the condition reported.
491  */
492 static int
493 page_retire_done(page_t *pp, int code)
494 {
495 	page_retire_op_t *prop;
496 	uint64_t	pa = 0;
497 	int		i;
498 
499 	if (pp != NULL) {
500 		pa = mmu_ptob(pp->p_pagenum);
501 	}
502 
503 	prop = NULL;
504 	for (i = 0; page_retire_ops[i].pr_key != PRD_INVALID_KEY; i++) {
505 		if (page_retire_ops[i].pr_key == code) {
506 			prop = &page_retire_ops[i];
507 			break;
508 		}
509 	}
510 
511 #ifdef	DEBUG
512 	if (page_retire_ops[i].pr_key == PRD_INVALID_KEY) {
513 		cmn_err(CE_PANIC, "page_retire_done: Invalid opcode %d", code);
514 	}
515 #endif
516 
517 	ASSERT(prop->pr_key == code);
518 
519 	prop->pr_count++;
520 
521 	PR_MESSAGE(CE_NOTE, prop->pr_msglvl, prop->pr_message, pa);
522 	if (pp != NULL) {
523 		page_settoxic(pp, PR_MSG);
524 	}
525 
526 	return (prop->pr_retval);
527 }
528 
529 /*
530  * On a reboot, our friend mdboot() wants to clear up any PP_PR_REQ() pages
531  * that we were not able to retire. On large machines, walking the complete
532  * page_t array and looking at every page_t takes too long. So, as a page is
533  * marked toxic, we track it using a list that can be processed at reboot
534  * time.  page_retire_enqueue() will do its best to try to avoid duplicate
535  * entries, but if we get too many errors at once the queue can overflow,
536  * in which case we will end up walking every page_t as a last resort.
537  * The background thread also makes use of this queue to find which pages
538  * are pending retirement.
539  */
540 static void
541 page_retire_enqueue(page_t *pp)
542 {
543 	int	nslot = -1;
544 	int	i;
545 
546 	mutex_enter(&pr_q_mutex);
547 
548 	/*
549 	 * Check to make sure retire hasn't already dequeued it.
550 	 * In the meantime if the page was cleaned up, no need
551 	 * to enqueue it.
552 	 */
553 	if (PP_RETIRED(pp) || pp->p_toxic == 0) {
554 		mutex_exit(&pr_q_mutex);
555 		PR_DEBUG(prd_noaction);
556 		return;
557 	}
558 
559 	for (i = 0; i < PR_PENDING_QMAX; i++) {
560 		if (pr_pending_q[i] == pp) {
561 			mutex_exit(&pr_q_mutex);
562 			PR_DEBUG(prd_dup);
563 			return;
564 		} else if (nslot == -1 && pr_pending_q[i] == NULL) {
565 			nslot = i;
566 		}
567 	}
568 
569 	PR_INCR_KSTAT(pr_pending);
570 
571 	if (nslot != -1) {
572 		pr_pending_q[nslot] = pp;
573 		PR_DEBUG(prd_queued);
574 	} else {
575 		PR_INCR_KSTAT(pr_enqueue_fail);
576 		PR_DEBUG(prd_notqueued);
577 	}
578 	mutex_exit(&pr_q_mutex);
579 }
580 
581 static void
582 page_retire_dequeue(page_t *pp)
583 {
584 	int i;
585 
586 	mutex_enter(&pr_q_mutex);
587 
588 	for (i = 0; i < PR_PENDING_QMAX; i++) {
589 		if (pr_pending_q[i] == pp) {
590 			pr_pending_q[i] = NULL;
591 			break;
592 		}
593 	}
594 
595 	if (i == PR_PENDING_QMAX) {
596 		PR_INCR_KSTAT(pr_dequeue_fail);
597 	}
598 
599 	PR_DECR_KSTAT(pr_pending);
600 	PR_DEBUG(prd_dequeue);
601 
602 	mutex_exit(&pr_q_mutex);
603 }
604 
605 /*
606  * Act like page_destroy(), but instead of freeing the page, hash it onto
607  * the retired_pages vnode, and mark it retired.
608  *
609  * For fun, we try to scrub the page until it's squeaky clean.
610  * availrmem is adjusted here.
611  */
612 static void
613 page_retire_destroy(page_t *pp)
614 {
615 	ASSERT(PAGE_EXCL(pp));
616 	ASSERT(!PP_ISFREE(pp));
617 	ASSERT(pp->p_szc == 0);
618 	ASSERT(!hat_page_is_mapped(pp));
619 	ASSERT(!pp->p_vnode);
620 
621 	page_clr_all_props(pp);
622 	pagescrub(pp, 0, MMU_PAGESIZE);
623 
624 	pp->p_next = NULL;
625 	pp->p_prev = NULL;
626 	if (page_hashin(pp, retired_pages, (u_offset_t)pp, NULL) == 0) {
627 		cmn_err(CE_PANIC, "retired page %p hashin failed", (void *)pp);
628 	}
629 
630 	page_settoxic(pp, PR_RETIRED);
631 	page_clrtoxic(pp, PR_BUSY);
632 	page_retire_dequeue(pp);
633 	PR_INCR_KSTAT(pr_retired);
634 
635 	if (pp->p_toxic & PR_FMA) {
636 		PR_INCR_KSTAT(pr_fma);
637 	} else if (pp->p_toxic & PR_UE) {
638 		PR_INCR_KSTAT(pr_ue);
639 	} else {
640 		PR_INCR_KSTAT(pr_mce);
641 	}
642 
643 	mutex_enter(&freemem_lock);
644 	availrmem--;
645 	mutex_exit(&freemem_lock);
646 
647 	page_unlock(pp);
648 }
649 
650 /*
651  * Check whether the number of pages which have been retired already exceeds
652  * the maximum allowable percentage of memory which may be retired.
653  *
654  * Returns 1 if the limit has been exceeded.
655  */
656 static int
657 page_retire_limit(void)
658 {
659 	if (PR_KSTAT_RETIRED_NOTUE >= (uint64_t)PAGE_RETIRE_LIMIT) {
660 		PR_INCR_KSTAT(pr_limit_exceeded);
661 		return (1);
662 	}
663 
664 	return (0);
665 }
666 
667 #define	MSG_DM	"Data Mismatch occurred at PA 0x%08x.%08x"		\
668 	"[ 0x%x != 0x%x ] while attempting to clear previously "	\
669 	"reported error; page removed from service"
670 
671 #define	MSG_UE	"Uncorrectable Error occurred at PA 0x%08x.%08x while "	\
672 	"attempting to clear previously reported error; page removed "	\
673 	"from service"
674 
675 /*
676  * Attempt to clear a UE from a page.
677  * Returns 1 if the error has been successfully cleared.
678  */
679 static int
680 page_clear_transient_ue(page_t *pp)
681 {
682 	caddr_t		kaddr;
683 	uint8_t		rb, wb;
684 	uint64_t	pa;
685 	uint32_t	pa_hi, pa_lo;
686 	on_trap_data_t	otd;
687 	int		errors = 0;
688 	int		i;
689 
690 	ASSERT(PAGE_EXCL(pp));
691 	ASSERT(PP_PR_REQ(pp));
692 	ASSERT(pp->p_szc == 0);
693 	ASSERT(!hat_page_is_mapped(pp));
694 
695 	/*
696 	 * Clear the page and attempt to clear the UE.  If we trap
697 	 * on the next access to the page, we know the UE has recurred.
698 	 */
699 	pagescrub(pp, 0, PAGESIZE);
700 
701 	/*
702 	 * Map the page and write a bunch of bit patterns to compare
703 	 * what we wrote with what we read back.  This isn't a perfect
704 	 * test but it should be good enough to catch most of the
705 	 * recurring UEs. If this fails to catch a recurrent UE, we'll
706 	 * retire the page the next time we see a UE on the page.
707 	 */
708 	kaddr = ppmapin(pp, PROT_READ|PROT_WRITE, (caddr_t)-1);
709 
710 	pa = ptob((uint64_t)page_pptonum(pp));
711 	pa_hi = (uint32_t)(pa >> 32);
712 	pa_lo = (uint32_t)pa;
713 
714 	/*
715 	 * Fill the page with each (0x00 - 0xFF] bit pattern, flushing
716 	 * the cache in between reading and writing.  We do this under
717 	 * on_trap() protection to avoid recursion.
718 	 */
719 	if (on_trap(&otd, OT_DATA_EC)) {
720 		PR_MESSAGE(CE_WARN, 1, MSG_UE, pa);
721 		errors = 1;
722 	} else {
723 		for (wb = 0xff; wb > 0; wb--) {
724 			for (i = 0; i < PAGESIZE; i++) {
725 				kaddr[i] = wb;
726 			}
727 
728 			sync_data_memory(kaddr, PAGESIZE);
729 
730 			for (i = 0; i < PAGESIZE; i++) {
731 				rb = kaddr[i];
732 				if (rb != wb) {
733 					/*
734 					 * We had a mismatch without a trap.
735 					 * Uh-oh. Something is really wrong
736 					 * with this system.
737 					 */
738 					if (page_retire_messages) {
739 						cmn_err(CE_WARN, MSG_DM,
740 						    pa_hi, pa_lo, rb, wb);
741 					}
742 					errors = 1;
743 					goto out;	/* double break */
744 				}
745 			}
746 		}
747 	}
748 out:
749 	no_trap();
750 	ppmapout(kaddr);
751 
752 	return (errors ? 0 : 1);
753 }
754 
755 /*
756  * Try to clear a page_t with a single UE. If the UE was transient, it is
757  * returned to service, and we return 1. Otherwise we return 0 meaning
758  * that further processing is required to retire the page.
759  */
760 static int
761 page_retire_transient_ue(page_t *pp)
762 {
763 	ASSERT(PAGE_EXCL(pp));
764 	ASSERT(!hat_page_is_mapped(pp));
765 
766 	/*
767 	 * If this page is a repeat offender, retire him under the
768 	 * "two strikes and you're out" rule. The caller is responsible
769 	 * for scrubbing the page to try to clear the error.
770 	 */
771 	if (pp->p_toxic & PR_UE_SCRUBBED) {
772 		PR_INCR_KSTAT(pr_ue_persistent);
773 		return (0);
774 	}
775 
776 	if (page_clear_transient_ue(pp)) {
777 		/*
778 		 * We set the PR_SCRUBBED_UE bit; if we ever see this
779 		 * page again, we will retire it, no questions asked.
780 		 */
781 		page_settoxic(pp, PR_UE_SCRUBBED);
782 
783 		if (page_retire_first_ue) {
784 			PR_INCR_KSTAT(pr_ue_cleared_retire);
785 			return (0);
786 		} else {
787 			PR_INCR_KSTAT(pr_ue_cleared_free);
788 
789 			page_clrtoxic(pp, PR_UE | PR_MCE | PR_MSG | PR_BUSY);
790 			page_retire_dequeue(pp);
791 
792 			/*
793 			 * Clear the free bit if it's set, since the
794 			 * page free code will get cranky if we don't.
795 			 */
796 			PP_CLRFREE(pp);
797 
798 			/* LINTED: CONSTCOND */
799 			VN_DISPOSE(pp, B_FREE, 1, kcred);
800 			return (1);
801 		}
802 	}
803 
804 	PR_INCR_KSTAT(pr_ue_persistent);
805 	return (0);
806 }
807 
808 /*
809  * Update the statistics dynamically when our kstat is read.
810  */
811 static int
812 page_retire_kstat_update(kstat_t *ksp, int rw)
813 {
814 	struct page_retire_kstat *pr;
815 
816 	if (ksp == NULL)
817 	    return (EINVAL);
818 
819 	switch (rw) {
820 
821 	case KSTAT_READ:
822 		pr = (struct page_retire_kstat *)ksp->ks_data;
823 		ASSERT(pr == &page_retire_kstat);
824 		pr->pr_limit.value.ui64 = PAGE_RETIRE_LIMIT;
825 		return (0);
826 
827 	case KSTAT_WRITE:
828 		return (EACCES);
829 
830 	default:
831 		return (EINVAL);
832 	}
833 	/*NOTREACHED*/
834 }
835 
836 /*
837  * Initialize the page retire mechanism:
838  *
839  *   - Establish the correctable error retire limit.
840  *   - Initialize locks.
841  *   - Build the retired_pages vnode.
842  *   - Set up the kstats.
843  *   - Fire off the background thread.
844  *   - Tell page_tryretire() it's OK to start retiring pages.
845  */
846 void
847 page_retire_init(void)
848 {
849 	const fs_operation_def_t retired_vnodeops_template[] = {NULL, NULL};
850 	struct vnodeops *vops;
851 
852 	const uint_t page_retire_ndata =
853 	    sizeof (page_retire_kstat) / sizeof (kstat_named_t);
854 
855 	ASSERT(page_retire_ksp == NULL);
856 
857 	if (max_pages_retired_bps <= 0) {
858 		max_pages_retired_bps = MCE_BPT;
859 	}
860 
861 	mutex_init(&pr_q_mutex, NULL, MUTEX_DEFAULT, NULL);
862 
863 	retired_pages = vn_alloc(KM_SLEEP);
864 	if (vn_make_ops("retired_pages", retired_vnodeops_template, &vops)) {
865 		cmn_err(CE_PANIC,
866 		    "page_retired_init: can't make retired vnodeops");
867 	}
868 	vn_setops(retired_pages, vops);
869 
870 	if ((page_retire_ksp = kstat_create("unix", 0, "page_retire",
871 	    "misc", KSTAT_TYPE_NAMED, page_retire_ndata,
872 	    KSTAT_FLAG_VIRTUAL)) == NULL) {
873 		cmn_err(CE_WARN, "kstat_create for page_retire failed");
874 	} else {
875 		page_retire_ksp->ks_data = (void *)&page_retire_kstat;
876 		page_retire_ksp->ks_update = page_retire_kstat_update;
877 		kstat_install(page_retire_ksp);
878 	}
879 
880 	pr_thread_shortwait = 23 * hz;
881 	pr_thread_longwait = 1201 * hz;
882 	mutex_init(&pr_thread_mutex, NULL, MUTEX_DEFAULT, NULL);
883 	cv_init(&pr_cv, NULL, CV_DEFAULT, NULL);
884 	pr_thread_id = thread_create(NULL, 0, page_retire_thread, NULL, 0, &p0,
885 	    TS_RUN, minclsyspri);
886 
887 	pr_enable = 1;
888 }
889 
890 /*
891  * page_retire_hunt() callback for the retire thread.
892  */
893 static void
894 page_retire_thread_cb(page_t *pp)
895 {
896 	PR_DEBUG(prd_tctop);
897 	if (pp->p_vnode != &kvp && page_trylock(pp, SE_EXCL)) {
898 		PR_DEBUG(prd_tclocked);
899 		page_unlock(pp);
900 	}
901 }
902 
903 /*
904  * page_retire_hunt() callback for mdboot().
905  *
906  * It is necessary to scrub any failing pages prior to reboot in order to
907  * prevent a latent error trap from occurring on the next boot.
908  */
909 void
910 page_retire_mdboot_cb(page_t *pp)
911 {
912 	/*
913 	 * Don't scrub the kernel, since we might still need it, unless
914 	 * we have UEs on the page, in which case we have nothing to lose.
915 	 */
916 	if (pp->p_vnode != &kvp || PP_TOXIC(pp)) {
917 		pp->p_selock = -1;	/* pacify ASSERTs */
918 		pagescrub(pp, 0, PAGESIZE);
919 		pp->p_selock = 0;
920 	}
921 	pp->p_toxic = 0;
922 }
923 
924 /*
925  * Hunt down any pages in the system that have not yet been retired, invoking
926  * the provided callback function on each of them.
927  */
928 void
929 page_retire_hunt(void (*callback)(page_t *))
930 {
931 	page_t *pp;
932 	page_t *first;
933 	int i, found;
934 
935 	PR_DEBUG(prd_hunt);
936 
937 	if (PR_KSTAT_PENDING == 0) {
938 		return;
939 	}
940 
941 	PR_DEBUG(prd_dohunt);
942 
943 	found = 0;
944 	mutex_enter(&pr_q_mutex);
945 
946 	for (i = 0; i < PR_PENDING_QMAX; i++) {
947 		if ((pp = pr_pending_q[i]) != NULL) {
948 			mutex_exit(&pr_q_mutex);
949 			callback(pp);
950 			mutex_enter(&pr_q_mutex);
951 			found++;
952 		}
953 	}
954 
955 	if (PR_KSTAT_EQFAIL == PR_KSTAT_DQFAIL && found == PR_KSTAT_PENDING) {
956 		mutex_exit(&pr_q_mutex);
957 		PR_DEBUG(prd_earlyhunt);
958 		return;
959 	}
960 	mutex_exit(&pr_q_mutex);
961 
962 	PR_DEBUG(prd_latehunt);
963 
964 	/*
965 	 * We've lost track of a page somewhere. Hunt it down.
966 	 */
967 	memsegs_lock(0);
968 	pp = first = page_first();
969 	do {
970 		if (PP_PR_REQ(pp)) {
971 			callback(pp);
972 			if (++found == PR_KSTAT_PENDING) {
973 				break;	/* got 'em all */
974 			}
975 		}
976 	} while ((pp = page_next(pp)) != first);
977 	memsegs_unlock(0);
978 }
979 
980 /*
981  * The page_retire_thread loops forever, looking to see if there are
982  * pages still waiting to be retired.
983  */
984 static void
985 page_retire_thread(void)
986 {
987 	callb_cpr_t c;
988 
989 	CALLB_CPR_INIT(&c, &pr_thread_mutex, callb_generic_cpr, "page_retire");
990 
991 	mutex_enter(&pr_thread_mutex);
992 	for (;;) {
993 		if (pr_enable && PR_KSTAT_PENDING) {
994 			kmem_reap();
995 			seg_preap();
996 			page_retire_hunt(page_retire_thread_cb);
997 			CALLB_CPR_SAFE_BEGIN(&c);
998 			(void) cv_timedwait(&pr_cv, &pr_thread_mutex,
999 			    lbolt + pr_thread_shortwait);
1000 			CALLB_CPR_SAFE_END(&c, &pr_thread_mutex);
1001 		} else {
1002 			CALLB_CPR_SAFE_BEGIN(&c);
1003 			(void) cv_timedwait(&pr_cv, &pr_thread_mutex,
1004 			    lbolt + pr_thread_longwait);
1005 			CALLB_CPR_SAFE_END(&c, &pr_thread_mutex);
1006 		}
1007 	}
1008 	/*NOTREACHED*/
1009 }
1010 
1011 /*
1012  * page_retire_pp() decides what to do with a failing page.
1013  *
1014  * When we get a free page (e.g. the scrubber or in the free path) life is
1015  * nice because the page is clean and marked free -- those always retire
1016  * nicely. From there we go by order of difficulty. If the page has data,
1017  * we attempt to relocate its contents to a suitable replacement page. If
1018  * that does not succeed, we look to see if it is clean. If after all of
1019  * this we have a clean, unmapped page (which we usually do!), we retire it.
1020  * If the page is not clean, we still process it regardless on a UE; for
1021  * CEs or FMA requests, we fail leaving the page in service. The page will
1022  * eventually be tried again later. We always return with the page unlocked
1023  * since we are called from page_unlock().
1024  *
1025  * We don't call panic or do anything fancy down in here. Our boss the DE
1026  * gets paid handsomely to do his job of figuring out what to do when errors
1027  * occur. We just do what he tells us to do.
1028  */
1029 static int
1030 page_retire_pp(page_t *pp)
1031 {
1032 	int		toxic;
1033 
1034 	ASSERT(PAGE_EXCL(pp));
1035 	ASSERT(pp->p_iolock_state == 0);
1036 	ASSERT(pp->p_szc == 0);
1037 
1038 	PR_DEBUG(prd_top);
1039 	PR_TYPES(pp);
1040 
1041 	toxic = pp->p_toxic;
1042 	ASSERT(toxic & PR_REASONS);
1043 
1044 	if ((toxic & (PR_FMA | PR_MCE)) && !(toxic & PR_UE) &&
1045 	    page_retire_limit()) {
1046 		page_clrtoxic(pp, PR_FMA | PR_MCE | PR_MSG | PR_BUSY);
1047 		page_retire_dequeue(pp);
1048 		page_unlock(pp);
1049 		return (page_retire_done(pp, PRD_LIMIT));
1050 	}
1051 
1052 	if (PP_ISFREE(pp)) {
1053 		PR_DEBUG(prd_free);
1054 		if (!MTBF(recl_calls, recl_mtbf) || !page_reclaim(pp, NULL)) {
1055 			PR_DEBUG(prd_noreclaim);
1056 			PR_INCR_KSTAT(pr_failed);
1057 			page_unlock(pp);
1058 			return (page_retire_done(pp, PRD_FAILED));
1059 		}
1060 	}
1061 
1062 	if ((toxic & PR_UE) == 0 && pp->p_vnode && !PP_ISFREE(pp) &&
1063 	    !PP_ISNORELOC(pp) && MTBF(reloc_calls, reloc_mtbf)) {
1064 		page_t *newpp;
1065 		spgcnt_t count;
1066 
1067 		/*
1068 		 * If we can relocate the page, great! newpp will go
1069 		 * on without us, and everything is fine.  Regardless
1070 		 * of whether the relocation succeeds, we are still
1071 		 * going to take `pp' around back and shoot it.
1072 		 */
1073 		PR_DEBUG(prd_reloc);
1074 		newpp = NULL;
1075 		if (page_relocate(&pp, &newpp, 0, 0, &count, NULL) == 0) {
1076 			page_unlock(newpp);
1077 			ASSERT(hat_page_getattr(pp, P_MOD) == 0);
1078 		}
1079 	}
1080 
1081 	if (pp->p_vnode == &kvp) {
1082 		PR_DEBUG(prd_kern);
1083 		PR_INCR_KSTAT(pr_failed_kernel);
1084 		page_unlock(pp);
1085 		return (page_retire_done(pp, PRD_FAILED));
1086 	}
1087 
1088 	if (pp->p_lckcnt || pp->p_cowcnt) {
1089 		if (toxic & PR_UE) {
1090 			(void) page_clear_lck_cow(pp, 1);
1091 		} else {
1092 			PR_DEBUG(prd_locked);
1093 			PR_INCR_KSTAT(pr_failed);
1094 			page_unlock(pp);
1095 			return (page_retire_done(pp, PRD_FAILED));
1096 		}
1097 	}
1098 
1099 	(void) hat_pageunload(pp, HAT_FORCE_PGUNLOAD);
1100 	ASSERT(!PP_ISFREE(pp));
1101 	ASSERT(!hat_page_is_mapped(pp));
1102 
1103 	/*
1104 	 * If the page is modified, was not relocated, and not toxic,
1105 	 * we can't retire it without dropping data on the floor.
1106 	 *
1107 	 * RFE: we could change fsflush so that it (and only it) will
1108 	 * be allowed to lock this page and push it out.  Once it cleans
1109 	 * the page, we'd then be able to retire it on the free path.
1110 	 * In practice, this should be exceedingly rare.
1111 	 */
1112 	if (hat_ismod(pp)) {
1113 		if ((toxic & PR_UE) == 0) {
1114 			PR_DEBUG(prd_modce);
1115 			PR_INCR_KSTAT(pr_failed);
1116 			page_unlock(pp);
1117 			return (page_retire_done(pp, PRD_FAILED));
1118 		} else if (page_retire_modified == 0) {
1119 			PR_DEBUG(prd_modue_fail);
1120 			PR_INCR_KSTAT(pr_failed);
1121 			page_unlock(pp);
1122 			return (page_retire_done(pp, PRD_FAILED));
1123 		}
1124 		PR_DEBUG(prd_modue_retire);
1125 	}
1126 
1127 	if (pp->p_vnode) {
1128 		PR_DEBUG(prd_hashout);
1129 		page_hashout(pp, NULL);
1130 	}
1131 	ASSERT(!pp->p_vnode);
1132 
1133 	/*
1134 	 * The problem page is locked, demoted, unmapped, not free,
1135 	 * hashed out, and not COW or mlocked (whew!).
1136 	 *
1137 	 * Now we select our ammunition, take it around back, and shoot it.
1138 	 */
1139 	if (toxic & PR_UE) {
1140 		if (hat_ismod(pp)) {
1141 			/*
1142 			 * Let the user know we are dropping their data
1143 			 * on the floor.
1144 			 */
1145 			PR_MESSAGE(CE_WARN, 1, "Removing modified page "
1146 			    "0x%08x.%08x from service",
1147 			    mmu_ptob(pp->p_pagenum));
1148 		}
1149 		if (page_retire_transient_ue(pp)) {
1150 			PR_DEBUG(prd_uescrubbed);
1151 			return (page_retire_done(pp, PRD_UE_SCRUBBED));
1152 		} else {
1153 			PR_DEBUG(prd_uenotscrubbed);
1154 			page_retire_destroy(pp);
1155 			return (page_retire_done(pp, PRD_SUCCESS));
1156 		}
1157 	} else if (toxic & PR_FMA) {
1158 		PR_DEBUG(prd_fma);
1159 		page_retire_destroy(pp);
1160 		return (page_retire_done(pp, PRD_SUCCESS));
1161 	} else if (toxic & PR_MCE) {
1162 		PR_DEBUG(prd_mce);
1163 		page_retire_destroy(pp);
1164 		return (page_retire_done(pp, PRD_SUCCESS));
1165 	}
1166 	panic("page_retire_pp: bad toxic flags %d", toxic);
1167 	/*NOTREACHED*/
1168 }
1169 
1170 /*
1171  * Try to retire a page when we stumble onto it in the page lock routines.
1172  */
1173 void
1174 page_tryretire(page_t *pp)
1175 {
1176 	ASSERT(PAGE_EXCL(pp));
1177 
1178 	if (!pr_enable) {
1179 		page_unlock(pp);
1180 		return;
1181 	}
1182 
1183 	/*
1184 	 * If the page is a big page, try to break it up.
1185 	 *
1186 	 * If there are other bad pages besides `pp', they will be
1187 	 * recursively retired for us thanks to a bit of magic.
1188 	 * If the page is a small page with errors, try to retire it.
1189 	 */
1190 	if (pp->p_szc > 0) {
1191 		if (PP_ISFREE(pp) && !page_try_demote_free_pages(pp)) {
1192 			page_unlock(pp);
1193 			PR_DEBUG(prd_nofreedemote);
1194 			return;
1195 		} else if (!page_try_demote_pages(pp)) {
1196 			page_unlock(pp);
1197 			PR_DEBUG(prd_nodemote);
1198 			return;
1199 		}
1200 		PR_DEBUG(prd_demoted);
1201 		page_unlock(pp);
1202 	} else {
1203 		(void) page_retire_pp(pp);
1204 	}
1205 }
1206 
1207 /*
1208  * page_retire() - the front door in to retire a page.
1209  *
1210  * Ideally, page_retire() would instantly retire the requested page.
1211  * Unfortunately, some pages are locked or otherwise tied up and cannot be
1212  * retired right away. To deal with that, bits are set in p_toxic of the
1213  * page_t. An attempt is made to lock the page; if the attempt is successful,
1214  * we instantly unlock the page counting on page_unlock() to notice p_toxic
1215  * is nonzero and to call back into page_retire_pp(). Success is determined
1216  * by looking to see whether the page has been retired once it has been
1217  * unlocked.
1218  *
1219  * Returns:
1220  *
1221  *   - 0 on success,
1222  *   - EINVAL when the PA is whacko,
1223  *   - EBUSY if the page is already retired, or
1224  *   - EAGAIN if the page could not be _immediately_ retired.
1225  */
1226 int
1227 page_retire(uint64_t pa, uchar_t reason)
1228 {
1229 	page_t	*pp;
1230 
1231 	ASSERT(reason & PR_REASONS);		/* there must be a reason */
1232 	ASSERT(!(reason & ~PR_REASONS));	/* but no other bits */
1233 
1234 	pp = page_numtopp_nolock(mmu_btop(pa));
1235 	if (pp == NULL) {
1236 		PR_MESSAGE(CE_WARN, 1, "Cannot schedule clearing of error on"
1237 		    " page 0x%08x.%08x; page is not relocatable memory", pa);
1238 		return (page_retire_done(pp, PRD_INVALID_PA));
1239 	}
1240 	if (PP_RETIRED(pp)) {
1241 		return (page_retire_done(pp, PRD_DUPLICATE));
1242 	}
1243 
1244 	if (reason & PR_UE) {
1245 		PR_MESSAGE(CE_NOTE, 1, "Scheduling clearing of error on"
1246 		    " page 0x%08x.%08x", pa);
1247 	} else {
1248 		PR_MESSAGE(CE_NOTE, 1, "Scheduling removal of"
1249 		    " page 0x%08x.%08x", pa);
1250 	}
1251 	page_settoxic(pp, reason);
1252 	page_retire_enqueue(pp);
1253 
1254 	/*
1255 	 * And now for some magic.
1256 	 *
1257 	 * We marked this page toxic up above.  All there is left to do is
1258 	 * to try to lock the page and then unlock it.  The page lock routines
1259 	 * will intercept the page and retire it if they can.  If the page
1260 	 * cannot be locked, 's okay -- page_unlock() will eventually get it,
1261 	 * or the background thread, until then the lock routines will deny
1262 	 * further locks on it.
1263 	 */
1264 	if (MTBF(pr_calls, pr_mtbf) && page_trylock(pp, SE_EXCL)) {
1265 		PR_DEBUG(prd_prlocked);
1266 		page_unlock(pp);
1267 	} else {
1268 		PR_DEBUG(prd_prnotlocked);
1269 	}
1270 
1271 	if (PP_RETIRED(pp)) {
1272 		PR_DEBUG(prd_prretired);
1273 		return (0);
1274 	} else {
1275 		cv_signal(&pr_cv);
1276 		PR_INCR_KSTAT(pr_failed);
1277 
1278 		if (pp->p_toxic & PR_MSG) {
1279 			return (page_retire_done(pp, PRD_FAILED));
1280 		} else {
1281 			return (page_retire_done(pp, PRD_PENDING));
1282 		}
1283 	}
1284 }
1285 
1286 /*
1287  * Take a retired page off the retired-pages vnode and clear the toxic flags.
1288  * If "free" is nonzero, lock it and put it back on the freelist. If "free"
1289  * is zero, the caller already holds SE_EXCL lock so we simply unretire it
1290  * and don't do anything else with it.
1291  *
1292  * Any unretire messages are printed from this routine.
1293  *
1294  * Returns 0 if page pp was unretired; else an error code.
1295  */
1296 int
1297 page_unretire_pp(page_t *pp, int free)
1298 {
1299 	/*
1300 	 * To be retired, a page has to be hashed onto the retired_pages vnode
1301 	 * and have PR_RETIRED set in p_toxic.
1302 	 */
1303 	if (free == 0 || page_try_reclaim_lock(pp, SE_EXCL, SE_RETIRED)) {
1304 		ASSERT(PAGE_EXCL(pp));
1305 		PR_DEBUG(prd_ulocked);
1306 		if (!PP_RETIRED(pp)) {
1307 			PR_DEBUG(prd_unotretired);
1308 			page_unlock(pp);
1309 			return (page_retire_done(pp, PRD_UNR_NOT));
1310 		}
1311 
1312 		PR_MESSAGE(CE_NOTE, 1, "unretiring retired"
1313 		    " page 0x%08x.%08x", mmu_ptob(pp->p_pagenum));
1314 		if (pp->p_toxic & PR_FMA) {
1315 			PR_DECR_KSTAT(pr_fma);
1316 		} else if (pp->p_toxic & PR_UE) {
1317 			PR_DECR_KSTAT(pr_ue);
1318 		} else {
1319 			PR_DECR_KSTAT(pr_mce);
1320 		}
1321 		page_clrtoxic(pp, PR_ALLFLAGS);
1322 
1323 		if (free) {
1324 			PR_DEBUG(prd_udestroy);
1325 			page_destroy(pp, 0);
1326 		} else {
1327 			PR_DEBUG(prd_uhashout);
1328 			page_hashout(pp, NULL);
1329 		}
1330 
1331 		mutex_enter(&freemem_lock);
1332 		availrmem++;
1333 		mutex_exit(&freemem_lock);
1334 
1335 		PR_DEBUG(prd_uunretired);
1336 		PR_DECR_KSTAT(pr_retired);
1337 		PR_INCR_KSTAT(pr_unretired);
1338 		return (page_retire_done(pp, PRD_UNR_SUCCESS));
1339 	}
1340 	PR_DEBUG(prd_unotlocked);
1341 	return (page_retire_done(pp, PRD_UNR_CANTLOCK));
1342 }
1343 
1344 /*
1345  * Return a page to service by moving it from the retired_pages vnode
1346  * onto the freelist.
1347  *
1348  * Called from mmioctl_page_retire() on behalf of the FMA DE.
1349  *
1350  * Returns:
1351  *
1352  *   - 0 if the page is unretired,
1353  *   - EAGAIN if the pp can not be locked,
1354  *   - EINVAL if the PA is whacko, and
1355  *   - EBADF if the pp is not retired.
1356  */
1357 int
1358 page_unretire(uint64_t pa)
1359 {
1360 	page_t	*pp;
1361 
1362 	pp = page_numtopp_nolock(mmu_btop(pa));
1363 	if (pp == NULL) {
1364 		return (page_retire_done(pp, PRD_INVALID_PA));
1365 	}
1366 
1367 	return (page_unretire_pp(pp, 1));
1368 }
1369 
1370 /*
1371  * Test a page to see if it is retired. If errors is non-NULL, the toxic
1372  * bits of the page are returned. Returns 0 on success, error code on failure.
1373  */
1374 int
1375 page_retire_check_pp(page_t *pp, uint64_t *errors)
1376 {
1377 	int rc;
1378 
1379 	if (PP_RETIRED(pp)) {
1380 		PR_DEBUG(prd_checkhit);
1381 		rc = 0;
1382 	} else {
1383 		PR_DEBUG(prd_checkmiss);
1384 		rc = EAGAIN;
1385 	}
1386 
1387 	/*
1388 	 * We have magically arranged the bit values returned to fmd(1M)
1389 	 * to line up with the FMA, MCE, and UE bits of the page_t.
1390 	 */
1391 	if (errors) {
1392 		uint64_t toxic = (uint64_t)(pp->p_toxic & PR_ERRMASK);
1393 		if (toxic & PR_UE_SCRUBBED) {
1394 			toxic &= ~PR_UE_SCRUBBED;
1395 			toxic |= PR_UE;
1396 		}
1397 		*errors = toxic;
1398 	}
1399 
1400 	return (rc);
1401 }
1402 
1403 /*
1404  * Test to see if the page_t for a given PA is retired, and return the
1405  * hardware errors we have seen on the page if requested.
1406  *
1407  * Called from mmioctl_page_retire on behalf of the FMA DE.
1408  *
1409  * Returns:
1410  *
1411  *   - 0 if the page is retired,
1412  *   - EAGAIN if it is not, and
1413  *   - EINVAL if the PA is whacko.
1414  */
1415 int
1416 page_retire_check(uint64_t pa, uint64_t *errors)
1417 {
1418 	page_t	*pp;
1419 
1420 	if (errors) {
1421 		*errors = 0;
1422 	}
1423 
1424 	pp = page_numtopp_nolock(mmu_btop(pa));
1425 	if (pp == NULL) {
1426 		return (page_retire_done(pp, PRD_INVALID_PA));
1427 	}
1428 
1429 	return (page_retire_check_pp(pp, errors));
1430 }
1431 
1432 /*
1433  * Page retire self-test. For now, it always returns 0.
1434  */
1435 int
1436 page_retire_test(void)
1437 {
1438 	page_t *first, *pp, *cpp, *cpp2, *lpp;
1439 
1440 	/*
1441 	 * Tests the corner case where a large page can't be retired
1442 	 * because one of the constituent pages is locked. We mark
1443 	 * one page to be retired and try to retire it, and mark the
1444 	 * other page to be retired but don't try to retire it, so
1445 	 * that page_unlock() in the failure path will recurse and try
1446 	 * to retire THAT page. This is the worst possible situation
1447 	 * we can get ourselves into.
1448 	 */
1449 	memsegs_lock(0);
1450 	pp = first = page_first();
1451 	do {
1452 		if (pp->p_szc && PP_PAGEROOT(pp) == pp) {
1453 			cpp = pp + 1;
1454 			lpp = PP_ISFREE(pp)? pp : pp + 2;
1455 			cpp2 = pp + 3;
1456 			if (!page_trylock(lpp, pp == lpp? SE_EXCL : SE_SHARED))
1457 				continue;
1458 			if (!page_trylock(cpp, SE_EXCL)) {
1459 				page_unlock(lpp);
1460 				continue;
1461 			}
1462 			page_settoxic(cpp, PR_FMA | PR_BUSY);
1463 			page_settoxic(cpp2, PR_FMA);
1464 			page_tryretire(cpp);	/* will fail */
1465 			page_unlock(lpp);
1466 			(void) page_retire(cpp->p_pagenum, PR_FMA);
1467 			(void) page_retire(cpp2->p_pagenum, PR_FMA);
1468 		}
1469 	} while ((pp = page_next(pp)) != first);
1470 	memsegs_unlock(0);
1471 
1472 	return (0);
1473 }
1474