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