1// Copyright (c) 2012 The Chromium Authors. All rights reserved. 2// Use of this source code is governed by a BSD-style license that can be 3// found in the LICENSE file. 4 5#include "net/disk_cache/mapped_file.h" 6 7#include <errno.h> 8#include <sys/mman.h> 9 10#include "base/files/file_path.h" 11#include "base/logging.h" 12#include "net/disk_cache/disk_cache.h" 13 14namespace disk_cache { 15 16void* MappedFile::Init(const base::FilePath& name, size_t size) { 17 DCHECK(!init_); 18 if (init_ || !File::Init(name)) 19 return NULL; 20 21 size_t temp_len = size ? size : 4096; 22 if (!size) 23 size = GetLength(); 24 25 buffer_ = mmap(NULL, size, PROT_READ | PROT_WRITE, MAP_SHARED, 26 platform_file(), 0); 27 init_ = true; 28 view_size_ = size; 29 DCHECK(reinterpret_cast<intptr_t>(buffer_) != -1); 30 if (reinterpret_cast<intptr_t>(buffer_) == -1) 31 buffer_ = 0; 32 33 // Make sure we detect hardware failures reading the headers. 34 scoped_ptr<char[]> temp(new char[temp_len]); 35 if (!Read(temp.get(), temp_len, 0)) 36 return NULL; 37 38 return buffer_; 39} 40 41bool MappedFile::Load(const FileBlock* block) { 42 size_t offset = block->offset() + view_size_; 43 return Read(block->buffer(), block->size(), offset); 44} 45 46bool MappedFile::Store(const FileBlock* block) { 47 size_t offset = block->offset() + view_size_; 48 return Write(block->buffer(), block->size(), offset); 49} 50 51void MappedFile::Flush() { 52} 53 54MappedFile::~MappedFile() { 55 if (!init_) 56 return; 57 58 if (buffer_) { 59 int ret = munmap(buffer_, view_size_); 60 DCHECK_EQ(0, ret); 61 } 62} 63 64} // namespace disk_cache 65