backend_impl_v3.h revision 03b57e008b61dfcb1fbad3aea950ae0e001748b0
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// See net/disk_cache/disk_cache.h for the public interface of the cache. 6 7#ifndef NET_DISK_CACHE_BLOCKFILE_BACKEND_IMPL_V3_H_ 8#define NET_DISK_CACHE_BLOCKFILE_BACKEND_IMPL_V3_H_ 9 10#include "base/containers/hash_tables.h" 11#include "base/files/file_path.h" 12#include "base/memory/ref_counted.h" 13#include "base/timer/timer.h" 14#include "net/disk_cache/blockfile/block_bitmaps_v3.h" 15#include "net/disk_cache/blockfile/block_files.h" 16#include "net/disk_cache/blockfile/eviction_v3.h" 17#include "net/disk_cache/blockfile/index_table_v3.h" 18#include "net/disk_cache/blockfile/stats.h" 19#include "net/disk_cache/blockfile/stress_support.h" 20#include "net/disk_cache/blockfile/trace.h" 21#include "net/disk_cache/disk_cache.h" 22 23namespace base { 24class SingleThreadTaskRunner; 25} // namespace base 26 27namespace net { 28class NetLog; 29} // namespace net 30 31namespace disk_cache { 32 33class EntryImplV3; 34 35// This class implements the Backend interface. An object of this 36// class handles the operations of the cache for a particular profile. 37class NET_EXPORT_PRIVATE BackendImplV3 : public Backend { 38 public: 39 enum BackendFlags { 40 MAX_SIZE = 1 << 1, // A maximum size was provided. 41 UNIT_TEST_MODE = 1 << 2, // We are modifying the behavior for testing. 42 UPGRADE_MODE = 1 << 3, // This is the upgrade tool (dump). 43 EVICTION_V2 = 1 << 4, // Use of new eviction was specified. 44 BASIC_UNIT_TEST = 1 << 5, // Identifies almost all unit tests. 45 NO_LOAD_PROTECTION = 1 << 6, // Don't act conservatively under load. 46 NO_BUFFERING = 1 << 7, // Disable extended IO buffering. 47 NO_CLEAN_ON_EXIT = 1 << 8 // Avoid saving data at exit time. 48 }; 49 50 BackendImplV3(const base::FilePath& path, 51 const scoped_refptr<base::SingleThreadTaskRunner>& cache_thread, 52 net::NetLog* net_log); 53 virtual ~BackendImplV3(); 54 55 // Performs general initialization for this current instance of the cache. 56 int Init(const CompletionCallback& callback); 57 58 // Same behavior as OpenNextEntry but walks the list from back to front. 59 int OpenPrevEntry(void** iter, Entry** prev_entry, 60 const CompletionCallback& callback); 61 62 // Sets the maximum size for the total amount of data stored by this instance. 63 bool SetMaxSize(int max_bytes); 64 65 // Sets the cache type for this backend. 66 void SetType(net::CacheType type); 67 68 // Creates a new storage block of size block_count. 69 bool CreateBlock(FileType block_type, int block_count, 70 Addr* block_address); 71 72 // Updates the ranking information for an entry. 73 void UpdateRank(EntryImplV3* entry, bool modified); 74 75 // Permanently deletes an entry, but still keeps track of it. 76 void InternalDoomEntry(EntryImplV3* entry); 77 78 // This method must be called when an entry is released for the last time, so 79 // the entry should not be used anymore. |address| is the cache address of the 80 // entry. 81 void OnEntryDestroyBegin(Addr address); 82 83 // This method must be called after all resources for an entry have been 84 // released. 85 void OnEntryDestroyEnd(); 86 87 // If the |address| corresponds to an open entry, returns a pointer to that 88 // entry, otherwise returns NULL. Note that this method does not increase the 89 // ref counter for the entry. 90 EntryImplV3* GetOpenEntry(Addr address) const; 91 92 // Returns the id being used on this run of the cache. 93 int32 GetCurrentEntryId() const; 94 95 // Returns the maximum size for a file to reside on the cache. 96 int MaxFileSize() const; 97 98 // A user data block is being created, extended or truncated. 99 void ModifyStorageSize(int32 old_size, int32 new_size); 100 101 // Logs requests that are denied due to being too big. 102 void TooMuchStorageRequested(int32 size); 103 104 // Returns true if a temporary buffer is allowed to be extended. 105 bool IsAllocAllowed(int current_size, int new_size); 106 107 // Tracks the release of |size| bytes by an entry buffer. 108 void BufferDeleted(int size); 109 110 // Only intended for testing the two previous methods. 111 int GetTotalBuffersSize() const { 112 return buffer_bytes_; 113 } 114 115 // Returns true if this instance seems to be under heavy load. 116 bool IsLoaded() const; 117 118 // Returns the full histogram name, for the given base |name| and the current 119 // cache type. The name will be "DiskCache3.name_type". 120 std::string HistogramName(const char* name) const; 121 122 net::CacheType cache_type() const { 123 return cache_type_; 124 } 125 126 bool read_only() const { 127 return read_only_; 128 } 129 130 // Returns a weak pointer to this object. 131 base::WeakPtr<BackendImplV3> GetWeakPtr(); 132 133 // Returns true if we should send histograms for this user again. The caller 134 // must call this function only once per run (because it returns always the 135 // same thing on a given run). 136 bool ShouldReportAgain(); 137 138 // Reports some data when we filled up the cache. 139 void FirstEviction(); 140 141 // Called when an interesting event should be logged (counted). 142 void OnEvent(Stats::Counters an_event); 143 144 // Keeps track of payload access (doesn't include metadata). 145 void OnRead(int bytes); 146 void OnWrite(int bytes); 147 148 // Timer callback to calculate usage statistics and perform backups. 149 void OnTimerTick(); 150 151 // Sets internal parameters to enable unit testing mode. 152 void SetUnitTestMode(); 153 154 // Sets internal parameters to enable upgrade mode (for internal tools). 155 void SetUpgradeMode(); 156 157 // Sets the eviction algorithm to version 2. 158 void SetNewEviction(); 159 160 // Sets an explicit set of BackendFlags. 161 void SetFlags(uint32 flags); 162 163 // Sends a dummy operation through the operation queue, for unit tests. 164 int FlushQueueForTest(const CompletionCallback& callback); 165 166 // Trims an entry (all if |empty| is true) from the list of deleted 167 // entries. This method should be called directly on the cache thread. 168 void TrimForTest(bool empty); 169 170 // Trims an entry (all if |empty| is true) from the list of deleted 171 // entries. This method should be called directly on the cache thread. 172 void TrimDeletedListForTest(bool empty); 173 174 // Performs a simple self-check, and returns the number of dirty items 175 // or an error code (negative value). 176 int SelfCheck(); 177 178 // Backend implementation. 179 virtual net::CacheType GetCacheType() const OVERRIDE; 180 virtual int32 GetEntryCount() const OVERRIDE; 181 virtual int OpenEntry(const std::string& key, Entry** entry, 182 const CompletionCallback& callback) OVERRIDE; 183 virtual int CreateEntry(const std::string& key, Entry** entry, 184 const CompletionCallback& callback) OVERRIDE; 185 virtual int DoomEntry(const std::string& key, 186 const CompletionCallback& callback) OVERRIDE; 187 virtual int DoomAllEntries(const CompletionCallback& callback) OVERRIDE; 188 virtual int DoomEntriesBetween(base::Time initial_time, 189 base::Time end_time, 190 const CompletionCallback& callback) OVERRIDE; 191 virtual int DoomEntriesSince(base::Time initial_time, 192 const CompletionCallback& callback) OVERRIDE; 193 virtual int OpenNextEntry(void** iter, Entry** next_entry, 194 const CompletionCallback& callback) OVERRIDE; 195 virtual void EndEnumeration(void** iter) OVERRIDE; 196 virtual void GetStats(StatsItems* stats) OVERRIDE; 197 virtual void OnExternalCacheHit(const std::string& key) OVERRIDE; 198 199 private: 200 friend class EvictionV3; 201 typedef base::hash_map<CacheAddr, EntryImplV3*> EntriesMap; 202 class Worker; 203 204 void AdjustMaxCacheSize(); 205 bool InitStats(void* stats_data); 206 void StoreStats(); 207 208 // Deletes the cache and starts again. 209 void RestartCache(bool failure); 210 void PrepareForRestart(); 211 212 // Performs final cleanup. 213 void CleanupCache(); 214 215 // Creates a new entry object. Returns zero on success, or a disk_cache error 216 // on failure. 217 int NewEntry(Addr address, EntryImplV3** entry); 218 219 // Opens the next or previous entry on a cache iteration. 220 int OpenFollowingEntry(bool forward, void** iter, Entry** next_entry, 221 const CompletionCallback& callback); 222 223 // Handles the used storage count. 224 void AddStorageSize(int32 bytes); 225 void SubstractStorageSize(int32 bytes); 226 227 // Update the number of referenced cache entries. 228 void IncreaseNumRefs(); 229 void DecreaseNumRefs(); 230 void IncreaseNumEntries(); 231 void DecreaseNumEntries(); 232 233 // Dumps current cache statistics to the log. 234 void LogStats(); 235 236 // Send UMA stats. 237 void ReportStats(); 238 239 // Reports an uncommon, recoverable error. 240 void ReportError(int error); 241 242 // Performs basic checks on the index file. Returns false on failure. 243 bool CheckIndex(); 244 245 // Part of the self test. Returns the number or dirty entries, or an error. 246 int CheckAllEntries(); 247 248 // Part of the self test. Returns false if the entry is corrupt. 249 bool CheckEntry(EntryImplV3* cache_entry); 250 251 // Returns the maximum total memory for the memory buffers. 252 int MaxBuffersSize(); 253 254 IndexTable index_; 255 base::FilePath path_; // Path to the folder used as backing storage. 256 BlockBitmaps block_files_; 257 int32 max_size_; // Maximum data size for this instance. 258 EvictionV3 eviction_; // Handler of the eviction algorithm. 259 EntriesMap open_entries_; 260 int num_refs_; // Number of referenced cache entries. 261 int max_refs_; // Max number of referenced cache entries. 262 int entry_count_; // Number of entries accessed lately. 263 int byte_count_; // Number of bytes read/written lately. 264 int buffer_bytes_; // Total size of the temporary entries' buffers. 265 int up_ticks_; // The number of timer ticks received (OnTimerTick). 266 net::CacheType cache_type_; 267 int uma_report_; // Controls transmission of UMA data. 268 uint32 user_flags_; // Flags set by the user. 269 bool init_; // controls the initialization of the system. 270 bool restarted_; 271 bool read_only_; // Prevents updates of the rankings data (used by tools). 272 bool disabled_; 273 bool lru_eviction_; // What eviction algorithm should be used. 274 bool first_timer_; // True if the timer has not been called. 275 bool user_load_; // True if we see a high load coming from the caller. 276 277 net::NetLog* net_log_; 278 279 Stats stats_; // Usage statistics. 280 scoped_ptr<base::RepeatingTimer<BackendImplV3> > timer_; // Usage timer. 281 scoped_refptr<TraceObject> trace_object_; // Initializes internal tracing. 282 base::WeakPtrFactory<BackendImplV3> ptr_factory_; 283 284 DISALLOW_COPY_AND_ASSIGN(BackendImplV3); 285}; 286 287} // namespace disk_cache 288 289#endif // NET_DISK_CACHE_BLOCKFILE_BACKEND_IMPL_V3_H_ 290