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