xref: /titanic_44/usr/src/uts/common/vm/vm_usage.c (revision 55434c770c89aa1b84474f2559a106803511aba0)
1 /*
2  * CDDL HEADER START
3  *
4  * The contents of this file are subject to the terms of the
5  * Common Development and Distribution License (the "License").
6  * You may not use this file except in compliance with the License.
7  *
8  * You can obtain a copy of the license at usr/src/OPENSOLARIS.LICENSE
9  * or http://www.opensolaris.org/os/licensing.
10  * See the License for the specific language governing permissions
11  * and limitations under the License.
12  *
13  * When distributing Covered Code, include this CDDL HEADER in each
14  * file and include the License file at usr/src/OPENSOLARIS.LICENSE.
15  * If applicable, add the following below this CDDL HEADER, with the
16  * fields enclosed by brackets "[]" replaced with your own identifying
17  * information: Portions Copyright [yyyy] [name of copyright owner]
18  *
19  * CDDL HEADER END
20  */
21 
22 /*
23  * Copyright 2006 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  * vm_usage
31  *
32  * This file implements the getvmusage() private system call.
33  * getvmusage() counts the amount of resident memory pages and swap
34  * reserved by the specified process collective. A "process collective" is
35  * the set of processes owned by a particular, zone, project, task, or user.
36  *
37  * rss and swap are counted so that for a given process collective, a page is
38  * only counted once.  For example, this means that if multiple processes in
39  * the same project map the same page, then the project will only be charged
40  * once for that page.  On the other hand, if two processes in different
41  * projects map the same page, then both projects will be charged
42  * for the page.
43  *
44  * The vm_getusage() calculation is implemented so that the first thread
45  * performs the rss/swap counting. Other callers will wait for that thread to
46  * finish, copying the results.  This enables multiple rcapds and prstats to
47  * consume data from the same calculation.  The results are also cached so that
48  * a caller interested in recent results can just copy them instead of starting
49  * a new calculation. The caller passes the maximium age (in seconds) of the
50  * data.  If the cached data is young enough, the cache is copied, otherwise,
51  * a new calculation is executed and the cache is replaced with the new
52  * data.
53  *
54  * The rss calculation for each process collective is as follows:
55  *
56  *   - Inspect flags, determine if counting rss for zones, projects, tasks,
57  *     and/or users.
58  *   - For each proc:
59  *	- Figure out proc's collectives (zone, project, task, and/or user).
60  *	- For each seg in proc's address space:
61  *		- If seg is private:
62  *			- Lookup anons in the amp.
63  *			- For incore pages not previously visited each of the
64  *			  proc's collectives, add incore pagesize to each.
65  *			  collective.
66  *			  Anon's with a refcnt of 1 can be assummed to be not
67  *			  previously visited.
68  *			- For address ranges without anons in the amp:
69  *				- Lookup pages in underlying vnode.
70  *				- For incore pages not previously visiting for
71  *				  each of the proc's collectives, add incore
72  *				  pagesize to each collective.
73  *		- If seg is shared:
74  *			- Lookup pages in the shared amp or vnode.
75  *			- For incore pages not previously visited for each of
76  *			  the proc's collectives, add incore pagesize to each
77  *			  collective.
78  *
79  * Swap is reserved by private segments, and shared anonymous segments.
80  * The only shared anon segments which do not reserve swap are ISM segments
81  * and schedctl segments, both of which can be identified by having
82  * amp->swresv == 0.
83  *
84  * The swap calculation for each collective is as follows:
85  *
86  *   - Inspect flags, determine if counting rss for zones, projects, tasks,
87  *     and/or users.
88  *   - For each proc:
89  *	- Figure out proc's collectives (zone, project, task, and/or user).
90  *	- For each seg in proc's address space:
91  *		- If seg is private:
92  *			- Add svd->swresv pages to swap count for each of the
93  *			  proc's collectives.
94  *		- If seg is anon, shared, and amp->swresv != 0
95  *			- For address ranges in amp not previously visited for
96  *			  each of the proc's collectives, add size of address
97  *			  range to the swap count for each collective.
98  *
99  * These two calculations are done simultaneously, with most of the work
100  * being done in vmu_calculate_seg().  The results of the calculation are
101  * copied into "vmu_data.vmu_cache_results".
102  *
103  * To perform the calculation, various things are tracked and cached:
104  *
105  *    - incore/not-incore page ranges for all vnodes.
106  *	(vmu_data.vmu_all_vnodes_hash)
107  *	This eliminates looking up the same page more than once.
108  *
109  *    - incore/not-incore page ranges for all shared amps.
110  *	(vmu_data.vmu_all_amps_hash)
111  *	This eliminates looking up the same page more than once.
112  *
113  *    - visited page ranges for each collective.
114  *	   - per vnode (entity->vme_vnode_hash)
115  *	   - per shared amp (entity->vme_amp_hash)
116  *	For accurate counting of map-shared and cow-shared pages.
117  *
118  *    - visited private anons (refcnt > 1) for each collective.
119  *	(entity->vme_anon_hash)
120  *	For accurate counting of cow-shared pages.
121  *
122  * The common accounting structure is the vmu_entity_t, which represents
123  * collectives:
124  *
125  *    - A zone.
126  *    - A project, task, or user within a zone.
127  *    - The entire system (vmu_data.vmu_system).
128  *    - Each collapsed (col) project and user.  This means a given projid or
129  *	uid, regardless of which zone the process is in.  For instance,
130  *      project 0 in the global zone and project 0 in a non global zone are
131  *	the same collapsed project.
132  *
133  *  Each entity structure tracks which pages have been already visited for
134  *  that entity (via previously inspected processes) so that these pages are
135  *  not double counted.
136  */
137 
138 #include <sys/errno.h>
139 #include <sys/types.h>
140 #include <sys/zone.h>
141 #include <sys/proc.h>
142 #include <sys/project.h>
143 #include <sys/task.h>
144 #include <sys/thread.h>
145 #include <sys/time.h>
146 #include <sys/mman.h>
147 #include <sys/modhash.h>
148 #include <sys/modhash_impl.h>
149 #include <sys/shm.h>
150 #include <sys/swap.h>
151 #include <sys/synch.h>
152 #include <sys/systm.h>
153 #include <sys/var.h>
154 #include <sys/vm_usage.h>
155 #include <sys/zone.h>
156 #include <vm/anon.h>
157 #include <vm/as.h>
158 #include <vm/seg_vn.h>
159 #include <vm/seg_spt.h>
160 
161 #define	VMUSAGE_HASH_SIZE		512
162 
163 #define	VMUSAGE_TYPE_VNODE		1
164 #define	VMUSAGE_TYPE_AMP		2
165 #define	VMUSAGE_TYPE_ANON		3
166 
167 #define	VMUSAGE_BOUND_UNKNOWN		0
168 #define	VMUSAGE_BOUND_INCORE		1
169 #define	VMUSAGE_BOUND_NOT_INCORE	2
170 
171 /*
172  * bounds for vnodes and shared amps
173  * Each bound is either entirely incore, entirely not in core, or
174  * entirely unknown.  bounds are stored in order by offset.
175  */
176 typedef struct vmu_bound {
177 	struct  vmu_bound *vmb_next;
178 	pgcnt_t vmb_start;  /* page offset in vnode/amp on which bound starts */
179 	pgcnt_t	vmb_end;    /* page offset in vnode/amp on which bound ends */
180 	char	vmb_type;   /* One of VMUSAGE_BOUND_* */
181 } vmu_bound_t;
182 
183 /*
184  * hash of visited objects (vnodes or shared amps)
185  * key is address of vnode or amp.  Bounds lists known incore/non-incore
186  * bounds for vnode/amp.
187  */
188 typedef struct vmu_object {
189 	struct vmu_object	*vmo_next;	/* free list */
190 	caddr_t		vmo_key;
191 	short		vmo_type;
192 	vmu_bound_t	*vmo_bounds;
193 } vmu_object_t;
194 
195 /*
196  * Entity by which to count results.
197  *
198  * The entity structure keeps the current rss/swap counts for each entity
199  * (zone, project, etc), and hashes of vm structures that have already
200  * been visited for the entity.
201  *
202  * vme_next:	links the list of all entities currently being counted by
203  *		vmu_calculate().
204  *
205  * vme_next_calc: links the list of entities related to the current process
206  *		 being counted by vmu_calculate_proc().
207  *
208  * vmu_calculate_proc() walks all processes.  For each process, it makes a
209  * list of the entities related to that process using vme_next_calc.  This
210  * list changes each time vmu_calculate_proc() is called.
211  *
212  */
213 typedef struct vmu_entity {
214 	struct vmu_entity *vme_next;
215 	struct vmu_entity *vme_next_calc;
216 	mod_hash_t	*vme_vnode_hash; /* vnodes visited for entity */
217 	mod_hash_t	*vme_amp_hash;	 /* shared amps visited for entity */
218 	mod_hash_t	*vme_anon_hash;	 /* cow anons visited for entity */
219 	vmusage_t	vme_result;	 /* identifies entity and results */
220 } vmu_entity_t;
221 
222 /*
223  * Hash of entities visited within a zone, and an entity for the zone
224  * itself.
225  */
226 typedef struct vmu_zone {
227 	struct vmu_zone	*vmz_next;	/* free list */
228 	id_t		vmz_id;
229 	vmu_entity_t	*vmz_zone;
230 	mod_hash_t	*vmz_projects_hash;
231 	mod_hash_t	*vmz_tasks_hash;
232 	mod_hash_t	*vmz_rusers_hash;
233 	mod_hash_t	*vmz_eusers_hash;
234 } vmu_zone_t;
235 
236 /*
237  * Cache of results from last calculation
238  */
239 typedef struct vmu_cache {
240 	vmusage_t	*vmc_results;	/* Results from last call to */
241 					/* vm_getusage(). */
242 	uint64_t	vmc_nresults;	/* Count of cached results */
243 	uint64_t	vmc_refcnt;	/* refcnt for free */
244 	uint_t		vmc_flags;	/* Flags for vm_getusage() */
245 	hrtime_t	vmc_timestamp;	/* when cache was created */
246 } vmu_cache_t;
247 
248 /*
249  * top level rss info for the system
250  */
251 typedef struct vmu_data {
252 	kmutex_t	vmu_lock;		/* Protects vmu_data */
253 	kcondvar_t	vmu_cv;			/* Used to signal threads */
254 						/* Waiting for */
255 						/* Rss_calc_thread to finish */
256 	vmu_entity_t	*vmu_system;		/* Entity for tracking */
257 						/* rss/swap for all processes */
258 						/* in all zones */
259 	mod_hash_t	*vmu_zones_hash;	/* Zones visited */
260 	mod_hash_t	*vmu_projects_col_hash; /* These *_col_hash hashes */
261 	mod_hash_t	*vmu_rusers_col_hash;	/* keep track of entities, */
262 	mod_hash_t	*vmu_eusers_col_hash;	/* ignoring zoneid, in order */
263 						/* to implement VMUSAGE_COL_* */
264 						/* flags, which aggregate by */
265 						/* project or user regardless */
266 						/* of zoneid. */
267 	mod_hash_t	*vmu_all_vnodes_hash;	/* System wide visited vnodes */
268 						/* to track incore/not-incore */
269 	mod_hash_t	*vmu_all_amps_hash;	/* System wide visited shared */
270 						/* amps to track incore/not- */
271 						/* incore */
272 	vmu_entity_t	*vmu_entities;		/* Linked list of entities */
273 	size_t		vmu_nentities;		/* Count of entities in list */
274 	vmu_cache_t	*vmu_cache;		/* Cached results */
275 	kthread_t	*vmu_calc_thread;	/* NULL, or thread running */
276 						/* vmu_calculate() */
277 	uint_t		vmu_calc_flags;		/* Flags being using by */
278 						/* currently running calc */
279 						/* thread */
280 	uint_t		vmu_pending_flags;	/* Flags of vm_getusage() */
281 						/* threads waiting for */
282 						/* calc thread to finish */
283 	uint_t		vmu_pending_waiters;	/* Number of threads waiting */
284 						/* for calc thread */
285 	vmu_bound_t	*vmu_free_bounds;
286 	vmu_object_t	*vmu_free_objects;
287 	vmu_entity_t	*vmu_free_entities;
288 	vmu_zone_t	*vmu_free_zones;
289 } vmu_data_t;
290 
291 extern struct as kas;
292 extern proc_t *practive;
293 extern zone_t *global_zone;
294 extern struct seg_ops segvn_ops;
295 extern struct seg_ops segspt_shmops;
296 
297 static vmu_data_t vmu_data;
298 static kmem_cache_t *vmu_bound_cache;
299 static kmem_cache_t *vmu_object_cache;
300 
301 /*
302  * Save a bound on the free list
303  */
304 static void
305 vmu_free_bound(vmu_bound_t *bound)
306 {
307 	bound->vmb_next = vmu_data.vmu_free_bounds;
308 	vmu_data.vmu_free_bounds = bound;
309 }
310 
311 /*
312  * Free an object, and all visited bound info.
313  */
314 static void
315 vmu_free_object(mod_hash_val_t val)
316 {
317 	vmu_object_t *obj = (vmu_object_t *)val;
318 	vmu_bound_t *bound = obj->vmo_bounds;
319 	vmu_bound_t *tmp;
320 
321 	while (bound != NULL) {
322 		tmp = bound;
323 		bound = bound->vmb_next;
324 		vmu_free_bound(tmp);
325 	}
326 	obj->vmo_next = vmu_data.vmu_free_objects;
327 	vmu_data.vmu_free_objects = obj;
328 }
329 
330 /*
331  * Free an entity, and hashes of visited objects for that entity.
332  */
333 static void
334 vmu_free_entity(mod_hash_val_t val)
335 {
336 	vmu_entity_t *entity = (vmu_entity_t *)val;
337 
338 	if (entity->vme_vnode_hash != NULL)
339 		i_mod_hash_clear_nosync(entity->vme_vnode_hash);
340 	if (entity->vme_amp_hash != NULL)
341 		i_mod_hash_clear_nosync(entity->vme_amp_hash);
342 	if (entity->vme_anon_hash != NULL)
343 		i_mod_hash_clear_nosync(entity->vme_anon_hash);
344 
345 	entity->vme_next = vmu_data.vmu_free_entities;
346 	vmu_data.vmu_free_entities = entity;
347 }
348 
349 /*
350  * Free zone entity, and all hashes of entities inside that zone,
351  * which are projects, tasks, and users.
352  */
353 static void
354 vmu_free_zone(mod_hash_val_t val)
355 {
356 	vmu_zone_t *zone = (vmu_zone_t *)val;
357 
358 	if (zone->vmz_zone != NULL) {
359 		vmu_free_entity((mod_hash_val_t)zone->vmz_zone);
360 		zone->vmz_zone = NULL;
361 	}
362 	if (zone->vmz_projects_hash != NULL)
363 		i_mod_hash_clear_nosync(zone->vmz_projects_hash);
364 	if (zone->vmz_tasks_hash != NULL)
365 		i_mod_hash_clear_nosync(zone->vmz_tasks_hash);
366 	if (zone->vmz_rusers_hash != NULL)
367 		i_mod_hash_clear_nosync(zone->vmz_rusers_hash);
368 	if (zone->vmz_eusers_hash != NULL)
369 		i_mod_hash_clear_nosync(zone->vmz_eusers_hash);
370 	zone->vmz_next = vmu_data.vmu_free_zones;
371 	vmu_data.vmu_free_zones = zone;
372 }
373 
374 /*
375  * Initialize synchronization primitives and hashes for system-wide tracking
376  * of visited vnodes and shared amps.  Initialize results cache.
377  */
378 void
379 vm_usage_init()
380 {
381 	mutex_init(&vmu_data.vmu_lock, NULL, MUTEX_DEFAULT, NULL);
382 	cv_init(&vmu_data.vmu_cv, NULL, CV_DEFAULT, NULL);
383 
384 	vmu_data.vmu_system = NULL;
385 	vmu_data.vmu_zones_hash = NULL;
386 	vmu_data.vmu_projects_col_hash = NULL;
387 	vmu_data.vmu_rusers_col_hash = NULL;
388 	vmu_data.vmu_eusers_col_hash = NULL;
389 
390 	vmu_data.vmu_free_bounds = NULL;
391 	vmu_data.vmu_free_objects = NULL;
392 	vmu_data.vmu_free_entities = NULL;
393 	vmu_data.vmu_free_zones = NULL;
394 
395 	vmu_data.vmu_all_vnodes_hash = mod_hash_create_ptrhash(
396 	    "vmusage vnode hash", VMUSAGE_HASH_SIZE, vmu_free_object,
397 	    sizeof (vnode_t));
398 	vmu_data.vmu_all_amps_hash = mod_hash_create_ptrhash(
399 	    "vmusage amp hash", VMUSAGE_HASH_SIZE, vmu_free_object,
400 	    sizeof (struct anon_map));
401 	vmu_data.vmu_projects_col_hash = mod_hash_create_idhash(
402 	    "vmusage collapsed project hash", VMUSAGE_HASH_SIZE,
403 	    vmu_free_entity);
404 	vmu_data.vmu_rusers_col_hash = mod_hash_create_idhash(
405 	    "vmusage collapsed ruser hash", VMUSAGE_HASH_SIZE,
406 	    vmu_free_entity);
407 	vmu_data.vmu_eusers_col_hash = mod_hash_create_idhash(
408 	    "vmusage collpased euser hash", VMUSAGE_HASH_SIZE,
409 	    vmu_free_entity);
410 	vmu_data.vmu_zones_hash = mod_hash_create_idhash(
411 	    "vmusage zone hash", VMUSAGE_HASH_SIZE, vmu_free_zone);
412 
413 	vmu_bound_cache = kmem_cache_create("vmu_bound_cache",
414 	    sizeof (vmu_bound_t), 0, NULL, NULL, NULL, NULL, NULL, 0);
415 	vmu_object_cache = kmem_cache_create("vmu_object_cache",
416 	    sizeof (vmu_object_t), 0, NULL, NULL, NULL, NULL, NULL, 0);
417 
418 	vmu_data.vmu_entities = NULL;
419 	vmu_data.vmu_nentities = 0;
420 
421 	vmu_data.vmu_cache = NULL;
422 	vmu_data.vmu_calc_thread = NULL;
423 	vmu_data.vmu_calc_flags = 0;
424 	vmu_data.vmu_pending_flags = 0;
425 	vmu_data.vmu_pending_waiters = 0;
426 }
427 
428 /*
429  * Allocate hashes for tracking vm objects visited for an entity.
430  * Update list of entities.
431  */
432 static vmu_entity_t *
433 vmu_alloc_entity(id_t id, int type, id_t zoneid)
434 {
435 	vmu_entity_t *entity;
436 
437 	if (vmu_data.vmu_free_entities != NULL) {
438 		entity = vmu_data.vmu_free_entities;
439 		vmu_data.vmu_free_entities =
440 		    vmu_data.vmu_free_entities->vme_next;
441 		bzero(&entity->vme_result, sizeof (vmusage_t));
442 	} else {
443 		entity = kmem_zalloc(sizeof (vmu_entity_t), KM_SLEEP);
444 	}
445 	entity->vme_result.vmu_id = id;
446 	entity->vme_result.vmu_zoneid = zoneid;
447 	entity->vme_result.vmu_type = type;
448 
449 	if (entity->vme_vnode_hash == NULL)
450 		entity->vme_vnode_hash = mod_hash_create_ptrhash(
451 		    "vmusage vnode hash", VMUSAGE_HASH_SIZE, vmu_free_object,
452 		    sizeof (vnode_t));
453 
454 	if (entity->vme_amp_hash == NULL)
455 		entity->vme_amp_hash = mod_hash_create_ptrhash(
456 		    "vmusage amp hash", VMUSAGE_HASH_SIZE, vmu_free_object,
457 		    sizeof (struct anon_map));
458 
459 	if (entity->vme_anon_hash == NULL)
460 		entity->vme_anon_hash = mod_hash_create_ptrhash(
461 		    "vmusage anon hash", VMUSAGE_HASH_SIZE,
462 		    mod_hash_null_valdtor, sizeof (struct anon));
463 
464 	entity->vme_next = vmu_data.vmu_entities;
465 	vmu_data.vmu_entities = entity;
466 	vmu_data.vmu_nentities++;
467 
468 	return (entity);
469 }
470 
471 /*
472  * Allocate a zone entity, and hashes for tracking visited vm objects
473  * for projects, tasks, and users within that zone.
474  */
475 static vmu_zone_t *
476 vmu_alloc_zone(id_t id)
477 {
478 	vmu_zone_t *zone;
479 
480 	if (vmu_data.vmu_free_zones != NULL) {
481 		zone = vmu_data.vmu_free_zones;
482 		vmu_data.vmu_free_zones =
483 		    vmu_data.vmu_free_zones->vmz_next;
484 		zone->vmz_next = NULL;
485 		zone->vmz_zone = NULL;
486 	} else {
487 		zone = kmem_zalloc(sizeof (vmu_zone_t), KM_SLEEP);
488 	}
489 
490 	zone->vmz_id = id;
491 
492 	if ((vmu_data.vmu_calc_flags & (VMUSAGE_ZONE | VMUSAGE_ALL_ZONES)) != 0)
493 		zone->vmz_zone = vmu_alloc_entity(id, VMUSAGE_ZONE, id);
494 
495 	if ((vmu_data.vmu_calc_flags & (VMUSAGE_PROJECTS |
496 	    VMUSAGE_ALL_PROJECTS)) != 0 && zone->vmz_projects_hash == NULL)
497 		zone->vmz_projects_hash = mod_hash_create_idhash(
498 		    "vmusage project hash", VMUSAGE_HASH_SIZE, vmu_free_entity);
499 
500 	if ((vmu_data.vmu_calc_flags & (VMUSAGE_TASKS | VMUSAGE_ALL_TASKS))
501 	    != 0 && zone->vmz_tasks_hash == NULL)
502 		zone->vmz_tasks_hash = mod_hash_create_idhash(
503 		    "vmusage task hash", VMUSAGE_HASH_SIZE, vmu_free_entity);
504 
505 	if ((vmu_data.vmu_calc_flags & (VMUSAGE_RUSERS | VMUSAGE_ALL_RUSERS))
506 	    != 0 && zone->vmz_rusers_hash == NULL)
507 		zone->vmz_rusers_hash = mod_hash_create_idhash(
508 		    "vmusage ruser hash", VMUSAGE_HASH_SIZE, vmu_free_entity);
509 
510 	if ((vmu_data.vmu_calc_flags & (VMUSAGE_EUSERS | VMUSAGE_ALL_EUSERS))
511 	    != 0 && zone->vmz_eusers_hash == NULL)
512 		zone->vmz_eusers_hash = mod_hash_create_idhash(
513 		    "vmusage euser hash", VMUSAGE_HASH_SIZE, vmu_free_entity);
514 
515 	return (zone);
516 }
517 
518 /*
519  * Allocate a structure for tracking visited bounds for a vm object.
520  */
521 static vmu_object_t *
522 vmu_alloc_object(caddr_t key, int type)
523 {
524 	vmu_object_t *object;
525 
526 	if (vmu_data.vmu_free_objects != NULL) {
527 		object = vmu_data.vmu_free_objects;
528 		vmu_data.vmu_free_objects =
529 		    vmu_data.vmu_free_objects->vmo_next;
530 	} else {
531 		object = kmem_cache_alloc(vmu_object_cache, KM_SLEEP);
532 	}
533 
534 	object->vmo_key = key;
535 	object->vmo_type = type;
536 	object->vmo_bounds = NULL;
537 
538 	return (object);
539 }
540 
541 /*
542  * Allocate and return a bound structure.
543  */
544 static vmu_bound_t *
545 vmu_alloc_bound()
546 {
547 	vmu_bound_t *bound;
548 
549 	if (vmu_data.vmu_free_bounds != NULL) {
550 		bound = vmu_data.vmu_free_bounds;
551 		vmu_data.vmu_free_bounds =
552 		    vmu_data.vmu_free_bounds->vmb_next;
553 		bzero(bound, sizeof (vmu_bound_t));
554 	} else {
555 		bound = kmem_cache_alloc(vmu_bound_cache, KM_SLEEP);
556 		bzero(bound, sizeof (vmu_bound_t));
557 	}
558 	return (bound);
559 }
560 
561 /*
562  * vmu_find_insert_* functions implement hash lookup or allocate and
563  * insert operations.
564  */
565 static vmu_object_t *
566 vmu_find_insert_object(mod_hash_t *hash, caddr_t key, uint_t type)
567 {
568 	int ret;
569 	vmu_object_t *object;
570 
571 	ret = i_mod_hash_find_nosync(hash, (mod_hash_key_t)key,
572 	    (mod_hash_val_t *)&object);
573 	if (ret != 0) {
574 		object = vmu_alloc_object(key, type);
575 		ret = i_mod_hash_insert_nosync(hash, (mod_hash_key_t)key,
576 		    (mod_hash_val_t)object, (mod_hash_hndl_t)0);
577 		ASSERT(ret == 0);
578 	}
579 	return (object);
580 }
581 
582 static int
583 vmu_find_insert_anon(mod_hash_t *hash, caddr_t key)
584 {
585 	int ret;
586 	caddr_t val;
587 
588 	ret = i_mod_hash_find_nosync(hash, (mod_hash_key_t)key,
589 	    (mod_hash_val_t *)&val);
590 
591 	if (ret == 0)
592 		return (0);
593 
594 	ret = i_mod_hash_insert_nosync(hash, (mod_hash_key_t)key,
595 	    (mod_hash_val_t)key, (mod_hash_hndl_t)0);
596 
597 	ASSERT(ret == 0);
598 
599 	return (1);
600 }
601 
602 static vmu_entity_t *
603 vmu_find_insert_entity(mod_hash_t *hash, id_t id, uint_t type, id_t zoneid)
604 {
605 	int ret;
606 	vmu_entity_t *entity;
607 
608 	ret = i_mod_hash_find_nosync(hash, (mod_hash_key_t)(uintptr_t)id,
609 	    (mod_hash_val_t *)&entity);
610 	if (ret != 0) {
611 		entity = vmu_alloc_entity(id, type, zoneid);
612 		ret = i_mod_hash_insert_nosync(hash,
613 		    (mod_hash_key_t)(uintptr_t)id, (mod_hash_val_t)entity,
614 		    (mod_hash_hndl_t)0);
615 		ASSERT(ret == 0);
616 	}
617 	return (entity);
618 }
619 
620 
621 
622 
623 /*
624  * Returns list of object bounds between start and end.  New bounds inserted
625  * by this call are given type.
626  *
627  * Returns the number of pages covered if new bounds are created.  Returns 0
628  * if region between start/end consists of all existing bounds.
629  */
630 static pgcnt_t
631 vmu_insert_lookup_object_bounds(vmu_object_t *ro, pgcnt_t start, pgcnt_t
632     end, char type, vmu_bound_t **first, vmu_bound_t **last)
633 {
634 	vmu_bound_t *next;
635 	vmu_bound_t *prev = NULL;
636 	vmu_bound_t *tmp = NULL;
637 	pgcnt_t ret = 0;
638 
639 	*first = *last = NULL;
640 
641 	for (next = ro->vmo_bounds; next != NULL; next = next->vmb_next) {
642 		/*
643 		 * Find bounds overlapping or overlapped by range [start,end].
644 		 */
645 		if (start > next->vmb_end) {
646 			/* bound is before new bound */
647 			prev = next;
648 			continue;
649 		}
650 		if (next->vmb_start > end) {
651 			/* bound is after new bound */
652 			break;
653 		}
654 		if (*first == NULL)
655 			*first = next;
656 		*last = next;
657 	}
658 
659 	if (*first == NULL) {
660 		ASSERT(*last == NULL);
661 		/*
662 		 * No bounds overlapping range [start,end], so create new
663 		 * bound
664 		 */
665 		tmp = vmu_alloc_bound();
666 		tmp->vmb_start = start;
667 		tmp->vmb_end = end;
668 		tmp->vmb_type = type;
669 		if (prev == NULL) {
670 			tmp->vmb_next = ro->vmo_bounds;
671 			ro->vmo_bounds = tmp;
672 		} else {
673 			tmp->vmb_next = prev->vmb_next;
674 			prev->vmb_next = tmp;
675 		}
676 		*first = tmp;
677 		*last = tmp;
678 		ASSERT(tmp->vmb_end >= tmp->vmb_start);
679 		ret = tmp->vmb_end - tmp->vmb_start + 1;
680 		return (ret);
681 	}
682 
683 	/* Check to see if start is before first known bound */
684 	ASSERT(first != NULL && last != NULL);
685 	next = (*first);
686 	if (start < (*first)->vmb_start) {
687 		/* Create new bound before first bound */
688 		tmp = vmu_alloc_bound();
689 		tmp->vmb_start = start;
690 		tmp->vmb_end = (*first)->vmb_start - 1;
691 		tmp->vmb_type = type;
692 		tmp->vmb_next = *first;
693 		if (*first == ro->vmo_bounds)
694 			ro->vmo_bounds = tmp;
695 		if (prev != NULL)
696 			prev->vmb_next = tmp;
697 		ASSERT(tmp->vmb_end >= tmp->vmb_start);
698 		ret += tmp->vmb_end - tmp->vmb_start + 1;
699 		*first = tmp;
700 	}
701 	/*
702 	 * Between start and end, search for gaps between and after existing
703 	 * bounds.  Create new bounds to fill gaps if they exist.
704 	 */
705 	while (end > next->vmb_end) {
706 		/*
707 		 * Check for gap between bound and next bound. if no gap,
708 		 * continue.
709 		 */
710 		if ((next != *last) &&
711 		    ((next->vmb_end + 1) == next->vmb_next->vmb_start)) {
712 			next = next->vmb_next;
713 			continue;
714 		}
715 		/*
716 		 * Insert new bound in gap after bound, and before next
717 		 * bound if next bound exists.
718 		 */
719 		tmp = vmu_alloc_bound();
720 		tmp->vmb_type = type;
721 		tmp->vmb_next = next->vmb_next;
722 		tmp->vmb_start = next->vmb_end + 1;
723 
724 		if (next != *last) {
725 			tmp->vmb_end = next->vmb_next->vmb_start - 1;
726 			ASSERT(tmp->vmb_end >= tmp->vmb_start);
727 			ret += tmp->vmb_end - tmp->vmb_start + 1;
728 			next->vmb_next = tmp;
729 			next = tmp->vmb_next;
730 		} else {
731 			tmp->vmb_end = end;
732 			ASSERT(tmp->vmb_end >= tmp->vmb_start);
733 			ret += tmp->vmb_end - tmp->vmb_start + 1;
734 			next->vmb_next = tmp;
735 			*last = tmp;
736 			break;
737 		}
738 	}
739 	return (ret);
740 }
741 
742 /*
743  * vmu_update_bounds()
744  *
745  * first, last:	list of continuous bounds, of which zero or more are of
746  * 		type VMUSAGE_BOUND_UNKNOWN.
747  *
748  * new_first, new_last:	list of continuous bounds, of which none are of
749  *			type VMUSAGE_BOUND_UNKNOWN.  These bounds are used to
750  *			update the types of bounds in (first,last) with
751  *			type VMUSAGE_BOUND_UNKNOWN.
752  *
753  * For the list of bounds (first,last), this function updates any bounds
754  * with type VMUSAGE_BOUND_UNKNOWN using the type of the corresponding bound in
755  * the list (new_first, new_last).
756  *
757  * If a bound of type VMUSAGE_BOUND_UNKNOWN spans multiple bounds in the list
758  * (new_first, new_last), it will be split into multiple bounds.
759  *
760  * Return value:
761  * 	The number of pages in the list of bounds (first,last) that were of
762  *	type VMUSAGE_BOUND_UNKNOWN, which have been updated to be of type
763  *	VMUSAGE_BOUND_INCORE.
764  *
765  */
766 static pgcnt_t
767 vmu_update_bounds(vmu_bound_t **first, vmu_bound_t **last,
768     vmu_bound_t *new_first, vmu_bound_t *new_last)
769 {
770 	vmu_bound_t *next, *new_next, *tmp;
771 	pgcnt_t rss = 0;
772 
773 	next = *first;
774 	new_next = new_first;
775 
776 	/* verify bounds span same pages */
777 	ASSERT((*first)->vmb_start >= new_next->vmb_start);
778 	ASSERT((*last)->vmb_end <= new_last->vmb_end);
779 	for (;;) {
780 		/* If bound already has type, proceed to next bound */
781 		if (next->vmb_type != VMUSAGE_BOUND_UNKNOWN) {
782 			if (next == *last)
783 				break;
784 			next = next->vmb_next;
785 			continue;
786 		}
787 		while (new_next->vmb_end < next->vmb_start)
788 			new_next = new_next->vmb_next;
789 		ASSERT(new_next->vmb_type != VMUSAGE_BOUND_UNKNOWN);
790 		next->vmb_type = new_next->vmb_type;
791 		if (new_next->vmb_end < next->vmb_end) {
792 			/* need to split bound */
793 			tmp = vmu_alloc_bound();
794 			tmp->vmb_type = VMUSAGE_BOUND_UNKNOWN;
795 			tmp->vmb_start = new_next->vmb_end + 1;
796 			tmp->vmb_end = next->vmb_end;
797 			tmp->vmb_next = next->vmb_next;
798 			next->vmb_end = new_next->vmb_end;
799 			next->vmb_next = tmp;
800 			if (*last == next)
801 				*last = tmp;
802 			if (next->vmb_type == VMUSAGE_BOUND_INCORE)
803 				rss += next->vmb_end - next->vmb_start + 1;
804 			next = tmp;
805 		} else {
806 			if (next->vmb_type == VMUSAGE_BOUND_INCORE)
807 				rss += next->vmb_end - next->vmb_start + 1;
808 			if (next == *last)
809 				break;
810 			next = next->vmb_next;
811 		}
812 	}
813 	return (rss);
814 }
815 
816 /*
817  * merges adjacent bounds with same type between first and last bound.
818  * After merge, last pointer is no longer valid, as last bound may be
819  * merged away.
820  */
821 static void
822 vmu_merge_bounds(vmu_bound_t **first, vmu_bound_t **last)
823 {
824 	vmu_bound_t *next;
825 	vmu_bound_t *tmp;
826 
827 	ASSERT(*first != NULL);
828 	ASSERT(*last != NULL);
829 
830 	next = *first;
831 	while (next != *last) {
832 
833 		/* If bounds are adjacent and have same type, merge them */
834 		if (((next->vmb_end + 1) == next->vmb_next->vmb_start) &&
835 		    (next->vmb_type == next->vmb_next->vmb_type)) {
836 			tmp = next->vmb_next;
837 			next->vmb_end = tmp->vmb_end;
838 			next->vmb_next = tmp->vmb_next;
839 			vmu_free_bound(tmp);
840 			if (tmp == *last)
841 				*last = next;
842 		} else {
843 			next = next->vmb_next;
844 		}
845 	}
846 }
847 
848 /*
849  * Given an amp and a list of bounds, updates each bound's type with
850  * VMUSAGE_BOUND_INCORE or VMUSAGE_BOUND_NOT_INCORE.
851  *
852  * If a bound is partially incore, it will be split into two bounds.
853  * first and last may be modified, as bounds may be split into multiple
854  * bounds if the are partially incore/not-incore.
855  *
856  * Set incore to non-zero if bounds are already known to be incore
857  *
858  */
859 static void
860 vmu_amp_update_incore_bounds(struct anon_map *amp, vmu_bound_t **first,
861     vmu_bound_t **last, boolean_t incore)
862 {
863 	vmu_bound_t *next;
864 	vmu_bound_t *tmp;
865 	pgcnt_t index;
866 	short bound_type;
867 	short page_type;
868 	vnode_t *vn;
869 	anoff_t off;
870 	struct anon *ap;
871 
872 	next = *first;
873 	/* Shared anon slots don't change once set */
874 	ANON_LOCK_ENTER(&amp->a_rwlock, RW_READER);
875 	for (;;) {
876 		if (incore == B_TRUE)
877 			next->vmb_type = VMUSAGE_BOUND_INCORE;
878 
879 		if (next->vmb_type != VMUSAGE_BOUND_UNKNOWN) {
880 			if (next == *last)
881 				break;
882 			next = next->vmb_next;
883 			continue;
884 		}
885 		bound_type = next->vmb_type;
886 		index = next->vmb_start;
887 		while (index <= next->vmb_end) {
888 
889 			/*
890 			 * These are used to determine how much to increment
891 			 * index when a large page is found.
892 			 */
893 			page_t *page;
894 			pgcnt_t pgcnt = 1;
895 			uint_t pgshft;
896 			pgcnt_t pgmsk;
897 
898 			ap = anon_get_ptr(amp->ahp, index);
899 			if (ap != NULL)
900 				swap_xlate(ap, &vn, &off);
901 
902 			if (ap != NULL && vn != NULL && vn->v_pages != NULL &&
903 			    (page = page_exists(vn, off)) != NULL) {
904 				page_type = VMUSAGE_BOUND_INCORE;
905 				if (page->p_szc > 0) {
906 					pgcnt = page_get_pagecnt(page->p_szc);
907 					pgshft = page_get_shift(page->p_szc);
908 					pgmsk = (0x1 << (pgshft - PAGESHIFT))
909 					    - 1;
910 				}
911 			} else {
912 				page_type = VMUSAGE_BOUND_NOT_INCORE;
913 			}
914 			if (bound_type == VMUSAGE_BOUND_UNKNOWN) {
915 				next->vmb_type = page_type;
916 			} else if (next->vmb_type != page_type) {
917 				/*
918 				 * if current bound type does not match page
919 				 * type, need to split off new bound.
920 				 */
921 				tmp = vmu_alloc_bound();
922 				tmp->vmb_type = page_type;
923 				tmp->vmb_start = index;
924 				tmp->vmb_end = next->vmb_end;
925 				tmp->vmb_next = next->vmb_next;
926 				next->vmb_end = index - 1;
927 				next->vmb_next = tmp;
928 				if (*last == next)
929 					*last = tmp;
930 				next = tmp;
931 			}
932 			if (pgcnt > 1) {
933 				/*
934 				 * If inside large page, jump to next large
935 				 * page
936 				 */
937 				index = (index & ~pgmsk) + pgcnt;
938 			} else {
939 				index++;
940 			}
941 		}
942 		if (next == *last) {
943 			ASSERT(next->vmb_type != VMUSAGE_BOUND_UNKNOWN);
944 			break;
945 		} else
946 			next = next->vmb_next;
947 	}
948 	ANON_LOCK_EXIT(&amp->a_rwlock);
949 }
950 
951 /*
952  * Same as vmu_amp_update_incore_bounds(), except for tracking
953  * incore-/not-incore for vnodes.
954  */
955 static void
956 vmu_vnode_update_incore_bounds(vnode_t *vnode, vmu_bound_t **first,
957     vmu_bound_t **last)
958 {
959 	vmu_bound_t *next;
960 	vmu_bound_t *tmp;
961 	pgcnt_t index;
962 	short bound_type;
963 	short page_type;
964 
965 	next = *first;
966 	for (;;) {
967 		if (vnode->v_pages == NULL)
968 			next->vmb_type = VMUSAGE_BOUND_NOT_INCORE;
969 
970 		if (next->vmb_type != VMUSAGE_BOUND_UNKNOWN) {
971 			if (next == *last)
972 				break;
973 			next = next->vmb_next;
974 			continue;
975 		}
976 
977 		bound_type = next->vmb_type;
978 		index = next->vmb_start;
979 		while (index <= next->vmb_end) {
980 
981 			/*
982 			 * These are used to determine how much to increment
983 			 * index when a large page is found.
984 			 */
985 			page_t *page;
986 			pgcnt_t pgcnt = 1;
987 			uint_t pgshft;
988 			pgcnt_t pgmsk;
989 
990 			if (vnode->v_pages != NULL &&
991 			    (page = page_exists(vnode, ptob(index))) != NULL) {
992 				page_type = VMUSAGE_BOUND_INCORE;
993 				if (page->p_szc > 0) {
994 					pgcnt = page_get_pagecnt(page->p_szc);
995 					pgshft = page_get_shift(page->p_szc);
996 					pgmsk = (0x1 << (pgshft - PAGESHIFT))
997 					    - 1;
998 				}
999 			} else {
1000 				page_type = VMUSAGE_BOUND_NOT_INCORE;
1001 			}
1002 			if (bound_type == VMUSAGE_BOUND_UNKNOWN) {
1003 				next->vmb_type = page_type;
1004 			} else if (next->vmb_type != page_type) {
1005 				/*
1006 				 * if current bound type does not match page
1007 				 * type, need to split off new bound.
1008 				 */
1009 				tmp = vmu_alloc_bound();
1010 				tmp->vmb_type = page_type;
1011 				tmp->vmb_start = index;
1012 				tmp->vmb_end = next->vmb_end;
1013 				tmp->vmb_next = next->vmb_next;
1014 				next->vmb_end = index - 1;
1015 				next->vmb_next = tmp;
1016 				if (*last == next)
1017 					*last = tmp;
1018 				next = tmp;
1019 			}
1020 			if (pgcnt > 1) {
1021 				/*
1022 				 * If inside large page, jump to next large
1023 				 * page
1024 				 */
1025 				index = (index & ~pgmsk) + pgcnt;
1026 			} else {
1027 				index++;
1028 			}
1029 		}
1030 		if (next == *last) {
1031 			ASSERT(next->vmb_type != VMUSAGE_BOUND_UNKNOWN);
1032 			break;
1033 		} else
1034 			next = next->vmb_next;
1035 	}
1036 }
1037 
1038 /*
1039  * Calculate the rss and swap consumed by a segment.  vmu_entities is the
1040  * list of entities to visit.  For shared segments, the vnode or amp
1041  * is looked up in each entity to see if has been already counted.  Private
1042  * anon pages are checked per entity to ensure that cow pages are not
1043  * double counted.
1044  *
1045  * For private mapped files, first the amp is checked for private pages.
1046  * Bounds not backed by the amp are looked up in the vnode for each entity
1047  * to avoid double counting of private COW vnode pages.
1048  */
1049 static void
1050 vmu_calculate_seg(vmu_entity_t *vmu_entities, struct seg *seg)
1051 {
1052 	struct segvn_data *svd;
1053 	struct shm_data *shmd;
1054 	struct spt_data *sptd;
1055 	vmu_object_t *shared_object = NULL;
1056 	vmu_object_t *entity_object = NULL;
1057 	vmu_entity_t *entity;
1058 	vmusage_t *result;
1059 	vmu_bound_t *first = NULL;
1060 	vmu_bound_t *last = NULL;
1061 	vmu_bound_t *cur = NULL;
1062 	vmu_bound_t *e_first = NULL;
1063 	vmu_bound_t *e_last = NULL;
1064 	vmu_bound_t *tmp;
1065 	pgcnt_t p_index, s_index, p_start, p_end, s_start, s_end, rss, virt;
1066 	struct anon_map *private_amp = NULL;
1067 	boolean_t incore = B_FALSE;
1068 	boolean_t shared = B_FALSE;
1069 	int file = 0;
1070 	pgcnt_t swresv = 0;
1071 	pgcnt_t panon = 0;
1072 
1073 	/* Can zero-length segments exist?  Not sure, so parenoia */
1074 	if (seg->s_size <= 0)
1075 		return;
1076 
1077 	/*
1078 	 * Figure out if there is a shared object (such as a named vnode or
1079 	 * a shared amp, then figure out if there is a private amp, which
1080 	 * identifies private pages.
1081 	 */
1082 	if (seg->s_ops == &segvn_ops) {
1083 		svd = (struct segvn_data *)seg->s_data;
1084 		if (svd->type == MAP_SHARED)
1085 			shared = B_TRUE;
1086 		else
1087 			swresv = svd->swresv;
1088 
1089 		if (svd->vp != NULL) {
1090 			file = 1;
1091 			shared_object = vmu_find_insert_object(
1092 			    vmu_data.vmu_all_vnodes_hash, (caddr_t)svd->vp,
1093 			    VMUSAGE_TYPE_VNODE);
1094 			s_start = btop(svd->offset);
1095 			s_end = btop(svd->offset + seg->s_size) - 1;
1096 		}
1097 		if (svd->amp != NULL && svd->type == MAP_SHARED) {
1098 			ASSERT(shared_object == NULL);
1099 			shared_object = vmu_find_insert_object(
1100 			    vmu_data.vmu_all_amps_hash, (caddr_t)svd->amp,
1101 			    VMUSAGE_TYPE_AMP);
1102 			s_start = svd->anon_index;
1103 			s_end = svd->anon_index + btop(seg->s_size) - 1;
1104 			/* schedctl mappings are always in core */
1105 			if (svd->amp->swresv == 0)
1106 				incore = B_TRUE;
1107 		}
1108 		if (svd->amp != NULL && svd->type == MAP_PRIVATE) {
1109 			private_amp = svd->amp;
1110 			p_start = svd->anon_index;
1111 			p_end = svd->anon_index + btop(seg->s_size) - 1;
1112 		}
1113 	} else if (seg->s_ops == &segspt_shmops) {
1114 		shared = B_TRUE;
1115 		shmd = (struct shm_data *)seg->s_data;
1116 		shared_object = vmu_find_insert_object(
1117 		    vmu_data.vmu_all_amps_hash, (caddr_t)shmd->shm_amp,
1118 		    VMUSAGE_TYPE_AMP);
1119 		s_start = 0;
1120 		s_end = btop(seg->s_size) - 1;
1121 		sptd = shmd->shm_sptseg->s_data;
1122 
1123 		/* ism segments are always incore and do not reserve swap */
1124 		if (sptd->spt_flags & SHM_SHARE_MMU)
1125 			incore = B_TRUE;
1126 
1127 	} else {
1128 		return;
1129 	}
1130 
1131 	/*
1132 	 * If there is a private amp, count anon pages that exist.  If an
1133 	 * anon has a refcnt > 1 (cow sharing), then save the anon in a
1134 	 * hash so that it is not double counted.
1135 	 *
1136 	 * If there is also a shared object, they figure out the bounds
1137 	 * which are not mapped by the private amp.
1138 	 */
1139 	if (private_amp != NULL) {
1140 
1141 		/* Enter as writer to prevent cow anons from being freed */
1142 		ANON_LOCK_ENTER(&private_amp->a_rwlock, RW_WRITER);
1143 
1144 		p_index = p_start;
1145 		s_index = s_start;
1146 
1147 		while (p_index <= p_end) {
1148 
1149 			pgcnt_t p_index_next;
1150 			pgcnt_t p_bound_size;
1151 			int cnt;
1152 			anoff_t off;
1153 			struct vnode *vn;
1154 			struct anon *ap;
1155 			page_t *page;		/* For handling of large */
1156 			pgcnt_t pgcnt = 1;	/* pages */
1157 			pgcnt_t pgstart;
1158 			pgcnt_t pgend;
1159 			uint_t pgshft;
1160 			pgcnt_t pgmsk;
1161 
1162 			p_index_next = p_index;
1163 			ap = anon_get_next_ptr(private_amp->ahp,
1164 			    &p_index_next);
1165 
1166 			/*
1167 			 * If next anon is past end of mapping, simulate
1168 			 * end of anon so loop terminates.
1169 			 */
1170 			if (p_index_next > p_end) {
1171 				p_index_next = p_end + 1;
1172 				ap = NULL;
1173 			}
1174 			/*
1175 			 * For cow segments, keep track of bounds not
1176 			 * backed by private amp so they can be looked
1177 			 * up in the backing vnode
1178 			 */
1179 			if (p_index_next != p_index) {
1180 
1181 				/*
1182 				 * Compute index difference between anon and
1183 				 * previous anon.
1184 				 */
1185 				p_bound_size = p_index_next - p_index - 1;
1186 
1187 				if (shared_object != NULL) {
1188 					cur = vmu_alloc_bound();
1189 					cur->vmb_next = NULL;
1190 					cur->vmb_start = s_index;
1191 					cur->vmb_end = s_index + p_bound_size;
1192 					cur->vmb_type = VMUSAGE_BOUND_UNKNOWN;
1193 					if (first == NULL) {
1194 						first = cur;
1195 						last = cur;
1196 					} else {
1197 						last->vmb_next = cur;
1198 						last = cur;
1199 					}
1200 				}
1201 				p_index = p_index + p_bound_size + 1;
1202 				s_index = s_index + p_bound_size + 1;
1203 			}
1204 
1205 			/* Detect end of anons in amp */
1206 			if (ap == NULL)
1207 				break;
1208 
1209 			cnt = ap->an_refcnt;
1210 			swap_xlate(ap, &vn, &off);
1211 
1212 			if (vn == NULL || vn->v_pages == NULL ||
1213 			    (page = page_exists(vn, off)) == NULL) {
1214 				p_index++;
1215 				s_index++;
1216 				continue;
1217 			}
1218 
1219 			/*
1220 			 * If large page is found, compute portion of large
1221 			 * page in mapping, and increment indicies to the next
1222 			 * large page.
1223 			 */
1224 			if (page->p_szc > 0) {
1225 
1226 				pgcnt = page_get_pagecnt(page->p_szc);
1227 				pgshft = page_get_shift(page->p_szc);
1228 				pgmsk = (0x1 << (pgshft - PAGESHIFT)) - 1;
1229 
1230 				/* First page in large page */
1231 				pgstart = p_index & ~pgmsk;
1232 				/* Last page in large page */
1233 				pgend = pgstart + pgcnt - 1;
1234 				/*
1235 				 * Artifically end page if page extends past
1236 				 * end of mapping.
1237 				 */
1238 				if (pgend > p_end)
1239 					pgend = p_end;
1240 
1241 				/*
1242 				 * Compute number of pages from large page
1243 				 * which are mapped.
1244 				 */
1245 				pgcnt = pgend - p_index + 1;
1246 
1247 				/*
1248 				 * Point indicies at page after large page,
1249 				 * or at page after end of mapping.
1250 				 */
1251 				p_index += pgcnt;
1252 				s_index += pgcnt;
1253 			} else {
1254 				p_index++;
1255 				s_index++;
1256 			}
1257 
1258 			/*
1259 			 * Assume anon structs with a refcnt
1260 			 * of 1 are not cow shared, so there
1261 			 * is no reason to track them per entity.
1262 			 */
1263 			if (cnt == 1) {
1264 				panon += pgcnt;
1265 				continue;
1266 			}
1267 			for (entity = vmu_entities; entity != NULL;
1268 			    entity = entity->vme_next_calc) {
1269 
1270 				result = &entity->vme_result;
1271 				/*
1272 				 * Track cow anons per entity so
1273 				 * they are not double counted.
1274 				 */
1275 				if (vmu_find_insert_anon(entity->vme_anon_hash,
1276 				    (caddr_t)ap) == 0)
1277 					continue;
1278 
1279 				result->vmu_rss_all += (pgcnt << PAGESHIFT);
1280 				result->vmu_rss_private +=
1281 				    (pgcnt << PAGESHIFT);
1282 			}
1283 		}
1284 		ANON_LOCK_EXIT(&private_amp->a_rwlock);
1285 	}
1286 
1287 	/* Add up resident anon and swap reserved for private mappings */
1288 	if (swresv > 0 || panon > 0) {
1289 		for (entity = vmu_entities; entity != NULL;
1290 		    entity = entity->vme_next_calc) {
1291 			result = &entity->vme_result;
1292 			result->vmu_swap_all += swresv;
1293 			result->vmu_swap_private += swresv;
1294 			result->vmu_rss_all += (panon << PAGESHIFT);
1295 			result->vmu_rss_private += (panon << PAGESHIFT);
1296 		}
1297 	}
1298 
1299 	/* Compute resident pages backing shared amp or named vnode */
1300 	if (shared_object != NULL) {
1301 		if (first == NULL) {
1302 			/*
1303 			 * No private amp, or private amp has no anon
1304 			 * structs.  This means entire segment is backed by
1305 			 * the shared object.
1306 			 */
1307 			first = vmu_alloc_bound();
1308 			first->vmb_next = NULL;
1309 			first->vmb_start = s_start;
1310 			first->vmb_end = s_end;
1311 			first->vmb_type = VMUSAGE_BOUND_UNKNOWN;
1312 		}
1313 		/*
1314 		 * Iterate bounds not backed by private amp, and compute
1315 		 * resident pages.
1316 		 */
1317 		cur = first;
1318 		while (cur != NULL) {
1319 
1320 			if (vmu_insert_lookup_object_bounds(shared_object,
1321 			    cur->vmb_start, cur->vmb_end, VMUSAGE_BOUND_UNKNOWN,
1322 			    &first, &last) > 0) {
1323 				/* new bounds, find incore/not-incore */
1324 				if (shared_object->vmo_type ==
1325 				    VMUSAGE_TYPE_VNODE)
1326 					vmu_vnode_update_incore_bounds(
1327 					    (vnode_t *)
1328 					    shared_object->vmo_key, &first,
1329 					    &last);
1330 				else
1331 					vmu_amp_update_incore_bounds(
1332 					    (struct anon_map *)
1333 					    shared_object->vmo_key, &first,
1334 					    &last, incore);
1335 				vmu_merge_bounds(&first, &last);
1336 			}
1337 			for (entity = vmu_entities; entity != NULL;
1338 			    entity = entity->vme_next_calc) {
1339 
1340 				result = &entity->vme_result;
1341 
1342 				entity_object = vmu_find_insert_object(
1343 				    shared_object->vmo_type ==
1344 				    VMUSAGE_TYPE_VNODE ? entity->vme_vnode_hash:
1345 					entity->vme_amp_hash,
1346 					shared_object->vmo_key,
1347 					shared_object->vmo_type);
1348 
1349 				virt = vmu_insert_lookup_object_bounds(
1350 				    entity_object, cur->vmb_start, cur->vmb_end,
1351 				    VMUSAGE_BOUND_UNKNOWN, &e_first, &e_last);
1352 
1353 				if (virt == 0)
1354 					continue;
1355 				/*
1356 				 * Range visited for this entity
1357 				 */
1358 				rss = vmu_update_bounds(&e_first,
1359 				    &e_last, first, last);
1360 				result->vmu_rss_all += (rss << PAGESHIFT);
1361 				if (shared == B_TRUE && file == B_FALSE) {
1362 					/* shared anon mapping */
1363 					result->vmu_swap_all +=
1364 					    (virt << PAGESHIFT);
1365 					result->vmu_swap_shared +=
1366 					    (virt << PAGESHIFT);
1367 					result->vmu_rss_shared +=
1368 					    (rss << PAGESHIFT);
1369 				} else if (shared == B_TRUE && file == B_TRUE) {
1370 					/* shared file mapping */
1371 					result->vmu_rss_shared +=
1372 					    (rss << PAGESHIFT);
1373 				} else if (shared == B_FALSE &&
1374 				    file == B_TRUE) {
1375 					/* private file mapping */
1376 					result->vmu_rss_private +=
1377 					    (rss << PAGESHIFT);
1378 				}
1379 				vmu_merge_bounds(&e_first, &e_last);
1380 			}
1381 			tmp = cur;
1382 			cur = cur->vmb_next;
1383 			vmu_free_bound(tmp);
1384 		}
1385 	}
1386 }
1387 
1388 /*
1389  * Based on the current calculation flags, find the relevant entities
1390  * which are relative to the process.  Then calculate each segment
1391  * in the process'es address space for each relevant entity.
1392  */
1393 static void
1394 vmu_calculate_proc(proc_t *p)
1395 {
1396 	vmu_entity_t *entities = NULL;
1397 	vmu_zone_t *zone;
1398 	vmu_entity_t *tmp;
1399 	struct as *as;
1400 	struct seg *seg;
1401 	int ret;
1402 
1403 	/* Figure out which entities are being computed */
1404 	if ((vmu_data.vmu_system) != NULL) {
1405 		tmp = vmu_data.vmu_system;
1406 		tmp->vme_next_calc = entities;
1407 		entities = tmp;
1408 	}
1409 	if (vmu_data.vmu_calc_flags &
1410 	    (VMUSAGE_ZONE | VMUSAGE_ALL_ZONES | VMUSAGE_PROJECTS |
1411 	    VMUSAGE_ALL_PROJECTS | VMUSAGE_TASKS | VMUSAGE_ALL_TASKS |
1412 	    VMUSAGE_RUSERS | VMUSAGE_ALL_RUSERS | VMUSAGE_EUSERS |
1413 	    VMUSAGE_ALL_EUSERS)) {
1414 		ret = i_mod_hash_find_nosync(vmu_data.vmu_zones_hash,
1415 		    (mod_hash_key_t)(uintptr_t)p->p_zone->zone_id,
1416 		    (mod_hash_val_t *)&zone);
1417 		if (ret != 0) {
1418 			zone = vmu_alloc_zone(p->p_zone->zone_id);
1419 			ret = i_mod_hash_insert_nosync(vmu_data.vmu_zones_hash,
1420 			    (mod_hash_key_t)(uintptr_t)p->p_zone->zone_id,
1421 			    (mod_hash_val_t)zone, (mod_hash_hndl_t)0);
1422 			ASSERT(ret == 0);
1423 		}
1424 		if (zone->vmz_zone != NULL) {
1425 			tmp = zone->vmz_zone;
1426 			tmp->vme_next_calc = entities;
1427 			entities = tmp;
1428 		}
1429 		if (vmu_data.vmu_calc_flags &
1430 		    (VMUSAGE_PROJECTS | VMUSAGE_ALL_PROJECTS)) {
1431 			tmp = vmu_find_insert_entity(zone->vmz_projects_hash,
1432 			    p->p_task->tk_proj->kpj_id, VMUSAGE_PROJECTS,
1433 			    zone->vmz_id);
1434 			tmp->vme_next_calc = entities;
1435 			entities = tmp;
1436 		}
1437 		if (vmu_data.vmu_calc_flags &
1438 		    (VMUSAGE_TASKS | VMUSAGE_ALL_TASKS)) {
1439 			tmp = vmu_find_insert_entity(zone->vmz_tasks_hash,
1440 			    p->p_task->tk_tkid, VMUSAGE_TASKS, zone->vmz_id);
1441 			tmp->vme_next_calc = entities;
1442 			entities = tmp;
1443 		}
1444 		if (vmu_data.vmu_calc_flags &
1445 		    (VMUSAGE_RUSERS | VMUSAGE_ALL_RUSERS)) {
1446 			tmp = vmu_find_insert_entity(zone->vmz_rusers_hash,
1447 			    crgetruid(p->p_cred), VMUSAGE_RUSERS, zone->vmz_id);
1448 			tmp->vme_next_calc = entities;
1449 			entities = tmp;
1450 		}
1451 		if (vmu_data.vmu_calc_flags &
1452 		    (VMUSAGE_EUSERS | VMUSAGE_ALL_EUSERS)) {
1453 			tmp = vmu_find_insert_entity(zone->vmz_eusers_hash,
1454 			    crgetuid(p->p_cred), VMUSAGE_EUSERS, zone->vmz_id);
1455 			tmp->vme_next_calc = entities;
1456 			entities = tmp;
1457 		}
1458 	}
1459 	/* Entities which collapse projects and users for all zones */
1460 	if (vmu_data.vmu_calc_flags & VMUSAGE_COL_PROJECTS) {
1461 		tmp = vmu_find_insert_entity(vmu_data.vmu_projects_col_hash,
1462 		    p->p_task->tk_proj->kpj_id, VMUSAGE_PROJECTS, ALL_ZONES);
1463 		tmp->vme_next_calc = entities;
1464 		entities = tmp;
1465 	}
1466 	if (vmu_data.vmu_calc_flags & VMUSAGE_COL_RUSERS) {
1467 		tmp = vmu_find_insert_entity(vmu_data.vmu_rusers_col_hash,
1468 		    crgetruid(p->p_cred), VMUSAGE_RUSERS, ALL_ZONES);
1469 		tmp->vme_next_calc = entities;
1470 		entities = tmp;
1471 	}
1472 	if (vmu_data.vmu_calc_flags & VMUSAGE_COL_EUSERS) {
1473 		tmp = vmu_find_insert_entity(vmu_data.vmu_eusers_col_hash,
1474 		    crgetuid(p->p_cred), VMUSAGE_EUSERS, ALL_ZONES);
1475 		tmp->vme_next_calc = entities;
1476 		entities = tmp;
1477 	}
1478 
1479 	ASSERT(entities != NULL);
1480 	/* process all segs in process's address space */
1481 	as = p->p_as;
1482 	AS_LOCK_ENTER(as, &as->a_lock, RW_READER);
1483 	for (seg = AS_SEGFIRST(as); seg != NULL;
1484 	    seg = AS_SEGNEXT(as, seg)) {
1485 		vmu_calculate_seg(entities, seg);
1486 	}
1487 	AS_LOCK_EXIT(as, &as->a_lock);
1488 }
1489 
1490 /*
1491  * Free data created by previous call to vmu_calculate().
1492  */
1493 static void
1494 vmu_clear_calc()
1495 {
1496 	if (vmu_data.vmu_system != NULL)
1497 		vmu_free_entity(vmu_data.vmu_system);
1498 		vmu_data.vmu_system = NULL;
1499 	if (vmu_data.vmu_zones_hash != NULL)
1500 		i_mod_hash_clear_nosync(vmu_data.vmu_zones_hash);
1501 	if (vmu_data.vmu_projects_col_hash != NULL)
1502 		i_mod_hash_clear_nosync(vmu_data.vmu_projects_col_hash);
1503 	if (vmu_data.vmu_rusers_col_hash != NULL)
1504 		i_mod_hash_clear_nosync(vmu_data.vmu_rusers_col_hash);
1505 	if (vmu_data.vmu_eusers_col_hash != NULL)
1506 		i_mod_hash_clear_nosync(vmu_data.vmu_eusers_col_hash);
1507 
1508 	i_mod_hash_clear_nosync(vmu_data.vmu_all_vnodes_hash);
1509 	i_mod_hash_clear_nosync(vmu_data.vmu_all_amps_hash);
1510 }
1511 
1512 /*
1513  * Free unused data structures.  These can result if the system workload
1514  * decreases between calculations.
1515  */
1516 static void
1517 vmu_free_extra()
1518 {
1519 	vmu_bound_t *tb;
1520 	vmu_object_t *to;
1521 	vmu_entity_t *te;
1522 	vmu_zone_t *tz;
1523 
1524 	while (vmu_data.vmu_free_bounds != NULL) {
1525 		tb = vmu_data.vmu_free_bounds;
1526 		vmu_data.vmu_free_bounds = vmu_data.vmu_free_bounds->vmb_next;
1527 		kmem_cache_free(vmu_bound_cache, tb);
1528 	}
1529 	while (vmu_data.vmu_free_objects != NULL) {
1530 		to = vmu_data.vmu_free_objects;
1531 		vmu_data.vmu_free_objects =
1532 		    vmu_data.vmu_free_objects->vmo_next;
1533 		kmem_cache_free(vmu_object_cache, to);
1534 	}
1535 	while (vmu_data.vmu_free_entities != NULL) {
1536 		te = vmu_data.vmu_free_entities;
1537 		vmu_data.vmu_free_entities =
1538 		    vmu_data.vmu_free_entities->vme_next;
1539 		if (te->vme_vnode_hash != NULL)
1540 			mod_hash_destroy_hash(te->vme_vnode_hash);
1541 		if (te->vme_amp_hash != NULL)
1542 			mod_hash_destroy_hash(te->vme_amp_hash);
1543 		if (te->vme_anon_hash != NULL)
1544 			mod_hash_destroy_hash(te->vme_anon_hash);
1545 		kmem_free(te, sizeof (vmu_entity_t));
1546 	}
1547 	while (vmu_data.vmu_free_zones != NULL) {
1548 		tz = vmu_data.vmu_free_zones;
1549 		vmu_data.vmu_free_zones =
1550 		    vmu_data.vmu_free_zones->vmz_next;
1551 		if (tz->vmz_projects_hash != NULL)
1552 			mod_hash_destroy_hash(tz->vmz_projects_hash);
1553 		if (tz->vmz_tasks_hash != NULL)
1554 			mod_hash_destroy_hash(tz->vmz_tasks_hash);
1555 		if (tz->vmz_rusers_hash != NULL)
1556 			mod_hash_destroy_hash(tz->vmz_rusers_hash);
1557 		if (tz->vmz_eusers_hash != NULL)
1558 			mod_hash_destroy_hash(tz->vmz_eusers_hash);
1559 		kmem_free(tz, sizeof (vmu_zone_t));
1560 	}
1561 }
1562 
1563 extern kcondvar_t *pr_pid_cv;
1564 
1565 /*
1566  * Determine which entity types are relevant and allocate the hashes to
1567  * track them.  Then walk the process table and count rss and swap
1568  * for each process'es address space.  Address space object such as
1569  * vnodes, amps and anons are tracked per entity, so that they are
1570  * not double counted in the results.
1571  *
1572  */
1573 static void
1574 vmu_calculate()
1575 {
1576 	int i = 0;
1577 	int ret;
1578 	proc_t *p;
1579 
1580 	vmu_clear_calc();
1581 
1582 	if (vmu_data.vmu_calc_flags & VMUSAGE_SYSTEM)
1583 		vmu_data.vmu_system = vmu_alloc_entity(0, VMUSAGE_SYSTEM,
1584 		    ALL_ZONES);
1585 
1586 	/*
1587 	 * Walk process table and calculate rss of each proc.
1588 	 *
1589 	 * Pidlock and p_lock cannot be held while doing the rss calculation.
1590 	 * This is because:
1591 	 *	1.  The calculation allocates using KM_SLEEP.
1592 	 *	2.  The calculation grabs a_lock, which cannot be grabbed
1593 	 *	    after p_lock.
1594 	 *
1595 	 * Since pidlock must be dropped, we cannot simply just walk the
1596 	 * practive list.  Instead, we walk the process table, and sprlock
1597 	 * each process to ensure that it does not exit during the
1598 	 * calculation.
1599 	 */
1600 
1601 	mutex_enter(&pidlock);
1602 	for (i = 0; i < v.v_proc; i++) {
1603 again:
1604 		p = pid_entry(i);
1605 		if (p == NULL)
1606 			continue;
1607 
1608 		mutex_enter(&p->p_lock);
1609 		mutex_exit(&pidlock);
1610 
1611 		if (panicstr) {
1612 			mutex_exit(&p->p_lock);
1613 			return;
1614 		}
1615 
1616 		/* Try to set P_PR_LOCK */
1617 		ret = sprtrylock_proc(p);
1618 		if (ret == -1) {
1619 			/* Process in invalid state */
1620 			mutex_exit(&p->p_lock);
1621 			mutex_enter(&pidlock);
1622 			continue;
1623 		} else if (ret == 1) {
1624 			/*
1625 			 * P_PR_LOCK is already set.  Wait and try again.
1626 			 * This also drops p_lock.
1627 			 */
1628 			sprwaitlock_proc(p);
1629 			mutex_enter(&pidlock);
1630 			goto again;
1631 		}
1632 		mutex_exit(&p->p_lock);
1633 
1634 		vmu_calculate_proc(p);
1635 
1636 		mutex_enter(&p->p_lock);
1637 		sprunlock(p);
1638 		mutex_enter(&pidlock);
1639 	}
1640 	mutex_exit(&pidlock);
1641 
1642 	vmu_free_extra();
1643 }
1644 
1645 /*
1646  * allocate a new cache for N results satisfying flags
1647  */
1648 vmu_cache_t *
1649 vmu_cache_alloc(size_t nres, uint_t flags)
1650 {
1651 	vmu_cache_t *cache;
1652 
1653 	cache = kmem_zalloc(sizeof (vmu_cache_t), KM_SLEEP);
1654 	cache->vmc_results = kmem_zalloc(sizeof (vmusage_t) * nres, KM_SLEEP);
1655 	cache->vmc_nresults = nres;
1656 	cache->vmc_flags = flags;
1657 	cache->vmc_refcnt = 1;
1658 	return (cache);
1659 }
1660 
1661 /*
1662  * Make sure cached results are not freed
1663  */
1664 static void
1665 vmu_cache_hold(vmu_cache_t *cache)
1666 {
1667 	ASSERT(MUTEX_HELD(&vmu_data.vmu_lock));
1668 	cache->vmc_refcnt++;
1669 }
1670 
1671 /*
1672  * free cache data
1673  */
1674 static void
1675 vmu_cache_rele(vmu_cache_t *cache)
1676 {
1677 	ASSERT(MUTEX_HELD(&vmu_data.vmu_lock));
1678 	ASSERT(cache->vmc_refcnt > 0);
1679 	cache->vmc_refcnt--;
1680 	if (cache->vmc_refcnt == 0) {
1681 		kmem_free(cache->vmc_results, sizeof (vmusage_t) *
1682 			cache->vmc_nresults);
1683 		kmem_free(cache, sizeof (vmu_cache_t));
1684 	}
1685 }
1686 
1687 /*
1688  * Copy out the cached results to a caller.  Inspect the callers flags
1689  * and zone to determine which cached results should be copied.
1690  */
1691 static int
1692 vmu_copyout_results(vmu_cache_t *cache, vmusage_t *buf, size_t *nres,
1693     uint_t flags)
1694 {
1695 	vmusage_t *result, *out_result;
1696 	vmusage_t dummy;
1697 	size_t i, count = 0;
1698 	size_t bufsize;
1699 	int ret = 0;
1700 	uint_t types = 0;
1701 
1702 	if (nres != NULL) {
1703 		if (copyin((caddr_t)nres, &bufsize, sizeof (size_t)))
1704 			return (set_errno(EFAULT));
1705 	} else {
1706 		bufsize = 0;
1707 	}
1708 
1709 	/* figure out what results the caller is interested in. */
1710 	if ((flags & VMUSAGE_SYSTEM) && curproc->p_zone == global_zone)
1711 		types |= VMUSAGE_SYSTEM;
1712 	if (flags & (VMUSAGE_ZONE | VMUSAGE_ALL_ZONES))
1713 		types |= VMUSAGE_ZONE;
1714 	if (flags & (VMUSAGE_PROJECTS | VMUSAGE_ALL_PROJECTS |
1715 	    VMUSAGE_COL_PROJECTS))
1716 		types |= VMUSAGE_PROJECTS;
1717 	if (flags & (VMUSAGE_TASKS | VMUSAGE_ALL_TASKS))
1718 		types |= VMUSAGE_TASKS;
1719 	if (flags & (VMUSAGE_RUSERS | VMUSAGE_ALL_RUSERS | VMUSAGE_COL_RUSERS))
1720 		types |= VMUSAGE_RUSERS;
1721 	if (flags & (VMUSAGE_EUSERS | VMUSAGE_ALL_EUSERS | VMUSAGE_COL_EUSERS))
1722 		types |= VMUSAGE_EUSERS;
1723 
1724 	/* count results for current zone */
1725 	out_result = buf;
1726 	for (result = cache->vmc_results, i = 0;
1727 	    i < cache->vmc_nresults; result++, i++) {
1728 
1729 		/* Do not return "other-zone" results to non-global zones */
1730 		if (curproc->p_zone != global_zone &&
1731 		    curproc->p_zone->zone_id != result->vmu_zoneid)
1732 			continue;
1733 
1734 		/*
1735 		 * If non-global zone requests VMUSAGE_SYSTEM, fake
1736 		 * up VMUSAGE_ZONE result as VMUSAGE_SYSTEM result.
1737 		 */
1738 		if (curproc->p_zone != global_zone &&
1739 		    (flags & VMUSAGE_SYSTEM) != 0 &&
1740 		    result->vmu_type == VMUSAGE_ZONE) {
1741 			count++;
1742 			if (out_result != NULL) {
1743 				if (bufsize < count) {
1744 					ret = set_errno(EOVERFLOW);
1745 				} else {
1746 					dummy = *result;
1747 					dummy.vmu_zoneid = ALL_ZONES;
1748 					dummy.vmu_id = 0;
1749 					dummy.vmu_type = VMUSAGE_SYSTEM;
1750 					if (copyout(&dummy, out_result,
1751 					    sizeof (vmusage_t)))
1752 						return (set_errno(
1753 						    EFAULT));
1754 					out_result++;
1755 				}
1756 			}
1757 		}
1758 
1759 		/* Skip results that do not match requested type */
1760 		if ((result->vmu_type & types) == 0)
1761 			continue;
1762 
1763 		/* Skip collated results if not requested */
1764 		if (result->vmu_zoneid == ALL_ZONES) {
1765 			if (result->vmu_type == VMUSAGE_PROJECTS &&
1766 			    (flags & VMUSAGE_COL_PROJECTS) == 0)
1767 				continue;
1768 			if (result->vmu_type == VMUSAGE_EUSERS &&
1769 			    (flags & VMUSAGE_COL_EUSERS) == 0)
1770 				continue;
1771 			if (result->vmu_type == VMUSAGE_RUSERS &&
1772 			    (flags & VMUSAGE_COL_RUSERS) == 0)
1773 				continue;
1774 		}
1775 
1776 		/* Skip "other zone" results if not requested */
1777 		if (result->vmu_zoneid != curproc->p_zone->zone_id) {
1778 			if (result->vmu_type == VMUSAGE_ZONE &&
1779 			    (flags & VMUSAGE_ALL_ZONES) == 0)
1780 				continue;
1781 			if (result->vmu_type == VMUSAGE_PROJECTS &&
1782 			    (flags & (VMUSAGE_ALL_PROJECTS |
1783 			    VMUSAGE_COL_PROJECTS)) == 0)
1784 				continue;
1785 			if (result->vmu_type == VMUSAGE_TASKS &&
1786 			    (flags & VMUSAGE_ALL_TASKS) == 0)
1787 				continue;
1788 			if (result->vmu_type == VMUSAGE_RUSERS &&
1789 			    (flags & (VMUSAGE_ALL_RUSERS |
1790 			    VMUSAGE_COL_RUSERS)) == 0)
1791 				continue;
1792 			if (result->vmu_type == VMUSAGE_EUSERS &&
1793 			    (flags & (VMUSAGE_ALL_EUSERS |
1794 			    VMUSAGE_COL_EUSERS)) == 0)
1795 				continue;
1796 		}
1797 		count++;
1798 		if (out_result != NULL) {
1799 			if (bufsize < count) {
1800 				ret = set_errno(EOVERFLOW);
1801 			} else {
1802 				if (copyout(result, out_result,
1803 				    sizeof (vmusage_t)))
1804 					return (set_errno(EFAULT));
1805 				out_result++;
1806 			}
1807 		}
1808 	}
1809 	if (nres != NULL)
1810 		if (copyout(&count, (void *)nres, sizeof (size_t)))
1811 			return (set_errno(EFAULT));
1812 
1813 	return (ret);
1814 }
1815 
1816 /*
1817  * vm_getusage()
1818  *
1819  * Counts rss and swap by zone, project, task, and/or user.  The flags argument
1820  * determines the type of results structures returned.  Flags requesting
1821  * results from more than one zone are "flattened" to the local zone if the
1822  * caller is not the global zone.
1823  *
1824  * args:
1825  *	flags:	bitmap consisting of one or more of VMUSAGE_*.
1826  *	age:	maximum allowable age (time since counting was done) in
1827  *		seconds of the results.  Results from previous callers are
1828  *		cached in kernel.
1829  *	buf:	pointer to buffer array of vmusage_t.  If NULL, then only nres
1830  *		set on success.
1831  *	nres:	Set to number of vmusage_t structures pointed to by buf
1832  *		before calling vm_getusage().
1833  *		On return 0 (success) or ENOSPC, is set to the number of result
1834  *		structures returned or attempted to return.
1835  *
1836  * returns 0 on success, -1 on failure:
1837  *	EINTR (interrupted)
1838  *	ENOSPC (nres to small for results, nres set to needed value for success)
1839  *	EINVAL (flags invalid)
1840  *	EFAULT (bad address for buf or nres)
1841  */
1842 int
1843 vm_getusage(uint_t flags, time_t age, vmusage_t *buf, size_t *nres)
1844 {
1845 	vmu_entity_t *entity;
1846 	vmusage_t *result;
1847 	int ret = 0;
1848 	int cacherecent = 0;
1849 	hrtime_t now;
1850 	uint_t flags_orig;
1851 
1852 	/*
1853 	 * Non-global zones cannot request system wide and/or collated
1854 	 * results, or the system result, so munge the flags accordingly.
1855 	 */
1856 	flags_orig = flags;
1857 	if (curproc->p_zone != global_zone) {
1858 		if (flags & (VMUSAGE_ALL_PROJECTS | VMUSAGE_COL_PROJECTS)) {
1859 			flags &= ~(VMUSAGE_ALL_PROJECTS | VMUSAGE_COL_PROJECTS);
1860 			flags |= VMUSAGE_PROJECTS;
1861 		}
1862 		if (flags & (VMUSAGE_ALL_RUSERS | VMUSAGE_COL_RUSERS)) {
1863 			flags &= ~(VMUSAGE_ALL_RUSERS | VMUSAGE_COL_RUSERS);
1864 			flags |= VMUSAGE_RUSERS;
1865 		}
1866 		if (flags & (VMUSAGE_ALL_EUSERS | VMUSAGE_COL_EUSERS)) {
1867 			flags &= ~(VMUSAGE_ALL_EUSERS | VMUSAGE_COL_EUSERS);
1868 			flags |= VMUSAGE_EUSERS;
1869 		}
1870 		if (flags & VMUSAGE_SYSTEM) {
1871 			flags &= ~VMUSAGE_SYSTEM;
1872 			flags |= VMUSAGE_ZONE;
1873 		}
1874 	}
1875 
1876 	/* Check for unknown flags */
1877 	if ((flags & (~VMUSAGE_MASK)) != 0)
1878 		return (set_errno(EINVAL));
1879 
1880 	/* Check for no flags */
1881 	if ((flags & VMUSAGE_MASK) == 0)
1882 		return (set_errno(EINVAL));
1883 
1884 	mutex_enter(&vmu_data.vmu_lock);
1885 	now = gethrtime();
1886 
1887 start:
1888 	if (vmu_data.vmu_cache != NULL) {
1889 
1890 		vmu_cache_t *cache;
1891 
1892 		if ((vmu_data.vmu_cache->vmc_timestamp +
1893 		    ((hrtime_t)age * NANOSEC)) > now)
1894 			cacherecent = 1;
1895 
1896 		if ((vmu_data.vmu_cache->vmc_flags & flags) == flags &&
1897 		    cacherecent == 1) {
1898 			cache = vmu_data.vmu_cache;
1899 			vmu_cache_hold(cache);
1900 			mutex_exit(&vmu_data.vmu_lock);
1901 
1902 			ret = vmu_copyout_results(cache, buf, nres, flags_orig);
1903 			mutex_enter(&vmu_data.vmu_lock);
1904 			vmu_cache_rele(cache);
1905 			if (vmu_data.vmu_pending_waiters > 0)
1906 				cv_broadcast(&vmu_data.vmu_cv);
1907 			mutex_exit(&vmu_data.vmu_lock);
1908 			return (ret);
1909 		}
1910 		/*
1911 		 * If the cache is recent, it is likely that there are other
1912 		 * consumers of vm_getusage running, so add their flags to the
1913 		 * desired flags for the calculation.
1914 		 */
1915 		if (cacherecent == 1)
1916 			flags = vmu_data.vmu_cache->vmc_flags | flags;
1917 	}
1918 	if (vmu_data.vmu_calc_thread == NULL) {
1919 
1920 		vmu_cache_t *cache;
1921 
1922 		vmu_data.vmu_calc_thread = curthread;
1923 		vmu_data.vmu_calc_flags = flags;
1924 		vmu_data.vmu_entities = NULL;
1925 		vmu_data.vmu_nentities = 0;
1926 		if (vmu_data.vmu_pending_waiters > 0)
1927 			vmu_data.vmu_calc_flags |=
1928 			    vmu_data.vmu_pending_flags;
1929 
1930 		vmu_data.vmu_pending_flags = 0;
1931 		mutex_exit(&vmu_data.vmu_lock);
1932 		vmu_calculate();
1933 		mutex_enter(&vmu_data.vmu_lock);
1934 		/* copy results to cache */
1935 		if (vmu_data.vmu_cache != NULL)
1936 			vmu_cache_rele(vmu_data.vmu_cache);
1937 		cache = vmu_data.vmu_cache =
1938 		    vmu_cache_alloc(vmu_data.vmu_nentities,
1939 			vmu_data.vmu_calc_flags);
1940 
1941 		result = cache->vmc_results;
1942 		for (entity = vmu_data.vmu_entities; entity != NULL;
1943 		    entity = entity->vme_next) {
1944 			*result = entity->vme_result;
1945 			result++;
1946 		}
1947 		cache->vmc_timestamp = gethrtime();
1948 		vmu_cache_hold(cache);
1949 
1950 		vmu_data.vmu_calc_flags = 0;
1951 		vmu_data.vmu_calc_thread = NULL;
1952 
1953 		if (vmu_data.vmu_pending_waiters > 0)
1954 			cv_broadcast(&vmu_data.vmu_cv);
1955 
1956 		mutex_exit(&vmu_data.vmu_lock);
1957 
1958 		/* copy cache */
1959 		ret = vmu_copyout_results(cache, buf, nres, flags_orig);
1960 		mutex_enter(&vmu_data.vmu_lock);
1961 		vmu_cache_rele(cache);
1962 		mutex_exit(&vmu_data.vmu_lock);
1963 
1964 		return (ret);
1965 	}
1966 	vmu_data.vmu_pending_flags |= flags;
1967 	vmu_data.vmu_pending_waiters++;
1968 	while (vmu_data.vmu_calc_thread != NULL) {
1969 		if (cv_wait_sig(&vmu_data.vmu_cv,
1970 		    &vmu_data.vmu_lock) == 0) {
1971 			vmu_data.vmu_pending_waiters--;
1972 			mutex_exit(&vmu_data.vmu_lock);
1973 			return (set_errno(EINTR));
1974 		}
1975 	}
1976 	vmu_data.vmu_pending_waiters--;
1977 	goto start;
1978 }
1979