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