xref: /netbsd-src/external/cddl/osnet/dist/lib/libdtrace/common/dt_consume.c (revision 63d4abf06d37aace2f9e41a494102a64fe3abddb)
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  * Copyright 2008 Sun Microsystems, Inc.  All rights reserved.
23  * Use is subject to license terms.
24  */
25 
26 #pragma ident	"%Z%%M%	%I%	%E% SMI"
27 
28 #include <stdlib.h>
29 #include <strings.h>
30 #include <errno.h>
31 #include <unistd.h>
32 #include <limits.h>
33 #include <assert.h>
34 #include <ctype.h>
35 #if defined(sun)
36 #include <alloca.h>
37 #endif
38 #include <dt_impl.h>
39 
40 #define	DT_MASK_LO 0x00000000FFFFFFFFULL
41 
42 /*
43  * We declare this here because (1) we need it and (2) we want to avoid a
44  * dependency on libm in libdtrace.
45  */
46 static long double
47 dt_fabsl(long double x)
48 {
49 	if (x < 0)
50 		return (-x);
51 
52 	return (x);
53 }
54 
55 /*
56  * 128-bit arithmetic functions needed to support the stddev() aggregating
57  * action.
58  */
59 static int
60 dt_gt_128(uint64_t *a, uint64_t *b)
61 {
62 	return (a[1] > b[1] || (a[1] == b[1] && a[0] > b[0]));
63 }
64 
65 static int
66 dt_ge_128(uint64_t *a, uint64_t *b)
67 {
68 	return (a[1] > b[1] || (a[1] == b[1] && a[0] >= b[0]));
69 }
70 
71 static int
72 dt_le_128(uint64_t *a, uint64_t *b)
73 {
74 	return (a[1] < b[1] || (a[1] == b[1] && a[0] <= b[0]));
75 }
76 
77 /*
78  * Shift the 128-bit value in a by b. If b is positive, shift left.
79  * If b is negative, shift right.
80  */
81 static void
82 dt_shift_128(uint64_t *a, int b)
83 {
84 	uint64_t mask;
85 
86 	if (b == 0)
87 		return;
88 
89 	if (b < 0) {
90 		b = -b;
91 		if (b >= 64) {
92 			a[0] = a[1] >> (b - 64);
93 			a[1] = 0;
94 		} else {
95 			a[0] >>= b;
96 			mask = 1LL << (64 - b);
97 			mask -= 1;
98 			a[0] |= ((a[1] & mask) << (64 - b));
99 			a[1] >>= b;
100 		}
101 	} else {
102 		if (b >= 64) {
103 			a[1] = a[0] << (b - 64);
104 			a[0] = 0;
105 		} else {
106 			a[1] <<= b;
107 			mask = a[0] >> (64 - b);
108 			a[1] |= mask;
109 			a[0] <<= b;
110 		}
111 	}
112 }
113 
114 static int
115 dt_nbits_128(uint64_t *a)
116 {
117 	int nbits = 0;
118 	uint64_t tmp[2];
119 	uint64_t zero[2] = { 0, 0 };
120 
121 	tmp[0] = a[0];
122 	tmp[1] = a[1];
123 
124 	dt_shift_128(tmp, -1);
125 	while (dt_gt_128(tmp, zero)) {
126 		dt_shift_128(tmp, -1);
127 		nbits++;
128 	}
129 
130 	return (nbits);
131 }
132 
133 static void
134 dt_subtract_128(uint64_t *minuend, uint64_t *subtrahend, uint64_t *difference)
135 {
136 	uint64_t result[2];
137 
138 	result[0] = minuend[0] - subtrahend[0];
139 	result[1] = minuend[1] - subtrahend[1] -
140 	    (minuend[0] < subtrahend[0] ? 1 : 0);
141 
142 	difference[0] = result[0];
143 	difference[1] = result[1];
144 }
145 
146 static void
147 dt_add_128(uint64_t *addend1, uint64_t *addend2, uint64_t *sum)
148 {
149 	uint64_t result[2];
150 
151 	result[0] = addend1[0] + addend2[0];
152 	result[1] = addend1[1] + addend2[1] +
153 	    (result[0] < addend1[0] || result[0] < addend2[0] ? 1 : 0);
154 
155 	sum[0] = result[0];
156 	sum[1] = result[1];
157 }
158 
159 /*
160  * The basic idea is to break the 2 64-bit values into 4 32-bit values,
161  * use native multiplication on those, and then re-combine into the
162  * resulting 128-bit value.
163  *
164  * (hi1 << 32 + lo1) * (hi2 << 32 + lo2) =
165  *     hi1 * hi2 << 64 +
166  *     hi1 * lo2 << 32 +
167  *     hi2 * lo1 << 32 +
168  *     lo1 * lo2
169  */
170 static void
171 dt_multiply_128(uint64_t factor1, uint64_t factor2, uint64_t *product)
172 {
173 	uint64_t hi1, hi2, lo1, lo2;
174 	uint64_t tmp[2];
175 
176 	hi1 = factor1 >> 32;
177 	hi2 = factor2 >> 32;
178 
179 	lo1 = factor1 & DT_MASK_LO;
180 	lo2 = factor2 & DT_MASK_LO;
181 
182 	product[0] = lo1 * lo2;
183 	product[1] = hi1 * hi2;
184 
185 	tmp[0] = hi1 * lo2;
186 	tmp[1] = 0;
187 	dt_shift_128(tmp, 32);
188 	dt_add_128(product, tmp, product);
189 
190 	tmp[0] = hi2 * lo1;
191 	tmp[1] = 0;
192 	dt_shift_128(tmp, 32);
193 	dt_add_128(product, tmp, product);
194 }
195 
196 /*
197  * This is long-hand division.
198  *
199  * We initialize subtrahend by shifting divisor left as far as possible. We
200  * loop, comparing subtrahend to dividend:  if subtrahend is smaller, we
201  * subtract and set the appropriate bit in the result.  We then shift
202  * subtrahend right by one bit for the next comparison.
203  */
204 static void
205 dt_divide_128(uint64_t *dividend, uint64_t divisor, uint64_t *quotient)
206 {
207 	uint64_t result[2] = { 0, 0 };
208 	uint64_t remainder[2];
209 	uint64_t subtrahend[2];
210 	uint64_t divisor_128[2];
211 	uint64_t mask[2] = { 1, 0 };
212 	int log = 0;
213 
214 	assert(divisor != 0);
215 
216 	divisor_128[0] = divisor;
217 	divisor_128[1] = 0;
218 
219 	remainder[0] = dividend[0];
220 	remainder[1] = dividend[1];
221 
222 	subtrahend[0] = divisor;
223 	subtrahend[1] = 0;
224 
225 	while (divisor > 0) {
226 		log++;
227 		divisor >>= 1;
228 	}
229 
230 	dt_shift_128(subtrahend, 128 - log);
231 	dt_shift_128(mask, 128 - log);
232 
233 	while (dt_ge_128(remainder, divisor_128)) {
234 		if (dt_ge_128(remainder, subtrahend)) {
235 			dt_subtract_128(remainder, subtrahend, remainder);
236 			result[0] |= mask[0];
237 			result[1] |= mask[1];
238 		}
239 
240 		dt_shift_128(subtrahend, -1);
241 		dt_shift_128(mask, -1);
242 	}
243 
244 	quotient[0] = result[0];
245 	quotient[1] = result[1];
246 }
247 
248 /*
249  * This is the long-hand method of calculating a square root.
250  * The algorithm is as follows:
251  *
252  * 1. Group the digits by 2 from the right.
253  * 2. Over the leftmost group, find the largest single-digit number
254  *    whose square is less than that group.
255  * 3. Subtract the result of the previous step (2 or 4, depending) and
256  *    bring down the next two-digit group.
257  * 4. For the result R we have so far, find the largest single-digit number
258  *    x such that 2 * R * 10 * x + x^2 is less than the result from step 3.
259  *    (Note that this is doubling R and performing a decimal left-shift by 1
260  *    and searching for the appropriate decimal to fill the one's place.)
261  *    The value x is the next digit in the square root.
262  * Repeat steps 3 and 4 until the desired precision is reached.  (We're
263  * dealing with integers, so the above is sufficient.)
264  *
265  * In decimal, the square root of 582,734 would be calculated as so:
266  *
267  *     __7__6__3
268  *    | 58 27 34
269  *     -49       (7^2 == 49 => 7 is the first digit in the square root)
270  *      --
271  *       9 27    (Subtract and bring down the next group.)
272  * 146   8 76    (2 * 7 * 10 * 6 + 6^2 == 876 => 6 is the next digit in
273  *      -----     the square root)
274  *         51 34 (Subtract and bring down the next group.)
275  * 1523    45 69 (2 * 76 * 10 * 3 + 3^2 == 4569 => 3 is the next digit in
276  *         -----  the square root)
277  *          5 65 (remainder)
278  *
279  * The above algorithm applies similarly in binary, but note that the
280  * only possible non-zero value for x in step 4 is 1, so step 4 becomes a
281  * simple decision: is 2 * R * 2 * 1 + 1^2 (aka R << 2 + 1) less than the
282  * preceding difference?
283  *
284  * In binary, the square root of 11011011 would be calculated as so:
285  *
286  *     __1__1__1__0
287  *    | 11 01 10 11
288  *      01          (0 << 2 + 1 == 1 < 11 => this bit is 1)
289  *      --
290  *      10 01 10 11
291  * 101   1 01       (1 << 2 + 1 == 101 < 1001 => next bit is 1)
292  *      -----
293  *       1 00 10 11
294  * 1101    11 01    (11 << 2 + 1 == 1101 < 10010 => next bit is 1)
295  *       -------
296  *          1 01 11
297  * 11101    1 11 01 (111 << 2 + 1 == 11101 > 10111 => last bit is 0)
298  *
299  */
300 static uint64_t
301 dt_sqrt_128(uint64_t *square)
302 {
303 	uint64_t result[2] = { 0, 0 };
304 	uint64_t diff[2] = { 0, 0 };
305 	uint64_t one[2] = { 1, 0 };
306 	uint64_t next_pair[2];
307 	uint64_t next_try[2];
308 	uint64_t bit_pairs, pair_shift;
309 	int i;
310 
311 	bit_pairs = dt_nbits_128(square) / 2;
312 	pair_shift = bit_pairs * 2;
313 
314 	for (i = 0; i <= bit_pairs; i++) {
315 		/*
316 		 * Bring down the next pair of bits.
317 		 */
318 		next_pair[0] = square[0];
319 		next_pair[1] = square[1];
320 		dt_shift_128(next_pair, -pair_shift);
321 		next_pair[0] &= 0x3;
322 		next_pair[1] = 0;
323 
324 		dt_shift_128(diff, 2);
325 		dt_add_128(diff, next_pair, diff);
326 
327 		/*
328 		 * next_try = R << 2 + 1
329 		 */
330 		next_try[0] = result[0];
331 		next_try[1] = result[1];
332 		dt_shift_128(next_try, 2);
333 		dt_add_128(next_try, one, next_try);
334 
335 		if (dt_le_128(next_try, diff)) {
336 			dt_subtract_128(diff, next_try, diff);
337 			dt_shift_128(result, 1);
338 			dt_add_128(result, one, result);
339 		} else {
340 			dt_shift_128(result, 1);
341 		}
342 
343 		pair_shift -= 2;
344 	}
345 
346 	assert(result[1] == 0);
347 
348 	return (result[0]);
349 }
350 
351 uint64_t
352 dt_stddev(uint64_t *data, uint64_t normal)
353 {
354 	uint64_t avg_of_squares[2];
355 	uint64_t square_of_avg[2];
356 	int64_t norm_avg;
357 	uint64_t diff[2];
358 
359 	/*
360 	 * The standard approximation for standard deviation is
361 	 * sqrt(average(x**2) - average(x)**2), i.e. the square root
362 	 * of the average of the squares minus the square of the average.
363 	 */
364 	dt_divide_128(data + 2, normal, avg_of_squares);
365 	dt_divide_128(avg_of_squares, data[0], avg_of_squares);
366 
367 	norm_avg = (int64_t)data[1] / (int64_t)normal / (int64_t)data[0];
368 
369 	if (norm_avg < 0)
370 		norm_avg = -norm_avg;
371 
372 	dt_multiply_128((uint64_t)norm_avg, (uint64_t)norm_avg, square_of_avg);
373 
374 	dt_subtract_128(avg_of_squares, square_of_avg, diff);
375 
376 	return (dt_sqrt_128(diff));
377 }
378 
379 static int
380 dt_flowindent(dtrace_hdl_t *dtp, dtrace_probedata_t *data, dtrace_epid_t last,
381     dtrace_bufdesc_t *buf, size_t offs)
382 {
383 	dtrace_probedesc_t *pd = data->dtpda_pdesc, *npd;
384 	dtrace_eprobedesc_t *epd = data->dtpda_edesc, *nepd;
385 	char *p = pd->dtpd_provider, *n = pd->dtpd_name, *sub;
386 	dtrace_flowkind_t flow = DTRACEFLOW_NONE;
387 	const char *str = NULL;
388 	static const char *e_str[2] = { " -> ", " => " };
389 	static const char *r_str[2] = { " <- ", " <= " };
390 	static const char *ent = "entry", *ret = "return";
391 	static int entlen = 0, retlen = 0;
392 	dtrace_epid_t next, id = epd->dtepd_epid;
393 	int rval;
394 
395 	if (entlen == 0) {
396 		assert(retlen == 0);
397 		entlen = strlen(ent);
398 		retlen = strlen(ret);
399 	}
400 
401 	/*
402 	 * If the name of the probe is "entry" or ends with "-entry", we
403 	 * treat it as an entry; if it is "return" or ends with "-return",
404 	 * we treat it as a return.  (This allows application-provided probes
405 	 * like "method-entry" or "function-entry" to participate in flow
406 	 * indentation -- without accidentally misinterpreting popular probe
407 	 * names like "carpentry", "gentry" or "Coventry".)
408 	 */
409 	if ((sub = strstr(n, ent)) != NULL && sub[entlen] == '\0' &&
410 	    (sub == n || sub[-1] == '-')) {
411 		flow = DTRACEFLOW_ENTRY;
412 		str = e_str[strcmp(p, "syscall") == 0];
413 	} else if ((sub = strstr(n, ret)) != NULL && sub[retlen] == '\0' &&
414 	    (sub == n || sub[-1] == '-')) {
415 		flow = DTRACEFLOW_RETURN;
416 		str = r_str[strcmp(p, "syscall") == 0];
417 	}
418 
419 	/*
420 	 * If we're going to indent this, we need to check the ID of our last
421 	 * call.  If we're looking at the same probe ID but a different EPID,
422 	 * we _don't_ want to indent.  (Yes, there are some minor holes in
423 	 * this scheme -- it's a heuristic.)
424 	 */
425 	if (flow == DTRACEFLOW_ENTRY) {
426 		if ((last != DTRACE_EPIDNONE && id != last &&
427 		    pd->dtpd_id == dtp->dt_pdesc[last]->dtpd_id))
428 			flow = DTRACEFLOW_NONE;
429 	}
430 
431 	/*
432 	 * If we're going to unindent this, it's more difficult to see if
433 	 * we don't actually want to unindent it -- we need to look at the
434 	 * _next_ EPID.
435 	 */
436 	if (flow == DTRACEFLOW_RETURN) {
437 		offs += epd->dtepd_size;
438 
439 		do {
440 			if (offs >= buf->dtbd_size) {
441 				/*
442 				 * We're at the end -- maybe.  If the oldest
443 				 * record is non-zero, we need to wrap.
444 				 */
445 				if (buf->dtbd_oldest != 0) {
446 					offs = 0;
447 				} else {
448 					goto out;
449 				}
450 			}
451 
452 			next = *(uint32_t *)((uintptr_t)buf->dtbd_data + offs);
453 
454 			if (next == DTRACE_EPIDNONE)
455 				offs += sizeof (id);
456 		} while (next == DTRACE_EPIDNONE);
457 
458 		if ((rval = dt_epid_lookup(dtp, next, &nepd, &npd)) != 0)
459 			return (rval);
460 
461 		if (next != id && npd->dtpd_id == pd->dtpd_id)
462 			flow = DTRACEFLOW_NONE;
463 	}
464 
465 out:
466 	if (flow == DTRACEFLOW_ENTRY || flow == DTRACEFLOW_RETURN) {
467 		data->dtpda_prefix = str;
468 	} else {
469 		data->dtpda_prefix = "| ";
470 	}
471 
472 	if (flow == DTRACEFLOW_RETURN && data->dtpda_indent > 0)
473 		data->dtpda_indent -= 2;
474 
475 	data->dtpda_flow = flow;
476 
477 	return (0);
478 }
479 
480 static int
481 dt_nullprobe()
482 {
483 	return (DTRACE_CONSUME_THIS);
484 }
485 
486 static int
487 dt_nullrec()
488 {
489 	return (DTRACE_CONSUME_NEXT);
490 }
491 
492 int
493 dt_print_quantline(dtrace_hdl_t *dtp, FILE *fp, int64_t val,
494     uint64_t normal, long double total, char positives, char negatives)
495 {
496 	long double f;
497 	uint_t depth, len = 40;
498 
499 	const char *ats = "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@";
500 	const char *spaces = "                                        ";
501 
502 	assert(strlen(ats) == len && strlen(spaces) == len);
503 	assert(!(total == 0 && (positives || negatives)));
504 	assert(!(val < 0 && !negatives));
505 	assert(!(val > 0 && !positives));
506 	assert(!(val != 0 && total == 0));
507 
508 	if (!negatives) {
509 		if (positives) {
510 			f = (dt_fabsl((long double)val) * len) / total;
511 			depth = (uint_t)(f + 0.5);
512 		} else {
513 			depth = 0;
514 		}
515 
516 		return (dt_printf(dtp, fp, "|%s%s %-9lld\n", ats + len - depth,
517 		    spaces + depth, (long long)val / normal));
518 	}
519 
520 	if (!positives) {
521 		f = (dt_fabsl((long double)val) * len) / total;
522 		depth = (uint_t)(f + 0.5);
523 
524 		return (dt_printf(dtp, fp, "%s%s| %-9lld\n", spaces + depth,
525 		    ats + len - depth, (long long)val / normal));
526 	}
527 
528 	/*
529 	 * If we're here, we have both positive and negative bucket values.
530 	 * To express this graphically, we're going to generate both positive
531 	 * and negative bars separated by a centerline.  These bars are half
532 	 * the size of normal quantize()/lquantize() bars, so we divide the
533 	 * length in half before calculating the bar length.
534 	 */
535 	len /= 2;
536 	ats = &ats[len];
537 	spaces = &spaces[len];
538 
539 	f = (dt_fabsl((long double)val) * len) / total;
540 	depth = (uint_t)(f + 0.5);
541 
542 	if (val <= 0) {
543 		return (dt_printf(dtp, fp, "%s%s|%*s %-9lld\n", spaces + depth,
544 		    ats + len - depth, len, "", (long long)val / normal));
545 	} else {
546 		return (dt_printf(dtp, fp, "%20s|%s%s %-9lld\n", "",
547 		    ats + len - depth, spaces + depth,
548 		    (long long)val / normal));
549 	}
550 }
551 
552 int
553 dt_print_quantize(dtrace_hdl_t *dtp, FILE *fp, const void *addr,
554     size_t size, uint64_t normal)
555 {
556 	const int64_t *data = addr;
557 	int i, first_bin = 0, last_bin = DTRACE_QUANTIZE_NBUCKETS - 1;
558 	long double total = 0;
559 	char positives = 0, negatives = 0;
560 
561 	if (size != DTRACE_QUANTIZE_NBUCKETS * sizeof (uint64_t))
562 		return (dt_set_errno(dtp, EDT_DMISMATCH));
563 
564 	while (first_bin < DTRACE_QUANTIZE_NBUCKETS - 1 && data[first_bin] == 0)
565 		first_bin++;
566 
567 	if (first_bin == DTRACE_QUANTIZE_NBUCKETS - 1) {
568 		/*
569 		 * There isn't any data.  This is possible if (and only if)
570 		 * negative increment values have been used.  In this case,
571 		 * we'll print the buckets around 0.
572 		 */
573 		first_bin = DTRACE_QUANTIZE_ZEROBUCKET - 1;
574 		last_bin = DTRACE_QUANTIZE_ZEROBUCKET + 1;
575 	} else {
576 		if (first_bin > 0)
577 			first_bin--;
578 
579 		while (last_bin > 0 && data[last_bin] == 0)
580 			last_bin--;
581 
582 		if (last_bin < DTRACE_QUANTIZE_NBUCKETS - 1)
583 			last_bin++;
584 	}
585 
586 	for (i = first_bin; i <= last_bin; i++) {
587 		positives |= (data[i] > 0);
588 		negatives |= (data[i] < 0);
589 		total += dt_fabsl((long double)data[i]);
590 	}
591 
592 	if (dt_printf(dtp, fp, "\n%16s %41s %-9s\n", "value",
593 	    "------------- Distribution -------------", "count") < 0)
594 		return (-1);
595 
596 	for (i = first_bin; i <= last_bin; i++) {
597 		if (dt_printf(dtp, fp, "%16lld ",
598 		    (long long)DTRACE_QUANTIZE_BUCKETVAL(i)) < 0)
599 			return (-1);
600 
601 		if (dt_print_quantline(dtp, fp, data[i], normal, total,
602 		    positives, negatives) < 0)
603 			return (-1);
604 	}
605 
606 	return (0);
607 }
608 
609 int
610 dt_print_lquantize(dtrace_hdl_t *dtp, FILE *fp, const void *addr,
611     size_t size, uint64_t normal)
612 {
613 	const int64_t *data = addr;
614 	int i, first_bin, last_bin, base;
615 	uint64_t arg;
616 	long double total = 0;
617 	uint16_t step, levels;
618 	char positives = 0, negatives = 0;
619 
620 	if (size < sizeof (uint64_t))
621 		return (dt_set_errno(dtp, EDT_DMISMATCH));
622 
623 	arg = *data++;
624 	size -= sizeof (uint64_t);
625 
626 	base = DTRACE_LQUANTIZE_BASE(arg);
627 	step = DTRACE_LQUANTIZE_STEP(arg);
628 	levels = DTRACE_LQUANTIZE_LEVELS(arg);
629 
630 	first_bin = 0;
631 	last_bin = levels + 1;
632 
633 	if (size != sizeof (uint64_t) * (levels + 2))
634 		return (dt_set_errno(dtp, EDT_DMISMATCH));
635 
636 	while (first_bin <= levels + 1 && data[first_bin] == 0)
637 		first_bin++;
638 
639 	if (first_bin > levels + 1) {
640 		first_bin = 0;
641 		last_bin = 2;
642 	} else {
643 		if (first_bin > 0)
644 			first_bin--;
645 
646 		while (last_bin > 0 && data[last_bin] == 0)
647 			last_bin--;
648 
649 		if (last_bin < levels + 1)
650 			last_bin++;
651 	}
652 
653 	for (i = first_bin; i <= last_bin; i++) {
654 		positives |= (data[i] > 0);
655 		negatives |= (data[i] < 0);
656 		total += dt_fabsl((long double)data[i]);
657 	}
658 
659 	if (dt_printf(dtp, fp, "\n%16s %41s %-9s\n", "value",
660 	    "------------- Distribution -------------", "count") < 0)
661 		return (-1);
662 
663 	for (i = first_bin; i <= last_bin; i++) {
664 		char c[32];
665 		int err;
666 
667 		if (i == 0) {
668 			(void) snprintf(c, sizeof (c), "< %d",
669 			    base / (uint32_t)normal);
670 			err = dt_printf(dtp, fp, "%16s ", c);
671 		} else if (i == levels + 1) {
672 			(void) snprintf(c, sizeof (c), ">= %d",
673 			    base + (levels * step));
674 			err = dt_printf(dtp, fp, "%16s ", c);
675 		} else {
676 			err = dt_printf(dtp, fp, "%16d ",
677 			    base + (i - 1) * step);
678 		}
679 
680 		if (err < 0 || dt_print_quantline(dtp, fp, data[i], normal,
681 		    total, positives, negatives) < 0)
682 			return (-1);
683 	}
684 
685 	return (0);
686 }
687 
688 /*ARGSUSED*/
689 static int
690 dt_print_average(dtrace_hdl_t *dtp, FILE *fp, caddr_t addr,
691     size_t size, uint64_t normal)
692 {
693 	/* LINTED - alignment */
694 	int64_t *data = (int64_t *)addr;
695 
696 	return (dt_printf(dtp, fp, " %16lld", data[0] ?
697 	    (long long)(data[1] / (int64_t)normal / data[0]) : 0));
698 }
699 
700 /*ARGSUSED*/
701 static int
702 dt_print_stddev(dtrace_hdl_t *dtp, FILE *fp, caddr_t addr,
703     size_t size, uint64_t normal)
704 {
705 	/* LINTED - alignment */
706 	uint64_t *data = (uint64_t *)addr;
707 
708 	return (dt_printf(dtp, fp, " %16llu", data[0] ?
709 	    (unsigned long long) dt_stddev(data, normal) : 0));
710 }
711 
712 /*ARGSUSED*/
713 int
714 dt_print_bytes(dtrace_hdl_t *dtp, FILE *fp, caddr_t addr,
715     size_t nbytes, int width, int quiet, int raw)
716 {
717 	/*
718 	 * If the byte stream is a series of printable characters, followed by
719 	 * a terminating byte, we print it out as a string.  Otherwise, we
720 	 * assume that it's something else and just print the bytes.
721 	 */
722 	int i, j, margin = 5;
723 	char *c = (char *)addr;
724 
725 	if (nbytes == 0)
726 		return (0);
727 
728 	if (raw || dtp->dt_options[DTRACEOPT_RAWBYTES] != DTRACEOPT_UNSET)
729 		goto raw;
730 
731 	for (i = 0; i < nbytes; i++) {
732 		/*
733 		 * We define a "printable character" to be one for which
734 		 * isprint(3C) returns non-zero, isspace(3C) returns non-zero,
735 		 * or a character which is either backspace or the bell.
736 		 * Backspace and the bell are regrettably special because
737 		 * they fail the first two tests -- and yet they are entirely
738 		 * printable.  These are the only two control characters that
739 		 * have meaning for the terminal and for which isprint(3C) and
740 		 * isspace(3C) return 0.
741 		 */
742 		if (isprint(c[i]) || isspace(c[i]) ||
743 		    c[i] == '\b' || c[i] == '\a')
744 			continue;
745 
746 		if (c[i] == '\0' && i > 0) {
747 			/*
748 			 * This looks like it might be a string.  Before we
749 			 * assume that it is indeed a string, check the
750 			 * remainder of the byte range; if it contains
751 			 * additional non-nul characters, we'll assume that
752 			 * it's a binary stream that just happens to look like
753 			 * a string, and we'll print out the individual bytes.
754 			 */
755 			for (j = i + 1; j < nbytes; j++) {
756 				if (c[j] != '\0')
757 					break;
758 			}
759 
760 			if (j != nbytes)
761 				break;
762 
763 			if (quiet)
764 				return (dt_printf(dtp, fp, "%s", c));
765 			else
766 				return (dt_printf(dtp, fp, "  %-*s", width, c));
767 		}
768 
769 		break;
770 	}
771 
772 	if (i == nbytes) {
773 		/*
774 		 * The byte range is all printable characters, but there is
775 		 * no trailing nul byte.  We'll assume that it's a string and
776 		 * print it as such.
777 		 */
778 		char *s = alloca(nbytes + 1);
779 		bcopy(c, s, nbytes);
780 		s[nbytes] = '\0';
781 		return (dt_printf(dtp, fp, "  %-*s", width, s));
782 	}
783 
784 raw:
785 	if (dt_printf(dtp, fp, "\n%*s      ", margin, "") < 0)
786 		return (-1);
787 
788 	for (i = 0; i < 16; i++)
789 		if (dt_printf(dtp, fp, "  %c", "0123456789abcdef"[i]) < 0)
790 			return (-1);
791 
792 	if (dt_printf(dtp, fp, "  0123456789abcdef\n") < 0)
793 		return (-1);
794 
795 
796 	for (i = 0; i < nbytes; i += 16) {
797 		if (dt_printf(dtp, fp, "%*s%5x:", margin, "", i) < 0)
798 			return (-1);
799 
800 		for (j = i; j < i + 16 && j < nbytes; j++) {
801 			if (dt_printf(dtp, fp, " %02x", (uchar_t)c[j]) < 0)
802 				return (-1);
803 		}
804 
805 		while (j++ % 16) {
806 			if (dt_printf(dtp, fp, "   ") < 0)
807 				return (-1);
808 		}
809 
810 		if (dt_printf(dtp, fp, "  ") < 0)
811 			return (-1);
812 
813 		for (j = i; j < i + 16 && j < nbytes; j++) {
814 			if (dt_printf(dtp, fp, "%c",
815 			    c[j] < ' ' || c[j] > '~' ? '.' : c[j]) < 0)
816 				return (-1);
817 		}
818 
819 		if (dt_printf(dtp, fp, "\n") < 0)
820 			return (-1);
821 	}
822 
823 	return (0);
824 }
825 
826 int
827 dt_print_stack(dtrace_hdl_t *dtp, FILE *fp, const char *format,
828     caddr_t addr, int depth, int size)
829 {
830 	dtrace_syminfo_t dts;
831 	GElf_Sym sym;
832 	int i, indent;
833 	char c[PATH_MAX * 2];
834 	uint64_t pc;
835 
836 	if (dt_printf(dtp, fp, "\n") < 0)
837 		return (-1);
838 
839 	if (format == NULL)
840 		format = "%s";
841 
842 	if (dtp->dt_options[DTRACEOPT_STACKINDENT] != DTRACEOPT_UNSET)
843 		indent = (int)dtp->dt_options[DTRACEOPT_STACKINDENT];
844 	else
845 		indent = _dtrace_stkindent;
846 
847 	for (i = 0; i < depth; i++) {
848 		switch (size) {
849 		case sizeof (uint32_t):
850 			/* LINTED - alignment */
851 			pc = *((uint32_t *)addr);
852 			break;
853 
854 		case sizeof (uint64_t):
855 			/* LINTED - alignment */
856 			pc = *((uint64_t *)addr);
857 			break;
858 
859 		default:
860 			return (dt_set_errno(dtp, EDT_BADSTACKPC));
861 		}
862 
863 		if (pc == 0)
864 			break;
865 
866 		addr += size;
867 
868 		if (dt_printf(dtp, fp, "%*s", indent, "") < 0)
869 			return (-1);
870 
871 		if (dtrace_lookup_by_addr(dtp, pc, &sym, &dts) == 0) {
872 			if (pc > sym.st_value) {
873 				(void) snprintf(c, sizeof (c), "%s`%s+0x%llx",
874 				    dts.dts_object, dts.dts_name,
875 				    pc - sym.st_value);
876 			} else {
877 				(void) snprintf(c, sizeof (c), "%s`%s",
878 				    dts.dts_object, dts.dts_name);
879 			}
880 		} else {
881 			/*
882 			 * We'll repeat the lookup, but this time we'll specify
883 			 * a NULL GElf_Sym -- indicating that we're only
884 			 * interested in the containing module.
885 			 */
886 			if (dtrace_lookup_by_addr(dtp, pc, NULL, &dts) == 0) {
887 				(void) snprintf(c, sizeof (c), "%s`0x%llx",
888 				    dts.dts_object, pc);
889 			} else {
890 				(void) snprintf(c, sizeof (c), "0x%llx", pc);
891 			}
892 		}
893 
894 		if (dt_printf(dtp, fp, format, c) < 0)
895 			return (-1);
896 
897 		if (dt_printf(dtp, fp, "\n") < 0)
898 			return (-1);
899 	}
900 
901 	return (0);
902 }
903 
904 int
905 dt_print_ustack(dtrace_hdl_t *dtp, FILE *fp, const char *format,
906     caddr_t addr, uint64_t arg)
907 {
908 #if 0	/* XXX TBD needs libproc */
909 	/* LINTED - alignment */
910 	uint64_t *pc = (uint64_t *)addr;
911 	uint32_t depth = DTRACE_USTACK_NFRAMES(arg);
912 	uint32_t strsize = DTRACE_USTACK_STRSIZE(arg);
913 	const char *strbase = addr + (depth + 1) * sizeof (uint64_t);
914 	const char *str = strsize ? strbase : NULL;
915 	int err = 0;
916 
917 	char name[PATH_MAX], objname[PATH_MAX], c[PATH_MAX * 2];
918 	struct ps_prochandle *P;
919 	GElf_Sym sym;
920 	int i, indent;
921 	pid_t pid;
922 
923 	if (depth == 0)
924 		return (0);
925 
926 	pid = (pid_t)*pc++;
927 
928 	if (dt_printf(dtp, fp, "\n") < 0)
929 		return (-1);
930 
931 	if (format == NULL)
932 		format = "%s";
933 
934 	if (dtp->dt_options[DTRACEOPT_STACKINDENT] != DTRACEOPT_UNSET)
935 		indent = (int)dtp->dt_options[DTRACEOPT_STACKINDENT];
936 	else
937 		indent = _dtrace_stkindent;
938 
939 	/*
940 	 * Ultimately, we need to add an entry point in the library vector for
941 	 * determining <symbol, offset> from <pid, address>.  For now, if
942 	 * this is a vector open, we just print the raw address or string.
943 	 */
944 	if (dtp->dt_vector == NULL)
945 		P = dt_proc_grab(dtp, pid, PGRAB_RDONLY | PGRAB_FORCE, 0);
946 	else
947 		P = NULL;
948 
949 	if (P != NULL)
950 		dt_proc_lock(dtp, P); /* lock handle while we perform lookups */
951 
952 	for (i = 0; i < depth && pc[i] != 0; i++) {
953 		const prmap_t *map;
954 
955 		if ((err = dt_printf(dtp, fp, "%*s", indent, "")) < 0)
956 			break;
957 
958 #if defined(sun)
959 		if (P != NULL && Plookup_by_addr(P, pc[i],
960 #else
961 		if (P != NULL && proc_addr2sym(P, pc[i],
962 #endif
963 		    name, sizeof (name), &sym) == 0) {
964 #if defined(sun)
965 			(void) Pobjname(P, pc[i], objname, sizeof (objname));
966 #else
967 			(void) proc_objname(P, pc[i], objname, sizeof (objname));
968 #endif
969 
970 			if (pc[i] > sym.st_value) {
971 				(void) snprintf(c, sizeof (c),
972 				    "%s`%s+0x%llx", dt_basename(objname), name,
973 				    (u_longlong_t)(pc[i] - sym.st_value));
974 			} else {
975 				(void) snprintf(c, sizeof (c),
976 				    "%s`%s", dt_basename(objname), name);
977 			}
978 		} else if (str != NULL && str[0] != '\0' && str[0] != '@' &&
979 #if defined(sun)
980 		    (P != NULL && ((map = Paddr_to_map(P, pc[i])) == NULL ||
981 		    (map->pr_mflags & MA_WRITE)))) {
982 #else
983 		    (P != NULL && ((map = proc_addr2map(P, pc[i])) == NULL))) {
984 #endif
985 			/*
986 			 * If the current string pointer in the string table
987 			 * does not point to an empty string _and_ the program
988 			 * counter falls in a writable region, we'll use the
989 			 * string from the string table instead of the raw
990 			 * address.  This last condition is necessary because
991 			 * some (broken) ustack helpers will return a string
992 			 * even for a program counter that they can't
993 			 * identify.  If we have a string for a program
994 			 * counter that falls in a segment that isn't
995 			 * writable, we assume that we have fallen into this
996 			 * case and we refuse to use the string.
997 			 */
998 			(void) snprintf(c, sizeof (c), "%s", str);
999 		} else {
1000 #if defined(sun)
1001 			if (P != NULL && Pobjname(P, pc[i], objname,
1002 #else
1003 			if (P != NULL && proc_objname(P, pc[i], objname,
1004 #endif
1005 			    sizeof (objname)) != 0) {
1006 				(void) snprintf(c, sizeof (c), "%s`0x%llx",
1007 				    dt_basename(objname), (u_longlong_t)pc[i]);
1008 			} else {
1009 				(void) snprintf(c, sizeof (c), "0x%llx",
1010 				    (u_longlong_t)pc[i]);
1011 			}
1012 		}
1013 
1014 		if ((err = dt_printf(dtp, fp, format, c)) < 0)
1015 			break;
1016 
1017 		if ((err = dt_printf(dtp, fp, "\n")) < 0)
1018 			break;
1019 
1020 		if (str != NULL && str[0] == '@') {
1021 			/*
1022 			 * If the first character of the string is an "at" sign,
1023 			 * then the string is inferred to be an annotation --
1024 			 * and it is printed out beneath the frame and offset
1025 			 * with brackets.
1026 			 */
1027 			if ((err = dt_printf(dtp, fp, "%*s", indent, "")) < 0)
1028 				break;
1029 
1030 			(void) snprintf(c, sizeof (c), "  [ %s ]", &str[1]);
1031 
1032 			if ((err = dt_printf(dtp, fp, format, c)) < 0)
1033 				break;
1034 
1035 			if ((err = dt_printf(dtp, fp, "\n")) < 0)
1036 				break;
1037 		}
1038 
1039 		if (str != NULL) {
1040 			str += strlen(str) + 1;
1041 			if (str - strbase >= strsize)
1042 				str = NULL;
1043 		}
1044 	}
1045 
1046 	if (P != NULL) {
1047 		dt_proc_unlock(dtp, P);
1048 		dt_proc_release(dtp, P);
1049 	}
1050 
1051 	return (err);
1052 #else
1053 	printf("XXX %s not implemented\n", __func__);
1054 	return ENODEV;
1055 #endif
1056 }
1057 
1058 static int
1059 dt_print_usym(dtrace_hdl_t *dtp, FILE *fp, caddr_t addr, dtrace_actkind_t act)
1060 {
1061 #if 0	/* XXX TBD needs libproc */
1062 	/* LINTED - alignment */
1063 	uint64_t pid = ((uint64_t *)addr)[0];
1064 	/* LINTED - alignment */
1065 	uint64_t pc = ((uint64_t *)addr)[1];
1066 	const char *format = "  %-50s";
1067 	char *s;
1068 	int n, len = 256;
1069 
1070 	if (act == DTRACEACT_USYM && dtp->dt_vector == NULL) {
1071 		struct ps_prochandle *P;
1072 
1073 		if ((P = dt_proc_grab(dtp, pid,
1074 		    PGRAB_RDONLY | PGRAB_FORCE, 0)) != NULL) {
1075 			GElf_Sym sym;
1076 
1077 			dt_proc_lock(dtp, P);
1078 
1079 #if defined(sun)
1080 			if (Plookup_by_addr(P, pc, NULL, 0, &sym) == 0)
1081 #else
1082 			if (proc_addr2sym(P, pc, NULL, 0, &sym) == 0)
1083 #endif
1084 				pc = sym.st_value;
1085 
1086 			dt_proc_unlock(dtp, P);
1087 			dt_proc_release(dtp, P);
1088 		}
1089 	}
1090 
1091 	do {
1092 		n = len;
1093 		s = alloca(n);
1094 	} while ((len = dtrace_uaddr2str(dtp, pid, pc, s, n)) >= n);
1095 
1096 	return (dt_printf(dtp, fp, format, s));
1097 #else
1098 	printf("XXX %s not implemented\n", __func__);
1099 	return ENODEV;
1100 #endif
1101 }
1102 
1103 int
1104 dt_print_umod(dtrace_hdl_t *dtp, FILE *fp, const char *format, caddr_t addr)
1105 {
1106 #if 0	/* XXX TBD needs libproc */
1107 	/* LINTED - alignment */
1108 	uint64_t pid = ((uint64_t *)addr)[0];
1109 	/* LINTED - alignment */
1110 	uint64_t pc = ((uint64_t *)addr)[1];
1111 	int err = 0;
1112 
1113 	char objname[PATH_MAX], c[PATH_MAX * 2];
1114 	struct ps_prochandle *P;
1115 
1116 	if (format == NULL)
1117 		format = "  %-50s";
1118 
1119 	/*
1120 	 * See the comment in dt_print_ustack() for the rationale for
1121 	 * printing raw addresses in the vectored case.
1122 	 */
1123 	if (dtp->dt_vector == NULL)
1124 		P = dt_proc_grab(dtp, pid, PGRAB_RDONLY | PGRAB_FORCE, 0);
1125 	else
1126 		P = NULL;
1127 
1128 	if (P != NULL)
1129 		dt_proc_lock(dtp, P); /* lock handle while we perform lookups */
1130 
1131 #if defined(sun)
1132 	if (P != NULL && Pobjname(P, pc, objname, sizeof (objname)) != 0) {
1133 #else
1134 	if (P != NULL && proc_objname(P, pc, objname, sizeof (objname)) != 0) {
1135 #endif
1136 		(void) snprintf(c, sizeof (c), "%s", dt_basename(objname));
1137 	} else {
1138 		(void) snprintf(c, sizeof (c), "0x%llx", (u_longlong_t)pc);
1139 	}
1140 
1141 	err = dt_printf(dtp, fp, format, c);
1142 
1143 	if (P != NULL) {
1144 		dt_proc_unlock(dtp, P);
1145 		dt_proc_release(dtp, P);
1146 	}
1147 
1148 	return (err);
1149 #else
1150 	printf("XXX %s not implemented\n", __func__);
1151 	return -1;
1152 #endif
1153 }
1154 
1155 int
1156 dt_print_memory(dtrace_hdl_t *dtp, FILE *fp, caddr_t addr)
1157 {
1158 	int quiet = (dtp->dt_options[DTRACEOPT_QUIET] != DTRACEOPT_UNSET);
1159 	size_t nbytes = *((uintptr_t *) addr);
1160 
1161 	return (dt_print_bytes(dtp, fp, addr + sizeof(uintptr_t),
1162 	    nbytes, 50, quiet, 1));
1163 }
1164 
1165 typedef struct dt_type_cbdata {
1166 	dtrace_hdl_t		*dtp;
1167 	dtrace_typeinfo_t	dtt;
1168 	caddr_t			addr;
1169 	caddr_t			addrend;
1170 	const char		*name;
1171 	int			f_type;
1172 	int			indent;
1173 	int			type_width;
1174 	int			name_width;
1175 	FILE			*fp;
1176 } dt_type_cbdata_t;
1177 
1178 static int	dt_print_type_data(dt_type_cbdata_t *, ctf_id_t);
1179 
1180 static int
1181 dt_print_type_member(const char *name, ctf_id_t type, ulong_t off, void *arg)
1182 {
1183 	dt_type_cbdata_t cbdata;
1184 	dt_type_cbdata_t *cbdatap = arg;
1185 	ssize_t ssz;
1186 
1187 	if ((ssz = ctf_type_size(cbdatap->dtt.dtt_ctfp, type)) <= 0)
1188 		return (0);
1189 
1190 	off /= 8;
1191 
1192 	cbdata = *cbdatap;
1193 	cbdata.name = name;
1194 	cbdata.addr += off;
1195 	cbdata.addrend = cbdata.addr + ssz;
1196 
1197 	return (dt_print_type_data(&cbdata, type));
1198 }
1199 
1200 static int
1201 dt_print_type_width(const char *name, ctf_id_t type, ulong_t off, void *arg)
1202 {
1203 	char buf[DT_TYPE_NAMELEN];
1204 	char *p;
1205 	dt_type_cbdata_t *cbdatap = arg;
1206 	size_t sz = strlen(name);
1207 
1208 	ctf_type_name(cbdatap->dtt.dtt_ctfp, type, buf, sizeof (buf));
1209 
1210 	if ((p = strchr(buf, '[')) != NULL)
1211 		p[-1] = '\0';
1212 	else
1213 		p = "";
1214 
1215 	sz += strlen(p);
1216 
1217 	if (sz > cbdatap->name_width)
1218 		cbdatap->name_width = sz;
1219 
1220 	sz = strlen(buf);
1221 
1222 	if (sz > cbdatap->type_width)
1223 		cbdatap->type_width = sz;
1224 
1225 	return (0);
1226 }
1227 
1228 static int
1229 dt_print_type_data(dt_type_cbdata_t *cbdatap, ctf_id_t type)
1230 {
1231 	caddr_t addr = cbdatap->addr;
1232 	caddr_t addrend = cbdatap->addrend;
1233 	char buf[DT_TYPE_NAMELEN];
1234 	char *p;
1235 	int cnt = 0;
1236 	uint_t kind = ctf_type_kind(cbdatap->dtt.dtt_ctfp, type);
1237 	ssize_t ssz = ctf_type_size(cbdatap->dtt.dtt_ctfp, type);
1238 
1239 	ctf_type_name(cbdatap->dtt.dtt_ctfp, type, buf, sizeof (buf));
1240 
1241 	if ((p = strchr(buf, '[')) != NULL)
1242 		p[-1] = '\0';
1243 	else
1244 		p = "";
1245 
1246 	if (cbdatap->f_type) {
1247 		int type_width = roundup(cbdatap->type_width + 1, 4);
1248 		int name_width = roundup(cbdatap->name_width + 1, 4);
1249 
1250 		name_width -= strlen(cbdatap->name);
1251 
1252 		dt_printf(cbdatap->dtp, cbdatap->fp, "%*s%-*s%s%-*s	= ",cbdatap->indent * 4,"",type_width,buf,cbdatap->name,name_width,p);
1253 	}
1254 
1255 	while (addr < addrend) {
1256 		dt_type_cbdata_t cbdata;
1257 		ctf_arinfo_t arinfo;
1258 		ctf_encoding_t cte;
1259 		uintptr_t *up;
1260 		void *vp = addr;
1261 		cbdata = *cbdatap;
1262 		cbdata.name = "";
1263 		cbdata.addr = addr;
1264 		cbdata.addrend = addr + ssz;
1265 		cbdata.f_type = 0;
1266 		cbdata.indent++;
1267 		cbdata.type_width = 0;
1268 		cbdata.name_width = 0;
1269 
1270 		if (cnt > 0)
1271 			dt_printf(cbdatap->dtp, cbdatap->fp, "%*s", cbdatap->indent * 4,"");
1272 
1273 		switch (kind) {
1274 		case CTF_K_INTEGER:
1275 			if (ctf_type_encoding(cbdatap->dtt.dtt_ctfp, type, &cte) != 0)
1276 				return (-1);
1277 			if ((cte.cte_format & CTF_INT_SIGNED) != 0)
1278 				switch (cte.cte_bits) {
1279 				case 8:
1280 					if (isprint(*((char *) vp)))
1281 						dt_printf(cbdatap->dtp, cbdatap->fp, "'%c', ", *((char *) vp));
1282 					dt_printf(cbdatap->dtp, cbdatap->fp, "%d (0x%x);\n", *((char *) vp), *((char *) vp));
1283 					break;
1284 				case 16:
1285 					dt_printf(cbdatap->dtp, cbdatap->fp, "%hd (0x%hx);\n", *((short *) vp), *((u_short *) vp));
1286 					break;
1287 				case 32:
1288 					dt_printf(cbdatap->dtp, cbdatap->fp, "%d (0x%x);\n", *((int *) vp), *((u_int *) vp));
1289 					break;
1290 				case 64:
1291 					dt_printf(cbdatap->dtp, cbdatap->fp, "%jd (0x%jx);\n", *((long long *) vp), *((unsigned long long *) vp));
1292 					break;
1293 				default:
1294 					dt_printf(cbdatap->dtp, cbdatap->fp, "CTF_K_INTEGER: format %x offset %u bits %u\n",cte.cte_format,cte.cte_offset,cte.cte_bits);
1295 					break;
1296 				}
1297 			else
1298 				switch (cte.cte_bits) {
1299 				case 8:
1300 					dt_printf(cbdatap->dtp, cbdatap->fp, "%u (0x%x);\n", *((uint8_t *) vp) & 0xff, *((uint8_t *) vp) & 0xff);
1301 					break;
1302 				case 16:
1303 					dt_printf(cbdatap->dtp, cbdatap->fp, "%hu (0x%hx);\n", *((u_short *) vp), *((u_short *) vp));
1304 					break;
1305 				case 32:
1306 					dt_printf(cbdatap->dtp, cbdatap->fp, "%u (0x%x);\n", *((u_int *) vp), *((u_int *) vp));
1307 					break;
1308 				case 64:
1309 					dt_printf(cbdatap->dtp, cbdatap->fp, "%ju (0x%jx);\n", *((unsigned long long *) vp), *((unsigned long long *) vp));
1310 					break;
1311 				default:
1312 					dt_printf(cbdatap->dtp, cbdatap->fp, "CTF_K_INTEGER: format %x offset %u bits %u\n",cte.cte_format,cte.cte_offset,cte.cte_bits);
1313 					break;
1314 				}
1315 			break;
1316 		case CTF_K_FLOAT:
1317 			dt_printf(cbdatap->dtp, cbdatap->fp, "CTF_K_FLOAT: format %x offset %u bits %u\n",cte.cte_format,cte.cte_offset,cte.cte_bits);
1318 			break;
1319 		case CTF_K_POINTER:
1320 			dt_printf(cbdatap->dtp, cbdatap->fp, "%p;\n", *((void **) addr));
1321 			break;
1322 		case CTF_K_ARRAY:
1323 			if (ctf_array_info(cbdatap->dtt.dtt_ctfp, type, &arinfo) != 0)
1324 				return (-1);
1325 			dt_printf(cbdatap->dtp, cbdatap->fp, "{\n%*s",cbdata.indent * 4,"");
1326 			dt_print_type_data(&cbdata, arinfo.ctr_contents);
1327 			dt_printf(cbdatap->dtp, cbdatap->fp, "%*s};\n",cbdatap->indent * 4,"");
1328 			break;
1329 		case CTF_K_FUNCTION:
1330 			dt_printf(cbdatap->dtp, cbdatap->fp, "CTF_K_FUNCTION:\n");
1331 			break;
1332 		case CTF_K_STRUCT:
1333 			cbdata.f_type = 1;
1334 			if (ctf_member_iter(cbdatap->dtt.dtt_ctfp, type,
1335 			    dt_print_type_width, &cbdata) != 0)
1336 				return (-1);
1337 			dt_printf(cbdatap->dtp, cbdatap->fp, "{\n");
1338 			if (ctf_member_iter(cbdatap->dtt.dtt_ctfp, type,
1339 			    dt_print_type_member, &cbdata) != 0)
1340 				return (-1);
1341 			dt_printf(cbdatap->dtp, cbdatap->fp, "%*s};\n",cbdatap->indent * 4,"");
1342 			break;
1343 		case CTF_K_UNION:
1344 			cbdata.f_type = 1;
1345 			if (ctf_member_iter(cbdatap->dtt.dtt_ctfp, type,
1346 			    dt_print_type_width, &cbdata) != 0)
1347 				return (-1);
1348 			dt_printf(cbdatap->dtp, cbdatap->fp, "{\n");
1349 			if (ctf_member_iter(cbdatap->dtt.dtt_ctfp, type,
1350 			    dt_print_type_member, &cbdata) != 0)
1351 				return (-1);
1352 			dt_printf(cbdatap->dtp, cbdatap->fp, "%*s};\n",cbdatap->indent * 4,"");
1353 			break;
1354 		case CTF_K_ENUM:
1355 			dt_printf(cbdatap->dtp, cbdatap->fp, "%s;\n", ctf_enum_name(cbdatap->dtt.dtt_ctfp, type, *((int *) vp)));
1356 			break;
1357 		case CTF_K_TYPEDEF:
1358 			dt_print_type_data(&cbdata, ctf_type_reference(cbdatap->dtt.dtt_ctfp,type));
1359 			break;
1360 		case CTF_K_VOLATILE:
1361 			if (cbdatap->f_type)
1362 				dt_printf(cbdatap->dtp, cbdatap->fp, "volatile ");
1363 			dt_print_type_data(&cbdata, ctf_type_reference(cbdatap->dtt.dtt_ctfp,type));
1364 			break;
1365 		case CTF_K_CONST:
1366 			if (cbdatap->f_type)
1367 				dt_printf(cbdatap->dtp, cbdatap->fp, "const ");
1368 			dt_print_type_data(&cbdata, ctf_type_reference(cbdatap->dtt.dtt_ctfp,type));
1369 			break;
1370 		case CTF_K_RESTRICT:
1371 			if (cbdatap->f_type)
1372 				dt_printf(cbdatap->dtp, cbdatap->fp, "restrict ");
1373 			dt_print_type_data(&cbdata, ctf_type_reference(cbdatap->dtt.dtt_ctfp,type));
1374 			break;
1375 		default:
1376 			break;
1377 		}
1378 
1379 		addr += ssz;
1380 		cnt++;
1381 	}
1382 
1383 	return (0);
1384 }
1385 
1386 static int
1387 dt_print_type(dtrace_hdl_t *dtp, FILE *fp, caddr_t addr)
1388 {
1389 	caddr_t addrend;
1390 	char *p;
1391 	dtrace_typeinfo_t dtt;
1392 	dt_type_cbdata_t cbdata;
1393 	int num = 0;
1394 	int quiet = (dtp->dt_options[DTRACEOPT_QUIET] != DTRACEOPT_UNSET);
1395 	ssize_t ssz;
1396 
1397 	if (!quiet)
1398 		dt_printf(dtp, fp, "\n");
1399 
1400 	/* Get the total number of bytes of data buffered. */
1401 	size_t nbytes = *((uintptr_t *) addr);
1402 	addr += sizeof(uintptr_t);
1403 
1404 	/*
1405 	 * Get the size of the type so that we can check that it matches
1406 	 * the CTF data we look up and so that we can figure out how many
1407 	 * type elements are buffered.
1408 	 */
1409 	size_t typs = *((uintptr_t *) addr);
1410 	addr += sizeof(uintptr_t);
1411 
1412 	/*
1413 	 * Point to the type string in the buffer. Get it's string
1414 	 * length and round it up to become the offset to the start
1415 	 * of the buffered type data which we would like to be aligned
1416 	 * for easy access.
1417 	 */
1418 	char *strp = (char *) addr;
1419 	int offset = roundup(strlen(strp) + 1, sizeof(uintptr_t));
1420 
1421 	/*
1422 	 * The type string might have a format such as 'int [20]'.
1423 	 * Check if there is an array dimension present.
1424 	 */
1425 	if ((p = strchr(strp, '[')) != NULL) {
1426 		/* Strip off the array dimension. */
1427 		*p++ = '\0';
1428 
1429 		for (; *p != '\0' && *p != ']'; p++)
1430 			num = num * 10 + *p - '0';
1431 	} else
1432 		/* No array dimension, so default. */
1433 		num = 1;
1434 
1435 	/* Lookup the CTF type from the type string. */
1436 	if (dtrace_lookup_by_type(dtp,  DTRACE_OBJ_EVERY, strp, &dtt) < 0)
1437 		return (-1);
1438 
1439 	/* Offset the buffer address to the start of the data... */
1440 	addr += offset;
1441 
1442 	ssz = ctf_type_size(dtt.dtt_ctfp, dtt.dtt_type);
1443 
1444 	if (typs != ssz) {
1445 		printf("Expected type size from buffer (%lu) to match type size looked up now (%ld)\n", (u_long) typs, (long) ssz);
1446 		return (-1);
1447 	}
1448 
1449 	cbdata.dtp = dtp;
1450 	cbdata.dtt = dtt;
1451 	cbdata.name = "";
1452 	cbdata.addr = addr;
1453 	cbdata.addrend = addr + nbytes;
1454 	cbdata.indent = 1;
1455 	cbdata.f_type = 1;
1456 	cbdata.type_width = 0;
1457 	cbdata.name_width = 0;
1458 	cbdata.fp = fp;
1459 
1460 	return (dt_print_type_data(&cbdata, dtt.dtt_type));
1461 }
1462 
1463 static int
1464 dt_print_sym(dtrace_hdl_t *dtp, FILE *fp, const char *format, caddr_t addr)
1465 {
1466 	/* LINTED - alignment */
1467 	uint64_t pc = *((uint64_t *)addr);
1468 	dtrace_syminfo_t dts;
1469 	GElf_Sym sym;
1470 	char c[PATH_MAX * 2];
1471 
1472 	if (format == NULL)
1473 		format = "  %-50s";
1474 
1475 	if (dtrace_lookup_by_addr(dtp, pc, &sym, &dts) == 0) {
1476 		(void) snprintf(c, sizeof (c), "%s`%s",
1477 		    dts.dts_object, dts.dts_name);
1478 	} else {
1479 		/*
1480 		 * We'll repeat the lookup, but this time we'll specify a
1481 		 * NULL GElf_Sym -- indicating that we're only interested in
1482 		 * the containing module.
1483 		 */
1484 		if (dtrace_lookup_by_addr(dtp, pc, NULL, &dts) == 0) {
1485 			(void) snprintf(c, sizeof (c), "%s`0x%llx",
1486 			    dts.dts_object, (u_longlong_t)pc);
1487 		} else {
1488 			(void) snprintf(c, sizeof (c), "0x%llx",
1489 			    (u_longlong_t)pc);
1490 		}
1491 	}
1492 
1493 	if (dt_printf(dtp, fp, format, c) < 0)
1494 		return (-1);
1495 
1496 	return (0);
1497 }
1498 
1499 int
1500 dt_print_mod(dtrace_hdl_t *dtp, FILE *fp, const char *format, caddr_t addr)
1501 {
1502 	/* LINTED - alignment */
1503 	uint64_t pc = *((uint64_t *)addr);
1504 	dtrace_syminfo_t dts;
1505 	char c[PATH_MAX * 2];
1506 
1507 	if (format == NULL)
1508 		format = "  %-50s";
1509 
1510 	if (dtrace_lookup_by_addr(dtp, pc, NULL, &dts) == 0) {
1511 		(void) snprintf(c, sizeof (c), "%s", dts.dts_object);
1512 	} else {
1513 		(void) snprintf(c, sizeof (c), "0x%llx", (u_longlong_t)pc);
1514 	}
1515 
1516 	if (dt_printf(dtp, fp, format, c) < 0)
1517 		return (-1);
1518 
1519 	return (0);
1520 }
1521 
1522 typedef struct dt_normal {
1523 	dtrace_aggvarid_t dtnd_id;
1524 	uint64_t dtnd_normal;
1525 } dt_normal_t;
1526 
1527 static int
1528 dt_normalize_agg(const dtrace_aggdata_t *aggdata, void *arg)
1529 {
1530 	dt_normal_t *normal = arg;
1531 	dtrace_aggdesc_t *agg = aggdata->dtada_desc;
1532 	dtrace_aggvarid_t id = normal->dtnd_id;
1533 
1534 	if (agg->dtagd_nrecs == 0)
1535 		return (DTRACE_AGGWALK_NEXT);
1536 
1537 	if (agg->dtagd_varid != id)
1538 		return (DTRACE_AGGWALK_NEXT);
1539 
1540 	((dtrace_aggdata_t *)aggdata)->dtada_normal = normal->dtnd_normal;
1541 	return (DTRACE_AGGWALK_NORMALIZE);
1542 }
1543 
1544 static int
1545 dt_normalize(dtrace_hdl_t *dtp, caddr_t base, dtrace_recdesc_t *rec)
1546 {
1547 	dt_normal_t normal;
1548 	caddr_t addr;
1549 
1550 	/*
1551 	 * We (should) have two records:  the aggregation ID followed by the
1552 	 * normalization value.
1553 	 */
1554 	addr = base + rec->dtrd_offset;
1555 
1556 	if (rec->dtrd_size != sizeof (dtrace_aggvarid_t))
1557 		return (dt_set_errno(dtp, EDT_BADNORMAL));
1558 
1559 	/* LINTED - alignment */
1560 	normal.dtnd_id = *((dtrace_aggvarid_t *)addr);
1561 	rec++;
1562 
1563 	if (rec->dtrd_action != DTRACEACT_LIBACT)
1564 		return (dt_set_errno(dtp, EDT_BADNORMAL));
1565 
1566 	if (rec->dtrd_arg != DT_ACT_NORMALIZE)
1567 		return (dt_set_errno(dtp, EDT_BADNORMAL));
1568 
1569 	addr = base + rec->dtrd_offset;
1570 
1571 	switch (rec->dtrd_size) {
1572 	case sizeof (uint64_t):
1573 		/* LINTED - alignment */
1574 		normal.dtnd_normal = *((uint64_t *)addr);
1575 		break;
1576 	case sizeof (uint32_t):
1577 		/* LINTED - alignment */
1578 		normal.dtnd_normal = *((uint32_t *)addr);
1579 		break;
1580 	case sizeof (uint16_t):
1581 		/* LINTED - alignment */
1582 		normal.dtnd_normal = *((uint16_t *)addr);
1583 		break;
1584 	case sizeof (uint8_t):
1585 		normal.dtnd_normal = *((uint8_t *)addr);
1586 		break;
1587 	default:
1588 		return (dt_set_errno(dtp, EDT_BADNORMAL));
1589 	}
1590 
1591 	(void) dtrace_aggregate_walk(dtp, dt_normalize_agg, &normal);
1592 
1593 	return (0);
1594 }
1595 
1596 static int
1597 dt_denormalize_agg(const dtrace_aggdata_t *aggdata, void *arg)
1598 {
1599 	dtrace_aggdesc_t *agg = aggdata->dtada_desc;
1600 	dtrace_aggvarid_t id = *((dtrace_aggvarid_t *)arg);
1601 
1602 	if (agg->dtagd_nrecs == 0)
1603 		return (DTRACE_AGGWALK_NEXT);
1604 
1605 	if (agg->dtagd_varid != id)
1606 		return (DTRACE_AGGWALK_NEXT);
1607 
1608 	return (DTRACE_AGGWALK_DENORMALIZE);
1609 }
1610 
1611 static int
1612 dt_clear_agg(const dtrace_aggdata_t *aggdata, void *arg)
1613 {
1614 	dtrace_aggdesc_t *agg = aggdata->dtada_desc;
1615 	dtrace_aggvarid_t id = *((dtrace_aggvarid_t *)arg);
1616 
1617 	if (agg->dtagd_nrecs == 0)
1618 		return (DTRACE_AGGWALK_NEXT);
1619 
1620 	if (agg->dtagd_varid != id)
1621 		return (DTRACE_AGGWALK_NEXT);
1622 
1623 	return (DTRACE_AGGWALK_CLEAR);
1624 }
1625 
1626 typedef struct dt_trunc {
1627 	dtrace_aggvarid_t dttd_id;
1628 	uint64_t dttd_remaining;
1629 } dt_trunc_t;
1630 
1631 static int
1632 dt_trunc_agg(const dtrace_aggdata_t *aggdata, void *arg)
1633 {
1634 	dt_trunc_t *trunc = arg;
1635 	dtrace_aggdesc_t *agg = aggdata->dtada_desc;
1636 	dtrace_aggvarid_t id = trunc->dttd_id;
1637 
1638 	if (agg->dtagd_nrecs == 0)
1639 		return (DTRACE_AGGWALK_NEXT);
1640 
1641 	if (agg->dtagd_varid != id)
1642 		return (DTRACE_AGGWALK_NEXT);
1643 
1644 	if (trunc->dttd_remaining == 0)
1645 		return (DTRACE_AGGWALK_REMOVE);
1646 
1647 	trunc->dttd_remaining--;
1648 	return (DTRACE_AGGWALK_NEXT);
1649 }
1650 
1651 static int
1652 dt_trunc(dtrace_hdl_t *dtp, caddr_t base, dtrace_recdesc_t *rec)
1653 {
1654 	dt_trunc_t trunc;
1655 	caddr_t addr;
1656 	int64_t remaining;
1657 	int (*func)(dtrace_hdl_t *, dtrace_aggregate_f *, void *);
1658 
1659 	/*
1660 	 * We (should) have two records:  the aggregation ID followed by the
1661 	 * number of aggregation entries after which the aggregation is to be
1662 	 * truncated.
1663 	 */
1664 	addr = base + rec->dtrd_offset;
1665 
1666 	if (rec->dtrd_size != sizeof (dtrace_aggvarid_t))
1667 		return (dt_set_errno(dtp, EDT_BADTRUNC));
1668 
1669 	/* LINTED - alignment */
1670 	trunc.dttd_id = *((dtrace_aggvarid_t *)addr);
1671 	rec++;
1672 
1673 	if (rec->dtrd_action != DTRACEACT_LIBACT)
1674 		return (dt_set_errno(dtp, EDT_BADTRUNC));
1675 
1676 	if (rec->dtrd_arg != DT_ACT_TRUNC)
1677 		return (dt_set_errno(dtp, EDT_BADTRUNC));
1678 
1679 	addr = base + rec->dtrd_offset;
1680 
1681 	switch (rec->dtrd_size) {
1682 	case sizeof (uint64_t):
1683 		/* LINTED - alignment */
1684 		remaining = *((int64_t *)addr);
1685 		break;
1686 	case sizeof (uint32_t):
1687 		/* LINTED - alignment */
1688 		remaining = *((int32_t *)addr);
1689 		break;
1690 	case sizeof (uint16_t):
1691 		/* LINTED - alignment */
1692 		remaining = *((int16_t *)addr);
1693 		break;
1694 	case sizeof (uint8_t):
1695 		remaining = *((int8_t *)addr);
1696 		break;
1697 	default:
1698 		return (dt_set_errno(dtp, EDT_BADNORMAL));
1699 	}
1700 
1701 	if (remaining < 0) {
1702 		func = dtrace_aggregate_walk_valsorted;
1703 		remaining = -remaining;
1704 	} else {
1705 		func = dtrace_aggregate_walk_valrevsorted;
1706 	}
1707 
1708 	assert(remaining >= 0);
1709 	trunc.dttd_remaining = remaining;
1710 
1711 	(void) func(dtp, dt_trunc_agg, &trunc);
1712 
1713 	return (0);
1714 }
1715 
1716 static int
1717 dt_print_datum(dtrace_hdl_t *dtp, FILE *fp, dtrace_recdesc_t *rec,
1718     caddr_t addr, size_t size, uint64_t normal)
1719 {
1720 	int err;
1721 	dtrace_actkind_t act = rec->dtrd_action;
1722 
1723 	switch (act) {
1724 	case DTRACEACT_STACK:
1725 		return (dt_print_stack(dtp, fp, NULL, addr,
1726 		    rec->dtrd_arg, rec->dtrd_size / rec->dtrd_arg));
1727 
1728 	case DTRACEACT_USTACK:
1729 	case DTRACEACT_JSTACK:
1730 		return (dt_print_ustack(dtp, fp, NULL, addr, rec->dtrd_arg));
1731 
1732 	case DTRACEACT_USYM:
1733 	case DTRACEACT_UADDR:
1734 		return (dt_print_usym(dtp, fp, addr, act));
1735 
1736 	case DTRACEACT_UMOD:
1737 		return (dt_print_umod(dtp, fp, NULL, addr));
1738 
1739 	case DTRACEACT_SYM:
1740 		return (dt_print_sym(dtp, fp, NULL, addr));
1741 
1742 	case DTRACEACT_MOD:
1743 		return (dt_print_mod(dtp, fp, NULL, addr));
1744 
1745 	case DTRACEAGG_QUANTIZE:
1746 		return (dt_print_quantize(dtp, fp, addr, size, normal));
1747 
1748 	case DTRACEAGG_LQUANTIZE:
1749 		return (dt_print_lquantize(dtp, fp, addr, size, normal));
1750 
1751 	case DTRACEAGG_AVG:
1752 		return (dt_print_average(dtp, fp, addr, size, normal));
1753 
1754 	case DTRACEAGG_STDDEV:
1755 		return (dt_print_stddev(dtp, fp, addr, size, normal));
1756 
1757 	default:
1758 		break;
1759 	}
1760 
1761 	switch (size) {
1762 	case sizeof (uint64_t):
1763 		err = dt_printf(dtp, fp, " %16lld",
1764 		    /* LINTED - alignment */
1765 		    (long long)*((uint64_t *)addr) / normal);
1766 		break;
1767 	case sizeof (uint32_t):
1768 		/* LINTED - alignment */
1769 		err = dt_printf(dtp, fp, " %8d", *((uint32_t *)addr) /
1770 		    (uint32_t)normal);
1771 		break;
1772 	case sizeof (uint16_t):
1773 		/* LINTED - alignment */
1774 		err = dt_printf(dtp, fp, " %5d", *((uint16_t *)addr) /
1775 		    (uint32_t)normal);
1776 		break;
1777 	case sizeof (uint8_t):
1778 		err = dt_printf(dtp, fp, " %3d", *((uint8_t *)addr) /
1779 		    (uint32_t)normal);
1780 		break;
1781 	default:
1782 		err = dt_print_bytes(dtp, fp, addr, size, 50, 0, 0);
1783 		break;
1784 	}
1785 
1786 	return (err);
1787 }
1788 
1789 int
1790 dt_print_aggs(const dtrace_aggdata_t **aggsdata, int naggvars, void *arg)
1791 {
1792 	int i, aggact = 0;
1793 	dt_print_aggdata_t *pd = arg;
1794 	const dtrace_aggdata_t *aggdata = aggsdata[0];
1795 	dtrace_aggdesc_t *agg = aggdata->dtada_desc;
1796 	FILE *fp = pd->dtpa_fp;
1797 	dtrace_hdl_t *dtp = pd->dtpa_dtp;
1798 	dtrace_recdesc_t *rec;
1799 	dtrace_actkind_t act;
1800 	caddr_t addr;
1801 	size_t size;
1802 
1803 	/*
1804 	 * Iterate over each record description in the key, printing the traced
1805 	 * data, skipping the first datum (the tuple member created by the
1806 	 * compiler).
1807 	 */
1808 	for (i = 1; i < agg->dtagd_nrecs; i++) {
1809 		rec = &agg->dtagd_rec[i];
1810 		act = rec->dtrd_action;
1811 		addr = aggdata->dtada_data + rec->dtrd_offset;
1812 		size = rec->dtrd_size;
1813 
1814 		if (DTRACEACT_ISAGG(act)) {
1815 			aggact = i;
1816 			break;
1817 		}
1818 
1819 		if (dt_print_datum(dtp, fp, rec, addr, size, 1) < 0)
1820 			return (-1);
1821 
1822 		if (dt_buffered_flush(dtp, NULL, rec, aggdata,
1823 		    DTRACE_BUFDATA_AGGKEY) < 0)
1824 			return (-1);
1825 	}
1826 
1827 	assert(aggact != 0);
1828 
1829 	for (i = (naggvars == 1 ? 0 : 1); i < naggvars; i++) {
1830 		uint64_t normal;
1831 
1832 		aggdata = aggsdata[i];
1833 		agg = aggdata->dtada_desc;
1834 		rec = &agg->dtagd_rec[aggact];
1835 		act = rec->dtrd_action;
1836 		addr = aggdata->dtada_data + rec->dtrd_offset;
1837 		size = rec->dtrd_size;
1838 
1839 		assert(DTRACEACT_ISAGG(act));
1840 		normal = aggdata->dtada_normal;
1841 
1842 		if (dt_print_datum(dtp, fp, rec, addr, size, normal) < 0)
1843 			return (-1);
1844 
1845 		if (dt_buffered_flush(dtp, NULL, rec, aggdata,
1846 		    DTRACE_BUFDATA_AGGVAL) < 0)
1847 			return (-1);
1848 
1849 		if (!pd->dtpa_allunprint)
1850 			agg->dtagd_flags |= DTRACE_AGD_PRINTED;
1851 	}
1852 
1853 	if (dt_printf(dtp, fp, "\n") < 0)
1854 		return (-1);
1855 
1856 	if (dt_buffered_flush(dtp, NULL, NULL, aggdata,
1857 	    DTRACE_BUFDATA_AGGFORMAT | DTRACE_BUFDATA_AGGLAST) < 0)
1858 		return (-1);
1859 
1860 	return (0);
1861 }
1862 
1863 int
1864 dt_print_agg(const dtrace_aggdata_t *aggdata, void *arg)
1865 {
1866 	dt_print_aggdata_t *pd = arg;
1867 	dtrace_aggdesc_t *agg = aggdata->dtada_desc;
1868 	dtrace_aggvarid_t aggvarid = pd->dtpa_id;
1869 
1870 	if (pd->dtpa_allunprint) {
1871 		if (agg->dtagd_flags & DTRACE_AGD_PRINTED)
1872 			return (0);
1873 	} else {
1874 		/*
1875 		 * If we're not printing all unprinted aggregations, then the
1876 		 * aggregation variable ID denotes a specific aggregation
1877 		 * variable that we should print -- skip any other aggregations
1878 		 * that we encounter.
1879 		 */
1880 		if (agg->dtagd_nrecs == 0)
1881 			return (0);
1882 
1883 		if (aggvarid != agg->dtagd_varid)
1884 			return (0);
1885 	}
1886 
1887 	return (dt_print_aggs(&aggdata, 1, arg));
1888 }
1889 
1890 int
1891 dt_setopt(dtrace_hdl_t *dtp, const dtrace_probedata_t *data,
1892     const char *option, const char *value)
1893 {
1894 	int len, rval;
1895 	char *msg;
1896 	const char *errstr;
1897 	dtrace_setoptdata_t optdata;
1898 
1899 	bzero(&optdata, sizeof (optdata));
1900 	(void) dtrace_getopt(dtp, option, &optdata.dtsda_oldval);
1901 
1902 	if (dtrace_setopt(dtp, option, value) == 0) {
1903 		(void) dtrace_getopt(dtp, option, &optdata.dtsda_newval);
1904 		optdata.dtsda_probe = data;
1905 		optdata.dtsda_option = option;
1906 		optdata.dtsda_handle = dtp;
1907 
1908 		if ((rval = dt_handle_setopt(dtp, &optdata)) != 0)
1909 			return (rval);
1910 
1911 		return (0);
1912 	}
1913 
1914 	errstr = dtrace_errmsg(dtp, dtrace_errno(dtp));
1915 	len = strlen(option) + strlen(value) + strlen(errstr) + 80;
1916 	msg = alloca(len);
1917 
1918 	(void) snprintf(msg, len, "couldn't set option \"%s\" to \"%s\": %s\n",
1919 	    option, value, errstr);
1920 
1921 	if ((rval = dt_handle_liberr(dtp, data, msg)) == 0)
1922 		return (0);
1923 
1924 	return (rval);
1925 }
1926 
1927 static int
1928 dt_consume_cpu(dtrace_hdl_t *dtp, FILE *fp, int cpu, dtrace_bufdesc_t *buf,
1929     dtrace_consume_probe_f *efunc, dtrace_consume_rec_f *rfunc, void *arg)
1930 {
1931 	dtrace_epid_t id;
1932 	size_t offs, start = buf->dtbd_oldest, end = buf->dtbd_size;
1933 	int flow = (dtp->dt_options[DTRACEOPT_FLOWINDENT] != DTRACEOPT_UNSET);
1934 	int quiet = (dtp->dt_options[DTRACEOPT_QUIET] != DTRACEOPT_UNSET);
1935 	int rval, i, n;
1936 	dtrace_epid_t last = DTRACE_EPIDNONE;
1937 	dtrace_probedata_t data;
1938 	uint64_t drops;
1939 	caddr_t addr;
1940 
1941 	bzero(&data, sizeof (data));
1942 	data.dtpda_handle = dtp;
1943 	data.dtpda_cpu = cpu;
1944 
1945 again:
1946 	for (offs = start; offs < end; ) {
1947 		dtrace_eprobedesc_t *epd;
1948 
1949 		/*
1950 		 * We're guaranteed to have an ID.
1951 		 */
1952 		id = *(uint32_t *)((uintptr_t)buf->dtbd_data + offs);
1953 
1954 		if (id == DTRACE_EPIDNONE) {
1955 			/*
1956 			 * This is filler to assure proper alignment of the
1957 			 * next record; we simply ignore it.
1958 			 */
1959 			offs += sizeof (id);
1960 			continue;
1961 		}
1962 
1963 		if ((rval = dt_epid_lookup(dtp, id, &data.dtpda_edesc,
1964 		    &data.dtpda_pdesc)) != 0)
1965 			return (rval);
1966 
1967 		epd = data.dtpda_edesc;
1968 		data.dtpda_data = buf->dtbd_data + offs;
1969 
1970 		if (data.dtpda_edesc->dtepd_uarg != DT_ECB_DEFAULT) {
1971 			rval = dt_handle(dtp, &data);
1972 
1973 			if (rval == DTRACE_CONSUME_NEXT)
1974 				goto nextepid;
1975 
1976 			if (rval == DTRACE_CONSUME_ERROR)
1977 				return (-1);
1978 		}
1979 
1980 		if (flow)
1981 			(void) dt_flowindent(dtp, &data, last, buf, offs);
1982 
1983 		rval = (*efunc)(&data, arg);
1984 
1985 		if (flow) {
1986 			if (data.dtpda_flow == DTRACEFLOW_ENTRY)
1987 				data.dtpda_indent += 2;
1988 		}
1989 
1990 		if (rval == DTRACE_CONSUME_NEXT)
1991 			goto nextepid;
1992 
1993 		if (rval == DTRACE_CONSUME_ABORT)
1994 			return (dt_set_errno(dtp, EDT_DIRABORT));
1995 
1996 		if (rval != DTRACE_CONSUME_THIS)
1997 			return (dt_set_errno(dtp, EDT_BADRVAL));
1998 
1999 		for (i = 0; i < epd->dtepd_nrecs; i++) {
2000 			dtrace_recdesc_t *rec = &epd->dtepd_rec[i];
2001 			dtrace_actkind_t act = rec->dtrd_action;
2002 
2003 			data.dtpda_data = buf->dtbd_data + offs +
2004 			    rec->dtrd_offset;
2005 			addr = data.dtpda_data;
2006 
2007 			if (act == DTRACEACT_LIBACT) {
2008 				uint64_t arg = rec->dtrd_arg;
2009 				dtrace_aggvarid_t id;
2010 
2011 				switch (arg) {
2012 				case DT_ACT_CLEAR:
2013 					/* LINTED - alignment */
2014 					id = *((dtrace_aggvarid_t *)addr);
2015 					(void) dtrace_aggregate_walk(dtp,
2016 					    dt_clear_agg, &id);
2017 					continue;
2018 
2019 				case DT_ACT_DENORMALIZE:
2020 					/* LINTED - alignment */
2021 					id = *((dtrace_aggvarid_t *)addr);
2022 					(void) dtrace_aggregate_walk(dtp,
2023 					    dt_denormalize_agg, &id);
2024 					continue;
2025 
2026 				case DT_ACT_FTRUNCATE:
2027 					if (fp == NULL)
2028 						continue;
2029 
2030 					(void) fflush(fp);
2031 					(void) ftruncate(fileno(fp), 0);
2032 					(void) fseeko(fp, 0, SEEK_SET);
2033 					continue;
2034 
2035 				case DT_ACT_NORMALIZE:
2036 					if (i == epd->dtepd_nrecs - 1)
2037 						return (dt_set_errno(dtp,
2038 						    EDT_BADNORMAL));
2039 
2040 					if (dt_normalize(dtp,
2041 					    buf->dtbd_data + offs, rec) != 0)
2042 						return (-1);
2043 
2044 					i++;
2045 					continue;
2046 
2047 				case DT_ACT_SETOPT: {
2048 					uint64_t *opts = dtp->dt_options;
2049 					dtrace_recdesc_t *valrec;
2050 					uint32_t valsize;
2051 					caddr_t val;
2052 					int rv;
2053 
2054 					if (i == epd->dtepd_nrecs - 1) {
2055 						return (dt_set_errno(dtp,
2056 						    EDT_BADSETOPT));
2057 					}
2058 
2059 					valrec = &epd->dtepd_rec[++i];
2060 					valsize = valrec->dtrd_size;
2061 
2062 					if (valrec->dtrd_action != act ||
2063 					    valrec->dtrd_arg != arg) {
2064 						return (dt_set_errno(dtp,
2065 						    EDT_BADSETOPT));
2066 					}
2067 
2068 					if (valsize > sizeof (uint64_t)) {
2069 						val = buf->dtbd_data + offs +
2070 						    valrec->dtrd_offset;
2071 					} else {
2072 						val = "1";
2073 					}
2074 
2075 					rv = dt_setopt(dtp, &data, addr, val);
2076 
2077 					if (rv != 0)
2078 						return (-1);
2079 
2080 					flow = (opts[DTRACEOPT_FLOWINDENT] !=
2081 					    DTRACEOPT_UNSET);
2082 					quiet = (opts[DTRACEOPT_QUIET] !=
2083 					    DTRACEOPT_UNSET);
2084 
2085 					continue;
2086 				}
2087 
2088 				case DT_ACT_TRUNC:
2089 					if (i == epd->dtepd_nrecs - 1)
2090 						return (dt_set_errno(dtp,
2091 						    EDT_BADTRUNC));
2092 
2093 					if (dt_trunc(dtp,
2094 					    buf->dtbd_data + offs, rec) != 0)
2095 						return (-1);
2096 
2097 					i++;
2098 					continue;
2099 
2100 				default:
2101 					continue;
2102 				}
2103 			}
2104 
2105 			rval = (*rfunc)(&data, rec, arg);
2106 
2107 			if (rval == DTRACE_CONSUME_NEXT)
2108 				continue;
2109 
2110 			if (rval == DTRACE_CONSUME_ABORT)
2111 				return (dt_set_errno(dtp, EDT_DIRABORT));
2112 
2113 			if (rval != DTRACE_CONSUME_THIS)
2114 				return (dt_set_errno(dtp, EDT_BADRVAL));
2115 
2116 			if (act == DTRACEACT_STACK) {
2117 				int depth = rec->dtrd_arg;
2118 
2119 				if (dt_print_stack(dtp, fp, NULL, addr, depth,
2120 				    rec->dtrd_size / depth) < 0)
2121 					return (-1);
2122 				goto nextrec;
2123 			}
2124 
2125 			if (act == DTRACEACT_USTACK ||
2126 			    act == DTRACEACT_JSTACK) {
2127 				if (dt_print_ustack(dtp, fp, NULL,
2128 				    addr, rec->dtrd_arg) < 0)
2129 					return (-1);
2130 				goto nextrec;
2131 			}
2132 
2133 			if (act == DTRACEACT_SYM) {
2134 				if (dt_print_sym(dtp, fp, NULL, addr) < 0)
2135 					return (-1);
2136 				goto nextrec;
2137 			}
2138 
2139 			if (act == DTRACEACT_MOD) {
2140 				if (dt_print_mod(dtp, fp, NULL, addr) < 0)
2141 					return (-1);
2142 				goto nextrec;
2143 			}
2144 
2145 			if (act == DTRACEACT_USYM || act == DTRACEACT_UADDR) {
2146 				if (dt_print_usym(dtp, fp, addr, act) < 0)
2147 					return (-1);
2148 				goto nextrec;
2149 			}
2150 
2151 			if (act == DTRACEACT_UMOD) {
2152 				if (dt_print_umod(dtp, fp, NULL, addr) < 0)
2153 					return (-1);
2154 				goto nextrec;
2155 			}
2156 
2157 			if (act == DTRACEACT_PRINTM) {
2158 				if (dt_print_memory(dtp, fp, addr) < 0)
2159 					return (-1);
2160 				goto nextrec;
2161 			}
2162 
2163 			if (act == DTRACEACT_PRINTT) {
2164 				if (dt_print_type(dtp, fp, addr) < 0)
2165 					return (-1);
2166 				goto nextrec;
2167 			}
2168 
2169 			if (DTRACEACT_ISPRINTFLIKE(act)) {
2170 				void *fmtdata;
2171 				int (*func)(dtrace_hdl_t *, FILE *, void *,
2172 				    const dtrace_probedata_t *,
2173 				    const dtrace_recdesc_t *, uint_t,
2174 				    const void *buf, size_t);
2175 
2176 				if ((fmtdata = dt_format_lookup(dtp,
2177 				    rec->dtrd_format)) == NULL)
2178 					goto nofmt;
2179 
2180 				switch (act) {
2181 				case DTRACEACT_PRINTF:
2182 					func = dtrace_fprintf;
2183 					break;
2184 				case DTRACEACT_PRINTA:
2185 					func = dtrace_fprinta;
2186 					break;
2187 				case DTRACEACT_SYSTEM:
2188 					func = dtrace_system;
2189 					break;
2190 				case DTRACEACT_FREOPEN:
2191 					func = dtrace_freopen;
2192 					break;
2193 				}
2194 
2195 				n = (*func)(dtp, fp, fmtdata, &data,
2196 				    rec, epd->dtepd_nrecs - i,
2197 				    (uchar_t *)buf->dtbd_data + offs,
2198 				    buf->dtbd_size - offs);
2199 
2200 				if (n < 0)
2201 					return (-1); /* errno is set for us */
2202 
2203 				if (n > 0)
2204 					i += n - 1;
2205 				goto nextrec;
2206 			}
2207 
2208 nofmt:
2209 			if (act == DTRACEACT_PRINTA) {
2210 				dt_print_aggdata_t pd;
2211 				dtrace_aggvarid_t *aggvars;
2212 				int j, naggvars = 0;
2213 				size_t size = ((epd->dtepd_nrecs - i) *
2214 				    sizeof (dtrace_aggvarid_t));
2215 
2216 				if ((aggvars = dt_alloc(dtp, size)) == NULL)
2217 					return (-1);
2218 
2219 				/*
2220 				 * This might be a printa() with multiple
2221 				 * aggregation variables.  We need to scan
2222 				 * forward through the records until we find
2223 				 * a record from a different statement.
2224 				 */
2225 				for (j = i; j < epd->dtepd_nrecs; j++) {
2226 					dtrace_recdesc_t *nrec;
2227 					caddr_t naddr;
2228 
2229 					nrec = &epd->dtepd_rec[j];
2230 
2231 					if (nrec->dtrd_uarg != rec->dtrd_uarg)
2232 						break;
2233 
2234 					if (nrec->dtrd_action != act) {
2235 						return (dt_set_errno(dtp,
2236 						    EDT_BADAGG));
2237 					}
2238 
2239 					naddr = buf->dtbd_data + offs +
2240 					    nrec->dtrd_offset;
2241 
2242 					aggvars[naggvars++] =
2243 					    /* LINTED - alignment */
2244 					    *((dtrace_aggvarid_t *)naddr);
2245 				}
2246 
2247 				i = j - 1;
2248 				bzero(&pd, sizeof (pd));
2249 				pd.dtpa_dtp = dtp;
2250 				pd.dtpa_fp = fp;
2251 
2252 				assert(naggvars >= 1);
2253 
2254 				if (naggvars == 1) {
2255 					pd.dtpa_id = aggvars[0];
2256 					dt_free(dtp, aggvars);
2257 
2258 					if (dt_printf(dtp, fp, "\n") < 0 ||
2259 					    dtrace_aggregate_walk_sorted(dtp,
2260 					    dt_print_agg, &pd) < 0)
2261 						return (-1);
2262 					goto nextrec;
2263 				}
2264 
2265 				if (dt_printf(dtp, fp, "\n") < 0 ||
2266 				    dtrace_aggregate_walk_joined(dtp, aggvars,
2267 				    naggvars, dt_print_aggs, &pd) < 0) {
2268 					dt_free(dtp, aggvars);
2269 					return (-1);
2270 				}
2271 
2272 				dt_free(dtp, aggvars);
2273 				goto nextrec;
2274 			}
2275 
2276 			switch (rec->dtrd_size) {
2277 			case sizeof (uint64_t):
2278 				n = dt_printf(dtp, fp,
2279 				    quiet ? "%lld" : " %16lld",
2280 				    /* LINTED - alignment */
2281 				    *((unsigned long long *)addr));
2282 				break;
2283 			case sizeof (uint32_t):
2284 				n = dt_printf(dtp, fp, quiet ? "%d" : " %8d",
2285 				    /* LINTED - alignment */
2286 				    *((uint32_t *)addr));
2287 				break;
2288 			case sizeof (uint16_t):
2289 				n = dt_printf(dtp, fp, quiet ? "%d" : " %5d",
2290 				    /* LINTED - alignment */
2291 				    *((uint16_t *)addr));
2292 				break;
2293 			case sizeof (uint8_t):
2294 				n = dt_printf(dtp, fp, quiet ? "%d" : " %3d",
2295 				    *((uint8_t *)addr));
2296 				break;
2297 			default:
2298 				n = dt_print_bytes(dtp, fp, addr,
2299 				    rec->dtrd_size, 33, quiet, 0);
2300 				break;
2301 			}
2302 
2303 			if (n < 0)
2304 				return (-1); /* errno is set for us */
2305 
2306 nextrec:
2307 			if (dt_buffered_flush(dtp, &data, rec, NULL, 0) < 0)
2308 				return (-1); /* errno is set for us */
2309 		}
2310 
2311 		/*
2312 		 * Call the record callback with a NULL record to indicate
2313 		 * that we're done processing this EPID.
2314 		 */
2315 		rval = (*rfunc)(&data, NULL, arg);
2316 nextepid:
2317 		offs += epd->dtepd_size;
2318 		last = id;
2319 	}
2320 
2321 	if (buf->dtbd_oldest != 0 && start == buf->dtbd_oldest) {
2322 		end = buf->dtbd_oldest;
2323 		start = 0;
2324 		goto again;
2325 	}
2326 
2327 	if ((drops = buf->dtbd_drops) == 0)
2328 		return (0);
2329 
2330 	/*
2331 	 * Explicitly zero the drops to prevent us from processing them again.
2332 	 */
2333 	buf->dtbd_drops = 0;
2334 
2335 	return (dt_handle_cpudrop(dtp, cpu, DTRACEDROP_PRINCIPAL, drops));
2336 }
2337 
2338 typedef struct dt_begin {
2339 	dtrace_consume_probe_f *dtbgn_probefunc;
2340 	dtrace_consume_rec_f *dtbgn_recfunc;
2341 	void *dtbgn_arg;
2342 	dtrace_handle_err_f *dtbgn_errhdlr;
2343 	void *dtbgn_errarg;
2344 	int dtbgn_beginonly;
2345 } dt_begin_t;
2346 
2347 static int
2348 dt_consume_begin_probe(const dtrace_probedata_t *data, void *arg)
2349 {
2350 	dt_begin_t *begin = (dt_begin_t *)arg;
2351 	dtrace_probedesc_t *pd = data->dtpda_pdesc;
2352 
2353 	int r1 = (strcmp(pd->dtpd_provider, "dtrace") == 0);
2354 	int r2 = (strcmp(pd->dtpd_name, "BEGIN") == 0);
2355 
2356 	if (begin->dtbgn_beginonly) {
2357 		if (!(r1 && r2))
2358 			return (DTRACE_CONSUME_NEXT);
2359 	} else {
2360 		if (r1 && r2)
2361 			return (DTRACE_CONSUME_NEXT);
2362 	}
2363 
2364 	/*
2365 	 * We have a record that we're interested in.  Now call the underlying
2366 	 * probe function...
2367 	 */
2368 	return (begin->dtbgn_probefunc(data, begin->dtbgn_arg));
2369 }
2370 
2371 static int
2372 dt_consume_begin_record(const dtrace_probedata_t *data,
2373     const dtrace_recdesc_t *rec, void *arg)
2374 {
2375 	dt_begin_t *begin = (dt_begin_t *)arg;
2376 
2377 	return (begin->dtbgn_recfunc(data, rec, begin->dtbgn_arg));
2378 }
2379 
2380 static int
2381 dt_consume_begin_error(const dtrace_errdata_t *data, void *arg)
2382 {
2383 	dt_begin_t *begin = (dt_begin_t *)arg;
2384 	dtrace_probedesc_t *pd = data->dteda_pdesc;
2385 
2386 	int r1 = (strcmp(pd->dtpd_provider, "dtrace") == 0);
2387 	int r2 = (strcmp(pd->dtpd_name, "BEGIN") == 0);
2388 
2389 	if (begin->dtbgn_beginonly) {
2390 		if (!(r1 && r2))
2391 			return (DTRACE_HANDLE_OK);
2392 	} else {
2393 		if (r1 && r2)
2394 			return (DTRACE_HANDLE_OK);
2395 	}
2396 
2397 	return (begin->dtbgn_errhdlr(data, begin->dtbgn_errarg));
2398 }
2399 
2400 static int
2401 dt_consume_begin(dtrace_hdl_t *dtp, FILE *fp, dtrace_bufdesc_t *buf,
2402     dtrace_consume_probe_f *pf, dtrace_consume_rec_f *rf, void *arg)
2403 {
2404 	/*
2405 	 * There's this idea that the BEGIN probe should be processed before
2406 	 * everything else, and that the END probe should be processed after
2407 	 * anything else.  In the common case, this is pretty easy to deal
2408 	 * with.  However, a situation may arise where the BEGIN enabling and
2409 	 * END enabling are on the same CPU, and some enabling in the middle
2410 	 * occurred on a different CPU.  To deal with this (blech!) we need to
2411 	 * consume the BEGIN buffer up until the end of the BEGIN probe, and
2412 	 * then set it aside.  We will then process every other CPU, and then
2413 	 * we'll return to the BEGIN CPU and process the rest of the data
2414 	 * (which will inevitably include the END probe, if any).  Making this
2415 	 * even more complicated (!) is the library's ERROR enabling.  Because
2416 	 * this enabling is processed before we even get into the consume call
2417 	 * back, any ERROR firing would result in the library's ERROR enabling
2418 	 * being processed twice -- once in our first pass (for BEGIN probes),
2419 	 * and again in our second pass (for everything but BEGIN probes).  To
2420 	 * deal with this, we interpose on the ERROR handler to assure that we
2421 	 * only process ERROR enablings induced by BEGIN enablings in the
2422 	 * first pass, and that we only process ERROR enablings _not_ induced
2423 	 * by BEGIN enablings in the second pass.
2424 	 */
2425 	dt_begin_t begin;
2426 	processorid_t cpu = dtp->dt_beganon;
2427 	dtrace_bufdesc_t nbuf;
2428 #if !defined(sun)
2429 	dtrace_bufdesc_t *pbuf;
2430 #endif
2431 	int rval, i;
2432 	static int max_ncpus;
2433 	dtrace_optval_t size;
2434 
2435 	dtp->dt_beganon = -1;
2436 
2437 #if defined(sun)
2438 	if (dt_ioctl(dtp, DTRACEIOC_BUFSNAP, buf) == -1) {
2439 #else
2440 	if (dt_ioctl(dtp, DTRACEIOC_BUFSNAP, &buf) == -1) {
2441 #endif
2442 		/*
2443 		 * We really don't expect this to fail, but it is at least
2444 		 * technically possible for this to fail with ENOENT.  In this
2445 		 * case, we just drive on...
2446 		 */
2447 		if (errno == ENOENT)
2448 			return (0);
2449 
2450 		return (dt_set_errno(dtp, errno));
2451 	}
2452 
2453 	if (!dtp->dt_stopped || buf->dtbd_cpu != dtp->dt_endedon) {
2454 		/*
2455 		 * This is the simple case.  We're either not stopped, or if
2456 		 * we are, we actually processed any END probes on another
2457 		 * CPU.  We can simply consume this buffer and return.
2458 		 */
2459 		return (dt_consume_cpu(dtp, fp, cpu, buf, pf, rf, arg));
2460 	}
2461 
2462 	begin.dtbgn_probefunc = pf;
2463 	begin.dtbgn_recfunc = rf;
2464 	begin.dtbgn_arg = arg;
2465 	begin.dtbgn_beginonly = 1;
2466 
2467 	/*
2468 	 * We need to interpose on the ERROR handler to be sure that we
2469 	 * only process ERRORs induced by BEGIN.
2470 	 */
2471 	begin.dtbgn_errhdlr = dtp->dt_errhdlr;
2472 	begin.dtbgn_errarg = dtp->dt_errarg;
2473 	dtp->dt_errhdlr = dt_consume_begin_error;
2474 	dtp->dt_errarg = &begin;
2475 
2476 	rval = dt_consume_cpu(dtp, fp, cpu, buf, dt_consume_begin_probe,
2477 	    dt_consume_begin_record, &begin);
2478 
2479 	dtp->dt_errhdlr = begin.dtbgn_errhdlr;
2480 	dtp->dt_errarg = begin.dtbgn_errarg;
2481 
2482 	if (rval != 0)
2483 		return (rval);
2484 
2485 	/*
2486 	 * Now allocate a new buffer.  We'll use this to deal with every other
2487 	 * CPU.
2488 	 */
2489 	bzero(&nbuf, sizeof (dtrace_bufdesc_t));
2490 	(void) dtrace_getopt(dtp, "bufsize", &size);
2491 	if ((nbuf.dtbd_data = malloc(size)) == NULL)
2492 		return (dt_set_errno(dtp, EDT_NOMEM));
2493 
2494 	if (max_ncpus == 0)
2495 		max_ncpus = dt_sysconf(dtp, _SC_CPUID_MAX) + 1;
2496 
2497 	for (i = 0; i < max_ncpus; i++) {
2498 		nbuf.dtbd_cpu = i;
2499 
2500 		if (i == cpu)
2501 			continue;
2502 
2503 #if defined(sun)
2504 		if (dt_ioctl(dtp, DTRACEIOC_BUFSNAP, &nbuf) == -1) {
2505 #else
2506 		pbuf = &nbuf;
2507 		if (dt_ioctl(dtp, DTRACEIOC_BUFSNAP, &pbuf) == -1) {
2508 #endif
2509 			/*
2510 			 * If we failed with ENOENT, it may be because the
2511 			 * CPU was unconfigured -- this is okay.  Any other
2512 			 * error, however, is unexpected.
2513 			 */
2514 			if (errno == ENOENT)
2515 				continue;
2516 
2517 			free(nbuf.dtbd_data);
2518 
2519 			return (dt_set_errno(dtp, errno));
2520 		}
2521 
2522 		if ((rval = dt_consume_cpu(dtp, fp,
2523 		    i, &nbuf, pf, rf, arg)) != 0) {
2524 			free(nbuf.dtbd_data);
2525 			return (rval);
2526 		}
2527 	}
2528 
2529 	free(nbuf.dtbd_data);
2530 
2531 	/*
2532 	 * Okay -- we're done with the other buffers.  Now we want to
2533 	 * reconsume the first buffer -- but this time we're looking for
2534 	 * everything _but_ BEGIN.  And of course, in order to only consume
2535 	 * those ERRORs _not_ associated with BEGIN, we need to reinstall our
2536 	 * ERROR interposition function...
2537 	 */
2538 	begin.dtbgn_beginonly = 0;
2539 
2540 	assert(begin.dtbgn_errhdlr == dtp->dt_errhdlr);
2541 	assert(begin.dtbgn_errarg == dtp->dt_errarg);
2542 	dtp->dt_errhdlr = dt_consume_begin_error;
2543 	dtp->dt_errarg = &begin;
2544 
2545 	rval = dt_consume_cpu(dtp, fp, cpu, buf, dt_consume_begin_probe,
2546 	    dt_consume_begin_record, &begin);
2547 
2548 	dtp->dt_errhdlr = begin.dtbgn_errhdlr;
2549 	dtp->dt_errarg = begin.dtbgn_errarg;
2550 
2551 	return (rval);
2552 }
2553 
2554 int
2555 dtrace_consume(dtrace_hdl_t *dtp, FILE *fp,
2556     dtrace_consume_probe_f *pf, dtrace_consume_rec_f *rf, void *arg)
2557 {
2558 	dtrace_bufdesc_t *buf = &dtp->dt_buf;
2559 	dtrace_optval_t size;
2560 	static int max_ncpus;
2561 	int i, rval;
2562 	dtrace_optval_t interval = dtp->dt_options[DTRACEOPT_SWITCHRATE];
2563 	hrtime_t now = gethrtime();
2564 
2565 	if (dtp->dt_lastswitch != 0) {
2566 		if (now - dtp->dt_lastswitch < interval)
2567 			return (0);
2568 
2569 		dtp->dt_lastswitch += interval;
2570 	} else {
2571 		dtp->dt_lastswitch = now;
2572 	}
2573 
2574 	if (!dtp->dt_active)
2575 		return (dt_set_errno(dtp, EINVAL));
2576 
2577 	if (max_ncpus == 0)
2578 		max_ncpus = dt_sysconf(dtp, _SC_CPUID_MAX) + 1;
2579 
2580 	if (pf == NULL)
2581 		pf = (dtrace_consume_probe_f *)dt_nullprobe;
2582 
2583 	if (rf == NULL)
2584 		rf = (dtrace_consume_rec_f *)dt_nullrec;
2585 
2586 	if (buf->dtbd_data == NULL) {
2587 		(void) dtrace_getopt(dtp, "bufsize", &size);
2588 		if ((buf->dtbd_data = malloc(size)) == NULL)
2589 			return (dt_set_errno(dtp, EDT_NOMEM));
2590 
2591 		buf->dtbd_size = size;
2592 	}
2593 
2594 	/*
2595 	 * If we have just begun, we want to first process the CPU that
2596 	 * executed the BEGIN probe (if any).
2597 	 */
2598 	if (dtp->dt_active && dtp->dt_beganon != -1) {
2599 		buf->dtbd_cpu = dtp->dt_beganon;
2600 		if ((rval = dt_consume_begin(dtp, fp, buf, pf, rf, arg)) != 0)
2601 			return (rval);
2602 	}
2603 
2604 	for (i = 0; i < max_ncpus; i++) {
2605 		buf->dtbd_cpu = i;
2606 
2607 		/*
2608 		 * If we have stopped, we want to process the CPU on which the
2609 		 * END probe was processed only _after_ we have processed
2610 		 * everything else.
2611 		 */
2612 		if (dtp->dt_stopped && (i == dtp->dt_endedon))
2613 			continue;
2614 
2615 #if defined(sun)
2616 		if (dt_ioctl(dtp, DTRACEIOC_BUFSNAP, buf) == -1) {
2617 #else
2618 		if (dt_ioctl(dtp, DTRACEIOC_BUFSNAP, &buf) == -1) {
2619 #endif
2620 			/*
2621 			 * If we failed with ENOENT, it may be because the
2622 			 * CPU was unconfigured -- this is okay.  Any other
2623 			 * error, however, is unexpected.
2624 			 */
2625 			if (errno == ENOENT)
2626 				continue;
2627 
2628 			return (dt_set_errno(dtp, errno));
2629 		}
2630 
2631 		if ((rval = dt_consume_cpu(dtp, fp, i, buf, pf, rf, arg)) != 0)
2632 			return (rval);
2633 	}
2634 
2635 	if (!dtp->dt_stopped)
2636 		return (0);
2637 
2638 	buf->dtbd_cpu = dtp->dt_endedon;
2639 
2640 #if defined(sun)
2641 	if (dt_ioctl(dtp, DTRACEIOC_BUFSNAP, buf) == -1) {
2642 #else
2643 	if (dt_ioctl(dtp, DTRACEIOC_BUFSNAP, &buf) == -1) {
2644 #endif
2645 		/*
2646 		 * This _really_ shouldn't fail, but it is strictly speaking
2647 		 * possible for this to return ENOENT if the CPU that called
2648 		 * the END enabling somehow managed to become unconfigured.
2649 		 * It's unclear how the user can possibly expect anything
2650 		 * rational to happen in this case -- the state has been thrown
2651 		 * out along with the unconfigured CPU -- so we'll just drive
2652 		 * on...
2653 		 */
2654 		if (errno == ENOENT)
2655 			return (0);
2656 
2657 		return (dt_set_errno(dtp, errno));
2658 	}
2659 
2660 	return (dt_consume_cpu(dtp, fp, dtp->dt_endedon, buf, pf, rf, arg));
2661 }
2662