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