File: BTreeMiscOps.c

package info (click to toggle)
hfsprogs 332.25-8
  • links: PTS
  • area: main
  • in suites: squeeze
  • size: 6,424 kB
  • ctags: 7,768
  • sloc: ansic: 58,114; makefile: 59
file content (582 lines) | stat: -rw-r--r-- 15,530 bytes parent folder | download | duplicates (3)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
/*
 * Copyright (c) 1999 Apple Computer, Inc. All rights reserved.
 *
 * @APPLE_LICENSE_HEADER_START@
 * 
 * "Portions Copyright (c) 1999 Apple Computer, Inc.  All Rights
 * Reserved.  This file contains Original Code and/or Modifications of
 * Original Code as defined in and that are subject to the Apple Public
 * Source License Version 1.0 (the 'License').  You may not use this file
 * except in compliance with the License.  Please obtain a copy of the
 * License at http://www.apple.com/publicsource and read it before using
 * this file.
 * 
 * The Original Code and all software distributed under the License are
 * distributed on an 'AS IS' basis, WITHOUT WARRANTY OF ANY KIND, EITHER
 * EXPRESS OR IMPLIED, AND APPLE HEREBY DISCLAIMS ALL SUCH WARRANTIES,
 * INCLUDING WITHOUT LIMITATION, ANY WARRANTIES OF MERCHANTABILITY,
 * FITNESS FOR A PARTICULAR PURPOSE OR NON-INFRINGEMENT.  Please see the
 * License for the specific language governing rights and limitations
 * under the License."
 * 
 * @APPLE_LICENSE_HEADER_END@
 */
/*
	File:		BTreeMiscOps.c

	Contains:	Miscellaneous operations for the BTree Module.

	Version:	xxx put the technology version here xxx

	Written by:	Gordon Sheridan and Bill Bruffey

	Copyright:	� 1992-1999 by Apple Computer, Inc., all rights reserved.
*/

#include "BTreePrivate.h"


////////////////////////////// Routine Definitions //////////////////////////////

/*-------------------------------------------------------------------------------
Routine:	CalcKeyRecordSize	-	Return size of combined key/record structure.

Function:	Rounds keySize and recSize so they will end on word boundaries.
			Does NOT add size of offset.

Input:		keySize		- length of key (including length field)
			recSize		- length of record data

Output:		none
			
Result:		UInt16		- size of combined key/record that will be inserted in btree
-------------------------------------------------------------------------------*/

UInt16		CalcKeyRecordSize		(UInt16					 keySize,
									 UInt16					 recSize )
{
	if ( M_IsOdd (keySize) )	keySize += 1;	// pad byte
	
	if (M_IsOdd (recSize) )		recSize += 1;	// pad byte
	
	return	(keySize + recSize);
}



/*-------------------------------------------------------------------------------
Routine:	VerifyHeader	-	Validate fields of the BTree header record.

Function:	Examines the fields of the BTree header record to determine if the
			fork appears to contain a valid BTree.
			
Input:		forkPtr		- pointer to fork control block
			header		- pointer to BTree header
			
			
Result:		noErr		- success
			!= noErr	- failure
-------------------------------------------------------------------------------*/

OSStatus	VerifyHeader	(SFCB				*filePtr,
							 BTHeaderRec		*header )
{
	UInt32		forkSize;
	UInt32		totalNodes;
	

	switch (header->nodeSize)							// node size == 512*2^n
	{
		case   512:
		case  1024:
		case  2048:
		case  4096:
		case  8192:
		case 16384:
		case 32768:		break;
		default:		return	fsBTInvalidHeaderErr;			//�� E_BadNodeType
	}
	
	totalNodes = header->totalNodes;

	forkSize = totalNodes * header->nodeSize;
	
	if ( forkSize != filePtr->fcbLogicalSize )
		return fsBTInvalidHeaderErr;
	
	if ( header->freeNodes >= totalNodes )
		return fsBTInvalidHeaderErr;
	
	if ( header->rootNode >= totalNodes )
		return fsBTInvalidHeaderErr;
	
	if ( header->firstLeafNode >= totalNodes )
		return fsBTInvalidHeaderErr;
	
	if ( header->lastLeafNode >= totalNodes )
		return fsBTInvalidHeaderErr;
	
	if ( header->treeDepth > kMaxTreeDepth )
		return fsBTInvalidHeaderErr;


	/////////////////////////// Check BTree Type ////////////////////////////////
	
	switch (header->btreeType)
	{
		case	0:					// HFS Type - no Key Descriptor
		case	kUserBTreeType:		// with Key Descriptors etc.
		case	kReservedBTreeType:	// Desktop Mgr BTree ?
									break;

		default:					return fsBTUnknownVersionErr;		
	}
	
	return noErr;
}



