[kernel] generic-2.6: sync yaffs code with the official CVS tree
[openwrt.git] / target / linux / generic-2.6 / files / fs / yaffs2 / yaffs_guts.c
1 /*
2 * YAFFS: Yet Another Flash File System. A NAND-flash specific file system.
3 *
4 * Copyright (C) 2002-2007 Aleph One Ltd.
5 * for Toby Churchill Ltd and Brightstar Engineering
6 *
7 * Created by Charles Manning <charles@aleph1.co.uk>
8 *
9 * This program is free software; you can redistribute it and/or modify
10 * it under the terms of the GNU General Public License version 2 as
11 * published by the Free Software Foundation.
12 */
13
14 const char *yaffs_guts_c_version =
15 "$Id: yaffs_guts.c,v 1.56 2008-05-08 23:23:26 charles Exp $";
16
17 #include "yportenv.h"
18
19 #include "yaffsinterface.h"
20 #include "yaffs_guts.h"
21 #include "yaffs_tagsvalidity.h"
22 #include "yaffs_getblockinfo.h"
23
24 #include "yaffs_tagscompat.h"
25 #ifndef CONFIG_YAFFS_USE_OWN_SORT
26 #include "yaffs_qsort.h"
27 #endif
28 #include "yaffs_nand.h"
29
30 #include "yaffs_checkptrw.h"
31
32 #include "yaffs_nand.h"
33 #include "yaffs_packedtags2.h"
34
35
36 #ifdef CONFIG_YAFFS_WINCE
37 void yfsd_LockYAFFS(BOOL fsLockOnly);
38 void yfsd_UnlockYAFFS(BOOL fsLockOnly);
39 #endif
40
41 #define YAFFS_PASSIVE_GC_CHUNKS 2
42
43 #include "yaffs_ecc.h"
44
45
46 /* Robustification (if it ever comes about...) */
47 static void yaffs_RetireBlock(yaffs_Device * dev, int blockInNAND);
48 static void yaffs_HandleWriteChunkError(yaffs_Device * dev, int chunkInNAND, int erasedOk);
49 static void yaffs_HandleWriteChunkOk(yaffs_Device * dev, int chunkInNAND,
50 const __u8 * data,
51 const yaffs_ExtendedTags * tags);
52 static void yaffs_HandleUpdateChunk(yaffs_Device * dev, int chunkInNAND,
53 const yaffs_ExtendedTags * tags);
54
55 /* Other local prototypes */
56 static int yaffs_UnlinkObject( yaffs_Object *obj);
57 static int yaffs_ObjectHasCachedWriteData(yaffs_Object *obj);
58
59 static void yaffs_HardlinkFixup(yaffs_Device *dev, yaffs_Object *hardList);
60
61 static int yaffs_WriteNewChunkWithTagsToNAND(yaffs_Device * dev,
62 const __u8 * buffer,
63 yaffs_ExtendedTags * tags,
64 int useReserve);
65 static int yaffs_PutChunkIntoFile(yaffs_Object * in, int chunkInInode,
66 int chunkInNAND, int inScan);
67
68 static yaffs_Object *yaffs_CreateNewObject(yaffs_Device * dev, int number,
69 yaffs_ObjectType type);
70 static void yaffs_AddObjectToDirectory(yaffs_Object * directory,
71 yaffs_Object * obj);
72 static int yaffs_UpdateObjectHeader(yaffs_Object * in, const YCHAR * name,
73 int force, int isShrink, int shadows);
74 static void yaffs_RemoveObjectFromDirectory(yaffs_Object * obj);
75 static int yaffs_CheckStructures(void);
76 static int yaffs_DeleteWorker(yaffs_Object * in, yaffs_Tnode * tn, __u32 level,
77 int chunkOffset, int *limit);
78 static int yaffs_DoGenericObjectDeletion(yaffs_Object * in);
79
80 static yaffs_BlockInfo *yaffs_GetBlockInfo(yaffs_Device * dev, int blockNo);
81
82
83 static int yaffs_CheckChunkErased(struct yaffs_DeviceStruct *dev,
84 int chunkInNAND);
85
86 static int yaffs_UnlinkWorker(yaffs_Object * obj);
87 static void yaffs_DestroyObject(yaffs_Object * obj);
88
89 static int yaffs_TagsMatch(const yaffs_ExtendedTags * tags, int objectId,
90 int chunkInObject);
91
92 loff_t yaffs_GetFileSize(yaffs_Object * obj);
93
94 static int yaffs_AllocateChunk(yaffs_Device * dev, int useReserve, yaffs_BlockInfo **blockUsedPtr);
95
96 static void yaffs_VerifyFreeChunks(yaffs_Device * dev);
97
98 static void yaffs_CheckObjectDetailsLoaded(yaffs_Object *in);
99
100 #ifdef YAFFS_PARANOID
101 static int yaffs_CheckFileSanity(yaffs_Object * in);
102 #else
103 #define yaffs_CheckFileSanity(in)
104 #endif
105
106 static void yaffs_InvalidateWholeChunkCache(yaffs_Object * in);
107 static void yaffs_InvalidateChunkCache(yaffs_Object * object, int chunkId);
108
109 static void yaffs_InvalidateCheckpoint(yaffs_Device *dev);
110
111 static int yaffs_FindChunkInFile(yaffs_Object * in, int chunkInInode,
112 yaffs_ExtendedTags * tags);
113
114 static __u32 yaffs_GetChunkGroupBase(yaffs_Device *dev, yaffs_Tnode *tn, unsigned pos);
115 static yaffs_Tnode *yaffs_FindLevel0Tnode(yaffs_Device * dev,
116 yaffs_FileStructure * fStruct,
117 __u32 chunkId);
118
119
120 /* Function to calculate chunk and offset */
121
122 static void yaffs_AddrToChunk(yaffs_Device *dev, loff_t addr, int *chunkOut, __u32 *offsetOut)
123 {
124 int chunk;
125 __u32 offset;
126
127 chunk = (__u32)(addr >> dev->chunkShift);
128
129 if(dev->chunkDiv == 1)
130 {
131 /* easy power of 2 case */
132 offset = (__u32)(addr & dev->chunkMask);
133 }
134 else
135 {
136 /* Non power-of-2 case */
137
138 loff_t chunkBase;
139
140 chunk /= dev->chunkDiv;
141
142 chunkBase = ((loff_t)chunk) * dev->nDataBytesPerChunk;
143 offset = (__u32)(addr - chunkBase);
144 }
145
146 *chunkOut = chunk;
147 *offsetOut = offset;
148 }
149
150 /* Function to return the number of shifts for a power of 2 greater than or equal
151 * to the given number
152 * Note we don't try to cater for all possible numbers and this does not have to
153 * be hellishly efficient.
154 */
155
156 static __u32 ShiftsGE(__u32 x)
157 {
158 int extraBits;
159 int nShifts;
160
161 nShifts = extraBits = 0;
162
163 while(x>1){
164 if(x & 1) extraBits++;
165 x>>=1;
166 nShifts++;
167 }
168
169 if(extraBits)
170 nShifts++;
171
172 return nShifts;
173 }
174
175 /* Function to return the number of shifts to get a 1 in bit 0
176 */
177
178 static __u32 Shifts(__u32 x)
179 {
180 int nShifts;
181
182 nShifts = 0;
183
184 if(!x) return 0;
185
186 while( !(x&1)){
187 x>>=1;
188 nShifts++;
189 }
190
191 return nShifts;
192 }
193
194
195
196 /*
197 * Temporary buffer manipulations.
198 */
199
200 static int yaffs_InitialiseTempBuffers(yaffs_Device *dev)
201 {
202 int i;
203 __u8 *buf = (__u8 *)1;
204
205 memset(dev->tempBuffer,0,sizeof(dev->tempBuffer));
206
207 for (i = 0; buf && i < YAFFS_N_TEMP_BUFFERS; i++) {
208 dev->tempBuffer[i].line = 0; /* not in use */
209 dev->tempBuffer[i].buffer = buf =
210 YMALLOC_DMA(dev->totalBytesPerChunk);
211 }
212
213 return buf ? YAFFS_OK : YAFFS_FAIL;
214
215 }
216
217 __u8 *yaffs_GetTempBuffer(yaffs_Device * dev, int lineNo)
218 {
219 int i, j;
220
221 dev->tempInUse++;
222 if(dev->tempInUse > dev->maxTemp)
223 dev->maxTemp = dev->tempInUse;
224
225 for (i = 0; i < YAFFS_N_TEMP_BUFFERS; i++) {
226 if (dev->tempBuffer[i].line == 0) {
227 dev->tempBuffer[i].line = lineNo;
228 if ((i + 1) > dev->maxTemp) {
229 dev->maxTemp = i + 1;
230 for (j = 0; j <= i; j++)
231 dev->tempBuffer[j].maxLine =
232 dev->tempBuffer[j].line;
233 }
234
235 return dev->tempBuffer[i].buffer;
236 }
237 }
238
239 T(YAFFS_TRACE_BUFFERS,
240 (TSTR("Out of temp buffers at line %d, other held by lines:"),
241 lineNo));
242 for (i = 0; i < YAFFS_N_TEMP_BUFFERS; i++) {
243 T(YAFFS_TRACE_BUFFERS, (TSTR(" %d "), dev->tempBuffer[i].line));
244 }
245 T(YAFFS_TRACE_BUFFERS, (TSTR(" " TENDSTR)));
246
247 /*
248 * If we got here then we have to allocate an unmanaged one
249 * This is not good.
250 */
251
252 dev->unmanagedTempAllocations++;
253 return YMALLOC(dev->nDataBytesPerChunk);
254
255 }
256
257 void yaffs_ReleaseTempBuffer(yaffs_Device * dev, __u8 * buffer,
258 int lineNo)
259 {
260 int i;
261
262 dev->tempInUse--;
263
264 for (i = 0; i < YAFFS_N_TEMP_BUFFERS; i++) {
265 if (dev->tempBuffer[i].buffer == buffer) {
266 dev->tempBuffer[i].line = 0;
267 return;
268 }
269 }
270
271 if (buffer) {
272 /* assume it is an unmanaged one. */
273 T(YAFFS_TRACE_BUFFERS,
274 (TSTR("Releasing unmanaged temp buffer in line %d" TENDSTR),
275 lineNo));
276 YFREE(buffer);
277 dev->unmanagedTempDeallocations++;
278 }
279
280 }
281
282 /*
283 * Determine if we have a managed buffer.
284 */
285 int yaffs_IsManagedTempBuffer(yaffs_Device * dev, const __u8 * buffer)
286 {
287 int i;
288 for (i = 0; i < YAFFS_N_TEMP_BUFFERS; i++) {
289 if (dev->tempBuffer[i].buffer == buffer)
290 return 1;
291
292 }
293
294 for (i = 0; i < dev->nShortOpCaches; i++) {
295 if( dev->srCache[i].data == buffer )
296 return 1;
297
298 }
299
300 if (buffer == dev->checkpointBuffer)
301 return 1;
302
303 T(YAFFS_TRACE_ALWAYS,
304 (TSTR("yaffs: unmaged buffer detected.\n" TENDSTR)));
305 return 0;
306 }
307
308
309
310 /*
311 * Chunk bitmap manipulations
312 */
313
314 static Y_INLINE __u8 *yaffs_BlockBits(yaffs_Device * dev, int blk)
315 {
316 if (blk < dev->internalStartBlock || blk > dev->internalEndBlock) {
317 T(YAFFS_TRACE_ERROR,
318 (TSTR("**>> yaffs: BlockBits block %d is not valid" TENDSTR),
319 blk));
320 YBUG();
321 }
322 return dev->chunkBits +
323 (dev->chunkBitmapStride * (blk - dev->internalStartBlock));
324 }
325
326 static Y_INLINE void yaffs_VerifyChunkBitId(yaffs_Device *dev, int blk, int chunk)
327 {
328 if(blk < dev->internalStartBlock || blk > dev->internalEndBlock ||
329 chunk < 0 || chunk >= dev->nChunksPerBlock) {
330 T(YAFFS_TRACE_ERROR,
331 (TSTR("**>> yaffs: Chunk Id (%d:%d) invalid"TENDSTR),blk,chunk));
332 YBUG();
333 }
334 }
335
336 static Y_INLINE void yaffs_ClearChunkBits(yaffs_Device * dev, int blk)
337 {
338 __u8 *blkBits = yaffs_BlockBits(dev, blk);
339
340 memset(blkBits, 0, dev->chunkBitmapStride);
341 }
342
343 static Y_INLINE void yaffs_ClearChunkBit(yaffs_Device * dev, int blk, int chunk)
344 {
345 __u8 *blkBits = yaffs_BlockBits(dev, blk);
346
347 yaffs_VerifyChunkBitId(dev,blk,chunk);
348
349 blkBits[chunk / 8] &= ~(1 << (chunk & 7));
350 }
351
352 static Y_INLINE void yaffs_SetChunkBit(yaffs_Device * dev, int blk, int chunk)
353 {
354 __u8 *blkBits = yaffs_BlockBits(dev, blk);
355
356 yaffs_VerifyChunkBitId(dev,blk,chunk);
357
358 blkBits[chunk / 8] |= (1 << (chunk & 7));
359 }
360
361 static Y_INLINE int yaffs_CheckChunkBit(yaffs_Device * dev, int blk, int chunk)
362 {
363 __u8 *blkBits = yaffs_BlockBits(dev, blk);
364 yaffs_VerifyChunkBitId(dev,blk,chunk);
365
366 return (blkBits[chunk / 8] & (1 << (chunk & 7))) ? 1 : 0;
367 }
368
369 static Y_INLINE int yaffs_StillSomeChunkBits(yaffs_Device * dev, int blk)
370 {
371 __u8 *blkBits = yaffs_BlockBits(dev, blk);
372 int i;
373 for (i = 0; i < dev->chunkBitmapStride; i++) {
374 if (*blkBits)
375 return 1;
376 blkBits++;
377 }
378 return 0;
379 }
380
381 static int yaffs_CountChunkBits(yaffs_Device * dev, int blk)
382 {
383 __u8 *blkBits = yaffs_BlockBits(dev, blk);
384 int i;
385 int n = 0;
386 for (i = 0; i < dev->chunkBitmapStride; i++) {
387 __u8 x = *blkBits;
388 while(x){
389 if(x & 1)
390 n++;
391 x >>=1;
392 }
393
394 blkBits++;
395 }
396 return n;
397 }
398
399 /*
400 * Verification code
401 */
402
403 static int yaffs_SkipVerification(yaffs_Device *dev)
404 {
405 return !(yaffs_traceMask & (YAFFS_TRACE_VERIFY | YAFFS_TRACE_VERIFY_FULL));
406 }
407
408 #if 0
409 static int yaffs_SkipFullVerification(yaffs_Device *dev)
410 {
411 return !(yaffs_traceMask & (YAFFS_TRACE_VERIFY_FULL));
412 }
413
414 #endif
415
416 static int yaffs_SkipNANDVerification(yaffs_Device *dev)
417 {
418 return !(yaffs_traceMask & (YAFFS_TRACE_VERIFY_NAND));
419 }
420
421 static const char * blockStateName[] = {
422 "Unknown",
423 "Needs scanning",
424 "Scanning",
425 "Empty",
426 "Allocating",
427 "Full",
428 "Dirty",
429 "Checkpoint",
430 "Collecting",
431 "Dead"
432 };
433
434 static void yaffs_VerifyBlock(yaffs_Device *dev,yaffs_BlockInfo *bi,int n)
435 {
436 int actuallyUsed;
437 int inUse;
438
439 if(yaffs_SkipVerification(dev))
440 return;
441
442 /* Report illegal runtime states */
443 if(bi->blockState <0 || bi->blockState >= YAFFS_NUMBER_OF_BLOCK_STATES)
444 T(YAFFS_TRACE_VERIFY,(TSTR("Block %d has undefined state %d"TENDSTR),n,bi->blockState));
445
446 switch(bi->blockState){
447 case YAFFS_BLOCK_STATE_UNKNOWN:
448 case YAFFS_BLOCK_STATE_SCANNING:
449 case YAFFS_BLOCK_STATE_NEEDS_SCANNING:
450 T(YAFFS_TRACE_VERIFY,(TSTR("Block %d has bad run-state %s"TENDSTR),
451 n,blockStateName[bi->blockState]));
452 }
453
454 /* Check pages in use and soft deletions are legal */
455
456 actuallyUsed = bi->pagesInUse - bi->softDeletions;
457
458 if(bi->pagesInUse < 0 || bi->pagesInUse > dev->nChunksPerBlock ||
459 bi->softDeletions < 0 || bi->softDeletions > dev->nChunksPerBlock ||
460 actuallyUsed < 0 || actuallyUsed > dev->nChunksPerBlock)
461 T(YAFFS_TRACE_VERIFY,(TSTR("Block %d has illegal values pagesInUsed %d softDeletions %d"TENDSTR),
462 n,bi->pagesInUse,bi->softDeletions));
463
464
465 /* Check chunk bitmap legal */
466 inUse = yaffs_CountChunkBits(dev,n);
467 if(inUse != bi->pagesInUse)
468 T(YAFFS_TRACE_VERIFY,(TSTR("Block %d has inconsistent values pagesInUse %d counted chunk bits %d"TENDSTR),
469 n,bi->pagesInUse,inUse));
470
471 /* Check that the sequence number is valid.
472 * Ten million is legal, but is very unlikely
473 */
474 if(dev->isYaffs2 &&
475 (bi->blockState == YAFFS_BLOCK_STATE_ALLOCATING || bi->blockState == YAFFS_BLOCK_STATE_FULL) &&
476 (bi->sequenceNumber < YAFFS_LOWEST_SEQUENCE_NUMBER || bi->sequenceNumber > 10000000 ))
477 T(YAFFS_TRACE_VERIFY,(TSTR("Block %d has suspect sequence number of %d"TENDSTR),
478 n,bi->sequenceNumber));
479
480 }
481
482 static void yaffs_VerifyCollectedBlock(yaffs_Device *dev,yaffs_BlockInfo *bi,int n)
483 {
484 yaffs_VerifyBlock(dev,bi,n);
485
486 /* After collection the block should be in the erased state */
487 /* TODO: This will need to change if we do partial gc */
488
489 if(bi->blockState != YAFFS_BLOCK_STATE_EMPTY){
490 T(YAFFS_TRACE_ERROR,(TSTR("Block %d is in state %d after gc, should be erased"TENDSTR),
491 n,bi->blockState));
492 }
493 }
494
495 static void yaffs_VerifyBlocks(yaffs_Device *dev)
496 {
497 int i;
498 int nBlocksPerState[YAFFS_NUMBER_OF_BLOCK_STATES];
499 int nIllegalBlockStates = 0;
500
501
502 if(yaffs_SkipVerification(dev))
503 return;
504
505 memset(nBlocksPerState,0,sizeof(nBlocksPerState));
506
507
508 for(i = dev->internalStartBlock; i <= dev->internalEndBlock; i++){
509 yaffs_BlockInfo *bi = yaffs_GetBlockInfo(dev,i);
510 yaffs_VerifyBlock(dev,bi,i);
511
512 if(bi->blockState >=0 && bi->blockState < YAFFS_NUMBER_OF_BLOCK_STATES)
513 nBlocksPerState[bi->blockState]++;
514 else
515 nIllegalBlockStates++;
516
517 }
518
519 T(YAFFS_TRACE_VERIFY,(TSTR(""TENDSTR)));
520 T(YAFFS_TRACE_VERIFY,(TSTR("Block summary"TENDSTR)));
521
522 T(YAFFS_TRACE_VERIFY,(TSTR("%d blocks have illegal states"TENDSTR),nIllegalBlockStates));
523 if(nBlocksPerState[YAFFS_BLOCK_STATE_ALLOCATING] > 1)
524 T(YAFFS_TRACE_VERIFY,(TSTR("Too many allocating blocks"TENDSTR)));
525
526 for(i = 0; i < YAFFS_NUMBER_OF_BLOCK_STATES; i++)
527 T(YAFFS_TRACE_VERIFY,
528 (TSTR("%s %d blocks"TENDSTR),
529 blockStateName[i],nBlocksPerState[i]));
530
531 if(dev->blocksInCheckpoint != nBlocksPerState[YAFFS_BLOCK_STATE_CHECKPOINT])
532 T(YAFFS_TRACE_VERIFY,
533 (TSTR("Checkpoint block count wrong dev %d count %d"TENDSTR),
534 dev->blocksInCheckpoint, nBlocksPerState[YAFFS_BLOCK_STATE_CHECKPOINT]));
535
536 if(dev->nErasedBlocks != nBlocksPerState[YAFFS_BLOCK_STATE_EMPTY])
537 T(YAFFS_TRACE_VERIFY,
538 (TSTR("Erased block count wrong dev %d count %d"TENDSTR),
539 dev->nErasedBlocks, nBlocksPerState[YAFFS_BLOCK_STATE_EMPTY]));
540
541 if(nBlocksPerState[YAFFS_BLOCK_STATE_COLLECTING] > 1)
542 T(YAFFS_TRACE_VERIFY,
543 (TSTR("Too many collecting blocks %d (max is 1)"TENDSTR),
544 nBlocksPerState[YAFFS_BLOCK_STATE_COLLECTING]));
545
546 T(YAFFS_TRACE_VERIFY,(TSTR(""TENDSTR)));
547
548 }
549
550 /*
551 * Verify the object header. oh must be valid, but obj and tags may be NULL in which
552 * case those tests will not be performed.
553 */
554 static void yaffs_VerifyObjectHeader(yaffs_Object *obj, yaffs_ObjectHeader *oh, yaffs_ExtendedTags *tags, int parentCheck)
555 {
556 if(yaffs_SkipVerification(obj->myDev))
557 return;
558
559 if(!(tags && obj && oh)){
560 T(YAFFS_TRACE_VERIFY,
561 (TSTR("Verifying object header tags %x obj %x oh %x"TENDSTR),
562 (__u32)tags,(__u32)obj,(__u32)oh));
563 return;
564 }
565
566 if(oh->type <= YAFFS_OBJECT_TYPE_UNKNOWN ||
567 oh->type > YAFFS_OBJECT_TYPE_MAX)
568 T(YAFFS_TRACE_VERIFY,
569 (TSTR("Obj %d header type is illegal value 0x%x"TENDSTR),
570 tags->objectId, oh->type));
571
572 if(tags->objectId != obj->objectId)
573 T(YAFFS_TRACE_VERIFY,
574 (TSTR("Obj %d header mismatch objectId %d"TENDSTR),
575 tags->objectId, obj->objectId));
576
577
578 /*
579 * Check that the object's parent ids match if parentCheck requested.
580 *
581 * Tests do not apply to the root object.
582 */
583
584 if(parentCheck && tags->objectId > 1 && !obj->parent)
585 T(YAFFS_TRACE_VERIFY,
586 (TSTR("Obj %d header mismatch parentId %d obj->parent is NULL"TENDSTR),
587 tags->objectId, oh->parentObjectId));
588
589
590 if(parentCheck && obj->parent &&
591 oh->parentObjectId != obj->parent->objectId &&
592 (oh->parentObjectId != YAFFS_OBJECTID_UNLINKED ||
593 obj->parent->objectId != YAFFS_OBJECTID_DELETED))
594 T(YAFFS_TRACE_VERIFY,
595 (TSTR("Obj %d header mismatch parentId %d parentObjectId %d"TENDSTR),
596 tags->objectId, oh->parentObjectId, obj->parent->objectId));
597
598
599 if(tags->objectId > 1 && oh->name[0] == 0) /* Null name */
600 T(YAFFS_TRACE_VERIFY,
601 (TSTR("Obj %d header name is NULL"TENDSTR),
602 obj->objectId));
603
604 if(tags->objectId > 1 && ((__u8)(oh->name[0])) == 0xff) /* Trashed name */
605 T(YAFFS_TRACE_VERIFY,
606 (TSTR("Obj %d header name is 0xFF"TENDSTR),
607 obj->objectId));
608 }
609
610
611
612 static int yaffs_VerifyTnodeWorker(yaffs_Object * obj, yaffs_Tnode * tn,
613 __u32 level, int chunkOffset)
614 {
615 int i;
616 yaffs_Device *dev = obj->myDev;
617 int ok = 1;
618
619 if (tn) {
620 if (level > 0) {
621
622 for (i = 0; i < YAFFS_NTNODES_INTERNAL && ok; i++){
623 if (tn->internal[i]) {
624 ok = yaffs_VerifyTnodeWorker(obj,
625 tn->internal[i],
626 level - 1,
627 (chunkOffset<<YAFFS_TNODES_INTERNAL_BITS) + i);
628 }
629 }
630 } else if (level == 0) {
631 int i;
632 yaffs_ExtendedTags tags;
633 __u32 objectId = obj->objectId;
634
635 chunkOffset <<= YAFFS_TNODES_LEVEL0_BITS;
636
637 for(i = 0; i < YAFFS_NTNODES_LEVEL0; i++){
638 __u32 theChunk = yaffs_GetChunkGroupBase(dev,tn,i);
639
640 if(theChunk > 0){
641 /* T(~0,(TSTR("verifying (%d:%d) %d"TENDSTR),tags.objectId,tags.chunkId,theChunk)); */
642 yaffs_ReadChunkWithTagsFromNAND(dev,theChunk,NULL, &tags);
643 if(tags.objectId != objectId || tags.chunkId != chunkOffset){
644 T(~0,(TSTR("Object %d chunkId %d NAND mismatch chunk %d tags (%d:%d)"TENDSTR),
645 objectId, chunkOffset, theChunk,
646 tags.objectId, tags.chunkId));
647 }
648 }
649 chunkOffset++;
650 }
651 }
652 }
653
654 return ok;
655
656 }
657
658
659 static void yaffs_VerifyFile(yaffs_Object *obj)
660 {
661 int requiredTallness;
662 int actualTallness;
663 __u32 lastChunk;
664 __u32 x;
665 __u32 i;
666 yaffs_Device *dev;
667 yaffs_ExtendedTags tags;
668 yaffs_Tnode *tn;
669 __u32 objectId;
670
671 if(obj && yaffs_SkipVerification(obj->myDev))
672 return;
673
674 dev = obj->myDev;
675 objectId = obj->objectId;
676
677 /* Check file size is consistent with tnode depth */
678 lastChunk = obj->variant.fileVariant.fileSize / dev->nDataBytesPerChunk + 1;
679 x = lastChunk >> YAFFS_TNODES_LEVEL0_BITS;
680 requiredTallness = 0;
681 while (x> 0) {
682 x >>= YAFFS_TNODES_INTERNAL_BITS;
683 requiredTallness++;
684 }
685
686 actualTallness = obj->variant.fileVariant.topLevel;
687
688 if(requiredTallness > actualTallness )
689 T(YAFFS_TRACE_VERIFY,
690 (TSTR("Obj %d had tnode tallness %d, needs to be %d"TENDSTR),
691 obj->objectId,actualTallness, requiredTallness));
692
693
694 /* Check that the chunks in the tnode tree are all correct.
695 * We do this by scanning through the tnode tree and
696 * checking the tags for every chunk match.
697 */
698
699 if(yaffs_SkipNANDVerification(dev))
700 return;
701
702 for(i = 1; i <= lastChunk; i++){
703 tn = yaffs_FindLevel0Tnode(dev, &obj->variant.fileVariant,i);
704
705 if (tn) {
706 __u32 theChunk = yaffs_GetChunkGroupBase(dev,tn,i);
707 if(theChunk > 0){
708 /* T(~0,(TSTR("verifying (%d:%d) %d"TENDSTR),objectId,i,theChunk)); */
709 yaffs_ReadChunkWithTagsFromNAND(dev,theChunk,NULL, &tags);
710 if(tags.objectId != objectId || tags.chunkId != i){
711 T(~0,(TSTR("Object %d chunkId %d NAND mismatch chunk %d tags (%d:%d)"TENDSTR),
712 objectId, i, theChunk,
713 tags.objectId, tags.chunkId));
714 }
715 }
716 }
717
718 }
719
720 }
721
722 static void yaffs_VerifyDirectory(yaffs_Object *obj)
723 {
724 if(obj && yaffs_SkipVerification(obj->myDev))
725 return;
726
727 }
728
729 static void yaffs_VerifyHardLink(yaffs_Object *obj)
730 {
731 if(obj && yaffs_SkipVerification(obj->myDev))
732 return;
733
734 /* Verify sane equivalent object */
735 }
736
737 static void yaffs_VerifySymlink(yaffs_Object *obj)
738 {
739 if(obj && yaffs_SkipVerification(obj->myDev))
740 return;
741
742 /* Verify symlink string */
743 }
744
745 static void yaffs_VerifySpecial(yaffs_Object *obj)
746 {
747 if(obj && yaffs_SkipVerification(obj->myDev))
748 return;
749 }
750
751 static void yaffs_VerifyObject(yaffs_Object *obj)
752 {
753 yaffs_Device *dev;
754
755 __u32 chunkMin;
756 __u32 chunkMax;
757
758 __u32 chunkIdOk;
759 __u32 chunkIsLive;
760
761 if(!obj)
762 return;
763
764 dev = obj->myDev;
765
766 if(yaffs_SkipVerification(dev))
767 return;
768
769 /* Check sane object header chunk */
770
771 chunkMin = dev->internalStartBlock * dev->nChunksPerBlock;
772 chunkMax = (dev->internalEndBlock+1) * dev->nChunksPerBlock - 1;
773
774 chunkIdOk = (obj->chunkId >= chunkMin && obj->chunkId <= chunkMax);
775 chunkIsLive = chunkIdOk &&
776 yaffs_CheckChunkBit(dev,
777 obj->chunkId / dev->nChunksPerBlock,
778 obj->chunkId % dev->nChunksPerBlock);
779 if(!obj->fake &&
780 (!chunkIdOk || !chunkIsLive)) {
781 T(YAFFS_TRACE_VERIFY,
782 (TSTR("Obj %d has chunkId %d %s %s"TENDSTR),
783 obj->objectId,obj->chunkId,
784 chunkIdOk ? "" : ",out of range",
785 chunkIsLive || !chunkIdOk ? "" : ",marked as deleted"));
786 }
787
788 if(chunkIdOk && chunkIsLive &&!yaffs_SkipNANDVerification(dev)) {
789 yaffs_ExtendedTags tags;
790 yaffs_ObjectHeader *oh;
791 __u8 *buffer = yaffs_GetTempBuffer(dev,__LINE__);
792
793 oh = (yaffs_ObjectHeader *)buffer;
794
795 yaffs_ReadChunkWithTagsFromNAND(dev, obj->chunkId,buffer, &tags);
796
797 yaffs_VerifyObjectHeader(obj,oh,&tags,1);
798
799 yaffs_ReleaseTempBuffer(dev,buffer,__LINE__);
800 }
801
802 /* Verify it has a parent */
803 if(obj && !obj->fake &&
804 (!obj->parent || obj->parent->myDev != dev)){
805 T(YAFFS_TRACE_VERIFY,
806 (TSTR("Obj %d has parent pointer %p which does not look like an object"TENDSTR),
807 obj->objectId,obj->parent));
808 }
809
810 /* Verify parent is a directory */
811 if(obj->parent && obj->parent->variantType != YAFFS_OBJECT_TYPE_DIRECTORY){
812 T(YAFFS_TRACE_VERIFY,
813 (TSTR("Obj %d's parent is not a directory (type %d)"TENDSTR),
814 obj->objectId,obj->parent->variantType));
815 }
816
817 switch(obj->variantType){
818 case YAFFS_OBJECT_TYPE_FILE:
819 yaffs_VerifyFile(obj);
820 break;
821 case YAFFS_OBJECT_TYPE_SYMLINK:
822 yaffs_VerifySymlink(obj);
823 break;
824 case YAFFS_OBJECT_TYPE_DIRECTORY:
825 yaffs_VerifyDirectory(obj);
826 break;
827 case YAFFS_OBJECT_TYPE_HARDLINK:
828 yaffs_VerifyHardLink(obj);
829 break;
830 case YAFFS_OBJECT_TYPE_SPECIAL:
831 yaffs_VerifySpecial(obj);
832 break;
833 case YAFFS_OBJECT_TYPE_UNKNOWN:
834 default:
835 T(YAFFS_TRACE_VERIFY,
836 (TSTR("Obj %d has illegaltype %d"TENDSTR),
837 obj->objectId,obj->variantType));
838 break;
839 }
840
841
842 }
843
844 static void yaffs_VerifyObjects(yaffs_Device *dev)
845 {
846 yaffs_Object *obj;
847 int i;
848 struct ylist_head *lh;
849
850 if(yaffs_SkipVerification(dev))
851 return;
852
853 /* Iterate through the objects in each hash entry */
854
855 for(i = 0; i < YAFFS_NOBJECT_BUCKETS; i++){
856 ylist_for_each(lh, &dev->objectBucket[i].list) {
857 if (lh) {
858 obj = ylist_entry(lh, yaffs_Object, hashLink);
859 yaffs_VerifyObject(obj);
860 }
861 }
862 }
863
864 }
865
866
867 /*
868 * Simple hash function. Needs to have a reasonable spread
869 */
870
871 static Y_INLINE int yaffs_HashFunction(int n)
872 {
873 n = abs(n);
874 return (n % YAFFS_NOBJECT_BUCKETS);
875 }
876
877 /*
878 * Access functions to useful fake objects
879 */
880
881 yaffs_Object *yaffs_Root(yaffs_Device * dev)
882 {
883 return dev->rootDir;
884 }
885
886 yaffs_Object *yaffs_LostNFound(yaffs_Device * dev)
887 {
888 return dev->lostNFoundDir;
889 }
890
891
892 /*
893 * Erased NAND checking functions
894 */
895
896 int yaffs_CheckFF(__u8 * buffer, int nBytes)
897 {
898 /* Horrible, slow implementation */
899 while (nBytes--) {
900 if (*buffer != 0xFF)
901 return 0;
902 buffer++;
903 }
904 return 1;
905 }
906
907 static int yaffs_CheckChunkErased(struct yaffs_DeviceStruct *dev,
908 int chunkInNAND)
909 {
910
911 int retval = YAFFS_OK;
912 __u8 *data = yaffs_GetTempBuffer(dev, __LINE__);
913 yaffs_ExtendedTags tags;
914 int result;
915
916 result = yaffs_ReadChunkWithTagsFromNAND(dev, chunkInNAND, data, &tags);
917
918 if(tags.eccResult > YAFFS_ECC_RESULT_NO_ERROR)
919 retval = YAFFS_FAIL;
920
921
922 if (!yaffs_CheckFF(data, dev->nDataBytesPerChunk) || tags.chunkUsed) {
923 T(YAFFS_TRACE_NANDACCESS,
924 (TSTR("Chunk %d not erased" TENDSTR), chunkInNAND));
925 retval = YAFFS_FAIL;
926 }
927
928 yaffs_ReleaseTempBuffer(dev, data, __LINE__);
929
930 return retval;
931
932 }
933
934 static int yaffs_WriteNewChunkWithTagsToNAND(struct yaffs_DeviceStruct *dev,
935 const __u8 * data,
936 yaffs_ExtendedTags * tags,
937 int useReserve)
938 {
939 int attempts = 0;
940 int writeOk = 0;
941 int chunk;
942
943 yaffs_InvalidateCheckpoint(dev);
944
945 do {
946 yaffs_BlockInfo *bi = 0;
947 int erasedOk = 0;
948
949 chunk = yaffs_AllocateChunk(dev, useReserve, &bi);
950 if (chunk < 0) {
951 /* no space */
952 break;
953 }
954
955 /* First check this chunk is erased, if it needs
956 * checking. The checking policy (unless forced
957 * always on) is as follows:
958 *
959 * Check the first page we try to write in a block.
960 * If the check passes then we don't need to check any
961 * more. If the check fails, we check again...
962 * If the block has been erased, we don't need to check.
963 *
964 * However, if the block has been prioritised for gc,
965 * then we think there might be something odd about
966 * this block and stop using it.
967 *
968 * Rationale: We should only ever see chunks that have
969 * not been erased if there was a partially written
970 * chunk due to power loss. This checking policy should
971 * catch that case with very few checks and thus save a
972 * lot of checks that are most likely not needed.
973 */
974 if (bi->gcPrioritise) {
975 yaffs_DeleteChunk(dev, chunk, 1, __LINE__);
976 /* try another chunk */
977 continue;
978 }
979
980 /* let's give it a try */
981 attempts++;
982
983 #ifdef CONFIG_YAFFS_ALWAYS_CHECK_CHUNK_ERASED
984 bi->skipErasedCheck = 0;
985 #endif
986 if (!bi->skipErasedCheck) {
987 erasedOk = yaffs_CheckChunkErased(dev, chunk);
988 if (erasedOk != YAFFS_OK) {
989 T(YAFFS_TRACE_ERROR,
990 (TSTR ("**>> yaffs chunk %d was not erased"
991 TENDSTR), chunk));
992
993 /* try another chunk */
994 continue;
995 }
996 bi->skipErasedCheck = 1;
997 }
998
999 writeOk = yaffs_WriteChunkWithTagsToNAND(dev, chunk,
1000 data, tags);
1001 if (writeOk != YAFFS_OK) {
1002 yaffs_HandleWriteChunkError(dev, chunk, erasedOk);
1003 /* try another chunk */
1004 continue;
1005 }
1006
1007 /* Copy the data into the robustification buffer */
1008 yaffs_HandleWriteChunkOk(dev, chunk, data, tags);
1009
1010 } while (writeOk != YAFFS_OK &&
1011 (yaffs_wr_attempts <= 0 || attempts <= yaffs_wr_attempts));
1012
1013 if(!writeOk)
1014 chunk = -1;
1015
1016 if (attempts > 1) {
1017 T(YAFFS_TRACE_ERROR,
1018 (TSTR("**>> yaffs write required %d attempts" TENDSTR),
1019 attempts));
1020
1021 dev->nRetriedWrites += (attempts - 1);
1022 }
1023
1024 return chunk;
1025 }
1026
1027 /*
1028 * Block retiring for handling a broken block.
1029 */
1030
1031 static void yaffs_RetireBlock(yaffs_Device * dev, int blockInNAND)
1032 {
1033 yaffs_BlockInfo *bi = yaffs_GetBlockInfo(dev, blockInNAND);
1034
1035 yaffs_InvalidateCheckpoint(dev);
1036
1037 yaffs_MarkBlockBad(dev, blockInNAND);
1038
1039 bi->blockState = YAFFS_BLOCK_STATE_DEAD;
1040 bi->gcPrioritise = 0;
1041 bi->needsRetiring = 0;
1042
1043 dev->nRetiredBlocks++;
1044 }
1045
1046 /*
1047 * Functions for robustisizing TODO
1048 *
1049 */
1050
1051 static void yaffs_HandleWriteChunkOk(yaffs_Device * dev, int chunkInNAND,
1052 const __u8 * data,
1053 const yaffs_ExtendedTags * tags)
1054 {
1055 }
1056
1057 static void yaffs_HandleUpdateChunk(yaffs_Device * dev, int chunkInNAND,
1058 const yaffs_ExtendedTags * tags)
1059 {
1060 }
1061
1062 void yaffs_HandleChunkError(yaffs_Device *dev, yaffs_BlockInfo *bi)
1063 {
1064 if(!bi->gcPrioritise){
1065 bi->gcPrioritise = 1;
1066 dev->hasPendingPrioritisedGCs = 1;
1067 bi->chunkErrorStrikes ++;
1068
1069 if(bi->chunkErrorStrikes > 3){
1070 bi->needsRetiring = 1; /* Too many stikes, so retire this */
1071 T(YAFFS_TRACE_ALWAYS, (TSTR("yaffs: Block struck out" TENDSTR)));
1072
1073 }
1074
1075 }
1076 }
1077
1078 static void yaffs_HandleWriteChunkError(yaffs_Device * dev, int chunkInNAND, int erasedOk)
1079 {
1080
1081 int blockInNAND = chunkInNAND / dev->nChunksPerBlock;
1082 yaffs_BlockInfo *bi = yaffs_GetBlockInfo(dev, blockInNAND);
1083
1084 yaffs_HandleChunkError(dev,bi);
1085
1086
1087 if(erasedOk ) {
1088 /* Was an actual write failure, so mark the block for retirement */
1089 bi->needsRetiring = 1;
1090 T(YAFFS_TRACE_ERROR | YAFFS_TRACE_BAD_BLOCKS,
1091 (TSTR("**>> Block %d needs retiring" TENDSTR), blockInNAND));
1092
1093
1094 }
1095
1096 /* Delete the chunk */
1097 yaffs_DeleteChunk(dev, chunkInNAND, 1, __LINE__);
1098 }
1099
1100
1101 /*---------------- Name handling functions ------------*/
1102
1103 static __u16 yaffs_CalcNameSum(const YCHAR * name)
1104 {
1105 __u16 sum = 0;
1106 __u16 i = 1;
1107
1108 YUCHAR *bname = (YUCHAR *) name;
1109 if (bname) {
1110 while ((*bname) && (i < (YAFFS_MAX_NAME_LENGTH/2))) {
1111
1112 #ifdef CONFIG_YAFFS_CASE_INSENSITIVE
1113 sum += yaffs_toupper(*bname) * i;
1114 #else
1115 sum += (*bname) * i;
1116 #endif
1117 i++;
1118 bname++;
1119 }
1120 }
1121 return sum;
1122 }
1123
1124 static void yaffs_SetObjectName(yaffs_Object * obj, const YCHAR * name)
1125 {
1126 #ifdef CONFIG_YAFFS_SHORT_NAMES_IN_RAM
1127 if (name && yaffs_strlen(name) <= YAFFS_SHORT_NAME_LENGTH) {
1128 yaffs_strcpy(obj->shortName, name);
1129 } else {
1130 obj->shortName[0] = _Y('\0');
1131 }
1132 #endif
1133 obj->sum = yaffs_CalcNameSum(name);
1134 }
1135
1136 /*-------------------- TNODES -------------------
1137
1138 * List of spare tnodes
1139 * The list is hooked together using the first pointer
1140 * in the tnode.
1141 */
1142
1143 /* yaffs_CreateTnodes creates a bunch more tnodes and
1144 * adds them to the tnode free list.
1145 * Don't use this function directly
1146 */
1147
1148 static int yaffs_CreateTnodes(yaffs_Device * dev, int nTnodes)
1149 {
1150 int i;
1151 int tnodeSize;
1152 yaffs_Tnode *newTnodes;
1153 __u8 *mem;
1154 yaffs_Tnode *curr;
1155 yaffs_Tnode *next;
1156 yaffs_TnodeList *tnl;
1157
1158 if (nTnodes < 1)
1159 return YAFFS_OK;
1160
1161 /* Calculate the tnode size in bytes for variable width tnode support.
1162 * Must be a multiple of 32-bits */
1163 tnodeSize = (dev->tnodeWidth * YAFFS_NTNODES_LEVEL0)/8;
1164
1165 if(tnodeSize < sizeof(yaffs_Tnode))
1166 tnodeSize = sizeof(yaffs_Tnode);
1167
1168
1169 /* make these things */
1170
1171 newTnodes = YMALLOC(nTnodes * tnodeSize);
1172 mem = (__u8 *)newTnodes;
1173
1174 if (!newTnodes) {
1175 T(YAFFS_TRACE_ERROR,
1176 (TSTR("yaffs: Could not allocate Tnodes" TENDSTR)));
1177 return YAFFS_FAIL;
1178 }
1179
1180 /* Hook them into the free list */
1181 #if 0
1182 for (i = 0; i < nTnodes - 1; i++) {
1183 newTnodes[i].internal[0] = &newTnodes[i + 1];
1184 #ifdef CONFIG_YAFFS_TNODE_LIST_DEBUG
1185 newTnodes[i].internal[YAFFS_NTNODES_INTERNAL] = (void *)1;
1186 #endif
1187 }
1188
1189 newTnodes[nTnodes - 1].internal[0] = dev->freeTnodes;
1190 #ifdef CONFIG_YAFFS_TNODE_LIST_DEBUG
1191 newTnodes[nTnodes - 1].internal[YAFFS_NTNODES_INTERNAL] = (void *)1;
1192 #endif
1193 dev->freeTnodes = newTnodes;
1194 #else
1195 /* New hookup for wide tnodes */
1196 for(i = 0; i < nTnodes -1; i++) {
1197 curr = (yaffs_Tnode *) &mem[i * tnodeSize];
1198 next = (yaffs_Tnode *) &mem[(i+1) * tnodeSize];
1199 curr->internal[0] = next;
1200 }
1201
1202 curr = (yaffs_Tnode *) &mem[(nTnodes - 1) * tnodeSize];
1203 curr->internal[0] = dev->freeTnodes;
1204 dev->freeTnodes = (yaffs_Tnode *)mem;
1205
1206 #endif
1207
1208
1209 dev->nFreeTnodes += nTnodes;
1210 dev->nTnodesCreated += nTnodes;
1211
1212 /* Now add this bunch of tnodes to a list for freeing up.
1213 * NB If we can't add this to the management list it isn't fatal
1214 * but it just means we can't free this bunch of tnodes later.
1215 */
1216
1217 tnl = YMALLOC(sizeof(yaffs_TnodeList));
1218 if (!tnl) {
1219 T(YAFFS_TRACE_ERROR,
1220 (TSTR
1221 ("yaffs: Could not add tnodes to management list" TENDSTR)));
1222 return YAFFS_FAIL;
1223
1224 } else {
1225 tnl->tnodes = newTnodes;
1226 tnl->next = dev->allocatedTnodeList;
1227 dev->allocatedTnodeList = tnl;
1228 }
1229
1230 T(YAFFS_TRACE_ALLOCATE, (TSTR("yaffs: Tnodes added" TENDSTR)));
1231
1232 return YAFFS_OK;
1233 }
1234
1235 /* GetTnode gets us a clean tnode. Tries to make allocate more if we run out */
1236
1237 static yaffs_Tnode *yaffs_GetTnodeRaw(yaffs_Device * dev)
1238 {
1239 yaffs_Tnode *tn = NULL;
1240
1241 /* If there are none left make more */
1242 if (!dev->freeTnodes) {
1243 yaffs_CreateTnodes(dev, YAFFS_ALLOCATION_NTNODES);
1244 }
1245
1246 if (dev->freeTnodes) {
1247 tn = dev->freeTnodes;
1248 #ifdef CONFIG_YAFFS_TNODE_LIST_DEBUG
1249 if (tn->internal[YAFFS_NTNODES_INTERNAL] != (void *)1) {
1250 /* Hoosterman, this thing looks like it isn't in the list */
1251 T(YAFFS_TRACE_ALWAYS,
1252 (TSTR("yaffs: Tnode list bug 1" TENDSTR)));
1253 }
1254 #endif
1255 dev->freeTnodes = dev->freeTnodes->internal[0];
1256 dev->nFreeTnodes--;
1257 }
1258
1259 dev->nCheckpointBlocksRequired = 0; /* force recalculation*/
1260
1261 return tn;
1262 }
1263
1264 static yaffs_Tnode *yaffs_GetTnode(yaffs_Device * dev)
1265 {
1266 yaffs_Tnode *tn = yaffs_GetTnodeRaw(dev);
1267 int tnodeSize = (dev->tnodeWidth * YAFFS_NTNODES_LEVEL0)/8;
1268
1269 if(tnodeSize < sizeof(yaffs_Tnode))
1270 tnodeSize = sizeof(yaffs_Tnode);
1271
1272 if(tn)
1273 memset(tn, 0, tnodeSize);
1274
1275 return tn;
1276 }
1277
1278 /* FreeTnode frees up a tnode and puts it back on the free list */
1279 static void yaffs_FreeTnode(yaffs_Device * dev, yaffs_Tnode * tn)
1280 {
1281 if (tn) {
1282 #ifdef CONFIG_YAFFS_TNODE_LIST_DEBUG
1283 if (tn->internal[YAFFS_NTNODES_INTERNAL] != 0) {
1284 /* Hoosterman, this thing looks like it is already in the list */
1285 T(YAFFS_TRACE_ALWAYS,
1286 (TSTR("yaffs: Tnode list bug 2" TENDSTR)));
1287 }
1288 tn->internal[YAFFS_NTNODES_INTERNAL] = (void *)1;
1289 #endif
1290 tn->internal[0] = dev->freeTnodes;
1291 dev->freeTnodes = tn;
1292 dev->nFreeTnodes++;
1293 }
1294 dev->nCheckpointBlocksRequired = 0; /* force recalculation*/
1295
1296 }
1297
1298 static void yaffs_DeinitialiseTnodes(yaffs_Device * dev)
1299 {
1300 /* Free the list of allocated tnodes */
1301 yaffs_TnodeList *tmp;
1302
1303 while (dev->allocatedTnodeList) {
1304 tmp = dev->allocatedTnodeList->next;
1305
1306 YFREE(dev->allocatedTnodeList->tnodes);
1307 YFREE(dev->allocatedTnodeList);
1308 dev->allocatedTnodeList = tmp;
1309
1310 }
1311
1312 dev->freeTnodes = NULL;
1313 dev->nFreeTnodes = 0;
1314 }
1315
1316 static void yaffs_InitialiseTnodes(yaffs_Device * dev)
1317 {
1318 dev->allocatedTnodeList = NULL;
1319 dev->freeTnodes = NULL;
1320 dev->nFreeTnodes = 0;
1321 dev->nTnodesCreated = 0;
1322
1323 }
1324
1325
1326 void yaffs_PutLevel0Tnode(yaffs_Device *dev, yaffs_Tnode *tn, unsigned pos, unsigned val)
1327 {
1328 __u32 *map = (__u32 *)tn;
1329 __u32 bitInMap;
1330 __u32 bitInWord;
1331 __u32 wordInMap;
1332 __u32 mask;
1333
1334 pos &= YAFFS_TNODES_LEVEL0_MASK;
1335 val >>= dev->chunkGroupBits;
1336
1337 bitInMap = pos * dev->tnodeWidth;
1338 wordInMap = bitInMap /32;
1339 bitInWord = bitInMap & (32 -1);
1340
1341 mask = dev->tnodeMask << bitInWord;
1342
1343 map[wordInMap] &= ~mask;
1344 map[wordInMap] |= (mask & (val << bitInWord));
1345
1346 if(dev->tnodeWidth > (32-bitInWord)) {
1347 bitInWord = (32 - bitInWord);
1348 wordInMap++;;
1349 mask = dev->tnodeMask >> (/*dev->tnodeWidth -*/ bitInWord);
1350 map[wordInMap] &= ~mask;
1351 map[wordInMap] |= (mask & (val >> bitInWord));
1352 }
1353 }
1354
1355 static __u32 yaffs_GetChunkGroupBase(yaffs_Device *dev, yaffs_Tnode *tn, unsigned pos)
1356 {
1357 __u32 *map = (__u32 *)tn;
1358 __u32 bitInMap;
1359 __u32 bitInWord;
1360 __u32 wordInMap;
1361 __u32 val;
1362
1363 pos &= YAFFS_TNODES_LEVEL0_MASK;
1364
1365 bitInMap = pos * dev->tnodeWidth;
1366 wordInMap = bitInMap /32;
1367 bitInWord = bitInMap & (32 -1);
1368
1369 val = map[wordInMap] >> bitInWord;
1370
1371 if(dev->tnodeWidth > (32-bitInWord)) {
1372 bitInWord = (32 - bitInWord);
1373 wordInMap++;;
1374 val |= (map[wordInMap] << bitInWord);
1375 }
1376
1377 val &= dev->tnodeMask;
1378 val <<= dev->chunkGroupBits;
1379
1380 return val;
1381 }
1382
1383 /* ------------------- End of individual tnode manipulation -----------------*/
1384
1385 /* ---------Functions to manipulate the look-up tree (made up of tnodes) ------
1386 * The look up tree is represented by the top tnode and the number of topLevel
1387 * in the tree. 0 means only the level 0 tnode is in the tree.
1388 */
1389
1390 /* FindLevel0Tnode finds the level 0 tnode, if one exists. */
1391 static yaffs_Tnode *yaffs_FindLevel0Tnode(yaffs_Device * dev,
1392 yaffs_FileStructure * fStruct,
1393 __u32 chunkId)
1394 {
1395
1396 yaffs_Tnode *tn = fStruct->top;
1397 __u32 i;
1398 int requiredTallness;
1399 int level = fStruct->topLevel;
1400
1401 /* Check sane level and chunk Id */
1402 if (level < 0 || level > YAFFS_TNODES_MAX_LEVEL) {
1403 return NULL;
1404 }
1405
1406 if (chunkId > YAFFS_MAX_CHUNK_ID) {
1407 return NULL;
1408 }
1409
1410 /* First check we're tall enough (ie enough topLevel) */
1411
1412 i = chunkId >> YAFFS_TNODES_LEVEL0_BITS;
1413 requiredTallness = 0;
1414 while (i) {
1415 i >>= YAFFS_TNODES_INTERNAL_BITS;
1416 requiredTallness++;
1417 }
1418
1419 if (requiredTallness > fStruct->topLevel) {
1420 /* Not tall enough, so we can't find it, return NULL. */
1421 return NULL;
1422 }
1423
1424 /* Traverse down to level 0 */
1425 while (level > 0 && tn) {
1426 tn = tn->
1427 internal[(chunkId >>
1428 ( YAFFS_TNODES_LEVEL0_BITS +
1429 (level - 1) *
1430 YAFFS_TNODES_INTERNAL_BITS)
1431 ) &
1432 YAFFS_TNODES_INTERNAL_MASK];
1433 level--;
1434
1435 }
1436
1437 return tn;
1438 }
1439
1440 /* AddOrFindLevel0Tnode finds the level 0 tnode if it exists, otherwise first expands the tree.
1441 * This happens in two steps:
1442 * 1. If the tree isn't tall enough, then make it taller.
1443 * 2. Scan down the tree towards the level 0 tnode adding tnodes if required.
1444 *
1445 * Used when modifying the tree.
1446 *
1447 * If the tn argument is NULL, then a fresh tnode will be added otherwise the specified tn will
1448 * be plugged into the ttree.
1449 */
1450
1451 static yaffs_Tnode *yaffs_AddOrFindLevel0Tnode(yaffs_Device * dev,
1452 yaffs_FileStructure * fStruct,
1453 __u32 chunkId,
1454 yaffs_Tnode *passedTn)
1455 {
1456
1457 int requiredTallness;
1458 int i;
1459 int l;
1460 yaffs_Tnode *tn;
1461
1462 __u32 x;
1463
1464
1465 /* Check sane level and page Id */
1466 if (fStruct->topLevel < 0 || fStruct->topLevel > YAFFS_TNODES_MAX_LEVEL) {
1467 return NULL;
1468 }
1469
1470 if (chunkId > YAFFS_MAX_CHUNK_ID) {
1471 return NULL;
1472 }
1473
1474 /* First check we're tall enough (ie enough topLevel) */
1475
1476 x = chunkId >> YAFFS_TNODES_LEVEL0_BITS;
1477 requiredTallness = 0;
1478 while (x) {
1479 x >>= YAFFS_TNODES_INTERNAL_BITS;
1480 requiredTallness++;
1481 }
1482
1483
1484 if (requiredTallness > fStruct->topLevel) {
1485 /* Not tall enough,gotta make the tree taller */
1486 for (i = fStruct->topLevel; i < requiredTallness; i++) {
1487
1488 tn = yaffs_GetTnode(dev);
1489
1490 if (tn) {
1491 tn->internal[0] = fStruct->top;
1492 fStruct->top = tn;
1493 } else {
1494 T(YAFFS_TRACE_ERROR,
1495 (TSTR("yaffs: no more tnodes" TENDSTR)));
1496 }
1497 }
1498
1499 fStruct->topLevel = requiredTallness;
1500 }
1501
1502 /* Traverse down to level 0, adding anything we need */
1503
1504 l = fStruct->topLevel;
1505 tn = fStruct->top;
1506
1507 if(l > 0) {
1508 while (l > 0 && tn) {
1509 x = (chunkId >>
1510 ( YAFFS_TNODES_LEVEL0_BITS +
1511 (l - 1) * YAFFS_TNODES_INTERNAL_BITS)) &
1512 YAFFS_TNODES_INTERNAL_MASK;
1513
1514
1515 if((l>1) && !tn->internal[x]){
1516 /* Add missing non-level-zero tnode */
1517 tn->internal[x] = yaffs_GetTnode(dev);
1518
1519 } else if(l == 1) {
1520 /* Looking from level 1 at level 0 */
1521 if (passedTn) {
1522 /* If we already have one, then release it.*/
1523 if(tn->internal[x])
1524 yaffs_FreeTnode(dev,tn->internal[x]);
1525 tn->internal[x] = passedTn;
1526
1527 } else if(!tn->internal[x]) {
1528 /* Don't have one, none passed in */
1529 tn->internal[x] = yaffs_GetTnode(dev);
1530 }
1531 }
1532
1533 tn = tn->internal[x];
1534 l--;
1535 }
1536 } else {
1537 /* top is level 0 */
1538 if(passedTn) {
1539 memcpy(tn,passedTn,(dev->tnodeWidth * YAFFS_NTNODES_LEVEL0)/8);
1540 yaffs_FreeTnode(dev,passedTn);
1541 }
1542 }
1543
1544 return tn;
1545 }
1546
1547 static int yaffs_FindChunkInGroup(yaffs_Device * dev, int theChunk,
1548 yaffs_ExtendedTags * tags, int objectId,
1549 int chunkInInode)
1550 {
1551 int j;
1552
1553 for (j = 0; theChunk && j < dev->chunkGroupSize; j++) {
1554 if (yaffs_CheckChunkBit
1555 (dev, theChunk / dev->nChunksPerBlock,
1556 theChunk % dev->nChunksPerBlock)) {
1557 yaffs_ReadChunkWithTagsFromNAND(dev, theChunk, NULL,
1558 tags);
1559 if (yaffs_TagsMatch(tags, objectId, chunkInInode)) {
1560 /* found it; */
1561 return theChunk;
1562
1563 }
1564 }
1565 theChunk++;
1566 }
1567 return -1;
1568 }
1569
1570
1571 /* DeleteWorker scans backwards through the tnode tree and deletes all the
1572 * chunks and tnodes in the file
1573 * Returns 1 if the tree was deleted.
1574 * Returns 0 if it stopped early due to hitting the limit and the delete is incomplete.
1575 */
1576
1577 static int yaffs_DeleteWorker(yaffs_Object * in, yaffs_Tnode * tn, __u32 level,
1578 int chunkOffset, int *limit)
1579 {
1580 int i;
1581 int chunkInInode;
1582 int theChunk;
1583 yaffs_ExtendedTags tags;
1584 int foundChunk;
1585 yaffs_Device *dev = in->myDev;
1586
1587 int allDone = 1;
1588
1589 if (tn) {
1590 if (level > 0) {
1591
1592 for (i = YAFFS_NTNODES_INTERNAL - 1; allDone && i >= 0;
1593 i--) {
1594 if (tn->internal[i]) {
1595 if (limit && (*limit) < 0) {
1596 allDone = 0;
1597 } else {
1598 allDone =
1599 yaffs_DeleteWorker(in,
1600 tn->
1601 internal
1602 [i],
1603 level -
1604 1,
1605 (chunkOffset
1606 <<
1607 YAFFS_TNODES_INTERNAL_BITS)
1608 + i,
1609 limit);
1610 }
1611 if (allDone) {
1612 yaffs_FreeTnode(dev,
1613 tn->
1614 internal[i]);
1615 tn->internal[i] = NULL;
1616 }
1617 }
1618
1619 }
1620 return (allDone) ? 1 : 0;
1621 } else if (level == 0) {
1622 int hitLimit = 0;
1623
1624 for (i = YAFFS_NTNODES_LEVEL0 - 1; i >= 0 && !hitLimit;
1625 i--) {
1626 theChunk = yaffs_GetChunkGroupBase(dev,tn,i);
1627 if (theChunk) {
1628
1629 chunkInInode =
1630 (chunkOffset <<
1631 YAFFS_TNODES_LEVEL0_BITS) + i;
1632
1633 foundChunk =
1634 yaffs_FindChunkInGroup(dev,
1635 theChunk,
1636 &tags,
1637 in->objectId,
1638 chunkInInode);
1639
1640 if (foundChunk > 0) {
1641 yaffs_DeleteChunk(dev,
1642 foundChunk, 1,
1643 __LINE__);
1644 in->nDataChunks--;
1645 if (limit) {
1646 *limit = *limit - 1;
1647 if (*limit <= 0) {
1648 hitLimit = 1;
1649 }
1650 }
1651
1652 }
1653
1654 yaffs_PutLevel0Tnode(dev,tn,i,0);
1655 }
1656
1657 }
1658 return (i < 0) ? 1 : 0;
1659
1660 }
1661
1662 }
1663
1664 return 1;
1665
1666 }
1667
1668 static void yaffs_SoftDeleteChunk(yaffs_Device * dev, int chunk)
1669 {
1670
1671 yaffs_BlockInfo *theBlock;
1672
1673 T(YAFFS_TRACE_DELETION, (TSTR("soft delete chunk %d" TENDSTR), chunk));
1674
1675 theBlock = yaffs_GetBlockInfo(dev, chunk / dev->nChunksPerBlock);
1676 if (theBlock) {
1677 theBlock->softDeletions++;
1678 dev->nFreeChunks++;
1679 }
1680 }
1681
1682 /* SoftDeleteWorker scans backwards through the tnode tree and soft deletes all the chunks in the file.
1683 * All soft deleting does is increment the block's softdelete count and pulls the chunk out
1684 * of the tnode.
1685 * Thus, essentially this is the same as DeleteWorker except that the chunks are soft deleted.
1686 */
1687
1688 static int yaffs_SoftDeleteWorker(yaffs_Object * in, yaffs_Tnode * tn,
1689 __u32 level, int chunkOffset)
1690 {
1691 int i;
1692 int theChunk;
1693 int allDone = 1;
1694 yaffs_Device *dev = in->myDev;
1695
1696 if (tn) {
1697 if (level > 0) {
1698
1699 for (i = YAFFS_NTNODES_INTERNAL - 1; allDone && i >= 0;
1700 i--) {
1701 if (tn->internal[i]) {
1702 allDone =
1703 yaffs_SoftDeleteWorker(in,
1704 tn->
1705 internal[i],
1706 level - 1,
1707 (chunkOffset
1708 <<
1709 YAFFS_TNODES_INTERNAL_BITS)
1710 + i);
1711 if (allDone) {
1712 yaffs_FreeTnode(dev,
1713 tn->
1714 internal[i]);
1715 tn->internal[i] = NULL;
1716 } else {
1717 /* Hoosterman... how could this happen? */
1718 }
1719 }
1720 }
1721 return (allDone) ? 1 : 0;
1722 } else if (level == 0) {
1723
1724 for (i = YAFFS_NTNODES_LEVEL0 - 1; i >= 0; i--) {
1725 theChunk = yaffs_GetChunkGroupBase(dev,tn,i);
1726 if (theChunk) {
1727 /* Note this does not find the real chunk, only the chunk group.
1728 * We make an assumption that a chunk group is not larger than
1729 * a block.
1730 */
1731 yaffs_SoftDeleteChunk(dev, theChunk);
1732 yaffs_PutLevel0Tnode(dev,tn,i,0);
1733 }
1734
1735 }
1736 return 1;
1737
1738 }
1739
1740 }
1741
1742 return 1;
1743
1744 }
1745
1746 static void yaffs_SoftDeleteFile(yaffs_Object * obj)
1747 {
1748 if (obj->deleted &&
1749 obj->variantType == YAFFS_OBJECT_TYPE_FILE && !obj->softDeleted) {
1750 if (obj->nDataChunks <= 0) {
1751 /* Empty file with no duplicate object headers, just delete it immediately */
1752 yaffs_FreeTnode(obj->myDev,
1753 obj->variant.fileVariant.top);
1754 obj->variant.fileVariant.top = NULL;
1755 T(YAFFS_TRACE_TRACING,
1756 (TSTR("yaffs: Deleting empty file %d" TENDSTR),
1757 obj->objectId));
1758 yaffs_DoGenericObjectDeletion(obj);
1759 } else {
1760 yaffs_SoftDeleteWorker(obj,
1761 obj->variant.fileVariant.top,
1762 obj->variant.fileVariant.
1763 topLevel, 0);
1764 obj->softDeleted = 1;
1765 }
1766 }
1767 }
1768
1769 /* Pruning removes any part of the file structure tree that is beyond the
1770 * bounds of the file (ie that does not point to chunks).
1771 *
1772 * A file should only get pruned when its size is reduced.
1773 *
1774 * Before pruning, the chunks must be pulled from the tree and the
1775 * level 0 tnode entries must be zeroed out.
1776 * Could also use this for file deletion, but that's probably better handled
1777 * by a special case.
1778 */
1779
1780 static yaffs_Tnode *yaffs_PruneWorker(yaffs_Device * dev, yaffs_Tnode * tn,
1781 __u32 level, int del0)
1782 {
1783 int i;
1784 int hasData;
1785
1786 if (tn) {
1787 hasData = 0;
1788
1789 for (i = 0; i < YAFFS_NTNODES_INTERNAL; i++) {
1790 if (tn->internal[i] && level > 0) {
1791 tn->internal[i] =
1792 yaffs_PruneWorker(dev, tn->internal[i],
1793 level - 1,
1794 (i == 0) ? del0 : 1);
1795 }
1796
1797 if (tn->internal[i]) {
1798 hasData++;
1799 }
1800 }
1801
1802 if (hasData == 0 && del0) {
1803 /* Free and return NULL */
1804
1805 yaffs_FreeTnode(dev, tn);
1806 tn = NULL;
1807 }
1808
1809 }
1810
1811 return tn;
1812
1813 }
1814
1815 static int yaffs_PruneFileStructure(yaffs_Device * dev,
1816 yaffs_FileStructure * fStruct)
1817 {
1818 int i;
1819 int hasData;
1820 int done = 0;
1821 yaffs_Tnode *tn;
1822
1823 if (fStruct->topLevel > 0) {
1824 fStruct->top =
1825 yaffs_PruneWorker(dev, fStruct->top, fStruct->topLevel, 0);
1826
1827 /* Now we have a tree with all the non-zero branches NULL but the height
1828 * is the same as it was.
1829 * Let's see if we can trim internal tnodes to shorten the tree.
1830 * We can do this if only the 0th element in the tnode is in use
1831 * (ie all the non-zero are NULL)
1832 */
1833
1834 while (fStruct->topLevel && !done) {
1835 tn = fStruct->top;
1836
1837 hasData = 0;
1838 for (i = 1; i < YAFFS_NTNODES_INTERNAL; i++) {
1839 if (tn->internal[i]) {
1840 hasData++;
1841 }
1842 }
1843
1844 if (!hasData) {
1845 fStruct->top = tn->internal[0];
1846 fStruct->topLevel--;
1847 yaffs_FreeTnode(dev, tn);
1848 } else {
1849 done = 1;
1850 }
1851 }
1852 }
1853
1854 return YAFFS_OK;
1855 }
1856
1857 /*-------------------- End of File Structure functions.-------------------*/
1858
1859 /* yaffs_CreateFreeObjects creates a bunch more objects and
1860 * adds them to the object free list.
1861 */
1862 static int yaffs_CreateFreeObjects(yaffs_Device * dev, int nObjects)
1863 {
1864 int i;
1865 yaffs_Object *newObjects;
1866 yaffs_ObjectList *list;
1867
1868 if (nObjects < 1)
1869 return YAFFS_OK;
1870
1871 /* make these things */
1872 newObjects = YMALLOC(nObjects * sizeof(yaffs_Object));
1873 list = YMALLOC(sizeof(yaffs_ObjectList));
1874
1875 if (!newObjects || !list) {
1876 if(newObjects)
1877 YFREE(newObjects);
1878 if(list)
1879 YFREE(list);
1880 T(YAFFS_TRACE_ALLOCATE,
1881 (TSTR("yaffs: Could not allocate more objects" TENDSTR)));
1882 return YAFFS_FAIL;
1883 }
1884
1885 /* Hook them into the free list */
1886 for (i = 0; i < nObjects - 1; i++) {
1887 newObjects[i].siblings.next =
1888 (struct ylist_head *)(&newObjects[i + 1]);
1889 }
1890
1891 newObjects[nObjects - 1].siblings.next = (void *)dev->freeObjects;
1892 dev->freeObjects = newObjects;
1893 dev->nFreeObjects += nObjects;
1894 dev->nObjectsCreated += nObjects;
1895
1896 /* Now add this bunch of Objects to a list for freeing up. */
1897
1898 list->objects = newObjects;
1899 list->next = dev->allocatedObjectList;
1900 dev->allocatedObjectList = list;
1901
1902 return YAFFS_OK;
1903 }
1904
1905
1906 /* AllocateEmptyObject gets us a clean Object. Tries to make allocate more if we run out */
1907 static yaffs_Object *yaffs_AllocateEmptyObject(yaffs_Device * dev)
1908 {
1909 yaffs_Object *tn = NULL;
1910
1911 /* If there are none left make more */
1912 if (!dev->freeObjects) {
1913 yaffs_CreateFreeObjects(dev, YAFFS_ALLOCATION_NOBJECTS);
1914 }
1915
1916 if (dev->freeObjects) {
1917 tn = dev->freeObjects;
1918 dev->freeObjects =
1919 (yaffs_Object *) (dev->freeObjects->siblings.next);
1920 dev->nFreeObjects--;
1921
1922 /* Now sweeten it up... */
1923
1924 memset(tn, 0, sizeof(yaffs_Object));
1925 tn->myDev = dev;
1926 tn->chunkId = -1;
1927 tn->variantType = YAFFS_OBJECT_TYPE_UNKNOWN;
1928 YINIT_LIST_HEAD(&(tn->hardLinks));
1929 YINIT_LIST_HEAD(&(tn->hashLink));
1930 YINIT_LIST_HEAD(&tn->siblings);
1931
1932 /* Add it to the lost and found directory.
1933 * NB Can't put root or lostNFound in lostNFound so
1934 * check if lostNFound exists first
1935 */
1936 if (dev->lostNFoundDir) {
1937 yaffs_AddObjectToDirectory(dev->lostNFoundDir, tn);
1938 }
1939 }
1940
1941 dev->nCheckpointBlocksRequired = 0; /* force recalculation*/
1942
1943 return tn;
1944 }
1945
1946 static yaffs_Object *yaffs_CreateFakeDirectory(yaffs_Device * dev, int number,
1947 __u32 mode)
1948 {
1949
1950 yaffs_Object *obj =
1951 yaffs_CreateNewObject(dev, number, YAFFS_OBJECT_TYPE_DIRECTORY);
1952 if (obj) {
1953 obj->fake = 1; /* it is fake so it has no NAND presence... */
1954 obj->renameAllowed = 0; /* ... and we're not allowed to rename it... */
1955 obj->unlinkAllowed = 0; /* ... or unlink it */
1956 obj->deleted = 0;
1957 obj->unlinked = 0;
1958 obj->yst_mode = mode;
1959 obj->myDev = dev;
1960 obj->chunkId = 0; /* Not a valid chunk. */
1961 }
1962
1963 return obj;
1964
1965 }
1966
1967 static void yaffs_UnhashObject(yaffs_Object * tn)
1968 {
1969 int bucket;
1970 yaffs_Device *dev = tn->myDev;
1971
1972 /* If it is still linked into the bucket list, free from the list */
1973 if (!ylist_empty(&tn->hashLink)) {
1974 ylist_del_init(&tn->hashLink);
1975 bucket = yaffs_HashFunction(tn->objectId);
1976 dev->objectBucket[bucket].count--;
1977 }
1978
1979 }
1980
1981 /* FreeObject frees up a Object and puts it back on the free list */
1982 static void yaffs_FreeObject(yaffs_Object * tn)
1983 {
1984
1985 yaffs_Device *dev = tn->myDev;
1986
1987 #ifdef __KERNEL__
1988 if (tn->myInode) {
1989 /* We're still hooked up to a cached inode.
1990 * Don't delete now, but mark for later deletion
1991 */
1992 tn->deferedFree = 1;
1993 return;
1994 }
1995 #endif
1996
1997 yaffs_UnhashObject(tn);
1998
1999 /* Link into the free list. */
2000 tn->siblings.next = (struct ylist_head *)(dev->freeObjects);
2001 dev->freeObjects = tn;
2002 dev->nFreeObjects++;
2003
2004 dev->nCheckpointBlocksRequired = 0; /* force recalculation*/
2005
2006 }
2007
2008 #ifdef __KERNEL__
2009
2010 void yaffs_HandleDeferedFree(yaffs_Object * obj)
2011 {
2012 if (obj->deferedFree) {
2013 yaffs_FreeObject(obj);
2014 }
2015 }
2016
2017 #endif
2018
2019 static void yaffs_DeinitialiseObjects(yaffs_Device * dev)
2020 {
2021 /* Free the list of allocated Objects */
2022
2023 yaffs_ObjectList *tmp;
2024
2025 while (dev->allocatedObjectList) {
2026 tmp = dev->allocatedObjectList->next;
2027 YFREE(dev->allocatedObjectList->objects);
2028 YFREE(dev->allocatedObjectList);
2029
2030 dev->allocatedObjectList = tmp;
2031 }
2032
2033 dev->freeObjects = NULL;
2034 dev->nFreeObjects = 0;
2035 }
2036
2037 static void yaffs_InitialiseObjects(yaffs_Device * dev)
2038 {
2039 int i;
2040
2041 dev->allocatedObjectList = NULL;
2042 dev->freeObjects = NULL;
2043 dev->nFreeObjects = 0;
2044
2045 for (i = 0; i < YAFFS_NOBJECT_BUCKETS; i++) {
2046 YINIT_LIST_HEAD(&dev->objectBucket[i].list);
2047 dev->objectBucket[i].count = 0;
2048 }
2049
2050 }
2051
2052 static int yaffs_FindNiceObjectBucket(yaffs_Device * dev)
2053 {
2054 static int x = 0;
2055 int i;
2056 int l = 999;
2057 int lowest = 999999;
2058
2059 /* First let's see if we can find one that's empty. */
2060
2061 for (i = 0; i < 10 && lowest > 0; i++) {
2062 x++;
2063 x %= YAFFS_NOBJECT_BUCKETS;
2064 if (dev->objectBucket[x].count < lowest) {
2065 lowest = dev->objectBucket[x].count;
2066 l = x;
2067 }
2068
2069 }
2070
2071 /* If we didn't find an empty list, then try
2072 * looking a bit further for a short one
2073 */
2074
2075 for (i = 0; i < 10 && lowest > 3; i++) {
2076 x++;
2077 x %= YAFFS_NOBJECT_BUCKETS;
2078 if (dev->objectBucket[x].count < lowest) {
2079 lowest = dev->objectBucket[x].count;
2080 l = x;
2081 }
2082
2083 }
2084
2085 return l;
2086 }
2087
2088 static int yaffs_CreateNewObjectNumber(yaffs_Device * dev)
2089 {
2090 int bucket = yaffs_FindNiceObjectBucket(dev);
2091
2092 /* Now find an object value that has not already been taken
2093 * by scanning the list.
2094 */
2095
2096 int found = 0;
2097 struct ylist_head *i;
2098
2099 __u32 n = (__u32) bucket;
2100
2101 /* yaffs_CheckObjectHashSanity(); */
2102
2103 while (!found) {
2104 found = 1;
2105 n += YAFFS_NOBJECT_BUCKETS;
2106 if (1 || dev->objectBucket[bucket].count > 0) {
2107 ylist_for_each(i, &dev->objectBucket[bucket].list) {
2108 /* If there is already one in the list */
2109 if (i
2110 && ylist_entry(i, yaffs_Object,
2111 hashLink)->objectId == n) {
2112 found = 0;
2113 }
2114 }
2115 }
2116 }
2117
2118
2119 return n;
2120 }
2121
2122 static void yaffs_HashObject(yaffs_Object * in)
2123 {
2124 int bucket = yaffs_HashFunction(in->objectId);
2125 yaffs_Device *dev = in->myDev;
2126
2127 ylist_add(&in->hashLink, &dev->objectBucket[bucket].list);
2128 dev->objectBucket[bucket].count++;
2129
2130 }
2131
2132 yaffs_Object *yaffs_FindObjectByNumber(yaffs_Device * dev, __u32 number)
2133 {
2134 int bucket = yaffs_HashFunction(number);
2135 struct ylist_head *i;
2136 yaffs_Object *in;
2137
2138 ylist_for_each(i, &dev->objectBucket[bucket].list) {
2139 /* Look if it is in the list */
2140 if (i) {
2141 in = ylist_entry(i, yaffs_Object, hashLink);
2142 if (in->objectId == number) {
2143 #ifdef __KERNEL__
2144 /* Don't tell the VFS about this one if it is defered free */
2145 if (in->deferedFree)
2146 return NULL;
2147 #endif
2148
2149 return in;
2150 }
2151 }
2152 }
2153
2154 return NULL;
2155 }
2156
2157 yaffs_Object *yaffs_CreateNewObject(yaffs_Device * dev, int number,
2158 yaffs_ObjectType type)
2159 {
2160
2161 yaffs_Object *theObject;
2162 yaffs_Tnode *tn = NULL;
2163
2164 if (number < 0) {
2165 number = yaffs_CreateNewObjectNumber(dev);
2166 }
2167
2168 theObject = yaffs_AllocateEmptyObject(dev);
2169 if(!theObject)
2170 return NULL;
2171
2172 if(type == YAFFS_OBJECT_TYPE_FILE){
2173 tn = yaffs_GetTnode(dev);
2174 if(!tn){
2175 yaffs_FreeObject(theObject);
2176 return NULL;
2177 }
2178 }
2179
2180
2181
2182 if (theObject) {
2183 theObject->fake = 0;
2184 theObject->renameAllowed = 1;
2185 theObject->unlinkAllowed = 1;
2186 theObject->objectId = number;
2187 yaffs_HashObject(theObject);
2188 theObject->variantType = type;
2189 #ifdef CONFIG_YAFFS_WINCE
2190 yfsd_WinFileTimeNow(theObject->win_atime);
2191 theObject->win_ctime[0] = theObject->win_mtime[0] =
2192 theObject->win_atime[0];
2193 theObject->win_ctime[1] = theObject->win_mtime[1] =
2194 theObject->win_atime[1];
2195
2196 #else
2197
2198 theObject->yst_atime = theObject->yst_mtime =
2199 theObject->yst_ctime = Y_CURRENT_TIME;
2200 #endif
2201 switch (type) {
2202 case YAFFS_OBJECT_TYPE_FILE:
2203 theObject->variant.fileVariant.fileSize = 0;
2204 theObject->variant.fileVariant.scannedFileSize = 0;
2205 theObject->variant.fileVariant.shrinkSize = 0xFFFFFFFF; /* max __u32 */
2206 theObject->variant.fileVariant.topLevel = 0;
2207 theObject->variant.fileVariant.top = tn;
2208 break;
2209 case YAFFS_OBJECT_TYPE_DIRECTORY:
2210 YINIT_LIST_HEAD(&theObject->variant.directoryVariant.
2211 children);
2212 break;
2213 case YAFFS_OBJECT_TYPE_SYMLINK:
2214 case YAFFS_OBJECT_TYPE_HARDLINK:
2215 case YAFFS_OBJECT_TYPE_SPECIAL:
2216 /* No action required */
2217 break;
2218 case YAFFS_OBJECT_TYPE_UNKNOWN:
2219 /* todo this should not happen */
2220 break;
2221 }
2222 }
2223
2224 return theObject;
2225 }
2226
2227 static yaffs_Object *yaffs_FindOrCreateObjectByNumber(yaffs_Device * dev,
2228 int number,
2229 yaffs_ObjectType type)
2230 {
2231 yaffs_Object *theObject = NULL;
2232
2233 if (number > 0) {
2234 theObject = yaffs_FindObjectByNumber(dev, number);
2235 }
2236
2237 if (!theObject) {
2238 theObject = yaffs_CreateNewObject(dev, number, type);
2239 }
2240
2241 return theObject;
2242
2243 }
2244
2245
2246 static YCHAR *yaffs_CloneString(const YCHAR * str)
2247 {
2248 YCHAR *newStr = NULL;
2249
2250 if (str && *str) {
2251 newStr = YMALLOC((yaffs_strlen(str) + 1) * sizeof(YCHAR));
2252 if(newStr)
2253 yaffs_strcpy(newStr, str);
2254 }
2255
2256 return newStr;
2257
2258 }
2259
2260 /*
2261 * Mknod (create) a new object.
2262 * equivalentObject only has meaning for a hard link;
2263 * aliasString only has meaning for a sumlink.
2264 * rdev only has meaning for devices (a subset of special objects)
2265 */
2266
2267 static yaffs_Object *yaffs_MknodObject(yaffs_ObjectType type,
2268 yaffs_Object * parent,
2269 const YCHAR * name,
2270 __u32 mode,
2271 __u32 uid,
2272 __u32 gid,
2273 yaffs_Object * equivalentObject,
2274 const YCHAR * aliasString, __u32 rdev)
2275 {
2276 yaffs_Object *in;
2277 YCHAR *str = NULL;
2278
2279 yaffs_Device *dev = parent->myDev;
2280
2281 /* Check if the entry exists. If it does then fail the call since we don't want a dup.*/
2282 if (yaffs_FindObjectByName(parent, name)) {
2283 return NULL;
2284 }
2285
2286 in = yaffs_CreateNewObject(dev, -1, type);
2287
2288 if(type == YAFFS_OBJECT_TYPE_SYMLINK){
2289 str = yaffs_CloneString(aliasString);
2290 if(!str){
2291 yaffs_FreeObject(in);
2292 return NULL;
2293 }
2294 }
2295
2296
2297
2298 if (in) {
2299 in->chunkId = -1;
2300 in->valid = 1;
2301 in->variantType = type;
2302
2303 in->yst_mode = mode;
2304
2305 #ifdef CONFIG_YAFFS_WINCE
2306 yfsd_WinFileTimeNow(in->win_atime);
2307 in->win_ctime[0] = in->win_mtime[0] = in->win_atime[0];
2308 in->win_ctime[1] = in->win_mtime[1] = in->win_atime[1];
2309
2310 #else
2311 in->yst_atime = in->yst_mtime = in->yst_ctime = Y_CURRENT_TIME;
2312
2313 in->yst_rdev = rdev;
2314 in->yst_uid = uid;
2315 in->yst_gid = gid;
2316 #endif
2317 in->nDataChunks = 0;
2318
2319 yaffs_SetObjectName(in, name);
2320 in->dirty = 1;
2321
2322 yaffs_AddObjectToDirectory(parent, in);
2323
2324 in->myDev = parent->myDev;
2325
2326 switch (type) {
2327 case YAFFS_OBJECT_TYPE_SYMLINK:
2328 in->variant.symLinkVariant.alias = str;
2329 break;
2330 case YAFFS_OBJECT_TYPE_HARDLINK:
2331 in->variant.hardLinkVariant.equivalentObject =
2332 equivalentObject;
2333 in->variant.hardLinkVariant.equivalentObjectId =
2334 equivalentObject->objectId;
2335 ylist_add(&in->hardLinks, &equivalentObject->hardLinks);
2336 break;
2337 case YAFFS_OBJECT_TYPE_FILE:
2338 case YAFFS_OBJECT_TYPE_DIRECTORY:
2339 case YAFFS_OBJECT_TYPE_SPECIAL:
2340 case YAFFS_OBJECT_TYPE_UNKNOWN:
2341 /* do nothing */
2342 break;
2343 }
2344
2345 if (yaffs_UpdateObjectHeader(in, name, 0, 0, 0) < 0) {
2346 /* Could not create the object header, fail the creation */
2347 yaffs_DestroyObject(in);
2348 in = NULL;
2349 }
2350
2351 }
2352
2353 return in;
2354 }
2355
2356 yaffs_Object *yaffs_MknodFile(yaffs_Object * parent, const YCHAR * name,
2357 __u32 mode, __u32 uid, __u32 gid)
2358 {
2359 return yaffs_MknodObject(YAFFS_OBJECT_TYPE_FILE, parent, name, mode,
2360 uid, gid, NULL, NULL, 0);
2361 }
2362
2363 yaffs_Object *yaffs_MknodDirectory(yaffs_Object * parent, const YCHAR * name,
2364 __u32 mode, __u32 uid, __u32 gid)
2365 {
2366 return yaffs_MknodObject(YAFFS_OBJECT_TYPE_DIRECTORY, parent, name,
2367 mode, uid, gid, NULL, NULL, 0);
2368 }
2369
2370 yaffs_Object *yaffs_MknodSpecial(yaffs_Object * parent, const YCHAR * name,
2371 __u32 mode, __u32 uid, __u32 gid, __u32 rdev)
2372 {
2373 return yaffs_MknodObject(YAFFS_OBJECT_TYPE_SPECIAL, parent, name, mode,
2374 uid, gid, NULL, NULL, rdev);
2375 }
2376
2377 yaffs_Object *yaffs_MknodSymLink(yaffs_Object * parent, const YCHAR * name,
2378 __u32 mode, __u32 uid, __u32 gid,
2379 const YCHAR * alias)
2380 {
2381 return yaffs_MknodObject(YAFFS_OBJECT_TYPE_SYMLINK, parent, name, mode,
2382 uid, gid, NULL, alias, 0);
2383 }
2384
2385 /* yaffs_Link returns the object id of the equivalent object.*/
2386 yaffs_Object *yaffs_Link(yaffs_Object * parent, const YCHAR * name,
2387 yaffs_Object * equivalentObject)
2388 {
2389 /* Get the real object in case we were fed a hard link as an equivalent object */
2390 equivalentObject = yaffs_GetEquivalentObject(equivalentObject);
2391
2392 if (yaffs_MknodObject
2393 (YAFFS_OBJECT_TYPE_HARDLINK, parent, name, 0, 0, 0,
2394 equivalentObject, NULL, 0)) {
2395 return equivalentObject;
2396 } else {
2397 return NULL;
2398 }
2399
2400 }
2401
2402 static int yaffs_ChangeObjectName(yaffs_Object * obj, yaffs_Object * newDir,
2403 const YCHAR * newName, int force, int shadows)
2404 {
2405 int unlinkOp;
2406 int deleteOp;
2407
2408 yaffs_Object *existingTarget;
2409
2410 if (newDir == NULL) {
2411 newDir = obj->parent; /* use the old directory */
2412 }
2413
2414 if (newDir->variantType != YAFFS_OBJECT_TYPE_DIRECTORY) {
2415 T(YAFFS_TRACE_ALWAYS,
2416 (TSTR
2417 ("tragendy: yaffs_ChangeObjectName: newDir is not a directory"
2418 TENDSTR)));
2419 YBUG();
2420 }
2421
2422 /* TODO: Do we need this different handling for YAFFS2 and YAFFS1?? */
2423 if (obj->myDev->isYaffs2) {
2424 unlinkOp = (newDir == obj->myDev->unlinkedDir);
2425 } else {
2426 unlinkOp = (newDir == obj->myDev->unlinkedDir
2427 && obj->variantType == YAFFS_OBJECT_TYPE_FILE);
2428 }
2429
2430 deleteOp = (newDir == obj->myDev->deletedDir);
2431
2432 existingTarget = yaffs_FindObjectByName(newDir, newName);
2433
2434 /* If the object is a file going into the unlinked directory,
2435 * then it is OK to just stuff it in since duplicate names are allowed.
2436 * else only proceed if the new name does not exist and if we're putting
2437 * it into a directory.
2438 */
2439 if ((unlinkOp ||
2440 deleteOp ||
2441 force ||
2442 (shadows > 0) ||
2443 !existingTarget) &&
2444 newDir->variantType == YAFFS_OBJECT_TYPE_DIRECTORY) {
2445 yaffs_SetObjectName(obj, newName);
2446 obj->dirty = 1;
2447
2448 yaffs_AddObjectToDirectory(newDir, obj);
2449
2450 if (unlinkOp)
2451 obj->unlinked = 1;
2452
2453 /* If it is a deletion then we mark it as a shrink for gc purposes. */
2454 if (yaffs_UpdateObjectHeader(obj, newName, 0, deleteOp, shadows)>= 0)
2455 return YAFFS_OK;
2456 }
2457
2458 return YAFFS_FAIL;
2459 }
2460
2461 int yaffs_RenameObject(yaffs_Object * oldDir, const YCHAR * oldName,
2462 yaffs_Object * newDir, const YCHAR * newName)
2463 {
2464 yaffs_Object *obj;
2465 yaffs_Object *existingTarget;
2466 int force = 0;
2467
2468 #ifdef CONFIG_YAFFS_CASE_INSENSITIVE
2469 /* Special case for case insemsitive systems (eg. WinCE).
2470 * While look-up is case insensitive, the name isn't.
2471 * Therefore we might want to change x.txt to X.txt
2472 */
2473 if (oldDir == newDir && yaffs_strcmp(oldName, newName) == 0) {
2474 force = 1;
2475 }
2476 #endif
2477
2478 obj = yaffs_FindObjectByName(oldDir, oldName);
2479 /* Check new name to long. */
2480 if (obj->variantType == YAFFS_OBJECT_TYPE_SYMLINK &&
2481 yaffs_strlen(newName) > YAFFS_MAX_ALIAS_LENGTH)
2482 /* ENAMETOOLONG */
2483 return YAFFS_FAIL;
2484 else if (obj->variantType != YAFFS_OBJECT_TYPE_SYMLINK &&
2485 yaffs_strlen(newName) > YAFFS_MAX_NAME_LENGTH)
2486 /* ENAMETOOLONG */
2487 return YAFFS_FAIL;
2488
2489 if (obj && obj->renameAllowed) {
2490
2491 /* Now do the handling for an existing target, if there is one */
2492
2493 existingTarget = yaffs_FindObjectByName(newDir, newName);
2494 if (existingTarget &&
2495 existingTarget->variantType == YAFFS_OBJECT_TYPE_DIRECTORY &&
2496 !ylist_empty(&existingTarget->variant.directoryVariant.children)) {
2497 /* There is a target that is a non-empty directory, so we fail */
2498 return YAFFS_FAIL; /* EEXIST or ENOTEMPTY */
2499 } else if (existingTarget && existingTarget != obj) {
2500 /* Nuke the target first, using shadowing,
2501 * but only if it isn't the same object
2502 */
2503 yaffs_ChangeObjectName(obj, newDir, newName, force,
2504 existingTarget->objectId);
2505 yaffs_UnlinkObject(existingTarget);
2506 }
2507
2508 return yaffs_ChangeObjectName(obj, newDir, newName, 1, 0);
2509 }
2510 return YAFFS_FAIL;
2511 }
2512
2513 /*------------------------- Block Management and Page Allocation ----------------*/
2514
2515 static int yaffs_InitialiseBlocks(yaffs_Device * dev)
2516 {
2517 int nBlocks = dev->internalEndBlock - dev->internalStartBlock + 1;
2518
2519 dev->blockInfo = NULL;
2520 dev->chunkBits = NULL;
2521
2522 dev->allocationBlock = -1; /* force it to get a new one */
2523
2524 /* If the first allocation strategy fails, thry the alternate one */
2525 dev->blockInfo = YMALLOC(nBlocks * sizeof(yaffs_BlockInfo));
2526 if(!dev->blockInfo){
2527 dev->blockInfo = YMALLOC_ALT(nBlocks * sizeof(yaffs_BlockInfo));
2528 dev->blockInfoAlt = 1;
2529 }
2530 else
2531 dev->blockInfoAlt = 0;
2532
2533 if(dev->blockInfo){
2534
2535 /* Set up dynamic blockinfo stuff. */
2536 dev->chunkBitmapStride = (dev->nChunksPerBlock + 7) / 8; /* round up bytes */
2537 dev->chunkBits = YMALLOC(dev->chunkBitmapStride * nBlocks);
2538 if(!dev->chunkBits){
2539 dev->chunkBits = YMALLOC_ALT(dev->chunkBitmapStride * nBlocks);
2540 dev->chunkBitsAlt = 1;
2541 }
2542 else
2543 dev->chunkBitsAlt = 0;
2544 }
2545
2546 if (dev->blockInfo && dev->chunkBits) {
2547 memset(dev->blockInfo, 0, nBlocks * sizeof(yaffs_BlockInfo));
2548 memset(dev->chunkBits, 0, dev->chunkBitmapStride * nBlocks);
2549 return YAFFS_OK;
2550 }
2551
2552 return YAFFS_FAIL;
2553
2554 }
2555
2556 static void yaffs_DeinitialiseBlocks(yaffs_Device * dev)
2557 {
2558 if(dev->blockInfoAlt && dev->blockInfo)
2559 YFREE_ALT(dev->blockInfo);
2560 else if(dev->blockInfo)
2561 YFREE(dev->blockInfo);
2562
2563 dev->blockInfoAlt = 0;
2564
2565 dev->blockInfo = NULL;
2566
2567 if(dev->chunkBitsAlt && dev->chunkBits)
2568 YFREE_ALT(dev->chunkBits);
2569 else if(dev->chunkBits)
2570 YFREE(dev->chunkBits);
2571 dev->chunkBitsAlt = 0;
2572 dev->chunkBits = NULL;
2573 }
2574
2575 static int yaffs_BlockNotDisqualifiedFromGC(yaffs_Device * dev,
2576 yaffs_BlockInfo * bi)
2577 {
2578 int i;
2579 __u32 seq;
2580 yaffs_BlockInfo *b;
2581
2582 if (!dev->isYaffs2)
2583 return 1; /* disqualification only applies to yaffs2. */
2584
2585 if (!bi->hasShrinkHeader)
2586 return 1; /* can gc */
2587
2588 /* Find the oldest dirty sequence number if we don't know it and save it
2589 * so we don't have to keep recomputing it.
2590 */
2591 if (!dev->oldestDirtySequence) {
2592 seq = dev->sequenceNumber;
2593
2594 for (i = dev->internalStartBlock; i <= dev->internalEndBlock;
2595 i++) {
2596 b = yaffs_GetBlockInfo(dev, i);
2597 if (b->blockState == YAFFS_BLOCK_STATE_FULL &&
2598 (b->pagesInUse - b->softDeletions) <
2599 dev->nChunksPerBlock && b->sequenceNumber < seq) {
2600 seq = b->sequenceNumber;
2601 }
2602 }
2603 dev->oldestDirtySequence = seq;
2604 }
2605
2606 /* Can't do gc of this block if there are any blocks older than this one that have
2607 * discarded pages.
2608 */
2609 return (bi->sequenceNumber <= dev->oldestDirtySequence);
2610
2611 }
2612
2613 /* FindDiretiestBlock is used to select the dirtiest block (or close enough)
2614 * for garbage collection.
2615 */
2616
2617 static int yaffs_FindBlockForGarbageCollection(yaffs_Device * dev,
2618 int aggressive)
2619 {
2620
2621 int b = dev->currentDirtyChecker;
2622
2623 int i;
2624 int iterations;
2625 int dirtiest = -1;
2626 int pagesInUse = 0;
2627 int prioritised=0;
2628 yaffs_BlockInfo *bi;
2629 int pendingPrioritisedExist = 0;
2630
2631 /* First let's see if we need to grab a prioritised block */
2632 if(dev->hasPendingPrioritisedGCs){
2633 for(i = dev->internalStartBlock; i < dev->internalEndBlock && !prioritised; i++){
2634
2635 bi = yaffs_GetBlockInfo(dev, i);
2636 //yaffs_VerifyBlock(dev,bi,i);
2637
2638 if(bi->gcPrioritise) {
2639 pendingPrioritisedExist = 1;
2640 if(bi->blockState == YAFFS_BLOCK_STATE_FULL &&
2641 yaffs_BlockNotDisqualifiedFromGC(dev, bi)){
2642 pagesInUse = (bi->pagesInUse - bi->softDeletions);
2643 dirtiest = i;
2644 prioritised = 1;
2645 aggressive = 1; /* Fool the non-aggressive skip logiv below */
2646 }
2647 }
2648 }
2649
2650 if(!pendingPrioritisedExist) /* None found, so we can clear this */
2651 dev->hasPendingPrioritisedGCs = 0;
2652 }
2653
2654 /* If we're doing aggressive GC then we are happy to take a less-dirty block, and
2655 * search harder.
2656 * else (we're doing a leasurely gc), then we only bother to do this if the
2657 * block has only a few pages in use.
2658 */
2659
2660 dev->nonAggressiveSkip--;
2661
2662 if (!aggressive && (dev->nonAggressiveSkip > 0)) {
2663 return -1;
2664 }
2665
2666 if(!prioritised)
2667 pagesInUse =
2668 (aggressive) ? dev->nChunksPerBlock : YAFFS_PASSIVE_GC_CHUNKS + 1;
2669
2670 if (aggressive) {
2671 iterations =
2672 dev->internalEndBlock - dev->internalStartBlock + 1;
2673 } else {
2674 iterations =
2675 dev->internalEndBlock - dev->internalStartBlock + 1;
2676 iterations = iterations / 16;
2677 if (iterations > 200) {
2678 iterations = 200;
2679 }
2680 }
2681
2682 for (i = 0; i <= iterations && pagesInUse > 0 && !prioritised; i++) {
2683 b++;
2684 if (b < dev->internalStartBlock || b > dev->internalEndBlock) {
2685 b = dev->internalStartBlock;
2686 }
2687
2688 if (b < dev->internalStartBlock || b > dev->internalEndBlock) {
2689 T(YAFFS_TRACE_ERROR,
2690 (TSTR("**>> Block %d is not valid" TENDSTR), b));
2691 YBUG();
2692 }
2693
2694 bi = yaffs_GetBlockInfo(dev, b);
2695
2696 #if 0
2697 if (bi->blockState == YAFFS_BLOCK_STATE_CHECKPOINT) {
2698 dirtiest = b;
2699 pagesInUse = 0;
2700 }
2701 else
2702 #endif
2703
2704 if (bi->blockState == YAFFS_BLOCK_STATE_FULL &&
2705 (bi->pagesInUse - bi->softDeletions) < pagesInUse &&
2706 yaffs_BlockNotDisqualifiedFromGC(dev, bi)) {
2707 dirtiest = b;
2708 pagesInUse = (bi->pagesInUse - bi->softDeletions);
2709 }
2710 }
2711
2712 dev->currentDirtyChecker = b;
2713
2714 if (dirtiest > 0) {
2715 T(YAFFS_TRACE_GC,
2716 (TSTR("GC Selected block %d with %d free, prioritised:%d" TENDSTR), dirtiest,
2717 dev->nChunksPerBlock - pagesInUse,prioritised));
2718 }
2719
2720 dev->oldestDirtySequence = 0;
2721
2722 if (dirtiest > 0) {
2723 dev->nonAggressiveSkip = 4;
2724 }
2725
2726 return dirtiest;
2727 }
2728
2729 static void yaffs_BlockBecameDirty(yaffs_Device * dev, int blockNo)
2730 {
2731 yaffs_BlockInfo *bi = yaffs_GetBlockInfo(dev, blockNo);
2732
2733 int erasedOk = 0;
2734
2735 /* If the block is still healthy erase it and mark as clean.
2736 * If the block has had a data failure, then retire it.
2737 */
2738
2739 T(YAFFS_TRACE_GC | YAFFS_TRACE_ERASE,
2740 (TSTR("yaffs_BlockBecameDirty block %d state %d %s"TENDSTR),
2741 blockNo, bi->blockState, (bi->needsRetiring) ? "needs retiring" : ""));
2742
2743 bi->blockState = YAFFS_BLOCK_STATE_DIRTY;
2744
2745 if (!bi->needsRetiring) {
2746 yaffs_InvalidateCheckpoint(dev);
2747 erasedOk = yaffs_EraseBlockInNAND(dev, blockNo);
2748 if (!erasedOk) {
2749 dev->nErasureFailures++;
2750 T(YAFFS_TRACE_ERROR | YAFFS_TRACE_BAD_BLOCKS,
2751 (TSTR("**>> Erasure failed %d" TENDSTR), blockNo));
2752 }
2753 }
2754
2755 if (erasedOk &&
2756 ((yaffs_traceMask & YAFFS_TRACE_ERASE) || !yaffs_SkipVerification(dev))) {
2757 int i;
2758 for (i = 0; i < dev->nChunksPerBlock; i++) {
2759 if (!yaffs_CheckChunkErased
2760 (dev, blockNo * dev->nChunksPerBlock + i)) {
2761 T(YAFFS_TRACE_ERROR,
2762 (TSTR
2763 (">>Block %d erasure supposedly OK, but chunk %d not erased"
2764 TENDSTR), blockNo, i));
2765 }
2766 }
2767 }
2768
2769 if (erasedOk) {
2770 /* Clean it up... */
2771 bi->blockState = YAFFS_BLOCK_STATE_EMPTY;
2772 dev->nErasedBlocks++;
2773 bi->pagesInUse = 0;
2774 bi->softDeletions = 0;
2775 bi->hasShrinkHeader = 0;
2776 bi->skipErasedCheck = 1; /* This is clean, so no need to check */
2777 bi->gcPrioritise = 0;
2778 yaffs_ClearChunkBits(dev, blockNo);
2779
2780 T(YAFFS_TRACE_ERASE,
2781 (TSTR("Erased block %d" TENDSTR), blockNo));
2782 } else {
2783 dev->nFreeChunks -= dev->nChunksPerBlock; /* We lost a block of free space */
2784
2785 yaffs_RetireBlock(dev, blockNo);
2786 T(YAFFS_TRACE_ERROR | YAFFS_TRACE_BAD_BLOCKS,
2787 (TSTR("**>> Block %d retired" TENDSTR), blockNo));
2788 }
2789 }
2790
2791 static int yaffs_FindBlockForAllocation(yaffs_Device * dev)
2792 {
2793 int i;
2794
2795 yaffs_BlockInfo *bi;
2796
2797 if (dev->nErasedBlocks < 1) {
2798 /* Hoosterman we've got a problem.
2799 * Can't get space to gc
2800 */
2801 T(YAFFS_TRACE_ERROR,
2802 (TSTR("yaffs tragedy: no more eraased blocks" TENDSTR)));
2803
2804 return -1;
2805 }
2806
2807 /* Find an empty block. */
2808
2809 for (i = dev->internalStartBlock; i <= dev->internalEndBlock; i++) {
2810 dev->allocationBlockFinder++;
2811 if (dev->allocationBlockFinder < dev->internalStartBlock
2812 || dev->allocationBlockFinder > dev->internalEndBlock) {
2813 dev->allocationBlockFinder = dev->internalStartBlock;
2814 }
2815
2816 bi = yaffs_GetBlockInfo(dev, dev->allocationBlockFinder);
2817
2818 if (bi->blockState == YAFFS_BLOCK_STATE_EMPTY) {
2819 bi->blockState = YAFFS_BLOCK_STATE_ALLOCATING;
2820 dev->sequenceNumber++;
2821 bi->sequenceNumber = dev->sequenceNumber;
2822 dev->nErasedBlocks--;
2823 T(YAFFS_TRACE_ALLOCATE,
2824 (TSTR("Allocated block %d, seq %d, %d left" TENDSTR),
2825 dev->allocationBlockFinder, dev->sequenceNumber,
2826 dev->nErasedBlocks));
2827 return dev->allocationBlockFinder;
2828 }
2829 }
2830
2831 T(YAFFS_TRACE_ALWAYS,
2832 (TSTR
2833 ("yaffs tragedy: no more eraased blocks, but there should have been %d"
2834 TENDSTR), dev->nErasedBlocks));
2835
2836 return -1;
2837 }
2838
2839
2840
2841 static int yaffs_CalcCheckpointBlocksRequired(yaffs_Device *dev)
2842 {
2843 if(!dev->nCheckpointBlocksRequired){
2844 /* Not a valid value so recalculate */
2845 int nBytes = 0;
2846 int nBlocks;
2847 int devBlocks = (dev->endBlock - dev->startBlock + 1);
2848 int tnodeSize;
2849
2850 tnodeSize = (dev->tnodeWidth * YAFFS_NTNODES_LEVEL0)/8;
2851
2852 if(tnodeSize < sizeof(yaffs_Tnode))
2853 tnodeSize = sizeof(yaffs_Tnode);
2854
2855 nBytes += sizeof(yaffs_CheckpointValidity);
2856 nBytes += sizeof(yaffs_CheckpointDevice);
2857 nBytes += devBlocks * sizeof(yaffs_BlockInfo);
2858 nBytes += devBlocks * dev->chunkBitmapStride;
2859 nBytes += (sizeof(yaffs_CheckpointObject) + sizeof(__u32)) * (dev->nObjectsCreated - dev->nFreeObjects);
2860 nBytes += (tnodeSize + sizeof(__u32)) * (dev->nTnodesCreated - dev->nFreeTnodes);
2861 nBytes += sizeof(yaffs_CheckpointValidity);
2862 nBytes += sizeof(__u32); /* checksum*/
2863
2864 /* Round up and add 2 blocks to allow for some bad blocks, so add 3 */
2865
2866 nBlocks = (nBytes/(dev->nDataBytesPerChunk * dev->nChunksPerBlock)) + 3;
2867
2868 dev->nCheckpointBlocksRequired = nBlocks;
2869 }
2870
2871 return dev->nCheckpointBlocksRequired;
2872 }
2873
2874 // Check if there's space to allocate...
2875 // Thinks.... do we need top make this ths same as yaffs_GetFreeChunks()?
2876 static int yaffs_CheckSpaceForAllocation(yaffs_Device * dev)
2877 {
2878 int reservedChunks;
2879 int reservedBlocks = dev->nReservedBlocks;
2880 int checkpointBlocks;
2881
2882 checkpointBlocks = yaffs_CalcCheckpointBlocksRequired(dev) - dev->blocksInCheckpoint;
2883 if(checkpointBlocks < 0)
2884 checkpointBlocks = 0;
2885
2886 reservedChunks = ((reservedBlocks + checkpointBlocks) * dev->nChunksPerBlock);
2887
2888 return (dev->nFreeChunks > reservedChunks);
2889 }
2890
2891 static int yaffs_AllocateChunk(yaffs_Device * dev, int useReserve, yaffs_BlockInfo **blockUsedPtr)
2892 {
2893 int retVal;
2894 yaffs_BlockInfo *bi;
2895
2896 if (dev->allocationBlock < 0) {
2897 /* Get next block to allocate off */
2898 dev->allocationBlock = yaffs_FindBlockForAllocation(dev);
2899 dev->allocationPage = 0;
2900 }
2901
2902 if (!useReserve && !yaffs_CheckSpaceForAllocation(dev)) {
2903 /* Not enough space to allocate unless we're allowed to use the reserve. */
2904 return -1;
2905 }
2906
2907 if (dev->nErasedBlocks < dev->nReservedBlocks
2908 && dev->allocationPage == 0) {
2909 T(YAFFS_TRACE_ALLOCATE, (TSTR("Allocating reserve" TENDSTR)));
2910 }
2911
2912 /* Next page please.... */
2913 if (dev->allocationBlock >= 0) {
2914 bi = yaffs_GetBlockInfo(dev, dev->allocationBlock);
2915
2916 retVal = (dev->allocationBlock * dev->nChunksPerBlock) +
2917 dev->allocationPage;
2918 bi->pagesInUse++;
2919 yaffs_SetChunkBit(dev, dev->allocationBlock,
2920 dev->allocationPage);
2921
2922 dev->allocationPage++;
2923
2924 dev->nFreeChunks--;
2925
2926 /* If the block is full set the state to full */
2927 if (dev->allocationPage >= dev->nChunksPerBlock) {
2928 bi->blockState = YAFFS_BLOCK_STATE_FULL;
2929 dev->allocationBlock = -1;
2930 }
2931
2932 if(blockUsedPtr)
2933 *blockUsedPtr = bi;
2934
2935 return retVal;
2936 }
2937
2938 T(YAFFS_TRACE_ERROR,
2939 (TSTR("!!!!!!!!! Allocator out !!!!!!!!!!!!!!!!!" TENDSTR)));
2940
2941 return -1;
2942 }
2943
2944 static int yaffs_GetErasedChunks(yaffs_Device * dev)
2945 {
2946 int n;
2947
2948 n = dev->nErasedBlocks * dev->nChunksPerBlock;
2949
2950 if (dev->allocationBlock > 0) {
2951 n += (dev->nChunksPerBlock - dev->allocationPage);
2952 }
2953
2954 return n;
2955
2956 }
2957
2958 static int yaffs_GarbageCollectBlock(yaffs_Device * dev, int block)
2959 {
2960 int oldChunk;
2961 int newChunk;
2962 int chunkInBlock;
2963 int markNAND;
2964 int retVal = YAFFS_OK;
2965 int cleanups = 0;
2966 int i;
2967 int isCheckpointBlock;
2968 int matchingChunk;
2969
2970 int chunksBefore = yaffs_GetErasedChunks(dev);
2971 int chunksAfter;
2972
2973 yaffs_ExtendedTags tags;
2974
2975 yaffs_BlockInfo *bi = yaffs_GetBlockInfo(dev, block);
2976
2977 yaffs_Object *object;
2978
2979 isCheckpointBlock = (bi->blockState == YAFFS_BLOCK_STATE_CHECKPOINT);
2980
2981 bi->blockState = YAFFS_BLOCK_STATE_COLLECTING;
2982
2983 T(YAFFS_TRACE_TRACING,
2984 (TSTR("Collecting block %d, in use %d, shrink %d, " TENDSTR), block,
2985 bi->pagesInUse, bi->hasShrinkHeader));
2986
2987 /*yaffs_VerifyFreeChunks(dev); */
2988
2989 bi->hasShrinkHeader = 0; /* clear the flag so that the block can erase */
2990
2991 /* Take off the number of soft deleted entries because
2992 * they're going to get really deleted during GC.
2993 */
2994 dev->nFreeChunks -= bi->softDeletions;
2995
2996 dev->isDoingGC = 1;
2997
2998 if (isCheckpointBlock ||
2999 !yaffs_StillSomeChunkBits(dev, block)) {
3000 T(YAFFS_TRACE_TRACING,
3001 (TSTR
3002 ("Collecting block %d that has no chunks in use" TENDSTR),
3003 block));
3004 yaffs_BlockBecameDirty(dev, block);
3005 } else {
3006
3007 __u8 *buffer = yaffs_GetTempBuffer(dev, __LINE__);
3008
3009 yaffs_VerifyBlock(dev,bi,block);
3010
3011 for (chunkInBlock = 0, oldChunk = block * dev->nChunksPerBlock;
3012 chunkInBlock < dev->nChunksPerBlock
3013 && yaffs_StillSomeChunkBits(dev, block);
3014 chunkInBlock++, oldChunk++) {
3015 if (yaffs_CheckChunkBit(dev, block, chunkInBlock)) {
3016
3017 /* This page is in use and might need to be copied off */
3018
3019 markNAND = 1;
3020
3021 yaffs_InitialiseTags(&tags);
3022
3023 yaffs_ReadChunkWithTagsFromNAND(dev, oldChunk,
3024 buffer, &tags);
3025
3026 object =
3027 yaffs_FindObjectByNumber(dev,
3028 tags.objectId);
3029
3030 T(YAFFS_TRACE_GC_DETAIL,
3031 (TSTR
3032 ("Collecting page %d, %d %d %d " TENDSTR),
3033 chunkInBlock, tags.objectId, tags.chunkId,
3034 tags.byteCount));
3035
3036 if(object && !yaffs_SkipVerification(dev)){
3037 if(tags.chunkId == 0)
3038 matchingChunk = object->chunkId;
3039 else if(object->softDeleted)
3040 matchingChunk = oldChunk; /* Defeat the test */
3041 else
3042 matchingChunk = yaffs_FindChunkInFile(object,tags.chunkId,NULL);
3043
3044 if(oldChunk != matchingChunk)
3045 T(YAFFS_TRACE_ERROR,
3046 (TSTR("gc: page in gc mismatch: %d %d %d %d"TENDSTR),
3047 oldChunk,matchingChunk,tags.objectId, tags.chunkId));
3048
3049 }
3050
3051 if (!object) {
3052 T(YAFFS_TRACE_ERROR,
3053 (TSTR
3054 ("page %d in gc has no object: %d %d %d "
3055 TENDSTR), oldChunk,
3056 tags.objectId, tags.chunkId, tags.byteCount));
3057 }
3058
3059 if (object && object->deleted
3060 && tags.chunkId != 0) {
3061 /* Data chunk in a deleted file, throw it away
3062 * It's a soft deleted data chunk,
3063 * No need to copy this, just forget about it and
3064 * fix up the object.
3065 */
3066
3067 object->nDataChunks--;
3068
3069 if (object->nDataChunks <= 0) {
3070 /* remeber to clean up the object */
3071 dev->gcCleanupList[cleanups] =
3072 tags.objectId;
3073 cleanups++;
3074 }
3075 markNAND = 0;
3076 } else if (0
3077 /* Todo object && object->deleted && object->nDataChunks == 0 */
3078 ) {
3079 /* Deleted object header with no data chunks.
3080 * Can be discarded and the file deleted.
3081 */
3082 object->chunkId = 0;
3083 yaffs_FreeTnode(object->myDev,
3084 object->variant.
3085 fileVariant.top);
3086 object->variant.fileVariant.top = NULL;
3087 yaffs_DoGenericObjectDeletion(object);
3088
3089 } else if (object) {
3090 /* It's either a data chunk in a live file or
3091 * an ObjectHeader, so we're interested in it.
3092 * NB Need to keep the ObjectHeaders of deleted files
3093 * until the whole file has been deleted off
3094 */
3095 tags.serialNumber++;
3096
3097 dev->nGCCopies++;
3098
3099 if (tags.chunkId == 0) {
3100 /* It is an object Id,
3101 * We need to nuke the shrinkheader flags first
3102 * We no longer want the shrinkHeader flag since its work is done
3103 * and if it is left in place it will mess up scanning.
3104 * Also, clear out any shadowing stuff
3105 */
3106
3107 yaffs_ObjectHeader *oh;
3108 oh = (yaffs_ObjectHeader *)buffer;
3109 oh->isShrink = 0;
3110 oh->shadowsObject = oh->inbandShadowsObject = -1;
3111 tags.extraShadows = 0;
3112 tags.extraIsShrinkHeader = 0;
3113
3114 yaffs_VerifyObjectHeader(object,oh,&tags,1);
3115 }
3116
3117 newChunk =
3118 yaffs_WriteNewChunkWithTagsToNAND(dev, buffer, &tags, 1);
3119
3120 if (newChunk < 0) {
3121 retVal = YAFFS_FAIL;
3122 } else {
3123
3124 /* Ok, now fix up the Tnodes etc. */
3125
3126 if (tags.chunkId == 0) {
3127 /* It's a header */
3128 object->chunkId = newChunk;
3129 object->serial = tags.serialNumber;
3130 } else {
3131 /* It's a data chunk */
3132 yaffs_PutChunkIntoFile
3133 (object,
3134 tags.chunkId,
3135 newChunk, 0);
3136 }
3137 }
3138 }
3139
3140 yaffs_DeleteChunk(dev, oldChunk, markNAND, __LINE__);
3141
3142 }
3143 }
3144
3145 yaffs_ReleaseTempBuffer(dev, buffer, __LINE__);
3146
3147
3148 /* Do any required cleanups */
3149 for (i = 0; i < cleanups; i++) {
3150 /* Time to delete the file too */
3151 object =
3152 yaffs_FindObjectByNumber(dev,
3153 dev->gcCleanupList[i]);
3154 if (object) {
3155 yaffs_FreeTnode(dev,
3156 object->variant.fileVariant.
3157 top);
3158 object->variant.fileVariant.top = NULL;
3159 T(YAFFS_TRACE_GC,
3160 (TSTR
3161 ("yaffs: About to finally delete object %d"
3162 TENDSTR), object->objectId));
3163 yaffs_DoGenericObjectDeletion(object);
3164 object->myDev->nDeletedFiles--;
3165 }
3166
3167 }
3168
3169 }
3170
3171 yaffs_VerifyCollectedBlock(dev,bi,block);
3172
3173 if (chunksBefore >= (chunksAfter = yaffs_GetErasedChunks(dev))) {
3174 T(YAFFS_TRACE_GC,
3175 (TSTR
3176 ("gc did not increase free chunks before %d after %d"
3177 TENDSTR), chunksBefore, chunksAfter));
3178 }
3179
3180 dev->isDoingGC = 0;
3181
3182 return YAFFS_OK;
3183 }
3184
3185 /* New garbage collector
3186 * If we're very low on erased blocks then we do aggressive garbage collection
3187 * otherwise we do "leasurely" garbage collection.
3188 * Aggressive gc looks further (whole array) and will accept less dirty blocks.
3189 * Passive gc only inspects smaller areas and will only accept more dirty blocks.
3190 *
3191 * The idea is to help clear out space in a more spread-out manner.
3192 * Dunno if it really does anything useful.
3193 */
3194 static int yaffs_CheckGarbageCollection(yaffs_Device * dev)
3195 {
3196 int block;
3197 int aggressive;
3198 int gcOk = YAFFS_OK;
3199 int maxTries = 0;
3200
3201 int checkpointBlockAdjust;
3202
3203 if (dev->isDoingGC) {
3204 /* Bail out so we don't get recursive gc */
3205 return YAFFS_OK;
3206 }
3207
3208 /* This loop should pass the first time.
3209 * We'll only see looping here if the erase of the collected block fails.
3210 */
3211
3212 do {
3213 maxTries++;
3214
3215 checkpointBlockAdjust = yaffs_CalcCheckpointBlocksRequired(dev) - dev->blocksInCheckpoint;
3216 if(checkpointBlockAdjust < 0)
3217 checkpointBlockAdjust = 0;
3218
3219 if (dev->nErasedBlocks < (dev->nReservedBlocks + checkpointBlockAdjust + 2)) {
3220 /* We need a block soon...*/
3221 aggressive = 1;
3222 } else {
3223 /* We're in no hurry */
3224 aggressive = 0;
3225 }
3226
3227 block = yaffs_FindBlockForGarbageCollection(dev, aggressive);
3228
3229 if (block > 0) {
3230 dev->garbageCollections++;
3231 if (!aggressive) {
3232 dev->passiveGarbageCollections++;
3233 }
3234
3235 T(YAFFS_TRACE_GC,
3236 (TSTR
3237 ("yaffs: GC erasedBlocks %d aggressive %d" TENDSTR),
3238 dev->nErasedBlocks, aggressive));
3239
3240 gcOk = yaffs_GarbageCollectBlock(dev, block);
3241 }
3242
3243 if (dev->nErasedBlocks < (dev->nReservedBlocks) && block > 0) {
3244 T(YAFFS_TRACE_GC,
3245 (TSTR
3246 ("yaffs: GC !!!no reclaim!!! erasedBlocks %d after try %d block %d"
3247 TENDSTR), dev->nErasedBlocks, maxTries, block));
3248 }
3249 } while ((dev->nErasedBlocks < dev->nReservedBlocks) && (block > 0)
3250 && (maxTries < 2));
3251
3252 return aggressive ? gcOk : YAFFS_OK;
3253 }
3254
3255 /*------------------------- TAGS --------------------------------*/
3256
3257 static int yaffs_TagsMatch(const yaffs_ExtendedTags * tags, int objectId,
3258 int chunkInObject)
3259 {
3260 return (tags->chunkId == chunkInObject &&
3261 tags->objectId == objectId && !tags->chunkDeleted) ? 1 : 0;
3262
3263 }
3264
3265
3266 /*-------------------- Data file manipulation -----------------*/
3267
3268 static int yaffs_FindChunkInFile(yaffs_Object * in, int chunkInInode,
3269 yaffs_ExtendedTags * tags)
3270 {
3271 /*Get the Tnode, then get the level 0 offset chunk offset */
3272 yaffs_Tnode *tn;
3273 int theChunk = -1;
3274 yaffs_ExtendedTags localTags;
3275 int retVal = -1;
3276
3277 yaffs_Device *dev = in->myDev;
3278
3279 if (!tags) {
3280 /* Passed a NULL, so use our own tags space */
3281 tags = &localTags;
3282 }
3283
3284 tn = yaffs_FindLevel0Tnode(dev, &in->variant.fileVariant, chunkInInode);
3285
3286 if (tn) {
3287 theChunk = yaffs_GetChunkGroupBase(dev,tn,chunkInInode);
3288
3289 retVal =
3290 yaffs_FindChunkInGroup(dev, theChunk, tags, in->objectId,
3291 chunkInInode);
3292 }
3293 return retVal;
3294 }
3295
3296 static int yaffs_FindAndDeleteChunkInFile(yaffs_Object * in, int chunkInInode,
3297 yaffs_ExtendedTags * tags)
3298 {
3299 /* Get the Tnode, then get the level 0 offset chunk offset */
3300 yaffs_Tnode *tn;
3301 int theChunk = -1;
3302 yaffs_ExtendedTags localTags;
3303
3304 yaffs_Device *dev = in->myDev;
3305 int retVal = -1;
3306
3307 if (!tags) {
3308 /* Passed a NULL, so use our own tags space */
3309 tags = &localTags;
3310 }
3311
3312 tn = yaffs_FindLevel0Tnode(dev, &in->variant.fileVariant, chunkInInode);
3313
3314 if (tn) {
3315
3316 theChunk = yaffs_GetChunkGroupBase(dev,tn,chunkInInode);
3317
3318 retVal =
3319 yaffs_FindChunkInGroup(dev, theChunk, tags, in->objectId,
3320 chunkInInode);
3321
3322 /* Delete the entry in the filestructure (if found) */
3323 if (retVal != -1) {
3324 yaffs_PutLevel0Tnode(dev,tn,chunkInInode,0);
3325 }
3326 } else {
3327 /*T(("No level 0 found for %d\n", chunkInInode)); */
3328 }
3329
3330 if (retVal == -1) {
3331 /* T(("Could not find %d to delete\n",chunkInInode)); */
3332 }
3333 return retVal;
3334 }
3335
3336 #ifdef YAFFS_PARANOID
3337
3338 static int yaffs_CheckFileSanity(yaffs_Object * in)
3339 {
3340 int chunk;
3341 int nChunks;
3342 int fSize;
3343 int failed = 0;
3344 int objId;
3345 yaffs_Tnode *tn;
3346 yaffs_Tags localTags;
3347 yaffs_Tags *tags = &localTags;
3348 int theChunk;
3349 int chunkDeleted;
3350
3351 if (in->variantType != YAFFS_OBJECT_TYPE_FILE) {
3352 /* T(("Object not a file\n")); */
3353 return YAFFS_FAIL;
3354 }
3355
3356 objId = in->objectId;
3357 fSize = in->variant.fileVariant.fileSize;
3358 nChunks =
3359 (fSize + in->myDev->nDataBytesPerChunk - 1) / in->myDev->nDataBytesPerChunk;
3360
3361 for (chunk = 1; chunk <= nChunks; chunk++) {
3362 tn = yaffs_FindLevel0Tnode(in->myDev, &in->variant.fileVariant,
3363 chunk);
3364
3365 if (tn) {
3366
3367 theChunk = yaffs_GetChunkGroupBase(dev,tn,chunk);
3368
3369 if (yaffs_CheckChunkBits
3370 (dev, theChunk / dev->nChunksPerBlock,
3371 theChunk % dev->nChunksPerBlock)) {
3372
3373 yaffs_ReadChunkTagsFromNAND(in->myDev, theChunk,
3374 tags,
3375 &chunkDeleted);
3376 if (yaffs_TagsMatch
3377 (tags, in->objectId, chunk, chunkDeleted)) {
3378 /* found it; */
3379
3380 }
3381 } else {
3382
3383 failed = 1;
3384 }
3385
3386 } else {
3387 /* T(("No level 0 found for %d\n", chunk)); */
3388 }
3389 }
3390
3391 return failed ? YAFFS_FAIL : YAFFS_OK;
3392 }
3393
3394 #endif
3395
3396 static int yaffs_PutChunkIntoFile(yaffs_Object * in, int chunkInInode,
3397 int chunkInNAND, int inScan)
3398 {
3399 /* NB inScan is zero unless scanning.
3400 * For forward scanning, inScan is > 0;
3401 * for backward scanning inScan is < 0
3402 */
3403
3404 yaffs_Tnode *tn;
3405 yaffs_Device *dev = in->myDev;
3406 int existingChunk;
3407 yaffs_ExtendedTags existingTags;
3408 yaffs_ExtendedTags newTags;
3409 unsigned existingSerial, newSerial;
3410
3411 if (in->variantType != YAFFS_OBJECT_TYPE_FILE) {
3412 /* Just ignore an attempt at putting a chunk into a non-file during scanning
3413 * If it is not during Scanning then something went wrong!
3414 */
3415 if (!inScan) {
3416 T(YAFFS_TRACE_ERROR,
3417 (TSTR
3418 ("yaffs tragedy:attempt to put data chunk into a non-file"
3419 TENDSTR)));
3420 YBUG();
3421 }
3422
3423 yaffs_DeleteChunk(dev, chunkInNAND, 1, __LINE__);
3424 return YAFFS_OK;
3425 }
3426
3427 tn = yaffs_AddOrFindLevel0Tnode(dev,
3428 &in->variant.fileVariant,
3429 chunkInInode,
3430 NULL);
3431 if (!tn) {
3432 return YAFFS_FAIL;
3433 }
3434
3435 existingChunk = yaffs_GetChunkGroupBase(dev,tn,chunkInInode);
3436
3437 if (inScan != 0) {
3438 /* If we're scanning then we need to test for duplicates
3439 * NB This does not need to be efficient since it should only ever
3440 * happen when the power fails during a write, then only one
3441 * chunk should ever be affected.
3442 *
3443 * Correction for YAFFS2: This could happen quite a lot and we need to think about efficiency! TODO
3444 * Update: For backward scanning we don't need to re-read tags so this is quite cheap.
3445 */
3446
3447 if (existingChunk != 0) {
3448 /* NB Right now existing chunk will not be real chunkId if the device >= 32MB
3449 * thus we have to do a FindChunkInFile to get the real chunk id.
3450 *
3451 * We have a duplicate now we need to decide which one to use:
3452 *
3453 * Backwards scanning YAFFS2: The old one is what we use, dump the new one.
3454 * Forward scanning YAFFS2: The new one is what we use, dump the old one.
3455 * YAFFS1: Get both sets of tags and compare serial numbers.
3456 */
3457
3458 if (inScan > 0) {
3459 /* Only do this for forward scanning */
3460 yaffs_ReadChunkWithTagsFromNAND(dev,
3461 chunkInNAND,
3462 NULL, &newTags);
3463
3464 /* Do a proper find */
3465 existingChunk =
3466 yaffs_FindChunkInFile(in, chunkInInode,
3467 &existingTags);
3468 }
3469
3470 if (existingChunk <= 0) {
3471 /*Hoosterman - how did this happen? */
3472
3473 T(YAFFS_TRACE_ERROR,
3474 (TSTR
3475 ("yaffs tragedy: existing chunk < 0 in scan"
3476 TENDSTR)));
3477
3478 }
3479
3480 /* NB The deleted flags should be false, otherwise the chunks will
3481 * not be loaded during a scan
3482 */
3483
3484 newSerial = newTags.serialNumber;
3485 existingSerial = existingTags.serialNumber;
3486
3487 if ((inScan > 0) &&
3488 (in->myDev->isYaffs2 ||
3489 existingChunk <= 0 ||
3490 ((existingSerial + 1) & 3) == newSerial)) {
3491 /* Forward scanning.
3492 * Use new
3493 * Delete the old one and drop through to update the tnode
3494 */
3495 yaffs_DeleteChunk(dev, existingChunk, 1,
3496 __LINE__);
3497 } else {
3498 /* Backward scanning or we want to use the existing one
3499 * Use existing.
3500 * Delete the new one and return early so that the tnode isn't changed
3501 */
3502 yaffs_DeleteChunk(dev, chunkInNAND, 1,
3503 __LINE__);
3504 return YAFFS_OK;
3505 }
3506 }
3507
3508 }
3509
3510 if (existingChunk == 0) {
3511 in->nDataChunks++;
3512 }
3513
3514 yaffs_PutLevel0Tnode(dev,tn,chunkInInode,chunkInNAND);
3515
3516 return YAFFS_OK;
3517 }
3518
3519 static int yaffs_ReadChunkDataFromObject(yaffs_Object * in, int chunkInInode,
3520 __u8 * buffer)
3521 {
3522 int chunkInNAND = yaffs_FindChunkInFile(in, chunkInInode, NULL);
3523
3524 if (chunkInNAND >= 0) {
3525 return yaffs_ReadChunkWithTagsFromNAND(in->myDev, chunkInNAND,
3526 buffer,NULL);
3527 } else {
3528 T(YAFFS_TRACE_NANDACCESS,
3529 (TSTR("Chunk %d not found zero instead" TENDSTR),
3530 chunkInNAND));
3531 /* get sane (zero) data if you read a hole */
3532 memset(buffer, 0, in->myDev->nDataBytesPerChunk);
3533 return 0;
3534 }
3535
3536 }
3537
3538 void yaffs_DeleteChunk(yaffs_Device * dev, int chunkId, int markNAND, int lyn)
3539 {
3540 int block;
3541 int page;
3542 yaffs_ExtendedTags tags;
3543 yaffs_BlockInfo *bi;
3544
3545 if (chunkId <= 0)
3546 return;
3547
3548
3549 dev->nDeletions++;
3550 block = chunkId / dev->nChunksPerBlock;
3551 page = chunkId % dev->nChunksPerBlock;
3552
3553
3554 if(!yaffs_CheckChunkBit(dev,block,page))
3555 T(YAFFS_TRACE_VERIFY,
3556 (TSTR("Deleting invalid chunk %d"TENDSTR),
3557 chunkId));
3558
3559 bi = yaffs_GetBlockInfo(dev, block);
3560
3561 T(YAFFS_TRACE_DELETION,
3562 (TSTR("line %d delete of chunk %d" TENDSTR), lyn, chunkId));
3563
3564 if (markNAND &&
3565 bi->blockState != YAFFS_BLOCK_STATE_COLLECTING && !dev->isYaffs2) {
3566
3567 yaffs_InitialiseTags(&tags);
3568
3569 tags.chunkDeleted = 1;
3570
3571 yaffs_WriteChunkWithTagsToNAND(dev, chunkId, NULL, &tags);
3572 yaffs_HandleUpdateChunk(dev, chunkId, &tags);
3573 } else {
3574 dev->nUnmarkedDeletions++;
3575 }
3576
3577 /* Pull out of the management area.
3578 * If the whole block became dirty, this will kick off an erasure.
3579 */
3580 if (bi->blockState == YAFFS_BLOCK_STATE_ALLOCATING ||
3581 bi->blockState == YAFFS_BLOCK_STATE_FULL ||
3582 bi->blockState == YAFFS_BLOCK_STATE_NEEDS_SCANNING ||
3583 bi->blockState == YAFFS_BLOCK_STATE_COLLECTING) {
3584 dev->nFreeChunks++;
3585
3586 yaffs_ClearChunkBit(dev, block, page);
3587
3588 bi->pagesInUse--;
3589
3590 if (bi->pagesInUse == 0 &&
3591 !bi->hasShrinkHeader &&
3592 bi->blockState != YAFFS_BLOCK_STATE_ALLOCATING &&
3593 bi->blockState != YAFFS_BLOCK_STATE_NEEDS_SCANNING) {
3594 yaffs_BlockBecameDirty(dev, block);
3595 }
3596
3597 } else {
3598 /* T(("Bad news deleting chunk %d\n",chunkId)); */
3599 }
3600
3601 }
3602
3603 static int yaffs_WriteChunkDataToObject(yaffs_Object * in, int chunkInInode,
3604 const __u8 * buffer, int nBytes,
3605 int useReserve)
3606 {
3607 /* Find old chunk Need to do this to get serial number
3608 * Write new one and patch into tree.
3609 * Invalidate old tags.
3610 */
3611
3612 int prevChunkId;
3613 yaffs_ExtendedTags prevTags;
3614
3615 int newChunkId;
3616 yaffs_ExtendedTags newTags;
3617
3618 yaffs_Device *dev = in->myDev;
3619
3620 yaffs_CheckGarbageCollection(dev);
3621
3622 /* Get the previous chunk at this location in the file if it exists */
3623 prevChunkId = yaffs_FindChunkInFile(in, chunkInInode, &prevTags);
3624
3625 /* Set up new tags */
3626 yaffs_InitialiseTags(&newTags);
3627
3628 newTags.chunkId = chunkInInode;
3629 newTags.objectId = in->objectId;
3630 newTags.serialNumber =
3631 (prevChunkId >= 0) ? prevTags.serialNumber + 1 : 1;
3632 newTags.byteCount = nBytes;
3633
3634 newChunkId =
3635 yaffs_WriteNewChunkWithTagsToNAND(dev, buffer, &newTags,
3636 useReserve);
3637
3638 if (newChunkId >= 0) {
3639 yaffs_PutChunkIntoFile(in, chunkInInode, newChunkId, 0);
3640
3641 if (prevChunkId >= 0) {
3642 yaffs_DeleteChunk(dev, prevChunkId, 1, __LINE__);
3643
3644 }
3645
3646 yaffs_CheckFileSanity(in);
3647 }
3648 return newChunkId;
3649
3650 }
3651
3652 /* UpdateObjectHeader updates the header on NAND for an object.
3653 * If name is not NULL, then that new name is used.
3654 */
3655 int yaffs_UpdateObjectHeader(yaffs_Object * in, const YCHAR * name, int force,
3656 int isShrink, int shadows)
3657 {
3658
3659 yaffs_BlockInfo *bi;
3660
3661 yaffs_Device *dev = in->myDev;
3662
3663 int prevChunkId;
3664 int retVal = 0;
3665 int result = 0;
3666
3667 int newChunkId;
3668 yaffs_ExtendedTags newTags;
3669 yaffs_ExtendedTags oldTags;
3670
3671 __u8 *buffer = NULL;
3672 YCHAR oldName[YAFFS_MAX_NAME_LENGTH + 1];
3673
3674 yaffs_ObjectHeader *oh = NULL;
3675
3676 yaffs_strcpy(oldName,"silly old name");
3677
3678 if (!in->fake || force) {
3679
3680 yaffs_CheckGarbageCollection(dev);
3681 yaffs_CheckObjectDetailsLoaded(in);
3682
3683 buffer = yaffs_GetTempBuffer(in->myDev, __LINE__);
3684 oh = (yaffs_ObjectHeader *) buffer;
3685
3686 prevChunkId = in->chunkId;
3687
3688 if (prevChunkId >= 0) {
3689 result = yaffs_ReadChunkWithTagsFromNAND(dev, prevChunkId,
3690 buffer, &oldTags);
3691
3692 yaffs_VerifyObjectHeader(in,oh,&oldTags,0);
3693
3694 memcpy(oldName, oh->name, sizeof(oh->name));
3695 }
3696
3697 memset(buffer, 0xFF, dev->nDataBytesPerChunk);
3698
3699 oh->type = in->variantType;
3700 oh->yst_mode = in->yst_mode;
3701 oh->shadowsObject = oh->inbandShadowsObject = shadows;
3702
3703 #ifdef CONFIG_YAFFS_WINCE
3704 oh->win_atime[0] = in->win_atime[0];
3705 oh->win_ctime[0] = in->win_ctime[0];
3706 oh->win_mtime[0] = in->win_mtime[0];
3707 oh->win_atime[1] = in->win_atime[1];
3708 oh->win_ctime[1] = in->win_ctime[1];
3709 oh->win_mtime[1] = in->win_mtime[1];
3710 #else
3711 oh->yst_uid = in->yst_uid;
3712 oh->yst_gid = in->yst_gid;
3713 oh->yst_atime = in->yst_atime;
3714 oh->yst_mtime = in->yst_mtime;
3715 oh->yst_ctime = in->yst_ctime;
3716 oh->yst_rdev = in->yst_rdev;
3717 #endif
3718 if (in->parent) {
3719 oh->parentObjectId = in->parent->objectId;
3720 } else {
3721 oh->parentObjectId = 0;
3722 }
3723
3724 if (name && *name) {
3725 memset(oh->name, 0, sizeof(oh->name));
3726 yaffs_strncpy(oh->name, name, YAFFS_MAX_NAME_LENGTH);
3727 } else if (prevChunkId>=0) {
3728 memcpy(oh->name, oldName, sizeof(oh->name));
3729 } else {
3730 memset(oh->name, 0, sizeof(oh->name));
3731 }
3732
3733 oh->isShrink = isShrink;
3734
3735 switch (in->variantType) {
3736 case YAFFS_OBJECT_TYPE_UNKNOWN:
3737 /* Should not happen */
3738 break;
3739 case YAFFS_OBJECT_TYPE_FILE:
3740 oh->fileSize =
3741 (oh->parentObjectId == YAFFS_OBJECTID_DELETED
3742 || oh->parentObjectId ==
3743 YAFFS_OBJECTID_UNLINKED) ? 0 : in->variant.
3744 fileVariant.fileSize;
3745 break;
3746 case YAFFS_OBJECT_TYPE_HARDLINK:
3747 oh->equivalentObjectId =
3748 in->variant.hardLinkVariant.equivalentObjectId;
3749 break;
3750 case YAFFS_OBJECT_TYPE_SPECIAL:
3751 /* Do nothing */
3752 break;
3753 case YAFFS_OBJECT_TYPE_DIRECTORY:
3754 /* Do nothing */
3755 break;
3756 case YAFFS_OBJECT_TYPE_SYMLINK:
3757 yaffs_strncpy(oh->alias,
3758 in->variant.symLinkVariant.alias,
3759 YAFFS_MAX_ALIAS_LENGTH);
3760 oh->alias[YAFFS_MAX_ALIAS_LENGTH] = 0;
3761 break;
3762 }
3763
3764 /* Tags */
3765 yaffs_InitialiseTags(&newTags);
3766 in->serial++;
3767 newTags.chunkId = 0;
3768 newTags.objectId = in->objectId;
3769 newTags.serialNumber = in->serial;
3770
3771 /* Add extra info for file header */
3772
3773 newTags.extraHeaderInfoAvailable = 1;
3774 newTags.extraParentObjectId = oh->parentObjectId;
3775 newTags.extraFileLength = oh->fileSize;
3776 newTags.extraIsShrinkHeader = oh->isShrink;
3777 newTags.extraEquivalentObjectId = oh->equivalentObjectId;
3778 newTags.extraShadows = (oh->shadowsObject > 0) ? 1 : 0;
3779 newTags.extraObjectType = in->variantType;
3780
3781 yaffs_VerifyObjectHeader(in,oh,&newTags,1);
3782
3783 /* Create new chunk in NAND */
3784 newChunkId =
3785 yaffs_WriteNewChunkWithTagsToNAND(dev, buffer, &newTags,
3786 (prevChunkId >= 0) ? 1 : 0);
3787
3788 if (newChunkId >= 0) {
3789
3790 in->chunkId = newChunkId;
3791
3792 if (prevChunkId >= 0) {
3793 yaffs_DeleteChunk(dev, prevChunkId, 1,
3794 __LINE__);
3795 }
3796
3797 if(!yaffs_ObjectHasCachedWriteData(in))
3798 in->dirty = 0;
3799
3800 /* If this was a shrink, then mark the block that the chunk lives on */
3801 if (isShrink) {
3802 bi = yaffs_GetBlockInfo(in->myDev,
3803 newChunkId /in->myDev-> nChunksPerBlock);
3804 bi->hasShrinkHeader = 1;
3805 }
3806
3807 }
3808
3809 retVal = newChunkId;
3810
3811 }
3812
3813 if (buffer)
3814 yaffs_ReleaseTempBuffer(dev, buffer, __LINE__);
3815
3816 return retVal;
3817 }
3818
3819 /*------------------------ Short Operations Cache ----------------------------------------
3820 * In many situations where there is no high level buffering (eg WinCE) a lot of
3821 * reads might be short sequential reads, and a lot of writes may be short
3822 * sequential writes. eg. scanning/writing a jpeg file.
3823 * In these cases, a short read/write cache can provide a huge perfomance benefit
3824 * with dumb-as-a-rock code.
3825 * In Linux, the page cache provides read buffering aand the short op cache provides write
3826 * buffering.
3827 *
3828 * There are a limited number (~10) of cache chunks per device so that we don't
3829 * need a very intelligent search.
3830 */
3831
3832 static int yaffs_ObjectHasCachedWriteData(yaffs_Object *obj)
3833 {
3834 yaffs_Device *dev = obj->myDev;
3835 int i;
3836 yaffs_ChunkCache *cache;
3837 int nCaches = obj->myDev->nShortOpCaches;
3838
3839 for(i = 0; i < nCaches; i++){
3840 cache = &dev->srCache[i];
3841 if (cache->object == obj &&
3842 cache->dirty)
3843 return 1;
3844 }
3845
3846 return 0;
3847 }
3848
3849
3850 static void yaffs_FlushFilesChunkCache(yaffs_Object * obj)
3851 {
3852 yaffs_Device *dev = obj->myDev;
3853 int lowest = -99; /* Stop compiler whining. */
3854 int i;
3855 yaffs_ChunkCache *cache;
3856 int chunkWritten = 0;
3857 int nCaches = obj->myDev->nShortOpCaches;
3858
3859 if (nCaches > 0) {
3860 do {
3861 cache = NULL;
3862
3863 /* Find the dirty cache for this object with the lowest chunk id. */
3864 for (i = 0; i < nCaches; i++) {
3865 if (dev->srCache[i].object == obj &&
3866 dev->srCache[i].dirty) {
3867 if (!cache
3868 || dev->srCache[i].chunkId <
3869 lowest) {
3870 cache = &dev->srCache[i];
3871 lowest = cache->chunkId;
3872 }
3873 }
3874 }
3875
3876 if (cache && !cache->locked) {
3877 /* Write it out and free it up */
3878
3879 chunkWritten =
3880 yaffs_WriteChunkDataToObject(cache->object,
3881 cache->chunkId,
3882 cache->data,
3883 cache->nBytes,
3884 1);
3885 cache->dirty = 0;
3886 cache->object = NULL;
3887 }
3888
3889 } while (cache && chunkWritten > 0);
3890
3891 if (cache) {
3892 /* Hoosterman, disk full while writing cache out. */
3893 T(YAFFS_TRACE_ERROR,
3894 (TSTR("yaffs tragedy: no space during cache write" TENDSTR)));
3895
3896 }
3897 }
3898
3899 }
3900
3901 /*yaffs_FlushEntireDeviceCache(dev)
3902 *
3903 *
3904 */
3905
3906 void yaffs_FlushEntireDeviceCache(yaffs_Device *dev)
3907 {
3908 yaffs_Object *obj;
3909 int nCaches = dev->nShortOpCaches;
3910 int i;
3911
3912 /* Find a dirty object in the cache and flush it...
3913 * until there are no further dirty objects.
3914 */
3915 do {
3916 obj = NULL;
3917 for( i = 0; i < nCaches && !obj; i++) {
3918 if (dev->srCache[i].object &&
3919 dev->srCache[i].dirty)
3920 obj = dev->srCache[i].object;
3921
3922 }
3923 if(obj)
3924 yaffs_FlushFilesChunkCache(obj);
3925
3926 } while(obj);
3927
3928 }
3929
3930
3931 /* Grab us a cache chunk for use.
3932 * First look for an empty one.
3933 * Then look for the least recently used non-dirty one.
3934 * Then look for the least recently used dirty one...., flush and look again.
3935 */
3936 static yaffs_ChunkCache *yaffs_GrabChunkCacheWorker(yaffs_Device * dev)
3937 {
3938 int i;
3939 int usage;
3940 int theOne;
3941
3942 if (dev->nShortOpCaches > 0) {
3943 for (i = 0; i < dev->nShortOpCaches; i++) {
3944 if (!dev->srCache[i].object)
3945 return &dev->srCache[i];
3946 }
3947
3948 return NULL;
3949
3950 theOne = -1;
3951 usage = 0; /* just to stop the compiler grizzling */
3952
3953 for (i = 0; i < dev->nShortOpCaches; i++) {
3954 if (!dev->srCache[i].dirty &&
3955 ((dev->srCache[i].lastUse < usage && theOne >= 0) ||
3956 theOne < 0)) {
3957 usage = dev->srCache[i].lastUse;
3958 theOne = i;
3959 }
3960 }
3961
3962
3963 return theOne >= 0 ? &dev->srCache[theOne] : NULL;
3964 } else {
3965 return NULL;
3966 }
3967
3968 }
3969
3970 static yaffs_ChunkCache *yaffs_GrabChunkCache(yaffs_Device * dev)
3971 {
3972 yaffs_ChunkCache *cache;
3973 yaffs_Object *theObj;
3974 int usage;
3975 int i;
3976 int pushout;
3977
3978 if (dev->nShortOpCaches > 0) {
3979 /* Try find a non-dirty one... */
3980
3981 cache = yaffs_GrabChunkCacheWorker(dev);
3982
3983 if (!cache) {
3984 /* They were all dirty, find the last recently used object and flush
3985 * its cache, then find again.
3986 * NB what's here is not very accurate, we actually flush the object
3987 * the last recently used page.
3988 */
3989
3990 /* With locking we can't assume we can use entry zero */
3991
3992 theObj = NULL;
3993 usage = -1;
3994 cache = NULL;
3995 pushout = -1;
3996
3997 for (i = 0; i < dev->nShortOpCaches; i++) {
3998 if (dev->srCache[i].object &&
3999 !dev->srCache[i].locked &&
4000 (dev->srCache[i].lastUse < usage || !cache))
4001 {
4002 usage = dev->srCache[i].lastUse;
4003 theObj = dev->srCache[i].object;
4004 cache = &dev->srCache[i];
4005 pushout = i;
4006 }
4007 }
4008
4009 if (!cache || cache->dirty) {
4010 /* Flush and try again */
4011 yaffs_FlushFilesChunkCache(theObj);
4012 cache = yaffs_GrabChunkCacheWorker(dev);
4013 }
4014
4015 }
4016 return cache;
4017 } else
4018 return NULL;
4019
4020 }
4021
4022 /* Find a cached chunk */
4023 static yaffs_ChunkCache *yaffs_FindChunkCache(const yaffs_Object * obj,
4024 int chunkId)
4025 {
4026 yaffs_Device *dev = obj->myDev;
4027 int i;
4028 if (dev->nShortOpCaches > 0) {
4029 for (i = 0; i < dev->nShortOpCaches; i++) {
4030 if (dev->srCache[i].object == obj &&
4031 dev->srCache[i].chunkId == chunkId) {
4032 dev->cacheHits++;
4033
4034 return &dev->srCache[i];
4035 }
4036 }
4037 }
4038 return NULL;
4039 }
4040
4041 /* Mark the chunk for the least recently used algorithym */
4042 static void yaffs_UseChunkCache(yaffs_Device * dev, yaffs_ChunkCache * cache,
4043 int isAWrite)
4044 {
4045
4046 if (dev->nShortOpCaches > 0) {
4047 if (dev->srLastUse < 0 || dev->srLastUse > 100000000) {
4048 /* Reset the cache usages */
4049 int i;
4050 for (i = 1; i < dev->nShortOpCaches; i++) {
4051 dev->srCache[i].lastUse = 0;
4052 }
4053 dev->srLastUse = 0;
4054 }
4055
4056 dev->srLastUse++;
4057
4058 cache->lastUse = dev->srLastUse;
4059
4060 if (isAWrite) {
4061 cache->dirty = 1;
4062 }
4063 }
4064 }
4065
4066 /* Invalidate a single cache page.
4067 * Do this when a whole page gets written,
4068 * ie the short cache for this page is no longer valid.
4069 */
4070 static void yaffs_InvalidateChunkCache(yaffs_Object * object, int chunkId)
4071 {
4072 if (object->myDev->nShortOpCaches > 0) {
4073 yaffs_ChunkCache *cache = yaffs_FindChunkCache(object, chunkId);
4074
4075 if (cache) {
4076 cache->object = NULL;
4077 }
4078 }
4079 }
4080
4081 /* Invalidate all the cache pages associated with this object
4082 * Do this whenever ther file is deleted or resized.
4083 */
4084 static void yaffs_InvalidateWholeChunkCache(yaffs_Object * in)
4085 {
4086 int i;
4087 yaffs_Device *dev = in->myDev;
4088
4089 if (dev->nShortOpCaches > 0) {
4090 /* Invalidate it. */
4091 for (i = 0; i < dev->nShortOpCaches; i++) {
4092 if (dev->srCache[i].object == in) {
4093 dev->srCache[i].object = NULL;
4094 }
4095 }
4096 }
4097 }
4098
4099 /*--------------------- Checkpointing --------------------*/
4100
4101
4102 static int yaffs_WriteCheckpointValidityMarker(yaffs_Device *dev,int head)
4103 {
4104 yaffs_CheckpointValidity cp;
4105
4106 memset(&cp,0,sizeof(cp));
4107
4108 cp.structType = sizeof(cp);
4109 cp.magic = YAFFS_MAGIC;
4110 cp.version = YAFFS_CHECKPOINT_VERSION;
4111 cp.head = (head) ? 1 : 0;
4112
4113 return (yaffs_CheckpointWrite(dev,&cp,sizeof(cp)) == sizeof(cp))?
4114 1 : 0;
4115 }
4116
4117 static int yaffs_ReadCheckpointValidityMarker(yaffs_Device *dev, int head)
4118 {
4119 yaffs_CheckpointValidity cp;
4120 int ok;
4121
4122 ok = (yaffs_CheckpointRead(dev,&cp,sizeof(cp)) == sizeof(cp));
4123
4124 if(ok)
4125 ok = (cp.structType == sizeof(cp)) &&
4126 (cp.magic == YAFFS_MAGIC) &&
4127 (cp.version == YAFFS_CHECKPOINT_VERSION) &&
4128 (cp.head == ((head) ? 1 : 0));
4129 return ok ? 1 : 0;
4130 }
4131
4132 static void yaffs_DeviceToCheckpointDevice(yaffs_CheckpointDevice *cp,
4133 yaffs_Device *dev)
4134 {
4135 cp->nErasedBlocks = dev->nErasedBlocks;
4136 cp->allocationBlock = dev->allocationBlock;
4137 cp->allocationPage = dev->allocationPage;
4138 cp->nFreeChunks = dev->nFreeChunks;
4139
4140 cp->nDeletedFiles = dev->nDeletedFiles;
4141 cp->nUnlinkedFiles = dev->nUnlinkedFiles;
4142 cp->nBackgroundDeletions = dev->nBackgroundDeletions;
4143 cp->sequenceNumber = dev->sequenceNumber;
4144 cp->oldestDirtySequence = dev->oldestDirtySequence;
4145
4146 }
4147
4148 static void yaffs_CheckpointDeviceToDevice(yaffs_Device *dev,
4149 yaffs_CheckpointDevice *cp)
4150 {
4151 dev->nErasedBlocks = cp->nErasedBlocks;
4152 dev->allocationBlock = cp->allocationBlock;
4153 dev->allocationPage = cp->allocationPage;
4154 dev->nFreeChunks = cp->nFreeChunks;
4155
4156 dev->nDeletedFiles = cp->nDeletedFiles;
4157 dev->nUnlinkedFiles = cp->nUnlinkedFiles;
4158 dev->nBackgroundDeletions = cp->nBackgroundDeletions;
4159 dev->sequenceNumber = cp->sequenceNumber;
4160 dev->oldestDirtySequence = cp->oldestDirtySequence;
4161 }
4162
4163
4164 static int yaffs_WriteCheckpointDevice(yaffs_Device *dev)
4165 {
4166 yaffs_CheckpointDevice cp;
4167 __u32 nBytes;
4168 __u32 nBlocks = (dev->internalEndBlock - dev->internalStartBlock + 1);
4169
4170 int ok;
4171
4172 /* Write device runtime values*/
4173 yaffs_DeviceToCheckpointDevice(&cp,dev);
4174 cp.structType = sizeof(cp);
4175
4176 ok = (yaffs_CheckpointWrite(dev,&cp,sizeof(cp)) == sizeof(cp));
4177
4178 /* Write block info */
4179 if(ok) {
4180 nBytes = nBlocks * sizeof(yaffs_BlockInfo);
4181 ok = (yaffs_CheckpointWrite(dev,dev->blockInfo,nBytes) == nBytes);
4182 }
4183
4184 /* Write chunk bits */
4185 if(ok) {
4186 nBytes = nBlocks * dev->chunkBitmapStride;
4187 ok = (yaffs_CheckpointWrite(dev,dev->chunkBits,nBytes) == nBytes);
4188 }
4189 return ok ? 1 : 0;
4190
4191 }
4192
4193 static int yaffs_ReadCheckpointDevice(yaffs_Device *dev)
4194 {
4195 yaffs_CheckpointDevice cp;
4196 __u32 nBytes;
4197 __u32 nBlocks = (dev->internalEndBlock - dev->internalStartBlock + 1);
4198
4199 int ok;
4200
4201 ok = (yaffs_CheckpointRead(dev,&cp,sizeof(cp)) == sizeof(cp));
4202 if(!ok)
4203 return 0;
4204
4205 if(cp.structType != sizeof(cp))
4206 return 0;
4207
4208
4209 yaffs_CheckpointDeviceToDevice(dev,&cp);
4210
4211 nBytes = nBlocks * sizeof(yaffs_BlockInfo);
4212
4213 ok = (yaffs_CheckpointRead(dev,dev->blockInfo,nBytes) == nBytes);
4214
4215 if(!ok)
4216 return 0;
4217 nBytes = nBlocks * dev->chunkBitmapStride;
4218
4219 ok = (yaffs_CheckpointRead(dev,dev->chunkBits,nBytes) == nBytes);
4220
4221 return ok ? 1 : 0;
4222 }
4223
4224 static void yaffs_ObjectToCheckpointObject(yaffs_CheckpointObject *cp,
4225 yaffs_Object *obj)
4226 {
4227
4228 cp->objectId = obj->objectId;
4229 cp->parentId = (obj->parent) ? obj->parent->objectId : 0;
4230 cp->chunkId = obj->chunkId;
4231 cp->variantType = obj->variantType;
4232 cp->deleted = obj->deleted;
4233 cp->softDeleted = obj->softDeleted;
4234 cp->unlinked = obj->unlinked;
4235 cp->fake = obj->fake;
4236 cp->renameAllowed = obj->renameAllowed;
4237 cp->unlinkAllowed = obj->unlinkAllowed;
4238 cp->serial = obj->serial;
4239 cp->nDataChunks = obj->nDataChunks;
4240
4241 if(obj->variantType == YAFFS_OBJECT_TYPE_FILE)
4242 cp->fileSizeOrEquivalentObjectId = obj->variant.fileVariant.fileSize;
4243 else if(obj->variantType == YAFFS_OBJECT_TYPE_HARDLINK)
4244 cp->fileSizeOrEquivalentObjectId = obj->variant.hardLinkVariant.equivalentObjectId;
4245 }
4246
4247 static void yaffs_CheckpointObjectToObject( yaffs_Object *obj,yaffs_CheckpointObject *cp)
4248 {
4249
4250 yaffs_Object *parent;
4251
4252 obj->objectId = cp->objectId;
4253
4254 if(cp->parentId)
4255 parent = yaffs_FindOrCreateObjectByNumber(
4256 obj->myDev,
4257 cp->parentId,
4258 YAFFS_OBJECT_TYPE_DIRECTORY);
4259 else
4260 parent = NULL;
4261
4262 if(parent)
4263 yaffs_AddObjectToDirectory(parent, obj);
4264
4265 obj->chunkId = cp->chunkId;
4266 obj->variantType = cp->variantType;
4267 obj->deleted = cp->deleted;
4268 obj->softDeleted = cp->softDeleted;
4269 obj->unlinked = cp->unlinked;
4270 obj->fake = cp->fake;
4271 obj->renameAllowed = cp->renameAllowed;
4272 obj->unlinkAllowed = cp->unlinkAllowed;
4273 obj->serial = cp->serial;
4274 obj->nDataChunks = cp->nDataChunks;
4275
4276 if(obj->variantType == YAFFS_OBJECT_TYPE_FILE)
4277 obj->variant.fileVariant.fileSize = cp->fileSizeOrEquivalentObjectId;
4278 else if(obj->variantType == YAFFS_OBJECT_TYPE_HARDLINK)
4279 obj->variant.hardLinkVariant.equivalentObjectId = cp->fileSizeOrEquivalentObjectId;
4280
4281 if(obj->objectId >= YAFFS_NOBJECT_BUCKETS)
4282 obj->lazyLoaded = 1;
4283 }
4284
4285
4286
4287 static int yaffs_CheckpointTnodeWorker(yaffs_Object * in, yaffs_Tnode * tn,
4288 __u32 level, int chunkOffset)
4289 {
4290 int i;
4291 yaffs_Device *dev = in->myDev;
4292 int ok = 1;
4293 int tnodeSize = (dev->tnodeWidth * YAFFS_NTNODES_LEVEL0)/8;
4294
4295 if(tnodeSize < sizeof(yaffs_Tnode))
4296 tnodeSize = sizeof(yaffs_Tnode);
4297
4298
4299 if (tn) {
4300 if (level > 0) {
4301
4302 for (i = 0; i < YAFFS_NTNODES_INTERNAL && ok; i++){
4303 if (tn->internal[i]) {
4304 ok = yaffs_CheckpointTnodeWorker(in,
4305 tn->internal[i],
4306 level - 1,
4307 (chunkOffset<<YAFFS_TNODES_INTERNAL_BITS) + i);
4308 }
4309 }
4310 } else if (level == 0) {
4311 __u32 baseOffset = chunkOffset << YAFFS_TNODES_LEVEL0_BITS;
4312 /* printf("write tnode at %d\n",baseOffset); */
4313 ok = (yaffs_CheckpointWrite(dev,&baseOffset,sizeof(baseOffset)) == sizeof(baseOffset));
4314 if(ok)
4315 ok = (yaffs_CheckpointWrite(dev,tn,tnodeSize) == tnodeSize);
4316 }
4317 }
4318
4319 return ok;
4320
4321 }
4322
4323 static int yaffs_WriteCheckpointTnodes(yaffs_Object *obj)
4324 {
4325 __u32 endMarker = ~0;
4326 int ok = 1;
4327
4328 if(obj->variantType == YAFFS_OBJECT_TYPE_FILE){
4329 ok = yaffs_CheckpointTnodeWorker(obj,
4330 obj->variant.fileVariant.top,
4331 obj->variant.fileVariant.topLevel,
4332 0);
4333 if(ok)
4334 ok = (yaffs_CheckpointWrite(obj->myDev,&endMarker,sizeof(endMarker)) ==
4335 sizeof(endMarker));
4336 }
4337
4338 return ok ? 1 : 0;
4339 }
4340
4341 static int yaffs_ReadCheckpointTnodes(yaffs_Object *obj)
4342 {
4343 __u32 baseChunk;
4344 int ok = 1;
4345 yaffs_Device *dev = obj->myDev;
4346 yaffs_FileStructure *fileStructPtr = &obj->variant.fileVariant;
4347 yaffs_Tnode *tn;
4348 int nread = 0;
4349 int tnodeSize = (dev->tnodeWidth * YAFFS_NTNODES_LEVEL0)/8;
4350
4351 if(tnodeSize < sizeof(yaffs_Tnode))
4352 tnodeSize = sizeof(yaffs_Tnode);
4353
4354 ok = (yaffs_CheckpointRead(dev,&baseChunk,sizeof(baseChunk)) == sizeof(baseChunk));
4355
4356 while(ok && (~baseChunk)){
4357 nread++;
4358 /* Read level 0 tnode */
4359
4360
4361 /* printf("read tnode at %d\n",baseChunk); */
4362 tn = yaffs_GetTnodeRaw(dev);
4363 if(tn)
4364 ok = (yaffs_CheckpointRead(dev,tn,tnodeSize) == tnodeSize);
4365 else
4366 ok = 0;
4367
4368 if(tn && ok){
4369 ok = yaffs_AddOrFindLevel0Tnode(dev,
4370 fileStructPtr,
4371 baseChunk,
4372 tn) ? 1 : 0;
4373
4374 }
4375
4376 if(ok)
4377 ok = (yaffs_CheckpointRead(dev,&baseChunk,sizeof(baseChunk)) == sizeof(baseChunk));
4378
4379 }
4380
4381 T(YAFFS_TRACE_CHECKPOINT,(
4382 TSTR("Checkpoint read tnodes %d records, last %d. ok %d" TENDSTR),
4383 nread,baseChunk,ok));
4384
4385 return ok ? 1 : 0;
4386 }
4387
4388
4389 static int yaffs_WriteCheckpointObjects(yaffs_Device *dev)
4390 {
4391 yaffs_Object *obj;
4392 yaffs_CheckpointObject cp;
4393 int i;
4394 int ok = 1;
4395 struct ylist_head *lh;
4396
4397
4398 /* Iterate through the objects in each hash entry,
4399 * dumping them to the checkpointing stream.
4400 */
4401
4402 for(i = 0; ok && i < YAFFS_NOBJECT_BUCKETS; i++){
4403 ylist_for_each(lh, &dev->objectBucket[i].list) {
4404 if (lh) {
4405 obj = ylist_entry(lh, yaffs_Object, hashLink);
4406 if (!obj->deferedFree) {
4407 yaffs_ObjectToCheckpointObject(&cp,obj);
4408 cp.structType = sizeof(cp);
4409
4410 T(YAFFS_TRACE_CHECKPOINT,(
4411 TSTR("Checkpoint write object %d parent %d type %d chunk %d obj addr %x" TENDSTR),
4412 cp.objectId,cp.parentId,cp.variantType,cp.chunkId,(unsigned) obj));
4413
4414 ok = (yaffs_CheckpointWrite(dev,&cp,sizeof(cp)) == sizeof(cp));
4415
4416 if(ok && obj->variantType == YAFFS_OBJECT_TYPE_FILE){
4417 ok = yaffs_WriteCheckpointTnodes(obj);
4418 }
4419 }
4420 }
4421 }
4422 }
4423
4424 /* Dump end of list */
4425 memset(&cp,0xFF,sizeof(yaffs_CheckpointObject));
4426 cp.structType = sizeof(cp);
4427
4428 if(ok)
4429 ok = (yaffs_CheckpointWrite(dev,&cp,sizeof(cp)) == sizeof(cp));
4430
4431 return ok ? 1 : 0;
4432 }
4433
4434 static int yaffs_ReadCheckpointObjects(yaffs_Device *dev)
4435 {
4436 yaffs_Object *obj;
4437 yaffs_CheckpointObject cp;
4438 int ok = 1;
4439 int done = 0;
4440 yaffs_Object *hardList = NULL;
4441
4442 while(ok && !done) {
4443 ok = (yaffs_CheckpointRead(dev,&cp,sizeof(cp)) == sizeof(cp));
4444 if(cp.structType != sizeof(cp)) {
4445 T(YAFFS_TRACE_CHECKPOINT,(TSTR("struct size %d instead of %d ok %d"TENDSTR),
4446 cp.structType,sizeof(cp),ok));
4447 ok = 0;
4448 }
4449
4450 T(YAFFS_TRACE_CHECKPOINT,(TSTR("Checkpoint read object %d parent %d type %d chunk %d " TENDSTR),
4451 cp.objectId,cp.parentId,cp.variantType,cp.chunkId));
4452
4453 if(ok && cp.objectId == ~0)
4454 done = 1;
4455 else if(ok){
4456 obj = yaffs_FindOrCreateObjectByNumber(dev,cp.objectId, cp.variantType);
4457 if(obj) {
4458 yaffs_CheckpointObjectToObject(obj,&cp);
4459 if(obj->variantType == YAFFS_OBJECT_TYPE_FILE) {
4460 ok = yaffs_ReadCheckpointTnodes(obj);
4461 } else if(obj->variantType == YAFFS_OBJECT_TYPE_HARDLINK) {
4462 obj->hardLinks.next =
4463 (struct ylist_head *)
4464 hardList;
4465 hardList = obj;
4466 }
4467
4468 }
4469 }
4470 }
4471
4472 if(ok)
4473 yaffs_HardlinkFixup(dev,hardList);
4474
4475 return ok ? 1 : 0;
4476 }
4477
4478 static int yaffs_WriteCheckpointSum(yaffs_Device *dev)
4479 {
4480 __u32 checkpointSum;
4481 int ok;
4482
4483 yaffs_GetCheckpointSum(dev,&checkpointSum);
4484
4485 ok = (yaffs_CheckpointWrite(dev,&checkpointSum,sizeof(checkpointSum)) == sizeof(checkpointSum));
4486
4487 if(!ok)
4488 return 0;
4489
4490 return 1;
4491 }
4492
4493 static int yaffs_ReadCheckpointSum(yaffs_Device *dev)
4494 {
4495 __u32 checkpointSum0;
4496 __u32 checkpointSum1;
4497 int ok;
4498
4499 yaffs_GetCheckpointSum(dev,&checkpointSum0);
4500
4501 ok = (yaffs_CheckpointRead(dev,&checkpointSum1,sizeof(checkpointSum1)) == sizeof(checkpointSum1));
4502
4503 if(!ok)
4504 return 0;
4505
4506 if(checkpointSum0 != checkpointSum1)
4507 return 0;
4508
4509 return 1;
4510 }
4511
4512
4513 static int yaffs_WriteCheckpointData(yaffs_Device *dev)
4514 {
4515
4516 int ok = 1;
4517
4518 if(dev->skipCheckpointWrite || !dev->isYaffs2){
4519 T(YAFFS_TRACE_CHECKPOINT,(TSTR("skipping checkpoint write" TENDSTR)));
4520 ok = 0;
4521 }
4522
4523 if(ok)
4524 ok = yaffs_CheckpointOpen(dev,1);
4525
4526 if(ok){
4527 T(YAFFS_TRACE_CHECKPOINT,(TSTR("write checkpoint validity" TENDSTR)));
4528 ok = yaffs_WriteCheckpointValidityMarker(dev,1);
4529 }
4530 if(ok){
4531 T(YAFFS_TRACE_CHECKPOINT,(TSTR("write checkpoint device" TENDSTR)));
4532 ok = yaffs_WriteCheckpointDevice(dev);
4533 }
4534 if(ok){
4535 T(YAFFS_TRACE_CHECKPOINT,(TSTR("write checkpoint objects" TENDSTR)));
4536 ok = yaffs_WriteCheckpointObjects(dev);
4537 }
4538 if(ok){
4539 T(YAFFS_TRACE_CHECKPOINT,(TSTR("write checkpoint validity" TENDSTR)));
4540 ok = yaffs_WriteCheckpointValidityMarker(dev,0);
4541 }
4542
4543 if(ok){
4544 ok = yaffs_WriteCheckpointSum(dev);
4545 }
4546
4547
4548 if(!yaffs_CheckpointClose(dev))
4549 ok = 0;
4550
4551 if(ok)
4552 dev->isCheckpointed = 1;
4553 else
4554 dev->isCheckpointed = 0;
4555
4556 return dev->isCheckpointed;
4557 }
4558
4559 static int yaffs_ReadCheckpointData(yaffs_Device *dev)
4560 {
4561 int ok = 1;
4562
4563 if(dev->skipCheckpointRead || !dev->isYaffs2){
4564 T(YAFFS_TRACE_CHECKPOINT,(TSTR("skipping checkpoint read" TENDSTR)));
4565 ok = 0;
4566 }
4567
4568 if(ok)
4569 ok = yaffs_CheckpointOpen(dev,0); /* open for read */
4570
4571 if(ok){
4572 T(YAFFS_TRACE_CHECKPOINT,(TSTR("read checkpoint validity" TENDSTR)));
4573 ok = yaffs_ReadCheckpointValidityMarker(dev,1);
4574 }
4575 if(ok){
4576 T(YAFFS_TRACE_CHECKPOINT,(TSTR("read checkpoint device" TENDSTR)));
4577 ok = yaffs_ReadCheckpointDevice(dev);
4578 }
4579 if(ok){
4580 T(YAFFS_TRACE_CHECKPOINT,(TSTR("read checkpoint objects" TENDSTR)));
4581 ok = yaffs_ReadCheckpointObjects(dev);
4582 }
4583 if(ok){
4584 T(YAFFS_TRACE_CHECKPOINT,(TSTR("read checkpoint validity" TENDSTR)));
4585 ok = yaffs_ReadCheckpointValidityMarker(dev,0);
4586 }
4587
4588 if(ok){
4589 ok = yaffs_ReadCheckpointSum(dev);
4590 T(YAFFS_TRACE_CHECKPOINT,(TSTR("read checkpoint checksum %d" TENDSTR),ok));
4591 }
4592
4593 if(!yaffs_CheckpointClose(dev))
4594 ok = 0;
4595
4596 if(ok)
4597 dev->isCheckpointed = 1;
4598 else
4599 dev->isCheckpointed = 0;
4600
4601 return ok ? 1 : 0;
4602
4603 }
4604
4605 static void yaffs_InvalidateCheckpoint(yaffs_Device *dev)
4606 {
4607 if(dev->isCheckpointed ||
4608 dev->blocksInCheckpoint > 0){
4609 dev->isCheckpointed = 0;
4610 yaffs_CheckpointInvalidateStream(dev);
4611 if(dev->superBlock && dev->markSuperBlockDirty)
4612 dev->markSuperBlockDirty(dev->superBlock);
4613 }
4614 }
4615
4616
4617 int yaffs_CheckpointSave(yaffs_Device *dev)
4618 {
4619
4620 T(YAFFS_TRACE_CHECKPOINT,(TSTR("save entry: isCheckpointed %d"TENDSTR),dev->isCheckpointed));
4621
4622 yaffs_VerifyObjects(dev);
4623 yaffs_VerifyBlocks(dev);
4624 yaffs_VerifyFreeChunks(dev);
4625
4626 if(!dev->isCheckpointed) {
4627 yaffs_InvalidateCheckpoint(dev);
4628 yaffs_WriteCheckpointData(dev);
4629 }
4630
4631 T(YAFFS_TRACE_ALWAYS,(TSTR("save exit: isCheckpointed %d"TENDSTR),dev->isCheckpointed));
4632
4633 return dev->isCheckpointed;
4634 }
4635
4636 int yaffs_CheckpointRestore(yaffs_Device *dev)
4637 {
4638 int retval;
4639 T(YAFFS_TRACE_CHECKPOINT,(TSTR("restore entry: isCheckpointed %d"TENDSTR),dev->isCheckpointed));
4640
4641 retval = yaffs_ReadCheckpointData(dev);
4642
4643 if(dev->isCheckpointed){
4644 yaffs_VerifyObjects(dev);
4645 yaffs_VerifyBlocks(dev);
4646 yaffs_VerifyFreeChunks(dev);
4647 }
4648
4649 T(YAFFS_TRACE_CHECKPOINT,(TSTR("restore exit: isCheckpointed %d"TENDSTR),dev->isCheckpointed));
4650
4651 return retval;
4652 }
4653
4654 /*--------------------- File read/write ------------------------
4655 * Read and write have very similar structures.
4656 * In general the read/write has three parts to it
4657 * An incomplete chunk to start with (if the read/write is not chunk-aligned)
4658 * Some complete chunks
4659 * An incomplete chunk to end off with
4660 *
4661 * Curve-balls: the first chunk might also be the last chunk.
4662 */
4663
4664 int yaffs_ReadDataFromFile(yaffs_Object * in, __u8 * buffer, loff_t offset,
4665 int nBytes)
4666 {
4667
4668 int chunk;
4669 __u32 start;
4670 int nToCopy;
4671 int n = nBytes;
4672 int nDone = 0;
4673 yaffs_ChunkCache *cache;
4674
4675 yaffs_Device *dev;
4676
4677 dev = in->myDev;
4678
4679 while (n > 0) {
4680 //chunk = offset / dev->nDataBytesPerChunk + 1;
4681 //start = offset % dev->nDataBytesPerChunk;
4682 yaffs_AddrToChunk(dev,offset,&chunk,&start);
4683 chunk++;
4684
4685 /* OK now check for the curveball where the start and end are in
4686 * the same chunk.
4687 */
4688 if ((start + n) < dev->nDataBytesPerChunk) {
4689 nToCopy = n;
4690 } else {
4691 nToCopy = dev->nDataBytesPerChunk - start;
4692 }
4693
4694 cache = yaffs_FindChunkCache(in, chunk);
4695
4696 /* If the chunk is already in the cache or it is less than a whole chunk
4697 * or we're using inband tags then use the cache (if there is caching)
4698 * else bypass the cache.
4699 */
4700 if (cache || nToCopy != dev->nDataBytesPerChunk || dev->inbandTags) {
4701 if (dev->nShortOpCaches > 0) {
4702
4703 /* If we can't find the data in the cache, then load it up. */
4704
4705 if (!cache) {
4706 cache = yaffs_GrabChunkCache(in->myDev);
4707 cache->object = in;
4708 cache->chunkId = chunk;
4709 cache->dirty = 0;
4710 cache->locked = 0;
4711 yaffs_ReadChunkDataFromObject(in, chunk,
4712 cache->
4713 data);
4714 cache->nBytes = 0;
4715 }
4716
4717 yaffs_UseChunkCache(dev, cache, 0);
4718
4719 cache->locked = 1;
4720
4721 #ifdef CONFIG_YAFFS_WINCE
4722 yfsd_UnlockYAFFS(TRUE);
4723 #endif
4724 memcpy(buffer, &cache->data[start], nToCopy);
4725
4726 #ifdef CONFIG_YAFFS_WINCE
4727 yfsd_LockYAFFS(TRUE);
4728 #endif
4729 cache->locked = 0;
4730 } else {
4731 /* Read into the local buffer then copy..*/
4732
4733 __u8 *localBuffer =
4734 yaffs_GetTempBuffer(dev, __LINE__);
4735 yaffs_ReadChunkDataFromObject(in, chunk,
4736 localBuffer);
4737 #ifdef CONFIG_YAFFS_WINCE
4738 yfsd_UnlockYAFFS(TRUE);
4739 #endif
4740 memcpy(buffer, &localBuffer[start], nToCopy);
4741
4742 #ifdef CONFIG_YAFFS_WINCE
4743 yfsd_LockYAFFS(TRUE);
4744 #endif
4745 yaffs_ReleaseTempBuffer(dev, localBuffer,
4746 __LINE__);
4747 }
4748
4749 } else {
4750 #ifdef CONFIG_YAFFS_WINCE
4751 __u8 *localBuffer = yaffs_GetTempBuffer(dev, __LINE__);
4752
4753 /* Under WinCE can't do direct transfer. Need to use a local buffer.
4754 * This is because we otherwise screw up WinCE's memory mapper
4755 */
4756 yaffs_ReadChunkDataFromObject(in, chunk, localBuffer);
4757
4758 #ifdef CONFIG_YAFFS_WINCE
4759 yfsd_UnlockYAFFS(TRUE);
4760 #endif
4761 memcpy(buffer, localBuffer, dev->nDataBytesPerChunk);
4762
4763 #ifdef CONFIG_YAFFS_WINCE
4764 yfsd_LockYAFFS(TRUE);
4765 yaffs_ReleaseTempBuffer(dev, localBuffer, __LINE__);
4766 #endif
4767
4768 #else
4769 /* A full chunk. Read directly into the supplied buffer. */
4770 yaffs_ReadChunkDataFromObject(in, chunk, buffer);
4771 #endif
4772 }
4773
4774 n -= nToCopy;
4775 offset += nToCopy;
4776 buffer += nToCopy;
4777 nDone += nToCopy;
4778
4779 }
4780
4781 return nDone;
4782 }
4783
4784 int yaffs_WriteDataToFile(yaffs_Object * in, const __u8 * buffer, loff_t offset,
4785 int nBytes, int writeThrough)
4786 {
4787
4788 int chunk;
4789 __u32 start;
4790 int nToCopy;
4791 int n = nBytes;
4792 int nDone = 0;
4793 int nToWriteBack;
4794 int startOfWrite = offset;
4795 int chunkWritten = 0;
4796 int nBytesRead;
4797
4798 yaffs_Device *dev;
4799
4800 dev = in->myDev;
4801
4802 while (n > 0 && chunkWritten >= 0) {
4803 //chunk = offset / dev->nDataBytesPerChunk + 1;
4804 //start = offset % dev->nDataBytesPerChunk;
4805 yaffs_AddrToChunk(dev,offset,&chunk,&start);
4806 chunk++;
4807
4808 /* OK now check for the curveball where the start and end are in
4809 * the same chunk.
4810 */
4811
4812 if ((start + n) < dev->nDataBytesPerChunk) {
4813 nToCopy = n;
4814
4815 /* Now folks, to calculate how many bytes to write back....
4816 * If we're overwriting and not writing to then end of file then
4817 * we need to write back as much as was there before.
4818 */
4819
4820 nBytesRead =
4821 in->variant.fileVariant.fileSize -
4822 ((chunk - 1) * dev->nDataBytesPerChunk);
4823
4824 if (nBytesRead > dev->nDataBytesPerChunk) {
4825 nBytesRead = dev->nDataBytesPerChunk;
4826 }
4827
4828 nToWriteBack =
4829 (nBytesRead >
4830 (start + n)) ? nBytesRead : (start + n);
4831
4832 } else {
4833 nToCopy = dev->nDataBytesPerChunk - start;
4834 nToWriteBack = dev->nDataBytesPerChunk;
4835 }
4836
4837 if (nToCopy != dev->nDataBytesPerChunk || dev->inbandTags) {
4838 /* An incomplete start or end chunk (or maybe both start and end chunk),
4839 * or we're using inband tags, so we want to use the cache buffers.
4840 */
4841 if (dev->nShortOpCaches > 0) {
4842 yaffs_ChunkCache *cache;
4843 /* If we can't find the data in the cache, then load the cache */
4844 cache = yaffs_FindChunkCache(in, chunk);
4845
4846 if (!cache
4847 && yaffs_CheckSpaceForAllocation(in->
4848 myDev)) {
4849 cache = yaffs_GrabChunkCache(in->myDev);
4850 cache->object = in;
4851 cache->chunkId = chunk;
4852 cache->dirty = 0;
4853 cache->locked = 0;
4854 yaffs_ReadChunkDataFromObject(in, chunk,
4855 cache->
4856 data);
4857 }
4858 else if(cache &&
4859 !cache->dirty &&
4860 !yaffs_CheckSpaceForAllocation(in->myDev)){
4861 /* Drop the cache if it was a read cache item and
4862 * no space check has been made for it.
4863 */
4864 cache = NULL;
4865 }
4866
4867 if (cache) {
4868 yaffs_UseChunkCache(dev, cache, 1);
4869 cache->locked = 1;
4870 #ifdef CONFIG_YAFFS_WINCE
4871 yfsd_UnlockYAFFS(TRUE);
4872 #endif
4873
4874 memcpy(&cache->data[start], buffer,
4875 nToCopy);
4876
4877 #ifdef CONFIG_YAFFS_WINCE
4878 yfsd_LockYAFFS(TRUE);
4879 #endif
4880 cache->locked = 0;
4881 cache->nBytes = nToWriteBack;
4882
4883 if (writeThrough) {
4884 chunkWritten =
4885 yaffs_WriteChunkDataToObject
4886 (cache->object,
4887 cache->chunkId,
4888 cache->data, cache->nBytes,
4889 1);
4890 cache->dirty = 0;
4891 }
4892
4893 } else {
4894 chunkWritten = -1; /* fail the write */
4895 }
4896 } else {
4897 /* An incomplete start or end chunk (or maybe both start and end chunk)
4898 * Read into the local buffer then copy, then copy over and write back.
4899 */
4900
4901 __u8 *localBuffer =
4902 yaffs_GetTempBuffer(dev, __LINE__);
4903
4904 yaffs_ReadChunkDataFromObject(in, chunk,
4905 localBuffer);
4906
4907 #ifdef CONFIG_YAFFS_WINCE
4908 yfsd_UnlockYAFFS(TRUE);
4909 #endif
4910
4911 memcpy(&localBuffer[start], buffer, nToCopy);
4912
4913 #ifdef CONFIG_YAFFS_WINCE
4914 yfsd_LockYAFFS(TRUE);
4915 #endif
4916 chunkWritten =
4917 yaffs_WriteChunkDataToObject(in, chunk,
4918 localBuffer,
4919 nToWriteBack,
4920 0);
4921
4922 yaffs_ReleaseTempBuffer(dev, localBuffer,
4923 __LINE__);
4924
4925 }
4926
4927 } else {
4928 /* A full chunk. Write directly from the supplied buffer. */
4929
4930 #ifdef CONFIG_YAFFS_WINCE
4931 /* Under WinCE can't do direct transfer. Need to use a local buffer.
4932 * This is because we otherwise screw up WinCE's memory mapper
4933 */
4934 __u8 *localBuffer = yaffs_GetTempBuffer(dev, __LINE__);
4935 #ifdef CONFIG_YAFFS_WINCE
4936 yfsd_UnlockYAFFS(TRUE);
4937 #endif
4938 memcpy(localBuffer, buffer, dev->nDataBytesPerChunk);
4939 #ifdef CONFIG_YAFFS_WINCE
4940 yfsd_LockYAFFS(TRUE);
4941 #endif
4942 chunkWritten =
4943 yaffs_WriteChunkDataToObject(in, chunk, localBuffer,
4944 dev->nDataBytesPerChunk,
4945 0);
4946 yaffs_ReleaseTempBuffer(dev, localBuffer, __LINE__);
4947 #else
4948
4949 chunkWritten =
4950 yaffs_WriteChunkDataToObject(in, chunk, buffer,
4951 dev->nDataBytesPerChunk,
4952 0);
4953 #endif
4954 /* Since we've overwritten the cached data, we better invalidate it. */
4955 yaffs_InvalidateChunkCache(in, chunk);
4956 }
4957
4958 if (chunkWritten >= 0) {
4959 n -= nToCopy;
4960 offset += nToCopy;
4961 buffer += nToCopy;
4962 nDone += nToCopy;
4963 }
4964
4965 }
4966
4967 /* Update file object */
4968
4969 if ((startOfWrite + nDone) > in->variant.fileVariant.fileSize) {
4970 in->variant.fileVariant.fileSize = (startOfWrite + nDone);
4971 }
4972
4973 in->dirty = 1;
4974
4975 return nDone;
4976 }
4977
4978
4979 /* ---------------------- File resizing stuff ------------------ */
4980
4981 static void yaffs_PruneResizedChunks(yaffs_Object * in, int newSize)
4982 {
4983
4984 yaffs_Device *dev = in->myDev;
4985 int oldFileSize = in->variant.fileVariant.fileSize;
4986
4987 int lastDel = 1 + (oldFileSize - 1) / dev->nDataBytesPerChunk;
4988
4989 int startDel = 1 + (newSize + dev->nDataBytesPerChunk - 1) /
4990 dev->nDataBytesPerChunk;
4991 int i;
4992 int chunkId;
4993
4994 /* Delete backwards so that we don't end up with holes if
4995 * power is lost part-way through the operation.
4996 */
4997 for (i = lastDel; i >= startDel; i--) {
4998 /* NB this could be optimised somewhat,
4999 * eg. could retrieve the tags and write them without
5000 * using yaffs_DeleteChunk
5001 */
5002
5003 chunkId = yaffs_FindAndDeleteChunkInFile(in, i, NULL);
5004 if (chunkId > 0) {
5005 if (chunkId <
5006 (dev->internalStartBlock * dev->nChunksPerBlock)
5007 || chunkId >=
5008 ((dev->internalEndBlock +
5009 1) * dev->nChunksPerBlock)) {
5010 T(YAFFS_TRACE_ALWAYS,
5011 (TSTR("Found daft chunkId %d for %d" TENDSTR),
5012 chunkId, i));
5013 } else {
5014 in->nDataChunks--;
5015 yaffs_DeleteChunk(dev, chunkId, 1, __LINE__);
5016 }
5017 }
5018 }
5019
5020 }
5021
5022 int yaffs_ResizeFile(yaffs_Object * in, loff_t newSize)
5023 {
5024
5025 int oldFileSize = in->variant.fileVariant.fileSize;
5026 __u32 newSizeOfPartialChunk;
5027 int newFullChunks;
5028
5029 yaffs_Device *dev = in->myDev;
5030
5031 yaffs_AddrToChunk(dev, newSize, &newFullChunks, &newSizeOfPartialChunk);
5032
5033 yaffs_FlushFilesChunkCache(in);
5034 yaffs_InvalidateWholeChunkCache(in);
5035
5036 yaffs_CheckGarbageCollection(dev);
5037
5038 if (in->variantType != YAFFS_OBJECT_TYPE_FILE) {
5039 return YAFFS_FAIL;
5040 }
5041
5042 if (newSize == oldFileSize) {
5043 return YAFFS_OK;
5044 }
5045
5046 if (newSize < oldFileSize) {
5047
5048 yaffs_PruneResizedChunks(in, newSize);
5049
5050 if (newSizeOfPartialChunk != 0) {
5051 int lastChunk = 1 + newFullChunks;
5052
5053 __u8 *localBuffer = yaffs_GetTempBuffer(dev, __LINE__);
5054
5055 /* Got to read and rewrite the last chunk with its new size and zero pad */
5056 yaffs_ReadChunkDataFromObject(in, lastChunk,
5057 localBuffer);
5058
5059 memset(localBuffer + newSizeOfPartialChunk, 0,
5060 dev->nDataBytesPerChunk - newSizeOfPartialChunk);
5061
5062 yaffs_WriteChunkDataToObject(in, lastChunk, localBuffer,
5063 newSizeOfPartialChunk, 1);
5064
5065 yaffs_ReleaseTempBuffer(dev, localBuffer, __LINE__);
5066 }
5067
5068 in->variant.fileVariant.fileSize = newSize;
5069
5070 yaffs_PruneFileStructure(dev, &in->variant.fileVariant);
5071 } else {
5072 /* newsSize > oldFileSize */
5073 in->variant.fileVariant.fileSize = newSize;
5074 }
5075
5076
5077
5078 /* Write a new object header.
5079 * show we've shrunk the file, if need be
5080 * Do this only if the file is not in the deleted directories.
5081 */
5082 if (in->parent->objectId != YAFFS_OBJECTID_UNLINKED &&
5083 in->parent->objectId != YAFFS_OBJECTID_DELETED) {
5084 yaffs_UpdateObjectHeader(in, NULL, 0,
5085 (newSize < oldFileSize) ? 1 : 0, 0);
5086 }
5087
5088 return YAFFS_OK;
5089 }
5090
5091 loff_t yaffs_GetFileSize(yaffs_Object * obj)
5092 {
5093 obj = yaffs_GetEquivalentObject(obj);
5094
5095 switch (obj->variantType) {
5096 case YAFFS_OBJECT_TYPE_FILE:
5097 return obj->variant.fileVariant.fileSize;
5098 case YAFFS_OBJECT_TYPE_SYMLINK:
5099 return yaffs_strlen(obj->variant.symLinkVariant.alias);
5100 default:
5101 return 0;
5102 }
5103 }
5104
5105
5106
5107 int yaffs_FlushFile(yaffs_Object * in, int updateTime)
5108 {
5109 int retVal;
5110 if (in->dirty) {
5111 yaffs_FlushFilesChunkCache(in);
5112 if (updateTime) {
5113 #ifdef CONFIG_YAFFS_WINCE
5114 yfsd_WinFileTimeNow(in->win_mtime);
5115 #else
5116
5117 in->yst_mtime = Y_CURRENT_TIME;
5118
5119 #endif
5120 }
5121
5122 retVal =
5123 (yaffs_UpdateObjectHeader(in, NULL, 0, 0, 0) >=
5124 0) ? YAFFS_OK : YAFFS_FAIL;
5125 } else {
5126 retVal = YAFFS_OK;
5127 }
5128
5129 return retVal;
5130
5131 }
5132
5133 static int yaffs_DoGenericObjectDeletion(yaffs_Object * in)
5134 {
5135
5136 /* First off, invalidate the file's data in the cache, without flushing. */
5137 yaffs_InvalidateWholeChunkCache(in);
5138
5139 if (in->myDev->isYaffs2 && (in->parent != in->myDev->deletedDir)) {
5140 /* Move to the unlinked directory so we have a record that it was deleted. */
5141 yaffs_ChangeObjectName(in, in->myDev->deletedDir,_Y("deleted"), 0, 0);
5142
5143 }
5144
5145 yaffs_RemoveObjectFromDirectory(in);
5146 yaffs_DeleteChunk(in->myDev, in->chunkId, 1, __LINE__);
5147 in->chunkId = -1;
5148
5149 yaffs_FreeObject(in);
5150 return YAFFS_OK;
5151
5152 }
5153
5154 /* yaffs_DeleteFile deletes the whole file data
5155 * and the inode associated with the file.
5156 * It does not delete the links associated with the file.
5157 */
5158 static int yaffs_UnlinkFile(yaffs_Object * in)
5159 {
5160
5161 int retVal;
5162 int immediateDeletion = 0;
5163
5164 if (1) {
5165 #ifdef __KERNEL__
5166 if (!in->myInode) {
5167 immediateDeletion = 1;
5168
5169 }
5170 #else
5171 if (in->inUse <= 0) {
5172 immediateDeletion = 1;
5173
5174 }
5175 #endif
5176 if (immediateDeletion) {
5177 retVal =
5178 yaffs_ChangeObjectName(in, in->myDev->deletedDir,
5179 _Y("deleted"), 0, 0);
5180 T(YAFFS_TRACE_TRACING,
5181 (TSTR("yaffs: immediate deletion of file %d" TENDSTR),
5182 in->objectId));
5183 in->deleted = 1;
5184 in->myDev->nDeletedFiles++;
5185 if (0 && in->myDev->isYaffs2) {
5186 yaffs_ResizeFile(in, 0);
5187 }
5188 yaffs_SoftDeleteFile(in);
5189 } else {
5190 retVal =
5191 yaffs_ChangeObjectName(in, in->myDev->unlinkedDir,
5192 _Y("unlinked"), 0, 0);
5193 }
5194
5195 }
5196 return retVal;
5197 }
5198
5199 int yaffs_DeleteFile(yaffs_Object * in)
5200 {
5201 int retVal = YAFFS_OK;
5202
5203 if (in->nDataChunks > 0) {
5204 /* Use soft deletion if there is data in the file */
5205 if (!in->unlinked) {
5206 retVal = yaffs_UnlinkFile(in);
5207 }
5208 if (retVal == YAFFS_OK && in->unlinked && !in->deleted) {
5209 in->deleted = 1;
5210 in->myDev->nDeletedFiles++;
5211 yaffs_SoftDeleteFile(in);
5212 }
5213 return in->deleted ? YAFFS_OK : YAFFS_FAIL;
5214 } else {
5215 /* The file has no data chunks so we toss it immediately */
5216 yaffs_FreeTnode(in->myDev, in->variant.fileVariant.top);
5217 in->variant.fileVariant.top = NULL;
5218 yaffs_DoGenericObjectDeletion(in);
5219
5220 return YAFFS_OK;
5221 }
5222 }
5223
5224 static int yaffs_DeleteDirectory(yaffs_Object * in)
5225 {
5226 /* First check that the directory is empty. */
5227 if (ylist_empty(&in->variant.directoryVariant.children)) {
5228 return yaffs_DoGenericObjectDeletion(in);
5229 }
5230
5231 return YAFFS_FAIL;
5232
5233 }
5234
5235 static int yaffs_DeleteSymLink(yaffs_Object * in)
5236 {
5237 YFREE(in->variant.symLinkVariant.alias);
5238
5239 return yaffs_DoGenericObjectDeletion(in);
5240 }
5241
5242 static int yaffs_DeleteHardLink(yaffs_Object * in)
5243 {
5244 /* remove this hardlink from the list assocaited with the equivalent
5245 * object
5246 */
5247 ylist_del(&in->hardLinks);
5248 return yaffs_DoGenericObjectDeletion(in);
5249 }
5250
5251 static void yaffs_DestroyObject(yaffs_Object * obj)
5252 {
5253 switch (obj->variantType) {
5254 case YAFFS_OBJECT_TYPE_FILE:
5255 yaffs_DeleteFile(obj);
5256 break;
5257 case YAFFS_OBJECT_TYPE_DIRECTORY:
5258 yaffs_DeleteDirectory(obj);
5259 break;
5260 case YAFFS_OBJECT_TYPE_SYMLINK:
5261 yaffs_DeleteSymLink(obj);
5262 break;
5263 case YAFFS_OBJECT_TYPE_HARDLINK:
5264 yaffs_DeleteHardLink(obj);
5265 break;
5266 case YAFFS_OBJECT_TYPE_SPECIAL:
5267 yaffs_DoGenericObjectDeletion(obj);
5268 break;
5269 case YAFFS_OBJECT_TYPE_UNKNOWN:
5270 break; /* should not happen. */
5271 }
5272 }
5273
5274 static int yaffs_UnlinkWorker(yaffs_Object * obj)
5275 {
5276
5277 if (obj->variantType == YAFFS_OBJECT_TYPE_HARDLINK) {
5278 return yaffs_DeleteHardLink(obj);
5279 } else if (!ylist_empty(&obj->hardLinks)) {
5280 /* Curve ball: We're unlinking an object that has a hardlink.
5281 *
5282 * This problem arises because we are not strictly following
5283 * The Linux link/inode model.
5284 *
5285 * We can't really delete the object.
5286 * Instead, we do the following:
5287 * - Select a hardlink.
5288 * - Unhook it from the hard links
5289 * - Unhook it from its parent directory (so that the rename can work)
5290 * - Rename the object to the hardlink's name.
5291 * - Delete the hardlink
5292 */
5293
5294 yaffs_Object *hl;
5295 int retVal;
5296 YCHAR name[YAFFS_MAX_NAME_LENGTH + 1];
5297
5298 hl = ylist_entry(obj->hardLinks.next, yaffs_Object, hardLinks);
5299
5300 ylist_del_init(&hl->hardLinks);
5301 ylist_del_init(&hl->siblings);
5302
5303 yaffs_GetObjectName(hl, name, YAFFS_MAX_NAME_LENGTH + 1);
5304
5305 retVal = yaffs_ChangeObjectName(obj, hl->parent, name, 0, 0);
5306
5307 if (retVal == YAFFS_OK) {
5308 retVal = yaffs_DoGenericObjectDeletion(hl);
5309 }
5310 return retVal;
5311
5312 } else {
5313 switch (obj->variantType) {
5314 case YAFFS_OBJECT_TYPE_FILE:
5315 return yaffs_UnlinkFile(obj);
5316 break;
5317 case YAFFS_OBJECT_TYPE_DIRECTORY:
5318 return yaffs_DeleteDirectory(obj);
5319 break;
5320 case YAFFS_OBJECT_TYPE_SYMLINK:
5321 return yaffs_DeleteSymLink(obj);
5322 break;
5323 case YAFFS_OBJECT_TYPE_SPECIAL:
5324 return yaffs_DoGenericObjectDeletion(obj);
5325 break;
5326 case YAFFS_OBJECT_TYPE_HARDLINK:
5327 case YAFFS_OBJECT_TYPE_UNKNOWN:
5328 default:
5329 return YAFFS_FAIL;
5330 }
5331 }
5332 }
5333
5334
5335 static int yaffs_UnlinkObject( yaffs_Object *obj)
5336 {
5337
5338 if (obj && obj->unlinkAllowed) {
5339 return yaffs_UnlinkWorker(obj);
5340 }
5341
5342 return YAFFS_FAIL;
5343
5344 }
5345 int yaffs_Unlink(yaffs_Object * dir, const YCHAR * name)
5346 {
5347 yaffs_Object *obj;
5348
5349 obj = yaffs_FindObjectByName(dir, name);
5350 return yaffs_UnlinkObject(obj);
5351 }
5352
5353 /*----------------------- Initialisation Scanning ---------------------- */
5354
5355 static void yaffs_HandleShadowedObject(yaffs_Device * dev, int objId,
5356 int backwardScanning)
5357 {
5358 yaffs_Object *obj;
5359
5360 if (!backwardScanning) {
5361 /* Handle YAFFS1 forward scanning case
5362 * For YAFFS1 we always do the deletion
5363 */
5364
5365 } else {
5366 /* Handle YAFFS2 case (backward scanning)
5367 * If the shadowed object exists then ignore.
5368 */
5369 if (yaffs_FindObjectByNumber(dev, objId)) {
5370 return;
5371 }
5372 }
5373
5374 /* Let's create it (if it does not exist) assuming it is a file so that it can do shrinking etc.
5375 * We put it in unlinked dir to be cleaned up after the scanning
5376 */
5377 obj =
5378 yaffs_FindOrCreateObjectByNumber(dev, objId,
5379 YAFFS_OBJECT_TYPE_FILE);
5380 yaffs_AddObjectToDirectory(dev->unlinkedDir, obj);
5381 obj->variant.fileVariant.shrinkSize = 0;
5382 obj->valid = 1; /* So that we don't read any other info for this file */
5383
5384 }
5385
5386 typedef struct {
5387 int seq;
5388 int block;
5389 } yaffs_BlockIndex;
5390
5391
5392 static void yaffs_HardlinkFixup(yaffs_Device *dev, yaffs_Object *hardList)
5393 {
5394 yaffs_Object *hl;
5395 yaffs_Object *in;
5396
5397 while (hardList) {
5398 hl = hardList;
5399 hardList = (yaffs_Object *) (hardList->hardLinks.next);
5400
5401 in = yaffs_FindObjectByNumber(dev,
5402 hl->variant.hardLinkVariant.
5403 equivalentObjectId);
5404
5405 if (in) {
5406 /* Add the hardlink pointers */
5407 hl->variant.hardLinkVariant.equivalentObject = in;
5408 ylist_add(&hl->hardLinks, &in->hardLinks);
5409 } else {
5410 /* Todo Need to report/handle this better.
5411 * Got a problem... hardlink to a non-existant object
5412 */
5413 hl->variant.hardLinkVariant.equivalentObject = NULL;
5414 YINIT_LIST_HEAD(&hl->hardLinks);
5415
5416 }
5417
5418 }
5419
5420 }
5421
5422
5423
5424
5425
5426 static int ybicmp(const void *a, const void *b){
5427 register int aseq = ((yaffs_BlockIndex *)a)->seq;
5428 register int bseq = ((yaffs_BlockIndex *)b)->seq;
5429 register int ablock = ((yaffs_BlockIndex *)a)->block;
5430 register int bblock = ((yaffs_BlockIndex *)b)->block;
5431 if( aseq == bseq )
5432 return ablock - bblock;
5433 else
5434 return aseq - bseq;
5435
5436 }
5437
5438 static int yaffs_Scan(yaffs_Device * dev)
5439 {
5440 yaffs_ExtendedTags tags;
5441 int blk;
5442 int blockIterator;
5443 int startIterator;
5444 int endIterator;
5445 int nBlocksToScan = 0;
5446 int result;
5447
5448 int chunk;
5449 int c;
5450 int deleted;
5451 yaffs_BlockState state;
5452 yaffs_Object *hardList = NULL;
5453 yaffs_BlockInfo *bi;
5454 __u32 sequenceNumber;
5455 yaffs_ObjectHeader *oh;
5456 yaffs_Object *in;
5457 yaffs_Object *parent;
5458 int nBlocks = dev->internalEndBlock - dev->internalStartBlock + 1;
5459
5460 int alloc_failed = 0;
5461
5462
5463 __u8 *chunkData;
5464
5465 yaffs_BlockIndex *blockIndex = NULL;
5466
5467 if (dev->isYaffs2) {
5468 T(YAFFS_TRACE_SCAN,
5469 (TSTR("yaffs_Scan is not for YAFFS2!" TENDSTR)));
5470 return YAFFS_FAIL;
5471 }
5472
5473 //TODO Throw all the yaffs2 stuuf out of yaffs_Scan since it is only for yaffs1 format.
5474
5475 T(YAFFS_TRACE_SCAN,
5476 (TSTR("yaffs_Scan starts intstartblk %d intendblk %d..." TENDSTR),
5477 dev->internalStartBlock, dev->internalEndBlock));
5478
5479 chunkData = yaffs_GetTempBuffer(dev, __LINE__);
5480
5481 dev->sequenceNumber = YAFFS_LOWEST_SEQUENCE_NUMBER;
5482
5483 if (dev->isYaffs2) {
5484 blockIndex = YMALLOC(nBlocks * sizeof(yaffs_BlockIndex));
5485 if(!blockIndex)
5486 return YAFFS_FAIL;
5487 }
5488
5489 /* Scan all the blocks to determine their state */
5490 for (blk = dev->internalStartBlock; blk <= dev->internalEndBlock; blk++) {
5491 bi = yaffs_GetBlockInfo(dev, blk);
5492 yaffs_ClearChunkBits(dev, blk);
5493 bi->pagesInUse = 0;
5494 bi->softDeletions = 0;
5495
5496 yaffs_QueryInitialBlockState(dev, blk, &state, &sequenceNumber);
5497
5498 bi->blockState = state;
5499 bi->sequenceNumber = sequenceNumber;
5500
5501 T(YAFFS_TRACE_SCAN_DEBUG,
5502 (TSTR("Block scanning block %d state %d seq %d" TENDSTR), blk,
5503 state, sequenceNumber));
5504
5505 if (state == YAFFS_BLOCK_STATE_DEAD) {
5506 T(YAFFS_TRACE_BAD_BLOCKS,
5507 (TSTR("block %d is bad" TENDSTR), blk));
5508 } else if (state == YAFFS_BLOCK_STATE_EMPTY) {
5509 T(YAFFS_TRACE_SCAN_DEBUG,
5510 (TSTR("Block empty " TENDSTR)));
5511 dev->nErasedBlocks++;
5512 dev->nFreeChunks += dev->nChunksPerBlock;
5513 } else if (state == YAFFS_BLOCK_STATE_NEEDS_SCANNING) {
5514
5515 /* Determine the highest sequence number */
5516 if (dev->isYaffs2 &&
5517 sequenceNumber >= YAFFS_LOWEST_SEQUENCE_NUMBER &&
5518 sequenceNumber < YAFFS_HIGHEST_SEQUENCE_NUMBER) {
5519
5520 blockIndex[nBlocksToScan].seq = sequenceNumber;
5521 blockIndex[nBlocksToScan].block = blk;
5522
5523 nBlocksToScan++;
5524
5525 if (sequenceNumber >= dev->sequenceNumber) {
5526 dev->sequenceNumber = sequenceNumber;
5527 }
5528 } else if (dev->isYaffs2) {
5529 /* TODO: Nasty sequence number! */
5530 T(YAFFS_TRACE_SCAN,
5531 (TSTR
5532 ("Block scanning block %d has bad sequence number %d"
5533 TENDSTR), blk, sequenceNumber));
5534
5535 }
5536 }
5537 }
5538
5539 /* Sort the blocks
5540 * Dungy old bubble sort for now...
5541 */
5542 if (dev->isYaffs2) {
5543 yaffs_BlockIndex temp;
5544 int i;
5545 int j;
5546
5547 for (i = 0; i < nBlocksToScan; i++)
5548 for (j = i + 1; j < nBlocksToScan; j++)
5549 if (blockIndex[i].seq > blockIndex[j].seq) {
5550 temp = blockIndex[j];
5551 blockIndex[j] = blockIndex[i];
5552 blockIndex[i] = temp;
5553 }
5554 }
5555
5556 /* Now scan the blocks looking at the data. */
5557 if (dev->isYaffs2) {
5558 startIterator = 0;
5559 endIterator = nBlocksToScan - 1;
5560 T(YAFFS_TRACE_SCAN_DEBUG,
5561 (TSTR("%d blocks to be scanned" TENDSTR), nBlocksToScan));
5562 } else {
5563 startIterator = dev->internalStartBlock;
5564 endIterator = dev->internalEndBlock;
5565 }
5566
5567 /* For each block.... */
5568 for (blockIterator = startIterator; !alloc_failed && blockIterator <= endIterator;
5569 blockIterator++) {
5570
5571 YYIELD();
5572
5573 if (dev->isYaffs2) {
5574 /* get the block to scan in the correct order */
5575 blk = blockIndex[blockIterator].block;
5576 } else {
5577 blk = blockIterator;
5578 }
5579
5580 bi = yaffs_GetBlockInfo(dev, blk);
5581 state = bi->blockState;
5582
5583 deleted = 0;
5584
5585 /* For each chunk in each block that needs scanning....*/
5586 for (c = 0; !alloc_failed && c < dev->nChunksPerBlock &&
5587 state == YAFFS_BLOCK_STATE_NEEDS_SCANNING; c++) {
5588 /* Read the tags and decide what to do */
5589 chunk = blk * dev->nChunksPerBlock + c;
5590
5591 result = yaffs_ReadChunkWithTagsFromNAND(dev, chunk, NULL,
5592 &tags);
5593
5594 /* Let's have a good look at this chunk... */
5595
5596 if (!dev->isYaffs2 && tags.chunkDeleted) {
5597 /* YAFFS1 only...
5598 * A deleted chunk
5599 */
5600 deleted++;
5601 dev->nFreeChunks++;
5602 /*T((" %d %d deleted\n",blk,c)); */
5603 } else if (!tags.chunkUsed) {
5604 /* An unassigned chunk in the block
5605 * This means that either the block is empty or
5606 * this is the one being allocated from
5607 */
5608
5609 if (c == 0) {
5610 /* We're looking at the first chunk in the block so the block is unused */
5611 state = YAFFS_BLOCK_STATE_EMPTY;
5612 dev->nErasedBlocks++;
5613 } else {
5614 /* this is the block being allocated from */
5615 T(YAFFS_TRACE_SCAN,
5616 (TSTR
5617 (" Allocating from %d %d" TENDSTR),
5618 blk, c));
5619 state = YAFFS_BLOCK_STATE_ALLOCATING;
5620 dev->allocationBlock = blk;
5621 dev->allocationPage = c;
5622 dev->allocationBlockFinder = blk;
5623 /* Set it to here to encourage the allocator to go forth from here. */
5624
5625 /* Yaffs2 sanity check:
5626 * This should be the one with the highest sequence number
5627 */
5628 if (dev->isYaffs2
5629 && (dev->sequenceNumber !=
5630 bi->sequenceNumber)) {
5631 T(YAFFS_TRACE_ALWAYS,
5632 (TSTR
5633 ("yaffs: Allocation block %d was not highest sequence id: block seq = %d, dev seq = %d"
5634 TENDSTR), blk,bi->sequenceNumber,dev->sequenceNumber));
5635 }
5636 }
5637
5638 dev->nFreeChunks += (dev->nChunksPerBlock - c);
5639 } else if (tags.chunkId > 0) {
5640 /* chunkId > 0 so it is a data chunk... */
5641 unsigned int endpos;
5642
5643 yaffs_SetChunkBit(dev, blk, c);
5644 bi->pagesInUse++;
5645
5646 in = yaffs_FindOrCreateObjectByNumber(dev,
5647 tags.
5648 objectId,
5649 YAFFS_OBJECT_TYPE_FILE);
5650 /* PutChunkIntoFile checks for a clash (two data chunks with
5651 * the same chunkId).
5652 */
5653
5654 if(!in)
5655 alloc_failed = 1;
5656
5657 if(in){
5658 if(!yaffs_PutChunkIntoFile(in, tags.chunkId, chunk,1))
5659 alloc_failed = 1;
5660 }
5661
5662 endpos =
5663 (tags.chunkId - 1) * dev->nDataBytesPerChunk +
5664 tags.byteCount;
5665 if (in &&
5666 in->variantType == YAFFS_OBJECT_TYPE_FILE
5667 && in->variant.fileVariant.scannedFileSize <
5668 endpos) {
5669 in->variant.fileVariant.
5670 scannedFileSize = endpos;
5671 if (!dev->useHeaderFileSize) {
5672 in->variant.fileVariant.
5673 fileSize =
5674 in->variant.fileVariant.
5675 scannedFileSize;
5676 }
5677
5678 }
5679 /* T((" %d %d data %d %d\n",blk,c,tags.objectId,tags.chunkId)); */
5680 } else {
5681 /* chunkId == 0, so it is an ObjectHeader.
5682 * Thus, we read in the object header and make the object
5683 */
5684 yaffs_SetChunkBit(dev, blk, c);
5685 bi->pagesInUse++;
5686
5687 result = yaffs_ReadChunkWithTagsFromNAND(dev, chunk,
5688 chunkData,
5689 NULL);
5690
5691 oh = (yaffs_ObjectHeader *) chunkData;
5692
5693 in = yaffs_FindObjectByNumber(dev,
5694 tags.objectId);
5695 if (in && in->variantType != oh->type) {
5696 /* This should not happen, but somehow
5697 * Wev'e ended up with an objectId that has been reused but not yet
5698 * deleted, and worse still it has changed type. Delete the old object.
5699 */
5700
5701 yaffs_DestroyObject(in);
5702
5703 in = 0;
5704 }
5705
5706 in = yaffs_FindOrCreateObjectByNumber(dev,
5707 tags.
5708 objectId,
5709 oh->type);
5710
5711 if(!in)
5712 alloc_failed = 1;
5713
5714 if (in && oh->shadowsObject > 0) {
5715 yaffs_HandleShadowedObject(dev,
5716 oh->
5717 shadowsObject,
5718 0);
5719 }
5720
5721 if (in && in->valid) {
5722 /* We have already filled this one. We have a duplicate and need to resolve it. */
5723
5724 unsigned existingSerial = in->serial;
5725 unsigned newSerial = tags.serialNumber;
5726
5727 if (dev->isYaffs2 ||
5728 ((existingSerial + 1) & 3) ==
5729 newSerial) {
5730 /* Use new one - destroy the exisiting one */
5731 yaffs_DeleteChunk(dev,
5732 in->chunkId,
5733 1, __LINE__);
5734 in->valid = 0;
5735 } else {
5736 /* Use existing - destroy this one. */
5737 yaffs_DeleteChunk(dev, chunk, 1,
5738 __LINE__);
5739 }
5740 }
5741
5742 if (in && !in->valid &&
5743 (tags.objectId == YAFFS_OBJECTID_ROOT ||
5744 tags.objectId == YAFFS_OBJECTID_LOSTNFOUND)) {
5745 /* We only load some info, don't fiddle with directory structure */
5746 in->valid = 1;
5747 in->variantType = oh->type;
5748
5749 in->yst_mode = oh->yst_mode;
5750 #ifdef CONFIG_YAFFS_WINCE
5751 in->win_atime[0] = oh->win_atime[0];
5752 in->win_ctime[0] = oh->win_ctime[0];
5753 in->win_mtime[0] = oh->win_mtime[0];
5754 in->win_atime[1] = oh->win_atime[1];
5755 in->win_ctime[1] = oh->win_ctime[1];
5756 in->win_mtime[1] = oh->win_mtime[1];
5757 #else
5758 in->yst_uid = oh->yst_uid;
5759 in->yst_gid = oh->yst_gid;
5760 in->yst_atime = oh->yst_atime;
5761 in->yst_mtime = oh->yst_mtime;
5762 in->yst_ctime = oh->yst_ctime;
5763 in->yst_rdev = oh->yst_rdev;
5764 #endif
5765 in->chunkId = chunk;
5766
5767 } else if (in && !in->valid) {
5768 /* we need to load this info */
5769
5770 in->valid = 1;
5771 in->variantType = oh->type;
5772
5773 in->yst_mode = oh->yst_mode;
5774 #ifdef CONFIG_YAFFS_WINCE
5775 in->win_atime[0] = oh->win_atime[0];
5776 in->win_ctime[0] = oh->win_ctime[0];
5777 in->win_mtime[0] = oh->win_mtime[0];
5778 in->win_atime[1] = oh->win_atime[1];
5779 in->win_ctime[1] = oh->win_ctime[1];
5780 in->win_mtime[1] = oh->win_mtime[1];
5781 #else
5782 in->yst_uid = oh->yst_uid;
5783 in->yst_gid = oh->yst_gid;
5784 in->yst_atime = oh->yst_atime;
5785 in->yst_mtime = oh->yst_mtime;
5786 in->yst_ctime = oh->yst_ctime;
5787 in->yst_rdev = oh->yst_rdev;
5788 #endif
5789 in->chunkId = chunk;
5790
5791 yaffs_SetObjectName(in, oh->name);
5792 in->dirty = 0;
5793
5794 /* directory stuff...
5795 * hook up to parent
5796 */
5797
5798 parent =
5799 yaffs_FindOrCreateObjectByNumber
5800 (dev, oh->parentObjectId,
5801 YAFFS_OBJECT_TYPE_DIRECTORY);
5802 if (parent->variantType ==
5803 YAFFS_OBJECT_TYPE_UNKNOWN) {
5804 /* Set up as a directory */
5805 parent->variantType =
5806 YAFFS_OBJECT_TYPE_DIRECTORY;
5807 YINIT_LIST_HEAD(&parent->variant.
5808 directoryVariant.
5809 children);
5810 } else if (parent->variantType !=
5811 YAFFS_OBJECT_TYPE_DIRECTORY)
5812 {
5813 /* Hoosterman, another problem....
5814 * We're trying to use a non-directory as a directory
5815 */
5816
5817 T(YAFFS_TRACE_ERROR,
5818 (TSTR
5819 ("yaffs tragedy: attempting to use non-directory as a directory in scan. Put in lost+found."
5820 TENDSTR)));
5821 parent = dev->lostNFoundDir;
5822 }
5823
5824 yaffs_AddObjectToDirectory(parent, in);
5825
5826 if (0 && (parent == dev->deletedDir ||
5827 parent == dev->unlinkedDir)) {
5828 in->deleted = 1; /* If it is unlinked at start up then it wants deleting */
5829 dev->nDeletedFiles++;
5830 }
5831 /* Note re hardlinks.
5832 * Since we might scan a hardlink before its equivalent object is scanned
5833 * we put them all in a list.
5834 * After scanning is complete, we should have all the objects, so we run through this
5835 * list and fix up all the chains.
5836 */
5837
5838 switch (in->variantType) {
5839 case YAFFS_OBJECT_TYPE_UNKNOWN:
5840 /* Todo got a problem */
5841 break;
5842 case YAFFS_OBJECT_TYPE_FILE:
5843 if (dev->isYaffs2
5844 && oh->isShrink) {
5845 /* Prune back the shrunken chunks */
5846 yaffs_PruneResizedChunks
5847 (in, oh->fileSize);
5848 /* Mark the block as having a shrinkHeader */
5849 bi->hasShrinkHeader = 1;
5850 }
5851
5852 if (dev->useHeaderFileSize)
5853
5854 in->variant.fileVariant.
5855 fileSize =
5856 oh->fileSize;
5857
5858 break;
5859 case YAFFS_OBJECT_TYPE_HARDLINK:
5860 in->variant.hardLinkVariant.
5861 equivalentObjectId =
5862 oh->equivalentObjectId;
5863 in->hardLinks.next =
5864 (struct ylist_head *)
5865 hardList;
5866 hardList = in;
5867 break;
5868 case YAFFS_OBJECT_TYPE_DIRECTORY:
5869 /* Do nothing */
5870 break;
5871 case YAFFS_OBJECT_TYPE_SPECIAL:
5872 /* Do nothing */
5873 break;
5874 case YAFFS_OBJECT_TYPE_SYMLINK:
5875 in->variant.symLinkVariant.alias =
5876 yaffs_CloneString(oh->alias);
5877 if(!in->variant.symLinkVariant.alias)
5878 alloc_failed = 1;
5879 break;
5880 }
5881
5882 if (parent == dev->deletedDir) {
5883 yaffs_DestroyObject(in);
5884 bi->hasShrinkHeader = 1;
5885 }
5886 }
5887 }
5888 }
5889
5890 if (state == YAFFS_BLOCK_STATE_NEEDS_SCANNING) {
5891 /* If we got this far while scanning, then the block is fully allocated.*/
5892 state = YAFFS_BLOCK_STATE_FULL;
5893 }
5894
5895 bi->blockState = state;
5896
5897 /* Now let's see if it was dirty */
5898 if (bi->pagesInUse == 0 &&
5899 !bi->hasShrinkHeader &&
5900 bi->blockState == YAFFS_BLOCK_STATE_FULL) {
5901 yaffs_BlockBecameDirty(dev, blk);
5902 }
5903
5904 }
5905
5906 if (blockIndex) {
5907 YFREE(blockIndex);
5908 }
5909
5910
5911 /* Ok, we've done all the scanning.
5912 * Fix up the hard link chains.
5913 * We should now have scanned all the objects, now it's time to add these
5914 * hardlinks.
5915 */
5916
5917 yaffs_HardlinkFixup(dev,hardList);
5918
5919 /* Handle the unlinked files. Since they were left in an unlinked state we should
5920 * just delete them.
5921 */
5922 {
5923 struct ylist_head *i;
5924 struct ylist_head *n;
5925
5926 yaffs_Object *l;
5927 /* Soft delete all the unlinked files */
5928 ylist_for_each_safe(i, n,
5929 &dev->unlinkedDir->variant.directoryVariant.
5930 children) {
5931 if (i) {
5932 l = ylist_entry(i, yaffs_Object, siblings);
5933 yaffs_DestroyObject(l);
5934 }
5935 }
5936 }
5937
5938 yaffs_ReleaseTempBuffer(dev, chunkData, __LINE__);
5939
5940 if(alloc_failed){
5941 return YAFFS_FAIL;
5942 }
5943
5944 T(YAFFS_TRACE_SCAN, (TSTR("yaffs_Scan ends" TENDSTR)));
5945
5946
5947 return YAFFS_OK;
5948 }
5949
5950 static void yaffs_CheckObjectDetailsLoaded(yaffs_Object *in)
5951 {
5952 __u8 *chunkData;
5953 yaffs_ObjectHeader *oh;
5954 yaffs_Device *dev = in->myDev;
5955 yaffs_ExtendedTags tags;
5956 int result;
5957 int alloc_failed = 0;
5958
5959 if(!in)
5960 return;
5961
5962 #if 0
5963 T(YAFFS_TRACE_SCAN,(TSTR("details for object %d %s loaded" TENDSTR),
5964 in->objectId,
5965 in->lazyLoaded ? "not yet" : "already"));
5966 #endif
5967
5968 if(in->lazyLoaded){
5969 in->lazyLoaded = 0;
5970 chunkData = yaffs_GetTempBuffer(dev, __LINE__);
5971
5972 result = yaffs_ReadChunkWithTagsFromNAND(dev,in->chunkId,chunkData,&tags);
5973 oh = (yaffs_ObjectHeader *) chunkData;
5974
5975 in->yst_mode = oh->yst_mode;
5976 #ifdef CONFIG_YAFFS_WINCE
5977 in->win_atime[0] = oh->win_atime[0];
5978 in->win_ctime[0] = oh->win_ctime[0];
5979 in->win_mtime[0] = oh->win_mtime[0];
5980 in->win_atime[1] = oh->win_atime[1];
5981 in->win_ctime[1] = oh->win_ctime[1];
5982 in->win_mtime[1] = oh->win_mtime[1];
5983 #else
5984 in->yst_uid = oh->yst_uid;
5985 in->yst_gid = oh->yst_gid;
5986 in->yst_atime = oh->yst_atime;
5987 in->yst_mtime = oh->yst_mtime;
5988 in->yst_ctime = oh->yst_ctime;
5989 in->yst_rdev = oh->yst_rdev;
5990
5991 #endif
5992 yaffs_SetObjectName(in, oh->name);
5993
5994 if(in->variantType == YAFFS_OBJECT_TYPE_SYMLINK){
5995 in->variant.symLinkVariant.alias =
5996 yaffs_CloneString(oh->alias);
5997 if(!in->variant.symLinkVariant.alias)
5998 alloc_failed = 1; /* Not returned to caller */
5999 }
6000
6001 yaffs_ReleaseTempBuffer(dev,chunkData, __LINE__);
6002 }
6003 }
6004
6005 static int yaffs_ScanBackwards(yaffs_Device * dev)
6006 {
6007 yaffs_ExtendedTags tags;
6008 int blk;
6009 int blockIterator;
6010 int startIterator;
6011 int endIterator;
6012 int nBlocksToScan = 0;
6013
6014 int chunk;
6015 int result;
6016 int c;
6017 int deleted;
6018 yaffs_BlockState state;
6019 yaffs_Object *hardList = NULL;
6020 yaffs_BlockInfo *bi;
6021 __u32 sequenceNumber;
6022 yaffs_ObjectHeader *oh;
6023 yaffs_Object *in;
6024 yaffs_Object *parent;
6025 int nBlocks = dev->internalEndBlock - dev->internalStartBlock + 1;
6026 int itsUnlinked;
6027 __u8 *chunkData;
6028
6029 int fileSize;
6030 int isShrink;
6031 int foundChunksInBlock;
6032 int equivalentObjectId;
6033 int alloc_failed = 0;
6034
6035
6036 yaffs_BlockIndex *blockIndex = NULL;
6037 int altBlockIndex = 0;
6038
6039 if (!dev->isYaffs2) {
6040 T(YAFFS_TRACE_SCAN,
6041 (TSTR("yaffs_ScanBackwards is only for YAFFS2!" TENDSTR)));
6042 return YAFFS_FAIL;
6043 }
6044
6045 T(YAFFS_TRACE_SCAN,
6046 (TSTR
6047 ("yaffs_ScanBackwards starts intstartblk %d intendblk %d..."
6048 TENDSTR), dev->internalStartBlock, dev->internalEndBlock));
6049
6050
6051 dev->sequenceNumber = YAFFS_LOWEST_SEQUENCE_NUMBER;
6052
6053 blockIndex = YMALLOC(nBlocks * sizeof(yaffs_BlockIndex));
6054
6055 if(!blockIndex) {
6056 blockIndex = YMALLOC_ALT(nBlocks * sizeof(yaffs_BlockIndex));
6057 altBlockIndex = 1;
6058 }
6059
6060 if(!blockIndex) {
6061 T(YAFFS_TRACE_SCAN,
6062 (TSTR("yaffs_Scan() could not allocate block index!" TENDSTR)));
6063 return YAFFS_FAIL;
6064 }
6065
6066 dev->blocksInCheckpoint = 0;
6067
6068 chunkData = yaffs_GetTempBuffer(dev, __LINE__);
6069
6070 /* Scan all the blocks to determine their state */
6071 for (blk = dev->internalStartBlock; blk <= dev->internalEndBlock; blk++) {
6072 bi = yaffs_GetBlockInfo(dev, blk);
6073 yaffs_ClearChunkBits(dev, blk);
6074 bi->pagesInUse = 0;
6075 bi->softDeletions = 0;
6076
6077 yaffs_QueryInitialBlockState(dev, blk, &state, &sequenceNumber);
6078
6079 bi->blockState = state;
6080 bi->sequenceNumber = sequenceNumber;
6081
6082 if(bi->sequenceNumber == YAFFS_SEQUENCE_CHECKPOINT_DATA)
6083 bi->blockState = state = YAFFS_BLOCK_STATE_CHECKPOINT;
6084
6085 T(YAFFS_TRACE_SCAN_DEBUG,
6086 (TSTR("Block scanning block %d state %d seq %d" TENDSTR), blk,
6087 state, sequenceNumber));
6088
6089
6090 if(state == YAFFS_BLOCK_STATE_CHECKPOINT){
6091 dev->blocksInCheckpoint++;
6092
6093 } else if (state == YAFFS_BLOCK_STATE_DEAD) {
6094 T(YAFFS_TRACE_BAD_BLOCKS,
6095 (TSTR("block %d is bad" TENDSTR), blk));
6096 } else if (state == YAFFS_BLOCK_STATE_EMPTY) {
6097 T(YAFFS_TRACE_SCAN_DEBUG,
6098 (TSTR("Block empty " TENDSTR)));
6099 dev->nErasedBlocks++;
6100 dev->nFreeChunks += dev->nChunksPerBlock;
6101 } else if (state == YAFFS_BLOCK_STATE_NEEDS_SCANNING) {
6102
6103 /* Determine the highest sequence number */
6104 if (dev->isYaffs2 &&
6105 sequenceNumber >= YAFFS_LOWEST_SEQUENCE_NUMBER &&
6106 sequenceNumber < YAFFS_HIGHEST_SEQUENCE_NUMBER) {
6107
6108 blockIndex[nBlocksToScan].seq = sequenceNumber;
6109 blockIndex[nBlocksToScan].block = blk;
6110
6111 nBlocksToScan++;
6112
6113 if (sequenceNumber >= dev->sequenceNumber) {
6114 dev->sequenceNumber = sequenceNumber;
6115 }
6116 } else if (dev->isYaffs2) {
6117 /* TODO: Nasty sequence number! */
6118 T(YAFFS_TRACE_SCAN,
6119 (TSTR
6120 ("Block scanning block %d has bad sequence number %d"
6121 TENDSTR), blk, sequenceNumber));
6122
6123 }
6124 }
6125 }
6126
6127 T(YAFFS_TRACE_SCAN,
6128 (TSTR("%d blocks to be sorted..." TENDSTR), nBlocksToScan));
6129
6130
6131
6132 YYIELD();
6133
6134 /* Sort the blocks */
6135 #ifndef CONFIG_YAFFS_USE_OWN_SORT
6136 {
6137 /* Use qsort now. */
6138 yaffs_qsort(blockIndex, nBlocksToScan, sizeof(yaffs_BlockIndex), ybicmp);
6139 }
6140 #else
6141 {
6142 /* Dungy old bubble sort... */
6143
6144 yaffs_BlockIndex temp;
6145 int i;
6146 int j;
6147
6148 for (i = 0; i < nBlocksToScan; i++)
6149 for (j = i + 1; j < nBlocksToScan; j++)
6150 if (blockIndex[i].seq > blockIndex[j].seq) {
6151 temp = blockIndex[j];
6152 blockIndex[j] = blockIndex[i];
6153 blockIndex[i] = temp;
6154 }
6155 }
6156 #endif
6157
6158 YYIELD();
6159
6160 T(YAFFS_TRACE_SCAN, (TSTR("...done" TENDSTR)));
6161
6162 /* Now scan the blocks looking at the data. */
6163 startIterator = 0;
6164 endIterator = nBlocksToScan - 1;
6165 T(YAFFS_TRACE_SCAN_DEBUG,
6166 (TSTR("%d blocks to be scanned" TENDSTR), nBlocksToScan));
6167
6168 /* For each block.... backwards */
6169 for (blockIterator = endIterator; !alloc_failed && blockIterator >= startIterator;
6170 blockIterator--) {
6171 /* Cooperative multitasking! This loop can run for so
6172 long that watchdog timers expire. */
6173 YYIELD();
6174
6175 /* get the block to scan in the correct order */
6176 blk = blockIndex[blockIterator].block;
6177
6178 bi = yaffs_GetBlockInfo(dev, blk);
6179
6180
6181 state = bi->blockState;
6182
6183 deleted = 0;
6184
6185 /* For each chunk in each block that needs scanning.... */
6186 foundChunksInBlock = 0;
6187 for (c = dev->nChunksPerBlock - 1;
6188 !alloc_failed && c >= 0 &&
6189 (state == YAFFS_BLOCK_STATE_NEEDS_SCANNING ||
6190 state == YAFFS_BLOCK_STATE_ALLOCATING); c--) {
6191 /* Scan backwards...
6192 * Read the tags and decide what to do
6193 */
6194
6195 chunk = blk * dev->nChunksPerBlock + c;
6196
6197 result = yaffs_ReadChunkWithTagsFromNAND(dev, chunk, NULL,
6198 &tags);
6199
6200 /* Let's have a good look at this chunk... */
6201
6202 if (!tags.chunkUsed) {
6203 /* An unassigned chunk in the block.
6204 * If there are used chunks after this one, then
6205 * it is a chunk that was skipped due to failing the erased
6206 * check. Just skip it so that it can be deleted.
6207 * But, more typically, We get here when this is an unallocated
6208 * chunk and his means that either the block is empty or
6209 * this is the one being allocated from
6210 */
6211
6212 if(foundChunksInBlock)
6213 {
6214 /* This is a chunk that was skipped due to failing the erased check */
6215
6216 } else if (c == 0) {
6217 /* We're looking at the first chunk in the block so the block is unused */
6218 state = YAFFS_BLOCK_STATE_EMPTY;
6219 dev->nErasedBlocks++;
6220 } else {
6221 if (state == YAFFS_BLOCK_STATE_NEEDS_SCANNING ||
6222 state == YAFFS_BLOCK_STATE_ALLOCATING) {
6223 if(dev->sequenceNumber == bi->sequenceNumber) {
6224 /* this is the block being allocated from */
6225
6226 T(YAFFS_TRACE_SCAN,
6227 (TSTR
6228 (" Allocating from %d %d"
6229 TENDSTR), blk, c));
6230
6231 state = YAFFS_BLOCK_STATE_ALLOCATING;
6232 dev->allocationBlock = blk;
6233 dev->allocationPage = c;
6234 dev->allocationBlockFinder = blk;
6235 }
6236 else {
6237 /* This is a partially written block that is not
6238 * the current allocation block. This block must have
6239 * had a write failure, so set up for retirement.
6240 */
6241
6242 bi->needsRetiring = 1;
6243 bi->gcPrioritise = 1;
6244
6245 T(YAFFS_TRACE_ALWAYS,
6246 (TSTR("Partially written block %d being set for retirement" TENDSTR),
6247 blk));
6248 }
6249
6250 }
6251
6252 }
6253
6254 dev->nFreeChunks++;
6255
6256 } else if (tags.chunkId > 0) {
6257 /* chunkId > 0 so it is a data chunk... */
6258 unsigned int endpos;
6259 __u32 chunkBase =
6260 (tags.chunkId - 1) * dev->nDataBytesPerChunk;
6261
6262 foundChunksInBlock = 1;
6263
6264
6265 yaffs_SetChunkBit(dev, blk, c);
6266 bi->pagesInUse++;
6267
6268 in = yaffs_FindOrCreateObjectByNumber(dev,
6269 tags.
6270 objectId,
6271 YAFFS_OBJECT_TYPE_FILE);
6272 if(!in){
6273 /* Out of memory */
6274 alloc_failed = 1;
6275 }
6276
6277 if (in &&
6278 in->variantType == YAFFS_OBJECT_TYPE_FILE
6279 && chunkBase <
6280 in->variant.fileVariant.shrinkSize) {
6281 /* This has not been invalidated by a resize */
6282 if(!yaffs_PutChunkIntoFile(in, tags.chunkId,
6283 chunk, -1)){
6284 alloc_failed = 1;
6285 }
6286
6287 /* File size is calculated by looking at the data chunks if we have not
6288 * seen an object header yet. Stop this practice once we find an object header.
6289 */
6290 endpos =
6291 (tags.chunkId -
6292 1) * dev->nDataBytesPerChunk +
6293 tags.byteCount;
6294
6295 if (!in->valid && /* have not got an object header yet */
6296 in->variant.fileVariant.
6297 scannedFileSize < endpos) {
6298 in->variant.fileVariant.
6299 scannedFileSize = endpos;
6300 in->variant.fileVariant.
6301 fileSize =
6302 in->variant.fileVariant.
6303 scannedFileSize;
6304 }
6305
6306 } else if(in) {
6307 /* This chunk has been invalidated by a resize, so delete */
6308 yaffs_DeleteChunk(dev, chunk, 1, __LINE__);
6309
6310 }
6311 } else {
6312 /* chunkId == 0, so it is an ObjectHeader.
6313 * Thus, we read in the object header and make the object
6314 */
6315 foundChunksInBlock = 1;
6316
6317 yaffs_SetChunkBit(dev, blk, c);
6318 bi->pagesInUse++;
6319
6320 oh = NULL;
6321 in = NULL;
6322
6323 if (tags.extraHeaderInfoAvailable) {
6324 in = yaffs_FindOrCreateObjectByNumber
6325 (dev, tags.objectId,
6326 tags.extraObjectType);
6327 }
6328
6329 if (!in ||
6330 #ifdef CONFIG_YAFFS_DISABLE_LAZY_LOAD
6331 !in->valid ||
6332 #endif
6333 tags.extraShadows ||
6334 (!in->valid &&
6335 (tags.objectId == YAFFS_OBJECTID_ROOT ||
6336 tags.objectId == YAFFS_OBJECTID_LOSTNFOUND))
6337 ) {
6338
6339 /* If we don't have valid info then we need to read the chunk
6340 * TODO In future we can probably defer reading the chunk and
6341 * living with invalid data until needed.
6342 */
6343
6344 result = yaffs_ReadChunkWithTagsFromNAND(dev,
6345 chunk,
6346 chunkData,
6347 NULL);
6348
6349 oh = (yaffs_ObjectHeader *) chunkData;
6350
6351 if(dev->inbandTags){
6352 /* Fix up the header if they got corrupted by inband tags */
6353 oh->shadowsObject = oh->inbandShadowsObject;
6354 oh->isShrink = oh->inbandIsShrink;
6355 }
6356
6357 if (!in)
6358 in = yaffs_FindOrCreateObjectByNumber(dev, tags.objectId, oh->type);
6359
6360 }
6361
6362 if (!in) {
6363 /* TODO Hoosterman we have a problem! */
6364 T(YAFFS_TRACE_ERROR,
6365 (TSTR
6366 ("yaffs tragedy: Could not make object for object %d at chunk %d during scan"
6367 TENDSTR), tags.objectId, chunk));
6368
6369 }
6370
6371 if (in->valid) {
6372 /* We have already filled this one.
6373 * We have a duplicate that will be discarded, but
6374 * we first have to suck out resize info if it is a file.
6375 */
6376
6377 if ((in->variantType == YAFFS_OBJECT_TYPE_FILE) &&
6378 ((oh &&
6379 oh-> type == YAFFS_OBJECT_TYPE_FILE)||
6380 (tags.extraHeaderInfoAvailable &&
6381 tags.extraObjectType == YAFFS_OBJECT_TYPE_FILE))
6382 ) {
6383 __u32 thisSize =
6384 (oh) ? oh->fileSize : tags.
6385 extraFileLength;
6386 __u32 parentObjectId =
6387 (oh) ? oh->
6388 parentObjectId : tags.
6389 extraParentObjectId;
6390 unsigned isShrink =
6391 (oh) ? oh->isShrink : tags.
6392 extraIsShrinkHeader;
6393
6394 /* If it is deleted (unlinked at start also means deleted)
6395 * we treat the file size as being zeroed at this point.
6396 */
6397 if (parentObjectId ==
6398 YAFFS_OBJECTID_DELETED
6399 || parentObjectId ==
6400 YAFFS_OBJECTID_UNLINKED) {
6401 thisSize = 0;
6402 isShrink = 1;
6403 }
6404
6405 if (isShrink &&
6406 in->variant.fileVariant.
6407 shrinkSize > thisSize) {
6408 in->variant.fileVariant.
6409 shrinkSize =
6410 thisSize;
6411 }
6412
6413 if (isShrink) {
6414 bi->hasShrinkHeader = 1;
6415 }
6416
6417 }
6418 /* Use existing - destroy this one. */
6419 yaffs_DeleteChunk(dev, chunk, 1, __LINE__);
6420
6421 }
6422
6423 if (!in->valid &&
6424 (tags.objectId == YAFFS_OBJECTID_ROOT ||
6425 tags.objectId ==
6426 YAFFS_OBJECTID_LOSTNFOUND)) {
6427 /* We only load some info, don't fiddle with directory structure */
6428 in->valid = 1;
6429
6430 if(oh) {
6431 in->variantType = oh->type;
6432
6433 in->yst_mode = oh->yst_mode;
6434 #ifdef CONFIG_YAFFS_WINCE
6435 in->win_atime[0] = oh->win_atime[0];
6436 in->win_ctime[0] = oh->win_ctime[0];
6437 in->win_mtime[0] = oh->win_mtime[0];
6438 in->win_atime[1] = oh->win_atime[1];
6439 in->win_ctime[1] = oh->win_ctime[1];
6440 in->win_mtime[1] = oh->win_mtime[1];
6441 #else
6442 in->yst_uid = oh->yst_uid;
6443 in->yst_gid = oh->yst_gid;
6444 in->yst_atime = oh->yst_atime;
6445 in->yst_mtime = oh->yst_mtime;
6446 in->yst_ctime = oh->yst_ctime;
6447 in->yst_rdev = oh->yst_rdev;
6448
6449 #endif
6450 } else {
6451 in->variantType = tags.extraObjectType;
6452 in->lazyLoaded = 1;
6453 }
6454
6455 in->chunkId = chunk;
6456
6457 } else if (!in->valid) {
6458 /* we need to load this info */
6459
6460 in->valid = 1;
6461 in->chunkId = chunk;
6462
6463 if(oh) {
6464 in->variantType = oh->type;
6465
6466 in->yst_mode = oh->yst_mode;
6467 #ifdef CONFIG_YAFFS_WINCE
6468 in->win_atime[0] = oh->win_atime[0];
6469 in->win_ctime[0] = oh->win_ctime[0];
6470 in->win_mtime[0] = oh->win_mtime[0];
6471 in->win_atime[1] = oh->win_atime[1];
6472 in->win_ctime[1] = oh->win_ctime[1];
6473 in->win_mtime[1] = oh->win_mtime[1];
6474 #else
6475 in->yst_uid = oh->yst_uid;
6476 in->yst_gid = oh->yst_gid;
6477 in->yst_atime = oh->yst_atime;
6478 in->yst_mtime = oh->yst_mtime;
6479 in->yst_ctime = oh->yst_ctime;
6480 in->yst_rdev = oh->yst_rdev;
6481 #endif
6482
6483 if (oh->shadowsObject > 0)
6484 yaffs_HandleShadowedObject(dev,
6485 oh->
6486 shadowsObject,
6487 1);
6488
6489
6490 yaffs_SetObjectName(in, oh->name);
6491 parent =
6492 yaffs_FindOrCreateObjectByNumber
6493 (dev, oh->parentObjectId,
6494 YAFFS_OBJECT_TYPE_DIRECTORY);
6495
6496 fileSize = oh->fileSize;
6497 isShrink = oh->isShrink;
6498 equivalentObjectId = oh->equivalentObjectId;
6499
6500 }
6501 else {
6502 in->variantType = tags.extraObjectType;
6503 parent =
6504 yaffs_FindOrCreateObjectByNumber
6505 (dev, tags.extraParentObjectId,
6506 YAFFS_OBJECT_TYPE_DIRECTORY);
6507 fileSize = tags.extraFileLength;
6508 isShrink = tags.extraIsShrinkHeader;
6509 equivalentObjectId = tags.extraEquivalentObjectId;
6510 in->lazyLoaded = 1;
6511
6512 }
6513 in->dirty = 0;
6514
6515 /* directory stuff...
6516 * hook up to parent
6517 */
6518
6519 if (parent->variantType ==
6520 YAFFS_OBJECT_TYPE_UNKNOWN) {
6521 /* Set up as a directory */
6522 parent->variantType =
6523 YAFFS_OBJECT_TYPE_DIRECTORY;
6524 YINIT_LIST_HEAD(&parent->variant.
6525 directoryVariant.
6526 children);
6527 } else if (parent->variantType !=
6528 YAFFS_OBJECT_TYPE_DIRECTORY)
6529 {
6530 /* Hoosterman, another problem....
6531 * We're trying to use a non-directory as a directory
6532 */
6533
6534 T(YAFFS_TRACE_ERROR,
6535 (TSTR
6536 ("yaffs tragedy: attempting to use non-directory as a directory in scan. Put in lost+found."
6537 TENDSTR)));
6538 parent = dev->lostNFoundDir;
6539 }
6540
6541 yaffs_AddObjectToDirectory(parent, in);
6542
6543 itsUnlinked = (parent == dev->deletedDir) ||
6544 (parent == dev->unlinkedDir);
6545
6546 if (isShrink) {
6547 /* Mark the block as having a shrinkHeader */
6548 bi->hasShrinkHeader = 1;
6549 }
6550
6551 /* Note re hardlinks.
6552 * Since we might scan a hardlink before its equivalent object is scanned
6553 * we put them all in a list.
6554 * After scanning is complete, we should have all the objects, so we run
6555 * through this list and fix up all the chains.
6556 */
6557
6558 switch (in->variantType) {
6559 case YAFFS_OBJECT_TYPE_UNKNOWN:
6560 /* Todo got a problem */
6561 break;
6562 case YAFFS_OBJECT_TYPE_FILE:
6563
6564 if (in->variant.fileVariant.
6565 scannedFileSize < fileSize) {
6566 /* This covers the case where the file size is greater
6567 * than where the data is
6568 * This will happen if the file is resized to be larger
6569 * than its current data extents.
6570 */
6571 in->variant.fileVariant.fileSize = fileSize;
6572 in->variant.fileVariant.scannedFileSize =
6573 in->variant.fileVariant.fileSize;
6574 }
6575
6576 if (isShrink &&
6577 in->variant.fileVariant.shrinkSize > fileSize) {
6578 in->variant.fileVariant.shrinkSize = fileSize;
6579 }
6580
6581 break;
6582 case YAFFS_OBJECT_TYPE_HARDLINK:
6583 if(!itsUnlinked) {
6584 in->variant.hardLinkVariant.equivalentObjectId =
6585 equivalentObjectId;
6586 in->hardLinks.next =
6587 (struct ylist_head *) hardList;
6588 hardList = in;
6589 }
6590 break;
6591 case YAFFS_OBJECT_TYPE_DIRECTORY:
6592 /* Do nothing */
6593 break;
6594 case YAFFS_OBJECT_TYPE_SPECIAL:
6595 /* Do nothing */
6596 break;
6597 case YAFFS_OBJECT_TYPE_SYMLINK:
6598 if(oh){
6599 in->variant.symLinkVariant.alias =
6600 yaffs_CloneString(oh->
6601 alias);
6602 if(!in->variant.symLinkVariant.alias)
6603 alloc_failed = 1;
6604 }
6605 break;
6606 }
6607
6608 }
6609
6610 }
6611
6612 } /* End of scanning for each chunk */
6613
6614 if (state == YAFFS_BLOCK_STATE_NEEDS_SCANNING) {
6615 /* If we got this far while scanning, then the block is fully allocated. */
6616 state = YAFFS_BLOCK_STATE_FULL;
6617 }
6618
6619 bi->blockState = state;
6620
6621 /* Now let's see if it was dirty */
6622 if (bi->pagesInUse == 0 &&
6623 !bi->hasShrinkHeader &&
6624 bi->blockState == YAFFS_BLOCK_STATE_FULL) {
6625 yaffs_BlockBecameDirty(dev, blk);
6626 }
6627
6628 }
6629
6630 if (altBlockIndex)
6631 YFREE_ALT(blockIndex);
6632 else
6633 YFREE(blockIndex);
6634
6635 /* Ok, we've done all the scanning.
6636 * Fix up the hard link chains.
6637 * We should now have scanned all the objects, now it's time to add these
6638 * hardlinks.
6639 */
6640 yaffs_HardlinkFixup(dev,hardList);
6641
6642
6643 /*
6644 * Sort out state of unlinked and deleted objects.
6645 */
6646 {
6647 struct ylist_head *i;
6648 struct ylist_head *n;
6649
6650 yaffs_Object *l;
6651
6652 /* Soft delete all the unlinked files */
6653 ylist_for_each_safe(i, n,
6654 &dev->unlinkedDir->variant.directoryVariant.
6655 children) {
6656 if (i) {
6657 l = ylist_entry(i, yaffs_Object, siblings);
6658 yaffs_DestroyObject(l);
6659 }
6660 }
6661
6662 /* Soft delete all the deletedDir files */
6663 ylist_for_each_safe(i, n,
6664 &dev->deletedDir->variant.directoryVariant.
6665 children) {
6666 if (i) {
6667 l = ylist_entry(i, yaffs_Object, siblings);
6668 yaffs_DestroyObject(l);
6669
6670 }
6671 }
6672 }
6673
6674 yaffs_ReleaseTempBuffer(dev, chunkData, __LINE__);
6675
6676 if(alloc_failed){
6677 return YAFFS_FAIL;
6678 }
6679
6680 T(YAFFS_TRACE_SCAN, (TSTR("yaffs_ScanBackwards ends" TENDSTR)));
6681
6682 return YAFFS_OK;
6683 }
6684
6685 /*------------------------------ Directory Functions ----------------------------- */
6686
6687 static void yaffs_RemoveObjectFromDirectory(yaffs_Object * obj)
6688 {
6689 yaffs_Device *dev = obj->myDev;
6690
6691 if(dev && dev->removeObjectCallback)
6692 dev->removeObjectCallback(obj);
6693
6694 ylist_del_init(&obj->siblings);
6695 obj->parent = NULL;
6696 }
6697
6698
6699 static void yaffs_AddObjectToDirectory(yaffs_Object * directory,
6700 yaffs_Object * obj)
6701 {
6702
6703 if (!directory) {
6704 T(YAFFS_TRACE_ALWAYS,
6705 (TSTR
6706 ("tragedy: Trying to add an object to a null pointer directory"
6707 TENDSTR)));
6708 YBUG();
6709 }
6710 if (directory->variantType != YAFFS_OBJECT_TYPE_DIRECTORY) {
6711 T(YAFFS_TRACE_ALWAYS,
6712 (TSTR
6713 ("tragedy: Trying to add an object to a non-directory"
6714 TENDSTR)));
6715 YBUG();
6716 }
6717
6718 if (obj->siblings.prev == NULL) {
6719 /* Not initialised */
6720 YINIT_LIST_HEAD(&obj->siblings);
6721
6722 } else if (!ylist_empty(&obj->siblings)) {
6723 /* If it is holed up somewhere else, un hook it */
6724 yaffs_RemoveObjectFromDirectory(obj);
6725 }
6726 /* Now add it */
6727 ylist_add(&obj->siblings, &directory->variant.directoryVariant.children);
6728 obj->parent = directory;
6729
6730 if (directory == obj->myDev->unlinkedDir
6731 || directory == obj->myDev->deletedDir) {
6732 obj->unlinked = 1;
6733 obj->myDev->nUnlinkedFiles++;
6734 obj->renameAllowed = 0;
6735 }
6736 }
6737
6738 yaffs_Object *yaffs_FindObjectByName(yaffs_Object * directory,
6739 const YCHAR * name)
6740 {
6741 int sum;
6742
6743 struct ylist_head *i;
6744 YCHAR buffer[YAFFS_MAX_NAME_LENGTH + 1];
6745
6746 yaffs_Object *l;
6747
6748 if (!name) {
6749 return NULL;
6750 }
6751
6752 if (!directory) {
6753 T(YAFFS_TRACE_ALWAYS,
6754 (TSTR
6755 ("tragedy: yaffs_FindObjectByName: null pointer directory"
6756 TENDSTR)));
6757 YBUG();
6758 }
6759 if (directory->variantType != YAFFS_OBJECT_TYPE_DIRECTORY) {
6760 T(YAFFS_TRACE_ALWAYS,
6761 (TSTR
6762 ("tragedy: yaffs_FindObjectByName: non-directory" TENDSTR)));
6763 YBUG();
6764 }
6765
6766 sum = yaffs_CalcNameSum(name);
6767
6768 ylist_for_each(i, &directory->variant.directoryVariant.children) {
6769 if (i) {
6770 l = ylist_entry(i, yaffs_Object, siblings);
6771
6772 yaffs_CheckObjectDetailsLoaded(l);
6773
6774 /* Special case for lost-n-found */
6775 if (l->objectId == YAFFS_OBJECTID_LOSTNFOUND) {
6776 if (yaffs_strcmp(name, YAFFS_LOSTNFOUND_NAME) == 0) {
6777 return l;
6778 }
6779 } else if (yaffs_SumCompare(l->sum, sum) || l->chunkId <= 0)
6780 {
6781 /* LostnFound cunk called Objxxx
6782 * Do a real check
6783 */
6784 yaffs_GetObjectName(l, buffer,
6785 YAFFS_MAX_NAME_LENGTH);
6786 if (yaffs_strncmp(name, buffer,YAFFS_MAX_NAME_LENGTH) == 0) {
6787 return l;
6788 }
6789
6790 }
6791 }
6792 }
6793
6794 return NULL;
6795 }
6796
6797
6798 #if 0
6799 int yaffs_ApplyToDirectoryChildren(yaffs_Object * theDir,
6800 int (*fn) (yaffs_Object *))
6801 {
6802 struct ylist_head *i;
6803 yaffs_Object *l;
6804
6805 if (!theDir) {
6806 T(YAFFS_TRACE_ALWAYS,
6807 (TSTR
6808 ("tragedy: yaffs_FindObjectByName: null pointer directory"
6809 TENDSTR)));
6810 YBUG();
6811 }
6812 if (theDir->variantType != YAFFS_OBJECT_TYPE_DIRECTORY) {
6813 T(YAFFS_TRACE_ALWAYS,
6814 (TSTR
6815 ("tragedy: yaffs_FindObjectByName: non-directory" TENDSTR)));
6816 YBUG();
6817 }
6818
6819 ylist_for_each(i, &theDir->variant.directoryVariant.children) {
6820 if (i) {
6821 l = ylist_entry(i, yaffs_Object, siblings);
6822 if (l && !fn(l)) {
6823 return YAFFS_FAIL;
6824 }
6825 }
6826 }
6827
6828 return YAFFS_OK;
6829
6830 }
6831 #endif
6832
6833 /* GetEquivalentObject dereferences any hard links to get to the
6834 * actual object.
6835 */
6836
6837 yaffs_Object *yaffs_GetEquivalentObject(yaffs_Object * obj)
6838 {
6839 if (obj && obj->variantType == YAFFS_OBJECT_TYPE_HARDLINK) {
6840 /* We want the object id of the equivalent object, not this one */
6841 obj = obj->variant.hardLinkVariant.equivalentObject;
6842 yaffs_CheckObjectDetailsLoaded(obj);
6843 }
6844 return obj;
6845
6846 }
6847
6848 int yaffs_GetObjectName(yaffs_Object * obj, YCHAR * name, int buffSize)
6849 {
6850 memset(name, 0, buffSize * sizeof(YCHAR));
6851
6852 yaffs_CheckObjectDetailsLoaded(obj);
6853
6854 if (obj->objectId == YAFFS_OBJECTID_LOSTNFOUND) {
6855 yaffs_strncpy(name, YAFFS_LOSTNFOUND_NAME, buffSize - 1);
6856 } else if (obj->chunkId <= 0) {
6857 YCHAR locName[20];
6858 /* make up a name */
6859 yaffs_sprintf(locName, _Y("%s%d"), YAFFS_LOSTNFOUND_PREFIX,
6860 obj->objectId);
6861 yaffs_strncpy(name, locName, buffSize - 1);
6862
6863 }
6864 #ifdef CONFIG_YAFFS_SHORT_NAMES_IN_RAM
6865 else if (obj->shortName[0]) {
6866 yaffs_strcpy(name, obj->shortName);
6867 }
6868 #endif
6869 else {
6870 int result;
6871 __u8 *buffer = yaffs_GetTempBuffer(obj->myDev, __LINE__);
6872
6873 yaffs_ObjectHeader *oh = (yaffs_ObjectHeader *) buffer;
6874
6875 memset(buffer, 0, obj->myDev->nDataBytesPerChunk);
6876
6877 if (obj->chunkId >= 0) {
6878 result = yaffs_ReadChunkWithTagsFromNAND(obj->myDev,
6879 obj->chunkId, buffer,
6880 NULL);
6881 }
6882 yaffs_strncpy(name, oh->name, buffSize - 1);
6883
6884 yaffs_ReleaseTempBuffer(obj->myDev, buffer, __LINE__);
6885 }
6886
6887 return yaffs_strlen(name);
6888 }
6889
6890 int yaffs_GetObjectFileLength(yaffs_Object * obj)
6891 {
6892
6893 /* Dereference any hard linking */
6894 obj = yaffs_GetEquivalentObject(obj);
6895
6896 if (obj->variantType == YAFFS_OBJECT_TYPE_FILE) {
6897 return obj->variant.fileVariant.fileSize;
6898 }
6899 if (obj->variantType == YAFFS_OBJECT_TYPE_SYMLINK) {
6900 return yaffs_strlen(obj->variant.symLinkVariant.alias);
6901 } else {
6902 /* Only a directory should drop through to here */
6903 return obj->myDev->nDataBytesPerChunk;
6904 }
6905 }
6906
6907 int yaffs_GetObjectLinkCount(yaffs_Object * obj)
6908 {
6909 int count = 0;
6910 struct ylist_head *i;
6911
6912 if (!obj->unlinked) {
6913 count++; /* the object itself */
6914 }
6915 ylist_for_each(i, &obj->hardLinks) {
6916 count++; /* add the hard links; */
6917 }
6918 return count;
6919
6920 }
6921
6922 int yaffs_GetObjectInode(yaffs_Object * obj)
6923 {
6924 obj = yaffs_GetEquivalentObject(obj);
6925
6926 return obj->objectId;
6927 }
6928
6929 unsigned yaffs_GetObjectType(yaffs_Object * obj)
6930 {
6931 obj = yaffs_GetEquivalentObject(obj);
6932
6933 switch (obj->variantType) {
6934 case YAFFS_OBJECT_TYPE_FILE:
6935 return DT_REG;
6936 break;
6937 case YAFFS_OBJECT_TYPE_DIRECTORY:
6938 return DT_DIR;
6939 break;
6940 case YAFFS_OBJECT_TYPE_SYMLINK:
6941 return DT_LNK;
6942 break;
6943 case YAFFS_OBJECT_TYPE_HARDLINK:
6944 return DT_REG;
6945 break;
6946 case YAFFS_OBJECT_TYPE_SPECIAL:
6947 if (S_ISFIFO(obj->yst_mode))
6948 return DT_FIFO;
6949 if (S_ISCHR(obj->yst_mode))
6950 return DT_CHR;
6951 if (S_ISBLK(obj->yst_mode))
6952 return DT_BLK;
6953 if (S_ISSOCK(obj->yst_mode))
6954 return DT_SOCK;
6955 default:
6956 return DT_REG;
6957 break;
6958 }
6959 }
6960
6961 YCHAR *yaffs_GetSymlinkAlias(yaffs_Object * obj)
6962 {
6963 obj = yaffs_GetEquivalentObject(obj);
6964 if (obj->variantType == YAFFS_OBJECT_TYPE_SYMLINK) {
6965 return yaffs_CloneString(obj->variant.symLinkVariant.alias);
6966 } else {
6967 return yaffs_CloneString(_Y(""));
6968 }
6969 }
6970
6971 #ifndef CONFIG_YAFFS_WINCE
6972
6973 int yaffs_SetAttributes(yaffs_Object * obj, struct iattr *attr)
6974 {
6975 unsigned int valid = attr->ia_valid;
6976
6977 if (valid & ATTR_MODE)
6978 obj->yst_mode = attr->ia_mode;
6979 if (valid & ATTR_UID)
6980 obj->yst_uid = attr->ia_uid;
6981 if (valid & ATTR_GID)
6982 obj->yst_gid = attr->ia_gid;
6983
6984 if (valid & ATTR_ATIME)
6985 obj->yst_atime = Y_TIME_CONVERT(attr->ia_atime);
6986 if (valid & ATTR_CTIME)
6987 obj->yst_ctime = Y_TIME_CONVERT(attr->ia_ctime);
6988 if (valid & ATTR_MTIME)
6989 obj->yst_mtime = Y_TIME_CONVERT(attr->ia_mtime);
6990
6991 if (valid & ATTR_SIZE)
6992 yaffs_ResizeFile(obj, attr->ia_size);
6993
6994 yaffs_UpdateObjectHeader(obj, NULL, 1, 0, 0);
6995
6996 return YAFFS_OK;
6997
6998 }
6999 int yaffs_GetAttributes(yaffs_Object * obj, struct iattr *attr)
7000 {
7001 unsigned int valid = 0;
7002
7003 attr->ia_mode = obj->yst_mode;
7004 valid |= ATTR_MODE;
7005 attr->ia_uid = obj->yst_uid;
7006 valid |= ATTR_UID;
7007 attr->ia_gid = obj->yst_gid;
7008 valid |= ATTR_GID;
7009
7010 Y_TIME_CONVERT(attr->ia_atime) = obj->yst_atime;
7011 valid |= ATTR_ATIME;
7012 Y_TIME_CONVERT(attr->ia_ctime) = obj->yst_ctime;
7013 valid |= ATTR_CTIME;
7014 Y_TIME_CONVERT(attr->ia_mtime) = obj->yst_mtime;
7015 valid |= ATTR_MTIME;
7016
7017 attr->ia_size = yaffs_GetFileSize(obj);
7018 valid |= ATTR_SIZE;
7019
7020 attr->ia_valid = valid;
7021
7022 return YAFFS_OK;
7023
7024 }
7025
7026 #endif
7027
7028 #if 0
7029 int yaffs_DumpObject(yaffs_Object * obj)
7030 {
7031 YCHAR name[257];
7032
7033 yaffs_GetObjectName(obj, name, 256);
7034
7035 T(YAFFS_TRACE_ALWAYS,
7036 (TSTR
7037 ("Object %d, inode %d \"%s\"\n dirty %d valid %d serial %d sum %d"
7038 " chunk %d type %d size %d\n"
7039 TENDSTR), obj->objectId, yaffs_GetObjectInode(obj), name,
7040 obj->dirty, obj->valid, obj->serial, obj->sum, obj->chunkId,
7041 yaffs_GetObjectType(obj), yaffs_GetObjectFileLength(obj)));
7042
7043 return YAFFS_OK;
7044 }
7045 #endif
7046
7047 /*---------------------------- Initialisation code -------------------------------------- */
7048
7049 static int yaffs_CheckDevFunctions(const yaffs_Device * dev)
7050 {
7051
7052 /* Common functions, gotta have */
7053 if (!dev->eraseBlockInNAND || !dev->initialiseNAND)
7054 return 0;
7055
7056 #ifdef CONFIG_YAFFS_YAFFS2
7057
7058 /* Can use the "with tags" style interface for yaffs1 or yaffs2 */
7059 if (dev->writeChunkWithTagsToNAND &&
7060 dev->readChunkWithTagsFromNAND &&
7061 !dev->writeChunkToNAND &&
7062 !dev->readChunkFromNAND &&
7063 dev->markNANDBlockBad && dev->queryNANDBlock)
7064 return 1;
7065 #endif
7066
7067 /* Can use the "spare" style interface for yaffs1 */
7068 if (!dev->isYaffs2 &&
7069 !dev->writeChunkWithTagsToNAND &&
7070 !dev->readChunkWithTagsFromNAND &&
7071 dev->writeChunkToNAND &&
7072 dev->readChunkFromNAND &&
7073 !dev->markNANDBlockBad && !dev->queryNANDBlock)
7074 return 1;
7075
7076 return 0; /* bad */
7077 }
7078
7079
7080 static int yaffs_CreateInitialDirectories(yaffs_Device *dev)
7081 {
7082 /* Initialise the unlinked, deleted, root and lost and found directories */
7083
7084 dev->lostNFoundDir = dev->rootDir = NULL;
7085 dev->unlinkedDir = dev->deletedDir = NULL;
7086
7087 dev->unlinkedDir =
7088 yaffs_CreateFakeDirectory(dev, YAFFS_OBJECTID_UNLINKED, S_IFDIR);
7089
7090 dev->deletedDir =
7091 yaffs_CreateFakeDirectory(dev, YAFFS_OBJECTID_DELETED, S_IFDIR);
7092
7093 dev->rootDir =
7094 yaffs_CreateFakeDirectory(dev, YAFFS_OBJECTID_ROOT,
7095 YAFFS_ROOT_MODE | S_IFDIR);
7096 dev->lostNFoundDir =
7097 yaffs_CreateFakeDirectory(dev, YAFFS_OBJECTID_LOSTNFOUND,
7098 YAFFS_LOSTNFOUND_MODE | S_IFDIR);
7099
7100 if(dev->lostNFoundDir && dev->rootDir && dev->unlinkedDir && dev->deletedDir){
7101 yaffs_AddObjectToDirectory(dev->rootDir, dev->lostNFoundDir);
7102 return YAFFS_OK;
7103 }
7104
7105 return YAFFS_FAIL;
7106 }
7107
7108 int yaffs_GutsInitialise(yaffs_Device * dev)
7109 {
7110 int init_failed = 0;
7111 unsigned x;
7112 int bits;
7113
7114 T(YAFFS_TRACE_TRACING, (TSTR("yaffs: yaffs_GutsInitialise()" TENDSTR)));
7115
7116 /* Check stuff that must be set */
7117
7118 if (!dev) {
7119 T(YAFFS_TRACE_ALWAYS, (TSTR("yaffs: Need a device" TENDSTR)));
7120 return YAFFS_FAIL;
7121 }
7122
7123 dev->internalStartBlock = dev->startBlock;
7124 dev->internalEndBlock = dev->endBlock;
7125 dev->blockOffset = 0;
7126 dev->chunkOffset = 0;
7127 dev->nFreeChunks = 0;
7128
7129 if (dev->startBlock == 0) {
7130 dev->internalStartBlock = dev->startBlock + 1;
7131 dev->internalEndBlock = dev->endBlock + 1;
7132 dev->blockOffset = 1;
7133 dev->chunkOffset = dev->nChunksPerBlock;
7134 }
7135
7136 /* Check geometry parameters. */
7137
7138 if ((!dev->inbandTags && dev->isYaffs2 && dev->totalBytesPerChunk < 1024) ||
7139 (!dev->isYaffs2 && dev->totalBytesPerChunk != 512) ||
7140 (dev->inbandTags && !dev->isYaffs2 ) ||
7141 dev->nChunksPerBlock < 2 ||
7142 dev->nReservedBlocks < 2 ||
7143 dev->internalStartBlock <= 0 ||
7144 dev->internalEndBlock <= 0 ||
7145 dev->internalEndBlock <= (dev->internalStartBlock + dev->nReservedBlocks + 2) // otherwise it is too small
7146 ) {
7147 T(YAFFS_TRACE_ALWAYS,
7148 (TSTR
7149 ("yaffs: NAND geometry problems: chunk size %d, type is yaffs%s, inbandTags %d "
7150 TENDSTR), dev->totalBytesPerChunk, dev->isYaffs2 ? "2" : "", dev->inbandTags));
7151 return YAFFS_FAIL;
7152 }
7153
7154 if (yaffs_InitialiseNAND(dev) != YAFFS_OK) {
7155 T(YAFFS_TRACE_ALWAYS,
7156 (TSTR("yaffs: InitialiseNAND failed" TENDSTR)));
7157 return YAFFS_FAIL;
7158 }
7159
7160 /* Sort out space for inband tags, if required */
7161 if(dev->inbandTags)
7162 dev->nDataBytesPerChunk = dev->totalBytesPerChunk - sizeof(yaffs_PackedTags2TagsPart);
7163 else
7164 dev->nDataBytesPerChunk = dev->totalBytesPerChunk;
7165
7166 /* Got the right mix of functions? */
7167 if (!yaffs_CheckDevFunctions(dev)) {
7168 /* Function missing */
7169 T(YAFFS_TRACE_ALWAYS,
7170 (TSTR
7171 ("yaffs: device function(s) missing or wrong\n" TENDSTR)));
7172
7173 return YAFFS_FAIL;
7174 }
7175
7176 /* This is really a compilation check. */
7177 if (!yaffs_CheckStructures()) {
7178 T(YAFFS_TRACE_ALWAYS,
7179 (TSTR("yaffs_CheckStructures failed\n" TENDSTR)));
7180 return YAFFS_FAIL;
7181 }
7182
7183 if (dev->isMounted) {
7184 T(YAFFS_TRACE_ALWAYS,
7185 (TSTR("yaffs: device already mounted\n" TENDSTR)));
7186 return YAFFS_FAIL;
7187 }
7188
7189 /* Finished with most checks. One or two more checks happen later on too. */
7190
7191 dev->isMounted = 1;
7192
7193
7194
7195 /* OK now calculate a few things for the device */
7196
7197 /*
7198 * Calculate all the chunk size manipulation numbers:
7199 */
7200 {
7201 __u32 x = dev->nDataBytesPerChunk;
7202 /* We always use dev->chunkShift and dev->chunkDiv */
7203 dev->chunkShift = Shifts(x);
7204 x >>= dev->chunkShift;
7205 dev->chunkDiv = x;
7206 /* We only use chunk mask if chunkDiv is 1 */
7207 dev->chunkMask = (1<<dev->chunkShift) - 1;
7208 }
7209
7210
7211 /*
7212 * Calculate chunkGroupBits.
7213 * We need to find the next power of 2 > than internalEndBlock
7214 */
7215
7216 x = dev->nChunksPerBlock * (dev->internalEndBlock + 1);
7217
7218 bits = ShiftsGE(x);
7219
7220 /* Set up tnode width if wide tnodes are enabled. */
7221 if(!dev->wideTnodesDisabled){
7222 /* bits must be even so that we end up with 32-bit words */
7223 if(bits & 1)
7224 bits++;
7225 if(bits < 16)
7226 dev->tnodeWidth = 16;
7227 else
7228 dev->tnodeWidth = bits;
7229 }
7230 else
7231 dev->tnodeWidth = 16;
7232
7233 dev->tnodeMask = (1<<dev->tnodeWidth)-1;
7234
7235 /* Level0 Tnodes are 16 bits or wider (if wide tnodes are enabled),
7236 * so if the bitwidth of the
7237 * chunk range we're using is greater than 16 we need
7238 * to figure out chunk shift and chunkGroupSize
7239 */
7240
7241 if (bits <= dev->tnodeWidth)
7242 dev->chunkGroupBits = 0;
7243 else
7244 dev->chunkGroupBits = bits - dev->tnodeWidth;
7245
7246
7247 dev->chunkGroupSize = 1 << dev->chunkGroupBits;
7248
7249 if (dev->nChunksPerBlock < dev->chunkGroupSize) {
7250 /* We have a problem because the soft delete won't work if
7251 * the chunk group size > chunks per block.
7252 * This can be remedied by using larger "virtual blocks".
7253 */
7254 T(YAFFS_TRACE_ALWAYS,
7255 (TSTR("yaffs: chunk group too large\n" TENDSTR)));
7256
7257 return YAFFS_FAIL;
7258 }
7259
7260 /* OK, we've finished verifying the device, lets continue with initialisation */
7261
7262 /* More device initialisation */
7263 dev->garbageCollections = 0;
7264 dev->passiveGarbageCollections = 0;
7265 dev->currentDirtyChecker = 0;
7266 dev->bufferedBlock = -1;
7267 dev->doingBufferedBlockRewrite = 0;
7268 dev->nDeletedFiles = 0;
7269 dev->nBackgroundDeletions = 0;
7270 dev->nUnlinkedFiles = 0;
7271 dev->eccFixed = 0;
7272 dev->eccUnfixed = 0;
7273 dev->tagsEccFixed = 0;
7274 dev->tagsEccUnfixed = 0;
7275 dev->nErasureFailures = 0;
7276 dev->nErasedBlocks = 0;
7277 dev->isDoingGC = 0;
7278 dev->hasPendingPrioritisedGCs = 1; /* Assume the worst for now, will get fixed on first GC */
7279
7280 /* Initialise temporary buffers and caches. */
7281 if(!yaffs_InitialiseTempBuffers(dev))
7282 init_failed = 1;
7283
7284 dev->srCache = NULL;
7285 dev->gcCleanupList = NULL;
7286
7287
7288 if (!init_failed &&
7289 dev->nShortOpCaches > 0) {
7290 int i;
7291 void *buf;
7292 int srCacheBytes = dev->nShortOpCaches * sizeof(yaffs_ChunkCache);
7293
7294 if (dev->nShortOpCaches > YAFFS_MAX_SHORT_OP_CACHES) {
7295 dev->nShortOpCaches = YAFFS_MAX_SHORT_OP_CACHES;
7296 }
7297
7298 buf = dev->srCache = YMALLOC(srCacheBytes);
7299
7300 if(dev->srCache)
7301 memset(dev->srCache,0,srCacheBytes);
7302
7303 for (i = 0; i < dev->nShortOpCaches && buf; i++) {
7304 dev->srCache[i].object = NULL;
7305 dev->srCache[i].lastUse = 0;
7306 dev->srCache[i].dirty = 0;
7307 dev->srCache[i].data = buf = YMALLOC_DMA(dev->totalBytesPerChunk);
7308 }
7309 if(!buf)
7310 init_failed = 1;
7311
7312 dev->srLastUse = 0;
7313 }
7314
7315 dev->cacheHits = 0;
7316
7317 if(!init_failed){
7318 dev->gcCleanupList = YMALLOC(dev->nChunksPerBlock * sizeof(__u32));
7319 if(!dev->gcCleanupList)
7320 init_failed = 1;
7321 }
7322
7323 if (dev->isYaffs2) {
7324 dev->useHeaderFileSize = 1;
7325 }
7326 if(!init_failed && !yaffs_InitialiseBlocks(dev))
7327 init_failed = 1;
7328
7329 yaffs_InitialiseTnodes(dev);
7330 yaffs_InitialiseObjects(dev);
7331
7332 if(!init_failed && !yaffs_CreateInitialDirectories(dev))
7333 init_failed = 1;
7334
7335
7336 if(!init_failed){
7337 /* Now scan the flash. */
7338 if (dev->isYaffs2) {
7339 if(yaffs_CheckpointRestore(dev)) {
7340 T(YAFFS_TRACE_ALWAYS,
7341 (TSTR("yaffs: restored from checkpoint" TENDSTR)));
7342 } else {
7343
7344 /* Clean up the mess caused by an aborted checkpoint load
7345 * and scan backwards.
7346 */
7347 yaffs_DeinitialiseBlocks(dev);
7348 yaffs_DeinitialiseTnodes(dev);
7349 yaffs_DeinitialiseObjects(dev);
7350
7351
7352 dev->nErasedBlocks = 0;
7353 dev->nFreeChunks = 0;
7354 dev->allocationBlock = -1;
7355 dev->allocationPage = -1;
7356 dev->nDeletedFiles = 0;
7357 dev->nUnlinkedFiles = 0;
7358 dev->nBackgroundDeletions = 0;
7359 dev->oldestDirtySequence = 0;
7360
7361 if(!init_failed && !yaffs_InitialiseBlocks(dev))
7362 init_failed = 1;
7363
7364 yaffs_InitialiseTnodes(dev);
7365 yaffs_InitialiseObjects(dev);
7366
7367 if(!init_failed && !yaffs_CreateInitialDirectories(dev))
7368 init_failed = 1;
7369
7370 if(!init_failed && !yaffs_ScanBackwards(dev))
7371 init_failed = 1;
7372 }
7373 }else
7374 if(!yaffs_Scan(dev))
7375 init_failed = 1;
7376 }
7377
7378 if(init_failed){
7379 /* Clean up the mess */
7380 T(YAFFS_TRACE_TRACING,
7381 (TSTR("yaffs: yaffs_GutsInitialise() aborted.\n" TENDSTR)));
7382
7383 yaffs_Deinitialise(dev);
7384 return YAFFS_FAIL;
7385 }
7386
7387 /* Zero out stats */
7388 dev->nPageReads = 0;
7389 dev->nPageWrites = 0;
7390 dev->nBlockErasures = 0;
7391 dev->nGCCopies = 0;
7392 dev->nRetriedWrites = 0;
7393
7394 dev->nRetiredBlocks = 0;
7395
7396 yaffs_VerifyFreeChunks(dev);
7397 yaffs_VerifyBlocks(dev);
7398
7399
7400 T(YAFFS_TRACE_TRACING,
7401 (TSTR("yaffs: yaffs_GutsInitialise() done.\n" TENDSTR)));
7402 return YAFFS_OK;
7403
7404 }
7405
7406 void yaffs_Deinitialise(yaffs_Device * dev)
7407 {
7408 if (dev->isMounted) {
7409 int i;
7410
7411 yaffs_DeinitialiseBlocks(dev);
7412 yaffs_DeinitialiseTnodes(dev);
7413 yaffs_DeinitialiseObjects(dev);
7414 if (dev->nShortOpCaches > 0 &&
7415 dev->srCache) {
7416
7417 for (i = 0; i < dev->nShortOpCaches; i++) {
7418 if(dev->srCache[i].data)
7419 YFREE(dev->srCache[i].data);
7420 dev->srCache[i].data = NULL;
7421 }
7422
7423 YFREE(dev->srCache);
7424 dev->srCache = NULL;
7425 }
7426
7427 YFREE(dev->gcCleanupList);
7428
7429 for (i = 0; i < YAFFS_N_TEMP_BUFFERS; i++) {
7430 YFREE(dev->tempBuffer[i].buffer);
7431 }
7432
7433
7434 dev->isMounted = 0;
7435 }
7436
7437 }
7438
7439 static int yaffs_CountFreeChunks(yaffs_Device * dev)
7440 {
7441 int nFree;
7442 int b;
7443
7444 yaffs_BlockInfo *blk;
7445
7446 for (nFree = 0, b = dev->internalStartBlock; b <= dev->internalEndBlock;
7447 b++) {
7448 blk = yaffs_GetBlockInfo(dev, b);
7449
7450 switch (blk->blockState) {
7451 case YAFFS_BLOCK_STATE_EMPTY:
7452 case YAFFS_BLOCK_STATE_ALLOCATING:
7453 case YAFFS_BLOCK_STATE_COLLECTING:
7454 case YAFFS_BLOCK_STATE_FULL:
7455 nFree +=
7456 (dev->nChunksPerBlock - blk->pagesInUse +
7457 blk->softDeletions);
7458 break;
7459 default:
7460 break;
7461 }
7462
7463 }
7464
7465 return nFree;
7466 }
7467
7468 int yaffs_GetNumberOfFreeChunks(yaffs_Device * dev)
7469 {
7470 /* This is what we report to the outside world */
7471
7472 int nFree;
7473 int nDirtyCacheChunks;
7474 int blocksForCheckpoint;
7475
7476 #if 1
7477 nFree = dev->nFreeChunks;
7478 #else
7479 nFree = yaffs_CountFreeChunks(dev);
7480 #endif
7481
7482 nFree += dev->nDeletedFiles;
7483
7484 /* Now count the number of dirty chunks in the cache and subtract those */
7485
7486 {
7487 int i;
7488 for (nDirtyCacheChunks = 0, i = 0; i < dev->nShortOpCaches; i++) {
7489 if (dev->srCache[i].dirty)
7490 nDirtyCacheChunks++;
7491 }
7492 }
7493
7494 nFree -= nDirtyCacheChunks;
7495
7496 nFree -= ((dev->nReservedBlocks + 1) * dev->nChunksPerBlock);
7497
7498 /* Now we figure out how much to reserve for the checkpoint and report that... */
7499 blocksForCheckpoint = yaffs_CalcCheckpointBlocksRequired(dev) - dev->blocksInCheckpoint;
7500 if(blocksForCheckpoint < 0)
7501 blocksForCheckpoint = 0;
7502
7503 nFree -= (blocksForCheckpoint * dev->nChunksPerBlock);
7504
7505 if (nFree < 0)
7506 nFree = 0;
7507
7508 return nFree;
7509
7510 }
7511
7512 static int yaffs_freeVerificationFailures;
7513
7514 static void yaffs_VerifyFreeChunks(yaffs_Device * dev)
7515 {
7516 int counted;
7517 int difference;
7518
7519 if(yaffs_SkipVerification(dev))
7520 return;
7521
7522 counted = yaffs_CountFreeChunks(dev);
7523
7524 difference = dev->nFreeChunks - counted;
7525
7526 if (difference) {
7527 T(YAFFS_TRACE_ALWAYS,
7528 (TSTR("Freechunks verification failure %d %d %d" TENDSTR),
7529 dev->nFreeChunks, counted, difference));
7530 yaffs_freeVerificationFailures++;
7531 }
7532 }
7533
7534 /*---------------------------------------- YAFFS test code ----------------------*/
7535
7536 #define yaffs_CheckStruct(structure,syze, name) \
7537 do { \
7538 if(sizeof(structure) != syze) \
7539 { \
7540 T(YAFFS_TRACE_ALWAYS,(TSTR("%s should be %d but is %d\n" TENDSTR),\
7541 name,syze,sizeof(structure))); \
7542 return YAFFS_FAIL; \
7543 } \
7544 } while(0)
7545
7546 static int yaffs_CheckStructures(void)
7547 {
7548 /* yaffs_CheckStruct(yaffs_Tags,8,"yaffs_Tags"); */
7549 /* yaffs_CheckStruct(yaffs_TagsUnion,8,"yaffs_TagsUnion"); */
7550 /* yaffs_CheckStruct(yaffs_Spare,16,"yaffs_Spare"); */
7551 #ifndef CONFIG_YAFFS_TNODE_LIST_DEBUG
7552 yaffs_CheckStruct(yaffs_Tnode, 2 * YAFFS_NTNODES_LEVEL0, "yaffs_Tnode");
7553 #endif
7554 #ifndef CONFIG_YAFFS_WINCE
7555 yaffs_CheckStruct(yaffs_ObjectHeader, 512, "yaffs_ObjectHeader");
7556 #endif
7557 return YAFFS_OK;
7558 }
This page took 0.46899 seconds and 5 git commands to generate.