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