portability.cc 12.7 KB
Newer Older
1 2
/* -*- mode: C++; c-basic-offset: 4; indent-tabs-mode: nil -*- */
// vim: ft=cpp:expandtab:ts=8:sw=4:softtabstop=4:
3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54
/*
COPYING CONDITIONS NOTICE:

  This program is free software; you can redistribute it and/or modify
  it under the terms of version 2 of the GNU General Public License as
  published by the Free Software Foundation, and provided that the
  following conditions are met:

      * Redistributions of source code must retain this COPYING
        CONDITIONS NOTICE, the COPYRIGHT NOTICE (below), the
        DISCLAIMER (below), the UNIVERSITY PATENT NOTICE (below), the
        PATENT MARKING NOTICE (below), and the PATENT RIGHTS
        GRANT (below).

      * Redistributions in binary form must reproduce this COPYING
        CONDITIONS NOTICE, the COPYRIGHT NOTICE (below), the
        DISCLAIMER (below), the UNIVERSITY PATENT NOTICE (below), the
        PATENT MARKING NOTICE (below), and the PATENT RIGHTS
        GRANT (below) in the documentation and/or other materials
        provided with the distribution.

  You should have received a copy of the GNU General Public License
  along with this program; if not, write to the Free Software
  Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA
  02110-1301, USA.

COPYRIGHT NOTICE:

  TokuDB, Tokutek Fractal Tree Indexing Library.
  Copyright (C) 2007-2013 Tokutek, Inc.

DISCLAIMER:

  This program is distributed in the hope that it will be useful, but
  WITHOUT ANY WARRANTY; without even the implied warranty of
  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
  General Public License for more details.

UNIVERSITY PATENT NOTICE:

  The technology is licensed by the Massachusetts Institute of
  Technology, Rutgers State University of New Jersey, and the Research
  Foundation of State University of New York at Stony Brook under
  United States of America Serial No. 11/760379 and to the patents
  and/or patent applications resulting from it.

PATENT MARKING NOTICE:

  This software is covered by US Patent No. 8,185,551.

PATENT RIGHTS GRANT:

55
  "THIS IMPLEMENTATION" means the copyrightable works distributed by
56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86
  Tokutek as part of the Fractal Tree project.

  "PATENT CLAIMS" means the claims of patents that are owned or
  licensable by Tokutek, both currently or in the future; and that in
  the absence of this license would be infringed by THIS
  IMPLEMENTATION or by using or running THIS IMPLEMENTATION.

  "PATENT CHALLENGE" shall mean a challenge to the validity,
  patentability, enforceability and/or non-infringement of any of the
  PATENT CLAIMS or otherwise opposing any of the PATENT CLAIMS.

  Tokutek hereby grants to you, for the term and geographical scope of
  the PATENT CLAIMS, a non-exclusive, no-charge, royalty-free,
  irrevocable (except as stated in this section) patent license to
  make, have made, use, offer to sell, sell, import, transfer, and
  otherwise run, modify, and propagate the contents of THIS
  IMPLEMENTATION, where such license applies only to the PATENT
  CLAIMS.  This grant does not include claims that would be infringed
  only as a consequence of further modifications of THIS
  IMPLEMENTATION.  If you or your agent or licensee institute or order
  or agree to the institution of patent litigation against any entity
  (including a cross-claim or counterclaim in a lawsuit) alleging that
  THIS IMPLEMENTATION constitutes direct or contributory patent
  infringement, or inducement of patent infringement, then any rights
  granted to you under this License shall terminate as of the date
  such litigation is filed.  If you or your agent or exclusive
  licensee institute or order or agree to the institution of a PATENT
  CHALLENGE, then Tokutek may terminate any rights granted to you
  under this License.
*/

87
#ident "Copyright (c) 2007-2013 Tokutek Inc.  All rights reserved."
88 89
#ident "$Id$"

90
#include "toku_config.h"
91

