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