diff options
Diffstat (limited to 'lib/libkvm')
35 files changed, 7559 insertions, 0 deletions
diff --git a/lib/libkvm/Makefile b/lib/libkvm/Makefile new file mode 100644 index 0000000..1250bf7 --- /dev/null +++ b/lib/libkvm/Makefile @@ -0,0 +1,34 @@ +# @(#)Makefile 8.1 (Berkeley) 6/4/93 +# $FreeBSD$ + +LIB= kvm +SHLIBDIR?= /lib +CFLAGS+=-DLIBC_SCCS -I${.CURDIR} + +.if exists(${.CURDIR}/kvm_${MACHINE_ARCH}.c) +KVM_ARCH=${MACHINE_ARCH} +.else +KVM_ARCH=${MACHINE_CPUARCH} +.endif + +WARNS?= 3 + +SRCS= kvm.c kvm_${KVM_ARCH}.c kvm_cptime.c kvm_file.c kvm_getloadavg.c \ + kvm_getswapinfo.c kvm_pcpu.c kvm_proc.c kvm_vnet.c +.if ${MACHINE_CPUARCH} == "amd64" || ${MACHINE_CPUARCH} == "i386" || \ + ${MACHINE_CPUARCH} == "arm" || ${MACHINE_CPUARCH} == "mips" +SRCS+= kvm_minidump_${KVM_ARCH}.c +.endif +INCS= kvm.h + +MAN= kvm.3 kvm_getcptime.3 kvm_geterr.3 kvm_getfiles.3 kvm_getloadavg.3 \ + kvm_getpcpu.3 kvm_getprocs.3 kvm_getswapinfo.3 kvm_nlist.3 kvm_open.3 \ + kvm_read.3 + +MLINKS+=kvm_getpcpu.3 kvm_getmaxcpu.3 +MLINKS+=kvm_getpcpu.3 kvm_dpcpu_setcpu.3 +MLINKS+=kvm_getprocs.3 kvm_getargv.3 kvm_getprocs.3 kvm_getenvv.3 +MLINKS+=kvm_open.3 kvm_close.3 kvm_open.3 kvm_openfiles.3 +MLINKS+=kvm_read.3 kvm_write.3 + +.include <bsd.lib.mk> diff --git a/lib/libkvm/kvm.3 b/lib/libkvm/kvm.3 new file mode 100644 index 0000000..9dcd772 --- /dev/null +++ b/lib/libkvm/kvm.3 @@ -0,0 +1,120 @@ +.\" Copyright (c) 1992, 1993 +.\" The Regents of the University of California. All rights reserved. +.\" +.\" This code is derived from software developed by the Computer Systems +.\" Engineering group at Lawrence Berkeley Laboratory under DARPA contract +.\" BG 91-66 and contributed to Berkeley. +.\" +.\" Redistribution and use in source and binary forms, with or without +.\" modification, are permitted provided that the following conditions +.\" are met: +.\" 1. Redistributions of source code must retain the above copyright +.\" notice, this list of conditions and the following disclaimer. +.\" 2. Redistributions in binary form must reproduce the above copyright +.\" notice, this list of conditions and the following disclaimer in the +.\" documentation and/or other materials provided with the distribution. +.\" 4. Neither the name of the University nor the names of its contributors +.\" may be used to endorse or promote products derived from this software +.\" without specific prior written permission. +.\" +.\" THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND +.\" ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE +.\" IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE +.\" ARE DISCLAIMED. IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE +.\" FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL +.\" DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS +.\" OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) +.\" HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT +.\" LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY +.\" OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF +.\" SUCH DAMAGE. +.\" +.\" @(#)kvm.3 8.1 (Berkeley) 6/4/93 +.\" $FreeBSD$ +.\" +.Dd April 25, 2010 +.Dt KVM 3 +.Os +.Sh NAME +.Nm kvm +.Nd kernel memory interface +.Sh LIBRARY +.Lb libkvm +.Sh DESCRIPTION +The +.Nm +library provides a uniform interface for accessing kernel virtual memory +images, including live systems and crash dumps. +Access to live systems is via +.Xr sysctl 3 +for some functions, and +.Xr mem 4 +and +.Xr kmem 4 +for other functions, +while crash dumps can be examined via the core file generated by +.Xr savecore 8 . +The interface behaves similarly in both cases. +Memory can be read and written, kernel symbol addresses can be +looked up efficiently, and information about user processes can +be gathered. +.Pp +The +.Fn kvm_open +function is first called to obtain a descriptor for all subsequent calls. +.Sh COMPATIBILITY +The kvm interface was first introduced in SunOS. +A considerable +number of programs have been developed that use this interface, +making backward compatibility highly desirable. +In most respects, the Sun kvm interface is consistent and clean. +Accordingly, the generic portion of the interface (i.e., +.Fn kvm_open , +.Fn kvm_close , +.Fn kvm_read , +.Fn kvm_write , +and +.Fn kvm_nlist ) +has been incorporated into the +.Bx +interface. +Indeed, many kvm +applications (i.e., debuggers and statistical monitors) use only +this subset of the interface. +.Pp +The process interface was not kept. +This is not a portability +issue since any code that manipulates processes is inherently +machine dependent. +.Pp +Finally, the Sun kvm error reporting semantics are poorly defined. +The library can be configured either to print errors to +.Dv stderr +automatically, +or to print no error messages at all. +In the latter case, the nature of the error cannot be determined. +To overcome this, the +.Bx +interface includes a +routine, +.Xr kvm_geterr 3 , +to return (not print out) the error message +corresponding to the most recent error condition on the +given descriptor. +.Sh SEE ALSO +.Xr kvm_close 3 , +.Xr kvm_getargv 3 , +.Xr kvm_getenvv 3 , +.Xr kvm_geterr 3 , +.Xr kvm_getfiles 3 , +.Xr kvm_getloadavg 3 , +.Xr kvm_getprocs 3 , +.Xr kvm_getswapinfo 3 , +.Xr kvm_nlist 3 , +.Xr kvm_open 3 , +.Xr kvm_openfiles 3 , +.Xr kvm_read 3 , +.Xr kvm_write 3 , +.Xr sysctl 3 , +.Xr kmem 4 , +.Xr mem 4 diff --git a/lib/libkvm/kvm.c b/lib/libkvm/kvm.c new file mode 100644 index 0000000..6c19a14 --- /dev/null +++ b/lib/libkvm/kvm.c @@ -0,0 +1,594 @@ +/*- + * Copyright (c) 1989, 1992, 1993 + * The Regents of the University of California. All rights reserved. + * + * This code is derived from software developed by the Computer Systems + * Engineering group at Lawrence Berkeley Laboratory under DARPA contract + * BG 91-66 and contributed to Berkeley. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions + * are met: + * 1. Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * 2. Redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in the + * documentation and/or other materials provided with the distribution. + * 4. Neither the name of the University nor the names of its contributors + * may be used to endorse or promote products derived from this software + * without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND + * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + * ARE DISCLAIMED. IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE + * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL + * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS + * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) + * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT + * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY + * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF + * SUCH DAMAGE. + */ + +#include <sys/cdefs.h> +__FBSDID("$FreeBSD$"); + +#if defined(LIBC_SCCS) && !defined(lint) +#if 0 +static char sccsid[] = "@(#)kvm.c 8.2 (Berkeley) 2/13/94"; +#endif +#endif /* LIBC_SCCS and not lint */ + +#include <sys/param.h> + +#define _WANT_VNET + +#include <sys/user.h> +#include <sys/proc.h> +#include <sys/ioctl.h> +#include <sys/stat.h> +#include <sys/sysctl.h> +#include <sys/linker.h> +#include <sys/pcpu.h> + +#include <net/vnet.h> + +#include <vm/vm.h> +#include <vm/vm_param.h> + +#include <machine/vmparam.h> + +#include <ctype.h> +#include <fcntl.h> +#include <kvm.h> +#include <limits.h> +#include <nlist.h> +#include <paths.h> +#include <stdio.h> +#include <stdlib.h> +#include <string.h> +#include <strings.h> +#include <unistd.h> + +#include "kvm_private.h" + +/* from src/lib/libc/gen/nlist.c */ +int __fdnlist(int, struct nlist *); + +char * +kvm_geterr(kvm_t *kd) +{ + return (kd->errbuf); +} + +#include <stdarg.h> + +/* + * Report an error using printf style arguments. "program" is kd->program + * on hard errors, and 0 on soft errors, so that under sun error emulation, + * only hard errors are printed out (otherwise, programs like gdb will + * generate tons of error messages when trying to access bogus pointers). + */ +void +_kvm_err(kvm_t *kd, const char *program, const char *fmt, ...) +{ + va_list ap; + + va_start(ap, fmt); + if (program != NULL) { + (void)fprintf(stderr, "%s: ", program); + (void)vfprintf(stderr, fmt, ap); + (void)fputc('\n', stderr); + } else + (void)vsnprintf(kd->errbuf, + sizeof(kd->errbuf), fmt, ap); + + va_end(ap); +} + +void +_kvm_syserr(kvm_t *kd, const char *program, const char *fmt, ...) +{ + va_list ap; + int n; + + va_start(ap, fmt); + if (program != NULL) { + (void)fprintf(stderr, "%s: ", program); + (void)vfprintf(stderr, fmt, ap); + (void)fprintf(stderr, ": %s\n", strerror(errno)); + } else { + char *cp = kd->errbuf; + + (void)vsnprintf(cp, sizeof(kd->errbuf), fmt, ap); + n = strlen(cp); + (void)snprintf(&cp[n], sizeof(kd->errbuf) - n, ": %s", + strerror(errno)); + } + va_end(ap); +} + +void * +_kvm_malloc(kvm_t *kd, size_t n) +{ + void *p; + + if ((p = calloc(n, sizeof(char))) == NULL) + _kvm_err(kd, kd->program, "can't allocate %zu bytes: %s", + n, strerror(errno)); + return (p); +} + +static kvm_t * +_kvm_open(kvm_t *kd, const char *uf, const char *mf, int flag, char *errout) +{ + struct stat st; + + kd->vmfd = -1; + kd->pmfd = -1; + kd->nlfd = -1; + kd->vmst = 0; + kd->procbase = 0; + kd->argspc = 0; + kd->argv = 0; + + if (uf == 0) + uf = getbootfile(); + else if (strlen(uf) >= MAXPATHLEN) { + _kvm_err(kd, kd->program, "exec file name too long"); + goto failed; + } + if (flag & ~O_RDWR) { + _kvm_err(kd, kd->program, "bad flags arg"); + goto failed; + } + if (mf == 0) + mf = _PATH_MEM; + + if ((kd->pmfd = open(mf, flag, 0)) < 0) { + _kvm_syserr(kd, kd->program, "%s", mf); + goto failed; + } + if (fstat(kd->pmfd, &st) < 0) { + _kvm_syserr(kd, kd->program, "%s", mf); + goto failed; + } + if (S_ISREG(st.st_mode) && st.st_size <= 0) { + errno = EINVAL; + _kvm_syserr(kd, kd->program, "empty file"); + goto failed; + } + if (fcntl(kd->pmfd, F_SETFD, FD_CLOEXEC) < 0) { + _kvm_syserr(kd, kd->program, "%s", mf); + goto failed; + } + if (S_ISCHR(st.st_mode)) { + /* + * If this is a character special device, then check that + * it's /dev/mem. If so, open kmem too. (Maybe we should + * make it work for either /dev/mem or /dev/kmem -- in either + * case you're working with a live kernel.) + */ + if (strcmp(mf, _PATH_DEVNULL) == 0) { + kd->vmfd = open(_PATH_DEVNULL, O_RDONLY); + return (kd); + } else if (strcmp(mf, _PATH_MEM) == 0) { + if ((kd->vmfd = open(_PATH_KMEM, flag)) < 0) { + _kvm_syserr(kd, kd->program, "%s", _PATH_KMEM); + goto failed; + } + if (fcntl(kd->vmfd, F_SETFD, FD_CLOEXEC) < 0) { + _kvm_syserr(kd, kd->program, "%s", _PATH_KMEM); + goto failed; + } + return (kd); + } + } + /* + * This is a crash dump. + * Initialize the virtual address translation machinery, + * but first setup the namelist fd. + */ + if ((kd->nlfd = open(uf, O_RDONLY, 0)) < 0) { + _kvm_syserr(kd, kd->program, "%s", uf); + goto failed; + } + if (fcntl(kd->nlfd, F_SETFD, FD_CLOEXEC) < 0) { + _kvm_syserr(kd, kd->program, "%s", uf); + goto failed; + } + if (strncmp(mf, _PATH_FWMEM, strlen(_PATH_FWMEM)) == 0) + kd->rawdump = 1; + if (_kvm_initvtop(kd) < 0) + goto failed; + return (kd); +failed: + /* + * Copy out the error if doing sane error semantics. + */ + if (errout != 0) + strlcpy(errout, kd->errbuf, _POSIX2_LINE_MAX); + (void)kvm_close(kd); + return (0); +} + +kvm_t * +kvm_openfiles(const char *uf, const char *mf, const char *sf __unused, int flag, + char *errout) +{ + kvm_t *kd; + + if ((kd = calloc(1, sizeof(*kd))) == NULL) { + (void)strlcpy(errout, strerror(errno), _POSIX2_LINE_MAX); + return (0); + } + kd->program = 0; + return (_kvm_open(kd, uf, mf, flag, errout)); +} + +kvm_t * +kvm_open(const char *uf, const char *mf, const char *sf __unused, int flag, + const char *errstr) +{ + kvm_t *kd; + + if ((kd = calloc(1, sizeof(*kd))) == NULL) { + if (errstr != NULL) + (void)fprintf(stderr, "%s: %s\n", + errstr, strerror(errno)); + return (0); + } + kd->program = errstr; + return (_kvm_open(kd, uf, mf, flag, NULL)); +} + +int +kvm_close(kvm_t *kd) +{ + int error = 0; + + if (kd->pmfd >= 0) + error |= close(kd->pmfd); + if (kd->vmfd >= 0) + error |= close(kd->vmfd); + if (kd->nlfd >= 0) + error |= close(kd->nlfd); + if (kd->vmst) + _kvm_freevtop(kd); + if (kd->procbase != 0) + free((void *)kd->procbase); + if (kd->argbuf != 0) + free((void *) kd->argbuf); + if (kd->argspc != 0) + free((void *) kd->argspc); + if (kd->argv != 0) + free((void *)kd->argv); + free((void *)kd); + + return (0); +} + +/* + * Walk the list of unresolved symbols, generate a new list and prefix the + * symbol names, try again, and merge back what we could resolve. + */ +static int +kvm_fdnlist_prefix(kvm_t *kd, struct nlist *nl, int missing, const char *prefix, + uintptr_t (*validate_fn)(kvm_t *, uintptr_t)) +{ + struct nlist *n, *np, *p; + char *cp, *ce; + const char *ccp; + size_t len; + int slen, unresolved; + + /* + * Calculate the space we need to malloc for nlist and names. + * We are going to store the name twice for later lookups: once + * with the prefix and once the unmodified name delmited by \0. + */ + len = 0; + unresolved = 0; + for (p = nl; p->n_name && p->n_name[0]; ++p) { + if (p->n_type != N_UNDF) + continue; + len += sizeof(struct nlist) + strlen(prefix) + + 2 * (strlen(p->n_name) + 1); + unresolved++; + } + if (unresolved == 0) + return (unresolved); + /* Add space for the terminating nlist entry. */ + len += sizeof(struct nlist); + unresolved++; + + /* Alloc one chunk for (nlist, [names]) and setup pointers. */ + n = np = malloc(len); + bzero(n, len); + if (n == NULL) + return (missing); + cp = ce = (char *)np; + cp += unresolved * sizeof(struct nlist); + ce += len; + + /* Generate shortened nlist with special prefix. */ + unresolved = 0; + for (p = nl; p->n_name && p->n_name[0]; ++p) { + if (p->n_type != N_UNDF) + continue; + bcopy(p, np, sizeof(struct nlist)); + /* Save the new\0orig. name so we can later match it again. */ + slen = snprintf(cp, ce - cp, "%s%s%c%s", prefix, + (prefix[0] != '\0' && p->n_name[0] == '_') ? + (p->n_name + 1) : p->n_name, '\0', p->n_name); + if (slen < 0 || slen >= ce - cp) + continue; + np->n_name = cp; + cp += slen + 1; + np++; + unresolved++; + } + + /* Do lookup on the reduced list. */ + np = n; + unresolved = __fdnlist(kd->nlfd, np); + + /* Check if we could resolve further symbols and update the list. */ + if (unresolved >= 0 && unresolved < missing) { + /* Find the first freshly resolved entry. */ + for (; np->n_name && np->n_name[0]; np++) + if (np->n_type != N_UNDF) + break; + /* + * The lists are both in the same order, + * so we can walk them in parallel. + */ + for (p = nl; np->n_name && np->n_name[0] && + p->n_name && p->n_name[0]; ++p) { + if (p->n_type != N_UNDF) + continue; + /* Skip expanded name and compare to orig. one. */ + ccp = np->n_name + strlen(np->n_name) + 1; + if (strcmp(ccp, p->n_name) != 0) + continue; + /* Update nlist with new, translated results. */ + p->n_type = np->n_type; + p->n_other = np->n_other; + p->n_desc = np->n_desc; + if (validate_fn) + p->n_value = (*validate_fn)(kd, np->n_value); + else + p->n_value = np->n_value; + missing--; + /* Find next freshly resolved entry. */ + for (np++; np->n_name && np->n_name[0]; np++) + if (np->n_type != N_UNDF) + break; + } + } + /* We could assert missing = unresolved here. */ + + free(n); + return (unresolved); +} + +int +_kvm_nlist(kvm_t *kd, struct nlist *nl, int initialize) +{ + struct nlist *p; + int nvalid; + struct kld_sym_lookup lookup; + int error; + const char *prefix = ""; + char symname[1024]; /* XXX-BZ symbol name length limit? */ + int tried_vnet, tried_dpcpu; + + /* + * If we can't use the kld symbol lookup, revert to the + * slow library call. + */ + if (!ISALIVE(kd)) { + error = __fdnlist(kd->nlfd, nl); + if (error <= 0) /* Hard error or success. */ + return (error); + + if (_kvm_vnet_initialized(kd, initialize)) + error = kvm_fdnlist_prefix(kd, nl, error, + VNET_SYMPREFIX, _kvm_vnet_validaddr); + + if (error > 0 && _kvm_dpcpu_initialized(kd, initialize)) + error = kvm_fdnlist_prefix(kd, nl, error, + DPCPU_SYMPREFIX, _kvm_dpcpu_validaddr); + + return (error); + } + + /* + * We can use the kld lookup syscall. Go through each nlist entry + * and look it up with a kldsym(2) syscall. + */ + nvalid = 0; + tried_vnet = 0; + tried_dpcpu = 0; +again: + for (p = nl; p->n_name && p->n_name[0]; ++p) { + if (p->n_type != N_UNDF) + continue; + + lookup.version = sizeof(lookup); + lookup.symvalue = 0; + lookup.symsize = 0; + + error = snprintf(symname, sizeof(symname), "%s%s", prefix, + (prefix[0] != '\0' && p->n_name[0] == '_') ? + (p->n_name + 1) : p->n_name); + if (error < 0 || error >= (int)sizeof(symname)) + continue; + lookup.symname = symname; + if (lookup.symname[0] == '_') + lookup.symname++; + + if (kldsym(0, KLDSYM_LOOKUP, &lookup) != -1) { + p->n_type = N_TEXT; + p->n_other = 0; + p->n_desc = 0; + if (_kvm_vnet_initialized(kd, initialize) && + strcmp(prefix, VNET_SYMPREFIX) == 0) + p->n_value = + _kvm_vnet_validaddr(kd, lookup.symvalue); + else if (_kvm_dpcpu_initialized(kd, initialize) && + strcmp(prefix, DPCPU_SYMPREFIX) == 0) + p->n_value = + _kvm_dpcpu_validaddr(kd, lookup.symvalue); + else + p->n_value = lookup.symvalue; + ++nvalid; + /* lookup.symsize */ + } + } + + /* + * Check the number of entries that weren't found. If they exist, + * try again with a prefix for virtualized or DPCPU symbol names. + */ + error = ((p - nl) - nvalid); + if (error && _kvm_vnet_initialized(kd, initialize) && !tried_vnet) { + tried_vnet = 1; + prefix = VNET_SYMPREFIX; + goto again; + } + if (error && _kvm_dpcpu_initialized(kd, initialize) && !tried_dpcpu) { + tried_dpcpu = 1; + prefix = DPCPU_SYMPREFIX; + goto again; + } + + /* + * Return the number of entries that weren't found. If they exist, + * also fill internal error buffer. + */ + error = ((p - nl) - nvalid); + if (error) + _kvm_syserr(kd, kd->program, "kvm_nlist"); + return (error); +} + +int +kvm_nlist(kvm_t *kd, struct nlist *nl) +{ + + /* + * If called via the public interface, permit intialization of + * further virtualized modules on demand. + */ + return (_kvm_nlist(kd, nl, 1)); +} + +ssize_t +kvm_read(kvm_t *kd, u_long kva, void *buf, size_t len) +{ + int cc; + ssize_t cr; + off_t pa; + char *cp; + + if (ISALIVE(kd)) { + /* + * We're using /dev/kmem. Just read straight from the + * device and let the active kernel do the address translation. + */ + errno = 0; + if (lseek(kd->vmfd, (off_t)kva, 0) == -1 && errno != 0) { + _kvm_err(kd, 0, "invalid address (%lx)", kva); + return (-1); + } + cr = read(kd->vmfd, buf, len); + if (cr < 0) { + _kvm_syserr(kd, 0, "kvm_read"); + return (-1); + } else if (cr < (ssize_t)len) + _kvm_err(kd, kd->program, "short read"); + return (cr); + } + + cp = buf; + while (len > 0) { + cc = _kvm_kvatop(kd, kva, &pa); + if (cc == 0) + return (-1); + if (cc > (ssize_t)len) + cc = len; + errno = 0; + if (lseek(kd->pmfd, pa, 0) == -1 && errno != 0) { + _kvm_syserr(kd, 0, _PATH_MEM); + break; + } + cr = read(kd->pmfd, cp, cc); + if (cr < 0) { + _kvm_syserr(kd, kd->program, "kvm_read"); + break; + } + /* + * If kvm_kvatop returns a bogus value or our core file is + * truncated, we might wind up seeking beyond the end of the + * core file in which case the read will return 0 (EOF). + */ + if (cr == 0) + break; + cp += cr; + kva += cr; + len -= cr; + } + + return (cp - (char *)buf); +} + +ssize_t +kvm_write(kvm_t *kd, u_long kva, const void *buf, size_t len) +{ + int cc; + + if (ISALIVE(kd)) { + /* + * Just like kvm_read, only we write. + */ + errno = 0; + if (lseek(kd->vmfd, (off_t)kva, 0) == -1 && errno != 0) { + _kvm_err(kd, 0, "invalid address (%lx)", kva); + return (-1); + } + cc = write(kd->vmfd, buf, len); + if (cc < 0) { + _kvm_syserr(kd, 0, "kvm_write"); + return (-1); + } else if ((size_t)cc < len) + _kvm_err(kd, kd->program, "short write"); + return (cc); + } else { + _kvm_err(kd, kd->program, + "kvm_write not implemented for dead kernels"); + return (-1); + } + /* NOTREACHED */ +} diff --git a/lib/libkvm/kvm.h b/lib/libkvm/kvm.h new file mode 100644 index 0000000..912f1d4 --- /dev/null +++ b/lib/libkvm/kvm.h @@ -0,0 +1,95 @@ +/*- + * Copyright (c) 1989, 1993 + * The Regents of the University of California. All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions + * are met: + * 1. Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * 2. Redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in the + * documentation and/or other materials provided with the distribution. + * 4. Neither the name of the University nor the names of its contributors + * may be used to endorse or promote products derived from this software + * without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND + * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + * ARE DISCLAIMED. IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE + * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL + * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS + * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) + * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT + * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY + * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF + * SUCH DAMAGE. + * + * @(#)kvm.h 8.1 (Berkeley) 6/2/93 + * $FreeBSD$ + */ + +#ifndef _KVM_H_ +#define _KVM_H_ + +#include <sys/cdefs.h> +#include <sys/_types.h> +#include <nlist.h> + +/* Default version symbol. */ +#define VRS_SYM "_version" +#define VRS_KEY "VERSION" + +#ifndef _SIZE_T_DECLARED +typedef __size_t size_t; +#define _SIZE_T_DECLARED +#endif + +#ifndef _SSIZE_T_DECLARED +typedef __ssize_t ssize_t; +#define _SSIZE_T_DECLARED +#endif + +typedef struct __kvm kvm_t; + +struct kinfo_proc; +struct proc; + +struct kvm_swap { + char ksw_devname[32]; + int ksw_used; + int ksw_total; + int ksw_flags; + int ksw_reserved1; + int ksw_reserved2; +}; + +#define SWIF_DEV_PREFIX 0x0002 + +__BEGIN_DECLS +int kvm_close(kvm_t *); +int kvm_dpcpu_setcpu(kvm_t *, unsigned int); +char **kvm_getargv(kvm_t *, const struct kinfo_proc *, int); +int kvm_getcptime(kvm_t *, long *); +char **kvm_getenvv(kvm_t *, const struct kinfo_proc *, int); +char *kvm_geterr(kvm_t *); +char *kvm_getfiles(kvm_t *, int, int, int *); +int kvm_getloadavg(kvm_t *, double [], int); +int kvm_getmaxcpu(kvm_t *); +void *kvm_getpcpu(kvm_t *, int); +struct kinfo_proc * + kvm_getprocs(kvm_t *, int, int, int *); +int kvm_getswapinfo(kvm_t *, struct kvm_swap *, int, int); +int kvm_nlist(kvm_t *, struct nlist *); +kvm_t *kvm_open + (const char *, const char *, const char *, int, const char *); +kvm_t *kvm_openfiles + (const char *, const char *, const char *, int, char *); +ssize_t kvm_read(kvm_t *, unsigned long, void *, size_t); +ssize_t kvm_uread + (kvm_t *, const struct kinfo_proc *, unsigned long, char *, size_t); +ssize_t kvm_write(kvm_t *, unsigned long, const void *, size_t); +__END_DECLS + +#endif /* !_KVM_H_ */ diff --git a/lib/libkvm/kvm_amd64.c b/lib/libkvm/kvm_amd64.c new file mode 100644 index 0000000..65d697c --- /dev/null +++ b/lib/libkvm/kvm_amd64.c @@ -0,0 +1,357 @@ +/*- + * Copyright (c) 1989, 1992, 1993 + * The Regents of the University of California. All rights reserved. + * + * This code is derived from software developed by the Computer Systems + * Engineering group at Lawrence Berkeley Laboratory under DARPA contract + * BG 91-66 and contributed to Berkeley. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions + * are met: + * 1. Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * 2. Redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in the + * documentation and/or other materials provided with the distribution. + * 4. Neither the name of the University nor the names of its contributors + * may be used to endorse or promote products derived from this software + * without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND + * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + * ARE DISCLAIMED. IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE + * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL + * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS + * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) + * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT + * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY + * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF + * SUCH DAMAGE. + */ + +#include <sys/cdefs.h> +__FBSDID("$FreeBSD$"); + +#if defined(LIBC_SCCS) && !defined(lint) +#if 0 +static char sccsid[] = "@(#)kvm_hp300.c 8.1 (Berkeley) 6/4/93"; +#endif +#endif /* LIBC_SCCS and not lint */ + +/* + * AMD64 machine dependent routines for kvm. Hopefully, the forthcoming + * vm code will one day obsolete this module. + */ + +#include <sys/param.h> +#include <sys/user.h> +#include <sys/proc.h> +#include <sys/stat.h> +#include <sys/mman.h> +#include <stdlib.h> +#include <string.h> +#include <unistd.h> +#include <nlist.h> +#include <kvm.h> + +#include <vm/vm.h> +#include <vm/vm_param.h> + +#include <machine/elf.h> + +#include <limits.h> + +#include "kvm_private.h" + +#ifndef btop +#define btop(x) (amd64_btop(x)) +#define ptob(x) (amd64_ptob(x)) +#endif + +/* minidump must be the first item! */ +struct vmstate { + int minidump; /* 1 = minidump mode */ + void *mmapbase; + size_t mmapsize; + pml4_entry_t *PML4; +}; + +/* + * Map the ELF headers into the process' address space. We do this in two + * steps: first the ELF header itself and using that information the whole + * set of headers. (Taken from kvm_ia64.c) + */ +static int +_kvm_maphdrs(kvm_t *kd, size_t sz) +{ + struct vmstate *vm = kd->vmst; + + /* munmap() previous mmap(). */ + if (vm->mmapbase != NULL) { + munmap(vm->mmapbase, vm->mmapsize); + vm->mmapbase = NULL; + } + + vm->mmapsize = sz; + vm->mmapbase = mmap(NULL, sz, PROT_READ, MAP_PRIVATE, kd->pmfd, 0); + if (vm->mmapbase == MAP_FAILED) { + _kvm_err(kd, kd->program, "cannot mmap corefile"); + return (-1); + } + return (0); +} + +/* + * Translate a physical memory address to a file-offset in the crash-dump. + * (Taken from kvm_ia64.c) + */ +static size_t +_kvm_pa2off(kvm_t *kd, uint64_t pa, off_t *ofs) +{ + Elf_Ehdr *e = kd->vmst->mmapbase; + Elf_Phdr *p; + int n; + + if (kd->rawdump) { + *ofs = pa; + return (PAGE_SIZE - ((size_t)pa & PAGE_MASK)); + } + + p = (Elf_Phdr*)((char*)e + e->e_phoff); + n = e->e_phnum; + while (n && (pa < p->p_paddr || pa >= p->p_paddr + p->p_memsz)) + p++, n--; + if (n == 0) + return (0); + *ofs = (pa - p->p_paddr) + p->p_offset; + return (PAGE_SIZE - ((size_t)pa & PAGE_MASK)); +} + +void +_kvm_freevtop(kvm_t *kd) +{ + struct vmstate *vm = kd->vmst; + + if (kd->vmst->minidump) + return (_kvm_minidump_freevtop(kd)); + if (vm->mmapbase != NULL) + munmap(vm->mmapbase, vm->mmapsize); + if (vm->PML4) + free(vm->PML4); + free(vm); + kd->vmst = NULL; +} + +int +_kvm_initvtop(kvm_t *kd) +{ + struct nlist nl[2]; + u_long pa; + u_long kernbase; + pml4_entry_t *PML4; + Elf_Ehdr *ehdr; + size_t hdrsz; + char minihdr[8]; + + if (!kd->rawdump && pread(kd->pmfd, &minihdr, 8, 0) == 8) + if (memcmp(&minihdr, "minidump", 8) == 0) + return (_kvm_minidump_initvtop(kd)); + + kd->vmst = (struct vmstate *)_kvm_malloc(kd, sizeof(*kd->vmst)); + if (kd->vmst == 0) { + _kvm_err(kd, kd->program, "cannot allocate vm"); + return (-1); + } + kd->vmst->PML4 = 0; + + if (kd->rawdump == 0) { + if (_kvm_maphdrs(kd, sizeof(Elf_Ehdr)) == -1) + return (-1); + + ehdr = kd->vmst->mmapbase; + hdrsz = ehdr->e_phoff + ehdr->e_phentsize * ehdr->e_phnum; + if (_kvm_maphdrs(kd, hdrsz) == -1) + return (-1); + } + + nl[0].n_name = "kernbase"; + nl[1].n_name = 0; + + if (kvm_nlist(kd, nl) != 0) { + _kvm_err(kd, kd->program, "bad namelist - no kernbase"); + return (-1); + } + kernbase = nl[0].n_value; + + nl[0].n_name = "KPML4phys"; + nl[1].n_name = 0; + + if (kvm_nlist(kd, nl) != 0) { + _kvm_err(kd, kd->program, "bad namelist - no KPML4phys"); + return (-1); + } + if (kvm_read(kd, (nl[0].n_value - kernbase), &pa, sizeof(pa)) != + sizeof(pa)) { + _kvm_err(kd, kd->program, "cannot read KPML4phys"); + return (-1); + } + PML4 = _kvm_malloc(kd, PAGE_SIZE); + if (kvm_read(kd, pa, PML4, PAGE_SIZE) != PAGE_SIZE) { + _kvm_err(kd, kd->program, "cannot read KPML4phys"); + return (-1); + } + kd->vmst->PML4 = PML4; + return (0); +} + +static int +_kvm_vatop(kvm_t *kd, u_long va, off_t *pa) +{ + struct vmstate *vm; + u_long offset; + u_long pdpe_pa; + u_long pde_pa; + u_long pte_pa; + pml4_entry_t pml4e; + pdp_entry_t pdpe; + pd_entry_t pde; + pt_entry_t pte; + u_long pml4eindex; + u_long pdpeindex; + u_long pdeindex; + u_long pteindex; + u_long a; + off_t ofs; + size_t s; + + vm = kd->vmst; + offset = va & (PAGE_SIZE - 1); + + /* + * If we are initializing (kernel page table descriptor pointer + * not yet set) then return pa == va to avoid infinite recursion. + */ + if (vm->PML4 == 0) { + s = _kvm_pa2off(kd, va, pa); + if (s == 0) { + _kvm_err(kd, kd->program, + "_kvm_vatop: bootstrap data not in dump"); + goto invalid; + } else + return (PAGE_SIZE - offset); + } + + pml4eindex = (va >> PML4SHIFT) & (NPML4EPG - 1); + pml4e = vm->PML4[pml4eindex]; + if (((u_long)pml4e & PG_V) == 0) { + _kvm_err(kd, kd->program, "_kvm_vatop: pml4e not valid"); + goto invalid; + } + + pdpeindex = (va >> PDPSHIFT) & (NPDPEPG-1); + pdpe_pa = ((u_long)pml4e & PG_FRAME) + + (pdpeindex * sizeof(pdp_entry_t)); + + s = _kvm_pa2off(kd, pdpe_pa, &ofs); + if (s < sizeof pdpe) { + _kvm_err(kd, kd->program, "_kvm_vatop: pdpe_pa not found"); + goto invalid; + } + if (lseek(kd->pmfd, ofs, 0) == -1) { + _kvm_syserr(kd, kd->program, "_kvm_vatop: lseek pdpe_pa"); + goto invalid; + } + if (read(kd->pmfd, &pdpe, sizeof pdpe) != sizeof pdpe) { + _kvm_syserr(kd, kd->program, "_kvm_vatop: read pdpe"); + goto invalid; + } + if (((u_long)pdpe & PG_V) == 0) { + _kvm_err(kd, kd->program, "_kvm_vatop: pdpe not valid"); + goto invalid; + } + + pdeindex = (va >> PDRSHIFT) & (NPDEPG-1); + pde_pa = ((u_long)pdpe & PG_FRAME) + (pdeindex * sizeof(pd_entry_t)); + + s = _kvm_pa2off(kd, pde_pa, &ofs); + if (s < sizeof pde) { + _kvm_syserr(kd, kd->program, "_kvm_vatop: pde_pa not found"); + goto invalid; + } + if (lseek(kd->pmfd, ofs, 0) == -1) { + _kvm_err(kd, kd->program, "_kvm_vatop: lseek pde_pa"); + goto invalid; + } + if (read(kd->pmfd, &pde, sizeof pde) != sizeof pde) { + _kvm_syserr(kd, kd->program, "_kvm_vatop: read pde"); + goto invalid; + } + if (((u_long)pde & PG_V) == 0) { + _kvm_err(kd, kd->program, "_kvm_vatop: pde not valid"); + goto invalid; + } + + if ((u_long)pde & PG_PS) { + /* + * No final-level page table; ptd describes one 2MB page. + */ +#define PAGE2M_MASK (NBPDR - 1) +#define PG_FRAME2M (~PAGE2M_MASK) + a = ((u_long)pde & PG_FRAME2M) + (va & PAGE2M_MASK); + s = _kvm_pa2off(kd, a, pa); + if (s == 0) { + _kvm_err(kd, kd->program, + "_kvm_vatop: 2MB page address not in dump"); + goto invalid; + } else + return (NBPDR - (va & PAGE2M_MASK)); + } + + pteindex = (va >> PAGE_SHIFT) & (NPTEPG-1); + pte_pa = ((u_long)pde & PG_FRAME) + (pteindex * sizeof(pt_entry_t)); + + s = _kvm_pa2off(kd, pte_pa, &ofs); + if (s < sizeof pte) { + _kvm_err(kd, kd->program, "_kvm_vatop: pte_pa not found"); + goto invalid; + } + if (lseek(kd->pmfd, ofs, 0) == -1) { + _kvm_syserr(kd, kd->program, "_kvm_vatop: lseek"); + goto invalid; + } + if (read(kd->pmfd, &pte, sizeof pte) != sizeof pte) { + _kvm_syserr(kd, kd->program, "_kvm_vatop: read"); + goto invalid; + } + if (((u_long)pte & PG_V) == 0) { + _kvm_err(kd, kd->program, "_kvm_vatop: pte not valid"); + goto invalid; + } + + a = ((u_long)pte & PG_FRAME) + offset; + s = _kvm_pa2off(kd, a, pa); + if (s == 0) { + _kvm_err(kd, kd->program, "_kvm_vatop: address not in dump"); + goto invalid; + } else + return (PAGE_SIZE - offset); + +invalid: + _kvm_err(kd, 0, "invalid address (0x%lx)", va); + return (0); +} + +int +_kvm_kvatop(kvm_t *kd, u_long va, off_t *pa) +{ + + if (kd->vmst->minidump) + return (_kvm_minidump_kvatop(kd, va, pa)); + if (ISALIVE(kd)) { + _kvm_err(kd, 0, "kvm_kvatop called in live kernel!"); + return (0); + } + return (_kvm_vatop(kd, va, pa)); +} diff --git a/lib/libkvm/kvm_arm.c b/lib/libkvm/kvm_arm.c new file mode 100644 index 0000000..b1274e9 --- /dev/null +++ b/lib/libkvm/kvm_arm.c @@ -0,0 +1,266 @@ +/*- + * Copyright (c) 2005 Olivier Houchard + * Copyright (c) 1989, 1992, 1993 + * The Regents of the University of California. All rights reserved. + * + * This code is derived from software developed by the Computer Systems + * Engineering group at Lawrence Berkeley Laboratory under DARPA contract + * BG 91-66 and contributed to Berkeley. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions + * are met: + * 1. Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * 2. Redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in the + * documentation and/or other materials provided with the distribution. + * 4. Neither the name of the University nor the names of its contributors + * may be used to endorse or promote products derived from this software + * without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY TOOLS GMBH ``AS IS'' AND ANY EXPRESS OR + * IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES + * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. + * IN NO EVENT SHALL TOOLS GMBH BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, + * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, + * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; + * OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, + * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR + * OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF + * ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + */ + +/* + * ARM machine dependent routines for kvm. + */ + +#include <sys/cdefs.h> +__FBSDID("$FreeBSD$"); + +#include <sys/param.h> +#include <sys/elf32.h> +#include <sys/mman.h> + +#include <vm/vm.h> +#include <vm/vm_param.h> +#include <vm/pmap.h> + +#include <machine/pmap.h> + +#include <db.h> +#include <limits.h> +#include <kvm.h> +#include <stdlib.h> +#include <string.h> +#include <unistd.h> + +#include "kvm_private.h" + +/* minidump must be the first item! */ +struct vmstate { + int minidump; /* 1 = minidump mode */ + pd_entry_t *l1pt; + void *mmapbase; + size_t mmapsize; +}; + +static int +_kvm_maphdrs(kvm_t *kd, size_t sz) +{ + struct vmstate *vm = kd->vmst; + + /* munmap() previous mmap(). */ + if (vm->mmapbase != NULL) { + munmap(vm->mmapbase, vm->mmapsize); + vm->mmapbase = NULL; + } + + vm->mmapsize = sz; + vm->mmapbase = mmap(NULL, sz, PROT_READ, MAP_PRIVATE, kd->pmfd, 0); + if (vm->mmapbase == MAP_FAILED) { + _kvm_err(kd, kd->program, "cannot mmap corefile"); + return (-1); + } + + return (0); +} + +/* + * Translate a physical memory address to a file-offset in the crash-dump. + */ +static size_t +_kvm_pa2off(kvm_t *kd, uint64_t pa, off_t *ofs, size_t pgsz) +{ + Elf32_Ehdr *e = kd->vmst->mmapbase; + Elf32_Phdr *p = (Elf32_Phdr*)((char*)e + e->e_phoff); + int n = e->e_phnum; + + while (n && (pa < p->p_paddr || pa >= p->p_paddr + p->p_memsz)) + p++, n--; + if (n == 0) + return (0); + + *ofs = (pa - p->p_paddr) + p->p_offset; + if (pgsz == 0) + return (p->p_memsz - (pa - p->p_paddr)); + return (pgsz - ((size_t)pa & (pgsz - 1))); +} + +void +_kvm_freevtop(kvm_t *kd) +{ + if (kd->vmst != 0) { + if (kd->vmst->minidump) + return (_kvm_minidump_freevtop(kd)); + if (kd->vmst->mmapbase != NULL) + munmap(kd->vmst->mmapbase, kd->vmst->mmapsize); + free(kd->vmst); + kd->vmst = NULL; + } +} + +int +_kvm_initvtop(kvm_t *kd) +{ + struct vmstate *vm; + struct nlist nl[2]; + u_long kernbase, physaddr, pa; + pd_entry_t *l1pt; + Elf32_Ehdr *ehdr; + size_t hdrsz; + char minihdr[8]; + + if (!kd->rawdump) { + if (pread(kd->pmfd, &minihdr, 8, 0) == 8) { + if (memcmp(&minihdr, "minidump", 8) == 0) + return (_kvm_minidump_initvtop(kd)); + } else { + _kvm_err(kd, kd->program, "cannot read header"); + return (-1); + } + } + + vm = _kvm_malloc(kd, sizeof(*vm)); + if (vm == 0) { + _kvm_err(kd, kd->program, "cannot allocate vm"); + return (-1); + } + kd->vmst = vm; + vm->l1pt = NULL; + if (_kvm_maphdrs(kd, sizeof(Elf32_Ehdr)) == -1) + return (-1); + ehdr = kd->vmst->mmapbase; + hdrsz = ehdr->e_phoff + ehdr->e_phentsize * ehdr->e_phnum; + if (_kvm_maphdrs(kd, hdrsz) == -1) + return (-1); + nl[0].n_name = "kernbase"; + nl[1].n_name = NULL; + if (kvm_nlist(kd, nl) != 0) + kernbase = KERNBASE; + else + kernbase = nl[0].n_value; + + nl[0].n_name = "physaddr"; + if (kvm_nlist(kd, nl) != 0) { + _kvm_err(kd, kd->program, "couldn't get phys addr"); + return (-1); + } + physaddr = nl[0].n_value; + nl[0].n_name = "kernel_l1pa"; + if (kvm_nlist(kd, nl) != 0) { + _kvm_err(kd, kd->program, "bad namelist"); + return (-1); + } + if (kvm_read(kd, (nl[0].n_value - kernbase + physaddr), &pa, + sizeof(pa)) != sizeof(pa)) { + _kvm_err(kd, kd->program, "cannot read kernel_l1pa"); + return (-1); + } + l1pt = _kvm_malloc(kd, L1_TABLE_SIZE); + if (kvm_read(kd, pa, l1pt, L1_TABLE_SIZE) != L1_TABLE_SIZE) { + _kvm_err(kd, kd->program, "cannot read l1pt"); + free(l1pt); + return (-1); + } + vm->l1pt = l1pt; + return 0; +} + +/* from arm/pmap.c */ +#define L1_IDX(va) (((vm_offset_t)(va)) >> L1_S_SHIFT) +/* from arm/pmap.h */ +#define L1_TYPE_INV 0x00 /* Invalid (fault) */ +#define L1_TYPE_C 0x01 /* Coarse L2 */ +#define L1_TYPE_S 0x02 /* Section */ +#define L1_TYPE_F 0x03 /* Fine L2 */ +#define L1_TYPE_MASK 0x03 /* mask of type bits */ + +#define l1pte_section_p(pde) (((pde) & L1_TYPE_MASK) == L1_TYPE_S) +#define l1pte_valid(pde) ((pde) != 0) +#define l2pte_valid(pte) ((pte) != 0) +#define l2pte_index(v) (((v) & L2_ADDR_BITS) >> L2_S_SHIFT) + + +int +_kvm_kvatop(kvm_t *kd, u_long va, off_t *pa) +{ + struct vmstate *vm = kd->vmst; + pd_entry_t pd; + pt_entry_t pte; + u_long pte_pa; + + if (kd->vmst->minidump) + return (_kvm_minidump_kvatop(kd, va, pa)); + + if (vm->l1pt == NULL) + return (_kvm_pa2off(kd, va, pa, PAGE_SIZE)); + pd = vm->l1pt[L1_IDX(va)]; + if (!l1pte_valid(pd)) + goto invalid; + if (l1pte_section_p(pd)) { + /* 1MB section mapping. */ + *pa = ((u_long)pd & L1_S_ADDR_MASK) + (va & L1_S_OFFSET); + return (_kvm_pa2off(kd, *pa, pa, L1_S_SIZE)); + } + pte_pa = (pd & L1_ADDR_MASK) + l2pte_index(va) * sizeof(pte); + _kvm_pa2off(kd, pte_pa, (off_t *)&pte_pa, L1_S_SIZE); + if (lseek(kd->pmfd, pte_pa, 0) == -1) { + _kvm_syserr(kd, kd->program, "_kvm_kvatop: lseek"); + goto invalid; + } + if (read(kd->pmfd, &pte, sizeof(pte)) != sizeof (pte)) { + _kvm_syserr(kd, kd->program, "_kvm_kvatop: read"); + goto invalid; + } + if (!l2pte_valid(pte)) { + goto invalid; + } + if ((pte & L2_TYPE_MASK) == L2_TYPE_L) { + *pa = (pte & L2_L_FRAME) | (va & L2_L_OFFSET); + return (_kvm_pa2off(kd, *pa, pa, L2_L_SIZE)); + } + *pa = (pte & L2_S_FRAME) | (va & L2_S_OFFSET); + return (_kvm_pa2off(kd, *pa, pa, PAGE_SIZE)); +invalid: + _kvm_err(kd, 0, "Invalid address (%lx)", va); + return 0; +} + +/* + * Machine-dependent initialization for ALL open kvm descriptors, + * not just those for a kernel crash dump. Some architectures + * have to deal with these NOT being constants! (i.e. m68k) + */ +#ifdef FBSD_NOT_YET +int +_kvm_mdopen(kvm_t *kd) +{ + + kd->usrstack = USRSTACK; + kd->min_uva = VM_MIN_ADDRESS; + kd->max_uva = VM_MAXUSER_ADDRESS; + + return (0); +} +#endif diff --git a/lib/libkvm/kvm_cptime.c b/lib/libkvm/kvm_cptime.c new file mode 100644 index 0000000..08f3fca --- /dev/null +++ b/lib/libkvm/kvm_cptime.c @@ -0,0 +1,134 @@ +/*- + * Copyright (c) 2008 Yahoo!, Inc. + * All rights reserved. + * Written by: John Baldwin <jhb@FreeBSD.org> + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions + * are met: + * 1. Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * 2. Redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in the + * documentation and/or other materials provided with the distribution. + * 3. Neither the name of the author nor the names of any co-contributors + * may be used to endorse or promote products derived from this software + * without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE AUTHOR AND CONTRIBUTORS ``AS IS'' AND + * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + * ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE + * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL + * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS + * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) + * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT + * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY + * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF + * SUCH DAMAGE. + */ + +#include <sys/cdefs.h> +__FBSDID("$FreeBSD$"); + +#include <sys/param.h> +#include <sys/pcpu.h> +#include <sys/resource.h> +#include <sys/sysctl.h> +#include <errno.h> +#include <kvm.h> +#include <limits.h> +#include <stdlib.h> +#include <string.h> + +#include "kvm_private.h" + +static struct nlist kvm_cp_time_nl[] = { + { .n_name = "_cp_time" }, /* (deprecated) */ + { .n_name = NULL }, +}; + +#define NL_CP_TIME 0 + +static int kvm_cp_time_cached; + +static int +_kvm_cp_time_init(kvm_t *kd) +{ + + if (kvm_nlist(kd, kvm_cp_time_nl) < 0) + return (-1); + kvm_cp_time_cached = 1; + return (0); +} + +static int +getsysctl(kvm_t *kd, const char *name, void *buf, size_t len) +{ + size_t nlen; + + nlen = len; + if (sysctlbyname(name, buf, &nlen, NULL, 0) < 0) { + _kvm_err(kd, kd->program, "cannot read sysctl %s:%s", name, + strerror(errno)); + return (-1); + } + if (nlen != len) { + _kvm_err(kd, kd->program, "sysctl %s has unexpected size", + name); + return (-1); + } + return (0); +} + +int +kvm_getcptime(kvm_t *kd, long *cp_time) +{ + struct pcpu *pc; + int i, j, maxcpu; + + if (kd == NULL) { + kvm_cp_time_cached = 0; + return (0); + } + + if (ISALIVE(kd)) + return (getsysctl(kd, "kern.cp_time", cp_time, sizeof(long) * + CPUSTATES)); + + if (kvm_cp_time_cached == 0) { + if (_kvm_cp_time_init(kd) < 0) + return (-1); + } + + /* If this kernel has a "cp_time[]" symbol, then just read that. */ + if (kvm_cp_time_nl[NL_CP_TIME].n_value != 0) { + if (kvm_read(kd, kvm_cp_time_nl[NL_CP_TIME].n_value, cp_time, + sizeof(long) * CPUSTATES) != sizeof(long) * CPUSTATES) { + _kvm_err(kd, kd->program, "cannot read cp_time array"); + return (-1); + } + return (0); + } + + /* + * If we don't have that symbol, then we have to simulate + * "cp_time[]" by adding up the individual times for each CPU. + */ + maxcpu = kvm_getmaxcpu(kd); + if (maxcpu < 0) + return (-1); + for (i = 0; i < CPUSTATES; i++) + cp_time[i] = 0; + for (i = 0; i < maxcpu; i++) { + pc = kvm_getpcpu(kd, i); + if (pc == NULL) + continue; + if (pc == (void *)-1) + return (-1); + for (j = 0; j < CPUSTATES; j++) + cp_time[j] += pc->pc_cp_time[j]; + free(pc); + } + return (0); +} diff --git a/lib/libkvm/kvm_file.c b/lib/libkvm/kvm_file.c new file mode 100644 index 0000000..863a9fa --- /dev/null +++ b/lib/libkvm/kvm_file.c @@ -0,0 +1,226 @@ +/*- + * Copyright (c) 1989, 1992, 1993 + * The Regents of the University of California. All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions + * are met: + * 1. Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * 2. Redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in the + * documentation and/or other materials provided with the distribution. + * 4. Neither the name of the University nor the names of its contributors + * may be used to endorse or promote products derived from this software + * without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND + * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + * ARE DISCLAIMED. IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE + * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL + * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS + * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) + * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT + * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY + * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF + * SUCH DAMAGE. + */ + +#include <sys/cdefs.h> +__FBSDID("$FreeBSD$"); + +#if defined(LIBC_SCCS) && !defined(lint) +#if 0 +static char sccsid[] = "@(#)kvm_file.c 8.1 (Berkeley) 6/4/93"; +#endif +#endif /* LIBC_SCCS and not lint */ + +/* + * File list interface for kvm. pstat, fstat and netstat are + * users of this code, so we've factored it out into a separate module. + * Thus, we keep this grunge out of the other kvm applications (i.e., + * most other applications are interested only in open/close/read/nlist). + */ + +#include <sys/param.h> +#include <sys/user.h> +#include <sys/proc.h> +#define _WANT_FILE /* make file.h give us 'struct file' */ +#include <sys/file.h> +#include <sys/stat.h> +#include <sys/ioctl.h> +#include <nlist.h> +#include <kvm.h> + +#include <vm/vm.h> +#include <vm/vm_param.h> + +#include <sys/sysctl.h> + +#include <limits.h> +#include <ndbm.h> +#include <paths.h> +#include <stdlib.h> + +#include "kvm_private.h" + +#define KREAD(kd, addr, obj) \ + (kvm_read(kd, addr, obj, sizeof(*obj)) != sizeof(*obj)) + +#define KREADN(kd, addr, obj, cnt) \ + (kvm_read(kd, addr, obj, (cnt)) != (ssize_t)(cnt)) + +/* + * Get file structures. + */ +static int +kvm_deadfiles(kvm_t *kd, int op __unused, int arg __unused, long allproc_o, + int nprocs __unused) +{ + struct proc proc; + struct filedesc filed; + int buflen = kd->arglen, ocnt = 0, n = 0, once = 0, i; + struct file **ofiles; + struct file *fp; + struct proc *p; + char *where = kd->argspc; + + if (buflen < (int)(sizeof(struct file *) + sizeof(struct file))) + return (0); + if (KREAD(kd, allproc_o, &p)) { + _kvm_err(kd, kd->program, "cannot read allproc"); + return (0); + } + for (; p != NULL; p = LIST_NEXT(&proc, p_list)) { + if (KREAD(kd, (u_long)p, &proc)) { + _kvm_err(kd, kd->program, "can't read proc at %p", p); + goto fail; + } + if (proc.p_state == PRS_NEW) + continue; + if (proc.p_fd == NULL) + continue; + if (KREAD(kd, (u_long)p->p_fd, &filed)) { + _kvm_err(kd, kd->program, "can't read filedesc at %p", + p->p_fd); + goto fail; + } + if (filed.fd_lastfile + 1 > ocnt) { + ocnt = filed.fd_lastfile + 1; + free(ofiles); + ofiles = (struct file **)_kvm_malloc(kd, + ocnt * sizeof(struct file *)); + if (ofiles == 0) + return (0); + } + if (KREADN(kd, (u_long)filed.fd_ofiles, ofiles, + ocnt * sizeof(struct file *))) { + _kvm_err(kd, kd->program, "can't read ofiles at %p", + filed.fd_ofiles); + return (0); + } + for (i = 0; i <= filed.fd_lastfile; i++) { + if ((fp = ofiles[i]) == NULL) + continue; + /* + * copyout filehead (legacy) + */ + if (!once) { + *(struct file **)kd->argspc = fp; + *(struct file **)where = fp; + buflen -= sizeof (fp); + where += sizeof (fp); + once = 1; + } + if (buflen < (int)sizeof(struct file)) + goto fail; + if (KREAD(kd, (long)fp, ((struct file *)where))) { + _kvm_err(kd, kd->program, "can't read kfp"); + goto fail; + } + buflen -= sizeof (struct file); + fp = (struct file *)where; + where += sizeof (struct file); + n++; + } + } + free(ofiles); + return (n); +fail: + free(ofiles); + return (0); + +} + +char * +kvm_getfiles(kvm_t *kd, int op, int arg, int *cnt) +{ + int mib[2], st, n, nfiles, nprocs; + size_t size; + + _kvm_syserr(kd, kd->program, "kvm_getfiles has been broken for years"); + return (0); + if (ISALIVE(kd)) { + size = 0; + mib[0] = CTL_KERN; + mib[1] = KERN_FILE; + st = sysctl(mib, 2, NULL, &size, NULL, 0); + if (st == -1) { + _kvm_syserr(kd, kd->program, "kvm_getfiles"); + return (0); + } + if (kd->argspc == 0) + kd->argspc = (char *)_kvm_malloc(kd, size); + else if (kd->arglen < (int)size) + kd->argspc = (char *)_kvm_realloc(kd, kd->argspc, size); + if (kd->argspc == 0) + return (0); + kd->arglen = size; + st = sysctl(mib, 2, kd->argspc, &size, NULL, 0); + if (st != 0) { + _kvm_syserr(kd, kd->program, "kvm_getfiles"); + return (0); + } + nfiles = size / sizeof(struct xfile); + } else { + struct nlist nl[4], *p; + + nl[0].n_name = "_allproc"; + nl[1].n_name = "_nprocs"; + nl[2].n_name = "_nfiles"; + nl[3].n_name = 0; + + if (kvm_nlist(kd, nl) != 0) { + for (p = nl; p->n_type != 0; ++p) + ; + _kvm_err(kd, kd->program, + "%s: no such symbol", p->n_name); + return (0); + } + if (KREAD(kd, nl[1].n_value, &nprocs)) { + _kvm_err(kd, kd->program, "can't read nprocs"); + return (0); + } + if (KREAD(kd, nl[2].n_value, &nfiles)) { + _kvm_err(kd, kd->program, "can't read nfiles"); + return (0); + } + size = sizeof(void *) + (nfiles + 10) * sizeof(struct file); + if (kd->argspc == 0) + kd->argspc = (char *)_kvm_malloc(kd, size); + else if (kd->arglen < (int)size) + kd->argspc = (char *)_kvm_realloc(kd, kd->argspc, size); + if (kd->argspc == 0) + return (0); + kd->arglen = size; + n = kvm_deadfiles(kd, op, arg, nl[0].n_value, nprocs); + if (n != nfiles) { + _kvm_err(kd, kd->program, "inconsistant nfiles"); + return (0); + } + nfiles = n; + } + *cnt = nfiles; + return (kd->argspc); +} diff --git a/lib/libkvm/kvm_getcptime.3 b/lib/libkvm/kvm_getcptime.3 new file mode 100644 index 0000000..2ddc272 --- /dev/null +++ b/lib/libkvm/kvm_getcptime.3 @@ -0,0 +1,77 @@ +.\" Copyright (c) 2008 Yahoo!, Inc. +.\" All rights reserved. +.\" Written by: John Baldwin <jhb@FreeBSD.org> +.\" +.\" Redistribution and use in source and binary forms, with or without +.\" modification, are permitted provided that the following conditions +.\" are met: +.\" 1. Redistributions of source code must retain the above copyright +.\" notice, this list of conditions and the following disclaimer. +.\" 2. Redistributions in binary form must reproduce the above copyright +.\" notice, this list of conditions and the following disclaimer in the +.\" documentation and/or other materials provided with the distribution. +.\" 3. Neither the name of the author nor the names of any co-contributors +.\" may be used to endorse or promote products derived from this software +.\" without specific prior written permission. +.\" +.\" THIS SOFTWARE IS PROVIDED BY THE AUTHOR AND CONTRIBUTORS ``AS IS'' AND +.\" ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE +.\" IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE +.\" ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE +.\" FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL +.\" DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS +.\" OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) +.\" HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT +.\" LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY +.\" OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF +.\" SUCH DAMAGE. +.\" +.\" $FreeBSD$ +.\" +.Dd August 19, 2008 +.Dt KVM_GETCPTIME 3 +.Os +.Sh NAME +.Nm kvm_getcptime +.Nd fetch global CPU time statistics +.Sh LIBRARY +.Lb libkvm +.Sh SYNOPSIS +.In sys/param.h +.In sys/resource.h +.In sys/sysctl.h +.In kvm.h +.Ft int +.Fn kvm_getcptime "kvm_t *kd" "long *cp_time" +.Sh DESCRIPTION +The +.Fn kvm_getcptime +function stores the global CPU time statistics from the kernel +.Fa kd +in the array of counters pointed to by +.Fa cp_time . +Note that +.Fa cp_time +should point to an array of +.Dv CPUSTATES +long integers. +The format of the counters is identical to that output by the +.Va kern.cp_time +sysctl. +.Sh CACHING +This function caches the nlist values for various kernel variables which it +reuses in successive calls. +You may call the function with +.Fa kd +set to +.Dv NULL +to clear this cache. +.Sh RETURN VALUES +The +.Nm kvm_getcptime +function returns 0 on success and -1 on failure. +If an error occurs, +then an error message may be retrieved via +.Xr kvm_geterr 3 . +.Sh SEE ALSO +.Xr kvm 3 diff --git a/lib/libkvm/kvm_geterr.3 b/lib/libkvm/kvm_geterr.3 new file mode 100644 index 0000000..3ce5c72 --- /dev/null +++ b/lib/libkvm/kvm_geterr.3 @@ -0,0 +1,78 @@ +.\" Copyright (c) 1992, 1993 +.\" The Regents of the University of California. All rights reserved. +.\" +.\" This code is derived from software developed by the Computer Systems +.\" Engineering group at Lawrence Berkeley Laboratory under DARPA contract +.\" BG 91-66 and contributed to Berkeley. +.\" +.\" Redistribution and use in source and binary forms, with or without +.\" modification, are permitted provided that the following conditions +.\" are met: +.\" 1. Redistributions of source code must retain the above copyright +.\" notice, this list of conditions and the following disclaimer. +.\" 2. Redistributions in binary form must reproduce the above copyright +.\" notice, this list of conditions and the following disclaimer in the +.\" documentation and/or other materials provided with the distribution. +.\" 4. Neither the name of the University nor the names of its contributors +.\" may be used to endorse or promote products derived from this software +.\" without specific prior written permission. +.\" +.\" THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND +.\" ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE +.\" IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE +.\" ARE DISCLAIMED. IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE +.\" FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL +.\" DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS +.\" OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) +.\" HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT +.\" LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY +.\" OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF +.\" SUCH DAMAGE. +.\" +.\" @(#)kvm_geterr.3 8.1 (Berkeley) 6/4/93 +.\" $FreeBSD$ +.\" +.Dd June 4, 1993 +.Dt KVM_GETERR 3 +.Os +.Sh NAME +.Nm kvm_geterr +.Nd get error message on kvm descriptor +.Sh LIBRARY +.Lb libkvm +.Sh SYNOPSIS +.In kvm.h +.Ft char * +.Fn kvm_geterr "kvm_t *kd" +.Sh DESCRIPTION +This function returns a string describing the most recent error condition +on the descriptor +.Fa kd . +The results are undefined if the most recent +.Xr kvm 3 +library call did not produce an error. +The string returned is stored in memory owned by +.Xr kvm 3 +so the message should be copied out and saved elsewhere if necessary. +.Sh SEE ALSO +.Xr kvm 3 , +.Xr kvm_close 3 , +.Xr kvm_getargv 3 , +.Xr kvm_getenvv 3 , +.Xr kvm_getprocs 3 , +.Xr kvm_nlist 3 , +.Xr kvm_open 3 , +.Xr kvm_openfiles 3 , +.Xr kvm_read 3 , +.Xr kvm_write 3 +.Sh BUGS +This routine cannot be used to access error conditions due to a failed +.Fn kvm_openfiles +call, since failure is indicated by returning a +.Dv NULL +descriptor. +Therefore, errors on open are output to the special error buffer +passed to +.Fn kvm_openfiles . +This option is not available to +.Fn kvm_open . diff --git a/lib/libkvm/kvm_getfiles.3 b/lib/libkvm/kvm_getfiles.3 new file mode 100644 index 0000000..22bfd92 --- /dev/null +++ b/lib/libkvm/kvm_getfiles.3 @@ -0,0 +1,87 @@ +.\" Copyright (c) 1992, 1993 +.\" The Regents of the University of California. All rights reserved. +.\" +.\" This code is derived from software developed by the Computer Systems +.\" Engineering group at Lawrence Berkeley Laboratory under DARPA contract +.\" BG 91-66 and contributed to Berkeley. +.\" +.\" Redistribution and use in source and binary forms, with or without +.\" modification, are permitted provided that the following conditions +.\" are met: +.\" 1. Redistributions of source code must retain the above copyright +.\" notice, this list of conditions and the following disclaimer. +.\" 2. Redistributions in binary form must reproduce the above copyright +.\" notice, this list of conditions and the following disclaimer in the +.\" documentation and/or other materials provided with the distribution. +.\" 4. Neither the name of the University nor the names of its contributors +.\" may be used to endorse or promote products derived from this software +.\" without specific prior written permission. +.\" +.\" THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND +.\" ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE +.\" IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE +.\" ARE DISCLAIMED. IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE +.\" FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL +.\" DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS +.\" OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) +.\" HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT +.\" LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY +.\" OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF +.\" SUCH DAMAGE. +.\" +.\" @(#)kvm_getfiles.3 8.2 (Berkeley) 4/19/94 +.\" $FreeBSD$ +.\" +.Dd April 19, 1994 +.Dt KVM_GETFILES 3 +.Os +.Sh NAME +.Nm kvm_getfiles +.Nd survey open files +.Sh LIBRARY +.Lb libkvm +.Sh SYNOPSIS +.In kvm.h +.In sys/types.h +.Fd #define _KERNEL +.In sys/file.h +.Fd #undef _KERNEL +.\" .Fa kvm_t *kd +.Ft char * +.Fn kvm_getfiles "kvm_t *kd" "int op" "int arg" "int *cnt" +.Sh DESCRIPTION +The +.Fn kvm_getfiles +function returns a (sub-)set of the open files in the kernel indicated by +.Fa kd . +The +.Fa op +and +.Fa arg +arguments constitute a predicate which limits the set of files +returned. +No predicates are currently defined. +.Pp +The number of files found is returned in the reference parameter +.Fa cnt . +The files are returned as a contiguous array of file structures, +preceded by the address of the first file entry in the kernel. +This memory is owned by kvm and is not guaranteed to be persistent across +subsequent kvm library calls. +Data should be copied out if it needs to be +saved. +.Sh RETURN VALUES +The +.Fn kvm_getfiles +function will return NULL on failure. +.Sh SEE ALSO +.Xr kvm 3 , +.Xr kvm_close 3 , +.Xr kvm_geterr 3 , +.Xr kvm_nlist 3 , +.Xr kvm_open 3 , +.Xr kvm_openfiles 3 , +.Xr kvm_read 3 , +.Xr kvm_write 3 +.Sh BUGS +This routine does not belong in the kvm interface. diff --git a/lib/libkvm/kvm_getloadavg.3 b/lib/libkvm/kvm_getloadavg.3 new file mode 100644 index 0000000..6587b1a --- /dev/null +++ b/lib/libkvm/kvm_getloadavg.3 @@ -0,0 +1,62 @@ +.\" Copyright (c) 1992, 1993 +.\" The Regents of the University of California. All rights reserved. +.\" +.\" Redistribution and use in source and binary forms, with or without +.\" modification, are permitted provided that the following conditions +.\" are met: +.\" 1. Redistributions of source code must retain the above copyright +.\" notice, this list of conditions and the following disclaimer. +.\" 2. Redistributions in binary form must reproduce the above copyright +.\" notice, this list of conditions and the following disclaimer in the +.\" documentation and/or other materials provided with the distribution. +.\" 4. Neither the name of the University nor the names of its contributors +.\" may be used to endorse or promote products derived from this software +.\" without specific prior written permission. +.\" +.\" THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND +.\" ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE +.\" IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE +.\" ARE DISCLAIMED. IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE +.\" FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL +.\" DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS +.\" OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) +.\" HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT +.\" LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY +.\" OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF +.\" SUCH DAMAGE. +.\" +.\" @(#)kvm_getloadavg.3 8.1 (Berkeley) 6/4/93 +.\" $FreeBSD$ +.\" +.Dd June 4, 1993 +.Dt KVM_GETLOADAVG 3 +.Os +.Sh NAME +.Nm kvm_getloadavg +.Nd get load average of the system +.Sh LIBRARY +.Lb libkvm +.Sh SYNOPSIS +.In kvm.h +.Ft int +.Fn kvm_getloadavg "kvm_t *kd" "double loadavg[]" "int nelem" +.Sh DESCRIPTION +The +.Fn kvm_getloadavg +function returns the number of processes in the system run queue +of the kernel indicated by +.Fa kd , +averaged over various periods of time. +Up to +.Fa nelem +samples are retrieved and assigned to successive elements of +.Fa loadavg Ns Bq . +The system imposes a maximum of 3 samples, representing averages +over the last 1, 5, and 15 minutes, respectively. +.Sh DIAGNOSTICS +If the load average was unobtainable, \-1 is returned; otherwise, +the number of samples actually retrieved is returned. +.Sh SEE ALSO +.Xr uptime 1 , +.Xr getloadavg 3 , +.Xr kvm 3 diff --git a/lib/libkvm/kvm_getloadavg.c b/lib/libkvm/kvm_getloadavg.c new file mode 100644 index 0000000..ecfc321 --- /dev/null +++ b/lib/libkvm/kvm_getloadavg.c @@ -0,0 +1,99 @@ +/*- + * Copyright (c) 1993 + * The Regents of the University of California. All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions + * are met: + * 1. Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * 2. Redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in the + * documentation and/or other materials provided with the distribution. + * 4. Neither the name of the University nor the names of its contributors + * may be used to endorse or promote products derived from this software + * without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND + * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + * ARE DISCLAIMED. IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE + * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL + * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS + * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) + * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT + * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY + * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF + * SUCH DAMAGE. + */ + +#include <sys/cdefs.h> +__FBSDID("$FreeBSD$"); + +#if defined(LIBC_SCCS) && !defined(lint) +#if 0 +static char sccsid[] = "@(#)kvm_getloadavg.c 8.1 (Berkeley) 6/4/93"; +#endif +#endif /* LIBC_SCCS and not lint */ + +#include <sys/param.h> +#include <sys/time.h> +#include <sys/resource.h> + +#include <stdlib.h> +#include <limits.h> +#include <nlist.h> +#include <kvm.h> + +#include "kvm_private.h" + +static struct nlist nl[] = { + { .n_name = "_averunnable" }, +#define X_AVERUNNABLE 0 + { .n_name = "_fscale" }, +#define X_FSCALE 1 + { .n_name = "" }, +}; + +/* + * kvm_getloadavg() -- Get system load averages, from live or dead kernels. + * + * Put `nelem' samples into `loadavg' array. + * Return number of samples retrieved, or -1 on error. + */ +int +kvm_getloadavg(kvm_t *kd, double loadavg[], int nelem) +{ + struct loadavg loadinfo; + struct nlist *p; + int fscale, i; + + if (ISALIVE(kd)) + return (getloadavg(loadavg, nelem)); + + if (kvm_nlist(kd, nl) != 0) { + for (p = nl; p->n_type != 0; ++p); + _kvm_err(kd, kd->program, + "%s: no such symbol", p->n_name); + return (-1); + } + +#define KREAD(kd, addr, obj) \ + (kvm_read(kd, addr, (char *)(obj), sizeof(*obj)) != sizeof(*obj)) + if (KREAD(kd, nl[X_AVERUNNABLE].n_value, &loadinfo)) { + _kvm_err(kd, kd->program, "can't read averunnable"); + return (-1); + } + + /* + * Old kernels have fscale separately; if not found assume + * running new format. + */ + if (!KREAD(kd, nl[X_FSCALE].n_value, &fscale)) + loadinfo.fscale = fscale; + + nelem = MIN(nelem, (int)(sizeof(loadinfo.ldavg) / sizeof(fixpt_t))); + for (i = 0; i < nelem; i++) + loadavg[i] = (double) loadinfo.ldavg[i] / loadinfo.fscale; + return (nelem); +} diff --git a/lib/libkvm/kvm_getpcpu.3 b/lib/libkvm/kvm_getpcpu.3 new file mode 100644 index 0000000..1e0c1f4 --- /dev/null +++ b/lib/libkvm/kvm_getpcpu.3 @@ -0,0 +1,130 @@ +.\" Copyright (c) 2008 Yahoo!, Inc. +.\" All rights reserved. +.\" Written by: John Baldwin <jhb@FreeBSD.org> +.\" +.\" Redistribution and use in source and binary forms, with or without +.\" modification, are permitted provided that the following conditions +.\" are met: +.\" 1. Redistributions of source code must retain the above copyright +.\" notice, this list of conditions and the following disclaimer. +.\" 2. Redistributions in binary form must reproduce the above copyright +.\" notice, this list of conditions and the following disclaimer in the +.\" documentation and/or other materials provided with the distribution. +.\" 3. Neither the name of the author nor the names of any co-contributors +.\" may be used to endorse or promote products derived from this software +.\" without specific prior written permission. +.\" +.\" THIS SOFTWARE IS PROVIDED BY THE AUTHOR AND CONTRIBUTORS ``AS IS'' AND +.\" ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE +.\" IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE +.\" ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE +.\" FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL +.\" DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS +.\" OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) +.\" HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT +.\" LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY +.\" OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF +.\" SUCH DAMAGE. +.\" +.\" $FreeBSD$ +.\" +.Dd February 28, 2010 +.Dt KVM_GETPCPU 3 +.Os +.Sh NAME +.Nm kvm_dpcpu_setcpu +.Nm kvm_getmaxcpu , +.Nm kvm_getpcpu +.Nd access per-CPU data +.Sh LIBRARY +.Lb libkvm +.Sh SYNOPSIS +.In sys/param.h +.In sys/pcpu.h +.In sys/sysctl.h +.In kvm.h +.Ft int +.Fn kvm_dpcpu_setcpu "kvm_t *kd" "u_int cpu" +.Ft int +.Fn kvm_getmaxcpu "kvm_t *kd" +.Ft void * +.Fn kvm_getpcpu "kvm_t *kd" "int cpu" +.Sh DESCRIPTION +The +.Fn kvm_dpcpu_setcpu , +.Fn kvm_getmaxcpu , +and +.Fn kvm_getpcpu +functions are used to access the per-CPU data of active processors in the +kernel indicated by +.Fa kd . +Per-CPU storage comes in two flavours: data stored directly in a +.Vt "struct pcpu" +associated with each CPU, and dynamic per-CPU storage (DPCPU), in which a +single kernel symbol refers to different data depending on what CPU it is +accessed from. +.Pp +The +.Fn kvm_getmaxcpu +function returns the maximum number of CPUs supported by the kernel. +.Pp +The +.Fn kvm_getpcpu +function returns a buffer holding the per-CPU data for a single CPU. +This buffer is described by the +.Vt "struct pcpu" +type. +The caller is responsible for releasing the buffer via a call to +.Xr free 3 +when it is no longer needed. +If +.Fa cpu +is not active, then +.Dv NULL +is returned instead. +.Pp +Symbols for dynamic per-CPU data are accessed via +.Xr kvm_nlist 3 +as with other symbols. +.Nm libkvm +maintains a notion of the "current CPU", set by +.Xr kvm_dpcpu_setcpu , +which defaults to 0. +Once another CPU is selected, +.Xr kvm_nlist 3 +will return pointers to that data on the appropriate CPU. +.Sh CACHING +.Fn kvm_getmaxcpu +and +.Fn kvm_getpcpu +cache the nlist values for various kernel variables which are +reused in successive calls. +You may call either function with +.Fa kd +set to +.Dv NULL +to clear this cache. +.Sh RETURN VALUES +On success, the +.Fn kvm_getmaxcpu +function returns the maximum number of CPUs supported by the kernel. +If an error occurs, +it returns -1 instead. +.Pp +On success, the +.Fn kvm_getpcpu +function returns a pointer to an allocated buffer or +.Dv NULL . +If an error occurs, +it returns -1 instead. +.Pp +On success, the +.Fn kvm_dpcpu_setcpu +call returns 0; if an error occurs, it returns -1 instead. +.Pp +If any function encounters an error, +then an error message may be retrieved via +.Xr kvm_geterr 3 . +.Sh SEE ALSO +.Xr free 3 , +.Xr kvm 3 diff --git a/lib/libkvm/kvm_getprocs.3 b/lib/libkvm/kvm_getprocs.3 new file mode 100644 index 0000000..013da08 --- /dev/null +++ b/lib/libkvm/kvm_getprocs.3 @@ -0,0 +1,174 @@ +.\" Copyright (c) 1992, 1993 +.\" The Regents of the University of California. All rights reserved. +.\" +.\" This code is derived from software developed by the Computer Systems +.\" Engineering group at Lawrence Berkeley Laboratory under DARPA contract +.\" BG 91-66 and contributed to Berkeley. +.\" +.\" Redistribution and use in source and binary forms, with or without +.\" modification, are permitted provided that the following conditions +.\" are met: +.\" 1. Redistributions of source code must retain the above copyright +.\" notice, this list of conditions and the following disclaimer. +.\" 2. Redistributions in binary form must reproduce the above copyright +.\" notice, this list of conditions and the following disclaimer in the +.\" documentation and/or other materials provided with the distribution. +.\" 4. Neither the name of the University nor the names of its contributors +.\" may be used to endorse or promote products derived from this software +.\" without specific prior written permission. +.\" +.\" THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND +.\" ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE +.\" IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE +.\" ARE DISCLAIMED. IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE +.\" FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL +.\" DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS +.\" OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) +.\" HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT +.\" LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY +.\" OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF +.\" SUCH DAMAGE. +.\" +.\" @(#)kvm_getprocs.3 8.1 (Berkeley) 6/4/93 +.\" $FreeBSD$ +.\" +.Dd November 22, 2011 +.Dt KVM_GETPROCS 3 +.Os +.Sh NAME +.Nm kvm_getprocs , +.Nm kvm_getargv , +.Nm kvm_getenvv +.Nd access user process state +.Sh LIBRARY +.Lb libkvm +.Sh SYNOPSIS +.In kvm.h +.In sys/param.h +.In sys/sysctl.h +.In sys/user.h +.\" .Fa kvm_t *kd +.Ft struct kinfo_proc * +.Fn kvm_getprocs "kvm_t *kd" "int op" "int arg" "int *cnt" +.Ft char ** +.Fn kvm_getargv "kvm_t *kd" "const struct kinfo_proc *p" "int nchr" +.Ft char ** +.Fn kvm_getenvv "kvm_t *kd" "const struct kinfo_proc *p" "int nchr" +.Sh DESCRIPTION +The +.Fn kvm_getprocs +function returns a (sub-)set of active processes in the kernel indicated by +.Fa kd . +The +.Fa op +and +.Fa arg +arguments constitute a predicate which limits the set of processes +returned. +The value of +.Fa op +describes the filtering predicate as follows: +.Pp +.Bl -tag -width 20n -offset indent -compact +.It Dv KERN_PROC_ALL +all processes and kernel visible threads +.It Dv KERN_PROC_PROC +all processes, without threads +.It Dv KERN_PROC_PID +processes with process ID +.Fa arg +.It Dv KERN_PROC_PGRP +processes with process group +.Fa arg +.It Dv KERN_PROC_SESSION +processes with session +.Fa arg +.It Dv KERN_PROC_TTY +processes with TTY +.Fa arg +.It Dv KERN_PROC_UID +processes with effective user ID +.Fa arg +.It Dv KERN_PROC_RUID +processes with real user ID +.Fa arg +.It Dv KERN_PROC_INC_THREAD +modifier to return all kernel visible threads when filtering +by process ID, process group, TTY, user ID, and real user ID +.El +.Pp +The number of processes found is returned in the reference parameter +.Fa cnt . +The processes are returned as a contiguous array of kinfo_proc structures. +This memory is locally allocated, and subsequent calls to +.Fn kvm_getprocs +and +.Fn kvm_close +will overwrite this storage. +.Pp +The +.Fn kvm_getargv +function returns a null-terminated argument vector that corresponds to the +command line arguments passed to process indicated by +.Fa p . +Most likely, these arguments correspond to the values passed to +.Xr exec 3 +on process creation. +This information is, however, +deliberately under control of the process itself. +Note that the original command name can be found, unaltered, +in the p_comm field of the process structure returned by +.Fn kvm_getprocs . +.Pp +The +.Fa nchr +argument indicates the maximum number of characters, including null bytes, +to use in building the strings. +If this amount is exceeded, the string +causing the overflow is truncated and the partial result is returned. +This is handy for programs like +.Xr ps 1 +and +.Xr w 1 +that print only a one line summary of a command and should not copy +out large amounts of text only to ignore it. +If +.Fa nchr +is zero, no limit is imposed and all argument strings are returned in +their entirety. +.Pp +The memory allocated to the argv pointers and string storage +is owned by the kvm library. +Subsequent +.Fn kvm_getprocs +and +.Xr kvm_close 3 +calls will clobber this storage. +.Pp +The +.Fn kvm_getenvv +function is similar to +.Fn kvm_getargv +but returns the vector of environment strings. +This data is +also alterable by the process. +.Sh RETURN VALUES +The +.Fn kvm_getprocs , +.Fn kvm_getargv , +and +.Fn kvm_getenvv +functions return +.Dv NULL +on failure. +.Sh SEE ALSO +.Xr kvm 3 , +.Xr kvm_close 3 , +.Xr kvm_geterr 3 , +.Xr kvm_nlist 3 , +.Xr kvm_open 3 , +.Xr kvm_openfiles 3 , +.Xr kvm_read 3 , +.Xr kvm_write 3 +.Sh BUGS +These routines do not belong in the kvm interface. diff --git a/lib/libkvm/kvm_getswapinfo.3 b/lib/libkvm/kvm_getswapinfo.3 new file mode 100644 index 0000000..edd2068 --- /dev/null +++ b/lib/libkvm/kvm_getswapinfo.3 @@ -0,0 +1,111 @@ +.\" Copyright (C) 1999 Matthew Dillon. All rights reserved. +.\" +.\" Redistribution and use in source and binary forms, with or without +.\" modification, are permitted provided that the following conditions +.\" are met: +.\" 1. Redistributions of source code must retain the above copyright +.\" notice, this list of conditions and the following disclaimer. +.\" 2. Redistributions in binary form must reproduce the above copyright +.\" notice, this list of conditions and the following disclaimer in the +.\" documentation and/or other materials provided with the distribution. +.\" +.\" THIS SOFTWARE IS PROVIDED BY AUTHOR AND CONTRIBUTORS ``AS IS'' AND +.\" ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE +.\" IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE +.\" ARE DISCLAIMED. IN NO EVENT SHALL AUTHOR OR CONTRIBUTORS BE LIABLE +.\" FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL +.\" DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS +.\" OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) +.\" HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT +.\" LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY +.\" OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF +.\" SUCH DAMAGE. +.\" +.\" $FreeBSD$ +.\" +.Dd January 22, 1999 +.Dt KVM_SWAPINFO 3 +.Os +.Sh NAME +.Nm kvm_getswapinfo +.Nd return swap summary statistics for the system +.Sh LIBRARY +.Lb libkvm +.Sh SYNOPSIS +.In kvm.h +.Ft int +.Fn kvm_getswapinfo "kvm_t *kd" "struct kvm_swap *" "int maxswap" "int flags" +.Sh DESCRIPTION +The +.Fn kvm_getswapinfo +function fills an array of +.Vt kvm_swap +structures with swap summary +information for each swap device, for up to +.Fa maxswap +\- 1 devices. +The number of devices, up to +.Fa maxswap +\- 1, is returned. +A grand +total of all swap devices (including any devices that go beyond +.Fa maxswap +\- 1) is returned in one additional array entry. +This +entry is not counted in the return value. +Thus, if you specify a +.Fa maxswap +value of 1, the function will typically return the +value 0 and the single +.Vt kvm_swap +structure will be filled with +the grand total over all swap devices. +The grand total is calculated +from all available swap devices whether or not you made room +for them all in the array. +The grand total is returned. +.Pp +The flags argument is currently unused and must be passed as 0. +.Pp +If an error occurs, -1 is returned. +.Pp +Each swap partition and the grand total is summarized in the +.Vt kvm_swap +structure. +This structure contains the following fields: +.Pp +.Bl -item -offset indent -compact +.It +.Va char ksw_devname[] ; +.It +.Va int ksw_total ; +.It +.Va int ksw_used ; +.It +.Va int ksw_flags ; +.El +.Pp +Values are in +.Dv PAGE_SIZE Ns 'd +chunks (see +.Xr getpagesize 3 ) . +.Va ksw_flags +contains +a copy of the swap device flags. +.Sh CACHING +This function caches the nlist values for various kernel variables which +it reuses in successive calls. +You may call the function with +.Fa kd +== +.Dv NULL +to clear the cache. +.Sh DIAGNOSTICS +If the load average was unobtainable, \-1 is returned; otherwise, +the number of swap devices actually retrieved is returned. +.Pp +If the name of the swap device does not fit in the static char buffer +in the structure, it is truncated. +The buffer is always zero terminated. +.Sh SEE ALSO +.Xr kvm 3 diff --git a/lib/libkvm/kvm_getswapinfo.c b/lib/libkvm/kvm_getswapinfo.c new file mode 100644 index 0000000..d79d70c --- /dev/null +++ b/lib/libkvm/kvm_getswapinfo.c @@ -0,0 +1,261 @@ +/* + * Copyright (c) 1999, Matthew Dillon. All Rights Reserved. + * Copyright (c) 2001, Thomas Moestl. All Rights Reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions + * are met: + * 1. Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * 2. Redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in the + * documentation and/or other materials provided with the distribution. + * + * THIS SOFTWARE IS PROVIDED BY AUTHOR AND CONTRIBUTORS ``AS IS'' AND + * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + * ARE DISCLAIMED. IN NO EVENT SHALL AUTHOR OR CONTRIBUTORS BE LIABLE + * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL + * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS + * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) + * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT + * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY + * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF + * SUCH DAMAGE. + */ + +#include <sys/cdefs.h> +__FBSDID("$FreeBSD$"); + +#include <sys/param.h> +#include <sys/time.h> +#include <sys/stat.h> +#include <sys/blist.h> +#include <sys/sysctl.h> + +#include <vm/swap_pager.h> +#include <vm/vm_param.h> + +#include <err.h> +#include <errno.h> +#include <fcntl.h> +#include <kvm.h> +#include <nlist.h> +#include <paths.h> +#include <stdio.h> +#include <stdlib.h> +#include <string.h> +#include <unistd.h> +#include <limits.h> + +#include "kvm_private.h" + +static struct nlist kvm_swap_nl[] = { + { .n_name = "_swtailq" }, /* list of swap devices and sizes */ + { .n_name = "_dmmax" }, /* maximum size of a swap block */ + { .n_name = NULL } +}; + +#define NL_SWTAILQ 0 +#define NL_DMMAX 1 + +static int kvm_swap_nl_cached = 0; +static int unswdev; /* number of found swap dev's */ +static int dmmax; + +static int kvm_getswapinfo_kvm(kvm_t *, struct kvm_swap *, int, int); +static int kvm_getswapinfo_sysctl(kvm_t *, struct kvm_swap *, int, int); +static int nlist_init(kvm_t *); +static int getsysctl(kvm_t *, const char *, void *, size_t); + +#define KREAD(kd, addr, obj) \ + (kvm_read(kd, addr, (char *)(obj), sizeof(*obj)) != sizeof(*obj)) +#define KGET(idx, var) \ + KGET2(kvm_swap_nl[(idx)].n_value, var, kvm_swap_nl[(idx)].n_name) +#define KGET2(addr, var, msg) \ + if (KREAD(kd, (u_long)(addr), (var))) { \ + _kvm_err(kd, kd->program, "cannot read %s", msg); \ + return (-1); \ + } + +#define GETSWDEVNAME(dev, str, flags) \ + if (dev == NODEV) { \ + strlcpy(str, "[NFS swap]", sizeof(str)); \ + } else { \ + snprintf( \ + str, sizeof(str),"%s%s", \ + ((flags & SWIF_DEV_PREFIX) ? _PATH_DEV : ""), \ + devname(dev, S_IFCHR) \ + ); \ + } + +int +kvm_getswapinfo(kvm_t *kd, struct kvm_swap *swap_ary, int swap_max, int flags) +{ + + /* + * clear cache + */ + if (kd == NULL) { + kvm_swap_nl_cached = 0; + return(0); + } + + if (ISALIVE(kd)) { + return kvm_getswapinfo_sysctl(kd, swap_ary, swap_max, flags); + } else { + return kvm_getswapinfo_kvm(kd, swap_ary, swap_max, flags); + } +} + +int +kvm_getswapinfo_kvm(kvm_t *kd, struct kvm_swap *swap_ary, int swap_max, + int flags) +{ + int i, ttl; + TAILQ_HEAD(, swdevt) swtailq; + struct swdevt *sp, swinfo; + struct kvm_swap tot; + + if (!nlist_init(kd)) + return (-1); + + bzero(&tot, sizeof(tot)); + KGET(NL_SWTAILQ, &swtailq); + sp = TAILQ_FIRST(&swtailq); + for (i = 0; sp != NULL; i++) { + KGET2(sp, &swinfo, "swinfo"); + ttl = swinfo.sw_nblks - dmmax; + if (i < swap_max - 1) { + bzero(&swap_ary[i], sizeof(swap_ary[i])); + swap_ary[i].ksw_total = ttl; + swap_ary[i].ksw_used = swinfo.sw_used; + swap_ary[i].ksw_flags = swinfo.sw_flags; + GETSWDEVNAME(swinfo.sw_dev, swap_ary[i].ksw_devname, + flags); + } + tot.ksw_total += ttl; + tot.ksw_used += swinfo.sw_used; + sp = TAILQ_NEXT(&swinfo, sw_list); + } + + if (i >= swap_max) + i = swap_max - 1; + if (i >= 0) + swap_ary[i] = tot; + + return(i); +} + +#define GETSYSCTL(kd, name, var) \ + getsysctl(kd, name, &(var), sizeof(var)) + +/* The maximum MIB length for vm.swap_info and an additional device number */ +#define SWI_MAXMIB 3 + +int +kvm_getswapinfo_sysctl(kvm_t *kd, struct kvm_swap *swap_ary, int swap_max, + int flags) +{ + int ti, ttl; + size_t mibi, len; + int soid[SWI_MAXMIB]; + struct xswdev xsd; + struct kvm_swap tot; + + if (!GETSYSCTL(kd, "vm.dmmax", dmmax)) + return -1; + + mibi = SWI_MAXMIB - 1; + if (sysctlnametomib("vm.swap_info", soid, &mibi) == -1) { + _kvm_err(kd, kd->program, "sysctlnametomib failed: %s", + strerror(errno)); + return -1; + } + bzero(&tot, sizeof(tot)); + for (unswdev = 0;; unswdev++) { + soid[mibi] = unswdev; + len = sizeof(xsd); + if (sysctl(soid, mibi + 1, &xsd, &len, NULL, 0) == -1) { + if (errno == ENOENT) + break; + _kvm_err(kd, kd->program, "cannot read sysctl: %s.", + strerror(errno)); + return -1; + } + if (len != sizeof(xsd)) { + _kvm_err(kd, kd->program, "struct xswdev has unexpected " + "size; kernel and libkvm out of sync?"); + return -1; + } + if (xsd.xsw_version != XSWDEV_VERSION) { + _kvm_err(kd, kd->program, "struct xswdev version " + "mismatch; kernel and libkvm out of sync?"); + return -1; + } + + ttl = xsd.xsw_nblks - dmmax; + if (unswdev < swap_max - 1) { + bzero(&swap_ary[unswdev], sizeof(swap_ary[unswdev])); + swap_ary[unswdev].ksw_total = ttl; + swap_ary[unswdev].ksw_used = xsd.xsw_used; + swap_ary[unswdev].ksw_flags = xsd.xsw_flags; + GETSWDEVNAME(xsd.xsw_dev, swap_ary[unswdev].ksw_devname, + flags); + } + tot.ksw_total += ttl; + tot.ksw_used += xsd.xsw_used; + } + + ti = unswdev; + if (ti >= swap_max) + ti = swap_max - 1; + if (ti >= 0) + swap_ary[ti] = tot; + + return(ti); +} + +static int +nlist_init(kvm_t *kd) +{ + + if (kvm_swap_nl_cached) + return (1); + + if (kvm_nlist(kd, kvm_swap_nl) < 0) + return (0); + + /* Required entries */ + if (kvm_swap_nl[NL_SWTAILQ].n_value == 0) { + _kvm_err(kd, kd->program, "unable to find swtailq"); + return (0); + } + + if (kvm_swap_nl[NL_DMMAX].n_value == 0) { + _kvm_err(kd, kd->program, "unable to find dmmax"); + return (0); + } + + /* Get globals, type of swap */ + KGET(NL_DMMAX, &dmmax); + + kvm_swap_nl_cached = 1; + return (1); +} + +static int +getsysctl(kvm_t *kd, const char *name, void *ptr, size_t len) +{ + size_t nlen = len; + if (sysctlbyname(name, ptr, &nlen, NULL, 0) == -1) { + _kvm_err(kd, kd->program, "cannot read sysctl %s:%s", name, + strerror(errno)); + return (0); + } + if (nlen != len) { + _kvm_err(kd, kd->program, "sysctl %s has unexpected size", name); + return (0); + } + return (1); +} diff --git a/lib/libkvm/kvm_i386.c b/lib/libkvm/kvm_i386.c new file mode 100644 index 0000000..601126b --- /dev/null +++ b/lib/libkvm/kvm_i386.c @@ -0,0 +1,453 @@ +/*- + * Copyright (c) 1989, 1992, 1993 + * The Regents of the University of California. All rights reserved. + * + * This code is derived from software developed by the Computer Systems + * Engineering group at Lawrence Berkeley Laboratory under DARPA contract + * BG 91-66 and contributed to Berkeley. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions + * are met: + * 1. Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * 2. Redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in the + * documentation and/or other materials provided with the distribution. + * 4. Neither the name of the University nor the names of its contributors + * may be used to endorse or promote products derived from this software + * without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND + * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + * ARE DISCLAIMED. IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE + * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL + * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS + * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) + * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT + * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY + * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF + * SUCH DAMAGE. + */ + +#include <sys/cdefs.h> +__FBSDID("$FreeBSD$"); + +#if defined(LIBC_SCCS) && !defined(lint) +#if 0 +static char sccsid[] = "@(#)kvm_hp300.c 8.1 (Berkeley) 6/4/93"; +#endif +#endif /* LIBC_SCCS and not lint */ + +/* + * i386 machine dependent routines for kvm. Hopefully, the forthcoming + * vm code will one day obsolete this module. + */ + +#include <sys/param.h> +#include <sys/user.h> +#include <sys/proc.h> +#include <sys/stat.h> +#include <sys/mman.h> +#include <stdlib.h> +#include <string.h> +#include <unistd.h> +#include <nlist.h> +#include <kvm.h> + +#include <vm/vm.h> +#include <vm/vm_param.h> + +#include <machine/elf.h> + +#include <limits.h> + +#include "kvm_private.h" + +#ifndef btop +#define btop(x) (i386_btop(x)) +#define ptob(x) (i386_ptob(x)) +#endif + +#define PG_FRAME_PAE (~((uint64_t)PAGE_MASK)) +#define PDRSHIFT_PAE 21 +#define NPTEPG_PAE (PAGE_SIZE/sizeof(uint64_t)) +#define NBPDR_PAE (1<<PDRSHIFT_PAE) + +/* minidump must be the first item! */ +struct vmstate { + int minidump; /* 1 = minidump mode */ + void *mmapbase; + size_t mmapsize; + void *PTD; + int pae; +}; + +/* + * Map the ELF headers into the process' address space. We do this in two + * steps: first the ELF header itself and using that information the whole + * set of headers. (Taken from kvm_ia64.c) + */ +static int +_kvm_maphdrs(kvm_t *kd, size_t sz) +{ + struct vmstate *vm = kd->vmst; + + /* munmap() previous mmap(). */ + if (vm->mmapbase != NULL) { + munmap(vm->mmapbase, vm->mmapsize); + vm->mmapbase = NULL; + } + + vm->mmapsize = sz; + vm->mmapbase = mmap(NULL, sz, PROT_READ, MAP_PRIVATE, kd->pmfd, 0); + if (vm->mmapbase == MAP_FAILED) { + _kvm_err(kd, kd->program, "cannot mmap corefile"); + return (-1); + } + return (0); +} + +/* + * Translate a physical memory address to a file-offset in the crash-dump. + * (Taken from kvm_ia64.c) + */ +static size_t +_kvm_pa2off(kvm_t *kd, uint64_t pa, off_t *ofs) +{ + Elf_Ehdr *e = kd->vmst->mmapbase; + Elf_Phdr *p; + int n; + + if (kd->rawdump) { + *ofs = pa; + return (PAGE_SIZE - ((size_t)pa & PAGE_MASK)); + } + + p = (Elf_Phdr*)((char*)e + e->e_phoff); + n = e->e_phnum; + while (n && (pa < p->p_paddr || pa >= p->p_paddr + p->p_memsz)) + p++, n--; + if (n == 0) + return (0); + *ofs = (pa - p->p_paddr) + p->p_offset; + return (PAGE_SIZE - ((size_t)pa & PAGE_MASK)); +} + +void +_kvm_freevtop(kvm_t *kd) +{ + struct vmstate *vm = kd->vmst; + + if (kd->vmst->minidump) + return (_kvm_minidump_freevtop(kd)); + if (vm->mmapbase != NULL) + munmap(vm->mmapbase, vm->mmapsize); + if (vm->PTD) + free(vm->PTD); + free(vm); + kd->vmst = NULL; +} + +int +_kvm_initvtop(kvm_t *kd) +{ + struct nlist nl[2]; + u_long pa; + u_long kernbase; + char *PTD; + Elf_Ehdr *ehdr; + size_t hdrsz; + int i; + char minihdr[8]; + + if (!kd->rawdump && pread(kd->pmfd, &minihdr, 8, 0) == 8) + if (memcmp(&minihdr, "minidump", 8) == 0) + return (_kvm_minidump_initvtop(kd)); + + kd->vmst = (struct vmstate *)_kvm_malloc(kd, sizeof(*kd->vmst)); + if (kd->vmst == 0) { + _kvm_err(kd, kd->program, "cannot allocate vm"); + return (-1); + } + kd->vmst->PTD = 0; + + if (kd->rawdump == 0) { + if (_kvm_maphdrs(kd, sizeof(Elf_Ehdr)) == -1) + return (-1); + + ehdr = kd->vmst->mmapbase; + hdrsz = ehdr->e_phoff + ehdr->e_phentsize * ehdr->e_phnum; + if (_kvm_maphdrs(kd, hdrsz) == -1) + return (-1); + } + + nl[0].n_name = "kernbase"; + nl[1].n_name = 0; + + if (kvm_nlist(kd, nl) != 0) + kernbase = KERNBASE; /* for old kernels */ + else + kernbase = nl[0].n_value; + + nl[0].n_name = "IdlePDPT"; + nl[1].n_name = 0; + + if (kvm_nlist(kd, nl) == 0) { + uint64_t pa64; + + if (kvm_read(kd, (nl[0].n_value - kernbase), &pa, + sizeof(pa)) != sizeof(pa)) { + _kvm_err(kd, kd->program, "cannot read IdlePDPT"); + return (-1); + } + PTD = _kvm_malloc(kd, 4 * PAGE_SIZE); + for (i = 0; i < 4; i++) { + if (kvm_read(kd, pa + (i * sizeof(pa64)), &pa64, + sizeof(pa64)) != sizeof(pa64)) { + _kvm_err(kd, kd->program, "Cannot read PDPT"); + free(PTD); + return (-1); + } + if (kvm_read(kd, pa64 & PG_FRAME_PAE, + PTD + (i * PAGE_SIZE), PAGE_SIZE) != (PAGE_SIZE)) { + _kvm_err(kd, kd->program, "cannot read PDPT"); + free(PTD); + return (-1); + } + } + kd->vmst->PTD = PTD; + kd->vmst->pae = 1; + } else { + nl[0].n_name = "IdlePTD"; + nl[1].n_name = 0; + + if (kvm_nlist(kd, nl) != 0) { + _kvm_err(kd, kd->program, "bad namelist"); + return (-1); + } + if (kvm_read(kd, (nl[0].n_value - kernbase), &pa, + sizeof(pa)) != sizeof(pa)) { + _kvm_err(kd, kd->program, "cannot read IdlePTD"); + return (-1); + } + PTD = _kvm_malloc(kd, PAGE_SIZE); + if (kvm_read(kd, pa, PTD, PAGE_SIZE) != PAGE_SIZE) { + _kvm_err(kd, kd->program, "cannot read PTD"); + return (-1); + } + kd->vmst->PTD = PTD; + kd->vmst->pae = 0; + } + return (0); +} + +static int +_kvm_vatop(kvm_t *kd, u_long va, off_t *pa) +{ + struct vmstate *vm; + u_long offset; + u_long pte_pa; + u_long pde_pa; + pd_entry_t pde; + pt_entry_t pte; + u_long pdeindex; + u_long pteindex; + size_t s; + u_long a; + off_t ofs; + uint32_t *PTD; + + vm = kd->vmst; + PTD = (uint32_t *)vm->PTD; + offset = va & (PAGE_SIZE - 1); + + /* + * If we are initializing (kernel page table descriptor pointer + * not yet set) then return pa == va to avoid infinite recursion. + */ + if (PTD == 0) { + s = _kvm_pa2off(kd, va, pa); + if (s == 0) { + _kvm_err(kd, kd->program, + "_kvm_vatop: bootstrap data not in dump"); + goto invalid; + } else + return (PAGE_SIZE - offset); + } + + pdeindex = va >> PDRSHIFT; + pde = PTD[pdeindex]; + if (((u_long)pde & PG_V) == 0) { + _kvm_err(kd, kd->program, "_kvm_vatop: pde not valid"); + goto invalid; + } + + if ((u_long)pde & PG_PS) { + /* + * No second-level page table; ptd describes one 4MB page. + * (We assume that the kernel wouldn't set PG_PS without enabling + * it cr0). + */ +#define PAGE4M_MASK (NBPDR - 1) +#define PG_FRAME4M (~PAGE4M_MASK) + pde_pa = ((u_long)pde & PG_FRAME4M) + (va & PAGE4M_MASK); + s = _kvm_pa2off(kd, pde_pa, &ofs); + if (s == 0) { + _kvm_err(kd, kd->program, + "_kvm_vatop: 4MB page address not in dump"); + goto invalid; + } + *pa = ofs; + return (NBPDR - (va & PAGE4M_MASK)); + } + + pteindex = (va >> PAGE_SHIFT) & (NPTEPG-1); + pte_pa = ((u_long)pde & PG_FRAME) + (pteindex * sizeof(pde)); + + s = _kvm_pa2off(kd, pte_pa, &ofs); + if (s < sizeof pte) { + _kvm_err(kd, kd->program, "_kvm_vatop: pdpe_pa not found"); + goto invalid; + } + + /* XXX This has to be a physical address read, kvm_read is virtual */ + if (lseek(kd->pmfd, ofs, 0) == -1) { + _kvm_syserr(kd, kd->program, "_kvm_vatop: lseek"); + goto invalid; + } + if (read(kd->pmfd, &pte, sizeof pte) != sizeof pte) { + _kvm_syserr(kd, kd->program, "_kvm_vatop: read"); + goto invalid; + } + if (((u_long)pte & PG_V) == 0) { + _kvm_err(kd, kd->program, "_kvm_kvatop: pte not valid"); + goto invalid; + } + + a = ((u_long)pte & PG_FRAME) + offset; + s =_kvm_pa2off(kd, a, pa); + if (s == 0) { + _kvm_err(kd, kd->program, "_kvm_vatop: address not in dump"); + goto invalid; + } else + return (PAGE_SIZE - offset); + +invalid: + _kvm_err(kd, 0, "invalid address (0x%lx)", va); + return (0); +} + +static int +_kvm_vatop_pae(kvm_t *kd, u_long va, off_t *pa) +{ + struct vmstate *vm; + uint64_t offset; + uint64_t pte_pa; + uint64_t pde_pa; + uint64_t pde; + uint64_t pte; + u_long pdeindex; + u_long pteindex; + size_t s; + uint64_t a; + off_t ofs; + uint64_t *PTD; + + vm = kd->vmst; + PTD = (uint64_t *)vm->PTD; + offset = va & (PAGE_SIZE - 1); + + /* + * If we are initializing (kernel page table descriptor pointer + * not yet set) then return pa == va to avoid infinite recursion. + */ + if (PTD == 0) { + s = _kvm_pa2off(kd, va, pa); + if (s == 0) { + _kvm_err(kd, kd->program, + "_kvm_vatop_pae: bootstrap data not in dump"); + goto invalid; + } else + return (PAGE_SIZE - offset); + } + + pdeindex = va >> PDRSHIFT_PAE; + pde = PTD[pdeindex]; + if (((u_long)pde & PG_V) == 0) { + _kvm_err(kd, kd->program, "_kvm_kvatop_pae: pde not valid"); + goto invalid; + } + + if ((u_long)pde & PG_PS) { + /* + * No second-level page table; ptd describes one 2MB page. + * (We assume that the kernel wouldn't set PG_PS without enabling + * it cr0). + */ +#define PAGE2M_MASK (NBPDR_PAE - 1) +#define PG_FRAME2M (~PAGE2M_MASK) + pde_pa = ((u_long)pde & PG_FRAME2M) + (va & PAGE2M_MASK); + s = _kvm_pa2off(kd, pde_pa, &ofs); + if (s == 0) { + _kvm_err(kd, kd->program, + "_kvm_vatop: 2MB page address not in dump"); + goto invalid; + } + *pa = ofs; + return (NBPDR_PAE - (va & PAGE2M_MASK)); + } + + pteindex = (va >> PAGE_SHIFT) & (NPTEPG_PAE-1); + pte_pa = ((uint64_t)pde & PG_FRAME_PAE) + (pteindex * sizeof(pde)); + + s = _kvm_pa2off(kd, pte_pa, &ofs); + if (s < sizeof pte) { + _kvm_err(kd, kd->program, "_kvm_vatop_pae: pdpe_pa not found"); + goto invalid; + } + + /* XXX This has to be a physical address read, kvm_read is virtual */ + if (lseek(kd->pmfd, ofs, 0) == -1) { + _kvm_syserr(kd, kd->program, "_kvm_vatop_pae: lseek"); + goto invalid; + } + if (read(kd->pmfd, &pte, sizeof pte) != sizeof pte) { + _kvm_syserr(kd, kd->program, "_kvm_vatop_pae: read"); + goto invalid; + } + if (((uint64_t)pte & PG_V) == 0) { + _kvm_err(kd, kd->program, "_kvm_vatop_pae: pte not valid"); + goto invalid; + } + + a = ((uint64_t)pte & PG_FRAME_PAE) + offset; + s =_kvm_pa2off(kd, a, pa); + if (s == 0) { + _kvm_err(kd, kd->program, + "_kvm_vatop_pae: address not in dump"); + goto invalid; + } else + return (PAGE_SIZE - offset); + +invalid: + _kvm_err(kd, 0, "invalid address (0x%lx)", va); + return (0); +} + +int +_kvm_kvatop(kvm_t *kd, u_long va, off_t *pa) +{ + + if (kd->vmst->minidump) + return (_kvm_minidump_kvatop(kd, va, pa)); + if (ISALIVE(kd)) { + _kvm_err(kd, 0, "vatop called in live kernel!"); + return (0); + } + if (kd->vmst->pae) + return (_kvm_vatop_pae(kd, va, pa)); + else + return (_kvm_vatop(kd, va, pa)); +} diff --git a/lib/libkvm/kvm_ia64.c b/lib/libkvm/kvm_ia64.c new file mode 100644 index 0000000..74e2b80 --- /dev/null +++ b/lib/libkvm/kvm_ia64.c @@ -0,0 +1,292 @@ +/* $FreeBSD$ */ +/* $NetBSD: kvm_alpha.c,v 1.7.2.1 1997/11/02 20:34:26 mellon Exp $ */ + +/* + * Copyright (c) 1994, 1995 Carnegie-Mellon University. + * All rights reserved. + * + * Author: Chris G. Demetriou + * + * Permission to use, copy, modify and distribute this software and + * its documentation is hereby granted, provided that both the copyright + * notice and this permission notice appear in all copies of the + * software, derivative works or modified versions, and any portions + * thereof, and that both notices appear in supporting documentation. + * + * CARNEGIE MELLON ALLOWS FREE USE OF THIS SOFTWARE IN ITS "AS IS" + * CONDITION. CARNEGIE MELLON DISCLAIMS ANY LIABILITY OF ANY KIND + * FOR ANY DAMAGES WHATSOEVER RESULTING FROM THE USE OF THIS SOFTWARE. + * + * Carnegie Mellon requests users of this software to return to + * + * Software Distribution Coordinator or Software.Distribution@CS.CMU.EDU + * School of Computer Science + * Carnegie Mellon University + * Pittsburgh PA 15213-3890 + * + * any improvements or extensions that they make and grant Carnegie the + * rights to redistribute these changes. + */ + +#include <sys/types.h> +#include <sys/elf64.h> +#include <sys/mman.h> + +#include <machine/atomic.h> +#include <machine/bootinfo.h> +#include <machine/pte.h> + +#include <kvm.h> +#include <limits.h> +#include <stdlib.h> +#include <unistd.h> + +#include "kvm_private.h" + +#define REGION_BASE(n) (((uint64_t)(n)) << 61) +#define REGION_ADDR(x) ((x) & ((1LL<<61)-1LL)) + +#define NKPTEPG(ps) ((ps) / sizeof(struct ia64_lpte)) +#define NKPTEDIR(ps) ((ps) >> 3) +#define KPTE_PTE_INDEX(va,ps) (((va)/(ps)) % NKPTEPG(ps)) +#define KPTE_DIR0_INDEX(va,ps) ((((va)/(ps)) / NKPTEPG(ps)) / NKPTEDIR(ps)) +#define KPTE_DIR1_INDEX(va,ps) ((((va)/(ps)) / NKPTEPG(ps)) % NKPTEDIR(ps)) + +#define PBVM_BASE 0x9ffc000000000000UL +#define PBVM_PGSZ (64 * 1024) + +struct vmstate { + void *mmapbase; + size_t mmapsize; + size_t pagesize; + u_long kptdir; + u_long *pbvm_pgtbl; + u_int pbvm_pgtblsz; +}; + +/* + * Map the ELF headers into the process' address space. We do this in two + * steps: first the ELF header itself and using that information the whole + * set of headers. + */ +static int +_kvm_maphdrs(kvm_t *kd, size_t sz) +{ + struct vmstate *vm = kd->vmst; + + /* munmap() previous mmap(). */ + if (vm->mmapbase != NULL) { + munmap(vm->mmapbase, vm->mmapsize); + vm->mmapbase = NULL; + } + + vm->mmapsize = sz; + vm->mmapbase = mmap(NULL, sz, PROT_READ, MAP_PRIVATE, kd->pmfd, 0); + if (vm->mmapbase == MAP_FAILED) { + _kvm_err(kd, kd->program, "cannot mmap corefile"); + return (-1); + } + + return (0); +} + +/* + * Translate a physical memory address to a file-offset in the crash-dump. + */ +static size_t +_kvm_pa2off(kvm_t *kd, uint64_t pa, off_t *ofs, size_t pgsz) +{ + Elf64_Ehdr *e = kd->vmst->mmapbase; + Elf64_Phdr *p = (Elf64_Phdr*)((char*)e + e->e_phoff); + int n = e->e_phnum; + + if (pa != REGION_ADDR(pa)) { + _kvm_err(kd, kd->program, "internal error"); + return (0); + } + + while (n && (pa < p->p_paddr || pa >= p->p_paddr + p->p_memsz)) + p++, n--; + if (n == 0) + return (0); + + *ofs = (pa - p->p_paddr) + p->p_offset; + if (pgsz == 0) + return (p->p_memsz - (pa - p->p_paddr)); + return (pgsz - ((size_t)pa & (pgsz - 1))); +} + +static ssize_t +_kvm_read_phys(kvm_t *kd, uint64_t pa, void *buf, size_t bufsz) +{ + off_t ofs; + size_t sz; + + sz = _kvm_pa2off(kd, pa, &ofs, 0); + if (sz < bufsz) + return ((ssize_t)sz); + + if (lseek(kd->pmfd, ofs, 0) == -1) + return (-1); + return (read(kd->pmfd, buf, bufsz)); +} + +void +_kvm_freevtop(kvm_t *kd) +{ + struct vmstate *vm = kd->vmst; + + if (vm->pbvm_pgtbl != NULL) + free(vm->pbvm_pgtbl); + if (vm->mmapbase != NULL) + munmap(vm->mmapbase, vm->mmapsize); + free(vm); + kd->vmst = NULL; +} + +int +_kvm_initvtop(kvm_t *kd) +{ + struct bootinfo bi; + struct nlist nl[2]; + uint64_t va; + Elf64_Ehdr *ehdr; + size_t hdrsz; + ssize_t sz; + + kd->vmst = (struct vmstate *)_kvm_malloc(kd, sizeof(*kd->vmst)); + if (kd->vmst == NULL) { + _kvm_err(kd, kd->program, "cannot allocate vm"); + return (-1); + } + + kd->vmst->pagesize = getpagesize(); + + if (_kvm_maphdrs(kd, sizeof(Elf64_Ehdr)) == -1) + return (-1); + + ehdr = kd->vmst->mmapbase; + hdrsz = ehdr->e_phoff + ehdr->e_phentsize * ehdr->e_phnum; + if (_kvm_maphdrs(kd, hdrsz) == -1) + return (-1); + + /* + * Load the PBVM page table. We need this to resolve PBVM addresses. + * The PBVM page table is obtained from the bootinfo structure, of + * which the physical address is given to us in e_entry. If e_entry + * is 0, then this is assumed to be a pre-PBVM kernel. + */ + if (ehdr->e_entry != 0) { + sz = _kvm_read_phys(kd, ehdr->e_entry, &bi, sizeof(bi)); + if (sz != sizeof(bi)) { + _kvm_err(kd, kd->program, + "cannot read bootinfo from PA %#lx", ehdr->e_entry); + return (-1); + } + if (bi.bi_magic != BOOTINFO_MAGIC) { + _kvm_err(kd, kd->program, "invalid bootinfo"); + return (-1); + } + kd->vmst->pbvm_pgtbl = _kvm_malloc(kd, bi.bi_pbvm_pgtblsz); + if (kd->vmst->pbvm_pgtbl == NULL) { + _kvm_err(kd, kd->program, "cannot allocate page table"); + return (-1); + } + kd->vmst->pbvm_pgtblsz = bi.bi_pbvm_pgtblsz; + sz = _kvm_read_phys(kd, bi.bi_pbvm_pgtbl, kd->vmst->pbvm_pgtbl, + bi.bi_pbvm_pgtblsz); + if (sz != bi.bi_pbvm_pgtblsz) { + _kvm_err(kd, kd->program, + "cannot read page table from PA %#lx", + bi.bi_pbvm_pgtbl); + return (-1); + } + } else { + kd->vmst->pbvm_pgtbl = NULL; + kd->vmst->pbvm_pgtblsz = 0; + } + + /* + * At this point we've got enough information to use kvm_read() for + * direct mapped (ie region 6 and region 7) address, such as symbol + * addresses/values. + */ + + nl[0].n_name = "ia64_kptdir"; + nl[1].n_name = 0; + + if (kvm_nlist(kd, nl) != 0) { + _kvm_err(kd, kd->program, "bad namelist"); + return (-1); + } + + if (kvm_read(kd, (nl[0].n_value), &va, sizeof(va)) != sizeof(va)) { + _kvm_err(kd, kd->program, "cannot read kptdir"); + return (-1); + } + + if (va < REGION_BASE(6)) { + _kvm_err(kd, kd->program, "kptdir is itself virtual"); + return (-1); + } + + kd->vmst->kptdir = va; + return (0); +} + +int +_kvm_kvatop(kvm_t *kd, u_long va, off_t *ofs) +{ + struct ia64_lpte pte; + uint64_t pa, pgaddr, pt0addr, pt1addr; + size_t pgno, pgsz, pt0no, pt1no; + + if (va >= REGION_BASE(6)) { + /* Regions 6 and 7: direct mapped. */ + pa = REGION_ADDR(va); + return (_kvm_pa2off(kd, pa, ofs, 0)); + } else if (va >= REGION_BASE(5)) { + /* Region 5: Kernel Virtual Memory. */ + va = REGION_ADDR(va); + pgsz = kd->vmst->pagesize; + pt0no = KPTE_DIR0_INDEX(va, pgsz); + pt1no = KPTE_DIR1_INDEX(va, pgsz); + pgno = KPTE_PTE_INDEX(va, pgsz); + if (pt0no >= NKPTEDIR(pgsz)) + goto fail; + pt0addr = kd->vmst->kptdir + (pt0no << 3); + if (kvm_read(kd, pt0addr, &pt1addr, 8) != 8) + goto fail; + if (pt1addr == 0) + goto fail; + pt1addr += pt1no << 3; + if (kvm_read(kd, pt1addr, &pgaddr, 8) != 8) + goto fail; + if (pgaddr == 0) + goto fail; + pgaddr += pgno * sizeof(pte); + if (kvm_read(kd, pgaddr, &pte, sizeof(pte)) != sizeof(pte)) + goto fail; + if (!(pte.pte & PTE_PRESENT)) + goto fail; + pa = (pte.pte & PTE_PPN_MASK) + (va & (pgsz - 1)); + return (_kvm_pa2off(kd, pa, ofs, pgsz)); + } else if (va >= PBVM_BASE) { + /* Region 4: Pre-Boot Virtual Memory (PBVM). */ + va -= PBVM_BASE; + pgsz = PBVM_PGSZ; + pt0no = va / pgsz; + if (pt0no >= (kd->vmst->pbvm_pgtblsz >> 3)) + goto fail; + pt0addr = kd->vmst->pbvm_pgtbl[pt0no]; + if (!(pt0addr & PTE_PRESENT)) + goto fail; + pa = (pt0addr & PTE_PPN_MASK) + va % pgsz; + return (_kvm_pa2off(kd, pa, ofs, pgsz)); + } + + fail: + _kvm_err(kd, kd->program, "invalid kernel virtual address"); + *ofs = ~0UL; + return (0); +} diff --git a/lib/libkvm/kvm_minidump_amd64.c b/lib/libkvm/kvm_minidump_amd64.c new file mode 100644 index 0000000..8d31673 --- /dev/null +++ b/lib/libkvm/kvm_minidump_amd64.c @@ -0,0 +1,332 @@ +/*- + * Copyright (c) 2006 Peter Wemm + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions + * are met: + * 1. Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * 2. Redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in the + * documentation and/or other materials provided with the distribution. + * + * THIS SOFTWARE IS PROVIDED BY THE AUTHOR AND CONTRIBUTORS ``AS IS'' AND + * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + * ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE + * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL + * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS + * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) + * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT + * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY + * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF + * SUCH DAMAGE. + */ + +#include <sys/cdefs.h> +__FBSDID("$FreeBSD$"); + +/* + * AMD64 machine dependent routines for kvm and minidumps. + */ + +#include <sys/param.h> +#include <sys/user.h> +#include <sys/proc.h> +#include <sys/stat.h> +#include <sys/mman.h> +#include <sys/fnv_hash.h> +#include <stdlib.h> +#include <string.h> +#include <unistd.h> +#include <nlist.h> +#include <kvm.h> + +#include <vm/vm.h> +#include <vm/vm_param.h> + +#include <machine/elf.h> +#include <machine/cpufunc.h> +#include <machine/minidump.h> + +#include <limits.h> + +#include "kvm_private.h" + +struct hpte { + struct hpte *next; + vm_paddr_t pa; + int64_t off; +}; + +#define HPT_SIZE 1024 + +/* minidump must be the first item! */ +struct vmstate { + int minidump; /* 1 = minidump mode */ + struct minidumphdr hdr; + void *hpt_head[HPT_SIZE]; + uint64_t *bitmap; + uint64_t *page_map; +}; + +static void +hpt_insert(kvm_t *kd, vm_paddr_t pa, int64_t off) +{ + struct hpte *hpte; + uint32_t fnv = FNV1_32_INIT; + + fnv = fnv_32_buf(&pa, sizeof(pa), fnv); + fnv &= (HPT_SIZE - 1); + hpte = malloc(sizeof(*hpte)); + hpte->pa = pa; + hpte->off = off; + hpte->next = kd->vmst->hpt_head[fnv]; + kd->vmst->hpt_head[fnv] = hpte; +} + +static int64_t +hpt_find(kvm_t *kd, vm_paddr_t pa) +{ + struct hpte *hpte; + uint32_t fnv = FNV1_32_INIT; + + fnv = fnv_32_buf(&pa, sizeof(pa), fnv); + fnv &= (HPT_SIZE - 1); + for (hpte = kd->vmst->hpt_head[fnv]; hpte != NULL; hpte = hpte->next) { + if (pa == hpte->pa) + return (hpte->off); + } + return (-1); +} + +static int +inithash(kvm_t *kd, uint64_t *base, int len, off_t off) +{ + uint64_t idx; + uint64_t bit, bits; + vm_paddr_t pa; + + for (idx = 0; idx < len / sizeof(*base); idx++) { + bits = base[idx]; + while (bits) { + bit = bsfq(bits); + bits &= ~(1ul << bit); + pa = (idx * sizeof(*base) * NBBY + bit) * PAGE_SIZE; + hpt_insert(kd, pa, off); + off += PAGE_SIZE; + } + } + return (off); +} + +void +_kvm_minidump_freevtop(kvm_t *kd) +{ + struct vmstate *vm = kd->vmst; + + if (vm->bitmap) + free(vm->bitmap); + if (vm->page_map) + free(vm->page_map); + free(vm); + kd->vmst = NULL; +} + +int +_kvm_minidump_initvtop(kvm_t *kd) +{ + struct vmstate *vmst; + off_t off; + + vmst = _kvm_malloc(kd, sizeof(*vmst)); + if (vmst == 0) { + _kvm_err(kd, kd->program, "cannot allocate vm"); + return (-1); + } + kd->vmst = vmst; + vmst->minidump = 1; + if (pread(kd->pmfd, &vmst->hdr, sizeof(vmst->hdr), 0) != + sizeof(vmst->hdr)) { + _kvm_err(kd, kd->program, "cannot read dump header"); + return (-1); + } + if (strncmp(MINIDUMP_MAGIC, vmst->hdr.magic, sizeof(vmst->hdr.magic)) != 0) { + _kvm_err(kd, kd->program, "not a minidump for this platform"); + return (-1); + } + + /* + * NB: amd64 minidump header is binary compatible between version 1 + * and version 2; this may not be the case for the future versions. + */ + if (vmst->hdr.version != MINIDUMP_VERSION && vmst->hdr.version != 1) { + _kvm_err(kd, kd->program, "wrong minidump version. expected %d got %d", + MINIDUMP_VERSION, vmst->hdr.version); + return (-1); + } + + /* Skip header and msgbuf */ + off = PAGE_SIZE + round_page(vmst->hdr.msgbufsize); + + vmst->bitmap = _kvm_malloc(kd, vmst->hdr.bitmapsize); + if (vmst->bitmap == NULL) { + _kvm_err(kd, kd->program, "cannot allocate %d bytes for bitmap", vmst->hdr.bitmapsize); + return (-1); + } + if (pread(kd->pmfd, vmst->bitmap, vmst->hdr.bitmapsize, off) != + vmst->hdr.bitmapsize) { + _kvm_err(kd, kd->program, "cannot read %d bytes for page bitmap", vmst->hdr.bitmapsize); + return (-1); + } + off += round_page(vmst->hdr.bitmapsize); + + vmst->page_map = _kvm_malloc(kd, vmst->hdr.pmapsize); + if (vmst->page_map == NULL) { + _kvm_err(kd, kd->program, "cannot allocate %d bytes for page_map", vmst->hdr.pmapsize); + return (-1); + } + if (pread(kd->pmfd, vmst->page_map, vmst->hdr.pmapsize, off) != + vmst->hdr.pmapsize) { + _kvm_err(kd, kd->program, "cannot read %d bytes for page_map", vmst->hdr.pmapsize); + return (-1); + } + off += vmst->hdr.pmapsize; + + /* build physical address hash table for sparse pages */ + inithash(kd, vmst->bitmap, vmst->hdr.bitmapsize, off); + + return (0); +} + +static int +_kvm_minidump_vatop_v1(kvm_t *kd, u_long va, off_t *pa) +{ + struct vmstate *vm; + u_long offset; + pt_entry_t pte; + u_long pteindex; + u_long a; + off_t ofs; + + vm = kd->vmst; + offset = va & (PAGE_SIZE - 1); + + if (va >= vm->hdr.kernbase) { + pteindex = (va - vm->hdr.kernbase) >> PAGE_SHIFT; + pte = vm->page_map[pteindex]; + if (((u_long)pte & PG_V) == 0) { + _kvm_err(kd, kd->program, "_kvm_vatop: pte not valid"); + goto invalid; + } + a = pte & PG_FRAME; + ofs = hpt_find(kd, a); + if (ofs == -1) { + _kvm_err(kd, kd->program, "_kvm_vatop: physical address 0x%lx not in minidump", a); + goto invalid; + } + *pa = ofs + offset; + return (PAGE_SIZE - offset); + } else if (va >= vm->hdr.dmapbase && va < vm->hdr.dmapend) { + a = (va - vm->hdr.dmapbase) & ~PAGE_MASK; + ofs = hpt_find(kd, a); + if (ofs == -1) { + _kvm_err(kd, kd->program, "_kvm_vatop: direct map address 0x%lx not in minidump", va); + goto invalid; + } + *pa = ofs + offset; + return (PAGE_SIZE - offset); + } else { + _kvm_err(kd, kd->program, "_kvm_vatop: virtual address 0x%lx not minidumped", va); + goto invalid; + } + +invalid: + _kvm_err(kd, 0, "invalid address (0x%lx)", va); + return (0); +} + +static int +_kvm_minidump_vatop(kvm_t *kd, u_long va, off_t *pa) +{ + pt_entry_t pt[NPTEPG]; + struct vmstate *vm; + u_long offset; + pd_entry_t pde; + pd_entry_t pte; + u_long pteindex; + u_long pdeindex; + u_long a; + off_t ofs; + + vm = kd->vmst; + offset = va & PAGE_MASK; + + if (va >= vm->hdr.kernbase) { + pdeindex = (va - vm->hdr.kernbase) >> PDRSHIFT; + pde = vm->page_map[pdeindex]; + if (((u_long)pde & PG_V) == 0) { + _kvm_err(kd, kd->program, "_kvm_vatop: pde not valid"); + goto invalid; + } + if ((pde & PG_PS) == 0) { + a = pde & PG_FRAME; + ofs = hpt_find(kd, a); + if (ofs == -1) { + _kvm_err(kd, kd->program, "_kvm_vatop: pt physical address 0x%lx not in minidump", a); + goto invalid; + } + if (pread(kd->pmfd, &pt, PAGE_SIZE, ofs) != PAGE_SIZE) { + _kvm_err(kd, kd->program, "cannot read %d bytes for pt", PAGE_SIZE); + return (-1); + } + pteindex = (va >> PAGE_SHIFT) & ((1ul << NPTEPGSHIFT) - 1); + pte = pt[pteindex]; + if (((u_long)pte & PG_V) == 0) { + _kvm_err(kd, kd->program, "_kvm_vatop: pte not valid"); + goto invalid; + } + a = pte & PG_FRAME; + } else { + a = pde & PG_PS_FRAME; + a += (va & PDRMASK) ^ offset; + } + ofs = hpt_find(kd, a); + if (ofs == -1) { + _kvm_err(kd, kd->program, "_kvm_vatop: physical address 0x%lx not in minidump", a); + goto invalid; + } + *pa = ofs + offset; + return (PAGE_SIZE - offset); + } else if (va >= vm->hdr.dmapbase && va < vm->hdr.dmapend) { + a = (va - vm->hdr.dmapbase) & ~PAGE_MASK; + ofs = hpt_find(kd, a); + if (ofs == -1) { + _kvm_err(kd, kd->program, "_kvm_vatop: direct map address 0x%lx not in minidump", va); + goto invalid; + } + *pa = ofs + offset; + return (PAGE_SIZE - offset); + } else { + _kvm_err(kd, kd->program, "_kvm_vatop: virtual address 0x%lx not minidumped", va); + goto invalid; + } + +invalid: + _kvm_err(kd, 0, "invalid address (0x%lx)", va); + return (0); +} + +int +_kvm_minidump_kvatop(kvm_t *kd, u_long va, off_t *pa) +{ + + if (ISALIVE(kd)) { + _kvm_err(kd, 0, "kvm_kvatop called in live kernel!"); + return (0); + } + if (((struct vmstate *)kd->vmst)->hdr.version == 1) + return (_kvm_minidump_vatop_v1(kd, va, pa)); + else + return (_kvm_minidump_vatop(kd, va, pa)); +} diff --git a/lib/libkvm/kvm_minidump_arm.c b/lib/libkvm/kvm_minidump_arm.c new file mode 100644 index 0000000..f6147d0 --- /dev/null +++ b/lib/libkvm/kvm_minidump_arm.c @@ -0,0 +1,260 @@ +/*- + * Copyright (c) 2008 Semihalf, Grzegorz Bernacki + * Copyright (c) 2006 Peter Wemm + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions + * are met: + * 1. Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * 2. Redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in the + * documentation and/or other materials provided with the distribution. + * + * THIS SOFTWARE IS PROVIDED BY THE AUTHOR AND CONTRIBUTORS ``AS IS'' AND + * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + * ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE + * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL + * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS + * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) + * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT + * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY + * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF + * SUCH DAMAGE. + * + * From: FreeBSD: src/lib/libkvm/kvm_minidump_i386.c,v 1.2 2006/06/05 08:51:14 + */ + +#include <sys/cdefs.h> +__FBSDID("$FreeBSD$"); + +/* + * ARM machine dependent routines for kvm and minidumps. + */ + +#include <sys/param.h> +#include <sys/user.h> +#include <sys/proc.h> +#include <sys/stat.h> +#include <sys/mman.h> +#include <sys/fnv_hash.h> +#include <stdlib.h> +#include <string.h> +#include <unistd.h> +#include <nlist.h> +#include <kvm.h> + +#include <vm/vm.h> +#include <vm/vm_param.h> + +#include <machine/elf.h> +#include <machine/cpufunc.h> +#include <machine/minidump.h> + +#include <limits.h> + +#include "kvm_private.h" + +struct hpte { + struct hpte *next; + uint64_t pa; + int64_t off; +}; + +#define HPT_SIZE 1024 + +/* minidump must be the first field */ +struct vmstate { + int minidump; /* 1 = minidump mode */ + struct minidumphdr hdr; + void *hpt_head[HPT_SIZE]; + uint32_t *bitmap; + void *ptemap; +}; + +static void +hpt_insert(kvm_t *kd, uint64_t pa, int64_t off) +{ + struct hpte *hpte; + uint32_t fnv = FNV1_32_INIT; + + fnv = fnv_32_buf(&pa, sizeof(pa), fnv); + fnv &= (HPT_SIZE - 1); + hpte = malloc(sizeof(*hpte)); + hpte->pa = pa; + hpte->off = off; + hpte->next = kd->vmst->hpt_head[fnv]; + kd->vmst->hpt_head[fnv] = hpte; +} + +static int64_t +hpt_find(kvm_t *kd, uint64_t pa) +{ + struct hpte *hpte; + uint32_t fnv = FNV1_32_INIT; + + fnv = fnv_32_buf(&pa, sizeof(pa), fnv); + fnv &= (HPT_SIZE - 1); + for (hpte = kd->vmst->hpt_head[fnv]; hpte != NULL; hpte = hpte->next) + if (pa == hpte->pa) + return (hpte->off); + + return (-1); +} + +static int +inithash(kvm_t *kd, uint32_t *base, int len, off_t off) +{ + uint64_t idx, pa; + uint32_t bit, bits; + + for (idx = 0; idx < len / sizeof(*base); idx++) { + bits = base[idx]; + while (bits) { + bit = ffs(bits) - 1; + bits &= ~(1ul << bit); + pa = (idx * sizeof(*base) * NBBY + bit) * PAGE_SIZE; + hpt_insert(kd, pa, off); + off += PAGE_SIZE; + } + } + return (off); +} + +void +_kvm_minidump_freevtop(kvm_t *kd) +{ + struct vmstate *vm = kd->vmst; + + if (vm->bitmap) + free(vm->bitmap); + if (vm->ptemap) + free(vm->ptemap); + free(vm); + kd->vmst = NULL; +} + +int +_kvm_minidump_initvtop(kvm_t *kd) +{ + struct vmstate *vmst; + off_t off; + + vmst = _kvm_malloc(kd, sizeof(*vmst)); + if (vmst == 0) { + _kvm_err(kd, kd->program, "cannot allocate vm"); + return (-1); + } + + kd->vmst = vmst; + vmst->minidump = 1; + + if (pread(kd->pmfd, &vmst->hdr, + sizeof(vmst->hdr), 0) != sizeof(vmst->hdr)) { + _kvm_err(kd, kd->program, "cannot read dump header"); + return (-1); + } + + if (strncmp(MINIDUMP_MAGIC, vmst->hdr.magic, + sizeof(vmst->hdr.magic)) != 0) { + _kvm_err(kd, kd->program, "not a minidump for this platform"); + return (-1); + } + if (vmst->hdr.version != MINIDUMP_VERSION) { + _kvm_err(kd, kd->program, "wrong minidump version. " + "Expected %d got %d", MINIDUMP_VERSION, vmst->hdr.version); + return (-1); + } + + /* Skip header and msgbuf */ + off = PAGE_SIZE + round_page(vmst->hdr.msgbufsize); + + vmst->bitmap = _kvm_malloc(kd, vmst->hdr.bitmapsize); + if (vmst->bitmap == NULL) { + _kvm_err(kd, kd->program, "cannot allocate %d bytes for " + "bitmap", vmst->hdr.bitmapsize); + return (-1); + } + + if (pread(kd->pmfd, vmst->bitmap, vmst->hdr.bitmapsize, off) != + (ssize_t)vmst->hdr.bitmapsize) { + _kvm_err(kd, kd->program, "cannot read %d bytes for page bitmap", + vmst->hdr.bitmapsize); + return (-1); + } + off += round_page(vmst->hdr.bitmapsize); + + vmst->ptemap = _kvm_malloc(kd, vmst->hdr.ptesize); + if (vmst->ptemap == NULL) { + _kvm_err(kd, kd->program, "cannot allocate %d bytes for " + "ptemap", vmst->hdr.ptesize); + return (-1); + } + + if (pread(kd->pmfd, vmst->ptemap, vmst->hdr.ptesize, off) != + (ssize_t)vmst->hdr.ptesize) { + _kvm_err(kd, kd->program, "cannot read %d bytes for ptemap", + vmst->hdr.ptesize); + return (-1); + } + + off += vmst->hdr.ptesize; + + /* Build physical address hash table for sparse pages */ + inithash(kd, vmst->bitmap, vmst->hdr.bitmapsize, off); + + return (0); +} + +int +_kvm_minidump_kvatop(kvm_t *kd, u_long va, off_t *pa) +{ + struct vmstate *vm; + pt_entry_t pte; + u_long offset, pteindex, a; + off_t ofs; + uint32_t *ptemap; + + if (ISALIVE(kd)) { + _kvm_err(kd, 0, "kvm_kvatop called in live kernel!"); + return (0); + } + + vm = kd->vmst; + ptemap = vm->ptemap; + + if (va >= vm->hdr.kernbase) { + pteindex = (va - vm->hdr.kernbase) >> PAGE_SHIFT; + pte = ptemap[pteindex]; + if (!pte) { + _kvm_err(kd, kd->program, "_kvm_vatop: pte not valid"); + goto invalid; + } + if ((pte & L2_TYPE_MASK) == L2_TYPE_L) { + offset = va & L2_L_OFFSET; + a = pte & L2_L_FRAME; + } else if ((pte & L2_TYPE_MASK) == L2_TYPE_S) { + offset = va & L2_S_OFFSET; + a = pte & L2_S_FRAME; + } else + goto invalid; + + ofs = hpt_find(kd, a); + if (ofs == -1) { + _kvm_err(kd, kd->program, "_kvm_vatop: physical " + "address 0x%lx not in minidump", a); + goto invalid; + } + + *pa = ofs + offset; + return (PAGE_SIZE - offset); + + } else + _kvm_err(kd, kd->program, "_kvm_vatop: virtual address 0x%lx " + "not minidumped", va); + +invalid: + _kvm_err(kd, 0, "invalid address (0x%lx)", va); + return (0); +} diff --git a/lib/libkvm/kvm_minidump_i386.c b/lib/libkvm/kvm_minidump_i386.c new file mode 100644 index 0000000..5850a55 --- /dev/null +++ b/lib/libkvm/kvm_minidump_i386.c @@ -0,0 +1,291 @@ +/*- + * Copyright (c) 2006 Peter Wemm + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions + * are met: + * 1. Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * 2. Redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in the + * documentation and/or other materials provided with the distribution. + * + * THIS SOFTWARE IS PROVIDED BY THE AUTHOR AND CONTRIBUTORS ``AS IS'' AND + * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + * ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE + * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL + * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS + * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) + * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT + * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY + * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF + * SUCH DAMAGE. + */ + +#include <sys/cdefs.h> +__FBSDID("$FreeBSD$"); + +/* + * AMD64 machine dependent routines for kvm and minidumps. + */ + +#include <sys/param.h> +#include <sys/user.h> +#include <sys/proc.h> +#include <sys/stat.h> +#include <sys/mman.h> +#include <sys/fnv_hash.h> +#include <stdlib.h> +#include <string.h> +#include <unistd.h> +#include <nlist.h> +#include <kvm.h> + +#include <vm/vm.h> +#include <vm/vm_param.h> + +#include <machine/elf.h> +#include <machine/cpufunc.h> +#include <machine/minidump.h> + +#include <limits.h> + +#include "kvm_private.h" + +#define PG_FRAME_PAE (~((uint64_t)PAGE_MASK)) + +struct hpte { + struct hpte *next; + uint64_t pa; + int64_t off; +}; + +#define HPT_SIZE 1024 + +/* minidump must be the first item! */ +struct vmstate { + int minidump; /* 1 = minidump mode */ + struct minidumphdr hdr; + void *hpt_head[HPT_SIZE]; + uint32_t *bitmap; + void *ptemap; +}; + +static void +hpt_insert(kvm_t *kd, uint64_t pa, int64_t off) +{ + struct hpte *hpte; + uint32_t fnv = FNV1_32_INIT; + + fnv = fnv_32_buf(&pa, sizeof(pa), fnv); + fnv &= (HPT_SIZE - 1); + hpte = malloc(sizeof(*hpte)); + hpte->pa = pa; + hpte->off = off; + hpte->next = kd->vmst->hpt_head[fnv]; + kd->vmst->hpt_head[fnv] = hpte; +} + +static int64_t +hpt_find(kvm_t *kd, uint64_t pa) +{ + struct hpte *hpte; + uint32_t fnv = FNV1_32_INIT; + + fnv = fnv_32_buf(&pa, sizeof(pa), fnv); + fnv &= (HPT_SIZE - 1); + for (hpte = kd->vmst->hpt_head[fnv]; hpte != NULL; hpte = hpte->next) { + if (pa == hpte->pa) + return (hpte->off); + } + return (-1); +} + +static int +inithash(kvm_t *kd, uint32_t *base, int len, off_t off) +{ + uint64_t idx; + uint32_t bit, bits; + uint64_t pa; + + for (idx = 0; idx < len / sizeof(*base); idx++) { + bits = base[idx]; + while (bits) { + bit = bsfl(bits); + bits &= ~(1ul << bit); + pa = (idx * sizeof(*base) * NBBY + bit) * PAGE_SIZE; + hpt_insert(kd, pa, off); + off += PAGE_SIZE; + } + } + return (off); +} + +void +_kvm_minidump_freevtop(kvm_t *kd) +{ + struct vmstate *vm = kd->vmst; + + if (vm->bitmap) + free(vm->bitmap); + if (vm->ptemap) + free(vm->ptemap); + free(vm); + kd->vmst = NULL; +} + +int +_kvm_minidump_initvtop(kvm_t *kd) +{ + struct vmstate *vmst; + off_t off; + + vmst = _kvm_malloc(kd, sizeof(*vmst)); + if (vmst == 0) { + _kvm_err(kd, kd->program, "cannot allocate vm"); + return (-1); + } + kd->vmst = vmst; + vmst->minidump = 1; + if (pread(kd->pmfd, &vmst->hdr, sizeof(vmst->hdr), 0) != + sizeof(vmst->hdr)) { + _kvm_err(kd, kd->program, "cannot read dump header"); + return (-1); + } + if (strncmp(MINIDUMP_MAGIC, vmst->hdr.magic, sizeof(vmst->hdr.magic)) != 0) { + _kvm_err(kd, kd->program, "not a minidump for this platform"); + return (-1); + } + if (vmst->hdr.version != MINIDUMP_VERSION) { + _kvm_err(kd, kd->program, "wrong minidump version. expected %d got %d", + MINIDUMP_VERSION, vmst->hdr.version); + return (-1); + } + + /* Skip header and msgbuf */ + off = PAGE_SIZE + round_page(vmst->hdr.msgbufsize); + + vmst->bitmap = _kvm_malloc(kd, vmst->hdr.bitmapsize); + if (vmst->bitmap == NULL) { + _kvm_err(kd, kd->program, "cannot allocate %d bytes for bitmap", vmst->hdr.bitmapsize); + return (-1); + } + if (pread(kd->pmfd, vmst->bitmap, vmst->hdr.bitmapsize, off) != + (ssize_t)vmst->hdr.bitmapsize) { + _kvm_err(kd, kd->program, "cannot read %d bytes for page bitmap", vmst->hdr.bitmapsize); + return (-1); + } + off += round_page(vmst->hdr.bitmapsize); + + vmst->ptemap = _kvm_malloc(kd, vmst->hdr.ptesize); + if (vmst->ptemap == NULL) { + _kvm_err(kd, kd->program, "cannot allocate %d bytes for ptemap", vmst->hdr.ptesize); + return (-1); + } + if (pread(kd->pmfd, vmst->ptemap, vmst->hdr.ptesize, off) != + (ssize_t)vmst->hdr.ptesize) { + _kvm_err(kd, kd->program, "cannot read %d bytes for ptemap", vmst->hdr.ptesize); + return (-1); + } + off += vmst->hdr.ptesize; + + /* build physical address hash table for sparse pages */ + inithash(kd, vmst->bitmap, vmst->hdr.bitmapsize, off); + + return (0); +} + +static int +_kvm_minidump_vatop_pae(kvm_t *kd, u_long va, off_t *pa) +{ + struct vmstate *vm; + uint64_t offset; + uint64_t pte; + u_long pteindex; + uint64_t a; + off_t ofs; + uint64_t *ptemap; + + vm = kd->vmst; + ptemap = vm->ptemap; + offset = va & (PAGE_SIZE - 1); + + if (va >= vm->hdr.kernbase) { + pteindex = (va - vm->hdr.kernbase) >> PAGE_SHIFT; + pte = ptemap[pteindex]; + if ((pte & PG_V) == 0) { + _kvm_err(kd, kd->program, "_kvm_vatop: pte not valid"); + goto invalid; + } + a = pte & PG_FRAME_PAE; + ofs = hpt_find(kd, a); + if (ofs == -1) { + _kvm_err(kd, kd->program, "_kvm_vatop: physical address 0x%llx not in minidump", a); + goto invalid; + } + *pa = ofs + offset; + return (PAGE_SIZE - offset); + } else { + _kvm_err(kd, kd->program, "_kvm_vatop: virtual address 0x%lx not minidumped", va); + goto invalid; + } + +invalid: + _kvm_err(kd, 0, "invalid address (0x%lx)", va); + return (0); +} + +static int +_kvm_minidump_vatop(kvm_t *kd, u_long va, off_t *pa) +{ + struct vmstate *vm; + u_long offset; + pt_entry_t pte; + u_long pteindex; + u_long a; + off_t ofs; + uint32_t *ptemap; + + vm = kd->vmst; + ptemap = vm->ptemap; + offset = va & (PAGE_SIZE - 1); + + if (va >= vm->hdr.kernbase) { + pteindex = (va - vm->hdr.kernbase) >> PAGE_SHIFT; + pte = ptemap[pteindex]; + if ((pte & PG_V) == 0) { + _kvm_err(kd, kd->program, "_kvm_vatop: pte not valid"); + goto invalid; + } + a = pte & PG_FRAME; + ofs = hpt_find(kd, a); + if (ofs == -1) { + _kvm_err(kd, kd->program, "_kvm_vatop: physical address 0x%lx not in minidump", a); + goto invalid; + } + *pa = ofs + offset; + return (PAGE_SIZE - offset); + } else { + _kvm_err(kd, kd->program, "_kvm_vatop: virtual address 0x%lx not minidumped", va); + goto invalid; + } + +invalid: + _kvm_err(kd, 0, "invalid address (0x%lx)", va); + return (0); +} + +int +_kvm_minidump_kvatop(kvm_t *kd, u_long va, off_t *pa) +{ + + if (ISALIVE(kd)) { + _kvm_err(kd, 0, "kvm_kvatop called in live kernel!"); + return (0); + } + if (kd->vmst->hdr.paemode) + return (_kvm_minidump_vatop_pae(kd, va, pa)); + else + return (_kvm_minidump_vatop(kd, va, pa)); +} diff --git a/lib/libkvm/kvm_minidump_mips.c b/lib/libkvm/kvm_minidump_mips.c new file mode 100644 index 0000000..7161115 --- /dev/null +++ b/lib/libkvm/kvm_minidump_mips.c @@ -0,0 +1,273 @@ +/*- + * Copyright (c) 2010 Oleksandr Tymoshenko + * Copyright (c) 2008 Semihalf, Grzegorz Bernacki + * Copyright (c) 2006 Peter Wemm + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions + * are met: + * 1. Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * 2. Redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in the + * documentation and/or other materials provided with the distribution. + * + * THIS SOFTWARE IS PROVIDED BY THE AUTHOR AND CONTRIBUTORS ``AS IS'' AND + * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + * ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE + * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL + * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS + * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) + * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT + * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY + * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF + * SUCH DAMAGE. + * + * From: FreeBSD: src/lib/libkvm/kvm_minidump_arm.c r214223 + */ + +#include <sys/cdefs.h> +__FBSDID("$FreeBSD$"); + +/* + * MIPS machine dependent routines for kvm and minidumps. + */ + +#include <sys/param.h> +#include <sys/user.h> +#include <sys/proc.h> +#include <sys/stat.h> +#include <sys/mman.h> +#include <sys/fnv_hash.h> +#include <stdlib.h> +#include <string.h> +#include <unistd.h> +#include <nlist.h> +#include <kvm.h> + +#include <vm/vm.h> +#include <vm/vm_param.h> + +#include <machine/elf.h> +#include <machine/cpufunc.h> +#include <machine/minidump.h> + +#include <limits.h> + +#include "kvm_private.h" + +struct hpte { + struct hpte *next; + uint64_t pa; + int64_t off; +}; + +#define HPT_SIZE 1024 + +/* minidump must be the first field */ +struct vmstate { + int minidump; /* 1 = minidump mode */ + struct minidumphdr hdr; + void *hpt_head[HPT_SIZE]; + uint32_t *bitmap; + void *ptemap; +}; + +static void +hpt_insert(kvm_t *kd, uint64_t pa, int64_t off) +{ + struct hpte *hpte; + uint32_t fnv = FNV1_32_INIT; + + fnv = fnv_32_buf(&pa, sizeof(pa), fnv); + fnv &= (HPT_SIZE - 1); + hpte = malloc(sizeof(*hpte)); + hpte->pa = pa; + hpte->off = off; + hpte->next = kd->vmst->hpt_head[fnv]; + kd->vmst->hpt_head[fnv] = hpte; +} + +static int64_t +hpt_find(kvm_t *kd, uint64_t pa) +{ + struct hpte *hpte; + uint32_t fnv = FNV1_32_INIT; + + fnv = fnv_32_buf(&pa, sizeof(pa), fnv); + fnv &= (HPT_SIZE - 1); + for (hpte = kd->vmst->hpt_head[fnv]; hpte != NULL; hpte = hpte->next) + if (pa == hpte->pa) + return (hpte->off); + + return (-1); +} + +static int +inithash(kvm_t *kd, uint32_t *base, int len, off_t off) +{ + uint64_t idx, pa; + uint32_t bit, bits; + + for (idx = 0; idx < len / sizeof(*base); idx++) { + bits = base[idx]; + while (bits) { + bit = ffs(bits) - 1; + bits &= ~(1ul << bit); + pa = (idx * sizeof(*base) * NBBY + bit) * PAGE_SIZE; + hpt_insert(kd, pa, off); + off += PAGE_SIZE; + } + } + + return (off); +} + +void +_kvm_minidump_freevtop(kvm_t *kd) +{ + struct vmstate *vm = kd->vmst; + + if (vm->bitmap) + free(vm->bitmap); + if (vm->ptemap) + free(vm->ptemap); + free(vm); + kd->vmst = NULL; +} + +int +_kvm_minidump_initvtop(kvm_t *kd) +{ + struct vmstate *vmst; + off_t off; + + vmst = _kvm_malloc(kd, sizeof(*vmst)); + if (vmst == 0) { + _kvm_err(kd, kd->program, "cannot allocate vm"); + return (-1); + } + + kd->vmst = vmst; + vmst->minidump = 1; + + off = lseek(kd->pmfd, 0, SEEK_CUR); + if (pread(kd->pmfd, &vmst->hdr, + sizeof(vmst->hdr), 0) != sizeof(vmst->hdr)) { + _kvm_err(kd, kd->program, "cannot read dump header"); + return (-1); + } + + if (strncmp(MINIDUMP_MAGIC, vmst->hdr.magic, + sizeof(vmst->hdr.magic)) != 0) { + _kvm_err(kd, kd->program, "not a minidump for this platform"); + return (-1); + } + if (vmst->hdr.version != MINIDUMP_VERSION) { + _kvm_err(kd, kd->program, "wrong minidump version. " + "Expected %d got %d", MINIDUMP_VERSION, vmst->hdr.version); + return (-1); + } + + /* Skip header and msgbuf */ + off = PAGE_SIZE + round_page(vmst->hdr.msgbufsize); + + vmst->bitmap = _kvm_malloc(kd, vmst->hdr.bitmapsize); + if (vmst->bitmap == NULL) { + _kvm_err(kd, kd->program, "cannot allocate %d bytes for " + "bitmap", vmst->hdr.bitmapsize); + return (-1); + } + + if (pread(kd->pmfd, vmst->bitmap, vmst->hdr.bitmapsize, off) != + (ssize_t)vmst->hdr.bitmapsize) { + _kvm_err(kd, kd->program, "cannot read %d bytes for page bitmap", + vmst->hdr.bitmapsize); + return (-1); + } + off += round_page(vmst->hdr.bitmapsize); + + vmst->ptemap = _kvm_malloc(kd, vmst->hdr.ptesize); + if (vmst->ptemap == NULL) { + _kvm_err(kd, kd->program, "cannot allocate %d bytes for " + "ptemap", vmst->hdr.ptesize); + return (-1); + } + + if (pread(kd->pmfd, vmst->ptemap, vmst->hdr.ptesize, off) != + (ssize_t)vmst->hdr.ptesize) { + _kvm_err(kd, kd->program, "cannot read %d bytes for ptemap", + vmst->hdr.ptesize); + return (-1); + } + + off += vmst->hdr.ptesize; + + /* Build physical address hash table for sparse pages */ + inithash(kd, vmst->bitmap, vmst->hdr.bitmapsize, off); + + return (0); +} + +int +_kvm_minidump_kvatop(kvm_t *kd, u_long va, off_t *pa) +{ + struct vmstate *vm; + pt_entry_t pte; + u_long offset, pteindex, a; + off_t ofs; + pt_entry_t *ptemap; + + if (ISALIVE(kd)) { + _kvm_err(kd, 0, "kvm_kvatop called in live kernel!"); + return (0); + } + + offset = va & PAGE_MASK; + /* Operate with page-aligned address */ + va &= ~PAGE_MASK; + + vm = kd->vmst; + ptemap = vm->ptemap; + +#if defined(__mips_n64) + if (va >= MIPS_XKPHYS_START && va < MIPS_XKPHYS_END) + a = (MIPS_XKPHYS_TO_PHYS(va)); + else +#endif + if (va >= (u_long)MIPS_KSEG0_START && va < (u_long)MIPS_KSEG0_END) + a = (MIPS_KSEG0_TO_PHYS(va)); + else if (va >= (u_long)MIPS_KSEG1_START && va < (u_long)MIPS_KSEG1_END) + a = (MIPS_KSEG1_TO_PHYS(va)); + else if (va >= vm->hdr.kernbase) { + pteindex = (va - vm->hdr.kernbase) >> PAGE_SHIFT; + pte = ptemap[pteindex]; + if (!pte) { + _kvm_err(kd, kd->program, "_kvm_vatop: pte not valid"); + goto invalid; + } + + a = TLBLO_PTE_TO_PA(pte); + + } else { + _kvm_err(kd, kd->program, "_kvm_vatop: virtual address 0x%lx " + "not minidumped", va); + return (0); + } + + ofs = hpt_find(kd, a); + if (ofs == -1) { + _kvm_err(kd, kd->program, "_kvm_vatop: physical " + "address 0x%lx not in minidump", a); + goto invalid; + } + + *pa = ofs + offset; + return (PAGE_SIZE - offset); + + +invalid: + _kvm_err(kd, 0, "invalid address (0x%lx)", va); + return (0); +} diff --git a/lib/libkvm/kvm_mips.c b/lib/libkvm/kvm_mips.c new file mode 100644 index 0000000..ad0834b --- /dev/null +++ b/lib/libkvm/kvm_mips.c @@ -0,0 +1,120 @@ +/*- + * Copyright (C) 2006 Bruce M. Simpson. + * All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions + * are met: + * 1. Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * 2. Redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in the + * documentation and/or other materials provided with the distribution. + * 3. All advertising materials mentioning features or use of this software + * must display the following acknowledgement: + * This product includes software developed by Bruce M. Simpson. + * 4. The name of Bruce M. Simpson may not be used to endorse or promote products + * derived from this software without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY BRUCE M. SIMPSON ``AS IS'' AND ANY EXPRESS OR + * IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES + * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. + * IN NO EVENT SHALL BRUCE M. SIMPSON BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, + * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, + * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; + * OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, + * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR + * OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF + * ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + */ + +/* + * MIPS machine dependent routines for kvm. + */ + +#include <sys/cdefs.h> +__FBSDID("$FreeBSD$"); + +#include <sys/param.h> +#include <sys/elf32.h> +#include <sys/mman.h> + +#include <vm/vm.h> +#include <vm/vm_param.h> +#include <vm/pmap.h> + +#include <machine/pmap.h> + +#include <db.h> +#include <limits.h> +#include <kvm.h> +#include <stdlib.h> +#include <string.h> +#include <unistd.h> + +#include "kvm_private.h" + +/* minidump must be the first item! */ +struct vmstate { + int minidump; /* 1 = minidump mode */ + void *mmapbase; + size_t mmapsize; +}; + +void +_kvm_freevtop(kvm_t *kd) +{ + if (kd->vmst != 0) { + if (kd->vmst->minidump) + return (_kvm_minidump_freevtop(kd)); + if (kd->vmst->mmapbase != NULL) + munmap(kd->vmst->mmapbase, kd->vmst->mmapsize); + free(kd->vmst); + kd->vmst = NULL; + } +} + +int +_kvm_initvtop(kvm_t *kd) +{ + char minihdr[8]; + + if (!kd->rawdump) { + if (pread(kd->pmfd, &minihdr, 8, 0) == 8) { + if (memcmp(&minihdr, "minidump", 8) == 0) + return (_kvm_minidump_initvtop(kd)); + } else { + _kvm_err(kd, kd->program, "cannot read header"); + return (-1); + } + } + + _kvm_err(kd, 0, "_kvm_initvtop: Unsupported image type"); + return (-1); +} + +int +_kvm_kvatop(kvm_t *kd, u_long va, off_t *pa) +{ + + if (kd->vmst->minidump) + return _kvm_minidump_kvatop(kd, va, pa); + + + _kvm_err(kd, 0, "_kvm_kvatop: Unsupported image type"); + return (0); +} + +/* + * Machine-dependent initialization for ALL open kvm descriptors, + * not just those for a kernel crash dump. Some architectures + * have to deal with these NOT being constants! (i.e. m68k) + */ +#ifdef FBSD_NOT_YET +int +_kvm_mdopen(kvm_t *kd __unused) +{ + + return (0); +} +#endif diff --git a/lib/libkvm/kvm_nlist.3 b/lib/libkvm/kvm_nlist.3 new file mode 100644 index 0000000..a151a3b --- /dev/null +++ b/lib/libkvm/kvm_nlist.3 @@ -0,0 +1,85 @@ +.\" Copyright (c) 1992, 1993 +.\" The Regents of the University of California. All rights reserved. +.\" +.\" This code is derived from software developed by the Computer Systems +.\" Engineering group at Lawrence Berkeley Laboratory under DARPA contract +.\" BG 91-66 and contributed to Berkeley. +.\" +.\" Redistribution and use in source and binary forms, with or without +.\" modification, are permitted provided that the following conditions +.\" are met: +.\" 1. Redistributions of source code must retain the above copyright +.\" notice, this list of conditions and the following disclaimer. +.\" 2. Redistributions in binary form must reproduce the above copyright +.\" notice, this list of conditions and the following disclaimer in the +.\" documentation and/or other materials provided with the distribution. +.\" 4. Neither the name of the University nor the names of its contributors +.\" may be used to endorse or promote products derived from this software +.\" without specific prior written permission. +.\" +.\" THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND +.\" ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE +.\" IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE +.\" ARE DISCLAIMED. IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE +.\" FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL +.\" DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS +.\" OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) +.\" HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT +.\" LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY +.\" OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF +.\" SUCH DAMAGE. +.\" +.\" @(#)kvm_nlist.3 8.1 (Berkeley) 6/4/93 +.\" $FreeBSD$ +.\" +.Dd June 4, 1993 +.Dt KVM_NLIST 3 +.Os +.Sh NAME +.Nm kvm_nlist +.Nd retrieve symbol table names from a kernel image +.Sh LIBRARY +.Lb libkvm +.Sh SYNOPSIS +.In kvm.h +.In nlist.h +.Ft int +.Fn kvm_nlist "kvm_t *kd" "struct nlist *nl" +.Sh DESCRIPTION +The +.Fn kvm_nlist +function retrieves the symbol table entries indicated by the name list argument +.Fa \&nl . +This argument points to an array of nlist structures, terminated by +an entry whose n_name field is +.Dv NULL +(see +.Xr nlist 3 ) . +Each symbol is looked up using the n_name field, and if found, the +corresponding n_type and n_value fields are filled in. +These fields are set +to 0 if the symbol is not found. +.Pp +The +.Xr kldsym 2 +system call is used to locate the symbol. +This is a less than perfect +emulation of the nlist values but has the advantage of being aware of kernel +modules and is reasonably fast. +.Sh RETURN VALUES +The +.Fn kvm_nlist +function returns the number of invalid entries found. +If the kernel symbol table was unreadable, -1 is returned. +.Sh SEE ALSO +.Xr kldsym 2 , +.Xr kvm 3 , +.Xr kvm_close 3 , +.Xr kvm_getargv 3 , +.Xr kvm_getenvv 3 , +.Xr kvm_geterr 3 , +.Xr kvm_getprocs 3 , +.Xr kvm_open 3 , +.Xr kvm_openfiles 3 , +.Xr kvm_read 3 , +.Xr kvm_write 3 diff --git a/lib/libkvm/kvm_open.3 b/lib/libkvm/kvm_open.3 new file mode 100644 index 0000000..1b62482 --- /dev/null +++ b/lib/libkvm/kvm_open.3 @@ -0,0 +1,205 @@ +.\" Copyright (c) 1992, 1993 +.\" The Regents of the University of California. All rights reserved. +.\" +.\" This code is derived from software developed by the Computer Systems +.\" Engineering group at Lawrence Berkeley Laboratory under DARPA contract +.\" BG 91-66 and contributed to Berkeley. +.\" +.\" Redistribution and use in source and binary forms, with or without +.\" modification, are permitted provided that the following conditions +.\" are met: +.\" 1. Redistributions of source code must retain the above copyright +.\" notice, this list of conditions and the following disclaimer. +.\" 2. Redistributions in binary form must reproduce the above copyright +.\" notice, this list of conditions and the following disclaimer in the +.\" documentation and/or other materials provided with the distribution. +.\" 4. Neither the name of the University nor the names of its contributors +.\" may be used to endorse or promote products derived from this software +.\" without specific prior written permission. +.\" +.\" THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND +.\" ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE +.\" IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE +.\" ARE DISCLAIMED. IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE +.\" FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL +.\" DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS +.\" OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) +.\" HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT +.\" LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY +.\" OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF +.\" SUCH DAMAGE. +.\" +.\" @(#)kvm_open.3 8.3 (Berkeley) 4/19/94 +.\" $FreeBSD$ +.\" +.Dd January 29, 2004 +.Dt KVM_OPEN 3 +.Os +.Sh NAME +.Nm kvm_open , +.Nm kvm_openfiles , +.Nm kvm_close +.Nd initialize kernel virtual memory access +.Sh LIBRARY +.Lb libkvm +.Sh SYNOPSIS +.In fcntl.h +.In kvm.h +.Ft kvm_t * +.Fn kvm_open "const char *execfile" "const char *corefile" "const char *swapfile" "int flags" "const char *errstr" +.Ft kvm_t * +.Fn kvm_openfiles "const char *execfile" "const char *corefile" "const char *swapfile" "int flags" "char *errbuf" +.Ft int +.Fn kvm_close "kvm_t *kd" +.Sh DESCRIPTION +The functions +.Fn kvm_open +and +.Fn kvm_openfiles +return a descriptor used to access kernel virtual memory +via the +.Xr kvm 3 +library routines. +Both active kernels and crash dumps are accessible +through this interface. +.Pp +The +.Fa execfile +argument is the executable image of the kernel being examined. +This file must contain a symbol table. +If this argument is +.Dv NULL , +the currently running system is assumed, +as determined from +.Xr getbootfile 3 . +.Pp +The +.Fa corefile +argument is the kernel memory device file. +It can be either +.Pa /dev/mem +or a crash dump core generated by +.Xr savecore 8 . +If +.Fa corefile +is +.Dv NULL , +the default indicated by +.Dv _PATH_MEM +from +.In paths.h +is used. +It can also be set to a special value +.Pa /dev/null +by utilities like +.Xr ps 1 +that do not directly access kernel memory. +.Pp +The +.Fa swapfile +argument is currently unused. +.Pp +The +.Fa flags +argument indicates read/write access as in +.Xr open 2 +and applies only to the core file. +Only +.Dv O_RDONLY , +.Dv O_WRONLY , +and +.Dv O_RDWR +are permitted. +.Pp +There are two open routines which differ only with respect to +the error mechanism. +One provides backward compatibility with the SunOS kvm library, while the +other provides an improved error reporting framework. +.Pp +The +.Fn kvm_open +function is the Sun kvm compatible open call. +Here, the +.Fa errstr +argument indicates how errors should be handled. +If it is +.Dv NULL , +no errors are reported and the application cannot know the +specific nature of the failed kvm call. +If it is not +.Dv NULL , +errors are printed to +.Dv stderr +with +.Fa errstr +prepended to the message, as in +.Xr perror 3 . +Normally, the name of the program is used here. +The string is assumed to persist at least until the corresponding +.Fn kvm_close +call. +.Pp +The +.Fn kvm_openfiles +function provides +.Bx +style error reporting. +Here, error messages are not printed out by the library. +Instead, the application obtains the error message +corresponding to the most recent kvm library call using +.Fn kvm_geterr +(see +.Xr kvm_geterr 3 ) . +The results are undefined if the most recent kvm call did not produce +an error. +Since +.Fn kvm_geterr +requires a kvm descriptor, but the open routines return +.Dv NULL +on failure, +.Fn kvm_geterr +cannot be used to get the error message if open fails. +Thus, +.Fn kvm_openfiles +will place any error message in the +.Fa errbuf +argument. +This buffer should be _POSIX2_LINE_MAX characters large (from +<limits.h>). +.Sh RETURN VALUES +The +.Fn kvm_open +and +.Fn kvm_openfiles +functions both return a descriptor to be used +in all subsequent kvm library calls. +The library is fully re-entrant. +On failure, +.Dv NULL +is returned, in which case +.Fn kvm_openfiles +writes the error message into +.Fa errbuf . +.Pp +The +.Fn kvm_close +function returns 0 on success and -1 on failure. +.Sh SEE ALSO +.Xr open 2 , +.Xr kvm 3 , +.Xr kvm_getargv 3 , +.Xr kvm_getenvv 3 , +.Xr kvm_geterr 3 , +.Xr kvm_getprocs 3 , +.Xr kvm_nlist 3 , +.Xr kvm_read 3 , +.Xr kvm_write 3 , +.Xr kmem 4 , +.Xr mem 4 +.Sh BUGS +There should not be two open calls. +The ill-defined error semantics +of the Sun library and the desire to have a backward-compatible library +for +.Bx +left little choice. diff --git a/lib/libkvm/kvm_pcpu.c b/lib/libkvm/kvm_pcpu.c new file mode 100644 index 0000000..d7108b4 --- /dev/null +++ b/lib/libkvm/kvm_pcpu.c @@ -0,0 +1,291 @@ +/*- + * Copyright (c) 2010 Juniper Networks, Inc. + * Copyright (c) 2009 Robert N. M. Watson + * Copyright (c) 2009 Bjoern A. Zeeb <bz@FreeBSD.org> + * Copyright (c) 2008 Yahoo!, Inc. + * All rights reserved. + * + * Written by: John Baldwin <jhb@FreeBSD.org> + * + * This software was developed by Robert N. M. Watson under contract + * to Juniper Networks, Inc. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions + * are met: + * 1. Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * 2. Redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in the + * documentation and/or other materials provided with the distribution. + * 3. Neither the name of the author nor the names of any co-contributors + * may be used to endorse or promote products derived from this software + * without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE AUTHOR AND CONTRIBUTORS ``AS IS'' AND + * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + * ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE + * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL + * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS + * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) + * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT + * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY + * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF + * SUCH DAMAGE. + */ + +#include <sys/cdefs.h> +__FBSDID("$FreeBSD$"); + +#include <sys/param.h> +#include <sys/pcpu.h> +#include <sys/sysctl.h> +#include <kvm.h> +#include <limits.h> +#include <stdlib.h> + +#include "kvm_private.h" + +static struct nlist kvm_pcpu_nl[] = { + { .n_name = "_cpuid_to_pcpu" }, + { .n_name = "_mp_maxcpus" }, + { .n_name = NULL }, +}; + +/* + * Kernel per-CPU data state. We cache this stuff on the first + * access. + * + * XXXRW: Possibly, this (and kvmpcpu_nl) should be per-kvm_t, in case the + * consumer has multiple handles in flight to differently configured + * kernels/crashdumps. + */ +static void **pcpu_data; +static int maxcpu; + +#define NL_CPUID_TO_PCPU 0 +#define NL_MP_MAXCPUS 1 + +static int +_kvm_pcpu_init(kvm_t *kd) +{ + size_t len; + int max; + void *data; + + if (kvm_nlist(kd, kvm_pcpu_nl) < 0) + return (-1); + if (kvm_pcpu_nl[NL_CPUID_TO_PCPU].n_value == 0) { + _kvm_err(kd, kd->program, "unable to find cpuid_to_pcpu"); + return (-1); + } + if (kvm_pcpu_nl[NL_MP_MAXCPUS].n_value == 0) { + _kvm_err(kd, kd->program, "unable to find mp_maxcpus"); + return (-1); + } + if (kvm_read(kd, kvm_pcpu_nl[NL_MP_MAXCPUS].n_value, &max, + sizeof(max)) != sizeof(max)) { + _kvm_err(kd, kd->program, "cannot read mp_maxcpus"); + return (-1); + } + len = max * sizeof(void *); + data = malloc(len); + if (data == NULL) { + _kvm_err(kd, kd->program, "out of memory"); + return (-1); + } + if (kvm_read(kd, kvm_pcpu_nl[NL_CPUID_TO_PCPU].n_value, data, len) != + (ssize_t)len) { + _kvm_err(kd, kd->program, "cannot read cpuid_to_pcpu array"); + free(data); + return (-1); + } + pcpu_data = data; + maxcpu = max; + return (0); +} + +static void +_kvm_pcpu_clear(void) +{ + + maxcpu = 0; + free(pcpu_data); + pcpu_data = NULL; +} + +void * +kvm_getpcpu(kvm_t *kd, int cpu) +{ + char *buf; + + if (kd == NULL) { + _kvm_pcpu_clear(); + return (NULL); + } + + if (maxcpu == 0) + if (_kvm_pcpu_init(kd) < 0) + return ((void *)-1); + + if (cpu >= maxcpu || pcpu_data[cpu] == NULL) + return (NULL); + + buf = malloc(sizeof(struct pcpu)); + if (buf == NULL) { + _kvm_err(kd, kd->program, "out of memory"); + return ((void *)-1); + } + if (kvm_read(kd, (uintptr_t)pcpu_data[cpu], buf, + sizeof(struct pcpu)) != sizeof(struct pcpu)) { + _kvm_err(kd, kd->program, "unable to read per-CPU data"); + free(buf); + return ((void *)-1); + } + return (buf); +} + +int +kvm_getmaxcpu(kvm_t *kd) +{ + + if (kd == NULL) { + _kvm_pcpu_clear(); + return (0); + } + + if (maxcpu == 0) + if (_kvm_pcpu_init(kd) < 0) + return (-1); + return (maxcpu); +} + +static int +_kvm_dpcpu_setcpu(kvm_t *kd, u_int cpu, int report_error) +{ + + if (!kd->dpcpu_initialized) { + if (report_error) + _kvm_err(kd, kd->program, "%s: not initialized", + __func__); + return (-1); + } + if (cpu >= kd->dpcpu_maxcpus) { + if (report_error) + _kvm_err(kd, kd->program, "%s: CPU %u too big", + __func__, cpu); + return (-1); + } + if (kd->dpcpu_off[cpu] == 0) { + if (report_error) + _kvm_err(kd, kd->program, "%s: CPU %u not found", + __func__, cpu); + return (-1); + } + kd->dpcpu_curcpu = cpu; + kd->dpcpu_curoff = kd->dpcpu_off[cpu]; + return (0); +} + +/* + * Set up libkvm to handle dynamic per-CPU memory. + */ +static int +_kvm_dpcpu_init(kvm_t *kd) +{ + struct nlist nl[] = { +#define NLIST_START_SET_PCPU 0 + { .n_name = "___start_" DPCPU_SETNAME }, +#define NLIST_STOP_SET_PCPU 1 + { .n_name = "___stop_" DPCPU_SETNAME }, +#define NLIST_DPCPU_OFF 2 + { .n_name = "_dpcpu_off" }, +#define NLIST_MP_MAXCPUS 3 + { .n_name = "_mp_maxcpus" }, + { .n_name = NULL }, + }; + uintptr_t *dpcpu_off_buf; + size_t len; + u_int dpcpu_maxcpus; + + /* + * Locate and cache locations of important symbols using the internal + * version of _kvm_nlist, turning off initialization to avoid + * recursion in case of unresolveable symbols. + */ + if (_kvm_nlist(kd, nl, 0) != 0) + return (-1); + if (kvm_read(kd, nl[NLIST_MP_MAXCPUS].n_value, &dpcpu_maxcpus, + sizeof(dpcpu_maxcpus)) != sizeof(dpcpu_maxcpus)) + return (-1); + len = dpcpu_maxcpus * sizeof(*dpcpu_off_buf); + dpcpu_off_buf = malloc(len); + if (dpcpu_off_buf == NULL) + return (-1); + if (kvm_read(kd, nl[NLIST_DPCPU_OFF].n_value, dpcpu_off_buf, len) != + (ssize_t)len) { + free(dpcpu_off_buf); + return (-1); + } + kd->dpcpu_start = nl[NLIST_START_SET_PCPU].n_value; + kd->dpcpu_stop = nl[NLIST_STOP_SET_PCPU].n_value; + kd->dpcpu_maxcpus = dpcpu_maxcpus; + kd->dpcpu_off = dpcpu_off_buf; + kd->dpcpu_initialized = 1; + (void)_kvm_dpcpu_setcpu(kd, 0, 0); + return (0); +} + +/* + * Check whether the dpcpu module has been initialized sucessfully or not, + * initialize it if permitted. + */ +int +_kvm_dpcpu_initialized(kvm_t *kd, int intialize) +{ + + if (kd->dpcpu_initialized || !intialize) + return (kd->dpcpu_initialized); + + (void)_kvm_dpcpu_init(kd); + + return (kd->dpcpu_initialized); +} + +/* + * Check whether the value is within the dpcpu symbol range and only if so + * adjust the offset relative to the current offset. + */ +uintptr_t +_kvm_dpcpu_validaddr(kvm_t *kd, uintptr_t value) +{ + + if (value == 0) + return (value); + + if (!kd->dpcpu_initialized) + return (value); + + if (value < kd->dpcpu_start || value >= kd->dpcpu_stop) + return (value); + + return (kd->dpcpu_curoff + value); +} + +int +kvm_dpcpu_setcpu(kvm_t *kd, u_int cpu) +{ + int ret; + + if (!kd->dpcpu_initialized) { + ret = _kvm_dpcpu_init(kd); + if (ret != 0) { + _kvm_err(kd, kd->program, "%s: init failed", + __func__); + return (ret); + } + } + + return (_kvm_dpcpu_setcpu(kd, cpu, 1)); +} diff --git a/lib/libkvm/kvm_powerpc.c b/lib/libkvm/kvm_powerpc.c new file mode 100644 index 0000000..fa38021 --- /dev/null +++ b/lib/libkvm/kvm_powerpc.c @@ -0,0 +1,219 @@ +/*- + * Copyright (c) 2008, Juniper Networks, Inc. + * All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions + * are met: + * 1. Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * 2. Redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in the + * documentation and/or other materials provided with the distribution. + * 3. Neither the name of the author nor the names of any co-contributors + * may be used to endorse or promote products derived from this software + * without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR + * IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES + * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. + * IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT, + * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT + * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, + * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY + * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT + * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF + * THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + */ + +#include <sys/cdefs.h> +__FBSDID("$FreeBSD$"); + +#include <sys/param.h> +#include <sys/endian.h> +#include <sys/kerneldump.h> +#include <sys/mman.h> + +#include <vm/vm.h> + +#include <db.h> +#include <elf.h> +#include <limits.h> +#include <kvm.h> +#include <stdlib.h> +#include <string.h> + +#include "kvm_private.h" + +struct vmstate { + void *map; + size_t mapsz; + size_t dmphdrsz; + Elf32_Ehdr *eh; + Elf32_Phdr *ph; +}; + +static int +valid_elf_header(Elf32_Ehdr *eh) +{ + + if (!IS_ELF(*eh)) + return (0); + if (eh->e_ident[EI_CLASS] != ELFCLASS32) + return (0); + if (eh->e_ident[EI_DATA] != ELFDATA2MSB) + return (0); + if (eh->e_ident[EI_VERSION] != EV_CURRENT) + return (0); + if (eh->e_ident[EI_OSABI] != ELFOSABI_STANDALONE) + return (0); + if (be16toh(eh->e_type) != ET_CORE) + return (0); + if (be16toh(eh->e_machine) != EM_PPC) + return (0); + /* Can't think of anything else to check... */ + return (1); +} + +static size_t +dump_header_size(struct kerneldumpheader *dh) +{ + + if (strcmp(dh->magic, KERNELDUMPMAGIC) != 0) + return (0); + if (strcmp(dh->architecture, "powerpc") != 0) + return (0); + /* That should do it... */ + return (sizeof(*dh)); +} + +/* + * Map the ELF headers into the process' address space. We do this in two + * steps: first the ELF header itself and using that information the whole + * set of headers. + */ +static int +powerpc_maphdrs(kvm_t *kd) +{ + struct vmstate *vm; + size_t mapsz; + + vm = kd->vmst; + + vm->mapsz = PAGE_SIZE; + vm->map = mmap(NULL, vm->mapsz, PROT_READ, MAP_PRIVATE, kd->pmfd, 0); + if (vm->map == MAP_FAILED) { + _kvm_err(kd, kd->program, "cannot map corefile"); + return (-1); + } + vm->dmphdrsz = 0; + vm->eh = vm->map; + if (!valid_elf_header(vm->eh)) { + /* + * Hmmm, no ELF header. Maybe we still have a dump header. + * This is normal when the core file wasn't created by + * savecore(8), but instead was dumped over TFTP. We can + * easily skip the dump header... + */ + vm->dmphdrsz = dump_header_size(vm->map); + if (vm->dmphdrsz == 0) + goto inval; + vm->eh = (void *)((uintptr_t)vm->map + vm->dmphdrsz); + if (!valid_elf_header(vm->eh)) + goto inval; + } + mapsz = be16toh(vm->eh->e_phentsize) * be16toh(vm->eh->e_phnum) + + be32toh(vm->eh->e_phoff); + munmap(vm->map, vm->mapsz); + + /* Map all headers. */ + vm->mapsz = vm->dmphdrsz + mapsz; + vm->map = mmap(NULL, vm->mapsz, PROT_READ, MAP_PRIVATE, kd->pmfd, 0); + if (vm->map == MAP_FAILED) { + _kvm_err(kd, kd->program, "cannot map corefle headers"); + return (-1); + } + vm->eh = (void *)((uintptr_t)vm->map + vm->dmphdrsz); + vm->ph = (void *)((uintptr_t)vm->eh + be32toh(vm->eh->e_phoff)); + return (0); + + inval: + munmap(vm->map, vm->mapsz); + vm->map = MAP_FAILED; + _kvm_err(kd, kd->program, "invalid corefile"); + return (-1); +} + +/* + * Determine the offset within the corefile corresponding the virtual + * address. Return the number of contiguous bytes in the corefile or + * 0 when the virtual address is invalid. + */ +static size_t +powerpc_va2off(kvm_t *kd, u_long va, off_t *ofs) +{ + struct vmstate *vm = kd->vmst; + Elf32_Phdr *ph; + int nph; + + ph = vm->ph; + nph = be16toh(vm->eh->e_phnum); + while (nph && (va < be32toh(ph->p_vaddr) || + va >= be32toh(ph->p_vaddr) + be32toh(ph->p_memsz))) { + nph--; + ph = (void *)((uintptr_t)ph + be16toh(vm->eh->e_phentsize)); + } + if (nph == 0) + return (0); + + /* Segment found. Return file offset and range. */ + *ofs = vm->dmphdrsz + be32toh(ph->p_offset) + + (va - be32toh(ph->p_vaddr)); + return (be32toh(ph->p_memsz) - (va - be32toh(ph->p_vaddr))); +} + +void +_kvm_freevtop(kvm_t *kd) +{ + struct vmstate *vm = kd->vmst; + + if (vm == NULL) + return; + + if (vm->eh != MAP_FAILED) { + munmap(vm->eh, vm->mapsz); + vm->eh = MAP_FAILED; + } + free(vm); + kd->vmst = NULL; +} + +int +_kvm_initvtop(kvm_t *kd) +{ + + kd->vmst = (struct vmstate *)_kvm_malloc(kd, sizeof(*kd->vmst)); + if (kd->vmst == NULL) { + _kvm_err(kd, kd->program, "out of virtual memory"); + return (-1); + } + if (powerpc_maphdrs(kd) == -1) { + free(kd->vmst); + kd->vmst = NULL; + return (-1); + } + return (0); +} + +int +_kvm_kvatop(kvm_t *kd, u_long va, off_t *ofs) +{ + struct vmstate *vm; + + vm = kd->vmst; + if (vm->ph->p_paddr == ~0U) + return ((int)powerpc_va2off(kd, va, ofs)); + + _kvm_err(kd, kd->program, "Raw corefile not supported"); + return (0); +} diff --git a/lib/libkvm/kvm_powerpc64.c b/lib/libkvm/kvm_powerpc64.c new file mode 100644 index 0000000..f3a2b24 --- /dev/null +++ b/lib/libkvm/kvm_powerpc64.c @@ -0,0 +1,219 @@ +/*- + * Copyright (c) 2008, Juniper Networks, Inc. + * All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions + * are met: + * 1. Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * 2. Redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in the + * documentation and/or other materials provided with the distribution. + * 3. Neither the name of the author nor the names of any co-contributors + * may be used to endorse or promote products derived from this software + * without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR + * IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES + * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. + * IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT, + * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT + * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, + * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY + * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT + * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF + * THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + */ + +#include <sys/cdefs.h> +__FBSDID("$FreeBSD$"); + +#include <sys/param.h> +#include <sys/endian.h> +#include <sys/kerneldump.h> +#include <sys/mman.h> + +#include <vm/vm.h> + +#include <db.h> +#include <elf.h> +#include <limits.h> +#include <kvm.h> +#include <stdlib.h> +#include <string.h> + +#include "kvm_private.h" + +struct vmstate { + void *map; + size_t mapsz; + size_t dmphdrsz; + Elf64_Ehdr *eh; + Elf64_Phdr *ph; +}; + +static int +valid_elf_header(Elf64_Ehdr *eh) +{ + + if (!IS_ELF(*eh)) + return (0); + if (eh->e_ident[EI_CLASS] != ELFCLASS64) + return (0); + if (eh->e_ident[EI_DATA] != ELFDATA2MSB) + return (0); + if (eh->e_ident[EI_VERSION] != EV_CURRENT) + return (0); + if (eh->e_ident[EI_OSABI] != ELFOSABI_STANDALONE) + return (0); + if (be16toh(eh->e_type) != ET_CORE) + return (0); + if (be16toh(eh->e_machine) != EM_PPC64) + return (0); + /* Can't think of anything else to check... */ + return (1); +} + +static size_t +dump_header_size(struct kerneldumpheader *dh) +{ + + if (strcmp(dh->magic, KERNELDUMPMAGIC) != 0) + return (0); + if (strcmp(dh->architecture, "powerpc64") != 0) + return (0); + /* That should do it... */ + return (sizeof(*dh)); +} + +/* + * Map the ELF headers into the process' address space. We do this in two + * steps: first the ELF header itself and using that information the whole + * set of headers. + */ +static int +powerpc_maphdrs(kvm_t *kd) +{ + struct vmstate *vm; + size_t mapsz; + + vm = kd->vmst; + + vm->mapsz = PAGE_SIZE; + vm->map = mmap(NULL, vm->mapsz, PROT_READ, MAP_PRIVATE, kd->pmfd, 0); + if (vm->map == MAP_FAILED) { + _kvm_err(kd, kd->program, "cannot map corefile"); + return (-1); + } + vm->dmphdrsz = 0; + vm->eh = vm->map; + if (!valid_elf_header(vm->eh)) { + /* + * Hmmm, no ELF header. Maybe we still have a dump header. + * This is normal when the core file wasn't created by + * savecore(8), but instead was dumped over TFTP. We can + * easily skip the dump header... + */ + vm->dmphdrsz = dump_header_size(vm->map); + if (vm->dmphdrsz == 0) + goto inval; + vm->eh = (void *)((uintptr_t)vm->map + vm->dmphdrsz); + if (!valid_elf_header(vm->eh)) + goto inval; + } + mapsz = be16toh(vm->eh->e_phentsize) * be16toh(vm->eh->e_phnum) + + be64toh(vm->eh->e_phoff); + munmap(vm->map, vm->mapsz); + + /* Map all headers. */ + vm->mapsz = vm->dmphdrsz + mapsz; + vm->map = mmap(NULL, vm->mapsz, PROT_READ, MAP_PRIVATE, kd->pmfd, 0); + if (vm->map == MAP_FAILED) { + _kvm_err(kd, kd->program, "cannot map corefle headers"); + return (-1); + } + vm->eh = (void *)((uintptr_t)vm->map + vm->dmphdrsz); + vm->ph = (void *)((uintptr_t)vm->eh + be64toh(vm->eh->e_phoff)); + return (0); + + inval: + munmap(vm->map, vm->mapsz); + vm->map = MAP_FAILED; + _kvm_err(kd, kd->program, "invalid corefile"); + return (-1); +} + +/* + * Determine the offset within the corefile corresponding the virtual + * address. Return the number of contiguous bytes in the corefile or + * 0 when the virtual address is invalid. + */ +static size_t +powerpc64_va2off(kvm_t *kd, u_long va, off_t *ofs) +{ + struct vmstate *vm = kd->vmst; + Elf64_Phdr *ph; + int nph; + + ph = vm->ph; + nph = be16toh(vm->eh->e_phnum); + while (nph && (va < be64toh(ph->p_vaddr) || + va >= be64toh(ph->p_vaddr) + be64toh(ph->p_memsz))) { + nph--; + ph = (void *)((uintptr_t)ph + be16toh(vm->eh->e_phentsize)); + } + if (nph == 0) + return (0); + + /* Segment found. Return file offset and range. */ + *ofs = vm->dmphdrsz + be64toh(ph->p_offset) + + (va - be64toh(ph->p_vaddr)); + return (be64toh(ph->p_memsz) - (va - be64toh(ph->p_vaddr))); +} + +void +_kvm_freevtop(kvm_t *kd) +{ + struct vmstate *vm = kd->vmst; + + if (vm == NULL) + return; + + if (vm->eh != MAP_FAILED) { + munmap(vm->eh, vm->mapsz); + vm->eh = MAP_FAILED; + } + free(vm); + kd->vmst = NULL; +} + +int +_kvm_initvtop(kvm_t *kd) +{ + + kd->vmst = (struct vmstate *)_kvm_malloc(kd, sizeof(*kd->vmst)); + if (kd->vmst == NULL) { + _kvm_err(kd, kd->program, "out of virtual memory"); + return (-1); + } + if (powerpc_maphdrs(kd) == -1) { + free(kd->vmst); + kd->vmst = NULL; + return (-1); + } + return (0); +} + +int +_kvm_kvatop(kvm_t *kd, u_long va, off_t *ofs) +{ + struct vmstate *vm; + + vm = kd->vmst; + if (vm->ph->p_paddr == ~0UL) + return ((int)powerpc64_va2off(kd, va, ofs)); + + _kvm_err(kd, kd->program, "Raw corefile not supported"); + return (0); +} diff --git a/lib/libkvm/kvm_private.h b/lib/libkvm/kvm_private.h new file mode 100644 index 0000000..b3eeea7 --- /dev/null +++ b/lib/libkvm/kvm_private.h @@ -0,0 +1,112 @@ +/*- + * Copyright (c) 1992, 1993 + * The Regents of the University of California. All rights reserved. + * + * This code is derived from software developed by the Computer Systems + * Engineering group at Lawrence Berkeley Laboratory under DARPA contract + * BG 91-66 and contributed to Berkeley. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions + * are met: + * 1. Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * 2. Redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in the + * documentation and/or other materials provided with the distribution. + * 4. Neither the name of the University nor the names of its contributors + * may be used to endorse or promote products derived from this software + * without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND + * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + * ARE DISCLAIMED. IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE + * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL + * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS + * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) + * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT + * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY + * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF + * SUCH DAMAGE. + * + * @(#)kvm_private.h 8.1 (Berkeley) 6/4/93 + * $FreeBSD$ + */ + +struct __kvm { + /* + * a string to be prepended to error messages + * provided for compatibility with sun's interface + * if this value is null, errors are saved in errbuf[] + */ + const char *program; + char *errp; /* XXX this can probably go away */ + char errbuf[_POSIX2_LINE_MAX]; +#define ISALIVE(kd) ((kd)->vmfd >= 0) + int pmfd; /* physical memory file (or crashdump) */ + int vmfd; /* virtual memory file (-1 if crashdump) */ + int unused; /* was: swap file (e.g., /dev/drum) */ + int nlfd; /* namelist file (e.g., /kernel) */ + struct kinfo_proc *procbase; + char *argspc; /* (dynamic) storage for argv strings */ + int arglen; /* length of the above */ + char **argv; /* (dynamic) storage for argv pointers */ + int argc; /* length of above (not actual # present) */ + char *argbuf; /* (dynamic) temporary storage */ + /* + * Kernel virtual address translation state. This only gets filled + * in for dead kernels; otherwise, the running kernel (i.e. kmem) + * will do the translations for us. It could be big, so we + * only allocate it if necessary. + */ + struct vmstate *vmst; + int rawdump; /* raw dump format */ + + int vnet_initialized; /* vnet fields set up */ + uintptr_t vnet_start; /* start of kernel's vnet region */ + uintptr_t vnet_stop; /* stop of kernel's vnet region */ + uintptr_t vnet_current; /* vnet we're working with */ + uintptr_t vnet_base; /* vnet base of current vnet */ + + /* + * Dynamic per-CPU kernel memory. We translate symbols, on-demand, + * to the data associated with dpcpu_curcpu, set with + * kvm_dpcpu_setcpu(). + */ + int dpcpu_initialized; /* dpcpu fields set up */ + uintptr_t dpcpu_start; /* start of kernel's dpcpu region */ + uintptr_t dpcpu_stop; /* stop of kernel's dpcpu region */ + u_int dpcpu_maxcpus; /* size of base array */ + uintptr_t *dpcpu_off; /* base array, indexed by CPU ID */ + u_int dpcpu_curcpu; /* CPU we're currently working with */ + uintptr_t dpcpu_curoff; /* dpcpu base of current CPU */ +}; + +/* + * Functions used internally by kvm, but across kvm modules. + */ +void _kvm_err(kvm_t *kd, const char *program, const char *fmt, ...) + __printflike(3, 4); +void _kvm_freeprocs(kvm_t *kd); +void _kvm_freevtop(kvm_t *); +int _kvm_initvtop(kvm_t *); +int _kvm_kvatop(kvm_t *, u_long, off_t *); +void *_kvm_malloc(kvm_t *kd, size_t); +int _kvm_nlist(kvm_t *, struct nlist *, int); +void *_kvm_realloc(kvm_t *kd, void *, size_t); +void _kvm_syserr (kvm_t *kd, const char *program, const char *fmt, ...) + __printflike(3, 4); +int _kvm_uvatop(kvm_t *, const struct proc *, u_long, u_long *); +int _kvm_vnet_selectpid(kvm_t *, pid_t); +int _kvm_vnet_initialized(kvm_t *, int); +uintptr_t _kvm_vnet_validaddr(kvm_t *, uintptr_t); +int _kvm_dpcpu_initialized(kvm_t *, int); +uintptr_t _kvm_dpcpu_validaddr(kvm_t *, uintptr_t); + +#if defined(__amd64__) || defined(__i386__) || defined(__arm__) || \ + defined(__mips__) +void _kvm_minidump_freevtop(kvm_t *); +int _kvm_minidump_initvtop(kvm_t *); +int _kvm_minidump_kvatop(kvm_t *, u_long, off_t *); +#endif diff --git a/lib/libkvm/kvm_proc.c b/lib/libkvm/kvm_proc.c new file mode 100644 index 0000000..31258d7 --- /dev/null +++ b/lib/libkvm/kvm_proc.c @@ -0,0 +1,714 @@ +/*- + * Copyright (c) 1989, 1992, 1993 + * The Regents of the University of California. All rights reserved. + * + * This code is derived from software developed by the Computer Systems + * Engineering group at Lawrence Berkeley Laboratory under DARPA contract + * BG 91-66 and contributed to Berkeley. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions + * are met: + * 1. Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * 2. Redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in the + * documentation and/or other materials provided with the distribution. + * 4. Neither the name of the University nor the names of its contributors + * may be used to endorse or promote products derived from this software + * without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND + * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + * ARE DISCLAIMED. IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE + * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL + * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS + * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) + * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT + * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY + * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF + * SUCH DAMAGE. + */ + +#if 0 +#if defined(LIBC_SCCS) && !defined(lint) +static char sccsid[] = "@(#)kvm_proc.c 8.3 (Berkeley) 9/23/93"; +#endif /* LIBC_SCCS and not lint */ +#endif + +#include <sys/cdefs.h> +__FBSDID("$FreeBSD$"); + +/* + * Proc traversal interface for kvm. ps and w are (probably) the exclusive + * users of this code, so we've factored it out into a separate module. + * Thus, we keep this grunge out of the other kvm applications (i.e., + * most other applications are interested only in open/close/read/nlist). + */ + +#include <sys/param.h> +#define _WANT_UCRED /* make ucred.h give us 'struct ucred' */ +#include <sys/ucred.h> +#include <sys/queue.h> +#include <sys/_lock.h> +#include <sys/_mutex.h> +#include <sys/_task.h> +#include <sys/cpuset.h> +#include <sys/user.h> +#include <sys/proc.h> +#define _WANT_PRISON /* make jail.h give us 'struct prison' */ +#include <sys/jail.h> +#include <sys/exec.h> +#include <sys/stat.h> +#include <sys/sysent.h> +#include <sys/ioctl.h> +#include <sys/tty.h> +#include <sys/file.h> +#include <sys/conf.h> +#include <stdio.h> +#include <stdlib.h> +#include <unistd.h> +#include <nlist.h> +#include <kvm.h> + +#include <sys/sysctl.h> + +#include <limits.h> +#include <memory.h> +#include <paths.h> + +#include "kvm_private.h" + +#define KREAD(kd, addr, obj) \ + (kvm_read(kd, addr, (char *)(obj), sizeof(*obj)) != sizeof(*obj)) + +static int ticks; +static int hz; +static uint64_t cpu_tick_frequency; + +/* + * From sys/kern/kern_tc.c. Depends on cpu_tick_frequency, which is + * read/initialized before this function is ever called. + */ +static uint64_t +cputick2usec(uint64_t tick) +{ + + if (cpu_tick_frequency == 0) + return (0); + if (tick > 18446744073709551) /* floor(2^64 / 1000) */ + return (tick / (cpu_tick_frequency / 1000000)); + else if (tick > 18446744073709) /* floor(2^64 / 1000000) */ + return ((tick * 1000) / (cpu_tick_frequency / 1000)); + else + return ((tick * 1000000) / cpu_tick_frequency); +} + +/* + * Read proc's from memory file into buffer bp, which has space to hold + * at most maxcnt procs. + */ +static int +kvm_proclist(kvm_t *kd, int what, int arg, struct proc *p, + struct kinfo_proc *bp, int maxcnt) +{ + int cnt = 0; + struct kinfo_proc kinfo_proc, *kp; + struct pgrp pgrp; + struct session sess; + struct cdev t_cdev; + struct tty tty; + struct vmspace vmspace; + struct sigacts sigacts; +#if 0 + struct pstats pstats; +#endif + struct ucred ucred; + struct prison pr; + struct thread mtd; + struct proc proc; + struct proc pproc; + struct sysentvec sysent; + char svname[KI_EMULNAMELEN]; + + kp = &kinfo_proc; + kp->ki_structsize = sizeof(kinfo_proc); + /* + * Loop on the processes. this is completely broken because we need to be + * able to loop on the threads and merge the ones that are the same process some how. + */ + for (; cnt < maxcnt && p != NULL; p = LIST_NEXT(&proc, p_list)) { + memset(kp, 0, sizeof *kp); + if (KREAD(kd, (u_long)p, &proc)) { + _kvm_err(kd, kd->program, "can't read proc at %p", p); + return (-1); + } + if (proc.p_state == PRS_NEW) + continue; + if (proc.p_state != PRS_ZOMBIE) { + if (KREAD(kd, (u_long)TAILQ_FIRST(&proc.p_threads), + &mtd)) { + _kvm_err(kd, kd->program, + "can't read thread at %p", + TAILQ_FIRST(&proc.p_threads)); + return (-1); + } + } + if (KREAD(kd, (u_long)proc.p_ucred, &ucred) == 0) { + kp->ki_ruid = ucred.cr_ruid; + kp->ki_svuid = ucred.cr_svuid; + kp->ki_rgid = ucred.cr_rgid; + kp->ki_svgid = ucred.cr_svgid; + kp->ki_cr_flags = ucred.cr_flags; + if (ucred.cr_ngroups > KI_NGROUPS) { + kp->ki_ngroups = KI_NGROUPS; + kp->ki_cr_flags |= KI_CRF_GRP_OVERFLOW; + } else + kp->ki_ngroups = ucred.cr_ngroups; + kvm_read(kd, (u_long)ucred.cr_groups, kp->ki_groups, + kp->ki_ngroups * sizeof(gid_t)); + kp->ki_uid = ucred.cr_uid; + if (ucred.cr_prison != NULL) { + if (KREAD(kd, (u_long)ucred.cr_prison, &pr)) { + _kvm_err(kd, kd->program, + "can't read prison at %p", + ucred.cr_prison); + return (-1); + } + kp->ki_jid = pr.pr_id; + } + } + + switch(what & ~KERN_PROC_INC_THREAD) { + + case KERN_PROC_GID: + if (kp->ki_groups[0] != (gid_t)arg) + continue; + break; + + case KERN_PROC_PID: + if (proc.p_pid != (pid_t)arg) + continue; + break; + + case KERN_PROC_RGID: + if (kp->ki_rgid != (gid_t)arg) + continue; + break; + + case KERN_PROC_UID: + if (kp->ki_uid != (uid_t)arg) + continue; + break; + + case KERN_PROC_RUID: + if (kp->ki_ruid != (uid_t)arg) + continue; + break; + } + /* + * We're going to add another proc to the set. If this + * will overflow the buffer, assume the reason is because + * nprocs (or the proc list) is corrupt and declare an error. + */ + if (cnt >= maxcnt) { + _kvm_err(kd, kd->program, "nprocs corrupt"); + return (-1); + } + /* + * gather kinfo_proc + */ + kp->ki_paddr = p; + kp->ki_addr = 0; /* XXX uarea */ + /* kp->ki_kstack = proc.p_thread.td_kstack; XXXKSE */ + kp->ki_args = proc.p_args; + kp->ki_tracep = proc.p_tracevp; + kp->ki_textvp = proc.p_textvp; + kp->ki_fd = proc.p_fd; + kp->ki_vmspace = proc.p_vmspace; + if (proc.p_sigacts != NULL) { + if (KREAD(kd, (u_long)proc.p_sigacts, &sigacts)) { + _kvm_err(kd, kd->program, + "can't read sigacts at %p", proc.p_sigacts); + return (-1); + } + kp->ki_sigignore = sigacts.ps_sigignore; + kp->ki_sigcatch = sigacts.ps_sigcatch; + } +#if 0 + if ((proc.p_flag & P_INMEM) && proc.p_stats != NULL) { + if (KREAD(kd, (u_long)proc.p_stats, &pstats)) { + _kvm_err(kd, kd->program, + "can't read stats at %x", proc.p_stats); + return (-1); + } + kp->ki_start = pstats.p_start; + + /* + * XXX: The times here are probably zero and need + * to be calculated from the raw data in p_rux and + * p_crux. + */ + kp->ki_rusage = pstats.p_ru; + kp->ki_childstime = pstats.p_cru.ru_stime; + kp->ki_childutime = pstats.p_cru.ru_utime; + /* Some callers want child-times in a single value */ + timeradd(&kp->ki_childstime, &kp->ki_childutime, + &kp->ki_childtime); + } +#endif + if (proc.p_oppid) + kp->ki_ppid = proc.p_oppid; + else if (proc.p_pptr) { + if (KREAD(kd, (u_long)proc.p_pptr, &pproc)) { + _kvm_err(kd, kd->program, + "can't read pproc at %p", proc.p_pptr); + return (-1); + } + kp->ki_ppid = pproc.p_pid; + } else + kp->ki_ppid = 0; + if (proc.p_pgrp == NULL) + goto nopgrp; + if (KREAD(kd, (u_long)proc.p_pgrp, &pgrp)) { + _kvm_err(kd, kd->program, "can't read pgrp at %p", + proc.p_pgrp); + return (-1); + } + kp->ki_pgid = pgrp.pg_id; + kp->ki_jobc = pgrp.pg_jobc; + if (KREAD(kd, (u_long)pgrp.pg_session, &sess)) { + _kvm_err(kd, kd->program, "can't read session at %p", + pgrp.pg_session); + return (-1); + } + kp->ki_sid = sess.s_sid; + (void)memcpy(kp->ki_login, sess.s_login, + sizeof(kp->ki_login)); + kp->ki_kiflag = sess.s_ttyvp ? KI_CTTY : 0; + if (sess.s_leader == p) + kp->ki_kiflag |= KI_SLEADER; + if ((proc.p_flag & P_CONTROLT) && sess.s_ttyp != NULL) { + if (KREAD(kd, (u_long)sess.s_ttyp, &tty)) { + _kvm_err(kd, kd->program, + "can't read tty at %p", sess.s_ttyp); + return (-1); + } + if (tty.t_dev != NULL) { + if (KREAD(kd, (u_long)tty.t_dev, &t_cdev)) { + _kvm_err(kd, kd->program, + "can't read cdev at %p", + tty.t_dev); + return (-1); + } +#if 0 + kp->ki_tdev = t_cdev.si_udev; +#else + kp->ki_tdev = NODEV; +#endif + } + if (tty.t_pgrp != NULL) { + if (KREAD(kd, (u_long)tty.t_pgrp, &pgrp)) { + _kvm_err(kd, kd->program, + "can't read tpgrp at %p", + tty.t_pgrp); + return (-1); + } + kp->ki_tpgid = pgrp.pg_id; + } else + kp->ki_tpgid = -1; + if (tty.t_session != NULL) { + if (KREAD(kd, (u_long)tty.t_session, &sess)) { + _kvm_err(kd, kd->program, + "can't read session at %p", + tty.t_session); + return (-1); + } + kp->ki_tsid = sess.s_sid; + } + } else { +nopgrp: + kp->ki_tdev = NODEV; + } + if ((proc.p_state != PRS_ZOMBIE) && mtd.td_wmesg) + (void)kvm_read(kd, (u_long)mtd.td_wmesg, + kp->ki_wmesg, WMESGLEN); + + (void)kvm_read(kd, (u_long)proc.p_vmspace, + (char *)&vmspace, sizeof(vmspace)); + kp->ki_size = vmspace.vm_map.size; + /* + * Approximate the kernel's method of calculating + * this field. + */ +#define pmap_resident_count(pm) ((pm)->pm_stats.resident_count) + kp->ki_rssize = pmap_resident_count(&vmspace.vm_pmap); + kp->ki_swrss = vmspace.vm_swrss; + kp->ki_tsize = vmspace.vm_tsize; + kp->ki_dsize = vmspace.vm_dsize; + kp->ki_ssize = vmspace.vm_ssize; + + switch (what & ~KERN_PROC_INC_THREAD) { + + case KERN_PROC_PGRP: + if (kp->ki_pgid != (pid_t)arg) + continue; + break; + + case KERN_PROC_SESSION: + if (kp->ki_sid != (pid_t)arg) + continue; + break; + + case KERN_PROC_TTY: + if ((proc.p_flag & P_CONTROLT) == 0 || + kp->ki_tdev != (dev_t)arg) + continue; + break; + } + if (proc.p_comm[0] != 0) + strlcpy(kp->ki_comm, proc.p_comm, MAXCOMLEN); + (void)kvm_read(kd, (u_long)proc.p_sysent, (char *)&sysent, + sizeof(sysent)); + (void)kvm_read(kd, (u_long)sysent.sv_name, (char *)&svname, + sizeof(svname)); + if (svname[0] != 0) + strlcpy(kp->ki_emul, svname, KI_EMULNAMELEN); + if ((proc.p_state != PRS_ZOMBIE) && + (mtd.td_blocked != 0)) { + kp->ki_kiflag |= KI_LOCKBLOCK; + if (mtd.td_lockname) + (void)kvm_read(kd, + (u_long)mtd.td_lockname, + kp->ki_lockname, LOCKNAMELEN); + kp->ki_lockname[LOCKNAMELEN] = 0; + } + kp->ki_runtime = cputick2usec(proc.p_rux.rux_runtime); + kp->ki_pid = proc.p_pid; + kp->ki_siglist = proc.p_siglist; + SIGSETOR(kp->ki_siglist, mtd.td_siglist); + kp->ki_sigmask = mtd.td_sigmask; + kp->ki_xstat = proc.p_xstat; + kp->ki_acflag = proc.p_acflag; + kp->ki_lock = proc.p_lock; + if (proc.p_state != PRS_ZOMBIE) { + kp->ki_swtime = (ticks - proc.p_swtick) / hz; + kp->ki_flag = proc.p_flag; + kp->ki_sflag = 0; + kp->ki_nice = proc.p_nice; + kp->ki_traceflag = proc.p_traceflag; + if (proc.p_state == PRS_NORMAL) { + if (TD_ON_RUNQ(&mtd) || + TD_CAN_RUN(&mtd) || + TD_IS_RUNNING(&mtd)) { + kp->ki_stat = SRUN; + } else if (mtd.td_state == + TDS_INHIBITED) { + if (P_SHOULDSTOP(&proc)) { + kp->ki_stat = SSTOP; + } else if ( + TD_IS_SLEEPING(&mtd)) { + kp->ki_stat = SSLEEP; + } else if (TD_ON_LOCK(&mtd)) { + kp->ki_stat = SLOCK; + } else { + kp->ki_stat = SWAIT; + } + } + } else { + kp->ki_stat = SIDL; + } + /* Stuff from the thread */ + kp->ki_pri.pri_level = mtd.td_priority; + kp->ki_pri.pri_native = mtd.td_base_pri; + kp->ki_lastcpu = mtd.td_lastcpu; + kp->ki_wchan = mtd.td_wchan; + if (mtd.td_name[0] != 0) + strlcpy(kp->ki_tdname, mtd.td_name, MAXCOMLEN); + kp->ki_oncpu = mtd.td_oncpu; + if (mtd.td_name[0] != '\0') + strlcpy(kp->ki_tdname, mtd.td_name, sizeof(kp->ki_tdname)); + kp->ki_pctcpu = 0; + kp->ki_rqindex = 0; + } else { + kp->ki_stat = SZOMB; + } + bcopy(&kinfo_proc, bp, sizeof(kinfo_proc)); + ++bp; + ++cnt; + } + return (cnt); +} + +/* + * Build proc info array by reading in proc list from a crash dump. + * Return number of procs read. maxcnt is the max we will read. + */ +static int +kvm_deadprocs(kvm_t *kd, int what, int arg, u_long a_allproc, + u_long a_zombproc, int maxcnt) +{ + struct kinfo_proc *bp = kd->procbase; + int acnt, zcnt; + struct proc *p; + + if (KREAD(kd, a_allproc, &p)) { + _kvm_err(kd, kd->program, "cannot read allproc"); + return (-1); + } + acnt = kvm_proclist(kd, what, arg, p, bp, maxcnt); + if (acnt < 0) + return (acnt); + + if (KREAD(kd, a_zombproc, &p)) { + _kvm_err(kd, kd->program, "cannot read zombproc"); + return (-1); + } + zcnt = kvm_proclist(kd, what, arg, p, bp + acnt, maxcnt - acnt); + if (zcnt < 0) + zcnt = 0; + + return (acnt + zcnt); +} + +struct kinfo_proc * +kvm_getprocs(kvm_t *kd, int op, int arg, int *cnt) +{ + int mib[4], st, nprocs; + size_t size, osize; + int temp_op; + + if (kd->procbase != 0) { + free((void *)kd->procbase); + /* + * Clear this pointer in case this call fails. Otherwise, + * kvm_close() will free it again. + */ + kd->procbase = 0; + } + if (ISALIVE(kd)) { + size = 0; + mib[0] = CTL_KERN; + mib[1] = KERN_PROC; + mib[2] = op; + mib[3] = arg; + temp_op = op & ~KERN_PROC_INC_THREAD; + st = sysctl(mib, + temp_op == KERN_PROC_ALL || temp_op == KERN_PROC_PROC ? + 3 : 4, NULL, &size, NULL, 0); + if (st == -1) { + _kvm_syserr(kd, kd->program, "kvm_getprocs"); + return (0); + } + /* + * We can't continue with a size of 0 because we pass + * it to realloc() (via _kvm_realloc()), and passing 0 + * to realloc() results in undefined behavior. + */ + if (size == 0) { + /* + * XXX: We should probably return an invalid, + * but non-NULL, pointer here so any client + * program trying to dereference it will + * crash. However, _kvm_freeprocs() calls + * free() on kd->procbase if it isn't NULL, + * and free()'ing a junk pointer isn't good. + * Then again, _kvm_freeprocs() isn't used + * anywhere . . . + */ + kd->procbase = _kvm_malloc(kd, 1); + goto liveout; + } + do { + size += size / 10; + kd->procbase = (struct kinfo_proc *) + _kvm_realloc(kd, kd->procbase, size); + if (kd->procbase == 0) + return (0); + osize = size; + st = sysctl(mib, temp_op == KERN_PROC_ALL || + temp_op == KERN_PROC_PROC ? 3 : 4, + kd->procbase, &size, NULL, 0); + } while (st == -1 && errno == ENOMEM && size == osize); + if (st == -1) { + _kvm_syserr(kd, kd->program, "kvm_getprocs"); + return (0); + } + /* + * We have to check the size again because sysctl() + * may "round up" oldlenp if oldp is NULL; hence it + * might've told us that there was data to get when + * there really isn't any. + */ + if (size > 0 && + kd->procbase->ki_structsize != sizeof(struct kinfo_proc)) { + _kvm_err(kd, kd->program, + "kinfo_proc size mismatch (expected %zu, got %d)", + sizeof(struct kinfo_proc), + kd->procbase->ki_structsize); + return (0); + } +liveout: + nprocs = size == 0 ? 0 : size / kd->procbase->ki_structsize; + } else { + struct nlist nl[7], *p; + + nl[0].n_name = "_nprocs"; + nl[1].n_name = "_allproc"; + nl[2].n_name = "_zombproc"; + nl[3].n_name = "_ticks"; + nl[4].n_name = "_hz"; + nl[5].n_name = "_cpu_tick_frequency"; + nl[6].n_name = 0; + + if (kvm_nlist(kd, nl) != 0) { + for (p = nl; p->n_type != 0; ++p) + ; + _kvm_err(kd, kd->program, + "%s: no such symbol", p->n_name); + return (0); + } + if (KREAD(kd, nl[0].n_value, &nprocs)) { + _kvm_err(kd, kd->program, "can't read nprocs"); + return (0); + } + if (KREAD(kd, nl[3].n_value, &ticks)) { + _kvm_err(kd, kd->program, "can't read ticks"); + return (0); + } + if (KREAD(kd, nl[4].n_value, &hz)) { + _kvm_err(kd, kd->program, "can't read hz"); + return (0); + } + if (KREAD(kd, nl[5].n_value, &cpu_tick_frequency)) { + _kvm_err(kd, kd->program, + "can't read cpu_tick_frequency"); + return (0); + } + size = nprocs * sizeof(struct kinfo_proc); + kd->procbase = (struct kinfo_proc *)_kvm_malloc(kd, size); + if (kd->procbase == 0) + return (0); + + nprocs = kvm_deadprocs(kd, op, arg, nl[1].n_value, + nl[2].n_value, nprocs); + if (nprocs <= 0) { + _kvm_freeprocs(kd); + nprocs = 0; + } +#ifdef notdef + else { + size = nprocs * sizeof(struct kinfo_proc); + kd->procbase = realloc(kd->procbase, size); + } +#endif + } + *cnt = nprocs; + return (kd->procbase); +} + +void +_kvm_freeprocs(kvm_t *kd) +{ + if (kd->procbase) { + free(kd->procbase); + kd->procbase = 0; + } +} + +void * +_kvm_realloc(kvm_t *kd, void *p, size_t n) +{ + void *np = (void *)realloc(p, n); + + if (np == 0) { + free(p); + _kvm_err(kd, kd->program, "out of memory"); + } + return (np); +} + +/* + * Get the command args or environment. + */ +static char ** +kvm_argv(kvm_t *kd, const struct kinfo_proc *kp, int env, int nchr) +{ + int oid[4]; + int i; + size_t bufsz; + static int buflen; + static char *buf, *p; + static char **bufp; + static int argc; + + if (!ISALIVE(kd)) { + _kvm_err(kd, kd->program, + "cannot read user space from dead kernel"); + return (0); + } + + if (nchr == 0 || nchr > ARG_MAX) + nchr = ARG_MAX; + if (buflen == 0) { + buf = malloc(nchr); + if (buf == NULL) { + _kvm_err(kd, kd->program, "cannot allocate memory"); + return (0); + } + buflen = nchr; + argc = 32; + bufp = malloc(sizeof(char *) * argc); + } else if (nchr > buflen) { + p = realloc(buf, nchr); + if (p != NULL) { + buf = p; + buflen = nchr; + } + } + oid[0] = CTL_KERN; + oid[1] = KERN_PROC; + oid[2] = env ? KERN_PROC_ENV : KERN_PROC_ARGS; + oid[3] = kp->ki_pid; + bufsz = buflen; + if (sysctl(oid, 4, buf, &bufsz, 0, 0) == -1) { + /* + * If the supplied buf is too short to hold the requested + * value the sysctl returns with ENOMEM. The buf is filled + * with the truncated value and the returned bufsz is equal + * to the requested len. + */ + if (errno != ENOMEM || bufsz != (size_t)buflen) + return (0); + buf[bufsz - 1] = '\0'; + errno = 0; + } else if (bufsz == 0) { + return (0); + } + i = 0; + p = buf; + do { + bufp[i++] = p; + p += strlen(p) + 1; + if (i >= argc) { + argc += argc; + bufp = realloc(bufp, + sizeof(char *) * argc); + } + } while (p < buf + bufsz); + bufp[i++] = 0; + return (bufp); +} + +char ** +kvm_getargv(kvm_t *kd, const struct kinfo_proc *kp, int nchr) +{ + return (kvm_argv(kd, kp, 0, nchr)); +} + +char ** +kvm_getenvv(kvm_t *kd, const struct kinfo_proc *kp, int nchr) +{ + return (kvm_argv(kd, kp, 1, nchr)); +} diff --git a/lib/libkvm/kvm_read.3 b/lib/libkvm/kvm_read.3 new file mode 100644 index 0000000..a2efd3c --- /dev/null +++ b/lib/libkvm/kvm_read.3 @@ -0,0 +1,92 @@ +.\" Copyright (c) 1992, 1993 +.\" The Regents of the University of California. All rights reserved. +.\" +.\" This code is derived from software developed by the Computer Systems +.\" Engineering group at Lawrence Berkeley Laboratory under DARPA contract +.\" BG 91-66 and contributed to Berkeley. +.\" +.\" Redistribution and use in source and binary forms, with or without +.\" modification, are permitted provided that the following conditions +.\" are met: +.\" 1. Redistributions of source code must retain the above copyright +.\" notice, this list of conditions and the following disclaimer. +.\" 2. Redistributions in binary form must reproduce the above copyright +.\" notice, this list of conditions and the following disclaimer in the +.\" documentation and/or other materials provided with the distribution. +.\" 4. Neither the name of the University nor the names of its contributors +.\" may be used to endorse or promote products derived from this software +.\" without specific prior written permission. +.\" +.\" THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND +.\" ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE +.\" IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE +.\" ARE DISCLAIMED. IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE +.\" FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL +.\" DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS +.\" OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) +.\" HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT +.\" LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY +.\" OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF +.\" SUCH DAMAGE. +.\" +.\" @(#)kvm_read.3 8.1 (Berkeley) 6/4/93 +.\" $FreeBSD$ +.\" +.Dd June 4, 1993 +.Dt KVM_READ 3 +.Os +.Sh NAME +.Nm kvm_read , +.Nm kvm_write +.Nd read or write kernel virtual memory +.Sh LIBRARY +.Lb libkvm +.Sh SYNOPSIS +.In kvm.h +.Ft ssize_t +.Fn kvm_read "kvm_t *kd" "unsigned long addr" "void *buf" "size_t nbytes" +.Ft ssize_t +.Fn kvm_write "kvm_t *kd" "unsigned long addr" "const void *buf" "size_t nbytes" +.Sh DESCRIPTION +The +.Fn kvm_read +and +.Fn kvm_write +functions are used to read and write kernel virtual memory (or a crash +dump file). +See +.Fn kvm_open 3 +or +.Fn kvm_openfiles 3 +for information regarding opening kernel virtual memory and crash dumps. +.Pp +The +.Fn kvm_read +function transfers +.Fa nbytes +bytes of data from +the kernel space address +.Fa addr +to +.Fa buf . +Conversely, +.Fn kvm_write +transfers data from +.Fa buf +to +.Fa addr . +Unlike their SunOS counterparts, these functions cannot be used to +read or write process address spaces. +.Sh RETURN VALUES +Upon success, the number of bytes actually transferred is returned. +Otherwise, -1 is returned. +.Sh SEE ALSO +.Xr kvm 3 , +.Xr kvm_close 3 , +.Xr kvm_getargv 3 , +.Xr kvm_getenvv 3 , +.Xr kvm_geterr 3 , +.Xr kvm_getprocs 3 , +.Xr kvm_nlist 3 , +.Xr kvm_open 3 , +.Xr kvm_openfiles 3 diff --git a/lib/libkvm/kvm_sparc.c b/lib/libkvm/kvm_sparc.c new file mode 100644 index 0000000..bafd08c --- /dev/null +++ b/lib/libkvm/kvm_sparc.c @@ -0,0 +1,236 @@ +/*- + * Copyright (c) 1992, 1993 + * The Regents of the University of California. All rights reserved. + * + * This code is derived from software developed by the Computer Systems + * Engineering group at Lawrence Berkeley Laboratory under DARPA contract + * BG 91-66 and contributed to Berkeley. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions + * are met: + * 1. Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * 2. Redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in the + * documentation and/or other materials provided with the distribution. + * 4. Neither the name of the University nor the names of its contributors + * may be used to endorse or promote products derived from this software + * without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND + * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + * ARE DISCLAIMED. IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE + * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL + * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS + * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) + * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT + * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY + * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF + * SUCH DAMAGE. + */ + +#include <sys/cdefs.h> +__FBSDID("$FreeBSD$"); + +#if defined(LIBC_SCCS) && !defined(lint) +#if 0 +static char sccsid[] = "@(#)kvm_sparc.c 8.1 (Berkeley) 6/4/93"; +#endif +#endif /* LIBC_SCCS and not lint */ + +/* + * Sparc machine dependent routines for kvm. Hopefully, the forthcoming + * vm code will one day obsolete this module. + */ + +#include <sys/param.h> +#include <sys/user.h> +#include <sys/proc.h> +#include <sys/stat.h> +#include <unistd.h> +#include <nlist.h> +#include <kvm.h> + +#include <vm/vm.h> +#include <vm/vm_param.h> + +#include <limits.h> + +#include "kvm_private.h" + +#define NPMEG 128 + +/* XXX from sparc/pmap.c */ +#define MAXMEM (128 * 1024 * 1024) /* no more than 128 MB phys mem */ +#define NPGBANK 16 /* 2^4 pages per bank (64K / bank) */ +#define BSHIFT 4 /* log2(NPGBANK) */ +#define BOFFSET (NPGBANK - 1) +#define BTSIZE (MAXMEM / NBPG / NPGBANK) +#define HWTOSW(pmap_stod, pg) (pmap_stod[(pg) >> BSHIFT] | ((pg) & BOFFSET)) + +struct vmstate { + pmeg_t segmap[NKSEG]; + int pmeg[NPMEG][NPTESG]; + int pmap_stod[BTSIZE]; /* dense to sparse */ +}; + +void +_kvm_freevtop(kd) + kvm_t *kd; +{ + if (kd->vmst != 0) + free(kd->vmst); +} + +int +_kvm_initvtop(kd) + kvm_t *kd; +{ + int i; + int off; + struct vmstate *vm; + struct stat st; + struct nlist nlist[2]; + + vm = (struct vmstate *)_kvm_malloc(kd, sizeof(*vm)); + if (vm == 0) + return (-1); + + kd->vmst = vm; + + if (fstat(kd->pmfd, &st) < 0) + return (-1); + /* + * Read segment table. + */ + off = st.st_size - ctob(btoc(sizeof(vm->segmap))); + errno = 0; + if (lseek(kd->pmfd, (off_t)off, 0) == -1 && errno != 0 || + read(kd->pmfd, (char *)vm->segmap, sizeof(vm->segmap)) < 0) { + _kvm_err(kd, kd->program, "cannot read segment map"); + return (-1); + } + /* + * Read PMEGs. + */ + off = st.st_size - ctob(btoc(sizeof(vm->pmeg)) + + btoc(sizeof(vm->segmap))); + errno = 0; + if (lseek(kd->pmfd, (off_t)off, 0) == -1 && errno != 0 || + read(kd->pmfd, (char *)vm->pmeg, sizeof(vm->pmeg)) < 0) { + _kvm_err(kd, kd->program, "cannot read PMEG table"); + return (-1); + } + /* + * Make pmap_stod be an identity map so we can bootstrap it in. + * We assume it's in the first contiguous chunk of physical memory. + */ + for (i = 0; i < BTSIZE; ++i) + vm->pmap_stod[i] = i << 4; + + /* + * It's okay to do this nlist separately from the one kvm_getprocs() + * does, since the only time we could gain anything by combining + * them is if we do a kvm_getprocs() on a dead kernel, which is + * not too common. + */ + nlist[0].n_name = "_pmap_stod"; + nlist[1].n_name = 0; + if (kvm_nlist(kd, nlist) != 0) { + _kvm_err(kd, kd->program, "pmap_stod: no such symbol"); + return (-1); + } + if (kvm_read(kd, (u_long)nlist[0].n_value, + (char *)vm->pmap_stod, sizeof(vm->pmap_stod)) + != sizeof(vm->pmap_stod)) { + _kvm_err(kd, kd->program, "cannot read pmap_stod"); + return (-1); + } + return (0); +} + +#define VA_OFF(va) (va & (NBPG - 1)) + +/* + * Translate a user virtual address to a physical address. + */ +int +_kvm_uvatop(kd, p, va, pa) + kvm_t *kd; + const struct proc *p; + u_long va; + u_long *pa; +{ + int kva, pte; + int off, frame; + struct vmspace *vms = p->p_vmspace; + + if ((u_long)vms < KERNBASE) { + _kvm_err(kd, kd->program, "_kvm_uvatop: corrupt proc"); + return (0); + } + if (va >= KERNBASE) + return (0); + /* + * Get the PTE. This takes two steps. We read the + * base address of the table, then we index it. + * Note that the index pte table is indexed by + * virtual segment rather than physical segment. + */ + kva = (u_long)&vms->vm_pmap.pm_rpte[VA_VSEG(va)]; + if (kvm_read(kd, kva, (char *)&kva, 4) != 4 || kva == 0) + goto invalid; + kva += sizeof(vms->vm_pmap.pm_rpte[0]) * VA_VPG(va); + if (kvm_read(kd, kva, (char *)&pte, 4) == 4 && (pte & PG_V)) { + off = VA_OFF(va); + /* + * /dev/mem adheres to the hardware model of physical memory + * (with holes in the address space), while crashdumps + * adhere to the contiguous software model. + */ + if (ISALIVE(kd)) + frame = pte & PG_PFNUM; + else + frame = HWTOSW(kd->vmst->pmap_stod, pte & PG_PFNUM); + *pa = (frame << PGSHIFT) | off; + return (NBPG - off); + } +invalid: + _kvm_err(kd, 0, "invalid address (%x)", va); + return (0); +} + +/* + * Translate a kernel virtual address to a physical address using the + * mapping information in kd->vm. Returns the result in pa, and returns + * the number of bytes that are contiguously available from this + * physical address. This routine is used only for crashdumps. + */ +int +_kvm_kvatop(kd, va, pa) + kvm_t *kd; + u_long va; + uint64_t *pa; +{ + struct vmstate *vm; + int s; + int pte; + int off; + + if (va >= KERNBASE) { + vm = kd->vmst; + s = vm->segmap[VA_VSEG(va) - NUSEG]; + pte = vm->pmeg[s][VA_VPG(va)]; + if ((pte & PG_V) != 0) { + off = VA_OFF(va); + *pa = (HWTOSW(vm->pmap_stod, pte & PG_PFNUM) + << PGSHIFT) | off; + + return (NBPG - off); + } + } + _kvm_err(kd, 0, "invalid address (%x)", va); + return (0); +} diff --git a/lib/libkvm/kvm_sparc64.c b/lib/libkvm/kvm_sparc64.c new file mode 100644 index 0000000..1f925a9 --- /dev/null +++ b/lib/libkvm/kvm_sparc64.c @@ -0,0 +1,221 @@ +/*- + * Copyright (c) 1989, 1992, 1993 + * The Regents of the University of California. All rights reserved. + * + * This code is derived from software developed by the Computer Systems + * Engineering group at Lawrence Berkeley Laboratory under DARPA contract + * BG 91-66 and contributed to Berkeley. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions + * are met: + * 1. Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * 2. Redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in the + * documentation and/or other materials provided with the distribution. + * 4. Neither the name of the University nor the names of its contributors + * may be used to endorse or promote products derived from this software + * without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND + * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + * ARE DISCLAIMED. IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE + * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL + * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS + * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) + * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT + * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY + * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF + * SUCH DAMAGE. + * + * from: FreeBSD: src/lib/libkvm/kvm_i386.c,v 1.15 2001/10/10 17:48:43 + */ + +#include <sys/cdefs.h> +__FBSDID("$FreeBSD$"); + +#if defined(LIBC_SCCS) && !defined(lint) +#if 0 +static char sccsid[] = "@(#)kvm_hp300.c 8.1 (Berkeley) 6/4/93"; +#endif +#endif /* LIBC_SCCS and not lint */ + +/* + * sparc64 machine dependent routines for kvm. + */ + +#include <sys/param.h> +#include <sys/user.h> +#include <sys/proc.h> +#include <sys/stat.h> +#include <stdlib.h> +#include <unistd.h> +#include <nlist.h> +#include <kvm.h> + +#include <vm/vm.h> +#include <vm/vm_param.h> + +#include <machine/kerneldump.h> +#include <machine/tte.h> +#include <machine/tlb.h> +#include <machine/tsb.h> + +#include <limits.h> + +#include "kvm_private.h" + +#ifndef btop +#define btop(x) (sparc64_btop(x)) +#define ptob(x) (sparc64_ptob(x)) +#endif + +struct vmstate { + off_t vm_tsb_off; + vm_size_t vm_tsb_mask; + int vm_nregions; + struct sparc64_dump_reg *vm_regions; +}; + +void +_kvm_freevtop(kvm_t *kd) +{ + if (kd->vmst != 0) { + free(kd->vmst->vm_regions); + free(kd->vmst); + } +} + +static int +_kvm_read_phys(kvm_t *kd, off_t pos, void *buf, size_t size) +{ + + /* XXX This has to be a raw file read, kvm_read is virtual. */ + if (lseek(kd->pmfd, pos, SEEK_SET) == -1) { + _kvm_syserr(kd, kd->program, "_kvm_read_phys: lseek"); + return (0); + } + if (read(kd->pmfd, buf, size) != (ssize_t)size) { + _kvm_syserr(kd, kd->program, "_kvm_read_phys: read"); + return (0); + } + return (1); +} + +static int +_kvm_reg_cmp(const void *a, const void *b) +{ + const struct sparc64_dump_reg *ra, *rb; + + ra = a; + rb = b; + if (ra->dr_pa < rb->dr_pa) + return (-1); + else if (ra->dr_pa >= rb->dr_pa + rb->dr_size) + return (1); + else + return (0); +} + +#define KVM_OFF_NOTFOUND 0 + +static off_t +_kvm_find_off(struct vmstate *vm, vm_offset_t pa, vm_size_t size) +{ + struct sparc64_dump_reg *reg, key; + vm_offset_t o; + + key.dr_pa = pa; + reg = bsearch(&key, vm->vm_regions, vm->vm_nregions, + sizeof(*vm->vm_regions), _kvm_reg_cmp); + if (reg == NULL) + return (KVM_OFF_NOTFOUND); + o = pa - reg->dr_pa; + if (o + size > reg->dr_size) + return (KVM_OFF_NOTFOUND); + return (reg->dr_offs + o); +} + +int +_kvm_initvtop(kvm_t *kd) +{ + struct sparc64_dump_hdr hdr; + struct sparc64_dump_reg *regs; + struct vmstate *vm; + size_t regsz; + vm_offset_t pa; + + vm = (struct vmstate *)_kvm_malloc(kd, sizeof(*vm)); + if (vm == NULL) { + _kvm_err(kd, kd->program, "cannot allocate vm"); + return (-1); + } + kd->vmst = vm; + + if (!_kvm_read_phys(kd, 0, &hdr, sizeof(hdr))) + goto fail_vm; + pa = hdr.dh_tsb_pa; + + regsz = hdr.dh_nregions * sizeof(*regs); + regs = _kvm_malloc(kd, regsz); + if (regs == NULL) { + _kvm_err(kd, kd->program, "cannot allocate regions"); + goto fail_vm; + } + if (!_kvm_read_phys(kd, sizeof(hdr), regs, regsz)) + goto fail_regs; + qsort(regs, hdr.dh_nregions, sizeof(*regs), _kvm_reg_cmp); + + vm->vm_tsb_mask = hdr.dh_tsb_mask; + vm->vm_regions = regs; + vm->vm_nregions = hdr.dh_nregions; + vm->vm_tsb_off = _kvm_find_off(vm, hdr.dh_tsb_pa, hdr.dh_tsb_size); + if (vm->vm_tsb_off == KVM_OFF_NOTFOUND) { + _kvm_err(kd, kd->program, "tsb not found in dump"); + goto fail_regs; + } + return (0); + +fail_regs: + free(regs); +fail_vm: + free(vm); + return (-1); +} + +int +_kvm_kvatop(kvm_t *kd, u_long va, off_t *pa) +{ + struct tte tte; + off_t tte_off; + u_long vpn; + off_t pa_off; + u_long pg_off; + int rest; + + pg_off = va & PAGE_MASK; + if (va >= VM_MIN_DIRECT_ADDRESS) + pa_off = TLB_DIRECT_TO_PHYS(va) & ~PAGE_MASK; + else { + vpn = btop(va); + tte_off = kd->vmst->vm_tsb_off + + ((vpn & kd->vmst->vm_tsb_mask) << TTE_SHIFT); + if (!_kvm_read_phys(kd, tte_off, &tte, sizeof(tte))) + goto invalid; + if (!tte_match(&tte, va)) + goto invalid; + pa_off = TTE_GET_PA(&tte); + } + rest = PAGE_SIZE - pg_off; + pa_off = _kvm_find_off(kd->vmst, pa_off, rest); + if (pa_off == KVM_OFF_NOTFOUND) + goto invalid; + *pa = pa_off + pg_off; + return (rest); + +invalid: + _kvm_err(kd, 0, "invalid address (%lx)", va); + return (0); +} diff --git a/lib/libkvm/kvm_vnet.c b/lib/libkvm/kvm_vnet.c new file mode 100644 index 0000000..12ecafc --- /dev/null +++ b/lib/libkvm/kvm_vnet.c @@ -0,0 +1,239 @@ +/*- + * Copyright (c) 2009 Robert N. M. Watson + * Copyright (c) 2009 Bjoern A. Zeeb <bz@FreeBSD.org> + * All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions + * are met: + * 1. Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * 2. Redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in the + * documentation and/or other materials provided with the distribution. + * + * THIS SOFTWARE IS PROVIDED BY THE AUTHOR AND CONTRIBUTORS ``AS IS'' AND + * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + * ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE + * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL + * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS + * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) + * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT + * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY + * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF + * SUCH DAMAGE. + */ + +#include <sys/cdefs.h> +__FBSDID("$FreeBSD$"); + +#include <sys/param.h> + +#define _WANT_PRISON +#define _WANT_UCRED +#define _WANT_VNET + +#include <sys/_lock.h> +#include <sys/_mutex.h> +#include <sys/_task.h> +#include <sys/jail.h> +#include <sys/proc.h> +#include <sys/types.h> + +#include <net/vnet.h> + +#include <nlist.h> +#include <kvm.h> +#include <limits.h> +#include <stdlib.h> +#include <unistd.h> + +#include "kvm_private.h" + +/* + * Set up libkvm to handle virtual network stack symbols by selecting a + * starting pid. + */ +int +_kvm_vnet_selectpid(kvm_t *kd, pid_t pid) +{ + struct proc proc; + struct ucred cred; + struct prison prison; + struct vnet vnet; + struct nlist nl[] = { + /* + * Note: kvm_nlist strips the first '_' so add an extra one + * here to __{start,stop}_set_vnet. + */ +#define NLIST_START_VNET 0 + { .n_name = "___start_" VNET_SETNAME }, +#define NLIST_STOP_VNET 1 + { .n_name = "___stop_" VNET_SETNAME }, +#define NLIST_VNET_HEAD 2 + { .n_name = "vnet_head" }, +#define NLIST_ALLPROC 3 + { .n_name = "allproc" }, +#define NLIST_DUMPTID 4 + { .n_name = "dumptid" }, +#define NLIST_PROC0 5 + { .n_name = "proc0" }, + { .n_name = NULL }, + }; + uintptr_t procp, credp; +#define VMCORE_VNET_OF_PROC0 +#ifndef VMCORE_VNET_OF_PROC0 + struct thread td; + uintptr_t tdp; +#endif + lwpid_t dumptid; + + /* + * Locate and cache locations of important symbols + * using the internal version of _kvm_nlist, turning + * off initialization to avoid recursion in case of + * unresolveable symbols. + */ + if (_kvm_nlist(kd, nl, 0) != 0) { + /* + * XXX-BZ: ___start_/___stop_VNET_SETNAME may fail. + * For now do not report an error here as we are called + * internally and in `void context' until we merge the + * functionality to optionally activate this into programs. + * By that time we can properly fail and let the callers + * handle the error. + */ + /* _kvm_err(kd, kd->program, "%s: no namelist", __func__); */ + return (-1); + } + + /* + * Auto-detect if this is a crashdump by reading dumptid. + */ + dumptid = 0; + if (nl[NLIST_DUMPTID].n_value) { + if (kvm_read(kd, nl[NLIST_DUMPTID].n_value, &dumptid, + sizeof(dumptid)) != sizeof(dumptid)) { + _kvm_err(kd, kd->program, "%s: dumptid", __func__); + return (-1); + } + } + + /* + * First, find the process for this pid. If we are working on a + * dump, either locate the thread dumptid is refering to or proc0. + * Based on either, take the address of the ucred. + */ + credp = 0; + + procp = nl[NLIST_ALLPROC].n_value; +#ifdef VMCORE_VNET_OF_PROC0 + if (dumptid > 0) { + procp = nl[NLIST_PROC0].n_value; + pid = 0; + } +#endif + while (procp != 0) { + if (kvm_read(kd, procp, &proc, sizeof(proc)) != sizeof(proc)) { + _kvm_err(kd, kd->program, "%s: proc", __func__); + return (-1); + } +#ifndef VMCORE_VNET_OF_PROC0 + if (dumptid > 0) { + tdp = (uintptr_t)TAILQ_FIRST(&proc.p_threads); + while (tdp != 0) { + if (kvm_read(kd, tdp, &td, sizeof(td)) != + sizeof(td)) { + _kvm_err(kd, kd->program, "%s: thread", + __func__); + return (-1); + } + if (td.td_tid == dumptid) { + credp = (uintptr_t)td.td_ucred; + break; + } + tdp = (uintptr_t)TAILQ_NEXT(&td, td_plist); + } + } else +#endif + if (proc.p_pid == pid) + credp = (uintptr_t)proc.p_ucred; + if (credp != 0) + break; + procp = (uintptr_t)LIST_NEXT(&proc, p_list); + } + if (credp == 0) { + _kvm_err(kd, kd->program, "%s: pid/tid not found", __func__); + return (-1); + } + if (kvm_read(kd, (uintptr_t)credp, &cred, sizeof(cred)) != + sizeof(cred)) { + _kvm_err(kd, kd->program, "%s: cred", __func__); + return (-1); + } + if (cred.cr_prison == NULL) { + _kvm_err(kd, kd->program, "%s: no jail", __func__); + return (-1); + } + if (kvm_read(kd, (uintptr_t)cred.cr_prison, &prison, sizeof(prison)) != + sizeof(prison)) { + _kvm_err(kd, kd->program, "%s: prison", __func__); + return (-1); + } + if (prison.pr_vnet == NULL) { + _kvm_err(kd, kd->program, "%s: no vnet", __func__); + return (-1); + } + if (kvm_read(kd, (uintptr_t)prison.pr_vnet, &vnet, sizeof(vnet)) != + sizeof(vnet)) { + _kvm_err(kd, kd->program, "%s: vnet", __func__); + return (-1); + } + if (vnet.vnet_magic_n != VNET_MAGIC_N) { + _kvm_err(kd, kd->program, "%s: invalid vnet magic#", __func__); + return (-1); + } + kd->vnet_initialized = 1; + kd->vnet_start = nl[NLIST_START_VNET].n_value; + kd->vnet_stop = nl[NLIST_STOP_VNET].n_value; + kd->vnet_current = (uintptr_t)prison.pr_vnet; + kd->vnet_base = vnet.vnet_data_base; + return (0); +} + +/* + * Check whether the vnet module has been initialized sucessfully + * or not, intialize it if permitted. + */ +int +_kvm_vnet_initialized(kvm_t *kd, int intialize) +{ + + if (kd->vnet_initialized || !intialize) + return (kd->vnet_initialized); + + (void) _kvm_vnet_selectpid(kd, getpid()); + + return (kd->vnet_initialized); +} + +/* + * Check whether the value is within the vnet symbol range and + * only if so adjust the offset relative to the current base. + */ +uintptr_t +_kvm_vnet_validaddr(kvm_t *kd, uintptr_t value) +{ + + if (value == 0) + return (value); + + if (!kd->vnet_initialized) + return (value); + + if (value < kd->vnet_start || value >= kd->vnet_stop) + return (value); + + return (kd->vnet_base + value); +} |