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