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