Windows should animate when they are about to get docked at screen edges.
[chromium-blink-merge.git] / net / disk_cache / backend_impl.h
blob982bee64818098c0c04ecb23be0288ef412cd374
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.
5 // See net/disk_cache/disk_cache.h for the public interface of the cache.
7 #ifndef NET_DISK_CACHE_BACKEND_IMPL_H_
8 #define NET_DISK_CACHE_BACKEND_IMPL_H_
10 #include "base/containers/hash_tables.h"
11 #include "base/files/file_path.h"
12 #include "base/timer/timer.h"
13 #include "net/disk_cache/block_files.h"
14 #include "net/disk_cache/disk_cache.h"
15 #include "net/disk_cache/eviction.h"
16 #include "net/disk_cache/in_flight_backend_io.h"
17 #include "net/disk_cache/rankings.h"
18 #include "net/disk_cache/stats.h"
19 #include "net/disk_cache/stress_support.h"
20 #include "net/disk_cache/trace.h"
22 namespace net {
23 class NetLog;
24 } // namespace net
26 namespace disk_cache {
28 struct Index;
30 enum BackendFlags {
31 kNone = 0,
32 kMask = 1, // A mask (for the index table) was specified.
33 kMaxSize = 1 << 1, // A maximum size was provided.
34 kUnitTestMode = 1 << 2, // We are modifying the behavior for testing.
35 kUpgradeMode = 1 << 3, // This is the upgrade tool (dump).
36 kNewEviction = 1 << 4, // Use of new eviction was specified.
37 kNoRandom = 1 << 5, // Don't add randomness to the behavior.
38 kNoLoadProtection = 1 << 6, // Don't act conservatively under load.
39 kNoBuffering = 1 << 7 // Disable extended IO buffering.
42 // This class implements the Backend interface. An object of this
43 // class handles the operations of the cache for a particular profile.
44 class NET_EXPORT_PRIVATE BackendImpl : public Backend {
45 friend class Eviction;
46 public:
47 BackendImpl(const base::FilePath& path, base::MessageLoopProxy* cache_thread,
48 net::NetLog* net_log);
49 // mask can be used to limit the usable size of the hash table, for testing.
50 BackendImpl(const base::FilePath& path, uint32 mask,
51 base::MessageLoopProxy* cache_thread, net::NetLog* net_log);
52 virtual ~BackendImpl();
54 // Performs general initialization for this current instance of the cache.
55 int Init(const CompletionCallback& callback);
57 // Performs the actual initialization and final cleanup on destruction.
58 int SyncInit();
59 void CleanupCache();
61 // Same behavior as OpenNextEntry but walks the list from back to front.
62 int OpenPrevEntry(void** iter, Entry** prev_entry,
63 const CompletionCallback& callback);
65 // Synchronous implementation of the asynchronous interface.
66 int SyncOpenEntry(const std::string& key, Entry** entry);
67 int SyncCreateEntry(const std::string& key, Entry** entry);
68 int SyncDoomEntry(const std::string& key);
69 int SyncDoomAllEntries();
70 int SyncDoomEntriesBetween(base::Time initial_time,
71 base::Time end_time);
72 int SyncDoomEntriesSince(base::Time initial_time);
73 int SyncOpenNextEntry(void** iter, Entry** next_entry);
74 int SyncOpenPrevEntry(void** iter, Entry** prev_entry);
75 void SyncEndEnumeration(void* iter);
76 void SyncOnExternalCacheHit(const std::string& key);
78 // Open or create an entry for the given |key| or |iter|.
79 EntryImpl* OpenEntryImpl(const std::string& key);
80 EntryImpl* CreateEntryImpl(const std::string& key);
81 EntryImpl* OpenNextEntryImpl(void** iter);
82 EntryImpl* OpenPrevEntryImpl(void** iter);
84 // Sets the maximum size for the total amount of data stored by this instance.
85 bool SetMaxSize(int max_bytes);
87 // Sets the cache type for this backend.
88 void SetType(net::CacheType type);
90 // Returns the full name for an external storage file.
91 base::FilePath GetFileName(Addr address) const;
93 // Returns the actual file used to store a given (non-external) address.
94 MappedFile* File(Addr address);
96 // Returns a weak pointer to the background queue.
97 base::WeakPtr<InFlightBackendIO> GetBackgroundQueue();
99 // Creates an external storage file.
100 bool CreateExternalFile(Addr* address);
102 // Creates a new storage block of size block_count.
103 bool CreateBlock(FileType block_type, int block_count,
104 Addr* block_address);
106 // Deletes a given storage block. deep set to true can be used to zero-fill
107 // the related storage in addition of releasing the related block.
108 void DeleteBlock(Addr block_address, bool deep);
110 // Retrieves a pointer to the LRU-related data.
111 LruData* GetLruData();
113 // Updates the ranking information for an entry.
114 void UpdateRank(EntryImpl* entry, bool modified);
116 // A node was recovered from a crash, it may not be on the index, so this
117 // method checks it and takes the appropriate action.
118 void RecoveredEntry(CacheRankingsBlock* rankings);
120 // Permanently deletes an entry, but still keeps track of it.
121 void InternalDoomEntry(EntryImpl* entry);
123 #if defined(NET_BUILD_STRESS_CACHE)
124 // Returns the address of the entry linked to the entry at a given |address|.
125 CacheAddr GetNextAddr(Addr address);
127 // Verifies that |entry| is not currently reachable through the index.
128 void NotLinked(EntryImpl* entry);
129 #endif
131 // Removes all references to this entry.
132 void RemoveEntry(EntryImpl* entry);
134 // This method must be called when an entry is released for the last time, so
135 // the entry should not be used anymore. |address| is the cache address of the
136 // entry.
137 void OnEntryDestroyBegin(Addr address);
139 // This method must be called after all resources for an entry have been
140 // released.
141 void OnEntryDestroyEnd();
143 // If the data stored by the provided |rankings| points to an open entry,
144 // returns a pointer to that entry, otherwise returns NULL. Note that this
145 // method does NOT increase the ref counter for the entry.
146 EntryImpl* GetOpenEntry(CacheRankingsBlock* rankings) const;
148 // Returns the id being used on this run of the cache.
149 int32 GetCurrentEntryId() const;
151 // Returns the maximum size for a file to reside on the cache.
152 int MaxFileSize() const;
154 // A user data block is being created, extended or truncated.
155 void ModifyStorageSize(int32 old_size, int32 new_size);
157 // Logs requests that are denied due to being too big.
158 void TooMuchStorageRequested(int32 size);
160 // Returns true if a temporary buffer is allowed to be extended.
161 bool IsAllocAllowed(int current_size, int new_size);
163 // Tracks the release of |size| bytes by an entry buffer.
164 void BufferDeleted(int size);
166 // Only intended for testing the two previous methods.
167 int GetTotalBuffersSize() const {
168 return buffer_bytes_;
171 // Returns true if this instance seems to be under heavy load.
172 bool IsLoaded() const;
174 // Returns the full histogram name, for the given base |name| and experiment,
175 // and the current cache type. The name will be "DiskCache.t.name_e" where n
176 // is the cache type and e the provided |experiment|.
177 std::string HistogramName(const char* name, int experiment) const;
179 net::CacheType cache_type() const {
180 return cache_type_;
183 bool read_only() const {
184 return read_only_;
187 // Returns a weak pointer to this object.
188 base::WeakPtr<BackendImpl> GetWeakPtr();
190 // Returns true if we should send histograms for this user again. The caller
191 // must call this function only once per run (because it returns always the
192 // same thing on a given run).
193 bool ShouldReportAgain();
195 // Reports some data when we filled up the cache.
196 void FirstEviction();
198 // Reports a critical error (and disables the cache).
199 void CriticalError(int error);
201 // Reports an uncommon, recoverable error.
202 void ReportError(int error);
204 // Called when an interesting event should be logged (counted).
205 void OnEvent(Stats::Counters an_event);
207 // Keeps track of payload access (doesn't include metadata).
208 void OnRead(int bytes);
209 void OnWrite(int bytes);
211 // Timer callback to calculate usage statistics.
212 void OnStatsTimer();
214 // Handles the pending asynchronous IO count.
215 void IncrementIoCount();
216 void DecrementIoCount();
218 // Sets internal parameters to enable unit testing mode.
219 void SetUnitTestMode();
221 // Sets internal parameters to enable upgrade mode (for internal tools).
222 void SetUpgradeMode();
224 // Sets the eviction algorithm to version 2.
225 void SetNewEviction();
227 // Sets an explicit set of BackendFlags.
228 void SetFlags(uint32 flags);
230 // Clears the counter of references to test handling of corruptions.
231 void ClearRefCountForTest();
233 // Sends a dummy operation through the operation queue, for unit tests.
234 int FlushQueueForTest(const CompletionCallback& callback);
236 // Runs the provided task on the cache thread. The task will be automatically
237 // deleted after it runs.
238 int RunTaskForTest(const base::Closure& task,
239 const CompletionCallback& callback);
241 // Trims an entry (all if |empty| is true) from the list of deleted
242 // entries. This method should be called directly on the cache thread.
243 void TrimForTest(bool empty);
245 // Trims an entry (all if |empty| is true) from the list of deleted
246 // entries. This method should be called directly on the cache thread.
247 void TrimDeletedListForTest(bool empty);
249 // Performs a simple self-check, and returns the number of dirty items
250 // or an error code (negative value).
251 int SelfCheck();
253 // Ensures the index is flushed to disk (a no-op on platforms with mmap).
254 void FlushIndex();
256 // Backend implementation.
257 virtual net::CacheType GetCacheType() const OVERRIDE;
258 virtual int32 GetEntryCount() const OVERRIDE;
259 virtual int OpenEntry(const std::string& key, Entry** entry,
260 const CompletionCallback& callback) OVERRIDE;
261 virtual int CreateEntry(const std::string& key, Entry** entry,
262 const CompletionCallback& callback) OVERRIDE;
263 virtual int DoomEntry(const std::string& key,
264 const CompletionCallback& callback) OVERRIDE;
265 virtual int DoomAllEntries(const CompletionCallback& callback) OVERRIDE;
266 virtual int DoomEntriesBetween(base::Time initial_time,
267 base::Time end_time,
268 const CompletionCallback& callback) OVERRIDE;
269 virtual int DoomEntriesSince(base::Time initial_time,
270 const CompletionCallback& callback) OVERRIDE;
271 virtual int OpenNextEntry(void** iter, Entry** next_entry,
272 const CompletionCallback& callback) OVERRIDE;
273 virtual void EndEnumeration(void** iter) OVERRIDE;
274 virtual void GetStats(StatsItems* stats) OVERRIDE;
275 virtual void OnExternalCacheHit(const std::string& key) OVERRIDE;
277 private:
278 typedef base::hash_map<CacheAddr, EntryImpl*> EntriesMap;
280 // Creates a new backing file for the cache index.
281 bool CreateBackingStore(disk_cache::File* file);
282 bool InitBackingStore(bool* file_created);
283 void AdjustMaxCacheSize(int table_len);
285 bool InitStats();
286 void StoreStats();
288 // Deletes the cache and starts again.
289 void RestartCache(bool failure);
290 void PrepareForRestart();
292 // Creates a new entry object. Returns zero on success, or a disk_cache error
293 // on failure.
294 int NewEntry(Addr address, EntryImpl** entry);
296 // Returns a given entry from the cache. The entry to match is determined by
297 // key and hash, and the returned entry may be the matched one or it's parent
298 // on the list of entries with the same hash (or bucket). To look for a parent
299 // of a given entry, |entry_addr| should be grabbed from that entry, so that
300 // if it doesn't match the entry on the index, we know that it was replaced
301 // with a new entry; in this case |*match_error| will be set to true and the
302 // return value will be NULL.
303 EntryImpl* MatchEntry(const std::string& key, uint32 hash, bool find_parent,
304 Addr entry_addr, bool* match_error);
306 // Opens the next or previous entry on a cache iteration.
307 EntryImpl* OpenFollowingEntry(bool forward, void** iter);
309 // Opens the next or previous entry on a single list. If successful,
310 // |from_entry| will be updated to point to the new entry, otherwise it will
311 // be set to NULL; in other words, it is used as an explicit iterator.
312 bool OpenFollowingEntryFromList(bool forward, Rankings::List list,
313 CacheRankingsBlock** from_entry,
314 EntryImpl** next_entry);
316 // Returns the entry that is pointed by |next|, from the given |list|.
317 EntryImpl* GetEnumeratedEntry(CacheRankingsBlock* next, Rankings::List list);
319 // Re-opens an entry that was previously deleted.
320 EntryImpl* ResurrectEntry(EntryImpl* deleted_entry);
322 void DestroyInvalidEntry(EntryImpl* entry);
324 // Handles the used storage count.
325 void AddStorageSize(int32 bytes);
326 void SubstractStorageSize(int32 bytes);
328 // Update the number of referenced cache entries.
329 void IncreaseNumRefs();
330 void DecreaseNumRefs();
331 void IncreaseNumEntries();
332 void DecreaseNumEntries();
334 // Dumps current cache statistics to the log.
335 void LogStats();
337 // Send UMA stats.
338 void ReportStats();
340 // Upgrades the index file to version 2.1.
341 void UpgradeTo2_1();
343 // Performs basic checks on the index file. Returns false on failure.
344 bool CheckIndex();
346 // Part of the self test. Returns the number or dirty entries, or an error.
347 int CheckAllEntries();
349 // Part of the self test. Returns false if the entry is corrupt.
350 bool CheckEntry(EntryImpl* cache_entry);
352 // Returns the maximum total memory for the memory buffers.
353 int MaxBuffersSize();
355 InFlightBackendIO background_queue_; // The controller of pending operations.
356 scoped_refptr<MappedFile> index_; // The main cache index.
357 base::FilePath path_; // Path to the folder used as backing storage.
358 Index* data_; // Pointer to the index data.
359 BlockFiles block_files_; // Set of files used to store all data.
360 Rankings rankings_; // Rankings to be able to trim the cache.
361 uint32 mask_; // Binary mask to map a hash to the hash table.
362 int32 max_size_; // Maximum data size for this instance.
363 Eviction eviction_; // Handler of the eviction algorithm.
364 EntriesMap open_entries_; // Map of open entries.
365 int num_refs_; // Number of referenced cache entries.
366 int max_refs_; // Max number of referenced cache entries.
367 int num_pending_io_; // Number of pending IO operations.
368 int entry_count_; // Number of entries accessed lately.
369 int byte_count_; // Number of bytes read/written lately.
370 int buffer_bytes_; // Total size of the temporary entries' buffers.
371 int up_ticks_; // The number of timer ticks received (OnStatsTimer).
372 net::CacheType cache_type_;
373 int uma_report_; // Controls transmission of UMA data.
374 uint32 user_flags_; // Flags set by the user.
375 bool init_; // controls the initialization of the system.
376 bool restarted_;
377 bool unit_test_;
378 bool read_only_; // Prevents updates of the rankings data (used by tools).
379 bool disabled_;
380 bool new_eviction_; // What eviction algorithm should be used.
381 bool first_timer_; // True if the timer has not been called.
382 bool user_load_; // True if we see a high load coming from the caller.
384 net::NetLog* net_log_;
386 Stats stats_; // Usage statistics.
387 scoped_ptr<base::RepeatingTimer<BackendImpl> > timer_; // Usage timer.
388 base::WaitableEvent done_; // Signals the end of background work.
389 scoped_refptr<TraceObject> trace_object_; // Initializes internal tracing.
390 base::WeakPtrFactory<BackendImpl> ptr_factory_;
392 DISALLOW_COPY_AND_ASSIGN(BackendImpl);
395 // Returns the preferred max cache size given the available disk space.
396 NET_EXPORT_PRIVATE int PreferedCacheSize(int64 available);
398 } // namespace disk_cache
400 #endif // NET_DISK_CACHE_BACKEND_IMPL_H_