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.

UsageMap.java 35KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120
  1. /*
  2. Copyright (c) 2005 Health Market Science, Inc.
  3. Licensed under the Apache License, Version 2.0 (the "License");
  4. you may not use this file except in compliance with the License.
  5. You may obtain a copy of the License at
  6. http://www.apache.org/licenses/LICENSE-2.0
  7. Unless required by applicable law or agreed to in writing, software
  8. distributed under the License is distributed on an "AS IS" BASIS,
  9. WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  10. See the License for the specific language governing permissions and
  11. limitations under the License.
  12. */
  13. package com.healthmarketscience.jackcess.impl;
  14. import java.io.IOException;
  15. import java.nio.ByteBuffer;
  16. import java.util.ArrayList;
  17. import java.util.BitSet;
  18. import java.util.List;
  19. /**
  20. * Describes which database pages a particular table uses
  21. * @author Tim McCune
  22. */
  23. public class UsageMap
  24. {
  25. /** Inline map type */
  26. public static final byte MAP_TYPE_INLINE = 0x0;
  27. /** Reference map type, for maps that are too large to fit inline */
  28. public static final byte MAP_TYPE_REFERENCE = 0x1;
  29. /** bit index value for an invalid page number */
  30. private static final int INVALID_BIT_INDEX = -1;
  31. /** owning database */
  32. private final DatabaseImpl _database;
  33. /** Page number of the map table declaration */
  34. private final int _tablePageNum;
  35. /** Offset of the data page at which the usage map data starts */
  36. private int _startOffset;
  37. /** Offset of the data page at which the usage map declaration starts */
  38. private final short _rowStart;
  39. /** First page that this usage map applies to */
  40. private int _startPage;
  41. /** Last page that this usage map applies to */
  42. private int _endPage;
  43. /** bits representing page numbers used, offset from _startPage */
  44. private BitSet _pageNumbers = new BitSet();
  45. /** Buffer that contains the usage map table declaration page */
  46. private final ByteBuffer _tableBuffer;
  47. /** modification count on the usage map, used to keep the cursors in
  48. sync */
  49. private int _modCount;
  50. /** the current handler implementation for reading/writing the specific
  51. usage map type. note, this may change over time. */
  52. private Handler _handler;
  53. /** Error message prefix used when map type is unrecognized. */
  54. static final String MSG_PREFIX_UNRECOGNIZED_MAP = "Unrecognized map type: ";
  55. /**
  56. * @param database database that contains this usage map
  57. * @param tableBuffer Buffer that contains this map's declaration
  58. * @param pageNum Page number that this usage map is contained in
  59. * @param rowStart Offset at which the declaration starts in the buffer
  60. */
  61. private UsageMap(DatabaseImpl database, ByteBuffer tableBuffer,
  62. int pageNum, short rowStart)
  63. throws IOException
  64. {
  65. _database = database;
  66. _tableBuffer = tableBuffer;
  67. _tablePageNum = pageNum;
  68. _rowStart = rowStart;
  69. _tableBuffer.position(_rowStart + getFormat().OFFSET_USAGE_MAP_START);
  70. _startOffset = _tableBuffer.position();
  71. }
  72. public DatabaseImpl getDatabase() {
  73. return _database;
  74. }
  75. public JetFormat getFormat() {
  76. return getDatabase().getFormat();
  77. }
  78. public PageChannel getPageChannel() {
  79. return getDatabase().getPageChannel();
  80. }
  81. /**
  82. * @param database database that contains this usage map
  83. * @param buf buffer which contains the usage map row info
  84. * @return Either an InlineUsageMap or a ReferenceUsageMap, depending on
  85. * which type of map is found
  86. */
  87. public static UsageMap read(DatabaseImpl database, ByteBuffer buf)
  88. throws IOException
  89. {
  90. int umapRowNum = buf.get();
  91. int umapPageNum = ByteUtil.get3ByteInt(buf);
  92. return read(database, umapPageNum, umapRowNum, false);
  93. }
  94. /**
  95. * @param database database that contains this usage map
  96. * @param pageNum Page number that this usage map is contained in
  97. * @param rowNum Number of the row on the page that contains this usage map
  98. * @param isGlobal whether or not we are reading the "global" usage map
  99. * @return Either an InlineUsageMap or a ReferenceUsageMap, depending on
  100. * which type of map is found
  101. */
  102. static UsageMap read(DatabaseImpl database, int pageNum,
  103. int rowNum, boolean isGlobal)
  104. throws IOException
  105. {
  106. if(pageNum <= 0) {
  107. // usage maps will never appear on page 0 (or less)
  108. throw new IllegalStateException("Invalid usage map page number " + pageNum);
  109. }
  110. JetFormat format = database.getFormat();
  111. PageChannel pageChannel = database.getPageChannel();
  112. ByteBuffer tableBuffer = pageChannel.createPageBuffer();
  113. pageChannel.readPage(tableBuffer, pageNum);
  114. short rowStart = TableImpl.findRowStart(tableBuffer, rowNum, format);
  115. int rowEnd = TableImpl.findRowEnd(tableBuffer, rowNum, format);
  116. tableBuffer.limit(rowEnd);
  117. byte mapType = tableBuffer.get(rowStart);
  118. UsageMap rtn = new UsageMap(database, tableBuffer, pageNum, rowStart);
  119. rtn.initHandler(mapType, isGlobal);
  120. return rtn;
  121. }
  122. private void initHandler(byte mapType, boolean isGlobal)
  123. throws IOException
  124. {
  125. if (mapType == MAP_TYPE_INLINE) {
  126. _handler = (isGlobal ? new GlobalInlineHandler() :
  127. new InlineHandler());
  128. } else if (mapType == MAP_TYPE_REFERENCE) {
  129. _handler = (isGlobal ? new GlobalReferenceHandler() :
  130. new ReferenceHandler());
  131. } else {
  132. throw new IOException(MSG_PREFIX_UNRECOGNIZED_MAP + mapType);
  133. }
  134. }
  135. public PageCursor cursor() {
  136. return new PageCursor();
  137. }
  138. public int getPageCount() {
  139. return _pageNumbers.cardinality();
  140. }
  141. protected short getRowStart() {
  142. return _rowStart;
  143. }
  144. protected int getRowEnd() {
  145. return getTableBuffer().limit();
  146. }
  147. protected void setStartOffset(int startOffset) {
  148. _startOffset = startOffset;
  149. }
  150. protected int getStartOffset() {
  151. return _startOffset;
  152. }
  153. protected ByteBuffer getTableBuffer() {
  154. return _tableBuffer;
  155. }
  156. protected int getTablePageNumber() {
  157. return _tablePageNum;
  158. }
  159. protected int getStartPage() {
  160. return _startPage;
  161. }
  162. protected int getEndPage() {
  163. return _endPage;
  164. }
  165. protected BitSet getPageNumbers() {
  166. return _pageNumbers;
  167. }
  168. protected void setPageRange(int newStartPage, int newEndPage) {
  169. _startPage = newStartPage;
  170. _endPage = newEndPage;
  171. }
  172. protected boolean isPageWithinRange(int pageNumber)
  173. {
  174. return((pageNumber >= _startPage) && (pageNumber < _endPage));
  175. }
  176. protected int getFirstPageNumber() {
  177. return bitIndexToPageNumber(getNextBitIndex(-1),
  178. RowIdImpl.LAST_PAGE_NUMBER);
  179. }
  180. protected int getNextPageNumber(int curPage) {
  181. return bitIndexToPageNumber(
  182. getNextBitIndex(pageNumberToBitIndex(curPage)),
  183. RowIdImpl.LAST_PAGE_NUMBER);
  184. }
  185. protected int getNextBitIndex(int curIndex) {
  186. return _pageNumbers.nextSetBit(curIndex + 1);
  187. }
  188. protected int getLastPageNumber() {
  189. return bitIndexToPageNumber(getPrevBitIndex(_pageNumbers.length()),
  190. RowIdImpl.FIRST_PAGE_NUMBER);
  191. }
  192. protected int getPrevPageNumber(int curPage) {
  193. return bitIndexToPageNumber(
  194. getPrevBitIndex(pageNumberToBitIndex(curPage)),
  195. RowIdImpl.FIRST_PAGE_NUMBER);
  196. }
  197. protected int getPrevBitIndex(int curIndex) {
  198. --curIndex;
  199. while((curIndex >= 0) && !_pageNumbers.get(curIndex)) {
  200. --curIndex;
  201. }
  202. return curIndex;
  203. }
  204. protected int bitIndexToPageNumber(int bitIndex,
  205. int invalidPageNumber) {
  206. return((bitIndex >= 0) ? (_startPage + bitIndex) : invalidPageNumber);
  207. }
  208. protected int pageNumberToBitIndex(int pageNumber) {
  209. return((pageNumber >= 0) ? (pageNumber - _startPage) :
  210. INVALID_BIT_INDEX);
  211. }
  212. protected void clearTableAndPages()
  213. {
  214. // reset some values
  215. _pageNumbers.clear();
  216. _startPage = 0;
  217. _endPage = 0;
  218. ++_modCount;
  219. // clear out the table data (everything except map type)
  220. int tableStart = getRowStart() + 1;
  221. int tableEnd = getRowEnd();
  222. ByteUtil.clearRange(_tableBuffer, tableStart, tableEnd);
  223. }
  224. protected void writeTable()
  225. throws IOException
  226. {
  227. // note, we only want to write the row data with which we are working
  228. getPageChannel().writePage(_tableBuffer, _tablePageNum, _rowStart);
  229. }
  230. /**
  231. * Read in the page numbers in this inline map
  232. */
  233. protected void processMap(ByteBuffer buffer, int bufferStartPage)
  234. {
  235. int byteCount = 0;
  236. while (buffer.hasRemaining()) {
  237. byte b = buffer.get();
  238. if(b != (byte)0) {
  239. for (int i = 0; i < 8; i++) {
  240. if ((b & (1 << i)) != 0) {
  241. int pageNumberOffset = (byteCount * 8 + i) + bufferStartPage;
  242. int pageNumber = bitIndexToPageNumber(
  243. pageNumberOffset,
  244. PageChannel.INVALID_PAGE_NUMBER);
  245. if(!isPageWithinRange(pageNumber)) {
  246. throw new IllegalStateException(
  247. "found page number " + pageNumber
  248. + " in usage map outside of expected range " +
  249. _startPage + " to " + _endPage);
  250. }
  251. _pageNumbers.set(pageNumberOffset);
  252. }
  253. }
  254. }
  255. byteCount++;
  256. }
  257. }
  258. /**
  259. * Determines if the given page number is contained in this map.
  260. */
  261. public boolean containsPageNumber(int pageNumber) {
  262. return _handler.containsPageNumber(pageNumber);
  263. }
  264. /**
  265. * Add a page number to this usage map
  266. */
  267. public void addPageNumber(int pageNumber) throws IOException {
  268. ++_modCount;
  269. _handler.addOrRemovePageNumber(pageNumber, true, false);
  270. }
  271. /**
  272. * Remove a page number from this usage map
  273. */
  274. public void removePageNumber(int pageNumber)
  275. throws IOException
  276. {
  277. removePageNumber(pageNumber, true);
  278. }
  279. private void removePageNumber(int pageNumber, boolean force)
  280. throws IOException
  281. {
  282. ++_modCount;
  283. _handler.addOrRemovePageNumber(pageNumber, false, force);
  284. }
  285. protected void updateMap(int absolutePageNumber,
  286. int bufferRelativePageNumber,
  287. ByteBuffer buffer, boolean add, boolean force)
  288. throws IOException
  289. {
  290. //Find the byte to which to apply the bitmask and create the bitmask
  291. int offset = bufferRelativePageNumber / 8;
  292. int bitmask = 1 << (bufferRelativePageNumber % 8);
  293. byte b = buffer.get(_startOffset + offset);
  294. // check current value for this page number
  295. int pageNumberOffset = pageNumberToBitIndex(absolutePageNumber);
  296. boolean isOn = _pageNumbers.get(pageNumberOffset);
  297. if((isOn == add) && !force) {
  298. throw new IOException("Page number " + absolutePageNumber + " already " +
  299. ((add) ? "added to" : "removed from") +
  300. " usage map, expected range " +
  301. _startPage + " to " + _endPage);
  302. }
  303. //Apply the bitmask
  304. if (add) {
  305. b |= bitmask;
  306. _pageNumbers.set(pageNumberOffset);
  307. } else {
  308. b &= ~bitmask;
  309. _pageNumbers.clear(pageNumberOffset);
  310. }
  311. buffer.put(_startOffset + offset, b);
  312. }
  313. /**
  314. * Promotes and inline usage map to a reference usage map.
  315. */
  316. private void promoteInlineHandlerToReferenceHandler(int newPageNumber)
  317. throws IOException
  318. {
  319. // copy current page number info to new references and then clear old
  320. int oldStartPage = _startPage;
  321. BitSet oldPageNumbers = (BitSet)_pageNumbers.clone();
  322. // clear out the main table (inline usage map data and start page)
  323. clearTableAndPages();
  324. // set the new map type
  325. _tableBuffer.put(getRowStart(), MAP_TYPE_REFERENCE);
  326. // write the new table data
  327. writeTable();
  328. // set new handler
  329. _handler = new ReferenceHandler();
  330. // update new handler with old data
  331. reAddPages(oldStartPage, oldPageNumbers, newPageNumber);
  332. }
  333. private void reAddPages(int oldStartPage, BitSet oldPageNumbers,
  334. int newPageNumber)
  335. throws IOException
  336. {
  337. // add all the old pages back in
  338. for(int i = oldPageNumbers.nextSetBit(0); i >= 0;
  339. i = oldPageNumbers.nextSetBit(i + 1)) {
  340. addPageNumber(oldStartPage + i);
  341. }
  342. if(newPageNumber > PageChannel.INVALID_PAGE_NUMBER) {
  343. // and then add the new page
  344. addPageNumber(newPageNumber);
  345. }
  346. }
  347. @Override
  348. public String toString() {
  349. List<String> ranges = new ArrayList<String>();
  350. PageCursor pCursor = cursor();
  351. int curRangeStart = Integer.MIN_VALUE;
  352. int prevPage = Integer.MIN_VALUE;
  353. while(true) {
  354. int nextPage = pCursor.getNextPage();
  355. if(nextPage < 0) {
  356. break;
  357. }
  358. if(nextPage != (prevPage + 1)) {
  359. if(prevPage >= 0) {
  360. rangeToString(ranges, curRangeStart, prevPage);
  361. }
  362. curRangeStart = nextPage;
  363. }
  364. prevPage = nextPage;
  365. }
  366. if(prevPage >= 0) {
  367. rangeToString(ranges, curRangeStart, prevPage);
  368. }
  369. return CustomToStringStyle.valueBuilder(
  370. _handler.getClass().getSimpleName())
  371. .append("range", "(" + _startPage + "-" + _endPage + ")")
  372. .append("pageNumbers", ranges)
  373. .toString();
  374. }
  375. private static void rangeToString(List<String> ranges, int rangeStart,
  376. int rangeEnd)
  377. {
  378. if(rangeEnd > rangeStart) {
  379. ranges.add(rangeStart + "-" + rangeEnd);
  380. } else {
  381. ranges.add(String.valueOf(rangeStart));
  382. }
  383. }
  384. private abstract class Handler
  385. {
  386. protected Handler() {
  387. }
  388. public boolean containsPageNumber(int pageNumber) {
  389. return(isPageWithinRange(pageNumber) &&
  390. getPageNumbers().get(pageNumberToBitIndex(pageNumber)));
  391. }
  392. /**
  393. * @param pageNumber Page number to add or remove from this map
  394. * @param add True to add it, false to remove it
  395. * @param force true to force add/remove and ignore certain inconsistencies
  396. */
  397. public abstract void addOrRemovePageNumber(int pageNumber, boolean add,
  398. boolean force)
  399. throws IOException;
  400. }
  401. /**
  402. * Usage map whose map is written inline in the same page. For Jet4, this
  403. * type of map can usually contains a maximum of 512 pages. Free space maps
  404. * are always inline, used space maps may be inline or reference. It has a
  405. * start page, which all page numbers in its map are calculated as starting
  406. * from.
  407. * @author Tim McCune
  408. */
  409. private class InlineHandler extends Handler
  410. {
  411. private final int _maxInlinePages;
  412. protected InlineHandler() throws IOException
  413. {
  414. _maxInlinePages = (getInlineDataEnd() - getInlineDataStart()) * 8;
  415. int startPage = getTableBuffer().getInt(getRowStart() + 1);
  416. setInlinePageRange(startPage);
  417. processMap(getTableBuffer(), 0);
  418. }
  419. protected final int getMaxInlinePages() {
  420. return _maxInlinePages;
  421. }
  422. protected final int getInlineDataStart() {
  423. return getRowStart() + getFormat().OFFSET_USAGE_MAP_START;
  424. }
  425. protected final int getInlineDataEnd() {
  426. return getRowEnd();
  427. }
  428. /**
  429. * Sets the page range for an inline usage map starting from the given
  430. * page.
  431. */
  432. private void setInlinePageRange(int startPage) {
  433. setPageRange(startPage, startPage + getMaxInlinePages());
  434. }
  435. @Override
  436. public void addOrRemovePageNumber(int pageNumber, boolean add,
  437. boolean force)
  438. throws IOException
  439. {
  440. if(isPageWithinRange(pageNumber)) {
  441. // easy enough, just update the inline data
  442. int bufferRelativePageNumber = pageNumberToBitIndex(pageNumber);
  443. updateMap(pageNumber, bufferRelativePageNumber, getTableBuffer(), add,
  444. force);
  445. // Write the updated map back to disk
  446. writeTable();
  447. } else {
  448. // uh-oh, we've split our britches. what now?
  449. addOrRemovePageNumberOutsideRange(pageNumber, add, force);
  450. }
  451. }
  452. protected void addOrRemovePageNumberOutsideRange(
  453. int pageNumber, boolean add, boolean force)
  454. throws IOException
  455. {
  456. // determine what our status is before taking action
  457. if(add) {
  458. int firstPage = getFirstPageNumber();
  459. int lastPage = getLastPageNumber();
  460. // we are adding, can we shift the bits and stay inline?
  461. if(firstPage <= PageChannel.INVALID_PAGE_NUMBER) {
  462. // no pages currently
  463. firstPage = pageNumber;
  464. lastPage = pageNumber;
  465. } else if(pageNumber > lastPage) {
  466. lastPage = pageNumber;
  467. } else {
  468. firstPage = pageNumber;
  469. }
  470. if((lastPage - firstPage + 1) < getMaxInlinePages()) {
  471. // we can still fit within an inline map
  472. moveToNewStartPage(firstPage, pageNumber);
  473. } else {
  474. // not going to happen, need to promote the usage map to a
  475. // reference map
  476. promoteInlineHandlerToReferenceHandler(pageNumber);
  477. }
  478. } else {
  479. // we are removing, what does that mean?
  480. if(!force) {
  481. // this should not happen, we are removing a page which is not in
  482. // the map
  483. throw new IOException("Page number " + pageNumber +
  484. " already removed from usage map" +
  485. ", expected range " +
  486. _startPage + " to " + _endPage);
  487. }
  488. }
  489. }
  490. /**
  491. * Shifts the inline usage map so that it now starts with the given page.
  492. * @param newStartPage new page at which to start
  493. * @param newPageNumber optional page number to add once the map has been
  494. * shifted to the new start page
  495. */
  496. protected final void moveToNewStartPage(int newStartPage, int newPageNumber)
  497. throws IOException
  498. {
  499. int oldStartPage = getStartPage();
  500. BitSet oldPageNumbers = (BitSet)getPageNumbers().clone();
  501. // clear out the main table (inline usage map data and start page)
  502. clearTableAndPages();
  503. // write new start page
  504. ByteBuffer tableBuffer = getTableBuffer();
  505. tableBuffer.position(getRowStart() + 1);
  506. tableBuffer.putInt(newStartPage);
  507. // write the new table data
  508. writeTable();
  509. // set new page range
  510. setInlinePageRange(newStartPage);
  511. // put the pages back in
  512. reAddPages(oldStartPage, oldPageNumbers, newPageNumber);
  513. }
  514. }
  515. /**
  516. * Modified version of an "inline" usage map used for the global usage map.
  517. * When an inline usage map is used for the global usage map, we assume
  518. * out-of-range bits are on. We never promote the global usage map to a
  519. * reference usage map (although ms access may).
  520. *
  521. * Note, this UsageMap does not implement all the methods "correctly". Only
  522. * addPageNumber and removePageNumber should be called by PageChannel.
  523. */
  524. private class GlobalInlineHandler extends InlineHandler
  525. {
  526. private GlobalInlineHandler() throws IOException {
  527. }
  528. @Override
  529. public boolean containsPageNumber(int pageNumber) {
  530. // should never be called on global map
  531. throw new UnsupportedOperationException();
  532. }
  533. @Override
  534. protected void addOrRemovePageNumberOutsideRange(
  535. int pageNumber, boolean add, boolean force)
  536. throws IOException
  537. {
  538. // determine what our status is
  539. // for the global usage map, we can ignore out-of-range page addition
  540. // since we assuming out-of-range bits are "on". Note, we are leaving
  541. // small holes in the database here (leaving behind some free pages),
  542. // but it's not the end of the world.
  543. if(!add) {
  544. int firstPage = getFirstPageNumber();
  545. int lastPage = getLastPageNumber();
  546. // we are using an inline map and assuming that anything not
  547. // within the current range is "on". so, if we attempt to set a
  548. // bit which is before the current page, ignore it, we are not
  549. // going back for it.
  550. if((firstPage <= PageChannel.INVALID_PAGE_NUMBER) ||
  551. (pageNumber > lastPage)) {
  552. // move to new start page, filling in as we move
  553. moveToNewStartPageForRemove(firstPage, pageNumber);
  554. }
  555. }
  556. }
  557. /**
  558. * Shifts the inline usage map so that it now starts with the given
  559. * firstPage (if valid), otherwise the newPageNumber. Any page numbers
  560. * added to the end of the usage map are set to "on".
  561. * @param firstPage current first used page
  562. * @param newPageNumber page number to remove once the map has been
  563. * shifted to the new start page
  564. */
  565. private void moveToNewStartPageForRemove(int firstPage, int newPageNumber)
  566. throws IOException
  567. {
  568. int oldEndPage = getEndPage();
  569. int newStartPage =
  570. ((firstPage <= PageChannel.INVALID_PAGE_NUMBER) ? newPageNumber :
  571. // just shift a little and discard any initial unused pages.
  572. (newPageNumber - (getMaxInlinePages() / 2)));
  573. // move the current data
  574. moveToNewStartPage(newStartPage, PageChannel.INVALID_PAGE_NUMBER);
  575. if(firstPage <= PageChannel.INVALID_PAGE_NUMBER) {
  576. // this is the common case where we left everything behind
  577. ByteUtil.fillRange(_tableBuffer, getInlineDataStart(),
  578. getInlineDataEnd());
  579. // write out the updated table
  580. writeTable();
  581. // "add" all the page numbers
  582. getPageNumbers().set(0, getMaxInlinePages());
  583. } else {
  584. // add every new page manually
  585. for(int i = oldEndPage; i < getEndPage(); ++i) {
  586. addPageNumber(i);
  587. }
  588. }
  589. // lastly, remove the new page
  590. removePageNumber(newPageNumber, false);
  591. }
  592. }
  593. /**
  594. * Usage map whose map is written across one or more entire separate pages
  595. * of page type USAGE_MAP. For Jet4, this type of map can contain 32736
  596. * pages per reference page, and a maximum of 17 reference map pages for a
  597. * total maximum of 556512 pages (2 GB).
  598. * @author Tim McCune
  599. */
  600. private class ReferenceHandler extends Handler
  601. {
  602. /** Buffer that contains the current reference map page */
  603. private final TempPageHolder _mapPageHolder =
  604. TempPageHolder.newHolder(TempBufferHolder.Type.SOFT);
  605. private final int _maxPagesPerUsageMapPage;
  606. private ReferenceHandler() throws IOException
  607. {
  608. _maxPagesPerUsageMapPage = ((getFormat().PAGE_SIZE -
  609. getFormat().OFFSET_USAGE_MAP_PAGE_DATA) * 8);
  610. int numUsagePages = (getRowEnd() - getRowStart() - 1) / 4;
  611. setStartOffset(getFormat().OFFSET_USAGE_MAP_PAGE_DATA);
  612. setPageRange(0, (numUsagePages * _maxPagesPerUsageMapPage));
  613. // there is no "start page" for a reference usage map, so we get an
  614. // extra page reference on top of the number of page references that fit
  615. // in the table
  616. for (int i = 0; i < numUsagePages; i++) {
  617. int mapPageNum = getTableBuffer().getInt(
  618. calculateMapPagePointerOffset(i));
  619. if (mapPageNum > 0) {
  620. ByteBuffer mapPageBuffer =
  621. _mapPageHolder.setPage(getPageChannel(), mapPageNum);
  622. byte pageType = mapPageBuffer.get();
  623. if (pageType != PageTypes.USAGE_MAP) {
  624. throw new IOException("Looking for usage map at page " +
  625. mapPageNum + ", but page type is " +
  626. pageType);
  627. }
  628. mapPageBuffer.position(getFormat().OFFSET_USAGE_MAP_PAGE_DATA);
  629. processMap(mapPageBuffer, (_maxPagesPerUsageMapPage * i));
  630. }
  631. }
  632. }
  633. protected final int getMaxPagesPerUsagePage() {
  634. return _maxPagesPerUsageMapPage;
  635. }
  636. @Override
  637. public void addOrRemovePageNumber(int pageNumber, boolean add,
  638. boolean force)
  639. throws IOException
  640. {
  641. if(!isPageWithinRange(pageNumber)) {
  642. if(force) {
  643. return;
  644. }
  645. throw new IOException("Page number " + pageNumber +
  646. " is out of supported range");
  647. }
  648. int pageIndex = (pageNumber / getMaxPagesPerUsagePage());
  649. int mapPageNum = getTableBuffer().getInt(
  650. calculateMapPagePointerOffset(pageIndex));
  651. ByteBuffer mapPageBuffer = null;
  652. if(mapPageNum > 0) {
  653. mapPageBuffer = _mapPageHolder.setPage(getPageChannel(), mapPageNum);
  654. } else {
  655. // Need to create a new usage map page
  656. mapPageBuffer = createNewUsageMapPage(pageIndex);
  657. mapPageNum = _mapPageHolder.getPageNumber();
  658. }
  659. updateMap(pageNumber,
  660. (pageNumber - (getMaxPagesPerUsagePage() * pageIndex)),
  661. mapPageBuffer, add, force);
  662. getPageChannel().writePage(mapPageBuffer, mapPageNum);
  663. }
  664. /**
  665. * Create a new usage map page and update the map declaration with a
  666. * pointer to it.
  667. * @param pageIndex Index of the page reference within the map declaration
  668. */
  669. private ByteBuffer createNewUsageMapPage(int pageIndex) throws IOException
  670. {
  671. ByteBuffer mapPageBuffer = allocateNewUsageMapPage(pageIndex);
  672. int mapPageNum = _mapPageHolder.getPageNumber();
  673. getTableBuffer().putInt(calculateMapPagePointerOffset(pageIndex),
  674. mapPageNum);
  675. writeTable();
  676. return mapPageBuffer;
  677. }
  678. private int calculateMapPagePointerOffset(int pageIndex) {
  679. return getRowStart() + getFormat().OFFSET_REFERENCE_MAP_PAGE_NUMBERS +
  680. (pageIndex * 4);
  681. }
  682. protected ByteBuffer allocateNewUsageMapPage(int pageIndex)
  683. throws IOException
  684. {
  685. ByteBuffer mapPageBuffer = _mapPageHolder.setNewPage(getPageChannel());
  686. mapPageBuffer.put(PageTypes.USAGE_MAP);
  687. mapPageBuffer.put((byte) 0x01); //Unknown
  688. mapPageBuffer.putShort((short) 0); //Unknown
  689. return mapPageBuffer;
  690. }
  691. }
  692. /**
  693. * Modified version of a "reference" usage map used for the global usage
  694. * map. Since reference usage maps require allocating pages for their own
  695. * use, we need to handle potential cycles where the PageChannel is
  696. * attempting to allocate a new page (and remove it from the global usage
  697. * map) and this usage map also needs to allocate a new page. When that
  698. * happens, we stash the pending information from the PageChannel and handle
  699. * it after we have retrieved the new page.
  700. *
  701. * Note, this UsageMap does not implement all the methods "correctly". Only
  702. * addPageNumber and removePageNumber should be called by PageChannel.
  703. */
  704. private class GlobalReferenceHandler extends ReferenceHandler
  705. {
  706. private boolean _allocatingPage;
  707. private Integer _pendingPage;
  708. private GlobalReferenceHandler() throws IOException {
  709. }
  710. @Override
  711. public boolean containsPageNumber(int pageNumber) {
  712. // should never be called on global map
  713. throw new UnsupportedOperationException();
  714. }
  715. @Override
  716. public void addOrRemovePageNumber(int pageNumber, boolean add,
  717. boolean force)
  718. throws IOException
  719. {
  720. if(_allocatingPage && !add) {
  721. // we are in the midst of allocating a page for ourself, keep track of
  722. // this new page so we can mark it later...
  723. if(_pendingPage != null) {
  724. throw new IllegalStateException("should only have single pending page");
  725. }
  726. _pendingPage = pageNumber;
  727. return;
  728. }
  729. super.addOrRemovePageNumber(pageNumber, add, force);
  730. while(_pendingPage != null) {
  731. // while updating our usage map, we needed to allocate a new page (and
  732. // thus mark a new page as used). we delayed that marking so that we
  733. // didn't get into an infinite loop. now that we completed the
  734. // original updated, handle the new page. (we use a loop under the
  735. // off the wall chance that adding this page requires allocating a new
  736. // page. in theory, we could do this more than once, but not
  737. // forever).
  738. int removedPageNumber = _pendingPage;
  739. _pendingPage = null;
  740. super.addOrRemovePageNumber(removedPageNumber, false, true);
  741. }
  742. }
  743. @Override
  744. protected ByteBuffer allocateNewUsageMapPage(int pageIndex)
  745. throws IOException
  746. {
  747. try {
  748. // keep track of the fact that we are actively allocating a page for our
  749. // own use so that we can break the potential cycle.
  750. _allocatingPage = true;
  751. ByteBuffer mapPageBuffer = super.allocateNewUsageMapPage(pageIndex);
  752. // for the global usage map, all pages are "on" by default. so
  753. // whenever we add a new backing page to the usage map, we need to
  754. // turn all the pages that it represents to "on" (we essentially lazy
  755. // load this map, which is fine because we should only add pages which
  756. // represent the size of the database currently in use).
  757. int dataStart = getFormat().OFFSET_USAGE_MAP_PAGE_DATA;
  758. ByteUtil.fillRange(mapPageBuffer, dataStart,
  759. getFormat().PAGE_SIZE - dataStart);
  760. int maxPagesPerUmapPage = getMaxPagesPerUsagePage();
  761. int firstNewPage = (pageIndex * maxPagesPerUmapPage);
  762. int lastNewPage = firstNewPage + maxPagesPerUmapPage;
  763. _pageNumbers.set(firstNewPage, lastNewPage);
  764. return mapPageBuffer;
  765. } finally {
  766. _allocatingPage = false;
  767. }
  768. }
  769. }
  770. /**
  771. * Utility class to traverse over the pages in the UsageMap. Remains valid
  772. * in the face of usage map modifications.
  773. */
  774. public final class PageCursor
  775. {
  776. /** handler for moving the page cursor forward */
  777. private final DirHandler _forwardDirHandler = new ForwardDirHandler();
  778. /** handler for moving the page cursor backward */
  779. private final DirHandler _reverseDirHandler = new ReverseDirHandler();
  780. /** the current used page number */
  781. private int _curPageNumber;
  782. /** the previous used page number */
  783. private int _prevPageNumber;
  784. /** the last read modification count on the UsageMap. we track this so
  785. that the cursor can detect updates to the usage map while traversing
  786. and act accordingly */
  787. private int _lastModCount;
  788. private PageCursor() {
  789. reset();
  790. }
  791. public UsageMap getUsageMap() {
  792. return UsageMap.this;
  793. }
  794. /**
  795. * Returns the DirHandler for the given direction
  796. */
  797. private DirHandler getDirHandler(boolean moveForward) {
  798. return (moveForward ? _forwardDirHandler : _reverseDirHandler);
  799. }
  800. /**
  801. * Returns {@code true} if this cursor is up-to-date with respect to its
  802. * usage map.
  803. */
  804. public boolean isUpToDate() {
  805. return(UsageMap.this._modCount == _lastModCount);
  806. }
  807. /**
  808. * @return valid page number if there was another page to read,
  809. * {@link RowIdImpl#LAST_PAGE_NUMBER} otherwise
  810. */
  811. public int getNextPage() {
  812. return getAnotherPage(CursorImpl.MOVE_FORWARD);
  813. }
  814. /**
  815. * @return valid page number if there was another page to read,
  816. * {@link RowIdImpl#FIRST_PAGE_NUMBER} otherwise
  817. */
  818. public int getPreviousPage() {
  819. return getAnotherPage(CursorImpl.MOVE_REVERSE);
  820. }
  821. /**
  822. * Gets another page in the given direction, returning the new page.
  823. */
  824. private int getAnotherPage(boolean moveForward) {
  825. DirHandler handler = getDirHandler(moveForward);
  826. if(_curPageNumber == handler.getEndPageNumber()) {
  827. if(!isUpToDate()) {
  828. restorePosition(_prevPageNumber);
  829. // drop through and retry moving to another page
  830. } else {
  831. // at end, no more
  832. return _curPageNumber;
  833. }
  834. }
  835. checkForModification();
  836. _prevPageNumber = _curPageNumber;
  837. _curPageNumber = handler.getAnotherPageNumber(_curPageNumber);
  838. return _curPageNumber;
  839. }
  840. /**
  841. * After calling this method, getNextPage will return the first page in
  842. * the map
  843. */
  844. public void reset() {
  845. beforeFirst();
  846. }
  847. /**
  848. * After calling this method, {@link #getNextPage} will return the first
  849. * page in the map
  850. */
  851. public void beforeFirst() {
  852. reset(CursorImpl.MOVE_FORWARD);
  853. }
  854. /**
  855. * After calling this method, {@link #getPreviousPage} will return the
  856. * last page in the map
  857. */
  858. public void afterLast() {
  859. reset(CursorImpl.MOVE_REVERSE);
  860. }
  861. /**
  862. * Resets this page cursor for traversing the given direction.
  863. */
  864. protected void reset(boolean moveForward) {
  865. _curPageNumber = getDirHandler(moveForward).getBeginningPageNumber();
  866. _prevPageNumber = _curPageNumber;
  867. _lastModCount = UsageMap.this._modCount;
  868. }
  869. /**
  870. * Restores a current position for the cursor (current position becomes
  871. * previous position).
  872. */
  873. private void restorePosition(int curPageNumber)
  874. {
  875. restorePosition(curPageNumber, _curPageNumber);
  876. }
  877. /**
  878. * Restores a current and previous position for the cursor.
  879. */
  880. protected void restorePosition(int curPageNumber, int prevPageNumber)
  881. {
  882. if((curPageNumber != _curPageNumber) ||
  883. (prevPageNumber != _prevPageNumber))
  884. {
  885. _prevPageNumber = updatePosition(prevPageNumber);
  886. _curPageNumber = updatePosition(curPageNumber);
  887. _lastModCount = UsageMap.this._modCount;
  888. } else {
  889. checkForModification();
  890. }
  891. }
  892. /**
  893. * Checks the usage map for modifications an updates state accordingly.
  894. */
  895. private void checkForModification() {
  896. if(!isUpToDate()) {
  897. _prevPageNumber = updatePosition(_prevPageNumber);
  898. _curPageNumber = updatePosition(_curPageNumber);
  899. _lastModCount = UsageMap.this._modCount;
  900. }
  901. }
  902. private int updatePosition(int pageNumber) {
  903. if(pageNumber < UsageMap.this.getFirstPageNumber()) {
  904. pageNumber = RowIdImpl.FIRST_PAGE_NUMBER;
  905. } else if(pageNumber > UsageMap.this.getLastPageNumber()) {
  906. pageNumber = RowIdImpl.LAST_PAGE_NUMBER;
  907. }
  908. return pageNumber;
  909. }
  910. @Override
  911. public String toString() {
  912. return getClass().getSimpleName() + " CurPosition " + _curPageNumber +
  913. ", PrevPosition " + _prevPageNumber;
  914. }
  915. /**
  916. * Handles moving the cursor in a given direction. Separates cursor
  917. * logic from value storage.
  918. */
  919. private abstract class DirHandler {
  920. public abstract int getAnotherPageNumber(int curPageNumber);
  921. public abstract int getBeginningPageNumber();
  922. public abstract int getEndPageNumber();
  923. }
  924. /**
  925. * Handles moving the cursor forward.
  926. */
  927. private final class ForwardDirHandler extends DirHandler {
  928. @Override
  929. public int getAnotherPageNumber(int curPageNumber) {
  930. if(curPageNumber == getBeginningPageNumber()) {
  931. return UsageMap.this.getFirstPageNumber();
  932. }
  933. return UsageMap.this.getNextPageNumber(curPageNumber);
  934. }
  935. @Override
  936. public int getBeginningPageNumber() {
  937. return RowIdImpl.FIRST_PAGE_NUMBER;
  938. }
  939. @Override
  940. public int getEndPageNumber() {
  941. return RowIdImpl.LAST_PAGE_NUMBER;
  942. }
  943. }
  944. /**
  945. * Handles moving the cursor backward.
  946. */
  947. private final class ReverseDirHandler extends DirHandler {
  948. @Override
  949. public int getAnotherPageNumber(int curPageNumber) {
  950. if(curPageNumber == getBeginningPageNumber()) {
  951. return UsageMap.this.getLastPageNumber();
  952. }
  953. return UsageMap.this.getPrevPageNumber(curPageNumber);
  954. }
  955. @Override
  956. public int getBeginningPageNumber() {
  957. return RowIdImpl.LAST_PAGE_NUMBER;
  958. }
  959. @Override
  960. public int getEndPageNumber() {
  961. return RowIdImpl.FIRST_PAGE_NUMBER;
  962. }
  963. }
  964. }
  965. }