windows-callp-to-rxcallp-20080721
[openafs.git] / src / WINNT / afsd / cm_vnodeops.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 #include <afs/param.h>
11 #include <afs/stds.h>
12
13 #include <windows.h>
14 #include <winsock2.h>
15 #include <stddef.h>
16 #include <malloc.h>
17 #include <string.h>
18 #include <stdlib.h>
19 #include <errno.h>
20
21 #include <osi.h>
22
23 #include "afsd.h"
24 #include "smb.h"
25 #include "cm_btree.h"
26
27 #include <strsafe.h>
28
29 #ifdef DEBUG
30 extern void afsi_log(char *pattern, ...);
31 #endif
32
33 int cm_enableServerLocks = 1;
34
35 int cm_followBackupPath = 0;
36
37 /*
38  * Case-folding array.  This was constructed by inspecting of SMBtrace output.
39  * I do not know anything more about it.
40  */
41 unsigned char cm_foldUpper[256] = {
42      0x0,  0x1,  0x2,  0x3,  0x4,  0x5,  0x6,  0x7,
43      0x8,  0x9,  0xa,  0xb,  0xc,  0xd,  0xe,  0xf,
44     0x10, 0x11, 0x12, 0x13, 0x14, 0x15, 0x16, 0x17,
45     0x18, 0x19, 0x1a, 0x1b, 0x1c, 0x1d, 0x1e, 0x1f,
46     0x20, 0x21, 0x22, 0x23, 0x24, 0x25, 0x26, 0x27,
47     0x28, 0x29, 0x2a, 0x2b, 0x2c, 0x2d, 0x2e, 0x2f,
48     0x30, 0x31, 0x32, 0x33, 0x34, 0x35, 0x36, 0x37,
49     0x38, 0x39, 0x3a, 0x3b, 0x3c, 0x3d, 0x3e, 0x3f,
50     0x40, 0x41, 0x42, 0x43, 0x44, 0x45, 0x46, 0x47,
51     0x48, 0x49, 0x4a, 0x4b, 0x4c, 0x4d, 0x4e, 0x4f,
52     0x50, 0x51, 0x52, 0x53, 0x54, 0x55, 0x56, 0x57,
53     0x58, 0x59, 0x5a, 0x5b, 0x5c, 0x5d, 0x5e, 0x5f,
54     0x60, 0x41, 0x42, 0x43, 0x44, 0x45, 0x46, 0x47,
55     0x48, 0x49, 0x4a, 0x4b, 0x4c, 0x4d, 0x4e, 0x4f,
56     0x50, 0x51, 0x52, 0x53, 0x54, 0x55, 0x56, 0x57,
57     0x58, 0x59, 0x5a, 0x7b, 0x7c, 0x7d, 0x7e, 0x7f,
58     0x80, 0x9a, 0x90, 0x41, 0x8e, 0x41, 0x8f, 0x80,
59     0x45, 0x45, 0x45, 0x49, 0x49, 0x49, 0x8e, 0x8f,
60     0x90, 0x92, 0x92, 0x4f, 0x99, 0x4f, 0x55, 0x55,
61     0x59, 0x99, 0x9a, 0x9b, 0x9c, 0x9d, 0x9e, 0x9f,
62     0x41, 0x49, 0x4f, 0x55, 0xa5, 0xa5, 0x56, 0xa7,
63     0xa8, 0xa9, 0xaa, 0xab, 0xac, 0xad, 0xae, 0xaf,
64     0xb0, 0xb1, 0xb2, 0xb3, 0xb4, 0xb5, 0xb6, 0xb7,
65     0xb8, 0xb9, 0xba, 0xbb, 0xbc, 0xbd, 0xbe, 0xbf,
66     0xc0, 0xc1, 0xc2, 0xc3, 0xc4, 0xc5, 0xc6, 0xc7,
67     0xc8, 0xc9, 0xca, 0xcb, 0xcc, 0xcd, 0xce, 0xcf,
68     0xd0, 0xd1, 0xd2, 0xd3, 0xd4, 0xd5, 0xd6, 0xd7,
69     0xd8, 0xd9, 0xda, 0xdb, 0xdc, 0xdd, 0xde, 0xdf,
70     0xe0, 0xe1, 0xe2, 0xe3, 0xe4, 0xe5, 0xe6, 0xe7,
71     0xe8, 0xe9, 0xea, 0xeb, 0xec, 0xed, 0xee, 0xef,
72     0xf0, 0xf1, 0xf2, 0xf3, 0xf4, 0xf5, 0xf6, 0xf7,
73     0xf8, 0xf9, 0xfa, 0xfb, 0xfc, 0xfd, 0xfe, 0xff
74 };
75
76 /*
77  * Case-insensitive string comparison.  We used to use stricmp, but it doesn't
78  * know about 8-bit characters (e.g. 129 is lowercase u-umlaut, 154 is
79  * upper-case u-umlaut).
80  */
81 int cm_stricmp(const char *str1, const char *str2)
82 {
83     char c1, c2;
84
85     while (1) {
86         if (*str1 == 0)
87             if (*str2 == 0)
88                 return 0;
89             else
90                 return -1;
91         if (*str2 == 0)
92             return 1;
93         c1 = (char) cm_foldUpper[(unsigned char)(*str1++)];
94         c2 = (char) cm_foldUpper[(unsigned char)(*str2++)];
95         if (c1 < c2)
96             return -1;
97         if (c1 > c2)
98             return 1;
99     }
100 }
101
102
103
104 /* return success if we can open this file in this mode */
105 long cm_CheckOpen(cm_scache_t *scp, int openMode, int trunc, cm_user_t *userp,
106                   cm_req_t *reqp)
107 {
108     long rights;
109     long code;
110
111     rights = 0;
112     if (openMode != 1) 
113         rights |= PRSFS_READ;
114     if (openMode == 1 || openMode == 2 || trunc) 
115         rights |= PRSFS_WRITE;
116         
117     lock_ObtainWrite(&scp->rw);
118
119     code = cm_SyncOp(scp, NULL, userp, reqp, rights,
120                       CM_SCACHESYNC_GETSTATUS
121                      | CM_SCACHESYNC_NEEDCALLBACK
122                      | CM_SCACHESYNC_LOCK);
123
124     if (code == 0 && 
125         ((rights & PRSFS_WRITE) || (rights & PRSFS_READ)) &&
126         scp->fileType == CM_SCACHETYPE_FILE) {
127
128         cm_key_t key;
129         unsigned int sLockType;
130         LARGE_INTEGER LOffset, LLength;
131
132         /* Check if there's some sort of lock on the file at the
133            moment. */
134
135         key = cm_GenerateKey(CM_SESSION_CMINT,0,0);
136
137         if (rights & PRSFS_WRITE)
138             sLockType = 0;
139         else
140             sLockType = LOCKING_ANDX_SHARED_LOCK;
141
142         LOffset.HighPart = CM_FLSHARE_OFFSET_HIGH;
143         LOffset.LowPart  = CM_FLSHARE_OFFSET_LOW;
144         LLength.HighPart = CM_FLSHARE_LENGTH_HIGH;
145         LLength.LowPart  = CM_FLSHARE_LENGTH_LOW;
146
147         code = cm_Lock(scp, sLockType, LOffset, LLength, key, 0, userp, reqp, NULL);
148
149         if (code == 0) {
150             cm_Unlock(scp, sLockType, LOffset, LLength, key, userp, reqp);
151         } else {
152             /* In this case, we allow the file open to go through even
153                though we can't enforce mandatory locking on the
154                file. */
155             if (code == CM_ERROR_NOACCESS &&
156                 !(rights & PRSFS_WRITE))
157                 code = 0;
158             else {
159                 switch (code) {
160                 case CM_ERROR_ALLOFFLINE:
161                 case CM_ERROR_ALLDOWN:
162                 case CM_ERROR_ALLBUSY:
163                 case CM_ERROR_TIMEDOUT:
164                 case CM_ERROR_RETRY:
165                 case CM_ERROR_WOULDBLOCK:
166                     break;
167                 default:
168                     code = CM_ERROR_SHARING_VIOLATION;
169                 }
170             }
171         }
172
173     } else if (code != 0) {
174         goto _done;
175     }
176
177     cm_SyncOpDone(scp, NULL, CM_SCACHESYNC_LOCK);
178
179  _done:
180
181     lock_ReleaseWrite(&scp->rw);
182
183     return code;
184 }
185
186 /* return success if we can open this file in this mode */
187 long cm_CheckNTOpen(cm_scache_t *scp, unsigned int desiredAccess,
188                     unsigned int createDisp, cm_user_t *userp, cm_req_t *reqp, 
189                     cm_lock_data_t **ldpp)
190 {
191     long rights;
192     long code;
193
194     osi_assertx(ldpp != NULL, "null cm_lock_data_t");
195     *ldpp = NULL;
196
197     /* Always allow delete; the RPC will tell us if it's OK */
198     if (desiredAccess == DELETE)
199         return 0;
200
201     rights = 0;
202
203     if (desiredAccess & (AFS_ACCESS_READ|AFS_ACCESS_EXECUTE))
204         rights |= (scp->fileType == CM_SCACHETYPE_DIRECTORY ? PRSFS_LOOKUP : PRSFS_READ);
205
206     /* We used to require PRSFS_WRITE if createDisp was 4
207        (OPEN_ALWAYS) even if AFS_ACCESS_WRITE was not requested.
208        However, we don't need to do that since the existence of the
209        scp implies that we don't need to create it. */
210     if (desiredAccess & AFS_ACCESS_WRITE)
211         rights |= PRSFS_WRITE;
212
213     lock_ObtainWrite(&scp->rw);
214
215     code = cm_SyncOp(scp, NULL, userp, reqp, rights,
216                       CM_SCACHESYNC_GETSTATUS
217                      | CM_SCACHESYNC_NEEDCALLBACK
218                      | CM_SCACHESYNC_LOCK);
219
220     /*
221      * If the open will fail because the volume is readonly, then we will
222      * return an access denied error instead.  This is to help brain-dead
223      * apps run correctly on replicated volumes.
224      * See defect 10007 for more information.
225      */
226     if (code == CM_ERROR_READONLY)
227         code = CM_ERROR_NOACCESS;
228
229     if (code == 0 &&
230              ((rights & PRSFS_WRITE) || (rights & PRSFS_READ)) &&
231              scp->fileType == CM_SCACHETYPE_FILE) {
232         cm_key_t key;
233         unsigned int sLockType;
234         LARGE_INTEGER LOffset, LLength;
235
236         /* Check if there's some sort of lock on the file at the
237            moment. */
238
239         key = cm_GenerateKey(CM_SESSION_CMINT,0,0);
240         if (rights & PRSFS_WRITE)
241             sLockType = 0;
242         else
243             sLockType = LOCKING_ANDX_SHARED_LOCK;
244
245         /* single byte lock at offset 0x0100 0000 0000 0000 */
246         LOffset.HighPart = CM_FLSHARE_OFFSET_HIGH;
247         LOffset.LowPart  = CM_FLSHARE_OFFSET_LOW;
248         LLength.HighPart = CM_FLSHARE_LENGTH_HIGH;
249         LLength.LowPart  = CM_FLSHARE_LENGTH_LOW;
250
251         code = cm_Lock(scp, sLockType, LOffset, LLength, key, 0, userp, reqp, NULL);
252
253         if (code == 0) {
254             (*ldpp) = (cm_lock_data_t *)malloc(sizeof(cm_lock_data_t));
255             if (!*ldpp) {
256                 code = ENOMEM;
257                 goto _syncopdone;
258             }
259
260             (*ldpp)->key = key;
261             (*ldpp)->sLockType = sLockType;
262             (*ldpp)->LOffset.HighPart = LOffset.HighPart;
263             (*ldpp)->LOffset.LowPart = LOffset.LowPart;
264             (*ldpp)->LLength.HighPart = LLength.HighPart;
265             (*ldpp)->LLength.LowPart = LLength.LowPart;
266         } else {
267             /* In this case, we allow the file open to go through even
268                though we can't enforce mandatory locking on the
269                file. */
270             if (code == CM_ERROR_NOACCESS &&
271                 !(rights & PRSFS_WRITE))
272                 code = 0;
273             else {
274                 switch (code) {
275                 case CM_ERROR_ALLOFFLINE:
276                 case CM_ERROR_ALLDOWN:
277                 case CM_ERROR_ALLBUSY:
278                 case CM_ERROR_TIMEDOUT:
279                 case CM_ERROR_RETRY:
280                 case CM_ERROR_WOULDBLOCK:
281                     break;
282                 default:
283                     code = CM_ERROR_SHARING_VIOLATION;
284                 }
285             }
286         }
287     } else if (code != 0) {
288         goto _done;
289     }
290
291   _syncopdone:
292     cm_SyncOpDone(scp, NULL, CM_SCACHESYNC_LOCK);
293
294  _done:
295     lock_ReleaseWrite(&scp->rw);
296
297     osi_Log3(afsd_logp,"cm_CheckNTOpen scp 0x%p ldp 0x%p code 0x%x", scp, *ldpp, code);
298     return code;
299 }
300
301 extern long cm_CheckNTOpenDone(cm_scache_t *scp, cm_user_t *userp, cm_req_t *reqp, 
302                                cm_lock_data_t ** ldpp)
303 {
304     osi_Log2(afsd_logp,"cm_CheckNTOpenDone scp 0x%p ldp 0x%p", scp, *ldpp);
305     if (*ldpp) {
306         lock_ObtainWrite(&scp->rw);
307         cm_Unlock(scp, (*ldpp)->sLockType, (*ldpp)->LOffset, (*ldpp)->LLength, 
308                   (*ldpp)->key, userp, reqp);
309         lock_ReleaseWrite(&scp->rw);
310         free(*ldpp);
311         *ldpp = NULL;
312     }
313     return 0;
314 }
315 /*
316  * When CAP_NT_SMBS has been negotiated, deletion (of files or directories) is
317  * done in three steps:
318  * (1) open for deletion (NT_CREATE_AND_X)
319  * (2) set for deletion on close (NT_TRANSACTION2, SET_FILE_INFO)
320  * (3) close (CLOSE)
321  * We must not do the RPC until step 3.  But if we are going to return an error
322  * code (e.g. directory not empty), we must return it by step 2, otherwise most
323  * clients will not notice it.  So we do a preliminary check.  For deleting
324  * files, this is almost free, since we have already done the RPC to get the
325  * parent directory's status bits.  But for deleting directories, we must do an
326  * additional RPC to get the directory's data to check if it is empty.  Sigh.
327  */
328 long cm_CheckNTDelete(cm_scache_t *dscp, cm_scache_t *scp, cm_user_t *userp,
329         cm_req_t *reqp)
330 {
331     long code;
332     osi_hyper_t thyper;
333     cm_buf_t *bufferp;
334     cm_dirEntry_t *dep = 0;
335     unsigned short *hashTable;
336     unsigned int i, idx;
337     int BeyondPage = 0, HaveDot = 0, HaveDotDot = 0;
338     int releaseLock = 0;
339
340     /* First check permissions */
341     lock_ObtainWrite(&scp->rw);
342     code = cm_SyncOp(scp, NULL, userp, reqp, PRSFS_DELETE,
343                       CM_SCACHESYNC_GETSTATUS | CM_SCACHESYNC_NEEDCALLBACK);
344     cm_SyncOpDone(scp, NULL, CM_SCACHESYNC_NEEDCALLBACK | CM_SCACHESYNC_GETSTATUS);
345     lock_ReleaseWrite(&scp->rw);
346     if (code)
347         return code;
348
349     /* If deleting directory, must be empty */
350
351     if (scp->fileType != CM_SCACHETYPE_DIRECTORY)
352         return code;
353
354     thyper.HighPart = 0; thyper.LowPart = 0;
355     code = buf_Get(scp, &thyper, &bufferp);
356     if (code)
357         return code;
358
359     lock_ObtainMutex(&bufferp->mx);
360     lock_ObtainWrite(&scp->rw);
361     releaseLock = 1;
362     while (1) {
363         code = cm_SyncOp(scp, bufferp, userp, reqp, 0,
364                           CM_SCACHESYNC_NEEDCALLBACK
365                           | CM_SCACHESYNC_READ
366                           | CM_SCACHESYNC_BUFLOCKED);
367         if (code)
368             goto done;
369
370         if (cm_HaveBuffer(scp, bufferp, 1))
371             break;
372
373         /* otherwise, load the buffer and try again */
374         lock_ReleaseMutex(&bufferp->mx);
375         code = cm_GetBuffer(scp, bufferp, NULL, userp, reqp);
376         lock_ReleaseWrite(&scp->rw);
377         lock_ObtainMutex(&bufferp->mx);
378         lock_ObtainWrite(&scp->rw);
379         cm_SyncOpDone(scp, bufferp, CM_SCACHESYNC_NEEDCALLBACK | CM_SCACHESYNC_READ | CM_SCACHESYNC_BUFLOCKED);
380         if (code)
381             goto done;
382     }
383
384     lock_ReleaseWrite(&scp->rw);
385     releaseLock = 0;
386
387     /* We try to determine emptiness without looking beyond the first page,
388      * and without assuming "." and ".." are present and are on the first
389      * page (though these assumptions might, after all, be reasonable).
390      */
391     hashTable = (unsigned short *)(bufferp->datap + (32 * 5));
392     for (i=0; i<128; i++) {
393         idx = ntohs(hashTable[i]);
394         while (idx) {
395             if (idx >= 64) {
396                 BeyondPage = 1;
397                 break;
398             }
399             dep = (cm_dirEntry_t *)(bufferp->datap + (32 * idx));
400             if (strcmp(dep->name, ".") == 0)
401                 HaveDot = 1;
402             else if (strcmp(dep->name, "..") == 0)
403                 HaveDotDot = 1;
404             else {
405                 code = CM_ERROR_NOTEMPTY;
406                 goto done;
407             }
408             idx = ntohs(dep->next);
409         }
410     }
411     if (BeyondPage && HaveDot && HaveDotDot)
412         code = CM_ERROR_NOTEMPTY;
413     else
414         code = 0;
415   done:   
416     lock_ReleaseMutex(&bufferp->mx);
417     buf_Release(bufferp);
418     if (releaseLock)
419         lock_ReleaseWrite(&scp->rw);
420     return code;
421 }       
422
423 /*
424  * Iterate through all entries in a directory.
425  * When the function funcp is called, the buffer is locked but the
426  * directory vnode is not.
427  *
428  * If the retscp parameter is not NULL, the parmp must be a 
429  * cm_lookupSearch_t object.  
430  */
431 long cm_ApplyDir(cm_scache_t *scp, cm_DirFuncp_t funcp, void *parmp,
432                  osi_hyper_t *startOffsetp, cm_user_t *userp, cm_req_t *reqp,
433                  cm_scache_t **retscp)
434 {
435     char *tp;
436     long code;
437     cm_dirEntry_t *dep = 0;
438     cm_buf_t *bufferp;
439     long temp;
440     osi_hyper_t dirLength;
441     osi_hyper_t bufferOffset;
442     osi_hyper_t curOffset;
443     osi_hyper_t thyper;
444     long entryInDir;
445     long entryInBuffer;
446     cm_pageHeader_t *pageHeaderp;
447     int slotInPage;
448     long nextEntryCookie;
449     int numDirChunks;   /* # of 32 byte dir chunks in this entry */
450         
451     /* get the directory size */
452     lock_ObtainWrite(&scp->rw);
453     code = cm_SyncOp(scp, NULL, userp, reqp, PRSFS_LOOKUP,
454                       CM_SCACHESYNC_NEEDCALLBACK | CM_SCACHESYNC_GETSTATUS);
455     lock_ReleaseWrite(&scp->rw);
456     if (code)
457         return code;
458         
459     if (scp->fileType != CM_SCACHETYPE_DIRECTORY)
460         return CM_ERROR_NOTDIR;
461
462     if (retscp)                         /* if this is a lookup call */
463     {
464         cm_lookupSearch_t*      sp = parmp;
465
466         if (
467 #ifdef AFS_FREELANCE_CLIENT
468         /* Freelance entries never end up in the DNLC because they
469          * do not have an associated cm_server_t
470          */
471             !(cm_freelanceEnabled &&
472             sp->fid.cell==AFS_FAKE_ROOT_CELL_ID &&
473               sp->fid.volume==AFS_FAKE_ROOT_VOL_ID )
474 #else /* !AFS_FREELANCE_CLIENT */
475             TRUE
476 #endif
477             ) 
478         {
479             int casefold = sp->caseFold;
480             sp->caseFold = 0; /* we have a strong preference for exact matches */
481             if ( *retscp = cm_dnlcLookup(scp, sp))      /* dnlc hit */
482             {
483                 sp->caseFold = casefold;
484                 return 0;
485             }
486             sp->caseFold = casefold;
487
488             /* see if we can find it using the directory hash tables.
489                we can only do exact matches, since the hash is case
490                sensitive. */
491             {
492                 cm_dirOp_t dirop;
493 #ifdef USE_BPLUS
494                 int usedBplus = 0;
495 #endif
496
497                 code = ENOENT;
498
499                 code = cm_BeginDirOp(scp, userp, reqp, CM_DIRLOCK_READ, &dirop);
500                 if (code == 0) {
501
502 #ifdef USE_BPLUS
503                     code = cm_BPlusDirLookup(&dirop, sp->nsearchNamep, &sp->fid);
504                     if (code != EINVAL)
505                         usedBplus = 1;
506                     else 
507 #endif
508                         code = cm_DirLookup(&dirop, sp->searchNamep, &sp->fid);
509
510                     cm_EndDirOp(&dirop);
511                 }
512
513                 if (code == 0) {
514                     /* found it */
515                     sp->found = TRUE;
516                     sp->ExactFound = TRUE;
517                     *retscp = NULL; /* force caller to call cm_GetSCache() */
518                     return 0;
519                 }
520 #ifdef USE_BPLUS
521                 if (usedBplus) {
522                     if (sp->caseFold && code == CM_ERROR_INEXACT_MATCH) {
523                         /* found it */
524                         sp->found = TRUE;
525                         sp->ExactFound = FALSE;
526                         *retscp = NULL; /* force caller to call cm_GetSCache() */
527                         return 0;
528                     }
529                     
530                     return CM_ERROR_BPLUS_NOMATCH;
531                 }
532 #endif 
533             }
534         }
535     }   
536
537     /*
538      * XXX We only get the length once.  It might change when we drop the
539      * lock.
540      */
541     dirLength = scp->length;
542
543     bufferp = NULL;
544     bufferOffset.LowPart = bufferOffset.HighPart = 0;
545     if (startOffsetp)
546         curOffset = *startOffsetp;
547     else {
548         curOffset.HighPart = 0;
549         curOffset.LowPart = 0;
550     }   
551
552     while (1) {
553         /* make sure that curOffset.LowPart doesn't point to the first
554          * 32 bytes in the 2nd through last dir page, and that it
555          * doesn't point at the first 13 32-byte chunks in the first
556          * dir page, since those are dir and page headers, and don't
557          * contain useful information.
558          */
559         temp = curOffset.LowPart & (2048-1);
560         if (curOffset.HighPart == 0 && curOffset.LowPart < 2048) {
561             /* we're in the first page */
562             if (temp < 13*32) temp = 13*32;
563         }
564         else {
565             /* we're in a later dir page */
566             if (temp < 32) temp = 32;
567         }       
568                 
569         /* make sure the low order 5 bits are zero */
570         temp &= ~(32-1);
571                 
572         /* now put temp bits back ito curOffset.LowPart */
573         curOffset.LowPart &= ~(2048-1);
574         curOffset.LowPart |= temp;
575
576         /* check if we've passed the dir's EOF */
577         if (LargeIntegerGreaterThanOrEqualTo(curOffset, dirLength))
578             break;
579                 
580         /* see if we can use the bufferp we have now; compute in which
581          * page the current offset would be, and check whether that's
582          * the offset of the buffer we have.  If not, get the buffer.
583          */
584         thyper.HighPart = curOffset.HighPart;
585         thyper.LowPart = curOffset.LowPart & ~(cm_data.buf_blockSize-1);
586         if (!bufferp || !LargeIntegerEqualTo(thyper, bufferOffset)) {
587             /* wrong buffer */
588             if (bufferp) {
589                 lock_ReleaseMutex(&bufferp->mx);
590                 buf_Release(bufferp);
591                 bufferp = NULL;
592             }
593
594             code = buf_Get(scp, &thyper, &bufferp);
595             if (code) {
596                 /* if buf_Get() fails we do not have a buffer object to lock */
597                 bufferp = NULL;
598                 break;
599             }
600
601             lock_ObtainMutex(&bufferp->mx);
602             bufferOffset = thyper;
603
604             /* now get the data in the cache */
605             while (1) {
606                 lock_ObtainWrite(&scp->rw);
607                 code = cm_SyncOp(scp, bufferp, userp, reqp,
608                                   PRSFS_LOOKUP,
609                                   CM_SCACHESYNC_NEEDCALLBACK
610                                   | CM_SCACHESYNC_READ
611                                   | CM_SCACHESYNC_BUFLOCKED);
612                 if (code) {
613                     lock_ReleaseWrite(&scp->rw);
614                     break;
615                 }
616                 cm_SyncOpDone(scp, bufferp, CM_SCACHESYNC_NEEDCALLBACK | CM_SCACHESYNC_READ | CM_SCACHESYNC_BUFLOCKED);
617                                 
618                 if (cm_HaveBuffer(scp, bufferp, 1)) {
619                     lock_ReleaseWrite(&scp->rw);
620                     break;
621                 }
622
623                 /* otherwise, load the buffer and try again */
624                 lock_ReleaseMutex(&bufferp->mx);
625                 code = cm_GetBuffer(scp, bufferp, NULL, userp,
626                                     reqp);
627                 lock_ReleaseWrite(&scp->rw);
628                 lock_ObtainMutex(&bufferp->mx);
629                 if (code) 
630                     break;
631             }
632             if (code) {
633                 lock_ReleaseMutex(&bufferp->mx);
634                 buf_Release(bufferp);
635                 bufferp = NULL;
636                 break;
637             }
638         }       /* if (wrong buffer) ... */
639            
640         /* now we have the buffer containing the entry we're interested
641          * in; copy it out if it represents a non-deleted entry.
642          */
643         entryInDir = curOffset.LowPart & (2048-1);
644         entryInBuffer = curOffset.LowPart & (cm_data.buf_blockSize - 1);
645
646         /* page header will help tell us which entries are free.  Page
647          * header can change more often than once per buffer, since
648          * AFS 3 dir page size may be less than (but not more than) a
649          * buffer package buffer.
650          */
651         /* only look intra-buffer */
652         temp = curOffset.LowPart & (cm_data.buf_blockSize - 1);
653         temp &= ~(2048 - 1);    /* turn off intra-page bits */
654         pageHeaderp = (cm_pageHeader_t *) (bufferp->datap + temp);
655
656         /* now determine which entry we're looking at in the page.  If
657          * it is free (there's a free bitmap at the start of the dir),
658          * we should skip these 32 bytes.
659          */
660         slotInPage = (entryInDir & 0x7e0) >> 5;
661         if (!(pageHeaderp->freeBitmap[slotInPage>>3]
662                & (1 << (slotInPage & 0x7)))) {
663             /* this entry is free */
664             numDirChunks = 1;   /* only skip this guy */
665             goto nextEntry;
666         }
667
668         tp = bufferp->datap + entryInBuffer;
669         dep = (cm_dirEntry_t *) tp;     /* now points to AFS3 dir entry */
670
671         /* while we're here, compute the next entry's location, too,
672          * since we'll need it when writing out the cookie into the
673          * dir listing stream.
674          */
675         numDirChunks = cm_NameEntries(dep->name, NULL);
676                 
677         /* compute the offset of the cookie representing the next entry */
678         nextEntryCookie = curOffset.LowPart
679             + (CM_DIR_CHUNKSIZE * numDirChunks);
680
681         if (dep->fid.vnode != 0) {
682             /* this is one of the entries to use: it is not deleted */
683             code = (*funcp)(scp, dep, parmp, &curOffset);
684             if (code) 
685                 break;
686         }       /* if we're including this name */
687                 
688       nextEntry:
689         /* and adjust curOffset to be where the new cookie is */
690         thyper.HighPart = 0;
691         thyper.LowPart = CM_DIR_CHUNKSIZE * numDirChunks;
692         curOffset = LargeIntegerAdd(thyper, curOffset);
693     }           /* while copying data for dir listing */
694
695     /* release the mutex */
696     if (bufferp) {
697         lock_ReleaseMutex(&bufferp->mx);
698         buf_Release(bufferp);
699     }
700     return code;
701 }
702
703 int cm_NoneUpper(normchar_t *s)
704 {
705     normchar_t c;
706     while (c = *s++)
707         if (c >= 'A' && c <= 'Z')
708             return 0;
709     return 1;
710 }
711
712 int cm_NoneLower(normchar_t *s)
713 {
714     normchar_t c;
715     while (c = *s++)
716         if (c >= 'a' && c <= 'z')
717             return 0;
718     return 1;
719 }
720
721 long cm_LookupSearchProc(cm_scache_t *scp, cm_dirEntry_t *dep, void *rockp,
722                          osi_hyper_t *offp)
723 {
724     cm_lookupSearch_t *sp;
725     int match;
726     normchar_t matchName[MAX_PATH];
727     int looking_for_short_name = FALSE;
728
729     sp = (cm_lookupSearch_t *) rockp;
730
731     cm_FsStringToNormString(dep->name, -1, matchName, lengthof(matchName));
732     if (sp->caseFold)
733         match = cm_NormStrCmpI(matchName, sp->nsearchNamep);
734     else
735         match = cm_NormStrCmp(matchName, sp->nsearchNamep);
736
737     if (match != 0
738         && sp->hasTilde
739         && !cm_Is8Dot3(matchName)) {
740
741         cm_Gen8Dot3NameInt(dep->name, &dep->fid, matchName, NULL);
742         if (sp->caseFold)
743             match = cm_NormStrCmpI(matchName, sp->nsearchNamep);
744         else
745             match = cm_NormStrCmp(matchName, sp->nsearchNamep);
746         looking_for_short_name = TRUE;
747     }
748
749     if (match != 0)
750         return 0;
751
752     sp->found = 1;
753     if (!sp->caseFold) 
754         sp->ExactFound = 1;
755
756     if (!sp->caseFold || looking_for_short_name) {
757         cm_SetFid(&sp->fid, sp->fid.cell, sp->fid.volume, ntohl(dep->fid.vnode), ntohl(dep->fid.unique));
758         return CM_ERROR_STOPNOW;
759     }
760
761     /*
762      * If we get here, we are doing a case-insensitive search, and we
763      * have found a match.  Now we determine what kind of match it is:
764      * exact, lower-case, upper-case, or none of the above.  This is done
765      * in order to choose among matches, if there are more than one.
766      */
767
768     /* Exact matches are the best. */
769     match = cm_NormStrCmp(matchName, sp->nsearchNamep);
770     if (match == 0) {
771         sp->ExactFound = 1;
772         cm_SetFid(&sp->fid, sp->fid.cell, sp->fid.volume, ntohl(dep->fid.vnode), ntohl(dep->fid.unique));
773         return CM_ERROR_STOPNOW;
774     }
775
776     /* Lower-case matches are next. */
777     if (sp->LCfound)
778         return 0;
779     if (cm_NoneUpper(matchName)) {
780         sp->LCfound = 1;
781         goto inexact;
782     }
783
784     /* Upper-case matches are next. */
785     if (sp->UCfound)
786         return 0;
787     if (cm_NoneLower(matchName)) {
788         sp->UCfound = 1;
789         goto inexact;
790     }
791
792     /* General matches are last. */
793     if (sp->NCfound)
794         return 0;
795     sp->NCfound = 1;
796
797   inexact:
798     cm_SetFid(&sp->fid, sp->fid.cell, sp->fid.volume, ntohl(dep->fid.vnode), ntohl(dep->fid.unique));
799     return 0;
800 }       
801
802 /* read the contents of a mount point into the appropriate string.
803  * called with write locked scp, and returns with locked scp.
804  */
805 long cm_ReadMountPoint(cm_scache_t *scp, cm_user_t *userp, cm_req_t *reqp)
806 {
807     long code;
808     cm_buf_t *bufp;
809     osi_hyper_t thyper;
810     int tlen;
811
812     if (scp->mountPointStringp[0]) 
813         return 0;
814         
815     /* otherwise, we have to read it in */
816     lock_ReleaseWrite(&scp->rw);
817
818     thyper.LowPart = thyper.HighPart = 0;
819     code = buf_Get(scp, &thyper, &bufp);
820
821     lock_ObtainWrite(&scp->rw);
822     if (code)
823         return code;
824
825     while (1) {
826         code = cm_SyncOp(scp, bufp, userp, reqp, 0,
827                           CM_SCACHESYNC_READ | CM_SCACHESYNC_NEEDCALLBACK);
828         if (code)
829             goto done;
830
831         cm_SyncOpDone(scp, bufp, CM_SCACHESYNC_NEEDCALLBACK | CM_SCACHESYNC_READ);
832
833         if (cm_HaveBuffer(scp, bufp, 0)) 
834             break;
835
836         /* otherwise load buffer */
837         code = cm_GetBuffer(scp, bufp, NULL, userp, reqp);
838         if (code)
839             goto done;
840     }
841     /* locked, has callback, has valid data in buffer */
842     if ((tlen = scp->length.LowPart) > MOUNTPOINTLEN - 1) 
843         return CM_ERROR_TOOBIG;
844     if (tlen <= 0) {
845         code = CM_ERROR_INVAL;
846         goto done;
847     }
848
849     /* someone else did the work while we were out */
850     if (scp->mountPointStringp[0]) {
851         code = 0;
852         goto done;
853     }
854
855     /* otherwise, copy out the link */
856     memcpy(scp->mountPointStringp, bufp->datap, tlen);
857
858     /* now make it null-terminated.  Note that the original contents of a
859      * link that is a mount point is "#volname." where "." is there just to
860      * be turned into a null.  That is, we can trash the last char of the
861      * link without damaging the vol name.  This is a stupid convention,
862      * but that's the protocol.
863      */
864     scp->mountPointStringp[tlen-1] = 0;
865     code = 0;
866
867   done:
868     if (bufp) 
869         buf_Release(bufp);
870     return code;
871 }
872
873
874 /* called with a locked scp and chases the mount point, yielding outScpp.
875  * scp remains write locked, just for simplicity of describing the interface.
876  */
877 long cm_FollowMountPoint(cm_scache_t *scp, cm_scache_t *dscp, cm_user_t *userp,
878                          cm_req_t *reqp, cm_scache_t **outScpp)
879 {
880     fschar_t *cellNamep = NULL;
881     fschar_t *volNamep = NULL;
882     int tlen;
883     afs_uint32 code;
884     fschar_t *cp;
885     fschar_t *mpNamep;
886     cm_volume_t *volp = NULL;
887     cm_cell_t *cellp;
888     fschar_t mtType;
889     cm_fid_t tfid;
890     size_t vnLength;
891     int targetType;
892
893     if (scp->mountRootFid.cell != 0 && scp->mountRootGen >= cm_data.mountRootGen) {
894         tfid = scp->mountRootFid;
895         lock_ReleaseWrite(&scp->rw);
896         code = cm_GetSCache(&tfid, outScpp, userp, reqp);
897         lock_ObtainWrite(&scp->rw);
898         return code;
899     }
900
901     /* parse the volume name */
902     mpNamep = scp->mountPointStringp;
903     if (!mpNamep[0])
904         return CM_ERROR_NOSUCHPATH;
905     tlen = cm_FsStrLen(scp->mountPointStringp);
906     mtType = *scp->mountPointStringp;
907
908     cp = cm_FsStrChr(mpNamep, _FS(':'));
909     if (cp) {
910         /* cellular mount point */
911         cellNamep = (fschar_t *)malloc((cp - mpNamep) * sizeof(fschar_t));
912         cm_FsStrCpyN(cellNamep, cp - mpNamep, mpNamep + 1, cp - mpNamep - 1);
913         volNamep = cm_FsStrDup(cp+1);
914
915         /* now look up the cell */
916         lock_ReleaseWrite(&scp->rw);
917         cellp = cm_GetCell(cellNamep, CM_FLAG_CREATE);
918         lock_ObtainWrite(&scp->rw);
919     } else {
920         /* normal mt pt */
921         volNamep = cm_FsStrDup(mpNamep + 1);
922
923         cellp = cm_FindCellByID(scp->fid.cell, 0);
924     }
925
926     if (!cellp) {
927         code = CM_ERROR_NOSUCHCELL;
928         goto done;
929     }
930
931     vnLength = cm_FsStrLen(volNamep);
932     if (vnLength >= 8 && cm_FsStrCmp(volNamep + vnLength - 7, ".backup") == 0)
933         targetType = BACKVOL;
934     else if (vnLength >= 10
935              && cm_FsStrCmp(volNamep + vnLength - 9, ".readonly") == 0)
936         targetType = ROVOL;
937     else
938         targetType = RWVOL;
939
940     /* check for backups within backups */
941     if (targetType == BACKVOL
942          && (scp->flags & (CM_SCACHEFLAG_RO | CM_SCACHEFLAG_PURERO))
943          == CM_SCACHEFLAG_RO) {
944         code = CM_ERROR_NOSUCHVOLUME;
945         goto done;
946     }
947
948     /* now we need to get the volume */
949     lock_ReleaseWrite(&scp->rw);
950     if (cm_VolNameIsID(volNamep)) {
951         code = cm_FindVolumeByID(cellp, atoi(volNamep), userp, reqp, 
952                                 CM_GETVOL_FLAG_CREATE, &volp);
953     } else {
954         code = cm_FindVolumeByName(cellp, volNamep, userp, reqp, 
955                                   CM_GETVOL_FLAG_CREATE, &volp);
956     }
957     lock_ObtainWrite(&scp->rw);
958         
959     if (code == 0) {
960         afs_uint32 cell, volume;
961         cm_vol_state_t *statep;
962
963         cell = cellp->cellID;
964         
965         /* if the mt pt originates in a .backup volume (not a .readonly)
966          * and FollowBackupPath is active, and if there is a .backup
967          * volume for the target, then use the .backup of the target
968          * instead of the read-write.
969          */
970         if (cm_followBackupPath && 
971             volp->vol[BACKVOL].ID != 0 &&
972             (dscp->flags & (CM_SCACHEFLAG_RO|CM_SCACHEFLAG_PURERO)) == CM_SCACHEFLAG_RO &&
973             (targetType == RWVOL || targetType == ROVOL && volp->vol[ROVOL].ID == 0)
974             ) {
975             targetType = BACKVOL;
976         } 
977         /* if the mt pt is in a read-only volume (not just a
978          * backup), and if there is a read-only volume for the
979          * target, and if this is a targetType '#' mount point, use
980          * the read-only, otherwise use the one specified.
981          */
982         else if (mtType == '#' && targetType == RWVOL && 
983                  (scp->flags & CM_SCACHEFLAG_PURERO) && 
984                  volp->vol[ROVOL].ID != 0) {
985             targetType = ROVOL;
986         }
987
988         lock_ObtainWrite(&volp->rw);
989         statep = cm_VolumeStateByType(volp, targetType);
990         volume = statep->ID;
991         statep->dotdotFid = dscp->fid;
992         lock_ReleaseWrite(&volp->rw);
993
994         /* the rest of the fid is a magic number */
995         cm_SetFid(&scp->mountRootFid, cell, volume, 1, 1);
996         scp->mountRootGen = cm_data.mountRootGen;
997
998         tfid = scp->mountRootFid;
999         lock_ReleaseWrite(&scp->rw);
1000         code = cm_GetSCache(&tfid, outScpp, userp, reqp);
1001         lock_ObtainWrite(&scp->rw);
1002     }
1003
1004   done:
1005     if (volp)
1006         cm_PutVolume(volp);
1007     if (cellNamep)
1008         free(cellNamep);
1009     if (volNamep)
1010         free(volNamep);
1011     return code;
1012 }       
1013
1014 long cm_LookupInternal(cm_scache_t *dscp, clientchar_t *cnamep, long flags, cm_user_t *userp,
1015                        cm_req_t *reqp, cm_scache_t **outpScpp)
1016 {
1017     long code;
1018     int dnlcHit = 1;    /* did we hit in the dnlc? yes, we did */
1019     cm_scache_t *tscp = NULL;
1020     cm_scache_t *mountedScp;
1021     cm_lookupSearch_t rock;
1022     int getroot;
1023     normchar_t *nnamep = NULL;
1024     fschar_t *fnamep = NULL;
1025
1026     memset(&rock, 0, sizeof(rock));
1027
1028     if (dscp->fid.vnode == 1 && dscp->fid.unique == 1
1029         && cm_ClientStrCmp(cnamep, _C("..")) == 0) {
1030         if (dscp->dotdotFid.volume == 0)
1031             return CM_ERROR_NOSUCHVOLUME;
1032         rock.fid = dscp->dotdotFid;
1033         goto haveFid;
1034     } else if (cm_ClientStrCmp(cnamep, _C(".")) == 0) {
1035         rock.fid = dscp->fid;
1036         goto haveFid;
1037     }
1038
1039     nnamep = cm_ClientStringToNormStringAlloc(cnamep, -1, NULL);
1040     fnamep = cm_ClientStringToFsStringAlloc(cnamep, -1, NULL);
1041
1042     if (flags & CM_FLAG_NOMOUNTCHASE) {
1043         /* In this case, we should go and call cm_Dir* functions
1044            directly since the following cm_ApplyDir() function will
1045            not. */
1046
1047         cm_dirOp_t dirop;
1048 #ifdef USE_BPLUS
1049         int usedBplus = 0;
1050 #endif
1051
1052         code = cm_BeginDirOp(dscp, userp, reqp, CM_DIRLOCK_READ, &dirop);
1053         if (code == 0) {
1054 #ifdef USE_BPLUS
1055             code = cm_BPlusDirLookup(&dirop, nnamep, &rock.fid);
1056             if (code != EINVAL)
1057                 usedBplus = 1;
1058             else
1059 #endif
1060                 code = cm_DirLookup(&dirop, fnamep, &rock.fid);
1061
1062             cm_EndDirOp(&dirop);
1063         }
1064
1065         if (code == 0) {
1066             /* found it */
1067             rock.found = TRUE;
1068             goto haveFid;
1069         }
1070 #ifdef USE_BPLUS
1071         if (usedBplus) {
1072             if (code == CM_ERROR_INEXACT_MATCH && (flags & CM_FLAG_CASEFOLD)) {
1073                 /* found it */
1074                 code = 0;
1075                 rock.found = TRUE;
1076                 goto haveFid;
1077             }
1078             
1079             return CM_ERROR_BPLUS_NOMATCH;
1080         }
1081 #endif
1082     }
1083
1084     rock.fid.cell = dscp->fid.cell;
1085     rock.fid.volume = dscp->fid.volume;
1086     rock.searchNamep = fnamep;
1087     rock.nsearchNamep = nnamep;
1088     rock.caseFold = (flags & CM_FLAG_CASEFOLD);
1089     rock.hasTilde = ((cm_ClientStrChr(cnamep, '~') != NULL) ? 1 : 0);
1090
1091     /* If NOMOUNTCHASE, bypass DNLC by passing NULL scp pointer */
1092     code = cm_ApplyDir(dscp, cm_LookupSearchProc, &rock, NULL, userp, reqp,
1093                        (flags & CM_FLAG_NOMOUNTCHASE) ? NULL : &tscp);
1094
1095     /* code == 0 means we fell off the end of the dir, while stopnow means
1096      * that we stopped early, probably because we found the entry we're
1097      * looking for.  Any other non-zero code is an error.
1098      */
1099     if (code && code != CM_ERROR_STOPNOW) {
1100         /* if the cm_scache_t we are searching in is not a directory 
1101          * we must return path not found because the error 
1102          * is to describe the final component not an intermediary
1103          */
1104         if (code == CM_ERROR_NOTDIR) {
1105             if (flags & CM_FLAG_CHECKPATH)
1106                 code = CM_ERROR_NOSUCHPATH;
1107             else
1108                 code = CM_ERROR_NOSUCHFILE;
1109         }
1110         goto done;
1111     }
1112
1113     getroot = (dscp==cm_data.rootSCachep) ;
1114     if (!rock.found) {
1115         if (!cm_freelanceEnabled || !getroot) {
1116             if (flags & CM_FLAG_CHECKPATH)
1117                 code = CM_ERROR_NOSUCHPATH;
1118             else
1119                 code = CM_ERROR_NOSUCHFILE;
1120             goto done;
1121         }
1122         else if (!cm_ClientStrChr(cnamep, '#') &&
1123                  !cm_ClientStrChr(cnamep, '%') &&
1124                  cm_ClientStrCmpI(cnamep, _C("srvsvc")) &&
1125                  cm_ClientStrCmpI(cnamep, _C("wkssvc")) &&
1126                  cm_ClientStrCmpI(cnamep, _C("ipc$"))) 
1127         {
1128             /* nonexistent dir on freelance root, so add it */
1129             fschar_t fullname[200] = ".";
1130             int  found = 0;
1131
1132             osi_Log1(afsd_logp,"cm_Lookup adding mount for non-existent directory: %S", 
1133                      osi_LogSaveClientString(afsd_logp,cnamep));
1134
1135             /* 
1136              * There is an ugly behavior where a share name "foo" will be searched
1137              * for as "fo".  If the searched for name differs by an already existing
1138              * symlink or mount point in the Freelance directory, do not add the 
1139              * new value automatically.
1140              */
1141
1142             code = -1;
1143             if (cnamep[0] == '.') {
1144                 if (cm_GetCell_Gen(&fnamep[1], &fullname[1], CM_FLAG_CREATE)) {
1145                     found = 1;
1146                     if (!cm_FreelanceMountPointExists(fullname, 0))
1147                         code = cm_FreelanceAddMount(fullname, &fullname[1], "root.cell.",
1148                                                     1, &rock.fid);
1149                     if ( cm_FsStrCmpI(&fnamep[1], &fullname[1]) && 
1150                          !cm_FreelanceMountPointExists(fnamep, flags & CM_FLAG_DFS_REFERRAL ? 1 : 0) &&
1151                          !cm_FreelanceSymlinkExists(fnamep, flags & CM_FLAG_DFS_REFERRAL ? 1 : 0))
1152                         code = cm_FreelanceAddSymlink(fnamep, fullname, &rock.fid);
1153                 }
1154             } else {
1155                 if (cm_GetCell_Gen(fnamep, fullname, CM_FLAG_CREATE)) {
1156                     found = 1;
1157                     if (!cm_FreelanceMountPointExists(fullname, 0))
1158                         code = cm_FreelanceAddMount(fullname, fullname, "root.cell.", 0, &rock.fid);
1159                     if ( cm_FsStrCmpI(fnamep, fullname) && 
1160                          !cm_FreelanceMountPointExists(fnamep, flags & CM_FLAG_DFS_REFERRAL ? 1 : 0) &&
1161                          !cm_FreelanceSymlinkExists(fnamep, flags & CM_FLAG_DFS_REFERRAL ? 1 : 0))
1162                         code = cm_FreelanceAddSymlink(fnamep, fullname, &rock.fid);
1163                 }
1164             }
1165             if (!found || code < 0) {   /* add mount point failed, so give up */
1166                 if (flags & CM_FLAG_CHECKPATH)
1167                     code = CM_ERROR_NOSUCHPATH;
1168                 else
1169                     code = CM_ERROR_NOSUCHFILE;
1170                 goto done;
1171             }
1172             tscp = NULL;   /* to force call of cm_GetSCache */
1173         } else {
1174             if (flags & CM_FLAG_CHECKPATH)
1175                 code = CM_ERROR_NOSUCHPATH;
1176             else
1177                 code = CM_ERROR_NOSUCHFILE;
1178             goto done;
1179         }
1180     }
1181
1182   haveFid:       
1183     if ( !tscp )    /* we did not find it in the dnlc */
1184     {
1185         dnlcHit = 0; 
1186         code = cm_GetSCache(&rock.fid, &tscp, userp, reqp);
1187         if (code) 
1188             goto done;
1189     }
1190     /* tscp is now held */
1191
1192     lock_ObtainWrite(&tscp->rw);
1193     code = cm_SyncOp(tscp, NULL, userp, reqp, 0,
1194                       CM_SCACHESYNC_GETSTATUS | CM_SCACHESYNC_NEEDCALLBACK);
1195     if (code) { 
1196         lock_ReleaseWrite(&tscp->rw);
1197         cm_ReleaseSCache(tscp);
1198         goto done;
1199     }
1200     cm_SyncOpDone(tscp, NULL, CM_SCACHESYNC_NEEDCALLBACK | CM_SCACHESYNC_GETSTATUS);
1201     /* tscp is now locked */
1202
1203     if (!(flags & CM_FLAG_NOMOUNTCHASE)
1204          && tscp->fileType == CM_SCACHETYPE_MOUNTPOINT) {
1205         /* mount points are funny: they have a volume name to mount
1206          * the root of.
1207          */
1208         code = cm_ReadMountPoint(tscp, userp, reqp);
1209         if (code == 0)
1210             code = cm_FollowMountPoint(tscp, dscp, userp, reqp,
1211                                        &mountedScp);
1212         lock_ReleaseWrite(&tscp->rw);
1213         cm_ReleaseSCache(tscp);
1214         if (code)
1215             goto done;
1216
1217         tscp = mountedScp;
1218     }
1219     else {
1220         lock_ReleaseWrite(&tscp->rw);
1221     }
1222
1223     /* copy back pointer */
1224     *outpScpp = tscp;
1225
1226     /* insert scache in dnlc */
1227     if ( !dnlcHit && !(flags & CM_FLAG_NOMOUNTCHASE) && rock.ExactFound ) {
1228         /* lock the directory entry to prevent racing callback revokes */
1229         lock_ObtainRead(&dscp->rw);
1230         if ( dscp->cbServerp != NULL && dscp->cbExpires > 0 ) {
1231             /* TODO: reuse nnamep from above */
1232             if (nnamep) 
1233                 free(nnamep);
1234             nnamep = cm_ClientStringToNormStringAlloc(cnamep, -1, NULL);
1235             cm_dnlcEnter(dscp, nnamep, tscp);
1236         }
1237         lock_ReleaseRead(&dscp->rw);
1238     }
1239
1240     /* and return */
1241   done:
1242     if (fnamep) {
1243         free (fnamep);
1244         fnamep = NULL;
1245     }
1246     if (nnamep) {
1247         free (nnamep);
1248         nnamep = NULL;
1249     }
1250
1251     return code;
1252 }
1253
1254 int cm_ExpandSysName(clientchar_t *inp, clientchar_t *outp, long outSizeCch, unsigned int index)
1255 {
1256     clientchar_t *tp;
1257     int prefixCount;
1258
1259     tp = cm_ClientStrRChr(inp, '@');
1260     if (tp == NULL) 
1261         return 0;               /* no @sys */
1262
1263     if (cm_ClientStrCmp(tp, _C("@sys")) != 0) 
1264         return 0;       /* no @sys */
1265
1266     /* caller just wants to know if this is a valid @sys type of name */
1267     if (outp == NULL) 
1268         return 1;
1269
1270     if (index >= cm_sysNameCount)
1271         return -1;
1272
1273     /* otherwise generate the properly expanded @sys name */
1274     prefixCount = (int)(tp - inp);
1275
1276     cm_ClientStrCpyN(outp, outSizeCch, inp, prefixCount);       /* copy out "a." from "a.@sys" */
1277     outp[prefixCount] = 0;              /* null terminate the "a." */
1278     cm_ClientStrCat(outp, outSizeCch, cm_sysNameList[index]);/* append i386_nt40 */
1279     return 1;
1280 }   
1281
1282 long cm_EvaluateVolumeReference(clientchar_t * namep, long flags, cm_user_t * userp,
1283                                 cm_req_t *reqp, cm_scache_t ** outpScpp)
1284 {
1285     afs_uint32    code = 0;
1286     fschar_t      cellName[CELL_MAXNAMELEN];
1287     fschar_t      volumeName[VL_MAXNAMELEN];
1288     size_t        len;
1289     fschar_t *        cp;
1290     fschar_t *        tp;
1291     fschar_t *        fnamep = NULL;
1292
1293     cm_cell_t *   cellp = NULL;
1294     cm_volume_t * volp = NULL;
1295     cm_fid_t      fid;
1296     afs_uint32    volume;
1297     int           volType;
1298     int           mountType = RWVOL;
1299
1300     osi_Log1(afsd_logp, "cm_EvaluateVolumeReference for string [%S]",
1301              osi_LogSaveClientString(afsd_logp, namep));
1302
1303     if (cm_ClientStrCmpNI(namep, _C(CM_PREFIX_VOL), CM_PREFIX_VOL_CCH) != 0) {
1304         goto _exit_invalid_path;
1305     }
1306
1307     /* namep is assumed to look like the following:
1308
1309        @vol:<cellname>%<volume>\0
1310        or
1311        @vol:<cellname>#<volume>\0
1312
1313      */
1314
1315     fnamep = cm_ClientStringToFsStringAlloc(namep, -1, NULL);
1316     cp = fnamep + CM_PREFIX_VOL_CCH; /* cp points to cell name, hopefully */
1317     tp = cm_FsStrChr(cp, '%');
1318     if (tp == NULL)
1319         tp = cm_FsStrChr(cp, '#');
1320     if (tp == NULL ||
1321         (len = tp - cp) == 0 ||
1322         len > CELL_MAXNAMELEN)
1323         goto _exit_invalid_path;
1324     cm_FsStrCpyN(cellName, lengthof(cellName), cp, len);
1325
1326     if (*tp == '#')
1327         mountType = ROVOL;
1328
1329     cp = tp+1;                  /* cp now points to volume, supposedly */
1330     cm_FsStrCpy(volumeName, lengthof(volumeName), cp);
1331
1332     /* OK, now we have the cell and the volume */
1333     osi_Log2(afsd_logp, "   Found cell [%s] and volume [%s]",
1334              osi_LogSaveFsString(afsd_logp, cellName),
1335              osi_LogSaveFsString(afsd_logp, volumeName));
1336
1337     cellp = cm_GetCell(cellName, CM_FLAG_CREATE);
1338     if (cellp == NULL) {
1339         goto _exit_invalid_path;
1340     }
1341
1342     len = cm_FsStrLen(volumeName);
1343     if (len >= 8 && cm_FsStrCmp(volumeName + len - 7, ".backup") == 0)
1344         volType = BACKVOL;
1345     else if (len >= 10 &&
1346              cm_FsStrCmp(volumeName + len - 9, ".readonly") == 0)
1347         volType = ROVOL;
1348     else
1349         volType = RWVOL;
1350
1351     if (cm_VolNameIsID(volumeName)) {
1352         code = cm_FindVolumeByID(cellp, atoi(volumeName), userp, reqp,
1353                                 CM_GETVOL_FLAG_CREATE, &volp);
1354     } else {
1355         code = cm_FindVolumeByName(cellp, volumeName, userp, reqp,
1356                                   CM_GETVOL_FLAG_CREATE, &volp);
1357     }
1358
1359     if (code != 0)
1360         goto _exit_cleanup;
1361
1362     if (volType == BACKVOL)
1363         volume = volp->vol[BACKVOL].ID;
1364     else if (volType == ROVOL ||
1365              (volType == RWVOL && mountType == ROVOL && volp->vol[ROVOL].ID != 0))
1366         volume = volp->vol[ROVOL].ID;
1367     else
1368         volume = volp->vol[RWVOL].ID;
1369
1370     cm_SetFid(&fid, cellp->cellID, volume, 1, 1);
1371
1372     code = cm_GetSCache(&fid, outpScpp, userp, reqp);
1373
1374   _exit_cleanup:
1375     if (fnamep)
1376         free(fnamep);
1377
1378     if (volp)
1379         cm_PutVolume(volp);
1380
1381     if (code == 0)
1382         return code;
1383
1384  _exit_invalid_path:
1385     if (flags & CM_FLAG_CHECKPATH)
1386         return CM_ERROR_NOSUCHPATH;
1387     else
1388         return CM_ERROR_NOSUCHFILE;
1389 }
1390
1391 #ifdef DEBUG_REFCOUNT
1392 long cm_LookupDbg(cm_scache_t *dscp, clientchar_t *namep, long flags, cm_user_t *userp,
1393                cm_req_t *reqp, cm_scache_t **outpScpp, char * file, long line)
1394 #else
1395 long cm_Lookup(cm_scache_t *dscp, clientchar_t *namep, long flags, cm_user_t *userp,
1396                cm_req_t *reqp, cm_scache_t **outpScpp)
1397 #endif
1398 {
1399     long code;
1400     clientchar_t tname[AFSPATHMAX];
1401     int sysNameIndex = 0;
1402     cm_scache_t *scp = NULL;
1403
1404 #ifdef DEBUG_REFCOUNT
1405     afsi_log("%s:%d cm_Lookup dscp 0x%p ref %d", file, line, dscp, dscp->refCount, file, line);
1406     osi_Log2(afsd_logp, "cm_Lookup dscp 0x%p ref %d", dscp, dscp->refCount);
1407 #endif
1408
1409     if ( cm_ClientStrCmpI(namep,_C(SMB_IOCTL_FILENAME_NOSLASH)) == 0 ) {
1410         if (flags & CM_FLAG_CHECKPATH)
1411             return CM_ERROR_NOSUCHPATH;
1412         else
1413             return CM_ERROR_NOSUCHFILE;
1414     }
1415
1416     if (dscp == cm_data.rootSCachep &&
1417         cm_ClientStrCmpNI(namep, _C(CM_PREFIX_VOL), CM_PREFIX_VOL_CCH) == 0) {
1418         return cm_EvaluateVolumeReference(namep, flags, userp, reqp, outpScpp);
1419     }
1420
1421     if (cm_ExpandSysName(namep, NULL, 0, 0) > 0) {
1422         for ( sysNameIndex = 0; sysNameIndex < MAXNUMSYSNAMES; sysNameIndex++) {
1423             code = cm_ExpandSysName(namep, tname, lengthof(tname), sysNameIndex);
1424             if (code > 0) {
1425                 code = cm_LookupInternal(dscp, tname, flags, userp, reqp, &scp);
1426 #ifdef DEBUG_REFCOUNT
1427                 afsi_log("%s:%d cm_LookupInternal (1) code 0x%x dscp 0x%p ref %d scp 0x%p ref %d", file, line, code, dscp, dscp->refCount, scp, scp ? scp->refCount : 0);
1428                 osi_Log3(afsd_logp, "cm_LookupInternal (1) code 0x%x dscp 0x%p scp 0x%p", code, dscp, scp);
1429 #endif
1430
1431                 if (code == 0) {
1432                     *outpScpp = scp;
1433                     return 0;
1434                 }
1435                 if (scp) {
1436                     cm_ReleaseSCache(scp);
1437                     scp = NULL;
1438                 }
1439             } else {
1440                 code = cm_LookupInternal(dscp, namep, flags, userp, reqp, &scp);
1441 #ifdef DEBUG_REFCOUNT
1442                 afsi_log("%s:%d cm_LookupInternal (2) code 0x%x dscp 0x%p ref %d scp 0x%p ref %d", file, line, code, dscp, dscp->refCount, scp, scp ? scp->refCount : 0);
1443                 osi_Log3(afsd_logp, "cm_LookupInternal (2) code 0x%x dscp 0x%p scp 0x%p", code, dscp, scp);
1444 #endif
1445                 *outpScpp = scp;
1446                 return code;
1447             }
1448         }
1449     } else {
1450         code = cm_LookupInternal(dscp, namep, flags, userp, reqp, &scp);
1451 #ifdef DEBUG_REFCOUNT
1452         afsi_log("%s:%d cm_LookupInternal (2) code 0x%x dscp 0x%p ref %d scp 0x%p ref %d", file, line, code, dscp, dscp->refCount, scp, scp ? scp->refCount : 0);
1453         osi_Log3(afsd_logp, "cm_LookupInternal (2) code 0x%x dscp 0x%p scp 0x%p", code, dscp, scp);
1454 #endif
1455         *outpScpp = scp;
1456         return code;
1457     }
1458
1459     /* None of the possible sysName expansions could be found */
1460     if (flags & CM_FLAG_CHECKPATH)
1461         return CM_ERROR_NOSUCHPATH;
1462     else
1463         return CM_ERROR_NOSUCHFILE;
1464 }
1465
1466 /*! \brief Unlink a file name
1467
1468   Encapsulates a call to RXAFS_RemoveFile().
1469
1470   \param[in] dscp cm_scache_t pointing at the directory containing the
1471       name to be unlinked.
1472
1473   \param[in] fnamep Original name to be unlinked.  This is the
1474       name that will be passed into the RXAFS_RemoveFile() call.
1475       This parameter is optional.  If not provided, the value will
1476       be looked up.
1477
1478   \param[in] came Client name to be unlinked.  This name will be used
1479       to update the local directory caches.
1480
1481   \param[in] userp cm_user_t for the request.
1482
1483   \param[in] reqp Request tracker.
1484  
1485  */
1486 long cm_Unlink(cm_scache_t *dscp, fschar_t *fnamep, clientchar_t * cnamep,
1487                cm_user_t *userp, cm_req_t *reqp)
1488 {
1489     long code;
1490     cm_conn_t *connp;
1491     AFSFid afsFid;
1492     int sflags;
1493     AFSFetchStatus newDirStatus;
1494     AFSVolSync volSync;
1495     struct rx_connection * rxconnp;
1496     cm_dirOp_t dirop;
1497     cm_scache_t *scp = NULL;
1498     int free_fnamep = FALSE;
1499
1500     if (fnamep == NULL) {
1501         code = -1;
1502 #ifdef USE_BPLUS
1503         code = cm_BeginDirOp(dscp, userp, reqp, CM_DIRLOCK_READ, &dirop);
1504         if (code == 0) {
1505             code = cm_BPlusDirLookupOriginalName(&dirop, cnamep, &fnamep);
1506             if (code == 0)
1507                 free_fnamep = TRUE;
1508             cm_EndDirOp(&dirop);
1509         }
1510 #endif
1511         if (code)
1512             goto done;
1513     }
1514
1515 #ifdef AFS_FREELANCE_CLIENT
1516     if (cm_freelanceEnabled && dscp == cm_data.rootSCachep) {
1517         /* deleting a mount point from the root dir. */
1518         code = cm_FreelanceRemoveMount(fnamep);
1519         goto done;
1520     }
1521 #endif  
1522
1523     code = cm_Lookup(dscp, cnamep, CM_FLAG_NOMOUNTCHASE, userp, reqp, &scp);
1524
1525     /* make sure we don't screw up the dir status during the merge */
1526     code = cm_BeginDirOp(dscp, userp, reqp, CM_DIRLOCK_NONE, &dirop);
1527
1528     lock_ObtainWrite(&dscp->rw);
1529     sflags = CM_SCACHESYNC_STOREDATA;
1530     code = cm_SyncOp(dscp, NULL, userp, reqp, 0, sflags);
1531     lock_ReleaseWrite(&dscp->rw);
1532     if (code) {
1533         cm_EndDirOp(&dirop);
1534         goto done;
1535     }
1536
1537     /* make the RPC */
1538     afsFid.Volume = dscp->fid.volume;
1539     afsFid.Vnode = dscp->fid.vnode;
1540     afsFid.Unique = dscp->fid.unique;
1541
1542     osi_Log1(afsd_logp, "CALL RemoveFile scp 0x%p", dscp);
1543     do {
1544         code = cm_ConnFromFID(&dscp->fid, userp, reqp, &connp);
1545         if (code)
1546             continue;
1547
1548         rxconnp = cm_GetRxConn(connp);
1549         code = RXAFS_RemoveFile(rxconnp, &afsFid, fnamep,
1550                                 &newDirStatus, &volSync);
1551         rx_PutConnection(rxconnp);
1552
1553     } while (cm_Analyze(connp, userp, reqp, &dscp->fid, &volSync, NULL, NULL, code));
1554     code = cm_MapRPCError(code, reqp);
1555
1556     if (code)
1557         osi_Log1(afsd_logp, "CALL RemoveFile FAILURE, code 0x%x", code);
1558     else
1559         osi_Log0(afsd_logp, "CALL RemoveFile SUCCESS");
1560
1561     if (dirop.scp) {
1562         lock_ObtainWrite(&dirop.scp->dirlock);
1563         dirop.lockType = CM_DIRLOCK_WRITE;
1564     }
1565     lock_ObtainWrite(&dscp->rw);
1566     cm_dnlcRemove(dscp, cnamep);
1567     cm_SyncOpDone(dscp, NULL, sflags);
1568     if (code == 0) {
1569         cm_MergeStatus(NULL, dscp, &newDirStatus, &volSync, userp, CM_MERGEFLAG_DIROP);
1570     } else if (code == CM_ERROR_NOSUCHFILE) {
1571         /* windows would not have allowed the request to delete the file 
1572          * if it did not believe the file existed.  therefore, we must 
1573          * have an inconsistent view of the world.
1574          */
1575         dscp->cbServerp = NULL;
1576     }
1577     lock_ReleaseWrite(&dscp->rw);
1578
1579     if (code == 0 && cm_CheckDirOpForSingleChange(&dirop) && cnamep) {
1580         cm_DirDeleteEntry(&dirop, fnamep);
1581 #ifdef USE_BPLUS
1582         cm_BPlusDirDeleteEntry(&dirop, cnamep);
1583 #endif
1584     }
1585     cm_EndDirOp(&dirop);
1586
1587     if (scp) {
1588         cm_ReleaseSCache(scp);
1589         if (code == 0) {
1590             lock_ObtainWrite(&scp->rw);
1591             scp->flags |= CM_SCACHEFLAG_DELETED;
1592             lock_ReleaseWrite(&scp->rw);
1593         }
1594     }
1595
1596   done:
1597     if (free_fnamep)
1598         free(fnamep);
1599
1600     return code;
1601 }
1602
1603 /* called with a write locked vnode, and fills in the link info.
1604  * returns this the vnode still write locked.
1605  */
1606 long cm_HandleLink(cm_scache_t *linkScp, cm_user_t *userp, cm_req_t *reqp)
1607 {
1608     long code;
1609     cm_buf_t *bufp;
1610     long temp;
1611     osi_hyper_t thyper;
1612
1613     lock_AssertWrite(&linkScp->rw);
1614     if (!linkScp->mountPointStringp[0]) {
1615         /* read the link data */
1616         lock_ReleaseWrite(&linkScp->rw);
1617         thyper.LowPart = thyper.HighPart = 0;
1618         code = buf_Get(linkScp, &thyper, &bufp);
1619         lock_ObtainWrite(&linkScp->rw);
1620         if (code) 
1621             return code;
1622         while (1) {
1623             code = cm_SyncOp(linkScp, bufp, userp, reqp, 0,
1624                               CM_SCACHESYNC_NEEDCALLBACK | CM_SCACHESYNC_READ);
1625             if (code) {
1626                 buf_Release(bufp);
1627                 return code;
1628             }
1629             cm_SyncOpDone(linkScp, bufp, CM_SCACHESYNC_NEEDCALLBACK | CM_SCACHESYNC_READ);
1630
1631             if (cm_HaveBuffer(linkScp, bufp, 0)) 
1632                 break;
1633
1634             code = cm_GetBuffer(linkScp, bufp, NULL, userp, reqp);
1635             if (code) {
1636                 buf_Release(bufp);
1637                 return code;
1638             }
1639         } /* while loop to get the data */
1640                 
1641         /* now if we still have no link read in,
1642          * copy the data from the buffer */
1643         if ((temp = linkScp->length.LowPart) >= MOUNTPOINTLEN) {
1644             buf_Release(bufp);
1645             return CM_ERROR_TOOBIG;
1646         }
1647
1648         /* otherwise, it fits; make sure it is still null (could have
1649          * lost race with someone else referencing this link above),
1650          * and if so, copy in the data.
1651          */
1652         if (!linkScp->mountPointStringp[0]) {
1653             strncpy(linkScp->mountPointStringp, bufp->datap, temp);
1654             linkScp->mountPointStringp[temp] = 0;       /* null terminate */
1655
1656             if ( !strnicmp(linkScp->mountPointStringp, "msdfs:", strlen("msdfs:")) )
1657                  linkScp->fileType = CM_SCACHETYPE_DFSLINK;
1658         }
1659         buf_Release(bufp);
1660     }   /* don't have sym link contents cached */
1661
1662     return 0;
1663 }       
1664
1665 /* called with a held vnode and a path suffix, with the held vnode being a
1666  * symbolic link.  Our goal is to generate a new path to interpret, and return
1667  * this new path in newSpaceBufferp.  If the new vnode is relative to a dir
1668  * other than the directory containing the symbolic link, then the new root is
1669  * returned in *newRootScpp, otherwise a null is returned there.
1670  */
1671 long cm_AssembleLink(cm_scache_t *linkScp, fschar_t *pathSuffixp,
1672                      cm_scache_t **newRootScpp, cm_space_t **newSpaceBufferp,
1673                      cm_user_t *userp, cm_req_t *reqp)
1674 {
1675     long code = 0;
1676     long len;
1677     fschar_t *linkp;
1678     cm_space_t *tsp;
1679
1680     *newRootScpp = NULL;
1681     *newSpaceBufferp = NULL;
1682
1683     lock_ObtainWrite(&linkScp->rw);
1684     code = cm_HandleLink(linkScp, userp, reqp);
1685     if (code)
1686         goto done;
1687
1688     /* if we may overflow the buffer, bail out; buffer is signficantly
1689      * bigger than max path length, so we don't really have to worry about
1690      * being a little conservative here.
1691      */
1692     if (cm_FsStrLen(linkScp->mountPointStringp) + cm_FsStrLen(pathSuffixp) + 2
1693         >= CM_UTILS_SPACESIZE) {
1694         code = CM_ERROR_TOOBIG;
1695         goto done;
1696     }
1697
1698     tsp = cm_GetSpace();
1699     linkp = linkScp->mountPointStringp;
1700     if (strncmp(linkp, cm_mountRoot, cm_mountRootLen) == 0) {
1701         if (strlen(linkp) > cm_mountRootLen)
1702             StringCbCopyA((char *) tsp->data, sizeof(tsp->data), linkp+cm_mountRootLen+1);
1703         else
1704             tsp->data[0] = 0;
1705         *newRootScpp = cm_data.rootSCachep;
1706         cm_HoldSCache(cm_data.rootSCachep);
1707     } else if (linkp[0] == '\\' && linkp[1] == '\\') {
1708         if (!strnicmp(&linkp[2], cm_NetbiosName, (len = (long)strlen(cm_NetbiosName)))) 
1709         {
1710             char * p = &linkp[len + 3];
1711             if (strnicmp(p, "all", 3) == 0)
1712                 p += 4;
1713
1714             StringCbCopyA(tsp->data, sizeof(tsp->data), p);
1715             for (p = tsp->data; *p; p++) {
1716                 if (*p == '\\')
1717                     *p = '/';
1718             }
1719             *newRootScpp = cm_data.rootSCachep;
1720             cm_HoldSCache(cm_data.rootSCachep);
1721         } else {
1722             linkScp->fileType = CM_SCACHETYPE_DFSLINK;
1723             StringCchCopyA(tsp->data,lengthof(tsp->data), linkp);
1724             code = CM_ERROR_PATH_NOT_COVERED;
1725         }
1726     } else if ( linkScp->fileType == CM_SCACHETYPE_DFSLINK ||
1727                 !strnicmp(linkp, "msdfs:", (len = (long)strlen("msdfs:"))) ) {
1728         linkScp->fileType = CM_SCACHETYPE_DFSLINK;
1729         StringCchCopyA(tsp->data,lengthof(tsp->data), linkp);
1730         code = CM_ERROR_PATH_NOT_COVERED;
1731     } else if (*linkp == '\\' || *linkp == '/') {
1732 #if 0   
1733         /* formerly, this was considered to be from the AFS root,
1734          * but this seems to create problems.  instead, we will just
1735          * reject the link */
1736         StringCchCopyA(tsp->data,lengthof(tsp->data), linkp+1);
1737         *newRootScpp = cm_data.rootSCachep;
1738         cm_HoldSCache(cm_data.rootSCachep);
1739 #else
1740         /* we still copy the link data into the response so that 
1741          * the user can see what the link points to
1742          */
1743         linkScp->fileType = CM_SCACHETYPE_INVALID;
1744         StringCchCopyA(tsp->data,lengthof(tsp->data), linkp);
1745         code = CM_ERROR_NOSUCHPATH;
1746 #endif  
1747     } else {
1748         /* a relative link */
1749         StringCchCopyA(tsp->data,lengthof(tsp->data), linkp);
1750     }
1751     if (pathSuffixp[0] != 0) {  /* if suffix string is non-null */
1752         StringCchCatA(tsp->data,lengthof(tsp->data), "\\");
1753         StringCchCatA(tsp->data,lengthof(tsp->data), pathSuffixp);
1754     }
1755     if (code == 0) {
1756         clientchar_t * cpath = cm_FsStringToClientStringAlloc(tsp->data, -1, NULL);
1757         cm_ClientStrCpy(tsp->wdata, lengthof(tsp->wdata), cpath);
1758         free(cpath);
1759         *newSpaceBufferp = tsp;
1760     } else {
1761         cm_FreeSpace(tsp);
1762
1763         if (code == CM_ERROR_PATH_NOT_COVERED && reqp->tidPathp && reqp->relPathp) {
1764             cm_VolStatus_Notify_DFS_Mapping(linkScp, reqp->tidPathp, reqp->relPathp);
1765         }
1766     }
1767
1768  done:
1769     lock_ReleaseWrite(&linkScp->rw);
1770     return code;
1771 }
1772 #ifdef DEBUG_REFCOUNT
1773 long cm_NameIDbg(cm_scache_t *rootSCachep, clientchar_t *pathp, long flags,
1774                  cm_user_t *userp, clientchar_t *tidPathp, cm_req_t *reqp,
1775                  cm_scache_t **outScpp, 
1776                  char * file, long line)
1777 #else
1778 long cm_NameI(cm_scache_t *rootSCachep, clientchar_t *pathp, long flags,
1779               cm_user_t *userp, clientchar_t *tidPathp,
1780               cm_req_t *reqp, cm_scache_t **outScpp)
1781 #endif
1782 {
1783     long code;
1784     clientchar_t *tp;                   /* ptr moving through input buffer */
1785     clientchar_t tc;                    /* temp char */
1786     int haveComponent;          /* has new component started? */
1787     clientchar_t component[AFSPATHMAX]; /* this is the new component */
1788     clientchar_t *cp;                   /* component name being assembled */
1789     cm_scache_t *tscp;          /* current location in the hierarchy */
1790     cm_scache_t *nscp;          /* next dude down */
1791     cm_scache_t *dirScp;        /* last dir we searched */
1792     cm_scache_t *linkScp;       /* new root for the symlink we just
1793     * looked up */
1794     cm_space_t *psp;            /* space for current path, if we've hit
1795     * any symlinks */
1796     cm_space_t *tempsp;         /* temp vbl */
1797     clientchar_t *restp;                /* rest of the pathname to interpret */
1798     int symlinkCount;           /* count of # of symlinks traversed */
1799     int extraFlag;              /* avoid chasing mt pts for dir cmd */
1800     int phase = 1;              /* 1 = tidPathp, 2 = pathp */
1801 #define MAX_FID_COUNT 512
1802     cm_fid_t fids[MAX_FID_COUNT]; /* array of fids processed in this path walk */
1803     int fid_count = 0;          /* number of fids processed in this path walk */
1804     int i;
1805
1806 #ifdef DEBUG_REFCOUNT
1807     afsi_log("%s:%d cm_NameI rootscp 0x%p ref %d", file, line, rootSCachep, rootSCachep->refCount);
1808     osi_Log4(afsd_logp,"cm_NameI rootscp 0x%p path %S tidpath %S flags 0x%x",
1809              rootSCachep, pathp ? pathp : "<NULL>", tidPathp ? tidPathp : "<NULL>", 
1810              flags);
1811 #endif
1812
1813     tp = tidPathp;
1814     if (tp == NULL) {
1815         tp = pathp;
1816         phase = 2;
1817     }
1818     if (tp == NULL) {
1819         tp = _C("");
1820     }
1821     haveComponent = 0;
1822     psp = NULL;
1823     tscp = rootSCachep;
1824     cm_HoldSCache(tscp);
1825     symlinkCount = 0;
1826     dirScp = NULL;
1827
1828
1829     while (1) {
1830         tc = *tp++;
1831
1832         /* map Unix slashes into DOS ones so we can interpret Unix
1833          * symlinks properly
1834          */
1835         if (tc == '/') 
1836             tc = '\\';
1837
1838         if (!haveComponent) {
1839             if (tc == '\\') {
1840                 continue;
1841             } else if (tc == 0) {
1842                 if (phase == 1) {
1843                     phase = 2;
1844                     tp = pathp;
1845                     continue;
1846                 }
1847                 code = 0;
1848                 break;
1849             } else {
1850                 haveComponent = 1;
1851                 cp = component;
1852                 *cp++ = tc;
1853             }
1854         } else {
1855             /* we have a component here */
1856             if (tc == 0 || tc == '\\') {
1857                 /* end of the component; we're at the last
1858                  * component if tc == 0.  However, if the last
1859                  * is a symlink, we have more to do.
1860                  */
1861                 *cp++ = 0;      /* add null termination */
1862                 extraFlag = 0;
1863                 if ((flags & CM_FLAG_DIRSEARCH) && tc == 0)
1864                     extraFlag = CM_FLAG_NOMOUNTCHASE;
1865                 code = cm_Lookup(tscp, component,
1866                                  flags | extraFlag,
1867                                  userp, reqp, &nscp);
1868
1869                 if (code == 0) {
1870                     if (!cm_ClientStrCmp(component,_C("..")) ||
1871                         !cm_ClientStrCmp(component,_C("."))) {
1872                         /* 
1873                          * roll back the fid list until we find the
1874                          * fid that matches where we are now.  Its not
1875                          * necessarily one or two fids because they
1876                          * might have been symlinks or mount points or
1877                          * both that were crossed.
1878                          */
1879                         for ( i=fid_count-1; i>=0; i--) {
1880                             if (!cm_FidCmp(&nscp->fid, &fids[i]))
1881                                 break;
1882                         }
1883                         fid_count = i+1;
1884                     } else {
1885                         /* add the new fid to the list */
1886                         for ( i=0; i<fid_count; i++) {
1887                             if ( !cm_FidCmp(&nscp->fid, &fids[i]) ) {
1888                                 code = CM_ERROR_TOO_MANY_SYMLINKS;
1889                                 cm_ReleaseSCache(nscp);
1890                                 nscp = NULL;
1891                                 break;
1892                             }
1893                         }
1894                         if (i == fid_count && fid_count < MAX_FID_COUNT) {
1895                             fids[fid_count++] = nscp->fid;
1896                         }
1897                     }
1898                 }
1899
1900                 if (code) {
1901                     cm_ReleaseSCache(tscp);
1902                     if (dirScp)
1903                         cm_ReleaseSCache(dirScp);
1904                     if (psp) 
1905                         cm_FreeSpace(psp);
1906                     if ((code == CM_ERROR_NOSUCHFILE || code == CM_ERROR_BPLUS_NOMATCH) && 
1907                         tscp->fileType == CM_SCACHETYPE_SYMLINK) {
1908                         osi_Log0(afsd_logp,"cm_NameI code CM_ERROR_NOSUCHPATH");
1909                         return CM_ERROR_NOSUCHPATH;
1910                     } else {
1911                         osi_Log1(afsd_logp,"cm_NameI code 0x%x", code);
1912                         return code;
1913                     }
1914                 }
1915
1916                 haveComponent = 0;      /* component done */
1917                 if (dirScp)
1918                     cm_ReleaseSCache(dirScp);
1919                 dirScp = tscp;          /* for some symlinks */
1920                 tscp = nscp;            /* already held */
1921                 nscp = NULL;
1922                 if (tc == 0 && !(flags & CM_FLAG_FOLLOW) && phase == 2) {
1923                     code = 0;
1924                     if (dirScp) {
1925                         cm_ReleaseSCache(dirScp);
1926                         dirScp = NULL;
1927                     }
1928                     break;
1929                 }
1930
1931                 /* now, if tscp is a symlink, we should follow it and
1932                  * assemble the path again.
1933                  */
1934                 lock_ObtainWrite(&tscp->rw);
1935                 code = cm_SyncOp(tscp, NULL, userp, reqp, 0,
1936                                   CM_SCACHESYNC_GETSTATUS
1937                                   | CM_SCACHESYNC_NEEDCALLBACK);
1938                 if (code) {
1939                     lock_ReleaseWrite(&tscp->rw);
1940                     cm_ReleaseSCache(tscp);
1941                     tscp = NULL;
1942                     if (dirScp) {
1943                         cm_ReleaseSCache(dirScp);
1944                         dirScp = NULL;
1945                     }
1946                     break;
1947                 }
1948                 cm_SyncOpDone(tscp, NULL, CM_SCACHESYNC_NEEDCALLBACK | CM_SCACHESYNC_GETSTATUS);
1949
1950                 if (tscp->fileType == CM_SCACHETYPE_SYMLINK) {
1951                     /* this is a symlink; assemble a new buffer */
1952                     lock_ReleaseWrite(&tscp->rw);
1953                     if (symlinkCount++ >= MAX_SYMLINK_COUNT) {
1954                         cm_ReleaseSCache(tscp);
1955                         tscp = NULL;
1956                         if (dirScp) {
1957                             cm_ReleaseSCache(dirScp);
1958                             dirScp = NULL;
1959                         }
1960                         if (psp) 
1961                             cm_FreeSpace(psp);
1962                         osi_Log0(afsd_logp,"cm_NameI code CM_ERROR_TOO_MANY_SYMLINKS");
1963                         return CM_ERROR_TOO_MANY_SYMLINKS;
1964                     }
1965                     if (tc == 0) 
1966                         restp = _C("");
1967                     else 
1968                         restp = tp;
1969
1970                     {
1971                         fschar_t * frestp;
1972
1973                         /* TODO: make this better */
1974                         frestp = cm_ClientStringToFsStringAlloc(restp, -1, NULL);
1975                         code = cm_AssembleLink(tscp, frestp, &linkScp, &tempsp, userp, reqp);
1976                         free(frestp);
1977                     }
1978
1979                     if (code == 0 && linkScp != NULL) {
1980                         if (linkScp == cm_data.rootSCachep) 
1981                             fid_count = 0;
1982                         else {
1983                             for ( i=0; i<fid_count; i++) {
1984                                 if ( !cm_FidCmp(&linkScp->fid, &fids[i]) ) {
1985                                     code = CM_ERROR_TOO_MANY_SYMLINKS;
1986                                     cm_ReleaseSCache(linkScp);
1987                                     nscp = NULL;
1988                                     break;
1989                                 }
1990                             }
1991                         }
1992                         if (i == fid_count && fid_count < MAX_FID_COUNT) {
1993                             fids[fid_count++] = linkScp->fid;
1994                         }
1995                     }
1996
1997                     if (code) {
1998                         /* something went wrong */
1999                         cm_ReleaseSCache(tscp);
2000                         tscp = NULL;
2001                         if (dirScp) {
2002                             cm_ReleaseSCache(dirScp);
2003                             dirScp = NULL;
2004                         }
2005                         break;
2006                     }
2007
2008                     /* otherwise, tempsp has the new path,
2009                      * and linkScp is the new root from
2010                      * which to interpret that path.
2011                      * Continue with the namei processing,
2012                      * also doing the bookkeeping for the
2013                      * space allocation and tracking the
2014                      * vnode reference counts.
2015                      */
2016                     if (psp) 
2017                         cm_FreeSpace(psp);
2018                     psp = tempsp;
2019                     tp = psp->wdata;
2020                     cm_ReleaseSCache(tscp);
2021                     tscp = linkScp;
2022                     linkScp = NULL;
2023                     /* already held
2024                      * by AssembleLink
2025                      * now, if linkScp is null, that's
2026                      * AssembleLink's way of telling us that
2027                      * the sym link is relative to the dir
2028                      * containing the link.  We have a ref
2029                      * to it in dirScp, and we hold it now
2030                      * and reuse it as the new spot in the
2031                      * dir hierarchy.
2032                      */
2033                     if (tscp == NULL) {
2034                         tscp = dirScp;
2035                         dirScp = NULL;
2036                     }
2037                 } else {
2038                     /* not a symlink, we may be done */
2039                     lock_ReleaseWrite(&tscp->rw);
2040                     if (tc == 0) {
2041                         if (phase == 1) {
2042                             phase = 2;
2043                             tp = pathp;
2044                             continue;
2045                         }
2046                         if (dirScp) {
2047                             cm_ReleaseSCache(dirScp);
2048                             dirScp = NULL;
2049                         }
2050                         code = 0;
2051                         break;
2052                     }
2053                 }
2054                 if (dirScp) {
2055                     cm_ReleaseSCache(dirScp);
2056                     dirScp = NULL;
2057                 }
2058             } /* end of a component */
2059             else 
2060                 *cp++ = tc;
2061         } /* we have a component */
2062     } /* big while loop over all components */
2063
2064     /* already held */
2065     if (dirScp)
2066         cm_ReleaseSCache(dirScp);
2067     if (psp) 
2068         cm_FreeSpace(psp);
2069     if (code == 0) 
2070         *outScpp = tscp;
2071     else if (tscp)
2072         cm_ReleaseSCache(tscp);
2073
2074 #ifdef DEBUG_REFCOUNT
2075     afsi_log("%s:%d cm_NameI code 0x%x outScpp 0x%p ref %d", file, line, code, *outScpp, (*outScpp)->refCount);
2076 #endif
2077     osi_Log2(afsd_logp,"cm_NameI code 0x%x outScpp 0x%p", code, *outScpp);
2078     return code;
2079 }
2080
2081 /* called with a dir, and a vnode within the dir that happens to be a symlink.
2082  * We chase the link, and return a held pointer to the target, if it exists,
2083  * in *outScpp.  If we succeed, we return 0, otherwise we return an error code
2084  * and do not hold or return a target vnode.
2085  *
2086  * This is very similar to calling cm_NameI with the last component of a name,
2087  * which happens to be a symlink, except that we've already passed by the name.
2088  *
2089  * This function is typically called by the directory listing functions, which
2090  * encounter symlinks but need to return the proper file length so programs
2091  * like "more" work properly when they make use of the attributes retrieved from
2092  * the dir listing.
2093  *
2094  * The input vnode should not be locked when this function is called.
2095  */
2096 long cm_EvaluateSymLink(cm_scache_t *dscp, cm_scache_t *linkScp,
2097                          cm_scache_t **outScpp, cm_user_t *userp, cm_req_t *reqp)
2098 {
2099     long code;
2100     cm_space_t *spacep;
2101     cm_scache_t *newRootScp;
2102
2103     osi_Log1(afsd_logp, "Evaluating symlink scp 0x%p", linkScp);
2104
2105     code = cm_AssembleLink(linkScp, "", &newRootScp, &spacep, userp, reqp);
2106     if (code) 
2107         return code;
2108
2109     /* now, if newRootScp is NULL, we're really being told that the symlink
2110      * is relative to the current directory (dscp).
2111      */
2112     if (newRootScp == NULL) {
2113         newRootScp = dscp;
2114         cm_HoldSCache(dscp);
2115     }
2116
2117     code = cm_NameI(newRootScp, spacep->wdata,
2118                     CM_FLAG_CASEFOLD | CM_FLAG_FOLLOW | CM_FLAG_DIRSEARCH,
2119                     userp, NULL, reqp, outScpp);
2120
2121     if (code == CM_ERROR_NOSUCHFILE || code == CM_ERROR_BPLUS_NOMATCH)
2122         code = CM_ERROR_NOSUCHPATH;
2123
2124     /* this stuff is allocated no matter what happened on the namei call,
2125      * so free it */
2126     cm_FreeSpace(spacep);
2127     cm_ReleaseSCache(newRootScp);
2128
2129     if (linkScp == *outScpp) {
2130         cm_ReleaseSCache(*outScpp);
2131         *outScpp = NULL;
2132         code = CM_ERROR_NOSUCHPATH;
2133     }
2134
2135     return code;
2136 }
2137
2138 /* for a given entry, make sure that it isn't in the stat cache, and then
2139  * add it to the list of file IDs to be obtained.
2140  *
2141  * Don't bother adding it if we already have a vnode.  Note that the dir
2142  * is locked, so we have to be careful checking the vnode we're thinking of
2143  * processing, to avoid deadlocks.
2144  */
2145 long cm_TryBulkProc(cm_scache_t *scp, cm_dirEntry_t *dep, void *rockp,
2146                      osi_hyper_t *offp)
2147 {
2148     osi_hyper_t thyper;
2149     cm_bulkStat_t *bsp;
2150     int i;
2151     cm_scache_t *tscp;
2152     cm_fid_t tfid;
2153
2154     bsp = rockp;
2155
2156     /* Don't overflow bsp. */
2157     if (bsp->counter >= CM_BULKMAX)
2158         return CM_ERROR_STOPNOW;
2159
2160     thyper.LowPart = cm_data.buf_blockSize;
2161     thyper.HighPart = 0;
2162     thyper = LargeIntegerAdd(thyper, bsp->bufOffset);
2163
2164     /* thyper is now the first byte past the end of the record we're
2165      * interested in, and bsp->bufOffset is the first byte of the record
2166      * we're interested in.
2167      * Skip data in the others.
2168      * Skip '.' and '..'
2169      */
2170     if (LargeIntegerLessThan(*offp, bsp->bufOffset))
2171         return 0;
2172     if (LargeIntegerGreaterThanOrEqualTo(*offp, thyper))
2173         return CM_ERROR_STOPNOW;
2174     if (strcmp(dep->name, ".") == 0 || strcmp(dep->name, "..") == 0)
2175         return 0;
2176
2177     cm_SetFid(&tfid, scp->fid.cell, scp->fid.volume, ntohl(dep->fid.vnode), ntohl(dep->fid.unique));
2178     tscp = cm_FindSCache(&tfid);
2179     if (tscp) {
2180         if (lock_TryWrite(&tscp->rw)) {
2181             /* we have an entry that we can look at */
2182             if (!(tscp->flags & CM_SCACHEFLAG_EACCESS) && cm_HaveCallback(tscp)) {
2183                 /* we have a callback on it.  Don't bother
2184                  * fetching this stat entry, since we're happy
2185                  * with the info we have.
2186                  */
2187                 lock_ReleaseWrite(&tscp->rw);
2188                 cm_ReleaseSCache(tscp);
2189                 return 0;
2190             }
2191             lock_ReleaseWrite(&tscp->rw);
2192         }       /* got lock */
2193         cm_ReleaseSCache(tscp);
2194     }   /* found entry */
2195
2196 #ifdef AFS_FREELANCE_CLIENT
2197     // yj: if this is a mountpoint under root.afs then we don't want it
2198     // to be bulkstat-ed, instead, we call getSCache directly and under
2199     // getSCache, it is handled specially.
2200     if  ( cm_freelanceEnabled &&
2201           tfid.cell==AFS_FAKE_ROOT_CELL_ID && 
2202           tfid.volume==AFS_FAKE_ROOT_VOL_ID &&
2203           !(tfid.vnode==0x1 && tfid.unique==0x1) )
2204     {       
2205         osi_Log0(afsd_logp, "cm_TryBulkProc Freelance calls cm_SCache on root.afs mountpoint");
2206         return cm_GetSCache(&tfid, &tscp, NULL, NULL);
2207     }
2208 #endif /* AFS_FREELANCE_CLIENT */
2209
2210     i = bsp->counter++;
2211     bsp->fids[i].Volume = scp->fid.volume;
2212     bsp->fids[i].Vnode = tfid.vnode;
2213     bsp->fids[i].Unique = tfid.unique;
2214     return 0;
2215 }       
2216
2217 afs_int32
2218 cm_TryBulkStatRPC(cm_scache_t *dscp, cm_bulkStat_t *bbp, cm_user_t *userp, cm_req_t *reqp)
2219 {
2220     afs_int32 code = 0;
2221     AFSCBFids fidStruct;
2222     AFSBulkStats statStruct;
2223     cm_conn_t *connp;
2224     AFSCBs callbackStruct;
2225     long filex;
2226     AFSVolSync volSync;
2227     cm_callbackRequest_t cbReq;
2228     long filesThisCall;
2229     long i;
2230     long j;
2231     cm_scache_t *scp;
2232     cm_fid_t tfid;
2233     struct rx_connection * rxconnp;
2234     int inlinebulk = 0;         /* Did we use InlineBulkStatus RPC or not? */
2235         
2236     /* otherwise, we may have one or more bulk stat's worth of stuff in bb;
2237      * make the calls to create the entries.  Handle AFSCBMAX files at a
2238      * time.
2239      */
2240     for (filex = 0; filex < bbp->counter; filex += filesThisCall) {
2241         filesThisCall = bbp->counter - filex;
2242         if (filesThisCall > AFSCBMAX) 
2243             filesThisCall = AFSCBMAX;
2244
2245         fidStruct.AFSCBFids_len = filesThisCall;
2246         fidStruct.AFSCBFids_val = &bbp->fids[filex];
2247         statStruct.AFSBulkStats_len = filesThisCall;
2248         statStruct.AFSBulkStats_val = &bbp->stats[filex];
2249         callbackStruct.AFSCBs_len = filesThisCall;
2250         callbackStruct.AFSCBs_val = &bbp->callbacks[filex];
2251         cm_StartCallbackGrantingCall(NULL, &cbReq);
2252         osi_Log1(afsd_logp, "CALL BulkStatus, %d entries", filesThisCall);
2253         do {
2254             code = cm_ConnFromFID(&dscp->fid, userp, reqp, &connp);
2255             if (code) 
2256                 continue;
2257
2258             rxconnp = cm_GetRxConn(connp);
2259             if (!(connp->serverp->flags & CM_SERVERFLAG_NOINLINEBULK)) {
2260                 code = RXAFS_InlineBulkStatus(rxconnp, &fidStruct,
2261                                      &statStruct, &callbackStruct, &volSync);
2262                 if (code == RXGEN_OPCODE) {
2263                     cm_SetServerNoInlineBulk(connp->serverp, 0);
2264                 } else {
2265                     inlinebulk = 1;
2266                 }
2267             }
2268             if (!inlinebulk) {
2269                 code = RXAFS_BulkStatus(rxconnp, &fidStruct,
2270                                         &statStruct, &callbackStruct, &volSync);
2271             }
2272             rx_PutConnection(rxconnp);
2273
2274         } while (cm_Analyze(connp, userp, reqp, &dscp->fid,
2275                              &volSync, NULL, &cbReq, code));
2276         code = cm_MapRPCError(code, reqp);
2277         if (code)
2278             osi_Log2(afsd_logp, "CALL %sBulkStatus FAILURE code 0x%x", 
2279                       inlinebulk ? "Inline" : "", code);
2280         else
2281             osi_Log1(afsd_logp, "CALL %sBulkStatus SUCCESS", inlinebulk ? "Inline" : "");
2282
2283         /* may as well quit on an error, since we're not going to do
2284          * much better on the next immediate call, either.
2285          */
2286         if (code) {
2287             cm_EndCallbackGrantingCall(NULL, &cbReq, NULL, 0);
2288             break;
2289         }
2290
2291         /* otherwise, we should do the merges */
2292         for (i = 0; i<filesThisCall; i++) {
2293             j = filex + i;
2294             cm_SetFid(&tfid, dscp->fid.cell, bbp->fids[j].Volume, bbp->fids[j].Vnode, bbp->fids[j].Unique);
2295             code = cm_GetSCache(&tfid, &scp, userp, reqp);
2296             if (code != 0) 
2297                 continue;
2298
2299             /* otherwise, if this entry has no callback info, 
2300              * merge in this.
2301              */
2302             lock_ObtainWrite(&scp->rw);
2303             /* now, we have to be extra paranoid on merging in this
2304              * information, since we didn't use cm_SyncOp before
2305              * starting the fetch to make sure that no bad races
2306              * were occurring.  Specifically, we need to make sure
2307              * we don't obliterate any newer information in the
2308              * vnode than have here.
2309              *
2310              * Right now, be pretty conservative: if there's a
2311              * callback or a pending call, skip it.
2312              */
2313             if ((scp->cbServerp == NULL || (scp->flags & CM_SCACHEFLAG_EACCESS))
2314                  && !(scp->flags &
2315                        (CM_SCACHEFLAG_FETCHING
2316                          | CM_SCACHEFLAG_STORING
2317                          | CM_SCACHEFLAG_SIZESTORING))) {
2318                 cm_EndCallbackGrantingCall(scp, &cbReq,
2319                                             &bbp->callbacks[j],
2320                                             CM_CALLBACK_MAINTAINCOUNT);
2321                 cm_MergeStatus(dscp, scp, &bbp->stats[j], &volSync, userp, 0);
2322             }       
2323             lock_ReleaseWrite(&scp->rw);
2324             cm_ReleaseSCache(scp);
2325         } /* all files in the response */
2326         /* now tell it to drop the count,
2327          * after doing the vnode processing above */
2328         cm_EndCallbackGrantingCall(NULL, &cbReq, NULL, 0);
2329     }   /* while there are still more files to process */
2330
2331     /* If we did the InlineBulk RPC pull out the return code and log it */
2332     if (inlinebulk) {
2333         if ((&bbp->stats[0])->errorCode) {
2334             osi_Log1(afsd_logp, "cm_TryBulkStat bulk stat error: %d", 
2335                      (&bbp->stats[0])->errorCode);
2336             code = (&bbp->stats[0])->errorCode;
2337         }
2338     }
2339
2340     return code;
2341 }
2342
2343 /* called with a write locked scp and a pointer to a buffer.  Make bulk stat
2344  * calls on all undeleted files in the page of the directory specified.
2345  */
2346 afs_int32
2347 cm_TryBulkStat(cm_scache_t *dscp, osi_hyper_t *offsetp, cm_user_t *userp,
2348                cm_req_t *reqp)
2349 {
2350     afs_int32 code;
2351     cm_bulkStat_t *bbp;
2352
2353     osi_Log1(afsd_logp, "cm_TryBulkStat dir 0x%p", dscp);
2354
2355     /* should be on a buffer boundary */
2356     osi_assertx((offsetp->LowPart & (cm_data.buf_blockSize - 1)) == 0, "invalid offset");
2357
2358     bbp = malloc(sizeof(cm_bulkStat_t));
2359     memset(bbp, 0, sizeof(cm_bulkStat_t));
2360     bbp->bufOffset = *offsetp;
2361
2362     lock_ReleaseWrite(&dscp->rw);
2363     /* first, assemble the file IDs we need to stat */
2364     code = cm_ApplyDir(dscp, cm_TryBulkProc, (void *) bbp, offsetp, userp, reqp, NULL);
2365
2366     /* if we failed, bail out early */
2367     if (code && code != CM_ERROR_STOPNOW) {
2368         free(bbp);
2369         lock_ObtainWrite(&dscp->rw);
2370         return code;
2371     }
2372
2373     code = cm_TryBulkStatRPC(dscp, bbp, userp, reqp);
2374     osi_Log1(afsd_logp, "END cm_TryBulkStat code 0x%x", code);
2375
2376     lock_ObtainWrite(&dscp->rw);
2377     free(bbp);
2378     return 0;
2379 }       
2380
2381 void cm_StatusFromAttr(AFSStoreStatus *statusp, cm_scache_t *scp, cm_attr_t *attrp)
2382 {
2383     long mask;
2384
2385     /* initialize store back mask as inexpensive local variable */
2386     mask = 0;
2387     memset(statusp, 0, sizeof(AFSStoreStatus));
2388
2389     /* copy out queued info from scache first, if scp passed in */
2390     if (scp) {
2391         if (scp->mask & CM_SCACHEMASK_CLIENTMODTIME) {
2392             statusp->ClientModTime = scp->clientModTime;
2393             mask |= AFS_SETMODTIME;
2394             scp->mask &= ~CM_SCACHEMASK_CLIENTMODTIME;
2395         }
2396     }
2397
2398     if (attrp) {
2399         /* now add in our locally generated request */
2400         if (attrp->mask & CM_ATTRMASK_CLIENTMODTIME) {
2401             statusp->ClientModTime = attrp->clientModTime;
2402             mask |= AFS_SETMODTIME;
2403         }
2404         if (attrp->mask & CM_ATTRMASK_UNIXMODEBITS) {
2405             statusp->UnixModeBits = attrp->unixModeBits;
2406             mask |= AFS_SETMODE;
2407         }
2408         if (attrp->mask & CM_ATTRMASK_OWNER) {
2409             statusp->Owner = attrp->owner;
2410             mask |= AFS_SETOWNER;
2411         }
2412         if (attrp->mask & CM_ATTRMASK_GROUP) {
2413             statusp->Group = attrp->group;
2414             mask |= AFS_SETGROUP;
2415         }
2416     }
2417     statusp->Mask = mask;
2418 }       
2419
2420 /* set the file size, and make sure that all relevant buffers have been
2421  * truncated.  Ensure that any partially truncated buffers have been zeroed
2422  * to the end of the buffer.
2423  */
2424 long cm_SetLength(cm_scache_t *scp, osi_hyper_t *sizep, cm_user_t *userp,
2425                    cm_req_t *reqp)
2426 {
2427     long code;
2428     int shrinking;
2429
2430     /* start by locking out buffer creation */
2431     lock_ObtainWrite(&scp->bufCreateLock);
2432
2433     /* verify that this is a file, not a dir or a symlink */
2434     lock_ObtainWrite(&scp->rw);
2435     code = cm_SyncOp(scp, NULL, userp, reqp, 0,
2436                       CM_SCACHESYNC_NEEDCALLBACK | CM_SCACHESYNC_GETSTATUS);
2437     if (code) 
2438         goto done;
2439     cm_SyncOpDone(scp, NULL, CM_SCACHESYNC_NEEDCALLBACK | CM_SCACHESYNC_GETSTATUS);
2440
2441     if (scp->fileType != CM_SCACHETYPE_FILE) {
2442         code = CM_ERROR_ISDIR;
2443         goto done;
2444     }
2445
2446   startover:
2447     if (LargeIntegerLessThan(*sizep, scp->length))
2448         shrinking = 1;
2449     else
2450         shrinking = 0;
2451
2452     lock_ReleaseWrite(&scp->rw);
2453
2454     /* can't hold scp->rw lock here, since we may wait for a storeback to
2455      * finish if the buffer package is cleaning a buffer by storing it to
2456      * the server.
2457      */
2458     if (shrinking)
2459         buf_Truncate(scp, userp, reqp, sizep);
2460
2461     /* now ensure that file length is short enough, and update truncPos */
2462     lock_ObtainWrite(&scp->rw);
2463
2464     /* make sure we have a callback (so we have the right value for the
2465      * length), and wait for it to be safe to do a truncate.
2466      */
2467     code = cm_SyncOp(scp, NULL, userp, reqp, PRSFS_WRITE,
2468                       CM_SCACHESYNC_NEEDCALLBACK | CM_SCACHESYNC_GETSTATUS
2469                       | CM_SCACHESYNC_SETSTATUS | CM_SCACHESYNC_SETSIZE);
2470
2471     /* If we only have 'i' bits, then we should still be able to set
2472        the size of a file we created. */
2473     if (code == CM_ERROR_NOACCESS && scp->creator == userp) {
2474         code = cm_SyncOp(scp, NULL, userp, reqp, PRSFS_INSERT,
2475                          CM_SCACHESYNC_NEEDCALLBACK | CM_SCACHESYNC_GETSTATUS
2476                          | CM_SCACHESYNC_SETSTATUS | CM_SCACHESYNC_SETSIZE);
2477     }
2478
2479     if (code) 
2480         goto done;
2481
2482     if (LargeIntegerLessThan(*sizep, scp->length)) {
2483         /* a real truncation.  If truncPos is not set yet, or is bigger
2484          * than where we're truncating the file, set truncPos to this
2485          * new value.
2486          */
2487         if (!shrinking)
2488             goto startover;
2489         if (!(scp->mask & CM_SCACHEMASK_TRUNCPOS)
2490              || LargeIntegerLessThan(*sizep, scp->length)) {
2491             /* set trunc pos */
2492             scp->truncPos = *sizep;
2493             scp->mask |= CM_SCACHEMASK_TRUNCPOS;
2494         }
2495         /* in either case, the new file size has been changed */
2496         scp->length = *sizep;
2497         scp->mask |= CM_SCACHEMASK_LENGTH;
2498     }
2499     else if (LargeIntegerGreaterThan(*sizep, scp->length)) {
2500         /* really extending the file */
2501         scp->length = *sizep;
2502         scp->mask |= CM_SCACHEMASK_LENGTH;
2503     }
2504
2505     /* done successfully */
2506     code = 0;
2507
2508     cm_SyncOpDone(scp, NULL, 
2509                    CM_SCACHESYNC_NEEDCALLBACK | CM_SCACHESYNC_GETSTATUS
2510                    | CM_SCACHESYNC_SETSTATUS | CM_SCACHESYNC_SETSIZE);
2511
2512   done:
2513     lock_ReleaseWrite(&scp->rw);
2514     lock_ReleaseWrite(&scp->bufCreateLock);
2515
2516     return code;
2517 }
2518
2519 /* set the file size or other attributes (but not both at once) */
2520 long cm_SetAttr(cm_scache_t *scp, cm_attr_t *attrp, cm_user_t *userp,
2521                 cm_req_t *reqp)
2522 {
2523     long code;
2524     AFSFetchStatus afsOutStatus;
2525     AFSVolSync volSync;
2526     cm_conn_t *connp;
2527     AFSFid tfid;
2528     AFSStoreStatus afsInStatus;
2529     struct rx_connection * rxconnp;
2530
2531     /* handle file length setting */
2532     if (attrp->mask & CM_ATTRMASK_LENGTH)
2533         return cm_SetLength(scp, &attrp->length, userp, reqp);
2534
2535     lock_ObtainWrite(&scp->rw);
2536     /* otherwise, we have to make an RPC to get the status */
2537     code = cm_SyncOp(scp, NULL, userp, reqp, 0, CM_SCACHESYNC_STORESTATUS);
2538     if (code) {
2539         lock_ReleaseWrite(&scp->rw);
2540         return code;
2541     }
2542     lock_ConvertWToR(&scp->rw);
2543
2544     /* make the attr structure */
2545     cm_StatusFromAttr(&afsInStatus, scp, attrp);
2546
2547     tfid.Volume = scp->fid.volume;
2548     tfid.Vnode = scp->fid.vnode;
2549     tfid.Unique = scp->fid.unique;
2550     lock_ReleaseRead(&scp->rw);
2551
2552     /* now make the RPC */
2553     osi_Log1(afsd_logp, "CALL StoreStatus scp 0x%p", scp);
2554     do {
2555         code = cm_ConnFromFID(&scp->fid, userp, reqp, &connp);
2556         if (code) 
2557             continue;
2558
2559         rxconnp = cm_GetRxConn(connp);
2560         code = RXAFS_StoreStatus(rxconnp, &tfid,
2561                                   &afsInStatus, &afsOutStatus, &volSync);
2562         rx_PutConnection(rxconnp);
2563
2564     } while (cm_Analyze(connp, userp, reqp,
2565                          &scp->fid, &volSync, NULL, NULL, code));
2566     code = cm_MapRPCError(code, reqp);
2567
2568     if (code)
2569         osi_Log1(afsd_logp, "CALL StoreStatus FAILURE, code 0x%x", code);
2570     else
2571         osi_Log0(afsd_logp, "CALL StoreStatus SUCCESS");
2572
2573     lock_ObtainWrite(&scp->rw);
2574     cm_SyncOpDone(scp, NULL, CM_SCACHESYNC_STORESTATUS);
2575     if (code == 0)
2576         cm_MergeStatus(NULL, scp, &afsOutStatus, &volSync, userp,
2577                         CM_MERGEFLAG_FORCE|CM_MERGEFLAG_STOREDATA);
2578         
2579     /* if we're changing the mode bits, discard the ACL cache, 
2580      * since we changed the mode bits.
2581      */
2582     if (afsInStatus.Mask & AFS_SETMODE) 
2583         cm_FreeAllACLEnts(scp);
2584     lock_ReleaseWrite(&scp->rw);
2585     return code;
2586 }       
2587
2588 long cm_Create(cm_scache_t *dscp, clientchar_t *cnamep, long flags, cm_attr_t *attrp,
2589                cm_scache_t **scpp, cm_user_t *userp, cm_req_t *reqp)
2590 {       
2591     cm_conn_t *connp;
2592     long code;
2593     AFSFid dirAFSFid;
2594     cm_callbackRequest_t cbReq;
2595     AFSFid newAFSFid;
2596     cm_fid_t newFid;
2597     cm_scache_t *scp = NULL;
2598     int didEnd;
2599     AFSStoreStatus inStatus;
2600     AFSFetchStatus updatedDirStatus;
2601     AFSFetchStatus newFileStatus;
2602     AFSCallBack newFileCallback;
2603     AFSVolSync volSync;
2604     struct rx_connection * rxconnp;
2605     cm_dirOp_t dirop;
2606     fschar_t * fnamep = NULL;
2607
2608     /* can't create names with @sys in them; must expand it manually first.
2609      * return "invalid request" if they try.
2610      */
2611     if (cm_ExpandSysName(cnamep, NULL, 0, 0)) {
2612         return CM_ERROR_ATSYS;
2613     }
2614
2615 #ifdef AFS_FREELANCE_CLIENT
2616     /* Freelance root volume does not hold files */
2617     if (cm_freelanceEnabled &&
2618         dscp->fid.cell==AFS_FAKE_ROOT_CELL_ID &&
2619         dscp->fid.volume==AFS_FAKE_ROOT_VOL_ID )
2620     {
2621         return CM_ERROR_NOACCESS;
2622     }
2623 #endif /* AFS_FREELANCE_CLIENT */
2624
2625     /* before starting the RPC, mark that we're changing the file data, so
2626      * that someone who does a chmod will know to wait until our call
2627      * completes.
2628      */
2629     cm_BeginDirOp(dscp, userp, reqp, CM_DIRLOCK_NONE, &dirop);
2630     lock_ObtainWrite(&dscp->rw);
2631     code = cm_SyncOp(dscp, NULL, userp, reqp, 0, CM_SCACHESYNC_STOREDATA);
2632     lock_ReleaseWrite(&dscp->rw);
2633     if (code == 0) {
2634         cm_StartCallbackGrantingCall(NULL, &cbReq);
2635     } else {
2636         cm_EndDirOp(&dirop);
2637     }
2638     if (code) {
2639         return code;
2640     }
2641     didEnd = 0;
2642
2643     fnamep = cm_ClientStringToFsStringAlloc(cnamep, -1, NULL);
2644
2645     cm_StatusFromAttr(&inStatus, NULL, attrp);
2646
2647     /* try the RPC now */
2648     osi_Log1(afsd_logp, "CALL CreateFile scp 0x%p", dscp);
2649     do {
2650         code = cm_ConnFromFID(&dscp->fid, userp, reqp, &connp);
2651         if (code) 
2652             continue;
2653
2654         dirAFSFid.Volume = dscp->fid.volume;
2655         dirAFSFid.Vnode = dscp->fid.vnode;
2656         dirAFSFid.Unique = dscp->fid.unique;
2657
2658         rxconnp = cm_GetRxConn(connp);
2659         code = RXAFS_CreateFile(connp->rxconnp, &dirAFSFid, fnamep,
2660                                  &inStatus, &newAFSFid, &newFileStatus,
2661                                  &updatedDirStatus, &newFileCallback,
2662                                  &volSync);
2663         rx_PutConnection(rxconnp);
2664
2665     } while (cm_Analyze(connp, userp, reqp,
2666                          &dscp->fid, &volSync, NULL, &cbReq, code));
2667     code = cm_MapRPCError(code, reqp);
2668         
2669     if (code)
2670         osi_Log1(afsd_logp, "CALL CreateFile FAILURE, code 0x%x", code);
2671     else
2672         osi_Log0(afsd_logp, "CALL CreateFile SUCCESS");
2673
2674     if (dirop.scp) {
2675         lock_ObtainWrite(&dirop.scp->dirlock);
2676         dirop.lockType = CM_DIRLOCK_WRITE;
2677     }
2678     lock_ObtainWrite(&dscp->rw);
2679     cm_SyncOpDone(dscp, NULL, CM_SCACHESYNC_STOREDATA);
2680     if (code == 0) {
2681         cm_MergeStatus(NULL, dscp, &updatedDirStatus, &volSync, userp, CM_MERGEFLAG_DIROP);
2682     }
2683     lock_ReleaseWrite(&dscp->rw);
2684
2685     /* now try to create the file's entry, too, but be careful to 
2686      * make sure that we don't merge in old info.  Since we weren't locking
2687      * out any requests during the file's creation, we may have pretty old
2688      * info.
2689      */
2690     if (code == 0) {
2691         cm_SetFid(&newFid, dscp->fid.cell, dscp->fid.volume, newAFSFid.Vnode, newAFSFid.Unique);
2692         code = cm_GetSCache(&newFid, &scp, userp, reqp);
2693         if (code == 0) {
2694             lock_ObtainWrite(&scp->rw);
2695             scp->creator = userp;               /* remember who created it */
2696             if (!cm_HaveCallback(scp)) {
2697                 cm_MergeStatus(dscp, scp, &newFileStatus, &volSync,
2698                                userp, 0);
2699                 cm_EndCallbackGrantingCall(scp, &cbReq,
2700                                            &newFileCallback, 0);
2701                 didEnd = 1;     
2702             }       
2703             lock_ReleaseWrite(&scp->rw);
2704             *scpp = scp;
2705         }
2706     }
2707
2708     /* make sure we end things properly */
2709     if (!didEnd)
2710         cm_EndCallbackGrantingCall(NULL, &cbReq, NULL, 0);
2711
2712     if (scp && cm_CheckDirOpForSingleChange(&dirop)) {
2713         cm_DirCreateEntry(&dirop, fnamep, &newFid);
2714 #ifdef USE_BPLUS
2715         cm_BPlusDirCreateEntry(&dirop, cnamep, &newFid);
2716 #endif
2717     }
2718     cm_EndDirOp(&dirop);
2719
2720     if (fnamep)
2721         free(fnamep);
2722
2723     return code;
2724 }       
2725
2726 long cm_FSync(cm_scache_t *scp, cm_user_t *userp, cm_req_t *reqp)
2727 {
2728     long code;
2729
2730     code = buf_CleanVnode(scp, userp, reqp);
2731     if (code == 0) {
2732         lock_ObtainWrite(&scp->rw);
2733
2734         if (scp->mask & (CM_SCACHEMASK_TRUNCPOS
2735                           | CM_SCACHEMASK_CLIENTMODTIME
2736                           | CM_SCACHEMASK_LENGTH))
2737             code = cm_StoreMini(scp, userp, reqp);
2738
2739         if (scp->flags & (CM_SCACHEFLAG_OVERQUOTA | CM_SCACHEFLAG_OUTOFSPACE)) {
2740             code = (scp->flags & CM_SCACHEFLAG_OVERQUOTA) ? CM_ERROR_QUOTA : CM_ERROR_SPACE;
2741             scp->flags &= ~(CM_SCACHEFLAG_OVERQUOTA | CM_SCACHEFLAG_OUTOFSPACE);
2742         }
2743
2744         lock_ReleaseWrite(&scp->rw);
2745     }
2746     return code;
2747 }
2748
2749 long cm_MakeDir(cm_scache_t *dscp, clientchar_t *cnamep, long flags, cm_attr_t *attrp,
2750                  cm_user_t *userp, cm_req_t *reqp)
2751 {
2752     cm_conn_t *connp;
2753     long code;
2754     AFSFid dirAFSFid;
2755     cm_callbackRequest_t cbReq;
2756     AFSFid newAFSFid;
2757     cm_fid_t newFid;
2758     cm_scache_t *scp = NULL;
2759     int didEnd;
2760     AFSStoreStatus inStatus;
2761     AFSFetchStatus updatedDirStatus;
2762     AFSFetchStatus newDirStatus;
2763     AFSCallBack newDirCallback;
2764     AFSVolSync volSync;
2765     struct rx_connection * rxconnp;
2766     cm_dirOp_t dirop;
2767     fschar_t * fnamep = NULL;
2768
2769     /* can't create names with @sys in them; must expand it manually first.
2770      * return "invalid request" if they try.
2771      */
2772     if (cm_ExpandSysName(cnamep, NULL, 0, 0)) {
2773         return CM_ERROR_ATSYS;
2774     }
2775
2776 #ifdef AFS_FREELANCE_CLIENT
2777     /* Freelance root volume does not hold subdirectories */
2778     if (cm_freelanceEnabled &&
2779         dscp->fid.cell==AFS_FAKE_ROOT_CELL_ID &&
2780         dscp->fid.volume==AFS_FAKE_ROOT_VOL_ID )
2781     {
2782         return CM_ERROR_NOACCESS;
2783     }
2784 #endif /* AFS_FREELANCE_CLIENT */
2785
2786     /* before starting the RPC, mark that we're changing the directory
2787      * data, so that someone who does a chmod on the dir will wait until
2788      * our call completes.
2789      */
2790     cm_BeginDirOp(dscp, userp, reqp, CM_DIRLOCK_NONE, &dirop);
2791     lock_ObtainWrite(&dscp->rw);
2792     code = cm_SyncOp(dscp, NULL, userp, reqp, 0, CM_SCACHESYNC_STOREDATA);
2793     lock_ReleaseWrite(&dscp->rw);
2794     if (code == 0) {
2795         cm_StartCallbackGrantingCall(NULL, &cbReq);
2796     } else {
2797         cm_EndDirOp(&dirop);
2798     }
2799     if (code) {
2800         return code;
2801     }
2802     didEnd = 0;
2803
2804     fnamep = cm_ClientStringToFsStringAlloc(cnamep, -1, NULL);
2805     cm_StatusFromAttr(&inStatus, NULL, attrp);
2806
2807     /* try the RPC now */
2808     osi_Log1(afsd_logp, "CALL MakeDir scp 0x%p", dscp);
2809     do {
2810         code = cm_ConnFromFID(&dscp->fid, userp, reqp, &connp);
2811         if (code) 
2812             continue;
2813
2814         dirAFSFid.Volume = dscp->fid.volume;
2815         dirAFSFid.Vnode = dscp->fid.vnode;
2816         dirAFSFid.Unique = dscp->fid.unique;
2817
2818         rxconnp = cm_GetRxConn(connp);
2819         code = RXAFS_MakeDir(connp->rxconnp, &dirAFSFid, fnamep,
2820                               &inStatus, &newAFSFid, &newDirStatus,
2821                               &updatedDirStatus, &newDirCallback,
2822                               &volSync);
2823         rx_PutConnection(rxconnp);
2824
2825     } while (cm_Analyze(connp, userp, reqp,
2826                         &dscp->fid, &volSync, NULL, &cbReq, code));
2827     code = cm_MapRPCError(code, reqp);
2828         
2829     if (code)
2830         osi_Log1(afsd_logp, "CALL MakeDir FAILURE, code 0x%x", code);
2831     else
2832         osi_Log0(afsd_logp, "CALL MakeDir SUCCESS");
2833
2834     if (dirop.scp) {
2835         lock_ObtainWrite(&dirop.scp->dirlock);
2836         dirop.lockType = CM_DIRLOCK_WRITE;
2837     }
2838     lock_ObtainWrite(&dscp->rw);
2839     cm_SyncOpDone(dscp, NULL, CM_SCACHESYNC_STOREDATA);
2840     if (code == 0) {
2841         cm_MergeStatus(NULL, dscp, &updatedDirStatus, &volSync, userp, CM_MERGEFLAG_DIROP);
2842     }
2843     lock_ReleaseWrite(&dscp->rw);
2844
2845     /* now try to create the new dir's entry, too, but be careful to 
2846      * make sure that we don't merge in old info.  Since we weren't locking
2847      * out any requests during the file's creation, we may have pretty old
2848      * info.
2849      */
2850     if (code == 0) {
2851         cm_SetFid(&newFid, dscp->fid.cell, dscp->fid.volume, newAFSFid.Vnode, newAFSFid.Unique);
2852         code = cm_GetSCache(&newFid, &scp, userp, reqp);
2853         if (code == 0) {
2854             lock_ObtainWrite(&scp->rw);
2855             if (!cm_HaveCallback(scp)) {
2856                 cm_MergeStatus(dscp, scp, &newDirStatus, &volSync,
2857                                 userp, 0);
2858                 cm_EndCallbackGrantingCall(scp, &cbReq,
2859                                             &newDirCallback, 0);
2860                 didEnd = 1;             
2861             }
2862             lock_ReleaseWrite(&scp->rw);
2863             cm_ReleaseSCache(scp);
2864         }
2865     }
2866
2867     /* make sure we end things properly */
2868     if (!didEnd)
2869         cm_EndCallbackGrantingCall(NULL, &cbReq, NULL, 0);
2870
2871     if (scp && cm_CheckDirOpForSingleChange(&dirop)) {
2872         cm_DirCreateEntry(&dirop, fnamep, &newFid);
2873 #ifdef USE_BPLUS
2874         cm_BPlusDirCreateEntry(&dirop, cnamep, &newFid);
2875 #endif
2876     }
2877     cm_EndDirOp(&dirop);
2878
2879     free(fnamep);
2880
2881     /* and return error code */
2882     return code;
2883 }       
2884
2885 long cm_Link(cm_scache_t *dscp, clientchar_t *cnamep, cm_scache_t *sscp, long flags,
2886              cm_user_t *userp, cm_req_t *reqp)
2887 {
2888     cm_conn_t *connp;
2889     long code = 0;
2890     AFSFid dirAFSFid;
2891     AFSFid existingAFSFid;
2892     AFSFetchStatus updatedDirStatus;
2893     AFSFetchStatus newLinkStatus;
2894     AFSVolSync volSync;
2895     struct rx_connection * rxconnp;
2896     cm_dirOp_t dirop;
2897     fschar_t * fnamep = NULL;
2898
2899     if (dscp->fid.cell != sscp->fid.cell ||
2900         dscp->fid.volume != sscp->fid.volume) {
2901         return CM_ERROR_CROSSDEVLINK;
2902     }
2903
2904     cm_BeginDirOp(dscp, userp, reqp, CM_DIRLOCK_NONE, &dirop);
2905     lock_ObtainWrite(&dscp->rw);
2906     code = cm_SyncOp(dscp, NULL, userp, reqp, 0, CM_SCACHESYNC_STOREDATA);
2907     lock_ReleaseWrite(&dscp->rw);
2908     if (code != 0)
2909         cm_EndDirOp(&dirop);
2910
2911     if (code)
2912         return code;
2913
2914     fnamep = cm_ClientStringToFsStringAlloc(cnamep, -1, NULL);
2915
2916     /* try the RPC now */
2917     osi_Log1(afsd_logp, "CALL Link scp 0x%p", dscp);
2918     do {
2919         code = cm_ConnFromFID(&dscp->fid, userp, reqp, &connp);
2920         if (code) continue;
2921
2922         dirAFSFid.Volume = dscp->fid.volume;
2923         dirAFSFid.Vnode = dscp->fid.vnode;
2924         dirAFSFid.Unique = dscp->fid.unique;
2925
2926         existingAFSFid.Volume = sscp->fid.volume;
2927         existingAFSFid.Vnode = sscp->fid.vnode;
2928         existingAFSFid.Unique = sscp->fid.unique;
2929
2930         rxconnp = cm_GetRxConn(connp);
2931         code = RXAFS_Link(rxconnp, &dirAFSFid, fnamep, &existingAFSFid,
2932             &newLinkStatus, &updatedDirStatus, &volSync);
2933         rx_PutConnection(rxconnp);
2934         osi_Log1(afsd_logp,"  RXAFS_Link returns 0x%x", code);
2935
2936     } while (cm_Analyze(connp, userp, reqp,
2937         &dscp->fid, &volSync, NULL, NULL, code));
2938
2939     code = cm_MapRPCError(code, reqp);
2940
2941     if (code)
2942         osi_Log1(afsd_logp, "CALL Link FAILURE, code 0x%x", code);
2943     else
2944         osi_Log0(afsd_logp, "CALL Link SUCCESS");
2945
2946     if (dirop.scp) {
2947         lock_ObtainWrite(&dirop.scp->dirlock);
2948         dirop.lockType = CM_DIRLOCK_WRITE;
2949     }
2950     lock_ObtainWrite(&dscp->rw);
2951     cm_SyncOpDone(dscp, NULL, CM_SCACHESYNC_STOREDATA);
2952     if (code == 0) {
2953         cm_MergeStatus(NULL, dscp, &updatedDirStatus, &volSync, userp, CM_MERGEFLAG_DIROP);
2954     }
2955     lock_ReleaseWrite(&dscp->rw);
2956
2957     if (code == 0) {
2958         if (cm_CheckDirOpForSingleChange(&dirop)) {
2959             cm_DirCreateEntry(&dirop, fnamep, &sscp->fid);
2960 #ifdef USE_BPLUS
2961             cm_BPlusDirCreateEntry(&dirop, cnamep, &sscp->fid);
2962 #endif
2963         }
2964     }
2965     cm_EndDirOp(&dirop);
2966
2967     free(fnamep);
2968
2969     return code;
2970 }
2971
2972 long cm_SymLink(cm_scache_t *dscp, clientchar_t *cnamep, fschar_t *contentsp, long flags,
2973                 cm_attr_t *attrp, cm_user_t *userp, cm_req_t *reqp)
2974 {
2975     cm_conn_t *connp;
2976     long code;
2977     AFSFid dirAFSFid;
2978     AFSFid newAFSFid;
2979     cm_fid_t newFid;
2980     cm_scache_t *scp;
2981     AFSStoreStatus inStatus;
2982     AFSFetchStatus updatedDirStatus;
2983     AFSFetchStatus newLinkStatus;
2984     AFSVolSync volSync;
2985     struct rx_connection * rxconnp;
2986     cm_dirOp_t dirop;
2987     fschar_t *fnamep = NULL;
2988
2989     /* before starting the RPC, mark that we're changing the directory data,
2990      * so that someone who does a chmod on the dir will wait until our
2991      * call completes.
2992      */
2993     cm_BeginDirOp(dscp, userp, reqp, CM_DIRLOCK_NONE, &dirop);
2994     lock_ObtainWrite(&dscp->rw);
2995     code = cm_SyncOp(dscp, NULL, userp, reqp, 0, CM_SCACHESYNC_STOREDATA);
2996     lock_ReleaseWrite(&dscp->rw);
2997     if (code != 0)
2998         cm_EndDirOp(&dirop);
2999     if (code) {
3000         return code;
3001     }
3002
3003     fnamep = cm_ClientStringToFsStringAlloc(cnamep, -1, NULL);
3004
3005     cm_StatusFromAttr(&inStatus, NULL, attrp);
3006
3007     /* try the RPC now */
3008     osi_Log1(afsd_logp, "CALL Symlink scp 0x%p", dscp);
3009     do {
3010         code = cm_ConnFromFID(&dscp->fid, userp, reqp, &connp);
3011         if (code) 
3012             continue;
3013
3014         dirAFSFid.Volume = dscp->fid.volume;
3015         dirAFSFid.Vnode = dscp->fid.vnode;
3016         dirAFSFid.Unique = dscp->fid.unique;
3017
3018         rxconnp = cm_GetRxConn(connp);
3019         code = RXAFS_Symlink(rxconnp, &dirAFSFid, fnamep, contentsp,
3020                               &inStatus, &newAFSFid, &newLinkStatus,
3021                               &updatedDirStatus, &volSync);
3022         rx_PutConnection(rxconnp);
3023
3024     } while (cm_Analyze(connp, userp, reqp,
3025                          &dscp->fid, &volSync, NULL, NULL, code));
3026     code = cm_MapRPCError(code, reqp);
3027         
3028     if (code)
3029         osi_Log1(afsd_logp, "CALL Symlink FAILURE, code 0x%x", code);
3030     else
3031         osi_Log0(afsd_logp, "CALL Symlink SUCCESS");
3032
3033     if (dirop.scp) {
3034         lock_ObtainWrite(&dirop.scp->dirlock);
3035         dirop.lockType = CM_DIRLOCK_WRITE;
3036     }
3037     lock_ObtainWrite(&dscp->rw);
3038     cm_SyncOpDone(dscp, NULL, CM_SCACHESYNC_STOREDATA);
3039     if (code == 0) {
3040         cm_MergeStatus(NULL, dscp, &updatedDirStatus, &volSync, userp, CM_MERGEFLAG_DIROP);
3041     }
3042     lock_ReleaseWrite(&dscp->rw);
3043
3044     if (code == 0) {
3045         if (cm_CheckDirOpForSingleChange(&dirop)) {
3046             cm_SetFid(&newFid, dscp->fid.cell, dscp->fid.volume, newAFSFid.Vnode, newAFSFid.Unique);
3047
3048             cm_DirCreateEntry(&dirop, fnamep, &newFid);
3049 #ifdef USE_BPLUS
3050             cm_BPlusDirCreateEntry(&dirop, cnamep, &newFid);
3051 #endif
3052         }
3053     }
3054     cm_EndDirOp(&dirop);
3055
3056     /* now try to create the new dir's entry, too, but be careful to 
3057      * make sure that we don't merge in old info.  Since we weren't locking
3058      * out any requests during the file's creation, we may have pretty old
3059      * info.
3060      */
3061     if (code == 0) {
3062         cm_SetFid(&newFid, dscp->fid.cell, dscp->fid.volume, newAFSFid.Vnode, newAFSFid.Unique);
3063         code = cm_GetSCache(&newFid, &scp, userp, reqp);
3064         if (code == 0) {
3065             lock_ObtainWrite(&scp->rw);
3066             if (!cm_HaveCallback(scp)) {
3067                 cm_MergeStatus(dscp, scp, &newLinkStatus, &volSync,
3068                                 userp, 0);
3069             }       
3070             lock_ReleaseWrite(&scp->rw);
3071             cm_ReleaseSCache(scp);
3072         }
3073     }
3074
3075     free(fnamep);
3076         
3077     /* and return error code */
3078     return code;
3079 }
3080
3081 /*! \brief Remove a directory
3082
3083   Encapsulates a call to RXAFS_RemoveDir().
3084
3085   \param[in] dscp cm_scache_t for the directory containing the
3086       directory to be removed.
3087
3088   \param[in] fnamep This will be the original name of the directory
3089       as known to the file server.   It will be passed in to RXAFS_RemoveDir().
3090       This parameter is optional.  If it is not provided the value
3091       will be looked up.
3092
3093   \param[in] cnamep Normalized name used to update the local
3094       directory caches.
3095
3096   \param[in] userp cm_user_t for the request.
3097
3098   \param[in] reqp Request tracker.
3099 */
3100 long cm_RemoveDir(cm_scache_t *dscp, fschar_t *fnamep, clientchar_t *cnamep, cm_user_t *userp, cm_req_t *reqp)
3101 {
3102     cm_conn_t *connp;
3103     long code;
3104     AFSFid dirAFSFid;
3105     int didEnd;
3106     AFSFetchStatus updatedDirStatus;
3107     AFSVolSync volSync;
3108     struct rx_connection * rxconnp;
3109     cm_dirOp_t dirop;
3110     cm_scache_t *scp = NULL;
3111     int free_fnamep = FALSE;
3112
3113     if (fnamep == NULL) {
3114         code = -1;
3115 #ifdef USE_BPLUS
3116         code = cm_BeginDirOp(dscp, userp, reqp, CM_DIRLOCK_READ, &dirop);
3117         if (code == 0) {
3118             code = cm_BPlusDirLookupOriginalName(&dirop, cnamep, &fnamep);
3119             if (code == 0)
3120                 free_fnamep = TRUE;
3121             cm_EndDirOp(&dirop);
3122         }
3123 #endif
3124         if (code)
3125             goto done;
3126     }
3127
3128     code = cm_Lookup(dscp, cnamep, CM_FLAG_NOMOUNTCHASE, userp, reqp, &scp);
3129     if (code)
3130         goto done;
3131
3132     /* before starting the RPC, mark that we're changing the directory data,
3133      * so that someone who does a chmod on the dir will wait until our
3134      * call completes.
3135      */
3136     cm_BeginDirOp(dscp, userp, reqp, CM_DIRLOCK_NONE, &dirop);
3137     lock_ObtainWrite(&dscp->rw);
3138     code = cm_SyncOp(dscp, NULL, userp, reqp, 0, CM_SCACHESYNC_STOREDATA);
3139     lock_ReleaseWrite(&dscp->rw);
3140     if (code) {
3141         cm_EndDirOp(&dirop);
3142         goto done;
3143     }
3144     didEnd = 0;
3145
3146     /* try the RPC now */
3147     osi_Log1(afsd_logp, "CALL RemoveDir scp 0x%p", dscp);
3148     do {
3149         code = cm_ConnFromFID(&dscp->fid, userp, reqp, &connp);
3150         if (code) 
3151             continue;
3152
3153         dirAFSFid.Volume = dscp->fid.volume;
3154         dirAFSFid.Vnode = dscp->fid.vnode;
3155         dirAFSFid.Unique = dscp->fid.unique;
3156
3157         rxconnp = cm_GetRxConn(connp);
3158         code = RXAFS_RemoveDir(rxconnp, &dirAFSFid, fnamep,
3159                                &updatedDirStatus, &volSync);
3160         rx_PutConnection(rxconnp);
3161
3162     } while (cm_Analyze(connp, userp, reqp,
3163                         &dscp->fid, &volSync, NULL, NULL, code));
3164     code = cm_MapRPCErrorRmdir(code, reqp);
3165
3166     if (code)
3167         osi_Log1(afsd_logp, "CALL RemoveDir FAILURE, code 0x%x", code);
3168     else
3169         osi_Log0(afsd_logp, "CALL RemoveDir SUCCESS");
3170
3171     if (dirop.scp) {
3172         lock_ObtainWrite(&dirop.scp->dirlock);
3173         dirop.lockType = CM_DIRLOCK_WRITE;
3174     }
3175     lock_ObtainWrite(&dscp->rw);
3176     cm_SyncOpDone(dscp, NULL, CM_SCACHESYNC_STOREDATA);
3177     if (code == 0) {
3178         cm_dnlcRemove(dscp, cnamep); 
3179         cm_MergeStatus(NULL, dscp, &updatedDirStatus, &volSync, userp, CM_MERGEFLAG_DIROP);
3180     }
3181     lock_ReleaseWrite(&dscp->rw);
3182
3183     if (code == 0) {
3184         if (cm_CheckDirOpForSingleChange(&dirop) && cnamep != NULL) {
3185             cm_DirDeleteEntry(&dirop, fnamep);
3186 #ifdef USE_BPLUS
3187             cm_BPlusDirDeleteEntry(&dirop, cnamep);
3188 #endif
3189         }
3190     }
3191     cm_EndDirOp(&dirop);
3192
3193     if (scp) {
3194         cm_ReleaseSCache(scp);
3195         if (code == 0) {
3196             lock_ObtainWrite(&scp->rw);
3197             scp->flags |= CM_SCACHEFLAG_DELETED;
3198             lock_ReleaseWrite(&scp->rw);
3199         }
3200     }
3201
3202   done:
3203     if (free_fnamep)
3204         free(fnamep);
3205
3206     /* and return error code */
3207     return code;
3208 }
3209
3210 long cm_Open(cm_scache_t *scp, int type, cm_user_t *userp)
3211 {
3212     /* grab mutex on contents */
3213     lock_ObtainWrite(&scp->rw);
3214
3215     /* reset the prefetch info */
3216     scp->prefetch.base.LowPart = 0;             /* base */
3217     scp->prefetch.base.HighPart = 0;
3218     scp->prefetch.end.LowPart = 0;              /* and end */
3219     scp->prefetch.end.HighPart = 0;
3220
3221     /* release mutex on contents */
3222     lock_ReleaseWrite(&scp->rw);
3223
3224     /* we're done */
3225     return 0;
3226 }       
3227
3228 /*! \brief Rename a file or directory
3229
3230   Encapsulates a RXAFS_Rename() call.
3231
3232   \param[in] oldDscp cm_scache_t for the directory containing the old
3233       name.
3234
3235   \param[in] oldNamep The original old name known to the file server.
3236       This is the name that will be passed into the RXAFS_Rename().
3237       If it is not provided, it will be looked up.
3238
3239   \param[in] normalizedOldNamep Normalized old name.  This is used for
3240   updating local directory caches.
3241
3242   \param[in] newDscp cm_scache_t for the directory containing the new
3243   name.
3244
3245   \param[in] newNamep New name. Normalized.
3246
3247   \param[in] userp cm_user_t for the request.
3248
3249   \param[in,out] reqp Request tracker.
3250
3251 */
3252 long cm_Rename(cm_scache_t *oldDscp, fschar_t *oldNamep, clientchar_t *cOldNamep,
3253                cm_scache_t *newDscp, clientchar_t *cNewNamep, cm_user_t *userp,
3254                cm_req_t *reqp)
3255 {
3256     cm_conn_t *connp;
3257     long code;
3258     AFSFid oldDirAFSFid;
3259     AFSFid newDirAFSFid;
3260     int didEnd;
3261     AFSFetchStatus updatedOldDirStatus;
3262     AFSFetchStatus updatedNewDirStatus;
3263     AFSVolSync volSync;
3264     int oneDir;
3265     struct rx_connection * rxconnp;
3266     cm_dirOp_t oldDirOp;
3267     cm_fid_t   fileFid;
3268     int        diropCode = -1;
3269     cm_dirOp_t newDirOp;
3270     fschar_t * newNamep = NULL;
3271     int free_oldNamep = FALSE;
3272
3273     if (oldNamep == NULL) {
3274         code = -1;
3275 #ifdef USE_BPLUS
3276         code = cm_BeginDirOp(oldDscp, userp, reqp, CM_DIRLOCK_READ, &oldDirOp);
3277         if (code == 0) {
3278             code = cm_BPlusDirLookupOriginalName(&oldDirOp, cOldNamep, &oldNamep);
3279             if (code == 0)
3280                 free_oldNamep = TRUE;
3281             cm_EndDirOp(&oldDirOp);
3282         }
3283 #endif
3284         if (code)
3285             goto done;
3286     }
3287
3288
3289     /* before starting the RPC, mark that we're changing the directory data,
3290      * so that someone who does a chmod on the dir will wait until our call
3291      * completes.  We do this in vnode order so that we don't deadlock,
3292      * which makes the code a little verbose.
3293      */
3294     if (oldDscp == newDscp) {
3295         /* check for identical names */
3296         if (cm_ClientStrCmp(cOldNamep, cNewNamep) == 0) {
3297             code = CM_ERROR_RENAME_IDENTICAL;
3298             goto done;
3299         }
3300
3301         oneDir = 1;
3302         cm_BeginDirOp(oldDscp, userp, reqp, CM_DIRLOCK_NONE, &oldDirOp);
3303         lock_ObtainWrite(&oldDscp->rw);
3304         cm_dnlcRemove(oldDscp, cOldNamep);
3305         cm_dnlcRemove(oldDscp, cNewNamep);
3306         code = cm_SyncOp(oldDscp, NULL, userp, reqp, 0,
3307                           CM_SCACHESYNC_STOREDATA);
3308         lock_ReleaseWrite(&oldDscp->rw);
3309         if (code != 0) {
3310             cm_EndDirOp(&oldDirOp);
3311         }
3312     }
3313     else {
3314         /* two distinct dir vnodes */
3315         oneDir = 0;
3316         if (oldDscp->fid.cell != newDscp->fid.cell ||
3317              oldDscp->fid.volume != newDscp->fid.volume) {
3318             code = CM_ERROR_CROSSDEVLINK;
3319             goto done;
3320         }
3321
3322         /* shouldn't happen that we have distinct vnodes for two
3323          * different files, but could due to deliberate attack, or
3324          * stale info.  Avoid deadlocks and quit now.
3325          */
3326         if (oldDscp->fid.vnode == newDscp->fid.vnode) {
3327             code = CM_ERROR_CROSSDEVLINK;
3328             goto done;
3329         }
3330
3331         if (oldDscp->fid.vnode < newDscp->fid.vnode) {
3332             cm_BeginDirOp(oldDscp, userp, reqp, CM_DIRLOCK_NONE, &oldDirOp);
3333             lock_ObtainWrite(&oldDscp->rw);
3334             cm_dnlcRemove(oldDscp, cOldNamep);
3335             code = cm_SyncOp(oldDscp, NULL, userp, reqp, 0,
3336                              CM_SCACHESYNC_STOREDATA);
3337             lock_ReleaseWrite(&oldDscp->rw);
3338             if (code != 0)
3339                 cm_EndDirOp(&oldDirOp);
3340             if (code == 0) {
3341                 cm_BeginDirOp(newDscp, userp, reqp, CM_DIRLOCK_NONE, &newDirOp);
3342                 lock_ObtainWrite(&newDscp->rw);
3343                 cm_dnlcRemove(newDscp, cNewNamep);
3344                 code = cm_SyncOp(newDscp, NULL, userp, reqp, 0,
3345                                  CM_SCACHESYNC_STOREDATA);
3346                 lock_ReleaseWrite(&newDscp->rw);
3347                 if (code) {
3348                     cm_EndDirOp(&newDirOp);
3349
3350                     /* cleanup first one */
3351                     lock_ObtainWrite(&oldDscp->rw);
3352                     cm_SyncOpDone(oldDscp, NULL,
3353                                    CM_SCACHESYNC_STOREDATA);
3354                     lock_ReleaseWrite(&oldDscp->rw);
3355                     cm_EndDirOp(&oldDirOp);
3356                 }       
3357             }
3358         }
3359         else {
3360             /* lock the new vnode entry first */
3361             cm_BeginDirOp(newDscp, userp, reqp, CM_DIRLOCK_NONE, &newDirOp);
3362             lock_ObtainWrite(&newDscp->rw);
3363             cm_dnlcRemove(newDscp, cNewNamep);
3364             code = cm_SyncOp(newDscp, NULL, userp, reqp, 0,
3365                               CM_SCACHESYNC_STOREDATA);
3366             lock_ReleaseWrite(&newDscp->rw);
3367             if (code != 0)
3368                 cm_EndDirOp(&newDirOp);
3369             if (code == 0) {
3370                 cm_BeginDirOp(oldDscp, userp, reqp, CM_DIRLOCK_NONE, &oldDirOp);
3371                 lock_ObtainWrite(&oldDscp->rw);
3372                 cm_dnlcRemove(oldDscp, cOldNamep);
3373                 code = cm_SyncOp(oldDscp, NULL, userp, reqp, 0,
3374                                   CM_SCACHESYNC_STOREDATA);
3375                 lock_ReleaseWrite(&oldDscp->rw);
3376                 if (code != 0)
3377                     cm_EndDirOp(&oldDirOp);
3378                 if (code) {
3379                     /* cleanup first one */
3380                     lock_ObtainWrite(&newDscp->rw);
3381                     cm_SyncOpDone(newDscp, NULL,
3382                                    CM_SCACHESYNC_STOREDATA);
3383                     lock_ReleaseWrite(&newDscp->rw);
3384                     cm_EndDirOp(&newDirOp);
3385                 }       
3386             }
3387         }
3388     }   /* two distinct vnodes */
3389
3390     if (code) 
3391         goto done;
3392
3393     didEnd = 0;
3394
3395     newNamep = cm_ClientStringToFsStringAlloc(cNewNamep, -1, NULL);
3396
3397     /* try the RPC now */
3398     osi_Log2(afsd_logp, "CALL Rename old scp 0x%p new scp 0x%p", 
3399               oldDscp, newDscp);
3400     do {
3401         code = cm_ConnFromFID(&oldDscp->fid, userp, reqp, &connp);
3402         if (code) 
3403             continue;
3404
3405         oldDirAFSFid.Volume = oldDscp->fid.volume;
3406         oldDirAFSFid.Vnode = oldDscp->fid.vnode;
3407         oldDirAFSFid.Unique = oldDscp->fid.unique;
3408         newDirAFSFid.Volume = newDscp->fid.volume;
3409         newDirAFSFid.Vnode = newDscp->fid.vnode;
3410         newDirAFSFid.Unique = newDscp->fid.unique;
3411
3412         rxconnp = cm_GetRxConn(connp);
3413         code = RXAFS_Rename(rxconnp, &oldDirAFSFid, oldNamep,
3414                             &newDirAFSFid, newNamep,
3415                             &updatedOldDirStatus, &updatedNewDirStatus,
3416                             &volSync);
3417         rx_PutConnection(rxconnp);
3418
3419     } while (cm_Analyze(connp, userp, reqp, &oldDscp->fid,
3420                          &volSync, NULL, NULL, code));
3421     code = cm_MapRPCError(code, reqp);
3422         
3423     if (code)
3424         osi_Log1(afsd_logp, "CALL Rename FAILURE, code 0x%x", code);
3425     else
3426         osi_Log0(afsd_logp, "CALL Rename SUCCESS");
3427
3428     /* update the individual stat cache entries for the directories */
3429     if (oldDirOp.scp) {
3430         lock_ObtainWrite(&oldDirOp.scp->dirlock);
3431         oldDirOp.lockType = CM_DIRLOCK_WRITE;
3432     }
3433     lock_ObtainWrite(&oldDscp->rw);
3434     cm_SyncOpDone(oldDscp, NULL, CM_SCACHESYNC_STOREDATA);
3435
3436     if (code == 0)
3437         cm_MergeStatus(NULL, oldDscp, &updatedOldDirStatus, &volSync,
3438                        userp, CM_MERGEFLAG_DIROP);
3439     lock_ReleaseWrite(&oldDscp->rw);
3440
3441     if (code == 0) {
3442         if (cm_CheckDirOpForSingleChange(&oldDirOp)) {
3443
3444 #ifdef USE_BPLUS
3445             diropCode = cm_BPlusDirLookup(&oldDirOp, cOldNamep, &fileFid);
3446             if (diropCode == CM_ERROR_INEXACT_MATCH)
3447                 diropCode = 0;
3448             else if (diropCode == EINVAL)
3449 #endif
3450                 diropCode = cm_DirLookup(&oldDirOp, oldNamep, &fileFid);
3451
3452             if (diropCode == 0) {
3453                 if (oneDir) {
3454                     diropCode = cm_DirCreateEntry(&oldDirOp, newNamep, &fileFid);
3455 #ifdef USE_BPLUS
3456                     cm_BPlusDirCreateEntry(&oldDirOp, cNewNamep, &fileFid);
3457 #endif
3458                 }
3459                 
3460                 if (diropCode == 0) { 
3461                     diropCode = cm_DirDeleteEntry(&oldDirOp, oldNamep);
3462 #ifdef USE_BPLUS
3463                     cm_BPlusDirDeleteEntry(&oldDirOp, cOldNamep);
3464 #endif
3465                 }
3466             }
3467         }
3468     }
3469     cm_EndDirOp(&oldDirOp);
3470
3471     /* and update it for the new one, too, if necessary */
3472     if (!oneDir) {
3473         if (newDirOp.scp) {
3474             lock_ObtainWrite(&newDirOp.scp->dirlock);
3475             newDirOp.lockType = CM_DIRLOCK_WRITE;
3476         }
3477         lock_ObtainWrite(&newDscp->rw);
3478         cm_SyncOpDone(newDscp, NULL, CM_SCACHESYNC_STOREDATA);
3479         if (code == 0)
3480             cm_MergeStatus(NULL, newDscp, &updatedNewDirStatus, &volSync,
3481                             userp, CM_MERGEFLAG_DIROP);
3482         lock_ReleaseWrite(&newDscp->rw);
3483
3484         if (code == 0) {
3485             /* we only make the local change if we successfully made
3486                the change in the old directory AND there was only one
3487                change in the new directory */
3488             if (diropCode == 0 && cm_CheckDirOpForSingleChange(&newDirOp)) {
3489                 cm_DirCreateEntry(&newDirOp, newNamep, &fileFid);
3490 #ifdef USE_BPLUS
3491                 cm_BPlusDirCreateEntry(&newDirOp, cNewNamep, &fileFid);
3492 #endif
3493             }
3494         }
3495         cm_EndDirOp(&newDirOp);
3496     }
3497
3498   done:
3499     if (free_oldNamep)
3500         free(oldNamep);
3501
3502     free(newNamep);
3503
3504     /* and return error code */
3505     return code;
3506 }
3507
3508 /* Byte range locks:
3509
3510    The OpenAFS Windows client has to fake byte range locks given no
3511    server side support for such locks.  This is implemented as keyed
3512    byte range locks on the cache manager.
3513
3514    Keyed byte range locks:
3515
3516    Each cm_scache_t structure keeps track of a list of keyed locks.
3517    The key for a lock identifies an owner of a set of locks (referred
3518    to as a client).  Each key is represented by a value.  The set of
3519    key values used within a specific cm_scache_t structure form a
3520    namespace that has a scope of just that cm_scache_t structure.  The
3521    same key value can be used with another cm_scache_t structure and
3522    correspond to a completely different client.  However it is
3523    advantageous for the SMB or IFS layer to make sure that there is a
3524    1-1 mapping between client and keys over all cm_scache_t objects.
3525
3526    Assume a client C has key Key(C) (although, since the scope of the
3527    key is a cm_scache_t, the key can be Key(C,S), where S is the
3528    cm_scache_t.  But assume a 1-1 relation between keys and clients).
3529    A byte range (O,+L) denotes byte addresses (O) through (O+L-1)
3530    inclusive (a.k.a. [O,O+L-1]).  The function Key(x) is implemented
3531    through cm_generateKey() function for both SMB and IFS.
3532
3533    The list of locks for a cm_scache_t object S is maintained in
3534    S->fileLocks.  The cache manager will set a lock on the AFS file
3535    server in order to assert the locks in S->fileLocks.  If only
3536    shared locks are in place for S, then the cache manager will obtain
3537    a LockRead lock, while if there are any exclusive locks, it will
3538    obtain a LockWrite lock.  If the exclusive locks are all released
3539    while the shared locks remain, then the cache manager will
3540    downgrade the lock from LockWrite to LockRead.  Similarly, if an
3541    exclusive lock is obtained when only shared locks exist, then the
3542    cache manager will try to upgrade the lock from LockRead to
3543    LockWrite.
3544
3545    Each lock L owned by client C maintains a key L->key such that
3546    L->key == Key(C), the effective range defined by L->LOffset and
3547    L->LLength such that the range of bytes affected by the lock is
3548    (L->LOffset, +L->LLength), a type maintained in L->LockType which
3549    is either exclusive or shared.
3550
3551    Lock states:
3552
3553    A lock exists iff it is in S->fileLocks for some cm_scache_t
3554    S. Existing locks are in one of the following states: ACTIVE,
3555    WAITLOCK, WAITUNLOCK, LOST, DELETED.
3556
3557    The following sections describe each lock and the associated
3558    transitions.
3559
3560    1. ACTIVE: A lock L is ACTIVE iff the cache manager has asserted
3561       the lock with the AFS file server.  This type of lock can be
3562       exercised by a client to read or write to the locked region (as
3563       the lock allows).
3564
3565       1.1 ACTIVE->LOST: When the AFS file server fails to extend a
3566         server lock that was required to assert the lock.  Before
3567         marking the lock as lost, the cache manager checks if the file
3568         has changed on the server.  If the file has not changed, then
3569         the cache manager will attempt to obtain a new server lock
3570         that is sufficient to assert the client side locks for the
3571         file.  If any of these fail, the lock is marked as LOST.
3572         Otherwise, it is left as ACTIVE.
3573
3574       1.2 ACTIVE->DELETED: Lock is released.
3575
3576    2. WAITLOCK: A lock is in a WAITLOCK state if the cache manager
3577       grants the lock but the lock is yet to be asserted with the AFS
3578       file server.  Once the file server grants the lock, the state
3579       will transition to an ACTIVE lock.
3580
3581       2.1 WAITLOCK->ACTIVE: The server granted the lock.
3582
3583       2.2 WAITLOCK->DELETED: Lock is abandoned, or timed out during
3584         waiting.
3585
3586       2.3 WAITLOCK->LOST: One or more locks from this client were
3587         marked as LOST.  No further locks will be granted to this
3588         client until all lost locks are removed.
3589
3590    3. WAITUNLOCK: A lock is in a WAITUNLOCK state if the cache manager
3591       receives a request for a lock that conflicts with an existing
3592       ACTIVE or WAITLOCK lock.  The lock will be placed in the queue
3593       and will be granted at such time the conflicting locks are
3594       removed, at which point the state will transition to either
3595       WAITLOCK or ACTIVE.
3596
3597       3.1 WAITUNLOCK->ACTIVE: The conflicting lock was removed.  The
3598         current serverLock is sufficient to assert this lock, or a
3599         sufficient serverLock is obtained.
3600
3601       3.2 WAITUNLOCK->WAITLOCK: The conflicting lock was removed,
3602         however the required serverLock is yet to be asserted with the
3603         server.
3604
3605       3.3 WAITUNLOCK->DELETED: The lock is abandoned, timed out or
3606         released.
3607
3608       3.5 WAITUNLOCK->LOST: One or more locks from this client were
3609         marked as LOST.  No further locks will be granted to this
3610         client until all lost locks are removed.
3611
3612    4. LOST: A lock L is LOST if the server lock that was required to
3613       assert the lock could not be obtained or if it could not be
3614       extended, or if other locks by the same client were LOST.
3615       Essentially, once a lock is LOST, the contract between the cache
3616       manager and that specific client is no longer valid.
3617
3618       The cache manager rechecks the server lock once every minute and
3619       extends it as appropriate.  If this is not done for 5 minutes,
3620       the AFS file server will release the lock (the 5 minute timeout
3621       is based on current file server code and is fairly arbitrary).
3622       Once released, the lock cannot be re-obtained without verifying
3623       that the contents of the file hasn't been modified since the
3624       time the lock was released.  Re-obtaining the lock without
3625       verifying this may lead to data corruption.  If the lock can not
3626       be obtained safely, then all active locks for the cm_scache_t
3627       are marked as LOST.
3628
3629       4.1 LOST->DELETED: The lock is released.
3630
3631    5. DELETED: The lock is no longer relevant.  Eventually, it will
3632       get removed from the cm_scache_t. In the meantime, it will be
3633       treated as if it does not exist.
3634
3635       5.1 DELETED->not exist: The lock is removed from the
3636         cm_scache_t.
3637
3638    The following are classifications of locks based on their state.
3639
3640    6* A lock L is ACCEPTED if it is ACTIVE or WAITLOCK.  These locks
3641       have been accepted by the cache manager, but may or may not have
3642       been granted back to the client.
3643
3644    7* A lock L is QUEUED if it is ACTIVE, WAITLOCK or WAITUNLOCK.
3645
3646    8* A lock L is WAITING if it is WAITLOCK or WAITUNLOCK.
3647
3648    Lock operation:
3649
3650    A client C can READ range (Offset,+Length) of a file represented by
3651    cm_scache_t S iff (1):
3652
3653    1. for all _a_ in (Offset,+Length), all of the following is true:
3654
3655        1.1 For each ACTIVE lock L in S->fileLocks such that _a_ in
3656          (L->LOffset,+L->LLength); L->key == Key(C) OR L->LockType is
3657          shared.
3658
3659        1.2 For each LOST lock L in S->fileLocks such that _a_ in
3660          (L->LOffset,+L->LLength); L->LockType is shared AND L->key !=
3661          Key(C)
3662
3663        (When locks are lost on an cm_scache_t, all locks are lost.  By
3664        4.2 (below), if there is an exclusive LOST lock, then there
3665        can't be any overlapping ACTIVE locks.)
3666
3667    A client C can WRITE range (Offset,+Length) of cm_scache_t S iff (2):
3668
3669    2. for all _a_ in (Offset,+Length), one of the following is true:
3670
3671        2.1 Byte _a_ of S is unowned (as specified in 1.1) AND there
3672          does not exist a LOST lock L such that _a_ in
3673          (L->LOffset,+L->LLength).
3674
3675        2.2 Byte _a_ of S is owned by C under lock L (as specified in
3676          1.2) AND L->LockType is exclusive.
3677
3678    A client C can OBTAIN a lock L on cm_scache_t S iff (both 3 and 4):
3679
3680    3. for all _a_ in (L->LOffset,+L->LLength), ALL of the following is
3681       true:
3682
3683        3.1 If L->LockType is exclusive then there does NOT exist a
3684          ACCEPTED lock M in S->fileLocks such that _a_ in
3685          (M->LOffset,+M->LLength).
3686
3687          (If we count all QUEUED locks then we hit cases such as
3688          cascading waiting locks where the locks later on in the queue
3689          can be granted without compromising file integrity.  On the
3690          other hand if only ACCEPTED locks are considered, then locks
3691          that were received earlier may end up waiting for locks that
3692          were received later to be unlocked. The choice of ACCEPTED
3693          locks was made to mimic the Windows byte range lock
3694          semantics.)
3695
3696        3.2 If L->LockType is shared then for each ACCEPTED lock M in
3697          S->fileLocks, if _a_ in (M->LOffset,+M->LLength) then
3698          M->LockType is shared.
3699
3700    4. For all LOST locks M in S->fileLocks, ALL of the following are true:
3701
3702        4.1 M->key != Key(C)
3703
3704        4.2 If M->LockType is exclusive, then (L->LOffset,+L->LLength)
3705          and (M->LOffset,+M->LLength) do not intersect.
3706
3707          (Note: If a client loses a lock, it loses all locks.
3708          Subsequently, it will not be allowed to obtain any more locks
3709          until all existing LOST locks that belong to the client are
3710          released.  Once all locks are released by a single client,
3711          there exists no further contract between the client and AFS
3712          about the contents of the file, hence the client can then
3713          proceed to obtain new locks and establish a new contract.
3714
3715          This doesn't quite work as you think it should, because most
3716          applications aren't built to deal with losing locks they
3717          thought they once had.  For now, we don't have a good
3718          solution to lost locks.
3719
3720          Also, for consistency reasons, we have to hold off on
3721          granting locks that overlap exclusive LOST locks.)
3722
3723    A client C can only unlock locks L in S->fileLocks which have
3724    L->key == Key(C).
3725
3726    The representation and invariants are as follows:
3727
3728    - Each cm_scache_t structure keeps:
3729
3730        - A queue of byte-range locks (cm_scache_t::fileLocks) which
3731          are of type cm_file_lock_t.
3732
3733        - A record of the highest server-side lock that has been
3734          obtained for this object (cm_scache_t::serverLock), which is
3735          one of (-1), LockRead, LockWrite.
3736
3737        - A count of ACCEPTED exclusive and shared locks that are in the
3738          queue (cm_scache_t::sharedLocks and
3739          cm_scache_t::exclusiveLocks)
3740
3741    - Each cm_file_lock_t structure keeps:
3742
3743        - The type of lock (cm_file_lock_t::LockType)
3744
3745        - The key associated with the lock (cm_file_lock_t::key)
3746
3747        - The offset and length of the lock (cm_file_lock_t::LOffset
3748          and cm_file_lock_t::LLength)
3749
3750        - The state of the lock.
3751
3752        - Time of issuance or last successful extension
3753
3754    Semantic invariants:
3755
3756        I1. The number of ACCEPTED locks in S->fileLocks are
3757            (S->sharedLocks + S->exclusiveLocks)
3758
3759    External invariants:
3760
3761        I3. S->serverLock is the lock that we have asserted with the
3762            AFS file server for this cm_scache_t.
3763
3764        I4. S->serverLock == LockRead iff there is at least one ACTIVE
3765            shared lock, but no ACTIVE exclusive locks.
3766
3767        I5. S->serverLock == LockWrite iff there is at least one ACTIVE
3768            exclusive lock.
3769
3770        I6. If L is a LOST lock, then for each lock M in S->fileLocks,
3771            M->key == L->key IMPLIES M is LOST or DELETED.
3772
3773    --asanka
3774  */
3775
3776 #define IS_LOCK_ACTIVE(lockp)     (((lockp)->flags & (CM_FILELOCK_FLAG_DELETED|CM_FILELOCK_FLAG_WAITLOCK|CM_FILELOCK_FLAG_WAITUNLOCK|CM_FILELOCK_FLAG_LOST)) == 0)
3777
3778 #define IS_LOCK_WAITLOCK(lockp)   (((lockp)->flags & (CM_FILELOCK_FLAG_DELETED|CM_FILELOCK_FLAG_WAITLOCK|CM_FILELOCK_FLAG_WAITUNLOCK|CM_FILELOCK_FLAG_LOST)) == CM_FILELOCK_FLAG_WAITLOCK)
3779
3780 #define IS_LOCK_WAITUNLOCK(lockp) (((lockp)->flags & (CM_FILELOCK_FLAG_DELETED|CM_FILELOCK_FLAG_WAITLOCK|CM_FILELOCK_FLAG_WAITUNLOCK|CM_FILELOCK_FLAG_LOST)) == CM_FILELOCK_FLAG_WAITUNLOCK)
3781
3782 #define IS_LOCK_LOST(lockp)       (((lockp)->flags & (CM_FILELOCK_FLAG_DELETED|CM_FILELOCK_FLAG_LOST)) == CM_FILELOCK_FLAG_LOST)
3783
3784 #define IS_LOCK_DELETED(lockp)    (((lockp)->flags & CM_FILELOCK_FLAG_DELETED) == CM_FILELOCK_FLAG_DELETED)
3785
3786 /* unsafe */
3787 #define IS_LOCK_ACCEPTED(lockp)   (IS_LOCK_ACTIVE(lockp) || IS_LOCK_WAITLOCK(lockp))
3788
3789 /* unsafe */
3790 #define IS_LOCK_CLIENTONLY(lockp) ((((lockp)->scp->flags & CM_SCACHEFLAG_RO) == CM_SCACHEFLAG_RO) || (((lockp)->flags & CM_FILELOCK_FLAG_CLIENTONLY) == CM_FILELOCK_FLAG_CLIENTONLY))
3791
3792 /* unsafe */
3793 #define INTERSECT_RANGE(r1,r2) (((r2).offset+(r2).length) > (r1).offset && ((r1).offset +(r1).length) > (r2).offset)
3794
3795 /* unsafe */
3796 #define CONTAINS_RANGE(r1,r2) (((r2).offset+(r2).length) <= ((r1).offset+(r1).length) && (r1).offset <= (r2).offset)
3797
3798 #if defined(VICED_CAPABILITY_USE_BYTE_RANGE_LOCKS) && !defined(LOCK_TESTING)
3799 #define SCP_SUPPORTS_BRLOCKS(scp) ((scp)->cbServerp && ((scp)->cbServerp->capabilities & VICED_CAPABILITY_USE_BYTE_RANGE_LOCKS))
3800 #else
3801 #define SCP_SUPPORTS_BRLOCKS(scp) (1)
3802 #endif
3803
3804 #define SERVERLOCKS_ENABLED(scp) (!((scp)->flags & CM_SCACHEFLAG_RO) && cm_enableServerLocks && SCP_SUPPORTS_BRLOCKS(scp))
3805
3806 #if defined(VICED_CAPABILITY_WRITELOCKACL)
3807 #define SCP_SUPPORTS_WRITELOCKACL(scp) ((scp)->cbServerp && ((scp->cbServerp->capabilities & VICED_CAPABILITY_WRITELOCKACL)))
3808 #else
3809 #define SCP_SUPPORTS_WRITELOCKACL(scp) (0)
3810
3811 /* This should really be defined in any build that this code is being
3812    compiled. */
3813 #error  VICED_CAPABILITY_WRITELOCKACL not defined.
3814 #endif
3815
3816 static void cm_LockRangeSubtract(cm_range_t * pos, const cm_range_t * neg)
3817 {
3818     afs_int64 int_begin;
3819     afs_int64 int_end;
3820
3821     int_begin = MAX(pos->offset, neg->offset);
3822     int_end = MIN(pos->offset+pos->length, neg->offset+neg->length);
3823
3824     if (int_begin < int_end) {
3825         if (int_begin == pos->offset) {
3826             pos->length = pos->offset + pos->length - int_end;
3827             pos->offset = int_end;
3828         } else if (int_end == pos->offset + pos->length) {
3829             pos->length = int_begin - pos->offset;
3830         }
3831
3832         /* We only subtract ranges if the resulting range is
3833            contiguous.  If we try to support non-contigous ranges, we
3834            aren't actually improving performance. */
3835     }
3836 }
3837
3838 /* Called with scp->rw held.  Returns 0 if all is clear to read the
3839    specified range by the client identified by key.
3840  */
3841 long cm_LockCheckRead(cm_scache_t *scp, 
3842                       LARGE_INTEGER LOffset, 
3843                       LARGE_INTEGER LLength, 
3844                       cm_key_t key)
3845 {
3846 #ifndef ADVISORY_LOCKS
3847
3848     cm_file_lock_t *fileLock;
3849     osi_queue_t *q;
3850     long code = 0;
3851     cm_range_t range;
3852     int substract_ranges = FALSE;
3853
3854     range.offset = LOffset.QuadPart;
3855     range.length = LLength.QuadPart;
3856
3857     /*
3858
3859      1. for all _a_ in (Offset,+Length), all of the following is true:
3860
3861        1.1 For each ACTIVE lock L in S->fileLocks such that _a_ in
3862          (L->LOffset,+L->LLength); L->key == Key(C) OR L->LockType is
3863          shared.
3864
3865        1.2 For each LOST lock L in S->fileLocks such that _a_ in
3866          (L->LOffset,+L->LLength); L->LockType is shared AND L->key !=
3867          Key(C)
3868
3869     */
3870
3871     lock_ObtainRead(&cm_scacheLock);
3872
3873     for (q = scp->fileLocksH; q && range.length > 0; q = osi_QNext(q)) {
3874         fileLock = 
3875             (cm_file_lock_t *)((char *) q - offsetof(cm_file_lock_t, fileq));
3876
3877         if (INTERSECT_RANGE(range, fileLock->range)) {
3878             if (IS_LOCK_ACTIVE(fileLock)) {
3879                 if (fileLock->key == key) {
3880
3881                     /* If there is an active lock for this client, it
3882                        is safe to substract ranges.*/
3883                     cm_LockRangeSubtract(&range, &fileLock->range);
3884                     substract_ranges = TRUE;
3885                 } else {
3886                     if (fileLock->lockType != LockRead) {
3887                         code = CM_ERROR_LOCK_CONFLICT;
3888                         break;
3889                     }
3890
3891                     /* even if the entire range is locked for reading,
3892                        we still can't grant the lock at this point
3893                        because the client may have lost locks. That
3894                        is, unless we have already seen an active lock
3895                        belonging to the client, in which case there
3896                        can't be any lost locks for this client. */
3897                     if (substract_ranges)
3898                         cm_LockRangeSubtract(&range, &fileLock->range);
3899                 }
3900             } else if (IS_LOCK_LOST(fileLock) &&
3901                       (fileLock->key == key || fileLock->lockType == LockWrite)) {
3902                 code = CM_ERROR_BADFD;
3903                 break;
3904             }
3905         }
3906     }
3907
3908     lock_ReleaseRead(&cm_scacheLock);
3909
3910     osi_Log4(afsd_logp, "cm_LockCheckRead scp 0x%x offset %d length %d code 0x%x",
3911               scp, (unsigned long)LOffset.QuadPart, (unsigned long)LLength.QuadPart, code);
3912
3913     return code;
3914
3915 #else
3916
3917     return 0;
3918
3919 #endif
3920 }
3921
3922 /* Called with scp->rw held.  Returns 0 if all is clear to write the
3923    specified range by the client identified by key.
3924  */
3925 long cm_LockCheckWrite(cm_scache_t *scp,
3926                        LARGE_INTEGER LOffset,
3927                        LARGE_INTEGER LLength,
3928                        cm_key_t key)
3929 {
3930 #ifndef ADVISORY_LOCKS
3931
3932     cm_file_lock_t *fileLock;
3933     osi_queue_t *q;
3934     long code = 0;
3935     cm_range_t range;
3936
3937     range.offset = LOffset.QuadPart;
3938     range.length = LLength.QuadPart;
3939
3940     /*
3941    A client C can WRITE range (Offset,+Length) of cm_scache_t S iff (2):
3942
3943    2. for all _a_ in (Offset,+Length), one of the following is true:
3944
3945        2.1 Byte _a_ of S is unowned AND there does not exist a LOST
3946          lock L such that _a_ in (L->LOffset,+L->LLength).
3947
3948        2.2 Byte _a_ of S is owned by C under lock L AND L->LockType is
3949          exclusive.
3950     */
3951
3952     lock_ObtainRead(&cm_scacheLock);
3953
3954     for (q = scp->fileLocksH; q && range.length > 0; q = osi_QNext(q)) {
3955         fileLock = 
3956             (cm_file_lock_t *)((char *) q - offsetof(cm_file_lock_t, fileq));
3957
3958         if (INTERSECT_RANGE(range, fileLock->range)) {
3959             if (IS_LOCK_ACTIVE(fileLock)) {
3960                 if (fileLock->key == key) {
3961                     if (fileLock->lockType == LockWrite) {
3962
3963                         /* if there is an active lock for this client, it
3964                            is safe to substract ranges */
3965                         cm_LockRangeSubtract(&range, &fileLock->range);
3966                     } else {
3967                         code = CM_ERROR_LOCK_CONFLICT;
3968                         break;
3969                     }
3970                 } else {
3971                     code = CM_ERROR_LOCK_CONFLICT;
3972                     break;
3973                 }
3974             } else if (IS_LOCK_LOST(fileLock)) {
3975                 code = CM_ERROR_BADFD;
3976                 break;
3977             }
3978         }
3979     }
3980
3981     lock_ReleaseRead(&cm_scacheLock);
3982
3983     osi_Log4(afsd_logp, "cm_LockCheckWrite scp 0x%x offset %d length %d code 0x%x",
3984               scp, (unsigned long)LOffset.QuadPart, (unsigned long)LLength.QuadPart, code);
3985
3986     return code;
3987
3988 #else
3989
3990     return 0;
3991
3992 #endif
3993 }
3994
3995 /* Called with cm_scacheLock write locked */
3996 static cm_file_lock_t * cm_GetFileLock(void) {
3997     cm_file_lock_t * l;
3998
3999     l = (cm_file_lock_t *) cm_freeFileLocks;
4000     if (l) {
4001         osi_QRemove(&cm_freeFileLocks, &l->q);
4002     } else {
4003         l = malloc(sizeof(cm_file_lock_t));
4004         osi_assertx(l, "null cm_file_lock_t");
4005     }
4006
4007     memset(l, 0, sizeof(cm_file_lock_t));
4008
4009     return l;
4010 }
4011
4012 /* Called with cm_scacheLock write locked */
4013 static void cm_PutFileLock(cm_file_lock_t *l) {
4014     osi_QAdd(&cm_freeFileLocks, &l->q);
4015 }
4016
4017 /* called with scp->rw held.  May release it during processing, but
4018    leaves it held on exit. */
4019 long cm_IntSetLock(cm_scache_t * scp, cm_user_t * userp, int lockType,
4020                    cm_req_t * reqp) {
4021     long code = 0;
4022     AFSFid tfid;
4023     cm_fid_t cfid;
4024     cm_conn_t * connp;
4025     struct rx_connection * rxconnp;
4026     AFSVolSync volSync;
4027     afs_uint32 reqflags = reqp->flags;
4028
4029     tfid.Volume = scp->fid.volume;
4030     tfid.Vnode = scp->fid.vnode;
4031     tfid.Unique = scp->fid.unique;
4032     cfid = scp->fid;
4033
4034     osi_Log2(afsd_logp, "CALL SetLock scp 0x%p for lock %d", scp, lockType);
4035
4036     reqp->flags |= CM_REQ_NORETRY;
4037     lock_ReleaseWrite(&scp->rw);
4038
4039     do {
4040         code = cm_ConnFromFID(&cfid, userp, reqp, &connp);
4041         if (code) 
4042             break;
4043
4044         rxconnp = cm_GetRxConn(connp);
4045         code = RXAFS_SetLock(rxconnp, &tfid, lockType,
4046                              &volSync);
4047         rx_PutConnection(rxconnp);
4048
4049     } while (cm_Analyze(connp, userp, reqp, &cfid, &volSync,
4050                         NULL, NULL, code));
4051
4052     code = cm_MapRPCError(code, reqp);
4053     if (code) {
4054         osi_Log1(afsd_logp, "CALL SetLock FAILURE, code 0x%x", code);
4055     } else {
4056         osi_Log0(afsd_logp, "CALL SetLock SUCCESS");
4057     }
4058
4059     lock_ObtainWrite(&scp->rw);
4060     reqp->flags = reqflags;
4061     return code;
4062 }
4063
4064 /* called with scp->rw held.  Releases it during processing */
4065 long cm_IntReleaseLock(cm_scache_t * scp, cm_user_t * userp,
4066                        cm_req_t * reqp) {
4067     long code = 0;
4068     AFSFid tfid;
4069     cm_fid_t cfid;
4070     cm_conn_t * connp;
4071     struct rx_connection * rxconnp;
4072     AFSVolSync volSync;
4073
4074     tfid.Volume = scp->fid.volume;
4075     tfid.Vnode = scp->fid.vnode;
4076     tfid.Unique = scp->fid.unique;
4077     cfid = scp->fid;
4078
4079     lock_ReleaseWrite(&scp->rw);
4080
4081     osi_Log1(afsd_logp, "CALL ReleaseLock scp 0x%p", scp);
4082
4083     do {
4084         code = cm_ConnFromFID(&cfid, userp, reqp, &connp);
4085         if (code) 
4086             break;
4087
4088         rxconnp = cm_GetRxConn(connp);
4089         code = RXAFS_ReleaseLock(rxconnp, &tfid, &volSync);
4090         rx_PutConnection(rxconnp);
4091
4092     } while (cm_Analyze(connp, userp, reqp, &cfid, &volSync,
4093                         NULL, NULL, code));
4094     code = cm_MapRPCError(code, reqp);
4095     if (code)
4096         osi_Log1(afsd_logp,
4097                  "CALL ReleaseLock FAILURE, code 0x%x", code);
4098     else
4099         osi_Log0(afsd_logp,
4100                  "CALL ReleaseLock SUCCESS");
4101         
4102     lock_ObtainWrite(&scp->rw);
4103
4104     return code;
4105 }
4106
4107 /* called with scp->rw held.  May release it during processing, but
4108    will exit with lock held.
4109
4110    This will return:
4111
4112    - 0 if the user has permission to get the specified lock for the scp
4113
4114    - CM_ERROR_NOACCESS if not
4115
4116    Any other error from cm_SyncOp will be sent down untranslated.
4117
4118    If CM_ERROR_NOACCESS is returned and lock_type is LockRead, then
4119    phas_insert (if non-NULL) will receive a boolean value indicating
4120    whether the user has INSERT permission or not.
4121 */
4122 long cm_LockCheckPerms(cm_scache_t * scp,
4123                        int lock_type,
4124                        cm_user_t * userp,
4125                        cm_req_t * reqp,
4126                        int * phas_insert)
4127 {
4128     long rights = 0;
4129     long code = 0, code2 = 0;
4130
4131     /* lock permissions are slightly tricky because of the 'i' bit.
4132        If the user has PRSFS_LOCK, she can read-lock the file.  If the
4133        user has PRSFS_WRITE, she can write-lock the file.  However, if
4134        the user has PRSFS_INSERT, then she can write-lock new files,
4135        but not old ones.  Since we don't have information about
4136        whether a file is new or not, we assume that if the user owns
4137        the scp, then she has the permissions that are granted by
4138        PRSFS_INSERT. */
4139
4140     osi_Log3(afsd_logp, "cm_LockCheckPerms for scp[0x%p] type[%d] user[0x%p]",
4141              scp, lock_type, userp);
4142
4143     if (lock_type == LockRead)
4144         rights |= PRSFS_LOCK;
4145     else if (lock_type == LockWrite)
4146         rights |= PRSFS_WRITE | PRSFS_LOCK;
4147     else {
4148         /* hmmkay */
4149         osi_assertx(FALSE, "invalid lock type");
4150         return 0;
4151     }
4152
4153     if (phas_insert)
4154         *phas_insert = FALSE;
4155
4156     code = cm_SyncOp(scp, NULL, userp, reqp, rights,
4157                      CM_SCACHESYNC_GETSTATUS |
4158                      CM_SCACHESYNC_NEEDCALLBACK);
4159
4160     if (phas_insert && scp->creator == userp) {
4161
4162         /* If this file was created by the user, then we check for
4163            PRSFS_INSERT.  If the file server is recent enough, then
4164            this should be sufficient for her to get a write-lock (but
4165            not necessarily a read-lock). VICED_CAPABILITY_WRITELOCKACL
4166            indicates whether a file server supports getting write
4167            locks when the user only has PRSFS_INSERT. 
4168            
4169            If the file was not created by the user we skip the check
4170            because the INSERT bit will not apply to this user even
4171            if it is set.
4172          */
4173
4174         code2 = cm_SyncOp(scp, NULL, userp, reqp, PRSFS_INSERT,
4175                          CM_SCACHESYNC_GETSTATUS |
4176                          CM_SCACHESYNC_NEEDCALLBACK);
4177
4178         if (code2 == CM_ERROR_NOACCESS) {
4179             osi_Log0(afsd_logp, "cm_LockCheckPerms user has no INSERT bits");
4180         } else {
4181             *phas_insert = TRUE;
4182             osi_Log0(afsd_logp, "cm_LockCheckPerms user has INSERT bits");
4183         }
4184     }
4185
4186     cm_SyncOpDone(scp, NULL, CM_SCACHESYNC_NEEDCALLBACK | CM_SCACHESYNC_GETSTATUS);
4187
4188     osi_Log1(afsd_logp, "cm_LockCheckPerms returning code %d", code);
4189
4190     return code;
4191 }
4192
4193 /* called with scp->rw held */
4194 long cm_Lock(cm_scache_t *scp, unsigned char sLockType,
4195              LARGE_INTEGER LOffset, LARGE_INTEGER LLength,
4196              cm_key_t key,
4197              int allowWait, cm_user_t *userp, cm_req_t *reqp,
4198              cm_file_lock_t **lockpp)
4199 {
4200     long code = 0;
4201     int Which = ((sLockType & LOCKING_ANDX_SHARED_LOCK) ? LockRead : LockWrite);
4202     cm_file_lock_t *fileLock;
4203     osi_queue_t *q;
4204     cm_range_t range;
4205     int wait_unlock = FALSE;
4206     int force_client_lock = FALSE;
4207
4208     osi_Log4(afsd_logp, "cm_Lock scp 0x%x type 0x%x offset %d length %d",
4209              scp, sLockType, (unsigned long)LOffset.QuadPart, (unsigned long)LLength.QuadPart);
4210     osi_Log3(afsd_logp, "... allowWait %d key 0x%x:%x", allowWait, 
4211              (unsigned long)(key >> 32), (unsigned long)(key & 0xffffffff));
4212
4213     /*
4214    A client C can OBTAIN a lock L on cm_scache_t S iff (both 3 and 4):
4215
4216    3. for all _a_ in (L->LOffset,+L->LLength), ALL of the following is
4217       true:
4218
4219        3.1 If L->LockType is exclusive then there does NOT exist a
4220          ACCEPTED lock M in S->fileLocks such that _a_ in
4221          (M->LOffset,+M->LLength).
4222
4223        3.2 If L->LockType is shared then for each ACCEPTED lock M in
4224          S->fileLocks, if _a_ in (M->LOffset,+M->LLength) then
4225          M->LockType is shared.
4226
4227    4. For all LOST locks M in S->fileLocks, ALL of the following are true:
4228
4229        4.1 M->key != Key(C)
4230
4231        4.2 If M->LockType is exclusive, then (L->LOffset,+L->LLength)
4232          and (M->LOffset,+M->LLength) do not intersect.
4233     */
4234
4235     range.offset = LOffset.QuadPart;
4236     range.length = LLength.QuadPart;
4237
4238     lock_ObtainRead(&cm_scacheLock);
4239
4240     for (q = scp->fileLocksH; q; q = osi_QNext(q)) {
4241         fileLock =
4242             (cm_file_lock_t *)((char *) q - offsetof(cm_file_lock_t, fileq));
4243
4244         if (IS_LOCK_LOST(fileLock)) {
4245             if (fileLock->key == key) {
4246                 code = CM_ERROR_BADFD;
4247                 break;
4248             } else if (fileLock->lockType == LockWrite && INTERSECT_RANGE(range, fileLock->range)) {
4249                 code = CM_ERROR_WOULDBLOCK;
4250                 wait_unlock = TRUE;
4251                 break;
4252             }
4253         }
4254
4255         /* we don't need to check for deleted locks here since deleted
4256            locks are dequeued from scp->fileLocks */
4257         if (IS_LOCK_ACCEPTED(fileLock) &&
4258            INTERSECT_RANGE(range, fileLock->range)) {
4259
4260             if ((sLockType & LOCKING_ANDX_SHARED_LOCK) == 0 ||
4261                 fileLock->lockType != LockRead) {
4262                 wait_unlock = TRUE;
4263                 code = CM_ERROR_WOULDBLOCK;
4264                 break;
4265             }
4266         }
4267     }
4268
4269     lock_ReleaseRead(&cm_scacheLock);
4270
4271     if (code == 0 && SERVERLOCKS_ENABLED(scp)) {
4272         if (Which == scp->serverLock ||
4273            (Which == LockRead && scp->serverLock == LockWrite)) {
4274
4275             int has_insert = 0;
4276
4277             /* we already have the lock we need */
4278             osi_Log3(afsd_logp, "   we already have the correct lock. exclusives[%d], shared[%d], serverLock[%d]", 
4279                      scp->exclusiveLocks, scp->sharedLocks, (int)(signed char) scp->serverLock);
4280
4281             code = cm_LockCheckPerms(scp, Which, userp, reqp, &has_insert);
4282
4283             /* special case: if we don't have permission to read-lock
4284                the file, then we force a clientside lock.  This is to
4285                compensate for applications that obtain a read-lock for
4286                reading files off of directories that don't grant
4287                read-locks to the user. */
4288             if (code == CM_ERROR_NOACCESS && Which == LockRead) {
4289
4290                 if (has_insert && SCP_SUPPORTS_WRITELOCKACL(scp)) {
4291                     osi_Log0(afsd_logp, "   User has no read-lock perms, but has INSERT perms.");
4292                     code = 0;
4293                 } else {
4294                     osi_Log0(afsd_logp, "   User has no read-lock perms. Forcing client-side lock");
4295                     force_client_lock = TRUE;
4296                 }
4297             }
4298
4299         } else if ((scp->exclusiveLocks > 0) ||
4300                    (scp->sharedLocks > 0 && scp->serverLock != LockRead)) {
4301             int has_insert = 0;
4302
4303             /* We are already waiting for some other lock.  We should
4304                wait for the daemon to catch up instead of generating a
4305                flood of SetLock calls. */
4306             osi_Log3(afsd_logp, "   already waiting for other lock. exclusives[%d], shared[%d], serverLock[%d]",
4307                      scp->exclusiveLocks, scp->sharedLocks, (int)(signed char) scp->serverLock);
4308
4309             /* see if we have permission to create the lock in the
4310                first place. */
4311             code = cm_LockCheckPerms(scp, Which, userp, reqp, &has_insert);
4312             if (code == 0)
4313                 code = CM_ERROR_WOULDBLOCK;
4314             else if (code == CM_ERROR_NOACCESS && Which == LockRead) {
4315
4316                 if (has_insert && SCP_SUPPORTS_WRITELOCKACL(scp)) {
4317                     osi_Log0(afsd_logp,
4318                              "   User has no read-lock perms, but has INSERT perms.");
4319                     code = CM_ERROR_WOULDBLOCK;
4320                 } else {
4321                     osi_Log0(afsd_logp,
4322                              "   User has no read-lock perms. Forcing client-side lock");
4323                     force_client_lock = TRUE;
4324                 }
4325             }
4326
4327             /* leave any other codes as-is */
4328
4329         } else {
4330             int newLock;
4331             int check_data_version = FALSE;
4332             int has_insert = 0;
4333
4334             /* first check if we have permission to elevate or obtain
4335                the lock. */
4336             code = cm_LockCheckPerms(scp, Which, userp, reqp, &has_insert);
4337             if (code) {
4338                 if (code == CM_ERROR_NOACCESS && Which == LockRead &&
4339                     (!has_insert || !SCP_SUPPORTS_WRITELOCKACL(scp))) {
4340                     osi_Log0(afsd_logp, "   User has no read-lock perms.  Forcing client-side lock");
4341                     force_client_lock = TRUE;
4342                 }
4343                 goto check_code;
4344             }
4345
4346             /* has_insert => (Which == LockRead, code == CM_ERROR_NOACCESS) */
4347
4348             if (scp->serverLock == LockRead && Which == LockWrite) {
4349
4350                 /* We want to escalate the lock to a LockWrite.
4351                  * Unfortunately that's not really possible without
4352                  * letting go of the current lock.  But for now we do
4353                  * it anyway. */
4354
4355                 osi_Log0(afsd_logp,
4356                          "   attempting to UPGRADE from LockRead to LockWrite.");
4357                 osi_Log1(afsd_logp,
4358                          "   dataVersion on scp: %I64d", scp->dataVersion);
4359
4360                 /* we assume at this point (because scp->serverLock
4361                    was valid) that we had a valid server lock. */
4362                 scp->lockDataVersion = scp->dataVersion;
4363                 check_data_version = TRUE;
4364         
4365                 code = cm_IntReleaseLock(scp, userp, reqp);
4366
4367                 if (code) {
4368                     /* We couldn't release the lock */
4369                     goto check_code;
4370                 } else {
4371                     scp->serverLock = -1;
4372                 }
4373             }
4374
4375             /* We need to obtain a server lock of type Which in order
4376              * to assert this file lock */
4377 #ifndef AGGRESSIVE_LOCKS
4378             newLock = Which;
4379 #else
4380             newLock = LockWrite;
4381 #endif
4382
4383             code = cm_IntSetLock(scp, userp, newLock, reqp);
4384
4385 #ifdef AGGRESSIVE_LOCKS
4386             if ((code == CM_ERROR_WOULDBLOCK ||
4387                  code == CM_ERROR_NOACCESS) && newLock != Which) {
4388                 /* we wanted LockRead.  We tried LockWrite. Now try
4389                  * LockRead again */
4390                 newLock = Which;
4391
4392                 /* am I sane? */
4393                 osi_assertx(newLock == LockRead, "lock type not read");
4394
4395                 code = cm_IntSetLock(scp, userp, newLock, reqp);
4396             }
4397 #endif
4398
4399             if (code == CM_ERROR_NOACCESS) {
4400                 if (Which == LockRead) {
4401                     if (has_insert && SCP_SUPPORTS_WRITELOCKACL(scp)) {
4402                         long tcode;
4403                         /* We requested a read-lock, but we have permission to
4404                          * get a write-lock. Try that */
4405
4406                         tcode = cm_LockCheckPerms(scp, LockWrite, userp, reqp, NULL);
4407
4408                         if (tcode == 0) {
4409                             newLock = LockWrite;
4410
4411                             osi_Log0(afsd_logp, "   User has 'i' perms and the request was for a LockRead.  Trying to get a LockWrite instead");
4412
4413                             code = cm_IntSetLock(scp, userp, newLock, reqp);
4414                         }
4415                     } else {
4416                         osi_Log0(afsd_logp, "   User has no read-lock perms.  Forcing client-side lock");
4417                         force_client_lock = TRUE;
4418                     }
4419                 } else if (Which == LockWrite &&
4420                            scp->creator == userp && !SCP_SUPPORTS_WRITELOCKACL(scp)) {
4421                     long tcode;
4422
4423                     /* Special case: if the lock request was for a
4424                      * LockWrite and the user owns the file and we weren't
4425                      * allowed to obtain the serverlock, we either lost a
4426                      * race (the permissions changed from under us), or we
4427                      * have 'i' bits, but we aren't allowed to lock the
4428                      * file. */
4429
4430                     /* check if we lost a race... */
4431                     tcode = cm_LockCheckPerms(scp, Which, userp, reqp, NULL);
4432
4433                     if (tcode == 0) {
4434                         osi_Log0(afsd_logp, "   User has 'i' perms but can't obtain write locks. Using client-side locks.");
4435                         force_client_lock = TRUE;
4436                     }
4437                 }
4438             }
4439
4440             if (code == 0 && check_data_version &&
4441                scp->dataVersion != scp->lockDataVersion) {
4442                 /* We lost a race.  Although we successfully obtained
4443                  * a lock, someone modified the file in between.  The
4444                  * locks have all been technically lost. */
4445
4446                 osi_Log0(afsd_logp,
4447                          "  Data version mismatch while upgrading lock.");
4448                 osi_Log2(afsd_logp,
4449                          "  Data versions before=%I64d, after=%I64d",
4450                          scp->lockDataVersion,
4451                          scp->dataVersion);
4452                 osi_Log1(afsd_logp,
4453                          "  Releasing stale lock for scp 0x%x", scp);
4454
4455                 code = cm_IntReleaseLock(scp, userp, reqp);
4456
4457                 scp->serverLock = -1;
4458
4459                 code = CM_ERROR_INVAL;
4460             } else if (code == 0) {
4461                 scp->serverLock = newLock;
4462                 scp->lockDataVersion = scp->dataVersion;
4463             }
4464
4465             if (code != 0 &&
4466                 (scp->sharedLocks > 0 || scp->exclusiveLocks > 0) &&
4467                 scp->serverLock == -1) {
4468                 /* Oops. We lost the lock. */
4469                 cm_LockMarkSCacheLost(scp);
4470             }
4471         }
4472     } else if (code == 0) {     /* server locks not enabled */
4473         osi_Log0(afsd_logp,
4474                  "  Skipping server lock for scp");
4475     }
4476
4477  check_code:
4478
4479     if (code != 0 && !force_client_lock) {
4480         /* Special case error translations
4481
4482            Applications don't expect certain errors from a
4483            LockFile/UnlockFile call.  We need to translate some error
4484            code to codes that apps expect and handle. */
4485
4486         /* We shouldn't actually need to handle this case since we
4487            simulate locks for RO scps anyway. */
4488         if (code == CM_ERROR_READONLY) {
4489             osi_Log0(afsd_logp, "   Reinterpreting CM_ERROR_READONLY as CM_ERROR_NOACCESS");
4490             code = CM_ERROR_NOACCESS;
4491         }
4492     }
4493
4494     if (code == 0 || (code == CM_ERROR_WOULDBLOCK && allowWait) ||
4495         force_client_lock) {
4496
4497         /* clear the error if we are forcing a client lock, so we
4498            don't get confused later. */
4499         if (force_client_lock && code != CM_ERROR_WOULDBLOCK)
4500             code = 0;
4501
4502         lock_ObtainWrite(&cm_scacheLock);
4503         fileLock = cm_GetFileLock();
4504         lock_ReleaseWrite(&cm_scacheLock);
4505 #ifdef DEBUG
4506         fileLock->fid = scp->fid;
4507 #endif
4508         fileLock->key = key;
4509         fileLock->lockType = Which;
4510         cm_HoldUser(userp);
4511         fileLock->userp = userp;
4512         fileLock->range = range;
4513         fileLock->flags = (code == 0 ? 0 : 
4514                            ((wait_unlock)?
4515                             CM_FILELOCK_FLAG_WAITUNLOCK :
4516                             CM_FILELOCK_FLAG_WAITLOCK));
4517
4518         if (force_client_lock || !SERVERLOCKS_ENABLED(scp))
4519             fileLock->flags |= CM_FILELOCK_FLAG_CLIENTONLY;
4520
4521         fileLock->lastUpdate = (code == 0 && !force_client_lock) ? time(NULL) : 0;
4522
4523         lock_ObtainWrite(&cm_scacheLock);
4524         osi_QAddT(&scp->fileLocksH, &scp->fileLocksT, &fileLock->fileq);
4525         cm_HoldSCacheNoLock(scp);
4526         fileLock->scp = scp;
4527         osi_QAdd(&cm_allFileLocks, &fileLock->q);
4528         lock_ReleaseWrite(&cm_scacheLock);
4529
4530         if (code != 0) {
4531             *lockpp = fileLock;
4532         }
4533
4534         if (IS_LOCK_CLIENTONLY(fileLock)) {
4535             scp->clientLocks++;
4536         } else if (IS_LOCK_ACCEPTED(fileLock)) {
4537             if (Which == LockRead)
4538                 scp->sharedLocks++;
4539             else
4540                 scp->exclusiveLocks++;
4541         }
4542
4543         osi_Log3(afsd_logp,
4544                  "cm_Lock Lock added 0x%p flags 0x%x to scp [0x%p]",
4545                  fileLock, fileLock->flags, scp);
4546         osi_Log4(afsd_logp,
4547                  "   exclusives[%d] shared[%d] client[%d] serverLock[%d]",
4548                  scp->exclusiveLocks, scp->sharedLocks, scp->clientLocks,
4549                  (int)(signed char) scp->serverLock);
4550     } else {
4551         osi_Log1(afsd_logp,
4552                  "cm_Lock Rejecting lock (code = 0x%x)", code);
4553     }
4554
4555     return code;
4556 }
4557
4558 static int cm_KeyEquals(cm_key_t k1, cm_key_t k2, int flags);
4559
4560 /* Called with scp->rw held */
4561 long cm_UnlockByKey(cm_scache_t * scp,
4562                     cm_key_t key,
4563                     int flags,
4564                     cm_user_t * userp,
4565                      cm_req_t * reqp)
4566 {
4567     long code = 0;
4568     cm_file_lock_t *fileLock;
4569     osi_queue_t *q, *qn;
4570     int n_unlocks = 0;
4571
4572     osi_Log4(afsd_logp, "cm_UnlockByKey scp 0x%p key 0x%x:%x flags=0x%x",
4573              scp,
4574              (unsigned long)(key >> 32),
4575              (unsigned long)(key & 0xffffffff),
4576              flags);
4577
4578     lock_ObtainWrite(&cm_scacheLock);
4579
4580     for (q = scp->fileLocksH; q; q = qn) {
4581         qn = osi_QNext(q);
4582
4583         fileLock = (cm_file_lock_t *)
4584             ((char *) q - offsetof(cm_file_lock_t, fileq));
4585
4586 #ifdef DEBUG
4587         osi_Log4(afsd_logp, "   Checking lock[0x%x] range[%d,+%d] type[%d]",
4588                  fileLock,
4589                  (unsigned long) fileLock->range.offset,
4590                  (unsigned long) fileLock->range.length,
4591                 fileLock->lockType);
4592         osi_Log3(afsd_logp, "     key[0x%x:%x] flags[0x%x]",
4593                  (unsigned long)(fileLock->key >> 32),
4594                  (unsigned long)(fileLock->key & 0xffffffff),
4595                  fileLock->flags);
4596
4597         if (cm_FidCmp(&fileLock->fid, &fileLock->scp->fid)) {
4598             osi_Log0(afsd_logp, "!!fileLock->fid != scp->fid");
4599             osi_Log4(afsd_logp, "  fileLock->fid(cell=[%d], volume=[%d], vnode=[%d], unique=[%d]",
4600                      fileLock->fid.cell,
4601                      fileLock->fid.volume,
4602                      fileLock->fid.vnode,
4603                      fileLock->fid.unique);
4604             osi_Log4(afsd_logp, "  scp->fid(cell=[%d], volume=[%d], vnode=[%d], unique=[%d]",
4605                      fileLock->scp->fid.cell,
4606                      fileLock->scp->fid.volume,
4607                      fileLock->scp->fid.vnode,
4608                      fileLock->scp->fid.unique);
4609             osi_assertx(FALSE, "invalid fid value");
4610         }
4611 #endif
4612
4613         if (!IS_LOCK_DELETED(fileLock) &&
4614             cm_KeyEquals(fileLock->key, key, flags)) {
4615             osi_Log3(afsd_logp, "...Unlock range [%d,+%d] type %d",
4616                     fileLock->range.offset,
4617                     fileLock->range.length,
4618                     fileLock->lockType);
4619
4620             if (scp->fileLocksT == q)
4621                 scp->fileLocksT = osi_QPrev(q);
4622             osi_QRemoveHT(&scp->fileLocksH, &scp->fileLocksT, q);
4623
4624             if (IS_LOCK_CLIENTONLY(fileLock)) {
4625                 scp->clientLocks--;
4626             } else if (IS_LOCK_ACCEPTED(fileLock)) {
4627                 if (fileLock->lockType == LockRead)
4628                     scp->sharedLocks--;
4629                 else
4630                     scp->exclusiveLocks--;
4631             }
4632
4633             fileLock->flags |= CM_FILELOCK_FLAG_DELETED;
4634
4635             cm_ReleaseUser(fileLock->userp);
4636             cm_ReleaseSCacheNoLock(scp);
4637
4638             fileLock->userp = NULL;
4639             fileLock->scp = NULL;
4640
4641             n_unlocks++;
4642         }
4643     }
4644
4645     lock_ReleaseWrite(&cm_scacheLock);
4646
4647     if (n_unlocks == 0) {
4648         osi_Log0(afsd_logp, "cm_UnlockByKey no locks found");
4649         osi_Log3(afsd_logp, "   Leaving scp with exclusives[%d], shared[%d], serverLock[%d]",
4650                  scp->exclusiveLocks, scp->sharedLocks, (int)(signed char) scp->serverLock);
4651         
4652         return 0;
4653     }
4654
4655     osi_Log1(afsd_logp, "cm_UnlockByKey done with %d locks", n_unlocks);
4656
4657     osi_assertx(scp->sharedLocks >= 0, "scp->sharedLocks < 0");
4658     osi_assertx(scp->exclusiveLocks >= 0, "scp->exclusiveLocks < 0");
4659     osi_assertx(scp->clientLocks >= 0, "scp->clientLocks < 0");
4660
4661     if (!SERVERLOCKS_ENABLED(scp)) {
4662         osi_Log0(afsd_logp, "  Skipping server lock for scp");
4663         goto done;
4664     }
4665
4666     /* Ideally we would go through the rest of the locks to determine
4667      * if one or more locks that were formerly in WAITUNLOCK can now
4668      * be put to ACTIVE or WAITLOCK and update scp->exclusiveLocks and
4669      * scp->sharedLocks accordingly.  However, the retrying of locks
4670      * in that manner is done cm_RetryLock() manually.
4671      */
4672
4673     if (scp->serverLock == LockWrite &&
4674         scp->exclusiveLocks == 0 &&
4675         scp->sharedLocks > 0) {
4676
4677         /* The serverLock should be downgraded to LockRead */
4678         osi_Log0(afsd_logp, "  DOWNGRADE lock from LockWrite to LockRead");
4679
4680         /* since scp->serverLock looked sane, we are going to assume
4681            that we have a valid server lock. */
4682         scp->lockDataVersion = scp->dataVersion;
4683         osi_Log1(afsd_logp, "  dataVersion on scp = %I64d", scp->dataVersion);
4684
4685         code = cm_IntReleaseLock(scp, userp, reqp);
4686
4687         if (code) {
4688             /* so we couldn't release it.  Just let the lock be for now */
4689             code = 0;
4690             goto done;
4691         } else {
4692             scp->serverLock = -1;
4693         }
4694
4695         code = cm_IntSetLock(scp, userp, LockRead, reqp);
4696
4697         if (code == 0 && scp->lockDataVersion == scp->dataVersion) {
4698             scp->serverLock = LockRead;
4699         } else if (code == 0 && scp->lockDataVersion != scp->dataVersion) {
4700             /* We lost a race condition.  Although we have a valid
4701                lock on the file, the data has changed and essentially
4702                we have lost the lock we had during the transition. */
4703
4704             osi_Log0(afsd_logp, "Data version mismatch during lock downgrade");
4705             osi_Log2(afsd_logp, "  Data versions before=%I64d, after=%I64d",
4706                      scp->lockDataVersion,
4707                      scp->dataVersion);
4708             
4709             code = cm_IntReleaseLock(scp, userp, reqp);
4710
4711             code = CM_ERROR_INVAL;
4712             scp->serverLock = -1;
4713         }
4714
4715         if (code != 0 &&
4716             (scp->sharedLocks > 0 || scp->exclusiveLocks > 0) &&
4717                 (scp->serverLock == -1)) {
4718                 /* Oopsie */
4719                 cm_LockMarkSCacheLost(scp);
4720             }
4721
4722         /* failure here has no bearing on the return value of
4723            cm_Unlock() */
4724         code = 0;
4725
4726     } else if (scp->serverLock != (-1) &&
4727               scp->exclusiveLocks == 0 &&
4728               scp->sharedLocks == 0) {
4729         /* The serverLock should be released entirely */
4730
4731         code = cm_IntReleaseLock(scp, userp, reqp);
4732
4733         if (code == 0)
4734             scp->serverLock = (-1);
4735     }
4736
4737  done:
4738
4739     osi_Log1(afsd_logp, "cm_UnlockByKey code 0x%x", code);
4740     osi_Log4(afsd_logp, "   Leaving scp with excl[%d], shared[%d], client[%d], serverLock[%d]",
4741              scp->exclusiveLocks, scp->sharedLocks, scp->clientLocks,
4742              (int)(signed char) scp->serverLock);
4743
4744     return code;
4745 }
4746
4747 long cm_Unlock(cm_scache_t *scp, 
4748                unsigned char sLockType,
4749                LARGE_INTEGER LOffset, LARGE_INTEGER LLength,
4750                cm_key_t key, 
4751                cm_user_t *userp, 
4752                cm_req_t *reqp)
4753 {
4754     long code = 0;
4755     int Which = ((sLockType & LOCKING_ANDX_SHARED_LOCK) ? LockRead : LockWrite);
4756     cm_file_lock_t *fileLock;
4757     osi_queue_t *q;
4758     int release_userp = FALSE;
4759
4760     osi_Log4(afsd_logp, "cm_Unlock scp 0x%p type 0x%x offset %d length %d",
4761              scp, sLockType, (unsigned long)LOffset.QuadPart, (unsigned long)LLength.QuadPart);
4762     osi_Log2(afsd_logp, "... key 0x%x:%x",
4763              (unsigned long) (key >> 32), (unsigned long) (key & 0xffffffff));
4764
4765     lock_ObtainRead(&cm_scacheLock);
4766
4767     for (q = scp->fileLocksH; q; q = osi_QNext(q)) {
4768         fileLock = (cm_file_lock_t *)
4769             ((char *) q - offsetof(cm_file_lock_t, fileq));
4770
4771 #ifdef DEBUG
4772         if (cm_FidCmp(&fileLock->fid, &fileLock->scp->fid)) {
4773             osi_Log0(afsd_logp, "!!fileLock->fid != scp->fid");
4774             osi_Log4(afsd_logp, "  fileLock->fid(cell=[%d], volume=[%d], vnode=[%d], unique=[%d]",
4775                      fileLock->fid.cell,
4776                      fileLock->fid.volume,
4777                      fileLock->fid.vnode,
4778                      fileLock->fid.unique);
4779             osi_Log4(afsd_logp, "  scp->fid(cell=[%d], volume=[%d], vnode=[%d], unique=[%d]",
4780                      fileLock->scp->fid.cell,
4781                      fileLock->scp->fid.volume,
4782                      fileLock->scp->fid.vnode,
4783                      fileLock->scp->fid.unique);
4784             osi_assertx(FALSE, "invalid fid value");
4785         }
4786 #endif
4787         if (!IS_LOCK_DELETED(fileLock) &&
4788             fileLock->key == key &&
4789             fileLock->range.offset == LOffset.QuadPart &&
4790             fileLock->range.length == LLength.QuadPart) {
4791             break;
4792         }
4793     }
4794
4795     if (!q) {
4796         osi_Log0(afsd_logp, "cm_Unlock lock not found; failure");
4797         
4798         lock_ReleaseRead(&cm_scacheLock);
4799
4800         /* The lock didn't exist anyway. *shrug* */
4801         return CM_ERROR_RANGE_NOT_LOCKED;
4802     }
4803
4804     /* discard lock record */
4805     lock_ConvertRToW(&cm_scacheLock);
4806     if (scp->fileLocksT == q)
4807         scp->fileLocksT = osi_QPrev(q);
4808     osi_QRemoveHT(&scp->fileLocksH, &scp->fileLocksT, q);
4809
4810     /*
4811      * Don't delete it here; let the daemon delete it, to simplify
4812      * the daemon's traversal of the list.
4813      */
4814
4815     if (IS_LOCK_CLIENTONLY(fileLock)) {
4816         scp->clientLocks--;
4817     } else if (IS_LOCK_ACCEPTED(fileLock)) {
4818         if (fileLock->lockType == LockRead)
4819             scp->sharedLocks--;
4820         else
4821             scp->exclusiveLocks--;
4822     }
4823
4824     fileLock->flags |= CM_FILELOCK_FLAG_DELETED;
4825     if (userp != NULL) {
4826         cm_ReleaseUser(fileLock->userp);
4827     } else {
4828         userp = fileLock->userp;
4829         release_userp = TRUE;
4830     }
4831     fileLock->userp = NULL;
4832     cm_ReleaseSCacheNoLock(scp);
4833     fileLock->scp = NULL;
4834     lock_ReleaseWrite(&cm_scacheLock);
4835
4836     if (!SERVERLOCKS_ENABLED(scp)) {
4837         osi_Log0(afsd_logp, "   Skipping server locks for scp");
4838         goto done;
4839     }
4840
4841     /* Ideally we would go through the rest of the locks to determine
4842      * if one or more locks that were formerly in WAITUNLOCK can now
4843      * be put to ACTIVE or WAITLOCK and update scp->exclusiveLocks and
4844      * scp->sharedLocks accordingly.  However, the retrying of locks
4845      * in that manner is done cm_RetryLock() manually.
4846      */
4847
4848     if (scp->serverLock == LockWrite &&
4849         scp->exclusiveLocks == 0 &&
4850         scp->sharedLocks > 0) {
4851
4852         /* The serverLock should be downgraded to LockRead */
4853         osi_Log0(afsd_logp, "  DOWNGRADE lock from LockWrite to LockRead");
4854
4855         /* Since we already had a lock, we assume that there is a
4856            valid server lock. */
4857         scp->lockDataVersion = scp->dataVersion;
4858         osi_Log1(afsd_logp, "   dataVersion on scp is %I64d", scp->dataVersion);
4859
4860         /* before we downgrade, make sure that we have enough
4861            permissions to get the read lock. */
4862         code = cm_LockCheckPerms(scp, LockRead, userp, reqp, NULL);
4863         if (code != 0) {
4864
4865             osi_Log0(afsd_logp, "  SKIPPING downgrade because user doesn't have perms to get downgraded lock");
4866
4867             code = 0;
4868             goto done;
4869         }
4870
4871         code = cm_IntReleaseLock(scp, userp, reqp);
4872
4873         if (code) {
4874             /* so we couldn't release it.  Just let the lock be for now */
4875             code = 0;
4876             goto done;
4877         } else {
4878             scp->serverLock = -1;
4879         }
4880
4881         code = cm_IntSetLock(scp, userp, LockRead, reqp);
4882
4883         if (code == 0 && scp->lockDataVersion == scp->dataVersion) {
4884             scp->serverLock = LockRead;
4885         } else if (code == 0 && scp->lockDataVersion != scp->dataVersion) {
4886             /* Lost a race.  We obtained a new lock, but that is
4887                meaningless since someone modified the file
4888                inbetween. */
4889
4890             osi_Log0(afsd_logp,
4891                      "Data version mismatch while downgrading lock");
4892             osi_Log2(afsd_logp,
4893                      "  Data versions before=%I64d, after=%I64d",
4894                      scp->lockDataVersion,
4895                      scp->dataVersion);
4896             
4897             code = cm_IntReleaseLock(scp, userp, reqp);
4898
4899             scp->serverLock = -1;
4900             code = CM_ERROR_INVAL;
4901         }
4902
4903         if (code != 0 &&
4904             (scp->sharedLocks > 0 || scp->exclusiveLocks > 0) &&
4905                 (scp->serverLock == -1)) {
4906                 /* Oopsie */
4907                 cm_LockMarkSCacheLost(scp);
4908             }
4909
4910         /* failure here has no bearing on the return value of
4911            cm_Unlock() */
4912         code = 0;
4913
4914     } else if (scp->serverLock != (-1) &&
4915               scp->exclusiveLocks == 0 &&
4916               scp->sharedLocks == 0) {
4917         /* The serverLock should be released entirely */
4918
4919         code = cm_IntReleaseLock(scp, userp, reqp);
4920
4921         if (code == 0) {
4922             scp->serverLock = (-1);
4923         }
4924     }
4925
4926     if (release_userp)
4927         cm_ReleaseUser(userp);
4928
4929  done:
4930
4931     osi_Log1(afsd_logp, "cm_Unlock code 0x%x", code);
4932     osi_Log4(afsd_logp, "  leaving scp with excl[%d], shared[%d], client[%d], serverLock[%d]",
4933              scp->exclusiveLocks, scp->sharedLocks, scp->clientLocks,
4934              (int)(signed char) scp->serverLock);
4935
4936     return code;
4937 }
4938
4939 /* called with scp->rw held */
4940 void cm_LockMarkSCacheLost(cm_scache_t * scp)
4941 {
4942     cm_file_lock_t *fileLock;
4943     osi_queue_t *q;
4944
4945     osi_Log1(afsd_logp, "cm_LockMarkSCacheLost scp 0x%x", scp);
4946
4947     /* cm_scacheLock needed because we are modifying fileLock->flags */
4948     lock_ObtainWrite(&cm_scacheLock);
4949
4950     for (q = scp->fileLocksH; q; q = osi_QNext(q)) {
4951         fileLock = 
4952             (cm_file_lock_t *)((char *) q - offsetof(cm_file_lock_t, fileq));
4953
4954         if (IS_LOCK_ACTIVE(fileLock) &&
4955             !IS_LOCK_CLIENTONLY(fileLock)) {
4956             if (fileLock->lockType == LockRead)
4957                 scp->sharedLocks--;
4958             else
4959                 scp->exclusiveLocks--;
4960
4961             fileLock->flags |= CM_FILELOCK_FLAG_LOST;
4962         }
4963     }
4964
4965     scp->serverLock = -1;
4966     scp->lockDataVersion = -1;
4967     lock_ReleaseWrite(&cm_scacheLock);
4968 }
4969
4970 /* Called with no relevant locks held */
4971 void cm_CheckLocks()
4972 {
4973     osi_queue_t *q, *nq;
4974     cm_file_lock_t *fileLock;
4975     cm_req_t req;
4976     AFSFid tfid;
4977     AFSVolSync volSync;
4978     cm_conn_t *connp;
4979     long code;
4980     struct rx_connection * rxconnp;
4981     cm_scache_t * scp;
4982
4983     cm_InitReq(&req);
4984
4985     lock_ObtainWrite(&cm_scacheLock);
4986
4987     cm_lockRefreshCycle++;
4988
4989     osi_Log1(afsd_logp, "cm_CheckLocks starting lock check cycle %d", cm_lockRefreshCycle);
4990
4991     for (q = cm_allFileLocks; q; q = nq) {
4992         fileLock = (cm_file_lock_t *) q;
4993         nq = osi_QNext(q);
4994         code = -1;
4995
4996         if (IS_LOCK_DELETED(fileLock)) {
4997
4998             osi_QRemove(&cm_allFileLocks, q);
4999             cm_PutFileLock(fileLock);
5000
5001         } else if (IS_LOCK_ACTIVE(fileLock) && !IS_LOCK_CLIENTONLY(fileLock)) {
5002
5003             /* Server locks must have been enabled for us to have
5004                received an active non-client-only lock. */
5005             osi_assertx(cm_enableServerLocks, "!cm_enableServerLocks");
5006
5007             scp = fileLock->scp;
5008             osi_assertx(scp != NULL, "null cm_scache_t");
5009
5010             cm_HoldSCacheNoLock(scp);
5011
5012 #ifdef DEBUG
5013             if (cm_FidCmp(&fileLock->fid, &fileLock->scp->fid)) {
5014                 osi_Log0(afsd_logp, "!!fileLock->fid != scp->fid");
5015                 osi_Log4(afsd_logp, "  fileLock->fid(cell=[%d], volume=[%d], vnode=[%d], unique=[%d]",
5016                          fileLock->fid.cell,
5017                          fileLock->fid.volume,
5018                          fileLock->fid.vnode,
5019                          fileLock->fid.unique);
5020                 osi_Log4(afsd_logp, "  scp->fid(cell=[%d], volume=[%d], vnode=[%d], unique=[%d]",
5021                          fileLock->scp->fid.cell,
5022                          fileLock->scp->fid.volume,
5023                          fileLock->scp->fid.vnode,
5024                          fileLock->scp->fid.unique);
5025                 osi_assertx(FALSE, "invalid fid");
5026             }
5027 #endif
5028             /* Server locks are extended once per scp per refresh
5029                cycle. */
5030             if (scp->lastRefreshCycle != cm_lockRefreshCycle) {
5031
5032                 int scp_done = FALSE;
5033
5034                 osi_Log1(afsd_logp, "cm_CheckLocks Updating scp 0x%x", scp);
5035
5036                 lock_ReleaseWrite(&cm_scacheLock);
5037                 lock_ObtainWrite(&scp->rw);
5038
5039                 /* did the lock change while we weren't holding the lock? */
5040                 if (!IS_LOCK_ACTIVE(fileLock))
5041                     goto post_syncopdone;
5042
5043                 code = cm_SyncOp(scp, NULL, fileLock->userp, &req, 0,
5044                                  CM_SCACHESYNC_NEEDCALLBACK
5045                                  | CM_SCACHESYNC_GETSTATUS
5046                                  | CM_SCACHESYNC_LOCK);
5047
5048                 if (code) {
5049                     osi_Log1(afsd_logp,
5050                              "cm_CheckLocks SyncOp failure code 0x%x", code);
5051                     goto post_syncopdone;
5052                 }
5053
5054                 /* cm_SyncOp releases scp->rw during which the lock
5055                    may get released. */
5056                 if (!IS_LOCK_ACTIVE(fileLock))
5057                     goto pre_syncopdone;
5058
5059                 if (scp->serverLock != -1 && !(scp->flags & CM_SCACHEFLAG_DELETED)) {
5060                     cm_fid_t cfid;
5061                     cm_user_t * userp;
5062
5063                     tfid.Volume = scp->fid.volume;
5064                     tfid.Vnode = scp->fid.vnode;
5065                     tfid.Unique = scp->fid.unique;
5066                     cfid = scp->fid;
5067                     userp = fileLock->userp;
5068                     
5069                     osi_Log3(afsd_logp, "CALL ExtendLock lock 0x%p for scp=0x%p with lock %d", 
5070                              fileLock,
5071                              scp,
5072                              (int) scp->serverLock);
5073
5074                     lock_ReleaseWrite(&scp->rw);
5075
5076                     do {
5077                         code = cm_ConnFromFID(&cfid, userp,
5078                                        &req, &connp);
5079                         if (code) 
5080                             break;
5081
5082                         rxconnp = cm_GetRxConn(connp);
5083                         code = RXAFS_ExtendLock(rxconnp, &tfid,
5084                                                 &volSync);
5085                         rx_PutConnection(rxconnp);
5086
5087                         osi_Log1(afsd_logp, "   ExtendLock returns %d", code);
5088
5089                     } while (cm_Analyze(connp, userp, &req,
5090                                         &cfid, &volSync, NULL, NULL,
5091                                         code));
5092
5093                     code = cm_MapRPCError(code, &req);
5094
5095                     lock_ObtainWrite(&scp->rw);
5096
5097                     if (code) {
5098                         osi_Log1(afsd_logp, "CALL ExtendLock FAILURE, code 0x%x", code);
5099                     } else {
5100                         osi_Log0(afsd_logp, "CALL ExtendLock SUCCESS");
5101                         scp->lockDataVersion = scp->dataVersion;
5102                     }
5103
5104                     if ((code == EINVAL || code == CM_ERROR_INVAL) &&
5105                         scp->lockDataVersion == scp->dataVersion) {
5106                         int lockType;
5107
5108                         lockType =
5109                             (scp->exclusiveLocks > 0) ? LockWrite: LockRead;
5110
5111                         /* we might still have a chance to obtain a
5112                            new lock */
5113
5114                         code = cm_IntSetLock(scp, userp, lockType, &req);
5115
5116                         if (code) {
5117                             code = CM_ERROR_INVAL;
5118                         } else if (scp->lockDataVersion != scp->dataVersion) {
5119
5120                             /* now check if we still have the file at
5121                                the right data version. */
5122                             osi_Log1(afsd_logp,
5123                                      "Data version mismatch on scp 0x%p",
5124                                      scp);
5125                             osi_Log2(afsd_logp,
5126                                      "   Data versions: before=%I64d, after=%I64d",
5127                                      scp->lockDataVersion,
5128                                      scp->dataVersion);
5129
5130                             code = cm_IntReleaseLock(scp, userp, &req);
5131
5132                             code = CM_ERROR_INVAL;
5133                         }
5134                     }
5135
5136                     if (code == EINVAL || code == CM_ERROR_INVAL ||
5137                         code == CM_ERROR_BADFD) {
5138                         cm_LockMarkSCacheLost(scp);
5139                     }
5140
5141                 } else {
5142                     /* interestingly, we have found an active lock
5143                        belonging to an scache that has no
5144                        serverLock */
5145                     cm_LockMarkSCacheLost(scp);
5146                 }
5147
5148                 scp_done = TRUE;
5149
5150             pre_syncopdone:
5151
5152                 cm_SyncOpDone(scp, NULL, CM_SCACHESYNC_LOCK);
5153
5154             post_syncopdone:
5155                 lock_ReleaseWrite(&scp->rw);
5156
5157                 lock_ObtainWrite(&cm_scacheLock);
5158
5159                 if (code == 0) {
5160                     fileLock->lastUpdate = time(NULL);
5161                 }
5162                 
5163                 if (scp_done)
5164                     scp->lastRefreshCycle = cm_lockRefreshCycle;
5165
5166             } else {
5167                 /* we have already refreshed the locks on this scp */
5168                 fileLock->lastUpdate = time(NULL);
5169             }
5170
5171             cm_ReleaseSCacheNoLock(scp);
5172
5173         } else if (IS_LOCK_ACTIVE(fileLock) && IS_LOCK_CLIENTONLY(fileLock)) {
5174             /* TODO: Check callbacks */
5175         }
5176     }
5177
5178     lock_ReleaseWrite(&cm_scacheLock);
5179     osi_Log1(afsd_logp, "cm_CheckLocks completes lock check cycle %d", cm_lockRefreshCycle);
5180 }
5181
5182 /* NOT called with scp->rw held. */
5183 long cm_RetryLock(cm_file_lock_t *oldFileLock, int client_is_dead)
5184 {
5185     long code = 0;
5186     cm_scache_t *scp = NULL;
5187     cm_file_lock_t *fileLock;
5188     osi_queue_t *q;
5189     cm_req_t req;
5190     int newLock = -1;
5191     int force_client_lock = FALSE;
5192     int has_insert = FALSE;
5193     int check_data_version = FALSE;
5194
5195     cm_InitReq(&req);
5196
5197     if (client_is_dead) {
5198         code = CM_ERROR_TIMEDOUT;
5199         goto updateLock;
5200     }
5201
5202     lock_ObtainRead(&cm_scacheLock);
5203
5204     osi_Log2(afsd_logp, "cm_RetryLock checking lock %p (scp=%p)", oldFileLock, oldFileLock->scp);
5205     osi_Log4(afsd_logp, "    offset(%x:%x) length(%x:%x)",
5206              (unsigned)(oldFileLock->range.offset >> 32),
5207              (unsigned)(oldFileLock->range.offset & 0xffffffff),
5208              (unsigned)(oldFileLock->range.length >> 32),
5209              (unsigned)(oldFileLock->range.length & 0xffffffff));
5210     osi_Log3(afsd_logp, "    key(%x:%x) flags=%x",
5211              (unsigned)(oldFileLock->key >> 32),
5212              (unsigned)(oldFileLock->key & 0xffffffff),
5213              (unsigned)(oldFileLock->flags));
5214
5215     /* if the lock has already been granted, then we have nothing to do */
5216     if (IS_LOCK_ACTIVE(oldFileLock)) {
5217         lock_ReleaseRead(&cm_scacheLock);
5218         osi_Log0(afsd_logp, "cm_RetryLock lock already granted");
5219         return 0;
5220     }
5221
5222     /* we can't do anything with lost or deleted locks at the moment. */
5223     if (IS_LOCK_LOST(oldFileLock) || IS_LOCK_DELETED(oldFileLock)) {
5224         code = CM_ERROR_BADFD;
5225         osi_Log0(afsd_logp, "cm_RetryLock lock is lost or deleted");
5226         lock_ReleaseRead(&cm_scacheLock);
5227         goto updateLock;
5228     }
5229
5230     scp = oldFileLock->scp;
5231
5232     osi_assertx(scp != NULL, "null cm_scache_t");
5233
5234     lock_ReleaseRead(&cm_scacheLock);
5235     lock_ObtainWrite(&scp->rw);
5236
5237     code = cm_LockCheckPerms(scp, oldFileLock->lockType,
5238                              oldFileLock->userp,
5239                              &req, &has_insert);
5240
5241     if (code == CM_ERROR_NOACCESS && oldFileLock->lockType == LockRead) {
5242         if (!has_insert || !SCP_SUPPORTS_WRITELOCKACL(scp)) {
5243         force_client_lock = TRUE;
5244         }
5245         code = 0;
5246     } else if (code) {
5247         lock_ReleaseWrite(&scp->rw);
5248         return code;
5249     }
5250
5251     lock_ObtainWrite(&cm_scacheLock);
5252
5253     /* Check if we already have a sufficient server lock to allow this
5254        lock to go through. */
5255     if (IS_LOCK_WAITLOCK(oldFileLock) &&
5256         (!SERVERLOCKS_ENABLED(scp) ||
5257          scp->serverLock == oldFileLock->lockType ||
5258          scp->serverLock == LockWrite)) {
5259
5260         oldFileLock->flags &= ~CM_FILELOCK_FLAG_WAITLOCK;
5261
5262         if (SERVERLOCKS_ENABLED(scp)) {
5263             osi_Log1(afsd_logp, "cm_RetryLock Server lock (%d) is sufficient for lock.  Granting",
5264                      (int) scp->serverLock);
5265         } else {
5266             osi_Log0(afsd_logp, "cm_RetryLock skipping server lock for scp");
5267         }
5268
5269         lock_ReleaseWrite(&cm_scacheLock);
5270         lock_ReleaseWrite(&scp->rw);
5271
5272         return 0;
5273     }
5274
5275     if (IS_LOCK_WAITUNLOCK(oldFileLock)) {
5276
5277         /* check if the conflicting locks have dissappeared already */
5278         for (q = scp->fileLocksH; q; q = osi_QNext(q)) {
5279
5280             fileLock = (cm_file_lock_t *)
5281                 ((char *) q - offsetof(cm_file_lock_t, fileq));
5282
5283             if (IS_LOCK_LOST(fileLock)) {
5284                 if (fileLock->key == oldFileLock->key) {
5285                     code = CM_ERROR_BADFD;
5286                     oldFileLock->flags |= CM_FILELOCK_FLAG_LOST;
5287                     osi_Log1(afsd_logp, "    found lost lock %p for same key.  Marking lock as lost",
5288                              fileLock);
5289                     break;
5290                 } else if (fileLock->lockType == LockWrite &&
5291                            INTERSECT_RANGE(oldFileLock->range, fileLock->range)) {
5292                     osi_Log1(afsd_logp, "    found conflicting LOST lock %p", fileLock);
5293                     code = CM_ERROR_WOULDBLOCK;
5294                     break;
5295                 }
5296             }
5297
5298             if (IS_LOCK_ACCEPTED(fileLock) &&
5299                 INTERSECT_RANGE(oldFileLock->range, fileLock->range)) {
5300
5301                 if (oldFileLock->lockType != LockRead ||
5302                    fileLock->lockType != LockRead) {
5303
5304                     osi_Log1(afsd_logp, "    found conflicting lock %p", fileLock);
5305                     code = CM_ERROR_WOULDBLOCK;
5306                     break;
5307                 }
5308             }
5309         }
5310     }
5311
5312     if (code != 0) {
5313         lock_ReleaseWrite(&cm_scacheLock);
5314         lock_ReleaseWrite(&scp->rw);
5315
5316         goto handleCode;
5317     }
5318
5319     /* when we get here, the lock is either a WAITUNLOCK or WAITLOCK.
5320        If it is WAITUNLOCK, then we didn't find any conflicting lock
5321        but we haven't verfied whether the serverLock is sufficient to
5322        assert it.  If it is WAITLOCK, then the serverLock is
5323        insufficient to assert it. Eitherway, we are ready to accept
5324        the lock as either ACTIVE or WAITLOCK depending on the
5325        serverLock. */
5326
5327     /* First, promote the WAITUNLOCK to a WAITLOCK */
5328     if (IS_LOCK_WAITUNLOCK(oldFileLock)) {
5329         if (oldFileLock->lockType == LockRead)
5330             scp->sharedLocks++;
5331         else
5332             scp->exclusiveLocks++;
5333
5334         oldFileLock->flags &= ~CM_FILELOCK_FLAG_WAITUNLOCK;
5335         oldFileLock->flags |= CM_FILELOCK_FLAG_WAITLOCK;
5336     }
5337
5338     osi_assertx(IS_LOCK_WAITLOCK(oldFileLock), "!IS_LOCK_WAITLOCK");
5339
5340     if (force_client_lock ||
5341         !SERVERLOCKS_ENABLED(scp) ||
5342         scp->serverLock == oldFileLock->lockType ||
5343         (oldFileLock->lockType == LockRead &&
5344          scp->serverLock == LockWrite)) {
5345
5346         oldFileLock->flags &= ~CM_FILELOCK_FLAG_WAITLOCK;
5347
5348         if ((force_client_lock ||
5349              !SERVERLOCKS_ENABLED(scp)) &&
5350             !IS_LOCK_CLIENTONLY(oldFileLock)) {
5351
5352             oldFileLock->flags |= CM_FILELOCK_FLAG_CLIENTONLY;
5353
5354             if (oldFileLock->lockType == LockRead)
5355                 scp->sharedLocks--;
5356             else
5357                 scp->exclusiveLocks--;
5358
5359             scp->clientLocks++;
5360         }
5361
5362         lock_ReleaseWrite(&cm_scacheLock);
5363         lock_ReleaseWrite(&scp->rw);
5364
5365         return 0;
5366
5367     } else {
5368         cm_user_t * userp;
5369
5370         code = cm_SyncOp(scp, NULL, oldFileLock->userp, &req, 0,
5371                          CM_SCACHESYNC_NEEDCALLBACK
5372                          | CM_SCACHESYNC_GETSTATUS
5373                          | CM_SCACHESYNC_LOCK);
5374         if (code) {
5375             osi_Log1(afsd_logp, "cm_RetryLock SyncOp failure code 0x%x", code);
5376             lock_ReleaseWrite(&cm_scacheLock);
5377             goto post_syncopdone;
5378         }
5379
5380         if (!IS_LOCK_WAITLOCK(oldFileLock))
5381             goto pre_syncopdone;
5382
5383         userp = oldFileLock->userp;
5384
5385 #ifndef AGGRESSIVE_LOCKS
5386         newLock = oldFileLock->lockType;
5387 #else
5388         newLock = LockWrite;
5389 #endif
5390
5391         if (has_insert) {
5392             /* if has_insert is non-zero, then:
5393                - the lock a LockRead
5394                - we don't have permission to get a LockRead
5395                - we do have permission to get a LockWrite
5396                - the server supports VICED_CAPABILITY_WRITELOCKACL
5397             */
5398
5399             newLock = LockWrite;
5400         }
5401
5402         lock_ReleaseWrite(&cm_scacheLock);
5403
5404         /* when we get here, either we have a read-lock and want a
5405            write-lock or we don't have any locks and we want some
5406            lock. */
5407
5408         if (scp->serverLock == LockRead) {
5409
5410             osi_assertx(newLock == LockWrite, "!LockWrite");
5411
5412             osi_Log0(afsd_logp, "  Attempting to UPGRADE from LockRead to LockWrite");
5413
5414             scp->lockDataVersion = scp->dataVersion;
5415             check_data_version = TRUE;
5416
5417             code = cm_IntReleaseLock(scp, userp, &req);
5418
5419             if (code)
5420                 goto pre_syncopdone;
5421             else
5422                 scp->serverLock = -1;
5423         }
5424
5425         code = cm_IntSetLock(scp, userp, newLock, &req);
5426
5427         if (code == 0) {
5428             if (scp->dataVersion != scp->lockDataVersion) {
5429                 /* we lost a race.  too bad */
5430
5431                 osi_Log0(afsd_logp,
5432                          "  Data version mismatch while upgrading lock.");
5433                 osi_Log2(afsd_logp,
5434                          "  Data versions before=%I64d, after=%I64d",
5435                          scp->lockDataVersion,
5436                          scp->dataVersion);
5437                 osi_Log1(afsd_logp,
5438                          "  Releasing stale lock for scp 0x%x", scp);
5439
5440                 code = cm_IntReleaseLock(scp, userp, &req);
5441
5442                 scp->serverLock = -1;
5443
5444                 code = CM_ERROR_INVAL;
5445
5446                 cm_LockMarkSCacheLost(scp);
5447             } else {
5448                 scp->serverLock = newLock;
5449             }
5450         }
5451
5452     pre_syncopdone:
5453         cm_SyncOpDone(scp, NULL, CM_SCACHESYNC_LOCK);
5454     post_syncopdone:
5455         ;
5456     }
5457
5458   handleCode:
5459     if (code != 0 && code != CM_ERROR_WOULDBLOCK) {
5460         lock_ObtainWrite(&cm_scacheLock);
5461         if (scp->fileLocksT == &oldFileLock->fileq)
5462             scp->fileLocksT = osi_QPrev(&oldFileLock->fileq);
5463         osi_QRemoveHT(&scp->fileLocksH, &scp->fileLocksT, &oldFileLock->fileq);
5464         lock_ReleaseWrite(&cm_scacheLock);
5465     }
5466     lock_ReleaseWrite(&scp->rw);
5467
5468   updateLock:
5469     lock_ObtainWrite(&cm_scacheLock);
5470     if (code == 0) {
5471         oldFileLock->flags &= ~CM_FILELOCK_FLAG_WAITLOCK;
5472     } else if (code != CM_ERROR_WOULDBLOCK) {
5473         oldFileLock->flags |= CM_FILELOCK_FLAG_DELETED;
5474         cm_ReleaseUser(oldFileLock->userp);
5475         oldFileLock->userp = NULL;
5476         if (oldFileLock->scp) {
5477             cm_ReleaseSCacheNoLock(oldFileLock->scp);
5478             oldFileLock->scp = NULL;
5479         }
5480     }
5481     lock_ReleaseWrite(&cm_scacheLock);
5482
5483     return code;
5484 }
5485
5486 cm_key_t cm_GenerateKey(unsigned int session_id, unsigned long process_id, unsigned int file_id)
5487 {
5488 #ifdef DEBUG
5489     osi_assertx((process_id & 0xffffffff) == process_id, "unexpected process_id");
5490     osi_assertx((session_id & 0xffff) == session_id, "unexpected session_id");
5491     osi_assertx((file_id & 0xffff) == file_id, "unexpected file_id");
5492 #endif
5493
5494     return 
5495         (((cm_key_t) (process_id & 0xffffffff)) << 32) |
5496         (((cm_key_t) (session_id & 0xffff)) << 16) |
5497         (((cm_key_t) (file_id & 0xffff)));
5498 }
5499
5500 static int cm_KeyEquals(cm_key_t k1, cm_key_t k2, int flags)
5501 {
5502     if (flags & CM_UNLOCK_BY_FID) {
5503         return ((k1 & 0xffffffff) == (k2 & 0xffffffff));
5504     } else {
5505         return (k1 == k2);
5506     }
5507 }
5508
5509 void cm_ReleaseAllLocks(void)
5510 {
5511     cm_scache_t *scp;
5512     cm_req_t req;
5513     cm_user_t *userp;
5514     cm_key_t   key;
5515     cm_file_lock_t *fileLock;
5516     unsigned int i;
5517
5518     for (i = 0; i < cm_data.scacheHashTableSize; i++)
5519     {
5520         for ( scp = cm_data.scacheHashTablep[i]; scp; scp = scp->nextp ) {
5521             while (scp->fileLocksH != NULL) {
5522                 lock_ObtainWrite(&scp->rw);
5523                 lock_ObtainWrite(&cm_scacheLock);
5524                 if (!scp->fileLocksH) {
5525                     lock_ReleaseWrite(&cm_scacheLock);
5526                     lock_ReleaseWrite(&scp->rw);
5527                     break;
5528                 }
5529                 fileLock = (cm_file_lock_t *)((char *) scp->fileLocksH - offsetof(cm_file_lock_t, fileq));
5530                 userp = fileLock->userp;
5531                 cm_HoldUser(userp);
5532                 key = fileLock->key;
5533                 cm_HoldSCacheNoLock(scp);
5534                 lock_ReleaseWrite(&cm_scacheLock);
5535                 cm_UnlockByKey(scp, key, 0, userp, &req);
5536                 cm_ReleaseSCache(scp);
5537                 cm_ReleaseUser(userp);
5538                 lock_ReleaseWrite(&scp->rw);
5539             }
5540         }
5541     }
5542 }