openbsd-20021108
[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 RCSID("$Header$");
17
18 #include "afs/sysincludes.h" /*Standard vendor system headers*/
19 #include "afsincludes.h" /*AFS-based standard headers*/
20 #include "afs/afs_stats.h"  /* statistics */
21 #include "afs/afs_cbqueue.h"
22 #include "afs/afs_osidnlc.h"
23
24 afs_uint32 afs_stampValue=0;
25
26 /*
27  * afs_StoreMini
28  *
29  * Description:
30  *      Send a truncation request to a FileServer.
31  *
32  * Parameters:
33  *      xxx : description
34  *
35  * Environment:
36  *      We're write-locked upon entry.
37  */
38
39 int afs_StoreMini(register struct vcache *avc, struct vrequest *areq)
40 {
41     register struct 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, base = 0;
48     XSTATS_DECLS
49
50     AFS_STATCNT(afs_StoreMini);
51     afs_Trace2(afs_iclSetp, CM_TRACE_STOREMINI, ICL_TYPE_POINTER, avc,
52                ICL_TYPE_INT32, avc->m.Length);
53     tlen = avc->m.Length;
54     if (avc->truncPos < tlen) tlen = avc->truncPos;
55     avc->truncPos = AFS_NOTRUNC;
56     avc->states &= ~CExtendedFile;
57
58     do {
59         tc = afs_Conn(&avc->fid, areq, SHARED_LOCK);
60         if (tc) {
61             RX_AFS_GUNLOCK();
62 retry:
63             tcall = rx_NewCall(tc->id);
64             RX_AFS_GLOCK();
65             /* Set the client mod time since we always want the file
66              * to have the client's mod time and not the server's one
67              * (to avoid problems with make, etc.) It almost always
68              * works fine with standard afs because them server/client
69              * times are in sync and more importantly this storemini
70              * it's a special call that would typically be followed by
71              * the proper store-data or store-status calls.
72              */
73             InStatus.Mask = AFS_SETMODTIME;
74             InStatus.ClientModTime = avc->m.Date;
75             XSTATS_START_TIME(AFS_STATS_FS_RPCIDX_STOREDATA);
76             afs_Trace4(afs_iclSetp, CM_TRACE_STOREDATA64, 
77                 ICL_TYPE_FID, &avc->fid.Fid,
78                 ICL_TYPE_OFFSET, ICL_HANDLE_OFFSET(base), 
79                 ICL_TYPE_OFFSET, ICL_HANDLE_OFFSET(tlen), 
80                 ICL_TYPE_OFFSET, ICL_HANDLE_OFFSET(avc->m.Length));
81             RX_AFS_GUNLOCK();
82 #ifdef AFS_64BIT_CLIENT
83             if (!afs_serverHasNo64Bit(tc)) {
84                 code = StartRXAFS_StoreData64(tcall,
85                                         (struct AFSFid *)&avc->fid.Fid,
86                                         &InStatus, avc->m.Length,
87                                         base, tlen);
88             } else {
89                 afs_int32 l1, l2;
90                 l1 = avc->m.Length;
91                 l2 = tlen;
92                 code = StartRXAFS_StoreData(tcall,
93                                         (struct AFSFid *)&avc->fid.Fid,
94                                         &InStatus, l1, 0, l2);
95             }
96 #else /* AFS_64BIT_CLIENT */
97             code = StartRXAFS_StoreData(tcall,
98                                         (struct AFSFid *)&avc->fid.Fid,
99                                         &InStatus, avc->m.Length, 0, tlen);
100 #endif /* AFS_64BIT_CLIENT */
101             if (code == 0) {
102                 code = EndRXAFS_StoreData(tcall, &OutStatus, &tsync);
103 #ifdef AFS_64BIT_CLIENT
104                 if (code == RXGEN_OPCODE) {
105                     afs_serverSetNo64Bit(tc);
106                     code = rx_EndCall(tcall, code);
107                     goto retry;
108                 }
109 #endif /* AFS_64BIT_CLIENT */
110             }
111             code = rx_EndCall(tcall, code);
112             RX_AFS_GLOCK();
113             XSTATS_END_TIME;
114         }
115         else code = -1;
116     } while
117         (afs_Analyze(tc, code, &avc->fid, areq,
118                      AFS_STATS_FS_RPCIDX_STOREDATA,
119                      SHARED_LOCK, NULL));
120
121     if (code == 0) {
122         afs_ProcessFS(avc, &OutStatus, areq);
123     }
124     else {
125         /* blew it away */
126         afs_InvalidateAllSegments(avc);
127     }
128     return code;
129
130 } /*afs_StoreMini*/
131
132 unsigned int storeallmissing = 0;
133 #define lmin(a,b) (((a) < (b)) ? (a) : (b))
134 /*
135  * afs_StoreAllSegments
136  *
137  * Description:
138  *      Stores all modified segments back to server
139  *
140  * Parameters:
141  *      avc  : Pointer to vcache entry.
142  *      areq : Pointer to request structure.
143  *
144  * Environment:
145  *      Called with avc write-locked.
146  */
147 #if defined (AFS_HPUX_ENV) || defined(AFS_ULTRIX_ENV)
148 int NCHUNKSATONCE = 3;
149 #else
150 int NCHUNKSATONCE = 64 ;
151 #endif
152 int afs_dvhack=0;
153
154
155 int afs_StoreAllSegments(register struct vcache *avc, struct vrequest *areq, 
156         int sync)
157 {
158     register struct dcache *tdc;
159     register afs_int32 code=0;
160     register afs_int32 index;
161     register afs_int32 origCBs, foreign=0;
162     int hash, stored;
163     afs_hyper_t newDV, oldDV;   /* DV when we start, and finish, respectively */
164     struct dcache **dcList, **dclist;
165     unsigned int i, j, minj, moredata, high, off;
166     afs_size_t tlen;
167     afs_size_t maxStoredLength; /* highest offset we've written to server. */
168     int safety;
169 #ifndef AFS_NOSTATS
170     struct afs_stats_xferData *xferP;   /* Ptr to this op's xfer struct */
171     osi_timeval_t  xferStartTime,       /*FS xfer start time*/
172                    xferStopTime;        /*FS xfer stop time*/
173     afs_size_t bytesToXfer;                     /* # bytes to xfer*/
174     afs_size_t bytesXferred;                    /* # bytes actually xferred*/
175 #endif /* AFS_NOSTATS */
176
177
178     AFS_STATCNT(afs_StoreAllSegments);
179  
180     hset(oldDV, avc->m.DataVersion);
181     hset(newDV, avc->m.DataVersion);
182     hash = DVHash(&avc->fid);
183     foreign = (avc->states & CForeign);
184     dcList = (struct dcache **) osi_AllocLargeSpace(AFS_LRALLOCSIZ);
185     afs_Trace2(afs_iclSetp, CM_TRACE_STOREALL, ICL_TYPE_POINTER, avc,
186                ICL_TYPE_OFFSET, ICL_HANDLE_OFFSET(avc->m.Length));
187 #if !defined(AFS_AIX32_ENV) && !defined(AFS_SGI65_ENV)
188     /* In the aix vm implementation we need to do the vm_writep even
189      * on the memcache case since that's we adjust the file's size
190      * and finish flushing partial vm pages.
191      */
192     if (cacheDiskType != AFS_FCACHE_TYPE_MEM) 
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
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   retry:
237     maxStoredLength = 0;
238     tlen = avc->m.Length;
239     minj = 0 ; 
240
241     do {
242       memset((char *)dcList, 0, NCHUNKSATONCE * sizeof(struct dcache *));
243       high = 0;
244       moredata = FALSE;
245
246       /* lock and start over from beginning of hash chain 
247        * in order to avoid a race condition. */
248       MObtainWriteLock(&afs_xdcache,284);  
249       index = afs_dvhashTbl[hash];
250     
251       for(j=0; index != NULLIDX;) {
252         if ((afs_indexFlags[index] & IFDataMod) &&
253             (afs_indexUnique[index] == avc->fid.Fid.Unique)) {
254           tdc = afs_GetDSlot(index, 0);  /* refcount+1. */
255           ReleaseReadLock(&tdc->tlock);
256           if (!FidCmp( &tdc->f.fid, &avc->fid ) && tdc->f.chunk >= minj ) {
257             off = tdc->f.chunk - minj;
258             if (off < NCHUNKSATONCE) {
259               if ( dcList[ off ] )
260                 osi_Panic("dclist slot already in use!");
261               dcList[ off ] = tdc;
262               if (off > high) 
263                 high = off;
264               j++;
265               /* DCLOCKXXX: chunkBytes is protected by tdc->lock which we
266                * can't grab here, due to lock ordering with afs_xdcache.
267                * So, disable this shortcut for now.  -- kolya 2001-10-13
268                */
269               /* shortcut: big win for little files */
270               /* tlen -= tdc->f.chunkBytes;
271                * if (tlen <= 0)
272                *    break;
273                */
274             }
275             else {
276               moredata = TRUE;
277               afs_PutDCache(tdc);
278               if (j == NCHUNKSATONCE)
279                 break;
280             }
281           } else {
282             afs_PutDCache(tdc);
283           }
284         }
285         index = afs_dvnextTbl[index];
286       }
287       MReleaseWriteLock(&afs_xdcache);
288
289       /* this guy writes chunks, puts back dcache structs, and bumps newDV */
290       /* "moredata" just says "there are more dirty chunks yet to come".
291        */
292       if (j) {
293 #ifdef AFS_NOSTATS
294         static afs_uint32 lp1 = 10000, lp2 = 10000;
295 #endif
296         struct AFSStoreStatus InStatus;
297         struct AFSFetchStatus OutStatus;
298         int doProcessFS = 0;
299         afs_size_t base, bytes;
300         afs_uint32 nchunks;
301         int nomore;
302         unsigned int first;
303         int *shouldwake;
304         struct conn * tc;
305         struct osi_file * tfile;
306         struct rx_call * tcall;
307         XSTATS_DECLS
308
309         for (bytes = 0, j = 0; !code && j<=high; j++) {
310           if (dcList[j]) {
311             ObtainSharedLock(&(dcList[j]->lock), 629);
312             if (!bytes)
313               first = j;
314             bytes += dcList[j]->f.chunkBytes;
315             if ((dcList[j]->f.chunkBytes < afs_OtherCSize)
316                 && (dcList[j]->f.chunk - minj < high)
317                 && dcList[j+1]) {
318                 int sbytes = afs_OtherCSize - dcList[j]->f.chunkBytes;
319                 bytes += sbytes;
320             }
321           }         
322           if (bytes && (j==high || !dcList[j+1])) {
323             /* base = AFS_CHUNKTOBASE(dcList[first]->f.chunk); */
324             base = AFS_CHUNKTOBASE(first + minj) ;
325             /*
326              * 
327              * take a list of dcache structs and send them all off to the server
328              * the list must be in order, and the chunks contiguous.
329              * Note - there is no locking done by this code currently.  For
330              * safety's sake, xdcache could be locked over the entire call.
331              * However, that pretty well ties up all the threads.  Meantime, all
332              * the chunks _MUST_ have their refcounts bumped.
333              * The writes done before a store back will clear setuid-ness
334              * in cache file.
335              * We can permit CacheStoreProc to wake up the user process IFF we 
336              * are doing the last RPC for this close, ie, storing back the last 
337              * set of contiguous chunks of a file.
338              */
339
340             dclist = &dcList[first];
341             nchunks = 1+j-first;
342             nomore = !(moredata || (j!=high));
343             InStatus.ClientModTime = avc->m.Date;
344             InStatus.Mask = AFS_SETMODTIME;
345             if (sync & AFS_SYNC) {
346                 InStatus.Mask |= AFS_FSYNC;
347             }
348             tlen = lmin(avc->m.Length, avc->truncPos);
349             afs_Trace4(afs_iclSetp, CM_TRACE_STOREDATA64, 
350                 ICL_TYPE_FID, &avc->fid.Fid,
351                 ICL_TYPE_OFFSET, ICL_HANDLE_OFFSET(base), 
352                 ICL_TYPE_OFFSET, ICL_HANDLE_OFFSET(bytes), 
353                 ICL_TYPE_OFFSET, ICL_HANDLE_OFFSET(tlen));
354
355             do {
356                 stored = 0;
357                 tc = afs_Conn(&avc->fid, areq, 0);
358                 if (tc) {
359 restart:
360                     RX_AFS_GUNLOCK();
361                     tcall = rx_NewCall(tc->id);
362 #ifdef AFS_64BIT_CLIENT
363                     if (!afs_serverHasNo64Bit(tc)) {
364                         code = StartRXAFS_StoreData64(tcall, 
365                                 (struct AFSFid *) &avc->fid.Fid,
366                                 &InStatus, base, bytes, tlen);
367                     } else {
368                         if (tlen > 0xFFFFFFFF) {
369                             code = EFBIG;
370                         } else {
371                             afs_int32 t1, t2, t3;
372                             t1 = base;
373                             t2 = bytes;
374                             t3 = tlen;
375                             code = StartRXAFS_StoreData(tcall, 
376                                         (struct AFSFid *) &avc->fid.Fid,
377                                         &InStatus, t1, t2, t3);
378                         }
379                     }
380 #else /* AFS_64BIT_CLIENT */
381                     code = StartRXAFS_StoreData(tcall, (struct AFSFid *) &avc->fid.Fid,
382                                                 &InStatus, base, bytes, tlen);
383 #endif /* AFS_64BIT_CLIENT */
384                     RX_AFS_GLOCK();
385                 } else {
386                     code = -1;
387                     tcall = NULL;
388                 }
389                 if (!code) {
390                     XSTATS_START_TIME(AFS_STATS_FS_RPCIDX_STOREDATA);
391                     avc->truncPos = AFS_NOTRUNC;
392                 }
393                 for (i = 0; i<nchunks && !code;i++) {
394                     tdc = dclist[i];
395                     if (!tdc) {
396                         afs_warn("afs: missing dcache!\n");
397                         storeallmissing++;
398                         continue; /* panic? */
399                     }
400                     afs_Trace4(afs_iclSetp, CM_TRACE_STOREALL2,
401                         ICL_TYPE_POINTER, avc, 
402                         ICL_TYPE_INT32, tdc->f.chunk,
403                         ICL_TYPE_INT32, tdc->index,
404                         ICL_TYPE_INT32, tdc->f.inode);
405                     shouldwake = 0;
406                     if (nomore) {
407                        if (avc->asynchrony == -1) {
408                           if (afs_defaultAsynchrony > (bytes-stored)) {
409                              shouldwake = &nomore;
410                           }
411                        } else if ((afs_uint32)avc->asynchrony >= (bytes-stored)) {
412                           shouldwake = &nomore;
413                        }
414                     }
415                     tfile = afs_CFileOpen(tdc->f.inode);
416 #ifndef AFS_NOSTATS
417                     xferP = &(afs_stats_cmfullperf.rpc.fsXferTimes[AFS_STATS_FS_XFERIDX_STOREDATA]);
418                     osi_GetuTime(&xferStartTime);
419
420                     code = afs_CacheStoreProc(tcall, tfile, tdc->f.chunkBytes,
421                                               avc, shouldwake, &bytesToXfer,
422                                               &bytesXferred);
423
424                     osi_GetuTime(&xferStopTime);
425                     (xferP->numXfers)++;
426                     if (!code) {
427                         (xferP->numSuccesses)++;
428                         afs_stats_XferSumBytes[AFS_STATS_FS_XFERIDX_STOREDATA] += bytesXferred;
429                         (xferP->sumBytes) += (afs_stats_XferSumBytes[AFS_STATS_FS_XFERIDX_STOREDATA] >> 10);
430                         afs_stats_XferSumBytes[AFS_STATS_FS_XFERIDX_STOREDATA] &= 0x3FF;
431                         if (bytesXferred < xferP->minBytes)
432                            xferP->minBytes = bytesXferred;
433                         if (bytesXferred > xferP->maxBytes)
434                            xferP->maxBytes = bytesXferred;
435                     
436                       /*
437                        * Tally the size of the object.  Note: we tally the actual size,
438                        * NOT the number of bytes that made it out over the wire.
439                        */
440                         if (bytesToXfer <= AFS_STATS_MAXBYTES_BUCKET0)
441                             (xferP->count[0])++;
442                         else
443                             if (bytesToXfer <= AFS_STATS_MAXBYTES_BUCKET1)
444                                 (xferP->count[1])++;
445                         else
446                             if (bytesToXfer <= AFS_STATS_MAXBYTES_BUCKET2)
447                                 (xferP->count[2])++;
448                         else
449                             if (bytesToXfer <= AFS_STATS_MAXBYTES_BUCKET3)
450                                 (xferP->count[3])++;
451                         else
452                             if (bytesToXfer <= AFS_STATS_MAXBYTES_BUCKET4)
453                                 (xferP->count[4])++;
454                         else
455                             if (bytesToXfer <= AFS_STATS_MAXBYTES_BUCKET5)
456                                 (xferP->count[5])++;
457                         else
458                             if (bytesToXfer <= AFS_STATS_MAXBYTES_BUCKET6)
459                                 (xferP->count[6])++;
460                         else
461                             if (bytesToXfer <= AFS_STATS_MAXBYTES_BUCKET7)
462                                 (xferP->count[7])++;
463                         else
464                             (xferP->count[8])++;
465
466                         afs_stats_GetDiff(elapsedTime, xferStartTime, xferStopTime);
467                         afs_stats_AddTo((xferP->sumTime), elapsedTime);
468                         afs_stats_SquareAddTo((xferP->sqrTime), elapsedTime);
469                         if (afs_stats_TimeLessThan(elapsedTime, (xferP->minTime))) {
470                            afs_stats_TimeAssign((xferP->minTime), elapsedTime);
471                         }
472                         if (afs_stats_TimeGreaterThan(elapsedTime, (xferP->maxTime))) {
473                            afs_stats_TimeAssign((xferP->maxTime), elapsedTime);
474                         }
475                       }
476 #else
477                     code = afs_CacheStoreProc(tcall, tfile, tdc->f.chunkBytes, 
478                                                 avc, shouldwake, &lp1, &lp2);
479 #endif /* AFS_NOSTATS */
480                     afs_CFileClose(tfile);
481 #ifdef AFS_64BIT_CLIENT
482                     if (code == RXGEN_OPCODE) {
483                         afs_serverSetNo64Bit(tc);
484                         goto restart;
485                     }
486 #endif /* AFS_64BIT_CLIENT */
487                     if ((tdc->f.chunkBytes < afs_OtherCSize) && 
488                         (i < (nchunks-1))) {
489                        int bsent, tlen, sbytes = afs_OtherCSize - tdc->f.chunkBytes;
490                        char *tbuffer = osi_AllocLargeSpace(AFS_LRALLOCSIZ);
491  
492                        while (sbytes > 0) {
493                            tlen = (sbytes > AFS_LRALLOCSIZ ? AFS_LRALLOCSIZ : sbytes);
494                            memset(tbuffer, 0, tlen);
495                            RX_AFS_GUNLOCK();
496                            bsent = rx_Write(tcall, tbuffer, tlen);
497                            RX_AFS_GLOCK();
498
499                            if (bsent != tlen) {
500                                code = -33;     /* XXX */
501                                break;
502                            }
503                            sbytes -= tlen;
504                        }
505                        osi_FreeLargeSpace(tbuffer);
506                     }    
507                     stored += tdc->f.chunkBytes;
508
509                     /* ideally, I'd like to unlock the dcache and turn
510                      * off the writing bit here, but that would
511                      * require being able to retry StoreAllSegments in
512                      * the event of a failure. It only really matters
513                      * if user can't read from a 'locked' dcache or
514                      * one which has the writing bit turned on. */
515                 }
516                 if (!code) {
517                     struct AFSVolSync tsync;
518                     RX_AFS_GUNLOCK();
519                     code = EndRXAFS_StoreData(tcall, &OutStatus, &tsync);
520                     RX_AFS_GLOCK();
521                     hadd32(newDV, 1);
522                     XSTATS_END_TIME;
523                     if (!code) doProcessFS = 1; /* Flag to run afs_ProcessFS() later on */
524                 }
525                 if (tcall) {
526                     RX_AFS_GUNLOCK();
527                     code = rx_EndCall(tcall, code);  
528                     RX_AFS_GLOCK();
529                 }
530             } while (afs_Analyze(tc, code, &avc->fid, areq,
531                                  AFS_STATS_FS_RPCIDX_STOREDATA,
532                                  SHARED_LOCK, NULL));
533
534             /* put back all remaining locked dcache entries */  
535             for (i=0; i<nchunks; i++) {
536                 tdc = dclist[i];
537                 if (!code) {
538                     if (afs_indexFlags[tdc->index] & IFDataMod) {
539                         /*
540                          * LOCKXXX -- should hold afs_xdcache(W) when
541                          * modifying afs_indexFlags.
542                          */
543                         afs_indexFlags[tdc->index] &= ~IFDataMod;
544                         afs_stats_cmperf.cacheCurrDirtyChunks--;
545                         afs_indexFlags[tdc->index] &= ~IFDirtyPages;
546                         if ( sync & AFS_VMSYNC_INVAL )
547                         {
548                             /* since we have invalidated all the pages of this
549                             ** vnode by calling osi_VM_TryToSmush, we can
550                             ** safely mark this dcache entry as not having
551                             ** any pages. This vnode now becomes eligible for
552                             ** reclamation by getDownD.
553                             */
554                             afs_indexFlags[tdc->index] &= ~IFAnyPages;
555                         }
556                     }
557                 }
558                 UpgradeSToWLock(&tdc->lock, 628);
559                 tdc->f.states &= ~DWriting;  /* correct?*/
560                 tdc->dflags |= DFEntryMod;
561                 ReleaseWriteLock(&tdc->lock);
562                 afs_PutDCache(tdc);
563                 /* Mark the entry as released */
564                 dclist[i] = NULL;
565             }
566
567             if (doProcessFS) {
568                 /* Now copy out return params */
569                 UpgradeSToWLock(&avc->lock,28);    /* keep out others for a while */
570                 afs_ProcessFS(avc, &OutStatus, areq);
571                 /* Keep last (max) size of file on server to see if
572                  * we need to call afs_StoreMini to extend the file.
573                  */
574                 if (!moredata)
575                     maxStoredLength = OutStatus.Length;
576                 ConvertWToSLock(&avc->lock);
577                 doProcessFS = 0;
578             }
579
580             if (code) {
581                 for (j++; j<=high; j++) {
582                     if ( dcList[j] ) {
583                         ReleaseSharedLock(&(dcList[j]->lock));
584                         afs_PutDCache(dcList[j]);
585                         /* Releasing entry */
586                         dcList[j] = NULL;
587                     }
588                 }
589             }
590
591             afs_Trace2(afs_iclSetp, CM_TRACE_STOREALLDCDONE,
592                        ICL_TYPE_POINTER, avc, ICL_TYPE_INT32, code);
593             bytes = 0;
594           }
595         }
596         
597         /* Release any zero-length dcache entries in our interval
598          * that we locked but didn't store back above.
599          */
600         for (j = 0; j<=high; j++) {
601           tdc = dcList[j];
602           if (tdc) {
603             osi_Assert(tdc->f.chunkBytes == 0);
604             ReleaseSharedLock(&tdc->lock);
605             afs_PutDCache(tdc);
606           }
607         }
608       } /* if (j) */
609
610     minj += NCHUNKSATONCE;
611     } while ( !code && moredata ); 
612     
613     UpgradeSToWLock(&avc->lock,29);
614
615   /* send a trivial truncation store if did nothing else */
616   if (code == 0) {
617     /*
618      * Call StoreMini if we haven't written enough data to extend the
619      * file at the fileserver to the client's notion of the file length.
620      */
621     if ((avc->truncPos != AFS_NOTRUNC) ||
622         ((avc->states & CExtendedFile) && (maxStoredLength < avc->m.Length))) {
623       code = afs_StoreMini(avc, areq);
624       if (code == 0)
625         hadd32(newDV, 1);       /* just bumped here, too */
626     }
627     avc->states &= ~CExtendedFile;
628   }
629   
630   /*
631    * Finally, turn off DWriting, turn on DFEntryMod,
632    * update f.versionNo.
633    * A lot of this could be integrated into the loop above 
634    */
635     if (!code) {
636       afs_hyper_t h_unset;
637       hones(h_unset);
638
639       minj = 0;
640
641       do {
642         moredata = FALSE;
643         memset((char *)dcList, 0, NCHUNKSATONCE * sizeof(struct dcache *));
644
645         /* overkill, but it gets the lock in case GetDSlot needs it */
646         MObtainWriteLock(&afs_xdcache,285);
647
648         for(j = 0, safety = 0, index = afs_dvhashTbl[hash]; 
649             index != NULLIDX && safety < afs_cacheFiles+2;) {
650
651             if (afs_indexUnique[index] == avc->fid.Fid.Unique) {
652                 tdc = afs_GetDSlot(index, 0);
653                 ReleaseReadLock(&tdc->tlock);
654
655                 if (!FidCmp(&tdc->f.fid, &avc->fid) && tdc->f.chunk >= minj) {
656                     off = tdc->f.chunk - minj;
657                     if (off < NCHUNKSATONCE) {
658                         /* this is the file, and the correct chunk range */
659                         if (j >= NCHUNKSATONCE)
660                             osi_Panic("Too many dcache entries in range\n");
661                         dcList[j++] = tdc;
662                     } else {
663                         moredata = TRUE;
664                         afs_PutDCache(tdc);
665                         if (j == NCHUNKSATONCE)
666                             break;
667                     }
668                 } else {
669                     afs_PutDCache(tdc);
670                 }
671             }
672
673             index = afs_dvnextTbl[index];
674         }
675         MReleaseWriteLock(&afs_xdcache);
676
677         for (i=0; i<j; i++) {
678             /* Iterate over the dcache entries we collected above */
679             tdc = dcList[i];
680             ObtainSharedLock(&tdc->lock, 677);
681
682             /* was code here to clear IFDataMod, but it should only be done
683              * in storedcache and storealldcache.
684              */
685             /* Only increase DV if we had up-to-date data to start with.
686              * Otherwise, we could be falsely upgrading an old chunk
687              * (that we never read) into one labelled with the current
688              * DV #.  Also note that we check that no intervening stores
689              * occurred, otherwise we might mislabel cache information
690              * for a chunk that we didn't store this time
691              */
692              /* Don't update the version number if it's not yet set. */
693             if (!hsame(tdc->f.versionNo, h_unset) &&
694                 hcmp(tdc->f.versionNo, oldDV) >= 0) {
695
696                 if ((!(afs_dvhack || foreign) && hsame(avc->m.DataVersion, newDV))
697                     || ((afs_dvhack || foreign) && (origCBs == afs_allCBs)) ) {
698                     /* no error, this is the DV */
699
700                     UpgradeSToWLock(&tdc->lock, 678);
701                     hset(tdc->f.versionNo, avc->m.DataVersion);
702                     tdc->dflags |= DFEntryMod;
703                     ConvertWToSLock(&tdc->lock);
704                 }
705             }
706
707             ReleaseSharedLock(&tdc->lock);
708             afs_PutDCache(tdc);
709         }
710
711         minj += NCHUNKSATONCE;
712
713       } while (moredata);
714     }
715
716     if (code) {
717         /*
718          * Invalidate chunks after an error for ccores files since
719          * afs_inactive won't be called for these and they won't be
720          * invalidated. Also discard data if it's a permanent error from the
721          * fileserver.
722          */
723         if (areq->permWriteError || (avc->states & (CCore1 | CCore))) {
724             afs_InvalidateAllSegments(avc);
725         }
726     }
727     afs_Trace3(afs_iclSetp, CM_TRACE_STOREALLDONE, ICL_TYPE_POINTER, avc,
728                ICL_TYPE_INT32, avc->m.Length, ICL_TYPE_INT32, code);
729     /* would like a Trace5, but it doesn't exist...*/
730     afs_Trace3(afs_iclSetp, CM_TRACE_AVCLOCKER, ICL_TYPE_POINTER, avc,
731                ICL_TYPE_INT32, avc->lock.wait_states, 
732                ICL_TYPE_INT32, avc->lock.excl_locked);
733     afs_Trace4(afs_iclSetp, CM_TRACE_AVCLOCKEE, ICL_TYPE_POINTER, avc,
734                ICL_TYPE_INT32, avc->lock.wait_states, 
735                ICL_TYPE_INT32, avc->lock.readers_reading, 
736                ICL_TYPE_INT32, avc->lock.num_waiting );
737   
738     /*
739      * Finally, if updated DataVersion matches newDV, we did all of the
740      * stores.  If mapDV indicates that the page cache was flushed up
741      * to when we started the store, then we can relabel them as flushed
742      * as recently as newDV.
743      * Turn off CDirty bit because the stored data is now in sync with server.
744      */
745     if (code == 0 && hcmp(avc->mapDV, oldDV) >= 0) {
746       if ((!(afs_dvhack || foreign) && hsame(avc->m.DataVersion, newDV))
747           || ((afs_dvhack || foreign) && (origCBs == afs_allCBs)) ) {
748           hset(avc->mapDV, newDV);
749           avc->states &= ~CDirty;
750       }
751     }
752     osi_FreeLargeSpace(dcList);
753
754     /* If not the final write a temporary error is ok. */
755     if (code && !areq->permWriteError && !(sync & AFS_LASTSTORE))
756         code = 0;
757
758     return code;
759   
760 } /*afs_StoreAllSegments (new 03/02/94)*/
761
762
763 /*
764  * afs_InvalidateAllSegments
765  *
766  * Description:
767  *      Invalidates all chunks for a given file
768  *
769  * Parameters:
770  *      avc      : Pointer to vcache entry.
771  *
772  * Environment:
773  *      For example, called after an error has been detected.  Called
774  *      with avc write-locked, and afs_xdcache unheld.
775  */
776    
777 int afs_InvalidateAllSegments(struct vcache *avc)
778 {
779     struct dcache *tdc;
780     afs_int32 hash;
781     afs_int32 index;
782     struct dcache **dcList;
783     int i, dcListMax, dcListCount;
784
785     AFS_STATCNT(afs_InvalidateAllSegments);
786     afs_Trace2(afs_iclSetp, CM_TRACE_INVALL, ICL_TYPE_POINTER, avc,
787                ICL_TYPE_OFFSET, ICL_HANDLE_OFFSET(avc->m.Length));
788     hash = DVHash(&avc->fid);
789     avc->truncPos = AFS_NOTRUNC;  /* don't truncate later */
790     avc->states &= ~CExtendedFile; /* not any more */
791     ObtainWriteLock(&afs_xcbhash, 459);
792     afs_DequeueCallback(avc);
793     avc->states &= ~(CStatd|CDirty); /* mark status information as bad, too */
794     ReleaseWriteLock(&afs_xcbhash);
795     if (avc->fid.Fid.Vnode & 1 || (vType(avc) == VDIR))
796         osi_dnlc_purgedp(avc);
797     /* Blow away pages; for now, only for Solaris */
798 #if     (defined(AFS_SUN5_ENV))
799     if (WriteLocked(&avc->lock))
800         osi_ReleaseVM(avc, (struct AFS_UCRED *)0);
801 #endif
802     /*
803      * Block out others from screwing with this table; is a read lock
804      * sufficient?
805      */
806     MObtainWriteLock(&afs_xdcache,286);
807     dcListMax = 0;
808
809     for(index = afs_dvhashTbl[hash]; index != NULLIDX;) {
810         if (afs_indexUnique[index] == avc->fid.Fid.Unique) {
811             tdc = afs_GetDSlot(index, 0);
812             ReleaseReadLock(&tdc->tlock);
813             if (!FidCmp(&tdc->f.fid, &avc->fid))
814                 dcListMax++;
815             afs_PutDCache(tdc);
816         }
817         index = afs_dvnextTbl[index];
818     }
819
820     dcList = osi_Alloc(dcListMax * sizeof(struct dcache *));
821     dcListCount = 0;
822
823     for(index = afs_dvhashTbl[hash]; index != NULLIDX;) {
824         if (afs_indexUnique[index] == avc->fid.Fid.Unique) {
825             tdc = afs_GetDSlot(index, 0);
826             ReleaseReadLock(&tdc->tlock);
827             if (!FidCmp(&tdc->f.fid, &avc->fid)) {
828                 /* same file? we'll zap it */
829                 if (afs_indexFlags[index] & IFDataMod) {
830                     afs_stats_cmperf.cacheCurrDirtyChunks--;
831                     /* don't write it back */
832                     afs_indexFlags[index] &= ~IFDataMod;
833                 }
834                 afs_indexFlags[index] &= ~IFAnyPages;
835                 if (dcListCount < dcListMax)
836                     dcList[dcListCount++] = tdc;
837                 else
838                     afs_PutDCache(tdc);
839             } else {
840                 afs_PutDCache(tdc);
841             }
842         }
843         index = afs_dvnextTbl[index];
844     }
845     MReleaseWriteLock(&afs_xdcache);
846
847     for (i=0; i<dcListCount; i++) {
848         tdc = dcList[i];
849
850         ObtainWriteLock(&tdc->lock, 679);
851         ZapDCE(tdc);
852         if (vType(avc) == VDIR)
853             DZap(&tdc->f.inode);
854         ReleaseWriteLock(&tdc->lock);
855         afs_PutDCache(tdc);
856     }
857
858     osi_Free(dcList, dcListMax * sizeof(struct dcache *));
859
860     return 0;
861 }
862
863
864 /*
865  * afs_TruncateAllSegments
866  *
867  * Description:
868  *      Truncate a cache file.
869  *
870  * Parameters:
871  *      avc  : Ptr to vcache entry to truncate.
872  *      alen : Number of bytes to make the file.
873  *      areq : Ptr to request structure.
874  *
875  * Environment:
876  *      Called with avc write-locked; in VFS40 systems, pvnLock is also
877  *      held.
878  */
879 int afs_TruncateAllSegments(register struct vcache *avc, afs_size_t alen, 
880         struct vrequest *areq, struct AFS_UCRED *acred)
881 {
882     register struct dcache *tdc;
883     register afs_int32 code;
884     register afs_int32 index;
885     afs_int32 newSize;
886
887     int dcCount, dcPos;
888     struct dcache **tdcArray;
889
890     AFS_STATCNT(afs_TruncateAllSegments);
891     avc->m.Date = osi_Time();
892     afs_Trace3(afs_iclSetp, CM_TRACE_TRUNCALL, ICL_TYPE_POINTER, avc,
893                         ICL_TYPE_OFFSET, ICL_HANDLE_OFFSET(avc->m.Length), 
894                         ICL_TYPE_OFFSET, ICL_HANDLE_OFFSET(alen));
895     if (alen >= avc->m.Length) {
896         /*
897          * Special speedup since Sun's vm extends the file this way;
898          * we've never written to the file thus we can just set the new
899          * length and avoid the needless calls below.
900          * Also used for ftruncate calls which can extend the file.
901          * To completely minimize the possible extra StoreMini RPC, we really
902          * should keep the ExtendedPos as well and clear this flag if we
903          * truncate below that value before we store the file back.
904          */
905         avc->states |= CExtendedFile;
906         avc->m.Length = alen;
907         return 0;
908     }
909
910 #if     (defined(AFS_SUN5_ENV))
911
912     /* Zero unused portion of last page */
913     osi_VM_PreTruncate(avc, alen, acred);
914
915 #endif
916
917 #if     (defined(AFS_SUN5_ENV))
918     ObtainWriteLock(&avc->vlock, 546);
919     avc->activeV++;             /* Block new getpages */
920     ReleaseWriteLock(&avc->vlock);
921 #endif
922
923     ReleaseWriteLock(&avc->lock);
924     AFS_GUNLOCK();
925
926     /* Flush pages beyond end-of-file. */
927     osi_VM_Truncate(avc, alen, acred);
928
929     AFS_GLOCK();
930     ObtainWriteLock(&avc->lock,79);
931
932     avc->m.Length = alen;
933     
934     if (alen < avc->truncPos) avc->truncPos = alen;
935     code = DVHash(&avc->fid);
936
937     /* block out others from screwing with this table */
938     MObtainWriteLock(&afs_xdcache,287);
939
940     dcCount = 0;
941     for(index = afs_dvhashTbl[code]; index != NULLIDX;) {
942       if (afs_indexUnique[index] == avc->fid.Fid.Unique) {
943         tdc = afs_GetDSlot(index, 0);
944         ReleaseReadLock(&tdc->tlock);
945         if (!FidCmp(&tdc->f.fid, &avc->fid))
946             dcCount++;
947         afs_PutDCache(tdc);
948       }
949       index = afs_dvnextTbl[index];
950     }
951
952     /* Now allocate space where we can save those dcache entries, and
953      * do a second pass over them..  Since we're holding xdcache, it
954      * shouldn't be changing.
955      */
956     tdcArray = osi_Alloc(dcCount * sizeof(struct dcache *));
957     dcPos = 0;
958
959     for(index = afs_dvhashTbl[code]; index != NULLIDX;) {
960       if (afs_indexUnique[index] == avc->fid.Fid.Unique) {
961         tdc = afs_GetDSlot(index, 0);
962         ReleaseReadLock(&tdc->tlock);
963         if (!FidCmp(&tdc->f.fid, &avc->fid)) {
964             /* same file, and modified, we'll store it back */
965             if (dcPos < dcCount) {
966                 tdcArray[dcPos++] = tdc;
967             } else {
968                 afs_PutDCache(tdc);
969             }
970         } else {
971             afs_PutDCache(tdc);
972         }
973       }
974       index = afs_dvnextTbl[index];
975     }
976
977     MReleaseWriteLock(&afs_xdcache);
978
979     /* Now we loop over the array of dcache entries and truncate them */
980     for (index = 0; index < dcPos; index++) {
981         struct osi_file *tfile;
982
983         tdc = tdcArray[index];
984
985         newSize = alen - AFS_CHUNKTOBASE(tdc->f.chunk);
986         if (newSize < 0) newSize = 0;
987         ObtainSharedLock(&tdc->lock, 672);
988         if (newSize < tdc->f.chunkBytes) {
989             UpgradeSToWLock(&tdc->lock, 673);
990             tfile = afs_CFileOpen(tdc->f.inode);
991             afs_CFileTruncate(tfile, newSize);
992             afs_CFileClose(tfile);
993             afs_AdjustSize(tdc, newSize);
994             ConvertWToSLock(&tdc->lock);
995         }
996         ReleaseSharedLock(&tdc->lock);
997         afs_PutDCache(tdc);
998     }
999
1000     osi_Free(tdcArray, dcCount * sizeof(struct dcache *));
1001
1002 #if     (defined(AFS_SUN5_ENV))
1003     ObtainWriteLock(&avc->vlock, 547);
1004     if (--avc->activeV == 0 && (avc->vstates & VRevokeWait)) {
1005         avc->vstates &= ~VRevokeWait;
1006         afs_osi_Wakeup((char *)&avc->vstates);
1007     }
1008     ReleaseWriteLock(&avc->vlock);
1009 #endif
1010     return 0;
1011 }