You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

DfsBlockCache.java 16KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564
  1. /*
  2. * Copyright (C) 2008-2011, Google Inc.
  3. * Copyright (C) 2008, Shawn O. Pearce <spearce@spearce.org>
  4. * and other copyright owners as documented in the project's IP log.
  5. *
  6. * This program and the accompanying materials are made available
  7. * under the terms of the Eclipse Distribution License v1.0 which
  8. * accompanies this distribution, is reproduced below, and is
  9. * available at http://www.eclipse.org/org/documents/edl-v10.php
  10. *
  11. * All rights reserved.
  12. *
  13. * Redistribution and use in source and binary forms, with or
  14. * without modification, are permitted provided that the following
  15. * conditions are met:
  16. *
  17. * - Redistributions of source code must retain the above copyright
  18. * notice, this list of conditions and the following disclaimer.
  19. *
  20. * - Redistributions in binary form must reproduce the above
  21. * copyright notice, this list of conditions and the following
  22. * disclaimer in the documentation and/or other materials provided
  23. * with the distribution.
  24. *
  25. * - Neither the name of the Eclipse Foundation, Inc. nor the
  26. * names of its contributors may be used to endorse or promote
  27. * products derived from this software without specific prior
  28. * written permission.
  29. *
  30. * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND
  31. * CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES,
  32. * INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
  33. * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
  34. * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR
  35. * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
  36. * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
  37. * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
  38. * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
  39. * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT,
  40. * STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
  41. * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF
  42. * ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
  43. */
  44. package org.eclipse.jgit.internal.storage.dfs;
  45. import java.io.IOException;
  46. import java.util.Collection;
  47. import java.util.Collections;
  48. import java.util.Map;
  49. import java.util.concurrent.ConcurrentHashMap;
  50. import java.util.concurrent.atomic.AtomicLong;
  51. import java.util.concurrent.atomic.AtomicReferenceArray;
  52. import java.util.concurrent.locks.ReentrantLock;
  53. import org.eclipse.jgit.internal.JGitText;
  54. /**
  55. * Caches slices of a {@link DfsPackFile} in memory for faster read access.
  56. * <p>
  57. * The DfsBlockCache serves as a Java based "buffer cache", loading segments of
  58. * a DfsPackFile into the JVM heap prior to use. As JGit often wants to do reads
  59. * of only tiny slices of a file, the DfsBlockCache tries to smooth out these
  60. * tiny reads into larger block-sized IO operations.
  61. * <p>
  62. * Whenever a cache miss occurs, loading is invoked by exactly one thread for
  63. * the given <code>(DfsPackKey,position)</code> key tuple. This is ensured by an
  64. * array of locks, with the tuple hashed to a lock instance.
  65. * <p>
  66. * Its too expensive during object access to be accurate with a least recently
  67. * used (LRU) algorithm. Strictly ordering every read is a lot of overhead that
  68. * typically doesn't yield a corresponding benefit to the application. This
  69. * cache implements a clock replacement algorithm, giving each block one chance
  70. * to have been accessed during a sweep of the cache to save itself from
  71. * eviction.
  72. * <p>
  73. * Entities created by the cache are held under hard references, preventing the
  74. * Java VM from clearing anything. Blocks are discarded by the replacement
  75. * algorithm when adding a new block would cause the cache to exceed its
  76. * configured maximum size.
  77. * <p>
  78. * The key tuple is passed through to methods as a pair of parameters rather
  79. * than as a single Object, thus reducing the transient memory allocations of
  80. * callers. It is more efficient to avoid the allocation, as we can't be 100%
  81. * sure that a JIT would be able to stack-allocate a key tuple.
  82. * <p>
  83. * The internal hash table does not expand at runtime, instead it is fixed in
  84. * size at cache creation time. The internal lock table used to gate load
  85. * invocations is also fixed in size.
  86. */
  87. public final class DfsBlockCache {
  88. private static volatile DfsBlockCache cache;
  89. static {
  90. reconfigure(new DfsBlockCacheConfig());
  91. }
  92. /**
  93. * Modify the configuration of the window cache.
  94. * <p>
  95. * The new configuration is applied immediately, and the existing cache is
  96. * cleared.
  97. *
  98. * @param cfg
  99. * the new window cache configuration.
  100. * @throws IllegalArgumentException
  101. * the cache configuration contains one or more invalid
  102. * settings, usually too low of a limit.
  103. */
  104. public static void reconfigure(DfsBlockCacheConfig cfg) {
  105. DfsBlockCache nc = new DfsBlockCache(cfg);
  106. DfsBlockCache oc = cache;
  107. cache = nc;
  108. if (oc != null) {
  109. for (DfsPackFile pack : oc.getPackFiles())
  110. pack.key.cachedSize.set(0);
  111. }
  112. }
  113. /** @return the currently active DfsBlockCache. */
  114. public static DfsBlockCache getInstance() {
  115. return cache;
  116. }
  117. /** Number of entries in {@link #table}. */
  118. private final int tableSize;
  119. /** Hash bucket directory; entries are chained below. */
  120. private final AtomicReferenceArray<HashEntry> table;
  121. /** Locks to prevent concurrent loads for same (PackFile,position). */
  122. private final ReentrantLock[] loadLocks;
  123. /** Maximum number of bytes the cache should hold. */
  124. private final long maxBytes;
  125. /** Pack files smaller than this size can be copied through the cache. */
  126. private final long maxStreamThroughCache;
  127. /**
  128. * Suggested block size to read from pack files in.
  129. * <p>
  130. * If a pack file does not have a native block size, this size will be used.
  131. * <p>
  132. * If a pack file has a native size, a whole multiple of the native size
  133. * will be used until it matches this size.
  134. */
  135. private final int blockSize;
  136. /** As {@link #blockSize} is a power of 2, bits to shift for a / blockSize. */
  137. private final int blockSizeShift;
  138. /** Cache of pack files, indexed by description. */
  139. private final Map<DfsPackDescription, DfsPackFile> packCache;
  140. /** View of pack files in the pack cache. */
  141. private final Collection<DfsPackFile> packFiles;
  142. /** Number of times a block was found in the cache. */
  143. private final AtomicLong statHit;
  144. /** Number of times a block was not found, and had to be loaded. */
  145. private final AtomicLong statMiss;
  146. /** Number of blocks evicted due to cache being full. */
  147. private volatile long statEvict;
  148. /** Protects the clock and its related data. */
  149. private final ReentrantLock clockLock;
  150. /** Current position of the clock. */
  151. private Ref clockHand;
  152. /** Number of bytes currently loaded in the cache. */
  153. private volatile long liveBytes;
  154. private DfsBlockCache(final DfsBlockCacheConfig cfg) {
  155. tableSize = tableSize(cfg);
  156. if (tableSize < 1)
  157. throw new IllegalArgumentException(JGitText.get().tSizeMustBeGreaterOrEqual1);
  158. table = new AtomicReferenceArray<HashEntry>(tableSize);
  159. loadLocks = new ReentrantLock[32];
  160. for (int i = 0; i < loadLocks.length; i++)
  161. loadLocks[i] = new ReentrantLock(true /* fair */);
  162. maxBytes = cfg.getBlockLimit();
  163. maxStreamThroughCache = (long) (maxBytes * cfg.getStreamRatio());
  164. blockSize = cfg.getBlockSize();
  165. blockSizeShift = Integer.numberOfTrailingZeros(blockSize);
  166. clockLock = new ReentrantLock(true /* fair */);
  167. clockHand = new Ref<Object>(new DfsPackKey(), -1, 0, null);
  168. clockHand.next = clockHand;
  169. packCache = new ConcurrentHashMap<DfsPackDescription, DfsPackFile>(
  170. 16, 0.75f, 1);
  171. packFiles = Collections.unmodifiableCollection(packCache.values());
  172. statHit = new AtomicLong();
  173. statMiss = new AtomicLong();
  174. }
  175. boolean shouldCopyThroughCache(long length) {
  176. return length <= maxStreamThroughCache;
  177. }
  178. /** @return total number of bytes in the cache. */
  179. public long getCurrentSize() {
  180. return liveBytes;
  181. }
  182. /** @return 0..100, defining how full the cache is. */
  183. public long getFillPercentage() {
  184. return getCurrentSize() * 100 / maxBytes;
  185. }
  186. /** @return number of requests for items in the cache. */
  187. public long getHitCount() {
  188. return statHit.get();
  189. }
  190. /** @return number of requests for items not in the cache. */
  191. public long getMissCount() {
  192. return statMiss.get();
  193. }
  194. /** @return total number of requests (hit + miss). */
  195. public long getTotalRequestCount() {
  196. return getHitCount() + getMissCount();
  197. }
  198. /** @return 0..100, defining number of cache hits. */
  199. public long getHitRatio() {
  200. long hits = statHit.get();
  201. long miss = statMiss.get();
  202. long total = hits + miss;
  203. if (total == 0)
  204. return 0;
  205. return hits * 100 / total;
  206. }
  207. /** @return number of evictions performed due to cache being full. */
  208. public long getEvictions() {
  209. return statEvict;
  210. }
  211. /**
  212. * Get the pack files stored in this cache.
  213. *
  214. * @return a collection of pack files, some of which may not actually be
  215. * present; the caller should check the pack's cached size.
  216. */
  217. public Collection<DfsPackFile> getPackFiles() {
  218. return packFiles;
  219. }
  220. DfsPackFile getOrCreate(DfsPackDescription dsc, DfsPackKey key) {
  221. // TODO This table grows without bound. It needs to clean up
  222. // entries that aren't in cache anymore, and aren't being used
  223. // by a live DfsObjDatabase reference.
  224. synchronized (packCache) {
  225. DfsPackFile pack = packCache.get(dsc);
  226. if (pack != null && pack.invalid()) {
  227. packCache.remove(dsc);
  228. pack = null;
  229. }
  230. if (pack == null) {
  231. if (key == null)
  232. key = new DfsPackKey();
  233. pack = new DfsPackFile(this, dsc, key);
  234. packCache.put(dsc, pack);
  235. }
  236. return pack;
  237. }
  238. }
  239. private int hash(int packHash, long off) {
  240. return packHash + (int) (off >>> blockSizeShift);
  241. }
  242. int getBlockSize() {
  243. return blockSize;
  244. }
  245. private static int tableSize(final DfsBlockCacheConfig cfg) {
  246. final int wsz = cfg.getBlockSize();
  247. final long limit = cfg.getBlockLimit();
  248. if (wsz <= 0)
  249. throw new IllegalArgumentException(JGitText.get().invalidWindowSize);
  250. if (limit < wsz)
  251. throw new IllegalArgumentException(JGitText.get().windowSizeMustBeLesserThanLimit);
  252. return (int) Math.min(5 * (limit / wsz) / 2, Integer.MAX_VALUE);
  253. }
  254. /**
  255. * Lookup a cached object, creating and loading it if it doesn't exist.
  256. *
  257. * @param pack
  258. * the pack that "contains" the cached object.
  259. * @param position
  260. * offset within <code>pack</code> of the object.
  261. * @param ctx
  262. * current thread's reader.
  263. * @return the object reference.
  264. * @throws IOException
  265. * the reference was not in the cache and could not be loaded.
  266. */
  267. DfsBlock getOrLoad(DfsPackFile pack, long position, DfsReader ctx)
  268. throws IOException {
  269. final long requestedPosition = position;
  270. position = pack.alignToBlock(position);
  271. DfsPackKey key = pack.key;
  272. int slot = slot(key, position);
  273. HashEntry e1 = table.get(slot);
  274. DfsBlock v = scan(e1, key, position);
  275. if (v != null) {
  276. statHit.incrementAndGet();
  277. return v;
  278. }
  279. reserveSpace(blockSize);
  280. ReentrantLock regionLock = lockFor(key, position);
  281. regionLock.lock();
  282. try {
  283. HashEntry e2 = table.get(slot);
  284. if (e2 != e1) {
  285. v = scan(e2, key, position);
  286. if (v != null) {
  287. statHit.incrementAndGet();
  288. creditSpace(blockSize);
  289. return v;
  290. }
  291. }
  292. statMiss.incrementAndGet();
  293. boolean credit = true;
  294. try {
  295. v = pack.readOneBlock(position, ctx);
  296. credit = false;
  297. } finally {
  298. if (credit)
  299. creditSpace(blockSize);
  300. }
  301. if (position != v.start) {
  302. // The file discovered its blockSize and adjusted.
  303. position = v.start;
  304. slot = slot(key, position);
  305. e2 = table.get(slot);
  306. }
  307. key.cachedSize.addAndGet(v.size());
  308. Ref<DfsBlock> ref = new Ref<DfsBlock>(key, position, v.size(), v);
  309. ref.hot = true;
  310. for (;;) {
  311. HashEntry n = new HashEntry(clean(e2), ref);
  312. if (table.compareAndSet(slot, e2, n))
  313. break;
  314. e2 = table.get(slot);
  315. }
  316. addToClock(ref, blockSize - v.size());
  317. } finally {
  318. regionLock.unlock();
  319. }
  320. // If the block size changed from the default, it is possible the block
  321. // that was loaded is the wrong block for the requested position.
  322. if (v.contains(pack.key, requestedPosition))
  323. return v;
  324. return getOrLoad(pack, requestedPosition, ctx);
  325. }
  326. @SuppressWarnings("unchecked")
  327. private void reserveSpace(int reserve) {
  328. clockLock.lock();
  329. try {
  330. long live = liveBytes + reserve;
  331. if (maxBytes < live) {
  332. Ref prev = clockHand;
  333. Ref hand = clockHand.next;
  334. do {
  335. if (hand.hot) {
  336. // Value was recently touched. Clear
  337. // hot and give it another chance.
  338. hand.hot = false;
  339. prev = hand;
  340. hand = hand.next;
  341. continue;
  342. } else if (prev == hand)
  343. break;
  344. // No recent access since last scan, kill
  345. // value and remove from clock.
  346. Ref dead = hand;
  347. hand = hand.next;
  348. prev.next = hand;
  349. dead.next = null;
  350. dead.value = null;
  351. live -= dead.size;
  352. dead.pack.cachedSize.addAndGet(-dead.size);
  353. statEvict++;
  354. } while (maxBytes < live);
  355. clockHand = prev;
  356. }
  357. liveBytes = live;
  358. } finally {
  359. clockLock.unlock();
  360. }
  361. }
  362. private void creditSpace(int credit) {
  363. clockLock.lock();
  364. liveBytes -= credit;
  365. clockLock.unlock();
  366. }
  367. private void addToClock(Ref ref, int credit) {
  368. clockLock.lock();
  369. try {
  370. if (credit != 0)
  371. liveBytes -= credit;
  372. Ref ptr = clockHand;
  373. ref.next = ptr.next;
  374. ptr.next = ref;
  375. clockHand = ref;
  376. } finally {
  377. clockLock.unlock();
  378. }
  379. }
  380. void put(DfsBlock v) {
  381. put(v.pack, v.start, v.size(), v);
  382. }
  383. <T> Ref<T> put(DfsPackKey key, long pos, int size, T v) {
  384. int slot = slot(key, pos);
  385. HashEntry e1 = table.get(slot);
  386. Ref<T> ref = scanRef(e1, key, pos);
  387. if (ref != null)
  388. return ref;
  389. reserveSpace(size);
  390. ReentrantLock regionLock = lockFor(key, pos);
  391. regionLock.lock();
  392. try {
  393. HashEntry e2 = table.get(slot);
  394. if (e2 != e1) {
  395. ref = scanRef(e2, key, pos);
  396. if (ref != null) {
  397. creditSpace(size);
  398. return ref;
  399. }
  400. }
  401. key.cachedSize.addAndGet(size);
  402. ref = new Ref<T>(key, pos, size, v);
  403. ref.hot = true;
  404. for (;;) {
  405. HashEntry n = new HashEntry(clean(e2), ref);
  406. if (table.compareAndSet(slot, e2, n))
  407. break;
  408. e2 = table.get(slot);
  409. }
  410. addToClock(ref, 0);
  411. } finally {
  412. regionLock.unlock();
  413. }
  414. return ref;
  415. }
  416. boolean contains(DfsPackKey key, long position) {
  417. return scan(table.get(slot(key, position)), key, position) != null;
  418. }
  419. @SuppressWarnings("unchecked")
  420. <T> T get(DfsPackKey key, long position) {
  421. T val = (T) scan(table.get(slot(key, position)), key, position);
  422. if (val == null)
  423. statMiss.incrementAndGet();
  424. else
  425. statHit.incrementAndGet();
  426. return val;
  427. }
  428. private <T> T scan(HashEntry n, DfsPackKey pack, long position) {
  429. Ref<T> r = scanRef(n, pack, position);
  430. return r != null ? r.get() : null;
  431. }
  432. @SuppressWarnings("unchecked")
  433. private <T> Ref<T> scanRef(HashEntry n, DfsPackKey pack, long position) {
  434. for (; n != null; n = n.next) {
  435. Ref<T> r = n.ref;
  436. if (r.pack == pack && r.position == position)
  437. return r.get() != null ? r : null;
  438. }
  439. return null;
  440. }
  441. void remove(DfsPackFile pack) {
  442. synchronized (packCache) {
  443. packCache.remove(pack.getPackDescription());
  444. }
  445. }
  446. private int slot(DfsPackKey pack, long position) {
  447. return (hash(pack.hash, position) >>> 1) % tableSize;
  448. }
  449. private ReentrantLock lockFor(DfsPackKey pack, long position) {
  450. return loadLocks[(hash(pack.hash, position) >>> 1) % loadLocks.length];
  451. }
  452. private static HashEntry clean(HashEntry top) {
  453. while (top != null && top.ref.next == null)
  454. top = top.next;
  455. if (top == null)
  456. return null;
  457. HashEntry n = clean(top.next);
  458. return n == top.next ? top : new HashEntry(n, top.ref);
  459. }
  460. private static final class HashEntry {
  461. /** Next entry in the hash table's chain list. */
  462. final HashEntry next;
  463. /** The referenced object. */
  464. final Ref ref;
  465. HashEntry(HashEntry n, Ref r) {
  466. next = n;
  467. ref = r;
  468. }
  469. }
  470. static final class Ref<T> {
  471. final DfsPackKey pack;
  472. final long position;
  473. final int size;
  474. volatile T value;
  475. Ref next;
  476. volatile boolean hot;
  477. Ref(DfsPackKey pack, long position, int size, T v) {
  478. this.pack = pack;
  479. this.position = position;
  480. this.size = size;
  481. this.value = v;
  482. }
  483. T get() {
  484. T v = value;
  485. if (v != null)
  486. hot = true;
  487. return v;
  488. }
  489. boolean has() {
  490. return value != null;
  491. }
  492. }
  493. }