Home | History | Annotate | Line # | Download | only in kern
kern_subr.c revision 1.159
      1 /*	$NetBSD: kern_subr.c,v 1.159 2007/06/24 01:43:34 dyoung Exp $	*/
      2 
      3 /*-
      4  * Copyright (c) 1997, 1998, 1999, 2002 The NetBSD Foundation, Inc.
      5  * All rights reserved.
      6  *
      7  * This code is derived from software contributed to The NetBSD Foundation
      8  * by Jason R. Thorpe of the Numerical Aerospace Simulation Facility,
      9  * NASA Ames Research Center, and by Luke Mewburn.
     10  *
     11  * Redistribution and use in source and binary forms, with or without
     12  * modification, are permitted provided that the following conditions
     13  * are met:
     14  * 1. Redistributions of source code must retain the above copyright
     15  *    notice, this list of conditions and the following disclaimer.
     16  * 2. Redistributions in binary form must reproduce the above copyright
     17  *    notice, this list of conditions and the following disclaimer in the
     18  *    documentation and/or other materials provided with the distribution.
     19  * 3. All advertising materials mentioning features or use of this software
     20  *    must display the following acknowledgement:
     21  *	This product includes software developed by the NetBSD
     22  *	Foundation, Inc. and its contributors.
     23  * 4. Neither the name of The NetBSD Foundation nor the names of its
     24  *    contributors may be used to endorse or promote products derived
     25  *    from this software without specific prior written permission.
     26  *
     27  * THIS SOFTWARE IS PROVIDED BY THE NETBSD FOUNDATION, INC. AND CONTRIBUTORS
     28  * ``AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED
     29  * TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
     30  * PURPOSE ARE DISCLAIMED.  IN NO EVENT SHALL THE FOUNDATION OR CONTRIBUTORS
     31  * BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
     32  * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
     33  * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
     34  * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
     35  * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
     36  * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
     37  * POSSIBILITY OF SUCH DAMAGE.
     38  */
     39 
     40 /*
     41  * Copyright (c) 1982, 1986, 1991, 1993
     42  *	The Regents of the University of California.  All rights reserved.
     43  * (c) UNIX System Laboratories, Inc.
     44  * All or some portions of this file are derived from material licensed
     45  * to the University of California by American Telephone and Telegraph
     46  * Co. or Unix System Laboratories, Inc. and are reproduced herein with
     47  * the permission of UNIX System Laboratories, Inc.
     48  *
     49  * Copyright (c) 1992, 1993
     50  *	The Regents of the University of California.  All rights reserved.
     51  *
     52  * This software was developed by the Computer Systems Engineering group
     53  * at Lawrence Berkeley Laboratory under DARPA contract BG 91-66 and
     54  * contributed to Berkeley.
     55  *
     56  * All advertising materials mentioning features or use of this software
     57  * must display the following acknowledgement:
     58  *	This product includes software developed by the University of
     59  *	California, Lawrence Berkeley Laboratory.
     60  *
     61  * Redistribution and use in source and binary forms, with or without
     62  * modification, are permitted provided that the following conditions
     63  * are met:
     64  * 1. Redistributions of source code must retain the above copyright
     65  *    notice, this list of conditions and the following disclaimer.
     66  * 2. Redistributions in binary form must reproduce the above copyright
     67  *    notice, this list of conditions and the following disclaimer in the
     68  *    documentation and/or other materials provided with the distribution.
     69  * 3. Neither the name of the University nor the names of its contributors
     70  *    may be used to endorse or promote products derived from this software
     71  *    without specific prior written permission.
     72  *
     73  * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
     74  * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
     75  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
     76  * ARE DISCLAIMED.  IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
     77  * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
     78  * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
     79  * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
     80  * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
     81  * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
     82  * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
     83  * SUCH DAMAGE.
     84  *
     85  *	@(#)kern_subr.c	8.4 (Berkeley) 2/14/95
     86  */
     87 
     88 #include <sys/cdefs.h>
     89 __KERNEL_RCSID(0, "$NetBSD: kern_subr.c,v 1.159 2007/06/24 01:43:34 dyoung Exp $");
     90 
     91 #include "opt_ddb.h"
     92 #include "opt_md.h"
     93 #include "opt_syscall_debug.h"
     94 #include "opt_ktrace.h"
     95 #include "opt_ptrace.h"
     96 #include "opt_systrace.h"
     97 #include "opt_powerhook.h"
     98 #include "opt_tftproot.h"
     99 
    100 #include <sys/param.h>
    101 #include <sys/systm.h>
    102 #include <sys/proc.h>
    103 #include <sys/malloc.h>
    104 #include <sys/mount.h>
    105 #include <sys/device.h>
    106 #include <sys/reboot.h>
    107 #include <sys/conf.h>
    108 #include <sys/disk.h>
    109 #include <sys/disklabel.h>
    110 #include <sys/queue.h>
    111 #include <sys/systrace.h>
    112 #include <sys/ktrace.h>
    113 #include <sys/ptrace.h>
    114 #include <sys/fcntl.h>
    115 
    116 #include <uvm/uvm_extern.h>
    117 
    118 #include <dev/cons.h>
    119 
    120 #include <net/if.h>
    121 
    122 /* XXX these should eventually move to subr_autoconf.c */
    123 static struct device *finddevice(const char *);
    124 static struct device *getdisk(char *, int, int, dev_t *, int);
    125 static struct device *parsedisk(char *, int, int, dev_t *);
    126 static const char *getwedgename(const char *, int);
    127 
    128 /*
    129  * A generic linear hook.
    130  */
    131 struct hook_desc {
    132 	LIST_ENTRY(hook_desc) hk_list;
    133 	void	(*hk_fn)(void *);
    134 	void	*hk_arg;
    135 };
    136 typedef LIST_HEAD(, hook_desc) hook_list_t;
    137 
    138 MALLOC_DEFINE(M_IOV, "iov", "large iov's");
    139 
    140 #ifdef TFTPROOT
    141 int tftproot_dhcpboot(struct device *);
    142 #endif
    143 
    144 void
    145 uio_setup_sysspace(struct uio *uio)
    146 {
    147 
    148 	uio->uio_vmspace = vmspace_kernel();
    149 }
    150 
    151 int
    152 uiomove(void *buf, size_t n, struct uio *uio)
    153 {
    154 	struct vmspace *vm = uio->uio_vmspace;
    155 	struct iovec *iov;
    156 	u_int cnt;
    157 	int error = 0;
    158 	char *cp = buf;
    159 #ifdef MULTIPROCESSOR
    160 	int hold_count;
    161 #endif
    162 
    163 	KERNEL_UNLOCK_ALL(NULL, &hold_count);
    164 
    165 	ASSERT_SLEEPABLE(NULL, "uiomove");
    166 
    167 #ifdef DIAGNOSTIC
    168 	if (uio->uio_rw != UIO_READ && uio->uio_rw != UIO_WRITE)
    169 		panic("uiomove: mode");
    170 #endif
    171 	while (n > 0 && uio->uio_resid) {
    172 		iov = uio->uio_iov;
    173 		cnt = iov->iov_len;
    174 		if (cnt == 0) {
    175 			KASSERT(uio->uio_iovcnt > 0);
    176 			uio->uio_iov++;
    177 			uio->uio_iovcnt--;
    178 			continue;
    179 		}
    180 		if (cnt > n)
    181 			cnt = n;
    182 		if (!VMSPACE_IS_KERNEL_P(vm)) {
    183 			if (curcpu()->ci_schedstate.spc_flags &
    184 			    SPCF_SHOULDYIELD)
    185 				preempt();
    186 		}
    187 
    188 		if (uio->uio_rw == UIO_READ) {
    189 			error = copyout_vmspace(vm, cp, iov->iov_base,
    190 			    cnt);
    191 		} else {
    192 			error = copyin_vmspace(vm, iov->iov_base, cp,
    193 			    cnt);
    194 		}
    195 		if (error) {
    196 			break;
    197 		}
    198 		iov->iov_base = (char *)iov->iov_base + cnt;
    199 		iov->iov_len -= cnt;
    200 		uio->uio_resid -= cnt;
    201 		uio->uio_offset += cnt;
    202 		cp += cnt;
    203 		KDASSERT(cnt <= n);
    204 		n -= cnt;
    205 	}
    206 	KERNEL_LOCK(hold_count, NULL);
    207 	return (error);
    208 }
    209 
    210 /*
    211  * Wrapper for uiomove() that validates the arguments against a known-good
    212  * kernel buffer.
    213  */
    214 int
    215 uiomove_frombuf(void *buf, size_t buflen, struct uio *uio)
    216 {
    217 	size_t offset;
    218 
    219 	if (uio->uio_offset < 0 || /* uio->uio_resid < 0 || */
    220 	    (offset = uio->uio_offset) != uio->uio_offset)
    221 		return (EINVAL);
    222 	if (offset >= buflen)
    223 		return (0);
    224 	return (uiomove((char *)buf + offset, buflen - offset, uio));
    225 }
    226 
    227 /*
    228  * Give next character to user as result of read.
    229  */
    230 int
    231 ureadc(int c, struct uio *uio)
    232 {
    233 	struct iovec *iov;
    234 
    235 	if (uio->uio_resid <= 0)
    236 		panic("ureadc: non-positive resid");
    237 again:
    238 	if (uio->uio_iovcnt <= 0)
    239 		panic("ureadc: non-positive iovcnt");
    240 	iov = uio->uio_iov;
    241 	if (iov->iov_len <= 0) {
    242 		uio->uio_iovcnt--;
    243 		uio->uio_iov++;
    244 		goto again;
    245 	}
    246 	if (!VMSPACE_IS_KERNEL_P(uio->uio_vmspace)) {
    247 		if (subyte(iov->iov_base, c) < 0)
    248 			return (EFAULT);
    249 	} else {
    250 		*(char *)iov->iov_base = c;
    251 	}
    252 	iov->iov_base = (char *)iov->iov_base + 1;
    253 	iov->iov_len--;
    254 	uio->uio_resid--;
    255 	uio->uio_offset++;
    256 	return (0);
    257 }
    258 
    259 /*
    260  * Like copyin(), but operates on an arbitrary vmspace.
    261  */
    262 int
    263 copyin_vmspace(struct vmspace *vm, const void *uaddr, void *kaddr, size_t len)
    264 {
    265 	struct iovec iov;
    266 	struct uio uio;
    267 	int error;
    268 
    269 	if (len == 0)
    270 		return (0);
    271 
    272 	if (VMSPACE_IS_KERNEL_P(vm)) {
    273 		return kcopy(uaddr, kaddr, len);
    274 	}
    275 	if (__predict_true(vm == curproc->p_vmspace)) {
    276 		return copyin(uaddr, kaddr, len);
    277 	}
    278 
    279 	iov.iov_base = kaddr;
    280 	iov.iov_len = len;
    281 	uio.uio_iov = &iov;
    282 	uio.uio_iovcnt = 1;
    283 	uio.uio_offset = (off_t)(intptr_t)uaddr;
    284 	uio.uio_resid = len;
    285 	uio.uio_rw = UIO_READ;
    286 	UIO_SETUP_SYSSPACE(&uio);
    287 	error = uvm_io(&vm->vm_map, &uio);
    288 
    289 	return (error);
    290 }
    291 
    292 /*
    293  * Like copyout(), but operates on an arbitrary vmspace.
    294  */
    295 int
    296 copyout_vmspace(struct vmspace *vm, const void *kaddr, void *uaddr, size_t len)
    297 {
    298 	struct iovec iov;
    299 	struct uio uio;
    300 	int error;
    301 
    302 	if (len == 0)
    303 		return (0);
    304 
    305 	if (VMSPACE_IS_KERNEL_P(vm)) {
    306 		return kcopy(kaddr, uaddr, len);
    307 	}
    308 	if (__predict_true(vm == curproc->p_vmspace)) {
    309 		return copyout(kaddr, uaddr, len);
    310 	}
    311 
    312 	iov.iov_base = __UNCONST(kaddr); /* XXXUNCONST cast away const */
    313 	iov.iov_len = len;
    314 	uio.uio_iov = &iov;
    315 	uio.uio_iovcnt = 1;
    316 	uio.uio_offset = (off_t)(intptr_t)uaddr;
    317 	uio.uio_resid = len;
    318 	uio.uio_rw = UIO_WRITE;
    319 	UIO_SETUP_SYSSPACE(&uio);
    320 	error = uvm_io(&vm->vm_map, &uio);
    321 
    322 	return (error);
    323 }
    324 
    325 /*
    326  * Like copyin(), but operates on an arbitrary process.
    327  */
    328 int
    329 copyin_proc(struct proc *p, const void *uaddr, void *kaddr, size_t len)
    330 {
    331 	struct vmspace *vm;
    332 	int error;
    333 
    334 	error = proc_vmspace_getref(p, &vm);
    335 	if (error) {
    336 		return error;
    337 	}
    338 	error = copyin_vmspace(vm, uaddr, kaddr, len);
    339 	uvmspace_free(vm);
    340 
    341 	return error;
    342 }
    343 
    344 /*
    345  * Like copyout(), but operates on an arbitrary process.
    346  */
    347 int
    348 copyout_proc(struct proc *p, const void *kaddr, void *uaddr, size_t len)
    349 {
    350 	struct vmspace *vm;
    351 	int error;
    352 
    353 	error = proc_vmspace_getref(p, &vm);
    354 	if (error) {
    355 		return error;
    356 	}
    357 	error = copyout_vmspace(vm, kaddr, uaddr, len);
    358 	uvmspace_free(vm);
    359 
    360 	return error;
    361 }
    362 
    363 /*
    364  * Like copyin(), except it operates on kernel addresses when the FKIOCTL
    365  * flag is passed in `ioctlflags' from the ioctl call.
    366  */
    367 int
    368 ioctl_copyin(int ioctlflags, const void *src, void *dst, size_t len)
    369 {
    370 	if (ioctlflags & FKIOCTL)
    371 		return kcopy(src, dst, len);
    372 	return copyin(src, dst, len);
    373 }
    374 
    375 /*
    376  * Like copyout(), except it operates on kernel addresses when the FKIOCTL
    377  * flag is passed in `ioctlflags' from the ioctl call.
    378  */
    379 int
    380 ioctl_copyout(int ioctlflags, const void *src, void *dst, size_t len)
    381 {
    382 	if (ioctlflags & FKIOCTL)
    383 		return kcopy(src, dst, len);
    384 	return copyout(src, dst, len);
    385 }
    386 
    387 /*
    388  * General routine to allocate a hash table.
    389  * Allocate enough memory to hold at least `elements' list-head pointers.
    390  * Return a pointer to the allocated space and set *hashmask to a pattern
    391  * suitable for masking a value to use as an index into the returned array.
    392  */
    393 void *
    394 hashinit(u_int elements, enum hashtype htype, struct malloc_type *mtype,
    395     int mflags, u_long *hashmask)
    396 {
    397 	u_long hashsize, i;
    398 	LIST_HEAD(, generic) *hashtbl_list;
    399 	TAILQ_HEAD(, generic) *hashtbl_tailq;
    400 	size_t esize;
    401 	void *p;
    402 
    403 	if (elements == 0)
    404 		panic("hashinit: bad cnt");
    405 	for (hashsize = 1; hashsize < elements; hashsize <<= 1)
    406 		continue;
    407 
    408 	switch (htype) {
    409 	case HASH_LIST:
    410 		esize = sizeof(*hashtbl_list);
    411 		break;
    412 	case HASH_TAILQ:
    413 		esize = sizeof(*hashtbl_tailq);
    414 		break;
    415 	default:
    416 #ifdef DIAGNOSTIC
    417 		panic("hashinit: invalid table type");
    418 #else
    419 		return NULL;
    420 #endif
    421 	}
    422 
    423 	if ((p = malloc(hashsize * esize, mtype, mflags)) == NULL)
    424 		return (NULL);
    425 
    426 	switch (htype) {
    427 	case HASH_LIST:
    428 		hashtbl_list = p;
    429 		for (i = 0; i < hashsize; i++)
    430 			LIST_INIT(&hashtbl_list[i]);
    431 		break;
    432 	case HASH_TAILQ:
    433 		hashtbl_tailq = p;
    434 		for (i = 0; i < hashsize; i++)
    435 			TAILQ_INIT(&hashtbl_tailq[i]);
    436 		break;
    437 	}
    438 	*hashmask = hashsize - 1;
    439 	return (p);
    440 }
    441 
    442 /*
    443  * Free memory from hash table previosly allocated via hashinit().
    444  */
    445 void
    446 hashdone(void *hashtbl, struct malloc_type *mtype)
    447 {
    448 
    449 	free(hashtbl, mtype);
    450 }
    451 
    452 
    453 static void *
    454 hook_establish(hook_list_t *list, void (*fn)(void *), void *arg)
    455 {
    456 	struct hook_desc *hd;
    457 
    458 	hd = malloc(sizeof(*hd), M_DEVBUF, M_NOWAIT);
    459 	if (hd == NULL)
    460 		return (NULL);
    461 
    462 	hd->hk_fn = fn;
    463 	hd->hk_arg = arg;
    464 	LIST_INSERT_HEAD(list, hd, hk_list);
    465 
    466 	return (hd);
    467 }
    468 
    469 static void
    470 hook_disestablish(hook_list_t *list, void *vhook)
    471 {
    472 #ifdef DIAGNOSTIC
    473 	struct hook_desc *hd;
    474 
    475 	LIST_FOREACH(hd, list, hk_list) {
    476                 if (hd == vhook)
    477 			break;
    478 	}
    479 
    480 	if (hd == NULL)
    481 		panic("hook_disestablish: hook %p not established", vhook);
    482 #endif
    483 	LIST_REMOVE((struct hook_desc *)vhook, hk_list);
    484 	free(vhook, M_DEVBUF);
    485 }
    486 
    487 static void
    488 hook_destroy(hook_list_t *list)
    489 {
    490 	struct hook_desc *hd;
    491 
    492 	while ((hd = LIST_FIRST(list)) != NULL) {
    493 		LIST_REMOVE(hd, hk_list);
    494 		free(hd, M_DEVBUF);
    495 	}
    496 }
    497 
    498 static void
    499 hook_proc_run(hook_list_t *list, struct proc *p)
    500 {
    501 	struct hook_desc *hd;
    502 
    503 	for (hd = LIST_FIRST(list); hd != NULL; hd = LIST_NEXT(hd, hk_list)) {
    504 		((void (*)(struct proc *, void *))*hd->hk_fn)(p,
    505 		    hd->hk_arg);
    506 	}
    507 }
    508 
    509 /*
    510  * "Shutdown hook" types, functions, and variables.
    511  *
    512  * Should be invoked immediately before the
    513  * system is halted or rebooted, i.e. after file systems unmounted,
    514  * after crash dump done, etc.
    515  *
    516  * Each shutdown hook is removed from the list before it's run, so that
    517  * it won't be run again.
    518  */
    519 
    520 static hook_list_t shutdownhook_list;
    521 
    522 void *
    523 shutdownhook_establish(void (*fn)(void *), void *arg)
    524 {
    525 	return hook_establish(&shutdownhook_list, fn, arg);
    526 }
    527 
    528 void
    529 shutdownhook_disestablish(void *vhook)
    530 {
    531 	hook_disestablish(&shutdownhook_list, vhook);
    532 }
    533 
    534 /*
    535  * Run shutdown hooks.  Should be invoked immediately before the
    536  * system is halted or rebooted, i.e. after file systems unmounted,
    537  * after crash dump done, etc.
    538  *
    539  * Each shutdown hook is removed from the list before it's run, so that
    540  * it won't be run again.
    541  */
    542 void
    543 doshutdownhooks(void)
    544 {
    545 	struct hook_desc *dp;
    546 
    547 	while ((dp = LIST_FIRST(&shutdownhook_list)) != NULL) {
    548 		LIST_REMOVE(dp, hk_list);
    549 		(*dp->hk_fn)(dp->hk_arg);
    550 #if 0
    551 		/*
    552 		 * Don't bother freeing the hook structure,, since we may
    553 		 * be rebooting because of a memory corruption problem,
    554 		 * and this might only make things worse.  It doesn't
    555 		 * matter, anyway, since the system is just about to
    556 		 * reboot.
    557 		 */
    558 		free(dp, M_DEVBUF);
    559 #endif
    560 	}
    561 }
    562 
    563 /*
    564  * "Mountroot hook" types, functions, and variables.
    565  */
    566 
    567 static hook_list_t mountroothook_list;
    568 
    569 void *
    570 mountroothook_establish(void (*fn)(struct device *), struct device *dev)
    571 {
    572 	return hook_establish(&mountroothook_list, (void (*)(void *))fn, dev);
    573 }
    574 
    575 void
    576 mountroothook_disestablish(void *vhook)
    577 {
    578 	hook_disestablish(&mountroothook_list, vhook);
    579 }
    580 
    581 void
    582 mountroothook_destroy(void)
    583 {
    584 	hook_destroy(&mountroothook_list);
    585 }
    586 
    587 void
    588 domountroothook(void)
    589 {
    590 	struct hook_desc *hd;
    591 
    592 	LIST_FOREACH(hd, &mountroothook_list, hk_list) {
    593 		if (hd->hk_arg == (void *)root_device) {
    594 			(*hd->hk_fn)(hd->hk_arg);
    595 			return;
    596 		}
    597 	}
    598 }
    599 
    600 static hook_list_t exechook_list;
    601 
    602 void *
    603 exechook_establish(void (*fn)(struct proc *, void *), void *arg)
    604 {
    605 	return hook_establish(&exechook_list, (void (*)(void *))fn, arg);
    606 }
    607 
    608 void
    609 exechook_disestablish(void *vhook)
    610 {
    611 	hook_disestablish(&exechook_list, vhook);
    612 }
    613 
    614 /*
    615  * Run exec hooks.
    616  */
    617 void
    618 doexechooks(struct proc *p)
    619 {
    620 	hook_proc_run(&exechook_list, p);
    621 }
    622 
    623 static hook_list_t exithook_list;
    624 
    625 void *
    626 exithook_establish(void (*fn)(struct proc *, void *), void *arg)
    627 {
    628 	return hook_establish(&exithook_list, (void (*)(void *))fn, arg);
    629 }
    630 
    631 void
    632 exithook_disestablish(void *vhook)
    633 {
    634 	hook_disestablish(&exithook_list, vhook);
    635 }
    636 
    637 /*
    638  * Run exit hooks.
    639  */
    640 void
    641 doexithooks(struct proc *p)
    642 {
    643 	hook_proc_run(&exithook_list, p);
    644 }
    645 
    646 static hook_list_t forkhook_list;
    647 
    648 void *
    649 forkhook_establish(void (*fn)(struct proc *, struct proc *))
    650 {
    651 	return hook_establish(&forkhook_list, (void (*)(void *))fn, NULL);
    652 }
    653 
    654 void
    655 forkhook_disestablish(void *vhook)
    656 {
    657 	hook_disestablish(&forkhook_list, vhook);
    658 }
    659 
    660 /*
    661  * Run fork hooks.
    662  */
    663 void
    664 doforkhooks(struct proc *p2, struct proc *p1)
    665 {
    666 	struct hook_desc *hd;
    667 
    668 	LIST_FOREACH(hd, &forkhook_list, hk_list) {
    669 		((void (*)(struct proc *, struct proc *))*hd->hk_fn)
    670 		    (p2, p1);
    671 	}
    672 }
    673 
    674 /*
    675  * "Power hook" types, functions, and variables.
    676  * The list of power hooks is kept ordered with the last registered hook
    677  * first.
    678  * When running the hooks on power down the hooks are called in reverse
    679  * registration order, when powering up in registration order.
    680  */
    681 struct powerhook_desc {
    682 	CIRCLEQ_ENTRY(powerhook_desc) sfd_list;
    683 	void	(*sfd_fn)(int, void *);
    684 	void	*sfd_arg;
    685 	char	sfd_name[16];
    686 };
    687 
    688 static CIRCLEQ_HEAD(, powerhook_desc) powerhook_list =
    689     CIRCLEQ_HEAD_INITIALIZER(powerhook_list);
    690 
    691 void *
    692 powerhook_establish(const char *name, void (*fn)(int, void *), void *arg)
    693 {
    694 	struct powerhook_desc *ndp;
    695 
    696 	ndp = (struct powerhook_desc *)
    697 	    malloc(sizeof(*ndp), M_DEVBUF, M_NOWAIT);
    698 	if (ndp == NULL)
    699 		return (NULL);
    700 
    701 	ndp->sfd_fn = fn;
    702 	ndp->sfd_arg = arg;
    703 	strlcpy(ndp->sfd_name, name, sizeof(ndp->sfd_name));
    704 	CIRCLEQ_INSERT_HEAD(&powerhook_list, ndp, sfd_list);
    705 
    706 	return (ndp);
    707 }
    708 
    709 void
    710 powerhook_disestablish(void *vhook)
    711 {
    712 #ifdef DIAGNOSTIC
    713 	struct powerhook_desc *dp;
    714 
    715 	CIRCLEQ_FOREACH(dp, &powerhook_list, sfd_list)
    716                 if (dp == vhook)
    717 			goto found;
    718 	panic("powerhook_disestablish: hook %p not established", vhook);
    719  found:
    720 #endif
    721 
    722 	CIRCLEQ_REMOVE(&powerhook_list, (struct powerhook_desc *)vhook,
    723 	    sfd_list);
    724 	free(vhook, M_DEVBUF);
    725 }
    726 
    727 /*
    728  * Run power hooks.
    729  */
    730 void
    731 dopowerhooks(int why)
    732 {
    733 	struct powerhook_desc *dp;
    734 
    735 #ifdef POWERHOOK_DEBUG
    736 	printf("dopowerhooks ");
    737 	switch (why) {
    738 	case PWR_RESUME:
    739 		printf("resume");
    740 		break;
    741 	case PWR_SOFTRESUME:
    742 		printf("softresume");
    743 		break;
    744 	case PWR_SUSPEND:
    745 		printf("suspend");
    746 		break;
    747 	case PWR_SOFTSUSPEND:
    748 		printf("softsuspend");
    749 		break;
    750 	case PWR_STANDBY:
    751 		printf("standby");
    752 		break;
    753 	}
    754 	printf(":");
    755 #endif
    756 
    757 	if (why == PWR_RESUME || why == PWR_SOFTRESUME) {
    758 		CIRCLEQ_FOREACH_REVERSE(dp, &powerhook_list, sfd_list) {
    759 #ifdef POWERHOOK_DEBUG
    760 			printf(" %s", dp->sfd_name);
    761 #endif
    762 			(*dp->sfd_fn)(why, dp->sfd_arg);
    763 		}
    764 	} else {
    765 		CIRCLEQ_FOREACH(dp, &powerhook_list, sfd_list) {
    766 #ifdef POWERHOOK_DEBUG
    767 			printf(" %s", dp->sfd_name);
    768 #endif
    769 			(*dp->sfd_fn)(why, dp->sfd_arg);
    770 		}
    771 	}
    772 
    773 #ifdef POWERHOOK_DEBUG
    774 	printf(".\n");
    775 #endif
    776 }
    777 
    778 /*
    779  * Determine the root device and, if instructed to, the root file system.
    780  */
    781 
    782 #include "md.h"
    783 #if NMD == 0
    784 #undef MEMORY_DISK_HOOKS
    785 #endif
    786 
    787 #ifdef MEMORY_DISK_HOOKS
    788 static struct device fakemdrootdev[NMD];
    789 extern struct cfdriver md_cd;
    790 #endif
    791 
    792 #ifdef MEMORY_DISK_IS_ROOT
    793 #define BOOT_FROM_MEMORY_HOOKS 1
    794 #endif
    795 
    796 /*
    797  * The device and wedge that we booted from.  If booted_wedge is NULL,
    798  * the we might consult booted_partition.
    799  */
    800 struct device *booted_device;
    801 struct device *booted_wedge;
    802 int booted_partition;
    803 
    804 /*
    805  * Use partition letters if it's a disk class but not a wedge.
    806  * XXX Check for wedge is kinda gross.
    807  */
    808 #define	DEV_USES_PARTITIONS(dv)						\
    809 	(device_class((dv)) == DV_DISK &&				\
    810 	 !device_is_a((dv), "dk"))
    811 
    812 void
    813 setroot(struct device *bootdv, int bootpartition)
    814 {
    815 	struct device *dv;
    816 	int len, majdev;
    817 #ifdef MEMORY_DISK_HOOKS
    818 	int i;
    819 #endif
    820 	dev_t nrootdev;
    821 	dev_t ndumpdev = NODEV;
    822 	char buf[128];
    823 	const char *rootdevname;
    824 	const char *dumpdevname;
    825 	struct device *rootdv = NULL;		/* XXX gcc -Wuninitialized */
    826 	struct device *dumpdv = NULL;
    827 	struct ifnet *ifp;
    828 	const char *deffsname;
    829 	struct vfsops *vops;
    830 
    831 #ifdef TFTPROOT
    832 	if (tftproot_dhcpboot(bootdv) != 0)
    833 		boothowto |= RB_ASKNAME;
    834 #endif
    835 
    836 #ifdef MEMORY_DISK_HOOKS
    837 	for (i = 0; i < NMD; i++) {
    838 		fakemdrootdev[i].dv_class  = DV_DISK;
    839 		fakemdrootdev[i].dv_cfdata = NULL;
    840 		fakemdrootdev[i].dv_cfdriver = &md_cd;
    841 		fakemdrootdev[i].dv_unit   = i;
    842 		fakemdrootdev[i].dv_parent = NULL;
    843 		snprintf(fakemdrootdev[i].dv_xname,
    844 		    sizeof(fakemdrootdev[i].dv_xname), "md%d", i);
    845 	}
    846 #endif /* MEMORY_DISK_HOOKS */
    847 
    848 #ifdef MEMORY_DISK_IS_ROOT
    849 	bootdv = &fakemdrootdev[0];
    850 	bootpartition = 0;
    851 #endif
    852 
    853 	/*
    854 	 * If NFS is specified as the file system, and we found
    855 	 * a DV_DISK boot device (or no boot device at all), then
    856 	 * find a reasonable network interface for "rootspec".
    857 	 */
    858 	vops = vfs_getopsbyname("nfs");
    859 	if (vops != NULL && vops->vfs_mountroot == mountroot &&
    860 	    rootspec == NULL &&
    861 	    (bootdv == NULL || device_class(bootdv) != DV_IFNET)) {
    862 		IFNET_FOREACH(ifp) {
    863 			if ((ifp->if_flags &
    864 			     (IFF_LOOPBACK|IFF_POINTOPOINT)) == 0)
    865 				break;
    866 		}
    867 		if (ifp == NULL) {
    868 			/*
    869 			 * Can't find a suitable interface; ask the
    870 			 * user.
    871 			 */
    872 			boothowto |= RB_ASKNAME;
    873 		} else {
    874 			/*
    875 			 * Have a suitable interface; behave as if
    876 			 * the user specified this interface.
    877 			 */
    878 			rootspec = (const char *)ifp->if_xname;
    879 		}
    880 	}
    881 
    882 	/*
    883 	 * If wildcarded root and we the boot device wasn't determined,
    884 	 * ask the user.
    885 	 */
    886 	if (rootspec == NULL && bootdv == NULL)
    887 		boothowto |= RB_ASKNAME;
    888 
    889  top:
    890 	if (boothowto & RB_ASKNAME) {
    891 		struct device *defdumpdv;
    892 
    893 		for (;;) {
    894 			printf("root device");
    895 			if (bootdv != NULL) {
    896 				printf(" (default %s", bootdv->dv_xname);
    897 				if (DEV_USES_PARTITIONS(bootdv))
    898 					printf("%c", bootpartition + 'a');
    899 				printf(")");
    900 			}
    901 			printf(": ");
    902 			len = cngetsn(buf, sizeof(buf));
    903 			if (len == 0 && bootdv != NULL) {
    904 				strlcpy(buf, bootdv->dv_xname, sizeof(buf));
    905 				len = strlen(buf);
    906 			}
    907 			if (len > 0 && buf[len - 1] == '*') {
    908 				buf[--len] = '\0';
    909 				dv = getdisk(buf, len, 1, &nrootdev, 0);
    910 				if (dv != NULL) {
    911 					rootdv = dv;
    912 					break;
    913 				}
    914 			}
    915 			dv = getdisk(buf, len, bootpartition, &nrootdev, 0);
    916 			if (dv != NULL) {
    917 				rootdv = dv;
    918 				break;
    919 			}
    920 		}
    921 
    922 		/*
    923 		 * Set up the default dump device.  If root is on
    924 		 * a network device, there is no default dump
    925 		 * device, since we don't support dumps to the
    926 		 * network.
    927 		 */
    928 		if (DEV_USES_PARTITIONS(rootdv) == 0)
    929 			defdumpdv = NULL;
    930 		else
    931 			defdumpdv = rootdv;
    932 
    933 		for (;;) {
    934 			printf("dump device");
    935 			if (defdumpdv != NULL) {
    936 				/*
    937 				 * Note, we know it's a disk if we get here.
    938 				 */
    939 				printf(" (default %sb)", defdumpdv->dv_xname);
    940 			}
    941 			printf(": ");
    942 			len = cngetsn(buf, sizeof(buf));
    943 			if (len == 0) {
    944 				if (defdumpdv != NULL) {
    945 					ndumpdev = MAKEDISKDEV(major(nrootdev),
    946 					    DISKUNIT(nrootdev), 1);
    947 				}
    948 				dumpdv = defdumpdv;
    949 				break;
    950 			}
    951 			if (len == 4 && strcmp(buf, "none") == 0) {
    952 				dumpdv = NULL;
    953 				break;
    954 			}
    955 			dv = getdisk(buf, len, 1, &ndumpdev, 1);
    956 			if (dv != NULL) {
    957 				dumpdv = dv;
    958 				break;
    959 			}
    960 		}
    961 
    962 		rootdev = nrootdev;
    963 		dumpdev = ndumpdev;
    964 
    965 		for (vops = LIST_FIRST(&vfs_list); vops != NULL;
    966 		     vops = LIST_NEXT(vops, vfs_list)) {
    967 			if (vops->vfs_mountroot != NULL &&
    968 			    vops->vfs_mountroot == mountroot)
    969 			break;
    970 		}
    971 
    972 		if (vops == NULL) {
    973 			mountroot = NULL;
    974 			deffsname = "generic";
    975 		} else
    976 			deffsname = vops->vfs_name;
    977 
    978 		for (;;) {
    979 			printf("file system (default %s): ", deffsname);
    980 			len = cngetsn(buf, sizeof(buf));
    981 			if (len == 0)
    982 				break;
    983 			if (len == 4 && strcmp(buf, "halt") == 0)
    984 				cpu_reboot(RB_HALT, NULL);
    985 			else if (len == 6 && strcmp(buf, "reboot") == 0)
    986 				cpu_reboot(0, NULL);
    987 #if defined(DDB)
    988 			else if (len == 3 && strcmp(buf, "ddb") == 0) {
    989 				console_debugger();
    990 			}
    991 #endif
    992 			else if (len == 7 && strcmp(buf, "generic") == 0) {
    993 				mountroot = NULL;
    994 				break;
    995 			}
    996 			vops = vfs_getopsbyname(buf);
    997 			if (vops == NULL || vops->vfs_mountroot == NULL) {
    998 				printf("use one of: generic");
    999 				for (vops = LIST_FIRST(&vfs_list);
   1000 				     vops != NULL;
   1001 				     vops = LIST_NEXT(vops, vfs_list)) {
   1002 					if (vops->vfs_mountroot != NULL)
   1003 						printf(" %s", vops->vfs_name);
   1004 				}
   1005 #if defined(DDB)
   1006 				printf(" ddb");
   1007 #endif
   1008 				printf(" halt reboot\n");
   1009 			} else {
   1010 				mountroot = vops->vfs_mountroot;
   1011 				break;
   1012 			}
   1013 		}
   1014 
   1015 	} else if (rootspec == NULL) {
   1016 		/*
   1017 		 * Wildcarded root; use the boot device.
   1018 		 */
   1019 		rootdv = bootdv;
   1020 
   1021 		majdev = devsw_name2blk(bootdv->dv_xname, NULL, 0);
   1022 		if (majdev >= 0) {
   1023 			/*
   1024 			 * Root is on a disk.  `bootpartition' is root,
   1025 			 * unless the device does not use partitions.
   1026 			 */
   1027 			if (DEV_USES_PARTITIONS(bootdv))
   1028 				rootdev = MAKEDISKDEV(majdev,
   1029 						      device_unit(bootdv),
   1030 						      bootpartition);
   1031 			else
   1032 				rootdev = makedev(majdev, device_unit(bootdv));
   1033 		}
   1034 	} else {
   1035 
   1036 		/*
   1037 		 * `root on <dev> ...'
   1038 		 */
   1039 
   1040 		/*
   1041 		 * If it's a network interface, we can bail out
   1042 		 * early.
   1043 		 */
   1044 		dv = finddevice(rootspec);
   1045 		if (dv != NULL && device_class(dv) == DV_IFNET) {
   1046 			rootdv = dv;
   1047 			goto haveroot;
   1048 		}
   1049 
   1050 		if (rootdev == NODEV &&
   1051 		    device_class(dv) == DV_DISK && device_is_a(dv, "dk") &&
   1052 		    (majdev = devsw_name2blk(dv->dv_xname, NULL, 0)) >= 0)
   1053 			rootdev = makedev(majdev, device_unit(dv));
   1054 
   1055 		rootdevname = devsw_blk2name(major(rootdev));
   1056 		if (rootdevname == NULL) {
   1057 			printf("unknown device major 0x%x\n", rootdev);
   1058 			boothowto |= RB_ASKNAME;
   1059 			goto top;
   1060 		}
   1061 		memset(buf, 0, sizeof(buf));
   1062 		snprintf(buf, sizeof(buf), "%s%d", rootdevname,
   1063 		    DISKUNIT(rootdev));
   1064 
   1065 		rootdv = finddevice(buf);
   1066 		if (rootdv == NULL) {
   1067 			printf("device %s (0x%x) not configured\n",
   1068 			    buf, rootdev);
   1069 			boothowto |= RB_ASKNAME;
   1070 			goto top;
   1071 		}
   1072 	}
   1073 
   1074  haveroot:
   1075 
   1076 	root_device = rootdv;
   1077 
   1078 	switch (device_class(rootdv)) {
   1079 	case DV_IFNET:
   1080 	case DV_DISK:
   1081 		aprint_normal("root on %s", rootdv->dv_xname);
   1082 		if (DEV_USES_PARTITIONS(rootdv))
   1083 			aprint_normal("%c", DISKPART(rootdev) + 'a');
   1084 		break;
   1085 
   1086 	default:
   1087 		printf("can't determine root device\n");
   1088 		boothowto |= RB_ASKNAME;
   1089 		goto top;
   1090 	}
   1091 
   1092 	/*
   1093 	 * Now configure the dump device.
   1094 	 *
   1095 	 * If we haven't figured out the dump device, do so, with
   1096 	 * the following rules:
   1097 	 *
   1098 	 *	(a) We already know dumpdv in the RB_ASKNAME case.
   1099 	 *
   1100 	 *	(b) If dumpspec is set, try to use it.  If the device
   1101 	 *	    is not available, punt.
   1102 	 *
   1103 	 *	(c) If dumpspec is not set, the dump device is
   1104 	 *	    wildcarded or unspecified.  If the root device
   1105 	 *	    is DV_IFNET, punt.  Otherwise, use partition b
   1106 	 *	    of the root device.
   1107 	 */
   1108 
   1109 	if (boothowto & RB_ASKNAME) {		/* (a) */
   1110 		if (dumpdv == NULL)
   1111 			goto nodumpdev;
   1112 	} else if (dumpspec != NULL) {		/* (b) */
   1113 		if (strcmp(dumpspec, "none") == 0 || dumpdev == NODEV) {
   1114 			/*
   1115 			 * Operator doesn't want a dump device.
   1116 			 * Or looks like they tried to pick a network
   1117 			 * device.  Oops.
   1118 			 */
   1119 			goto nodumpdev;
   1120 		}
   1121 
   1122 		dumpdevname = devsw_blk2name(major(dumpdev));
   1123 		if (dumpdevname == NULL)
   1124 			goto nodumpdev;
   1125 		memset(buf, 0, sizeof(buf));
   1126 		snprintf(buf, sizeof(buf), "%s%d", dumpdevname,
   1127 		    DISKUNIT(dumpdev));
   1128 
   1129 		dumpdv = finddevice(buf);
   1130 		if (dumpdv == NULL) {
   1131 			/*
   1132 			 * Device not configured.
   1133 			 */
   1134 			goto nodumpdev;
   1135 		}
   1136 	} else {				/* (c) */
   1137 		if (DEV_USES_PARTITIONS(rootdv) == 0)
   1138 			goto nodumpdev;
   1139 		else {
   1140 			dumpdv = rootdv;
   1141 			dumpdev = MAKEDISKDEV(major(rootdev),
   1142 			    device_unit(dumpdv), 1);
   1143 		}
   1144 	}
   1145 
   1146 	aprint_normal(" dumps on %s", dumpdv->dv_xname);
   1147 	if (DEV_USES_PARTITIONS(dumpdv))
   1148 		aprint_normal("%c", DISKPART(dumpdev) + 'a');
   1149 	aprint_normal("\n");
   1150 	return;
   1151 
   1152  nodumpdev:
   1153 	dumpdev = NODEV;
   1154 	aprint_normal("\n");
   1155 }
   1156 
   1157 static struct device *
   1158 finddevice(const char *name)
   1159 {
   1160 	const char *wname;
   1161 	struct device *dv;
   1162 #if defined(BOOT_FROM_MEMORY_HOOKS)
   1163 	int j;
   1164 #endif /* BOOT_FROM_MEMORY_HOOKS */
   1165 
   1166 	if ((wname = getwedgename(name, strlen(name))) != NULL)
   1167 		return dkwedge_find_by_wname(wname);
   1168 
   1169 #ifdef BOOT_FROM_MEMORY_HOOKS
   1170 	for (j = 0; j < NMD; j++) {
   1171 		if (strcmp(name, fakemdrootdev[j].dv_xname) == 0)
   1172 			return &fakemdrootdev[j];
   1173 	}
   1174 #endif /* BOOT_FROM_MEMORY_HOOKS */
   1175 
   1176 	TAILQ_FOREACH(dv, &alldevs, dv_list) {
   1177 		if (strcmp(dv->dv_xname, name) == 0)
   1178 			break;
   1179 	}
   1180 	return dv;
   1181 }
   1182 
   1183 static struct device *
   1184 getdisk(char *str, int len, int defpart, dev_t *devp, int isdump)
   1185 {
   1186 	struct device	*dv;
   1187 #ifdef MEMORY_DISK_HOOKS
   1188 	int		i;
   1189 #endif
   1190 
   1191 	if ((dv = parsedisk(str, len, defpart, devp)) == NULL) {
   1192 		printf("use one of:");
   1193 #ifdef MEMORY_DISK_HOOKS
   1194 		if (isdump == 0)
   1195 			for (i = 0; i < NMD; i++)
   1196 				printf(" %s[a-%c]", fakemdrootdev[i].dv_xname,
   1197 				    'a' + MAXPARTITIONS - 1);
   1198 #endif
   1199 		TAILQ_FOREACH(dv, &alldevs, dv_list) {
   1200 			if (DEV_USES_PARTITIONS(dv))
   1201 				printf(" %s[a-%c]", dv->dv_xname,
   1202 				    'a' + MAXPARTITIONS - 1);
   1203 			else if (device_class(dv) == DV_DISK)
   1204 				printf(" %s", dv->dv_xname);
   1205 			if (isdump == 0 && device_class(dv) == DV_IFNET)
   1206 				printf(" %s", dv->dv_xname);
   1207 		}
   1208 		dkwedge_print_wnames();
   1209 		if (isdump)
   1210 			printf(" none");
   1211 #if defined(DDB)
   1212 		printf(" ddb");
   1213 #endif
   1214 		printf(" halt reboot\n");
   1215 	}
   1216 	return dv;
   1217 }
   1218 
   1219 static const char *
   1220 getwedgename(const char *name, int namelen)
   1221 {
   1222 	const char *wpfx = "wedge:";
   1223 	const int wpfxlen = strlen(wpfx);
   1224 
   1225 	if (namelen < wpfxlen || strncmp(name, wpfx, wpfxlen) != 0)
   1226 		return NULL;
   1227 
   1228 	return name + wpfxlen;
   1229 }
   1230 
   1231 static struct device *
   1232 parsedisk(char *str, int len, int defpart, dev_t *devp)
   1233 {
   1234 	struct device *dv;
   1235 	const char *wname;
   1236 	char *cp, c;
   1237 	int majdev, part;
   1238 #ifdef MEMORY_DISK_HOOKS
   1239 	int i;
   1240 #endif
   1241 	if (len == 0)
   1242 		return (NULL);
   1243 
   1244 	if (len == 4 && strcmp(str, "halt") == 0)
   1245 		cpu_reboot(RB_HALT, NULL);
   1246 	else if (len == 6 && strcmp(str, "reboot") == 0)
   1247 		cpu_reboot(0, NULL);
   1248 #if defined(DDB)
   1249 	else if (len == 3 && strcmp(str, "ddb") == 0)
   1250 		console_debugger();
   1251 #endif
   1252 
   1253 	cp = str + len - 1;
   1254 	c = *cp;
   1255 
   1256 	if ((wname = getwedgename(str, len)) != NULL) {
   1257 		if ((dv = dkwedge_find_by_wname(wname)) == NULL)
   1258 			return NULL;
   1259 		part = defpart;
   1260 		goto gotdisk;
   1261 	} else if (c >= 'a' && c <= ('a' + MAXPARTITIONS - 1)) {
   1262 		part = c - 'a';
   1263 		*cp = '\0';
   1264 	} else
   1265 		part = defpart;
   1266 
   1267 #ifdef MEMORY_DISK_HOOKS
   1268 	for (i = 0; i < NMD; i++)
   1269 		if (strcmp(str, fakemdrootdev[i].dv_xname) == 0) {
   1270 			dv = &fakemdrootdev[i];
   1271 			goto gotdisk;
   1272 		}
   1273 #endif
   1274 
   1275 	dv = finddevice(str);
   1276 	if (dv != NULL) {
   1277 		if (device_class(dv) == DV_DISK) {
   1278  gotdisk:
   1279 			majdev = devsw_name2blk(dv->dv_xname, NULL, 0);
   1280 			if (majdev < 0)
   1281 				panic("parsedisk");
   1282 			if (DEV_USES_PARTITIONS(dv))
   1283 				*devp = MAKEDISKDEV(majdev, device_unit(dv),
   1284 						    part);
   1285 			else
   1286 				*devp = makedev(majdev, device_unit(dv));
   1287 		}
   1288 
   1289 		if (device_class(dv) == DV_IFNET)
   1290 			*devp = NODEV;
   1291 	}
   1292 
   1293 	*cp = c;
   1294 	return (dv);
   1295 }
   1296 
   1297 /*
   1298  * snprintf() `bytes' into `buf', reformatting it so that the number,
   1299  * plus a possible `x' + suffix extension) fits into len bytes (including
   1300  * the terminating NUL).
   1301  * Returns the number of bytes stored in buf, or -1 if there was a problem.
   1302  * E.g, given a len of 9 and a suffix of `B':
   1303  *	bytes		result
   1304  *	-----		------
   1305  *	99999		`99999 B'
   1306  *	100000		`97 kB'
   1307  *	66715648	`65152 kB'
   1308  *	252215296	`240 MB'
   1309  */
   1310 int
   1311 humanize_number(char *buf, size_t len, uint64_t bytes, const char *suffix,
   1312     int divisor)
   1313 {
   1314        	/* prefixes are: (none), kilo, Mega, Giga, Tera, Peta, Exa */
   1315 	const char *prefixes;
   1316 	int		r;
   1317 	uint64_t	umax;
   1318 	size_t		i, suffixlen;
   1319 
   1320 	if (buf == NULL || suffix == NULL)
   1321 		return (-1);
   1322 	if (len > 0)
   1323 		buf[0] = '\0';
   1324 	suffixlen = strlen(suffix);
   1325 	/* check if enough room for `x y' + suffix + `\0' */
   1326 	if (len < 4 + suffixlen)
   1327 		return (-1);
   1328 
   1329 	if (divisor == 1024) {
   1330 		/*
   1331 		 * binary multiplies
   1332 		 * XXX IEC 60027-2 recommends Ki, Mi, Gi...
   1333 		 */
   1334 		prefixes = " KMGTPE";
   1335 	} else
   1336 		prefixes = " kMGTPE"; /* SI for decimal multiplies */
   1337 
   1338 	umax = 1;
   1339 	for (i = 0; i < len - suffixlen - 3; i++)
   1340 		umax *= 10;
   1341 	for (i = 0; bytes >= umax && prefixes[i + 1]; i++)
   1342 		bytes /= divisor;
   1343 
   1344 	r = snprintf(buf, len, "%qu%s%c%s", (unsigned long long)bytes,
   1345 	    i == 0 ? "" : " ", prefixes[i], suffix);
   1346 
   1347 	return (r);
   1348 }
   1349 
   1350 int
   1351 format_bytes(char *buf, size_t len, uint64_t bytes)
   1352 {
   1353 	int	rv;
   1354 	size_t	nlen;
   1355 
   1356 	rv = humanize_number(buf, len, bytes, "B", 1024);
   1357 	if (rv != -1) {
   1358 			/* nuke the trailing ` B' if it exists */
   1359 		nlen = strlen(buf) - 2;
   1360 		if (strcmp(&buf[nlen], " B") == 0)
   1361 			buf[nlen] = '\0';
   1362 	}
   1363 	return (rv);
   1364 }
   1365 
   1366 /*
   1367  * Return true if system call tracing is enabled for the specified process.
   1368  */
   1369 bool
   1370 trace_is_enabled(struct proc *p)
   1371 {
   1372 #ifdef SYSCALL_DEBUG
   1373 	return (true);
   1374 #endif
   1375 #ifdef KTRACE
   1376 	if (ISSET(p->p_traceflag, (KTRFAC_SYSCALL | KTRFAC_SYSRET)))
   1377 		return (true);
   1378 #endif
   1379 #ifdef SYSTRACE
   1380 	if (ISSET(p->p_flag, PK_SYSTRACE))
   1381 		return (true);
   1382 #endif
   1383 #ifdef PTRACE
   1384 	if (ISSET(p->p_slflag, PSL_SYSCALL))
   1385 		return (true);
   1386 #endif
   1387 
   1388 	return (false);
   1389 }
   1390 
   1391 /*
   1392  * Start trace of particular system call. If process is being traced,
   1393  * this routine is called by MD syscall dispatch code just before
   1394  * a system call is actually executed.
   1395  * MD caller guarantees the passed 'code' is within the supported
   1396  * system call number range for emulation the process runs under.
   1397  */
   1398 int
   1399 trace_enter(struct lwp *l, register_t code,
   1400     register_t realcode, const struct sysent *callp, void *args)
   1401 {
   1402 #if defined(SYSCALL_DEBUG) || defined(KTRACE) || defined(PTRACE) || defined(SYSTRACE)
   1403 	struct proc *p = l->l_proc;
   1404 
   1405 #ifdef SYSCALL_DEBUG
   1406 	scdebug_call(l, code, args);
   1407 #endif /* SYSCALL_DEBUG */
   1408 
   1409 #ifdef KTRACE
   1410 	if (KTRPOINT(p, KTR_SYSCALL))
   1411 		ktrsyscall(l, code, realcode, callp, args);
   1412 #endif /* KTRACE */
   1413 
   1414 #ifdef PTRACE
   1415 	if ((p->p_slflag & (PSL_SYSCALL|PSL_TRACED)) ==
   1416 	    (PSL_SYSCALL|PSL_TRACED))
   1417 		process_stoptrace(l);
   1418 #endif
   1419 
   1420 #ifdef SYSTRACE
   1421 	if (ISSET(p->p_flag, PK_SYSTRACE)) {
   1422 		int error;
   1423 		KERNEL_LOCK(1, l);
   1424 		error = systrace_enter(l, code, args);
   1425 		KERNEL_UNLOCK_ONE(l);
   1426 		return error;
   1427 	}
   1428 #endif
   1429 #endif /* SYSCALL_DEBUG || {K,P,SYS}TRACE */
   1430 	return 0;
   1431 }
   1432 
   1433 /*
   1434  * End trace of particular system call. If process is being traced,
   1435  * this routine is called by MD syscall dispatch code just after
   1436  * a system call finishes.
   1437  * MD caller guarantees the passed 'code' is within the supported
   1438  * system call number range for emulation the process runs under.
   1439  */
   1440 void
   1441 trace_exit(struct lwp *l, register_t code, void *args, register_t rval[],
   1442     int error)
   1443 {
   1444 #if defined(SYSCALL_DEBUG) || defined(KTRACE) || defined(PTRACE) || defined(SYSTRACE)
   1445 	struct proc *p = l->l_proc;
   1446 
   1447 #ifdef SYSCALL_DEBUG
   1448 	scdebug_ret(l, code, error, rval);
   1449 #endif /* SYSCALL_DEBUG */
   1450 
   1451 #ifdef KTRACE
   1452 	if (KTRPOINT(p, KTR_SYSRET))
   1453 		ktrsysret(l, code, error, rval);
   1454 #endif /* KTRACE */
   1455 
   1456 #ifdef PTRACE
   1457 	if ((p->p_slflag & (PSL_SYSCALL|PSL_TRACED)) ==
   1458 	    (PSL_SYSCALL|PSL_TRACED))
   1459 		process_stoptrace(l);
   1460 #endif
   1461 
   1462 #ifdef SYSTRACE
   1463 	if (ISSET(p->p_flag, PK_SYSTRACE)) {
   1464 		KERNEL_LOCK(1, l);
   1465 		systrace_exit(l, code, args, rval, error);
   1466 		KERNEL_UNLOCK_ONE(l);
   1467 	}
   1468 #endif
   1469 #endif /* SYSCALL_DEBUG || {K,P,SYS}TRACE */
   1470 }
   1471