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 17KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577
  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.storage.dfs;
  45. import java.io.IOException;
  46. import java.util.ArrayList;
  47. import java.util.Collection;
  48. import java.util.Collections;
  49. import java.util.List;
  50. import java.util.Map;
  51. import java.util.concurrent.ConcurrentHashMap;
  52. import java.util.concurrent.ThreadPoolExecutor;
  53. import java.util.concurrent.atomic.AtomicLong;
  54. import java.util.concurrent.atomic.AtomicReferenceArray;
  55. import java.util.concurrent.locks.ReentrantLock;
  56. import org.eclipse.jgit.JGitText;
  57. /**
  58. * Caches slices of a {@link DfsPackFile} in memory for faster read access.
  59. * <p>
  60. * The DfsBlockCache serves as a Java based "buffer cache", loading segments of
  61. * a DfsPackFile into the JVM heap prior to use. As JGit often wants to do reads
  62. * of only tiny slices of a file, the DfsBlockCache tries to smooth out these
  63. * tiny reads into larger block-sized IO operations.
  64. * <p>
  65. * Whenever a cache miss occurs, loading is invoked by exactly one thread for
  66. * the given <code>(DfsPackKey,position)</code> key tuple. This is ensured by an
  67. * array of locks, with the tuple hashed to a lock instance.
  68. * <p>
  69. * Its too expensive during object access to be accurate with a least recently
  70. * used (LRU) algorithm. Strictly ordering every read is a lot of overhead that
  71. * typically doesn't yield a corresponding benefit to the application. This
  72. * cache implements a clock replacement algorithm, giving each block one chance
  73. * to have been accessed during a sweep of the cache to save itself from
  74. * eviction.
  75. * <p>
  76. * Entities created by the cache are held under hard references, preventing the
  77. * Java VM from clearing anything. Blocks are discarded by the replacement
  78. * algorithm when adding a new block would cause the cache to exceed its
  79. * configured maximum size.
  80. * <p>
  81. * The key tuple is passed through to methods as a pair of parameters rather
  82. * than as a single Object, thus reducing the transient memory allocations of
  83. * callers. It is more efficient to avoid the allocation, as we can't be 100%
  84. * sure that a JIT would be able to stack-allocate a key tuple.
  85. * <p>
  86. * The internal hash table does not expand at runtime, instead it is fixed in
  87. * size at cache creation time. The internal lock table used to gate load
  88. * invocations is also fixed in size.
  89. */
  90. public final class DfsBlockCache {
  91. private static volatile DfsBlockCache cache;
  92. static {
  93. reconfigure(new DfsBlockCacheConfig());
  94. }
  95. /**
  96. * Modify the configuration of the window cache.
  97. * <p>
  98. * The new configuration is applied immediately, and the existing cache is
  99. * cleared.
  100. *
  101. * @param cfg
  102. * the new window cache configuration.
  103. * @throws IllegalArgumentException
  104. * the cache configuration contains one or more invalid
  105. * settings, usually too low of a limit.
  106. */
  107. public static void reconfigure(DfsBlockCacheConfig cfg) {
  108. DfsBlockCache nc = new DfsBlockCache(cfg);
  109. DfsBlockCache oc = cache;
  110. cache = nc;
  111. if (oc != null && oc.readAheadService != null)
  112. oc.readAheadService.shutdown();
  113. }
  114. /** @return the currently active DfsBlockCache. */
  115. public static DfsBlockCache getInstance() {
  116. return cache;
  117. }
  118. /** Number of entries in {@link #table}. */
  119. private final int tableSize;
  120. /** Hash bucket directory; entries are chained below. */
  121. private final AtomicReferenceArray<HashEntry> table;
  122. /** Locks to prevent concurrent loads for same (PackFile,position). */
  123. private final ReentrantLock[] loadLocks;
  124. /** Maximum number of bytes the cache should hold. */
  125. private final long maxBytes;
  126. /**
  127. * Suggested block size to read from pack files in.
  128. * <p>
  129. * If a pack file does not have a native block size, this size will be used.
  130. * <p>
  131. * If a pack file has a native size, a whole multiple of the native size
  132. * will be used until it matches this size.
  133. */
  134. private final int blockSize;
  135. /** As {@link #blockSize} is a power of 2, bits to shift for a / blockSize. */
  136. private final int blockSizeShift;
  137. /** Number of bytes to read-ahead from current read position. */
  138. private final int readAheadLimit;
  139. /** Thread pool to handle optimistic read-ahead. */
  140. private final ThreadPoolExecutor readAheadService;
  141. /** Cache of pack files, indexed by description. */
  142. private final Map<DfsPackDescription, DfsPackFile> packCache;
  143. /** View of pack files in the pack cache. */
  144. private final Collection<DfsPackFile> packFiles;
  145. /** Number of times a block was found in the cache. */
  146. private final AtomicLong statHit;
  147. /** Number of times a block was not found, and had to be loaded. */
  148. private final AtomicLong statMiss;
  149. /** Number of blocks evicted due to cache being full. */
  150. private volatile long statEvict;
  151. /** Protects the clock and its related data. */
  152. private final ReentrantLock clockLock;
  153. /** Current position of the clock. */
  154. private Ref clockHand;
  155. /** Number of bytes currently loaded in the cache. */
  156. private volatile long liveBytes;
  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[32];
  163. for (int i = 0; i < loadLocks.length; i++)
  164. loadLocks[i] = new ReentrantLock(true /* fair */);
  165. int eb = (int) (tableSize * .1);
  166. if (64 < eb)
  167. eb = 64;
  168. else if (eb < 4)
  169. eb = 4;
  170. if (tableSize < eb)
  171. eb = tableSize;
  172. maxBytes = cfg.getBlockLimit();
  173. blockSize = cfg.getBlockSize();
  174. blockSizeShift = Integer.numberOfTrailingZeros(blockSize);
  175. clockLock = new ReentrantLock(true /* fair */);
  176. clockHand = new Ref<Object>(null, -1, 0, null);
  177. clockHand.next = clockHand;
  178. readAheadLimit = cfg.getReadAheadLimit();
  179. readAheadService = cfg.getReadAheadService();
  180. packCache = new ConcurrentHashMap<DfsPackDescription, DfsPackFile>(
  181. 16, 0.75f, 1);
  182. packFiles = Collections.unmodifiableCollection(packCache.values());
  183. statHit = new AtomicLong();
  184. statMiss = new AtomicLong();
  185. }
  186. /** @return total number of bytes in the cache. */
  187. public long getCurrentSize() {
  188. return liveBytes;
  189. }
  190. /** @return 0..100, defining how full the cache is. */
  191. public long getFillPercentage() {
  192. return getCurrentSize() * 100 / maxBytes;
  193. }
  194. /** @return 0..100, defining number of cache hits. */
  195. public long getHitRatio() {
  196. long hits = statHit.get();
  197. long miss = statMiss.get();
  198. long total = hits + miss;
  199. if (total == 0)
  200. return 0;
  201. return hits * 100 / total;
  202. }
  203. /** @return number of evictions performed due to cache being full. */
  204. public long getEvictions() {
  205. return statEvict;
  206. }
  207. /**
  208. * Get the pack files stored in this cache.
  209. *
  210. * @return a collection of pack files, some of which may not actually be
  211. * present; the caller should check the pack's cached size.
  212. */
  213. public Collection<DfsPackFile> getPackFiles() {
  214. return packFiles;
  215. }
  216. DfsPackFile getOrCreate(DfsPackDescription dsc, DfsPackKey key) {
  217. // TODO This table grows without bound. It needs to clean up
  218. // entries that aren't in cache anymore, and aren't being used
  219. // by a live DfsObjDatabase reference.
  220. synchronized (packCache) {
  221. DfsPackFile pack = packCache.get(dsc);
  222. if (pack != null && pack.invalid()) {
  223. packCache.remove(dsc);
  224. pack = null;
  225. }
  226. if (pack == null) {
  227. if (key == null)
  228. key = new DfsPackKey();
  229. pack = new DfsPackFile(this, dsc, key);
  230. packCache.put(dsc, pack);
  231. }
  232. return pack;
  233. }
  234. }
  235. private int hash(int packHash, long off) {
  236. return packHash + (int) (off >>> blockSizeShift);
  237. }
  238. int getBlockSize() {
  239. return blockSize;
  240. }
  241. private static int tableSize(final DfsBlockCacheConfig cfg) {
  242. final int wsz = cfg.getBlockSize();
  243. final long limit = cfg.getBlockLimit();
  244. if (wsz <= 0)
  245. throw new IllegalArgumentException(JGitText.get().invalidWindowSize);
  246. if (limit < wsz)
  247. throw new IllegalArgumentException(JGitText.get().windowSizeMustBeLesserThanLimit);
  248. return (int) Math.min(5 * (limit / wsz) / 2, Integer.MAX_VALUE);
  249. }
  250. /**
  251. * Lookup a cached object, creating and loading it if it doesn't exist.
  252. *
  253. * @param pack
  254. * the pack that "contains" the cached object.
  255. * @param position
  256. * offset within <code>pack</code> of the object.
  257. * @param ctx
  258. * current thread's reader.
  259. * @return the object reference.
  260. * @throws IOException
  261. * the reference was not in the cache and could not be loaded.
  262. */
  263. DfsBlock getOrLoad(DfsPackFile pack, long position, DfsReader ctx)
  264. throws IOException {
  265. final long requestedPosition = position;
  266. position = pack.alignToBlock(position);
  267. DfsPackKey key = pack.key;
  268. int slot = slot(key, position);
  269. HashEntry e1 = table.get(slot);
  270. DfsBlock v = scan(e1, key, position);
  271. if (v != null)
  272. return v;
  273. reserveSpace(blockSize);
  274. ReentrantLock regionLock = lockFor(key, position);
  275. regionLock.lock();
  276. try {
  277. HashEntry e2 = table.get(slot);
  278. if (e2 != e1) {
  279. v = scan(e2, key, position);
  280. if (v != null) {
  281. creditSpace(blockSize);
  282. return v;
  283. }
  284. }
  285. statMiss.incrementAndGet();
  286. boolean credit = true;
  287. try {
  288. v = pack.readOneBlock(position, ctx);
  289. credit = false;
  290. } finally {
  291. if (credit)
  292. creditSpace(blockSize);
  293. }
  294. if (position != v.start) {
  295. // The file discovered its blockSize and adjusted.
  296. position = v.start;
  297. slot = slot(key, position);
  298. e2 = table.get(slot);
  299. }
  300. Ref<DfsBlock> ref = new Ref<DfsBlock>(key, position, v.size(), v);
  301. ref.hot = true;
  302. for (;;) {
  303. HashEntry n = new HashEntry(clean(e2), ref);
  304. if (table.compareAndSet(slot, e2, n))
  305. break;
  306. e2 = table.get(slot);
  307. }
  308. addToClock(ref, blockSize - v.size());
  309. } finally {
  310. regionLock.unlock();
  311. }
  312. // If the block size changed from the default, it is possible the block
  313. // that was loaded is the wrong block for the requested position.
  314. if (v.contains(pack.key, requestedPosition))
  315. return v;
  316. return getOrLoad(pack, requestedPosition, ctx);
  317. }
  318. @SuppressWarnings("unchecked")
  319. private void reserveSpace(int reserve) {
  320. clockLock.lock();
  321. long live = liveBytes + reserve;
  322. if (maxBytes < live) {
  323. Ref prev = clockHand;
  324. Ref hand = clockHand.next;
  325. do {
  326. if (hand.hot) {
  327. // Value was recently touched. Clear
  328. // hot and give it another chance.
  329. hand.hot = false;
  330. prev = hand;
  331. hand = hand.next;
  332. continue;
  333. } else if (prev == hand)
  334. break;
  335. // No recent access since last scan, kill
  336. // value and remove from clock.
  337. Ref dead = hand;
  338. hand = hand.next;
  339. prev.next = hand;
  340. dead.next = null;
  341. dead.value = null;
  342. live -= dead.size;
  343. statEvict++;
  344. } while (maxBytes < live);
  345. clockHand = prev;
  346. }
  347. liveBytes = live;
  348. clockLock.unlock();
  349. }
  350. private void creditSpace(int credit) {
  351. clockLock.lock();
  352. liveBytes -= credit;
  353. clockLock.unlock();
  354. }
  355. private void addToClock(Ref ref, int credit) {
  356. clockLock.lock();
  357. if (credit != 0)
  358. liveBytes -= credit;
  359. Ref ptr = clockHand;
  360. ref.next = ptr.next;
  361. ptr.next = ref;
  362. clockHand = ref;
  363. clockLock.unlock();
  364. }
  365. void put(DfsBlock v) {
  366. put(v.pack, v.start, v.size(), v);
  367. }
  368. <T> Ref<T> put(DfsPackKey key, long pos, int size, T v) {
  369. int slot = slot(key, pos);
  370. HashEntry e1 = table.get(slot);
  371. Ref<T> ref = scanRef(e1, key, pos);
  372. if (ref != null)
  373. return ref;
  374. reserveSpace(size);
  375. ReentrantLock regionLock = lockFor(key, pos);
  376. regionLock.lock();
  377. try {
  378. HashEntry e2 = table.get(slot);
  379. if (e2 != e1) {
  380. ref = scanRef(e2, key, pos);
  381. if (ref != null) {
  382. creditSpace(size);
  383. return ref;
  384. }
  385. }
  386. ref = new Ref<T>(key, pos, size, v);
  387. ref.hot = true;
  388. for (;;) {
  389. HashEntry n = new HashEntry(clean(e2), ref);
  390. if (table.compareAndSet(slot, e2, n))
  391. break;
  392. e2 = table.get(slot);
  393. }
  394. addToClock(ref, 0);
  395. } finally {
  396. regionLock.unlock();
  397. }
  398. return ref;
  399. }
  400. boolean contains(DfsPackKey key, long position) {
  401. return scan(table.get(slot(key, position)), key, position) != null;
  402. }
  403. @SuppressWarnings("unchecked")
  404. <T> T get(DfsPackKey key, long position) {
  405. T val = (T) scan(table.get(slot(key, position)), key, position);
  406. if (val == null)
  407. statMiss.incrementAndGet();
  408. return val;
  409. }
  410. boolean readAhead(ReadableChannel rc, DfsPackKey key, int size, long pos,
  411. long len, DfsReader ctx) {
  412. if (!ctx.wantReadAhead() || readAheadLimit <= 0 || readAheadService == null)
  413. return false;
  414. int cap = readAheadLimit / size;
  415. long readAheadEnd = pos + readAheadLimit;
  416. List<ReadAheadTask.BlockFuture> blocks = new ArrayList<ReadAheadTask.BlockFuture>(cap);
  417. while (pos < readAheadEnd && pos < len) {
  418. long end = Math.min(pos + size, len);
  419. if (!contains(key, pos))
  420. blocks.add(new ReadAheadTask.BlockFuture(key, pos, end));
  421. pos = end;
  422. }
  423. if (blocks.isEmpty())
  424. return false;
  425. ReadAheadTask task = new ReadAheadTask(this, rc, blocks);
  426. ReadAheadTask.TaskFuture t = new ReadAheadTask.TaskFuture(task);
  427. for (ReadAheadTask.BlockFuture b : blocks)
  428. b.setTask(t);
  429. readAheadService.execute(t);
  430. ctx.startedReadAhead(blocks);
  431. return true;
  432. }
  433. @SuppressWarnings("unchecked")
  434. private <T> T scan(HashEntry n, DfsPackKey pack, long position) {
  435. for (; n != null; n = n.next) {
  436. Ref<T> r = n.ref;
  437. if (r.pack != pack || r.position != position)
  438. continue;
  439. T v = r.get();
  440. if (v == null)
  441. return null;
  442. statHit.incrementAndGet();
  443. return v;
  444. }
  445. return null;
  446. }
  447. @SuppressWarnings("unchecked")
  448. private <T> Ref<T> scanRef(HashEntry n, DfsPackKey pack, long position) {
  449. for (; n != null; n = n.next) {
  450. Ref<T> r = n.ref;
  451. if (r.pack == pack && r.position == position)
  452. return r.get() != null ? r : null;
  453. }
  454. return null;
  455. }
  456. void remove(DfsPackFile pack) {
  457. synchronized (packCache) {
  458. packCache.remove(pack.getPackDescription());
  459. }
  460. }
  461. private int slot(DfsPackKey pack, long position) {
  462. return (hash(pack.hash, position) >>> 1) % tableSize;
  463. }
  464. private ReentrantLock lockFor(DfsPackKey pack, long position) {
  465. return loadLocks[(hash(pack.hash, position) >>> 1) % loadLocks.length];
  466. }
  467. private static HashEntry clean(HashEntry top) {
  468. while (top != null && top.ref.next == null)
  469. top = top.next;
  470. if (top == null)
  471. return null;
  472. HashEntry n = clean(top.next);
  473. return n == top.next ? top : new HashEntry(n, top.ref);
  474. }
  475. private static final class HashEntry {
  476. /** Next entry in the hash table's chain list. */
  477. final HashEntry next;
  478. /** The referenced object. */
  479. final Ref ref;
  480. HashEntry(HashEntry n, Ref r) {
  481. next = n;
  482. ref = r;
  483. }
  484. }
  485. static final class Ref<T> {
  486. final DfsPackKey pack;
  487. final long position;
  488. final int size;
  489. volatile T value;
  490. Ref next;
  491. volatile boolean hot;
  492. Ref(DfsPackKey pack, long position, int size, T v) {
  493. this.pack = pack;
  494. this.position = position;
  495. this.size = size;
  496. this.value = v;
  497. }
  498. T get() {
  499. T v = value;
  500. if (v != null)
  501. hot = true;
  502. return v;
  503. }
  504. }
  505. }