19f8118474e9513f7a5b7d2a05e4a0fb15d1a6569Jesse Wilson// Copyright (c) 2012 The Chromium Authors. All rights reserved.
29f8118474e9513f7a5b7d2a05e4a0fb15d1a6569Jesse Wilson// Use of this source code is governed by a BSD-style license that can be
39f8118474e9513f7a5b7d2a05e4a0fb15d1a6569Jesse Wilson// found in the LICENSE file.
49f8118474e9513f7a5b7d2a05e4a0fb15d1a6569Jesse Wilson
59f8118474e9513f7a5b7d2a05e4a0fb15d1a6569Jesse Wilson#include "net/disk_cache/blockfile/mapped_file.h"
69f8118474e9513f7a5b7d2a05e4a0fb15d1a6569Jesse Wilson
79f8118474e9513f7a5b7d2a05e4a0fb15d1a6569Jesse Wilson#include "base/files/file_path.h"
89f8118474e9513f7a5b7d2a05e4a0fb15d1a6569Jesse Wilson#include "base/logging.h"
99f8118474e9513f7a5b7d2a05e4a0fb15d1a6569Jesse Wilson#include "base/memory/scoped_ptr.h"
109f8118474e9513f7a5b7d2a05e4a0fb15d1a6569Jesse Wilson#include "net/disk_cache/disk_cache.h"
119f8118474e9513f7a5b7d2a05e4a0fb15d1a6569Jesse Wilson
129f8118474e9513f7a5b7d2a05e4a0fb15d1a6569Jesse Wilsonnamespace disk_cache {
139f8118474e9513f7a5b7d2a05e4a0fb15d1a6569Jesse Wilson
149f8118474e9513f7a5b7d2a05e4a0fb15d1a6569Jesse Wilsonvoid* MappedFile::Init(const base::FilePath& name, size_t size) {
159f8118474e9513f7a5b7d2a05e4a0fb15d1a6569Jesse Wilson  DCHECK(!init_);
169f8118474e9513f7a5b7d2a05e4a0fb15d1a6569Jesse Wilson  if (init_ || !File::Init(name))
179f8118474e9513f7a5b7d2a05e4a0fb15d1a6569Jesse Wilson    return NULL;
189f8118474e9513f7a5b7d2a05e4a0fb15d1a6569Jesse Wilson
199f8118474e9513f7a5b7d2a05e4a0fb15d1a6569Jesse Wilson  buffer_ = NULL;
209f8118474e9513f7a5b7d2a05e4a0fb15d1a6569Jesse Wilson  init_ = true;
219f8118474e9513f7a5b7d2a05e4a0fb15d1a6569Jesse Wilson  section_ = CreateFileMapping(platform_file(), NULL, PAGE_READWRITE, 0,
229f8118474e9513f7a5b7d2a05e4a0fb15d1a6569Jesse Wilson                               static_cast<DWORD>(size), NULL);
239f8118474e9513f7a5b7d2a05e4a0fb15d1a6569Jesse Wilson  if (!section_)
249f8118474e9513f7a5b7d2a05e4a0fb15d1a6569Jesse Wilson    return NULL;
259f8118474e9513f7a5b7d2a05e4a0fb15d1a6569Jesse Wilson
269f8118474e9513f7a5b7d2a05e4a0fb15d1a6569Jesse Wilson  buffer_ = MapViewOfFile(section_, FILE_MAP_READ | FILE_MAP_WRITE, 0, 0, size);
279f8118474e9513f7a5b7d2a05e4a0fb15d1a6569Jesse Wilson  DCHECK(buffer_);
289f8118474e9513f7a5b7d2a05e4a0fb15d1a6569Jesse Wilson  view_size_ = size;
29
30  // Make sure we detect hardware failures reading the headers.
31  size_t temp_len = size ? size : 4096;
32  scoped_ptr<char[]> temp(new char[temp_len]);
33  if (!Read(temp.get(), temp_len, 0))
34    return NULL;
35
36  return buffer_;
37}
38
39MappedFile::~MappedFile() {
40  if (!init_)
41    return;
42
43  if (buffer_) {
44    BOOL ret = UnmapViewOfFile(buffer_);
45    DCHECK(ret);
46  }
47
48  if (section_)
49    CloseHandle(section_);
50}
51
52void MappedFile::Flush() {
53}
54
55}  // namespace disk_cache
56