root/usr/src/lib/libzpool/common/kernel.c
/*
 * CDDL HEADER START
 *
 * The contents of this file are subject to the terms of the
 * Common Development and Distribution License (the "License").
 * You may not use this file except in compliance with the License.
 *
 * You can obtain a copy of the license at usr/src/OPENSOLARIS.LICENSE
 * or http://www.opensolaris.org/os/licensing.
 * See the License for the specific language governing permissions
 * and limitations under the License.
 *
 * When distributing Covered Code, include this CDDL HEADER in each
 * file and include the License file at usr/src/OPENSOLARIS.LICENSE.
 * If applicable, add the following below this CDDL HEADER, with the
 * fields enclosed by brackets "[]" replaced with your own identifying
 * information: Portions Copyright [yyyy] [name of copyright owner]
 *
 * CDDL HEADER END
 */
/*
 * Copyright (c) 2005, 2010, Oracle and/or its affiliates. All rights reserved.
 * Copyright (c) 2012, 2015 by Delphix. All rights reserved.
 * Copyright 2020 Joyent, Inc.
 * Copyright 2017 RackTop Systems.
 */

#include <assert.h>
#include <fcntl.h>
#include <poll.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <zlib.h>
#include <libgen.h>
#include <sys/spa.h>
#include <sys/stat.h>
#include <sys/processor.h>
#include <sys/zfs_context.h>
#include <zfs_fletcher.h>
#include <sys/rrwlock.h>
#include <sys/zmod.h>
#include <sys/utsname.h>
#include <sys/systeminfo.h>
#include <libzutil.h>
#include <sys/crypto/common.h>
#include <sys/crypto/impl.h>
#include <sys/crypto/api.h>
#include <sys/sha2.h>
#include <crypto/aes/aes_impl.h>

extern void system_taskq_init(void);
extern void system_taskq_fini(void);

/*
 * Emulation of kernel services in userland.
 */

pgcnt_t physmem;
vnode_t *rootdir = (vnode_t *)0xabcd1234;
char hw_serial[HW_HOSTID_LEN];
kmutex_t cpu_lock;
vmem_t *zio_arena = NULL;

/* If set, all blocks read will be copied to the specified directory. */
char *vn_dumpdir = NULL;

struct utsname utsname = {
        "userland", "libzpool", "1", "1", "na"
};

/*
 * =========================================================================
 * vnode operations
 * =========================================================================
 */
/*
 * Note: for the xxxat() versions of these functions, we assume that the
 * starting vp is always rootdir (which is true for spa_directory.c, the only
 * ZFS consumer of these interfaces).  We assert this is true, and then emulate
 * them by adding '/' in front of the path.
 */