/*-------------------------------------------------------------------------------
Routine:	UpdateHeader	-	Write BTreeInfoRec fields to Header node.

Function:	Checks the kBTHeaderDirty flag in the BTreeInfoRec and updates the
			header node if necessary.
			
Input:		btreePtr		- pointer to BTreeInfoRec
			
			
Result:		noErr		- success
			!= noErr	- failure
-------------------------------------------------------------------------------*/

OSStatus	UpdateHeader	(BTreeControlBlockPtr		btreePtr)
{
	OSStatus				err;
	BlockDescriptor			node;
	BTHeaderRec				*header;	

	
	if ((btreePtr->flags & kBTHeaderDirty) == 0)			// btree info already flushed
	return	noErr;
	
	
	err = GetNode (btreePtr, kHeaderNodeNum, &node );
	if (err != noErr)
		return	err;
	
	header = (BTHeaderRec*) (node.buffer + sizeof(BTNodeDescriptor));
	
	header->treeDepth		= btreePtr->treeDepth;
	header->rootNode		= btreePtr->rootNode;
	header->leafRecords		= btreePtr->leafRecords;
	header->firstLeafNode	= btreePtr->firstLeafNode;
	header->lastLeafNode	= btreePtr->lastLeafNode;
	header->nodeSize		= btreePtr->nodeSize;			//�� this shouldn't change
	header->maxKeyLength	= btreePtr->maxKeyLength;		//�� neither should this
	header->totalNodes		= btreePtr->totalNodes;
	header->freeNodes		= btreePtr->freeNodes;
	header->btreeType		= btreePtr->btreeType;

	// ignore	header->clumpSize;							//�� rename this field?

	err = UpdateNode (btreePtr, &node);

	btreePtr->flags &= (~kBTHeaderDirty);

	return	err;
}



/*-------------------------------------------------------------------------------
Routine:	FindIteratorPosition	-	One_line_description.

Function:	Brief_description_of_the_function_and_any_side_effects

Algorithm:	see FSC.BT.BTIterateRecord.PICT

Note:		//�� document side-effects of bad node hints

Input:		btreePtr		- description
			iterator		- description
			

Output:		iterator		- description
			left			- description
			middle			- description
			right			- description
			nodeNum			- description
			returnIndex		- description
			foundRecord		- description
			
			
Result:		noErr		- success
			!= noErr	- failure
-------------------------------------------------------------------------------*/