92 93 94 95 96 97 98
#include <stdio.h>
#include <stdlib.h>
#include <stdint.h>
#include <unistd.h>
#include <string.h>
#include <fcntl.h>
#include <errno.h>
99
#include <toku_assert.h>
100 101 102 103 104
#if defined(HAVE_MALLOC_H)
# include <malloc.h>
#elif defined(HAVE_SYS_MALLOC_H)
# include <sys/malloc.h>
#endif
105 106 107
#include <sys/types.h>
#include <sys/stat.h>
#include <sys/file.h>
108 109
#if defined(HAVE_SYSCALL_H)
# include <syscall.h>
110 111
#endif
#if defined(HAVE_SYS_SYSCALL_H)
112 113 114 115 116
# include <sys/syscall.h>
#endif
#if defined(HAVE_SYS_SYSCTL_H)
# include <sys/sysctl.h>
#endif
117 118 119
#if defined(HAVE_PTHREAD_NP_H)
# include <pthread_np.h>
#endif
120
#include <inttypes.h>
121
#include <sys/time.h>
122 123 124
#if defined(HAVE_SYS_RESOURCE_H)
# include <sys/resource.h>
#endif
125
#include <sys/statvfs.h>
126
#include "toku_portability.h"
Rich Prohaska's avatar
Rich Prohaska committed
127
#include "toku_os.h"
128
#include "toku_time.h"
129
#include "memory.h"
130
#include <portability/toku_atomic.h>
131
#include <util/partitioned_counter.h>
Yoni Fogel's avatar
Yoni Fogel committed
132 133 134

int
toku_portability_init(void) {
135
    int r = toku_memory_startup();
Rich Prohaska's avatar
Rich Prohaska committed
136 137
    if (r == 0) {
        uint64_t hz;
138
        r = toku_os_get_processor_frequency(&hz); // get and cache freq
Rich Prohaska's avatar
Rich Prohaska committed
139
    }
140
    (void) toku_os_get_pagesize(); // get and cache pagesize
Yoni Fogel's avatar
Yoni Fogel committed
141 142 143
    return r;
}

144
void
Yoni Fogel's avatar
Yoni Fogel committed
145
toku_portability_destroy(void) {
146
    toku_memory_shutdown();
Yoni Fogel's avatar
Yoni Fogel committed
147
}
148 149

int
Rich Prohaska's avatar
Rich Prohaska committed
150
toku_os_getpid(void) {
151 152 153 154
    return getpid();
}

int
Rich Prohaska's avatar
Rich Prohaska committed
155
toku_os_gettid(void) {
156
#if defined(__NR_gettid)
157
    return syscall(__NR_gettid);
158 159 160 161 162 163 164
#elif defined(SYS_gettid)
    return syscall(SYS_gettid);
#elif defined(HAVE_PTHREAD_GETTHREADID_NP)
    return pthread_getthreadid_np();
#else
# error "no implementation of gettid available"
#endif
165 166 167
}

int
Rich Prohaska's avatar
Rich Prohaska committed
168
toku_os_get_number_processors(void) {
169 170 171 172
    return sysconf(_SC_NPROCESSORS_CONF);
}

int
Rich Prohaska's avatar
Rich Prohaska committed
173
toku_os_get_number_active_processors(void) {
174 175 176
    int n = sysconf(_SC_NPROCESSORS_ONLN);
#define DO_TOKU_NCPUS 1
#if DO_TOKU_NCPUS
177 178 179 180 181 182 183
    {
        char *toku_ncpus = getenv("TOKU_NCPUS");
        if (toku_ncpus) {
            int ncpus = atoi(toku_ncpus);
            if (ncpus < n)
                n = ncpus;
        }
184 185 186
    }
#endif
    return n;
187 188
}

189 190
int toku_cached_pagesize = 0;

191
int
Rich Prohaska's avatar
Rich Prohaska committed
192
toku_os_get_pagesize(void) {
193 194 195 196 197 198 199 200
    int pagesize = toku_cached_pagesize;
    if (pagesize == 0) {
        pagesize = sysconf(_SC_PAGESIZE);
        if (pagesize) {
            toku_cached_pagesize = pagesize;
        }
    }
    return pagesize;
201 202 203
}

uint64_t
Rich Prohaska's avatar
Rich Prohaska committed
204
toku_os_get_phys_memory_size(void) {
205
#if defined(_SC_PHYS_PAGES)
206 207 208
    uint64_t npages = sysconf(_SC_PHYS_PAGES);
    uint64_t pagesize = sysconf(_SC_PAGESIZE);
    return npages*pagesize;
209 210 211 212 213 214 215 216
#elif defined(HAVE_SYS_SYSCTL_H)
    uint64_t memsize;
    size_t len = sizeof memsize;
    sysctlbyname("hw.memsize", &memsize, &len, NULL, 0);
    return memsize;
#else
# error "cannot find _SC_PHYS_PAGES or sysctlbyname()"
#endif
217 218 219
}

int
Rich Prohaska's avatar
Rich Prohaska committed
220
toku_os_get_file_size(int fildes, int64_t *fsize) {
221
    toku_struct_stat sbuf;
222 223 224 225 226 227 228 229
    int r = fstat(fildes, &sbuf);
    if (r==0) {
        *fsize = sbuf.st_size;
    }
    return r;
}

