regain glock on storedata error exit
[openafs.git] / src / afs / afs_segments.c
1 /*
2  * Copyright 2000, International Business Machines Corporation and others.
3  * All Rights Reserved.
4  * 
5  * This software has been released under the terms of the IBM Public
6  * License.  For details, see the LICENSE file in the top-level source
7  * directory or online at http://www.openafs.org/dl/license10.html
8  */
9
10 /*
11  * --------------------- Required definitions ---------------------
12  */
13 #include <afsconfig.h>
14 #include "afs/param.h"
15
16
17 #include "afs/sysincludes.h"    /*Standard vendor system headers */
18 #include "afsincludes.h"        /*AFS-based standard headers */
19 #include "afs/afs_stats.h"      /* statistics */
20 #include "afs/afs_cbqueue.h"
21 #include "afs/afs_osidnlc.h"
22
23 afs_uint32 afs_stampValue = 0;
24
25 /*
26  * afs_StoreMini
27  *
28  * Description:
29  *      Send a truncation request to a FileServer.
30  *
31  * Parameters:
32  *      xxx : description
33  *
34  * Environment:
35  *      We're write-locked upon entry.
36  */
37
38 static int
39 afs_StoreMini(register struct vcache *avc, struct vrequest *areq)
40 {
41     register struct afs_conn *tc;
42     struct AFSStoreStatus InStatus;
43     struct AFSFetchStatus OutStatus;
44     struct AFSVolSync tsync;
45     register afs_int32 code, code2;
46     register struct rx_call *tcall;
47     afs_size_t tlen, xlen = 0;
48     XSTATS_DECLS;
49     AFS_STATCNT(afs_StoreMini);
50     afs_Trace2(afs_iclSetp, CM_TRACE_STOREMINI, ICL_TYPE_POINTER, avc,
51                ICL_TYPE_INT32, avc->f.m.Length);
52     tlen = avc->f.m.Length;
53     if (avc->f.truncPos < tlen)
54         tlen = avc->f.truncPos;
55     avc->f.truncPos = AFS_NOTRUNC;
56     avc->f.states &= ~CExtendedFile;
57
58     do {
59         tc = afs_Conn(&avc->f.fid, areq, SHARED_LOCK);
60         if (tc) {
61 #ifdef AFS_64BIT_CLIENT
62           retry:
63 #endif
64             RX_AFS_GUNLOCK();
65             tcall = rx_NewCall(tc->id);
66             RX_AFS_GLOCK();
67             /* Set the client mod time since we always want the file
68              * to have the client's mod time and not the server's one
69              * (to avoid problems with make, etc.) It almost always
70              * works fine with standard afs because them server/client
71              * times are in sync and more importantly this storemini
72              * it's a special call that would typically be followed by
73              * the proper store-data or store-status calls.
74              */
75             InStatus.Mask = AFS_SETMODTIME;
76             InStatus.ClientModTime = avc->f.m.Date;
77             XSTATS_START_TIME(AFS_STATS_FS_RPCIDX_STOREDATA);
78             afs_Trace4(afs_iclSetp, CM_TRACE_STOREDATA64, ICL_TYPE_FID,
79                        &avc->f.fid.Fid, ICL_TYPE_OFFSET,
80                        ICL_HANDLE_OFFSET(avc->f.m.Length), ICL_TYPE_OFFSET,
81                        ICL_HANDLE_OFFSET(xlen), ICL_TYPE_OFFSET,
82                        ICL_HANDLE_OFFSET(tlen));
83             RX_AFS_GUNLOCK();
84 #ifdef AFS_64BIT_CLIENT
85             if (!afs_serverHasNo64Bit(tc)) {
86                 code =
87                     StartRXAFS_StoreData64(tcall,
88                                            (struct AFSFid *)&avc->f.fid.Fid,
89                                            &InStatus, avc->f.m.Length,
90                                            (afs_size_t) 0, tlen);
91             } else {
92                 afs_int32 l1, l2;
93                 l1 = avc->f.m.Length;
94                 l2 = tlen;
95                 if ((avc->f.m.Length > 0x7fffffff) ||
96                     (tlen > 0x7fffffff) ||
97                     ((0x7fffffff - tlen) < avc->f.m.Length)) {
98                     RX_AFS_GLOCK();
99                     return EFBIG;
100                 }
101                 code =
102                     StartRXAFS_StoreData(tcall,
103                                          (struct AFSFid *)&avc->f.fid.Fid,
104                                          &InStatus, l1, 0, l2);
105             }
106 #else /* AFS_64BIT_CLIENT */
107             code =
108                 StartRXAFS_StoreData(tcall, (struct AFSFid *)&avc->f.fid.Fid,
109                                      &InStatus, avc->f.m.Length, 0, tlen);
110 #endif /* AFS_64BIT_CLIENT */
111             if (code == 0) {
112                 code = EndRXAFS_StoreData(tcall, &OutStatus, &tsync);
113             }
114             code2 = rx_EndCall(tcall, code);
115             if (code2 && !code)
116                 code = code2;
117             RX_AFS_GLOCK();
118             XSTATS_END_TIME;
119 #ifdef AFS_64BIT_CLIENT
120             if (code == RXGEN_OPCODE && !afs_serverHasNo64Bit(tc)) {
121                 afs_serverSetNo64Bit(tc);
122                 goto retry;
123             }
124 #endif /* AFS_64BIT_CLIENT */
125         } else
126             code = -1;
127     } while (afs_Analyze
128              (tc, code, &avc->f.fid, areq, AFS_STATS_FS_RPCIDX_STOREDATA,
129               SHARED_LOCK, NULL));
130
131     if (code == 0)
132         afs_ProcessFS(avc, &OutStatus, areq);
133
134     return code;
135 }                               /*afs_StoreMini */
136
137 /*
138  * afs_StoreAllSegments
139  *
140  * Description:
141  *      Stores all modified segments back to server
142  *
143  * Parameters:
144  *      avc  : Pointer to vcache entry.
145  *      areq : Pointer to request structure.
146  *
147  * Environment:
148  *      Called with avc write-locked.
149  */
150 #if defined (AFS_HPUX_ENV)
151 int NCHUNKSATONCE = 3;
152 #else
153 int NCHUNKSATONCE = 64;
154 #endif
155 int afs_dvhack = 0;
156
157
158 int
159 afs_StoreAllSegments(register struct vcache *avc, struct vrequest *areq,
160                      int sync)
161 {
162     register struct dcache *tdc;
163     register afs_int32 code = 0;
164     register afs_int32 index;
165     register afs_int32 origCBs, foreign = 0;
166     int hash;
167     afs_hyper_t newDV, oldDV;   /* DV when we start, and finish, respectively */
168     struct dcache **dcList;
169     unsigned int i, j, minj, moredata, high, off;
170     afs_size_t tlen;
171     afs_size_t maxStoredLength; /* highest offset we've written to server. */
172     int safety, marineronce = 0;
173
174     AFS_STATCNT(afs_StoreAllSegments);
175
176     hset(oldDV, avc->f.m.DataVersion);
177     hset(newDV, avc->f.m.DataVersion);
178     hash = DVHash(&avc->f.fid);
179     foreign = (avc->f.states & CForeign);
180     dcList = (struct dcache **)osi_AllocLargeSpace(AFS_LRALLOCSIZ);
181     afs_Trace2(afs_iclSetp, CM_TRACE_STOREALL, ICL_TYPE_POINTER, avc,
182                ICL_TYPE_OFFSET, ICL_HANDLE_OFFSET(avc->f.m.Length));
183 #if !defined(AFS_AIX32_ENV) && !defined(AFS_SGI65_ENV)
184     /* In the aix vm implementation we need to do the vm_writep even
185      * on the memcache case since that's we adjust the file's size
186      * and finish flushing partial vm pages.
187      */
188     if ((cacheDiskType != AFS_FCACHE_TYPE_MEM) || (sync & AFS_LASTSTORE))
189 #endif /* !AFS_AIX32_ENV && !AFS_SGI65_ENV */
190     {
191         /* If we're not diskless, reading a file may stress the VM
192          * system enough to cause a pageout, and this vnode would be
193          * locked when the pageout occurs.  We can prevent this problem
194          * by making sure all dirty pages are already flushed.  We don't
195          * do this when diskless because reading a diskless (i.e.
196          * memory-resident) chunk doesn't require using new VM, and we
197          * also don't want to dump more dirty data into a diskless cache,
198          * since they're smaller, and we might exceed its available
199          * space.
200          */
201 #if     defined(AFS_SUN5_ENV)
202         if (sync & AFS_VMSYNC_INVAL)    /* invalidate VM pages */
203             osi_VM_TryToSmush(avc, CRED(), 1);
204         else
205 #endif
206             osi_VM_StoreAllSegments(avc);
207     }
208     if (AFS_IS_DISCONNECTED && !AFS_IN_SYNC) {
209         /* This will probably make someone sad ... */
210         /*printf("Net down in afs_StoreSegments\n");*/
211         return ENETDOWN;
212     }
213     ConvertWToSLock(&avc->lock);
214
215     /*
216      * Subsequent code expects a sorted list, and it expects all the
217      * chunks in the list to be contiguous, so we need a sort and a
218      * while loop in here, too - but this will work for a first pass...
219      * 92.10.05 - OK, there's a sort in here now.  It's kind of a modified
220      *            bin sort, I guess.  Chunk numbers start with 0
221      *
222      * - Have to get a write lock on xdcache because GetDSlot might need it (if
223      *   the chunk doesn't have a dcache struct).
224      *   This seems like overkill in most cases.
225      * - I'm not sure that it's safe to do "index = .hvNextp", then unlock 
226      *   xdcache, then relock xdcache and try to use index.  It is done
227      *   a lot elsewhere in the CM, but I'm not buying that argument.
228      * - should be able to check IFDataMod without doing the GetDSlot (just
229      *   hold afs_xdcache).  That way, it's easy to do this without the
230      *   writelock on afs_xdcache, and we save unneccessary disk
231      *   operations. I don't think that works, 'cuz the next pointers 
232      *   are still on disk.
233      */
234     origCBs = afs_allCBs;
235
236     maxStoredLength = 0;
237     tlen = avc->f.m.Length;
238     minj = 0;
239
240     do {
241         memset(dcList, 0, NCHUNKSATONCE * sizeof(struct dcache *));
242         high = 0;
243         moredata = FALSE;
244
245         /* lock and start over from beginning of hash chain 
246          * in order to avoid a race condition. */
247         ObtainWriteLock(&afs_xdcache, 284);
248         index = afs_dvhashTbl[hash];
249
250         for (j = 0; index != NULLIDX;) {
251             if ((afs_indexFlags[index] & IFDataMod)
252                 && (afs_indexUnique[index] == avc->f.fid.Fid.Unique)) {
253                 tdc = afs_GetDSlot(index, 0);   /* refcount+1. */
254                 ReleaseReadLock(&tdc->tlock);
255                 if (!FidCmp(&tdc->f.fid, &avc->f.fid) && tdc->f.chunk >= minj) {
256                     off = tdc->f.chunk - minj;
257                     if (off < NCHUNKSATONCE) {
258                         if (dcList[off])
259                             osi_Panic("dclist slot already in use!");
260                         if (afs_mariner && !marineronce) {
261                             /* first chunk only */
262                             afs_MarinerLog("store$Storing", avc);
263                             marineronce++;
264                         }
265                         dcList[off] = tdc;
266                         if (off > high)
267                             high = off;
268                         j++;
269                         /* DCLOCKXXX: chunkBytes is protected by tdc->lock which we
270                          * can't grab here, due to lock ordering with afs_xdcache.
271                          * So, disable this shortcut for now.  -- kolya 2001-10-13
272                          */
273                         /* shortcut: big win for little files */
274                         /* tlen -= tdc->f.chunkBytes;
275                          * if (tlen <= 0)
276                          *    break;
277                          */
278                     } else {
279                         moredata = TRUE;
280                         afs_PutDCache(tdc);
281                         if (j == NCHUNKSATONCE)
282                             break;
283                     }
284                 } else {
285                     afs_PutDCache(tdc);
286                 }
287             }
288             index = afs_dvnextTbl[index];
289         }
290         ReleaseWriteLock(&afs_xdcache);
291
292         /* this guy writes chunks, puts back dcache structs, and bumps newDV */
293         /* "moredata" just says "there are more dirty chunks yet to come".
294          */
295         if (j) {
296             code =
297                 afs_CacheStoreVCache(dcList, avc, areq, sync,
298                                    minj, high, moredata,
299                                    &newDV, &maxStoredLength);
300             /* Release any zero-length dcache entries in our interval
301              * that we locked but didn't store back above.
302              */
303             for (j = 0; j <= high; j++) {
304                 tdc = dcList[j];
305                 if (tdc) {
306                     osi_Assert(tdc->f.chunkBytes == 0);
307                     ReleaseSharedLock(&tdc->lock);
308                     afs_PutDCache(tdc);
309                 }
310             }
311         }
312         /* if (j) */
313         minj += NCHUNKSATONCE;
314     } while (!code && moredata);
315
316     UpgradeSToWLock(&avc->lock, 29);
317
318     /* send a trivial truncation store if did nothing else */
319     if (code == 0) {
320         /*
321          * Call StoreMini if we haven't written enough data to extend the
322          * file at the fileserver to the client's notion of the file length.
323          */
324         if ((avc->f.truncPos != AFS_NOTRUNC) 
325             || ((avc->f.states & CExtendedFile)
326                 && (maxStoredLength < avc->f.m.Length))) {
327             code = afs_StoreMini(avc, areq);
328             if (code == 0)
329                 hadd32(newDV, 1);       /* just bumped here, too */
330         }
331         avc->f.states &= ~CExtendedFile;
332     }
333
334     /*
335      * Finally, turn off DWriting, turn on DFEntryMod,
336      * update f.versionNo.
337      * A lot of this could be integrated into the loop above 
338      */
339     if (!code) {
340         afs_hyper_t h_unset;
341         hones(h_unset);
342
343         minj = 0;
344
345         do {
346             moredata = FALSE;
347             memset(dcList, 0,
348                    NCHUNKSATONCE * sizeof(struct dcache *));
349
350             /* overkill, but it gets the lock in case GetDSlot needs it */
351             ObtainWriteLock(&afs_xdcache, 285);
352
353             for (j = 0, safety = 0, index = afs_dvhashTbl[hash];
354                  index != NULLIDX && safety < afs_cacheFiles + 2;) {
355
356                 if (afs_indexUnique[index] == avc->f.fid.Fid.Unique) {
357                     tdc = afs_GetDSlot(index, 0);
358                     ReleaseReadLock(&tdc->tlock);
359
360                     if (!FidCmp(&tdc->f.fid, &avc->f.fid)
361                         && tdc->f.chunk >= minj) {
362                         off = tdc->f.chunk - minj;
363                         if (off < NCHUNKSATONCE) {
364                             /* this is the file, and the correct chunk range */
365                             if (j >= NCHUNKSATONCE)
366                                 osi_Panic
367                                     ("Too many dcache entries in range\n");
368                             dcList[j++] = tdc;
369                         } else {
370                             moredata = TRUE;
371                             afs_PutDCache(tdc);
372                             if (j == NCHUNKSATONCE)
373                                 break;
374                         }
375                     } else {
376                         afs_PutDCache(tdc);
377                     }
378                 }
379
380                 index = afs_dvnextTbl[index];
381             }
382             ReleaseWriteLock(&afs_xdcache);
383
384             for (i = 0; i < j; i++) {
385                 /* Iterate over the dcache entries we collected above */
386                 tdc = dcList[i];
387                 ObtainSharedLock(&tdc->lock, 677);
388
389                 /* was code here to clear IFDataMod, but it should only be done
390                  * in storedcache and storealldcache.
391                  */
392                 /* Only increase DV if we had up-to-date data to start with.
393                  * Otherwise, we could be falsely upgrading an old chunk
394                  * (that we never read) into one labelled with the current
395                  * DV #.  Also note that we check that no intervening stores
396                  * occurred, otherwise we might mislabel cache information
397                  * for a chunk that we didn't store this time
398                  */
399                 /* Don't update the version number if it's not yet set. */
400                 if (!hsame(tdc->f.versionNo, h_unset)
401                     && hcmp(tdc->f.versionNo, oldDV) >= 0) {
402
403                     if ((!(afs_dvhack || foreign)
404                          && hsame(avc->f.m.DataVersion, newDV))
405                         || ((afs_dvhack || foreign)
406                             && (origCBs == afs_allCBs))) {
407                         /* no error, this is the DV */
408
409                         UpgradeSToWLock(&tdc->lock, 678);
410                         hset(tdc->f.versionNo, avc->f.m.DataVersion);
411                         tdc->dflags |= DFEntryMod;
412                         ConvertWToSLock(&tdc->lock);
413                     }
414                 }
415
416                 ReleaseSharedLock(&tdc->lock);
417                 afs_PutDCache(tdc);
418             }
419
420             minj += NCHUNKSATONCE;
421
422         } while (moredata);
423     }
424
425     if (code) {
426         /*
427          * Invalidate chunks after an error for ccores files since
428          * afs_inactive won't be called for these and they won't be
429          * invalidated. Also discard data if it's a permanent error from the
430          * fileserver.
431          */
432         if (areq->permWriteError || (avc->f.states & CCore)) {
433             afs_InvalidateAllSegments(avc);
434         }
435     }
436     afs_Trace3(afs_iclSetp, CM_TRACE_STOREALLDONE, ICL_TYPE_POINTER, avc,
437                ICL_TYPE_INT32, avc->f.m.Length, ICL_TYPE_INT32, code);
438     /* would like a Trace5, but it doesn't exist... */
439     afs_Trace3(afs_iclSetp, CM_TRACE_AVCLOCKER, ICL_TYPE_POINTER, avc,
440                ICL_TYPE_INT32, avc->lock.wait_states, ICL_TYPE_INT32,
441                avc->lock.excl_locked);
442     afs_Trace4(afs_iclSetp, CM_TRACE_AVCLOCKEE, ICL_TYPE_POINTER, avc,
443                ICL_TYPE_INT32, avc->lock.wait_states, ICL_TYPE_INT32,
444                avc->lock.readers_reading, ICL_TYPE_INT32,
445                avc->lock.num_waiting);
446
447     /*
448      * Finally, if updated DataVersion matches newDV, we did all of the
449      * stores.  If mapDV indicates that the page cache was flushed up
450      * to when we started the store, then we can relabel them as flushed
451      * as recently as newDV.
452      * Turn off CDirty bit because the stored data is now in sync with server.
453      */
454     if (code == 0 && hcmp(avc->mapDV, oldDV) >= 0) {
455         if ((!(afs_dvhack || foreign) && hsame(avc->f.m.DataVersion, newDV))
456             || ((afs_dvhack || foreign) && (origCBs == afs_allCBs))) {
457             hset(avc->mapDV, newDV);
458             avc->f.states &= ~CDirty;
459         }
460     }
461     osi_FreeLargeSpace(dcList);
462
463     /* If not the final write a temporary error is ok. */
464     if (code && !areq->permWriteError && !(sync & AFS_LASTSTORE))
465         code = 0;
466
467     return code;
468
469 }                               /*afs_StoreAllSegments (new 03/02/94) */
470
471
472 /*
473  * afs_InvalidateAllSegments
474  *
475  * Description:
476  *      Invalidates all chunks for a given file
477  *
478  * Parameters:
479  *      avc      : Pointer to vcache entry.
480  *
481  * Environment:
482  *      For example, called after an error has been detected.  Called
483  *      with avc write-locked, and afs_xdcache unheld.
484  */
485
486 int
487 afs_InvalidateAllSegments(struct vcache *avc)
488 {
489     struct dcache *tdc;
490     afs_int32 hash;
491     afs_int32 index;
492     struct dcache **dcList;
493     int i, dcListMax, dcListCount;
494
495     AFS_STATCNT(afs_InvalidateAllSegments);
496     afs_Trace2(afs_iclSetp, CM_TRACE_INVALL, ICL_TYPE_POINTER, avc,
497                ICL_TYPE_OFFSET, ICL_HANDLE_OFFSET(avc->f.m.Length));
498     hash = DVHash(&avc->f.fid);
499     avc->f.truncPos = AFS_NOTRUNC;      /* don't truncate later */
500     avc->f.states &= ~CExtendedFile;    /* not any more */
501     ObtainWriteLock(&afs_xcbhash, 459);
502     afs_DequeueCallback(avc);
503     avc->f.states &= ~(CStatd | CDirty);        /* mark status information as bad, too */
504     ReleaseWriteLock(&afs_xcbhash);
505     if (avc->f.fid.Fid.Vnode & 1 || (vType(avc) == VDIR))
506         osi_dnlc_purgedp(avc);
507     /* Blow away pages; for now, only for Solaris */
508 #if     (defined(AFS_SUN5_ENV))
509     if (WriteLocked(&avc->lock))
510         osi_ReleaseVM(avc, (afs_ucred_t *)0);
511 #endif
512     /*
513      * Block out others from screwing with this table; is a read lock
514      * sufficient?
515      */
516     ObtainWriteLock(&afs_xdcache, 286);
517     dcListMax = 0;
518
519     for (index = afs_dvhashTbl[hash]; index != NULLIDX;) {
520         if (afs_indexUnique[index] == avc->f.fid.Fid.Unique) {
521             tdc = afs_GetDSlot(index, 0);
522             ReleaseReadLock(&tdc->tlock);
523             if (!FidCmp(&tdc->f.fid, &avc->f.fid))
524                 dcListMax++;
525             afs_PutDCache(tdc);
526         }
527         index = afs_dvnextTbl[index];
528     }
529
530     dcList = osi_Alloc(dcListMax * sizeof(struct dcache *));
531     dcListCount = 0;
532
533     for (index = afs_dvhashTbl[hash]; index != NULLIDX;) {
534         if (afs_indexUnique[index] == avc->f.fid.Fid.Unique) {
535             tdc = afs_GetDSlot(index, 0);
536             ReleaseReadLock(&tdc->tlock);
537             if (!FidCmp(&tdc->f.fid, &avc->f.fid)) {
538                 /* same file? we'll zap it */
539                 if (afs_indexFlags[index] & IFDataMod) {
540                     afs_stats_cmperf.cacheCurrDirtyChunks--;
541                     /* don't write it back */
542                     afs_indexFlags[index] &= ~IFDataMod;
543                 }
544                 afs_indexFlags[index] &= ~IFAnyPages;
545                 if (dcListCount < dcListMax)
546                     dcList[dcListCount++] = tdc;
547                 else
548                     afs_PutDCache(tdc);
549             } else {
550                 afs_PutDCache(tdc);
551             }
552         }
553         index = afs_dvnextTbl[index];
554     }
555     ReleaseWriteLock(&afs_xdcache);
556
557     for (i = 0; i < dcListCount; i++) {
558         tdc = dcList[i];
559
560         ObtainWriteLock(&tdc->lock, 679);
561         ZapDCE(tdc);
562         if (vType(avc) == VDIR)
563             DZap(tdc);
564         ReleaseWriteLock(&tdc->lock);
565         afs_PutDCache(tdc);
566     }
567
568     osi_Free(dcList, dcListMax * sizeof(struct dcache *));
569
570     return 0;
571 }
572
573 /*! 
574  * 
575  * Extend a cache file
576  *
577  * \param avc pointer to vcache to extend data for
578  * \param alen Length to extend file to
579  * \param areq
580  *
581  * \note avc must be write locked. May release and reobtain avc and GLOCK
582  */
583 int
584 afs_ExtendSegments(struct vcache *avc, afs_size_t alen, struct vrequest *areq) {
585     afs_size_t offset, toAdd;
586     struct osi_file *tfile;
587     afs_int32 code = 0;
588     struct dcache *tdc;
589     void *zeros;
590
591     zeros = (void *) afs_osi_Alloc(AFS_PAGESIZE);
592     if (zeros == NULL)
593         return ENOMEM;
594     memset(zeros, 0, AFS_PAGESIZE);
595
596     while (avc->f.m.Length < alen) {
597         tdc = afs_ObtainDCacheForWriting(avc, avc->f.m.Length, alen - avc->f.m.Length, areq, 0);
598         if (!tdc) {
599             code = EIO;
600             break;
601         }
602
603         toAdd = alen - avc->f.m.Length;
604
605         offset = avc->f.m.Length - AFS_CHUNKTOBASE(tdc->f.chunk);
606         if (offset + toAdd > AFS_CHUNKTOSIZE(tdc->f.chunk)) {
607             toAdd = AFS_CHUNKTOSIZE(tdc->f.chunk) - offset;
608         }
609         tfile = afs_CFileOpen(&tdc->f.inode);
610         while(tdc->validPos < avc->f.m.Length + toAdd) {
611              afs_size_t towrite;
612
613              towrite = (avc->f.m.Length + toAdd) - tdc->validPos;
614              if (towrite > AFS_PAGESIZE) towrite = AFS_PAGESIZE;
615
616              code = afs_CFileWrite(tfile, 
617                                    tdc->validPos - AFS_CHUNKTOBASE(tdc->f.chunk), 
618                                    zeros, towrite);
619              tdc->validPos += towrite;
620         }
621         afs_CFileClose(tfile);
622         afs_AdjustSize(tdc, offset + toAdd );
623         avc->f.m.Length += toAdd;
624         ReleaseWriteLock(&tdc->lock);
625         afs_PutDCache(tdc);
626     }
627
628     afs_osi_Free(zeros, AFS_PAGESIZE);
629     return code;
630 }
631
632 /*
633  * afs_TruncateAllSegments
634  *
635  * Description:
636  *      Truncate a cache file.
637  *
638  * Parameters:
639  *      avc  : Ptr to vcache entry to truncate.
640  *      alen : Number of bytes to make the file.
641  *      areq : Ptr to request structure.
642  *
643  * Environment:
644  *      Called with avc write-locked; in VFS40 systems, pvnLock is also
645  *      held.
646  */
647 int
648 afs_TruncateAllSegments(register struct vcache *avc, afs_size_t alen,
649                         struct vrequest *areq, afs_ucred_t *acred)
650 {
651     register struct dcache *tdc;
652     register afs_int32 code;
653     register afs_int32 index;
654     afs_size_t newSize;
655
656     int dcCount, dcPos;
657     struct dcache **tdcArray;
658
659     AFS_STATCNT(afs_TruncateAllSegments);
660     avc->f.m.Date = osi_Time();
661     afs_Trace3(afs_iclSetp, CM_TRACE_TRUNCALL, ICL_TYPE_POINTER, avc,
662                ICL_TYPE_OFFSET, ICL_HANDLE_OFFSET(avc->f.m.Length),
663                ICL_TYPE_OFFSET, ICL_HANDLE_OFFSET(alen));
664     if (alen >= avc->f.m.Length) {
665         /*
666          * Special speedup since Sun's vm extends the file this way;
667          * we've never written to the file thus we can just set the new
668          * length and avoid the needless calls below.
669          * Also used for ftruncate calls which can extend the file.
670          * To completely minimize the possible extra StoreMini RPC, we really
671          * should keep the ExtendedPos as well and clear this flag if we
672          * truncate below that value before we store the file back.
673          */
674         avc->f.states |= CExtendedFile;
675         avc->f.m.Length = alen;
676         return 0;
677     }
678 #if     (defined(AFS_SUN5_ENV))
679
680     /* Zero unused portion of last page */
681     osi_VM_PreTruncate(avc, alen, acred);
682
683 #endif
684
685 #if     (defined(AFS_SUN5_ENV))
686     ObtainWriteLock(&avc->vlock, 546);
687     avc->activeV++;             /* Block new getpages */
688     ReleaseWriteLock(&avc->vlock);
689 #endif
690
691     ReleaseWriteLock(&avc->lock);
692     AFS_GUNLOCK();
693
694     /* Flush pages beyond end-of-file. */
695     osi_VM_Truncate(avc, alen, acred);
696
697     AFS_GLOCK();
698     ObtainWriteLock(&avc->lock, 79);
699
700     avc->f.m.Length = alen;
701
702     if (alen < avc->f.truncPos)
703         avc->f.truncPos = alen;
704     code = DVHash(&avc->f.fid);
705
706     /* block out others from screwing with this table */
707     ObtainWriteLock(&afs_xdcache, 287);
708
709     dcCount = 0;
710     for (index = afs_dvhashTbl[code]; index != NULLIDX;) {
711         if (afs_indexUnique[index] == avc->f.fid.Fid.Unique) {
712             tdc = afs_GetDSlot(index, 0);
713             ReleaseReadLock(&tdc->tlock);
714             if (!FidCmp(&tdc->f.fid, &avc->f.fid))
715                 dcCount++;
716             afs_PutDCache(tdc);
717         }
718         index = afs_dvnextTbl[index];
719     }
720
721     /* Now allocate space where we can save those dcache entries, and
722      * do a second pass over them..  Since we're holding xdcache, it
723      * shouldn't be changing.
724      */
725     tdcArray = osi_Alloc(dcCount * sizeof(struct dcache *));
726     dcPos = 0;
727
728     for (index = afs_dvhashTbl[code]; index != NULLIDX;) {
729         if (afs_indexUnique[index] == avc->f.fid.Fid.Unique) {
730             tdc = afs_GetDSlot(index, 0);
731             ReleaseReadLock(&tdc->tlock);
732             if (!FidCmp(&tdc->f.fid, &avc->f.fid)) {
733                 /* same file, and modified, we'll store it back */
734                 if (dcPos < dcCount) {
735                     tdcArray[dcPos++] = tdc;
736                 } else {
737                     afs_PutDCache(tdc);
738                 }
739             } else {
740                 afs_PutDCache(tdc);
741             }
742         }
743         index = afs_dvnextTbl[index];
744     }
745
746     ReleaseWriteLock(&afs_xdcache);
747
748     /* Now we loop over the array of dcache entries and truncate them */
749     for (index = 0; index < dcPos; index++) {
750         struct osi_file *tfile;
751
752         tdc = tdcArray[index];
753
754         newSize = alen - AFS_CHUNKTOBASE(tdc->f.chunk);
755         if (newSize < 0)
756             newSize = 0;
757         ObtainSharedLock(&tdc->lock, 672);
758         if (newSize < tdc->f.chunkBytes && newSize < MAX_AFS_UINT32) {
759             UpgradeSToWLock(&tdc->lock, 673);
760             tfile = afs_CFileOpen(&tdc->f.inode);
761             afs_CFileTruncate(tfile, (afs_int32)newSize);
762             afs_CFileClose(tfile);
763             afs_AdjustSize(tdc, (afs_int32)newSize);
764             if (alen < tdc->validPos) {
765                 if (alen < AFS_CHUNKTOBASE(tdc->f.chunk))
766                     tdc->validPos = 0;
767                 else
768                     tdc->validPos = alen;
769             }
770             ConvertWToSLock(&tdc->lock);
771         }
772         ReleaseSharedLock(&tdc->lock);
773         afs_PutDCache(tdc);
774     }
775
776     osi_Free(tdcArray, dcCount * sizeof(struct dcache *));
777
778 #if     (defined(AFS_SUN5_ENV))
779     ObtainWriteLock(&avc->vlock, 547);
780     if (--avc->activeV == 0 && (avc->vstates & VRevokeWait)) {
781         avc->vstates &= ~VRevokeWait;
782         afs_osi_Wakeup((char *)&avc->vstates);
783     }
784     ReleaseWriteLock(&avc->vlock);
785 #endif
786
787     return 0;
788 }