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