Advertisement
Guest User

Untitled

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