Home | History | Annotate | Line # | Download | only in librumpuser
rumpuser.c revision 1.49
      1 /*	$NetBSD: rumpuser.c,v 1.49 2013/05/01 17:17:54 pooka Exp $	*/
      2 
      3 /*
      4  * Copyright (c) 2007-2010 Antti Kantee.  All Rights Reserved.
      5  *
      6  * Redistribution and use in source and binary forms, with or without
      7  * modification, are permitted provided that the following conditions
      8  * are met:
      9  * 1. Redistributions of source code must retain the above copyright
     10  *    notice, this list of conditions and the following disclaimer.
     11  * 2. Redistributions in binary form must reproduce the above copyright
     12  *    notice, this list of conditions and the following disclaimer in the
     13  *    documentation and/or other materials provided with the distribution.
     14  *
     15  * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS
     16  * OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
     17  * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
     18  * DISCLAIMED. IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE
     19  * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
     20  * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
     21  * SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
     22  * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
     23  * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
     24  * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
     25  * SUCH DAMAGE.
     26  */
     27 
     28 #include "rumpuser_port.h"
     29 
     30 #if !defined(lint)
     31 __RCSID("$NetBSD: rumpuser.c,v 1.49 2013/05/01 17:17:54 pooka Exp $");
     32 #endif /* !lint */
     33 
     34 #include <sys/ioctl.h>
     35 #include <sys/mman.h>
     36 #include <sys/uio.h>
     37 #include <sys/stat.h>
     38 #include <sys/time.h>
     39 
     40 #ifdef __NetBSD__
     41 #include <sys/disk.h>
     42 #include <sys/disklabel.h>
     43 #include <sys/dkio.h>
     44 #endif
     45 
     46 #if defined(__NetBSD__) || defined(__FreeBSD__) || defined(__DragonFly__)
     47 #include <sys/sysctl.h>
     48 #endif
     49 
     50 #include <assert.h>
     51 #include <errno.h>
     52 #include <fcntl.h>
     53 #include <netdb.h>
     54 #include <signal.h>
     55 #include <stdarg.h>
     56 #include <stdint.h>
     57 #include <stdio.h>
     58 #include <stdlib.h>
     59 #include <string.h>
     60 #include <time.h>
     61 #include <unistd.h>
     62 
     63 #include <rump/rumpuser.h>
     64 
     65 #include "rumpuser_int.h"
     66 
     67 struct rumpuser_hyperup rumpuser__hyp;
     68 
     69 int
     70 rumpuser_init(int version, const struct rumpuser_hyperup *hyp)
     71 {
     72 
     73 	if (version != RUMPUSER_VERSION) {
     74 		fprintf(stderr, "rumpuser mismatch, kern: %d, hypervisor %d\n",
     75 		    version, RUMPUSER_VERSION);
     76 		return 1;
     77 	}
     78 
     79 #ifdef RUMPUSER_USE_DEVRANDOM
     80 	uint32_t rv;
     81 	int fd;
     82 
     83 	if ((fd = open("/dev/urandom", O_RDONLY)) == -1) {
     84 		srandom(time(NULL));
     85 	} else {
     86 		if (read(fd, &rv, sizeof(rv)) != sizeof(rv))
     87 			srandom(time(NULL));
     88 		else
     89 			srandom(rv);
     90 		close(fd);
     91 	}
     92 #endif
     93 
     94 	rumpuser__thrinit();
     95 	rumpuser__hyp = *hyp;
     96 
     97 	return 0;
     98 }
     99 
    100 int
    101 rumpuser_getfileinfo(const char *path, uint64_t *sizep, int *ftp)
    102 {
    103 	struct stat sb;
    104 	uint64_t size = 0;
    105 	int needsdev = 0, rv = 0, ft = 0;
    106 	int fd = -1;
    107 
    108 	if (stat(path, &sb) == -1) {
    109 		rv = errno;
    110 		goto out;
    111 	}
    112 
    113 	switch (sb.st_mode & S_IFMT) {
    114 	case S_IFDIR:
    115 		ft = RUMPUSER_FT_DIR;
    116 		break;
    117 	case S_IFREG:
    118 		ft = RUMPUSER_FT_REG;
    119 		break;
    120 	case S_IFBLK:
    121 		ft = RUMPUSER_FT_BLK;
    122 		needsdev = 1;
    123 		break;
    124 	case S_IFCHR:
    125 		ft = RUMPUSER_FT_CHR;
    126 		needsdev = 1;
    127 		break;
    128 	default:
    129 		ft = RUMPUSER_FT_OTHER;
    130 		break;
    131 	}
    132 
    133 	if (!needsdev) {
    134 		size = sb.st_size;
    135 	} else if (sizep) {
    136 		/*
    137 		 * Welcome to the jungle.  Of course querying the kernel
    138 		 * for a device partition size is supposed to be far from
    139 		 * trivial.  On NetBSD we use ioctl.  On $other platform
    140 		 * we have a problem.  We try "the lseek trick" and just
    141 		 * fail if that fails.  Platform specific code can later
    142 		 * be written here if appropriate.
    143 		 *
    144 		 * On NetBSD we hope and pray that for block devices nobody
    145 		 * else is holding them open, because otherwise the kernel
    146 		 * will not permit us to open it.  Thankfully, this is
    147 		 * usually called only in bootstrap and then we can
    148 		 * forget about it.
    149 		 */
    150 #ifndef __NetBSD__
    151 		off_t off;
    152 
    153 		fd = open(path, O_RDONLY);
    154 		if (fd == -1) {
    155 			rv = errno;
    156 			goto out;
    157 		}
    158 
    159 		off = lseek(fd, 0, SEEK_END);
    160 		if (off != 0) {
    161 			size = off;
    162 			goto out;
    163 		}
    164 		fprintf(stderr, "error: device size query not implemented on "
    165 		    "this platform\n");
    166 		rv = EOPNOTSUPP;
    167 		goto out;
    168 #else
    169 		struct disklabel lab;
    170 		struct partition *parta;
    171 		struct dkwedge_info dkw;
    172 
    173 		fd = open(path, O_RDONLY);
    174 		if (fd == -1) {
    175 			rv = errno;
    176 			goto out;
    177 		}
    178 
    179 		if (ioctl(fd, DIOCGDINFO, &lab) == 0) {
    180 			parta = &lab.d_partitions[DISKPART(sb.st_rdev)];
    181 			size = (uint64_t)lab.d_secsize * parta->p_size;
    182 			goto out;
    183 		}
    184 
    185 		if (ioctl(fd, DIOCGWEDGEINFO, &dkw) == 0) {
    186 			/*
    187 			 * XXX: should use DIOCGDISKINFO to query
    188 			 * sector size, but that requires proplib,
    189 			 * so just don't bother for now.  it's nice
    190 			 * that something as difficult as figuring out
    191 			 * a partition's size has been made so easy.
    192 			 */
    193 			size = dkw.dkw_size << DEV_BSHIFT;
    194 			goto out;
    195 		}
    196 
    197 		rv = errno;
    198 #endif /* __NetBSD__ */
    199 	}
    200 
    201  out:
    202 	if (rv == 0 && sizep)
    203 		*sizep = size;
    204 	if (rv == 0 && ftp)
    205 		*ftp = ft;
    206 	if (fd != -1)
    207 		close(fd);
    208 
    209 	ET(rv);
    210 }
    211 
    212 int
    213 rumpuser_malloc(size_t howmuch, int alignment, void **memp)
    214 {
    215 	void *mem;
    216 	int rv;
    217 
    218 	if (alignment == 0)
    219 		alignment = sizeof(void *);
    220 
    221 	rv = posix_memalign(&mem, (size_t)alignment, howmuch);
    222 	if (__predict_false(rv != 0)) {
    223 		if (rv == EINVAL) {
    224 			printf("rumpuser_malloc: invalid alignment %d\n",
    225 			    alignment);
    226 			abort();
    227 		}
    228 	}
    229 
    230 	*memp = mem;
    231 	ET(rv);
    232 }
    233 
    234 /*ARGSUSED1*/
    235 void
    236 rumpuser_free(void *ptr, size_t size)
    237 {
    238 
    239 	free(ptr);
    240 }
    241 
    242 int
    243 rumpuser_anonmmap(void *prefaddr, size_t size, int alignbit,
    244 	int exec, void **memp)
    245 {
    246 	void *mem;
    247 	int prot, rv;
    248 
    249 #ifndef MAP_ALIGNED
    250 #define MAP_ALIGNED(a) 0
    251 	if (alignbit)
    252 		fprintf(stderr, "rumpuser_anonmmap: warning, requested "
    253 		    "alignment not supported by hypervisor\n");
    254 #endif
    255 
    256 	prot = PROT_READ|PROT_WRITE;
    257 	if (exec)
    258 		prot |= PROT_EXEC;
    259 	mem = mmap(prefaddr, size, prot,
    260 	    MAP_PRIVATE | MAP_ANON | MAP_ALIGNED(alignbit), -1, 0);
    261 	if (mem == MAP_FAILED) {
    262 		rv = errno;
    263 	} else {
    264 		*memp = mem;
    265 		rv = 0;
    266 	}
    267 
    268 	ET(rv);
    269 }
    270 
    271 void
    272 rumpuser_unmap(void *addr, size_t len)
    273 {
    274 
    275 	munmap(addr, len);
    276 }
    277 
    278 int
    279 rumpuser_open(const char *path, int ruflags, int *fdp)
    280 {
    281 	int fd, flags, rv;
    282 
    283 	switch (ruflags & RUMPUSER_OPEN_ACCMODE) {
    284 	case RUMPUSER_OPEN_RDONLY:
    285 		flags = O_RDONLY;
    286 		break;
    287 	case RUMPUSER_OPEN_WRONLY:
    288 		flags = O_WRONLY;
    289 		break;
    290 	case RUMPUSER_OPEN_RDWR:
    291 		flags = O_RDWR;
    292 		break;
    293 	default:
    294 		rv = EINVAL;
    295 		goto out;
    296 	}
    297 
    298 #define TESTSET(_ru_, _h_) if (ruflags & _ru_) flags |= _h_;
    299 	TESTSET(RUMPUSER_OPEN_CREATE, O_CREAT);
    300 	TESTSET(RUMPUSER_OPEN_EXCL, O_EXCL);
    301 #undef TESTSET
    302 
    303 	KLOCK_WRAP(fd = open(path, flags, 0644));
    304 	if (fd == -1) {
    305 		rv = errno;
    306 	} else {
    307 		*fdp = fd;
    308 		rv = 0;
    309 	}
    310 
    311  out:
    312 	ET(rv);
    313 }
    314 
    315 int
    316 rumpuser_close(int fd)
    317 {
    318 	int nlocks;
    319 
    320 	rumpkern_unsched(&nlocks, NULL);
    321 	fsync(fd);
    322 	close(fd);
    323 	rumpkern_sched(nlocks, NULL);
    324 
    325 	ET(0);
    326 }
    327 
    328 /*
    329  * Assume "struct rumpuser_iovec" and "struct iovec" are the same.
    330  * If you encounter POSIX platforms where they aren't, add some
    331  * translation for iovlen > 1.
    332  */
    333 int
    334 rumpuser_iovread(int fd, struct rumpuser_iovec *ruiov, size_t iovlen,
    335 	off_t off, size_t *retp)
    336 {
    337 	struct iovec *iov = (struct iovec *)ruiov;
    338 	ssize_t nn;
    339 	int rv;
    340 
    341 	if (off == RUMPUSER_IOV_NOSEEK) {
    342 		KLOCK_WRAP(nn = readv(fd, iov, iovlen));
    343 	} else {
    344 		int nlocks;
    345 
    346 		rumpkern_unsched(&nlocks, NULL);
    347 		if (lseek(fd, off, SEEK_SET) == off) {
    348 			nn = readv(fd, iov, iovlen);
    349 		} else {
    350 			nn = -1;
    351 		}
    352 		rumpkern_sched(nlocks, NULL);
    353 	}
    354 
    355 	if (nn == -1) {
    356 		rv = errno;
    357 	} else {
    358 		*retp = (size_t)nn;
    359 		rv = 0;
    360 	}
    361 
    362 	ET(rv);
    363 }
    364 
    365 int
    366 rumpuser_iovwrite(int fd, const struct rumpuser_iovec *ruiov, size_t iovlen,
    367 	off_t off, size_t *retp)
    368 {
    369 	const struct iovec *iov = (const struct iovec *)ruiov;
    370 	ssize_t nn;
    371 	int rv;
    372 
    373 	if (off == RUMPUSER_IOV_NOSEEK) {
    374 		KLOCK_WRAP(nn = writev(fd, iov, iovlen));
    375 	} else {
    376 		int nlocks;
    377 
    378 		rumpkern_unsched(&nlocks, NULL);
    379 		if (lseek(fd, off, SEEK_SET) == off) {
    380 			nn = writev(fd, iov, iovlen);
    381 		} else {
    382 			nn = -1;
    383 		}
    384 		rumpkern_sched(nlocks, NULL);
    385 	}
    386 
    387 	if (nn == -1) {
    388 		rv = errno;
    389 	} else {
    390 		*retp = (size_t)nn;
    391 		rv = 0;
    392 	}
    393 
    394 	ET(rv);
    395 }
    396 
    397 int
    398 rumpuser_clock_gettime(enum rumpclock rclk, uint64_t *sec, uint64_t *nsec)
    399 {
    400 	struct timespec ts;
    401 	clockid_t clk;
    402 	int rv;
    403 
    404 	switch (rclk) {
    405 	case RUMPUSER_CLOCK_RELWALL:
    406 		clk = CLOCK_REALTIME;
    407 		break;
    408 	case RUMPUSER_CLOCK_ABSMONO:
    409 #ifdef HAVE_CLOCK_NANOSLEEP
    410 		clk = CLOCK_MONOTONIC;
    411 #else
    412 		clk = CLOCK_REALTIME;
    413 #endif
    414 		break;
    415 	default:
    416 		abort();
    417 	}
    418 
    419 	if (clock_gettime(clk, &ts) == -1) {
    420 		rv = errno;
    421 	} else {
    422 		*sec = ts.tv_sec;
    423 		*nsec = ts.tv_nsec;
    424 		rv = 0;
    425 	}
    426 
    427 	ET(rv);
    428 }
    429 
    430 int
    431 rumpuser_clock_sleep(enum rumpclock clk, uint64_t sec, uint64_t nsec)
    432 {
    433 	struct timespec rqt, rmt;
    434 	int nlocks;
    435 	int rv;
    436 
    437 	rumpkern_unsched(&nlocks, NULL);
    438 
    439 	/*LINTED*/
    440 	rqt.tv_sec = sec;
    441 	/*LINTED*/
    442 	rqt.tv_nsec = nsec;
    443 
    444 	switch (clk) {
    445 	case RUMPUSER_CLOCK_RELWALL:
    446 		do {
    447 			rv = nanosleep(&rqt, &rmt);
    448 			rqt = rmt;
    449 		} while (rv == -1 && errno == EINTR);
    450 		if (rv == -1) {
    451 			rv = errno;
    452 		}
    453 		break;
    454 	case RUMPUSER_CLOCK_ABSMONO:
    455 		do {
    456 #ifdef HAVE_CLOCK_NANOSLEEP
    457 			rv = clock_nanosleep(CLOCK_MONOTONIC, TIMER_ABSTIME,
    458 			    &rqt, NULL);
    459 #else
    460 			/* le/la/der/die/das sigh. timevalspec tailspin */
    461 			struct timespec ts, tsr;
    462 			clock_gettime(CLOCK_REALTIME, &ts);
    463 			if (ts.tv_sec == rqt.tv_sec ?
    464 			    ts.tv_nsec > rqt.tv_nsec : ts.tv_sec > rqt.tv_sec) {
    465 				rv = 0;
    466 			} else {
    467 				tsr.tv_sec = rqt.tv_sec - ts.tv_sec;
    468 				tsr.tv_nsec = rqt.tv_nsec - ts.tv_nsec;
    469 				if (tsr.tv_nsec < 0) {
    470 					tsr.tv_sec--;
    471 					tsr.tv_nsec += 1000*1000*1000;
    472 				}
    473 				rv = nanosleep(&tsr, NULL);
    474 			}
    475 #endif
    476 		} while (rv == -1 && errno == EINTR);
    477 		if (rv == -1) {
    478 			rv = errno;
    479 		}
    480 		break;
    481 	default:
    482 		abort();
    483 	}
    484 
    485 	rumpkern_sched(nlocks, NULL);
    486 
    487 	ET(rv);
    488 }
    489 
    490 static int
    491 gethostncpu(void)
    492 {
    493 	int ncpu = 1;
    494 
    495 #if defined(__NetBSD__) || defined(__FreeBSD__) || defined(__DragonFly__)
    496 	size_t sz = sizeof(ncpu);
    497 
    498 	sysctlbyname("hw.ncpu", &ncpu, &sz, NULL, 0);
    499 #elif defined(__linux__) || defined(__CYGWIN__)
    500 	FILE *fp;
    501 	char *line = NULL;
    502 	size_t n = 0;
    503 
    504 	/* If anyone knows a better way, I'm all ears */
    505 	if ((fp = fopen("/proc/cpuinfo", "r")) != NULL) {
    506 		ncpu = 0;
    507 		while (getline(&line, &n, fp) != -1) {
    508 			if (strncmp(line,
    509 			    "processor", sizeof("processor")-1) == 0)
    510 			    	ncpu++;
    511 		}
    512 		if (ncpu == 0)
    513 			ncpu = 1;
    514 		free(line);
    515 		fclose(fp);
    516 	}
    517 #elif __sun__
    518 	/* XXX: this is just a rough estimate ... */
    519 	ncpu = sysconf(_SC_NPROCESSORS_ONLN);
    520 #endif
    521 
    522 	return ncpu;
    523 }
    524 
    525 int
    526 rumpuser_getparam(const char *name, void *buf, size_t blen)
    527 {
    528 	int rv;
    529 
    530 	if (strcmp(name, RUMPUSER_PARAM_NCPU) == 0) {
    531 		int ncpu;
    532 
    533 		if (getenv_r("RUMP_NCPU", buf, blen) == -1) {
    534 			ncpu = gethostncpu();
    535 			snprintf(buf, blen, "%d", ncpu);
    536 		}
    537 		rv = 0;
    538 	} else if (strcmp(name, RUMPUSER_PARAM_HOSTNAME) == 0) {
    539 		char tmp[MAXHOSTNAMELEN];
    540 
    541 		if (gethostname(tmp, sizeof(tmp)) == -1) {
    542 			snprintf(buf, blen, "rump-%05d", (int)getpid());
    543 		} else {
    544 			snprintf(buf, blen, "rump-%05d.%s",
    545 			    (int)getpid(), tmp);
    546 		}
    547 		rv = 0;
    548 	} else if (*name == '_') {
    549 		rv = EINVAL;
    550 	} else {
    551 		if (getenv_r(name, buf, blen) == -1)
    552 			rv = errno;
    553 		else
    554 			rv = 0;
    555 	}
    556 
    557 	ET(rv);
    558 }
    559 
    560 void
    561 rumpuser_putchar(int c)
    562 {
    563 
    564 	putchar(c);
    565 }
    566 
    567 void
    568 rumpuser_exit(int rv)
    569 {
    570 
    571 	if (rv == RUMPUSER_PANIC)
    572 		abort();
    573 	else
    574 		exit(rv);
    575 }
    576 
    577 void
    578 rumpuser_seterrno(int error)
    579 {
    580 
    581 	errno = error;
    582 }
    583 
    584 /*
    585  * This is meant for safe debugging prints from the kernel.
    586  */
    587 void
    588 rumpuser_dprintf(const char *format, ...)
    589 {
    590 	va_list ap;
    591 
    592 	va_start(ap, format);
    593 	vfprintf(stderr, format, ap);
    594 	va_end(ap);
    595 }
    596 
    597 int
    598 rumpuser_kill(int64_t pid, int sig)
    599 {
    600 	int rv;
    601 
    602 #ifdef __NetBSD__
    603 	int error;
    604 
    605 	if (pid == RUMPUSER_PID_SELF) {
    606 		error = raise(sig);
    607 	} else {
    608 		error = kill((pid_t)pid, sig);
    609 	}
    610 	if (error == -1)
    611 		rv = errno;
    612 	else
    613 		rv = 0;
    614 #else
    615 	/* XXXfixme: signal numbers may not match on non-NetBSD */
    616 	rv = EOPNOTSUPP;
    617 #endif
    618 
    619 	ET(rv);
    620 }
    621 
    622 int
    623 rumpuser_getrandom(void *buf, size_t buflen, int flags, size_t *retp)
    624 {
    625 	size_t origlen = buflen;
    626 	uint32_t *p = buf;
    627 	uint32_t tmp;
    628 	int chunk;
    629 
    630 	do {
    631 		chunk = buflen < 4 ? buflen : 4; /* portable MIN ... */
    632 		tmp = RUMPUSER_RANDOM();
    633 		memcpy(p, &tmp, chunk);
    634 		p++;
    635 		buflen -= chunk;
    636 	} while (chunk);
    637 
    638 	*retp = origlen;
    639 	ET(0);
    640 }
    641