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 2009 Sun Microsystems, Inc.  All rights reserved.
23 * Use is subject to license terms.
24 */
25
26/* #pragma ident	"@(#)sdt.c	1.9	08/07/01 SMI" */
27
28#ifdef KERNEL
29#ifndef _KERNEL
30#define _KERNEL /* Solaris vs. Darwin */
31#endif
32#endif
33
34#include <sys/param.h>
35#include <sys/systm.h>
36#include <sys/errno.h>
37#include <sys/stat.h>
38#include <sys/ioctl.h>
39#include <sys/conf.h>
40#include <sys/fcntl.h>
41#include <miscfs/devfs/devfs.h>
42
43#include <sys/dtrace.h>
44#include <sys/dtrace_impl.h>
45
46#include <sys/dtrace_glue.h>
47
48#include <sys/sdt_impl.h>
49extern int dtrace_kernel_symbol_mode;
50
51struct savearea_t; /* Used anonymously */
52typedef kern_return_t (*perfCallback)(int, struct savearea_t *, uintptr_t *, int);
53
54#if defined(__i386__) || defined(__x86_64__)
55extern perfCallback tempDTraceTrapHook;
56extern kern_return_t fbt_perfCallback(int, struct savearea_t *, int, int);
57
58#define	SDT_PATCHVAL	0xf0
59#define	SDT_AFRAMES		6
60#else
61#error Unknown architecture
62#endif
63
64#define	SDT_PROBETAB_SIZE	0x1000		/* 4k entries -- 16K total */
65
66#define DTRACE_PROBE_PREFIX "_dtrace_probe$"
67
68static dev_info_t		*sdt_devi;
69static int			sdt_verbose = 0;
70sdt_probe_t		**sdt_probetab;
71int			sdt_probetab_size;
72int			sdt_probetab_mask;
73
74/*ARGSUSED*/
75static void
76__sdt_provide_module(void *arg, struct modctl *ctl)
77{
78#pragma unused(arg)
79	struct module *mp = (struct module *)ctl->mod_address;
80	char *modname = ctl->mod_modname;
81	sdt_probedesc_t *sdpd;
82	sdt_probe_t *sdp, *old;
83	sdt_provider_t *prov;
84	int len;
85
86	/*
87	 * One for all, and all for one:  if we haven't yet registered all of
88	 * our providers, we'll refuse to provide anything.
89	 */
90	for (prov = sdt_providers; prov->sdtp_name != NULL; prov++) {
91		if (prov->sdtp_id == DTRACE_PROVNONE)
92			return;
93	}
94
95	if (!mp || mp->sdt_nprobes != 0 || (sdpd = mp->sdt_probes) == NULL)
96		return;
97
98	for (sdpd = mp->sdt_probes; sdpd != NULL; sdpd = sdpd->sdpd_next) {
99	    const char *name = sdpd->sdpd_name, *func;
100	    char *nname;
101		int i, j;
102		dtrace_id_t id;
103
104		for (prov = sdt_providers; prov->sdtp_prefix != NULL; prov++) {
105			const char *prefpart, *prefix = prov->sdtp_prefix;
106
107			if ((prefpart = strstr(name, prefix))) {
108				name = prefpart + strlen(prefix);
109				break;
110			}
111		}
112
113		nname = kmem_alloc(len = strlen(name) + 1, KM_SLEEP);
114
115		for (i = 0, j = 0; name[j] != '\0'; i++) {
116			if (name[j] == '_' && name[j + 1] == '_') {
117				nname[i] = '-';
118				j += 2;
119			} else {
120				nname[i] = name[j++];
121			}
122		}
123
124		nname[i] = '\0';
125
126		sdp = kmem_zalloc(sizeof (sdt_probe_t), KM_SLEEP);
127		sdp->sdp_loadcnt = ctl->mod_loadcnt;
128		sdp->sdp_ctl = ctl;
129		sdp->sdp_name = nname;
130		sdp->sdp_namelen = len;
131		sdp->sdp_provider = prov;
132
133		func = sdpd->sdpd_func;
134
135		if (func == NULL)
136			func = "<unknown>";
137
138		/*
139		 * We have our provider.  Now create the probe.
140		 */
141		if ((id = dtrace_probe_lookup(prov->sdtp_id, modname,
142		    func, nname)) != DTRACE_IDNONE) {
143			old = dtrace_probe_arg(prov->sdtp_id, id);
144			ASSERT(old != NULL);
145
146			sdp->sdp_next = old->sdp_next;
147			sdp->sdp_id = id;
148			old->sdp_next = sdp;
149		} else {
150			sdp->sdp_id = dtrace_probe_create(prov->sdtp_id,
151			    modname, func, nname, SDT_AFRAMES, sdp);
152
153			mp->sdt_nprobes++;
154		}
155
156		sdp->sdp_hashnext =
157		    sdt_probetab[SDT_ADDR2NDX(sdpd->sdpd_offset)];
158		sdt_probetab[SDT_ADDR2NDX(sdpd->sdpd_offset)] = sdp;
159
160		sdp->sdp_patchval = SDT_PATCHVAL;
161		sdp->sdp_patchpoint = (sdt_instr_t *)sdpd->sdpd_offset;
162		sdp->sdp_savedval = *sdp->sdp_patchpoint;
163	}
164}
165
166/*ARGSUSED*/
167static void
168sdt_destroy(void *arg, dtrace_id_t id, void *parg)
169{
170#pragma unused(arg,id)
171	sdt_probe_t *sdp = parg, *old, *last, *hash;
172	int ndx;
173#if !defined(__APPLE__)
174	struct modctl *ctl = sdp->sdp_ctl;
175
176	if (ctl != NULL && ctl->mod_loadcnt == sdp->sdp_loadcnt) {
177		if ((ctl->mod_loadcnt == sdp->sdp_loadcnt &&
178		    ctl->mod_loaded)) {
179			((struct module *)(ctl->mod_mp))->sdt_nprobes--;
180		}
181	}
182#endif /* __APPLE__ */
183
184	while (sdp != NULL) {
185		old = sdp;
186
187		/*
188		 * Now we need to remove this probe from the sdt_probetab.
189		 */
190		ndx = SDT_ADDR2NDX(sdp->sdp_patchpoint);
191		last = NULL;
192		hash = sdt_probetab[ndx];
193
194		while (hash != sdp) {
195			ASSERT(hash != NULL);
196			last = hash;
197			hash = hash->sdp_hashnext;
198		}
199
200		if (last != NULL) {
201			last->sdp_hashnext = sdp->sdp_hashnext;
202		} else {
203			sdt_probetab[ndx] = sdp->sdp_hashnext;
204		}
205
206		kmem_free(sdp->sdp_name, sdp->sdp_namelen);
207		sdp = sdp->sdp_next;
208		kmem_free(old, sizeof (sdt_probe_t));
209	}
210}
211
212/*ARGSUSED*/
213static int
214sdt_enable(void *arg, dtrace_id_t id, void *parg)
215{
216#pragma unused(arg,id)
217	sdt_probe_t *sdp = parg;
218	struct modctl *ctl = sdp->sdp_ctl;
219
220	ctl->mod_nenabled++;
221
222	/*
223	 * If this module has disappeared since we discovered its probes,
224	 * refuse to enable it.
225	 */
226	if (!ctl->mod_loaded) {
227		if (sdt_verbose) {
228			cmn_err(CE_NOTE, "sdt is failing for probe %s "
229			    "(module %s unloaded)",
230			    sdp->sdp_name, ctl->mod_modname);
231		}
232		goto err;
233	}
234
235	/*
236	 * Now check that our modctl has the expected load count.  If it
237	 * doesn't, this module must have been unloaded and reloaded -- and
238	 * we're not going to touch it.
239	 */
240	if (ctl->mod_loadcnt != sdp->sdp_loadcnt) {
241		if (sdt_verbose) {
242			cmn_err(CE_NOTE, "sdt is failing for probe %s "
243			    "(module %s reloaded)",
244			    sdp->sdp_name, ctl->mod_modname);
245		}
246		goto err;
247	}
248
249	dtrace_casptr(&tempDTraceTrapHook, NULL, fbt_perfCallback);
250	if (tempDTraceTrapHook != (perfCallback)fbt_perfCallback) {
251		if (sdt_verbose) {
252			cmn_err(CE_NOTE, "sdt_enable is failing for probe %s "
253			    "in module %s: tempDTraceTrapHook already occupied.",
254			    sdp->sdp_name, ctl->mod_modname);
255		}
256		return (0);
257	}
258
259	while (sdp != NULL) {
260		(void)ml_nofault_copy( (vm_offset_t)&sdp->sdp_patchval, (vm_offset_t)sdp->sdp_patchpoint,
261		                       (vm_size_t)sizeof(sdp->sdp_patchval));
262		sdp = sdp->sdp_next;
263	}
264
265err:
266	return (0);
267}
268
269/*ARGSUSED*/
270static void
271sdt_disable(void *arg, dtrace_id_t id, void *parg)
272{
273#pragma unused(arg,id)
274	sdt_probe_t *sdp = parg;
275	struct modctl *ctl = sdp->sdp_ctl;
276
277	ctl->mod_nenabled--;
278
279	if (!ctl->mod_loaded || ctl->mod_loadcnt != sdp->sdp_loadcnt)
280		goto err;
281
282	while (sdp != NULL) {
283		(void)ml_nofault_copy( (vm_offset_t)&sdp->sdp_savedval, (vm_offset_t)sdp->sdp_patchpoint,
284		                       (vm_size_t)sizeof(sdp->sdp_savedval));
285		sdp = sdp->sdp_next;
286	}
287
288err:
289	;
290}
291
292static dtrace_pops_t sdt_pops = {
293	NULL,
294	sdt_provide_module,
295	sdt_enable,
296	sdt_disable,
297	NULL,
298	NULL,
299	sdt_getargdesc,
300	sdt_getarg,
301	NULL,
302	sdt_destroy
303};
304
305/*ARGSUSED*/
306static int
307sdt_attach(dev_info_t *devi, ddi_attach_cmd_t cmd)
308{
309#pragma unused(cmd)
310	sdt_provider_t *prov;
311
312	if (ddi_create_minor_node(devi, "sdt", S_IFCHR,
313	    0, DDI_PSEUDO, 0) == DDI_FAILURE) {
314		cmn_err(CE_NOTE, "/dev/sdt couldn't create minor node");
315		ddi_remove_minor_node(devi, NULL);
316		return (DDI_FAILURE);
317	}
318
319	ddi_report_dev(devi);
320	sdt_devi = devi;
321
322	if (sdt_probetab_size == 0)
323		sdt_probetab_size = SDT_PROBETAB_SIZE;
324
325	sdt_probetab_mask = sdt_probetab_size - 1;
326	sdt_probetab =
327	    kmem_zalloc(sdt_probetab_size * sizeof (sdt_probe_t *), KM_SLEEP);
328	dtrace_invop_add(sdt_invop);
329
330	for (prov = sdt_providers; prov->sdtp_name != NULL; prov++) {
331		if (dtrace_register(prov->sdtp_name, prov->sdtp_attr,
332		    DTRACE_PRIV_KERNEL, NULL,
333		    &sdt_pops, prov, &prov->sdtp_id) != 0) {
334			cmn_err(CE_WARN, "failed to register sdt provider %s",
335			    prov->sdtp_name);
336		}
337	}
338
339	return (DDI_SUCCESS);
340}
341
342#if !defined(__APPLE__)
343/*ARGSUSED*/
344static int
345sdt_detach(dev_info_t *dip, ddi_detach_cmd_t cmd)
346{
347	sdt_provider_t *prov;
348
349	switch (cmd) {
350	case DDI_DETACH:
351		break;
352
353	case DDI_SUSPEND:
354		return (DDI_SUCCESS);
355
356	default:
357		return (DDI_FAILURE);
358	}
359
360	for (prov = sdt_providers; prov->sdtp_name != NULL; prov++) {
361		if (prov->sdtp_id != DTRACE_PROVNONE) {
362			if (dtrace_unregister(prov->sdtp_id) != 0)
363				return (DDI_FAILURE);
364
365			prov->sdtp_id = DTRACE_PROVNONE;
366		}
367	}
368
369	dtrace_invop_remove(sdt_invop);
370	kmem_free(sdt_probetab, sdt_probetab_size * sizeof (sdt_probe_t *));
371
372	return (DDI_SUCCESS);
373}
374
375/*ARGSUSED*/
376static int
377sdt_info(dev_info_t *dip, ddi_info_cmd_t infocmd, void *arg, void **result)
378{
379	int error;
380
381	switch (infocmd) {
382	case DDI_INFO_DEVT2DEVINFO:
383		*result = (void *)sdt_devi;
384		error = DDI_SUCCESS;
385		break;
386	case DDI_INFO_DEVT2INSTANCE:
387		*result = (void *)0;
388		error = DDI_SUCCESS;
389		break;
390	default:
391		error = DDI_FAILURE;
392	}
393	return (error);
394}
395
396/*ARGSUSED*/
397static int
398sdt_open(dev_t *devp, int flag, int otyp, cred_t *cred_p)
399{
400	return (0);
401}
402
403static struct cb_ops sdt_cb_ops = {
404	sdt_open,		/* open */
405	nodev,			/* close */
406	nulldev,		/* strategy */
407	nulldev,		/* print */
408	nodev,			/* dump */
409	nodev,			/* read */
410	nodev,			/* write */
411	nodev,			/* ioctl */
412	nodev,			/* devmap */
413	nodev,			/* mmap */
414	nodev,			/* segmap */
415	nochpoll,		/* poll */
416	ddi_prop_op,		/* cb_prop_op */
417	0,			/* streamtab  */
418	D_NEW | D_MP		/* Driver compatibility flag */
419};
420
421static struct dev_ops sdt_ops = {
422	DEVO_REV,		/* devo_rev, */
423	0,			/* refcnt  */
424	sdt_info,		/* get_dev_info */
425	nulldev,		/* identify */
426	nulldev,		/* probe */
427	sdt_attach,		/* attach */
428	sdt_detach,		/* detach */
429	nodev,			/* reset */
430	&sdt_cb_ops,		/* driver operations */
431	NULL,			/* bus operations */
432	nodev			/* dev power */
433};
434
435/*
436 * Module linkage information for the kernel.
437 */
438static struct modldrv modldrv = {
439	&mod_driverops,		/* module type (this is a pseudo driver) */
440	"Statically Defined Tracing",	/* name of module */
441	&sdt_ops,		/* driver ops */
442};
443
444static struct modlinkage modlinkage = {
445	MODREV_1,
446	(void *)&modldrv,
447	NULL
448};
449
450int
451_init(void)
452{
453	return (mod_install(&modlinkage));
454}
455
456int
457_info(struct modinfo *modinfop)
458{
459	return (mod_info(&modlinkage, modinfop));
460}
461
462int
463_fini(void)
464{
465	return (mod_remove(&modlinkage));
466}
467#else
468d_open_t _sdt_open;
469
470int _sdt_open(dev_t dev, int flags, int devtype, struct proc *p)
471{
472#pragma unused(dev,flags,devtype,p)
473	return 0;
474}
475
476#define SDT_MAJOR  -24 /* let the kernel pick the device number */
477
478/*
479 * A struct describing which functions will get invoked for certain
480 * actions.
481 */
482static struct cdevsw sdt_cdevsw =
483{
484	_sdt_open,		/* open */
485	eno_opcl,			/* close */
486	eno_rdwrt,			/* read */
487	eno_rdwrt,			/* write */
488	eno_ioctl,			/* ioctl */
489	(stop_fcn_t *)nulldev, /* stop */
490	(reset_fcn_t *)nulldev, /* reset */
491	NULL,				/* tty's */
492	eno_select,			/* select */
493	eno_mmap,			/* mmap */
494	eno_strat,			/* strategy */
495	eno_getc,			/* getc */
496	eno_putc,			/* putc */
497	0					/* type */
498};
499
500static int gSDTInited = 0;
501static struct modctl g_sdt_kernctl;
502static struct module g_sdt_mach_module;
503
504#include <mach-o/nlist.h>
505#include <libkern/kernel_mach_header.h>
506
507void sdt_init( void )
508{
509	if (0 == gSDTInited)
510	{
511		int majdevno = cdevsw_add(SDT_MAJOR, &sdt_cdevsw);
512
513		if (majdevno < 0) {
514			printf("sdt_init: failed to allocate a major number!\n");
515			gSDTInited = 0;
516			return;
517		}
518
519		if (MH_MAGIC_KERNEL != _mh_execute_header.magic) {
520			g_sdt_kernctl.mod_address = (vm_address_t)NULL;
521			g_sdt_kernctl.mod_size = 0;
522		} else {
523			kernel_mach_header_t        *mh;
524			struct load_command         *cmd;
525			kernel_segment_command_t    *orig_ts = NULL, *orig_le = NULL;
526			struct symtab_command       *orig_st = NULL;
527			kernel_nlist_t		    *sym = NULL;
528			char                        *strings;
529			unsigned int 		    i;
530
531			g_sdt_mach_module.sdt_nprobes = 0;
532			g_sdt_mach_module.sdt_probes = NULL;
533
534			g_sdt_kernctl.mod_address = (vm_address_t)&g_sdt_mach_module;
535			g_sdt_kernctl.mod_size = 0;
536			strncpy((char *)&(g_sdt_kernctl.mod_modname), "mach_kernel", KMOD_MAX_NAME);
537
538			g_sdt_kernctl.mod_next = NULL;
539			g_sdt_kernctl.mod_stale = NULL;
540			g_sdt_kernctl.mod_id = 0;
541			g_sdt_kernctl.mod_loadcnt = 1;
542			g_sdt_kernctl.mod_loaded = 1;
543			g_sdt_kernctl.mod_flags = 0;
544			g_sdt_kernctl.mod_nenabled = 0;
545
546			mh = &_mh_execute_header;
547			cmd = (struct load_command*) &mh[1];
548			for (i = 0; i < mh->ncmds; i++) {
549				if (cmd->cmd == LC_SEGMENT_KERNEL) {
550					kernel_segment_command_t *orig_sg = (kernel_segment_command_t *) cmd;
551
552					if (LIT_STRNEQL(orig_sg->segname, SEG_TEXT))
553						orig_ts = orig_sg;
554					else if (LIT_STRNEQL(orig_sg->segname, SEG_LINKEDIT))
555						orig_le = orig_sg;
556					else if (LIT_STRNEQL(orig_sg->segname, ""))
557						orig_ts = orig_sg; /* kexts have a single unnamed segment */
558				}
559				else if (cmd->cmd == LC_SYMTAB)
560					orig_st = (struct symtab_command *) cmd;
561
562				cmd = (struct load_command *) ((uintptr_t) cmd + cmd->cmdsize);
563			}
564
565			if ((orig_ts == NULL) || (orig_st == NULL) || (orig_le == NULL))
566				return;
567
568			sym = (kernel_nlist_t *)(orig_le->vmaddr + orig_st->symoff - orig_le->fileoff);
569			strings = (char *)(orig_le->vmaddr + orig_st->stroff - orig_le->fileoff);
570
571			for (i = 0; i < orig_st->nsyms; i++) {
572				uint8_t n_type = sym[i].n_type & (N_TYPE | N_EXT);
573				char *name = strings + sym[i].n_un.n_strx;
574				const char *prev_name;
575				unsigned long best;
576				unsigned int j;
577
578				/* Check that the symbol is a global and that it has a name. */
579				if (((N_SECT | N_EXT) != n_type && (N_ABS | N_EXT) != n_type))
580					continue;
581
582				if (0 == sym[i].n_un.n_strx) /* iff a null, "", name. */
583					continue;
584
585				/* Lop off omnipresent leading underscore. */
586				if (*name == '_')
587					name += 1;
588
589				if (strncmp(name, DTRACE_PROBE_PREFIX, sizeof(DTRACE_PROBE_PREFIX) - 1) == 0) {
590					sdt_probedesc_t *sdpd = kmem_alloc(sizeof(sdt_probedesc_t), KM_SLEEP);
591					int len = strlen(name) + 1;
592
593					sdpd->sdpd_name = kmem_alloc(len, KM_SLEEP);
594					strncpy(sdpd->sdpd_name, name, len); /* NUL termination is ensured. */
595
596					prev_name = "<unknown>";
597					best = 0;
598
599					/*
600					 * Find the symbol immediately preceding the sdt probe site just discovered,
601					 * that symbol names the function containing the sdt probe.
602					 */
603					for (j = 0; j < orig_st->nsyms; j++) {
604						uint8_t jn_type = sym[j].n_type & (N_TYPE | N_EXT);
605						char *jname = strings + sym[j].n_un.n_strx;
606
607						if (((N_SECT | N_EXT) != jn_type && (N_ABS | N_EXT) != jn_type))
608							continue;
609
610						if (0 == sym[j].n_un.n_strx) /* iff a null, "", name. */
611							continue;
612
613						if (*jname == '_')
614							jname += 1;
615
616						if (*(unsigned long *)sym[i].n_value <= (unsigned long)sym[j].n_value)
617							continue;
618
619						if ((unsigned long)sym[j].n_value > best) {
620							best = (unsigned long)sym[j].n_value;
621							prev_name = jname;
622						}
623					}
624
625					sdpd->sdpd_func = kmem_alloc((len = strlen(prev_name) + 1), KM_SLEEP);
626					strncpy(sdpd->sdpd_func, prev_name, len); /* NUL termination is ensured. */
627
628					sdpd->sdpd_offset = *(unsigned long *)sym[i].n_value;
629
630					sdpd->sdpd_next = g_sdt_mach_module.sdt_probes;
631					g_sdt_mach_module.sdt_probes = sdpd;
632				} else {
633					prev_name = name;
634				}
635			}
636		}
637
638		sdt_attach( (dev_info_t	*)(uintptr_t)majdevno, DDI_ATTACH );
639
640		gSDTInited = 1;
641	} else
642		panic("sdt_init: called twice!\n");
643}
644
645#undef SDT_MAJOR
646
647/*ARGSUSED*/
648void
649sdt_provide_module(void *arg, struct modctl *ctl)
650{
651#pragma unused(arg)
652	ASSERT(ctl != NULL);
653	ASSERT(dtrace_kernel_symbol_mode != DTRACE_KERNEL_SYMBOLS_NEVER);
654	lck_mtx_assert(&mod_lock, LCK_MTX_ASSERT_OWNED);
655
656	if (MOD_SDT_DONE(ctl))
657		return;
658
659	if (MOD_IS_MACH_KERNEL(ctl)) {
660		__sdt_provide_module(arg, &g_sdt_kernctl);
661
662		sdt_probedesc_t *sdpd = g_sdt_mach_module.sdt_probes;
663		while (sdpd) {
664			sdt_probedesc_t *this_sdpd = sdpd;
665			kmem_free((void *)sdpd->sdpd_name, strlen(sdpd->sdpd_name) + 1);
666			kmem_free((void *)sdpd->sdpd_func, strlen(sdpd->sdpd_func) + 1);
667			sdpd = sdpd->sdpd_next;
668			kmem_free((void *)this_sdpd, sizeof(sdt_probedesc_t));
669		}
670		g_sdt_mach_module.sdt_probes = NULL;
671	} else {
672		/* FIXME -- sdt in kext not yet supported */
673	}
674
675	/* Need to mark this module as completed */
676	ctl->mod_flags |= MODCTL_SDT_PROBES_PROVIDED;
677}
678
679#endif /* __APPLE__ */
680