Advertisement
Guest User

Untitled

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