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 */
747 lock_ObtainMutex(&bufferp->mx);
748 bufferOffset = thyper;
750 /* now get the data in the cache */
752 lock_ObtainWrite(&scp->rw);
753 code = cm_SyncOp(scp, bufferp, userp, reqp,
755 CM_SCACHESYNC_NEEDCALLBACK
757 | CM_SCACHESYNC_BUFLOCKED);
759 lock_ReleaseWrite(&scp->rw);
762 cm_SyncOpDone(scp, bufferp, CM_SCACHESYNC_NEEDCALLBACK | CM_SCACHESYNC_READ | CM_SCACHESYNC_BUFLOCKED);
764 if (cm_HaveBuffer(scp, bufferp, 1)) {
765 lock_ReleaseWrite(&scp->rw);
769 /* otherwise, load the buffer and try again */
770 lock_ReleaseMutex(&bufferp->mx);
771 code = cm_GetBuffer(scp, bufferp, NULL, userp,
773 lock_ReleaseWrite(&scp->rw);
774 lock_ObtainMutex(&bufferp->mx);
779 lock_ReleaseMutex(&bufferp->mx);
780 buf_Release(bufferp);
784 } /* if (wrong buffer) ... */
786 /* now we have the buffer containing the entry we're interested
787 * in; copy it out if it represents a non-deleted entry.
789 entryInDir = curOffset.LowPart & (2048-1);
790 entryInBuffer = curOffset.LowPart & (cm_data.buf_blockSize - 1);
792 /* page header will help tell us which entries are free. Page
793 * header can change more often than once per buffer, since
794 * AFS 3 dir page size may be less than (but not more than) a
795 * buffer package buffer.
797 /* only look intra-buffer */
798 temp = curOffset.LowPart & (cm_data.buf_blockSize - 1);
799 temp &= ~(2048 - 1); /* turn off intra-page bits */
800 pageHeaderp = (cm_pageHeader_t *) (bufferp->datap + temp);
802 /* now determine which entry we're looking at in the page. If
803 * it is free (there's a free bitmap at the start of the dir),
804 * we should skip these 32 bytes.
806 slotInPage = (entryInDir & 0x7e0) >> 5;
807 if (!(pageHeaderp->freeBitmap[slotInPage>>3]
808 & (1 << (slotInPage & 0x7)))) {
809 /* this entry is free */
810 numDirChunks = 1; /* only skip this guy */
814 tp = bufferp->datap + entryInBuffer;
815 dep = (cm_dirEntry_t *) tp; /* now points to AFS3 dir entry */
817 /* while we're here, compute the next entry's location, too,
818 * since we'll need it when writing out the cookie into the
819 * dir listing stream.
821 numDirChunks = cm_NameEntries(dep->name, NULL);
823 /* compute the offset of the cookie representing the next entry */
824 nextEntryCookie = curOffset.LowPart
825 + (CM_DIR_CHUNKSIZE * numDirChunks);
827 if (dep->fid.vnode != 0) {
828 /* this is one of the entries to use: it is not deleted */
829 code = (*funcp)(scp, dep, parmp, &curOffset);
832 } /* if we're including this name */
835 /* and adjust curOffset to be where the new cookie is */
837 thyper.LowPart = CM_DIR_CHUNKSIZE * numDirChunks;
838 curOffset = LargeIntegerAdd(thyper, curOffset);
839 } /* while copying data for dir listing */
841 /* release the mutex */
843 lock_ReleaseMutex(&bufferp->mx);
844 buf_Release(bufferp);
849 int cm_NoneUpper(char *s)
853 if (c >= 'A' && c <= 'Z')
858 int cm_NoneLower(char *s)
862 if (c >= 'a' && c <= 'z')
867 long cm_LookupSearchProc(cm_scache_t *scp, cm_dirEntry_t *dep, void *rockp,
870 cm_lookupSearch_t *sp;
872 char matchName[MAX_PATH];
873 int looking_for_short_name = FALSE;
875 sp = (cm_lookupSearch_t *) rockp;
877 cm_NormalizeUtf8String(dep->name, -1, matchName, sizeof(matchName)/sizeof(char));
879 match = cm_stricmp_utf8(matchName, sp->searchNamep);
881 match = strcmp(matchName, sp->searchNamep);
885 && !cm_Is8Dot3(dep->name)) {
887 cm_Gen8Dot3Name(dep, matchName, NULL);
889 match = cm_stricmp_utf8(matchName, sp->searchNamep);
891 match = strcmp(matchName, sp->searchNamep);
892 looking_for_short_name = TRUE;
902 if (!sp->caseFold || looking_for_short_name) {
903 cm_SetFid(&sp->fid, sp->fid.cell, sp->fid.volume, ntohl(dep->fid.vnode), ntohl(dep->fid.unique));
904 return CM_ERROR_STOPNOW;
908 * If we get here, we are doing a case-insensitive search, and we
909 * have found a match. Now we determine what kind of match it is:
910 * exact, lower-case, upper-case, or none of the above. This is done
911 * in order to choose among matches, if there are more than one.
914 /* Exact matches are the best. */
915 match = strcmp(matchName, sp->searchNamep);
918 cm_SetFid(&sp->fid, sp->fid.cell, sp->fid.volume, ntohl(dep->fid.vnode), ntohl(dep->fid.unique));
919 return CM_ERROR_STOPNOW;
922 /* Lower-case matches are next. */
925 if (cm_NoneUpper(matchName)) {
930 /* Upper-case matches are next. */
933 if (cm_NoneLower(matchName)) {
938 /* General matches are last. */
944 cm_SetFid(&sp->fid, sp->fid.cell, sp->fid.volume, ntohl(dep->fid.vnode), ntohl(dep->fid.unique));
948 /* read the contents of a mount point into the appropriate string.
949 * called with write locked scp, and returns with locked scp.
951 long cm_ReadMountPoint(cm_scache_t *scp, cm_user_t *userp, cm_req_t *reqp)
958 if (scp->mountPointStringp[0])
961 /* otherwise, we have to read it in */
962 lock_ReleaseWrite(&scp->rw);
964 thyper.LowPart = thyper.HighPart = 0;
965 code = buf_Get(scp, &thyper, &bufp);
967 lock_ObtainWrite(&scp->rw);
972 code = cm_SyncOp(scp, bufp, userp, reqp, 0,
973 CM_SCACHESYNC_READ | CM_SCACHESYNC_NEEDCALLBACK);
977 cm_SyncOpDone(scp, bufp, CM_SCACHESYNC_NEEDCALLBACK | CM_SCACHESYNC_READ);
979 if (cm_HaveBuffer(scp, bufp, 0))
982 /* otherwise load buffer */
983 code = cm_GetBuffer(scp, bufp, NULL, userp, reqp);
987 /* locked, has callback, has valid data in buffer */
988 if ((tlen = scp->length.LowPart) > MOUNTPOINTLEN - 1)
989 return CM_ERROR_TOOBIG;
991 code = CM_ERROR_INVAL;
995 /* someone else did the work while we were out */
996 if (scp->mountPointStringp[0]) {
1001 /* otherwise, copy out the link */
1002 memcpy(scp->mountPointStringp, bufp->datap, tlen);
1004 /* now make it null-terminated. Note that the original contents of a
1005 * link that is a mount point is "#volname." where "." is there just to
1006 * be turned into a null. That is, we can trash the last char of the
1007 * link without damaging the vol name. This is a stupid convention,
1008 * but that's the protocol.
1010 scp->mountPointStringp[tlen-1] = 0;
1020 /* called with a locked scp and chases the mount point, yielding outScpp.
1021 * scp remains write locked, just for simplicity of describing the interface.
1023 long cm_FollowMountPoint(cm_scache_t *scp, cm_scache_t *dscp, cm_user_t *userp,
1024 cm_req_t *reqp, cm_scache_t **outScpp)
1032 cm_volume_t *volp = NULL;
1039 if (scp->mountRootFid.cell != 0 && scp->mountRootGen >= cm_data.mountRootGen) {
1040 tfid = scp->mountRootFid;
1041 lock_ReleaseWrite(&scp->rw);
1042 code = cm_GetSCache(&tfid, outScpp, userp, reqp);
1043 lock_ObtainWrite(&scp->rw);
1047 /* parse the volume name */
1048 mpNamep = scp->mountPointStringp;
1050 return CM_ERROR_NOSUCHPATH;
1051 tlen = (int)strlen(scp->mountPointStringp);
1052 mtType = *scp->mountPointStringp;
1053 cellNamep = malloc(tlen);
1054 volNamep = malloc(tlen);
1056 cp = strrchr(mpNamep, ':');
1058 /* cellular mount point */
1059 memset(cellNamep, 0, tlen);
1060 strncpy(cellNamep, mpNamep+1, cp - mpNamep - 1);
1061 strcpy(volNamep, cp+1);
1062 /* now look up the cell */
1063 lock_ReleaseWrite(&scp->rw);
1064 cellp = cm_GetCell(cellNamep, CM_FLAG_CREATE);
1065 lock_ObtainWrite(&scp->rw);
1069 strcpy(volNamep, mpNamep+1);
1071 cellp = cm_FindCellByID(scp->fid.cell, 0);
1075 code = CM_ERROR_NOSUCHCELL;
1079 vnLength = strlen(volNamep);
1080 if (vnLength >= 8 && strcmp(volNamep + vnLength - 7, ".backup") == 0)
1081 targetType = BACKVOL;
1082 else if (vnLength >= 10
1083 && strcmp(volNamep + vnLength - 9, ".readonly") == 0)
1088 /* check for backups within backups */
1089 if (targetType == BACKVOL
1090 && (scp->flags & (CM_SCACHEFLAG_RO | CM_SCACHEFLAG_PURERO))
1091 == CM_SCACHEFLAG_RO) {
1092 code = CM_ERROR_NOSUCHVOLUME;
1096 /* now we need to get the volume */
1097 lock_ReleaseWrite(&scp->rw);
1098 if (cm_VolNameIsID(volNamep)) {
1099 code = cm_FindVolumeByID(cellp, atoi(volNamep), userp, reqp,
1100 CM_GETVOL_FLAG_CREATE, &volp);
1102 code = cm_FindVolumeByName(cellp, volNamep, userp, reqp,
1103 CM_GETVOL_FLAG_CREATE, &volp);
1105 lock_ObtainWrite(&scp->rw);
1108 afs_uint32 cell, volume;
1109 cm_vol_state_t *statep;
1111 cell = cellp->cellID;
1113 /* if the mt pt originates in a .backup volume (not a .readonly)
1114 * and FollowBackupPath is active, and if there is a .backup
1115 * volume for the target, then use the .backup of the target
1116 * instead of the read-write.
1118 if (cm_followBackupPath &&
1119 volp->vol[BACKVOL].ID != 0 &&
1120 (dscp->flags & (CM_SCACHEFLAG_RO|CM_SCACHEFLAG_PURERO)) == CM_SCACHEFLAG_RO &&
1121 (targetType == RWVOL || targetType == ROVOL && volp->vol[ROVOL].ID == 0)
1123 targetType = BACKVOL;
1125 /* if the mt pt is in a read-only volume (not just a
1126 * backup), and if there is a read-only volume for the
1127 * target, and if this is a targetType '#' mount point, use
1128 * the read-only, otherwise use the one specified.
1130 else if (mtType == '#' && targetType == RWVOL &&
1131 (scp->flags & CM_SCACHEFLAG_PURERO) &&
1132 volp->vol[ROVOL].ID != 0) {
1136 lock_ObtainWrite(&volp->rw);
1137 statep = cm_VolumeStateByType(volp, targetType);
1138 volume = statep->ID;
1139 statep->dotdotFid = dscp->fid;
1140 lock_ReleaseWrite(&volp->rw);
1142 /* the rest of the fid is a magic number */
1143 cm_SetFid(&scp->mountRootFid, cell, volume, 1, 1);
1144 scp->mountRootGen = cm_data.mountRootGen;
1146 tfid = scp->mountRootFid;
1147 lock_ReleaseWrite(&scp->rw);
1148 code = cm_GetSCache(&tfid, outScpp, userp, reqp);
1149 lock_ObtainWrite(&scp->rw);
1160 long cm_LookupInternal(cm_scache_t *dscp, char *namep, long flags, cm_user_t *userp,
1161 cm_req_t *reqp, cm_scache_t **outpScpp)
1164 int dnlcHit = 1; /* did we hit in the dnlc? yes, we did */
1165 cm_scache_t *tscp = NULL;
1166 cm_scache_t *mountedScp;
1167 cm_lookupSearch_t rock;
1170 memset(&rock, 0, sizeof(rock));
1172 if (dscp->fid.vnode == 1 && dscp->fid.unique == 1
1173 && strcmp(namep, "..") == 0) {
1174 if (dscp->dotdotFid.volume == 0)
1175 return CM_ERROR_NOSUCHVOLUME;
1176 rock.fid = dscp->dotdotFid;
1178 } else if (strcmp(namep, ".") == 0) {
1179 rock.fid = dscp->fid;
1183 if (flags & CM_FLAG_NOMOUNTCHASE) {
1184 /* In this case, we should go and call cm_Dir* functions
1185 directly since the following cm_ApplyDir() function will
1193 code = cm_BeginDirOp(dscp, userp, reqp, CM_DIRLOCK_READ, &dirop);
1196 code = cm_BPlusDirLookup(&dirop, namep, &rock.fid);
1201 code = cm_DirLookup(&dirop, namep, &rock.fid);
1203 cm_EndDirOp(&dirop);
1213 if (code == CM_ERROR_INEXACT_MATCH && (flags & CM_FLAG_CASEFOLD)) {
1220 return CM_ERROR_BPLUS_NOMATCH;
1225 rock.fid.cell = dscp->fid.cell;
1226 rock.fid.volume = dscp->fid.volume;
1227 rock.searchNamep = namep;
1228 rock.caseFold = (flags & CM_FLAG_CASEFOLD);
1229 rock.hasTilde = ((strchr(namep, '~') != NULL) ? 1 : 0);
1231 /* If NOMOUNTCHASE, bypass DNLC by passing NULL scp pointer */
1232 code = cm_ApplyDir(dscp, cm_LookupSearchProc, &rock, NULL, userp, reqp,
1233 (flags & CM_FLAG_NOMOUNTCHASE) ? NULL : &tscp);
1235 /* code == 0 means we fell off the end of the dir, while stopnow means
1236 * that we stopped early, probably because we found the entry we're
1237 * looking for. Any other non-zero code is an error.
1239 if (code && code != CM_ERROR_STOPNOW) {
1240 /* if the cm_scache_t we are searching in is not a directory
1241 * we must return path not found because the error
1242 * is to describe the final component not an intermediary
1244 if (code == CM_ERROR_NOTDIR) {
1245 if (flags & CM_FLAG_CHECKPATH)
1246 return CM_ERROR_NOSUCHPATH;
1248 return CM_ERROR_NOSUCHFILE;
1253 getroot = (dscp==cm_data.rootSCachep) ;
1255 if (!cm_freelanceEnabled || !getroot) {
1256 if (flags & CM_FLAG_CHECKPATH)
1257 return CM_ERROR_NOSUCHPATH;
1259 return CM_ERROR_NOSUCHFILE;
1261 else if (!strchr(namep, '#') && !strchr(namep, '%') &&
1262 strcmp(namep, "srvsvc") && strcmp(namep, "wkssvc") &&
1263 strcmp(namep, "ipc$"))
1265 /* nonexistent dir on freelance root, so add it */
1266 char fullname[200] = ".";
1269 osi_Log1(afsd_logp,"cm_Lookup adding mount for non-existent directory: %s",
1270 osi_LogSaveString(afsd_logp,namep));
1273 * There is an ugly behavior where a share name "foo" will be searched
1274 * for as "fo". If the searched for name differs by an already existing
1275 * symlink or mount point in the Freelance directory, do not add the
1276 * new value automatically.
1280 if (namep[0] == '.') {
1281 if (cm_GetCell_Gen(&namep[1], &fullname[1], CM_FLAG_CREATE)) {
1283 if (!cm_FreelanceMountPointExists(fullname, 0))
1284 code = cm_FreelanceAddMount(fullname, &fullname[1], "root.cell.", 1, &rock.fid);
1285 if ( cm_stricmp_utf8(&namep[1], &fullname[1]) &&
1286 !cm_FreelanceMountPointExists(namep, flags & CM_FLAG_DFS_REFERRAL ? 1 : 0) &&
1287 !cm_FreelanceSymlinkExists(namep, flags & CM_FLAG_DFS_REFERRAL ? 1 : 0))
1288 code = cm_FreelanceAddSymlink(namep, fullname, &rock.fid);
1291 if (cm_GetCell_Gen(namep, fullname, CM_FLAG_CREATE)) {
1293 if (!cm_FreelanceMountPointExists(fullname, 0))
1294 code = cm_FreelanceAddMount(fullname, fullname, "root.cell.", 0, &rock.fid);
1295 if ( cm_stricmp_utf8(namep, fullname) &&
1296 !cm_FreelanceMountPointExists(namep, flags & CM_FLAG_DFS_REFERRAL ? 1 : 0) &&
1297 !cm_FreelanceSymlinkExists(namep, flags & CM_FLAG_DFS_REFERRAL ? 1 : 0))
1298 code = cm_FreelanceAddSymlink(namep, fullname, &rock.fid);
1301 if (!found || code < 0) { /* add mount point failed, so give up */
1302 if (flags & CM_FLAG_CHECKPATH)
1303 return CM_ERROR_NOSUCHPATH;
1305 return CM_ERROR_NOSUCHFILE;
1307 tscp = NULL; /* to force call of cm_GetSCache */
1309 if (flags & CM_FLAG_CHECKPATH)
1310 return CM_ERROR_NOSUCHPATH;
1312 return CM_ERROR_NOSUCHFILE;
1317 if ( !tscp ) /* we did not find it in the dnlc */
1320 code = cm_GetSCache(&rock.fid, &tscp, userp, reqp);
1324 /* tscp is now held */
1326 lock_ObtainWrite(&tscp->rw);
1327 code = cm_SyncOp(tscp, NULL, userp, reqp, 0,
1328 CM_SCACHESYNC_GETSTATUS | CM_SCACHESYNC_NEEDCALLBACK);
1330 lock_ReleaseWrite(&tscp->rw);
1331 cm_ReleaseSCache(tscp);
1334 cm_SyncOpDone(tscp, NULL, CM_SCACHESYNC_NEEDCALLBACK | CM_SCACHESYNC_GETSTATUS);
1335 /* tscp is now locked */
1337 if (!(flags & CM_FLAG_NOMOUNTCHASE)
1338 && tscp->fileType == CM_SCACHETYPE_MOUNTPOINT) {
1339 /* mount points are funny: they have a volume name to mount
1342 code = cm_ReadMountPoint(tscp, userp, reqp);
1344 code = cm_FollowMountPoint(tscp, dscp, userp, reqp,
1346 lock_ReleaseWrite(&tscp->rw);
1347 cm_ReleaseSCache(tscp);
1354 lock_ReleaseWrite(&tscp->rw);
1357 /* copy back pointer */
1360 /* insert scache in dnlc */
1361 if ( !dnlcHit && !(flags & CM_FLAG_NOMOUNTCHASE) && rock.ExactFound ) {
1362 /* lock the directory entry to prevent racing callback revokes */
1363 lock_ObtainRead(&dscp->rw);
1364 if ( dscp->cbServerp != NULL && dscp->cbExpires > 0 ) {
1365 /* Note: namep is a normalized name */
1366 cm_dnlcEnter(dscp, namep, tscp);
1368 lock_ReleaseRead(&dscp->rw);
1375 int cm_ExpandSysName(char *inp, char *outp, long outSize, unsigned int index)
1380 tp = strrchr(inp, '@');
1382 return 0; /* no @sys */
1384 if (strcmp(tp, "@sys") != 0)
1385 return 0; /* no @sys */
1387 /* caller just wants to know if this is a valid @sys type of name */
1391 if (index >= cm_sysNameCount)
1394 /* otherwise generate the properly expanded @sys name */
1395 prefixCount = (int)(tp - inp);
1397 strncpy(outp, inp, prefixCount); /* copy out "a." from "a.@sys" */
1398 outp[prefixCount] = 0; /* null terminate the "a." */
1399 strcat(outp, cm_sysNameList[index]);/* append i386_nt40 */
1403 long cm_EvaluateVolumeReference(char * namep, long flags, cm_user_t * userp,
1404 cm_req_t *reqp, cm_scache_t ** outpScpp)
1407 char cellName[CELL_MAXNAMELEN];
1408 char volumeName[VL_MAXNAMELEN];
1413 cm_cell_t * cellp = NULL;
1414 cm_volume_t * volp = NULL;
1418 int mountType = RWVOL;
1420 osi_Log1(afsd_logp, "cm_EvaluateVolumeReference for string [%s]",
1421 osi_LogSaveString(afsd_logp, namep));
1423 if (strnicmp(namep, CM_PREFIX_VOL, CM_PREFIX_VOL_CCH) != 0) {
1424 goto _exit_invalid_path;
1427 /* namep is assumed to look like the following:
1429 @vol:<cellname>%<volume>\0
1431 @vol:<cellname>#<volume>\0
1435 cp = namep + CM_PREFIX_VOL_CCH; /* cp points to cell name, hopefully */
1436 tp = strchr(cp, '%');
1438 tp = strchr(cp, '#');
1440 (len = tp - cp) == 0 ||
1441 len > CELL_MAXNAMELEN)
1442 goto _exit_invalid_path;
1443 strncpy(cellName, cp, len);
1444 cellName[len] = '\0';
1449 cp = tp+1; /* cp now points to volume, supposedly */
1450 strncpy(volumeName, cp, VL_MAXNAMELEN-1);
1451 volumeName[VL_MAXNAMELEN - 1] = 0;
1453 /* OK, now we have the cell and the volume */
1454 osi_Log2(afsd_logp, " Found cell [%s] and volume [%s]",
1455 osi_LogSaveString(afsd_logp, cellName),
1456 osi_LogSaveString(afsd_logp, volumeName));
1458 cellp = cm_GetCell(cellName, CM_FLAG_CREATE);
1459 if (cellp == NULL) {
1460 goto _exit_invalid_path;
1463 len = strlen(volumeName);
1464 if (len >= 8 && strcmp(volumeName + len - 7, ".backup") == 0)
1466 else if (len >= 10 &&
1467 strcmp(volumeName + len - 9, ".readonly") == 0)
1472 if (cm_VolNameIsID(volumeName)) {
1473 code = cm_FindVolumeByID(cellp, atoi(volumeName), userp, reqp,
1474 CM_GETVOL_FLAG_CREATE, &volp);
1476 code = cm_FindVolumeByName(cellp, volumeName, userp, reqp,
1477 CM_GETVOL_FLAG_CREATE, &volp);
1483 if (volType == BACKVOL)
1484 volume = volp->vol[BACKVOL].ID;
1485 else if (volType == ROVOL ||
1486 (volType == RWVOL && mountType == ROVOL && volp->vol[ROVOL].ID != 0))
1487 volume = volp->vol[ROVOL].ID;
1489 volume = volp->vol[RWVOL].ID;
1491 cm_SetFid(&fid, cellp->cellID, volume, 1, 1);
1493 code = cm_GetSCache(&fid, outpScpp, userp, reqp);
1503 if (flags & CM_FLAG_CHECKPATH)
1504 return CM_ERROR_NOSUCHPATH;
1506 return CM_ERROR_NOSUCHFILE;
1509 #ifdef DEBUG_REFCOUNT
1510 long cm_LookupDbg(cm_scache_t *dscp, char *namep, long flags, cm_user_t *userp,
1511 cm_req_t *reqp, cm_scache_t **outpScpp, char * file, long line)
1513 long cm_Lookup(cm_scache_t *dscp, char *namep, long flags, cm_user_t *userp,
1514 cm_req_t *reqp, cm_scache_t **outpScpp)
1518 char tname[AFSPATHMAX];
1519 int sysNameIndex = 0;
1520 cm_scache_t *scp = NULL;
1522 #ifdef DEBUG_REFCOUNT
1523 afsi_log("%s:%d cm_Lookup dscp 0x%p ref %d", file, line, dscp, dscp->refCount, file, line);
1524 osi_Log2(afsd_logp, "cm_Lookup dscp 0x%p ref %d", dscp, dscp->refCount);
1527 if ( cm_stricmp_utf8N(namep,SMB_IOCTL_FILENAME_NOSLASH) == 0 ) {
1528 if (flags & CM_FLAG_CHECKPATH)
1529 return CM_ERROR_NOSUCHPATH;
1531 return CM_ERROR_NOSUCHFILE;
1534 if (dscp == cm_data.rootSCachep &&
1535 strnicmp(namep, CM_PREFIX_VOL, CM_PREFIX_VOL_CCH) == 0) {
1536 return cm_EvaluateVolumeReference(namep, flags, userp, reqp, outpScpp);
1539 if (cm_ExpandSysName(namep, NULL, 0, 0) > 0) {
1540 for ( sysNameIndex = 0; sysNameIndex < MAXNUMSYSNAMES; sysNameIndex++) {
1541 code = cm_ExpandSysName(namep, tname, sizeof(tname), sysNameIndex);
1543 code = cm_LookupInternal(dscp, tname, flags, userp, reqp, &scp);
1544 #ifdef DEBUG_REFCOUNT
1545 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);
1546 osi_Log3(afsd_logp, "cm_LookupInternal (1) code 0x%x dscp 0x%p scp 0x%p", code, dscp, scp);
1554 cm_ReleaseSCache(scp);
1558 code = cm_LookupInternal(dscp, namep, flags, userp, reqp, &scp);
1559 #ifdef DEBUG_REFCOUNT
1560 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);
1561 osi_Log3(afsd_logp, "cm_LookupInternal (2) code 0x%x dscp 0x%p scp 0x%p", code, dscp, scp);
1568 code = cm_LookupInternal(dscp, namep, flags, userp, reqp, &scp);
1569 #ifdef DEBUG_REFCOUNT
1570 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);
1571 osi_Log3(afsd_logp, "cm_LookupInternal (2) code 0x%x dscp 0x%p scp 0x%p", code, dscp, scp);
1577 /* None of the possible sysName expansions could be found */
1578 if (flags & CM_FLAG_CHECKPATH)
1579 return CM_ERROR_NOSUCHPATH;
1581 return CM_ERROR_NOSUCHFILE;
1584 /*! \brief Unlink a file name
1586 Encapsulates a call to RXAFS_RemoveFile().
1588 \param[in] dscp cm_scache_t pointing at the directory containing the
1589 name to be unlinked.
1591 \param[in] namep Non-normalized name to be unlinked. This is the
1592 name that will be passed into the RXAFS_RemoveFile() call.
1594 \param[in] normalizedName Normalized name to be unlinked. This name
1595 will be used to update the local directory caches.
1597 \param[in] userp cm_user_t for the request.
1599 \param[in] reqp Request tracker.
1602 long cm_Unlink(cm_scache_t *dscp, char *namep, char * normalizedName,
1603 cm_user_t *userp, cm_req_t *reqp)
1609 AFSFetchStatus newDirStatus;
1611 struct rx_connection * callp;
1613 cm_scache_t *scp = NULL;
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 code = cm_Lookup(dscp, namep, CM_FLAG_NOMOUNTCHASE, userp, reqp, &scp);
1625 /* make sure we don't screw up the dir status during the merge */
1626 code = cm_BeginDirOp(dscp, userp, reqp, CM_DIRLOCK_NONE, &dirop);
1628 lock_ObtainWrite(&dscp->rw);
1629 sflags = CM_SCACHESYNC_STOREDATA;
1630 code = cm_SyncOp(dscp, NULL, userp, reqp, 0, sflags);
1631 lock_ReleaseWrite(&dscp->rw);
1633 cm_EndDirOp(&dirop);
1638 afsFid.Volume = dscp->fid.volume;
1639 afsFid.Vnode = dscp->fid.vnode;
1640 afsFid.Unique = dscp->fid.unique;
1642 osi_Log1(afsd_logp, "CALL RemoveFile scp 0x%p", dscp);
1644 code = cm_ConnFromFID(&dscp->fid, userp, reqp, &connp);
1648 callp = cm_GetRxConn(connp);
1649 code = RXAFS_RemoveFile(callp, &afsFid, namep,
1650 &newDirStatus, &volSync);
1651 rx_PutConnection(callp);
1653 } while (cm_Analyze(connp, userp, reqp, &dscp->fid, &volSync, NULL, NULL, code));
1654 code = cm_MapRPCError(code, reqp);
1657 osi_Log1(afsd_logp, "CALL RemoveFile FAILURE, code 0x%x", code);
1659 osi_Log0(afsd_logp, "CALL RemoveFile SUCCESS");
1662 lock_ObtainWrite(&dirop.scp->dirlock);
1663 dirop.lockType = CM_DIRLOCK_WRITE;
1665 lock_ObtainWrite(&dscp->rw);
1666 cm_dnlcRemove(dscp, normalizedName);
1667 cm_SyncOpDone(dscp, NULL, sflags);
1669 cm_MergeStatus(NULL, dscp, &newDirStatus, &volSync, userp, CM_MERGEFLAG_DIROP);
1670 } else if (code == CM_ERROR_NOSUCHFILE) {
1671 /* windows would not have allowed the request to delete the file
1672 * if it did not believe the file existed. therefore, we must
1673 * have an inconsistent view of the world.
1675 dscp->cbServerp = NULL;
1677 lock_ReleaseWrite(&dscp->rw);
1679 if (code == 0 && cm_CheckDirOpForSingleChange(&dirop) && normalizedName) {
1680 cm_DirDeleteEntry(&dirop, namep);
1682 cm_BPlusDirDeleteEntry(&dirop, normalizedName);
1685 cm_EndDirOp(&dirop);
1688 cm_ReleaseSCache(scp);
1690 lock_ObtainWrite(&scp->rw);
1691 scp->flags |= CM_SCACHEFLAG_DELETED;
1692 lock_ReleaseWrite(&scp->rw);
1699 /* called with a write locked vnode, and fills in the link info.
1700 * returns this the vnode still write locked.
1702 long cm_HandleLink(cm_scache_t *linkScp, cm_user_t *userp, cm_req_t *reqp)
1709 lock_AssertWrite(&linkScp->rw);
1710 if (!linkScp->mountPointStringp[0]) {
1711 /* read the link data */
1712 lock_ReleaseWrite(&linkScp->rw);
1713 thyper.LowPart = thyper.HighPart = 0;
1714 code = buf_Get(linkScp, &thyper, &bufp);
1715 lock_ObtainWrite(&linkScp->rw);
1719 code = cm_SyncOp(linkScp, bufp, userp, reqp, 0,
1720 CM_SCACHESYNC_NEEDCALLBACK | CM_SCACHESYNC_READ);
1725 cm_SyncOpDone(linkScp, bufp, CM_SCACHESYNC_NEEDCALLBACK | CM_SCACHESYNC_READ);
1727 if (cm_HaveBuffer(linkScp, bufp, 0))
1730 code = cm_GetBuffer(linkScp, bufp, NULL, userp, reqp);
1735 } /* while loop to get the data */
1737 /* now if we still have no link read in,
1738 * copy the data from the buffer */
1739 if ((temp = linkScp->length.LowPart) >= MOUNTPOINTLEN) {
1741 return CM_ERROR_TOOBIG;
1744 /* otherwise, it fits; make sure it is still null (could have
1745 * lost race with someone else referencing this link above),
1746 * and if so, copy in the data.
1748 if (!linkScp->mountPointStringp[0]) {
1749 strncpy(linkScp->mountPointStringp, bufp->datap, temp);
1750 linkScp->mountPointStringp[temp] = 0; /* null terminate */
1752 if ( !strnicmp(linkScp->mountPointStringp, "msdfs:", strlen("msdfs:")) )
1753 linkScp->fileType = CM_SCACHETYPE_DFSLINK;
1756 } /* don't have sym link contents cached */
1761 /* called with a held vnode and a path suffix, with the held vnode being a
1762 * symbolic link. Our goal is to generate a new path to interpret, and return
1763 * this new path in newSpaceBufferp. If the new vnode is relative to a dir
1764 * other than the directory containing the symbolic link, then the new root is
1765 * returned in *newRootScpp, otherwise a null is returned there.
1767 long cm_AssembleLink(cm_scache_t *linkScp, char *pathSuffixp,
1768 cm_scache_t **newRootScpp, cm_space_t **newSpaceBufferp,
1769 cm_user_t *userp, cm_req_t *reqp)
1776 *newRootScpp = NULL;
1777 *newSpaceBufferp = NULL;
1779 lock_ObtainWrite(&linkScp->rw);
1780 code = cm_HandleLink(linkScp, userp, reqp);
1784 /* if we may overflow the buffer, bail out; buffer is signficantly
1785 * bigger than max path length, so we don't really have to worry about
1786 * being a little conservative here.
1788 if (strlen(linkScp->mountPointStringp) + strlen(pathSuffixp) + 2
1789 >= CM_UTILS_SPACESIZE) {
1790 code = CM_ERROR_TOOBIG;
1794 tsp = cm_GetSpace();
1795 linkp = linkScp->mountPointStringp;
1796 if (strncmp(linkp, cm_mountRoot, cm_mountRootLen) == 0) {
1797 if (strlen(linkp) > cm_mountRootLen)
1798 strcpy(tsp->data, linkp+cm_mountRootLen+1);
1801 *newRootScpp = cm_data.rootSCachep;
1802 cm_HoldSCache(cm_data.rootSCachep);
1803 } else if (linkp[0] == '\\' && linkp[1] == '\\') {
1804 if (!strnicmp(&linkp[2], cm_NetbiosName, (len = (long)strlen(cm_NetbiosName))))
1806 char * p = &linkp[len + 3];
1807 if (strnicmp(p, "all", 3) == 0)
1810 strcpy(tsp->data, p);
1811 for (p = tsp->data; *p; p++) {
1815 *newRootScpp = cm_data.rootSCachep;
1816 cm_HoldSCache(cm_data.rootSCachep);
1818 linkScp->fileType = CM_SCACHETYPE_DFSLINK;
1819 strcpy(tsp->data, linkp);
1820 code = CM_ERROR_PATH_NOT_COVERED;
1822 } else if ( linkScp->fileType == CM_SCACHETYPE_DFSLINK ||
1823 !strnicmp(linkp, "msdfs:", (len = (long)strlen("msdfs:"))) ) {
1824 linkScp->fileType = CM_SCACHETYPE_DFSLINK;
1825 strcpy(tsp->data, linkp);
1826 code = CM_ERROR_PATH_NOT_COVERED;
1827 } else if (*linkp == '\\' || *linkp == '/') {
1829 /* formerly, this was considered to be from the AFS root,
1830 * but this seems to create problems. instead, we will just
1831 * reject the link */
1832 strcpy(tsp->data, linkp+1);
1833 *newRootScpp = cm_data.rootSCachep;
1834 cm_HoldSCache(cm_data.rootSCachep);
1836 /* we still copy the link data into the response so that
1837 * the user can see what the link points to
1839 linkScp->fileType = CM_SCACHETYPE_INVALID;
1840 strcpy(tsp->data, linkp);
1841 code = CM_ERROR_NOSUCHPATH;
1844 /* a relative link */
1845 strcpy(tsp->data, linkp);
1847 if (pathSuffixp[0] != 0) { /* if suffix string is non-null */
1848 strcat(tsp->data, "\\");
1849 strcat(tsp->data, pathSuffixp);
1852 *newSpaceBufferp = tsp;
1856 if (code == CM_ERROR_PATH_NOT_COVERED && reqp->tidPathp && reqp->relPathp)
1857 cm_VolStatus_Notify_DFS_Mapping(linkScp, reqp->tidPathp, reqp->relPathp);
1861 lock_ReleaseWrite(&linkScp->rw);
1864 #ifdef DEBUG_REFCOUNT
1865 long cm_NameIDbg(cm_scache_t *rootSCachep, char *pathp, long flags,
1866 cm_user_t *userp, char *tidPathp, cm_req_t *reqp, cm_scache_t **outScpp,
1867 char * file, long line)
1869 long cm_NameI(cm_scache_t *rootSCachep, char *pathp, long flags,
1870 cm_user_t *userp, char *tidPathp, cm_req_t *reqp, cm_scache_t **outScpp)
1874 char *tp; /* ptr moving through input buffer */
1875 char tc; /* temp char */
1876 int haveComponent; /* has new component started? */
1877 char component[AFSPATHMAX]; /* this is the new component */
1878 char *cp; /* component name being assembled */
1879 cm_scache_t *tscp; /* current location in the hierarchy */
1880 cm_scache_t *nscp; /* next dude down */
1881 cm_scache_t *dirScp; /* last dir we searched */
1882 cm_scache_t *linkScp; /* new root for the symlink we just
1884 cm_space_t *psp; /* space for current path, if we've hit
1886 cm_space_t *tempsp; /* temp vbl */
1887 char *restp; /* rest of the pathname to interpret */
1888 int symlinkCount; /* count of # of symlinks traversed */
1889 int extraFlag; /* avoid chasing mt pts for dir cmd */
1890 int phase = 1; /* 1 = tidPathp, 2 = pathp */
1891 #define MAX_FID_COUNT 512
1892 cm_fid_t fids[MAX_FID_COUNT]; /* array of fids processed in this path walk */
1893 int fid_count = 0; /* number of fids processed in this path walk */
1896 #ifdef DEBUG_REFCOUNT
1897 afsi_log("%s:%d cm_NameI rootscp 0x%p ref %d", file, line, rootSCachep, rootSCachep->refCount);
1898 osi_Log4(afsd_logp,"cm_NameI rootscp 0x%p path %s tidpath %s flags 0x%x",
1899 rootSCachep, pathp ? pathp : "<NULL>", tidPathp ? tidPathp : "<NULL>",
1914 cm_HoldSCache(tscp);
1922 /* map Unix slashes into DOS ones so we can interpret Unix
1928 if (!haveComponent) {
1931 } else if (tc == 0) {
1945 /* we have a component here */
1946 if (tc == 0 || tc == '\\') {
1947 /* end of the component; we're at the last
1948 * component if tc == 0. However, if the last
1949 * is a symlink, we have more to do.
1951 *cp++ = 0; /* add null termination */
1953 if ((flags & CM_FLAG_DIRSEARCH) && tc == 0)
1954 extraFlag = CM_FLAG_NOMOUNTCHASE;
1955 code = cm_Lookup(tscp, component,
1957 userp, reqp, &nscp);
1960 if (!strcmp(component,"..") || !strcmp(component,".")) {
1962 * roll back the fid list until we find the fid
1963 * that matches where we are now. Its not necessarily
1964 * one or two fids because they might have been
1965 * symlinks or mount points or both that were crossed.
1967 for ( i=fid_count-1; i>=0; i--) {
1968 if (!cm_FidCmp(&nscp->fid, &fids[i]))
1973 /* add the new fid to the list */
1974 for ( i=0; i<fid_count; i++) {
1975 if ( !cm_FidCmp(&nscp->fid, &fids[i]) ) {
1976 code = CM_ERROR_TOO_MANY_SYMLINKS;
1977 cm_ReleaseSCache(nscp);
1982 if (i == fid_count && fid_count < MAX_FID_COUNT) {
1983 fids[fid_count++] = nscp->fid;
1989 cm_ReleaseSCache(tscp);
1991 cm_ReleaseSCache(dirScp);
1994 if ((code == CM_ERROR_NOSUCHFILE || code == CM_ERROR_BPLUS_NOMATCH) &&
1995 tscp->fileType == CM_SCACHETYPE_SYMLINK)
1997 osi_Log0(afsd_logp,"cm_NameI code CM_ERROR_NOSUCHPATH");
1998 return CM_ERROR_NOSUCHPATH;
2000 osi_Log1(afsd_logp,"cm_NameI code 0x%x", code);
2005 haveComponent = 0; /* component done */
2007 cm_ReleaseSCache(dirScp);
2008 dirScp = tscp; /* for some symlinks */
2009 tscp = nscp; /* already held */
2011 if (tc == 0 && !(flags & CM_FLAG_FOLLOW) && phase == 2) {
2014 cm_ReleaseSCache(dirScp);
2020 /* now, if tscp is a symlink, we should follow
2021 * it and assemble the path again.
2023 lock_ObtainWrite(&tscp->rw);
2024 code = cm_SyncOp(tscp, NULL, userp, reqp, 0,
2025 CM_SCACHESYNC_GETSTATUS
2026 | CM_SCACHESYNC_NEEDCALLBACK);
2028 lock_ReleaseWrite(&tscp->rw);
2029 cm_ReleaseSCache(tscp);
2032 cm_ReleaseSCache(dirScp);
2037 cm_SyncOpDone(tscp, NULL, CM_SCACHESYNC_NEEDCALLBACK | CM_SCACHESYNC_GETSTATUS);
2039 if (tscp->fileType == CM_SCACHETYPE_SYMLINK) {
2040 /* this is a symlink; assemble a new buffer */
2041 lock_ReleaseWrite(&tscp->rw);
2042 if (symlinkCount++ >= MAX_SYMLINK_COUNT) {
2043 cm_ReleaseSCache(tscp);
2046 cm_ReleaseSCache(dirScp);
2051 osi_Log0(afsd_logp,"cm_NameI code CM_ERROR_TOO_MANY_SYMLINKS");
2052 return CM_ERROR_TOO_MANY_SYMLINKS;
2058 code = cm_AssembleLink(tscp, restp, &linkScp, &tempsp, userp, reqp);
2060 if (code == 0 && linkScp != NULL) {
2061 if (linkScp == cm_data.rootSCachep)
2064 for ( i=0; i<fid_count; i++) {
2065 if ( !cm_FidCmp(&linkScp->fid, &fids[i]) ) {
2066 code = CM_ERROR_TOO_MANY_SYMLINKS;
2067 cm_ReleaseSCache(linkScp);
2073 if (i == fid_count && fid_count < MAX_FID_COUNT) {
2074 fids[fid_count++] = linkScp->fid;
2079 /* something went wrong */
2080 cm_ReleaseSCache(tscp);
2083 cm_ReleaseSCache(dirScp);
2089 /* otherwise, tempsp has the new path,
2090 * and linkScp is the new root from
2091 * which to interpret that path.
2092 * Continue with the namei processing,
2093 * also doing the bookkeeping for the
2094 * space allocation and tracking the
2095 * vnode reference counts.
2101 cm_ReleaseSCache(tscp);
2106 * now, if linkScp is null, that's
2107 * AssembleLink's way of telling us that
2108 * the sym link is relative to the dir
2109 * containing the link. We have a ref
2110 * to it in dirScp, and we hold it now
2111 * and reuse it as the new spot in the
2119 /* not a symlink, we may be done */
2120 lock_ReleaseWrite(&tscp->rw);
2128 cm_ReleaseSCache(dirScp);
2136 cm_ReleaseSCache(dirScp);
2139 } /* end of a component */
2142 } /* we have a component */
2143 } /* big while loop over all components */
2147 cm_ReleaseSCache(dirScp);
2153 cm_ReleaseSCache(tscp);
2155 #ifdef DEBUG_REFCOUNT
2156 afsi_log("%s:%d cm_NameI code 0x%x outScpp 0x%p ref %d", file, line, code, *outScpp, (*outScpp)->refCount);
2158 osi_Log2(afsd_logp,"cm_NameI code 0x%x outScpp 0x%p", code, *outScpp);
2162 /* called with a dir, and a vnode within the dir that happens to be a symlink.
2163 * We chase the link, and return a held pointer to the target, if it exists,
2164 * in *outScpp. If we succeed, we return 0, otherwise we return an error code
2165 * and do not hold or return a target vnode.
2167 * This is very similar to calling cm_NameI with the last component of a name,
2168 * which happens to be a symlink, except that we've already passed by the name.
2170 * This function is typically called by the directory listing functions, which
2171 * encounter symlinks but need to return the proper file length so programs
2172 * like "more" work properly when they make use of the attributes retrieved from
2175 * The input vnode should not be locked when this function is called.
2177 long cm_EvaluateSymLink(cm_scache_t *dscp, cm_scache_t *linkScp,
2178 cm_scache_t **outScpp, cm_user_t *userp, cm_req_t *reqp)
2182 cm_scache_t *newRootScp;
2184 osi_Log1(afsd_logp, "Evaluating symlink scp 0x%p", linkScp);
2186 code = cm_AssembleLink(linkScp, "", &newRootScp, &spacep, userp, reqp);
2190 /* now, if newRootScp is NULL, we're really being told that the symlink
2191 * is relative to the current directory (dscp).
2193 if (newRootScp == NULL) {
2195 cm_HoldSCache(dscp);
2198 code = cm_NameI(newRootScp, spacep->data,
2199 CM_FLAG_CASEFOLD | CM_FLAG_FOLLOW | CM_FLAG_DIRSEARCH,
2200 userp, NULL, reqp, outScpp);
2202 if (code == CM_ERROR_NOSUCHFILE || code == CM_ERROR_BPLUS_NOMATCH)
2203 code = CM_ERROR_NOSUCHPATH;
2205 /* this stuff is allocated no matter what happened on the namei call,
2207 cm_FreeSpace(spacep);
2208 cm_ReleaseSCache(newRootScp);
2210 if (linkScp == *outScpp) {
2211 cm_ReleaseSCache(*outScpp);
2213 code = CM_ERROR_NOSUCHPATH;
2219 /* make this big enough so that one buffer of dir pages won't overflow. We'll
2220 * check anyway, but we want to minimize the chance that we have to leave stuff
2223 #define CM_BULKMAX (3 * AFSCBMAX)
2225 /* rock for bulk stat calls */
2226 typedef struct cm_bulkStat {
2227 osi_hyper_t bufOffset; /* only do it for things in this buffer page */
2229 /* info for the actual call */
2230 int counter; /* next free slot */
2231 AFSFid fids[CM_BULKMAX];
2232 AFSFetchStatus stats[CM_BULKMAX];
2233 AFSCallBack callbacks[CM_BULKMAX];
2236 /* for a given entry, make sure that it isn't in the stat cache, and then
2237 * add it to the list of file IDs to be obtained.
2239 * Don't bother adding it if we already have a vnode. Note that the dir
2240 * is locked, so we have to be careful checking the vnode we're thinking of
2241 * processing, to avoid deadlocks.
2243 long cm_TryBulkProc(cm_scache_t *scp, cm_dirEntry_t *dep, void *rockp,
2254 /* Don't overflow bsp. */
2255 if (bsp->counter >= CM_BULKMAX)
2256 return CM_ERROR_STOPNOW;
2258 thyper.LowPart = cm_data.buf_blockSize;
2259 thyper.HighPart = 0;
2260 thyper = LargeIntegerAdd(thyper, bsp->bufOffset);
2262 /* thyper is now the first byte past the end of the record we're
2263 * interested in, and bsp->bufOffset is the first byte of the record
2264 * we're interested in.
2265 * Skip data in the others.
2268 if (LargeIntegerLessThan(*offp, bsp->bufOffset))
2270 if (LargeIntegerGreaterThanOrEqualTo(*offp, thyper))
2271 return CM_ERROR_STOPNOW;
2272 if (strcmp(dep->name, ".") == 0 || strcmp(dep->name, "..") == 0)
2275 cm_SetFid(&tfid, scp->fid.cell, scp->fid.volume, ntohl(dep->fid.vnode), ntohl(dep->fid.unique));
2276 tscp = cm_FindSCache(&tfid);
2278 if (lock_TryWrite(&tscp->rw)) {
2279 /* we have an entry that we can look at */
2280 if (!(tscp->flags & CM_SCACHEFLAG_EACCESS) && cm_HaveCallback(tscp)) {
2281 /* we have a callback on it. Don't bother
2282 * fetching this stat entry, since we're happy
2283 * with the info we have.
2285 lock_ReleaseWrite(&tscp->rw);
2286 cm_ReleaseSCache(tscp);
2289 lock_ReleaseWrite(&tscp->rw);
2291 cm_ReleaseSCache(tscp);
2294 #ifdef AFS_FREELANCE_CLIENT
2295 // yj: if this is a mountpoint under root.afs then we don't want it
2296 // to be bulkstat-ed, instead, we call getSCache directly and under
2297 // getSCache, it is handled specially.
2298 if ( cm_freelanceEnabled &&
2299 tfid.cell==AFS_FAKE_ROOT_CELL_ID &&
2300 tfid.volume==AFS_FAKE_ROOT_VOL_ID &&
2301 !(tfid.vnode==0x1 && tfid.unique==0x1) )
2303 osi_Log0(afsd_logp, "cm_TryBulkProc Freelance calls cm_SCache on root.afs mountpoint");
2304 return cm_GetSCache(&tfid, &tscp, NULL, NULL);
2306 #endif /* AFS_FREELANCE_CLIENT */
2309 bsp->fids[i].Volume = scp->fid.volume;
2310 bsp->fids[i].Vnode = tfid.vnode;
2311 bsp->fids[i].Unique = tfid.unique;
2315 /* called with a write locked scp and a pointer to a buffer. Make bulk stat
2316 * calls on all undeleted files in the page of the directory specified.
2319 cm_TryBulkStat(cm_scache_t *dscp, osi_hyper_t *offsetp, cm_user_t *userp,
2323 cm_bulkStat_t bb; /* this is *BIG*, probably 16K or so;
2324 * watch for stack problems */
2325 AFSCBFids fidStruct;
2326 AFSBulkStats statStruct;
2328 AFSCBs callbackStruct;
2331 cm_callbackRequest_t cbReq;
2337 struct rx_connection * callp;
2338 int inlinebulk = 0; /* Did we use InlineBulkStatus RPC or not? */
2340 osi_Log1(afsd_logp, "cm_TryBulkStat dir 0x%p", dscp);
2342 /* should be on a buffer boundary */
2343 osi_assertx((offsetp->LowPart & (cm_data.buf_blockSize - 1)) == 0, "invalid offset");
2345 memset(&bb, 0, sizeof(bb));
2346 bb.bufOffset = *offsetp;
2348 lock_ReleaseWrite(&dscp->rw);
2349 /* first, assemble the file IDs we need to stat */
2350 code = cm_ApplyDir(dscp, cm_TryBulkProc, (void *) &bb, offsetp, userp, reqp, NULL);
2352 /* if we failed, bail out early */
2353 if (code && code != CM_ERROR_STOPNOW) {
2354 lock_ObtainWrite(&dscp->rw);
2358 /* otherwise, we may have one or more bulk stat's worth of stuff in bb;
2359 * make the calls to create the entries. Handle AFSCBMAX files at a
2363 while (filex < bb.counter) {
2364 filesThisCall = bb.counter - filex;
2365 if (filesThisCall > AFSCBMAX)
2366 filesThisCall = AFSCBMAX;
2368 fidStruct.AFSCBFids_len = filesThisCall;
2369 fidStruct.AFSCBFids_val = &bb.fids[filex];
2370 statStruct.AFSBulkStats_len = filesThisCall;
2371 statStruct.AFSBulkStats_val = &bb.stats[filex];
2372 callbackStruct.AFSCBs_len = filesThisCall;
2373 callbackStruct.AFSCBs_val = &bb.callbacks[filex];
2374 cm_StartCallbackGrantingCall(NULL, &cbReq);
2375 osi_Log1(afsd_logp, "CALL BulkStatus, %d entries", filesThisCall);
2377 code = cm_ConnFromFID(&dscp->fid, userp, reqp, &connp);
2381 callp = cm_GetRxConn(connp);
2382 if (!(connp->serverp->flags & CM_SERVERFLAG_NOINLINEBULK)) {
2383 code = RXAFS_InlineBulkStatus(callp, &fidStruct,
2384 &statStruct, &callbackStruct, &volSync);
2385 if (code == RXGEN_OPCODE) {
2386 cm_SetServerNoInlineBulk(connp->serverp, 0);
2392 code = RXAFS_BulkStatus(callp, &fidStruct,
2393 &statStruct, &callbackStruct, &volSync);
2395 rx_PutConnection(callp);
2397 } while (cm_Analyze(connp, userp, reqp, &dscp->fid,
2398 &volSync, NULL, &cbReq, code));
2399 code = cm_MapRPCError(code, reqp);
2401 osi_Log2(afsd_logp, "CALL %sBulkStatus FAILURE code 0x%x",
2402 inlinebulk ? "Inline" : "", code);
2404 osi_Log1(afsd_logp, "CALL %sBulkStatus SUCCESS", inlinebulk ? "Inline" : "");
2406 /* may as well quit on an error, since we're not going to do
2407 * much better on the next immediate call, either.
2410 cm_EndCallbackGrantingCall(NULL, &cbReq, NULL, 0);
2414 /* otherwise, we should do the merges */
2415 for (i = 0; i<filesThisCall; i++) {
2417 cm_SetFid(&tfid, dscp->fid.cell, bb.fids[j].Volume, bb.fids[j].Vnode, bb.fids[j].Unique);
2418 code = cm_GetSCache(&tfid, &scp, userp, reqp);
2422 /* otherwise, if this entry has no callback info,
2425 lock_ObtainWrite(&scp->rw);
2426 /* now, we have to be extra paranoid on merging in this
2427 * information, since we didn't use cm_SyncOp before
2428 * starting the fetch to make sure that no bad races
2429 * were occurring. Specifically, we need to make sure
2430 * we don't obliterate any newer information in the
2431 * vnode than have here.
2433 * Right now, be pretty conservative: if there's a
2434 * callback or a pending call, skip it.
2436 if ((scp->cbServerp == NULL || (scp->flags & CM_SCACHEFLAG_EACCESS))
2438 (CM_SCACHEFLAG_FETCHING
2439 | CM_SCACHEFLAG_STORING
2440 | CM_SCACHEFLAG_SIZESTORING))) {
2441 cm_EndCallbackGrantingCall(scp, &cbReq,
2443 CM_CALLBACK_MAINTAINCOUNT);
2444 cm_MergeStatus(dscp, scp, &bb.stats[j], &volSync, userp, 0);
2446 lock_ReleaseWrite(&scp->rw);
2447 cm_ReleaseSCache(scp);
2448 } /* all files in the response */
2449 /* now tell it to drop the count,
2450 * after doing the vnode processing above */
2451 cm_EndCallbackGrantingCall(NULL, &cbReq, NULL, 0);
2453 filex += filesThisCall;
2454 } /* while there are still more files to process */
2455 lock_ObtainWrite(&dscp->rw);
2457 /* If we did the InlineBulk RPC pull out the return code and log it */
2459 if ((&bb.stats[0])->errorCode) {
2460 osi_Log1(afsd_logp, "cm_TryBulkStat bulk stat error: %d",
2461 (&bb.stats[0])->errorCode);
2465 osi_Log0(afsd_logp, "END cm_TryBulkStat");
2469 void cm_StatusFromAttr(AFSStoreStatus *statusp, cm_scache_t *scp, cm_attr_t *attrp)
2473 /* initialize store back mask as inexpensive local variable */
2475 memset(statusp, 0, sizeof(AFSStoreStatus));
2477 /* copy out queued info from scache first, if scp passed in */
2479 if (scp->mask & CM_SCACHEMASK_CLIENTMODTIME) {
2480 statusp->ClientModTime = scp->clientModTime;
2481 mask |= AFS_SETMODTIME;
2482 scp->mask &= ~CM_SCACHEMASK_CLIENTMODTIME;
2487 /* now add in our locally generated request */
2488 if (attrp->mask & CM_ATTRMASK_CLIENTMODTIME) {
2489 statusp->ClientModTime = attrp->clientModTime;
2490 mask |= AFS_SETMODTIME;
2492 if (attrp->mask & CM_ATTRMASK_UNIXMODEBITS) {
2493 statusp->UnixModeBits = attrp->unixModeBits;
2494 mask |= AFS_SETMODE;
2496 if (attrp->mask & CM_ATTRMASK_OWNER) {
2497 statusp->Owner = attrp->owner;
2498 mask |= AFS_SETOWNER;
2500 if (attrp->mask & CM_ATTRMASK_GROUP) {
2501 statusp->Group = attrp->group;
2502 mask |= AFS_SETGROUP;
2505 statusp->Mask = mask;
2508 /* set the file size, and make sure that all relevant buffers have been
2509 * truncated. Ensure that any partially truncated buffers have been zeroed
2510 * to the end of the buffer.
2512 long cm_SetLength(cm_scache_t *scp, osi_hyper_t *sizep, cm_user_t *userp,
2518 /* start by locking out buffer creation */
2519 lock_ObtainWrite(&scp->bufCreateLock);
2521 /* verify that this is a file, not a dir or a symlink */
2522 lock_ObtainWrite(&scp->rw);
2523 code = cm_SyncOp(scp, NULL, userp, reqp, 0,
2524 CM_SCACHESYNC_NEEDCALLBACK | CM_SCACHESYNC_GETSTATUS);
2527 cm_SyncOpDone(scp, NULL, CM_SCACHESYNC_NEEDCALLBACK | CM_SCACHESYNC_GETSTATUS);
2529 if (scp->fileType != CM_SCACHETYPE_FILE) {
2530 code = CM_ERROR_ISDIR;
2535 if (LargeIntegerLessThan(*sizep, scp->length))
2540 lock_ReleaseWrite(&scp->rw);
2542 /* can't hold scp->rw lock here, since we may wait for a storeback to
2543 * finish if the buffer package is cleaning a buffer by storing it to
2547 buf_Truncate(scp, userp, reqp, sizep);
2549 /* now ensure that file length is short enough, and update truncPos */
2550 lock_ObtainWrite(&scp->rw);
2552 /* make sure we have a callback (so we have the right value for the
2553 * length), and wait for it to be safe to do a truncate.
2555 code = cm_SyncOp(scp, NULL, userp, reqp, PRSFS_WRITE,
2556 CM_SCACHESYNC_NEEDCALLBACK | CM_SCACHESYNC_GETSTATUS
2557 | CM_SCACHESYNC_SETSTATUS | CM_SCACHESYNC_SETSIZE);
2559 /* If we only have 'i' bits, then we should still be able to set
2560 the size of a file we created. */
2561 if (code == CM_ERROR_NOACCESS && scp->creator == userp) {
2562 code = cm_SyncOp(scp, NULL, userp, reqp, PRSFS_INSERT,
2563 CM_SCACHESYNC_NEEDCALLBACK | CM_SCACHESYNC_GETSTATUS
2564 | CM_SCACHESYNC_SETSTATUS | CM_SCACHESYNC_SETSIZE);
2570 if (LargeIntegerLessThan(*sizep, scp->length)) {
2571 /* a real truncation. If truncPos is not set yet, or is bigger
2572 * than where we're truncating the file, set truncPos to this
2577 if (!(scp->mask & CM_SCACHEMASK_TRUNCPOS)
2578 || LargeIntegerLessThan(*sizep, scp->length)) {
2580 scp->truncPos = *sizep;
2581 scp->mask |= CM_SCACHEMASK_TRUNCPOS;
2583 /* in either case, the new file size has been changed */
2584 scp->length = *sizep;
2585 scp->mask |= CM_SCACHEMASK_LENGTH;
2587 else if (LargeIntegerGreaterThan(*sizep, scp->length)) {
2588 /* really extending the file */
2589 scp->length = *sizep;
2590 scp->mask |= CM_SCACHEMASK_LENGTH;
2593 /* done successfully */
2596 cm_SyncOpDone(scp, NULL,
2597 CM_SCACHESYNC_NEEDCALLBACK | CM_SCACHESYNC_GETSTATUS
2598 | CM_SCACHESYNC_SETSTATUS | CM_SCACHESYNC_SETSIZE);
2601 lock_ReleaseWrite(&scp->rw);
2602 lock_ReleaseWrite(&scp->bufCreateLock);
2607 /* set the file size or other attributes (but not both at once) */
2608 long cm_SetAttr(cm_scache_t *scp, cm_attr_t *attrp, cm_user_t *userp,
2612 AFSFetchStatus afsOutStatus;
2616 AFSStoreStatus afsInStatus;
2617 struct rx_connection * callp;
2619 /* handle file length setting */
2620 if (attrp->mask & CM_ATTRMASK_LENGTH)
2621 return cm_SetLength(scp, &attrp->length, userp, reqp);
2623 lock_ObtainWrite(&scp->rw);
2624 /* otherwise, we have to make an RPC to get the status */
2625 code = cm_SyncOp(scp, NULL, userp, reqp, 0, CM_SCACHESYNC_STORESTATUS);
2627 lock_ReleaseWrite(&scp->rw);
2630 lock_ConvertWToR(&scp->rw);
2632 /* make the attr structure */
2633 cm_StatusFromAttr(&afsInStatus, scp, attrp);
2635 tfid.Volume = scp->fid.volume;
2636 tfid.Vnode = scp->fid.vnode;
2637 tfid.Unique = scp->fid.unique;
2638 lock_ReleaseRead(&scp->rw);
2640 /* now make the RPC */
2641 osi_Log1(afsd_logp, "CALL StoreStatus scp 0x%p", scp);
2643 code = cm_ConnFromFID(&scp->fid, userp, reqp, &connp);
2647 callp = cm_GetRxConn(connp);
2648 code = RXAFS_StoreStatus(callp, &tfid,
2649 &afsInStatus, &afsOutStatus, &volSync);
2650 rx_PutConnection(callp);
2652 } while (cm_Analyze(connp, userp, reqp,
2653 &scp->fid, &volSync, NULL, NULL, code));
2654 code = cm_MapRPCError(code, reqp);
2657 osi_Log1(afsd_logp, "CALL StoreStatus FAILURE, code 0x%x", code);
2659 osi_Log0(afsd_logp, "CALL StoreStatus SUCCESS");
2661 lock_ObtainWrite(&scp->rw);
2662 cm_SyncOpDone(scp, NULL, CM_SCACHESYNC_STORESTATUS);
2664 cm_MergeStatus(NULL, scp, &afsOutStatus, &volSync, userp,
2665 CM_MERGEFLAG_FORCE|CM_MERGEFLAG_STOREDATA);
2667 /* if we're changing the mode bits, discard the ACL cache,
2668 * since we changed the mode bits.
2670 if (afsInStatus.Mask & AFS_SETMODE)
2671 cm_FreeAllACLEnts(scp);
2672 lock_ReleaseWrite(&scp->rw);
2676 long cm_Create(cm_scache_t *dscp, char *namep, long flags, cm_attr_t *attrp,
2677 cm_scache_t **scpp, cm_user_t *userp, cm_req_t *reqp)
2682 cm_callbackRequest_t cbReq;
2685 cm_scache_t *scp = NULL;
2687 AFSStoreStatus inStatus;
2688 AFSFetchStatus updatedDirStatus;
2689 AFSFetchStatus newFileStatus;
2690 AFSCallBack newFileCallback;
2692 struct rx_connection * callp;
2695 /* can't create names with @sys in them; must expand it manually first.
2696 * return "invalid request" if they try.
2698 if (cm_ExpandSysName(namep, NULL, 0, 0)) {
2699 return CM_ERROR_ATSYS;
2702 #ifdef AFS_FREELANCE_CLIENT
2703 /* Freelance root volume does not hold files */
2704 if (cm_freelanceEnabled &&
2705 dscp->fid.cell==AFS_FAKE_ROOT_CELL_ID &&
2706 dscp->fid.volume==AFS_FAKE_ROOT_VOL_ID )
2708 return CM_ERROR_NOACCESS;
2710 #endif /* AFS_FREELANCE_CLIENT */
2712 /* before starting the RPC, mark that we're changing the file data, so
2713 * that someone who does a chmod will know to wait until our call
2716 cm_BeginDirOp(dscp, userp, reqp, CM_DIRLOCK_NONE, &dirop);
2717 lock_ObtainWrite(&dscp->rw);
2718 code = cm_SyncOp(dscp, NULL, userp, reqp, 0, CM_SCACHESYNC_STOREDATA);
2719 lock_ReleaseWrite(&dscp->rw);
2721 cm_StartCallbackGrantingCall(NULL, &cbReq);
2723 cm_EndDirOp(&dirop);
2730 cm_StatusFromAttr(&inStatus, NULL, attrp);
2732 /* try the RPC now */
2733 osi_Log1(afsd_logp, "CALL CreateFile scp 0x%p", dscp);
2735 code = cm_ConnFromFID(&dscp->fid, userp, reqp, &connp);
2739 dirAFSFid.Volume = dscp->fid.volume;
2740 dirAFSFid.Vnode = dscp->fid.vnode;
2741 dirAFSFid.Unique = dscp->fid.unique;
2743 callp = cm_GetRxConn(connp);
2744 code = RXAFS_CreateFile(connp->callp, &dirAFSFid, namep,
2745 &inStatus, &newAFSFid, &newFileStatus,
2746 &updatedDirStatus, &newFileCallback,
2748 rx_PutConnection(callp);
2750 } while (cm_Analyze(connp, userp, reqp,
2751 &dscp->fid, &volSync, NULL, &cbReq, code));
2752 code = cm_MapRPCError(code, reqp);
2755 osi_Log1(afsd_logp, "CALL CreateFile FAILURE, code 0x%x", code);
2757 osi_Log0(afsd_logp, "CALL CreateFile SUCCESS");
2760 lock_ObtainWrite(&dirop.scp->dirlock);
2761 dirop.lockType = CM_DIRLOCK_WRITE;
2763 lock_ObtainWrite(&dscp->rw);
2764 cm_SyncOpDone(dscp, NULL, CM_SCACHESYNC_STOREDATA);
2766 cm_MergeStatus(NULL, dscp, &updatedDirStatus, &volSync, userp, CM_MERGEFLAG_DIROP);
2768 lock_ReleaseWrite(&dscp->rw);
2770 /* now try to create the file's entry, too, but be careful to
2771 * make sure that we don't merge in old info. Since we weren't locking
2772 * out any requests during the file's creation, we may have pretty old
2776 cm_SetFid(&newFid, dscp->fid.cell, dscp->fid.volume, newAFSFid.Vnode, newAFSFid.Unique);
2777 code = cm_GetSCache(&newFid, &scp, userp, reqp);
2779 lock_ObtainWrite(&scp->rw);
2780 scp->creator = userp; /* remember who created it */
2781 if (!cm_HaveCallback(scp)) {
2782 cm_MergeStatus(dscp, scp, &newFileStatus, &volSync,
2784 cm_EndCallbackGrantingCall(scp, &cbReq,
2785 &newFileCallback, 0);
2788 lock_ReleaseWrite(&scp->rw);
2793 /* make sure we end things properly */
2795 cm_EndCallbackGrantingCall(NULL, &cbReq, NULL, 0);
2797 if (scp && cm_CheckDirOpForSingleChange(&dirop)) {
2798 cm_DirCreateEntry(&dirop, namep, &newFid);
2800 cm_BPlusDirCreateEntry(&dirop, namep, &newFid);
2803 cm_EndDirOp(&dirop);
2808 long cm_FSync(cm_scache_t *scp, cm_user_t *userp, cm_req_t *reqp)
2812 code = buf_CleanVnode(scp, userp, reqp);
2814 lock_ObtainWrite(&scp->rw);
2816 if (scp->mask & (CM_SCACHEMASK_TRUNCPOS
2817 | CM_SCACHEMASK_CLIENTMODTIME
2818 | CM_SCACHEMASK_LENGTH))
2819 code = cm_StoreMini(scp, userp, reqp);
2821 if (scp->flags & (CM_SCACHEFLAG_OVERQUOTA | CM_SCACHEFLAG_OUTOFSPACE)) {
2822 code = (scp->flags & CM_SCACHEFLAG_OVERQUOTA) ? CM_ERROR_QUOTA : CM_ERROR_SPACE;
2823 scp->flags &= ~(CM_SCACHEFLAG_OVERQUOTA | CM_SCACHEFLAG_OUTOFSPACE);
2826 lock_ReleaseWrite(&scp->rw);
2831 long cm_MakeDir(cm_scache_t *dscp, char *namep, long flags, cm_attr_t *attrp,
2832 cm_user_t *userp, cm_req_t *reqp)
2837 cm_callbackRequest_t cbReq;
2840 cm_scache_t *scp = NULL;
2842 AFSStoreStatus inStatus;
2843 AFSFetchStatus updatedDirStatus;
2844 AFSFetchStatus newDirStatus;
2845 AFSCallBack newDirCallback;
2847 struct rx_connection * callp;
2850 /* can't create names with @sys in them; must expand it manually first.
2851 * return "invalid request" if they try.
2853 if (cm_ExpandSysName(namep, NULL, 0, 0)) {
2854 return CM_ERROR_ATSYS;
2857 #ifdef AFS_FREELANCE_CLIENT
2858 /* Freelance root volume does not hold subdirectories */
2859 if (cm_freelanceEnabled &&
2860 dscp->fid.cell==AFS_FAKE_ROOT_CELL_ID &&
2861 dscp->fid.volume==AFS_FAKE_ROOT_VOL_ID )
2863 return CM_ERROR_NOACCESS;
2865 #endif /* AFS_FREELANCE_CLIENT */
2867 /* before starting the RPC, mark that we're changing the directory
2868 * data, so that someone who does a chmod on the dir will wait until
2869 * our call completes.
2871 cm_BeginDirOp(dscp, userp, reqp, CM_DIRLOCK_NONE, &dirop);
2872 lock_ObtainWrite(&dscp->rw);
2873 code = cm_SyncOp(dscp, NULL, userp, reqp, 0, CM_SCACHESYNC_STOREDATA);
2874 lock_ReleaseWrite(&dscp->rw);
2876 cm_StartCallbackGrantingCall(NULL, &cbReq);
2878 cm_EndDirOp(&dirop);
2885 cm_StatusFromAttr(&inStatus, NULL, attrp);
2887 /* try the RPC now */
2888 osi_Log1(afsd_logp, "CALL MakeDir scp 0x%p", dscp);
2890 code = cm_ConnFromFID(&dscp->fid, userp, reqp, &connp);
2894 dirAFSFid.Volume = dscp->fid.volume;
2895 dirAFSFid.Vnode = dscp->fid.vnode;
2896 dirAFSFid.Unique = dscp->fid.unique;
2898 callp = cm_GetRxConn(connp);
2899 code = RXAFS_MakeDir(connp->callp, &dirAFSFid, namep,
2900 &inStatus, &newAFSFid, &newDirStatus,
2901 &updatedDirStatus, &newDirCallback,
2903 rx_PutConnection(callp);
2905 } while (cm_Analyze(connp, userp, reqp,
2906 &dscp->fid, &volSync, NULL, &cbReq, code));
2907 code = cm_MapRPCError(code, reqp);
2910 osi_Log1(afsd_logp, "CALL MakeDir FAILURE, code 0x%x", code);
2912 osi_Log0(afsd_logp, "CALL MakeDir SUCCESS");
2915 lock_ObtainWrite(&dirop.scp->dirlock);
2916 dirop.lockType = CM_DIRLOCK_WRITE;
2918 lock_ObtainWrite(&dscp->rw);
2919 cm_SyncOpDone(dscp, NULL, CM_SCACHESYNC_STOREDATA);
2921 cm_MergeStatus(NULL, dscp, &updatedDirStatus, &volSync, userp, CM_MERGEFLAG_DIROP);
2923 lock_ReleaseWrite(&dscp->rw);
2925 /* now try to create the new dir's entry, too, but be careful to
2926 * make sure that we don't merge in old info. Since we weren't locking
2927 * out any requests during the file's creation, we may have pretty old
2931 cm_SetFid(&newFid, dscp->fid.cell, dscp->fid.volume, newAFSFid.Vnode, newAFSFid.Unique);
2932 code = cm_GetSCache(&newFid, &scp, userp, reqp);
2934 lock_ObtainWrite(&scp->rw);
2935 if (!cm_HaveCallback(scp)) {
2936 cm_MergeStatus(dscp, scp, &newDirStatus, &volSync,
2938 cm_EndCallbackGrantingCall(scp, &cbReq,
2939 &newDirCallback, 0);
2942 lock_ReleaseWrite(&scp->rw);
2943 cm_ReleaseSCache(scp);
2947 /* make sure we end things properly */
2949 cm_EndCallbackGrantingCall(NULL, &cbReq, NULL, 0);
2951 if (scp && cm_CheckDirOpForSingleChange(&dirop)) {
2952 cm_DirCreateEntry(&dirop, namep, &newFid);
2954 cm_BPlusDirCreateEntry(&dirop, namep, &newFid);
2957 cm_EndDirOp(&dirop);
2959 /* and return error code */
2963 long cm_Link(cm_scache_t *dscp, char *namep, cm_scache_t *sscp, long flags,
2964 cm_user_t *userp, cm_req_t *reqp)
2969 AFSFid existingAFSFid;
2970 AFSFetchStatus updatedDirStatus;
2971 AFSFetchStatus newLinkStatus;
2973 struct rx_connection * callp;
2976 if (dscp->fid.cell != sscp->fid.cell ||
2977 dscp->fid.volume != sscp->fid.volume) {
2978 return CM_ERROR_CROSSDEVLINK;
2981 cm_BeginDirOp(dscp, userp, reqp, CM_DIRLOCK_NONE, &dirop);
2982 lock_ObtainWrite(&dscp->rw);
2983 code = cm_SyncOp(dscp, NULL, userp, reqp, 0, CM_SCACHESYNC_STOREDATA);
2984 lock_ReleaseWrite(&dscp->rw);
2986 cm_EndDirOp(&dirop);
2991 /* try the RPC now */
2992 osi_Log1(afsd_logp, "CALL Link scp 0x%p", dscp);
2994 code = cm_ConnFromFID(&dscp->fid, userp, reqp, &connp);
2997 dirAFSFid.Volume = dscp->fid.volume;
2998 dirAFSFid.Vnode = dscp->fid.vnode;
2999 dirAFSFid.Unique = dscp->fid.unique;
3001 existingAFSFid.Volume = sscp->fid.volume;
3002 existingAFSFid.Vnode = sscp->fid.vnode;
3003 existingAFSFid.Unique = sscp->fid.unique;
3005 callp = cm_GetRxConn(connp);
3006 code = RXAFS_Link(callp, &dirAFSFid, namep, &existingAFSFid,
3007 &newLinkStatus, &updatedDirStatus, &volSync);
3008 rx_PutConnection(callp);
3009 osi_Log1(afsd_logp," RXAFS_Link returns 0x%x", code);
3011 } while (cm_Analyze(connp, userp, reqp,
3012 &dscp->fid, &volSync, NULL, NULL, code));
3014 code = cm_MapRPCError(code, reqp);
3017 osi_Log1(afsd_logp, "CALL Link FAILURE, code 0x%x", code);
3019 osi_Log0(afsd_logp, "CALL Link SUCCESS");
3022 lock_ObtainWrite(&dirop.scp->dirlock);
3023 dirop.lockType = CM_DIRLOCK_WRITE;
3025 lock_ObtainWrite(&dscp->rw);
3026 cm_SyncOpDone(dscp, NULL, CM_SCACHESYNC_STOREDATA);
3028 cm_MergeStatus(NULL, dscp, &updatedDirStatus, &volSync, userp, CM_MERGEFLAG_DIROP);
3030 lock_ReleaseWrite(&dscp->rw);
3033 if (cm_CheckDirOpForSingleChange(&dirop)) {
3034 cm_DirCreateEntry(&dirop, namep, &sscp->fid);
3036 cm_BPlusDirCreateEntry(&dirop, namep, &sscp->fid);
3040 cm_EndDirOp(&dirop);
3045 long cm_SymLink(cm_scache_t *dscp, char *namep, char *contentsp, long flags,
3046 cm_attr_t *attrp, cm_user_t *userp, cm_req_t *reqp)
3054 AFSStoreStatus inStatus;
3055 AFSFetchStatus updatedDirStatus;
3056 AFSFetchStatus newLinkStatus;
3058 struct rx_connection * callp;
3061 /* before starting the RPC, mark that we're changing the directory data,
3062 * so that someone who does a chmod on the dir will wait until our
3065 cm_BeginDirOp(dscp, userp, reqp, CM_DIRLOCK_NONE, &dirop);
3066 lock_ObtainWrite(&dscp->rw);
3067 code = cm_SyncOp(dscp, NULL, userp, reqp, 0, CM_SCACHESYNC_STOREDATA);
3068 lock_ReleaseWrite(&dscp->rw);
3070 cm_EndDirOp(&dirop);
3075 cm_StatusFromAttr(&inStatus, NULL, attrp);
3077 /* try the RPC now */
3078 osi_Log1(afsd_logp, "CALL Symlink scp 0x%p", dscp);
3080 code = cm_ConnFromFID(&dscp->fid, userp, reqp, &connp);
3084 dirAFSFid.Volume = dscp->fid.volume;
3085 dirAFSFid.Vnode = dscp->fid.vnode;
3086 dirAFSFid.Unique = dscp->fid.unique;
3088 callp = cm_GetRxConn(connp);
3089 code = RXAFS_Symlink(callp, &dirAFSFid, namep, contentsp,
3090 &inStatus, &newAFSFid, &newLinkStatus,
3091 &updatedDirStatus, &volSync);
3092 rx_PutConnection(callp);
3094 } while (cm_Analyze(connp, userp, reqp,
3095 &dscp->fid, &volSync, NULL, NULL, code));
3096 code = cm_MapRPCError(code, reqp);
3099 osi_Log1(afsd_logp, "CALL Symlink FAILURE, code 0x%x", code);
3101 osi_Log0(afsd_logp, "CALL Symlink SUCCESS");
3104 lock_ObtainWrite(&dirop.scp->dirlock);
3105 dirop.lockType = CM_DIRLOCK_WRITE;
3107 lock_ObtainWrite(&dscp->rw);
3108 cm_SyncOpDone(dscp, NULL, CM_SCACHESYNC_STOREDATA);
3110 cm_MergeStatus(NULL, dscp, &updatedDirStatus, &volSync, userp, CM_MERGEFLAG_DIROP);
3112 lock_ReleaseWrite(&dscp->rw);
3115 if (cm_CheckDirOpForSingleChange(&dirop)) {
3116 cm_SetFid(&newFid, dscp->fid.cell, dscp->fid.volume, newAFSFid.Vnode, newAFSFid.Unique);
3118 cm_DirCreateEntry(&dirop, namep, &newFid);
3120 cm_BPlusDirCreateEntry(&dirop, namep, &newFid);
3124 cm_EndDirOp(&dirop);
3126 /* now try to create the new dir's entry, too, but be careful to
3127 * make sure that we don't merge in old info. Since we weren't locking
3128 * out any requests during the file's creation, we may have pretty old
3132 cm_SetFid(&newFid, dscp->fid.cell, dscp->fid.volume, newAFSFid.Vnode, newAFSFid.Unique);
3133 code = cm_GetSCache(&newFid, &scp, userp, reqp);
3135 lock_ObtainWrite(&scp->rw);
3136 if (!cm_HaveCallback(scp)) {
3137 cm_MergeStatus(dscp, scp, &newLinkStatus, &volSync,
3140 lock_ReleaseWrite(&scp->rw);
3141 cm_ReleaseSCache(scp);
3145 /* and return error code */
3149 /*! \brief Remove a directory
3151 Encapsulates a call to RXAFS_RemoveDir().
3153 \param[in] dscp cm_scache_t for the directory containing the
3154 directory to be removed.
3156 \param[in] namep Non-normalized name of the directory to be
3157 removed. This will be the name that is passed in to
3160 \param[in] normalizedNamep Normalized name used to update the local
3163 \param[in] userp cm_user_t for the request.
3165 \param[in] reqp Request tracker.
3167 long cm_RemoveDir(cm_scache_t *dscp, char *namep, char *normalizedNamep,
3168 cm_user_t *userp, cm_req_t *reqp)
3174 AFSFetchStatus updatedDirStatus;
3176 struct rx_connection * callp;
3178 cm_scache_t *scp = NULL;
3180 code = cm_Lookup(dscp, namep, CM_FLAG_NOMOUNTCHASE, userp, reqp, &scp);
3182 /* before starting the RPC, mark that we're changing the directory data,
3183 * so that someone who does a chmod on the dir will wait until our
3186 cm_BeginDirOp(dscp, userp, reqp, CM_DIRLOCK_NONE, &dirop);
3187 lock_ObtainWrite(&dscp->rw);
3188 code = cm_SyncOp(dscp, NULL, userp, reqp, 0, CM_SCACHESYNC_STOREDATA);
3189 lock_ReleaseWrite(&dscp->rw);
3191 cm_EndDirOp(&dirop);
3196 /* try the RPC now */
3197 osi_Log1(afsd_logp, "CALL RemoveDir scp 0x%p", dscp);
3199 code = cm_ConnFromFID(&dscp->fid, userp, reqp, &connp);
3203 dirAFSFid.Volume = dscp->fid.volume;
3204 dirAFSFid.Vnode = dscp->fid.vnode;
3205 dirAFSFid.Unique = dscp->fid.unique;
3207 callp = cm_GetRxConn(connp);
3208 code = RXAFS_RemoveDir(callp, &dirAFSFid, namep,
3209 &updatedDirStatus, &volSync);
3210 rx_PutConnection(callp);
3212 } while (cm_Analyze(connp, userp, reqp,
3213 &dscp->fid, &volSync, NULL, NULL, code));
3214 code = cm_MapRPCErrorRmdir(code, reqp);
3217 osi_Log1(afsd_logp, "CALL RemoveDir FAILURE, code 0x%x", code);
3219 osi_Log0(afsd_logp, "CALL RemoveDir SUCCESS");
3222 lock_ObtainWrite(&dirop.scp->dirlock);
3223 dirop.lockType = CM_DIRLOCK_WRITE;
3225 lock_ObtainWrite(&dscp->rw);
3226 cm_SyncOpDone(dscp, NULL, CM_SCACHESYNC_STOREDATA);
3228 cm_dnlcRemove(dscp, normalizedNamep);
3229 cm_MergeStatus(NULL, dscp, &updatedDirStatus, &volSync, userp, CM_MERGEFLAG_DIROP);
3231 lock_ReleaseWrite(&dscp->rw);
3234 if (cm_CheckDirOpForSingleChange(&dirop) && normalizedNamep != NULL) {
3235 cm_DirDeleteEntry(&dirop, namep);
3237 cm_BPlusDirDeleteEntry(&dirop, normalizedNamep);
3241 cm_EndDirOp(&dirop);
3244 cm_ReleaseSCache(scp);
3246 lock_ObtainWrite(&scp->rw);
3247 scp->flags |= CM_SCACHEFLAG_DELETED;
3248 lock_ReleaseWrite(&scp->rw);
3252 /* and return error code */
3256 long cm_Open(cm_scache_t *scp, int type, cm_user_t *userp)
3258 /* grab mutex on contents */
3259 lock_ObtainWrite(&scp->rw);
3261 /* reset the prefetch info */
3262 scp->prefetch.base.LowPart = 0; /* base */
3263 scp->prefetch.base.HighPart = 0;
3264 scp->prefetch.end.LowPart = 0; /* and end */
3265 scp->prefetch.end.HighPart = 0;
3267 /* release mutex on contents */
3268 lock_ReleaseWrite(&scp->rw);
3274 /*! \brief Rename a file or directory
3276 Encapsulates a RXAFS_Rename() call.
3278 \param[in] oldDscp cm_scache_t for the directory containing the old
3281 \param[in] oldNamep Non-normalized old name. This is the name that
3282 will be passed into the RXAFS_Rename().
3284 \param[in] normalizedOldNamep Normalized old name. This is used for
3285 updating local directory caches.
3287 \param[in] newDscp cm_scache_t for the directory containing the new
3290 \param[in] newNamep New name. Normalized.
3292 \param[in] userp cm_user_t for the request.
3294 \param[in,out] reqp Request tracker.
3297 long cm_Rename(cm_scache_t *oldDscp, char *oldNamep, char *normalizedOldNamep,
3298 cm_scache_t *newDscp, char *newNamep, cm_user_t *userp,
3303 AFSFid oldDirAFSFid;
3304 AFSFid newDirAFSFid;
3306 AFSFetchStatus updatedOldDirStatus;
3307 AFSFetchStatus updatedNewDirStatus;
3310 struct rx_connection * callp;
3311 cm_dirOp_t oldDirOp;
3314 cm_dirOp_t newDirOp;
3316 /* before starting the RPC, mark that we're changing the directory data,
3317 * so that someone who does a chmod on the dir will wait until our call
3318 * completes. We do this in vnode order so that we don't deadlock,
3319 * which makes the code a little verbose.
3321 if (oldDscp == newDscp) {
3322 /* check for identical names */
3323 if (strcmp(oldNamep, newNamep) == 0)
3324 return CM_ERROR_RENAME_IDENTICAL;
3327 cm_BeginDirOp(oldDscp, userp, reqp, CM_DIRLOCK_NONE, &oldDirOp);
3328 lock_ObtainWrite(&oldDscp->rw);
3329 cm_dnlcRemove(oldDscp, normalizedOldNamep);
3330 cm_dnlcRemove(oldDscp, newNamep);
3331 code = cm_SyncOp(oldDscp, NULL, userp, reqp, 0,
3332 CM_SCACHESYNC_STOREDATA);
3333 lock_ReleaseWrite(&oldDscp->rw);
3335 cm_EndDirOp(&oldDirOp);
3339 /* two distinct dir vnodes */
3341 if (oldDscp->fid.cell != newDscp->fid.cell ||
3342 oldDscp->fid.volume != newDscp->fid.volume)
3343 return CM_ERROR_CROSSDEVLINK;
3345 /* shouldn't happen that we have distinct vnodes for two
3346 * different files, but could due to deliberate attack, or
3347 * stale info. Avoid deadlocks and quit now.
3349 if (oldDscp->fid.vnode == newDscp->fid.vnode)
3350 return CM_ERROR_CROSSDEVLINK;
3352 if (oldDscp->fid.vnode < newDscp->fid.vnode) {
3353 cm_BeginDirOp(oldDscp, userp, reqp, CM_DIRLOCK_NONE, &oldDirOp);
3354 lock_ObtainWrite(&oldDscp->rw);
3355 cm_dnlcRemove(oldDscp, normalizedOldNamep);
3356 code = cm_SyncOp(oldDscp, NULL, userp, reqp, 0,
3357 CM_SCACHESYNC_STOREDATA);
3358 lock_ReleaseWrite(&oldDscp->rw);
3360 cm_EndDirOp(&oldDirOp);
3362 cm_BeginDirOp(newDscp, userp, reqp, CM_DIRLOCK_NONE, &newDirOp);
3363 lock_ObtainWrite(&newDscp->rw);
3364 cm_dnlcRemove(newDscp, newNamep);
3365 code = cm_SyncOp(newDscp, NULL, userp, reqp, 0,
3366 CM_SCACHESYNC_STOREDATA);
3367 lock_ReleaseWrite(&newDscp->rw);
3369 cm_EndDirOp(&newDirOp);
3371 /* cleanup first one */
3372 lock_ObtainWrite(&oldDscp->rw);
3373 cm_SyncOpDone(oldDscp, NULL,
3374 CM_SCACHESYNC_STOREDATA);
3375 lock_ReleaseWrite(&oldDscp->rw);
3376 cm_EndDirOp(&oldDirOp);
3381 /* lock the new vnode entry first */
3382 cm_BeginDirOp(newDscp, userp, reqp, CM_DIRLOCK_NONE, &newDirOp);
3383 lock_ObtainWrite(&newDscp->rw);
3384 cm_dnlcRemove(newDscp, newNamep);
3385 code = cm_SyncOp(newDscp, NULL, userp, reqp, 0,
3386 CM_SCACHESYNC_STOREDATA);
3387 lock_ReleaseWrite(&newDscp->rw);
3389 cm_EndDirOp(&newDirOp);
3391 cm_BeginDirOp(oldDscp, userp, reqp, CM_DIRLOCK_NONE, &oldDirOp);
3392 lock_ObtainWrite(&oldDscp->rw);
3393 cm_dnlcRemove(oldDscp, normalizedOldNamep);
3394 code = cm_SyncOp(oldDscp, NULL, userp, reqp, 0,
3395 CM_SCACHESYNC_STOREDATA);
3396 lock_ReleaseWrite(&oldDscp->rw);
3398 cm_EndDirOp(&oldDirOp);
3400 /* cleanup first one */
3401 lock_ObtainWrite(&newDscp->rw);
3402 cm_SyncOpDone(newDscp, NULL,
3403 CM_SCACHESYNC_STOREDATA);
3404 lock_ReleaseWrite(&newDscp->rw);
3405 cm_EndDirOp(&newDirOp);
3409 } /* two distinct vnodes */
3416 /* try the RPC now */
3417 osi_Log2(afsd_logp, "CALL Rename old scp 0x%p new scp 0x%p",
3420 code = cm_ConnFromFID(&oldDscp->fid, userp, reqp, &connp);
3424 oldDirAFSFid.Volume = oldDscp->fid.volume;
3425 oldDirAFSFid.Vnode = oldDscp->fid.vnode;
3426 oldDirAFSFid.Unique = oldDscp->fid.unique;
3427 newDirAFSFid.Volume = newDscp->fid.volume;
3428 newDirAFSFid.Vnode = newDscp->fid.vnode;
3429 newDirAFSFid.Unique = newDscp->fid.unique;
3431 callp = cm_GetRxConn(connp);
3432 code = RXAFS_Rename(callp, &oldDirAFSFid, oldNamep,
3433 &newDirAFSFid, newNamep,
3434 &updatedOldDirStatus, &updatedNewDirStatus,
3436 rx_PutConnection(callp);
3438 } while (cm_Analyze(connp, userp, reqp, &oldDscp->fid,
3439 &volSync, NULL, NULL, code));
3440 code = cm_MapRPCError(code, reqp);
3443 osi_Log1(afsd_logp, "CALL Rename FAILURE, code 0x%x", code);
3445 osi_Log0(afsd_logp, "CALL Rename SUCCESS");
3447 /* update the individual stat cache entries for the directories */
3449 lock_ObtainWrite(&oldDirOp.scp->dirlock);
3450 oldDirOp.lockType = CM_DIRLOCK_WRITE;
3452 lock_ObtainWrite(&oldDscp->rw);
3453 cm_SyncOpDone(oldDscp, NULL, CM_SCACHESYNC_STOREDATA);
3456 cm_MergeStatus(NULL, oldDscp, &updatedOldDirStatus, &volSync,
3457 userp, CM_MERGEFLAG_DIROP);
3458 lock_ReleaseWrite(&oldDscp->rw);
3461 if (cm_CheckDirOpForSingleChange(&oldDirOp)) {
3464 diropCode = cm_BPlusDirLookup(&oldDirOp, normalizedOldNamep, &fileFid);
3465 if (diropCode == CM_ERROR_INEXACT_MATCH)
3467 else if (diropCode == EINVAL)
3469 diropCode = cm_DirLookup(&oldDirOp, oldNamep, &fileFid);
3471 if (diropCode == 0) {
3473 diropCode = cm_DirCreateEntry(&oldDirOp, newNamep, &fileFid);
3475 cm_BPlusDirCreateEntry(&oldDirOp, newNamep, &fileFid);
3479 if (diropCode == 0) {
3480 diropCode = cm_DirDeleteEntry(&oldDirOp, oldNamep);
3482 cm_BPlusDirDeleteEntry(&oldDirOp, normalizedOldNamep);
3488 cm_EndDirOp(&oldDirOp);
3490 /* and update it for the new one, too, if necessary */
3493 lock_ObtainWrite(&newDirOp.scp->dirlock);
3494 newDirOp.lockType = CM_DIRLOCK_WRITE;
3496 lock_ObtainWrite(&newDscp->rw);
3497 cm_SyncOpDone(newDscp, NULL, CM_SCACHESYNC_STOREDATA);
3499 cm_MergeStatus(NULL, newDscp, &updatedNewDirStatus, &volSync,
3500 userp, CM_MERGEFLAG_DIROP);
3501 lock_ReleaseWrite(&newDscp->rw);
3504 /* we only make the local change if we successfully made
3505 the change in the old directory AND there was only one
3506 change in the new directory */
3507 if (diropCode == 0 && cm_CheckDirOpForSingleChange(&newDirOp)) {
3508 cm_DirCreateEntry(&newDirOp, newNamep, &fileFid);
3510 cm_BPlusDirCreateEntry(&newDirOp, newNamep, &fileFid);
3514 cm_EndDirOp(&newDirOp);
3517 /* and return error code */
3521 /* Byte range locks:
3523 The OpenAFS Windows client has to fake byte range locks given no
3524 server side support for such locks. This is implemented as keyed
3525 byte range locks on the cache manager.
3527 Keyed byte range locks:
3529 Each cm_scache_t structure keeps track of a list of keyed locks.
3530 The key for a lock identifies an owner of a set of locks (referred
3531 to as a client). Each key is represented by a value. The set of
3532 key values used within a specific cm_scache_t structure form a
3533 namespace that has a scope of just that cm_scache_t structure. The
3534 same key value can be used with another cm_scache_t structure and
3535 correspond to a completely different client. However it is
3536 advantageous for the SMB or IFS layer to make sure that there is a
3537 1-1 mapping between client and keys over all cm_scache_t objects.
3539 Assume a client C has key Key(C) (although, since the scope of the
3540 key is a cm_scache_t, the key can be Key(C,S), where S is the
3541 cm_scache_t. But assume a 1-1 relation between keys and clients).
3542 A byte range (O,+L) denotes byte addresses (O) through (O+L-1)
3543 inclusive (a.k.a. [O,O+L-1]). The function Key(x) is implemented
3544 through cm_generateKey() function for both SMB and IFS.
3546 The list of locks for a cm_scache_t object S is maintained in
3547 S->fileLocks. The cache manager will set a lock on the AFS file
3548 server in order to assert the locks in S->fileLocks. If only
3549 shared locks are in place for S, then the cache manager will obtain
3550 a LockRead lock, while if there are any exclusive locks, it will
3551 obtain a LockWrite lock. If the exclusive locks are all released
3552 while the shared locks remain, then the cache manager will
3553 downgrade the lock from LockWrite to LockRead. Similarly, if an
3554 exclusive lock is obtained when only shared locks exist, then the
3555 cache manager will try to upgrade the lock from LockRead to
3558 Each lock L owned by client C maintains a key L->key such that
3559 L->key == Key(C), the effective range defined by L->LOffset and
3560 L->LLength such that the range of bytes affected by the lock is
3561 (L->LOffset, +L->LLength), a type maintained in L->LockType which
3562 is either exclusive or shared.
3566 A lock exists iff it is in S->fileLocks for some cm_scache_t
3567 S. Existing locks are in one of the following states: ACTIVE,
3568 WAITLOCK, WAITUNLOCK, LOST, DELETED.
3570 The following sections describe each lock and the associated
3573 1. ACTIVE: A lock L is ACTIVE iff the cache manager has asserted
3574 the lock with the AFS file server. This type of lock can be
3575 exercised by a client to read or write to the locked region (as
3578 1.1 ACTIVE->LOST: When the AFS file server fails to extend a
3579 server lock that was required to assert the lock. Before
3580 marking the lock as lost, the cache manager checks if the file
3581 has changed on the server. If the file has not changed, then
3582 the cache manager will attempt to obtain a new server lock
3583 that is sufficient to assert the client side locks for the
3584 file. If any of these fail, the lock is marked as LOST.
3585 Otherwise, it is left as ACTIVE.
3587 1.2 ACTIVE->DELETED: Lock is released.
3589 2. WAITLOCK: A lock is in a WAITLOCK state if the cache manager
3590 grants the lock but the lock is yet to be asserted with the AFS
3591 file server. Once the file server grants the lock, the state
3592 will transition to an ACTIVE lock.
3594 2.1 WAITLOCK->ACTIVE: The server granted the lock.
3596 2.2 WAITLOCK->DELETED: Lock is abandoned, or timed out during
3599 2.3 WAITLOCK->LOST: One or more locks from this client were
3600 marked as LOST. No further locks will be granted to this
3601 client until all lost locks are removed.
3603 3. WAITUNLOCK: A lock is in a WAITUNLOCK state if the cache manager
3604 receives a request for a lock that conflicts with an existing
3605 ACTIVE or WAITLOCK lock. The lock will be placed in the queue
3606 and will be granted at such time the conflicting locks are
3607 removed, at which point the state will transition to either
3610 3.1 WAITUNLOCK->ACTIVE: The conflicting lock was removed. The
3611 current serverLock is sufficient to assert this lock, or a
3612 sufficient serverLock is obtained.
3614 3.2 WAITUNLOCK->WAITLOCK: The conflicting lock was removed,
3615 however the required serverLock is yet to be asserted with the
3618 3.3 WAITUNLOCK->DELETED: The lock is abandoned, timed out or
3621 3.5 WAITUNLOCK->LOST: One or more locks from this client were
3622 marked as LOST. No further locks will be granted to this
3623 client until all lost locks are removed.
3625 4. LOST: A lock L is LOST if the server lock that was required to
3626 assert the lock could not be obtained or if it could not be
3627 extended, or if other locks by the same client were LOST.
3628 Essentially, once a lock is LOST, the contract between the cache
3629 manager and that specific client is no longer valid.
3631 The cache manager rechecks the server lock once every minute and
3632 extends it as appropriate. If this is not done for 5 minutes,
3633 the AFS file server will release the lock (the 5 minute timeout
3634 is based on current file server code and is fairly arbitrary).
3635 Once released, the lock cannot be re-obtained without verifying
3636 that the contents of the file hasn't been modified since the
3637 time the lock was released. Re-obtaining the lock without
3638 verifying this may lead to data corruption. If the lock can not
3639 be obtained safely, then all active locks for the cm_scache_t
3642 4.1 LOST->DELETED: The lock is released.
3644 5. DELETED: The lock is no longer relevant. Eventually, it will
3645 get removed from the cm_scache_t. In the meantime, it will be
3646 treated as if it does not exist.
3648 5.1 DELETED->not exist: The lock is removed from the
3651 The following are classifications of locks based on their state.
3653 6* A lock L is ACCEPTED if it is ACTIVE or WAITLOCK. These locks
3654 have been accepted by the cache manager, but may or may not have
3655 been granted back to the client.
3657 7* A lock L is QUEUED if it is ACTIVE, WAITLOCK or WAITUNLOCK.
3659 8* A lock L is WAITING if it is WAITLOCK or WAITUNLOCK.
3663 A client C can READ range (Offset,+Length) of a file represented by
3664 cm_scache_t S iff (1):
3666 1. for all _a_ in (Offset,+Length), all of the following is true:
3668 1.1 For each ACTIVE lock L in S->fileLocks such that _a_ in
3669 (L->LOffset,+L->LLength); L->key == Key(C) OR L->LockType is
3672 1.2 For each LOST lock L in S->fileLocks such that _a_ in
3673 (L->LOffset,+L->LLength); L->LockType is shared AND L->key !=
3676 (When locks are lost on an cm_scache_t, all locks are lost. By
3677 4.2 (below), if there is an exclusive LOST lock, then there
3678 can't be any overlapping ACTIVE locks.)
3680 A client C can WRITE range (Offset,+Length) of cm_scache_t S iff (2):
3682 2. for all _a_ in (Offset,+Length), one of the following is true:
3684 2.1 Byte _a_ of S is unowned (as specified in 1.1) AND there
3685 does not exist a LOST lock L such that _a_ in
3686 (L->LOffset,+L->LLength).
3688 2.2 Byte _a_ of S is owned by C under lock L (as specified in
3689 1.2) AND L->LockType is exclusive.
3691 A client C can OBTAIN a lock L on cm_scache_t S iff (both 3 and 4):
3693 3. for all _a_ in (L->LOffset,+L->LLength), ALL of the following is
3696 3.1 If L->LockType is exclusive then there does NOT exist a
3697 ACCEPTED lock M in S->fileLocks such that _a_ in
3698 (M->LOffset,+M->LLength).
3700 (If we count all QUEUED locks then we hit cases such as
3701 cascading waiting locks where the locks later on in the queue
3702 can be granted without compromising file integrity. On the
3703 other hand if only ACCEPTED locks are considered, then locks
3704 that were received earlier may end up waiting for locks that
3705 were received later to be unlocked. The choice of ACCEPTED
3706 locks was made to mimic the Windows byte range lock
3709 3.2 If L->LockType is shared then for each ACCEPTED lock M in
3710 S->fileLocks, if _a_ in (M->LOffset,+M->LLength) then
3711 M->LockType is shared.
3713 4. For all LOST locks M in S->fileLocks, ALL of the following are true:
3715 4.1 M->key != Key(C)
3717 4.2 If M->LockType is exclusive, then (L->LOffset,+L->LLength)
3718 and (M->LOffset,+M->LLength) do not intersect.
3720 (Note: If a client loses a lock, it loses all locks.
3721 Subsequently, it will not be allowed to obtain any more locks
3722 until all existing LOST locks that belong to the client are
3723 released. Once all locks are released by a single client,
3724 there exists no further contract between the client and AFS
3725 about the contents of the file, hence the client can then
3726 proceed to obtain new locks and establish a new contract.
3728 This doesn't quite work as you think it should, because most
3729 applications aren't built to deal with losing locks they
3730 thought they once had. For now, we don't have a good
3731 solution to lost locks.
3733 Also, for consistency reasons, we have to hold off on
3734 granting locks that overlap exclusive LOST locks.)
3736 A client C can only unlock locks L in S->fileLocks which have
3739 The representation and invariants are as follows:
3741 - Each cm_scache_t structure keeps:
3743 - A queue of byte-range locks (cm_scache_t::fileLocks) which
3744 are of type cm_file_lock_t.
3746 - A record of the highest server-side lock that has been
3747 obtained for this object (cm_scache_t::serverLock), which is
3748 one of (-1), LockRead, LockWrite.
3750 - A count of ACCEPTED exclusive and shared locks that are in the
3751 queue (cm_scache_t::sharedLocks and
3752 cm_scache_t::exclusiveLocks)
3754 - Each cm_file_lock_t structure keeps:
3756 - The type of lock (cm_file_lock_t::LockType)
3758 - The key associated with the lock (cm_file_lock_t::key)
3760 - The offset and length of the lock (cm_file_lock_t::LOffset
3761 and cm_file_lock_t::LLength)
3763 - The state of the lock.
3765 - Time of issuance or last successful extension
3767 Semantic invariants:
3769 I1. The number of ACCEPTED locks in S->fileLocks are
3770 (S->sharedLocks + S->exclusiveLocks)
3772 External invariants:
3774 I3. S->serverLock is the lock that we have asserted with the
3775 AFS file server for this cm_scache_t.
3777 I4. S->serverLock == LockRead iff there is at least one ACTIVE
3778 shared lock, but no ACTIVE exclusive locks.
3780 I5. S->serverLock == LockWrite iff there is at least one ACTIVE
3783 I6. If L is a LOST lock, then for each lock M in S->fileLocks,
3784 M->key == L->key IMPLIES M is LOST or DELETED.
3789 #define IS_LOCK_ACTIVE(lockp) (((lockp)->flags & (CM_FILELOCK_FLAG_DELETED|CM_FILELOCK_FLAG_WAITLOCK|CM_FILELOCK_FLAG_WAITUNLOCK|CM_FILELOCK_FLAG_LOST)) == 0)
3791 #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)
3793 #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)
3795 #define IS_LOCK_LOST(lockp) (((lockp)->flags & (CM_FILELOCK_FLAG_DELETED|CM_FILELOCK_FLAG_LOST)) == CM_FILELOCK_FLAG_LOST)
3797 #define IS_LOCK_DELETED(lockp) (((lockp)->flags & CM_FILELOCK_FLAG_DELETED) == CM_FILELOCK_FLAG_DELETED)
3800 #define IS_LOCK_ACCEPTED(lockp) (IS_LOCK_ACTIVE(lockp) || IS_LOCK_WAITLOCK(lockp))
3803 #define IS_LOCK_CLIENTONLY(lockp) ((((lockp)->scp->flags & CM_SCACHEFLAG_RO) == CM_SCACHEFLAG_RO) || (((lockp)->flags & CM_FILELOCK_FLAG_CLIENTONLY) == CM_FILELOCK_FLAG_CLIENTONLY))
3806 #define INTERSECT_RANGE(r1,r2) (((r2).offset+(r2).length) > (r1).offset && ((r1).offset +(r1).length) > (r2).offset)
3809 #define CONTAINS_RANGE(r1,r2) (((r2).offset+(r2).length) <= ((r1).offset+(r1).length) && (r1).offset <= (r2).offset)
3811 #if defined(VICED_CAPABILITY_USE_BYTE_RANGE_LOCKS) && !defined(LOCK_TESTING)
3812 #define SCP_SUPPORTS_BRLOCKS(scp) ((scp)->cbServerp && ((scp)->cbServerp->capabilities & VICED_CAPABILITY_USE_BYTE_RANGE_LOCKS))
3814 #define SCP_SUPPORTS_BRLOCKS(scp) (1)
3817 #define SERVERLOCKS_ENABLED(scp) (!((scp)->flags & CM_SCACHEFLAG_RO) && cm_enableServerLocks && SCP_SUPPORTS_BRLOCKS(scp))
3819 #if defined(VICED_CAPABILITY_WRITELOCKACL)
3820 #define SCP_SUPPORTS_WRITELOCKACL(scp) ((scp)->cbServerp && ((scp->cbServerp->capabilities & VICED_CAPABILITY_WRITELOCKACL)))
3822 #define SCP_SUPPORTS_WRITELOCKACL(scp) (0)
3824 /* This should really be defined in any build that this code is being
3826 #error VICED_CAPABILITY_WRITELOCKACL not defined.
3829 static void cm_LockRangeSubtract(cm_range_t * pos, const cm_range_t * neg)
3831 afs_int64 int_begin;
3834 int_begin = MAX(pos->offset, neg->offset);
3835 int_end = MIN(pos->offset+pos->length, neg->offset+neg->length);
3837 if (int_begin < int_end) {
3838 if (int_begin == pos->offset) {
3839 pos->length = pos->offset + pos->length - int_end;
3840 pos->offset = int_end;
3841 } else if (int_end == pos->offset + pos->length) {
3842 pos->length = int_begin - pos->offset;
3845 /* We only subtract ranges if the resulting range is
3846 contiguous. If we try to support non-contigous ranges, we
3847 aren't actually improving performance. */
3851 /* Called with scp->rw held. Returns 0 if all is clear to read the
3852 specified range by the client identified by key.
3854 long cm_LockCheckRead(cm_scache_t *scp,
3855 LARGE_INTEGER LOffset,
3856 LARGE_INTEGER LLength,
3859 #ifndef ADVISORY_LOCKS
3861 cm_file_lock_t *fileLock;
3865 int substract_ranges = FALSE;
3867 range.offset = LOffset.QuadPart;
3868 range.length = LLength.QuadPart;
3872 1. for all _a_ in (Offset,+Length), all of the following is true:
3874 1.1 For each ACTIVE lock L in S->fileLocks such that _a_ in
3875 (L->LOffset,+L->LLength); L->key == Key(C) OR L->LockType is
3878 1.2 For each LOST lock L in S->fileLocks such that _a_ in
3879 (L->LOffset,+L->LLength); L->LockType is shared AND L->key !=
3884 lock_ObtainRead(&cm_scacheLock);
3886 for (q = scp->fileLocksH; q && range.length > 0; q = osi_QNext(q)) {
3888 (cm_file_lock_t *)((char *) q - offsetof(cm_file_lock_t, fileq));
3890 if (INTERSECT_RANGE(range, fileLock->range)) {
3891 if (IS_LOCK_ACTIVE(fileLock)) {
3892 if (fileLock->key == key) {
3894 /* If there is an active lock for this client, it
3895 is safe to substract ranges.*/
3896 cm_LockRangeSubtract(&range, &fileLock->range);
3897 substract_ranges = TRUE;
3899 if (fileLock->lockType != LockRead) {
3900 code = CM_ERROR_LOCK_CONFLICT;
3904 /* even if the entire range is locked for reading,
3905 we still can't grant the lock at this point
3906 because the client may have lost locks. That
3907 is, unless we have already seen an active lock
3908 belonging to the client, in which case there
3909 can't be any lost locks for this client. */
3910 if (substract_ranges)
3911 cm_LockRangeSubtract(&range, &fileLock->range);
3913 } else if (IS_LOCK_LOST(fileLock) &&
3914 (fileLock->key == key || fileLock->lockType == LockWrite)) {
3915 code = CM_ERROR_BADFD;
3921 lock_ReleaseRead(&cm_scacheLock);
3923 osi_Log4(afsd_logp, "cm_LockCheckRead scp 0x%x offset %d length %d code 0x%x",
3924 scp, (unsigned long)LOffset.QuadPart, (unsigned long)LLength.QuadPart, code);
3935 /* Called with scp->rw held. Returns 0 if all is clear to write the
3936 specified range by the client identified by key.
3938 long cm_LockCheckWrite(cm_scache_t *scp,
3939 LARGE_INTEGER LOffset,
3940 LARGE_INTEGER LLength,
3943 #ifndef ADVISORY_LOCKS
3945 cm_file_lock_t *fileLock;
3950 range.offset = LOffset.QuadPart;
3951 range.length = LLength.QuadPart;
3954 A client C can WRITE range (Offset,+Length) of cm_scache_t S iff (2):
3956 2. for all _a_ in (Offset,+Length), one of the following is true:
3958 2.1 Byte _a_ of S is unowned AND there does not exist a LOST
3959 lock L such that _a_ in (L->LOffset,+L->LLength).
3961 2.2 Byte _a_ of S is owned by C under lock L AND L->LockType is
3965 lock_ObtainRead(&cm_scacheLock);
3967 for (q = scp->fileLocksH; q && range.length > 0; q = osi_QNext(q)) {
3969 (cm_file_lock_t *)((char *) q - offsetof(cm_file_lock_t, fileq));
3971 if (INTERSECT_RANGE(range, fileLock->range)) {
3972 if (IS_LOCK_ACTIVE(fileLock)) {
3973 if (fileLock->key == key) {
3974 if (fileLock->lockType == LockWrite) {
3976 /* if there is an active lock for this client, it
3977 is safe to substract ranges */
3978 cm_LockRangeSubtract(&range, &fileLock->range);
3980 code = CM_ERROR_LOCK_CONFLICT;
3984 code = CM_ERROR_LOCK_CONFLICT;
3987 } else if (IS_LOCK_LOST(fileLock)) {
3988 code = CM_ERROR_BADFD;
3994 lock_ReleaseRead(&cm_scacheLock);
3996 osi_Log4(afsd_logp, "cm_LockCheckWrite scp 0x%x offset %d length %d code 0x%x",
3997 scp, (unsigned long)LOffset.QuadPart, (unsigned long)LLength.QuadPart, code);
4008 /* Called with cm_scacheLock write locked */
4009 static cm_file_lock_t * cm_GetFileLock(void) {
4012 l = (cm_file_lock_t *) cm_freeFileLocks;
4014 osi_QRemove(&cm_freeFileLocks, &l->q);
4016 l = malloc(sizeof(cm_file_lock_t));
4017 osi_assertx(l, "null cm_file_lock_t");
4020 memset(l, 0, sizeof(cm_file_lock_t));
4025 /* Called with cm_scacheLock write locked */
4026 static void cm_PutFileLock(cm_file_lock_t *l) {
4027 osi_QAdd(&cm_freeFileLocks, &l->q);
4030 /* called with scp->rw held. May release it during processing, but
4031 leaves it held on exit. */
4032 long cm_IntSetLock(cm_scache_t * scp, cm_user_t * userp, int lockType,
4038 struct rx_connection * callp;
4040 afs_uint32 reqflags = reqp->flags;
4042 tfid.Volume = scp->fid.volume;
4043 tfid.Vnode = scp->fid.vnode;
4044 tfid.Unique = scp->fid.unique;
4047 osi_Log2(afsd_logp, "CALL SetLock scp 0x%p for lock %d", scp, lockType);
4049 reqp->flags |= CM_REQ_NORETRY;
4050 lock_ReleaseWrite(&scp->rw);
4053 code = cm_ConnFromFID(&cfid, userp, reqp, &connp);
4057 callp = cm_GetRxConn(connp);
4058 code = RXAFS_SetLock(callp, &tfid, lockType,
4060 rx_PutConnection(callp);
4062 } while (cm_Analyze(connp, userp, reqp, &cfid, &volSync,
4065 code = cm_MapRPCError(code, reqp);
4067 osi_Log1(afsd_logp, "CALL SetLock FAILURE, code 0x%x", code);
4069 osi_Log0(afsd_logp, "CALL SetLock SUCCESS");
4072 lock_ObtainWrite(&scp->rw);
4073 reqp->flags = reqflags;
4077 /* called with scp->rw held. Releases it during processing */
4078 long cm_IntReleaseLock(cm_scache_t * scp, cm_user_t * userp,
4084 struct rx_connection * callp;
4087 tfid.Volume = scp->fid.volume;
4088 tfid.Vnode = scp->fid.vnode;
4089 tfid.Unique = scp->fid.unique;
4092 lock_ReleaseWrite(&scp->rw);
4094 osi_Log1(afsd_logp, "CALL ReleaseLock scp 0x%p", scp);
4097 code = cm_ConnFromFID(&cfid, userp, reqp, &connp);
4101 callp = cm_GetRxConn(connp);
4102 code = RXAFS_ReleaseLock(callp, &tfid, &volSync);
4103 rx_PutConnection(callp);
4105 } while (cm_Analyze(connp, userp, reqp, &cfid, &volSync,
4107 code = cm_MapRPCError(code, reqp);
4110 "CALL ReleaseLock FAILURE, code 0x%x", code);
4113 "CALL ReleaseLock SUCCESS");
4115 lock_ObtainWrite(&scp->rw);
4120 /* called with scp->rw held. May release it during processing, but
4121 will exit with lock held.
4125 - 0 if the user has permission to get the specified lock for the scp
4127 - CM_ERROR_NOACCESS if not
4129 Any other error from cm_SyncOp will be sent down untranslated.
4131 If CM_ERROR_NOACCESS is returned and lock_type is LockRead, then
4132 phas_insert (if non-NULL) will receive a boolean value indicating
4133 whether the user has INSERT permission or not.
4135 long cm_LockCheckPerms(cm_scache_t * scp,
4142 long code = 0, code2 = 0;
4144 /* lock permissions are slightly tricky because of the 'i' bit.
4145 If the user has PRSFS_LOCK, she can read-lock the file. If the
4146 user has PRSFS_WRITE, she can write-lock the file. However, if
4147 the user has PRSFS_INSERT, then she can write-lock new files,
4148 but not old ones. Since we don't have information about
4149 whether a file is new or not, we assume that if the user owns
4150 the scp, then she has the permissions that are granted by
4153 osi_Log3(afsd_logp, "cm_LockCheckPerms for scp[0x%p] type[%d] user[0x%p]",
4154 scp, lock_type, userp);
4156 if (lock_type == LockRead)
4157 rights |= PRSFS_LOCK;
4158 else if (lock_type == LockWrite)
4159 rights |= PRSFS_WRITE | PRSFS_LOCK;
4162 osi_assertx(FALSE, "invalid lock type");
4167 *phas_insert = FALSE;
4169 code = cm_SyncOp(scp, NULL, userp, reqp, rights,
4170 CM_SCACHESYNC_GETSTATUS |
4171 CM_SCACHESYNC_NEEDCALLBACK);
4173 if (phas_insert && scp->creator == userp) {
4175 /* If this file was created by the user, then we check for
4176 PRSFS_INSERT. If the file server is recent enough, then
4177 this should be sufficient for her to get a write-lock (but
4178 not necessarily a read-lock). VICED_CAPABILITY_WRITELOCKACL
4179 indicates whether a file server supports getting write
4180 locks when the user only has PRSFS_INSERT.
4182 If the file was not created by the user we skip the check
4183 because the INSERT bit will not apply to this user even
4187 code2 = cm_SyncOp(scp, NULL, userp, reqp, PRSFS_INSERT,
4188 CM_SCACHESYNC_GETSTATUS |
4189 CM_SCACHESYNC_NEEDCALLBACK);
4191 if (code2 == CM_ERROR_NOACCESS) {
4192 osi_Log0(afsd_logp, "cm_LockCheckPerms user has no INSERT bits");
4194 *phas_insert = TRUE;
4195 osi_Log0(afsd_logp, "cm_LockCheckPerms user has INSERT bits");
4199 cm_SyncOpDone(scp, NULL, CM_SCACHESYNC_NEEDCALLBACK | CM_SCACHESYNC_GETSTATUS);
4201 osi_Log1(afsd_logp, "cm_LockCheckPerms returning code %d", code);
4206 /* called with scp->rw held */
4207 long cm_Lock(cm_scache_t *scp, unsigned char sLockType,
4208 LARGE_INTEGER LOffset, LARGE_INTEGER LLength,
4210 int allowWait, cm_user_t *userp, cm_req_t *reqp,
4211 cm_file_lock_t **lockpp)
4214 int Which = ((sLockType & LOCKING_ANDX_SHARED_LOCK) ? LockRead : LockWrite);
4215 cm_file_lock_t *fileLock;
4218 int wait_unlock = FALSE;
4219 int force_client_lock = FALSE;
4221 osi_Log4(afsd_logp, "cm_Lock scp 0x%x type 0x%x offset %d length %d",
4222 scp, sLockType, (unsigned long)LOffset.QuadPart, (unsigned long)LLength.QuadPart);
4223 osi_Log3(afsd_logp, "... allowWait %d key 0x%x:%x", allowWait,
4224 (unsigned long)(key >> 32), (unsigned long)(key & 0xffffffff));
4227 A client C can OBTAIN a lock L on cm_scache_t S iff (both 3 and 4):
4229 3. for all _a_ in (L->LOffset,+L->LLength), ALL of the following is
4232 3.1 If L->LockType is exclusive then there does NOT exist a
4233 ACCEPTED lock M in S->fileLocks such that _a_ in
4234 (M->LOffset,+M->LLength).
4236 3.2 If L->LockType is shared then for each ACCEPTED lock M in
4237 S->fileLocks, if _a_ in (M->LOffset,+M->LLength) then
4238 M->LockType is shared.
4240 4. For all LOST locks M in S->fileLocks, ALL of the following are true:
4242 4.1 M->key != Key(C)
4244 4.2 If M->LockType is exclusive, then (L->LOffset,+L->LLength)
4245 and (M->LOffset,+M->LLength) do not intersect.
4248 range.offset = LOffset.QuadPart;
4249 range.length = LLength.QuadPart;
4251 lock_ObtainRead(&cm_scacheLock);
4253 for (q = scp->fileLocksH; q; q = osi_QNext(q)) {
4255 (cm_file_lock_t *)((char *) q - offsetof(cm_file_lock_t, fileq));
4257 if (IS_LOCK_LOST(fileLock)) {
4258 if (fileLock->key == key) {
4259 code = CM_ERROR_BADFD;
4261 } else if (fileLock->lockType == LockWrite && INTERSECT_RANGE(range, fileLock->range)) {
4262 code = CM_ERROR_WOULDBLOCK;
4268 /* we don't need to check for deleted locks here since deleted
4269 locks are dequeued from scp->fileLocks */
4270 if (IS_LOCK_ACCEPTED(fileLock) &&
4271 INTERSECT_RANGE(range, fileLock->range)) {
4273 if ((sLockType & LOCKING_ANDX_SHARED_LOCK) == 0 ||
4274 fileLock->lockType != LockRead) {
4276 code = CM_ERROR_WOULDBLOCK;
4282 lock_ReleaseRead(&cm_scacheLock);
4284 if (code == 0 && SERVERLOCKS_ENABLED(scp)) {
4285 if (Which == scp->serverLock ||
4286 (Which == LockRead && scp->serverLock == LockWrite)) {
4290 /* we already have the lock we need */
4291 osi_Log3(afsd_logp, " we already have the correct lock. exclusives[%d], shared[%d], serverLock[%d]",
4292 scp->exclusiveLocks, scp->sharedLocks, (int)(signed char) scp->serverLock);
4294 code = cm_LockCheckPerms(scp, Which, userp, reqp, &has_insert);
4296 /* special case: if we don't have permission to read-lock
4297 the file, then we force a clientside lock. This is to
4298 compensate for applications that obtain a read-lock for
4299 reading files off of directories that don't grant
4300 read-locks to the user. */
4301 if (code == CM_ERROR_NOACCESS && Which == LockRead) {
4303 if (has_insert && SCP_SUPPORTS_WRITELOCKACL(scp)) {
4304 osi_Log0(afsd_logp, " User has no read-lock perms, but has INSERT perms.");
4307 osi_Log0(afsd_logp, " User has no read-lock perms. Forcing client-side lock");
4308 force_client_lock = TRUE;
4312 } else if ((scp->exclusiveLocks > 0) ||
4313 (scp->sharedLocks > 0 && scp->serverLock != LockRead)) {
4316 /* We are already waiting for some other lock. We should
4317 wait for the daemon to catch up instead of generating a
4318 flood of SetLock calls. */
4319 osi_Log3(afsd_logp, " already waiting for other lock. exclusives[%d], shared[%d], serverLock[%d]",
4320 scp->exclusiveLocks, scp->sharedLocks, (int)(signed char) scp->serverLock);
4322 /* see if we have permission to create the lock in the
4324 code = cm_LockCheckPerms(scp, Which, userp, reqp, &has_insert);
4326 code = CM_ERROR_WOULDBLOCK;
4327 else if (code == CM_ERROR_NOACCESS && Which == LockRead) {
4329 if (has_insert && SCP_SUPPORTS_WRITELOCKACL(scp)) {
4331 " User has no read-lock perms, but has INSERT perms.");
4332 code = CM_ERROR_WOULDBLOCK;
4335 " User has no read-lock perms. Forcing client-side lock");
4336 force_client_lock = TRUE;
4340 /* leave any other codes as-is */
4344 int check_data_version = FALSE;
4347 /* first check if we have permission to elevate or obtain
4349 code = cm_LockCheckPerms(scp, Which, userp, reqp, &has_insert);
4351 if (code == CM_ERROR_NOACCESS && Which == LockRead &&
4352 (!has_insert || !SCP_SUPPORTS_WRITELOCKACL(scp))) {
4353 osi_Log0(afsd_logp, " User has no read-lock perms. Forcing client-side lock");
4354 force_client_lock = TRUE;
4359 /* has_insert => (Which == LockRead, code == CM_ERROR_NOACCESS) */
4361 if (scp->serverLock == LockRead && Which == LockWrite) {
4363 /* We want to escalate the lock to a LockWrite.
4364 * Unfortunately that's not really possible without
4365 * letting go of the current lock. But for now we do
4369 " attempting to UPGRADE from LockRead to LockWrite.");
4371 " dataVersion on scp: %I64d", scp->dataVersion);
4373 /* we assume at this point (because scp->serverLock
4374 was valid) that we had a valid server lock. */
4375 scp->lockDataVersion = scp->dataVersion;
4376 check_data_version = TRUE;
4378 code = cm_IntReleaseLock(scp, userp, reqp);
4381 /* We couldn't release the lock */
4384 scp->serverLock = -1;
4388 /* We need to obtain a server lock of type Which in order
4389 * to assert this file lock */
4390 #ifndef AGGRESSIVE_LOCKS
4393 newLock = LockWrite;
4396 code = cm_IntSetLock(scp, userp, newLock, reqp);
4398 #ifdef AGGRESSIVE_LOCKS
4399 if ((code == CM_ERROR_WOULDBLOCK ||
4400 code == CM_ERROR_NOACCESS) && newLock != Which) {
4401 /* we wanted LockRead. We tried LockWrite. Now try
4406 osi_assertx(newLock == LockRead, "lock type not read");
4408 code = cm_IntSetLock(scp, userp, newLock, reqp);
4412 if (code == CM_ERROR_NOACCESS) {
4413 if (Which == LockRead) {
4414 if (has_insert && SCP_SUPPORTS_WRITELOCKACL(scp)) {
4416 /* We requested a read-lock, but we have permission to
4417 * get a write-lock. Try that */
4419 tcode = cm_LockCheckPerms(scp, LockWrite, userp, reqp, NULL);
4422 newLock = LockWrite;
4424 osi_Log0(afsd_logp, " User has 'i' perms and the request was for a LockRead. Trying to get a LockWrite instead");
4426 code = cm_IntSetLock(scp, userp, newLock, reqp);
4429 osi_Log0(afsd_logp, " User has no read-lock perms. Forcing client-side lock");
4430 force_client_lock = TRUE;
4432 } else if (Which == LockWrite &&
4433 scp->creator == userp && !SCP_SUPPORTS_WRITELOCKACL(scp)) {
4436 /* Special case: if the lock request was for a
4437 * LockWrite and the user owns the file and we weren't
4438 * allowed to obtain the serverlock, we either lost a
4439 * race (the permissions changed from under us), or we
4440 * have 'i' bits, but we aren't allowed to lock the
4443 /* check if we lost a race... */
4444 tcode = cm_LockCheckPerms(scp, Which, userp, reqp, NULL);
4447 osi_Log0(afsd_logp, " User has 'i' perms but can't obtain write locks. Using client-side locks.");
4448 force_client_lock = TRUE;
4453 if (code == 0 && check_data_version &&
4454 scp->dataVersion != scp->lockDataVersion) {
4455 /* We lost a race. Although we successfully obtained
4456 * a lock, someone modified the file in between. The
4457 * locks have all been technically lost. */
4460 " Data version mismatch while upgrading lock.");
4462 " Data versions before=%I64d, after=%I64d",
4463 scp->lockDataVersion,
4466 " Releasing stale lock for scp 0x%x", scp);
4468 code = cm_IntReleaseLock(scp, userp, reqp);
4470 scp->serverLock = -1;
4472 code = CM_ERROR_INVAL;
4473 } else if (code == 0) {
4474 scp->serverLock = newLock;
4475 scp->lockDataVersion = scp->dataVersion;
4479 (scp->sharedLocks > 0 || scp->exclusiveLocks > 0) &&
4480 scp->serverLock == -1) {
4481 /* Oops. We lost the lock. */
4482 cm_LockMarkSCacheLost(scp);
4485 } else if (code == 0) { /* server locks not enabled */
4487 " Skipping server lock for scp");
4492 if (code != 0 && !force_client_lock) {
4493 /* Special case error translations
4495 Applications don't expect certain errors from a
4496 LockFile/UnlockFile call. We need to translate some error
4497 code to codes that apps expect and handle. */
4499 /* We shouldn't actually need to handle this case since we
4500 simulate locks for RO scps anyway. */
4501 if (code == CM_ERROR_READONLY) {
4502 osi_Log0(afsd_logp, " Reinterpreting CM_ERROR_READONLY as CM_ERROR_NOACCESS");
4503 code = CM_ERROR_NOACCESS;
4507 if (code == 0 || (code == CM_ERROR_WOULDBLOCK && allowWait) ||
4508 force_client_lock) {
4510 /* clear the error if we are forcing a client lock, so we
4511 don't get confused later. */
4512 if (force_client_lock && code != CM_ERROR_WOULDBLOCK)
4515 lock_ObtainWrite(&cm_scacheLock);
4516 fileLock = cm_GetFileLock();
4517 lock_ReleaseWrite(&cm_scacheLock);
4519 fileLock->fid = scp->fid;
4521 fileLock->key = key;
4522 fileLock->lockType = Which;
4524 fileLock->userp = userp;
4525 fileLock->range = range;
4526 fileLock->flags = (code == 0 ? 0 :
4528 CM_FILELOCK_FLAG_WAITUNLOCK :
4529 CM_FILELOCK_FLAG_WAITLOCK));
4531 if (force_client_lock || !SERVERLOCKS_ENABLED(scp))
4532 fileLock->flags |= CM_FILELOCK_FLAG_CLIENTONLY;
4534 fileLock->lastUpdate = (code == 0 && !force_client_lock) ? time(NULL) : 0;
4536 lock_ObtainWrite(&cm_scacheLock);
4537 osi_QAddT(&scp->fileLocksH, &scp->fileLocksT, &fileLock->fileq);
4538 cm_HoldSCacheNoLock(scp);
4539 fileLock->scp = scp;
4540 osi_QAdd(&cm_allFileLocks, &fileLock->q);
4541 lock_ReleaseWrite(&cm_scacheLock);
4547 if (IS_LOCK_CLIENTONLY(fileLock)) {
4549 } else if (IS_LOCK_ACCEPTED(fileLock)) {
4550 if (Which == LockRead)
4553 scp->exclusiveLocks++;
4557 "cm_Lock Lock added 0x%p flags 0x%x to scp [0x%p]",
4558 fileLock, fileLock->flags, scp);
4560 " exclusives[%d] shared[%d] client[%d] serverLock[%d]",
4561 scp->exclusiveLocks, scp->sharedLocks, scp->clientLocks,
4562 (int)(signed char) scp->serverLock);
4565 "cm_Lock Rejecting lock (code = 0x%x)", code);
4571 static int cm_KeyEquals(cm_key_t k1, cm_key_t k2, int flags);
4573 /* Called with scp->rw held */
4574 long cm_UnlockByKey(cm_scache_t * scp,
4581 cm_file_lock_t *fileLock;
4582 osi_queue_t *q, *qn;
4585 osi_Log4(afsd_logp, "cm_UnlockByKey scp 0x%p key 0x%x:%x flags=0x%x",
4587 (unsigned long)(key >> 32),
4588 (unsigned long)(key & 0xffffffff),
4591 lock_ObtainWrite(&cm_scacheLock);
4593 for (q = scp->fileLocksH; q; q = qn) {
4596 fileLock = (cm_file_lock_t *)
4597 ((char *) q - offsetof(cm_file_lock_t, fileq));
4600 osi_Log4(afsd_logp, " Checking lock[0x%x] range[%d,+%d] type[%d]",
4602 (unsigned long) fileLock->range.offset,
4603 (unsigned long) fileLock->range.length,
4604 fileLock->lockType);
4605 osi_Log3(afsd_logp, " key[0x%x:%x] flags[0x%x]",
4606 (unsigned long)(fileLock->key >> 32),
4607 (unsigned long)(fileLock->key & 0xffffffff),
4610 if (cm_FidCmp(&fileLock->fid, &fileLock->scp->fid)) {
4611 osi_Log0(afsd_logp, "!!fileLock->fid != scp->fid");
4612 osi_Log4(afsd_logp, " fileLock->fid(cell=[%d], volume=[%d], vnode=[%d], unique=[%d]",
4614 fileLock->fid.volume,
4615 fileLock->fid.vnode,
4616 fileLock->fid.unique);
4617 osi_Log4(afsd_logp, " scp->fid(cell=[%d], volume=[%d], vnode=[%d], unique=[%d]",
4618 fileLock->scp->fid.cell,
4619 fileLock->scp->fid.volume,
4620 fileLock->scp->fid.vnode,
4621 fileLock->scp->fid.unique);
4622 osi_assertx(FALSE, "invalid fid value");
4626 if (!IS_LOCK_DELETED(fileLock) &&
4627 cm_KeyEquals(fileLock->key, key, flags)) {
4628 osi_Log3(afsd_logp, "...Unlock range [%d,+%d] type %d",
4629 fileLock->range.offset,
4630 fileLock->range.length,
4631 fileLock->lockType);
4633 if (scp->fileLocksT == q)
4634 scp->fileLocksT = osi_QPrev(q);
4635 osi_QRemoveHT(&scp->fileLocksH, &scp->fileLocksT, q);
4637 if (IS_LOCK_CLIENTONLY(fileLock)) {
4639 } else if (IS_LOCK_ACCEPTED(fileLock)) {
4640 if (fileLock->lockType == LockRead)
4643 scp->exclusiveLocks--;
4646 fileLock->flags |= CM_FILELOCK_FLAG_DELETED;
4648 cm_ReleaseUser(fileLock->userp);
4649 cm_ReleaseSCacheNoLock(scp);
4651 fileLock->userp = NULL;
4652 fileLock->scp = NULL;
4658 lock_ReleaseWrite(&cm_scacheLock);
4660 if (n_unlocks == 0) {
4661 osi_Log0(afsd_logp, "cm_UnlockByKey no locks found");
4662 osi_Log3(afsd_logp, " Leaving scp with exclusives[%d], shared[%d], serverLock[%d]",
4663 scp->exclusiveLocks, scp->sharedLocks, (int)(signed char) scp->serverLock);
4668 osi_Log1(afsd_logp, "cm_UnlockByKey done with %d locks", n_unlocks);
4670 osi_assertx(scp->sharedLocks >= 0, "scp->sharedLocks < 0");
4671 osi_assertx(scp->exclusiveLocks >= 0, "scp->exclusiveLocks < 0");
4672 osi_assertx(scp->clientLocks >= 0, "scp->clientLocks < 0");
4674 if (!SERVERLOCKS_ENABLED(scp)) {
4675 osi_Log0(afsd_logp, " Skipping server lock for scp");
4679 /* Ideally we would go through the rest of the locks to determine
4680 * if one or more locks that were formerly in WAITUNLOCK can now
4681 * be put to ACTIVE or WAITLOCK and update scp->exclusiveLocks and
4682 * scp->sharedLocks accordingly. However, the retrying of locks
4683 * in that manner is done cm_RetryLock() manually.
4686 if (scp->serverLock == LockWrite &&
4687 scp->exclusiveLocks == 0 &&
4688 scp->sharedLocks > 0) {
4690 /* The serverLock should be downgraded to LockRead */
4691 osi_Log0(afsd_logp, " DOWNGRADE lock from LockWrite to LockRead");
4693 /* since scp->serverLock looked sane, we are going to assume
4694 that we have a valid server lock. */
4695 scp->lockDataVersion = scp->dataVersion;
4696 osi_Log1(afsd_logp, " dataVersion on scp = %I64d", scp->dataVersion);
4698 code = cm_IntReleaseLock(scp, userp, reqp);
4701 /* so we couldn't release it. Just let the lock be for now */
4705 scp->serverLock = -1;
4708 code = cm_IntSetLock(scp, userp, LockRead, reqp);
4710 if (code == 0 && scp->lockDataVersion == scp->dataVersion) {
4711 scp->serverLock = LockRead;
4712 } else if (code == 0 && scp->lockDataVersion != scp->dataVersion) {
4713 /* We lost a race condition. Although we have a valid
4714 lock on the file, the data has changed and essentially
4715 we have lost the lock we had during the transition. */
4717 osi_Log0(afsd_logp, "Data version mismatch during lock downgrade");
4718 osi_Log2(afsd_logp, " Data versions before=%I64d, after=%I64d",
4719 scp->lockDataVersion,
4722 code = cm_IntReleaseLock(scp, userp, reqp);
4724 code = CM_ERROR_INVAL;
4725 scp->serverLock = -1;
4729 (scp->sharedLocks > 0 || scp->exclusiveLocks > 0) &&
4730 (scp->serverLock == -1)) {
4732 cm_LockMarkSCacheLost(scp);
4735 /* failure here has no bearing on the return value of
4739 } else if (scp->serverLock != (-1) &&
4740 scp->exclusiveLocks == 0 &&
4741 scp->sharedLocks == 0) {
4742 /* The serverLock should be released entirely */
4744 code = cm_IntReleaseLock(scp, userp, reqp);
4747 scp->serverLock = (-1);
4752 osi_Log1(afsd_logp, "cm_UnlockByKey code 0x%x", code);
4753 osi_Log4(afsd_logp, " Leaving scp with excl[%d], shared[%d], client[%d], serverLock[%d]",
4754 scp->exclusiveLocks, scp->sharedLocks, scp->clientLocks,
4755 (int)(signed char) scp->serverLock);
4760 long cm_Unlock(cm_scache_t *scp,
4761 unsigned char sLockType,
4762 LARGE_INTEGER LOffset, LARGE_INTEGER LLength,
4768 int Which = ((sLockType & LOCKING_ANDX_SHARED_LOCK) ? LockRead : LockWrite);
4769 cm_file_lock_t *fileLock;
4771 int release_userp = FALSE;
4773 osi_Log4(afsd_logp, "cm_Unlock scp 0x%p type 0x%x offset %d length %d",
4774 scp, sLockType, (unsigned long)LOffset.QuadPart, (unsigned long)LLength.QuadPart);
4775 osi_Log2(afsd_logp, "... key 0x%x:%x",
4776 (unsigned long) (key >> 32), (unsigned long) (key & 0xffffffff));
4778 lock_ObtainRead(&cm_scacheLock);
4780 for (q = scp->fileLocksH; q; q = osi_QNext(q)) {
4781 fileLock = (cm_file_lock_t *)
4782 ((char *) q - offsetof(cm_file_lock_t, fileq));
4785 if (cm_FidCmp(&fileLock->fid, &fileLock->scp->fid)) {
4786 osi_Log0(afsd_logp, "!!fileLock->fid != scp->fid");
4787 osi_Log4(afsd_logp, " fileLock->fid(cell=[%d], volume=[%d], vnode=[%d], unique=[%d]",
4789 fileLock->fid.volume,
4790 fileLock->fid.vnode,
4791 fileLock->fid.unique);
4792 osi_Log4(afsd_logp, " scp->fid(cell=[%d], volume=[%d], vnode=[%d], unique=[%d]",
4793 fileLock->scp->fid.cell,
4794 fileLock->scp->fid.volume,
4795 fileLock->scp->fid.vnode,
4796 fileLock->scp->fid.unique);
4797 osi_assertx(FALSE, "invalid fid value");
4800 if (!IS_LOCK_DELETED(fileLock) &&
4801 fileLock->key == key &&
4802 fileLock->range.offset == LOffset.QuadPart &&
4803 fileLock->range.length == LLength.QuadPart) {
4809 osi_Log0(afsd_logp, "cm_Unlock lock not found; failure");
4811 lock_ReleaseRead(&cm_scacheLock);
4813 /* The lock didn't exist anyway. *shrug* */
4814 return CM_ERROR_RANGE_NOT_LOCKED;
4817 /* discard lock record */
4818 lock_ConvertRToW(&cm_scacheLock);
4819 if (scp->fileLocksT == q)
4820 scp->fileLocksT = osi_QPrev(q);
4821 osi_QRemoveHT(&scp->fileLocksH, &scp->fileLocksT, q);
4824 * Don't delete it here; let the daemon delete it, to simplify
4825 * the daemon's traversal of the list.
4828 if (IS_LOCK_CLIENTONLY(fileLock)) {
4830 } else if (IS_LOCK_ACCEPTED(fileLock)) {
4831 if (fileLock->lockType == LockRead)
4834 scp->exclusiveLocks--;
4837 fileLock->flags |= CM_FILELOCK_FLAG_DELETED;
4838 if (userp != NULL) {
4839 cm_ReleaseUser(fileLock->userp);
4841 userp = fileLock->userp;
4842 release_userp = TRUE;
4844 fileLock->userp = NULL;
4845 cm_ReleaseSCacheNoLock(scp);
4846 fileLock->scp = NULL;
4847 lock_ReleaseWrite(&cm_scacheLock);
4849 if (!SERVERLOCKS_ENABLED(scp)) {
4850 osi_Log0(afsd_logp, " Skipping server locks for scp");
4854 /* Ideally we would go through the rest of the locks to determine
4855 * if one or more locks that were formerly in WAITUNLOCK can now
4856 * be put to ACTIVE or WAITLOCK and update scp->exclusiveLocks and
4857 * scp->sharedLocks accordingly. However, the retrying of locks
4858 * in that manner is done cm_RetryLock() manually.
4861 if (scp->serverLock == LockWrite &&
4862 scp->exclusiveLocks == 0 &&
4863 scp->sharedLocks > 0) {
4865 /* The serverLock should be downgraded to LockRead */
4866 osi_Log0(afsd_logp, " DOWNGRADE lock from LockWrite to LockRead");
4868 /* Since we already had a lock, we assume that there is a
4869 valid server lock. */
4870 scp->lockDataVersion = scp->dataVersion;
4871 osi_Log1(afsd_logp, " dataVersion on scp is %I64d", scp->dataVersion);
4873 /* before we downgrade, make sure that we have enough
4874 permissions to get the read lock. */
4875 code = cm_LockCheckPerms(scp, LockRead, userp, reqp, NULL);
4878 osi_Log0(afsd_logp, " SKIPPING downgrade because user doesn't have perms to get downgraded lock");
4884 code = cm_IntReleaseLock(scp, userp, reqp);
4887 /* so we couldn't release it. Just let the lock be for now */
4891 scp->serverLock = -1;
4894 code = cm_IntSetLock(scp, userp, LockRead, reqp);
4896 if (code == 0 && scp->lockDataVersion == scp->dataVersion) {
4897 scp->serverLock = LockRead;
4898 } else if (code == 0 && scp->lockDataVersion != scp->dataVersion) {
4899 /* Lost a race. We obtained a new lock, but that is
4900 meaningless since someone modified the file
4904 "Data version mismatch while downgrading lock");
4906 " Data versions before=%I64d, after=%I64d",
4907 scp->lockDataVersion,
4910 code = cm_IntReleaseLock(scp, userp, reqp);
4912 scp->serverLock = -1;
4913 code = CM_ERROR_INVAL;
4917 (scp->sharedLocks > 0 || scp->exclusiveLocks > 0) &&
4918 (scp->serverLock == -1)) {
4920 cm_LockMarkSCacheLost(scp);
4923 /* failure here has no bearing on the return value of
4927 } else if (scp->serverLock != (-1) &&
4928 scp->exclusiveLocks == 0 &&
4929 scp->sharedLocks == 0) {
4930 /* The serverLock should be released entirely */
4932 code = cm_IntReleaseLock(scp, userp, reqp);
4935 scp->serverLock = (-1);
4940 cm_ReleaseUser(userp);
4944 osi_Log1(afsd_logp, "cm_Unlock code 0x%x", code);
4945 osi_Log4(afsd_logp, " leaving scp with excl[%d], shared[%d], client[%d], serverLock[%d]",
4946 scp->exclusiveLocks, scp->sharedLocks, scp->clientLocks,
4947 (int)(signed char) scp->serverLock);
4952 /* called with scp->rw held */
4953 void cm_LockMarkSCacheLost(cm_scache_t * scp)
4955 cm_file_lock_t *fileLock;
4958 osi_Log1(afsd_logp, "cm_LockMarkSCacheLost scp 0x%x", scp);
4960 /* cm_scacheLock needed because we are modifying fileLock->flags */
4961 lock_ObtainWrite(&cm_scacheLock);
4963 for (q = scp->fileLocksH; q; q = osi_QNext(q)) {
4965 (cm_file_lock_t *)((char *) q - offsetof(cm_file_lock_t, fileq));
4967 if (IS_LOCK_ACTIVE(fileLock) &&
4968 !IS_LOCK_CLIENTONLY(fileLock)) {
4969 if (fileLock->lockType == LockRead)
4972 scp->exclusiveLocks--;
4974 fileLock->flags |= CM_FILELOCK_FLAG_LOST;
4978 scp->serverLock = -1;
4979 scp->lockDataVersion = -1;
4980 lock_ReleaseWrite(&cm_scacheLock);
4983 /* Called with no relevant locks held */
4984 void cm_CheckLocks()
4986 osi_queue_t *q, *nq;
4987 cm_file_lock_t *fileLock;
4993 struct rx_connection * callp;
4998 lock_ObtainWrite(&cm_scacheLock);
5000 cm_lockRefreshCycle++;
5002 osi_Log1(afsd_logp, "cm_CheckLocks starting lock check cycle %d", cm_lockRefreshCycle);
5004 for (q = cm_allFileLocks; q; q = nq) {
5005 fileLock = (cm_file_lock_t *) q;
5009 if (IS_LOCK_DELETED(fileLock)) {
5011 osi_QRemove(&cm_allFileLocks, q);
5012 cm_PutFileLock(fileLock);
5014 } else if (IS_LOCK_ACTIVE(fileLock) && !IS_LOCK_CLIENTONLY(fileLock)) {
5016 /* Server locks must have been enabled for us to have
5017 received an active non-client-only lock. */
5018 osi_assertx(cm_enableServerLocks, "!cm_enableServerLocks");
5020 scp = fileLock->scp;
5021 osi_assertx(scp != NULL, "null cm_scache_t");
5023 cm_HoldSCacheNoLock(scp);
5026 if (cm_FidCmp(&fileLock->fid, &fileLock->scp->fid)) {
5027 osi_Log0(afsd_logp, "!!fileLock->fid != scp->fid");
5028 osi_Log4(afsd_logp, " fileLock->fid(cell=[%d], volume=[%d], vnode=[%d], unique=[%d]",
5030 fileLock->fid.volume,
5031 fileLock->fid.vnode,
5032 fileLock->fid.unique);
5033 osi_Log4(afsd_logp, " scp->fid(cell=[%d], volume=[%d], vnode=[%d], unique=[%d]",
5034 fileLock->scp->fid.cell,
5035 fileLock->scp->fid.volume,
5036 fileLock->scp->fid.vnode,
5037 fileLock->scp->fid.unique);
5038 osi_assertx(FALSE, "invalid fid");
5041 /* Server locks are extended once per scp per refresh
5043 if (scp->lastRefreshCycle != cm_lockRefreshCycle) {
5045 int scp_done = FALSE;
5047 osi_Log1(afsd_logp, "cm_CheckLocks Updating scp 0x%x", scp);
5049 lock_ReleaseWrite(&cm_scacheLock);
5050 lock_ObtainWrite(&scp->rw);
5052 /* did the lock change while we weren't holding the lock? */
5053 if (!IS_LOCK_ACTIVE(fileLock))
5054 goto post_syncopdone;
5056 code = cm_SyncOp(scp, NULL, fileLock->userp, &req, 0,
5057 CM_SCACHESYNC_NEEDCALLBACK
5058 | CM_SCACHESYNC_GETSTATUS
5059 | CM_SCACHESYNC_LOCK);
5063 "cm_CheckLocks SyncOp failure code 0x%x", code);
5064 goto post_syncopdone;
5067 /* cm_SyncOp releases scp->rw during which the lock
5068 may get released. */
5069 if (!IS_LOCK_ACTIVE(fileLock))
5070 goto pre_syncopdone;
5072 if (scp->serverLock != -1 && !(scp->flags & CM_SCACHEFLAG_DELETED)) {
5076 tfid.Volume = scp->fid.volume;
5077 tfid.Vnode = scp->fid.vnode;
5078 tfid.Unique = scp->fid.unique;
5080 userp = fileLock->userp;
5082 osi_Log3(afsd_logp, "CALL ExtendLock lock 0x%p for scp=0x%p with lock %d",
5085 (int) scp->serverLock);
5087 lock_ReleaseWrite(&scp->rw);
5090 code = cm_ConnFromFID(&cfid, userp,
5095 callp = cm_GetRxConn(connp);
5096 code = RXAFS_ExtendLock(callp, &tfid,
5098 rx_PutConnection(callp);
5100 osi_Log1(afsd_logp, " ExtendLock returns %d", code);
5102 } while (cm_Analyze(connp, userp, &req,
5103 &cfid, &volSync, NULL, NULL,
5106 code = cm_MapRPCError(code, &req);
5108 lock_ObtainWrite(&scp->rw);
5111 osi_Log1(afsd_logp, "CALL ExtendLock FAILURE, code 0x%x", code);
5113 osi_Log0(afsd_logp, "CALL ExtendLock SUCCESS");
5114 scp->lockDataVersion = scp->dataVersion;
5117 if ((code == EINVAL || code == CM_ERROR_INVAL) &&
5118 scp->lockDataVersion == scp->dataVersion) {
5122 (scp->exclusiveLocks > 0) ? LockWrite: LockRead;
5124 /* we might still have a chance to obtain a
5127 code = cm_IntSetLock(scp, userp, lockType, &req);
5130 code = CM_ERROR_INVAL;
5131 } else if (scp->lockDataVersion != scp->dataVersion) {
5133 /* now check if we still have the file at
5134 the right data version. */
5136 "Data version mismatch on scp 0x%p",
5139 " Data versions: before=%I64d, after=%I64d",
5140 scp->lockDataVersion,
5143 code = cm_IntReleaseLock(scp, userp, &req);
5145 code = CM_ERROR_INVAL;
5149 if (code == EINVAL || code == CM_ERROR_INVAL ||
5150 code == CM_ERROR_BADFD) {
5151 cm_LockMarkSCacheLost(scp);
5155 /* interestingly, we have found an active lock
5156 belonging to an scache that has no
5158 cm_LockMarkSCacheLost(scp);
5165 cm_SyncOpDone(scp, NULL, CM_SCACHESYNC_LOCK);
5168 lock_ReleaseWrite(&scp->rw);
5170 lock_ObtainWrite(&cm_scacheLock);
5173 fileLock->lastUpdate = time(NULL);
5177 scp->lastRefreshCycle = cm_lockRefreshCycle;
5180 /* we have already refreshed the locks on this scp */
5181 fileLock->lastUpdate = time(NULL);
5184 cm_ReleaseSCacheNoLock(scp);
5186 } else if (IS_LOCK_ACTIVE(fileLock) && IS_LOCK_CLIENTONLY(fileLock)) {
5187 /* TODO: Check callbacks */
5191 lock_ReleaseWrite(&cm_scacheLock);
5192 osi_Log1(afsd_logp, "cm_CheckLocks completes lock check cycle %d", cm_lockRefreshCycle);
5195 /* NOT called with scp->rw held. */
5196 long cm_RetryLock(cm_file_lock_t *oldFileLock, int client_is_dead)
5199 cm_scache_t *scp = NULL;
5200 cm_file_lock_t *fileLock;
5204 int force_client_lock = FALSE;
5205 int has_insert = FALSE;
5206 int check_data_version = FALSE;
5210 if (client_is_dead) {
5211 code = CM_ERROR_TIMEDOUT;
5215 lock_ObtainRead(&cm_scacheLock);
5217 osi_Log2(afsd_logp, "cm_RetryLock checking lock %p (scp=%p)", oldFileLock, oldFileLock->scp);
5218 osi_Log4(afsd_logp, " offset(%x:%x) length(%x:%x)",
5219 (unsigned)(oldFileLock->range.offset >> 32),
5220 (unsigned)(oldFileLock->range.offset & 0xffffffff),
5221 (unsigned)(oldFileLock->range.length >> 32),
5222 (unsigned)(oldFileLock->range.length & 0xffffffff));
5223 osi_Log3(afsd_logp, " key(%x:%x) flags=%x",
5224 (unsigned)(oldFileLock->key >> 32),
5225 (unsigned)(oldFileLock->key & 0xffffffff),
5226 (unsigned)(oldFileLock->flags));
5228 /* if the lock has already been granted, then we have nothing to do */
5229 if (IS_LOCK_ACTIVE(oldFileLock)) {
5230 lock_ReleaseRead(&cm_scacheLock);
5231 osi_Log0(afsd_logp, "cm_RetryLock lock already granted");
5235 /* we can't do anything with lost or deleted locks at the moment. */
5236 if (IS_LOCK_LOST(oldFileLock) || IS_LOCK_DELETED(oldFileLock)) {
5237 code = CM_ERROR_BADFD;
5238 osi_Log0(afsd_logp, "cm_RetryLock lock is lost or deleted");
5239 lock_ReleaseRead(&cm_scacheLock);
5243 scp = oldFileLock->scp;
5245 osi_assertx(scp != NULL, "null cm_scache_t");
5247 lock_ReleaseRead(&cm_scacheLock);
5248 lock_ObtainWrite(&scp->rw);
5250 code = cm_LockCheckPerms(scp, oldFileLock->lockType,
5254 if (code == CM_ERROR_NOACCESS && oldFileLock->lockType == LockRead) {
5255 if (!has_insert || !SCP_SUPPORTS_WRITELOCKACL(scp)) {
5256 force_client_lock = TRUE;
5260 lock_ReleaseWrite(&scp->rw);
5264 lock_ObtainWrite(&cm_scacheLock);
5266 /* Check if we already have a sufficient server lock to allow this
5267 lock to go through. */
5268 if (IS_LOCK_WAITLOCK(oldFileLock) &&
5269 (!SERVERLOCKS_ENABLED(scp) ||
5270 scp->serverLock == oldFileLock->lockType ||
5271 scp->serverLock == LockWrite)) {
5273 oldFileLock->flags &= ~CM_FILELOCK_FLAG_WAITLOCK;
5275 if (SERVERLOCKS_ENABLED(scp)) {
5276 osi_Log1(afsd_logp, "cm_RetryLock Server lock (%d) is sufficient for lock. Granting",
5277 (int) scp->serverLock);
5279 osi_Log0(afsd_logp, "cm_RetryLock skipping server lock for scp");
5282 lock_ReleaseWrite(&cm_scacheLock);
5283 lock_ReleaseWrite(&scp->rw);
5288 if (IS_LOCK_WAITUNLOCK(oldFileLock)) {
5290 /* check if the conflicting locks have dissappeared already */
5291 for (q = scp->fileLocksH; q; q = osi_QNext(q)) {
5293 fileLock = (cm_file_lock_t *)
5294 ((char *) q - offsetof(cm_file_lock_t, fileq));
5296 if (IS_LOCK_LOST(fileLock)) {
5297 if (fileLock->key == oldFileLock->key) {
5298 code = CM_ERROR_BADFD;
5299 oldFileLock->flags |= CM_FILELOCK_FLAG_LOST;
5300 osi_Log1(afsd_logp, " found lost lock %p for same key. Marking lock as lost",
5303 } else if (fileLock->lockType == LockWrite &&
5304 INTERSECT_RANGE(oldFileLock->range, fileLock->range)) {
5305 osi_Log1(afsd_logp, " found conflicting LOST lock %p", fileLock);
5306 code = CM_ERROR_WOULDBLOCK;
5311 if (IS_LOCK_ACCEPTED(fileLock) &&
5312 INTERSECT_RANGE(oldFileLock->range, fileLock->range)) {
5314 if (oldFileLock->lockType != LockRead ||
5315 fileLock->lockType != LockRead) {
5317 osi_Log1(afsd_logp, " found conflicting lock %p", fileLock);
5318 code = CM_ERROR_WOULDBLOCK;
5326 lock_ReleaseWrite(&cm_scacheLock);
5327 lock_ReleaseWrite(&scp->rw);
5332 /* when we get here, the lock is either a WAITUNLOCK or WAITLOCK.
5333 If it is WAITUNLOCK, then we didn't find any conflicting lock
5334 but we haven't verfied whether the serverLock is sufficient to
5335 assert it. If it is WAITLOCK, then the serverLock is
5336 insufficient to assert it. Eitherway, we are ready to accept
5337 the lock as either ACTIVE or WAITLOCK depending on the
5340 /* First, promote the WAITUNLOCK to a WAITLOCK */
5341 if (IS_LOCK_WAITUNLOCK(oldFileLock)) {
5342 if (oldFileLock->lockType == LockRead)
5345 scp->exclusiveLocks++;
5347 oldFileLock->flags &= ~CM_FILELOCK_FLAG_WAITUNLOCK;
5348 oldFileLock->flags |= CM_FILELOCK_FLAG_WAITLOCK;
5351 osi_assertx(IS_LOCK_WAITLOCK(oldFileLock), "!IS_LOCK_WAITLOCK");
5353 if (force_client_lock ||
5354 !SERVERLOCKS_ENABLED(scp) ||
5355 scp->serverLock == oldFileLock->lockType ||
5356 (oldFileLock->lockType == LockRead &&
5357 scp->serverLock == LockWrite)) {
5359 oldFileLock->flags &= ~CM_FILELOCK_FLAG_WAITLOCK;
5361 if ((force_client_lock ||
5362 !SERVERLOCKS_ENABLED(scp)) &&
5363 !IS_LOCK_CLIENTONLY(oldFileLock)) {
5365 oldFileLock->flags |= CM_FILELOCK_FLAG_CLIENTONLY;
5367 if (oldFileLock->lockType == LockRead)
5370 scp->exclusiveLocks--;
5375 lock_ReleaseWrite(&cm_scacheLock);
5376 lock_ReleaseWrite(&scp->rw);
5383 code = cm_SyncOp(scp, NULL, oldFileLock->userp, &req, 0,
5384 CM_SCACHESYNC_NEEDCALLBACK
5385 | CM_SCACHESYNC_GETSTATUS
5386 | CM_SCACHESYNC_LOCK);
5388 osi_Log1(afsd_logp, "cm_RetryLock SyncOp failure code 0x%x", code);
5389 lock_ReleaseWrite(&cm_scacheLock);
5390 goto post_syncopdone;
5393 if (!IS_LOCK_WAITLOCK(oldFileLock))
5394 goto pre_syncopdone;
5396 userp = oldFileLock->userp;
5398 #ifndef AGGRESSIVE_LOCKS
5399 newLock = oldFileLock->lockType;
5401 newLock = LockWrite;
5405 /* if has_insert is non-zero, then:
5406 - the lock a LockRead
5407 - we don't have permission to get a LockRead
5408 - we do have permission to get a LockWrite
5409 - the server supports VICED_CAPABILITY_WRITELOCKACL
5412 newLock = LockWrite;
5415 lock_ReleaseWrite(&cm_scacheLock);
5417 /* when we get here, either we have a read-lock and want a
5418 write-lock or we don't have any locks and we want some
5421 if (scp->serverLock == LockRead) {
5423 osi_assertx(newLock == LockWrite, "!LockWrite");
5425 osi_Log0(afsd_logp, " Attempting to UPGRADE from LockRead to LockWrite");
5427 scp->lockDataVersion = scp->dataVersion;
5428 check_data_version = TRUE;
5430 code = cm_IntReleaseLock(scp, userp, &req);
5433 goto pre_syncopdone;
5435 scp->serverLock = -1;
5438 code = cm_IntSetLock(scp, userp, newLock, &req);
5441 if (scp->dataVersion != scp->lockDataVersion) {
5442 /* we lost a race. too bad */
5445 " Data version mismatch while upgrading lock.");
5447 " Data versions before=%I64d, after=%I64d",
5448 scp->lockDataVersion,
5451 " Releasing stale lock for scp 0x%x", scp);
5453 code = cm_IntReleaseLock(scp, userp, &req);
5455 scp->serverLock = -1;
5457 code = CM_ERROR_INVAL;
5459 cm_LockMarkSCacheLost(scp);
5461 scp->serverLock = newLock;
5466 cm_SyncOpDone(scp, NULL, CM_SCACHESYNC_LOCK);
5472 if (code != 0 && code != CM_ERROR_WOULDBLOCK) {
5473 lock_ObtainWrite(&cm_scacheLock);
5474 if (scp->fileLocksT == &oldFileLock->fileq)
5475 scp->fileLocksT = osi_QPrev(&oldFileLock->fileq);
5476 osi_QRemoveHT(&scp->fileLocksH, &scp->fileLocksT, &oldFileLock->fileq);
5477 lock_ReleaseWrite(&cm_scacheLock);
5479 lock_ReleaseWrite(&scp->rw);
5482 lock_ObtainWrite(&cm_scacheLock);
5484 oldFileLock->flags &= ~CM_FILELOCK_FLAG_WAITLOCK;
5485 } else if (code != CM_ERROR_WOULDBLOCK) {
5486 oldFileLock->flags |= CM_FILELOCK_FLAG_DELETED;
5487 cm_ReleaseUser(oldFileLock->userp);
5488 oldFileLock->userp = NULL;
5489 if (oldFileLock->scp) {
5490 cm_ReleaseSCacheNoLock(oldFileLock->scp);
5491 oldFileLock->scp = NULL;
5494 lock_ReleaseWrite(&cm_scacheLock);
5499 cm_key_t cm_GenerateKey(unsigned int session_id, unsigned long process_id, unsigned int file_id)
5502 osi_assertx((process_id & 0xffffffff) == process_id, "unexpected process_id");
5503 osi_assertx((session_id & 0xffff) == session_id, "unexpected session_id");
5504 osi_assertx((file_id & 0xffff) == file_id, "unexpected file_id");
5508 (((cm_key_t) (process_id & 0xffffffff)) << 32) |
5509 (((cm_key_t) (session_id & 0xffff)) << 16) |
5510 (((cm_key_t) (file_id & 0xffff)));
5513 static int cm_KeyEquals(cm_key_t k1, cm_key_t k2, int flags)
5515 if (flags & CM_UNLOCK_BY_FID) {
5516 return ((k1 & 0xffffffff) == (k2 & 0xffffffff));
5522 void cm_ReleaseAllLocks(void)
5528 cm_file_lock_t *fileLock;
5531 for (i = 0; i < cm_data.scacheHashTableSize; i++)
5533 for ( scp = cm_data.scacheHashTablep[i]; scp; scp = scp->nextp ) {
5534 while (scp->fileLocksH != NULL) {
5535 lock_ObtainWrite(&scp->rw);
5536 lock_ObtainWrite(&cm_scacheLock);
5537 if (!scp->fileLocksH) {
5538 lock_ReleaseWrite(&cm_scacheLock);
5539 lock_ReleaseWrite(&scp->rw);
5542 fileLock = (cm_file_lock_t *)((char *) scp->fileLocksH - offsetof(cm_file_lock_t, fileq));
5543 userp = fileLock->userp;
5545 key = fileLock->key;
5546 cm_HoldSCacheNoLock(scp);
5547 lock_ReleaseWrite(&cm_scacheLock);
5548 cm_UnlockByKey(scp, key, 0, userp, &req);
5549 cm_ReleaseSCache(scp);
5550 cm_ReleaseUser(userp);
5551 lock_ReleaseWrite(&scp->rw);