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