2 * Copyright (c) 2000 Apple Computer, Inc. All rights reserved.
4 * @APPLE_LICENSE_HEADER_START@
6 * This file contains Original Code and/or Modifications of Original Code
7 * as defined in and that are subject to the Apple Public Source License
8 * Version 2.0 (the 'License'). You may not use this file except in
9 * compliance with the License. Please obtain a copy of the License at
10 * http://www.opensource.apple.com/apsl/ and read it before using this
13 * The Original Code and all software distributed under the License are
14 * distributed on an 'AS IS' basis, WITHOUT WARRANTY OF ANY KIND, EITHER
15 * EXPRESS OR IMPLIED, AND APPLE HEREBY DISCLAIMS ALL SUCH WARRANTIES,
16 * INCLUDING WITHOUT LIMITATION, ANY WARRANTIES OF MERCHANTABILITY,
17 * FITNESS FOR A PARTICULAR PURPOSE, QUIET ENJOYMENT OR NON-INFRINGEMENT.
18 * Please see the License for the specific language governing rights and
19 * limitations under the License.
21 * @APPLE_LICENSE_HEADER_END@
26 Contains: Multi-node tree operations for the BTree Module.
28 Version: xxx put the technology version here xxx
30 Written by: Gordon Sheridan and Bill Bruffey
32 Copyright: © 1992-1999 by Apple Computer, Inc., all rights reserved.
38 Other Contact: Mark Day
40 Technology: File Systems
48 Change History (most recent first):
50 <MOSXS> 6/1/99 djb Sync up with Mac OS 8.6.
51 <CS5> 12/8/97 djb Radar #2200632, CollapseTree wasn't marking root node dirty.
52 <CS4> 11/24/97 djb Radar #2005325, InsertLevel incorrectly handled root splits!
53 <CS3> 10/17/97 msd Conditionalize DebugStrs.
54 <CS2> 5/16/97 msd InsertNode() needs a return statement in ErrorExit.
55 <CS1> 4/23/97 djb first checked in
57 <HFS8> 3/17/97 DSH Conditionalize out Panic assertion for SC.
58 <HFS7> 3/3/97 djb Removed DebugStr in InsertLevel.
59 <HFS6> 2/19/97 djb Major re-write of insert code; added InsertLevel and InsertNode.
60 <HFS5> 1/27/97 djb InsertTree and DeleteTree are now recursive and support variable
62 <HFS4> 1/16/97 djb Removed DebugStr in SearchTree. Added initial support for
63 variable sized index keys.
64 <HFS3> 1/3/97 djb Changed len8 to length8.
65 <HFS2> 1/3/97 djb Added support for large keys.
66 <HFS1> 12/19/96 djb first checked in
68 History applicable to original Scarecrow Design:
70 <3> 10/25/96 ser Changing for new VFPI
71 <2> 1/22/96 dkh Add #include Memory.h
72 <1> 10/18/95 rst Moved from Scarecrow project.
74 <12> 7/18/95 mbb Change MoveData & ClearBytes to BlockMoveData & BlockZero.
75 <11> 9/30/94 prp Get in sync with D2 interface changes.
76 <10> 7/25/94 wjk Eliminate usage of BytePtr in favor of UInt8 *.
77 <9> 7/22/94 wjk Convert to the new set of header files.
78 <8> 12/2/93 wjk Move from Makefiles to BuildFiles. Fit into the ModernOS and
80 <7> 11/30/93 wjk Change some Ptr's to BytePtr's in function definitions so they
81 agree with their prototypes.
82 <6> 5/21/93 gs Debug DeleteTree. Modify InsertTree for BTReplaceRecord.
83 <5> 5/10/93 gs Modify RotateLeft, and add DeleteTree, CollapseTree routines.
84 <4> 3/23/93 gs revise RotateLeft to use InsertKeyRecord instead of
86 <3> 3/23/93 gs Implement SplitLeft, InsertTree routine.
87 <2> 2/8/93 gs Implement SearchTree, and RotateLeft.
88 <1> 11/15/92 gs first checked in
92 #include "../headers/BTreesPrivate.h"
95 /////////////////////// Routines Internal To BTree Module ///////////////////////
100 ////////////////////// Routines Internal To BTreeTreeOps.c //////////////////////
102 static OSStatus
AddNewRootNode (BTreeControlBlockPtr btreePtr
,
103 NodeDescPtr leftNode
,
104 NodeDescPtr rightNode
);
106 static OSStatus
CollapseTree (BTreeControlBlockPtr btreePtr
,
107 BlockDescriptor
*blockPtr
);
109 static OSStatus
RotateLeft (BTreeControlBlockPtr btreePtr
,
110 NodeDescPtr leftNode
,
111 NodeDescPtr rightNode
,
112 UInt16 rightInsertIndex
,
117 UInt32
*insertNodeNum
,
119 UInt16
*recsRotated
);
121 static Boolean
RotateRecordLeft (BTreeControlBlockPtr btreePtr
,
122 NodeDescPtr leftNode
,
123 NodeDescPtr rightNode
);
125 static OSStatus
SplitLeft (BTreeControlBlockPtr btreePtr
,
126 BlockDescriptor
*leftNode
,
127 BlockDescriptor
*rightNode
,
134 UInt32
*insertNodeNum
,
135 UInt16
*recsRotated
);
139 static OSStatus
InsertLevel (BTreeControlBlockPtr btreePtr
,
140 TreePathTable treePathTable
,
141 InsertKey
*primaryKey
,
142 InsertKey
*secondaryKey
,
143 BlockDescriptor
*targetNode
,
146 UInt32
*insertNode
);
148 static OSErr
InsertNode (BTreeControlBlockPtr btreePtr
,
150 BlockDescriptor
*rightNode
,
155 BlockDescriptor
*leftNode
,
156 Boolean
*updateParent
,
157 Boolean
*insertParent
,
158 Boolean
*rootSplit
);
160 static UInt16
GetKeyLength (const BTreeControlBlock
*btreePtr
,
162 Boolean forLeafNode
);
166 //////////////////////// BTree Multi-node Tree Operations ///////////////////////
169 /*-------------------------------------------------------------------------------
171 Routine: SearchTree - Search BTree for key and set up Tree Path Table.
173 Function: Searches BTree for specified key, setting up the Tree Path Table to
174 reflect the search path.
177 Input: btreePtr - pointer to control block of BTree to search
178 keyPtr - pointer to the key to search for
179 treePathTable - pointer to the tree path table to construct
181 Output: nodeNum - number of the node containing the key position
182 iterator - BTreeIterator specifying record or insert position
184 Result: noErr - key found, index is record index
185 fsBTRecordNotFoundErr - key not found, index is insert index
186 fsBTEmptyErr - key not found, return params are nil
187 otherwise - catastrophic failure (GetNode/ReleaseNode failed)
188 -------------------------------------------------------------------------------*/
190 OSStatus
SearchTree (BTreeControlBlockPtr btreePtr
,
191 BTreeKeyPtr searchKey
,
192 TreePathTable treePathTable
,
194 BlockDescriptor
*nodePtr
,
195 UInt16
*returnIndex
)
198 SInt16 level
; // Expected depth of current node
199 UInt32 curNodeNum
; // Current node we're searching
203 SInt8 nodeKind
; // Kind of current node (index/leaf)
209 curNodeNum
= btreePtr
->rootNode
;
210 level
= btreePtr
->treeDepth
;
212 if (level
== 0) // is the tree empty?
218 //\80\80 for debugging...
219 treePathTable
[0].node
= 0;
220 treePathTable
[0].index
= 0;
225 // [2550929] Node number 0 is the header node. It is never a valid
226 // index or leaf node. If we're ever asked to search through node 0,
227 // something has gone wrong (typically a bad child node number, or
228 // we found a node full of zeroes that we thought was an index node).
232 // Panic("\pSearchTree: curNodeNum is zero!");
237 err
= GetNode (btreePtr
, curNodeNum
, &nodeRec
);
244 // [2550929] Sanity check the node height and node type. We expect
245 // particular values at each iteration in the search. This checking
246 // quickly finds bad pointers, loops, and other damage to the
247 // hierarchy of the B-tree.
249 if (((BTNodeDescriptor
*)nodeRec
.buffer
)->height
!= level
)
251 // Panic("\pIncorrect node height");
255 nodeKind
= ((BTNodeDescriptor
*)nodeRec
.buffer
)->kind
;
258 // Nodes at level 1 must be leaves, by definition
259 if (nodeKind
!= kBTLeafNode
)
261 // Panic("\pIncorrect node type: expected leaf");
268 // A node at any other depth must be an index node
269 if (nodeKind
!= kBTIndexNode
)
271 // Panic("\pIncorrect node type: expected index");
277 keyFound
= SearchNode (btreePtr
, nodeRec
.buffer
, searchKey
, &index
);
279 treePathTable
[level
].node
= curNodeNum
;
281 if (nodeKind
== kBTLeafNode
)
283 treePathTable
[level
].index
= index
;
284 break; // were done...
287 if ( (keyFound
!= true) && (index
!= 0))
290 treePathTable
[level
].index
= index
;
292 err
= GetRecordByIndex (btreePtr
, nodeRec
.buffer
, index
, &keyPtr
, &dataPtr
, &dataSize
);
295 // [2550929] If we got an error, it is probably because the index was bad
296 // (typically a corrupt node that confused SearchNode). Invalidate the node
297 // so we won't accidentally use the corrupted contents. NOTE: the Mac OS 9
298 // sources call this InvalidateNode.
300 (void) TrashNode(btreePtr
, &nodeRec
);
304 // Get the child pointer out of this index node. We're now done with the current
305 // node and can continue the search with the child node.
306 curNodeNum
= *(UInt32
*)dataPtr
;
307 err
= ReleaseNode (btreePtr
, &nodeRec
);
313 // The child node should be at a level one less than the parent.
317 *nodeNum
= curNodeNum
;
319 *returnIndex
= index
;
322 return noErr
; // searchKey found, index identifies record in node
324 return fsBTRecordNotFoundErr
; // searchKey not found, index identifies insert point
327 (void) ReleaseNode(btreePtr
, &nodeRec
);
328 // fall into ErrorExit
333 nodePtr
->buffer
= nil
;
334 nodePtr
->blockHeader
= nil
;
343 ////////////////////////////////// InsertTree ///////////////////////////////////
345 OSStatus
InsertTree ( BTreeControlBlockPtr btreePtr
,
346 TreePathTable treePathTable
,
350 BlockDescriptor
*targetNode
,
353 Boolean replacingKey
,
356 InsertKey primaryKey
;
359 primaryKey
.keyPtr
= keyPtr
;
360 primaryKey
.keyLength
= GetKeyLength(btreePtr
, primaryKey
.keyPtr
, (level
== 1));
361 primaryKey
.recPtr
= recPtr
;
362 primaryKey
.recSize
= recSize
;
363 primaryKey
.replacingKey
= replacingKey
;
364 primaryKey
.skipRotate
= false;
366 err
= InsertLevel (btreePtr
, treePathTable
, &primaryKey
, nil
,
367 targetNode
, index
, level
, insertNode
);
371 } // End of InsertTree
374 ////////////////////////////////// InsertLevel //////////////////////////////////
376 OSStatus
InsertLevel (BTreeControlBlockPtr btreePtr
,
377 TreePathTable treePathTable
,
378 InsertKey
*primaryKey
,
379 InsertKey
*secondaryKey
,
380 BlockDescriptor
*targetNode
,
386 BlockDescriptor leftNode
;
387 UInt32 targetNodeNum
;
390 Boolean insertParent
;
391 Boolean updateParent
;
395 #if defined(applec) && !defined(__SC__)
396 PanicIf ((level
== 1) && (((NodeDescPtr
)targetNode
->buffer
)->kind
!= kBTLeafNode
), "\P InsertLevel: non-leaf at level 1! ");
398 leftNode
.buffer
= nil
;
399 leftNode
.blockHeader
= nil
;
400 targetNodeNum
= treePathTable
[level
].node
;
402 insertParent
= false;
403 updateParent
= false;
406 ModifyBlockStart(btreePtr
->fileRefNum
, targetNode
);
408 ////// process first insert //////
410 err
= InsertNode (btreePtr
, primaryKey
, targetNode
, targetNodeNum
, index
,
411 &newNodeNum
, &newIndex
, &leftNode
, &updateParent
, &insertParent
, &newRoot
);
416 // Extend the treePathTable by adding an entry for the new
417 // root node that references the current targetNode.
419 // If inserting the secondaryKey changes the first key of
420 // the target node, then we'll have to update the second
421 // key in the new root node.
423 treePathTable
[level
+ 1].node
= btreePtr
->rootNode
;
424 treePathTable
[level
+ 1].index
= 1; // 1 since we always split/rotate left
428 *insertNode
= newNodeNum
;
430 ////// process second insert (if any) //////
432 if ( secondaryKey
!= nil
)
436 err
= InsertNode (btreePtr
, secondaryKey
, targetNode
, newNodeNum
, newIndex
,
437 &newNodeNum
, &newIndex
, &leftNode
, &updateParent
, &insertParent
, &temp
);
440 if ( DEBUG_BUILD
&& updateParent
&& newRoot
)
441 DebugStr("\p InsertLevel: New root from primary key, update from secondary key...");
444 //////////////////////// Update Parent(s) ///////////////////////////////
446 if ( insertParent
|| updateParent
)
448 BlockDescriptor parentNode
;
449 UInt32 parentNodeNum
;
454 parentNode
.buffer
= nil
;
455 parentNode
.blockHeader
= nil
;
459 PanicIf ( (level
== btreePtr
->treeDepth
), "\p InsertLevel: unfinished insert!?");
463 // Get Parent Node data...
464 index
= treePathTable
[level
].index
;
465 parentNodeNum
= treePathTable
[level
].node
;
467 PanicIf ( parentNodeNum
== 0, "\p InsertLevel: parent node is zero!?");
469 err
= GetNode (btreePtr
, parentNodeNum
, &parentNode
); // released as target node in next level up
471 #if defined(applec) && !defined(__SC__)
472 if (DEBUG_BUILD
&& level
> 1)
473 PanicIf ( ((NodeDescPtr
)parentNode
.buffer
)->kind
!= kBTIndexNode
, "\P InsertLevel: parent node not an index node! ");
475 ////////////////////////// Update Parent Index //////////////////////////////
480 ModifyBlockStart(btreePtr
->fileRefNum
, &parentNode
);
482 //\80\80 debug: check if ptr == targetNodeNum
483 GetRecordByIndex (btreePtr
, parentNode
.buffer
, index
, &keyPtr
, &recPtr
, &recSize
);
484 PanicIf( (*(UInt32
*) recPtr
) != targetNodeNum
, "\p InsertLevel: parent ptr doesn't match target node!");
486 // need to delete and re-insert this parent key/ptr
487 // we delete it here and it gets re-inserted in the
488 // InsertLevel call below.
489 DeleteRecord (btreePtr
, parentNode
.buffer
, index
);
491 primaryKey
->keyPtr
= (KeyPtr
) GetRecordAddress( btreePtr
, targetNode
->buffer
, 0 );
492 primaryKey
->keyLength
= GetKeyLength(btreePtr
, primaryKey
->keyPtr
, false);
493 primaryKey
->recPtr
= (UInt8
*) &targetNodeNum
;
494 primaryKey
->recSize
= sizeof(targetNodeNum
);
495 primaryKey
->replacingKey
= kReplaceRecord
;
496 primaryKey
->skipRotate
= insertParent
; // don't rotate left if we have two inserts occuring
499 ////////////////////////// Add New Parent Index /////////////////////////////
503 InsertKey
*insertKeyPtr
;
507 insertKeyPtr
= &insertKey
;
508 secondaryKey
= &insertKey
;
512 insertKeyPtr
= primaryKey
;
515 insertKeyPtr
->keyPtr
= (KeyPtr
) GetRecordAddress (btreePtr
, leftNode
.buffer
, 0);
516 insertKeyPtr
->keyLength
= GetKeyLength(btreePtr
, insertKeyPtr
->keyPtr
, false);
517 insertKeyPtr
->recPtr
= (UInt8
*) &((NodeDescPtr
)targetNode
->buffer
)->bLink
;
518 insertKeyPtr
->recSize
= sizeof(UInt32
);
519 insertKeyPtr
->replacingKey
= kInsertRecord
;
520 insertKeyPtr
->skipRotate
= false; // a rotate is OK during second insert
523 err
= InsertLevel (btreePtr
, treePathTable
, primaryKey
, secondaryKey
,
524 &parentNode
, index
, level
, insertNode
);
528 err
= UpdateNode (btreePtr
, targetNode
, 0, kLockTransaction
); // all done with target
531 err
= UpdateNode (btreePtr
, &leftNode
, 0, kLockTransaction
); // all done with left sibling
538 (void) ReleaseNode (btreePtr
, targetNode
);
539 (void) ReleaseNode (btreePtr
, &leftNode
);
541 Panic ("\p InsertLevel: an error occurred!");
545 } // End of InsertLevel
549 ////////////////////////////////// InsertNode ///////////////////////////////////
551 static OSErr
InsertNode (BTreeControlBlockPtr btreePtr
,
554 BlockDescriptor
*rightNode
,
561 BlockDescriptor
*leftNode
,
562 Boolean
*updateParent
,
563 Boolean
*insertParent
,
566 BlockDescriptor
*targetNode
;
574 PanicIf ( rightNode
->buffer
== leftNode
->buffer
, "\p InsertNode: rightNode == leftNode, huh?");
576 leftNodeNum
= ((NodeDescPtr
) rightNode
->buffer
)->bLink
;
579 /////////////////////// Try Simple Insert ///////////////////////////////
581 if ( node
== leftNodeNum
)
582 targetNode
= leftNode
;
584 targetNode
= rightNode
;
586 recordFit
= InsertKeyRecord (btreePtr
, targetNode
->buffer
, index
, key
->keyPtr
, key
->keyLength
, key
->recPtr
, key
->recSize
);
593 if ( (index
== 0) && (((NodeDescPtr
) targetNode
->buffer
)->height
!= btreePtr
->treeDepth
) )
594 *updateParent
= true; // the first record changed so we need to update the parent
598 //////////////////////// Try Rotate Left ////////////////////////////////
600 if ( !recordFit
&& leftNodeNum
> 0 )
602 PanicIf ( leftNode
->buffer
!= nil
, "\p InsertNode: leftNode already aquired!");
604 if ( leftNode
->buffer
== nil
)
606 err
= GetNode (btreePtr
, leftNodeNum
, leftNode
); // will be released by caller or a split below
609 ModifyBlockStart(btreePtr
->fileRefNum
, leftNode
);
612 PanicIf ( ((NodeDescPtr
) leftNode
->buffer
)->fLink
!= node
, "\p InsertNode, RotateLeft: invalid sibling link!" );
614 if ( !key
->skipRotate
) // are rotates allowed?
616 err
= RotateLeft (btreePtr
, leftNode
->buffer
, rightNode
->buffer
, index
, key
->keyPtr
, key
->recPtr
,
617 key
->recSize
, newIndex
, newNode
, &recordFit
, &recsRotated
);
622 if ( key
->replacingKey
|| (recsRotated
> 1) || (index
> 0) )
623 *updateParent
= true;
629 //////////////////////// Try Split Left /////////////////////////////////
633 // might not have left node...
634 err
= SplitLeft (btreePtr
, leftNode
, rightNode
, node
, index
, key
->keyPtr
,
635 key
->recPtr
, key
->recSize
, newIndex
, newNode
, &recsRotated
);
638 // if we split root node - add new root
640 if ( ((NodeDescPtr
) rightNode
->buffer
)->height
== btreePtr
->treeDepth
)
642 err
= AddNewRootNode (btreePtr
, leftNode
->buffer
, rightNode
->buffer
); // Note: does not update TPT
648 *insertParent
= true;
650 if ( key
->replacingKey
|| (recsRotated
> 1) || (index
> 0) )
651 *updateParent
= true;
658 (void) ReleaseNode (btreePtr
, leftNode
);
661 } // End of InsertNode
664 /*-------------------------------------------------------------------------------
665 Routine: DeleteTree - One_line_description.
667 Function: Brief_description_of_the_function_and_any_side_effects
671 Input: btreePtr - description
672 treePathTable - description
673 targetNode - description
676 Result: noErr - success
678 -------------------------------------------------------------------------------*/
680 OSStatus
DeleteTree (BTreeControlBlockPtr btreePtr
,
681 TreePathTable treePathTable
,
682 BlockDescriptor
*targetNode
,
687 BlockDescriptor parentNode
;
688 BTNodeDescriptor
*targetNodePtr
;
689 UInt32 targetNodeNum
;
690 Boolean deleteRequired
;
691 Boolean updateRequired
;
693 // XXXdbg - initialize these to null in case we get an
694 // error and try to exit before it's initialized
695 parentNode
.buffer
= nil
;
696 parentNode
.blockHeader
= nil
;
698 deleteRequired
= false;
699 updateRequired
= false;
701 targetNodeNum
= treePathTable
[level
].node
;
702 targetNodePtr
= targetNode
->buffer
;
703 PanicIf (targetNodePtr
== nil
, "\pDeleteTree: targetNode has nil buffer!");
706 ModifyBlockStart(btreePtr
->fileRefNum
, targetNode
);
708 DeleteRecord (btreePtr
, targetNodePtr
, index
);
710 //\80\80 coalesce remaining records?
712 if ( targetNodePtr
->numRecords
== 0 ) // did we delete the last record?
714 BlockDescriptor siblingNode
;
715 UInt32 siblingNodeNum
;
717 deleteRequired
= true;
719 siblingNode
.buffer
= nil
;
720 siblingNode
.blockHeader
= nil
;
722 ////////////////// Get Siblings & Update Links //////////////////////////
724 siblingNodeNum
= targetNodePtr
->bLink
; // Left Sibling Node
725 if ( siblingNodeNum
!= 0 )
727 err
= GetNode (btreePtr
, siblingNodeNum
, &siblingNode
);
731 ModifyBlockStart(btreePtr
->fileRefNum
, &siblingNode
);
733 ((NodeDescPtr
)siblingNode
.buffer
)->fLink
= targetNodePtr
->fLink
;
734 err
= UpdateNode (btreePtr
, &siblingNode
, 0, kLockTransaction
);
737 else if ( targetNodePtr
->kind
== kBTLeafNode
) // update firstLeafNode
739 btreePtr
->firstLeafNode
= targetNodePtr
->fLink
;
742 siblingNodeNum
= targetNodePtr
->fLink
; // Right Sibling Node
743 if ( siblingNodeNum
!= 0 )
745 err
= GetNode (btreePtr
, siblingNodeNum
, &siblingNode
);
749 ModifyBlockStart(btreePtr
->fileRefNum
, &siblingNode
);
751 ((NodeDescPtr
)siblingNode
.buffer
)->bLink
= targetNodePtr
->bLink
;
752 err
= UpdateNode (btreePtr
, &siblingNode
, 0, kLockTransaction
);
755 else if ( targetNodePtr
->kind
== kBTLeafNode
) // update lastLeafNode
757 btreePtr
->lastLeafNode
= targetNodePtr
->bLink
;
760 //////////////////////// Free Empty Node ////////////////////////////////
762 ClearNode (btreePtr
, targetNodePtr
);
764 err
= UpdateNode (btreePtr
, targetNode
, 0, kLockTransaction
);
767 err
= FreeNode (btreePtr
, targetNodeNum
);
770 else if ( index
== 0 ) // did we delete the first record?
772 updateRequired
= true; // yes, so we need to update parent
776 if ( level
== btreePtr
->treeDepth
) // then targetNode->buffer is the root node
778 deleteRequired
= false;
779 updateRequired
= false;
781 if ( targetNode
->buffer
== nil
) // then root was freed and the btree is empty
783 btreePtr
->rootNode
= 0;
784 btreePtr
->treeDepth
= 0;
786 else if ( ((NodeDescPtr
)targetNode
->buffer
)->numRecords
== 1 )
788 err
= CollapseTree (btreePtr
, targetNode
);
794 if ( updateRequired
|| deleteRequired
)
796 ++level
; // next level
798 //// Get Parent Node and index
799 index
= treePathTable
[level
].index
;
800 err
= GetNode (btreePtr
, treePathTable
[level
].node
, &parentNode
);
803 if ( updateRequired
)
811 ModifyBlockStart(btreePtr
->fileRefNum
, &parentNode
);
813 //\80\80 debug: check if ptr == targetNodeNum
814 GetRecordByIndex (btreePtr
, parentNode
.buffer
, index
, &keyPtr
, &recPtr
, &recSize
);
815 PanicIf( (*(UInt32
*) recPtr
) != targetNodeNum
, "\p DeleteTree: parent ptr doesn't match targetNodeNum!!");
817 // need to delete and re-insert this parent key/ptr
818 DeleteRecord (btreePtr
, parentNode
.buffer
, index
);
820 keyPtr
= (KeyPtr
) GetRecordAddress( btreePtr
, targetNode
->buffer
, 0 );
821 recPtr
= (UInt8
*) &targetNodeNum
;
822 recSize
= sizeof(targetNodeNum
);
824 err
= InsertTree (btreePtr
, treePathTable
, keyPtr
, recPtr
, recSize
,
825 &parentNode
, index
, level
, kReplaceRecord
, &insertNode
);
828 else // deleteRequired
830 err
= DeleteTree (btreePtr
, treePathTable
, &parentNode
, index
, level
);
836 err
= UpdateNode (btreePtr
, targetNode
, 0, kLockTransaction
);
843 (void) ReleaseNode (btreePtr
, targetNode
);
844 (void) ReleaseNode (btreePtr
, &parentNode
);
852 ///////////////////////////////// CollapseTree //////////////////////////////////
854 static OSStatus
CollapseTree (BTreeControlBlockPtr btreePtr
,
855 BlockDescriptor
*blockPtr
)
861 originalRoot
= btreePtr
->rootNode
;
864 ModifyBlockStart(btreePtr
->fileRefNum
, blockPtr
);
868 if ( ((NodeDescPtr
)blockPtr
->buffer
)->numRecords
> 1)
869 break; // this will make a fine root node
871 if ( ((NodeDescPtr
)blockPtr
->buffer
)->kind
== kBTLeafNode
)
872 break; // we've hit bottom
874 nodeNum
= btreePtr
->rootNode
;
875 btreePtr
->rootNode
= GetChildNodeNum (btreePtr
, blockPtr
->buffer
, 0);
876 --btreePtr
->treeDepth
;
878 //// Clear and Free Current Old Root Node ////
879 ClearNode (btreePtr
, blockPtr
->buffer
);
880 err
= UpdateNode (btreePtr
, blockPtr
, 0, kLockTransaction
);
882 err
= FreeNode (btreePtr
, nodeNum
);
885 //// Get New Root Node
886 err
= GetNode (btreePtr
, btreePtr
->rootNode
, blockPtr
);
890 ModifyBlockStart(btreePtr
->fileRefNum
, blockPtr
);
893 if (btreePtr
->rootNode
!= originalRoot
)
894 M_BTreeHeaderDirty (btreePtr
);
896 err
= UpdateNode (btreePtr
, blockPtr
, 0, kLockTransaction
); // always update!
902 /////////////////////////////////// ErrorExit ///////////////////////////////////
905 (void) ReleaseNode (btreePtr
, blockPtr
);
911 ////////////////////////////////// RotateLeft ///////////////////////////////////
913 /*-------------------------------------------------------------------------------
915 Routine: RotateLeft - One_line_description.
917 Function: Brief_description_of_the_function_and_any_side_effects
919 Algorithm: if rightIndex > insertIndex, subtract 1 for actual rightIndex
921 Input: btreePtr - description
922 leftNode - description
923 rightNode - description
924 rightInsertIndex - description
927 recSize - description
930 insertNodeNum - description
931 recordFit - description
934 Result: noErr - success
936 -------------------------------------------------------------------------------*/
938 static OSStatus
RotateLeft (BTreeControlBlockPtr btreePtr
,
939 NodeDescPtr leftNode
,
940 NodeDescPtr rightNode
,
941 UInt16 rightInsertIndex
,
946 UInt32
*insertNodeNum
,
948 UInt16
*recsRotated
)
953 SInt32 leftSize
, rightSize
;
956 UInt16 lengthFieldSize
;
957 UInt16 index
, moveIndex
;
960 ///////////////////// Determine If Record Will Fit //////////////////////////
962 keyLength
= GetKeyLength(btreePtr
, keyPtr
, (rightNode
->kind
== kBTLeafNode
));
964 // the key's length field is 8-bits in HFS and 16-bits in HFS+
965 if ( btreePtr
->attributes
& kBTBigKeysMask
)
966 lengthFieldSize
= sizeof(UInt16
);
968 lengthFieldSize
= sizeof(UInt8
);
970 insertSize
= keyLength
+ lengthFieldSize
+ recSize
+ sizeof(UInt16
);
972 if ( M_IsOdd (insertSize
) )
973 ++insertSize
; // add pad byte;
975 nodeSize
= btreePtr
->nodeSize
;
977 // add size of insert record to right node
978 rightSize
= nodeSize
- GetNodeFreeSize (btreePtr
, rightNode
) + insertSize
;
979 leftSize
= nodeSize
- GetNodeFreeSize (btreePtr
, leftNode
);
983 while ( leftSize
< rightSize
)
985 if ( moveIndex
< rightInsertIndex
)
987 moveSize
= GetRecordSize (btreePtr
, rightNode
, moveIndex
) + 2;
989 else if ( moveIndex
== rightInsertIndex
)
991 moveSize
= insertSize
;
993 else // ( moveIndex > rightInsertIndex )
995 moveSize
= GetRecordSize (btreePtr
, rightNode
, moveIndex
- 1) + 2;
998 leftSize
+= moveSize
;
999 rightSize
-= moveSize
;
1003 if ( leftSize
> nodeSize
) // undo last move
1005 leftSize
-= moveSize
;
1006 rightSize
+= moveSize
;
1010 if ( rightSize
> nodeSize
) // record won't fit - failure, but not error
1020 // we've found balance point, moveIndex == number of records moved into leftNode
1023 //////////////////////////// Rotate Records /////////////////////////////////
1025 *recsRotated
= moveIndex
;
1029 while ( index
< moveIndex
)
1031 if ( index
== rightInsertIndex
) // insert new record in left node
1033 UInt16 leftInsertIndex
;
1035 leftInsertIndex
= leftNode
->numRecords
;
1037 didItFit
= InsertKeyRecord (btreePtr
, leftNode
, leftInsertIndex
,
1038 keyPtr
, keyLength
, recPtr
, recSize
);
1041 Panic ("\pRotateLeft: InsertKeyRecord (left) returned false!");
1042 err
= fsBTBadRotateErr
;
1046 *insertIndex
= leftInsertIndex
;
1047 *insertNodeNum
= rightNode
->bLink
;
1051 didItFit
= RotateRecordLeft (btreePtr
, leftNode
, rightNode
);
1054 Panic ("\pRotateLeft: RotateRecordLeft returned false!");
1055 err
= fsBTBadRotateErr
;
1063 if ( moveIndex
<= rightInsertIndex
) // then insert new record in right node
1065 rightInsertIndex
-= index
; // adjust for records already rotated
1067 didItFit
= InsertKeyRecord (btreePtr
, rightNode
, rightInsertIndex
,
1068 keyPtr
, keyLength
, recPtr
, recSize
);
1071 Panic ("\pRotateLeft: InsertKeyRecord (right) returned false!");
1072 err
= fsBTBadRotateErr
;
1076 *insertIndex
= rightInsertIndex
;
1077 *insertNodeNum
= leftNode
->fLink
;
1084 ////////////////////////////// Error Exit ///////////////////////////////////
1098 /////////////////////////////////// SplitLeft ///////////////////////////////////
1100 static OSStatus
SplitLeft (BTreeControlBlockPtr btreePtr
,
1101 BlockDescriptor
*leftNode
,
1102 BlockDescriptor
*rightNode
,
1103 UInt32 rightNodeNum
,
1108 UInt16
*insertIndex
,
1109 UInt32
*insertNodeNum
,
1110 UInt16
*recsRotated
)
1113 NodeDescPtr left
, right
;
1118 ///////////////////////////// Compare Nodes /////////////////////////////////
1120 right
= rightNode
->buffer
;
1121 left
= leftNode
->buffer
;
1123 PanicIf ( right
->bLink
!= 0 && left
== 0, "\p SplitLeft: left sibling missing!?" );
1125 /* type should be kBTLeafNode or kBTIndexNode */
1127 if ( (right
->height
== 1) && (right
->kind
!= kBTLeafNode
) )
1128 return fsBTInvalidNodeErr
;
1132 if ( left
->fLink
!= rightNodeNum
)
1133 return fsBTInvalidNodeErr
; //\80\80 E_BadSibling ?
1135 if ( left
->height
!= right
->height
)
1136 return fsBTInvalidNodeErr
; //\80\80 E_BadNodeHeight ?
1138 if ( left
->kind
!= right
->kind
)
1139 return fsBTInvalidNodeErr
; //\80\80 E_BadNodeType ?
1143 ///////////////////////////// Allocate Node /////////////////////////////////
1145 err
= AllocateNode (btreePtr
, &newNodeNum
);
1146 M_ExitOnError (err
);
1149 /////////////// Update Forward Link In Original Left Node ///////////////////
1154 ModifyBlockStart(btreePtr
->fileRefNum
, leftNode
);
1156 left
->fLink
= newNodeNum
;
1157 err
= UpdateNode (btreePtr
, leftNode
, 0, kLockTransaction
);
1158 M_ExitOnError (err
);
1162 /////////////////////// Initialize New Left Node ////////////////////////////
1164 err
= GetNewNode (btreePtr
, newNodeNum
, leftNode
);
1165 M_ExitOnError (err
);
1168 ModifyBlockStart(btreePtr
->fileRefNum
, leftNode
);
1170 left
= leftNode
->buffer
;
1171 left
->fLink
= rightNodeNum
;
1174 // Steal Info From Right Node
1176 left
->bLink
= right
->bLink
;
1177 left
->kind
= right
->kind
;
1178 left
->height
= right
->height
;
1180 right
->bLink
= newNodeNum
; // update Right bLink
1182 if ( (left
->kind
== kBTLeafNode
) && (left
->bLink
== 0) )
1184 // if we're adding a new first leaf node - update BTreeInfoRec
1186 btreePtr
->firstLeafNode
= newNodeNum
;
1187 M_BTreeHeaderDirty (btreePtr
); //\80\80 AllocateNode should have set the bit already...
1190 ////////////////////////////// Rotate Left //////////////////////////////////
1192 err
= RotateLeft (btreePtr
, left
, right
, index
, keyPtr
, recPtr
, recSize
,
1193 insertIndex
, insertNodeNum
, &recordFit
, recsRotated
);
1195 M_ExitOnError (err
);
1201 (void) ReleaseNode (btreePtr
, leftNode
);
1202 (void) ReleaseNode (btreePtr
, rightNode
);
1204 //\80\80 Free new node if allocated?
1215 /////////////////////////////// RotateRecordLeft ////////////////////////////////
1217 static Boolean
RotateRecordLeft (BTreeControlBlockPtr btreePtr
,
1218 NodeDescPtr leftNode
,
1219 NodeDescPtr rightNode
)
1225 size
= GetRecordSize (btreePtr
, rightNode
, 0);
1226 recPtr
= GetRecordAddress (btreePtr
, rightNode
, 0);
1228 recordFit
= InsertRecord (btreePtr
, leftNode
, leftNode
->numRecords
, recPtr
, size
);
1233 DeleteRecord (btreePtr
, rightNode
, 0);
1239 //////////////////////////////// AddNewRootNode /////////////////////////////////
1241 static OSStatus
AddNewRootNode (BTreeControlBlockPtr btreePtr
,
1242 NodeDescPtr leftNode
,
1243 NodeDescPtr rightNode
)
1246 BlockDescriptor rootNode
;
1252 rootNode
.buffer
= nil
;
1253 rootNode
.blockHeader
= nil
;
1255 PanicIf (leftNode
== nil
, "\pAddNewRootNode: leftNode == nil");
1256 PanicIf (rightNode
== nil
, "\pAddNewRootNode: rightNode == nil");
1259 /////////////////////// Initialize New Root Node ////////////////////////////
1261 err
= AllocateNode (btreePtr
, &rootNum
);
1262 M_ExitOnError (err
);
1264 err
= GetNewNode (btreePtr
, rootNum
, &rootNode
);
1265 M_ExitOnError (err
);
1268 ModifyBlockStart(btreePtr
->fileRefNum
, &rootNode
);
1270 ((NodeDescPtr
)rootNode
.buffer
)->kind
= kBTIndexNode
;
1271 ((NodeDescPtr
)rootNode
.buffer
)->height
= ++btreePtr
->treeDepth
;
1274 ///////////////////// Insert Left Node Index Record /////////////////////////
1276 keyPtr
= (KeyPtr
) GetRecordAddress (btreePtr
, leftNode
, 0);
1277 keyLength
= GetKeyLength(btreePtr
, keyPtr
, false);
1279 didItFit
= InsertKeyRecord ( btreePtr
, rootNode
.buffer
, 0, keyPtr
, keyLength
,
1280 (UInt8
*) &rightNode
->bLink
, 4 );
1282 PanicIf ( !didItFit
, "\pAddNewRootNode:InsertKeyRecord failed for left index record");
1285 //////////////////// Insert Right Node Index Record /////////////////////////
1287 keyPtr
= (KeyPtr
) GetRecordAddress (btreePtr
, rightNode
, 0);
1288 keyLength
= GetKeyLength(btreePtr
, keyPtr
, false);
1290 didItFit
= InsertKeyRecord ( btreePtr
, rootNode
.buffer
, 1, keyPtr
, keyLength
,
1291 (UInt8
*) &leftNode
->fLink
, 4 );
1293 PanicIf ( !didItFit
, "\pAddNewRootNode:InsertKeyRecord failed for right index record");
1296 /////////////////////////// Release Root Node ///////////////////////////////
1298 err
= UpdateNode (btreePtr
, &rootNode
, 0, kLockTransaction
);
1299 M_ExitOnError (err
);
1301 // update BTreeInfoRec
1303 btreePtr
->rootNode
= rootNum
;
1304 btreePtr
->flags
|= kBTHeaderDirty
;
1309 ////////////////////////////// Error Exit ///////////////////////////////////
1317 static UInt16
GetKeyLength ( const BTreeControlBlock
*btreePtr
, const BTreeKey
*key
, Boolean forLeafNode
)
1321 if ( forLeafNode
|| btreePtr
->attributes
& kBTVariableIndexKeysMask
)
1322 length
= KeyLength (btreePtr
, key
); // just use actual key length
1324 length
= btreePtr
->maxKeyLength
; // fixed sized index key (i.e. HFS) //\80\80 shouldn't we clear the pad bytes?