/*ARGSUSED*/
int
vn_open(char *path, int x1, int flags, int mode, vnode_t **vpp, int x2, int x3)
{
        int fd;
        int dump_fd;
        vnode_t *vp;
        int old_umask;
        char realpath[MAXPATHLEN];
        struct stat64 st;

        /*
         * If we're accessing a real disk from userland, we need to use
         * the character interface to avoid caching.  This is particularly
         * important if we're trying to look at a real in-kernel storage
         * pool from userland, e.g. via zdb, because otherwise we won't
         * see the changes occurring under the segmap cache.
         * On the other hand, the stupid character device returns zero
         * for its size.  So -- gag -- we open the block device to get
         * its size, and remember it for subsequent VOP_GETATTR().
         */
        if (strncmp(path, "/dev/", 5) == 0) {
                char *dsk;
                fd = open64(path, O_RDONLY);
                if (fd == -1)
                        return (errno);
                if (fstat64(fd, &st) == -1) {
                        close(fd);
                        return (errno);
                }
                close(fd);
                (void) sprintf(realpath, "%s", path);
                dsk = strstr(path, "/dsk/");
                if (dsk != NULL)
                        (void) sprintf(realpath + (dsk - path) + 1, "r%s",
                            dsk + 1);
        } else {
                (void) sprintf(realpath, "%s", path);
                if (!(flags & FCREAT) && stat64(realpath, &st) == -1)
                        return (errno);
        }

        if (flags & FCREAT)
                old_umask = umask(0);

        /*
         * The construct 'flags - FREAD' conveniently maps combinations of
         * FREAD and FWRITE to the corresponding O_RDONLY, O_WRONLY, and O_RDWR.
         */
        fd = open64(realpath, flags - FREAD, mode);

        if (flags & FCREAT)
                (void) umask(old_umask);

        if (vn_dumpdir != NULL) {
                char dumppath[MAXPATHLEN];
                (void) snprintf(dumppath, sizeof (dumppath),
                    "%s/%s", vn_dumpdir, basename(realpath));
                dump_fd = open64(dumppath, O_CREAT | O_WRONLY, 0666);
                if (dump_fd == -1)
                        return (errno);
        } else {
                dump_fd = -1;
        }

        if (fd == -1)
                return (errno);

        if (fstat64(fd, &st) == -1) {
                close(fd);
                return (errno);
        }

        (void) fcntl(fd, F_SETFD, FD_CLOEXEC);

        *vpp = vp = umem_zalloc(sizeof (vnode_t), UMEM_NOFAIL);

        vp->v_fd = fd;
        vp->v_size = st.st_size;
        vp->v_path = spa_strdup(path);
        vp->v_dump_fd = dump_fd;

        return (0);
}

/*ARGSUSED*/
int
vn_openat(char *path, int x1, int flags, int mode, vnode_t **vpp, int x2,
    int x3, vnode_t *startvp, int fd)
{
        char *realpath = umem_alloc(strlen(path) + 2, UMEM_NOFAIL);
        int ret;

        ASSERT(startvp == rootdir);
        (void) sprintf(realpath, "/%s", path);

        /* fd ignored for now, need if want to simulate nbmand support */
        ret = vn_open(realpath, x1, flags, mode, vpp, x2, x3);

        umem_free(realpath, strlen(path) + 2);

        return (ret);
}

/*ARGSUSED*/
int
vn_rdwr(int uio, vnode_t *vp, void *addr, ssize_t len, offset_t offset,
    int x1, int x2, rlim64_t x3, void *x4, ssize_t *residp)
{
        ssize_t iolen, split;

        if (uio == UIO_READ) {
                iolen = pread64(vp->v_fd, addr, len, offset);
                if (vp->v_dump_fd != -1) {
                        int status =
                            pwrite64(vp->v_dump_fd, addr, iolen, offset);
                        ASSERT(status != -1);
                }
        } else {
                /*
                 * To simulate partial disk writes, we split writes into two
                 * system calls so that the process can be killed in between.
                 */
                int sectors = len >> SPA_MINBLOCKSHIFT;
                split = (sectors > 0 ? rand() % sectors : 0) <<
                    SPA_MINBLOCKSHIFT;
                iolen = pwrite64(vp->v_fd, addr, split, offset);
                iolen += pwrite64(vp->v_fd, (char *)addr + split,
                    len - split, offset + split);
        }

        if (iolen == -1)
                return (errno);
        if (residp)
                *residp = len - iolen;
        else if (iolen != len)
                return (EIO);
        return (0);
}

void
vn_close(vnode_t *vp)
{
        close(vp->v_fd);
        if (vp->v_dump_fd != -1)
                close(vp->v_dump_fd);
        spa_strfree(vp->v_path);
        umem_free(vp, sizeof (vnode_t));
}

/*
 * At a minimum we need to update the size since vdev_reopen()
 * will no longer call vn_openat().
 */
int
fop_getattr(vnode_t *vp, vattr_t *vap)
{
        struct stat64 st;

        if (fstat64(vp->v_fd, &st) == -1) {
                close(vp->v_fd);
                return (errno);
        }

        vap->va_size = st.st_size;
        return (0);
}

#ifdef ZFS_DEBUG

/*
 * =========================================================================
 * Figure out which debugging statements to print
 * =========================================================================
 */

static char *dprintf_string;
static int dprintf_print_all;

