Path: blob/master/test/jdk/java/nio/channels/FileChannel/directio/libDirectIO.c
41161 views
/*1* Copyright (c) 2017, Oracle and/or its affiliates. All rights reserved.2* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.3*4* This code is free software; you can redistribute it and/or modify it5* under the terms of the GNU General Public License version 2 only, as6* published by the Free Software Foundation.7*8* This code is distributed in the hope that it will be useful, but WITHOUT9* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or10* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License11* version 2 for more details (a copy is included in the LICENSE file that12* accompanied this code).13*14* You should have received a copy of the GNU General Public License version15* 2 along with this work; if not, write to the Free Software Foundation,16* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.17*18* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA19* or visit www.oracle.com if you need additional information or have any20* questions.21*/2223/*24* Test if a file exists in the file system cache25*/26#include <stdlib.h>27#include <fcntl.h>28#include <sys/types.h>29#include <sys/stat.h>30#include <unistd.h>31#include <sys/mman.h>3233#include "jni.h"3435/*36* Throws an exception with the given class name and detail message37*/38static void ThrowException(JNIEnv *env, const char *name, const char *msg) {39jclass cls = (*env)->FindClass(env, name);40if (cls != NULL) {41(*env)->ThrowNew(env, cls, msg);42}43}4445/*46* Class: DirectIO47* Method: isFileInCache048* Signature: (ILjava/lang/String;)Z49*/50JNIEXPORT jboolean Java_DirectIOTest_isFileInCache0(JNIEnv *env,51jclass cls,52jint file_size,53jstring file_path) {54void *f_mmap;55#ifdef __linux__56unsigned char *f_seg;57#else58char *f_seg;59#endif6061#ifdef __APPLE__62size_t mask = MINCORE_INCORE;63#else64size_t mask = 0x1;65#endif6667size_t page_size = getpagesize();68size_t index = (file_size + page_size - 1) /page_size;69jboolean result = JNI_FALSE;7071const char* path = (*env)->GetStringUTFChars(env, file_path, JNI_FALSE);7273int fd = open(path, O_RDWR);7475(*env)->ReleaseStringUTFChars(env, file_path, path);7677f_mmap = mmap(0, file_size, PROT_NONE, MAP_SHARED, fd, 0);78if (f_mmap == MAP_FAILED) {79close(fd);80ThrowException(env, "java/io/IOException",81"test of whether file exists in cache failed");82}83f_seg = malloc(index);84if (f_seg != NULL) {85if(mincore(f_mmap, file_size, f_seg) == 0) {86size_t i;87for (i = 0; i < index; i++) {88if (f_seg[i] & mask) {89result = JNI_TRUE;90break;91}92}93}94free(f_seg);95} else {96ThrowException(env, "java/io/IOException",97"test of whether file exists in cache failed");98}99close(fd);100munmap(f_mmap, file_size);101return result;102}103104105