2 * Copyright 2000, International Business Machines Corporation and others.
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
10 #include <afs/param.h>
27 extern void afsi_log(char *pattern, ...);
30 int cm_enableServerLocks = 1;
32 int cm_followBackupPath = 0;
35 * Case-folding array. This was constructed by inspecting of SMBtrace output.
36 * I do not know anything more about it.
38 unsigned char cm_foldUpper[256] = {
39 0x0, 0x1, 0x2, 0x3, 0x4, 0x5, 0x6, 0x7,
40 0x8, 0x9, 0xa, 0xb, 0xc, 0xd, 0xe, 0xf,
41 0x10, 0x11, 0x12, 0x13, 0x14, 0x15, 0x16, 0x17,
42 0x18, 0x19, 0x1a, 0x1b, 0x1c, 0x1d, 0x1e, 0x1f,
43 0x20, 0x21, 0x22, 0x23, 0x24, 0x25, 0x26, 0x27,
44 0x28, 0x29, 0x2a, 0x2b, 0x2c, 0x2d, 0x2e, 0x2f,
45 0x30, 0x31, 0x32, 0x33, 0x34, 0x35, 0x36, 0x37,
46 0x38, 0x39, 0x3a, 0x3b, 0x3c, 0x3d, 0x3e, 0x3f,
47 0x40, 0x41, 0x42, 0x43, 0x44, 0x45, 0x46, 0x47,
48 0x48, 0x49, 0x4a, 0x4b, 0x4c, 0x4d, 0x4e, 0x4f,
49 0x50, 0x51, 0x52, 0x53, 0x54, 0x55, 0x56, 0x57,
50 0x58, 0x59, 0x5a, 0x5b, 0x5c, 0x5d, 0x5e, 0x5f,
51 0x60, 0x41, 0x42, 0x43, 0x44, 0x45, 0x46, 0x47,
52 0x48, 0x49, 0x4a, 0x4b, 0x4c, 0x4d, 0x4e, 0x4f,
53 0x50, 0x51, 0x52, 0x53, 0x54, 0x55, 0x56, 0x57,
54 0x58, 0x59, 0x5a, 0x7b, 0x7c, 0x7d, 0x7e, 0x7f,
55 0x80, 0x9a, 0x90, 0x41, 0x8e, 0x41, 0x8f, 0x80,
56 0x45, 0x45, 0x45, 0x49, 0x49, 0x49, 0x8e, 0x8f,
57 0x90, 0x92, 0x92, 0x4f, 0x99, 0x4f, 0x55, 0x55,
58 0x59, 0x99, 0x9a, 0x9b, 0x9c, 0x9d, 0x9e, 0x9f,
59 0x41, 0x49, 0x4f, 0x55, 0xa5, 0xa5, 0x56, 0xa7,
60 0xa8, 0xa9, 0xaa, 0xab, 0xac, 0xad, 0xae, 0xaf,
61 0xb0, 0xb1, 0xb2, 0xb3, 0xb4, 0xb5, 0xb6, 0xb7,
62 0xb8, 0xb9, 0xba, 0xbb, 0xbc, 0xbd, 0xbe, 0xbf,
63 0xc0, 0xc1, 0xc2, 0xc3, 0xc4, 0xc5, 0xc6, 0xc7,
64 0xc8, 0xc9, 0xca, 0xcb, 0xcc, 0xcd, 0xce, 0xcf,
65 0xd0, 0xd1, 0xd2, 0xd3, 0xd4, 0xd5, 0xd6, 0xd7,
66 0xd8, 0xd9, 0xda, 0xdb, 0xdc, 0xdd, 0xde, 0xdf,
67 0xe0, 0xe1, 0xe2, 0xe3, 0xe4, 0xe5, 0xe6, 0xe7,
68 0xe8, 0xe9, 0xea, 0xeb, 0xec, 0xed, 0xee, 0xef,
69 0xf0, 0xf1, 0xf2, 0xf3, 0xf4, 0xf5, 0xf6, 0xf7,
70 0xf8, 0xf9, 0xfa, 0xfb, 0xfc, 0xfd, 0xfe, 0xff
74 * Case-insensitive string comparison. We used to use stricmp, but it doesn't
75 * know about 8-bit characters (e.g. 129 is lowercase u-umlaut, 154 is
76 * upper-case u-umlaut).
78 int cm_stricmp(const char *str1, const char *str2)
90 c1 = (char) cm_foldUpper[(unsigned char)(*str1++)];
91 c2 = (char) cm_foldUpper[(unsigned char)(*str2++)];
99 /* characters that are legal in an 8.3 name */
101 * We used to have 1's for all characters from 128 to 254. But
102 * the NT client behaves better if we create an 8.3 name for any
103 * name that has a character with the high bit on, and if we
104 * delete those characters from 8.3 names. In particular, see
105 * Sybase defect 10859.
107 char cm_LegalChars[256] = {
108 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
109 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
110 0, 1, 0, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 1, 0, 0,
111 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0,
112 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,
113 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 1, 1,
114 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,
115 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 1, 1, 1,
116 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
117 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
118 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
119 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
120 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
121 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
122 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
123 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0
126 /* return true iff component is a valid 8.3 name */
127 int cm_Is8Dot3(char *namep)
134 * can't have a leading dot;
135 * special case for . and ..
137 if (namep[0] == '.') {
140 if (namep[1] == '.' && namep[2] == 0)
144 while (tc = *namep++) {
146 /* saw another dot */
147 if (sawDot) return 0; /* second dot */
152 if (cm_LegalChars[tc] == 0)
155 if (!sawDot && charCount > 8)
156 /* more than 8 chars in name */
158 if (sawDot && charCount > 3)
159 /* more than 3 chars in extension */
166 * Number unparsing map for generating 8.3 names;
167 * The version taken from DFS was on drugs.
168 * You can't include '&' and '@' in a file name.
170 char cm_8Dot3Mapping[42] =
171 {'0', '1', '2', '3', '4', '5', '6', '7', '8', '9',
172 'A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'J', 'K',
173 'L', 'M', 'N', 'O', 'P', 'Q', 'R', 'S', 'T', 'U',
174 'V', 'W', 'X', 'Y', 'Z', '_', '-', '$', '#', '!', '+', '='
176 int cm_8Dot3MapSize = sizeof(cm_8Dot3Mapping);
178 void cm_Gen8Dot3NameInt(const char * longname, cm_dirFid_t * pfid,
179 char *shortName, char **shortNameEndp)
183 int vnode = ntohl(pfid->vnode);
185 int validExtension = 0;
189 /* Unparse the file's vnode number to get a "uniquifier" */
191 number[nsize] = cm_8Dot3Mapping[vnode % cm_8Dot3MapSize];
193 vnode /= cm_8Dot3MapSize;
197 * Look for valid extension. There has to be a dot, and
198 * at least one of the characters following has to be legal.
200 lastDot = strrchr(longname, '.');
202 temp = lastDot; temp++;
204 if (cm_LegalChars[tc])
210 /* Copy name characters */
211 for (i = 0, name = longname;
212 i < (7 - nsize) && name != lastDot; ) {
217 if (!cm_LegalChars[tc])
220 *shortName++ = toupper(tc);
226 /* Copy uniquifier characters */
227 memcpy(shortName, number, nsize);
230 if (validExtension) {
231 /* Copy extension characters */
232 *shortName++ = *lastDot++; /* copy dot */
233 for (i = 0, tc = *lastDot++;
236 if (cm_LegalChars[tc]) {
238 *shortName++ = toupper(tc);
247 *shortNameEndp = shortName;
250 /* return success if we can open this file in this mode */
251 long cm_CheckOpen(cm_scache_t *scp, int openMode, int trunc, cm_user_t *userp,
259 rights |= PRSFS_READ;
260 if (openMode == 1 || openMode == 2 || trunc)
261 rights |= PRSFS_WRITE;
263 lock_ObtainWrite(&scp->rw);
265 code = cm_SyncOp(scp, NULL, userp, reqp, rights,
266 CM_SCACHESYNC_GETSTATUS
267 | CM_SCACHESYNC_NEEDCALLBACK
268 | CM_SCACHESYNC_LOCK);
271 ((rights & PRSFS_WRITE) || (rights & PRSFS_READ)) &&
272 scp->fileType == CM_SCACHETYPE_FILE) {
275 unsigned int sLockType;
276 LARGE_INTEGER LOffset, LLength;
278 /* Check if there's some sort of lock on the file at the
281 key = cm_GenerateKey(CM_SESSION_CMINT,0,0);
283 if (rights & PRSFS_WRITE)
286 sLockType = LOCKING_ANDX_SHARED_LOCK;
288 LOffset.HighPart = CM_FLSHARE_OFFSET_HIGH;
289 LOffset.LowPart = CM_FLSHARE_OFFSET_LOW;
290 LLength.HighPart = CM_FLSHARE_LENGTH_HIGH;
291 LLength.LowPart = CM_FLSHARE_LENGTH_LOW;
293 code = cm_Lock(scp, sLockType, LOffset, LLength, key, 0, userp, reqp, NULL);
296 cm_Unlock(scp, sLockType, LOffset, LLength, key, userp, reqp);
298 /* In this case, we allow the file open to go through even
299 though we can't enforce mandatory locking on the
301 if (code == CM_ERROR_NOACCESS &&
302 !(rights & PRSFS_WRITE))
306 case CM_ERROR_ALLOFFLINE:
307 case CM_ERROR_ALLDOWN:
308 case CM_ERROR_ALLBUSY:
309 case CM_ERROR_TIMEDOUT:
311 case CM_ERROR_WOULDBLOCK:
314 code = CM_ERROR_SHARING_VIOLATION;
319 } else if (code != 0) {
323 cm_SyncOpDone(scp, NULL, CM_SCACHESYNC_LOCK);
327 lock_ReleaseWrite(&scp->rw);
332 /* return success if we can open this file in this mode */
333 long cm_CheckNTOpen(cm_scache_t *scp, unsigned int desiredAccess,
334 unsigned int createDisp, cm_user_t *userp, cm_req_t *reqp,
335 cm_lock_data_t **ldpp)
340 osi_assertx(ldpp != NULL, "null cm_lock_data_t");
343 /* Always allow delete; the RPC will tell us if it's OK */
344 if (desiredAccess == DELETE)
349 if (desiredAccess & (AFS_ACCESS_READ|AFS_ACCESS_EXECUTE))
350 rights |= (scp->fileType == CM_SCACHETYPE_DIRECTORY ? PRSFS_LOOKUP : PRSFS_READ);
352 /* We used to require PRSFS_WRITE if createDisp was 4
353 (OPEN_ALWAYS) even if AFS_ACCESS_WRITE was not requested.
354 However, we don't need to do that since the existence of the
355 scp implies that we don't need to create it. */
356 if (desiredAccess & AFS_ACCESS_WRITE)
357 rights |= PRSFS_WRITE;
359 lock_ObtainWrite(&scp->rw);
361 code = cm_SyncOp(scp, NULL, userp, reqp, rights,
362 CM_SCACHESYNC_GETSTATUS
363 | CM_SCACHESYNC_NEEDCALLBACK
364 | CM_SCACHESYNC_LOCK);
367 * If the open will fail because the volume is readonly, then we will
368 * return an access denied error instead. This is to help brain-dead
369 * apps run correctly on replicated volumes.
370 * See defect 10007 for more information.
372 if (code == CM_ERROR_READONLY)
373 code = CM_ERROR_NOACCESS;
376 ((rights & PRSFS_WRITE) || (rights & PRSFS_READ)) &&
377 scp->fileType == CM_SCACHETYPE_FILE) {
379 unsigned int sLockType;
380 LARGE_INTEGER LOffset, LLength;
382 /* Check if there's some sort of lock on the file at the
385 key = cm_GenerateKey(CM_SESSION_CMINT,0,0);
386 if (rights & PRSFS_WRITE)
389 sLockType = LOCKING_ANDX_SHARED_LOCK;
391 /* single byte lock at offset 0x0100 0000 0000 0000 */
392 LOffset.HighPart = CM_FLSHARE_OFFSET_HIGH;
393 LOffset.LowPart = CM_FLSHARE_OFFSET_LOW;
394 LLength.HighPart = CM_FLSHARE_LENGTH_HIGH;
395 LLength.LowPart = CM_FLSHARE_LENGTH_LOW;
397 code = cm_Lock(scp, sLockType, LOffset, LLength, key, 0, userp, reqp, NULL);
400 (*ldpp) = (cm_lock_data_t *)malloc(sizeof(cm_lock_data_t));
407 (*ldpp)->sLockType = sLockType;
408 (*ldpp)->LOffset.HighPart = LOffset.HighPart;
409 (*ldpp)->LOffset.LowPart = LOffset.LowPart;
410 (*ldpp)->LLength.HighPart = LLength.HighPart;
411 (*ldpp)->LLength.LowPart = LLength.LowPart;
413 /* In this case, we allow the file open to go through even
414 though we can't enforce mandatory locking on the
416 if (code == CM_ERROR_NOACCESS &&
417 !(rights & PRSFS_WRITE))
421 case CM_ERROR_ALLOFFLINE:
422 case CM_ERROR_ALLDOWN:
423 case CM_ERROR_ALLBUSY:
424 case CM_ERROR_TIMEDOUT:
426 case CM_ERROR_WOULDBLOCK:
429 code = CM_ERROR_SHARING_VIOLATION;
433 } else if (code != 0) {
438 cm_SyncOpDone(scp, NULL, CM_SCACHESYNC_LOCK);
441 lock_ReleaseWrite(&scp->rw);
443 osi_Log3(afsd_logp,"cm_CheckNTOpen scp 0x%p ldp 0x%p code 0x%x", scp, *ldpp, code);
447 extern long cm_CheckNTOpenDone(cm_scache_t *scp, cm_user_t *userp, cm_req_t *reqp,
448 cm_lock_data_t ** ldpp)
450 osi_Log2(afsd_logp,"cm_CheckNTOpenDone scp 0x%p ldp 0x%p", scp, *ldpp);
452 lock_ObtainWrite(&scp->rw);
453 cm_Unlock(scp, (*ldpp)->sLockType, (*ldpp)->LOffset, (*ldpp)->LLength,
454 (*ldpp)->key, userp, reqp);
455 lock_ReleaseWrite(&scp->rw);
462 * When CAP_NT_SMBS has been negotiated, deletion (of files or directories) is
463 * done in three steps:
464 * (1) open for deletion (NT_CREATE_AND_X)
465 * (2) set for deletion on close (NT_TRANSACTION2, SET_FILE_INFO)
467 * We must not do the RPC until step 3. But if we are going to return an error
468 * code (e.g. directory not empty), we must return it by step 2, otherwise most
469 * clients will not notice it. So we do a preliminary check. For deleting
470 * files, this is almost free, since we have already done the RPC to get the
471 * parent directory's status bits. But for deleting directories, we must do an
472 * additional RPC to get the directory's data to check if it is empty. Sigh.
474 long cm_CheckNTDelete(cm_scache_t *dscp, cm_scache_t *scp, cm_user_t *userp,
480 cm_dirEntry_t *dep = 0;
481 unsigned short *hashTable;
483 int BeyondPage = 0, HaveDot = 0, HaveDotDot = 0;
486 /* First check permissions */
487 lock_ObtainWrite(&scp->rw);
488 code = cm_SyncOp(scp, NULL, userp, reqp, PRSFS_DELETE,
489 CM_SCACHESYNC_GETSTATUS | CM_SCACHESYNC_NEEDCALLBACK);
490 cm_SyncOpDone(scp, NULL, CM_SCACHESYNC_NEEDCALLBACK | CM_SCACHESYNC_GETSTATUS);
491 lock_ReleaseWrite(&scp->rw);
495 /* If deleting directory, must be empty */
497 if (scp->fileType != CM_SCACHETYPE_DIRECTORY)
500 thyper.HighPart = 0; thyper.LowPart = 0;
501 code = buf_Get(scp, &thyper, &bufferp);
505 lock_ObtainMutex(&bufferp->mx);
506 lock_ObtainWrite(&scp->rw);
509 code = cm_SyncOp(scp, bufferp, userp, reqp, 0,
510 CM_SCACHESYNC_NEEDCALLBACK
512 | CM_SCACHESYNC_BUFLOCKED);
516 if (cm_HaveBuffer(scp, bufferp, 1))
519 /* otherwise, load the buffer and try again */
520 lock_ReleaseMutex(&bufferp->mx);
521 code = cm_GetBuffer(scp, bufferp, NULL, userp, reqp);
522 lock_ReleaseWrite(&scp->rw);
523 lock_ObtainMutex(&bufferp->mx);
524 lock_ObtainWrite(&scp->rw);
525 cm_SyncOpDone(scp, bufferp, CM_SCACHESYNC_NEEDCALLBACK | CM_SCACHESYNC_READ | CM_SCACHESYNC_BUFLOCKED);
530 lock_ReleaseWrite(&scp->rw);
533 /* We try to determine emptiness without looking beyond the first page,
534 * and without assuming "." and ".." are present and are on the first
535 * page (though these assumptions might, after all, be reasonable).
537 hashTable = (unsigned short *)(bufferp->datap + (32 * 5));
538 for (i=0; i<128; i++) {
539 idx = ntohs(hashTable[i]);
545 dep = (cm_dirEntry_t *)(bufferp->datap + (32 * idx));
546 if (strcmp(dep->name, ".") == 0)
548 else if (strcmp(dep->name, "..") == 0)
551 code = CM_ERROR_NOTEMPTY;
554 idx = ntohs(dep->next);
557 if (BeyondPage && HaveDot && HaveDotDot)
558 code = CM_ERROR_NOTEMPTY;
562 lock_ReleaseMutex(&bufferp->mx);
563 buf_Release(bufferp);
565 lock_ReleaseWrite(&scp->rw);
570 * Iterate through all entries in a directory.
571 * When the function funcp is called, the buffer is locked but the
572 * directory vnode is not.
574 * If the retscp parameter is not NULL, the parmp must be a
575 * cm_lookupSearch_t object.
577 long cm_ApplyDir(cm_scache_t *scp, cm_DirFuncp_t funcp, void *parmp,
578 osi_hyper_t *startOffsetp, cm_user_t *userp, cm_req_t *reqp,
579 cm_scache_t **retscp)
583 cm_dirEntry_t *dep = 0;
586 osi_hyper_t dirLength;
587 osi_hyper_t bufferOffset;
588 osi_hyper_t curOffset;
592 cm_pageHeader_t *pageHeaderp;
594 long nextEntryCookie;
595 int numDirChunks; /* # of 32 byte dir chunks in this entry */
597 /* get the directory size */
598 lock_ObtainWrite(&scp->rw);
599 code = cm_SyncOp(scp, NULL, userp, reqp, PRSFS_LOOKUP,
600 CM_SCACHESYNC_NEEDCALLBACK | CM_SCACHESYNC_GETSTATUS);
601 lock_ReleaseWrite(&scp->rw);
605 if (scp->fileType != CM_SCACHETYPE_DIRECTORY)
606 return CM_ERROR_NOTDIR;
608 if (retscp) /* if this is a lookup call */
610 cm_lookupSearch_t* sp = parmp;
613 #ifdef AFS_FREELANCE_CLIENT
614 /* Freelance entries never end up in the DNLC because they
615 * do not have an associated cm_server_t
617 !(cm_freelanceEnabled &&
618 sp->fid.cell==AFS_FAKE_ROOT_CELL_ID &&
619 sp->fid.volume==AFS_FAKE_ROOT_VOL_ID )
620 #else /* !AFS_FREELANCE_CLIENT */
625 int casefold = sp->caseFold;
626 sp->caseFold = 0; /* we have a strong preference for exact matches */
627 if ( *retscp = cm_dnlcLookup(scp, sp)) /* dnlc hit */
629 sp->caseFold = casefold;
632 sp->caseFold = casefold;
634 /* see if we can find it using the directory hash tables.
635 we can only do exact matches, since the hash is case
645 code = cm_BeginDirOp(scp, userp, reqp, CM_DIRLOCK_READ, &dirop);
649 code = cm_BPlusDirLookup(&dirop, sp->searchNamep, &sp->fid);
654 code = cm_DirLookup(&dirop, sp->searchNamep, &sp->fid);
662 sp->ExactFound = TRUE;
663 *retscp = NULL; /* force caller to call cm_GetSCache() */
668 if (sp->caseFold && code == CM_ERROR_INEXACT_MATCH) {
671 sp->ExactFound = FALSE;
672 *retscp = NULL; /* force caller to call cm_GetSCache() */
676 return CM_ERROR_BPLUS_NOMATCH;
684 * XXX We only get the length once. It might change when we drop the
687 dirLength = scp->length;
690 bufferOffset.LowPart = bufferOffset.HighPart = 0;
692 curOffset = *startOffsetp;
694 curOffset.HighPart = 0;
695 curOffset.LowPart = 0;
699 /* make sure that curOffset.LowPart doesn't point to the first
700 * 32 bytes in the 2nd through last dir page, and that it
701 * doesn't point at the first 13 32-byte chunks in the first
702 * dir page, since those are dir and page headers, and don't
703 * contain useful information.
705 temp = curOffset.LowPart & (2048-1);
706 if (curOffset.HighPart == 0 && curOffset.LowPart < 2048) {
707 /* we're in the first page */
708 if (temp < 13*32) temp = 13*32;
711 /* we're in a later dir page */
712 if (temp < 32) temp = 32;
715 /* make sure the low order 5 bits are zero */
718 /* now put temp bits back ito curOffset.LowPart */
719 curOffset.LowPart &= ~(2048-1);
720 curOffset.LowPart |= temp;
722 /* check if we've passed the dir's EOF */
723 if (LargeIntegerGreaterThanOrEqualTo(curOffset, dirLength))
726 /* see if we can use the bufferp we have now; compute in which
727 * page the current offset would be, and check whether that's
728 * the offset of the buffer we have. If not, get the buffer.
730 thyper.HighPart = curOffset.HighPart;
731 thyper.LowPart = curOffset.LowPart & ~(cm_data.buf_blockSize-1);
732 if (!bufferp || !LargeIntegerEqualTo(thyper, bufferOffset)) {
735 lock_ReleaseMutex(&bufferp->mx);
736 buf_Release(bufferp);
740 code = buf_Get(scp, &thyper, &bufferp);
742 /* if buf_Get() fails we do not have a buffer object to lock */
748 /* for the IFS version, we bulkstat the dirents because this
749 routine is used in place of smb_ReceiveCoreSearchDir. our
750 other option is to modify smb_ReceiveCoreSearchDir itself,
751 but this seems to be the proper use for cm_ApplyDir. */
752 lock_ObtainWrite(&scp->rw);
753 if ((scp->flags & CM_SCACHEFLAG_BULKSTATTING) == 0
754 && (scp->bulkStatProgress.QuadPart <= thyper.QuadPart))
756 scp->flags |= CM_SCACHEFLAG_BULKSTATTING;
757 code = cm_TryBulkStat(scp, &thyper, userp, reqp);
758 scp->flags &= ~CM_SCACHEFLAG_BULKSTATTING;
759 scp->bulkStatProgress = thyper;
761 lock_ReleaseWrite(&scp->rw);
764 lock_ObtainMutex(&bufferp->mx);
765 bufferOffset = thyper;
767 /* now get the data in the cache */
769 lock_ObtainWrite(&scp->rw);
770 code = cm_SyncOp(scp, bufferp, userp, reqp,
772 CM_SCACHESYNC_NEEDCALLBACK
774 | CM_SCACHESYNC_BUFLOCKED);
776 lock_ReleaseWrite(&scp->rw);
779 cm_SyncOpDone(scp, bufferp, CM_SCACHESYNC_NEEDCALLBACK | CM_SCACHESYNC_READ | CM_SCACHESYNC_BUFLOCKED);
781 if (cm_HaveBuffer(scp, bufferp, 1)) {
782 lock_ReleaseWrite(&scp->rw);
786 /* otherwise, load the buffer and try again */
787 lock_ReleaseMutex(&bufferp->mx);
788 code = cm_GetBuffer(scp, bufferp, NULL, userp,
790 lock_ReleaseWrite(&scp->rw);
791 lock_ObtainMutex(&bufferp->mx);
796 lock_ReleaseMutex(&bufferp->mx);
797 buf_Release(bufferp);
801 } /* if (wrong buffer) ... */
803 /* now we have the buffer containing the entry we're interested
804 * in; copy it out if it represents a non-deleted entry.
806 entryInDir = curOffset.LowPart & (2048-1);
807 entryInBuffer = curOffset.LowPart & (cm_data.buf_blockSize - 1);
809 /* page header will help tell us which entries are free. Page
810 * header can change more often than once per buffer, since
811 * AFS 3 dir page size may be less than (but not more than) a
812 * buffer package buffer.
814 /* only look intra-buffer */
815 temp = curOffset.LowPart & (cm_data.buf_blockSize - 1);
816 temp &= ~(2048 - 1); /* turn off intra-page bits */
817 pageHeaderp = (cm_pageHeader_t *) (bufferp->datap + temp);
819 /* now determine which entry we're looking at in the page. If
820 * it is free (there's a free bitmap at the start of the dir),
821 * we should skip these 32 bytes.
823 slotInPage = (entryInDir & 0x7e0) >> 5;
824 if (!(pageHeaderp->freeBitmap[slotInPage>>3]
825 & (1 << (slotInPage & 0x7)))) {
826 /* this entry is free */
827 numDirChunks = 1; /* only skip this guy */
831 tp = bufferp->datap + entryInBuffer;
832 dep = (cm_dirEntry_t *) tp; /* now points to AFS3 dir entry */
834 /* while we're here, compute the next entry's location, too,
835 * since we'll need it when writing out the cookie into the
836 * dir listing stream.
838 numDirChunks = cm_NameEntries(dep->name, NULL);
840 /* compute the offset of the cookie representing the next entry */
841 nextEntryCookie = curOffset.LowPart
842 + (CM_DIR_CHUNKSIZE * numDirChunks);
844 if (dep->fid.vnode != 0) {
845 /* this is one of the entries to use: it is not deleted */
846 code = (*funcp)(scp, dep, parmp, &curOffset);
849 } /* if we're including this name */
852 /* and adjust curOffset to be where the new cookie is */
854 thyper.LowPart = CM_DIR_CHUNKSIZE * numDirChunks;
855 curOffset = LargeIntegerAdd(thyper, curOffset);
856 } /* while copying data for dir listing */
858 /* release the mutex */
860 lock_ReleaseMutex(&bufferp->mx);
861 buf_Release(bufferp);
866 int cm_NoneUpper(char *s)
870 if (c >= 'A' && c <= 'Z')
875 int cm_NoneLower(char *s)
879 if (c >= 'a' && c <= 'z')
884 long cm_LookupSearchProc(cm_scache_t *scp, cm_dirEntry_t *dep, void *rockp,
887 cm_lookupSearch_t *sp;
892 sp = (cm_lookupSearch_t *) rockp;
894 matchName = dep->name;
896 match = cm_stricmp(matchName, sp->searchNamep);
898 match = strcmp(matchName, sp->searchNamep);
902 && !cm_Is8Dot3(dep->name)) {
903 matchName = shortName;
904 cm_Gen8Dot3Name(dep, shortName, NULL);
906 match = cm_stricmp(matchName, sp->searchNamep);
908 match = strcmp(matchName, sp->searchNamep);
918 if (!sp->caseFold || matchName == shortName) {
919 sp->fid.vnode = ntohl(dep->fid.vnode);
920 sp->fid.unique = ntohl(dep->fid.unique);
921 return CM_ERROR_STOPNOW;
925 * If we get here, we are doing a case-insensitive search, and we
926 * have found a match. Now we determine what kind of match it is:
927 * exact, lower-case, upper-case, or none of the above. This is done
928 * in order to choose among matches, if there are more than one.
931 /* Exact matches are the best. */
932 match = strcmp(matchName, sp->searchNamep);
935 sp->fid.vnode = ntohl(dep->fid.vnode);
936 sp->fid.unique = ntohl(dep->fid.unique);
937 return CM_ERROR_STOPNOW;
940 /* Lower-case matches are next. */
943 if (cm_NoneUpper(matchName)) {
948 /* Upper-case matches are next. */
951 if (cm_NoneLower(matchName)) {
956 /* General matches are last. */
962 sp->fid.vnode = ntohl(dep->fid.vnode);
963 sp->fid.unique = ntohl(dep->fid.unique);
967 /* read the contents of a mount point into the appropriate string.
968 * called with write locked scp, and returns with locked scp.
970 long cm_ReadMountPoint(cm_scache_t *scp, cm_user_t *userp, cm_req_t *reqp)
977 if (scp->mountPointStringp[0])
980 /* otherwise, we have to read it in */
981 lock_ReleaseWrite(&scp->rw);
983 thyper.LowPart = thyper.HighPart = 0;
984 code = buf_Get(scp, &thyper, &bufp);
986 lock_ObtainWrite(&scp->rw);
991 code = cm_SyncOp(scp, bufp, userp, reqp, 0,
992 CM_SCACHESYNC_READ | CM_SCACHESYNC_NEEDCALLBACK);
996 cm_SyncOpDone(scp, bufp, CM_SCACHESYNC_NEEDCALLBACK | CM_SCACHESYNC_READ);
998 if (cm_HaveBuffer(scp, bufp, 0))
1001 /* otherwise load buffer */
1002 code = cm_GetBuffer(scp, bufp, NULL, userp, reqp);
1006 /* locked, has callback, has valid data in buffer */
1007 if ((tlen = scp->length.LowPart) > MOUNTPOINTLEN - 1)
1008 return CM_ERROR_TOOBIG;
1010 code = CM_ERROR_INVAL;
1014 /* someone else did the work while we were out */
1015 if (scp->mountPointStringp[0]) {
1020 /* otherwise, copy out the link */
1021 memcpy(scp->mountPointStringp, bufp->datap, tlen);
1023 /* now make it null-terminated. Note that the original contents of a
1024 * link that is a mount point is "#volname." where "." is there just to
1025 * be turned into a null. That is, we can trash the last char of the
1026 * link without damaging the vol name. This is a stupid convention,
1027 * but that's the protocol.
1029 scp->mountPointStringp[tlen-1] = 0;
1039 /* called with a locked scp and chases the mount point, yielding outScpp.
1040 * scp remains write locked, just for simplicity of describing the interface.
1042 long cm_FollowMountPoint(cm_scache_t *scp, cm_scache_t *dscp, cm_user_t *userp,
1043 cm_req_t *reqp, cm_scache_t **outScpp)
1051 cm_volume_t *volp = NULL;
1058 if (scp->mountRootFid.cell != 0 && scp->mountRootGen >= cm_data.mountRootGen) {
1059 tfid = scp->mountRootFid;
1060 lock_ReleaseWrite(&scp->rw);
1061 code = cm_GetSCache(&tfid, outScpp, userp, reqp);
1062 lock_ObtainWrite(&scp->rw);
1066 /* parse the volume name */
1067 mpNamep = scp->mountPointStringp;
1069 return CM_ERROR_NOSUCHPATH;
1070 tlen = (int)strlen(scp->mountPointStringp);
1071 mtType = *scp->mountPointStringp;
1072 cellNamep = malloc(tlen);
1073 volNamep = malloc(tlen);
1075 cp = strrchr(mpNamep, ':');
1077 /* cellular mount point */
1078 memset(cellNamep, 0, tlen);
1079 strncpy(cellNamep, mpNamep+1, cp - mpNamep - 1);
1080 strcpy(volNamep, cp+1);
1081 /* now look up the cell */
1082 lock_ReleaseWrite(&scp->rw);
1083 cellp = cm_GetCell(cellNamep, CM_FLAG_CREATE);
1084 lock_ObtainWrite(&scp->rw);
1088 strcpy(volNamep, mpNamep+1);
1090 cellp = cm_FindCellByID(scp->fid.cell, 0);
1094 code = CM_ERROR_NOSUCHCELL;
1098 vnLength = strlen(volNamep);
1099 if (vnLength >= 8 && strcmp(volNamep + vnLength - 7, ".backup") == 0)
1100 targetType = BACKVOL;
1101 else if (vnLength >= 10
1102 && strcmp(volNamep + vnLength - 9, ".readonly") == 0)
1107 /* check for backups within backups */
1108 if (targetType == BACKVOL
1109 && (scp->flags & (CM_SCACHEFLAG_RO | CM_SCACHEFLAG_PURERO))
1110 == CM_SCACHEFLAG_RO) {
1111 code = CM_ERROR_NOSUCHVOLUME;
1115 /* now we need to get the volume */
1116 lock_ReleaseWrite(&scp->rw);
1117 if (cm_VolNameIsID(volNamep)) {
1118 code = cm_GetVolumeByID(cellp, atoi(volNamep), userp, reqp,
1119 CM_GETVOL_FLAG_CREATE, &volp);
1121 code = cm_GetVolumeByName(cellp, volNamep, userp, reqp,
1122 CM_GETVOL_FLAG_CREATE, &volp);
1124 lock_ObtainWrite(&scp->rw);
1127 afs_uint32 cell, volume;
1129 /* save the parent of the volume root for this is the
1130 * place where the volume is mounted and we must remember
1131 * this in the volume structure rather than just in the
1132 * scache entry lest the scache entry gets recycled
1135 lock_ObtainMutex(&volp->mx);
1136 volp->dotdotFid = dscp->fid;
1137 lock_ReleaseMutex(&volp->mx);
1139 cell = cellp->cellID;
1141 /* if the mt pt originates in a .backup volume (not a .readonly)
1142 * and FollowBackupPath is active, and if there is a .backup
1143 * volume for the target, then use the .backup of the target
1144 * instead of the read-write.
1146 if (cm_followBackupPath &&
1148 (dscp->flags & (CM_SCACHEFLAG_RO|CM_SCACHEFLAG_PURERO)) == CM_SCACHEFLAG_RO &&
1149 (targetType == RWVOL || targetType == ROVOL && volp->ro.ID == 0)
1151 targetType = BACKVOL;
1153 /* if the mt pt is in a read-only volume (not just a
1154 * backup), and if there is a read-only volume for the
1155 * target, and if this is a targetType '#' mount point, use
1156 * the read-only, otherwise use the one specified.
1158 else if (mtType == '#' && targetType == RWVOL &&
1159 (scp->flags & CM_SCACHEFLAG_PURERO) &&
1163 if (targetType == ROVOL)
1164 volume = volp->ro.ID;
1165 else if (targetType == BACKVOL)
1166 volume = volp->bk.ID;
1168 volume = volp->rw.ID;
1170 /* the rest of the fid is a magic number */
1171 cm_SetFid(&scp->mountRootFid, cell, volume, 1, 1);
1172 scp->mountRootGen = cm_data.mountRootGen;
1174 tfid = scp->mountRootFid;
1175 lock_ReleaseWrite(&scp->rw);
1176 code = cm_GetSCache(&tfid, outScpp, userp, reqp);
1177 lock_ObtainWrite(&scp->rw);
1188 long cm_LookupInternal(cm_scache_t *dscp, char *namep, long flags, cm_user_t *userp,
1189 cm_req_t *reqp, cm_scache_t **outpScpp)
1192 int dnlcHit = 1; /* did we hit in the dnlc? yes, we did */
1193 cm_scache_t *tscp = NULL;
1194 cm_scache_t *mountedScp;
1195 cm_lookupSearch_t rock;
1198 memset(&rock, 0, sizeof(rock));
1200 if (dscp->fid.vnode == 1 && dscp->fid.unique == 1
1201 && strcmp(namep, "..") == 0) {
1202 if (dscp->dotdotFid.volume == 0)
1203 return CM_ERROR_NOSUCHVOLUME;
1204 rock.fid = dscp->dotdotFid;
1206 } else if (strcmp(namep, ".") == 0) {
1207 rock.fid = dscp->fid;
1211 if (flags & CM_FLAG_NOMOUNTCHASE) {
1212 /* In this case, we should go and call cm_Dir* functions
1213 directly since the following cm_ApplyDir() function will
1221 code = cm_BeginDirOp(dscp, userp, reqp, CM_DIRLOCK_READ, &dirop);
1224 code = cm_BPlusDirLookup(&dirop, namep, &rock.fid);
1229 code = cm_DirLookup(&dirop, namep, &rock.fid);
1231 cm_EndDirOp(&dirop);
1241 if (code == CM_ERROR_INEXACT_MATCH && (flags & CM_FLAG_CASEFOLD)) {
1248 return CM_ERROR_BPLUS_NOMATCH;
1253 rock.fid.cell = dscp->fid.cell;
1254 rock.fid.volume = dscp->fid.volume;
1255 rock.searchNamep = namep;
1256 rock.caseFold = (flags & CM_FLAG_CASEFOLD);
1257 rock.hasTilde = ((strchr(namep, '~') != NULL) ? 1 : 0);
1259 /* If NOMOUNTCHASE, bypass DNLC by passing NULL scp pointer */
1260 code = cm_ApplyDir(dscp, cm_LookupSearchProc, &rock, NULL, userp, reqp,
1261 (flags & CM_FLAG_NOMOUNTCHASE) ? NULL : &tscp);
1263 /* code == 0 means we fell off the end of the dir, while stopnow means
1264 * that we stopped early, probably because we found the entry we're
1265 * looking for. Any other non-zero code is an error.
1267 if (code && code != CM_ERROR_STOPNOW) {
1268 /* if the cm_scache_t we are searching in is not a directory
1269 * we must return path not found because the error
1270 * is to describe the final component not an intermediary
1272 if (code == CM_ERROR_NOTDIR) {
1273 if (flags & CM_FLAG_CHECKPATH)
1274 return CM_ERROR_NOSUCHPATH;
1276 return CM_ERROR_NOSUCHFILE;
1281 getroot = (dscp==cm_data.rootSCachep) ;
1283 if (!cm_freelanceEnabled || !getroot) {
1284 if (flags & CM_FLAG_CHECKPATH)
1285 return CM_ERROR_NOSUCHPATH;
1287 return CM_ERROR_NOSUCHFILE;
1289 else if (!strchr(namep, '#') && !strchr(namep, '%') &&
1290 strcmp(namep, "srvsvc") && strcmp(namep, "wkssvc") &&
1291 strcmp(namep, "ipc$")) {
1292 /* nonexistent dir on freelance root, so add it */
1293 char fullname[200] = ".";
1296 osi_Log1(afsd_logp,"cm_Lookup adding mount for non-existent directory: %s",
1297 osi_LogSaveString(afsd_logp,namep));
1300 * There is an ugly behavior where a share name "foo" will be searched
1301 * for as "fo". If the searched for name differs by an already existing
1302 * symlink or mount point in the Freelance directory, do not add the
1303 * new value automatically.
1307 if (namep[0] == '.') {
1308 if (cm_GetCell_Gen(&namep[1], &fullname[1], CM_FLAG_CREATE)) {
1310 if (!cm_FreelanceMountPointExists(fullname, 0))
1311 code = cm_FreelanceAddMount(fullname, &fullname[1], "root.cell.", 1, &rock.fid);
1312 if ( stricmp(&namep[1], &fullname[1]) &&
1313 !cm_FreelanceMountPointExists(namep, flags & CM_FLAG_DFS_REFERRAL ? 1 : 0) &&
1314 !cm_FreelanceSymlinkExists(namep, flags & CM_FLAG_DFS_REFERRAL ? 1 : 0))
1315 code = cm_FreelanceAddSymlink(namep, fullname, &rock.fid);
1318 if (cm_GetCell_Gen(namep, fullname, CM_FLAG_CREATE)) {
1320 if (!cm_FreelanceMountPointExists(fullname, 0))
1321 code = cm_FreelanceAddMount(fullname, fullname, "root.cell.", 0, &rock.fid);
1322 if ( stricmp(namep, fullname) &&
1323 !cm_FreelanceMountPointExists(namep, flags & CM_FLAG_DFS_REFERRAL ? 1 : 0) &&
1324 !cm_FreelanceSymlinkExists(namep, flags & CM_FLAG_DFS_REFERRAL ? 1 : 0))
1325 code = cm_FreelanceAddSymlink(namep, fullname, &rock.fid);
1328 if (!found || code < 0) { /* add mount point failed, so give up */
1329 if (flags & CM_FLAG_CHECKPATH)
1330 return CM_ERROR_NOSUCHPATH;
1332 return CM_ERROR_NOSUCHFILE;
1334 tscp = NULL; /* to force call of cm_GetSCache */
1339 if ( !tscp ) /* we did not find it in the dnlc */
1342 code = cm_GetSCache(&rock.fid, &tscp, userp, reqp);
1346 /* tscp is now held */
1348 lock_ObtainWrite(&tscp->rw);
1349 code = cm_SyncOp(tscp, NULL, userp, reqp, 0,
1350 CM_SCACHESYNC_GETSTATUS | CM_SCACHESYNC_NEEDCALLBACK);
1352 lock_ReleaseWrite(&tscp->rw);
1353 cm_ReleaseSCache(tscp);
1356 cm_SyncOpDone(tscp, NULL, CM_SCACHESYNC_NEEDCALLBACK | CM_SCACHESYNC_GETSTATUS);
1357 /* tscp is now locked */
1359 if (!(flags & CM_FLAG_NOMOUNTCHASE)
1360 && tscp->fileType == CM_SCACHETYPE_MOUNTPOINT) {
1361 /* mount points are funny: they have a volume name to mount
1364 code = cm_ReadMountPoint(tscp, userp, reqp);
1366 code = cm_FollowMountPoint(tscp, dscp, userp, reqp,
1368 lock_ReleaseWrite(&tscp->rw);
1369 cm_ReleaseSCache(tscp);
1376 lock_ReleaseWrite(&tscp->rw);
1379 /* copy back pointer */
1382 /* insert scache in dnlc */
1383 if ( !dnlcHit && !(flags & CM_FLAG_NOMOUNTCHASE) && rock.ExactFound ) {
1384 /* lock the directory entry to prevent racing callback revokes */
1385 lock_ObtainRead(&dscp->rw);
1386 if ( dscp->cbServerp != NULL && dscp->cbExpires > 0 )
1387 cm_dnlcEnter(dscp, namep, tscp);
1388 lock_ReleaseRead(&dscp->rw);
1395 int cm_ExpandSysName(char *inp, char *outp, long outSize, unsigned int index)
1400 tp = strrchr(inp, '@');
1402 return 0; /* no @sys */
1404 if (strcmp(tp, "@sys") != 0)
1405 return 0; /* no @sys */
1407 /* caller just wants to know if this is a valid @sys type of name */
1411 if (index >= cm_sysNameCount)
1414 /* otherwise generate the properly expanded @sys name */
1415 prefixCount = (int)(tp - inp);
1417 strncpy(outp, inp, prefixCount); /* copy out "a." from "a.@sys" */
1418 outp[prefixCount] = 0; /* null terminate the "a." */
1419 strcat(outp, cm_sysNameList[index]);/* append i386_nt40 */
1423 long cm_EvaluateVolumeReference(char * namep, long flags, cm_user_t * userp,
1424 cm_req_t *reqp, cm_scache_t ** outpScpp)
1427 char cellName[CELL_MAXNAMELEN];
1428 char volumeName[VL_MAXNAMELEN];
1433 cm_cell_t * cellp = NULL;
1434 cm_volume_t * volp = NULL;
1438 int mountType = RWVOL;
1440 osi_Log1(afsd_logp, "cm_EvaluateVolumeReference for string [%s]",
1441 osi_LogSaveString(afsd_logp, namep));
1443 if (strnicmp(namep, CM_PREFIX_VOL, CM_PREFIX_VOL_CCH) != 0) {
1444 goto _exit_invalid_path;
1447 /* namep is assumed to look like the following:
1449 @vol:<cellname>%<volume>\0
1451 @vol:<cellname>#<volume>\0
1455 cp = namep + CM_PREFIX_VOL_CCH; /* cp points to cell name, hopefully */
1456 tp = strchr(cp, '%');
1458 tp = strchr(cp, '#');
1460 (len = tp - cp) == 0 ||
1461 len > CELL_MAXNAMELEN)
1462 goto _exit_invalid_path;
1463 strncpy(cellName, cp, len);
1464 cellName[len] = '\0';
1469 cp = tp+1; /* cp now points to volume, supposedly */
1470 strncpy(volumeName, cp, VL_MAXNAMELEN-1);
1471 volumeName[VL_MAXNAMELEN - 1] = 0;
1473 /* OK, now we have the cell and the volume */
1474 osi_Log2(afsd_logp, " Found cell [%s] and volume [%s]",
1475 osi_LogSaveString(afsd_logp, cellName),
1476 osi_LogSaveString(afsd_logp, volumeName));
1478 cellp = cm_GetCell(cellName, CM_FLAG_CREATE);
1479 if (cellp == NULL) {
1480 goto _exit_invalid_path;
1483 len = strlen(volumeName);
1484 if (len >= 8 && strcmp(volumeName + len - 7, ".backup") == 0)
1486 else if (len >= 10 &&
1487 strcmp(volumeName + len - 9, ".readonly") == 0)
1492 if (cm_VolNameIsID(volumeName)) {
1493 code = cm_GetVolumeByID(cellp, atoi(volumeName), userp, reqp,
1494 CM_GETVOL_FLAG_CREATE, &volp);
1496 code = cm_GetVolumeByName(cellp, volumeName, userp, reqp,
1497 CM_GETVOL_FLAG_CREATE, &volp);
1503 if (volType == BACKVOL)
1504 volume = volp->bk.ID;
1505 else if (volType == ROVOL ||
1506 (volType == RWVOL && mountType == ROVOL && volp->ro.ID != 0))
1507 volume = volp->ro.ID;
1509 volume = volp->rw.ID;
1511 cm_SetFid(&fid, cellp->cellID, volume, 1, 1);
1513 code = cm_GetSCache(&fid, outpScpp, userp, reqp);
1523 if (flags & CM_FLAG_CHECKPATH)
1524 return CM_ERROR_NOSUCHPATH;
1526 return CM_ERROR_NOSUCHFILE;
1529 #ifdef DEBUG_REFCOUNT
1530 long cm_LookupDbg(cm_scache_t *dscp, char *namep, long flags, cm_user_t *userp,
1531 cm_req_t *reqp, cm_scache_t **outpScpp, char * file, long line)
1533 long cm_Lookup(cm_scache_t *dscp, char *namep, long flags, cm_user_t *userp,
1534 cm_req_t *reqp, cm_scache_t **outpScpp)
1538 char tname[AFSPATHMAX];
1539 int sysNameIndex = 0;
1540 cm_scache_t *scp = NULL;
1542 #ifdef DEBUG_REFCOUNT
1543 afsi_log("%s:%d cm_Lookup dscp 0x%p ref %d", file, line, dscp, dscp->refCount, file, line);
1544 osi_Log2(afsd_logp, "cm_Lookup dscp 0x%p ref %d", dscp, dscp->refCount);
1547 if ( stricmp(namep,SMB_IOCTL_FILENAME_NOSLASH) == 0 ) {
1548 if (flags & CM_FLAG_CHECKPATH)
1549 return CM_ERROR_NOSUCHPATH;
1551 return CM_ERROR_NOSUCHFILE;
1554 if (dscp == cm_data.rootSCachep &&
1555 strnicmp(namep, CM_PREFIX_VOL, CM_PREFIX_VOL_CCH) == 0) {
1556 return cm_EvaluateVolumeReference(namep, flags, userp, reqp, outpScpp);
1559 if (cm_ExpandSysName(namep, NULL, 0, 0) > 0) {
1560 for ( sysNameIndex = 0; sysNameIndex < MAXNUMSYSNAMES; sysNameIndex++) {
1561 code = cm_ExpandSysName(namep, tname, sizeof(tname), sysNameIndex);
1563 code = cm_LookupInternal(dscp, tname, flags, userp, reqp, &scp);
1564 #ifdef DEBUG_REFCOUNT
1565 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);
1566 osi_Log3(afsd_logp, "cm_LookupInternal (1) code 0x%x dscp 0x%p scp 0x%p", code, dscp, scp);
1574 cm_ReleaseSCache(scp);
1578 code = cm_LookupInternal(dscp, namep, flags, userp, reqp, &scp);
1579 #ifdef DEBUG_REFCOUNT
1580 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);
1581 osi_Log3(afsd_logp, "cm_LookupInternal (2) code 0x%x dscp 0x%p scp 0x%p", code, dscp, scp);
1588 code = cm_LookupInternal(dscp, namep, flags, userp, reqp, &scp);
1589 #ifdef DEBUG_REFCOUNT
1590 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);
1591 osi_Log3(afsd_logp, "cm_LookupInternal (2) code 0x%x dscp 0x%p scp 0x%p", code, dscp, scp);
1597 /* None of the possible sysName expansions could be found */
1598 if (flags & CM_FLAG_CHECKPATH)
1599 return CM_ERROR_NOSUCHPATH;
1601 return CM_ERROR_NOSUCHFILE;
1604 long cm_Unlink(cm_scache_t *dscp, char *namep, cm_user_t *userp, cm_req_t *reqp)
1610 AFSFetchStatus newDirStatus;
1612 struct rx_connection * callp;
1615 #ifdef AFS_FREELANCE_CLIENT
1616 if (cm_freelanceEnabled && dscp == cm_data.rootSCachep) {
1617 /* deleting a mount point from the root dir. */
1618 code = cm_FreelanceRemoveMount(namep);
1623 /* make sure we don't screw up the dir status during the merge */
1624 code = cm_BeginDirOp(dscp, userp, reqp, CM_DIRLOCK_NONE, &dirop);
1626 lock_ObtainWrite(&dscp->rw);
1627 sflags = CM_SCACHESYNC_STOREDATA;
1628 code = cm_SyncOp(dscp, NULL, userp, reqp, 0, sflags);
1629 lock_ReleaseWrite(&dscp->rw);
1631 cm_EndDirOp(&dirop);
1636 afsFid.Volume = dscp->fid.volume;
1637 afsFid.Vnode = dscp->fid.vnode;
1638 afsFid.Unique = dscp->fid.unique;
1640 osi_Log1(afsd_logp, "CALL RemoveFile scp 0x%p", dscp);
1642 code = cm_ConnFromFID(&dscp->fid, userp, reqp, &connp);
1646 callp = cm_GetRxConn(connp);
1647 code = RXAFS_RemoveFile(callp, &afsFid, namep,
1648 &newDirStatus, &volSync);
1649 rx_PutConnection(callp);
1651 } while (cm_Analyze(connp, userp, reqp, &dscp->fid, &volSync, NULL, NULL, code));
1652 code = cm_MapRPCError(code, reqp);
1655 osi_Log1(afsd_logp, "CALL RemoveFile FAILURE, code 0x%x", code);
1657 osi_Log0(afsd_logp, "CALL RemoveFile SUCCESS");
1660 lock_ObtainWrite(&dirop.scp->dirlock);
1661 dirop.lockType = CM_DIRLOCK_WRITE;
1663 lock_ObtainWrite(&dscp->rw);
1664 cm_dnlcRemove(dscp, namep);
1665 cm_SyncOpDone(dscp, NULL, sflags);
1667 cm_MergeStatus(NULL, dscp, &newDirStatus, &volSync, userp, CM_MERGEFLAG_DIROP);
1668 } else if (code == CM_ERROR_NOSUCHFILE) {
1669 /* windows would not have allowed the request to delete the file
1670 * if it did not believe the file existed. therefore, we must
1671 * have an inconsistent view of the world.
1673 dscp->cbServerp = NULL;
1675 lock_ReleaseWrite(&dscp->rw);
1677 if (code == 0 && cm_CheckDirOpForSingleChange(&dirop)) {
1678 cm_DirDeleteEntry(&dirop, namep);
1680 cm_BPlusDirDeleteEntry(&dirop, namep);
1683 cm_EndDirOp(&dirop);
1688 /* called with a write locked vnode, and fills in the link info.
1689 * returns this the vnode still write locked.
1691 long cm_HandleLink(cm_scache_t *linkScp, cm_user_t *userp, cm_req_t *reqp)
1698 lock_AssertWrite(&linkScp->rw);
1699 if (!linkScp->mountPointStringp[0]) {
1700 /* read the link data */
1701 lock_ReleaseWrite(&linkScp->rw);
1702 thyper.LowPart = thyper.HighPart = 0;
1703 code = buf_Get(linkScp, &thyper, &bufp);
1704 lock_ObtainWrite(&linkScp->rw);
1708 code = cm_SyncOp(linkScp, bufp, userp, reqp, 0,
1709 CM_SCACHESYNC_NEEDCALLBACK | CM_SCACHESYNC_READ);
1714 cm_SyncOpDone(linkScp, bufp, CM_SCACHESYNC_NEEDCALLBACK | CM_SCACHESYNC_READ);
1716 if (cm_HaveBuffer(linkScp, bufp, 0))
1719 code = cm_GetBuffer(linkScp, bufp, NULL, userp, reqp);
1724 } /* while loop to get the data */
1726 /* now if we still have no link read in,
1727 * copy the data from the buffer */
1728 if ((temp = linkScp->length.LowPart) >= MOUNTPOINTLEN) {
1730 return CM_ERROR_TOOBIG;
1733 /* otherwise, it fits; make sure it is still null (could have
1734 * lost race with someone else referencing this link above),
1735 * and if so, copy in the data.
1737 if (!linkScp->mountPointStringp[0]) {
1738 strncpy(linkScp->mountPointStringp, bufp->datap, temp);
1739 linkScp->mountPointStringp[temp] = 0; /* null terminate */
1741 if ( !strnicmp(linkScp->mountPointStringp, "msdfs:", strlen("msdfs:")) )
1742 linkScp->fileType = CM_SCACHETYPE_DFSLINK;
1745 } /* don't have sym link contents cached */
1750 /* called with a held vnode and a path suffix, with the held vnode being a
1751 * symbolic link. Our goal is to generate a new path to interpret, and return
1752 * this new path in newSpaceBufferp. If the new vnode is relative to a dir
1753 * other than the directory containing the symbolic link, then the new root is
1754 * returned in *newRootScpp, otherwise a null is returned there.
1756 long cm_AssembleLink(cm_scache_t *linkScp, char *pathSuffixp,
1757 cm_scache_t **newRootScpp, cm_space_t **newSpaceBufferp,
1758 cm_user_t *userp, cm_req_t *reqp)
1765 *newRootScpp = NULL;
1766 *newSpaceBufferp = NULL;
1768 lock_ObtainWrite(&linkScp->rw);
1769 code = cm_HandleLink(linkScp, userp, reqp);
1773 /* if we may overflow the buffer, bail out; buffer is signficantly
1774 * bigger than max path length, so we don't really have to worry about
1775 * being a little conservative here.
1777 if (strlen(linkScp->mountPointStringp) + strlen(pathSuffixp) + 2
1778 >= CM_UTILS_SPACESIZE) {
1779 code = CM_ERROR_TOOBIG;
1783 tsp = cm_GetSpace();
1784 linkp = linkScp->mountPointStringp;
1785 if (strncmp(linkp, cm_mountRoot, cm_mountRootLen) == 0) {
1786 if (strlen(linkp) > cm_mountRootLen)
1787 strcpy(tsp->data, linkp+cm_mountRootLen+1);
1790 *newRootScpp = cm_data.rootSCachep;
1791 cm_HoldSCache(cm_data.rootSCachep);
1792 } else if (linkp[0] == '\\' && linkp[1] == '\\') {
1793 if (!strnicmp(&linkp[2], cm_NetbiosName, (len = (long)strlen(cm_NetbiosName))))
1795 char * p = &linkp[len + 3];
1796 if (strnicmp(p, "all", 3) == 0)
1799 strcpy(tsp->data, p);
1800 for (p = tsp->data; *p; p++) {
1804 *newRootScpp = cm_data.rootSCachep;
1805 cm_HoldSCache(cm_data.rootSCachep);
1807 linkScp->fileType = CM_SCACHETYPE_DFSLINK;
1808 strcpy(tsp->data, linkp);
1809 code = CM_ERROR_PATH_NOT_COVERED;
1811 } else if ( linkScp->fileType == CM_SCACHETYPE_DFSLINK ||
1812 !strnicmp(linkp, "msdfs:", (len = (long)strlen("msdfs:"))) ) {
1813 linkScp->fileType = CM_SCACHETYPE_DFSLINK;
1814 strcpy(tsp->data, linkp);
1815 code = CM_ERROR_PATH_NOT_COVERED;
1816 } else if (*linkp == '\\' || *linkp == '/') {
1818 /* formerly, this was considered to be from the AFS root,
1819 * but this seems to create problems. instead, we will just
1820 * reject the link */
1821 strcpy(tsp->data, linkp+1);
1822 *newRootScpp = cm_data.rootSCachep;
1823 cm_HoldSCache(cm_data.rootSCachep);
1825 /* we still copy the link data into the response so that
1826 * the user can see what the link points to
1828 linkScp->fileType = CM_SCACHETYPE_INVALID;
1829 strcpy(tsp->data, linkp);
1830 code = CM_ERROR_NOSUCHPATH;
1833 /* a relative link */
1834 strcpy(tsp->data, linkp);
1836 if (pathSuffixp[0] != 0) { /* if suffix string is non-null */
1837 strcat(tsp->data, "\\");
1838 strcat(tsp->data, pathSuffixp);
1841 *newSpaceBufferp = tsp;
1845 if (code == CM_ERROR_PATH_NOT_COVERED && reqp->tidPathp && reqp->relPathp)
1846 cm_VolStatus_Notify_DFS_Mapping(linkScp, reqp->tidPathp, reqp->relPathp);
1850 lock_ReleaseWrite(&linkScp->rw);
1853 #ifdef DEBUG_REFCOUNT
1854 long cm_NameIDbg(cm_scache_t *rootSCachep, char *pathp, long flags,
1855 cm_user_t *userp, char *tidPathp, cm_req_t *reqp, cm_scache_t **outScpp,
1856 char * file, long line)
1858 long cm_NameI(cm_scache_t *rootSCachep, char *pathp, long flags,
1859 cm_user_t *userp, char *tidPathp, cm_req_t *reqp, cm_scache_t **outScpp)
1863 char *tp; /* ptr moving through input buffer */
1864 char tc; /* temp char */
1865 int haveComponent; /* has new component started? */
1866 char component[AFSPATHMAX]; /* this is the new component */
1867 char *cp; /* component name being assembled */
1868 cm_scache_t *tscp; /* current location in the hierarchy */
1869 cm_scache_t *nscp; /* next dude down */
1870 cm_scache_t *dirScp; /* last dir we searched */
1871 cm_scache_t *linkScp; /* new root for the symlink we just
1873 cm_space_t *psp; /* space for current path, if we've hit
1875 cm_space_t *tempsp; /* temp vbl */
1876 char *restp; /* rest of the pathname to interpret */
1877 int symlinkCount; /* count of # of symlinks traversed */
1878 int extraFlag; /* avoid chasing mt pts for dir cmd */
1879 int phase = 1; /* 1 = tidPathp, 2 = pathp */
1880 #define MAX_FID_COUNT 512
1881 cm_fid_t fids[MAX_FID_COUNT]; /* array of fids processed in this path walk */
1882 int fid_count = 0; /* number of fids processed in this path walk */
1885 #ifdef DEBUG_REFCOUNT
1886 afsi_log("%s:%d cm_NameI rootscp 0x%p ref %d", file, line, rootSCachep, rootSCachep->refCount);
1887 osi_Log4(afsd_logp,"cm_NameI rootscp 0x%p path %s tidpath %s flags 0x%x",
1888 rootSCachep, pathp ? pathp : "<NULL>", tidPathp ? tidPathp : "<NULL>",
1903 cm_HoldSCache(tscp);
1911 /* map Unix slashes into DOS ones so we can interpret Unix
1917 if (!haveComponent) {
1920 } else if (tc == 0) {
1934 /* we have a component here */
1935 if (tc == 0 || tc == '\\') {
1936 /* end of the component; we're at the last
1937 * component if tc == 0. However, if the last
1938 * is a symlink, we have more to do.
1940 *cp++ = 0; /* add null termination */
1942 if ((flags & CM_FLAG_DIRSEARCH) && tc == 0)
1943 extraFlag = CM_FLAG_NOMOUNTCHASE;
1944 code = cm_Lookup(tscp, component,
1946 userp, reqp, &nscp);
1949 if (!strcmp(component,"..") || !strcmp(component,".")) {
1951 * roll back the fid list until we find the fid
1952 * that matches where we are now. Its not necessarily
1953 * one or two fids because they might have been
1954 * symlinks or mount points or both that were crossed.
1956 for ( i=fid_count-1; i>=0; i--) {
1957 if (!cm_FidCmp(&nscp->fid, &fids[i]))
1962 /* add the new fid to the list */
1963 for ( i=0; i<fid_count; i++) {
1964 if ( !cm_FidCmp(&nscp->fid, &fids[i]) ) {
1965 code = CM_ERROR_TOO_MANY_SYMLINKS;
1966 cm_ReleaseSCache(nscp);
1971 if (i == fid_count && fid_count < MAX_FID_COUNT) {
1972 fids[fid_count++] = nscp->fid;
1978 cm_ReleaseSCache(tscp);
1980 cm_ReleaseSCache(dirScp);
1983 if ((code == CM_ERROR_NOSUCHFILE || code == CM_ERROR_BPLUS_NOMATCH) &&
1984 tscp->fileType == CM_SCACHETYPE_SYMLINK)
1986 osi_Log0(afsd_logp,"cm_NameI code CM_ERROR_NOSUCHPATH");
1987 return CM_ERROR_NOSUCHPATH;
1989 osi_Log1(afsd_logp,"cm_NameI code 0x%x", code);
1994 haveComponent = 0; /* component done */
1996 cm_ReleaseSCache(dirScp);
1997 dirScp = tscp; /* for some symlinks */
1998 tscp = nscp; /* already held */
2000 if (tc == 0 && !(flags & CM_FLAG_FOLLOW) && phase == 2) {
2003 cm_ReleaseSCache(dirScp);
2009 /* now, if tscp is a symlink, we should follow
2010 * it and assemble the path again.
2012 lock_ObtainWrite(&tscp->rw);
2013 code = cm_SyncOp(tscp, NULL, userp, reqp, 0,
2014 CM_SCACHESYNC_GETSTATUS
2015 | CM_SCACHESYNC_NEEDCALLBACK);
2017 lock_ReleaseWrite(&tscp->rw);
2018 cm_ReleaseSCache(tscp);
2021 cm_ReleaseSCache(dirScp);
2026 cm_SyncOpDone(tscp, NULL, CM_SCACHESYNC_NEEDCALLBACK | CM_SCACHESYNC_GETSTATUS);
2028 if (tscp->fileType == CM_SCACHETYPE_SYMLINK) {
2029 /* this is a symlink; assemble a new buffer */
2030 lock_ReleaseWrite(&tscp->rw);
2031 if (symlinkCount++ >= MAX_SYMLINK_COUNT) {
2032 cm_ReleaseSCache(tscp);
2035 cm_ReleaseSCache(dirScp);
2040 osi_Log0(afsd_logp,"cm_NameI code CM_ERROR_TOO_MANY_SYMLINKS");
2041 return CM_ERROR_TOO_MANY_SYMLINKS;
2047 code = cm_AssembleLink(tscp, restp, &linkScp, &tempsp, userp, reqp);
2049 if (code == 0 && linkScp != NULL) {
2050 if (linkScp == cm_data.rootSCachep)
2053 for ( i=0; i<fid_count; i++) {
2054 if ( !cm_FidCmp(&linkScp->fid, &fids[i]) ) {
2055 code = CM_ERROR_TOO_MANY_SYMLINKS;
2056 cm_ReleaseSCache(linkScp);
2062 if (i == fid_count && fid_count < MAX_FID_COUNT) {
2063 fids[fid_count++] = linkScp->fid;
2068 /* something went wrong */
2069 cm_ReleaseSCache(tscp);
2072 cm_ReleaseSCache(dirScp);
2078 /* otherwise, tempsp has the new path,
2079 * and linkScp is the new root from
2080 * which to interpret that path.
2081 * Continue with the namei processing,
2082 * also doing the bookkeeping for the
2083 * space allocation and tracking the
2084 * vnode reference counts.
2090 cm_ReleaseSCache(tscp);
2095 * now, if linkScp is null, that's
2096 * AssembleLink's way of telling us that
2097 * the sym link is relative to the dir
2098 * containing the link. We have a ref
2099 * to it in dirScp, and we hold it now
2100 * and reuse it as the new spot in the
2108 /* not a symlink, we may be done */
2109 lock_ReleaseWrite(&tscp->rw);
2117 cm_ReleaseSCache(dirScp);
2125 cm_ReleaseSCache(dirScp);
2128 } /* end of a component */
2131 } /* we have a component */
2132 } /* big while loop over all components */
2136 cm_ReleaseSCache(dirScp);
2142 cm_ReleaseSCache(tscp);
2144 #ifdef DEBUG_REFCOUNT
2145 afsi_log("%s:%d cm_NameI code 0x%x outScpp 0x%p ref %d", file, line, code, *outScpp, (*outScpp)->refCount);
2147 osi_Log2(afsd_logp,"cm_NameI code 0x%x outScpp 0x%p", code, *outScpp);
2151 /* called with a dir, and a vnode within the dir that happens to be a symlink.
2152 * We chase the link, and return a held pointer to the target, if it exists,
2153 * in *outScpp. If we succeed, we return 0, otherwise we return an error code
2154 * and do not hold or return a target vnode.
2156 * This is very similar to calling cm_NameI with the last component of a name,
2157 * which happens to be a symlink, except that we've already passed by the name.
2159 * This function is typically called by the directory listing functions, which
2160 * encounter symlinks but need to return the proper file length so programs
2161 * like "more" work properly when they make use of the attributes retrieved from
2164 * The input vnode should not be locked when this function is called.
2166 long cm_EvaluateSymLink(cm_scache_t *dscp, cm_scache_t *linkScp,
2167 cm_scache_t **outScpp, cm_user_t *userp, cm_req_t *reqp)
2171 cm_scache_t *newRootScp;
2173 osi_Log1(afsd_logp, "Evaluating symlink scp 0x%p", linkScp);
2175 code = cm_AssembleLink(linkScp, "", &newRootScp, &spacep, userp, reqp);
2179 /* now, if newRootScp is NULL, we're really being told that the symlink
2180 * is relative to the current directory (dscp).
2182 if (newRootScp == NULL) {
2184 cm_HoldSCache(dscp);
2187 code = cm_NameI(newRootScp, spacep->data,
2188 CM_FLAG_CASEFOLD | CM_FLAG_FOLLOW | CM_FLAG_DIRSEARCH,
2189 userp, NULL, reqp, outScpp);
2191 if (code == CM_ERROR_NOSUCHFILE || code == CM_ERROR_BPLUS_NOMATCH)
2192 code = CM_ERROR_NOSUCHPATH;
2194 /* this stuff is allocated no matter what happened on the namei call,
2196 cm_FreeSpace(spacep);
2197 cm_ReleaseSCache(newRootScp);
2199 if (linkScp == *outScpp) {
2200 cm_ReleaseSCache(*outScpp);
2202 code = CM_ERROR_NOSUCHPATH;
2208 /* make this big enough so that one buffer of dir pages won't overflow. We'll
2209 * check anyway, but we want to minimize the chance that we have to leave stuff
2212 #define CM_BULKMAX (3 * AFSCBMAX)
2214 /* rock for bulk stat calls */
2215 typedef struct cm_bulkStat {
2216 osi_hyper_t bufOffset; /* only do it for things in this buffer page */
2218 /* info for the actual call */
2219 int counter; /* next free slot */
2220 AFSFid fids[CM_BULKMAX];
2221 AFSFetchStatus stats[CM_BULKMAX];
2222 AFSCallBack callbacks[CM_BULKMAX];
2225 /* for a given entry, make sure that it isn't in the stat cache, and then
2226 * add it to the list of file IDs to be obtained.
2228 * Don't bother adding it if we already have a vnode. Note that the dir
2229 * is locked, so we have to be careful checking the vnode we're thinking of
2230 * processing, to avoid deadlocks.
2232 long cm_TryBulkProc(cm_scache_t *scp, cm_dirEntry_t *dep, void *rockp,
2243 /* Don't overflow bsp. */
2244 if (bsp->counter >= CM_BULKMAX)
2245 return CM_ERROR_STOPNOW;
2247 thyper.LowPart = cm_data.buf_blockSize;
2248 thyper.HighPart = 0;
2249 thyper = LargeIntegerAdd(thyper, bsp->bufOffset);
2251 /* thyper is now the first byte past the end of the record we're
2252 * interested in, and bsp->bufOffset is the first byte of the record
2253 * we're interested in.
2254 * Skip data in the others.
2257 if (LargeIntegerLessThan(*offp, bsp->bufOffset))
2259 if (LargeIntegerGreaterThanOrEqualTo(*offp, thyper))
2260 return CM_ERROR_STOPNOW;
2261 if (strcmp(dep->name, ".") == 0 || strcmp(dep->name, "..") == 0)
2264 cm_SetFid(&tfid, scp->fid.cell, scp->fid.volume, ntohl(dep->fid.vnode), ntohl(dep->fid.unique));
2265 tscp = cm_FindSCache(&tfid);
2267 if (lock_TryWrite(&tscp->rw)) {
2268 /* we have an entry that we can look at */
2269 if (!(tscp->flags & CM_SCACHEFLAG_EACCESS) && cm_HaveCallback(tscp)) {
2270 /* we have a callback on it. Don't bother
2271 * fetching this stat entry, since we're happy
2272 * with the info we have.
2274 lock_ReleaseWrite(&tscp->rw);
2275 cm_ReleaseSCache(tscp);
2278 lock_ReleaseWrite(&tscp->rw);
2280 cm_ReleaseSCache(tscp);
2283 #ifdef AFS_FREELANCE_CLIENT
2284 // yj: if this is a mountpoint under root.afs then we don't want it
2285 // to be bulkstat-ed, instead, we call getSCache directly and under
2286 // getSCache, it is handled specially.
2287 if ( cm_freelanceEnabled &&
2288 tfid.cell==AFS_FAKE_ROOT_CELL_ID &&
2289 tfid.volume==AFS_FAKE_ROOT_VOL_ID &&
2290 !(tfid.vnode==0x1 && tfid.unique==0x1) )
2292 osi_Log0(afsd_logp, "cm_TryBulkProc Freelance calls cm_SCache on root.afs mountpoint");
2293 return cm_GetSCache(&tfid, &tscp, NULL, NULL);
2295 #endif /* AFS_FREELANCE_CLIENT */
2298 bsp->fids[i].Volume = scp->fid.volume;
2299 bsp->fids[i].Vnode = tfid.vnode;
2300 bsp->fids[i].Unique = tfid.unique;
2304 /* called with a write locked scp and a pointer to a buffer. Make bulk stat
2305 * calls on all undeleted files in the page of the directory specified.
2308 cm_TryBulkStat(cm_scache_t *dscp, osi_hyper_t *offsetp, cm_user_t *userp,
2312 cm_bulkStat_t bb; /* this is *BIG*, probably 16K or so;
2313 * watch for stack problems */
2314 AFSCBFids fidStruct;
2315 AFSBulkStats statStruct;
2317 AFSCBs callbackStruct;
2320 cm_callbackRequest_t cbReq;
2326 struct rx_connection * callp;
2327 int inlinebulk = 0; /* Did we use InlineBulkStatus RPC or not? */
2329 osi_Log1(afsd_logp, "cm_TryBulkStat dir 0x%p", dscp);
2331 /* should be on a buffer boundary */
2332 osi_assertx((offsetp->LowPart & (cm_data.buf_blockSize - 1)) == 0, "invalid offset");
2334 memset(&bb, 0, sizeof(bb));
2335 bb.bufOffset = *offsetp;
2337 lock_ReleaseWrite(&dscp->rw);
2338 /* first, assemble the file IDs we need to stat */
2339 code = cm_ApplyDir(dscp, cm_TryBulkProc, (void *) &bb, offsetp, userp, reqp, NULL);
2341 /* if we failed, bail out early */
2342 if (code && code != CM_ERROR_STOPNOW) {
2343 lock_ObtainWrite(&dscp->rw);
2347 /* otherwise, we may have one or more bulk stat's worth of stuff in bb;
2348 * make the calls to create the entries. Handle AFSCBMAX files at a
2352 while (filex < bb.counter) {
2353 filesThisCall = bb.counter - filex;
2354 if (filesThisCall > AFSCBMAX)
2355 filesThisCall = AFSCBMAX;
2357 fidStruct.AFSCBFids_len = filesThisCall;
2358 fidStruct.AFSCBFids_val = &bb.fids[filex];
2359 statStruct.AFSBulkStats_len = filesThisCall;
2360 statStruct.AFSBulkStats_val = &bb.stats[filex];
2361 callbackStruct.AFSCBs_len = filesThisCall;
2362 callbackStruct.AFSCBs_val = &bb.callbacks[filex];
2363 cm_StartCallbackGrantingCall(NULL, &cbReq);
2364 osi_Log1(afsd_logp, "CALL BulkStatus, %d entries", filesThisCall);
2366 code = cm_ConnFromFID(&dscp->fid, userp, reqp, &connp);
2370 callp = cm_GetRxConn(connp);
2371 if (!(connp->serverp->flags & CM_SERVERFLAG_NOINLINEBULK)) {
2372 code = RXAFS_InlineBulkStatus(callp, &fidStruct,
2373 &statStruct, &callbackStruct, &volSync);
2374 if (code == RXGEN_OPCODE) {
2375 cm_SetServerNoInlineBulk(connp->serverp, 0);
2381 code = RXAFS_BulkStatus(callp, &fidStruct,
2382 &statStruct, &callbackStruct, &volSync);
2384 rx_PutConnection(callp);
2386 } while (cm_Analyze(connp, userp, reqp, &dscp->fid,
2387 &volSync, NULL, &cbReq, code));
2388 code = cm_MapRPCError(code, reqp);
2390 osi_Log2(afsd_logp, "CALL %sBulkStatus FAILURE code 0x%x",
2391 inlinebulk ? "Inline" : "", code);
2393 osi_Log1(afsd_logp, "CALL %sBulkStatus SUCCESS", inlinebulk ? "Inline" : "");
2395 /* may as well quit on an error, since we're not going to do
2396 * much better on the next immediate call, either.
2399 cm_EndCallbackGrantingCall(NULL, &cbReq, NULL, 0);
2403 /* otherwise, we should do the merges */
2404 for (i = 0; i<filesThisCall; i++) {
2406 cm_SetFid(&tfid, dscp->fid.cell, bb.fids[j].Volume, bb.fids[j].Vnode, bb.fids[j].Unique);
2407 code = cm_GetSCache(&tfid, &scp, userp, reqp);
2411 /* otherwise, if this entry has no callback info,
2414 lock_ObtainWrite(&scp->rw);
2415 /* now, we have to be extra paranoid on merging in this
2416 * information, since we didn't use cm_SyncOp before
2417 * starting the fetch to make sure that no bad races
2418 * were occurring. Specifically, we need to make sure
2419 * we don't obliterate any newer information in the
2420 * vnode than have here.
2422 * Right now, be pretty conservative: if there's a
2423 * callback or a pending call, skip it.
2425 if ((scp->cbServerp == NULL || (scp->flags & CM_SCACHEFLAG_EACCESS))
2427 (CM_SCACHEFLAG_FETCHING
2428 | CM_SCACHEFLAG_STORING
2429 | CM_SCACHEFLAG_SIZESTORING))) {
2430 cm_EndCallbackGrantingCall(scp, &cbReq,
2432 CM_CALLBACK_MAINTAINCOUNT);
2433 cm_MergeStatus(dscp, scp, &bb.stats[j], &volSync, userp, 0);
2435 lock_ReleaseWrite(&scp->rw);
2436 cm_ReleaseSCache(scp);
2437 } /* all files in the response */
2438 /* now tell it to drop the count,
2439 * after doing the vnode processing above */
2440 cm_EndCallbackGrantingCall(NULL, &cbReq, NULL, 0);
2442 filex += filesThisCall;
2443 } /* while there are still more files to process */
2444 lock_ObtainWrite(&dscp->rw);
2446 /* If we did the InlineBulk RPC pull out the return code and log it */
2448 if ((&bb.stats[0])->errorCode) {
2449 osi_Log1(afsd_logp, "cm_TryBulkStat bulk stat error: %d",
2450 (&bb.stats[0])->errorCode);
2454 osi_Log0(afsd_logp, "END cm_TryBulkStat");
2458 void cm_StatusFromAttr(AFSStoreStatus *statusp, cm_scache_t *scp, cm_attr_t *attrp)
2462 /* initialize store back mask as inexpensive local variable */
2464 memset(statusp, 0, sizeof(AFSStoreStatus));
2466 /* copy out queued info from scache first, if scp passed in */
2468 if (scp->mask & CM_SCACHEMASK_CLIENTMODTIME) {
2469 statusp->ClientModTime = scp->clientModTime;
2470 mask |= AFS_SETMODTIME;
2471 scp->mask &= ~CM_SCACHEMASK_CLIENTMODTIME;
2476 /* now add in our locally generated request */
2477 if (attrp->mask & CM_ATTRMASK_CLIENTMODTIME) {
2478 statusp->ClientModTime = attrp->clientModTime;
2479 mask |= AFS_SETMODTIME;
2481 if (attrp->mask & CM_ATTRMASK_UNIXMODEBITS) {
2482 statusp->UnixModeBits = attrp->unixModeBits;
2483 mask |= AFS_SETMODE;
2485 if (attrp->mask & CM_ATTRMASK_OWNER) {
2486 statusp->Owner = attrp->owner;
2487 mask |= AFS_SETOWNER;
2489 if (attrp->mask & CM_ATTRMASK_GROUP) {
2490 statusp->Group = attrp->group;
2491 mask |= AFS_SETGROUP;
2494 statusp->Mask = mask;
2497 /* set the file size, and make sure that all relevant buffers have been
2498 * truncated. Ensure that any partially truncated buffers have been zeroed
2499 * to the end of the buffer.
2501 long cm_SetLength(cm_scache_t *scp, osi_hyper_t *sizep, cm_user_t *userp,
2507 /* start by locking out buffer creation */
2508 lock_ObtainWrite(&scp->bufCreateLock);
2510 /* verify that this is a file, not a dir or a symlink */
2511 lock_ObtainWrite(&scp->rw);
2512 code = cm_SyncOp(scp, NULL, userp, reqp, 0,
2513 CM_SCACHESYNC_NEEDCALLBACK | CM_SCACHESYNC_GETSTATUS);
2516 cm_SyncOpDone(scp, NULL, CM_SCACHESYNC_NEEDCALLBACK | CM_SCACHESYNC_GETSTATUS);
2518 if (scp->fileType != CM_SCACHETYPE_FILE) {
2519 code = CM_ERROR_ISDIR;
2524 if (LargeIntegerLessThan(*sizep, scp->length))
2529 lock_ReleaseWrite(&scp->rw);
2531 /* can't hold scp->rw lock here, since we may wait for a storeback to
2532 * finish if the buffer package is cleaning a buffer by storing it to
2536 buf_Truncate(scp, userp, reqp, sizep);
2538 /* now ensure that file length is short enough, and update truncPos */
2539 lock_ObtainWrite(&scp->rw);
2541 /* make sure we have a callback (so we have the right value for the
2542 * length), and wait for it to be safe to do a truncate.
2544 code = cm_SyncOp(scp, NULL, userp, reqp, PRSFS_WRITE,
2545 CM_SCACHESYNC_NEEDCALLBACK | CM_SCACHESYNC_GETSTATUS
2546 | CM_SCACHESYNC_SETSTATUS | CM_SCACHESYNC_SETSIZE);
2548 /* If we only have 'i' bits, then we should still be able to set
2549 the size of a file we created. */
2550 if (code == CM_ERROR_NOACCESS && scp->creator == userp) {
2551 code = cm_SyncOp(scp, NULL, userp, reqp, PRSFS_INSERT,
2552 CM_SCACHESYNC_NEEDCALLBACK | CM_SCACHESYNC_GETSTATUS
2553 | CM_SCACHESYNC_SETSTATUS | CM_SCACHESYNC_SETSIZE);
2559 if (LargeIntegerLessThan(*sizep, scp->length)) {
2560 /* a real truncation. If truncPos is not set yet, or is bigger
2561 * than where we're truncating the file, set truncPos to this
2566 if (!(scp->mask & CM_SCACHEMASK_TRUNCPOS)
2567 || LargeIntegerLessThan(*sizep, scp->length)) {
2569 scp->truncPos = *sizep;
2570 scp->mask |= CM_SCACHEMASK_TRUNCPOS;
2572 /* in either case, the new file size has been changed */
2573 scp->length = *sizep;
2574 scp->mask |= CM_SCACHEMASK_LENGTH;
2576 else if (LargeIntegerGreaterThan(*sizep, scp->length)) {
2577 /* really extending the file */
2578 scp->length = *sizep;
2579 scp->mask |= CM_SCACHEMASK_LENGTH;
2582 /* done successfully */
2585 cm_SyncOpDone(scp, NULL,
2586 CM_SCACHESYNC_NEEDCALLBACK | CM_SCACHESYNC_GETSTATUS
2587 | CM_SCACHESYNC_SETSTATUS | CM_SCACHESYNC_SETSIZE);
2590 lock_ReleaseWrite(&scp->rw);
2591 lock_ReleaseWrite(&scp->bufCreateLock);
2596 /* set the file size or other attributes (but not both at once) */
2597 long cm_SetAttr(cm_scache_t *scp, cm_attr_t *attrp, cm_user_t *userp,
2601 AFSFetchStatus afsOutStatus;
2605 AFSStoreStatus afsInStatus;
2606 struct rx_connection * callp;
2608 /* handle file length setting */
2609 if (attrp->mask & CM_ATTRMASK_LENGTH)
2610 return cm_SetLength(scp, &attrp->length, userp, reqp);
2612 lock_ObtainWrite(&scp->rw);
2613 /* otherwise, we have to make an RPC to get the status */
2614 code = cm_SyncOp(scp, NULL, userp, reqp, 0, CM_SCACHESYNC_STORESTATUS);
2616 lock_ReleaseWrite(&scp->rw);
2619 lock_ConvertWToR(&scp->rw);
2621 /* make the attr structure */
2622 cm_StatusFromAttr(&afsInStatus, scp, attrp);
2624 tfid.Volume = scp->fid.volume;
2625 tfid.Vnode = scp->fid.vnode;
2626 tfid.Unique = scp->fid.unique;
2627 lock_ReleaseRead(&scp->rw);
2629 /* now make the RPC */
2630 osi_Log1(afsd_logp, "CALL StoreStatus scp 0x%p", scp);
2632 code = cm_ConnFromFID(&scp->fid, userp, reqp, &connp);
2636 callp = cm_GetRxConn(connp);
2637 code = RXAFS_StoreStatus(callp, &tfid,
2638 &afsInStatus, &afsOutStatus, &volSync);
2639 rx_PutConnection(callp);
2641 } while (cm_Analyze(connp, userp, reqp,
2642 &scp->fid, &volSync, NULL, NULL, code));
2643 code = cm_MapRPCError(code, reqp);
2646 osi_Log1(afsd_logp, "CALL StoreStatus FAILURE, code 0x%x", code);
2648 osi_Log0(afsd_logp, "CALL StoreStatus SUCCESS");
2650 lock_ObtainWrite(&scp->rw);
2651 cm_SyncOpDone(scp, NULL, CM_SCACHESYNC_STORESTATUS);
2653 cm_MergeStatus(NULL, scp, &afsOutStatus, &volSync, userp,
2654 CM_MERGEFLAG_FORCE|CM_MERGEFLAG_STOREDATA);
2656 /* if we're changing the mode bits, discard the ACL cache,
2657 * since we changed the mode bits.
2659 if (afsInStatus.Mask & AFS_SETMODE)
2660 cm_FreeAllACLEnts(scp);
2661 lock_ReleaseWrite(&scp->rw);
2665 long cm_Create(cm_scache_t *dscp, char *namep, long flags, cm_attr_t *attrp,
2666 cm_scache_t **scpp, cm_user_t *userp, cm_req_t *reqp)
2671 cm_callbackRequest_t cbReq;
2674 cm_scache_t *scp = NULL;
2676 AFSStoreStatus inStatus;
2677 AFSFetchStatus updatedDirStatus;
2678 AFSFetchStatus newFileStatus;
2679 AFSCallBack newFileCallback;
2681 struct rx_connection * callp;
2684 /* can't create names with @sys in them; must expand it manually first.
2685 * return "invalid request" if they try.
2687 if (cm_ExpandSysName(namep, NULL, 0, 0)) {
2688 return CM_ERROR_ATSYS;
2691 #ifdef AFS_FREELANCE_CLIENT
2692 /* Freelance root volume does not hold files */
2693 if (cm_freelanceEnabled &&
2694 dscp->fid.cell==AFS_FAKE_ROOT_CELL_ID &&
2695 dscp->fid.volume==AFS_FAKE_ROOT_VOL_ID )
2697 return CM_ERROR_NOACCESS;
2699 #endif /* AFS_FREELANCE_CLIENT */
2701 /* before starting the RPC, mark that we're changing the file data, so
2702 * that someone who does a chmod will know to wait until our call
2705 cm_BeginDirOp(dscp, userp, reqp, CM_DIRLOCK_NONE, &dirop);
2706 lock_ObtainWrite(&dscp->rw);
2707 code = cm_SyncOp(dscp, NULL, userp, reqp, 0, CM_SCACHESYNC_STOREDATA);
2708 lock_ReleaseWrite(&dscp->rw);
2710 cm_StartCallbackGrantingCall(NULL, &cbReq);
2712 cm_EndDirOp(&dirop);
2719 cm_StatusFromAttr(&inStatus, NULL, attrp);
2721 /* try the RPC now */
2722 osi_Log1(afsd_logp, "CALL CreateFile scp 0x%p", dscp);
2724 code = cm_ConnFromFID(&dscp->fid, userp, reqp, &connp);
2728 dirAFSFid.Volume = dscp->fid.volume;
2729 dirAFSFid.Vnode = dscp->fid.vnode;
2730 dirAFSFid.Unique = dscp->fid.unique;
2732 callp = cm_GetRxConn(connp);
2733 code = RXAFS_CreateFile(connp->callp, &dirAFSFid, namep,
2734 &inStatus, &newAFSFid, &newFileStatus,
2735 &updatedDirStatus, &newFileCallback,
2737 rx_PutConnection(callp);
2739 } while (cm_Analyze(connp, userp, reqp,
2740 &dscp->fid, &volSync, NULL, &cbReq, code));
2741 code = cm_MapRPCError(code, reqp);
2744 osi_Log1(afsd_logp, "CALL CreateFile FAILURE, code 0x%x", code);
2746 osi_Log0(afsd_logp, "CALL CreateFile SUCCESS");
2749 lock_ObtainWrite(&dirop.scp->dirlock);
2750 dirop.lockType = CM_DIRLOCK_WRITE;
2752 lock_ObtainWrite(&dscp->rw);
2753 cm_SyncOpDone(dscp, NULL, CM_SCACHESYNC_STOREDATA);
2755 cm_MergeStatus(NULL, dscp, &updatedDirStatus, &volSync, userp, CM_MERGEFLAG_DIROP);
2757 lock_ReleaseWrite(&dscp->rw);
2759 /* now try to create the file's entry, too, but be careful to
2760 * make sure that we don't merge in old info. Since we weren't locking
2761 * out any requests during the file's creation, we may have pretty old
2765 cm_SetFid(&newFid, dscp->fid.cell, dscp->fid.volume, newAFSFid.Vnode, newAFSFid.Unique);
2766 code = cm_GetSCache(&newFid, &scp, userp, reqp);
2768 lock_ObtainWrite(&scp->rw);
2769 scp->creator = userp; /* remember who created it */
2770 if (!cm_HaveCallback(scp)) {
2771 cm_MergeStatus(dscp, scp, &newFileStatus, &volSync,
2773 cm_EndCallbackGrantingCall(scp, &cbReq,
2774 &newFileCallback, 0);
2777 lock_ReleaseWrite(&scp->rw);
2782 /* make sure we end things properly */
2784 cm_EndCallbackGrantingCall(NULL, &cbReq, NULL, 0);
2786 if (scp && cm_CheckDirOpForSingleChange(&dirop)) {
2787 cm_DirCreateEntry(&dirop, namep, &newFid);
2789 cm_BPlusDirCreateEntry(&dirop, namep, &newFid);
2792 cm_EndDirOp(&dirop);
2797 long cm_FSync(cm_scache_t *scp, cm_user_t *userp, cm_req_t *reqp)
2801 code = buf_CleanVnode(scp, userp, reqp);
2803 lock_ObtainWrite(&scp->rw);
2805 if (scp->mask & (CM_SCACHEMASK_TRUNCPOS
2806 | CM_SCACHEMASK_CLIENTMODTIME
2807 | CM_SCACHEMASK_LENGTH))
2808 code = cm_StoreMini(scp, userp, reqp);
2810 if (scp->flags & (CM_SCACHEFLAG_OVERQUOTA | CM_SCACHEFLAG_OUTOFSPACE)) {
2811 code = (scp->flags & CM_SCACHEFLAG_OVERQUOTA) ? CM_ERROR_QUOTA : CM_ERROR_SPACE;
2812 scp->flags &= ~(CM_SCACHEFLAG_OVERQUOTA | CM_SCACHEFLAG_OUTOFSPACE);
2815 lock_ReleaseWrite(&scp->rw);
2820 long cm_MakeDir(cm_scache_t *dscp, char *namep, long flags, cm_attr_t *attrp,
2821 cm_user_t *userp, cm_req_t *reqp)
2826 cm_callbackRequest_t cbReq;
2829 cm_scache_t *scp = NULL;
2831 AFSStoreStatus inStatus;
2832 AFSFetchStatus updatedDirStatus;
2833 AFSFetchStatus newDirStatus;
2834 AFSCallBack newDirCallback;
2836 struct rx_connection * callp;
2839 /* can't create names with @sys in them; must expand it manually first.
2840 * return "invalid request" if they try.
2842 if (cm_ExpandSysName(namep, NULL, 0, 0)) {
2843 return CM_ERROR_ATSYS;
2846 #ifdef AFS_FREELANCE_CLIENT
2847 /* Freelance root volume does not hold subdirectories */
2848 if (cm_freelanceEnabled &&
2849 dscp->fid.cell==AFS_FAKE_ROOT_CELL_ID &&
2850 dscp->fid.volume==AFS_FAKE_ROOT_VOL_ID )
2852 return CM_ERROR_NOACCESS;
2854 #endif /* AFS_FREELANCE_CLIENT */
2856 /* before starting the RPC, mark that we're changing the directory
2857 * data, so that someone who does a chmod on the dir will wait until
2858 * our call completes.
2860 cm_BeginDirOp(dscp, userp, reqp, CM_DIRLOCK_NONE, &dirop);
2861 lock_ObtainWrite(&dscp->rw);
2862 code = cm_SyncOp(dscp, NULL, userp, reqp, 0, CM_SCACHESYNC_STOREDATA);
2863 lock_ReleaseWrite(&dscp->rw);
2865 cm_StartCallbackGrantingCall(NULL, &cbReq);
2867 cm_EndDirOp(&dirop);
2874 cm_StatusFromAttr(&inStatus, NULL, attrp);
2876 /* try the RPC now */
2877 osi_Log1(afsd_logp, "CALL MakeDir scp 0x%p", dscp);
2879 code = cm_ConnFromFID(&dscp->fid, userp, reqp, &connp);
2883 dirAFSFid.Volume = dscp->fid.volume;
2884 dirAFSFid.Vnode = dscp->fid.vnode;
2885 dirAFSFid.Unique = dscp->fid.unique;
2887 callp = cm_GetRxConn(connp);
2888 code = RXAFS_MakeDir(connp->callp, &dirAFSFid, namep,
2889 &inStatus, &newAFSFid, &newDirStatus,
2890 &updatedDirStatus, &newDirCallback,
2892 rx_PutConnection(callp);
2894 } while (cm_Analyze(connp, userp, reqp,
2895 &dscp->fid, &volSync, NULL, &cbReq, code));
2896 code = cm_MapRPCError(code, reqp);
2899 osi_Log1(afsd_logp, "CALL MakeDir FAILURE, code 0x%x", code);
2901 osi_Log0(afsd_logp, "CALL MakeDir SUCCESS");
2904 lock_ObtainWrite(&dirop.scp->dirlock);
2905 dirop.lockType = CM_DIRLOCK_WRITE;
2907 lock_ObtainWrite(&dscp->rw);
2908 cm_SyncOpDone(dscp, NULL, CM_SCACHESYNC_STOREDATA);
2910 cm_MergeStatus(NULL, dscp, &updatedDirStatus, &volSync, userp, CM_MERGEFLAG_DIROP);
2912 lock_ReleaseWrite(&dscp->rw);
2914 /* now try to create the new dir's entry, too, but be careful to
2915 * make sure that we don't merge in old info. Since we weren't locking
2916 * out any requests during the file's creation, we may have pretty old
2920 cm_SetFid(&newFid, dscp->fid.cell, dscp->fid.volume, newAFSFid.Vnode, newAFSFid.Unique);
2921 code = cm_GetSCache(&newFid, &scp, userp, reqp);
2923 lock_ObtainWrite(&scp->rw);
2924 if (!cm_HaveCallback(scp)) {
2925 cm_MergeStatus(dscp, scp, &newDirStatus, &volSync,
2927 cm_EndCallbackGrantingCall(scp, &cbReq,
2928 &newDirCallback, 0);
2931 lock_ReleaseWrite(&scp->rw);
2932 cm_ReleaseSCache(scp);
2936 /* make sure we end things properly */
2938 cm_EndCallbackGrantingCall(NULL, &cbReq, NULL, 0);
2940 if (scp && cm_CheckDirOpForSingleChange(&dirop)) {
2941 cm_DirCreateEntry(&dirop, namep, &newFid);
2943 cm_BPlusDirCreateEntry(&dirop, namep, &newFid);
2946 cm_EndDirOp(&dirop);
2948 /* and return error code */
2952 long cm_Link(cm_scache_t *dscp, char *namep, cm_scache_t *sscp, long flags,
2953 cm_user_t *userp, cm_req_t *reqp)
2958 AFSFid existingAFSFid;
2959 AFSFetchStatus updatedDirStatus;
2960 AFSFetchStatus newLinkStatus;
2962 struct rx_connection * callp;
2965 if (dscp->fid.cell != sscp->fid.cell ||
2966 dscp->fid.volume != sscp->fid.volume) {
2967 return CM_ERROR_CROSSDEVLINK;
2970 cm_BeginDirOp(dscp, userp, reqp, CM_DIRLOCK_NONE, &dirop);
2971 lock_ObtainWrite(&dscp->rw);
2972 code = cm_SyncOp(dscp, NULL, userp, reqp, 0, CM_SCACHESYNC_STOREDATA);
2973 lock_ReleaseWrite(&dscp->rw);
2975 cm_EndDirOp(&dirop);
2980 /* try the RPC now */
2981 osi_Log1(afsd_logp, "CALL Link scp 0x%p", dscp);
2983 code = cm_ConnFromFID(&dscp->fid, userp, reqp, &connp);
2986 dirAFSFid.Volume = dscp->fid.volume;
2987 dirAFSFid.Vnode = dscp->fid.vnode;
2988 dirAFSFid.Unique = dscp->fid.unique;
2990 existingAFSFid.Volume = sscp->fid.volume;
2991 existingAFSFid.Vnode = sscp->fid.vnode;
2992 existingAFSFid.Unique = sscp->fid.unique;
2994 callp = cm_GetRxConn(connp);
2995 code = RXAFS_Link(callp, &dirAFSFid, namep, &existingAFSFid,
2996 &newLinkStatus, &updatedDirStatus, &volSync);
2997 rx_PutConnection(callp);
2998 osi_Log1(smb_logp," RXAFS_Link returns 0x%x", code);
3000 } while (cm_Analyze(connp, userp, reqp,
3001 &dscp->fid, &volSync, NULL, NULL, code));
3003 code = cm_MapRPCError(code, reqp);
3006 osi_Log1(afsd_logp, "CALL Link FAILURE, code 0x%x", code);
3008 osi_Log0(afsd_logp, "CALL Link SUCCESS");
3011 lock_ObtainWrite(&dirop.scp->dirlock);
3012 dirop.lockType = CM_DIRLOCK_WRITE;
3014 lock_ObtainWrite(&dscp->rw);
3015 cm_SyncOpDone(dscp, NULL, CM_SCACHESYNC_STOREDATA);
3017 cm_MergeStatus(NULL, dscp, &updatedDirStatus, &volSync, userp, CM_MERGEFLAG_DIROP);
3019 lock_ReleaseWrite(&dscp->rw);
3022 if (cm_CheckDirOpForSingleChange(&dirop)) {
3023 cm_DirCreateEntry(&dirop, namep, &sscp->fid);
3025 cm_BPlusDirCreateEntry(&dirop, namep, &sscp->fid);
3029 cm_EndDirOp(&dirop);
3034 long cm_SymLink(cm_scache_t *dscp, char *namep, char *contentsp, long flags,
3035 cm_attr_t *attrp, cm_user_t *userp, cm_req_t *reqp)
3043 AFSStoreStatus inStatus;
3044 AFSFetchStatus updatedDirStatus;
3045 AFSFetchStatus newLinkStatus;
3047 struct rx_connection * callp;
3050 /* before starting the RPC, mark that we're changing the directory data,
3051 * so that someone who does a chmod on the dir will wait until our
3054 cm_BeginDirOp(dscp, userp, reqp, CM_DIRLOCK_NONE, &dirop);
3055 lock_ObtainWrite(&dscp->rw);
3056 code = cm_SyncOp(dscp, NULL, userp, reqp, 0, CM_SCACHESYNC_STOREDATA);
3057 lock_ReleaseWrite(&dscp->rw);
3059 cm_EndDirOp(&dirop);
3064 cm_StatusFromAttr(&inStatus, NULL, attrp);
3066 /* try the RPC now */
3067 osi_Log1(afsd_logp, "CALL Symlink scp 0x%p", dscp);
3069 code = cm_ConnFromFID(&dscp->fid, userp, reqp, &connp);
3073 dirAFSFid.Volume = dscp->fid.volume;
3074 dirAFSFid.Vnode = dscp->fid.vnode;
3075 dirAFSFid.Unique = dscp->fid.unique;
3077 callp = cm_GetRxConn(connp);
3078 code = RXAFS_Symlink(callp, &dirAFSFid, namep, contentsp,
3079 &inStatus, &newAFSFid, &newLinkStatus,
3080 &updatedDirStatus, &volSync);
3081 rx_PutConnection(callp);
3083 } while (cm_Analyze(connp, userp, reqp,
3084 &dscp->fid, &volSync, NULL, NULL, code));
3085 code = cm_MapRPCError(code, reqp);
3088 osi_Log1(afsd_logp, "CALL Symlink FAILURE, code 0x%x", code);
3090 osi_Log0(afsd_logp, "CALL Symlink SUCCESS");
3093 lock_ObtainWrite(&dirop.scp->dirlock);
3094 dirop.lockType = CM_DIRLOCK_WRITE;
3096 lock_ObtainWrite(&dscp->rw);
3097 cm_SyncOpDone(dscp, NULL, CM_SCACHESYNC_STOREDATA);
3099 cm_MergeStatus(NULL, dscp, &updatedDirStatus, &volSync, userp, CM_MERGEFLAG_DIROP);
3101 lock_ReleaseWrite(&dscp->rw);
3104 if (cm_CheckDirOpForSingleChange(&dirop)) {
3105 cm_SetFid(&newFid, dscp->fid.cell, dscp->fid.volume, newAFSFid.Vnode, newAFSFid.Unique);
3107 cm_DirCreateEntry(&dirop, namep, &newFid);
3109 cm_BPlusDirCreateEntry(&dirop, namep, &newFid);
3113 cm_EndDirOp(&dirop);
3115 /* now try to create the new dir's entry, too, but be careful to
3116 * make sure that we don't merge in old info. Since we weren't locking
3117 * out any requests during the file's creation, we may have pretty old
3121 cm_SetFid(&newFid, dscp->fid.cell, dscp->fid.volume, newAFSFid.Vnode, newAFSFid.Unique);
3122 code = cm_GetSCache(&newFid, &scp, userp, reqp);
3124 lock_ObtainWrite(&scp->rw);
3125 if (!cm_HaveCallback(scp)) {
3126 cm_MergeStatus(dscp, scp, &newLinkStatus, &volSync,
3129 lock_ReleaseWrite(&scp->rw);
3130 cm_ReleaseSCache(scp);
3134 /* and return error code */
3138 long cm_RemoveDir(cm_scache_t *dscp, char *namep, cm_user_t *userp,
3145 AFSFetchStatus updatedDirStatus;
3147 struct rx_connection * callp;
3150 /* before starting the RPC, mark that we're changing the directory data,
3151 * so that someone who does a chmod on the dir will wait until our
3154 cm_BeginDirOp(dscp, userp, reqp, CM_DIRLOCK_NONE, &dirop);
3155 lock_ObtainWrite(&dscp->rw);
3156 code = cm_SyncOp(dscp, NULL, userp, reqp, 0, CM_SCACHESYNC_STOREDATA);
3157 lock_ReleaseWrite(&dscp->rw);
3159 cm_EndDirOp(&dirop);
3164 /* try the RPC now */
3165 osi_Log1(afsd_logp, "CALL RemoveDir scp 0x%p", dscp);
3167 code = cm_ConnFromFID(&dscp->fid, userp, reqp, &connp);
3171 dirAFSFid.Volume = dscp->fid.volume;
3172 dirAFSFid.Vnode = dscp->fid.vnode;
3173 dirAFSFid.Unique = dscp->fid.unique;
3175 callp = cm_GetRxConn(connp);
3176 code = RXAFS_RemoveDir(callp, &dirAFSFid, namep,
3177 &updatedDirStatus, &volSync);
3178 rx_PutConnection(callp);
3180 } while (cm_Analyze(connp, userp, reqp,
3181 &dscp->fid, &volSync, NULL, NULL, code));
3182 code = cm_MapRPCErrorRmdir(code, reqp);
3185 osi_Log1(afsd_logp, "CALL RemoveDir FAILURE, code 0x%x", code);
3187 osi_Log0(afsd_logp, "CALL RemoveDir SUCCESS");
3190 lock_ObtainWrite(&dirop.scp->dirlock);
3191 dirop.lockType = CM_DIRLOCK_WRITE;
3193 lock_ObtainWrite(&dscp->rw);
3194 cm_SyncOpDone(dscp, NULL, CM_SCACHESYNC_STOREDATA);
3196 cm_dnlcRemove(dscp, namep);
3197 cm_MergeStatus(NULL, dscp, &updatedDirStatus, &volSync, userp, CM_MERGEFLAG_DIROP);
3199 lock_ReleaseWrite(&dscp->rw);
3202 if (cm_CheckDirOpForSingleChange(&dirop)) {
3203 cm_DirDeleteEntry(&dirop, namep);
3205 cm_BPlusDirDeleteEntry(&dirop, namep);
3209 cm_EndDirOp(&dirop);
3211 /* and return error code */
3215 long cm_Open(cm_scache_t *scp, int type, cm_user_t *userp)
3217 /* grab mutex on contents */
3218 lock_ObtainWrite(&scp->rw);
3220 /* reset the prefetch info */
3221 scp->prefetch.base.LowPart = 0; /* base */
3222 scp->prefetch.base.HighPart = 0;
3223 scp->prefetch.end.LowPart = 0; /* and end */
3224 scp->prefetch.end.HighPart = 0;
3226 /* release mutex on contents */
3227 lock_ReleaseWrite(&scp->rw);
3233 long cm_Rename(cm_scache_t *oldDscp, char *oldNamep, cm_scache_t *newDscp,
3234 char *newNamep, cm_user_t *userp, cm_req_t *reqp)
3238 AFSFid oldDirAFSFid;
3239 AFSFid newDirAFSFid;
3241 AFSFetchStatus updatedOldDirStatus;
3242 AFSFetchStatus updatedNewDirStatus;
3245 struct rx_connection * callp;
3246 cm_dirOp_t oldDirOp;
3249 cm_dirOp_t newDirOp;
3251 /* before starting the RPC, mark that we're changing the directory data,
3252 * so that someone who does a chmod on the dir will wait until our call
3253 * completes. We do this in vnode order so that we don't deadlock,
3254 * which makes the code a little verbose.
3256 if (oldDscp == newDscp) {
3257 /* check for identical names */
3258 if (strcmp(oldNamep, newNamep) == 0)
3259 return CM_ERROR_RENAME_IDENTICAL;
3262 cm_BeginDirOp(oldDscp, userp, reqp, CM_DIRLOCK_NONE, &oldDirOp);
3263 lock_ObtainWrite(&oldDscp->rw);
3264 cm_dnlcRemove(oldDscp, oldNamep);
3265 cm_dnlcRemove(oldDscp, newNamep);
3266 code = cm_SyncOp(oldDscp, NULL, userp, reqp, 0,
3267 CM_SCACHESYNC_STOREDATA);
3268 lock_ReleaseWrite(&oldDscp->rw);
3270 cm_EndDirOp(&oldDirOp);
3274 /* two distinct dir vnodes */
3276 if (oldDscp->fid.cell != newDscp->fid.cell ||
3277 oldDscp->fid.volume != newDscp->fid.volume)
3278 return CM_ERROR_CROSSDEVLINK;
3280 /* shouldn't happen that we have distinct vnodes for two
3281 * different files, but could due to deliberate attack, or
3282 * stale info. Avoid deadlocks and quit now.
3284 if (oldDscp->fid.vnode == newDscp->fid.vnode)
3285 return CM_ERROR_CROSSDEVLINK;
3287 if (oldDscp->fid.vnode < newDscp->fid.vnode) {
3288 cm_BeginDirOp(oldDscp, userp, reqp, CM_DIRLOCK_NONE, &oldDirOp);
3289 lock_ObtainWrite(&oldDscp->rw);
3290 cm_dnlcRemove(oldDscp, oldNamep);
3291 code = cm_SyncOp(oldDscp, NULL, userp, reqp, 0,
3292 CM_SCACHESYNC_STOREDATA);
3293 lock_ReleaseWrite(&oldDscp->rw);
3295 cm_EndDirOp(&oldDirOp);
3297 cm_BeginDirOp(newDscp, userp, reqp, CM_DIRLOCK_NONE, &newDirOp);
3298 lock_ObtainWrite(&newDscp->rw);
3299 cm_dnlcRemove(newDscp, newNamep);
3300 code = cm_SyncOp(newDscp, NULL, userp, reqp, 0,
3301 CM_SCACHESYNC_STOREDATA);
3302 lock_ReleaseWrite(&newDscp->rw);
3304 cm_EndDirOp(&newDirOp);
3306 /* cleanup first one */
3307 lock_ObtainWrite(&oldDscp->rw);
3308 cm_SyncOpDone(oldDscp, NULL,
3309 CM_SCACHESYNC_STOREDATA);
3310 lock_ReleaseWrite(&oldDscp->rw);
3311 cm_EndDirOp(&oldDirOp);
3316 /* lock the new vnode entry first */
3317 cm_BeginDirOp(newDscp, userp, reqp, CM_DIRLOCK_NONE, &newDirOp);
3318 lock_ObtainWrite(&newDscp->rw);
3319 cm_dnlcRemove(newDscp, newNamep);
3320 code = cm_SyncOp(newDscp, NULL, userp, reqp, 0,
3321 CM_SCACHESYNC_STOREDATA);
3322 lock_ReleaseWrite(&newDscp->rw);
3324 cm_EndDirOp(&newDirOp);
3326 cm_BeginDirOp(oldDscp, userp, reqp, CM_DIRLOCK_NONE, &oldDirOp);
3327 lock_ObtainWrite(&oldDscp->rw);
3328 cm_dnlcRemove(oldDscp, oldNamep);
3329 code = cm_SyncOp(oldDscp, NULL, userp, reqp, 0,
3330 CM_SCACHESYNC_STOREDATA);
3331 lock_ReleaseWrite(&oldDscp->rw);
3333 cm_EndDirOp(&oldDirOp);
3335 /* cleanup first one */
3336 lock_ObtainWrite(&newDscp->rw);
3337 cm_SyncOpDone(newDscp, NULL,
3338 CM_SCACHESYNC_STOREDATA);
3339 lock_ReleaseWrite(&newDscp->rw);
3340 cm_EndDirOp(&newDirOp);
3344 } /* two distinct vnodes */
3351 /* try the RPC now */
3352 osi_Log2(afsd_logp, "CALL Rename old scp 0x%p new scp 0x%p",
3355 code = cm_ConnFromFID(&oldDscp->fid, userp, reqp, &connp);
3359 oldDirAFSFid.Volume = oldDscp->fid.volume;
3360 oldDirAFSFid.Vnode = oldDscp->fid.vnode;
3361 oldDirAFSFid.Unique = oldDscp->fid.unique;
3362 newDirAFSFid.Volume = newDscp->fid.volume;
3363 newDirAFSFid.Vnode = newDscp->fid.vnode;
3364 newDirAFSFid.Unique = newDscp->fid.unique;
3366 callp = cm_GetRxConn(connp);
3367 code = RXAFS_Rename(callp, &oldDirAFSFid, oldNamep,
3368 &newDirAFSFid, newNamep,
3369 &updatedOldDirStatus, &updatedNewDirStatus,
3371 rx_PutConnection(callp);
3373 } while (cm_Analyze(connp, userp, reqp, &oldDscp->fid,
3374 &volSync, NULL, NULL, code));
3375 code = cm_MapRPCError(code, reqp);
3378 osi_Log1(afsd_logp, "CALL Rename FAILURE, code 0x%x", code);
3380 osi_Log0(afsd_logp, "CALL Rename SUCCESS");
3382 /* update the individual stat cache entries for the directories */
3384 lock_ObtainWrite(&oldDirOp.scp->dirlock);
3385 oldDirOp.lockType = CM_DIRLOCK_WRITE;
3387 lock_ObtainWrite(&oldDscp->rw);
3388 cm_SyncOpDone(oldDscp, NULL, CM_SCACHESYNC_STOREDATA);
3391 cm_MergeStatus(NULL, oldDscp, &updatedOldDirStatus, &volSync,
3392 userp, CM_MERGEFLAG_DIROP);
3393 lock_ReleaseWrite(&oldDscp->rw);
3396 if (cm_CheckDirOpForSingleChange(&oldDirOp)) {
3399 diropCode = cm_BPlusDirLookup(&oldDirOp, oldNamep, &fileFid);
3400 if (diropCode == CM_ERROR_INEXACT_MATCH)
3402 else if (diropCode == EINVAL)
3404 diropCode = cm_DirLookup(&oldDirOp, oldNamep, &fileFid);
3406 if (diropCode == 0) {
3408 diropCode = cm_DirCreateEntry(&oldDirOp, newNamep, &fileFid);
3410 cm_BPlusDirCreateEntry(&oldDirOp, newNamep, &fileFid);
3414 if (diropCode == 0) {
3415 diropCode = cm_DirDeleteEntry(&oldDirOp, oldNamep);
3417 cm_BPlusDirDeleteEntry(&oldDirOp, oldNamep);
3423 cm_EndDirOp(&oldDirOp);
3425 /* and update it for the new one, too, if necessary */
3428 lock_ObtainWrite(&newDirOp.scp->dirlock);
3429 newDirOp.lockType = CM_DIRLOCK_WRITE;
3431 lock_ObtainWrite(&newDscp->rw);
3432 cm_SyncOpDone(newDscp, NULL, CM_SCACHESYNC_STOREDATA);
3434 cm_MergeStatus(NULL, newDscp, &updatedNewDirStatus, &volSync,
3435 userp, CM_MERGEFLAG_DIROP);
3436 lock_ReleaseWrite(&newDscp->rw);
3439 /* we only make the local change if we successfully made
3440 the change in the old directory AND there was only one
3441 change in the new directory */
3442 if (diropCode == 0 && cm_CheckDirOpForSingleChange(&newDirOp)) {
3443 cm_DirCreateEntry(&newDirOp, newNamep, &fileFid);
3445 cm_BPlusDirCreateEntry(&newDirOp, newNamep, &fileFid);
3449 cm_EndDirOp(&newDirOp);
3452 /* and return error code */
3456 /* Byte range locks:
3458 The OpenAFS Windows client has to fake byte range locks given no
3459 server side support for such locks. This is implemented as keyed
3460 byte range locks on the cache manager.
3462 Keyed byte range locks:
3464 Each cm_scache_t structure keeps track of a list of keyed locks.
3465 The key for a lock identifies an owner of a set of locks (referred
3466 to as a client). Each key is represented by a value. The set of
3467 key values used within a specific cm_scache_t structure form a
3468 namespace that has a scope of just that cm_scache_t structure. The
3469 same key value can be used with another cm_scache_t structure and
3470 correspond to a completely different client. However it is
3471 advantageous for the SMB or IFS layer to make sure that there is a
3472 1-1 mapping between client and keys over all cm_scache_t objects.
3474 Assume a client C has key Key(C) (although, since the scope of the
3475 key is a cm_scache_t, the key can be Key(C,S), where S is the
3476 cm_scache_t. But assume a 1-1 relation between keys and clients).
3477 A byte range (O,+L) denotes byte addresses (O) through (O+L-1)
3478 inclusive (a.k.a. [O,O+L-1]). The function Key(x) is implemented
3479 through cm_generateKey() function for both SMB and IFS.
3481 The list of locks for a cm_scache_t object S is maintained in
3482 S->fileLocks. The cache manager will set a lock on the AFS file
3483 server in order to assert the locks in S->fileLocks. If only
3484 shared locks are in place for S, then the cache manager will obtain
3485 a LockRead lock, while if there are any exclusive locks, it will
3486 obtain a LockWrite lock. If the exclusive locks are all released
3487 while the shared locks remain, then the cache manager will
3488 downgrade the lock from LockWrite to LockRead. Similarly, if an
3489 exclusive lock is obtained when only shared locks exist, then the
3490 cache manager will try to upgrade the lock from LockRead to
3493 Each lock L owned by client C maintains a key L->key such that
3494 L->key == Key(C), the effective range defined by L->LOffset and
3495 L->LLength such that the range of bytes affected by the lock is
3496 (L->LOffset, +L->LLength), a type maintained in L->LockType which
3497 is either exclusive or shared.
3501 A lock exists iff it is in S->fileLocks for some cm_scache_t
3502 S. Existing locks are in one of the following states: ACTIVE,
3503 WAITLOCK, WAITUNLOCK, LOST, DELETED.
3505 The following sections describe each lock and the associated
3508 1. ACTIVE: A lock L is ACTIVE iff the cache manager has asserted
3509 the lock with the AFS file server. This type of lock can be
3510 exercised by a client to read or write to the locked region (as
3513 1.1 ACTIVE->LOST: When the AFS file server fails to extend a
3514 server lock that was required to assert the lock. Before
3515 marking the lock as lost, the cache manager checks if the file
3516 has changed on the server. If the file has not changed, then
3517 the cache manager will attempt to obtain a new server lock
3518 that is sufficient to assert the client side locks for the
3519 file. If any of these fail, the lock is marked as LOST.
3520 Otherwise, it is left as ACTIVE.
3522 1.2 ACTIVE->DELETED: Lock is released.
3524 2. WAITLOCK: A lock is in a WAITLOCK state if the cache manager
3525 grants the lock but the lock is yet to be asserted with the AFS
3526 file server. Once the file server grants the lock, the state
3527 will transition to an ACTIVE lock.
3529 2.1 WAITLOCK->ACTIVE: The server granted the lock.
3531 2.2 WAITLOCK->DELETED: Lock is abandoned, or timed out during
3534 2.3 WAITLOCK->LOST: One or more locks from this client were
3535 marked as LOST. No further locks will be granted to this
3536 client until all lost locks are removed.
3538 3. WAITUNLOCK: A lock is in a WAITUNLOCK state if the cache manager
3539 receives a request for a lock that conflicts with an existing
3540 ACTIVE or WAITLOCK lock. The lock will be placed in the queue
3541 and will be granted at such time the conflicting locks are
3542 removed, at which point the state will transition to either
3545 3.1 WAITUNLOCK->ACTIVE: The conflicting lock was removed. The
3546 current serverLock is sufficient to assert this lock, or a
3547 sufficient serverLock is obtained.
3549 3.2 WAITUNLOCK->WAITLOCK: The conflicting lock was removed,
3550 however the required serverLock is yet to be asserted with the
3553 3.3 WAITUNLOCK->DELETED: The lock is abandoned, timed out or
3556 3.5 WAITUNLOCK->LOST: One or more locks from this client were
3557 marked as LOST. No further locks will be granted to this
3558 client until all lost locks are removed.
3560 4. LOST: A lock L is LOST if the server lock that was required to
3561 assert the lock could not be obtained or if it could not be
3562 extended, or if other locks by the same client were LOST.
3563 Essentially, once a lock is LOST, the contract between the cache
3564 manager and that specific client is no longer valid.
3566 The cache manager rechecks the server lock once every minute and
3567 extends it as appropriate. If this is not done for 5 minutes,
3568 the AFS file server will release the lock (the 5 minute timeout
3569 is based on current file server code and is fairly arbitrary).
3570 Once released, the lock cannot be re-obtained without verifying
3571 that the contents of the file hasn't been modified since the
3572 time the lock was released. Re-obtaining the lock without
3573 verifying this may lead to data corruption. If the lock can not
3574 be obtained safely, then all active locks for the cm_scache_t
3577 4.1 LOST->DELETED: The lock is released.
3579 5. DELETED: The lock is no longer relevant. Eventually, it will
3580 get removed from the cm_scache_t. In the meantime, it will be
3581 treated as if it does not exist.
3583 5.1 DELETED->not exist: The lock is removed from the
3586 The following are classifications of locks based on their state.
3588 6* A lock L is ACCEPTED if it is ACTIVE or WAITLOCK. These locks
3589 have been accepted by the cache manager, but may or may not have
3590 been granted back to the client.
3592 7* A lock L is QUEUED if it is ACTIVE, WAITLOCK or WAITUNLOCK.
3594 8* A lock L is WAITING if it is WAITLOCK or WAITUNLOCK.
3598 A client C can READ range (Offset,+Length) of a file represented by
3599 cm_scache_t S iff (1):
3601 1. for all _a_ in (Offset,+Length), all of the following is true:
3603 1.1 For each ACTIVE lock L in S->fileLocks such that _a_ in
3604 (L->LOffset,+L->LLength); L->key == Key(C) OR L->LockType is
3607 1.2 For each LOST lock L in S->fileLocks such that _a_ in
3608 (L->LOffset,+L->LLength); L->LockType is shared AND L->key !=
3611 (When locks are lost on an cm_scache_t, all locks are lost. By
3612 4.2 (below), if there is an exclusive LOST lock, then there
3613 can't be any overlapping ACTIVE locks.)
3615 A client C can WRITE range (Offset,+Length) of cm_scache_t S iff (2):
3617 2. for all _a_ in (Offset,+Length), one of the following is true:
3619 2.1 Byte _a_ of S is unowned (as specified in 1.1) AND there
3620 does not exist a LOST lock L such that _a_ in
3621 (L->LOffset,+L->LLength).
3623 2.2 Byte _a_ of S is owned by C under lock L (as specified in
3624 1.2) AND L->LockType is exclusive.
3626 A client C can OBTAIN a lock L on cm_scache_t S iff (both 3 and 4):
3628 3. for all _a_ in (L->LOffset,+L->LLength), ALL of the following is
3631 3.1 If L->LockType is exclusive then there does NOT exist a
3632 ACCEPTED lock M in S->fileLocks such that _a_ in
3633 (M->LOffset,+M->LLength).
3635 (If we count all QUEUED locks then we hit cases such as
3636 cascading waiting locks where the locks later on in the queue
3637 can be granted without compromising file integrity. On the
3638 other hand if only ACCEPTED locks are considered, then locks
3639 that were received earlier may end up waiting for locks that
3640 were received later to be unlocked. The choice of ACCEPTED
3641 locks was made to mimic the Windows byte range lock
3644 3.2 If L->LockType is shared then for each ACCEPTED lock M in
3645 S->fileLocks, if _a_ in (M->LOffset,+M->LLength) then
3646 M->LockType is shared.
3648 4. For all LOST locks M in S->fileLocks, ALL of the following are true:
3650 4.1 M->key != Key(C)
3652 4.2 If M->LockType is exclusive, then (L->LOffset,+L->LLength)
3653 and (M->LOffset,+M->LLength) do not intersect.
3655 (Note: If a client loses a lock, it loses all locks.
3656 Subsequently, it will not be allowed to obtain any more locks
3657 until all existing LOST locks that belong to the client are
3658 released. Once all locks are released by a single client,
3659 there exists no further contract between the client and AFS
3660 about the contents of the file, hence the client can then
3661 proceed to obtain new locks and establish a new contract.
3663 This doesn't quite work as you think it should, because most
3664 applications aren't built to deal with losing locks they
3665 thought they once had. For now, we don't have a good
3666 solution to lost locks.
3668 Also, for consistency reasons, we have to hold off on
3669 granting locks that overlap exclusive LOST locks.)
3671 A client C can only unlock locks L in S->fileLocks which have
3674 The representation and invariants are as follows:
3676 - Each cm_scache_t structure keeps:
3678 - A queue of byte-range locks (cm_scache_t::fileLocks) which
3679 are of type cm_file_lock_t.
3681 - A record of the highest server-side lock that has been
3682 obtained for this object (cm_scache_t::serverLock), which is
3683 one of (-1), LockRead, LockWrite.
3685 - A count of ACCEPTED exclusive and shared locks that are in the
3686 queue (cm_scache_t::sharedLocks and
3687 cm_scache_t::exclusiveLocks)
3689 - Each cm_file_lock_t structure keeps:
3691 - The type of lock (cm_file_lock_t::LockType)
3693 - The key associated with the lock (cm_file_lock_t::key)
3695 - The offset and length of the lock (cm_file_lock_t::LOffset
3696 and cm_file_lock_t::LLength)
3698 - The state of the lock.
3700 - Time of issuance or last successful extension
3702 Semantic invariants:
3704 I1. The number of ACCEPTED locks in S->fileLocks are
3705 (S->sharedLocks + S->exclusiveLocks)
3707 External invariants:
3709 I3. S->serverLock is the lock that we have asserted with the
3710 AFS file server for this cm_scache_t.
3712 I4. S->serverLock == LockRead iff there is at least one ACTIVE
3713 shared lock, but no ACTIVE exclusive locks.
3715 I5. S->serverLock == LockWrite iff there is at least one ACTIVE
3718 I6. If L is a LOST lock, then for each lock M in S->fileLocks,
3719 M->key == L->key IMPLIES M is LOST or DELETED.
3724 #define IS_LOCK_ACTIVE(lockp) (((lockp)->flags & (CM_FILELOCK_FLAG_DELETED|CM_FILELOCK_FLAG_WAITLOCK|CM_FILELOCK_FLAG_WAITUNLOCK|CM_FILELOCK_FLAG_LOST)) == 0)
3726 #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)
3728 #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)
3730 #define IS_LOCK_LOST(lockp) (((lockp)->flags & (CM_FILELOCK_FLAG_DELETED|CM_FILELOCK_FLAG_LOST)) == CM_FILELOCK_FLAG_LOST)
3732 #define IS_LOCK_DELETED(lockp) (((lockp)->flags & CM_FILELOCK_FLAG_DELETED) == CM_FILELOCK_FLAG_DELETED)
3735 #define IS_LOCK_ACCEPTED(lockp) (IS_LOCK_ACTIVE(lockp) || IS_LOCK_WAITLOCK(lockp))
3738 #define IS_LOCK_CLIENTONLY(lockp) ((((lockp)->scp->flags & CM_SCACHEFLAG_RO) == CM_SCACHEFLAG_RO) || (((lockp)->flags & CM_FILELOCK_FLAG_CLIENTONLY) == CM_FILELOCK_FLAG_CLIENTONLY))
3741 #define INTERSECT_RANGE(r1,r2) (((r2).offset+(r2).length) > (r1).offset && ((r1).offset +(r1).length) > (r2).offset)
3744 #define CONTAINS_RANGE(r1,r2) (((r2).offset+(r2).length) <= ((r1).offset+(r1).length) && (r1).offset <= (r2).offset)
3746 #if defined(VICED_CAPABILITY_USE_BYTE_RANGE_LOCKS) && !defined(LOCK_TESTING)
3747 #define SCP_SUPPORTS_BRLOCKS(scp) ((scp)->cbServerp && ((scp)->cbServerp->capabilities & VICED_CAPABILITY_USE_BYTE_RANGE_LOCKS))
3749 #define SCP_SUPPORTS_BRLOCKS(scp) (1)
3752 #define SERVERLOCKS_ENABLED(scp) (!((scp)->flags & CM_SCACHEFLAG_RO) && cm_enableServerLocks && SCP_SUPPORTS_BRLOCKS(scp))
3754 #if defined(VICED_CAPABILITY_WRITELOCKACL)
3755 #define SCP_SUPPORTS_WRITELOCKACL(scp) ((scp)->cbServerp && ((scp->cbServerp->capabilities & VICED_CAPABILITY_WRITELOCKACL)))
3757 #define SCP_SUPPORTS_WRITELOCKACL(scp) (0)
3759 /* This should really be defined in any build that this code is being
3761 #error VICED_CAPABILITY_WRITELOCKACL not defined.
3764 static void cm_LockRangeSubtract(cm_range_t * pos, const cm_range_t * neg)
3766 afs_int64 int_begin;
3769 int_begin = MAX(pos->offset, neg->offset);
3770 int_end = MIN(pos->offset+pos->length, neg->offset+neg->length);
3772 if (int_begin < int_end) {
3773 if (int_begin == pos->offset) {
3774 pos->length = pos->offset + pos->length - int_end;
3775 pos->offset = int_end;
3776 } else if (int_end == pos->offset + pos->length) {
3777 pos->length = int_begin - pos->offset;
3780 /* We only subtract ranges if the resulting range is
3781 contiguous. If we try to support non-contigous ranges, we
3782 aren't actually improving performance. */
3786 /* Called with scp->rw held. Returns 0 if all is clear to read the
3787 specified range by the client identified by key.
3789 long cm_LockCheckRead(cm_scache_t *scp,
3790 LARGE_INTEGER LOffset,
3791 LARGE_INTEGER LLength,
3794 #ifndef ADVISORY_LOCKS
3796 cm_file_lock_t *fileLock;
3800 int substract_ranges = FALSE;
3802 range.offset = LOffset.QuadPart;
3803 range.length = LLength.QuadPart;
3807 1. for all _a_ in (Offset,+Length), all of the following is true:
3809 1.1 For each ACTIVE lock L in S->fileLocks such that _a_ in
3810 (L->LOffset,+L->LLength); L->key == Key(C) OR L->LockType is
3813 1.2 For each LOST lock L in S->fileLocks such that _a_ in
3814 (L->LOffset,+L->LLength); L->LockType is shared AND L->key !=
3819 lock_ObtainRead(&cm_scacheLock);
3821 for (q = scp->fileLocksH; q && range.length > 0; q = osi_QNext(q)) {
3823 (cm_file_lock_t *)((char *) q - offsetof(cm_file_lock_t, fileq));
3825 if (INTERSECT_RANGE(range, fileLock->range)) {
3826 if (IS_LOCK_ACTIVE(fileLock)) {
3827 if (fileLock->key == key) {
3829 /* If there is an active lock for this client, it
3830 is safe to substract ranges.*/
3831 cm_LockRangeSubtract(&range, &fileLock->range);
3832 substract_ranges = TRUE;
3834 if (fileLock->lockType != LockRead) {
3835 code = CM_ERROR_LOCK_CONFLICT;
3839 /* even if the entire range is locked for reading,
3840 we still can't grant the lock at this point
3841 because the client may have lost locks. That
3842 is, unless we have already seen an active lock
3843 belonging to the client, in which case there
3844 can't be any lost locks for this client. */
3845 if (substract_ranges)
3846 cm_LockRangeSubtract(&range, &fileLock->range);
3848 } else if (IS_LOCK_LOST(fileLock) &&
3849 (fileLock->key == key || fileLock->lockType == LockWrite)) {
3850 code = CM_ERROR_BADFD;
3856 lock_ReleaseRead(&cm_scacheLock);
3858 osi_Log4(afsd_logp, "cm_LockCheckRead scp 0x%x offset %d length %d code 0x%x",
3859 scp, (unsigned long)LOffset.QuadPart, (unsigned long)LLength.QuadPart, code);
3870 /* Called with scp->rw held. Returns 0 if all is clear to write the
3871 specified range by the client identified by key.
3873 long cm_LockCheckWrite(cm_scache_t *scp,
3874 LARGE_INTEGER LOffset,
3875 LARGE_INTEGER LLength,
3878 #ifndef ADVISORY_LOCKS
3880 cm_file_lock_t *fileLock;
3885 range.offset = LOffset.QuadPart;
3886 range.length = LLength.QuadPart;
3889 A client C can WRITE range (Offset,+Length) of cm_scache_t S iff (2):
3891 2. for all _a_ in (Offset,+Length), one of the following is true:
3893 2.1 Byte _a_ of S is unowned AND there does not exist a LOST
3894 lock L such that _a_ in (L->LOffset,+L->LLength).
3896 2.2 Byte _a_ of S is owned by C under lock L AND L->LockType is
3900 lock_ObtainRead(&cm_scacheLock);
3902 for (q = scp->fileLocksH; q && range.length > 0; q = osi_QNext(q)) {
3904 (cm_file_lock_t *)((char *) q - offsetof(cm_file_lock_t, fileq));
3906 if (INTERSECT_RANGE(range, fileLock->range)) {
3907 if (IS_LOCK_ACTIVE(fileLock)) {
3908 if (fileLock->key == key) {
3909 if (fileLock->lockType == LockWrite) {
3911 /* if there is an active lock for this client, it
3912 is safe to substract ranges */
3913 cm_LockRangeSubtract(&range, &fileLock->range);
3915 code = CM_ERROR_LOCK_CONFLICT;
3919 code = CM_ERROR_LOCK_CONFLICT;
3922 } else if (IS_LOCK_LOST(fileLock)) {
3923 code = CM_ERROR_BADFD;
3929 lock_ReleaseRead(&cm_scacheLock);
3931 osi_Log4(afsd_logp, "cm_LockCheckWrite scp 0x%x offset %d length %d code 0x%x",
3932 scp, (unsigned long)LOffset.QuadPart, (unsigned long)LLength.QuadPart, code);
3943 /* Called with cm_scacheLock write locked */
3944 static cm_file_lock_t * cm_GetFileLock(void) {
3947 l = (cm_file_lock_t *) cm_freeFileLocks;
3949 osi_QRemove(&cm_freeFileLocks, &l->q);
3951 l = malloc(sizeof(cm_file_lock_t));
3952 osi_assertx(l, "null cm_file_lock_t");
3955 memset(l, 0, sizeof(cm_file_lock_t));
3960 /* Called with cm_scacheLock write locked */
3961 static void cm_PutFileLock(cm_file_lock_t *l) {
3962 osi_QAdd(&cm_freeFileLocks, &l->q);
3965 /* called with scp->rw held. May release it during processing, but
3966 leaves it held on exit. */
3967 long cm_IntSetLock(cm_scache_t * scp, cm_user_t * userp, int lockType,
3973 struct rx_connection * callp;
3975 afs_uint32 reqflags = reqp->flags;
3977 tfid.Volume = scp->fid.volume;
3978 tfid.Vnode = scp->fid.vnode;
3979 tfid.Unique = scp->fid.unique;
3982 osi_Log2(afsd_logp, "CALL SetLock scp 0x%p for lock %d", scp, lockType);
3984 reqp->flags |= CM_REQ_NORETRY;
3985 lock_ReleaseWrite(&scp->rw);
3988 code = cm_ConnFromFID(&cfid, userp, reqp, &connp);
3992 callp = cm_GetRxConn(connp);
3993 code = RXAFS_SetLock(callp, &tfid, lockType,
3995 rx_PutConnection(callp);
3997 } while (cm_Analyze(connp, userp, reqp, &cfid, &volSync,
4000 code = cm_MapRPCError(code, reqp);
4002 osi_Log1(afsd_logp, "CALL SetLock FAILURE, code 0x%x", code);
4004 osi_Log0(afsd_logp, "CALL SetLock SUCCESS");
4007 lock_ObtainWrite(&scp->rw);
4008 reqp->flags = reqflags;
4012 /* called with scp->rw held. Releases it during processing */
4013 long cm_IntReleaseLock(cm_scache_t * scp, cm_user_t * userp,
4019 struct rx_connection * callp;
4022 tfid.Volume = scp->fid.volume;
4023 tfid.Vnode = scp->fid.vnode;
4024 tfid.Unique = scp->fid.unique;
4027 lock_ReleaseWrite(&scp->rw);
4029 osi_Log1(afsd_logp, "CALL ReleaseLock scp 0x%p", scp);
4032 code = cm_ConnFromFID(&cfid, userp, reqp, &connp);
4036 callp = cm_GetRxConn(connp);
4037 code = RXAFS_ReleaseLock(callp, &tfid, &volSync);
4038 rx_PutConnection(callp);
4040 } while (cm_Analyze(connp, userp, reqp, &cfid, &volSync,
4042 code = cm_MapRPCError(code, reqp);
4045 "CALL ReleaseLock FAILURE, code 0x%x", code);
4048 "CALL ReleaseLock SUCCESS");
4050 lock_ObtainWrite(&scp->rw);
4055 /* called with scp->rw held. May release it during processing, but
4056 will exit with lock held.
4060 - 0 if the user has permission to get the specified lock for the scp
4062 - CM_ERROR_NOACCESS if not
4064 Any other error from cm_SyncOp will be sent down untranslated.
4066 If CM_ERROR_NOACCESS is returned and lock_type is LockRead, then
4067 phas_insert (if non-NULL) will receive a boolean value indicating
4068 whether the user has INSERT permission or not.
4070 long cm_LockCheckPerms(cm_scache_t * scp,
4077 long code = 0, code2 = 0;
4079 /* lock permissions are slightly tricky because of the 'i' bit.
4080 If the user has PRSFS_LOCK, she can read-lock the file. If the
4081 user has PRSFS_WRITE, she can write-lock the file. However, if
4082 the user has PRSFS_INSERT, then she can write-lock new files,
4083 but not old ones. Since we don't have information about
4084 whether a file is new or not, we assume that if the user owns
4085 the scp, then she has the permissions that are granted by
4088 osi_Log3(afsd_logp, "cm_LockCheckPerms for scp[0x%p] type[%d] user[0x%p]",
4089 scp, lock_type, userp);
4091 if (lock_type == LockRead)
4092 rights |= PRSFS_LOCK;
4093 else if (lock_type == LockWrite)
4094 rights |= PRSFS_WRITE | PRSFS_LOCK;
4097 osi_assertx(FALSE, "invalid lock type");
4102 *phas_insert = FALSE;
4104 code = cm_SyncOp(scp, NULL, userp, reqp, rights,
4105 CM_SCACHESYNC_GETSTATUS |
4106 CM_SCACHESYNC_NEEDCALLBACK);
4108 if (phas_insert && scp->creator == userp) {
4110 /* If this file was created by the user, then we check for
4111 PRSFS_INSERT. If the file server is recent enough, then
4112 this should be sufficient for her to get a write-lock (but
4113 not necessarily a read-lock). VICED_CAPABILITY_WRITELOCKACL
4114 indicates whether a file server supports getting write
4115 locks when the user only has PRSFS_INSERT.
4117 If the file was not created by the user we skip the check
4118 because the INSERT bit will not apply to this user even
4122 code2 = cm_SyncOp(scp, NULL, userp, reqp, PRSFS_INSERT,
4123 CM_SCACHESYNC_GETSTATUS |
4124 CM_SCACHESYNC_NEEDCALLBACK);
4126 if (code2 == CM_ERROR_NOACCESS) {
4127 osi_Log0(afsd_logp, "cm_LockCheckPerms user has no INSERT bits");
4129 *phas_insert = TRUE;
4130 osi_Log0(afsd_logp, "cm_LockCheckPerms user has INSERT bits");
4134 cm_SyncOpDone(scp, NULL, CM_SCACHESYNC_NEEDCALLBACK | CM_SCACHESYNC_GETSTATUS);
4136 osi_Log1(afsd_logp, "cm_LockCheckPerms returning code %d", code);
4141 /* called with scp->rw held */
4142 long cm_Lock(cm_scache_t *scp, unsigned char sLockType,
4143 LARGE_INTEGER LOffset, LARGE_INTEGER LLength,
4145 int allowWait, cm_user_t *userp, cm_req_t *reqp,
4146 cm_file_lock_t **lockpp)
4149 int Which = ((sLockType & LOCKING_ANDX_SHARED_LOCK) ? LockRead : LockWrite);
4150 cm_file_lock_t *fileLock;
4153 int wait_unlock = FALSE;
4154 int force_client_lock = FALSE;
4156 osi_Log4(afsd_logp, "cm_Lock scp 0x%x type 0x%x offset %d length %d",
4157 scp, sLockType, (unsigned long)LOffset.QuadPart, (unsigned long)LLength.QuadPart);
4158 osi_Log3(afsd_logp, "... allowWait %d key 0x%x:%x", allowWait,
4159 (unsigned long)(key >> 32), (unsigned long)(key & 0xffffffff));
4162 A client C can OBTAIN a lock L on cm_scache_t S iff (both 3 and 4):
4164 3. for all _a_ in (L->LOffset,+L->LLength), ALL of the following is
4167 3.1 If L->LockType is exclusive then there does NOT exist a
4168 ACCEPTED lock M in S->fileLocks such that _a_ in
4169 (M->LOffset,+M->LLength).
4171 3.2 If L->LockType is shared then for each ACCEPTED lock M in
4172 S->fileLocks, if _a_ in (M->LOffset,+M->LLength) then
4173 M->LockType is shared.
4175 4. For all LOST locks M in S->fileLocks, ALL of the following are true:
4177 4.1 M->key != Key(C)
4179 4.2 If M->LockType is exclusive, then (L->LOffset,+L->LLength)
4180 and (M->LOffset,+M->LLength) do not intersect.
4183 range.offset = LOffset.QuadPart;
4184 range.length = LLength.QuadPart;
4186 lock_ObtainRead(&cm_scacheLock);
4188 for (q = scp->fileLocksH; q; q = osi_QNext(q)) {
4190 (cm_file_lock_t *)((char *) q - offsetof(cm_file_lock_t, fileq));
4192 if (IS_LOCK_LOST(fileLock)) {
4193 if (fileLock->key == key) {
4194 code = CM_ERROR_BADFD;
4196 } else if (fileLock->lockType == LockWrite && INTERSECT_RANGE(range, fileLock->range)) {
4197 code = CM_ERROR_WOULDBLOCK;
4203 /* we don't need to check for deleted locks here since deleted
4204 locks are dequeued from scp->fileLocks */
4205 if (IS_LOCK_ACCEPTED(fileLock) &&
4206 INTERSECT_RANGE(range, fileLock->range)) {
4208 if ((sLockType & LOCKING_ANDX_SHARED_LOCK) == 0 ||
4209 fileLock->lockType != LockRead) {
4211 code = CM_ERROR_WOULDBLOCK;
4217 lock_ReleaseRead(&cm_scacheLock);
4219 if (code == 0 && SERVERLOCKS_ENABLED(scp)) {
4220 if (Which == scp->serverLock ||
4221 (Which == LockRead && scp->serverLock == LockWrite)) {
4225 /* we already have the lock we need */
4226 osi_Log3(afsd_logp, " we already have the correct lock. exclusives[%d], shared[%d], serverLock[%d]",
4227 scp->exclusiveLocks, scp->sharedLocks, (int)(signed char) scp->serverLock);
4229 code = cm_LockCheckPerms(scp, Which, userp, reqp, &has_insert);
4231 /* special case: if we don't have permission to read-lock
4232 the file, then we force a clientside lock. This is to
4233 compensate for applications that obtain a read-lock for
4234 reading files off of directories that don't grant
4235 read-locks to the user. */
4236 if (code == CM_ERROR_NOACCESS && Which == LockRead) {
4238 if (has_insert && SCP_SUPPORTS_WRITELOCKACL(scp)) {
4239 osi_Log0(afsd_logp, " User has no read-lock perms, but has INSERT perms.");
4242 osi_Log0(afsd_logp, " User has no read-lock perms. Forcing client-side lock");
4243 force_client_lock = TRUE;
4247 } else if ((scp->exclusiveLocks > 0) ||
4248 (scp->sharedLocks > 0 && scp->serverLock != LockRead)) {
4251 /* We are already waiting for some other lock. We should
4252 wait for the daemon to catch up instead of generating a
4253 flood of SetLock calls. */
4254 osi_Log3(afsd_logp, " already waiting for other lock. exclusives[%d], shared[%d], serverLock[%d]",
4255 scp->exclusiveLocks, scp->sharedLocks, (int)(signed char) scp->serverLock);
4257 /* see if we have permission to create the lock in the
4259 code = cm_LockCheckPerms(scp, Which, userp, reqp, &has_insert);
4261 code = CM_ERROR_WOULDBLOCK;
4262 else if (code == CM_ERROR_NOACCESS && Which == LockRead) {
4264 if (has_insert && SCP_SUPPORTS_WRITELOCKACL(scp)) {
4266 " User has no read-lock perms, but has INSERT perms.");
4267 code = CM_ERROR_WOULDBLOCK;
4270 " User has no read-lock perms. Forcing client-side lock");
4271 force_client_lock = TRUE;
4275 /* leave any other codes as-is */
4279 int check_data_version = FALSE;
4282 /* first check if we have permission to elevate or obtain
4284 code = cm_LockCheckPerms(scp, Which, userp, reqp, &has_insert);
4286 if (code == CM_ERROR_NOACCESS && Which == LockRead &&
4287 (!has_insert || !SCP_SUPPORTS_WRITELOCKACL(scp))) {
4288 osi_Log0(afsd_logp, " User has no read-lock perms. Forcing client-side lock");
4289 force_client_lock = TRUE;
4294 /* has_insert => (Which == LockRead, code == CM_ERROR_NOACCESS) */
4296 if (scp->serverLock == LockRead && Which == LockWrite) {
4298 /* We want to escalate the lock to a LockWrite.
4299 * Unfortunately that's not really possible without
4300 * letting go of the current lock. But for now we do
4304 " attempting to UPGRADE from LockRead to LockWrite.");
4306 " dataVersion on scp: %I64d", scp->dataVersion);
4308 /* we assume at this point (because scp->serverLock
4309 was valid) that we had a valid server lock. */
4310 scp->lockDataVersion = scp->dataVersion;
4311 check_data_version = TRUE;
4313 code = cm_IntReleaseLock(scp, userp, reqp);
4316 /* We couldn't release the lock */
4319 scp->serverLock = -1;
4323 /* We need to obtain a server lock of type Which in order
4324 * to assert this file lock */
4325 #ifndef AGGRESSIVE_LOCKS
4328 newLock = LockWrite;
4331 code = cm_IntSetLock(scp, userp, newLock, reqp);
4333 #ifdef AGGRESSIVE_LOCKS
4334 if ((code == CM_ERROR_WOULDBLOCK ||
4335 code == CM_ERROR_NOACCESS) && newLock != Which) {
4336 /* we wanted LockRead. We tried LockWrite. Now try
4341 osi_assertx(newLock == LockRead, "lock type not read");
4343 code = cm_IntSetLock(scp, userp, newLock, reqp);
4347 if (code == CM_ERROR_NOACCESS) {
4348 if (Which == LockRead) {
4349 if (has_insert && SCP_SUPPORTS_WRITELOCKACL(scp)) {
4351 /* We requested a read-lock, but we have permission to
4352 * get a write-lock. Try that */
4354 tcode = cm_LockCheckPerms(scp, LockWrite, userp, reqp, NULL);
4357 newLock = LockWrite;
4359 osi_Log0(afsd_logp, " User has 'i' perms and the request was for a LockRead. Trying to get a LockWrite instead");
4361 code = cm_IntSetLock(scp, userp, newLock, reqp);
4364 osi_Log0(afsd_logp, " User has no read-lock perms. Forcing client-side lock");
4365 force_client_lock = TRUE;
4367 } else if (Which == LockWrite &&
4368 scp->creator == userp && !SCP_SUPPORTS_WRITELOCKACL(scp)) {
4371 /* Special case: if the lock request was for a
4372 * LockWrite and the user owns the file and we weren't
4373 * allowed to obtain the serverlock, we either lost a
4374 * race (the permissions changed from under us), or we
4375 * have 'i' bits, but we aren't allowed to lock the
4378 /* check if we lost a race... */
4379 tcode = cm_LockCheckPerms(scp, Which, userp, reqp, NULL);
4382 osi_Log0(afsd_logp, " User has 'i' perms but can't obtain write locks. Using client-side locks.");
4383 force_client_lock = TRUE;
4388 if (code == 0 && check_data_version &&
4389 scp->dataVersion != scp->lockDataVersion) {
4390 /* We lost a race. Although we successfully obtained
4391 * a lock, someone modified the file in between. The
4392 * locks have all been technically lost. */
4395 " Data version mismatch while upgrading lock.");
4397 " Data versions before=%I64d, after=%I64d",
4398 scp->lockDataVersion,
4401 " Releasing stale lock for scp 0x%x", scp);
4403 code = cm_IntReleaseLock(scp, userp, reqp);
4405 scp->serverLock = -1;
4407 code = CM_ERROR_INVAL;
4408 } else if (code == 0) {
4409 scp->serverLock = newLock;
4410 scp->lockDataVersion = scp->dataVersion;
4414 (scp->sharedLocks > 0 || scp->exclusiveLocks > 0) &&
4415 scp->serverLock == -1) {
4416 /* Oops. We lost the lock. */
4417 cm_LockMarkSCacheLost(scp);
4420 } else if (code == 0) { /* server locks not enabled */
4422 " Skipping server lock for scp");
4427 if (code != 0 && !force_client_lock) {
4428 /* Special case error translations
4430 Applications don't expect certain errors from a
4431 LockFile/UnlockFile call. We need to translate some error
4432 code to codes that apps expect and handle. */
4434 /* We shouldn't actually need to handle this case since we
4435 simulate locks for RO scps anyway. */
4436 if (code == CM_ERROR_READONLY) {
4437 osi_Log0(afsd_logp, " Reinterpreting CM_ERROR_READONLY as CM_ERROR_NOACCESS");
4438 code = CM_ERROR_NOACCESS;
4442 if (code == 0 || (code == CM_ERROR_WOULDBLOCK && allowWait) ||
4443 force_client_lock) {
4445 /* clear the error if we are forcing a client lock, so we
4446 don't get confused later. */
4447 if (force_client_lock && code != CM_ERROR_WOULDBLOCK)
4450 lock_ObtainWrite(&cm_scacheLock);
4451 fileLock = cm_GetFileLock();
4452 lock_ReleaseWrite(&cm_scacheLock);
4454 fileLock->fid = scp->fid;
4456 fileLock->key = key;
4457 fileLock->lockType = Which;
4459 fileLock->userp = userp;
4460 fileLock->range = range;
4461 fileLock->flags = (code == 0 ? 0 :
4463 CM_FILELOCK_FLAG_WAITUNLOCK :
4464 CM_FILELOCK_FLAG_WAITLOCK));
4466 if (force_client_lock || !SERVERLOCKS_ENABLED(scp))
4467 fileLock->flags |= CM_FILELOCK_FLAG_CLIENTONLY;
4469 fileLock->lastUpdate = (code == 0 && !force_client_lock) ? time(NULL) : 0;
4471 lock_ObtainWrite(&cm_scacheLock);
4472 osi_QAddT(&scp->fileLocksH, &scp->fileLocksT, &fileLock->fileq);
4473 cm_HoldSCacheNoLock(scp);
4474 fileLock->scp = scp;
4475 osi_QAdd(&cm_allFileLocks, &fileLock->q);
4476 lock_ReleaseWrite(&cm_scacheLock);
4482 if (IS_LOCK_CLIENTONLY(fileLock)) {
4484 } else if (IS_LOCK_ACCEPTED(fileLock)) {
4485 if (Which == LockRead)
4488 scp->exclusiveLocks++;
4492 "cm_Lock Lock added 0x%p flags 0x%x to scp [0x%p]",
4493 fileLock, fileLock->flags, scp);
4495 " exclusives[%d] shared[%d] client[%d] serverLock[%d]",
4496 scp->exclusiveLocks, scp->sharedLocks, scp->clientLocks,
4497 (int)(signed char) scp->serverLock);
4500 "cm_Lock Rejecting lock (code = 0x%x)", code);
4506 static int cm_KeyEquals(cm_key_t k1, cm_key_t k2, int flags);
4508 /* Called with scp->rw held */
4509 long cm_UnlockByKey(cm_scache_t * scp,
4516 cm_file_lock_t *fileLock;
4517 osi_queue_t *q, *qn;
4520 osi_Log4(afsd_logp, "cm_UnlockByKey scp 0x%p key 0x%x:%x flags=0x%x",
4522 (unsigned long)(key >> 32),
4523 (unsigned long)(key & 0xffffffff),
4526 lock_ObtainWrite(&cm_scacheLock);
4528 for (q = scp->fileLocksH; q; q = qn) {
4531 fileLock = (cm_file_lock_t *)
4532 ((char *) q - offsetof(cm_file_lock_t, fileq));
4535 osi_Log4(afsd_logp, " Checking lock[0x%x] range[%d,+%d] type[%d]",
4537 (unsigned long) fileLock->range.offset,
4538 (unsigned long) fileLock->range.length,
4539 fileLock->lockType);
4540 osi_Log3(afsd_logp, " key[0x%x:%x] flags[0x%x]",
4541 (unsigned long)(fileLock->key >> 32),
4542 (unsigned long)(fileLock->key & 0xffffffff),
4545 if (cm_FidCmp(&fileLock->fid, &fileLock->scp->fid)) {
4546 osi_Log0(afsd_logp, "!!fileLock->fid != scp->fid");
4547 osi_Log4(afsd_logp, " fileLock->fid(cell=[%d], volume=[%d], vnode=[%d], unique=[%d]",
4549 fileLock->fid.volume,
4550 fileLock->fid.vnode,
4551 fileLock->fid.unique);
4552 osi_Log4(afsd_logp, " scp->fid(cell=[%d], volume=[%d], vnode=[%d], unique=[%d]",
4553 fileLock->scp->fid.cell,
4554 fileLock->scp->fid.volume,
4555 fileLock->scp->fid.vnode,
4556 fileLock->scp->fid.unique);
4557 osi_assertx(FALSE, "invalid fid value");
4561 if (!IS_LOCK_DELETED(fileLock) &&
4562 cm_KeyEquals(fileLock->key, key, flags)) {
4563 osi_Log3(afsd_logp, "...Unlock range [%d,+%d] type %d",
4564 fileLock->range.offset,
4565 fileLock->range.length,
4566 fileLock->lockType);
4568 if (scp->fileLocksT == q)
4569 scp->fileLocksT = osi_QPrev(q);
4570 osi_QRemoveHT(&scp->fileLocksH, &scp->fileLocksT, q);
4572 if (IS_LOCK_CLIENTONLY(fileLock)) {
4574 } else if (IS_LOCK_ACCEPTED(fileLock)) {
4575 if (fileLock->lockType == LockRead)
4578 scp->exclusiveLocks--;
4581 fileLock->flags |= CM_FILELOCK_FLAG_DELETED;
4583 cm_ReleaseUser(fileLock->userp);
4584 cm_ReleaseSCacheNoLock(scp);
4586 fileLock->userp = NULL;
4587 fileLock->scp = NULL;
4593 lock_ReleaseWrite(&cm_scacheLock);
4595 if (n_unlocks == 0) {
4596 osi_Log0(afsd_logp, "cm_UnlockByKey no locks found");
4597 osi_Log3(afsd_logp, " Leaving scp with exclusives[%d], shared[%d], serverLock[%d]",
4598 scp->exclusiveLocks, scp->sharedLocks, (int)(signed char) scp->serverLock);
4603 osi_Log1(afsd_logp, "cm_UnlockByKey done with %d locks", n_unlocks);
4605 osi_assertx(scp->sharedLocks >= 0, "scp->sharedLocks < 0");
4606 osi_assertx(scp->exclusiveLocks >= 0, "scp->exclusiveLocks < 0");
4607 osi_assertx(scp->clientLocks >= 0, "scp->clientLocks < 0");
4609 if (!SERVERLOCKS_ENABLED(scp)) {
4610 osi_Log0(afsd_logp, " Skipping server lock for scp");
4614 /* Ideally we would go through the rest of the locks to determine
4615 * if one or more locks that were formerly in WAITUNLOCK can now
4616 * be put to ACTIVE or WAITLOCK and update scp->exclusiveLocks and
4617 * scp->sharedLocks accordingly. However, the retrying of locks
4618 * in that manner is done cm_RetryLock() manually.
4621 if (scp->serverLock == LockWrite &&
4622 scp->exclusiveLocks == 0 &&
4623 scp->sharedLocks > 0) {
4625 /* The serverLock should be downgraded to LockRead */
4626 osi_Log0(afsd_logp, " DOWNGRADE lock from LockWrite to LockRead");
4628 /* since scp->serverLock looked sane, we are going to assume
4629 that we have a valid server lock. */
4630 scp->lockDataVersion = scp->dataVersion;
4631 osi_Log1(afsd_logp, " dataVersion on scp = %I64d", scp->dataVersion);
4633 code = cm_IntReleaseLock(scp, userp, reqp);
4636 /* so we couldn't release it. Just let the lock be for now */
4640 scp->serverLock = -1;
4643 code = cm_IntSetLock(scp, userp, LockRead, reqp);
4645 if (code == 0 && scp->lockDataVersion == scp->dataVersion) {
4646 scp->serverLock = LockRead;
4647 } else if (code == 0 && scp->lockDataVersion != scp->dataVersion) {
4648 /* We lost a race condition. Although we have a valid
4649 lock on the file, the data has changed and essentially
4650 we have lost the lock we had during the transition. */
4652 osi_Log0(afsd_logp, "Data version mismatch during lock downgrade");
4653 osi_Log2(afsd_logp, " Data versions before=%I64d, after=%I64d",
4654 scp->lockDataVersion,
4657 code = cm_IntReleaseLock(scp, userp, reqp);
4659 code = CM_ERROR_INVAL;
4660 scp->serverLock = -1;
4664 (scp->sharedLocks > 0 || scp->exclusiveLocks > 0) &&
4665 (scp->serverLock == -1)) {
4667 cm_LockMarkSCacheLost(scp);
4670 /* failure here has no bearing on the return value of
4674 } else if (scp->serverLock != (-1) &&
4675 scp->exclusiveLocks == 0 &&
4676 scp->sharedLocks == 0) {
4677 /* The serverLock should be released entirely */
4679 code = cm_IntReleaseLock(scp, userp, reqp);
4682 scp->serverLock = (-1);
4687 osi_Log1(afsd_logp, "cm_UnlockByKey code 0x%x", code);
4688 osi_Log4(afsd_logp, " Leaving scp with excl[%d], shared[%d], client[%d], serverLock[%d]",
4689 scp->exclusiveLocks, scp->sharedLocks, scp->clientLocks,
4690 (int)(signed char) scp->serverLock);
4695 long cm_Unlock(cm_scache_t *scp,
4696 unsigned char sLockType,
4697 LARGE_INTEGER LOffset, LARGE_INTEGER LLength,
4703 int Which = ((sLockType & LOCKING_ANDX_SHARED_LOCK) ? LockRead : LockWrite);
4704 cm_file_lock_t *fileLock;
4706 int release_userp = FALSE;
4708 osi_Log4(afsd_logp, "cm_Unlock scp 0x%p type 0x%x offset %d length %d",
4709 scp, sLockType, (unsigned long)LOffset.QuadPart, (unsigned long)LLength.QuadPart);
4710 osi_Log2(afsd_logp, "... key 0x%x:%x",
4711 (unsigned long) (key >> 32), (unsigned long) (key & 0xffffffff));
4713 lock_ObtainRead(&cm_scacheLock);
4715 for (q = scp->fileLocksH; q; q = osi_QNext(q)) {
4716 fileLock = (cm_file_lock_t *)
4717 ((char *) q - offsetof(cm_file_lock_t, fileq));
4720 if (cm_FidCmp(&fileLock->fid, &fileLock->scp->fid)) {
4721 osi_Log0(afsd_logp, "!!fileLock->fid != scp->fid");
4722 osi_Log4(afsd_logp, " fileLock->fid(cell=[%d], volume=[%d], vnode=[%d], unique=[%d]",
4724 fileLock->fid.volume,
4725 fileLock->fid.vnode,
4726 fileLock->fid.unique);
4727 osi_Log4(afsd_logp, " scp->fid(cell=[%d], volume=[%d], vnode=[%d], unique=[%d]",
4728 fileLock->scp->fid.cell,
4729 fileLock->scp->fid.volume,
4730 fileLock->scp->fid.vnode,
4731 fileLock->scp->fid.unique);
4732 osi_assertx(FALSE, "invalid fid value");
4735 if (!IS_LOCK_DELETED(fileLock) &&
4736 fileLock->key == key &&
4737 fileLock->range.offset == LOffset.QuadPart &&
4738 fileLock->range.length == LLength.QuadPart) {
4744 osi_Log0(afsd_logp, "cm_Unlock lock not found; failure");
4746 lock_ReleaseRead(&cm_scacheLock);
4748 /* The lock didn't exist anyway. *shrug* */
4749 return CM_ERROR_RANGE_NOT_LOCKED;
4752 /* discard lock record */
4753 lock_ConvertRToW(&cm_scacheLock);
4754 if (scp->fileLocksT == q)
4755 scp->fileLocksT = osi_QPrev(q);
4756 osi_QRemoveHT(&scp->fileLocksH, &scp->fileLocksT, q);
4759 * Don't delete it here; let the daemon delete it, to simplify
4760 * the daemon's traversal of the list.
4763 if (IS_LOCK_CLIENTONLY(fileLock)) {
4765 } else if (IS_LOCK_ACCEPTED(fileLock)) {
4766 if (fileLock->lockType == LockRead)
4769 scp->exclusiveLocks--;
4772 fileLock->flags |= CM_FILELOCK_FLAG_DELETED;
4773 if (userp != NULL) {
4774 cm_ReleaseUser(fileLock->userp);
4776 userp = fileLock->userp;
4777 release_userp = TRUE;
4779 fileLock->userp = NULL;
4780 cm_ReleaseSCacheNoLock(scp);
4781 fileLock->scp = NULL;
4782 lock_ReleaseWrite(&cm_scacheLock);
4784 if (!SERVERLOCKS_ENABLED(scp)) {
4785 osi_Log0(afsd_logp, " Skipping server locks for scp");
4789 /* Ideally we would go through the rest of the locks to determine
4790 * if one or more locks that were formerly in WAITUNLOCK can now
4791 * be put to ACTIVE or WAITLOCK and update scp->exclusiveLocks and
4792 * scp->sharedLocks accordingly. However, the retrying of locks
4793 * in that manner is done cm_RetryLock() manually.
4796 if (scp->serverLock == LockWrite &&
4797 scp->exclusiveLocks == 0 &&
4798 scp->sharedLocks > 0) {
4800 /* The serverLock should be downgraded to LockRead */
4801 osi_Log0(afsd_logp, " DOWNGRADE lock from LockWrite to LockRead");
4803 /* Since we already had a lock, we assume that there is a
4804 valid server lock. */
4805 scp->lockDataVersion = scp->dataVersion;
4806 osi_Log1(afsd_logp, " dataVersion on scp is %I64d", scp->dataVersion);
4808 /* before we downgrade, make sure that we have enough
4809 permissions to get the read lock. */
4810 code = cm_LockCheckPerms(scp, LockRead, userp, reqp, NULL);
4813 osi_Log0(afsd_logp, " SKIPPING downgrade because user doesn't have perms to get downgraded lock");
4819 code = cm_IntReleaseLock(scp, userp, reqp);
4822 /* so we couldn't release it. Just let the lock be for now */
4826 scp->serverLock = -1;
4829 code = cm_IntSetLock(scp, userp, LockRead, reqp);
4831 if (code == 0 && scp->lockDataVersion == scp->dataVersion) {
4832 scp->serverLock = LockRead;
4833 } else if (code == 0 && scp->lockDataVersion != scp->dataVersion) {
4834 /* Lost a race. We obtained a new lock, but that is
4835 meaningless since someone modified the file
4839 "Data version mismatch while downgrading lock");
4841 " Data versions before=%I64d, after=%I64d",
4842 scp->lockDataVersion,
4845 code = cm_IntReleaseLock(scp, userp, reqp);
4847 scp->serverLock = -1;
4848 code = CM_ERROR_INVAL;
4852 (scp->sharedLocks > 0 || scp->exclusiveLocks > 0) &&
4853 (scp->serverLock == -1)) {
4855 cm_LockMarkSCacheLost(scp);
4858 /* failure here has no bearing on the return value of
4862 } else if (scp->serverLock != (-1) &&
4863 scp->exclusiveLocks == 0 &&
4864 scp->sharedLocks == 0) {
4865 /* The serverLock should be released entirely */
4867 code = cm_IntReleaseLock(scp, userp, reqp);
4870 scp->serverLock = (-1);
4875 cm_ReleaseUser(userp);
4879 osi_Log1(afsd_logp, "cm_Unlock code 0x%x", code);
4880 osi_Log4(afsd_logp, " leaving scp with excl[%d], shared[%d], client[%d], serverLock[%d]",
4881 scp->exclusiveLocks, scp->sharedLocks, scp->clientLocks,
4882 (int)(signed char) scp->serverLock);
4887 /* called with scp->rw held */
4888 void cm_LockMarkSCacheLost(cm_scache_t * scp)
4890 cm_file_lock_t *fileLock;
4893 osi_Log1(afsd_logp, "cm_LockMarkSCacheLost scp 0x%x", scp);
4896 /* With the current code, we can't lose a lock on a RO scp */
4897 osi_assertx(!(scp->flags & CM_SCACHEFLAG_RO), "CM_SCACHEFLAG_RO unexpected");
4900 /* cm_scacheLock needed because we are modifying fileLock->flags */
4901 lock_ObtainWrite(&cm_scacheLock);
4903 for (q = scp->fileLocksH; q; q = osi_QNext(q)) {
4905 (cm_file_lock_t *)((char *) q - offsetof(cm_file_lock_t, fileq));
4907 if (IS_LOCK_ACTIVE(fileLock) &&
4908 !IS_LOCK_CLIENTONLY(fileLock)) {
4909 if (fileLock->lockType == LockRead)
4912 scp->exclusiveLocks--;
4914 fileLock->flags |= CM_FILELOCK_FLAG_LOST;
4918 scp->serverLock = -1;
4919 scp->lockDataVersion = -1;
4920 lock_ReleaseWrite(&cm_scacheLock);
4923 /* Called with no relevant locks held */
4924 void cm_CheckLocks()
4926 osi_queue_t *q, *nq;
4927 cm_file_lock_t *fileLock;
4933 struct rx_connection * callp;
4938 lock_ObtainWrite(&cm_scacheLock);
4940 cm_lockRefreshCycle++;
4942 osi_Log1(afsd_logp, "cm_CheckLocks starting lock check cycle %d", cm_lockRefreshCycle);
4944 for (q = cm_allFileLocks; q; q = nq) {
4945 fileLock = (cm_file_lock_t *) q;
4949 if (IS_LOCK_DELETED(fileLock)) {
4951 osi_QRemove(&cm_allFileLocks, q);
4952 cm_PutFileLock(fileLock);
4954 } else if (IS_LOCK_ACTIVE(fileLock) && !IS_LOCK_CLIENTONLY(fileLock)) {
4956 /* Server locks must have been enabled for us to have
4957 received an active non-client-only lock. */
4958 osi_assertx(cm_enableServerLocks, "!cm_enableServerLocks");
4960 scp = fileLock->scp;
4961 osi_assertx(scp != NULL, "null cm_scache_t");
4963 cm_HoldSCacheNoLock(scp);
4966 if (cm_FidCmp(&fileLock->fid, &fileLock->scp->fid)) {
4967 osi_Log0(afsd_logp, "!!fileLock->fid != scp->fid");
4968 osi_Log4(afsd_logp, " fileLock->fid(cell=[%d], volume=[%d], vnode=[%d], unique=[%d]",
4970 fileLock->fid.volume,
4971 fileLock->fid.vnode,
4972 fileLock->fid.unique);
4973 osi_Log4(afsd_logp, " scp->fid(cell=[%d], volume=[%d], vnode=[%d], unique=[%d]",
4974 fileLock->scp->fid.cell,
4975 fileLock->scp->fid.volume,
4976 fileLock->scp->fid.vnode,
4977 fileLock->scp->fid.unique);
4978 osi_assertx(FALSE, "invalid fid");
4981 /* Server locks are extended once per scp per refresh
4983 if (scp->lastRefreshCycle != cm_lockRefreshCycle) {
4985 int scp_done = FALSE;
4987 osi_Log1(afsd_logp, "cm_CheckLocks Updating scp 0x%x", scp);
4989 lock_ReleaseWrite(&cm_scacheLock);
4990 lock_ObtainWrite(&scp->rw);
4992 /* did the lock change while we weren't holding the lock? */
4993 if (!IS_LOCK_ACTIVE(fileLock))
4994 goto post_syncopdone;
4996 code = cm_SyncOp(scp, NULL, fileLock->userp, &req, 0,
4997 CM_SCACHESYNC_NEEDCALLBACK
4998 | CM_SCACHESYNC_GETSTATUS
4999 | CM_SCACHESYNC_LOCK);
5003 "cm_CheckLocks SyncOp failure code 0x%x", code);
5004 goto post_syncopdone;
5007 /* cm_SyncOp releases scp->rw during which the lock
5008 may get released. */
5009 if (!IS_LOCK_ACTIVE(fileLock))
5010 goto pre_syncopdone;
5012 if (scp->serverLock != -1 && !(scp->flags & CM_SCACHEFLAG_DELETED)) {
5016 tfid.Volume = scp->fid.volume;
5017 tfid.Vnode = scp->fid.vnode;
5018 tfid.Unique = scp->fid.unique;
5020 userp = fileLock->userp;
5022 osi_Log3(afsd_logp, "CALL ExtendLock lock 0x%p for scp=0x%p with lock %d",
5025 (int) scp->serverLock);
5027 lock_ReleaseWrite(&scp->rw);
5030 code = cm_ConnFromFID(&cfid, userp,
5035 callp = cm_GetRxConn(connp);
5036 code = RXAFS_ExtendLock(callp, &tfid,
5038 rx_PutConnection(callp);
5040 osi_Log1(afsd_logp, " ExtendLock returns %d", code);
5042 } while (cm_Analyze(connp, userp, &req,
5043 &cfid, &volSync, NULL, NULL,
5046 code = cm_MapRPCError(code, &req);
5048 lock_ObtainWrite(&scp->rw);
5051 osi_Log1(afsd_logp, "CALL ExtendLock FAILURE, code 0x%x", code);
5053 osi_Log0(afsd_logp, "CALL ExtendLock SUCCESS");
5054 scp->lockDataVersion = scp->dataVersion;
5057 if ((code == EINVAL || code == CM_ERROR_INVAL) &&
5058 scp->lockDataVersion == scp->dataVersion) {
5062 (scp->exclusiveLocks > 0) ? LockWrite: LockRead;
5064 /* we might still have a chance to obtain a
5067 code = cm_IntSetLock(scp, userp, lockType, &req);
5070 code = CM_ERROR_INVAL;
5071 } else if (scp->lockDataVersion != scp->dataVersion) {
5073 /* now check if we still have the file at
5074 the right data version. */
5076 "Data version mismatch on scp 0x%p",
5079 " Data versions: before=%I64d, after=%I64d",
5080 scp->lockDataVersion,
5083 code = cm_IntReleaseLock(scp, userp, &req);
5085 code = CM_ERROR_INVAL;
5089 if (code == EINVAL || code == CM_ERROR_INVAL ||
5090 code == CM_ERROR_BADFD) {
5091 cm_LockMarkSCacheLost(scp);
5095 /* interestingly, we have found an active lock
5096 belonging to an scache that has no
5098 cm_LockMarkSCacheLost(scp);
5105 cm_SyncOpDone(scp, NULL, CM_SCACHESYNC_LOCK);
5108 lock_ReleaseWrite(&scp->rw);
5110 lock_ObtainWrite(&cm_scacheLock);
5113 fileLock->lastUpdate = time(NULL);
5117 scp->lastRefreshCycle = cm_lockRefreshCycle;
5120 /* we have already refreshed the locks on this scp */
5121 fileLock->lastUpdate = time(NULL);
5124 cm_ReleaseSCacheNoLock(scp);
5126 } else if (IS_LOCK_ACTIVE(fileLock) && IS_LOCK_CLIENTONLY(fileLock)) {
5127 /* TODO: Check callbacks */
5131 lock_ReleaseWrite(&cm_scacheLock);
5132 osi_Log1(afsd_logp, "cm_CheckLocks completes lock check cycle %d", cm_lockRefreshCycle);
5135 /* NOT called with scp->rw held. */
5136 long cm_RetryLock(cm_file_lock_t *oldFileLock, int client_is_dead)
5139 cm_scache_t *scp = NULL;
5140 cm_file_lock_t *fileLock;
5144 int force_client_lock = FALSE;
5145 int has_insert = FALSE;
5146 int check_data_version = FALSE;
5150 if (client_is_dead) {
5151 code = CM_ERROR_TIMEDOUT;
5155 lock_ObtainRead(&cm_scacheLock);
5157 osi_Log2(afsd_logp, "cm_RetryLock checking lock %p (scp=%p)", oldFileLock, oldFileLock->scp);
5158 osi_Log4(afsd_logp, " offset(%x:%x) length(%x:%x)",
5159 (unsigned)(oldFileLock->range.offset >> 32),
5160 (unsigned)(oldFileLock->range.offset & 0xffffffff),
5161 (unsigned)(oldFileLock->range.length >> 32),
5162 (unsigned)(oldFileLock->range.length & 0xffffffff));
5163 osi_Log3(afsd_logp, " key(%x:%x) flags=%x",
5164 (unsigned)(oldFileLock->key >> 32),
5165 (unsigned)(oldFileLock->key & 0xffffffff),
5166 (unsigned)(oldFileLock->flags));
5168 /* if the lock has already been granted, then we have nothing to do */
5169 if (IS_LOCK_ACTIVE(oldFileLock)) {
5170 lock_ReleaseRead(&cm_scacheLock);
5171 osi_Log0(afsd_logp, "cm_RetryLock lock already granted");
5175 /* we can't do anything with lost or deleted locks at the moment. */
5176 if (IS_LOCK_LOST(oldFileLock) || IS_LOCK_DELETED(oldFileLock)) {
5177 code = CM_ERROR_BADFD;
5178 osi_Log0(afsd_logp, "cm_RetryLock lock is lost or deleted");
5179 lock_ReleaseRead(&cm_scacheLock);
5183 scp = oldFileLock->scp;
5185 osi_assertx(scp != NULL, "null cm_scache_t");
5187 lock_ReleaseRead(&cm_scacheLock);
5188 lock_ObtainWrite(&scp->rw);
5190 code = cm_LockCheckPerms(scp, oldFileLock->lockType,
5194 if (code == CM_ERROR_NOACCESS && oldFileLock->lockType == LockRead) {
5195 if (!has_insert || !SCP_SUPPORTS_WRITELOCKACL(scp)) {
5196 force_client_lock = TRUE;
5200 lock_ReleaseWrite(&scp->rw);
5204 lock_ObtainWrite(&cm_scacheLock);
5206 /* Check if we already have a sufficient server lock to allow this
5207 lock to go through. */
5208 if (IS_LOCK_WAITLOCK(oldFileLock) &&
5209 (!SERVERLOCKS_ENABLED(scp) ||
5210 scp->serverLock == oldFileLock->lockType ||
5211 scp->serverLock == LockWrite)) {
5213 oldFileLock->flags &= ~CM_FILELOCK_FLAG_WAITLOCK;
5215 if (SERVERLOCKS_ENABLED(scp)) {
5216 osi_Log1(afsd_logp, "cm_RetryLock Server lock (%d) is sufficient for lock. Granting",
5217 (int) scp->serverLock);
5219 osi_Log0(afsd_logp, "cm_RetryLock skipping server lock for scp");
5222 lock_ReleaseWrite(&cm_scacheLock);
5223 lock_ReleaseWrite(&scp->rw);
5228 if (IS_LOCK_WAITUNLOCK(oldFileLock)) {
5230 /* check if the conflicting locks have dissappeared already */
5231 for (q = scp->fileLocksH; q; q = osi_QNext(q)) {
5233 fileLock = (cm_file_lock_t *)
5234 ((char *) q - offsetof(cm_file_lock_t, fileq));
5236 if (IS_LOCK_LOST(fileLock)) {
5237 if (fileLock->key == oldFileLock->key) {
5238 code = CM_ERROR_BADFD;
5239 oldFileLock->flags |= CM_FILELOCK_FLAG_LOST;
5240 osi_Log1(afsd_logp, " found lost lock %p for same key. Marking lock as lost",
5243 } else if (fileLock->lockType == LockWrite &&
5244 INTERSECT_RANGE(oldFileLock->range, fileLock->range)) {
5245 osi_Log1(afsd_logp, " found conflicting LOST lock %p", fileLock);
5246 code = CM_ERROR_WOULDBLOCK;
5251 if (IS_LOCK_ACCEPTED(fileLock) &&
5252 INTERSECT_RANGE(oldFileLock->range, fileLock->range)) {
5254 if (oldFileLock->lockType != LockRead ||
5255 fileLock->lockType != LockRead) {
5257 osi_Log1(afsd_logp, " found conflicting lock %p", fileLock);
5258 code = CM_ERROR_WOULDBLOCK;
5266 lock_ReleaseWrite(&cm_scacheLock);
5267 lock_ReleaseWrite(&scp->rw);
5272 /* when we get here, the lock is either a WAITUNLOCK or WAITLOCK.
5273 If it is WAITUNLOCK, then we didn't find any conflicting lock
5274 but we haven't verfied whether the serverLock is sufficient to
5275 assert it. If it is WAITLOCK, then the serverLock is
5276 insufficient to assert it. Eitherway, we are ready to accept
5277 the lock as either ACTIVE or WAITLOCK depending on the
5280 /* First, promote the WAITUNLOCK to a WAITLOCK */
5281 if (IS_LOCK_WAITUNLOCK(oldFileLock)) {
5282 if (oldFileLock->lockType == LockRead)
5285 scp->exclusiveLocks++;
5287 oldFileLock->flags &= ~CM_FILELOCK_FLAG_WAITUNLOCK;
5288 oldFileLock->flags |= CM_FILELOCK_FLAG_WAITLOCK;
5291 osi_assertx(IS_LOCK_WAITLOCK(oldFileLock), "!IS_LOCK_WAITLOCK");
5293 if (force_client_lock ||
5294 !SERVERLOCKS_ENABLED(scp) ||
5295 scp->serverLock == oldFileLock->lockType ||
5296 (oldFileLock->lockType == LockRead &&
5297 scp->serverLock == LockWrite)) {
5299 oldFileLock->flags &= ~CM_FILELOCK_FLAG_WAITLOCK;
5301 if ((force_client_lock ||
5302 !SERVERLOCKS_ENABLED(scp)) &&
5303 !IS_LOCK_CLIENTONLY(oldFileLock)) {
5305 oldFileLock->flags |= CM_FILELOCK_FLAG_CLIENTONLY;
5307 if (oldFileLock->lockType == LockRead)
5310 scp->exclusiveLocks--;
5315 lock_ReleaseWrite(&cm_scacheLock);
5316 lock_ReleaseWrite(&scp->rw);
5323 code = cm_SyncOp(scp, NULL, oldFileLock->userp, &req, 0,
5324 CM_SCACHESYNC_NEEDCALLBACK
5325 | CM_SCACHESYNC_GETSTATUS
5326 | CM_SCACHESYNC_LOCK);
5328 osi_Log1(smb_logp, "cm_RetryLock SyncOp failure code 0x%x", code);
5329 lock_ReleaseWrite(&cm_scacheLock);
5330 goto post_syncopdone;
5333 if (!IS_LOCK_WAITLOCK(oldFileLock))
5334 goto pre_syncopdone;
5336 userp = oldFileLock->userp;
5338 #ifndef AGGRESSIVE_LOCKS
5339 newLock = oldFileLock->lockType;
5341 newLock = LockWrite;
5345 /* if has_insert is non-zero, then:
5346 - the lock a LockRead
5347 - we don't have permission to get a LockRead
5348 - we do have permission to get a LockWrite
5349 - the server supports VICED_CAPABILITY_WRITELOCKACL
5352 newLock = LockWrite;
5355 lock_ReleaseWrite(&cm_scacheLock);
5357 /* when we get here, either we have a read-lock and want a
5358 write-lock or we don't have any locks and we want some
5361 if (scp->serverLock == LockRead) {
5363 osi_assertx(newLock == LockWrite, "!LockWrite");
5365 osi_Log0(afsd_logp, " Attempting to UPGRADE from LockRead to LockWrite");
5367 scp->lockDataVersion = scp->dataVersion;
5368 check_data_version = TRUE;
5370 code = cm_IntReleaseLock(scp, userp, &req);
5373 goto pre_syncopdone;
5375 scp->serverLock = -1;
5378 code = cm_IntSetLock(scp, userp, newLock, &req);
5381 if (scp->dataVersion != scp->lockDataVersion) {
5382 /* we lost a race. too bad */
5385 " Data version mismatch while upgrading lock.");
5387 " Data versions before=%I64d, after=%I64d",
5388 scp->lockDataVersion,
5391 " Releasing stale lock for scp 0x%x", scp);
5393 code = cm_IntReleaseLock(scp, userp, &req);
5395 scp->serverLock = -1;
5397 code = CM_ERROR_INVAL;
5399 cm_LockMarkSCacheLost(scp);
5401 scp->serverLock = newLock;
5406 cm_SyncOpDone(scp, NULL, CM_SCACHESYNC_LOCK);
5412 if (code != 0 && code != CM_ERROR_WOULDBLOCK) {
5413 lock_ObtainWrite(&cm_scacheLock);
5414 if (scp->fileLocksT == &oldFileLock->fileq)
5415 scp->fileLocksT = osi_QPrev(&oldFileLock->fileq);
5416 osi_QRemoveHT(&scp->fileLocksH, &scp->fileLocksT, &oldFileLock->fileq);
5417 lock_ReleaseWrite(&cm_scacheLock);
5419 lock_ReleaseWrite(&scp->rw);
5422 lock_ObtainWrite(&cm_scacheLock);
5424 oldFileLock->flags &= ~CM_FILELOCK_FLAG_WAITLOCK;
5425 } else if (code != CM_ERROR_WOULDBLOCK) {
5426 oldFileLock->flags |= CM_FILELOCK_FLAG_DELETED;
5427 cm_ReleaseUser(oldFileLock->userp);
5428 oldFileLock->userp = NULL;
5429 if (oldFileLock->scp) {
5430 cm_ReleaseSCacheNoLock(oldFileLock->scp);
5431 oldFileLock->scp = NULL;
5434 lock_ReleaseWrite(&cm_scacheLock);
5439 cm_key_t cm_GenerateKey(unsigned int session_id, unsigned long process_id, unsigned int file_id)
5442 osi_assertx((process_id & 0xffffffff) == process_id, "unexpected process_id");
5443 osi_assertx((session_id & 0xffff) == session_id, "unexpected session_id");
5444 osi_assertx((file_id & 0xffff) == file_id, "unexpected file_id");
5448 (((cm_key_t) (process_id & 0xffffffff)) << 32) |
5449 (((cm_key_t) (session_id & 0xffff)) << 16) |
5450 (((cm_key_t) (file_id & 0xffff)));
5453 static int cm_KeyEquals(cm_key_t k1, cm_key_t k2, int flags)
5455 if (flags & CM_UNLOCK_BY_FID) {
5456 return ((k1 & 0xffffffff) == (k2 & 0xffffffff));
5462 void cm_ReleaseAllLocks(void)
5468 cm_file_lock_t *fileLock;
5471 for (i = 0; i < cm_data.scacheHashTableSize; i++)
5473 for ( scp = cm_data.scacheHashTablep[i]; scp; scp = scp->nextp ) {
5474 while (scp->fileLocksH != NULL) {
5475 lock_ObtainWrite(&scp->rw);
5476 lock_ObtainWrite(&cm_scacheLock);
5477 if (!scp->fileLocksH) {
5478 lock_ReleaseWrite(&cm_scacheLock);
5479 lock_ReleaseWrite(&scp->rw);
5482 fileLock = (cm_file_lock_t *)((char *) scp->fileLocksH - offsetof(cm_file_lock_t, fileq));
5483 userp = fileLock->userp;
5485 key = fileLock->key;
5486 cm_HoldSCacheNoLock(scp);
5487 lock_ReleaseWrite(&cm_scacheLock);
5488 cm_UnlockByKey(scp, key, 0, userp, &req);
5489 cm_ReleaseSCache(scp);
5490 cm_ReleaseUser(userp);
5491 lock_ReleaseWrite(&scp->rw);