Advertisement
Guest User

Untitled

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