xref: /netbsd-src/external/bsd/top/dist/machine/m_netbsd.c (revision 6a493d6bc668897c91594964a732d38505b70cbb)
1 /*	$NetBSD: m_netbsd.c,v 1.18 2013/10/20 03:02:27 christos Exp $	*/
2 
3 /*
4  * top - a top users display for Unix
5  *
6  * SYNOPSIS:  For a NetBSD-1.5 (or later) system
7  *
8  * DESCRIPTION:
9  * Originally written for BSD4.4 system by Christos Zoulas.
10  * Based on the FreeBSD 2.0 version by Steven Wallace and Wolfram Schneider.
11  * NetBSD-1.0 port by Arne Helme. Process ordering by Luke Mewburn.
12  * NetBSD-1.3 port by Luke Mewburn, based on code by Matthew Green.
13  * NetBSD-1.4/UVM port by matthew green.
14  * NetBSD-1.5 port by Simon Burge.
15  * NetBSD-1.6/UBC port by Tomas Svensson.
16  * -
17  * This is the machine-dependent module for NetBSD-1.5 and later
18  * works for:
19  *	NetBSD-1.6ZC
20  * and should work for:
21  *	NetBSD-2.0	(when released)
22  * -
23  * top does not need to be installed setuid or setgid with this module.
24  *
25  * LIBS: -lkvm
26  *
27  * CFLAGS: -DHAVE_GETOPT -DORDER -DHAVE_STRERROR
28  *
29  * AUTHORS:	Christos Zoulas <christos@ee.cornell.edu>
30  *		Steven Wallace <swallace@freebsd.org>
31  *		Wolfram Schneider <wosch@cs.tu-berlin.de>
32  *		Arne Helme <arne@acm.org>
33  *		Luke Mewburn <lukem@NetBSD.org>
34  *		matthew green <mrg@eterna.com.au>
35  *		Simon Burge <simonb@NetBSD.org>
36  *		Tomas Svensson <ts@unix1.net>
37  *		Andrew Doran <ad@NetBSD.org>
38  *
39  *
40  * $Id: m_netbsd.c,v 1.18 2013/10/20 03:02:27 christos Exp $
41  */
42 #include <sys/cdefs.h>
43 
44 #ifndef lint
45 __RCSID("$NetBSD: m_netbsd.c,v 1.18 2013/10/20 03:02:27 christos Exp $");
46 #endif
47 
48 #include <sys/param.h>
49 #include <sys/resource.h>
50 #include <sys/sysctl.h>
51 #include <sys/sched.h>
52 #include <sys/swap.h>
53 
54 #include <uvm/uvm_extern.h>
55 
56 #include <err.h>
57 #include <errno.h>
58 #include <kvm.h>
59 #include <math.h>
60 #include <nlist.h>
61 #include <stdio.h>
62 #include <stdlib.h>
63 #include <string.h>
64 #include <unistd.h>
65 
66 #include "os.h"
67 #include "top.h"
68 #include "machine.h"
69 #include "utils.h"
70 #include "display.h"
71 #include "loadavg.h"
72 #include "username.h"
73 
74 static void percentages64(int, int *, u_int64_t *, u_int64_t *,
75     u_int64_t *);
76 
77 /* get_process_info passes back a handle.  This is what it looks like: */
78 
79 struct handle {
80 	struct process_select *sel;
81 	struct kinfo_proc2 **next_proc;	/* points to next valid proc pointer */
82 	int remaining;		/* number of pointers remaining */
83 };
84 
85 /* define what weighted CPU is. */
86 #define weighted_cpu(pfx, pct, pp) ((pp)->pfx ## swtime == 0 ? 0.0 : \
87 			 ((pct) / (1.0 - exp((pp)->pfx ## swtime * logcpu))))
88 
89 /* what we consider to be process size: */
90 /* NetBSD introduced p_vm_msize with RLIMIT_AS */
91 #ifdef RLIMIT_AS
92 #define PROCSIZE(pp) \
93     ((pp)->p_vm_msize)
94 #else
95 #define PROCSIZE(pp) \
96     ((pp)->p_vm_tsize + (pp)->p_vm_dsize + (pp)->p_vm_ssize)
97 #endif
98 
99 
100 /*
101  * These definitions control the format of the per-process area
102  */
103 
104 static char Proc_header[] =
105   "  PID X        PRI NICE   SIZE   RES STATE      TIME   WCPU    CPU COMMAND";
106 /* 0123456   -- field to fill in starts at header+6 */
107 #define PROC_UNAME_START 6
108 #define Proc_format \
109 	"%5d %-8.8s %3d %4d%7s %5s %-8.8s%7s %5.*f%% %5.*f%% %s"
110 
111 static char Thread_header[] =
112   "  PID   LID X        PRI STATE      TIME   WCPU    CPU NAME      COMMAND";
113 /* 0123456   -- field to fill in starts at header+6 */
114 #define THREAD_UNAME_START 12
115 #define Thread_format \
116         "%5d %5d %-8.8s %3d %-8.8s%7s %5.2f%% %5.2f%% %-9.9s %s"
117 
118 /*
119  * Process state names for the "STATE" column of the display.
120  */
121 
122 const char *state_abbrev[] = {
123 	"", "IDLE", "RUN", "SLEEP", "STOP", "ZOMB", "DEAD", "CPU"
124 };
125 
126 static kvm_t *kd;
127 
128 static char *(*userprint)(int);
129 
130 /* these are retrieved from the kernel in _init */
131 
132 static double logcpu;
133 static int hz;
134 static int ccpu;
135 
136 /* these are for calculating CPU state percentages */
137 
138 static int ncpu = 0;
139 static u_int64_t *cp_time;
140 static u_int64_t *cp_old;
141 static u_int64_t *cp_diff;
142 
143 /* these are for detailing the process states */
144 
145 int process_states[8];
146 const char *procstatenames[] = {
147 	"", " idle, ", " runnable, ", " sleeping, ", " stopped, ",
148 	" zombie, ", " dead, ", " on CPU, ",
149 	NULL
150 };
151 
152 /* these are for detailing the CPU states */
153 
154 int *cpu_states;
155 const char *cpustatenames[] = {
156 	"user", "nice", "system", "interrupt", "idle", NULL
157 };
158 
159 /* these are for detailing the memory statistics */
160 
161 long memory_stats[7];
162 const char *memorynames[] = {
163 	"K Act, ", "K Inact, ", "K Wired, ", "K Exec, ", "K File, ",
164 	"K Free, ",
165 	NULL
166 };
167 
168 long swap_stats[4];
169 const char *swapnames[] = {
170 	"K Total, ", "K Used, ", "K Free, ",
171 	NULL
172 };
173 
174 
175 /* these are names given to allowed sorting orders -- first is default */
176 const char *ordernames[] = {
177 	"cpu",
178 	"pri",
179 	"res",
180 	"size",
181 	"state",
182 	"time",
183 	"pid",
184 	"command",
185 	"username",
186 	NULL
187 };
188 
189 /* forward definitions for comparison functions */
190 static int compare_cpu(struct proc **, struct proc **);
191 static int compare_prio(struct proc **, struct proc **);
192 static int compare_res(struct proc **, struct proc **);
193 static int compare_size(struct proc **, struct proc **);
194 static int compare_state(struct proc **, struct proc **);
195 static int compare_time(struct proc **, struct proc **);
196 static int compare_pid(struct proc **, struct proc **);
197 static int compare_command(struct proc **, struct proc **);
198 static int compare_username(struct proc **, struct proc **);
199 
200 int (*proc_compares[])(struct proc **, struct proc **) = {
201 	compare_cpu,
202 	compare_prio,
203 	compare_res,
204 	compare_size,
205 	compare_state,
206 	compare_time,
207 	compare_pid,
208 	compare_command,
209 	compare_username,
210 	NULL
211 };
212 
213 static char *format_next_lwp(caddr_t, char *(*)(int));
214 static char *format_next_proc(caddr_t, char *(*)(int));
215 
216 static caddr_t get_proc_info(struct system_info *, struct process_select *,
217 			     int (*)(struct proc **, struct proc **));
218 static caddr_t get_lwp_info(struct system_info *, struct process_select *,
219 			    int (*)(struct proc **, struct proc **));
220 
221 /* these are for keeping track of the proc array */
222 
223 static int nproc;
224 static int onproc = -1;
225 static int nlwp;
226 static int onlwp = -1;
227 static int pref_len;
228 static int lref_len;
229 static struct kinfo_proc2 *pbase;
230 static struct kinfo_lwp *lbase;
231 static struct kinfo_proc2 **pref;
232 static struct kinfo_lwp **lref;
233 static int maxswap;
234 static void *swapp;
235 static int procgen;
236 static int thread_nproc;
237 static int thread_onproc = -1;
238 static struct kinfo_proc2 *thread_pbase;
239 
240 /* these are for getting the memory statistics */
241 
242 static int pageshift;		/* log base 2 of the pagesize */
243 
244 int threadmode;
245 
246 /* define pagetok in terms of pageshift */
247 
248 #define pagetok(size) ((size) << pageshift)
249 
250 /*
251  * Print swapped processes as <pname> and
252  * system processes as [pname]
253  */
254 static const char *
255 get_pretty(const struct kinfo_proc2 *pp)
256 {
257 	if ((pp->p_flag & P_SYSTEM) != 0)
258 		return "[]";
259 	if ((pp->p_flag & P_INMEM) == 0)
260 		return "<>";
261 	return "";
262 }
263 
264 static const char *
265 get_command(const struct process_select *sel, struct kinfo_proc2 *pp)
266 {
267 	static char cmdbuf[128];
268 	const char *pretty;
269 	char **argv;
270 	if (pp == NULL)
271 		return "<gone>";
272 	pretty = get_pretty(pp);
273 
274 	if (sel->fullcmd == 0 || kd == NULL || (argv = kvm_getargv2(kd, pp,
275 	    sizeof(cmdbuf))) == NULL) {
276 		if (pretty[0] != '\0' && pp->p_comm[0] != pretty[0])
277 			snprintf(cmdbuf, sizeof(cmdbuf), "%c%s%c", pretty[0],
278 			    printable(pp->p_comm), pretty[1]);
279 		else
280 			strlcpy(cmdbuf, printable(pp->p_comm), sizeof(cmdbuf));
281 	} else {
282 		char *d = cmdbuf;
283 		if (pretty[0] != '\0' && argv[0][0] != pretty[0])
284 			*d++ = pretty[0];
285 		while (*argv) {
286 			const char *s = printable(*argv++);
287 			while (d < cmdbuf + sizeof(cmdbuf) - 2 &&
288 			    (*d++ = *s++) != '\0')
289 				continue;
290 			if (d > cmdbuf && d < cmdbuf + sizeof(cmdbuf) - 2 &&
291 			    d[-1] == '\0')
292 				d[-1] = ' ';
293 		}
294 		if (pretty[0] != '\0' && pretty[0] == cmdbuf[0])
295 			*d++ = pretty[1];
296 		*d++ = '\0';
297 	}
298 	return cmdbuf;
299 }
300 
301 int
302 machine_init(statics)
303 	struct statics *statics;
304 {
305 	int pagesize;
306 	int mib[2];
307 	size_t size;
308 	struct clockinfo clockinfo;
309 	struct timeval boottime;
310 
311 	if ((kd = kvm_open(NULL, NULL, NULL, KVM_NO_FILES, "kvm_open")) == NULL)
312 		return -1;
313 
314 	mib[0] = CTL_HW;
315 	mib[1] = HW_NCPU;
316 	size = sizeof(ncpu);
317 	if (sysctl(mib, 2, &ncpu, &size, NULL, 0) == -1) {
318 		fprintf(stderr, "top: sysctl hw.ncpu failed: %s\n",
319 		    strerror(errno));
320 		return(-1);
321 	}
322 	statics->ncpu = ncpu;
323 	cp_time = malloc(sizeof(cp_time[0]) * CPUSTATES * ncpu);
324 	mib[0] = CTL_KERN;
325 	mib[1] = KERN_CP_TIME;
326 	size = sizeof(cp_time[0]) * CPUSTATES * ncpu;
327 	if (sysctl(mib, 2, cp_time, &size, NULL, 0) < 0) {
328 		fprintf(stderr, "top: sysctl kern.cp_time failed: %s\n",
329 		    strerror(errno));
330 		return(-1);
331 	}
332 
333 	/* Handle old call that returned only aggregate */
334 	if (size == sizeof(cp_time[0]) * CPUSTATES)
335 		ncpu = 1;
336 
337 	cpu_states = malloc(sizeof(cpu_states[0]) * CPUSTATES * ncpu);
338 	cp_old = malloc(sizeof(cp_old[0]) * CPUSTATES * ncpu);
339 	cp_diff = malloc(sizeof(cp_diff[0]) * CPUSTATES * ncpu);
340 	if (cpu_states == NULL || cp_time == NULL || cp_old == NULL ||
341 	    cp_diff == NULL) {
342 		fprintf(stderr, "top: machine_init: %s\n",
343 		    strerror(errno));
344 		return(-1);
345 	}
346 
347 	mib[0] = CTL_KERN;
348 	mib[1] = KERN_CCPU;
349 	size = sizeof(ccpu);
350 	if (sysctl(mib, 2, &ccpu, &size, NULL, 0) == -1) {
351 		fprintf(stderr, "top: sysctl kern.ccpu failed: %s\n",
352 		    strerror(errno));
353 		return(-1);
354 	}
355 
356 	mib[0] = CTL_KERN;
357 	mib[1] = KERN_CLOCKRATE;
358 	size = sizeof(clockinfo);
359 	if (sysctl(mib, 2, &clockinfo, &size, NULL, 0) == -1) {
360 		fprintf(stderr, "top: sysctl kern.clockrate failed: %s\n",
361 		    strerror(errno));
362 		return(-1);
363 	}
364 	hz = clockinfo.stathz;
365 
366 	/* this is used in calculating WCPU -- calculate it ahead of time */
367 	logcpu = log(loaddouble(ccpu));
368 
369 	pbase = NULL;
370 	lbase = NULL;
371 	pref = NULL;
372 	nproc = 0;
373 	onproc = -1;
374 	nlwp = 0;
375 	onlwp = -1;
376 	/* get the page size with "getpagesize" and calculate pageshift from it */
377 	pagesize = getpagesize();
378 	pageshift = 0;
379 	while (pagesize > 1) {
380 		pageshift++;
381 		pagesize >>= 1;
382 	}
383 
384 	/* we only need the amount of log(2)1024 for our conversion */
385 	pageshift -= LOG1024;
386 
387 	/* fill in the statics information */
388 #ifdef notyet
389 	statics->ncpu = ncpu;
390 #endif
391 	statics->procstate_names = procstatenames;
392 	statics->cpustate_names = cpustatenames;
393 	statics->memory_names = memorynames;
394 	statics->swap_names = swapnames;
395 	statics->order_names = ordernames;
396 	statics->flags.threads = 1;
397 	statics->flags.fullcmds = 1;
398 
399 	mib[0] = CTL_KERN;
400 	mib[1] = KERN_BOOTTIME;
401 	size = sizeof(boottime);
402 	if (sysctl(mib, 2, &boottime, &size, NULL, 0) != -1 &&
403     	    boottime.tv_sec != 0)
404 		statics->boottime = boottime.tv_sec;
405 	else
406 		statics->boottime = 0;
407 	/* all done! */
408 	return(0);
409 }
410 
411 char *
412 format_process_header(struct process_select *sel, caddr_t handle, int count)
413 
414 {
415 	char *header;
416 	char *ptr;
417 	const char *uname_field = sel->usernames ? "USERNAME" : "    UID ";
418 
419 	if (sel->threads) {
420 		header = Thread_header;
421 		ptr = header + THREAD_UNAME_START;
422 	} else {
423 		header = Proc_header;
424 		ptr = header + PROC_UNAME_START;
425 	}
426 
427 	while (*uname_field != '\0') {
428 		*ptr++ = *uname_field++;
429 	}
430 
431 	return(header);
432 }
433 
434 char *
435 format_header(char *uname_field)
436 {
437 	char *header = Proc_header;
438 	char *ptr = header + PROC_UNAME_START;
439 
440 	while (*uname_field != '\0') {
441 		*ptr++ = *uname_field++;
442 	}
443 
444 	return(header);
445 }
446 
447 void
448 get_system_info(struct system_info *si)
449 {
450 	size_t ssize;
451 	int mib[2];
452 	struct uvmexp_sysctl uvmexp;
453 	struct swapent *sep;
454 	u_int64_t totalsize, totalinuse;
455 	int size, inuse, ncounted, i;
456 	int rnswap, nswap;
457 
458 	mib[0] = CTL_KERN;
459 	mib[1] = KERN_CP_TIME;
460 	ssize = sizeof(cp_time[0]) * CPUSTATES * ncpu;
461 	if (sysctl(mib, 2, cp_time, &ssize, NULL, 0) < 0) {
462 		fprintf(stderr, "top: sysctl kern.cp_time failed: %s\n",
463 		    strerror(errno));
464 		quit(23);
465 	}
466 
467 	if (getloadavg(si->load_avg, NUM_AVERAGES) < 0) {
468 		int j;
469 
470 		warn("can't getloadavg");
471 		for (j = 0; j < NUM_AVERAGES; j++)
472 			si->load_avg[j] = 0.0;
473 	}
474 
475 	/* convert cp_time counts to percentages */
476 	for (i = 0; i < ncpu; i++) {
477 	    int j = i * CPUSTATES;
478 	    percentages64(CPUSTATES, cpu_states + j, cp_time + j, cp_old + j,
479 		cp_diff + j);
480 	}
481 
482 	mib[0] = CTL_VM;
483 	mib[1] = VM_UVMEXP2;
484 	ssize = sizeof(uvmexp);
485 	if (sysctl(mib, 2, &uvmexp, &ssize, NULL, 0) < 0) {
486 		fprintf(stderr, "top: sysctl vm.uvmexp2 failed: %s\n",
487 		    strerror(errno));
488 		quit(23);
489 	}
490 
491 	/* convert memory stats to Kbytes */
492 	memory_stats[0] = pagetok(uvmexp.active);
493 	memory_stats[1] = pagetok(uvmexp.inactive);
494 	memory_stats[2] = pagetok(uvmexp.wired);
495 	memory_stats[3] = pagetok(uvmexp.execpages);
496 	memory_stats[4] = pagetok(uvmexp.filepages);
497 	memory_stats[5] = pagetok(uvmexp.free);
498 
499 	swap_stats[0] = swap_stats[1] = swap_stats[2] = 0;
500 
501 	do {
502 		nswap = swapctl(SWAP_NSWAP, 0, 0);
503 		if (nswap < 1)
504 			break;
505 		if (nswap > maxswap) {
506 			if (swapp)
507 				free(swapp);
508 			swapp = sep = malloc(nswap * sizeof(*sep));
509 			if (sep == NULL)
510 				break;
511 			maxswap = nswap;
512 		} else
513 			sep = swapp;
514 		rnswap = swapctl(SWAP_STATS, (void *)sep, nswap);
515 		if (nswap != rnswap)
516 			break;
517 
518 		totalsize = totalinuse = ncounted = 0;
519 		for (; rnswap-- > 0; sep++) {
520 			ncounted++;
521 			size = sep->se_nblks;
522 			inuse = sep->se_inuse;
523 			totalsize += size;
524 			totalinuse += inuse;
525 		}
526 		swap_stats[0] = dbtob(totalsize) / 1024;
527 		swap_stats[1] = dbtob(totalinuse) / 1024;
528 		swap_stats[2] = dbtob(totalsize) / 1024 - swap_stats[1];
529 	} while (0);
530 
531 	memory_stats[6] = -1;
532 	swap_stats[3] = -1;
533 
534 	/* set arrays and strings */
535 	si->cpustates = cpu_states;
536 	si->memory = memory_stats;
537 	si->swap = swap_stats;
538 	si->last_pid = -1;
539 
540 }
541 
542 static struct kinfo_proc2 *
543 proc_from_thread(struct kinfo_lwp *pl)
544 {
545 	struct kinfo_proc2 *pp = thread_pbase;
546 	int i;
547 
548 	for (i = 0; i < thread_nproc; i++, pp++)
549 		if ((pid_t)pp->p_pid == (pid_t)pl->l_pid)
550 			return pp;
551 	return NULL;
552 }
553 
554 static int
555 uid_from_thread(struct kinfo_lwp *pl)
556 {
557 	struct kinfo_proc2 *pp;
558 
559 	if ((pp = proc_from_thread(pl)) == NULL)
560 		return -1;
561 	return pp->p_ruid;
562 }
563 
564 caddr_t
565 get_process_info(struct system_info *si, struct process_select *sel, int c)
566 {
567 	userprint = sel->usernames ? username : itoa7;
568 
569 	if ((threadmode = sel->threads) != 0)
570 		return get_lwp_info(si, sel, proc_compares[c]);
571 	else
572 		return get_proc_info(si, sel, proc_compares[c]);
573 }
574 
575 static caddr_t
576 get_proc_info(struct system_info *si, struct process_select *sel,
577 	      int (*compare)(struct proc **, struct proc **))
578 {
579 	int i;
580 	int total_procs;
581 	int active_procs;
582 	struct kinfo_proc2 **prefp, **n;
583 	struct kinfo_proc2 *pp;
584 	int op, arg;
585 
586 	/* these are copied out of sel for speed */
587 	int show_idle;
588 	int show_system;
589 	int show_uid;
590 
591 	static struct handle handle;
592 
593 	procgen++;
594 
595 	if (sel->pid == (pid_t)-1) {
596 		op = KERN_PROC_ALL;
597 		arg = 0;
598 	} else {
599 		op = KERN_PROC_PID;
600 		arg = sel->pid;
601 	}
602 
603 	pbase = kvm_getproc2(kd, op, arg, sizeof(struct kinfo_proc2), &nproc);
604 	if (pbase == NULL) {
605 		if (sel->pid != (pid_t)-1) {
606 			nproc = 0;
607 		} else {
608 			(void) fprintf(stderr, "top: Out of memory.\n");
609 			quit(23);
610 		}
611 	}
612 	if (nproc > onproc) {
613 		n = (struct kinfo_proc2 **) realloc(pref,
614 		    sizeof(struct kinfo_proc2 *) * nproc);
615 		if (n == NULL) {
616 			(void) fprintf(stderr, "top: Out of memory.\n");
617 			quit(23);
618 		}
619 		pref = n;
620 		onproc = nproc;
621 	}
622 	/* get a pointer to the states summary array */
623 	si->procstates = process_states;
624 
625 	/* set up flags which define what we are going to select */
626 	show_idle = sel->idle;
627 	show_system = sel->system;
628 	show_uid = sel->uid != -1;
629 
630 	/* count up process states and get pointers to interesting procs */
631 	total_procs = 0;
632 	active_procs = 0;
633 	memset((char *)process_states, 0, sizeof(process_states));
634 	prefp = pref;
635 	for (pp = pbase, i = 0; i < nproc; pp++, i++) {
636 
637 		/*
638 		 * Place pointers to each valid proc structure in pref[].
639 		 * Process slots that are actually in use have a non-zero
640 		 * status field.  Processes with P_SYSTEM set are system
641 		 * processes---these get ignored unless show_sysprocs is set.
642 		 */
643 		if (pp->p_stat != 0 && (show_system || ((pp->p_flag & P_SYSTEM) == 0))) {
644 			total_procs++;
645 			process_states[(unsigned char) pp->p_stat]++;
646 			if (pp->p_stat != LSZOMB &&
647 			    (show_idle || (pp->p_pctcpu != 0) ||
648 			    (pp->p_stat == LSRUN || pp->p_stat == LSONPROC)) &&
649 			    (!show_uid || pp->p_ruid == (uid_t)sel->uid)) {
650 				*prefp++ = pp;
651 				active_procs++;
652 			}
653 		}
654 	}
655 
656 	/* if requested, sort the "interesting" processes */
657 	if (compare != NULL) {
658 		qsort((char *)pref, active_procs, sizeof(struct kinfo_proc2 *),
659 		    (int (*)(const void *, const void *))compare);
660 	}
661 
662 	/* remember active and total counts */
663 	si->p_total = total_procs;
664 	si->p_active = pref_len = active_procs;
665 
666 	/* pass back a handle */
667 	handle.next_proc = pref;
668 	handle.remaining = active_procs;
669 	handle.sel = sel;
670 	return((caddr_t)&handle);
671 }
672 
673 static caddr_t
674 get_lwp_info(struct system_info *si, struct process_select *sel,
675 	     int (*compare)(struct proc **, struct proc **))
676 {
677 	int i;
678 	int total_lwps;
679 	int active_lwps;
680 	struct kinfo_lwp **lrefp, **n;
681 	struct kinfo_lwp *lp;
682 	struct kinfo_proc2 *pp;
683 
684 	/* these are copied out of sel for speed */
685 	int show_idle;
686 	int show_system;
687 	int show_uid;
688 
689 	static struct handle handle;
690 
691 	pp = kvm_getproc2(kd, KERN_PROC_ALL, 0, sizeof(struct kinfo_proc2),
692 	    &thread_nproc);
693 	if (pp == NULL) {
694 		(void) fprintf(stderr, "top: Out of memory.\n");
695 		quit(23);
696 	}
697 	if (thread_pbase == NULL || thread_nproc != thread_onproc) {
698 		free(thread_pbase);
699 		thread_onproc = thread_nproc;
700 		thread_pbase = calloc(sizeof(struct kinfo_proc2), thread_nproc);
701 		if (thread_pbase == NULL) {
702 			(void) fprintf(stderr, "top: Out of memory.\n");
703 			quit(23);
704 		}
705 	}
706 	memcpy(thread_pbase, pp, sizeof(struct kinfo_proc2) * thread_nproc);
707 
708 	lbase = kvm_getlwps(kd, -1, 0, sizeof(struct kinfo_lwp), &nlwp);
709 	if (lbase == NULL) {
710 #ifdef notyet
711 		if (sel->pid != (pid_t)-1) {
712 			nproc = 0;
713 			nlwp = 0;
714 		}
715 		else
716 #endif
717 		{
718 			(void) fprintf(stderr, "top: Out of memory.\n");
719 			quit(23);
720 		}
721 	}
722 	if (nlwp > onlwp) {
723 		n = (struct kinfo_lwp **) realloc(lref,
724 		    sizeof(struct kinfo_lwp *) * nlwp);
725 		if (n == NULL) {
726 			(void) fprintf(stderr, "top: Out of memory.\n");
727 			quit(23);
728 		}
729 		lref = n;
730 		onlwp = nlwp;
731 	}
732 	/* get a pointer to the states summary array */
733 	si->procstates = process_states;
734 
735 	/* set up flags which define what we are going to select */
736 	show_idle = sel->idle;
737 	show_system = sel->system;
738 	show_uid = sel->uid != -1;
739 
740 	/* count up thread states and get pointers to interesting threads */
741 	total_lwps = 0;
742 	active_lwps = 0;
743 	memset((char *)process_states, 0, sizeof(process_states));
744 	lrefp = lref;
745 	for (lp = lbase, i = 0; i < nlwp; lp++, i++) {
746 		if (sel->pid != (pid_t)-1 && sel->pid != (pid_t)lp->l_pid)
747 			continue;
748 
749 		/*
750 		 * Place pointers to each valid lwp structure in lref[].
751 		 * thread slots that are actually in use have a non-zero
752 		 * status field.  threads with L_SYSTEM set are system
753 		 * threads---these get ignored unless show_sysprocs is set.
754 		 */
755 		if (lp->l_stat != 0 && (show_system || ((lp->l_flag & LW_SYSTEM) == 0))) {
756 			total_lwps++;
757 			process_states[(unsigned char) lp->l_stat]++;
758 			if (lp->l_stat != LSZOMB &&
759 			    (show_idle || (lp->l_pctcpu != 0) ||
760 			    (lp->l_stat == LSRUN || lp->l_stat == LSONPROC)) &&
761 			    (!show_uid || uid_from_thread(lp) == sel->uid)) {
762 				*lrefp++ = lp;
763 				active_lwps++;
764 			}
765 		}
766 	}
767 
768 	/* if requested, sort the "interesting" threads */
769 	if (compare != NULL) {
770 		qsort((char *)lref, active_lwps, sizeof(struct kinfo_lwp *),
771 		    (int (*)(const void *, const void *))compare);
772 	}
773 
774 	/* remember active and total counts */
775 	si->p_total = total_lwps;
776 	si->p_active = lref_len = active_lwps;
777 
778 	/* pass back a handle */
779 	handle.next_proc = (struct kinfo_proc2 **)lref;
780 	handle.remaining = active_lwps;
781 	handle.sel = sel;
782 
783 	return((caddr_t)&handle);
784 }
785 
786 char *
787 format_next_process(caddr_t handle, char *(*get_userid)(int))
788 {
789 
790 	if (threadmode)
791 		return format_next_lwp(handle, get_userid);
792 	else
793 		return format_next_proc(handle, get_userid);
794 }
795 
796 
797 char *
798 format_next_proc(caddr_t handle, char *(*get_userid)(int))
799 {
800 	struct kinfo_proc2 *pp;
801 	long cputime;
802 	double pct, wcpu, cpu;
803 	struct handle *hp;
804 	const char *statep;
805 #ifdef KI_NOCPU
806 	char state[10];
807 #endif
808 	char wmesg[KI_WMESGLEN + 1];
809 	static char fmt[MAX_COLS];		/* static area where result is built */
810 
811 	/* find and remember the next proc structure */
812 	hp = (struct handle *)handle;
813 	pp = *(hp->next_proc++);
814 	hp->remaining--;
815 
816 	/* get the process's user struct and set cputime */
817 
818 #if 0
819 	/* This does not produce the correct results */
820 	cputime = pp->p_uticks + pp->p_sticks + pp->p_iticks;
821 #else
822 	cputime = pp->p_rtime_sec;	/* This does not count interrupts */
823 #endif
824 
825 	/* calculate the base for CPU percentages */
826 	pct = pctdouble(pp->p_pctcpu);
827 
828 	if (pp->p_stat == LSSLEEP) {
829 		strlcpy(wmesg, pp->p_wmesg, sizeof(wmesg));
830 		statep = wmesg;
831 	} else
832 		statep = state_abbrev[(unsigned)pp->p_stat];
833 
834 #ifdef KI_NOCPU
835 	/* Post-1.5 change: add CPU number if appropriate */
836 	if (pp->p_cpuid != KI_NOCPU && ncpu > 1) {
837 		switch (pp->p_stat) {
838 		case LSONPROC:
839 		case LSRUN:
840 		case LSSLEEP:
841 		case LSIDL:
842 			(void)snprintf(state, sizeof(state), "%.6s/%u",
843 			     statep, (unsigned int)pp->p_cpuid);
844 			statep = state;
845 			break;
846 		}
847 	}
848 #endif
849 	wcpu = 100.0 * weighted_cpu(p_, pct, pp);
850 	cpu = 100.0 * pct;
851 
852 	/* format this entry */
853 	sprintf(fmt,
854 	    Proc_format,
855 	    pp->p_pid,
856 	    (*userprint)(pp->p_ruid),
857 	    pp->p_priority,
858 	    pp->p_nice - NZERO,
859 	    format_k(pagetok(PROCSIZE(pp))),
860 	    format_k(pagetok(pp->p_vm_rssize)),
861 	    statep,
862 	    format_time(cputime),
863 	    (wcpu >= 100.0) ? 0 : 2, wcpu,
864 	    (cpu >= 100.0) ? 0 : 2, cpu,
865 	    get_command(hp->sel, pp));
866 
867 	/* return the result */
868 	return(fmt);
869 }
870 
871 static char *
872 format_next_lwp(caddr_t handle, char *(*get_userid)(int))
873 {
874 	struct kinfo_proc2 *pp;
875 	struct kinfo_lwp *pl;
876 	long cputime;
877 	double pct;
878 	struct handle *hp;
879 	const char *statep;
880 #ifdef KI_NOCPU
881 	char state[10];
882 #endif
883 	char wmesg[KI_WMESGLEN + 1];
884 	static char fmt[MAX_COLS];		/* static area where result is built */
885 	int uid;
886 
887 	/* find and remember the next proc structure */
888 	hp = (struct handle *)handle;
889 	pl = (struct kinfo_lwp *)*(hp->next_proc++);
890 	hp->remaining--;
891 	pp = proc_from_thread(pl);
892 
893 	/* get the process's user struct and set cputime */
894 	uid = pp ? pp->p_ruid : 0;
895 
896 	cputime = pl->l_rtime_sec;
897 
898 	/* calculate the base for CPU percentages */
899 	pct = pctdouble(pl->l_pctcpu);
900 
901 	if (pl->l_stat == LSSLEEP) {
902 		strlcpy(wmesg, pl->l_wmesg, sizeof(wmesg));
903 		statep = wmesg;
904 	} else
905 		statep = state_abbrev[(unsigned)pl->l_stat];
906 
907 #ifdef KI_NOCPU
908 	/* Post-1.5 change: add CPU number if appropriate */
909 	if (pl->l_cpuid != KI_NOCPU && ncpu > 1) {
910 		switch (pl->l_stat) {
911 		case LSONPROC:
912 		case LSRUN:
913 		case LSSLEEP:
914 		case LSIDL:
915 			(void)snprintf(state, sizeof(state), "%.6s/%u",
916 			     statep, (unsigned int)pl->l_cpuid);
917 			statep = state;
918 			break;
919 		}
920 	}
921 #endif
922 
923 	if (pl->l_name[0] == '\0') {
924 		pl->l_name[0] = '-';
925 		pl->l_name[1] = '\0';
926 	}
927 
928 	/* format this entry */
929 	sprintf(fmt,
930 	    Thread_format,
931 	    pl->l_pid,
932 	    pl->l_lid,
933 	    (*userprint)(uid),
934 	    pl->l_priority,
935 	    statep,
936 	    format_time(cputime),
937 	    100.0 * weighted_cpu(l_, pct, pl),
938 	    100.0 * pct,
939 	    printable(pl->l_name),
940 	    get_command(hp->sel, pp));
941 
942 	/* return the result */
943 	return(fmt);
944 }
945 
946 /* comparison routines for qsort */
947 
948 /*
949  * There are currently four possible comparison routines.  main selects
950  * one of these by indexing in to the array proc_compares.
951  *
952  * Possible keys are defined as macros below.  Currently these keys are
953  * defined:  percent CPU, CPU ticks, process state, resident set size,
954  * total virtual memory usage.  The process states are ordered as follows
955  * (from least to most important):  WAIT, zombie, sleep, stop, start, run.
956  * The array declaration below maps a process state index into a number
957  * that reflects this ordering.
958  */
959 
960 /*
961  * First, the possible comparison keys.  These are defined in such a way
962  * that they can be merely listed in the source code to define the actual
963  * desired ordering.
964  */
965 
966 #define ORDERKEY_PCTCPU(pfx) \
967 	if (lresult = (pctcpu)(p2)->pfx ## pctcpu - (pctcpu)(p1)->pfx ## pctcpu,\
968 	    (result = lresult > 0 ? 1 : lresult < 0 ? -1 : 0) == 0)
969 
970 #define ORDERKEY_CPTICKS(pfx) \
971 	if (lresult = (pctcpu)(p2)->pfx ## rtime_sec \
972 		    - (pctcpu)(p1)->pfx ## rtime_sec,\
973 	    (result = lresult > 0 ? 1 : lresult < 0 ? -1 : 0) == 0)
974 
975 #define ORDERKEY_STATE(pfx) \
976 	if ((result = sorted_state[(int)(p2)->pfx ## stat] - \
977 		      sorted_state[(int)(p1)->pfx ## stat] ) == 0)
978 
979 #define ORDERKEY_PRIO(pfx) \
980 	if ((result = (p2)->pfx ## priority - (p1)->pfx ## priority) == 0)
981 
982 #define ORDERKEY_RSSIZE \
983 	if ((result = p2->p_vm_rssize - p1->p_vm_rssize) == 0)
984 
985 #define ORDERKEY_MEM	\
986 	if ((result = (PROCSIZE(p2) - PROCSIZE(p1))) == 0)
987 #define ORDERKEY_SIZE(v1, v2)	\
988 	if ((result = (v2 - v1)) == 0)
989 
990 /*
991  * Now the array that maps process state to a weight.
992  * The order of the elements should match those in state_abbrev[]
993  */
994 
995 static int sorted_state[] = {
996 	0,	/*  (not used)	  ?	*/
997 	1,	/* "start"	SIDL	*/
998 	4,	/* "run"	SRUN	*/
999 	3,	/* "sleep"	SSLEEP	*/
1000 	3,	/* "stop"	SSTOP	*/
1001 	2,	/* "dead"	SDEAD	*/
1002 	1,	/* "zomb"	SZOMB	*/
1003 	5,	/* "onproc"	SONPROC	*/
1004 };
1005 
1006 /* compare_cpu - the comparison function for sorting by CPU percentage */
1007 
1008 static int
1009 compare_cpu(pp1, pp2)
1010 	struct proc **pp1, **pp2;
1011 {
1012 	int result;
1013 	pctcpu lresult;
1014 
1015 	if (threadmode) {
1016 		struct kinfo_lwp *p1 = *(struct kinfo_lwp **) pp1;
1017 		struct kinfo_lwp *p2 = *(struct kinfo_lwp **) pp2;
1018 
1019 		ORDERKEY_PCTCPU(l_)
1020 		ORDERKEY_CPTICKS(l_)
1021 		ORDERKEY_STATE(l_)
1022 		ORDERKEY_PRIO(l_)
1023 		return result;
1024 	} else {
1025 		struct kinfo_proc2 *p1 = *(struct kinfo_proc2 **) pp1;
1026 		struct kinfo_proc2 *p2 = *(struct kinfo_proc2 **) pp2;
1027 
1028 		ORDERKEY_PCTCPU(p_)
1029 		ORDERKEY_CPTICKS(p_)
1030 		ORDERKEY_STATE(p_)
1031 		ORDERKEY_PRIO(p_)
1032 		ORDERKEY_RSSIZE
1033 		ORDERKEY_MEM
1034 		return result;
1035 	}
1036 
1037 	return (result);
1038 }
1039 
1040 /* compare_prio - the comparison function for sorting by process priority */
1041 
1042 static int
1043 compare_prio(pp1, pp2)
1044 	struct proc **pp1, **pp2;
1045 {
1046 	int result;
1047 	pctcpu lresult;
1048 
1049 	if (threadmode) {
1050 		struct kinfo_lwp *p1 = *(struct kinfo_lwp **) pp1;
1051 		struct kinfo_lwp *p2 = *(struct kinfo_lwp **) pp2;
1052 
1053 		ORDERKEY_PRIO(l_)
1054 		ORDERKEY_PCTCPU(l_)
1055 		ORDERKEY_CPTICKS(l_)
1056 		ORDERKEY_STATE(l_)
1057 		return result;
1058 	} else {
1059 		struct kinfo_proc2 *p1 = *(struct kinfo_proc2 **) pp1;
1060 		struct kinfo_proc2 *p2 = *(struct kinfo_proc2 **) pp2;
1061 
1062 		ORDERKEY_PRIO(p_)
1063 		ORDERKEY_PCTCPU(p_)
1064 		ORDERKEY_CPTICKS(p_)
1065 		ORDERKEY_STATE(p_)
1066 		ORDERKEY_RSSIZE
1067 		ORDERKEY_MEM
1068 		return result;
1069 	}
1070 
1071 	return (result);
1072 }
1073 
1074 /* compare_res - the comparison function for sorting by resident set size */
1075 
1076 static int
1077 compare_res(pp1, pp2)
1078 	struct proc **pp1, **pp2;
1079 {
1080 	int result;
1081 	pctcpu lresult;
1082 
1083 	if (threadmode) {
1084 		struct kinfo_lwp *p1 = *(struct kinfo_lwp **) pp1;
1085 		struct kinfo_lwp *p2 = *(struct kinfo_lwp **) pp2;
1086 
1087 		ORDERKEY_PCTCPU(l_)
1088 		ORDERKEY_CPTICKS(l_)
1089 		ORDERKEY_STATE(l_)
1090 		ORDERKEY_PRIO(l_)
1091 		return result;
1092 	} else {
1093 		struct kinfo_proc2 *p1 = *(struct kinfo_proc2 **) pp1;
1094 		struct kinfo_proc2 *p2 = *(struct kinfo_proc2 **) pp2;
1095 
1096 		ORDERKEY_RSSIZE
1097 		ORDERKEY_MEM
1098 		ORDERKEY_PCTCPU(p_)
1099 		ORDERKEY_CPTICKS(p_)
1100 		ORDERKEY_STATE(p_)
1101 		ORDERKEY_PRIO(p_)
1102 		return result;
1103 	}
1104 
1105 	return (result);
1106 }
1107 
1108 static int
1109 compare_pid(pp1, pp2)
1110 	struct proc **pp1, **pp2;
1111 {
1112 	if (threadmode) {
1113 		struct kinfo_lwp *l1 = *(struct kinfo_lwp **) pp1;
1114 		struct kinfo_lwp *l2 = *(struct kinfo_lwp **) pp2;
1115 		struct kinfo_proc2 *p1 = proc_from_thread(l1);
1116 		struct kinfo_proc2 *p2 = proc_from_thread(l2);
1117 		return p2->p_pid - p1->p_pid;
1118 	} else {
1119 		struct kinfo_proc2 *p1 = *(struct kinfo_proc2 **) pp1;
1120 		struct kinfo_proc2 *p2 = *(struct kinfo_proc2 **) pp2;
1121 		return p2->p_pid - p1->p_pid;
1122 	}
1123 }
1124 
1125 static int
1126 compare_command(pp1, pp2)
1127 	struct proc **pp1, **pp2;
1128 {
1129 	if (threadmode) {
1130 		struct kinfo_lwp *l1 = *(struct kinfo_lwp **) pp1;
1131 		struct kinfo_lwp *l2 = *(struct kinfo_lwp **) pp2;
1132 		struct kinfo_proc2 *p1 = proc_from_thread(l1);
1133 		struct kinfo_proc2 *p2 = proc_from_thread(l2);
1134 		return strcmp(p2->p_comm, p1->p_comm);
1135 	} else {
1136 		struct kinfo_proc2 *p1 = *(struct kinfo_proc2 **) pp1;
1137 		struct kinfo_proc2 *p2 = *(struct kinfo_proc2 **) pp2;
1138 		return strcmp(p2->p_comm, p1->p_comm);
1139 	}
1140 }
1141 
1142 static int
1143 compare_username(pp1, pp2)
1144 	struct proc **pp1, **pp2;
1145 {
1146 	if (threadmode) {
1147 		struct kinfo_lwp *l1 = *(struct kinfo_lwp **) pp1;
1148 		struct kinfo_lwp *l2 = *(struct kinfo_lwp **) pp2;
1149 		struct kinfo_proc2 *p1 = proc_from_thread(l1);
1150 		struct kinfo_proc2 *p2 = proc_from_thread(l2);
1151 		return strcmp(p2->p_login, p1->p_login);
1152 	} else {
1153 		struct kinfo_proc2 *p1 = *(struct kinfo_proc2 **) pp1;
1154 		struct kinfo_proc2 *p2 = *(struct kinfo_proc2 **) pp2;
1155 		return strcmp(p2->p_login, p1->p_login);
1156 	}
1157 }
1158 /* compare_size - the comparison function for sorting by total memory usage */
1159 
1160 static int
1161 compare_size(pp1, pp2)
1162 	struct proc **pp1, **pp2;
1163 {
1164 	int result;
1165 	pctcpu lresult;
1166 
1167 	if (threadmode) {
1168 		struct kinfo_lwp *p1 = *(struct kinfo_lwp **) pp1;
1169 		struct kinfo_lwp *p2 = *(struct kinfo_lwp **) pp2;
1170 
1171 		ORDERKEY_PCTCPU(l_)
1172 		ORDERKEY_CPTICKS(l_)
1173 		ORDERKEY_STATE(l_)
1174 		ORDERKEY_PRIO(l_)
1175 		return result;
1176 	} else {
1177 		struct kinfo_proc2 *p1 = *(struct kinfo_proc2 **) pp1;
1178 		struct kinfo_proc2 *p2 = *(struct kinfo_proc2 **) pp2;
1179 
1180 		ORDERKEY_MEM
1181 		ORDERKEY_RSSIZE
1182 		ORDERKEY_PCTCPU(p_)
1183 		ORDERKEY_CPTICKS(p_)
1184 		ORDERKEY_STATE(p_)
1185 		ORDERKEY_PRIO(p_)
1186 		return result;
1187 	}
1188 
1189 	return (result);
1190 }
1191 
1192 /* compare_state - the comparison function for sorting by process state */
1193 
1194 static int
1195 compare_state(pp1, pp2)
1196 	struct proc **pp1, **pp2;
1197 {
1198 	int result;
1199 	pctcpu lresult;
1200 
1201 	if (threadmode) {
1202 		struct kinfo_lwp *p1 = *(struct kinfo_lwp **) pp1;
1203 		struct kinfo_lwp *p2 = *(struct kinfo_lwp **) pp2;
1204 
1205 		ORDERKEY_STATE(l_)
1206 		ORDERKEY_PCTCPU(l_)
1207 		ORDERKEY_CPTICKS(l_)
1208 		ORDERKEY_PRIO(l_)
1209 		return result;
1210 	} else {
1211 		struct kinfo_proc2 *p1 = *(struct kinfo_proc2 **) pp1;
1212 		struct kinfo_proc2 *p2 = *(struct kinfo_proc2 **) pp2;
1213 
1214 		ORDERKEY_STATE(p_)
1215 		ORDERKEY_PCTCPU(p_)
1216 		ORDERKEY_CPTICKS(p_)
1217 		ORDERKEY_PRIO(p_)
1218 		ORDERKEY_RSSIZE
1219 		ORDERKEY_MEM
1220 		return result;
1221 	}
1222 
1223 	return (result);
1224 }
1225 
1226 /* compare_time - the comparison function for sorting by total CPU time */
1227 
1228 static int
1229 compare_time(pp1, pp2)
1230 	struct proc **pp1, **pp2;
1231 {
1232 	int result;
1233 	pctcpu lresult;
1234 
1235 	if (threadmode) {
1236 		struct kinfo_lwp *p1 = *(struct kinfo_lwp **) pp1;
1237 		struct kinfo_lwp *p2 = *(struct kinfo_lwp **) pp2;
1238 
1239 		ORDERKEY_CPTICKS(l_)
1240 		ORDERKEY_PCTCPU(l_)
1241 		ORDERKEY_STATE(l_)
1242 		ORDERKEY_PRIO(l_)
1243 		return result;
1244 	} else {
1245 		struct kinfo_proc2 *p1 = *(struct kinfo_proc2 **) pp1;
1246 		struct kinfo_proc2 *p2 = *(struct kinfo_proc2 **) pp2;
1247 
1248 		ORDERKEY_CPTICKS(p_)
1249 		ORDERKEY_PCTCPU(p_)
1250 		ORDERKEY_STATE(p_)
1251 		ORDERKEY_PRIO(p_)
1252 		ORDERKEY_MEM
1253 		ORDERKEY_RSSIZE
1254 		return result;
1255 	}
1256 
1257 	return (result);
1258 }
1259 
1260 
1261 /*
1262  * proc_owner(pid) - returns the uid that owns process "pid", or -1 if
1263  *		the process does not exist.
1264  *		It is EXTREMLY IMPORTANT that this function work correctly.
1265  *		If top runs setuid root (as in SVR4), then this function
1266  *		is the only thing that stands in the way of a serious
1267  *		security problem.  It validates requests for the "kill"
1268  *		and "renice" commands.
1269  */
1270 
1271 int
1272 proc_owner(pid)
1273 	int pid;
1274 {
1275 	int cnt;
1276 	struct kinfo_proc2 **prefp;
1277 	struct kinfo_proc2 *pp;
1278 
1279 	if (threadmode)
1280 		return(-1);
1281 
1282 	prefp = pref;
1283 	cnt = pref_len;
1284 	while (--cnt >= 0) {
1285 		pp = *prefp++;
1286 		if (pp->p_pid == (pid_t)pid)
1287 			return(pp->p_ruid);
1288 	}
1289 	return(-1);
1290 }
1291 
1292 /*
1293  *  percentages(cnt, out, new, old, diffs) - calculate percentage change
1294  *	between array "old" and "new", putting the percentages i "out".
1295  *	"cnt" is size of each array and "diffs" is used for scratch space.
1296  *	The array "old" is updated on each call.
1297  *	The routine assumes modulo arithmetic.  This function is especially
1298  *	useful on BSD mchines for calculating CPU state percentages.
1299  */
1300 
1301 static void
1302 percentages64(cnt, out, new, old, diffs)
1303 	int cnt;
1304 	int *out;
1305 	u_int64_t *new;
1306 	u_int64_t *old;
1307 	u_int64_t *diffs;
1308 {
1309 	int i;
1310 	u_int64_t change;
1311 	u_int64_t total_change;
1312 	u_int64_t *dp;
1313 	u_int64_t half_total;
1314 
1315 	/* initialization */
1316 	total_change = 0;
1317 	dp = diffs;
1318 
1319 	/* calculate changes for each state and the overall change */
1320 	for (i = 0; i < cnt; i++) {
1321 		/*
1322 		 * Don't worry about wrapping - even at hz=1GHz, a
1323 		 * u_int64_t will last at least 544 years.
1324 		 */
1325 		change = *new - *old;
1326 		total_change += (*dp++ = change);
1327 		*old++ = *new++;
1328 	}
1329 
1330 	/* avoid divide by zero potential */
1331 	if (total_change == 0)
1332 		total_change = 1;
1333 
1334 	/* calculate percentages based on overall change, rounding up */
1335 	half_total = total_change / 2;
1336 	for (i = 0; i < cnt; i++)
1337 		*out++ = (int)((*diffs++ * 1000 + half_total) / total_change);
1338 }
1339