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

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568
  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. * <p>
  135. * The value for blockSize must be a power of 2.
  136. */
  137. private final int blockSize;
  138. /** As {@link #blockSize} is a power of 2, bits to shift for a / blockSize. */
  139. private final int blockSizeShift;
  140. /** Cache of pack files, indexed by description. */
  141. private final Map<DfsPackDescription, DfsPackFile> packCache;
  142. /** View of pack files in the pack cache. */
  143. private final Collection<DfsPackFile> packFiles;
  144. /** Number of times a block was found in the cache. */
  145. private final AtomicLong statHit;
  146. /** Number of times a block was not found, and had to be loaded. */
  147. private final AtomicLong statMiss;
  148. /** Number of blocks evicted due to cache being full. */
  149. private volatile long statEvict;
  150. /** Protects the clock and its related data. */
  151. private final ReentrantLock clockLock;
  152. /** Current position of the clock. */
  153. private Ref clockHand;
  154. /** Number of bytes currently loaded in the cache. */
  155. private volatile long liveBytes;
  156. @SuppressWarnings("unchecked")
  157. private DfsBlockCache(final DfsBlockCacheConfig cfg) {
  158. tableSize = tableSize(cfg);
  159. if (tableSize < 1)
  160. throw new IllegalArgumentException(JGitText.get().tSizeMustBeGreaterOrEqual1);
  161. table = new AtomicReferenceArray<HashEntry>(tableSize);
  162. loadLocks = new ReentrantLock[cfg.getConcurrencyLevel()];
  163. for (int i = 0; i < loadLocks.length; i++)
  164. loadLocks[i] = new ReentrantLock(true /* fair */);
  165. maxBytes = cfg.getBlockLimit();
  166. maxStreamThroughCache = (long) (maxBytes * cfg.getStreamRatio());
  167. blockSize = cfg.getBlockSize();
  168. blockSizeShift = Integer.numberOfTrailingZeros(blockSize);
  169. clockLock = new ReentrantLock(true /* fair */);
  170. clockHand = new Ref<Object>(new DfsPackKey(), -1, 0, null);
  171. clockHand.next = clockHand;
  172. packCache = new ConcurrentHashMap<DfsPackDescription, DfsPackFile>(
  173. 16, 0.75f, 1);
  174. packFiles = Collections.unmodifiableCollection(packCache.values());
  175. statHit = new AtomicLong();
  176. statMiss = new AtomicLong();
  177. }
  178. boolean shouldCopyThroughCache(long length) {
  179. return length <= maxStreamThroughCache;
  180. }
  181. /** @return total number of bytes in the cache. */
  182. public long getCurrentSize() {
  183. return liveBytes;
  184. }
  185. /** @return 0..100, defining how full the cache is. */
  186. public long getFillPercentage() {
  187. return getCurrentSize() * 100 / maxBytes;
  188. }
  189. /** @return number of requests for items in the cache. */
  190. public long getHitCount() {
  191. return statHit.get();
  192. }
  193. /** @return number of requests for items not in the cache. */
  194. public long getMissCount() {
  195. return statMiss.get();
  196. }
  197. /** @return total number of requests (hit + miss). */
  198. public long getTotalRequestCount() {
  199. return getHitCount() + getMissCount();
  200. }
  201. /** @return 0..100, defining number of cache hits. */
  202. public long getHitRatio() {
  203. long hits = statHit.get();
  204. long miss = statMiss.get();
  205. long total = hits + miss;
  206. if (total == 0)
  207. return 0;
  208. return hits * 100 / total;
  209. }
  210. /** @return number of evictions performed due to cache being full. */
  211. public long getEvictions() {
  212. return statEvict;
  213. }
  214. /**
  215. * Get the pack files stored in this cache.
  216. *
  217. * @return a collection of pack files, some of which may not actually be
  218. * present; the caller should check the pack's cached size.
  219. */
  220. public Collection<DfsPackFile> getPackFiles() {
  221. return packFiles;
  222. }
  223. DfsPackFile getOrCreate(DfsPackDescription dsc, DfsPackKey key) {
  224. // TODO This table grows without bound. It needs to clean up
  225. // entries that aren't in cache anymore, and aren't being used
  226. // by a live DfsObjDatabase reference.
  227. synchronized (packCache) {
  228. DfsPackFile pack = packCache.get(dsc);
  229. if (pack != null && pack.invalid()) {
  230. packCache.remove(dsc);
  231. pack = null;
  232. }
  233. if (pack == null) {
  234. if (key == null)
  235. key = new DfsPackKey();
  236. pack = new DfsPackFile(this, dsc, key);
  237. packCache.put(dsc, pack);
  238. }
  239. return pack;
  240. }
  241. }
  242. private int hash(int packHash, long off) {
  243. return packHash + (int) (off >>> blockSizeShift);
  244. }
  245. int getBlockSize() {
  246. return blockSize;
  247. }
  248. private static int tableSize(final DfsBlockCacheConfig cfg) {
  249. final int wsz = cfg.getBlockSize();
  250. final long limit = cfg.getBlockLimit();
  251. if (wsz <= 0)
  252. throw new IllegalArgumentException(JGitText.get().invalidWindowSize);
  253. if (limit < wsz)
  254. throw new IllegalArgumentException(JGitText.get().windowSizeMustBeLesserThanLimit);
  255. return (int) Math.min(5 * (limit / wsz) / 2, Integer.MAX_VALUE);
  256. }
  257. /**
  258. * Lookup a cached object, creating and loading it if it doesn't exist.
  259. *
  260. * @param pack
  261. * the pack that "contains" the cached object.
  262. * @param position
  263. * offset within <code>pack</code> of the object.
  264. * @param ctx
  265. * current thread's reader.
  266. * @return the object reference.
  267. * @throws IOException
  268. * the reference was not in the cache and could not be loaded.
  269. */
  270. DfsBlock getOrLoad(DfsPackFile pack, long position, DfsReader ctx)
  271. throws IOException {
  272. final long requestedPosition = position;
  273. position = pack.alignToBlock(position);
  274. DfsPackKey key = pack.key;
  275. int slot = slot(key, position);
  276. HashEntry e1 = table.get(slot);
  277. DfsBlock v = scan(e1, key, position);
  278. if (v != null) {
  279. statHit.incrementAndGet();
  280. return v;
  281. }
  282. reserveSpace(blockSize);
  283. ReentrantLock regionLock = lockFor(key, position);
  284. regionLock.lock();
  285. try {
  286. HashEntry e2 = table.get(slot);
  287. if (e2 != e1) {
  288. v = scan(e2, key, position);
  289. if (v != null) {
  290. statHit.incrementAndGet();
  291. creditSpace(blockSize);
  292. return v;
  293. }
  294. }
  295. statMiss.incrementAndGet();
  296. boolean credit = true;
  297. try {
  298. v = pack.readOneBlock(position, ctx);
  299. credit = false;
  300. } finally {
  301. if (credit)
  302. creditSpace(blockSize);
  303. }
  304. if (position != v.start) {
  305. // The file discovered its blockSize and adjusted.
  306. position = v.start;
  307. slot = slot(key, position);
  308. e2 = table.get(slot);
  309. }
  310. key.cachedSize.addAndGet(v.size());
  311. Ref<DfsBlock> ref = new Ref<DfsBlock>(key, position, v.size(), v);
  312. ref.hot = true;
  313. for (;;) {
  314. HashEntry n = new HashEntry(clean(e2), ref);
  315. if (table.compareAndSet(slot, e2, n))
  316. break;
  317. e2 = table.get(slot);
  318. }
  319. addToClock(ref, blockSize - v.size());
  320. } finally {
  321. regionLock.unlock();
  322. }
  323. // If the block size changed from the default, it is possible the block
  324. // that was loaded is the wrong block for the requested position.
  325. if (v.contains(pack.key, requestedPosition))
  326. return v;
  327. return getOrLoad(pack, requestedPosition, ctx);
  328. }
  329. @SuppressWarnings("unchecked")
  330. private void reserveSpace(int reserve) {
  331. clockLock.lock();
  332. try {
  333. long live = liveBytes + reserve;
  334. if (maxBytes < live) {
  335. Ref prev = clockHand;
  336. Ref hand = clockHand.next;
  337. do {
  338. if (hand.hot) {
  339. // Value was recently touched. Clear
  340. // hot and give it another chance.
  341. hand.hot = false;
  342. prev = hand;
  343. hand = hand.next;
  344. continue;
  345. } else if (prev == hand)
  346. break;
  347. // No recent access since last scan, kill
  348. // value and remove from clock.
  349. Ref dead = hand;
  350. hand = hand.next;
  351. prev.next = hand;
  352. dead.next = null;
  353. dead.value = null;
  354. live -= dead.size;
  355. dead.pack.cachedSize.addAndGet(-dead.size);
  356. statEvict++;
  357. } while (maxBytes < live);
  358. clockHand = prev;
  359. }
  360. liveBytes = live;
  361. } finally {
  362. clockLock.unlock();
  363. }
  364. }
  365. private void creditSpace(int credit) {
  366. clockLock.lock();
  367. liveBytes -= credit;
  368. clockLock.unlock();
  369. }
  370. @SuppressWarnings("unchecked")
  371. private void addToClock(Ref ref, int credit) {
  372. clockLock.lock();
  373. try {
  374. if (credit != 0)
  375. liveBytes -= credit;
  376. Ref ptr = clockHand;
  377. ref.next = ptr.next;
  378. ptr.next = ref;
  379. clockHand = ref;
  380. } finally {
  381. clockLock.unlock();
  382. }
  383. }
  384. void put(DfsBlock v) {
  385. put(v.pack, v.start, v.size(), v);
  386. }
  387. <T> Ref<T> put(DfsPackKey key, long pos, int size, T v) {
  388. int slot = slot(key, pos);
  389. HashEntry e1 = table.get(slot);
  390. Ref<T> ref = scanRef(e1, key, pos);
  391. if (ref != null)
  392. return ref;
  393. reserveSpace(size);
  394. ReentrantLock regionLock = lockFor(key, pos);
  395. regionLock.lock();
  396. try {
  397. HashEntry e2 = table.get(slot);
  398. if (e2 != e1) {
  399. ref = scanRef(e2, key, pos);
  400. if (ref != null) {
  401. creditSpace(size);
  402. return ref;
  403. }
  404. }
  405. key.cachedSize.addAndGet(size);
  406. ref = new Ref<T>(key, pos, size, v);
  407. ref.hot = true;
  408. for (;;) {
  409. HashEntry n = new HashEntry(clean(e2), ref);
  410. if (table.compareAndSet(slot, e2, n))
  411. break;
  412. e2 = table.get(slot);
  413. }
  414. addToClock(ref, 0);
  415. } finally {
  416. regionLock.unlock();
  417. }
  418. return ref;
  419. }
  420. boolean contains(DfsPackKey key, long position) {
  421. return scan(table.get(slot(key, position)), key, position) != null;
  422. }
  423. @SuppressWarnings("unchecked")
  424. <T> T get(DfsPackKey key, long position) {
  425. T val = (T) scan(table.get(slot(key, position)), key, position);
  426. if (val == null)
  427. statMiss.incrementAndGet();
  428. else
  429. statHit.incrementAndGet();
  430. return val;
  431. }
  432. private <T> T scan(HashEntry n, DfsPackKey pack, long position) {
  433. Ref<T> r = scanRef(n, pack, position);
  434. return r != null ? r.get() : null;
  435. }
  436. @SuppressWarnings("unchecked")
  437. private <T> Ref<T> scanRef(HashEntry n, DfsPackKey pack, long position) {
  438. for (; n != null; n = n.next) {
  439. Ref<T> r = n.ref;
  440. if (r.pack == pack && r.position == position)
  441. return r.get() != null ? r : null;
  442. }
  443. return null;
  444. }
  445. void remove(DfsPackFile pack) {
  446. synchronized (packCache) {
  447. packCache.remove(pack.getPackDescription());
  448. }
  449. }
  450. private int slot(DfsPackKey pack, long position) {
  451. return (hash(pack.hash, position) >>> 1) % tableSize;
  452. }
  453. private ReentrantLock lockFor(DfsPackKey pack, long position) {
  454. return loadLocks[(hash(pack.hash, position) >>> 1) % loadLocks.length];
  455. }
  456. private static HashEntry clean(HashEntry top) {
  457. while (top != null && top.ref.next == null)
  458. top = top.next;
  459. if (top == null)
  460. return null;
  461. HashEntry n = clean(top.next);
  462. return n == top.next ? top : new HashEntry(n, top.ref);
  463. }
  464. private static final class HashEntry {
  465. /** Next entry in the hash table's chain list. */
  466. final HashEntry next;
  467. /** The referenced object. */
  468. final Ref ref;
  469. HashEntry(HashEntry n, Ref r) {
  470. next = n;
  471. ref = r;
  472. }
  473. }
  474. static final class Ref<T> {
  475. final DfsPackKey pack;
  476. final long position;
  477. final int size;
  478. volatile T value;
  479. Ref next;
  480. volatile boolean hot;
  481. Ref(DfsPackKey pack, long position, int size, T v) {
  482. this.pack = pack;
  483. this.position = position;
  484. this.size = size;
  485. this.value = v;
  486. }
  487. T get() {
  488. T v = value;
  489. if (v != null)
  490. hot = true;
  491. return v;
  492. }
  493. boolean has() {
  494. return value != null;
  495. }
  496. }
  497. }