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