Advertisement
Guest User

Untitled

a guest
Jun 10th, 2017
532
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Diff 259.60 KB | None | 0 0
  1. Index: src/add-ons/kernel/file_systems/ext2/InodeJournal.h
  2. ===================================================================
  3. --- src/add-ons/kernel/file_systems/ext2/InodeJournal.h (revision 0)
  4. +++ src/add-ons/kernel/file_systems/ext2/InodeJournal.h (revision 0)
  5. @@ -0,0 +1,29 @@
  6. +/*
  7. + * Copyright 2001-2010, Haiku Inc. All rights reserved.
  8. + * This file may be used under the terms of the MIT License.
  9. + *
  10. + * Authors:
  11. + *     Janito V. Ferreira Filho
  12. + */
  13. +#ifndef INODEJOURNAL_H
  14. +#define INODEJOURNAL_H
  15. +
  16. +
  17. +#include "Inode.h"
  18. +#include "Journal.h"
  19. +
  20. +
  21. +class InodeJournal : public Journal {
  22. +public:
  23. +                       InodeJournal(Inode* inode);
  24. +                       ~InodeJournal();
  25. +
  26. +           status_t    InitCheck();
  27. +          
  28. +           status_t    MapBlock(uint32 logical, uint32& physical);
  29. +private:
  30. +           Inode*      fInode;
  31. +           status_t    fInitStatus;
  32. +};
  33. +
  34. +#endif // INODEJOURNAL_H
  35. Index: src/add-ons/kernel/file_systems/ext2/InodeAllocator.cpp
  36. ===================================================================
  37. --- src/add-ons/kernel/file_systems/ext2/InodeAllocator.cpp (revision 0)
  38. +++ src/add-ons/kernel/file_systems/ext2/InodeAllocator.cpp (revision 0)
  39. @@ -0,0 +1,193 @@
  40. +/*
  41. + * Copyright 2001-2010, Haiku Inc. All rights reserved.
  42. + * This file may be used under the terms of the MIT License.
  43. + *
  44. + * Authors:
  45. + *     Janito V. Ferreira Filho
  46. + */
  47. +
  48. +
  49. +#include "InodeAllocator.h"
  50. +
  51. +#include <util/AutoLock.h>
  52. +
  53. +#include "BitmapBlock.h"
  54. +#include "Inode.h"
  55. +#include "Volume.h"
  56. +
  57. +
  58. +//#define TRACE_EXT2
  59. +#ifdef TRACE_EXT2
  60. +#  define TRACE(x...) dprintf("\33[34mext2:\33[0m " x)
  61. +#else
  62. +#  define TRACE(x...) ;
  63. +#endif
  64. +
  65. +
  66. +InodeAllocator::InodeAllocator(Volume* volume)
  67. +   :
  68. +   fVolume(volume)
  69. +{
  70. +   mutex_init(&fLock, "ext2 inode allocator");
  71. +}
  72. +
  73. +
  74. +InodeAllocator::~InodeAllocator()
  75. +{
  76. +   mutex_destroy(&fLock);
  77. +}
  78. +
  79. +
  80. +/*virtual*/ status_t
  81. +InodeAllocator::New(Transaction& transaction, Inode* parent, int32 mode,
  82. +   ino_t& id)
  83. +{
  84. +   // Apply allocation policy
  85. +   uint32 preferredBlockGroup = parent == NULL ? parent->ID()
  86. +       / parent->GetVolume()->InodesPerGroup() : 0;
  87. +  
  88. +   return _Allocate(transaction, preferredBlockGroup, S_ISDIR(mode), id);
  89. +}
  90. +
  91. +
  92. +/*virtual*/ status_t
  93. +InodeAllocator::Free(Transaction& transaction, ino_t id, bool isDirectory)
  94. +{
  95. +   TRACE("InodeAllocator::Free(%d, %c)\n", (int)id, isDirectory ? 't' : 'f');
  96. +   MutexLocker lock(fLock);
  97. +
  98. +   uint32 numInodes = fVolume->InodesPerGroup();
  99. +   uint32 blockGroup = (id - 1) / numInodes;
  100. +   ext2_block_group* group;
  101. +
  102. +   status_t status = fVolume->GetBlockGroup(blockGroup, &group);
  103. +   if (status != B_OK)
  104. +       return status;
  105. +
  106. +   if (blockGroup == fVolume->NumGroups() - 1)
  107. +       numInodes = fVolume->NumInodes() - blockGroup * numInodes;
  108. +
  109. +   TRACE("InodeAllocator::Free(): Updating block group data\n");
  110. +   group->SetFreeInodes(group->FreeInodes() + 1);
  111. +   if (isDirectory)
  112. +       group->SetUsedDirectories(group->UsedDirectories() - 1);
  113. +
  114. +   status = fVolume->WriteBlockGroup(transaction, blockGroup);
  115. +   if (status != B_OK)
  116. +       return status;
  117. +
  118. +   return _UnmarkInBitmap(transaction, group->InodeBitmap(), numInodes, id);
  119. +}
  120. +
  121. +
  122. +status_t
  123. +InodeAllocator::_Allocate(Transaction& transaction, uint32 preferredBlockGroup,
  124. +   bool isDirectory, ino_t& id)
  125. +{
  126. +   MutexLocker lock(fLock);
  127. +
  128. +   uint32 blockGroup = preferredBlockGroup;
  129. +   uint32 lastBlockGroup = fVolume->NumGroups() - 1;
  130. +
  131. +   for (int i = 0; i < 2; ++i) {
  132. +       for (; blockGroup < lastBlockGroup; ++blockGroup) {
  133. +           ext2_block_group* group;
  134. +
  135. +           status_t status = fVolume->GetBlockGroup(blockGroup, &group);
  136. +           if (status != B_OK)
  137. +               return status;
  138. +
  139. +           uint32 freeInodes = group->FreeInodes();
  140. +           if (freeInodes != 0) {
  141. +               group->SetFreeInodes(freeInodes - 1);
  142. +               if (isDirectory)
  143. +                   group->SetUsedDirectories(group->UsedDirectories() + 1);
  144. +
  145. +               status = fVolume->WriteBlockGroup(transaction, blockGroup);
  146. +               if (status != B_OK)
  147. +                   return status;
  148. +
  149. +               return _MarkInBitmap(transaction, group->InodeBitmap(),
  150. +                   blockGroup, fVolume->InodesPerGroup(), id);
  151. +           }
  152. +       }
  153. +
  154. +       if (i == 0) {
  155. +           ext2_block_group* group;
  156. +
  157. +           status_t status = fVolume->GetBlockGroup(blockGroup, &group);
  158. +           if (status != B_OK)
  159. +               return status;
  160. +
  161. +           uint32 freeInodes = group->FreeInodes();
  162. +           if (group->FreeInodes() != 0) {
  163. +               group->SetFreeInodes(freeInodes - 1);
  164. +
  165. +               return _MarkInBitmap(transaction, group->InodeBitmap(),
  166. +                   blockGroup, fVolume->NumInodes()
  167. +                       - blockGroup * fVolume->InodesPerGroup(), id);
  168. +           }
  169. +       }
  170. +
  171. +       blockGroup = 0;
  172. +       lastBlockGroup = preferredBlockGroup;
  173. +   }
  174. +
  175. +   return B_DEVICE_FULL;
  176. +}
  177. +
  178. +
  179. +status_t
  180. +InodeAllocator::_MarkInBitmap(Transaction& transaction, uint32 bitmapBlock,
  181. +   uint32 blockGroup, uint32 numInodes, ino_t& id)
  182. +{
  183. +   BitmapBlock inodeBitmap(fVolume, numInodes);
  184. +
  185. +   if (!inodeBitmap.SetToWritable(transaction, bitmapBlock)) {
  186. +       TRACE("Unable to open inode bitmap (block number: %lu) for block group "
  187. +           "%lu\n", bitmapBlock, blockGroup);
  188. +       return B_IO_ERROR;
  189. +   }
  190. +
  191. +   uint32 pos = 0;
  192. +   inodeBitmap.FindNextUnmarked(pos);
  193. +
  194. +   if (pos == inodeBitmap.NumBits()) {
  195. +       TRACE("Even though the block group %lu indicates there are free "
  196. +           "inodes, no unmarked bit was found in the inode bitmap at block "
  197. +           "%lu.", blockGroup, bitmapBlock);
  198. +       return B_ERROR;
  199. +   }
  200. +
  201. +   if (!inodeBitmap.Mark(pos, 1)) {
  202. +       TRACE("Failed to mark bit %lu at bitmap block %lu\n", pos,
  203. +           bitmapBlock);
  204. +       return B_BAD_DATA;
  205. +   }
  206. +
  207. +   id = pos + blockGroup * fVolume->InodesPerGroup() + 1;
  208. +
  209. +   return B_OK;
  210. +}
  211. +
  212. +
  213. +status_t
  214. +InodeAllocator::_UnmarkInBitmap(Transaction& transaction, uint32 bitmapBlock,
  215. +   uint32 numInodes, ino_t id)
  216. +{
  217. +   BitmapBlock inodeBitmap(fVolume, numInodes);
  218. +
  219. +   if (!inodeBitmap.SetToWritable(transaction, bitmapBlock)) {
  220. +       TRACE("Unable to open inode bitmap at block %lu\n", bitmapBlock);
  221. +       return B_IO_ERROR;
  222. +   }
  223. +
  224. +   uint32 pos = (id - 1) % fVolume->InodesPerGroup();
  225. +   if (!inodeBitmap.Unmark(pos, 1)) {
  226. +       TRACE("Unable to unmark bit %lu in inode bitmap block %lu\n", pos,
  227. +           bitmapBlock);
  228. +       return B_BAD_DATA;
  229. +   }
  230. +
  231. +   return B_OK;
  232. +}
  233.  
  234. Property changes on: src/add-ons/kernel/file_systems/ext2/InodeAllocator.cpp
  235. ___________________________________________________________________
  236. Added: svn:executable
  237.    + *
  238.  
  239. Index: src/add-ons/kernel/file_systems/ext2/BlockAllocator.h
  240. ===================================================================
  241. --- src/add-ons/kernel/file_systems/ext2/BlockAllocator.h   (revision 0)
  242. +++ src/add-ons/kernel/file_systems/ext2/BlockAllocator.h   (revision 0)
  243. @@ -0,0 +1,53 @@
  244. +/*
  245. + * Copyright 2001-2010, Haiku Inc. All rights reserved.
  246. + * This file may be used under the terms of the MIT License.
  247. + *
  248. + * Authors:
  249. + *     Janito V. Ferreira Filho
  250. + */
  251. +#ifndef BLOCKALLOCATOR_H
  252. +#define BLOCKALLOCATOR_H
  253. +
  254. +#include <lock.h>
  255. +
  256. +#include "Transaction.h"
  257. +
  258. +
  259. +class AllocationBlockGroup;
  260. +class Inode;
  261. +class Volume;
  262. +
  263. +
  264. +class BlockAllocator {
  265. +public:
  266. +                       BlockAllocator(Volume* volume);
  267. +                       ~BlockAllocator();
  268. +
  269. +           status_t    Initialize();
  270. +
  271. +           status_t    AllocateBlocks(Transaction& transaction,
  272. +                           uint32 minimum, uint32 maximum, uint32& blockGroup,
  273. +                           uint32& start, uint32& length);
  274. +           status_t    Allocate(Transaction& transaction, Inode* inode,
  275. +                           off_t numBlocks, uint32 minimum, uint32& start,
  276. +                           uint32& length);
  277. +           status_t    Free(Transaction& transaction, uint32 start,
  278. +                           uint32 length);
  279. +
  280. +           uint32      FreeBlocks();
  281. +
  282. +protected:
  283. +   static  status_t    _Initialize(BlockAllocator* allocator);
  284. +
  285. +
  286. +           Volume*     fVolume;
  287. +           mutex       fLock;
  288. +
  289. +           AllocationBlockGroup* fGroups;
  290. +           uint32      fBlocksPerGroup;
  291. +           uint32      fNumBlocks;
  292. +           uint32      fNumGroups;
  293. +           uint32      fFirstBlock;
  294. +};
  295. +
  296. +#endif // BLOCKALLOCATOR_H
  297.  
  298. Property changes on: src/add-ons/kernel/file_systems/ext2/BlockAllocator.h
  299. ___________________________________________________________________
  300. Added: svn:executable
  301.    + *
  302.  
  303. Index: src/add-ons/kernel/file_systems/ext2/HTreeEntryIterator.cpp
  304. ===================================================================
  305. --- src/add-ons/kernel/file_systems/ext2/HTreeEntryIterator.cpp (revision 38119)
  306. +++ src/add-ons/kernel/file_systems/ext2/HTreeEntryIterator.cpp (working copy)
  307. @@ -11,8 +11,8 @@
  308.  
  309.  #include <new>
  310.  
  311. +#include "CachedBlock.h"
  312.  #include "HTree.h"
  313. -#include "IndexedDirectoryIterator.h"
  314.  #include "Inode.h"
  315.  
  316.  
  317. @@ -27,81 +27,92 @@
  318.  
  319.  HTreeEntryIterator::HTreeEntryIterator(off_t offset, Inode* directory)
  320.     :
  321. +   fDirectory(directory),
  322. +   fVolume(directory->GetVolume()),
  323.     fHasCollision(false),
  324. -   fDirectory(directory),
  325. -   fOffset(offset),
  326. +   fBlockSize(directory->GetVolume()->BlockSize()),
  327.     fParent(NULL),
  328.     fChild(NULL)
  329.  {
  330. -   fBlockSize = fDirectory->GetVolume()->BlockSize();
  331. +   fInitStatus = fDirectory->FindBlock(offset, fBlockNum);
  332. +  
  333. +   if (fInitStatus == B_OK) {
  334. +       fFirstEntry = offset % fBlockSize / sizeof(HTreeEntry);
  335. +       fCurrentEntry = fFirstEntry;
  336. +   }
  337. +
  338. +   TRACE("HTreeEntryIterator::HTreeEntryIterator() block %lu entry no. %lu\n",
  339. +       fBlockNum, (uint32)fCurrentEntry);
  340.  }
  341.  
  342.  
  343.  HTreeEntryIterator::HTreeEntryIterator(uint32 block, uint32 blockSize,
  344.     Inode* directory, HTreeEntryIterator* parent, bool hasCollision)
  345.     :
  346. +   fDirectory(directory),
  347. +   fVolume(directory->GetVolume()),
  348.     fHasCollision(hasCollision),
  349. +   fFirstEntry(1),
  350. +   fCurrentEntry(1),
  351.     fBlockSize(blockSize),
  352. -   fDirectory(directory),
  353. -   fOffset(block * blockSize + sizeof(HTreeFakeDirEntry)),
  354. +   fBlockNum(block),
  355.     fParent(parent),
  356.     fChild(NULL)
  357.  {
  358. -   TRACE("HTreeEntryIterator::HTreeEntryIterator() block %ld offset %Lx\n",
  359. -       block, fOffset);
  360. +   // fCurrentEntry is initialized to 1 to skip the fake directory entry
  361. +   fInitStatus = B_OK;
  362. +
  363. +   TRACE("HTreeEntryIterator::HTreeEntryIterator() block %lu\n", block);
  364.  }
  365.  
  366.  
  367.  status_t
  368.  HTreeEntryIterator::Init()
  369.  {
  370. -   size_t length = sizeof(HTreeCountLimit);
  371. -   HTreeCountLimit countLimit;
  372. +   TRACE("HTreeEntryIterator::Init() first entry: %lu\n",
  373. +       (uint32)fFirstEntry);
  374.    
  375. -   status_t status = fDirectory->ReadAt(fOffset, (uint8*)&countLimit,
  376. -       &length);
  377. -  
  378. -   if (status != B_OK)
  379. -       return status;
  380. -  
  381. -   if (length != sizeof(HTreeCountLimit)) {
  382. -       ERROR("HTreeEntryIterator::Init() bad length %ld fOffset 0x%Lx\n",
  383. -           length, fOffset);
  384. +   if (fInitStatus != B_OK)
  385. +       return fInitStatus;
  386. +
  387. +   CachedBlock cached(fVolume);
  388. +   const uint8* block = cached.SetTo(fBlockNum);
  389. +   if (block == NULL) {
  390. +       ERROR("Failed to read htree entry block.\n");
  391.         fCount = fLimit = 0;
  392. -       return B_ERROR;
  393. +       return B_IO_ERROR;
  394.     }
  395. -  
  396. -   fCount = countLimit.Count();
  397. -   fLimit = countLimit.Limit();
  398.  
  399. +   HTreeCountLimit* countLimit = (HTreeCountLimit*)(
  400. +       &((HTreeEntry*)block)[fFirstEntry]);
  401. +
  402. +   fCount = countLimit->Count();
  403. +   fLimit = countLimit->Limit();
  404. +
  405.     if (fCount >= fLimit) {
  406. -       ERROR("HTreeEntryIterator::Init() bad fCount %d fOffset 0x%Lx\n",
  407. -           fCount, fOffset);
  408. +       ERROR("HTreeEntryIterator::Init() bad fCount %lu\n", (uint32)fCount);
  409.         fCount = fLimit = 0;
  410.         return B_ERROR;
  411.     }
  412.  
  413. -   if (fParent != NULL &&
  414. -       fLimit != ((fBlockSize - sizeof(HTreeFakeDirEntry))
  415. -           / sizeof(HTreeEntry)) ) {
  416. -       ERROR("HTreeEntryIterator::Init() bad fLimit %d should be %ld "
  417. -           "fOffset 0x%Lx\n", fLimit, (fBlockSize - sizeof(HTreeFakeDirEntry))
  418. -               / sizeof(HTreeEntry), fOffset);
  419. +   if (fLimit != fBlockSize / sizeof(HTreeEntry) - fFirstEntry) {
  420. +       ERROR("HTreeEntryIterator::Init() bad fLimit %lu should be %lu "
  421. +           "at block %lu\n", (uint32)fLimit, fBlockSize / sizeof(HTreeEntry)
  422. +               - fFirstEntry, fBlockNum);
  423.         fCount = fLimit = 0;
  424.         return B_ERROR;
  425. -   }
  426. +   }
  427.  
  428. -   TRACE("HTreeEntryIterator::Init() count 0x%x limit 0x%x\n", fCount,
  429. -       fLimit);
  430. +   TRACE("HTreeEntryIterator::Init() count %lu limit %lu\n",
  431. +       (uint32)fCount, (uint32)fLimit);
  432.  
  433. -   fMaxOffset = fOffset + (fCount - 1) * sizeof(HTreeEntry);
  434. -  
  435.     return B_OK;
  436.  }
  437.  
  438.  
  439.  HTreeEntryIterator::~HTreeEntryIterator()
  440.  {
  441. +   delete fChild;
  442.  }
  443.  
  444.  
  445. @@ -109,68 +120,80 @@
  446.  HTreeEntryIterator::Lookup(uint32 hash, int indirections,
  447.     DirectoryIterator** directoryIterator)
  448.  {
  449. -   off_t start = fOffset + sizeof(HTreeEntry);
  450. -   off_t end = fMaxOffset;
  451. -   off_t middle = start;
  452. -   size_t entrySize = sizeof(HTreeEntry);
  453. -   HTreeEntry entry;
  454. +   TRACE("HTreeEntryIterator::Lookup()\n");
  455. +
  456. +   if (fCount == 0)
  457. +       return B_ENTRY_NOT_FOUND;
  458. +
  459. +   CachedBlock cached(fVolume);
  460. +   const uint8* block = cached.SetTo(fBlockNum);
  461. +   if (block == NULL) {
  462. +       ERROR("Failed to read htree entry block.\n");
  463. +       // Fallback to linear search
  464. +       *directoryIterator = new(std::nothrow)
  465. +           DirectoryIterator(fDirectory);
  466. +
  467. +       if (*directoryIterator == NULL)
  468. +           return B_NO_MEMORY;
  469. +
  470. +       return B_OK;
  471. +   }
  472. +
  473. +   HTreeEntry* start = (HTreeEntry*)block + fCurrentEntry + 1;
  474. +   HTreeEntry* end = (HTreeEntry*)block + fCount + fFirstEntry - 1;
  475. +   HTreeEntry* middle = start;
  476.    
  477. +   TRACE("HTreeEntryIterator::Lookup() current entry: %lu\n",
  478. +       (uint32)fCurrentEntry);
  479. +   TRACE("HTreeEntryIterator::Lookup() indirections: %d s:%p m:%p e:%p\n",
  480. +       indirections, start, middle, end);
  481. +
  482.     while (start <= end) {
  483. -       middle = (end - start) / 2;
  484. -       middle -= middle % entrySize; // Alignment
  485. -       middle += start;
  486. +       middle = (HTreeEntry*)((end - start) / 2
  487. +           + start);
  488.  
  489. -       TRACE("HTreeEntryIterator::Lookup() %d 0x%Lx 0x%Lx 0x%Lx\n",
  490. -           indirections, start, end, middle);
  491. -      
  492. -       status_t status = fDirectory->ReadAt(middle, (uint8*)&entry,
  493. -           &entrySize);
  494. +       TRACE("HTreeEntryIterator::Lookup() indirections: %d s:%p m:%p e:%p\n",
  495. +           indirections, start, middle, end);
  496.  
  497. -       TRACE("HTreeEntryIterator::Lookup() %lx %lx\n", hash, entry.Hash());
  498. -      
  499. -       if (status != B_OK)
  500. -           return status;
  501. -       else if (entrySize != sizeof(entry)) {
  502. -           // Fallback to linear search
  503. -           *directoryIterator = new(std::nothrow)
  504. -               DirectoryIterator(fDirectory);
  505. -          
  506. -           if (*directoryIterator == NULL)
  507. -               return B_NO_MEMORY;
  508. -          
  509. -           return B_OK;
  510. -       }
  511. -      
  512. -       if (hash >= entry.Hash())
  513. -           start = middle + entrySize;
  514. +       TRACE("HTreeEntryIterator::Lookup() %lx %lx\n", hash, middle->Hash());
  515. +
  516. +       if (hash >= middle->Hash())
  517. +           start = middle + 1;
  518.         else
  519. -           end = middle - entrySize;
  520. +           end = middle - 1;
  521.     }
  522.  
  523. -   status_t status = fDirectory->ReadAt(start - entrySize, (uint8*)&entry,
  524. -       &entrySize);
  525. -   if (status != B_OK)
  526. -       return status;
  527. -  
  528. +   --start;
  529. +
  530. +   fCurrentEntry = ((uint8*)start - block) / sizeof(HTreeEntry);
  531. +
  532.     if (indirections == 0) {
  533. +       TRACE("HTreeEntryIterator::Lookup(): Creating an indexed directory "
  534. +           "iterator starting at block: %lu, hash: 0x%lX\n", start->Block(),
  535. +           start->Hash());
  536.         *directoryIterator = new(std::nothrow)
  537. -           IndexedDirectoryIterator(entry.Block() * fBlockSize, fBlockSize,
  538. -           fDirectory, this);
  539. -      
  540. +           DirectoryIterator(fDirectory, start->Block() * fBlockSize, this);
  541. +
  542.         if (*directoryIterator == NULL)
  543.             return B_NO_MEMORY;
  544.  
  545.         return B_OK;
  546.     }
  547.  
  548. +   TRACE("HTreeEntryIterator::Lookup(): Creating a HTree entry iterator "
  549. +       "starting at block: %lu, hash: 0x%lX\n", start->Block(), start->Hash());
  550. +   uint32 blockNum;
  551. +   status_t status = fDirectory->FindBlock(start->Block() * fBlockSize,
  552. +       blockNum);
  553. +   if (status != B_OK)
  554. +       return status;
  555. +
  556.     delete fChild;
  557.  
  558. -   fChild = new(std::nothrow) HTreeEntryIterator(entry.Block(), fBlockSize,
  559. -       fDirectory, this, entry.Hash() & 1 == 1);
  560. -  
  561. +   fChild = new(std::nothrow) HTreeEntryIterator(blockNum, fBlockSize,
  562. +       fDirectory, this, start->Hash() & 1 == 1);
  563.     if (fChild == NULL)
  564.         return B_NO_MEMORY;
  565. -   fChildDeleter.SetTo(fChild);
  566.    
  567.     status = fChild->Init();
  568.     if (status != B_OK)
  569. @@ -181,40 +204,62 @@
  570.  
  571.  
  572.  status_t
  573. -HTreeEntryIterator::GetNext(off_t& childOffset)
  574. +HTreeEntryIterator::GetNext(uint32& childBlock)
  575.  {
  576. -   size_t entrySize = sizeof(HTreeEntry);
  577. -   fOffset += entrySize;
  578. -   bool firstEntry = fOffset >= fMaxOffset;
  579. -  
  580. -   if (firstEntry) {
  581. -       if (fParent == NULL)
  582. +   fCurrentEntry++;
  583. +   TRACE("HTreeEntryIterator::GetNext(): current entry: %lu\n",
  584. +       (uint32)fCurrentEntry);
  585. +   bool endOfBlock = fCurrentEntry >= (fCount + fFirstEntry);
  586. +
  587. +   if (endOfBlock) {
  588. +       TRACE("HTreeEntryIterator::GetNext(): end of entries in the block\n");
  589. +       if (fParent == NULL) {
  590. +           TRACE("HTreeEntryIterator::GetNext(): block was the root block\n");
  591.             return B_ENTRY_NOT_FOUND;
  592. +       }
  593.        
  594. -       status_t status = fParent->GetNext(fOffset);
  595. +       uint32 logicalBlock;
  596. +       status_t status = fParent->GetNext(logicalBlock);
  597.         if (status != B_OK)
  598.             return status;
  599.        
  600. +       TRACE("HTreeEntryIterator::GetNext(): moving to next block: %lu\n",
  601. +           logicalBlock);
  602. +      
  603. +       status = fDirectory->FindBlock(logicalBlock * fBlockSize, fBlockNum);
  604. +       if (status != B_OK)
  605. +           return status;
  606. +      
  607. +       fFirstEntry = 1; // Skip fake directory entry
  608. +       fCurrentEntry = 1;
  609.         status = Init();
  610.         if (status != B_OK)
  611.             return status;
  612.  
  613.         fHasCollision = fParent->HasCollision();
  614.     }
  615. +
  616. +   CachedBlock cached(fVolume);
  617. +   const uint8* block = cached.SetTo(fBlockNum);
  618. +   if (block == NULL)
  619. +       return B_IO_ERROR;
  620. +
  621. +   HTreeEntry* entry = &((HTreeEntry*)block)[fCurrentEntry];
  622. +
  623. +   if (!endOfBlock)
  624. +       fHasCollision = (entry[fCurrentEntry].Hash() & 1) == 1;
  625.    
  626. -   HTreeEntry entry;
  627. -   status_t status = fDirectory->ReadAt(fOffset, (uint8*)&entry, &entrySize);
  628. -   if (status != B_OK)
  629. -       return status;
  630. -   else if (entrySize != sizeof(entry)) {
  631. -       // Weird error, try to skip it
  632. -       return GetNext(childOffset);
  633. -   }
  634. +   TRACE("HTreeEntryIterator::GetNext(): next block: %lu\n",
  635. +       entry->Block());
  636. +
  637. +   childBlock = entry->Block();
  638.    
  639. -   if (!firstEntry)
  640. -       fHasCollision = (entry.Hash() & 1) == 1;
  641. -  
  642. -   childOffset = entry.Block() * fBlockSize;
  643. -  
  644.     return B_OK;
  645.  }
  646. +
  647. +
  648. +status_t
  649. +HTreeEntryIterator::InsertEntry(uint32 hash, uint32 block, bool hasCollision)
  650. +{
  651. +   return B_OK;
  652. +}
  653. Index: src/add-ons/kernel/file_systems/ext2/Inode.h
  654. ===================================================================
  655. --- src/add-ons/kernel/file_systems/ext2/Inode.h    (revision 38119)
  656. +++ src/add-ons/kernel/file_systems/ext2/Inode.h    (working copy)
  657. @@ -6,13 +6,15 @@
  658.  #define INODE_H
  659.  
  660.  
  661. +#include <fs_cache.h>
  662.  #include <lock.h>
  663. +#include <string.h>
  664.  
  665.  #include "ext2.h"
  666.  #include "Volume.h"
  667.  
  668.  
  669. -class Inode {
  670. +class Inode : public TransactionListener {
  671.  public:
  672.                         Inode(Volume* volume, ino_t id);
  673.                         ~Inode();
  674. @@ -22,54 +24,204 @@
  675.             ino_t       ID() const { return fID; }
  676.  
  677.             rw_lock*    Lock() { return &fLock; }
  678. +           void        WriteLockInTransaction(Transaction& transaction);
  679.  
  680. +           status_t    UpdateNodeFromDisk();
  681. +           status_t    WriteBack(Transaction& transaction);
  682. +
  683.             bool        IsDirectory() const
  684.                             { return S_ISDIR(Mode()); }
  685.             bool        IsFile() const
  686.                             { return S_ISREG(Mode()); }
  687.             bool        IsSymLink() const
  688.                             { return S_ISLNK(Mode()); }
  689. -
  690.             status_t    CheckPermissions(int accessMode) const;
  691.  
  692. -           mode_t      Mode() const { return fNode->Mode(); }
  693. -           int32       Flags() const { return fNode->Flags(); }
  694. +           bool        IsDeleted() const { return fUnlinked; }
  695.  
  696. -           off_t       Size() const { return fNode->Size(); }
  697. +           mode_t      Mode() const { return fNode.Mode(); }
  698. +           int32       Flags() const { return fNode.Flags(); }
  699. +
  700. +           off_t       Size() const { return fNode.Size(); }
  701.             time_t      ModificationTime() const
  702. -                           { return fNode->ModificationTime(); }
  703. +                           { return fNode.ModificationTime(); }
  704.             time_t      CreationTime() const
  705. -                           { return fNode->CreationTime(); }
  706. +                           { return fNode.CreationTime(); }
  707.             time_t      AccessTime() const
  708. -                           { return fNode->AccessTime(); }
  709. +                           { return fNode.AccessTime(); }
  710.  
  711.             //::Volume* _Volume() const { return fVolume; }
  712.             Volume*     GetVolume() const { return fVolume; }
  713.  
  714.             status_t    FindBlock(off_t offset, uint32& block);
  715.             status_t    ReadAt(off_t pos, uint8 *buffer, size_t *length);
  716. +           status_t    WriteAt(Transaction& transaction, off_t pos,
  717. +                           const uint8* buffer, size_t* length);
  718. +           status_t    FillGapWithZeros(off_t start, off_t end);
  719.  
  720. +           status_t    Resize(Transaction& transaction, off_t size);
  721. +
  722.             status_t    AttributeBlockReadAt(off_t pos, uint8 *buffer,
  723.                             size_t *length);
  724.  
  725. -           ext2_inode& Node() { return *fNode; }
  726. +           ext2_inode& Node() { return fNode; }
  727.  
  728. +           status_t    InitDirectory(Transaction& transaction, Inode* parent);
  729. +
  730. +           status_t    Unlink(Transaction& transaction);
  731. +
  732. +   static  status_t    Create(Transaction& transaction, Inode* parent,
  733. +                           const char* name, int32 mode, int openMode,
  734. +                           uint8 type, bool* _created = NULL,
  735. +                           ino_t* _id = NULL, Inode** _inode = NULL,
  736. +                           fs_vnode_ops* vnodeOps = NULL,
  737. +                           uint32 publishFlags = 0);
  738. +
  739.             void*       FileCache() const { return fCache; }
  740.             void*       Map() const { return fMap; }
  741. +           status_t    EnableFileCache();
  742. +           status_t    DisableFileCache();
  743. +           bool        IsFileCacheDisabled() const { return !fCached; }
  744.  
  745. +           status_t    Sync();
  746. +
  747. +protected:
  748. +   virtual void        TransactionDone(bool success);
  749. +   virtual void        RemovedFromTransaction();
  750. +
  751. +
  752.  private:
  753. +                       Inode(Volume* volume);
  754.                         Inode(const Inode&);
  755.                         Inode &operator=(const Inode&);
  756.                             // no implementation
  757.  
  758. +           status_t    _EnlargeDataStream(Transaction& transaction,
  759. +                           off_t size);
  760. +           status_t    _ShrinkDataStream(Transaction& transaction, off_t size);
  761. +
  762. +
  763. +           rw_lock     fLock;
  764. +           ::Volume*   fVolume;
  765. +           ino_t       fID;
  766. +           void*       fCache;
  767. +           void*       fMap;
  768. +           bool        fCached;
  769. +           bool        fUnlinked;
  770. +           ext2_inode  fNode;
  771. +           uint32      fNodeSize;
  772. +               // Inodes have a varible size, but the important
  773. +               // information is always the same size (except in ext4)
  774. +           ext2_xattr_header* fAttributesBlock;
  775. +           status_t    fInitStatus;
  776. +};
  777. +
  778. +
  779. +// The Vnode class provides a convenience layer upon get_vnode(), so that
  780. +// you don't have to call put_vnode() anymore, which may make code more
  781. +// readable in some cases
  782. +
  783. +class Vnode {
  784. +public:
  785. +   Vnode(Volume* volume, ino_t id)
  786. +       :
  787. +       fInode(NULL)
  788. +   {
  789. +       SetTo(volume, id);
  790. +   }
  791. +
  792. +   Vnode()
  793. +       :
  794. +       fStatus(B_NO_INIT),
  795. +       fInode(NULL)
  796. +   {
  797. +   }
  798. +
  799. +   ~Vnode()
  800. +   {
  801. +       Unset();
  802. +   }
  803. +
  804. +   status_t InitCheck()
  805. +   {
  806. +       return fStatus;
  807. +   }
  808. +
  809. +   void Unset()
  810. +   {
  811. +       if (fInode != NULL) {
  812. +           put_vnode(fInode->GetVolume()->FSVolume(), fInode->ID());
  813. +           fInode = NULL;
  814. +           fStatus = B_NO_INIT;
  815. +       }
  816. +   }
  817. +
  818. +   status_t SetTo(Volume* volume, ino_t id)
  819. +   {
  820. +       Unset();
  821. +
  822. +       return fStatus = get_vnode(volume->FSVolume(), id, (void**)&fInode);
  823. +   }
  824. +
  825. +   status_t Get(Inode** _inode)
  826. +   {
  827. +       *_inode = fInode;
  828. +       return fStatus;
  829. +   }
  830. +
  831. +   void Keep()
  832. +   {
  833. +       dprintf("Vnode::Keep()\n");
  834. +       fInode = NULL;
  835. +   }
  836. +
  837. +   status_t Publish(Transaction& transaction, Inode* inode,
  838. +       fs_vnode_ops* vnodeOps, uint32 publishFlags)
  839. +   {
  840. +       dprintf("Vnode::Publish()\n");
  841. +       Volume* volume = transaction.GetVolume();
  842. +
  843. +       status_t status = B_OK;
  844. +
  845. +       if (!inode->IsSymLink() && volume->ID() >= 0) {
  846. +           dprintf("Vnode::Publish(): Publishing vnode: %d, %d, %p, %p, %x, "
  847. +               "%x\n", (int)volume->FSVolume(), (int)inode->ID(), inode,
  848. +               vnodeOps != NULL ? vnodeOps : &gExt2VnodeOps, (int)inode->Mode(),
  849. +               (int)publishFlags);
  850. +           status = publish_vnode(volume->FSVolume(), inode->ID(), inode,
  851. +               vnodeOps != NULL ? vnodeOps : &gExt2VnodeOps, inode->Mode(),
  852. +               publishFlags);
  853. +           dprintf("Vnode::Publish(): Result: %s\n", strerror(status));
  854. +       }
  855. +
  856. +       if (status == B_OK) {
  857. +           dprintf("Vnode::Publish(): Preparing internal data\n");
  858. +           fInode = inode;
  859. +           fStatus = B_OK;
  860. +
  861. +           cache_add_transaction_listener(volume->BlockCache(),
  862. +               transaction.ID(), TRANSACTION_ABORTED, &_TransactionListener,
  863. +               inode);
  864. +       }
  865. +
  866. +       return status;
  867. +   }
  868. +
  869.  private:
  870. -   rw_lock             fLock;
  871. -   ::Volume*           fVolume;
  872. -   ino_t               fID;
  873. -   void*               fCache;
  874. -   void*               fMap;
  875. -   ext2_inode*         fNode;
  876. -   ext2_xattr_header*  fAttributesBlock;
  877. +   status_t    fStatus;
  878. +   Inode*      fInode;
  879. +
  880. +   // TODO: How to apply coding style here?
  881. +   static void _TransactionListener(int32 id, int32 event, void* _inode)
  882. +   {
  883. +       Inode* inode = (Inode*)_inode;
  884. +
  885. +       if (event == TRANSACTION_ABORTED) {
  886. +           // TODO: Unpublish?
  887. +           panic("Transaction %d aborted, inode %p still exists!\n", (int)id,
  888. +               inode);
  889. +       }
  890. +   }
  891.  };
  892.  
  893.  #endif // INODE_H
  894. Index: src/add-ons/kernel/file_systems/ext2/Volume.cpp
  895. ===================================================================
  896. --- src/add-ons/kernel/file_systems/ext2/Volume.cpp (revision 38119)
  897. +++ src/add-ons/kernel/file_systems/ext2/Volume.cpp (working copy)
  898. @@ -20,7 +20,10 @@
  899.  
  900.  #include <util/AutoLock.h>
  901.  
  902. +#include "CachedBlock.h"
  903.  #include "Inode.h"
  904. +#include "InodeJournal.h"
  905. +#include "NoJournal.h"
  906.  
  907.  
  908.  //#define TRACE_EXT2
  909. @@ -199,7 +202,7 @@
  910.     // TODO: check some more values!
  911.     if (Magic() != (uint32)EXT2_SUPER_BLOCK_MAGIC)
  912.         return false;
  913. -
  914. +  
  915.     return true;
  916.  }
  917.  
  918. @@ -210,6 +213,9 @@
  919.  Volume::Volume(fs_volume* volume)
  920.     :
  921.     fFSVolume(volume),
  922. +   fBlockAllocator(this),
  923. +   fInodeAllocator(this),
  924. +   fJournalInode(NULL),
  925.     fFlags(0),
  926.     fGroupBlocks(NULL),
  927.     fRootNode(NULL)
  928. @@ -220,6 +226,7 @@
  929.  
  930.  Volume::~Volume()
  931.  {
  932. +   TRACE("Volume destructor.\n");
  933.     if (fGroupBlocks != NULL) {
  934.         uint32 blockCount = (fNumGroups + fGroupsPerBlock - 1)
  935.             / fGroupsPerBlock;
  936. @@ -252,8 +259,14 @@
  937.  status_t
  938.  Volume::Mount(const char* deviceName, uint32 flags)
  939.  {
  940. -   flags |= B_MOUNT_READ_ONLY;
  941. +   // flags |= B_MOUNT_READ_ONLY;
  942.         // we only support read-only for now
  943. +  
  944. +   if ((flags & B_MOUNT_READ_ONLY) != 0) {
  945. +       TRACE("Volume::Mount(): Read only\n");
  946. +   } else {
  947. +       TRACE("Volume::Mount(): Read write\n");
  948. +   }
  949.  
  950.     DeviceOpener opener(deviceName, (flags & B_MOUNT_READ_ONLY) != 0
  951.         ? O_RDONLY : O_RDWR);
  952. @@ -278,10 +291,17 @@
  953.     fBlockSize = 1UL << fSuperBlock.BlockShift();
  954.     fFirstDataBlock = fSuperBlock.FirstDataBlock();
  955.  
  956. +   fFreeBlocks = fSuperBlock.FreeBlocks();
  957. +   fFreeInodes = fSuperBlock.FreeInodes();
  958. +
  959. +   uint32 numBlocks = fSuperBlock.NumBlocks() - fFirstDataBlock;
  960. +   uint32 blocksPerGroup = fSuperBlock.BlocksPerGroup();
  961. +   fNumGroups = numBlocks / blocksPerGroup;
  962. +   if (numBlocks % blocksPerGroup != 0)
  963. +       fNumGroups++;
  964. +
  965. +   fGroupsPerBlock = fBlockSize / sizeof(ext2_block_group);
  966.     fNumInodes = fSuperBlock.NumInodes();
  967. -   fNumGroups = (fSuperBlock.NumBlocks() - fFirstDataBlock - 1)
  968. -       / fSuperBlock.BlocksPerGroup() + 1;
  969. -   fGroupsPerBlock = fBlockSize / sizeof(ext2_block_group);
  970.  
  971.     TRACE("block size %ld, num groups %ld, groups per block %ld, first %lu\n",
  972.         fBlockSize, fNumGroups, fGroupsPerBlock, fFirstDataBlock);
  973. @@ -309,7 +329,59 @@
  974.     fBlockCache = opener.InitCache(NumBlocks(), fBlockSize);
  975.     if (fBlockCache == NULL)
  976.         return B_ERROR;
  977. +  
  978. +   TRACE("Volume::Mount(): Initialized block cache: %p\n", fBlockCache);
  979.  
  980. +   // initialize journal
  981. +   if ((fSuperBlock.CompatibleFeatures() & EXT2_FEATURE_HAS_JOURNAL) != 0) {
  982. +       // TODO: There should be a mount option to ignore the existent journal
  983. +       if (fSuperBlock.JournalInode() != 0) {
  984. +           fJournalInode = new(std::nothrow) Inode(this,
  985. +               fSuperBlock.JournalInode());
  986. +
  987. +           if (fJournalInode == NULL)
  988. +               return B_NO_MEMORY;
  989. +
  990. +           TRACE("Opening an on disk, inode mapped journal.\n");
  991. +           fJournal = new(std::nothrow) InodeJournal(fJournalInode);
  992. +       } else {
  993. +           // TODO: external journal
  994. +           TRACE("Can not open an external journal.\n");
  995. +           return B_NOT_SUPPORTED;
  996. +       }
  997. +   } else {
  998. +       TRACE("Opening a fake journal (NoJournal).\n");
  999. +       fJournal = new(std::nothrow) NoJournal(this);
  1000. +   }
  1001. +
  1002. +   if (fJournal == NULL) {
  1003. +       TRACE("No memory to create the journal\n");
  1004. +       return B_NO_MEMORY;
  1005. +   }
  1006. +
  1007. +   TRACE("Volume::Mount(): Checking if journal was initialized\n");
  1008. +   status = fJournal->InitCheck();
  1009. +   if (status != B_OK)
  1010. +       return status;
  1011. +
  1012. +   // TODO: Only recover if asked to
  1013. +   TRACE("Volume::Mount(): Asking journal to recover\n");
  1014. +   status = fJournal->Recover();
  1015. +   if (status != B_OK)
  1016. +       return status;
  1017. +
  1018. +   TRACE("Volume::Mount(): Restart journal log\n");
  1019. +   status = fJournal->StartLog();
  1020. +   if (status != B_OK)
  1021. +       return status;
  1022. +
  1023. +   // Initialize allocators
  1024. +   TRACE("Volume::Mount(): Initialize block allocator\n");
  1025. +   status = fBlockAllocator.Initialize();
  1026. +   if (status != B_OK)
  1027. +       return status;
  1028. +
  1029. +   // ready
  1030.     status = get_vnode(fFSVolume, EXT2_ROOT_NODE, (void**)&fRootNode);
  1031.     if (status != B_OK) {
  1032.         TRACE("could not create root node: get_vnode() failed!\n");
  1033. @@ -342,11 +414,22 @@
  1034.  status_t
  1035.  Volume::Unmount()
  1036.  {
  1037. +   TRACE("Volume::Unmount()\n");
  1038. +
  1039. +   status_t status = fJournal->Uninit();
  1040. +
  1041. +   delete fJournal;
  1042. +   delete fJournalInode;
  1043. +
  1044. +   TRACE("Volume::Unmount(): Putting root node\n");
  1045.     put_vnode(fFSVolume, RootNode()->ID());
  1046. +   TRACE("Volume::Unmount(): Deleting the block cache\n");
  1047.     block_cache_delete(fBlockCache, !IsReadOnly());
  1048. +   TRACE("Volume::Unmount(): Closing device\n");
  1049.     close(fDevice);
  1050.  
  1051. -   return B_OK;
  1052. +   TRACE("Volume::Unmount(): Done\n");
  1053. +   return status;
  1054.  }
  1055.  
  1056.  
  1057. @@ -391,13 +474,13 @@
  1058.  }
  1059.  
  1060.  
  1061. -off_t
  1062. -Volume::_GroupBlockOffset(uint32 blockIndex)
  1063. +uint32
  1064. +Volume::_GroupDescriptorBlock(uint32 blockIndex)
  1065.  {
  1066.     if ((fSuperBlock.IncompatibleFeatures()
  1067.             & EXT2_INCOMPATIBLE_FEATURE_META_GROUP) == 0
  1068.         || blockIndex < fSuperBlock.FirstMetaBlockGroup())
  1069. -       return off_t(fFirstDataBlock + blockIndex + 1) << fBlockShift;
  1070. +       return fFirstDataBlock + blockIndex + 1;
  1071.  
  1072.     panic("meta block");
  1073.     return 0;
  1074. @@ -419,18 +502,16 @@
  1075.     MutexLocker _(fLock);
  1076.  
  1077.     if (fGroupBlocks[blockIndex] == NULL) {
  1078. +       CachedBlock cached(this);
  1079. +       const uint8* block = cached.SetTo(_GroupDescriptorBlock(blockIndex));
  1080. +       if (block == NULL)
  1081. +           return B_IO_ERROR;
  1082. +
  1083.         ext2_block_group* groupBlock = (ext2_block_group*)malloc(fBlockSize);
  1084.         if (groupBlock == NULL)
  1085.             return B_NO_MEMORY;
  1086.  
  1087. -       ssize_t bytesRead = read_pos(fDevice, _GroupBlockOffset(blockIndex),
  1088. -           groupBlock, fBlockSize);
  1089. -       if (bytesRead >= B_OK && (uint32)bytesRead != fBlockSize)
  1090. -           bytesRead = B_IO_ERROR;
  1091. -       if (bytesRead < B_OK) {
  1092. -           free(groupBlock);
  1093. -           return bytesRead;
  1094. -       }
  1095. +       memcpy((uint8*)groupBlock, block, fBlockSize);
  1096.  
  1097.         fGroupBlocks[blockIndex] = groupBlock;
  1098.  
  1099. @@ -443,6 +524,261 @@
  1100.  }
  1101.  
  1102.  
  1103. +status_t
  1104. +Volume::WriteBlockGroup(Transaction& transaction, int32 index)
  1105. +{
  1106. +   if (index < 0 || (uint32)index > fNumGroups)
  1107. +       return B_BAD_VALUE;
  1108. +
  1109. +   TRACE("Volume::WriteBlockGroup()\n");
  1110. +
  1111. +   int32 blockIndex = index / fGroupsPerBlock;
  1112. +
  1113. +   MutexLocker _(fLock);
  1114. +
  1115. +   if (fGroupBlocks[blockIndex] == NULL)
  1116. +       return B_BAD_VALUE;
  1117. +
  1118. +   CachedBlock cached(this);
  1119. +   uint8* block = cached.SetToWritable(transaction,
  1120. +       _GroupDescriptorBlock(blockIndex));
  1121. +   if (block == NULL)
  1122. +       return B_IO_ERROR;
  1123. +
  1124. +   memcpy(block, (const uint8*)fGroupBlocks[blockIndex], fBlockSize);
  1125. +
  1126. +   // TODO: Write copies
  1127. +
  1128. +   return B_OK;
  1129. +}
  1130. +
  1131. +
  1132. +status_t
  1133. +Volume::SaveOrphan(Transaction& transaction, ino_t newID, ino_t& oldID)
  1134. +{
  1135. +   oldID = fSuperBlock.LastOrphan();
  1136. +   TRACE("Volume::SaveOrphan(): Old: %d, New: %d\n", (int)oldID, (int)newID);
  1137. +   fSuperBlock.SetLastOrphan(newID);
  1138. +
  1139. +   return WriteSuperBlock(transaction);
  1140. +}
  1141. +
  1142. +
  1143. +status_t
  1144. +Volume::RemoveOrphan(Transaction& transaction, ino_t id)
  1145. +{
  1146. +   ino_t currentID = fSuperBlock.LastOrphan();
  1147. +   TRACE("Volume::RemoveOrphan(): ID: %d\n", (int)id);
  1148. +   if (currentID == 0)
  1149. +       return B_OK;
  1150. +
  1151. +   CachedBlock cached(this);
  1152. +
  1153. +   uint32 blockNum;
  1154. +   status_t status = GetInodeBlock(currentID, blockNum);
  1155. +   if (status != B_OK)
  1156. +       return status;
  1157. +
  1158. +   uint8* block = cached.SetToWritable(transaction, blockNum);
  1159. +   if (block == NULL)
  1160. +       return B_IO_ERROR;
  1161. +
  1162. +   ext2_inode* inode = (ext2_inode*)(block
  1163. +       + InodeBlockIndex(currentID) * InodeSize());
  1164. +  
  1165. +   if (currentID == id) {
  1166. +       TRACE("Volume::RemoveOrphan(): First entry. Updating head to: %d\n",
  1167. +           (int)inode->NextOrphan());
  1168. +       fSuperBlock.SetLastOrphan(inode->NextOrphan());
  1169. +
  1170. +       return WriteSuperBlock(transaction);
  1171. +   }
  1172. +
  1173. +   currentID = inode->NextOrphan();
  1174. +   if (currentID == 0)
  1175. +       return B_OK;
  1176. +
  1177. +   do {
  1178. +       uint32 lastBlockNum = blockNum;
  1179. +       status = GetInodeBlock(currentID, blockNum);
  1180. +       if (status != B_OK)
  1181. +           return status;
  1182. +
  1183. +       if (blockNum != lastBlockNum) {
  1184. +           block = cached.SetToWritable(transaction, blockNum);
  1185. +           if (block == NULL)
  1186. +               return B_IO_ERROR;
  1187. +       }
  1188. +
  1189. +       ext2_inode* inode = (ext2_inode*)(block
  1190. +           + InodeBlockIndex(currentID) * InodeSize());
  1191. +
  1192. +       currentID = inode->NextOrphan();
  1193. +       if (currentID == 0)
  1194. +           return B_OK;
  1195. +   } while(currentID != id);
  1196. +
  1197. +   CachedBlock cachedRemoved(this);
  1198. +
  1199. +   status = GetInodeBlock(id, blockNum);
  1200. +   if (status != B_OK)
  1201. +       return status;
  1202. +
  1203. +   uint8* removedBlock = cachedRemoved.SetToWritable(transaction, blockNum);
  1204. +   if (removedBlock == NULL)
  1205. +       return B_IO_ERROR;
  1206. +
  1207. +   ext2_inode* removedInode = (ext2_inode*)(removedBlock
  1208. +       + InodeBlockIndex(id) * InodeSize());
  1209. +
  1210. +   // Next orphan is stored inside deletion time
  1211. +   inode->deletion_time = removedInode->deletion_time;
  1212. +   TRACE("Volume::RemoveOrphan(): Updated pointer to %d\n",
  1213. +       (int)inode->NextOrphan());
  1214. +
  1215. +   return status;
  1216. +}
  1217. +
  1218. +
  1219. +status_t
  1220. +Volume::AllocateInode(Transaction& transaction, Inode* parent, int32 mode,
  1221. +   ino_t& id)
  1222. +{
  1223. +   status_t status = fInodeAllocator.New(transaction, parent, mode, id);
  1224. +   if (status != B_OK)
  1225. +       return status;
  1226. +
  1227. +   --fFreeInodes;
  1228. +
  1229. +   return WriteSuperBlock(transaction);
  1230. +}
  1231. +
  1232. +
  1233. +status_t
  1234. +Volume::FreeInode(Transaction& transaction, ino_t id, bool isDirectory)
  1235. +{
  1236. +   status_t status = fInodeAllocator.Free(transaction, id, isDirectory);
  1237. +   if (status != B_OK)
  1238. +       return status;
  1239. +
  1240. +   ++fFreeInodes;
  1241. +
  1242. +   return WriteSuperBlock(transaction);
  1243. +}
  1244. +
  1245. +
  1246. +status_t
  1247. +Volume::AllocateBlocks(Transaction& transaction, uint32 minimum, uint32 maximum,
  1248. +   uint32& blockGroup, uint32& start, uint32& length)
  1249. +{
  1250. +   TRACE("Volume::AllocateBlocks()\n");
  1251. +   if (IsReadOnly())
  1252. +       return B_READ_ONLY_DEVICE;
  1253. +
  1254. +   TRACE("Volume::AllocateBlocks(): Calling the block allocator\n");
  1255. +
  1256. +   status_t status = fBlockAllocator.AllocateBlocks(transaction, minimum,
  1257. +       maximum, blockGroup, start, length);
  1258. +   if (status != B_OK)
  1259. +       return status;
  1260. +
  1261. +   TRACE("Volume::AllocateBlocks(): Allocated %lu blocks\n", length);
  1262. +
  1263. +   fFreeBlocks -= length;
  1264. +
  1265. +   return WriteSuperBlock(transaction);
  1266. +}
  1267. +
  1268. +
  1269. +status_t
  1270. +Volume::FreeBlocks(Transaction& transaction, uint32 start, uint32 length)
  1271. +{
  1272. +   TRACE("Volume::FreeBlocks(%lu, %lu)\n", start, length);
  1273. +   if (IsReadOnly())
  1274. +       return B_READ_ONLY_DEVICE;
  1275. +
  1276. +   status_t status = fBlockAllocator.Free(transaction, start, length);
  1277. +   if (status != B_OK)
  1278. +       return status;
  1279. +
  1280. +   TRACE("Volume::FreeBlocks(): number of free blocks (before): %lu\n",
  1281. +       fFreeBlocks);
  1282. +   fFreeBlocks += length;
  1283. +   TRACE("Volume::FreeBlocks(): number of free blocks (after): %lu\n",
  1284. +       fFreeBlocks);
  1285. +
  1286. +   return WriteSuperBlock(transaction);
  1287. +}
  1288. +
  1289. +
  1290. +status_t
  1291. +Volume::LoadSuperBlock()
  1292. +{
  1293. +   CachedBlock cached(this);
  1294. +   const uint8* block = cached.SetTo(fFirstDataBlock);
  1295. +
  1296. +   if (block == NULL)
  1297. +       return B_IO_ERROR;
  1298. +
  1299. +   if (fFirstDataBlock == 0)
  1300. +       memcpy(&fSuperBlock, block + 1024, sizeof(fSuperBlock));
  1301. +   else
  1302. +       memcpy(&fSuperBlock, block, sizeof(fSuperBlock));
  1303. +
  1304. +   fFreeBlocks = fSuperBlock.FreeBlocks();
  1305. +   fFreeInodes = fSuperBlock.FreeInodes();
  1306. +
  1307. +   return B_OK;
  1308. +}
  1309. +
  1310. +
  1311. +status_t
  1312. +Volume::WriteSuperBlock(Transaction& transaction)
  1313. +{
  1314. +   TRACE("Volume::WriteSuperBlock()\n");
  1315. +   fSuperBlock.SetFreeBlocks(fFreeBlocks);
  1316. +   fSuperBlock.SetFreeInodes(fFreeInodes);
  1317. +   // TODO: Rest of fields that can be modified
  1318. +
  1319. +   TRACE("Volume::WriteSuperBlock(): free blocks: %lu, free inodes: %lu\n",
  1320. +       fSuperBlock.FreeBlocks(), fSuperBlock.FreeInodes());
  1321. +
  1322. +   CachedBlock cached(this);
  1323. +   uint8* block = cached.SetToWritable(transaction, fFirstDataBlock);
  1324. +
  1325. +   if (block == NULL)
  1326. +       return B_IO_ERROR;
  1327. +
  1328. +   TRACE("Volume::WriteSuperBlock(): first data block: %lu, block: %p, "
  1329. +       "superblock: %p\n", fFirstDataBlock, block, &fSuperBlock);
  1330. +
  1331. +   if (fFirstDataBlock == 0)
  1332. +       memcpy(block + 1024, &fSuperBlock, sizeof(fSuperBlock));
  1333. +   else
  1334. +       memcpy(block, &fSuperBlock, sizeof(fSuperBlock));
  1335. +
  1336. +   TRACE("Volume::WriteSuperBlock(): Done\n");
  1337. +
  1338. +   return B_OK;
  1339. +}
  1340. +
  1341. +
  1342. +status_t
  1343. +Volume::FlushDevice()
  1344. +{
  1345. +   TRACE("Volume::FlushDevice(): %p, %p\n", this, fBlockCache);
  1346. +   return block_cache_sync(fBlockCache);
  1347. +}
  1348. +
  1349. +
  1350. +status_t
  1351. +Volume::Sync()
  1352. +{
  1353. +   TRACE("Volume::Sync()\n");
  1354. +   return fJournal->FlushLogAndBlocks();
  1355. +}
  1356. +
  1357. +
  1358.  // #pragma mark - Disk scanning and initialization
  1359.  
  1360.  
  1361. @@ -460,3 +796,20 @@
  1362.         ? B_OK : B_NOT_SUPPORTED;
  1363.  }
  1364.  
  1365. +
  1366. +void
  1367. +Volume::TransactionDone(bool success)
  1368. +{
  1369. +   if (!success) {
  1370. +       status_t status = LoadSuperBlock();
  1371. +       if (status != B_OK)
  1372. +           panic("Failed to reload ext2 superblock.\n");
  1373. +   }
  1374. +}
  1375. +
  1376. +
  1377. +void
  1378. +Volume::RemovedFromTransaction()
  1379. +{
  1380. +   // TODO: Does it make a difference?
  1381. +}
  1382. Index: src/add-ons/kernel/file_systems/ext2/Utility.h
  1383. ===================================================================
  1384. --- src/add-ons/kernel/file_systems/ext2/Utility.h  (revision 0)
  1385. +++ src/add-ons/kernel/file_systems/ext2/Utility.h  (revision 0)
  1386. @@ -0,0 +1,39 @@
  1387. +/*
  1388. + * Copyright 2001-2009, Axel Dörfler, axeld@pinc-software.de.
  1389. + * This file may be used under the terms of the MIT License.
  1390. + */
  1391. +#ifndef UTILITY_H
  1392. +#define UTILITY_H
  1393. +
  1394. +#include "ext2.h"
  1395. +
  1396. +enum inode_type {
  1397. +   S_DIRECTORY     = S_IFDIR,
  1398. +   S_FILE          = S_IFREG,
  1399. +   S_SYMLINK       = S_IFLNK,
  1400. +
  1401. +   S_INDEX_TYPES   = (S_STR_INDEX | S_INT_INDEX | S_UINT_INDEX
  1402. +                       | S_LONG_LONG_INDEX | S_ULONG_LONG_INDEX
  1403. +                       | S_FLOAT_INDEX | S_DOUBLE_INDEX),
  1404. +
  1405. +   S_EXTENDED_TYPES = (S_ATTR_DIR | S_ATTR | S_INDEX_DIR)
  1406. +};
  1407. +
  1408. +
  1409. +/*!    Converts the open mode, the open flags given to bfs_open(), into
  1410. +   access modes, e.g. since O_RDONLY requires read access to the
  1411. +   file, it will be converted to R_OK.
  1412. +*/
  1413. +inline int
  1414. +open_mode_to_access(int openMode)
  1415. +{
  1416. +   openMode &= O_RWMASK;
  1417. +   if (openMode == O_RDONLY)
  1418. +       return R_OK;
  1419. +   if (openMode == O_WRONLY)
  1420. +       return W_OK;
  1421. +
  1422. +   return R_OK | W_OK;
  1423. +}
  1424. +
  1425. +#endif // UTILITY_H
  1426.  
  1427. Property changes on: src/add-ons/kernel/file_systems/ext2/Utility.h
  1428. ___________________________________________________________________
  1429. Added: svn:executable
  1430.    + *
  1431.  
  1432. Index: src/add-ons/kernel/file_systems/ext2/Journal.cpp
  1433. ===================================================================
  1434. --- src/add-ons/kernel/file_systems/ext2/Journal.cpp    (revision 0)
  1435. +++ src/add-ons/kernel/file_systems/ext2/Journal.cpp    (revision 0)
  1436. @@ -0,0 +1,1261 @@
  1437. +/*
  1438. + * Copyright 2001-2010, Haiku Inc. All rights reserved.
  1439. + * This file may be used under the terms of the MIT License.
  1440. + *
  1441. + * Authors:
  1442. + *     Janito V. Ferreira Filho
  1443. + */
  1444. +
  1445. +
  1446. +#include "Journal.h"
  1447. +
  1448. +#include <new>
  1449. +#include <string.h>
  1450. +#include <unistd.h>
  1451. +
  1452. +#include <fs_cache.h>
  1453. +
  1454. +#include "CachedBlock.h"
  1455. +#include "HashRevokeManager.h"
  1456. +
  1457. +
  1458. +//#define TRACE_EXT2
  1459. +#ifdef TRACE_EXT2
  1460. +#  define TRACE(x...) dprintf("\33[34mext2:\33[0m " x)
  1461. +#else
  1462. +#  define TRACE(x...) ;
  1463. +#endif
  1464. +
  1465. +
  1466. +class LogEntry : public DoublyLinkedListLinkImpl<LogEntry> {
  1467. +public:
  1468. +                           LogEntry(Journal* journal, uint32 logStart,
  1469. +                               uint32 length);
  1470. +                           ~LogEntry();
  1471. +
  1472. +           uint32          Start() const { return fStart; }
  1473. +           uint32          CommitID() const { return fCommitID; }
  1474. +
  1475. +           Journal*        GetJournal() { return fJournal; }
  1476. +
  1477. +private:
  1478. +           Journal*        fJournal;
  1479. +           uint32          fStart;
  1480. +           uint32          fCommitID;
  1481. +};
  1482. +
  1483. +
  1484. +LogEntry::LogEntry(Journal* journal, uint32 logStart, uint32 commitID)
  1485. +   :
  1486. +   fJournal(journal),
  1487. +   fStart(logStart),
  1488. +   fCommitID(commitID)
  1489. +{
  1490. +}
  1491. +
  1492. +
  1493. +LogEntry::~LogEntry()
  1494. +{
  1495. +}
  1496. +
  1497. +
  1498. +void
  1499. +JournalHeader::MakeDescriptor(uint32 sequence)
  1500. +{
  1501. +   this->magic = B_HOST_TO_BENDIAN_INT32(JOURNAL_MAGIC);
  1502. +   this->sequence = B_HOST_TO_BENDIAN_INT32(sequence);
  1503. +   this->block_type = B_HOST_TO_BENDIAN_INT32(JOURNAL_DESCRIPTOR_BLOCK);
  1504. +}
  1505. +
  1506. +
  1507. +void
  1508. +JournalHeader::MakeCommit(uint32 sequence)
  1509. +{
  1510. +   this->magic = B_HOST_TO_BENDIAN_INT32(JOURNAL_MAGIC);
  1511. +   this->sequence = B_HOST_TO_BENDIAN_INT32(sequence);
  1512. +   this->block_type = B_HOST_TO_BENDIAN_INT32(JOURNAL_COMMIT_BLOCK);
  1513. +}
  1514. +
  1515. +
  1516. +Journal::Journal(Volume* fsVolume, Volume* jVolume)
  1517. +   :
  1518. +   fJournalVolume(jVolume),
  1519. +   fJournalBlockCache(jVolume->BlockCache()),
  1520. +   fFilesystemVolume(fsVolume),
  1521. +   fFilesystemBlockCache(fsVolume->BlockCache()),
  1522. +   fRevokeManager(NULL),
  1523. +   fInitStatus(B_OK),
  1524. +   fBlockSize(sizeof(JournalSuperBlock)),
  1525. +   fFirstCommitID(0),
  1526. +   fFirstCacheCommitID(0),
  1527. +   fFirstLogBlock(1),
  1528. +   fLogSize(0),
  1529. +   fVersion(0),
  1530. +   fLogStart(0),
  1531. +   fLogEnd(0),
  1532. +   fFreeBlocks(0),
  1533. +   fMaxTransactionSize(0),
  1534. +   fCurrentCommitID(0),
  1535. +   fHasSubTransaction(false),
  1536. +   fSeparateSubTransactions(false),
  1537. +   fUnwrittenTransactions(0),
  1538. +   fTransactionID(0)
  1539. +{
  1540. +   recursive_lock_init(&fLock, "ext2 journal");
  1541. +   mutex_init(&fLogEntriesLock, "ext2 journal log entries");
  1542. +
  1543. +   HashRevokeManager* revokeManager = new(std::nothrow) HashRevokeManager;
  1544. +   TRACE("Journal::Journal(): Allocated a hash revoke manager at %p\n",
  1545. +       revokeManager);
  1546. +
  1547. +   if (revokeManager == NULL)
  1548. +       fInitStatus = B_NO_MEMORY;
  1549. +   else {
  1550. +       fInitStatus = revokeManager->Init();
  1551. +      
  1552. +       if (fInitStatus == B_OK) {
  1553. +           fRevokeManager = revokeManager;
  1554. +           fInitStatus = _LoadSuperBlock();
  1555. +       }
  1556. +   }
  1557. +}
  1558. +
  1559. +
  1560. +Journal::Journal()
  1561. +   :
  1562. +   fJournalVolume(NULL),
  1563. +   fJournalBlockCache(NULL),
  1564. +   fFilesystemVolume(NULL),
  1565. +   fFilesystemBlockCache(NULL),
  1566. +   fRevokeManager(NULL),
  1567. +   fInitStatus(B_OK),
  1568. +   fBlockSize(sizeof(JournalSuperBlock)),
  1569. +   fFirstCommitID(0),
  1570. +   fFirstCacheCommitID(0),
  1571. +   fFirstLogBlock(1),
  1572. +   fLogSize(0),
  1573. +   fVersion(0),
  1574. +   fLogStart(0),
  1575. +   fLogEnd(0),
  1576. +   fFreeBlocks(0),
  1577. +   fMaxTransactionSize(0),
  1578. +   fCurrentCommitID(0),
  1579. +   fHasSubTransaction(false),
  1580. +   fSeparateSubTransactions(false),
  1581. +   fUnwrittenTransactions(0),
  1582. +   fTransactionID(0)
  1583. +{
  1584. +   recursive_lock_init(&fLock, "ext2 journal");
  1585. +   mutex_init(&fLogEntriesLock, "ext2 journal log entries");
  1586. +}
  1587. +
  1588. +
  1589. +Journal::~Journal()
  1590. +{
  1591. +   TRACE("Journal destructor.\n");
  1592. +
  1593. +   TRACE("Journal::~Journal(): Attempting to delete revoke manager at %p\n",
  1594. +       fRevokeManager);
  1595. +   delete fRevokeManager;
  1596. +
  1597. +   recursive_lock_destroy(&fLock);
  1598. +   mutex_destroy(&fLogEntriesLock);
  1599. +}
  1600. +
  1601. +
  1602. +status_t
  1603. +Journal::InitCheck()
  1604. +{
  1605. +   return fInitStatus;
  1606. +}
  1607. +
  1608. +
  1609. +status_t
  1610. +Journal::Uninit()
  1611. +{
  1612. +   status_t status = FlushLogAndBlocks();
  1613. +
  1614. +   if (status == B_OK) {
  1615. +       // Mark journal as clean
  1616. +       fLogStart = 0;
  1617. +       status = _SaveSuperBlock();
  1618. +   }
  1619. +
  1620. +   return status;
  1621. +}
  1622. +
  1623. +
  1624. +/*virtual*/ status_t
  1625. +Journal::StartLog()
  1626. +{
  1627. +   fLogStart = fFirstLogBlock;
  1628. +   fLogEnd = fFirstLogBlock;
  1629. +   fFreeBlocks = 0;
  1630. +
  1631. +   fCurrentCommitID = fFirstCommitID;
  1632. +
  1633. +   return _SaveSuperBlock();
  1634. +}
  1635. +
  1636. +
  1637. +status_t
  1638. +Journal::RestartLog()
  1639. +{
  1640. +   fFirstCommitID = 1;
  1641. +
  1642. +   return B_OK;
  1643. +}
  1644. +
  1645. +
  1646. +/*virtual*/ status_t
  1647. +Journal::Lock(Transaction* owner, bool separateSubTransactions)
  1648. +{
  1649. +   TRACE("Journal::Lock()\n");
  1650. +   status_t status = recursive_lock_lock(&fLock);
  1651. +   if (status != B_OK)
  1652. +       return status;
  1653. +
  1654. +   TRACE("Journal::Lock(): Aquired lock\n");
  1655. +
  1656. +   if (!fSeparateSubTransactions && recursive_lock_get_recursion(&fLock) > 1) {
  1657. +       // reuse current transaction
  1658. +       TRACE("Journal::Lock(): Reusing current transaction\n");
  1659. +       return B_OK;
  1660. +   }
  1661. +
  1662. +   if(separateSubTransactions)
  1663. +       fSeparateSubTransactions = true;
  1664. +
  1665. +   if (owner != NULL)
  1666. +       owner->SetParent(fOwner);
  1667. +
  1668. +   fOwner = owner;
  1669. +
  1670. +   if (fOwner != NULL) {
  1671. +       if (fUnwrittenTransactions > 0) {
  1672. +           // start a sub transaction
  1673. +           TRACE("Journal::Lock(): Starting sub transaction\n");
  1674. +           cache_start_sub_transaction(fFilesystemBlockCache, fTransactionID);
  1675. +           fHasSubTransaction = true;
  1676. +       } else {
  1677. +           TRACE("Journal::Lock(): Starting new transaction\n");
  1678. +           fTransactionID = cache_start_transaction(fFilesystemBlockCache);
  1679. +       }
  1680. +
  1681. +       if (fTransactionID < B_OK) {
  1682. +           recursive_lock_unlock(&fLock);
  1683. +           return fTransactionID;
  1684. +       }
  1685. +
  1686. +       cache_add_transaction_listener(fFilesystemBlockCache, fTransactionID,
  1687. +           TRANSACTION_IDLE, _TransactionIdle, this);
  1688. +   }
  1689. +
  1690. +   return B_OK;
  1691. +}
  1692. +
  1693. +
  1694. +/*virtual*/ status_t
  1695. +Journal::Unlock(Transaction* owner, bool success)
  1696. +{
  1697. +   TRACE("Journal::Unlock(): Lock recursion: %ld\n",
  1698. +       recursive_lock_get_recursion(&fLock));
  1699. +   if (fSeparateSubTransactions
  1700. +       || recursive_lock_get_recursion(&fLock) == 1) {
  1701. +       // we only end the transaction if we unlock it
  1702. +       if (owner != NULL) {
  1703. +           TRACE("Journal::Unlock(): Calling _TransactionDone\n");
  1704. +           status_t status = _TransactionDone(success);
  1705. +           if (status != B_OK)
  1706. +               return status;
  1707. +
  1708. +           TRACE("Journal::Unlock(): Returned from _TransactionDone\n");
  1709. +           bool separateSubTransactions = fSeparateSubTransactions;
  1710. +           fSeparateSubTransactions = true;
  1711. +           TRACE("Journal::Unlock(): Notifying listeners for: %p\n", owner);
  1712. +           owner->NotifyListeners(success);
  1713. +           TRACE("Journal::Unlock(): Done notifying listeners\n");
  1714. +           fSeparateSubTransactions = separateSubTransactions;
  1715. +
  1716. +           fOwner = owner->Parent();
  1717. +       } else
  1718. +           fOwner = NULL;
  1719. +
  1720. +       if (fSeparateSubTransactions
  1721. +           && recursive_lock_get_recursion(&fLock) == 1)
  1722. +           fSeparateSubTransactions = false;
  1723. +   } else
  1724. +       owner->MoveListenersTo(fOwner);
  1725. +
  1726. +   TRACE("Journal::Unlock(): Unlocking the lock\n");
  1727. +
  1728. +   recursive_lock_unlock(&fLock);
  1729. +   return B_OK;
  1730. +}
  1731. +
  1732. +
  1733. +status_t
  1734. +Journal::MapBlock(uint32 logical, uint32& physical)
  1735. +{
  1736. +   TRACE("Journal::MapBlock()\n");
  1737. +   physical = logical;
  1738. +  
  1739. +   return B_OK;
  1740. +}
  1741. +
  1742. +
  1743. +inline uint32
  1744. +Journal::FreeLogBlocks() const
  1745. +{
  1746. +   TRACE("Journal::FreeLogBlocks(): start: %lu, end: %lu, size: %lu\n",
  1747. +       fLogStart, fLogEnd, fLogSize);
  1748. +   return fLogStart <= fLogEnd
  1749. +       ? fLogSize - fLogEnd + fLogStart - 1
  1750. +       : fLogStart - fLogEnd;
  1751. +}
  1752. +
  1753. +
  1754. +status_t
  1755. +Journal::FlushLogAndBlocks()
  1756. +{
  1757. +   return _FlushLog(true, true);
  1758. +}
  1759. +
  1760. +
  1761. +int32
  1762. +Journal::TransactionID() const
  1763. +{
  1764. +   return fTransactionID;
  1765. +}
  1766. +
  1767. +
  1768. +status_t
  1769. +Journal::_WritePartialTransactionToLog(JournalHeader* descriptorBlock,
  1770. +   bool detached, uint8** _escapedData, uint32 &logBlock, off_t& blockNumber,
  1771. +   long& cookie, ArrayDeleter<uint8>& escapedDataDeleter, uint32& blockCount,
  1772. +   bool& finished)
  1773. +{
  1774. +   TRACE("Journal::_WritePartialTransactionToLog()\n");
  1775. +
  1776. +   uint32 descriptorBlockPos = logBlock;
  1777. +   uint8* escapedData = *_escapedData;
  1778. +
  1779. +   JournalBlockTag* tag = (JournalBlockTag*)descriptorBlock->data;
  1780. +   JournalBlockTag* lastTag = (JournalBlockTag*)((uint8*)descriptorBlock
  1781. +       + fBlockSize - sizeof(JournalHeader));
  1782. +  
  1783. +   finished = false;
  1784. +   status_t status = B_OK;
  1785. +
  1786. +   while (tag < lastTag && status == B_OK) {
  1787. +       tag->SetBlockNumber(blockNumber);
  1788. +       tag->SetFlags(0);
  1789. +
  1790. +       CachedBlock data(fFilesystemVolume);
  1791. +       const JournalHeader* blockData = (JournalHeader*)data.SetTo(
  1792. +           blockNumber);
  1793. +       if (blockData == NULL) {
  1794. +           panic("Got a NULL pointer while iterating through transaction "
  1795. +               "blocks.\n");
  1796. +           return B_ERROR;
  1797. +       }
  1798. +
  1799. +       void* finalData;
  1800. +
  1801. +       if (blockData->CheckMagic()) {
  1802. +           // The journaled block starts with the magic value
  1803. +           // We must remove it to prevent confusion
  1804. +           TRACE("Journal::_WritePartialTransactionToLog(): Block starts with "
  1805. +               "magic number. Escaping it\n");
  1806. +           tag->SetEscapedFlag();
  1807. +
  1808. +           if (escapedData == NULL) {
  1809. +               TRACE("Journal::_WritePartialTransactionToLog(): Allocating "
  1810. +                   "space for escaped block (%lu)\n", fBlockSize);
  1811. +               escapedData = new(std::nothrow) uint8[fBlockSize];
  1812. +               if (escapedData == NULL) {
  1813. +                   TRACE("Journal::_WritePartialTransactionToLof(): Failed to "
  1814. +                       "allocate buffer for escaped data block\n");
  1815. +                   return B_NO_MEMORY;
  1816. +               }
  1817. +               escapedDataDeleter.SetTo(escapedData);
  1818. +               *_escapedData = escapedData;
  1819. +
  1820. +               ((int32*)escapedData)[0] = 0; // Remove magic
  1821. +           }
  1822. +
  1823. +           memcpy(escapedData + 4, blockData->data, fBlockSize - 4);
  1824. +           finalData = escapedData;
  1825. +       } else
  1826. +           finalData = (void*)blockData;
  1827. +
  1828. +       // TODO: use iovecs?
  1829. +
  1830. +       logBlock = _WrapAroundLog(logBlock + 1);
  1831. +
  1832. +       uint32 physicalBlock;
  1833. +       status = MapBlock(logBlock, physicalBlock);
  1834. +       if (status != B_OK)
  1835. +           return status;
  1836. +
  1837. +       off_t logOffset = physicalBlock * fBlockSize;
  1838. +
  1839. +       TRACE("Journal::_WritePartialTransactionToLog(): Writing from memory: "
  1840. +           "%p, to disk: %ld\n", finalData, (long)logOffset);
  1841. +       size_t written = write_pos(fJournalVolume->Device(), logOffset,
  1842. +           finalData, fBlockSize);
  1843. +       if (written != fBlockSize) {
  1844. +           TRACE("Failed to write journal block.\n");
  1845. +           return B_IO_ERROR;
  1846. +       }
  1847. +
  1848. +       TRACE("Journal::_WritePartialTransactionToLog(): Wrote a journal block "
  1849. +           "at: %lu\n", logBlock);
  1850. +
  1851. +       blockCount++;
  1852. +       tag++;
  1853. +
  1854. +       status = cache_next_block_in_transaction(fFilesystemBlockCache,
  1855. +           fTransactionID, detached, &cookie, &blockNumber, NULL, NULL);
  1856. +   }
  1857. +
  1858. +   finished = status != B_OK;
  1859. +  
  1860. +   // Write descriptor block
  1861. +   --tag;
  1862. +   tag->SetLastTagFlag();
  1863. +  
  1864. +   uint32 physicalBlock;
  1865. +   status = MapBlock(descriptorBlockPos, physicalBlock);
  1866. +   if (status != B_OK)
  1867. +       return status;
  1868. +
  1869. +   off_t descriptorBlockOffset = physicalBlock * fBlockSize;
  1870. +
  1871. +   TRACE("Journal::_WritePartialTransactionToLog(): Writing to: %ld\n",
  1872. +       (long)descriptorBlockOffset);
  1873. +   size_t written = write_pos(fJournalVolume->Device(),
  1874. +       descriptorBlockOffset, descriptorBlock, fBlockSize);
  1875. +   if (written != fBlockSize) {
  1876. +       TRACE("Failed to write journal descriptor block.\n");
  1877. +       return B_IO_ERROR;
  1878. +   }
  1879. +
  1880. +   blockCount++;
  1881. +   logBlock = _WrapAroundLog(logBlock + 1);
  1882. +
  1883. +   return B_OK;
  1884. +}
  1885. +
  1886. +
  1887. +status_t
  1888. +Journal::_WriteTransactionToLog()
  1889. +{
  1890. +   TRACE("Journal::_WriteTransactionToLog()\n");
  1891. +   // Transaction enters the Flush state
  1892. +   bool detached = false;
  1893. +   TRACE("Journal::_WriteTransactionToLog(): Attempting to get transaction "
  1894. +       "size\n");
  1895. +   size_t size = _FullTransactionSize();
  1896. +   TRACE("Journal::_WriteTransactionToLog(): transaction size: %lu\n", size);
  1897. +
  1898. +   if (size > fMaxTransactionSize) {
  1899. +       TRACE("Journal::_WriteTransactionToLog(): not enough free space "
  1900. +           "for the transaction. Attempting to free some space.\n");
  1901. +       size = _MainTransactionSize();
  1902. +       TRACE("Journal::_WriteTransactionToLog(): main transaction size: %lu\n",
  1903. +           size);
  1904. +
  1905. +       if(fHasSubTransaction && size < fMaxTransactionSize) {
  1906. +           TRACE("Journal::_WriteTransactionToLog(): transaction doesn't fit, "
  1907. +               "but it can be separated\n");
  1908. +           detached = true;
  1909. +       } else {
  1910. +           // Error: transaction can't fit in log
  1911. +           panic("transaction too large (size: %lu, max size: %lu, log size: "
  1912. +               "%lu)\n", size, fMaxTransactionSize, fLogSize);
  1913. +           return B_BUFFER_OVERFLOW;
  1914. +       }
  1915. +   }
  1916. +
  1917. +   TRACE("Journal::_WriteTransactionToLog(): free log blocks: %lu\n",
  1918. +       FreeLogBlocks());
  1919. +   if (size > FreeLogBlocks()) {
  1920. +       TRACE("Journal::_WriteTransactionToLog(): Syncing block cache\n");
  1921. +       cache_sync_transaction(fFilesystemBlockCache, fTransactionID);
  1922. +      
  1923. +       if (size > FreeLogBlocks()) {
  1924. +           panic("Transaction fits, but sync didn't result in enough"
  1925. +               "free space.\n\tGot %ld when at least %ld was expected.",
  1926. +               (long)FreeLogBlocks(), (long)size);
  1927. +       }
  1928. +   }
  1929. +  
  1930. +   TRACE("Journal::_WriteTransactionToLog(): finished managing space for "
  1931. +       "the transaction\n");
  1932. +
  1933. +   fHasSubTransaction = false;
  1934. +
  1935. +   // Prepare Descriptor block
  1936. +   TRACE("Journal::_WriteTransactionToLog(): attempting to allocate space for "
  1937. +       "the descriptor block, block size %lu\n", fBlockSize);
  1938. +   JournalHeader* descriptorBlock =
  1939. +       (JournalHeader*)new(std::nothrow) uint8[fBlockSize];
  1940. +   if (descriptorBlock == NULL) {
  1941. +       TRACE("Journal::_WriteTransactionToLog(): Failed to allocate a buffer "
  1942. +           "for the descriptor block\n");
  1943. +       return B_NO_MEMORY;
  1944. +   }
  1945. +   ArrayDeleter<uint8> descriptorBlockDeleter((uint8*)descriptorBlock);
  1946. +
  1947. +   descriptorBlock->MakeDescriptor(fCurrentCommitID);
  1948. +
  1949. +   // Prepare Commit block
  1950. +   TRACE("Journal::_WriteTransactionToLog(): attempting to allocate space for "
  1951. +       "the commit block, block size %lu\n", fBlockSize);
  1952. +   JournalHeader* commitBlock =
  1953. +       (JournalHeader*)new(std::nothrow) uint8[fBlockSize];
  1954. +   if (descriptorBlock == NULL) {
  1955. +       TRACE("Journal::_WriteTransactionToLog(): Failed to allocate a buffer "
  1956. +           "for the commit block\n");
  1957. +       return B_NO_MEMORY;
  1958. +   }
  1959. +   ArrayDeleter<uint8> commitBlockDeleter((uint8*)commitBlock);
  1960. +
  1961. +   commitBlock->MakeCommit(fCurrentCommitID + 1);
  1962. +   memset(commitBlock->data, 0, fBlockSize - sizeof(JournalHeader));
  1963. +       // TODO: This probably isn't necessary
  1964. +
  1965. +   uint8* escapedData = NULL;
  1966. +   ArrayDeleter<uint8> escapedDataDeleter;
  1967. +
  1968. +   off_t blockNumber;
  1969. +   long cookie = 0;
  1970. +
  1971. +   status_t status = cache_next_block_in_transaction(fFilesystemBlockCache,
  1972. +       fTransactionID, detached, &cookie, &blockNumber, NULL, NULL);
  1973. +   if (status != B_OK) {
  1974. +       TRACE("Journal::_WriteTransactionToLog(): Transaction has no blocks to
  1975. +           write\n");
  1976. +       return B_OK;
  1977. +   }
  1978. +
  1979. +   uint32 blockCount = 0;
  1980. +
  1981. +   uint32 logBlock = _WrapAroundLog(fLogEnd);
  1982. +  
  1983. +   bool finished = false;
  1984. +
  1985. +   status = _WritePartialTransactionToLog(descriptorBlock, detached,
  1986. +       &escapedData, logBlock, blockNumber, cookie, escapedDataDeleter,
  1987. +       blockCount, finished);
  1988. +   if (!finished && status != B_OK)
  1989. +       return status;
  1990. +
  1991. +   uint32 commitBlockPos = logBlock;
  1992. +
  1993. +   while (!finished) {
  1994. +       descriptorBlock->IncrementSequence();
  1995. +
  1996. +       status = _WritePartialTransactionToLog(descriptorBlock, detached,
  1997. +           &escapedData, logBlock, blockNumber, cookie, escapedDataDeleter,
  1998. +           blockCount, finished);
  1999. +       if (!finished && status != B_OK)
  2000. +           return status;
  2001. +      
  2002. +       // It is okay to write the commit blocks of the partial transactions
  2003. +       // as long as the commit block of the first partial transaction isn't
  2004. +       // written. When it recovery reaches where the first commit should be
  2005. +       // and doesn't find it, it considers it found the end of the log.
  2006. +
  2007. +       uint32 physicalBlock;
  2008. +       status = MapBlock(logBlock, physicalBlock);
  2009. +       if (status != B_OK)
  2010. +           return status;
  2011. +
  2012. +       off_t logOffset = physicalBlock * fBlockSize;
  2013. +      
  2014. +       TRACE("Journal::_WriteTransactionToLog(): Writting commit block to "
  2015. +           "%ld\n", (long)logOffset);
  2016. +       off_t written = write_pos(fJournalVolume->Device(), logOffset,
  2017. +           commitBlock, fBlockSize);
  2018. +       if (written != fBlockSize) {
  2019. +           TRACE("Failed to write journal commit block.\n");
  2020. +           return B_IO_ERROR;
  2021. +       }
  2022. +
  2023. +       commitBlock->IncrementSequence();
  2024. +       blockCount++;
  2025. +      
  2026. +       logBlock = _WrapAroundLog(logBlock + 1);
  2027. +   }
  2028. +
  2029. +   // Transaction will enter the Commit state
  2030. +   uint32 physicalBlock;
  2031. +   status = MapBlock(commitBlockPos, physicalBlock);
  2032. +   if (status != B_OK)
  2033. +       return status;
  2034. +
  2035. +   off_t logOffset = physicalBlock * fBlockSize;
  2036. +
  2037. +   TRACE("Journal::_WriteTansactionToLog(): Writing to: %ld\n",
  2038. +       (long)logOffset);
  2039. +   off_t written = write_pos(fJournalVolume->Device(), logOffset, commitBlock,
  2040. +       fBlockSize);
  2041. +   if (written != fBlockSize) {
  2042. +       TRACE("Failed to write journal commit block.\n");
  2043. +       return B_IO_ERROR;
  2044. +   }
  2045. +  
  2046. +   blockCount++;
  2047. +   fLogEnd = _WrapAroundLog(fLogEnd + blockCount);
  2048. +
  2049. +   status = _SaveSuperBlock();
  2050. +
  2051. +   // Transaction will enter Finished state
  2052. +   LogEntry *logEntry = new LogEntry(this, fLogEnd, fCurrentCommitID++);
  2053. +   TRACE("Journal::_WriteTransactionToLog(): Allocating log entry at %p\n", logEntry);
  2054. +   if (logEntry == NULL) {
  2055. +       panic("no memory to allocate log entries!");
  2056. +       return B_NO_MEMORY;
  2057. +   }
  2058. +
  2059. +   mutex_lock(&fLogEntriesLock);
  2060. +   fLogEntries.Add(logEntry);
  2061. +   mutex_unlock(&fLogEntriesLock);
  2062. +
  2063. +   if (detached) {
  2064. +       fTransactionID = cache_detach_sub_transaction(fFilesystemBlockCache,
  2065. +           fTransactionID, _TransactionWritten, logEntry);
  2066. +       fUnwrittenTransactions = 1;
  2067. +
  2068. +       if (status == B_OK && _FullTransactionSize() > fLogSize) {
  2069. +           // If the transaction is too large after writing, there is no way to
  2070. +           // recover, so let this transaction fail.
  2071. +           dprintf("transaction too large (%d blocks, log size %d)!\n",
  2072. +               (int)_FullTransactionSize(), (int)fLogSize);
  2073. +           return B_BUFFER_OVERFLOW;
  2074. +       }
  2075. +   } else {
  2076. +       cache_end_transaction(fFilesystemBlockCache, fTransactionID,
  2077. +           _TransactionWritten, logEntry);
  2078. +       fUnwrittenTransactions = 0;
  2079. +   }
  2080. +
  2081. +   return B_OK;
  2082. +}
  2083. +
  2084. +
  2085. +status_t
  2086. +Journal::_SaveSuperBlock()
  2087. +{
  2088. +   TRACE("Journal::_SaveSuperBlock()\n");
  2089. +   uint32 physicalBlock;
  2090. +   status_t status = MapBlock(0, physicalBlock);
  2091. +   if (status != B_OK)
  2092. +       return status;
  2093. +
  2094. +   off_t superblockPos = physicalBlock * fBlockSize;
  2095. +
  2096. +   JournalSuperBlock superblock;
  2097. +   size_t bytesRead = read_pos(fJournalVolume->Device(), superblockPos,
  2098. +       &superblock, sizeof(superblock));
  2099. +
  2100. +   if (bytesRead != sizeof(superblock))
  2101. +       return B_IO_ERROR;
  2102. +
  2103. +   superblock.SetFirstCommitID(fFirstCommitID);
  2104. +   superblock.SetLogStart(fLogStart);
  2105. +  
  2106. +   TRACE("Journal::SaveSuperBlock(): Write to %ld\n", (long)superblockPos);
  2107. +   size_t bytesWritten = write_pos(fJournalVolume->Device(), superblockPos,
  2108. +       &superblock, sizeof(superblock));
  2109. +
  2110. +   if (bytesWritten != sizeof(superblock))
  2111. +       return B_IO_ERROR;
  2112. +
  2113. +   TRACE("Journal::_SaveSuperBlock(): Done\n");
  2114. +
  2115. +   return B_OK;
  2116. +}
  2117. +
  2118. +
  2119. +status_t
  2120. +Journal::_LoadSuperBlock()
  2121. +{
  2122. +   TRACE("Journal::_LoadSuperBlock()\n");
  2123. +   uint32 superblockPos;
  2124. +
  2125. +   status_t status = MapBlock(0, superblockPos);
  2126. +   if (status != B_OK)
  2127. +       return status;
  2128. +  
  2129. +   TRACE("Journal::_LoadSuperBlock(): super block physical block: %lu\n",
  2130. +       superblockPos);
  2131. +  
  2132. +   JournalSuperBlock superblock;
  2133. +   size_t bytesRead = read_pos(fJournalVolume->Device(), superblockPos
  2134. +       * fJournalVolume->BlockSize(), &superblock, sizeof(superblock));
  2135. +
  2136. +   if (bytesRead != sizeof(superblock)) {
  2137. +       TRACE("Journal::_LoadSuperBlock(): failed to read superblock\n");
  2138. +       return B_IO_ERROR;
  2139. +   }
  2140. +
  2141. +   if (!superblock.header.CheckMagic()) {
  2142. +       TRACE("Journal::_LoadSuperBlock(): Invalid superblock magic %lX\n",
  2143. +           superblock.header.Magic());
  2144. +       return B_BAD_VALUE;
  2145. +   }
  2146. +
  2147. +   if (superblock.header.BlockType() == JOURNAL_SUPERBLOCK_V1) {
  2148. +       TRACE("Journal::_LoadSuperBlock(): Journal superblock version 1\n");
  2149. +       fVersion = 1;
  2150. +   } else if (superblock.header.BlockType() == JOURNAL_SUPERBLOCK_V2) {
  2151. +       TRACE("Journal::_LoadSuperBlock(): Journal superblock version 2\n");
  2152. +       fVersion = 2;
  2153. +   } else {
  2154. +       TRACE("Journal::_LoadSuperBlock(): Invalid superblock version\n");
  2155. +       return B_BAD_VALUE;
  2156. +   }
  2157. +
  2158. +   if (fVersion >= 2) {
  2159. +       status = _CheckFeatures(&superblock);
  2160. +
  2161. +       if (status != B_OK) {
  2162. +           TRACE("Journal::_LoadSuperBlock(): Unsupported features\n");
  2163. +           return status;
  2164. +       }
  2165. +   }
  2166. +
  2167. +   fBlockSize = superblock.BlockSize();
  2168. +   fFirstCommitID = superblock.FirstCommitID();
  2169. +   fFirstLogBlock = superblock.FirstLogBlock();
  2170. +   fLogStart = superblock.LogStart();
  2171. +   fLogSize = superblock.NumBlocks();
  2172. +
  2173. +   uint32 descriptorTags = (fBlockSize - sizeof(JournalHeader))
  2174. +       / sizeof(JournalBlockTag);
  2175. +       // Maximum tags per descriptor block
  2176. +   uint32 maxDescriptors = (fLogSize - 1) / (descriptorTags + 2);
  2177. +       // Maximum number of full journal transactions
  2178. +   fMaxTransactionSize = maxDescriptors * descriptorTags;
  2179. +   fMaxTransactionSize += (fLogSize - 1) - fMaxTransactionSize - 2;
  2180. +       // Maximum size of a "logical" transaction
  2181. +       // TODO: Why is "superblock.MaxTransactionBlocks();" zero?
  2182. +   //fFirstCacheCommitID = fFirstCommitID - fTransactionID /*+ 1*/;
  2183. +
  2184. +   TRACE("Journal::_LoadSuperBlock(): block size: %lu, first commit id: %lu, "
  2185. +       "first log block: %lu, log start: %lu, log size: %lu, max transaction "
  2186. +       "size: %lu\n", fBlockSize, fFirstCommitID, fFirstLogBlock, fLogStart,
  2187. +       fLogSize, fMaxTransactionSize);
  2188. +
  2189. +   return B_OK;
  2190. +}
  2191. +
  2192. +
  2193. +status_t
  2194. +Journal::_CheckFeatures(JournalSuperBlock* superblock)
  2195. +{
  2196. +   if ((superblock->ReadOnlyCompatibleFeatures()
  2197. +           & ~JOURNAL_KNOWN_READ_ONLY_COMPATIBLE_FEATURES) != 0
  2198. +       || (superblock->IncompatibleFeatures()
  2199. +           & ~JOURNAL_KNOWN_INCOMPATIBLE_FEATURES) != 0)
  2200. +       return B_NOT_SUPPORTED;
  2201. +
  2202. +   return B_OK;
  2203. +}
  2204. +
  2205. +
  2206. +uint32
  2207. +Journal::_CountTags(JournalHeader* descriptorBlock)
  2208. +{
  2209. +   uint32 count = 0;
  2210. +
  2211. +   JournalBlockTag* tags = (JournalBlockTag*)descriptorBlock->data;
  2212. +       // Skip the header
  2213. +   JournalBlockTag* lastTag = (JournalBlockTag*)
  2214. +       (descriptorBlock + fBlockSize - sizeof(JournalBlockTag));
  2215. +
  2216. +   while (tags < lastTag && (tags->Flags() & JOURNAL_FLAG_LAST_TAG) == 0) {
  2217. +       if ((tags->Flags() & JOURNAL_FLAG_SAME_UUID) == 0) {
  2218. +           // sizeof(UUID) = 16 = 2*sizeof(JournalBlockTag)
  2219. +           tags += 2;  // Skip new UUID
  2220. +       }
  2221. +
  2222. +       TRACE("Journal::_CountTags(): Tag block: %lu\n", tags->BlockNumber());
  2223. +
  2224. +       tags++; // Go to next tag
  2225. +       count++;
  2226. +   }
  2227. +
  2228. +   if ((tags->Flags() & JOURNAL_FLAG_LAST_TAG) != 0)
  2229. +       count++;
  2230. +  
  2231. +   TRACE("Journal::_CountTags(): counted tags: %lu\n", count);
  2232. +
  2233. +   return count;
  2234. +}
  2235. +
  2236. +
  2237. +/*virtual*/ status_t
  2238. +Journal::Recover()
  2239. +{
  2240. +   TRACE("Journal::Recover()\n");
  2241. +   if (fLogStart == 0) // Journal was cleanly unmounted
  2242. +       return B_OK;
  2243. +
  2244. +   TRACE("Journal::Recover(): Journal needs recovery\n");
  2245. +
  2246. +   uint32 lastCommitID;
  2247. +
  2248. +   status_t status = _RecoverPassScan(lastCommitID);
  2249. +   if (status != B_OK)
  2250. +       return status;
  2251. +  
  2252. +   status = _RecoverPassRevoke(lastCommitID);
  2253. +   if (status != B_OK)
  2254. +       return status;
  2255. +
  2256. +   return _RecoverPassReplay(lastCommitID);
  2257. +}
  2258. +
  2259. +
  2260. +// First pass: Find the end of the log
  2261. +status_t
  2262. +Journal::_RecoverPassScan(uint32& lastCommitID)
  2263. +{
  2264. +   TRACE("Journal Recover: 1st Pass: Scan\n");
  2265. +
  2266. +   CachedBlock cached(fJournalVolume);
  2267. +   JournalHeader* header;
  2268. +   uint32 nextCommitID = fFirstCommitID;
  2269. +   uint32 nextBlock = fLogStart;
  2270. +   uint32 nextBlockPos;
  2271. +
  2272. +   status_t status = MapBlock(nextBlock, nextBlockPos);
  2273. +   if (status != B_OK)
  2274. +       return status;
  2275. +
  2276. +   header = (JournalHeader*)cached.SetTo(nextBlockPos);
  2277. +
  2278. +   while (header->CheckMagic() && header->Sequence() == nextCommitID) {
  2279. +       uint32 blockType = header->BlockType();
  2280. +
  2281. +       if (blockType == JOURNAL_DESCRIPTOR_BLOCK) {
  2282. +           uint32 tags = _CountTags(header);
  2283. +           nextBlock += tags;
  2284. +           TRACE("Journal recover pass scan: Found a descriptor block with "
  2285. +               "%lu tags\n", tags);
  2286. +       } else if (blockType == JOURNAL_COMMIT_BLOCK) {
  2287. +           nextCommitID++;
  2288. +           TRACE("Journal recover pass scan: Found a commit block. Next "
  2289. +               "commit ID: %lu\n", nextCommitID);
  2290. +       } else if (blockType != JOURNAL_REVOKE_BLOCK) {
  2291. +           TRACE("Journal recover pass scan: Reached an unrecognized block, "
  2292. +               "assuming as log's end.\n");
  2293. +           break;
  2294. +       } else {
  2295. +           TRACE("Journal recover pass scan: Found a revoke block, "
  2296. +               "skipping it\n");
  2297. +       }
  2298. +
  2299. +       nextBlock = _WrapAroundLog(nextBlock + 1);
  2300. +
  2301. +       status = MapBlock(nextBlock, nextBlockPos);
  2302. +       if (status != B_OK)
  2303. +           return status;
  2304. +
  2305. +       header = (JournalHeader*)cached.SetTo(nextBlockPos);
  2306. +   }
  2307. +
  2308. +   TRACE("Journal Recovery pass scan: Last detected transaction ID: %lu\n",
  2309. +       nextCommitID);
  2310. +
  2311. +   lastCommitID = nextCommitID;
  2312. +   return B_OK;
  2313. +}
  2314. +
  2315. +
  2316. +// Second pass: Collect all revoked blocks
  2317. +status_t
  2318. +Journal::_RecoverPassRevoke(uint32 lastCommitID)
  2319. +{
  2320. +   TRACE("Journal Recover: 2nd Pass: Revoke\n");
  2321. +
  2322. +   CachedBlock cached(fJournalVolume);
  2323. +   JournalHeader* header;
  2324. +   uint32 nextCommitID = fFirstCommitID;
  2325. +   uint32 nextBlock = fLogStart;
  2326. +   uint32 nextBlockPos;
  2327. +
  2328. +   status_t status = MapBlock(nextBlock, nextBlockPos);
  2329. +   if (status != B_OK)
  2330. +       return status;
  2331. +
  2332. +   header = (JournalHeader*)cached.SetTo(nextBlockPos);
  2333. +
  2334. +   while (nextCommitID < lastCommitID) {
  2335. +       if (!header->CheckMagic() || header->Sequence() != nextCommitID) {
  2336. +           // Somehow the log is different than the expexted
  2337. +           return B_ERROR;
  2338. +       }
  2339. +
  2340. +       uint32 blockType = header->BlockType();
  2341. +
  2342. +       if (blockType == JOURNAL_DESCRIPTOR_BLOCK)
  2343. +           nextBlock += _CountTags(header);
  2344. +       else if (blockType == JOURNAL_COMMIT_BLOCK)
  2345. +           nextCommitID++;
  2346. +       else if (blockType == JOURNAL_REVOKE_BLOCK) {
  2347. +           TRACE("Journal::_RecoverPassRevoke(): Found a revoke block\n");
  2348. +           status = fRevokeManager->ScanRevokeBlock(
  2349. +               (JournalRevokeHeader*)header, nextCommitID);
  2350. +
  2351. +           if (status != B_OK)
  2352. +               return status;
  2353. +       } else {
  2354. +               // TODO: Warn that we found an unrecognized block
  2355. +           break;
  2356. +       }
  2357. +
  2358. +       nextBlock = _WrapAroundLog(nextBlock + 1);
  2359. +
  2360. +       status = MapBlock(nextBlock, nextBlockPos);
  2361. +       if (status != B_OK)
  2362. +           return status;
  2363. +
  2364. +       header = (JournalHeader*)cached.SetTo(nextBlockPos);
  2365. +   }
  2366. +
  2367. +   if (nextCommitID != lastCommitID) {
  2368. +       // Possibly because of some sort of IO error
  2369. +       TRACE("Journal::_RecoverPassRevoke(): Incompatible commit IDs\n");
  2370. +       return B_ERROR;
  2371. +   }
  2372. +
  2373. +   TRACE("Journal recovery pass revoke: Revoked blocks: %lu\n",
  2374. +       fRevokeManager->NumRevokes());
  2375. +
  2376. +   return B_OK;
  2377. +}
  2378. +
  2379. +
  2380. +// Third pass: Replay log
  2381. +status_t
  2382. +Journal::_RecoverPassReplay(uint32 lastCommitID)
  2383. +{
  2384. +   TRACE("Journal Recover: 3rd Pass: Replay\n");
  2385. +
  2386. +   uint32 nextCommitID = fFirstCommitID;
  2387. +   uint32 nextBlock = fLogStart;
  2388. +   uint32 nextBlockPos;
  2389. +
  2390. +   status_t status = MapBlock(nextBlock, nextBlockPos);
  2391. +   if (status != B_OK)
  2392. +       return status;
  2393. +
  2394. +   CachedBlock cached(fJournalVolume);
  2395. +   JournalHeader* header = (JournalHeader*)cached.SetTo(nextBlockPos);
  2396. +
  2397. +   int count = 0;
  2398. +
  2399. +   uint8* data = new(std::nothrow) uint8[fBlockSize];
  2400. +   if (data == NULL) {
  2401. +       TRACE("Journal::_RecoverPassReplay(): Failed to allocate memory for "
  2402. +           "data\n");
  2403. +       return B_NO_MEMORY;
  2404. +   }
  2405. +  
  2406. +   ArrayDeleter<uint8> dataDeleter(data);
  2407. +
  2408. +   while (nextCommitID < lastCommitID) {
  2409. +       if (!header->CheckMagic() || header->Sequence() != nextCommitID) {
  2410. +           // Somehow the log is different than the expexted
  2411. +           TRACE("Journal::_RecoverPassReplay(): Wierd problem with block\n");
  2412. +           return B_ERROR;
  2413. +       }
  2414. +
  2415. +       uint32 blockType = header->BlockType();
  2416. +
  2417. +       if (blockType == JOURNAL_DESCRIPTOR_BLOCK) {
  2418. +           JournalBlockTag* last_tag = (JournalBlockTag*)((uint8*)header
  2419. +               + fBlockSize - sizeof(JournalBlockTag));
  2420. +
  2421. +           for (JournalBlockTag* tag = (JournalBlockTag*)header->data;
  2422. +               tag <= last_tag; ++tag) {
  2423. +               nextBlock = _WrapAroundLog(nextBlock + 1);
  2424. +
  2425. +               status = MapBlock(nextBlock, nextBlockPos);
  2426. +               if (status != B_OK)
  2427. +                   return status;
  2428. +
  2429. +               if (!fRevokeManager->Lookup(tag->BlockNumber(),
  2430. +                       nextCommitID)) {
  2431. +                   // Block isn't revoked
  2432. +                   size_t read = read_pos(fJournalVolume->Device(),
  2433. +                       nextBlockPos * fBlockSize, data, fBlockSize);
  2434. +                   if (read != fBlockSize)
  2435. +                       return B_IO_ERROR;
  2436. +
  2437. +                   if ((tag->Flags() & JOURNAL_FLAG_ESCAPED) != 0) {
  2438. +                       // Block is escaped
  2439. +                       ((int32*)data)[0]
  2440. +                           = B_HOST_TO_BENDIAN_INT32(JOURNAL_MAGIC);
  2441. +                   }
  2442. +
  2443. +                   TRACE("Journal::_RevoverPassReplay(): Write to %lu\n",
  2444. +                       tag->BlockNumber() * fBlockSize);
  2445. +                   size_t written = write_pos(fFilesystemVolume->Device(),
  2446. +                       tag->BlockNumber() * fBlockSize, data, fBlockSize);
  2447. +
  2448. +                   if (written != fBlockSize)
  2449. +                       return B_IO_ERROR;
  2450. +
  2451. +                   ++count;
  2452. +               }
  2453. +
  2454. +               if ((tag->Flags() & JOURNAL_FLAG_LAST_TAG) != 0)
  2455. +                   break;
  2456. +               if ((tag->Flags() & JOURNAL_FLAG_SAME_UUID) == 0) {
  2457. +                   // TODO: Check new UUID with file system UUID
  2458. +                   tag += 2;
  2459. +                       // sizeof(JournalBlockTag) = 8
  2460. +                       // sizeof(UUID) = 16
  2461. +               }
  2462. +           }
  2463. +       } else if (blockType == JOURNAL_COMMIT_BLOCK)
  2464. +           nextCommitID++;
  2465. +       else if (blockType != JOURNAL_REVOKE_BLOCK) {
  2466. +               // TODO: Warn that we found an unrecognized block
  2467. +           break;
  2468. +       } // If blockType == JOURNAL_REVOKE_BLOCK we just skip it
  2469. +
  2470. +       nextBlock = _WrapAroundLog(nextBlock + 1);
  2471. +
  2472. +       status = MapBlock(nextBlock, nextBlockPos);
  2473. +       if (status != B_OK)
  2474. +           return status;
  2475. +
  2476. +       header = (JournalHeader*)cached.SetTo(nextBlockPos);
  2477. +   }
  2478. +
  2479. +   if (nextCommitID != lastCommitID) {
  2480. +       // Possibly because of some sort of IO error
  2481. +       return B_ERROR;
  2482. +   }
  2483. +
  2484. +   TRACE("Journal recovery pass replay: Replayed blocks: %u\n", count);
  2485. +
  2486. +   return B_OK;
  2487. +}
  2488. +
  2489. +
  2490. +status_t
  2491. +Journal::_FlushLog(bool canWait, bool flushBlocks)
  2492. +{
  2493. +   TRACE("Journal::_FlushLog()\n");
  2494. +   status_t status = canWait ? recursive_lock_lock(&fLock)
  2495. +       : recursive_lock_trylock(&fLock);
  2496. +
  2497. +   TRACE("Journal::_FlushLog(): Acquired fLock, recursion: %ld\n",
  2498. +       recursive_lock_get_recursion(&fLock));
  2499. +   if (status != B_OK)
  2500. +       return status;
  2501. +
  2502. +   if (recursive_lock_get_recursion(&fLock) > 1) {
  2503. +       // Called from inside a transaction
  2504. +       recursive_lock_unlock(&fLock);
  2505. +       TRACE("Journal::_FlushLog(): Called from a transaction. Leaving...\n");
  2506. +       return B_OK;
  2507. +   }
  2508. +
  2509. +   if (fUnwrittenTransactions != 0 && _FullTransactionSize() != 0) {
  2510. +       status = _WriteTransactionToLog();
  2511. +       if (status < B_OK)
  2512. +           panic("Failed flushing transaction: %s\n", strerror(status));
  2513. +   }
  2514. +
  2515. +   TRACE("Journal::_FlushLog(): Attempting to flush journal volume at %p\n",
  2516. +       fJournalVolume);
  2517. +
  2518. +   // TODO: Not sure this is correct. Need to review...
  2519. +   // NOTE: Not correct. Causes double lock of a block cache mutex
  2520. +   // TODO: Need some other way to synchronize the journal...
  2521. +   /*status = fJournalVolume->FlushDevice();
  2522. +   if (status != B_OK)
  2523. +       return status;*/
  2524. +
  2525. +   TRACE("Journal::_FlushLog(): Flushed journal volume\n");
  2526. +
  2527. +   if (flushBlocks) {
  2528. +       TRACE("Journal::_FlushLog(): Attempting to flush file system volume "
  2529. +           "at %p\n", fFilesystemVolume);
  2530. +       status = fFilesystemVolume->FlushDevice();
  2531. +       if (status == B_OK)
  2532. +           TRACE("Journal::_FlushLog(): Flushed file system volume\n");
  2533. +   }
  2534. +
  2535. +   TRACE("Journal::_FlushLog(): Finished. Releasing lock\n");
  2536. +
  2537. +   recursive_lock_unlock(&fLock);
  2538. +  
  2539. +   TRACE("Journal::_FlushLog(): Done, final status: %s\n", strerror(status));
  2540. +   return status;
  2541. +}
  2542. +
  2543. +
  2544. +inline uint32
  2545. +Journal::_WrapAroundLog(uint32 block)
  2546. +{
  2547. +   TRACE("Journal::_WrapAroundLog()\n");
  2548. +   if (block >= fLogSize)
  2549. +       return block - fLogSize + fFirstLogBlock;
  2550. +   else
  2551. +       return block;
  2552. +}
  2553. +
  2554. +
  2555. +size_t
  2556. +Journal::_CurrentTransactionSize() const
  2557. +{
  2558. +   TRACE("Journal::_CurrentTransactionSize(): transaction %ld\n",
  2559. +       fTransactionID);
  2560. +
  2561. +   size_t count;
  2562. +
  2563. +   if (fHasSubTransaction) {
  2564. +       count = cache_blocks_in_sub_transaction(fFilesystemBlockCache,
  2565. +           fTransactionID);
  2566. +
  2567. +       TRACE("\tSub transaction size: %ld\n", count);
  2568. +   } else {
  2569. +       count =  cache_blocks_in_transaction(fFilesystemBlockCache,
  2570. +           fTransactionID);
  2571. +
  2572. +       TRACE("\tTransaction size: %ld\n", count);
  2573. +   }
  2574. +
  2575. +   return count;
  2576. +}
  2577. +
  2578. +
  2579. +size_t
  2580. +Journal::_FullTransactionSize() const
  2581. +{
  2582. +   TRACE("Journal::_FullTransactionSize(): transaction %ld\n", fTransactionID);
  2583. +   TRACE("\tFile sytem block cache: %p\n", fFilesystemBlockCache);
  2584. +
  2585. +   size_t count = cache_blocks_in_transaction(fFilesystemBlockCache,
  2586. +        fTransactionID);
  2587. +  
  2588. +   TRACE("\tFull transaction size: %ld\n", count);
  2589. +  
  2590. +   return count;
  2591. +}
  2592. +
  2593. +
  2594. +size_t
  2595. +Journal::_MainTransactionSize() const
  2596. +{
  2597. +   TRACE("Journal::_MainTransactionSize(): transaction %ld\n", fTransactionID);
  2598. +
  2599. +   size_t count =  cache_blocks_in_main_transaction(fFilesystemBlockCache,
  2600. +       fTransactionID);
  2601. +  
  2602. +   TRACE("\tMain transaction size: %ld\n", count);
  2603. +  
  2604. +   return count;
  2605. +}
  2606. +
  2607. +
  2608. +status_t
  2609. +Journal::_TransactionDone(bool success)
  2610. +{
  2611. +   if (!success) {
  2612. +       if (fHasSubTransaction) {
  2613. +           TRACE("Journal::_TransactionDone(): transaction %ld failed, "
  2614. +               "aborting subtransaction\n", fTransactionID);
  2615. +           cache_abort_sub_transaction(fFilesystemBlockCache, fTransactionID);
  2616. +           // parent is unaffected
  2617. +       } else {
  2618. +           TRACE("Journal::_TransactionDone(): transaction %ld failed,"
  2619. +               " aborting\n", fTransactionID);
  2620. +           cache_abort_transaction(fFilesystemBlockCache, fTransactionID);
  2621. +           fUnwrittenTransactions = 0;
  2622. +       }
  2623. +
  2624. +       TRACE("Journal::_TransactionDone(): returning B_OK\n");
  2625. +       return B_OK;
  2626. +   }
  2627. +  
  2628. +   // If possible, delay flushing the transaction
  2629. +   uint32 size = _FullTransactionSize();
  2630. +   TRACE("Journal::_TransactionDone(): full transaction size: %lu, max "
  2631. +       "transaction size: %lu, free log blocks: %lu\n", size,
  2632. +       fMaxTransactionSize, FreeLogBlocks());
  2633. +   if (fMaxTransactionSize > 0 && size < fMaxTransactionSize) {
  2634. +       TRACE("Journal::_TransactionDone(): delaying flush of transaction "
  2635. +           "%ld\n", fTransactionID);
  2636. +      
  2637. +       // Make sure the transaction fits in the log
  2638. +       if (size < FreeLogBlocks())
  2639. +           cache_sync_transaction(fFilesystemBlockCache, fTransactionID);
  2640. +      
  2641. +       fUnwrittenTransactions++;
  2642. +       TRACE("Journal::_TransactionDone(): returning B_OK\n");
  2643. +       return B_OK;
  2644. +   }
  2645. +
  2646. +   return _WriteTransactionToLog();
  2647. +}
  2648. +
  2649. +
  2650. +/*static*/ void
  2651. +Journal::_TransactionWritten(int32 transactionID, int32 event, void* _logEntry)
  2652. +{
  2653. +   LogEntry* logEntry = (LogEntry*)_logEntry;
  2654. +
  2655. +   TRACE("Journal::_TransactionWritten(): Transaction %ld checkpointed\n",
  2656. +       transactionID);
  2657. +
  2658. +   Journal* journal = logEntry->GetJournal();
  2659. +
  2660. +   TRACE("Journal::_TransactionWritten(): log entry: %p, journal: %p\n",
  2661. +       logEntry, journal);
  2662. +   TRACE("Journal::_TransactionWritten(): log entries: %p\n",
  2663. +       &journal->fLogEntries);
  2664. +
  2665. +   mutex_lock(&journal->fLogEntriesLock);
  2666. +
  2667. +   TRACE("Journal::_TransactionWritten(): first log entry: %p\n",
  2668. +       journal->fLogEntries.First());
  2669. +   if (logEntry == journal->fLogEntries.First()) {
  2670. +       TRACE("Journal::_TransactionWritten(): Moving start of log to %lu\n",
  2671. +           logEntry->Start());
  2672. +       journal->fLogStart = logEntry->Start();
  2673. +       journal->fFirstCommitID = logEntry->CommitID();
  2674. +       TRACE("Journal::_TransactionWritten(): Setting commit ID to %lu\n",
  2675. +           logEntry->CommitID());
  2676. +
  2677. +       if (journal->_SaveSuperBlock() != B_OK)
  2678. +           panic("ext2: Failed to write journal superblock\n");
  2679. +   }
  2680. +  
  2681. +   TRACE("Journal::_TransactionWritten(): Removing log entry\n");
  2682. +   journal->fLogEntries.Remove(logEntry);
  2683. +
  2684. +   TRACE("Journal::_TransactionWritten(): Unlocking entries list\n");
  2685. +   mutex_unlock(&journal->fLogEntriesLock);
  2686. +
  2687. +   TRACE("Journal::_TransactionWritten(): Deleting log entry at %p\n", logEntry);
  2688. +   delete logEntry;
  2689. +}
  2690. +
  2691. +
  2692. +/*static*/ void
  2693. +Journal::_TransactionIdle(int32 transactionID, int32 event, void* _journal)
  2694. +{
  2695. +   Journal* journal = (Journal*)_journal;
  2696. +   journal->_FlushLog(false, false);
  2697. +}
  2698.  
  2699. Property changes on: src/add-ons/kernel/file_systems/ext2/Journal.cpp
  2700. ___________________________________________________________________
  2701. Added: svn:executable
  2702.    + *
  2703.  
  2704. Index: src/add-ons/kernel/file_systems/ext2/NoJournal.h
  2705. ===================================================================
  2706. --- src/add-ons/kernel/file_systems/ext2/NoJournal.h    (revision 0)
  2707. +++ src/add-ons/kernel/file_systems/ext2/NoJournal.h    (revision 0)
  2708. @@ -0,0 +1,34 @@
  2709. +/*
  2710. + * Copyright 2001-2010, Haiku Inc. All rights reserved.
  2711. + * This file may be used under the terms of the MIT License.
  2712. + *
  2713. + * Authors:
  2714. + *     Janito V. Ferreira Filho
  2715. + */
  2716. +#ifndef NOJOURNAL_H
  2717. +#define NOJOURNAL_H
  2718. +
  2719. +
  2720. +#include "Journal.h"
  2721. +
  2722. +
  2723. +class NoJournal : public Journal {
  2724. +public:
  2725. +                       NoJournal(Volume* volume);
  2726. +                       ~NoJournal();
  2727. +
  2728. +           status_t    InitCheck();
  2729. +           status_t    Recover();
  2730. +           status_t    StartLog();
  2731. +          
  2732. +           status_t    Lock(Transaction* owner, bool separateSubTransactions);
  2733. +           status_t    Unlock(Transaction* owner, bool success);
  2734. +
  2735. +private:
  2736. +           status_t    _WriteTransactionToLog();
  2737. +
  2738. +   static  void        _TransactionWritten(int32 transactionID,
  2739. +                           int32 event, void* param);
  2740. +};
  2741. +
  2742. +#endif // NOJOURNAL_H
  2743. Index: src/add-ons/kernel/file_systems/ext2/HTree.h
  2744. ===================================================================
  2745. --- src/add-ons/kernel/file_systems/ext2/HTree.h    (revision 38119)
  2746. +++ src/add-ons/kernel/file_systems/ext2/HTree.h    (working copy)
  2747. @@ -9,8 +9,6 @@
  2748.  #define HTREE_H
  2749.  
  2750.  
  2751. -#include <AutoDeleter.h>
  2752. -
  2753.  #include "ext2.h"
  2754.  #include "DirectoryIterator.h"
  2755.  #include "HTreeEntryIterator.h"
  2756. @@ -26,14 +24,14 @@
  2757.  
  2758.  
  2759.  struct HTreeFakeDirEntry {
  2760. -   uint32              inode_num;
  2761. +   uint32              inode_id;
  2762.     uint16              entry_length;
  2763.     uint8               name_length;
  2764.     uint8               file_type;
  2765.     char                file_name[0];
  2766.    
  2767. -   uint32              Inode()
  2768. -       { return B_LENDIAN_TO_HOST_INT32(inode_num); }
  2769. +   uint32              InodeID() const
  2770. +       { return B_LENDIAN_TO_HOST_INT32(inode_id); }
  2771.  } _PACKED;
  2772.  
  2773.  struct HTreeCountLimit {
  2774. @@ -41,9 +39,15 @@
  2775.     uint16              count;
  2776.    
  2777.     uint16              Limit() const
  2778. -       { return B_LENDIAN_TO_HOST_INT32(limit); }
  2779. +       { return B_LENDIAN_TO_HOST_INT16(limit); }
  2780.     uint16              Count() const
  2781. -       { return B_LENDIAN_TO_HOST_INT32(count); }
  2782. +       { return B_LENDIAN_TO_HOST_INT16(count); }
  2783. +
  2784. +   void                SetLimit(uint16 value)
  2785. +       { limit = B_HOST_TO_LENDIAN_INT16(value); }
  2786. +
  2787. +   void                SetCount(uint16 value)
  2788. +       { count = B_HOST_TO_LENDIAN_INT16(value); }
  2789.  } _PACKED;
  2790.  
  2791.  struct HTreeEntry {
  2792. @@ -54,6 +58,12 @@
  2793.         { return B_LENDIAN_TO_HOST_INT32(hash); }
  2794.     uint32              Block() const
  2795.         { return B_LENDIAN_TO_HOST_INT32(block); }
  2796. +
  2797. +   void                SetHash(uint32 newHash)
  2798. +       { hash = B_HOST_TO_LENDIAN_INT32(newHash); }
  2799. +
  2800. +   void                SetBlock(uint32 newBlock)
  2801. +       { block = B_HOST_TO_LENDIAN_INT32(newBlock); }
  2802.  } _PACKED;
  2803.  
  2804.  struct HTreeRoot {
  2805. @@ -67,6 +77,8 @@
  2806.     uint8               root_info_length;
  2807.     uint8               indirection_levels;
  2808.     uint8               flags;
  2809. +
  2810. +   HTreeCountLimit     count_limit[0];
  2811.    
  2812.     bool            IsValid() const;
  2813.         // Implemented in HTree.cpp
  2814. @@ -94,17 +106,21 @@
  2815.                                 HTree(Volume* volume, Inode* directory);
  2816.                                 ~HTree();
  2817.  
  2818. +           status_t            PrepareForHash();
  2819. +           uint32              Hash(const char* name, uint8 length);
  2820. +
  2821.             status_t            Lookup(const char* name,
  2822.                                     DirectoryIterator** directory);
  2823.  
  2824. +   static  status_t            InitDir(Transaction& transaction, Inode* inode,
  2825. +                                   Inode* parent);
  2826. +
  2827.  private:
  2828.             status_t            _LookupInNode(uint32 hash, off_t& firstEntry,
  2829.                                     off_t& lastEntry,
  2830.                                     uint32 remainingIndirects);
  2831.            
  2832. -           uint32              _Hash(const char* name, uint8 version);
  2833. -          
  2834. -           uint32              _HashLegacy(const char* name);
  2835. +           uint32              _HashLegacy(const char* name, uint8 length);
  2836.  
  2837.     inline  uint32              _MD4F(uint32 x, uint32 y, uint32 z);
  2838.     inline  uint32              _MD4G(uint32 x, uint32 y, uint32 z);
  2839. @@ -113,21 +129,24 @@
  2840.                                     uint32& c, uint32& d);
  2841.             void                _HalfMD4Transform(uint32 buffer[4],
  2842.                                     uint32 blocks[8]);
  2843. -           uint32              _HashHalfMD4(const char* name);
  2844. +           uint32              _HashHalfMD4(const char* name, uint8 length);
  2845.            
  2846.             void                _TEATransform(uint32 buffer[4],
  2847.                                     uint32 blocks[4]);
  2848. -           uint32              _HashTEA(const char* name);
  2849. +           uint32              _HashTEA(const char* name, uint8 length);
  2850.            
  2851.             void                _PrepareBlocksForHash(const char* string,
  2852. -                                   int length, uint32* blocks, int numBlocks);
  2853. +                                   uint32 length, uint32* blocks, uint32 numBlocks);
  2854.  
  2855. +   inline  status_t            _FallbackToLinearIteration(
  2856. +                                   DirectoryIterator** iterator);
  2857. +
  2858.             bool                fIndexed;
  2859.             uint32              fBlockSize;
  2860.             Inode*              fDirectory;
  2861.             uint32              fHashSeed[4];
  2862.             HTreeEntryIterator* fRootEntry;
  2863. -           ObjectDeleter<HTreeEntryIterator> fRootDeleter;
  2864. +           uint8               fHashVersion;
  2865.  };
  2866.  
  2867.  #endif // HTREE_H
  2868.  
  2869. Property changes on: src/add-ons/kernel/file_systems/ext2/HTree.h
  2870. ___________________________________________________________________
  2871. Added: svn:executable
  2872.    + *
  2873.  
  2874. Index: src/add-ons/kernel/file_systems/ext2/IndexedDirectoryIterator.cpp
  2875. ===================================================================
  2876. --- src/add-ons/kernel/file_systems/ext2/IndexedDirectoryIterator.cpp   (revision 38119)
  2877. +++ src/add-ons/kernel/file_systems/ext2/IndexedDirectoryIterator.cpp   (working copy)
  2878. @@ -1,75 +0,0 @@
  2879. -/*
  2880. - * Copyright 2010, Haiku Inc. All rights reserved.
  2881. - * This file may be used under the terms of the MIT License.
  2882. - *
  2883. - * Authors:
  2884. - *     Janito V. Ferreira Filho
  2885. - */
  2886. -
  2887. -
  2888. -#include "IndexedDirectoryIterator.h"
  2889. -
  2890. -#include "ext2.h"
  2891. -#include "HTree.h"
  2892. -#include "HTreeEntryIterator.h"
  2893. -#include "Inode.h"
  2894. -
  2895. -
  2896. -//#define TRACE_EXT2
  2897. -#ifdef TRACE_EXT2
  2898. -#  define TRACE(x...) dprintf("\33[34mext2:\33[0m " x)
  2899. -#else
  2900. -#  define TRACE(x...) ;
  2901. -#endif
  2902. -
  2903. -
  2904. -IndexedDirectoryIterator::IndexedDirectoryIterator(off_t start,
  2905. -   uint32 blockSize, Inode* directory, HTreeEntryIterator* parent)
  2906. -   :
  2907. -   DirectoryIterator(directory),
  2908. -   fIndexing(true),
  2909. -  
  2910. -   fParent(parent),
  2911. -   fMaxOffset(start + blockSize),
  2912. -   fBlockSize(blockSize),
  2913. -   fMaxAttempts(0)
  2914. -{
  2915. -   fOffset = start;
  2916. -}
  2917. -
  2918. -
  2919. -IndexedDirectoryIterator::~IndexedDirectoryIterator()
  2920. -{
  2921. -}
  2922. -
  2923. -
  2924. -status_t
  2925. -IndexedDirectoryIterator::GetNext(char* name, size_t* nameLength, ino_t* id)
  2926. -{
  2927. -   if (fIndexing && fOffset + sizeof(HTreeFakeDirEntry) >= fMaxOffset) {
  2928. -       TRACE("IndexedDirectoryIterator::GetNext() calling next block\n");
  2929. -       status_t status = fParent->GetNext(fOffset);
  2930. -       if (status != B_OK)
  2931. -           return status;
  2932. -
  2933. -       if (fMaxAttempts++ > 4)
  2934. -           return B_ERROR;
  2935. -      
  2936. -       fMaxOffset = fOffset + fBlockSize;
  2937. -   }
  2938. -  
  2939. -   return DirectoryIterator::GetNext(name, nameLength, id);
  2940. -}
  2941. -
  2942. -
  2943. -status_t
  2944. -IndexedDirectoryIterator::Rewind()
  2945. -{
  2946. -   // The only way to rewind it is too loose indexing
  2947. -  
  2948. -   fOffset = 0;
  2949. -   fMaxOffset = fInode->Size();
  2950. -   fIndexing = false;
  2951. -
  2952. -   return B_OK;
  2953. -}
  2954. Index: src/add-ons/kernel/file_systems/ext2/DirectoryIterator.h
  2955. ===================================================================
  2956. --- src/add-ons/kernel/file_systems/ext2/DirectoryIterator.h    (revision 38119)
  2957. +++ src/add-ons/kernel/file_systems/ext2/DirectoryIterator.h    (working copy)
  2958. @@ -6,28 +6,77 @@
  2959.  #define DIRECTORY_ITERATOR_H
  2960.  
  2961.  
  2962. +#include <AutoDeleter.h>
  2963.  #include <SupportDefs.h>
  2964.  
  2965. +#include "Transaction.h"
  2966.  
  2967. +
  2968. +class HTreeEntryIterator;
  2969.  class Inode;
  2970.  
  2971.  class DirectoryIterator {
  2972.  public:
  2973. -                       DirectoryIterator(Inode* inode);
  2974. -   virtual             ~DirectoryIterator();
  2975. +                       DirectoryIterator(Inode* inode, off_t start = 0,
  2976. +                           HTreeEntryIterator* parent = NULL);
  2977. +                       ~DirectoryIterator();
  2978.  
  2979. -   virtual status_t    GetNext(char* name, size_t* _nameLength, ino_t* id);
  2980. +           status_t    InitCheck();
  2981.  
  2982. -   virtual status_t    Rewind();
  2983.  
  2984. +           status_t    Next();
  2985. +           status_t    Get(char* name, size_t* _nameLength, ino_t* id);
  2986. +
  2987. +           status_t    Rewind();
  2988. +           void        Restart();
  2989. +
  2990. +           status_t    AddEntry(Transaction& transaction, const char* name,
  2991. +                           size_t nameLength, ino_t id, uint8 type);
  2992. +           status_t    FindEntry(const char* name, ino_t* id = NULL);
  2993. +           status_t    RemoveEntry(Transaction& transaction);
  2994. +
  2995. +           status_t    ChangeEntry(Transaction& transaction, ino_t id,
  2996. +                           uint8 fileType);
  2997. +
  2998.  private:
  2999.                         DirectoryIterator(const DirectoryIterator&);
  3000.                         DirectoryIterator &operator=(const DirectoryIterator&);
  3001.                             // no implementation
  3002.  
  3003. +
  3004.  protected:
  3005. -   Inode*              fInode;
  3006. -   off_t               fOffset;
  3007. +           status_t    _AllocateBestEntryInBlock(uint8 nameLength, uint16& pos,
  3008. +                           uint16& newLength);
  3009. +           status_t    _AddEntry(Transaction& transaction, const char* name,
  3010. +                           uint8 nameLength, ino_t id, uint8 fileType,
  3011. +                           uint16 newLength, uint16 pos,
  3012. +                           bool hasPrevious = true);
  3013. +           status_t    _SplitIndexedBlock(Transaction& transaction,
  3014. +                           const char* name, uint8 nameLength, ino_t id,
  3015. +                           bool firstSplit = false);
  3016. +
  3017. +           status_t    _NextBlock();
  3018. +
  3019. +
  3020. +   Inode*              fDirectory;
  3021. +   Volume*             fVolume;
  3022. +   uint32              fBlockSize;
  3023. +   HTreeEntryIterator* fParent;
  3024. +   bool                fIndexing;
  3025. +
  3026. +   uint32              fLogicalBlock;
  3027. +   uint32              fPhysicalBlock;
  3028. +   uint32              fDisplacement;
  3029. +   uint32              fPreviousDisplacement;
  3030. +
  3031. +   uint32              fStartPhysicalBlock;
  3032. +   uint32              fStartLogicalBlock;
  3033. +   uint32              fStartDisplacement;
  3034. +
  3035. +   ObjectDeleter<HTreeEntryIterator> fParentDeleter;
  3036. +
  3037. +   status_t            fInitStatus;
  3038.  };
  3039.  
  3040.  #endif // DIRECTORY_ITERATOR_H
  3041. +
  3042. Index: src/add-ons/kernel/file_systems/ext2/DataStream.cpp
  3043. ===================================================================
  3044. --- src/add-ons/kernel/file_systems/ext2/DataStream.cpp (revision 0)
  3045. +++ src/add-ons/kernel/file_systems/ext2/DataStream.cpp (revision 0)
  3046. @@ -0,0 +1,642 @@
  3047. +/*
  3048. + * Copyright 2001-2010, Haiku Inc. All rights reserved.
  3049. + * This file may be used under the terms of the MIT License.
  3050. + *
  3051. + * Authors:
  3052. + *     Janito V. Ferreira Filho
  3053. + */
  3054. +
  3055. +
  3056. +#include "DataStream.h"
  3057. +
  3058. +#include "CachedBlock.h"
  3059. +#include "Volume.h"
  3060. +
  3061. +
  3062. +//#define TRACE_EXT2
  3063. +#ifdef TRACE_EXT2
  3064. +#  define TRACE(x...) dprintf("\33[34mext2:\33[0m " x)
  3065. +#else
  3066. +#  define TRACE(x...) ;
  3067. +#endif
  3068. +
  3069. +
  3070. +DataStream::DataStream(Volume* volume, ext2_data_stream* stream,
  3071. +   off_t size)
  3072. +   :
  3073. +   kBlockSize(volume->BlockSize()),
  3074. +   kIndirectsPerBlock(kBlockSize / 4),
  3075. +   kIndirectsPerBlock2(kIndirectsPerBlock * kIndirectsPerBlock),
  3076. +   kIndirectsPerBlock3(kIndirectsPerBlock2 * kIndirectsPerBlock),
  3077. +   kMaxDirect(EXT2_DIRECT_BLOCKS),
  3078. +   kMaxIndirect(kMaxDirect + kIndirectsPerBlock),
  3079. +   kMaxDoubleIndirect(kMaxIndirect + kIndirectsPerBlock2),
  3080. +   fVolume(volume),
  3081. +   fStream(stream),
  3082. +   fFirstBlock(volume->FirstDataBlock()),
  3083. +   fAllocated(0),
  3084. +   fAllocatedPos(fFirstBlock),
  3085. +   fWaiting(0),
  3086. +   fFreeStart(0),
  3087. +   fFreeCount(0),
  3088. +   fRemovedBlocks(0)
  3089. +{
  3090. +   fNumBlocks = size == 0 ? 0 : (size - 1) / kBlockSize + 1;
  3091. +}
  3092. +
  3093. +
  3094. +DataStream::~DataStream()
  3095. +{
  3096. +}
  3097. +
  3098. +
  3099. +status_t
  3100. +DataStream::Enlarge(Transaction& transaction, uint32 numBlocks)
  3101. +{
  3102. +   TRACE("DataStream::Enlarge(): current size: %lu, target size: %lu\n",
  3103. +       fNumBlocks, numBlocks);
  3104. +  
  3105. +   fWaiting = _BlocksNeeded(numBlocks);
  3106. +
  3107. +   status_t status;
  3108. +
  3109. +   if (fNumBlocks <= kMaxDirect) {
  3110. +       status = _AddForDirectBlocks(transaction, numBlocks);
  3111. +
  3112. +       if (status != B_OK)
  3113. +           return status;
  3114. +
  3115. +       TRACE("DataStream::Enlarge(): current size: %lu, target size: %lu\n",
  3116. +           fNumBlocks, numBlocks);
  3117. +  
  3118. +       if (fNumBlocks == numBlocks)
  3119. +           return B_OK;
  3120. +   }
  3121. +
  3122. +   if (fNumBlocks <= kMaxIndirect) {
  3123. +       status = _AddForIndirectBlock(transaction, numBlocks);
  3124. +
  3125. +       if (status != B_OK)
  3126. +           return status;
  3127. +
  3128. +       TRACE("DataStream::Enlarge(): current size: %lu, target size: %lu\n",
  3129. +           fNumBlocks, numBlocks);
  3130. +  
  3131. +       if (fNumBlocks == numBlocks)
  3132. +           return B_OK;
  3133. +   }
  3134. +
  3135. +   if (fNumBlocks <= kMaxDoubleIndirect) {
  3136. +       status = _AddForDoubleIndirectBlock(transaction, numBlocks);
  3137. +
  3138. +       if (status != B_OK)
  3139. +           return status;
  3140. +
  3141. +       TRACE("DataStream::Enlarge(): current size: %lu, target size: %lu\n",
  3142. +           fNumBlocks, numBlocks);
  3143. +  
  3144. +       if (fNumBlocks == numBlocks)
  3145. +           return B_OK;
  3146. +   }
  3147. +
  3148. +   TRACE("DataStream::Enlarge(): allocated: %lu, waiting: %lu\n", fAllocated,
  3149. +       fWaiting);
  3150. +
  3151. +   return _AddForTripleIndirectBlock(transaction, numBlocks);
  3152. +}
  3153. +
  3154. +
  3155. +status_t
  3156. +DataStream::Shrink(Transaction& transaction, uint32 numBlocks)
  3157. +{
  3158. +   TRACE("DataStream::Shrink(): current size: %lu, target size: %lu\n",
  3159. +       fNumBlocks, numBlocks);
  3160. +
  3161. +   fFreeStart = 0;
  3162. +   fFreeCount = 0;
  3163. +   fRemovedBlocks = 0;
  3164. +
  3165. +   uint32 blocksToRemove = fNumBlocks - numBlocks;
  3166. +
  3167. +   status_t status;
  3168. +
  3169. +   if (numBlocks < kMaxDirect) {
  3170. +       status = _RemoveFromDirectBlocks(transaction, numBlocks);
  3171. +
  3172. +       if (status != B_OK)
  3173. +           return status;
  3174. +
  3175. +       if (fRemovedBlocks == blocksToRemove) {
  3176. +           fNumBlocks -= fRemovedBlocks;
  3177. +           return _PerformFree(transaction);
  3178. +       }
  3179. +   }
  3180. +
  3181. +   if (numBlocks < kMaxIndirect) {
  3182. +       status = _RemoveFromIndirectBlock(transaction, numBlocks);
  3183. +
  3184. +       if (status != B_OK)
  3185. +           return status;
  3186. +
  3187. +       if (fRemovedBlocks == blocksToRemove) {
  3188. +           fNumBlocks -= fRemovedBlocks;
  3189. +           return _PerformFree(transaction);
  3190. +       }
  3191. +   }
  3192. +
  3193. +   if (numBlocks < kMaxDoubleIndirect) {
  3194. +       status = _RemoveFromDoubleIndirectBlock(transaction, numBlocks);
  3195. +
  3196. +       if (status != B_OK)
  3197. +           return status;
  3198. +
  3199. +       if (fRemovedBlocks == blocksToRemove) {
  3200. +           fNumBlocks -= fRemovedBlocks;
  3201. +           return _PerformFree(transaction);
  3202. +       }
  3203. +   }
  3204. +
  3205. +   status = _RemoveFromTripleIndirectBlock(transaction, numBlocks);
  3206. +
  3207. +   if (status != B_OK)
  3208. +       return status;
  3209. +
  3210. +   fNumBlocks -= fRemovedBlocks;
  3211. +   return _PerformFree(transaction);
  3212. +}
  3213. +
  3214. +
  3215. +uint32
  3216. +DataStream::_BlocksNeeded(uint32 numBlocks)
  3217. +{
  3218. +   TRACE("DataStream::BlocksNeeded(): num blocks %lu\n", numBlocks);
  3219. +   uint32 blocksNeeded = 0;
  3220. +
  3221. +   if (numBlocks > fNumBlocks) {
  3222. +       blocksNeeded += numBlocks - fNumBlocks;
  3223. +
  3224. +       if (numBlocks > kMaxDirect) {
  3225. +           if (fNumBlocks <= kMaxDirect)
  3226. +               blocksNeeded += 1;
  3227. +
  3228. +           if (numBlocks > kMaxIndirect) {
  3229. +               if (fNumBlocks <= kMaxIndirect) {
  3230. +                   blocksNeeded += 2 + (numBlocks - kMaxIndirect - 1)
  3231. +                       / kIndirectsPerBlock;
  3232. +               } else {
  3233. +                   blocksNeeded += (numBlocks - fNumBlocks)
  3234. +                       / kIndirectsPerBlock;
  3235. +
  3236. +                   uint32 halfIndirectsPerBlock = kIndirectsPerBlock / 2;
  3237. +                   uint32 remCurrent = (fNumBlocks - kMaxIndirect - 1)
  3238. +                       % kIndirectsPerBlock;
  3239. +                   uint32 remTarget = (numBlocks - kMaxIndirect - 1)
  3240. +                       % kIndirectsPerBlock;
  3241. +
  3242. +                   if ((remCurrent >= halfIndirectsPerBlock
  3243. +                           && remTarget < halfIndirectsPerBlock)
  3244. +                       || (remCurrent > halfIndirectsPerBlock
  3245. +                           && remTarget <= halfIndirectsPerBlock))
  3246. +                       blocksNeeded++;
  3247. +               }
  3248. +
  3249. +               if (numBlocks > kMaxDoubleIndirect) {
  3250. +                   if (fNumBlocks <= kMaxDoubleIndirect) {
  3251. +                       blocksNeeded += 2 + (numBlocks - kMaxDoubleIndirect - 1)
  3252. +                           / kIndirectsPerBlock2;
  3253. +                   } else {
  3254. +                       blocksNeeded += (numBlocks - fNumBlocks)
  3255. +                           / kIndirectsPerBlock2;
  3256. +
  3257. +                       uint32 halfIndirectsPerBlock2 = kIndirectsPerBlock2 / 2;
  3258. +                       uint32 remCurrent = (fNumBlocks - kMaxDoubleIndirect
  3259. +                               - 1)
  3260. +                           % kIndirectsPerBlock2;
  3261. +                       uint32 remTarget = (numBlocks - kMaxDoubleIndirect - 1)
  3262. +                           % kIndirectsPerBlock2;
  3263. +
  3264. +                       if ((remCurrent >= halfIndirectsPerBlock2
  3265. +                               && remTarget < halfIndirectsPerBlock2)
  3266. +                           || (remCurrent > halfIndirectsPerBlock2
  3267. +                               && remTarget <= halfIndirectsPerBlock2))
  3268. +                           blocksNeeded++;
  3269. +                   }
  3270. +               }
  3271. +           }
  3272. +       }
  3273. +   }
  3274. +
  3275. +   TRACE("DataStream::BlocksNeeded(): %lu\n", blocksNeeded);
  3276. +   return blocksNeeded;
  3277. +}
  3278. +
  3279. +
  3280. +
  3281. +
  3282. +status_t
  3283. +DataStream::_GetBlock(Transaction& transaction, uint32& block)
  3284. +{
  3285. +   TRACE("DataStream::_GetBlock(): allocated: %lu, pos: %lu, waiting: %lu\n",
  3286. +       fAllocated, fAllocatedPos, fWaiting);
  3287. +
  3288. +   if (fAllocated == 0) {
  3289. +       uint32 blockGroup = (fAllocatedPos - fFirstBlock)
  3290. +           / fVolume->BlocksPerGroup();
  3291. +       fAllocatedPos %= fVolume->BlocksPerGroup();
  3292. +
  3293. +       status_t status = fVolume->AllocateBlocks(transaction, 1, fWaiting,
  3294. +           blockGroup, fAllocatedPos, fAllocated);
  3295. +       if (status != B_OK)
  3296. +           return status;
  3297. +
  3298. +       fWaiting -= fAllocated;
  3299. +       fAllocatedPos += fVolume->BlocksPerGroup() * blockGroup + fFirstBlock;
  3300. +   }
  3301. +
  3302. +   fAllocated--;
  3303. +   block = fAllocatedPos++;
  3304. +
  3305. +   return B_OK;
  3306. +}
  3307. +
  3308. +
  3309. +status_t
  3310. +DataStream::_PrepareBlock(Transaction& transaction, uint32* pos,
  3311. +   uint32& blockNum, bool& clear)
  3312. +{
  3313. +   blockNum = B_LENDIAN_TO_HOST_INT32(*pos);
  3314. +   clear = false;
  3315. +
  3316. +   if (blockNum == 0) {
  3317. +       status_t status = _GetBlock(transaction, blockNum);
  3318. +       if (status != B_OK)
  3319. +           return status;
  3320. +
  3321. +       *pos = B_HOST_TO_LENDIAN_INT32(blockNum);
  3322. +       clear = true;
  3323. +   }
  3324. +
  3325. +   return B_OK;
  3326. +}
  3327. +
  3328. +
  3329. +status_t
  3330. +DataStream::_AddBlocks(Transaction& transaction, uint32* block, uint32 _count)
  3331. +{
  3332. +   uint32 count = _count;
  3333. +   TRACE("DataStream::_AddBlocks(): count: %lu\n", count);
  3334. +
  3335. +   while (count > 0) {
  3336. +       uint32 blockNum;
  3337. +       status_t status = _GetBlock(transaction, blockNum);
  3338. +       if (status != B_OK)
  3339. +           return status;
  3340. +
  3341. +       *(block++) = B_HOST_TO_LENDIAN_INT32(blockNum);
  3342. +       --count;
  3343. +   }
  3344. +
  3345. +   fNumBlocks += _count;
  3346. +
  3347. +   return B_OK;
  3348. +}
  3349. +
  3350. +
  3351. +status_t
  3352. +DataStream::_AddBlocks(Transaction& transaction, uint32* block, uint32 start,
  3353. +   uint32 end, int recursion)
  3354. +{
  3355. +   TRACE("DataStream::_AddBlocks(): start: %lu, end %lu, recursion: %d\n",
  3356. +       start, end, recursion);
  3357. +
  3358. +   bool clear;
  3359. +   uint32 blockNum;
  3360. +   status_t status = _PrepareBlock(transaction, block, blockNum, clear);
  3361. +   if (status != B_OK)
  3362. +       return status;
  3363. +
  3364. +   CachedBlock cached(fVolume);   
  3365. +   uint32* childBlock = (uint32*)cached.SetToWritable(transaction, blockNum,
  3366. +       clear);
  3367. +   if (childBlock == NULL)
  3368. +       return B_IO_ERROR;
  3369. +
  3370. +   if (recursion == 0)
  3371. +       return _AddBlocks(transaction, &childBlock[start], end - start);
  3372. +
  3373. +   uint32 elementWidth;
  3374. +   if (recursion == 1)
  3375. +       elementWidth = kIndirectsPerBlock;
  3376. +   else if (recursion == 2)
  3377. +       elementWidth = kIndirectsPerBlock2;
  3378. +   else {
  3379. +       panic("Undefinied recursion level\n");
  3380. +       elementWidth = 0;
  3381. +   }
  3382. +
  3383. +   uint32 elementPos = start / elementWidth;
  3384. +   uint32 endPos = end / elementWidth;
  3385. +
  3386. +   TRACE("DataStream::_AddBlocks(): element pos: %lu, end pos: %lu\n",
  3387. +       elementPos, endPos);
  3388. +
  3389. +   recursion--;
  3390. +
  3391. +   if (elementPos == endPos) {
  3392. +       return _AddBlocks(transaction, &childBlock[elementPos],
  3393. +           start % elementWidth, end % elementWidth, recursion);
  3394. +   }
  3395. +  
  3396. +   if (start % elementWidth != 0) {
  3397. +       status = _AddBlocks(transaction, &childBlock[elementPos],
  3398. +           start % elementWidth, elementWidth, recursion);
  3399. +       if (status != B_OK)
  3400. +           return status;
  3401. +
  3402. +       elementPos++;
  3403. +   }
  3404. +
  3405. +   while (elementPos < endPos) {
  3406. +       status = _AddBlocks(transaction, &childBlock[elementPos], 0,
  3407. +           elementWidth, recursion);
  3408. +       if (status != B_OK)
  3409. +           return status;
  3410. +
  3411. +       elementPos++;
  3412. +   }
  3413. +
  3414. +   if (end % elementWidth != 0) {
  3415. +       status = _AddBlocks(transaction, &childBlock[elementPos], 0,
  3416. +           end % elementWidth, recursion);
  3417. +       if (status != B_OK)
  3418. +           return status;
  3419. +   }
  3420. +      
  3421. +   return B_OK;
  3422. +}
  3423. +
  3424. +
  3425. +status_t
  3426. +DataStream::_AddForDirectBlocks(Transaction& transaction, uint32 numBlocks)
  3427. +{
  3428. +   TRACE("DataStream::_AddForDirectBlocks(): current size: %lu, target size: "
  3429. +       "%lu\n", fNumBlocks, numBlocks);
  3430. +   uint32* direct = &fStream->direct[fNumBlocks];
  3431. +   uint32 end = numBlocks > kMaxDirect ? kMaxDirect : numBlocks;
  3432. +
  3433. +   return _AddBlocks(transaction, direct, end - fNumBlocks);
  3434. +}
  3435. +
  3436. +
  3437. +status_t
  3438. +DataStream::_AddForIndirectBlock(Transaction& transaction, uint32 numBlocks)
  3439. +{
  3440. +   TRACE("DataStream::_AddForIndirectBlocks(): current size: %lu, target "
  3441. +       "size: %lu\n", fNumBlocks, numBlocks);
  3442. +   uint32 *indirect = &fStream->indirect;
  3443. +   uint32 start = fNumBlocks - kMaxDirect;
  3444. +   uint32 end = numBlocks - kMaxDirect;
  3445. +
  3446. +   if (end > kIndirectsPerBlock)
  3447. +       end = kIndirectsPerBlock;
  3448. +
  3449. +   return _AddBlocks(transaction, indirect, start, end, 0);
  3450. +}
  3451. +
  3452. +
  3453. +status_t
  3454. +DataStream::_AddForDoubleIndirectBlock(Transaction& transaction,
  3455. +   uint32 numBlocks)
  3456. +{
  3457. +   TRACE("DataStream::_AddForDoubleIndirectBlock(): current size: %lu, "
  3458. +       "target size: %lu\n", fNumBlocks, numBlocks);
  3459. +   uint32 *doubleIndirect = &fStream->double_indirect;
  3460. +   uint32 start = fNumBlocks - kMaxIndirect;
  3461. +   uint32 end = numBlocks - kMaxIndirect;
  3462. +
  3463. +   if (end > kIndirectsPerBlock2)
  3464. +       end = kIndirectsPerBlock2;
  3465. +
  3466. +   return _AddBlocks(transaction, doubleIndirect, start, end, 1);
  3467. +}
  3468. +
  3469. +
  3470. +
  3471. +status_t
  3472. +DataStream::_AddForTripleIndirectBlock(Transaction& transaction,
  3473. +   uint32 numBlocks)
  3474. +{
  3475. +   TRACE("DataStream::_AddForTripleIndirectBlock(): current size: %lu, "
  3476. +       "target size: %lu\n", fNumBlocks, numBlocks);
  3477. +   uint32 *tripleIndirect = &fStream->triple_indirect;
  3478. +   uint32 start = fNumBlocks - kMaxDoubleIndirect;
  3479. +   uint32 end = numBlocks - kMaxDoubleIndirect;
  3480. +
  3481. +   return _AddBlocks(transaction, tripleIndirect, start, end, 2);
  3482. +}
  3483. +
  3484. +
  3485. +status_t
  3486. +DataStream::_PerformFree(Transaction& transaction)
  3487. +{
  3488. +   TRACE("DataStream::_PerformFree(): start: %lu, count: %lu\n", fFreeStart,
  3489. +       fFreeCount);
  3490. +   status_t status;
  3491. +
  3492. +   if (fFreeCount == 0)
  3493. +       status = B_OK;
  3494. +   else
  3495. +       status = fVolume->FreeBlocks(transaction, fFreeStart, fFreeCount);
  3496. +
  3497. +   fFreeStart = 0;
  3498. +   fFreeCount = 0;
  3499. +
  3500. +   return status;
  3501. +}
  3502. +
  3503. +
  3504. +status_t
  3505. +DataStream::_MarkBlockForRemoval(Transaction& transaction, uint32* block)
  3506. +{
  3507. +   TRACE("DataStream::_MarkBlockForRemoval(*(%p) = %lu): free start: %lu, "
  3508. +       "free count: %lu\n", block, *block, fFreeStart, fFreeCount);
  3509. +   uint32 blockNum = B_LENDIAN_TO_HOST_INT32(*block)
  3510. +   *block = 0;
  3511. +
  3512. +   if (blockNum != fFreeStart + fFreeCount) {
  3513. +       if (fFreeCount != 0) {
  3514. +           status_t status = fVolume->FreeBlocks(transaction, fFreeStart,
  3515. +               fFreeCount);
  3516. +           if (status != B_OK)
  3517. +               return status;
  3518. +       }
  3519. +
  3520. +       fFreeStart = blockNum;
  3521. +       fFreeCount = 0;
  3522. +   }
  3523. +
  3524. +   fFreeCount++;
  3525. +
  3526. +   return B_OK;
  3527. +}
  3528. +
  3529. +
  3530. +status_t
  3531. +DataStream::_FreeBlocks(Transaction& transaction, uint32* block, uint32 _count)
  3532. +{
  3533. +   uint32 count = _count;
  3534. +   TRACE("DataStream::_FreeBlocks(%p, %lu)\n", block, count);
  3535. +
  3536. +   while (count > 0) {
  3537. +       status_t status = _MarkBlockForRemoval(transaction, block);
  3538. +       if (status != B_OK)
  3539. +           return status;
  3540. +
  3541. +       block++;
  3542. +       count--;
  3543. +   }
  3544. +
  3545. +   fRemovedBlocks += _count;
  3546. +
  3547. +   return B_OK;
  3548. +}
  3549. +
  3550. +
  3551. +status_t
  3552. +DataStream::_FreeBlocks(Transaction& transaction, uint32* block, uint32 start,
  3553. +   uint32 end, bool freeParent, int recursion)
  3554. +{
  3555. +   // TODO: Designed specifically for shrinking. Perhaps make it more general?
  3556. +   TRACE("DataStream::_FreeBlocks(%p, %lu, %lu, %c, %d)\n",
  3557. +       block, start, end, freeParent ? 't' : 'f', recursion);
  3558. +
  3559. +   uint32 blockNum = B_LENDIAN_TO_HOST_INT32(*block);
  3560. +
  3561. +   if (freeParent) {
  3562. +       status_t status = _MarkBlockForRemoval(transaction, block);
  3563. +       if (status != B_OK)
  3564. +           return status;
  3565. +   }
  3566. +
  3567. +   CachedBlock cached(fVolume);
  3568. +   uint32* childBlock = (uint32*)cached.SetToWritable(transaction, blockNum);
  3569. +   if (childBlock == NULL)
  3570. +       return B_IO_ERROR;
  3571. +
  3572. +   if (recursion == 0)
  3573. +       return _FreeBlocks(transaction, &childBlock[start], end - start);
  3574. +
  3575. +   uint32 elementWidth;
  3576. +   if (recursion == 1)
  3577. +       elementWidth = kIndirectsPerBlock;
  3578. +   else if (recursion == 2)
  3579. +       elementWidth = kIndirectsPerBlock2;
  3580. +   else {
  3581. +       panic("Undefinied recursion level\n");
  3582. +       elementWidth = 0;
  3583. +   }
  3584. +
  3585. +   uint32 elementPos = start / elementWidth;
  3586. +   uint32 endPos = end / elementWidth;
  3587. +
  3588. +   recursion--;
  3589. +
  3590. +   if (elementPos == endPos) {
  3591. +       bool free = freeParent || start % elementWidth == 0;
  3592. +       return _FreeBlocks(transaction, &childBlock[elementPos],
  3593. +           start % elementWidth, end % elementWidth, free, recursion);
  3594. +   }
  3595. +
  3596. +   status_t status = B_OK;
  3597. +
  3598. +   if (start % elementWidth != 0) {
  3599. +       status = _FreeBlocks(transaction, &childBlock[elementPos],
  3600. +           start % elementWidth, elementWidth, false, recursion);
  3601. +       if (status != B_OK)
  3602. +           return status;
  3603. +
  3604. +       elementPos++;
  3605. +   }
  3606. +
  3607. +   while (elementPos < endPos) {
  3608. +       status = _FreeBlocks(transaction, &childBlock[elementPos], 0,
  3609. +           elementWidth, true, recursion);
  3610. +       if (status != B_OK)
  3611. +           return status;
  3612. +
  3613. +       elementPos++;
  3614. +   }
  3615. +
  3616. +   if (end % elementWidth != 0) {
  3617. +       status = _FreeBlocks(transaction, &childBlock[elementPos], 0,
  3618. +           end % elementWidth, true, recursion);
  3619. +   }
  3620. +
  3621. +   return status;
  3622. +}
  3623. +
  3624. +
  3625. +status_t
  3626. +DataStream::_RemoveFromDirectBlocks(Transaction& transaction, uint32 numBlocks)
  3627. +{
  3628. +   TRACE("DataStream::_RemoveFromDirectBlocks(): current size: %lu, "
  3629. +       "target size: %lu\n", fNumBlocks, numBlocks);
  3630. +   uint32* direct = &fStream->direct[numBlocks];
  3631. +   uint32 end = fNumBlocks > kMaxDirect ? kMaxDirect : fNumBlocks;
  3632. +
  3633. +   return _FreeBlocks(transaction, direct, end - numBlocks);
  3634. +}
  3635. +
  3636. +
  3637. +status_t
  3638. +DataStream::_RemoveFromIndirectBlock(Transaction& transaction, uint32 numBlocks)
  3639. +{
  3640. +   TRACE("DataStream::_RemoveFromIndirectBlock(): current size: %lu, "
  3641. +       "target size: %lu\n", fNumBlocks, numBlocks);
  3642. +   uint32* indirect = &fStream->indirect;
  3643. +   uint32 start = numBlocks <= kMaxDirect ? 0 : numBlocks - kMaxDirect;
  3644. +   uint32 end = fNumBlocks - kMaxDirect;
  3645. +
  3646. +   if (end > kIndirectsPerBlock)
  3647. +       end = kIndirectsPerBlock;
  3648. +
  3649. +   bool freeAll = start == 0;
  3650. +
  3651. +   return _FreeBlocks(transaction, indirect, start, end, freeAll, 0);
  3652. +}
  3653. +
  3654. +
  3655. +status_t
  3656. +DataStream::_RemoveFromDoubleIndirectBlock(Transaction& transaction,
  3657. +   uint32 numBlocks)
  3658. +{
  3659. +   TRACE("DataStream::_RemoveFromDoubleIndirectBlock(): current size: %lu, "
  3660. +       "target size: %lu\n", fNumBlocks, numBlocks);
  3661. +   uint32* doubleIndirect = &fStream->double_indirect;
  3662. +   uint32 start = numBlocks <= kMaxIndirect ? 0 : numBlocks - kMaxIndirect;
  3663. +   uint32 end = fNumBlocks - kMaxIndirect;
  3664. +
  3665. +   if (end > kIndirectsPerBlock2)
  3666. +       end = kIndirectsPerBlock2;
  3667. +
  3668. +   bool freeAll = start == 0;
  3669. +
  3670. +   return _FreeBlocks(transaction, doubleIndirect, start, end, freeAll, 1);
  3671. +}
  3672. +
  3673. +
  3674. +status_t
  3675. +DataStream::_RemoveFromTripleIndirectBlock(Transaction& transaction,
  3676. +   uint32 numBlocks)
  3677. +{
  3678. +   TRACE("DataStream::_RemoveFromTripleIndirectBlock(): current size: %lu, "
  3679. +       "target size: %lu\n", fNumBlocks, numBlocks);
  3680. +   uint32* tripleIndirect = &fStream->triple_indirect;
  3681. +   uint32 start = numBlocks <= kMaxDoubleIndirect ? 0
  3682. +       : numBlocks - kMaxDoubleIndirect;
  3683. +   uint32 end = fNumBlocks - kMaxDoubleIndirect;
  3684. +
  3685. +   bool freeAll = start == 0;
  3686. +
  3687. +   return _FreeBlocks(transaction, tripleIndirect, start, end, freeAll, 2);
  3688. +}
  3689. Index: src/add-ons/kernel/file_systems/ext2/Jamfile
  3690. ===================================================================
  3691. --- src/add-ons/kernel/file_systems/ext2/Jamfile    (revision 38119)
  3692. +++ src/add-ons/kernel/file_systems/ext2/Jamfile    (working copy)
  3693. @@ -7,17 +7,27 @@
  3694.  }
  3695.  
  3696.  #UsePrivateHeaders [ FDirName kernel disk_device_manager ] ;
  3697. +UsePrivateHeaders [ FDirName kernel util ] ;
  3698.  UsePrivateHeaders shared storage ;
  3699.  UsePrivateKernelHeaders ;
  3700.  
  3701.  KernelAddon ext2 :
  3702.     Volume.cpp
  3703. +   DataStream.cpp
  3704.     Inode.cpp
  3705.     AttributeIterator.cpp
  3706.     DirectoryIterator.cpp
  3707. -   IndexedDirectoryIterator.cpp
  3708.     HTree.cpp
  3709.     HTreeEntryIterator.cpp
  3710. +   RevokeManager.cpp
  3711. +   HashRevokeManager.cpp
  3712. +   Journal.cpp
  3713. +   NoJournal.cpp
  3714. +   InodeJournal.cpp
  3715. +   Transaction.cpp
  3716. +   BitmapBlock.cpp
  3717. +   BlockAllocator.cpp
  3718. +   InodeAllocator.cpp
  3719.  
  3720.     kernel_interface.cpp
  3721.  ;
  3722. Index: src/add-ons/kernel/file_systems/ext2/RevokeManager.cpp
  3723. ===================================================================
  3724. --- src/add-ons/kernel/file_systems/ext2/RevokeManager.cpp  (revision 0)
  3725. +++ src/add-ons/kernel/file_systems/ext2/RevokeManager.cpp  (revision 0)
  3726. @@ -0,0 +1,52 @@
  3727. +/*
  3728. + * Copyright 2001-2010, Haiku Inc. All rights reserved.
  3729. + * This file may be used under the terms of the MIT License.
  3730. + *
  3731. + * Authors:
  3732. + *     Janito V. Ferreira Filho
  3733. + */
  3734. +
  3735. +
  3736. +#include "RevokeManager.h"
  3737. +
  3738. +
  3739. +//#define TRACE_EXT2
  3740. +#ifdef TRACE_EXT2
  3741. +#  define TRACE(x...) dprintf("\33[34mext2:\33[0m " x)
  3742. +#else
  3743. +#  define TRACE(x...) ;
  3744. +#endif
  3745. +
  3746. +
  3747. +RevokeManager::RevokeManager()
  3748. +   :
  3749. +   fRevokeCount(0)
  3750. +{
  3751. +}
  3752. +
  3753. +
  3754. +RevokeManager::~RevokeManager()
  3755. +{
  3756. +}
  3757. +
  3758. +
  3759. +status_t
  3760. +RevokeManager::ScanRevokeBlock(JournalRevokeHeader* revokeBlock, uint32 commitID)
  3761. +{
  3762. +   TRACE("RevokeManager::ScanRevokeBlock(): Commit ID: %lu\n", commitID);
  3763. +   int count = revokeBlock->NumBytes() / 4;
  3764. +  
  3765. +   for (int i = 0; i < count; ++i) {
  3766. +       TRACE("RevokeManager::ScanRevokeBlock(): Found a revoked block: %lu\n",
  3767. +           revokeBlock->RevokeBlock(i));
  3768. +       status_t status = Insert(revokeBlock->RevokeBlock(i), commitID);
  3769. +      
  3770. +       if (status != B_OK) {
  3771. +           TRACE("RevokeManager::ScanRevokeBlock(): Error inserting\n");
  3772. +           return status;
  3773. +       }
  3774. +   }
  3775. +
  3776. +   return B_OK;
  3777. +}
  3778. +
  3779.  
  3780. Property changes on: src/add-ons/kernel/file_systems/ext2/RevokeManager.cpp
  3781. ___________________________________________________________________
  3782. Added: svn:executable
  3783.    + *
  3784.  
  3785. Index: src/add-ons/kernel/file_systems/ext2/BitmapBlock.cpp
  3786. ===================================================================
  3787. --- src/add-ons/kernel/file_systems/ext2/BitmapBlock.cpp    (revision 0)
  3788. +++ src/add-ons/kernel/file_systems/ext2/BitmapBlock.cpp    (revision 0)
  3789. @@ -0,0 +1,664 @@
  3790. +/*
  3791. + * Copyright 2001-2010, Haiku Inc. All rights reserved.
  3792. + * This file may be used under the terms of the MIT License.
  3793. + *
  3794. + * Authors:
  3795. + *     Janito V. Ferreira Filho
  3796. + */
  3797. +
  3798. +
  3799. +#include "BitmapBlock.h"
  3800. +
  3801. +
  3802. +//#define TRACE_EXT2
  3803. +#ifdef TRACE_EXT2
  3804. +#  define TRACE(x...) dprintf("\33[34mext2:\33[0m " x)
  3805. +#else
  3806. +#  define TRACE(x...) ;
  3807. +#endif
  3808. +
  3809. +
  3810. +BitmapBlock::BitmapBlock(Volume* volume, uint32 numBits)
  3811. +   :
  3812. +   CachedBlock(volume),
  3813. +   fData(NULL),
  3814. +   fReadOnlyData(NULL),
  3815. +   fNumBits(numBits)
  3816. +{
  3817. +   TRACE("BitmapBlock::BitmapBlock(): num bits: %lu\n", fNumBits);
  3818. +}
  3819. +
  3820. +
  3821. +BitmapBlock::~BitmapBlock()
  3822. +{
  3823. +}
  3824. +
  3825. +
  3826. +/*virtual*/ bool
  3827. +BitmapBlock::SetTo(uint32 block)
  3828. +{
  3829. +   fData = NULL;
  3830. +   fReadOnlyData = (uint32*)CachedBlock::SetTo(block);
  3831. +
  3832. +   return fReadOnlyData != NULL;
  3833. +}
  3834. +
  3835. +
  3836. +/*virtual*/ bool
  3837. +BitmapBlock::SetToWritable(Transaction& transaction, uint32 block, bool empty)
  3838. +{
  3839. +   fReadOnlyData = NULL;
  3840. +   fData = (uint32*)CachedBlock::SetToWritable(transaction, block, empty);
  3841. +
  3842. +   return fData != NULL;
  3843. +}
  3844. +
  3845. +
  3846. +/*virtual*/ bool
  3847. +BitmapBlock::CheckUnmarked(uint32 start, uint32 length)
  3848. +{
  3849. +   const uint32* data = fData == NULL ? fReadOnlyData : fData;
  3850. +   if (data == NULL)
  3851. +       return false;
  3852. +
  3853. +   if (start + length > fNumBits)
  3854. +       return false;
  3855. +
  3856. +   uint32 startIndex = start >> 5;
  3857. +   uint32 startBit = start & 0x1F;
  3858. +   uint32 remainingBits = (length - startBit) & 0x1F;
  3859. +
  3860. +   uint32 iterations;
  3861. +  
  3862. +   if (length < 32) {
  3863. +       if (startBit + length < 32) {
  3864. +           uint32 bits = B_LENDIAN_TO_HOST_INT32(fData[startIndex]);
  3865. +
  3866. +           uint32 mask = (1 << startBit + length) - 1;
  3867. +           mask &= ~((1 << startBit) - 1);
  3868. +          
  3869. +           return (bits & mask) == 0;
  3870. +       } else
  3871. +           iterations = 0;
  3872. +   } else
  3873. +       iterations = (length - 32 + startBit) >> 5;
  3874. +
  3875. +   uint32 index = startIndex;
  3876. +   uint32 mask = 0;
  3877. +
  3878. +   if (startBit != 0) {
  3879. +       mask = ~((1 << startBit) - 1);
  3880. +       uint32 bits = B_LENDIAN_TO_HOST_INT32(data[index]);
  3881. +
  3882. +       if ((bits & mask) != 0)
  3883. +           return false;
  3884. +
  3885. +       index += 1;
  3886. +   }
  3887. +
  3888. +   for (; iterations > 0; --iterations) {
  3889. +       if (data[index++] != 0)
  3890. +           return false;
  3891. +   }
  3892. +
  3893. +   if (remainingBits != 0) {
  3894. +       mask = (1 << remainingBits + 1) - 1;
  3895. +
  3896. +       uint32 bits = B_LENDIAN_TO_HOST_INT32(data[index]);
  3897. +       if ((bits & mask) != 0)
  3898. +           return false;
  3899. +   }
  3900. +
  3901. +   return true;
  3902. +}
  3903. +
  3904. +
  3905. +/*virtual*/ bool
  3906. +BitmapBlock::CheckMarked(uint32 start, uint32 length)
  3907. +{
  3908. +   const uint32* data = fData == NULL ? fReadOnlyData : fData;
  3909. +   if (data == NULL)
  3910. +       return false;
  3911. +
  3912. +   if (start + length > fNumBits)
  3913. +       return false;
  3914. +
  3915. +   uint32 startIndex = start >> 5;
  3916. +   uint32 startBit = start & 0x1F;
  3917. +   uint32 remainingBits = (length - startBit) & 0x1F;
  3918. +
  3919. +   uint32 iterations;
  3920. +  
  3921. +   if (length < 32) {
  3922. +       if (startBit + length < 32) {
  3923. +           uint32 bits = B_LENDIAN_TO_HOST_INT32(fData[startIndex]);
  3924. +
  3925. +           uint32 mask = (1 << startBit + length) - 1;
  3926. +           mask &= ~((1 << startBit) - 1);
  3927. +          
  3928. +           return (bits & mask) != 0;
  3929. +       } else
  3930. +           iterations = 0;
  3931. +   } else
  3932. +       iterations = (length - 32 + startBit) >> 5;
  3933. +
  3934. +   uint32 index = startIndex;
  3935. +   uint32 mask = 0;
  3936. +
  3937. +   if (startBit != 0) {
  3938. +       mask = ~((1 << startBit) - 1);
  3939. +       uint32 bits = B_LENDIAN_TO_HOST_INT32(data[index]);
  3940. +
  3941. +       if ((bits & mask) != mask)
  3942. +           return false;
  3943. +
  3944. +       index += 1;
  3945. +   }
  3946. +
  3947. +   mask = 0xFFFFFFFF;
  3948. +   for (; iterations > 0; --iterations) {
  3949. +       if (data[index++] != mask)
  3950. +           return false;
  3951. +   }
  3952. +
  3953. +   if (remainingBits != 0) {
  3954. +       mask = (1 << remainingBits + 1) - 1;
  3955. +       uint32 bits = B_HOST_TO_LENDIAN_INT32(data[index]);
  3956. +
  3957. +       if ((bits & mask) != mask)
  3958. +           return false;
  3959. +   }
  3960. +
  3961. +   return true;
  3962. +}
  3963. +
  3964. +
  3965. +/*virtual*/ bool
  3966. +BitmapBlock::Mark(uint32 start, uint32 length, bool force)
  3967. +{
  3968. +   if (fData == NULL || start + length > fNumBits)
  3969. +       return false;
  3970. +
  3971. +   uint32 startIndex = start >> 5;
  3972. +   uint32 startBit = start & 0x1F;
  3973. +   uint32 remainingBits = (length - 32 + startBit) & 0x1F;
  3974. +
  3975. +   uint32 iterations;
  3976. +  
  3977. +   if (length < 32) {
  3978. +       if (startBit + length < 32) {
  3979. +           uint32 bits = B_LENDIAN_TO_HOST_INT32(fData[startIndex]);
  3980. +
  3981. +           uint32 mask = (1 << startBit + length) - 1;
  3982. +           mask &= ~((1 << startBit) - 1);
  3983. +          
  3984. +           if ((bits & mask) != 0)
  3985. +               return false;
  3986. +          
  3987. +           bits |= mask;
  3988. +          
  3989. +           fData[startIndex] = B_HOST_TO_LENDIAN_INT32(bits);
  3990. +          
  3991. +           return true;
  3992. +       } else
  3993. +           iterations = 0;
  3994. +   } else
  3995. +       iterations = (length - 32 + startBit) >> 5;
  3996. +
  3997. +   uint32 index = startIndex;
  3998. +   uint32 mask = 0;
  3999. +  
  4000. +   TRACE("BitmapBlock::Mark(): start: %lu, length: %lu, startIndex: %lu, "
  4001. +       "startBit: %lu, iterations: %lu, remainingBits: %lu\n", start, length,
  4002. +       startIndex, startBit, iterations, remainingBits);
  4003. +
  4004. +   if (startBit != 0) {
  4005. +       mask = ~((1 << startBit) - 1);
  4006. +       uint32 bits = B_LENDIAN_TO_HOST_INT32(fData[index]);
  4007. +      
  4008. +       TRACE("BitmapBlock::Mark(): mask: %lX, bits: %lX\n", mask, bits);
  4009. +
  4010. +       if (!force && (bits & mask) != 0)
  4011. +           return false;
  4012. +
  4013. +       bits |= mask;
  4014. +       fData[index] = B_HOST_TO_LENDIAN_INT32(bits);
  4015. +
  4016. +       index += 1;
  4017. +   }
  4018. +
  4019. +   mask = 0xFFFFFFFF;
  4020. +   for (; iterations > 0; --iterations) {
  4021. +       if (!force && fData[index] != 0)
  4022. +           return false;
  4023. +       fData[index++] |= mask;
  4024. +   }
  4025. +
  4026. +   if (remainingBits != 0) {
  4027. +       mask = (1 << remainingBits) - 1;
  4028. +       uint32 bits = B_LENDIAN_TO_HOST_INT32(fData[index]);
  4029. +       TRACE("BitmapBlock::(): marking remaining %lu bits: %lX, mask: %lX\n",
  4030. +           remainingBits, bits, mask);
  4031. +
  4032. +       if (!force && (bits & mask) != 0)
  4033. +           return false;
  4034. +
  4035. +       bits |= mask;
  4036. +       fData[index] = B_HOST_TO_LENDIAN_INT32(bits);
  4037. +   }
  4038. +
  4039. +   return true;
  4040. +}
  4041. +
  4042. +
  4043. +/*virtual*/ bool
  4044. +BitmapBlock::Unmark(uint32 start, uint32 length, bool force)
  4045. +{
  4046. +   TRACE("BitmapBlock::Unmark(%lu, %lu, %c)\n", start, length,
  4047. +       force ? 't' : 'f');
  4048. +
  4049. +   if (fData == NULL || start + length > fNumBits)
  4050. +       return false;
  4051. +
  4052. +   uint32 startIndex = start >> 5;
  4053. +   uint32 startBit = start & 0x1F;
  4054. +   uint32 remainingBits = (length - 32 + startBit) & 0x1F;
  4055. +
  4056. +   TRACE("BitmapBlock::Unmark(): start index: %lu, start bit: %lu, remaining "
  4057. +       "bits: %lu)\n", startIndex, startBit, remainingBits);
  4058. +   uint32 iterations;
  4059. +  
  4060. +   if (length < 32) {
  4061. +       if (startBit + length < 32) {
  4062. +           uint32 bits = B_LENDIAN_TO_HOST_INT32(fData[startIndex]);
  4063. +           TRACE("BitmapBlock::Unmark(): bits: %lx\n", bits);
  4064. +
  4065. +           uint32 mask = (1 << startBit + length) - 1;
  4066. +           mask &= ~((1 << startBit) - 1);
  4067. +          
  4068. +           TRACE("BitmapBlock::Unmark(): mask: %lx\n", mask);
  4069. +
  4070. +           if ((bits & mask) != mask)
  4071. +               return false;
  4072. +          
  4073. +           bits &= ~mask;
  4074. +          
  4075. +           TRACE("BitmapBlock::Unmark(): updated bits: %lx\n", bits);
  4076. +           fData[startIndex] = B_HOST_TO_LENDIAN_INT32(bits);
  4077. +          
  4078. +           return true;
  4079. +       } else
  4080. +           iterations = 0;
  4081. +   } else
  4082. +       iterations = (length - 32 + startBit) >> 5;
  4083. +
  4084. +   TRACE("BitmapBlock::Unmark(): iterations: %lu\n", iterations);
  4085. +   uint32 index = startIndex;
  4086. +   uint32 mask = 0;
  4087. +
  4088. +   if (startBit != 0) {
  4089. +       mask = ~((1 << startBit) - 1);
  4090. +       uint32 bits = B_LENDIAN_TO_HOST_INT32(fData[index]);
  4091. +
  4092. +       TRACE("BitmapBlock::Unmark(): mask: %lx, bits: %lx\n", mask, bits);
  4093. +
  4094. +       if (!force && (bits & mask) != mask)
  4095. +           return false;
  4096. +
  4097. +       bits &= ~mask;
  4098. +       fData[index] = B_HOST_TO_LENDIAN_INT32(bits);
  4099. +
  4100. +       TRACE("BitmapBlock::Unmark(): updated bits: %lx\n", bits);
  4101. +       index += 1;
  4102. +   }
  4103. +
  4104. +   mask = 0xFFFFFFFF;
  4105. +   for (; iterations > 0; --iterations) {
  4106. +       if (!force && fData[index] != mask)
  4107. +           return false;
  4108. +       fData[index++] = 0;
  4109. +   }
  4110. +
  4111. +   TRACE("BitmapBlock::Unmark(): Finished iterations\n");
  4112. +
  4113. +   if (remainingBits != 0) {
  4114. +       mask = (1 << remainingBits) - 1;
  4115. +       uint32 bits = B_LENDIAN_TO_HOST_INT32(fData[index]);
  4116. +
  4117. +       TRACE("BitmapBlock::Unmark(): mask: %lx, bits: %lx\n", mask, bits);
  4118. +
  4119. +       if (!force && (bits & mask) != mask)
  4120. +           return false;
  4121. +
  4122. +       bits &= ~mask;
  4123. +       fData[index] = B_HOST_TO_LENDIAN_INT32(bits);
  4124. +
  4125. +       TRACE("BitmapBlock::Unmark(): updated bits: %lx\n", bits);
  4126. +   }
  4127. +
  4128. +   return true;
  4129. +}
  4130. +
  4131. +
  4132. +void
  4133. +BitmapBlock::FindNextMarked(uint32& pos)
  4134. +{
  4135. +   TRACE("BitmapBlock::FindNextMarked(): pos: %lu\n", pos);
  4136. +
  4137. +   const uint32* data = fData == NULL ? fReadOnlyData : fData;
  4138. +   if (data == NULL)
  4139. +       return;
  4140. +
  4141. +   if (pos >= fNumBits) {
  4142. +       pos = fNumBits;
  4143. +       return;
  4144. +   }
  4145. +
  4146. +   uint32 index = pos >> 5;
  4147. +   uint32 bit = pos & 0x1F;
  4148. +
  4149. +   uint32 mask = (1 << bit) - 1;
  4150. +   uint32 bits = B_LENDIAN_TO_HOST_INT32(data[index]);
  4151. +
  4152. +   TRACE("BitmapBlock::FindNextMarked(): index: %lu, bit: %lu, mask: %lX, "
  4153. +       "bits: %lX\n", index, bit, mask, bits);
  4154. +
  4155. +   bits = bits & ~mask;
  4156. +
  4157. +   if (bits == 0) {
  4158. +       // Find a block of 32 bits that has a marked bit
  4159. +       uint32 maxIndex = fNumBits >> 5;
  4160. +       TRACE("BitmapBlock::FindNextMarked(): max index: %lu\n", maxIndex);
  4161. +
  4162. +       do {
  4163. +           index++;
  4164. +       } while (index < maxIndex && data[index] == 0);
  4165. +
  4166. +       if (index >= maxIndex) {
  4167. +           // Not found
  4168. +           TRACE("BitmapBlock::FindNextMarked(): reached end of block, num "
  4169. +               "bits: %lu\n", fNumBits);
  4170. +           pos = fNumBits;
  4171. +           return;
  4172. +       }
  4173. +
  4174. +       bits = B_LENDIAN_TO_HOST_INT32(data[index]);
  4175. +       bit = 0;
  4176. +   }
  4177. +
  4178. +   for (; bit < 32; ++bit) {
  4179. +       // Find the marked bit
  4180. +       if ((bits >> bit & 1) != 0) {
  4181. +           pos = index << 5 | bit;
  4182. +           TRACE("BitmapBlock::FindNextMarked(): found bit: %lu\n", pos);
  4183. +           return;
  4184. +       }
  4185. +   }
  4186. +
  4187. +   panic("Couldn't find marked bit inside an int32 which is different than "
  4188. +       "zero!?\n");
  4189. +}
  4190. +
  4191. +
  4192. +void
  4193. +BitmapBlock::FindNextUnmarked(uint32& pos)
  4194. +{
  4195. +   TRACE("BitmapBlock::FindNextUnmarked(): pos: %lu\n", pos);
  4196. +
  4197. +   const uint32* data = fData == NULL ? fReadOnlyData : fData;
  4198. +   if (data == NULL)
  4199. +       return;
  4200. +
  4201. +   if (pos >= fNumBits) {
  4202. +       pos = fNumBits;
  4203. +       return;
  4204. +   }
  4205. +
  4206. +   uint32 index = pos >> 5;
  4207. +   uint32 bit = pos & 0x1F;
  4208. +
  4209. +   uint32 mask = (1 << bit) - 1;
  4210. +   uint32 bits = B_LENDIAN_TO_HOST_INT32(data[index]);
  4211. +
  4212. +   TRACE("BitmapBlock::FindNextUnmarked(): index: %lu, bit: %lu, mask: %lX, "
  4213. +       "bits: %lX\n", index, bit, mask, bits);
  4214. +
  4215. +   bits &= ~mask;
  4216. +
  4217. +   if (bits == ~mask) {
  4218. +       // Find an block of 32 bits that has a unmarked bit
  4219. +       uint32 maxIndex = fNumBits >> 5;
  4220. +       TRACE("BitmapBlock::FindNextUnmarked(): max index: %lu\n", maxIndex);
  4221. +
  4222. +       do {
  4223. +           index++;
  4224. +       } while (index < maxIndex && data[index] == 0xFFFFFFFF);
  4225. +
  4226. +       if (index >= maxIndex) {
  4227. +           // Not found
  4228. +           TRACE("BitmapBlock::FindNextUnmarked(): reached end of block, num "
  4229. +               "bits: %lu\n", fNumBits);
  4230. +           pos = fNumBits;
  4231. +           return;
  4232. +       }
  4233. +
  4234. +       bits = B_LENDIAN_TO_HOST_INT32(data[index]);
  4235. +       bit = 0;
  4236. +   }
  4237. +
  4238. +   for (; bit < 32; ++bit) {
  4239. +       // Find the unmarked bit
  4240. +       if ((bits >> bit & 1) == 0) {
  4241. +           pos = index << 5 | bit;
  4242. +           TRACE("BitmapBlock::FindNextUnmarked(): found bit: %lu\n", pos);
  4243. +           return;
  4244. +       }
  4245. +   }
  4246. +
  4247. +   panic("Couldn't find unmarked bit inside an int32 whith value zero!?\n");
  4248. +}
  4249. +
  4250. +
  4251. +void
  4252. +BitmapBlock::FindPreviousMarked(uint32& pos)
  4253. +{
  4254. +   TRACE("BitmapBlock::FindPreviousMarked(%lu)\n", pos);
  4255. +   const uint32* data = fData == NULL ? fReadOnlyData : fData;
  4256. +   if (data == NULL)
  4257. +       return;
  4258. +
  4259. +   if (pos >= fNumBits)
  4260. +       pos = fNumBits;
  4261. +
  4262. +   if (pos == 0)
  4263. +       return;
  4264. +
  4265. +   uint32 index = pos >> 5;
  4266. +   int32 bit = pos & 0x1F;
  4267. +
  4268. +   uint32 mask = (1 << bit + 1) - 1;
  4269. +   uint32 bits = B_LENDIAN_TO_HOST_INT32(data[index]);
  4270. +   bits = bits & mask;
  4271. +
  4272. +   TRACE("BitmapBlock::FindPreviousMarked(): index: %lu, bit: %lu\n", index,
  4273. +       bit);
  4274. +
  4275. +   if (bits == 0) {
  4276. +       // Find an block of 32 bits that has a marked bit
  4277. +       do {
  4278. +           index--;
  4279. +       } while (data[index] == 0 && index >= 0);
  4280. +
  4281. +       bits = B_LENDIAN_TO_HOST_INT32(data[index]);
  4282. +       if (bits == 0) {
  4283. +           // Not found
  4284. +           pos = 0;
  4285. +           return;
  4286. +       }
  4287. +
  4288. +       bit = 31;
  4289. +   }
  4290. +
  4291. +   for (; bit >= 0; --bit) {
  4292. +       // Find the unmarked bit
  4293. +       if ((bits >> bit & 1) != 0) {
  4294. +           pos = index << 5 | bit;
  4295. +           return;
  4296. +       }
  4297. +   }
  4298. +
  4299. +   panic("Couldn't find marked bit inside an int32 whith value different than "
  4300. +       "zero!?\n");
  4301. +}
  4302. +
  4303. +
  4304. +void
  4305. +BitmapBlock::FindLargestUnmarkedRange(uint32& start, uint32& length)
  4306. +{
  4307. +   const uint32* data = fData == NULL ? fReadOnlyData : fData;
  4308. +   if (data == NULL)
  4309. +       return;
  4310. +
  4311. +   uint32 wordSpan = length >> 5;
  4312. +   uint32 lastIndex = fNumBits >> 5;
  4313. +   uint32 startIndex = 0;
  4314. +   uint32 index = 0;
  4315. +   uint32 bits = B_LENDIAN_TO_HOST_INT32(data[0]);
  4316. +
  4317. +   TRACE("BitmapBlock::FindLargestUnmarkedRange(): word span: %lu, last "
  4318. +       "index: %lu, start index: %lu, index: %lu, bits: %lX, start: %lu, "
  4319. +       "length: %lu\n", wordSpan, lastIndex, startIndex, index, bits, start,
  4320. +       length);
  4321. +
  4322. +   if (wordSpan == 0) {
  4323. +       uint32 startPos = 0;
  4324. +       uint32 endPos = 0;
  4325. +
  4326. +       while (endPos < fNumBits) {
  4327. +           FindNextUnmarked(startPos);
  4328. +           endPos = startPos;
  4329. +
  4330. +           if (startPos != fNumBits) {
  4331. +               FindNextMarked(endPos);
  4332. +
  4333. +               uint32 newLength = endPos - startPos;
  4334. +
  4335. +               if (newLength > length) {
  4336. +                   start = startPos;
  4337. +                   length = newLength;
  4338. +                   TRACE("BitmapBlock::FindLargestUnmarkedRange(): Found "
  4339. +                       "larger length %lu starting at %lu\n", length, start);
  4340. +               }
  4341. +
  4342. +               startPos = endPos;
  4343. +
  4344. +               if (newLength >= 32)
  4345. +                   break;
  4346. +           }
  4347. +       }
  4348. +      
  4349. +       if (endPos >= fNumBits)
  4350. +           return;
  4351. +
  4352. +       wordSpan = length >> 5;
  4353. +       startIndex = startPos >> 5;
  4354. +       index = (endPos >> 5) + 1;
  4355. +       bits = B_LENDIAN_TO_HOST_INT32(data[index]);
  4356. +   }
  4357. +
  4358. +   for (; index < lastIndex; ++index) {
  4359. +       bits = B_LENDIAN_TO_HOST_INT32(data[index]);
  4360. +
  4361. +       if (bits != 0) {
  4362. +           // Contains marked bits
  4363. +           if (index - startIndex >= wordSpan) {
  4364. +               uint32 newLength = index - startIndex - 1 << 5;
  4365. +               uint32 newStart = startIndex + 1 << 5;
  4366. +
  4367. +               uint32 startBits =
  4368. +                   B_LENDIAN_TO_HOST_INT32(data[startIndex]);
  4369. +
  4370. +               for (int32 bit = 31; bit >= 0; --bit) {
  4371. +                   if ((startBits >> bit & 1) != 0)
  4372. +                       break;
  4373. +
  4374. +                   ++newLength;
  4375. +                   --newStart;
  4376. +               }
  4377. +
  4378. +               for (int32 bit = 0; bit < 32; ++bit) {
  4379. +                   if ((bits >> bit & 1) != 0)
  4380. +                       break;
  4381. +
  4382. +                   ++newLength;
  4383. +               }
  4384. +
  4385. +               if (newLength > length) {
  4386. +                   start = newStart;
  4387. +                   length = newLength;
  4388. +                   wordSpan = length >> 5;
  4389. +                  
  4390. +                   TRACE("BitmapBlock::FindLargestUnmarkedRange(): Found "
  4391. +                       "larger length %lu starting at %lu; word span: "
  4392. +                       "%lu\n", length, start, wordSpan);
  4393. +               }
  4394. +           }
  4395. +
  4396. +           startIndex = index;
  4397. +       }
  4398. +   }
  4399. +  
  4400. +   --index;
  4401. +
  4402. +   if (index - startIndex >= wordSpan) {
  4403. +       uint32 newLength = index - startIndex << 5;
  4404. +       uint32 newStart = startIndex + 1 << 5;
  4405. +      
  4406. +       TRACE("BitmapBlock::FindLargestUnmarkedRange(): Possibly found a "
  4407. +           "larger range. index: %lu, start index: %lu, word span: %lu, "
  4408. +           "new length: %lu, new start: %lu\n", index, startIndex, wordSpan,
  4409. +           newLength, newStart);
  4410. +
  4411. +       if (newStart != 0) {
  4412. +           uint32 startBits = B_LENDIAN_TO_HOST_INT32(data[startIndex]);
  4413. +          
  4414. +           TRACE("BitmapBlock::FindLargestUnmarkedRange(): start bits: %lu\n",
  4415. +               startBits);
  4416. +
  4417. +           for (int32 bit = 31; bit >= 0; --bit) {
  4418. +               if ((startBits >> bit & 1) != 0)
  4419. +                   break;
  4420. +
  4421. +               ++newLength;
  4422. +               --newStart;
  4423. +           }
  4424. +          
  4425. +           TRACE("BitmapBlock::FindLargestUnmarkedRange(): updated new start "
  4426. +               "to %lu and new length to %lu\n", newStart, newLength);
  4427. +       }
  4428. +
  4429. +       for (int32 bit = 0; bit < 32; ++bit) {
  4430. +           if ((bits >> bit & 1) == 0)
  4431. +               break;
  4432. +
  4433. +           ++newLength;
  4434. +       }
  4435. +      
  4436. +       TRACE("BitmapBlock::FindLargestUnmarkedRange(): updated new length to "
  4437. +           "%lu\n", newLength);
  4438. +
  4439. +       if (newLength > length) {
  4440. +           start = newStart;
  4441. +           length = newLength;
  4442. +           TRACE("BitmapBlock::FindLargestUnmarkedRange(): Found "
  4443. +               "largest length %lu starting at %lu\n", length, start);
  4444. +       }
  4445. +   }
  4446. +}
  4447. +
  4448. +
  4449. +uint32
  4450. +BitmapBlock::NumBits() const
  4451. +{
  4452. +   return fNumBits;
  4453. +}
  4454.  
  4455. Property changes on: src/add-ons/kernel/file_systems/ext2/BitmapBlock.cpp
  4456. ___________________________________________________________________
  4457. Added: svn:executable
  4458.    + *
  4459.  
  4460. Index: src/add-ons/kernel/file_systems/ext2/InodeJournal.cpp
  4461. ===================================================================
  4462. --- src/add-ons/kernel/file_systems/ext2/InodeJournal.cpp   (revision 0)
  4463. +++ src/add-ons/kernel/file_systems/ext2/InodeJournal.cpp   (revision 0)
  4464. @@ -0,0 +1,91 @@
  4465. +/*
  4466. + * Copyright 2001-2010, Haiku Inc. All rights reserved.
  4467. + * This file may be used under the terms of the MIT License.
  4468. + *
  4469. + * Authors:
  4470. + *     Janito V. Ferreira Filho
  4471. + */
  4472. +
  4473. +
  4474. +#include "InodeJournal.h"
  4475. +
  4476. +#include <new>
  4477. +
  4478. +#include <fs_cache.h>
  4479. +
  4480. +#include "HashRevokeManager.h"
  4481. +
  4482. +
  4483. +//#define TRACE_EXT2
  4484. +#ifdef TRACE_EXT2
  4485. +#  define TRACE(x...) dprintf("\33[34mext2:\33[0m " x)
  4486. +#else
  4487. +#  define TRACE(x...) ;
  4488. +#endif
  4489. +
  4490. +
  4491. +InodeJournal::InodeJournal(Inode* inode)
  4492. +   :
  4493. +   Journal(),
  4494. +   fInode(inode)
  4495. +{
  4496. +   if (inode == NULL)
  4497. +       fInitStatus = B_BAD_DATA;
  4498. +   else {
  4499. +       Volume* volume = inode->GetVolume();
  4500. +
  4501. +       fFilesystemVolume = volume;
  4502. +       fFilesystemBlockCache = volume->BlockCache();
  4503. +       fJournalVolume = volume;
  4504. +       fJournalBlockCache = volume->BlockCache();
  4505. +
  4506. +       if (!inode->IsFileCacheDisabled())
  4507. +           fInitStatus = inode->DisableFileCache();
  4508. +       else
  4509. +           fInitStatus = B_OK;
  4510. +      
  4511. +       if (fInitStatus == B_OK) {
  4512. +           TRACE("InodeJournal::InodeJournal(): Inode's file cache disabled "
  4513. +               "successfully\n");
  4514. +           HashRevokeManager* revokeManager = new(std::nothrow)
  4515. +               HashRevokeManager;
  4516. +           TRACE("InodeJournal::InodeJournal(): Allocated a hash revoke "
  4517. +               "manager at %p\n", revokeManager);
  4518. +
  4519. +           if (revokeManager == NULL) {
  4520. +               TRACE("InodeJournal::InodeJournal(): Insufficient memory to "
  4521. +                   "create the hash revoke manager\n");
  4522. +               fInitStatus = B_NO_MEMORY;
  4523. +           } else {
  4524. +               fInitStatus = revokeManager->Init();
  4525. +              
  4526. +               if (fInitStatus == B_OK) {
  4527. +                   fRevokeManager = revokeManager;
  4528. +                   fInitStatus = _LoadSuperBlock();
  4529. +               }
  4530. +           }
  4531. +       }
  4532. +   }
  4533. +}
  4534. +
  4535. +
  4536. +InodeJournal::~InodeJournal()
  4537. +{
  4538. +}
  4539. +
  4540. +
  4541. +status_t
  4542. +InodeJournal::InitCheck()
  4543. +{
  4544. +   if (fInitStatus != B_OK)
  4545. +       TRACE("InodeJournal: Initialization error\n");
  4546. +   return fInitStatus;
  4547. +}
  4548. +
  4549. +
  4550. +status_t
  4551. +InodeJournal::MapBlock(uint32 logical, uint32& physical)
  4552. +{
  4553. +   TRACE("InodeJournal::MapBlock()\n");
  4554. +   return fInode->FindBlock(logical * fBlockSize, physical);
  4555. +}
  4556. Index: src/add-ons/kernel/file_systems/ext2/Transaction.h
  4557. ===================================================================
  4558. --- src/add-ons/kernel/file_systems/ext2/Transaction.h  (revision 0)
  4559. +++ src/add-ons/kernel/file_systems/ext2/Transaction.h  (revision 0)
  4560. @@ -0,0 +1,72 @@
  4561. +/*
  4562. + * Copyright 2001-2010, Haiku Inc. All rights reserved.
  4563. + * This file may be used under the terms of the MIT License.
  4564. + *
  4565. + * Authors:
  4566. + *     Janito V. Ferreira Filho
  4567. + */
  4568. +#ifndef TRANSACTION_H
  4569. +#define TRANSACTION_H
  4570. +
  4571. +
  4572. +#include <util/DoublyLinkedList.h>
  4573. +
  4574. +
  4575. +class Journal;
  4576. +class Volume;
  4577. +
  4578. +
  4579. +class TransactionListener
  4580. +   : public DoublyLinkedListLinkImpl<TransactionListener> {
  4581. +public:
  4582. +                               TransactionListener();
  4583. +   virtual                     ~TransactionListener();
  4584. +
  4585. +   virtual void                TransactionDone(bool success) = 0;
  4586. +   virtual void                RemovedFromTransaction() = 0;
  4587. +};
  4588. +
  4589. +typedef DoublyLinkedList<TransactionListener> TransactionListeners;
  4590. +
  4591. +
  4592. +class Transaction {
  4593. +public:
  4594. +                                   Transaction();
  4595. +                                   Transaction(Journal* journal);
  4596. +                                   ~Transaction();
  4597. +
  4598. +           status_t                Start(Journal* journal);
  4599. +           status_t                Done(bool success = true);
  4600. +
  4601. +           bool                    IsStarted() const;
  4602. +           bool                    HasParent() const;
  4603. +
  4604. +           status_t                WriteBlocks(off_t blockNumber,
  4605. +                                       const uint8* buffer,
  4606. +                                       size_t numBlocks = 1);
  4607. +
  4608. +           void                    Split();
  4609. +
  4610. +           Volume*                 GetVolume() const;
  4611. +           int32                   ID() const;
  4612. +
  4613. +           void                    AddListener(TransactionListener* listener);
  4614. +           void                    RemoveListener(
  4615. +                                       TransactionListener* listener);
  4616. +
  4617. +           void                    NotifyListeners(bool success);
  4618. +           void                    MoveListenersTo(Transaction* transaction);
  4619. +          
  4620. +           void                    SetParent(Transaction* transaction);
  4621. +           Transaction*            Parent() const;
  4622. +private:
  4623. +                                   Transaction(const Transaction& other);
  4624. +           Transaction&            operator=(const Transaction& other);
  4625. +               // no implementation
  4626. +
  4627. +           Journal*                fJournal;
  4628. +           TransactionListeners    fListeners;
  4629. +           Transaction*            fParent;
  4630. +};
  4631. +
  4632. +#endif // TRANSACTION_H
  4633. Index: src/add-ons/kernel/file_systems/ext2/BlockAllocator.cpp
  4634. ===================================================================
  4635. --- src/add-ons/kernel/file_systems/ext2/BlockAllocator.cpp (revision 0)
  4636. +++ src/add-ons/kernel/file_systems/ext2/BlockAllocator.cpp (revision 0)
  4637. @@ -0,0 +1,714 @@
  4638. +/*
  4639. + * Copyright 2001-2010, Haiku Inc. All rights reserved.
  4640. + * This file may be used under the terms of the MIT License.
  4641. + *
  4642. + * Authors:
  4643. + *     Janito V. Ferreira Filho
  4644. + */
  4645. +
  4646. +
  4647. +#include "BlockAllocator.h"
  4648. +
  4649. +#include <util/AutoLock.h>
  4650. +
  4651. +#include "BitmapBlock.h"
  4652. +#include "Inode.h"
  4653. +
  4654. +
  4655. +//#define TRACE_EXT2
  4656. +#ifdef TRACE_EXT2
  4657. +#  define TRACE(x...) dprintf("\33[34mext2:\33[0m " x)
  4658. +#else
  4659. +#  define TRACE(x...) ;
  4660. +#endif
  4661. +
  4662. +
  4663. +class AllocationBlockGroup : public TransactionListener {
  4664. +public:
  4665. +                       AllocationBlockGroup();
  4666. +                       ~AllocationBlockGroup();
  4667. +
  4668. +           status_t    Initialize(Volume* volume, uint32 blockGroup,
  4669. +                           uint32 numBits);
  4670. +
  4671. +           status_t    ScanFreeRanges();
  4672. +           bool        IsFull() const;
  4673. +
  4674. +           status_t    Allocate(Transaction& transaction, uint32 start,
  4675. +                           uint32 length);
  4676. +           status_t    Free(Transaction& transaction, uint32 start,
  4677. +                           uint32 length);
  4678. +           status_t    FreeAll(Transaction& transaction);
  4679. +           status_t    Check(uint32 start, uint32 length);
  4680. +
  4681. +           uint32      NumBits() const;
  4682. +           uint32      FreeBits() const;
  4683. +           uint32      Start() const;
  4684. +
  4685. +           uint32      LargestStart() const;
  4686. +           uint32      LargestLength() const;
  4687. +
  4688. +           // TransactionListener implementation
  4689. +           void        TransactionDone(bool success);
  4690. +           void        RemovedFromTransaction();
  4691. +
  4692. +private:
  4693. +           void        _AddFreeRange(uint32 start, uint32 length);
  4694. +           void        _LockInTransaction(Transaction& transaction);
  4695. +
  4696. +
  4697. +           Volume*     fVolume;
  4698. +           uint32      fBlockGroup;
  4699. +           ext2_block_group* fGroupDescriptor;
  4700. +
  4701. +           mutex       fLock;
  4702. +           mutex       fTransactionLock;
  4703. +           int32       fCurrentTransaction;
  4704. +
  4705. +           uint32      fStart;
  4706. +           uint32      fNumBits;
  4707. +           uint32      fBitmapBlock;
  4708. +
  4709. +           uint32      fFreeBits;
  4710. +           uint32      fFirstFree;
  4711. +           uint32      fLargestStart;
  4712. +           uint32      fLargestLength;
  4713. +          
  4714. +           uint32      fPreviousFreeBits;
  4715. +           uint32      fPreviousFirstFree;
  4716. +           uint32      fPreviousLargestStart;
  4717. +           uint32      fPreviousLargestLength;
  4718. +};
  4719. +
  4720. +
  4721. +AllocationBlockGroup::AllocationBlockGroup()
  4722. +   :
  4723. +   fVolume(NULL),
  4724. +   fBlockGroup(0),
  4725. +   fGroupDescriptor(NULL),
  4726. +   fStart(0),
  4727. +   fNumBits(0),
  4728. +   fBitmapBlock(0),
  4729. +   fFreeBits(0),
  4730. +   fFirstFree(0),
  4731. +   fLargestStart(0),
  4732. +   fLargestLength(0),
  4733. +   fPreviousFreeBits(0),
  4734. +   fPreviousFirstFree(0),
  4735. +   fPreviousLargestStart(0),
  4736. +   fPreviousLargestLength(0)
  4737. +{
  4738. +   mutex_init(&fLock, "ext2 allocation block group");
  4739. +   mutex_init(&fTransactionLock, "ext2 allocation block group transaction");
  4740. +}
  4741. +
  4742. +
  4743. +AllocationBlockGroup::~AllocationBlockGroup()
  4744. +{
  4745. +   mutex_destroy(&fLock);
  4746. +   mutex_destroy(&fTransactionLock);
  4747. +}
  4748. +
  4749. +
  4750. +status_t
  4751. +AllocationBlockGroup::Initialize(Volume* volume, uint32 blockGroup,
  4752. +   uint32 numBits)
  4753. +{
  4754. +   fVolume = volume;
  4755. +   fBlockGroup = blockGroup;
  4756. +   fNumBits = numBits;
  4757. +
  4758. +   status_t status = fVolume->GetBlockGroup(blockGroup, &fGroupDescriptor);
  4759. +   if (status != B_OK)
  4760. +       return status;
  4761. +
  4762. +   fBitmapBlock = fGroupDescriptor->BlockBitmap();
  4763. +
  4764. +   status = ScanFreeRanges();
  4765. +
  4766. +   if (fGroupDescriptor->FreeBlocks() != fFreeBits) {
  4767. +       TRACE("AllocationBlockGroup::Initialize(): Mismatch between counted "
  4768. +           "free blocks (%lu) and what is set on the group descriptor "
  4769. +           "(%lu)\n", fFreeBits, (uint32)fGroupDescriptor->FreeBlocks());
  4770. +       return B_BAD_DATA;
  4771. +   }
  4772. +
  4773. +   fPreviousFreeBits = fFreeBits;
  4774. +   fPreviousFirstFree = fFirstFree;
  4775. +   fPreviousLargestStart = fLargestStart;
  4776. +   fPreviousLargestLength = fLargestLength;
  4777. +  
  4778. +   return status;
  4779. +}
  4780. +
  4781. +
  4782. +status_t
  4783. +AllocationBlockGroup::ScanFreeRanges()
  4784. +{
  4785. +   TRACE("AllocationBlockGroup::ScanFreeRanges()\n");
  4786. +   BitmapBlock block(fVolume, fNumBits);
  4787. +
  4788. +   if (!block.SetTo(fBitmapBlock))
  4789. +       return B_ERROR;
  4790. +
  4791. +   uint32 start = 0;
  4792. +   uint32 end = 0;
  4793. +
  4794. +   while (end < fNumBits) {
  4795. +       block.FindNextUnmarked(start);
  4796. +       end = start;
  4797. +
  4798. +       if (start != block.NumBits()) {
  4799. +           block.FindNextMarked(end);
  4800. +           _AddFreeRange(start, end - start);
  4801. +           start = end;
  4802. +       }
  4803. +   }
  4804. +
  4805. +   return B_OK;
  4806. +}
  4807. +
  4808. +
  4809. +bool
  4810. +AllocationBlockGroup::IsFull() const
  4811. +{
  4812. +   return fFreeBits == 0;
  4813. +}
  4814. +
  4815. +
  4816. +status_t
  4817. +AllocationBlockGroup::Allocate(Transaction& transaction, uint32 start,
  4818. +   uint32 length)
  4819. +{
  4820. +   TRACE("AllocationBlockGroup::Allocate()\n");
  4821. +   uint32 end = start + length;
  4822. +   if (end > fNumBits)
  4823. +       return B_BAD_DATA;
  4824. +
  4825. +   _LockInTransaction(transaction);
  4826. +
  4827. +   BitmapBlock block(fVolume, fNumBits);
  4828. +
  4829. +   if (!block.SetToWritable(transaction, fBitmapBlock))
  4830. +       return B_ERROR;
  4831. +  
  4832. +   if (!block.Mark(start, length)) {
  4833. +       TRACE("Failed to allocate blocks from %lu to %lu. Some were "
  4834. +           "already allocated.\n", start, start + length);
  4835. +       return B_ERROR;
  4836. +   }
  4837. +
  4838. +   fFreeBits -= length;
  4839. +   fGroupDescriptor->SetFreeBlocks((uint16)fFreeBits);
  4840. +   fVolume->WriteBlockGroup(transaction, fBlockGroup);
  4841. +
  4842. +   if (start == fLargestStart) {
  4843. +       if (fFirstFree == fLargestStart)
  4844. +           fFirstFree += length;
  4845. +
  4846. +       fLargestStart += length;
  4847. +       fLargestLength -= length;
  4848. +   } else if (start + length == fLargestStart + fLargestLength) {
  4849. +       fLargestLength -= length;
  4850. +   } else if (start < fLargestStart + fLargestLength
  4851. +           && start > fLargestStart) {
  4852. +       uint32 firstLength = start - fLargestStart;
  4853. +       uint32 secondLength = fLargestStart + fLargestLength
  4854. +           - (start + length);
  4855. +
  4856. +       if (firstLength >= secondLength) {
  4857. +           fLargestLength = firstLength;
  4858. +       } else {
  4859. +           fLargestLength = secondLength;
  4860. +           fLargestStart = start + length;
  4861. +       }
  4862. +   } else {
  4863. +       // No need to revalidate the largest free range
  4864. +       return B_OK;
  4865. +   }
  4866. +
  4867. +   if (fLargestLength < fNumBits / 2)
  4868. +       block.FindLargestUnmarkedRange(fLargestStart, fLargestLength);
  4869. +
  4870. +   return B_OK;
  4871. +}
  4872. +
  4873. +
  4874. +status_t
  4875. +AllocationBlockGroup::Free(Transaction& transaction, uint32 start,
  4876. +   uint32 length)
  4877. +{
  4878. +   TRACE("AllocationBlockGroup::Free(): start: %lu, length %lu\n", start,
  4879. +       length);
  4880. +
  4881. +   if (length == 0)
  4882. +       return B_OK;
  4883. +
  4884. +   uint32 end = start + length;
  4885. +
  4886. +   if (end > fNumBits)
  4887. +       return B_BAD_DATA;
  4888. +
  4889. +   _LockInTransaction(transaction);
  4890. +
  4891. +   BitmapBlock block(fVolume, fNumBits);
  4892. +
  4893. +   if (!block.SetToWritable(transaction, fBitmapBlock))
  4894. +       return B_ERROR;
  4895. +
  4896. +   if (!block.Unmark(start, length)) {
  4897. +       TRACE("Failed to free blocks from %lu to %lu. Some were "
  4898. +           "already freed.\n", start, start + length);
  4899. +       return B_ERROR;
  4900. +   }
  4901. +
  4902. +   TRACE("AllocationGroup::Free(): Unmarked bits in bitmap\n");
  4903. +
  4904. +   if (fFirstFree > start)
  4905. +       fFirstFree = start;
  4906. +
  4907. +   if (start + length == fLargestStart) {
  4908. +       fLargestStart = start;
  4909. +       fLargestLength += length;
  4910. +   } else if (start == fLargestStart + fLargestLength) {
  4911. +       fLargestLength += length;
  4912. +   } else if (fLargestLength <= fNumBits / 2) {
  4913. +       // May have merged with some free blocks, becoming the largest
  4914. +       uint32 newEnd = start + length;
  4915. +       block.FindNextMarked(newEnd);
  4916. +
  4917. +       uint32 newStart = start;
  4918. +       block.FindPreviousMarked(newStart);
  4919. +
  4920. +       if (newEnd - newStart > fLargestLength) {
  4921. +           fLargestLength = newEnd - newStart;
  4922. +           fLargestStart = newStart;
  4923. +       }
  4924. +   }
  4925. +
  4926. +   fFreeBits += length;
  4927. +   fGroupDescriptor->SetFreeBlocks((uint16)fFreeBits);
  4928. +   fVolume->WriteBlockGroup(transaction, fBlockGroup);
  4929. +
  4930. +   return B_OK;
  4931. +}
  4932. +
  4933. +
  4934. +status_t
  4935. +AllocationBlockGroup::FreeAll(Transaction& transaction)
  4936. +{
  4937. +   return Free(transaction, 0, fNumBits);
  4938. +}
  4939. +
  4940. +
  4941. +uint32
  4942. +AllocationBlockGroup::NumBits() const
  4943. +{
  4944. +   return fNumBits;
  4945. +}
  4946. +
  4947. +
  4948. +uint32
  4949. +AllocationBlockGroup::FreeBits() const
  4950. +{
  4951. +   return fFreeBits;
  4952. +}
  4953. +
  4954. +
  4955. +uint32
  4956. +AllocationBlockGroup::Start() const
  4957. +{
  4958. +   return fStart;
  4959. +}
  4960. +
  4961. +
  4962. +uint32
  4963. +AllocationBlockGroup::LargestStart() const
  4964. +{
  4965. +   return fLargestStart;
  4966. +}
  4967. +
  4968. +
  4969. +uint32
  4970. +AllocationBlockGroup::LargestLength() const
  4971. +{
  4972. +   return fLargestLength;
  4973. +}
  4974. +
  4975. +
  4976. +void
  4977. +AllocationBlockGroup::_AddFreeRange(uint32 start, uint32 length)
  4978. +{
  4979. +   if (IsFull()) {
  4980. +       fFirstFree = start;
  4981. +       fLargestStart = start;
  4982. +       fLargestLength = length;
  4983. +   } else if (length > fLargestLength) {
  4984. +       fLargestStart = start;
  4985. +       fLargestLength = length;
  4986. +   }
  4987. +
  4988. +   fFreeBits += length;
  4989. +}
  4990. +
  4991. +
  4992. +void
  4993. +AllocationBlockGroup::_LockInTransaction(Transaction& transaction)
  4994. +{
  4995. +   mutex_lock(&fLock);
  4996. +
  4997. +   if (transaction.ID() != fCurrentTransaction) {
  4998. +       mutex_unlock(&fLock);
  4999. +
  5000. +       mutex_lock(&fTransactionLock);
  5001. +       mutex_lock(&fLock);
  5002. +
  5003. +       fCurrentTransaction = transaction.ID();
  5004. +       transaction.AddListener(this);
  5005. +   }
  5006. +
  5007. +   mutex_unlock(&fLock);
  5008. +}
  5009. +
  5010. +
  5011. +void
  5012. +AllocationBlockGroup::TransactionDone(bool success)
  5013. +{
  5014. +   if (success) {
  5015. +       TRACE("AllocationBlockGroup::TransactionDone(): The transaction "
  5016. +           "succeeded, discarding previous state\n");
  5017. +       fPreviousFreeBits = fFreeBits;
  5018. +       fPreviousFirstFree = fFirstFree;
  5019. +       fPreviousLargestStart = fLargestStart;
  5020. +       fPreviousLargestLength = fLargestLength;
  5021. +   } else {
  5022. +       TRACE("AllocationBlockGroup::TransactionDone(): The transaction "
  5023. +           "failed, restoring to previous state\n");
  5024. +       fFreeBits = fPreviousFreeBits;
  5025. +       fFirstFree = fPreviousFirstFree;
  5026. +       fLargestStart = fPreviousLargestStart;
  5027. +       fLargestLength = fPreviousLargestLength;
  5028. +   }
  5029. +}
  5030. +
  5031. +
  5032. +void
  5033. +AllocationBlockGroup::RemovedFromTransaction()
  5034. +{
  5035. +   mutex_unlock(&fTransactionLock);
  5036. +   fCurrentTransaction = -1;
  5037. +}
  5038. +
  5039. +
  5040. +BlockAllocator::BlockAllocator(Volume* volume)
  5041. +   :
  5042. +   fVolume(volume),
  5043. +   fGroups(NULL),
  5044. +   fBlocksPerGroup(0),
  5045. +   fNumBlocks(0),
  5046. +   fNumGroups(0)
  5047. +{
  5048. +   mutex_init(&fLock, "ext2 block allocator");
  5049. +}
  5050. +
  5051. +
  5052. +BlockAllocator::~BlockAllocator()
  5053. +{
  5054. +   mutex_destroy(&fLock);
  5055. +
  5056. +   if (fGroups != NULL)
  5057. +       delete [] fGroups;
  5058. +}
  5059. +
  5060. +
  5061. +status_t
  5062. +BlockAllocator::Initialize()
  5063. +{
  5064. +   fBlocksPerGroup = fVolume->BlocksPerGroup();
  5065. +   fNumGroups = fVolume->NumGroups();
  5066. +   fFirstBlock = fVolume->FirstDataBlock();
  5067. +   fNumBlocks = fVolume->NumBlocks();
  5068. +  
  5069. +   TRACE("BlockAllocator::Initialize(): blocks per group: %lu, block groups: "
  5070. +       "%lu, first block: %lu, num blocks: %lu\n", fBlocksPerGroup,
  5071. +       fNumGroups, fFirstBlock, fNumBlocks);
  5072. +
  5073. +   fGroups = new(std::nothrow) AllocationBlockGroup[fNumGroups];
  5074. +   if (fGroups == NULL)
  5075. +       return B_NO_MEMORY;
  5076. +
  5077. +   TRACE("BlockAllocator::Initialize(): allocated allocation block groups\n");
  5078. +
  5079. +   mutex_lock(&fLock);
  5080. +       // Released by _Initialize
  5081. +
  5082. +   thread_id id = -1; // spawn_kernel_thread(
  5083. +       // (thread_func)BlockAllocator::_Initialize, "ext2 block allocator",
  5084. +       // B_LOW_PRIORITY, this);
  5085. +   if (id < B_OK)
  5086. +       return _Initialize(this);
  5087. +
  5088. +   // mutex_transfer_lock(&fLock, id);
  5089. +
  5090. +   // return resume_thread(id);
  5091. +   panic("Failed to fall back to synchronous block allocator"
  5092. +       "initialization.\n");
  5093. +   return B_ERROR;
  5094. +}
  5095. +
  5096. +
  5097. +status_t
  5098. +BlockAllocator::AllocateBlocks(Transaction& transaction, uint32 minimum,
  5099. +   uint32 maximum, uint32& blockGroup, uint32& start, uint32& length)
  5100. +{
  5101. +   TRACE("BlockAllocator::AllocateBlocks()\n");
  5102. +   MutexLocker lock(fLock);
  5103. +   TRACE("BlockAllocator::AllocateBlocks(): Aquired lock\n");
  5104. +
  5105. +   TRACE("BlockAllocator::AllocateBlocks(): transaction: %ld, min: %lu, "
  5106. +       "max: %lu, block group: %lu, start: %lu, num groups: %lu\n",
  5107. +       transaction.ID(), minimum, maximum, blockGroup, start, fNumGroups);
  5108. +
  5109. +   uint32 bestStart = 0;
  5110. +   uint32 bestLength = 0;
  5111. +   uint32 bestGroup = 0;
  5112. +
  5113. +   uint32 groupNum = blockGroup;
  5114. +
  5115. +   AllocationBlockGroup* last = &fGroups[fNumGroups];
  5116. +   AllocationBlockGroup* group = &fGroups[blockGroup];
  5117. +
  5118. +   for (int32 iterations = 0; iterations < 2; iterations++) {
  5119. +       for (; group < last; ++group, ++groupNum) {
  5120. +           TRACE("BlockAllocator::AllocateBlocks(): Group %lu has largest "
  5121. +           "length of %lu\n", groupNum, group->LargestLength());
  5122. +
  5123. +           if (group->LargestLength() > bestLength) {
  5124. +               if (start <= group->LargestStart()) {
  5125. +                   bestStart = group->LargestStart();
  5126. +                   bestLength = group->LargestLength();
  5127. +                   bestGroup = groupNum;
  5128. +
  5129. +                   TRACE("BlockAllocator::AllocateBlocks(): Found a better "
  5130. +                       "range: block group: %lu, %lu-%lu\n", groupNum,
  5131. +                       bestStart, bestStart + bestLength);
  5132. +
  5133. +                   if (bestLength >= maximum)
  5134. +                       break;
  5135. +               }
  5136. +           }
  5137. +
  5138. +           start = 0;
  5139. +       }
  5140. +
  5141. +       if (bestLength >= maximum)
  5142. +           break;
  5143. +
  5144. +       groupNum = 0;
  5145. +
  5146. +       group = &fGroups[0];
  5147. +       last = &fGroups[blockGroup + 1];
  5148. +   }
  5149. +
  5150. +   if (bestLength < minimum) {
  5151. +       TRACE("BlockAllocator::AllocateBlocks(): best range (length %lu) "
  5152. +           "doesn't have minimum length of %lu\n", bestLength, minimum);
  5153. +       return B_DEVICE_FULL;
  5154. +   }
  5155. +
  5156. +   if (bestLength > maximum)
  5157. +       bestLength = maximum;
  5158. +
  5159. +   TRACE("BlockAllocator::AllocateBlocks(): Selected range: block group %lu, "
  5160. +       "%lu-%lu\n", bestGroup, bestStart, bestStart + bestLength);
  5161. +
  5162. +   status_t status = fGroups[bestGroup].Allocate(transaction, bestStart,
  5163. +       bestLength);
  5164. +   if (status != B_OK) {
  5165. +       TRACE("BlockAllocator::AllocateBlocks(): Failed to allocate %lu blocks "
  5166. +           "inside block group %lu.\n", bestLength, bestGroup);
  5167. +       return status;
  5168. +   }
  5169. +
  5170. +   start = bestStart;
  5171. +   length = bestLength;
  5172. +   blockGroup = bestGroup;
  5173. +
  5174. +   return B_OK;
  5175. +}
  5176. +
  5177. +
  5178. +status_t
  5179. +BlockAllocator::Allocate(Transaction& transaction, Inode* inode,
  5180. +   off_t numBlocks, uint32 minimum, uint32& start, uint32& allocated)
  5181. +{
  5182. +   if (numBlocks <= 0)
  5183. +       return B_ERROR;
  5184. +
  5185. +   uint32 group = inode->ID() / fVolume->InodesPerGroup();
  5186. +   uint32 preferred = 0;
  5187. +
  5188. +   if (inode->Size() > 0) {
  5189. +       // Try to allocate near it's last blocks
  5190. +       ext2_data_stream* dataStream = &inode->Node().stream;
  5191. +       uint32 numBlocks = inode->Size() / fVolume->BlockSize() + 1;
  5192. +       uint32 lastBlock = 0;
  5193. +
  5194. +       // DANGER! What happens with sparse files?
  5195. +       if (numBlocks < EXT2_DIRECT_BLOCKS) {
  5196. +           // Only direct blocks
  5197. +           lastBlock = dataStream->direct[numBlocks];
  5198. +       } else {
  5199. +           numBlocks -= EXT2_DIRECT_BLOCKS - 1;
  5200. +           uint32 numIndexes = fVolume->BlockSize() / 4;
  5201. +               // block size / sizeof(int32)
  5202. +           uint32 numIndexes2 = numIndexes * numIndexes;
  5203. +           uint32 numIndexes3 = numIndexes2 * numIndexes;
  5204. +           uint32 indexesInIndirect = numIndexes;
  5205. +           uint32 indexesInDoubleIndirect = indexesInIndirect
  5206. +               + numIndexes2;
  5207. +           // uint32 indexesInTripleIndirect = indexesInDoubleIndirect
  5208. +               // + numIndexes3;
  5209. +
  5210. +           uint32 doubleIndirectBlock = EXT2_DIRECT_BLOCKS + 1;
  5211. +           uint32 indirectBlock = EXT2_DIRECT_BLOCKS;
  5212. +
  5213. +           CachedBlock cached(fVolume);
  5214. +           uint32* indirectData;
  5215. +
  5216. +           if (numBlocks > indexesInDoubleIndirect) {
  5217. +               // Triple indirect blocks
  5218. +               indirectData = (uint32*)cached.SetTo(EXT2_DIRECT_BLOCKS + 2);
  5219. +               if (indirectData == NULL)
  5220. +                   return B_IO_ERROR;
  5221. +
  5222. +               uint32 index = (numBlocks - indexesInDoubleIndirect)
  5223. +                   / numIndexes3;
  5224. +               doubleIndirectBlock = indirectData[index];
  5225. +           }
  5226. +
  5227. +           if (numBlocks > indexesInIndirect) {
  5228. +               // Double indirect blocks
  5229. +               indirectData = (uint32*)cached.SetTo(doubleIndirectBlock);
  5230. +               if (indirectData == NULL)
  5231. +                   return B_IO_ERROR;
  5232. +
  5233. +               uint32 index = (numBlocks - indexesInIndirect) / numIndexes2;
  5234. +               indirectBlock = indirectData[index];
  5235. +           }
  5236. +
  5237. +           indirectData = (uint32*)cached.SetTo(indirectBlock);
  5238. +               if (indirectData == NULL)
  5239. +                   return B_IO_ERROR;
  5240. +
  5241. +           uint32 index = numBlocks / numIndexes;
  5242. +           lastBlock = indirectData[index];
  5243. +       }
  5244. +
  5245. +       group = (lastBlock - fFirstBlock) / fBlocksPerGroup;
  5246. +       preferred = (lastBlock - fFirstBlock) % fBlocksPerGroup + 1;
  5247. +   }
  5248. +
  5249. +   // TODO: Apply some more policies
  5250. +
  5251. +   return AllocateBlocks(transaction, minimum, minimum + 8, group, start,
  5252. +       allocated);
  5253. +}
  5254. +
  5255. +
  5256. +status_t
  5257. +BlockAllocator::Free(Transaction& transaction, uint32 start, uint32 length)
  5258. +{
  5259. +   TRACE("BlockAllocator::Free(%lu, %lu)\n", start, length);
  5260. +   MutexLocker lock(fLock);
  5261. +
  5262. +   if (start <= fFirstBlock) {
  5263. +       panic("Trying to free superblock!\n");
  5264. +       return B_BAD_DATA;
  5265. +   }
  5266. +
  5267. +   if (length == 0)
  5268. +       return B_OK;
  5269. +
  5270. +   TRACE("BlockAllocator::Free(): first block: %lu, blocks per group: %lu\n",
  5271. +       fFirstBlock, fBlocksPerGroup);
  5272. +
  5273. +   start -= fFirstBlock;
  5274. +   uint32 end = start + length - 1;
  5275. +
  5276. +   uint32 group = start / fBlocksPerGroup;
  5277. +   uint32 lastGroup = end / fBlocksPerGroup;
  5278. +   start = start % fBlocksPerGroup;
  5279. +
  5280. +   if (group == lastGroup)
  5281. +       return fGroups[group].Free(transaction, start, length);
  5282. +
  5283. +   TRACE("BlockAllocator::Free(): Freeing from group %lu: %lu, %lu\n", group,
  5284. +       start, fGroups[group].NumBits() - start);
  5285. +
  5286. +   status_t status = fGroups[group].Free(transaction, start,
  5287. +       fGroups[group].NumBits() - start);
  5288. +   if (status != B_OK)
  5289. +       return status;
  5290. +
  5291. +   for (++group; group < lastGroup; ++group) {
  5292. +       TRACE("BlockAllocator::Free(): Freeing all from group %lu\n", group);
  5293. +       status = fGroups[group].FreeAll(transaction);
  5294. +       if (status != B_OK)
  5295. +           return status;
  5296. +   }
  5297. +
  5298. +   TRACE("BlockAllocator::Free(): Freeing from group %lu: 0-%lu \n", group,
  5299. +       end % fBlocksPerGroup);
  5300. +   return fGroups[group].Free(transaction, 0, (end + 1) % fBlocksPerGroup);
  5301. +}
  5302. +
  5303. +
  5304. +/*static*/ status_t
  5305. +BlockAllocator::_Initialize(BlockAllocator* allocator)
  5306. +{
  5307. +   TRACE("BlockAllocator::_Initialize()\n");
  5308. +   // fLock is already heald
  5309. +   Volume* volume = allocator->fVolume;
  5310. +
  5311. +   AllocationBlockGroup* groups = allocator->fGroups;
  5312. +   uint32 numGroups = allocator->fNumGroups - 1;
  5313. +
  5314. +   uint32 freeBlocks = 0;
  5315. +   TRACE("BlockAllocator::_Initialize(): free blocks: %lu\n", freeBlocks);
  5316. +
  5317. +   for (uint32 i = 0; i < numGroups; ++i) {
  5318. +       status_t status = groups[i].Initialize(volume, i,
  5319. +           allocator->fBlocksPerGroup);
  5320. +       if (status != B_OK) {
  5321. +           mutex_unlock(&allocator->fLock);
  5322. +           return status;
  5323. +       }
  5324. +
  5325. +       freeBlocks += groups[i].FreeBits();
  5326. +       TRACE("BlockAllocator::_Initialize(): free blocks: %lu\n", freeBlocks);
  5327. +   }
  5328. +  
  5329. +   // Last block group may have less blocks
  5330. +   status_t status = groups[numGroups].Initialize(volume, numGroups,
  5331. +       allocator->fNumBlocks - allocator->fBlocksPerGroup * numGroups
  5332. +       - allocator->fFirstBlock);
  5333. +   if (status != B_OK) {
  5334. +       mutex_unlock(&allocator->fLock);
  5335. +       return status;
  5336. +   }
  5337. +  
  5338. +   freeBlocks += groups[numGroups].FreeBits();
  5339. +
  5340. +   TRACE("BlockAllocator::_Initialize(): free blocks: %lu\n", freeBlocks);
  5341. +
  5342. +   mutex_unlock(&allocator->fLock);
  5343. +
  5344. +   if (freeBlocks != volume->NumFreeBlocks()) {
  5345. +       TRACE("Counted free blocks (%lu) doesn't match value in the "
  5346. +           "superblock (%lu).\n", freeBlocks, (uint32)volume->NumFreeBlocks());
  5347. +       return B_BAD_DATA;
  5348. +   }
  5349. +
  5350. +   return B_OK;
  5351. +}
  5352.  
  5353. Property changes on: src/add-ons/kernel/file_systems/ext2/BlockAllocator.cpp
  5354. ___________________________________________________________________
  5355. Added: svn:executable
  5356.    + *
  5357.  
  5358. Index: src/add-ons/kernel/file_systems/ext2/Inode.cpp
  5359. ===================================================================
  5360. --- src/add-ons/kernel/file_systems/ext2/Inode.cpp  (revision 38119)
  5361. +++ src/add-ons/kernel/file_systems/ext2/Inode.cpp  (working copy)
  5362. @@ -8,8 +8,13 @@
  5363.  
  5364.  #include <fs_cache.h>
  5365.  #include <string.h>
  5366. +#include <util/AutoLock.h>
  5367.  
  5368.  #include "CachedBlock.h"
  5369. +#include "DataStream.h"
  5370. +#include "DirectoryIterator.h"
  5371. +#include "HTree.h"
  5372. +#include "Utility.h"
  5373.  
  5374.  
  5375.  //#define TRACE_EXT2
  5376. @@ -26,56 +31,151 @@
  5377.     fID(id),
  5378.     fCache(NULL),
  5379.     fMap(NULL),
  5380. -   fNode(NULL),
  5381. +   fCached(false),
  5382.     fAttributesBlock(NULL)
  5383.  {
  5384.     rw_lock_init(&fLock, "ext2 inode");
  5385.  
  5386. -   uint32 block;
  5387. -   if (volume->GetInodeBlock(id, block) == B_OK) {
  5388. -       TRACE("inode %Ld at block %lu\n", ID(), block);
  5389. -       uint8* inodeBlock = (uint8*)block_cache_get(volume->BlockCache(),
  5390. -           block);
  5391. -       if (inodeBlock != NULL) {
  5392. -           fNode = (ext2_inode*)(inodeBlock + volume->InodeBlockIndex(id)
  5393. -               * volume->InodeSize());
  5394. -       }
  5395. -   }
  5396. +   TRACE("Inode::Inode(): ext2_inode: %lu, disk inode: %lu\n",
  5397. +       sizeof(ext2_inode), fVolume->InodeSize());
  5398. +   fNodeSize = sizeof(ext2_inode) > fVolume->InodeSize()
  5399. +       ? fVolume->InodeSize() : sizeof(ext2_inode);
  5400.  
  5401. -   if (fNode != NULL) {
  5402. -       // TODO: we don't need a cache for short symlinks
  5403. -       fCache = file_cache_create(fVolume->ID(), ID(), Size());
  5404. -       fMap = file_map_create(fVolume->ID(), ID(), Size());
  5405. -   }
  5406. +   fInitStatus = UpdateNodeFromDisk();
  5407. +   if (fInitStatus == B_OK) {
  5408. +       if (IsDirectory() || (IsSymLink() && Size() < 60)) {
  5409. +           TRACE("Inode::Inode(): Not creating the file cache\n");
  5410. +           fCached = false;
  5411. +
  5412. +           fInitStatus = B_OK;
  5413. +       } else
  5414. +           fInitStatus = EnableFileCache();
  5415. +   } else
  5416. +       TRACE("Inode: Failed initialization\n");
  5417.  }
  5418.  
  5419.  
  5420. +Inode::Inode(Volume* volume)
  5421. +   :
  5422. +   fVolume(volume),
  5423. +   fID(0),
  5424. +   fCache(NULL),
  5425. +   fMap(NULL),
  5426. +   fCached(false),
  5427. +   fAttributesBlock(NULL),
  5428. +   fInitStatus(B_NO_INIT)
  5429. +{
  5430. +   rw_lock_init(&fLock, "ext2 inode");
  5431. +
  5432. +   TRACE("Inode::Inode(): ext2_inode: %lu, disk inode: %lu\n",
  5433. +       sizeof(ext2_inode), fVolume->InodeSize());
  5434. +   fNodeSize = sizeof(ext2_inode) > fVolume->InodeSize()
  5435. +       ? fVolume->InodeSize() : sizeof(ext2_inode);
  5436. +}
  5437. +
  5438. +
  5439.  Inode::~Inode()
  5440.  {
  5441. -   file_cache_delete(FileCache());
  5442. -   file_map_delete(Map());
  5443. +   TRACE("Inode destructor\n");
  5444.  
  5445. +   if (fCached) {
  5446. +       TRACE("Deleting the file cache and file map\n");
  5447. +       file_cache_delete(FileCache());
  5448. +       file_map_delete(Map());
  5449. +   }
  5450. +
  5451.     if (fAttributesBlock) {
  5452. +       TRACE("Returning the attributes block\n");
  5453.         uint32 block = B_LENDIAN_TO_HOST_INT32(Node().file_access_control);
  5454.         block_cache_put(fVolume->BlockCache(), block);
  5455.     }
  5456.  
  5457. -   if (fNode != NULL) {
  5458. -       uint32 block;
  5459. -       if (fVolume->GetInodeBlock(ID(), block) == B_OK)
  5460. -           block_cache_put(fVolume->BlockCache(), block);
  5461. -   }
  5462. +   TRACE("Inode destructor: Done\n");
  5463.  }
  5464.  
  5465.  
  5466.  status_t
  5467.  Inode::InitCheck()
  5468.  {
  5469. -   return fNode != NULL ? B_OK : B_ERROR;
  5470. +   return fInitStatus;
  5471.  }
  5472.  
  5473.  
  5474. +void
  5475. +Inode::WriteLockInTransaction(Transaction& transaction)
  5476. +{
  5477. +   acquire_vnode(fVolume->FSVolume(), ID());
  5478. +
  5479. +   TRACE("Inode::WriteLockInTransaction(): Locking\n");
  5480. +   rw_lock_write_lock(&fLock);
  5481. +
  5482. +   transaction.AddListener(this);
  5483. +}
  5484. +
  5485. +
  5486.  status_t
  5487. +Inode::WriteBack(Transaction& transaction)
  5488. +{
  5489. +   uint32 inodeBlock;
  5490. +
  5491. +   status_t status = fVolume->GetInodeBlock(fID, inodeBlock);
  5492. +   if (status != B_OK)
  5493. +       return status;
  5494. +
  5495. +   CachedBlock cached(fVolume);
  5496. +   uint8* inodeBlockData = cached.SetToWritable(transaction, inodeBlock);
  5497. +   if (inodeBlockData == NULL)
  5498. +       return B_IO_ERROR;
  5499. +
  5500. +   TRACE("Inode::WriteBack(): Inode ID: %d, inode block: %lu, data: %p, "
  5501. +       "index: %lu, inode size: %lu, node size: %lu, this: %p, node: %p\n",
  5502. +       (int)fID, inodeBlock, inodeBlockData, fVolume->InodeBlockIndex(fID),
  5503. +       fVolume->InodeSize(), fNodeSize, this, &fNode);
  5504. +   memcpy(inodeBlockData +
  5505. +           fVolume->InodeBlockIndex(fID) * fVolume->InodeSize(),
  5506. +       (uint8*)&fNode, fNodeSize);
  5507. +
  5508. +   TRACE("Inode::WriteBack() finished\n");
  5509. +
  5510. +   return B_OK;
  5511. +}
  5512. +
  5513. +
  5514. +status_t
  5515. +Inode::UpdateNodeFromDisk()
  5516. +{
  5517. +   uint32 block;
  5518. +
  5519. +   status_t status = fVolume->GetInodeBlock(fID, block);
  5520. +   if (status != B_OK)
  5521. +       return status;
  5522. +
  5523. +   TRACE("inode %Ld at block %lu\n", fID, block);
  5524. +
  5525. +   CachedBlock cached(fVolume);
  5526. +   const uint8* inodeBlock = cached.SetTo(block);
  5527. +
  5528. +   if (inodeBlock == NULL)
  5529. +       return B_IO_ERROR;
  5530. +
  5531. +   TRACE("Inode size: %lu, inode index: %lu\n", fVolume->InodeSize(),
  5532. +       fVolume->InodeBlockIndex(fID));
  5533. +   ext2_inode* inode = (ext2_inode*)(inodeBlock
  5534. +       + fVolume->InodeBlockIndex(fID) * fVolume->InodeSize());
  5535. +
  5536. +   TRACE("Attempting to copy inode data from %p to %p, ext2_inode "
  5537. +       "size: %lu\n", inode, &fNode, fNodeSize);
  5538. +
  5539. +   memcpy(&fNode, inode, fNodeSize);
  5540. +
  5541. +   uint32 numLinks = fNode.NumLinks();
  5542. +   fUnlinked = numLinks == 0 || (IsDirectory() && numLinks == 1);
  5543. +
  5544. +   return B_OK;
  5545. +}
  5546. +
  5547. +
  5548. +status_t
  5549.  Inode::CheckPermissions(int accessMode) const
  5550.  {
  5551.     uid_t user = geteuid();
  5552. @@ -95,9 +195,9 @@
  5553.  
  5554.     // shift mode bits, to check directly against accessMode
  5555.     mode_t mode = Mode();
  5556. -   if (user == (uid_t)fNode->UserID())
  5557. +   if (user == (uid_t)fNode.UserID())
  5558.         mode >>= 6;
  5559. -   else if (group == (gid_t)fNode->GroupID())
  5560. +   else if (group == (gid_t)fNode.GroupID())
  5561.         mode >>= 3;
  5562.  
  5563.     if (accessMode & ~(mode & S_IRWXO))
  5564. @@ -114,8 +214,10 @@
  5565.     uint32 perIndirectBlock = perBlock * perBlock;
  5566.     uint32 index = offset >> fVolume->BlockShift();
  5567.  
  5568. -   if (offset >= Size())
  5569. +   if (offset >= Size()) {
  5570. +       TRACE("FindBlock: offset larger than inode size\n");
  5571.         return B_ENTRY_NOT_FOUND;
  5572. +   }
  5573.  
  5574.     // TODO: we could return the size of the sparse range, as this might be more
  5575.     // than just a block
  5576. @@ -186,7 +288,7 @@
  5577.             }
  5578.         }
  5579.     } else {
  5580. -       // outside of the possible data stream
  5581. +       // Outside of the possible data stream
  5582.         dprintf("ext2: block outside datastream!\n");
  5583.         return B_ERROR;
  5584.     }
  5585. @@ -203,7 +305,8 @@
  5586.  
  5587.     // set/check boundaries for pos/length
  5588.     if (pos < 0) {
  5589. -       TRACE("inode %Ld: ReadAt failed(pos %Ld, length %lu)\n", ID(), pos, length);
  5590. +       TRACE("inode %Ld: ReadAt failed(pos %Ld, length %lu)\n", ID(), pos,
  5591. +           length);
  5592.         return B_BAD_VALUE;
  5593.     }
  5594.  
  5595. @@ -218,6 +321,143 @@
  5596.  
  5597.  
  5598.  status_t
  5599. +Inode::WriteAt(Transaction& transaction, off_t pos, const uint8* buffer,
  5600. +   size_t* _length)
  5601. +{
  5602. +   TRACE("Inode::WriteAt(%lld, %p, *(%p) = %ld)\n", (long long)pos, buffer,
  5603. +       _length, (long)*_length);
  5604. +   ReadLocker readLocker(fLock);
  5605. +
  5606. +   if (IsFileCacheDisabled())
  5607. +       return B_BAD_VALUE;
  5608. +
  5609. +   if (pos < 0)
  5610. +       return B_BAD_VALUE;
  5611. +
  5612. +   readLocker.Unlock();
  5613. +
  5614. +   TRACE("Inode::WriteAt(): Starting transaction\n");
  5615. +   transaction.Start(fVolume->GetJournal());
  5616. +
  5617. +   WriteLocker writeLocker(fLock);
  5618. +
  5619. +   TRACE("Inode::WriteAt(): Updating modification time\n");
  5620. +   fNode.SetModificationTime(real_time_clock());
  5621. +
  5622. +   size_t length = *_length;
  5623. +   off_t end = pos + length;
  5624. +   off_t oldSize = Size();
  5625. +
  5626. +   TRACE("Inode::WriteAt(): Old size: %d, new size: %d\n", (int)oldSize,
  5627. +       (int)end);
  5628. +
  5629. +   if (end > oldSize) {
  5630. +       status_t status = Resize(transaction, end);
  5631. +       if (status != B_OK) {
  5632. +           *_length = 0;
  5633. +           WriteLockInTransaction(transaction);
  5634. +           return status;
  5635. +       }
  5636. +
  5637. +       status = WriteBack(transaction);
  5638. +       if (status != B_OK) {
  5639. +           *_length = 0;
  5640. +           WriteLockInTransaction(transaction);
  5641. +           return status;
  5642. +       }
  5643. +   }
  5644. +
  5645. +   writeLocker.Unlock();
  5646. +
  5647. +   if (oldSize < pos)
  5648. +       FillGapWithZeros(oldSize, pos);
  5649. +
  5650. +   if (length == 0) {
  5651. +       // Probably just changed the file size with the pos parameter
  5652. +       return B_OK;
  5653. +   }
  5654. +
  5655. +   TRACE("Inode::WriteAt(): Performing write: %p, %d, %p, %d\n",
  5656. +       FileCache(), (int)pos, buffer, (int)*_length);
  5657. +   status_t status = file_cache_write(FileCache(), NULL, pos, buffer, _length);
  5658. +
  5659. +   WriteLockInTransaction(transaction);
  5660. +
  5661. +   TRACE("Inode::WriteAt(): Done\n");
  5662. +
  5663. +   return status;
  5664. +}
  5665. +
  5666. +
  5667. +status_t
  5668. +Inode::FillGapWithZeros(off_t start, off_t end)
  5669. +{
  5670. +   TRACE("Inode::FileGapWithZeros(%ld - %ld)\n", (long)start, (long)end);
  5671. +
  5672. +   while (start < end) {
  5673. +       size_t size;
  5674. +
  5675. +       if (end > start + 1024 * 1024 * 1024)
  5676. +           size = 1024 * 1024 * 1024;
  5677. +       else
  5678. +           size = end - start;
  5679. +
  5680. +       TRACE("Inode::FillGapWithZeros(): Calling file_cache_write(%p, NULL, "
  5681. +           "%ld, NULL, &(%ld) = %p)\n", fCache, (long)start, (long)size,
  5682. +           &size);
  5683. +       status_t status = file_cache_write(fCache, NULL, start, NULL,
  5684. +           &size);
  5685. +       if (status != B_OK)
  5686. +           return status;
  5687. +
  5688. +       start += size;
  5689. +   }
  5690. +
  5691. +   return B_OK;
  5692. +}
  5693. +
  5694. +
  5695. +status_t
  5696. +Inode::Resize(Transaction& transaction, off_t size)
  5697. +{
  5698. +   TRACE("Inode::Resize(): size: %ld\n", (long)size);
  5699. +   if (size < 0)
  5700. +       return B_BAD_VALUE;
  5701. +
  5702. +   off_t oldSize = Size();
  5703. +
  5704. +   if (size == oldSize)
  5705. +       return B_OK;
  5706. +
  5707. +   TRACE("Inode::Resize(): old size: %ld, new size: %ld\n", (long)oldSize,
  5708. +       (long)size);
  5709. +
  5710. +   status_t status;
  5711. +   if (size > oldSize) {
  5712. +       status = _EnlargeDataStream(transaction, size);
  5713. +       if (status != B_OK) {
  5714. +           // Restore original size
  5715. +           _ShrinkDataStream(transaction, oldSize);
  5716. +       }
  5717. +   } else
  5718. +       status = _ShrinkDataStream(transaction, size);
  5719. +
  5720. +   TRACE("Inode::Resize(): Updating file map and cache\n");
  5721. +
  5722. +   if (status != B_OK)
  5723. +       return status;
  5724. +
  5725. +   file_cache_set_size(FileCache(), size);
  5726. +   file_map_set_size(Map(), size);
  5727. +
  5728. +   TRACE("Inode::Resize(): Writing back inode changes. Size: %ld\n",
  5729. +       (long)Size());
  5730. +
  5731. +   return WriteBack(transaction);
  5732. +}
  5733. +
  5734. +
  5735. +status_t
  5736.  Inode::AttributeBlockReadAt(off_t pos, uint8* buffer, size_t* _length)
  5737.  {
  5738.     TRACE("Inode::%s(%Ld, , %lu)\n", __FUNCTION__, pos, *_length);
  5739. @@ -245,3 +485,438 @@
  5740.     *_length = length;
  5741.     return B_NO_ERROR;
  5742.  }
  5743. +
  5744. +
  5745. +status_t
  5746. +Inode::InitDirectory(Transaction& transaction, Inode* parent)
  5747. +{
  5748. +   TRACE("Inode::InitDirectory()\n");
  5749. +   uint32 blockSize = fVolume->BlockSize();
  5750. +
  5751. +   status_t status = Resize(transaction, blockSize);
  5752. +   if (status != B_OK)
  5753. +       return status;
  5754. +
  5755. +   uint32 blockNum;
  5756. +   status = FindBlock(0, blockNum);
  5757. +   if (status != B_OK)
  5758. +       return status;
  5759. +
  5760. +   CachedBlock cached(fVolume);
  5761. +   uint8* block = cached.SetToWritable(transaction, blockNum, true);
  5762. +
  5763. +   HTreeRoot* root = (HTreeRoot*)block;
  5764. +   root->dot.inode_id = fID;
  5765. +   root->dot.entry_length = 12;
  5766. +   root->dot.name_length = 1;
  5767. +   root->dot.file_type = EXT2_TYPE_DIRECTORY;
  5768. +   root->dot_entry_name[0] = '.';
  5769. +
  5770. +   root->dotdot.inode_id = parent == NULL ? fID : parent->ID();
  5771. +   root->dotdot.entry_length = blockSize - 12;
  5772. +   root->dotdot.name_length = 2;
  5773. +   root->dotdot.file_type = EXT2_TYPE_DIRECTORY;
  5774. +   root->dotdot_entry_name[0] = '.';
  5775. +   root->dotdot_entry_name[1] = '.';
  5776. +
  5777. +   parent->Node().SetNumLinks(parent->Node().NumLinks() + 1);
  5778. +
  5779. +   return parent->WriteBack(transaction);
  5780. +}
  5781. +
  5782. +
  5783. +status_t
  5784. +Inode::Unlink(Transaction& transaction)
  5785. +{
  5786. +   uint32 numLinks = fNode.NumLinks();
  5787. +   TRACE("Inode::Unlink(): Current links: %lu\n", numLinks);
  5788. +
  5789. +   if (numLinks == 0)
  5790. +       return B_BAD_VALUE;
  5791. +
  5792. +   if ((IsDirectory() && numLinks == 2) || (numLinks == 1))  {
  5793. +       fUnlinked = true;
  5794. +
  5795. +       TRACE("Inode::Unlink(): Putting inode in orphan list\n");
  5796. +       ino_t firstOrphanID;
  5797. +       status_t status = fVolume->SaveOrphan(transaction, fID, firstOrphanID);
  5798. +       if (status != B_OK)
  5799. +           return status;
  5800. +
  5801. +       if (firstOrphanID != 0) {
  5802. +           Vnode firstOrphan(fVolume, firstOrphanID);
  5803. +           Inode* nextOrphan;
  5804. +      
  5805. +           status = firstOrphan.Get(&nextOrphan);
  5806. +           if (status != B_OK)
  5807. +               return status;
  5808. +
  5809. +           fNode.SetNextOrphan(nextOrphan->ID());
  5810. +       } else {
  5811. +           // Next orphan link is stored in deletion time
  5812. +           fNode.deletion_time = 0;
  5813. +       }
  5814. +
  5815. +       fNode.num_links = 0;
  5816. +
  5817. +       status = remove_vnode(fVolume->FSVolume(), fID);
  5818. +       if (status != B_OK)
  5819. +           return status;
  5820. +   } else
  5821. +       fNode.SetNumLinks(--numLinks);
  5822. +
  5823. +   return WriteBack(transaction);
  5824. +}
  5825. +
  5826. +
  5827. +/*static*/ status_t
  5828. +Inode::Create(Transaction& transaction, Inode* parent, const char* name,
  5829. +   int32 mode, int openMode, uint8 type, bool* _created, ino_t* _id,
  5830. +   Inode** _inode, fs_vnode_ops* vnodeOps, uint32 publishFlags)
  5831. +{
  5832. +   TRACE("Inode::Create()\n");
  5833. +   Volume* volume = transaction.GetVolume();
  5834. +
  5835. +   DirectoryIterator* entries = NULL;
  5836. +   ObjectDeleter<DirectoryIterator> entriesDeleter;
  5837. +
  5838. +   if (parent != NULL) {
  5839. +       parent->WriteLockInTransaction(transaction);
  5840. +
  5841. +       TRACE("Inode::Create(): Looking up entry destination\n");
  5842. +       HTree htree(volume, parent);
  5843. +
  5844. +       status_t status = htree.Lookup(name, &entries);
  5845. +       if (status == B_ENTRY_NOT_FOUND) {
  5846. +           panic("We need to add the first node.\n");
  5847. +           return B_ERROR;
  5848. +       }
  5849. +       if (status != B_OK)
  5850. +           return status;
  5851. +       entriesDeleter.SetTo(entries);
  5852. +
  5853. +       TRACE("Inode::Create(): Looking up to see if file already exists\n");
  5854. +       ino_t entryID;
  5855. +
  5856. +       status = entries->FindEntry(name, &entryID);
  5857. +       if (status == B_OK) {
  5858. +           // File already exists
  5859. +           TRACE("Inode::Create(): File already exists\n");
  5860. +           if (S_ISDIR(mode) || S_ISLNK(mode) || (openMode & O_EXCL) != 0)
  5861. +               return B_FILE_EXISTS;
  5862. +
  5863. +           Vnode vnode(volume, entryID);
  5864. +           Inode* inode;
  5865. +  
  5866. +           status = vnode.Get(&inode);
  5867. +           if (status != B_OK) {
  5868. +               TRACE("Inode::Create() Failed to get the inode from the "
  5869. +                   "vnode\n");
  5870. +               return B_ENTRY_NOT_FOUND;
  5871. +           }
  5872. +
  5873. +           if (inode->IsDirectory() && (openMode & O_RWMASK) != O_RDONLY)
  5874. +               return B_IS_A_DIRECTORY;
  5875. +           if ((openMode & O_DIRECTORY) != 0 && !inode->IsDirectory())
  5876. +               return B_NOT_A_DIRECTORY;
  5877. +
  5878. +           if (inode->CheckPermissions(open_mode_to_access(openMode)
  5879. +                   | ((openMode & O_TRUNC) != 0 ? W_OK : 0)) != B_OK)
  5880. +               return B_NOT_ALLOWED;
  5881. +
  5882. +           if ((openMode & O_TRUNC) != 0) {
  5883. +               // Truncate requested
  5884. +               TRACE("Inode::Create(): Truncating file\n");
  5885. +               inode->WriteLockInTransaction(transaction);
  5886. +
  5887. +               status = inode->Resize(transaction, 0);
  5888. +               if (status != B_OK)
  5889. +                   return status;
  5890. +           }
  5891. +
  5892. +           if (_created != NULL)
  5893. +               *_created = false;
  5894. +           if (_id != NULL)
  5895. +               *_id = inode->ID();
  5896. +           if (_inode != NULL)
  5897. +               *_inode = inode;
  5898. +
  5899. +           if (_id != NULL || _inode != NULL)
  5900. +               vnode.Keep();
  5901. +
  5902. +           TRACE("Inode::Create(): Done opening file\n");
  5903. +           return B_OK;
  5904. +       /*} else if ((mode & S_ATTR_DIR) == 0) {
  5905. +           TRACE("Inode::Create(): (mode & S_ATTR_DIR) == 0\n");
  5906. +           return B_BAD_VALUE;*/
  5907. +       } else if ((openMode & O_DIRECTORY) != 0) {
  5908. +           TRACE("Inode::Create(): (openMode & O_DIRECTORY) != 0\n");
  5909. +           return B_ENTRY_NOT_FOUND;
  5910. +       }
  5911. +
  5912. +       // Return to initial position
  5913. +       TRACE("Inode::Create(): Restarting iterator\n");
  5914. +       entries->Restart();
  5915. +   }
  5916. +
  5917. +   status_t status;
  5918. +   if (parent != NULL) {
  5919. +       status = parent->CheckPermissions(W_OK);
  5920. +       if (status != B_OK)
  5921. +           return status;
  5922. +   }
  5923. +
  5924. +   TRACE("Inode::Create(): Allocating inode\n");
  5925. +   ino_t id;
  5926. +   status = volume->AllocateInode(transaction, parent, mode, id);
  5927. +   if (status != B_OK)
  5928. +       return status;
  5929. +
  5930. +   if (entries != NULL) {
  5931. +       size_t nameLength = strlen(name);
  5932. +       status = entries->AddEntry(transaction, name, nameLength, id, type);
  5933. +       if (status != B_OK)
  5934. +           return status;
  5935. +   }
  5936. +
  5937. +   TRACE("Inode::Create(): Creating inode\n");
  5938. +   Inode* inode = new(std::nothrow) Inode(volume);
  5939. +   if (inode == NULL)
  5940. +       return B_NO_MEMORY;
  5941. +
  5942. +   TRACE("Inode::Create(): Getting node structure\n");
  5943. +   ext2_inode& node = inode->Node();
  5944. +   TRACE("Inode::Create(): Initializing inode data\n");
  5945. +   node.SetMode(mode);
  5946. +   node.SetUserID(geteuid());
  5947. +   node.SetGroupID(parent != NULL ? parent->Node().GroupID() : getegid());
  5948. +   node.size = 0;
  5949. +   node.SetNumLinks(inode->IsDirectory() ? 2 : 1);
  5950. +   node.SetNumBlocks(volume->BlockSize() / 512);
  5951. +   TRACE("Inode::Create(): Setting block pointers to zero\n");
  5952. +   node.stream.direct[0] = 0;
  5953. +   node.stream.direct[1] = 0;
  5954. +   node.stream.direct[2] = 0;
  5955. +   node.stream.direct[3] = 0;
  5956. +   node.stream.direct[4] = 0;
  5957. +   node.stream.direct[5] = 0;
  5958. +   node.stream.direct[6] = 0;
  5959. +   node.stream.direct[7] = 0;
  5960. +   node.stream.direct[8] = 0;
  5961. +   node.stream.direct[9] = 0;
  5962. +   node.stream.direct[10] = 0;
  5963. +   node.stream.direct[11] = 0;
  5964. +   node.stream.indirect = 0;
  5965. +   node.stream.double_indirect = 0;
  5966. +   node.stream.triple_indirect = 0;
  5967. +
  5968. +   TRACE("Inode::Create(): Updating time\n");
  5969. +   time_t creationTime = real_time_clock();
  5970. +   node.SetAccessTime(creationTime);
  5971. +   node.SetCreationTime(creationTime);
  5972. +   node.SetModificationTime(creationTime);
  5973. +   node.deletion_time = 0;
  5974. +   node.flags = 0;
  5975. +   node._reserved1 = 0;
  5976. +
  5977. +   TRACE("Inode::Create(): Updating ID\n");
  5978. +   inode->fID = id;
  5979. +
  5980. +   TRACE("Inode::Create(): Possibly initializing directory\n");
  5981. +   if (inode->IsDirectory()) {
  5982. +       status = inode->InitDirectory(transaction, parent);
  5983. +       if (status != B_OK)
  5984. +           return status;
  5985. +   }
  5986. +
  5987. +   TRACE("Inode::Create(): Saving inode\n");
  5988. +   status = inode->WriteBack(transaction);
  5989. +   if (status != B_OK)
  5990. +       return status;
  5991. +
  5992. +   TRACE("Inode::Create(): Creating vnode\n");
  5993. +
  5994. +   Vnode vnode;
  5995. +   status = vnode.Publish(transaction, inode, vnodeOps, publishFlags);
  5996. +   if (status != B_OK)
  5997. +       return status;
  5998. +
  5999. +   if (!inode->IsSymLink()) {
  6000. +       // Vnode::Publish doesn't publish symlinks
  6001. +       if (!inode->IsDirectory()) {
  6002. +           status = inode->EnableFileCache();
  6003. +           if (status != B_OK)
  6004. +               return status;
  6005. +       }
  6006. +
  6007. +       inode->WriteLockInTransaction(transaction);
  6008. +   }
  6009. +
  6010. +   if (_created)
  6011. +       *_created = true;
  6012. +   if (_id != NULL)
  6013. +       *_id = id;
  6014. +   if (_inode != NULL)
  6015. +       *_inode = inode;
  6016. +
  6017. +   if (_id != NULL || _inode != NULL)
  6018. +       vnode.Keep();
  6019. +
  6020. +   TRACE("Inode::Create(): Done\n");
  6021. +   return B_OK;
  6022. +}
  6023. +
  6024. +
  6025. +status_t
  6026. +Inode::EnableFileCache()
  6027. +{
  6028. +   TRACE("Inode::EnableFileCache()\n");
  6029. +
  6030. +   if (fCached)
  6031. +       return B_OK;
  6032. +   if (fCache != NULL) {
  6033. +       fCached = true;
  6034. +       return B_OK;
  6035. +   }
  6036. +
  6037. +   TRACE("Inode::EnableFileCache(): Creating the file cache: %d, %d, %d\n",
  6038. +       (int)fVolume->ID(), (int)ID(), (int)Size());
  6039. +   fCache = file_cache_create(fVolume->ID(), ID(), Size());
  6040. +   fMap = file_map_create(fVolume->ID(), ID(), Size());
  6041. +
  6042. +   if (fCache == NULL) {
  6043. +       TRACE("Inode::EnableFileCache(): Failed to create file cache\n");
  6044. +       fCached = false;
  6045. +       return B_ERROR;
  6046. +   }
  6047. +
  6048. +   fCached = true;
  6049. +   TRACE("Inode::EnableFileCache(): Done\n");
  6050. +
  6051. +   return B_OK;
  6052. +}
  6053. +
  6054. +
  6055. +status_t
  6056. +Inode::DisableFileCache()
  6057. +{
  6058. +   TRACE("Inode::DisableFileCache()\n");
  6059. +
  6060. +   if (!fCached)
  6061. +       return B_OK;
  6062. +
  6063. +   file_cache_delete(FileCache());
  6064. +   file_map_delete(Map());
  6065. +
  6066. +   fCached = false;
  6067. +
  6068. +   return B_OK;
  6069. +}
  6070. +
  6071. +
  6072. +status_t
  6073. +Inode::Sync()
  6074. +{
  6075. +   if (!IsFileCacheDisabled())
  6076. +       return file_cache_sync(fCache);
  6077. +
  6078. +   return B_OK;
  6079. +}
  6080. +
  6081. +
  6082. +void
  6083. +Inode::TransactionDone(bool success)
  6084. +{
  6085. +   if (!success) {
  6086. +       // Revert any changes to the inode
  6087. +       if (fInitStatus == B_OK && UpdateNodeFromDisk() != B_OK)
  6088. +           panic("Failed to reload inode from disk!\n");
  6089. +       else if (fInitStatus == B_NO_INIT) {
  6090. +           // TODO: Unpublish vnode?
  6091. +           panic("Failed to finish creating inode\n");
  6092. +       }
  6093. +   } else {
  6094. +       if (fInitStatus == B_NO_INIT) {
  6095. +           TRACE("Inode::TransactionDone(): Inode creation succeeded\n");
  6096. +           fInitStatus = B_OK;
  6097. +       }
  6098. +   }
  6099. +}
  6100. +
  6101. +
  6102. +void
  6103. +Inode::RemovedFromTransaction()
  6104. +{
  6105. +   TRACE("Inode::RemovedFromTransaction(): Unlocking\n");
  6106. +   rw_lock_write_unlock(&fLock);
  6107. +
  6108. +   put_vnode(fVolume->FSVolume(), ID());
  6109. +}
  6110. +
  6111. +
  6112. +status_t
  6113. +Inode::_EnlargeDataStream(Transaction& transaction, off_t size)
  6114. +{
  6115. +   // TODO: Update fNode.num_blocks
  6116. +   if (size < 0)
  6117. +       return B_BAD_DATA;
  6118. +
  6119. +   TRACE("Inode::_EnlargeDataStream()\n");
  6120. +
  6121. +   uint32 blockSize = fVolume->BlockSize();
  6122. +   off_t oldSize = Size();
  6123. +   off_t maxSize = oldSize;
  6124. +   if (maxSize % blockSize != 0)
  6125. +       maxSize += blockSize - maxSize % blockSize;
  6126. +
  6127. +   if (size <= maxSize) {
  6128. +       // No need to allocate more blocks
  6129. +       TRACE("Inode::_EnlargeDataStream(): No need to allocate more blocks\n");
  6130. +       TRACE("Inode::_EnlargeDataStream(): Setting size to %ld\n", (long)size);
  6131. +       fNode.SetSize(size);
  6132. +       return B_OK;
  6133. +   }
  6134. +
  6135. +   uint32 end = size == 0 ? 0 : (size - 1) / fVolume->BlockSize() + 1;
  6136. +   DataStream stream(fVolume, &fNode.stream, oldSize);
  6137. +   stream.Enlarge(transaction, end);
  6138. +
  6139. +   TRACE("Inode::_EnlargeDataStream(): Setting size to %ld\n", (long)size);
  6140. +   fNode.SetSize(size);
  6141. +   fNode.SetNumBlocks(end * (fVolume->BlockSize() / 512));
  6142. +
  6143. +   return B_OK;
  6144. +}
  6145. +
  6146. +
  6147. +status_t
  6148. +Inode::_ShrinkDataStream(Transaction& transaction, off_t size)
  6149. +{
  6150. +   TRACE("Inode::_ShrinkDataStream()\n");
  6151. +
  6152. +   if (size < 0)
  6153. +       return B_BAD_DATA;
  6154. +
  6155. +   uint32 blockSize = fVolume->BlockSize();
  6156. +   off_t oldSize = Size();
  6157. +   off_t lastByte = oldSize == 0 ? 0 : oldSize - 1;
  6158. +   off_t minSize = (lastByte / blockSize + 1) * blockSize;
  6159. +       // Minimum size that doesn't require freeing blocks
  6160. +
  6161. +   if (size > minSize) {
  6162. +       // No need to allocate more blocks
  6163. +       TRACE("Inode::_ShrinkDataStream(): No need to allocate more blocks\n");
  6164. +       TRACE("Inode::_ShrinkDataStream(): Setting size to %ld\n", (long)size);
  6165. +       fNode.SetSize(size);
  6166. +       return B_OK;
  6167. +   }
  6168. +
  6169. +   uint32 end = size == 0 ? 0 : (size - 1) / fVolume->BlockSize() + 1;
  6170. +   DataStream stream(fVolume, &fNode.stream, oldSize);
  6171. +   stream.Shrink(transaction, end);
  6172. +
  6173. +   fNode.SetSize(size);
  6174. +   fNode.SetNumBlocks(end * (fVolume->BlockSize() / 512));
  6175. +
  6176. +   return B_OK;
  6177. +}
  6178. Index: src/add-ons/kernel/file_systems/ext2/HashRevokeManager.h
  6179. ===================================================================
  6180. --- src/add-ons/kernel/file_systems/ext2/HashRevokeManager.h    (revision 0)
  6181. +++ src/add-ons/kernel/file_systems/ext2/HashRevokeManager.h    (revision 0)
  6182. @@ -0,0 +1,47 @@
  6183. +/*
  6184. + * Copyright 2001-2010, Haiku Inc. All rights reserved.
  6185. + * This file may be used under the terms of the MIT License.
  6186. + *
  6187. + * Authors:
  6188. + *     Janito V. Ferreira Filho
  6189. + */
  6190. +#ifndef HASHREVOKEMANAGER_H
  6191. +#define HASHREVOKEMANAGER_H
  6192. +
  6193. +#include <util/khash.h>
  6194. +
  6195. +#include "RevokeManager.h"
  6196. +
  6197. +
  6198. +struct RevokeElement {
  6199. +   RevokeElement*  next;   // Next in hash
  6200. +   uint32          block;
  6201. +   uint32          commitID;
  6202. +};
  6203. +
  6204. +
  6205. +class HashRevokeManager : public RevokeManager {
  6206. +public:
  6207. +                       HashRevokeManager();
  6208. +   virtual             ~HashRevokeManager();
  6209. +
  6210. +           status_t    Init();
  6211. +
  6212. +   virtual status_t    Insert(uint32 block, uint32 commitID);
  6213. +   virtual status_t    Remove(uint32 block);
  6214. +   virtual bool        Lookup(uint32 block, uint32 commitID);
  6215. +          
  6216. +   static  int         Compare(void* element, const void* key);
  6217. +   static  uint32      Hash(void* element, const void* key, uint32 range);
  6218. +
  6219. +protected:
  6220. +           status_t    _ForceInsert(uint32 block, uint32 commitID);
  6221. +
  6222. +private:
  6223. +           hash_table* fHash;
  6224. +
  6225. +   const   int         kInitialHashSize;
  6226. +};
  6227. +
  6228. +#endif // HASHREVOKEMANAGER_H
  6229. +
  6230.  
  6231. Property changes on: src/add-ons/kernel/file_systems/ext2/HashRevokeManager.h
  6232. ___________________________________________________________________
  6233. Added: svn:executable
  6234.    + *
  6235.  
  6236. Index: src/add-ons/kernel/file_systems/ext2/kernel_interface.cpp
  6237. ===================================================================
  6238. --- src/add-ons/kernel/file_systems/ext2/kernel_interface.cpp   (revision 38119)
  6239. +++ src/add-ons/kernel/file_systems/ext2/kernel_interface.cpp   (working copy)
  6240. @@ -11,12 +11,18 @@
  6241.  #include <AutoDeleter.h>
  6242.  #include <fs_cache.h>
  6243.  #include <fs_info.h>
  6244. +#include <io_requests.h>
  6245. +#include <NodeMonitor.h>
  6246. +#include <util/AutoLock.h>
  6247.  
  6248.  #include "AttributeIterator.h"
  6249. +#include "CachedBlock.h"
  6250.  #include "DirectoryIterator.h"
  6251.  #include "ext2.h"
  6252.  #include "HTree.h"
  6253.  #include "Inode.h"
  6254. +#include "Journal.h"
  6255. +#include "Utility.h"
  6256.  
  6257.  
  6258.  //#define TRACE_EXT2
  6259. @@ -35,23 +41,29 @@
  6260.  };
  6261.  
  6262.  
  6263. -/*!    Converts the open mode, the open flags given to bfs_open(), into
  6264. -   access modes, e.g. since O_RDONLY requires read access to the
  6265. -   file, it will be converted to R_OK.
  6266. -*/
  6267. -int
  6268. -open_mode_to_access(int openMode)
  6269. +//!    ext2_io() callback hook
  6270. +static status_t
  6271. +iterative_io_get_vecs_hook(void* cookie, io_request* request, off_t offset,
  6272. +   size_t size, struct file_io_vec* vecs, size_t* _count)
  6273.  {
  6274. -   openMode &= O_RWMASK;
  6275. -   if (openMode == O_RDONLY)
  6276. -       return R_OK;
  6277. -   else if (openMode == O_WRONLY)
  6278. -       return W_OK;
  6279. +   Inode* inode = (Inode*)cookie;
  6280.  
  6281. -   return R_OK | W_OK;
  6282. +   return file_map_translate(inode->Map(), offset, size, vecs, _count,
  6283. +       inode->GetVolume()->BlockSize());
  6284.  }
  6285.  
  6286.  
  6287. +//!    ext2_io() callback hook
  6288. +static status_t
  6289. +iterative_io_finished_hook(void* cookie, io_request* request, status_t status,
  6290. +   bool partialTransfer, size_t bytesTransferred)
  6291. +{
  6292. +   Inode* inode = (Inode*)cookie;
  6293. +   rw_lock_read_unlock(inode->Lock());
  6294. +   return B_OK;
  6295. +}
  6296. +
  6297. +
  6298.  // #pragma mark - Scanning
  6299.  
  6300.  
  6301. @@ -116,6 +128,7 @@
  6302.  
  6303.     status_t status = volume->Mount(device, flags);
  6304.     if (status != B_OK) {
  6305. +       TRACE("Failed mounting the volume. Error: %s\n", strerror(status));
  6306.         delete volume;
  6307.         return status;
  6308.     }
  6309. @@ -148,7 +161,7 @@
  6310.     info->io_size = EXT2_IO_SIZE;
  6311.     info->block_size = volume->BlockSize();
  6312.     info->total_blocks = volume->NumBlocks();
  6313. -   info->free_blocks = volume->FreeBlocks();
  6314. +   info->free_blocks = volume->NumFreeBlocks();
  6315.  
  6316.     // Volume name
  6317.     strlcpy(info->volume_name, volume->Name(), sizeof(info->volume_name));
  6318. @@ -201,6 +214,50 @@
  6319.  }
  6320.  
  6321.  
  6322. +static status_t
  6323. +ext2_remove_vnode(fs_volume* _volume, fs_vnode* _node, bool reenter)
  6324. +{
  6325. +   TRACE("ext2_remove_vnode()\n");
  6326. +   Volume* volume = (Volume*)_volume->private_volume;
  6327. +   Inode* inode = (Inode*)_node->private_node;
  6328. +   ObjectDeleter<Inode> inodeDeleter(inode);
  6329. +
  6330. +   if (!inode->IsDeleted())
  6331. +       return B_OK;
  6332. +
  6333. +   TRACE("ext2_remove_vnode(): Starting transaction\n");
  6334. +   Transaction transaction(volume->GetJournal());
  6335. +
  6336. +   if (!inode->IsSymLink() || inode->Size() >= EXT2_SHORT_SYMLINK_LENGTH) {
  6337. +       TRACE("ext2_remove_vnode(): Truncating\n");
  6338. +       status_t status = inode->Resize(transaction, 0);
  6339. +       if (status != B_OK)
  6340. +           return status;
  6341. +   }
  6342. +
  6343. +   TRACE("ext2_remove_vnode(): Removing from orphan list\n");
  6344. +   status_t status = volume->RemoveOrphan(transaction, inode->ID());
  6345. +   if (status != B_OK)
  6346. +       return status;
  6347. +
  6348. +   TRACE("ext2_remove_vnode(): Setting deletion time\n");
  6349. +   inode->Node().SetDeletionTime(real_time_clock());
  6350. +
  6351. +   status = inode->WriteBack(transaction);
  6352. +   if (status != B_OK)
  6353. +       return status;
  6354. +  
  6355. +   TRACE("ext2_remove_vnode(): Freeing inode\n");
  6356. +   status = volume->FreeInode(transaction, inode->ID(), inode->IsDirectory());
  6357. +
  6358. +   // TODO: When Transaction::Done() fails, do we have to re-add the vnode?
  6359. +   if (status == B_OK)
  6360. +       status = transaction.Done();
  6361. +
  6362. +   return status;
  6363. +}
  6364. +
  6365. +
  6366.  static bool
  6367.  ext2_can_page(fs_volume* _volume, fs_vnode* _node, void* _cookie)
  6368.  {
  6369. @@ -253,9 +310,85 @@
  6370.  
  6371.  
  6372.  static status_t
  6373. +ext2_write_pages(fs_volume* _volume, fs_vnode* _node, void* _cookie,
  6374. +   off_t pos, const iovec* vecs, size_t count, size_t* _numBytes)
  6375. +{
  6376. +   Volume* volume = (Volume*)_volume->private_volume;
  6377. +   Inode* inode = (Inode*)_node->private_node;
  6378. +
  6379. +   if (volume->IsReadOnly())
  6380. +       return B_READ_ONLY_DEVICE;
  6381. +
  6382. +   if (inode->FileCache() == NULL)
  6383. +       return B_BAD_VALUE;
  6384. +
  6385. +   rw_lock_read_lock(inode->Lock());
  6386. +
  6387. +   uint32 vecIndex = 0;
  6388. +   size_t vecOffset = 0;
  6389. +   size_t bytesLeft = *_numBytes;
  6390. +   status_t status;
  6391. +
  6392. +   while (true) {
  6393. +       file_io_vec fileVecs[8];
  6394. +       size_t fileVecCount = 8;
  6395. +
  6396. +       status = file_map_translate(inode->Map(), pos, bytesLeft, fileVecs,
  6397. +           &fileVecCount, 0);
  6398. +       if (status != B_OK && status != B_BUFFER_OVERFLOW)
  6399. +           break;
  6400. +
  6401. +       bool bufferOverflow = status == B_BUFFER_OVERFLOW;
  6402. +
  6403. +       size_t bytes = bytesLeft;
  6404. +       status = write_file_io_vec_pages(volume->Device(), fileVecs,
  6405. +           fileVecCount, vecs, count, &vecIndex, &vecOffset, &bytes);
  6406. +       if (status != B_OK || !bufferOverflow)
  6407. +           break;
  6408. +
  6409. +       pos += bytes;
  6410. +       bytesLeft -= bytes;
  6411. +   }
  6412. +
  6413. +   rw_lock_read_unlock(inode->Lock());
  6414. +
  6415. +   return status;
  6416. +}
  6417. +
  6418. +
  6419. +static status_t
  6420. +ext2_io(fs_volume* _volume, fs_vnode* _node, void* _cookie, io_request* request)
  6421. +{
  6422. +   Volume* volume = (Volume*)_volume->private_volume;
  6423. +   Inode* inode = (Inode*)_node->private_node;
  6424. +
  6425. +#ifndef EXT2_SHELL
  6426. +   if (io_request_is_write(request) && volume->IsReadOnly()) {
  6427. +       notify_io_request(request, B_READ_ONLY_DEVICE);
  6428. +       return B_READ_ONLY_DEVICE;
  6429. +   }
  6430. +#endif
  6431. +
  6432. +   if (inode->FileCache() == NULL) {
  6433. +#ifndef EXT2_SHELL
  6434. +       notify_io_request(request, B_BAD_VALUE);
  6435. +#endif
  6436. +       return B_BAD_VALUE;
  6437. +   }
  6438. +
  6439. +   // We lock the node here and will unlock it in the "finished" hook.
  6440. +   rw_lock_read_lock(inode->Lock());
  6441. +
  6442. +   return do_iterative_fd_io(volume->Device(), request,
  6443. +       iterative_io_get_vecs_hook, iterative_io_finished_hook, inode);
  6444. +}
  6445. +
  6446. +
  6447. +static status_t
  6448.  ext2_get_file_map(fs_volume* _volume, fs_vnode* _node, off_t offset,
  6449.     size_t size, struct file_io_vec* vecs, size_t* _count)
  6450.  {
  6451. +   TRACE("ext2_get_file_map()\n");
  6452.     Volume* volume = (Volume*)_volume->private_volume;
  6453.     Inode* inode = (Inode*)_node->private_node;
  6454.     size_t index = 0, max = *_count;
  6455. @@ -294,7 +427,7 @@
  6456.         if (size <= vecs[index - 1].length || offset >= inode->Size()) {
  6457.             // We're done!
  6458.             *_count = index;
  6459. -           TRACE("ext2_get_file_map for inode %ld\n", inode->ID());
  6460. +           TRACE("ext2_get_file_map for inode %ld\n", (long)inode->ID());
  6461.             return B_OK;
  6462.         }
  6463.     }
  6464. @@ -311,6 +444,8 @@
  6465.  ext2_lookup(fs_volume* _volume, fs_vnode* _directory, const char* name,
  6466.     ino_t* _vnodeID)
  6467.  {
  6468. +   TRACE("ext2_lookup: name address: %p\n", name);
  6469. +   TRACE("ext2_lookup: name: %s\n", name);
  6470.     Volume* volume = (Volume*)_volume->private_volume;
  6471.     Inode* directory = (Inode*)_directory->private_node;
  6472.  
  6473. @@ -328,23 +463,78 @@
  6474.    
  6475.     ObjectDeleter<DirectoryIterator> iteratorDeleter(iterator);
  6476.  
  6477. -   while (true) {
  6478. -       char buffer[B_FILE_NAME_LENGTH];
  6479. -       size_t length = sizeof(buffer);
  6480. -       status = iterator->GetNext(buffer, &length, _vnodeID);
  6481. -       if (status != B_OK)
  6482. -           return status;
  6483. -       TRACE("ext2_lookup() %s\n", buffer);
  6484. +   status = iterator->FindEntry(name, _vnodeID);
  6485. +   if (status != B_OK)
  6486. +       return status;
  6487. +  
  6488. +   return get_vnode(volume->FSVolume(), *_vnodeID, NULL);
  6489. +}
  6490.  
  6491. -       if (!strcmp(buffer, name))
  6492. -           break;
  6493. +
  6494. +static status_t
  6495. +ext2_ioctl(fs_volume* _volume, fs_vnode* _node, void* _cookie, uint32 cmd,
  6496. +   void* buffer, size_t bufferLength)
  6497. +{
  6498. +   TRACE("ioctl: %lu\n", cmd);
  6499. +
  6500. +   Volume* volume = (Volume*)_volume->private_volume;
  6501. +   switch (cmd) {
  6502. +       case 56742:
  6503. +       {
  6504. +           TRACE("ioctl: Test the block allocator\n");
  6505. +           // Test the block allocator
  6506. +           TRACE("ioctl: Creating transaction\n");
  6507. +           Transaction transaction(volume->GetJournal());
  6508. +           TRACE("ioctl: Creating cached block\n");
  6509. +           CachedBlock cached(volume);
  6510. +           uint32 blocksPerGroup = volume->BlocksPerGroup();
  6511. +           uint32 blockSize  = volume->BlockSize();
  6512. +           uint32 firstBlock = volume->FirstDataBlock();
  6513. +           uint32 start = 0;
  6514. +           uint32 group = 0;
  6515. +           uint32 length;
  6516. +
  6517. +           TRACE("ioctl: blocks per group: %lu, block size: %lu, "
  6518. +               "first block: %lu, start: %lu, group: %lu\n", blocksPerGroup,
  6519. +               blockSize, firstBlock, start, group);
  6520. +
  6521. +           while (volume->AllocateBlocks(transaction, 1, 2048, group, start,
  6522. +                   length) == B_OK) {
  6523. +               TRACE("ioctl: Allocated blocks in group %lu: %lu-%lu\n", group,
  6524. +                   start, start + length);
  6525. +               uint32 blockNum = start + group * blocksPerGroup - firstBlock;
  6526. +
  6527. +               for (uint32 i = 0; i < length; ++i) {
  6528. +                   uint8* block = cached.SetToWritable(transaction, blockNum);
  6529. +                   memset(block, 0, blockSize);
  6530. +                   blockNum++;
  6531. +               }
  6532. +
  6533. +               TRACE("ioctl: Blocks cleared\n");
  6534. +              
  6535. +               transaction.Done();
  6536. +               transaction.Start(volume->GetJournal());
  6537. +           }
  6538. +
  6539. +           TRACE("ioctl: Done\n");
  6540. +
  6541. +           return B_OK;
  6542. +       }
  6543.     }
  6544.  
  6545. -   return get_vnode(volume->FSVolume(), *_vnodeID, NULL);
  6546. +   return B_OK;
  6547.  }
  6548.  
  6549.  
  6550.  static status_t
  6551. +ext2_fsync(fs_volume* _volume, fs_vnode* _node)
  6552. +{
  6553. +   Inode* inode = (Inode*)_node->private_node;
  6554. +   return inode->Sync();
  6555. +}
  6556. +
  6557. +
  6558. +static status_t
  6559.  ext2_read_stat(fs_volume* _volume, fs_vnode* _node, struct stat* stat)
  6560.  {
  6561.     Inode* inode = (Inode*)_node->private_node;
  6562. @@ -371,9 +561,486 @@
  6563.  }
  6564.  
  6565.  
  6566. +status_t
  6567. +ext2_write_stat(fs_volume* _volume, fs_vnode* _node, const struct stat* stat,
  6568. +   uint32 mask)
  6569. +{
  6570. +   TRACE("ext2_write_stat\n");
  6571. +   Volume* volume = (Volume*)_volume->private_volume;
  6572. +
  6573. +   if (volume->IsReadOnly())
  6574. +       return B_READ_ONLY_DEVICE;
  6575. +
  6576. +   Inode* inode = (Inode*)_node->private_node;
  6577. +
  6578. +   status_t status = inode->CheckPermissions(W_OK);
  6579. +   if (status < B_OK)
  6580. +       return status;
  6581. +
  6582. +   TRACE("ext2_write_stat: Starting transaction\n");
  6583. +   Transaction transaction(volume->GetJournal());
  6584. +   inode->WriteLockInTransaction(transaction);
  6585. +
  6586. +   bool updateTime = false;
  6587. +
  6588. +   if ((mask & B_STAT_SIZE) != 0) {
  6589. +       if (inode->IsDirectory())
  6590. +           return B_IS_A_DIRECTORY;
  6591. +       if (!inode->IsFile())
  6592. +           return B_BAD_VALUE;
  6593. +
  6594. +       TRACE("ext2_write_stat: Old size: %ld, new size: %ld\n",
  6595. +           (long)inode->Size(), (long)stat->st_size);
  6596. +       if (inode->Size() != stat->st_size) {
  6597. +           off_t oldSize = inode->Size();
  6598. +
  6599. +           status = inode->Resize(transaction, stat->st_size);
  6600. +           if(status != B_OK)
  6601. +               return status;
  6602. +
  6603. +           if ((mask & B_STAT_SIZE_INSECURE) == 0) {
  6604. +               rw_lock_write_unlock(inode->Lock());
  6605. +               inode->FillGapWithZeros(oldSize, inode->Size());
  6606. +               rw_lock_write_lock(inode->Lock());
  6607. +           }
  6608. +
  6609. +           updateTime = true;
  6610. +       }
  6611. +   }
  6612. +
  6613. +   ext2_inode& node = inode->Node();
  6614. +
  6615. +   if ((mask & B_STAT_MODE) != 0) {
  6616. +       node.UpdateMode(stat->st_mode, S_IUMSK);
  6617. +       updateTime = true;
  6618. +   }
  6619. +
  6620. +   if ((mask & B_STAT_UID) != 0) {
  6621. +       node.SetUserID(stat->st_uid);
  6622. +       updateTime = true;
  6623. +   }
  6624. +   if ((mask & B_STAT_GID) != 0) {
  6625. +       node.SetGroupID(stat->st_gid);
  6626. +       updateTime = true;
  6627. +   }
  6628. +
  6629. +   if ((mask & B_STAT_MODIFICATION_TIME) != 0 || updateTime
  6630. +       || (mask & B_STAT_CHANGE_TIME) != 0) {
  6631. +       time_t newTime = 0;
  6632. +
  6633. +       if ((mask & B_STAT_MODIFICATION_TIME) != 0)
  6634. +           newTime = stat->st_mtim.tv_sec;
  6635. +
  6636. +       if ((mask & B_STAT_CHANGE_TIME) != 0)
  6637. +           newTime = newTime > stat->st_ctim.tv_sec ? newTime
  6638. +               : stat->st_ctim.tv_sec;
  6639. +
  6640. +       if (newTime == 0)
  6641. +           newTime = real_time_clock();
  6642. +
  6643. +       node.SetModificationTime(newTime);
  6644. +   }
  6645. +   if ((mask & B_STAT_CREATION_TIME) != 0)
  6646. +       node.SetCreationTime(stat->st_crtim.tv_sec);
  6647. +
  6648. +   status = inode->WriteBack(transaction);
  6649. +   if (status == B_OK)
  6650. +       status = transaction.Done();
  6651. +   if (status == B_OK)
  6652. +       notify_stat_changed(volume->ID(), inode->ID(), mask);
  6653. +
  6654. +   return status;
  6655. +}
  6656. +
  6657. +
  6658.  static status_t
  6659. +ext2_create(fs_volume* _volume, fs_vnode* _directory, const char* name,
  6660. +   int openMode, int mode, void** _cookie, ino_t* _vnodeID)
  6661. +{
  6662. +   Volume* volume = (Volume*)_volume->private_volume;
  6663. +   Inode* directory = (Inode*)_directory->private_node;
  6664. +
  6665. +   TRACE("ext2_create()\n");
  6666. +
  6667. +   if (volume->IsReadOnly())
  6668. +       return B_READ_ONLY_DEVICE;
  6669. +
  6670. +   if (!directory->IsDirectory())
  6671. +       return B_BAD_TYPE;
  6672. +
  6673. +   TRACE("ext2_create(): Creating cookie\n");
  6674. +
  6675. +   // Allocate cookie
  6676. +   file_cookie* cookie = new(std::nothrow) file_cookie;
  6677. +   if (cookie == NULL)
  6678. +       return B_NO_MEMORY;
  6679. +   ObjectDeleter<file_cookie> cookieDeleter(cookie);
  6680. +
  6681. +   cookie->open_mode = openMode;
  6682. +   cookie->last_size = 0;
  6683. +   cookie->last_notification = system_time();
  6684. +
  6685. +   TRACE("ext2_create(): Starting transaction\n");
  6686. +
  6687. +   Transaction transaction(volume->GetJournal());
  6688. +
  6689. +   TRACE("ext2_create(): Creating inode\n");
  6690. +
  6691. +   Inode* inode;
  6692. +   bool created;
  6693. +   status_t status = Inode::Create(transaction, directory, name,
  6694. +       S_FILE | (mode & S_IUMSK), openMode, EXT2_TYPE_FILE, &created, _vnodeID,
  6695. +       &inode, &gExt2VnodeOps);
  6696. +   if (status != B_OK)
  6697. +       return status;
  6698. +
  6699. +   if ((openMode & O_NOCACHE) != 0 && !inode->IsFileCacheDisabled()) {
  6700. +       status = inode->DisableFileCache();
  6701. +       if (status != B_OK)
  6702. +           return status;
  6703. +   }
  6704. +
  6705. +   entry_cache_add(volume->ID(), directory->ID(), name, *_vnodeID);
  6706. +
  6707. +   status == transaction.Done();
  6708. +   if (status != B_OK) {
  6709. +       entry_cache_remove(volume->ID(), directory->ID(), name);
  6710. +       return status;
  6711. +   }
  6712. +
  6713. +   *_cookie = cookie;
  6714. +   cookieDeleter.Detach();
  6715. +
  6716. +   if (created)
  6717. +       notify_entry_created(volume->ID(), directory->ID(), name, *_vnodeID);
  6718. +
  6719. +   return B_OK;
  6720. +}
  6721. +
  6722. +
  6723. +static status_t
  6724. +ext2_create_symlink(fs_volume* _volume, fs_vnode* _directory, const char* name,
  6725. +   const char* path, int mode)
  6726. +{
  6727. +   TRACE("ext2_create_symlink()\n");
  6728. +
  6729. +   Volume* volume = (Volume*)_volume->private_volume;
  6730. +   Inode* directory = (Inode*)_directory->private_node;
  6731. +
  6732. +   if (volume->IsReadOnly())
  6733. +       return B_READ_ONLY_DEVICE;
  6734. +
  6735. +   if (!directory->IsDirectory())
  6736. +       return B_BAD_TYPE;
  6737. +
  6738. +   status_t status = directory->CheckPermissions(W_OK);
  6739. +   if (status != B_OK)
  6740. +       return status;
  6741. +
  6742. +   TRACE("ext2_create_symlink(): Starting transaction\n");
  6743. +   Transaction transaction(volume->GetJournal());
  6744. +
  6745. +   Inode* link;
  6746. +   ino_t id;
  6747. +   status = Inode::Create(transaction, directory, name, S_SYMLINK | 0777,
  6748. +       0, (uint8)EXT2_TYPE_SYMLINK, NULL, &id, &link);
  6749. +   if (status < B_OK)
  6750. +       return status;
  6751. +
  6752. +   // TODO: We have to prepare the link before publishing?
  6753. +
  6754. +   size_t length = strlen(path);
  6755. +   TRACE("ext2_create_symlink(): Path (%s) length: %d\n", path, (int)length);
  6756. +   if (length < EXT2_SHORT_SYMLINK_LENGTH) {
  6757. +       strcpy(link->Node().symlink, path);
  6758. +       link->Node().SetSize((uint32)length);
  6759. +
  6760. +       TRACE("ext2_create_symlink(): Publishing vnode\n");
  6761. +       publish_vnode(volume->FSVolume(), id, link, &gExt2VnodeOps,
  6762. +           link->Mode(), 0);
  6763. +       put_vnode(volume->FSVolume(), id);
  6764. +   } else {
  6765. +       TRACE("ext2_create_symlink(): Publishing vnode\n");
  6766. +       publish_vnode(volume->FSVolume(), id, link, &gExt2VnodeOps,
  6767. +           link->Mode(), 0);
  6768. +       put_vnode(volume->FSVolume(), id);
  6769. +
  6770. +       if (link->IsFileCacheDisabled()) {
  6771. +           status = link->EnableFileCache();
  6772. +           if (status != B_OK)
  6773. +               return status;
  6774. +       }
  6775. +
  6776. +       size_t written = length;
  6777. +       status = link->WriteAt(transaction, 0, (const uint8*)path, &written);
  6778. +       if (status == B_OK && written != length)
  6779. +           status = B_IO_ERROR;
  6780. +   }
  6781. +
  6782. +   if (status == B_OK)
  6783. +       status = link->WriteBack(transaction);
  6784. +
  6785. +   entry_cache_add(volume->ID(), directory->ID(), name, id);
  6786. +
  6787. +   status = transaction.Done();
  6788. +   if (status != B_OK) {
  6789. +       entry_cache_remove(volume->ID(), directory->ID(), name);
  6790. +       return status;
  6791. +   }
  6792. +
  6793. +   notify_entry_created(volume->ID(), directory->ID(), name, id);
  6794. +
  6795. +   TRACE("ext2_create_symlink(): Done\n");
  6796. +
  6797. +   return status;
  6798. +}
  6799. +
  6800. +
  6801. +static status_t
  6802. +ext2_link(fs_volume* volume, fs_vnode* dir, const char* name, fs_vnode* node)
  6803. +{
  6804. +   // TODO
  6805. +  
  6806. +   return B_NOT_SUPPORTED;
  6807. +}
  6808. +
  6809. +
  6810. +static status_t
  6811. +ext2_unlink(fs_volume* _volume, fs_vnode* _directory, const char* name)
  6812. +{
  6813. +   TRACE("ext2_unlink()\n");
  6814. +   if (strcmp(name, ".") == 0 || strcmp(name, "..") == 0)
  6815. +       return B_NOT_ALLOWED;
  6816. +
  6817. +   Volume* volume = (Volume*)_volume->private_volume;
  6818. +   Inode* directory = (Inode*)_directory->private_node;
  6819. +
  6820. +   status_t status = directory->CheckPermissions(W_OK);
  6821. +   if (status != B_OK)
  6822. +       return status;
  6823. +
  6824. +   TRACE("ext2_unlink(): Starting transaction\n");
  6825. +   Transaction transaction(volume->GetJournal());
  6826. +
  6827. +   directory->WriteLockInTransaction(transaction);
  6828. +
  6829. +   TRACE("ext2_unlink(): Looking up for directory entry\n");
  6830. +   HTree htree(volume, directory);
  6831. +   DirectoryIterator* directoryIterator;
  6832. +
  6833. +   status = htree.Lookup(name, &directoryIterator);
  6834. +   if (status != B_OK)
  6835. +       return status;
  6836. +
  6837. +   ino_t id;
  6838. +   status = directoryIterator->FindEntry(name, &id);
  6839. +   if (status != B_OK)
  6840. +       return status;
  6841. +
  6842. +   Vnode vnode(volume, id);
  6843. +   Inode* inode;
  6844. +   status = vnode.Get(&inode);
  6845. +   if (status != B_OK)
  6846. +       return status;
  6847. +
  6848. +   inode->WriteLockInTransaction(transaction);
  6849. +
  6850. +   status = inode->Unlink(transaction);
  6851. +   if (status != B_OK)
  6852. +       return status;
  6853. +
  6854. +   status = directoryIterator->RemoveEntry(transaction);
  6855. +   if (status != B_OK)
  6856. +       return status;
  6857. +
  6858. +   entry_cache_remove(volume->ID(), directory->ID(), name);
  6859. +
  6860. +   status = transaction.Done();
  6861. +   if (status != B_OK)
  6862. +       entry_cache_add(volume->ID(), directory->ID(), name, id);
  6863. +   else
  6864. +       notify_entry_removed(volume->ID(), directory->ID(), name, id);
  6865. +
  6866. +   return status;
  6867. +}
  6868. +
  6869. +
  6870. +static status_t
  6871. +ext2_rename(fs_volume* _volume, fs_vnode* _oldDir, const char* oldName,
  6872. +   fs_vnode* _newDir, const char* newName)
  6873. +{
  6874. +   Volume* volume = (Volume*)_volume->private_volume;
  6875. +   Inode* oldDirectory = (Inode*)_oldDir->private_node;
  6876. +   Inode* newDirectory = (Inode*)_newDir->private_node;
  6877. +
  6878. +   if (oldDirectory == newDirectory && strcmp(oldName, newName) == 0)
  6879. +       return B_OK;
  6880. +
  6881. +   Transaction transaction(volume->GetJournal());
  6882. +
  6883. +   oldDirectory->WriteLockInTransaction(transaction);
  6884. +   if (oldDirectory != newDirectory)
  6885. +       newDirectory->WriteLockInTransaction(transaction);
  6886. +
  6887. +   status_t status = oldDirectory->CheckPermissions(W_OK);
  6888. +   if (status == B_OK)
  6889. +       status = newDirectory->CheckPermissions(W_OK);
  6890. +   if (status != B_OK)
  6891. +       return status;
  6892. +
  6893. +   HTree oldHTree(volume, oldDirectory);
  6894. +   DirectoryIterator* oldIterator;
  6895. +
  6896. +   status = oldHTree.Lookup(oldName, &oldIterator);
  6897. +   if (status != B_OK)
  6898. +       return status;
  6899. +
  6900. +   ObjectDeleter<DirectoryIterator> oldIteratorDeleter(oldIterator);
  6901. +
  6902. +   ino_t oldID;
  6903. +   status = oldIterator->FindEntry(oldName, &oldID);
  6904. +   if (status != B_OK)
  6905. +       return status;
  6906. +
  6907. +   if (oldDirectory != newDirectory) {
  6908. +       CachedBlock cached(volume);
  6909. +
  6910. +       ino_t newDirID = newDirectory->ID();
  6911. +       ino_t parentID = oldDirectory->ID();
  6912. +
  6913. +       do {
  6914. +           Vnode vnode(volume, parentID);
  6915. +           Inode* parent;
  6916. +
  6917. +           status = vnode.Get(&parent);
  6918. +           if (status != B_OK)
  6919. +               return B_IO_ERROR;
  6920. +
  6921. +           uint32 blockNum;
  6922. +           status = parent->FindBlock(0, blockNum);
  6923. +           if (status != B_OK)
  6924. +               return status;
  6925. +
  6926. +           const HTreeRoot* data = (const HTreeRoot*)cached.SetTo(blockNum);
  6927. +           parentID = data->dotdot.InodeID();
  6928. +       } while (parentID != newDirID && parentID != EXT2_ROOT_NODE);
  6929. +
  6930. +       if (parentID != EXT2_ROOT_NODE)
  6931. +           return B_BAD_VALUE;
  6932. +   }
  6933. +
  6934. +   HTree newHTree(volume, newDirectory);
  6935. +   DirectoryIterator* newIterator;
  6936. +
  6937. +   status = newHTree.Lookup(newName, &newIterator);
  6938. +   if (status != B_OK)
  6939. +       return status;
  6940. +
  6941. +   ObjectDeleter<DirectoryIterator> newIteratorDeleter(newIterator);
  6942. +
  6943. +   Vnode vnode(volume, oldID);
  6944. +   Inode* inode;
  6945. +
  6946. +   status = vnode.Get(&inode);
  6947. +   if (status != B_OK)
  6948. +       return status;
  6949. +
  6950. +   uint8 fileType;
  6951. +
  6952. +   // TODO: Support all file types?
  6953. +   if (inode->IsDirectory())
  6954. +       fileType = EXT2_TYPE_DIRECTORY;
  6955. +   else if (inode->IsSymLink())
  6956. +       fileType = EXT2_TYPE_SYMLINK;
  6957. +   else
  6958. +       fileType = EXT2_TYPE_FILE;
  6959. +
  6960. +   // Add entry in destination directory
  6961. +   ino_t existentID;
  6962. +   status = newIterator->FindEntry(newName, &existentID);
  6963. +   if (status == B_OK) {
  6964. +       if (existentID == oldID) {
  6965. +           // Remove entry in oldID
  6966. +           // return inode->Unlink();
  6967. +           return B_BAD_VALUE;
  6968. +       }
  6969. +
  6970. +       Vnode vnodeExistent(volume, existentID);
  6971. +       Inode* existent;
  6972. +
  6973. +       if (vnodeExistent.Get(&existent) != B_OK)
  6974. +           return B_NAME_IN_USE;
  6975. +
  6976. +       if (existent->IsDirectory() != inode->IsDirectory()) {
  6977. +           return existent->IsDirectory() ? B_IS_A_DIRECTORY
  6978. +               : B_NOT_A_DIRECTORY;
  6979. +       }
  6980. +
  6981. +       // TODO: Perhaps we have to revert this in case of error?
  6982. +       status = newIterator->ChangeEntry(transaction, oldID, fileType);
  6983. +       if (status != B_OK)
  6984. +           return status;
  6985. +
  6986. +       notify_entry_removed(volume->ID(), newDirectory->ID(), newName,
  6987. +           existentID);
  6988. +   } else if (status == B_ENTRY_NOT_FOUND) {
  6989. +       newIterator->Restart();
  6990. +
  6991. +       status = newIterator->AddEntry(transaction, newName, strlen(newName),
  6992. +           oldID, fileType);
  6993. +       if (status != B_OK)
  6994. +           return status;
  6995. +   } else
  6996. +       return status;
  6997. +  
  6998. +   // Remove entry from source folder
  6999. +   status = oldIterator->RemoveEntry(transaction);
  7000. +   if (status != B_OK)
  7001. +       return status;
  7002. +
  7003. +   inode->WriteLockInTransaction(transaction);
  7004. +
  7005. +   if (oldDirectory != newDirectory && inode->IsDirectory()) {
  7006. +       DirectoryIterator inodeIterator(inode);
  7007. +
  7008. +       status = inodeIterator.FindEntry("..");
  7009. +       if (status == B_ENTRY_NOT_FOUND) {
  7010. +           TRACE("Corrupt file sytem. Missing \"..\" in directory %ld\n",
  7011. +               inode->ID());
  7012. +           return B_BAD_DATA;
  7013. +       } else if (status != B_OK)
  7014. +           return status;
  7015. +
  7016. +       inodeIterator.ChangeEntry(transaction, newDirectory->ID(),
  7017. +           (uint8)EXT2_TYPE_DIRECTORY);
  7018. +   }
  7019. +
  7020. +   status = inode->WriteBack(transaction);
  7021. +   if (status != B_OK)
  7022. +       return status;
  7023. +
  7024. +   entry_cache_remove(volume->ID(), oldDirectory->ID(), oldName);
  7025. +   entry_cache_add(volume->ID(), newDirectory->ID(), newName, oldID);
  7026. +
  7027. +   status = transaction.Done();
  7028. +   if (status != B_OK) {
  7029. +       entry_cache_remove(volume->ID(), oldDirectory->ID(), newName);
  7030. +       entry_cache_add(volume->ID(), newDirectory->ID(), oldName, oldID);
  7031. +  
  7032. +       return status;
  7033. +   }
  7034. +
  7035. +   notify_entry_moved(volume->ID(), oldDirectory->ID(), oldName,
  7036. +       newDirectory->ID(), newName, oldID);
  7037. +
  7038. +   return B_OK;
  7039. +}
  7040. +
  7041. +
  7042. +static status_t
  7043.  ext2_open(fs_volume* _volume, fs_vnode* _node, int openMode, void** _cookie)
  7044.  {
  7045. +   Volume* volume = (Volume*)_volume->private_volume;
  7046.     Inode* inode = (Inode*)_node->private_node;
  7047.  
  7048.     // opening a directory read-only is allowed, although you can't read
  7049. @@ -381,30 +1048,119 @@
  7050.     if (inode->IsDirectory() && (openMode & O_RWMASK) != 0)
  7051.         return B_IS_A_DIRECTORY;
  7052.  
  7053. -   if ((openMode & O_TRUNC) != 0)
  7054. -       return B_READ_ONLY_DEVICE;
  7055. +   status_t status =  inode->CheckPermissions(open_mode_to_access(openMode)
  7056. +       | (openMode & O_TRUNC ? W_OK : 0));
  7057. +   if (status != B_OK)
  7058. +       return status;
  7059.  
  7060. -   return inode->CheckPermissions(open_mode_to_access(openMode)
  7061. -       | (openMode & O_TRUNC ? W_OK : 0));
  7062. +   // Prepare the cookie
  7063. +   file_cookie* cookie = new(std::nothrow) file_cookie;
  7064. +   if (cookie == NULL)
  7065. +       return B_NO_MEMORY;
  7066. +   ObjectDeleter<file_cookie> cookieDeleter(cookie);
  7067. +
  7068. +   cookie->open_mode = openMode & EXT2_OPEN_MODE_USER_MASK;
  7069. +   cookie->last_size = inode->Size();
  7070. +   cookie->last_notification = system_time();
  7071. +
  7072. +   if ((openMode & O_NOCACHE) != 0) {
  7073. +       status = inode->DisableFileCache();
  7074. +       if (status != B_OK)
  7075. +           return status;
  7076. +   }
  7077. +
  7078. +   // Should we truncate the file?
  7079. +   if ((openMode & O_TRUNC) != 0) {
  7080. +       if ((openMode & O_RWMASK) == O_RDONLY)
  7081. +           return B_NOT_ALLOWED;
  7082. +
  7083. +       Transaction transaction(volume->GetJournal());
  7084. +       inode->WriteLockInTransaction(transaction);
  7085. +
  7086. +       status_t status = inode->Resize(transaction, 0);
  7087. +       if (status == B_OK)
  7088. +           status = inode->WriteBack(transaction);
  7089. +       if (status == B_OK)
  7090. +           status = transaction.Done();
  7091. +       if (status != B_OK)
  7092. +           return status;
  7093. +
  7094. +       // TODO: No need to notify file size changed?
  7095. +   }
  7096. +
  7097. +   cookieDeleter.Detach();
  7098. +   *_cookie = cookie;
  7099. +
  7100. +   return B_OK;
  7101.  }
  7102.  
  7103.  
  7104.  static status_t
  7105. -ext2_read(fs_volume *_volume, fs_vnode *_node, void *_cookie, off_t pos,
  7106. -   void *buffer, size_t *_length)
  7107. +ext2_read(fs_volume* _volume, fs_vnode* _node, void* _cookie, off_t pos,
  7108. +   void* buffer, size_t* _length)
  7109.  {
  7110. -   Inode *inode = (Inode *)_node->private_node;
  7111. +   Inode* inode = (Inode*)_node->private_node;
  7112.  
  7113.     if (!inode->IsFile()) {
  7114.         *_length = 0;
  7115.         return inode->IsDirectory() ? B_IS_A_DIRECTORY : B_BAD_VALUE;
  7116.     }
  7117.  
  7118. -   return inode->ReadAt(pos, (uint8 *)buffer, _length);
  7119. +   return inode->ReadAt(pos, (uint8*)buffer, _length);
  7120.  }
  7121.  
  7122.  
  7123.  static status_t
  7124. +ext2_write(fs_volume* _volume, fs_vnode* _node, void* _cookie, off_t pos,
  7125. +   const void* buffer, size_t* _length)
  7126. +{
  7127. +   TRACE("ext2_write()\n");
  7128. +   Volume* volume = (Volume*)_volume->private_volume;
  7129. +   Inode* inode = (Inode*)_node->private_node;
  7130. +
  7131. +   if (volume->IsReadOnly())
  7132. +       return B_READ_ONLY_DEVICE;
  7133. +
  7134. +   if (inode->IsDirectory()) {
  7135. +       *_length = 0;
  7136. +       return B_IS_A_DIRECTORY;
  7137. +   }
  7138. +
  7139. +   TRACE("ext2_write(): Preparing cookie\n");
  7140. +
  7141. +   file_cookie* cookie = (file_cookie*)_cookie;
  7142. +
  7143. +   if ((cookie->open_mode & O_APPEND) != 0)
  7144. +       pos = inode->Size();
  7145. +
  7146. +   TRACE("ext2_write(): Creating transaction\n");
  7147. +   Transaction transaction;
  7148. +
  7149. +   status_t status = inode->WriteAt(transaction, pos, (const uint8*)buffer,
  7150. +       _length);
  7151. +   if (status == B_OK)
  7152. +       status = transaction.Done();
  7153. +   if (status == B_OK) {
  7154. +       TRACE("ext2_write(): Finalizing\n");
  7155. +       ReadLocker lock(*inode->Lock());
  7156. +
  7157. +       if (cookie->last_size != inode->Size()
  7158. +           && system_time() > cookie->last_notification
  7159. +               + INODE_NOTIFICATION_INTERVAL) {
  7160. +           notify_stat_changed(volume->ID(), inode->ID(),
  7161. +               B_STAT_MODIFICATION_TIME | B_STAT_SIZE | B_STAT_INTERIM_UPDATE);
  7162. +           cookie->last_size = inode->Size();
  7163. +           cookie->last_notification = system_time();
  7164. +       }
  7165. +   }
  7166. +
  7167. +   TRACE("ext2_write(): Done\n");
  7168. +
  7169. +   return status;
  7170. +}
  7171. +
  7172. +
  7173. +static status_t
  7174.  ext2_close(fs_volume *_volume, fs_vnode *_node, void *_cookie)
  7175.  {
  7176.     return B_OK;
  7177. @@ -412,8 +1168,16 @@
  7178.  
  7179.  
  7180.  static status_t
  7181. -ext2_free_cookie(fs_volume* _volume, fs_vnode* _node, void* cookie)
  7182. +ext2_free_cookie(fs_volume* _volume, fs_vnode* _node, void* _cookie)
  7183.  {
  7184. +   file_cookie* cookie = (file_cookie*)_cookie;
  7185. +   Volume* volume = (Volume*)_volume->private_volume;
  7186. +   Inode* inode = (Inode*)_node->private_node;
  7187. +
  7188. +   if (inode->Size() != cookie->last_size)
  7189. +       notify_stat_changed(volume->ID(), inode->ID(), B_STAT_SIZE);
  7190. +
  7191. +   delete cookie;
  7192.     return B_OK;
  7193.  }
  7194.  
  7195. @@ -450,9 +1214,118 @@
  7196.  
  7197.  
  7198.  static status_t
  7199. -ext2_open_dir(fs_volume *_volume, fs_vnode *_node, void **_cookie)
  7200. +ext2_create_dir(fs_volume* _volume, fs_vnode* _directory, const char* name,
  7201. +   int mode)
  7202. +{
  7203. +   TRACE("ext2_create_dir()\n");
  7204. +   Volume* volume = (Volume*)_volume->private_volume;
  7205. +   Inode* directory = (Inode*)_directory->private_node;
  7206. +
  7207. +   if (volume->IsReadOnly())
  7208. +       return B_READ_ONLY_DEVICE;
  7209. +
  7210. +   if (!directory->IsDirectory())
  7211. +       return B_BAD_TYPE;
  7212. +
  7213. +   status_t status = directory->CheckPermissions(W_OK);
  7214. +   if (status != B_OK)
  7215. +       return status;
  7216. +
  7217. +   TRACE("ext2_create_dir(): Starting transaction\n");
  7218. +   Transaction transaction(volume->GetJournal());
  7219. +
  7220. +   ino_t id;
  7221. +   status = Inode::Create(transaction, directory, name,
  7222. +       S_DIRECTORY | (mode & S_IUMSK), 0, EXT2_TYPE_DIRECTORY, NULL, &id);
  7223. +   if (status != B_OK)
  7224. +       return status;
  7225. +
  7226. +   put_vnode(volume->FSVolume(), id);
  7227. +
  7228. +   entry_cache_add(volume->ID(), directory->ID(), name, id);
  7229. +
  7230. +   status = transaction.Done();
  7231. +   if (status != B_OK) {
  7232. +       entry_cache_remove(volume->ID(), directory->ID(), name);
  7233. +       return status;
  7234. +   }
  7235. +
  7236. +   notify_entry_created(volume->ID(), directory->ID(), name, id);
  7237. +
  7238. +   TRACE("ext2_create_dir(): Done\n");
  7239. +
  7240. +   return B_OK;
  7241. +}
  7242. +
  7243. +
  7244. +static status_t
  7245. +ext2_remove_dir(fs_volume* _volume, fs_vnode* _directory, const char* name)
  7246.  {
  7247. -   Inode *inode = (Inode *)_node->private_node;
  7248. +   TRACE("ext2_remove_dir()\n");
  7249. +
  7250. +   Volume* volume = (Volume*)_volume->private_volume;
  7251. +   Inode* directory = (Inode*)_directory->private_node;
  7252. +
  7253. +   status_t status = directory->CheckPermissions(W_OK);
  7254. +   if (status != B_OK)
  7255. +       return status;
  7256. +
  7257. +   TRACE("ext2_remove_dir(): Starting transaction\n");
  7258. +   Transaction transaction(volume->GetJournal());
  7259. +
  7260. +   directory->WriteLockInTransaction(transaction);
  7261. +
  7262. +   TRACE("ext2_remove_dir(): Looking up for directory entry\n");
  7263. +   HTree htree(volume, directory);
  7264. +   DirectoryIterator* directoryIterator;
  7265. +
  7266. +   status = htree.Lookup(name, &directoryIterator);
  7267. +   if (status != B_OK)
  7268. +       return status;
  7269. +
  7270. +   ino_t id;
  7271. +   status = directoryIterator->FindEntry(name, &id);
  7272. +   if (status != B_OK)
  7273. +       return status;
  7274. +
  7275. +   Vnode vnode(volume, id);
  7276. +   Inode* inode;
  7277. +   status = vnode.Get(&inode);
  7278. +   if (status != B_OK)
  7279. +       return status;
  7280. +
  7281. +   inode->WriteLockInTransaction(transaction);
  7282. +
  7283. +   status = inode->Unlink(transaction);
  7284. +   if (status != B_OK)
  7285. +       return status;
  7286. +
  7287. +   status = directory->Unlink(transaction);
  7288. +   if (status != B_OK)
  7289. +       return status;
  7290. +
  7291. +   status = directoryIterator->RemoveEntry(transaction);
  7292. +   if (status != B_OK)
  7293. +       return status;
  7294. +
  7295. +   entry_cache_remove(volume->ID(), directory->ID(), name);
  7296. +   entry_cache_remove(volume->ID(), id, "..");
  7297. +
  7298. +   status = transaction.Done();
  7299. +   if (status != B_OK) {
  7300. +       entry_cache_add(volume->ID(), directory->ID(), name, id);
  7301. +       entry_cache_add(volume->ID(), id, "..", id);
  7302. +   } else
  7303. +       notify_entry_removed(volume->ID(), directory->ID(), name, id);
  7304. +
  7305. +   return status;
  7306. +}
  7307. +
  7308. +
  7309. +static status_t
  7310. +ext2_open_dir(fs_volume* _volume, fs_vnode* _node, void** _cookie)
  7311. +{
  7312. +   Inode* inode = (Inode*)_node->private_node;
  7313.     status_t status = inode->CheckPermissions(R_OK);
  7314.     if (status < B_OK)
  7315.         return status;
  7316. @@ -477,13 +1350,17 @@
  7317.  
  7318.     size_t length = bufferSize;
  7319.     ino_t id;
  7320. -   status_t status = iterator->GetNext(dirent->d_name, &length, &id);
  7321. +   status_t status = iterator->Get(dirent->d_name, &length, &id);
  7322.     if (status == B_ENTRY_NOT_FOUND) {
  7323.         *_num = 0;
  7324.         return B_OK;
  7325.     } else if (status != B_OK)
  7326.         return status;
  7327.  
  7328. +   status = iterator->Next();
  7329. +   if (status != B_OK && status != B_ENTRY_NOT_FOUND)
  7330. +       return status;
  7331. +
  7332.     Volume* volume = (Volume*)_volume->private_volume;
  7333.  
  7334.     dirent->d_dev = volume->ID();
  7335. @@ -513,7 +1390,7 @@
  7336.  static status_t
  7337.  ext2_free_dir_cookie(fs_volume *_volume, fs_vnode *_node, void *_cookie)
  7338.  {
  7339. -   delete (DirectoryIterator *)_cookie;
  7340. +   delete (DirectoryIterator*)_cookie;
  7341.     return B_OK;
  7342.  }
  7343.  
  7344. @@ -736,46 +1613,46 @@
  7345.     &ext2_lookup,
  7346.     NULL,
  7347.     &ext2_put_vnode,
  7348. -   NULL,
  7349. +   &ext2_remove_vnode,
  7350.  
  7351.     /* VM file access */
  7352.     &ext2_can_page,
  7353.     &ext2_read_pages,
  7354. -   NULL,
  7355. +   &ext2_write_pages,
  7356.  
  7357.     NULL,   // io()
  7358.     NULL,   // cancel_io()
  7359.  
  7360.     &ext2_get_file_map,
  7361.  
  7362. +   &ext2_ioctl,
  7363.     NULL,
  7364. -   NULL,
  7365.     NULL,   // fs_select
  7366.     NULL,   // fs_deselect
  7367.     NULL,
  7368.  
  7369.     &ext2_read_link,
  7370. -   NULL,
  7371. +   &ext2_create_symlink,
  7372.  
  7373.     NULL,
  7374. -   NULL,
  7375. -   NULL,
  7376. +   &ext2_unlink,
  7377. +   &ext2_rename,
  7378.  
  7379.     &ext2_access,
  7380.     &ext2_read_stat,
  7381. -   NULL,
  7382. +   &ext2_write_stat,
  7383.  
  7384.     /* file operations */
  7385. -   NULL,
  7386. +   &ext2_create,
  7387.     &ext2_open,
  7388.     &ext2_close,
  7389.     &ext2_free_cookie,
  7390.     &ext2_read,
  7391. -   NULL,
  7392. +   &ext2_write,
  7393.  
  7394.     /* directory operations */
  7395. -   NULL,
  7396. -   NULL,
  7397. +   &ext2_create_dir,
  7398. +   &ext2_remove_dir,
  7399.     &ext2_open_dir,
  7400.     &ext2_close_dir,
  7401.     &ext2_free_dir_cookie,
  7402. Index: src/add-ons/kernel/file_systems/ext2/InodeAllocator.h
  7403. ===================================================================
  7404. --- src/add-ons/kernel/file_systems/ext2/InodeAllocator.h   (revision 0)
  7405. +++ src/add-ons/kernel/file_systems/ext2/InodeAllocator.h   (revision 0)
  7406. @@ -0,0 +1,45 @@
  7407. +/*
  7408. + * Copyright 2001-2010, Haiku Inc. All rights reserved.
  7409. + * This file may be used under the terms of the MIT License.
  7410. + *
  7411. + * Authors:
  7412. + *     Janito V. Ferreira Filho
  7413. + */
  7414. +#ifndef INODEALLOCATOR_H
  7415. +#define INODEALLOCATOR_H
  7416. +
  7417. +#include <lock.h>
  7418. +
  7419. +#include "Transaction.h"
  7420. +
  7421. +
  7422. +class Inode;
  7423. +class Volume;
  7424. +
  7425. +
  7426. +class InodeAllocator {
  7427. +public:
  7428. +                       InodeAllocator(Volume* volume);
  7429. +   virtual             ~InodeAllocator();
  7430. +
  7431. +   virtual status_t    New(Transaction& transaction, Inode* parent,
  7432. +                           int32 mode, ino_t& id);
  7433. +   virtual status_t    Free(Transaction& transaction, ino_t id,
  7434. +                           bool isDirectory);
  7435. +
  7436. +private:
  7437. +           status_t    _Allocate(Transaction& transaction,
  7438. +                           uint32 prefferedBlockGroup, bool isDirectory,
  7439. +                           ino_t& id);
  7440. +           status_t    _MarkInBitmap(Transaction& transaction,
  7441. +                           uint32 bitmapBlock, uint32 blockGroup,
  7442. +                           uint32 numInodes, ino_t& id);
  7443. +           status_t    _UnmarkInBitmap(Transaction& transaction,
  7444. +                           uint32 bitmapBlock, uint32 numInodes, ino_t id);
  7445. +
  7446. +
  7447. +           Volume*     fVolume;
  7448. +           mutex       fLock;
  7449. +};
  7450. +
  7451. +#endif // INODEALLOCATOR_H
  7452.  
  7453. Property changes on: src/add-ons/kernel/file_systems/ext2/InodeAllocator.h
  7454. ___________________________________________________________________
  7455. Added: svn:executable
  7456.    + *
  7457.  
  7458. Index: src/add-ons/kernel/file_systems/ext2/NoJournal.cpp
  7459. ===================================================================
  7460. --- src/add-ons/kernel/file_systems/ext2/NoJournal.cpp  (revision 0)
  7461. +++ src/add-ons/kernel/file_systems/ext2/NoJournal.cpp  (revision 0)
  7462. @@ -0,0 +1,100 @@
  7463. +/*
  7464. + * Copyright 2001-2010, Haiku Inc. All rights reserved.
  7465. + * This file may be used under the terms of the MIT License.
  7466. + *
  7467. + * Authors:
  7468. + *     Janito V. Ferreira Filho
  7469. + */
  7470. +
  7471. +#include "NoJournal.h"
  7472. +
  7473. +#include <string.h>
  7474. +
  7475. +#include <fs_cache.h>
  7476. +
  7477. +
  7478. +//#define TRACE_EXT2
  7479. +#ifdef TRACE_EXT2
  7480. +#  define TRACE(x...) dprintf("\33[34mext2:\33[0m " x)
  7481. +#else
  7482. +#  define TRACE(x...) ;
  7483. +#endif
  7484. +
  7485. +
  7486. +NoJournal::NoJournal(Volume* volume)
  7487. +   :
  7488. +   Journal()
  7489. +{
  7490. +   fFilesystemVolume = volume;
  7491. +   fFilesystemBlockCache = volume->BlockCache();
  7492. +   fJournalVolume = volume;
  7493. +   fHasSubTransaction = false;
  7494. +   fSeparateSubTransactions = false;
  7495. +}
  7496. +
  7497. +
  7498. +NoJournal::~NoJournal()
  7499. +{
  7500. +}
  7501. +
  7502. +
  7503. +status_t
  7504. +NoJournal::InitCheck()
  7505. +{
  7506. +   return B_OK;
  7507. +}
  7508. +
  7509. +
  7510. +status_t
  7511. +NoJournal::Recover()
  7512. +{
  7513. +   return B_OK;
  7514. +}
  7515. +
  7516. +
  7517. +status_t
  7518. +NoJournal::StartLog()
  7519. +{
  7520. +   return B_OK;
  7521. +}
  7522. +
  7523. +
  7524. +status_t
  7525. +NoJournal::Lock(Transaction* owner, bool separateSubTransactions)
  7526. +{
  7527. +   status_t status = block_cache_sync(fFilesystemBlockCache);
  7528. +   TRACE("NoJournal::Lock(): block_cache_sync: %s\n", strerror(status));
  7529. +  
  7530. +   if (status == B_OK)
  7531. +       status = Journal::Lock(owner, separateSubTransactions);
  7532. +  
  7533. +   return status;
  7534. +}
  7535. +
  7536. +
  7537. +status_t
  7538. +NoJournal::Unlock(Transaction* owner, bool success)
  7539. +{
  7540. +   TRACE("NoJournal::Unlock\n");
  7541. +   return Journal::Unlock(owner, success);
  7542. +}
  7543. +
  7544. +
  7545. +status_t
  7546. +NoJournal::_WriteTransactionToLog()
  7547. +{
  7548. +   TRACE("NoJournal::_WriteTransactionToLog(): Ending transaction %ld\n",
  7549. +       fTransactionID);
  7550. +
  7551. +   fTransactionID = cache_end_transaction(fFilesystemBlockCache,
  7552. +       fTransactionID, _TransactionWritten, NULL);
  7553. +  
  7554. +   return B_OK;
  7555. +}
  7556. +
  7557. +
  7558. +/*static*/ void
  7559. +NoJournal::_TransactionWritten(int32 transactionID, int32 event, void* param)
  7560. +{
  7561. +   TRACE("Transaction %ld checkpointed\n", transactionID);
  7562. +}
  7563. Index: src/add-ons/kernel/file_systems/ext2/HTree.cpp
  7564. ===================================================================
  7565. --- src/add-ons/kernel/file_systems/ext2/HTree.cpp  (revision 38119)
  7566. +++ src/add-ons/kernel/file_systems/ext2/HTree.cpp  (working copy)
  7567. @@ -7,6 +7,7 @@
  7568.   */
  7569.  
  7570.  
  7571. +#include "CachedBlock.h"
  7572.  #include "HTree.h"
  7573.  
  7574.  #include <new>
  7575. @@ -17,6 +18,8 @@
  7576.  #include "Volume.h"
  7577.  
  7578.  
  7579. +//#define COLLISION_TEST
  7580. +
  7581.  //#define TRACE_EXT2
  7582.  #ifdef TRACE_EXT2
  7583.  #  define TRACE(x...) dprintf("\33[34mext2:\33[0m " x)
  7584. @@ -75,90 +78,119 @@
  7585.  
  7586.  HTree::~HTree()
  7587.  {
  7588. +   delete fRootEntry;
  7589.  }
  7590.  
  7591.  
  7592.  status_t
  7593. +HTree::PrepareForHash()
  7594. +{
  7595. +   uint32 blockNum;
  7596. +   status_t status = fDirectory->FindBlock(0, blockNum);
  7597. +   if (status != B_OK)
  7598. +       return status;
  7599. +
  7600. +   CachedBlock cached(fDirectory->GetVolume());
  7601. +   const uint8* block = cached.SetTo(blockNum);
  7602. +
  7603. +   HTreeRoot* root = (HTreeRoot*)block;
  7604. +
  7605. +   if (root == NULL)
  7606. +       return B_IO_ERROR;
  7607. +   if (!root->IsValid())
  7608. +       return B_BAD_DATA;
  7609. +
  7610. +   fHashVersion = root->hash_version;
  7611. +
  7612. +   return B_OK;
  7613. +}
  7614. +
  7615. +
  7616. +status_t
  7617.  HTree::Lookup(const char* name, DirectoryIterator** iterator)
  7618.  {
  7619. +   TRACE("HTree::Lookup()\n");
  7620.     if (!fIndexed || (name[0] == '.'
  7621.         && (name[1] == '\0' || (name[1] == '.' && name[2] == '0')))) {
  7622.         // No HTree support or looking for trivial directories
  7623. -       // TODO: Does these directories get hashed?
  7624. -       *iterator = new(std::nothrow) DirectoryIterator(fDirectory);
  7625. -      
  7626. -       if (*iterator == NULL)
  7627. -           return B_NO_MEMORY;
  7628. -       return B_OK;
  7629. +       return _FallbackToLinearIteration(iterator);
  7630.     }
  7631.    
  7632. -   HTreeRoot root;
  7633. -   size_t length = sizeof(root);
  7634. +   uint32 blockNum;
  7635. +   status_t status = fDirectory->FindBlock(0, blockNum);
  7636. +   if (status != B_OK)
  7637. +       return _FallbackToLinearIteration(iterator);
  7638. +
  7639. +   CachedBlock cached(fDirectory->GetVolume());
  7640. +   const uint8* block = cached.SetTo(blockNum);
  7641. +
  7642. +   HTreeRoot* root = (HTreeRoot*)block;
  7643.    
  7644. -   status_t status = fDirectory->ReadAt(0, (uint8*)&root, &length);
  7645. -   if (status < B_OK)
  7646. -       return status;
  7647. +   if (root == NULL || !root->IsValid())
  7648. +       return _FallbackToLinearIteration(iterator);
  7649. +
  7650. +   fHashVersion = root->hash_version;
  7651.    
  7652. -   if (length != sizeof(root) || !root.IsValid()) {
  7653. -       // Fallback to linear search
  7654. -       *iterator = new(std::nothrow) DirectoryIterator(fDirectory);
  7655. -       if (*iterator == NULL)
  7656. -           return B_NO_MEMORY;
  7657. -      
  7658. -       return B_OK;
  7659. -   }
  7660. +   size_t _nameLength = strlen(name);
  7661. +   uint8 nameLength = _nameLength >= 256 ? 255 : (uint8)_nameLength;
  7662. +
  7663. +   uint32 hash = Hash(name, nameLength);
  7664.    
  7665. -   uint32 hash = _Hash(name, root.hash_version);
  7666. -  
  7667. -   off_t start = (off_t)root.root_info_length
  7668. +   off_t start = (off_t)root->root_info_length
  7669.         + 2 * (sizeof(HTreeFakeDirEntry) + 4);
  7670.  
  7671. +   delete fRootEntry;
  7672. +
  7673.     fRootEntry = new(std::nothrow) HTreeEntryIterator(start, fDirectory);
  7674.     if (fRootEntry == NULL)
  7675.         return B_NO_MEMORY;
  7676.    
  7677. -   fRootDeleter.SetTo(fRootEntry);
  7678.     status = fRootEntry->Init();
  7679.     if (status != B_OK)
  7680.         return status;
  7681.    
  7682. -   return fRootEntry->Lookup(hash, (uint32)root.indirection_levels, iterator);
  7683. +   return fRootEntry->Lookup(hash, (uint32)root->indirection_levels, iterator);
  7684.  }
  7685.  
  7686.  
  7687.  uint32
  7688. -HTree::_Hash(const char* name, uint8 version)
  7689. +HTree::Hash(const char* name, uint8 length)
  7690.  {
  7691.     uint32 hash;
  7692.    
  7693. -   switch (version) {
  7694. +#ifndef COLLISION_TEST
  7695. +   switch (fHashVersion) {
  7696.         case HTREE_HASH_LEGACY:
  7697. -           hash = _HashLegacy(name);
  7698. +           hash = _HashLegacy(name, length);
  7699.             break;
  7700.         case HTREE_HASH_HALF_MD4:
  7701. -           hash = _HashHalfMD4(name);
  7702. +           hash = _HashHalfMD4(name, length);
  7703.             break;
  7704.         case HTREE_HASH_TEA:
  7705. -           hash = _HashTEA(name);
  7706. +           hash = _HashTEA(name, length);
  7707.             break;
  7708.         default:
  7709.             panic("Hash verification succeeded but then failed?");
  7710.             hash = 0;
  7711.     };
  7712. +#else
  7713. +   hash = 0;
  7714. +#endif
  7715.  
  7716. -   TRACE("Filename hash: %u\n", hash);
  7717. +   TRACE("HTree::_Hash(): filename hash 0x%lX\n", hash);
  7718.    
  7719.     return hash & ~1;
  7720.  }
  7721.  
  7722.  
  7723.  uint32
  7724. -HTree::_HashLegacy(const char* name)
  7725. +HTree::_HashLegacy(const char* name, uint8 length)
  7726.  {
  7727. +   TRACE("HTree::_HashLegacy()\n");
  7728.     uint32 hash = 0x12a3fe2d;
  7729.     uint32 previous = 0x37abe8f9;
  7730.    
  7731. -   for (; *name != '\0'; ++name) {
  7732. +   for (; length > 0; --length, ++name) {
  7733.         uint32 next = previous + (hash ^ (*name * 7152373));
  7734.        
  7735.         if ((next & 0x80000000) != 0)
  7736. @@ -168,7 +200,7 @@
  7737.         hash = next;
  7738.     }
  7739.    
  7740. -   return hash;
  7741. +   return hash << 1;
  7742.  }
  7743.  
  7744.  
  7745. @@ -230,8 +262,8 @@
  7746.     shifts[2] = 9;
  7747.     shifts[3] = 13;
  7748.  
  7749. -   for (int j = 0; j < 2; ++j) {
  7750. -       for (int i = j; i < 4; i += 2) {
  7751. +   for (int j = 1; j >= 0; --j) {
  7752. +       for (int i = j; i < 8; i += 2) {
  7753.             a += _MD4G(b, c, d) + blocks[i] + 013240474631UL;
  7754.             uint32 shift = shifts[i / 2];
  7755.             a = (a << shift) | (a >> (32 - shift));
  7756. @@ -247,13 +279,13 @@
  7757.  
  7758.     for (int i = 0; i < 4; ++i) {
  7759.         a += _MD4H(b, c, d) + blocks[3 - i] + 015666365641UL;
  7760. -       uint32 shift = shifts[i*2];
  7761. +       uint32 shift = shifts[i * 2 % 4];
  7762.         a = (a << shift) | (a >> (32 - shift));
  7763.        
  7764.         _MD4RotateVars(a, b, c, d);
  7765.        
  7766.         a += _MD4H(b, c, d) + blocks[7 - i] + 015666365641UL;
  7767. -       shift = shifts[i*2 + 1];
  7768. +       shift = shifts[(i * 2 + 1) % 4];
  7769.         a = (a << shift) | (a >> (32 - shift));
  7770.        
  7771.         _MD4RotateVars(a, b, c, d);
  7772. @@ -267,19 +299,21 @@
  7773.  
  7774.  
  7775.  uint32
  7776. -HTree::_HashHalfMD4(const char* name)
  7777. +HTree::_HashHalfMD4(const char* name, uint8 _length)
  7778.  {
  7779. +   TRACE("HTree::_HashHalfMD4()\n");
  7780.     uint32 buffer[4];
  7781. +   int32 length = (uint32)_length;
  7782.  
  7783.     buffer[0] = fHashSeed[0];
  7784.     buffer[1] = fHashSeed[1];
  7785.     buffer[2] = fHashSeed[2];
  7786.     buffer[3] = fHashSeed[3];
  7787.    
  7788. -   for (int length = strlen(name); length > 0; length -= 32) {
  7789. +   for (; length > 0; length -= 32) {
  7790.         uint32 blocks[8];
  7791.        
  7792. -       _PrepareBlocksForHash(name, length, blocks, 8);
  7793. +       _PrepareBlocksForHash(name, (uint32)length, blocks, 8);
  7794.         _HalfMD4Transform(buffer, blocks);
  7795.        
  7796.         name += 32;
  7797. @@ -316,19 +350,21 @@
  7798.  
  7799.  
  7800.  uint32
  7801. -HTree::_HashTEA(const char* name)
  7802. +HTree::_HashTEA(const char* name, uint8 _length)
  7803.  {
  7804. +   TRACE("HTree::_HashTEA()\n");
  7805.     uint32 buffer[4];
  7806. +   int32 length = _length;
  7807.  
  7808.     buffer[0] = fHashSeed[0];
  7809.     buffer[1] = fHashSeed[1];
  7810.     buffer[2] = fHashSeed[2];
  7811.     buffer[3] = fHashSeed[3];
  7812.    
  7813. -   for (int length = strlen(name); length > 0; length -= 16) {
  7814. +   for (; length > 0; length -= 16) {
  7815.         uint32 blocks[4];
  7816.        
  7817. -       _PrepareBlocksForHash(name, length, blocks, 4);
  7818. +       _PrepareBlocksForHash(name, (uint32)length, blocks, 4);
  7819.         TRACE("_HashTEA %lx %lx %lx\n", blocks[0], blocks[1], blocks[2]);
  7820.         _TEATransform(buffer, blocks);
  7821.        
  7822. @@ -340,21 +376,21 @@
  7823.  
  7824.  
  7825.  void
  7826. -HTree::_PrepareBlocksForHash(const char* string, int length, uint32* blocks,
  7827. -   int numBlocks)
  7828. +HTree::_PrepareBlocksForHash(const char* string, uint32 length, uint32* blocks,
  7829. +   uint32 numBlocks)
  7830.  {
  7831.     uint32 padding = (uint32)length;
  7832.     padding = (padding << 8) | padding;
  7833.     padding = (padding << 16) | padding;
  7834.    
  7835. -   int numBytes = numBlocks * 4;
  7836. +   uint32 numBytes = numBlocks * 4;
  7837.     if (length > numBytes)
  7838.         length = numBytes;
  7839.    
  7840. -   int completeIterations = length / 4;
  7841. +   uint32 completeIterations = length / 4;
  7842.    
  7843. -   for (int i = 0; i < completeIterations; ++i) {
  7844. -       uint32 value = 0 | *(string++);
  7845. +   for (uint32 i = 0; i < completeIterations; ++i) {
  7846. +       uint32 value = (padding << 8) | *(string++);
  7847.         value = (value << 8) | *(string++);
  7848.         value = (value << 8) | *(string++);
  7849.         value = (value << 8) | *(string++);
  7850. @@ -362,15 +398,24 @@
  7851.     }
  7852.    
  7853.     if (completeIterations < numBlocks) {
  7854. -       int remainingBytes = length % 4;
  7855. +       uint32 remainingBytes = length % 4;
  7856.        
  7857.         uint32 value = padding;
  7858. -       for (int i = 0; i < remainingBytes; ++i)
  7859. +       for (uint32 i = 0; i < remainingBytes; ++i)
  7860.             value = (value << 8) + *(string++);
  7861.        
  7862.         blocks[completeIterations] = value;
  7863.        
  7864. -       for (int i = completeIterations + 1; i < numBlocks; ++i)
  7865. +       for (uint32 i = completeIterations + 1; i < numBlocks; ++i)
  7866.             blocks[i] = padding;
  7867.     }
  7868.  }
  7869. +
  7870. +
  7871. +/*inline*/ status_t
  7872. +HTree::_FallbackToLinearIteration(DirectoryIterator** iterator)
  7873. +{
  7874. +   *iterator = new(std::nothrow) DirectoryIterator(fDirectory);
  7875. +
  7876. +   return *iterator == NULL ? B_NO_MEMORY : B_OK;
  7877. +}
  7878.  
  7879. Property changes on: src/add-ons/kernel/file_systems/ext2/HTree.cpp
  7880. ___________________________________________________________________
  7881. Added: svn:executable
  7882.    + *
  7883.  
  7884. Index: src/add-ons/kernel/file_systems/ext2/HTreeEntryIterator.h
  7885. ===================================================================
  7886. --- src/add-ons/kernel/file_systems/ext2/HTreeEntryIterator.h   (revision 38119)
  7887. +++ src/add-ons/kernel/file_systems/ext2/HTreeEntryIterator.h   (working copy)
  7888. @@ -14,6 +14,9 @@
  7889.  #include "DirectoryIterator.h"
  7890.  
  7891.  
  7892. +class Volume;
  7893. +
  7894. +
  7895.  class HTreeEntryIterator {
  7896.  public:
  7897.                                 HTreeEntryIterator(off_t offset,
  7898. @@ -26,7 +29,10 @@
  7899.                                     DirectoryIterator** iterator);
  7900.             bool                HasCollision() { return fHasCollision; }
  7901.                        
  7902. -           status_t            GetNext(off_t& offset);
  7903. +           status_t            GetNext(uint32& offset);
  7904. +
  7905. +           status_t            InsertEntry(uint32 hash, uint32 block,
  7906. +                                   bool hasCollision);
  7907.  private:
  7908.                                 HTreeEntryIterator(uint32 block,
  7909.                                     uint32 blockSize, Inode* directory,
  7910. @@ -34,17 +40,20 @@
  7911.                                     bool hasCollision);
  7912.  
  7913.  private:
  7914. +           Inode*              fDirectory;
  7915. +           Volume*             fVolume;
  7916. +           status_t            fInitStatus;
  7917. +
  7918.             bool                fHasCollision;
  7919.             uint16              fLimit, fCount;
  7920. +           uint16              fFirstEntry;
  7921. +           uint16              fCurrentEntry;
  7922.  
  7923.             uint32              fBlockSize;
  7924. -           Inode*              fDirectory;
  7925. -           off_t               fOffset;
  7926. -           off_t               fMaxOffset;
  7927. +           uint32              fBlockNum;
  7928.  
  7929.             HTreeEntryIterator* fParent;
  7930.             HTreeEntryIterator* fChild;
  7931. -           ObjectDeleter<HTreeEntryIterator> fChildDeleter;
  7932.  };
  7933.  
  7934.  #endif // HTREE_ENTRY_ITERATOR_H
  7935. Index: src/add-ons/kernel/file_systems/ext2/Volume.h
  7936. ===================================================================
  7937. --- src/add-ons/kernel/file_systems/ext2/Volume.h   (revision 38119)
  7938. +++ src/add-ons/kernel/file_systems/ext2/Volume.h   (working copy)
  7939. @@ -9,8 +9,12 @@
  7940.  #include <lock.h>
  7941.  
  7942.  #include "ext2.h"
  7943. +#include "BlockAllocator.h"
  7944. +#include "InodeAllocator.h"
  7945. +#include "Transaction.h"
  7946.  
  7947.  class Inode;
  7948. +class Journal;
  7949.  
  7950.  
  7951.  enum volume_flags {
  7952. @@ -18,7 +22,7 @@
  7953.  };
  7954.  
  7955.  
  7956. -class Volume {
  7957. +class Volume : public TransactionListener {
  7958.  public:
  7959.                                 Volume(fs_volume* volume);
  7960.                                 ~Volume();
  7961. @@ -40,35 +44,76 @@
  7962.  
  7963.             uint32              NumInodes() const
  7964.                                     { return fNumInodes; }
  7965. +           uint32              NumGroups() const
  7966. +                                   { return fNumGroups; }
  7967.             off_t               NumBlocks() const
  7968.                                     { return fSuperBlock.NumBlocks(); }
  7969. -           off_t               FreeBlocks() const
  7970. -                                   { return fSuperBlock.FreeBlocks(); }
  7971. +           off_t               NumFreeBlocks() const
  7972. +                                   { return fFreeBlocks; }
  7973. +           uint32              FirstDataBlock() const
  7974. +                                   { return fFirstDataBlock; }
  7975.  
  7976.             uint32              BlockSize() const { return fBlockSize; }
  7977.             uint32              BlockShift() const { return fBlockShift; }
  7978. +           uint32              BlocksPerGroup() const
  7979. +                                   { return fSuperBlock.BlocksPerGroup(); }
  7980.             uint32              InodeSize() const
  7981.                                     { return fSuperBlock.InodeSize(); }
  7982. +           uint32              InodesPerGroup() const
  7983. +                                   { return fSuperBlock.InodesPerGroup(); }
  7984.             ext2_super_block&   SuperBlock() { return fSuperBlock; }
  7985.  
  7986.             status_t            GetInodeBlock(ino_t id, uint32& block);
  7987.             uint32              InodeBlockIndex(ino_t id) const;
  7988.             status_t            GetBlockGroup(int32 index,
  7989.                                     ext2_block_group** _group);
  7990. -          
  7991. +           status_t            WriteBlockGroup(Transaction& transaction,
  7992. +                                   int32 index);
  7993. +
  7994. +           Journal*            GetJournal() { return fJournal; }
  7995. +
  7996.             bool                IndexedDirectories() const
  7997.                                     { return (fSuperBlock.CompatibleFeatures()
  7998.                                         & EXT2_FEATURE_DIRECTORY_INDEX) != 0; }
  7999. +           uint8               DefaultHashVersion() const
  8000. +                                   { return fSuperBlock.default_hash_version; }
  8001.  
  8002. +           status_t            SaveOrphan(Transaction& transaction,
  8003. +                                   ino_t newID, ino_t &oldID);
  8004. +           status_t            RemoveOrphan(Transaction& transaction,
  8005. +                                   ino_t id);
  8006. +
  8007. +           status_t            AllocateInode(Transaction& transaction,
  8008. +                                   Inode* parent, int32 mode, ino_t& id);
  8009. +           status_t            FreeInode(Transaction& transaction, ino_t id,
  8010. +                                   bool isDirectory);
  8011. +
  8012. +           status_t            AllocateBlocks(Transaction& transaction,
  8013. +                                   uint32 minimum, uint32 maximum,
  8014. +                                   uint32& blockGroup, uint32& start,
  8015. +                                   uint32& length);
  8016. +           status_t            FreeBlocks(Transaction& transaction,
  8017. +                                   uint32 start, uint32 length);
  8018. +
  8019. +           status_t            LoadSuperBlock();
  8020. +           status_t            WriteSuperBlock(Transaction& transaction);
  8021. +
  8022.             // cache access
  8023.             void*               BlockCache() { return fBlockCache; }
  8024.  
  8025. +           status_t            FlushDevice();
  8026. +           status_t            Sync();
  8027. +
  8028.     static  status_t            Identify(int fd, ext2_super_block* superBlock);
  8029.  
  8030. +           // TransactionListener functions
  8031. +           void                TransactionDone(bool success);
  8032. +           void                RemovedFromTransaction();
  8033. +
  8034.  private:
  8035.     static  uint32              _UnsupportedIncompatibleFeatures(
  8036.                                     ext2_super_block& superBlock);
  8037. -           off_t               _GroupBlockOffset(uint32 blockIndex);
  8038. +           uint32              _GroupDescriptorBlock(uint32 blockIndex);
  8039.  
  8040.  private:
  8041.             mutex               fLock;
  8042. @@ -76,12 +121,21 @@
  8043.             int                 fDevice;
  8044.             ext2_super_block    fSuperBlock;
  8045.             char                fName[32];
  8046. +
  8047. +           BlockAllocator      fBlockAllocator;
  8048. +           InodeAllocator      fInodeAllocator;
  8049. +           Journal*            fJournal;
  8050. +           Inode*              fJournalInode;
  8051. +
  8052.             uint32              fFlags;
  8053.             uint32              fBlockSize;
  8054.             uint32              fBlockShift;
  8055.             uint32              fFirstDataBlock;
  8056. +
  8057.             uint32              fNumInodes;
  8058.             uint32              fNumGroups;
  8059. +           uint32              fFreeBlocks;
  8060. +           uint32              fFreeInodes;
  8061.             uint32              fGroupsPerBlock;
  8062.             ext2_block_group**  fGroupBlocks;
  8063.             uint32              fInodesPerBlock;
  8064. Index: src/add-ons/kernel/file_systems/ext2/DirectoryIterator.cpp
  8065. ===================================================================
  8066. --- src/add-ons/kernel/file_systems/ext2/DirectoryIterator.cpp  (revision 38119)
  8067. +++ src/add-ons/kernel/file_systems/ext2/DirectoryIterator.cpp  (working copy)
  8068. @@ -8,6 +8,9 @@
  8069.  
  8070.  #include <string.h>
  8071.  
  8072. +#include <util/VectorSet.h>
  8073. +
  8074. +#include "CachedBlock.h"
  8075.  #include "HTree.h"
  8076.  #include "Inode.h"
  8077.  
  8078. @@ -20,11 +23,39 @@
  8079.  #endif
  8080.  
  8081.  
  8082. -DirectoryIterator::DirectoryIterator(Inode* inode)
  8083. +struct HashedEntry
  8084. +{
  8085. +   uint8*  position;
  8086. +   uint32  hash;
  8087. +
  8088. +   bool    operator<(const HashedEntry& other) const
  8089. +   {
  8090. +       return hash <= other.hash;
  8091. +   }
  8092. +
  8093. +   bool    operator>(const HashedEntry& other) const
  8094. +   {
  8095. +       return hash >= other.hash;
  8096. +   }
  8097. +};
  8098. +
  8099. +
  8100. +DirectoryIterator::DirectoryIterator(Inode* directory, off_t start,
  8101. +   HTreeEntryIterator* parent)
  8102.     :
  8103. -   fInode(inode),
  8104. -   fOffset(0)
  8105. +   fDirectory(directory),
  8106. +   fVolume(directory->GetVolume()),
  8107. +   fBlockSize(fVolume->BlockSize()),
  8108. +   fParent(parent),
  8109. +   fLogicalBlock(start / fBlockSize),
  8110. +   fDisplacement(start % fBlockSize),
  8111. +   fPreviousDisplacement(fPreviousDisplacement),
  8112. +   fStartLogicalBlock(fLogicalBlock),
  8113. +   fStartDisplacement(fDisplacement)
  8114.  {
  8115. +   fIndexing = parent != NULL;
  8116. +   fInitStatus = fDirectory->FindBlock(start, fPhysicalBlock);
  8117. +   fStartPhysicalBlock = fPhysicalBlock;
  8118.  }
  8119.  
  8120.  
  8121. @@ -34,60 +65,642 @@
  8122.  
  8123.  
  8124.  status_t
  8125. -DirectoryIterator::GetNext(char* name, size_t* _nameLength, ino_t* _id)
  8126. +DirectoryIterator::InitCheck()
  8127.  {
  8128. -   if (fOffset + sizeof(ext2_dir_entry) >= fInode->Size()) {
  8129. -       TRACE("DirectoryIterator::GetNext() out of entries\n");
  8130. +   return fInitStatus;
  8131. +}
  8132. +
  8133. +
  8134. +status_t
  8135. +DirectoryIterator::Get(char* name, size_t* _nameLength, ino_t* _id)
  8136. +{
  8137. +   if (fLogicalBlock * fBlockSize + fDisplacement >= fDirectory->Size()) {
  8138. +       TRACE("DirectoryIterator::Get() out of entries\n");
  8139.         return B_ENTRY_NOT_FOUND;
  8140.     }
  8141.  
  8142. -   ext2_dir_entry entry;
  8143. +   CachedBlock cached(fVolume);
  8144. +   const uint8* block = cached.SetTo(fPhysicalBlock);
  8145. +   if (block == NULL)
  8146. +       return B_IO_ERROR;
  8147.  
  8148. -   while (true) {
  8149. -       size_t length = ext2_dir_entry::MinimumSize();
  8150. -       status_t status = fInode->ReadAt(fOffset, (uint8*)&entry, &length);
  8151. +   TRACE("DirectoryIterator::Get(): Displacement: %lu\n", fDisplacement);
  8152. +   const ext2_dir_entry* entry = (const ext2_dir_entry*)&block[fDisplacement];
  8153. +
  8154. +   if (entry->NameLength() != 0) {
  8155. +       size_t length = entry->NameLength();
  8156. +
  8157. +       TRACE("block %lu, displacement %lu: entry ino %lu, length %u, "
  8158. +           "name length %lu, type %lu\n", fLogicalBlock, fDisplacement,
  8159. +           entry->InodeID(), entry->Length(), (uint32)length,
  8160. +           (uint32)entry->FileType());
  8161. +
  8162. +       if (*_nameLength > 0) {
  8163. +           if (*_nameLength < length)
  8164. +               length = *_nameLength - 1;
  8165. +
  8166. +           memcpy(name, entry->name, length);
  8167. +           name[length] = '\0';
  8168. +
  8169. +           *_nameLength = length;
  8170. +       }
  8171. +
  8172. +       *_id = entry->InodeID();
  8173. +   } else
  8174. +       *_nameLength = 0;
  8175. +
  8176. +   return B_OK;
  8177. +}
  8178. +
  8179. +
  8180. +status_t
  8181. +DirectoryIterator::Next()
  8182. +{
  8183. +   TRACE("DirectoryIterator::Next()\n");
  8184. +
  8185. +   if (fLogicalBlock * fBlockSize + fDisplacement >= fDirectory->Size()) {
  8186. +       TRACE("DirectoryIterator::Next() out of entries\n");
  8187. +       return B_ENTRY_NOT_FOUND;
  8188. +   }
  8189. +
  8190. +   TRACE("DirectoryIterator::Next(): Creating cached block\n");
  8191. +
  8192. +   CachedBlock cached(fVolume);
  8193. +   ext2_dir_entry* entry;
  8194. +
  8195. +   const uint8* block = cached.SetTo(fPhysicalBlock);
  8196. +   if (block == NULL)
  8197. +       return B_IO_ERROR;
  8198. +
  8199. +   entry = (ext2_dir_entry*)(block + fDisplacement);
  8200. +
  8201. +   do {
  8202. +       TRACE("Checking entry at block %lu, displacement %lu\n", fPhysicalBlock,
  8203. +           fDisplacement);
  8204. +
  8205. +       if (entry->Length() == 0) {
  8206. +           TRACE("empty entry.\n");
  8207. +           return B_ENTRY_NOT_FOUND;
  8208. +       }
  8209. +       if (!entry->IsValid()) {
  8210. +           TRACE("invalid entry.\n");
  8211. +           return B_BAD_DATA;
  8212. +       }
  8213. +
  8214. +       fPreviousDisplacement = fDisplacement;
  8215. +       fDisplacement += entry->Length();
  8216. +
  8217. +       if (fDisplacement == fBlockSize) {
  8218. +           TRACE("Reached end of block\n");
  8219. +
  8220. +           fDisplacement = 0;
  8221. +
  8222. +           status_t status = _NextBlock();
  8223. +           if (status != B_OK)
  8224. +               return status;
  8225. +          
  8226. +           if (fLogicalBlock * fBlockSize + ext2_dir_entry::MinimumSize()
  8227. +                   < fDirectory->Size()) {
  8228. +               status_t status = fDirectory->FindBlock(
  8229. +                   fLogicalBlock * fBlockSize, fPhysicalBlock);
  8230. +               if (status != B_OK)
  8231. +                   return status;
  8232. +           } else {
  8233. +               TRACE("DirectoryIterator::Next() end of directory file\n");
  8234. +               return B_ENTRY_NOT_FOUND;
  8235. +           }
  8236. +
  8237. +           if (entry->Length() == 0) {
  8238. +               block = cached.SetTo(fPhysicalBlock);
  8239. +               if (block == NULL)
  8240. +                   return B_IO_ERROR;
  8241. +           }
  8242. +       } else if (fDisplacement > fBlockSize) {
  8243. +           TRACE("The entry isn't block aligned.\n");
  8244. +           // TODO: Is block alignment obligatory?
  8245. +           return B_BAD_DATA;
  8246. +       }
  8247. +
  8248. +       entry = (ext2_dir_entry*)(block + fDisplacement);
  8249. +
  8250. +       TRACE("DirectoryIterator::Next() skipping entry\n");
  8251. +   } while (entry->Length() == 0);
  8252. +
  8253. +   return B_OK;
  8254. +}
  8255. +
  8256. +
  8257. +status_t
  8258. +DirectoryIterator::Rewind()
  8259. +{
  8260. +   fDisplacement = 0;
  8261. +   fPreviousDisplacement = 0;
  8262. +   fLogicalBlock = 0;
  8263. +
  8264. +   return fDirectory->FindBlock(0, fPhysicalBlock);
  8265. +}
  8266. +
  8267. +
  8268. +void
  8269. +DirectoryIterator::Restart()
  8270. +{
  8271. +   fLogicalBlock = fStartLogicalBlock;
  8272. +   fPhysicalBlock = fStartPhysicalBlock;
  8273. +   fDisplacement = fPreviousDisplacement = fStartDisplacement;
  8274. +}
  8275. +
  8276. +
  8277. +status_t
  8278. +DirectoryIterator::AddEntry(Transaction& transaction, const char* name,
  8279. +   size_t _nameLength, ino_t id, uint8 type)
  8280. +{
  8281. +   TRACE("DirectoryIterator::AddEntry()\n");
  8282. +
  8283. +   off_t inodeSize = fDirectory->Size();
  8284. +   uint8 nameLength = _nameLength > EXT2_NAME_LENGTH ? EXT2_NAME_LENGTH
  8285. +       : _nameLength;
  8286. +
  8287. +   uint32 lastBlock = (uint32)inodeSize / fBlockSize;
  8288. +   if (inodeSize % fBlockSize != 0)
  8289. +       lastBlock++;
  8290. +
  8291. +   while (fLogicalBlock < lastBlock) {
  8292. +       uint16 pos = 0;
  8293. +       uint16 newLength;
  8294. +
  8295. +       status_t status = _AllocateBestEntryInBlock(nameLength, pos, newLength);
  8296. +       if (status == B_OK) {
  8297. +           return _AddEntry(transaction, name, nameLength, id, type, newLength,
  8298. +               pos, pos != 0);
  8299. +       } else if (status != B_DEVICE_FULL)
  8300. +           return status;
  8301. +      
  8302. +       status = _NextBlock();
  8303. +       if (status == B_ENTRY_NOT_FOUND)
  8304. +           return _SplitIndexedBlock(transaction, name, nameLength, id);
  8305. +       else if(status != B_OK)
  8306. +           return status;
  8307. +
  8308. +       status = fDirectory->FindBlock(fLogicalBlock, fPhysicalBlock);
  8309.         if (status != B_OK)
  8310.             return status;
  8311. -       if (length < ext2_dir_entry::MinimumSize() || entry.Length() == 0)
  8312. -           return B_ENTRY_NOT_FOUND;
  8313. -       if (!entry.IsValid())
  8314. +   }
  8315. +
  8316. +   bool firstSplit = lastBlock == 1 && fVolume->IndexedDirectories();
  8317. +   if (firstSplit) {
  8318. +       // Allocate another block
  8319. +       ++lastBlock;
  8320. +   }
  8321. +
  8322. +   status_t status = fDirectory->Resize(transaction,
  8323. +       (lastBlock + 2) * fBlockSize);
  8324. +   if (status != B_OK)
  8325. +       return status;
  8326. +
  8327. +   if (firstSplit)
  8328. +       return _SplitIndexedBlock(transaction, name, nameLength, id, true);
  8329. +
  8330. +   fLogicalBlock = lastBlock + 1;
  8331. +   status = fDirectory->FindBlock(fLogicalBlock, fPhysicalBlock);
  8332. +   if (status != B_OK)
  8333. +       return status;
  8334. +
  8335. +   return _AddEntry(transaction, name, nameLength, id, type, fBlockSize, 0,
  8336. +       false);
  8337. +}
  8338. +
  8339. +
  8340. +status_t
  8341. +DirectoryIterator::FindEntry(const char* name, ino_t* _id)
  8342. +{
  8343. +   TRACE("DirectoryIterator::FindEntry(): %p %p\n", this, name);
  8344. +   char buffer[EXT2_NAME_LENGTH + 1];
  8345. +   ino_t id;
  8346. +
  8347. +   status_t status = B_OK;
  8348. +   while (status == B_OK) {
  8349. +       size_t nameLength = EXT2_NAME_LENGTH;
  8350. +       status = Get(buffer, &nameLength, &id);
  8351. +       if (status != B_OK)
  8352. +           return status;
  8353. +
  8354. +       if (strcmp(name, buffer) == 0) {
  8355. +           if (_id != NULL)
  8356. +               *_id = id;
  8357. +           return B_OK;
  8358. +       }
  8359. +
  8360. +       status = Next();
  8361. +   }
  8362. +
  8363. +   return status;
  8364. +}
  8365. +
  8366. +
  8367. +status_t
  8368. +DirectoryIterator::RemoveEntry(Transaction& transaction)
  8369. +{
  8370. +   ext2_dir_entry* previousEntry;
  8371. +   ext2_dir_entry* dirEntry;
  8372. +   CachedBlock cached(fVolume);
  8373. +
  8374. +   uint8* block = cached.SetToWritable(transaction, fPhysicalBlock);
  8375. +
  8376. +   if (fDisplacement == 0) {
  8377. +       previousEntry = (ext2_dir_entry*)&block[fDisplacement];
  8378. +
  8379. +       fPreviousDisplacement = fDisplacement;
  8380. +       fDisplacement += previousEntry->Length();
  8381. +
  8382. +       if (fDisplacement == fBlockSize) {
  8383. +           memset(&previousEntry->name_length, 0, fBlockSize - 6);
  8384. +           fDisplacement = 0;
  8385. +           return Next();
  8386. +       } else if (fDisplacement > fBlockSize) {
  8387. +           TRACE("DirectoryIterator::RemoveEntry(): Entry isn't aligned to "
  8388. +               "block entry.");
  8389.             return B_BAD_DATA;
  8390. +       }
  8391.  
  8392. -       if (entry.NameLength() != 0)
  8393. +       dirEntry = (ext2_dir_entry*)&block[fDisplacement];
  8394. +       memcpy(&block[fPreviousDisplacement], &block[fDisplacement],
  8395. +           dirEntry->Length());
  8396. +
  8397. +       previousEntry->SetLength(fDisplacement - fPreviousDisplacement
  8398. +           + previousEntry->Length());
  8399. +
  8400. +       return B_OK;
  8401. +   }
  8402. +
  8403. +   if (fPreviousDisplacement == fDisplacement) {
  8404. +       char buffer[EXT2_NAME_LENGTH + 1];
  8405. +
  8406. +       dirEntry = (ext2_dir_entry*)&block[fDisplacement];
  8407. +
  8408. +       memcpy(buffer, dirEntry->name, (uint32)dirEntry->name_length);
  8409. +
  8410. +       fDisplacement = 0;
  8411. +       status_t status = FindEntry(dirEntry->name);
  8412. +       if (status == B_ENTRY_NOT_FOUND)
  8413. +           return B_BAD_DATA;
  8414. +       if (status != B_OK)
  8415. +           return status;
  8416. +   }
  8417. +
  8418. +   previousEntry = (ext2_dir_entry*)&block[fPreviousDisplacement];
  8419. +   dirEntry = (ext2_dir_entry*)&block[fDisplacement];
  8420. +
  8421. +   previousEntry->SetLength(previousEntry->Length() + dirEntry->Length());
  8422. +
  8423. +   memset(&block[fDisplacement], 0,
  8424. +       fPreviousDisplacement + previousEntry->Length() - fDisplacement);
  8425. +
  8426. +   return B_OK;
  8427. +}
  8428. +
  8429. +
  8430. +status_t
  8431. +DirectoryIterator::ChangeEntry(Transaction& transaction, ino_t id,
  8432. +   uint8 fileType)
  8433. +{
  8434. +   CachedBlock cached(fVolume);
  8435. +
  8436. +   uint8* block = cached.SetToWritable(transaction, fPhysicalBlock);
  8437. +   if (block == NULL)
  8438. +       return B_IO_ERROR;
  8439. +
  8440. +   ext2_dir_entry* dirEntry = (ext2_dir_entry*)&block[fDisplacement];
  8441. +   dirEntry->SetInodeID(id);
  8442. +   dirEntry->file_type = fileType;
  8443. +
  8444. +   return B_OK;
  8445. +}
  8446. +
  8447. +
  8448. +status_t
  8449. +DirectoryIterator::_AllocateBestEntryInBlock(uint8 nameLength, uint16& pos,
  8450. +   uint16& newLength)
  8451. +{
  8452. +   TRACE("DirectoryIterator::_AllocateBestEntryInBlock()\n");
  8453. +   CachedBlock cached(fVolume);
  8454. +   const uint8* block = cached.SetTo(fPhysicalBlock);
  8455. +
  8456. +   uint16 requiredLength = nameLength + 8;
  8457. +   if (requiredLength % 4 != 0)
  8458. +       requiredLength += 4 - requiredLength % 4;
  8459. +  
  8460. +   uint16 bestPos = fBlockSize;
  8461. +   uint16 bestLength = fBlockSize;
  8462. +   uint16 bestRealLength = fBlockSize;
  8463. +   ext2_dir_entry* dirEntry;
  8464. +  
  8465. +   while (pos < fBlockSize) {
  8466. +       dirEntry = (ext2_dir_entry*)&block[pos];
  8467. +
  8468. +       uint16 realLength = dirEntry->NameLength() + 8;
  8469. +
  8470. +       if (realLength % 4 != 0)
  8471. +           realLength += 4 - realLength % 4;
  8472. +
  8473. +       uint16 emptySpace = dirEntry->Length() - realLength;
  8474. +       if (emptySpace == requiredLength) {
  8475. +           // Found an exact match
  8476. +           TRACE("DirectoryIterator::_AllocateBestEntryInBlock(): Found an "
  8477. +               "exact length match\n");
  8478. +           newLength = realLength;
  8479. +
  8480. +           return B_OK;
  8481. +       } else if (emptySpace > requiredLength && emptySpace < bestLength) {
  8482. +           bestPos = pos;
  8483. +           bestLength = emptySpace;
  8484. +           bestRealLength = realLength;
  8485. +       }
  8486. +
  8487. +       pos += dirEntry->Length();
  8488. +   }
  8489. +  
  8490. +   if (bestPos == fBlockSize)
  8491. +       return B_DEVICE_FULL;
  8492. +
  8493. +   TRACE("DirectoryIterator::_AllocateBestEntryInBlock(): Found a suitable "
  8494. +       "location: %lu\n", bestPos);
  8495. +   pos = bestPos;
  8496. +   newLength = bestRealLength;
  8497. +
  8498. +   return B_OK;
  8499. +}
  8500. +
  8501. +
  8502. +status_t
  8503. +DirectoryIterator::_AddEntry(Transaction& transaction, const char* name,
  8504. +   uint8 nameLength, ino_t id, uint8 type, uint16 newLength, uint16 pos,
  8505. +   bool hasPrevious)
  8506. +{
  8507. +   TRACE("DirectoryIterator::_AddEntry(%s, %d, %d, %d, %d, %d, %c)\n",
  8508. +       name, (int)nameLength, (int)id, (int)type, (int)newLength, (int)pos,
  8509. +       hasPrevious ? 't' : 'f');
  8510. +   CachedBlock cached(fVolume);
  8511. +
  8512. +   uint8* block = cached.SetToWritable(transaction, fPhysicalBlock);
  8513. +   if (block == NULL)
  8514. +       return B_IO_ERROR;
  8515. +
  8516. +   ext2_dir_entry* dirEntry = (ext2_dir_entry*)&block[pos];
  8517. +
  8518. +   if (hasPrevious) {
  8519. +       uint16 previousLength = dirEntry->Length();
  8520. +       dirEntry->SetLength(newLength);
  8521. +
  8522. +       dirEntry = (ext2_dir_entry*)&block[pos + newLength];
  8523. +       newLength = previousLength - newLength;
  8524. +   }
  8525. +
  8526. +   dirEntry->SetLength(newLength);
  8527. +   dirEntry->name_length = nameLength;
  8528. +   dirEntry->SetInodeID(id);
  8529. +   dirEntry->file_type = type;
  8530. +   memcpy(dirEntry->name, name, nameLength);
  8531. +
  8532. +   TRACE("DirectoryIterator::_AddEntry(): Done\n");
  8533. +
  8534. +   return B_OK;
  8535. +}
  8536. +
  8537. +
  8538. +status_t
  8539. +DirectoryIterator::_SplitIndexedBlock(Transaction& transaction,
  8540. +   const char* name, uint8 nameLength, ino_t id, bool firstSplit)
  8541. +{
  8542. +   // Block is full, split required
  8543. +   // Allocate a buffer for the entries in the block
  8544. +   uint8* buffer = new(std::nothrow) uint8[fBlockSize];
  8545. +   if (buffer == NULL)
  8546. +       return B_NO_MEMORY;
  8547. +   ArrayDeleter<uint8> bufferDeleter(buffer);
  8548. +
  8549. +   uint32 firstPhysicalBlock = 0;
  8550. +
  8551. +   // Prepare block to hold the first half of the entries and fill the buffer
  8552. +   CachedBlock cachedFirst(fVolume);
  8553. +
  8554. +   if (firstSplit) {
  8555. +       // Save all entries to the buffer
  8556. +       status_t status = fDirectory->FindBlock(0, firstPhysicalBlock);
  8557. +       if (status != B_OK)
  8558. +           return status;
  8559. +
  8560. +       const uint8* srcBlock = cachedFirst.SetTo(firstPhysicalBlock);
  8561. +       if (srcBlock == NULL)
  8562. +           return B_IO_ERROR;
  8563. +
  8564. +       memcpy(buffer, srcBlock, fBlockSize);
  8565. +
  8566. +       status = fDirectory->FindBlock(fBlockSize, fPhysicalBlock);
  8567. +       if (status != B_OK)
  8568. +           return status;
  8569. +   }
  8570. +
  8571. +   uint8* firstBlock = cachedFirst.SetToWritable(transaction, fPhysicalBlock);
  8572. +   if (firstBlock == NULL)
  8573. +       return B_IO_ERROR;
  8574. +
  8575. +   if (!firstSplit) {
  8576. +       // Save all entries to the buffer
  8577. +       memcpy(buffer, firstBlock, fBlockSize);
  8578. +   }
  8579. +
  8580. +   // Prepare last block to hold the second half of the entries
  8581. +   fDisplacement = 0;
  8582. +
  8583. +   status_t status = fDirectory->FindBlock(fDirectory->Size() - 1,
  8584. +       fPhysicalBlock);
  8585. +   if (status != B_OK)
  8586. +       return status;
  8587. +
  8588. +   CachedBlock cachedSecond(fVolume);
  8589. +   uint8* secondBlock = cachedSecond.SetToWritable(transaction,
  8590. +       fPhysicalBlock);
  8591. +   if (secondBlock == NULL)
  8592. +       return B_IO_ERROR;
  8593. +
  8594. +   // Sort entries
  8595. +   VectorSet<HashedEntry> entrySet;
  8596. +
  8597. +   HTree htree(fVolume, fDirectory);
  8598. +   status = htree.PrepareForHash();
  8599. +   if (status != B_OK)
  8600. +       return B_OK;
  8601. +
  8602. +   HashedEntry entry;
  8603. +
  8604. +   uint32 displacement = 0;
  8605. +   ext2_dir_entry* dirEntry = NULL;
  8606. +
  8607. +   while (displacement < fBlockSize) {
  8608. +       entry.position = &firstBlock[displacement];
  8609. +       dirEntry = (ext2_dir_entry*)entry.position;
  8610. +
  8611. +       entry.hash = htree.Hash(dirEntry->name, dirEntry->name_length);
  8612. +
  8613. +       status = entrySet.Insert(entry);
  8614. +       if (status != B_OK)
  8615. +           return status;
  8616. +
  8617. +       displacement += dirEntry->Length();
  8618. +   }
  8619. +
  8620. +   // Prepare the new entry to be included as well
  8621. +   ext2_dir_entry newEntry;
  8622. +
  8623. +   uint16 newLength = (uint16)nameLength;
  8624. +   if (newLength % 4 != 0)
  8625. +       newLength += 4 - newLength % 4;
  8626. +
  8627. +   newEntry.name_length = nameLength;
  8628. +   newEntry.SetLength(newLength);
  8629. +   newEntry.SetInodeID(id);
  8630. +   memcpy(newEntry.name, name, nameLength);
  8631. +
  8632. +   entry.position = (uint8*)&newEntry;
  8633. +   entry.hash = htree.Hash(name, nameLength);
  8634. +
  8635. +   entrySet.Insert(entry);
  8636. +
  8637. +   // Move first half of entries to the first block
  8638. +   VectorSet<HashedEntry>::Iterator iterator = entrySet.Begin();
  8639. +   int32 median = entrySet.Count() / 2;
  8640. +   displacement = 0;
  8641. +
  8642. +   for (int32 i = 0; i < median; ++i) {
  8643. +       dirEntry = (ext2_dir_entry*)(*iterator).position;
  8644. +
  8645. +       memcpy(&firstBlock[displacement], dirEntry, dirEntry->Length());
  8646. +
  8647. +       displacement += dirEntry->Length();
  8648. +       iterator++;
  8649. +   }
  8650. +
  8651. +   // Save the hash to store in the parent
  8652. +   iterator--;
  8653. +   uint32 medianHash = (*iterator).hash;
  8654. +   iterator++;
  8655. +   bool collision = false;
  8656. +
  8657. +   while ((*iterator).hash == medianHash) {
  8658. +       // Keep collisions on the same block
  8659. +       // This isn't the ideal solution, but it is a rare occurance
  8660. +       dirEntry = (ext2_dir_entry*)(*iterator).position;
  8661. +
  8662. +       if (displacement + dirEntry->Length() > fBlockSize) {
  8663. +           // Doesn't fit on the block
  8664. +           --iterator;
  8665. +           dirEntry = (ext2_dir_entry*)(*iterator).position;
  8666. +           ++iterator;
  8667. +          
  8668. +           collision = true;
  8669.             break;
  8670. +       }
  8671.  
  8672. -       fOffset += entry.Length();
  8673. -       TRACE("DirectoryIterator::GetNext() skipping entry\n");
  8674. +       memcpy(&firstBlock[displacement], dirEntry, dirEntry->Length());
  8675. +
  8676. +       displacement += dirEntry->Length();
  8677. +       iterator++;
  8678.     }
  8679.  
  8680. -   TRACE("offset %Ld: entry ino %lu, length %u, name length %u, type %u\n",
  8681. -       fOffset, entry.InodeID(), entry.Length(), entry.NameLength(),
  8682. -       entry.FileType());
  8683. +   // Update last entry in the block
  8684. +   uint16 oldLength = dirEntry->Length();
  8685. +   dirEntry = (ext2_dir_entry*)&firstBlock[displacement - oldLength];
  8686. +   dirEntry->SetLength(fBlockSize - displacement + oldLength);
  8687.  
  8688. -   // read name
  8689. +   // Move the second half of the entries to the second block
  8690. +   VectorSet<HashedEntry>::Iterator end = entrySet.End();
  8691. +   displacement = 0;
  8692.  
  8693. -   size_t length = entry.NameLength();
  8694. -   status_t status = fInode->ReadAt(fOffset + ext2_dir_entry::MinimumSize(),
  8695. -       (uint8*)entry.name, &length);
  8696. -   if (status == B_OK) {
  8697. -       if (*_nameLength < length)
  8698. -           length = *_nameLength - 1;
  8699. -       memcpy(name, entry.name, length);
  8700. -       name[length] = '\0';
  8701. +   while (iterator != end) {
  8702. +       dirEntry = (ext2_dir_entry*)(*iterator).position;
  8703.  
  8704. -       *_id = entry.InodeID();
  8705. -       *_nameLength = length;
  8706. +       memcpy(&secondBlock[displacement], dirEntry, dirEntry->Length());
  8707.  
  8708. -       fOffset += entry.Length();
  8709. +       displacement += dirEntry->Length();
  8710. +       iterator++;
  8711.     }
  8712.  
  8713. -   return status;
  8714. +   // Update last entry in the block
  8715. +   oldLength = dirEntry->Length();
  8716. +   dirEntry = (ext2_dir_entry*)&secondBlock[displacement - oldLength];
  8717. +   dirEntry->SetLength(fBlockSize - displacement + oldLength);
  8718. +
  8719. +   // Update parent
  8720. +   if (firstSplit) {
  8721. +       // Prepare the root node
  8722. +       fDirectory->Node().SetFlag(EXT2_INODE_INDEXED);
  8723. +       HTreeRoot* root;
  8724. +
  8725. +       firstBlock = cachedFirst.SetToWritable(transaction, firstPhysicalBlock);
  8726. +       if (firstBlock == NULL)
  8727. +           return B_IO_ERROR;
  8728. +
  8729. +       status = fDirectory->WriteBack(transaction);
  8730. +       if (status != B_OK)
  8731. +           return status;
  8732. +
  8733. +       root = (HTreeRoot*)firstBlock;
  8734. +
  8735. +       root->hash_version = fVolume->DefaultHashVersion();
  8736. +       root->root_info_length = 4;
  8737. +       root->indirection_levels = 0;
  8738. +       root->flags = 0;
  8739. +
  8740. +       root->count_limit->SetLimit((fBlockSize
  8741. +           - ((uint8*)root->count_limit - firstBlock)) / sizeof(HTreeEntry));
  8742. +       root->count_limit->SetCount(2);
  8743. +
  8744. +       HTreeEntry* htreeEntry = (HTreeEntry*)root->count_limit;
  8745. +       htreeEntry->SetBlock(1);
  8746. +      
  8747. +       ++htreeEntry;
  8748. +       htreeEntry->SetBlock(2);
  8749. +       htreeEntry->SetHash(medianHash);
  8750. +
  8751. +       off_t start = (off_t)root->root_info_length
  8752. +           + 2 * (sizeof(HTreeFakeDirEntry) + 4);
  8753. +       fParent = new(std::nothrow) HTreeEntryIterator(start, fDirectory);
  8754. +       if (fParent == NULL)
  8755. +           return B_NO_MEMORY;
  8756. +      
  8757. +       fParentDeleter.SetTo(fParent);
  8758. +
  8759. +       fLogicalBlock = 1;
  8760. +       status = fDirectory->FindBlock(fLogicalBlock * fBlockSize,
  8761. +           fPhysicalBlock);
  8762. +
  8763. +       fPreviousDisplacement = fDisplacement = 0;
  8764. +
  8765. +       return fParent->Init();
  8766. +   }
  8767. +   else
  8768. +       return fParent->InsertEntry(medianHash, fLogicalBlock, collision);
  8769.  }
  8770.  
  8771.  
  8772.  status_t
  8773. -DirectoryIterator::Rewind()
  8774. +DirectoryIterator::_NextBlock()
  8775.  {
  8776. -   fOffset = 0;
  8777. +   TRACE("DirectoryIterator::_NextBlock()\n");
  8778. +   if (fIndexing) {
  8779. +       TRACE("DirectoryIterator::_NextBlock(): Indexing\n");
  8780. +       if (!fParent->HasCollision()) {
  8781. +           TRACE("IndexedDirectoryIterator::_NextBlock(): next block doesn't "
  8782. +               "contain collisions from previous block\n");
  8783. +#ifndef COLLISION_TEST
  8784. +           return B_ENTRY_NOT_FOUND;
  8785. +#endif
  8786. +       }
  8787. +
  8788. +       return fParent->GetNext(fLogicalBlock);
  8789. +   }
  8790. +
  8791. +   ++fLogicalBlock;
  8792. +
  8793.     return B_OK;
  8794.  }
  8795. Index: src/add-ons/kernel/file_systems/ext2/Journal.h
  8796. ===================================================================
  8797. --- src/add-ons/kernel/file_systems/ext2/Journal.h  (revision 0)
  8798. +++ src/add-ons/kernel/file_systems/ext2/Journal.h  (revision 0)
  8799. @@ -0,0 +1,257 @@
  8800. +/*
  8801. + * Copyright 2001-2010, Haiku Inc. All rights reserved.
  8802. + * This file may be used under the terms of the MIT License.
  8803. + *
  8804. + * Authors:
  8805. + *     Janito V. Ferreira Filho
  8806. + */
  8807. +#ifndef JOURNAL_H
  8808. +#define JOURNAL_H
  8809. +
  8810. +
  8811. +#define JOURNAL_MAGIC                              0xc03b3998U
  8812. +
  8813. +#define JOURNAL_DESCRIPTOR_BLOCK                   1
  8814. +#define JOURNAL_COMMIT_BLOCK                       2
  8815. +#define JOURNAL_SUPERBLOCK_V1                      3
  8816. +#define JOURNAL_SUPERBLOCK_V2                      4
  8817. +#define JOURNAL_REVOKE_BLOCK                       5
  8818. +
  8819. +#define JOURNAL_FLAG_ESCAPED                       1
  8820. +#define JOURNAL_FLAG_SAME_UUID                     2
  8821. +#define JOURNAL_FLAG_DELETED                       4
  8822. +#define JOURNAL_FLAG_LAST_TAG                      8
  8823. +
  8824. +#define JOURNAL_FEATURE_INCOMPATIBLE_REVOKE            1
  8825. +
  8826. +#define JOURNAL_KNOWN_READ_ONLY_COMPATIBLE_FEATURES    0
  8827. +#define JOURNAL_KNOWN_INCOMPATIBLE_FEATURES            \
  8828. +   JOURNAL_FEATURE_INCOMPATIBLE_REVOKE
  8829. +
  8830. +
  8831. +#include "Volume.h"
  8832. +
  8833. +#include <AutoDeleter.h>
  8834. +#include <util/DoublyLinkedList.h>
  8835. +
  8836. +#include "Transaction.h"
  8837. +
  8838. +
  8839. +class RevokeManager;
  8840. +
  8841. +
  8842. +struct JournalHeader {
  8843. +   uint32          magic;
  8844. +   uint32          block_type;
  8845. +   uint32          sequence;
  8846. +   char            data[0];
  8847. +
  8848. +   uint32          Magic()         const  
  8849. +       { return B_BENDIAN_TO_HOST_INT32(magic); }
  8850. +   uint32          BlockType()     const  
  8851. +       { return B_BENDIAN_TO_HOST_INT32(block_type); }
  8852. +   uint32          Sequence()      const  
  8853. +       { return B_BENDIAN_TO_HOST_INT32(sequence); }
  8854. +
  8855. +   bool            CheckMagic()    const
  8856. +       { return Magic() == JOURNAL_MAGIC; }
  8857. +
  8858. +   void            IncrementSequence()
  8859. +       { sequence = B_HOST_TO_BENDIAN_INT32(Sequence() + 1); }
  8860. +   void            DecrementSequence()
  8861. +       { sequence = B_HOST_TO_BENDIAN_INT32(Sequence() - 1); }
  8862. +   void            MakeDescriptor(uint32 sequence);
  8863. +   void            MakeCommit(uint32 sequence);
  8864. +} _PACKED;
  8865. +
  8866. +
  8867. +struct JournalBlockTag {
  8868. +   uint32          block_number;
  8869. +   uint32          flags;
  8870. +
  8871. +   uint32          BlockNumber()   const  
  8872. +       { return B_BENDIAN_TO_HOST_INT32(block_number); }
  8873. +   uint32          Flags()         const  
  8874. +       { return B_BENDIAN_TO_HOST_INT32(flags); }
  8875. +
  8876. +   void            SetBlockNumber(uint32 block)
  8877. +       { block_number = B_HOST_TO_BENDIAN_INT32(block); }
  8878. +   void            SetFlags(uint32 new_flags)
  8879. +       { flags = B_HOST_TO_BENDIAN_INT32(new_flags); }
  8880. +   void            SetLastTagFlag()
  8881. +       { flags |= B_HOST_TO_BENDIAN_INT32(JOURNAL_FLAG_LAST_TAG); }
  8882. +   void            SetEscapedFlag()
  8883. +       { flags |= B_HOST_TO_BENDIAN_INT32(JOURNAL_FLAG_ESCAPED); }
  8884. +} _PACKED;
  8885. +
  8886. +
  8887. +struct JournalRevokeHeader {
  8888. +   JournalHeader   header;
  8889. +   uint32          num_bytes;
  8890. +
  8891. +   uint32          revoke_blocks[0];
  8892. +
  8893. +   uint32          NumBytes()      const  
  8894. +       { return B_BENDIAN_TO_HOST_INT32(num_bytes); }
  8895. +   uint32          RevokeBlock(int offset) const  
  8896. +       { return B_BENDIAN_TO_HOST_INT32(revoke_blocks[offset]); }
  8897. +} _PACKED;
  8898. +
  8899. +
  8900. +struct JournalSuperBlock {
  8901. +   JournalHeader   header;
  8902. +  
  8903. +   uint32          block_size;
  8904. +   uint32          num_blocks;
  8905. +   uint32          first_log_block;
  8906. +
  8907. +   uint32          first_commit_id;
  8908. +   uint32          log_start;
  8909. +
  8910. +   uint32          error;
  8911. +
  8912. +   uint32          compatible_features;
  8913. +   uint32          incompatible_features;
  8914. +   uint32          read_only_compatible_features;
  8915. +
  8916. +   uint8           uuid[16];
  8917. +
  8918. +   uint32          num_users;
  8919. +   uint32          dynamic_superblock;
  8920. +
  8921. +   uint32          max_transaction_blocks;
  8922. +   uint32          max_transaction_data;
  8923. +
  8924. +   uint32          padding[44];
  8925. +
  8926. +   uint8           user_ids[16*48];
  8927. +
  8928. +   uint32          BlockSize() const
  8929. +       { return B_BENDIAN_TO_HOST_INT32(block_size); }
  8930. +   uint32          NumBlocks() const
  8931. +       { return B_BENDIAN_TO_HOST_INT32(num_blocks); }
  8932. +   uint32          FirstLogBlock() const
  8933. +       { return B_BENDIAN_TO_HOST_INT32(first_log_block); }
  8934. +   uint32          FirstCommitID() const
  8935. +       { return B_BENDIAN_TO_HOST_INT32(first_commit_id); }
  8936. +   uint32          LogStart() const
  8937. +       { return B_BENDIAN_TO_HOST_INT32(log_start); }
  8938. +   uint32          IncompatibleFeatures() const
  8939. +       { return B_BENDIAN_TO_HOST_INT32(incompatible_features); }
  8940. +   uint32          ReadOnlyCompatibleFeatures() const
  8941. +       { return B_BENDIAN_TO_HOST_INT32(read_only_compatible_features); }
  8942. +   uint32          MaxTransactionBlocks() const
  8943. +       { return B_BENDIAN_TO_HOST_INT32(max_transaction_blocks); }
  8944. +   uint32          MaxTransactionData() const
  8945. +       { return B_BENDIAN_TO_HOST_INT32(max_transaction_data); }
  8946. +
  8947. +   void            SetLogStart(uint32 logStart)
  8948. +       { log_start = B_HOST_TO_BENDIAN_INT32(logStart); }
  8949. +   void            SetFirstCommitID(uint32 firstCommitID)
  8950. +       { first_commit_id = B_HOST_TO_BENDIAN_INT32(firstCommitID); }
  8951. +} _PACKED;
  8952. +
  8953. +class LogEntry;
  8954. +class Transaction;
  8955. +typedef DoublyLinkedList<LogEntry> LogEntryList;
  8956. +
  8957. +
  8958. +class Journal {
  8959. +public:
  8960. +                               Journal(Volume *fsVolume, Volume *jVolume);
  8961. +   virtual                     ~Journal();
  8962. +
  8963. +   virtual status_t            InitCheck();
  8964. +   virtual status_t            Uninit();
  8965. +
  8966. +   virtual status_t            Recover();
  8967. +   virtual status_t            StartLog();
  8968. +           status_t            RestartLog();
  8969. +
  8970. +   virtual status_t            Lock(Transaction* owner,
  8971. +                                   bool separateSubTransactions);
  8972. +   virtual status_t            Unlock(Transaction* owner, bool success);
  8973. +
  8974. +   virtual status_t            MapBlock(uint32 logical, uint32& physical);
  8975. +   inline  uint32              FreeLogBlocks() const;
  8976. +          
  8977. +           status_t            FlushLogAndBlocks();
  8978. +
  8979. +           int32               TransactionID() const;
  8980. +
  8981. +           Volume*             GetFilesystemVolume()
  8982. +               { return fFilesystemVolume; }
  8983. +protected:
  8984. +                               Journal();
  8985. +  
  8986. +           status_t            _WritePartialTransactionToLog(
  8987. +                                   JournalHeader* descriptorBlock,
  8988. +                                   bool detached, uint8** escapedBlock,
  8989. +                                   uint32& logBlock, off_t& blockNumber,
  8990. +                                   long& cookie,
  8991. +                                   ArrayDeleter<uint8>& escapedDataDeleter,
  8992. +                                   uint32& blockCount, bool& finished);
  8993. +   virtual status_t            _WriteTransactionToLog();
  8994. +
  8995. +           status_t            _SaveSuperBlock();
  8996. +           status_t            _LoadSuperBlock();
  8997. +
  8998. +
  8999. +           Volume*             fJournalVolume;
  9000. +           void*               fJournalBlockCache;
  9001. +           Volume*             fFilesystemVolume;
  9002. +           void*               fFilesystemBlockCache;
  9003. +
  9004. +           recursive_lock      fLock;
  9005. +           Transaction*        fOwner;
  9006. +
  9007. +           RevokeManager*      fRevokeManager;
  9008. +
  9009. +           status_t            fInitStatus;
  9010. +           uint32              fBlockSize;
  9011. +           uint32              fFirstCommitID;
  9012. +           uint32              fFirstCacheCommitID;
  9013. +           uint32              fFirstLogBlock;
  9014. +           uint32              fLogSize;
  9015. +           uint32              fVersion;
  9016. +          
  9017. +           uint32              fLogStart;
  9018. +           uint32              fLogEnd;
  9019. +           uint32              fFreeBlocks;
  9020. +           uint32              fMaxTransactionSize;
  9021. +
  9022. +           uint32              fCurrentCommitID;
  9023. +
  9024. +           LogEntryList        fLogEntries;
  9025. +           mutex               fLogEntriesLock;
  9026. +           bool                fHasSubTransaction;
  9027. +           bool                fSeparateSubTransactions;
  9028. +           int32               fUnwrittenTransactions;
  9029. +           int32               fTransactionID;
  9030. +
  9031. +private:
  9032. +           status_t            _CheckFeatures(JournalSuperBlock* superblock);
  9033. +
  9034. +           uint32              _CountTags(JournalHeader *descriptorBlock);
  9035. +           status_t            _RecoverPassScan(uint32& lastCommitID);
  9036. +           status_t            _RecoverPassRevoke(uint32 lastCommitID);
  9037. +           status_t            _RecoverPassReplay(uint32 lastCommitID);
  9038. +
  9039. +           status_t            _FlushLog(bool canWait, bool flushBlocks);
  9040. +
  9041. +   inline  uint32              _WrapAroundLog(uint32 block);
  9042. +          
  9043. +           size_t              _CurrentTransactionSize() const;
  9044. +           size_t              _FullTransactionSize() const;
  9045. +           size_t              _MainTransactionSize() const;
  9046. +          
  9047. +   virtual status_t            _TransactionDone(bool success);
  9048. +
  9049. +   static  void                _TransactionWritten(int32 transactionID,
  9050. +                                   int32 event, void* _logEntry);
  9051. +   static  void                _TransactionIdle(int32 transactionID,
  9052. +                                   int32 event, void* _journal);
  9053. +};
  9054. +
  9055. +#endif // JOURNAL_H
  9056. +
  9057.  
  9058. Property changes on: src/add-ons/kernel/file_systems/ext2/Journal.h
  9059. ___________________________________________________________________
  9060. Added: svn:executable
  9061.    + *
  9062.  
  9063. Index: src/add-ons/kernel/file_systems/ext2/IndexedDirectoryIterator.h
  9064. ===================================================================
  9065. --- src/add-ons/kernel/file_systems/ext2/IndexedDirectoryIterator.h (revision 38119)
  9066. +++ src/add-ons/kernel/file_systems/ext2/IndexedDirectoryIterator.h (working copy)
  9067. @@ -1,36 +0,0 @@
  9068. -/*
  9069. - * Copyright 2010, Haiku Inc. All rights reserved.
  9070. - * This file may be used under the terms of the MIT License.
  9071. - *
  9072. - * Authors:
  9073. - *     Janito V. Ferreira Filho
  9074. - */
  9075. -#ifndef INDEXED_DIRECTORY_ITERATOR_H
  9076. -#define INDEXED_DIRECTORY_ITERATOR_H
  9077. -
  9078. -
  9079. -#include "DirectoryIterator.h"
  9080. -
  9081. -
  9082. -class HTreeEntryIterator;
  9083. -
  9084. -class IndexedDirectoryIterator : public DirectoryIterator {
  9085. -public:
  9086. -                               IndexedDirectoryIterator(off_t start,
  9087. -                                   uint32 blockSize, Inode* directory,
  9088. -                                   HTreeEntryIterator* parent);
  9089. -   virtual                     ~IndexedDirectoryIterator();
  9090. -  
  9091. -           status_t            GetNext(char* name, size_t* nameLength,
  9092. -                                   ino_t* id);
  9093. -          
  9094. -           status_t            Rewind();
  9095. -private:
  9096. -           bool                fIndexing;
  9097. -           HTreeEntryIterator* fParent;
  9098. -           off_t               fMaxOffset;
  9099. -           uint32              fBlockSize;
  9100. -           uint32              fMaxAttempts;
  9101. -};
  9102. -
  9103. -#endif // INDEXED_DIRECTORY_ITERATOR_H
  9104. Index: src/add-ons/kernel/file_systems/ext2/Transaction.cpp
  9105. ===================================================================
  9106. --- src/add-ons/kernel/file_systems/ext2/Transaction.cpp    (revision 0)
  9107. +++ src/add-ons/kernel/file_systems/ext2/Transaction.cpp    (revision 0)
  9108. @@ -0,0 +1,224 @@
  9109. +/*
  9110. + * Copyright 2001-2010, Haiku Inc. All rights reserved.
  9111. + * This file may be used under the terms of the MIT License.
  9112. + *
  9113. + * Authors:
  9114. + *     Janito V. Ferreira Filho
  9115. + */
  9116. +
  9117. +
  9118. +#include "Transaction.h"
  9119. +
  9120. +#include <string.h>
  9121. +
  9122. +#include <fs_cache.h>
  9123. +
  9124. +#include "Journal.h"
  9125. +
  9126. +
  9127. +//#define TRACE_EXT2
  9128. +#ifdef TRACE_EXT2
  9129. +#  define TRACE(x...) dprintf("\33[34mext2:\33[0m " x)
  9130. +#else
  9131. +#  define TRACE(x...) ;
  9132. +#endif
  9133. +
  9134. +
  9135. +TransactionListener::TransactionListener()
  9136. +{
  9137. +}
  9138. +
  9139. +
  9140. +TransactionListener::~TransactionListener()
  9141. +{
  9142. +}
  9143. +
  9144. +
  9145. +Transaction::Transaction()
  9146. +   :
  9147. +   fJournal(NULL),
  9148. +   fParent(NULL)
  9149. +{
  9150. +}
  9151. +
  9152. +
  9153. +Transaction::Transaction(Journal* journal)
  9154. +   :
  9155. +   fJournal(NULL),
  9156. +   fParent(NULL)
  9157. +{
  9158. +   Start(journal);
  9159. +}
  9160. +
  9161. +
  9162. +Transaction::~Transaction()
  9163. +{
  9164. +   if (IsStarted())
  9165. +       fJournal->Unlock(this, false);
  9166. +}
  9167. +
  9168. +status_t
  9169. +Transaction::Start(Journal* journal)
  9170. +{
  9171. +   if (IsStarted())
  9172. +       return B_OK;
  9173. +
  9174. +   fJournal = journal;
  9175. +   if (fJournal == NULL)
  9176. +       return B_ERROR;
  9177. +  
  9178. +   status_t status = fJournal->Lock(this, false);
  9179. +   if (status != B_OK)
  9180. +       fJournal = NULL;
  9181. +
  9182. +   return status;
  9183. +}
  9184. +
  9185. +
  9186. +status_t
  9187. +Transaction::Done(bool success)
  9188. +{
  9189. +   if (!IsStarted())
  9190. +       return B_OK;
  9191. +
  9192. +   status_t status = fJournal->Unlock(this, success);
  9193. +  
  9194. +   if (status == B_OK)
  9195. +       fJournal = NULL;
  9196. +
  9197. +   return status;
  9198. +}
  9199. +
  9200. +
  9201. +int32
  9202. +Transaction::ID() const
  9203. +{
  9204. +   if (!IsStarted())
  9205. +       return -1;
  9206. +
  9207. +   return fJournal->TransactionID();
  9208. +}
  9209. +
  9210. +
  9211. +bool
  9212. +Transaction::IsStarted() const
  9213. +{
  9214. +   return fJournal != NULL;
  9215. +}
  9216. +
  9217. +
  9218. +bool
  9219. +Transaction::HasParent() const
  9220. +{
  9221. +   return fParent != NULL;
  9222. +}
  9223. +
  9224. +
  9225. +status_t
  9226. +Transaction::WriteBlocks(off_t blockNumber, const uint8* buffer,
  9227. +   size_t numBlocks)
  9228. +{
  9229. +   if (!IsStarted())
  9230. +       return B_NO_INIT;
  9231. +
  9232. +   void* cache = GetVolume()->BlockCache();
  9233. +   size_t blockSize = GetVolume()->BlockSize();
  9234. +
  9235. +   for (size_t i = 0; i < numBlocks; ++i) {
  9236. +       void* block = block_cache_get_empty(cache, blockNumber + i, ID());
  9237. +       if (block == NULL)
  9238. +           return B_ERROR;
  9239. +      
  9240. +       memcpy(block, buffer, blockSize);
  9241. +       buffer += blockSize;
  9242. +
  9243. +       block_cache_put(cache, blockNumber + i);
  9244. +   }
  9245. +
  9246. +   return B_OK;
  9247. +}
  9248. +
  9249. +
  9250. +void
  9251. +Transaction::Split()
  9252. +{
  9253. +   cache_start_sub_transaction(fJournal->GetFilesystemVolume()->BlockCache(),
  9254. +       ID());
  9255. +}
  9256. +
  9257. +
  9258. +Volume*
  9259. +Transaction::GetVolume() const
  9260. +{
  9261. +   if (!IsStarted())
  9262. +       return NULL;
  9263. +
  9264. +   return fJournal->GetFilesystemVolume();
  9265. +}
  9266. +
  9267. +
  9268. +void
  9269. +Transaction::AddListener(TransactionListener* listener)
  9270. +{
  9271. +   TRACE("Transaction::AddListener()\n");
  9272. +   if (!IsStarted())
  9273. +       panic("Transaction is not running!");
  9274. +
  9275. +   fListeners.Add(listener);
  9276. +}
  9277. +
  9278. +
  9279. +void
  9280. +Transaction::RemoveListener(TransactionListener* listener)
  9281. +{
  9282. +   TRACE("Transaction::RemoveListener()\n");
  9283. +   if (!IsStarted())
  9284. +       panic("Transaction is not running!");
  9285. +
  9286. +   fListeners.Remove(listener);
  9287. +   listener->RemovedFromTransaction();
  9288. +}
  9289. +
  9290. +
  9291. +void
  9292. +Transaction::NotifyListeners(bool success)
  9293. +{
  9294. +   TRACE("Transaction::NotifyListeners(): fListeners.First(): %p\n",
  9295. +       fListeners.First());
  9296. +   if (success) {
  9297. +       TRACE("Transaction::NotifyListeners(true): Number of listeners: %ld\n",
  9298. +           fListeners.Count());
  9299. +   } else {
  9300. +       TRACE("Transaction::NotifyListeners(false): Number of listeners: %ld\n",
  9301. +           fListeners.Count());
  9302. +   }
  9303. +   TRACE("Transaction::NotifyListeners(): Finished counting\n");
  9304. +
  9305. +   while (TransactionListener* listener = fListeners.RemoveHead()) {
  9306. +       listener->TransactionDone(success);
  9307. +       listener->RemovedFromTransaction();
  9308. +   }
  9309. +}
  9310. +
  9311. +
  9312. +void
  9313. +Transaction::MoveListenersTo(Transaction* transaction)
  9314. +{
  9315. +   TRACE("Transaction::MoveListenersTo()\n");
  9316. +   while (TransactionListener* listener = fListeners.RemoveHead())
  9317. +       transaction->fListeners.Add(listener);
  9318. +}
  9319. +
  9320. +
  9321. +void
  9322. +Transaction::SetParent(Transaction* transaction)
  9323. +{
  9324. +   fParent = transaction;
  9325. +}
  9326. +
  9327. +
  9328. +Transaction*
  9329. +Transaction::Parent() const
  9330. +{
  9331. +   return fParent;
  9332. +}
  9333. Index: src/add-ons/kernel/file_systems/ext2/ext2.h
  9334. ===================================================================
  9335. --- src/add-ons/kernel/file_systems/ext2/ext2.h (revision 38119)
  9336. +++ src/add-ons/kernel/file_systems/ext2/ext2.h (working copy)
  9337. @@ -13,6 +13,8 @@
  9338.  #include <KernelExport.h>
  9339.  
  9340.  
  9341. +#define TRACE_EXT2
  9342. +
  9343.  #define EXT2_SUPER_BLOCK_OFFSET    1024
  9344.  
  9345.  struct ext2_super_block {
  9346. @@ -108,9 +110,20 @@
  9347.         { return B_LENDIAN_TO_HOST_INT32(read_only_features); }
  9348.     uint32 IncompatibleFeatures() const
  9349.         { return B_LENDIAN_TO_HOST_INT32(incompatible_features); }
  9350. +   ino_t  JournalInode() const
  9351. +       { return B_LENDIAN_TO_HOST_INT32(journal_inode); }
  9352. +   ino_t  LastOrphan() const
  9353. +       { return (ino_t)B_LENDIAN_TO_HOST_INT32(last_orphan); }
  9354.     uint32 HashSeed(uint8 i) const
  9355.         { return B_LENDIAN_TO_HOST_INT32(hash_seed[i]); }
  9356.  
  9357. +   void SetFreeInodes(uint32 freeInodes)
  9358. +       { free_inodes = B_HOST_TO_LENDIAN_INT32(freeInodes); }
  9359. +   void SetFreeBlocks(uint32 freeBlocks)
  9360. +       { free_blocks = B_HOST_TO_LENDIAN_INT32(freeBlocks); }
  9361. +   void SetLastOrphan(ino_t id)
  9362. +       { last_orphan = B_HOST_TO_LENDIAN_INT32((uint32)id); }
  9363. +
  9364.     bool IsValid();
  9365.         // implemented in Volume.cpp
  9366.  } _PACKED;
  9367. @@ -162,8 +175,27 @@
  9368.     uint16  _padding;
  9369.     uint32  _reserved[3];
  9370.  
  9371. -   uint32 InodeTable() const
  9372. +   uint32  BlockBitmap() const
  9373. +       { return B_LENDIAN_TO_HOST_INT32(block_bitmap); }
  9374. +   uint32  InodeBitmap() const
  9375. +       { return B_LENDIAN_TO_HOST_INT32(inode_bitmap); }
  9376. +   uint32  InodeTable() const
  9377.         { return B_LENDIAN_TO_HOST_INT32(inode_table); }
  9378. +   uint16  FreeBlocks() const
  9379. +       { return B_LENDIAN_TO_HOST_INT16(free_blocks); }
  9380. +   uint16  FreeInodes() const
  9381. +       { return B_LENDIAN_TO_HOST_INT16(free_inodes); }
  9382. +   uint16  UsedDirectories() const
  9383. +       { return B_LENDIAN_TO_HOST_INT16(used_directories); }
  9384. +
  9385. +   void    SetFreeBlocks(uint16 freeBlocks)
  9386. +       { free_blocks = B_HOST_TO_LENDIAN_INT16(freeBlocks); }
  9387. +
  9388. +   void    SetFreeInodes(uint16 freeInodes)
  9389. +       { free_inodes = B_HOST_TO_LENDIAN_INT16(freeInodes); }
  9390. +
  9391. +   void    SetUsedDirectories(uint16 usedDirectories)
  9392. +       { used_directories = B_HOST_TO_LENDIAN_INT16(usedDirectories); }
  9393.  } _PACKED;
  9394.  
  9395.  #define EXT2_DIRECT_BLOCKS         12
  9396. @@ -214,11 +246,13 @@
  9397.     uint16 Mode() const { return B_LENDIAN_TO_HOST_INT16(mode); }
  9398.     uint32 Flags() const { return B_LENDIAN_TO_HOST_INT32(flags); }
  9399.     uint16 NumLinks() const { return B_LENDIAN_TO_HOST_INT16(num_links); }
  9400. +   uint32 NumBlocks() const { return B_LENDIAN_TO_HOST_INT32(num_blocks); }
  9401.  
  9402.     time_t AccessTime() const { return B_LENDIAN_TO_HOST_INT32(access_time); }
  9403.     time_t CreationTime() const { return B_LENDIAN_TO_HOST_INT32(creation_time); }
  9404.     time_t ModificationTime() const { return B_LENDIAN_TO_HOST_INT32(modification_time); }
  9405.     time_t DeletionTime() const { return B_LENDIAN_TO_HOST_INT32(deletion_time); }
  9406. +   ino_t  NextOrphan() const { return (ino_t)DeletionTime(); }
  9407.  
  9408.     off_t Size() const
  9409.     {
  9410. @@ -241,6 +275,80 @@
  9411.         return B_LENDIAN_TO_HOST_INT16(gid)
  9412.             | (B_LENDIAN_TO_HOST_INT16(gid_high) << 16);
  9413.     }
  9414. +
  9415. +   void SetMode(uint16 newMode)
  9416. +   {
  9417. +       mode = B_LENDIAN_TO_HOST_INT16(newMode);
  9418. +   }
  9419. +
  9420. +   void UpdateMode(uint16 newMode, uint16 mask)
  9421. +   {
  9422. +       SetMode((Mode() & ~mask) | (newMode & mask));
  9423. +   }
  9424. +
  9425. +   void SetFlag(uint32 mask)
  9426. +   {
  9427. +       flags |= B_HOST_TO_LENDIAN_INT32(mask);
  9428. +   }
  9429. +
  9430. +   void SetFlags(uint32 newFlags)
  9431. +   {
  9432. +       flags = B_HOST_TO_LENDIAN_INT32(newFlags);
  9433. +   }
  9434. +
  9435. +   void SetNumLinks(uint16 numLinks)
  9436. +   {
  9437. +       num_links = B_HOST_TO_LENDIAN_INT16(numLinks);
  9438. +   }
  9439. +
  9440. +   void SetNumBlocks(uint32 numBlocks)
  9441. +   {
  9442. +       num_blocks = B_HOST_TO_LENDIAN_INT32(numBlocks);
  9443. +   }
  9444. +
  9445. +   void SetAccessTime(time_t accessTime)
  9446. +   {
  9447. +       access_time = B_HOST_TO_LENDIAN_INT32((uint32)accessTime);
  9448. +   }
  9449. +
  9450. +   void SetCreationTime(time_t creationTime)
  9451. +   {
  9452. +       creation_time = B_HOST_TO_LENDIAN_INT32((uint32)creationTime);
  9453. +   }
  9454. +
  9455. +   void SetModificationTime(time_t modificationTime)
  9456. +   {
  9457. +       modification_time = B_HOST_TO_LENDIAN_INT32((uint32)modificationTime);
  9458. +   }
  9459. +
  9460. +   void SetDeletionTime(time_t deletionTime)
  9461. +   {
  9462. +       deletion_time = B_HOST_TO_LENDIAN_INT32((uint32)deletionTime);
  9463. +   }
  9464. +
  9465. +   void SetNextOrphan(ino_t id)
  9466. +   {
  9467. +       deletion_time = B_HOST_TO_LENDIAN_INT32((uint32)id);
  9468. +   }
  9469. +
  9470. +   void SetSize(off_t newSize)
  9471. +   {
  9472. +       size = B_HOST_TO_LENDIAN_INT32(newSize & 0xFFFFFFFF);
  9473. +       if (S_ISREG(Mode()))
  9474. +           size_high = B_HOST_TO_LENDIAN_INT32(newSize >> 32);
  9475. +   }
  9476. +
  9477. +   void SetUserID(uint32 newUID)
  9478. +   {
  9479. +       uid = B_HOST_TO_LENDIAN_INT16(newUID & 0xFFFF);
  9480. +       uid_high = B_HOST_TO_LENDIAN_INT16(newUID >> 16);
  9481. +   }
  9482. +
  9483. +   void SetGroupID(uint32 newGID)
  9484. +   {
  9485. +       gid = B_HOST_TO_LENDIAN_INT16(newGID & 0xFFFF);
  9486. +       gid_high = B_HOST_TO_LENDIAN_INT16(newGID >> 16);
  9487. +   }
  9488.  } _PACKED;
  9489.  
  9490.  #define EXT2_SUPER_BLOCK_MAGIC         0xef53
  9491. @@ -270,11 +378,27 @@
  9492.     uint8   file_type;
  9493.     char    name[EXT2_NAME_LENGTH];
  9494.  
  9495. -   uint32 InodeID() const { return B_LENDIAN_TO_HOST_INT32(inode_id); }
  9496. -   uint16 Length() const { return B_LENDIAN_TO_HOST_INT16(length); }
  9497. -   uint8 NameLength() const { return name_length; }
  9498. -   uint8 FileType() const { return file_type; }
  9499. +   uint32  InodeID() const { return B_LENDIAN_TO_HOST_INT32(inode_id); }
  9500. +   uint16  Length() const { return B_LENDIAN_TO_HOST_INT16(length); }
  9501. +   uint8   NameLength() const { return name_length; }
  9502. +   uint8   FileType() const { return file_type; }
  9503.  
  9504. +   void    SetInodeID(uint32 id) { inode_id = B_HOST_TO_LENDIAN_INT32(id); }
  9505. +
  9506. +   void    SetLength(uint16 newLength/*uint8 nameLength*/)
  9507. +   {
  9508. +       length = B_HOST_TO_LENDIAN_INT16(newLength);
  9509. +       /*name_length = nameLength;
  9510. +
  9511. +       if (nameLength % 4 == 0) {
  9512. +           length = B_HOST_TO_LENDIAN_INT16(
  9513. +               (short)(nameLength + MinimumSize()));
  9514. +       } else {
  9515. +           length = B_HOST_TO_LENDIAN_INT16(
  9516. +               (short)(nameLength % 4 + 1 + MinimumSize()));
  9517. +       }*/
  9518. +   }
  9519. +
  9520.     bool IsValid() const
  9521.     {
  9522.         return Length() > MinimumSize();
  9523. @@ -370,6 +494,17 @@
  9524.  } _PACKED;
  9525.  
  9526.  
  9527. +struct file_cookie {
  9528. +   bigtime_t   last_notification;
  9529. +   off_t       last_size;
  9530. +   int         open_mode;
  9531. +};
  9532. +
  9533. +#define EXT2_OPEN_MODE_USER_MASK       0x7fffffff
  9534. +
  9535. +#define INODE_NOTIFICATION_INTERVAL        10000000LL
  9536. +
  9537. +
  9538.  extern fs_volume_ops gExt2VolumeOps;
  9539.  extern fs_vnode_ops gExt2VnodeOps;
  9540.  
  9541. Index: src/add-ons/kernel/file_systems/ext2/CachedBlock.h
  9542. ===================================================================
  9543. --- src/add-ons/kernel/file_systems/ext2/CachedBlock.h  (revision 38119)
  9544. +++ src/add-ons/kernel/file_systems/ext2/CachedBlock.h  (working copy)
  9545. @@ -9,32 +9,40 @@
  9546.  
  9547.  #include <fs_cache.h>
  9548.  
  9549. +#include "Transaction.h"
  9550.  #include "Volume.h"
  9551.  
  9552.  
  9553.  class CachedBlock {
  9554.  public:
  9555. -                   CachedBlock(Volume* volume);
  9556. -                   CachedBlock(Volume* volume, uint32 block);
  9557. -                   ~CachedBlock();
  9558. +                           CachedBlock(Volume* volume);
  9559. +                           CachedBlock(Volume* volume, uint32 block);
  9560. +                           ~CachedBlock();
  9561.  
  9562. -           void    Keep();
  9563. -           void    Unset();
  9564. +           void            Keep();
  9565. +           void            Unset();
  9566.  
  9567. -   const   uint8*  SetTo(uint32 block);
  9568. +           const uint8*    SetTo(uint32 block);
  9569. +           uint8*          SetToWritable(Transaction& transaction,
  9570. +                               uint32 block, bool empty = false);
  9571. +           uint8*          SetToWritableWithoutTransaction(uint32 block,
  9572. +                               bool empty = false);
  9573.  
  9574. -   const   uint8*  Block() const { return fBlock; }
  9575. -           off_t   BlockNumber() const { return fBlockNumber; }
  9576. +           const uint8*    Block() const { return fBlock; }
  9577. +           off_t           BlockNumber() const { return fBlockNumber; }
  9578.  
  9579.  private:
  9580. -                   CachedBlock(const CachedBlock &);
  9581. -                   CachedBlock &operator=(const CachedBlock &);
  9582. -                       // no implementation
  9583. +                           CachedBlock(const CachedBlock &);
  9584. +                           CachedBlock &operator=(const CachedBlock &);
  9585. +                               // no implementation
  9586. +                      
  9587. +           uint8*          _SetToWritableEtc(int32 transaction, uint32 block,
  9588. +                               bool empty);
  9589.  
  9590.  protected:
  9591. -   Volume*         fVolume;
  9592. -   uint32          fBlockNumber;
  9593. -   uint8*          fBlock;
  9594. +           Volume*         fVolume;
  9595. +           uint32          fBlockNumber;
  9596. +           uint8*          fBlock;
  9597.  };
  9598.  
  9599.  
  9600. @@ -94,4 +102,35 @@
  9601.     return fBlock = (uint8 *)block_cache_get(fVolume->BlockCache(), block);
  9602.  }
  9603.  
  9604. +
  9605. +inline uint8*
  9606. +CachedBlock::SetToWritable(Transaction& transaction, uint32 block, bool empty)
  9607. +{
  9608. +   return _SetToWritableEtc(transaction.ID(), block, empty);
  9609. +}
  9610. +
  9611. +
  9612. +inline uint8*
  9613. +CachedBlock::SetToWritableWithoutTransaction(uint32 block, bool empty)
  9614. +{
  9615. +   return _SetToWritableEtc((int32)-1, block, empty);
  9616. +}
  9617. +
  9618. +inline uint8*
  9619. +CachedBlock::_SetToWritableEtc(int32 transaction, uint32 block, bool empty)
  9620. +{
  9621. +   Unset();
  9622. +   fBlockNumber = block;
  9623. +
  9624. +   if (empty) {
  9625. +       fBlock = (uint8*)block_cache_get_empty(fVolume->BlockCache(),
  9626. +           block, transaction);
  9627. +   } else {
  9628. +       fBlock = (uint8*)block_cache_get_writable(fVolume->BlockCache(),
  9629. +           block, transaction);
  9630. +   }
  9631. +
  9632. +   return fBlock;
  9633. +}
  9634. +
  9635.  #endif // CACHED_BLOCK_H
  9636. Index: src/add-ons/kernel/file_systems/ext2/HashRevokeManager.cpp
  9637. ===================================================================
  9638. --- src/add-ons/kernel/file_systems/ext2/HashRevokeManager.cpp  (revision 0)
  9639. +++ src/add-ons/kernel/file_systems/ext2/HashRevokeManager.cpp  (revision 0)
  9640. @@ -0,0 +1,170 @@
  9641. +/*
  9642. + * Copyright 2001-2010, Haiku Inc. All rights reserved.
  9643. + * This file may be used under the terms of the MIT License.
  9644. + *
  9645. + * Authors:
  9646. + *     Janito V. Ferreira Filho
  9647. + */
  9648. +
  9649. +
  9650. +#include "HashRevokeManager.h"
  9651. +
  9652. +#include <new>
  9653. +
  9654. +
  9655. +//#define TRACE_EXT2
  9656. +#ifdef TRACE_EXT2
  9657. +#  define TRACE(x...) dprintf("\33[34mext2:\33[0m " x)
  9658. +#else
  9659. +#  define TRACE(x...) ;
  9660. +#endif
  9661. +
  9662. +
  9663. +HashRevokeManager::HashRevokeManager()
  9664. +   :
  9665. +   fHash(NULL),
  9666. +   kInitialHashSize(128)
  9667. +       // TODO: Benchmark and find an optimal value
  9668. +{
  9669. +}
  9670. +
  9671. +
  9672. +HashRevokeManager::~HashRevokeManager()
  9673. +{
  9674. +   if (fHash != NULL) {
  9675. +       if (fRevokeCount != 0) {
  9676. +           RevokeElement *element =
  9677. +               (RevokeElement*)hash_remove_first(fHash, NULL);
  9678. +
  9679. +           while (element != NULL) {
  9680. +               delete element;
  9681. +               element = (RevokeElement*)hash_remove_first(fHash, NULL);
  9682. +           }
  9683. +       }
  9684. +
  9685. +       hash_uninit(fHash);
  9686. +   }
  9687. +}
  9688. +
  9689. +
  9690. +status_t
  9691. +HashRevokeManager::Init()
  9692. +{
  9693. +   RevokeElement dummyElement;
  9694. +  
  9695. +   fHash = hash_init(kInitialHashSize, offset_of_member(dummyElement, next),
  9696. +       &HashRevokeManager::Compare,
  9697. +       &HashRevokeManager::Hash);
  9698. +
  9699. +   if (fHash == NULL)
  9700. +       return B_NO_MEMORY;
  9701. +
  9702. +   return B_OK;
  9703. +}
  9704. +
  9705. +
  9706. +status_t
  9707. +HashRevokeManager::Insert(uint32 block, uint32 commitID)
  9708. +{
  9709. +   RevokeElement* element = (RevokeElement*)hash_lookup(fHash, &block);
  9710. +  
  9711. +   if (element != NULL) {
  9712. +       TRACE("HashRevokeManager::Insert(): Already has an element\n");
  9713. +       if (element->commitID < commitID) {
  9714. +           TRACE("HashRevokeManager::Insert(): Deleting previous element\n");
  9715. +           status_t retValue = hash_remove(fHash, element);
  9716. +          
  9717. +           if (retValue != B_OK)
  9718. +               return retValue;
  9719. +
  9720. +           delete element;
  9721. +       }
  9722. +       else {
  9723. +           return B_OK;
  9724. +               // We already have a newer version of the block
  9725. +       }
  9726. +   }
  9727. +
  9728. +   return _ForceInsert(block, commitID);
  9729. +}
  9730. +
  9731. +
  9732. +status_t
  9733. +HashRevokeManager::Remove(uint32 block)
  9734. +{
  9735. +   RevokeElement* element = (RevokeElement*)hash_lookup(fHash, &block);
  9736. +
  9737. +   if (element == NULL)
  9738. +       return B_ERROR; // TODO: Perhaps we should just ignore?
  9739. +
  9740. +   status_t retValue = hash_remove(fHash, element);
  9741. +  
  9742. +   if (retValue == B_OK)
  9743. +       delete element;
  9744. +
  9745. +   return retValue;
  9746. +}
  9747. +
  9748. +
  9749. +bool
  9750. +HashRevokeManager::Lookup(uint32 block, uint32 commitID)
  9751. +{
  9752. +   RevokeElement* element = (RevokeElement*)hash_lookup(fHash, &block);
  9753. +
  9754. +   if (element == NULL)
  9755. +       return false;
  9756. +
  9757. +   return element->commitID >= commitID;
  9758. +}
  9759. +
  9760. +
  9761. +/*static*/ int
  9762. +HashRevokeManager::Compare(void* _revoked, const void *_block)
  9763. +{
  9764. +   RevokeElement* revoked = (RevokeElement*)_revoked;
  9765. +   uint32 block = *(uint32*)_block;
  9766. +
  9767. +   if (revoked->block == block)
  9768. +       return 0;
  9769. +
  9770. +   return (revoked->block > block) ? 1 : -1;
  9771. +}
  9772. +
  9773. +
  9774. +/*static*/ uint32
  9775. +HashRevokeManager::Hash(void* _revoked, const void* _block, uint32 range)
  9776. +{
  9777. +   TRACE("HashRevokeManager::Hash(): revoked: %p, block: %p, range: %lu\n",
  9778. +       _revoked, _block, range);
  9779. +   RevokeElement* revoked = (RevokeElement*)_revoked;
  9780. +
  9781. +   if (revoked != NULL)
  9782. +       return revoked->block % range;
  9783. +
  9784. +   uint32 block = *(uint32*)_block;
  9785. +   return block % range;
  9786. +}
  9787. +
  9788. +
  9789. +status_t
  9790. +HashRevokeManager::_ForceInsert(uint32 block, uint32 commitID)
  9791. +{
  9792. +   RevokeElement* element = new(std::nothrow) RevokeElement;
  9793. +
  9794. +   if (element == NULL)
  9795. +       return B_NO_MEMORY;
  9796. +
  9797. +   element->block = block;
  9798. +   element->commitID = commitID;
  9799. +
  9800. +   status_t retValue = hash_insert_grow(fHash, element);
  9801. +
  9802. +   if (retValue == B_OK) {
  9803. +       fRevokeCount++;
  9804. +       TRACE("HashRevokeManager::_ForceInsert(): revoke count: %lu\n",
  9805. +           fRevokeCount);
  9806. +   }
  9807. +
  9808. +   return retValue;
  9809. +}
  9810. +
  9811.  
  9812. Property changes on: src/add-ons/kernel/file_systems/ext2/HashRevokeManager.cpp
  9813. ___________________________________________________________________
  9814. Added: svn:executable
  9815.    + *
  9816.  
  9817. Index: src/add-ons/kernel/file_systems/ext2/DataStream.h
  9818. ===================================================================
  9819. --- src/add-ons/kernel/file_systems/ext2/DataStream.h   (revision 0)
  9820. +++ src/add-ons/kernel/file_systems/ext2/DataStream.h   (revision 0)
  9821. @@ -0,0 +1,94 @@
  9822. +/*
  9823. + * Copyright 2001-2010, Haiku Inc. All rights reserved.
  9824. + * This file may be used under the terms of the MIT License.
  9825. + *
  9826. + * Authors:
  9827. + *     Janito V. Ferreira Filho
  9828. + */
  9829. +#ifndef DATASTREAM_H
  9830. +#define DATASTREAM_H
  9831. +
  9832. +#include "ext2.h"
  9833. +#include "Transaction.h"
  9834. +
  9835. +
  9836. +class Volume;
  9837. +
  9838. +
  9839. +class DataStream
  9840. +{
  9841. +public:
  9842. +                   DataStream(Volume* volume, ext2_data_stream* stream,
  9843. +                       off_t size);
  9844. +                   ~DataStream();
  9845. +
  9846. +   status_t        Enlarge(Transaction& transaction, uint32 numBlocks);
  9847. +   status_t        Shrink(Transaction& transaction, uint32 numBlocks);
  9848. +
  9849. +private:
  9850. +   uint32          _BlocksNeeded(uint32 end);
  9851. +
  9852. +   status_t        _GetBlock(Transaction& transaction, uint32& block);
  9853. +   status_t        _PrepareBlock(Transaction& transaction, uint32* pos,
  9854. +                       uint32& blockNum, bool& clear);
  9855. +
  9856. +   status_t        _AddBlocks(Transaction& transaction, uint32* block,
  9857. +                       uint32 count);
  9858. +   status_t        _AddBlocks(Transaction& transaction, uint32* block,
  9859. +                       uint32 start, uint32 end, int recursion);
  9860. +
  9861. +   status_t        _AddForDirectBlocks(Transaction& transaction,
  9862. +                       uint32 numBlocks);
  9863. +   status_t        _AddForIndirectBlock(Transaction& transaction,
  9864. +                       uint32 numBlocks);
  9865. +   status_t        _AddForDoubleIndirectBlock(Transaction& transaction,
  9866. +                       uint32 numBlocks);
  9867. +   status_t        _AddForTripleIndirectBlock(Transaction& transaction,
  9868. +                       uint32 numBlocks);
  9869. +
  9870. +   status_t        _PerformFree(Transaction& transaction);
  9871. +   status_t        _MarkBlockForRemoval(Transaction& transaction,
  9872. +                       uint32* block);
  9873. +
  9874. +   status_t        _FreeBlocks(Transaction& transaction, uint32* block,
  9875. +                       uint32 count);
  9876. +   status_t        _FreeBlocks(Transaction& transaction, uint32* block,
  9877. +                       uint32 start, uint32 end, bool freeParent,
  9878. +                       int recursion);
  9879. +
  9880. +   status_t        _RemoveFromDirectBlocks(Transaction& transaction,
  9881. +                       uint32 numBlocks);
  9882. +   status_t        _RemoveFromIndirectBlock(Transaction& transaction,
  9883. +                       uint32 numBlocks);
  9884. +   status_t        _RemoveFromDoubleIndirectBlock(Transaction& transaction,
  9885. +                       uint32 numBlocks);
  9886. +   status_t        _RemoveFromTripleIndirectBlock(Transaction& transaction,
  9887. +                       uint32 numBlocks);
  9888. +
  9889. +
  9890. +   const uint32    kBlockSize;
  9891. +   const uint32    kIndirectsPerBlock;
  9892. +   const uint32    kIndirectsPerBlock2;
  9893. +   const uint32    kIndirectsPerBlock3;
  9894. +
  9895. +   const uint32    kMaxDirect;
  9896. +   const uint32    kMaxIndirect;
  9897. +   const uint32    kMaxDoubleIndirect;
  9898. +
  9899. +   Volume*         fVolume;
  9900. +   ext2_data_stream* fStream;
  9901. +   uint32          fFirstBlock;
  9902. +
  9903. +   uint32          fAllocated;
  9904. +   uint32          fAllocatedPos;
  9905. +   uint32          fWaiting;
  9906. +
  9907. +   uint32          fFreeStart;
  9908. +   uint32          fFreeCount;
  9909. +
  9910. +   uint32          fNumBlocks;
  9911. +   uint32          fRemovedBlocks;
  9912. +};
  9913. +
  9914. +#endif // DATASTREAM_H
  9915. +
  9916. Index: src/add-ons/kernel/file_systems/ext2/RevokeManager.h
  9917. ===================================================================
  9918. --- src/add-ons/kernel/file_systems/ext2/RevokeManager.h    (revision 0)
  9919. +++ src/add-ons/kernel/file_systems/ext2/RevokeManager.h    (revision 0)
  9920. @@ -0,0 +1,35 @@
  9921. +/*
  9922. + * Copyright 2001-2010, Haiku Inc. All rights reserved.
  9923. + * This file may be used under the terms of the MIT License.
  9924. + *
  9925. + * Authors:
  9926. + *     Janito V. Ferreira Filho
  9927. + */
  9928. +#ifndef REVOKEMANAGER_H
  9929. +#define REVOKEMANAGER_H
  9930. +
  9931. +#include "Journal.h"
  9932. +
  9933. +
  9934. +struct JournalRevokeHeader;
  9935. +
  9936. +class RevokeManager {
  9937. +public:
  9938. +                       RevokeManager();
  9939. +   virtual             ~RevokeManager() = 0;
  9940. +
  9941. +   virtual status_t    Insert(uint32 block, uint32 commitID) = 0;
  9942. +   virtual status_t    Remove(uint32 block) = 0;
  9943. +   virtual bool        Lookup(uint32 block, uint32 commitID) = 0;
  9944. +          
  9945. +           uint32      NumRevokes() { return fRevokeCount; }
  9946. +
  9947. +           status_t    ScanRevokeBlock(JournalRevokeHeader* revokeBlock,
  9948. +                           uint32 commitID);
  9949. +
  9950. +protected:
  9951. +           uint32      fRevokeCount;
  9952. +};
  9953. +
  9954. +#endif // REVOKEMANAGER_H
  9955. +
  9956.  
  9957. Property changes on: src/add-ons/kernel/file_systems/ext2/RevokeManager.h
  9958. ___________________________________________________________________
  9959. Added: svn:executable
  9960.    + *
  9961.  
  9962. Index: src/add-ons/kernel/file_systems/ext2/BitmapBlock.h
  9963. ===================================================================
  9964. --- src/add-ons/kernel/file_systems/ext2/BitmapBlock.h  (revision 0)
  9965. +++ src/add-ons/kernel/file_systems/ext2/BitmapBlock.h  (revision 0)
  9966. @@ -0,0 +1,48 @@
  9967. +/*
  9968. + * Copyright 2001-2010, Haiku Inc. All rights reserved.
  9969. + * This file may be used under the terms of the MIT License.
  9970. + *
  9971. + * Authors:
  9972. + *     Janito V. Ferreira Filho
  9973. + */
  9974. +#ifndef BITMAPBLOCK_H
  9975. +#define BITMAPBLOCK_H
  9976. +
  9977. +#include "CachedBlock.h"
  9978. +
  9979. +
  9980. +class BitmapBlock : public CachedBlock {
  9981. +public:
  9982. +                           BitmapBlock(Volume* volume, uint32 numBits);
  9983. +                           ~BitmapBlock();
  9984. +
  9985. +           bool            SetTo(uint32 block);
  9986. +           bool            SetToWritable(Transaction& transaction,
  9987. +                               uint32 block, bool empty = false);
  9988. +
  9989. +           bool            CheckMarked(uint32 start, uint32 length);
  9990. +           bool            CheckUnmarked(uint32 start, uint32 length);
  9991. +
  9992. +           bool            Mark(uint32 start, uint32 length,
  9993. +                               bool force = false);
  9994. +           bool            Unmark(uint32 start, uint32 length,
  9995. +                               bool force = false);
  9996. +
  9997. +           void            FindNextMarked(uint32& pos);
  9998. +           void            FindNextUnmarked(uint32& pos);
  9999. +
  10000. +           void            FindPreviousMarked(uint32& pos);
  10001. +
  10002. +           void            FindLargestUnmarkedRange(uint32& start,
  10003. +                               uint32& length);
  10004. +
  10005. +           uint32          NumBits() const;
  10006. +
  10007. +protected:
  10008. +           uint32*         fData;
  10009. +           const uint32*   fReadOnlyData;
  10010. +
  10011. +           uint32          fNumBits;
  10012. +};
  10013. +
  10014. +#endif // BITMAPBLOCK_H
  10015.  
  10016. Property changes on: src/add-ons/kernel/file_systems/ext2/BitmapBlock.h
  10017. ___________________________________________________________________
  10018. Added: svn:executable
  10019.    + *
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement