2 * Copyright (c) 2000 Apple Computer, Inc. All rights reserved.
4 * @APPLE_LICENSE_HEADER_START@
6 * The contents of this file constitute Original Code as defined in and
7 * are subject to the Apple Public Source License Version 1.1 (the
8 * "License"). You may not use this file except in compliance with the
9 * License. Please obtain a copy of the License at
10 * http://www.apple.com/publicsource and read it before using this file.
12 * This Original Code and all software distributed under the License are
13 * distributed on an "AS IS" basis, WITHOUT WARRANTY OF ANY KIND, EITHER
14 * EXPRESS OR IMPLIED, AND APPLE HEREBY DISCLAIMS ALL SUCH WARRANTIES,
15 * INCLUDING WITHOUT LIMITATION, ANY WARRANTIES OF MERCHANTABILITY,
16 * FITNESS FOR A PARTICULAR PURPOSE OR NON-INFRINGEMENT. Please see the
17 * License for the specific language governing rights and limitations
20 * @APPLE_LICENSE_HEADER_END@
25 Contains: Multi-node tree operations for the BTree Module.
27 Version: xxx put the technology version here xxx
29 Written by: Gordon Sheridan and Bill Bruffey
31 Copyright: © 1992-1999 by Apple Computer, Inc., all rights reserved.
37 Other Contact: Mark Day
39 Technology: File Systems
47 Change History (most recent first):
49 <MOSXS> 6/1/99 djb Sync up with Mac OS 8.6.
50 <CS5> 12/8/97 djb Radar #2200632, CollapseTree wasn't marking root node dirty.
51 <CS4> 11/24/97 djb Radar #2005325, InsertLevel incorrectly handled root splits!
52 <CS3> 10/17/97 msd Conditionalize DebugStrs.
53 <CS2> 5/16/97 msd InsertNode() needs a return statement in ErrorExit.
54 <CS1> 4/23/97 djb first checked in
56 <HFS8> 3/17/97 DSH Conditionalize out Panic assertion for SC.
57 <HFS7> 3/3/97 djb Removed DebugStr in InsertLevel.
58 <HFS6> 2/19/97 djb Major re-write of insert code; added InsertLevel and InsertNode.
59 <HFS5> 1/27/97 djb InsertTree and DeleteTree are now recursive and support variable
61 <HFS4> 1/16/97 djb Removed DebugStr in SearchTree. Added initial support for
62 variable sized index keys.
63 <HFS3> 1/3/97 djb Changed len8 to length8.
64 <HFS2> 1/3/97 djb Added support for large keys.
65 <HFS1> 12/19/96 djb first checked in
67 History applicable to original Scarecrow Design:
69 <3> 10/25/96 ser Changing for new VFPI
70 <2> 1/22/96 dkh Add #include Memory.h
71 <1> 10/18/95 rst Moved from Scarecrow project.
73 <12> 7/18/95 mbb Change MoveData & ClearBytes to BlockMoveData & BlockZero.
74 <11> 9/30/94 prp Get in sync with D2 interface changes.
75 <10> 7/25/94 wjk Eliminate usage of BytePtr in favor of UInt8 *.
76 <9> 7/22/94 wjk Convert to the new set of header files.
77 <8> 12/2/93 wjk Move from Makefiles to BuildFiles. Fit into the ModernOS and
79 <7> 11/30/93 wjk Change some Ptr's to BytePtr's in function definitions so they
80 agree with their prototypes.
81 <6> 5/21/93 gs Debug DeleteTree. Modify InsertTree for BTReplaceRecord.
82 <5> 5/10/93 gs Modify RotateLeft, and add DeleteTree, CollapseTree routines.
83 <4> 3/23/93 gs revise RotateLeft to use InsertKeyRecord instead of
85 <3> 3/23/93 gs Implement SplitLeft, InsertTree routine.
86 <2> 2/8/93 gs Implement SearchTree, and RotateLeft.
87 <1> 11/15/92 gs first checked in
91 #include "../headers/BTreesPrivate.h"
94 /////////////////////// Routines Internal To BTree Module ///////////////////////
99 ////////////////////// Routines Internal To BTreeTreeOps.c //////////////////////
101 static OSStatus
AddNewRootNode (BTreeControlBlockPtr btreePtr
,
102 NodeDescPtr leftNode
,
103 NodeDescPtr rightNode
);
105 static OSStatus
CollapseTree (BTreeControlBlockPtr btreePtr
,
106 BlockDescriptor
*blockPtr
);
108 static OSStatus
RotateLeft (BTreeControlBlockPtr btreePtr
,
109 NodeDescPtr leftNode
,
110 NodeDescPtr rightNode
,
111 UInt16 rightInsertIndex
,
116 UInt32
*insertNodeNum
,
118 UInt16
*recsRotated
);
120 static Boolean
RotateRecordLeft (BTreeControlBlockPtr btreePtr
,
121 NodeDescPtr leftNode
,
122 NodeDescPtr rightNode
);
124 static OSStatus
SplitLeft (BTreeControlBlockPtr btreePtr
,
125 BlockDescriptor
*leftNode
,
126 BlockDescriptor
*rightNode
,
133 UInt32
*insertNodeNum
,
134 UInt16
*recsRotated
);
138 static OSStatus
InsertLevel (BTreeControlBlockPtr btreePtr
,
139 TreePathTable treePathTable
,
140 InsertKey
*primaryKey
,
141 InsertKey
*secondaryKey
,
142 BlockDescriptor
*targetNode
,
145 UInt32
*insertNode
);
147 static OSErr
InsertNode (BTreeControlBlockPtr btreePtr
,
149 BlockDescriptor
*rightNode
,
154 BlockDescriptor
*leftNode
,
155 Boolean
*updateParent
,
156 Boolean
*insertParent
,
157 Boolean
*rootSplit
);
159 static UInt16
GetKeyLength (const BTreeControlBlock
*btreePtr
,
161 Boolean forLeafNode
);
165 //////////////////////// BTree Multi-node Tree Operations ///////////////////////
168 /*-------------------------------------------------------------------------------
170 Routine: SearchTree - Search BTree for key and set up Tree Path Table.
172 Function: Searches BTree for specified key, setting up the Tree Path Table to
173 reflect the search path.
176 Input: btreePtr - pointer to control block of BTree to search
177 keyPtr - pointer to the key to search for
178 treePathTable - pointer to the tree path table to construct
180 Output: nodeNum - number of the node containing the key position
181 iterator - BTreeIterator specifying record or insert position
183 Result: noErr - key found, index is record index
184 fsBTRecordNotFoundErr - key not found, index is insert index
185 fsBTEmptyErr - key not found, return params are nil
186 otherwise - catastrophic failure (GetNode/ReleaseNode failed)
187 -------------------------------------------------------------------------------*/
189 OSStatus
SearchTree (BTreeControlBlockPtr btreePtr
,
190 BTreeKeyPtr searchKey
,
191 TreePathTable treePathTable
,
193 BlockDescriptor
*nodePtr
,
194 UInt16
*returnIndex
)
197 SInt16 level
; // Expected depth of current node
198 UInt32 curNodeNum
; // Current node we're searching
202 SInt8 nodeKind
; // Kind of current node (index/leaf)
208 curNodeNum
= btreePtr
->rootNode
;
209 level
= btreePtr
->treeDepth
;
211 if (level
== 0) // is the tree empty?
217 //\80\80 for debugging...
218 treePathTable
[0].node
= 0;
219 treePathTable
[0].index
= 0;
224 // [2550929] Node number 0 is the header node. It is never a valid
225 // index or leaf node. If we're ever asked to search through node 0,
226 // something has gone wrong (typically a bad child node number, or
227 // we found a node full of zeroes that we thought was an index node).
231 // Panic("\pSearchTree: curNodeNum is zero!");
236 err
= GetNode (btreePtr
, curNodeNum
, &nodeRec
);
243 // [2550929] Sanity check the node height and node type. We expect
244 // particular values at each iteration in the search. This checking
245 // quickly finds bad pointers, loops, and other damage to the
246 // hierarchy of the B-tree.
248 if (((BTNodeDescriptor
*)nodeRec
.buffer
)->height
!= level
)
250 // Panic("\pIncorrect node height");
254 nodeKind
= ((BTNodeDescriptor
*)nodeRec
.buffer
)->kind
;
257 // Nodes at level 1 must be leaves, by definition
258 if (nodeKind
!= kBTLeafNode
)
260 // Panic("\pIncorrect node type: expected leaf");
267 // A node at any other depth must be an index node
268 if (nodeKind
!= kBTIndexNode
)
270 // Panic("\pIncorrect node type: expected index");
276 keyFound
= SearchNode (btreePtr
, nodeRec
.buffer
, searchKey
, &index
);
278 treePathTable
[level
].node
= curNodeNum
;
280 if (nodeKind
== kBTLeafNode
)
282 treePathTable
[level
].index
= index
;
283 break; // were done...
286 if ( (keyFound
!= true) && (index
!= 0))
289 treePathTable
[level
].index
= index
;
291 err
= GetRecordByIndex (btreePtr
, nodeRec
.buffer
, index
, &keyPtr
, &dataPtr
, &dataSize
);
294 // [2550929] If we got an error, it is probably because the index was bad
295 // (typically a corrupt node that confused SearchNode). Invalidate the node
296 // so we won't accidentally use the corrupted contents. NOTE: the Mac OS 9
297 // sources call this InvalidateNode.
299 (void) TrashNode(btreePtr
, &nodeRec
);
303 // Get the child pointer out of this index node. We're now done with the current
304 // node and can continue the search with the child node.
305 curNodeNum
= *(UInt32
*)dataPtr
;
306 err
= ReleaseNode (btreePtr
, &nodeRec
);
312 // The child node should be at a level one less than the parent.
316 *nodeNum
= curNodeNum
;
318 *returnIndex
= index
;
321 return noErr
; // searchKey found, index identifies record in node
323 return fsBTRecordNotFoundErr
; // searchKey not found, index identifies insert point
326 (void) ReleaseNode(btreePtr
, &nodeRec
);
327 // fall into ErrorExit
332 nodePtr
->buffer
= nil
;
333 nodePtr
->blockHeader
= nil
;
342 ////////////////////////////////// InsertTree ///////////////////////////////////
344 OSStatus
InsertTree ( BTreeControlBlockPtr btreePtr
,
345 TreePathTable treePathTable
,
349 BlockDescriptor
*targetNode
,
352 Boolean replacingKey
,
355 InsertKey primaryKey
;
358 primaryKey
.keyPtr
= keyPtr
;
359 primaryKey
.keyLength
= GetKeyLength(btreePtr
, primaryKey
.keyPtr
, (level
== 1));
360 primaryKey
.recPtr
= recPtr
;
361 primaryKey
.recSize
= recSize
;
362 primaryKey
.replacingKey
= replacingKey
;
363 primaryKey
.skipRotate
= false;
365 err
= InsertLevel (btreePtr
, treePathTable
, &primaryKey
, nil
,
366 targetNode
, index
, level
, insertNode
);
370 } // End of InsertTree
373 ////////////////////////////////// InsertLevel //////////////////////////////////
375 OSStatus
InsertLevel (BTreeControlBlockPtr btreePtr
,
376 TreePathTable treePathTable
,
377 InsertKey
*primaryKey
,
378 InsertKey
*secondaryKey
,
379 BlockDescriptor
*targetNode
,
385 BlockDescriptor leftNode
;
386 UInt32 targetNodeNum
;
389 Boolean insertParent
;
390 Boolean updateParent
;
394 #if defined(applec) && !defined(__SC__)
395 PanicIf ((level
== 1) && (((NodeDescPtr
)targetNode
->buffer
)->kind
!= kBTLeafNode
), "\P InsertLevel: non-leaf at level 1! ");
397 leftNode
.buffer
= nil
;
398 leftNode
.blockHeader
= nil
;
399 targetNodeNum
= treePathTable
[level
].node
;
401 insertParent
= false;
402 updateParent
= false;
405 ModifyBlockStart(btreePtr
->fileRefNum
, targetNode
);
407 ////// process first insert //////
409 err
= InsertNode (btreePtr
, primaryKey
, targetNode
, targetNodeNum
, index
,
410 &newNodeNum
, &newIndex
, &leftNode
, &updateParent
, &insertParent
, &newRoot
);
415 // Extend the treePathTable by adding an entry for the new
416 // root node that references the current targetNode.
418 // If inserting the secondaryKey changes the first key of
419 // the target node, then we'll have to update the second
420 // key in the new root node.
422 treePathTable
[level
+ 1].node
= btreePtr
->rootNode
;
423 treePathTable
[level
+ 1].index
= 1; // 1 since we always split/rotate left
427 *insertNode
= newNodeNum
;
429 ////// process second insert (if any) //////
431 if ( secondaryKey
!= nil
)
435 err
= InsertNode (btreePtr
, secondaryKey
, targetNode
, newNodeNum
, newIndex
,
436 &newNodeNum
, &newIndex
, &leftNode
, &updateParent
, &insertParent
, &temp
);
439 if ( DEBUG_BUILD
&& updateParent
&& newRoot
)
440 DebugStr("\p InsertLevel: New root from primary key, update from secondary key...");
443 //////////////////////// Update Parent(s) ///////////////////////////////
445 if ( insertParent
|| updateParent
)
447 BlockDescriptor parentNode
;
448 UInt32 parentNodeNum
;
453 parentNode
.buffer
= nil
;
454 parentNode
.blockHeader
= nil
;
458 PanicIf ( (level
== btreePtr
->treeDepth
), "\p InsertLevel: unfinished insert!?");
462 // Get Parent Node data...
463 index
= treePathTable
[level
].index
;
464 parentNodeNum
= treePathTable
[level
].node
;
466 PanicIf ( parentNodeNum
== 0, "\p InsertLevel: parent node is zero!?");
468 err
= GetNode (btreePtr
, parentNodeNum
, &parentNode
); // released as target node in next level up
470 #if defined(applec) && !defined(__SC__)
471 if (DEBUG_BUILD
&& level
> 1)
472 PanicIf ( ((NodeDescPtr
)parentNode
.buffer
)->kind
!= kBTIndexNode
, "\P InsertLevel: parent node not an index node! ");
474 ////////////////////////// Update Parent Index //////////////////////////////
479 ModifyBlockStart(btreePtr
->fileRefNum
, &parentNode
);
481 //\80\80 debug: check if ptr == targetNodeNum
482 GetRecordByIndex (btreePtr
, parentNode
.buffer
, index
, &keyPtr
, &recPtr
, &recSize
);
483 PanicIf( (*(UInt32
*) recPtr
) != targetNodeNum
, "\p InsertLevel: parent ptr doesn't match target node!");
485 // need to delete and re-insert this parent key/ptr
486 // we delete it here and it gets re-inserted in the
487 // InsertLevel call below.
488 DeleteRecord (btreePtr
, parentNode
.buffer
, index
);
490 primaryKey
->keyPtr
= (KeyPtr
) GetRecordAddress( btreePtr
, targetNode
->buffer
, 0 );
491 primaryKey
->keyLength
= GetKeyLength(btreePtr
, primaryKey
->keyPtr
, false);
492 primaryKey
->recPtr
= (UInt8
*) &targetNodeNum
;
493 primaryKey
->recSize
= sizeof(targetNodeNum
);
494 primaryKey
->replacingKey
= kReplaceRecord
;
495 primaryKey
->skipRotate
= insertParent
; // don't rotate left if we have two inserts occuring
498 ////////////////////////// Add New Parent Index /////////////////////////////
502 InsertKey
*insertKeyPtr
;
506 insertKeyPtr
= &insertKey
;
507 secondaryKey
= &insertKey
;
511 insertKeyPtr
= primaryKey
;
514 insertKeyPtr
->keyPtr
= (KeyPtr
) GetRecordAddress (btreePtr
, leftNode
.buffer
, 0);
515 insertKeyPtr
->keyLength
= GetKeyLength(btreePtr
, insertKeyPtr
->keyPtr
, false);
516 insertKeyPtr
->recPtr
= (UInt8
*) &((NodeDescPtr
)targetNode
->buffer
)->bLink
;
517 insertKeyPtr
->recSize
= sizeof(UInt32
);
518 insertKeyPtr
->replacingKey
= kInsertRecord
;
519 insertKeyPtr
->skipRotate
= false; // a rotate is OK during second insert
522 err
= InsertLevel (btreePtr
, treePathTable
, primaryKey
, secondaryKey
,
523 &parentNode
, index
, level
, insertNode
);
527 err
= UpdateNode (btreePtr
, targetNode
, 0, kLockTransaction
); // all done with target
530 err
= UpdateNode (btreePtr
, &leftNode
, 0, kLockTransaction
); // all done with left sibling
537 (void) ReleaseNode (btreePtr
, targetNode
);
538 (void) ReleaseNode (btreePtr
, &leftNode
);
540 Panic ("\p InsertLevel: an error occured!");
544 } // End of InsertLevel
548 ////////////////////////////////// InsertNode ///////////////////////////////////
550 static OSErr
InsertNode (BTreeControlBlockPtr btreePtr
,
553 BlockDescriptor
*rightNode
,
560 BlockDescriptor
*leftNode
,
561 Boolean
*updateParent
,
562 Boolean
*insertParent
,
565 BlockDescriptor
*targetNode
;
573 PanicIf ( rightNode
->buffer
== leftNode
->buffer
, "\p InsertNode: rightNode == leftNode, huh?");
575 leftNodeNum
= ((NodeDescPtr
) rightNode
->buffer
)->bLink
;
578 /////////////////////// Try Simple Insert ///////////////////////////////
580 if ( node
== leftNodeNum
)
581 targetNode
= leftNode
;
583 targetNode
= rightNode
;
585 recordFit
= InsertKeyRecord (btreePtr
, targetNode
->buffer
, index
, key
->keyPtr
, key
->keyLength
, key
->recPtr
, key
->recSize
);
592 if ( (index
== 0) && (((NodeDescPtr
) targetNode
->buffer
)->height
!= btreePtr
->treeDepth
) )
593 *updateParent
= true; // the first record changed so we need to update the parent
597 //////////////////////// Try Rotate Left ////////////////////////////////
599 if ( !recordFit
&& leftNodeNum
> 0 )
601 PanicIf ( leftNode
->buffer
!= nil
, "\p InsertNode: leftNode already aquired!");
603 if ( leftNode
->buffer
== nil
)
605 err
= GetNode (btreePtr
, leftNodeNum
, leftNode
); // will be released by caller or a split below
608 ModifyBlockStart(btreePtr
->fileRefNum
, leftNode
);
611 PanicIf ( ((NodeDescPtr
) leftNode
->buffer
)->fLink
!= node
, "\p InsertNode, RotateLeft: invalid sibling link!" );
613 if ( !key
->skipRotate
) // are rotates allowed?
615 err
= RotateLeft (btreePtr
, leftNode
->buffer
, rightNode
->buffer
, index
, key
->keyPtr
, key
->recPtr
,
616 key
->recSize
, newIndex
, newNode
, &recordFit
, &recsRotated
);
621 if ( key
->replacingKey
|| (recsRotated
> 1) || (index
> 0) )
622 *updateParent
= true;
628 //////////////////////// Try Split Left /////////////////////////////////
632 // might not have left node...
633 err
= SplitLeft (btreePtr
, leftNode
, rightNode
, node
, index
, key
->keyPtr
,
634 key
->recPtr
, key
->recSize
, newIndex
, newNode
, &recsRotated
);
637 // if we split root node - add new root
639 if ( ((NodeDescPtr
) rightNode
->buffer
)->height
== btreePtr
->treeDepth
)
641 err
= AddNewRootNode (btreePtr
, leftNode
->buffer
, rightNode
->buffer
); // Note: does not update TPT
647 *insertParent
= true;
649 if ( key
->replacingKey
|| (recsRotated
> 1) || (index
> 0) )
650 *updateParent
= true;
657 (void) ReleaseNode (btreePtr
, leftNode
);
660 } // End of InsertNode
663 /*-------------------------------------------------------------------------------
664 Routine: DeleteTree - One_line_description.
666 Function: Brief_description_of_the_function_and_any_side_effects
670 Input: btreePtr - description
671 treePathTable - description
672 targetNode - description
675 Result: noErr - success
677 -------------------------------------------------------------------------------*/
679 OSStatus
DeleteTree (BTreeControlBlockPtr btreePtr
,
680 TreePathTable treePathTable
,
681 BlockDescriptor
*targetNode
,
686 BlockDescriptor parentNode
;
687 BTNodeDescriptor
*targetNodePtr
;
688 UInt32 targetNodeNum
;
689 Boolean deleteRequired
;
690 Boolean updateRequired
;
692 // XXXdbg - initialize these to null in case we get an
693 // error and try to exit before it's initialized
694 parentNode
.buffer
= nil
;
695 parentNode
.blockHeader
= nil
;
697 deleteRequired
= false;
698 updateRequired
= false;
700 targetNodeNum
= treePathTable
[level
].node
;
701 targetNodePtr
= targetNode
->buffer
;
702 PanicIf (targetNodePtr
== nil
, "\pDeleteTree: targetNode has nil buffer!");
705 ModifyBlockStart(btreePtr
->fileRefNum
, targetNode
);
707 DeleteRecord (btreePtr
, targetNodePtr
, index
);
709 //\80\80 coalesce remaining records?
711 if ( targetNodePtr
->numRecords
== 0 ) // did we delete the last record?
713 BlockDescriptor siblingNode
;
714 UInt32 siblingNodeNum
;
716 deleteRequired
= true;
718 siblingNode
.buffer
= nil
;
719 siblingNode
.blockHeader
= nil
;
721 ////////////////// Get Siblings & Update Links //////////////////////////
723 siblingNodeNum
= targetNodePtr
->bLink
; // Left Sibling Node
724 if ( siblingNodeNum
!= 0 )
726 err
= GetNode (btreePtr
, siblingNodeNum
, &siblingNode
);
730 ModifyBlockStart(btreePtr
->fileRefNum
, &siblingNode
);
732 ((NodeDescPtr
)siblingNode
.buffer
)->fLink
= targetNodePtr
->fLink
;
733 err
= UpdateNode (btreePtr
, &siblingNode
, 0, kLockTransaction
);
736 else if ( targetNodePtr
->kind
== kBTLeafNode
) // update firstLeafNode
738 btreePtr
->firstLeafNode
= targetNodePtr
->fLink
;
741 siblingNodeNum
= targetNodePtr
->fLink
; // Right Sibling Node
742 if ( siblingNodeNum
!= 0 )
744 err
= GetNode (btreePtr
, siblingNodeNum
, &siblingNode
);
748 ModifyBlockStart(btreePtr
->fileRefNum
, &siblingNode
);
750 ((NodeDescPtr
)siblingNode
.buffer
)->bLink
= targetNodePtr
->bLink
;
751 err
= UpdateNode (btreePtr
, &siblingNode
, 0, kLockTransaction
);
754 else if ( targetNodePtr
->kind
== kBTLeafNode
) // update lastLeafNode
756 btreePtr
->lastLeafNode
= targetNodePtr
->bLink
;
759 //////////////////////// Free Empty Node ////////////////////////////////
761 ClearNode (btreePtr
, targetNodePtr
);
763 err
= UpdateNode (btreePtr
, targetNode
, 0, kLockTransaction
);
766 err
= FreeNode (btreePtr
, targetNodeNum
);
769 else if ( index
== 0 ) // did we delete the first record?
771 updateRequired
= true; // yes, so we need to update parent
775 if ( level
== btreePtr
->treeDepth
) // then targetNode->buffer is the root node
777 deleteRequired
= false;
778 updateRequired
= false;
780 if ( targetNode
->buffer
== nil
) // then root was freed and the btree is empty
782 btreePtr
->rootNode
= 0;
783 btreePtr
->treeDepth
= 0;
785 else if ( ((NodeDescPtr
)targetNode
->buffer
)->numRecords
== 1 )
787 err
= CollapseTree (btreePtr
, targetNode
);
793 if ( updateRequired
|| deleteRequired
)
795 ++level
; // next level
797 //// Get Parent Node and index
798 index
= treePathTable
[level
].index
;
799 err
= GetNode (btreePtr
, treePathTable
[level
].node
, &parentNode
);
802 if ( updateRequired
)
810 ModifyBlockStart(btreePtr
->fileRefNum
, &parentNode
);
812 //\80\80 debug: check if ptr == targetNodeNum
813 GetRecordByIndex (btreePtr
, parentNode
.buffer
, index
, &keyPtr
, &recPtr
, &recSize
);
814 PanicIf( (*(UInt32
*) recPtr
) != targetNodeNum
, "\p DeleteTree: parent ptr doesn't match targetNodeNum!!");
816 // need to delete and re-insert this parent key/ptr
817 DeleteRecord (btreePtr
, parentNode
.buffer
, index
);
819 keyPtr
= (KeyPtr
) GetRecordAddress( btreePtr
, targetNode
->buffer
, 0 );
820 recPtr
= (UInt8
*) &targetNodeNum
;
821 recSize
= sizeof(targetNodeNum
);
823 err
= InsertTree (btreePtr
, treePathTable
, keyPtr
, recPtr
, recSize
,
824 &parentNode
, index
, level
, kReplaceRecord
, &insertNode
);
827 else // deleteRequired
829 err
= DeleteTree (btreePtr
, treePathTable
, &parentNode
, index
, level
);
835 err
= UpdateNode (btreePtr
, targetNode
, 0, kLockTransaction
);
842 (void) ReleaseNode (btreePtr
, targetNode
);
843 (void) ReleaseNode (btreePtr
, &parentNode
);
851 ///////////////////////////////// CollapseTree //////////////////////////////////
853 static OSStatus
CollapseTree (BTreeControlBlockPtr btreePtr
,
854 BlockDescriptor
*blockPtr
)
860 originalRoot
= btreePtr
->rootNode
;
863 ModifyBlockStart(btreePtr
->fileRefNum
, blockPtr
);
867 if ( ((NodeDescPtr
)blockPtr
->buffer
)->numRecords
> 1)
868 break; // this will make a fine root node
870 if ( ((NodeDescPtr
)blockPtr
->buffer
)->kind
== kBTLeafNode
)
871 break; // we've hit bottom
873 nodeNum
= btreePtr
->rootNode
;
874 btreePtr
->rootNode
= GetChildNodeNum (btreePtr
, blockPtr
->buffer
, 0);
875 --btreePtr
->treeDepth
;
877 //// Clear and Free Current Old Root Node ////
878 ClearNode (btreePtr
, blockPtr
->buffer
);
879 err
= UpdateNode (btreePtr
, blockPtr
, 0, kLockTransaction
);
881 err
= FreeNode (btreePtr
, nodeNum
);
884 //// Get New Root Node
885 err
= GetNode (btreePtr
, btreePtr
->rootNode
, blockPtr
);
889 ModifyBlockStart(btreePtr
->fileRefNum
, blockPtr
);
892 if (btreePtr
->rootNode
!= originalRoot
)
893 M_BTreeHeaderDirty (btreePtr
);
895 err
= UpdateNode (btreePtr
, blockPtr
, 0, kLockTransaction
); // always update!
901 /////////////////////////////////// ErrorExit ///////////////////////////////////
904 (void) ReleaseNode (btreePtr
, blockPtr
);
910 ////////////////////////////////// RotateLeft ///////////////////////////////////
912 /*-------------------------------------------------------------------------------
914 Routine: RotateLeft - One_line_description.
916 Function: Brief_description_of_the_function_and_any_side_effects
918 Algorithm: if rightIndex > insertIndex, subtract 1 for actual rightIndex
920 Input: btreePtr - description
921 leftNode - description
922 rightNode - description
923 rightInsertIndex - description
926 recSize - description
929 insertNodeNum - description
930 recordFit - description
933 Result: noErr - success
935 -------------------------------------------------------------------------------*/
937 static OSStatus
RotateLeft (BTreeControlBlockPtr btreePtr
,
938 NodeDescPtr leftNode
,
939 NodeDescPtr rightNode
,
940 UInt16 rightInsertIndex
,
945 UInt32
*insertNodeNum
,
947 UInt16
*recsRotated
)
952 SInt32 leftSize
, rightSize
;
955 UInt16 lengthFieldSize
;
956 UInt16 index
, moveIndex
;
959 ///////////////////// Determine If Record Will Fit //////////////////////////
961 keyLength
= GetKeyLength(btreePtr
, keyPtr
, (rightNode
->kind
== kBTLeafNode
));
963 // the key's length field is 8-bits in HFS and 16-bits in HFS+
964 if ( btreePtr
->attributes
& kBTBigKeysMask
)
965 lengthFieldSize
= sizeof(UInt16
);
967 lengthFieldSize
= sizeof(UInt8
);
969 insertSize
= keyLength
+ lengthFieldSize
+ recSize
+ sizeof(UInt16
);
971 if ( M_IsOdd (insertSize
) )
972 ++insertSize
; // add pad byte;
974 nodeSize
= btreePtr
->nodeSize
;
976 // add size of insert record to right node
977 rightSize
= nodeSize
- GetNodeFreeSize (btreePtr
, rightNode
) + insertSize
;
978 leftSize
= nodeSize
- GetNodeFreeSize (btreePtr
, leftNode
);
982 while ( leftSize
< rightSize
)
984 if ( moveIndex
< rightInsertIndex
)
986 moveSize
= GetRecordSize (btreePtr
, rightNode
, moveIndex
) + 2;
988 else if ( moveIndex
== rightInsertIndex
)
990 moveSize
= insertSize
;
992 else // ( moveIndex > rightInsertIndex )
994 moveSize
= GetRecordSize (btreePtr
, rightNode
, moveIndex
- 1) + 2;
997 leftSize
+= moveSize
;
998 rightSize
-= moveSize
;
1002 if ( leftSize
> nodeSize
) // undo last move
1004 leftSize
-= moveSize
;
1005 rightSize
+= moveSize
;
1009 if ( rightSize
> nodeSize
) // record won't fit - failure, but not error
1019 // we've found balance point, moveIndex == number of records moved into leftNode
1022 //////////////////////////// Rotate Records /////////////////////////////////
1024 *recsRotated
= moveIndex
;
1028 while ( index
< moveIndex
)
1030 if ( index
== rightInsertIndex
) // insert new record in left node
1032 UInt16 leftInsertIndex
;
1034 leftInsertIndex
= leftNode
->numRecords
;
1036 didItFit
= InsertKeyRecord (btreePtr
, leftNode
, leftInsertIndex
,
1037 keyPtr
, keyLength
, recPtr
, recSize
);
1040 Panic ("\pRotateLeft: InsertKeyRecord (left) returned false!");
1041 err
= fsBTBadRotateErr
;
1045 *insertIndex
= leftInsertIndex
;
1046 *insertNodeNum
= rightNode
->bLink
;
1050 didItFit
= RotateRecordLeft (btreePtr
, leftNode
, rightNode
);
1053 Panic ("\pRotateLeft: RotateRecordLeft returned false!");
1054 err
= fsBTBadRotateErr
;
1062 if ( moveIndex
<= rightInsertIndex
) // then insert new record in right node
1064 rightInsertIndex
-= index
; // adjust for records already rotated
1066 didItFit
= InsertKeyRecord (btreePtr
, rightNode
, rightInsertIndex
,
1067 keyPtr
, keyLength
, recPtr
, recSize
);
1070 Panic ("\pRotateLeft: InsertKeyRecord (right) returned false!");
1071 err
= fsBTBadRotateErr
;
1075 *insertIndex
= rightInsertIndex
;
1076 *insertNodeNum
= leftNode
->fLink
;
1083 ////////////////////////////// Error Exit ///////////////////////////////////
1097 /////////////////////////////////// SplitLeft ///////////////////////////////////
1099 static OSStatus
SplitLeft (BTreeControlBlockPtr btreePtr
,
1100 BlockDescriptor
*leftNode
,
1101 BlockDescriptor
*rightNode
,
1102 UInt32 rightNodeNum
,
1107 UInt16
*insertIndex
,
1108 UInt32
*insertNodeNum
,
1109 UInt16
*recsRotated
)
1112 NodeDescPtr left
, right
;
1117 ///////////////////////////// Compare Nodes /////////////////////////////////
1119 right
= rightNode
->buffer
;
1120 left
= leftNode
->buffer
;
1122 PanicIf ( right
->bLink
!= 0 && left
== 0, "\p SplitLeft: left sibling missing!?" );
1124 /* type should be kBTLeafNode or kBTIndexNode */
1126 if ( (right
->height
== 1) && (right
->kind
!= kBTLeafNode
) )
1127 return fsBTInvalidNodeErr
;
1131 if ( left
->fLink
!= rightNodeNum
)
1132 return fsBTInvalidNodeErr
; //\80\80 E_BadSibling ?
1134 if ( left
->height
!= right
->height
)
1135 return fsBTInvalidNodeErr
; //\80\80 E_BadNodeHeight ?
1137 if ( left
->kind
!= right
->kind
)
1138 return fsBTInvalidNodeErr
; //\80\80 E_BadNodeType ?
1142 ///////////////////////////// Allocate Node /////////////////////////////////
1144 err
= AllocateNode (btreePtr
, &newNodeNum
);
1145 M_ExitOnError (err
);
1148 /////////////// Update Forward Link In Original Left Node ///////////////////
1153 ModifyBlockStart(btreePtr
->fileRefNum
, leftNode
);
1155 left
->fLink
= newNodeNum
;
1156 err
= UpdateNode (btreePtr
, leftNode
, 0, kLockTransaction
);
1157 M_ExitOnError (err
);
1161 /////////////////////// Initialize New Left Node ////////////////////////////
1163 err
= GetNewNode (btreePtr
, newNodeNum
, leftNode
);
1164 M_ExitOnError (err
);
1167 ModifyBlockStart(btreePtr
->fileRefNum
, leftNode
);
1169 left
= leftNode
->buffer
;
1170 left
->fLink
= rightNodeNum
;
1173 // Steal Info From Right Node
1175 left
->bLink
= right
->bLink
;
1176 left
->kind
= right
->kind
;
1177 left
->height
= right
->height
;
1179 right
->bLink
= newNodeNum
; // update Right bLink
1181 if ( (left
->kind
== kBTLeafNode
) && (left
->bLink
== 0) )
1183 // if we're adding a new first leaf node - update BTreeInfoRec
1185 btreePtr
->firstLeafNode
= newNodeNum
;
1186 M_BTreeHeaderDirty (btreePtr
); //\80\80 AllocateNode should have set the bit already...
1189 ////////////////////////////// Rotate Left //////////////////////////////////
1191 err
= RotateLeft (btreePtr
, left
, right
, index
, keyPtr
, recPtr
, recSize
,
1192 insertIndex
, insertNodeNum
, &recordFit
, recsRotated
);
1194 M_ExitOnError (err
);
1200 (void) ReleaseNode (btreePtr
, leftNode
);
1201 (void) ReleaseNode (btreePtr
, rightNode
);
1203 //\80\80 Free new node if allocated?
1214 /////////////////////////////// RotateRecordLeft ////////////////////////////////
1216 static Boolean
RotateRecordLeft (BTreeControlBlockPtr btreePtr
,
1217 NodeDescPtr leftNode
,
1218 NodeDescPtr rightNode
)
1224 size
= GetRecordSize (btreePtr
, rightNode
, 0);
1225 recPtr
= GetRecordAddress (btreePtr
, rightNode
, 0);
1227 recordFit
= InsertRecord (btreePtr
, leftNode
, leftNode
->numRecords
, recPtr
, size
);
1232 DeleteRecord (btreePtr
, rightNode
, 0);
1238 //////////////////////////////// AddNewRootNode /////////////////////////////////
1240 static OSStatus
AddNewRootNode (BTreeControlBlockPtr btreePtr
,
1241 NodeDescPtr leftNode
,
1242 NodeDescPtr rightNode
)
1245 BlockDescriptor rootNode
;
1251 rootNode
.buffer
= nil
;
1252 rootNode
.blockHeader
= nil
;
1254 PanicIf (leftNode
== nil
, "\pAddNewRootNode: leftNode == nil");
1255 PanicIf (rightNode
== nil
, "\pAddNewRootNode: rightNode == nil");
1258 /////////////////////// Initialize New Root Node ////////////////////////////
1260 err
= AllocateNode (btreePtr
, &rootNum
);
1261 M_ExitOnError (err
);
1263 err
= GetNewNode (btreePtr
, rootNum
, &rootNode
);
1264 M_ExitOnError (err
);
1267 ModifyBlockStart(btreePtr
->fileRefNum
, &rootNode
);
1269 ((NodeDescPtr
)rootNode
.buffer
)->kind
= kBTIndexNode
;
1270 ((NodeDescPtr
)rootNode
.buffer
)->height
= ++btreePtr
->treeDepth
;
1273 ///////////////////// Insert Left Node Index Record /////////////////////////
1275 keyPtr
= (KeyPtr
) GetRecordAddress (btreePtr
, leftNode
, 0);
1276 keyLength
= GetKeyLength(btreePtr
, keyPtr
, false);
1278 didItFit
= InsertKeyRecord ( btreePtr
, rootNode
.buffer
, 0, keyPtr
, keyLength
,
1279 (UInt8
*) &rightNode
->bLink
, 4 );
1281 PanicIf ( !didItFit
, "\pAddNewRootNode:InsertKeyRecord failed for left index record");
1284 //////////////////// Insert Right Node Index Record /////////////////////////
1286 keyPtr
= (KeyPtr
) GetRecordAddress (btreePtr
, rightNode
, 0);
1287 keyLength
= GetKeyLength(btreePtr
, keyPtr
, false);
1289 didItFit
= InsertKeyRecord ( btreePtr
, rootNode
.buffer
, 1, keyPtr
, keyLength
,
1290 (UInt8
*) &leftNode
->fLink
, 4 );
1292 PanicIf ( !didItFit
, "\pAddNewRootNode:InsertKeyRecord failed for right index record");
1295 /////////////////////////// Release Root Node ///////////////////////////////
1297 err
= UpdateNode (btreePtr
, &rootNode
, 0, kLockTransaction
);
1298 M_ExitOnError (err
);
1300 // update BTreeInfoRec
1302 btreePtr
->rootNode
= rootNum
;
1303 btreePtr
->flags
|= kBTHeaderDirty
;
1308 ////////////////////////////// Error Exit ///////////////////////////////////
1316 static UInt16
GetKeyLength ( const BTreeControlBlock
*btreePtr
, const BTreeKey
*key
, Boolean forLeafNode
)
1320 if ( forLeafNode
|| btreePtr
->attributes
& kBTVariableIndexKeysMask
)
1321 length
= KeyLength (btreePtr
, key
); // just use actual key length
1323 length
= btreePtr
->maxKeyLength
; // fixed sized index key (i.e. HFS) //\80\80 shouldn't we clear the pad bytes?