int
dprintf_find_string(const char *string)
{
        char *tmp_str = dprintf_string;
        int len = strlen(string);

        /*
         * Find out if this is a string we want to print.
         * String format: file1.c,function_name1,file2.c,file3.c
         */

        while (tmp_str != NULL) {
                if (strncmp(tmp_str, string, len) == 0 &&
                    (tmp_str[len] == ',' || tmp_str[len] == '\0'))
                        return (1);
                tmp_str = strchr(tmp_str, ',');
                if (tmp_str != NULL)
                        tmp_str++; /* Get rid of , */
        }
        return (0);
}

void
dprintf_setup(int *argc, char **argv)
{
        int i, j;

        /*
         * Debugging can be specified two ways: by setting the
         * environment variable ZFS_DEBUG, or by including a
         * "debug=..."  argument on the command line.  The command
         * line setting overrides the environment variable.
         */

        for (i = 1; i < *argc; i++) {
                int len = strlen("debug=");
                /* First look for a command line argument */
                if (strncmp("debug=", argv[i], len) == 0) {
                        dprintf_string = argv[i] + len;
                        /* Remove from args */
                        for (j = i; j < *argc; j++)
                                argv[j] = argv[j+1];
                        argv[j] = NULL;
                        (*argc)--;
                }
        }

        if (dprintf_string == NULL) {
                /* Look for ZFS_DEBUG environment variable */
                dprintf_string = getenv("ZFS_DEBUG");
        }

        /*
         * Are we just turning on all debugging?
         */
        if (dprintf_find_string("on"))
                dprintf_print_all = 1;

        if (dprintf_string != NULL)
                zfs_flags |= ZFS_DEBUG_DPRINTF;
}

/*
 * =========================================================================
 * debug printfs
 * =========================================================================
 */
void
__dprintf(const char *file, const char *func, int line, const char *fmt, ...)
{
        const char *newfile;
        va_list adx;

        /*
         * Get rid of annoying "../common/" prefix to filename.
         */
        newfile = strrchr(file, '/');
        if (newfile != NULL) {
                newfile = newfile + 1; /* Get rid of leading / */
        } else {
                newfile = file;
        }

        if (dprintf_print_all ||
            dprintf_find_string(newfile) ||
            dprintf_find_string(func)) {
                /* Print out just the function name if requested */
                flockfile(stdout);
                if (dprintf_find_string("pid"))
                        (void) printf("%d ", getpid());
                if (dprintf_find_string("tid"))
                        (void) printf("%u ", thr_self());
                if (dprintf_find_string("cpu"))
                        (void) printf("%u ", getcpuid());
                if (dprintf_find_string("time"))
                        (void) printf("%llu ", gethrtime());
                if (dprintf_find_string("long"))
                        (void) printf("%s, line %d: ", newfile, line);
                (void) printf("%s: ", func);
                va_start(adx, fmt);
                (void) vprintf(fmt, adx);
                va_end(adx);
                funlockfile(stdout);
        }
}

#endif /* ZFS_DEBUG */

/*
 * =========================================================================
 * kobj interfaces
 * =========================================================================
 */
struct _buf *
kobj_open_file(char *name)
{
        struct _buf *file;
        vnode_t *vp;

        /* set vp as the _fd field of the file */
        if (vn_openat(name, UIO_SYSSPACE, FREAD, 0, &vp, 0, 0, rootdir,
            -1) != 0)
                return ((void *)-1UL);

        file = umem_zalloc(sizeof (struct _buf), UMEM_NOFAIL);
        file->_fd = (intptr_t)vp;
        return (file);
}

int
kobj_read_file(struct _buf *file, char *buf, unsigned size, unsigned off)
{
        ssize_t resid;

        vn_rdwr(UIO_READ, (vnode_t *)file->_fd, buf, size, (offset_t)off,
            UIO_SYSSPACE, 0, 0, 0, &resid);

        return (size - resid);
}