OSStatus	FindIteratorPosition	(BTreeControlBlockPtr	 btreePtr,
									 BTreeIteratorPtr		 iterator,
									 BlockDescriptor		*left,
									 BlockDescriptor		*middle,
									 BlockDescriptor		*right,
									 UInt32					*returnNodeNum,
									 UInt16					*returnIndex,
									 Boolean				*foundRecord )
{
	OSStatus		err;
	Boolean			foundIt;
	UInt32			nodeNum;
	UInt16			leftIndex,	index,	rightIndex;
	Boolean			validHint;

	// assume btreePtr valid
	// assume left, middle, right point to BlockDescriptors
	// assume nodeNum points to UInt32
	// assume index points to UInt16
	// assume foundRecord points to Boolean
	
	left->buffer		= NULL;
	middle->buffer		= NULL;
	right->buffer		= NULL;
	
	foundIt				= false;
	
	if (iterator == NULL)						// do we have an iterator?
	{
		err = fsBTInvalidIteratorErr;
		goto ErrorExit;
	}

#if SupportsKeyDescriptors
	//�� verify iterator key (change CheckKey to take btreePtr instead of keyDescPtr?)
	if (btreePtr->keyDescPtr != NULL)
	{
		err = CheckKey (&iterator->key, btreePtr->keyDescPtr, btreePtr->maxKeyLength );
		M_ExitOnError (err);
	}
#endif

	err = IsItAHint (btreePtr, iterator, &validHint);
	M_ExitOnError (err);

	nodeNum = iterator->hint.nodeNum;
	if (! validHint)							// does the hint appear to be valid?
	{
		goto SearchTheTree;
	}
	
	err = GetNode (btreePtr, nodeNum, middle);
	if( err == fsBTInvalidNodeErr )	// returned if nodeNum is out of range
		goto SearchTheTree;
		
	M_ExitOnError (err);
	
	if ( ((NodeDescPtr) middle->buffer)->kind		!=	kBTLeafNode ||
		 ((NodeDescPtr) middle->buffer)->numRecords	<=  0 )
	{	
		goto SearchTheTree;
	}
		
	++btreePtr->numValidHints;
	
	foundIt = SearchNode (btreePtr, middle->buffer, &iterator->key, &index);
	if (foundIt == true)
	{
		goto SuccessfulExit;
	}
	
	if (index == 0)
	{
		if (((NodeDescPtr) middle->buffer)->bLink == 0)		// before 1st btree record
		{
			goto SuccessfulExit;
		}
		
		nodeNum = ((NodeDescPtr) middle->buffer)->bLink;
		
		err = GetLeftSiblingNode (btreePtr, middle->buffer, left);
		M_ExitOnError (err);
		
		if ( ((NodeDescPtr) left->buffer)->kind			!=	kBTLeafNode ||
			 ((NodeDescPtr) left->buffer)->numRecords	<=  0 )
		{	
			goto SearchTheTree;
		}
		
		foundIt = SearchNode (btreePtr, left->buffer, &iterator->key, &leftIndex);
		if (foundIt == true)
		{
			*right			= *middle;
			*middle			= *left;
			left->buffer	= NULL;
			index			= leftIndex;
			
			goto SuccessfulExit;
		}
		
		if (leftIndex == 0)									// we're lost!
		{
			goto SearchTheTree;
		}
		else if (leftIndex >= ((NodeDescPtr) left->buffer)->numRecords)
		{
			nodeNum = ((NodeDescPtr) left->buffer)->fLink;
			
			PanicIf (index != 0, "\pFindIteratorPosition: index != 0");	//�� just checking...
			goto SuccessfulExit;
		}
		else
		{
			*right			= *middle;
			*middle			= *left;
			left->buffer	= NULL;
			index			= leftIndex;
			
			goto SuccessfulExit;
		}
	}
	else if (index >= ((NodeDescPtr) middle->buffer)->numRecords)
	{
		if (((NodeDescPtr) middle->buffer)->fLink == 0)	// beyond last record
		{
			goto SuccessfulExit;
		}
		
		nodeNum = ((NodeDescPtr) middle->buffer)->fLink;
		
		err = GetRightSiblingNode (btreePtr, middle->buffer, right);
		M_ExitOnError (err);
		
		if ( ((NodeDescPtr) right->buffer)->kind		!= kBTLeafNode ||
			 ((NodeDescPtr) right->buffer)->numRecords	<=  0 )
		{	
			goto SearchTheTree;
		}

		foundIt = SearchNode (btreePtr, right->buffer, &iterator->key, &rightIndex);
		if (rightIndex >= ((NodeDescPtr) right->buffer)->numRecords)		// we're lost
		{
			goto SearchTheTree;
		}
		else	// we found it, or rightIndex==0, or rightIndex<numRecs
		{
			*left			= *middle;
			*middle			= *right;
			right->buffer	= NULL;
			index			= rightIndex;
			
			goto SuccessfulExit;
		}
	}

	
	//////////////////////////// Search The Tree ////////////////////////////////	

SearchTheTree:
	{
		TreePathTable	treePathTable;		// so we only use stack space if we need to

		err = ReleaseNode (btreePtr, left);			M_ExitOnError (err);
		err = ReleaseNode (btreePtr, middle);		M_ExitOnError (err);
		err = ReleaseNode (btreePtr, right);		M_ExitOnError (err);
	
		err = SearchTree ( btreePtr, &iterator->key, treePathTable, &nodeNum, middle, &index);
		switch (err)				//�� separate find condition from exceptions
		{
			case noErr:			foundIt = true;				break;
			case fsBTRecordNotFoundErr:						break;
			default:				goto ErrorExit;
		}
	}

	/////////////////////////////// Success! ////////////////////////////////////

SuccessfulExit:
	
	*returnNodeNum	= nodeNum;
	*returnIndex 	= index;
	*foundRecord	= foundIt;
	
	return	noErr;
	
	
	////////////////////////////// Error Exit ///////////////////////////////////

ErrorExit:

	(void)	ReleaseNode (btreePtr, left);
	(void)	ReleaseNode (btreePtr, middle);
	(void)	ReleaseNode (btreePtr, right);

	*returnNodeNum	= 0;
	*returnIndex 	= 0;
	*foundRecord	= false;

	return	err;
}



/////////////////////////////// CheckInsertParams ///////////////////////////////

