ClusterUsageBitmap.cs 8.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221
  1. /* Copyright (C) 2014-2018 Tal Aloni <tal.aloni.il@gmail.com>. All rights reserved.
  2. *
  3. * You can redistribute this program and/or modify it under the terms of
  4. * the GNU Lesser Public License as published by the Free Software Foundation,
  5. * either version 3 of the License, or (at your option) any later version.
  6. */
  7. using System;
  8. using System.Collections.Generic;
  9. using System.IO;
  10. using Utilities;
  11. namespace DiskAccessLibrary.FileSystems.NTFS
  12. {
  13. public class ClusterUsageBitmap : NTFSFile
  14. {
  15. NTFSVolume m_volume;
  16. private long m_bufferedClusterVCN = -1;
  17. private byte[] m_bufferedCluster;
  18. private bool m_isBufferDirty; // if set to true, we need to write the buffer
  19. public ClusterUsageBitmap(NTFSVolume volume) : base(volume, MasterFileTable.BitmapSegmentNumber)
  20. {
  21. m_volume = volume;
  22. }
  23. private byte[] GetBitmapCluster(long bitmapClusterVCN)
  24. {
  25. if (m_bufferedClusterVCN != bitmapClusterVCN)
  26. {
  27. if (m_isBufferDirty)
  28. {
  29. FlushBuffer();
  30. }
  31. m_bufferedClusterVCN = bitmapClusterVCN;
  32. // ClusterUsageBitmap is always non-resident
  33. m_bufferedCluster = FileRecord.NonResidentDataRecord.ReadDataCluster(Volume, bitmapClusterVCN);
  34. }
  35. return m_bufferedCluster;
  36. }
  37. private void FlushBuffer()
  38. {
  39. FileRecord.NonResidentDataRecord.WriteDataClusters(Volume, m_bufferedClusterVCN, m_bufferedCluster);
  40. m_isBufferDirty = false;
  41. }
  42. /// <param name="lcn">Logical cluster number</param>
  43. private bool IsClusterFree(ulong lcn)
  44. {
  45. long bitmapClusterVCN = ((long)(lcn / 8)) / Volume.BytesPerCluster;
  46. byte[] bitmap = GetBitmapCluster(bitmapClusterVCN);
  47. int lcnByteOffset = (int)(((long)(lcn / 8)) % Volume.BytesPerCluster);
  48. int lcnBitIndex = (int)(lcn % 8);
  49. bool isInUse = ((bitmap[lcnByteOffset] >> lcnBitIndex) & 0x01) != 0;
  50. return !isInUse;
  51. }
  52. private void UpdateClusterStatus(ulong lcn, bool isUsed)
  53. {
  54. long bitmapClusterVCN = (long)(lcn / (8 * (uint)Volume.BytesPerCluster));
  55. // bitmap will reference m_bufferedCluster
  56. byte[] bitmap = GetBitmapCluster(bitmapClusterVCN);
  57. ulong clusterIndexInBitmap = lcn % (8 * (uint)Volume.BytesPerCluster);
  58. UpdateClusterStatus(bitmap, clusterIndexInBitmap, true);
  59. m_isBufferDirty = true;
  60. }
  61. public KeyValuePairList<ulong, long> AllocateClusters(ulong desiredStartLCN, long numberOfClusters)
  62. {
  63. KeyValuePairList<ulong, long> freeClusterRunList = FindClustersToAllocate(desiredStartLCN, numberOfClusters);
  64. // mark the clusters as used in the volume bitmap
  65. for (int index = 0; index < freeClusterRunList.Count; index++)
  66. {
  67. ulong runStartLCN = freeClusterRunList[index].Key;
  68. long runLength = freeClusterRunList[index].Value;
  69. for (uint position = 0; position < runLength; position++)
  70. {
  71. UpdateClusterStatus(runStartLCN + position, true);
  72. }
  73. }
  74. if (m_isBufferDirty)
  75. {
  76. FlushBuffer();
  77. }
  78. return freeClusterRunList;
  79. }
  80. /// <summary>
  81. /// Return list of free cluster runs, key is cluster LCN, value is run length
  82. /// </summary>
  83. private KeyValuePairList<ulong, long> FindClustersToAllocate(ulong desiredStartLCN, long numberOfClusters)
  84. {
  85. KeyValuePairList<ulong, long> result = new KeyValuePairList<ulong, long>();
  86. long leftToAllocate;
  87. ulong endLCN = (ulong)(m_volume.Size / m_volume.BytesPerCluster) - 1;
  88. KeyValuePairList<ulong, long> segment = FindClustersToAllocate(desiredStartLCN, endLCN, numberOfClusters, out leftToAllocate);
  89. result.AddRange(segment);
  90. if (leftToAllocate > 0 && desiredStartLCN > 0)
  91. {
  92. segment = FindClustersToAllocate(0, desiredStartLCN - 1, leftToAllocate, out leftToAllocate);
  93. result.AddRange(segment);
  94. }
  95. if (leftToAllocate > 0)
  96. {
  97. throw new Exception("Could not allocate clusters. Not enough free disk space");
  98. }
  99. return result;
  100. }
  101. /// <param name="clustersToAllocate">Number of clusters to allocate</param>
  102. private KeyValuePairList<ulong, long> FindClustersToAllocate(ulong startLCN, ulong endLCN, long clustersToAllocate, out long leftToAllocate)
  103. {
  104. KeyValuePairList<ulong, long> result = new KeyValuePairList<ulong, long>();
  105. leftToAllocate = clustersToAllocate;
  106. ulong runStartLCN = 0; // temporary
  107. long runLength = 0;
  108. ulong nextLCN = startLCN;
  109. while (nextLCN <= endLCN && leftToAllocate > 0)
  110. {
  111. if (IsClusterFree(nextLCN))
  112. {
  113. if (runLength == 0)
  114. {
  115. runStartLCN = nextLCN;
  116. runLength = 1;
  117. }
  118. else
  119. {
  120. runLength++;
  121. }
  122. leftToAllocate--;
  123. }
  124. else
  125. {
  126. if (runLength > 0)
  127. {
  128. result.Add(runStartLCN, runLength);
  129. runLength = 0;
  130. // add this run
  131. }
  132. }
  133. nextLCN++;
  134. }
  135. // add the last run
  136. if (runLength > 0)
  137. {
  138. result.Add(runStartLCN, runLength);
  139. }
  140. return result;
  141. }
  142. private byte CountNumberOfFreeClusters(byte bitmap)
  143. {
  144. byte result = 0;
  145. for (int bitIndex = 0; bitIndex < 8; bitIndex++)
  146. {
  147. bool isFree = ((bitmap >> bitIndex) & 0x01) == 0;
  148. if (isFree)
  149. {
  150. result++;
  151. }
  152. }
  153. return result;
  154. }
  155. // Each bit in the $Bitmap file represents a cluster.
  156. // The size of the $Bitmap file is always a multiple of 8 bytes, extra bits are always set to 1.
  157. public long CountNumberOfFreeClusters()
  158. {
  159. int transferSizeInClusters = Settings.MaximumTransferSizeLBA / m_volume.SectorsPerCluster;
  160. ulong endLCN = (ulong)(m_volume.Size / m_volume.BytesPerCluster) - 1;
  161. long lastClusterVCN = ((long)(endLCN / 8)) / Volume.BytesPerCluster;
  162. long result = 0;
  163. // build lookup table
  164. byte[] lookup = new byte[256];
  165. for (int index = 0; index < 256; index++)
  166. {
  167. lookup[index] = CountNumberOfFreeClusters((byte)index);
  168. }
  169. // extra bits will be marked as used, so no need for special treatment
  170. for (long bitmapVcn = 0; bitmapVcn < lastClusterVCN; bitmapVcn += transferSizeInClusters)
  171. {
  172. byte[] bitmap = FileRecord.NonResidentDataRecord.ReadDataClusters(Volume, bitmapVcn, transferSizeInClusters);
  173. for (int index = 0; index < bitmap.Length; index++)
  174. {
  175. result += lookup[bitmap[index]];
  176. }
  177. }
  178. return result;
  179. }
  180. public static void UpdateClusterStatus(byte[] bitmap, ulong clusterIndexInBitmap, bool isUsed)
  181. {
  182. ulong byteOffset = clusterIndexInBitmap / 8;
  183. int bitOffset = (int)(clusterIndexInBitmap % 8);
  184. if (isUsed)
  185. {
  186. bitmap[byteOffset] |= (byte)(0x01 << bitOffset);
  187. }
  188. else
  189. {
  190. bitmap[byteOffset] &= (byte)(~(0x01 << bitOffset));
  191. }
  192. }
  193. }
  194. }