int
Rich Prohaska's avatar
Rich Prohaska committed
230
toku_os_get_unique_file_id(int fildes, struct fileid *id) {
231
    toku_struct_stat statbuf;
232 233 234 235 236 237 238 239 240 241
    memset(id, 0, sizeof(*id));
    int r=fstat(fildes, &statbuf);
    if (r==0) {
        id->st_dev = statbuf.st_dev;
        id->st_ino = statbuf.st_ino;
    }
    return r;
}

int
242
toku_os_lock_file(const char *name) {
243 244 245 246 247 248 249 250 251 252 253 254 255 256 257
    int r;
    int fd = open(name, O_RDWR|O_CREAT, S_IRUSR | S_IWUSR);
    if (fd>=0) {
        r = flock(fd, LOCK_EX | LOCK_NB);
        if (r!=0) {
            r = errno; //Save errno from flock.
            close(fd);
            fd = -1; //Disable fd.
            errno = r;
        }
    }
    return fd;
}

int
Rich Prohaska's avatar
Rich Prohaska committed
258
toku_os_unlock_file(int fildes) {
259 260 261 262 263 264
    int r = flock(fildes, LOCK_UN);
    if (r==0) r = close(fildes);
    return r;
}

int
Rich Prohaska's avatar
Rich Prohaska committed
265
toku_os_mkdir(const char *pathname, mode_t mode) {
266 267 268 269 270
    int r = mkdir(pathname, mode);
    return r;
}

int
Rich Prohaska's avatar
Rich Prohaska committed
271
toku_os_get_process_times(struct timeval *usertime, struct timeval *kerneltime) {
272 273 274 275
    int r;
    struct rusage rusage;
    r = getrusage(RUSAGE_SELF, &rusage);
    if (r == -1)
276
        return get_error_errno();
277 278 279 280 281 282 283 284
    if (usertime) 
        *usertime = rusage.ru_utime;
    if (kerneltime)
        *kerneltime = rusage.ru_stime;
    return 0;
}

int
Rich Prohaska's avatar
Rich Prohaska committed
285
toku_os_initialize_settings(int UU(verbosity)) {
286 287 288 289 290 291 292
    int r = 0;
    static int initialized = 0;
    assert(initialized==0);
    initialized=1;
    return r;
}

293
bool toku_os_is_absolute_name(const char* path) {
Zardosht Kasheff's avatar
Zardosht Kasheff committed
294 295 296
    return path[0] == '/';
}

297 298 299 300 301 302 303
int
toku_os_get_max_process_data_size(uint64_t *maxdata) {
    int r;
    struct rlimit rlimit;

    r = getrlimit(RLIMIT_DATA, &rlimit);
    if (r == 0) {
304 305 306 307 308
        uint64_t d;
        d = rlimit.rlim_max;
	// with the "right" macros defined, the rlimit is a 64 bit number on a
	// 32 bit system.  getrlimit returns 2**64-1 which is clearly wrong.

309
        // for 32 bit processes, we assume that 1/2 of the address space is
310 311 312 313
        // used for mapping the kernel.  this may be pessimistic.
        if (sizeof (void *) == 4 && d > (1ULL << 31))
            d = 1ULL << 31;
	*maxdata = d;
314
    } else
315
        r = get_error_errno();
316 317
    return r;
}
318 319 320 321 322 323 324 325

int
toku_stat(const char *name, toku_struct_stat *buf) {
    int r = stat(name, buf);
    return r;
}

int
326
toku_fstat(int fd, toku_struct_stat *buf) {
327 328 329 330
    int r = fstat(fd, buf);
    return r;
}

331 332 333 334 335
static int
toku_get_processor_frequency_sys(uint64_t *hzret) {
    int r;
    FILE *fp = fopen("/sys/devices/system/cpu/cpu0/cpufreq/cpuinfo_max_freq", "r");
    if (!fp) 
336
        r = get_error_errno();
337 338 339 340 341 342 343 344 345 346 347 348 349 350
    else {
        unsigned int khz = 0;
        if (fscanf(fp, "%u", &khz) == 1) {
            *hzret = khz * 1000ULL;
            r = 0;
        } else
            r = ENOENT;
        fclose(fp);
    }
    return r;
}

