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

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129
  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 static int toValidStartPage(int startPage) {
  385. // start page must be a multiple of 8
  386. return ((startPage / 8) * 8);
  387. }
  388. private abstract class Handler
  389. {
  390. protected Handler() {
  391. }
  392. public boolean containsPageNumber(int pageNumber) {
  393. return(isPageWithinRange(pageNumber) &&
  394. getPageNumbers().get(pageNumberToBitIndex(pageNumber)));
  395. }
  396. /**
  397. * @param pageNumber Page number to add or remove from this map
  398. * @param add True to add it, false to remove it
  399. * @param force true to force add/remove and ignore certain inconsistencies
  400. */
  401. public abstract void addOrRemovePageNumber(int pageNumber, boolean add,
  402. boolean force)
  403. throws IOException;
  404. }
  405. /**
  406. * Usage map whose map is written inline in the same page. For Jet4, this
  407. * type of map can usually contains a maximum of 512 pages. Free space maps
  408. * are always inline, used space maps may be inline or reference. It has a
  409. * start page, which all page numbers in its map are calculated as starting
  410. * from.
  411. * @author Tim McCune
  412. */
  413. private class InlineHandler extends Handler
  414. {
  415. private final int _maxInlinePages;
  416. protected InlineHandler() throws IOException
  417. {
  418. _maxInlinePages = (getInlineDataEnd() - getInlineDataStart()) * 8;
  419. int startPage = getTableBuffer().getInt(getRowStart() + 1);
  420. setInlinePageRange(startPage);
  421. processMap(getTableBuffer(), 0);
  422. }
  423. protected final int getMaxInlinePages() {
  424. return _maxInlinePages;
  425. }
  426. protected final int getInlineDataStart() {
  427. return getRowStart() + getFormat().OFFSET_USAGE_MAP_START;
  428. }
  429. protected final int getInlineDataEnd() {
  430. return getRowEnd();
  431. }
  432. /**
  433. * Sets the page range for an inline usage map starting from the given
  434. * page.
  435. */
  436. private void setInlinePageRange(int startPage) {
  437. setPageRange(startPage, startPage + getMaxInlinePages());
  438. }
  439. @Override
  440. public void addOrRemovePageNumber(int pageNumber, boolean add,
  441. boolean force)
  442. throws IOException
  443. {
  444. if(isPageWithinRange(pageNumber)) {
  445. // easy enough, just update the inline data
  446. int bufferRelativePageNumber = pageNumberToBitIndex(pageNumber);
  447. updateMap(pageNumber, bufferRelativePageNumber, getTableBuffer(), add,
  448. force);
  449. // Write the updated map back to disk
  450. writeTable();
  451. } else {
  452. // uh-oh, we've split our britches. what now?
  453. addOrRemovePageNumberOutsideRange(pageNumber, add, force);
  454. }
  455. }
  456. protected void addOrRemovePageNumberOutsideRange(
  457. int pageNumber, boolean add, boolean force)
  458. throws IOException
  459. {
  460. // determine what our status is before taking action
  461. if(add) {
  462. int firstPage = getFirstPageNumber();
  463. int lastPage = getLastPageNumber();
  464. // we are adding, can we shift the bits and stay inline?
  465. if(firstPage <= PageChannel.INVALID_PAGE_NUMBER) {
  466. // no pages currently
  467. firstPage = pageNumber;
  468. lastPage = pageNumber;
  469. } else if(pageNumber > lastPage) {
  470. lastPage = pageNumber;
  471. } else {
  472. firstPage = pageNumber;
  473. }
  474. firstPage = toValidStartPage(firstPage);
  475. if((lastPage - firstPage + 1) < getMaxInlinePages()) {
  476. // we can still fit within an inline map
  477. moveToNewStartPage(firstPage, pageNumber);
  478. } else {
  479. // not going to happen, need to promote the usage map to a
  480. // reference map
  481. promoteInlineHandlerToReferenceHandler(pageNumber);
  482. }
  483. } else {
  484. // we are removing, what does that mean?
  485. if(!force) {
  486. // this should not happen, we are removing a page which is not in
  487. // the map
  488. throw new IOException("Page number " + pageNumber +
  489. " already removed from usage map" +
  490. ", expected range " +
  491. _startPage + " to " + _endPage);
  492. }
  493. }
  494. }
  495. /**
  496. * Shifts the inline usage map so that it now starts with the given page.
  497. * @param newStartPage new page at which to start
  498. * @param newPageNumber optional page number to add once the map has been
  499. * shifted to the new start page
  500. */
  501. protected final void moveToNewStartPage(int newStartPage, int newPageNumber)
  502. throws IOException
  503. {
  504. int oldStartPage = getStartPage();
  505. BitSet oldPageNumbers = (BitSet)getPageNumbers().clone();
  506. // clear out the main table (inline usage map data and start page)
  507. clearTableAndPages();
  508. // write new start page
  509. ByteBuffer tableBuffer = getTableBuffer();
  510. tableBuffer.position(getRowStart() + 1);
  511. tableBuffer.putInt(newStartPage);
  512. // write the new table data
  513. writeTable();
  514. // set new page range
  515. setInlinePageRange(newStartPage);
  516. // put the pages back in
  517. reAddPages(oldStartPage, oldPageNumbers, newPageNumber);
  518. }
  519. }
  520. /**
  521. * Modified version of an "inline" usage map used for the global usage map.
  522. * When an inline usage map is used for the global usage map, we assume
  523. * out-of-range bits are on. We never promote the global usage map to a
  524. * reference usage map (although ms access may).
  525. *
  526. * Note, this UsageMap does not implement all the methods "correctly". Only
  527. * addPageNumber and removePageNumber should be called by PageChannel.
  528. */
  529. private class GlobalInlineHandler extends InlineHandler
  530. {
  531. private GlobalInlineHandler() throws IOException {
  532. }
  533. @Override
  534. public boolean containsPageNumber(int pageNumber) {
  535. // should never be called on global map
  536. throw new UnsupportedOperationException();
  537. }
  538. @Override
  539. protected void addOrRemovePageNumberOutsideRange(
  540. int pageNumber, boolean add, boolean force)
  541. throws IOException
  542. {
  543. // determine what our status is
  544. // for the global usage map, we can ignore out-of-range page addition
  545. // since we assuming out-of-range bits are "on". Note, we are leaving
  546. // small holes in the database here (leaving behind some free pages),
  547. // but it's not the end of the world.
  548. if(!add) {
  549. int firstPage = getFirstPageNumber();
  550. int lastPage = getLastPageNumber();
  551. // we are using an inline map and assuming that anything not
  552. // within the current range is "on". so, if we attempt to set a
  553. // bit which is before the current page, ignore it, we are not
  554. // going back for it.
  555. if((firstPage <= PageChannel.INVALID_PAGE_NUMBER) ||
  556. (pageNumber > lastPage)) {
  557. // move to new start page, filling in as we move
  558. moveToNewStartPageForRemove(firstPage, pageNumber);
  559. }
  560. }
  561. }
  562. /**
  563. * Shifts the inline usage map so that it now starts with the given
  564. * firstPage (if valid), otherwise the newPageNumber. Any page numbers
  565. * added to the end of the usage map are set to "on".
  566. * @param firstPage current first used page
  567. * @param newPageNumber page number to remove once the map has been
  568. * shifted to the new start page
  569. */
  570. private void moveToNewStartPageForRemove(int firstPage, int newPageNumber)
  571. throws IOException
  572. {
  573. int oldEndPage = getEndPage();
  574. int newStartPage =
  575. toValidStartPage(
  576. ((firstPage <= PageChannel.INVALID_PAGE_NUMBER) ? newPageNumber :
  577. // just shift a little and discard any initial unused pages.
  578. (newPageNumber - (getMaxInlinePages() / 2))));
  579. // move the current data
  580. moveToNewStartPage(newStartPage, PageChannel.INVALID_PAGE_NUMBER);
  581. if(firstPage <= PageChannel.INVALID_PAGE_NUMBER) {
  582. // this is the common case where we left everything behind
  583. ByteUtil.fillRange(_tableBuffer, getInlineDataStart(),
  584. getInlineDataEnd());
  585. // write out the updated table
  586. writeTable();
  587. // "add" all the page numbers
  588. getPageNumbers().set(0, getMaxInlinePages());
  589. } else {
  590. // add every new page manually
  591. for(int i = oldEndPage; i < getEndPage(); ++i) {
  592. addPageNumber(i);
  593. }
  594. }
  595. // lastly, remove the new page
  596. removePageNumber(newPageNumber, false);
  597. }
  598. }
  599. /**
  600. * Usage map whose map is written across one or more entire separate pages
  601. * of page type USAGE_MAP. For Jet4, this type of map can contain 32736
  602. * pages per reference page, and a maximum of 17 reference map pages for a
  603. * total maximum of 556512 pages (2 GB).
  604. * @author Tim McCune
  605. */
  606. private class ReferenceHandler extends Handler
  607. {
  608. /** Buffer that contains the current reference map page */
  609. private final TempPageHolder _mapPageHolder =
  610. TempPageHolder.newHolder(TempBufferHolder.Type.SOFT);
  611. private final int _maxPagesPerUsageMapPage;
  612. private ReferenceHandler() throws IOException
  613. {
  614. _maxPagesPerUsageMapPage = ((getFormat().PAGE_SIZE -
  615. getFormat().OFFSET_USAGE_MAP_PAGE_DATA) * 8);
  616. int numUsagePages = (getRowEnd() - getRowStart() - 1) / 4;
  617. setStartOffset(getFormat().OFFSET_USAGE_MAP_PAGE_DATA);
  618. setPageRange(0, (numUsagePages * _maxPagesPerUsageMapPage));
  619. // there is no "start page" for a reference usage map, so we get an
  620. // extra page reference on top of the number of page references that fit
  621. // in the table
  622. for (int i = 0; i < numUsagePages; i++) {
  623. int mapPageNum = getTableBuffer().getInt(
  624. calculateMapPagePointerOffset(i));
  625. if (mapPageNum > 0) {
  626. ByteBuffer mapPageBuffer =
  627. _mapPageHolder.setPage(getPageChannel(), mapPageNum);
  628. byte pageType = mapPageBuffer.get();
  629. if (pageType != PageTypes.USAGE_MAP) {
  630. throw new IOException("Looking for usage map at page " +
  631. mapPageNum + ", but page type is " +
  632. pageType);
  633. }
  634. mapPageBuffer.position(getFormat().OFFSET_USAGE_MAP_PAGE_DATA);
  635. processMap(mapPageBuffer, (_maxPagesPerUsageMapPage * i));
  636. }
  637. }
  638. }
  639. protected final int getMaxPagesPerUsagePage() {
  640. return _maxPagesPerUsageMapPage;
  641. }
  642. @Override
  643. public void addOrRemovePageNumber(int pageNumber, boolean add,
  644. boolean force)
  645. throws IOException
  646. {
  647. if(!isPageWithinRange(pageNumber)) {
  648. if(force) {
  649. return;
  650. }
  651. throw new IOException("Page number " + pageNumber +
  652. " is out of supported range");
  653. }
  654. int pageIndex = (pageNumber / getMaxPagesPerUsagePage());
  655. int mapPageNum = getTableBuffer().getInt(
  656. calculateMapPagePointerOffset(pageIndex));
  657. ByteBuffer mapPageBuffer = null;
  658. if(mapPageNum > 0) {
  659. mapPageBuffer = _mapPageHolder.setPage(getPageChannel(), mapPageNum);
  660. } else {
  661. // Need to create a new usage map page
  662. mapPageBuffer = createNewUsageMapPage(pageIndex);
  663. mapPageNum = _mapPageHolder.getPageNumber();
  664. }
  665. updateMap(pageNumber,
  666. (pageNumber - (getMaxPagesPerUsagePage() * pageIndex)),
  667. mapPageBuffer, add, force);
  668. getPageChannel().writePage(mapPageBuffer, mapPageNum);
  669. }
  670. /**
  671. * Create a new usage map page and update the map declaration with a
  672. * pointer to it.
  673. * @param pageIndex Index of the page reference within the map declaration
  674. */
  675. private ByteBuffer createNewUsageMapPage(int pageIndex) throws IOException
  676. {
  677. ByteBuffer mapPageBuffer = allocateNewUsageMapPage(pageIndex);
  678. int mapPageNum = _mapPageHolder.getPageNumber();
  679. getTableBuffer().putInt(calculateMapPagePointerOffset(pageIndex),
  680. mapPageNum);
  681. writeTable();
  682. return mapPageBuffer;
  683. }
  684. private int calculateMapPagePointerOffset(int pageIndex) {
  685. return getRowStart() + getFormat().OFFSET_REFERENCE_MAP_PAGE_NUMBERS +
  686. (pageIndex * 4);
  687. }
  688. protected ByteBuffer allocateNewUsageMapPage(int pageIndex)
  689. throws IOException
  690. {
  691. ByteBuffer mapPageBuffer = _mapPageHolder.setNewPage(getPageChannel());
  692. mapPageBuffer.put(PageTypes.USAGE_MAP);
  693. mapPageBuffer.put((byte) 0x01); //Unknown
  694. mapPageBuffer.putShort((short) 0); //Unknown
  695. return mapPageBuffer;
  696. }
  697. }
  698. /**
  699. * Modified version of a "reference" usage map used for the global usage
  700. * map. Since reference usage maps require allocating pages for their own
  701. * use, we need to handle potential cycles where the PageChannel is
  702. * attempting to allocate a new page (and remove it from the global usage
  703. * map) and this usage map also needs to allocate a new page. When that
  704. * happens, we stash the pending information from the PageChannel and handle
  705. * it after we have retrieved the new page.
  706. *
  707. * Note, this UsageMap does not implement all the methods "correctly". Only
  708. * addPageNumber and removePageNumber should be called by PageChannel.
  709. */
  710. private class GlobalReferenceHandler extends ReferenceHandler
  711. {
  712. private boolean _allocatingPage;
  713. private Integer _pendingPage;
  714. private GlobalReferenceHandler() throws IOException {
  715. }
  716. @Override
  717. public boolean containsPageNumber(int pageNumber) {
  718. // should never be called on global map
  719. throw new UnsupportedOperationException();
  720. }
  721. @Override
  722. public void addOrRemovePageNumber(int pageNumber, boolean add,
  723. boolean force)
  724. throws IOException
  725. {
  726. if(_allocatingPage && !add) {
  727. // we are in the midst of allocating a page for ourself, keep track of
  728. // this new page so we can mark it later...
  729. if(_pendingPage != null) {
  730. throw new IllegalStateException("should only have single pending page");
  731. }
  732. _pendingPage = pageNumber;
  733. return;
  734. }
  735. super.addOrRemovePageNumber(pageNumber, add, force);
  736. while(_pendingPage != null) {
  737. // while updating our usage map, we needed to allocate a new page (and
  738. // thus mark a new page as used). we delayed that marking so that we
  739. // didn't get into an infinite loop. now that we completed the
  740. // original updated, handle the new page. (we use a loop under the
  741. // off the wall chance that adding this page requires allocating a new
  742. // page. in theory, we could do this more than once, but not
  743. // forever).
  744. int removedPageNumber = _pendingPage;
  745. _pendingPage = null;
  746. super.addOrRemovePageNumber(removedPageNumber, false, true);
  747. }
  748. }
  749. @Override
  750. protected ByteBuffer allocateNewUsageMapPage(int pageIndex)
  751. throws IOException
  752. {
  753. try {
  754. // keep track of the fact that we are actively allocating a page for our
  755. // own use so that we can break the potential cycle.
  756. _allocatingPage = true;
  757. ByteBuffer mapPageBuffer = super.allocateNewUsageMapPage(pageIndex);
  758. // for the global usage map, all pages are "on" by default. so
  759. // whenever we add a new backing page to the usage map, we need to
  760. // turn all the pages that it represents to "on" (we essentially lazy
  761. // load this map, which is fine because we should only add pages which
  762. // represent the size of the database currently in use).
  763. int dataStart = getFormat().OFFSET_USAGE_MAP_PAGE_DATA;
  764. ByteUtil.fillRange(mapPageBuffer, dataStart,
  765. getFormat().PAGE_SIZE - dataStart);
  766. int maxPagesPerUmapPage = getMaxPagesPerUsagePage();
  767. int firstNewPage = (pageIndex * maxPagesPerUmapPage);
  768. int lastNewPage = firstNewPage + maxPagesPerUmapPage;
  769. _pageNumbers.set(firstNewPage, lastNewPage);
  770. return mapPageBuffer;
  771. } finally {
  772. _allocatingPage = false;
  773. }
  774. }
  775. }
  776. /**
  777. * Utility class to traverse over the pages in the UsageMap. Remains valid
  778. * in the face of usage map modifications.
  779. */
  780. public final class PageCursor
  781. {
  782. /** handler for moving the page cursor forward */
  783. private final DirHandler _forwardDirHandler = new ForwardDirHandler();
  784. /** handler for moving the page cursor backward */
  785. private final DirHandler _reverseDirHandler = new ReverseDirHandler();
  786. /** the current used page number */
  787. private int _curPageNumber;
  788. /** the previous used page number */
  789. private int _prevPageNumber;
  790. /** the last read modification count on the UsageMap. we track this so
  791. that the cursor can detect updates to the usage map while traversing
  792. and act accordingly */
  793. private int _lastModCount;
  794. private PageCursor() {
  795. reset();
  796. }
  797. public UsageMap getUsageMap() {
  798. return UsageMap.this;
  799. }
  800. /**
  801. * Returns the DirHandler for the given direction
  802. */
  803. private DirHandler getDirHandler(boolean moveForward) {
  804. return (moveForward ? _forwardDirHandler : _reverseDirHandler);
  805. }
  806. /**
  807. * Returns {@code true} if this cursor is up-to-date with respect to its
  808. * usage map.
  809. */
  810. public boolean isUpToDate() {
  811. return(UsageMap.this._modCount == _lastModCount);
  812. }
  813. /**
  814. * @return valid page number if there was another page to read,
  815. * {@link RowIdImpl#LAST_PAGE_NUMBER} otherwise
  816. */
  817. public int getNextPage() {
  818. return getAnotherPage(CursorImpl.MOVE_FORWARD);
  819. }
  820. /**
  821. * @return valid page number if there was another page to read,
  822. * {@link RowIdImpl#FIRST_PAGE_NUMBER} otherwise
  823. */
  824. public int getPreviousPage() {
  825. return getAnotherPage(CursorImpl.MOVE_REVERSE);
  826. }
  827. /**
  828. * Gets another page in the given direction, returning the new page.
  829. */
  830. private int getAnotherPage(boolean moveForward) {
  831. DirHandler handler = getDirHandler(moveForward);
  832. if(_curPageNumber == handler.getEndPageNumber()) {
  833. if(!isUpToDate()) {
  834. restorePosition(_prevPageNumber);
  835. // drop through and retry moving to another page
  836. } else {
  837. // at end, no more
  838. return _curPageNumber;
  839. }
  840. }
  841. checkForModification();
  842. _prevPageNumber = _curPageNumber;
  843. _curPageNumber = handler.getAnotherPageNumber(_curPageNumber);
  844. return _curPageNumber;
  845. }
  846. /**
  847. * After calling this method, getNextPage will return the first page in
  848. * the map
  849. */
  850. public void reset() {
  851. beforeFirst();
  852. }
  853. /**
  854. * After calling this method, {@link #getNextPage} will return the first
  855. * page in the map
  856. */
  857. public void beforeFirst() {
  858. reset(CursorImpl.MOVE_FORWARD);
  859. }
  860. /**
  861. * After calling this method, {@link #getPreviousPage} will return the
  862. * last page in the map
  863. */
  864. public void afterLast() {
  865. reset(CursorImpl.MOVE_REVERSE);
  866. }
  867. /**
  868. * Resets this page cursor for traversing the given direction.
  869. */
  870. protected void reset(boolean moveForward) {
  871. _curPageNumber = getDirHandler(moveForward).getBeginningPageNumber();
  872. _prevPageNumber = _curPageNumber;
  873. _lastModCount = UsageMap.this._modCount;
  874. }
  875. /**
  876. * Restores a current position for the cursor (current position becomes
  877. * previous position).
  878. */
  879. private void restorePosition(int curPageNumber)
  880. {
  881. restorePosition(curPageNumber, _curPageNumber);
  882. }
  883. /**
  884. * Restores a current and previous position for the cursor.
  885. */
  886. protected void restorePosition(int curPageNumber, int prevPageNumber)
  887. {
  888. if((curPageNumber != _curPageNumber) ||
  889. (prevPageNumber != _prevPageNumber))
  890. {
  891. _prevPageNumber = updatePosition(prevPageNumber);
  892. _curPageNumber = updatePosition(curPageNumber);
  893. _lastModCount = UsageMap.this._modCount;
  894. } else {
  895. checkForModification();
  896. }
  897. }
  898. /**
  899. * Checks the usage map for modifications an updates state accordingly.
  900. */
  901. private void checkForModification() {
  902. if(!isUpToDate()) {
  903. _prevPageNumber = updatePosition(_prevPageNumber);
  904. _curPageNumber = updatePosition(_curPageNumber);
  905. _lastModCount = UsageMap.this._modCount;
  906. }
  907. }
  908. private int updatePosition(int pageNumber) {
  909. if(pageNumber < UsageMap.this.getFirstPageNumber()) {
  910. pageNumber = RowIdImpl.FIRST_PAGE_NUMBER;
  911. } else if(pageNumber > UsageMap.this.getLastPageNumber()) {
  912. pageNumber = RowIdImpl.LAST_PAGE_NUMBER;
  913. }
  914. return pageNumber;
  915. }
  916. @Override
  917. public String toString() {
  918. return getClass().getSimpleName() + " CurPosition " + _curPageNumber +
  919. ", PrevPosition " + _prevPageNumber;
  920. }
  921. /**
  922. * Handles moving the cursor in a given direction. Separates cursor
  923. * logic from value storage.
  924. */
  925. private abstract class DirHandler {
  926. public abstract int getAnotherPageNumber(int curPageNumber);
  927. public abstract int getBeginningPageNumber();
  928. public abstract int getEndPageNumber();
  929. }
  930. /**
  931. * Handles moving the cursor forward.
  932. */
  933. private final class ForwardDirHandler extends DirHandler {
  934. @Override
  935. public int getAnotherPageNumber(int curPageNumber) {
  936. if(curPageNumber == getBeginningPageNumber()) {
  937. return UsageMap.this.getFirstPageNumber();
  938. }
  939. return UsageMap.this.getNextPageNumber(curPageNumber);
  940. }
  941. @Override
  942. public int getBeginningPageNumber() {
  943. return RowIdImpl.FIRST_PAGE_NUMBER;
  944. }
  945. @Override
  946. public int getEndPageNumber() {
  947. return RowIdImpl.LAST_PAGE_NUMBER;
  948. }
  949. }
  950. /**
  951. * Handles moving the cursor backward.
  952. */
  953. private final class ReverseDirHandler extends DirHandler {
  954. @Override
  955. public int getAnotherPageNumber(int curPageNumber) {
  956. if(curPageNumber == getBeginningPageNumber()) {
  957. return UsageMap.this.getLastPageNumber();
  958. }
  959. return UsageMap.this.getPrevPageNumber(curPageNumber);
  960. }
  961. @Override
  962. public int getBeginningPageNumber() {
  963. return RowIdImpl.LAST_PAGE_NUMBER;
  964. }
  965. @Override
  966. public int getEndPageNumber() {
  967. return RowIdImpl.FIRST_PAGE_NUMBER;
  968. }
  969. }
  970. }
  971. }