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