void
kobj_close_file(struct _buf *file)
{
        vn_close((vnode_t *)file->_fd);
        umem_free(file, sizeof (struct _buf));
}

int
kobj_get_filesize(struct _buf *file, uint64_t *size)
{
        struct stat64 st;
        vnode_t *vp = (vnode_t *)file->_fd;

        if (fstat64(vp->v_fd, &st) == -1) {
                vn_close(vp);
                return (errno);
        }
        *size = st.st_size;
        return (0);
}

/*
 * =========================================================================
 * misc routines
 * =========================================================================
 */

/*
 * Find lowest one bit set.
 * Returns bit number + 1 of lowest bit that is set, otherwise returns 0.
 * This is basically a reimplementation of ffsll(), which is GNU specific.
 */
int
lowbit64(uint64_t i)
{
        register int h = 64;
        if (i == 0)
                return (0);

        if (i & 0x00000000ffffffffULL)
                h -= 32;
        else
                i >>= 32;

        if (i & 0x0000ffff)
                h -= 16;
        else
                i >>= 16;

        if (i & 0x00ff)
                h -= 8;
        else
                i >>= 8;

        if (i & 0x0f)
                h -= 4;
        else
                i >>= 4;

        if (i & 0x3)
                h -= 2;
        else
                i >>= 2;

        if (i & 0x1)
                h -= 1;

        return (h);
}

int
highbit64(uint64_t i)
{
        int h = 1;

        if (i == 0)
                return (0);
        if (i & 0xffffffff00000000ULL) {
                h += 32; i >>= 32;
        }
        if (i & 0xffff0000) {
                h += 16; i >>= 16;
        }
        if (i & 0xff00) {
                h += 8; i >>= 8;
        }
        if (i & 0xf0) {
                h += 4; i >>= 4;
        }
        if (i & 0xc) {
                h += 2; i >>= 2;
        }
        if (i & 0x2) {
                h += 1;
        }
        return (h);
}

/*
 * =========================================================================
 * kernel emulation setup & teardown
 * =========================================================================
 */
static int
umem_out_of_memory(void)
{
        char errmsg[] = "out of memory -- generating core dump\n";

        write(fileno(stderr), errmsg, sizeof (errmsg));
        abort();
        return (0);
}

void
kernel_init(int mode)
{
        extern uint_t rrw_tsd_key;

        umem_nofail_callback(umem_out_of_memory);

        physmem = sysconf(_SC_PHYS_PAGES);

        dprintf_zfs("physmem = %llu pages (%.2f GB)\n", physmem,
            (double)physmem * sysconf(_SC_PAGE_SIZE) / (1ULL << 30));

        (void) snprintf(hw_serial, sizeof (hw_serial), "%ld",
            (mode & FWRITE) ? get_system_hostid() : 0);

        system_taskq_init();

        mutex_init(&cpu_lock, NULL, MUTEX_DEFAULT, NULL);

        spa_init(mode);

        fletcher_4_init();

        tsd_create(&rrw_tsd_key, rrw_tsd_destroy);
}

void
kernel_fini(void)
{
        fletcher_4_fini();

        spa_fini();

        system_taskq_fini();
}

/* ARGSUSED */
uint32_t
zone_get_hostid(void *zonep)
{
        /*
         * We're emulating the system's hostid in userland.
         */
        return (strtoul(hw_serial, NULL, 10));
}

int
z_uncompress(void *dst, size_t *dstlen, const void *src, size_t srclen)
{
        int ret;
        uLongf len = *dstlen;

        if ((ret = uncompress(dst, &len, src, srclen)) == Z_OK)
                *dstlen = (size_t)len;

        return (ret);
}

int
z_compress_level(void *dst, size_t *dstlen, const void *src, size_t srclen,
    int level)
{
        int ret;
        uLongf len = *dstlen;

        if ((ret = compress2(dst, &len, src, srclen, level)) == Z_OK)
                *dstlen = (size_t)len;

        return (ret);
}

int
zfs_secpolicy_snapshot_perms(const char *name, cred_t *cr)
{
        return (0);
}

