Home | History | Annotate | Line # | Download | only in librumpuser
rumpuser.c revision 1.44
      1 /*	$NetBSD: rumpuser.c,v 1.44 2013/04/29 20:08:48 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.44 2013/04/29 20:08:48 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, int *error)
    102 {
    103 	struct stat sb;
    104 	uint64_t size;
    105 	int needsdev = 0, rv = 0, ft;
    106 	int fd = -1;
    107 
    108 	if (stat(path, &sb) == -1) {
    109 		seterror(errno);
    110 		return -1;
    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 			seterror(errno);
    156 			rv = -1;
    157 			goto out;
    158 		}
    159 
    160 		off = lseek(fd, 0, SEEK_END);
    161 		if (off != 0) {
    162 			size = off;
    163 			goto out;
    164 		}
    165 		fprintf(stderr, "error: device size query not implemented on "
    166 		    "this platform\n");
    167 		seterror(EOPNOTSUPP);
    168 		rv = -1;
    169 		goto out;
    170 #else
    171 		struct disklabel lab;
    172 		struct partition *parta;
    173 		struct dkwedge_info dkw;
    174 
    175 		fd = open(path, O_RDONLY);
    176 		if (fd == -1) {
    177 			seterror(errno);
    178 			rv = -1;
    179 			goto out;
    180 		}
    181 
    182 		if (ioctl(fd, DIOCGDINFO, &lab) == 0) {
    183 			parta = &lab.d_partitions[DISKPART(sb.st_rdev)];
    184 			size = (uint64_t)lab.d_secsize * parta->p_size;
    185 			goto out;
    186 		}
    187 
    188 		if (ioctl(fd, DIOCGWEDGEINFO, &dkw) == 0) {
    189 			/*
    190 			 * XXX: should use DIOCGDISKINFO to query
    191 			 * sector size, but that requires proplib,
    192 			 * so just don't bother for now.  it's nice
    193 			 * that something as difficult as figuring out
    194 			 * a partition's size has been made so easy.
    195 			 */
    196 			size = dkw.dkw_size << DEV_BSHIFT;
    197 			goto out;
    198 		}
    199 
    200 		seterror(errno);
    201 		rv = -1;
    202 #endif /* __NetBSD__ */
    203 	}
    204 
    205  out:
    206 	if (rv == 0 && sizep)
    207 		*sizep = size;
    208 	if (rv == 0 && ftp)
    209 		*ftp = ft;
    210 	if (fd != -1)
    211 		close(fd);
    212 
    213 	return rv;
    214 }
    215 
    216 void *
    217 rumpuser_malloc(size_t howmuch, int alignment)
    218 {
    219 	void *mem;
    220 	int rv;
    221 
    222 	if (alignment == 0)
    223 		alignment = sizeof(void *);
    224 
    225 	rv = posix_memalign(&mem, (size_t)alignment, howmuch);
    226 	if (__predict_false(rv != 0)) {
    227 		if (rv == EINVAL) {
    228 			printf("rumpuser_malloc: invalid alignment %d\n",
    229 			    alignment);
    230 			abort();
    231 		}
    232 		mem = NULL;
    233 	}
    234 
    235 	return mem;
    236 }
    237 
    238 /*ARGSUSED1*/
    239 void
    240 rumpuser_free(void *ptr, size_t size)
    241 {
    242 
    243 	free(ptr);
    244 }
    245 
    246 void *
    247 rumpuser_anonmmap(void *prefaddr, size_t size, int alignbit,
    248 	int exec, int *error)
    249 {
    250 	void *rv;
    251 	int prot;
    252 
    253 #ifndef MAP_ALIGNED
    254 #define MAP_ALIGNED(a) 0
    255 	if (alignbit)
    256 		fprintf(stderr, "rumpuser_anonmmap: warning, requested "
    257 		    "alignment not supported by hypervisor\n");
    258 #endif
    259 
    260 	prot = PROT_READ|PROT_WRITE;
    261 	if (exec)
    262 		prot |= PROT_EXEC;
    263 	rv = mmap(prefaddr, size, prot,
    264 	    MAP_PRIVATE | MAP_ANON | MAP_ALIGNED(alignbit), -1, 0);
    265 	if (rv == MAP_FAILED) {
    266 		seterror(errno);
    267 		return NULL;
    268 	}
    269 	return rv;
    270 }
    271 
    272 void
    273 rumpuser_unmap(void *addr, size_t len)
    274 {
    275 	int rv;
    276 
    277 	rv = munmap(addr, len);
    278 	assert(rv == 0);
    279 }
    280 
    281 int
    282 rumpuser_open(const char *path, int ruflags, int *error)
    283 {
    284 	int flags;
    285 
    286 	switch (ruflags & RUMPUSER_OPEN_ACCMODE) {
    287 	case RUMPUSER_OPEN_RDONLY:
    288 		flags = O_RDONLY;
    289 		break;
    290 	case RUMPUSER_OPEN_WRONLY:
    291 		flags = O_WRONLY;
    292 		break;
    293 	case RUMPUSER_OPEN_RDWR:
    294 		flags = O_RDWR;
    295 		break;
    296 	default:
    297 		*error = EINVAL;
    298 		return -1;
    299 	}
    300 
    301 #define TESTSET(_ru_, _h_) if (ruflags & _ru_) flags |= _h_;
    302 	TESTSET(RUMPUSER_OPEN_CREATE, O_CREAT);
    303 	TESTSET(RUMPUSER_OPEN_EXCL, O_EXCL);
    304 #undef TESTSET
    305 
    306 	DOCALL_KLOCK(int, (open(path, flags, 0644)));
    307 }
    308 
    309 int
    310 rumpuser_close(int fd, int *error)
    311 {
    312 	int nlocks;
    313 
    314 	rumpkern_unsched(&nlocks, NULL);
    315 	fsync(fd);
    316 	close(fd);
    317 	rumpkern_sched(nlocks, NULL);
    318 
    319 	return 0;
    320 }
    321 
    322 /*
    323  * Assume "struct rumpuser_iovec" and "struct iovec" are the same.
    324  * If you encounter POSIX platforms where they aren't, add some
    325  * translation for iovlen > 1.
    326  */
    327 ssize_t
    328 rumpuser_iovread(int fd, struct rumpuser_iovec *ruiov, size_t iovlen,
    329 	off_t off, int *error)
    330 {
    331 	struct iovec *iov = (struct iovec *)ruiov;
    332 	ssize_t rv;
    333 
    334 	if (off == RUMPUSER_IOV_NOSEEK)
    335 		KLOCK_WRAP(rv = readv(fd, iov, iovlen));
    336 	else
    337 		KLOCK_WRAP(rv = preadv(fd, iov, iovlen, off));
    338 
    339 	if (rv == -1)
    340 		seterror(errno);
    341 
    342 	return rv;
    343 }
    344 
    345 ssize_t
    346 rumpuser_iovwrite(int fd, const struct rumpuser_iovec *ruiov, size_t iovlen,
    347 	off_t off, int *error)
    348 {
    349 	const struct iovec *iov = (const struct iovec *)ruiov;
    350 	ssize_t rv;
    351 
    352 	if (off == RUMPUSER_IOV_NOSEEK)
    353 		KLOCK_WRAP(rv = writev(fd, iov, iovlen));
    354 	else
    355 		KLOCK_WRAP(rv = pwritev(fd, iov, iovlen, off));
    356 
    357 	if (rv == -1)
    358 		seterror(errno);
    359 
    360 	return rv;
    361 }
    362 
    363 int
    364 rumpuser_clock_gettime(uint64_t *sec, uint64_t *nsec, enum rumpclock rclk)
    365 {
    366 	struct timespec ts;
    367 	clockid_t clk;
    368 	int rv;
    369 
    370 	switch (rclk) {
    371 	case RUMPUSER_CLOCK_RELWALL:
    372 		clk = CLOCK_REALTIME;
    373 		break;
    374 	case RUMPUSER_CLOCK_ABSMONO:
    375 #ifdef HAVE_CLOCK_NANOSLEEP
    376 		clk = CLOCK_MONOTONIC;
    377 #else
    378 		clk = CLOCK_REALTIME;
    379 #endif
    380 		break;
    381 	default:
    382 		abort();
    383 	}
    384 
    385 	rv = clock_gettime(clk, &ts);
    386 	if (rv == -1) {
    387 		return errno;
    388 	}
    389 	*sec = ts.tv_sec;
    390 	*nsec = ts.tv_nsec;
    391 
    392 	return 0;
    393 }
    394 
    395 int
    396 rumpuser_clock_sleep(uint64_t sec, uint64_t nsec, enum rumpclock clk)
    397 {
    398 	struct timespec rqt, rmt;
    399 	int nlocks;
    400 	int rv;
    401 
    402 	rumpkern_unsched(&nlocks, NULL);
    403 
    404 	/*LINTED*/
    405 	rqt.tv_sec = sec;
    406 	/*LINTED*/
    407 	rqt.tv_nsec = nsec;
    408 
    409 	switch (clk) {
    410 	case RUMPUSER_CLOCK_RELWALL:
    411 		do {
    412 			rv = nanosleep(&rqt, &rmt);
    413 			rqt = rmt;
    414 		} while (rv == -1 && errno == EINTR);
    415 		if (rv == -1) {
    416 			rv = errno;
    417 		}
    418 		break;
    419 	case RUMPUSER_CLOCK_ABSMONO:
    420 		do {
    421 #ifdef HAVE_CLOCK_NANOSLEEP
    422 			rv = clock_nanosleep(CLOCK_MONOTONIC, TIMER_ABSTIME,
    423 			    &rqt, NULL);
    424 #else
    425 			/* le/la/der/die/das sigh. timevalspec tailspin */
    426 			struct timespec ts, tsr;
    427 			clock_gettime(CLOCK_REALTIME, &ts);
    428 			if (ts.tv_sec == rqt.tv_sec ?
    429 			    ts.tv_nsec > rqt.tv_nsec : ts.tv_sec > rqt.tv_sec) {
    430 				rv = 0;
    431 			} else {
    432 				tsr.tv_sec = rqt.tv_sec - ts.tv_sec;
    433 				tsr.tv_nsec = rqt.tv_nsec - ts.tv_nsec;
    434 				if (tsr.tv_nsec < 0) {
    435 					tsr.tv_sec--;
    436 					tsr.tv_nsec += 1000*1000*1000;
    437 				}
    438 				rv = nanosleep(&tsr, NULL);
    439 			}
    440 #endif
    441 		} while (rv == -1 && errno == EINTR);
    442 		if (rv == -1) {
    443 			rv = errno;
    444 		}
    445 		break;
    446 	default:
    447 		abort();
    448 	}
    449 
    450 	rumpkern_sched(nlocks, NULL);
    451 	return rv;
    452 }
    453 
    454 static int
    455 gethostncpu(void)
    456 {
    457 	int ncpu = 1;
    458 
    459 #if defined(__NetBSD__) || defined(__FreeBSD__) || defined(__DragonFly__)
    460 	size_t sz = sizeof(ncpu);
    461 
    462 	sysctlbyname("hw.ncpu", &ncpu, &sz, NULL, 0);
    463 #elif defined(__linux__) || defined(__CYGWIN__)
    464 	FILE *fp;
    465 	char *line = NULL;
    466 	size_t n = 0;
    467 
    468 	/* If anyone knows a better way, I'm all ears */
    469 	if ((fp = fopen("/proc/cpuinfo", "r")) != NULL) {
    470 		ncpu = 0;
    471 		while (getline(&line, &n, fp) != -1) {
    472 			if (strncmp(line,
    473 			    "processor", sizeof("processor")-1) == 0)
    474 			    	ncpu++;
    475 		}
    476 		if (ncpu == 0)
    477 			ncpu = 1;
    478 		free(line);
    479 		fclose(fp);
    480 	}
    481 #elif __sun__
    482 	/* XXX: this is just a rough estimate ... */
    483 	ncpu = sysconf(_SC_NPROCESSORS_ONLN);
    484 #endif
    485 
    486 	return ncpu;
    487 }
    488 
    489 int
    490 rumpuser_getparam(const char *name, void *buf, size_t blen)
    491 {
    492 
    493 	if (strcmp(name, RUMPUSER_PARAM_NCPU) == 0) {
    494 		int ncpu;
    495 
    496 		if (getenv_r("RUMP_NCPU", buf, blen) == -1) {
    497 			ncpu = gethostncpu();
    498 			snprintf(buf, blen, "%d", ncpu);
    499 		}
    500 		return 0;
    501 	} else if (strcmp(name, RUMPUSER_PARAM_HOSTNAME) == 0) {
    502 		char tmp[MAXHOSTNAMELEN];
    503 
    504 		if (gethostname(tmp, sizeof(tmp)) == -1) {
    505 			snprintf(buf, blen, "rump-%05d", (int)getpid());
    506 		} else {
    507 			snprintf(buf, blen, "rump-%05d.%s",
    508 			    (int)getpid(), tmp);
    509 		}
    510 		return 0;
    511 	} else if (*name == '_') {
    512 		return EINVAL;
    513 	} else {
    514 		if (getenv_r(name, buf, blen) == -1)
    515 			return errno;
    516 		else
    517 			return 0;
    518 	}
    519 }
    520 
    521 int
    522 rumpuser_putchar(int c, int *error)
    523 {
    524 
    525 	DOCALL(int, (putchar(c)));
    526 }
    527 
    528 void
    529 rumpuser_exit(int rv)
    530 {
    531 
    532 	if (rv == RUMPUSER_PANIC)
    533 		abort();
    534 	else
    535 		exit(rv);
    536 }
    537 
    538 void
    539 rumpuser_seterrno(int error)
    540 {
    541 
    542 	errno = error;
    543 }
    544 
    545 /*
    546  * This is meant for safe debugging prints from the kernel.
    547  */
    548 int
    549 rumpuser_dprintf(const char *format, ...)
    550 {
    551 	va_list ap;
    552 	int rv;
    553 
    554 	va_start(ap, format);
    555 	rv = vfprintf(stderr, format, ap);
    556 	va_end(ap);
    557 
    558 	return rv;
    559 }
    560 
    561 int
    562 rumpuser_kill(int64_t pid, int sig, int *error)
    563 {
    564 
    565 #ifdef __NetBSD__
    566 	if (pid == RUMPUSER_PID_SELF) {
    567 		DOCALL(int, raise(sig));
    568 	} else {
    569 		DOCALL(int, kill((pid_t)pid, sig));
    570 	}
    571 #else
    572 	/* XXXfixme: signal numbers may not match on non-NetBSD */
    573 	seterror(EOPNOTSUPP);
    574 	return -1;
    575 #endif
    576 }
    577 
    578 size_t
    579 rumpuser_getrandom(void *buf, size_t buflen, int flags)
    580 {
    581 	size_t origlen = buflen;
    582 	uint32_t *p = buf;
    583 	uint32_t tmp;
    584 	int chunk;
    585 
    586 	do {
    587 		chunk = buflen < 4 ? buflen : 4; /* portable MIN ... */
    588 		tmp = RUMPUSER_RANDOM();
    589 		memcpy(p, &tmp, chunk);
    590 		p++;
    591 		buflen -= chunk;
    592 	} while (chunk);
    593 
    594 	return origlen;
    595 }
    596