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_ObtainMutex(&scp->mx);
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_ReleaseMutex(&scp->mx);
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)
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_ObtainMutex(&scp->mx);
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_ReleaseMutex(&scp->mx);
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_ObtainMutex(&scp->mx);
453 cm_Unlock(scp, (*ldpp)->sLockType, (*ldpp)->LOffset, (*ldpp)->LLength,
454 (*ldpp)->key, userp, reqp);
455 lock_ReleaseMutex(&scp->mx);
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;
485 /* First check permissions */
486 lock_ObtainMutex(&scp->mx);
487 code = cm_SyncOp(scp, NULL, userp, reqp, PRSFS_DELETE,
488 CM_SCACHESYNC_GETSTATUS | CM_SCACHESYNC_NEEDCALLBACK);
489 cm_SyncOpDone(scp, NULL, CM_SCACHESYNC_NEEDCALLBACK | CM_SCACHESYNC_GETSTATUS);
490 lock_ReleaseMutex(&scp->mx);
494 /* If deleting directory, must be empty */
496 if (scp->fileType != CM_SCACHETYPE_DIRECTORY)
499 thyper.HighPart = 0; thyper.LowPart = 0;
500 code = buf_Get(scp, &thyper, &bufferp);
504 lock_ObtainMutex(&bufferp->mx);
505 lock_ObtainMutex(&scp->mx);
507 code = cm_SyncOp(scp, bufferp, userp, reqp, 0,
508 CM_SCACHESYNC_NEEDCALLBACK
510 | CM_SCACHESYNC_BUFLOCKED);
514 if (cm_HaveBuffer(scp, bufferp, 1))
517 /* otherwise, load the buffer and try again */
518 lock_ReleaseMutex(&bufferp->mx);
519 code = cm_GetBuffer(scp, bufferp, NULL, userp, reqp);
520 lock_ReleaseMutex(&scp->mx);
521 lock_ObtainMutex(&bufferp->mx);
522 lock_ObtainMutex(&scp->mx);
523 cm_SyncOpDone(scp, bufferp, CM_SCACHESYNC_NEEDCALLBACK | CM_SCACHESYNC_READ | CM_SCACHESYNC_BUFLOCKED);
528 /* We try to determine emptiness without looking beyond the first page,
529 * and without assuming "." and ".." are present and are on the first
530 * page (though these assumptions might, after all, be reasonable).
532 hashTable = (unsigned short *)(bufferp->datap + (32 * 5));
533 for (i=0; i<128; i++) {
534 idx = ntohs(hashTable[i]);
540 dep = (cm_dirEntry_t *)(bufferp->datap + (32 * idx));
541 if (strcmp(dep->name, ".") == 0)
543 else if (strcmp(dep->name, "..") == 0)
546 code = CM_ERROR_NOTEMPTY;
549 idx = ntohs(dep->next);
552 if (BeyondPage && HaveDot && HaveDotDot)
553 code = CM_ERROR_NOTEMPTY;
557 lock_ReleaseMutex(&bufferp->mx);
558 buf_Release(bufferp);
559 lock_ReleaseMutex(&scp->mx);
564 * Iterate through all entries in a directory.
565 * When the function funcp is called, the buffer is locked but the
566 * directory vnode is not.
568 * If the retscp parameter is not NULL, the parmp must be a
569 * cm_lookupSearch_t object.
571 long cm_ApplyDir(cm_scache_t *scp, cm_DirFuncp_t funcp, void *parmp,
572 osi_hyper_t *startOffsetp, cm_user_t *userp, cm_req_t *reqp,
573 cm_scache_t **retscp)
577 cm_dirEntry_t *dep = 0;
580 osi_hyper_t dirLength;
581 osi_hyper_t bufferOffset;
582 osi_hyper_t curOffset;
586 cm_pageHeader_t *pageHeaderp;
588 long nextEntryCookie;
589 int numDirChunks; /* # of 32 byte dir chunks in this entry */
591 /* get the directory size */
592 lock_ObtainMutex(&scp->mx);
593 code = cm_SyncOp(scp, NULL, userp, reqp, PRSFS_LOOKUP,
594 CM_SCACHESYNC_NEEDCALLBACK | CM_SCACHESYNC_GETSTATUS);
595 lock_ReleaseMutex(&scp->mx);
599 if (scp->fileType != CM_SCACHETYPE_DIRECTORY)
600 return CM_ERROR_NOTDIR;
602 if (retscp) /* if this is a lookup call */
604 cm_lookupSearch_t* sp = parmp;
607 #ifdef AFS_FREELANCE_CLIENT
608 /* Freelance entries never end up in the DNLC because they
609 * do not have an associated cm_server_t
611 !(cm_freelanceEnabled &&
612 sp->fid.cell==AFS_FAKE_ROOT_CELL_ID &&
613 sp->fid.volume==AFS_FAKE_ROOT_VOL_ID )
614 #else /* !AFS_FREELANCE_CLIENT */
619 int casefold = sp->caseFold;
620 sp->caseFold = 0; /* we have a strong preference for exact matches */
621 if ( *retscp = cm_dnlcLookup(scp, sp)) /* dnlc hit */
623 sp->caseFold = casefold;
626 sp->caseFold = casefold;
628 /* see if we can find it using the directory hash tables.
629 we can only do exact matches, since the hash is case
639 code = cm_BeginDirOp(scp, userp, reqp, CM_DIRLOCK_READ, &dirop);
643 code = cm_BPlusDirLookup(&dirop, sp->searchNamep, &sp->fid);
648 code = cm_DirLookup(&dirop, sp->searchNamep, &sp->fid);
656 sp->ExactFound = TRUE;
657 *retscp = NULL; /* force caller to call cm_GetSCache() */
662 if (sp->caseFold && code == CM_ERROR_INEXACT_MATCH) {
665 sp->ExactFound = FALSE;
666 *retscp = NULL; /* force caller to call cm_GetSCache() */
670 return CM_ERROR_BPLUS_NOMATCH;
678 * XXX We only get the length once. It might change when we drop the
681 dirLength = scp->length;
684 bufferOffset.LowPart = bufferOffset.HighPart = 0;
686 curOffset = *startOffsetp;
688 curOffset.HighPart = 0;
689 curOffset.LowPart = 0;
693 /* make sure that curOffset.LowPart doesn't point to the first
694 * 32 bytes in the 2nd through last dir page, and that it
695 * doesn't point at the first 13 32-byte chunks in the first
696 * dir page, since those are dir and page headers, and don't
697 * contain useful information.
699 temp = curOffset.LowPart & (2048-1);
700 if (curOffset.HighPart == 0 && curOffset.LowPart < 2048) {
701 /* we're in the first page */
702 if (temp < 13*32) temp = 13*32;
705 /* we're in a later dir page */
706 if (temp < 32) temp = 32;
709 /* make sure the low order 5 bits are zero */
712 /* now put temp bits back ito curOffset.LowPart */
713 curOffset.LowPart &= ~(2048-1);
714 curOffset.LowPart |= temp;
716 /* check if we've passed the dir's EOF */
717 if (LargeIntegerGreaterThanOrEqualTo(curOffset, dirLength))
720 /* see if we can use the bufferp we have now; compute in which
721 * page the current offset would be, and check whether that's
722 * the offset of the buffer we have. If not, get the buffer.
724 thyper.HighPart = curOffset.HighPart;
725 thyper.LowPart = curOffset.LowPart & ~(cm_data.buf_blockSize-1);
726 if (!bufferp || !LargeIntegerEqualTo(thyper, bufferOffset)) {
729 lock_ReleaseMutex(&bufferp->mx);
730 buf_Release(bufferp);
734 code = buf_Get(scp, &thyper, &bufferp);
736 /* if buf_Get() fails we do not have a buffer object to lock */
742 /* for the IFS version, we bulkstat the dirents because this
743 routine is used in place of smb_ReceiveCoreSearchDir. our
744 other option is to modify smb_ReceiveCoreSearchDir itself,
745 but this seems to be the proper use for cm_ApplyDir. */
746 lock_ObtainMutex(&scp->mx);
747 if ((scp->flags & CM_SCACHEFLAG_BULKSTATTING) == 0
748 && (scp->bulkStatProgress.QuadPart <= thyper.QuadPart))
750 scp->flags |= CM_SCACHEFLAG_BULKSTATTING;
751 code = cm_TryBulkStat(scp, &thyper, userp, reqp);
752 scp->flags &= ~CM_SCACHEFLAG_BULKSTATTING;
753 scp->bulkStatProgress = thyper;
755 lock_ReleaseMutex(&scp->mx);
758 lock_ObtainMutex(&bufferp->mx);
759 bufferOffset = thyper;
761 /* now get the data in the cache */
763 lock_ObtainMutex(&scp->mx);
764 code = cm_SyncOp(scp, bufferp, userp, reqp,
766 CM_SCACHESYNC_NEEDCALLBACK
768 | CM_SCACHESYNC_BUFLOCKED);
770 lock_ReleaseMutex(&scp->mx);
773 cm_SyncOpDone(scp, bufferp, CM_SCACHESYNC_NEEDCALLBACK | CM_SCACHESYNC_READ | CM_SCACHESYNC_BUFLOCKED);
775 if (cm_HaveBuffer(scp, bufferp, 1)) {
776 lock_ReleaseMutex(&scp->mx);
780 /* otherwise, load the buffer and try again */
781 lock_ReleaseMutex(&bufferp->mx);
782 code = cm_GetBuffer(scp, bufferp, NULL, userp,
784 lock_ReleaseMutex(&scp->mx);
785 lock_ObtainMutex(&bufferp->mx);
790 lock_ReleaseMutex(&bufferp->mx);
791 buf_Release(bufferp);
795 } /* if (wrong buffer) ... */
797 /* now we have the buffer containing the entry we're interested
798 * in; copy it out if it represents a non-deleted entry.
800 entryInDir = curOffset.LowPart & (2048-1);
801 entryInBuffer = curOffset.LowPart & (cm_data.buf_blockSize - 1);
803 /* page header will help tell us which entries are free. Page
804 * header can change more often than once per buffer, since
805 * AFS 3 dir page size may be less than (but not more than) a
806 * buffer package buffer.
808 /* only look intra-buffer */
809 temp = curOffset.LowPart & (cm_data.buf_blockSize - 1);
810 temp &= ~(2048 - 1); /* turn off intra-page bits */
811 pageHeaderp = (cm_pageHeader_t *) (bufferp->datap + temp);
813 /* now determine which entry we're looking at in the page. If
814 * it is free (there's a free bitmap at the start of the dir),
815 * we should skip these 32 bytes.
817 slotInPage = (entryInDir & 0x7e0) >> 5;
818 if (!(pageHeaderp->freeBitmap[slotInPage>>3]
819 & (1 << (slotInPage & 0x7)))) {
820 /* this entry is free */
821 numDirChunks = 1; /* only skip this guy */
825 tp = bufferp->datap + entryInBuffer;
826 dep = (cm_dirEntry_t *) tp; /* now points to AFS3 dir entry */
828 /* while we're here, compute the next entry's location, too,
829 * since we'll need it when writing out the cookie into the
830 * dir listing stream.
832 numDirChunks = cm_NameEntries(dep->name, NULL);
834 /* compute the offset of the cookie representing the next entry */
835 nextEntryCookie = curOffset.LowPart
836 + (CM_DIR_CHUNKSIZE * numDirChunks);
838 if (dep->fid.vnode != 0) {
839 /* this is one of the entries to use: it is not deleted */
840 code = (*funcp)(scp, dep, parmp, &curOffset);
843 } /* if we're including this name */
846 /* and adjust curOffset to be where the new cookie is */
848 thyper.LowPart = CM_DIR_CHUNKSIZE * numDirChunks;
849 curOffset = LargeIntegerAdd(thyper, curOffset);
850 } /* while copying data for dir listing */
852 /* release the mutex */
854 lock_ReleaseMutex(&bufferp->mx);
855 buf_Release(bufferp);
860 int cm_NoneUpper(char *s)
864 if (c >= 'A' && c <= 'Z')
869 int cm_NoneLower(char *s)
873 if (c >= 'a' && c <= 'z')
878 long cm_LookupSearchProc(cm_scache_t *scp, cm_dirEntry_t *dep, void *rockp,
881 cm_lookupSearch_t *sp;
886 sp = (cm_lookupSearch_t *) rockp;
888 matchName = dep->name;
890 match = cm_stricmp(matchName, sp->searchNamep);
892 match = strcmp(matchName, sp->searchNamep);
896 && !cm_Is8Dot3(dep->name)) {
897 matchName = shortName;
898 cm_Gen8Dot3Name(dep, shortName, NULL);
900 match = cm_stricmp(matchName, sp->searchNamep);
902 match = strcmp(matchName, sp->searchNamep);
912 if (!sp->caseFold || matchName == shortName) {
913 sp->fid.vnode = ntohl(dep->fid.vnode);
914 sp->fid.unique = ntohl(dep->fid.unique);
915 return CM_ERROR_STOPNOW;
919 * If we get here, we are doing a case-insensitive search, and we
920 * have found a match. Now we determine what kind of match it is:
921 * exact, lower-case, upper-case, or none of the above. This is done
922 * in order to choose among matches, if there are more than one.
925 /* Exact matches are the best. */
926 match = strcmp(matchName, sp->searchNamep);
929 sp->fid.vnode = ntohl(dep->fid.vnode);
930 sp->fid.unique = ntohl(dep->fid.unique);
931 return CM_ERROR_STOPNOW;
934 /* Lower-case matches are next. */
937 if (cm_NoneUpper(matchName)) {
942 /* Upper-case matches are next. */
945 if (cm_NoneLower(matchName)) {
950 /* General matches are last. */
956 sp->fid.vnode = ntohl(dep->fid.vnode);
957 sp->fid.unique = ntohl(dep->fid.unique);
961 /* read the contents of a mount point into the appropriate string.
962 * called with locked scp, and returns with locked scp.
964 long cm_ReadMountPoint(cm_scache_t *scp, cm_user_t *userp, cm_req_t *reqp)
971 if (scp->mountPointStringp[0])
974 /* otherwise, we have to read it in */
975 lock_ReleaseMutex(&scp->mx);
977 thyper.LowPart = thyper.HighPart = 0;
978 code = buf_Get(scp, &thyper, &bufp);
980 lock_ObtainMutex(&scp->mx);
985 code = cm_SyncOp(scp, bufp, userp, reqp, 0,
986 CM_SCACHESYNC_READ | CM_SCACHESYNC_NEEDCALLBACK);
990 cm_SyncOpDone(scp, bufp, CM_SCACHESYNC_NEEDCALLBACK | CM_SCACHESYNC_READ);
992 if (cm_HaveBuffer(scp, bufp, 0))
995 /* otherwise load buffer */
996 code = cm_GetBuffer(scp, bufp, NULL, userp, reqp);
1000 /* locked, has callback, has valid data in buffer */
1001 if ((tlen = scp->length.LowPart) > MOUNTPOINTLEN - 1)
1002 return CM_ERROR_TOOBIG;
1004 code = CM_ERROR_INVAL;
1008 /* someone else did the work while we were out */
1009 if (scp->mountPointStringp[0]) {
1014 /* otherwise, copy out the link */
1015 memcpy(scp->mountPointStringp, bufp->datap, tlen);
1017 /* now make it null-terminated. Note that the original contents of a
1018 * link that is a mount point is "#volname." where "." is there just to
1019 * be turned into a null. That is, we can trash the last char of the
1020 * link without damaging the vol name. This is a stupid convention,
1021 * but that's the protocol.
1023 scp->mountPointStringp[tlen-1] = 0;
1033 /* called with a locked scp and chases the mount point, yielding outScpp.
1034 * scp remains locked, just for simplicity of describing the interface.
1036 long cm_FollowMountPoint(cm_scache_t *scp, cm_scache_t *dscp, cm_user_t *userp,
1037 cm_req_t *reqp, cm_scache_t **outScpp)
1045 cm_volume_t *volp = NULL;
1052 if (scp->mountRootFid.cell != 0 && scp->mountRootGen >= cm_data.mountRootGen) {
1053 tfid = scp->mountRootFid;
1054 lock_ReleaseMutex(&scp->mx);
1055 code = cm_GetSCache(&tfid, outScpp, userp, reqp);
1056 lock_ObtainMutex(&scp->mx);
1060 /* parse the volume name */
1061 mpNamep = scp->mountPointStringp;
1063 return CM_ERROR_NOSUCHPATH;
1064 tlen = (int)strlen(scp->mountPointStringp);
1065 mtType = *scp->mountPointStringp;
1066 cellNamep = malloc(tlen);
1067 volNamep = malloc(tlen);
1069 cp = strrchr(mpNamep, ':');
1071 /* cellular mount point */
1072 memset(cellNamep, 0, tlen);
1073 strncpy(cellNamep, mpNamep+1, cp - mpNamep - 1);
1074 strcpy(volNamep, cp+1);
1075 /* now look up the cell */
1076 lock_ReleaseMutex(&scp->mx);
1077 cellp = cm_GetCell(cellNamep, CM_FLAG_CREATE);
1078 lock_ObtainMutex(&scp->mx);
1082 strcpy(volNamep, mpNamep+1);
1084 cellp = cm_FindCellByID(scp->fid.cell, 0);
1088 code = CM_ERROR_NOSUCHCELL;
1092 vnLength = strlen(volNamep);
1093 if (vnLength >= 8 && strcmp(volNamep + vnLength - 7, ".backup") == 0)
1094 targetType = BACKVOL;
1095 else if (vnLength >= 10
1096 && strcmp(volNamep + vnLength - 9, ".readonly") == 0)
1101 /* check for backups within backups */
1102 if (targetType == BACKVOL
1103 && (scp->flags & (CM_SCACHEFLAG_RO | CM_SCACHEFLAG_PURERO))
1104 == CM_SCACHEFLAG_RO) {
1105 code = CM_ERROR_NOSUCHVOLUME;
1109 /* now we need to get the volume */
1110 lock_ReleaseMutex(&scp->mx);
1111 if (cm_VolNameIsID(volNamep)) {
1112 code = cm_GetVolumeByID(cellp, atoi(volNamep), userp, reqp,
1113 CM_GETVOL_FLAG_CREATE, &volp);
1115 code = cm_GetVolumeByName(cellp, volNamep, userp, reqp,
1116 CM_GETVOL_FLAG_CREATE, &volp);
1118 lock_ObtainMutex(&scp->mx);
1121 afs_uint32 cell, volume;
1123 /* save the parent of the volume root for this is the
1124 * place where the volume is mounted and we must remember
1125 * this in the volume structure rather than just in the
1126 * scache entry lest the scache entry gets recycled
1129 lock_ObtainMutex(&volp->mx);
1130 volp->dotdotFid = dscp->fid;
1131 lock_ReleaseMutex(&volp->mx);
1133 cell = cellp->cellID;
1135 /* if the mt pt originates in a .backup volume (not a .readonly)
1136 * and FollowBackupPath is active, and if there is a .backup
1137 * volume for the target, then use the .backup of the target
1138 * instead of the read-write.
1140 if (cm_followBackupPath &&
1142 (dscp->flags & (CM_SCACHEFLAG_RO|CM_SCACHEFLAG_PURERO)) == CM_SCACHEFLAG_RO &&
1143 (targetType == RWVOL || targetType == ROVOL && volp->ro.ID == 0)
1145 targetType = BACKVOL;
1147 /* if the mt pt is in a read-only volume (not just a
1148 * backup), and if there is a read-only volume for the
1149 * target, and if this is a targetType '#' mount point, use
1150 * the read-only, otherwise use the one specified.
1152 else if (mtType == '#' && targetType == RWVOL &&
1153 (scp->flags & CM_SCACHEFLAG_PURERO) &&
1157 if (targetType == ROVOL)
1158 volume = volp->ro.ID;
1159 else if (targetType == BACKVOL)
1160 volume = volp->bk.ID;
1162 volume = volp->rw.ID;
1164 /* the rest of the fid is a magic number */
1165 cm_SetFid(&scp->mountRootFid, cell, volume, 1, 1);
1166 scp->mountRootGen = cm_data.mountRootGen;
1168 tfid = scp->mountRootFid;
1169 lock_ReleaseMutex(&scp->mx);
1170 code = cm_GetSCache(&tfid, outScpp, userp, reqp);
1171 lock_ObtainMutex(&scp->mx);
1182 long cm_LookupInternal(cm_scache_t *dscp, char *namep, long flags, cm_user_t *userp,
1183 cm_req_t *reqp, cm_scache_t **outpScpp)
1186 int dnlcHit = 1; /* did we hit in the dnlc? yes, we did */
1187 cm_scache_t *tscp = NULL;
1188 cm_scache_t *mountedScp;
1189 cm_lookupSearch_t rock;
1192 memset(&rock, 0, sizeof(rock));
1194 if (dscp->fid.vnode == 1 && dscp->fid.unique == 1
1195 && strcmp(namep, "..") == 0) {
1196 if (dscp->dotdotFid.volume == 0)
1197 return CM_ERROR_NOSUCHVOLUME;
1198 rock.fid = dscp->dotdotFid;
1200 } else if (strcmp(namep, ".") == 0) {
1201 rock.fid = dscp->fid;
1205 if (flags & CM_FLAG_NOMOUNTCHASE) {
1206 /* In this case, we should go and call cm_Dir* functions
1207 directly since the following cm_ApplyDir() function will
1215 code = cm_BeginDirOp(dscp, userp, reqp, CM_DIRLOCK_READ, &dirop);
1218 code = cm_BPlusDirLookup(&dirop, namep, &rock.fid);
1223 code = cm_DirLookup(&dirop, namep, &rock.fid);
1225 cm_EndDirOp(&dirop);
1235 if (code == CM_ERROR_INEXACT_MATCH && (flags & CM_FLAG_CASEFOLD)) {
1242 return CM_ERROR_BPLUS_NOMATCH;
1247 rock.fid.cell = dscp->fid.cell;
1248 rock.fid.volume = dscp->fid.volume;
1249 rock.searchNamep = namep;
1250 rock.caseFold = (flags & CM_FLAG_CASEFOLD);
1251 rock.hasTilde = ((strchr(namep, '~') != NULL) ? 1 : 0);
1253 /* If NOMOUNTCHASE, bypass DNLC by passing NULL scp pointer */
1254 code = cm_ApplyDir(dscp, cm_LookupSearchProc, &rock, NULL, userp, reqp,
1255 (flags & CM_FLAG_NOMOUNTCHASE) ? NULL : &tscp);
1257 /* code == 0 means we fell off the end of the dir, while stopnow means
1258 * that we stopped early, probably because we found the entry we're
1259 * looking for. Any other non-zero code is an error.
1261 if (code && code != CM_ERROR_STOPNOW) {
1262 /* if the cm_scache_t we are searching in is not a directory
1263 * we must return path not found because the error
1264 * is to describe the final component not an intermediary
1266 if (code == CM_ERROR_NOTDIR) {
1267 if (flags & CM_FLAG_CHECKPATH)
1268 return CM_ERROR_NOSUCHPATH;
1270 return CM_ERROR_NOSUCHFILE;
1275 getroot = (dscp==cm_data.rootSCachep) ;
1277 if (!cm_freelanceEnabled || !getroot) {
1278 if (flags & CM_FLAG_CHECKPATH)
1279 return CM_ERROR_NOSUCHPATH;
1281 return CM_ERROR_NOSUCHFILE;
1283 else if (!strchr(namep, '#') && !strchr(namep, '%') &&
1284 strcmp(namep, "srvsvc") && strcmp(namep, "wkssvc") &&
1285 strcmp(namep, "ipc$")) {
1286 /* nonexistent dir on freelance root, so add it */
1287 char fullname[200] = ".";
1290 osi_Log1(afsd_logp,"cm_Lookup adding mount for non-existent directory: %s",
1291 osi_LogSaveString(afsd_logp,namep));
1294 * There is an ugly behavior where a share name "foo" will be searched
1295 * for as "fo". If the searched for name differs by an already existing
1296 * symlink or mount point in the Freelance directory, do not add the
1297 * new value automatically.
1301 if (namep[0] == '.') {
1302 if (cm_GetCell_Gen(&namep[1], &fullname[1], CM_FLAG_CREATE)) {
1304 if (!cm_FreelanceMountPointExists(fullname, 0))
1305 code = cm_FreelanceAddMount(fullname, &fullname[1], "root.cell.", 1, &rock.fid);
1306 if ( stricmp(&namep[1], &fullname[1]) &&
1307 !cm_FreelanceMountPointExists(namep, flags & CM_FLAG_DFS_REFERRAL ? 1 : 0) &&
1308 !cm_FreelanceSymlinkExists(namep, flags & CM_FLAG_DFS_REFERRAL ? 1 : 0))
1309 code = cm_FreelanceAddSymlink(namep, fullname, &rock.fid);
1312 if (cm_GetCell_Gen(namep, fullname, CM_FLAG_CREATE)) {
1314 if (!cm_FreelanceMountPointExists(fullname, 0))
1315 code = cm_FreelanceAddMount(fullname, fullname, "root.cell.", 0, &rock.fid);
1316 if ( stricmp(namep, fullname) &&
1317 !cm_FreelanceMountPointExists(namep, flags & CM_FLAG_DFS_REFERRAL ? 1 : 0) &&
1318 !cm_FreelanceSymlinkExists(namep, flags & CM_FLAG_DFS_REFERRAL ? 1 : 0))
1319 code = cm_FreelanceAddSymlink(namep, fullname, &rock.fid);
1322 if (!found || code < 0) { /* add mount point failed, so give up */
1323 if (flags & CM_FLAG_CHECKPATH)
1324 return CM_ERROR_NOSUCHPATH;
1326 return CM_ERROR_NOSUCHFILE;
1328 tscp = NULL; /* to force call of cm_GetSCache */
1333 if ( !tscp ) /* we did not find it in the dnlc */
1336 code = cm_GetSCache(&rock.fid, &tscp, userp, reqp);
1340 /* tscp is now held */
1342 lock_ObtainMutex(&tscp->mx);
1343 code = cm_SyncOp(tscp, NULL, userp, reqp, 0,
1344 CM_SCACHESYNC_GETSTATUS | CM_SCACHESYNC_NEEDCALLBACK);
1346 lock_ReleaseMutex(&tscp->mx);
1347 cm_ReleaseSCache(tscp);
1350 cm_SyncOpDone(tscp, NULL, CM_SCACHESYNC_NEEDCALLBACK | CM_SCACHESYNC_GETSTATUS);
1351 /* tscp is now locked */
1353 if (!(flags & CM_FLAG_NOMOUNTCHASE)
1354 && tscp->fileType == CM_SCACHETYPE_MOUNTPOINT) {
1355 /* mount points are funny: they have a volume name to mount
1358 code = cm_ReadMountPoint(tscp, userp, reqp);
1360 code = cm_FollowMountPoint(tscp, dscp, userp, reqp,
1362 lock_ReleaseMutex(&tscp->mx);
1363 cm_ReleaseSCache(tscp);
1370 lock_ReleaseMutex(&tscp->mx);
1373 /* copy back pointer */
1376 /* insert scache in dnlc */
1377 if ( !dnlcHit && !(flags & CM_FLAG_NOMOUNTCHASE) && rock.ExactFound ) {
1378 /* lock the directory entry to prevent racing callback revokes */
1379 lock_ObtainMutex(&dscp->mx);
1380 if ( dscp->cbServerp != NULL && dscp->cbExpires > 0 )
1381 cm_dnlcEnter(dscp, namep, tscp);
1382 lock_ReleaseMutex(&dscp->mx);
1389 int cm_ExpandSysName(char *inp, char *outp, long outSize, unsigned int index)
1394 tp = strrchr(inp, '@');
1396 return 0; /* no @sys */
1398 if (strcmp(tp, "@sys") != 0)
1399 return 0; /* no @sys */
1401 /* caller just wants to know if this is a valid @sys type of name */
1405 if (index >= MAXNUMSYSNAMES)
1408 /* otherwise generate the properly expanded @sys name */
1409 prefixCount = (int)(tp - inp);
1411 strncpy(outp, inp, prefixCount); /* copy out "a." from "a.@sys" */
1412 outp[prefixCount] = 0; /* null terminate the "a." */
1413 strcat(outp, cm_sysNameList[index]);/* append i386_nt40 */
1417 long cm_EvaluateVolumeReference(char * namep, long flags, cm_user_t * userp,
1418 cm_req_t *reqp, cm_scache_t ** outpScpp)
1421 char cellName[CELL_MAXNAMELEN];
1422 char volumeName[VL_MAXNAMELEN];
1427 cm_cell_t * cellp = NULL;
1428 cm_volume_t * volp = NULL;
1432 int mountType = RWVOL;
1434 osi_Log1(afsd_logp, "cm_EvaluateVolumeReference for string [%s]",
1435 osi_LogSaveString(afsd_logp, namep));
1437 if (strnicmp(namep, CM_PREFIX_VOL, CM_PREFIX_VOL_CCH) != 0) {
1438 goto _exit_invalid_path;
1441 /* namep is assumed to look like the following:
1443 @vol:<cellname>%<volume>\0
1445 @vol:<cellname>#<volume>\0
1449 cp = namep + CM_PREFIX_VOL_CCH; /* cp points to cell name, hopefully */
1450 tp = strchr(cp, '%');
1452 tp = strchr(cp, '#');
1454 (len = tp - cp) == 0 ||
1455 len > CELL_MAXNAMELEN)
1456 goto _exit_invalid_path;
1457 strncpy(cellName, cp, len);
1458 cellName[len] = '\0';
1463 cp = tp+1; /* cp now points to volume, supposedly */
1464 strncpy(volumeName, cp, VL_MAXNAMELEN-1);
1465 volumeName[VL_MAXNAMELEN - 1] = 0;
1467 /* OK, now we have the cell and the volume */
1468 osi_Log2(afsd_logp, " Found cell [%s] and volume [%s]",
1469 osi_LogSaveString(afsd_logp, cellName),
1470 osi_LogSaveString(afsd_logp, volumeName));
1472 cellp = cm_GetCell(cellName, CM_FLAG_CREATE);
1473 if (cellp == NULL) {
1474 goto _exit_invalid_path;
1477 len = strlen(volumeName);
1478 if (len >= 8 && strcmp(volumeName + len - 7, ".backup") == 0)
1480 else if (len >= 10 &&
1481 strcmp(volumeName + len - 9, ".readonly") == 0)
1486 if (cm_VolNameIsID(volumeName)) {
1487 code = cm_GetVolumeByID(cellp, atoi(volumeName), userp, reqp,
1488 CM_GETVOL_FLAG_CREATE, &volp);
1490 code = cm_GetVolumeByName(cellp, volumeName, userp, reqp,
1491 CM_GETVOL_FLAG_CREATE, &volp);
1497 if (volType == BACKVOL)
1498 volume = volp->bk.ID;
1499 else if (volType == ROVOL ||
1500 (volType == RWVOL && mountType == ROVOL && volp->ro.ID != 0))
1501 volume = volp->ro.ID;
1503 volume = volp->rw.ID;
1505 cm_SetFid(&fid, cellp->cellID, volume, 1, 1);
1507 code = cm_GetSCache(&fid, outpScpp, userp, reqp);
1517 if (flags & CM_FLAG_CHECKPATH)
1518 return CM_ERROR_NOSUCHPATH;
1520 return CM_ERROR_NOSUCHFILE;
1523 #ifdef DEBUG_REFCOUNT
1524 long cm_LookupDbg(cm_scache_t *dscp, char *namep, long flags, cm_user_t *userp,
1525 cm_req_t *reqp, cm_scache_t **outpScpp, char * file, long line)
1527 long cm_Lookup(cm_scache_t *dscp, char *namep, long flags, cm_user_t *userp,
1528 cm_req_t *reqp, cm_scache_t **outpScpp)
1532 char tname[AFSPATHMAX];
1533 int sysNameIndex = 0;
1534 cm_scache_t *scp = NULL;
1536 #ifdef DEBUG_REFCOUNT
1537 afsi_log("%s:%d cm_Lookup dscp 0x%p ref %d", file, line, dscp, dscp->refCount, file, line);
1538 osi_Log2(afsd_logp, "cm_Lookup dscp 0x%p ref %d", dscp, dscp->refCount);
1541 if ( stricmp(namep,SMB_IOCTL_FILENAME_NOSLASH) == 0 ) {
1542 if (flags & CM_FLAG_CHECKPATH)
1543 return CM_ERROR_NOSUCHPATH;
1545 return CM_ERROR_NOSUCHFILE;
1548 if (dscp == cm_data.rootSCachep &&
1549 strnicmp(namep, CM_PREFIX_VOL, CM_PREFIX_VOL_CCH) == 0) {
1550 return cm_EvaluateVolumeReference(namep, flags, userp, reqp, outpScpp);
1553 if (cm_ExpandSysName(namep, NULL, 0, 0) > 0) {
1554 for ( sysNameIndex = 0; sysNameIndex < MAXNUMSYSNAMES; sysNameIndex++) {
1555 code = cm_ExpandSysName(namep, tname, sizeof(tname), sysNameIndex);
1557 code = cm_LookupInternal(dscp, tname, flags, userp, reqp, &scp);
1558 #ifdef DEBUG_REFCOUNT
1559 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);
1560 osi_Log3(afsd_logp, "cm_LookupInternal (1) code 0x%x dscp 0x%p scp 0x%p", code, dscp, scp);
1568 cm_ReleaseSCache(scp);
1572 code = cm_LookupInternal(dscp, namep, flags, userp, reqp, &scp);
1573 #ifdef DEBUG_REFCOUNT
1574 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);
1575 osi_Log3(afsd_logp, "cm_LookupInternal (2) code 0x%x dscp 0x%p scp 0x%p", code, dscp, scp);
1582 code = cm_LookupInternal(dscp, namep, flags, userp, reqp, &scp);
1583 #ifdef DEBUG_REFCOUNT
1584 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);
1585 osi_Log3(afsd_logp, "cm_LookupInternal (2) code 0x%x dscp 0x%p scp 0x%p", code, dscp, scp);
1591 /* None of the possible sysName expansions could be found */
1592 if (flags & CM_FLAG_CHECKPATH)
1593 return CM_ERROR_NOSUCHPATH;
1595 return CM_ERROR_NOSUCHFILE;
1598 long cm_Unlink(cm_scache_t *dscp, char *namep, cm_user_t *userp, cm_req_t *reqp)
1604 AFSFetchStatus newDirStatus;
1606 struct rx_connection * callp;
1609 #ifdef AFS_FREELANCE_CLIENT
1610 if (cm_freelanceEnabled && dscp == cm_data.rootSCachep) {
1611 /* deleting a mount point from the root dir. */
1612 code = cm_FreelanceRemoveMount(namep);
1617 /* make sure we don't screw up the dir status during the merge */
1618 code = cm_BeginDirOp(dscp, userp, reqp, CM_DIRLOCK_NONE, &dirop);
1620 lock_ObtainMutex(&dscp->mx);
1621 sflags = CM_SCACHESYNC_STOREDATA;
1622 code = cm_SyncOp(dscp, NULL, userp, reqp, 0, sflags);
1623 lock_ReleaseMutex(&dscp->mx);
1625 cm_EndDirOp(&dirop);
1630 afsFid.Volume = dscp->fid.volume;
1631 afsFid.Vnode = dscp->fid.vnode;
1632 afsFid.Unique = dscp->fid.unique;
1634 osi_Log1(afsd_logp, "CALL RemoveFile scp 0x%p", dscp);
1636 code = cm_ConnFromFID(&dscp->fid, userp, reqp, &connp);
1640 callp = cm_GetRxConn(connp);
1641 code = RXAFS_RemoveFile(callp, &afsFid, namep,
1642 &newDirStatus, &volSync);
1643 rx_PutConnection(callp);
1645 } while (cm_Analyze(connp, userp, reqp, &dscp->fid, &volSync, NULL, NULL, code));
1646 code = cm_MapRPCError(code, reqp);
1649 osi_Log1(afsd_logp, "CALL RemoveFile FAILURE, code 0x%x", code);
1651 osi_Log0(afsd_logp, "CALL RemoveFile SUCCESS");
1654 lock_ObtainWrite(&dirop.scp->dirlock);
1655 dirop.lockType = CM_DIRLOCK_WRITE;
1657 lock_ObtainMutex(&dscp->mx);
1658 cm_dnlcRemove(dscp, namep);
1659 cm_SyncOpDone(dscp, NULL, sflags);
1661 cm_MergeStatus(NULL, dscp, &newDirStatus, &volSync, userp, CM_MERGEFLAG_DIROP);
1662 } else if (code == CM_ERROR_NOSUCHFILE) {
1663 /* windows would not have allowed the request to delete the file
1664 * if it did not believe the file existed. therefore, we must
1665 * have an inconsistent view of the world.
1667 dscp->cbServerp = NULL;
1669 lock_ReleaseMutex(&dscp->mx);
1671 if (code == 0 && cm_CheckDirOpForSingleChange(&dirop)) {
1672 cm_DirDeleteEntry(&dirop, namep);
1674 cm_BPlusDirDeleteEntry(&dirop, namep);
1677 cm_EndDirOp(&dirop);
1682 /* called with a locked vnode, and fills in the link info.
1683 * returns this the vnode still locked.
1685 long cm_HandleLink(cm_scache_t *linkScp, cm_user_t *userp, cm_req_t *reqp)
1692 lock_AssertMutex(&linkScp->mx);
1693 if (!linkScp->mountPointStringp[0]) {
1694 /* read the link data */
1695 lock_ReleaseMutex(&linkScp->mx);
1696 thyper.LowPart = thyper.HighPart = 0;
1697 code = buf_Get(linkScp, &thyper, &bufp);
1698 lock_ObtainMutex(&linkScp->mx);
1702 code = cm_SyncOp(linkScp, bufp, userp, reqp, 0,
1703 CM_SCACHESYNC_NEEDCALLBACK | CM_SCACHESYNC_READ);
1708 cm_SyncOpDone(linkScp, bufp, CM_SCACHESYNC_NEEDCALLBACK | CM_SCACHESYNC_READ);
1710 if (cm_HaveBuffer(linkScp, bufp, 0))
1713 code = cm_GetBuffer(linkScp, bufp, NULL, userp, reqp);
1718 } /* while loop to get the data */
1720 /* now if we still have no link read in,
1721 * copy the data from the buffer */
1722 if ((temp = linkScp->length.LowPart) >= MOUNTPOINTLEN) {
1724 return CM_ERROR_TOOBIG;
1727 /* otherwise, it fits; make sure it is still null (could have
1728 * lost race with someone else referencing this link above),
1729 * and if so, copy in the data.
1731 if (!linkScp->mountPointStringp[0]) {
1732 strncpy(linkScp->mountPointStringp, bufp->datap, temp);
1733 linkScp->mountPointStringp[temp] = 0; /* null terminate */
1735 if ( !strnicmp(linkScp->mountPointStringp, "msdfs:", strlen("msdfs:")) )
1736 linkScp->fileType = CM_SCACHETYPE_DFSLINK;
1739 } /* don't have sym link contents cached */
1744 /* called with a held vnode and a path suffix, with the held vnode being a
1745 * symbolic link. Our goal is to generate a new path to interpret, and return
1746 * this new path in newSpaceBufferp. If the new vnode is relative to a dir
1747 * other than the directory containing the symbolic link, then the new root is
1748 * returned in *newRootScpp, otherwise a null is returned there.
1750 long cm_AssembleLink(cm_scache_t *linkScp, char *pathSuffixp,
1751 cm_scache_t **newRootScpp, cm_space_t **newSpaceBufferp,
1752 cm_user_t *userp, cm_req_t *reqp)
1759 *newRootScpp = NULL;
1760 *newSpaceBufferp = NULL;
1762 lock_ObtainMutex(&linkScp->mx);
1763 code = cm_HandleLink(linkScp, userp, reqp);
1767 /* if we may overflow the buffer, bail out; buffer is signficantly
1768 * bigger than max path length, so we don't really have to worry about
1769 * being a little conservative here.
1771 if (strlen(linkScp->mountPointStringp) + strlen(pathSuffixp) + 2
1772 >= CM_UTILS_SPACESIZE)
1773 return CM_ERROR_TOOBIG;
1775 tsp = cm_GetSpace();
1776 linkp = linkScp->mountPointStringp;
1777 if (strncmp(linkp, cm_mountRoot, cm_mountRootLen) == 0) {
1778 if (strlen(linkp) > cm_mountRootLen)
1779 strcpy(tsp->data, linkp+cm_mountRootLen+1);
1782 *newRootScpp = cm_data.rootSCachep;
1783 cm_HoldSCache(cm_data.rootSCachep);
1784 } else if (linkp[0] == '\\' && linkp[1] == '\\') {
1785 if (!strnicmp(&linkp[2], cm_NetbiosName, (len = (long)strlen(cm_NetbiosName))))
1787 char * p = &linkp[len + 3];
1788 if (strnicmp(p, "all", 3) == 0)
1791 strcpy(tsp->data, p);
1792 for (p = tsp->data; *p; p++) {
1796 *newRootScpp = cm_data.rootSCachep;
1797 cm_HoldSCache(cm_data.rootSCachep);
1799 linkScp->fileType = CM_SCACHETYPE_DFSLINK;
1800 strcpy(tsp->data, linkp);
1801 code = CM_ERROR_PATH_NOT_COVERED;
1803 } else if ( linkScp->fileType == CM_SCACHETYPE_DFSLINK ||
1804 !strnicmp(linkp, "msdfs:", (len = (long)strlen("msdfs:"))) ) {
1805 linkScp->fileType = CM_SCACHETYPE_DFSLINK;
1806 strcpy(tsp->data, linkp);
1807 code = CM_ERROR_PATH_NOT_COVERED;
1808 } else if (*linkp == '\\' || *linkp == '/') {
1810 /* formerly, this was considered to be from the AFS root,
1811 * but this seems to create problems. instead, we will just
1812 * reject the link */
1813 strcpy(tsp->data, linkp+1);
1814 *newRootScpp = cm_data.rootSCachep;
1815 cm_HoldSCache(cm_data.rootSCachep);
1817 /* we still copy the link data into the response so that
1818 * the user can see what the link points to
1820 linkScp->fileType = CM_SCACHETYPE_INVALID;
1821 strcpy(tsp->data, linkp);
1822 code = CM_ERROR_NOSUCHPATH;
1825 /* a relative link */
1826 strcpy(tsp->data, linkp);
1828 if (pathSuffixp[0] != 0) { /* if suffix string is non-null */
1829 strcat(tsp->data, "\\");
1830 strcat(tsp->data, pathSuffixp);
1833 *newSpaceBufferp = tsp;
1837 if (code == CM_ERROR_PATH_NOT_COVERED && reqp->tidPathp && reqp->relPathp)
1838 cm_VolStatus_Notify_DFS_Mapping(linkScp, reqp->tidPathp, reqp->relPathp);
1842 lock_ReleaseMutex(&linkScp->mx);
1845 #ifdef DEBUG_REFCOUNT
1846 long cm_NameIDbg(cm_scache_t *rootSCachep, char *pathp, long flags,
1847 cm_user_t *userp, char *tidPathp, cm_req_t *reqp, cm_scache_t **outScpp,
1848 char * file, long line)
1850 long cm_NameI(cm_scache_t *rootSCachep, char *pathp, long flags,
1851 cm_user_t *userp, char *tidPathp, cm_req_t *reqp, cm_scache_t **outScpp)
1855 char *tp; /* ptr moving through input buffer */
1856 char tc; /* temp char */
1857 int haveComponent; /* has new component started? */
1858 char component[AFSPATHMAX]; /* this is the new component */
1859 char *cp; /* component name being assembled */
1860 cm_scache_t *tscp; /* current location in the hierarchy */
1861 cm_scache_t *nscp; /* next dude down */
1862 cm_scache_t *dirScp; /* last dir we searched */
1863 cm_scache_t *linkScp; /* new root for the symlink we just
1865 cm_space_t *psp; /* space for current path, if we've hit
1867 cm_space_t *tempsp; /* temp vbl */
1868 char *restp; /* rest of the pathname to interpret */
1869 int symlinkCount; /* count of # of symlinks traversed */
1870 int extraFlag; /* avoid chasing mt pts for dir cmd */
1871 int phase = 1; /* 1 = tidPathp, 2 = pathp */
1872 #define MAX_FID_COUNT 512
1873 cm_fid_t fids[MAX_FID_COUNT]; /* array of fids processed in this path walk */
1874 int fid_count = 0; /* number of fids processed in this path walk */
1877 #ifdef DEBUG_REFCOUNT
1878 afsi_log("%s:%d cm_NameI rootscp 0x%p ref %d", file, line, rootSCachep, rootSCachep->refCount);
1879 osi_Log4(afsd_logp,"cm_NameI rootscp 0x%p path %s tidpath %s flags 0x%x",
1880 rootSCachep, pathp ? pathp : "<NULL>", tidPathp ? tidPathp : "<NULL>",
1895 cm_HoldSCache(tscp);
1903 /* map Unix slashes into DOS ones so we can interpret Unix
1909 if (!haveComponent) {
1912 } else if (tc == 0) {
1926 /* we have a component here */
1927 if (tc == 0 || tc == '\\') {
1928 /* end of the component; we're at the last
1929 * component if tc == 0. However, if the last
1930 * is a symlink, we have more to do.
1932 *cp++ = 0; /* add null termination */
1934 if ((flags & CM_FLAG_DIRSEARCH) && tc == 0)
1935 extraFlag = CM_FLAG_NOMOUNTCHASE;
1936 code = cm_Lookup(tscp, component,
1938 userp, reqp, &nscp);
1941 if (!strcmp(component,"..") || !strcmp(component,".")) {
1943 * roll back the fid list until we find the fid
1944 * that matches where we are now. Its not necessarily
1945 * one or two fids because they might have been
1946 * symlinks or mount points or both that were crossed.
1948 for ( i=fid_count-1; i>=0; i--) {
1949 if (!cm_FidCmp(&nscp->fid, &fids[i]))
1954 /* add the new fid to the list */
1955 for ( i=0; i<fid_count; i++) {
1956 if ( !cm_FidCmp(&nscp->fid, &fids[i]) ) {
1957 code = CM_ERROR_TOO_MANY_SYMLINKS;
1958 cm_ReleaseSCache(nscp);
1963 if (i == fid_count && fid_count < MAX_FID_COUNT) {
1964 fids[fid_count++] = nscp->fid;
1970 cm_ReleaseSCache(tscp);
1972 cm_ReleaseSCache(dirScp);
1975 if ((code == CM_ERROR_NOSUCHFILE || code == CM_ERROR_BPLUS_NOMATCH) &&
1976 tscp->fileType == CM_SCACHETYPE_SYMLINK)
1978 osi_Log0(afsd_logp,"cm_NameI code CM_ERROR_NOSUCHPATH");
1979 return CM_ERROR_NOSUCHPATH;
1981 osi_Log1(afsd_logp,"cm_NameI code 0x%x", code);
1986 haveComponent = 0; /* component done */
1988 cm_ReleaseSCache(dirScp);
1989 dirScp = tscp; /* for some symlinks */
1990 tscp = nscp; /* already held */
1992 if (tc == 0 && !(flags & CM_FLAG_FOLLOW) && phase == 2) {
1995 cm_ReleaseSCache(dirScp);
2001 /* now, if tscp is a symlink, we should follow
2002 * it and assemble the path again.
2004 lock_ObtainMutex(&tscp->mx);
2005 code = cm_SyncOp(tscp, NULL, userp, reqp, 0,
2006 CM_SCACHESYNC_GETSTATUS
2007 | CM_SCACHESYNC_NEEDCALLBACK);
2009 lock_ReleaseMutex(&tscp->mx);
2010 cm_ReleaseSCache(tscp);
2013 cm_ReleaseSCache(dirScp);
2018 cm_SyncOpDone(tscp, NULL, CM_SCACHESYNC_NEEDCALLBACK | CM_SCACHESYNC_GETSTATUS);
2020 if (tscp->fileType == CM_SCACHETYPE_SYMLINK) {
2021 /* this is a symlink; assemble a new buffer */
2022 lock_ReleaseMutex(&tscp->mx);
2023 if (symlinkCount++ >= MAX_SYMLINK_COUNT) {
2024 cm_ReleaseSCache(tscp);
2027 cm_ReleaseSCache(dirScp);
2032 osi_Log0(afsd_logp,"cm_NameI code CM_ERROR_TOO_MANY_SYMLINKS");
2033 return CM_ERROR_TOO_MANY_SYMLINKS;
2039 code = cm_AssembleLink(tscp, restp, &linkScp, &tempsp, userp, reqp);
2041 if (code == 0 && linkScp != NULL) {
2042 if (linkScp == cm_data.rootSCachep)
2045 for ( i=0; i<fid_count; i++) {
2046 if ( !cm_FidCmp(&linkScp->fid, &fids[i]) ) {
2047 code = CM_ERROR_TOO_MANY_SYMLINKS;
2048 cm_ReleaseSCache(linkScp);
2054 if (i == fid_count && fid_count < MAX_FID_COUNT) {
2055 fids[fid_count++] = linkScp->fid;
2060 /* something went wrong */
2061 cm_ReleaseSCache(tscp);
2064 cm_ReleaseSCache(dirScp);
2070 /* otherwise, tempsp has the new path,
2071 * and linkScp is the new root from
2072 * which to interpret that path.
2073 * Continue with the namei processing,
2074 * also doing the bookkeeping for the
2075 * space allocation and tracking the
2076 * vnode reference counts.
2082 cm_ReleaseSCache(tscp);
2087 * now, if linkScp is null, that's
2088 * AssembleLink's way of telling us that
2089 * the sym link is relative to the dir
2090 * containing the link. We have a ref
2091 * to it in dirScp, and we hold it now
2092 * and reuse it as the new spot in the
2100 /* not a symlink, we may be done */
2101 lock_ReleaseMutex(&tscp->mx);
2109 cm_ReleaseSCache(dirScp);
2117 cm_ReleaseSCache(dirScp);
2120 } /* end of a component */
2123 } /* we have a component */
2124 } /* big while loop over all components */
2128 cm_ReleaseSCache(dirScp);
2134 cm_ReleaseSCache(tscp);
2136 #ifdef DEBUG_REFCOUNT
2137 afsi_log("%s:%d cm_NameI code 0x%x outScpp 0x%p ref %d", file, line, code, *outScpp, (*outScpp)->refCount);
2139 osi_Log2(afsd_logp,"cm_NameI code 0x%x outScpp 0x%p", code, *outScpp);
2143 /* called with a dir, and a vnode within the dir that happens to be a symlink.
2144 * We chase the link, and return a held pointer to the target, if it exists,
2145 * in *outScpp. If we succeed, we return 0, otherwise we return an error code
2146 * and do not hold or return a target vnode.
2148 * This is very similar to calling cm_NameI with the last component of a name,
2149 * which happens to be a symlink, except that we've already passed by the name.
2151 * This function is typically called by the directory listing functions, which
2152 * encounter symlinks but need to return the proper file length so programs
2153 * like "more" work properly when they make use of the attributes retrieved from
2156 * The input vnode should not be locked when this function is called.
2158 long cm_EvaluateSymLink(cm_scache_t *dscp, cm_scache_t *linkScp,
2159 cm_scache_t **outScpp, cm_user_t *userp, cm_req_t *reqp)
2163 cm_scache_t *newRootScp;
2165 osi_Log1(afsd_logp, "Evaluating symlink scp 0x%p", linkScp);
2167 code = cm_AssembleLink(linkScp, "", &newRootScp, &spacep, userp, reqp);
2171 /* now, if newRootScp is NULL, we're really being told that the symlink
2172 * is relative to the current directory (dscp).
2174 if (newRootScp == NULL) {
2176 cm_HoldSCache(dscp);
2179 code = cm_NameI(newRootScp, spacep->data,
2180 CM_FLAG_CASEFOLD | CM_FLAG_FOLLOW | CM_FLAG_DIRSEARCH,
2181 userp, NULL, reqp, outScpp);
2183 if (code == CM_ERROR_NOSUCHFILE || code == CM_ERROR_BPLUS_NOMATCH)
2184 code = CM_ERROR_NOSUCHPATH;
2186 /* this stuff is allocated no matter what happened on the namei call,
2188 cm_FreeSpace(spacep);
2189 cm_ReleaseSCache(newRootScp);
2191 if (linkScp == *outScpp) {
2192 cm_ReleaseSCache(*outScpp);
2194 code = CM_ERROR_NOSUCHPATH;
2200 /* make this big enough so that one buffer of dir pages won't overflow. We'll
2201 * check anyway, but we want to minimize the chance that we have to leave stuff
2204 #define CM_BULKMAX (3 * AFSCBMAX)
2206 /* rock for bulk stat calls */
2207 typedef struct cm_bulkStat {
2208 osi_hyper_t bufOffset; /* only do it for things in this buffer page */
2210 /* info for the actual call */
2211 int counter; /* next free slot */
2212 AFSFid fids[CM_BULKMAX];
2213 AFSFetchStatus stats[CM_BULKMAX];
2214 AFSCallBack callbacks[CM_BULKMAX];
2217 /* for a given entry, make sure that it isn't in the stat cache, and then
2218 * add it to the list of file IDs to be obtained.
2220 * Don't bother adding it if we already have a vnode. Note that the dir
2221 * is locked, so we have to be careful checking the vnode we're thinking of
2222 * processing, to avoid deadlocks.
2224 long cm_TryBulkProc(cm_scache_t *scp, cm_dirEntry_t *dep, void *rockp,
2235 /* Don't overflow bsp. */
2236 if (bsp->counter >= CM_BULKMAX)
2237 return CM_ERROR_STOPNOW;
2239 thyper.LowPart = cm_data.buf_blockSize;
2240 thyper.HighPart = 0;
2241 thyper = LargeIntegerAdd(thyper, bsp->bufOffset);
2243 /* thyper is now the first byte past the end of the record we're
2244 * interested in, and bsp->bufOffset is the first byte of the record
2245 * we're interested in.
2246 * Skip data in the others.
2249 if (LargeIntegerLessThan(*offp, bsp->bufOffset))
2251 if (LargeIntegerGreaterThanOrEqualTo(*offp, thyper))
2252 return CM_ERROR_STOPNOW;
2253 if (strcmp(dep->name, ".") == 0 || strcmp(dep->name, "..") == 0)
2256 cm_SetFid(&tfid, scp->fid.cell, scp->fid.volume, ntohl(dep->fid.vnode), ntohl(dep->fid.unique));
2257 tscp = cm_FindSCache(&tfid);
2259 if (lock_TryMutex(&tscp->mx)) {
2260 /* we have an entry that we can look at */
2261 if (!(tscp->flags & CM_SCACHEFLAG_EACCESS) && cm_HaveCallback(tscp)) {
2262 /* we have a callback on it. Don't bother
2263 * fetching this stat entry, since we're happy
2264 * with the info we have.
2266 lock_ReleaseMutex(&tscp->mx);
2267 cm_ReleaseSCache(tscp);
2270 lock_ReleaseMutex(&tscp->mx);
2272 cm_ReleaseSCache(tscp);
2275 #ifdef AFS_FREELANCE_CLIENT
2276 // yj: if this is a mountpoint under root.afs then we don't want it
2277 // to be bulkstat-ed, instead, we call getSCache directly and under
2278 // getSCache, it is handled specially.
2279 if ( cm_freelanceEnabled &&
2280 tfid.cell==AFS_FAKE_ROOT_CELL_ID &&
2281 tfid.volume==AFS_FAKE_ROOT_VOL_ID &&
2282 !(tfid.vnode==0x1 && tfid.unique==0x1) )
2284 osi_Log0(afsd_logp, "cm_TryBulkProc Freelance calls cm_SCache on root.afs mountpoint");
2285 return cm_GetSCache(&tfid, &tscp, NULL, NULL);
2287 #endif /* AFS_FREELANCE_CLIENT */
2290 bsp->fids[i].Volume = scp->fid.volume;
2291 bsp->fids[i].Vnode = tfid.vnode;
2292 bsp->fids[i].Unique = tfid.unique;
2296 /* called with a locked scp and a pointer to a buffer. Make bulk stat
2297 * calls on all undeleted files in the page of the directory specified.
2300 cm_TryBulkStat(cm_scache_t *dscp, osi_hyper_t *offsetp, cm_user_t *userp,
2304 cm_bulkStat_t bb; /* this is *BIG*, probably 16K or so;
2305 * watch for stack problems */
2306 AFSCBFids fidStruct;
2307 AFSBulkStats statStruct;
2309 AFSCBs callbackStruct;
2312 cm_callbackRequest_t cbReq;
2318 struct rx_connection * callp;
2319 int inlinebulk = 0; /* Did we use InlineBulkStatus RPC or not? */
2321 osi_Log1(afsd_logp, "cm_TryBulkStat dir 0x%p", dscp);
2323 /* should be on a buffer boundary */
2324 osi_assertx((offsetp->LowPart & (cm_data.buf_blockSize - 1)) == 0, "invalid offset");
2326 memset(&bb, 0, sizeof(bb));
2327 bb.bufOffset = *offsetp;
2329 lock_ReleaseMutex(&dscp->mx);
2330 /* first, assemble the file IDs we need to stat */
2331 code = cm_ApplyDir(dscp, cm_TryBulkProc, (void *) &bb, offsetp, userp, reqp, NULL);
2333 /* if we failed, bail out early */
2334 if (code && code != CM_ERROR_STOPNOW) {
2335 lock_ObtainMutex(&dscp->mx);
2339 /* otherwise, we may have one or more bulk stat's worth of stuff in bb;
2340 * make the calls to create the entries. Handle AFSCBMAX files at a
2344 while (filex < bb.counter) {
2345 filesThisCall = bb.counter - filex;
2346 if (filesThisCall > AFSCBMAX)
2347 filesThisCall = AFSCBMAX;
2349 fidStruct.AFSCBFids_len = filesThisCall;
2350 fidStruct.AFSCBFids_val = &bb.fids[filex];
2351 statStruct.AFSBulkStats_len = filesThisCall;
2352 statStruct.AFSBulkStats_val = &bb.stats[filex];
2353 callbackStruct.AFSCBs_len = filesThisCall;
2354 callbackStruct.AFSCBs_val = &bb.callbacks[filex];
2355 cm_StartCallbackGrantingCall(NULL, &cbReq);
2356 osi_Log1(afsd_logp, "CALL BulkStatus, %d entries", filesThisCall);
2358 code = cm_ConnFromFID(&dscp->fid, userp, reqp, &connp);
2362 callp = cm_GetRxConn(connp);
2363 if (!(connp->serverp->flags & CM_SERVERFLAG_NOINLINEBULK)) {
2364 code = RXAFS_InlineBulkStatus(callp, &fidStruct,
2365 &statStruct, &callbackStruct, &volSync);
2366 if (code == RXGEN_OPCODE) {
2367 cm_SetServerNoInlineBulk(connp->serverp, 0);
2373 code = RXAFS_BulkStatus(callp, &fidStruct,
2374 &statStruct, &callbackStruct, &volSync);
2376 rx_PutConnection(callp);
2378 } while (cm_Analyze(connp, userp, reqp, &dscp->fid,
2379 &volSync, NULL, &cbReq, code));
2380 code = cm_MapRPCError(code, reqp);
2382 osi_Log2(afsd_logp, "CALL %sBulkStatus FAILURE code 0x%x",
2383 inlinebulk ? "Inline" : "", code);
2385 osi_Log1(afsd_logp, "CALL %sBulkStatus SUCCESS", inlinebulk ? "Inline" : "");
2387 /* may as well quit on an error, since we're not going to do
2388 * much better on the next immediate call, either.
2391 cm_EndCallbackGrantingCall(NULL, &cbReq, NULL, 0);
2395 /* otherwise, we should do the merges */
2396 for (i = 0; i<filesThisCall; i++) {
2398 cm_SetFid(&tfid, dscp->fid.cell, bb.fids[j].Volume, bb.fids[j].Vnode, bb.fids[j].Unique);
2399 code = cm_GetSCache(&tfid, &scp, userp, reqp);
2403 /* otherwise, if this entry has no callback info,
2406 lock_ObtainMutex(&scp->mx);
2407 /* now, we have to be extra paranoid on merging in this
2408 * information, since we didn't use cm_SyncOp before
2409 * starting the fetch to make sure that no bad races
2410 * were occurring. Specifically, we need to make sure
2411 * we don't obliterate any newer information in the
2412 * vnode than have here.
2414 * Right now, be pretty conservative: if there's a
2415 * callback or a pending call, skip it.
2417 if ((scp->cbServerp == NULL || (scp->flags & CM_SCACHEFLAG_EACCESS))
2419 (CM_SCACHEFLAG_FETCHING
2420 | CM_SCACHEFLAG_STORING
2421 | CM_SCACHEFLAG_SIZESTORING))) {
2422 cm_EndCallbackGrantingCall(scp, &cbReq,
2424 CM_CALLBACK_MAINTAINCOUNT);
2425 cm_MergeStatus(dscp, scp, &bb.stats[j], &volSync, userp, 0);
2427 lock_ReleaseMutex(&scp->mx);
2428 cm_ReleaseSCache(scp);
2429 } /* all files in the response */
2430 /* now tell it to drop the count,
2431 * after doing the vnode processing above */
2432 cm_EndCallbackGrantingCall(NULL, &cbReq, NULL, 0);
2434 filex += filesThisCall;
2435 } /* while there are still more files to process */
2436 lock_ObtainMutex(&dscp->mx);
2438 /* If we did the InlineBulk RPC pull out the return code and log it */
2440 if ((&bb.stats[0])->errorCode) {
2441 osi_Log1(afsd_logp, "cm_TryBulkStat bulk stat error: %d",
2442 (&bb.stats[0])->errorCode);
2446 osi_Log0(afsd_logp, "END cm_TryBulkStat");
2450 void cm_StatusFromAttr(AFSStoreStatus *statusp, cm_scache_t *scp, cm_attr_t *attrp)
2454 /* initialize store back mask as inexpensive local variable */
2456 memset(statusp, 0, sizeof(AFSStoreStatus));
2458 /* copy out queued info from scache first, if scp passed in */
2460 if (scp->mask & CM_SCACHEMASK_CLIENTMODTIME) {
2461 statusp->ClientModTime = scp->clientModTime;
2462 mask |= AFS_SETMODTIME;
2463 scp->mask &= ~CM_SCACHEMASK_CLIENTMODTIME;
2468 /* now add in our locally generated request */
2469 if (attrp->mask & CM_ATTRMASK_CLIENTMODTIME) {
2470 statusp->ClientModTime = attrp->clientModTime;
2471 mask |= AFS_SETMODTIME;
2473 if (attrp->mask & CM_ATTRMASK_UNIXMODEBITS) {
2474 statusp->UnixModeBits = attrp->unixModeBits;
2475 mask |= AFS_SETMODE;
2477 if (attrp->mask & CM_ATTRMASK_OWNER) {
2478 statusp->Owner = attrp->owner;
2479 mask |= AFS_SETOWNER;
2481 if (attrp->mask & CM_ATTRMASK_GROUP) {
2482 statusp->Group = attrp->group;
2483 mask |= AFS_SETGROUP;
2486 statusp->Mask = mask;
2489 /* set the file size, and make sure that all relevant buffers have been
2490 * truncated. Ensure that any partially truncated buffers have been zeroed
2491 * to the end of the buffer.
2493 long cm_SetLength(cm_scache_t *scp, osi_hyper_t *sizep, cm_user_t *userp,
2499 /* start by locking out buffer creation */
2500 lock_ObtainWrite(&scp->bufCreateLock);
2502 /* verify that this is a file, not a dir or a symlink */
2503 lock_ObtainMutex(&scp->mx);
2504 code = cm_SyncOp(scp, NULL, userp, reqp, 0,
2505 CM_SCACHESYNC_NEEDCALLBACK | CM_SCACHESYNC_GETSTATUS);
2508 cm_SyncOpDone(scp, NULL, CM_SCACHESYNC_NEEDCALLBACK | CM_SCACHESYNC_GETSTATUS);
2510 if (scp->fileType != CM_SCACHETYPE_FILE) {
2511 code = CM_ERROR_ISDIR;
2516 if (LargeIntegerLessThan(*sizep, scp->length))
2521 lock_ReleaseMutex(&scp->mx);
2523 /* can't hold scp->mx lock here, since we may wait for a storeback to
2524 * finish if the buffer package is cleaning a buffer by storing it to
2528 buf_Truncate(scp, userp, reqp, sizep);
2530 /* now ensure that file length is short enough, and update truncPos */
2531 lock_ObtainMutex(&scp->mx);
2533 /* make sure we have a callback (so we have the right value for the
2534 * length), and wait for it to be safe to do a truncate.
2536 code = cm_SyncOp(scp, NULL, userp, reqp, PRSFS_WRITE,
2537 CM_SCACHESYNC_NEEDCALLBACK | CM_SCACHESYNC_GETSTATUS
2538 | CM_SCACHESYNC_SETSTATUS | CM_SCACHESYNC_SETSIZE);
2540 /* If we only have 'i' bits, then we should still be able to set
2541 the size of a file we created. */
2542 if (code == CM_ERROR_NOACCESS && scp->creator == userp) {
2543 code = cm_SyncOp(scp, NULL, userp, reqp, PRSFS_INSERT,
2544 CM_SCACHESYNC_NEEDCALLBACK | CM_SCACHESYNC_GETSTATUS
2545 | CM_SCACHESYNC_SETSTATUS | CM_SCACHESYNC_SETSIZE);
2551 if (LargeIntegerLessThan(*sizep, scp->length)) {
2552 /* a real truncation. If truncPos is not set yet, or is bigger
2553 * than where we're truncating the file, set truncPos to this
2558 if (!(scp->mask & CM_SCACHEMASK_TRUNCPOS)
2559 || LargeIntegerLessThan(*sizep, scp->length)) {
2561 scp->truncPos = *sizep;
2562 scp->mask |= CM_SCACHEMASK_TRUNCPOS;
2564 /* in either case, the new file size has been changed */
2565 scp->length = *sizep;
2566 scp->mask |= CM_SCACHEMASK_LENGTH;
2568 else if (LargeIntegerGreaterThan(*sizep, scp->length)) {
2569 /* really extending the file */
2570 scp->length = *sizep;
2571 scp->mask |= CM_SCACHEMASK_LENGTH;
2574 /* done successfully */
2577 cm_SyncOpDone(scp, NULL,
2578 CM_SCACHESYNC_NEEDCALLBACK | CM_SCACHESYNC_GETSTATUS
2579 | CM_SCACHESYNC_SETSTATUS | CM_SCACHESYNC_SETSIZE);
2582 lock_ReleaseMutex(&scp->mx);
2583 lock_ReleaseWrite(&scp->bufCreateLock);
2588 /* set the file size or other attributes (but not both at once) */
2589 long cm_SetAttr(cm_scache_t *scp, cm_attr_t *attrp, cm_user_t *userp,
2593 AFSFetchStatus afsOutStatus;
2597 AFSStoreStatus afsInStatus;
2598 struct rx_connection * callp;
2600 /* handle file length setting */
2601 if (attrp->mask & CM_ATTRMASK_LENGTH)
2602 return cm_SetLength(scp, &attrp->length, userp, reqp);
2604 lock_ObtainMutex(&scp->mx);
2605 /* otherwise, we have to make an RPC to get the status */
2606 code = cm_SyncOp(scp, NULL, userp, reqp, 0, CM_SCACHESYNC_STORESTATUS);
2608 lock_ReleaseMutex(&scp->mx);
2612 /* make the attr structure */
2613 cm_StatusFromAttr(&afsInStatus, scp, attrp);
2615 tfid.Volume = scp->fid.volume;
2616 tfid.Vnode = scp->fid.vnode;
2617 tfid.Unique = scp->fid.unique;
2618 lock_ReleaseMutex(&scp->mx);
2620 /* now make the RPC */
2621 osi_Log1(afsd_logp, "CALL StoreStatus scp 0x%p", scp);
2623 code = cm_ConnFromFID(&scp->fid, userp, reqp, &connp);
2627 callp = cm_GetRxConn(connp);
2628 code = RXAFS_StoreStatus(callp, &tfid,
2629 &afsInStatus, &afsOutStatus, &volSync);
2630 rx_PutConnection(callp);
2632 } while (cm_Analyze(connp, userp, reqp,
2633 &scp->fid, &volSync, NULL, NULL, code));
2634 code = cm_MapRPCError(code, reqp);
2637 osi_Log1(afsd_logp, "CALL StoreStatus FAILURE, code 0x%x", code);
2639 osi_Log0(afsd_logp, "CALL StoreStatus SUCCESS");
2641 lock_ObtainMutex(&scp->mx);
2642 cm_SyncOpDone(scp, NULL, CM_SCACHESYNC_STORESTATUS);
2644 cm_MergeStatus(NULL, scp, &afsOutStatus, &volSync, userp,
2645 CM_MERGEFLAG_FORCE|CM_MERGEFLAG_STOREDATA);
2647 /* if we're changing the mode bits, discard the ACL cache,
2648 * since we changed the mode bits.
2650 if (afsInStatus.Mask & AFS_SETMODE)
2651 cm_FreeAllACLEnts(scp);
2652 lock_ReleaseMutex(&scp->mx);
2656 long cm_Create(cm_scache_t *dscp, char *namep, long flags, cm_attr_t *attrp,
2657 cm_scache_t **scpp, cm_user_t *userp, cm_req_t *reqp)
2662 cm_callbackRequest_t cbReq;
2665 cm_scache_t *scp = NULL;
2667 AFSStoreStatus inStatus;
2668 AFSFetchStatus updatedDirStatus;
2669 AFSFetchStatus newFileStatus;
2670 AFSCallBack newFileCallback;
2672 struct rx_connection * callp;
2675 /* can't create names with @sys in them; must expand it manually first.
2676 * return "invalid request" if they try.
2678 if (cm_ExpandSysName(namep, NULL, 0, 0)) {
2679 return CM_ERROR_ATSYS;
2682 #ifdef AFS_FREELANCE_CLIENT
2683 /* Freelance root volume does not hold files */
2684 if (cm_freelanceEnabled &&
2685 dscp->fid.cell==AFS_FAKE_ROOT_CELL_ID &&
2686 dscp->fid.volume==AFS_FAKE_ROOT_VOL_ID )
2688 return CM_ERROR_NOACCESS;
2690 #endif /* AFS_FREELANCE_CLIENT */
2692 /* before starting the RPC, mark that we're changing the file data, so
2693 * that someone who does a chmod will know to wait until our call
2696 cm_BeginDirOp(dscp, userp, reqp, CM_DIRLOCK_NONE, &dirop);
2697 lock_ObtainMutex(&dscp->mx);
2698 code = cm_SyncOp(dscp, NULL, userp, reqp, 0, CM_SCACHESYNC_STOREDATA);
2699 lock_ReleaseMutex(&dscp->mx);
2701 cm_StartCallbackGrantingCall(NULL, &cbReq);
2703 cm_EndDirOp(&dirop);
2710 cm_StatusFromAttr(&inStatus, NULL, attrp);
2712 /* try the RPC now */
2713 osi_Log1(afsd_logp, "CALL CreateFile scp 0x%p", dscp);
2715 code = cm_ConnFromFID(&dscp->fid, userp, reqp, &connp);
2719 dirAFSFid.Volume = dscp->fid.volume;
2720 dirAFSFid.Vnode = dscp->fid.vnode;
2721 dirAFSFid.Unique = dscp->fid.unique;
2723 callp = cm_GetRxConn(connp);
2724 code = RXAFS_CreateFile(connp->callp, &dirAFSFid, namep,
2725 &inStatus, &newAFSFid, &newFileStatus,
2726 &updatedDirStatus, &newFileCallback,
2728 rx_PutConnection(callp);
2730 } while (cm_Analyze(connp, userp, reqp,
2731 &dscp->fid, &volSync, NULL, &cbReq, code));
2732 code = cm_MapRPCError(code, reqp);
2735 osi_Log1(afsd_logp, "CALL CreateFile FAILURE, code 0x%x", code);
2737 osi_Log0(afsd_logp, "CALL CreateFile SUCCESS");
2740 lock_ObtainWrite(&dirop.scp->dirlock);
2741 dirop.lockType = CM_DIRLOCK_WRITE;
2743 lock_ObtainMutex(&dscp->mx);
2744 cm_SyncOpDone(dscp, NULL, CM_SCACHESYNC_STOREDATA);
2746 cm_MergeStatus(NULL, dscp, &updatedDirStatus, &volSync, userp, CM_MERGEFLAG_DIROP);
2748 lock_ReleaseMutex(&dscp->mx);
2750 /* now try to create the file's entry, too, but be careful to
2751 * make sure that we don't merge in old info. Since we weren't locking
2752 * out any requests during the file's creation, we may have pretty old
2756 cm_SetFid(&newFid, dscp->fid.cell, dscp->fid.volume, newAFSFid.Vnode, newAFSFid.Unique);
2757 code = cm_GetSCache(&newFid, &scp, userp, reqp);
2759 lock_ObtainMutex(&scp->mx);
2760 scp->creator = userp; /* remember who created it */
2761 if (!cm_HaveCallback(scp)) {
2762 cm_MergeStatus(dscp, scp, &newFileStatus, &volSync,
2764 cm_EndCallbackGrantingCall(scp, &cbReq,
2765 &newFileCallback, 0);
2768 lock_ReleaseMutex(&scp->mx);
2773 /* make sure we end things properly */
2775 cm_EndCallbackGrantingCall(NULL, &cbReq, NULL, 0);
2777 if (scp && cm_CheckDirOpForSingleChange(&dirop)) {
2778 cm_DirCreateEntry(&dirop, namep, &newFid);
2780 cm_BPlusDirCreateEntry(&dirop, namep, &newFid);
2783 cm_EndDirOp(&dirop);
2788 long cm_FSync(cm_scache_t *scp, cm_user_t *userp, cm_req_t *reqp)
2792 code = buf_CleanVnode(scp, userp, reqp);
2794 lock_ObtainMutex(&scp->mx);
2796 if (scp->mask & (CM_SCACHEMASK_TRUNCPOS
2797 | CM_SCACHEMASK_CLIENTMODTIME
2798 | CM_SCACHEMASK_LENGTH))
2799 code = cm_StoreMini(scp, userp, reqp);
2801 if (scp->flags & (CM_SCACHEFLAG_OVERQUOTA | CM_SCACHEFLAG_OUTOFSPACE)) {
2802 code = (scp->flags & CM_SCACHEFLAG_OVERQUOTA) ? CM_ERROR_QUOTA : CM_ERROR_SPACE;
2803 scp->flags &= ~(CM_SCACHEFLAG_OVERQUOTA | CM_SCACHEFLAG_OUTOFSPACE);
2806 lock_ReleaseMutex(&scp->mx);
2811 long cm_MakeDir(cm_scache_t *dscp, char *namep, long flags, cm_attr_t *attrp,
2812 cm_user_t *userp, cm_req_t *reqp)
2817 cm_callbackRequest_t cbReq;
2820 cm_scache_t *scp = NULL;
2822 AFSStoreStatus inStatus;
2823 AFSFetchStatus updatedDirStatus;
2824 AFSFetchStatus newDirStatus;
2825 AFSCallBack newDirCallback;
2827 struct rx_connection * callp;
2830 /* can't create names with @sys in them; must expand it manually first.
2831 * return "invalid request" if they try.
2833 if (cm_ExpandSysName(namep, NULL, 0, 0)) {
2834 return CM_ERROR_ATSYS;
2837 #ifdef AFS_FREELANCE_CLIENT
2838 /* Freelance root volume does not hold subdirectories */
2839 if (cm_freelanceEnabled &&
2840 dscp->fid.cell==AFS_FAKE_ROOT_CELL_ID &&
2841 dscp->fid.volume==AFS_FAKE_ROOT_VOL_ID )
2843 return CM_ERROR_NOACCESS;
2845 #endif /* AFS_FREELANCE_CLIENT */
2847 /* before starting the RPC, mark that we're changing the directory
2848 * data, so that someone who does a chmod on the dir will wait until
2849 * our call completes.
2851 cm_BeginDirOp(dscp, userp, reqp, CM_DIRLOCK_NONE, &dirop);
2852 lock_ObtainMutex(&dscp->mx);
2853 code = cm_SyncOp(dscp, NULL, userp, reqp, 0, CM_SCACHESYNC_STOREDATA);
2854 lock_ReleaseMutex(&dscp->mx);
2856 cm_StartCallbackGrantingCall(NULL, &cbReq);
2858 cm_EndDirOp(&dirop);
2865 cm_StatusFromAttr(&inStatus, NULL, attrp);
2867 /* try the RPC now */
2868 osi_Log1(afsd_logp, "CALL MakeDir scp 0x%p", dscp);
2870 code = cm_ConnFromFID(&dscp->fid, userp, reqp, &connp);
2874 dirAFSFid.Volume = dscp->fid.volume;
2875 dirAFSFid.Vnode = dscp->fid.vnode;
2876 dirAFSFid.Unique = dscp->fid.unique;
2878 callp = cm_GetRxConn(connp);
2879 code = RXAFS_MakeDir(connp->callp, &dirAFSFid, namep,
2880 &inStatus, &newAFSFid, &newDirStatus,
2881 &updatedDirStatus, &newDirCallback,
2883 rx_PutConnection(callp);
2885 } while (cm_Analyze(connp, userp, reqp,
2886 &dscp->fid, &volSync, NULL, &cbReq, code));
2887 code = cm_MapRPCError(code, reqp);
2890 osi_Log1(afsd_logp, "CALL MakeDir FAILURE, code 0x%x", code);
2892 osi_Log0(afsd_logp, "CALL MakeDir SUCCESS");
2895 lock_ObtainWrite(&dirop.scp->dirlock);
2896 dirop.lockType = CM_DIRLOCK_WRITE;
2898 lock_ObtainMutex(&dscp->mx);
2899 cm_SyncOpDone(dscp, NULL, CM_SCACHESYNC_STOREDATA);
2901 cm_MergeStatus(NULL, dscp, &updatedDirStatus, &volSync, userp, CM_MERGEFLAG_DIROP);
2903 lock_ReleaseMutex(&dscp->mx);
2905 /* now try to create the new dir's entry, too, but be careful to
2906 * make sure that we don't merge in old info. Since we weren't locking
2907 * out any requests during the file's creation, we may have pretty old
2911 cm_SetFid(&newFid, dscp->fid.cell, dscp->fid.volume, newAFSFid.Vnode, newAFSFid.Unique);
2912 code = cm_GetSCache(&newFid, &scp, userp, reqp);
2914 lock_ObtainMutex(&scp->mx);
2915 if (!cm_HaveCallback(scp)) {
2916 cm_MergeStatus(dscp, scp, &newDirStatus, &volSync,
2918 cm_EndCallbackGrantingCall(scp, &cbReq,
2919 &newDirCallback, 0);
2922 lock_ReleaseMutex(&scp->mx);
2923 cm_ReleaseSCache(scp);
2927 /* make sure we end things properly */
2929 cm_EndCallbackGrantingCall(NULL, &cbReq, NULL, 0);
2931 if (scp && cm_CheckDirOpForSingleChange(&dirop)) {
2932 cm_DirCreateEntry(&dirop, namep, &newFid);
2934 cm_BPlusDirCreateEntry(&dirop, namep, &newFid);
2937 cm_EndDirOp(&dirop);
2939 /* and return error code */
2943 long cm_Link(cm_scache_t *dscp, char *namep, cm_scache_t *sscp, long flags,
2944 cm_user_t *userp, cm_req_t *reqp)
2949 AFSFid existingAFSFid;
2950 AFSFetchStatus updatedDirStatus;
2951 AFSFetchStatus newLinkStatus;
2953 struct rx_connection * callp;
2956 if (dscp->fid.cell != sscp->fid.cell ||
2957 dscp->fid.volume != sscp->fid.volume) {
2958 return CM_ERROR_CROSSDEVLINK;
2961 cm_BeginDirOp(dscp, userp, reqp, CM_DIRLOCK_NONE, &dirop);
2962 lock_ObtainMutex(&dscp->mx);
2963 code = cm_SyncOp(dscp, NULL, userp, reqp, 0, CM_SCACHESYNC_STOREDATA);
2964 lock_ReleaseMutex(&dscp->mx);
2966 cm_EndDirOp(&dirop);
2971 /* try the RPC now */
2972 osi_Log1(afsd_logp, "CALL Link scp 0x%p", dscp);
2974 code = cm_ConnFromFID(&dscp->fid, userp, reqp, &connp);
2977 dirAFSFid.Volume = dscp->fid.volume;
2978 dirAFSFid.Vnode = dscp->fid.vnode;
2979 dirAFSFid.Unique = dscp->fid.unique;
2981 existingAFSFid.Volume = sscp->fid.volume;
2982 existingAFSFid.Vnode = sscp->fid.vnode;
2983 existingAFSFid.Unique = sscp->fid.unique;
2985 callp = cm_GetRxConn(connp);
2986 code = RXAFS_Link(callp, &dirAFSFid, namep, &existingAFSFid,
2987 &newLinkStatus, &updatedDirStatus, &volSync);
2988 rx_PutConnection(callp);
2989 osi_Log1(smb_logp," RXAFS_Link returns 0x%x", code);
2991 } while (cm_Analyze(connp, userp, reqp,
2992 &dscp->fid, &volSync, NULL, NULL, code));
2994 code = cm_MapRPCError(code, reqp);
2997 osi_Log1(afsd_logp, "CALL Link FAILURE, code 0x%x", code);
2999 osi_Log0(afsd_logp, "CALL Link SUCCESS");
3002 lock_ObtainWrite(&dirop.scp->dirlock);
3003 dirop.lockType = CM_DIRLOCK_WRITE;
3005 lock_ObtainMutex(&dscp->mx);
3006 cm_SyncOpDone(dscp, NULL, CM_SCACHESYNC_STOREDATA);
3008 cm_MergeStatus(NULL, dscp, &updatedDirStatus, &volSync, userp, CM_MERGEFLAG_DIROP);
3010 lock_ReleaseMutex(&dscp->mx);
3013 if (cm_CheckDirOpForSingleChange(&dirop)) {
3014 cm_DirCreateEntry(&dirop, namep, &sscp->fid);
3016 cm_BPlusDirCreateEntry(&dirop, namep, &sscp->fid);
3020 cm_EndDirOp(&dirop);
3025 long cm_SymLink(cm_scache_t *dscp, char *namep, char *contentsp, long flags,
3026 cm_attr_t *attrp, cm_user_t *userp, cm_req_t *reqp)
3034 AFSStoreStatus inStatus;
3035 AFSFetchStatus updatedDirStatus;
3036 AFSFetchStatus newLinkStatus;
3038 struct rx_connection * callp;
3041 /* before starting the RPC, mark that we're changing the directory data,
3042 * so that someone who does a chmod on the dir will wait until our
3045 cm_BeginDirOp(dscp, userp, reqp, CM_DIRLOCK_NONE, &dirop);
3046 lock_ObtainMutex(&dscp->mx);
3047 code = cm_SyncOp(dscp, NULL, userp, reqp, 0, CM_SCACHESYNC_STOREDATA);
3048 lock_ReleaseMutex(&dscp->mx);
3050 cm_EndDirOp(&dirop);
3055 cm_StatusFromAttr(&inStatus, NULL, attrp);
3057 /* try the RPC now */
3058 osi_Log1(afsd_logp, "CALL Symlink scp 0x%p", dscp);
3060 code = cm_ConnFromFID(&dscp->fid, userp, reqp, &connp);
3064 dirAFSFid.Volume = dscp->fid.volume;
3065 dirAFSFid.Vnode = dscp->fid.vnode;
3066 dirAFSFid.Unique = dscp->fid.unique;
3068 callp = cm_GetRxConn(connp);
3069 code = RXAFS_Symlink(callp, &dirAFSFid, namep, contentsp,
3070 &inStatus, &newAFSFid, &newLinkStatus,
3071 &updatedDirStatus, &volSync);
3072 rx_PutConnection(callp);
3074 } while (cm_Analyze(connp, userp, reqp,
3075 &dscp->fid, &volSync, NULL, NULL, code));
3076 code = cm_MapRPCError(code, reqp);
3079 osi_Log1(afsd_logp, "CALL Symlink FAILURE, code 0x%x", code);
3081 osi_Log0(afsd_logp, "CALL Symlink SUCCESS");
3084 lock_ObtainWrite(&dirop.scp->dirlock);
3085 dirop.lockType = CM_DIRLOCK_WRITE;
3087 lock_ObtainMutex(&dscp->mx);
3088 cm_SyncOpDone(dscp, NULL, CM_SCACHESYNC_STOREDATA);
3090 cm_MergeStatus(NULL, dscp, &updatedDirStatus, &volSync, userp, CM_MERGEFLAG_DIROP);
3092 lock_ReleaseMutex(&dscp->mx);
3095 if (cm_CheckDirOpForSingleChange(&dirop)) {
3096 cm_SetFid(&newFid, dscp->fid.cell, dscp->fid.volume, newAFSFid.Vnode, newAFSFid.Unique);
3098 cm_DirCreateEntry(&dirop, namep, &newFid);
3100 cm_BPlusDirCreateEntry(&dirop, namep, &newFid);
3104 cm_EndDirOp(&dirop);
3106 /* now try to create the new dir's entry, too, but be careful to
3107 * make sure that we don't merge in old info. Since we weren't locking
3108 * out any requests during the file's creation, we may have pretty old
3112 cm_SetFid(&newFid, dscp->fid.cell, dscp->fid.volume, newAFSFid.Vnode, newAFSFid.Unique);
3113 code = cm_GetSCache(&newFid, &scp, userp, reqp);
3115 lock_ObtainMutex(&scp->mx);
3116 if (!cm_HaveCallback(scp)) {
3117 cm_MergeStatus(dscp, scp, &newLinkStatus, &volSync,
3120 lock_ReleaseMutex(&scp->mx);
3121 cm_ReleaseSCache(scp);
3125 /* and return error code */
3129 long cm_RemoveDir(cm_scache_t *dscp, char *namep, cm_user_t *userp,
3136 AFSFetchStatus updatedDirStatus;
3138 struct rx_connection * callp;
3141 /* before starting the RPC, mark that we're changing the directory data,
3142 * so that someone who does a chmod on the dir will wait until our
3145 cm_BeginDirOp(dscp, userp, reqp, CM_DIRLOCK_NONE, &dirop);
3146 lock_ObtainMutex(&dscp->mx);
3147 code = cm_SyncOp(dscp, NULL, userp, reqp, 0, CM_SCACHESYNC_STOREDATA);
3148 lock_ReleaseMutex(&dscp->mx);
3150 cm_EndDirOp(&dirop);
3155 /* try the RPC now */
3156 osi_Log1(afsd_logp, "CALL RemoveDir scp 0x%p", dscp);
3158 code = cm_ConnFromFID(&dscp->fid, userp, reqp, &connp);
3162 dirAFSFid.Volume = dscp->fid.volume;
3163 dirAFSFid.Vnode = dscp->fid.vnode;
3164 dirAFSFid.Unique = dscp->fid.unique;
3166 callp = cm_GetRxConn(connp);
3167 code = RXAFS_RemoveDir(callp, &dirAFSFid, namep,
3168 &updatedDirStatus, &volSync);
3169 rx_PutConnection(callp);
3171 } while (cm_Analyze(connp, userp, reqp,
3172 &dscp->fid, &volSync, NULL, NULL, code));
3173 code = cm_MapRPCErrorRmdir(code, reqp);
3176 osi_Log1(afsd_logp, "CALL RemoveDir FAILURE, code 0x%x", code);
3178 osi_Log0(afsd_logp, "CALL RemoveDir SUCCESS");
3181 lock_ObtainWrite(&dirop.scp->dirlock);
3182 dirop.lockType = CM_DIRLOCK_WRITE;
3184 lock_ObtainMutex(&dscp->mx);
3185 cm_SyncOpDone(dscp, NULL, CM_SCACHESYNC_STOREDATA);
3187 cm_dnlcRemove(dscp, namep);
3188 cm_MergeStatus(NULL, dscp, &updatedDirStatus, &volSync, userp, CM_MERGEFLAG_DIROP);
3190 lock_ReleaseMutex(&dscp->mx);
3193 if (cm_CheckDirOpForSingleChange(&dirop)) {
3194 cm_DirDeleteEntry(&dirop, namep);
3196 cm_BPlusDirDeleteEntry(&dirop, namep);
3200 cm_EndDirOp(&dirop);
3202 /* and return error code */
3206 long cm_Open(cm_scache_t *scp, int type, cm_user_t *userp)
3208 /* grab mutex on contents */
3209 lock_ObtainMutex(&scp->mx);
3211 /* reset the prefetch info */
3212 scp->prefetch.base.LowPart = 0; /* base */
3213 scp->prefetch.base.HighPart = 0;
3214 scp->prefetch.end.LowPart = 0; /* and end */
3215 scp->prefetch.end.HighPart = 0;
3217 /* release mutex on contents */
3218 lock_ReleaseMutex(&scp->mx);
3224 long cm_Rename(cm_scache_t *oldDscp, char *oldNamep, cm_scache_t *newDscp,
3225 char *newNamep, cm_user_t *userp, cm_req_t *reqp)
3229 AFSFid oldDirAFSFid;
3230 AFSFid newDirAFSFid;
3232 AFSFetchStatus updatedOldDirStatus;
3233 AFSFetchStatus updatedNewDirStatus;
3236 struct rx_connection * callp;
3237 cm_dirOp_t oldDirOp;
3240 cm_dirOp_t newDirOp;
3242 /* before starting the RPC, mark that we're changing the directory data,
3243 * so that someone who does a chmod on the dir will wait until our call
3244 * completes. We do this in vnode order so that we don't deadlock,
3245 * which makes the code a little verbose.
3247 if (oldDscp == newDscp) {
3248 /* check for identical names */
3249 if (strcmp(oldNamep, newNamep) == 0)
3250 return CM_ERROR_RENAME_IDENTICAL;
3253 cm_BeginDirOp(oldDscp, userp, reqp, CM_DIRLOCK_NONE, &oldDirOp);
3254 lock_ObtainMutex(&oldDscp->mx);
3255 cm_dnlcRemove(oldDscp, oldNamep);
3256 cm_dnlcRemove(oldDscp, newNamep);
3257 code = cm_SyncOp(oldDscp, NULL, userp, reqp, 0,
3258 CM_SCACHESYNC_STOREDATA);
3259 lock_ReleaseMutex(&oldDscp->mx);
3261 cm_EndDirOp(&oldDirOp);
3265 /* two distinct dir vnodes */
3267 if (oldDscp->fid.cell != newDscp->fid.cell ||
3268 oldDscp->fid.volume != newDscp->fid.volume)
3269 return CM_ERROR_CROSSDEVLINK;
3271 /* shouldn't happen that we have distinct vnodes for two
3272 * different files, but could due to deliberate attack, or
3273 * stale info. Avoid deadlocks and quit now.
3275 if (oldDscp->fid.vnode == newDscp->fid.vnode)
3276 return CM_ERROR_CROSSDEVLINK;
3278 if (oldDscp->fid.vnode < newDscp->fid.vnode) {
3279 cm_BeginDirOp(oldDscp, userp, reqp, CM_DIRLOCK_NONE, &oldDirOp);
3280 lock_ObtainMutex(&oldDscp->mx);
3281 cm_dnlcRemove(oldDscp, oldNamep);
3282 code = cm_SyncOp(oldDscp, NULL, userp, reqp, 0,
3283 CM_SCACHESYNC_STOREDATA);
3284 lock_ReleaseMutex(&oldDscp->mx);
3286 cm_EndDirOp(&oldDirOp);
3288 cm_BeginDirOp(newDscp, userp, reqp, CM_DIRLOCK_NONE, &newDirOp);
3289 lock_ObtainMutex(&newDscp->mx);
3290 cm_dnlcRemove(newDscp, newNamep);
3291 code = cm_SyncOp(newDscp, NULL, userp, reqp, 0,
3292 CM_SCACHESYNC_STOREDATA);
3293 lock_ReleaseMutex(&newDscp->mx);
3295 cm_EndDirOp(&newDirOp);
3297 /* cleanup first one */
3298 lock_ObtainMutex(&oldDscp->mx);
3299 cm_SyncOpDone(oldDscp, NULL,
3300 CM_SCACHESYNC_STOREDATA);
3301 lock_ReleaseMutex(&oldDscp->mx);
3302 cm_EndDirOp(&oldDirOp);
3307 /* lock the new vnode entry first */
3308 cm_BeginDirOp(newDscp, userp, reqp, CM_DIRLOCK_NONE, &newDirOp);
3309 lock_ObtainMutex(&newDscp->mx);
3310 cm_dnlcRemove(newDscp, newNamep);
3311 code = cm_SyncOp(newDscp, NULL, userp, reqp, 0,
3312 CM_SCACHESYNC_STOREDATA);
3313 lock_ReleaseMutex(&newDscp->mx);
3315 cm_EndDirOp(&newDirOp);
3317 cm_BeginDirOp(oldDscp, userp, reqp, CM_DIRLOCK_NONE, &oldDirOp);
3318 lock_ObtainMutex(&oldDscp->mx);
3319 cm_dnlcRemove(oldDscp, oldNamep);
3320 code = cm_SyncOp(oldDscp, NULL, userp, reqp, 0,
3321 CM_SCACHESYNC_STOREDATA);
3322 lock_ReleaseMutex(&oldDscp->mx);
3324 cm_EndDirOp(&oldDirOp);
3326 /* cleanup first one */
3327 lock_ObtainMutex(&newDscp->mx);
3328 cm_SyncOpDone(newDscp, NULL,
3329 CM_SCACHESYNC_STOREDATA);
3330 lock_ReleaseMutex(&newDscp->mx);
3331 cm_EndDirOp(&newDirOp);
3335 } /* two distinct vnodes */
3342 /* try the RPC now */
3343 osi_Log2(afsd_logp, "CALL Rename old scp 0x%p new scp 0x%p",
3346 code = cm_ConnFromFID(&oldDscp->fid, userp, reqp, &connp);
3350 oldDirAFSFid.Volume = oldDscp->fid.volume;
3351 oldDirAFSFid.Vnode = oldDscp->fid.vnode;
3352 oldDirAFSFid.Unique = oldDscp->fid.unique;
3353 newDirAFSFid.Volume = newDscp->fid.volume;
3354 newDirAFSFid.Vnode = newDscp->fid.vnode;
3355 newDirAFSFid.Unique = newDscp->fid.unique;
3357 callp = cm_GetRxConn(connp);
3358 code = RXAFS_Rename(callp, &oldDirAFSFid, oldNamep,
3359 &newDirAFSFid, newNamep,
3360 &updatedOldDirStatus, &updatedNewDirStatus,
3362 rx_PutConnection(callp);
3364 } while (cm_Analyze(connp, userp, reqp, &oldDscp->fid,
3365 &volSync, NULL, NULL, code));
3366 code = cm_MapRPCError(code, reqp);
3369 osi_Log1(afsd_logp, "CALL Rename FAILURE, code 0x%x", code);
3371 osi_Log0(afsd_logp, "CALL Rename SUCCESS");
3373 /* update the individual stat cache entries for the directories */
3375 lock_ObtainWrite(&oldDirOp.scp->dirlock);
3376 oldDirOp.lockType = CM_DIRLOCK_WRITE;
3378 lock_ObtainMutex(&oldDscp->mx);
3379 cm_SyncOpDone(oldDscp, NULL, CM_SCACHESYNC_STOREDATA);
3382 cm_MergeStatus(NULL, oldDscp, &updatedOldDirStatus, &volSync,
3383 userp, CM_MERGEFLAG_DIROP);
3384 lock_ReleaseMutex(&oldDscp->mx);
3387 if (cm_CheckDirOpForSingleChange(&oldDirOp)) {
3390 diropCode = cm_BPlusDirLookup(&oldDirOp, oldNamep, &fileFid);
3391 if (diropCode == CM_ERROR_INEXACT_MATCH)
3393 else if (diropCode == EINVAL)
3395 diropCode = cm_DirLookup(&oldDirOp, oldNamep, &fileFid);
3397 if (diropCode == 0) {
3399 diropCode = cm_DirCreateEntry(&oldDirOp, newNamep, &fileFid);
3401 cm_BPlusDirCreateEntry(&oldDirOp, newNamep, &fileFid);
3405 if (diropCode == 0) {
3406 diropCode = cm_DirDeleteEntry(&oldDirOp, oldNamep);
3408 cm_BPlusDirDeleteEntry(&oldDirOp, oldNamep);
3414 cm_EndDirOp(&oldDirOp);
3416 /* and update it for the new one, too, if necessary */
3419 lock_ObtainWrite(&newDirOp.scp->dirlock);
3420 newDirOp.lockType = CM_DIRLOCK_WRITE;
3422 lock_ObtainMutex(&newDscp->mx);
3423 cm_SyncOpDone(newDscp, NULL, CM_SCACHESYNC_STOREDATA);
3425 cm_MergeStatus(NULL, newDscp, &updatedNewDirStatus, &volSync,
3426 userp, CM_MERGEFLAG_DIROP);
3427 lock_ReleaseMutex(&newDscp->mx);
3430 /* we only make the local change if we successfully made
3431 the change in the old directory AND there was only one
3432 change in the new directory */
3433 if (diropCode == 0 && cm_CheckDirOpForSingleChange(&newDirOp)) {
3434 cm_DirCreateEntry(&newDirOp, newNamep, &fileFid);
3436 cm_BPlusDirCreateEntry(&newDirOp, newNamep, &fileFid);
3440 cm_EndDirOp(&newDirOp);
3443 /* and return error code */
3447 /* Byte range locks:
3449 The OpenAFS Windows client has to fake byte range locks given no
3450 server side support for such locks. This is implemented as keyed
3451 byte range locks on the cache manager.
3453 Keyed byte range locks:
3455 Each cm_scache_t structure keeps track of a list of keyed locks.
3456 The key for a lock identifies an owner of a set of locks (referred
3457 to as a client). Each key is represented by a value. The set of
3458 key values used within a specific cm_scache_t structure form a
3459 namespace that has a scope of just that cm_scache_t structure. The
3460 same key value can be used with another cm_scache_t structure and
3461 correspond to a completely different client. However it is
3462 advantageous for the SMB or IFS layer to make sure that there is a
3463 1-1 mapping between client and keys over all cm_scache_t objects.
3465 Assume a client C has key Key(C) (although, since the scope of the
3466 key is a cm_scache_t, the key can be Key(C,S), where S is the
3467 cm_scache_t. But assume a 1-1 relation between keys and clients).
3468 A byte range (O,+L) denotes byte addresses (O) through (O+L-1)
3469 inclusive (a.k.a. [O,O+L-1]). The function Key(x) is implemented
3470 through cm_generateKey() function for both SMB and IFS.
3472 The list of locks for a cm_scache_t object S is maintained in
3473 S->fileLocks. The cache manager will set a lock on the AFS file
3474 server in order to assert the locks in S->fileLocks. If only
3475 shared locks are in place for S, then the cache manager will obtain
3476 a LockRead lock, while if there are any exclusive locks, it will
3477 obtain a LockWrite lock. If the exclusive locks are all released
3478 while the shared locks remain, then the cache manager will
3479 downgrade the lock from LockWrite to LockRead. Similarly, if an
3480 exclusive lock is obtained when only shared locks exist, then the
3481 cache manager will try to upgrade the lock from LockRead to
3484 Each lock L owned by client C maintains a key L->key such that
3485 L->key == Key(C), the effective range defined by L->LOffset and
3486 L->LLength such that the range of bytes affected by the lock is
3487 (L->LOffset, +L->LLength), a type maintained in L->LockType which
3488 is either exclusive or shared.
3492 A lock exists iff it is in S->fileLocks for some cm_scache_t
3493 S. Existing locks are in one of the following states: ACTIVE,
3494 WAITLOCK, WAITUNLOCK, LOST, DELETED.
3496 The following sections describe each lock and the associated
3499 1. ACTIVE: A lock L is ACTIVE iff the cache manager has asserted
3500 the lock with the AFS file server. This type of lock can be
3501 exercised by a client to read or write to the locked region (as
3504 1.1 ACTIVE->LOST: When the AFS file server fails to extend a
3505 server lock that was required to assert the lock. Before
3506 marking the lock as lost, the cache manager checks if the file
3507 has changed on the server. If the file has not changed, then
3508 the cache manager will attempt to obtain a new server lock
3509 that is sufficient to assert the client side locks for the
3510 file. If any of these fail, the lock is marked as LOST.
3511 Otherwise, it is left as ACTIVE.
3513 1.2 ACTIVE->DELETED: Lock is released.
3515 2. WAITLOCK: A lock is in a WAITLOCK state if the cache manager
3516 grants the lock but the lock is yet to be asserted with the AFS
3517 file server. Once the file server grants the lock, the state
3518 will transition to an ACTIVE lock.
3520 2.1 WAITLOCK->ACTIVE: The server granted the lock.
3522 2.2 WAITLOCK->DELETED: Lock is abandoned, or timed out during
3525 2.3 WAITLOCK->LOST: One or more locks from this client were
3526 marked as LOST. No further locks will be granted to this
3527 client until all lost locks are removed.
3529 3. WAITUNLOCK: A lock is in a WAITUNLOCK state if the cache manager
3530 receives a request for a lock that conflicts with an existing
3531 ACTIVE or WAITLOCK lock. The lock will be placed in the queue
3532 and will be granted at such time the conflicting locks are
3533 removed, at which point the state will transition to either
3536 3.1 WAITUNLOCK->ACTIVE: The conflicting lock was removed. The
3537 current serverLock is sufficient to assert this lock, or a
3538 sufficient serverLock is obtained.
3540 3.2 WAITUNLOCK->WAITLOCK: The conflicting lock was removed,
3541 however the required serverLock is yet to be asserted with the
3544 3.3 WAITUNLOCK->DELETED: The lock is abandoned, timed out or
3547 3.5 WAITUNLOCK->LOST: One or more locks from this client were
3548 marked as LOST. No further locks will be granted to this
3549 client until all lost locks are removed.
3551 4. LOST: A lock L is LOST if the server lock that was required to
3552 assert the lock could not be obtained or if it could not be
3553 extended, or if other locks by the same client were LOST.
3554 Essentially, once a lock is LOST, the contract between the cache
3555 manager and that specific client is no longer valid.
3557 The cache manager rechecks the server lock once every minute and
3558 extends it as appropriate. If this is not done for 5 minutes,
3559 the AFS file server will release the lock (the 5 minute timeout
3560 is based on current file server code and is fairly arbitrary).
3561 Once released, the lock cannot be re-obtained without verifying
3562 that the contents of the file hasn't been modified since the
3563 time the lock was released. Re-obtaining the lock without
3564 verifying this may lead to data corruption. If the lock can not
3565 be obtained safely, then all active locks for the cm_scache_t
3568 4.1 LOST->DELETED: The lock is released.
3570 5. DELETED: The lock is no longer relevant. Eventually, it will
3571 get removed from the cm_scache_t. In the meantime, it will be
3572 treated as if it does not exist.
3574 5.1 DELETED->not exist: The lock is removed from the
3577 The following are classifications of locks based on their state.
3579 6* A lock L is ACCEPTED if it is ACTIVE or WAITLOCK. These locks
3580 have been accepted by the cache manager, but may or may not have
3581 been granted back to the client.
3583 7* A lock L is QUEUED if it is ACTIVE, WAITLOCK or WAITUNLOCK.
3585 8* A lock L is WAITING if it is WAITLOCK or WAITUNLOCK.
3589 A client C can READ range (Offset,+Length) of a file represented by
3590 cm_scache_t S iff (1):
3592 1. for all _a_ in (Offset,+Length), all of the following is true:
3594 1.1 For each ACTIVE lock L in S->fileLocks such that _a_ in
3595 (L->LOffset,+L->LLength); L->key == Key(C) OR L->LockType is
3598 1.2 For each LOST lock L in S->fileLocks such that _a_ in
3599 (L->LOffset,+L->LLength); L->LockType is shared AND L->key !=
3602 (When locks are lost on an cm_scache_t, all locks are lost. By
3603 4.2 (below), if there is an exclusive LOST lock, then there
3604 can't be any overlapping ACTIVE locks.)
3606 A client C can WRITE range (Offset,+Length) of cm_scache_t S iff (2):
3608 2. for all _a_ in (Offset,+Length), one of the following is true:
3610 2.1 Byte _a_ of S is unowned (as specified in 1.1) AND there
3611 does not exist a LOST lock L such that _a_ in
3612 (L->LOffset,+L->LLength).
3614 2.2 Byte _a_ of S is owned by C under lock L (as specified in
3615 1.2) AND L->LockType is exclusive.
3617 A client C can OBTAIN a lock L on cm_scache_t S iff (both 3 and 4):
3619 3. for all _a_ in (L->LOffset,+L->LLength), ALL of the following is
3622 3.1 If L->LockType is exclusive then there does NOT exist a
3623 ACCEPTED lock M in S->fileLocks such that _a_ in
3624 (M->LOffset,+M->LLength).
3626 (If we count all QUEUED locks then we hit cases such as
3627 cascading waiting locks where the locks later on in the queue
3628 can be granted without compromising file integrity. On the
3629 other hand if only ACCEPTED locks are considered, then locks
3630 that were received earlier may end up waiting for locks that
3631 were received later to be unlocked. The choice of ACCEPTED
3632 locks was made to mimic the Windows byte range lock
3635 3.2 If L->LockType is shared then for each ACCEPTED lock M in
3636 S->fileLocks, if _a_ in (M->LOffset,+M->LLength) then
3637 M->LockType is shared.
3639 4. For all LOST locks M in S->fileLocks, ALL of the following are true:
3641 4.1 M->key != Key(C)
3643 4.2 If M->LockType is exclusive, then (L->LOffset,+L->LLength)
3644 and (M->LOffset,+M->LLength) do not intersect.
3646 (Note: If a client loses a lock, it loses all locks.
3647 Subsequently, it will not be allowed to obtain any more locks
3648 until all existing LOST locks that belong to the client are
3649 released. Once all locks are released by a single client,
3650 there exists no further contract between the client and AFS
3651 about the contents of the file, hence the client can then
3652 proceed to obtain new locks and establish a new contract.
3654 This doesn't quite work as you think it should, because most
3655 applications aren't built to deal with losing locks they
3656 thought they once had. For now, we don't have a good
3657 solution to lost locks.
3659 Also, for consistency reasons, we have to hold off on
3660 granting locks that overlap exclusive LOST locks.)
3662 A client C can only unlock locks L in S->fileLocks which have
3665 The representation and invariants are as follows:
3667 - Each cm_scache_t structure keeps:
3669 - A queue of byte-range locks (cm_scache_t::fileLocks) which
3670 are of type cm_file_lock_t.
3672 - A record of the highest server-side lock that has been
3673 obtained for this object (cm_scache_t::serverLock), which is
3674 one of (-1), LockRead, LockWrite.
3676 - A count of ACCEPTED exclusive and shared locks that are in the
3677 queue (cm_scache_t::sharedLocks and
3678 cm_scache_t::exclusiveLocks)
3680 - Each cm_file_lock_t structure keeps:
3682 - The type of lock (cm_file_lock_t::LockType)
3684 - The key associated with the lock (cm_file_lock_t::key)
3686 - The offset and length of the lock (cm_file_lock_t::LOffset
3687 and cm_file_lock_t::LLength)
3689 - The state of the lock.
3691 - Time of issuance or last successful extension
3693 Semantic invariants:
3695 I1. The number of ACCEPTED locks in S->fileLocks are
3696 (S->sharedLocks + S->exclusiveLocks)
3698 External invariants:
3700 I3. S->serverLock is the lock that we have asserted with the
3701 AFS file server for this cm_scache_t.
3703 I4. S->serverLock == LockRead iff there is at least one ACTIVE
3704 shared lock, but no ACTIVE exclusive locks.
3706 I5. S->serverLock == LockWrite iff there is at least one ACTIVE
3709 I6. If L is a LOST lock, then for each lock M in S->fileLocks,
3710 M->key == L->key IMPLIES M is LOST or DELETED.
3715 #define IS_LOCK_ACTIVE(lockp) (((lockp)->flags & (CM_FILELOCK_FLAG_DELETED|CM_FILELOCK_FLAG_WAITLOCK|CM_FILELOCK_FLAG_WAITUNLOCK|CM_FILELOCK_FLAG_LOST)) == 0)
3717 #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)
3719 #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)
3721 #define IS_LOCK_LOST(lockp) (((lockp)->flags & (CM_FILELOCK_FLAG_DELETED|CM_FILELOCK_FLAG_LOST)) == CM_FILELOCK_FLAG_LOST)
3723 #define IS_LOCK_DELETED(lockp) (((lockp)->flags & CM_FILELOCK_FLAG_DELETED) == CM_FILELOCK_FLAG_DELETED)
3726 #define IS_LOCK_ACCEPTED(lockp) (IS_LOCK_ACTIVE(lockp) || IS_LOCK_WAITLOCK(lockp))
3729 #define IS_LOCK_CLIENTONLY(lockp) ((((lockp)->scp->flags & CM_SCACHEFLAG_RO) == CM_SCACHEFLAG_RO) || (((lockp)->flags & CM_FILELOCK_FLAG_CLIENTONLY) == CM_FILELOCK_FLAG_CLIENTONLY))
3732 #define INTERSECT_RANGE(r1,r2) (((r2).offset+(r2).length) > (r1).offset && ((r1).offset +(r1).length) > (r2).offset)
3735 #define CONTAINS_RANGE(r1,r2) (((r2).offset+(r2).length) <= ((r1).offset+(r1).length) && (r1).offset <= (r2).offset)
3737 #if defined(VICED_CAPABILITY_USE_BYTE_RANGE_LOCKS) && !defined(LOCK_TESTING)
3738 #define SCP_SUPPORTS_BRLOCKS(scp) ((scp)->cbServerp && ((scp)->cbServerp->capabilities & VICED_CAPABILITY_USE_BYTE_RANGE_LOCKS))
3740 #define SCP_SUPPORTS_BRLOCKS(scp) (1)
3743 #define SERVERLOCKS_ENABLED(scp) (!((scp)->flags & CM_SCACHEFLAG_RO) && cm_enableServerLocks && SCP_SUPPORTS_BRLOCKS(scp))
3745 #if defined(VICED_CAPABILITY_WRITELOCKACL)
3746 #define SCP_SUPPORTS_WRITELOCKACL(scp) ((scp)->cbServerp && ((scp->cbServerp->capabilities & VICED_CAPABILITY_WRITELOCKACL)))
3748 #define SCP_SUPPORTS_WRITELOCKACL(scp) (0)
3750 /* This should really be defined in any build that this code is being
3752 #error VICED_CAPABILITY_WRITELOCKACL not defined.
3755 static void cm_LockRangeSubtract(cm_range_t * pos, const cm_range_t * neg)
3757 afs_int64 int_begin;
3760 int_begin = MAX(pos->offset, neg->offset);
3761 int_end = MIN(pos->offset+pos->length, neg->offset+neg->length);
3763 if (int_begin < int_end) {
3764 if (int_begin == pos->offset) {
3765 pos->length = pos->offset + pos->length - int_end;
3766 pos->offset = int_end;
3767 } else if (int_end == pos->offset + pos->length) {
3768 pos->length = int_begin - pos->offset;
3771 /* We only subtract ranges if the resulting range is
3772 contiguous. If we try to support non-contigous ranges, we
3773 aren't actually improving performance. */
3777 /* Called with scp->mx held. Returns 0 if all is clear to read the
3778 specified range by the client identified by key.
3780 long cm_LockCheckRead(cm_scache_t *scp,
3781 LARGE_INTEGER LOffset,
3782 LARGE_INTEGER LLength,
3785 #ifndef ADVISORY_LOCKS
3787 cm_file_lock_t *fileLock;
3791 int substract_ranges = FALSE;
3793 range.offset = LOffset.QuadPart;
3794 range.length = LLength.QuadPart;
3798 1. for all _a_ in (Offset,+Length), all of the following is true:
3800 1.1 For each ACTIVE lock L in S->fileLocks such that _a_ in
3801 (L->LOffset,+L->LLength); L->key == Key(C) OR L->LockType is
3804 1.2 For each LOST lock L in S->fileLocks such that _a_ in
3805 (L->LOffset,+L->LLength); L->LockType is shared AND L->key !=
3810 lock_ObtainRead(&cm_scacheLock);
3812 for (q = scp->fileLocksH; q && range.length > 0; q = osi_QNext(q)) {
3814 (cm_file_lock_t *)((char *) q - offsetof(cm_file_lock_t, fileq));
3816 if (INTERSECT_RANGE(range, fileLock->range)) {
3817 if (IS_LOCK_ACTIVE(fileLock)) {
3818 if (fileLock->key == key) {
3820 /* If there is an active lock for this client, it
3821 is safe to substract ranges.*/
3822 cm_LockRangeSubtract(&range, &fileLock->range);
3823 substract_ranges = TRUE;
3825 if (fileLock->lockType != LockRead) {
3826 code = CM_ERROR_LOCK_CONFLICT;
3830 /* even if the entire range is locked for reading,
3831 we still can't grant the lock at this point
3832 because the client may have lost locks. That
3833 is, unless we have already seen an active lock
3834 belonging to the client, in which case there
3835 can't be any lost locks for this client. */
3836 if (substract_ranges)
3837 cm_LockRangeSubtract(&range, &fileLock->range);
3839 } else if (IS_LOCK_LOST(fileLock) &&
3840 (fileLock->key == key || fileLock->lockType == LockWrite)) {
3841 code = CM_ERROR_BADFD;
3847 lock_ReleaseRead(&cm_scacheLock);
3849 osi_Log4(afsd_logp, "cm_LockCheckRead scp 0x%x offset %d length %d code 0x%x",
3850 scp, (unsigned long)LOffset.QuadPart, (unsigned long)LLength.QuadPart, code);
3861 /* Called with scp->mx held. Returns 0 if all is clear to write the
3862 specified range by the client identified by key.
3864 long cm_LockCheckWrite(cm_scache_t *scp,
3865 LARGE_INTEGER LOffset,
3866 LARGE_INTEGER LLength,
3869 #ifndef ADVISORY_LOCKS
3871 cm_file_lock_t *fileLock;
3876 range.offset = LOffset.QuadPart;
3877 range.length = LLength.QuadPart;
3880 A client C can WRITE range (Offset,+Length) of cm_scache_t S iff (2):
3882 2. for all _a_ in (Offset,+Length), one of the following is true:
3884 2.1 Byte _a_ of S is unowned AND there does not exist a LOST
3885 lock L such that _a_ in (L->LOffset,+L->LLength).
3887 2.2 Byte _a_ of S is owned by C under lock L AND L->LockType is
3891 lock_ObtainRead(&cm_scacheLock);
3893 for (q = scp->fileLocksH; q && range.length > 0; q = osi_QNext(q)) {
3895 (cm_file_lock_t *)((char *) q - offsetof(cm_file_lock_t, fileq));
3897 if (INTERSECT_RANGE(range, fileLock->range)) {
3898 if (IS_LOCK_ACTIVE(fileLock)) {
3899 if (fileLock->key == key) {
3900 if (fileLock->lockType == LockWrite) {
3902 /* if there is an active lock for this client, it
3903 is safe to substract ranges */
3904 cm_LockRangeSubtract(&range, &fileLock->range);
3906 code = CM_ERROR_LOCK_CONFLICT;
3910 code = CM_ERROR_LOCK_CONFLICT;
3913 } else if (IS_LOCK_LOST(fileLock)) {
3914 code = CM_ERROR_BADFD;
3920 lock_ReleaseRead(&cm_scacheLock);
3922 osi_Log4(afsd_logp, "cm_LockCheckWrite scp 0x%x offset %d length %d code 0x%x",
3923 scp, (unsigned long)LOffset.QuadPart, (unsigned long)LLength.QuadPart, code);
3934 /* Called with cm_scacheLock write locked */
3935 static cm_file_lock_t * cm_GetFileLock(void) {
3938 l = (cm_file_lock_t *) cm_freeFileLocks;
3940 osi_QRemove(&cm_freeFileLocks, &l->q);
3942 l = malloc(sizeof(cm_file_lock_t));
3943 osi_assertx(l, "null cm_file_lock_t");
3946 memset(l, 0, sizeof(cm_file_lock_t));
3951 /* Called with cm_scacheLock write locked */
3952 static void cm_PutFileLock(cm_file_lock_t *l) {
3953 osi_QAdd(&cm_freeFileLocks, &l->q);
3956 /* called with scp->mx held. May release it during processing, but
3957 leaves it held on exit. */
3958 long cm_IntSetLock(cm_scache_t * scp, cm_user_t * userp, int lockType,
3964 struct rx_connection * callp;
3966 afs_uint32 reqflags = reqp->flags;
3968 tfid.Volume = scp->fid.volume;
3969 tfid.Vnode = scp->fid.vnode;
3970 tfid.Unique = scp->fid.unique;
3973 osi_Log2(afsd_logp, "CALL SetLock scp 0x%p for lock %d", scp, lockType);
3975 reqp->flags |= CM_REQ_NORETRY;
3976 lock_ReleaseMutex(&scp->mx);
3979 code = cm_ConnFromFID(&cfid, userp, reqp, &connp);
3983 callp = cm_GetRxConn(connp);
3984 code = RXAFS_SetLock(callp, &tfid, lockType,
3986 rx_PutConnection(callp);
3988 } while (cm_Analyze(connp, userp, reqp, &cfid, &volSync,
3991 code = cm_MapRPCError(code, reqp);
3993 osi_Log1(afsd_logp, "CALL SetLock FAILURE, code 0x%x", code);
3995 osi_Log0(afsd_logp, "CALL SetLock SUCCESS");
3998 lock_ObtainMutex(&scp->mx);
3999 reqp->flags = reqflags;
4003 /* called with scp->mx held. Releases it during processing */
4004 long cm_IntReleaseLock(cm_scache_t * scp, cm_user_t * userp,
4010 struct rx_connection * callp;
4013 tfid.Volume = scp->fid.volume;
4014 tfid.Vnode = scp->fid.vnode;
4015 tfid.Unique = scp->fid.unique;
4018 lock_ReleaseMutex(&scp->mx);
4020 osi_Log1(afsd_logp, "CALL ReleaseLock scp 0x%p", scp);
4023 code = cm_ConnFromFID(&cfid, userp, reqp, &connp);
4027 callp = cm_GetRxConn(connp);
4028 code = RXAFS_ReleaseLock(callp, &tfid, &volSync);
4029 rx_PutConnection(callp);
4031 } while (cm_Analyze(connp, userp, reqp, &cfid, &volSync,
4033 code = cm_MapRPCError(code, reqp);
4036 "CALL ReleaseLock FAILURE, code 0x%x", code);
4039 "CALL ReleaseLock SUCCESS");
4041 lock_ObtainMutex(&scp->mx);
4046 /* called with scp->mx held. May release it during processing, but
4047 will exit with lock held.
4051 - 0 if the user has permission to get the specified lock for the scp
4053 - CM_ERROR_NOACCESS if not
4055 Any other error from cm_SyncOp will be sent down untranslated.
4057 If CM_ERROR_NOACCESS is returned and lock_type is LockRead, then
4058 phas_insert (if non-NULL) will receive a boolean value indicating
4059 whether the user has INSERT permission or not.
4061 long cm_LockCheckPerms(cm_scache_t * scp,
4068 long code = 0, code2 = 0;
4070 /* lock permissions are slightly tricky because of the 'i' bit.
4071 If the user has PRSFS_LOCK, she can read-lock the file. If the
4072 user has PRSFS_WRITE, she can write-lock the file. However, if
4073 the user has PRSFS_INSERT, then she can write-lock new files,
4074 but not old ones. Since we don't have information about
4075 whether a file is new or not, we assume that if the user owns
4076 the scp, then she has the permissions that are granted by
4079 osi_Log3(afsd_logp, "cm_LockCheckPerms for scp[0x%p] type[%d] user[0x%p]",
4080 scp, lock_type, userp);
4082 if (lock_type == LockRead)
4083 rights |= PRSFS_LOCK;
4084 else if (lock_type == LockWrite)
4085 rights |= PRSFS_WRITE | PRSFS_LOCK;
4088 osi_assertx(FALSE, "invalid lock type");
4093 *phas_insert = FALSE;
4095 code = cm_SyncOp(scp, NULL, userp, reqp, rights,
4096 CM_SCACHESYNC_GETSTATUS |
4097 CM_SCACHESYNC_NEEDCALLBACK);
4099 if (phas_insert && scp->creator == userp) {
4101 /* If this file was created by the user, then we check for
4102 PRSFS_INSERT. If the file server is recent enough, then
4103 this should be sufficient for her to get a write-lock (but
4104 not necessarily a read-lock). VICED_CAPABILITY_WRITELOCKACL
4105 indicates whether a file server supports getting write
4106 locks when the user only has PRSFS_INSERT.
4108 If the file was not created by the user we skip the check
4109 because the INSERT bit will not apply to this user even
4113 code2 = cm_SyncOp(scp, NULL, userp, reqp, PRSFS_INSERT,
4114 CM_SCACHESYNC_GETSTATUS |
4115 CM_SCACHESYNC_NEEDCALLBACK);
4117 if (code2 == CM_ERROR_NOACCESS) {
4118 osi_Log0(afsd_logp, "cm_LockCheckPerms user has no INSERT bits");
4120 *phas_insert = TRUE;
4121 osi_Log0(afsd_logp, "cm_LockCheckPerms user has INSERT bits");
4125 cm_SyncOpDone(scp, NULL, CM_SCACHESYNC_NEEDCALLBACK | CM_SCACHESYNC_GETSTATUS);
4127 osi_Log1(afsd_logp, "cm_LockCheckPerms returning code %d", code);
4132 /* called with scp->mx held */
4133 long cm_Lock(cm_scache_t *scp, unsigned char sLockType,
4134 LARGE_INTEGER LOffset, LARGE_INTEGER LLength,
4136 int allowWait, cm_user_t *userp, cm_req_t *reqp,
4137 cm_file_lock_t **lockpp)
4140 int Which = ((sLockType & LOCKING_ANDX_SHARED_LOCK) ? LockRead : LockWrite);
4141 cm_file_lock_t *fileLock;
4144 int wait_unlock = FALSE;
4145 int force_client_lock = FALSE;
4147 osi_Log4(afsd_logp, "cm_Lock scp 0x%x type 0x%x offset %d length %d",
4148 scp, sLockType, (unsigned long)LOffset.QuadPart, (unsigned long)LLength.QuadPart);
4149 osi_Log3(afsd_logp, "... allowWait %d key 0x%x:%x", allowWait,
4150 (unsigned long)(key >> 32), (unsigned long)(key & 0xffffffff));
4153 A client C can OBTAIN a lock L on cm_scache_t S iff (both 3 and 4):
4155 3. for all _a_ in (L->LOffset,+L->LLength), ALL of the following is
4158 3.1 If L->LockType is exclusive then there does NOT exist a
4159 ACCEPTED lock M in S->fileLocks such that _a_ in
4160 (M->LOffset,+M->LLength).
4162 3.2 If L->LockType is shared then for each ACCEPTED lock M in
4163 S->fileLocks, if _a_ in (M->LOffset,+M->LLength) then
4164 M->LockType is shared.
4166 4. For all LOST locks M in S->fileLocks, ALL of the following are true:
4168 4.1 M->key != Key(C)
4170 4.2 If M->LockType is exclusive, then (L->LOffset,+L->LLength)
4171 and (M->LOffset,+M->LLength) do not intersect.
4174 range.offset = LOffset.QuadPart;
4175 range.length = LLength.QuadPart;
4177 lock_ObtainRead(&cm_scacheLock);
4179 for (q = scp->fileLocksH; q; q = osi_QNext(q)) {
4181 (cm_file_lock_t *)((char *) q - offsetof(cm_file_lock_t, fileq));
4183 if (IS_LOCK_LOST(fileLock)) {
4184 if (fileLock->key == key) {
4185 code = CM_ERROR_BADFD;
4187 } else if (fileLock->lockType == LockWrite && INTERSECT_RANGE(range, fileLock->range)) {
4188 code = CM_ERROR_WOULDBLOCK;
4194 /* we don't need to check for deleted locks here since deleted
4195 locks are dequeued from scp->fileLocks */
4196 if (IS_LOCK_ACCEPTED(fileLock) &&
4197 INTERSECT_RANGE(range, fileLock->range)) {
4199 if ((sLockType & LOCKING_ANDX_SHARED_LOCK) == 0 ||
4200 fileLock->lockType != LockRead) {
4202 code = CM_ERROR_WOULDBLOCK;
4208 lock_ReleaseRead(&cm_scacheLock);
4210 if (code == 0 && SERVERLOCKS_ENABLED(scp)) {
4211 if (Which == scp->serverLock ||
4212 (Which == LockRead && scp->serverLock == LockWrite)) {
4216 /* we already have the lock we need */
4217 osi_Log3(afsd_logp, " we already have the correct lock. exclusives[%d], shared[%d], serverLock[%d]",
4218 scp->exclusiveLocks, scp->sharedLocks, (int)(signed char) scp->serverLock);
4220 code = cm_LockCheckPerms(scp, Which, userp, reqp, &has_insert);
4222 /* special case: if we don't have permission to read-lock
4223 the file, then we force a clientside lock. This is to
4224 compensate for applications that obtain a read-lock for
4225 reading files off of directories that don't grant
4226 read-locks to the user. */
4227 if (code == CM_ERROR_NOACCESS && Which == LockRead) {
4229 if (has_insert && SCP_SUPPORTS_WRITELOCKACL(scp)) {
4230 osi_Log0(afsd_logp, " User has no read-lock perms, but has INSERT perms.");
4233 osi_Log0(afsd_logp, " User has no read-lock perms. Forcing client-side lock");
4234 force_client_lock = TRUE;
4238 } else if ((scp->exclusiveLocks > 0) ||
4239 (scp->sharedLocks > 0 && scp->serverLock != LockRead)) {
4242 /* We are already waiting for some other lock. We should
4243 wait for the daemon to catch up instead of generating a
4244 flood of SetLock calls. */
4245 osi_Log3(afsd_logp, " already waiting for other lock. exclusives[%d], shared[%d], serverLock[%d]",
4246 scp->exclusiveLocks, scp->sharedLocks, (int)(signed char) scp->serverLock);
4248 /* see if we have permission to create the lock in the
4250 code = cm_LockCheckPerms(scp, Which, userp, reqp, &has_insert);
4252 code = CM_ERROR_WOULDBLOCK;
4253 else if (code == CM_ERROR_NOACCESS && Which == LockRead) {
4255 if (has_insert && SCP_SUPPORTS_WRITELOCKACL(scp)) {
4257 " User has no read-lock perms, but has INSERT perms.");
4258 code = CM_ERROR_WOULDBLOCK;
4261 " User has no read-lock perms. Forcing client-side lock");
4262 force_client_lock = TRUE;
4266 /* leave any other codes as-is */
4270 int check_data_version = FALSE;
4273 /* first check if we have permission to elevate or obtain
4275 code = cm_LockCheckPerms(scp, Which, userp, reqp, &has_insert);
4277 if (code == CM_ERROR_NOACCESS && Which == LockRead &&
4278 (!has_insert || !SCP_SUPPORTS_WRITELOCKACL(scp))) {
4279 osi_Log0(afsd_logp, " User has no read-lock perms. Forcing client-side lock");
4280 force_client_lock = TRUE;
4285 /* has_insert => (Which == LockRead, code == CM_ERROR_NOACCESS) */
4287 if (scp->serverLock == LockRead && Which == LockWrite) {
4289 /* We want to escalate the lock to a LockWrite.
4290 * Unfortunately that's not really possible without
4291 * letting go of the current lock. But for now we do
4295 " attempting to UPGRADE from LockRead to LockWrite.");
4297 " dataVersion on scp: %I64d", scp->dataVersion);
4299 /* we assume at this point (because scp->serverLock
4300 was valid) that we had a valid server lock. */
4301 scp->lockDataVersion = scp->dataVersion;
4302 check_data_version = TRUE;
4304 code = cm_IntReleaseLock(scp, userp, reqp);
4307 /* We couldn't release the lock */
4310 scp->serverLock = -1;
4314 /* We need to obtain a server lock of type Which in order
4315 * to assert this file lock */
4316 #ifndef AGGRESSIVE_LOCKS
4319 newLock = LockWrite;
4322 code = cm_IntSetLock(scp, userp, newLock, reqp);
4324 #ifdef AGGRESSIVE_LOCKS
4325 if ((code == CM_ERROR_WOULDBLOCK ||
4326 code == CM_ERROR_NOACCESS) && newLock != Which) {
4327 /* we wanted LockRead. We tried LockWrite. Now try
4332 osi_assertx(newLock == LockRead, "lock type not read");
4334 code = cm_IntSetLock(scp, userp, newLock, reqp);
4338 if (code == CM_ERROR_NOACCESS) {
4339 if (Which == LockRead) {
4340 if (has_insert && SCP_SUPPORTS_WRITELOCKACL(scp)) {
4342 /* We requested a read-lock, but we have permission to
4343 * get a write-lock. Try that */
4345 tcode = cm_LockCheckPerms(scp, LockWrite, userp, reqp, NULL);
4348 newLock = LockWrite;
4350 osi_Log0(afsd_logp, " User has 'i' perms and the request was for a LockRead. Trying to get a LockWrite instead");
4352 code = cm_IntSetLock(scp, userp, newLock, reqp);
4355 osi_Log0(afsd_logp, " User has no read-lock perms. Forcing client-side lock");
4356 force_client_lock = TRUE;
4358 } else if (Which == LockWrite &&
4359 scp->creator == userp && !SCP_SUPPORTS_WRITELOCKACL(scp)) {
4362 /* Special case: if the lock request was for a
4363 * LockWrite and the user owns the file and we weren't
4364 * allowed to obtain the serverlock, we either lost a
4365 * race (the permissions changed from under us), or we
4366 * have 'i' bits, but we aren't allowed to lock the
4369 /* check if we lost a race... */
4370 tcode = cm_LockCheckPerms(scp, Which, userp, reqp, NULL);
4373 osi_Log0(afsd_logp, " User has 'i' perms but can't obtain write locks. Using client-side locks.");
4374 force_client_lock = TRUE;
4379 if (code == 0 && check_data_version &&
4380 scp->dataVersion != scp->lockDataVersion) {
4381 /* We lost a race. Although we successfully obtained
4382 * a lock, someone modified the file in between. The
4383 * locks have all been technically lost. */
4386 " Data version mismatch while upgrading lock.");
4388 " Data versions before=%I64d, after=%I64d",
4389 scp->lockDataVersion,
4392 " Releasing stale lock for scp 0x%x", scp);
4394 code = cm_IntReleaseLock(scp, userp, reqp);
4396 scp->serverLock = -1;
4398 code = CM_ERROR_INVAL;
4399 } else if (code == 0) {
4400 scp->serverLock = newLock;
4401 scp->lockDataVersion = scp->dataVersion;
4405 (scp->sharedLocks > 0 || scp->exclusiveLocks > 0) &&
4406 scp->serverLock == -1) {
4407 /* Oops. We lost the lock. */
4408 cm_LockMarkSCacheLost(scp);
4411 } else if (code == 0) { /* server locks not enabled */
4413 " Skipping server lock for scp");
4418 if (code != 0 && !force_client_lock) {
4419 /* Special case error translations
4421 Applications don't expect certain errors from a
4422 LockFile/UnlockFile call. We need to translate some error
4423 code to codes that apps expect and handle. */
4425 /* We shouldn't actually need to handle this case since we
4426 simulate locks for RO scps anyway. */
4427 if (code == CM_ERROR_READONLY) {
4428 osi_Log0(afsd_logp, " Reinterpreting CM_ERROR_READONLY as CM_ERROR_NOACCESS");
4429 code = CM_ERROR_NOACCESS;
4433 if (code == 0 || (code == CM_ERROR_WOULDBLOCK && allowWait) ||
4434 force_client_lock) {
4436 /* clear the error if we are forcing a client lock, so we
4437 don't get confused later. */
4438 if (force_client_lock && code != CM_ERROR_WOULDBLOCK)
4441 lock_ObtainWrite(&cm_scacheLock);
4442 fileLock = cm_GetFileLock();
4443 lock_ReleaseWrite(&cm_scacheLock);
4445 fileLock->fid = scp->fid;
4447 fileLock->key = key;
4448 fileLock->lockType = Which;
4450 fileLock->userp = userp;
4451 fileLock->range = range;
4452 fileLock->flags = (code == 0 ? 0 :
4454 CM_FILELOCK_FLAG_WAITUNLOCK :
4455 CM_FILELOCK_FLAG_WAITLOCK));
4457 if (force_client_lock || !SERVERLOCKS_ENABLED(scp))
4458 fileLock->flags |= CM_FILELOCK_FLAG_CLIENTONLY;
4460 fileLock->lastUpdate = (code == 0 && !force_client_lock) ? time(NULL) : 0;
4462 lock_ObtainWrite(&cm_scacheLock);
4463 osi_QAddT(&scp->fileLocksH, &scp->fileLocksT, &fileLock->fileq);
4464 cm_HoldSCacheNoLock(scp);
4465 fileLock->scp = scp;
4466 osi_QAdd(&cm_allFileLocks, &fileLock->q);
4467 lock_ReleaseWrite(&cm_scacheLock);
4473 if (IS_LOCK_CLIENTONLY(fileLock)) {
4475 } else if (IS_LOCK_ACCEPTED(fileLock)) {
4476 if (Which == LockRead)
4479 scp->exclusiveLocks++;
4483 "cm_Lock Lock added 0x%p flags 0x%x to scp [0x%p]",
4484 fileLock, fileLock->flags, scp);
4486 " exclusives[%d] shared[%d] client[%d] serverLock[%d]",
4487 scp->exclusiveLocks, scp->sharedLocks, scp->clientLocks,
4488 (int)(signed char) scp->serverLock);
4491 "cm_Lock Rejecting lock (code = 0x%x)", code);
4497 static int cm_KeyEquals(cm_key_t k1, cm_key_t k2, int flags);
4499 /* Called with scp->mx held */
4500 long cm_UnlockByKey(cm_scache_t * scp,
4507 cm_file_lock_t *fileLock;
4508 osi_queue_t *q, *qn;
4511 osi_Log4(afsd_logp, "cm_UnlockByKey scp 0x%p key 0x%x:%x flags=0x%x",
4513 (unsigned long)(key >> 32),
4514 (unsigned long)(key & 0xffffffff),
4517 lock_ObtainWrite(&cm_scacheLock);
4519 for (q = scp->fileLocksH; q; q = qn) {
4522 fileLock = (cm_file_lock_t *)
4523 ((char *) q - offsetof(cm_file_lock_t, fileq));
4526 osi_Log4(afsd_logp, " Checking lock[0x%x] range[%d,+%d] type[%d]",
4528 (unsigned long) fileLock->range.offset,
4529 (unsigned long) fileLock->range.length,
4530 fileLock->lockType);
4531 osi_Log3(afsd_logp, " key[0x%x:%x] flags[0x%x]",
4532 (unsigned long)(fileLock->key >> 32),
4533 (unsigned long)(fileLock->key & 0xffffffff),
4536 if (cm_FidCmp(&fileLock->fid, &fileLock->scp->fid)) {
4537 osi_Log0(afsd_logp, "!!fileLock->fid != scp->fid");
4538 osi_Log4(afsd_logp, " fileLock->fid(cell=[%d], volume=[%d], vnode=[%d], unique=[%d]",
4540 fileLock->fid.volume,
4541 fileLock->fid.vnode,
4542 fileLock->fid.unique);
4543 osi_Log4(afsd_logp, " scp->fid(cell=[%d], volume=[%d], vnode=[%d], unique=[%d]",
4544 fileLock->scp->fid.cell,
4545 fileLock->scp->fid.volume,
4546 fileLock->scp->fid.vnode,
4547 fileLock->scp->fid.unique);
4548 osi_assertx(FALSE, "invalid fid value");
4552 if (!IS_LOCK_DELETED(fileLock) &&
4553 cm_KeyEquals(fileLock->key, key, flags)) {
4554 osi_Log3(afsd_logp, "...Unlock range [%d,+%d] type %d",
4555 fileLock->range.offset,
4556 fileLock->range.length,
4557 fileLock->lockType);
4559 if (scp->fileLocksT == q)
4560 scp->fileLocksT = osi_QPrev(q);
4561 osi_QRemoveHT(&scp->fileLocksH, &scp->fileLocksT, q);
4563 if (IS_LOCK_CLIENTONLY(fileLock)) {
4565 } else if (IS_LOCK_ACCEPTED(fileLock)) {
4566 if (fileLock->lockType == LockRead)
4569 scp->exclusiveLocks--;
4572 fileLock->flags |= CM_FILELOCK_FLAG_DELETED;
4574 cm_ReleaseUser(fileLock->userp);
4575 cm_ReleaseSCacheNoLock(scp);
4577 fileLock->userp = NULL;
4578 fileLock->scp = NULL;
4584 lock_ReleaseWrite(&cm_scacheLock);
4586 if (n_unlocks == 0) {
4587 osi_Log0(afsd_logp, "cm_UnlockByKey no locks found");
4588 osi_Log3(afsd_logp, " Leaving scp with exclusives[%d], shared[%d], serverLock[%d]",
4589 scp->exclusiveLocks, scp->sharedLocks, (int)(signed char) scp->serverLock);
4594 osi_Log1(afsd_logp, "cm_UnlockByKey done with %d locks", n_unlocks);
4596 osi_assertx(scp->sharedLocks >= 0, "scp->sharedLocks < 0");
4597 osi_assertx(scp->exclusiveLocks >= 0, "scp->exclusiveLocks < 0");
4598 osi_assertx(scp->clientLocks >= 0, "scp->clientLocks < 0");
4600 if (!SERVERLOCKS_ENABLED(scp)) {
4601 osi_Log0(afsd_logp, " Skipping server lock for scp");
4605 /* Ideally we would go through the rest of the locks to determine
4606 * if one or more locks that were formerly in WAITUNLOCK can now
4607 * be put to ACTIVE or WAITLOCK and update scp->exclusiveLocks and
4608 * scp->sharedLocks accordingly. However, the retrying of locks
4609 * in that manner is done cm_RetryLock() manually.
4612 if (scp->serverLock == LockWrite &&
4613 scp->exclusiveLocks == 0 &&
4614 scp->sharedLocks > 0) {
4616 /* The serverLock should be downgraded to LockRead */
4617 osi_Log0(afsd_logp, " DOWNGRADE lock from LockWrite to LockRead");
4619 /* since scp->serverLock looked sane, we are going to assume
4620 that we have a valid server lock. */
4621 scp->lockDataVersion = scp->dataVersion;
4622 osi_Log1(afsd_logp, " dataVersion on scp = %I64d", scp->dataVersion);
4624 code = cm_IntReleaseLock(scp, userp, reqp);
4627 /* so we couldn't release it. Just let the lock be for now */
4631 scp->serverLock = -1;
4634 code = cm_IntSetLock(scp, userp, LockRead, reqp);
4636 if (code == 0 && scp->lockDataVersion == scp->dataVersion) {
4637 scp->serverLock = LockRead;
4638 } else if (code == 0 && scp->lockDataVersion != scp->dataVersion) {
4639 /* We lost a race condition. Although we have a valid
4640 lock on the file, the data has changed and essentially
4641 we have lost the lock we had during the transition. */
4643 osi_Log0(afsd_logp, "Data version mismatch during lock downgrade");
4644 osi_Log2(afsd_logp, " Data versions before=%I64d, after=%I64d",
4645 scp->lockDataVersion,
4648 code = cm_IntReleaseLock(scp, userp, reqp);
4650 code = CM_ERROR_INVAL;
4651 scp->serverLock = -1;
4655 (scp->sharedLocks > 0 || scp->exclusiveLocks > 0) &&
4656 (scp->serverLock == -1)) {
4658 cm_LockMarkSCacheLost(scp);
4661 /* failure here has no bearing on the return value of
4665 } else if (scp->serverLock != (-1) &&
4666 scp->exclusiveLocks == 0 &&
4667 scp->sharedLocks == 0) {
4668 /* The serverLock should be released entirely */
4670 code = cm_IntReleaseLock(scp, userp, reqp);
4673 scp->serverLock = (-1);
4678 osi_Log1(afsd_logp, "cm_UnlockByKey code 0x%x", code);
4679 osi_Log4(afsd_logp, " Leaving scp with excl[%d], shared[%d], client[%d], serverLock[%d]",
4680 scp->exclusiveLocks, scp->sharedLocks, scp->clientLocks,
4681 (int)(signed char) scp->serverLock);
4686 long cm_Unlock(cm_scache_t *scp,
4687 unsigned char sLockType,
4688 LARGE_INTEGER LOffset, LARGE_INTEGER LLength,
4694 int Which = ((sLockType & LOCKING_ANDX_SHARED_LOCK) ? LockRead : LockWrite);
4695 cm_file_lock_t *fileLock;
4697 int release_userp = FALSE;
4699 osi_Log4(afsd_logp, "cm_Unlock scp 0x%p type 0x%x offset %d length %d",
4700 scp, sLockType, (unsigned long)LOffset.QuadPart, (unsigned long)LLength.QuadPart);
4701 osi_Log2(afsd_logp, "... key 0x%x:%x",
4702 (unsigned long) (key >> 32), (unsigned long) (key & 0xffffffff));
4704 lock_ObtainRead(&cm_scacheLock);
4706 for (q = scp->fileLocksH; q; q = osi_QNext(q)) {
4707 fileLock = (cm_file_lock_t *)
4708 ((char *) q - offsetof(cm_file_lock_t, fileq));
4711 if (cm_FidCmp(&fileLock->fid, &fileLock->scp->fid)) {
4712 osi_Log0(afsd_logp, "!!fileLock->fid != scp->fid");
4713 osi_Log4(afsd_logp, " fileLock->fid(cell=[%d], volume=[%d], vnode=[%d], unique=[%d]",
4715 fileLock->fid.volume,
4716 fileLock->fid.vnode,
4717 fileLock->fid.unique);
4718 osi_Log4(afsd_logp, " scp->fid(cell=[%d], volume=[%d], vnode=[%d], unique=[%d]",
4719 fileLock->scp->fid.cell,
4720 fileLock->scp->fid.volume,
4721 fileLock->scp->fid.vnode,
4722 fileLock->scp->fid.unique);
4723 osi_assertx(FALSE, "invalid fid value");
4726 if (!IS_LOCK_DELETED(fileLock) &&
4727 fileLock->key == key &&
4728 fileLock->range.offset == LOffset.QuadPart &&
4729 fileLock->range.length == LLength.QuadPart) {
4735 osi_Log0(afsd_logp, "cm_Unlock lock not found; failure");
4737 lock_ReleaseRead(&cm_scacheLock);
4739 /* The lock didn't exist anyway. *shrug* */
4740 return CM_ERROR_RANGE_NOT_LOCKED;
4743 /* discard lock record */
4744 lock_ConvertRToW(&cm_scacheLock);
4745 if (scp->fileLocksT == q)
4746 scp->fileLocksT = osi_QPrev(q);
4747 osi_QRemoveHT(&scp->fileLocksH, &scp->fileLocksT, q);
4750 * Don't delete it here; let the daemon delete it, to simplify
4751 * the daemon's traversal of the list.
4754 if (IS_LOCK_CLIENTONLY(fileLock)) {
4756 } else if (IS_LOCK_ACCEPTED(fileLock)) {
4757 if (fileLock->lockType == LockRead)
4760 scp->exclusiveLocks--;
4763 fileLock->flags |= CM_FILELOCK_FLAG_DELETED;
4764 if (userp != NULL) {
4765 cm_ReleaseUser(fileLock->userp);
4767 userp = fileLock->userp;
4768 release_userp = TRUE;
4770 fileLock->userp = NULL;
4771 cm_ReleaseSCacheNoLock(scp);
4772 fileLock->scp = NULL;
4773 lock_ReleaseWrite(&cm_scacheLock);
4775 if (!SERVERLOCKS_ENABLED(scp)) {
4776 osi_Log0(afsd_logp, " Skipping server locks for scp");
4780 /* Ideally we would go through the rest of the locks to determine
4781 * if one or more locks that were formerly in WAITUNLOCK can now
4782 * be put to ACTIVE or WAITLOCK and update scp->exclusiveLocks and
4783 * scp->sharedLocks accordingly. However, the retrying of locks
4784 * in that manner is done cm_RetryLock() manually.
4787 if (scp->serverLock == LockWrite &&
4788 scp->exclusiveLocks == 0 &&
4789 scp->sharedLocks > 0) {
4791 /* The serverLock should be downgraded to LockRead */
4792 osi_Log0(afsd_logp, " DOWNGRADE lock from LockWrite to LockRead");
4794 /* Since we already had a lock, we assume that there is a
4795 valid server lock. */
4796 scp->lockDataVersion = scp->dataVersion;
4797 osi_Log1(afsd_logp, " dataVersion on scp is %I64d", scp->dataVersion);
4799 /* before we downgrade, make sure that we have enough
4800 permissions to get the read lock. */
4801 code = cm_LockCheckPerms(scp, LockRead, userp, reqp, NULL);
4804 osi_Log0(afsd_logp, " SKIPPING downgrade because user doesn't have perms to get downgraded lock");
4810 code = cm_IntReleaseLock(scp, userp, reqp);
4813 /* so we couldn't release it. Just let the lock be for now */
4817 scp->serverLock = -1;
4820 code = cm_IntSetLock(scp, userp, LockRead, reqp);
4822 if (code == 0 && scp->lockDataVersion == scp->dataVersion) {
4823 scp->serverLock = LockRead;
4824 } else if (code == 0 && scp->lockDataVersion != scp->dataVersion) {
4825 /* Lost a race. We obtained a new lock, but that is
4826 meaningless since someone modified the file
4830 "Data version mismatch while downgrading lock");
4832 " Data versions before=%I64d, after=%I64d",
4833 scp->lockDataVersion,
4836 code = cm_IntReleaseLock(scp, userp, reqp);
4838 scp->serverLock = -1;
4839 code = CM_ERROR_INVAL;
4843 (scp->sharedLocks > 0 || scp->exclusiveLocks > 0) &&
4844 (scp->serverLock == -1)) {
4846 cm_LockMarkSCacheLost(scp);
4849 /* failure here has no bearing on the return value of
4853 } else if (scp->serverLock != (-1) &&
4854 scp->exclusiveLocks == 0 &&
4855 scp->sharedLocks == 0) {
4856 /* The serverLock should be released entirely */
4858 code = cm_IntReleaseLock(scp, userp, reqp);
4861 scp->serverLock = (-1);
4866 cm_ReleaseUser(userp);
4870 osi_Log1(afsd_logp, "cm_Unlock code 0x%x", code);
4871 osi_Log4(afsd_logp, " leaving scp with excl[%d], shared[%d], client[%d], serverLock[%d]",
4872 scp->exclusiveLocks, scp->sharedLocks, scp->clientLocks,
4873 (int)(signed char) scp->serverLock);
4878 /* called with scp->mx held */
4879 void cm_LockMarkSCacheLost(cm_scache_t * scp)
4881 cm_file_lock_t *fileLock;
4884 osi_Log1(afsd_logp, "cm_LockMarkSCacheLost scp 0x%x", scp);
4887 /* With the current code, we can't lose a lock on a RO scp */
4888 osi_assertx(!(scp->flags & CM_SCACHEFLAG_RO), "CM_SCACHEFLAG_RO unexpected");
4891 /* cm_scacheLock needed because we are modifying fileLock->flags */
4892 lock_ObtainWrite(&cm_scacheLock);
4894 for (q = scp->fileLocksH; q; q = osi_QNext(q)) {
4896 (cm_file_lock_t *)((char *) q - offsetof(cm_file_lock_t, fileq));
4898 if (IS_LOCK_ACTIVE(fileLock) &&
4899 !IS_LOCK_CLIENTONLY(fileLock)) {
4900 if (fileLock->lockType == LockRead)
4903 scp->exclusiveLocks--;
4905 fileLock->flags |= CM_FILELOCK_FLAG_LOST;
4909 scp->serverLock = -1;
4910 scp->lockDataVersion = -1;
4911 lock_ReleaseWrite(&cm_scacheLock);
4914 /* Called with no relevant locks held */
4915 void cm_CheckLocks()
4917 osi_queue_t *q, *nq;
4918 cm_file_lock_t *fileLock;
4924 struct rx_connection * callp;
4929 lock_ObtainWrite(&cm_scacheLock);
4931 cm_lockRefreshCycle++;
4933 osi_Log1(afsd_logp, "cm_CheckLocks starting lock check cycle %d", cm_lockRefreshCycle);
4935 for (q = cm_allFileLocks; q; q = nq) {
4936 fileLock = (cm_file_lock_t *) q;
4940 if (IS_LOCK_DELETED(fileLock)) {
4942 osi_QRemove(&cm_allFileLocks, q);
4943 cm_PutFileLock(fileLock);
4945 } else if (IS_LOCK_ACTIVE(fileLock) && !IS_LOCK_CLIENTONLY(fileLock)) {
4947 /* Server locks must have been enabled for us to have
4948 received an active non-client-only lock. */
4949 osi_assertx(cm_enableServerLocks, "!cm_enableServerLocks");
4951 scp = fileLock->scp;
4952 osi_assertx(scp != NULL, "null cm_scache_t");
4954 cm_HoldSCacheNoLock(scp);
4957 if (cm_FidCmp(&fileLock->fid, &fileLock->scp->fid)) {
4958 osi_Log0(afsd_logp, "!!fileLock->fid != scp->fid");
4959 osi_Log4(afsd_logp, " fileLock->fid(cell=[%d], volume=[%d], vnode=[%d], unique=[%d]",
4961 fileLock->fid.volume,
4962 fileLock->fid.vnode,
4963 fileLock->fid.unique);
4964 osi_Log4(afsd_logp, " scp->fid(cell=[%d], volume=[%d], vnode=[%d], unique=[%d]",
4965 fileLock->scp->fid.cell,
4966 fileLock->scp->fid.volume,
4967 fileLock->scp->fid.vnode,
4968 fileLock->scp->fid.unique);
4969 osi_assertx(FALSE, "invalid fid");
4972 /* Server locks are extended once per scp per refresh
4974 if (scp->lastRefreshCycle != cm_lockRefreshCycle) {
4976 int scp_done = FALSE;
4978 osi_Log1(afsd_logp, "cm_CheckLocks Updating scp 0x%x", scp);
4980 lock_ReleaseWrite(&cm_scacheLock);
4981 lock_ObtainMutex(&scp->mx);
4983 /* did the lock change while we weren't holding the lock? */
4984 if (!IS_LOCK_ACTIVE(fileLock))
4985 goto post_syncopdone;
4987 code = cm_SyncOp(scp, NULL, fileLock->userp, &req, 0,
4988 CM_SCACHESYNC_NEEDCALLBACK
4989 | CM_SCACHESYNC_GETSTATUS
4990 | CM_SCACHESYNC_LOCK);
4994 "cm_CheckLocks SyncOp failure code 0x%x", code);
4995 goto post_syncopdone;
4998 /* cm_SyncOp releases scp->mx during which the lock
4999 may get released. */
5000 if (!IS_LOCK_ACTIVE(fileLock))
5001 goto pre_syncopdone;
5003 if (scp->serverLock != -1 && !(scp->flags & CM_SCACHEFLAG_DELETED)) {
5007 tfid.Volume = scp->fid.volume;
5008 tfid.Vnode = scp->fid.vnode;
5009 tfid.Unique = scp->fid.unique;
5011 userp = fileLock->userp;
5013 osi_Log3(afsd_logp, "CALL ExtendLock lock 0x%p for scp=0x%p with lock %d",
5016 (int) scp->serverLock);
5018 lock_ReleaseMutex(&scp->mx);
5021 code = cm_ConnFromFID(&cfid, userp,
5026 callp = cm_GetRxConn(connp);
5027 code = RXAFS_ExtendLock(callp, &tfid,
5029 rx_PutConnection(callp);
5031 osi_Log1(afsd_logp, " ExtendLock returns %d", code);
5033 } while (cm_Analyze(connp, userp, &req,
5034 &cfid, &volSync, NULL, NULL,
5037 code = cm_MapRPCError(code, &req);
5039 lock_ObtainMutex(&scp->mx);
5042 osi_Log1(afsd_logp, "CALL ExtendLock FAILURE, code 0x%x", code);
5044 osi_Log0(afsd_logp, "CALL ExtendLock SUCCESS");
5045 scp->lockDataVersion = scp->dataVersion;
5048 if ((code == EINVAL || code == CM_ERROR_INVAL) &&
5049 scp->lockDataVersion == scp->dataVersion) {
5053 (scp->exclusiveLocks > 0) ? LockWrite: LockRead;
5055 /* we might still have a chance to obtain a
5058 code = cm_IntSetLock(scp, userp, lockType, &req);
5061 code = CM_ERROR_INVAL;
5062 } else if (scp->lockDataVersion != scp->dataVersion) {
5064 /* now check if we still have the file at
5065 the right data version. */
5067 "Data version mismatch on scp 0x%p",
5070 " Data versions: before=%I64d, after=%I64d",
5071 scp->lockDataVersion,
5074 code = cm_IntReleaseLock(scp, userp, &req);
5076 code = CM_ERROR_INVAL;
5080 if (code == EINVAL || code == CM_ERROR_INVAL ||
5081 code == CM_ERROR_BADFD) {
5082 cm_LockMarkSCacheLost(scp);
5086 /* interestingly, we have found an active lock
5087 belonging to an scache that has no
5089 cm_LockMarkSCacheLost(scp);
5096 cm_SyncOpDone(scp, NULL, CM_SCACHESYNC_LOCK);
5099 lock_ReleaseMutex(&scp->mx);
5101 lock_ObtainWrite(&cm_scacheLock);
5104 fileLock->lastUpdate = time(NULL);
5108 scp->lastRefreshCycle = cm_lockRefreshCycle;
5111 /* we have already refreshed the locks on this scp */
5112 fileLock->lastUpdate = time(NULL);
5115 cm_ReleaseSCacheNoLock(scp);
5117 } else if (IS_LOCK_ACTIVE(fileLock) && IS_LOCK_CLIENTONLY(fileLock)) {
5118 /* TODO: Check callbacks */
5122 lock_ReleaseWrite(&cm_scacheLock);
5123 osi_Log1(afsd_logp, "cm_CheckLocks completes lock check cycle %d", cm_lockRefreshCycle);
5126 /* NOT called with scp->mx held. */
5127 long cm_RetryLock(cm_file_lock_t *oldFileLock, int client_is_dead)
5130 cm_scache_t *scp = NULL;
5131 cm_file_lock_t *fileLock;
5135 int force_client_lock = FALSE;
5136 int has_insert = FALSE;
5137 int check_data_version = FALSE;
5141 if (client_is_dead) {
5142 code = CM_ERROR_TIMEDOUT;
5146 lock_ObtainRead(&cm_scacheLock);
5148 osi_Log2(afsd_logp, "cm_RetryLock checking lock %p (scp=%p)", oldFileLock, oldFileLock->scp);
5149 osi_Log4(afsd_logp, " offset(%x:%x) length(%x:%x)",
5150 (unsigned)(oldFileLock->range.offset >> 32),
5151 (unsigned)(oldFileLock->range.offset & 0xffffffff),
5152 (unsigned)(oldFileLock->range.length >> 32),
5153 (unsigned)(oldFileLock->range.length & 0xffffffff));
5154 osi_Log3(afsd_logp, " key(%x:%x) flags=%x",
5155 (unsigned)(oldFileLock->key >> 32),
5156 (unsigned)(oldFileLock->key & 0xffffffff),
5157 (unsigned)(oldFileLock->flags));
5159 /* if the lock has already been granted, then we have nothing to do */
5160 if (IS_LOCK_ACTIVE(oldFileLock)) {
5161 lock_ReleaseRead(&cm_scacheLock);
5162 osi_Log0(afsd_logp, "cm_RetryLock lock already granted");
5166 /* we can't do anything with lost or deleted locks at the moment. */
5167 if (IS_LOCK_LOST(oldFileLock) || IS_LOCK_DELETED(oldFileLock)) {
5168 code = CM_ERROR_BADFD;
5169 osi_Log0(afsd_logp, "cm_RetryLock lock is lost or deleted");
5170 lock_ReleaseRead(&cm_scacheLock);
5174 scp = oldFileLock->scp;
5176 osi_assertx(scp != NULL, "null cm_scache_t");
5178 lock_ReleaseRead(&cm_scacheLock);
5179 lock_ObtainMutex(&scp->mx);
5181 code = cm_LockCheckPerms(scp, oldFileLock->lockType,
5185 if (code == CM_ERROR_NOACCESS && oldFileLock->lockType == LockRead) {
5186 if (!has_insert || !SCP_SUPPORTS_WRITELOCKACL(scp)) {
5187 force_client_lock = TRUE;
5191 lock_ReleaseMutex(&scp->mx);
5195 lock_ObtainWrite(&cm_scacheLock);
5197 /* Check if we already have a sufficient server lock to allow this
5198 lock to go through. */
5199 if (IS_LOCK_WAITLOCK(oldFileLock) &&
5200 (!SERVERLOCKS_ENABLED(scp) ||
5201 scp->serverLock == oldFileLock->lockType ||
5202 scp->serverLock == LockWrite)) {
5204 oldFileLock->flags &= ~CM_FILELOCK_FLAG_WAITLOCK;
5206 if (SERVERLOCKS_ENABLED(scp)) {
5207 osi_Log1(afsd_logp, "cm_RetryLock Server lock (%d) is sufficient for lock. Granting",
5208 (int) scp->serverLock);
5210 osi_Log0(afsd_logp, "cm_RetryLock skipping server lock for scp");
5213 lock_ReleaseWrite(&cm_scacheLock);
5214 lock_ReleaseMutex(&scp->mx);
5219 if (IS_LOCK_WAITUNLOCK(oldFileLock)) {
5221 /* check if the conflicting locks have dissappeared already */
5222 for (q = scp->fileLocksH; q; q = osi_QNext(q)) {
5224 fileLock = (cm_file_lock_t *)
5225 ((char *) q - offsetof(cm_file_lock_t, fileq));
5227 if (IS_LOCK_LOST(fileLock)) {
5228 if (fileLock->key == oldFileLock->key) {
5229 code = CM_ERROR_BADFD;
5230 oldFileLock->flags |= CM_FILELOCK_FLAG_LOST;
5231 osi_Log1(afsd_logp, " found lost lock %p for same key. Marking lock as lost",
5234 } else if (fileLock->lockType == LockWrite &&
5235 INTERSECT_RANGE(oldFileLock->range, fileLock->range)) {
5236 osi_Log1(afsd_logp, " found conflicting LOST lock %p", fileLock);
5237 code = CM_ERROR_WOULDBLOCK;
5242 if (IS_LOCK_ACCEPTED(fileLock) &&
5243 INTERSECT_RANGE(oldFileLock->range, fileLock->range)) {
5245 if (oldFileLock->lockType != LockRead ||
5246 fileLock->lockType != LockRead) {
5248 osi_Log1(afsd_logp, " found conflicting lock %p", fileLock);
5249 code = CM_ERROR_WOULDBLOCK;
5257 lock_ReleaseWrite(&cm_scacheLock);
5258 lock_ReleaseMutex(&scp->mx);
5263 /* when we get here, the lock is either a WAITUNLOCK or WAITLOCK.
5264 If it is WAITUNLOCK, then we didn't find any conflicting lock
5265 but we haven't verfied whether the serverLock is sufficient to
5266 assert it. If it is WAITLOCK, then the serverLock is
5267 insufficient to assert it. Eitherway, we are ready to accept
5268 the lock as either ACTIVE or WAITLOCK depending on the
5271 /* First, promote the WAITUNLOCK to a WAITLOCK */
5272 if (IS_LOCK_WAITUNLOCK(oldFileLock)) {
5273 if (oldFileLock->lockType == LockRead)
5276 scp->exclusiveLocks++;
5278 oldFileLock->flags &= ~CM_FILELOCK_FLAG_WAITUNLOCK;
5279 oldFileLock->flags |= CM_FILELOCK_FLAG_WAITLOCK;
5282 osi_assertx(IS_LOCK_WAITLOCK(oldFileLock), "!IS_LOCK_WAITLOCK");
5284 if (force_client_lock ||
5285 !SERVERLOCKS_ENABLED(scp) ||
5286 scp->serverLock == oldFileLock->lockType ||
5287 (oldFileLock->lockType == LockRead &&
5288 scp->serverLock == LockWrite)) {
5290 oldFileLock->flags &= ~CM_FILELOCK_FLAG_WAITLOCK;
5292 if ((force_client_lock ||
5293 !SERVERLOCKS_ENABLED(scp)) &&
5294 !IS_LOCK_CLIENTONLY(oldFileLock)) {
5296 oldFileLock->flags |= CM_FILELOCK_FLAG_CLIENTONLY;
5298 if (oldFileLock->lockType == LockRead)
5301 scp->exclusiveLocks--;
5306 lock_ReleaseWrite(&cm_scacheLock);
5307 lock_ReleaseMutex(&scp->mx);
5314 code = cm_SyncOp(scp, NULL, oldFileLock->userp, &req, 0,
5315 CM_SCACHESYNC_NEEDCALLBACK
5316 | CM_SCACHESYNC_GETSTATUS
5317 | CM_SCACHESYNC_LOCK);
5319 osi_Log1(smb_logp, "cm_RetryLock SyncOp failure code 0x%x", code);
5320 lock_ReleaseWrite(&cm_scacheLock);
5321 goto post_syncopdone;
5324 if (!IS_LOCK_WAITLOCK(oldFileLock))
5325 goto pre_syncopdone;
5327 userp = oldFileLock->userp;
5329 #ifndef AGGRESSIVE_LOCKS
5330 newLock = oldFileLock->lockType;
5332 newLock = LockWrite;
5336 /* if has_insert is non-zero, then:
5337 - the lock a LockRead
5338 - we don't have permission to get a LockRead
5339 - we do have permission to get a LockWrite
5340 - the server supports VICED_CAPABILITY_WRITELOCKACL
5343 newLock = LockWrite;
5346 lock_ReleaseWrite(&cm_scacheLock);
5348 /* when we get here, either we have a read-lock and want a
5349 write-lock or we don't have any locks and we want some
5352 if (scp->serverLock == LockRead) {
5354 osi_assertx(newLock == LockWrite, "!LockWrite");
5356 osi_Log0(afsd_logp, " Attempting to UPGRADE from LockRead to LockWrite");
5358 scp->lockDataVersion = scp->dataVersion;
5359 check_data_version = TRUE;
5361 code = cm_IntReleaseLock(scp, userp, &req);
5364 goto pre_syncopdone;
5366 scp->serverLock = -1;
5369 code = cm_IntSetLock(scp, userp, newLock, &req);
5372 if (scp->dataVersion != scp->lockDataVersion) {
5373 /* we lost a race. too bad */
5376 " Data version mismatch while upgrading lock.");
5378 " Data versions before=%I64d, after=%I64d",
5379 scp->lockDataVersion,
5382 " Releasing stale lock for scp 0x%x", scp);
5384 code = cm_IntReleaseLock(scp, userp, &req);
5386 scp->serverLock = -1;
5388 code = CM_ERROR_INVAL;
5390 cm_LockMarkSCacheLost(scp);
5392 scp->serverLock = newLock;
5397 cm_SyncOpDone(scp, NULL, CM_SCACHESYNC_LOCK);
5403 if (code != 0 && code != CM_ERROR_WOULDBLOCK) {
5404 lock_ObtainWrite(&cm_scacheLock);
5405 if (scp->fileLocksT == &oldFileLock->fileq)
5406 scp->fileLocksT = osi_QPrev(&oldFileLock->fileq);
5407 osi_QRemoveHT(&scp->fileLocksH, &scp->fileLocksT, &oldFileLock->fileq);
5408 lock_ReleaseWrite(&cm_scacheLock);
5410 lock_ReleaseMutex(&scp->mx);
5413 lock_ObtainWrite(&cm_scacheLock);
5415 oldFileLock->flags &= ~CM_FILELOCK_FLAG_WAITLOCK;
5416 } else if (code != CM_ERROR_WOULDBLOCK) {
5417 oldFileLock->flags |= CM_FILELOCK_FLAG_DELETED;
5418 cm_ReleaseUser(oldFileLock->userp);
5419 oldFileLock->userp = NULL;
5420 if (oldFileLock->scp) {
5421 cm_ReleaseSCacheNoLock(oldFileLock->scp);
5422 oldFileLock->scp = NULL;
5425 lock_ReleaseWrite(&cm_scacheLock);
5430 cm_key_t cm_GenerateKey(unsigned int session_id, unsigned long process_id, unsigned int file_id)
5433 osi_assertx((process_id & 0xffffffff) == process_id, "unexpected process_id");
5434 osi_assertx((session_id & 0xffff) == session_id, "unexpected session_id");
5435 osi_assertx((file_id & 0xffff) == file_id, "unexpected file_id");
5439 (((cm_key_t) (process_id & 0xffffffff)) << 32) |
5440 (((cm_key_t) (session_id & 0xffff)) << 16) |
5441 (((cm_key_t) (file_id & 0xffff)));
5444 static int cm_KeyEquals(cm_key_t k1, cm_key_t k2, int flags)
5446 if (flags & CM_UNLOCK_BY_FID) {
5447 return ((k1 & 0xffffffff) == (k2 & 0xffffffff));
5453 void cm_ReleaseAllLocks(void)
5459 cm_file_lock_t *fileLock;
5462 for (i = 0; i < cm_data.scacheHashTableSize; i++)
5464 for ( scp = cm_data.scacheHashTablep[i]; scp; scp = scp->nextp ) {
5465 while (scp->fileLocksH != NULL) {
5466 lock_ObtainMutex(&scp->mx);
5467 lock_ObtainWrite(&cm_scacheLock);
5468 if (!scp->fileLocksH) {
5469 lock_ReleaseWrite(&cm_scacheLock);
5470 lock_ReleaseMutex(&scp->mx);
5473 fileLock = (cm_file_lock_t *)((char *) scp->fileLocksH - offsetof(cm_file_lock_t, fileq));
5474 userp = fileLock->userp;
5476 key = fileLock->key;
5477 cm_HoldSCacheNoLock(scp);
5478 lock_ReleaseWrite(&cm_scacheLock);
5479 cm_UnlockByKey(scp, key, 0, userp, &req);
5480 cm_ReleaseSCache(scp);
5481 cm_ReleaseUser(userp);
5482 lock_ReleaseMutex(&scp->mx);