xref: /titanic_44/usr/src/cmd/rcap/rcapd/rcapd_scanner.c (revision 09f67678c27dda8a89f87f1f408a87dd49ceb0e1)
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 2004 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 #include <sys/mman.h>
30 #include <sys/param.h>
31 #include <sys/stat.h>
32 #include <sys/types.h>
33 #include <assert.h>
34 #include <errno.h>
35 #include <fcntl.h>
36 #include <libproc.h>
37 #include <limits.h>
38 #include <procfs.h>
39 #include <stdio.h>
40 #include <stdlib.h>
41 #include <strings.h>
42 #include <time.h>
43 #include <unistd.h>
44 #include "rcapd.h"
45 #include "rcapd_rfd.h"
46 #include "rcapd_mapping.h"
47 #include "utils.h"
48 
49 static int lpc_xmap_update(lprocess_t *);
50 #ifdef DEBUG
51 extern int lmapping_dump_diff(lmapping_t *lm1, lmapping_t *lm2);
52 #endif /* DEBUG */
53 
54 /*
55  * The number of file descriptors required to grab a process and create an
56  * agent in it.
57  */
58 #define	PGRAB_FD_COUNT		10
59 
60 /*
61  * Record a position in an address space as it corresponds to a prpageheader_t
62  * and affiliated structures.
63  */
64 typedef struct prpageheader_cur {
65 	int pr_nmap;		/* number of mappings in address space */
66 	int pr_map;		/* number of this mapping */
67 	uint64_t pr_pgoff;	/* page offset into mapping */
68 	uint64_t pr_npage;	/* number of pages in mapping */
69 	uint64_t pr_pagesize;	/* page size of mapping */
70 	uintptr_t pr_addr;	/* base of mapping */
71 	prpageheader_t *pr_prpageheader;	/* associated page header */
72 	void *pr_pdaddr;	/* address of page's byte in pagedata */
73 	prxmap_t *pr_xmap;	/* array containing per-segment information */
74 	int pr_nxmap;		/* number of xmaps in array */
75 	int64_t pr_rss;		/* number of resident pages in mapping, */
76 				/* or -1 if xmap is out of sync */
77 	int64_t pr_pg_rss;	/* number of pageable pages in mapping, or -1 */
78 } prpageheader_cur_t;
79 
80 static struct ps_prochandle *scan_pr;	/* currently-scanned process's handle */
81 
82 typedef enum {
83 	STDL_NORMAL,
84 	STDL_HIGH
85 } st_debug_level_t;
86 
87 /*
88  * Output a scanning-related debug message.
89  */
90 /*PRINTFLIKE3*/ /*ARGSUSED*/
91 static void
92 st_debug(st_debug_level_t level, lcollection_t *lcol, char *msg, ...)
93 {
94 #ifdef DEBUG_MSG
95 	va_list alist;
96 	char *buf;
97 	size_t len;
98 
99 	if (get_message_priority() < ((level == STDL_HIGH) ? RCM_DEBUG_HIGH
100 	    : RCM_DEBUG))
101 		return;
102 
103 	len = strlen(msg) + LINELEN;
104 	buf = malloc(len);
105 	if (buf == NULL)
106 		return;
107 	(void) snprintf(buf, len, "%s %s scanner %s", rcfg.rcfg_mode_name,
108 	    lcol->lcol_name, msg);
109 
110 	va_start(alist, msg);
111 	vdprintfe(RCM_DEBUG, buf, alist);
112 	va_end(alist);
113 
114 	free(buf);
115 #endif /* DEBUG_MSG */
116 }
117 
118 /*
119  * Determine the collection's current victim, based on its last.  The last will
120  * be returned, or, if invalid, any other valid process, if the collection has
121  * any.
122  */
123 static lprocess_t *
124 get_valid_victim(lcollection_t *lcol, lprocess_t *lpc)
125 {
126 	if (lpc == NULL || !lcollection_member(lcol, lpc))
127 		lpc = lcol->lcol_lprocess;
128 
129 	/*
130 	 * Find the next scannable process, and make it the victim.
131 	 */
132 	while (lpc != NULL && lpc->lpc_unscannable != 0)
133 		lpc = lpc->lpc_next;
134 
135 	return (lpc);
136 }
137 
138 /*
139  * Get a process's combined current pagedata (per-page referenced and modified
140  * bits) and set the supplied pointer to it.  The caller is responsible for
141  * freeing the data.  If the pagedata is unreadable, a nonzero value is
142  * returned, and errno is set.  Otherwise, 0 is returned.
143  */
144 static int
145 get_pagedata(prpageheader_t **pghpp, int fd)
146 {
147 	int res;
148 	struct stat st;
149 
150 redo:
151 	errno = 0;
152 	if (fstat(fd, &st) != 0) {
153 		debug("cannot stat pagedata\n");
154 		return (-1);
155 	}
156 
157 	errno = 0;
158 	*pghpp = malloc(st.st_size);
159 	if (*pghpp == NULL) {
160 		debug("cannot malloc() %ld bytes for pagedata", st.st_size);
161 		return (-1);
162 	}
163 	(void) bzero(*pghpp, st.st_size);
164 
165 	errno = 0;
166 	if ((res = read(fd, *pghpp, st.st_size)) != st.st_size) {
167 		free(*pghpp);
168 		*pghpp = NULL;
169 		if (res > 0 || errno == E2BIG) {
170 			debug("pagedata changed size, retrying\n");
171 			goto redo;
172 		} else {
173 			debug("cannot read pagedata");
174 			return (-1);
175 		}
176 	}
177 
178 	return (0);
179 }
180 
181 /*
182  * Return the count of kilobytes of pages represented by the given pagedata
183  * which meet the given criteria, having pages which are in all of the states
184  * specified by the mask, and in none of the states in the notmask.  If the
185  * CP_CLEAR flag is set, the pagedata will also be cleared.
186  */
187 #define	CP_CLEAR	1
188 static uint64_t
189 count_pages(prpageheader_t *pghp, int flags, int mask, int notmask)
190 {
191 	int map;
192 	caddr_t cur, end;
193 	prpageheader_t pgh = *pghp;
194 	prasmap_t *asmapp;
195 	uint64_t count = 0;
196 
197 	cur = (caddr_t)pghp + sizeof (*pghp);
198 	for (map = 0; map < pgh.pr_nmap; map++) {
199 		asmapp = (prasmap_t *)(uintptr_t)cur;
200 		cur += sizeof (*asmapp);
201 		end = cur + asmapp->pr_npage;
202 		while (cur < end) {
203 			if ((*cur & mask) == mask && (*cur & notmask) == 0)
204 				count += asmapp->pr_pagesize / 1024;
205 			if ((flags & CP_CLEAR) != 0)
206 				*cur = 0;
207 			cur++;
208 		}
209 
210 		/*
211 		 * Skip to next 64-bit-aligned address to get the next
212 		 * prasmap_t.
213 		 */
214 		cur = (caddr_t)((intptr_t)(cur + 7) & ~7);
215 	}
216 
217 	return (count);
218 }
219 
220 /*
221  * Return the amount of memory (in kilobytes) that hasn't been referenced or
222  * modified, which memory which will be paged out first.  Should be written to
223  * exclude nonresident pages when sufficient interfaces exist.
224  */
225 static uint64_t
226 unrm_size(lprocess_t *lpc)
227 {
228 	return (count_pages(lpc->lpc_prpageheader, CP_CLEAR,
229 	    0, PG_MODIFIED | PG_REFERENCED));
230 }
231 
232 /*
233  * Advance a prpageheader_cur_t to the address space's next mapping, returning
234  * its address, or NULL if there is none.  Any known nonpageable or nonresident
235  * mappings will be skipped over.
236  */
237 static uintptr_t
238 advance_prpageheader_cur_nextmapping(prpageheader_cur_t *pcp)
239 {
240 	prasmap_t *pap;
241 	int i;
242 
243 next:
244 	ASSERT(pcp->pr_map < pcp->pr_nmap);
245 	if ((pcp->pr_map + 1) == pcp->pr_nmap)
246 		return (NULL);
247 	pcp->pr_map++;
248 	if (pcp->pr_pgoff < pcp->pr_npage) {
249 		pcp->pr_pdaddr = (caddr_t)((uintptr_t)pcp->pr_pdaddr +
250 		    (pcp->pr_npage - pcp->pr_pgoff));
251 		pcp->pr_pgoff = pcp->pr_npage;
252 	}
253 	/*
254 	 * Skip to next 64-bit-aligned address to get the next prasmap_t.
255 	 */
256 	pcp->pr_pdaddr = (caddr_t)(((uintptr_t)pcp->pr_pdaddr + 7) & ~7);
257 	pap = (prasmap_t *)pcp->pr_pdaddr;
258 	pcp->pr_pgoff = 0;
259 	pcp->pr_npage = pap->pr_npage;
260 	pcp->pr_pagesize = pap->pr_pagesize;
261 	pcp->pr_addr = pap->pr_vaddr;
262 	pcp->pr_pdaddr = pap + 1;
263 
264 	/*
265 	 * Skip any known nonpageable mappings.  Currently, the only one
266 	 * detected is the schedctl page.
267 	 */
268 	if ((pap->pr_mflags ^ (MA_SHARED | MA_READ | MA_WRITE | MA_EXEC |
269 	    MA_ANON)) == 0 && pap->pr_npage == 1) {
270 		debug("identified nonpageable schedctl mapping at %p\n",
271 		    (void *)pcp->pr_addr);
272 		goto next;
273 	}
274 
275 	/*
276 	 * Skip mappings with no resident pages.  If the xmap does not
277 	 * correspond to the pagedata for any reason, it will be ignored.
278 	 */
279 	pcp->pr_rss = -1;
280 	pcp->pr_pg_rss = -1;
281 	for (i = 0; i < pcp->pr_nxmap; i++) {
282 		prxmap_t *xmap = &pcp->pr_xmap[i];
283 
284 		if (pcp->pr_addr == xmap->pr_vaddr && xmap->pr_size ==
285 		    (pcp->pr_npage * pcp->pr_pagesize)) {
286 			pcp->pr_rss = xmap->pr_rss;
287 			/*
288 			 * Remove COW pages from the pageable RSS count.
289 			 */
290 			if ((xmap->pr_mflags & MA_SHARED) == 0)
291 				pcp->pr_pg_rss = xmap->pr_anon;
292 			break;
293 		}
294 	}
295 	if (pcp->pr_rss == 0) {
296 		debug("identified nonresident mapping at 0x%p\n",
297 		    (void *)pcp->pr_addr);
298 		goto next;
299 	} else if (pcp->pr_pg_rss == 0) {
300 		debug("identified unpageable mapping at 0x%p\n",
301 		    (void *)pcp->pr_addr);
302 		goto next;
303 	}
304 
305 	return (pcp->pr_addr);
306 }
307 
308 /*
309  * Advance a prpageheader_cur_t to the mapping's next page, returning its
310  * address, or NULL if there is none.
311  */
312 static void *
313 advance_prpageheader_cur(prpageheader_cur_t *pcp)
314 {
315 	ASSERT(pcp->pr_pgoff < pcp->pr_npage);
316 	if ((pcp->pr_pgoff + 1) == pcp->pr_npage)
317 		return (NULL);
318 	pcp->pr_pdaddr = (caddr_t)pcp->pr_pdaddr + 1;
319 	pcp->pr_pgoff++;
320 
321 	ASSERT((*(char *)pcp->pr_pdaddr & ~(PG_MODIFIED | PG_REFERENCED)) == 0);
322 	return ((caddr_t)pcp->pr_addr + pcp->pr_pgoff * pcp->pr_pagesize);
323 }
324 
325 /*
326  * Initialize a prpageheader_cur_t, positioned at the first page of the mapping
327  * of an address space.
328  */
329 static void *
330 set_prpageheader_cur(prpageheader_cur_t *pcp, prpageheader_t *php,
331     prxmap_t *xmap, int nxmap)
332 {
333 	bzero(pcp, sizeof (*pcp));
334 	pcp->pr_nmap = php->pr_nmap;
335 	pcp->pr_map = -1;
336 	pcp->pr_prpageheader = php;
337 	pcp->pr_xmap = xmap;
338 	pcp->pr_nxmap = nxmap;
339 	pcp->pr_pdaddr = (prpageheader_t *)php + 1;
340 
341 	return ((void *)advance_prpageheader_cur_nextmapping(pcp));
342 }
343 
344 /*
345  * Position a prpageheader_cur_t to the mapped address greater or equal to the
346  * given value.
347  */
348 static void *
349 set_prpageheader_cur_addr(prpageheader_cur_t *pcp, prpageheader_t *php,
350     prxmap_t *xmap, int nxmap, void *naddr)
351 {
352 	void *addr = set_prpageheader_cur(pcp, php, xmap, nxmap);
353 
354 	while (addr != NULL && addr <= naddr)
355 		if (naddr < (void *)((caddr_t)pcp->pr_addr +
356 		    pcp->pr_pagesize * pcp->pr_npage)) {
357 			uint64_t pgdiff = ((uintptr_t)naddr -
358 			    (uintptr_t)pcp->pr_addr) / pcp->pr_pagesize;
359 			pcp->pr_pgoff += pgdiff;
360 			pcp->pr_pdaddr = (caddr_t)pcp->pr_pdaddr + pgdiff;
361 			addr = (caddr_t)pcp->pr_addr + pcp->pr_pagesize *
362 			    pcp->pr_pgoff;
363 			break;
364 		} else
365 			addr =
366 			    (void *)advance_prpageheader_cur_nextmapping(pcp);
367 
368 	return (addr);
369 }
370 
371 static void
372 revoke_pagedata(rfd_t *rfd)
373 {
374 	lprocess_t *lpc = rfd->rfd_data;
375 
376 	st_debug(STDL_NORMAL, lpc->lpc_collection, "revoking pagedata for"
377 	    " process %d\n", (int)lpc->lpc_pid);
378 	ASSERT(lpc->lpc_pgdata_fd != -1);
379 	lpc->lpc_pgdata_fd = -1;
380 }
381 
382 #ifdef DEBUG
383 static void
384 mklmapping(lmapping_t **lm, prpageheader_t *pgh)
385 {
386 	prpageheader_cur_t cur;
387 	void *addr;
388 
389 	addr = set_prpageheader_cur(&cur, pgh, NULL, -1);
390 	ASSERT(*lm == NULL);
391 	while (addr != NULL) {
392 		(void) lmapping_insert(lm, cur.pr_addr, cur.pr_npage *
393 		    cur.pr_pagesize);
394 		addr = (void *)advance_prpageheader_cur_nextmapping(&cur);
395 	}
396 }
397 
398 static void
399 lmapping_dump(lmapping_t *lm)
400 {
401 	debug("lm: %p\n", (void *)lm);
402 	while (lm != NULL) {
403 		debug("\t(%p, %llx\n", (void *)lm->lm_addr,
404 		    (unsigned long long)lm->lm_size);
405 		lm = lm->lm_next;
406 	}
407 }
408 #endif /* DEBUG */
409 
410 /*
411  * OR two prpagedata_t which are supposedly snapshots of the same address
412  * space.  Intersecting mappings with different page sizes are tolerated but
413  * not normalized (not accurate).  If the mappings of the two snapshots differ
414  * in any regard, the supplied mappings_changed flag will be set.
415  */
416 static void
417 OR_pagedata(prpageheader_t *src, prpageheader_t *dst, int *mappings_changedp)
418 {
419 	prpageheader_cur_t src_cur;
420 	prpageheader_cur_t dst_cur;
421 	uintptr_t src_addr;
422 	uintptr_t dst_addr;
423 	int mappings_changed = 0;
424 
425 	/*
426 	 * OR source pagedata with the destination, for pages of intersecting
427 	 * mappings.
428 	 */
429 	src_addr = (uintptr_t)set_prpageheader_cur(&src_cur, src, NULL, -1);
430 	dst_addr = (uintptr_t)set_prpageheader_cur(&dst_cur, dst, NULL, -1);
431 	while (src_addr != NULL && dst_addr != NULL) {
432 		while (src_addr == dst_addr && src_addr != NULL) {
433 			*(char *)dst_cur.pr_pdaddr |=
434 			    *(char *)src_cur.pr_pdaddr;
435 			src_addr = (uintptr_t)advance_prpageheader_cur(
436 			    &src_cur);
437 			dst_addr = (uintptr_t)advance_prpageheader_cur(
438 			    &dst_cur);
439 		}
440 		if (src_addr != dst_addr)
441 			mappings_changed = 1;
442 		src_addr = advance_prpageheader_cur_nextmapping(&src_cur);
443 		dst_addr = advance_prpageheader_cur_nextmapping(&dst_cur);
444 		while (src_addr != dst_addr && src_addr != NULL && dst_addr !=
445 		    NULL) {
446 			mappings_changed = 1;
447 			if (src_addr < dst_addr)
448 				src_addr = advance_prpageheader_cur_nextmapping(
449 				    &src_cur);
450 			else
451 				dst_addr = advance_prpageheader_cur_nextmapping(
452 				    &dst_cur);
453 		}
454 	}
455 
456 	*mappings_changedp = mappings_changed;
457 }
458 
459 /*
460  * Merge the current pagedata with that on hand.  If the pagedata is
461  * unretrievable for any reason, such as the process having exited or being a
462  * zombie, a nonzero value is returned, the process should be marked
463  * unscannable, and future attempts to scan it should be avoided, since the
464  * symptom is probably permament.  If the mappings of either pagedata
465  * differ in any respect, the supplied callback will be invoked once.
466  */
467 static int
468 merge_current_pagedata(lprocess_t *lpc,
469     void(*mappings_changed_cb) (lprocess_t *))
470 {
471 	prpageheader_t *pghp;
472 	int mappings_changed = 0;
473 
474 	if (lpc->lpc_pgdata_fd < 0 || get_pagedata(&pghp, lpc->lpc_pgdata_fd) !=
475 	    0) {
476 		char pathbuf[PROC_PATH_MAX];
477 
478 		(void) snprintf(pathbuf, sizeof (pathbuf), "/proc/%d/pagedata",
479 		    (int)lpc->lpc_pid);
480 		if ((lpc->lpc_pgdata_fd = rfd_open(pathbuf, 1, RFD_PAGEDATA,
481 		    revoke_pagedata, lpc, O_RDONLY, 0)) < 0 ||
482 		    get_pagedata(&pghp, lpc->lpc_pgdata_fd) != 0)
483 			return (-1);
484 		debug("starting/resuming pagedata collection for %d\n",
485 		    (int)lpc->lpc_pid);
486 	}
487 	debug("process %d: %llu/%llukB r/m'd since last read\n",
488 	    (int)lpc->lpc_pid, (unsigned long long)count_pages(pghp, 0,
489 	    PG_MODIFIED | PG_REFERENCED, 0), (unsigned long long)lpc->lpc_rss);
490 	if (lpc->lpc_prpageheader != NULL) {
491 		/*
492 		 * OR the two snapshots.
493 		 */
494 #ifdef DEBUG
495 		lmapping_t *old = NULL;
496 		lmapping_t *new = NULL;
497 
498 		mklmapping(&new, pghp);
499 		mklmapping(&old, lpc->lpc_prpageheader);
500 #endif /* DEBUG */
501 		OR_pagedata(lpc->lpc_prpageheader, pghp, &mappings_changed);
502 #ifdef DEBUG
503 		if (((mappings_changed != 0) ^
504 		    (lmapping_dump_diff(old, new) != 0))) {
505 			debug("lmapping_changed inconsistent with lmapping\n");
506 			debug("old\n");
507 			lmapping_dump(old);
508 			debug("new\n");
509 			lmapping_dump(new);
510 			debug("ignored\n");
511 			lmapping_dump(lpc->lpc_ignore);
512 			ASSERT(0);
513 		}
514 		lmapping_free(&new);
515 		lmapping_free(&old);
516 #endif /* DEBUG */
517 		free(lpc->lpc_prpageheader);
518 	} else
519 		mappings_changed = 1;
520 	lpc->lpc_prpageheader = pghp;
521 	debug("process %d: %llu/%llukB r/m'd since hand swept\n",
522 	    (int)lpc->lpc_pid, (unsigned long long)count_pages(pghp, 0,
523 	    PG_MODIFIED | PG_REFERENCED, 0),
524 	    (unsigned long long)lpc->lpc_rss);
525 	if (mappings_changed != 0) {
526 		debug("process %d: mappings changed\n", (int)lpc->lpc_pid);
527 		if (mappings_changed_cb != NULL)
528 			mappings_changed_cb(lpc);
529 	}
530 	return (0);
531 }
532 
533 /*
534  * Attempt to page out a region of the given process's address space.  May
535  * return nonzero if not all of the pages may are pageable, for any reason.
536  */
537 static int
538 pageout(pid_t pid, struct ps_prochandle *Pr, caddr_t start, caddr_t end)
539 {
540 	int res;
541 
542 	if (end <= start)
543 		return (0);
544 
545 	errno = 0;
546 	res = pr_memcntl(Pr, start, (end - start), MC_SYNC,
547 	    (caddr_t)(MS_ASYNC | MS_INVALIDATE), 0, 0);
548 	debug_high("pr_memcntl [%p-%p): %d", (void *)start, (void *)end, res);
549 
550 	/*
551 	 * EBUSY indicates none of the pages have backing store allocated, or
552 	 * some pages were locked, which are less interesting than other
553 	 * conditions, which are noted.
554 	 */
555 	if (res != 0)
556 		if (errno == EBUSY)
557 			res = 0;
558 		else
559 			debug("%d: can't pageout %p+%llx (errno %d)", (int)pid,
560 			    (void *)start, (long long)(end - start), errno);
561 
562 	return (res);
563 }
564 
565 /*
566  * Compute the delta of the victim process's RSS since the last call.  If the
567  * psinfo cannot be obtained, no work is done, and no error is returned; it is
568  * up to the caller to detect the process' termination via other means.
569  */
570 static int64_t
571 rss_delta(psinfo_t *new_psinfo, psinfo_t *old_psinfo, lprocess_t *vic)
572 {
573 	int64_t d_rss = 0;
574 
575 	if (get_psinfo(vic->lpc_pid, new_psinfo, vic->lpc_psinfo_fd,
576 	    lprocess_update_psinfo_fd_cb, vic, vic) == 0) {
577 		d_rss = (int64_t)new_psinfo->pr_rssize -
578 		    (int64_t)old_psinfo->pr_rssize;
579 		if (d_rss < 0)
580 			vic->lpc_collection->lcol_stat.lcols_pg_eff +=
581 			    (- d_rss);
582 		*old_psinfo = *new_psinfo;
583 	}
584 
585 	return (d_rss);
586 }
587 
588 static void
589 unignore_mappings(lprocess_t *lpc)
590 {
591 	debug("clearing ignored set\n");
592 	lmapping_free(&lpc->lpc_ignore);
593 }
594 
595 static void
596 unignore_referenced_mappings(lprocess_t *lpc)
597 {
598 	prpageheader_cur_t cur;
599 	void *vicaddr;
600 
601 	vicaddr = set_prpageheader_cur(&cur, lpc->lpc_prpageheader, NULL, -1);
602 	while (vicaddr != NULL) {
603 		if (((*(char *)cur.pr_pdaddr) & (PG_REFERENCED | PG_MODIFIED))
604 		    != 0) {
605 			if (lmapping_remove(&lpc->lpc_ignore, cur.pr_addr,
606 			    cur.pr_npage * cur.pr_pagesize) == 0)
607 				debug("removed mapping 0x%p+0t%llukB from"
608 				    " ignored set\n", (void *)cur.pr_addr,
609 				    (unsigned long long)(cur.pr_npage *
610 				    cur.pr_pagesize / 1024));
611 			vicaddr = (void *)advance_prpageheader_cur_nextmapping(
612 			    &cur);
613 		} else if ((vicaddr = advance_prpageheader_cur(&cur)) == NULL)
614 			vicaddr = (void *)advance_prpageheader_cur_nextmapping(
615 			    &cur);
616 	}
617 }
618 
619 /*
620  * Resume scanning, starting with the last victim, if it is still valid, or any
621  * other one, otherwise.
622  */
623 void
624 scan(lcollection_t *lcol, int64_t excess)
625 {
626 	lprocess_t *vic, *lpc;
627 	void *vicaddr, *endaddr, *nvicaddr;
628 	prpageheader_cur_t cur;
629 	psinfo_t old_psinfo, new_psinfo;
630 	hrtime_t scan_start;
631 	int res, resumed;
632 	uint64_t col_unrm_size;
633 
634 	st_debug(STDL_NORMAL, lcol, "starting to scan, excess %lldk\n",
635 	    (long long)excess);
636 
637 	/*
638 	 * Determine the address to start scanning at, depending on whether
639 	 * scanning can be resumed.
640 	 */
641 	endaddr = NULL;
642 	if ((vic = get_valid_victim(lcol, lcol->lcol_victim)) ==
643 	    lcol->lcol_victim && lcol->lcol_resaddr != NULL) {
644 		vicaddr = lcol->lcol_resaddr;
645 		st_debug(STDL_NORMAL, lcol, "resuming process %d\n",
646 		    (int)vic->lpc_pid);
647 		resumed = 1;
648 	} else {
649 		vicaddr = NULL;
650 		resumed = 0;
651 	}
652 
653 	scan_start = gethrtime();
654 	/*
655 	 * Obtain the most current pagedata for the processes that might be
656 	 * scanned, and remove from the ignored set any mappings which have
657 	 * referenced or modified pages (in the hopes that the pageability of
658 	 * the mapping's pages may have changed).  Determine if the
659 	 * unreferenced and unmodified portion is impossibly small to suffice
660 	 * to reduce the excess completely.  If so, ignore these bits so that
661 	 * even working set will be paged out.
662 	 */
663 	col_unrm_size = 0;
664 	lpc = vic;
665 	while (lpc != NULL && should_run) {
666 		if (merge_current_pagedata(lpc, unignore_mappings) != 0) {
667 			st_debug(STDL_NORMAL, lcol, "process %d:"
668 			    " exited/temporarily unscannable",
669 			    (int)lpc->lpc_pid);
670 			goto next;
671 		}
672 		debug("process %d: %llu/%llukB scannable\n", (int)lpc->lpc_pid,
673 		    (unsigned long long)(lpc->lpc_unrm = unrm_size(lpc)),
674 		    (unsigned long long)lpc->lpc_size);
675 		col_unrm_size += lpc->lpc_unrm = unrm_size(lpc);
676 
677 		if ((lcol->lcol_stat.lcols_scan_count %
678 		    RCAPD_IGNORED_SET_FLUSH_IVAL) == 0) {
679 			/*
680 			 * Periodically clear the set of ignored mappings.
681 			 * This will allow processes whose ignored segments'
682 			 * pageability have changed (without a corresponding
683 			 * reference or modification to a page) to be
684 			 * recognized.
685 			 */
686 			if (lcol->lcol_stat.lcols_scan_count > 0)
687 				unignore_mappings(lpc);
688 		} else {
689 			/*
690 			 * Ensure mappings with referenced or modified pages
691 			 * are not in the ignored set.  Their usage might mean
692 			 * the condition which made them unpageable is gone.
693 			 */
694 			unignore_referenced_mappings(lpc);
695 		}
696 next:
697 		lpc = lpc->lpc_next != NULL ? get_valid_victim(lcol,
698 		    lpc->lpc_next) : NULL;
699 	}
700 	if (col_unrm_size < excess) {
701 		lpc = vic;
702 		debug("will not reduce excess with only unreferenced pages\n");
703 		while (lpc != NULL && should_run) {
704 			if (lpc->lpc_prpageheader != NULL) {
705 				(void) count_pages(lpc->lpc_prpageheader,
706 				    CP_CLEAR, 0, 0);
707 				if (lpc->lpc_pgdata_fd >= 0) {
708 					if (rfd_close(lpc->lpc_pgdata_fd) != 0)
709 						debug("coud not close %d"
710 						    " lpc_pgdata_fd %d",
711 						    (int)lpc->lpc_pid,
712 						    lpc->lpc_pgdata_fd);
713 					lpc->lpc_pgdata_fd = -1;
714 				}
715 			}
716 			lpc = lpc->lpc_next != NULL ? get_valid_victim(lcol,
717 			    lpc->lpc_next) : NULL;
718 		}
719 	}
720 
721 	/*
722 	 * Examine each process for pages to remove until the excess is
723 	 * reduced.
724 	 */
725 	while (vic != NULL && excess > 0 && should_run) {
726 		/*
727 		 * Skip processes whose death was reported when the merging of
728 		 * pagedata was attempted.
729 		 */
730 		if (vic->lpc_prpageheader == NULL)
731 			goto nextproc;
732 
733 		/*
734 		 * Obtain optional segment residency information.
735 		 */
736 		if (lpc_xmap_update(vic) != 0)
737 			st_debug(STDL_NORMAL, lcol, "process %d: xmap"
738 			    " unreadable; ignoring", (int)vic->lpc_pid);
739 
740 #ifdef DEBUG_MSG
741 		{
742 			void *ovicaddr = vicaddr;
743 #endif /* DEBUG_MSG */
744 		vicaddr = set_prpageheader_cur_addr(&cur, vic->lpc_prpageheader,
745 		    vic->lpc_xmap, vic->lpc_nxmap, vicaddr);
746 #ifdef DEBUG_MSG
747 			st_debug(STDL_NORMAL, lcol, "trying to resume from"
748 			    " 0x%p, next 0x%p\n", ovicaddr, vicaddr);
749 		}
750 #endif /* DEBUG_MSG */
751 
752 		/*
753 		 * Take control of the victim.
754 		 */
755 		if (get_psinfo(vic->lpc_pid, &old_psinfo,
756 		    vic->lpc_psinfo_fd, lprocess_update_psinfo_fd_cb,
757 		    vic, vic) != 0) {
758 			st_debug(STDL_NORMAL, lcol, "cannot get %d psinfo",
759 			    (int)vic->lpc_pid);
760 			goto nextproc;
761 		}
762 		(void) rfd_reserve(PGRAB_FD_COUNT);
763 		if ((scan_pr = Pgrab(vic->lpc_pid, 0, &res)) == NULL) {
764 			st_debug(STDL_NORMAL, lcol, "cannot grab %d (%d)",
765 			    (int)vic->lpc_pid, res);
766 			goto nextproc;
767 		}
768 		if (Pcreate_agent(scan_pr) != 0) {
769 			st_debug(STDL_NORMAL, lcol, "cannot control %d",
770 			    (int)vic->lpc_pid);
771 			goto nextproc;
772 		}
773 		/*
774 		 * Be very pessimistic about the state of the agent LWP --
775 		 * verify it's actually stopped.
776 		 */
777 		errno = 0;
778 		while (Pstate(scan_pr) == PS_RUN)
779 			(void) Pwait(scan_pr, 0);
780 		if (Pstate(scan_pr) != PS_STOP) {
781 			st_debug(STDL_NORMAL, lcol, "agent not in expected"
782 			    " state (%d)", Pstate(scan_pr));
783 			goto nextproc;
784 		}
785 
786 		/*
787 		 * Within the victim's address space, find contiguous ranges of
788 		 * unreferenced pages to page out.
789 		 */
790 		st_debug(STDL_NORMAL, lcol, "paging out process %d\n",
791 		    (int)vic->lpc_pid);
792 		while (excess > 0 && vicaddr != NULL && should_run) {
793 			/*
794 			 * Skip mappings in the ignored set.  Mappings get
795 			 * placed in the ignored set when all their resident
796 			 * pages are unreference and unmodified, yet unpageable
797 			 * -- such as when they are locked, or involved in
798 			 * asynchronous I/O.  They will be scanned again when
799 			 * some page is referenced or modified.
800 			 */
801 			if (lmapping_contains(vic->lpc_ignore, cur.pr_addr,
802 			    cur.pr_npage * cur.pr_pagesize)) {
803 				debug("ignored mapping at 0x%p\n",
804 				    (void *)cur.pr_addr);
805 				/*
806 				 * Update statistics.
807 				 */
808 				lcol->lcol_stat.lcols_pg_att +=
809 				    cur.pr_npage * cur.pr_pagesize / 1024;
810 
811 				vicaddr = (void *)
812 				    advance_prpageheader_cur_nextmapping(&cur);
813 				continue;
814 			}
815 
816 			/*
817 			 * Determine a range of unreferenced pages to page out,
818 			 * and clear the R/M bits in the preceding referenced
819 			 * range.
820 			 */
821 			st_debug(STDL_HIGH, lcol, "start from mapping at 0x%p,"
822 			    " npage %llu\n", vicaddr,
823 			    (unsigned long long)cur.pr_npage);
824 			while (vicaddr != NULL &&
825 			    *(caddr_t)cur.pr_pdaddr != 0) {
826 				*(caddr_t)cur.pr_pdaddr = 0;
827 				vicaddr = advance_prpageheader_cur(&cur);
828 			}
829 			st_debug(STDL_HIGH, lcol, "advance, vicaddr %p, pdaddr"
830 			    " %p\n", vicaddr, cur.pr_pdaddr);
831 			if (vicaddr == NULL) {
832 				/*
833 				 * The end of mapping was reached before any
834 				 * unreferenced pages were seen.
835 				 */
836 				vicaddr = (void *)
837 				    advance_prpageheader_cur_nextmapping(&cur);
838 				continue;
839 			}
840 			do
841 				endaddr = advance_prpageheader_cur(&cur);
842 			while (endaddr != NULL &&
843 			    *(caddr_t)cur.pr_pdaddr == 0 &&
844 			    (((intptr_t)endaddr - (intptr_t)vicaddr) /
845 				1024) < excess);
846 			st_debug(STDL_HIGH, lcol, "endaddr %p, *cur %d\n",
847 			    endaddr, *(caddr_t)cur.pr_pdaddr);
848 
849 			/*
850 			 * Page out from vicaddr to the end of the mapping, or
851 			 * endaddr if set, then continue scanning after
852 			 * endaddr, or the next mapping, if not set.
853 			 */
854 			nvicaddr = endaddr;
855 			if (endaddr == NULL)
856 				endaddr = (caddr_t)cur.pr_addr +
857 				    cur.pr_pagesize * cur.pr_npage;
858 			if (pageout(vic->lpc_pid, scan_pr, vicaddr, endaddr) ==
859 			    0) {
860 				int64_t d_rss, att;
861 				int willignore = 0;
862 
863 				excess += (d_rss = rss_delta(
864 				    &new_psinfo, &old_psinfo, vic));
865 
866 				/*
867 				 * If this pageout attempt was unsuccessful
868 				 * (the resident portion was not affected), and
869 				 * was for the whole mapping, put it in the
870 				 * ignored set, so it will not be scanned again
871 				 * until some page is referenced or modified.
872 				 */
873 				if (d_rss >= 0 && (void *)cur.pr_addr ==
874 				    vicaddr && (cur.pr_pagesize * cur.pr_npage)
875 				    == ((uintptr_t)endaddr -
876 				    (uintptr_t)vicaddr)) {
877 					if (lmapping_insert(
878 					    &vic->lpc_ignore,
879 					    cur.pr_addr,
880 					    cur.pr_pagesize *
881 					    cur.pr_npage) != 0)
882 						debug("not enough memory to add"
883 						    " mapping at %p to ignored"
884 						    " set\n",
885 						    (void *)cur.pr_addr);
886 					willignore = 1;
887 				}
888 
889 				/*
890 				 * Update statistics.
891 				 */
892 				lcol->lcol_stat.lcols_pg_att += (att =
893 				    ((intptr_t)endaddr - (intptr_t)vicaddr) /
894 				    1024);
895 				st_debug(STDL_NORMAL, lcol, "paged out 0x%p"
896 				    "+0t(%llu/%llu)kB%s\n", vicaddr,
897 				    (unsigned long long)((d_rss <
898 				    0) ? - d_rss : 0), (unsigned long long)att,
899 				    willignore ? " (will ignore)" : "");
900 			} else {
901 				st_debug(STDL_NORMAL, lcol,
902 				    "process %d: exited/unscannable\n",
903 				    (int)vic->lpc_pid);
904 				vic->lpc_unscannable = 1;
905 				goto nextproc;
906 			}
907 
908 			/*
909 			 * Update the statistics file, if it's time.
910 			 */
911 			check_update_statistics();
912 
913 			vicaddr = (nvicaddr != NULL) ? nvicaddr : (void
914 			    *)advance_prpageheader_cur_nextmapping(&cur);
915 		}
916 		excess += rss_delta(&new_psinfo, &old_psinfo, vic);
917 		st_debug(STDL_NORMAL, lcol, "done, excess %lld\n",
918 		    (long long)excess);
919 nextproc:
920 		/*
921 		 * If a process was grabbed, release it, destroying its agent.
922 		 */
923 		if (scan_pr != NULL) {
924 			(void) Prelease(scan_pr, 0);
925 			scan_pr = NULL;
926 		}
927 		lcol->lcol_victim = vic;
928 		/*
929 		 * Scan the collection at most once.  Only if scanning was not
930 		 * aborted for any reason, and the end of lprocess has not been
931 		 * reached, determine the next victim and scan it.
932 		 */
933 		if (vic != NULL) {
934 			if (vic->lpc_next != NULL) {
935 				/*
936 				 * Determine the next process to be scanned.
937 				 */
938 				if (excess > 0) {
939 					vic = get_valid_victim(lcol,
940 					    vic->lpc_next);
941 					vicaddr = 0;
942 				}
943 			} else {
944 				/*
945 				 * A complete scan of the collection was made,
946 				 * so tick the scan counter and stop scanning
947 				 * until the next request.
948 				 */
949 				lcol->lcol_stat.lcols_scan_count++;
950 				lcol->lcol_stat.lcols_scan_time_complete
951 				    = lcol->lcol_stat.lcols_scan_time;
952 				/*
953 				 * If an excess still exists, tick the
954 				 * "ineffective scan" counter, signalling that
955 				 * the cap may be uneforceable.
956 				 */
957 				if (resumed == 0 && excess > 0)
958 					lcol->lcol_stat
959 					    .lcols_scan_ineffective++;
960 				/*
961 				 * Scanning should start at the beginning of
962 				 * the process list at the next request.
963 				 */
964 				if (excess > 0)
965 					vic = NULL;
966 			}
967 		}
968 	}
969 	lcol->lcol_stat.lcols_scan_time += (gethrtime() - scan_start);
970 	st_debug(STDL_HIGH, lcol, "done scanning; excess %lld\n",
971 	    (long long)excess);
972 
973 	lcol->lcol_resaddr = vicaddr;
974 	if (lcol->lcol_resaddr == NULL && lcol->lcol_victim != NULL) {
975 		lcol->lcol_victim = get_valid_victim(lcol,
976 		    lcol->lcol_victim->lpc_next);
977 	}
978 }
979 
980 /*
981  * Abort the scan in progress, and destroy the agent LWP of any grabbed
982  * processes.
983  */
984 void
985 scan_abort(void)
986 {
987 	if (scan_pr != NULL)
988 		(void) Prelease(scan_pr, NULL);
989 }
990 
991 static void
992 revoke_xmap(rfd_t *rfd)
993 {
994 	lprocess_t *lpc = rfd->rfd_data;
995 
996 	debug("revoking xmap for process %d\n", (int)lpc->lpc_pid);
997 	ASSERT(lpc->lpc_xmap_fd != -1);
998 	lpc->lpc_xmap_fd = -1;
999 }
1000 
1001 /*
1002  * Retrieve the process's current xmap , which is used to determine the size of
1003  * the resident portion of its segments.  Return zero if successful.
1004  */
1005 static int
1006 lpc_xmap_update(lprocess_t *lpc)
1007 {
1008 	int res;
1009 	struct stat st;
1010 
1011 	free(lpc->lpc_xmap);
1012 	lpc->lpc_xmap = NULL;
1013 	lpc->lpc_nxmap = -1;
1014 
1015 	if (lpc->lpc_xmap_fd == -1) {
1016 		char pathbuf[PROC_PATH_MAX];
1017 
1018 		(void) snprintf(pathbuf, sizeof (pathbuf), "/proc/%d/xmap",
1019 		    (int)lpc->lpc_pid);
1020 		if ((lpc->lpc_xmap_fd = rfd_open(pathbuf, 1, RFD_XMAP,
1021 		    revoke_xmap, lpc, O_RDONLY, 0)) < 0)
1022 			return (-1);
1023 	}
1024 
1025 redo:
1026 	errno = 0;
1027 	if (fstat(lpc->lpc_xmap_fd, &st) != 0) {
1028 		debug("cannot stat xmap\n");
1029 		(void) rfd_close(lpc->lpc_xmap_fd);
1030 		lpc->lpc_xmap_fd = -1;
1031 		return (-1);
1032 	}
1033 
1034 	if ((st.st_size % sizeof (*lpc->lpc_xmap)) != 0) {
1035 		debug("xmap wrong size\n");
1036 		(void) rfd_close(lpc->lpc_xmap_fd);
1037 		lpc->lpc_xmap_fd = -1;
1038 		return (-1);
1039 	}
1040 
1041 	lpc->lpc_xmap = malloc(st.st_size);
1042 	if (lpc->lpc_xmap == NULL) {
1043 		debug("cannot malloc() %ld bytes for xmap", st.st_size);
1044 		(void) rfd_close(lpc->lpc_xmap_fd);
1045 		lpc->lpc_xmap_fd = -1;
1046 		return (-1);
1047 	}
1048 
1049 	if ((res = pread(lpc->lpc_xmap_fd, lpc->lpc_xmap, st.st_size, 0)) !=
1050 	    st.st_size) {
1051 		free(lpc->lpc_xmap);
1052 		lpc->lpc_xmap = NULL;
1053 		if (res > 0) {
1054 			debug("xmap changed size, retrying\n");
1055 			goto redo;
1056 		} else {
1057 			debug("cannot read xmap");
1058 			return (-1);
1059 		}
1060 	}
1061 	lpc->lpc_nxmap = st.st_size / sizeof (*lpc->lpc_xmap);
1062 
1063 	return (0);
1064 }
1065