static int
toku_get_processor_frequency_cpuinfo(uint64_t *hzret) {
351 352 353
    int r;
    FILE *fp = fopen("/proc/cpuinfo", "r");
    if (!fp) {
354
        r = get_error_errno();
355 356 357 358 359 360 361 362
    } else {
        uint64_t maxhz = 0;
        char *buf = NULL;
        size_t n = 0;
        while (getline(&buf, &n, fp) >= 0) {
            unsigned int cpu;
            sscanf(buf, "processor : %u", &cpu);
            unsigned int ma, mb;
363
            if (sscanf(buf, "cpu MHz : %u.%u", &ma, &mb) == 2) {
364 365 366 367 368 369 370 371 372 373 374 375 376
                uint64_t hz = ma * 1000000ULL + mb * 1000ULL;
                if (hz > maxhz)
                    maxhz = hz;
            }
        }
        if (buf)
            free(buf);
        fclose(fp);
        *hzret = maxhz;
        r = maxhz == 0 ? ENOENT : 0;;
    }
    return r;
}
377

378
static int
379
toku_get_processor_frequency_sysctl(const char * const cmd, uint64_t *hzret) {
380 381 382 383 384 385
    int r = 0;
    FILE *fp = popen(cmd, "r");
    if (!fp) {
        r = EINVAL;  // popen doesn't return anything useful in errno,
                     // gotta pick something
    } else {
Rich Prohaska's avatar
Rich Prohaska committed
386 387 388 389 390 391 392
        r = fscanf(fp, "%" SCNu64, hzret);
        if (r != 1) {
            r = get_maybe_error_errno();
        } else {
            r = 0;
        }
        pclose(fp);
393 394 395 396
    }
    return r;
}

Rich Prohaska's avatar
Rich Prohaska committed
397 398 399
static uint64_t toku_cached_hz; // cache the value of hz so that we avoid opening files to compute it later

int 
400 401
toku_os_get_processor_frequency(uint64_t *hzret) {
    int r;
Rich Prohaska's avatar
Rich Prohaska committed
402 403 404 405 406 407 408 409 410 411 412 413 414 415
    if (toku_cached_hz) {
        *hzret = toku_cached_hz;
        r = 0;
    } else {
        r = toku_get_processor_frequency_sys(hzret);
        if (r != 0)
            r = toku_get_processor_frequency_cpuinfo(hzret);
        if (r != 0)
            r = toku_get_processor_frequency_sysctl("sysctl -n hw.cpufrequency", hzret);
        if (r != 0)
            r = toku_get_processor_frequency_sysctl("sysctl -n machdep.tsc_freq", hzret);
        if (r == 0)
            toku_cached_hz = *hzret;
    }
416 417
    return r;
}
418

419 420 421 422
int
toku_get_filesystem_sizes(const char *path, uint64_t *avail_size, uint64_t *free_size, uint64_t *total_size) {
    struct statvfs s;
    int r = statvfs(path, &s);
423 424 425
    if (r == -1) {
        r = get_error_errno();
    } else {
426 427 428 429 430 431 432 433 434 435 436 437 438 439
        // get the block size in bytes
        uint64_t bsize = s.f_frsize ? s.f_frsize : s.f_bsize;
        // convert blocks to bytes
        if (avail_size)
            *avail_size = (uint64_t) s.f_bavail * bsize;
        if (free_size) 
            *free_size = (uint64_t) s.f_bfree * bsize;
        if (total_size) 
            *total_size = (uint64_t) s.f_blocks * bsize;
    }
    return r;
}


440 441 442 443 444 445 446
int
toku_dup2(int fd, int fd2) {
    int r;
    r = dup2(fd, fd2);
    return r;
}

447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462

// Time
static       double seconds_per_clock = -1;

double tokutime_to_seconds(tokutime_t t) {
    // Convert tokutime to seconds.
    if (seconds_per_clock<0) {
	uint64_t hz;
	int r = toku_os_get_processor_frequency(&hz);
	assert(r==0);
	// There's a race condition here, but it doesn't really matter.  If two threads call tokutime_to_seconds
	// for the first time at the same time, then both will fetch the value and set the same value.
	seconds_per_clock = 1.0/hz;
    }
    return t*seconds_per_clock;
}
Rich Prohaska's avatar
Rich Prohaska committed
463 464 465 466 467 468

#include <toku_race_tools.h>
void __attribute__((constructor)) toku_portability_helgrind_ignore(void);
void
toku_portability_helgrind_ignore(void) {
    TOKU_VALGRIND_HG_DISABLE_CHECKING(&toku_cached_hz, sizeof toku_cached_hz);
469
    TOKU_VALGRIND_HG_DISABLE_CHECKING(&toku_cached_pagesize, sizeof toku_cached_pagesize);
Rich Prohaska's avatar
Rich Prohaska committed
470
}