int
zfs_secpolicy_rename_perms(const char *from, const char *to, cred_t *cr)
{
        return (0);
}

int
zfs_secpolicy_destroy_perms(const char *name, cred_t *cr)
{
        return (0);
}

/* ARGSUSED */
int
zfs_onexit_fd_hold(int fd, minor_t *minorp)
{
        *minorp = 0;
        return (0);
}

/* ARGSUSED */
void
zfs_onexit_fd_rele(int fd)
{
}

/* ARGSUSED */
int
zfs_onexit_add_cb(minor_t minor, void (*func)(void *), void *data,
    uint64_t *action_handle)
{
        return (0);
}

/* ARGSUSED */
int
zfs_onexit_del_cb(minor_t minor, uint64_t action_handle, boolean_t fire)
{
        return (0);
}

/* ARGSUSED */
int
zfs_onexit_cb_data(minor_t minor, uint64_t action_handle, void **data)
{
        return (0);
}

void
bioinit(buf_t *bp)
{
        bzero(bp, sizeof (buf_t));
}

void
biodone(buf_t *bp)
{
        if (bp->b_iodone != NULL) {
                (*(bp->b_iodone))(bp);
                return;
        }
        ASSERT((bp->b_flags & B_DONE) == 0);
        bp->b_flags |= B_DONE;
}

void
bioerror(buf_t *bp, int error)
{
        ASSERT(bp != NULL);
        ASSERT(error >= 0);

        if (error != 0) {
                bp->b_flags |= B_ERROR;
        } else {
                bp->b_flags &= ~B_ERROR;
        }
        bp->b_error = error;
}


int
geterror(struct buf *bp)
{
        int error = 0;

        if (bp->b_flags & B_ERROR) {
                error = bp->b_error;
                if (!error)
                        error = EIO;
        }
        return (error);
}

int
crypto_create_ctx_template(crypto_mechanism_t *mech,
    crypto_key_t *key, crypto_ctx_template_t *tmpl, int kmflag)
{
        return (0);
}

crypto_mech_type_t
crypto_mech2id(const char *name)
{
        return (CRYPTO_MECH_INVALID);
}

int
crypto_mac(crypto_mechanism_t *mech, crypto_data_t *data,
    crypto_key_t *key, crypto_ctx_template_t impl,
    crypto_data_t *mac, crypto_call_req_t *cr)
{
        return (0);
}

int
crypto_encrypt(crypto_mechanism_t *mech, crypto_data_t *plaintext,
    crypto_key_t *key, crypto_ctx_template_t tmpl,
    crypto_data_t *ciphertext, crypto_call_req_t *cr)
{
        return (0);
}

/* This could probably be a weak reference */
int
crypto_decrypt(crypto_mechanism_t *mech, crypto_data_t *plaintext,
    crypto_key_t *key, crypto_ctx_template_t tmpl,
    crypto_data_t *ciphertext, crypto_call_req_t *cr)
{
        return (0);
}


int
crypto_digest_final(crypto_context_t context, crypto_data_t *digest,
    crypto_call_req_t *cr)
{
        return (0);
}

int
crypto_digest_update(crypto_context_t context, crypto_data_t *data,
    crypto_call_req_t *cr)
{
        return (0);
}

int
crypto_digest_init(crypto_mechanism_t *mech, crypto_context_t *ctxp,
    crypto_call_req_t  *crq)
{
        return (0);
}

void
crypto_destroy_ctx_template(crypto_ctx_template_t tmpl)
{
}

extern int crypto_mac_init(crypto_mechanism_t *mech, crypto_key_t *key,
        crypto_ctx_template_t tmpl, crypto_context_t *ctxp,
    crypto_call_req_t *cr)
{
        return (0);
}

extern int crypto_mac_update(crypto_context_t ctx, crypto_data_t *data,
        crypto_call_req_t *cr)
{
        return (0);
}

extern int crypto_mac_final(crypto_context_t ctx, crypto_data_t *data,
        crypto_call_req_t *cr)
{
        return (0);
}