xref: /illumos-gate/usr/src/lib/libdtrace/common/dt_aggregate.c (revision a07094369b21309434206d9b3601d162693466fc)
1 /*
2  * CDDL HEADER START
3  *
4  * The contents of this file are subject to the terms of the
5  * Common Development and Distribution License, Version 1.0 only
6  * (the "License").  You may not use this file except in compliance
7  * with the License.
8  *
9  * You can obtain a copy of the license at usr/src/OPENSOLARIS.LICENSE
10  * or http://www.opensolaris.org/os/licensing.
11  * See the License for the specific language governing permissions
12  * and limitations under the License.
13  *
14  * When distributing Covered Code, include this CDDL HEADER in each
15  * file and include the License file at usr/src/OPENSOLARIS.LICENSE.
16  * If applicable, add the following below this CDDL HEADER, with the
17  * fields enclosed by brackets "[]" replaced with your own identifying
18  * information: Portions Copyright [yyyy] [name of copyright owner]
19  *
20  * CDDL HEADER END
21  */
22 /*
23  * Copyright 2005 Sun Microsystems, Inc.  All rights reserved.
24  * Use is subject to license terms.
25  */
26 
27 #pragma ident	"%Z%%M%	%I%	%E% SMI"
28 
29 #include <stdlib.h>
30 #include <strings.h>
31 #include <errno.h>
32 #include <unistd.h>
33 #include <dt_impl.h>
34 #include <assert.h>
35 #include <alloca.h>
36 #include <limits.h>
37 
38 #define	DTRACE_AHASHSIZE	32779		/* big 'ol prime */
39 
40 /*
41  * Because qsort(3C) does not allow an argument to be passed to a comparison
42  * function, the variables that affect comparison must regrettably be global;
43  * they are protected by a global static lock, dt_qsort_lock.
44  */
45 static pthread_mutex_t dt_qsort_lock = PTHREAD_MUTEX_INITIALIZER;
46 
47 static int dt_revsort;
48 static int dt_keysort;
49 static int dt_keypos;
50 
51 #define	DT_LESSTHAN	(dt_revsort == 0 ? -1 : 1)
52 #define	DT_GREATERTHAN	(dt_revsort == 0 ? 1 : -1)
53 
54 static void
55 dt_aggregate_count(int64_t *existing, int64_t *new, size_t size)
56 {
57 	int i;
58 
59 	for (i = 0; i < size / sizeof (int64_t); i++)
60 		existing[i] = existing[i] + new[i];
61 }
62 
63 static int
64 dt_aggregate_countcmp(int64_t *lhs, int64_t *rhs)
65 {
66 	int64_t lvar = *lhs;
67 	int64_t rvar = *rhs;
68 
69 	if (lvar < rvar)
70 		return (DT_LESSTHAN);
71 
72 	if (lvar > rvar)
73 		return (DT_GREATERTHAN);
74 
75 	return (0);
76 }
77 
78 /*ARGSUSED*/
79 static void
80 dt_aggregate_min(int64_t *existing, int64_t *new, size_t size)
81 {
82 	if (*new < *existing)
83 		*existing = *new;
84 }
85 
86 /*ARGSUSED*/
87 static void
88 dt_aggregate_max(int64_t *existing, int64_t *new, size_t size)
89 {
90 	if (*new > *existing)
91 		*existing = *new;
92 }
93 
94 static int
95 dt_aggregate_averagecmp(int64_t *lhs, int64_t *rhs)
96 {
97 	int64_t lavg = lhs[0] ? (lhs[1] / lhs[0]) : 0;
98 	int64_t ravg = rhs[0] ? (rhs[1] / rhs[0]) : 0;
99 
100 	if (lavg < ravg)
101 		return (DT_LESSTHAN);
102 
103 	if (lavg > ravg)
104 		return (DT_GREATERTHAN);
105 
106 	return (0);
107 }
108 
109 /*ARGSUSED*/
110 static void
111 dt_aggregate_lquantize(int64_t *existing, int64_t *new, size_t size)
112 {
113 	int64_t arg = *existing++;
114 	uint16_t levels = DTRACE_LQUANTIZE_LEVELS(arg);
115 	int i;
116 
117 	for (i = 0; i <= levels + 1; i++)
118 		existing[i] = existing[i] + new[i + 1];
119 }
120 
121 static long double
122 dt_aggregate_lquantizedsum(int64_t *lquanta)
123 {
124 	int64_t arg = *lquanta++;
125 	int32_t base = DTRACE_LQUANTIZE_BASE(arg);
126 	uint16_t step = DTRACE_LQUANTIZE_STEP(arg);
127 	uint16_t levels = DTRACE_LQUANTIZE_LEVELS(arg), i;
128 	long double total = (long double)lquanta[0] * (long double)(base - 1);
129 
130 	for (i = 0; i < levels; base += step, i++)
131 		total += (long double)lquanta[i + 1] * (long double)base;
132 
133 	return (total + (long double)lquanta[levels + 1] *
134 	    (long double)(base + 1));
135 }
136 
137 static int64_t
138 dt_aggregate_lquantizedzero(int64_t *lquanta)
139 {
140 	int64_t arg = *lquanta++;
141 	int32_t base = DTRACE_LQUANTIZE_BASE(arg);
142 	uint16_t step = DTRACE_LQUANTIZE_STEP(arg);
143 	uint16_t levels = DTRACE_LQUANTIZE_LEVELS(arg), i;
144 
145 	if (base - 1 == 0)
146 		return (lquanta[0]);
147 
148 	for (i = 0; i < levels; base += step, i++) {
149 		if (base != 0)
150 			continue;
151 
152 		return (lquanta[i + 1]);
153 	}
154 
155 	if (base + 1 == 0)
156 		return (lquanta[levels + 1]);
157 
158 	return (0);
159 }
160 
161 static int
162 dt_aggregate_lquantizedcmp(int64_t *lhs, int64_t *rhs)
163 {
164 	long double lsum = dt_aggregate_lquantizedsum(lhs);
165 	long double rsum = dt_aggregate_lquantizedsum(rhs);
166 	int64_t lzero, rzero;
167 
168 	if (lsum < rsum)
169 		return (DT_LESSTHAN);
170 
171 	if (lsum > rsum)
172 		return (DT_GREATERTHAN);
173 
174 	/*
175 	 * If they're both equal, then we will compare based on the weights at
176 	 * zero.  If the weights at zero are equal (or if zero is not within
177 	 * the range of the linear quantization), then this will be judged a
178 	 * tie and will be resolved based on the key comparison.
179 	 */
180 	lzero = dt_aggregate_lquantizedzero(lhs);
181 	rzero = dt_aggregate_lquantizedzero(rhs);
182 
183 	if (lzero < rzero)
184 		return (DT_LESSTHAN);
185 
186 	if (lzero > rzero)
187 		return (DT_GREATERTHAN);
188 
189 	return (0);
190 }
191 
192 static int
193 dt_aggregate_quantizedcmp(int64_t *lhs, int64_t *rhs)
194 {
195 	int nbuckets = DTRACE_QUANTIZE_NBUCKETS, i;
196 	long double ltotal = 0, rtotal = 0;
197 	int64_t lzero, rzero;
198 
199 	for (i = 0; i < nbuckets; i++) {
200 		int64_t bucketval = DTRACE_QUANTIZE_BUCKETVAL(i);
201 
202 		if (bucketval == 0) {
203 			lzero = lhs[i];
204 			rzero = rhs[i];
205 		}
206 
207 		ltotal += (long double)bucketval * (long double)lhs[i];
208 		rtotal += (long double)bucketval * (long double)rhs[i];
209 	}
210 
211 	if (ltotal < rtotal)
212 		return (DT_LESSTHAN);
213 
214 	if (ltotal > rtotal)
215 		return (DT_GREATERTHAN);
216 
217 	/*
218 	 * If they're both equal, then we will compare based on the weights at
219 	 * zero.  If the weights at zero are equal, then this will be judged a
220 	 * tie and will be resolved based on the key comparison.
221 	 */
222 	if (lzero < rzero)
223 		return (DT_LESSTHAN);
224 
225 	if (lzero > rzero)
226 		return (DT_GREATERTHAN);
227 
228 	return (0);
229 }
230 
231 static void
232 dt_aggregate_usym(dtrace_hdl_t *dtp, uint64_t *data)
233 {
234 	uint64_t pid = data[0];
235 	uint64_t *pc = &data[1];
236 	struct ps_prochandle *P;
237 	GElf_Sym sym;
238 
239 	if (dtp->dt_vector != NULL)
240 		return;
241 
242 	if ((P = dt_proc_grab(dtp, pid, PGRAB_RDONLY | PGRAB_FORCE, 0)) == NULL)
243 		return;
244 
245 	dt_proc_lock(dtp, P);
246 
247 	if (Plookup_by_addr(P, *pc, NULL, 0, &sym) == 0)
248 		*pc = sym.st_value;
249 
250 	dt_proc_unlock(dtp, P);
251 	dt_proc_release(dtp, P);
252 }
253 
254 static void
255 dt_aggregate_umod(dtrace_hdl_t *dtp, uint64_t *data)
256 {
257 	uint64_t pid = data[0];
258 	uint64_t *pc = &data[1];
259 	struct ps_prochandle *P;
260 	const prmap_t *map;
261 
262 	if (dtp->dt_vector != NULL)
263 		return;
264 
265 	if ((P = dt_proc_grab(dtp, pid, PGRAB_RDONLY | PGRAB_FORCE, 0)) == NULL)
266 		return;
267 
268 	dt_proc_lock(dtp, P);
269 
270 	if ((map = Paddr_to_map(P, *pc)) != NULL)
271 		*pc = map->pr_vaddr;
272 
273 	dt_proc_unlock(dtp, P);
274 	dt_proc_release(dtp, P);
275 }
276 
277 static void
278 dt_aggregate_sym(dtrace_hdl_t *dtp, uint64_t *data)
279 {
280 	GElf_Sym sym;
281 	uint64_t *pc = data;
282 
283 	if (dtrace_lookup_by_addr(dtp, *pc, &sym, NULL) == 0)
284 		*pc = sym.st_value;
285 }
286 
287 static void
288 dt_aggregate_mod(dtrace_hdl_t *dtp, uint64_t *data)
289 {
290 	uint64_t *pc = data;
291 	dt_module_t *dmp;
292 
293 	if (dtp->dt_vector != NULL) {
294 		/*
295 		 * We don't have a way of just getting the module for a
296 		 * vectored open, and it doesn't seem to be worth defining
297 		 * one.  This means that use of mod() won't get true
298 		 * aggregation in the postmortem case (some modules may
299 		 * appear more than once in aggregation output).  It seems
300 		 * unlikely that anyone will ever notice or care...
301 		 */
302 		return;
303 	}
304 
305 	for (dmp = dt_list_next(&dtp->dt_modlist); dmp != NULL;
306 	    dmp = dt_list_next(dmp)) {
307 		if (*pc - dmp->dm_text_va < dmp->dm_text_size) {
308 			*pc = dmp->dm_text_va;
309 			return;
310 		}
311 	}
312 }
313 
314 static dtrace_aggvarid_t
315 dt_aggregate_aggvarid(dt_ahashent_t *ent)
316 {
317 	dtrace_aggdesc_t *agg = ent->dtahe_data.dtada_desc;
318 	caddr_t data = ent->dtahe_data.dtada_data;
319 	dtrace_recdesc_t *rec = agg->dtagd_rec;
320 
321 	/*
322 	 * First, we'll check the variable ID in the aggdesc.  If it's valid,
323 	 * we'll return it.  If not, we'll use the compiler-generated ID
324 	 * present as the first record.
325 	 */
326 	if (agg->dtagd_varid != DTRACE_AGGVARIDNONE)
327 		return (agg->dtagd_varid);
328 
329 	agg->dtagd_varid = *((dtrace_aggvarid_t *)(uintptr_t)(data +
330 	    rec->dtrd_offset));
331 
332 	return (agg->dtagd_varid);
333 }
334 
335 
336 static int
337 dt_aggregate_snap_cpu(dtrace_hdl_t *dtp, processorid_t cpu)
338 {
339 	dtrace_epid_t id;
340 	uint64_t hashval;
341 	size_t offs, roffs, size, ndx;
342 	int i, j, rval;
343 	caddr_t addr, data;
344 	dtrace_recdesc_t *rec;
345 	dt_aggregate_t *agp = &dtp->dt_aggregate;
346 	dtrace_aggdesc_t *agg;
347 	dt_ahash_t *hash = &agp->dtat_hash;
348 	dt_ahashent_t *h;
349 	dtrace_bufdesc_t b = agp->dtat_buf, *buf = &b;
350 	dtrace_aggdata_t *aggdata;
351 	int flags = agp->dtat_flags;
352 
353 	buf->dtbd_cpu = cpu;
354 
355 	if (dt_ioctl(dtp, DTRACEIOC_AGGSNAP, buf) == -1) {
356 		if (errno == ENOENT) {
357 			/*
358 			 * If that failed with ENOENT, it may be because the
359 			 * CPU was unconfigured.  This is okay; we'll just
360 			 * do nothing but return success.
361 			 */
362 			return (0);
363 		}
364 
365 		return (dt_set_errno(dtp, errno));
366 	}
367 
368 	if (buf->dtbd_drops != 0) {
369 		if (dt_handle_cpudrop(dtp, cpu,
370 		    DTRACEDROP_AGGREGATION, buf->dtbd_drops) == -1)
371 			return (-1);
372 	}
373 
374 	if (buf->dtbd_size == 0)
375 		return (0);
376 
377 	if (hash->dtah_hash == NULL) {
378 		size_t size;
379 
380 		hash->dtah_size = DTRACE_AHASHSIZE;
381 		size = hash->dtah_size * sizeof (dt_ahashent_t *);
382 
383 		if ((hash->dtah_hash = malloc(size)) == NULL)
384 			return (dt_set_errno(dtp, EDT_NOMEM));
385 
386 		bzero(hash->dtah_hash, size);
387 	}
388 
389 	for (offs = 0; offs < buf->dtbd_size; ) {
390 		/*
391 		 * We're guaranteed to have an ID.
392 		 */
393 		id = *((dtrace_epid_t *)((uintptr_t)buf->dtbd_data +
394 		    (uintptr_t)offs));
395 
396 		if (id == DTRACE_AGGIDNONE) {
397 			/*
398 			 * This is filler to assure proper alignment of the
399 			 * next record; we simply ignore it.
400 			 */
401 			offs += sizeof (id);
402 			continue;
403 		}
404 
405 		if ((rval = dt_aggid_lookup(dtp, id, &agg)) != 0)
406 			return (rval);
407 
408 		addr = buf->dtbd_data + offs;
409 		size = agg->dtagd_size;
410 		hashval = 0;
411 
412 		for (j = 0; j < agg->dtagd_nrecs - 1; j++) {
413 			rec = &agg->dtagd_rec[j];
414 			roffs = rec->dtrd_offset;
415 
416 			switch (rec->dtrd_action) {
417 			case DTRACEACT_USYM:
418 				dt_aggregate_usym(dtp,
419 				    /* LINTED - alignment */
420 				    (uint64_t *)&addr[roffs]);
421 				break;
422 
423 			case DTRACEACT_UMOD:
424 				dt_aggregate_umod(dtp,
425 				    /* LINTED - alignment */
426 				    (uint64_t *)&addr[roffs]);
427 				break;
428 
429 			case DTRACEACT_SYM:
430 				/* LINTED - alignment */
431 				dt_aggregate_sym(dtp, (uint64_t *)&addr[roffs]);
432 				break;
433 
434 			case DTRACEACT_MOD:
435 				/* LINTED - alignment */
436 				dt_aggregate_mod(dtp, (uint64_t *)&addr[roffs]);
437 				break;
438 
439 			default:
440 				break;
441 			}
442 
443 			for (i = 0; i < rec->dtrd_size; i++)
444 				hashval += addr[roffs + i];
445 		}
446 
447 		ndx = hashval % hash->dtah_size;
448 
449 		for (h = hash->dtah_hash[ndx]; h != NULL; h = h->dtahe_next) {
450 			if (h->dtahe_hashval != hashval)
451 				continue;
452 
453 			if (h->dtahe_size != size)
454 				continue;
455 
456 			aggdata = &h->dtahe_data;
457 			data = aggdata->dtada_data;
458 
459 			for (j = 0; j < agg->dtagd_nrecs - 1; j++) {
460 				rec = &agg->dtagd_rec[j];
461 				roffs = rec->dtrd_offset;
462 
463 				for (i = 0; i < rec->dtrd_size; i++)
464 					if (addr[roffs + i] != data[roffs + i])
465 						goto hashnext;
466 			}
467 
468 			/*
469 			 * We found it.  Now we need to apply the aggregating
470 			 * action on the data here.
471 			 */
472 			rec = &agg->dtagd_rec[agg->dtagd_nrecs - 1];
473 			roffs = rec->dtrd_offset;
474 			/* LINTED - alignment */
475 			h->dtahe_aggregate((int64_t *)&data[roffs],
476 			    /* LINTED - alignment */
477 			    (int64_t *)&addr[roffs], rec->dtrd_size);
478 
479 			/*
480 			 * If we're keeping per CPU data, apply the aggregating
481 			 * action there as well.
482 			 */
483 			if (aggdata->dtada_percpu != NULL) {
484 				data = aggdata->dtada_percpu[cpu];
485 
486 				/* LINTED - alignment */
487 				h->dtahe_aggregate((int64_t *)data,
488 				    /* LINTED - alignment */
489 				    (int64_t *)&addr[roffs], rec->dtrd_size);
490 			}
491 
492 			goto bufnext;
493 hashnext:
494 			continue;
495 		}
496 
497 		/*
498 		 * If we're here, we couldn't find an entry for this record.
499 		 */
500 		if ((h = malloc(sizeof (dt_ahashent_t))) == NULL)
501 			return (dt_set_errno(dtp, EDT_NOMEM));
502 		bzero(h, sizeof (dt_ahashent_t));
503 		aggdata = &h->dtahe_data;
504 
505 		if ((aggdata->dtada_data = malloc(size)) == NULL) {
506 			free(h);
507 			return (dt_set_errno(dtp, EDT_NOMEM));
508 		}
509 
510 		bcopy(addr, aggdata->dtada_data, size);
511 		aggdata->dtada_size = size;
512 		aggdata->dtada_desc = agg;
513 		aggdata->dtada_handle = dtp;
514 		(void) dt_epid_lookup(dtp, agg->dtagd_epid,
515 		    &aggdata->dtada_edesc, &aggdata->dtada_pdesc);
516 		aggdata->dtada_normal = 1;
517 
518 		h->dtahe_hashval = hashval;
519 		h->dtahe_size = size;
520 		(void) dt_aggregate_aggvarid(h);
521 
522 		rec = &agg->dtagd_rec[agg->dtagd_nrecs - 1];
523 
524 		if (flags & DTRACE_A_PERCPU) {
525 			int max_cpus = agp->dtat_maxcpu;
526 			caddr_t *percpu = malloc(max_cpus * sizeof (caddr_t));
527 
528 			if (percpu == NULL) {
529 				free(aggdata->dtada_data);
530 				free(h);
531 				return (dt_set_errno(dtp, EDT_NOMEM));
532 			}
533 
534 			for (j = 0; j < max_cpus; j++) {
535 				percpu[j] = malloc(rec->dtrd_size);
536 
537 				if (percpu[j] == NULL) {
538 					while (--j >= 0)
539 						free(percpu[j]);
540 
541 					free(aggdata->dtada_data);
542 					free(h);
543 					return (dt_set_errno(dtp, EDT_NOMEM));
544 				}
545 
546 				if (j == cpu) {
547 					bcopy(&addr[rec->dtrd_offset],
548 					    percpu[j], rec->dtrd_size);
549 				} else {
550 					bzero(percpu[j], rec->dtrd_size);
551 				}
552 			}
553 
554 			aggdata->dtada_percpu = percpu;
555 		}
556 
557 		switch (rec->dtrd_action) {
558 		case DTRACEAGG_MIN:
559 			h->dtahe_aggregate = dt_aggregate_min;
560 			break;
561 
562 		case DTRACEAGG_MAX:
563 			h->dtahe_aggregate = dt_aggregate_max;
564 			break;
565 
566 		case DTRACEAGG_LQUANTIZE:
567 			h->dtahe_aggregate = dt_aggregate_lquantize;
568 			break;
569 
570 		case DTRACEAGG_COUNT:
571 		case DTRACEAGG_SUM:
572 		case DTRACEAGG_AVG:
573 		case DTRACEAGG_QUANTIZE:
574 			h->dtahe_aggregate = dt_aggregate_count;
575 			break;
576 
577 		default:
578 			return (dt_set_errno(dtp, EDT_BADAGG));
579 		}
580 
581 		if (hash->dtah_hash[ndx] != NULL)
582 			hash->dtah_hash[ndx]->dtahe_prev = h;
583 
584 		h->dtahe_next = hash->dtah_hash[ndx];
585 		hash->dtah_hash[ndx] = h;
586 
587 		if (hash->dtah_all != NULL)
588 			hash->dtah_all->dtahe_prevall = h;
589 
590 		h->dtahe_nextall = hash->dtah_all;
591 		hash->dtah_all = h;
592 bufnext:
593 		offs += agg->dtagd_size;
594 	}
595 
596 	return (0);
597 }
598 
599 int
600 dtrace_aggregate_snap(dtrace_hdl_t *dtp)
601 {
602 	int i, rval;
603 	dt_aggregate_t *agp = &dtp->dt_aggregate;
604 	hrtime_t now = gethrtime();
605 	dtrace_optval_t interval = dtp->dt_options[DTRACEOPT_AGGRATE];
606 
607 	if (dtp->dt_lastagg != 0) {
608 		if (now - dtp->dt_lastagg < interval)
609 			return (0);
610 
611 		dtp->dt_lastagg += interval;
612 	} else {
613 		dtp->dt_lastagg = now;
614 	}
615 
616 	if (!dtp->dt_active)
617 		return (dt_set_errno(dtp, EINVAL));
618 
619 	if (agp->dtat_buf.dtbd_size == 0)
620 		return (0);
621 
622 	for (i = 0; i < agp->dtat_ncpus; i++) {
623 		if (rval = dt_aggregate_snap_cpu(dtp, agp->dtat_cpus[i]))
624 			return (rval);
625 	}
626 
627 	return (0);
628 }
629 
630 static int
631 dt_aggregate_hashcmp(const void *lhs, const void *rhs)
632 {
633 	dt_ahashent_t *lh = *((dt_ahashent_t **)lhs);
634 	dt_ahashent_t *rh = *((dt_ahashent_t **)rhs);
635 	dtrace_aggdesc_t *lagg = lh->dtahe_data.dtada_desc;
636 	dtrace_aggdesc_t *ragg = rh->dtahe_data.dtada_desc;
637 
638 	if (lagg->dtagd_nrecs < ragg->dtagd_nrecs)
639 		return (DT_LESSTHAN);
640 
641 	if (lagg->dtagd_nrecs > ragg->dtagd_nrecs)
642 		return (DT_GREATERTHAN);
643 
644 	return (0);
645 }
646 
647 static int
648 dt_aggregate_varcmp(const void *lhs, const void *rhs)
649 {
650 	dt_ahashent_t *lh = *((dt_ahashent_t **)lhs);
651 	dt_ahashent_t *rh = *((dt_ahashent_t **)rhs);
652 	dtrace_aggvarid_t lid, rid;
653 
654 	lid = dt_aggregate_aggvarid(lh);
655 	rid = dt_aggregate_aggvarid(rh);
656 
657 	if (lid < rid)
658 		return (DT_LESSTHAN);
659 
660 	if (lid > rid)
661 		return (DT_GREATERTHAN);
662 
663 	return (0);
664 }
665 
666 static int
667 dt_aggregate_keycmp(const void *lhs, const void *rhs)
668 {
669 	dt_ahashent_t *lh = *((dt_ahashent_t **)lhs);
670 	dt_ahashent_t *rh = *((dt_ahashent_t **)rhs);
671 	dtrace_aggdesc_t *lagg = lh->dtahe_data.dtada_desc;
672 	dtrace_aggdesc_t *ragg = rh->dtahe_data.dtada_desc;
673 	dtrace_recdesc_t *lrec, *rrec;
674 	char *ldata, *rdata;
675 	int rval, i, j, keypos, nrecs;
676 
677 	if ((rval = dt_aggregate_hashcmp(lhs, rhs)) != 0)
678 		return (rval);
679 
680 	nrecs = lagg->dtagd_nrecs - 1;
681 	assert(nrecs == ragg->dtagd_nrecs - 1);
682 
683 	keypos = dt_keypos + 1 >= nrecs ? 0 : dt_keypos;
684 
685 	for (i = 1; i < nrecs; i++) {
686 		uint64_t lval, rval;
687 		int ndx = i + keypos;
688 
689 		if (ndx >= nrecs)
690 			ndx = ndx - nrecs + 1;
691 
692 		lrec = &lagg->dtagd_rec[ndx];
693 		rrec = &ragg->dtagd_rec[ndx];
694 
695 		ldata = lh->dtahe_data.dtada_data + lrec->dtrd_offset;
696 		rdata = rh->dtahe_data.dtada_data + rrec->dtrd_offset;
697 
698 		if (lrec->dtrd_size < rrec->dtrd_size)
699 			return (DT_LESSTHAN);
700 
701 		if (lrec->dtrd_size > rrec->dtrd_size)
702 			return (DT_GREATERTHAN);
703 
704 		switch (lrec->dtrd_size) {
705 		case sizeof (uint64_t):
706 			/* LINTED - alignment */
707 			lval = *((uint64_t *)ldata);
708 			/* LINTED - alignment */
709 			rval = *((uint64_t *)rdata);
710 			break;
711 
712 		case sizeof (uint32_t):
713 			/* LINTED - alignment */
714 			lval = *((uint32_t *)ldata);
715 			/* LINTED - alignment */
716 			rval = *((uint32_t *)rdata);
717 			break;
718 
719 		case sizeof (uint16_t):
720 			/* LINTED - alignment */
721 			lval = *((uint16_t *)ldata);
722 			/* LINTED - alignment */
723 			rval = *((uint16_t *)rdata);
724 			break;
725 
726 		case sizeof (uint8_t):
727 			lval = *((uint8_t *)ldata);
728 			rval = *((uint8_t *)rdata);
729 			break;
730 
731 		default:
732 			for (j = 0; j < lrec->dtrd_size; j++) {
733 				lval = ((uint8_t *)ldata)[j];
734 				rval = ((uint8_t *)rdata)[j];
735 
736 				if (lval < rval)
737 					return (DT_LESSTHAN);
738 
739 				if (lval > rval)
740 					return (DT_GREATERTHAN);
741 
742 			}
743 
744 			continue;
745 		}
746 
747 		if (lval < rval)
748 			return (DT_LESSTHAN);
749 
750 		if (lval > rval)
751 			return (DT_GREATERTHAN);
752 	}
753 
754 	return (0);
755 }
756 
757 static int
758 dt_aggregate_valcmp(const void *lhs, const void *rhs)
759 {
760 	dt_ahashent_t *lh = *((dt_ahashent_t **)lhs);
761 	dt_ahashent_t *rh = *((dt_ahashent_t **)rhs);
762 	dtrace_aggdesc_t *lagg = lh->dtahe_data.dtada_desc;
763 	dtrace_aggdesc_t *ragg = rh->dtahe_data.dtada_desc;
764 	caddr_t ldata = lh->dtahe_data.dtada_data;
765 	caddr_t rdata = rh->dtahe_data.dtada_data;
766 	dtrace_recdesc_t *lrec, *rrec;
767 	int64_t *laddr, *raddr;
768 	int rval, i;
769 
770 	if ((rval = dt_aggregate_hashcmp(lhs, rhs)) != 0)
771 		return (rval);
772 
773 	if (lagg->dtagd_nrecs > ragg->dtagd_nrecs)
774 		return (DT_GREATERTHAN);
775 
776 	if (lagg->dtagd_nrecs < ragg->dtagd_nrecs)
777 		return (DT_LESSTHAN);
778 
779 	for (i = 0; i < lagg->dtagd_nrecs; i++) {
780 		lrec = &lagg->dtagd_rec[i];
781 		rrec = &ragg->dtagd_rec[i];
782 
783 		if (lrec->dtrd_offset < rrec->dtrd_offset)
784 			return (DT_LESSTHAN);
785 
786 		if (lrec->dtrd_offset > rrec->dtrd_offset)
787 			return (DT_GREATERTHAN);
788 
789 		if (lrec->dtrd_action < rrec->dtrd_action)
790 			return (DT_LESSTHAN);
791 
792 		if (lrec->dtrd_action > rrec->dtrd_action)
793 			return (DT_GREATERTHAN);
794 	}
795 
796 	laddr = (int64_t *)(uintptr_t)(ldata + lrec->dtrd_offset);
797 	raddr = (int64_t *)(uintptr_t)(rdata + rrec->dtrd_offset);
798 
799 	switch (lrec->dtrd_action) {
800 	case DTRACEAGG_AVG:
801 		rval = dt_aggregate_averagecmp(laddr, raddr);
802 		break;
803 
804 	case DTRACEAGG_QUANTIZE:
805 		rval = dt_aggregate_quantizedcmp(laddr, raddr);
806 		break;
807 
808 	case DTRACEAGG_LQUANTIZE:
809 		rval = dt_aggregate_lquantizedcmp(laddr, raddr);
810 		break;
811 
812 	case DTRACEAGG_COUNT:
813 	case DTRACEAGG_SUM:
814 	case DTRACEAGG_MIN:
815 	case DTRACEAGG_MAX:
816 		rval = dt_aggregate_countcmp(laddr, raddr);
817 		break;
818 
819 	default:
820 		assert(0);
821 	}
822 
823 	return (rval);
824 }
825 
826 static int
827 dt_aggregate_valkeycmp(const void *lhs, const void *rhs)
828 {
829 	int rval;
830 
831 	if ((rval = dt_aggregate_valcmp(lhs, rhs)) != 0)
832 		return (rval);
833 
834 	/*
835 	 * If we're here, the values for the two aggregation elements are
836 	 * equal.  We already know that the key layout is the same for the two
837 	 * elements; we must now compare the keys themselves as a tie-breaker.
838 	 */
839 	return (dt_aggregate_keycmp(lhs, rhs));
840 }
841 
842 static int
843 dt_aggregate_keyvarcmp(const void *lhs, const void *rhs)
844 {
845 	int rval;
846 
847 	if ((rval = dt_aggregate_keycmp(lhs, rhs)) != 0)
848 		return (rval);
849 
850 	return (dt_aggregate_varcmp(lhs, rhs));
851 }
852 
853 static int
854 dt_aggregate_varkeycmp(const void *lhs, const void *rhs)
855 {
856 	int rval;
857 
858 	if ((rval = dt_aggregate_varcmp(lhs, rhs)) != 0)
859 		return (rval);
860 
861 	return (dt_aggregate_keycmp(lhs, rhs));
862 }
863 
864 static int
865 dt_aggregate_valvarcmp(const void *lhs, const void *rhs)
866 {
867 	int rval;
868 
869 	if ((rval = dt_aggregate_valkeycmp(lhs, rhs)) != 0)
870 		return (rval);
871 
872 	return (dt_aggregate_varcmp(lhs, rhs));
873 }
874 
875 static int
876 dt_aggregate_varvalcmp(const void *lhs, const void *rhs)
877 {
878 	int rval;
879 
880 	if ((rval = dt_aggregate_varcmp(lhs, rhs)) != 0)
881 		return (rval);
882 
883 	return (dt_aggregate_valkeycmp(lhs, rhs));
884 }
885 
886 static int
887 dt_aggregate_keyvarrevcmp(const void *lhs, const void *rhs)
888 {
889 	return (dt_aggregate_keyvarcmp(rhs, lhs));
890 }
891 
892 static int
893 dt_aggregate_varkeyrevcmp(const void *lhs, const void *rhs)
894 {
895 	return (dt_aggregate_varkeycmp(rhs, lhs));
896 }
897 
898 static int
899 dt_aggregate_valvarrevcmp(const void *lhs, const void *rhs)
900 {
901 	return (dt_aggregate_valvarcmp(rhs, lhs));
902 }
903 
904 static int
905 dt_aggregate_varvalrevcmp(const void *lhs, const void *rhs)
906 {
907 	return (dt_aggregate_varvalcmp(rhs, lhs));
908 }
909 
910 static int
911 dt_aggregate_bundlecmp(const void *lhs, const void *rhs)
912 {
913 	dt_ahashent_t **lh = *((dt_ahashent_t ***)lhs);
914 	dt_ahashent_t **rh = *((dt_ahashent_t ***)rhs);
915 	int i, rval;
916 
917 	if (dt_keysort) {
918 		/*
919 		 * If we're sorting on keys, we need to scan until we find the
920 		 * last entry -- that's the representative key.  (The order of
921 		 * the bundle is values followed by key to accommodate the
922 		 * default behavior of sorting by value.)  If the keys are
923 		 * equal, we'll fall into the value comparison loop, below.
924 		 */
925 		for (i = 0; lh[i + 1] != NULL; i++)
926 			continue;
927 
928 		assert(i != 0);
929 		assert(rh[i + 1] == NULL);
930 
931 		if ((rval = dt_aggregate_keycmp(&lh[i], &rh[i])) != 0)
932 			return (rval);
933 	}
934 
935 	for (i = 0; ; i++) {
936 		if (lh[i + 1] == NULL) {
937 			/*
938 			 * All of the values are equal; if we're sorting on
939 			 * keys, then we're only here because the keys were
940 			 * found to be equal and these records are therefore
941 			 * equal.  If we're not sorting on keys, we'll use the
942 			 * key comparison from the representative key as the
943 			 * tie-breaker.
944 			 */
945 			if (dt_keysort)
946 				return (0);
947 
948 			assert(i != 0);
949 			assert(rh[i + 1] == NULL);
950 			return (dt_aggregate_keycmp(&lh[i], &rh[i]));
951 		} else {
952 			if ((rval = dt_aggregate_valcmp(&lh[i], &rh[i])) != 0)
953 				return (rval);
954 		}
955 	}
956 }
957 
958 int
959 dt_aggregate_go(dtrace_hdl_t *dtp)
960 {
961 	dt_aggregate_t *agp = &dtp->dt_aggregate;
962 	dtrace_optval_t size, cpu;
963 	dtrace_bufdesc_t *buf = &agp->dtat_buf;
964 	int rval, i;
965 
966 	assert(agp->dtat_maxcpu == 0);
967 	assert(agp->dtat_ncpu == 0);
968 	assert(agp->dtat_cpus == NULL);
969 
970 	agp->dtat_maxcpu = dt_sysconf(dtp, _SC_CPUID_MAX) + 1;
971 	agp->dtat_ncpu = dt_sysconf(dtp, _SC_NPROCESSORS_MAX);
972 	agp->dtat_cpus = malloc(agp->dtat_ncpu * sizeof (processorid_t));
973 
974 	if (agp->dtat_cpus == NULL)
975 		return (dt_set_errno(dtp, EDT_NOMEM));
976 
977 	/*
978 	 * Use the aggregation buffer size as reloaded from the kernel.
979 	 */
980 	size = dtp->dt_options[DTRACEOPT_AGGSIZE];
981 
982 	rval = dtrace_getopt(dtp, "aggsize", &size);
983 	assert(rval == 0);
984 
985 	if (size == 0 || size == DTRACEOPT_UNSET)
986 		return (0);
987 
988 	buf = &agp->dtat_buf;
989 	buf->dtbd_size = size;
990 
991 	if ((buf->dtbd_data = malloc(buf->dtbd_size)) == NULL)
992 		return (dt_set_errno(dtp, EDT_NOMEM));
993 
994 	/*
995 	 * Now query for the CPUs enabled.
996 	 */
997 	rval = dtrace_getopt(dtp, "cpu", &cpu);
998 	assert(rval == 0 && cpu != DTRACEOPT_UNSET);
999 
1000 	if (cpu != DTRACE_CPUALL) {
1001 		assert(cpu < agp->dtat_ncpu);
1002 		agp->dtat_cpus[agp->dtat_ncpus++] = (processorid_t)cpu;
1003 
1004 		return (0);
1005 	}
1006 
1007 	agp->dtat_ncpus = 0;
1008 	for (i = 0; i < agp->dtat_maxcpu; i++) {
1009 		if (dt_status(dtp, i) == -1)
1010 			continue;
1011 
1012 		agp->dtat_cpus[agp->dtat_ncpus++] = i;
1013 	}
1014 
1015 	return (0);
1016 }
1017 
1018 static int
1019 dt_aggwalk_rval(dtrace_hdl_t *dtp, dt_ahashent_t *h, int rval)
1020 {
1021 	dt_aggregate_t *agp = &dtp->dt_aggregate;
1022 	dtrace_aggdata_t *data;
1023 	dtrace_aggdesc_t *aggdesc;
1024 	dtrace_recdesc_t *rec;
1025 	int i;
1026 
1027 	switch (rval) {
1028 	case DTRACE_AGGWALK_NEXT:
1029 		break;
1030 
1031 	case DTRACE_AGGWALK_CLEAR: {
1032 		uint32_t size, offs = 0;
1033 
1034 		aggdesc = h->dtahe_data.dtada_desc;
1035 		rec = &aggdesc->dtagd_rec[aggdesc->dtagd_nrecs - 1];
1036 		size = rec->dtrd_size;
1037 		data = &h->dtahe_data;
1038 
1039 		if (rec->dtrd_action == DTRACEAGG_LQUANTIZE) {
1040 			offs = sizeof (uint64_t);
1041 			size -= sizeof (uint64_t);
1042 		}
1043 
1044 		bzero(&data->dtada_data[rec->dtrd_offset] + offs, size);
1045 
1046 		if (data->dtada_percpu == NULL)
1047 			break;
1048 
1049 		for (i = 0; i < dtp->dt_aggregate.dtat_maxcpu; i++)
1050 			bzero(data->dtada_percpu[i] + offs, size);
1051 		break;
1052 	}
1053 
1054 	case DTRACE_AGGWALK_ERROR:
1055 		/*
1056 		 * We assume that errno is already set in this case.
1057 		 */
1058 		return (dt_set_errno(dtp, errno));
1059 
1060 	case DTRACE_AGGWALK_ABORT:
1061 		return (dt_set_errno(dtp, EDT_DIRABORT));
1062 
1063 	case DTRACE_AGGWALK_DENORMALIZE:
1064 		h->dtahe_data.dtada_normal = 1;
1065 		return (0);
1066 
1067 	case DTRACE_AGGWALK_NORMALIZE:
1068 		if (h->dtahe_data.dtada_normal == 0) {
1069 			h->dtahe_data.dtada_normal = 1;
1070 			return (dt_set_errno(dtp, EDT_BADRVAL));
1071 		}
1072 
1073 		return (0);
1074 
1075 	case DTRACE_AGGWALK_REMOVE: {
1076 		dtrace_aggdata_t *aggdata = &h->dtahe_data;
1077 		int i, max_cpus = agp->dtat_maxcpu;
1078 
1079 		/*
1080 		 * First, remove this hash entry from its hash chain.
1081 		 */
1082 		if (h->dtahe_prev != NULL) {
1083 			h->dtahe_prev->dtahe_next = h->dtahe_next;
1084 		} else {
1085 			dt_ahash_t *hash = &agp->dtat_hash;
1086 			size_t ndx = h->dtahe_hashval % hash->dtah_size;
1087 
1088 			assert(hash->dtah_hash[ndx] == h);
1089 			hash->dtah_hash[ndx] = h->dtahe_next;
1090 		}
1091 
1092 		if (h->dtahe_next != NULL)
1093 			h->dtahe_next->dtahe_prev = h->dtahe_prev;
1094 
1095 		/*
1096 		 * Now remove it from the list of all hash entries.
1097 		 */
1098 		if (h->dtahe_prevall != NULL) {
1099 			h->dtahe_prevall->dtahe_nextall = h->dtahe_nextall;
1100 		} else {
1101 			dt_ahash_t *hash = &agp->dtat_hash;
1102 
1103 			assert(hash->dtah_all == h);
1104 			hash->dtah_all = h->dtahe_nextall;
1105 		}
1106 
1107 		if (h->dtahe_nextall != NULL)
1108 			h->dtahe_nextall->dtahe_prevall = h->dtahe_prevall;
1109 
1110 		/*
1111 		 * We're unlinked.  We can safely destroy the data.
1112 		 */
1113 		if (aggdata->dtada_percpu != NULL) {
1114 			for (i = 0; i < max_cpus; i++)
1115 				free(aggdata->dtada_percpu[i]);
1116 			free(aggdata->dtada_percpu);
1117 		}
1118 
1119 		free(aggdata->dtada_data);
1120 		free(h);
1121 
1122 		return (0);
1123 	}
1124 
1125 	default:
1126 		return (dt_set_errno(dtp, EDT_BADRVAL));
1127 	}
1128 
1129 	return (0);
1130 }
1131 
1132 void
1133 dt_aggregate_qsort(dtrace_hdl_t *dtp, void *base, size_t nel, size_t width,
1134     int (*compar)(const void *, const void *))
1135 {
1136 	int rev = dt_revsort, key = dt_keysort, keypos = dt_keypos;
1137 	dtrace_optval_t keyposopt = dtp->dt_options[DTRACEOPT_AGGSORTKEYPOS];
1138 
1139 	dt_revsort = (dtp->dt_options[DTRACEOPT_AGGSORTREV] != DTRACEOPT_UNSET);
1140 	dt_keysort = (dtp->dt_options[DTRACEOPT_AGGSORTKEY] != DTRACEOPT_UNSET);
1141 
1142 	if (keyposopt != DTRACEOPT_UNSET && keyposopt <= INT_MAX) {
1143 		dt_keypos = (int)keyposopt;
1144 	} else {
1145 		dt_keypos = 0;
1146 	}
1147 
1148 	if (compar == NULL) {
1149 		if (!dt_keysort) {
1150 			compar = dt_aggregate_varvalcmp;
1151 		} else {
1152 			compar = dt_aggregate_varkeycmp;
1153 		}
1154 	}
1155 
1156 	qsort(base, nel, width, compar);
1157 
1158 	dt_revsort = rev;
1159 	dt_keysort = key;
1160 	dt_keypos = keypos;
1161 }
1162 
1163 int
1164 dtrace_aggregate_walk(dtrace_hdl_t *dtp, dtrace_aggregate_f *func, void *arg)
1165 {
1166 	dt_ahashent_t *h, *next;
1167 	dt_ahash_t *hash = &dtp->dt_aggregate.dtat_hash;
1168 
1169 	for (h = hash->dtah_all; h != NULL; h = next) {
1170 		/*
1171 		 * dt_aggwalk_rval() can potentially remove the current hash
1172 		 * entry; we need to load the next hash entry before calling
1173 		 * into it.
1174 		 */
1175 		next = h->dtahe_nextall;
1176 
1177 		if (dt_aggwalk_rval(dtp, h, func(&h->dtahe_data, arg)) == -1)
1178 			return (-1);
1179 	}
1180 
1181 	return (0);
1182 }
1183 
1184 static int
1185 dt_aggregate_walk_sorted(dtrace_hdl_t *dtp,
1186     dtrace_aggregate_f *func, void *arg,
1187     int (*sfunc)(const void *, const void *))
1188 {
1189 	dt_aggregate_t *agp = &dtp->dt_aggregate;
1190 	dt_ahashent_t *h, **sorted;
1191 	dt_ahash_t *hash = &agp->dtat_hash;
1192 	size_t i, nentries = 0;
1193 
1194 	for (h = hash->dtah_all; h != NULL; h = h->dtahe_nextall)
1195 		nentries++;
1196 
1197 	sorted = dt_alloc(dtp, nentries * sizeof (dt_ahashent_t *));
1198 
1199 	if (sorted == NULL)
1200 		return (-1);
1201 
1202 	for (h = hash->dtah_all, i = 0; h != NULL; h = h->dtahe_nextall)
1203 		sorted[i++] = h;
1204 
1205 	(void) pthread_mutex_lock(&dt_qsort_lock);
1206 
1207 	if (sfunc == NULL) {
1208 		dt_aggregate_qsort(dtp, sorted, nentries,
1209 		    sizeof (dt_ahashent_t *), NULL);
1210 	} else {
1211 		/*
1212 		 * If we've been explicitly passed a sorting function,
1213 		 * we'll use that -- ignoring the values of the "aggsortrev",
1214 		 * "aggsortkey" and "aggsortkeypos" options.
1215 		 */
1216 		qsort(sorted, nentries, sizeof (dt_ahashent_t *), sfunc);
1217 	}
1218 
1219 	(void) pthread_mutex_unlock(&dt_qsort_lock);
1220 
1221 	for (i = 0; i < nentries; i++) {
1222 		h = sorted[i];
1223 
1224 		if (dt_aggwalk_rval(dtp, h, func(&h->dtahe_data, arg)) == -1) {
1225 			dt_free(dtp, sorted);
1226 			return (-1);
1227 		}
1228 	}
1229 
1230 	dt_free(dtp, sorted);
1231 	return (0);
1232 }
1233 
1234 int
1235 dtrace_aggregate_walk_sorted(dtrace_hdl_t *dtp,
1236     dtrace_aggregate_f *func, void *arg)
1237 {
1238 	return (dt_aggregate_walk_sorted(dtp, func, arg, NULL));
1239 }
1240 
1241 int
1242 dtrace_aggregate_walk_keysorted(dtrace_hdl_t *dtp,
1243     dtrace_aggregate_f *func, void *arg)
1244 {
1245 	return (dt_aggregate_walk_sorted(dtp, func,
1246 	    arg, dt_aggregate_varkeycmp));
1247 }
1248 
1249 int
1250 dtrace_aggregate_walk_valsorted(dtrace_hdl_t *dtp,
1251     dtrace_aggregate_f *func, void *arg)
1252 {
1253 	return (dt_aggregate_walk_sorted(dtp, func,
1254 	    arg, dt_aggregate_varvalcmp));
1255 }
1256 
1257 int
1258 dtrace_aggregate_walk_keyvarsorted(dtrace_hdl_t *dtp,
1259     dtrace_aggregate_f *func, void *arg)
1260 {
1261 	return (dt_aggregate_walk_sorted(dtp, func,
1262 	    arg, dt_aggregate_keyvarcmp));
1263 }
1264 
1265 int
1266 dtrace_aggregate_walk_valvarsorted(dtrace_hdl_t *dtp,
1267     dtrace_aggregate_f *func, void *arg)
1268 {
1269 	return (dt_aggregate_walk_sorted(dtp, func,
1270 	    arg, dt_aggregate_valvarcmp));
1271 }
1272 
1273 int
1274 dtrace_aggregate_walk_keyrevsorted(dtrace_hdl_t *dtp,
1275     dtrace_aggregate_f *func, void *arg)
1276 {
1277 	return (dt_aggregate_walk_sorted(dtp, func,
1278 	    arg, dt_aggregate_varkeyrevcmp));
1279 }
1280 
1281 int
1282 dtrace_aggregate_walk_valrevsorted(dtrace_hdl_t *dtp,
1283     dtrace_aggregate_f *func, void *arg)
1284 {
1285 	return (dt_aggregate_walk_sorted(dtp, func,
1286 	    arg, dt_aggregate_varvalrevcmp));
1287 }
1288 
1289 int
1290 dtrace_aggregate_walk_keyvarrevsorted(dtrace_hdl_t *dtp,
1291     dtrace_aggregate_f *func, void *arg)
1292 {
1293 	return (dt_aggregate_walk_sorted(dtp, func,
1294 	    arg, dt_aggregate_keyvarrevcmp));
1295 }
1296 
1297 int
1298 dtrace_aggregate_walk_valvarrevsorted(dtrace_hdl_t *dtp,
1299     dtrace_aggregate_f *func, void *arg)
1300 {
1301 	return (dt_aggregate_walk_sorted(dtp, func,
1302 	    arg, dt_aggregate_valvarrevcmp));
1303 }
1304 
1305 int
1306 dtrace_aggregate_walk_joined(dtrace_hdl_t *dtp, dtrace_aggvarid_t *aggvars,
1307     int naggvars, dtrace_aggregate_walk_joined_f *func, void *arg)
1308 {
1309 	dt_aggregate_t *agp = &dtp->dt_aggregate;
1310 	dt_ahashent_t *h, **sorted = NULL, ***bundle, **nbundle;
1311 	const dtrace_aggdata_t **data;
1312 	dt_ahashent_t *zaggdata = NULL;
1313 	dt_ahash_t *hash = &agp->dtat_hash;
1314 	size_t nentries = 0, nbundles = 0, start, zsize = 0, bundlesize;
1315 	dtrace_aggvarid_t max = 0, aggvar;
1316 	int rval = -1, *map, *remap = NULL;
1317 	int i, j;
1318 	dtrace_optval_t sortpos = dtp->dt_options[DTRACEOPT_AGGSORTPOS];
1319 
1320 	/*
1321 	 * If the sorting position is greater than the number of aggregation
1322 	 * variable IDs, we silently set it to 0.
1323 	 */
1324 	if (sortpos == DTRACEOPT_UNSET || sortpos >= naggvars)
1325 		sortpos = 0;
1326 
1327 	/*
1328 	 * First we need to translate the specified aggregation variable IDs
1329 	 * into a linear map that will allow us to translate an aggregation
1330 	 * variable ID into its position in the specified aggvars.
1331 	 */
1332 	for (i = 0; i < naggvars; i++) {
1333 		if (aggvars[i] == DTRACE_AGGVARIDNONE || aggvars[i] < 0)
1334 			return (dt_set_errno(dtp, EDT_BADAGGVAR));
1335 
1336 		if (aggvars[i] > max)
1337 			max = aggvars[i];
1338 	}
1339 
1340 	if ((map = dt_zalloc(dtp, (max + 1) * sizeof (int))) == NULL)
1341 		return (-1);
1342 
1343 	zaggdata = dt_zalloc(dtp, naggvars * sizeof (dt_ahashent_t));
1344 
1345 	if (zaggdata == NULL)
1346 		goto out;
1347 
1348 	for (i = 0; i < naggvars; i++) {
1349 		int ndx = i + sortpos;
1350 
1351 		if (ndx >= naggvars)
1352 			ndx -= naggvars;
1353 
1354 		aggvar = aggvars[ndx];
1355 		assert(aggvar <= max);
1356 
1357 		if (map[aggvar]) {
1358 			/*
1359 			 * We have an aggregation variable that is present
1360 			 * more than once in the array of aggregation
1361 			 * variables.  While it's unclear why one might want
1362 			 * to do this, it's legal.  To support this construct,
1363 			 * we will allocate a remap that will indicate the
1364 			 * position from which this aggregation variable
1365 			 * should be pulled.  (That is, where the remap will
1366 			 * map from one position to another.)
1367 			 */
1368 			if (remap == NULL) {
1369 				remap = dt_zalloc(dtp, naggvars * sizeof (int));
1370 
1371 				if (remap == NULL)
1372 					goto out;
1373 			}
1374 
1375 			/*
1376 			 * Given that the variable is already present, assert
1377 			 * that following through the mapping and adjusting
1378 			 * for the sort position yields the same aggregation
1379 			 * variable ID.
1380 			 */
1381 			assert(aggvars[(map[aggvar] - 1 + sortpos) %
1382 			    naggvars] == aggvars[ndx]);
1383 
1384 			remap[i] = map[aggvar];
1385 			continue;
1386 		}
1387 
1388 		map[aggvar] = i + 1;
1389 	}
1390 
1391 	/*
1392 	 * We need to take two passes over the data to size our allocation, so
1393 	 * we'll use the first pass to also fill in the zero-filled data to be
1394 	 * used to properly format a zero-valued aggregation.
1395 	 */
1396 	for (h = hash->dtah_all; h != NULL; h = h->dtahe_nextall) {
1397 		dtrace_aggvarid_t id;
1398 		int ndx;
1399 
1400 		if ((id = dt_aggregate_aggvarid(h)) > max || !(ndx = map[id]))
1401 			continue;
1402 
1403 		if (zaggdata[ndx - 1].dtahe_size == 0) {
1404 			zaggdata[ndx - 1].dtahe_size = h->dtahe_size;
1405 			zaggdata[ndx - 1].dtahe_data = h->dtahe_data;
1406 		}
1407 
1408 		nentries++;
1409 	}
1410 
1411 	if (nentries == 0) {
1412 		/*
1413 		 * We couldn't find any entries; there is nothing else to do.
1414 		 */
1415 		rval = 0;
1416 		goto out;
1417 	}
1418 
1419 	/*
1420 	 * Before we sort the data, we're going to look for any holes in our
1421 	 * zero-filled data.  This will occur if an aggregation variable that
1422 	 * we are being asked to print has not yet been assigned the result of
1423 	 * any aggregating action for _any_ tuple.  The issue becomes that we
1424 	 * would like a zero value to be printed for all columns for this
1425 	 * aggregation, but without any record description, we don't know the
1426 	 * aggregating action that corresponds to the aggregation variable.  To
1427 	 * try to find a match, we're simply going to lookup aggregation IDs
1428 	 * (which are guaranteed to be contiguous and to start from 1), looking
1429 	 * for the specified aggregation variable ID.  If we find a match,
1430 	 * we'll use that.  If we iterate over all aggregation IDs and don't
1431 	 * find a match, then we must be an anonymous enabling.  (Anonymous
1432 	 * enablings can't currently derive either aggregation variable IDs or
1433 	 * aggregation variable names given only an aggregation ID.)  In this
1434 	 * obscure case (anonymous enabling, multiple aggregation printa() with
1435 	 * some aggregations not represented for any tuple), our defined
1436 	 * behavior is that the zero will be printed in the format of the first
1437 	 * aggregation variable that contains any non-zero value.
1438 	 */
1439 	for (i = 0; i < naggvars; i++) {
1440 		if (zaggdata[i].dtahe_size == 0) {
1441 			dtrace_aggvarid_t aggvar;
1442 
1443 			aggvar = aggvars[(i - sortpos + naggvars) % naggvars];
1444 			assert(zaggdata[i].dtahe_data.dtada_data == NULL);
1445 
1446 			for (j = DTRACE_AGGIDNONE + 1; ; j++) {
1447 				dtrace_aggdesc_t *agg;
1448 				dtrace_aggdata_t *aggdata;
1449 
1450 				if (dt_aggid_lookup(dtp, j, &agg) != 0)
1451 					break;
1452 
1453 				if (agg->dtagd_varid != aggvar)
1454 					continue;
1455 
1456 				/*
1457 				 * We have our description -- now we need to
1458 				 * cons up the zaggdata entry for it.
1459 				 */
1460 				aggdata = &zaggdata[i].dtahe_data;
1461 				aggdata->dtada_size = agg->dtagd_size;
1462 				aggdata->dtada_desc = agg;
1463 				aggdata->dtada_handle = dtp;
1464 				(void) dt_epid_lookup(dtp, agg->dtagd_epid,
1465 				    &aggdata->dtada_edesc,
1466 				    &aggdata->dtada_pdesc);
1467 				aggdata->dtada_normal = 1;
1468 				zaggdata[i].dtahe_hashval = 0;
1469 				zaggdata[i].dtahe_size = agg->dtagd_size;
1470 				break;
1471 			}
1472 
1473 			if (zaggdata[i].dtahe_size == 0) {
1474 				caddr_t data;
1475 
1476 				/*
1477 				 * We couldn't find this aggregation, meaning
1478 				 * that we have never seen it before for any
1479 				 * tuple _and_ this is an anonymous enabling.
1480 				 * That is, we're in the obscure case outlined
1481 				 * above.  In this case, our defined behavior
1482 				 * is to format the data in the format of the
1483 				 * first non-zero aggregation -- of which, of
1484 				 * course, we know there to be at least one
1485 				 * (or nentries would have been zero).
1486 				 */
1487 				for (j = 0; j < naggvars; j++) {
1488 					if (zaggdata[j].dtahe_size != 0)
1489 						break;
1490 				}
1491 
1492 				assert(j < naggvars);
1493 				zaggdata[i] = zaggdata[j];
1494 
1495 				data = zaggdata[i].dtahe_data.dtada_data;
1496 				assert(data != NULL);
1497 			}
1498 		}
1499 	}
1500 
1501 	/*
1502 	 * Now we need to allocate our zero-filled data for use for
1503 	 * aggregations that don't have a value corresponding to a given key.
1504 	 */
1505 	for (i = 0; i < naggvars; i++) {
1506 		dtrace_aggdata_t *aggdata = &zaggdata[i].dtahe_data;
1507 		dtrace_aggdesc_t *aggdesc = aggdata->dtada_desc;
1508 		dtrace_recdesc_t *rec;
1509 		uint64_t larg;
1510 		caddr_t zdata;
1511 
1512 		zsize = zaggdata[i].dtahe_size;
1513 		assert(zsize != 0);
1514 
1515 		if ((zdata = dt_zalloc(dtp, zsize)) == NULL) {
1516 			/*
1517 			 * If we failed to allocated some zero-filled data, we
1518 			 * need to zero out the remaining dtada_data pointers
1519 			 * to prevent the wrong data from being freed below.
1520 			 */
1521 			for (j = i; j < naggvars; j++)
1522 				zaggdata[j].dtahe_data.dtada_data = NULL;
1523 			goto out;
1524 		}
1525 
1526 		aggvar = aggvars[(i - sortpos + naggvars) % naggvars];
1527 
1528 		/*
1529 		 * First, the easy bit.  To maintain compatibility with
1530 		 * consumers that pull the compiler-generated ID out of the
1531 		 * data, we put that ID at the top of the zero-filled data.
1532 		 */
1533 		rec = &aggdesc->dtagd_rec[0];
1534 		/* LINTED - alignment */
1535 		*((dtrace_aggvarid_t *)(zdata + rec->dtrd_offset)) = aggvar;
1536 
1537 		rec = &aggdesc->dtagd_rec[aggdesc->dtagd_nrecs - 1];
1538 
1539 		/*
1540 		 * Now for the more complicated part.  If (and only if) this
1541 		 * is an lquantize() aggregating action, zero-filled data is
1542 		 * not equivalent to an empty record:  we must also get the
1543 		 * parameters for the lquantize().
1544 		 */
1545 		if (rec->dtrd_action == DTRACEAGG_LQUANTIZE) {
1546 			if (aggdata->dtada_data != NULL) {
1547 				/*
1548 				 * The easier case here is if we actually have
1549 				 * some prototype data -- in which case we
1550 				 * manually dig it out of the aggregation
1551 				 * record.
1552 				 */
1553 				/* LINTED - alignment */
1554 				larg = *((uint64_t *)(aggdata->dtada_data +
1555 				    rec->dtrd_offset));
1556 			} else {
1557 				/*
1558 				 * We don't have any prototype data.  As a
1559 				 * result, we know that we _do_ have the
1560 				 * compiler-generated information.  (If this
1561 				 * were an anonymous enabling, all of our
1562 				 * zero-filled data would have prototype data
1563 				 * -- either directly or indirectly.) So as
1564 				 * gross as it is, we'll grovel around in the
1565 				 * compiler-generated information to find the
1566 				 * lquantize() parameters.
1567 				 */
1568 				dtrace_stmtdesc_t *sdp;
1569 				dt_ident_t *aid;
1570 				dt_idsig_t *isp;
1571 
1572 				sdp = (dtrace_stmtdesc_t *)(uintptr_t)
1573 				    aggdesc->dtagd_rec[0].dtrd_uarg;
1574 				aid = sdp->dtsd_aggdata;
1575 				isp = (dt_idsig_t *)aid->di_data;
1576 				assert(isp->dis_auxinfo != 0);
1577 				larg = isp->dis_auxinfo;
1578 			}
1579 
1580 			/* LINTED - alignment */
1581 			*((uint64_t *)(zdata + rec->dtrd_offset)) = larg;
1582 		}
1583 
1584 		aggdata->dtada_data = zdata;
1585 	}
1586 
1587 	/*
1588 	 * Now that we've dealt with setting up our zero-filled data, we can
1589 	 * allocate our sorted array, and take another pass over the data to
1590 	 * fill it.
1591 	 */
1592 	sorted = dt_alloc(dtp, nentries * sizeof (dt_ahashent_t *));
1593 
1594 	if (sorted == NULL)
1595 		goto out;
1596 
1597 	for (h = hash->dtah_all, i = 0; h != NULL; h = h->dtahe_nextall) {
1598 		dtrace_aggvarid_t id;
1599 
1600 		if ((id = dt_aggregate_aggvarid(h)) > max || !map[id])
1601 			continue;
1602 
1603 		sorted[i++] = h;
1604 	}
1605 
1606 	assert(i == nentries);
1607 
1608 	/*
1609 	 * We've loaded our array; now we need to sort by value to allow us
1610 	 * to create bundles of like value.  We're going to acquire the
1611 	 * dt_qsort_lock here, and hold it across all of our subsequent
1612 	 * comparison and sorting.
1613 	 */
1614 	(void) pthread_mutex_lock(&dt_qsort_lock);
1615 
1616 	qsort(sorted, nentries, sizeof (dt_ahashent_t *),
1617 	    dt_aggregate_keyvarcmp);
1618 
1619 	/*
1620 	 * Now we need to go through and create bundles.  Because the number
1621 	 * of bundles is bounded by the size of the sorted array, we're going
1622 	 * to reuse the underlying storage.  And note that "bundle" is an
1623 	 * array of pointers to arrays of pointers to dt_ahashent_t -- making
1624 	 * its type (regrettably) "dt_ahashent_t ***".  (Regrettable because
1625 	 * '*' -- like '_' and 'X' -- should never appear in triplicate in
1626 	 * an ideal world.)
1627 	 */
1628 	bundle = (dt_ahashent_t ***)sorted;
1629 
1630 	for (i = 1, start = 0; i <= nentries; i++) {
1631 		if (i < nentries &&
1632 		    dt_aggregate_keycmp(&sorted[i], &sorted[i - 1]) == 0)
1633 			continue;
1634 
1635 		/*
1636 		 * We have a bundle boundary.  Everything from start to
1637 		 * (i - 1) belongs in one bundle.
1638 		 */
1639 		assert(i - start <= naggvars);
1640 		bundlesize = (naggvars + 2) * sizeof (dt_ahashent_t *);
1641 
1642 		if ((nbundle = dt_zalloc(dtp, bundlesize)) == NULL) {
1643 			(void) pthread_mutex_unlock(&dt_qsort_lock);
1644 			goto out;
1645 		}
1646 
1647 		for (j = start; j < i; j++) {
1648 			dtrace_aggvarid_t id = dt_aggregate_aggvarid(sorted[j]);
1649 
1650 			assert(id <= max);
1651 			assert(map[id] != 0);
1652 			assert(map[id] - 1 < naggvars);
1653 			assert(nbundle[map[id] - 1] == NULL);
1654 			nbundle[map[id] - 1] = sorted[j];
1655 
1656 			if (nbundle[naggvars] == NULL)
1657 				nbundle[naggvars] = sorted[j];
1658 		}
1659 
1660 		for (j = 0; j < naggvars; j++) {
1661 			if (nbundle[j] != NULL)
1662 				continue;
1663 
1664 			/*
1665 			 * Before we assume that this aggregation variable
1666 			 * isn't present (and fall back to using the
1667 			 * zero-filled data allocated earlier), check the
1668 			 * remap.  If we have a remapping, we'll drop it in
1669 			 * here.  Note that we might be remapping an
1670 			 * aggregation variable that isn't present for this
1671 			 * key; in this case, the aggregation data that we
1672 			 * copy will point to the zeroed data.
1673 			 */
1674 			if (remap != NULL && remap[j]) {
1675 				assert(remap[j] - 1 < j);
1676 				assert(nbundle[remap[j] - 1] != NULL);
1677 				nbundle[j] = nbundle[remap[j] - 1];
1678 			} else {
1679 				nbundle[j] = &zaggdata[j];
1680 			}
1681 		}
1682 
1683 		bundle[nbundles++] = nbundle;
1684 		start = i;
1685 	}
1686 
1687 	/*
1688 	 * Now we need to re-sort based on the first value.
1689 	 */
1690 	dt_aggregate_qsort(dtp, bundle, nbundles, sizeof (dt_ahashent_t **),
1691 	    dt_aggregate_bundlecmp);
1692 
1693 	(void) pthread_mutex_unlock(&dt_qsort_lock);
1694 
1695 	/*
1696 	 * We're done!  Now we just need to go back over the sorted bundles,
1697 	 * calling the function.
1698 	 */
1699 	data = alloca((naggvars + 1) * sizeof (dtrace_aggdata_t *));
1700 
1701 	for (i = 0; i < nbundles; i++) {
1702 		for (j = 0; j < naggvars; j++)
1703 			data[j + 1] = NULL;
1704 
1705 		for (j = 0; j < naggvars; j++) {
1706 			int ndx = j - sortpos;
1707 
1708 			if (ndx < 0)
1709 				ndx += naggvars;
1710 
1711 			assert(bundle[i][ndx] != NULL);
1712 			data[j + 1] = &bundle[i][ndx]->dtahe_data;
1713 		}
1714 
1715 		for (j = 0; j < naggvars; j++)
1716 			assert(data[j + 1] != NULL);
1717 
1718 		/*
1719 		 * The representative key is the last element in the bundle.
1720 		 * Assert that we have one, and then set it to be the first
1721 		 * element of data.
1722 		 */
1723 		assert(bundle[i][j] != NULL);
1724 		data[0] = &bundle[i][j]->dtahe_data;
1725 
1726 		if ((rval = func(data, naggvars + 1, arg)) == -1)
1727 			goto out;
1728 	}
1729 
1730 	rval = 0;
1731 out:
1732 	for (i = 0; i < nbundles; i++)
1733 		dt_free(dtp, bundle[i]);
1734 
1735 	if (zaggdata != NULL) {
1736 		for (i = 0; i < naggvars; i++)
1737 			dt_free(dtp, zaggdata[i].dtahe_data.dtada_data);
1738 	}
1739 
1740 	dt_free(dtp, zaggdata);
1741 	dt_free(dtp, sorted);
1742 	dt_free(dtp, remap);
1743 	dt_free(dtp, map);
1744 
1745 	return (rval);
1746 }
1747 
1748 int
1749 dtrace_aggregate_print(dtrace_hdl_t *dtp, FILE *fp,
1750     dtrace_aggregate_walk_f *func)
1751 {
1752 	dt_print_aggdata_t pd;
1753 
1754 	pd.dtpa_dtp = dtp;
1755 	pd.dtpa_fp = fp;
1756 	pd.dtpa_allunprint = 1;
1757 
1758 	if (func == NULL)
1759 		func = dtrace_aggregate_walk_sorted;
1760 
1761 	if ((*func)(dtp, dt_print_agg, &pd) == -1)
1762 		return (dt_set_errno(dtp, dtp->dt_errno));
1763 
1764 	return (0);
1765 }
1766 
1767 void
1768 dtrace_aggregate_clear(dtrace_hdl_t *dtp)
1769 {
1770 	dt_aggregate_t *agp = &dtp->dt_aggregate;
1771 	dt_ahash_t *hash = &agp->dtat_hash;
1772 	dt_ahashent_t *h;
1773 	dtrace_aggdata_t *data;
1774 	dtrace_aggdesc_t *aggdesc;
1775 	dtrace_recdesc_t *rec;
1776 	int i, max_cpus = agp->dtat_maxcpu;
1777 
1778 	for (h = hash->dtah_all; h != NULL; h = h->dtahe_nextall) {
1779 		aggdesc = h->dtahe_data.dtada_desc;
1780 		rec = &aggdesc->dtagd_rec[aggdesc->dtagd_nrecs - 1];
1781 		data = &h->dtahe_data;
1782 
1783 		bzero(&data->dtada_data[rec->dtrd_offset], rec->dtrd_size);
1784 
1785 		if (data->dtada_percpu == NULL)
1786 			continue;
1787 
1788 		for (i = 0; i < max_cpus; i++)
1789 			bzero(data->dtada_percpu[i], rec->dtrd_size);
1790 	}
1791 }
1792 
1793 void
1794 dt_aggregate_destroy(dtrace_hdl_t *dtp)
1795 {
1796 	dt_aggregate_t *agp = &dtp->dt_aggregate;
1797 	dt_ahash_t *hash = &agp->dtat_hash;
1798 	dt_ahashent_t *h, *next;
1799 	dtrace_aggdata_t *aggdata;
1800 	int i, max_cpus = agp->dtat_maxcpu;
1801 
1802 	if (hash->dtah_hash == NULL) {
1803 		assert(hash->dtah_all == NULL);
1804 	} else {
1805 		free(hash->dtah_hash);
1806 
1807 		for (h = hash->dtah_all; h != NULL; h = next) {
1808 			next = h->dtahe_nextall;
1809 
1810 			aggdata = &h->dtahe_data;
1811 
1812 			if (aggdata->dtada_percpu != NULL) {
1813 				for (i = 0; i < max_cpus; i++)
1814 					free(aggdata->dtada_percpu[i]);
1815 				free(aggdata->dtada_percpu);
1816 			}
1817 
1818 			free(aggdata->dtada_data);
1819 			free(h);
1820 		}
1821 
1822 		hash->dtah_hash = NULL;
1823 		hash->dtah_all = NULL;
1824 		hash->dtah_size = 0;
1825 	}
1826 
1827 	free(agp->dtat_buf.dtbd_data);
1828 	free(agp->dtat_cpus);
1829 }
1830