OSStatus	CheckInsertParams		(SFCB						*filePtr,
									 BTreeIterator				*iterator,
									 FSBufferDescriptor			*record,
									 UInt16						 recordLen )
{
	BTreeControlBlockPtr	btreePtr;
	
	if (filePtr == NULL)									return	paramErr;

	btreePtr = (BTreeControlBlockPtr) filePtr->fcbBtree;
	if (btreePtr == NULL)								return	fsBTInvalidFileErr;
	if (iterator == NULL)								return	paramErr;
	if (record	 == NULL)								return	paramErr;
	
#if SupportsKeyDescriptors
	if (btreePtr->keyDescPtr != NULL)
	{
		OSStatus	err;

		err = CheckKey (&iterator->key, btreePtr->keyDescPtr, btreePtr->maxKeyLength);
		if (err != noErr)
			return	err;
	}
#endif

	//	check total key/record size limit
	if ( CalcKeyRecordSize (CalcKeySize(btreePtr, &iterator->key), recordLen) > (btreePtr->nodeSize >> 1))
		return	fsBTRecordTooLargeErr;
	
	return	noErr;
}



/*-------------------------------------------------------------------------------
Routine:	TrySimpleReplace	-	Attempts a simple insert, set, or replace.

Function:	If a hint exitst for the iterator, attempt to find the key in the hint
			node. If the key is found, an insert operation fails. If the is not
			found, a replace operation fails. If the key was not found, and the
			insert position is greater than 0 and less than numRecords, the record
			is inserted, provided there is enough freeSpace.  If the key was found,
			and there is more freeSpace than the difference between the new record
			and the old record, the old record is deleted and the new record is
			inserted.

Assumptions:	iterator key has already been checked by CheckKey


Input:		btreePtr		- description
			iterator		- description
			record			- description
			recordLen		- description
			operation		- description
			

Output:		recordInserted		- description
			
						
Result:		noErr			- success
			E_RecordExits		- insert operation failure
			!= noErr		- GetNode, ReleaseNode, UpdateNode returned an error
-------------------------------------------------------------------------------*/

OSStatus	TrySimpleReplace		(BTreeControlBlockPtr	 btreePtr,
									 NodeDescPtr			 nodePtr,
									 BTreeIterator			*iterator,
									 FSBufferDescriptor		*record,
									 UInt16					 recordLen,
									 Boolean				*recordInserted )
{
	UInt32				oldSpace;
	UInt32				spaceNeeded;
	UInt16				index;
	UInt16				keySize;
	Boolean				foundIt;
	Boolean				didItFit;
	
	
	*recordInserted	= false;								// we'll assume this won't work...
	
	if ( nodePtr->kind != kBTLeafNode )
		return	noErr;	// we're in the weeds!

	foundIt	= SearchNode (btreePtr, nodePtr, &iterator->key, &index);	

	if ( foundIt == false )
		return	noErr;	// we might be lost...
		
	keySize = CalcKeySize(btreePtr, &iterator->key);	// includes length field
	
	spaceNeeded	= CalcKeyRecordSize (keySize, recordLen);
	
	oldSpace = GetRecordSize (btreePtr, nodePtr, index);
	
	if ( spaceNeeded == oldSpace )
	{
		UInt8 *		dst;

		dst = GetRecordAddress (btreePtr, nodePtr, index);

		if ( M_IsOdd (keySize) )
			++keySize;			// add pad byte
		
		dst += keySize;		// skip over key to point at record

		CopyMemory(record->bufferAddress, dst, recordLen);	// blast away...

		*recordInserted = true;
	}
	else if ( (GetNodeFreeSize(btreePtr, nodePtr) + oldSpace) >= spaceNeeded)
	{
		DeleteRecord (btreePtr, nodePtr, index);
	
		didItFit = InsertKeyRecord (btreePtr, nodePtr, index,
										&iterator->key, KeyLength(btreePtr, &iterator->key),
										record->bufferAddress, recordLen);
		PanicIf (didItFit == false, "\pTrySimpleInsert: InsertKeyRecord returned false!");

		*recordInserted = true;
	}
	// else not enough space...

	return	noErr;
}


/*-------------------------------------------------------------------------------
Routine:	IsItAHint	-	checks the hint within a BTreeInterator.

Function:	checks the hint within a BTreeInterator.  If it is non-zero, it may 
			possibly be valid. 

Input:		btreePtr	- pointer to control block for BTree file
			iterator	- pointer to BTreeIterator
			
Output:		answer		- true if the hint looks reasonable
						- false if the hint is 0
			
Result:		noErr			- success
-------------------------------------------------------------------------------*/


OSStatus	IsItAHint	(BTreeControlBlockPtr btreePtr, BTreeIterator *iterator, Boolean *answer)
{
	++btreePtr->numHintChecks;
	
	//�� shouldn't we do a range check?
	if (iterator->hint.nodeNum == 0)
	{
		*answer = false;
	}
	else
	{
		*answer = true;
		++btreePtr->numPossibleHints;
	}
	
	return noErr;
}